FTP hacking

About FTP

In an FTP connection, two channels are opened. First, the client and server establish a control channel through TCP port 21. The client sends commands to the server, and the server returns status codes. Then both communication participants can establish the data channel via TCP port 20. This channel is used exclusively for data transmission, and the protocol watches for errors during this process.

A distinction is made between active and passive FTP. In the active variant, the client establishes the connection as described via TCP port 21 and thus informs the server via which client-side port the server can transmit its responses. However, if a firewall protects the client, the server cannot reply because all external connections are blocked. For this purpose, the passive mode has been developed. Here, the server announces a port through which the client can establish the data channel. Since the client initiates the connection in this method, the firewall does not block the transfer.

FTP is a clear-text protocol that can sometimes be sniffed if conditions on the network are right.

FTP server return codes always have three digits, and each digit has a special meaning. The first digit denotes whether the response is good, bad or incomplete:

RangePurpose
1xxPositive Preliminary replyThe requested action is being initiated; expect another reply before proceeding with a new command. (The user-process sending another command before the completion reply would be in violation of protocol; but server-FTP processes should queue any commands that arrive while a preceding command is in progress.) This type of reply can be used to indicate that the command was accepted and the user-process may now pay attention to the data connections, for implementations where simultaneous monitoring is difficult. The server-FTP process may send at most, one 1xx reply per command.
2xxPositive Completion replyThe requested action has been successfully completed. A new request may be initiated.
3xxPositive Intermediate replyThe command has been accepted, but the requested action is being held in abeyance, pending receipt of further information. The user should send another command specifying this information. This reply is used in command sequence groups.
4xxTransient Negative Completion replyThe command was not accepted and the requested action did not take place, but the error condition is temporary and the action may be requested again. The user should return to the beginning of the command sequence, if any. It is difficult to assign a meaning to “transient”, particularly when two distinct sites (Server- and User-processes) have to agree on the interpretation. Each reply in the 4xx category might have a slightly different time value, but the intent is that the user-process is encouraged to try again. A rule of thumb in determining if a reply fits into the 4xx or the 5xx (Permanent Negative) category is that replies are 4xx if the commands can be repeated without any change in command form or in properties of the User or Server (e.g., the command is spelled the same with the same arguments used; the user does not change his file access or user name; the server does not put up a new implementation.)
5xxPermanent Negative Completion replyThe command was not accepted and the requested action did not take place. The User-process is discouraged from repeating the exact request (in the same sequence). Even some “permanent” error conditions can be corrected, so the human user may want to direct his User-process to reinitiate the command sequence by direct action at some point in the future (e.g., after the spelling has been changed, or the user has altered his directory status.)
6xxProtected replyRFC 2228 introduced the concept of protected replies to increase security over FTP communications. The 6xx replies are Base64 encoded protected messages that serves as responses to secure commands. When properly decoded, these replies fall into the above categories.

The second digit is a grouping digit and encodes the following information:

RangePurpose
x0xSyntaxThese replies refer to syntax errors, syntactically correct commands that don’t fit any functional category, unimplemented or superfluous commands.
x1xInformationThese are replies to requests for information, such as status or help.
x2xConnectionsReplies referring to the control and data connections.
x3xAuthentication and accountingReplies for the login process and accounting procedures.
x4xUnspecified as of RFC 959.
x5xFile systemThese replies indicate the status of the Server file system vis-a-vis the requested transfer or other file system action.

Below is a list of all known return codes that may be issued by an FTP server.

