Вы находитесь на странице: 1из 33

Project Report on Implementation of Firewall on Linux Platform

1
Project Report on Implementation of Firewall on Linux Platform

LAN AND INTERNET

Extension of LAN to Internet


Before Networks were introduced, two or more computers could
communicate only through the manual exchange of data using
magnetic tapes, disks or card readers. Each computer had a
limited degree of productivity as it had to be equipped with its
own set of resources. Resource sharing was not possible. This
gave rise to Local Area Networks.
A Local Area Network is a group of computers either connected
to each other or to a central computer, all of which are in close
proximity to each other. LAN provided the advantages of
Resource sharing, Reliability and powerful communication
medium. Sharing of both hardware and software resources was
made possible in a network.
As business organizations ventured into new horizons there was a
need for people to communicate over larger distances. This was
not feasible with LAN's as it simply connected computers within
room, building or campus. Hence LAN extended itself to WAN.
WAN is a group of computers connected to each other or to a
central computer,all of which are not in close proximity to each
other. WAN is a network of computers connected across various
cities. Soon even this was found to be a shortcoming. Finally WAN
extended itself into Internet! ,which is simply a network of
networks.
Security in LAN
Security policy implemented in LAN was relatively simple.All that
was required was to station a guard at the door to the computer
room who made sure that there was no tampering of magnetic
tapes, disks or card readers by an unauthorised person. This
policy could not be extended to the internet, As it was not
possible to monitor the millions of data exchange that took place
across the various networks in the internet. Furthermore it was
beyond scope to insert physical security checkpoints across the
internet.
Internet and its Growth
The internet in its broadest possible terms is the network of
millions of computers, all of which link together through common
standards and protocols. The internet includes a large number of
LAN's, WAN's and routers. The united states government's

2
Project Report on Implementation of Firewall on Linux Platform

ARPANet(Advanced Research Project Agency ) is the internet's


predecessor.
In a LAN , each user connected to the LAN has a desktop or
laptop computer. Each user's computer has a network card that is
connected to one or more network servers by means of wires and
electronic equipment. In addition there are WAN's which connect
a large number of LAN's together.In addition to this the internet
also links millions of individual users who access the internet
through dial-up accounts with the scores of different Internet
service providers.
Internet is a PACKET SWITCHED NETWORK, that is packet
switching is the means of communication across the internet.
TCP/IP(transport control protocol / internet protocol) is the
protocol that is used for transmissions across the internet. It can
successfully switch packets from computer systems on any
network to another network, regardless of incidental network
pecularities, operating system differences and other packet
differences.It remains the backbone of the internet.

In the past ten years , the internet's growth has exploded.In 1985
the internet included only 1961 host computers . The growth of
internet has been phenomenal and by 1999 there has been
nearly 300,000 computers.The internet has continued to grow at
exponential rates.
More important than the increase in the number of hosts
connected to the internet is the increase in the number of
internet users. The internet has essentially doubled in size. Today
the number of internet users increases at a rate of nearly
200,000 new logins each month.

Security in Internet

November 2nd, 1988 is the most infamous date in the internet


history. It also recalls one of the Internet's finest hours. It was on
this day Network worm hit the internet. It was the first significant
virus ever to hit the internet.The virus was called Morris Worm
and nearly affected 4000 to 6000 machines. Fortunately it
represented only 5% of the total internet site.
Prior to this Internet was considered safe. Computers had caught
viruses before but they were due to infected diskettes and all
that was required was to reformat the hard drive. The Morris
worm however was the first networking worm that brought down

3
Project Report on Implementation of Firewall on Linux Platform

many of the world's leading Unix-based computer installations.


Though the Morris worm caused little damage, it nevertheless
ushered in a new significant era of security consciousness as it
revealed the internet's vulnerability. It gave rise to a new era of
"Cyber - terrorism".
Corporate losses due to computer security were also on the rise.
A survey showed that there was a significant increase in the
number of intrusions and data corruptions and also in the number
of companies that percieved the internet as a source of danger.
Packet switching is the root of many transmission security
problems. In packet switching the network server forwards the
packet in the wire that is immediately available. In LAN this may
not be problem but in case of internet it is possible for a packet
sent from home computer to the computer in the office to travel
through the server of the company's major competitor who
simply destroy the essential data.

The main danger to the internet security comes in the form of


HACKERS!. A Hacker simply refers to anyone who would break
into the computer security to steal or corrupt data,joy-riding,as
an ethical hacker.
Hackers are classified into the following categories in increasing
threat order.
• Security Experts
• Students
• Underemployed Adults
• Criminal Hackers
• Corporate spies
• Disgruntled Employees

Security Experts :
Most security experts are capable of hacking,but decline
from doing so for moral or economic reasons.Computer
security experts have found that there's more money in
preventing hacking than in perpetrating it.A number of large
internet service companies employ ethical hackers to test
their security systems.

Student Hackers :
These hackers belong to junior high, high school or college.
Their social position is Student. They usually perform joy-
riding through cyberspace looking for targets of opportunity

4
Project Report on Implementation of Firewall on Linux Platform

and concerned mostly with impressing their peers and not


getting caught .Their motivation is not to harm. They
generally hack for free internet stuff.

Underemployed Adult Hackers:


These are hackers who have either dropped out of school
or who have failed to achieve full time employment and
family commitments for some reason or other. They often
create the "crackz" to unlock other commercial software.
They also write majority of the software viruses.
They hack for notoriety,to impress their peers with exploits
and information they have obtained.

Criminal Hackers :
They hack for revenge or to perpetrate theft.These are the
persons who compromise internet servers to steal credit
card numbers or hack the internet banking mechanism to
steal money. They regarded as real criminals
Spies:
These are hackers employed by Foreign Governments
against high technology businesses. Many high technology
businesses are naïve about security, making them easy
targets for the experienced intelligence agencies of foreign
governments.
The main purpose is to extract technology that give their
own corporations an edge.

Disgruntled Employees:
They pose the most dangerous threat.They are the most
difficult to detect. An employee who is constantly picked by
an employer may become an hacker. As he is aware of the
security details in the company.
Hacking stages can be classified into the following areas:
• Eavesdropping and snooping
• Denial-of-service
• Impersonation
• Man-in-the-middle
• Hijacking

