Use Wireshark to uncover the content of FTP client GG and FTP server mm and to briefly emulate the FTP client that implements Windows with C code

Source: Internet
Author: User
Tags ftp client file transfer protocol htons



In front, we played HTTP, quite a bit of meaning, in this article, we continue to play FTP (File Transfer Protocol). Both HTTP and FTP are application-layer protocols built on TCP, no matter how they are packaged, how they are loaded bigger, and ultimately TCP end-to-end transmission. This paper is divided into two parts: first. Use Wireshark to capture the content of FTP client GG and FTP server mm. Two. Use C code to briefly simulate the FTP client that implements Windows.






Description, the experiment in this article, I used two computers, namely PC1 (192.168.1.100) and PC2 (192.168.1.102).  Among them, PC1 do the client (FTP client GG), PC2 do the service side (FTP server MM). OK, turn on the power button for both computers to play FTP.






I. Using Wireshark to uncover the content of FTP client GG and FTP server mm



1. On PC2, open FTP server MM, set user name to 1, password is 1. We execute Netstat-nao in cmd | findstr 21 can be seen, the PC turned on 21-port monitoring. Create A.txt and B.txt two files in the directory corresponding to the FTP server mm. (For FTP server mm, please refer to my previous blog:http://blog.csdn.net/stpeace/article/details/38026285)



2. On PC1, Wireshark grab the packet and open cmd, then execute the following command in order to get the result:



C:\Documents and settings\administrator>ftp 192.168.1.102
Connected to 192.168.1.102.
220 Welcome to visit Slyar ftpserver!
User (192.168.1.102: (None)): 1
331 Specify the password.
Password:
Successful Login.
Ftp>
Ftp>
ftp> dir
Port command successful.
Opening ASCII mode data connection for directory list.
-RWX------1 User group 0 APR 23:04 a.txt
-RWX------1 User group 0 APR 23:04 B.txt
226 Transfer Complete
ftp: Received 118 bytes, spents 0.01Seconds 7.87kbytes/sec.
Ftp>






We first execute the FTP 192.168.1.102, at which time the FTP client GG establishes a TCP connection with the FTP server mm and then enters the username and password for authentication. After the certification passed, finally with the dir command to query the FTP server mm what is there, the results saw A.txt and B.txt files



3. We will capture the package file (PORT.CAP) and analyze it as follows:






4. The first 1.2 package is very simple, live pc1 ARP broadcast, mainly to find 192.168.1.102 this computer (PC2) of the Mac, the 3rd package indicates the successful acquisition of PC2 MAC address, with a Mac to communicate ah.



5. In fact, the above ARP operation is triggered by the FTP 192.168.1.102, in fact, the more important use of FTP 192.168.1.102 is to establish a TCP connection channel with FTP server mm. 4th, 5, 6 packs is the legendary three-time handshake agreement, too important too basic, so not much to say.



6. 7-14th Package main user FTP client GG and FTP server mm between the user name and password authentication, about sister, to obtain the sister's verification and any, it is taken for granted.



7. When we execute the dir command, all subsequent packages are triggered. The 15th package is the FTP client GG sends the Port 192,168,1,100,7,220 command to the FTP server mm and says to the FTP server mm: You will be active with me later, to establish a TCP channel for data transmission (the second TCP channel), I Listen to the address is 192.168.1.100 on the (7*256+220) port, and do not hesitate to imply: You this FTP server mm to take the initiative to contact me, I just in the IP and port at the moment you, not see. At this time, the FTP server GG end listens (7*256+220) This port, waits for the FTP server mm to be actively hooked. The 16th package is the response of the FTP server mm, meaning: OK, I will go to that location that port to find you.



8. The 17th package is the DIR request sent by FTP client GG, which means asking for FTP server MM: How much do you have?



9. The 18th packet is the FTP server mm response, as if to say: I already know what you are asking questions, I will be in a moment before we agreed to tell you (a second temporary TCP channel).



10. Ok, so far, FTP client GG and FTP server mm first-round hooking up temporarily. Note, is temporarily over, not terminate, you see, there is no Wave Byebye receipt package AH.



11. OK, FTP client GG and FTP server mm second-round hooking formally started, but this time, the FTP server mm began to stir, take the initiative to the place to take the bait, please see 第19-21个 bag, this is the second round of three handshake agreement.



12. Let's just stare at the 22nd package, this time, FTP server mm to the newly established TCP channel (the second temporary TCP channel) to transmit data, do not forget, FTP client GG in the first round of hooking up asked the FTP server mm home How much property, this Times, FTP server mm to be honest, the property will certainly involve privacy ah, so with the new TCP channel to repay. Expand the 22nd package, we see the FTP server mm finally no longer reserved, put their own property, the contents of the communication:



-RWX------1 User group 0 APR 23:04 a.txt
-RWX------1 User group 0 APR 23:04 B.txt



13. We see, in fact, the FTP serve mm home also does not have much property, only the pitiful a.txt and b.txt two empty documents.



14. The next 23-29 packets are just some of the process of hanging the phone (close the second temporary TCP channel), said Byebye, you can clearly see the process of disconnecting the socket. It is worth noting that the 28th package, FTP server mm very intimate said: I have said, the property is so much, then you open to do it.



15. Note that, to this end, FTP client GG and FTP server mm have been disconnected on the second TCP channel, but remain in contact on the first TCP channel. Subsequent if the FTP client continues to execute other request commands, such as probing measurements, he will re-open the new random port for listening, and then tell FTP server mm again this random port, let FTP server mm to initiate a third temporary TCP connection. Similarly, FTP server mm will be on the third TCP channel measurements data is told to FTP client GG, then the third temporary TCP channel will be removed. The constant is that the first TCP channel is still tightly connected there.



Summary: The above is the FTP active mode. The first "permanent" TCP channel is mainly used to pass the request command, is the FTP client GG Active to seduce FTP server MM, followed by the second/three/four ... A temporary TCP channel is used primarily for data transmission, and is an active hook for FTP server mm. The so-called FTP active mode, refers to the FTP server mm active.






two. Use C code to briefly simulate the FTP client that implements Windows.



To this end, the TCP active mode should have a relatively transparent understanding, and now we try to use C code to briefly simulate the above process, simulation of the FTP client GG code is as follows:





// I spent a long time debugging, if you want to reprint, please indicate the blog address, respect the copyright
// Blog address: http://blog.csdn.net/stpeace/article/details/45100687

#include <stdio.h>
#include <string.h>
#include <winsock2.h> // winsock interface
#pragma comment (lib, "ws2_32.lib") // winsock implementation library

// buffer length
#define LEN (1024 + 1)

SOCKET g_ctrlSocket = 0; // The socket that the ftp client is responsible for communicating on the "command control tcp channel"

SOCKET g_listenSocket = 0; // socket that the ftp client is responsible for listening to
SOCKET g_dataSocket = 0; // socket that the ftp client is responsible for communicating on the "data transmission tcp channel"


// Create a "command control tcp channel" communication socket
int createCtrlSocket ()
{
g_ctrlSocket = socket (AF_INET, SOCK_STREAM, 0);
return 0;
}


// Get the information returned by the ftp server on the "command control tcp channel"
int getCmdResFromFtpServer ()
{
char szRecvBuf [LEN] = {0};
int nRet = recv (g_ctrlSocket, szRecvBuf, sizeof (szRecvBuf)-1, 0);
if (nRet <0)
{
printf ("recv error \ n");
return -1;
}

if (0 == nRet)
{
printf ("connection has been closed by ftp server");
return -1;
}

printf ("% s", szRecvBuf);
Ranch
return 0;
}


// Establish "command control tcp channel"
int connectFtpServer (const char * pIP, unsigned short port)
{
struct sockaddr_in ftpServerAddr;
ftpServerAddr.sin_family = AF_INET;
ftpServerAddr.sin_addr.S_un.S_addr = inet_addr (pIP);
ftpServerAddr.sin_port = htons (port);

int nRet = connect (g_ctrlSocket, (struct sockaddr *) & ftpServerAddr, sizeof (ftpServerAddr));
if (nRet <0)
{
printf ("connect error \ n");
return -1;
}

getCmdResFromFtpServer ();

return 0;
}


// Initiate related command requests from the "command control tcp channel" to the ftp server
int requestFtpServer (const char * pPassWord)
{
char szSendBuf [LEN] = {0};
sprintf (szSendBuf, "% s \ r \ n", pPassWord);
Ranch
send (g_ctrlSocket, szSendBuf, strlen (szSendBuf) + 1, 0);
getCmdResFromFtpServer ();

return 0;
}


// Start the ftp client listening thread and prepare to accept the ftp server request to establish a "data transmission tcp channel"
DWORD WINAPI createDataSocketThread (LPVOID p)
{
unsigned int a = 0;
unsigned int b = 0;
sscanf ((const char *) p, "% d:% d", & a, & b);

SOCKET g_listenSocket = socket (AF_INET, SOCK_STREAM, 0);

    SOCKADDR_IN addrSrv;
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_addr.S_un.S_addr = inet_addr ("192.168.1.100");
    addrSrv.sin_port = htons (a * 256 + b);


    bind (g_listenSocket, (SOCKADDR *) & addrSrv, sizeof (SOCKADDR));
    listen (g_listenSocket, 5);
 
    SOCKADDR_IN addrClient;
    int len = sizeof (SOCKADDR);

    // Wait for the ftp server to actively request the establishment of a "data transmission tcp channel"
    g_dataSocket = accept (g_listenSocket, (SOCKADDR *) & addrClient, & len);

return 0;
}


// Get data information of ftp server from "data transmission tcp channel"
int getDateFromFtpServer ()
{
char szRecvBuf [1000] = {0};
int nRet = recv (g_dataSocket, szRecvBuf, 1000-1, 0);
if (nRet <0)
{
printf ("recv error \ n");
return -1;
}

if (0 == nRet)
{
printf ("closed by ftp server \ n");
return -1;
}
Ranch
printf ("% s", szRecvBuf);

return 0;
}


int main ()
{
// network initialization
WSADATA wsaData;
WSAStartup (MAKEWORD (1,1), & wsaData);

// Create a communication socket on the "command control tcp channel"
createCtrlSocket ();

// Establish "command control tcp channel"
connectFtpServer ("192.168.1.102", 21);

// Send username and password from "command control tcp channel" to ftp server for authentication
requestFtpServer ("user 1");
requestFtpServer ("pass 1");

// Establish "data transmission tcp channel"
HANDLE handle = CreateThread (NULL, 0, createDataSocketThread, "12:34", 0, NULL);

// The main thread is blocked for 1s, make sure the createDataSocketThread thread is listening
Sleep (1000);

// From the "command control tcp channel", pass the IP and port to be monitored by the FTP client to the FTP server
requestFtpServer ("PORT 192,168,1,100,12,34");

// Pass the LIST message request from the "command control tcp channel"
requestFtpServer ("LIST");

// Wait for 1s (quite necessary), wait for the connection of the ftp server, otherwise, if the "data transmission tcp channel" is not created, what is the communication?
Sleep (1000);

// Receive data from "data transmission tcp channel"
getDateFromFtpServer ();

// Close the temporary "data transmission tcp channel". Note: "Command control tcp channel" cannot be closed
closesocket (g_dataSocket);
closesocket (g_listenSocket);



// repeat the above request
handle = CreateThread (NULL, 0, createDataSocketThread, "12:40", 0, NULL);
Sleep (1000);
requestFtpServer ("PORT 192,168,1,100,12,40");
requestFtpServer ("LIST");
Sleep (1000);
getDateFromFtpServer ();
closesocket (g_dataSocket);
closesocket (g_listenSocket);



while (1); // blocking



CloseHandle (handle);
closesocket (g_ctrlSocket);
WSACleanup ();
Ranch
return 0;
} 




The result of the FTP client side is:





220 Welcome to visit Slyar ftpserver!
331 Specify the password.
Successful Login.
Port command successful.
Opening ASCII mode data connection for directory list.
-RWX------1 User group 0 APR 23:04 a.txt
-RWX------1 User group 0 APR 23:04 B.txt
226 Transfer Complete
Port command successful.
-RWX------1 User group 0 APR 23:04 a.txt
-RWX------1 User group 0 APR 23:04 B.txt






I had some pains in debugging the above procedure, there are a few points worth noting:



1. Make sure that FTP server mm is turned on before running my program.



2. Make sure that the FTP server mm port 21 is not blocked by a firewall and can be tested with Telnet 192.168.1.102 21 on PC1.



3. Ensure that the FTP client GG random port is not blocked by the firewall, I am debugging, fell here, the results of FTP server mm is always unable to establish a second TCP channel with FTP client GG. The typical symptom is that on PC2, the execution of Telnet 192.168.1.100 xxx does not succeed, where xxx is the port that the FTP client GG listens to. Later, I put the PC1 on the firewall to let go.



4. It is a good way to use threading to create sockets in the program, making sure that FTP client GG starts the accept first.



5. The two sleep in the program is more critical, there are already comments in the program, so I will not repeat it.



6. A lot of information that in the subsequent "Data Transmission TCP channel", the FTP server mm port is 20, that is, to connect, her own socket bound to the 20 port, just, we have previously talked about the application of BIND in blog post. However, in the actual capture I found that the FTP server mm is not stuck on the 20 port, of course, this is not a mistake, mainly due to the specific implementation of the difference. And, I think it's better not to bind Port 20th.









Ok. So far, we have a more in-depth understanding of the active mode of FTP. What is the passive mode of FTP? Very simple: The first TCP channel is created by the FTP client GG request, all subsequent temporary TCP channels are also created by the FTP client GG request, that is, the FTP server mm is very passive, very passive.



I have also personally verified that the FTP client that comes with Windows does not actually support the so-called passive mode. The quote PASV or literal PASV on the internet does not actually have the function of PASV request. Of course, in this matter, the more detailed elaboration is: http://blogs.isaserver.org/pouseele/2006/11/09/about-the-microsoft-command-line-ftp-client/, If you are interested, you can take a peek.



In view of the FTP passive mode and the above-mentioned active mode is similar, I will not repeat the FTP passive mode, interested in children's shoes can be their own in-depth study, find a support Passive mode FTP client, catch the bag to see.









Well, the introduction of FTP ends here.















Use Wireshark to uncover the content of FTP client GG and FTP server mm and to briefly emulate the FTP client that implements Windows with C code


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.