Anda di halaman 1dari 74

ABSTRACT :

FTP is a traditional Internet application for receiving files from the

Internet or sending files from a computer to another computer. A general

purpose protocol, FTP handles three relatively independent aspects – Access

Control, File Name and File Transfer. FTP offers many facilities beyond the

transfer function itself, which includes interactive access, format representation

specification and security.

File transfer is among the most frequently used TCP/IP applications,

and it accounts for much network traffic. Originally defined as part of the

ARPANET protocols, FTP predates both TCP & IP. These early versions of file

transfer software evolved into a current standard known as the FTP. We have

to do this Transfer in secured way for this we use network intrusion detection

system(nids).

The SECURED FILE TRANSFER PROTOCOL is done in C on LINUX

operating system. The application has two main subdivisions, the client and the

server. The server side program of the application mainly deals with basis

connectivity for the client to the server. The client mainly consists of the user

interface through which the user interacts with the server.

B.Tech ( cse ) - secured file transfer protocol - 2004 1


CONTENTS
Page no
1. INTRODUCTION 1
2. ANALYSIS PHASE
2.1 Networking 3
2.2 Sockets 5
2.3 Ftp 8
2.4 Intrusion detector 12
2.5 About linux 15
2.6 C language 23
2.7 System requirements 26
3. DESIGN PHASE
3.1 Socket programming 28
3.2 Ftp commands 33
3.3 Intrusion detection 40
4. IMPLEMENTATION
4.1 Socket system calls 43
4.2 Connection establishment 46
4.3 Commands implementation 51
4.4 Pcap 54
4.5 Testing 61
5. RESULTS 65
6.CONCLUSION
6.1 Limitations 68
6.2 Future enhancements 69
7.REFERENCES
8.APPENDIX

B.Tech ( cse ) - secured file transfer protocol - 2004 2


1. INTRODUCTION

Now days, many software companies, educational institutions , universities,

private sector companies marinating there own local area networks in which may

computers are connected to one and other through some specified topology. These

topologies include ring, bus, star etc. Most of these LANS use client-server

architecture for there communication . In this architecture one system acts as a

server, where all other acts as clients. Clients are those who generate requests and

server is the one that serves the requests.

Generally the requests are of the following types. Requesting a file from

server, updating a file present in server, removing particular file in server. The server

contains some important file, which are needed by many clients.depending upon the

requests send by the clients the server serves the clients, by sending files which are

requested by clients, or by updating files in server with the data sent by clients , or by

removing a file in the server.but during this tranfer there may be threat of virus so we

should provide protection to this transfer by using some mechanisim.

But by using this client/server architectur we could not provide this

protection.so we need som programming technique to provide this.By keeping all this

in view we selected our project and tried to provide protection mechanisims to this

transfer.

B.Tech ( cse ) - secured file transfer protocol - 2004 3


ANALYSIS PHASE

B.Tech ( cse ) - secured file transfer protocol - 2004 4


2.1 NETWORKING
The merging of computers and communication had profound influence on
the way computer systems are organized.The old model of a single computer serving
all of the organizations computations needs has been replace by one in which a large
number of separate but interconnected computers do the job.These systems are
called computer networks.
Computer networks is collection of autonomus computers.Two computers
are said to be interconnected if they are able to exchange information.

2.1.1 CLIENT-SERVER ARCHITECTURE:


The standard model for network application is the client-server model.A server
is a process that is waiting to be contacted by a client process so that the server can
do something for the client.A typical(but not mandatory)scenario is as follows:
 The server process is started on some computer system.It initializes itself,then goes
to sleep waiting for a client process to contact it requesting some service.
 A client process is started, either on the same system or on another system that is
connected to the server’s system with a network.Client processes are often initiated
by an interactive user entering a command to a time-sharing system.The client
process sends a request across the network to the server requesting service of some
form.Some examples of the type of service that a server can provide are

1. return the time-of day to the client,


2. print a file on a printer for the client,
3. read or write a file on the server’s system for the client,
4. allow the client to login to the server’s system,
5. execute a command for the client on the server’s system.
 When the server process has finished providing its service to the client,the server
goes back to sleep,waiting for the next client request to arrive.
 We can futher divide the server processes into two types.

B.Tech ( cse ) - secured file transfer protocol - 2004 5


1. When a client’s request can be handled by the server in a known,short amount
of time,the server process handles the request itself.We call these iterative
servers.A time-of-day service is typically handled in an iterative fashion by the
server.
2. When the amount of time to service a request depends on the request itself(so
that the server doesn’t know ahead of time how much effort it takes to handle
each request),the server typically handles it in a concurrent fashion.These are
called concurrent servers.A concurrent server invokes another process to
handle each client request,so that the original server process can go backto
sleep,waiting for the next client request.Naturally,this type of server requiresan
operating system that allows multiple processes to run at the same time.Most
client requests that deal with a file of information(print a file,read or write a
file,for example)are handled in a concurrent fashion by the server,as the
amount of processing required to handle each request depends on the size of
the file.

B.Tech ( cse ) - secured file transfer protocol - 2004 6


2.2 SOCKETS
Sockets provide an interface between application programs and the
TCP/IP protocols. A socket is a communication mechanism that forms an end point of
a communication channel. It is an operating system resource that is allocated to
application programs upon request. Application programs request the operating
system to create a socket when one is needed. The operating system returns a small,
unique integer descriptor that is used by the application program to refer to the newly
created socket. Once a socket is created, it can’t be accessed by other processes.
Whenever it makes sense, sockets can perform exactly like UNIX files or devices, so
they can be used with traditional operations like read and write. For example, once an
application program creates a socket and creates a TCP connection from the socket
to a foreign destination, the program can use write to send a stream of data across
the connection, and the application at the other end can use read to collect the data.
To make it possible to use such primitives with both files and sockets, the operating
system allocates both the sockets descriptors and file descriptors from the same
integer set, and makes sure that if a given integer has been allocated as a file
descriptor , it will also not be allocated as a socket descriptor.

2.2.1 SOCKET ATTRIBUTES:


A socket is characterized by three attributes, domain, type, and protocol. They
also have an address that is used as their name. The formats of the addresses vary
depending on the domain, also known as the protocol family.

Socket Domains:
Domains specify the network medium that the socket communication will
use. The most common domain is AF_INET refers to Internet networking. It is used
on many UNIX local area networks and the Internet itself. The underlying protocol,
Internet protocol(IP), imposes a particular way of specifying computers on a network -
this is the IP address.
Socket domains include:

B.Tech ( cse ) - secured file transfer protocol - 2004 7


AF_UNIX - UNIX internal (file system sockets)
AF_INET - ARPA Internet protocol (UNIX network AF_ISO
sockets)
AF_ISO - ISO standard protocol
AF_NS - Xerox Network Systems protocols
AF_IPX - Novell IPX protocol
AF_APPLETALK - Appletalk DDS

Socket Types:
A socket domain may have a number of different ways of
communicating, each of which might have different characteristics. The most widely
used socket types are:

Stream Sockets:
Stream sockets are specified by the type SOCK_STREAM. They are
implemented in the AF_INET domain by TCP/IP connections. Stream sockets provide
a sequenced, reliable two way byte stream. Thus data us guaranteed not to be lost,
duplicated or re-ordered without an indication that an error has occurred.

Datagram Sockets:
Datagram sockets are specified by the type SOCK_DGRAM. They are
implemented in the AF_INET domain byte UDP.IP connections. Datagram sockets
provide an unsequenced, unreliable service.
Stream sockets treat communications as a continuous stream of characters,
while datagram sockets have to read entire messages at once. Each uses its own
communciations protocol. Stream sockets use TCP (Transmission Control Protocol),
which is a reliable, stream oriented protocol, and datagram sockets use UDP (Unix
Datagram Protocol), which is unreliable and message oriented.

B.Tech ( cse ) - secured file transfer protocol - 2004 8


Socket Protocols:
The socket protocol specifies a specific protocol for a socket. UNIX network
and file systems don’t require a protocol other than the default.

2.2.2 CONCURENT SERVERS VS ITERATIVE SERVERS:


Iterative servers can handle only one client at a time. Hence, if multiple client
requests arrive with a short time interval, the requests are processed in temporal
order. The next client in order will have to wait for the server to finish servicing the
current client requests and close that connection, before it can be processed.
Concurrent servers handle multiple clients at the same time. This is extremely
efficient when a client request can take long to service, since a server will not be tied
up with a single client. Unless forced by the operating system constraints, FTP
servers are concurrent servers. Typically, a concurrent server has two parts: a single
master program that is responsible for accepting new connections, and a set of
slaves that are responsible for handling individual requests.
The master performs the following steps :
Open Port: The master opens the well known port at which it can be reached.
Wait for Client: The master waits for a client to send a request.
Start Slave: The master starts an independent, concurrent slave to handle this
request. The slave handles one request and then terminates – the slave does not
wait for requests from other clients.
Continue: The master returns to the wait step and continues accepting new
connections while the newly created slave handles the previous request concurrently.