Eavesdropping and snooping:


The simplest thing a hacker can do to gain information is simply
to listen and ask the network computers information about

5
Project Report on Implementation of Firewall on Linux Platform

themselves. The hacker can communicate with other computers


that provide services to the computers to be hacked. Networked
computers volunteer a remarkable amount of information about
themselves and how they are configured especially if left in
default.
Common hacking practices include :
Password capture:
Many networking protocols do not encrypt
passwords,allowing any computer on the path between
the client and the server to "overhear" the username and
password. Not all encrypted logon procedures are safe
from eavesdropping either,because a hacker can record
the username and encrypted password to send to the
server later in a "reply attack".
Eavesdropping requires software that will listen to all the
communication that flow over the network medium.It must also
have access to a computer that is situated on a network link with
network traffic over it.
Network traffic analysis:
The hacker can obtain quite a bit of information about the
network from the nature the nature of the traffic in and out
of your network. The hacker looks for the IP addresses of the
source and destination computers.The locations of gateways
and routers.The amount of traffic originating from,being sent
to,or flowing through is identified by the Hacker.
Network Address scanning :
In this the Hacker specifies the beginning and ending
address to scan,and then the hacker's computer program
will attempt to establish a connection to a computer on each
of those network addresses in turn.If a computer answers
from any of those addresses then the Hacker has found a
target which he can hack.
Port scanning:
Once a hacker has identified a target computer,the hacker
attempts to determine the type of operating system and
what services are provided. In at TCP/IP based Network,
services are provided on numbered connections called
sockets. These are used by the hacker to determine what
operating system is running and what services are offered.
For eg:by scanning the TCP ports between 0 and 150, a
Hacker can discern windows hosts by the presence of port
139 in the scan list.

6
Project Report on Implementation of Firewall on Linux Platform

Denial of Service:
The next thing a hacker can do is to disable some aspect of
the network or to bring the network down. Methods hacker
can use to disable computer services are:
Ping of Death: In this a specially constructed ICMP packet
that violates the construction rules is sent by the hacker to
crash the computer if the computer's networking software
does not check for invalid ICMP packets.
SYN Attacks and ICMP flooding : This is another method
used by the Hackers.The initial IP packet of a TCP
Connection attempt is simple and easy to generate and
responding to this takes more time and memory space as
the receiving computer must record information about the
new connection. The Hacker can send one SYN packet after
another to the target computer and then the target
computer will be unable to process legitimate connection
attempts as its memory and time is wasted processing SYN
requests.
In ICMP flooding ,the Hacker sends a constant stream of
ICMP echo requests to the target computer.The target
computer then spends most of its time responding to the
echo requests instead of processing legitimate network
traffic.
Impersonation:
This is the next step the Hacker takes. By impersonating
another computer that the computers on a given network
trust, the hacker's computer may be able to trick the
computers in revealing enough information for the hacker
to get into the security. The tactic that a hacker uses is :
Source routed Attacks: Source routing is the route the
packet takes as it crosses the TCP/IP based network.This
makes it possible for the hacker to send data from one
computer and make it look like it comes from a trusted
source.The Hacker can use source routing to impersonate
an already connected user and inject additional information
into an otherwise benign communication between server
and authorised client computer.
Man -in - the -Middle:
This is a special case of impersonation, where the hacker
operates between two computers on a network. When the
client computer opens a connection to the server

7
Project Report on Implementation of Firewall on Linux Platform

computer,the hacker's computer intercepts it. The hacker


computer opens a connection on behalf of the client
computer to the server computer. Ideally the client thinks
he is communicating with the server,server thinks he is
communicating with the client and the hacker computer will
be able to observe all the communications between them.
For example,if the connection is an administrator-level
Telnet session into a server computer from a client
computer,the hacker computer in the middle could
download the password file from the server to the hacker
computer instead of uploading HTML pages as required.
Hijacking:
Another hacker trick is to hijack an already established and
authenticated networking connection.This mainly occurs at
the TCP connection layer.In order to hijack an existing TCP
connection,a hacker must be able to predict TCP sequence
numbers,which the two communicating computers use to
keep IP packets in order and to ensure that they arrive at
the destination.The hacker also redirects the TCP/IP
connection to the hacker computer and also launches a
denial-of-service attack on the client computer.

8
Project Report on Implementation of Firewall on Linux Platform

IPCHAINS USING C

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/icmp.h>
#include <linux/if.h>
#include <linux/ip_fwchains.h>
int setsockopt (int socket, IPPROTO_IP, int command, void
*data, int length)
DESCRIPTION
The IP firewall facilities in the Linux kernel provide mechanisms
for accounting IP packets, for building firewalls based on packet-
level filtering, for building firewalls using transparent proxy
servers (by redirecting packets to local sockets), and for
masquerading forwarded packets. The administration of these
functions is maintained in the kernel as a series of separated
table (hereafter referred to as chains) each containing zero or
more rules. There are three builtin chains which are called input,
forward and output which always exist. All other chains are user
defined. A chain is a sequence of rules; each rule contains
specific information about source and destination addresses,
protocols, port numbers, and some other characteristics.
Information about what to do if a packet matches the rule is also
contained. A packet will match with a rule when the
characteristics of the rule match those of the IP packet.
A packet always traverses a chain starting at rule number 1. Each
rule specifies what to do when a packet matches. If a packet does
not match a rule, the next rule in that chain is tried. If the end of
a builtin chain is reached the a default policy for that chain is
returned. If the end of a user defined chain is reached then the
rule after the rule which branched to that chain is tried. The
purpose of the three builtin chains are
Input firewall

9
Project Report on Implementation of Firewall on Linux Platform

These rules regulate the acceptance of incoming IP packets.


