-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathftpy
executable file
·356 lines (241 loc) · 8.55 KB
/
ftpy
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
#!/usr/bin/env python3
################################################################################
# #
# Copyright (C) 2023 Brunk (Anas) #
# #
# FTPy v1.2 - Simple Python3 FTP CLient #
# #
# #
# #
# GNU GENERAL PUBLIC LICENSE #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# 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. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from termcolor import colored
from time import strftime
from socket import socket
from sys import argv
from pwn import log
import re
def helpmsg() -> None:
"""
The local HELP function of this FTP Client
"""
log.info("Usage: ftpy <ip> <port (default 21)>")
log.success("Example: ftpy 192.168.1.10")
def parsearg(argv: list) -> None:
"""
This function is designed to parse argument provided
from Command Line, and to call the main function
"""
if len(argv) == 1:
log.critical("Missing parameter : <ip>")
return
elif len(argv) == 2:
if argv[1] in ['help', '--help', '-h', 'h']:
helpmsg()
return
# If there is only the IP and the user don't ask for HELP
# Then you should use the default FTP port
port = 21
elif len(argv) == 3:
# There is probably IP and Port passed through CLI
port = argv[2]
# Sanity check
if re.match("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", str(argv[1])) is None:
log.critical("Invalid IP !")
return
elif re.match("^[1-9][0-9]*$", str(port)) is None:
log.warning(f"Invalid port {port}, using default one")
port = 21
main(argv[1], port)
def login(s, ip: str) -> bool:
"""
Login to the FTP server using Socket
s: The socket
ip: The ip of the FTP server
"""
log.success(f"Connected to {ip}")
print(s.recv(20).strip().decode("UTF-8") + "\n")
try:
user = input("Username: ")
except:
return False
s.send(f"USER {user}\r\n".encode())
s.recv(32).strip().decode("UTF-8")
# TODO : Maybe use questionary.password to hide it ?
try:
passw = input("Password: ")
except:
return False
s.send(f"PASS {passw}\r\n".encode())
s.recv(4)
if "230" in s.recv(21).strip().decode("UTF-8"):
s.recv(4)
return True
else:
return False
def enter_pasv_mode(s):
s.send(b"PASV\r\n")
raw = s.recv(100).strip().decode("UTF-8")
ip = '.'.join(raw.strip().split("(")[1].split(",")[:4])
initial = raw.strip().split(",")[-2:]
port = (int(initial[0]) * 256) + int(initial[1].replace(").", ""))
pasv = socket()
pasv.connect((ip, port))
return pasv
def quit(s):
s.send(b"quit\r\n")
log.success("Goodbye !")
s.close()
# ---------- Implementation of basic FTP commands
def ls(s, cmd: str):
if len(cmd.split()) != 1:
toadd = cmd.split()[1]
else:
toadd = ""
pasv = enter_pasv_mode(s)
s.send(f"LIST {toadd}\r\n".encode())
# Get the output of the LIST command
resp = pasv.recv(4096)
print(resp.replace(b'\r\n', b'\n').decode())
pasv.close()
s.recv(1024)
s.recv(1024)
def cd(s, cmd: str):
if not len(cmd.split()) == 1:
s.send(f"CWD {cmd.split()[1]}\r\n".encode())
s.recv(1024)
else:
log.failure("Missing argument")
def mkdir(s, cmd: str):
if not len(cmd.split()) == 1:
s.send(f"MKD {cmd.split()[1]}\r\n".encode())
if not b"257" in s.recv(1024):
log.failure("An error has occured")
else:
log.failure("Missing argument")
def rm(s, cmd: str):
if not len(cmd.split()) == 1:
s.send(f"DELE {cmd.split()[1]}\r\n".encode())
a = s.recv(102)
if not b"250" in a:
log.failure("An error has occured")
else:
log.failure("Missing argument")
def chmod(s, cmd: str):
if len(cmd.split()) == 3:
cmd = cmd.split()[1:]
try:
int(cmd[0])
s.send(f"SITE CHMOD {cmd[0]} {cmd[1]}\r\n".encode())
except:
s.send(f"SITE CHMOD {cmd[1]} {cmd[0]}\r\n".encode())
if not b"200" in s.recv(1024):
log.failure("An error has occured")
else:
log.failure("Missing argument")
def get(s, cmd: str):
if len(cmd.split()) != 1:
toadd = cmd.split()[1]
pasv = enter_pasv_mode(s)
s.send(f"RETR {toadd}\r\n".encode())
resp = pasv.recv(4096)
pasv.close()
with open(toadd, 'wb') as f:
f.write(resp)
log.info("Done")
s.recv(1024)
else:
log.failure("An error occured")
def put(s, cmd: str):
# TODO
# Implement the possibility to put entire directory
# (mkdir() & put() )
if len(cmd.split()) != 1:
toadd = cmd.split()[1]
pasv = enter_pasv_mode(s)
try:
with open(toadd, 'rb') as f:
f = f.read()
except PermissionError:
log.failure("Permission denied !")
return
except FileNotFoundError:
log.failure("File does not exists !")
return
s.send(f"STOR {toadd}\r\n".encode())
resp = pasv.send(f+"\r\n".encode())
pasv.close()
s.recv(1024)
s.recv(1024)
log.info("Done")
else:
log.failure("Missing argument")
def interact(s) -> None:
"""
Get input from user, check if it's a valid FTP command,
and execute the function created for this effect.
"""
while True:
try:
cmd = input("ftp > ")
except:
cmd = "quit"
if "quit" in cmd:
quit(s)
return
elif "ls" in cmd:
ls(s, cmd)
elif "pwd" in cmd:
s.send(b"PWD\r\n")
print(s.recv(1024).decode().split('"')[1])
elif "cd" in cmd:
cd(s, cmd)
elif "mkdir" in cmd:
mkdir(s, cmd)
elif "rm" in cmd:
rm(s, cmd)
elif "chmod" in cmd:
chmod(s, cmd)
elif "get" in cmd:
get(s, cmd)
elif "put" in cmd:
put(s, cmd)
else:
log.failure("Invalid command")
def main(ip: str, port: int):
"""
Main function
"""
s = socket()
try:
s.connect((ip, int(port)))
except ConnectionRefusedError:
log.critical("Connection refused !")
return
except OSError:
log.critical("Cannot reach host !")
return
if login(s, ip):
interact(s)
else:
log.critical("Connection failed !")
return
if __name__ == "__main__":
#TODO : Maybe use a OOP with a class FTPClient ? idk
log.info("Launching FTPy at " + strftime("%H:%M:%S"))
parsearg(argv)
# EOL