B.Tech ( cse ) - secured file transfer protocol - 2004 9


FTP

ftp is a protocol for tansferring files from one host to another host. ftp
uses two parallel tcp connections to transfer a file ,a control connection and a data
connection the control connection is used for sending control information between
two hosts, information such as user identification, passwords ,commands to change
remote directory, and commands to put and get files. The data connection is used
actually to send a file.

-------------
|/---------\|
|| User || --------
||Interface|<--->| User |
|\----^----/| --------
---------- | | |
|/------\| FTP Commands |/----V----\|
||Server|<---------------->| User ||
|| PI || FTP Replies || PI ||
|\--^---/| |\----^----/|
| | | | | |
-------- |/--V---\| Data |/----V----\| --------
| File |<--->|Server|<---------------->| User |<--->| File |
|System| || DTP || Connection || DTP || |System|
-------- |\------/| |\---------/| --------
---------- -------------

Server-FTP USER-FTP

Model for FTP use

B.Tech ( cse ) - secured file transfer protocol - 2004 10


In the model described above the user-protocol interpreter initiates the
control connection.The control connection follows the Telnet protocol. At the
initiation of the user, standard FTP commands are generated by the user-PI and
transmitted to the server process via the control connection. Standard replies are
sent from the server-PI to the user-PI over the control connection in response to the
commands.

2.3.1 OBJECTIVES OF FTP :


 To transfer data reliably and efficiently,
 To promote sharing of files (computer programs and/or data),
 To encourage indirect or implicit (via Programs) use of remote computers.
 To shield a user from variation in file storages among hosts.

2.3.2 FTP TERMINOLOGY:


user: A person or a process on behalf of a person wishing to obtain file transfer
service.
PI: The Protocol Interpreter. The user and the server sides have distinct roles
implemented in a user-PI and the server-PI.
user-FTP process: A set of functions including a PI, a data transfer process and a
user interface which together perform the file transfer function in cooperation with one
or more FTP servers.
server-FTP process: A process or a set of processes which perform the file transfer
function in cooperation with a user-FTP process, and, possibly, another server.
user-PI: The user-PI initiates the control connection from its default port to the server-
FTP process, initiates the FTP commands and governs the user- DTP if that process
is a part of the file transfer.
server-PI: The server-PI listens on its default port for a connection from a user-PI,
and establishes a control communication path. It receives standard FTP commands
from the uer-PI, sends replies, and governs the server-DTP.

B.Tech ( cse ) - secured file transfer protocol - 2004 11


Control Connection: The control connection is the communication path between the
client-PI and the server-PI for the exchange of commands and replies.
Data Transfer Process (DTP): The data transfer process establishes and manages
the data connection. The DTP can be active or passive.
Data Connection: This is a full duplex connection over which data is transferred
when a file transfer is requested. The path may be between a server-DTP and a user-
DTP, or between server DTPs. The passive DTP “listens” on the data port for a
connection from the active DTP in order to open the data connection.

2.3.3 FTP PROCESS MODEL:

The FTP process can be modeled as shown in the figure. The user-PI initiates
the control connection with the server. The FTP commands initiated by the user are
transmitted to the server process via the control connection. In response to these
commands, standard replies are sent by the server-PI to the user-PI over the control
connection.

User Interface User


FTP commands
Server
PI FTP Replies User PI
File System
Data
Server DTP Connection User File System
DTP

Server-ftp
User-ftp

Process model

B.Tech ( cse ) - secured file transfer protocol - 2004 12


The FTP commands specify the nature of the file system operations and the
parameters for the data connection. The user-DTP or its designate should “listen” on
the specified data port, and the server should initiate the data connection and the
data transfer in accordance with the specified parameters. It should be noted that the
data port need not be in the same host that initiates the FTP commands via the
control connection, but the user or the user-FTP process must ensure “listen” on the
specified data port. It should be noted that client implementationsmay consist of a
single application program which performs both the control functions as well as the
data transfer. However, the protocol requires that such clients still use multiple TCP
connections, one for control and the other(s) for data transfer.

2.3.4 FTP General Model and User Interface:


FTP is designed to permit interactive or batch use. Users can invoke FTP
interactively- ie run an FTP client that establishes communication with a specified
server to transfer files . However , some softwares can invoke FTP automatically,
without requiring an user to interact with an FTP client.
When an user invokes FTP interactively, the user communicates with a
command driven interface. FTP issues a prompt to which the user responds by
entering a command, and then issues another prompt.

B.Tech ( cse ) - secured file transfer protocol - 2004 13


INTRUSION DETECTOR
Intrusion Detector is a libpcap-based packet sniffer/logger, which can be
used as a lightweight network intrusion detection system. It features rules based
logging and can perform protocol analysis, content searching/matching and can be
used to detect a variety of attacks and probes, such as buffer overflows, stealth port
scans, CGI attacks, SMB probes, OS fingerprinting attempts, and much more.
Intrusion detector has a real-time alerting capability, with alerts being sent to syslog, a
separate "alert" file, or as a WinPopup message via Samba's smbclient.

2.4.1 What is Network Intrusion Detection?


A Network Intrusion Detection System (NIDS) is a system that is responsible
for detecting anamolous, inappropriate, or other data that may be considered
unauthorized occuring on a network. Unlike a firewall, which is configured to allow or
deny access to a particular service or host based on a set of rules. If the traffic
matches an acceptable pattern, it is permitted regardless of what the packet contains.
However, an NIDS captures and inspects all traffic, regardless of whether it's
permitted or not. Based on the contents, at either the IP or application level, an alert
is generated.
Snort is a "lightweight" NIDS in that it is non-intrusive, easily configured,
utilizes familiar methods for rule development, and takes only a few minutes to install.
Snort currently includes the ability to detect more than 1100 potential vulnerabilities.
Keep in mind that Intrusion Detection devices work in conjunction with other security
measures, and are not a replacement for other good security practices.
It is also quite feature-packed right out of the box. Among its features include the
ability to:
 Detect and alert based on pattern matching for threats including buffer overflows,
stealth port scans, CGI attacks, SMB probes and NetBIOS queries, NMAP and
other portscanners, well-known backdoors and system vulnerabilities, DDoS
clients, and many more;

B.Tech ( cse ) - secured file transfer protocol - 2004 14


 Use syslog, SMB "WinPopUp" messages, or a file to alert an administrator;
 Develop new rules quickly once the pattern (attack signature) is known for the
vulnerability;
 Record packets in their human-readable form from the offending IP address in a
hierarchial directory structure.
 Used as a "passive trap" to record the presence of traffic that should not be found
on a network, such as NFS or Napster connections;
 Used on an existing workstation to monitor a home DSL connection, or on a
dedicated server to monitor a corporate web site
 Snort uses the popular libpcap library, the same library that tcpdump uses to
perform its packet sniffing. Snort decodes all the packets passing by on the
network to which it's attached by entering promiscous mode. Based upon the
content of the individual packets and the rules defined in the configuration file, an
alert is generated.

2.4.2 Why To Use Intrusion Detection?


Intrusion detection devices are an integral part of any network. The Internet is
constantly evolving, and new vulnerabilities and exploits are found regularly. They
provide an additional level of protection to detect the presence of an intruder, and
help to provide accountability for the attacker's actions.

2.4.3 Why is intrusion detection required ?


Intrusion detection is needed in today’s computing environment because it is
impossible to keep pace with the current and potential threats and vulnerabilities in
our computing systems. The environment is constantly evolving and changing fueled
by new technology and the Internet. To make matters worse, threats and
vulnerabilities in this environment are also constantly evolving. Intrusion detection
products are tools to assist in managing threats and vulnerabilities in this changing
environment.

B.Tech ( cse ) - secured file transfer protocol - 2004 15


Threats are due to people or groups who have the potential to compromise
your computer system. These may be a curious teenager, a disgruntled employee, or
espionage from a rival company or a foreign government. The hacker has become a
nemesis to many companies.
Vulnerabilities are weaknesses in the systems. Vulnerabilities can be
exploited and used to compromise your system. New vulnerabilities are discovered all
of the time. Every new technology, product, or system brings with it a new generation
of bugs and unintended conflicts or flaws. Also the possible impacts from exploiting
these vulnerabilities is constantly evolving. In a worst-case scenario, an intrusion may
cause production downtime, sabotage of critical information, theft of confidential
information, cash, or other assets, or even negative public relations that may affect a
company’s stock price.
Intrusion detection products are tools that can assist in protecting a company
from intrusion by expanding the options available to manage the risk from threats and
vulnerabilities. Intrusion detection capabilities can help a company secure its
information. The tool could be used to detect an intruder, identify and stop the
intruder, support investigations to find out how the intruder got in, and stop the exploit
from use by future intruders. The correction should be applied across the enterprise
to all similar platforms. Intrusion detection products can become a very powerful tool
in the information security practitioner’s tool kit.