All packets coming in via one of the local network interfaces
are checked against the input firewall rules (locally-
generate packets are considered to come from the loopback
interface). A rule which matches a packet will cause the
rule's packet and byte counters to be incremented
appropriately.
Forwarding firewall
These rules define the permissions for forwarding IP
packets. All packets sent by a remote host having another
remote host as destination are checked against the
forwarding firewall rules. A rule which matches will cause
the rule's packet and byte counters to be incremented
appropriately.
Output firewall
These rules define the permissions for sending IP packets.
All packets that are ready to be be sent via one of the local
network interfaces are checked against the output firewall
rules. A rule which matches will cause the rule's packet and
byte counters to be incremented appropriately.
Each of the firewall rules contains either a branch name or a
policy, which specifies what action has to be taken when a packet
matches with the rule. There are 5 different policies possible:
ACCEPT (let the packet pass the firewall), REJECT (do not accept
the packet and send an ICMP host unreachable message back to
the sender as notification), DENY (sometimes referred to as
block) (ignore the packet without sending any notification),
REDIRECT (redirected to a local socket - input rules only) and
MASQ (pass the packet, but perform IP masquerading -
forwarding rules only)
The last two are special; for REDIRECT, the packet will be
received by a local process, even if it was sent to another host
and/or another port number. This function only applies to TCP or
UDP packets.
For MASQ, the sender address in the IP packets is replaced by the
address of the local host and the source port in the TCP or UDP
header is replaced by a locally generated (temporary) port
number before being forwarded. Because this administration is
kept in the kernel, reverse packets (sent to the temporary port
number on the local host) are recognized automatically. The
destination address and port number of these packets will be

10
Project Report on Implementation of Firewall on Linux Platform

replaced by the original address and port number that was saved
when the first packet was masqueraded. This function only
applies to TCP or UDP packets.
There is also a special target RETURN which is equivalent to
falling off the end of the chain.
This paragraph describes the way a packet goes through the
firewall. Packets received via one of the local network interface
will pass the following chains:
input firewall (incoming device) Here, the device (network
interface) that is used when trying to match a rule with an
IP packet is listed between brackets. After this step, a
packet will optionally be redirected to a local socket. When
a packet has to be forwarded to a remote host, it will also
pass the next set of rules: forwarding firewall (outgoing
device) After this step, a packet will optionally be
masqueraded. Responses to masqueraded packets will
never pass the forwarding firewall (but they will pass both
the input and output firewalls). All packets sent via one of
the local network interfaces, either locally generated or
being forwarded, will pass the following sets of rules: output
firewall (outgoing device)
When a packet enters one of the three above chains rules are
traversed from the first rule in order. When analysing a rule one
of three things may occur.
Rule unmatched:
If a rules is unmatched then the next rule in that chain is
analysed. If there are no more rules for that chain the
default policy for that chain is returned (or traversal
continues back at the calling chain, in the case of a user-
defined chain).
Rule matched (with branch to chain):
When a rule is matched by a packet and the rule contains a
branch field then a jump/branch to that chain is made.
Jumps can only be made to user defined chains. As
described above, when the end of a builtin chain is reached
then a default policy is returned. If the end of a used
defined chain is reached then we return to the rule from
whence we came.

11
Project Report on Implementation of Firewall on Linux Platform

There is a reference counter at the head of each chain


which determines the number of references to that chain.
The reference count of a chain must be zero before it can
be deleted to ensure that no branches are effected. To
ensure the builtin chains are never deleted their reference
count is initialised to one. Also since no branches to builtin
chains can be made, their reference counts are always one.
The reference count on user defined chains are initialised to
zero and are changed accordingly when rules are inserted,
deleted etc.
Multiple jumps to different chains are possible which
unfortunately make loops possible. Loop detection is
therefore provided. Loops are detected when a packet tries
to re-enter a chain it is already traversing. An example of a
simple loop that could be created is if we set up two user
defined chains called "test1" and "test2". We firstly insert a
rule in the "input" chain which jumps to "test1". We then
create a rule in the "test1" chain which points to "test2" and
a rule in "test2" which points to "test1". Here we have
obviously created a loop. When a packet then enters the
input chain it will branch to the "test1" chain and then to
the "test2" chain. From here it will try to branch back to the
"test1" chain. A message in the syslog will be recorded
along with the path which the packet traversed, to assist in
debugging firewall rules.
Rule matched (special branch):
The special labels ACCEPT, DENY, REJECT, REDIRECT, MASQ
or RETURN can be given which specify the immediate fate
of the packet as discussed above. If no of labels is specified
then the next rule in the chain is analysed.
Using this last option (no label) an accounting chain can be
created. If each of the rules in this accounting chain have no
branch or label then the packet will always fall through to
the end of the chain and then return to the calling chain.
Each rule that matches in the accounting chain will have its
byte and packet counters incremented as expected. This
accounting chain can be branched to from any other chain
(eg input, forward or output chain). This is a very neat way
of performing packet accounting.

12
Project Report on Implementation of Firewall on Linux Platform

The firewall administration can be changed via calls to


setsockopt(2). The existing rules can be inspected by looking at 2
files in the /proc/net directory: ip_fwchains, ip_fwnames. These
two files are readable only by root. The current administration
related to masqueraded sessions can be found in the file
ip_masquerade in the same directory
COMMANDS
Command for changing and setting up chains and rules is
ipchains(8) Most commands require some additional data to be
passed. A pointer to this data and the length of the data are
passed as option value and option length arguments to
setsockopt. The following commands are available:
IP_FW_INSERT
This command allows a rule to be inserted in a chain at a
given position (where 1 is considered the start of the chain).
If there is already a rule in that position, it is moved one
slot, as are any preceding rules in that chain. The reference
count of any chains referenced by this inserted rule are
incremented appropriately. The data passed with this
command is an ip_fwnew structure, defining the position,
chain and contents of the new rule.
IP_FW_DELETE
Remove the first rule matching the specification from the
given chain. The data passed with this command is an
ip_fwchange structure, defining the rule to be deleted and
its chain. The reference count of any chains referenced by
this deleted rule are decremented appropriately. Note that
the fw_mark field is currently ignored in rule comparisons
(see the BUGS section).
IP_FW_DELETE_NUM
Remove a rule from one of the chains at a given rule
number (where 1 means the first rule). The data passed
with this command is an ip_fwdelnum structure, defining the
rule number of the rule to be deleted and its chain. The
reference count of any chains referenced by this deleted
rule are decremented appropriately.
IP_FW_ZERO