CodeExplanation
100 SeriesThe requested action is being initiated, expect another reply before proceeding with a new command.
110Restart marker replay . In this case, the text is exact and not left to the particular implementation; it must read: MARK yyyy = mmmm where yyyy is User-process data stream marker, and mmmm server’s equivalent marker (note the spaces between markers and “=”).
120Service ready in nnn minutes.
125Data connection already open; transfer starting.
150File status okay; about to open data connection.
200 SeriesThe requested action has been successfully completed.
202Command not implemented, superfluous at this site.
211System status, or system help reply.
212Directory status.
213File status.
214Help message. Explains how to use the server or the meaning of a particular non-standard command. This reply is useful only to the human user.
215NAME system type. Where NAME is an official system name from the registry kept by IANA.
220Service ready for new user.
221Service closing control connection. Logged out if appropriate.
225Data connection open; no transfer in progress.
226Closing data connection. Requested file action successful (for example, file transfer or file abort).
227Entering Passive Mode (h1,h2,h3,h4,p1,p2).
228Entering Long Passive Mode (long address, port).
229Entering Extended Passive Mode (|||port|).
230User logged in, proceed.
232User logged in, authorized by security data exchange.
234Server accepts the security mechanism specified by the client; no security data needs to be exchanged.
235Server accepts the security data given by the client; no further security data needs to be exchanged.
250Requested file action was okay, completed.
300 SeriesThe command is not acceptable, but the requested action is on hold, pending receipt of further information.
331User name okay, password needed.
332No need account for login.
334Server accepts the security mechanism specified by the client; some security data needs to be exchanged.
336Username okay, password okay. Challenge is “.…”.
421Service available, closing control connection. This may be a reply to any command if the service knows it must shut down.
425Can’t open data connection.
426Connection closed; transfer aborted.
430Invalid username or password
431Need some unavailable resource to process security.
434Requested host unavailable.
450Requested file action not taken.
451Requested action aborted. Local error in processing.
452Requested action not taken. Insufficient storage space in system. File unavailable (e.g., file busy).
500 SeriesSyntax error, command unrecognized and the requested action did not take place. This may include errors such as command line too long.
501Syntax error in parameters or arguments.
502Command not implemented.
503Bad sequence of commands.
504Command not implemented for that parameter.
530Not logged in.
532Need account for storing files.
533Command protection level denied for policy reasons.
534Request denied for policy reasons.
535Failed security check.
536Data protection level not supported by security mechanism.
537Command protection level not supported by security mechanism.
550Requested action not taken. File unavailable (e.g., file not found, no access).
551Requested action aborted. Page type unknown.
552Requested file action aborted. Exceeded storage allocation (for current directory or dataset).
553Requested action not taken. File name not allowed.
600 SeriesReplies regarding confidentiality and integrity
631Integrity protected reply.
632Confidentiality and integrity protected reply.
633Confidentiality protected reply.

TFTP

Trivial File Transfer Protocol (TFTP) is simpler than FTP and performs file transfers between client and server processes. However, it does not provide user authentication and other valuable features supported by FTP. In addition, while FTP uses TCP, TFTP uses UDP, making it an unreliable protocol and causing it to use UDP-assisted application layer recovery.

CommandsDescription
connectSets the remote host, and optionally the port, for file transfers.
getTransfers a file or set of files from the remote host to the local host.
putTransfers a file or set of files from the local host onto the remote host.
quitExits tftp.
statusShows the current status of tftp, including the current transfer mode (ascii or binary), connection status, time-out value, and so on.
verboseTurns verbose mode, which displays additional information during file transfer, on or off.

Unlike the FTP client, TFTP does not have directory listing functionality.

Anonymous FTP

First thing to do is check to see if anonymous access is allowed. Some servers let you enter “user anonymous” and prompt for email address as the password.

ftp 10.129.14.136

Connected to 10.129.14.136.
220 "Welcome to the HTB Academy vsFTP service."
Name (10.129.14.136:cry0l1t3): anonymous

230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.


ftp> ls

200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
-rw-rw-r--    1 1002     1002      8138592 Sep 14 16:54 Calender.pptx
drwxrwxr-x    2 1002     1002         4096 Sep 14 16:50 Clients
drwxrwxr-x    2 1002     1002         4096 Sep 14 16:50 Documents
drwxrwxr-x    2 1002     1002         4096 Sep 14 16:50 Employees
-rw-rw-r--    1 1002     1002           41 Sep 14 16:45 Important Notes.txt
226 Directory send OK.

You can also try status to see if more information can be gleaned. You can also try the debug and trace commands.

ftp> status

Connected to 10.129.14.136.
No proxy connection.
Connecting using address family: any.
Mode: stream; Type: binary; Form: non-print; Structure: file
Verbose: on; Bell: off; Prompting: on; Globbing: on
Store unique: off; Receive unique: off
Case: off; CR stripping: on
Quote control characters: on
Ntrans: off
Nmap: off
Hash mark printing: off; Use of PORT cmds: on
Tick counter printing: off

In the following example, we can see that if the hide_ids=YES setting is present, the UID and GUID representation of the service will be overwritten, making it more difficult for us to identify with which rights these files are written and uploaded.

ftp> ls

---> TYPE A
200 Switching to ASCII mode.
ftp: setsockopt (ignored): Permission denied
---> PORT 10,10,14,4,223,101
200 PORT command successful. Consider using PASV.
---> LIST
150 Here comes the directory listing.
-rw-rw-r--    1 ftp     ftp      8138592 Sep 14 16:54 Calender.pptx
drwxrwxr-x    2 ftp     ftp         4096 Sep 14 17:03 Clients
drwxrwxr-x    2 ftp     ftp         4096 Sep 14 16:50 Documents
drwxrwxr-x    2 ftp     ftp         4096 Sep 14 16:50 Employees
-rw-rw-r--    1 ftp     ftp           41 Sep 14 16:45 Important Notes.txt
-rw-------    1 ftp     ftp            0 Sep 15 14:57 testupload.txt
226 Directory send OK.