B.Tech ( cse ) - secured file transfer protocol - 2004 16


ABOUT LINUX
Linux is a free, from scratch operating system based heavily on the
POSIX and UNIX API's. It supports both 32 and 64 bit hardware and provides a stable
multiuser internet ready operating system.
Linux itself is not Unix, although many people call it that and you would
be very hard pushed to tell the difference. This is because the Unix trademark is
specific to systems that meet a complex set of X/Open standards and has a cost.
Some Linux vendors however are working on "Unix" branding.
Some of the many applications for Linux are: X11 Desktop, File server,
Computing Backend, Web Server, Usenet News, Terminal Server, FTP Archive, and
Firewall.
Linux uses internet and industry standard components and protocols
giving a system with complete network integration. The operating system can act as a
server for most major file serving protocols, and provide all the major internet
applications. The Xwindows provides a networked and platform independant
graphical interface that (unlike proprietary user interfaces) allows one desktop to
access applications running on multiple machines across local and wide area
networks.

2.5.1 LINUX ARCHITECTURE:


LINUX operating system contains three layers as shown in the fig. the
upper layer contains packages like postgressql, GTK, MYSQL which provide
additional facilities to the user. The middle layer caller KERNEL part of the operating
system consists a set of C programs written to interact with the hardware.

B.Tech ( cse ) - secured file transfer protocol - 2004 17


kernel packages

hardware kernel

hardware
architecture of linux

2.5.2 OVERVIEW ON FILES IN LINUX:


A simple description of the UNIX system, also applicable to Linux, is this:
"On a UNIX system, everything is a file; if something is not a file, it is a process."
This statement is true because there are special files that are more than just
files (named pipes and sockets, for instance), but to keep things simple, saying that
everything is a file is an acceptable generalization. A Linux system, just like UNIX,
makes no difference between a file and a directory, since a directory is just a file
containing names of other files. Programs, services, texts, images, and so forth, are
all files. Input and output devices, and generally all devices, are considered to be
files, according to the system.

Managing files in linux :


In order to manage all those files in an orderly fashion, man likes to
think of them in an ordered tree-like structure on the hard disk, as we know from MS-
DOS (Disk Operating System) for instance. The large branches contain more
branches, and the branches at the end contain the tree's leaves or normal files. For

B.Tech ( cse ) - secured file transfer protocol - 2004 18


now we will use this image of the tree, but we will find out later why this is not a fully
accurate image.

Sort of files:
Most files are just files, called regular files; they contain normal data,
for example text files, executable files or programs, input for or output from a program
and so on.
While it is reasonably safe to suppose that everything you encounter on
a Linux system is a file, there are some exceptions.
Directories: files that are lists of other files.
Special files: the mechanism used for input and output. Most special files are in
/dev, we will discuss them later.
Links: a system to make a file or directory visible in multiple parts of the system's file
tree. We will talk about links in detail.
(Domain) sockets: a special file type, similar to TCP/IP sockets, providing
inter-process networking protected by the file system's access control.
Named pipes: act more or less like sockets and form a way for processes to
communicate with each other, without using network socket semantics.

File system layout:


For convenience, the Linux file system is usually thought of in a tree structure.
The tree of the file system starts at the trunk or slash, indicated by a forward slash (/).
This directory, containing all underlying directories and files, is also called the root
directory or "the root" of the file system. The directories that reside in root are:
/bin : common programs, shared by the system, the system administrator and the
users.
/boot: the startup files and kernel.
/dev: contains references to all the CPU peripheral hardware, which are
represented as files with special properties.

B.Tech ( cse ) - secured file transfer protocol - 2004 19


/home: home directories of common user.

2.5.3 THE KERNEL:


The kernel is the heart of the system. It manages the communication
between the underlying hardware and the peripherals. The kernel also makes sure
that processes and daemons (server processes) are started and stopped at the exact
right times. The kernel has a lot of other important tasks, so many that there is a
special kernel-development mailing list on this subject only, where huge amounts of
information are shared. It would lead us too far to discuss the kernel in detail. For now
it suffices to know that the kernel is the most important file on the system.

2.5.4 THE SHELL


What is a shell?
All kinds of definitions are available, ranging from the simple
comparison that "the shell is the steering wheel of the car", to the vague definition in
the Bash manual which says that "bash is an sh-compatible command language
interpreter," or an even more obscure expression, "a shell manages the interaction
between the system and its users". A shell is much more than that.
A shell can best be compared with a way of talking to the computer, a
language. Most users do know that other language, the click-and-point language of
the desktop. But in that language the user is treated as a baby, asked to pick from
what is presented to him.
The shell, on the other hand, is an advanced way of communicating with the
system, because it allows for conversation and taking initiative. Both partners in the
communication are equal, so new ideas can be tested. The shell allows the user to
handle a system in a flexible way, and is also a means of stress reduction.
Shell types

B.Tech ( cse ) - secured file transfer protocol - 2004 20


Just like people know different languages and dialects, the computer
knows different shell types
sh or Bourne Shell: the original shell still used on UNIX systems and in UNIX
related environments. This is the basic shell, a small program with few features.
When in POSIX-compatible mode, bash will emulate this shell.
bash or Bourne Again shell: the standard GNU shell, intuitive and flexible.
Probably most advisable for beginning users while being at the same time a powerful
tool for the advanced and professional user. On Linux, bash is the standard shell for
common users. This shell is a so-called superset of the Bourne shell, a set of
add-ons and plug-ins. This means that the Bourne Again shell is compatible with the
Bourne shell: commands that work in sh, also work in bash. However, the reverse is
not always the case.
csh or C shell: the syntax of this shell resembles that of the C programming
language. Sometimes asked for by programmers.
tcsh or Turbo C shell: a superset of the common C shell, enhancing user-
friendliness and speed.
ksh or the Korn shell: sometimes appreciated by people with a UNIX background. A
superset of the Bourne shell; with standard configuration a nightmare for beginning
users.

2.5.5 VI EDITOR
Vi editor is a full-screen editor now available with all LINUX systems,which is
used to write some C programs and shell scripts.vi offers cryptic, and sometimes
mnemonic ,internal commands for editing work.It makes complete use of the
keyboard, where practically every key has a function.

The three modes:


A vi session begins by invoking the command vi with the filename:
$ vi serv1.c

B.Tech ( cse ) - secured file transfer protocol - 2004 21


You are presented a full empty screen , each line beginning with a ‘~’ .This is vi’s way
of indicating that they are non-existent lines.For text editing vi uses 24 of
the 25 lines that are normally available in a terminal. The last line is reserved for
some commands that you can enter to act on the text.This line also used by the
system to display the massages.the file name appears in this line with the message
“serv1.c”[newfile].

The relationship between these three modes is depicted in the following figure:

Command
mode

I,o,O,r,R,s,S,a,A <enter>
<Esc> :

Input
Ex mode
mode

1.Command mode:
when you open the file with vi , the cursor is positioned at the top left corner of
the screen.you are said to be in command mode.This is the mode you can pass the
commands to act on the text,using most of the keys of the keyboard.pressing a key
does not show it on the screen,but may perform a function like moving the cursor to
the next line, or deleting a line.you can’t use the command mode to enter or replace
the text.The following table summarizes the Command mode commands:

Command Action

x Deletes a single character


4x Deletes the current character

B.Tech ( cse ) - secured file transfer protocol - 2004 22


as well as three characters from the right
dd Deletes a single line
6dd Deletes the current line as well as
five lines below the current line

2.Input mode:
To enter text, you have to leave the command mode and enter the input
mode.Thereare ten keys which, when pressed take you to this mode,and whatever
you type shows up on the screen.To leave this mode you have to press <esc> key.
The following table summarizes the input mode commands:

Command Function

i Inserts text to left of cursor(Existing text shifted right)


I Inserts text at the beginning of the line(Existing text shifted right)
a Appends text to left of cursor(Existing text shifted to right)
A Appends at the end of line
o Opens line below
O Opens line above
Rch Replaces single character under cursor with ch
R Replaces text from cursor to right
s Replaces single character under cursor with any number of
characters
S Replaces entire line

3.Ex mode:

B.Tech ( cse ) - secured file transfer protocol - 2004 23


By entering ex mode you can save file or you can switch to editing another
file.This is also called line mode.you can enter the command in the last line of the
screen.

Command Action

:w Saves file and remains inediting mode


:x Saves file and quits editing mode
:wq Saves file and quits editing mode
:w n2w.p Like “save as “ in Microsoft windows
:q Quits editing mode when no changes are made to file
:q! Quits editing mode but after abandening changes
:n1,n2wbuild.sql Writes lines n1 to n2 to file build.sql
:.w build.sql Writes current line to file build.sql
:$w build.sql Writes last line to file build.sql
:sh Escape to Linux shell