13
Project Report on Implementation of Firewall on Linux Platform

Reset the packet and byte counters in all rules of a chain.


The data passed with this command is an ip_chainlabel
which defines the chain which is to be operated on. See also
the description of the /proc/net files for a way to atomically
list and reset the counters.
IP_FW_FLUSH
Remove all rules from a chain. The data passed with this
command is a ip_chainlabel which defines the chain to be
operated on.
IP_FW_REPLACE
Replace a rule in a chain. The new rule overwrites the rule
in the given position. Any chains referenced by the new rule
are incremented and chains referenced by the overwritten
rule are decremented. The data passed with this command
is an ip_fwnew structure, defining the contents of the new
rule, the the chain name and the position of the rule in that
chain.
IP_FW_APPEND
Insert a rule at the end of one of the chains. The data
passed with this command is an ip_fwchange structure,
defining the contents of the new rule and the chain to which
it is to be appended. Any chains referenced by this new rule
have their refcount incremented.
IP_FW_MASQ_TIMEOUTS
Set the timeout values used for masquerading. The data
passed with this command is a structure containing 3 fields
of type int, representing the timeout values (in jiffies, 1/HZ
second) for TCP sessions, TCP sessions after receiving a FIN
packet, and UDP packets, respectively. A timeout value 0
means that the current timeout value of the corresponding
entry is preserved.
IP_FW_CHECK
Check whether a packet would be accepted, denied,
rejected, redirected or masqueraded by a chain. The data
passed with this command is an ip_fwtest structure,
defining the packet to be tested and the chain which it is to
be test on. Both builtin and user defined chains can be
tested.
IP_FW_CREATECHAIN

14
Project Report on Implementation of Firewall on Linux Platform

Create a chain. The data passed with this command is an


ip_chainlabel defining the name of the chain to be created.
Two chains can not have the same name.
IP_FW_DELETECHAIN
Delete a chain. The data passed with this command is an
ip_chainlabel defining the name of the chain to be deleted.
The chain must not be referenced by any rule (ie. refcount
must be zero). The chain must also be empty which can be
achieved using IP_FW_FLUSH.
IP_FW_POLICY
Changes the default policy on a builtin rule. The data
passed with this command is an ip_fwpolicy structure,
defining the chain whose policy is to be changed and the
new policy. The chain must be a builtin chain as user-
defined chains don't have default policies.

STRUCTURES
The ip_fw structure contains the following relevant fields to be
filled in for adding or replacing a rule:
struct in_addr fw_src, fw_dst
Source and destination IP addresses.
struct in_addr fw_smsk, fw_dmsk
Masks for the source and destination IP addresses. Note
that a mask of 0.0.0.0 will result in a match for all hosts.
char fw_vianame[IFNAMSIZ]
Name of the interface via which a packet is received by the
system or is going to be sent by the system. If the option
IP_FW_F_WILDIF is specified, then the fw_vianame need
only match the packet interface up to the first NUL
character in fw_vianame. This allows wildcard-like effects.
The empty string has a special meaning: it will match with
all device names.
__u16 fw_flg
Flags for this rule. The flags for the different options can be
bitwise or'ed with each other.
The options are: IP_FW_F_TCPSYN (only matches with TCP
packets when the SYN bit is set and both the ACK and RST
bits are cleared in the TCP header, invalid with other
protocols), The option IP_FW_F_MARKABS is described
under the fw_mark entry. The option IP_FW_F_PRN can be

15
Project Report on Implementation of Firewall on Linux Platform

used to list some information about a matching packet via