If the ls_recurse_enable=YES option is set, you can get a recursive directory listing.

ftp> ls -R

---> PORT 10,10,14,4,222,149
200 PORT command successful. Consider using PASV.
---> LIST -R
150 Here comes the directory listing.
.:
-rw-rw-r--    1 ftp      ftp      8138592 Sep 14 16:54 Calender.pptx
drwxrwxr-x    2 ftp      ftp         4096 Sep 14 17:03 Clients
drwxrwxr-x    2 ftp      ftp         4096 Sep 14 16:50 Documents
drwxrwxr-x    2 ftp      ftp         4096 Sep 14 16:50 Employees
-rw-rw-r--    1 ftp      ftp           41 Sep 14 16:45 Important Notes.txt
-rw-------    1 ftp      ftp            0 Sep 15 14:57 testupload.txt

./Clients:
drwx------    2 ftp      ftp          4096 Sep 16 18:04 HackTheBox
drwxrwxrwx    2 ftp      ftp          4096 Sep 16 18:00 Inlanefreight

./Clients/HackTheBox:
-rw-r--r--    1 ftp      ftp         34872 Sep 16 18:04 appointments.xlsx
-rw-r--r--    1 ftp      ftp        498123 Sep 16 18:04 contract.docx
-rw-r--r--    1 ftp      ftp        478237 Sep 16 18:04 contract.pdf
-rw-r--r--    1 ftp      ftp           348 Sep 16 18:04 meetings.txt

./Clients/Inlanefreight:
-rw-r--r--    1 ftp      ftp         14211 Sep 16 18:00 appointments.xlsx
-rw-r--r--    1 ftp      ftp         37882 Sep 16 17:58 contract.docx
-rw-r--r--    1 ftp      ftp            89 Sep 16 17:58 meetings.txt
-rw-r--r--    1 ftp      ftp        483293 Sep 16 17:59 proposal.pptx

./Documents:
-rw-r--r--    1 ftp      ftp         23211 Sep 16 18:05 appointments-template.xlsx
-rw-r--r--    1 ftp      ftp         32521 Sep 16 18:05 contract-template.docx
-rw-r--r--    1 ftp      ftp        453312 Sep 16 18:05 contract-template.pdf

./Employees:
226 Directory send OK.

Oddly, all files can be downloaded at once like this:

wget -m --no-passive ftp://anonymous:anonymous@10.129.14.136

--2021-09-19 14:45:58--  ftp://anonymous:*password*@10.129.14.136/                                         
           => ‘10.129.14.136/.listing’                                                                     
Connecting to 10.129.14.136:21... connected.                                                               
Logging in as anonymous ... Logged in!
==> SYST ... done.    ==> PWD ... done.
==> TYPE I ... done.  ==> CWD not needed.
==> PORT ... done.    ==> LIST ... done.                                                                 
12.12.1.136/.listing           [ <=>                                  ]     466  --.-KB/s    in 0s       
                                                                                                         
2021-09-19 14:45:58 (65,8 MB/s) - ‘10.129.14.136/.listing’ saved [466]                                     
--2021-09-19 14:45:58--  ftp://anonymous:*password*@10.129.14.136/Calendar.pptx   
           => ‘10.129.14.136/Calendar.pptx’                                       
==> CWD not required.                                                           
==> SIZE Calendar.pptx ... done.                                                                                                                            
==> PORT ... done.    ==> RETR Calendar.pptx ... done.       

...SNIP...

2021-09-19 14:45:58 (48,3 MB/s) - ‘10.129.14.136/Employees/.listing’ saved [119]

FINISHED --2021-09-19 14:45:58--
Total wall clock time: 0,03s
Downloaded: 15 files, 1,7K in 0,001s (3,02 MB/s)

The ability to upload files to the FTP server connected to a web server increases the likelihood of gaining direct access to the webserver and even a reverse shell that allows us to execute internal system commands and perhaps even escalate our privileges.

nmap

nmap ftp scripts

You can get all nmap ftp scripts like this:

find / -type f -name ftp* 2>/dev/null | grep scripts

Scanning the FTP port

sudo nmap -sV -p21 -sC -A 10.129.14.136

--script-trace can be used to see all connections nmap makes to the server and the server’s response.

netcat

nc -nv 10.129.14.136 21

openssl

openssl can be used if the FTP server runs with TLS/SSL encryption.

openssl s_client -connect 10.129.14.136:21 -starttls ftp