Application of linux:
Today Linux has joined the desktop market. Linux developers concentrated on
networking and services in the beginning, and office applications have been the last
barrier to be taken down. Linux an acceptable choice as a workstation, providing an
easy user interface and MS compatible office applications like word processors,
spreadsheets, presentations and the like.
On the server side, Linux is well-known as a stable and reliable platform,
providing database and trading services for companies like Amazon, the well-known
online bookshop, US Post Office, the German army and such. Especially Internet

B.Tech ( cse ) - secured file transfer protocol - 2004 24


providers and Internet service providers have grown fond of Linux as firewall, proxy-
and web server, and there will be a Linux box within reach of every UNIX system
administrator who appreciates a comfortable management station. In post offices,
they are the nerve centers that route mail and in large search engine, clusters are
used to perform internet searches.These are only a few of the thousands of heavy-
duty jobs that Linux is performing day-to-day across the world

2.6 C Language
Functions used in c :
Memset :
This function is used to set n bytes of an array to a value s. The syntax is as
follows
memset(void *s ,int c ,size_t n);
Getcwd :
This function is used to get the current working directory.
getcwd(char *buff,int buflen);
buff contains the current directory and buflen is the length of the buff.
System :
It executes a command internally .
int system(char * command);
unlink:
this function is used to delete a file.if the file has readonly property this command
fails.
int unlink(const char * filename)
rename :
it is used to change the name of a file.
int rename(const char *oldfilename,const char *newfilename);
strdup :
this function is used to duplicat a given string.the syntax is
char * strdup(const char *s)

Files

B.Tech ( cse ) - secured file transfer protocol - 2004 25


Having dealt with the various console input/output functions like printf(), scanf(),
getch() etc., the disk i/o operations are performed on entities called files.

Opening A File:
Before we can write information to a file on a disk or read it, we must open
the file. When we request the operating system to open a file, what we get back, is a
pointer to the structure FILE. That is why, we make the following declaration before
opening the file,
FILE *fp;
fopen() is used to open a file. The syntax is as follows:
fp = fopen(“pr1.c”,”r”);

Reading A File:
To read a file, the file must be opened in the read mode. The syntax will be
as follows:
fp = fopen(“pr1.c”, “r”);
The contents in the file are read by using the function called, fscanf(). The
syntax is as follows :
fscanf(fp, format, values);

Writing A File:
Before writing data into a file, the file must be opened in write mode.
fp= fopen(“pr1.c”,”w”);
The data is written into the file , by using the function called, fprintf().The syntax is
as follows :
fprintf (fp, format, values);

Closing A File:
Closing of file is done by using the function called, fclose(). The syntax
is as follows:
fclose (fp);

File Opening Modes:

B.Tech ( cse ) - secured file transfer protocol - 2004 26


1. “r” Searches file. Operations possible are reading from a file
2.”w” Searches file. Operations possible are writing to the file.
3.”a” Searches file. Operations possible are appending new contents at
end of file
4.”r+” Searches file. Operations possible are reading existing contents,
writing new contents, modifying existing contents of the file.
5.”w+” Searches file. Operations possible are writing new contents, reading
them back and modifying existing contents of the file.
6.”a+” Searches file. Operations possible are reading existing contents,
appending new contents to end of file. Cannot modify existing contents.

B.Tech ( cse ) - secured file transfer protocol - 2004 27


2.7 SYSTEM REQUIREMENTS
Problem definition:
To simulate FTP protocol in secured way
Software requirements:
Our project is basically developed in C language with platform LINUX
operatingsystem.
Hardware requirements:
Pentium processor-III or more is used to run our project and memory of
40GB , lan are required.

B.Tech ( cse ) - secured file transfer protocol - 2004 28


DESGIN PHASE

B.Tech ( cse ) - secured file transfer protocol - 2004 29


3.1 SOCKET PROGRAMMING
A socket is a communication mechanism. A socket is normally idenitifed by a
small integer which may be called the socket descriptor. The socket mechanism was
first introduced in the 4.2 BSD Unix system in 1983 in conjunction with the TCP/IP
protocols that first appeared in the 4.1 BSD Unix system in late 1981.
Formally a socket is defined by a group of four numbers, these are
 The remote host identification number or address
 The remote host port number
 The local host identification number or address
 The local host port number
Users of Internet applications are normally aware of all except the local port number,
this is allocated when connection is established and is almost entirely arbitrary unlike
the well known port numbers associated with popular applications.
To the application programmer the sockets mechanism is accessed via a
number of functions. These are.
Socket() : create a socket.
Bind() : associate a socket with a network address.
Connect() : connect a socket to a remote network address.
Listen() : wait for incoming connection attempts.
Accept() : accept incoming connection attempts.
The sockets mechanism is usually used to implement client-server
applications. The client process is directly or indirectly user driven whereas the server
process sits on a host waiting for incoming connections. A server process will run
unattended and continuously. In the Unix environment such processes are called
daemon processes.
To create a daemon observe the following steps.
 Ensure that the return value from functions is always checked.
 Remember that the daemon inherits various things from the shell from
which it is invoked. .

B.Tech ( cse ) - secured file transfer protocol - 2004 30


 Close all open files. This includes stdin, stdout and stderr. Open suitable special files
for stdin, stdout and stderr if necessary.
 Change the working directory. Remember that if the daemon crashes it will drop core
in the current working directory. Also the working directory, and under some systems
the executable file, are open when the daemon is running. This may cause difficulties
if the system manager wants to unmount the relevant partition whilst the daemon is
running.
 Reset the file creation mask using umask().
To run a daemon in background after interaction to start it up, which may
be useful during development, use the fork() function.A socket is created using the
function socket(). The prototype is

Int socket(int domain, int type, int protocol)


domain is either AF_UNIX or AF_INET. This parameter specifies whether the
socket is to be used for communicating between Unix file system like objects or
Internet objects. Actually this parameter is intended to allow sockets to be used with a
wide variety of networking protocols and products. type specifies the
communications semantics. There are a number of possible values.
SOCK_STREAM: stream based full-duplex communication.
SOCK_DGRAM: datagram based communication
protocol is normally set to zero.
The return value from socket() is a small integer that may be used to refer
to a socket in subsequent calls. It may be called the socket descriptor or handle and
is analogous to a file descriptor.
The connect() function:
The connect() function is used by a client program to establish
communication with a remote entity.
incoming connections bind()

B.Tech ( cse ) - secured file transfer protocol - 2004 31


to accept incoming connection requests a server process must first
create a socket using socket() and then use bind() to associate a port number with
the socket.
This is similar to the connect() function except that, when binding in the
AF_INET domain, the components of the struct sockaddr_in are filled in differently.
Incoming connetions for listen():
Once an address has been bound to a socket it is then necessary to indicate
the socket is to be listened to for incoming connection requests. This is done using
the listen() function.
Incoming connections accept():
Once the listen() call has returned the accept() call should be issued, this will
block until a connection request is received from a remote host.
The return value of the call is the number of a new socket descriptor that
should be used for all subsequent communication with the remote host. You can, and
should, carry on listening on the original socket number. There is no way of rejecting
a connection request, you must accept it then close it.
Receiving data:
There are a variety of functions that may be used to receive incoming
messages. Read() may be used in the exactly the same way as for reading from files.
There are some complications with non-blocking reads. This call may only be used
with SOCK_STREAM type sockets.
The return value is the number of bytes received or -1. The value -1 indicates
an error.
Sending data:
There are a variety of functions that may be used to send outgoing messages.
Write() may be used in exactly the same way as it is used to write to files. This call
may only be used with SOCK_STREAM type sockets. The return value is the number
of bytes sent or -1.

3.1.1 Multipls server sessions:

B.Tech ( cse ) - secured file transfer protocol - 2004 32


If sockets programming is being used to proved a server facility it is important
to ensure that multiple simultaneous sessions are handled correctly. Once a
connection request has been accepted the program will be engaged in handling the
associated dialogue, further connection requests will be held until the listener
program gets round to issuing the accept() call again, so only one client can be
handled at a time.
There are several ways of handling this issue. Under Unix the simplest
solution is to fork a separate process to handle the client/server dialogue once a
connection request has been received.
The sockets and the connection that occur in the outline can be shown as
follows:
Server Client
listenf Connection
d Connect()
request

1. the status of the client and the sever while the server is blocked in the call to
accept and the connection request arrives from the client.
2. the connection status after connect returns is as follows:

Server Client
Listenfd
Connection Connect()
connfd

The kernel accepts the connection and a new socket connfd, is created. This is
a connected socket and data can now be read and written across connection.
3. the status after fork is as follows:

Server(parent) Client

Listenfd() Connect()
Connection
Connfd()

fork Server(child)

B.Tech ( cse ) - secured file transfer protocol - 2004 33


Listen fd()

Connfd()

the status after the child closes the connected socket and the child closes
the listening socket as follows.

Server(parent) client

listenfd
Connect()

Connection

Server(child)

connfd

this is the desired state of the sockets. The child is handling the connection
with the client and the parent can call accept again on the listening socket, to
handle the next connection.

B.Tech ( cse ) - secured file transfer protocol - 2004 34