printk(). The option IP_FW_F_FRAG can be used to specify
a rule which applies only to second and succeeding
fragments (initial fragments can be treated like normal
packets for the sake of firewalling). Non-fragmented
packets and initial fragments will never match such a rule.
Fragments do not contain the complete information
assumed for most firewall rules, notably ICMP type and
code, UDP/TCP port numbers, or TCP SYN or ACK bits. Rules
which try to match packets by these criteria will never
match a (non-first) fragment. The option
IP_FW_F_NETLINK can be specified if the kernel has been
compiled with CONFIG_IP_FIREWALL_NETLINK enabled. This
means that all matching packets will be sent out the firewall
netlink device (character device, major number 36, minor
number 3). The output of this device is four bytes indicating
the total length, four bytes indicating the mark value of the
packet (as describe under fw_mark above), a string of
IFNAMSIZ characters containing the interface name for the
packet, and then the packet itself. The packet is truncated
to fw_outputsize bytes if it is longer.
__u16 fw_invflg
This field is a set of flags used to negate the meaning of
other fields, eg. to specify that a packet must NOT be on an
interface. The valid flags are IP_FW_INV_SRCIP (invert the
meaning of the fw_src field) IP_FW_INV_DSTIP (invert the
meaning of fw_dst) IP_FW_INV_PROTO (invert the meaning
of fw_proto) IP_FW_INV_SRCPT (invert the meaning of
fw_spts) IP_FW_INV_DSTPT (invert the meaning of
fw_dpts) IP_FW_INV_VIA (invert the meaning of
fw_vianame) IP_FW_INV_SYN (invert the meaning of fw_flg
& IP_FW_F_TCPSYN) IP_FW_INV_FRAG (invert the meaning
of fw_flg & IP_FW_F_FRAG). It is illegal (and useless) to
specify a rule that can never be matched, by inverting an
all-inclusive set. Note also, that a fragment will never pass
any test on ports or SYN, even an inverted one.
__u16 fw_proto
The protocol that this rule applies to. The protocol number 0
is used to mean `any protocol'.
__u16 fw_spts[2], fw_dpts[2]
These fields specify the range of source ports, and the
range of destination ports respectively. The first array

16
Project Report on Implementation of Firewall on Linux Platform

element is the inclusive minimum, and the second is the


inclusive maximum. Unless the rule specifies a protocol of
TCP, UDP or ICMP, the port range must be 0 to 65535. For
ICMP, the fw_spts field is used to check the ICMP type, and
the fw_dpts field is used to check the ICMP code.
__u16 fw_redirpt
This field must be zero unless the target of the rule is
"REDIRECT". Otherwise, if this redirection port is 0, the
destination port of a packet will be used as the redirection
port.
__u32 fw_mark
This field indicates a value to mark the skbuff with (which
contains the administration data for the matching packet).
This is currently unused, but could be used to control how
individual packets are treated. If the IP_FW_F_MARKABS
flag is set then the value in fw_mark simply replaces the
current mark in the skbuff, rather than being added to the
current mark value which is normally done. To subtract a
value, simply use a large number for fw_mark and 32-bit
wrap-around will occur.
__u8 fw_tosand, fw_tosxor
These 8-bit masks define how the TOS field in the IP header
should be changed when a packet is accepted by the
firewall rule. The TOS field is first bitwise and'ed with
fw_tosand and the result of this will be bitwise xor'ed with
fw_tosxor. Obviously, only packets which match the rule
have their TOS effected. It is the responsibility of the user
that packets with invalid TOS bits are not created using this
option.
The ip_fwuser structure, used when calling some of the above
commands contains the following fields:
struct ip_fw ipfw
See above
ip_chainlabel label This is the label of the chain which is to be
operated on.
The ip_fwpkt structure, used when checking a packet, contains
the following fields:
struct iphdr fwp_iph
The IP header. See <linux/ip.h> for a detailed description of
the iphdr structure.

17
Project Report on Implementation of Firewall on Linux Platform

struct tcphdr fwp_protoh.fwp_tcph


struct udphdr fwp_protoh.fwp_udph
struct icmphdr fwp_protoh.fwp_icmph
The TCP, UDP, or ICMP header, combined in a union named
fwp_protoh. See <linux/tcp.h>, <linux/udp.h>, or
<linux/icmp.h> for a detailed description of the respective
structures.
struct in_addr fwp_via
The interface address via which the packet is pretended to be received or sent.

RETURN VALUE
On success (or a straightforward packet accept for the CHECK
options), zero is returned. On error, -1 is returned and errno is set
appropriately. See setsockopt(2) for a list of possible error values.
ENOENT indicates that given chain name doesn't exist. When the
check packet command is used, zero is returned when the packet
would be accepted without redirection or masquerading.
Otherwise, -1 is returned and errno is set to ECONNABORTED
(packet would be accepted using redirection), ECONNRESET
(packet would be accepted using masquerading), ETIMEDOUT
(packet would be denied), ECONNREFUSED (packet would be
rejected), ELOOP (packet got into a loop), ENFILE (packet fell
off end of chain (only occurs for used defined chains)).

18
Project Report on Implementation of Firewall on Linux Platform

FIREWALL

1. What is a firewall?
A firewall protects networked computers from intentional
hostile intrusion that could compromise confidentiality or
result in data corruption or denial of service. It may be a
hardware device or a software program running on a secure
host computer. In either case, it must have at least two
network interfaces, one for the network it is intended to
protect, and one for the network it is exposed to. A firewall
sits at the junction point or gateway between the two
networks, usually a private network and a public network
such as the Internet. The earliest firewalls were simply
routers. The term firewall comes from the fact that by
segmenting a network into different physical subnetworks,
they limited the damage that could spread from one subnet
to another just like firedoors or firewalls.

2. What does a firewall do?


A firewall examines all traffic routed between the two
networks to see if it meets certain criteria. If it does, it is
routed between the networks, otherwise it is stopped. A
firewall filters both inbound and outbound traffic. It can also
manage public access to private networked resources such
as host applications. It can be used to log all attempts to
enter the private network and trigger alarms when hostile or
unauthorized entry is attempted. Firewalls can filter packets
based on their source and destination addresses and port
numbers. This is known as address filtering. Firewalls can
also filter specific types of network traffic. This is also known
as protocol filtering because the decision to forward or
reject traffic is dependant upon the protocol used, for
example HTTP, ftp or telnet. Firewalls can also filter traffic
by packet attribute or state.

19
Project Report on Implementation of Firewall on Linux Platform

3. What can't a firewall do?


A firewall cannot prevent individual users with modems from
dialling into or out of the network, bypassing the firewall
altogether. Employee misconduct or carelessness cannot be
controlled by firewalls. Policies involving the use and misuse
of passwords and user accounts must be strictly enforced.
These are management issues that should be raised during
the planning of any security policy but that cannot be solved
with firewalls alone.
The arrest of the Phonemasters cracker ring brought these
security issues to light. Although they were accused of
breaking into information systems run by AT&T Corp., British
Telecommunications Inc., GTE Corp., MCI WorldCom,
Southwestern Bell, and Sprint Corp, the group did not use
any high tech methods such as IP spoofing (see question
10). They used a combination of social engineering and
dumpster diving. Social engineering involves skills not unlike
those of a confidence trickster. People are tricked into
revealing sensitive information. Dumpster diving or
garbology, as the name suggests, is just plain old looking
through company trash. Firewalls cannot be effective
against either of these techniques.
4. Who needs a firewall?
Anyone who is responsible for a private network that is
connected to a public network needs firewall protection.
Furthermore, anyone who connects so much as a single
computer to the Internet via modem should have personal
firewall software. Many dial-up Internet users believe that
anonymity will protect them. They feel that no malicious
intruder would be motivated to break into their computer.
Dial up users who have been victims of malicious attacks
and who have lost entire days of work, perhaps having to
reinstall their operating system, know that this is not true.
Irresponsible pranksters can use automated robots to scan
random IP addresses and attack whenever the opportunity
presents itself.
5. How does a firewall work?
There are two access denial methodologies used by

20
Project Report on Implementation of Firewall on Linux Platform

firewalls. A firewall may allow all traffic through unless it


meets certain criteria, or it may deny all traffic unless it
meets certain criteria . The type of criteria used to
determine whether traffic should be allowed through varies
from one type of firewall to another. Firewalls may be
concerned with the type of traffic, or with source or
destination addresses and ports. They may also use
complex rule bases that analyse the application data to
determine if the traffic should be allowed through. How a
firewall determines what traffic to let through depends on
which network layer it operates at. A discussion on network
layers and architecture follows.

6. What are the OSI and TCP/IP Network models?


To understand how firewalls work it helps to understand how
the different layers of a network interact. Network
architecture is designed around a seven layer model. Each
layer has its own set of responsibilities, and handles them in
a well-defined manner. This enables networks to mix and
match network protocols and physical supports. In a given
network, a single protocol can travel over more than one
physical support (layer one) because the physical layer has
been dissociated from the protocol layers (layers three to
seven). Similarly, a single physical cable can carry more
than one protocol. The TCP/IP model is older than the OSI
industry standard model which is why it does not comply in
every respect. The first four layers are so closely analogous
to OSI layers however that interoperability is a day to day
reality.
Firewalls operate at different layers to use different criteria
to restrict traffic. The lowest layer at which a firewall can
work is layer three. In the OSI model this is the network
layer. In TCP/IP it is the Internet Protocol layer. This layer is
concerned with routing packets to their destination. At this
layer a firewall can determine whether a packet is from a
trusted source, but cannot be concerned with what it
contains or what other packets it is associated with.
Firewalls that operate at the transport layer know a little
more about a packet, and are able to grant or deny access

21
Project Report on Implementation of Firewall on Linux Platform

depending on more sophisticated criteria. At the application


level, firewalls know a great deal about what is going on and
can be very selective in granting access.

It would appear then, that firewalls functioning at a higher


level in the stack must be superior in every respect. This is
not necessarily the case. The lower in the stack the packet
is intercepted, the more secure the firewall. If the intruder
cannot get past level three, it is impossible to gain control of
the operating system.

According To Byte Magazine*, traditional firewall technology


is susceptible to misconfiguration on non-hardened OSes.
More recently, however, "...firewalls have moved down the
protocol stack so far that the OS doesn't have to do much
more than act as a bootstrap loader, file system and GUI".
The author goes on to state that newer firewall code
bypasses the operating system's IP layer altogether, never
permitting "potentially hostile traffic to make its way up the
protocol stack to applications running on the system".
*June 1998
7. What different types of firewalls are there?
Firewalls fall into four broad categories: packet filters, circuit
level gateways, application level gateways and stateful
multilayer inspection firewalls.
Packet filtering firewalls work at the network level of the OSI
model, or the IP layer of TCP/IP. They are usually part of a
router. A router is a device that receives packets from one
network and forwards them to another network. In a packet
filtering firewall each packet is compared to a set of criteria
before it is forwarded. Depending on the packet and the
criteria, the firewall can drop the packet, forward it or send
a message to the originator. Rules can include source and
destination IP address, source and destination port number
and protocol used. The advantage of packet filtering

22
Project Report on Implementation of Firewall on Linux Platform

firewalls is their low cost and low impact on network


performance. Most routers support packet filtering. Even if
other firewalls are used, implementing packet filtering at the
router level affords an initial degree of security at a low
network layer. This type of firewall only works at the
network layer however and does not support sophisticated
rule based models . Network Address Translation (NAT)
routers offer the advantages of packet filtering firewalls but
can also hide the IP addresses of computers behind the
firewall, and offer a level of circuit-based filtering.

Circuit level gateways work at the session layer of the OSI


model, or the TCP layer of TCP/IP. They monitor TCP
handshaking between packets to determine whether a
requested session is legitimate. Information passed to
remote computer through a circuit level gateway appears to
have originated from the gateway. This is useful for hiding
information about protected networks. Circuit level
gateways are relatively inexpensive and have the
advantage of hiding information about the private network
they protect. On the other hand, they do not filter individual
packets.

Application level gateways, also called proxies, are similar to


circuit-level gateways except that they are application
specific. They can filter packets at the application layer of
the OSI model. Incoming or outgoing packets cannot access
services for which there is no proxy. In plain terms, an
application level gateway that is configured to be a web
proxy will not allow any ftp, gopher, telnet or other traffic
through. Because they examine packets at application layer,
they can filter application specific commands such as
http:post and get, etc. This cannot be accomplished with
either packet filtering firewalls or circuit level neither of
which know anything about the application level
information. Application level gateways can also be used to
log user activity and logins. They offer a high level of
security, but have a significant impact on network

23
Project Report on Implementation of Firewall on Linux Platform

performance. This is because of context switches that slow


down network access dramatically. They are not transparent
to end users and require manual configuration of each client
computer.

Stateful multilayer inspection firewalls combine the aspects


of the other three types of firewalls. They filter packets at
the network layer, determine whether session packets are
legitimate and evaluate contents of packets at the
application layer. They allow direct connection between
client and host, alleviating the problem caused by the lack
of transparency of application level gateways. They rely on
algorithms to recognize and process application layer data
instead of running application specific proxies. Stateful
multilayer inspection firewalls offer a high level of security,
good performance and transparency to end users. They are
expensive however, and due to their complexity are
potentially less secure than simpler types of firewalls if not
administered by highly competent personnel.

24
Project Report on Implementation of Firewall on Linux Platform

Fwall.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/icmp.h>
#include <linux/if.h>
#include <linux/ip_fw.h>
#include <netdb.h>
#include <string.h>
#define MAXPORT 60000
struct ip_fwnew fwnew;
struct ip_fwchange fwappend;
struct ip_fwdelnum fwdelnum;
#define TOKENLEN 20
#define RULELEN 500
unsigned int lineno,src,dst,srcmsk,dstmsk,port,in_no,out_no,for_no,pos;
char token[TOKENLEN],rule[RULELEN];
struct protoent *proto;
struct servent *servent;
struct hostent *hostent;
struct ip_fwpolicy fwpolicy;
char protoname[20];
int getvalue(char *str,long *val)
{
char *endptr;
*val = strtol(str,&endptr,10);
if(*endptr != '\0')
return(0);
return(1);
}
int gettoken()
{
int i;
for(;rule[pos] == ' ' || rule[pos] == '\t';pos++);
if(rule[pos] == '\0' || rule[pos] == '\n')
return(0);
for(i = 0;rule[pos] != ' ' && rule[pos] != '\t' && rule[pos] != '\n'&& rule[pos] !
= '\0';pos++)
token[i++] = rule[pos];
token[i] = '\0';
return(1);
}

25
Project Report on Implementation of Firewall on Linux Platform

void initialise(void)
{
fwappend.fwc_rule.ipfw.fw_mark = 0;
fwappend.fwc_rule.ipfw.fw_flg = IP_FW_F_WILDIF;
fwappend.fwc_rule.ipfw.fw_invflg = 0;
fwappend.fwc_rule.ipfw.fw_vianame[0] = '\0';
fwappend.fwc_rule.ipfw.fw_tosand = 0xff;
fwappend.fwc_rule.ipfw.fw_tosxor = 0;
fwappend.fwc_rule.ipfw.fw_proto = 0;
fwappend.fwc_rule.ipfw.fw_outputsize = 0;
fwappend.fwc_rule.ipfw.fw_spts[0] = 0;
fwappend.fwc_rule.ipfw.fw_spts[1] = 0xffff;
fwappend.fwc_rule.ipfw.fw_dpts[0] = 0;
fwappend.fwc_rule.ipfw.fw_dpts[1] = 0xffff;
fwappend.fwc_rule.ipfw.fw_src.s_addr = 0;
fwappend.fwc_rule.ipfw.fw_dst.s_addr = 0;
fwappend.fwc_rule.ipfw.fw_smsk.s_addr = 0;
fwappend.fwc_rule.ipfw.fw_dmsk.s_addr = 0;
protoname[0] = '\0';
}
int getports(__u16 ports[2])
{
char *endptr;
int count;
gettoken();
if(token[0] >= 'a' && token[0] <= 'z'){
if(protoname[0] == '\0')
strcpy(protoname,"tcp");
servent = getservbyname(token,protoname);
if(servent == NULL){
printf("Invalid service name %s in line %d col
%d\n",token,lineno,pos);
return(0);
}
ports[0] = ports[1] = ntohs(servent->s_port);
return(1);
}
count = strtol(token,&endptr,10);
if(*endptr == '\0'){
ports[0] = ports[1] = count;
return(1);
}
else if(*endptr == '.' && endptr[1] == '.'){
endptr += 2;
ports[0] = count;
count = strtol(endptr,&endptr,10);
if(*endptr != '\0'){
printf("invalid range at line %d col %d",lineno,pos);
return(0);
}
ports[1] = count;
}
else{
printf(" Expected [!][port[..port]] in line %d col %d\n",lineno,pos);
return(0);

26
Project Report on Implementation of Firewall on Linux Platform

}
return(1);
}
int getsord(struct in_addr *sd,struct in_addr *sdmsk)
{
char src[20],msk[20];
int count,i;
__u32 flag;
char *endptr;
gettoken();
sdmsk->s_addr = 0xffffffff;
for(i = 0; token[i] != '/' && token[i] != '\0' ;i++)
src[i] = token[i];
src[i] = '\0';
hostent = gethostbyname(src);
if(hostent == NULL){
printf(" Host %s was not found in line %d \n",src,lineno);
return(0);
}
else{
sd->s_addr = hostent->h_addr_list[0];
}
if(token[i] == '/'){
i++;
strcpy(msk,&token[i]);
count = strtol(msk,&endptr,10);
if(*endptr == '\0'){
flag = 0x1;
sdmsk->s_addr = 0;
for( ; count >0;count--,flag <<= 1){
sdmsk->s_addr |= flag;
}
}
else{
if(inet_aton(msk,sdmsk) == 0){
printf(" Error in line no %d col %d invalid address
mask\n",lineno,pos);
perror("");
return(0);
}
}
}
return(1);
}
int appendrule(void)
{
gettoken();
strcpy(fwappend.fwc_label,token);
while(1){
if(gettoken() == 0) return(1);
if(strcmp(token,"-p") == 0){
gettoken();
strcpy(protoname,token);
proto = getprotobyname(token);
if(proto == NULL){

27
Project Report on Implementation of Firewall on Linux Platform

printf(" Error illegal protocol name in line %d col


%d\n",lineno,pos);
return(0);
}
fwappend.fwc_rule.ipfw.fw_proto = proto->p_proto;
}
else if(strcmp(token,"-s") == 0 || strcmp(token,"!-s") == 0){
if(token[0] == '!')
fwappend.fwc_rule.ipfw.fw_invflg |= IP_FW_INV_SRCIP;
if( getsord(&fwappend.fwc_rule.ipfw.fw_src,
&fwappend.fwc_rule.ipfw.fw_smsk) == 0)
return(0);
}
else if(strcmp(token,"-sp") == 0 || strcmp(token,"!-sp") == 0){
if(token[0] == '!')
fwappend.fwc_rule.ipfw.fw_invflg |= IP_FW_INV_SRCPT;
if(getports(&fwappend.fwc_rule.ipfw.fw_spts) == 0)
return(0);
}
else if(strcmp(token,"-d") == 0 || strcmp(token,"!-d") == 0){
if(token[0] == '!')
fwappend.fwc_rule.ipfw.fw_invflg |= IP_FW_INV_DSTIP;
if( getsord(&fwappend.fwc_rule.ipfw.fw_dst,
&fwappend.fwc_rule.ipfw.fw_dmsk) == 0)
return(0);
}
else if(strcmp(token,"-dp") == 0 || strcmp(token,"!-dp") == 0){
if(token[0] == '!')
fwappend.fwc_rule.ipfw.fw_invflg |= IP_FW_INV_DSTPT;
if(getports(&fwappend.fwc_rule.ipfw.fw_dpts) == 0)
return(0);
}
else if(strcmp(token,"-j") == 0){
gettoken();
strcpy(fwappend.fwc_rule.label,token);
if(strcmp(token,"REDIRECT") == 0){
if(gettoken()){

getvalue(token,&fwappend.fwc_rule.ipfw.fw_redirpt);
}
}
}
else if(strcmp(token,"-f") == 0)
fwappend.fwc_rule.ipfw.fw_flg |= IP_FW_F_FRAG;
else if(strcmp(token,"!-f") == 0)
fwappend.fwc_rule.ipfw.fw_invflg |= IP_FW_INV_FRAG;
else if(strcmp(token,"-y") == 0)
fwappend.fwc_rule.ipfw.fw_flg |= IP_FW_F_TCPSYN;
else if(strcmp(token,"!-y") == 0)
fwappend.fwc_rule.ipfw.fw_invflg |= IP_FW_INV_SYN;
else if(strcmp(token,"-m") == 0){
gettoken();
if(getvalue(token,(long *)&fwappend.fwc_rule.ipfw.fw_mark) ==
0){

28
Project Report on Implementation of Firewall on Linux Platform

printf(" Error in mark value in line %d col


%d\n",lineno,pos);
return(0);
}
fwappend.fwc_rule.ipfw.fw_flg |= IP_FW_F_MARKABS;
}
else if(strcmp(token,"-t") == 0){
gettoken();
if(getvalue(token,(long
*)&fwappend.fwc_rule.ipfw.fw_tosand)==0){
printf(" Error in tos_and value in line %d col
%d\n",lineno,pos);
return(0);
}
gettoken();
if(getvalue(token,(long
*)&fwappend.fwc_rule.ipfw.fw_tosxor)==0){
printf(" Error in tos_xor value in line %d col
%d\n",lineno,pos);
return(0);
}
}
else if(strcmp(token,"-i") == 0 || strcmp(token,"!-i") == 0 ){
int i;
if(token[0] == '!')
fwappend.fwc_rule.ipfw.fw_invflg |= IP_FW_INV_VIA;
gettoken();
for(i = 0; token[i] != '\0' || token[i] != '+';i++)
fwappend.fwc_rule.ipfw.fw_vianame[i] = token[i];
fwappend.fwc_rule.ipfw.fw_vianame[i] = '\0';
if(token[i] == '\0')
fwappend.fwc_rule.ipfw.fw_flg &= ~IP_FW_F_WILDIF;
}
else if(strcmp(token,"-l") == 0){
fwappend.fwc_rule.ipfw.fw_flg |= IP_FW_F_PRN;
}
else{
printf(" Invalid option %s in line %d col %d",token,lineno,pos);
return(0);
}
}
}
main(int argc,char *argv[])
{
int sockfd;
char c;
FILE *fp;
char fname[20];
if(argc > 2){
printf("USAGE : fwall [configuration file] \n");
exit(0);
}
if(argc == 2)
strcpy(fname,argv[1]);
else

29
Project Report on Implementation of Firewall on Linux Platform

strcpy(fname,"fw.conf");
lineno = 0;
in_no = 1;
out_no = 1;
for_no = 1;
sockfd = socket(AF_INET,SOCK_STREAM,0);
fp = fopen(fname,"r");
if(fp == NULL){
printf(" File %s not found \n",fname);
exit(0);
}
setsockopt(sockfd,IPPROTO_IP,IP_FW_FLUSH,"input",9);
setsockopt(sockfd,IPPROTO_IP,IP_FW_FLUSH,"output",9);
setsockopt(sockfd,IPPROTO_IP,IP_FW_FLUSH,"forward",9);
while(fgets(rule,RULELEN,fp) != NULL){
lineno++;
pos = 0;
initialise();
if(gettoken() == 0)
continue;
if(strcmp(token,"#") == 0)
continue;
if(strcmp(token,"-A") == 0){
if(appendrule() == 1){

if( setsockopt(sockfd,IPPROTO_IP,IP_FW_APPEND,&fwappend,sizeof(fwappend)) != 0)
{
printf("Error setting socket option in line %d :",lineno);
perror("");
}
}
}
else if(strcmp(token,"-N") == 0){
gettoken();
if(setsockopt(sockfd,IPPROTO_IP,IP_FW_CREATECHAIN,token,9)
< 0){
printf("Error setting socket option in line %d :",lineno);
perror("");
}
}
else if(strcmp(token,"-P") == 0){
gettoken();
strcpy(fwpolicy.fwp_label,token);
gettoken();
strcpy(fwpolicy.fwp_policy,token);

if(setsockopt(sockfd,IPPROTO_IP,IP_FW_POLICY,&fwpolicy,sizeof(fwpolicy)) <
0){
printf(" Error setting policy of line %d",lineno);
perror("");
}
}
else
printf(" Error in line %d col %d invalid command %s
",lineno,pos,token);

30
Project Report on Implementation of Firewall on Linux Platform

}
}

31
Project Report on Implementation of Firewall on Linux Platform

fw.conf

#This file was created using the GetRules module.


#The Default policies are:
-P input DENY
-P output DENY
-P forward ACCEPT
#Allow Source Quench packets
-A input -p icmp -sp 4 -dp 0 -j ACCEPT
#Allow echo reply inbound
-A input -p icmp -i eth0 -sp 8 -dp 0 -j ACCEPT
#Allow TTL exceeded inbound
-A input -p icmp -i pp0 -sp 11 -dp 0 -j ACCEPT
#Drop packets below 21
-A input -p tcp -dp 0..20 -j DENY
#Drop X- windows packets
-A input -p tcp -dp 6000..6003 -j DENY
#Drop SNMP packets
-A input -p tcp -dp 161-162 -j DENY
#Drop incoming telnet connections
-A input -p tcp -dp telnet -i pp0 -j DENY
#Allow http packets to webcache
-A input -p tcp -dp webcache -i pp0 -j ACCEPT
#Drop tcp packets from non standard ports
-A input -p tcp -dp 1024..65535 -i pp0 -y -j DENY
#Disallow ftp data connections
-A input -p tcp -dp 20..21 -i pp0 -y -j DENY
#Allow incoming http
-A input -p tcp -sp 1024..65535 -dp 80 -i eth0 -j ACCEPT
-A input -p tcp -sp http -dp 1024..65535 !-y -i pp0 ACCEPT
# Allow echo requests outbound
-A output -p icmp -i pp0 -sp 0 -dp 0 -j ACCEPT
#Allow destination unreachable outbound.
-A output -p icmp -i pp0 -sp 3 -dp 1 -j ACCEPT
-A output -p icmp -i pp0 -sp 3 -dp 0 -j ACCEPT
-A output -p icmp -i pp0 -sp 3 -dp 2 -j ACCEPT
-A output -p icmp -i pp0 -sp 3 -dp 3 -j ACCEPT
-A output -p icmp -i pp0 -sp 3 -dp 4 -j ACCEPT

32
Project Report on Implementation of Firewall on Linux Platform

33

Вам также может понравиться