3.2 FTP COMMANDS
3.2.1 ACCESS CONTROL COMMANDS
The following commands specify access control identifiers (command codes are
shown in parentheses).
USER NAME (USER) :
The argument field is a Telnet string identifying the user.The user identification
is that which is required by the server for access to its file system. This command
will normally be the first command transmitted by the user after
the control connections are made (some servers may require this). Additional
identification information in the form of a password and/or an account command may
also be required by some servers. Servers may allow a new USER command to be
entered at any point in order to change the access control
and/or accounting information. This has the effect of flushing any user, password,
and account information already supplied and beginning the login sequence again.
All transfer parameters are unchanged and any file transfer in
progress is completed under the old access control paameters.
PASSWORD (PASS)
The argument field is a Telnet string specifying the user's password. This
command must be immediately preceded by the user name command, and, for some
sites, completes the user's identification for access control. Since password
information is quite sensitive, it is desirable in general to "mask" it or suppress
typeout. It appears that the server has no foolproof way to achieve this. It is
therefore the responsibility of the user-FTP process to hide the sensitive password
information.
CHANGE WORKING DIRECTORY (CWD)

B.Tech ( cse ) - secured file transfer protocol - 2004 35


This command allows the user to work with a different directory or dataset for file
storage or retrieval without altering his login or accounting information. Transfer
parameters are similarly unchanged. The argument is a pathname specifying a
directory or other system dependent ile group designator.
CHANGE TO PARENT DIRECTORY (CDUP)
This command is a special case of CWD, and is included to simplify the
implementation of programs for transferring directory trees between operating
systems having differentsyntaxes for naming the parent directory. The reply codes
shall be identical to the reply codes of CWD.
LOGOUT (QUIT)
This command terminates a USER and if file transfer is not in progress, the
server closes the control connection. If file transfer is in progress, the connection will
remain open for result response and the server will then close it.
If the user-process is transferring files for several USERs but does not wish to close
and then reopen connections for each, then the REIN command should be used
instead of QUIT.
An unexpected close on the control connection will cause the server to take
the effective action of an abort (ABOR) and a logout (QUIT).

3.2.2 SERVICE COMMANDS


The FTP service commands define the file transfer or the file system function
requested by the user. The argument of an FTP service command will normally be a
pathname. The syntax of pathnames must conform to server site conventions (with
standard defaults applicable), and the language conventions of the control
connection. The suggested default handling is to use the last specified device,
directory or file name, or the standard default defined for local users. The
commands may be in any order except that a "rename from" command must be
followed by a "rename to" command and the restart command must be followed by
the interrupted service command (e.g., STOR or RETR). The data, when transferred
in response to FTP service commands, shall always be sent over the data

B.Tech ( cse ) - secured file transfer protocol - 2004 36


connection, except for certain informative replies. The following commands specify
FTP service requests:

RETRIEVE (RETR)
This command causes the server-DTP to transfer a copy of the ile, specified
in the pathname, to the server- or user-DTP at the other end of the data connection.
The status and contents of the file at the server site shall be unaffected.
STORE (STOR)
This command causes the server-DTP to accept the data transferred via the
data connection and to store the data as a file at the server site. If the file specified in
the pathname exists at the server site, then its contents shall be replaced by the
data being transferred. A new file is created at the server site if the file specified in
the pathname does not already exist.
STORE UNIQUE (STOU)
This command behaves like STOR except that the resultant file is to be
created in the current directory under a name unique to that directory. The 250
Transfer Started response must include the name generated.
APPEND (with create) (APPE)
This command causes the server-DTP to accept the data transferred via the
data connection and to store the data in a file at the server site. If the file specified in
the pathname exists at the server site, then the data shall be appended to that file;
otherwise the file specified in the pathname shall be created at the server site.
DELETE (DELE)
This command causes the file specified in the pathname to be deleted at the
server site. If an extra level of protection is desired (such as the query, "Do you
really wish to delete?"), it should be provided by the user-FTP process.
REMOVE DIRECTORY (RMD)

B.Tech ( cse ) - secured file transfer protocol - 2004 37


This command causes the directory specified in the pathname to be removed
as a directory (if the pathname is absolute) or as a subdirectory of the current
working directory (if the pathname is relative).
MAKE DIRECTORY (MKD)
This command causes the directory specified in the pathname to be created
as a directory (if the pathname is absolute) or as a subdirectory of the current working
directory (if the pathname is relative).

PRESENT WORKING DIRECTORY (PWD)


This command causes the name of the current working directory to be
returned in the reply.
LIST (LIST)
This command causes a list to be sent from the server to the passive DTP. If
the pathname specifies a directory or other group of files, the server should transfer a
list of files in the specified directory. If the pathname specifies a
file then the server should send current information on the file. A null argument
implies the user's current working or default directory. The data transfer is over the
data connection in type ASCII or type EBCDIC. (The user must ensure that
the TYPE is appropriately ASCII or EBCDIC). Since the information on a file may
vary widely from system to system, this information may be hard to use automatically
in a program, but may be quite useful to a human user.
STATUS (STAT)
This command shall cause a status response to be sent over the control
connection in the form of a reply. The command may be sent during a file transfer
(along with the Telnet IP and Synch signals--see the Section on FTP Commands) in
which case the server will respond with the status of the operation in progress,
or it may be sent between file transfers. In the latter case, the command may have
an argument field. If the argument is a pathname, the command is analogous to the
"list" command except that data shall be transferred over the control
connection. If a partial pathname is given, the server may respond with a list of file
names or attributes associated with that specification. If no argument is given, the

B.Tech ( cse ) - secured file transfer protocol - 2004 38


server should return general status information about the server FTP process. This
should include current values of all transfer parameters and the status of
connections.
HELP (HELP)
This command shall cause the server to send helpful information regarding its
implementation status over the control connection to the user. The command may
take an argument (e.g., any command name) and return more specific
information as a response. The reply is type 211 or 214.

3.2.3 STATE DIAGRAMS


Here we present state diagrams for a very simple minded FTP
implementation. Only the first digit of the reply codes is used. There is one state
diagram for each group of FTP commands or command sequences.
The command groupings were determined by constructing a model for each
command then collecting together the commands with structurally identical models.
For each command or command sequence there are three possible outcomes:
success (S), failure (F), and error (E). In the state diagrams below we use the symbol
B for "begin", and the symbol W for "wait for reply".
We first present the diagram that represents the largest group of FTP
commands:

1,3
E

S
cmd W 2
B

F
4,5

B.Tech ( cse ) - secured file transfer protocol - 2004 39


This diagram models the commands:
ABOR, ALLO, DELE, CWD, CDUP, SMNT, HELP, MODE, NOOP, PASV,
QUIT, SITE, PORT, SYST, STAT, RMD, MKD, PWD, STRU, and TYPE.

3 E

B cmd W 2 S

F
1 4,5

This diagram models the commands:


APPE, LIST, NLST, REIN, RETR, STOR, and STOU.

Note that this second model could also be used to represent the first group of
commands, the only difference being that in the first group the 100 series replies are
unexpected and therefore treated as error, while the second group expects (some
may require) 100 series replies.
Remember that at most, one 100 series reply is allowed per command.

The remaining diagrams model command sequences, perhaps the simplest


of these is the rename sequence:

rnfr W 1,2
B E

3 4,5

B.Tech ( cse ) - secured file transfer protocol - 2004 40


S

2 1,3

rnto
F
W

4,5

The next diagram is a simple model of the Restart command:

Rest 1,2
B W E

3 4,5
S

2 3

cmd
W F

1 4,5

Where "cmd" is APPE, STOR, or RETR


We note that the above three models are similar.The Restart differs from the Rename
two only in the treatment of 100 series replies at the second stage, while the second
group expects (some may require) 100 series replies. Remember that at most, one
100 series reply is allowed per command.

B.Tech ( cse ) - secured file transfer protocol - 2004 41


3.3 INTRUSION DETECTION DEVICE PLACEMENT
The device may be placed outside an organization's firewall between the
firewall and the external untrusted network. This allows Intrusion Detector to detect
not only the attacks that may make it through the firewall, but also those that are
blocked by the firewall.
The presence of switches, routers and firewalls will all have an effect on the
correct placement of the box. A decision must be made as to which network segment
will catch the traffic you actually want to monitor. Placement of the NIDS on the local
side of the firewall will allow the NIDS to monitor traffic that the firewall has already
determined to be permissible, but not necessarily benign. This will, of course, not
catch traffic that the firewall has already blocked, potentially masquerading port
scans, probes and other types of attack.

Single Interface
The easiest configuration is a box with a single interface. The same interface that
listens to the network traffic is the same one from which administration is done.

B.Tech ( cse ) - secured file transfer protocol - 2004 42


This will be the typical configuration for home network users and administrators
monitoring internal networks.

Dual Interface
In a dual-interface configuration, one interface is used to listen to network traffic in
promiscuous mode while the other is used for remote administration. This type of
configuration is used in environments where it is not possible to administrate the box
from the same interface that is listening to the network traffic.

In this configuration, the external interface should be well protected and the box
designed explicitly for this purpose. The box should not be offering any network
services except for ssh on the internal interface only.

` Application Layer (Intrusion Detector Program)

TCP Layer UDP Layer

Ip layer

B.Tech ( cse ) - secured file transfer protocol - 2004 43


I/P Chain Formal Chain O/P Chain

Drop out

data
Data Link Layer

data
Physical Layer

IMPLEMENTATION

B.Tech ( cse ) - secured file transfer protocol - 2004 44


4.1 SOCKET SYSTEM CALLS

Socket Function:
The socket system call creates a socket on demand.
Int socket(int domain, int type, int protocol);
returns non-negative descriptor if OK, -1 on error
The domain parameter specifies the address family, the type parameter specifies the
type of communication to the used with the socket, and the protocol parameter
specifies the protocol to be employed.

Bind function:
The bind function assigns a local protocol address (name) to a socket, this
makes the socket available for use by other programs.
int bind(int sockfd, const struct sockaddr *address,socklen_t addrlen);
returns 0 if OK, -1 on error

B.Tech ( cse ) - secured file transfer protocol - 2004 45


The bind function assigns the address specified in the parameter address, to the
unnamed socket associated with the descriptor sockfd. The length of the address
structure is passed as addrlen.

listen Function:
This function is called by a server program, and has the following prototype.
int listen(int sockfd,int backlog);
returns 0 if OK, -1 on error
The listen function performs two actions:
When a socket is created by the socket function, it is assumed to be an active socket,
that is, a client socket that will issue a connect. The listen function converts an
unconnected socket into a passive socket, indicating that the kernal should accept
incoming connection requests directed to this socket.
The second argument to this function specifies the maximum number of connections
that the kernal should queue for this socket.

connect Function:
The connect function is used by a TCP client to establish a connection with a
TCP server.
int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);
returns 0 if OK, -1 on error
The function connects the socket specified by the parameter sockfd, to the server
socket specified by the parameter servaddr, which is of length addrlen.

accept Function:
The accept function is called by a TCP server to return the next completed
connection from the front of the connection queue.
int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);
returns non-negative descriptor if OK, -1 on error

B.Tech ( cse ) - secured file transfer protocol - 2004 46


The accept system call returns when a client program attempts to connect to the
server socket specified by the parameter sockfd. The client is the first pending
connection from that socket’s queue. The accept function creates a new socket to
communicate with that client and returns its descriptor. The new descriptor will have
the same type as the server listen type
The address of the calling client is placed in the sockaddr structure pointed to by
cliaddr. The parameter addrlen gives the length of the client structure. A null pointer is
used in the second argument if the client address is not required.
close Function:
The close function is used to close a socket and terminate a TCP connection.
int close(int sockfd);
returns 0 if OK, -1 on error
The analysis of sockets commands mainly helps to establish end-to-
end connectivity between client and server as the communication takes place over
the connection build across them. That is, a socket is an endpoint for communication
that can be named and addressed in a network. Two processes communicate via
TCP sockets. The socket model provides a process with a full-duplex byte stream
connection to another process. The application need not concern itself with the
management of this stream; these facilities are provided by TCP. Each side of TCP
connection has a socket that is identified by
<TCP ,IPaddress , portnumber >. If two processes are communicating over TCP, they
have a logical connection that is uniquely identifiable by the two socket involved.

B.Tech ( cse ) - secured file transfer protocol - 2004 47


4.2 CONNECTION ESTABLISHMENT

The typical scenario for a client/server interaction is as follows:


1. A server application creates a socket using the socket system call, which returns
an integer socket descriptor to identify the newly created socket.
2. Next, the server process gives the socket a name using the bind system call.
Local sockets are given a filename in the UNIX file system. For network sockets, it
will be a service identifier relevant to the particular network.

Server

Socket()

bind()

listen()

B.Tech ( cse ) - secured file transfer protocol - 2004 48


Well known port

Client
accept()
socket()
Blocks until connection from client
Connection established
connect()

Data (request)
write read()

Process request
Data (reply)
write()
read()

read()
close() EOF notification

close()

3. The server then waits for a client connection on the named socket. It calls the

listen system call to create a queue for incoming connections.

4. The server then calls the accept system call to accept client connections. On a

successful connection, accept returns a new socket, which is distinct from the

named socket. This new socket is used exclusively for communication with this

particular client. The named socket remains free for further connections from other

clients.

5. Once a connection is established with a client., the server processes the request

the request and sends back a reply to the client. This continues until the client

closes its end of the connection, which sends an end-of-file notification to the

server..

B.Tech ( cse ) - secured file transfer protocol - 2004 49


6. The server then closes its end of the connection and either terminates or waits for

a new client connection.

The FTP program is very basic – the user input to the FTP client are
directory manipulation commands and the file pathnames. The implementation
supports FTP commands: "list", “cd”, “copy”, “mkdir”, “rmdir” , “delete”, “transfer” ,
“exit”, and “help”.All the other FTP commands and options are not included in the
program because these additional commands are not really necessary for the task of
transferring files from one system to another.
Since the protocol implementation should support multiple users
simultaneously, the FTP server implemented is a concurrent server. The server is
started as a background process, it for connection requests ( on a fixed port )from
clients, and forks to create child processes as described in multipl server session.
These child processes handle individual clients and terminate after servicing the
clients.
The client implementation is fairly simple: the client program first establishes
a control connection with the server, and passes the file manipulation and file transfer
commands along with any parameters to the server over this connection. Each
command is sent as a message - a text string, to the server. The server processes
these commands and passes the results back to the client via the same control
connection. The next command is then read at the command prompt ‘FTP>’ & sent to
the server and the process continues. The session can be terminated by invoking
the exit command which closes the client side socket and breaks the connection.
Sockfd=if((socket(AF_INET,SOCK_STREAM,0))<0)/* opens a tcp socket */
Printf(“can’t open stream socket”);
/*fill the structure serv_addr with address of server*/
bzero((char *)&serv_addr,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(SERV_HOST_ADDR);
serv_addr.sin_port=htons(SERV_TCP_PORT);
/* connect to server*/

B.Tech ( cse ) - secured file transfer protocol - 2004 50


if(connect(sockfd,struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
printf(“error connecting to server”);
str_cli(stdin,sockfd);
close(sockfd);
exit(0);

The server implementation is as follows: when the server receives a request for
connection, it executes the accept system call, which returns a new socket descriptor
to the server. This new distinct socket is used to communicate with client. The server
then forks, and a new child, which also inherits the parents’ socket descriptor, is
created. Next, the parent and the child close the connected socket and the listening
socket ( named server socket ) respectively, and function independent of each other.
Sockfd=if((socket(AF_INET,SOCK_STREAM,0))<0)/* opens a tcp socket */
Printf(“can’t open stream socket”);
/*bind our local address so client can send us*/
bzero((char *)&serv_addr,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);;
serv_addr.sin_port=htons(SERV_TCP_PORT);
if(bind(sockfd,struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
printf(“can’t bind local address”);
listen(sockfd,5);
for( ; ;)
{
clilen=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr*) & cli_addr,&cli_len);
if(newsockfd<0)
printf(”accept error”);
if((childpid==fork())<0)
printf(“fork error”);
else if(childpid==0)

B.Tech ( cse ) - secured file transfer protocol - 2004 51


{
close(sockfd);
str_echo(newsockfd);
exit(0);
}
close(newockfd);
}
The command passed to the server is placed in a buffer using a read system
call, where it is broken up into the command and the parameter/s (if any) to that
function.
The commands are implemented using UNIX File API’s. some of the
general API’s that help in directory and file manipulations are as follows:
read:
the read function fetches a fixed block of data from a file referenced by a given
file descriptor.
Ssize_t read(int fdesc, void * buf, size_t size);
Fdesc is an integer value holding the file descriptor that refers to the open file. The
second argument, buf is the address of a buffer holding any data read. The third
argument specifies how many bytes of data are to be read from the file.
Write :
the write function puts a fixed size block of data to a file referenced by a
given file descriptor
Ssize_t write(int fdesc,const void* buf, size_t size);
Buf points to the buffer which contains the data to be written to the file. Size
specifies how many bytes are there in the buf argument.
Close:
the close function disconnects a file from a process.
Int close(int fdesc);
Stat, fstat:

B.Tech ( cse ) - secured file transfer protocol - 2004 52


these functions retrieve the file attributes like user ID, file size in bytes of a
given file. The difference between the two is the first argument to stat is a file path
name, whereas to fstat it is a file descriptor.
Int stat(const char * path_name, struct stat* statv);
Int fstat(const int fdesc, struct stat* statv);
Opendir:
opens a directory file for readonly . returns a file handler DIR* for further
reference to that file.
DIR* opendir(const char* path_name);
Readdir:
reads a record from a directory file referenced by dir_desc & returns record
information
Dirent * readdir(DIR* dir_desc);
Closedir:
closes a directory file referenced by dir_desc.
Int closedir(DIR* dir_desc);

4.3 COMMAND IMPLEMENTATION


status:
To know the current status of server.
system("ps>abc.txt");
fd=open("abc.txt",O_RDONLY);
n=read(fd,buf3,sizeof(buf3));
write(nd,buf3,n);
rmpwd:
To know the current working directory.
getcwd(buf3,sizeof(buf3));
write(nd,buf3,sizeof(buf3));
rmls:

B.Tech ( cse ) - secured file transfer protocol - 2004 53


To list files in current working directory of remote machine.
getcwd(buf1,sizeof(buf1));
dir=opendir(buf1);
read1=readdir(dir);
read1=readdir(dir);
while((read1=readdir(dir))!=NULL)
{
strcpy(buf2,read1->d_name);
write(nd,buf2,sizeof(buf2));
}
delete:
To delete a file on remote machine.
if(strcmp(buf2,s)==0)
{
unlink(s);
write(nd,"file delete successfully",40);
flag=1;
}

File Transfer Processing:


getfile:
The user at the client-side enters the command getfile<filename> at the MYFTP>
prompt.
This is read into a buffer and sent to the server for processing using a write API.
At the server side, the command line is broken up into
getfile &<filename>
If the file exists, it ‘s contents are read in to buffer and this text is sent over
the connection to the client which requested the service using a write API.
At the client side, a new file is created in the present working directory with the name
specified.
The data received from the server is stored in the new file.

B.Tech ( cse ) - secured file transfer protocol - 2004 54


Client code:
memset(buf,0,sizeof(buf));
n=read(sd,buf,sizeof(buf));
write(sd,"rao",3);
if(strcmp(buf,"completed")==0)
break;
write(fd,buf,n);

Server code:
fd=open(buf2,O_RDONLY);
do {
n=read(fd,buf6,sizeof(buf6));
write(nd,buf6,n);
if(read(fd,ch,1)==NULL)
break;
read(nd,buf,sizeof(buf));
}while(1);
n=read(fd,buf6,sizeof(buf6));
write(nd,"completed",9);
putfile:
The user at the client-side enters the command putfile<filename> at the
MYFTP> prompt.
If the file exists, it ‘s contents are read in to buffer and this text is sent over
the connection to the server using a write API.
At the server side, a new file is created in the present working directory with the
name specified.
The data received from the server is stored in the new file.

Client code :
read(sd,bu0,sizeof(sd));
nd=read(fd,buf2,sizeof(buf2));

B.Tech ( cse ) - secured file transfer protocol - 2004 55


write(sd,buf2,nd);
if(read(fd , ch ,1)==NULL)
break;
Server code:
do {
memset(buf2,0,sizeof(buf2));
write(nd,"rao",4);
as = read(nd,buf2,sizeof(buf2));
as = write(myfd1,buf2,as);
if(strcmp(buf2,"completed")==0)
break;
} while(1);

4.4 PCAP
Nids is implemented using pcap library.
The structure of pcap.h header is as follows:
#ifndef lib_pcap_h
#define lib_pcap_h
#include <sys/types.h>
#include <sys/time.h>
#include <net/bpf.h>
#include <stdio.h>
#define PCAP_VERSION_MAJOR 2
#define PCAP_VERSION_MINOR 4
#define PCAP_ERRBUF_SIZE 256

B.Tech ( cse ) - secured file transfer protocol - 2004 56


#if BPF_RELEASE - 0 < 199406
typedef int bpf_int32;
typedef u_int bpf_u_int32;
#endif
typedef struct pcap pcap_t;
typedef struct pcap_dumper pcap_dumper_t;
/*
* The first record in the file contains saved values for some
* of the flags used in the printout phases of tcpdump.
* Many fields here are 32 bit ints so compilers won't insert unwanted
* padding; these files need to be interchangeable across architectures.
*/
struct pcap_file_header {
bpf_u_int32 magic;
u_short version_major;
u_short version_minor;
bpf_int32 thiszone; /* gmt to local correction */
bpf_u_int32 sigfigs; /* accuracy of timestamps */
bpf_u_int32 snaplen; /* max length saved portion of each pkt */
bpf_u_int32 linktype; /* data link type (DLT_*) */
};
/*
* Each packet in the dump file is prepended with this generic header.
* This gets around the problem of different headers for different
* packet interfaces.
*/
struct pcap_pkthdr {
struct timeval ts; /* time stamp */
bpf_u_int32 caplen; /* length of portion present */
bpf_u_int32 len; /* length this packet (off wire) */
};

B.Tech ( cse ) - secured file transfer protocol - 2004 57


/*
* As returned by the pcap_stats()
*/
struct pcap_stat {
u_int ps_recv; /* number of packets received */
u_int ps_drop; /* number of packets dropped */
u_int ps_ifdrop; /* drops by interface XXX not yet supported */
};

typedef void (*pcap_handler)(u_char *,const struct pcap_pkthdr *,const u_char *);

char *pcap_lookupdev(char *);


int pcap_lookupnet(char *, bpf_u_int32 *, bpf_u_int32 *, char *);
pcap_t *pcap_open_live(char *, int, int, int, char *);
pcap_t *pcap_open_offline(const char *, char *);
void pcap_close(pcap_t *);
int pcap_loop(pcap_t *, int, pcap_handler, u_char *);
int pcap_dispatch(pcap_t *, int, pcap_handler, u_char *);
const u_char* pcap_next(pcap_t *, struct pcap_pkthdr *);
int pcap_stats(pcap_t *, struct pcap_stat *);
int pcap_setfilter(pcap_t *, struct bpf_program *);
void pcap_perror(pcap_t *, char *);
char *pcap_strerror(int);
char *pcap_geterr(pcap_t *);
int pcap_compile(pcap_t *, struct bpf_program *, char *, int bpf_u_int32);

/* XXX */
int pcap_freecode(pcap_t *, struct bpf_program *);
int pcap_datalink(pcap_t *);
int pcap_snapshot(pcap_t *);
int pcap_is_swapped(pcap_t *);

B.Tech ( cse ) - secured file transfer protocol - 2004 58


int pcap_major_version(pcap_t *);
int pcap_minor_version(pcap_t *);

/* XXX */
FILE *pcap_file(pcap_t *);
int pcap_fileno(pcap_t *);

pcap_dumper_t *pcap_dump_open(pcap_t *, const char *);


void pcap_dump_close(pcap_dumper_t *);
void pcap_dump(u_char *, const struct pcap_pkthdr *, const u_char *);

/* XXX this guy lives in the bpf tree */


u_int bpf_filter(struct bpf_insn *, u_char *, u_int, u_int);
char *bpf_image(struct bpf_insn *, int);
#endif

4.4.1 pcap - Packet Capture library


#include <pcap.h> /* Defined Above */
pcap_t *pcap_open_live(char *device, int snaplen,
int promisc, int to_ms, char *ebuf)
pcap_t *pcap_open_offline(char *fname, char *ebuf)
pcap_dumper_t *pcap_dump_open(pcap_t *p, char *fname)
char errbuf[PCAP_ERRBUF_SIZE];
char *pcap_lookupdev(char *errbuf)
int pcap_lookupnet(char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
char *errbuf)
int pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)

B.Tech ( cse ) - secured file transfer protocol - 2004 59


void pcap_dump(u_char *user, struct pcap_pkthdr *h, u_char *sp)
int pcap_compile(pcap_t *p, struct bpf_program *fp,char *str, int optimize,
bpf_u_int32 netmask)
int pcap_setfilter(pcap_t *p, struct bpf_program *fp)
u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h)
int pcap_datalink(pcap_t *p)
int pcap_snapshot(pcap_t *p)
int pcap_is_swapped(pcap_t *p)
int pcap_major_version(pcap_t *p)
int pcap_minor_version(pcap_t *p)
int pcap_stats(pcap_t *p, struct pcap_stat *ps)
FILE *pcap_file(pcap_t *p)
int pcap_fileno(pcap_t *p)
void pcap_perror(pcap_t *p, char *prefix)
char *pcap_geterr(pcap_t *p)
char *pcap_strerror(int error)
void pcap_close(pcap_t *p)
void pcap_dump_close(pcap_dumper_t *p)

4.4.2 ROUTINES DESCRIPTION:


The Packet Capture library provides a high level interface to packet capture
systems. All packets on the network, even those destined for other hosts, are
accessible through this mechanism.
pcap_open_live() is used to obtain a packet capture descriptor to look at
packets on the network. device is a string that specifies the network device to open.
Snaplen specifies the maximum number of bytes to capture. promisc specifies if the
interface is to be put into promiscuous mode. (Note that even if this parameter is
false, the interface could well be in promiscuous mode for some other reason.)
to_ms specifies the read timeout in milliseconds. ebuf is used to return error text
and is only set when pcap_open_live() fails and returns NULL.

B.Tech ( cse ) - secured file transfer protocol - 2004 60


pcap_open_offline() is called to open a ``savefile'' for reading. fname specifies
the name of the file to open. The file has the same format as those used by
tcpdump(1) and tcpslice(1). The name "-" in a synonym for stdin. ebuf is used
to return error text and is only set when pcap_open_offline() fails and returns NULL.
pcap_dump_open() is called to open a``savefile'' for writing. The name "-" in
a synonym for stdout. NULL is returned on failure. p is a pcap struct as returned
by pcap_open_offline() or pcap_open_live(). fname specifies the name of the file to
open. If NULL is returned, pcap_geterr() can be used to get the error text.
pcap_lookupdev() returns a pointer to a network device suitable for use
with pcap_open_live() and pcap_lookupnet(). If there is an error, NULL is
returned and errbuf is filled in with with an appropriate error message.
pcap_lookupnet() is used to determine the network number and mask
associated with the network device device. Both netp and maskp are bpf_u_int32
pointers. A return of -1 indicates an error in which case errbuf is filled in with an
appropriate error message.
pcap_dispatch() is used to collect and process packets.cnt specifies the
maximum number of packets to process before returning. A cnt of -1 processes all
the packets received in one buffer. A cnt of 0 processes all packets until an error
occurs, EOF is reached, or the read times out (when doing live reads and a non-
zero read timeout is specified). callback specifies a routine to be called with three
arguments: a u_char pointer which is passed in from pcap_dispatch(), a pointer to the
pcap_pkthdr struct (which precede the actual network headers and data), and a
u_char pointer to the packet data. The number of packets read is returned. Zero is
returned when EOF is reached in a ``savefile.'' A return of -1 indicates an error in
which case pcap_perror() or pcap_geterr() may be used to display the error text.
pcap_dump() outputs a packet to the ``savefile'' opened with
pcap_dump_open(). Note that its calling arguments are suitable for use with
pcap_dispatch().
pcap_compile() is used to compile the string str into a filter program.
program is a pointer to a bpf_program struct and is filled in by pcap_compile().

B.Tech ( cse ) - secured file transfer protocol - 2004 61


optimize controls whether optimization on the resulting code is performed. netmask
specifies the netmask of the local net.
pcap_setfilter() is used to specify a filter program. fp is a pointer to an array
of bpf_program struct, usually the result of a call to pcap_compile(). -1 is returned on
failure; 0 is returned on success.
pcap_loop() is similar to pcap_dispatch() except it keeps reading packets until
cnt packets are processed or an error occurs. It does not return when live read
timeouts occur. Rather, specifying a non-zero read timeout to
pcap_open_live() and then calling pcap_dispatch() allows the reception and
processing of any packets that arrive when the timeout occurs. A negative cnt
causes pcap_loop() to loop forever (or at least until an error occurs).
pcap_next() returns a u_char pointer to the next packet.
pcap_datalink() returns the link layer type, e.g. DLT_EN10MB.
pcap_snapshot() returns the snapshot length specified when
pcap_open_live was called.
pcap_is_swapped() returns true if the current ``savefile'' uses a different byte
order than the current system.
pcap_major_version() returns the major number of the version of the pcap
used to write the savefile.
pcap_minor_version() returns the minor number of the version of the pcap
used to write the savefile.
pcap_file() returns the name of the ``savefile.''
int pcap_stats() returns 0 and fills in a pcap_stat struct. The values
represent packet statistics from the start of the run to the time of the call. If there is
an error or the under lying packet capture doesn't support packet statistics, -1 is
returned and the error text can be obtained with pcap_perror() or pcap_geterr().
pcap_fileno() returns the file descriptor number of the ``savefile.''
pcap_perror() prints the text of the last pcap library error on stderr, prefixed by
prefix.
pcap_geterr() returns the error text pertaining to the last pcap library error.
pcap_strerror() is provided in case strerror(1) isn't available.

B.Tech ( cse ) - secured file transfer protocol - 2004 62


pcap_close() closes the files associated with p and deallocates resources.
pcap_dump_close() closes the ``savefile.''

4.5 TESTING
Testing techniques :

Testing is a process of executing a program with the intent of finding an error .


Any engineered product can be tested in one of the two ways :
1. Knowing the specified function that a product has been designed to
perform,tests can be conducted that demonstrate each function fully
operational while at the same time searching for errors in each function . this
approach is called black box testing.

B.Tech ( cse ) - secured file transfer protocol - 2004 63


2. Knowing the internal workings of the product,tests can be conducted to
ensure that “all gears mesh”, that is, internal operations are performed
according to specification and all internal components have been adequately
exercised. This approach is called white-box testing.

4.5.1 WHITE-BOX TESTING:

Flow graph notation:

Simple notation for the representation of control flow called a flow graph .

sequence

if

while

1. represents the state for comparing with no of input files to be transferred.


2. opens a file for reading and reads contents of a file in to buffer.

B.Tech ( cse ) - secured file transfer protocol - 2004 64


3. checks whether the read character is null.
4. if the character is null it breaks the loop
Flow graph for mputfile

3
4 5

5.if the character is not null it continues.


6.writes contents of a buffer in to a buffer on server side.
7.checks wether it has reched end of file.

Cyclomatic complexity
path1: 1-8
path2: 1-2-3-5-1-8
path3: 1-2-4-6-7-2-3-5-1-8

B.Tech ( cse ) - secured file transfer protocol - 2004 65


cyclocmatic complexity, V(G) for a flow graph, G, is defined as
v(G) = E-N+2
= 9-8+2
=3
path1:
condition: if no arument is present.
result: it closes opened file and no data is written in the server
Path2:
Condition: If argument is present and no data is present in the file.
Result: a file is created on the server side and no data is written to it
Path 3:
Condition: if arguments are present and data is present in the file
Result: a file is created on the server side and data is written in to it.

Condition testing
Condition testing is a test case design method that exercises the logical
conditions contained in a program module.
In our program we performed condition testing for checking whether given file is
present

if(strcmp(read1->d_name,arg_table[1])==0)

reads the contents of a directory anc compare with the input file.
Thus we check for the condition whether given file is present or not.
Loop Testing :
Loop testing is a white box testing technique that focues exclusively on the
validity of loop constructs. Four different classes of loops can be defined:
Simple loops, concatenated loops,nested loops and unstructured loops.
In our programs we have used mostly concatenated loops and nested loops
Nested loops:

B.Tech ( cse ) - secured file transfer protocol - 2004 66


for(i=0;i<arg_num;i++)
{
do
{ ------
-----------
}while(!feof(fp));

the inner loop will execute for arg_num times for every iteration of for loop.
While loop will execute end of file.
Termination conditions:
Inner loop terminate when i=arg_num
While loop terminate at two conditions.
a) end of file is reached .
b) empty file is read.

B.Tech ( cse ) - secured file transfer protocol - 2004 67


RESULTS

SERVER HANDLING MULTIPLE CLIENTS

B.Tech ( cse ) - secured file transfer protocol - 2004 68


TRANSFERING A NONVIRUSFILE

B.Tech ( cse ) - secured file transfer protocol - 2004 69


TRANSFERING A VIRUS FILE

B.Tech ( cse ) - secured file transfer protocol - 2004 70


B.Tech ( cse ) - secured file transfer protocol - 2004 71
CONCLUSION

• The utilityhas been tested for multiple file trasfer vetween two systems running
on Linux.
• It has been tested transferring a virus file and report was generated
succesfully.

B.Tech ( cse ) - secured file transfer protocol - 2004 72


• The performance of utility is found satisfactory.
• The connection mechanism used is TCP hence the communication is reliable.

LIMITATIONS
• It is diffcult for a nontechnical user to work.
• Nids alone could not stop transfering of virus packets.
• Signature of the virus should be known in advance.

FUTURE SCOPE

The present utility still needs some enhancements to be made for more global usage.
The following updations are to be implemented in future

• Remote Login facility.


• Graphical User Interface that provides easy understahding and usage of this
application.
• It can be upgraded between systems that run on windows and Linux.

REFERENCES

1.UNIX NETWORK PROGRAMMING(VOLUME I,II EDITION)


♣W.RICHARD STEVENS,PHIE
2.COMPUTER NETWORKS(III EDITION)

B.Tech ( cse ) - secured file transfer protocol - 2004 73


♣ANDREW TENENBAUM,PHIE
3.UNIX SYSTEM PROGRAMMING
♣KEITH HAVILAND
4.TCP ILLUSTRATION(VOLUME II)
♣GRAY R WRIGHT
♣W.RICHARD STEVEN,AWPE
5.INTERNETWORKING WITH TCP/IP(VOLUME II)
♣DOUGLAS E COMER
♣DAVID L STEVENS,PHIE

www.w3.org/protocols/rfc959/overview.html

http://searchnetworking.techtarget.coms

B.Tech ( cse ) - secured file transfer protocol - 2004 74

Anda mungkin juga menyukai