Linux For Hacking For Install Test and Hack Tools.
Linux For Hacking For Install Test and Hack Tools.
Part 1 - Appendixes
Overview
This book is dev oted to exploring one of the most popular operating sy stems
installed on serv ers: Linux. So f ar, this operating sy stem has not been as
popular among home users as among prof essional administrators. There hav
e been, howev er, dev elopments of late that make this sy stem likely to
capture a good segment of the home-computer operating sy stem market. The
operating sy stem is becoming easier to install all the time, and its graphical
user interf ace and the ease of use of ten giv e the most popular operating sy
stem among home users — Windows — a good run f or its money.
This book will be of use to Linux administrators and to those Linux users
who want to learn this operating sy stem in more detail. The discussion of the
conf iguration and security issues will come in handy f or network security
prof essionals, ev en those running other operating sy stems, because the
larger part of the inf ormation is not tied to any specif ic operating sy stem.
You will learn how hackers break into serv ers, and use the knowledge to
prev ent them f rom breaking into y our serv er. Because some examples prov
ided in the book can be used not only f or def ense but also f or of f ense, I
would like to giv e f air warning to y oung aspiring hackers. Curiosity is a
commendable quality, but remember that the law is ev er v igilant and alway
s gets its man. If y ou get away with one break-in, next time y ou may not be
so lucky and may hav e to spend some time in a company of unf ortunate
specimens of humankind, where y our hacking skills will be of little use to y
ou.
Some material in the book is presented f rom the hacker's point of v iew and
describes methods of breaking into computer sy stems. I hope that this inf
ormation will not actually be put to use. But being somewhat skeptical of the
av erage human integrity, I tried to place more emphasis on def ense against
breaking in. I also lef t out some aspects and gav e only a general description
of others in order not to lead y ou into the temptation of apply ing these
methods in practice.
You only need to spend a f ew minutes on programming or on Internet
research to f inalize my thoughts. Although this book can serv e as a starting
point f or learning break-in techniques, I hope y ou will not use the acquired
knowledge maliciously. If common morality is not enough to keep y ou f rom
stepping onto the slippery path of computer burglary, remember the legal
ramif ications of y our actions.
Any tool can be used f or both usef ul and destructiv e purposes. A simple
kitchen knif e is a good example. It can be used as intended f or its kitchen
chores or as a def ensiv e or killing weapon. Likewise, the hacker techniques
discussed in this book can be used f or ev ery day operating sy stem
maintenance as well as f or def ending against or perpetrating computer sy
stem break-ins. I hope that y ou will not use the acquired knowledge f or
destructiv e purposes, which will not add to y our good name. As f or cracker
notoriety, why do y ou need it? You will be better of f directing y our ef f orts
toward constructiv e pursuits.
Despite the obv ious striv ings by Linux to become an ev ery day home
computer operating sy stem, it is still quite dif f icult to conf igure and
contains lots of options that most people simply do not need. "Security " is a
misnomer when ref erring to a Linux sy stem operated with its def ault conf
iguration settings. But no operating sy stem running at the def ault conf
iguration settings can work reliably and be maximally secure. Sof tware dev
elopers cannot possibly know each user's indiv idual needs and striv e to
make the sof tware work on any hardware conf iguration. To achiev e this,
they hav e to build many extraneous capabilities into their product.
It just happens that being a Linux administrator requires more knowledge and
experience than being a Windows administrator. This is because Linux is
more complex to conf igure. In this book, I try to explain this operating sy
stem in the most understandable terms; moreov er, I try to do this f rom the
hacker's point of v iew.
This book considers the operating sy stem starting f rom the basics and
proceeding to the most complex manipulations with the sy stem. The material
is presented in language simple and comprehensible to ev ery one. This will
make it possible f or y ou to acquire essential Linux knowledge without hav
ing to use any supplementary literature, because y ou will learn all the
necessary inf ormation f rom one source. For more detailed inf ormation, y ou
can take adv antage of the man, info, and help f iles supplied with the
operating sy stem.
This book is dif f erent f rom other books on the subject in that the security
and perf ormance are considered not in separate chapters at the end of the
book — doing this would be a big mistake — but throughout the book as may
be necessary. If a person acquires unproductiv e habits of working with the sy
stem, two chapters at the end of the book as an af terthought will not break
these wrong habits to teach the right ones. This is why the perf ormance and
security of each area considered will be discussed immediately without
putting it of f until the end of the book.
The subject of v iruses is not treated in the book, because currently the activ
ity of Linux operating sy stem v iruses is minimal, which is not to say that
there is no such threat. Howev er small it may be, it alway s exists; but
protecting against v iruses is similar to protecting against Trojans, of which
there are quite a f ew of the Linux v ariety. You can obtain more inf ormation
about v irus attacks and protection against them in the already -mentioned
Hackish PCbook of my authorship.
So, start discov ering Linux. I am certain that y ou will see this operating sy
stem in an entirely dif f erent light and learn many new and interesting things.
Chapter 1: Introduction
Overview
Once I showed a Windows administrator how to install and work with Linux.
He liked the installation process, because it was easy in the latest v ersions of
the operating sy stem. But when we installed and decided to conf igure the
Samba serv er, there was a f lood of questions of the ty pe, "Why does Samba
hav e to be conf igured? Why can't I just be granted access automatically ?"
The truth is, Windows administrators are lazy and are used to the operating
sy stem doing ev ery thing f or them. But when their sy stem is broken into,
there ensues another f lood of questions, this time of a dif f erent ty pe: "Why
didn't Microsof t prov ide the tools to disable certain operations?"
It is rather rough going, because making a sy stem conv enient to use detracts
f rom its security and, on the contrary, making a sy stem more secure makes
lif e harder f or the users. So manuf acturers hav e to f ind some reasonable
compromise between these two requirements.
The hacker elite consisted mostly of honest people who conducted their
research in the security area with the goal of improv ing this security, not
compromising it.
The way things stand now, any inf ormation about v ulnerabilities — holes,
bugs, and so on — can be f ound in any corner of the Internet. Now any one
can be a hacker. The f reedom-of -inf ormation f ighters are to blame: How
this came to be? Unlimited f reedom alway s leads to destruction in the end. I
guess that the urge to destroy is in the blood of all of us. Most of us suppress
this, just like we do many other primitiv e desires, but some giv e in and use
the publicly av ailable inf ormation to become crackers.
Obtaining information. The sy stem is broken into to obtain inf ormation that
is not av ailable to the common public. Such break-ins are usually directed at
stealing business or f inancial secrets, sof tware source codes, conf idential
data, and so on. They are usually carried out by prof essional hackers f ulf
illing an order or f or personal gain.
Modifying or destroying data . All Internet or intranet serv ers are susceptible
to this ty pe of attack. They can be carried out not only by prof essional
hackers but also by amateurs, including disgruntled employ ees.
Denial of Service (DoS). The purpose of the attack is to render the serv er's
serv ice unav ailable without actually destroy ing any data. These attacks are
mainly carried out by amateurs whose only goal is to do damage.
Attacks can be classif ied into the f ollowing three groups, based on the
manner, in which they are executed:
Local attacks . These attacks are executed by an intruder with phy sical
access to the computer being broken into. This sort of attack is not dif f icult
to protect against because all that is necessary is to restrict phy sical access to
the serv er by, f or example, placing it in a limited-access room and guarding
it.
Remote attacks . These are carried out remotely v ia networks f rom a phy
sical location other than where the computer being broken into is located.
This ty pe of attack is the most dif f icult to protect against. Ev en the
installation of the best f irewalls and monitoring and logging sof tware cannot
guarantee complete security. Proof of this can be seen in the many break-ins
suf f ered by some of the world's most protected Internet serv ers (Yahoo,
Microsof t, NASA, etc.).
Remote attacks carried out by users of the local network . Yes, not only bad
dudes somewhere on the Internet can be hackers but also the guy next cubicle
who may try to break into y our computer f or f un, prof it, or rev enge.
When designing y our def enses, y ou must understand the techniques used
by hackers to break into computers. Only then will y ou be able to prev ent
unwanted intrusions and protect y our computers. Consider the main attack
techniques used by hackers and how they are used. To help y ou understand
the process better, I will look at them f rom the standpoint of the perpetrator.
I will not consider social engineering. This subject is worth a separate book,
and it makes no sense to only touch on the topic.
1.1.1. Research
Suppose that y ou want to break into a certain serv er to test how well it is
protected. What should y ou start with? There is no clear-cut answer to this
question. Again, any break-in is a creativ e process and requires an indiv
idual, creativ e approach. There are no set rules or ready -made templates.
Howev er, a f ew practical recommendations f or y ou to f ollow can be prov
ided.
Scanning
The f irst thing to do is test the sy stem's v ulnerability by scanning its ports.
What f or? To f ind out what serv ices (in Linux, daemons) are installed in the
sy stem. Each open port is a serv ice program installed on the serv er, to
which y ou can connect and make it do certain things f or y ou. For example,
port 21 is used by the File Transf er Protocol (FTP) serv ice. If y ou connect
to this port, y ou will be able to download f iles f rom and upload f iles to the
serv er. You will hav e to hav e the corresponding priv ileges, howev er, to be
able to do this.
First, y ou need to scan the f irst 1,024 ports. Many of them are used by
standard serv ices such as FTP, Hy perText Transf er Protocol (HTTP), and
Telnet. An open port is just like a locked entrance door to the serv er. The
more entrances of this ty pe there are, the greater the chances that the lock f
or one of them will succumb to picking and swing open to let y ou in.
A good administrator leav es only the most necessary ports open. For
example, if y our serv er is used only to serv e Web pages but not email, there
is no need to keep the mail serv ers open. The only port that a Web serv er
needs is port 80, so only it should be lef t open.
A good port scanner reports not only the open-port number but also the
names of the serv ice using them. Unf ortunately, the serv ice name is not
real; it is only the name of the serv er installed on the port. Thus, the name of
port 80 will be giv en as HTTP. It is desirable that the scanner could sav e the
scanning results to a f ile and ev en print them out. If y our scanner does not
hav e these f eatures, y ou will hav e to write down all the inf ormation y
ourself and sav e it. You will need this inf ormation f or y our f uture exploits.
Af ter scanning the f irst 1,024 ports, y ou can mov e on to scanning the rest.
Standard serv ices are a rare occurrence in this port range. Why bother
scanning them then? Well, there is alway s a chance that someone has already
v isited this area and lef t an open door or installed a Trojan horse on the serv
er. Most Trojan horses keep open ports in the range abov e port 1,024. So if y
ou are a serv er administrator, an open port abov e 1,024 should make y ou sit
up and take notice. If y ou're a hacker and stumble on an open port abov e
1,024, y ou should f ind out what Trojan horse serv er is installed on it and f
ind a client f or it to control the machine.
This will be all y ou need to do to break into the serv er. By using the Trojan
horse installed by a stranger, y ou can obtain access to the serv er without any
great ef f ort on y our part. Unf ortunately, lif e is rarely a bowl of cherries
and discov eries of this kind are the exception rather than the rule. In most
cases, y ou will hav e to do all the dirty work y ourself .
The f irst parameter is the serv er address and the second parameter is the port
number.
Here, the telnetcommand is executed, which tries to connect to the specif ied
port at the specif ied serv er. A successf ul attempt means that the port is
open; otherwise, the port is closed. If no more than f iv e ports per hour are
checked in this way, most of scanning-detection utilities will not react; the
scanning process, howev er, will stretch on f or weeks.
Because the administrator of the computer y ou are try ing to scan can enter y
our Internet protocol (IP) address into the suspect list, it is a wise mov e to
conduct scanning f rom a computer other than y our own. To this end,
crackers set up Web sites on f ree serv ers that allow them to use PHP and
Perl scripts. Free serv ers usually do not require personal data to be prov ided
during the registration, but ev en if they do, y ou can simply supply any
made-up data because no one is going to check them. As the next step, y ou
establish a saf e connection to the serv er v ia a proxy serv er and run y our
scripts to scan the target's computer.
Af ter the scanning, y ou will know, which doors are on the serv er that y ou
can use. But this is not enough; the doors also hav e to be open. This will take
much greater ef f ort.
The most popular scanning tool is the nmap utility. It has conquered the
hearts of hackers because it of f ers a great many f eatures and not all
scanning-detection tools can detect it. For example, a scanning-detection
program can watch f or attempts to connect to sev eral ports sequentially or at
once. But nmap may not establish an actual connection.
If the welcome prompt ref lects reality, the administrator is still wet around
the ears. An experienced administrator will alway s change the def ault
welcome message. And a really canny administrator can make the welcome
message show something dif f erent altogether. For example, a Windows NT
4.0 serv er can be made to display a Linux welcome message. This will make
an unsophisticated hacker waste lots of time using Linux v ulnerabilities to
break into the Windows NT serv er. Theref ore, don't put too much trust into
the welcome message. Try to ascertain the ty pe of the operating sy stem by
some other method.
To av oid being f ooled, alway s pay attention to the serv ices used on the
serv er. For example, a Linux serv er will not serv e Activ e Serv er Pages
(ASPs). Although things like this can be f aked, it is not of ten done. To make
an ASP run under Linux, PHP script f iles are sav ed with ASP extensions
and are redirected to the PHP interpreter. So it looks like the serv er serv es
ASP f iles, but these are actually PHP scripts.
As y ou can see, the def ending side goes to great lengths to make lif e as dif f
icult as possible f or hackers. Most inexperienced hackers believ e ev ery
thing they see and spend lots time try ing to break in using methods that hav e
not got the slightest chance of success. Consequently, breaking in becomes
too expensiv e an option, and the hacker giv es up.
The hacker's task is to untangle all of the f alse leads lef t by the administrator
and determine exactly what sy stem he or she is dealing with. Unless this
preliminary task has been completed successf ully, any f urther actions would
be like looking f or a needle in a hay stack. The hacker will not ev en know,
which commands to use or what executable f iles can be inf iltrated onto the
serv er.
Hackers like using the nmap utility f or determining the operating sy stem.
Although the programs main f unctionality is geared toward port scanning, if
run with the —O switch, it will attempt to determine the operating sy stem.
There is a chance that this attempt will not succeed, but there also is a chance
that it will.
Using Scripts
Now y ou know, which operating sy stem is running the serv er, which ports
are open, and the serv ices that are sitting on these ports. You should write
down all of this inf ormation either to a f ile or on paper. The important thing
is that it should be conv enient to work with.
This concludes the research part. Now y ou hav e enough inf ormation to
attempt a basic break-in using the v ulnerabilities in the serv er's operating sy
stem and serv ices. The inf ormation about which v ulnerabilities to use can
be f ound by regularly v isiting the www.securityfocus.com site. Inf
ormation about new v ulnerabilities is updated of ten on this site, and it is a
longstanding and well-known f act that most serv ers (70% to 90%,
depending on the source) simply are not patched. Theref ore, y ou should use
all known v ulnerabilities on the v ictim and hope that something works.
Breaking into a Web serv er inv olv es its own specif ic considerations.
Breaking a serv er that allows execution of Common Gateway Interf ace
(CGI), PHP, or other scripts requires a dif f erent approach than f or other
serv er ty pes. The break-in is started by scanning the serv er f or v ulnerable
CGI scripts. You may f ind it hard to believ e, but research conducted by v
arious companies indicates that many v ulnerable scripts are employ ed on
Internet sites.
Scripts are v ulnerable because pages are programmed by people, who hav e
an inherent propensity to err. Nov ice programmers seldom test the incoming
parameters, hoping that the users won't change the page code or the Unif orm
Resource Locator (URL), through which the data necessary f or executing
certain actions are passed to the serv er. But I hav e already considered how
to modif y page code and f ake IP addresses in this chapter. This was possible
because the programmers relied on v isitors being conscientious. They
shouldn't hav e.
The problem is aggrav ated because some programming languages (e.g., Perl)
were not intended f or use with the Internet. They contain some f unctions f
or manipulating the sy stem, and if a programmer inadv ertently uses them in
his or her work, hackers can take adv antage of them to obtain control ov er
the sy stem.
So y our main task is to add a couple of good CGI scanners into y our toollit.
Which CGI scanner should y ou obtain? It does not matter; any one of them
is better than nothing. Ev en the worst scanner can f ind v ulnerabilities,
about which ev en the best hackers are unaware. And it just may happen that
it will f ind this v ulnerability on the serv er y ou are try ing to break into. In
addition, y ou should become a f requent v isitor to www.securityfocus.com,
where they regularly put out descriptions of the latest v ulnerabilities of v
arious Web site programming languages.
When y our attempts to break into a serv er using y our basic brain power hav
e f ailed, y ou can alway s f all back on the brute-f orce method. No, brute f
orce does not mean that y ou will hav e to grab the site administrator by the
throat, knock his head on the wall, and demand that he surrender the
passwords. Brute f orce means simply try ing dif f erent passwords until y ou
hit on the right one.
Are y ou still skeptical? Then let me remind y ou about the f amous Morris
worm, which used the dictionary method to break into sy stems. Its own
dictionary contained f ewer than 100 words. In addition to its own dictionary,
the worm used the dictionaries f rom the compromised computers. But those
did not hav e too many passwords in them either. Using such a primitiv e
algorithm, the worm was able to spread through a huge number of the
Internet computers. This was one of the largest-scale inf ections ev er! Yes, it
happened a long time ago, but the lev el of prof essionalism of the av erage
user has not grown since then. There are many experienced users, but there
are many more green beginners.
Hacking a local network is easier than hacking the Internet f or the f ollowing
reasons: The computers are connected using a high-speed connection (10
MB/sec and higher), the traf f ic of the other network computers can be
monitored, f ake serv ers can be created, and f irewalls are seldom used
because they are mostly used as a shield between the local network and the
Internet. Consider the most popular local network hacking techniques.
Traffic Monitoring
Local networks hav e certain inherent f eatures. For example, if a local
network is built using coaxial or twisted-pair cable and hubs to connect the
computers, all the network traf f ic passes through all the computers in the
network. Why can't y ou see this traf f ic? Because the operating sy stem and
the network card are joined in a conspiracy and do not show y ou the traf f ic
that is not y ours. But if y ou really want to read other people's network traf f
ic, y ou can obtain a snif f er program and monitor all data that pass through y
our network card ev en if they are not intended f or y ou.
The snif f er trick will not work on the Internet; y ou will see only y our own
traf f ic. To be able to monitor the Internet traf f ic of other participants, y ou
would hav e to hack into the prov ider's serv er and install y our snif f er
there. This is a rather inv olv ed undertaking, f raught with the danger of
being f ound and lacked out. Theref ore, snif f ers are generally used only on
local networks.
Why can y ou see other people's traf f ic on a local network but not on the
Internet or switched local networks? When the computers are connected into
a network using a coaxial cable, they all sit on a common bus serially. The
bus can be made into a ring, with the computers at the bus ends connected to
each other. When the computers at the bus ends exchange data, all packets
pass through the network adapter of the computer (or computers) between
them.
Coaxial cable is seldom used as the choice network medium because such a
connection is unreliable and its bandwidth is limited to 10 MB/sec.
Since the early 1990s, the pref erred network conf iguration has been the
starconnected topology, with computers connected to one central point using
a hub or a switch. If the central connecting dev ice is of the hub ty pe (also
known as a multiport repeater), all packets that it receiv es f rom one of the
computers are simply resent to the rest of the network computers. If the
central connecting dev ice is of the switch ty pe, the packets are deliv ered
only to the recipient because the switch has built-in routing capabilities.
Switches usually route Medium Access Control (MAC) address-lev el
packets. This ty pe of addressing is used to exchange packets only in local
networks (ev en if data are sent to an IP address). In the Internet, packets are
addressed using IP addressing, but f ar f rom all switches can handle this ty
pe of addressing. In this case, a more intelligent dev ice is needed to send
packets to the right place: a router. Like switches, routers send packets only
to the computer, to which they are addressed, or to another router that knows
where the addressee computer is located.
Intercepting packets is only half of the job: The inf ormation contained in
them is in a f orm dif f icult f or humans to interpret. It is mostly just f
ragments of larger data blocks that hav e been broken into parts to be
transmitted.
Today, y ou can f ind any ty pe of snif f er, as well as add-ons f or it, on the
Internet. Dif f erent v ersions are optimized f or dif f erent tasks, so y ou
should select the one suited to y our particular task If y ou are af ter
passwords, y ou need a snif f er that can isolate the registration inf ormation f
rom the ov erall network traf f ic. This task is not dif f icult because, unless
the Secure Sockets Lay er (SSL) protocol is used, all passwords are sent to
the Internet in open text, just like the rest of the inf ormation.
The adv antage of using snif f ers when perpetrating a break-in is that they do
not interact with the computer being attacked, which means that they are hard
to detect. In most cases, it is simply impossible to know that y our traf f ic is
being monitored by someone.
Fake Address
It has already been mentioned that f irewalls allow or disallow user access
based on a set or rules. But it is not alway s conv enient to disallow all
accesses to all ports. For example, access to the management programs can
be disallowed f or all IP addresses except the one used by the sy stem
administrator. Any one try ing to enter the restricted area f rom a dif f erent
IP address will be stopped by the f irewall.
At f irst glance, the def ense seems perf ect. This would be the case were it
not f or an attack technique called spoof ing. This attack is carried out by f
aking the address of an authorized user to enter the serv er under attack. Old f
irewalls and cheaper contemporary examples cannot detect the f aked address
in the packets. A good f irewall should ping the computer try ing to connect
to ascertain that it is turned on and that this computer is actually requesting
the connection to the restricted resources.
Fake Servers
Attacks using f ake serv ers or serv ices are much easier to carry out in local
networks than on the Internet. For example, the f ollowing well-known f ake
Address Resolution Protocol (ARP) record attacks can be carried out only on
local networks.
If there is no computer with the specif ied IP address on the giv en network
segment, a router may reply by sending its own MAC address. In this case,
the computer will exchange data with the router, which will resend the packet
into another network segment or to another router until it reaches its
destination.
But what if the computer that replies is not the specif ied computer but,
instead, an impostor with a dif f erent IP address? When sending packets on a
local network, computers do not use IP addresses but go by MAC addresses.
So the packets will be sent to whichev er computer claims that its MAC
address corresponds to the specif ied IP address, regardless of what its real IP
address is. The hacker's task, theref ore, is to intercept an ARP request and
answer it, instead of the intended recipient doing so. In this way, a connection
can be taken ov er.
Using Trojan horses is the stupidest and unreliable method to employ against
network administrators, but good enough against regular users, because they
are easier to f ool. Although there are network administrators not quite up to
their position, v ery f ew of them will f all f or this trick. But who say s that
there are only administrators on networks? There also are plenty of regular
users with high access priv ileges and trusting souls. They are the ones y ou
can horse around with, so to speak.
A Trojan program consists of two parts: a serv er and a client. The serv er
needs to be installed on the v ictim's computer, one way or another, and
started. Most of ten, a Trojan program places itself into the start-up f older,
starts automatically with the sy stem, and runs surreptitiously in the
background. With the serv er part planted on the v ictim's computer, y ou can
use the client part to communicate with the serv er and make it do all kinds of
things, such as rebooting the computer and checking its hard driv es f or
interesting inf ormation.
The danger presented by Trojan horses is indirectly conf irmed by the f act
that most new antiv irus programs check not only f or v iruses but also f or
Trojan programs. For example, antiv irus programs identif y Back Orif ice as
the Win32.BO v irus.
The stupidest attack thought up by hackers is the DoS attack. The essence of
such an attack is that the hacker attempts to make the serv er stop answering
requests f or pages. How can this be done? This is of ten achiev ed by making
the serv er enter an endless loop. For example, if the serv er does not check
that incoming packets are in the proper f ormat, the hacker may send it a
request that will make the serv er serv icing this request endlessly, leav ing no
processor time f or serv icing other requests and, thus, deny ing serv ice to
other clients.
A DoS attack can be executed in two way s: by exploiting a bug in the serv er
program or by ov erloading the serv er's communications channel and/or
resources. The f irst method requires that the serv er hav e a v ulnerability and
that y ou know what it is. The most of ten used v ulnerability is the buf f er
ov erf low error.
If the program has no prov isions f or checking the actual size of the data it
receiv es and writes to the data buf f er, the buf f er is subject to ov erf low. If
a user sends 100 characters instead of just 5, when all these characters are
written to the buf f er intended to hold only 5 characters, the other characters
will be written into the program code area ov erwriting the code. This means
that the program code will be corrupted and will not be able to execute as
intended. The program will most likely hang. The serv er then stops
responding to the client requests, and y ou hav e carried out a successf ul buf
f er ov erf low DoS attack.
Consequently, the computer was not broken into, no inf ormation was
touched, but the computer has been put out of the network serv ice. DoS
attacks are ev en easier to execute in a local network. All y ou hav e to do is
to replace the IP address of y our machine with the IP address of the machine
under the attack. This will result, in the best case, in the machine under attack
becoming inaccessible or, in the worst case, in both machines becoming
inoperable.
If there are no limitations on the resources, the serv er will process as many
requests as it can. In this case, either the communications channel or the serv
er can be attacked. The choice of the target depends on which is weaker. For
example, if a 100-MB/sec channel is serv iced by a Pentium 100 serv er, it is
much easier to kill the computer than to ov erload the communications
channel. But if a relativ ely powerf ul serv er is sitting on a narrow bandwidth
channel, it is easier to ov erload the channel.
Ev en when hackers manage to obtain priv ileged sy stem rights, they still
striv e to lay their hands on the password f ile. Succeeding in this endeav or
giv es them access to the root account (in UNIX sy stems) and,
correspondingly, rights to the entire sy stem. But the passwords are encry
pted and the successf ul hacker will, at most, see the hash sums produced by
irrev ersible password encry ption.
When the administrator adds a new user, his or her password is irrev ersibly
encry pted (most of ten, using the MD5 algorithm), meaning that the plain
password cannot be reproduced f rom the encry pted f orm. The obtained
hash sum is sav ed in the password f ile. When the user enters the password,
it is encry pted and compared with the hash sum sav ed in the f ile. If the
results match, the password entered is accepted. The subject of how
passwords are stored in Linux will be cov ered later.
Because the encry pted password cannot be decry pted, it may seem at f irst
that the hash f ile is of no use. But appearances can be deceiv ing. Ev en
though the password cannot be decry pted, it can be picked by the brutef orce
method. There are many programs f or this task, John the Ripper
(www.openwall.com/john) and Password Pro (www.insidepro.com), f or
example.
Why can utilities like these be f reely obtained on the Internet by any one
when they can be used f or criminal purposes? Any program has negativ e as
well as positiv e aspects. What should y ou do when y ou f orget the
administrator password or the administrator has f orgotten to tell y ou what it
was when y ou f ired him? Reinstall the sy stem? This will take a long time
and is f raught with the danger of losing data. It is easier to remov e the hard
driv e, connect it to another computer (or simply load it f rom a diskette), take
the password f ile, and break the necessary password.
1.1.9. Summary
Each cracker has numerous break-in techniques and instruments in his or her
toolkit. The more experienced a hacker is, the more techniques he or she
collects and tries against the target serv er. Hav ing determined the serv er's
operating sy stem and the serv ices running on it, the cracker starts using the
attack methods in his or her arsenal one af ter another.
Any hacker can try password picking. This technique, howev er, is usually
the last one resorted to because it can take too much time and produce no
results in the end. In addition, password picking may f ail if the serv er is
conf igured to detect a password-picking attempt and the administrator reacts
properly to such attempts. One of the things the administrator could do af ter
detecting that someone is try ing to pick the password to the serv er is conf
igure the f irewall to prohibit connections f rom the IP address, f rom which
the password-picking activ ity was detected. This will render any other
miscreant's actions useless until he or she manages to change the IP address.
The preceding rev iew of hacker attacks is not exhaustiv e. I tried to prov ide
the most essential basic inf ormation. I did not describe any specif ic break-in
methods. Doing this could be considered a call to action, and the purpose of
this book is not to add to the already ov erly large host of crackers. My goal
is to show how hackers see the computer and how they use it. This should
help y ou learn more about the computer and make it more secure.
You must understand the theory underly ing breaking-in well to know what
to protect y ourself f rom. Without this knowledge, y ou will not be able to
build def enses capable of def lecting ev en the simplest hacker attacks. How
can y ou def end y ourself without knowing how the attack will be carried
out? You can't.
Hackers f rom dif f erent countries joined the project on a v oluntary basis
and started creating the most controv ersial operating sy stem. Controv ersies
around Linux arise almost daily, because the operating sy stem has become
widespread and customers can hav e it f or f ree. Some sof tware dev elopers
consider this project to hav e no f uture, and some (e.g., Microsof t)
periodically treat it as their worst enemy.
The f irst of f icial v ersion of the operating sy stem's kernel, v ersion 1.0, was
released in 1994, 3 y ears af ter Linux was f irst announced. Such a rapid dev
elopment phase was made possible by the large number of prof essionals who
joined in dev eloping Torv alds's interesting idea.
Linux is a multiuser, multitask operating sy stem, which means that sev eral
users can execute sev eral tasks at the computer at the same time.
Why has this operating sy stem become so popular, unlike other open-source
projects, some of which were implemented ev en better than Linux? I
attribute this popularity to Linux's being created by hackers and f or hackers.
It is a nice f eeling to work with an operating sy stem that y ou hav e taken
part in creating. Any user can change the source code of the sy stem in any
way without f ear of being persecuted under the law.
The operating sy stem in its present state allows practically any task to be run
under it. There hav e been numerous f ree sof tware packages f or handling v
arious tasks written f or Linux. Computers running Linux are used in div erse
areas, including creating special ef f ects f or mov ies.
But why is Linux so dif f icult to master? The answer is simple: Perf ormance
and conv enience are two incompatible things. Linux is a perf ormance
product, and Windows is a conv enience product. To do something in
Windows, y ou just need to go through a series of dialog windows, choosing f
rom the av ailable options. But this requires making lots of clicks, which in
turn consumes lots of precious time. To do the same thing in Linux, y ou just
launch the console and run the necessary command, which is much f aster.
But the problem is that y ou hav e to remember lots of dif f erent commands f
or all occasions.
Windows uses images and a graphical user interf ace wherev er possible.
Graphical utilities in Linux are too unsophisticated and of ten do not of f er
many f eatures. This, howev er, is changing as graphical conf iguration
utilities are becoming av ailable in ev er increasing numbers, making the conf
iguration process simpler and easier. It is only a matter of time bef ore Linux
becomes easy to use while preserv ing all of its power and the speed of the
command line interf ace.
You task is not to simply learn to work with Linux but to learn to do so ef f
iciently, meaning that y ou should be able to conf igure it f or maximum perf
ormance and security. This will be y our main goal as y ou use this book.
Nev ertheless, Linux security is higher than that of Windows, and this has
nothing to do with it being open source. Simply, many security -related
aspects in Linux are implemented better than in Windows. Take, f or
example, memory allocation. When a program is run, it is allocated a certain
memory area. In Linux, under normal circumstances a program cannot ov
erstep the bounds of the allocated memory. It can do this only in extreme
cases to exchange data with other programs. In Windows, any program can
access any memory area. Ov erstepping the allocated memory area is f raught
with the danger of the program mistakenly ov erwriting a memory area
allocated to another program or ev en to the sy stem itself , causing the sy
stem to crash in the latter case.
Starting with Windows 2000, the memory subsy stem operation has been
improv ing in this brand of the operating sy stem, but it still has lots of room f
or improv ement. For example, Linux can clear the program's memory area af
ter its termination because it knows exactly how much memory and at what
address it allocated memory f or the program's needs. The same maintenance
task is more dif f icult to implement in Windows, so y ou can only rely on the
quality of the application sof tware, which is unlikely to improv e. Thus,
there is constant memory leakage in this operating sy stem.
The Linux kernel v ersion is designated using three numbers as f ollows: The
f irst number indicates signif icant kernel changes.
The second number indicates slight changes. This number tells whether the
kernel is stable or is intended f or testing purposes only and may contain
errors. An ev en number means that the kernel has undergone thorough
testing and is stable. An odd number means that the kernel v ersion is in the
testing stage and stable operation is not guaranteed.
You hav e to update the kernel y ourself , which giv es y our sy stem new
capabilities. Updating to an unstable kernel v ersion, y ou can take part in its
testing. New kernel v ersions can be downloaded f rom the www.kernel.org
site or f rom the site of the dev eloper of y our distribution package.
Updating the kernel not only will giv e y our machine new capabilities f or
using the hardware components but also will correct errors, which are part of
all sof tware, no matter how well tested. It can ev en increase the ef f iciency
of y our sy stem. The most important thing is that y ou do not hav e to reconf
igure the entire operating sy stem to update the Linux kernel, as is done in
some operating sy stems. I hav e seen computers whose operating sy stems
were conf igured just as they had been when they were installed sev eral y
ears ago, with only the kernel and application programs being updated as
needed. This is an exception rather than a rule. Usually, the sy stem's
hardware has to be upgraded ev ery y ear or two to increase the perf ormance
and thus satisf y the ev er-increasing demands of users and new resource-
hungry sof tware.
1.5. Distributions
At present, there are dozens of v ersions of Linux, called distributions.
Despite this embarrassment of riches, y ou can easily see that they are similar
to one extent or another, because most of them hav e the same roots. Many
distributions, f or example, are built on the base of the Red Hat Linux brand.
Although Linux is f ree, its distributions are not quite so. Just like Windows
or other commercial sof tware, y ou hav e to buy Linux f rom sof tware v
endors. Their license agreements, howev er, are much more generous than
those f or commercial operating sy stems. For example, af ter buy ing one
copy of Linux, y ou can install it on as many computers as y ou want to.
Usually, v endors modif y the installer slightly (this mostly consists of
"dabbing some make-up" to the graphical interf ace), change the list of
application sof tware, and then sell it under their brand name. In most cases,
howev er, the sy stem's kernel and the application sof tware are not changed.
But ev en distributions of dif f erent origins almost alway s use the K Desktop
Env ironment (KDE) or/and GNU Network Object Model Env ironment
(GNOME) graphical shells. If , in an unlikely case, the distribution does not
supply these shells, y ou can easily obtain them f rom third-party sources and
install them y ourself . Consequently, all distributions use the same graphical
interf ace, regardless of their origins.
In this book, I will consider the Red Hat distribution of Linux because it is
the most widely used (by some accounts, it holds about a 50% share of the
Linux market). Don't worry if y ou are using another distribution: You will
not notice any signif icant dif f erences. The biggest dif f erences among
distributions show up mostly during the installation process, but ev en then
only in the way the graphical interf ace is implemented.
The price f or one copy of Linux is much lower than that f or Windows.
Moreov er, the distribution package includes a huge number of application
sof tware, such as of f ice applications, Internet utilities, and graphics editors.
Consequently, hav ing installed a Linux distribution y ou can immediately
use the sy stem to solv e most of f ice and home tasks (not the laundry,
though).
Microsof t's Paint, WordPad, and other application programs supplied with
the operating sy stem are too unsophisticated f or any thing but the most basic
tasks. To obtain corresponding application sof tware of acceptable perf
ormance, y ou will hav e to spend thousands of extra dollars. Theref ore, the
actual price of a ready -to-work Windows-based workstation is much higher
than the price of the operating sy stem, because application sof tware is to be
purchased in addition to the operating sy stem.
Comparing the combined cost of the operating sy stem and the application
sof tware, Linux is signif icantly less expensiv e than Windows. Microsof t,
howev er, prov ides f ree support f or its product; whereas to obtain any
decent support f or Linux, y ou must hav e access to the Red Hat network,
which is rather expensiv e. Thus, support expenses can make the ownership
costs of the two operating sy stems equal. This is why I am not say ing that
Linux is better than Windows because it is f ree; that is not quite right. But y
ou will see that Linux is better because it is more f lexible, more reliable, and,
if it is conf igured properly, more ef f icient. These properties are more
important than the price, and y ou will see that all of them are inherent to
Linux. Consider the main Linux distributions av ailable on the market.
Remember that Linux is just the kernel, and most of the application sof tware,
serv ices, and graphical shells are prov ided by third-party dev elopers.
Exactly which application sof tware is supplied with the operating sy stem
depends on the distribution's dev eloper.
This distribution is considered the classic and the trendsetter of this operating
sy stem, because the creator of Linux, Linus Torv alds, works f or Red Hat.
You can either purchase this distribution or download it f or f ree f rom the
company 's site at www.redhat.com. Red Hat produces two v ersions of its
Linux distribution: one f or serv er solutions and one f or client computers.
The interf ace of the latter v ersion is becoming increasingly userf riendly and
is suitable f or any home task.
Installing this distribution has been easy and conv enient f or a long time. I
will consider installing Red Hat inChapter 2, and y ou will see that there is
nothing dif f icult about it.
All Linux distributions hav e a bad reputation f or not being user-f riendly
where application sof tware installation is concerned. The latter is usually
supplied as the source code that has to be compiled. Red Hat made installing
programs, including the Linux kernel, easy with the help of the Red Hat
Package Manager (RPM), which may be v iewed as a counterpart of the
Windows installer.
Many Linux enthusiasts hope that the Red Hat initiativ es will make their f av
orite operating sy stem easy f or ev ery one to use and enable it to mov e
ahead of the competition.
I hav e worked with v arious sof tware packages produced by German dev
elopers and can say that describing their usability as "leav ing a lot to be
desired" would be a gross understatement. Their programs, at least those that
I had the misf ortune of working with, are cripples f rom birth. But the Linux
kernel f rom SUSE (www.novell.com/Unux/suse/) is a pleasant exception.
This distribution has a nice interf ace, and its huge database of driv ers prov
ides excellent hardware support. SUSE programmers hav e also added a
utility collection named YaST to the distribution, which makes administering
it much easier. But as y ou will see, although the ease of use is a desirable
quality, maximum ef f iciency can be achiev ed only by directly editing conf
iguration f iles.
1.5.4. Debian
There are many other distributions, spanning the range f rom large and
powerf ul sy stems including all necessary sof tware to small distributions f
itting on a diskette and running on old computers.
It would be dif f icult to describe all of them in one book, and there is no need
to do so. The main intention of this book is to teach y ou how to create a
secure and ef f icient sy stem. This is dif f icult to accomplish because of the
large number of distributions; security specif ics can dif f er among
distributions and ev en among kernel v ersions.
Another dif f icult task is partitioning disks. Linux requires at least two
partitions: the root partition and the swap f ile partition. Many people are
apprehensiv e of tinkering with disk partitioning, especially if the disk
already contains inf ormation on it. This apprehension is f ully justif ied,
because there is alway s a chance of losing the inf ormation if the instructions
are not f ollowed correctly or if the power is lost and the computer is not
powered f rom an uninterruptible power supply (UPS).
During the installation process, any operating sy stem must detect the
hardware dev ices installed, install the necessary driv ers, and make other
preparations necessary f or the dev ices to f unction properly. Only about 7 y
ears ago, the list of the supported dev ices could be read through in a couple
of minutes, because many dev ice manuf acturers ignored Linux and did not
prov ide their dev ices with Linux driv ers. Moreov er, they did not prov ide
the inf ormation about their dev ices that would allow third parties to write
driv ers f or them. Nowaday s, reading through the dev ice list will take day s,
because the penguin (an emblem of Linux) is recognized by all important
computer dev ice manuf acturers. The sy stem now determines dev ices
rapidly and without errors, requiring no user inv olv ement in most cases.
I also would like to recommend installing the latest v ersion of both the
kernel and the application sof tware of whatev er distribution y ou decide on.
The reason f or this is, as already mentioned, that the sof tware errors discov
ered in the earlier v ersions are f ixed in the latest v ersion. To this end,
updating y our kernel and application sof tware is also highly adv isable. If y
ou install an older distribution, y ou will hav e to update too many programs.
It is better to install all new stuf f f rom the get-go to av oid the trouble of
installing updates and put y our serv er in commission right away.
Well then, let's get down to considering the installation process. First, y ou
will hav e to prepare the hard disk f or installing the operating sy stem. If y
ou are installing Linux on a new computer with a hard disk that is not
partitioned, and if y ou are planning on using this operating sy stem only, y
ou don't hav e to do any thing with the disk; simply allocate all av ailable disk
space to Linux.
But if y ou already hav e Windows installed and want to keep it, y ou will
hav e to do some work. In this case, y ou must hav e some f ree disk space —
f ree not in the sense of av ailable space on the C: driv e but in the sense of
disk space not allocated at all. Newer distributions hav e capabilities to
release disk space during the installation. But if y our distribution is not one
of these, y ou will hav e to use a third-party utility, such as PartitionMagic
(www.powerquest.com/partitionmagic).
Your task is to reduce the size of the C: disk, to f ree the space on the phy
sical disk that can be used to create a new logical disk, on which to install
Linux.
Select disk C: in the lef t panel or at its graphical representation on the right.
Click the Resize partitions button at the bottom of the window. This will
open a dialog window, in which y ou can specif y a new size f or the logical
disk C:. You should hav e at least 4 GB or more of disk space to install
Linux. So if , f or example, the size of the logical disk is 20 GB, specif y ing
the new size as 16 GB will release 4 GB. Click the Exit button to apply the
changes. The program will ask y ou to conf irm the changes and may inf orm
y ou of the need to reboot in the Disk Operating Sy stem (DOS) mode, to
which y ou should agree. The rest of the procedure will be carried out
automatically, and when it is f inished, the size of the logical disk will be
reduced to the specif ied, and necessary disk space f reed.
First, y ou will see text lines on the screen reporting the results of testing the
computer, installed hard disk driv es, CD-ROM driv es, mouse, v ideo card,
monitor, and other hardware. This may seem unf amiliar and intimidating,
but there is nothing unusual about this. Windows also tests the sy stem during
the boot process; it simply does not show the results to the user.
Af ter it f inishes testing the hardware, the Linux installer switches into the
graphical mode and opens the dialog window to select the language to be
used during the installation. Select the language y ou are most comf ortable
with, and click the Next button.
This will open the Keyboard Configuration window (Fig. 2.2). Select the
necessary key board lay out and click the Next button again.
Figure 2.2:
TheKeyboard Configurationdialog
window
The next step is selecting the mouse ty pe. The installation program does not
trust its own judgment in this respect, and rightly so. Almost alway s when I
install Linux, the installer determines the mouse as the two-button PS/2 ty pe.
It does not ev en attempt to look f or the third button. It's no big deal, because
almost alway s only two mouse buttons are used in Linux. I, howev er, alway
s select a three-button mouse.
The mouse selection dialog window contains a list of mouse manuf acturers
in the lef t panel and a list of known dev ices of the selected manuf acturer in
the right panel. To keep things simple, select the Generic manuf acturer (this
conf iguration will work with dev ices f rom any manuf acturer); in the list in
the right window, select the dev ice with the correct number of buttons and
connection. The mouse-connection ty pe is shown to the right of the mouse in
parentheses and can be one of the f ollowing:
PS/2 — The modern port f or connecting input dev ices such as the key board
and mouse.
USB — Becoming an increasingly common univ ersal interf ace used with v
arious dev ices.
Serial — Also known as the COM port and is used in older mice and
computers. It is dif f icult to f ind a mouse with this interf ace nowaday s.
The next step af ter selecting the mouse is to select one of the f ollowing
installation ty pes:
Dif f erent distributions may of f er other choices than the f irst three just
listed, but most of them should include the Custom item. I recommend
selecting this ty pe of installation so that y ou hav e control ov er which sof
tware packages to install.
The next step is selecting the disk, onto which to install the operating sy
stem. This may present some dif f iculties, so I will describe this process in
more detail.
Remove all Linux partitions on this system — Selecting this option will
remov e only Linux partitions (if there are such f rom prev ious Linux
installations). No other partitions (such as 32-bit File Allocation Table, or
FAT32, and the new technology f ile sy stem, or NTFS) will be remov ed.
Remove all partitions on this system — Selecting this option will remov e
all existing partitions on y our hard disk (or disks, if y ou hav e more than one
hard disk driv e). This option is suitable when the operating sy stem being
installed will be the only one on the computer. In this case, the installation
program will select how much disk space to allocate to specif ic operating sy
stem components.
Keep all partitions and use existing free space — If there already is an
operating sy stem on this computer that y ou want to keep and y ou hav e
released disk space using a partition utility (such as PartitionMagic), y ou
should select this option. The installation program will create disks f or Linux
based on the amount of f ree space on the phy sical disk
In Linux, the disk-naming method is dif f erent f rom the one used in
Windows. There are no disks A:, C:, etc. in Linux. Instead, disks are named
as /dev /hdnX, where n is the phy sical disk letter (assigned as a, b, c, etc.)
and X is the primary or extended partition number or the logical disk number.
There can be up to f our primary partitions or three primary and one extended
partitions on a phy sical disk. Consequently, numbers f rom 1 to 4 are reserv
ed f or the primary and/or extended partitions. Logical disks in the extended
partition are giv en numbers starting with 5.
It may seem complicated at f irst, but the f ollowing example should make it
simple. Suppose y ou hav e two phy sical hard disk driv es on y our sy stem.
The f irst driv e is partitioned into a primary partition and an extended
partition. Furthermore, y ou div ide the extended partition on the f irst phy
sical driv e into two logical driv es. The second hard driv e has one primary
partition and one extended partition. Linux labels this arrangement as f
ollows:
/dev /hda — The f irst phy sical hard driv e
/dev /hdal — The primary partition on the f irst phy sical driv e
/dev /hda2 — The extended partition of the f irst phy sical driv e
/dev /hda5 — The f irst logical disk on the extended partition of the f irst phy
sical driv e
/dev /hda6 — The second logical disk on the extended partition of the f irst
phy sical driv e
/dev /hdb — The second phy sical hard driv e
/dev /hdb1 — The primary partition on the second phy sical driv e /dev /hdb2
— The extended partition on the second phy sical driv e
/dev /hdb5 — The logical disk on the extended partition of the second phy
sical driv e
The f irst logical disk on the extended partition of the f irst phy sical hard driv
e was assigned the number 5. The number 6 was assigned to the second
logical disk on the extended partition of the f irst phy sical hard driv e. The
logical disk on the extended partition of the second phy sical hard driv e was
also giv en the number 5.
Now, look at the f ile sy stems supported by Linux. This operating sy stem
supports v arious f ile sy stems, including the FAT, FAT32, and NTFS
Windows f ile sy stems. It is adv isable, howev er, to install Linux on its own
Ext2, Ext3, or ReiserFS (of ten shortened to just Reiser) f ile sy stem. The
Reiser f ile sy stem is the latest dev elopment and is based on a concept called
journaling. This makes this f ile sy stem more stable and the af ter-crash
recov er process much f aster. Thus, it is pref erable to install Linux on this f
ile sy stem.
To help choosing the optimal f ile sy stem, consider the basic operating
principles of the main f ile sy stems. With the Ext2 f ile sy stem, the data are
cached f irst and only then written to the disk, which makes f ile operations
highly ef f icient. Howev er, if there is a power outage or the sy stem crashes,
some of the data in the cache may not hav e been written to the disk and the f
ile sy stem will become corrupted. The next time the operating sy stem boots,
it will detect that the integrity of the f ile sy stem has been corrupted and will
run the f sck (a riv al of the Windows' scandisk) disk-checking utility to
detect and correct any potential damages. This will restore the disk's
operability but not the data. Moreov er, the scanning process takes a long
time, which adv ersely af f ects the speed, with which the serv er is put back
into operation. Consequently, be prepared f or the sy stem to take a longer
time to boot af ter a crash.
With the Reiser f ile sy stem, data are also cached bef ore being written to the
disk. But unlike with Ext2, af ter the data were written to the disk, their
integrity is checked and only if the write was successf ul is the cache cleared.
In case of a crash or power outage, upon the next boot, the journal record is
used to detect corrupted data and to "back out" these data, thereby prev enting
most data corruption and restoring the disk operability more rapidly than with
other f ile sy stems.
The Reiser f ile sy stem has another adv antage ov er other f ile sy stems.
Data are usually written to the disk in blocks. Assume that the size of a block
is 1 KB. Then, f or example, a 100-by te f ile written to the disk in FAT32
will occupy the whole block, with 90% of the block space being wasted.
Consequently, the amount of data that can actually be stored on a disk will be
slightly less than the disk size; if lots of small f iles are stored on the disk, the
waste will be ev en greater. The Reiser f ile sy stem prov ides more ef f icient
use of the disk space.
Disk waste in Windows can be demonstrated by opening a f ile's Properties
window (Fig. 2.3). Take note of the Size and Size on disk parameters. The f
ormer is the f ile's size and the latter is the disk space the f ile occupies. The
size of a disk cluster is 4 KB, or 4,096 by tes. The f ile is 973 by tes larger
than the cluster size, so another cluster is allocated to store these 973 by tes.
No more data can be stored in the second cluster, resulting in more than 75%
of its storage space being wasted.
The Ext3 f ile sy stem is another journaling f ile sy stem, which is analogous
to the Reiser f ile sy stem. Currently, it is the def ault f ile sy stem in most
modern Linux distributions. It is dif f icult to compare the perf ormance of
the Reiser and the Ext3 f iles sy stems, but f rom the reliability standpoint I
adv ise y ou to agree with the dev elopers and use the latter.
2.3.3. Manual Partitioning
The large panel in the lower right part of the window contains the list of
disks, including the f ree disk space. In this case, there is only one disk: /dev
/sda. Below the disk name, there usually is the table of the disk partition. As
can be seen in Fig. 2.4, there are no partitions on this disk.
To create a partition in the f ree disk space, click the New button. This will
open the Add Partition dialog window (Fig. 2.5).
Figure 2.5: TheAdd
Partitiondialog window
Select the f ile-sy stem ty pe in the File System Type dropdown list. As was
already stated, the most pref erable f ile sy stem f or Linux is Ext3, and this is
the ty pe of the f ile sy stem I recommend that y ou select.
The size of the new partition is set in the Size (MB) list box, either by ty ping
it into the entry f ield or by using the scroll buttons.
The ty pe of partition is selected f rom the Mount Point dropdown list.
The list of partitions that can be created, and their f unctions are listed in
Table 2.1. The exact list v aries f or dif f erent distributions.
Table 2.1: Linux Partitions
Partition Description
Root partition. While in Windows a path starts with the / name of the disk, in
Linux the path starts with the root
(depicted with a slash).
/bin Sy stem's main executable f iles. /boot Files necessary to boot the sy
stem. /dev Represents the dev ices attached. /etc Stores sy stem conf iguration
f iles. /home User f iles. /lib Contains binaries to support executables. /opt
Optional sof tware packages. /proc Files used f or mounting the v irtual f ile
sy stem. /sbin Executable f iles of the main (root) user. /tmp Temporary f iles.
/usr Stores sy stem f iles. /v ar Log, spool, or lock f iles. swap Swap f ile.
Note that, with the exception of the f irst and the last partitions in the table
(root and swap, respectiv ely ), the names of all partitions start with a slash.
This is because the root and the swap partitions are mandatory, while the rest
of the partitions can be represented as f olders in the root partition.
The swap partition alway s has to be a separate partition with its own f ile sy
stem. It cannot be represented as a f older in the root. The size of the swap
partition should be at least that of the installed sy stem memory. I recommend
making the swap partition at least 3 times the size of the installed sy stem
memory : It is possible that the memory will be extended in the f uture, but
changing the size of the swap f ile is a little complicated, requiring y ou to
edit the /etc/f stab f ile or use disk partitioning tools, such as f disk.
Linux requires at least two actual partitions: the root partition (denoted as /)
and the swap partition. The root partition can hav e any f ile ty pe except the
swap f ile ty pe. The swap partition can only hav e the swap f ile-ty pe sy
stem. The root partition is used to hold all f iles, and the swap partition is
used as v irtual memory to supplement the sy stem memory. The rest of the
partitions listed in Table 2.1 do not hav e to be created as actual disk
partitions but can be represented as f olders in the root partition.
/ — On the f irst phy sical hard driv e to hold all sy stem f iles swap — On
the f irst phy sical hard driv e /home — On the second phy sical hard driv e to
hold user f iles
It is adv isable to connect the disks to separate controllers; this will allow the
sy stem to work with them practically in parallel. In this way, the perf
ormance of the operating sy stem may be raised signif icantly, because Linux
can work with the sy stem and user f iles simultaneously.
If y ou are setting up a serv er, the /home and /v ar f olders are better to set up
on separate phy sical hard driv es. Placing these f olders on logical disks will
not produce the results desired.
How large should y ou make the partitions? The size of the swap partition
should be set depending on the amount of sy stem memory installed, as was
mentioned earlier. If the /v ar and /home partitions are placed on separate phy
sical driv es, 4 GB will be enough f or the root partition, although it can be
made larger.
If necessary, the /v ar and /home partitions can be placed on the same, the
largest, phy sical disk. But, in this case, allocate to the /home partition all
disk space lef t af ter other partitions. This partition is used to store user data,
which usually become v oluminous. Economizing on the space here will soon
result in users complaining about not being able to sav e results of their
games on the serv er. But if the technical characteristics of y our sy stem
allow this, place the /v ar and /home partitions each on an indiv idual phy
sical hard disk, as large as y ou can af f ord, and y ou will hav e no problems.
For a test sy stem, the simplest arrangement, with two partitions (the root and
the swap), will suf f ice.
Af ter partitioning the disk, the new partitions hav e to be f ormatted. Some
especially smart distributions will carry out this operation without asking any
questions.
When the sy stem is powered on, the boot loader will giv e y ou the choice of
into which operating sy stem to boot: Windows (if y ou hav e this operating
sy stem installed), Linux (or any of its kernels, if y ou hav e more than one
installed), or any other sy stem y ou hav e installed.
If y ou hav e selected not to install the boot loader into the MBR, I strongly
recommend creating a bootable diskette. It may come in handy in case the
Linux boot loader on the disk becomes corrupted, and it is the only way to
boot the computer into Linux if y ou installed it without a boot loader.
Depending on the Linux distribution, y ou will be giv en an opportunity to
create a bootable diskette during the installation process.
The next step is conf iguring the network. If there is only a single Dy namic
Host Conf iguration Protocol (DHCP) serv er in y our network, y ou can leav
e the def ault settings. If there are more serv ers in y our network or the
addresses hav e to be assigned manually, clear the check mark in the
Configure using DHCP checkbox.
All computer security specialists unanimously ask their users to use complex
passwords, but f ew of the latter f ollow those recommendations. Names,
meaningf ul words, birthday dates, and the like should not be used f or
passwords. These passwords can be easily compromised by a simple
dictionary -search method and, if there is already a dictionary of likely
passwords av ailable, this search will not take long.
Other v ariations of this method can be used, like replacing the original letters
with the letters to the right of them. Some replacement letters can also be
uppercase, which makes the password twice as dif f icult to pick. As y ou can
see, the method is surprisingly simple, but the passwords it produces are suf f
iciently dif f icult to pick.
There will be numerous ports opened and v arious serv ices running in the
operating sy stem, about which y ou do not y et hav e the slightest idea as to
their f unction and operation. As y ou know, there is no bug-f ree sof tware. It
is only a matter of time bef ore bugs are detected and, hopef ully, corrected. If
there is only one buggy daemon (a serv er program that processes client
requests), any hacker can penetrate y our sy stem and do whatev er he or she
likes in it.
For a work sy stem, I start by installing the bare operating sy stem, to which I
then add only the necessary components. Additional components can be
installed at any time, but remov ing an installed component is sometimes
tricky.
During the installation, the sof tware packages to install are selected in the
Package Group Selection dialog window (Fig. 2.8), which contains a list of
all components that can be installed div ided into groups. Packages that are to
be installed by def ault hav e their checkboxes marked. No serv er program is
installed by def ault, which is just f ine. Howev er, if y ou know that y ou
need to install some serv er, y ou can put a mark into its checkbox to hav e it
installed automatically.
Figure 2.8:
ThePackage Group Selectiondialog
window
Linux components can usually comprise more than one application. For
example, the Editor component contains f our text editors. To change which
particular text editor will be installed, click the Details label to open the list
of the av ailable components. Here y ou can v iew components that are av
ailable, and select those y ou want to install.
Take y our time and go through all the packages in the list. Select only the
most necessary components; y ou will be able to add other components af ter
the installation. Remember that during the installation stage, y ou are lay ing
the f oundation f or the f uture ef f iciency and security of y our sy stem.
Hav ing selected all necessary sof tware packages, click the Next button. This
will take y ou to the About to Install dialog window (Fig. 2.9). This is the
last point, at which y ou can go back to the beginning of the installation
process or saf ely abort the installation. Clicking the Next button will start the
process of writing the sy stem to the hard driv e, which cannot be undone.
The installation process will take a little while, during which y ou can make y
ourself a cup of cof f ee and ev en watch a short mov ie.
While the installation is under way, let me tell y ou more about this process
so that y ou will hav e the necessary knowledge when it is time to conf igure
the sy stem. Suppose that y ou must hav e three serv ers on y our network: a
Web serv er, an FTP serv er, and a news serv er. The security aspects of
running all three serv ers on one computer will be f ar f rom ideal. I alway s
install indiv idual serv ers on separate computers and adv ise that y ou don't
economize on hardware but do the same.
Each running daemon is a potential security hole. You already know that all
sof tware packages hav e bugs in them and that administrators are of ten not
the f irst ones to f ind this out. Assume that a bug was discov ered in the
Apache serv er. This sort of thing happens rarely of late, because the program
has been well debugged, but y ou can imagine such a situation f or the sake of
an example. Moreov er, the bug may be not in Apache but in the Web serv er
that it serv ices, or in the PHP/Perl interpreter. In any case, a hacker can take
adv antage of this hole to obtain access to y our computer. Once in the
computer, he or she can easily obtain access to, f or example, the FTP serv er
and download all secret data that y ou may hav e on the computer. But if y ou
hav e only a Web serv er running on the particular computer, the access to
conf idential data using the FTP serv er will not be that easy. The most that
the hacker will be able to do is def ace or destroy the site. And ev en though
this is not pleasant, restoring the home page or ev en the entire site is much
easier than reconstructing all FTP or newsserv er data.
To prev ent the malef actor f rom penetrating other network computers af ter
breaking into one of them, y ou should set a dif f erent password f or each
computer. Some administrators are too lazy to memorize many passwords
and use one password ev ery where. I will cov er the password subject in
more detail inChapter 4, but f or now y ou should know that y ou hav e to use
an indiv idual access password f or each sy stem.
Daemons are not the only potential problem. Many programs are included
into Linux as source codes and hav e to be compiled bef ore execution.
Programs taking adv antage of the v ulnerabilities of Linux sy stems also
come as source codes. To use them, the malef actor uploads such a module
on a serv er and executes the program. To make it impossible to compile
source codes, I adv ise y ou not to install dev elopment libraries and the GNU
C (GCC) compiler.
Program installers are seldom used in Linux; theref ore, all conf igurations
are perf ormed when the source codes are compiled. With GCC unav ailable,
the malef actor will hav e problems executing malicious code.
An experienced hacker can assemble a program f rom the source codes on his
or her own computer and then upload it onto the compromised serv er f or
execution, circumv enting the need f or the GCC compiler. A nov ice hacker,
howev er, may be nonplussed by not hav ing the compiler av ailable on the
target machine. And any problem f aced by hackers is a v ictory f or the
security specialist.
If y ou are just cutting y our teeth in the Linux world, I recommend that y ou
install the linuxconf sof tware package, which makes administering tasks
much easier. When learning y our way around Linux, y ou will see that many
of its settings are conf igured by manually editing conf iguration f iles. This
task has been made easier of late by numerous conf iguration utilities with a
graphical interf ace, linuxconf being one of them.
But if y ou are not daunted by the task of conf iguring the sy stem manually, I
recommend going about it this way : Conf iguration utilities with graphical
interf ace of ten introduce unsaf e parameters into the sy stem conf iguration,
or allow serv ice access rights that are too priv ileged. It is a good idea, theref
ore, to examine the modif ications made by the program, a task that requires
excellent knowledge of the structure and content of the conf iguration f iles.
Af ter the f iles are copied to the disk, the sy stem of f ers to conf igure the v
ideo sy stem. This is done in the Monitor Configuration dialog window
(Fig. 2.10).
Select the correct v ideo card and monitor and the display characteristics. If y
ou make a mistake here, y ou will hav e to start y our work with Linux with
the command line instead of the graphical interf ace. Later in this chapter, I
will show y ou how to conf igure the monitor f rom the command line.
The most important of these is creating a sy stem user. This is done in the
User Account dialog window (Fig. 2.12). You can use the root account f or
working with the sy stem, but this is not recommended. It is adv isable that ev
en the administrator enters the sy stem as a regular user (perhaps, with
slightly higher priv ileges to access the necessary f unctions). The root
account should be used only f or the most extreme needs.
Figure 2.12: TheUser
Accountdialog window
Af ter f inishing the f irst boot setup, the sy stem boots.
The f irst stage of the boot process in Linux is the same as in Windows: The
memory is tested, disks are determined, and inf ormation about the hardware
sy stem is display ed. When this process is ov er, the dialog window of the
boot loader selected inSection 2.4is display ed (Fig. 2.13).
Figure 2.13: The boot loader dialog window
Because I hav e only Linux installed, the only option is to boot into this sy
stem. If y ou had other operating sy stems or Linux kernels installed, they
would also be of f ered f or booting in the boot loader menu. Windows and
Linux can peacef ully coexist on the same computer. I must note, howev er,
that Windows XP and older Linux boot loaders, such as LILO, do not get
along with each other. It looks like Windows XP would brook no competition
and kill LILO. Modern Linux loaders are more capable and can stand up f or
themselv es.
Boot loaders in some Linux distributions, including Red Hat, may use the
command prompt instead of a graphical menu to select the operating sy stem.
Af ter the computer starts, a command line prompt to enter the necessary
operating sy stem is display ed as f ollows:
LILO boot:
The def ault operating sy stem is loaded by simply pressing the <Enter> key ;
alternativ e operating sy stems are loaded by entering its name f rom the key
board and then pressing the <Enter> key. Instead of ty ping the operating sy
stem into which to boot, y ou can use the key board arrow key s or the <Tab>
key to nav igate through the av ailable choices.
Af ter the selected operating sy stem (Linux in this case) starts booting, inf
ormation about dev ices detected, v ersions of v arious modules, and so on, is
display ed on the black background as white text (Fig. 2.14).
Figure 2.14: The
Linux booting process
At one point y ou will see the message say ing "Welcome to Red Hat Linux.
Press 'I' to enter interactiv e startup." (See Fig. 2.14.) Pressing the <I> key
will make the sy stem ask y our conf irmation bef ore loading another serv
ice. This is a handy f eature in case the sy stem becomes corrupted and some
serv ice causes the sy stem to hang. For example, in my experience, installing
the sendmail daemon of ten causes problems. When this happens, the
operating sy stem cannot boot. The situation is resolv ed by simply rebooting
the computer, entering the interactiv e mode, and ref using to load the
sendmail serv ice.
Linux is a multiuser operating sy stem. This means that sev eral people can
work on the same machine at the same time. The operating sy stem needs to
know the current user, so af ter it boots the sy stem will ask y ou to enter y
our login and password. The login identif ies y ou, and the password prev
ents someone else f rom entering the sy stem under y our name.
The user identif ication process in the text mode starts with the prompt to
enter y our login:
localhost login:
Then y ou hav e to enter the password to prov e to the operating sy stem that
y ou are who y ou say y ou are.
If y ou pref er to use the graphical interf ace to enter the sy stem, y ou can do
this in the dialog window like the one shown in Fig. 2.15. I say "like the one"
because the login window may dif f er in dif f erent Linux distributions.
Bef ore entering y our login, take a good look around the window. There is
menu in it containing the f ollowing f our items:
Language — The def ault language is English, but y ou can choose any other
av ailable language. Linux supports an extensiv e choice of languages that is
constantly expanding.
Session — This allows y ou to select the graphical interf ace. In this book, I
will mostly use the KDE and GNOME interf aces because they are the most
commonly used. Which graphical interf ace y ou select is up to y ou.
The Session menu item has an interesting subitem: Failsafe. Select this item
if there are errors in the sy stem conf iguration and the graphical interf ace
cannot launch. This will open the command line console bef ore the graphical
interf ace launches, and in it y ou can correct the problem.
Af ter setting the necessary parameters, enter y our login and password. Thus
y ou can enter the graphical world of Linux. But which account should y ou
log in under? During the installation y ou set the sy stem administrator (root)
password and added a user during the f irst-boot conf iguration. I strongly
recommend entering the sy stem under the user account, because the root
account allows the highest rank of priv ileges. This totalitarian control of ten
caused grief when administrators inadv ertently deleted some important data
when conducting some sy stem testing.
Working under the root account makes it easier to break into the computer
through seemingly the simplest applications. Suppose y ou logged in as root
and then decided to do some Web surf ing. The browser that y ou launch f or
this will hav e the root priv ileges. If there is a v ulnerability in the browser
allowing hard disk access, miscreants can take adv antage of this loophole to
break into y our computer and hav e access to whatev er the root user does.
or
su
When y ou enter the command, the sy stem will ask y ou to supply the
appropriate password. If y ou enter the password of the user whose priv
ileges y ou want to obtain, y ou will obtain the priv ileges requested. Hav ing
obtained the necessary priv ileges, y ou can do with the sy stem what the new
priv ileges allow. With administrator priv ileges, y ou are allowed to do ev
ery thing.
The multiple console f eature is a handy one. For example, in one console y
ou can start a program that takes a long time to execute, then y ou can switch
to another console and continue with other tasks in it. You can return to the f
irst console at any moment to check the program's execution.
You can switch into the graphical mode f rom the text mode at any time by
entering thestartxcommand in the command line. In this case, the graphical
shell will be loaded without asking y ou to prov ide the password because y
ou hav e already identif ied y ourself (when logging into the sy stem in the
text mode).
You may hav e to log into the sy stem in the text mode if the graphical login
window cannot be display ed f or some reason, f or example, because of conf
iguration errors. In this case, executing thestartxcommand will hav e no ef f
ect, because the graphical shell will not be able to load, and y ou will hav e to
conf igure the display settings anew. Most Linux conf iguration inf ormation
is stored in text f iles, which of ten hav e to be edited manually. Graphics
conf iguration inf ormation is also stored in text f iles, but it is not necessary
to edit them manually. You conf igure the sy stem with the help of the special
setup utility with the graphical interf ace. Enter the setup command in the
command line. This will open the window shown in Fig. 2.16. Select the X
configuration item in the list. The sy stem will, most likely, determine the v
ideo card and the driv ers necessary ; howev er, it may hav e problems
properly identif y ing the monitor and selecting the v ideo modes it supports.
In most cases, this task requires human interv ention.
Figure 2.16: The main
window of the setup utility
All possible monitor modes will be listed, and y ou can specif y any number
of them. Howev er, I recommend selecting only the mode that y ou f eel most
comf ortable working with. Make sure to test the selected graphical mode to
ensure that it works properly. If the conf iguration settings selected are
acceptable, the program will of f er to let y ou enter the sy stem using the
graphical mode.
The conf iguration can be perf ormed using the mouse, but, if f or some
reason the mouse is unav ailable, it can be done using the key board. Use the
<Tab> key to mov e f rom one button to another, the space bar to select menu
items, and the <↑> and <↓> arrows to mov e between list items.
The last time I had problems conf iguring a v ideo card (a cheap Chinese job
on the S3 chipset) was about 3 y ears ago under Red Hat 6.1. Modern
distributions hav e no problems determining hardware components of the sy
stem, especially brand-name ones.
Fig. 2.17 shows the KDE graphical shell, and Fig. 2.18 shows the GNOME
graphical shell.
Figure 2.17: The KDE
desktop
The lef tmost button (the one depicted as a red hat) is used to open the main
menu. It is an analogue of the Start button in Windows. The main menu
contains all programs and utilities installed on the computer.
Next are the rapid program-launch buttons. The red-f ramed button on both
desktops launches the terminal program.
The empty space to the right of the rapid-launch buttons is the actual task bar;
the icons f or the running programs — tasks — are display ed here. The task
buttons can be used to switch among running tasks.
Open the terminal window to see what it looks like. In most distributions, it is
a window with the black background and white text. Af ter launching, a
command prompt is display ed that can look like the f ollowing:
[root@Flenov root]:
What does it mean? First is the name, under which y ou entered the sy stem,
rootin this case. The computer name f ollows the @character, then space, and
then the name of the current f older.
User directories are located in the /home directory and are named by the
user's name. For example, the f ull name of the root user's directory is
/home/root/. The f iles of the root user are stored in this directory.
When a user enters the sy stem, his or her directory becomes the current
directory. Thus, when the root user enters the sy stem, the /home/root
directory becomes the current directory, and all commands will be executed
in this directory until another directory becomes current.
There are sev eral command shells in Linux, and each of them of f ers specif
ic f eatures. I will consider the Bourne Again Shell (bash), because it is the
one used most of ten.
When I was only cutting my teeth on Linux, af ter I installed it f or the f irst
time, I could not turn it of f correctly f or a long time because I did not know
what command to use to do this. I borrowed a Linux ref erence book f rom an
acquaintance to f ind out how to power down the sy stem properly. The
description of the power-of f procedure, howev er, was buried in the depths
of the book, and it took me about a month to read through to it. During all
this time I powered of f the sy stem by turning of f the computer.
So that y ou do not go through the same process, here is how to power down
the sy stem. This is done using theshutdowncommand. The command takes
sev eral parameters, the two most commonly used of which are-rto reboot
and-hto halt the computer af ter the shutdown. Also, the time, at which to
shut down the sy stem, must be specif ied at the end of the command.
For example, to reboot the sy stem right away, enter the f ollowing command:
shutdown -r now
To shut down the computer immediately, enter this command:
shutdown -h now
Do not shut down the computer in any other way ; alway s use this command.
Powering down the computer using the power button on the sy stem block is
f raught with the danger of losing data that were loaded into the memory but
not sav ed to the disk.
If y ou want to enter the sy stem under another name while working in the
text mode, y ou can do this with the help of the exitcommand.
To exit the sy stem when working in the graphical mode, click the main menu
button and select the Log Out item. This will unload the graphical shell, af
ter which the login screen will be display ed, in which y ou will be able to
enter the sy stem under another name or reboot the computer.
2.10. Help
Some operating sy stems are f amous f or being easy to use and f or of f ering
inf ormativ e help. But I will nev er tire of repeating that ef f iciency,
reliability, and being easy to use are not alway s compatible. There are many
commands in Linux, and each of them can be used with numerous
parameters. It is impossible to remember all of the commands and their
parameters, so the dev elopers hav e prov ided an extensiv e help program f
or the operating sy stem.
To obtain inf ormation about how to use a command or a program, enter its
name f ollowed by one of the f ollowing switches:-h, -help,or -?. Dif f erent
programs use their own switches and display short inf ormation about how to
use the program.
Here, nameis the name of the command or the program. For example, to v
iew the description of the shutdowncommand, enter man shutdownin the
command line.
To exit a help program, ty pe -e. This will produce the message "Quit at
endof -f ile (press RETURN)." Press the <Enter> key and then mov e to the
end of the help f ile, at which point the manprogram will terminate.
Run as f ew programs as possible. This concerns not only whole serv ices but
also their components. Suppose that y ou use the Apache Web serv er. This
program has many f eatures, among which is support of the PHP and Perl
interpreted languages. Site programmers, howev er, normally use only one of
these languages; consequently, there is no reason to enable both of them on y
our Apache serv er. If the site uses PHP, Perl should be disabled, and v ice v
ersa. If y our site uses both script languages, y ou should f ire y our
programmers: Mongrel sy stems are much more dif f icult to make secure.
Def ault settings are intended f or training purposes only, and most of ten
enable all f eatures so that y ou can ev aluate the program's capabilities.
Enabling all f eatures v iolates the second rule of minimization.
If conf iguring the program does not inv olv e many commands and
parameters, it can be conf igured f rom scratch. But if the procedure is
complex (a good example is conf iguring the sendmail program), the best
option is to start with the def ault settings and then modif y them as
necessary. Don't try to conf igure a complex program f rom scratch. More
likely than not, y ou will f orget something and make some error with the
conf iguration. Conf iguration f iles are dif f icult to work with because they
are in the text f ormat and the names of all parameters must be written
without the slightest error. If at least one character is entered incorrectly, the
parameter will not f unction properly or at all, and the operating sy stem or
the serv ice will work with errors.
When writing a parameter name or a f ile sy stem path, pay close attention
not only to spelling but also to the use of the uppercase and lowercase
characters. Linux is case-sensitiv e where names of f iles and directories are
concerned. The same applies to some conf iguration f iles.
During the installation, many serv ices set def ault passwords. This problem
is especially serious in Linux, because installation programs use RPM
packages that most of ten do not ev en of f er to change the def ault
passwords. If I were in the dev elopers' shoes, I would make it impossible to
start serv ices with no or def ault passwords.
Bef ore putting a sy stem into commission, make sure that all of its passwords
hav e been changed. Here is another example using My SQL. Administrators
rarely use this database themselv es; they only install it. The conf iguration is
usually perf ormed by the programmers, who tune databases to their personal
pref erences and, f or some reason, like to use def ault passwords. I am a
programmer and, when dev eloping databases, use def ault passwords, hoping
that the administrator will take care of changing the passwords, but, as stated
earlier, they seldom do.
Not only application programs and operating sy stems but also network dev
ices, such as routers and intelligent switches, use def ault passwords. These
dev ices hav e a built-in protection and authorization sy stem. When
initializing this sy stem, the manuf acturers don't bother with inv enting
account names and most of ten use Admin; the password is usually lef t blank
altogether. This is a big ov ersight. A good idea in this case would be to use
the dev ice's serial number as its password. It is easy f or the manuf acturer to
come up with and f or the user to remember but dif f icult f or hackers to
pick. But ev en using the serial number does not guarantee total protection,
because if a hacker sees the dev ice, he or she can take a crack at its serial
number being used as the password.
Lists of def ault passwords f or v arious dev ices hav e been av ailable on the
Internet f or a long time; thus, do not f orget to change the passwords af ter
installing a dev ice.
BIOS manuf acturers used to install univ ersal access codes into their chips,
which made it possible to enter the sy stem without knowing the main
password, installed by the administrator. For example, one of the Award
BIOS v ersions used AWARD_SW as a univ ersal password. Starting with v
ersion 4.51, this "serv ice" is no longer av ailable.
I already mentioned that security and perf ormance pursue two dif f erent
goals. Conf iguring the serv er f or maximum security requires enabling such
serv ices as logging, f irewalls, and the like, which lay their claim on
processor resources. The more serv ices enabled, the more sy stem resources
they use.
Each serv ice can be conf igured in dif f erent way s. For example, the
logging mode can be conf igured to log only the most important inf ormation.
This reduces the workload on the hard driv e but increases the chances of an
attack going unnoticed. The other extreme is to conf igure logging to log all
messages. Contrary to what y ou may think, this will not enhance the
security, because the increased resource consumption f acilitates carry ing out
a successf ul DoS attack.
When conf iguring a serv er and its serv ices, y ou must be guided by the
principle of necessary suf f iciency. This means that y ou should do ev ery
thing possible to make the serv er secure while keeping its perf ormance as
high as possible. To ascertain that this balance is achiev ed, the serv er should
be tested at the maximum workload possible. The latter is def ined as twice
the number of requests per minute that the serv er is expected to serv ice. If
the serv er is up to the task and can handle all client requests with processor
resources to spare, the sy stem can be put into serv ice. Otherwise, either the
conf iguration should be changed or the computer's capacity should be
enhanced.
We will take a close look at the f ile sy stem, the main conf iguration f iles,
and commands f or ev ery day work. Linux can work in two modes: graphical
and text. Many authors f or some reason consider only the text mode. This
intimidates those readers who are used to Windows with its intuitiv e interf
ace. I will consider both modes in parallel. Nev ertheless, the console will be
giv en more attention, because many problems of ten can be solv ed much f
aster using the console than using graphical utilities. I will try to show y ou
the adv antages of using the console ov er using the mouse. Commercial serv
ers of ten are placed in separate rooms and of ten are not ev en equipped with
a monitor. They are controlled through a remote console without using Linux
graphical f eatures. Why, then, waste memory by loading bulky graphics
libraries, f iles, and other resources? You will be better of f to preserv e it f or
other, more usef ul things.
The graphical mode, howev er, is usef ul f or working with user utilities. It
can also be usef ul when doing the initial serv er conf iguration. Taking into
account that not all Linux computers are used as serv ers and that
workstations can run under this operating sy stem, a conv enient and easy -to-
use graphical interf ace f or Linux is simply a must.
As y ou can see, being able to work in two modes is one of the adv antages of
Linux, not a shortcoming. If y ou were to unload the graphical shell in
Windows and leav e only the command-line interf ace, y ou could conserv e
memory resources and increase the reliability of this operating sy stem. When
graphics libraries are not used, they cause no problems. Remember those blue
screens of death caused by buggy v ideo card driv ers? You will not see those
in the Linux console.
Fig. 3.1 shows Midnight Commander running in the terminal window. The
program's window is div ided into two panels; in each panel, shown are f iles
and f olders of the current directory. Folder names start with slashes. Use the
<Tab> key to switch between the panels.
The right panel shows the contents of the root f older. This is the highest lev
el of the f ile sy stem. Examining the names of the f olders in this panel, y ou
will see that most of them are those listed in Table 2.1. Each of these f olders
can be placed in its own disk partition, if y ou chose to do so during the
installation. But ev en in this case, the f ile sy stem will look as one whole.
In Section 2.3.3, the root directory was mentioned, designated in Linux as /.
This directory is the top of the py ramid in the directory hierarchy. For
example, user f olders are stored in the /home f older. Then, /home/f lenov is
the path to the subf older of user Flenov. To mov e to a directory, y ou
doubleclick it with the mouse. Or y ou can select the needed directory using
the <↑> or <↓> key and then press the <Enter> key.
There is alway s a f older named / ‥at the top of the list of f olders and f iles
in any f older. There is actually no f older with this name. This is only the
pointer to the parent directory of the current f older. For example, mov ing to
f older / ‥f rom the /home/jose f older, y ou mov e one lev el up to the
/home directory.
Below the Midnight Commander window (see Fig. 3.1), y ou can see the
command prompt. This is the same prompt as in the terminal and is used in
the same way. Farther below, legends f or the <F1> through <F10> key s are
located. The f unctions of these key s are as f ollows:
F5 Copy — Copies the selected f ile of the f older. Selecting a f ile and
pressing the <F5> key opens the copy operation conf irmation window. By
def ault, the selected f ile or f older is copied to the current directory in the
opposite Midnight Commander panel.
The names of conf iguration f iles and f olders start with a period. Be caref ul
when mov ing or editing them. These f iles need to be giv en maximum
protection, which I will talk about later in v arious sections of the book.
pwd
Thepwdcommand display s the f ull path of the current directory.
ls
The lscommand display s the contents (f iles and f olders) of the specif ied
directory. If the directory is not specif ied, the command display s the
contents of the current directory. By def ault, all conf iguration f iles (whose
names start with a period) are hidden. To display them, thelscommand is used
with the-aswitch:
ls -a
This command, howev er, will display the contents of the current directory.
To v iew the contents of a directory other than the current one, f or example,
/etc, the necessary f older is specif ied af ter (or bef ore) the switches: ls -al
/etc
You can obtain more detailed inf ormation about the ls Note command f rom
the help sy stem by executing the f ollowing
command:man ls.
By def ault, the list of a f older's f iles and subf olders is display ed in sev eral
columns. Consider what inf ormation is display ed in each column using the f
irst line as an example:
Flenov is the name of the f ile's owner. FlenovGis the group, to which the f
ile belongs.
4096 is the f ile size. Because a directory has no f ile size, the
4096 v alue is not the actual f ile size but just a placeholder, and all
directories hav e this v alue in this column.
The sixth column shows the date and time the f ile was last changed.
The f inal column giv es the f ile name.
cat
The catcommand display s the contents of the f ile specif ied in the
command's argument. For example, to v iew the need.txt text f ile, thecat
command is entered as f ollows:
cat need.txt
To v iew a f ile located in a f older other than the current one, the f ull path to
the f ile has to be specif ied:
cat /home/root/need.txt
tac
Thetaccommand is a v ersion of thecatcommand, only it display s the specif
ied f ile in the rev erse order, that is, starting f rom the end of the f ile.
cd
The cdcommand is used to change the current directory to the one specif ied
as its argument:
cd /home/flenov
To mov e f rom the /home f older to the /f lenov subf older, only the subf
older's name has to be entered as the argument:
cd flenov
To mov e a lev el up f rom the current subf older, the destination f older is
specif ied as two periods (‥):
cd ..
As y ou already know, two periods designate the parent f older of the current
f older, or the f older one-lev el up the current one.
cp
Thecpcommand is used f or copy ing f iles. The f ollowing copy ing options
are av ailable:
Copy ing the contents of a f ile to another document in the same f older.
cp /home/root/need.txt /home/root/need22.txt
Copy ing sev eral f iles to another f older. All source f iles are listed as
parameters; the destination f older is giv en as the last parameter.
cp /home/root/need.txt /home/root/need22.txt /home/new/
But what if y ou hav e to copy all f iles whose names start with an nf rom one
f older to another? Isn't there an easier way than listing all of them? Relax,
there is. You simply use then*mask, where*is a wildcard that stands f or the
rest of the f ile's name af ter thencharacter:
cp /home/root/n* /home/new/
If all f iles whose names start withraand end intneed to be copied, the
ra*tmask is used.
mkdir
The mkdircommand creates a new directory. For example, a directory named
newdir is created in the current directory by the f ollowing command: mkdir
newdir
rm
The rmcommand deletes a f ile or a directory. The directory being deleted
must be empty.
rm /home/flenov/need22.txt
The names of the f iles can be giv en using the same *wildcard character as in
thecpcommand. To delete a directory, the f ollowing switches may hav e to
be specif ied:
-d — Remov e a directory.
-r— Remov e the contents of the directories recursiv ely.
-f — Do not prompt to conf irm the deletion. Be caref ul when using the last
switch, because the f iles specif ied will be deleted without the sy stem asking
f or any conf irmation. Make sure that y ou hav e written correctly the names
of the f iles y ou want to delete.
df
The dfcommand is used to determine the amount of f ree space on a disk or a
partition. If no dev ice is specif ied, the inf ormation about all currently
counted f ile sy stems is display ed.
Why is the CD-ROM mounted onto the /mnt/cdrom directory ? And how did
the sy stem know where to mount it if the mount directory was not specif ied
in the command? Mounting a CD-ROM requires much more data than the
command mount /dev/cdromcan prov ide alone. These data are stored in two
sy stem f iles that describe the main def ault dev ices and parameters: f stab
and mtab. Let's examine these two f iles.
/dev/hdal none
proc /proc
none /dev/shm none /dev/pts/ /dev/cdrom /mnt/cdrom swap proc tmpfs devpts
gid=5,mode=620 0 iso9660 noauto,owner,kudzu,ro 0 sw 0 defaults 0 defaults
0
There are two entries f or the main disks in the f ile. The f ile's contents are
presented in six columns. Take a look at the f irst disk entry. It describes
mounting of the hda2 disk. In my f ile sy stem, this is the main disk, so the
second parameter is/. This means that the disk will be mounted as the root.
The third column describes the f ile sy stem, which isext3in this case. The
roparameter indicates that the dev ice is mounted f or read-only. The rw v
alue f or this parameter means that the dev ice is mounted f or both read and
write.
The penultimate entry in the f ile describes the CD-ROM dev ice. Take a
good look at the second parameter:/mnt/cdrom. This is how the sy stem
knows, which directory to mount the CD-ROM dev ice on. The f ourth
column display s mounting options, which can be used to describe security
parameters. In this case, there are sev eral options specif ied f or the
CDROM:noauto, owner, kudzu, ro. The roparameter specif ies that the
CDROM is mounted f or read-only operations. It would be logical to mount
all dev ices that could be used by hackers to extract inf ormation f rom the
serv er f or read-only operations.
The contents of the mtab f ile are similar to those of the stab f ile: # <file
system> <mount point> <type> <options> <dump> <pass> /dev/hda2 / ext3
rw,errors=remount-ro 0 proc /proc proc rw 0 none /dev/shm tmpfs rw 0 none
/dev/pts devpts rw,gid=5,mode=620 0 none /proc/sys/fs/binfmt_misc
binfmt_misc rw 0 /dev/cdrom /mnt/cdrom iso9660 ro,nosuid,nodev 0
If y ou created some on separate disks, y ou can conf igure them also. Earlier,
I recommended placing the /home partition containing user directories on a
separate disk. If y ou f ollowed my adv ice, there may be another entry in the
f ile looking similar to the f ollowing:
/dev/hda3 /home ext3 rw,errors=remount-ro 0 0
Take a look at the f ourth parameter. It specif ies mounting options, which
can be manipulated to enhance the security of the sy stem. The options are
separated by commas. The options in this case are rw, errors=remountro.
Other av ailable mounting options are the f ollowing:
noexec — Disables f ile execution. If y ou are certain that the partition should
hav e no executable f iles, y ou can use this option. For example, on some sy
stems, the /home directory is only intended f or storing documents. Setting
the noexec parameter f or this partition will prev ent hackers f rom placing
into this partition the programs that can be used to break into the sy stem.
Actually, it will be possible to place programs into this partition but
impossible to execute them.
nosuid — Disables the ef f ect of Set User IDentif ier (SUID) and Set Group
IDentif ier (SGID) bits in programs. There should be no programs with these
bits set in the /home partition so that priv ileged programs can be prohibited
explicitly. SUID and SGID programs will be explained in Section 4.5.
nodev— Disables access to character or special dev ice f iles on the partition.
nosymfollow— Disables sof t links. Thenodevandnosymfollowoptions are
not that important security -wise, but they can be usef ul in certain situations.
Suppose that y our site uses Perl language. If a Perl interpreter is accessible f
or execution, a hacker can launch Perl scripts in any partition, including those
with thenoexecparameter set. Launching a script f rom the command line will
produce a message about access rights v iolation. But the f ollowing
command will launch the program:
perl file.pl
Recall that in the mtab f ile using SUID and SGID programs is disabled f or
the CD-ROM driv e. The same should be done f or at least the /home and
/tmp partitions. This will prev ent users f rom creating priv ileged programs
in their directories, which in turn will prev ent many potential attacks.
Try to mount the CD-ROM driv e on a directory other than the def ault one.
For this, y ou hav e to create it f irst:
mkdir /mnt/cd
The f irst command creates the /mnt/v f at directory, on which the FAT32
disk will be mounted.
The second command mounts the /dev /hda3 disk on the just-created
directory. Assume that this is the disk containing a Windows f ile sy stem.
The-toption specif ies the ty pe of the mounted f ile sy stem. It is a mandatory
option when mounting a dev ice not described in the /etc/f stab f ile. Because
the necessary inf ormation f or the CD-ROM is in the /etc/f stab f ile, y ou did
not hav e to indicate the f ile sy stem when mounting the CDROM.
Thevfatparameter specif ies the FAT32 f ile sy stem. This is the name used
by Linux to designate this f ile sy stem.
umount
When the CD-ROM is mounted, this dev ice is blocked and the disc cannot
be remov ed until the dev ice is unmounted. A mounted dev ice is unmounted
using theumountcommand. Thus, a mounted CD-ROM is unmounted by the f
ollowing command: umount /dev/cdrom
fdformat
Bef ore a diskette can be used, it has to be f ormatted. Diskettes are f
ormatted using thefdformatcommand.
tar
In the course of using this book, y ou will sometimes install v arious
programs that come in tar.gz archiv es. Most of ten, these programs are stored
as source code. Files stored in tar.gz archiv es are extracted using the f
ollowing command:
tar xzvf file_name.tar.gz
The command creates a f older with the same name as archiv e (only without
the extension), into which the extracted f iles are placed. For now y ou just
hav e to be able to unpack archiv es and install additional sof tware and
thirdparty utilities.
rpm
Today, most programs are supplied not as source code but in RPM packages.
These are easier to install because they are already compiled. To install an
RPM program using Midnight Commander, select the necessary package and
press the <Enter> key. This will open the package as a directory and allow y
ou to v iew its contents.
/bin/ls
I will consider the access priv ileges in detail in Chapter 4. Access priv ileges
are the cornerstone of security, but y ou cannot rely solely on this tool.
Additional tools are necessary f or preserv ing the sy stem's integrity. At the
least, y ou should be able to monitor changes in the f iles, the main objects of
the operating sy stem. Files are where inf ormation is stored, and inf ormation
is what hackers are af ter. Hackers striv e to read, modif y, or ev en destroy
inf ormation; consequently, y ou should know how to control it.
Modification Time
The simplest control method is to monitor the f ile modif ication time.
Suppose that y our sy stem was penetrated at 10:30 a.m. To f ind out what f
iles hav e been changed, y ou can search f or all f iles whose modif ication
time is later than this time. This is easy to implement but not v ery ef f ectiv
e, because the modif ication time can be edited using thetouchcommand. The
complete command looks as f ollows:
touch parameters MMDDhhmmYY file_name
The date parameters are in uppercase, and the time parameters are in
lowercase. The f ormat is somewhat unusual but not impossible to remember.
If the y ear is not specif ied, the current y ear is used.
Consider an example. Suppose y ou want to set the modif ication time of the
/etc/passwd f ile to January 21 of the current y ear at 11:40 a.m. This is done
by executing the f ollowing command:
touch 01211140 /etc/passwd
Now execute thels -l /etc/passwdcommand to ascertain that the date and time
hav e been changed as intended.
Thetouchcommand can also be used to create f iles stamped with the
necessary date.
Although the modif ication time can be changed easily, the hacker may f
orget, run out of time, or not hav e enough priv ileges to do this.
Thus, all f iles that were modif ied af ter January 21, 2005, 11:40 a.m., can be
f ound by executing the f ollowing sequence of commands:
touch 0121114005 /tmp/tempfile
find /etc \(-newer /tmp/tempfile \) -ls
find /etc \(-cnewer /tmp/tempfile \) -ls
find /etc \(-anewer /tmp/tempfile \) -ls
The f irst command created a f ile named tempf ile with the ref erence modif
ication date in the temporary /tmp directory.
The next three commands actually search f or f iles. Each of them has the f
ollowing structure:
find directory \parameter( -search_criterion file_name \) -ls
The f unctions of each part of the command are the f ollowing: find— The
search program.
-newer— The f ile's modif ication time is later than that of the ref erence f ile.
-cnewer — The f ile's status was changed later than the time, at which the ref
erence f ile was modif ied.
-anewer— The f ile was accessed more recently than the ref erence f ile.
-ls parameter— Files meeting the criterion are display ed on the screen (as
when thelscommand is executed).
Checksums
The modif ication time f ile-control method, while prov iding some degree of
security, is f ar f rom perf ect. The best f ile control method is the checksum
calculation. Suppose y ou want to monitor changes to the /etc directory. You
can do this by executing the f ollowing command:
md5sum /etc/*
This command calculates the checksum of the f iles specif ied in the
parameter. The f ollowing listing is an example of the command's execution
results:
783fd8fc5250c439914e88d490090ae1 /etc/DIR_COLORS
e2eb98e82a51806fe310bffdd23ca851 /etc/Muttrc
e1043de2310c8dd266eb0ce007ac9088 /etc/a2ps-site.cfg
4543eebd0f473107e6e99ca3fc7b8d47 /etc/a2ps.cfg
c09badb77749eecbeafd8cb21c562bd6 /etc/adjtime
70aba16e0d529c3db01a20207fd66b1f /etc/aliases
c3e3a40097daed5c27144f53f37de38e /etc/aliases.db
3e5bb9f9e8616bd8a5a4d7247f4d858e /etc/anacrontab
fe4aad090adcd03bf686103687d69f64 /etc/aspldr.conf ...
The command's execution results are display ed in two columns. The f irst
column display s the f ile's checksum; the second column display s the f ile's
name. Checksum can be calculated f or f iles only. Attempting to calculate a
checksum f or a directory will result in an error message.
In the example, checksums f or all f iles in the /etc f older are display ed. But,
unless y ou hav e a photographic memory, it is dif f icult to remember all the
inf ormation display ed. It would be more conv enient to write the results to a
f ile, which can then be used to analy ze any changes. The f ollowing
command sav es the results to the /home/f lenov /md f ile:
md5sum /etc/* >> /home/flenov/md
The current status of the checksums of the f iles in the /etc directory is
compared with their checksums stored in the /home/f lenov /md f ile by
executing the f ollowing command:
md5smn -c /home/flenov/md
A list of all f iles will be display ed. Those whose checksum has not changed
will be marked "Success." Modif y one of the f iles, f or example, by
executing the f ollowing command:
groupadd test
I will not go into the details of this command now; it will suf f ice if y ou
know that it modif ies the /etc/group f ile. Check the checksums of the f iles
again: md5sum -c /home/flenov/md
Now, the /etc/group f ile with be marked with an error message because its
checksum has been changed. Consequently, ev en if some smart hacker f ixes
the modif ication date of the f iles he or she f iddled with, y ou can easily
detect the intrusion by checking the checksum of the f iles in question. And it
is much more dif f icult to doctor the checksum.
One of the disadv antages is that prof essional hackers are skilled
programmers. It is no problem f or them to modif y the source code of some
utility, adding f unctions that they need in the process. In this way, hidden
doors are of ten opened in the sy stem.
Theref ore, y ou should monitor changes not only of conf iguration f iles but
also of all sy stem programs and libraries. In particular, I recommend
monitoring the /etc, /bin, /sbin, and /lib f olders.
There is a complication, howev er: Inv isible characters can be used in f ile
names. Hackers can take adv antage of this by naming their creation using
only inv isible characters, and users will not see such a f ile.
Consider an example using the linef eed inv isible character. Suppose that a
hacker named his f ile hacker\nhost.allow. In this case, the \n sequence
denotes linef eed, meaning that the name will be display ed as two lines as f
ollows:
hacker
hosts.allow
Not all programs can process this ty pe of name properly. If y our f ile
manager does not work correctly, it will display only the second string —
hosts.allow— and the administrator will not suspect that there is any thing to
be f eared in this name.
Another way to hide a f ile is to use a period (or two periods) and a space f or
its name. The f ile whose name is a period is a pointer to the current
directory. The administrator may not notice that there are two f iles named.
(because the space in the impostor's name is inv isible) in the list display ed
by thelscommand.
Spaces can be inserted any where in a f ile name — in the beginning, in the
middle, or in the end — and, unless y ou are looking caref ully, y ou will not
notice any thing wrong. Spaces at the end of a f ile name can be display ed by
adding the / character to the f ile name. This can be done by executing thels
command with-Foption.
Yet another way to hide, or rather to disguise, a f ile is to use characters that
look similar to characters in legitimate f iles' names. Take a look, f or
example, at this f ile name: hosts.allow. Can y ou see any thing suspicious? It
is dif f icult to notice any thing out of the ordinary during a cursory
examination of this name. But upon closer inspection y ou may realize that
those two "I"s are not letters at all but two instances of the digit "1" (one).
Hackers of ten use this trick. Another substitution of this ty pe is using letter
"b" instead of letter "d." Although these two letters look quite dif f erent
when compared by themselv es, when they are placed among other
characters, the substitution is of ten ov erlooked because when we see
something of ten the brain tends to interpret little irregularities as what it
expects to be there and not as what really is seen.
Thus, pay ing close attention is an administrator's main weapon. Any little
thing must come under the microscope of y our scrutiny, and y ou should see
what is there and not what y ou expect.
3.1.3. Links
There may be documents in y our sy stem that are shared among sev eral
users. Consider this situation on an example. Suppose that sev eral users need
to be able to access the /home/report f ile. One way to make this happen is to
giv e each user his or her own copy of the f ile. But this is easier said than
done, because sev eral copies of the same f ile used by sev eral users present
a sy nchronization problem. Moreov er, it is dif f icult to put modif ications f
rom sev eral f iles into one whole, especially if the same portion of the f ile
was edited. Who is to decide whose modif ications apply to the common f
ile?
This problem is solv ed with the help of hard links and sy mbolic links. To
understand the idea of links, y ou hav e to understand what a f ile is and how
the operating sy stem stores it. When a f ile is created, disk space is allocated
to it. The f ile's name is just a directory link to the area of the disk where the f
ile is phy sically located. Consequently, sev eral links to the same f ile can be
created, which is allowed in Linux.
The ls -lcommand display s detailed inf ormation about f iles in the current
directory in the f ollowing f ormat:
-rw-r--r-1 Flenov FlenovG 118 Nov 26 16:10 1.txt
Executing the command with the -ioption(ls -il)adds the f ile descriptor to the
inf ormation display ed:
913021 -rw-r--r-- 1 Flenov FlenovG 118 Nov 26 16:10 1.txt
The descriptor in the preceding string is the number at the beginning of the
string, which indicates the phy sical location of the f ile.
A hard link points directly to the f ile and has the same descriptor.
Consequently, a f ile cannot be phy sically deleted until all hard links hav e
been deleted. In essence, a f ile name is a hard link to the f ile's phy sical
location.
To be able to practice the material that will be considered, create a text f ile;
name it l.txt. This can be done by executing the f ollowing command: cat >
1.txt
Press the <Enter> key and ty pe a f ew lines of text; f inish by pressing the
<Ctr>+<D> key combination. Now y ou hav e a f ile to experiment with.
Create a hard link to the 1.txt f ile. This is done by executing the f ollowing
command:
ln 1.txt link.txt
Execute the cat link. txtcommand to display the contents of the link.txt f ile.
As y ou can see, it is identical to the contents of the 1.txt f ile. Now execute
thels -ilcommand to v iew the contents of the f older. There should be the f
ollowing two lines in the list of the f older f iles:
913021 -rw-r--r-- 2 root root 0 Feb 22 12:19 1.txt 913021 -rw-r--r-- 2 root
root 0 Feb 22 12:19 link.txt
Note that the f ile descriptors of both f iles (the numbers in the f irst column)
are the same. The number2in the third column means that there are two links
to the phy sical f ile.
Now, modif y the contents of either of the two f iles. This is done by
executing the f ollowing commands:
ls > link.txt
cat 1.txt
The f irst command sav es the execution results of the lscommand (a list of
the contents of the directory ); the second command display s the 1.txt
document. As y ou can see, the contents of both f iles hav e been changed and
are the same.
Now try to delete the 1.txt f ile and then v iew the contents of the directory
and of the link.txt f ile. This is done by executing the f ollowing sequence of
commands:
rm 1.txt
ls -il
cat link.txt
Although the 1.txt f ile has been successf ully deleted, the contents of the
link.txt hard link remain unchanged. In other words, the phy sical f ile has not
been deleted; only the 1.txt name it was ref erenced with has been. Note that
the number of links f or the link.txt f ile, shown in the third column, has
decreased to one.
A sy mbolic link points not to the phy sical f ile but to the f ile's name. It giv
es some adv antages but creates lots of problems. A sy mbolic link is created
by specif y ing the-soption with thelncommand. For example:
ln -s link.txt symbol.txt
Remov e the main f ile, then try to v iew the contents of the sy mbol.txt link
rm link. txt
1s -il
cat symbol.txt
The f irst command remov es the link.txt f ile. The second command display
s the contents of the directory. Make sure that the link.txt f ile is not there. If
y ou are using the Red Hat distributiv e, thelscommand display s dif f erent f
ile ty pes in dif f erent colors. Otherwise, replace the second command with ls
-color=tty -il.
This would display the sy mbolic link name and the f ile, to which the link
points, on the red background. This indicates that the link is broken; that is, it
points to a nonexistent f ile. Thecat symbol.txtcommand attempts to display
the contents of the f ile, to which the link points. Because the f ile does not
exist, it produces an error message.
Of interest is that attempting to write to a sof t link f ile (sy mbol.txt in this
case) whose main f ile (link.txt in this case) does not exist automatically
creates the main f ile. This is a huge shortcoming; consequently, y ou should
ensure that a f ile has no sy mbolic links bef ore deleting it.
Another shortcoming of sy mbolic links lies in their access rights, which will
be considered inChapter 4.
Yet another minus of links is that a f ile, to which a hard or sof t link exists, is
locked when opened f or editing. Suppose that a link exists to the /etc/passwd
or the /etc/shadow f ile. Locking one of these f iles will make it impossible to
enter the sy stem.
To prev ent hackers f rom taking adv antage of locking, the rights f or writing
to the sy stem directories should be limited. Users normally should be giv en
rights to write only to their /home directory and the /tmp directory. When f
iles are shared, it may be necessary to hav e access to other user directories.
But ev en in this case, the access should be limited to the /home directory,
where user directories are located.
With all of the security -related shortcomings of links, the question arises, "Is
it wise to use them?" I recommend using links only in extreme cases, when
other way s of solv ing the problem are ev en worse. But be caref ul when
doing this.
Moreov er, f ast booting allows the sy stem to be put back into operation
rapidly af ter a crash. All computers hav e to be rebooted at one time or
another to restore their f ull f unctionality lost because of sof tware errors,
power interruptions, and so on. The f aster y ou can do this, the f ewer
complaints y ou hear f rom irate users.
All necessary sy stem settings should be conf igured during the boot so that y
ou would not hav e to conf igure any thing manually af ter the boot. Manual
conf iguration may take a long time, and it is just too dull and boring to go
through the same routine ev ery time the sy stem boots.
3.2.1. Start-Up
If y ou are using the KDE or GNOME shell, y ou can use a graphical utility f
or conf iguring automatically launched daemons. The utility is located in the
Services section. Clicking the Start Here icon on the desktop will open a
window containing shortcuts to the main sy stem conf iguration utilities. The
shortcut to the Services section should be among them.
There also is another way to start this utility. Open the main menu, select the
System Settings item in it, select the Server Settings item in the submenu,
and f inally select the Services item in the next submenu (Fig. 3.2). In the f
uture, I will denote a sequence of menu items by simply listing them
delimited with a slash, as f ollows:
The main window of the Serv ices utility is shown in Fig. 3.3. There is a
twocolumn list of serv ices in the center of the f orm. Placing a check mark in
a serv ice's checkbox will make the serv ice start automatically. Check marks
are placed by double-clicking the necessary serv ice's checkbox.
A selected serv ice can be started, stopped, paused, or restarted using the
corresponding toolbar buttons or Actions menu items. Any modif ications of
the serv ices' automatic start hav e to be sav ed. This can be done by clicking
the Save button or executing the File/Save changes menu sequence.
Nev er start serv ices that y ou do no use. Only those programs that y ou or
the serv er users require regularly should be started automatically. If a
daemon is used only occasionally, it should
or
LILO boot:
You could press the <Enter> key to boot into the def ault operating sy stem or
use the <↑> and <↓> key s to select the necessary operating sy stem. The
modern boot loader has a more pleasant graphical appearance.
boot=/dev/hda
prompt
timeout=300
lba32
default=linux-2.4.18
image=/boot/vmlinuz-2.4.18-5asp initrd=/boot/initrd.2.4.18-5asp.img
label=linux-2.4.18
root=/dev/hda2
read-only
Each line in the f ile specif ies a certain boot parameter. There are numerous
boot options. You can obtain detailed inf ormation on all of them in the
documentation supplied with the operating sy stem, but f or now I will
consider only the main options. Most parameters are assigned v alues. This is
done as f ollows:
Parameter=Value
To the lef t of the equals sign is the name of the parameter, and to the right is
the v alue assigned to it. Some of the possible parameters that a lilo.conf conf
iguration f ile may contain are the f ollowing:
timeout=300 — Shows the time the boot loader waits f or the user to select
the operating sy stem to load bef ore loading the def ault operating sy stem.
default=linux-2.4.18 — Specif ies the def ault operating sy stem, into which
to boot. In this case,linux-2.4.18is specif ied.
This inf ormation will suf f ice f or now. Most of the options not considered
are obsolete and are needed only when old computers are used. Based on my
experience, I can state that the parameters just listed will be enough. Now,
edit the lilo.conf f ile when compiling the kernel to prov ide boot options.
The conf iguration f ile can be edited in any text editor. I normally use the
text editor built into the Midnight Commander program. Launch Midnight
Commander. Most likely, the current f older will be y our f older, f or
example, /home/root. You hav e to mov e to the root f older. Mov e to the
upper lev el directory by selecting the /‥entry in the directory content list
and pressing the <Enter> key. This will take y ou to the /home directory.
Repeat the process, and y ou will be taken to the root f older.
In the root f older, select the /etc f older and press the <Enter> key to open it.
Select the lilo.conf f ile and open it f or editing by pressing the <F4> key.
This will open a basic text editor. Edit the necessary parameters; press the
<Esc> key to exit the program. If the f ile has been changed, the program will
ask whether y ou want to sav e the changes. Agree if y ou want to.
If y ou hav e nev er edited conf iguration f iles, try doing this now. For
practice, y ou can try to change the time Linux waits f or the user to select the
boot method (f rom the hard driv e or diskette) bef ore booting using the def
ault method.
In Linux conf iguration f iles, there are entries that are called comments. A
comment is text that is ignored by the program and is used by the
programmer to supply some explanations or to temporarily disable some
parameters. A comment entry starts with the#character. All that f ollows this
character on the same line is ignored by the sy stem. For example: # This is a
comment.
boot=/dev/hda
timeout=300 # This entry specifies the timeout.
# lba32
default=linux-2.4.18 # This entry specifies the default OS.
In the preceding example, the f irst line starts with the #character and will be
ignored by the sy stem. In the third line, the comment f ollows the parameter.
This means that the parameter will be read but the explanation f ollowing it
will be ignored.
In the f ourth line, the #character in f ront of thelba32parameter will make the
sy stem treat this parameter as a comment; that is, the sy stem will simply
ignore it as if it were not there.
LILO can be used to prev ent unauthorized booting. This may be necessary,
because it is possible to execute commands during the boot process. If a
malef actor gains phy sical access to y our computer, he or she can easily
boot into the single-user mode and subsequently break the root password or
execute some commands.
If the LILO boot loader screen is a simple text prompt (which is characteristic
f or Red Had distributions), a command during the boot process is executed
by entering the name of the operating sy stem to boot into f ollowed by
init=command:
Linux Boot: linux init=command
image=/boot/vmlinuz-2.6.2 password=123456
initrd=/boot/initrd.2.6.2.img label=linux-2.6.2
root=/dev/hda2
read-only
I will explain how to conf igure LILO f or booting into two kernels inSection
3.8.4.
But the password only disables the booting, and not the f eature of being able
to execute commands when the sy stem is started. To disable this capability,
add the key wordrestrictedto the lilo.conf conf iguration f ile af ter the
password-setting line, as f ollows:
image=/boot/vmlinuz-2.4.18-5asp
password=qwerty
restricted
initrd=/boot/initrd.2.4.18-5asp.img label=linux-2.4.18
root=/dev/hda2
read-only
The modif ications to the conf iguration f ile are made ef f ectiv e by
executing the lilodirectiv e f rom the command line. This will write the new
parameters to the boot area, and the next sy stem booting will take them into
account.
3.2.3. init
LILO launches a program that initializes booting into the operating sy stem
by conf iguring the necessary equipment, loading driv ers, and mounting hard
driv es. Af ter this process f inishes, the initprogram is launched, which f
inalizes the booting.
The initprogram, like most other Linux utilities, has its own conf iguration f
ile (Listing 3.2). This f ile is named inittab and is located in the /etc f older.
Listing 3.2: The inittab configuration file
#
# inittab This file describes how the init process # should set up the system
# in a certain runlevel.
#
# Author: Miquel van Smoorenburg,
# <[email protected]>. # Modified for RHS Linux by Marc
Ewing and # Donnie Barnes
#
# Default runlevel. The runlevels used by RHS are: # 0 - Halt (Do NOT set
initdefault to this) # 1 - Single user mode
# 2 - Multiuser, without NFS (The same as 3, if you # do not have
networking)
# 3 - Full multiuser mode
# 4 - Unused
# 5 - X11
# 6 - Reboot (Do NOT set initdefault to this) # id:5:initdefault:
# System initialization
si::sysinit:/etc/rc.d/rc.sysinit
# What to do in single-user mode. ~~:S:wait:/sbin/sulogin
10:0:wait:/etc/rc.d/rc 0
11:1:wait:/etc/rc.d/rc 1
12:2:wait:/etc/rc.d/rc 2
13:3:wait:/etc/rc.d/rc 3
14:4:wait:/etc/rc.d/rc 4
15:5:wait:/etc/rc.d/rc 5
16:6:wait:/etc/rc.d/rc 6
# If power was restored before the shutdown kicked in, # cancel it.
pr:12345:powerokwait:/sbin/shutdown -c "Power Restored; Shutdown
Cancelled"
At the beginning of the f ile, inf ormation is prov ided in comments about the
module and the author f ollowed this with a description of the runlev els
supported by the sy stem. Some distributions hav e as f ew as two runlev els;
Red Hat clones support sev en runlev els. These are the f ollowing:
In addition to the sev en runlev els just listed, there also is the S runlev el. It
corresponds to the single-user mode and is used in script f iles, but sometimes
the inittab f ile also uses it.
Let's get acquainted with the f ile's structure now. Each of its lines (with the
exception of comments and empty lines) has the f ollowing structure:
identifier:runlevels:action:process
That is, each line consists of f our arguments delimited with a colon. The f
unction of each parameter is as f ollows:
runlevels — Runlev els, f or which the specif ied action is to be taken. For
example, if the action is supposed to work at the second and third runlev els,
this parameter should be 23. This is not the number 23 but two digits, "2" and
"3," which are not separated by spaces or any other delimiters. If the action is
supposed to be executed on all runlev els, this parameter should be lef t
blank.
action— The action to be taken. This can take on one of the f ollowing v
alues:
boot — The process is executed once, during the boot. In this case,
therunlevels parameter is ignored.
ctrlaltdel — This specif ies that the sy stem is set to shut down and reboot in
response the <Ctrl>+<Alt>+<Del>
combination. There should be no accidental or unplanned reboots. The
rebooting option is a drawback, because any one who can phy sically get to
the computer can press this combination out of curiosity, spite, or self ish
ends. I recommend disabling this option by commenting it out.
initdefault — The line with this parameter is processed only once, during f
irst access to the init f ile, and specif ies the runlev el, into which to enter af
ter sy stem boot. If the runlev el of this line is 5, the operating sy stem will
boot into the graphical mode. If y ou want to boot the operating sy stem into
the multiuser text mode with network support, change the v alue of the
parameter to 3 (see the description of the runlev els). It is possible to specif y
more than one lev el (which I do not recommend doing); in this case, the
maximum runlev el will be selected.
powerfail — The process will be executed when the power f ails;initdoes not
wait f or process completion. This works only if the computer is powered f
rom a UPS
communicating with the computer ov er a special interf ace (usually, USB or
COM port).
sysinit — The process will execute during sy stem boot bef ore the login
prompt is display ed. The operating sy stem waits f or the process to f inish.
wait — This indicates that the program will wait f or the process to f inish.
Theinit program will not execute any other
commands until the process f inishes. For example, if the disk has to be
checked, the boot process must be suspended until the disk check has been
completed.
Now, consider a f ew lines f rom Listing 3.2 to see what they mean and to
learn to control them f or enhancing the sy stem's productiv ity. The f irst line
af ter the comments is the f ollowing: id:5:initdefault:
You already know that the initdefaultparameter specif ies how the sy stem
will be booted. In this case, the init f ile will be executed at runlev el 5, that
is, in the graphical mode.
What is the f unction of the rcprogram? Its main task is to kill all current
processes and to launch new processes corresponding to the new execution
mode. For example, y ou want to mov e f rom runlev el 3 (the f ull multiuser
mode) to runlev el 1 (the single-user mode). The switch is carried out as f
ollows: All multiuser mode programs are terminated, af ter which only
singleuser mode processes are activ ated. This entire process is carried out by
the /etc/rc.d/rc program.
Open the /etc/rc.d/ f older and inspect its contents. In addition to the rc
program, it contains f olders f or each runlev el named rcX.d, where X is a
number in the range f rom 0 to 6, corresponding to the runlev el. Each of
these f olders contains scripts whose names start with the letter "K" or "S."
When a runlev el is exited, the K-scripts are executed; they kill all processes
running at the runlev el. When a runlev el is entered, the S-scripts are
executed, which activ ate all processes necessary f or the giv en runlev el.
Scripts are not edited manually, and the sy stem manages the f iles without y
our participation. Howev er, y ou should know about this boot f eature. For
example, y ou do not want a certain daemon to run when the sy stem boots
into lev el 3. You can do this by simply deleting the corresponding script f
rom the /etc/rc.d/rc3.d f older or changing its name to start with a letter other
than "S."
The /etc/rc.d/init.d f older contains scripts that launch, stop, or restart sy stem
serv ices. It is these scripts that are used when switching f rom one runlev el
to another.
Next, in the quotation marks, is the message that will be display ed on each
console. In the graphical mode, a window with the same message will be
display ed to all users.
Note that the time specif ied until shutdown is only 2 minutes. This is a short
time, because a plain UPS can power a computer up to 20 minutes. Taking
into account that in most cases serv ers are not equipped with a monitor or, if
they are, that the monitor is usually turned of f , the UPS can last up to 40
minutes. So I recommend checking how long y our UPS can last and
adjusting the timeout correspondingly to av oid unnecessary shutdowns.
Now, take a look at what happens when the main power is restored:
pr:12345:powerokwait:/sbin/shutdown -c "Power Restored; Shutdown
Cancelled"
This entry executes in lev els 1 through 5 and cancels the shutdown if the
main power is restored bef ore the timeout specif ied in theshutdownentry
expires. It cannot be used on runlev els 0 and 6 f or obv ious reasons.
vc/1
vc/2
vc/3
vc/4
vc/5
vc/6
vc/7
vc/8
vc/9
vc/10
vc/11 tty1
tty2
tty3
tty4
tty5
tty6
tty7
tty8
tty9
tty10 tty11
This f ile lists all consoles and terminals, f rom which a user can log into the
sy stem as the root user. The f irst 11 entries def ine 11 v irtual consoles; the
rest of the entries assign terminal windows. To permit login f rom only one
terminal, delete allttyXentries except f ortty1. This will leav e all terminals
operable, but only the f irst one can be used to log in with root rights.
Virtual consoles are switched by pressing the <Alt> key at the same time as
one of the <F1> through <F6> key s.
The last entry in the inittab f ile executes only on runlev el 5:
x:5:respawn:/etc/X11/prefdm -nodaemon
This entry executes the /etc/X11/pref dm shell script, which switches the sy
stem into the graphical mode and display s the corresponding login window
(considered inSection 2.8). You can use the pref dm shell script to switch to
the graphical mode f rom the text mode.
If y ou want that the initprogram only to reexamine the inittab conf iguration
f ile, it is run with theqargument:
/etc/init q
Here Xis the runlev el, to which y ou want the operating sy stem to switch.
This command is conv enient to use if y ou are working at runlev el 5 and
want to switch to the text mode, which is at runlev el 3. If y ou try to exit the
graphical mode using the regular sy stem means, the operating sy stem will
not switch to the text mode and the login prompt will remain graphical.
I would recommend, howev er, not switching to runlev els 0 and 6 to reboot
and shut down the sy stem, correspondingly, but using theshutdown
command with the appropriate arguments.
Bef ore the login prompt is presented, some text inf ormation is display ed on
the screen. Most of ten, this is the name of the distribution and its v ersion.
This inf ormation is stored in the /etc/issue f ile, and y ou can easily modif y
it using any text editor, including Midnight Commander.
Af ter successf ul login, a text message can also be display ed. The text is
stored in the /etc/motd f ile and is by def ault blank in most distributions. The
f ile can be used to prov ide dif f erent inf ormation to the sy stem's users, f or
example, reminding them to change the password the f irst day of a month.
The loginprogram compares the user name entered with the list of names in
the /etc/passwd f ile and the password with the corresponding entry in the
/etc/shadow f ile. The passwords in the f ile are encry pted. The password
entered by the user is also encry pted, and the result is compared with the
encry pted password stored in the /etc/shadow f ile f or the user name specif
ied.
Why is the v erif ication process so complex? The reason f or this is that all
passwords stored in the /etc/shadow f ile are encry pted with an irrev ersible
algorithm (most of ten, the MD5 algorithm is used). This means that the
plaintext password cannot be obtained f rom the encry pted password using
mathematical means; it can only be picked using the enumerativ e or the
dictionary methods. There are many simple programs that do this. The
simpler and shorter the password is, the f aster it is picked. If the password is
complex and more than 8 characters long (or, ev en better, more than 16
characters long), picking it may take too much time and discourage the
hacker.
If the user identif ication is successf ul, the loginprogram executes all
automatically -loaded scripts and launches the shell (the command line) that
will be used to interact with the sy stem. If the v erif ication f ails, the sy stem
returns control to thegettyconsole, which starts the login process anew.
Consequently, unless the user passes the login authorization, access to the
command shell will be denied and only thegettyconsole will be av ailable,
which can only ask f or the user's name and pass this name to thelogin
program.
Next I will consider some problems that may arise when logging into the sy
stem and how these problems can be solv ed.
In older Linux v ersions, the user list and the passwords were stored in the
/etc/passwd f ile. This was a security risk; all users had to hav e access to this
f ile because many innocent programs require user names. For example, when
thelscommand (v iew the contents of the current f older) is executed, it needs
to hav e access to the user list to obtain the names of the f ile owners.
Because the f ile can be read by any user, the encry pted passwords contained
in it can also be read by any user. This makes it possible f or a user to pick
any of the passwords by the enumeration or the dictionary method.
To protect the passwords, all modern Linux v ersions store them in the
/etc/shadow f ile, to which only the administrator has access. The /etc/passwd
f ile remains accessible to any one, but now no passwords are stored in it.
Take a look at the /etc/passwd f ile's structure. For an example, I took three f
irst lines f rom my f ile:
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x: 2:2:daemon:/sbin:/sbin/nologin
Each entry contains sev en items of user inf ormation delimited by colons.
Their f unctions, in order of their appearance, are as f ollows:
User name— The name ty ped when logging into the sy stem. Password—
The encry pted password. If shadow passwords are being used, this f ield
contains anxcharacter
User identifier (UID) — The unique numerical UID corresponding to the giv
en user name. Group identifier(GID) — The unique numerical GID.
User information— Optional inf ormation such as the user's f ull name,
address, and so on.
Home directory— The absolute path to the directory, in which the user starts
working when entering the sy stem.
Shell — The shell (a command interpreter) that will execute the user's
commands. If the user is not supposed to hav e a command interpreter, the
/sbin/nologin f ile is specif ied.
Now, examine the entry f or the root user. The f irst parameter is the user's
name, which is, of course,root. The password is not shown in the f ile. It is
represented by thex(or!!) character, the password itself being stored in the
corresponding entry of the /etc/shadow f ile.
The next two parameters are the unique UID and the unique GID. There can
be no two entries with the same UID in the f ile. The sy stem uses the GID to
determine the group, to which the user belongs, and def ine the rights granted
to this group and, accordingly, to the user.
The user inf ormation parameter can contain any data; it has no ef f ect on the
sy stem's operation. It is used to prov ide additional inf ormation about the
user that the administrator may deem necessary.
The next parameter is the user's home directory. This directory is opened f or
the user when he or she enters the sy stem.
The last parameter is the command interpreter that will process user requests.
The most common command interpreter is /bin/bash. If the user's commands
are not supposed to be executed, this parameter is set to /sbin/nologin. The
shell parameter f or thebin, daemon, and many other accounts is set to
/sbin/nologin, because these accounts are not used to enter the sy stem but are
only intended f or prov iding internal security f or certain programs.
Now, examine the /etc/shadow f ile structure. Three entries f rom this f ile
will be enough f or an example:
root:$1$1emP$XMJ3/GrkltC4c4h/:12726:0:99999:7:::
bin:*:12726:0:99999:7:::
daemon:*:12726:0:99999:7:::
Each entry contains sev eral parameters delimited with a colon. Of interest to
us are only the f irst two parameters: login and password. The login (the user
name) is used to map the entry in the /etc/shadow f ile to the corresponding
entry in the /etc/passwd f ile. The actual encry pted password is stored in the
second parameter. An asterisk in this f ield means that this account is locked
and the user is not allowed to log in. Thus, accounts f or usersbinand
daemoncannot be used to log into the sy stem.
Hav ing booted f rom a diskette, log into the sy stem as root and mount the
hard driv e (or the partition), on which the /etc directory is located. This is
done by executing the f ollowing command:
/sbin/mount -w hda1 /mnt/restore
Now, the /mnt/restore directory (this directory must exist bef ore the
command is executed) points to the primary partition of y our hard driv e, and
the f ile with the password is at the /mnt/restore/etc/shadow path. Open this f
ile in any text editor and remov e the root password by simply deleting all
text between the f irst and the second colons. The f ollowing is what I
obtained in my /etc/shadow f ile:
root::12726:0:99999:7:::
Now boot into the sy stem as usual and log in as root. The sy stem will not ev
en ask y ou to enter the password, because there is none. Do not, howev er, f
orget to set a new password, because f ailing to do this is a security risk.
The conf iguration f iles f or each serv ice that may use PAMs are located in
the /etc/pam.d directory. In most cases, y ou will not hav e to create these f
iles manually, because they are installed when the program is installed using
the RPM package. But y ou should know their structure in case there is a
need to change some parameters.
Each entry in the conf iguration f ile contains f our f ields delimited by
spaces. These are the f ollowing:
Module interface— Can be one of the f ollowing ty pes:
auth— These modules authenticate users and check their priv ileges.
Module path — Indicates the f ull path to the module's f ile. Module
arguments
The f ollowing is what the /etc/pam.d/f tp FTP serv ice conf iguration f ile
looks like:
#%PAM-1.0
auth required /lib/security/pam_listfile.so item=user sense=deny
file=/etc/ftpusers onerr=succeed
auth
auth
account session required /lib/security/pam_stack.so service=system-auth
required /lib/security/pam_shells.so
required /lib/security/pam_stack.so service=system-auth required
/lib/security/pam_stack.so service=system-auth
This inf ormation is all y ou need to know. The serv ice program takes care of
the rest without y our participation.
There are two main process ty pes: background and f oreground. A terminal
can hav e only one f oreground process. For example, hav ing launched the
manprogram, y ou will not be able to execute any other commands until y ou
terminateman.
Those who are f amiliar with Midnight Commander may ask how it is
possible to execute commands while working in Midnight Commander. The
answer is simple: processes can spawn child processes. So Midnight
Commander is the parent process, and the commands that are executed f rom
it are its child processes. Closing Midnight Commander closes all its child
processes.
All serv ices run as background processes. That is, they do their job in
parallel with whatev er else y ou are doing on the computer. Howev er, not
only serv ices but also any program can be run in the background mode. It is
done by issuing the command to launch the program and f ollowing it with a
space and the&character. For example, execute the f ollowing command: man
ls &
You will not see the help f ile but only the f ollowing string display ed on the
screen:
[1] 2802
The terminal is now ready to accept other commands, because the terminal's f
oreground process launched the man lscommand in the background mode and
itself remains in the f oreground.
But what does the message display ed in response to the command mean?
The sequential number of the background process launched is shown in the
square brackets. This number will successiv ely increase. Because this is the f
irst command issued, the number in the square brackets is 1. A separate count
of background processes is kept f or each user. If y ou log into the sy stem on
another terminal and launch a background process, y ou will see something
like the f ollowing:
[1] 2805
The number in the square brackets is 1 again, but the next number is, and
alway s will be, dif f erent than the one f or the f irst command on the f irst
terminal. This number is the Process IDentif ier (PID) of the process created
and is unique f or all users. This means that if y ou launch a process number,
f or example, 2802, no process launched by any other user will ev er hav e
this PID.
Remember the identif iers in the preceding two examples; y ou will need
them later.
You can f ind out what processes are running by executing the jobs
command. It display s the f ollowing result:
[1] + Stopped man ls
In this case, y ou can see that the process number,[1], is loaded into the
memory and the status of the man lscommand isStopped.
But what is the purpose of sending a command into the background execution
mode? You can use this f eature to run in the background a program that
takes a long time to complete, while y ou can engage into other tasks in the f
oreground. You can switch the command running in the background to the f
oreground. This is done by entering thefg %Xcommand, whereXis the
process number shown in the square brackets. Try executing this command
withX= 1; this will bring theman lsprocess to the f oreground and display
themanpage f or thelscommand.
Sometimes, processes can hang. Yes, ev en Linux is not f ree of this curse. A
f oreground process can be terminated using the <Ctrl>+<C> or <Ctrl>+
<Break> key combination. But this method does not alway s work f or all
programs. If a process ref uses to terminate when asked nicely, it is
terminated using thekillcommand. To terminate a process with the identif ier
giv en in the square brackets, issue the f ollowing command: kill %n
Here, nis the number of process giv en in the square brackets. For example,
the manprogram in the earlier examples is terminated by entering the f
ollowing in the command line:
kill %1
Right af terward, run the jobscommand. You should see the f ollowing
message on the screen:
[1] + Terminated man ls
Executing the jobscommand again will produce no inf ormation about the
man program. A process launched by another user whose PID is known is
terminated by the f ollowing command:
kill n
Here, nis the PID of the process. Note that it is entered without the %
character. Then the killcommand looks f or the process with the specif ied
PID and sends a signal f or its termination.
Inf ormation about running processes can be display ed using the jobs
command. To spy on what other users in the sy stem are doing, the ps
command is executed. Running this command without any options display s
the f ollowing inf ormation:
The f our columns display the f ollowing inf ormation: the PID; the terminal,
on which the program was started; the execution time; and the command
being executed.
The status of the processes is shown in the STATcolumn. It can be one of the
f ollowing:
S(sleeping) — This is the normal status f or serv ices, which only wake up to
serv ice client requests.
R(running) — This indicates that the process currently is being executed.
T(traced or stopped) — This process is currently being debugged or stopped.
Z(zombied) — The process has hung and can be killed without any adv erse
consequences.
W— The process has no resident pages.
<— This is a high-priority process. N— This is a low-priority process.
These are the main process statuses that y ou can observ e on y our sy stem.
A question mark in theSTATcolumn means that the process was started at the
sy stem boot stage and does not belong to any of the shells.
The preceding is just a small excerpt f rom the results returned by the ps
axucommand. There are many more processes running in a sy stem, and ev
en with the minimal number of serv ices running, the list may not f it into one
screen. I like sav ing the results of thepscommand in a text f ile so that I
could examine it at my leisure in any text editor. This is done by executing
the f ollowing command:
ps -axu >> ps.txt
To see what processes are run by other users, y ou can execute the w
command. The output it produces looks similar to the f ollowing: 10:59am up
37 min, 2 users, load average: 0.00, 0.00, 0.00 USER TTY FROM LOGIN@
IDLE JCPU PCPU WHAT root tty1 - 10:24am 0.00s 0.82s, 0 05s w flenov
tty2 - 10:39am 8:13 0.85s 0.03s grotty
You can see that there are two users in the sy stem at the giv en moment. The
root user is working on thetty1terminal, and the user Flenov is working on
thetty2terminal. TheLOGIN@column shows when the user logged into the sy
stem. What the user is doing at the giv en moment is shown in theWHAT
column.
The pscommand display s static inf ormation about the processes. You can
check the current resource usage with the help of thetopprogram. It display s
current processes sorted in descending order by the processor and memory
usage (Fig. 3.4). Thus, y ou can tell at a glance which serv ice or program
takes up too much of the sy stem's resources and puts a drag on the computer.
Figure 3.4: A sample of the results produced by the top program
At the top of the window display ed is the inf ormation about the number of
users, the ov erall sy stem workload, and the process statistics: the total
number of processes and the number of sleeping, executing, zombie, and
stopped processes.
A short set of statistics on memory usage is also display ed: the amount of av
ailable, used, and f ree sy stem memory and the same inf ormation f or the
swap f ile. In this case, the computer has 256 MB of random access memory
(RAM) installed, of which only 7 MB is f ree; the swap partition is not
currently being used. Such a small amount of f ree RAM av ailable tells me
that it would not hurt to increase the sy stem memory. The less the computer
resorts to the swap f ile, the more ef f iciently it works. That the swap f ile is
not being used at the moment does not mean much. Switching into the
graphical mode and launching a couple of resource-hungry applications will
quickly use up ev en this memory.
The topprogram also display s the processor workload inf ormation at the
specif ied time interv als. To exit the program, press the <Ctrl>+<C> key
combination.
3.5. Task Scheduling
Quite of ten, a certain operation has to be run at a certain time. In this respect,
I used to rely on my memory and would launch the necessary application at
the required time my self . But af ter f ailing a f ew times to do this — due to
simply being too busy to pay attention to the clock — I placed this task on
the computer's silicon shoulders. Come to think about it, why clutter my head
space with what the computer can do much better?
If this reason is not good enough, what if some simple but lengthy tasks need
to be perf ormed af ter work hours? What should the administrator do in this
case? Stay at work all night? Of course not. The computer can do ev ery thing
by itself ; y ou just hav e to tell it what and when has to be done.
The simplest, most reliable, and most belov ed hacker tool f or launching a
program at a certain time is theatcommand. Its simplest f ormat looks like the
f ollowing:
at hh:mm dd.mm. yy
The date can be omitted; in this case, the closest date is used. For example, if
the time specif ied is later than the current time, the current date is used; if it
is bef ore the current time, then the f ollowing date is used, because the
command can no longer be executed during the current day.
So as not to f orget to delete the user, y ou should schedule the deletion at the
same time as y ou create the account f or him or her. You start with executing
theatcommand specif y ing the time as 12:30. Just in case the user does not
manage to complete the job assigned by this time, giv e him or her an extra
20 minutes. Thus, the f inal command will be the f ollowing:
at 12:50
Af ter y ou press the <Enter> key, the prompt to enter the command will be
display ed:
at>
Enter the commands to be executed at the time scheduled. The user is deleted
by the userdelcommand; also, his or her directory is deleted by the
rmcommand. The necessary command sequence is the f ollowing: userdel
tempuser
rm -fr /home/tempuser
Ty pe the preceding commands, pressing the <Enter> key af ter each one.
Press the <Ctrl>+<D> key combination to quit the atcommand. The sy stem
will respond with a text message showing the task identif ier and the date and
time, at which the commands will be executed. It will look similar to the f
ollowing:
Job 1 at 2005-03-03 12:30
The queue of scheduled attasks can be v iewed using the atqcommand. The
results of its execution will look similar to the f ollowing:
1 2005-01-28 12:40 a root
2 2005-01-28 01:00 a root
3 2005-01-30 12:55 a root
In the f irst column, the task's number is display ed. The task can be
manipulated using this number. The second column holds the date f or the
task's execution; the name of the user who created the task is in the last
column.
Now suppose that some urgent processor-intensiv e job has to be done at the
time that the sy stem backup is scheduled to be perf ormed. The backup
process will put quite a brake on the other work, and it would be logical to
postpone the backup until the job has been f inished.
The atcommand is quite simple and easy to use, but it can be used to schedule
only a one-time task. Many administrator tasks (backup, f or example) must
be run on a recurrent basis. Suppose that y our sy stem has to be backed up ev
ery day at 10:00 p.m. Preparing theatcommand ev ery day is not much f un;
most likely, y ou will tire of doing this af ter a week at the most and will be
looking f or a way to optimize the task. A script f ile is not conv enient either,
because y ou will hav e to remember to run it.
The answer to this problem is using the cronprogram. Using this program
requires y ou to hav e thecronddaemon installed and running. It is also adv
isable to include it in the start-up.
The day of the week is specif ied by a number f rom 0 to 7, where both 0 and
7 denote Sunday. This is because in dif f erent countries the week starts on
dif f erent day s of week: in some it starts on Monday, and in others the week
begins on Sunday. In the f ormer, weekday s are denoted by numbers f rom 1
to 7, and in the latter they are numbered 0 to 6.
Parameters that are not used are f illed with an asterisk.
Here, only the hours and minutes are specif ied. Because the other parameters
are not specif ied, the command will execute daily at 05:00. The second
example:
00 20 * * 1 /home/flenov/backup2_script
This command executes the same script f ile ev ery Monday (the weekday
parameter is 1) at 20:00. The third example:
00 * * * * /home/flenov/backup3_script
Important prev iously scheduled tasks. To exit the program without sav ing
the changes, use only the <Ctrl>+ <C> key combination.
The cronserv ice also uses sev eral supplementary directories to simplif y the
scheduling process. Executable scripts are grouped in the f ollowing
directories:
It seems simple, but on which day of the week and at what time does a
weekly script execute? The answer becomes obv ious by examining the
/etc/crontab/ conf iguration f ile of thecronserv ice. It contains the f ollowing
entries:
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
The appropriate execution time is specif ied at the start of each entry in the f
ollowing f ormat:minute hour day month dayofweek.
The execution time can be specif ied in such a way that scripts f rom the
/etc/cron.monthly directory will execute hourly. So the def ault names of the
execution time directories are purely sy mbolic and can be easily changed.
Note that there are already scripts in these directories; y ou should remov e all
of them that are not necessary to av oid ov erloading the sy stem, or y ou
should schedule their execution f or a dif f erent time.
The list of existing tasks (stored in the crontab conf iguration f ile) can be v
iewed by executing thecrontab -1command. The crontab conf iguration f ile
can be edited by executing thecrontab -ecommand. This will open the f ile in
a text editor, in which y ou can edit its entries. If y ou hav e nev er worked
with this particular text editor, y ou may hav e some problems because it is
rather specif ic. If y ou hav e any problems, press <F1> to display the help inf
ormation. Changes become ef f ectiv e immediately upon quitting the editor.
To quit the editor without sav ing changes, ty pe :q!and press <Enter>.
All crontask inf ormation is stored astest. For each user, an indiv idual /v
ar/spool/ cron/f ile crontab f ile is created. The name of the f ile is the same as
the user's name.
You can edit this f ile directly, without using thecrontab -ecommand.
In conclusion, I want to giv e some security adv ice on working with the at
command. Hackers like to use this instruction a lot. For example, a hacker
may manage to obtain an account with maximum rights. He or she can then
use theatcommand to delete the account and clean up all the traces of entering
the sy stem.
There are two f iles in the /etc directory that y ou should conf igure properly :
at.allow — Only those users listed in this f ile hav e the right to execute
theatcommand.
Similar f iles exist f or the at.deny — Users listed in this f ile are explicitly
denied the right to use theatcommand.
cronserv ice:
cron.allow — Users listed in this f ile hav e the right to use the cronserv ice.
The f ile may not be created by def ault. cron.deny — Users listed in this f ile
are denied the right to use thecronserv ice.
I hav e said it many times and will repeat it again: You should maintain a
restrictiv e conf iguration policy. This means that y ou start with disabling all
serv ices and deny ing all users all rights; then y ou enable the serv ices that
are necessary and giv e the necessary rights to those users that require them.
But don't try to list all users in the at.deny f ile. Instead, create the at.allow f
ile and list in it only y our account, which pref erably is not the root one. If
some users complain that they need to use theatcommand, make sure that
they need it bef ore entering their accounts into the at.allow f ile.
The main protocol used in Linux is the Internet standard TCP/IP. This
protocol is installed during Linux installation and only has to be conf igured.
If y ou hav e nev er worked with this protocol, I recommend that y ou obtain
and read some inf ormation on this subject. I cannot consider all nuances of
TCP/IP in this book and will only consider the f undamental concepts.
For the network to work properly, the f ollowing minimal parameters should
be conf igured:
The address. Each dev ice in the network must hav e its address to be able to
communicate with other dev ices in the network. Imagine that there were no
addresses f or y our house. How, then, would mailmen deliv er y our mail?
Computer names cannot be used f or this purpose f or v arious reasons bey
ond the scope of this book.
Dev ices in a network are addressed using 32-bit-long IP addresses. For conv
enience, an IP address is div ided into f our binary octets, each of which is f
urther conv erted into a decimal number. The f our groups of decimal
numbers are delimited using periods (dots). The resulting f ormat is called
dotted decimal notation.
It is obv ious that each group can be no larger than 255. Your Internet interf
ace may hav e an IP address assigned by the Internet prov ider.
The subnet mask. In conjunction with the IP address, another dotted decimal
notation number is used to div ide the network into smaller segments. It is
called the subnet mask. Whereas y our home address can hav e sev eral
components (such as the house or apartment number, street, city, and zip
code), a computer address has only two characteristics: the network ID (also
called a network address) and the ID of the computer inside the network (also
called a host address). The subnet mask determines, which part of the
computer address def ines the network and which def ines the host.
To understand how the mask does this, each of its numbers has to be conv
erted into the binary f ormat. Consider this using mask 255.255.255.0 as an
example. In binary f ormat it looks as f ollows:
11111111.11111111.11111111.00000000
Now conv ert the 192.168.001.001 IP address into the binary f ormat:
11000000.10101000.00000001.00000001
Superimpose the mask on the IP address. The ones in the mask determine,
which parts of the IP address are the network address, and the zeros specif y
the host address. Ones in the mask must alway s be located in the lef t part of
the mask, and zeros must be in the right. Ones cannot alternate with zeros.
For example, the f ollowing mask is correct:
11111111.11111111.00000000.00000000
Consequently, with the 255.255.255.0 mask, the f irst three octets of the IP
address def ine the network ID, and the last octet def ines the host ID in this
network. Because the maximum v alue that this octet can assume is 255, this
is also the maximum number of computers the particular network can hav e.
In this case, the f irst two groups def ine the network ID, and the last two are
the host ID in this network. The number that can be expressed by two octets
is much larger than 255; consequently, the network will be much larger.
Inf ormation about the current conf iguration of the network cards and
TCP/IP can be obtained by executing the ifconfigcommand. An example of
the execution results is shown in Listing 3.4.
You can see that Listing 3.4prov ides inf ormation f or two interf aces: eth0
and lo. The f ormer is the actual network adapter. Network adapters are
named using the ethX f ormat, where X is the number of the dev ice. Dev ice
numbering starts with zero. Thus, if there are two network cards installed in y
our computer, they will be named eth0 and eth1.
In addition to the network interf ace conf iguration inf ormation, the ifconfig
command prov ides lots of other usef ul inf ormation. For example,
theRXand TXentries contain inf ormation about the number of sent and
receiv ed packets, respectiv ely.
Another interesting piece of inf ormation giv en f or the eth0 network card is
theHWaddr(hardware address) parameter. It is also of ten called the MAC
address. This is a 48-bit unique number assigned to the card by the manuf
acturer. It is unique because each manuf acturer has its own MAC address
range. Because the lo interf ace is created by sof tware and does not actually
exist, it cannot hav e a MAC address.
down — Causes the driv er f or the giv en interf ace to be shut down. For
example, theeth0network card can be shut down by executing theifconfig
eth0 downcommand. If the ifconfigcommand is executed without arguments
immediately af terward, the particular network interf ace will not be in the inf
ormation display ed.
up — Activ ates a disabled interf ace. For example, theeth0 network card can
be put back into operation by executing this command:ifconfig eth0 up.
With the IP address and subnet mask modif ication, the interf ace can also be
started by executing this command: ifconfig eth0 192.168.77.3 netmask
255.255.0.0 up.
These are the f unctions of the ifconfigcommand that y ou will most likely
need in y our work. You can obtain more detailed inf ormation in theifconfig
manpage.
You can f ind out the computer's (host's) name with the help of the hostname
command. The same command can be used to change the computer name by
executing it with the new name specif ied as the argument. For example, the f
ollowing command sets the host name to "serv er":
hostname server
The World Wide Web is a prolif ic source of the most div erse inf ormation.
You can f ind v arious sof tware and documentation there. InAppendix 2, I
prov ide some Internet ref erences, f rom which can be downloaded programs
that can make y our work with the computer easier and more ef f ectiv e. Of
course, y ou need to hav e Internet access to be able to do this.
At present, the simplest and most conv enient program f or creating Internet
connections is KPPP. It is launched by selecting the Internet/More Internet
Applications/KPPP item sequence in the main menu. A window similar to
the one shown in Fig. 3.5 will open.
Figure 3.5: The main window of the
KPPP program
Here, y ou most of ten will only hav e to specif y the prov ider's dial-up
phone number. The rest of the parameters can usually be lef t at their def ault
v alues.
At present, most sof tware is supplied as RPM packages, which are easy to
install. The same applies to the Linux kernel. But the newest kernel v ersions
are only av ailable as source codes. This makes the kernel-update process
more dif f icult, but it also giv es y ou an opportunity to tune the sy stem f or
the maximum productiv ity. You can install only the necessary kernel
components and optimize it f or y our specif ic hardware.
Dev elopers of dif f erent Linux distributions supply their products with a
univ ersal kernel, which can work equally well on v arious platf orms. Also,
all distributions that I am f amiliar with use modules to add new f eatures to
the kernel. This is conv enient but not alway s wise f rom the security
standpoint.
Only a f ew y ears ago hackers would switch sy stem f iles with doctored v
ersions that had built-in exploits (programs allowing v ulnerabilities in sof
tware to be exploited, hence the name) or backdoors. To f ight this plague,
numerous utilities to prev ent changing of the sy stem f iles and to monitor
their checksums hav e been dev eloped.
This did not stop hackers because they switched to using Linux modules. It is
more dif f icult to monitor their integrity, and their execution produces the
same results as the sy stem f iles; moreov er, they can be used to perf orm any
tasks. This hole in sy stem security can be closed by disabling the use of
modules, but y ou should keep in mind that this may also cause problems in
the operating sy stem's work. Some hardware manuf acturers and utility dev
elopers also like to use modules. This can be understood, because modules
are easy to install and make it possible to add new or improv ed kernel f
eatures without recompiling the latter. But y ou already know that the
security and the conv enience are two incompatible concepts.
Bef ore undertaking any steps to compile the kernel, y ou should prepare f or
the worst, namely, f or the chance that instead of increased perf ormance y
our update may crash the sy stem. The kernel is the core of the operating sy
stem, and any errors while updating it can degrade its operation or ev en
cause the sy stem to become unbootable.
You should also back up any data that y ou may hav e on the serv er. In
addition, it is a good idea to make sure that y ou hav e a working bootable
diskette to help y ou if af ter the update y ou cannot boot the sy stem f rom
the hard driv e.
Here, veris the number of the kernel v ersion installed on y our sy stem. If y
ou do not know the kernel v ersion installed, y ou can f ind it out by
executing the f ollowing command:
uname -r
If the wrong v ersion is specif ied, the diskette will not be created, because
the program looks f or the necessary f iles in the /lib/modules/v er directory,
where v er is the v ersion number. In this example, this directory will be
/lib/modules/2.4.20-8.
The simplest way to install a new kernel is to do this using an RPM package.
Installing a kernel is no dif f erent than installing any other program. To
update the kernel, the f ollowing command is executed:
rpm -Uvh Package_Name
If y ou want to install a new kernel, the Uoption has to be replaced with thei
option. One of the adv antages of Linux is that sev eral kernels can be
installed at the same time. Only one of them can be booted into at any giv en
time.
Only the necessary f iles, modules, and the boot loader are installed f rom the
RPM package, but to be able to boot into the new kernel it has to be
registered in the LILO boot loader.
Updating the kernel f rom an RPM package adds new f unctions to the kernel
and f ixes the bugs that it may contain. The main capabilities of the kernel
remain the same. The maximum benef its f rom an updating can only be
achiev ed by recompiling the kernel.
When updating the kernel f rom an RPM package, dev ice driv ers may be
compiled as part of the kernel or loaded separately f rom it. This kernel is
slower but allows driv ers to be updated by simply changing the appropriate
modules.
I recommend that y ou learn how to compile, because all new kernel v ersions
are f irst released as source codes, with the corresponding RPM packages
lagging by a week or ev en longer. All this time, y our sy stem will remain v
ulnerable.
As a rule, the source codes f or the kernel are supplied as a tar archiv e. It is
unarchiv ed by executing the f ollowing command:
tar xzvf linux-2.6.10-rc2.tar.gz
The archiv e name in y our particular case most likely will be more
sophisticated than in the example. I used the current kernel v ersion at the
time this book was being written. You can download the latest kernel v
ersions f rom the www.redhat.com site.
oldconfig — This is a script that installs the def ault settings v alues without
requiring any user participation. It is inv oked by executing themake
oldconfigcommand.
menuconfig — This text mode utility (Fig. 3.6) is the most conv enient way
to conf igure the compilation f rom the console. It is inv oked by executing
themake menuconfig command.
qconf (xconfig) — This graphical utility (Fig. 3.7) is the most conv enient
way to conf igure the compilation f rom the Linux graphical shell. It is inv
oiced by executing themake xconfigcommand.
When conf iguring the compilation using one of the mentioned utilities, y ou
hav e to specif y whether the resulting kernel is to support modules.
If y ou want to hav e two same-v ersion kernels, one supporting modules and
the other not, specif y dif f erent v alues f or theEXTRAVERSIONparameter
in the makef ile f ile:
The f ollowing command will take quite a long time to execute, because it
will actually be compiling the kernel. While it is occupied with this, y ou can
go and drink a f ew cups of cof f ee. The procedure will take an especially
long time if y ou hav e an underpowered processor and less than 256 MB of
RAM.
All modules are stored in the /lib/modules directory. The make modules
command builds the modules of the new kernel, and themake
modules_installcommand installs them into the /lib/modules directory. This
directory also contains subdirectories f or each of the kernel v ersions
installed in the sy stem.
Now, look at how to conf igure the LILO boot loader to load the new kernel,
along with the old kernel v ersions. This is done by adding the f ollowing
entries at the end of the /etc/lilo.conf f ile:
iinage=/boot/vmlinuz-2.6.10
label=Linux Kernel 2.6.10
initrd=initrd-2.6.10.
img read-only
root=/dev/hda0
The f irst entry specif ies the path to the new kernel. You should specif y the
correct path, or rather, the f ile name with its own v ersion number. Thelabel
entry specif ies the text to be display ed f or the new kernel option in the boot
loader menu. Theinitrdparameter is def ined by the boot loader. The last entry
specif ies the root disk and should be the same as f or the old kernel v ersions,
which already are in the lilo.conf f ile.
Af ter updating the /etc/lilo.conf conf iguration f ile, the changes must be
recorded in the boot area. This is done by executing thelilocommand.
Reboot the sy stem; the new boot loader menu will now hav e the option f or
the new kernel in addition to the old kernel v ersions' boot options. But any of
the kernels, the new as well as the old, will be loaded using the same conf
iguration f iles, which is conv enient. Should the new kernel compilation turn
out to be nonv iable, all y ou hav e to do is reboot the computer into an old
kernel and start troubleshooting the new kernel.
The adv antage of the modularized kernel compilation is that y ou can enable
only the most necessary f unctions at boot, thereby decreasing the number of
potential v ulnerabilities than can be exploited by hackers. But y ou should be
able to control modules (in the same way that y ou can control serv ices).
The sy stem should boot only with those modules that are used. All other
modules are loaded dy namically as the need arises, and unloaded when no
longer needed. The f ollowing are descriptions of main commands used to
control modules.
lsmod
The list of the loaded modules can be v iewed using the lsmodcommand. The
result of the command's execution looks similar to the f ollowing: Module
binfmt_misc autofs
tulip
ipchains
Size Used by Not tainted 7428 1
modinfo
Deciding which modules should be included into the start-up and which
should not is not an easy task. And it is important to be able to do this,
because ev ery extra module loaded increases the boot time, requires its share
of sy stem's resources, and so on. So how are y ou to decide what is needed
and what is not? You should intimately know each module and understand its
f unction.
Some of the inf ormation display ed is the f ile's name and location, the f ile
description, the author, and the license ty pe. The amount of inf ormation
depends on the module; to tell the truth, in some cases it is so scant that it is
impossible to tell the module's f unction by it.
modprobe
The modprobecommand is mainly used by the sy stem to load the installed
modules, but it can also be used manually. The command is executed with the
name of the module to be loaded as its parameter.
For example, the f ollowing command loads the iptable_natmodule (it will be
considered in Section 4.12):
modprobe iptable_nat
rmmod
The rmmodcommand unloads the module specif ied in its argument. When y
ou are f inished using a module, do not f orget to unload it. Otherwise, it may
turn out to be the prov erbial straw that broke the camel's back, or, more
pertinent, the loophole that hackers use to penetrate y our sy stem.
Regular users should be granted limited priv ileges, suf f icient f or carry ing
out only the necessary operations. You should keep the number of users with
extended priv ileges to a minimum, because accounts of this ty pe require
special attention and monitoring. Logging into the sy stem using a priv ileged
account f rom a computer that could not possibly belong to the owner of the
account will indicate a potential or actual break-in.
As y ou already know, the f irst column (10 characters wide) display s the
access rights. Dissect its contents. The f irst character indicates the ty pe of
entry. It can be one of the f ollowing:
The rcharacter indicates the read rights, the wthe write rights, and the xthe
execution rights. No letter means no corresponding rights. Take a look at a f
ew examples.
The access rights in the f irst entry in the example are assigned as the drwx
----string. The f irst character,d, means that the entry is a directory. The next
three characters,rwx, mean that the owner of the directory has the read, write,
and execute rights f or the directory. For the f ollowing two owner categories,
the access rights are denoted by dashes, meaning that users of the Flenov G
group and all other users hav e no rights f or the directory. The access rights f
or the second entry are denoted by the drwxr-xr-x string. This is a directory
again. The f irst group,rwx, giv es all rights to the directory 's owner. The
next group,r-x, allows read and execute rights and disallows write rights to
the group's members. The last triplet, also r-x, giv es the same rights to the
group members as to all other users.
The access rights string f or the last entry in the example, -rwxr-xr-, denotes f
ile access rights, as indicated by the f irst character, the dash. The f ile's
owner has f ull rights f or the f ile, as indicated by the f irst access rights
triplet,rwx. The members of the f ile owner's group hav e read and execute
rights but not write rights, as indicated by the second access rights triplet,rx.
The rest of the users can only read the f ile, as indicated by the last access
rights triplet,r-.
Access rights can also be represented as a sequence of ones and zeros. A one
f or a certain right means that it is allowed; a zero means that the right is
disallowed. Use this notation to write the rights denoted by the rwxr-xr-
string. Replace the rights-granting characters with ones and the rightsdeny
ing dashes with zeros. The resulting combination of ones and zeros should be
111101100. Break this sequence into three groups: 111, 101, and 100. Now
conv ert each triplet into the octal notation using the f ollowing f ormula:
Digitl * 4 + Digit2 * 2 + Digit3
Consider the digits obtained — 7, 5, and 4 — as an octal number 754.
Remember this number; y ou will use it when assigning access rights to f iles
and directories. The f ollowing is a list of all possible access rights
combinations f or each position of the octal number (the user ty pe):
Try to use this list to determine, which rights f or each user ty pe represents
number 754. Compare the obtained result with the rights denoted by the
rwxr-xr-string. They should be the same.
To hav e the right to create or delete f iles, the user must hav e Note
write rights f or the directory. Some beginning administrators are conf used
by why they cannot delete a f ile ev en though they hav e all rights f or it.
Access rights to f ile sy stem objects are modif ied using the
chmodcommand. It can be used to specif y new rights to an object in both the
sy mbolic and the digital notation.
u — Owner
g— Group
o— All other users
The next digit, second f rom the lef t, sets the user rights. It can hav e v alues
in the range f rom 0 to 7.
The third-f rom-the-lef t digit sets the group rights. It can also hav e v alues in
the range f rom 0 to 7.
The least signif icant digit sets the rights of all other users. It can also hav e v
alues in the range f rom 0 to 7.
For example, y ou want the owner and the group to hav e all rights (expressed
by 7 f or each user ty pe) and all other users to hav e only execute rights
(expressed by 1). The command to set these rights will look as f ollows:
chmod 771 filename
The rights expressed numerically as 771correspond to the rights expressed sy
mbolically asrwxrwx--x. The f ollowing command disallows read rights f or
the group:
chmod g-r text
Giv ing users unnecessary access to f ile sy stem objects can end in
compromise of the sy stem's security and inf ormation leak or ev en loss. For
example, a company 's accounting f iles should be accessible only by those
who work with them. Letting ev ery one see these f iles may expose the
contents to the danger of becoming public property, which is unlikely to
contribute to the company 's welf are.
The most important saf eguard f or y our sy stem is prev enting users f rom
modif y ing sy stem f iles. The most important Linux conf iguration f iles are
stored in the /etc directory. Only a sy stem administrator should hav e the
right to modif y these f iles. This is how dev elopers of Linux distributions
conf igure the sy stem's def ault setting, and y ou should not change them to
giv e users more rights without an actual need f or this.
When a user creates a new f ile or a directory, they are assigned def ault
permissions. Consider this in an example. To create a f ile, execute an is
command and redirect its output to a f ile as f ollows:
ls -al >> testfile
Consider how the mask af f ects assignment of f ile permissions. The def ault
permissions f or f iles are set to 666 minus the mask; f or directories,
permissions are set to 777 minus the mask.
From this, it f ollows that if the mask's v alue is 002, permissions f or a new f
ile will be set as 666 - 002 = 664, or rw-rw-r-in the sy mbolic f ormat. If the
mask's v alue is 0022, the def ault f ile's permissions will be set to 666 0022 =
644, or rw-r--r-in the sy mbolic f ormat.
The def ault permissions f or new directories are calculated similarly. Thus,
with the mask's v alue at 002, a new directory 's permissions will be set to
777
- 002 = 775, or drwxrwxr-xin the sy mbolic f ormat. If the mask's v alue is
0022, a new directory 's permissions will be set to 777 - 0022 = 755, or
drwxr-xr-xin the sy mbolic f ormat. This means that all users can v iew the
directory 's contents.
All this is no good. Although the owner must hav e access rights suf f icient f
or normal operations with f iles and directories, all other users are not
supposed to hav e any rights. This can be achiev ed by modif y ing the mask.
I recommend setting its v alue to 077. Then the def ault permissions will be
set to 777 - 077 = 700 (or drwx-----in the sy mbolic f ormat) f or directories
and to 666 - 077 = 600 (or -rw------in the sy mbolic f ormat) f or f iles. Then
only the owner will hav e access rights; all other users hav ing none.
It may seem that I did not get my arithmetic correct in the prev ious
permission calculation, as 666 - 077 should equal 589 and not 600. It cannot
be correct when conv entional rules are used. Here, the subtraction operation
starts with the most signif icant digit and is perf ormed f or each position
without borrowing f rom the higher digit. That is, the f irst zero in the mask is
subtracted f rom the f irst six, then each of the sev ens in the mask is
subtracted f rom the next two sixes. If the result is negativ e, it is set to zero.
These permissions are much more acceptable f rom the security standpoint. A
new mask's v alue can be set by executing the umask mask_value command.
In this case, it will be umask 077.
4.1.5. Link Access Rights
In Section 3.1.3, hard and sy mbolic links were considered. Recall what
permissions are giv en to hard links:
913021 -rw-r--r-- 2 root root 0 Feb 22 12:19 l.txt 913021 -rw-r--r-- 2 root
root 0 Feb 22 12:19 link.txt
As y ou can see, a hard link to a f ile has the same permissions as the f ile
itself . There is no reason to expect them to be dif f erent, because hard links
hav e the same descriptors as the corresponding f iles.
The situation is much worse with sy mbolic links. The f ollowing is inf
ormation f or a main f ile (the f irst entry ) and a sof t link to it (the second
entry ): 913021 -rw-r--r-- 1 root root 519 Feb 22 12:19 link.txt 913193
lrwxrwxrwx 1 root root 8 Feb 22 12:40 symbol.txt -> link.txt
As y ou can see, the sof t link has all permissions set. In practical terms, it
means that if y ou create a sy mbolic link to the /etc/shadow f ile and do not
modif y its def ault permissions, y ou can kiss y our passwords good-by e:
They will be either stolen or deleted. Remember that any operation perf
ormed on a sy mbolic link is actually perf ormed on the f ile it points to.
If y ou hav e to use sy mbolic links, do not f orget the peculiarity of how their
def ault permissions are set. If y ou cannot rely on y our memory, y ou can
carv e something like the f ollowing reminder on y our monitor: "Sof t links
are created with f ull permissions!"
On the other hand, y ou can combine all these users into a group and grant the
necessary f ile access rights to the entire group. Af terward, should y ou need
to deny access rights f or the group, y ou will be able to do this with one
command. Don't y ou think this way is much easier than setting each user's
rights indiv idually or writing a program to do this?
In Linux, all users are assigned to one group or another. If the group is not
specif ied when a new user account is created, a new group will be created
under the user's name by def ault.
-r — This option specif ies that a sy stem group is to be created. Such groups
are assigned identif iers less than 500. Unless the -goption is also giv en, the f
irst av ailable v alue less than 500 will be assigned.
-f — This prev ents the creation of groups that hav e the same name. The
command exits with an error, the new group is not created, and the existing
group is not altered.
If some options are omitted, their def ault v alues are used. The f ollowing are
some examples of adding a group. The commands' work is explained in the
comments f ollowing the # character.
groupadd testgroup1 # Creating a group named
# testgroup1 with a default ID groupadd -g 506 testgroup2 # Creating a group
named
# testgroup2 with ID 506
groupadd -r testgroup3 # Creating a group named
# testgroup3 with a default
# system ID (less than 500)
All inf ormation about groups is added to the /etc/group f ile. Open this f ile
either in Midnight Commander or by executing the cat /etc/group command
in the console.
There will be the f ollowing three entries containing inf ormation about the
groups added at the end of the f ile:
testgroup1:x:500:
testgroup2:x:506:
testgroup3:x:11:
The group name, the password, the identif ier, and the user list are presented
in f our columns, each delimited by a colon.
No identif ier was specif ied f or testgroup1;theref ore, the sy stem assigned a
def ault ID v alue. The group ID was explicitly specif ied f or testgroup2.
Because the -roption was specif ied in the last command, the sy stem
assigned testgroup3the next av ailable def ault sy stem identif ier (11 in this
case).
The last column (af ter the third colon) is empty. It is supposed to contain the
user list, but it has not been f ormed y et.
Bef ore deleting a group, y ou hav e to change the owners of all f iles
pertaining to the group; otherwise, only the administrator will be able to
access these f iles.
A group also cannot be deleted if it has users. Consequently, all group users
must be remov ed f rom the group bef ore the group itself can be deleted.
There are quite a f ew options, most of which y ou are f amiliar with f rom
the /etc/passwd f ile considered inChapter 3. The options and their f unctions
are the f ollowing:
-e— The date when the user account will be disabled. It is specif ied in the f
ormat YYYY-MM-DD.
-f — The number of day s af ter the password expires bef ore the account will
be disabled. If set to0, the account is disabled as soon as the password
expires. The f eature is disabled if set to-1. The def ault v alue is-1.
-g — The user's initial login group. This can be specif ied either as a name or
as an identif ier. In Linux, all users are assigned to one group or another.
-G, [...] — Additional groups, to which the new user will belong. The group
names are delimited with a comma only, with no space.
-m — Instructs the user's home directory to be created if it does not exist. All
f iles f rom the /etc/skel directory will be copied to this directory.
-M — Do not create the user home directory. By def ault, the user home
directory is created as /home/user_name. To prev ent this f rom happening,
the command must explicitly f orbid this.
The last argument is the name of the new user account. Consider this process
by adding a user account named robert, with all def ault options: useradd
robert
cat /etc/passwd
The f irst command created a new user account named robert. The second
command display s the contents of the /etc/passwd f ile, where all account inf
ormation is stored. The last entry in this f ile will look as f ollows:
robert:x:501:501::/home/robert:/bin/bash
I hav e already rev iewed the f ormat of the f ile's entries in Section 3.3. The f
irst parameter is the user name. The next f ield is the password. Because the
actual password is stored in the /etc/shadow f ile, the f ield contains an x
instead of the password. The next two f ields are the UIDs and GIDs. In this
case, it just happened that the next av ailable v alues f or both of these
parameters turned out to be the same, but this is f ar f rom an ev ery day
occurrence. The f ollowing f illed f ield is the user home directory. By def
ault, all user directories are created in the /home directory and are giv en the
user's name.
Open the /etc/shadow f ile. Note that there are two exclamation points in the
password f ield of the robert entry. No password was specif ied when the
account was created, so y ou cannot enter the sy stem using this account.
Actually, I do not recommend specif y ing a password when adding the user.
This is simply extra trouble, because it has to be encry pted using thecrypt f
unction ev en though it is not certain that a strong password will be produced.
It is easier to create the password af ter the user has been added using
thepasswdcommand:
passwd robert
The command will display the f ollowing prompt to change the password,
along with the instructions on how to create a strong password: Changing
password for user robert.
Now take a look what is in the directory of the new user. Do y ou think it is
empty ? Check it out. Open the /home/robert directory and execute the f
ollowing command:
ls -al /home/robert
The -aoption display s all f iles, including the sy stem f iles, and the-1option
display s detailed inf ormation. The execution results of this command should
look similar to the f ollowing:
drwx------ 3 robert robert 4096 Nov 26 16:10 .
drwxr-xr-x 5 root root 4096 Nov 26 16:21 ..
-rw-r--r-- 1 robert robert 24 Nov 26 16:10 .bash_logout
-rw-r--r-- 1 robert robert 191 Nov 26 16:10 .bash_profile
-rw-r--r-- 1 robert robert 124 Nov 26 16:10 .bashrc
-rw-r--r-- 1 robert robert 2247 Nov 26 16:10 .emacs
-rw-r--r-- 1 robert robert 118 Nov 26 16:10 .gtkrc
drwxr-xr-x 4 robert robert 4096 Nov 26 16:10 kde
Note that there are six f iles and one subdirectory in the directory. The most
interesting inf ormation is contained in the third and f ourth columns, in
which the f ile owner's name and group, respectiv ely, are display ed. All f ile
entries contain the name robert in these columns. But although the user with
this name was just created, the group was not. The answer is simple: When a
user is created, a corresponding user group is automatically created.
Here is another f ine point. The owner of the ..directory, which is the home
directory of the robert directory, is root. That is, the user robert is the owner
of his directory (/home/robert), but he has no rights to the directory abov e his
(/home).
The user robert has read and write rights to all f iles and directories in his f
older. The users of the robert group and all other users hav e only read rights,
not write rights.
Where do the f iles in the directory of a newly -created user come f rom?
When a new user account is created, f iles and directories f rom the /etc/skel
directory are copied into the new user's home directory. Create a f ile in the
/etc/skel directory and check whether it will be copied into the home
directory of a user that y ou will create. To keep things simple, create a new f
ile by executing the f ollowing command:
ls >> /etc/skel/text
The is command display s the contents of the current directory. The two >
characters redirect its output to the text f ile in the /etc/skel directory. This
means that the results of the command's execution will be placed into the
specif ied f ile. If the specif ied f ile does not exist, it will be created. In this
way, a new f ile has been placed in the /etc/skel directory. The contents of the
f ile are of no importance.
Add a new user, and then inspect the contents of his or her home directory :
useradd Denver
ls -al /home/Denver
You should see that, along with the other f iles, the text f ile y ou created in
the /etc/skel directory was copied to the new user's home directory. I use this
handy f eature quite of ten to giv e a new user the necessary rights, f iles,
documentation, and so on.
One of the f iles in the /etc/skel directory is bash_prof ile. It contains the prof
ile of the /bin/bash command interpreter. This f ile can be used to conf igure
certain user parameters, including the access rights mask. In Section 4.1, 1
described the permissions that are assigned by def ault to all new user f iles. I
argued that the def ault permissions are f ar f rom ideal f rom the security
standpoint, and I showed how to lower them using themask command.
Log into the sy stem as robert and inspect the mask using the umask
command. Notice that it is 0022, the def ault v alue. That is, inSection 4.1we
changed the then current user's mask, but robert still receiv ed the def ault
mask. This exposes his f iles to the dangers described inSection 4.1. To prev
ent this f rom happening, I recommend adding the f ollowing string at the end
of the /etc/skel/bash_prof ile f ile:
umask 0077
Because this f ile is copied into the home f iles of all new users, placing this
string in it ensures that all new users will receiv e a proper mask f rom the
security standpoint.
To enhance the security, I do not recommend giv ing user home directories
the same names as their account names. This correspondence may play into
the hands of hackers. Once a miscreant knows a user's home directory name,
he or she can easily f igure out the corresponding user login, and v ice v ersa.
Simply adding some sort of a pref ix to a user home directory will make the
malef actor's job at least somewhat more dif f icult.
Now take a look at where the user def ault settings come f rom. They are
stored in the /etc/def ault/useradd f ile. The f ollowing are the contents of this
f ile:
# useradd defaults file
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
The useraddcommand is also used to either display or update def ault v alues
of the new user's settings. It is done by issuing the command with the-
Doption and specif y ing the f ollowing options:
-f— The new def ault number of day s af ter the password has expired bef ore
the account will be disabled
-e— The new def ault account expiration date
-s— The new def ault shell (command interpreter)
If no options are specif ied, the command simply display s the current def ault
v alues of the new user settings.
I adv ise y ou to not ignore the account expiration date option. Assume that y
our company is being audited and the auditors request access to y ou
databases and certain f iles. In this case, when creating a new account f or the
auditors to use, set its expiration date to giv e them 1 day of work (or whatev
er they may need). Then y ou will not hav e to keep it in y our head or write it
down in a notebook (which y ou still hav e to remember to consult) that on a
certain date y ou hav e delete this account: It will become inactiv e by itself .
A user account can be modif ied directly by editing the /etc/passwd f ile.
Howev er, I recommend using theusermodcommand f or this purpose. It uses
the same options as theuseraddcommand, but instead of creating a user
account, it modif ies the settings of an already -existing one.
You can use this command to add an existing user to an existing group. Do
this with the user account robert; assign it to therootgroup to allow the user
perf orm some administrativ e f unctions:
usermod -G root robert
The command was executed with the -Goption, which specif ies the groups,
to which the user is to belong (therootgroup in this case). Sev eral groups,
delimited by commas, can be specif ied. More detailed inf ormation about the
usermodcommand can be v iewed inusermod man.
The command as used here does not delete the user's directory ; y ou hav e to
do this manually. Issuing the command with the-roption will delete the user's
home directory, along with the f iles in it:
userdel -r Denver
I strongly recommend that y ou do not use the command in this way. Alway s
delete directories manually, af ter ascertaining that there are no f iles that y ou
do not wish to delete in them.
If there are no other members of the group of the user being deleted, the user
group can also be deleted by the groupdelcommand.
# *REQUIRED*
# Directory where mailboxes reside, _or_ name of file, # relative to the home
directory. If you _do_ define # both, MAIL_DIR takes precedence.
# QMAIL_DIR is for Qmail
#
#QMAIL_DIR Maildir
MAIL_DIR /var/spool/mail
#MAIL_FILE .mail
#
# Min/max values for automatic UID selection in useradd #
UID_MIN 500
UID_MAX 60000
#
# Min/max values for automatic GID selection in groupadd #
GID_MIN 500
GID_MAX 60000
#
# If defined, this command is run when removing # a user. It should remove
any at/cron/print jobs # etc. owned by the user to be removed (passed as the #
first argument).
#
#USERDEL_CMD /usr/sbin/userdel_local
#
# If useradd should create home directories for users by # default on RH
systems, we do. This option is ORed with # the -m flag on useradd command
line.
#
CREATE_HOME yes
The f ile contains some interesting settings that can be used to enhance the sy
stem security. The f unction of the parameters is explained in the comments
to them. I would only like to expand on one of them: PASS_MIN_LEN—
Minimum acceptable password length. It is used only in the
passwdcommand; the useraddcommand ignores it. In most distributions, the v
alue of this parameter is 5. I recommend changing it to at least 8. This will
make it impossible to set the qwerty password so belov ed by so many users.
I want to remind y ou again about the danger of using simple passwords, not
only by the administrators but also by the lowest sy stem user. There are lots
of exploits that allow a simple user to raise his or her rights to those of the
administrator. But to use such an exploit, the hacker f irst has to enter the sy
stem as that simple user.
To prev ent this, all users, no matter what their rights may be, must use strong
passwords. If a hacker obtains access to the /etc/shadow f ile with, f or
example, 1,000 password entries, the task of picking at least one password
becomes signif icantly easier. As y ou remember, the passwords stored in the
/etc/shadow f ile are irrev ersibly encry pted. This means that when picking
the password using a straight-search method, each possible combination is
also encry pted and then compared with the corresponding entry in the
/etc/shadow f ile. Because the encry ption is a rather processorintensiv e
process, this takes a long time if working with only one entry.
But hav ing 1,000 entries speeds up the process practically a thousandf old,
because the encry ption has to be done only once, with the result compared
with all 1,000 entries. The chances of a hit increase sev eral times.
When hackers lay their hands on the /etc/shadow f ile, the f irst thing they do
is check f or entries, in which the password is the same as the login. You
won't believ e how of ten this happens: If the password f ile is large enough,
chances are one out of ten passwords will be the same as the corresponding
login.
If this does not work, then the dictionary method is resorted to. Here the
chances of a successf ul hit are close to 100%, because out of ten users there
is bound to be one beginner who will use a simple password. You should
instruct ev ery new user in the f ine art of password creation and periodically
run a program to detect weak passwords, such as those made up of common
words. If y ou can pick such passwords, hackers can do this ev en more
easily.
Consider a classic example with f iles and directories. Suppose that directory
access permissions are set todrwxrwxrwx(or 777), and all f iles in the
directory hav e-rw------permissions. Theoretically, a f ile can be modif ied
only by the f ile owner, but this is not quite so. True, the hacker will not be
able to change the f ile itself ; howev er, he or she can read and write the
documents in the directory. This allows the hacker to simply delete the
necessary f ile and create a new one with the same name but with all access
rights.
To prev ent such a dev elopment, y ou must restrict access not only to f iles
but also to directories.
There are, howev er, situations, in which directories hav e to hav e all
permissions. This applies to shared directories used by users to exchange f
iles. At the same time, only the administrator or f ile owners should be able to
delete f iles in these directories. No user should hav e the right to delete other
users' f iles. How can the problem of hav ing a directory accessible to all, y et
allowing only specif ic users to control their corresponding contents in it, be
solv ed?
Examine the access rights to the directory by executing the ls -al command. It
should display drwxrwxrwt. Note that in the triplet that indicates all other
users' access rights, instead of the x character there stands a tcharacter. It is
this character that indicates that the sticky bit is set. Now try to delete f rom
this directory a f ile belonging to another owner. This will result in the sy
stem issuing this message: "rm: cannot unlink 'f ile_name': Operation not
permitted."
Set this bit f or all open f olders. When they cannot gain access to inf
ormation, some malicious hackers v ent their anger by deleting ev ery thing
they come across. The sticky bit ensures that hackers can delete only objects
that they hav e created.
The SUID bit can be set by executing the chmodcommands with theu+s
option as f ollows:
chmod u+s progname
If y ou examine the f ile access permissions now, y ou will see that they hav e
become-rwsr-xr-x. As y ou can see, execute permission (thexcharacter) in the
owner rights triplet has been replaced with an s character, meaning that the
program can be run by regular users but with owner rights.
The SGID bit is similar to the SUID bit, but it allows regular users to run
programs with group-owner execution rights. This bit is set the same as the
SUID bit, only with theg+soption:
chmod g+s progname
In this case, the f ile access permissions will be -rwxr-sr-x. The s character in
place of thexin the group-owner rights triplet means that any user can run this
program with group-owner permissions.
The SUID and GUID permissions are quite conv enient and usef ul, but they
harbor numerous security problems. For example, when a minimal-rights user
launches a root-rights program, the program will execute with the root-access
permissions and not with the minimal user's permissions. Should the program
contain a bug allowing commands to be executed, these commands will be
executed with the access permissions of the program's owner, that is, the root.
Consequently, ev en if hackers cannot execute commands, f or which they
hav e no rights, they will be able to do so with the help of a priv ileged
program.
The SUID and GUID bits should be used judiciously ; in no case should the
owner of an SUID or GUID program be the root or another priv ileged user.
It is better to create a special account f or such a program that has only those
access permissions that the user needs.
This policy is in line with my main rule — Ev ery thing that is not permitted
is f orbidden — and will prov ide maximum security of the sy stem.
The current attributes of a f ile can be v iewed with the help of the lsattr
command:
lsattr filename.txt
A — The f ile'satimerecord (the time that the f ile was last accessed) is not
modif ied when the f ile is accessed. From the security standpoint, this
attribute has a negativ e ef f ect, because the access date can be used to
monitor when the f ile was modif ied last. I, theref ore, recommend not
setting this attribute. But if y ou are running Linux on a home computer and
hav e no need to monitor the access history, y ou can set this attribute to
reduce the number of disk writes (by eliminating an extra write operation
when sav ing the f ile). a— A f ile with this attribute set can only be opened
in the append mode. This means that any data it already contains cannot be
modif ied or deleted.
d — When the backup utility is run, f iles with this attribute set are not
backed up. Setting this attribute allows the size of the backup to be reduced.
Howev er, y ou should only set this attribute to f iles that are of little
importance, such as temporary f iles.
s — Af ter a f ile is deleted, it cannot be restored: Its blocks are set to zeros
and then written to the disk. This means that the disk space occupied by the f
ile will be f illed with zeros.
An attribute is set by specif y ing it pref ixed with the +character; it is cleared
by specif y ing it pref ixed with the - character. Consider the f ollowing
examples:
chattr +i test
chattr +s test
lsattr test
s--i---------- test
In the f irst entry, the f ile's iattribute is set, disallowing any modif ications to
the f ile. In the second entry, the f ile'ssattribute is set. When the f ile is
deleted, its place on the disk will be ov erwritten with zeros, ensuring that it
cannot be recov ered. The command in the third entry display s the f ile's
current attributes, which are display ed in the last entry. You can see that the f
ile'ssandiattributes are set.
These attributes are mutually exclusiv e: The f ormer disallows modif ication,
and the latter requires that the f ile be completely erased f rom the disk. What
will happen if y ou try to delete the f ile? Take a look:
rm test
rm: remove write-protected file "test"?
In the f irst entry, y ou execute the rmcommand to delete the f ile. The
operating sy stem reacts to the command by asking it to conf irm the deletion
of the write-protected f ile (the message in the second entry ). As y ou can
see, the operating sy stem detected the f ile'si(no modif ications) attribute.
Enter "Y" to agree to the deletion. The sy stem issues an error message and
the f ile remains intact.
Clear the iattribute and list the f ile's updated attributes: chattr -i test
lsattr test
s------------- test
You can see that the iattribute has been cleared. Now the f ile can be deleted
using the rmcommand without any problems.
While writing this book, I was too busy to make timely updates to my site,
which is hosted by a major hosting company. Hackers did not f ail to take adv
antage of this circumstance and carried out a f ew successf ul attacks on the
site. In a 2-day period, the site's home page was changed twice, and then the
miscreants took ov er the f orum. I was f orced to remov e the f orum to a saf
e place to restore my administrator rights, editing the My SQL database
directly.
The hackers carried out the f orum break-in by exploiting bugs in the f orum's
phpBB engine. This is one of the most popular f orum engines, and because it
is f ree many site owners use it. Most hackers try to discov er bugs in the
most popular sof tware, and sometimes they succeed. Only timely updates of
the sof tware can help y ou maintain the upper hand against attackers.
Examine how the attack on my site was carried out, using an abstract site,
www.sitename.com, as an example. Opening a f orum topic causes a ref
erence similar to the f ollowing to be display ed in the address bar:
http://www.sitename.com/forum/viewtopic.php?p=5583 Appending a
Linux command to this address in the f ollowing f ormat will make the serv
er execute the command:
&highlight=%2527.$poster=%60command Linux%60.%2527 In particular,
the f ollowing command can be used to v iew the contents of the serv er's /etc
directory :
&highlight=%2527.$poster=%60 1s%09/etc%09-1a%60.%2527
And the f ollowing command will delete the site's home page:
&highlight=%2527.$poster=%60rm%09index.php%60.%2527
As y ou can see, a single buggy f orum program line can put the entire serv er
in danger.
But the danger can be minimized by limiting the access permissions of the
Web serv er. This can be done by creating a v irtual env ironment f or the
Web serv er to execute in, thereby placing other sections of the serv er out of
the hackers' reach. This will also make the /etc directory inaccessible, and the
most that malef actors can do is destroy the site and disrupt the operation of
the Web serv ice; ev ery thing else will be working uninterrupted. It is much
easier to restore one serv ice than the complete serv er.
Af ter this incident, I spent a whole day surf ing the Internet in search f or v
ulnerable f orums. It seems like there are many lazy administrators who do
not stay current with updates, because I f ound plenty of v ulnerable f orums.
I believ e that these administrators will go through some hard times soon, if
they hav e not already. Sooner or later any v ulnerable f orum will be discov
ered by hackers and its owners can only pray that the hacker is just curious
and not out to do damage. So I will nev er tire of reminding people of the
need to update all application sof tware, serv ices, and the operating sy stem
itself . You will make y our administrativ e lif e easier by f ixing bugs bef ore
hackers can f ind and exploit them.
A program working in a chroot env ironment cannot access any f ile objects
outside of this env ironment. Take a look at Fig. 4.1, which shows part of a
Linux f ile sy stem. The root directory (/) is at the top of the f ile sy stem. It
contains the /bin, /usr, /v ar, and /home subdirectories. The /home f older
contains user directories. Create a new directory (name it chroot, f or
example) in this f older to serv e as the root f or the serv ice y ou want to
isolate. It has its own /bin, /usr, and other necessary directories. The serv ice
has to work with these directories, with ev ery thing abov e /home/chroot
being inaccessible to it.
Figure 4.1: A block diagram of a
chroot f ile sy stem
The directories that the serv ice can access are enclosed in the dotted line box
in Fig. 4.1. The serv ice will work in this env ironment, considering it the
actual f ile sy stem of the serv er.
If a hacker penetrates the sy stem through a protected serv ice and decides, f
or example, to v iew the /etc directory, he or she will see the contents of the
/home/chroot/etc directory but not those of the sy stem's /etc directory. To
prev ent the hacker f rom becoming suspicious, all f iles that the sy stem /etc
directory should usually hav e can also be placed in the /home/chroot/etc
directory, but containing incorrect inf ormation. Requesting to v iew, f or
example, the /etc/passwd f ile through the v ulnerable serv ice, the hacker will
be shown the /home/chroot/etc/passwd f ile, because to the protected serv ice
it is the sy stem f ile.
This will create a new directory, named jail, containing the program's source
code in the current directory. Yes, the source code, because the program is
distributed under the GNU general public license.
Now open the jail/src directory ( cs jail/src) and edit the makef ile f ile in any
text editor (Midnight Commander, f or example). Skip the parameters at the
beginning of the f ile until y ou see the f ollowing parameters:
ARCH=__LINUX__
#ARCH=__FREEBSD__
#ARCH=__IRIX__
#ARCH=__SOLARIS__
In the f irst entry, the operating sy stem is specif ied; it is Linux by def ault.
The next three entries, f or the FreeBSD, Irix, and Solaris operating sy stems,
are commented out. Leav e them that way. What y ou hav e to change is the
installation directory, specif ied in theINSTAL_DIRparameter. The latest v
ersion (when this book was written) uses the /tmp/jail directory by def ault. I
am puzzled about why this directory is used to install the program: This is a
temporary directory accessible to ev ery one. Earlier v ersions used the
/usr/local/bin directory by def ault, and this is where I recommend y ou to
install the program. This is the editing that has to be done; do not change any
thing else in the makef ile f ile.
To execute the ensuing commands, y ou will need root rights, so either log in
as the administrator or grant y ourself root rights by executing thesu root
command.
Bef ore compiling and installing the f ile, make sure that preinstall.sh has
execute permission. If it does not, set it using the f ollowing command:
chmod 755 preinstall.sh
Now y ou are ready to install the program. In the terminal, switch to the
jail/src directory and execute the f ollowing commands:
make
make install
If y ou did ev ery thing right, there should now be the f iles addjailsw,
addjailuser, jail, and mkjailenv in the /usr/local/bin directory.
First create the /home/chroot directory to be used as the root directory f or the
program to be used to test the sy stem. This is done by executing the f
ollowing command:
mkdir /home/chroot
Now the env ironment f or the serv ice has to be prepared. This is done by
executing the f ollowing command:
/usr/local/bin/mkjailenv /home/chroot
Inspect the /home/chroot directory. There should be two new directories now:
dev and etc. As y ou know, dev ice descriptions are stored in the dev
directory. In this case, the program did not copy the entire contents of the sy
stem /dev directory, creating only three main dev ices: null, urandom, and
zero.
The etc directory also contains only three f iles: group, passwd, and shadow.
These are partial copies of the corresponding sy stem f iles. For example, the
passwd f ile contains only the f ollowing entries:
root:x:0:0:Flenov,Admin:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
The rest of the inf ormation in the sy stem's passwd f ile, including the user
robert that y ou created inSection 4.3, has not been copied to the Jail passwd f
ile. The Jail shadow f ile contains the same inf ormation as the corresponding
sy stem's f ile. Make sure that its access permissions are no greater than 600
(rw------).
The /home/chroot/etc/shadow f ile presents one security problem: It contains
the actual encry pted root's password as in the /etc/shadow f ile. You should
either delete or change this password; otherwise, if hackers get a hold of it,
they will be able to penetrate the serv er through another door that not
protected by a v irtual env ironment.
While this command is executing, it display s inf ormation about what f iles
and directories are being copied to the /home/chroot directory. For example,
such programs as cat, cp, ls, and rm are copied to the /home/chroot/bin
directory, and the serv ice will use these f iles and not those in the /bin
directory.
The program copies those f iles and directories that it considers necessary,
but the serv ice that will work in the v irtual env ironment may not
necessarily need all of them. You should delete all unnecessary f iles, but
only af ter ascertaining that ev ery thing works properly.
Now that the necessary programs hav e been copied and the v irtual env
ironment is ready, y ou can install the serv ice:
/usr/local/bin/addjailsw /home/chroot -P httpd
The preceding command installs the httpd program (the Apache serv er) and
all libraries it needs into the new env ironment. The Jail program will
determine itself , which components to install.
Now y ou can add a new user to the v irtual env ironment. This is done by
executing the f ollowing command:
/usr/local/bin/addjailuser chroot home sh name
Here, chrootis the v irtual root directory ; in the example, this should be
/home/chroot. Thehomeparameter is the user's home directory with respect to
the v irtual directory. Theshargument is the shell (command interpreter),
andnameis the name of the user whom y ou want to add. The user must
already exist in the main operating sy stem env ironment.
The f ollowing command adds a specif ic user (robert) to the v irtual directory
: /usr/local/bin/addjailuser /home/chroot \
/home/robert /bin/bash robert
The command did not f it into one line, so I carried it to another line with the
help of the\character. (The\character tells the command interpreter that the
command continues in the next line.)
If y ou did ev ery thing right, the program will display the message "Done" to
show that the user hav e been successf ully added; otherwise, it will issue an
error message.
To run the httpdserv er (the Apache serv er in Linux), there has to be the
apache user in the v irtual env ironment. There is such a user in the real sy
stem. Check what its parameters are and create the same user in the v irtual
env ironment:
/usr/local/bin/addjailuser /home/chroot \
You must keep in mind, howev er, that most commands do not work here.
For example, Midnight Commander was not installed into this env ironment;
consequently, y ou will not be able to run it.
To ascertain that y ou are in the v irtual env ironment, execute this command:
ls -al /etc
You will see only a f ew f iles, which is just a small part of the contents of the
real /etc directory. If y ou examine the /etc/passwd f ile, y ou will see that it
contains only the v irtual env ironment users. Should this f ile be
compromised by hackers, they will only obtain these data. The /home/chroot
directory will be the only area of the sy stem accessible to the perpetrators;
the rest of the f ile sy stem and sy stem serv ices will be out of their reach.
So how can y ou log into the sy stem and retain maximum rights at the same
time? Recall how Linux manages access rights. The inf ormation about user
accounts is stored in the /etc/passwd f ile in the f ollowing f ormat:
robert:x:501:501::/home/robert:/bin/bash
The third and f ourth parameters are the UIDs and GIDs, respectiv ely. When
a f ile sy stem object is giv en access permissions, the sy stem only stores the
object's identif iers. In practical terms, it means the f ollowing: Suppose there
already is a user named robert, who is assigned the identif ier 501. When
another user account is created and giv en the same identif ier, no matter what
its name may be, it will hav e the same access rights as the original account
with this identif ier.
Of what use can this possibly be? Check out the identif ier of the root user: It
is zero. And it is a zero identif ier, not the name root, that specif ies
maximum rights. Now, edit the robert entry in the passwd f ile, changing the
UIDs and GIDs to zero. When done, this entry should look like the f ollowing
string:
robert:x:0:0::/home/robert:/bin/bash
Now log into the sy stem as this user and try to open and edit the /etc/passwd
f ile or try to add a new user. You will be successf ul, ev en though only the
root can edit the /etc/passwd f ile and add a new user. The sy stem determines
the user account's rights using its identif ier, which in this case is zero and
grants the user maximum rights.
Because the user name is of no importance, I recommend deleting the root
user in the /etc/passwd and /etc/shadow f iles and replacing it with a user with
a dif f erent name but with the zero UIDs and GIDs. If hackers try to
penetrate y our sy stem, they will try to pick a password f or the root login.
They will get nowhere because there will be no such login.
On the other hand, y ou can leav e the root user but change its identif ier to
greater than zero. I sometimes create a user account named root and set its ID
to 501 or greater. When a hacker sees this account, he or she thinks that it
possess maximum priv ileges although it is just a regular user.
As y ou can see, once a hacker has penetrated the sy stem with root rights, he
or she may not continue using this account. Instead, the attacker can create
another user with any name but with the zero UID and make f urther exploits
using this new maximum-rights account. Serv er administrators should watch
f or such shenanigans and prev ent any attempts to change UIDs.
UIDs and GIDs can be f ound with the help of the idcommand. When
executed without any options, the command display s the identif iers of the
current user. To obtain the identif iers f or a specif ic user, the command is
executed with the user name as the argument, as f ollows:
id user_name
Examine the identif iers of the user account robert. Execute the f ollowing
command:
id robert
Thus, y ou can alway s determine the identif ier of any user and his or her
real rights.
Take y our time and check the entire sy stem to ensure the proper assignment
of rights. No user, f ile sy stem object, or program should hav e any rights it
does not need; at the same time, each should hav e all permissions necessary f
or proper work.
You could try to solv e the problem by using links to copies of the f iles with
other access permissions, but y ou will become conf used in the tangle of dif f
erent f iles, copies of f iles, and f ile links, all with dif f erent access
permissions.
The problem can be solv ed relativ ely easily using Access Control Lists
(ACLs), the way it is done in Windows. The dif f icult part with this solution
is that there is no standard f or Linux. In essence, this operating sy stem is a
kernel, to which any dev eloper can attach any thing he or she desires, so
each dev eloper goes his or her own way in solv ing a particular problem, or
simply leav es it alone.
I cannot recommend a univ ersal solution, because there are sev eral dif f
erent solutions by dif f erent dev elopers. This means that whatev er solution
is used, the sy stem's stability can only be guaranteed f or the already -
existing Linux kernel v ersions. There is no guarantee that the ACL sy stem
will f unction error-f ree when the kernel is updated. This is why I can only
recommend that y ou take a look at the Linux Extended Attributes and ACLs
project (http://acl.bestbits.at/). If y ou decide to employ it, y ou will be
doing this at y our own risk.
Linux Extended Attributes and ACLs is a product that requires the kernel to
be recompiled af ter the installation. Its operating principle is based on
storing extended attributes f or each f ile. Not all f ile sy stems support
extended attributes, so make sure y our sy stem does so bef ore using ACLs. I
consider Reiser and Ext3 the best f ile sy stems to use with this sof tware.
Af ter the patch and supplementary programs are installed, y ou can start
working with ACLs. An ACL allows y ou to assign indiv idual users their
own f ile access rights. The creator of the f ile remains its owner and has f ull
rights. Other access permissions f or the f ile may not be set.
Thus, in addition to the main access permissions, there will be a list stored in
the sy stem of users that hav e access to it other than those specif ied by the
main access permission.
If this approach were implemented on the kernel lev el and were supported by
all distributions, I would consider Linux the most secure and stable operating
sy stem there is.
4.10. Firewalls
I hav e considered controlling f ile access in suf f icient detail, but there are
other areas, in which access rights hav e to be controlled. Nowaday s,
computer operations are impossible without connecting to a local network or
to the Internet. Consequently, bef ore putting y our serv er into operation, y
ou hav e to limit outside access to the computer and to some of its ports.
A f irewall is the f oundation of the network security and the f irst line of def
ense f rom external inv asion. When a f irewall is installed, hackers try ing to
break into the computer through the network will hav e to pass through the f
irewall f irst, and only af ter they succeed can they mov e on and try to enter
the f ile sy stem. At this point, they will hav e to penetrate the second line of
def ense: the f ile and directory access permissions.
Why, then, do I consider the f irst line of def ense af ter the second? Because
a f irewall protects only against network attacks, whereas proper regulation of
access rights protects against both local hackers and unscrupulous users that
hav e direct access to the computer. Both def ense lines are important. Ev ery
little thing counts where security is concerned, and y ou should pay attention
to all seemingly -insignif icant details.
A f irewall can prev ent access both to the computer as a whole and to its
indiv idual ports used by serv ices. It is not, howev er, a 100% guarantee
against a successf ul break-in. It just checks that the network packets meet
certain requirements; it cannot guarantee that a right packet was sent by the
right person.
The simplest way of by passing a f irewall is to use a f ake IP address. Once I
worked with a company where regular users were f orbidden to use the
Simple Mail Transf er Protocol (SMTP) and Post Of f ice Protocol (POP3)
(connected to ports 25 and 110, respectiv ely ). I belonged to this category of
users and could not receiv e or send email. My boss, howev er, belonged to
the priv ileged class and had this access. Neither could the Web interf ace be
used to access mail serv ices; this capability was blocked at the proxy serv er
lev el. But all these security measures did not prev ent me f rom sending an
email when I really had to. Here is how I did this:
Sent the email and changed my IP address back to what it was supposed to be
When my boss came back, he did not make much of his computer being of f ;
he thought that is simply hung and did not suspect a thing. So I used the serv
ice I was not supposed to use without any adv erse consequences f or hav ing
done this.
Although there are many way s to by pass a f irewall (not counting those
made av ailable by bugs), a properly -conf igured f irewall will make the liv
es of the administrator and the security specialist much easier.
In Linux, the f irewall f unction is perf ormed by a program that f ilters inf
ormation based on a set of certain rules clearly prescribing, which packets
can be processed or sent onto the network and which cannot. This makes
most attacks f ail without ev en hav ing entered the computer, because the f
irewall does not let the serv ices ev en see potentially dangerous packets.
A f irewall can be installed on each indiv idual computer (to prov ide
protection according to the tasks perf ormed) or at the network entrance (Fig.
4.2). In the latter case, the f irewall prov ides common protection f or all of
the network's computers.
Figure 4.2: A network f irewall
But there is one weak link in all f irewalls: They are sof tware-implemented
and use resources of the serv er they are installed on. Modern routers can also
prov ide many f unctions perf ormed by Linux f irewalls. On the other hand,
Linux sy stems are of ten used as routers to keep the cost of the sy stem low
by putting to use old computers that cannot be used f or any other
contemporary task.
The main, but not the only, task of a f irewall is f iltering packets. There is
already a f irewall built into Linux, and y ou do not hav e to install it
separately. In f act, there are two f irewalls:iptablesandipchains. They make it
possible to control the Transmission Control Protocol (TCP), User Data
Protocol (UDP), and Internet Control Message Protocol (ICMP) traf f ic
going through the computer. Because TCP is the main transport f or all other
main Internet protocols — FTP, HTTP, and POP3 — f iltering TCP traf f ic
allows all these serv ices to be protected.
All requests f rom or to the Internet must pass through the f irewall, which
examines them f or compliance with the specif ied rules. Packets in f ull
compliance are let through. But if at least one of the rules is not met, the of f
ending packet may be deleted in one of the f ollowing two way s:
Denied — Without inf orming the sending party about this Rejected — Inf
orming the sending party about this
I would not conf igure my f irewall in the latter way ; doing so would prov
ide hackers with extra inf ormation. It is better to delete of f ending packets
without inf orming the sending party and hav e it think that the serv ice is
simply unav ailable. But this is f raught with the danger of legitimate users
experiencing problems in case of incorrect f irewall conf iguration. Suppose
that y ou mistakenly blocked access to port 80, used by the Web serv ice. If a
client program tries to access the Web serv er behind the f irewall and does
not receiv e an answer, it will wait until the timeout. The timeout v alue can
be inf inite f or some programs, and they will hang. You will hav e to correct
the f irewall conf iguration error to let the user work trouble-f ree.
Moreov er, package-rejection messages are sent using ICMP and increase
channel traf f ic. A hacker can take adv antage of this to carry out a denial-of
serv ice (DoS) attack to f lood y our channel with superf luous
packagerejection messages. DoS attacks can be directed not only against traf
f ic but also against computer resources. A hacker can run a program
repeatedly asking to establish a connection with a disabled port, which will
cause y our computer to waste resources (processor time, memory, etc.)
examining the packets and sending rejection messages. If packets arriv e at a
f ast rate, the serv er may not be able to handle the load and may stop
answering requests f rom the legitimate users.
Firewall f ilters can be conf igured using one of the f ollowing two principles:
Ev ery thing that is not f orbidden is permitted. Ev ery thing that is not
permitted is f orbidden.
The latter way is more secure, because y ou start by f orbidding ev ery thing.
Then, as a need arises, y ou can allow access f or specif ic users to specif ic
serv ices. You should adhere to this policy when conf iguring y our f irewall f
ilters f or incoming packets.
When starting with ev ery one being permitted ev ery thing, it is easy f or the
administrator to simply f orget to limit some access rights and discov er the
ov ersight only when the sy stem is penetrated and damage has been inf
licted.
Packet f iltration is perf ormed by the f ollowing main packet parameters: the
source or destination port number, the sender or recipient address, and the
protocol used. As y ou already know, f irewalls supports three main protocols
(TCP, UDP, and ICMP) that f orm the f oundation f or all serv ices (FTP,
HTTP, POP3, and others).
But why f ilter outgoing traf f ic? At f irst it may seem senseless, but there are
important reasons f or this. Outgoing traf f ic can be less innocent than y ou
may think. It may be generated by Trojan horse programs sending conf
idential inf ormation gathered on y our hard driv e to some email address, or
connecting with the author's serv er to download f urther instructions f rom
there.
It will take a prof essional all but 5 minutes to write such a program.
There are many loopholes to penetrate y our computers, and y our task is to
close as many of them as possible. Consequently, y ou must control traf f ic
going in both directions.
Protocols
The base data transf er protocol f or HTTP, FTP, and other protocols is TCP.
It will make no sense to prohibit it, because this will depriv e y ou of all the
niceties of the World Wide Web. TCP transmits data by f irst establishing a
connection with the remote host and only then conducting data exchange.
This makes f aking the IP address of any of the connection parties more dif f
icult and sometimes ev en impossible.
UDP is the same lev el protocol as TCP, but it transmits data without
establishing a connection. This means that the protocol simply sends its data
onto the network to a specif ied address without ensuring that this address is
reachable f irst. In this case, there is no protection against f aking the IP
address, because the attacker may specif y any address as the source and the
receiv ing side will see nothing suspicious. Unless there is a justif iable need,
I prohibit UDP packets in both directions.
Port Filtration
The f irst thing that y ou hav e to pay close attention to is ports. Suppose that
y our Web serv er is open to all users. Also suppose that it serv es absolutely
saf e scripts (this is f rom the realm of f antasy, but suppose this f or the
example's sake) and/or static Hy perText Markup Language (HTML)
documents. Moreov er, all sof tware is current on updates and has no v
ulnerabilities. Does all this make the serv er really secure? Yes, but only f or
the time being. Sooner or later, y ou will hav e to update y our absolutely
secure scripts (dream on) and static HTML documents. It is doubtf ul that y
ou will use diskettes as the update v ehicle and will need some other way to
upload the update. Most of ten, f iles are transf erred using an FTP serv ice,
and this is where y ou breach a hole in the impenetrable wall of y our serv er
f ortress.
Only the most secure programs should use the FTP access and the strongest
passwords; nev ertheless, sooner or later hackers will break into this serv ice.
Passwords can be picked, stolen f rom some user's computer, tricked out of
some gullible employ ee with the help of social engineering, or obtained in
other countless way s. If there is a channel leading into the sy stem, it is v
ulnerable, because hackers will not be try ing to break in through nonexistent
channels but will concentrate their ef f orts on something that will ev entually
y ield to their relentless digging. Although the f irst one to try to break in may
walk away with nothing to show f or his or her pains, the second, the third, or
the hundredth may get lucky, break in on the f irst try, and destroy ev ery
thing he can lay his hands on.
Suppose that there are two Web serv ers on y our network, which happens
quite of ten. One of the serv ers is made av ailable f or all Internet v isitors,
and the other serv ices only company users (an intracompany site). In this
case, it will be logical to div ide the inf ormation into two categories: one f or
internal use and the other f or external. Then the closed serv er can serv ice
only the local network traf f ic regardless of what port it passes through.
This step was justif ied because carding was f lourishing in many of those
countries. (Carding is when stolen credit-card inf ormation is used to
purchase merchandise on the Internet.) To f ight this ev il, at least the greater
part of it perpetrated by the citizens of those countries, the serv ice disallowed
access to their serv er f rom whole batches of IP addresses. The ef f ect was
nil, because the prohibition turned out to be easy to by pass. All that a lov er
of f ree stuf f had to do to break through the barrier was use one of the anony
mous proxy serv ers in the United States or Canada. The bona f ide customers
f rom the banned countries, on the other hand, experienced serious problems
and were not able to use the serv ice to get paid f or the serv ices they had
prov ided.
I hav e not heard of such attacks f or a long time, but it cannot be ruled out
they will not happen. There are numerous IP addresses that should be f iltered
out and not let into y our network.
127.0.0.1 — This address is used to specif y the local machine (local host);
consequently, no packet can originate f rom this address on the Internet.
The Linux kernel contains the f ollowing three main rule chains: Input — For
incoming packets Output — For outgoing packets Forward — For transiting
packets
Users can create their own chains linked to a certain policy ; this subject,
howev er, is bey ond the scope of this book.
Linux checks all rules in the chain, which is selected depending on the
direction of the transf er. A packet is examined f or meeting each rule in the
chain. If it does not meet at least one rule, the sy stem decides whether to let
the packet through and carries out one of the actions specif ied f or this rule:
deny, reject, or accept.
This means that if a packet is f ound not to conf orm to one of the rules, it is
no longer checked f or conf orming to the f ollowing rules in the chain. For
example, suppose that y ou want to open port 21 f or y ourself only. This can
be done by the f ollowing chain of two rules:
Prohibit all incoming packets on port 21. Allow packets originating f rom
address 192.168.1.1 to port 21.
For the policy to work, the places of the rules hav e to be swapped. Then an
arriv ing packet is f irst checked f or originating f rom address 192.168.1.1
and is let through if it is. If it is not, it is ev aluated against the second rule,
triggering the prohibition f or all packets to enter port 21.
Packets routed to other ports do not meet the criteria f or the rules and will be
processed in the def ault order.
Don't be lulled into a f alse f eeling of security af ter hav ing installed a f
irewall: There are many way s to circumv ent not just a specif ic f irewall but
all of them.
Any f irewall is just a security guy at the f ront door. But the f ront door is
nev er the f irst choice as a point of entry f or a burglar. Burglars usually opt f
or the back door or a window. For example, Fig. 4.2 shows a protected
network and the f ront door: the Internet connection through a dedicated
computer running a f irewall. But if one of the network's computers happens
to be equipped with a modem but without a f irewall, this will create a back
door to the network, without any doorman standing guard around the clock
I hav e seen serv ers, f or which Internet access was permitted f rom only a
certain list of IP addresses. The administrators believ ed that this measure
would protect them f rom hackers. They are mistaken here, because an IP
address is easy to f ake.
At one time, I worked with a company where Internet access was controlled
by IP addresses. My monthly Internet traf f ic was limited to 100 MB, while
my neighbor had unlimited access. To conserv e my traf f ic, I did not use my
quota to download large f iles but only to v iew Web pages. When I needed to
download something, I did the f ollowing:
Waited until the neighbor's computer was not in use, f or example, when the
owner went to lunch.
Slightly pulled the network cable on the neighbor's computer out of the
network card socket to break the connection.
Assigned my computer the IP address of my neighbor and downloaded all
that I wanted to download.
Hav ing f inished, returned the IP addresses and the network cable to their
regular places.
In this way I was able to download all I needed ov er a month.
With modern f irewalls, simply switching the IP address will not help y ou
enter the sy stem. The identif ication techniques they use now are much more
sophisticated than simple IP-address checking. Switching the IP address may
only prov ide more priv ileges within the sy stem, and ev en this is only the
case if the network is not conf igured properly. But administrators worth their
salt will not allow such machinations ev en within the network, using MAC
addresses and access passwords to assign access rights.
A f irewall is a program that runs on a computer under the control of the
operating sy stem (a sof tware f irewall) or on a phy sical dev ice (a hardware
f irewall). But, in either case, this program is written by humans who, as we
all well know, are prone to error. Just like with the operating sy stem, the f
irewall needs to be updated regularly to repair the programming bugs that are
inev itably present in all sof tware.
A password or a dev ice like touch memory or smart card is of ten needed to
pass through a f irewall. But if the password is not protected, all of the money
inv ested in the f irewall will be wasted. Hackers can obtain the password in
one of a number of way s and use it to penetrate the f irewall. Many sy stems
hav e been broken into in this manner.
Passwords must be strictly controlled. You must control each user account.
For example, if an employ ee with high sy stem priv ileges quits, his or her
account must be disabled immediately and all passwords, to which the
employ ee had access, must be changed.
I was once called to a company to restore data on its serv er af ter they f ired
the administrator. He considered the termination of his employ ment unf air
and, a f ew day s later, destroy ed all inf ormation contained on the main serv
er without any problems. Ev en the well-conf igured f irewall did not stop
him. This happened because the f irewall was conf igured by the malef actor
himself . This ty pe of thing should nev er be allowed to happen, and the f
irewall must be conf igured so that not ev en a network administrator can
break through.
I alway s recommend to my clients that only one person knows the highest
lev el f irewall password. In a corporation, this should be the chief of the inf
ormation-processing department. In no case should it be a regular
administrator. Administrators come and go, and there is a chance of f
orgetting to change some password af ter the next administrator leav es.
From the preceding section, y ou may get the impression that f irewalls are a
waste of money. This is not the case. If the f irewall is properly conf igured,
is constantly monitored, and uses protected passwords, it can protect y our
computer or network f rom most problems.
A quality f irewall prov ides many lev els of checking access rights, and a
good administrator should nev er be limited to using just one. If y ou use only
the IP address check to control Internet access, y ou can start looking f or a
bank loan to pay y our Internet bill, because this address can be easily f aked.
But a sy stem, to which the access is controlled by the IP address, MAC
address, and password, is much more dif f icult to compromise. Yes, both
MAC and IP addresses can be f aked. To make sure that they are not, indiv
idual computers can be tied to specif ic port switches. In this case, ev en if the
hacker learns the password, he or she will hav e to use it at the computer, to
which it is assigned. This may require some ingenuity.
The protection can, and must, be multilev el. If y ou hav e data that need
protecting, use the maximum number of protection lev els. There is no such
thing as too much security.
Imagine y our av erage bank. Its entrance door will be much stronger than y
our av erage house or apartment door and equipped with an alarm sy stem to
boot. But if someone comes to do his or her banking in a tank, these
protections will be of little use.
In addition to protecting the premises with a good door, banks keep their
money in saf es, which are themselv es are placed into v aults. Money kept in
a bank can be compared to secret inf ormation stored on a serv er, and it must
be prov ided with maximum protection. This is why banks keep their money
in saf es equipped with sophisticated locks that take thiev es a long time to
open. While they are at it, there's more than enough time f or the cops to arriv
e on the scene.
To extend the bank saf e analogy to serv ers, here the role of the saf e is play
ed by encry ption. So, ev en if a hacker by passes the f irewall and reach the
data on the serv er, it will take too much time to decry pt them. He or she can
be nabbed while still sitting at the desk. But ev en if the hacker carries the saf
e away to crack at his or her leisure, meaning downloading the data to decry
pt them without being bothered, the chances are great that the inf ormation
will become obsolete by the time it can be decry pted. The important thing
here is that the encry ption algorithm and the key are suf f iciently
sophisticated.
The easiest way to conf igure the Linux f irewall is to use the built-in
graphical utility. Load the KDE graphical shell and select the Main
Menu/System/Firewall Configuration menu sequence. This will open the
Firewall Configuration dialog window with two tabs on it: Rules and
Options.
First, open the Options tab (Fig. 4.3). Here y ou can specif y def ault actions
f or each of the packet ty pes and restrict ICMP packet transit.
Figure 4.3: The
Options tab
On the Rules tab (Fig. 4.4), f iltration rules can be created, deleted, or edited.
A rule is created by clicking the Add button. This will open the dialog
window shown in Fig. 4.5.
Do not change any settings f or now. Just f amiliarize y ourself with the
appearance of the Firewall Conf iguration utility and its capabilities. You can
engage in conf iguration activ ities later, when y ou learn how to work with
using the ipchainsprogram, which is used to conf igure the f irewall f rom the
command line.
-I chain number rule — Insert the rule into the specif ied chain under the
specif ied number. For example, if number equals 1, the rule will be the f irst
one in the chain.
-p protocol — Def ine the protocol cov ered by the rule. The v alue of
theprotocolargument can betcp, udp, icmp, or all(the latter indicates that the
rule extends to all protocols).
-i interface — Def ine the network interf ace cov ered by the rule. If this
argument is not specif ied, the rule will extend to all interf aces.
--j action — Def ine the action to apply to the packet. EitherACCEPT,
REJECT,orDENYcan be specif ied as arguments.
--s address port— Set the attributes of the packet's sender.
Theaddressargument specif ies the source IP address; theportargument
(optional) specif ies the source port. Be caref ul: ICMP has no ports.
Based on the total prohibition principle, the def ault rule should prohibit any
actions. The def aultipchainssettings permit ev ery thing, which is only saf e f
or a standalone computer, not connected to a network. You can check the def
ault setting by executing theipchains -Lcommand.
In some distributions, the def ault ipchainssettings may be absent; then the sy
stem will issue the f ollowing error message:
ipchains: Incompatible with this kernel
This message can be issued if ipchainsis not installed or has been started
incorrectly. I hav e been greeted with this message sev eral times because the
distribution's dev elopers did not conf igure the sy stem def ault settings
properly. This bug is easy to f ix and does not require any operations on the
kernel.
If the f ile does not exist, it has to be created. This is done by executing the f
ollowing command:
cat >> /etc/sysconfig/ipchains
Now, commands that y ou enter f rom the console will be sav ed to the f ile.
To make theipchainsserv ice work, enter the f ollowing command f rom the
console:
:input ACCEPT
Now press the <Ctrl>+<D> key combination and restart the ipchainsserv ice
using the f ollowing command:
/etc/rc.d/init.d/ipchains restart
Be caref ul to specif y the f ull path in the command. Otherwise, the ipchains
utility will be started and will not launch the script f rom the /etc/rc.d/init.d/
directory.
Now specif y the def ault policy. This is done by executing the ipchains
command with the-Pparameter and specif y ing the security policy f or each
chain:
Note that f or the incoming (input) and transiting (f orward) packets I specif
ied complete denial, so they will be deleted without any warnings. The def
ault policy rule f or the outgoing packets can be specif ied asREJECTso that
the inside clients could be inf ormed of the error when attempting to connect
to the serv er.
Now, y our computer is inv isible and cannot be accessed f rom the network.
Try to scan the serv er's ports or ping it. Both actions will produce no results,
as if the computer were not connected to the network.
Now y ou can start specif y ing rules to allow some access to the serv er. You
should be aware that a rule appended to a chain may not work as intended.
There may already be a rule in the chain bef ore the one being added that will
prev ent packet processing against the new rule. To av oid this pitf all, I place
new rules at the head of the chain (by specif y ing the-Iand1options).
The rule prohibiting ev ery thing should be placed at the end of the chain.
Rules f or a specif ic action, port, or address should be placed at the head of
the chain.
Suppose that all users should be able to work with port 80 (the def ault Web
serv er port) of the public Web serv er. This is achiev ed by executing the f
ollowing commands:
ipchains -I input 1 -p tcp -d 192.168.77.1 80 -j ACCEPT ipchains -I output 1
-p tcp -s 192.168.77.1 80 -j ACCEPT
The port can be specif ied by either its name or its numerical identif ier. Thus,
to specif y the port by its name, the preceding commands will look like the f
ollowing:
ipchains -I input 1 -p tcp -d 192.168.77.1 web -j ACCEPT ipchains -I output
1 -p tcp -s 192.168.77.1 web -j ACCEPT
Here, the port is specif ied by its name,web, instead of its numerical identif
ier,80. Theipchainsprogram will process either argument correctly.
Examine each option of the f irst command:
-I input 1 — The-Ioption indicates that the rule should be placed in the chain
in the specif ied position. The argument f ollowing-Ispecif ies the chain, to
which the rule is to be added:input. The number1specif ies the position in the
chain to place the rule in; that is, it will be the f irst one in the chain.
-p tcp — The Web serv er operates under HTTP, which uses TCP as the
transport protocol. Do not f orget to specif y the protocol explicitly using the-
poption. Otherwise, y ou will open access to serv ices on two ports: TCP and
UDP. If y ou are lucky, there will be no program using UDP port 80 at this
time.
So the f irst rule allows ev ery one to send requests to the serv er. But the
main f unction of a Web serv er is to serv e the pages requested by clients.
This requires port 80 of my serv er (192.168.77.1) to be open f or outgoing
packets. This is achiev ed by the second command.
Executing the ipchains -Lcommand will display the f ollowing contents of all
y our chains:
Chain input (policy DENY): target prot opt source ACCEPT tcp ------
anywhere destination ports
flenovm.ru any -> http
Chain output (policy DENY): target prot opt source ACCEPT tcp ------
flenovm.ru anywhere http -> any Chain icmp (0 references):
destination ports
A new entry has been added to the inputand outputchains. Note that the IP
address of my computer in the sourceand destinationf ields was replaced with
its domain name:flenovm.ru. The serv er will do this substitution if it can
map the address to the name. Also, the numerical designation of the port is
replaced with its sy mbolic name in the ports f ields:httpinstead of 80.
I recommend that y ou study caref ully the list of created f ilters to be able to
understand clearly each of its parameters. Consider the structure of rule
chains using the inputchain as an example:
target — The action that will be perf ormed on the packet meeting the f ilter
requirements. In this case, the ACCEPT v alue means that the packet will be
let through; otherwise, the packet is destroy ed.
prot— The protocol,tcpin this case.
opt— Extra options. These were not specif ied in the example, so there are
dashes in their place.
source— The packet's source. The word anywheremeans that the packet can
originate on any computer.
destination— The packet's destination. This can be specif ied by either the
computer's name or its IP address.
ports — The ports, specif ied in the source -> destination f ormat. In this
case, the source port can be any, while the destination port can be only 80
(http).
-s 192.168.77.10 -j ACCEPT
ipchains -I output 1 -p tcp -s 192.168.77.1 21 \
-d 192.168.77.10 -j ACCEPT
The f irst command allows packets originating f rom any port of the computer
with the IP address 192.168.77.10 to reach port 21 of the serv er with the IP
address 192.168.77.1. The second command allows outgoing packets f rom
port 21 of the serv er with the IP address 192.168.77.1 to be addressed to the
client computer with the address 192.168.77.10.
This, howev er, will not put the FTP serv ice into operation. An FTP serv er
requires two ports: Port 21 is used to exchange commands and port 20 is used
to exchange data. Access to port 20 is opened by executing the f ollowing
commands:
ipchains -I input 1 -p tcp -d 192.168.77.1 20 \
-s 192.168.77.10 -j ACCEPT
ipchains -I output 1 -p tcp -s 192.168.77.1 20 \
-d 192.168.77.10 -j ACCEPT
Now the computer with the address 192.168.77.10 has f ull access to the FTP
serv ice, which is not av ailable to any other IP addresses. Scanning the serv
er f rom any computer in y our network will show that only port 80 is open;
ports 21 and 20 can be seen only f rom the 192.168.77.10 computer.
Examine the current state of the rule chains by executing the ipchains -L
command. The display ed inf ormation should look similar to the f ollowing:
Chain input (policy DENY):
target prot opt source Destination ports ACCEPT tcp ------ 192.168.77.10
flenovm.ru ACCEPT tcp ------ 192.168.77.10 flenovm.ru
ACCEPT tcp ------ anywhere flenovm.ru any -> ftp-data any -> ftp
any -> http
Chain forward (policy DENY):
Chain output (policy DENY): target prot opt source destination ports
ACCEPT tcp ------ flenovm.ru ACCEPT tcp ------ flenovm.ru ACCEPT tcp --
---- flenovm.ru Chain icmp (0 references): 192.168.77.10 ftp-data -> any
192.168.77.10 ftp -> any anywhere http -> any
The f ilters described in this section let through any packets regardless of the
interf ace. This is justif ied in most cases, but the loopback interf ace (which
alway s points to the local machine) requires no protection. It can only be
used locally ; no hacker can connect to y our computer through this v irtual
interf ace f rom a remote computer. So it will be only logical to allow all
packets through the loopback:
ipchains -A input -i lo -j ACCEPT
ipchains -A output -i lo -j ACCEPT
Try to cancel access to the FTP serv ice by deleting rules f rom the input
chain. I picked the FTP serv ice as an example because here two rules hav e
to be deleted and y ou hav e to be caref ul about how y ou do this. At f irst
glance, it may seem that the f ollowing two commands will produce the
desired result:
ipchains -D input 1
ipchains -D input 2
Executing the f irst command will modif y the contents of the input chain to
the f ollowing:
Chain input (policy DENY):
target prot opt source Destination ports
ACCEPT tcp ------ 192.168.77.10 flenovm.ru any -> ftp ACCEPT tcp ------
anywhere flenovm.ru any -> http
The rule f or the ftp-dataport, the f ormer rule number 1, is gone, which shif
ted the order of the remaining rules in the chain one position up. Thus,
executing the second command intended to delete the rule f or the ftpport
(port 21) will delete the rule f or the httpserv er, which is now the current rule
2, leav ing access to the ftpport intact. This mix up is easy to notice and
correct with only three rules in the chain. But what if there are a hundred
rules? It will be rather dif f icult to f igure out which rule was deleted
improperly. To av oid this problem, start deleting higher numbered rules and
proceed downward. In this case, the commands should be executed in the f
ollowing order:
ipchains -D input 2
ipchains -D input 1
There is another way of deleting rules f rom a chain, which is more reliable.
To consider it, y ou will need to create a rule in theforwardchain. Execute the
f ollowing command:
ipchains -A forward -p icmp -j DENY
Here the-Aoption is used, which appends the rule to chain (empty in this
case).
If f orwarding is disabled in y our sy stem, the rule will be added Note but the
sy stem may issue a warning. Forwarding will be
considered in detail inSection 4.11.7.
Inv estigate what this rule does. It will be triggered by an ICMP packet that
has to be f orwarded. TheDENYf ilter means that the packet will be simply
deleted. In this way y ou will hav e blocked f orwarding of the ICMP traf f ic.
To prohibit ICMP packets altogether, the f ollowing rule has to be added:
ipchains -A input -p icmp -j DENY
Now delete a rule f rom the f orward chain. This is done by executing the
same command as used f or adding the rule but with the-Doption instead of
-A(or instead of -I, if y ou used the insert option to add the rule). The
resulting command should look like the f ollowing:
ipchains -D forward -p icmp -j DENY
Rules of ten hav e to be specif ied in the "ev ery thing but" f ormat. For
example, y ou hav e to f orbid access to the Telnet port to all except the
computer with the 192.168.77.10 IP address. The best way to proceed will be
to f irst allow access to the port f or the 192.168.77.10 computer and then f
orbid access to any one else. Theinputchain will hav e the f ollowing two
rules in this case:
These rules are based on the assumption that the def ault policy is to allow
connections f rom any address. In that case, all incoming packets will be
checked f or compliance with the f irst rule and either let through (meeting
the 192.168.10 requirement) or passed to the second rule (not meeting the
192.168.77.10 requirement). The second rule simply deletes all incoming
packets that reach it.
The same result can be achiev ed with only one command. The rule in this
case is f ormulated as f ollows:
ipchains -I input 1 -p tcp -s ! 192.168.77.10 telnet -j DENY
In this command, all TCP packets (as indicated by the -p tcpoption) not
originating f rom the 192.168.77.10 address (the -s option) are prohibited (by
the-j DENYoption) f rom connecting. The!character denotes the not-equal
logical condition; that is, all packets not originating f rom the specif ied
source will meet the condition.
This command will work only if the def ault policy is to allow all packets.
Otherwise, packets sourced by the 192.168.77.10 computer will be deleted
any way.
The !character can also be used with ports. For example, y ou need allow f ull
access to the serv er with the exception of the Telnet port f rom the
192.168.77.12 address. Then the def ault policy should be deny ing all traf f
ic and issuing the f ollowing command:
ipchains -I input 1 -p tcp -s 192.168.77.12 ! telnet -j ACCEPT
This command allows f ull access to the serv er to all TCP packets f rom the
192.168.77.12 address with the exception of the Telnet port, the latter
prohibition indicated by the!character in f ront of the port name.
The protocol that many administrators f ind most dif f icult is ICMP, which is
required by RFC 792 f or the TCP/IP operation. But standards are not alway s
f ollowed in ev ery day lif e, and TCP/IP can work on computers, on which
ICMP is prohibited.
TCP is the most commonly used protocol, and any one inv olv ed with
networks has to deal with it to a v ary ing extent. The UDP in its
characteristics is similar to TCP, so most of those who are f amiliar with TCP
hav e no problems with this protocol either. But f ew are f amiliar with
ICMP, and many ev en f ear this protocol. Some people ev en believ e that it
would cause no harm at the worst and be benef icial at the best to simply
eliminate this protocol. This opinion, howev er, is f ormed because of lack of
understanding of this protocol's importance.
ICMP allows two network nodes to share inf ormation about the errors. It is
used to send packets not to a certain program but to the computer as a whole;
theref ore, it does not use any ports. Its packets, howev er, do hav e a ty pe
and a code. You can v iew these parameters by executing theipchains
-h icmpcommand.
Most of ten, ICMP packets are sent in response to a nonstandard situation.
Table 4.1 lists the main ty pes and codes of the packets.
Table 4.1: The main types and codes of ICMP packets Type Code
Description
0
thepingutility v erif y ing that there is a connection with a remote computer to
request a reply f rom the host.
9
and 0 These message ty pes are sent by routers.
10
When creating a rule, the ty pe of the ICMP message is specif ied in the same
way as the port f or TCP; the code is placed af ter the-doption. For example,
the f ollowing command prohibits ty pe 3 code 1 ICMP packets: ipchains -I
output 1 -p icmp -s 192.168.8.1 3 -d 1 -j DENY
Some administrators do not pay enough attention to ICMP. They make a
serious mistake doing this, because ICMP was used to perpetrate many
attacks. Moreov er, TCP traf f ic can be transmitted using ICMP messages
employ ing the tunneling technique.
4.11.7. Forwarding
All prev iously -considered rules only regulate access to the computer. But if
a computer is used as a dedicated f irewall, it will mostly deal with f orward
rules.
If y ou place a serv er prov iding public serv ices within the network, y ou
will hav e to create f irewall rules allowing all users f rom the Internet to
access it. Such rules were considered in Section 4.12.2; but that was only an
example, and in real lif e all public serv ices must be placed outside of the
priv ate network.
If , f or some reason, y ou hav e no other way to prov ide Web serv ice but
placing the serv er on y our network, I recommend that y ou organize the
arrangement as shown in Fig. 4.7. This will require an additional serv er,
howev er, to organize the second f irewall.
In the network arrangement shown in Fig. 4.7, Firewall 1 protects the Web
serv er. Its policy should be relativ ely mild to allow public access to some of
the serv er's ports, such as port 80 f or Web site browsing. The important
thing is that the f ilters allow public access to the address of the public serv er
and the designated ports on it only.
The second f irewall protects the local network; consequently, its rules must
be more stringent and restrict any outside connections. Moreov er, there
should be no trusting relations between the public serv er and the local
network. Allowing this serv er to f reely connect to any of the ports on the
local network negates the whole idea of using this arrangement. Should there
be a bug in the Web serv er's sof tware or the sites it serv es, it can be
exploited to execute commands on the serv er and establish connections with
the network on behalf of the Web serv er without ev en hav ing to break
through the second f irewall.
Some organizations, in addition to the public serv ers, place sev eral
computers between the two f irewalls in the arrangement shown in Fig. 4.7.
These are usually obsolete computers creating an appearance of a network to
conf use hackers. There is no important inf ormation on such sham networks.
There are, howev er, v arious intrusion-detection tools installed on them to
inf orm the administrators about unauthorized access attempts.
These bogus networks prov ide a certain lev el of protection against hackers
by taking them of f the right track — at least f or a while. The machines can
hav e v arious ports opened and store seemingly important but actually
useless inf ormation to whet the intruders' appetite and keep them rummaging
in the junky ard.
Another way to prov ide some extra protection f or y our network is to equip
the f irewall computer with three network cards. One of the cards prov ides
the Internet connection, another connects the priv ate local network, and the
last one connects the public network (see Fig. 4.8). Access to the public interf
ace is quite liberal, and the priv ate interf ace is protected with all av ailable
means.
The arrangement shown in Fig. 4.7has more ef f ectiv e security than the one
in Fig. 4.8. There the local network is protected by two f irewalls, which are
also easier to conf igure. The arrangement shown in Fig. 4.8is simpler and
less expensiv e, because it does not require an additional computer f or the
second f irewall. Howev er, this arrangement prov ides less security. Once a
hacker penetrates this f irewall computer, he or she will experience f ewer dif
f iculties breaking into the priv ate local network.
But let me return to the subject of f orwarding. Fig. 4.6shows a local network
connected using twisted pair to the central switch. Trace the routes that
packets in this network can f ollow. To reach the Internet, a packet f rom any
network computer passes through the switch, enters the f irewall computer
through one network adapter (call iteth0), and exits the f irewall computer
through another network adapter (call iteth1) onto the Internet.
The subject of allowing Internet access is cov ered in detail in Chapter 9. For
now, only the subject of conf iguring traf f ic-f orwarding security will be
considered.
A f irewall not only can inspect packets f or compliance with the f ilter rules
but also can hide addresses of the network's computers. This is done as f
ollows: 1. A packed placed by a client on the network trav els to the f irewall
with its own IP address.
2. The f irewall replaces the IP address of the sender with its own and f
orwards the packet in its name.
Consider a rule allowing the f orwarding of packets f rom the local network
to the external interf ace:
ipchains -A forward -i eth1 -s 192.168.1.0/24 -j MASQ
Because this is a general rule, I placed it at the end of the forwardchain using
the -Aoption to av oid blocking the f ilters specif ic f or indiv idual users but
interrelated with this rule.
This permission only allows packets f rom the 192.168.1.x network to be sent
to the eth1interf ace. This, howev er, does not mean that the traf f ic will be
able to enter the interf ace and be f orwarded to the Internet. For the f irewall
to accept user packets, there should be an ACCEPTrule in the inputchain. It
may look as f ollows:
Now, a rule to permit packets to exit the eth1interf ace has to be added to
theoutputchain, and all of y our network's computers will hav e access to the
Internet. The IP address of the f irewall computer has to be specif ied as the
gateway on all client machines.
Frequently, the Internet-side network dev ice is a modem and not a network
adapter. In this case, the masking rule f or theforwardchain will look like the f
ollowing:
ipchains -A forward -i ppp0 -s 192.168.1.0/24 -j MASQ
The traf f ic is f orwarded to the modem interf ace, which is denoted by the
ppp0parameter.
Clients of ten must hav e access to Internet resources ev en though the rev
erse connection is unwanted. When a TCP-connection request to a remote
computer is made, a packet with thesynbit set is sent. Regular packets (such
as responses to connection requests or data transmissions) are not supposed to
hav e this bit. Consequently, prohibiting TCP packets with this f lag set will
make it impossible f or a remote computer to connect to either the f irewall
computer or the network. This can be implements as f ollows:
ipchains -I input 1 -i ppp0 -p tcp --syn -j DENY
This command places the new rule in the inputchain. The rule checks f or
TCP packets with thesynf lag set (as indicated by the--synoption). Any
packets meeting this criterion are deleted.
To mask IP addresses, the corresponding support must be compiled into the
kernel, because the address substitution process takes place on the kernel lev
el.
Sav e the changes ev ery time y ou change the ipchainsconf iguration. Should
y ou hav e to reload the serv er f or some reason, y ou will most likely f orget
to restore the changes.
It is possible to automate the process of sav ing rule changes, but I do not
recommend that y ou rely on this. It will be more reliable to do this manually.
This f ile can also be used to restore chain rules. This is done by executing
the f ollowing command:
ipchain-restore < file
This is a handy f eature. Suppose y ou want to test a new set of rules but do
not want to corrupt the already -conf igured chains. In this case, y ou can sav
e the existing state in some f ile and then experiment all y ou want. If
something goes wrong, y ou can return to the starting point by restoring the
chains f rom the backup f ile.
-I chain number rule — Insert the rule into the specif ied chain under the
specif ied number. For example, in the number equals1, the rule will be the f
irst one in the chain.
-i interface— Specif ies the incoming network interf ace. Av ailable v alues
areINPUT, FORWARD, andPREROUTTNG.
-o interface— Specif ies the outgoing network interf ace. Av ailable v alues
areOUTPUT, FORWARD, andPOSTROUTING.
- j action — The action to apply to the packet, called the target in the
iptablesterminology. The main target options are the f ollowing:
As y ou can see, most of the parameters are the same as those f or the
ipchainsprogram. But there are also important dif f erences. For example, the
-oand -iparameters prov ide an easy way to specif y the source and
destination interf ace of a packet. Because the practical aspects of the conf
iguration processes f or both serv ices are similar, I will not waste book space
on considering the process separately f or iptablesand will only brief ly
consider the rule-creation process.
The conf iguration process f or iptableschains is not dif f erent f rom that f or
ipchains. The chain-f ormation process starts by f lushing all contents of the
chain. Rules are added to the chain starting with prohibiting ev ery thing and
then permitting only those actions and packets that will not harm the serv er.
Potentially dangerous serv ices should only be made av ailable to trusted
users who require them.
Changes to the iptablesconf iguration, as withipchains, must be sav ed
manually to the conf iguration f ile (/etc/sy sconf i/iptables by def ault):
service iptables save
4.12.2. Forwarding
Here,iptable_natis the kernel module that allows the f irewall to work with
NAT.
I personally recommend against logging. Public serv ers hav e their ports
scanned hundreds, if not thousands, of times. To log all of these scannings, y
ou would need a huge hard driv e to store the logs. Unless y ou prov ide
enough space to store the logs, a f ull hard driv e will take down the sy stem.
In this way, repeatedly scanning a prohibited port f or a certain period will
successf ully perpetrate a DoS attack
As y ou can see, creating a f ilter does not dif f er signif icantly f rom the
analogousipchainsprocedure.
To prohibit access f rom a certain interf ace, add the -ioption and specif y
theeth0interf ace as f ollows:
iptables -A INPUT -i eth0 -s 0/0 -d localhost \
-p tcp --dport 21 -j DROP
Suppose y ou want to allow access to the FTP serv er but prohibit access to
the /etc/passwd and /etc/shadow f iles. The latter is achiev ed by prohibiting
packets containing this particular text. A request packet containing ref
erences to these packets will be dropped. The f ollowing commands prohibit
access to these f iles using the FTP and the World Wide Web protocol:
iptables -A INPUT -m string --string "/etc/passwd" \
-s 0/0 -d localhost -p tcp --dport 21 -j DROP
iptables -A INPUT -m string --string "/etc/shadow" \
-s 0/0 -d localhost -p tcp --dport 21 -j DROP
iptables -A INPUT -m string --string "/etc/passwd" \
You also hav e to take into account the inf ormation-protection aspect.
Suppose y ou hav e a serv er that receiv es traf f ic encoded using the
"stunnel" technique, decodes it, and f orwards it to another machine. (The
stunnel — secure tunnel — technique, which creates an encoded channel
between two machines, is considered inSection 5.2.) In this case, the f irewall
will not detect the text to watch f or in the incoming packets. But the
outgoing packets are decoded and contain commands in plaintext. This conf
iguration requires that both incoming and outgoing traf f ic be controlled.
Ev en if stunnel transf ers the decoded traf f ic to another port within the same
computer, all ty pes of packets can be controlled on all interf aces to inspect
them af ter decoding.
In this section, I will consider some problems that y ou may encounter when
using the f irewall. You should hav e a clear idea of the potential problems so
that y ou could neutralize the danger they present.
As already stated, only being extremely caref ul when conf iguring the f
irewall can giv e y ou higher-than-av erage conf idence in that y our sy stem
is secure. Examine some of the ty pical blunders committed when conf
iguring the f irewall; this will help y ou av oid making similar mistakes.
As y ou should remember, the input and the output chains hav e three rules
apiece. Suppose y ou no longer require FTP access and disable it. Along with
disabling the FTP serv er, do not f orget to delete f rom the rule chains the
rules that allow such access.
Once, an administrator I knew did not delete the rules af ter disabling the serv
ice. Some time later, the FTP serv ice was enabled again, but the IP address,
to which the original permission was issued, was now used by another
employ ee. In this case, the person that unexpectedly obtained rights was a
loy al company employ ee and did not intend to misuse them, but y ou do
understand the implications, don't y ou?
The f irewall-conf iguring task is dif f icult when IP addresses are assigned
dy namically and change constantly. If addresses in y our network are
assigned using the Dy namic Host Conf iguration Protocol (DHCP), y ou
should see to it that computers that require special access and rules were
assigned a permanent address (f or example, that of the main gateway ). This
will prev ent the wrong person f rom obtaining a priv ileged IP address and
the real owner f rom losing it by accident.
Imagine what will happen if , in the example considered in Section 4.11.2, IP
address 192.168.8.10 is through a f luke assigned to another computer. It will
create problems because the user who is supposed to hav e it does not and the
new user may put it to the wrong use.
Be caref ul when creating rules. Some serv ices (f or example, FTP) may
require more than one port to f unction properly. Unless y ou open or close
all the ports, y ou will not achiev e the desired result.
Be especially caref ul when conf iguring the f irewall using a graphical shell.
When ev ery thing is prohibited, XWindows may hang if it loses the network
connection with the Linux kernel.
You should also pay close attention to what y ou are doing when conf iguring
the f irewall using a Secure SHell (SSH) protocol remote connection. One
wrong mov e here may break the connection, and the SSH client will
disconnect. Then y ou will hav e to go to the f irewall serv er and continue
conf iguring it in situ.
Test all connections af ter each change to the f irewall conf iguration. If y ou
make a mistake, it will be dif f icult to trace it af ter sev eral modif ications.
To debug problem rule chains, I sav e the conf iguration to a temporary f ile
and then print it. It is much easier to see the whole picture on paper than on
the monitor. Make sure y ou specif y the correct source and destination
parameters (the address and port). Quite of ten, administrators are not certain
about what parameters to specif y and act by the seat of their pants.
Go ov er each chain in y our mind, analy zing which packets are let through
and which are not. The inv estigation is best started with theinputchain
(where packets enter the sy stem). Next, inspect theforwardchain and, f
inally, theoutputchain. In this way, the complete packet cy cle has to be
traced. Remember that af ter the f irst rule that meets the packet's criteria, no f
urther checks are conducted.
When inspecting rules dealing with TCP, remember that this protocol
establishes a connection, meaning that packets hav e to trav el both way s.
UDP does not establish a connection and packets can be passed only one way
: input or output. But there are exceptions when some programs require
bidirectional exchange ov er UDP.
If some program does not work, make sure that there are the necessary rules f
or all necessary ports: Some protocols require access to two or more network
ports. Next, check that the permission rule precedes the prohibition rule.
Nev er open access to the specif ic port on all computers. For example,
simply adding a rule permitting incoming packets on port 80 will open this
port on all of the network's computers. But f ar f rom all computers require
access to this port. Thus, when creating a rule, specif y not only the port but
also the specif ic IP address, on which it applies.
And don't f orget to make backup copies of the conf iguration (using the
ipchain-savecommand). These will come in handy in case of problems with
test conf igurations.
A f irewall cannot prov ide absolute security because its operation algorithm,
like ev ery thing in lif e, is not perf ect. It is based on certain rules, according
to which the f irewall inspects the traf f ic passing through the network interf
ace and makes decisions as to whether or not to let it through. But, short of
complete prohibition, no f ilter can prov ide 100% security because there is
no rule that cannot be circumv ented.
A f irewall is a complex sof tware sy stem that requires signif icant technical
resources to analy ze all transiting traf f ic. Most of these resources are spent
analy zingsynpackets, that is, connection request packets. The f irewall has to
check the parameters of eachsynpacket against all set rules.
The problem becomes worse if the f irewall is conf igured to issue error
messages. This increases the processor workload because it has to create and
send packets to nonexisting addresses or addresses that do not belong to the
hacker.
If a client sends data that does not f it into one packet, the packet is broken
into sev eral parts. This process is called packet f ragmentation. Most f
irewalls inspect only the f irst block in a session and consider the rest of them
v alid. This is logical, because if the f irst block is v alid, why waste the serv
er's resources on inspecting the rest of them?
Packets can be f ragmented in such a way that the f irewall will let them
through. This ty pe of attack can be def ended against only if the f irewall
automatically assembles packets and inspects them assembled. Most f
irewalls cannot do this.
Firewalls sometimes experience attacks that are successf ul. If hackers take
ov er the f irewall, they will obtain complete access to the network it is
supposed to protect. In this case, y ou can only be sav ed f rom complete def
eat by an indiv idual f irewall on each of the network's computers. Ev en
though the indiv idual workstation f irewall security policy may not be as
stringent, it may be just enough to prev ent the hackers' f urther inv asion into
the network.
Any ty pe of f irewall can come under attack. Both Linux f irewalls and
routers with f irewall f unctions can hav e bugs.
The main task perf ormed by a f irewall is to prohibit access to the resources,
to which access is restricted. But some resources must be av ailable to ev ery
one. For example, a f irewall cannot protect against a break-in taking adv
antage of bugs in Web scripts on a Web serv er that is supposed to hav e f ree
access f or Internet users.
Maximum security comes at the price of sacrif icing some conv eniences.
Thus, as I already stated, all outside attempts to connect to the sy stem are
best prohibited. Only a network's client can initiate a connection, not a
remote computer. This will make it impossible f or hackers to connect to the
sy stem but may also cause problems f or the legitimate network users when,
f or example, they try to connect to an FTP serv er in the activ e mode. As y
ou already know, this serv ice uses two ports:ftpandftp-data (ftpd). It will be
no problem f or the user to connect to the serv er'sftpport. To serv e a f ile,
howev er, the FTP serv er itself has to initiate a connection with the client,
which will not be let through by the f irewall. This problem has been solv ed f
or the FTP serv ice by adding the passiv e operating mode; the issue remains
open f or other serv ices — chats, f or example.
But this is not the extent of their laziness. So as not to come to work af ter
hours in case of emergency, they connect to the serv er's console f rom home.
And this is a serious breach of security that may place the network they are
supposed to protect in a serious danger. It's all right if the program used to
manage the remote serv ers encodes the transmitted data in some way, but
what if it's just y our regular Telnet client? Hackers can intercept the
authentication inf ormation using a snif f ing utility and obtain the same
access priv ileges to the serv er as the administrator.
4.13.3. Safe Internet
The Internet will not be saf e until it is possible to determine the source of
each packet that comes f rom there. The way things are now, any f ield of the
IP packet can be f aked to the ef f ect that its authenticity can nev er be
established.
Once that y ou can nev er be sure that it is not a wolf in sheep's clothing that
is knocking at y our serv er's door, y ou should take good care to conceal,
which permissions and to whom they are giv en on y our serv er. The less inf
ormation y ou make av ailable to hackers, the more secure y our serv er will
be. You should also ruthlessly suppress any recognizance mov es, f or
example, port scanning, or tracing, etc.
This f eature can be used to determine the route a packet trav els to its
destination. It works as f ollows: In 99% of cases, packets trav el to the
destination ov er the same route. Setting the packet's TTL v alue to 1 will
make the f irst router it reaches issue an error message, which contains the
router's address. The next packet's TTL v alue is set to 2. The TTL error
message f or this packet will be issued by the second router it reaches. Thus,
sending a series of packets, sequentially incrementing the TTL v alue of each
packet by 1, all routers that the packets pass to reach the specif ied
destination can be established.
A f irewall should drop any packets whose TTL v alue equals 1. This will
protect the network but will also rev eal that it is protected by a f irewall. If a
regular packet (with a real TTL v alue) reaches the addressee but the
traceroutecommand to the same destination produces an error message, this
means there is a f irewall somewhere in the route.
To continue tracing bey ond the f irewall, the command has to be issued with
the TTL v alue of 19. The f irst 17 requests will produce responses, the 18th
will be lost, and the 19th will be let into the network The reason packet 19 is
let in is because when it reaches the f irewall, its TTL v alue equals 2. But the
f irst router in the local network will drop this packet.
In real lif e, howev er, ICMP packets are prohibited, and this method seldom
produces results.
But simply replacing a prohibited IP address with the good one will not let
the hacker through. The serv er simply will not respond to packets with the f
aked IP address. Why ? Take a look at Fig. 4.9: The answer to the hacker's
query goes to the real owner of the permitted address.
For the serv er to respond to the hacker's request, special inf ormation by
which the serv er can determine the real address of the hacker has to be
included in the IP packet.
A modern f irewall, including those supplied with Linux, easily detects the
swap and blocks f ake IP address packets.
When a connection attempt to the serv er is made, the f iles are checked as f
ollows:
1. If the requesting computer is in neither f ile, access is permitted by def ault.
The conv enience of using these f iles is that serv ices, to which access has to
be limited, can be specif ied in them f or specif ic hosts. This is done by
making an entry in the f ollowing f ormat in the f ile:
service: host
The serviceparameter specif ies the name of the serv ice, to which access has
to be restricted. It can also list sev eral serv ices delimited by commas. The
host parameter lists addresses delimited by commas (allowed f or the
/etc/hosts.allow f ile and prohibited f or the /etc/hosts.deny f ile). Instead of
addresses, the ALLkey word can be specif ied, which allows any address or
serv ice.
Consider an example conf iguring these f iles. For starters, close access to all
serv ices by all computers. This is done by adding this entry to the
/etc/hosts.deny f ile:ALL: ALL.The resulting f ile will look as f ollows: #
# hosts.deny This file describes the names of the hosts # not allowed to use
the local INET # services, as decided by the
# /usr/sbin/tcpd server.
#
# The portmap line is redundant, but it is left to remind # you that the new
secure portmap uses hosts.deny and # hosts.allow. In particular, you should
know that NFS # uses portmap!
Only computers with the addresses 192.168.1.2 and 192.168.1.3 can hav e
access to the FTP serv ice. The corresponding f ile f ollows:
#
# hosts.allow This file describes the names of the hosts # allowed to use the
local INET services, # as decided by the /usr/sbin/tcpd server. #
ALL: 192.168.1.1
ftpd: 192.168.1.2, 192.168.1.3
If y ou need to allow the entire network to access a serv ice, this can be done
as f ollows:
ftpd: 192.168.1.
This entry allows all computers in the 192.168.1. xnetwork to access the
ftpdserv ice. The xcharacter in the last octet means any number.
You may ask why this can't be done using the f irewall rule chains. This is
because should y ou delete or add a wrong rule, the serv er operation may be
disrupted or its security may be lowered. This is why I do not recommend
creating temporary f irewall rules.
As y ou can see, quite a bit of inf ormation can be obtained with just one
command; thus, port 111 must be closed.
To make controlling access to ports easier, div ide the open resources into the
f ollowing two categories:
Those f or public access, including v isitors f rom the Internet.
Those f or use only within the network. For example, such serv ices as FTP
and Telnet are inherently dangerous because they can be used to upload f iles
on the serv er and to execute commands. If these serv ices are not necessary f
or Internet v isitors, external connections to them should be explicitly
prohibited.
Programs started by the root run with root rights. Should there be a v
ulnerability in such a program, it can be used by hackers to obtain root rights.
Entering some command erroneously can impair the entire sy stem. And to
make a mistake when entering a command is not that dif f icult, because
Linux prov ides powerf ul regular expression capabilities.
The sy stem will respond with a message that y ou are denied permission to v
iew the f ile. Now execute the same command usingsudo:
sudo cat /etc/shadow
The sy stem will respond with the message that y our account is not the
sudoers (/etc/sudoers) f ile. This is the f ile, in which users who are permitted
to use the sudo command are listed. An example of this f ile's contents is
shown in Listing 4.2.
# sudoers file
# This file MUST be edited with the 'visudo' command as root. # See the
sudoers man page for the details on how to # write a sudoers file. # Host alias
specification
# Samples
# %users ALL = /sbin/mount /cdrom,/sbin/umount /cdrom # %users localhost
= /sbin/shutdown -h now
There is only one entry that is not commented out in this f ile. This is the f
ollowing:
root ALL=(ALL) ALL
In the f irst f ield, the user (or group) allowed to execute the specif ied
command is designated. I recommend listing specif ic users here. A hacker
can become a member of a group but cannot obtain access to running high-
priv ileged commands as hav ing no rights f or this.
In the second f ield, the name of the machine, on which the permitted user
can execute commands as the superuser is specif ied.
In the third f ield, the commands that the permitted user can execute as the
superuser are listed af ter the equals sign.
Now the user robert can use the sudocommand to perf orm any administrator
tasks. You can v erif y this by executing the catcommand v ia sudoagain:sudo
cat /etc/shadow.
This time the command should execute without any complaints f rom the sy
stem. You will hav e to enter the administrator's password to use the sudo f
eature.
Giv ing permission to execute all commands contradicts the secure sy stem
principles. Thus, y ou hav e to place certain restrictions.
Note that the absolute paths to the catprogram and the shadow f ile are giv en;
otherwise, executing the command will produce an error message. For
example, y ou want to giv e some user extended rights and allow him or her
not only to v iew the password f ile but also to mount the CD-ROM. For this,
edit the entry by adding permission to execute themountcommand: robert
ALL=/bin/cat /etc/shadow, /bin/mount
Note that this only giv es read permission f or the /etc/shadow f ile by
explicitly specif y ing thecatutility to access it with. It makes sense, because it
is edited using thepasswdcommand. You could simply giv e permission f or
executing thecatcommand as f ollows:
robert ALL=/bin/cat, /bin/mount
But in this case a hacker can v iew any f iles in the sy stem as root, including
those that a regular user cannot see.
No parameters were specif ied f or the mountcommand. In this way, the user
can specif y the parameters himself or herself . Specif y ing the CD-ROM as
an argument explicitly lets the user mount only this dev ice:
robert ALL=/bin/cat /etc/shadow, /bin/mount /dev/cdrom
In the examples considered, the computer parameter was specif ied as ALL,
which means any machine. Nev er use this v alue in a real sy stem. Alway s
specif y the particular computer, to which the entry applies. Most of ten, this
will be a local serv er.
The sudoutility can be used to execute commands not only as the root but
also as any other user. This is done by using the-uoption with it. For example,
the f ollowing command attempts to v iew the password f ile as the f lenov
user:
If the user is not specif ied, the sudoprogram requests the root's password.
Giv ing this password to the user robert is not smart f or security, because this
kills the whole idea of building such a complex security sy stem. Knowing
the root's password, the user can log into the sy stem as the administrator and
do whatev er his or her heart desires with it.
Nev er rev eal the administrator password to those who are not supposed to
know it. Use passwords f or other user accounts that hav e the right to work
with the necessary f iles and programs. In this case, the name of the user that
was assigned by the administrator to execute the command will hav e to be
specif ied.
Another way to av oid hav ing to rev eal the administrator password is to
allow the user to execute commands without authentication. This is done by
adding the key word NOPASSWDf ollowed by a colon between the equals
sign and the list of command as f ollows:
robert ALL=NOPASSWD:/bin/cat /etc/shadow, /bin/mount /dev/cdrom
Now when executing the sudoprogram the password will not be requested.
This is dangerous if y ou do not list the necessary options but only giv e the
ALLkey word.
robert ALL=NOPASSWD:ALL
If hackers obtain access to the user account robert, the sudo utility will giv e
them the ability to execute any commands in the sy stem. If y ou list only the
permitted options, the degree of harm that can be inf licted upon the sy stem
if it is compromised decreases to the extent of the dangerousness of the
commands the robert user is allowed to execute and the protection of this
account (i.e., how long and strong the password is, how diligent the owner is,
etc.)
The sudoutility can be used to allow access f or editing f iles. Nev er use this
capability. Launching a text editor to edit ev en the most innocent f ile will
giv e hackers too many opportunities. For example:
To execute sy stem commands. Because the editor runs with root rights, the
commands will also be executed with root rights, meaning that hackers will
hav e the entire sy stem at their disposal.
To open any other f ile taking adv antage of the root priv ileges.
I nev er delegate the ability to edit conf iguration f iles using a text editor. If
this cannot be helped, I nev er giv e root rights f or this. The conf iguration f
iles to be edited are assigned to another owner and the user delegated to edit
it will launch thesudoprogram as this new user, thus av oiding running the
editor with root rights.
The f ollowing commands are potentially dangerous and should not be
executed with root rights by other users:
The mountcommand — List only specif ic dev ices in the conf iguration f ile
and allow only trusted employ ees to execute this command. If hackers are
able to mount a dev ice with programs that hav e SUID bits set or Trojan
horse programs, they will be able to take ov er the entire sy stem.
Another thing to remember when working with the sudoprogram is that its
SUID bit is set, meaning that it executes with the rights of the owner, that is,
with root rights. The 1.5.5 through 1.6.5.p2 v ersions of thesudoprogram hav
e a memory -allocation bug. This bug can be exploited by hackers to
perpetrate a stack ov erf low attack. You can check y our v ersion by
executing thesudocommand with the -V option. If executed by the
administrator, it display s detailed inf ormation about the program as shown
in Listing 4.3.
Subject line for mail messages: *** SECURITY information for %h ***
LANGUAGE
LANG
LC_*
The display ed is just a f ragment of the f ile, showing the main inf ormation.
The f irst entry display s the program v ersion, 1.6.5.p2 in this case. The most
interesting items in this listing are the f ollowing three lines:
Authentication timestamp timeout: 5 minutes
Password prompt timeout: 5 minutes
Number of tries to enter a password: 3
The f irst line sets the time f or how long the password is sav ed in the cache.
In this case, it is 5 minutes. If the user executes the sudocommand within this
time again, the authentication procedure will not hav e to be gone through.
The f ollowing line specif ies the time to wait f or the user to enter the
password. The last line specif ies the number of attempts the user can make to
enter the password. If the correct password is not entered within this time f
rom the specif ied number of tries, the program terminates.
Chapter 5: Administration
Overview
In this chapter, the questions Linux administrators encounter daily are
considered. You will become acquainted with numerous Linux commands,
learn how to use them, and discov er many usef ul f acts about the sy stem.
The inf ormation will be illustrated by v arious examples and interesting f
acts.
But the chapter is not limited to a simple consideration of commands; this
would turn the book into a simple rewrite of Linux manuals. To av oid this, I
prov ide ready -made solutions to administrator tasks that may be of use to y
ou in y our ev ery day work. I hope that the inf ormation in this chapter will
prov ide y ou with answers to many questions and help y ou solv e at least
some of the problems y ou encounter in y our work.
A war is being waged between those try ing to break into computers and
those protecting against break-ins on the v ast expanses of the Internet. The
winner in this war will be the one who does his or her homework and reacts f
aster to the opponent's mov es.
5.1.1. netconfig
5.1.2. ping
The f irst entry display s the IP address of the computer being probed. If y ou
specif y the host name when issuing thepingcommand, y ou can f ind its IP
address in this way. At the end of the line, the size of the packets to be sent is
specif ied in by tes.
icmp_seq — The packet number. For each successiv e packet, this v alue is
incremented by one. If some number is missing, it means that either the ping
packet or the reply to it was lost in the Internet. This may be caused by
equipment errors, an unreliable cable connection, or one of the routers
between the two machines sending the packet the wrong way.
ttl — The time-to-liv e v alue. This is a number that specif ies how many
routers the packet can pass on the way to the destination bef ore it is
considered lost. The def aultttlv alue on most sy stems is 64, but it can be
changed. The v alue is decremented by one by each router that handles the
packet. When it becomes 0, the packet is considered lost and destroy ed.
Thus, this v alue can be used to approximately determine the number of
routers on the way to the packet's destination.
time — The round-trip time. This parameter prov ides inf ormation about the
speed of the link. The stability of the link can also be ev aluated based on
how much this v alue v aries f or each packet. Note that the round-trip time f
or the f irst packet is almost alway s longer than that of the successiv e
packets. The rest of the packets should hav e about the same round-trip time.
-sn — Specif y the packet size. For example, a 1000-by te packet is sent by
this command:ping -s 1000 195.10.14.18. Some older operating sy stem v
ersions contained bugs and would hang when a too-large packet was receiv
ed. These bugs hav e been f ixed in modern sy stems.
These are the most of ten used switches. Additional inf ormation on the ping
command can be obtained in the pingmanpage by executing the manping
command.
Not all serv ers can answer echo requests. Some serv ers may hav e their f
irewall conf igured not to let ICMP traf f ic through. Note In this case, a ping
request will produce no response, although the serv er is f unctioning
normally and can accept other ty pes of packets without any problems.
5.1.3. netstat
The netstatcommand display s all current connections to the serv er. The
result of its execution looks similar to the f ollowing:
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address tcp 0 0 FlencvM:ftp Foreign Address
State 192.168.77.10:3962 ESTABLISHED
Recv-Q — The number of by tes the user program has not copied.
Send-Q— The number of by tes the remote computer did not receiv e.
If y ou suspect that y our sy stem has been penetrated, y ou can use this
command to determine, which of the serv ices were used to carry out the
penetration and which resources the hackers may be using. For example, if
the hackers entered through the FTP serv ice, they are most likely working
with f iles and may be uploading their f iles to expand their takeov er of the
sy stem, modif y ing or deleting sy stem f iles, or downloading f iles
containing inf ormation of interest to them.
5.1.4. lsof
More detailed inf ormation about this command can be f ound in itsmanpage.
5.1.5. Telnet
The might of Linux and its text console consists of being able to execute
commands not only directly at the terminal but also remotely. All y ou hav e
to do f or this is to connect to the Telnet serv er port with help of a Telnet
client.
There are f ew utilities in Windows that can operate in the command line;
theref ore, this sy stem requires, and widely uses, graphical mode. The
command line in Windows of f ers rather limited capabilities. To solv e this
problem, a method of terminal access was created that makes it possible to
see the contents of the serv er's display on the client's screen and work with
them as if working directly at the serv er. But this method is traf f ic-intensiv
e and is inconv enient ov er slow communications channels.
Compared with the graphical mode of any operating sy stem, the Linux
command line v irtually does not use any traf f ic and can work reasonably
well ev en ov er the slowest channels, such as cellular phone General Packet
Radio Serv ices (GPRS) or home modem connections, which hav e rather
slow speeds.
As y ou by now understand, the Telnet sof tware consists of the serv er and
the client parts. When a Telnet serv er is started, port 23 is opened, to which a
client computer can connect and execute any commands allowed by the
Telnet serv er.
But that's not all: a Telnet client can be used to connect to other serv ers. For
example, a connection can be made to port 25 and send email messages f rom
the command line by executing Simple Mail Transf er Protocol (SMTP) serv
er commands.
In this case, y ou are connecting to the FTP serv er on the local computer, as
is specif ied by thelocalhostparameter. To connect to the FTP serv er on a
remote computer, y ou hav e to specif y its address in place of thelocalhost
parameter. The second parameter is the port that the serv er uses. The FTP
serv er receiv es control commands on port 21, so this port was specif ied. I
recommend using a Telnet client only f or conf iguring and debugging serv
ices but not f or controlling the sy stem. Thus, disable Telnet on all of the
network's machines. The utility is not secure because it sends plaintext data,
and all attempts to make Telnet secure hav e f ailed. One way to secure
Telnet is to use it through an Open Secure Sockets Lay er (OpenSSL) encry
pted channel. But there is another popular method of controlling a serv er:
using the Open Secure SHell (OpenSSH) protocol, which is considered
inSection 5.3.
Thus, y ou need a Telnet client, but the Telnet serv er should be remov ed f
rom the sy stem.
Do y ou notice any thing dangerous in the inf ormation display ed? My self , I
see detailed inf ormation about the distributiv e and kernel v ersions. All this
inf ormation becomes av ailable to any user ev en bef ore he or she registers
in the sy stem. If hackers see open port 23, they will not hav e to take pains of
learning y our operating sy stem and kernel v ersion; all they will hav e to do
is to connect to Telnet to obtain this inf ormation.
Telnet being too talkativ e is the huge security hole that has to be plugged as
soon as possible. The prompt messages display ed upon connecting are stored
in the /etc/issue and /etc/issue.net f iles. You can change the prompt messages
as f ollows:
echo Text > /etc/issue
echo Text > /etc/issue.net
Here Textis the text of the new prompt message. You can specif y a wrong
kernel v ersion to conf use hackers:
echo Debian Linux > /etc/issue
echo Kernel 2.4.4 on an i686 > /etc/issue.net
So, whatev er distribution and kernel v ersion y ou may hav e installed, any
hacker try ing to connect to y our computer ov er Telnet will think that y ou
are using the 2.4.4 old Debian core.
The contents of the f iles, howev er, will be restored af ter the next reboot and
Telnet will again show the distribution and core inf ormation in the welcome
message. You can av oid this by setting the f iles'-iattribute, which prev ents f
ile modif ications:
chattr +i /etc/issue
chattr +i /etc/issue.net
5.1.6. r Commands
There are so-called rcommands in Linux:rlogin, rsh, rcp, rsync, and rdist. I
will not consider them because they are obsolete and present a great security
danger. These commands allow remote connection to the sy stem and send
their data in plaintext. Although y ou may need a Telnet client to test serv
ices, y ou hav e no need f or these commands. I only mentioned them so that
y ou will delete them f rom the sy stem to av oid the temptation of using them
y ourself and to prev ent hackers f rom exploiting them.
5.2. Encryption
In the early day s of the Internet and f irst network protocols, nobody thought
about the security aspects. This issue became important only when actual
break-ins started happening. The two biggest ov ersights in the dev elopment
of these technologies were allowing data to be sent in plaintext on the
network and allowing network equipment to listen to all network traf f ic.
All the network cards on the bus can see all packets placed onto it. If y ou
really want to read other people's network traf f ic, y ou can f ind a snif f er
program and monitor all data that pass through y our network card ev en if
they are not intended f or y ou. Because most protocols process packets in
plaintext, any hacker can monitor the network and discov er conf idential inf
ormation trav eling ov er it, including access passwords.
The star topology ( Fig. 5.3) inv olv es computers connected to one central
dev ice, a hub or a switch. The computers are connected using twisted pair
wire. This arrangement is more reliable and supports 100-MB/sec bandwidth.
There also are switches that can handle packets on the IP address (logical
address) lev el, the way it is done by routers. In this case, packets are f
orwarded based on logical and not phy sical addresses and a switch can
connect entire networks.
At the remote computer, the same encry ption program is started at a certain
port. It receiv es the encry pted data, decodes them, and f orwards them in
plaintext to the FTP serv er port.
Fig. 5.4 shows the data encry ption process. Thus, all packets are sent v ia a
middleman that encodes them. Currently, the most widely -used encry ption
protocol is the Secure Sockets Lay er (SSL) protocol. It has earned a
reputation as a reliable data-exchange tool and has been used to protect
Internet transactions. For example, a secure encry pted connection is used
when a buy ing transaction is carried out through an Internet store to protect
the credit card inf ormation. When the browser connects to the serv er, the f
ormer automatically launches the encry ption program on the client computer,
v ia which the serv er sends and receiv es encry pted data.
Thus, encry ption does not change TCP/IP; data are simply encry pted and
decry pted on both the serv er's and the client's sides. This method is conv
enient because it can be used to encry pt data sent using any protocol. Should
the encry ption program hav e to be modif ied, f or example, to f ix a bug or
to use a longer key, the protocol will not hav e to be modif ied.
Consider an example with the Web serv ice, which works on port 80. The
encry ption program can be started on the serv er on port 1080, decry pting
all data that passes through the serv er and passing them to port 80. If y ou
only want to allow access to the Web ov er the SSL protocol, port 80 can be
blocked by a f irewall (considered in Chapter 4) and allow connections only f
rom the encry ption serv er.
Addresses of sites protected with special key s are pref ixed by https://. The
dif f erence f rom the regular sites is the "s" letter, which means that the
connection is secure. Moreov er, when connecting using a browser with SSL
enabled, the secure connection is indicated by an icon in the status panel in
the lower right part of the browser window. In the popular Internet Explorer
browser, this is an icon of a padlock (Fig. 5.5).
But ev en in Internet Explorer, this icon does not alway s appear when a
secure connection is established. The ty pe of the connection can be
determined more precisely by examining the page's properties. Most
browsers hav e a command to v iew the properties of the loaded page, among
which is the encry ption used. In Internet Explorer, page properties can be v
iewed by executing the File/Properties menu sequence. This will open a
dialog window similar to the one shown in Fig. 5.6. The inf ormation about
the connection is shown in the Connection f ield. In this case, it shows that
the 128-bit encoding SSL 3.0 RC4 protocol is being used.
Figure 5.6: An Internet page's
properties
5.2.1. stunnel
The program used most of ten in Linux f or encry pting and decry pting
network traf f ic isstunnel. The program itself only organizes the channel and
serv es as a middleman. The encry ption is perf ormed by the OpenSSL
packet, which is included in most Linux distributions. If y ou don't already
hav e it installed, y ou can do so by installing the corresponding RPM packet
f rom the installation disc. More detailed inf ormation about OpenSSL, as
well as the latest updates, can be f ound on the www.openssl.org site.
The OpenSSL operation principle is based on using two key s: public and
priv ate. The public key can only be used to encry pt data; the priv ate key is
required to decry pt it.
OpenSSL and the stunnelprogram hav e lots of parameters, and I will not
consider all of them. What I will do is to consider a real-lif e example and
teach y ou the most of ten used arguments.
Start the stunnelprogram on the serv er to decry pt the incoming traf f ic and f
orward it to some port, f or example, port 25 (used by the sendmail SMTP
serv er). This is done by executing the f ollowing command:
stunnel -p /usr/share/ssl/cert.pem -d 9002 -r 25
In this case, the program was started with the f ollowing three parameters:
-p — Af ter this key, the def ault SSL authorization certif icate is specif ied. It
is created when the operating sy stem or the stunnelprogram was installed
and is stored in the /usr/share/ssl/cert/pem f ile.
-d — This option specif ies that the tunnel is to work as a daemon. The
switch is f ollowed by an optional IP address and the port, on which to expect
the connection. If the address is not specif ied, all interf aces of the local
computer will be monitored. The port was specif ied as port 9002. All data
coming to it are considered encry pted and will be decry pted f or f orwarding
to another port of the local computer.
Things are much easier with the client. It is launched by the f ollowing
command:
stunnel -c -d 1000 -r 192.168.77.1:9002
The remaining switches are the same as f or the serv er. The -dswitch
indicates the port, on which the connection is expected, 1000 in this case; the-
rswitch is f ollowed by the computer and port, to which the encry pted data
are to be sent.
The client program has to be conf igured to send mail to the port, on which
thestunnelclient is running (port 1000 in this case). The latter will encry pt
the data and f orward them to port 9002 of the 192.168.77.1 computer. The
data on the destination computer are receiv ed by thestunnelserv er, which
decry pts and then f orwards them to the serv er's port 25.
2 — A certif icate must be used at this lev el. If there is no certif icate or if it
is inv alid, a connection cannot be established.
An SSL serv er can decry pt traf f ic and f orward it to the port of the receiv
ing program of not just the local computer but also another remote computer.
Thus, the SSL serv er and the serv er of the traf f ic receiv er can be located
on two dif f erent computers. It is desirable that, af ter decry pting data, the
serv er hide the source client's IP address. This can be done by specif y ing
the-Toption.
When the OpenSSL package is installed, certif icates and key pairs to be used
f or encry ption are created on the disk in the /usr/share/ssl/ directory.
The protocol to be used can be directly specif ied using the -noption. The f
ollowing protocols are currently supported: POP3, SMTP, and network news
transf er protocol (NNTP).
For most protocols, there are port numbers that hav e become standard. There
are ev en names of secure protocols, which are usually obtained by adding an
"s" letter to the name of the main protocol. This letter signif ies the secure
SSL connection. The relev ant inf ormation is shown in Table 5.1.
Table 5.1: Protocols and the corresponding ports Protocol SSL version
TCP port number
Note that two protected channels are required f or FTP. One is used f or the
control connection, and the other to transmit data. I will return to this in
Chapter 10, where this protocol is considered.
Some serv ers are used f or storing archiv e data — access to which, nev
ertheless, has to be restricted to authorized people only. The best way to
protect this inf ormation is to encry pt the f iles. This can be done using the
OpenSSL packet.
Not only backup or archiv e f iles may hav e to be encry pted but also conf
idential inf ormation f iles that are sent ov er insecure communications
channels, f or example, through email or a public FTP serv er.
The-inparameter specif ies the input f ile to be encry pted; the-out parameter
specif ies the f ile, into which the encry ption results are stored.
A f ile is decoded by the same command, but with the -doption added. The-
inargument specif ies the f ile to be decoded, and the-outargument specif ies
the f ile, into which the results of the decoding are to be placed:
/usr/bin/openssl algorithm -d -in file2 -out filel
Try using the OpenSSL program by encoding the /etc/passwd f ile. The f ile
is encoded with the DES algorithm, and the results are sav ed in the
/home/passwd f ile. This is done by executing the f ollowing command:
/usr/bin/openssl des -in /etc/passwd -out /home/passwd
The program will ask y ou to enter a password and then conf irm it to prev
ent potential entry errors.
Now, v erif y that the contents of the encoded f ile are unreadable by
executing thecat/home/passwdcommand.
Decode the encoded f ile by executing the f ollowing command:
/usr/bin/openssl des -d -in /home/passwd -out /etc/passwd
Encoded in this simple way, a copy of the password f ile can be saf ely
stored.
Hackers can use tunneling to achiev e their own ends. For example, recently I
connected to the Internet using the Asy mmetric Digital Subscriber Line
(ADSL). The monthly f ee cov ers only 400 MB of the traf f ic. But f or me
400 MB is a pittance. It is barely enough f or a week's work in the economy
mode because of my numerous contacts. Sometimes I download up to 20 MB
a day f rom my mailbox. The f ee f or megaby tes ov er the 400 MB monthly
limit is rather expensiv e.
The hacker uses the stunnelprogram to connect to the f ree Web serv er
located on the prov ider's machine. From the Web serv er the traf f ic is f
orwarded to some proxy serv er on the Internet or directly to Web sites. This
does not cost any money, because the two-way communication with the Web
serv er is f ree.
In this way, more than 400 MB can be downloaded, all f or f ree. There
should be, howev er, at least some sort of a Web page placed on the Web serv
er; otherwise, the administrator will notice right away that there is lots of traf
f ic going to the empty Web page and will be able to f igure out the tunnel.
Another nonstandard use of tunneling is expanding network access
capabilities. For example, some local network may prohibit certain Internet
access protocol. In my lif e, I hav e worked f or companies that allowed
access to Web sites only ov er HTTP. All other protocols were prohibited.
The management justif ied this policy by arguing that users should not be
able to send f iles to the Internet.
Is it possible to circumv ent this limitation? Again, place a tunnel on the Web
serv er and y ou can use any other protocol by hiding all traf f ic within
HTTP. The tunnel then f orwards the traf f ic to the necessary ports under the
necessary protocol.
Using this utility, y ou can administer y our network serv ers remotely f rom
one work-place without hav ing to equip each of them with a monitor and to
run to each serv er ev ery time y ou hav e to implement a minor conf
iguration change. This is how I administer my network: f rom one monitor
that I can connect to any sy stem block if the problem cannot be solv ed ov er
the network.
The adv antage of SSH is that this protocol allows commands to be executed
remotely but requires authentication and encry pts the communications
channel. An important f eature is that ev en user authentication passwords are
transmitted encry pted.
Presently, there are two v ersions of the SSH protocol, numbered 1 and 2.
The second v ersion employ s a stronger encoding algorithm and f ixes some
of the bugs f ound in the f irst v ersion. At present, Linux supports both v
ersions.
In Linux, the SSH protocol is handled by the OpenSSH program. The nativ e
platf orm of this program is another UNIX-like operating sy stem: OpenBSD,
f rom which it has been cloned to all other UNIX platf orms, including Linux.
But ev en now the OpenBSD name can be encountered sometimes in conf
iguration f iles.
The SSH protocol requires a serv er and a client f or operation. The serv er
waits f or connection and executes user commands. The client is used to
connect to the serv er and to send it commands to execute. Thus, both parts of
the protocol hav e to be properly conf igured f or normal operation.
The SSH serv er conf iguration f ile: sshd_conf ig The SSH client conf
iguration f ile: ssh_conf ig The key f iles f or dif f erent algorithms:
ssh_host_dsa_key ssh_host_dsa_key.pub
ssh_host_rsa_key.pub
What is the reason f or so many key f iles? It is that SSH uses dif f erent
encoding algorithms, including the two most popular and secure ones: the
Digital Signature Algorithm (DSA) and RSA. (The latter abbrev iation is
composed of the f irst letters of the last names of its creators: R.L. Riv est, A.
Shamir, and L.M. Adleman.) The ssh_host_dsa_key and
ssh_host_dsa_key.pub f iles are used by DSA, and the ssh_host rsa_key and
ssh_host_rsa_key.pub f iles are used by the RSA algorithm. The remaining
two key f iles — ssh_host_key and ssh_host_key.pub — store the key s to the
f irst SSH v ersion. Each algorithm requires two f iles: The f ile with the PUB
extension stores the public key, and the f ile without this extension stores the
priv ate key.
Data to be sent to the serv er are encry pted using the public key. They can
only be decry pted with the help of the priv ate key. The priv ate key cannot
be picked by any known algorithms within a reasonable length of time. It can,
howev er, be stolen; thus, y ou should take all necessary measures to prev ent
this f rom happening.
#Port 22
#Protocol 2,1
#ListenAddress 0.0.0.0 #ListenAddress ::
# Logging
#obsoletes QuietMode and FascistLogging #SyslogFacility AUTH
#SyslogFacility AUTHPRIV #LogLevel INFO
# Authentication:
#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys
#MaxStartups 10
# No default banner path #Banner /some/path
#VerifyReverseMapping no
Port — Shows the port, to which to connect on the remote machine. By def
ault, this is port 22. Some administrators like to change this v alue and to mov
e the serv er to another port. This action is justif ied to an extent. For
example, if y ou do not hav e a Web serv er, the port normally used by it can
be giv en to SSH. Hackers will think that this is a Web serv er and will not try
to break into it.
Protocol — Giv es the protocol v ersions supported. Note that f irst v ersion 2
is specif ied, and then v ersion 1. This means that the serv er will f irst try to
connect ov er the v ersion 2 protocol and only then ov er the v ersion 1
protocol. I recommend remov ing the comments f rom this line and deleting
the 1 number so that only the last protocol v ersion is used. It's high time we
updated the client sof tware and started using more secure technologies.
Getting stuck on old sof tware only causes losses.
HostKey — Specif ies the path to the f iles containing the encoding key. Only
priv ate key s need to be specif ied, used to decry pt incoming packets.
ServerKeyBits— Giv es the length of the serv er key. The def ault v alue is
768; the minimal v alue is 512.
SyslogFacility— Specif ies the ty pes of messages to be stored in the sy stem
log.
LogLevel — Specif ies the lev el of the ev ent to be logged. The possible lev
els correspond to the sy stem lev els, which are considered inSection 12.5.6.
LoginGraceTime — Giv es the time interv al, within which the user has to
enter the correct password bef ore the connection is broken.
PermitRootLogin — Specif ies whether the root user can log in using SSH. It
was already said that root is the god in the sy stem and its account's priv
ileges must be used with care. If it is not adv isable to log in as root regularly,
this is all the more so using SSH. Change this parameter tonoat once.
StrictModes — Specif ies whether sshd should check the status of the f iles
and their owners, user f iles, and home directory bef ore accepting the login.
It is desirable to set this parameter toyesbecause many nov ice users make
their f iles accessible f or writing to ev ery one.
Authorizedkeyfiles— Specif ies the f ile storing the public key that can be
used f or user authentication.
IgnoreRhosts — When set toyes, the ~/.rhosts and ~/.shosts cannot be read.
The v alue should not be changed unless really necessary, because doing so
may hav e a negativ e ef f ect on the security.
AllowGroups — Allows only the users of the specif ied groups to log into the
sy stem. The user group names are listed af ter the key word, separated by
spaces.
AllowUsers — Allows only the users listed af ter the key to enter the sy stem.
The user names are listed separated by spaces.
DenyGroups — Denies login to users of the specif ied groups. The user
group names are listed af ter the key word, separated by spaces.
AllowUsers — Denies login to users listed af ter the key. The user names are
listed separated by spaces. This parameter comes in handy when a user of a
permitted group has to be denied login.
I recommend specif y ing the names of the groups and users that can log into
the sy stem ov er SSH explicitly.
The SSH client conf iguration settings contain ev en f ewer parameters. The
global settings f or all of the sy stem's users are stored in the
/etc/ssh/ssh_conf ig f ile. But any settings f or any user can be redef ined in
the .ssh_conf ig f ile in the particular user's directory. The contents of the
global conf igurations f ile (with some comments omitted) are shown in
Listing 5.2.
# Host *
# ForwardAgent no
# ForwardXll no
# RhostsAuthentication yes
# RhostsRSAAuthentication yes
# RSAAuthentication yes
# PasswordAuthentication yes
# FallBackToRsh no
# UseRsh no
# BatchMode no
# CheckHostIP yes
# StrictHostKeyChecking ask
# IdentityFile ~/.ssh/identity
# IdentityFile ~/.ssh/id_rsa
# IdentityFile ~/.ssh/id_dsa
# Port 22
# Protocol 2, 1
# Cipher 3des
# Ciphers aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc,arcfour, # aes192-
cbc, aes256-cbc
# EscapeChar ~
Host *
Protocol 1, 2
Some of the parameters in this f ile are the same as in the serv er conf
iguration f ile. One of these is theProtocolparameter, which specif ies the
SSH v ersion being used. But in the case of the client, the v ersion 1 protocol
should not be disabled. This will not af f ect the security of the client but will
help y ou av oid problems when connecting to a serv er that supports only
this protocol.
The f ollowing are the most common client parameters: Host— Specif ies, to
which serv er the f ollowing declarations are to apply.
CheckHostIP— If this parameter is set toyes, the IP address will be checked
in the known_hosts f ile. Compression— Enables (yes) or disables (no) data
compression.
KerberosAuthentication— Enables (yes) or disables (no) Kerberos
authentication.
IdentityFile— Specif ies the name of the f ile containing the priv ate user key
s.
PasswordAutentication— Specif ies authentication by the password.
Consider how to connect to a remote serv er. This is done by executing the f
ollowing command:
ssh user@server
For example, to connect to the serv er f lenov m as the user f lenov, the f
ollowing command has to be executed:
ssh flenov@flenovm
This can be prev ented by using dif f erent passwords f or each connection.
But it is dif f icult to remember all of the passwords, so it is better to perf orm
authentication by key s, which are protected exceedingly well. All y ou hav e
to do f or this is modif y the conf iguration slightly.
Start by creating a new key. This is done with the help of thessh-keygen
program. It has to be passed the f ollowing two parameters:
-t — The key ty pe. This can bersaordsaf or the second SSH v ersion, orrsalf
or the f irst v ersion. Thersakey will be used in the example.
-f — The f ile, in which the priv ate key is to be stored. The open key f ile
will be named the same, but with the PUB extension.
-b— The key length, which should be 512 minimum. The def ault v alue is
1024, which y ou should leav e in place.
If the f ile, in which to store the key, is not specif ied when the key is
generated, by def ault an RSA key f ile, named id_rsa, will created in the
~/.ssh/ directory. The key f ile f or DSA encoding will be stored in the same
directory but will be named id-dsa. I specif ied the key f ile name on purpose
to show how to do this.
If y ou did ev ery thing right, the program should display the f ollowing
message:
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
If the password conf irmation is successf ul, the f ollowing messages are
display ed:
Your identification has been saved in ~/ssh/myrsakey. Your public key has
been saved in ~/ssh/myrsakey.pub.
The f irst message inf orms y ou that the priv ate key has been sav ed in the
~/ssh/my rsakey f ile. The public key is sav ed in the ~/ssh/my rsakey.pub f
ile.
The ~/ssh/my rsakey.pub key f ile has to be sent to the remote computer f or
the SSH serv er to use it f or the authentication. The f ile can be sent ov er
open communication channels, because ev en if it is intercepted by nef arious
indiv iduals, it is useless without the password y ou entered when the key s
were created and without the priv ate key.
The administrator of the remote serv er has to add the contents of the public
key f ile to the .ssh/authorized_key s f ile. This can be done by executing the
f ollowing command:
You can now connect to the serv er using the public key instead of a
password to authenticate y our identity. But bef ore y ou do this, make sure
that the serv er conf iguration f ile contains the f ollowing directiv es:
RSAAuthentication yes
PubkeyAuthentication yes
Now the serv er will ask y ou not f or the password but f or the passphrase
specif ied when generating the public key.
Enter passphrase for key
XllUseLocalhost yes — If this parameter is set toyes, the local X serv er will
be used.In this case, the client will work with the local X11 and the serv ice
inf ormation sent ov er the network will be encry pted.
If y ou want to connect to the Linux graphical shell f rom Windows, y ou will
need a program like X11 f or this operating sy stem. I can recommend the
XWin32 client f or this, which can be downloaded f rom this site:
www.starnet.com.
I do not recommend using X11, because this technology is still in the dev
elopment stage and there are methods to f ake or break into the connection.
The SSH packet also includes two usef ul utilities: the sf tp serv er (an FTP
serv er that supports data encry ption) and the sf tp client (an FTP client to
connect to the sf tp serv er). Examine the last line of the SSH serv er
/ect/ssh/sshd_conf ig conf iguration f ile:
Subsystem sftp /usr/libexec/openssh/sftp-server
Working with the sf tp client is no dif f erent f rom working with the SSH
client. Execute the sftp localhostcommand; the login message, the same as
considered in Section 5.3.5, will appear. Enter the correct password and y ou
will be taken to the f tp client command line, f rom which y ou can send and
receiv e f iles using FTP commands. This protocol is considered in detail in
Chapter 10; f or now, y ou only need to know that most of its commands are
similar to the Linux f ile handling commands.
You should keep it in mind, howev er, that not all FTP serv ers and clients
support SSH encoding. You should ascertain that y our sof tware supports
this protocol bef ore using it.
How do these daemons decide which serv ice to start? They employ the
/etc/serv ices f ile f or this. The f ile contains a list of serv ices and the
associated ports in the f ollowing f ormat:
name port/protocol alias
Name — The name of the serv ice to run. Port— The port number to monitor.
Protocol — The inetdserv ice can work with TCP and UDP, whose ports do
not intersect (and are totally dif f erent); thus, the protocol to work with has
to be specif ied explicitly.
Alias — A name that can be giv en to the serv ice. For example, there are f
ollowing lines in the /etc/serv ices f ile:
tcpmux 1/tcp # TCP port service multiplexer tcpmux 1/udp # TCP port
service multiplexer rje 5/tcp # Remote Job Entry
rje 5/udp # Remote Job Entry
echo 7/tcp
...
...
ftp 21/tcp
ftp 21/udp fsp fspd ...
...
I selected these entries on purpose to show y our how v arious serv ices are
described.
If y ou hav e an old Linux distribution, it most likely still uses inetd. As was
already mentioned, this old v ersion is a potential security problem. You
should update to xinetd, which is becoming, if it has not already become, the
standard.
The /etc/xinetd.conf f ile is the main conf iguration f ile f or the xinetd
daemon. The f ile contains def ault conf iguration settings f or the serv ices to
be launched and the directory, in which the conf iguration f iles f or specif ic
serv ices are to be stored. The contents of the f ile are shown in Listing 5.3.
#
# Simple configuration file for xinetd #
# Some defaults, and include /etc/xinetd.d/
defaults {
instances
log_type
log_on_success = 60
= SYSLOG authpriv = HOST PID
log_on_failure = HOST cps = 25 30
}
includedir /etc/xinetd.d
The defaultskey word is f ollowed by the def ault settings f or all serv ices.
Any of these v alues can be changed f or each indiv idual serv ice.
The last entry specif ies the /etc/xinet.d directory : includedir /etc/xinetd.d
This catalog contains conf iguration f iles f or each serv ice. The f iles are
named af ter the corresponding serv ices; their contents are similar to the
contents of the /etc.xinetd.conf f ile. Listing 5.4shows the contents of the
/etc/xinet.d/telnet conf iguration f ile f or the Telnet serv ice.
# default: on
# description: The telnet server services telnet sessions; # it uses unencrypted
username/password
# pairs for authentication.
service telnet
{
disable = no
flags = REUSE
socket_type = stream
wait = no
user = root
server = /usr/sbin/in.telnetd log_on_failure += USERID
}
The f ollowing are the main parameters that can be edited:
disable— If set totrue, this disables the serv ice. flags— Attributes f or the
serv ice's execution.
socket_type— The ty pe of the socket used. Should be streamf or TCP,
anddgramf or UDP.
protocol— The protocol used to transf er data (TCP or UDP).
server— The f ull path to the daemon's executable program.
user — Access rights. In most cases, the v alue of this parameter will beroot.
This is a normal situation, because the root rights are required f or working
with ports below 1024. Currently, most serv ices lower their rights according
to the settings.
In connection with the userparameter, I stated that the root rights are
necessary to be able to work with ports below 1024. What is the reason f or
this restriction? Unless a user has the root rights, he or she will not be able to
launch a serv ice that works with a port in the 1 to 1024 port number range.
This protection is necessary because ports in this range are used by important
serv ices that regular users are not allowed to run.
Just imagine that hackers who only manage to obtain user rights are able to
run the FTP serv er. This will allow them to upload to and download f rom
the serv er any f iles that they desire, which will not make y ou happy.
5.4.2. Security
You already know that the rights and time to access serv ices using the
xinetdprogram can be restricted. This can be done using theno_access,
only_from, andaccess_timecommands in the conf iguration f ile.
The no_accesscommand prohibits access f rom the specif ied computers. For
example, the f ollowing entry in the conf iguration f ile prohibits access f rom
the 192.168.1.1 address:
no_access 192.168.1.1
To prohibit access f rom an entire network, only its address has to be specif
ied. For example, to prohibit access to all computers in the
192.168.1.xnetwork, the f ollowing entry is added:
no_access 192.168.1
Note that in this case the IP address consists not of f our octets, as usual, but
only of three.
To prohibit access completely, the f ollowing line has to be added to the conf
iguration f ile:
no_access 0.0.0.0
Now consider how access can be allowed using the only_fromcommand. This
command is handy because it can be used to prohibit access f rom any
address and then allow it only f rom a specif ied address. Access f rom any
address is prohibited by issuing the command without an argument, as f
ollows:
only_from =
Next, consider how the access time can be specif ied. It is logical to allow
access to a serv er working in a company of f ice only during work hours. For
example, the f ollowing entry allows access only f rom 8:00 to 18:00:
The xinetdbuilt-in security f unctions are quite conv enient and powerf ul, ev
en though they double the access rights that can be conf igured in the
/etc/hosts.allow and /etc/hosts.deny f iles. I pref er conf iguring security
settings using the xinetdconf iguration f iles because the access parameters
here are stored in the f iles of those serv ices that they af f ect.
Many local network administrators did not wish to burden themselv es with
conf iguring the FTP serv er f or f ile sharing and started simply allocating a
dedicated FTP serv er with public access f or this.
Windows introduced a more conv enient way to share f iles: the Network
Neighborhood (My Network Places in Windows XP) serv ice. This serv ice
display s the network's computers, whose shared resources are av ailable to
all network users. This is a handy f eature, so it's no wonder that users
quickly became used to it despite the dangers posed by working with shared
resources.
The Samba package was dev eloped to let Windows users see Linux serv ers
in their network env ironment and perf orm f ile operations on them like on
Windows machines. The package is of ten called by its abbrev iated name
smb and comprises two programs. The serv er allows local f olders to be
shared; the client is used to connect to other computers and work with their
shared resources.
Samba can be used to make a practical, user-f riendly f ile serv er. I used to
employ a Windows 2000 serv er f or this purpose that was also used as a
database serv er. But a f ile archiv e takes too much disk space, consumes
network resources, and negativ ely af f ects the sy stem security. Theref ore, I
decided to mov e the f ile archiv e to a separate phy sical serv er. The
question was what operating sy stem this serv er should run under. To use
Windows 2000 to run a f ile serv er would be like using a luxury car f or
taking trash to a dumpster 20 f eet f rom y our house. Linux, which is much
less expensiv e and does not require routine maintenance, is much more
suited to this purpose. Once the serv er has been conf igured, it can run f or y
ears without requiring f urther attention. Such was the operating sy stem I
installed to run my f ile serv er, and it has been handling its duties without a
hitch ev er since.
There aren't many parameters in the smb.conf f ile, so I giv e a small example
of it in Listing 6.1to help y ou understand the ov erall structure of this f ile.
Further, I will consider other Linux serv ers, which require many more conf
iguration settings.
[global]
# Main parameters
workgroup = MYGROUP
server string = Samba Server
# Security parameters
security = user
; password server = <NT-Server-Name>
; password level = 8
; username level = 8
encrypt passwords = yes
smb passwd file = /etc/samba/smbpasswd
dns proxy = no
The actual f ile in y our sy stem will be much larger, because it contains
numerous comments describing and giv ing examples of how public
directories are conf igured. I deleted all of those comments to make it easier
to orient y ourself in the f ile's contents when considering its directiv es.
Directiv es in most Linux and application sof tware conf iguration f iles hav e
the f ollowing f ormat:
Parameter_Name Value
The v alue of the parameter is giv en af ter an equal sign. In this way, the
parameter name can consist of sev eral words and contain any character with
the exception of the equal sign.
workgroup = name — The name of the workgroup the serv er will appear to
be in when queried by clients. When y ou open the network env ironment in
Windows, y ou can see all av ailable resources shown by groups. Each group
can contain its computers or serv ers.
netbios name = name — This specif ies the name, by which the giv en Samba
serv er is known and will be shown in the network env ironment. It cannot be
the same as the workgroup name.
printcap name = file — This specif ies the f ile containing descriptions of the
printers connected to the sy stem. The def ault f ile is /etc/printcap.
load printers = yes | no — When set toyes, this specif ies all printers in the
printcap f ile to be loaded f or browsing by def ault. If there is no need f or
this, set this parameter tono.
printing = style — This specif ies the printing sty le. The f ollowing options
are av ailable:bsd, sysv, plp, lprng, aix, hpux,andqnx.
6.1.2. Security
The parameters that directly or indirectly af f ect security are the f ollowing:
guest account = name — This is a user name that will be used to access the
serv ices specif ied asguest ok. If y our serv er does not store any conf
idential inf ormation and is used f or open f ile exchange, y ou can create a
guest account; otherwise, allowing a guest login may be a security threat.
log file = file_name — This is the name of the log f ile, f or example, /v
ar/log/samba/%m.log. The %m combination in the f ile name will be
substituted with the name of the user whose activ ity is logged. Thus, f or the
user name robert, a log f ile named /v ar/log/samba/robert.log will be created.
max log size = n— This sets the maximum log size in kiloby tes. There is no
size limit if this is set to0.
security = level — Based on the v alue, clients decide whether and how to
transf er user and password inf ormation to the serv er. The f ollowing v alues
are av ailable:
user— A user must log onto ausersecurity serv er with a v alid user name and
password bef ore attempting to access shared resources.
share — Users don't hav e to log onto the sharesecurity serv er. A user name
and password are required when accessing each particular share.
server — This specif ies the name of the serv er, on which the passwords are
stored. (This is in case the passwords are stored on another serv er using
thepassword server = Server_Nameparameter.)
security = domain — The user name and password are v alidated by passing
them to a Windows NT primary or backup domain controller, just like a
Windows NT Serv er would do. The password f ile to use is specif ied using
thesmb passwd file = file_pathparameter.
For Windows 2000 and XP, the parameter is in the f ollowing key :
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\
LanmanWorkStation\Parameters
If y ou experience dif f iculties logging onto the serv er, switch the sy stem to
work with plaintext passwords. In this case, a Samba serv er will use the
/etc/passwd and /etc/shadow f iles to perf orm the authentication. It encry pts
the plaintext password using the MD5 algorithm and compares it with the
encry pted passwords stored in the /etc/shadow f ile.
smb passwd file = file_path — This specif ies the path to the encry pted
smbpasswd f ile. By def ault, this is the directory, in which Samba's conf
iguration f iles are located.
ssl CA certFile = file_path — This parameter specif ies the path to the Certif
ication Authority (CA) f ile, necessary f or operation of the SSL protocol
used f or secure data transf er.
For this directiv e to work, the program to change the password has to be
specif ied in the passwd program parameter and the program to control the
conv ersation that takes during the password change must be specif ied in the
passwd chatparameter. The f ollowing is an example of the parameter's use:
unix password sync = Yes
passwd program = /usr/bin/passwd %u
passwd chat = *New*password* %n\n *Retype*new*password* %n\ n
*passwd:*all*authentication*tokens*updated*successfully*
Moreov er, the encrypt passwordsand smb passwd file directiv es hav e to be
used.
username map = file_path — This specif ies the f ile containing a mapping of
user names f rom Windows clients to the Samba serv er. This f ile is
described in more detail in Section 6.3.
6.1.3. Network
In this section, the network protocol conf iguration parameters are
considered. These are the f ollowing:
include = file_path— This parameter allows y ou to use the smb.conf f ile f
rom another computer. The name of the f ile is specif ied in thepath.%mf
ormat. Here,pathis the absolute path to the f ile on the remote machine,
and%mis the NetBIOS name of the machine, f or example,
/etc/samba/smb.conf .robert.
local master = yes | no— This option allows a Samba serv er to become the
main local browser on the subnet.
domain master = yes | no— This option allows a Samba serv er to become
the main local browser on the domain. Do not set the v alue of this parameter
toyesif there is a Windows NT domain controller in y our network.
domain logons = yes | no — If set toyes, the Samba serv er will serv e
Windows 95/98 domain logons f or the workgroup it is in. This will allow
Samba passwords to be used when booting on a Windows computer.
logon path = path — Specif ies the home directory where user prof iles are
stored. To use this option, the comments must be remov ed f rom
the[Profiles]section in the def ault conf iguration f ile.
The Windows Internet Naming Serv ice (WINS) is a serv ice f or mapping
NetBIOS computer names to their respectiv e IP addresses. A WINS database
is similar to DNS, only it stores NetBIOS host names as opposed to the
domain names used in DNS.
File naming conv entions dif f er between Linux and Windows. For example,
in Linux, f ile names are case-sensitiv e, and in Windows they are not. This
means that DATA.TXT and data.txt are treated as the same f ile in Windows
but not in Linux. This problem can be solv ed by using sev eral parameters.
These are the f ollowing:
case sensitive = yes | no— If set to yes, case sensitiv ity is ignored.
default case = lower— All f ile names are depicted in lowercase.
preserve case = yes | no and short preserve case = yes | no— These
parameters control whether the case inf ormation in f ile names is preserv ed.
If there are Windows sy stems in the network, the preceding v alues should
not be changed. For a homogenous Linux network, case inf ormation can be
preserv ed.
Users normally want to work in their own directories. To do so, a user has to
hav e a Linux account, to which his or her directory will be linked. This
directory is specif ied as//server/name, whereserveris the serv er name or IP
address andnameis the name of the user whose home directory is to be v
iewed.
To allow users' work with their indiv idual directories, the [homes]section has
to be described. Consider an example of this section:
[homes]
browseable = yes | no — Specif ies whether the share is seen in the list of av
ailable shares in a network v iew and in the browse list. If set toyes, user f
olders will be shown in the network env ironment.
writable = yes— Specif ies whether the home directory can be written to.
When set to no, users of the serv ice may not create or modif y f iles in the
directory.
create mode = 0750 — Specif ies permission f or created f iles. In this case,
the f ile owner has f ull rights, group members hav e read and execute rights,
and all other users don't hav e any rights. Sometimes, howev er, the
parameter's v alue should be lowered to 740 so that group users would hav e
only read rights.
If a Linux serv er is conf igured to let a Windows user enter the sy stem
through Samba, using it as a domain, comments in the [netlogon]section must
be remov ed.
; [netlogon]
; comment = Network Logon Service
The v alue of the writableparameter is set to nobecause users must not hav e
write rights f or this directory ; scripts that are executed when they log onto
the sy stem are stored in this directory. Only the administrator should hav e
the write rights f or this directory.
The directory specif ied in this section stores user prof iles, and it should not
be seen in the Windows network env ironment. For this reason, the v alue of
the browseableparameter is set to no.
6.2.3. Printing
By def ault, the section is already open and registered users already hav e
access to the printers. To make printers av ailable to guest users, add the
public = yesentry to the section. I do not recommend doing this, because it
will giv e users additional means f or play ing jokes. For example, I know of
a case, in which a worker was sending pictures to all network computers. It
may look like an innocent joke, but this interf ered with legitimate work and
wasted paper and cartridge ink.
Ev en though hav ing this directory is quite conv enient, I recommend using it
in closed networks only. In networks with access to the Internet, I
recommend limiting access to Samba with the help of a f irewall. Because the
directory is open f or writing to any one, hackers can upload f iles into it that
can be used to obtain root priv ileges on the serv er.
All prev iously -considered sections of the smb.conf f ile solv e particular
tasks and hav e established names. In some cases, howev er, the name of a
section can be changed without af f ecting the serv er operation. I, howev er,
do not recommend doing this, because the new section name may work in
one Samba v ersion but not when the serv er sof tware is updated. In this
case, it will be dif f icult to trace the error causing the f aulty operation. You
can, howev er, create y our own sections and describe rights in them. For
example, y ou may want to create a shared directory, in which all users can v
iew f iles but only users of a certain group can write to. Suppose that this
directory is f or storing images. This task is accomplished by creating a
[shareimages]section as f ollows:
; [shareimages]
; comment = Share Images
; path = /home/samba/images
; public = yes
; writable = yes
; write list = @staff
; printable = no
Samba user names are described in the /etc/samba/smbusers f ile. The name
and location of the f ile can be changed using theusername mapparameter in
the smb.conf f ile. The contents of the /etc/samba/smbusers f ile are similar to
the f ollowing:
# Unix_name = SMB_name1 SMB_name2
root = administrator admin
nobody = guest pcguest smbguest
The list has sev eral uses. For example, it can be used to map DOS or
Windows user names to a Linux user name. For example, the maximum
rights Window user, administrator or admin, can be mapped to the Linux user
with the same f unction who goes by a dif f erent name: root. In this case, the
mapping is done in the second entry of the example:root =
administrator admin. Ev en though administrator and admin are dif f erent
accounts, they will use the same password: the one of the root user.
The f ile's second f unction is to accumulate sev eral user names under one
user account. For example, y ou may hav e to assign the same rights to a
group of users. This is done by creating a Linuxnobodyaccount, which users
will use f or their work. Next, Samba usersguest, pcguest, and smbguestare
created, which will be used to log onto the sy stem.
It can be seen right away that it is somewhat similar to the contents of the
/etc/passwd f ile. The inf ormation in it is div ided into sev eral colon-
delimited f ields. The most interesting of these f ields are the f irst three: the
user name, the Linux UID, and the password.
a — Adds a user to the Samba sy stem. The account should already exist in
the /etc/passwd f ile. For example, the f ollowing command adds the user
robert, which y ou worked with bef ore:
smbpasswd -a robert.
In response, the program asks y ou to enter and conf irm the password. This
password has no relation to the sy stem password and is only used to log onto
Samba. Thus, the sy stem and Samba passwords can dif f er. I recommend
making them dif f erent. All Windows v ersions can store passwords, and this
f unction is not implemented securely in Windows 9x.If the Samba password
is the same as the sy stem password and f alls into the wrong hands, the sy
stem will be compromised.
Note that the letter "D" was pref ixed to the contents of the f ourth f ield. It
indicates that this account has been deactiv ated. In this way, y ou can easily
tell, which accounts are activ e and which are not.
To connect to the serv er, at least two options hav e to be specif ied: -L(a serv
er's address) and-U(a user name). In response, the program asks y ou to enter
the password. If y ou are using encry ption, enter the sy stem password;
otherwise, enter the password specif ied when transf erring the user to the
/etc/samba/smbpasswd f ile (with thesmbpasswdcommand).
The sy stem will respond by display ing all shared resources of the serv er.
The result will look similar to this:
Domain=[MYGROUP] OS=[Unix] Server=[Samba 2.2.3a]
Sharename
--------Type Comment
------------
IPC$
ADMIN$ IPC IPC Service (Samba Server) Disk IPC Service (Samba Server)
Server
--------
FLENOVM
Comment
---------
Samba Server
Workgroup
--------MYGROUP
Master
---------
FLENOVM
Note that not all directories are shown in this list. For example, the v alue of
thebrowseableparameter f or home directories in the[homes]directory is set
tono(seeSection 6.2.1). This means that these directories will not be shown.
This is quite logical, because unauthorized people should not be allowed to v
iew directory names, especially if they correspond to user names or if the
directories contain conf idential data. Nev er change this parameter so that
hackers will not know what to hack.
For example, say y ou want to connect to the home directory of the f lenov
user. It address is \\192.168.1.1\f lenov.
If the connection to the serv er is successf ul, the serv er will respond with the
prompt, at which v arious f ile-handling commands can be entered. The
prompt looks as f ollows:
Smb: \>
For y our serv er machine to be able to serv e Web pages, it must hav e a
Web (HTTP) serv er program installed. The most widely -used Web serv er
has long been Apache. It is dif f icult to estimate the share of Apache serv ers
among the total number of Web serv ers, but it can be said with conf idence
that they comprise more than half . Ev en though there are other Web serv ers
f or Linux (e.g., TUX), when talking about a Web serv er f or Linux, it is
Apache that is meant.
Secure— Many prof essionals consider this serv er the saf est.
Reliable— In tandem with Linux, the serv er can work f or y ears without
being reloaded.
Undemanding— The serv er does not require any special resources and
places a minimal load on the sy stem.
Efficient— The serv er rapidly responds to and handles user requests.
There are Apache-based serv ers that work practically without ev er being
turned of f (av ailable 99.9% of time). Many corporations trust this serv er
with their important data, and I hav e nev er heard of any one who regretted
hav ing chosen Apache f or this.
The only shortcoming that users complain about is that the serv er is dif f
icult to conf igure. This is done by editing a text f ile, and, because there are a
huge number of conf iguration settings, this may be a demanding task. Also,
the abundance of settings makes it easy to set some of them to the wrong v
alues, which may negativ ely af f ect sy stem's ef f iciency and/or security.
Considering the conf iguration of all existing Apache parameters is bey ond
the scope of this book; there are just too many of them. But I will consider
the most important ones and explain what may af f ect the serv er's ef f
iciency and security.
Like most other serv ices, Apache can be conf igured using a simple and conv
enient graphical utility. It is launched by selecting the System
Settings/Server Settings/HTTP Server menu sequence in the main menu.
Fig. 7.1 shows the main window of the Apache graphical conf iguration
utility.
Figure 7.1: The main window of the Apache graphical conf iguration utility
The graphical utility is conv enient f or conf iguring initial settings, but af
terwards y ou should rev iew the conf iguration f ile. For this, y ou hav e to
know its parameters.
The graphical conf iguration utility should not be used af ter y ou edit the
conf iguration f ile manually because it may interpret the manually -edited v
alues incorrectly and replace
Note them with what it considers to be the right ones. For the changes to take
ef f ect, the serv er has to be restarted. The Apache serv er reads the conf
iguration f ile parameters only when it is started.
By editing the conf iguration f ile directly, the most secure and most ef f
icient serv er operation can be achiev ed. The main parameters of the Apache
Web serv er are the f ollowing:
ServerRoot— Specif ies the root directory, in which logs and conf iguration f
iles are located.
Timeout— Giv es the maximum time to wait when receiv ing or sending
packets.
Port — Specif ies the port, on which the serv ice is to work. The def ault v
alue f or public serv ers is 80. Howev er, this v alue can be changed f or priv
ate serv ers, f or example, to 10387. In this case, the page address is specif
ied as ServerName:10387— f or example,
www.linux.com:10387/index.htm. This prev ents hackers f rom penetrating
the sy stem through the standard Web port unless they scan all ports and f ind
out that port 10387 is used f or the Web serv er. This is a simple but quite ef f
ectiv e protection f rom script kiddies, who possess minimum knowledge
about computer security and break into computers only using exploits
designed by other hackers.
Full — Directs the header to display f ull inf ormation about the serv er and
the installed modules, including their v ersions. Using this parameter puts the
serv ers in the grav est danger.
Min — Directs the header to display minimal inf ormation: only the serv er
name and the installed modules. Ev en a simple list of modules without their
v ersions rev eals too much inf ormation to hackers.
ProductOnly — Specif ies the serv er, Apache in this case, and will return the
serv er's name without the v ersion. This is what y ou need.
Experienced administrators can ev en change the serv er's name, but this
requires them to recompile Apache's source codes. The header is stored in the
include/ap_releas.h f ile as the f ollowing two lines:
#define SERVER_BASEPRODUCT "Apache"
#define SERVER_BASEVERSION "2.0"
Replace the serv er name and v ersion with other v alues. Only use a real serv
er name, because a prof essional hacker will notice the switch.
In earlier Apache v ersions, the f ile was located in a dif f erent directory.
User/Group — Giv es the name of the user and group that hav e rights to run
the serv ice. The def ault v alue isapache. This user and group should possess
the minimal rights in the sy stem, suf f icient only f or operation of the Web
serv er and its modules. Nothing unnecessary should be allowed.
ErrorLogandCustomLog— Specif ies the location of the error and custom log
f iles.
LogLevel — Specif ies the ty pes of messages to log. Possible v alues are the
f ollowing:emerg, alert, crit, error, warn, notice, info, anddebug.
7.2. Modules
Modules are an important component f or conf iguring an Apache serv ice.
They are loaded according to the instructions in the
/etc/httpd/conf /httpd.conf f ile. These look similar to the f ollowing:
<IfDefine HAVE_PERL>
LoadModule perl_module modules/libperl.so
</IfDefine>
By def ault, all installed modules or the modules included in the distribution
are loaded. But this is not an ef f icient arrangement, because the
distribution's dev eloper cannot possibly know what modules a particular user
may need. The f ollowing main script-support modules can be loaded:
perl_module— Perl
php_module— PHP
php3_module— PHP v ersion 3
php4_module— PHP v ersion 4
python_module— Py thon
These modules present the biggest danger f or Web serv ers, because they
allow execution of scripts, which can be used to carry out a break-in. For
example, a hacker can exploit a bug in a PHP script to execute commands on
the serv er. Well-designed sites use only one Web programming language,
and y ou should load only the module necessary to support the corresponding
language.
Modules that are not used should be disabled; this will greatly limit
opportunities f or break-ins. Remember, a running program is an
administrator's enemy and a potential door a hacker can use to enter the sy
stem.
Rev iew the modules that are loaded, and delete or comment out those that
are not necessary. This will increase the security of the Web serv er by more
than 50%. Why is this so? Although Py thon is seldom used by hackers, Perl
and PHP are popular among them. As mentioned earlier, any program is a
potential entry point into the sy stem. Disabling one of the two programs
(PHP or Perl) cuts the number of the potential doorway s in half .
The f irst block of code sets permissions f or a certain directory on the disk
(in this case, the /v ar/www/html directory ); the second block of code limits
permissions f or a v irtual directory (in this example, the /serv ername/serv
erstatus directory ). If y ou are f amiliar with HTML, y ou should already
understand the preceding declarations. For those who do not hav e this
knowledge, I will prov ide a f ew explanations f or the directory example.
The declaration code starts with the f ollowing line:
<Directory Path>
In the angle brackets, the key word Directoryis specif ied, f ollowed by the
path to the directory, f or which the permissions hav e to be set. Af terward,
commands def ining the permissions f ollow. The block ends with the line:
</Directory>
The permissions are specif ied using the f ollowing directiv es:
Allow from parameter — Indicates, f rom which hosts the specif ied
directories can be accessed. Theparameterv alue can be one of the f ollowing:
domain name — Specif ies the domain name, f rom which the directory can
be accessed. For example, specif y ingdomain.comwill allow only users of
this domain to access the directory f rom the Web. If y ou want to protect
some f iles, y ou can limit access to the f older containing them to y our
domain or only to the local machine like this:allow from localhost.
env = VariableName — If the specif ied env ironmental v ariable is def ined,
access is allowed. The f ull f ormat of the directiv e is the f ollowing:allow
from env =
VariableName.
Deny from parameter — Denies access to the specif ied directory. The
parameters are the same as those f or the allow fromdirectiv e, only in this
case access is denied f rom the specif ied addresses, domains, and so on.
Order deny, allow — Initially, access is allowed to all; then prohibitions are
applied, f ollowed by permissions. It is adv isable to use this combination f or
shared directories, to which users can upload f iles.
Order allow, deny — Initially, access is denied to all; then permissions are
applied, f ollowed by prohibitions. It is adv isable to use this combination f or
all directories containing scripts.
Require parameter — Specif ies users who are allowed access to the
directory. The parameter v alue can be one of the f ollowing:
user — The name of users (or their IDs) allowed access to the directory. For
example, Require user robert FlenovM.
group— The names of groups whose users are allowed access to the
directory. The directiv e works the same as theuser directiv e.
valid-user — Access to the directory is allowed to any user that has been
authenticated.
Satisfy parameter — If set toany, access is restricted by using either a
login/password procedure or an IP address. To identif y users using both
procedures, the v alue should be set toall.
The key word optionis f ollowed by a plus or minus sign, which corresponds
to the option being enabled or disabled, respectiv ely. Theparameterv alue
can be one of the f ollowing:
All of the directiv es just described can be used not only in the /etc/httpd/conf
/ httpd.conf f ile but also in the .htaccess f iles, which can be placed in indiv
idual directories and def ine the permissions f or their corresponding
directories.
Access rights can be def ined not only f or directories but also f or indiv idual
f iles. The f iles access rights are def ined between the f ollowing two entries:
<Files FileName>
</Files>
This declaration is, in turn, placed inside the directory access rights def
inition, f or example, as f ollows:
<Directory /var/www/html>
Order allow, deny
Allow from all
<Files "/var/www/html/admin.php">
Also, sometimes only selected users can send data to the serv er. For
example, ev ery one can execute scripts in a specif ied directory, but only
administrators can load inf ormation to the serv er. This problem is easily
solv ed by separating the rights to use the HTTP methods.
As y ou can see, the process is similar to def ining f ile and directory access
rights. Ev en the same access-rights terms are used, which are placed within
the <Directory>or <Location>def inition blocks and af f ect only the specif
ied directory.
For example, the f ollowing def inition block can be used to prohibit any data
transf ers to the serv er's /home directory :
<Directory /home>
Within the rights def inition block f or the /home directory, the GETand
POST methods are limited.
Alway s, f irst prohibit ev ery thing that y ou can and only then start gradually
setting permissions so that all scripts will operate properly. It is better to
specif y an extra explicit prohibition than to let a permission slip through that
can be used by hackers to destroy y our serv er.
The parameters of the v irtual serv er are specif ied between these tags. For
example, the f ollowing is a description f or a v irtual serv er that uses address
192.168.1.1 and port 80:
<VirtualHost 192.168.1.1:80>
ServerAdmin admin@your_server.com
DocumentRoot /var/www/your_server
ServerName your_server.com
ErrorLog logs/your_server.com -error_log CustomLog logs/your_server.com
-access_log common
AuthGroupFile file path— Specif ies the name of the f ile, in which the list of
user groups is stored.
AuthUserFile file path — Specif ies the f ile containing user names and
passwords. It is adv isable to create this list using the htpasswd utility.
AuthAuthoritative On | Off — Specif ies the access rights check method. The
def ault v alue isOn.If the directiv e is set toOffand the user does not prov ide
a name, user authentication is carried out by other methods, f or example,
using the IP address.
The AuthUserFiledirectiv e specif ies the f ile containing the list of names
and passwords of the site's users. Finally, theRequiredirectiv e is used with
thevalid-userargument. This means that only successf ully authenticated users
will be able to open f iles in the current directory.
These permissions can also be specif ied in the .htaccess f ile: <directory
/path>
AuthType Basic
AuthName "By Invitation Only"
AuthUserFile /pub/home/flenov/passwd
Require valid-user
</directory>
The central httpd.conf f ile is pref erable f rom the security standpoint,
because it is located in the /etc directory, which is outside the scope of the
Web serv er root directory, and access to it must be f orbidden to regular
users.
In this section, y ou will learn how to create and control Apache password f
iles. The f ile specif ied in theAuthUserFiledirectiv e is a simple text f ile
containing user name and password entries in the f ollowing f ormat: flenov:
{SHA}1ZZEBtPy4/gdHsyztjUEWbOd90E=
There are two f ields in the preceding entry, separated by a colon. The f irst f
ield contains a user name, and the second f ield contains the user password
encry pted using the MD5 algorithm. It is dif f icult to edit this f ile manually
; moreov er, there is no need f or this because the htpasswd utility is intended
f or this task.
The utility can encry pt passwords using both the MD5 algorithm and the sy
stem'scrypt ()f unction. Both ty pes of passwords can be stored in the same f
ile.
If y ou store user names and passwords in a DMB database f ile (specif ied by
theAuthDBMUserFiledirectiv e in .htaccess f iles), use thedbmmanage
command to manage the database.
The htpasswd utility is inv oked as f ollows: htpasswd arguments file name
password
Use of thepasswordandfileswitches is optional, depending on the specif ied
options. The utility takes the f ollowing main switches:
-c — Creates a new f ile. If the specif ied f ile already exists, it is ov erwritten
and its old contents are lost. The f ollowing is an example of the command's
use:
When this directiv e is executed, a prompt to enter and then conf irm the
password f or the user robert will be display ed. Af ter successf ul completion
of this procedure, an .htaccess f ile will be created that contains an entry f or
the user robert and the corresponding specif ied password.
-m — Specif ies that passwords are to be created using the Apache modif ied
MD5 algorithm. A password f ile created using this algorithm can be ported
to any other platf orm (Windows, UNIX, BeOS, etc.), on which an Apache
serv er is running. This switch is handy f or a heterogeneous operating sy
stem network, because the same password f ile can be used on machines
running dif f erent operating sy stems.
-d— Indicates that passwords are to be encry pted using the crypt()sy stem f
unction.
-s — Specif ies that passwords are to be encry pted by the Secure Hash
Algorithm (SHA) used by the Netscape platf orm.
-p— Indicates no password encry ption. I don't recommend using this switch;
using it is not prudent f or security.
-n— Don't update the f ile; only display the results.
A new user can be added to the f ile by executing the command without any
switches, only passing the f ile and the user names as the arguments:
htpasswd .htaccess Flenov
There are two restrictions on using the htpasswdcommand: First, a user name
cannot contain a colon, and second, a password can be no longer than 255
characters. These are rather mild restrictions, and both can be liv ed with.
Unless y ou hav e masochistic tendencies, it is doubtf ul y ou will want to use
a password any where close to 255 characters long. As f or the colon, y ou'll
just hav e to do without it.
HTML f iles can be processed directly on the serv er, the same as PHP f iles.
On one hand, this is conv enient, because PHP code can be embedded into
HTM f iles. On the other hand, HTML f iles present a potential security
problem. If hackers modif y them, the serv er can become v ulnerable to a
break-in.
If y ou do not use SSI (and, accordingly, SHTML f iles) comment out the f
ollowing line (by def ault, it is enabled):
AddHandler server-parsed .shtml
The serv er's main settings, which seldom change, can also be separated into
the /etc/httpd/conf /access.conf f ile.
Comment all y our actions. Many settings remain unchanged f or y ears, but
most people hav e dif f iculties remembering why they set this or that directiv
e only a couple of months af ter they did so. For example, y ou prohibited
access to a directory y ou temporarily used to test scripts to all users. Some
time later, y ou may f orget why y ou did this, and open access to the raw
scripts, which may cause a sy stem crash or break-in.
The more conv enient it is to control the serv er security, the f ewer mistakes
y ou will make. Parameter grouping and detailed comments help y ou
remember the purpose of the specif ic settings. This approach to
administration also helps y ou solv e problems ef f iciently as they arise. As y
ou know, in the ev erlasting war between hackers and administrators, those
who know more, are more experienced, and react f aster win. The f
astreaction aspect is especially important.
Centralized storage of access rights in conf iguration f iles of the Web serv er
is only acceptable f or small sites. But these access-rights descriptions
become too unwieldy f or a hundred or more v irtual serv ers. Ev en if all
permission def initions are stored in the /etc/httpd/conf /access.conf f ile, its
size will be too large to f ind the necessary inf ormation in it ef f iciently.
For large sites, I recommend describing in the serv er's conf iguration f iles
only general rules that cov er sev eral directories at once. This can be done
because directory paths can be specif ied using regular expressions. The f
ollowing is an example that def ines rules f or ev ery thing contained in the
/home directory :
<Directory /home/* >
The saf est site is one that uses static (HTML) documents without serv er-side
scripts (PHP, ASP, Perl, Py thon, etc.). If y ou need an interpreter f or y our
site, limit it to minimal capabilities.
Suppose that y our site uses PHP scripts and has f unctions that access the sy
stem. If these f unctions are used improperly (f or example, user-specif ied
parameters are not checked), a malef actor can send such v alues that may
disrupt the serv er's operation. This book does not teach y ou how to write
correct scripts and how to make them secure, because this is a programmer's
job. But y ou should not rely on programmers' prof essionalism, because they
also are humans, and all humans make errors. What y ou should do is to take
all necessary steps to prev ent sof tware bugs f rom becoming f atal f or y our
serv er.
The PHP interpreter has a f eature called safe_mode.This f eature can be used
to describe the rules f or executing certain actions using more secure conf
iguration settings and access rights. But some scripts may not work in this
mode, and many administrators disable it. This is not alway s the right thing
to do. You should check f irst whether the of f ending script can be rewritten
to work; only when this is impossible shouldsafe_modebe disabled.
The administrator should act in close cooperation with the Web script
programmers. If the programmers require some options f or the scripts to be
enabled, the person to do this on both serv ers should be y ou. The dev
elopers should inf orm y ou of any changes in the scripts that require changes
in the access rights, so that y ou can make the necessary adjustments.
The administrator and dev elopers should maintain close contact to be able to
react rapidly to dev elopments necessitating the use of some extra f eatures.
Some administrators like to get rid of the interpreter-conf iguring
responsibilities, shif ting this f unction to their script dev elopers. This is not
right, because a programmer is trained to write programs and has no suf f
icient knowledge to conf igure with the necessary security lev el prov ided.
All PHP interpreter-conf iguration settings are stored in the /etc/php.ini conf
iguration f ile. Consideration of this f ile lies bey ond the scope of this book.
But as y ou already know, sooner or later bugs are discov ered in any sof
tware. Widely -used programs, in particular, attract hackers' attention,
because breaking these allows them to penetrate the numerous sy stems, on
which these programs are installed.
But if y ou do not know the specif ics of the programming language or hav e
no programming skills, y ou will be better of f using sof tware products
written by other people. A script written by an amateur can be broken ev en
by a nov ice hacker without knowledge of the source code, database
structure, and other details that f acilitate breaking Web scripts.
As they say, damned if y ou do, damned if y ou don't. The saf est course is to
use less popular sof tware dev eloped by prof essional programmers on y our
site. It would be ev en better f or it to be closed or ev en custom-written
source code. This entails extra f inancial expenses, but these are smaller than
the costs of restoring the sy stem af ter a break-in.
If y ou are responsible f or only one Web serv er, the task of sof tware
updating is not a problem. But administrators of hosting companies f ace a
daunting task in this respect, because their serv ers host hundreds if not
thousands of Web sites. It is impossible to monitor all Web sites f or regular
sof tware updates, but some sort of protection against careless or lazy site
owners is still needed. The Jail program (seeChapter 4) best suits this task.
Using this program, y ou place a Web serv ice into its own v irtual directory.
If hackers break a Web program and penetrate the Web serv ice using it, their
actions will be limited to the conf ines of the v irtual root directory.
When preparing the material f or this book, I f ound that a v ulnerability was
discov ered in a popular f orum engine that made it possible to execute any
command on a sy stem hosting a Web site with the f orum. This was done by
sending a command f ormatted in a special way through the URL string. I
started writing this chapter about a month af ter the bug was discov ered and,
remembering this, decided to check a f ew Internet serv ers f or it. I ran a
search of all sites using the v ulnerable f orum. You may f ind it hard to
believ e, but there were hundreds of them.
I do not recommend doing any thing similar y ourself . Not all administrators
take it well if their sites are broken into, ev en when this is done with benev
olent intentions. Some of them
Note
Placing Apache into a v irtual root directory, y ou only secure the sy stem; all
sites located in the v irtual directory remain v ulnerable. To protect Web sites,
y ou hav e to look to other way s — f or example, by regulating access rights,
running sev eral instances of the Apache Web serv er (each in its own v irtual
root directory ), running dedicated serv ers f or indiv idual sites, or
prohibiting insecure PHP f unctions f rom executing.
It is dif f icult and sometimes simply impossible to pick the most ef f ectiv e
way to protect multiple v irtual serv ers. For example, one site requires a PHP
interpreter, while another requires Perl. You hav e no choice and must allow
both languages.
Based on personal experience, I can suggest using indiv idual phy sical serv
ers to separate sites according to their requirements, such as the f ollowing:
Ev en though the security of a Web serv er depends largely on the scripts run
on it and the programmers who write these scripts, a serv er can be protected
independently of these f actors. An excellent solution to this problem is a f
ree Apache module calledmod_security.
The rules specif y what a request may and may not contain. A request usually
contains the URL, f rom which a document or f ile must be obtained. How
can rules f or the module be specif ied to enhance the sy stem's security ?
Consider a simple example: Unauthorized access to the /etc/passwd f ile
endangers the serv er's security ; consequently, there should be no ref erences
to it in the URL string.
Based on this rule, the module checks the URL string. If it does not comply
with the rule, the request is rejected.
Themod_securitymodule can be downloaded f rom the
www.modsecurity.org site. Installing the module allows new request-f
iltering directiv es to be specif ied in the httpd.conf f ile. The most interesting
of them are the f ollowing:
SecAuditLog logs/audit_log— Specif ies the log f ile, in which the audit inf
ormation is to be stored.
SecFilterDefaultAction "deny,log,status:406"— Specif ies the def ault action.
In this case, it is prohibition.
SecFilter "insert [[: space: ]] +into" — Prohibits the string used in SQL
queries f or adding data.
The preceding are the main methods that can be used to enhance the security
of y our Web serv er. Serv er networks can also be protected in this way.
Additional inf ormation can be obtained f rom the dev eloper's Web site.
No matter how caref ully scripts may be written and how well they are
protected by special modules: Undertaking additional security measures will
nev er hurt. There are sev eral more techniques that can be used toward this
goal. In this section, I hav e collected v arious recommendations that can help
y ou enhance serv er security.
Script Restriction
First, restrict script execution to an indiv idual directory. In most cases, this
will be the cgi-bin directory : I saw a sy stem once, in which the root
directory was specif ied f or this purpose, meaning scripts could be executed f
rom any directory. Don't repeat this mistake, because there are many dif f
erent Perl programs in the sy stem but they should not be allowed to execute
on the Web serv er.
Backup Copies
Nev er store backup copies of scripts in directories accessible to Web serv
ers. Consider an example. If a Web page contains PHP scripts, users do not
see them in the browser; they only see the results of their execution on the
serv er. To v iew the source code, some sort of access to the serv er is
necessary, f or example, through FTP or Telnet, because Apache does not
send this sort of data to clients.
Programmers like to sav e backup copies of scripts bef ore modif y ing them,
so that if something goes wrong, the old, working v ersion of the script could
be restored. Of ten they sav e these copies in the same directory as the
working script, only with a dif f erent extension. For example, old and bak
are the two used most f requently.
Because the serv er does not execute these f iles, if a f ile is requested, the
source code will be display ed in the browser. We all know that hav ing
access to the source code makes f inding v ulnerabilities in a program much
easier.
When a hacker is exploring scripts on the serv er, there is nothing to keep
him or her f rom checking whether there are backup copies of them. If a
hacker sees that there is a f ile named www.serv ername.com/index.php on
the serv er, he or she will try to load f iles www.serv ername.com/index.bak
or www.werv ername.com/index.old. Such copies of working script f iles are
of ten encountered on amateur sites. Learn f rom other people's mistakes and
don't do this on y our serv er.
Any security specialist should prohibit users f rom accessing backup copies.
No matter how of ten programmers are told not to keep on the serv er any
thing unnecessary, such as backup copies, they will continue doing this
because they f ind this conv enient. Your task is to store these copies saf ely
— that is, to f orbid Web clients to access them.
This can be done with the help of the f ollowing directiv es: <FilesMatch
"\.bak$">
Order deny, allow
Deny from all
</FilesMatch>
</FilesMatch>
The problem lies not only in the words with numerous meanings. There are
many commonly -used expressions that are dif f icult to apply when
conducting a search. These f actors f orced search sy stems to dev elop better
search algorithms, and now a search can be requested based on a combination
of v arious parameters. One of the today 's most powerf ul search sy stems is
Google (www.google.com). It of f ers many options to make the search more
precise. Unf ortunately, most users hav e not mastered these options, but
hackers hav e and use them f or nef arious purposes.
One of the simplest way s to use a search sy stem f or breaking into a serv er
is to use it to f ind a closed Web page. Some sites hav e areas that can be
accessed only through a password. Such sites include paid resources, f or
which the protection is based only on checking the password when entering
the sy stem; indiv idual pages are not protected, and SSL is not used. In this
case, Google can index the pages on closed sites and they can be v iewed
through the search sy stem. You just need to hav e an exact idea what inf
ormation is stored in the f ile, and to compose the search criteria as precisely
as possible.
Consider how indexing of Web pages that are not supposed to be open to
public can be disallowed. For this, y ou hav e to understand what search sy
stems index. The answer is simple: They index ev ery thing they come across
— texts, names, picture names, documents in v arious f ormats (PDF, XLS,
DOC, etc.), and so on.
Your task is to limit the search robots' doggedness so that they do not index
the stuf f y ou don't want them to. This is done by sending the robot a certain
signal. How is this done? The solution is simple y et elegant: A f ile named
robots.txt containing rules f or search robots to f ollow is placed in the site's
root.
Suppose that a robot is about to index the www.your_name.com site. Bef ore
it starts doing this, the robot will try to load the
www.y our_name.com/robots.txt f ile. If it succeeds, it will index the site f
ollowing the rules described in the f ile; otherwise, the contents of the entire
site will be indexed.
The f ormat of the f ile is simple: It uses only two directiv es. These are the f
ollowing:
User-Agent: parameter — The v alue of parameteris the name of the search
sy stem cov ered by the prohibition. There can be more that one such entry in
the f ile, each describing an indiv idual search sy stem. If the prohibitions
apply to all search sy stems, the v alue of parameteris set to *.
The f ollowing is an example of the robots.txt f ile that prohibits all search
robots f rom indexing pages located at the URLs
www.your_name.com/admin and www.your_name.com/cgi_bin: User-
Agent: *
Disallow: /cgi-bin/
Disallow: /admin/
The prohibitions set by the preceding rules also apply to subdirectories in the
specif ied directories. Thus, f iles located at
www.your_name.com/cgi_bin/forum will not be indexed. The f ollowing
example prohibits the site f rom being indexed:
User-Agent: *
Disallow: /
If y our site contains a directory with conf idential data, y ou should disallow
it to be indexed. But y ou should not become carried away and prohibit
indexing altogether; this will prev ent it f rom being included in searches and
y ou stand to lose potential v isitors. According to statistics, the number of v
isitors directed to sites by search engines is greater than the number of v
isitors coming f rom elsewhere.
What conf idential data can the hacker intercept when the client is v iewing
Web pages? Passwords, credit card numbers, bank accounts, and other
sensitiv e inf ormation that people enter on Web f orms ev ery day, mostly
without ev en thinking that it may f all into the wrong hands or can be
intercepted. The most dif f icult thing here is to organize f or the client to
connect not to the real Web serv er requested but to the hacker's computer.
Although people enter the addresses of the sites they want to v isit as sy
mbolic names, the actual connection is carried out using IP addresses. The
task of mapping sy mbolic names to the corresponding IP address is perf
ormed by DNS serv ers. It is possible to f ool the client with a f ake DNS
answer or a f ake DNS serv er, thereby redirecting the traf f ic to the hacker's
computer.
Af terwards, the computer in the middle will f orward requests f rom the
client to the real Web serv er and likewise return its answers to the client
(Fig. 7.3). In this way, all traf f ic will pass through the hacker's computer.
But this method is a thing of the past; now it is of little use because of the
protection against intercepts prov ided by HTTPS and an SSL connection.
Simply f orwarding encry pted data between the client and the serv er does
the hacker no good. The only way to decry pt the traf f ic is to use the f
ollowing technique:
1. The hacker generates a key pair and a certif icate on his or her computer.
2. The client connects to the hacker's computer and exchanges key s with it.
3. The data sent by the client are encry pted with the key supplied by the
hacker, so he or she has no problems decry pting them.
4. The hacker's computer connects to the Web serv er and obtains its public
key.
With this arrangement, the client receiv es a key that was generated by the
hacker and has no required signature. This means that a message will be
display ed on the client's computer inf orming the client that the connection is
to be established without a signed certif icate. This is the moment most users
commit a grav e security lapse: Hav ing been working on the Internet f or a
long time, they hav e tired of pay ing close attention to v arious warning
messages, so they just automatically click the OK button to continue
working, thus accepting an unsigned certif icate.
Users must remember that unless they connect to a site using a secure
connection, it is not a good idea to prov ide credit card numbers to this site.
The browser should display this warning in big red f lashing letters when
connecting to a serv er without a signed certif icate.
For me, an email client has become the main program I use f or
corresponding with my readers, f riends, coworkers, and so on. The people I
work with on bookliv e in dif f erent towns and ev en dif f erent countries.
My closest partners are more than 600 miles away, and the publishing house
of f ice is 1,000 miles away. I don't know how I would be able to handle this
arrangement without email, but with it I can liv e in the south and work f or a
company located in the north.
How does email operate? The f ollowing are the main stages of sending an
email:
1. A user creates a message using an email client (an email program), specif
ies the addressee, and sends the message to an email serv er. Most of ten,
SMTP serv ers are used f or sending email.
2. Af ter receiv ing the message, the serv er determines its destination. The
email address consists of two parts div ided by the at (@) character: the user
name and the serv er name, f or example,
[email protected]. The IP address of the servername.com serv
er is established using DNS.
3. The source mail serv er sends the message to the serv er, on which the
recipient is registered.
4. Af ter receiv ing the message, the servername.com serv er places it into
the username user's mailbox.
5. The addressee checks his or her mailbox using a mail client and can
download message.
The process just described is similar to how the traditional mail operates. The
serv ers play the role of post of f ices, which sort the mail by its destination
addresses, send it to the addressees, and f inally deliv er it to their mailboxes.
As was mentioned, f or transf erring messages, mail serv ers use SMTP,
which was dev eloped at the dawn of the Internet. It has long been considered
as lacking f unctionalities, but it is still used extensiv ely.
Sev eral decades ago, the UNIX-to-UNIX Copy Protocol (UUCP) was
employ ed f or working with mail. But it was tied to the specif ic operating sy
stem, and its f unctionalities were limited; theref ore, it did not become
commonly used and is rarely employ ed today.
There exist three protocols f or receiv ing mail. These are the f ollowing: Post
Of f ice Protocol v ersion 3 (POP3) — This is the most commonly used
protocol f or receiv ing mail today.
Internet Message Access Protocol v ersion 4 (IMAP4) — The capabilities of
this protocol are greater than those of POP3.
The most commonly used Linux mail package is an old sendmail program.
The program possesses great capabilities but is rather dif f icult to use.
Because it was dev eloped so long ago, the sendmail serv er has UUCP
capabilities, which are not that common nowaday s.
All settings in the sendmail.cf conf iguration f ile are grouped into sections. A
section is preceded by a header that looks like the f ollowing:
##################
# local info #
##################
These comments indicate that thelocal infosection f ollows them. Some of the
sections are the f ollowing:
Local inf o — Contains local inf ormation and the main inf ormation about
the serv er and domain
Format of headers
To make conf iguring sendmail easier, the latest v ersions of this serv ice use
a new conf iguration f ile: /etc/mail/sendmail.mc. Listing 8.1 shows an
example of this f ile's contents. Listing 8.1: A fragment of the
/etc/mail/sendmail.mc file
divert (-1)
dnl # This is the sendmail macro config file. If you make changes dnl # to
this file, you need the sendmail-cf rpm installed and then dnl # have to
generate a new /etc/sendmail.cf by running the dnl # following command:
dnl #
dnl # m4 /etc/mail/sendmail.mc > /etc/sendmail.cf dnl #
include('/usr/share/sendmail-cf/m4/cf.m4')
VERSIONID('linux setup for ASPLinux')dn1
OSTYPE('linux')
dnl # Uncomment and edit the following line if your mail needs to be dnl #
sent out through an external mail server:
dnl define('SMART_HOST','smtp.your.provider')
define('confDEF_USER_ID',"8:12")dnl
undefine('UUCP_RELAY')dnl
undefine('BITNET_RELAY')dnl
...
...
The f ormat of the sendmail.mc f ile is simpler than that of the old
sendmail.cf f ile, which reduces the chances of making a conf iguration error.
Af ter editing the sendmail.mc f ile, it has to be conv erted into the CF f
ormat with a special command to turn it into the sendmail.cf f ile.
In Chapter 2, I mentioned that Linux may hang at boot when starting the
sendmail serv ice. This happens because the mail serv er cannot determine
the name of y our computer. Open the /etc/hosts f ile. In most cases, there
will be only one entry in it:
127.0.0.1 localhost.localdomain localhost
This f ile is described in more detail in Chapter 11, where DNS is considered.
For now, it will suf f ice to know that this entry maps IP address 127.0.0.1 to
the localhostcomputer name. In any sy stem, these address and name indicate
the local machine. When the localhostname is specif ied in network
applications, this name is conv erted to IP address 127.0.0.1.
The sendmail program uses the name of the computer specif ied when Linux
was installed as the local machine name. If y ou hav e f orgotten what this
name is, y ou can use the hostnamecommand to ref resh y our memory. My
machine is named Flenov M. Because sendmail cannot determine the IP
address of the machine named Flenov M, it hangs the sy stem. The problem
can be f ixed by adding the f ollowing entry to the /etc/hosts f ile:
192.168.77.1 FlenovM FlenovM
Replace Flenov M with the name of y our computer and specif y its IP
address. Now, sendmail can be placed into the start-up and it will work
without a hitch ev en using def ault settings.
Each new user is automatically created a mailbox with the same name as the
user name. Mailbox f iles f or all users are stored in the /v ar/spool/mail
directory. Thus, the mailbox f or the root user is located in the
/v ar/spool/mail/root f ile.
For working with mail, y ou need a mail client to send and receiv e messages
to and f rom the serv er. There is a host of such programs; some Linux
distributions of f er up to sev en clients. Which one y ou choose is up to y ou
and y our pref erences.
You can do without a mail client and connect to the serv er directly using the
Telnet serv ice, especially because Telnet commands are quite simple and
easy to use. When using Telnet, mail is sent using port 25 (the SMTP port)
and receiv ed at port 110 (the POP3 port).
The program does not know y et, with which mailbox y ou want to work; y
ou will hav e to conf igure it. Execute the Settings/Configure KMail menu
sequence. This will open the conf iguration dialog window. Select the
Network
section; this will open the Setup for Sending and Receiving Messages
window in the right part of the conf iguration window with two tabs on it:
Sending and Receiving (Fig. 8.2).
On the Sending tab, y ou hav e to specif y the parameters of the sending serv
er. By def ault, the local sendmail is already conf igured, but what if the mail
serv er is located on another computer? Delete the existing account (select it
and click the Remove button) and then create new one.
Click the Add button to add a new account. This will open the protocol
selection dialog window, of f ering a choice of two protocols: SMTP and
sendmail. Select SMTP, because it is more univ ersal, and click the OK
button. This will open the Add Transport window. in which y ou will set the
parameters of the SMTP serv er (Fig. 8.3).
Figure 8.3: The SMTP serv er conf iguration window
Host — The SMTP serv er address. If the local serv er is used, local host or
127.0.0.1 can be specif ied.
Port — The SMTP serv er port. Most of ten, port 25 is used, but a dif f erent
port can be used.
If the serv er requires authentication, check the Server requires
authentication box and f ill in the Login and Password f ields that open. If y
ou hav e worked with email bef ore, creating SMTP serv er parameters
should giv e y ou no problems.
Next, the receiv ing part of the serv er has to be conf igured. Open the
Receiving tab; y ou will see a list of serv ers on it. Select all existing
accounts and delete them. Click the Add button to add a receiv ing serv er.
This will open a window, in which y ou hav e to specif y one of the f
ollowing the serv er ty pes: Local mailbox, POP3, IMAP, or Maildir
Mailbox. Most of ten, the POP3 serv er is used; the process f or creating it is
similar to that of the SMTP serv er. You also hav e to specif y the serv er
address, the port (port 110 by def ault), and a login and password.
For this, create a new account so that y ou can read security messages in a
conv enient f ormat. Click the Add button to open the serv er ty pe selection
window. Select the Local mailbox option and click the OK button. This will
open the Add account dialog window shown in Fig. 8.4.
Figure 8.4: The Local mailbox conf
iguration window
The f ollowing f ields hav e to be f illed in this window.
Name — An account name. This can be any name y ou choose.
Location — The mailbox location. By def ault, all mailboxes are stored in
the /v ar/spool/mail/name directory, where name is a user name. The
administrator's mailbox will be /v ar/spool/mail/root.
The rest of the parameters are most of ten set by def ault, unless the
administrator messed up the conf iguration.
Try to read mail using dif f erent protocols. Make sure that messages come
into y our mailbox and reach the recipient. Ev ery thing should be working all
right ev en with the def ault settings. Later, some specif ic settings will be
considered to make y our mail serv er more secure; bef ore making any
improv ements, howev er, y ou hav e to ensure that the basic v ersion is
working as intended.
Pretty Good Priv acy (PGP) — This encry ption program is used in many
areas, including encry pting mail messages. Numerous mail clients support
this standard. There are sev eral PGP v ersions, but many specialists
recommend using the GNU Priv acy Guard (GnuPG) program. No, this v
ersion is not any better than the rest, because all of them are based on the
same principle. What is good about this v ersion is that it was dev eloped bey
ond U.S. borders and, thus, out of reach of its key length-limiting laws. But
with any of these techniques, only messages are encry pted. The protocol
itself does not use encry ption, so all passwords are sent ov er the network in
plaintext and hav e to be protected. This can be done by using one of the
modern standards, such as RFC 1734 (MD5 APOP
Challenge/Response) or RFC 2095 (MD5 CRAM-HMAC
Challenge/Response), or by resorting to the stunnelutility.
hoststat — Shows the status of the hosts that worked with the local mail serv
er recently. The command is an equiv alent of the sendmail -bhcommand,
which is inactiv e by def ault.
mailq — Display s short inf ormation about messages waiting in the queue to
be processed. The f ollowing is an example of the command's execution
results:
/var/spool/mqueue (1 request)
----Q-ID---- --Size-- ----- Q-Time----- -----Sender/Recipient ----
jOIAnSTl1838 6 Tue Jan 18 13:49 <[email protected]>
The f irst line tells y ou that there is one message in the queue. The second
line (that is, the f irst line below the header) display s the date the message
was sent(Tue Jan 18 13:49)and the sender's address
([email protected]). The last line shows the message's
recipient:[email protected].
sendmail — This is the sendmail serv er command. When run with dif f erent
options, it can prov ide v arious ty pes of usef ul inf ormation. Consult
itsmanpage f or more inf ormation.
In this section, I will describe some parameters that can be conf igured to
enhance the serv ice's security.
Security problems start at the connection stage. Like most other serv ices, the
sendmail serv ice display s a greeting message containing the program name
and v ersion.
This inf ormation should be made unav ailable to hackers. This is achiev ed
by changing theSmtpGreetingMessageparameter in the /etc/sendmail.cf f ile.
In older sendmail v ersions, the v alue of this parameter was the f ollowing:
SmtpGreetingMessage=$j Sendmail $v/$Z; $b
The most dangerous element here is the $v/$Zoption, which display s the
program name and v ersion. Theref ore, it was remov ed in more recent v
ersions. Now the parameter is set to the f ollowing v alue:
SmtpGreetingMessage=$j $b
Any successf ul attempt to conf use hackers stalls them and giv es y ou a
small v ictory.
Mail serv ers of ten are used only to send mail. For example, Web serv ers
can hav e sendmail installed only so that mail could be send f rom Perl or
PHP scripts. If receiv ing mail is not a part of y our serv er's mission, this
mode should be disabled. This can be done by modif y ing the contents of the
/etc/sy sconf ig/sendmail f ile as f ollows:
DAEMON = yes
QUEUE = "qlh"
The second directiv e sets the parameters that will be passed to sendmail
when it is started. To allow y our serv er to receiv e mail, change the v alue of
theQUEUEparameter to-bd.
No operating-sy stem serv ice should be allowed to work with root priv
ileges. Should a v ulnerability be f ound in the program's code that allows
command execution, the sy stem can be considered already compromised,
because commands will be executed as root.
The serv ice should work with the priv ileges of a user that has access only to
the directories and f iles necessary f or the serv ice's operation. In the most
recent sendmail v ersions, this can be implemented with the help of the
RunAsUserparameter as f ollows:
0 RunAsUser = sendmail
By def ault, this entry may be commented out. If it is, remov e the comments.
You can also implicitly specif y the group with whose rights the program is
to run:
0 RunAsUser = sendmail:mail
The mail serv er can process a great number of commands, but not all of
them are usef ul. Make sure that the f ollowing entries are in y our conf
iguration f ile and that they are not commented out:
O Privacyoptions = authwarnings
O PrivacyOptions = noexpn
O PrivacyOptions = novrfy
All of these options can also be listed, delimited by commas, in one line as f
ollows:
O PrivacyOptions = authwarnings, noexpn, novrfy
The most dangerous element f or the serv er may turn out to be the vrfy
option, which is used to check whether a mailbox exists. The third directiv e
in the example disables this option.
The mail serv ice has one serious problem: It has to execute sy stem
commands, which is alway s f raught with danger. If a hacker can run such a
program with extended priv ileges, great harm can be done to the sy stem.
This is why I recommend lowering the serv ice's rights, but this alone is not
suf f icient.
Here, in parentheses, the f ollowing two parameters are specif ied: the name
of the command interpreter and the directory, in which it is located. Make
sure that this is where the command interpreter is located in y our sy stem;
otherwise, change the path.
The sendmail serv ice allows a list of users to be created that are trusted to
send messages without warnings. This list is sav ed in the
/etc/mail/trustedusers f ile. I do not recommend entering real users into this
list.
But the f ile can be usef ul under certain circumstances. You can add the
Apache user to it to allow letters to be sent f rom Web scripts.
8.4.7. DoS Attacks
Mail serv ers are of ten subjected to DoS attacks because they hav e to accept
connections f rom any users to serv ice the mailboxes. Consequently, ports 25
and 110 are, most of ten, publicly av ailable.
The sendmail serv ice can be made more secure against DoS attacks by
properly setting the f ollowing parameters:
At f irst, it may seem that this attack is easy to protect against: All y ou hav e
to do is increase the mailbox size or remov e the size limit. But this is the
worst thing that could be done: With a limited mailbox size, a successf ul
mail bomb attack will take out only one mailbox. With an unlimited mailbox
size, a successf ul DoS attack can be carried out against the entire serv er.
Mail messages are the only way f or an unauthorized person to upload inf
ormation onto a serv er. When an email message is receiv ed at a serv er, it is
stored on the serv er's hard driv e until it is downloaded by the user when the
mail is checked. Sending a constant f low of messages to a mailbox of
unlimited size will f ill the entire hard driv e, and the serv er will no longer be
able to receiv e messages into any of its mailboxes.
The worst situation that can be caused by mail bombing is when mailboxes
are located in the def ault directory, which is /v ar. If this directory is f illed,
the serv er will no longer be able to write serv ice inf ormation to it. The /v ar
directory is also used to store security logs. If these logs cannot be updated,
the serv er will become inaccessible.
Thus, the mailbox disk space must be limited. It is pref erable to lose one or
ev en a f ew mailboxes than to lose the entire serv er.
There is no f oolproof def ense against mail bombing. You can, howev er,
make it more dif f icult f or the perpetrator to carry it out. This can be done
with the help of the parameters considered inSection 8.4.7. Moreov er, the
maximum size of a single message that can be receiv ed to a mailbox can be
limited to a reasonable size using the MaxMessageSizeparameter. This will
make the miscreants' job more dif f icult because they will hav e to send
many small messages instead of one large message.
8.6. Spam
The scourge of the Inf ormation Age is unsolicited mail, or spam. Spam
makes up a large part of email traf f ic, and the existing techniques of f
ighting it do not alway s produce the results desired.
Thus, one of way s to f ight unwanted mail is to prohibit incoming mail f rom
serv ers f ound guilty of sourcing spam messages. But spammers keep f
inding new way s to get around the prohibitions, including using public or
zombied serv ers.
If y our serv er has been zombied and is used to send spam, this exposes y ou
to the f ollowing dangers:
Extra traf f ic expenses if y ou pay by v olume
Extra processor workload because spam mailings are usually carried out on a
mass scale and consume a lot of the processor time, thereby loading the
communication link
Moreov er, y our serv er may be entered on a spam blacklist, resulting in all y
our outgoing correspondence being f iltered out and not reaching the
recipients. The latter can be v iewed as a successf ul DoS attack against y our
mail serv ice.
There are many more way s to f ight spam than those described here. But
those described are suf f icient f or y ou to start taking steps against electronic
junk mail.
Filtering Servers
The sendmail program has an option to f ilter out serv ers, f rom which the
spam is receiv ed. The best way of doing this is to add a prohibiting directiv e
to the sendmail.mc f ile. The problem is, howev er, that this directiv e has a
dif f erent f ormat f or dif f erent sendmail v ersions.
Once, my sof tware sales serv er was placed on a spam list. Those were the
times when a serv er could become blacklisted deserv edly or f or no reason.
When I would mail the registration key s to the people who bought my sof
tware, about 10% of the messages would be returned marked as spam. This
kept some of my customers f rom using the sof tware they bought. This went
on f or a month until spam blacklists were judged to be inef f ectiv e.
Filtering Messages
More precise f iltering inv olv es blocking messages by their contents. A
special program analy zes all inf ormation passing through the serv er and
looks f or ty pical signs of spam mailings. If a message is judged to be spam,
it is deleted.
This method is the most ef f ectiv e; howev er, it is dif f icult to tell by the
text of a letter whether it is spam. Hackers are constantly looking f or new
way s to circumv ent such f ilters, so the percentage of f iltered out spam is
not high. The program can be conf igured to delete all messages, in which
"buy," "sell," and other words ty pical f or spam occur. Howev er, there is a
chance that this f ilter will delete some of y our good mail.
When conf iguring y our mail serv er, y ou should make it unav ailable to be
used by hackers f or mailing spam. The f ollowing conf iguration settings will
make using y our serv er f or mass mailings inef f ectiv e:
By def ault, SMTP does not require authorization, so any user can connect to
the serv er and send mail. This can be prev ented by doing one of the f
ollowing:
Conf igure the f irewall to prohibit f rom connecting to the SMTP port those
users who do not belong to y our network. This def ense is used most of ten
by prov iders and administrators of priv ate and corporate networks. You
should hav e no problems implementing this method, because I hav e
considered it sev eral times in this book.
Allow mail to be sent only within a certain period (e.g., 10 minutes) af ter
receiv ing mail by POP3. This allows the serv er to authorize the client when
the mail is checked and to use the obtained authorization data f or creating a f
irewall or some other permission to access SMTP. When this permission is
activ e, mail can be sent f rom the authorized IP address.
Use SMTP authorization. The original mailsending protocol did not contain
the userauthentication requirement, so not all serv ers support this f eature.
But sendmail and other powerf ul mail programs of f er an SMTP
userauthentication f eature.
You can place the f ollowing directiv es into this f ile to allow mailings only f
rom the local network computer or f rom the serv er:
localhost RELAY
your_domain.com RELAY
This method is ef f ectiv e only when the integrity of the local network's
computers and serv ers has not been compromised. But if hackers obtain
access to the network, they can mail any sort of spam f rom user accounts.
This is something that cannot be av oided. If there is at least some sort of
permission, hackers can take adv antage of it, so y our task is to make it dif f
icult f or them.
The POP3 authorization method, howev er, has one signif icant shortcoming:
If there is an anony mous proxy serv er or a masking f irewall in the route, v
ia which the letters arriv e, packets will arriv e with a dif f erent IP address.
This means that all users connected using the same proxy or f irewall are
automatically considered authorized. Consequently, a search in the log by the
IP address will not prov ide 100% protection.
The most pref erable is the SMTP authorization method (SMTP AUTH),
described in RFC 2554. The sendmail serv ice supports this extension starting
with v ersion 8.10.
If y ou decide to use SMTP AUTH, make sure that the user's mail clients are
conf igured to authenticate at the serv er.
8.7. Conclusion
I considered only the skin-deep workings of email, because conf iguring
sendmail requires a book of its own. More detailed sendmail conf iguration
inf ormation can be f ound in the documentation supplied with the operating
sy stem located in the /usr/share/sendmail-cf directory. Also, running a search
f or "conf iguring sendmail" in any Internet search sy stem will produce a
huge list of hits on this subject.
If this is still not enough, y ou can buy a book on the subject, f or example,
Sendmailby Bry an Costales and Eric Allman, published by O'Reilly Media.
If y ou are just beginning to work with the sendmail serv ice, I recommend
that y ou start with the def ault conf iguration settings and proceed f rom
there.
But it's a dangerous world out there on the Internet. You can run into all
kinds of people and learn that lif e is not a bowl of cherries. Along with law-
abiding Internet denizens, ev il hackers lurk online.
You hav e to learn to protect y our computer f rom them. When y ou build an
of f ice or some other building, y ou make its walls strong enough to resist
attempts to break through. The doors must keep dishonest people out. Finally,
y ou equip the f inished building with an alarm sy stem.
You hav e already built y our computer walls and taken care to make them
strong by securing y our local network. Now y ou hav e to install doors to
enter the network f rom the outside: the Internet. The door to the World Wide
Web in a computer building will play the roles of gateway and proxy serv er.
These are what will be considered in this chapter. In addition to conf iguring
the serv er, the client has to be conf igured.
Af ter making sure that the doors are up to snuf f , y ou will install the alarm
sy stem: utilities to monitor network traf f ic activ ities and to detect
unauthorized activ ities at the doors and in the building. These will be
considered in Chapter 12.
Af ter connecting to the Internet, ascertain that a DNS serv er (which maps sy
mbolic Internet site names to their corresponding IP addresses) is av ailable.
This can be done by pinging some Web site, like this: ping www.redhat.com
A proxy serv er solv es this problem by storing (caching) a Web page on the
local disk the f irst time it was accessed. The next time a local user asks to
access this page, instead of requesting it f rom the remote serv er, the local
serv er serv es it f rom the local disk cache. The economy is obv ious. With
time, these f eatures hav e been enhanced and currently of f er the f ollowing
f unctions:
Caching documents receiv ed f rom the network Caching the results of DNS
requests Organizing a network access gateway
Controlling Internet access Prov iding anony mous Internet access by hiding
addresses
Reducing IP address use
In this chapter, the most popular Linux proxy serv er — squid — will be
considered.
To reduce the bandwidth traf f ic and to increase the loading speed, a special
program is installed on the serv er that prov ides access to the Internet (Fig.
9.1). When a page, f or example, www.yahoo.com, is loaded on one of the
local network's computers f or the f irst time, all of its contents are sav ed in
the proxy 's cache. The next time the same page is requested f rom the local
network, the images it contains are loaded not f rom the Internet but f rom the
prov ider's proxy serv er, and the text (depending on the contents of the page
and the changes to it) may be loaded f rom the source serv er.
As a rule, the graphical contents of a page take up most of its v olume. The
text part of a page does not usually exceed 15 KB, but the graphical part can
be 100 KB and more. Loading the latter inf ormation f rom the local proxy
serv er makes it possible to reduce the bandwidth load and increase the
pageloading speed.
The loading speed is increased because the proxy serv er is sending most of
the Web page data (all graphics and the unmodif ied text) at the local network
rate, which currently is 100 Mb/sec on ev en the cheapest network
equipment. The dial-up Internet connection speed is much lower, ranging f
rom 2 to 8 Mb/sec. At this rate, only text data that do not change are loaded
(most of ten, HTML f ile contents).
In addition to caching Web pages, a proxy serv er can cache results of DNS
requests. This can also hav e a positiv e ef f ect on the productiv ity.
Although humans pref er to use sy mbolic Web page names, computers conv
ert them to the corresponding numerical IP addresses. Thus, bef ore a page
can be loaded, some time is taken f or conv erting the sy mbolic address to its
IP f orm. Howev er, if the site being accessed has already been accessed, its
IP address will be sav ed in the proxy 's cache. So instead of going to a DNS
serv er f or the IP address, the proxy will take it f rom its cache. The DNS
subject is discussed in more detail inChapter 11.
As the World Wide Web has been dev eloping and the requirements of its
users hav e been increasing, capabilities of proxy serv ers hav e also been
growing. Now, a proxy serv er can perf orm gateway f unctions and prov ide
Internet access without additional sof tware or equipment. Moreov er, it serv
es as a shield guarding the network against inv asions f rom the outside.
When any of the proxy clients sends a Web page request to the Internet, the
proxy serv er hides the client's IP address and sends the packets on its own
behalf . This means that hackers can see only the address of the proxy serv er
and will attempt to break into it and not into the computers it serv ices. This
makes it much easier to organize def ense against outside attacks, because y
ou can giv e more attention to one computer, that is, the proxy serv er, instead
of spreading it among all client computers. Howev er, the protection
capabilities of proxy serv ers are too basic and are easily circumv ented, so
they should be supplemented by a good f irewall and an eagle-ey ed
administrator.
There are two ty pes of proxy serv ers: transparent and anony mous.
Transparent proxies simply f orward a client's packets to the requested Web
serv er without changing the sender's address. A proxy that conceals the
sender's IP address is called anony mous. This serv er communicates with the
external world on behalf of clients under its own name. This f eature is of ten
taken adv antage of by miscreants. For example, hackers do their break-ins
through anony mous proxy serv ers so that the owners of the burglarized
machines will not be able to determine, f rom which address the break-in was
perpetrated.
Today, there are many serv ers on the Internet claiming to of f er anony mous
proxy serv ices, but not all them actually do. Some of them make the request
source IP av ailable to the sy stem, to which the request is directed; others log
all traf f ic activ ities, including IP addresses, with the logs av ailable to law-
enf orcement agencies. Consequently, y ou can nev er be sure that the serv er
is as anony mous as it claims to be.
Because not all of a network's computers are allowed Internet access, user
authentication can carried out on the proxy serv er lev el.
Some proxy v ersions hav e a handy f eature: They can exchange their cache
data. For example, sev eral of f ices may share one local network, but each of
them has separate Internet access through its own proxy serv er to keep the
Internet bills separate. The indiv idual proxies can be combined into a sort of
a proxy network so that if one of them does not hav e the inf ormation
requested in its cache, it will check the caches of the other proxies f or it.
Using cache sharing does not lead to a signif icant loading-speed increase
when requesting small documents, because it takes extra time to search f or
the documents in the shared caches. With a large request load on the serv ers
and a sizable cache base, the search time may ev en be so long that it
eliminates any speed load adv antages. It still leav es the bandwidth economy
f actor, which may be important f or those who hav e to watch each megaby
te of traf f ic.
Not all proxy serv ers will hav e the main f eatures just considered. It all
depends on what purposes a particular proxy was dev eloped f or, and some
of them are intended to address only one task.
To work through a proxy serv er, y ou hav e to properly conf igure the
program y ou want to use the proxy with. Consider the Mozilla browser as an
example. Launch the browser and select the Edit/Preferences menu
sequence. A tree of categories that can be conf igured is located in a pane on
the lef t in the Preferences dialog window. Select the Advanced/Proxies
category sequence to conf igure proxy serv er connections. The def ault is no
proxy : Direct connection to the Internet. You should select the Manual
proxy configuration and specif y the IP address and port of the proxy serv er
f or each protocol (Fig. 9.2).
When conf igured to use a proxy serv er, the browser will send all requests to
the proxy serv er, which will then f orward them to the destination serv er.
The proxy serv er alway s has to be loaded and must listen to the specif ic
port (or sev eral ports f or dif f erent protocols).
To enhance the security of y our network, y ou should conf igure the f irewall
to prohibit incoming connections to the ports used by the squid proxy serv
ice. For example, f or the HTTP proxy port 3128 is used. Prohibiting
incoming connections to this port will prev ent using the proxy serv er f or
purposes other than those it is intended f or, f or example, breaking into the
network.
9.3. Squid
As already mentioned, the most commonly used Linux proxy serv er is squid.
This serv er has been around f or quite a while, and during this time it has
gathered numerous f eatures. There is no task that I could not do using squid.
I will consider the main commands f or controlling the proxy serv er. As
usual, all parameters af f ecting productiv ity and security will be considered
in detail. Other settings will be giv en a cursory look only ; y ou can obtain
detailed inf ormation on them f rom the comments in the conf iguration f ile.
In the http_port ntag, thenparameter specif ies the port number to be used f or
the connection. The f irst things that need conf iguring are the ports, on which
the serv er will track f or connections f rom clients. These directiv es hav e
thexxxx_portf ormat. For an HTTP port, the directiv e looks as f ollows:
http_port 8080
Then y ou hav e to conf igure the browser on the client computer by specif y
ing the IP address of the serv er running squid and the port allocated by this
directiv e.
Consider an example. Suppose that y ou retriev ed a Web page with the URL
www.servername.con/cgi-bin/ping.cgi that allows the ping command to be
executed through the Web interf ace. Assume that the f irst time y ou pinged
address 18.1.1.1. The result will be sav ed in the proxy serv er's cache. The
next time y ou run the script to ping address 18.1.1.18; the browser, howev
er, will return the result of the f irst ping, because it will retriev e it f rom the
cache.
Pages containing scripts return v ary ing results, depending on the situation
and the parameters specif ied by the user. Caching these pages will cause the
browser to alway s return the same result: the one stored in cache. So instead
of conv enience of f ered by using proxy, y ou get a headache.
The question mark is of ten used to pass parameters to PHP scripts; thus,
these pages should not be cached either.
The hierarchy_stoplisttag prohibits y ou f rom retriev ing pages f rom cache.
The f ollowing two entries prohibit caching pages whose URLs contain
thecgi-binstring or a question mark altogether.
acl QUERY urlpath_regex cgi-bin \?
no_cache deny QUERY
I believ e y ou can see that there is no need to cache material that must be
prov ided by the serv er; this would only waste disk space.
There are sev eral tags to control FTP proxy operations. The f ollowing are
some of the main ones:
ftp_passive on | off — Specif ies the operation mode. If set toon,it enables the
passiv e mode. This is the def ault setting.
The squid serv er allows y ou to work with FTP but may require some
additional conf iguring. For example, if squid is located behind a f irewall
that does not allow the passiv e mode, the v alue of this parameter should be
changed tooff: ftp_passive off
ftp_user address — Specif ies the email address to be used as the password
during the authentication procedure on anony mous FTP serv ers.
No serv er can determine whether the email address entered is correct, so this
check can be disabled. Some FTP serv ers, howev er, v erif y whether the
email address is correct. The def ault string isftp_user squid@.
Any FTP serv er will accept this address as correct, because it complies with
all rules f or email addresses.
ftp_list_width n — Thennumber sets the width of the FTP listing. This v alue
should be set to f it the width of a standard browser. Setting it too small may
cut of f long f ile names.
The directory should be located in the largest partition, so that inf ormation
will not be spread ov er sev eral disks. But if all y ou hav e is one disk with
one partition on it, the location makes no dif f erence.
The def ault size of the directory is 100 MB. This is suf f icient to speed up
work f or three users. If there are many users in y our network and they all
hav e dif f erent tastes or jobs (meaning, they v isit dif f erent sites), the size
should be increased. I allocate at least 1 GB of disk space to cache. If the serv
er is allowed to cache large f iles, the allocated space will be f illed in no
time.
ipcache_size n— Specif ies the IP address cache size. The def ault v alue is
1,024 KB.
reference_age parameter — Specif ies objects' lif etime in the cache. Objects
whose lif etime exceeds this v alue can be deleted. The f ollowing are a f ew
examples:
reference_age 1 week
reference_age 3.5 days
reference_age 4 months
reference_age 2.2 hours
quick_abort_pct n — The same situation as with the prev ious two tags, but
only if more than the specif ied v alue has been retriev ed, the retriev al will
be completed.
cache_access_log file — Specif ies the path to the f ile, in which all user activ
ity (namely, HTTP and ICP requests) is logged. The def ault v alue is /v
ar/log/squid/ access.log.
cache_log file — Specif ies the path to the f ile in which general inf ormation
about the cache activ ity is logged. The def ault v alue is /v
ar/log/squid/cache.log.
cache_store_log file — Specif ies the path to the f ile, in which the activ ities
of the store manager are logged. The log shows, which objects are sav ed to
the cache and f or how long, and which are ev icted. The def ault v alue is
/v ar/log/squid/ store.log. Howev er, no utility exists f or analy zing the data
stored in this log. Besides, there is no practical use f or this data; y ou only
waste disk space and sy stem resources to sav e them. So y ou will be better
of f to disable this log by setting thefileparameter v alue tonone.
Linux logs and v arious serv ices are discussed in Section 12.5. InSection
12.5.4, the contents of the squid's main log — /v ar/log/squid/access.log —
are considered.
icp_port n — Specif ies the port number to be used f or ICP. The def ault v
alue is 3130. Setting thenv alue to 0 disables the protocol.
htcp_port n — Specif ies the port number to be used f or ICP working abov e
TCP/IP. The def ault v alue is 4827. Setting the nv alue to 0 disables the
protocol.
sibling — May only request objects already held in the cache. Cannot f
orward cache misses on behalf of a peer.
The option parameter can take on many dif f erent v alues, and considering
them is bey ond the scope of this book. Detailed inf ormation f or each option
v alue can be f ound in the conf iguration f ile comments.
The f ollowing tags I could not place into any specif ic category, but they are
of certain importance and need to be considered:
redirector_access allow | deny — Specif ies the list of processes sent to the
redirector process. By def ault, all requests are sent.
cache_mgr email — Indicates the email address, to which a notif ication will
be sent should there be problems in the squid operation.
The f irst thing to consider is the ACL, which is a powerf ul tool f or conf
iguring site access rights. Using a list of names, actions or users can be
grouped. The tag is issued in the f ollowing f ormat:
acl name type string
type — This parameter can take on the f ollowing v alues: src, dst,
srcdomain, dstdomain, url_pattern, urlpath_pattern, time, port, proto,
proxy_auth, method, browser,oruser.The f unctions of the main ty pes, specif
y ing how to interpret the preceding parameter (decision_string),are as f
ollows:
src— Access is controlled by source IP addresses.
url_regex — This instructs the f unction to search the entire URL f or the
regular expression y ou specif y.
time — This indicates the time in the f ormat day h1:m1 - h2:m2. This string
can be used to restrict access to only specif ied day s of the week and times of
day. The
abbrev iations f or the day s of week are the f ollowing:sf or Sunday,Mf or
Monday,Tf or Tuesday,wf or Wednesday,Hf or Thursday, Ff or Friday,Af or
Saturday.
The conf iguration f ile already contains sev eral lists that are ready to use
and usually do not hav e to be edited. These are shown in Listing 9.1.
Listing 9.1: Default ACL rules in the /etc/squid/squid.conf configuration
file
acl all src 0.0.0.0/0.0.0.0 acl manager proto cache_object acl localhost src
127.0.0.1/255.255.255.255 acl SSL_ports port 443 563 acl Safe_ports port 80
acl Safe_ports port 21
acl Safe_ports port 443 563 acl Safe_ports port 70
acl Safe_ports port 210
acl Safe_ports port 1025-65535 acl Safe_ports port 280
acl Safe_ports port 488
acl Safe_ports port 591
acl Safe_ports port 777
acl CONNECT method CONNECTs # http
# ftp
# https, snews
# gopher
# wais
# unregistered ports # http-mgmt
# gss-http
# filemaker
# multiling http
The f irst entry specif ies an aclnamed all.The srcty pe of decision string
means this list cov ers all users whose IP address matches 0.0.0.0/0.0.0.0, that
is, all users.
The next entry creates an ACL class named manager.It def ines access to the
cache_objectprotocol, as specif ied by the prototy pe and the
cache_objectdecision string. And so on.
Now, try to create y our own ACL class. Suppose y ou hav e to allow access
to the Internet f or ten computers in y our network with addresses f rom
192.168.8.1 to 192.168.8.10 (the subnet mask is 255.255.255.0). Access
should be denied to all other computers in the network
When creating the list, y ou should start by deny ing access to all and then
allowing it only to those who require it. A class f or all users already exists in
the def ault list:acl all src 0.0.0.0/0.0.0.0.A list f or ten computers is named, f
or example,AllowUsers;its decision string is of the srcty pe, the decision
string itself being the range of addresses in question. Here is how it looks:
acl AllowUsers src 192.168.8.1-192.168.8.10/255.255.255.0
By specif y ing access rights f or the AllowUsersACL, all it takes is one line
to allow access f or all computers included in this ACL. This eliminates the
need to specif y rights f or each computer and makes the liv es of
administrators of big networks much easier.
9.4.3. Authentication
Using an IP address to limit access rights does not guarantee that the IP
address cannot be f aked. Moreov er, there alway s exists a possibility that the
wrong people can obtain the phy sical access to the computer allowed access
to the Internet. Once they do, what they do with it is up their good, or ill, will.
Note
Authentication does not work if squid is conf igured to work in the
transparent mode.
Once, sev eral employ ees were noticed to hav e gone ov er their traf f ic limit
signif icantly. This would hav e been no big deal, except these guy s were
away on v acation. Someone was f aking their IP addresses and using their
share of the Internet traf f ic.
The directiv e specif ies the path to the external authentication program and
the path to the password f ile. By def ault, the authenticator program is not
used. The traditional proxy -authentication program can be specif ied by the f
ollowing directiv e:
authenticate_program /usr/lib/squid/ncsa_auth /usr/etc/passwd
When I f irst read squid documentation, I f ound the f ollowing two directiv
es interesting:cache_effective_userandcache_effective_group.If squid is run
as root, the user and group identif iers will be replaced with those specif ied
by these tags. The user and group identif iers are set tosquidby def ault:
cache_effective_user squid
cache_effective_group squid
In this way, squid will not work with the root rights, and when an attempt is
made to make it do so, the serv ice will itself lower its rights to squid. I do
not recommend modif y ing these directiv es. There is no need to giv e the
squid serv ice greater rights, because those f or the cache directory are suf f
icient f or it.
httpd_accel_port port — This sets the port, to which the accelerated requests
are to be f orwarded. Most of ten, this is the def ault port (port 80).
Many statistical sy stems do not take into account or do not allow entry to
users in whose requests theUser Agentf ield is blank. This f ield being blank
indicates that the request was channeled through a proxy.
It could hav e been suspicious, because there is a small f law in this charitable
solution. This is theUser Agentf ield, which was blanked out when requests
passed through my proxy. But there is a solution to this problem: the f ield
can be f illed out manually in the conf iguration f ile by the
fake_user_agentdirectiv e. For example, the f ollowing line emulates requests
coming f rom a Netscape browser:
fake_user_agent Netscrape/1.0 (CP/M; 8-bit)
9.5.4. Network Protection
The squid serv ice is a two-edged sword: it can be used both to protect the
network and to penetrate it. To prev ent outside users f rom using the proxy
serv er to connect to computers in the local network, the f ollowing directiv
es hav e to be added to the conf iguration f ile:
tcp_incoming_address downstream_address
tcp_outgoing_address upstream_address
udp_incoming_address downstream_address
udp_outgoing_address upstream_address
It was already mentioned that most traf f ic f rom any site is graphics. Most
browsers allow the image-v iewing f eature to be disabled; this, howev er,
will make Web surf ing less conv enient. Without graphics, some sites
become less inf ormativ e and more dif f icult to nav igate; thus, it is not
possible to dispense with graphics display altogether.
But there is a ty pe of graphics that irritates and does not carry any usef ul inf
ormation — the graphics we would lov e to, and can, get rid of . I am talking
about banners. Consider how to disable banner display way up on the proxy
serv er lev el. For this, f irst def ine the f ollowing rules in the squid.conf f ile:
acl banners_regex url_regex "/usr/etc/banners_regex"
acl banners_path_regex urlpath_regex "/usr/etc/banners_path_regex" acl
banners_exclusion url_regex "/usr/etc/banners_exclusion"
The f irst entry creates an ACL named banners_regexof theurl_regex ty pe
that allows a complete URL to be searched. The last parameter specif ies the
/usr/etc/banners_regex f ile, in which the URLs of banner sy stems will be
stored.
The third entry creates an ACL of the same ty pe as the f irst one, named
banners_exclusionand linked to the /usr/etc/banners_exclusion f ile. In the f
irst two f iles, descriptions of URLs or templates to be used f or killing
banners will be stored. Sometimes, howev er, y ou may want to v iew a
particular banner. In this case, its URL can be recorded in this f ile and the
banner will be loaded.
Both directiv es do basically the same: They prohibit loading f rom the
addresses specif ied in thebanners_path_regexandbanners_regexlists unless
they are included in thebanners_exclusionlist.
As y ou shsssould remember, this f ile contains template URL paths, and all
addresses that match them will be f iltered out.
The f irst entry describes a template that prohibits loading of addresses of the
f ollowing ty pe:
http://members.tripod.com/adm/popup/popup.html
As y ou can see, it is easy to do away with the popup windosws f rom the
www.tripod.com site. If y ou know how to build regular expressions, y ou
will be able to create a similar list f or any banner sy stem and cut of f the
most sophisticated paths of graphical pests. The subject of regular
expressions is not considered in this book because it is too extensiv e and
requires a book all f or itself
Ev en though in most cases banners and popup windows are irritating pests,
they prov ide some artistic dressing f or pages. Hav ing eliminated them, y ou
may f ind pages dull and unattractiv e. This problem can be allev iated by
replacing remov ed banners and popup windows with y our own images,
which are stored on the local serv er and, thus, do not hav e to be loaded f
rom the Internet.
There is only one little problem with this: Linux has no ready program f or
this task and y ou will hav e to write it y ourself . Any programming language
will do, but I will show an example implemented in Perl. If y ou know how to
program in this language, I am certain y ou will like replacing banners better
than simply killing them using ACLs.
# Specify the URL on your Web server, to which the images # are stored.
$YOURSITE = 'http://yourserver.com/squid';
$LOG = '/usr/etc/redirectlog';
$LAZY_WRITE = 1;
if ($LOG) {
open LOG, ">> $LOG"; unless ($LAZY_WRITE)
{ select LOG ;
$| = 1;
select STDOUT;
}
}
@b468_60 = qw (
www\.sitename\.com/cgi/
# Add descriptions of the 468 x 60 banners' # URLs here.
)
@b100 100= qw (
www\.sitename\.com/cgi/
# Add descriptions of the 100 x 100 banners' # URLs here.
);
@various = qw (
www\.sitename\.com/cgi/
# Add descriptions of non-standard size banners' # URLs here.
);
@popup_window = qw (
^http://members\.tripod\.com/adm/popup/.+html
^http://www\.geocities\.com/ad_container/pop\.html
^http://www\.geocities\.com/toto\?
# Add descriptions of popup windows' URLs here
);
while (<>)
{
($url, $who, $ident, $method) = /^(\S+) (\S+) (\S+) (\S+)$/; $prev = $url;
# An individual site not included in the list at the # beginning of the file
$url = "$YOURSITE/empty.gif" if $url =~ m%hitbox\.com/Hitbox\?%;
$mday, $mon + 1, $year + 1900, $hour, $min, $sec, "$who $prev > $url";
}
print "$url $who $ident $method\n";
}
close LOG if $LOG;
Sav e this program in the /usr/etc/redirector f ile and giv e squid the rights to
execute it. Af terward, add the f ollowing entry to the squid.conf f ile:
redirect_program /usr/local/etc/squid/redirector
For the program to work, y ou will hav e to create the f ollowing f iles on y
our Web serv er:
468_60.gif — A 468 × 60 image. 100_100.gif — A 100 × 100 image.
<html>
<head>
<script language = "JavaScript"> <!-
window.close();
//-->
</script>
</head>
<body>
</body>
</html>
All these f iles should be stored on the Web serv er in one directory. Don't f
orget to specif y the correct path to this directory in the script's$YOURSITE
v ariable.
I tried to explain the most important code areas in Listing 9.2with comments.
If y ou hav e Perl programming experience, y ou will hav e no problems
making it all work.
I had a conv ersation with an acquaintance not long ago, and he of f ered a
def inition of the Internet that I f ound amusing: The World Wide Web was
created f or and liv es by pornography. Although I do not completely agree
with him, I f eel he might be partially right in that the sites with sexy content
are most f requently v isited (if y ou don't take into account the Microsof t
update site, f rom which users download patches f or sof tware f rom this
company ).
No employ ers will be happy if their workers v isit sites with illicit content
during work hours. This produces not only traf f ic waste but also other
expenses unrelated to work. Parents do not want their children to be exposed
to sites like these either, and they striv e to shelter their sensibilities f rom too
many f acts of lif e. I am say ing this as a f ather of two children.
Pornography sites can be easily banned using the same methods as those used
to kill banners. For example, y ou could disallow any site whose URL
contains the word "sex." But this method can produce f alse calls. For
example, an address may contain the "GasExpo" text in it. Because it
contains a letter combination that spells "sex," this site will be barred. This is
a real-lif e example, in which a user was not allowed to load a gas-equipment
exhibition site.
Frequently, when organizing Internet access some users hav e to be prov ided
a high-speed connection. How can this be accomplished if , by def ault, all
users are peers and can access the Internet at the maximum speed av ailable?
You hav e to establish some priorities to achiev e this.
The f irst line — delay_pools n— specif ies that there will bennumber of
delay pools (rules describing access speeds) to use. By def ault, n equals 0;
there is no limit on the number of pools. Because y ou are going to create
three pools,nis set to 3.
1 — The download rates of all connections in the class are added together,
and the aggregate is kept below a giv en maximum v alue. For example, y ou
can limit the download speed f rom all adult entertainment sites (def ined in
adv ance usingacltag) to 32 Kb/sec. If y our Internet connection bandwidth is,
f or example, 256 Kb/sec, no matter how many people try to download hot
stuf f , they will hav e only 32 Kb/sec to share, with the rest of the users
guaranteed the remaining 224 Kb/sec of bandwidth.
In the example, I used delay pools class 1, class 2, and class 1 again. I did it
on purpose to make the example more illustrativ e.
Thus, the f irst directiv e sets the aggregate bandwidth of all connections to
256,000 by tes per second (or 2 Mb/sec). No bandwidth limit is imposed if it
is specif ied as -1.
Af ter the bandwidth limitations f or the f irst pool are specif ied, access
rights to the pool are set by thedelay_accessdirectiv e as f ollows:
delay_access delay_pool allow|deny acl
The f irst parameter is the pool number. This is f ollowed by theaccessor the
denyoption f or the members of the list, giv en as the last parameter(acl).
In the example, access rights to pool 1 are set f or two groups: alland admins:
delay_access 1 deny all
delay_access 1 allow admins
The f irst directiv e bars all users f rom working at the giv en bandwidth, and
the second giv es access to it to only the members of theadminsACL. It is
assumed that only administrators are such members.
Listing 9.4: Limiting speed for loading media during work hours
delay_class 2 2
# The first pool has no restrictions for anyone. delay_parameters 1 -1/-1 -1/-1
delay_access 1 allow fullspeed
I believ e the comments to the code are suf f icient to understand how it f
unctions. The media f ile download speed, howev er, is limited f or all users.
If y ou want to make exceptions f or certain users f rom this restriction, y ou
can create an ACL f or them (named, f or example,allowfull) and add the f
ollowing line at the end of the listing:
delay_access 2 deny !allowfull
Fig. 9.3 shows the dialog window f or conf iguring Mozilla cache. The
Memory Cache parameter is the maximum operating memory allocated to
caching pages. Its def ault v alue is 4,096 KB. Using memory cache speeds
up operations when browsing the same site, because most of its graphical
objects are sav ed in memory and retriev ed f rom there instead of f rom the
hard driv e.
Figure 9.3: Conf iguring Mozilla cache
The Disk Cache parameter sets the size of the disk cache. Usually, its def
ault v alue is set to 50,000 KB (about 50 MB). This amount is too small f or
regular Web surf ing and will be used up quickly. If y our hard driv e allows,
I recommend increasing this v alue. The Disk Cache Folder parameter specif
ies the f older, in which the disk cache is stored.
You can also specif y when a page in the cache should be compared with the
page on the network. The f ollowing f our options are av ailable:
Every time I view the page — Self -explanatory. When the page is out of
date — Ditto. Once per session — Ev ery time the browser is started.
Never — The page will alway s be loaded f rom the local cache; y ou can
reload it by clicking the Reload button on the browser's toolbar.
When working with the Internet using a proxy serv er or local browser
caching, y ou should remember that pages that load can be outdated. To load
the f resh v ersion of the page, click the Reload button.
Ev en now, some computers are equipped with 3.5-inch f loppy driv es,
because no cheaper alternativ e f or transf erring small v olumes of data has
been of f ered y et. But it is dif f icult to imagine an of f ice not equipped with
a f ull-f ledged local network. In some companies, all computers must be
connected to the local network. With computers connected into a local
network, the need to equip them with f loppy disk driv es is no longer there,
and the latter are simply remov ed f rom the machines. If y ou are itching to
ask why, because one nev er knows when a f loppy might come in handy, y
ou hav e f orgotten the main principle of security : There should be nothing
unnecessary. This applies not only to sof tware but also to computer
hardware.
A f loppy disk driv e is a hole, through which inf ormation can be taken of f
the computer without any hacking skills but by simply obtaining the phy sical
access to the machine. I know one company whose local network was
isolated, and they used to think that this made it imperv ious. Despite all this
seeming security, they lost secret trade inf ormation and subsequently their
market. And all because of little pieces of plastic that cannot be detected by
metal detectors. That's right, f loppy disks. Only then were f loppy disk driv
es remov ed f rom all of their computers.
Local networks make it possible to get rid of extra hardware and transf er the
data more rapidly and reliably. All y ou hav e to do is conf igure the
necessary protocols properly and use the network medium to its f ull
capacity. Currently, the most popular f ile exchange protocol is FTP. Ev en
though it was dev eloped some time ago, it is remains widely used. Granted,
some of its capabilities are not quite up to par f or modern requirements.
If y ou urgently need to test the protocol but hav e no FTP client installed, y
ou can use a simple browser f or this, like Internet Explorer or Netscape. This
is done by entering the address in the URL f ield in this f ormat:
FTP uses two ports f or its operation: One port is used to transf er control
commands, and the other is used to transf er actual data (f iles). The client
program connects to port 21 and starts sending commands. This port is used
by all users and the serv ice that listens to the channel works simultaneously
with sev eral connections.
Most FTP commands are similar to those used in Linux to work with f iles.
This is because when the protocol was dev eloped, the main network
operating sy stem was UNIX. Now we hav e Windows ev ery where, but 20 y
ears ago things were dif f erent.
The f irst line is the serv er greeting. It is issued right away to port 21. Most
of ten, this line describes the serv er and its v ersion. In this case, instead of a
specif ic serv er name, I placed my name. A real serv er with the def ault conf
iguration setting will display a line similar to the f ollowing: 220 flenovm.ru
FTP server (Version wu-2.6.2-5) ready.
Why did I change the greeting text? I did so because by def ault it showed the
domain name, the name and v ersion of the FTP serv er, and the prompt
message. Do y ou see any thing dangerous in this inf ormation? I do: All
hackers hav e to do f or f inding out what FTP serv er they are dealing with is
to connect to port 21.
Their f urther actions are easy to predict. If I were those hackers, I would
search all Bugtraq databases f or inf ormation about bugs in the giv en v
ersion of the Washington Univ ersity FTP daemon (wu-f tpd) serv ice. It is
more likely than not that I would f ind some. Then the administrator of the
serv er can only pray that I do not f ind exploits to take adv antage of the
discov ered bugs or that the bugs discov ered are minor and do not let any
thing serious be done with the sy stem.
Af ter the serv er display s the prompt, the client can start sending commands
to it. But bef ore this, the client has to introduce itself to the serv er. This is
done by executing f irst the USERand then PASSFTP commands, specif y
ing the user login and password as the parameter f or each, respectiv ely.
FTP serv ers allow operations with three ty pes of authorization: real, guest,
and anony mous. In the f irst case, y ou hav e to pass to the serv er the real
login and password of a user allowed access to the serv er. Af ter theUSER
command is executed, the serv er prompts y ou to enter the password f or the
specif ied user:
331 Password required for flenov.
Anony mous user access giv es minimal f ile and directory handling
capabilities and is used only to access open f ile archiv es. The anony mous
access is most of ten used to publish documents f or public access using FTP.
For example, sof tware dev elopers set up FTP serv ers with anony mous
access to let users download the sof tware updates or new sof tware v ersions.
A real user can trav erse the entire f ile sy stem of the serv er, being limited
only by the access rights of the user account chosen to connect to the serv er.
Guest login access rights are something between anony mous and real login
access rights. A guest login has more rights than an anony mous login and it
has rights to upload f iles, but unlike a real login, a guest can only work in its
own directory. For example, if a guest is giv en access to the /home/robert
directory, he or she can hav e f ull access to its f iles and subdirectories but
will not be able to go abov e this directory. You can designate any name as
guest.
Af ter a successf ul login to the serv er, y ou can execute any FTP commands.
Howev er, there is a problem with this — the command set depends on the
serv er. All dev elopers prov ide the main commands described in the
Requests For Comments (RFC). But because the capabilities prov ided by the
standard no longer meet today 's requirements, Web serv er dev elopers add
their own f unctions, which may dif f er f rom one dev eloper to another.
Thus, if a client program does not behav e as y ou would expect it to in some
situations, it does not necessarily mean that there is something wrong with it;
it simply may be incompatible with the serv er it is try ing to communicate
with.
The main FTP commands are listed in Table 10.1. They may be of use to y
ou when working with Telnet or testing the serv er.
Table 10.1: FTP commands Command Description
USER
login
Used to enter the login during the authorization procedure
PASS
password
Used to enter the password during the authorization procedure
SYST Returns the sy stem ty pe HELP Returns a list of av ailable commands
LIST Display s f iles and directories of the current directory PWD Display s
the current directory CWD
directory
Changes the current directory to the specif ied one
TYPE type
Specif ies the data transf er ty pe: A f or ASCII f iles, I f or binary f iles
RETR file Retriev es the specif ied f ile f rom the serv er STOR file Uploads
the specif ied f ile to the serv er ABOR Aborts the last FTP command or data
transf er QUIT Terminates the FTP session and exits
The FTP serv er responds to the commands it receiv es with messages that
prov ide inf ormation about the results of the command execution. Responses
consist of a three-digit code f ollowed by optional text. When a response
requires more than one line, the code and the text parts are separated with a
hy phen in the nonterminal lines and with a space in the terminal line.
You should know the meaning of the response codes to be able to determine
the ty pe of errors they indicate.
The meanings of the f irst and second digits of FTP serv er response codes
are listed in Tables 10.2 and 10.3, respectiv ely.
Table 10.2: The meaning of the first digit in FTP server codes Code
Description
The command has been launched successf ully but has not terminated y et;
the user has to wait f or the command
1
to terminate bef ore issuing new commands. This ty pe of response is giv en
when executing lengthy operations (e.g., f ile transf er). Another response
will be issued when the command terminates.
2
The command execution has been successf ul; the user can issue new
commands.
The command execution has been successf ul, but another command is
needed to complete the operation. These responses are giv en when executing
operations inv olv ing
4
attempt is made later. This response may be issued when the serv er cannot
execute the command right away because it is busy executing another
operation.
5
Execution f ailed. This response may be produced by incorrect command sy
ntax or parameter specif ication.
Table 10.3: The meaning of the second digit in FTP server codes Code
Description
0 A sy ntax error
1 A human-oriented help message
2 A connection establishing or terminating message
3 An authentication message
4 Not def ined
5 A f ile sy stem message
Consider an example. Suppose that y ou see the f ollowing message f rom the
serv er and are thinking about what to do next:
331 Anonymous access allowed.
Knowing what the code digits mean will help y ou handle this situation. The f
irst digit, 3, tells y ou that the prev ious command was executed successf ully
but that another command is needed to complete the transaction. The second
digit is also 3; that is, the response is an authentication message. When can
this response be issued? Of course, af ter the login was entered. The FTP serv
er is waiting f or the password and has inf ormed about this with the 331
message.
Fig. 10.2 shows the contents of a sendmail.cf f ile transf erred f rom a Linux
serv er to a Windows serv er in the binary mode and opened in the Windows
Notepad text editor. As y ou can see, it is dif f icult to make any thing out of
its contents, with the<CR>character printed as a rectangle instead of starting
each line as a new line.
Figure 10.2: A text f
ile transmitted in the binary
mode
The end-of -line problem is solv ed by transf erring the f ile in the ASCII
mode. In this case, the text is transmitted line by line and the receiv ing
operating sy stem adds the necessary line-f eed control characters itself . Fig.
10.3 shows the same sendmai.cf f ile transmitted in the ASCII mode. Its
contents are easily readable now.
Binary f iles (such as images or music) must be transf erred in the binary
mode. In this case, it makes no dif f erence under what operating sy stem the
f ile was created, because it will be properly recognized by any other
operating sy stem supporting this f ormat.
If a binary f ile is transf erred f rom Linux to Windows in the ASCII mode,
Windows will replace all<CR>characters (which are a regular occurrence in
binary f iles, although they do not indicate the carriage return operation) with
the<CR>+<LF>character combination, and the binary f ile transmitted will
become corrupted.
As already mentioned, FTP operations require two ports: a control port and a
data port. Port 21 is the control port, used to transf er FTP commands only.
Files are transf erred ov er another port. The process can be described as f
ollows:
1. The client opens the port on the local computer, to which
2. The client sends a request to the serv er to download the f ile, and inf orms
the serv er of the IP address and the port of the client computer, to which the
download is to be perf ormed.
3. The serv er makes a connection with the client computer and starts data
transf er.
This mode, in which the connection is established by the serv er, is called
activ e. The way the connection is established presents a problem. If there is a
f irewall installed on the client computer, it is most likely conf igured to
prohibit any connections initialized f rom outside to prev ent unauthorized
access to the local network. Only a computer inside the f irewall is authorized
to establish the connection.
Thus, FTP will not work properly in the activ e mode if the client f irewall is
properly conf igured. If the f irewall is conf igured to allow outside
connections, it might as well be nonexistent because it no longer prev ents
unauthorized outside access.
This problem is solv ed by the passiv e FTP mode transf ers. This is the def
ault mode on most serv er and client FTP programs, because almost all
modern operating sy stems hav e built-in f irewalls.
In the passiv e mode, the connection is established somewhat dif f erently :
1. The client asks to download a f ile.
2. The serv er allocates a port to be used f or the ensuing data transf er and inf
orms the client of the port number.
3. The client establishes a data connection with the specif ied port.
In this way, the serv er only opens its port and prepares to transf er the f ile;
all connections are established by the client. This is more in line with the
Modern distributions contain a graphical utility f or conf iguring the FTP serv
er, named kwuf tpd. It is launched by selecting the System/kwuftpd menu
sequence f rom the KDE main menu. The utility 's main window is shown in
Fig. 10.4. Howev er, as usual, I will consider f ine-tuning using conf
iguration f iles. Once y ou know how to conf igure the FTP serv ice using the
conf iguration f iles, y ou will hav e no problems doing this using the kwuf
tpd utility.
Figure 10.4: The main window of the kwuf tpd utility
The conf iguration inf ormation f or the FTP serv er is contained in the f
ollowing six f iles:
f tpaccess — Inf ormation specif y ing access rights to the serv er, the FTP
users, and the main security settings. f tpserv ers — Inf ormation specif y ing
v irtual FTP serv ers.
f tpusers — Inf ormation specif y ing users explicitly f orbidden access to the
FTP serv er.
f tphosts — Inf ormation specif y ing access rights to the serv er f or certain
hosts. Access can be both allowed and denied.
anonymous,guest anonymous
anonymous
anonymous
warn
When conf iguring the FTP serv er, the def ault v alues of many directiv es
are not changed because they do not af f ect the serv er's productiv ity or
security. Although some of the directiv es play a role in prev enting incorrect
or inef f icient use of the serv er (e.g., thetimeout XXXXdirectiv e contributes
to timely release of resources), their def ault v alues are suf f icient f or this;
moreov er, changing v alues of some directiv es may hav e negativ e ef f ects.
10.3.1. Access
Access directiv es def ine the main rights f or accessing the FTP serv er.
Consider the main directiv es of this category :
class name type address — Organizes user classes by ty pe and address. In
the example conf iguration f ile (Listing 10.2), there is the f ollowing entry :
class all anonymous,guest,real *
Classes are a handy concept. You can group certain users into a class and
assign them certain rights. For example, y ou can create a class of users
whose IP addresses lie within the address range f or y our of f ice, company,
or country. You then open f ull FTP access to this class only, prohibiting or
limiting access to all others. It is more conv enient to assign rights to an
entire class at once than to write access rights f or each user.
noretrieve type class_name file — Prohibits the specif ied f ile f rom being
read. Thetypeparameter specif ies theabsoluteorrelativepath to the f ile. The
next parameter,class_name, specif ies the class, to which the prohibition
applies. Theallclass described prev iously can either be specif ied explicitly or
not specif ied, in which case the prohibition will apply to all users. If
thefileparameter is specif ied with a f ull path, the prohibition will apply to
this f ile only. If only the f ile name is giv en, access to all f iles with this
name in all directories will be prohibited.
Add this line to y our conf iguration f ile and then connect to the serv er using
an FTP client. For testing the FTP serv er, I used the gFTP client program. Af
ter connecting to the serv er, I created a f ile named passwd in the /home
directory and then tried to download it to the /home/f lenov directory. In
response, the FTP client only created an empty f ile in the directory. But it
could not issue any messages because the prohibition on retriev al made it
crash. This sort of termination is specif ic to the gFTP serv er; other FTP
clients should process the error properly and remain operational.
If the FTP serv er is located on the same phy sical machine as the Web serv
er, it would be logical to also prohibit reading the .htaccess f ile, in which the
access rights to the Web serv er directories are def ined. FTP users should
hav e no right to ev en v iew these rights. It is better to assign rights to specif
ic users only, so that each of them could work only with his or her own
.htaccess f iles, or to prov ide some other way to edit rights.
deny address file — Prohibits client access f rom the specif ied addresses.
When a connection attempt is made f rom a prohibited address, a message
stored in the f ile specif ied by thefileparameter is display ed. The address can
be specif ied as a regular expression.
defumask mask — Indicates the access rights mask used to create new f iles.
The Linuxumaskcommand, which specif ies the current v alue of the mask,
was described inSection 4.1.
file-limit direction number class — Sets the limit on the number of transf
erred f iles. The direction parameter can be specif ied asin, out, ortotal. For
example, thefilelimit total 10command prohibits transf er of more than ten f
iles in both directions.
byte-limit direction number class — Limits the number of transf erred by tes.
The directiv e operates like thefilelimitscommand, only it works with by tes
instead of f iles.
guest-root directory — Makes all guests use the same directory (analogous to
the prev ious command). If each guest must hav e a personal directory, it is
better to create an account f or each guest explicitly (seeSection 10.6).
deny-email address — Denies access if the specif ied email address is giv en
as the password. Most FTP clients are conf igured with some arbitrary v alid
email address f or anony mous access — f or example, [email protected] —
that is rarely changed. Because this address complies with all rules f or the
email address f ormat, the serv er cannot determine that it is not a real
address. But when this address is specif ied explicitly in this parameter, users
will not be able to use this address as the password unless it is changed to
something else. But ev en this does not guarantee that anony mous users will
giv e their own email addresses as the password.
deny-uid identifiers — Prohibits users with specif ied identif iers f rom
accessing the FTP serv er. Theftpusersf ile, considered inSection 10.5, perf
orms the same f unction. This command is conv enient because it can be
applied to ranges of users. For example, thedeny-uid %-500command denies
access to all users whose user ID is less than 500.
deny-gid identifiers — Prohibits access the FTP serv er f or the users of the
group with the specif ied identif iers. The ftpuserscommand perf orms the
same f unction.
restricted_uid identifiers — Prohibits guest users with the specif ied IDs f
rom accessing directories outside their home directory.
restricted_gid identifiers — Prohibits users with the specif ied group ID f rom
accessing directories outside their home directory.
File upload is the most dangerous operation f or the serv er. Each user should
only be able to access his or her own directory. But what if anony mous users
also need to upload f iles? In this case, y ou should prohibit uploads by anony
mous users to v ulnerable directories, into which scripts could be uploaded
and executed af terwards.
The f tpaccess f ile can also be used to describe the main operations and their
permissions. The general f ormat of such commands is as f ollows: Action
yes|no user
For example, Listing 10.2 contains the f ollowing lines to prohibit access to
these operations:
banner name — Specif ies a text f ile (in thenameparameter) whose contents
will be display ed to the user when starting the login process. The contents
are arbitrary ; these may be a greeting, some inf ormation, or the FTP serv er
usage rules. You should remember that the banner is display ed bef ore the
authentication process; theref ore, it should not contain any inf ormation that
may help hackers break into the sy stem.
greeting full|brief|terse|text — Specif ies how much inf ormation about the sy
stem is giv en to the user bef ore the login. The greeting is a string that may
look like this: "220 f lenov m.ru FTP serv er (Version wu-2.6.2-5) ready." As
explained inSection 10.1, this string is display ed bef ore the authorization
process and contains inf ormation about the sy stem and the FTP serv er v
ersion. It is not a good idea to display either f ull or correct inf ormation; y ou
are better of f showing the least possible amount of correct inf ormation or,
ev en better, display ing something that is not true. The meanings of the
parameter v alues as f ollows:
full— The host name and daemon name and v ersion are display ed.
brief— Only the host name is display ed. terse— The "FTP serv er ready "
message is display ed.
text— A custom message is display ed.
I like the last option the best. The custom text to be display ed is entered af
ter a space f ollowing the text parameter, as f ollows:
greeting text text_string
On my serv ers, I use a custom message say ing either greeting text
flenovm.ru FTP Server (MS IIS 4.1.0) readyorgreeting text flenovm.ru FTP
Server (cd-ftpd 2.1.9) ready.
Neither of these two messages prov ides any inf ormation about what FTP
serv er is installed. The f irst one may make hackers think they are dealing
with the Internet inf ormation serv er f rom Microsof t, which is used only in
Windows sy stems. This can conf use ev en an experienced hacker. Unf
ortunately, this message does not prev ent the same hacker f rom using
special utilities to determine that the operating sy stem is actually Linux. Ev
en though these utilities will not be able to determine the exact v ersion of
Linux, they establish that the FTP serv er greeting message is a f ake.
In the second case, I specif y a nonexistent serv er. Not being able to f ind an
exploit to break into the serv er because of the lack of inf ormation about the
serv er used, the potential computer burglar may pref er looking f or easier
prey.
10.3.5. Logging
Some administrators log activ ities of anony mous and guest users only. Their
rationale f or this is that real sy stem users will not do any thing damaging to
the serv er that they need f or their work. This is f undamentally f lawed
thinking, because quite a f ew break-ins are perpetrated by real users; moreov
er, most of ten hackers use real user accounts to break in.
Should a nonstandard situation dev elop, logs will prov ide y ou with detailed
inf ormation about the reasons f or this. You can then take steps to eliminate
those particular causes. (The logging subject is cov ered in detail inChapter
12.)
The def ault f ile f or storing the wu-f tp log is /v ar/log/xf erlog. The history
of activ ity f or the last six day s can be v iewed in the /v ar/log/xf erlog.X f
ile, where X is a number f rom 0 to 5.
The f ollowing are some examples of conf iguring the wu-f tp serv er's
logging f unctions:
log syslog+xferlog— Sends the transf er logs to both the sy slog and the xf
erlog f iles.
I will not go into detail on the v irtual serv er subject, because this is bey ond
the scope of this book. If y ou desire more inf ormation on this subject, y ou
can f ind it in the documentation (e.g.,ftpaccess manpage). Also, y ou can
create one using the graphical FTP serv er-conf iguration utility.
To tell the truth, I am not f ond of the v irtual serv er f unctions of the wu-f tp
serv er. If y ou need sev eral v irtual FTP serv ers, I adv ise y ou to take a
look at the ProFTP serv er, which is, in my opinion, more suitable f or this
task. The wu-f tp serv er is too cumbersome to conf igure f or work with v
irtual serv ers because its conf iguration f iles are spread all ov er the sy stem.
All v irtual FTP serv ers are def ined in the f tpserv ers conf iguration f ile. A
v irtual FTP serv er is def ined by specif y ing its IP address and the directory
containing its conf iguration f iles (which are duplicates of the wu-f tp serv er
conf iguration f iles listed prev iously ). If a conf iguration f ile f or a v irtual
serv er is missing, the corresponding f ile in the /etc directory will be used
instead.
Because wu-f tp serv er uses operating sy stem accounts, which are stored in
the /etc/passwd f ile, any real user can automatically work with the FTP serv
er using his or her account and access rights. Howev er, f ar f rom all users
need this capability.
To prohibit real users f rom accessing the FTP serv er, their names should be
added to the /etc/f tpusers f ile. Listing 10.3 shows the contents of the f ile.
Depending on the distribution, the contents may v ary.
Note that the root user is prohibited access. This is because the administrator
has too many rights and if hackers highjack this account, they will obtain
complete control ov er the sy stem. Nev er allow high-priv ileged users
(administrators and administrator group users) access the FTP serv er.
The best policy would be to prohibit FTP access to all sy stem accounts
whose ID is less than 500. This can be done by adding the f ollowing entry to
the f tpaccess f ile:
deny-uid %-500
This way, y ou can be sure that y ou don't f orget to restrict access to
someone — especially if there is more than one user that has the same ID
number (f or example, 0).
Great administrator wisdom states that a f irewall helps those who help
themselv es. A f irewall prohibits access to the serv er to certain ports f rom
specif ic computers. The /etc/f tphosts conf iguration f ile perf orms a similar
f unction: It prohibits or allows access f rom the specif ied IP addresses or an
entire network.
By def ault, the f ile is empty, because the sof tware dev elopers cannot know
how y ou intend to go about organizing access. You can enter the f ollowing
directiv es into the f ile:
allow name template
deny name template
For example, if y ou want to deny anony mous users access f rom address
192.168.1.1, add the f ollowing line to the f ile:
deny anonymous 192.168.1.1
According to the " ev ery thing not permitted is prohibited" principle, it may
seem that the denydirectiv e is not necessary. This is a wrong way of
thinking, because a certain ty pe of users has to be allowed access f rom the
specif ied address and then all other users must be prohibited access to the
FTP serv er.
10.5.3. Grouping
The f tpgroups f ile contains descriptions of the groups allowed to use the
SITE GROUPand SITE GPASScommands when created. These are
nonstandard FTP directiv es, which f ew dev elopers support; consequently,
users may f ind working with these commands too in-conv enient.
First, a new account is created f or the user; name it robert_f tp. This is done
using the f ollowing command:
useradd robert_ftp
The corresponding entry f or this account in the /etc/passwd f ile should look
similar to the f ollowing:
robert_ftp:x:507:507::/home/robert_ftp:/bin/bash
This is a standard new user entry. But this account can be used to enter the sy
stem locally, and y ou only want to giv e it FTP access. Change the shell f or
the user to /bin/f tponly. There is no such shell right now, but it will be
created a little later. In addition, the /home/robert_f tp directory has to be
made a root directory. This is done by adding a directory named . (dot) at the
end of the user's home directory path.
The edited entry f or the robert_f tp user in the /etc/passwd f ile should look
as f ollows:
robert_ftp:x:507:507::/home/robert_ftp/.:/bin/ftponly
Note that the /bin/f tponly shell f ile does not exist. Create it now. Only one
such f ile has to be created f or being used by all guest accounts. The f ile is
created by thecatcommand as f ollows:
cat >> /bin/ftponly
The command creates a f ile named f tponly in the /bin/ directory and
redirects all subsequent console input to it. Enter the f ollowing text f rom the
console:
#! /bin/sh
echo 'You are not allowed to log in interactively' exit 0
Press the <Ctrl>+<X> key combination. This will sav e the f ile, terminate
the entry mode, and take y ou back to the regular console mode.
The f irst command in the /bin/f tponly f ile display s the message say ing an
interactiv e login is not allowed, and the second terminates the session.
Now the /bin/f tponly f ile has to be made executable. This is done by the f
ollowing command:
chmod 755 /bin/ftponly
Thus, y ou hav e a new user and a shell f ile f or this user. Attempting to log
into the sy stem as the robert_f tp user will display the "You are not allowed
to log in interactiv ely " message f or a moment, f ollowed by termination of
the current login session. Thus, y ou will not be able to log into the sy stem as
robert_f tp.
Instead of the /bin/f tponly f ile, the /dev /nul dev ice can be used as the shell.
This is a null dev ice, which cannot process commands and will not allow the
user to enter the sy stem. This dev ice is specif ied in the /etc/passwd f ile as
the console f or all sy stem accounts not intended f or local work.
There is one little thing lef t: Tell the FTP serv er that the robert_f tp user is a
guest. This is done by adding the f ollowing entry to the f tpaccess f ile:
guestuser robert_ftp
Now, when connecting to the FTP serv er as robert_f tp, y ou will only be
able to see y our directory, which will appear to be the root directory. The
rest of the directories abov e it will not be v isible.
On my sy stem, all FTP users work only as guests in their own directories, or
anony mously with shared directories. Real FTP user accounts are created
only f or selected administrators and then only when necessary, because such
accounts are more dif f icult to control.
You only hav e to restrict access f or guest users to a certain directory, with
the serv er protecting the rest. Howev er, there can be problems here.
Consider a classic programmer error. Suppose that a user is allowed access to
the /home/robert directory and that the serv er enf orces this access by simply
checking that any path f rom this user starts with this string. For hackers, this
directory will seem to be the root (/) directory, and they should not be able to
reach any higher directories. But take a look at the f ollowing command:
cat /home/robert/../../../../../etc/passwd
Despite being so obv ious and easy to av oid, this bug is quite common. All
the programmer has to do is ensure that the address does not contain the /‥
combination and take proper steps if it does. Although the wu-f tp serv er
does not hav e this bug now, it may acquire it with an update, when the check
may be disabled or deleted. This ty pe of thing sometimes happens, especially
if the sof tware is dev eloped by a team and the quality control of the ov erall
product is def icient.
4. The serv er opens a port and sends the pertinent inf ormation to the client.
5. The client connects to the specif ied port number and downloads or
uploads the f ile.
Most FTP serv ers today hav e a built-in f unction to compare the IP
addresses connected to port 21 and to the data port. This makes the attack
more dif f icult to carry out because now the hacker must f ake the IP address,
which is not an easy task with TCP.
Using IP-address binding does not alway s solv e the problem. If there is an
anony mous proxy serv er or a f irewall that masks IP addresses between the
FTP client and the serv er, the FTP serv er will see not the address of the FTP
client but the address of the proxy or the f irewall.
You could disable the passiv e mode, which would dispense with this issue
entirely. But this would not be a univ ersal remedy f or all security issues. As
y ou will see in the next section, the activ e FTP mode is also f ar f rom
secure.
You need a serv er that can execute scripts, which is not alway s easy to come
by.
Free serv ers that can execute scripts require y ou to register, and keep
detailed activ ity logs. If the registration requirement is no more than a f
ormality that is easily to get around by supply ing arbitrary inf ormation, the
logging part presents a big problem. Most serv ers nowaday s are conf igured
to watch f or scanning activ ities conducted using their resources, and will
record and call the administration's attentions to any such attempts. Af ter
that, f inding the person behind the scan is only a matter of technicalities.
Hackers hav e come up with an excellent way to make a serv er scan ports.
All y ou do is connect to an FTP serv er operating in the activ e mode.
Ref resh y our knowledge of how activ e-mode f ile transf er is conducted.
The FTP client sends the FTP serv er a request specif y ing the port on the
client computer, to which the serv er should connect to conduct the f ile transf
er. In addition to the port number, to which the serv er will send data, the
client sends the IP address. But this address does not hav e to be the client's
address! This means that a client whose address is 192.168.1.1 can request
the FTP serv er to connect to any port on a computer with any IP address and
the serv er will be none the wiser. Hackers f igured out how to use this
peculiarity and make the FTP serv er scan ports on other computers.
Once I carried out a successf ul DoS attack on my own serv er. I made the
FTP serv er scan the computer with the proxy used to connect to the Internet.
The proxy serv er had an attack-detection sy stem installed, which
automatically blocked any connection attempts upon detecting any
portscanning attempts. (Such sy stems are discussed inChapter 12). The
scanning was successf ul, and I went to lunch with the f eeling of a job well
done. But when I returned, I was swamped with complaints that the FTP serv
er was not working. I checked it out and ev ery thing was all right. So I
started scratching my head. As it turned out, the FTP serv er became
inaccessible to outside users connecting v ia the proxy serv er, because the
proxy serv er detected the scanning and put the FTP serv er on its black list.
You can use the nmap program to scan ports using the FTP serv er as f
ollows:
nmap -b user_name:password@ftp_server:port
As y ou can see, this entry looks much like the string to connect to the serv er
using a Web browser. If an anony mous serv er will be used to do the
scanning, the user name and the password can be omitted:
nmap -b ftpserver:port
If the serv er uses port 21, the port parameter can also be omitted.
One way of protecting against FTP port scanning is to conf igure the f irewall
to disable the activ e mode, that is, to block port 20, which is most of ten used
as the FTP data port. In this case, all connections are initialized by the client
only.
10.7.3. Mailings
The FTP serv er can be used to send email messages. This is done by placing
the f ollowing text f ile on the serv er:
HALO mailserver.com
MAIL FROM: [email protected]
RCPT TO: [email protected]
DATA
The letter body
.
The entries are SMTP serv er commands and mean the f ollowing:
Load this f ile on the FTP serv er and execute the f ollowing two commands:
PORT 192,168,1,1,25
RETR filename
The f irst entry is the FTP PORTcommand, telling the serv er to connect to
port 25 of the computer with IP address 192.168.1.1. The f irst f our numbers
are the computer's IP address, and the last is the port to connect to. This
command can be used to scan serv er ports manually, but in this case we are
af ter another thing.
The second entry is the command that sends to the serv er the filenamef ile
with SMTP commands. The SMTP serv er sees this as if the FTP serv er is
giv ing it directiv es to send the letter, which it will execute. The recipient of
the letter will nev er be able to determine its source. The letter's serv ice inf
ormation will only point to the FTP serv er. In this way, malef actors can
send anony mous letters without worry ing that they will be f ound out.
The most div erse ty pes of letters can be sent: v iruses, Trojans, spam, and so
on. Yet another way of using the FTP serv er to send email messages is to
place a large f ile there and make the serv er send this f ile to the SMTP serv
er endlessly. Launching sev eral such processes can be used to pull of f a
successf ul DoS attack against a weak SMTP channel.
The only way to protect against such an attack on the SMTP serv er side is to
use mandatory authorization to gain access. In this case, the hacker will hav e
to possess inf ormation on a real account that is allowed access to the SMTP
serv er. The FTP serv er is also protected by authenticating users who want to
connect to it. No anony mous connections should be allowed, especially f or f
ile uploads.
You can also read the wu-f tp serv er documentation in the /usr/share/doc/wuf
tpd-X.X.X directory (X.X.X is the v ersion number of the serv er installed on
y our machine).
All changes specif ied in the conf iguration f ile become ef f ectiv e
immediately. Howev er, clients hav e to reconnect to the serv er to start
working with the new settings.
ftpd — Starts the serv er with special parameters. There are many possible
attributes; inf ormation concerning them can be obtained f rom theftpd
manpage. I hav e nev er had to resort to using the command options because
once the serv er has been properly conf igured it works steadily.
-l n — Do not accept any new connections less thannminutes bef ore the
shutdown. Specif y a time suf f icient f or the clients to properly f inish their
serv er operations.
-d n — Disconnect the connectionsn minutes bef ore shutting down the FTP
serv er. I recommend setting the disconnection immediately or 1 minute bef
ore the shut down.
time — Specif ies the shutdown time f or the FTP serv er and is similar to the
same parameter in the Linuxshutdowncommand. You can shut down the serv
er immediately by specif y ing the v alue of the time parameter asnow; howev
er, I recommend using the +noption (where nis time in minutes until the
shutdown) or specif y ing the exact time in the HHMM f ormat.
ckconfig— Checks the FTP serv er's conf iguration and display s a report f or
each wu-f tp serv er conf iguration f ile.
10.9. Summary
FTP itself and FTP serv ers f rom v arious dev elopers hav e had serious
security problems throughout their history. The losses caused by FTP and
sendmail bugs combined may ev en ov ershadow the losses caused by v
iruses.
Back when it was created, FTP was needed f or data transf er, but today it
should be av oided. If y ou only want to let users download inf ormation,
consider using HTTP f or this. It is more secure, and it can be used to upload
f iles to the serv er.
Data exchange on a local network can be organized using the Samba serv er
or HTTP. Many administrators do f eel like conf iguring the Web serv er only
f or data exchange and install potentially dangerous scripts on it. But keep in
mind that FTP can also be dangerous to security. You should choose the
lesser of the two ev ils. If y ou already hav e a Web serv er running, use its
capabilities as much as possible; then y ou will be able to close port 21,
thereby protecting y ourself against potential problems that can arise f rom its
use.
If y ou need to use the FTP serv ice y ourself f or remote f ile operations, I
recommend using the SSH package and the built-in SSH FTP to encry pt
data. This ty pe of connection is much more dif f icult to compromise.
When y ou are requesting a Web page f rom a serv er, y ou need to know the
page's IP address. Once y ou know the address and send y our request to the
serv er, y ou hav e to supply it with y our own IP address so that the serv er
knows where to return the requested page. Here, an analogy with the regular
mail can be observ ed. If y ou want to receiv e an answer to y our letter, y ou
hav e to put y our return address on the env elope.
At the dawn of the Internet, the number of computers in it was not that large,
and the simplest and most logical method of implementing addressing was
selected: using numbers. Still, 20 numerical addresses is about the limit an av
erage human can remember, so f or the conv enience of humans, hosts are giv
en names that can be easily remembered, f or example,
www.webpage.com.
This made the situation with remembering addresses much easier f or people.
Now to v isit a site, f or example, of the Microsof t Corporation, y ou hav e to
know not its exact numerical IP address but just an easy -to-remember
domain name: www.microsoft.com.
But as the number of computers on the Internet grew, so did the size of the
database, until it became impossible f or each location to maintain a copy of
it. This is when the DNS came into being.
DNS is a distributed database of host names and their corresponding IP
addresses; there are thousands of DNS serv ers on the Internet. The domain
namespace has a hierarchical structure, with the root domain indicated by a .
(dot, or period). The root domain is f ollowed by subdomains, also separated
with a period. The domains af ter the root are called top-lev el domains. Some
of the top-lev el domain names are com, org, net, gov, edu, ru, and de. In
cydsoft.com, cydsoft is a second-lev el domain name. Fig. 11.1 shows an
example of the domain namespace hierarchy.
The adv antages of DNS become apparent not only on the Internet but also in
suf f iciently large local networks. Af ter DNS was implemented, another of
its adv antages came to light: The same IP address can be used f or sev eral
sites. This allows sev eral sites to be maintained on a single serv er.
All these operations are perf ormed transparently to the end user, so y ou will
nev er see all these intricacies when entering an address into a browser.
Depending on the browser, a message that the IP address is being looked up
(Opera) or that the Web page is being connected to (Internet Explorer) is
display ed in the browser's status line.
There also are numerous automatic DNS inf ormation-caching serv ers.
Caching DNS inf ormation makes it possible not to query the main database
all the time but to obtain the necessary address at the nearest serv er. Caching
serv ers exchange inf ormation among themselv es and allow any host name
to be resolv ed to its address. Thus, y our Internet prov ider may maintain its
own DNS serv er. In this case, the request to resolv e a host name to its IP
address is sent to this DNS serv er. If this serv er does not hav e the requested
host name inf ormation, the request is passed to another DNS serv er. The
request is relay ed among v arious DNS serv ers until the necessary host
name inf ormation is encountered; in this way, the IP address f or the
requested host name can be obtained f rom the nearest DNS serv er
containing the necessary inf ormation in its cache.
DNS serv ers can not only look up IP addresses by host names but also perf
orm rev erse lookups, that is, resolv e IP addresses to the corresponding host
names. In this case, the IP address is also parsed f rom right to lef t. For
example, to resolv e IP address 190.1.15.77 to the host name, the address in
the DNS request is entered as 77.15.1.190 with the .in-addr.arpa suf f ix
added, resulting in this: 77.15.1.190.in-addr.arpa.
Each entry in the f ile maps a host name to its corresponding IP address. By
def ault, there are only two entries in the f ile. The f irst entry is the loopback
mapping. For all computers, thelocalhostname and the 127.0.0.1 IP address
specif y the local machine. Thus, the local computer can be pinged as f
ollows:
ping 127.0.0.1
The second entry maps the computer name to the explicitly specif ied IP
address of the machine's network adapter. In this case, the network card's IP
address is set to 192.168.77.1; it is mapped to the Flenov M computer name.
This means that either the computer name or its IP address can be specif ied
as the parameter f or thepingcommand. The f ollowing two commands are
identical:
ping 192.168.77.1
ping FlenovM
But which, the /etc/hosts f ile or DNS, is ref erenced f irst to resolv e an
address? This depends on the conf iguration of the operating sy stem. There
is the f ollowing line in the /etc/host.conf f ile:
order hosts, bind
The orderdirectiv e specif ies the order, in which the address resolution sy
stems are ref erenced. At this setting, f irst the /etc/hosts f ile will be
consulted, and only if the necessary inf ormation is not f ound in it will the
bindcommand be executed to send a request to the DNS serv er. This speeds
up access to main serv ers. Suppose that y ou v isit the www.redhat.comsite
ev ery day. When a request is sent to the DNS serv er, it takes a couple of
seconds to resolv e the host name to its IP address and to start loading the
page.
To speed up the loading, the f ollowing entry can be made in the /etc/hosts f
ile:
209.132.177.50 www.redhat.com
If , f or some reason, the site will no longer load, delete the corresponding
entry f rom the /etc/hosts f ile. Then execute the ping redhat.comcommand to
check the communication with the serv er and to f ind out its IP address. This
will display the IP address, with which the ping messages are exchanged. IP
addresses of most sites change rarely, so once a mapping entry is added to the
/etc/hosts f ile, y ou can sav e lots of time and nerv es, especially when there
are problems with the DNS serv er.
The searchparameter in the f irst entry specif ies the host name search serv er.
The f ile on y our sy stem most likely also contains this entry, with the name
of y our computer specif ied as the serv er. This parameter can contain a
space- or tab-delimited list of sev eral serv ers. For example: search FlenovM
MyServer
The local serv er is searched quickly enough, but searching remote serv ers
may take a while.
In the second f ile, the domainparameter is specif ied. Users sometimes like
to specif y computer names without giv ing the top-lev el domain name; f or
example, "redhat" instead of "redhat.com." In thedomainparameter, the toplev
el domain name is specif ied to be used in such cases. Most of ten, a specif ic
top-lev el domain name f or local networks is specif ied in this parameter.
In most cases, a single serv er is enough, because all of them operate recursiv
ely. For example, when a computer requests to resolv e the redhat.com
address, the request is directed to the f irst DNS serv er on the list. If this serv
er does not f ind the necessary address, it f orwards the request to another
DNS serv er that is has on its own nameserverlist.
I, howev er, recommend specif y ing two DNS serv ers. Sometimes, when the
f irst DNS serv er f ails, the second one sav es the situation.
The ampersand (&) specif ies that the program is to be run in the background.
When a graphical utility is launched in the background, it does not interf ere
with the console operations. Note, howev er, that when the console window is
closed, all programs launched with the & option are also closed.
Fig. 11.2 shows the DNS conf iguration utility 's main window. In the center
of the main window, the dialog window f or adding a domain is shown. All y
ou hav e to do f or adding a domain is select the zone ty pe and specif y the
domain name.
Figure 11.2: DNS control windows
Ev en though DNS can be conf igured through the user-f riendly graphical
utility, I will consider doing this using the conf iguration f iles f or the serv
ice. Editing them directly allows the serv ice to be conf igured more precisely
and will also enable y ou to understand the DNS operation process better.
options {
directory "/var/named/";
};
zone "." {
type hint;
file "named.ca";
};
zone "sitename.com" {
type master;
file "sitename.zone";
};
zone "10.12.190.in-addr.arpa" {
type master;
file "10.12.190.in-addr.arpa.zone";
};
In this example, the f ile is broken into f our sections of the f ollowing f
ormat: type name {
Parameter1;
Parameter2;
...
};
The f unctions of each section are as f ollows. The f irst section isoptions:
options {
directory "/var/named/";
};
It contains only one parameter in braces:directory. It specif ies the home
directory of the DNS serv er, where all of its f iles will be stored. The rest of
the sections are of the zonety pe, with the zone name giv en in quotation
marks. Each of the sections contains two parameters. The type parameter def
ines the zone ty pe, and the fileparameter def ines the f ile containing the
description of the zone.
The f irst zone in the example is described as f ollows: zone "." {
type hint;
file "named.ca";
};
What is this . zone? Recall the DNS theory presented at the beginning of the
chapter. According to this theory, the DNS root domain is represented as a
period. Thus, the section describes the root zone. The section ty pe,hint,
means that the serv er will only store links to the DNS serv er. Because this is
the root zone, all links will be to the root serv ers.
The fileparameter specif ies the name of the f ile containing all links to the
root serv ers. Your sy stem may not hav e this f ile because the inf ormation
in it is dy namic. It is the best to obtain the latest v ersion of this f ile f rom
the internic.net serv er. This is done by executing the f ollowing command:
dig @rs.internic.net . ns > named.ca
The zone ty pe, master, means that y our DNS serv er will be the main one,
with the rest only v erif y ing and caching DNS inf ormation. The inf
ormation about this zone will be stored in the sitename.zone f ile in the work
directory, which is /v ar/named in this case.
type master;
file "10.12.190.in-addr.arpa.zone"; };
The zone ty pe ismasteragain.
named.ca — Links to the root serv ers are stored in this f ile. This f ile is
downloaded f rom the intenic.net serv er; theref ore, it should not be edited,
and I will not be considering it.
For security reasons, the HINFOandTXTrecords are not used; theref ore, they
will not rev eal any inf ormation to hackers. Hackers should not be giv en any
inf ormation about the computer, howev er innocent it may seem, and inf
ormation about the computer's operating sy stem and equipment is f ar f rom
innocent. TheHINFOandTXTrecords are purely inf ormational and do not
contain any data af f ecting the serv er's operation.
Now, return to the sitename.zone f ile and consider its contents. In the f irst
records (of theIN SOAty pe), the zone is described. First, the name of the
DNS serv er(ns.sitename.com)and the person responsible f or the record
([email protected])are giv en. The parameters in the parentheses are each
specif ied on a separate line f or conv enience. The f irst parameter is the
serial number. Increment this parameter by 1 af ter each modif ication or
replace it with the date the record was last modif ied. By this v alue, other
serv ers will f ind out whether the record was modif ied.
The refreshparameter sets the f requency, with which other serv ers must
update their inf ormation. In case of an error, the serv er has to try again af ter
the period specif ied in theretryparameter.
The expireparameter specif ies when cached-zone inf ormation will no longer
be v alid. The ttlparameter def ines the entry 's minimum TTL on caching
serv ers.
These parameters inf orm the rest of the DNS how to ref resh the inf ormation
about the zone controlled by y our DNS serv er.
The next record is of the NS ty pe; there can be sev eral such records. In this
case, NS stands f or name serv er. This record describes the DNS serv ers
responsible f or this zone. All other DNS participants will use these serv ers
to resolv e the sitename.com sy mbolic name to its IP address.
Next, mail exchange (MX) records can f ollow. DNS serv ers use these
records to determine where to send mail that comes to the sitename.com
domain. In this example, this is the mail.sitename.com serv er. The number
in f ront of the serv er name specif ies the MX entry 's priority. If there are
multiple MX records, they will be used in the order of their priorities.
The last records are used f or the rev erse lookup. They are of the f ollowing f
ormat:
name A address
1 ; serial
28800 ; refresh
7200 ; retry
604800 ; expire
86400 ; ttl
) IN NS localhost.
1 PTR servername.com. 2 PTR mail.servername.com.
You already know the purpose of the larger part of the f ile and only need to
consider the last two records. These map IP addresses to their corresponding
host names. Don't f orget that the f ile is responsible f or the 190.12.10.*
network. The asterisk is replaced with the number f rom the f irst f ield, and
the name corresponding to this IP address is giv en in the last f ield. The f ile
def ines the f ollowing mappings:
190.12.10.1 = servername.com.
190.12.10.2 = mail.servername.com.
It is mandatory that sy mbolic names end with a period.
You can f ind additional inf ormation concerning DNS in the RFC1035,
RFC1712, and RFC1706 documents.
Other than putting DNS serv ers out of order, hackers can extract too much
inf ormation about the network structure. To prev ent this, it is desirable to
use two DNS serv ers as f ollows:
One DNS serv er is publicly av ailable and contains only the mapping inf
ormation necessary f or remote users to work with shared resources.
Another DNS serv er is av ailable only to local network users and contains all
mapping inf ormation the users require f or their work.
The f irewall on the local DNS serv er can be conf igured to recognize local
traf f ic only and ignore access attempts f rom the Internet. This will make it
problematic f or hackers not only to obtain inf ormation f rom the DNS
database but also to disrupt the operation of this serv er. In this way, when the
f irewall is f unctional, all local users will be protected against disruptions in
DNS operations.
You could install a secondary serv er f or each primary serv er. This will
distribute each workload between two serv ers, reduce the response time, and
enhance the sy stem's robustness. Moreov er, if one of the serv ers f ails, the
other will pick up its workload and keep the DNS serv ice operational.
This will produce all database records about the serv er.com serv er. To prev
ent this, the addresses of the secondary serv ers hav e to be explicitly specif
ied in the named.conf f ile. This is done by adding the f ollowing entry to
itsoptions {...}section:
allow-transfer {192.168.1.1;}
This can also be done in the descriptions of the indiv idual zones, but it is
pref erable to do this once in the global options. If y ou do not employ a
secondary DNS serv er, prohibit data f rom being transf erred to the
secondary zone by adding the f ollowing entry :
allow-transfer {none;}
DNS serv ers can be subjected to DDoS attacks. The most notorious DDoS
attack on Internet DNS serv ers was carried out in Nov ember 2002. Sev eral
root serv ers were attacked simultaneously. If only one serv er had been
employ ed to prov ide DNS serv ices, the Internet would hav e become
inaccessible shortly af ter the attack started. This did not happen f or the f
ollowing reasons:
Caching serv ers Proxy serv ers, which also cache DNS records
Other aspects of securing a DNS serv er are identical to securing any other
serv ice and the operating sy stem. As already mentioned, the most secure
serv er is one that perf orms a narrowly -specif ied task. There are f ewer
open ports and f ewer running serv ices on such serv ers, which makes them
more dif f icult to compromise. The only problem with this approach is that
numerous serv ers make the process of updating the operating sy stem more
complex. Linux has its f air share of bugs that hav e to be f ixed, and when
updates are made av ailable, all serv ers, including DNS serv ers, hav e to be
updated.
If y ou hav e been hacked, y our task is not just to recov er gracef ully but
also to prev ent this f rom happening again. I hav e seen many administrators
who af ter a break-in simply restore deleted f iles and continue in the same
way, hoping that lightning will not strike in the same place twice. This is
mistake, because unlike lightning, a computer hacked into once is much more
likely to be hacked into again; the hacker already knows how to enter the sy
stem and mov e around it.
So instead of hoping that the hacker had all the f un he or she wanted and will
not return, y ou should take f or granted that the hackerwillreturn and hav e a
proper reception party prepared. Find out as much inf ormation as possible
about the hacker, the way s used to penetrate the sy stem, and how y ou might
block the attack. You also hav e to peruse the latest Bugtraq lists f or inf
ormation about bugs in y our operating sy stem and serv ices installed.
Hackers sometimes leav e back doors (e.g., setting the SUID bit of a program
that is not supposed to be set), and y ou should regularly conduct security
sweeps of the sy stem as described in the ensuing material. It is especially
applicable right af ter installing and initially conf iguring the operating sy
stem, installing new application sof tware, updating the sy stem sof tware, or
experiencing a break-in.
ISS has dev eloped a suite of utilities named SAFEsuite. The suite contains
not only sy stem-security testing utilities but also intrusion-detection utilities
and utilities to check the conf iguration of the main serv er operating sy
stems.
Security scanners are similar to antiv irus programs: They protect only
against known threats. Any new v ulnerability will not be detected until the
program is updated. For this reason, I don't recommend that y ou rely only on
the automatic security scanners; supplement them by manually checking f or
the latest v ulnerabilities described in Bugtraq.
The automatic scanners are good f or perf orming initial scanning f or old v
ulnerabilities. If y ou are a sy stem administrator and scanning detects v
ulnerabilities in y our sy stem, y ou should update the sof tware component
containing the v ulnerability or check one of the security sites (e.g.,
www.securityfocus.com) f or way s to neutralize the v ulnerabilities discov
ered. Almost alway s, the description of the remedy f or the v ulnerability is
giv en with a description of the v ulnerability. The way to neutralize the v
ulnerability may also be suggested by the scanning program if it has this in its
solution database.
Each scanner employ s indiv idual techniques and means, and v ulnerabilities
missed by one scanner may be detected by another. Computer-security prof
essionals like to use the apartment analogy. Suppose y ou came to v isit a f
riend, ringed his doorbell, but nobody opened the door. This, howev er, does
not mean that there was no one at home; the owner, f or example, may not
hav e heard the doorbell or it may hav e been out of order. But if y ou had
called him on the phone, he might hav e heard it and answered. Or it could be
the other way around: The f riend could miss the phone call but hear the
doorbell.
In the same way, one v ulnerability -detection technique may produce positiv
e results, and another may show negativ e ones. To return to the automatic
scanners, one scanner is like the phone call and another one is like the
doorbell. They both produce results, but with dif f erent serv er conf
igurations one may be better than the other.
During the probing process, the utility does not scan the serv er f or open
ports; it scans its programs f or v ulnerable code. This process is similar to
the way antiv irus programs work, which scan all programs f or v irus code.
Here the same thing takes place, only the object of the search is v ulnerable
code. The method is an ef f ectiv e one, but the same ty pe of error (e.g., a buf
f er ov erf low) can be present in programs written in dif f erent languages.
The scanner will not detect this ty pe of error.
The imitation method inv olv es the utility imitating attacks that it contains in
its database. For example, the FTP serv er may produce the buf f er-ov erf
low error when a certain command is executed. The scanner will not try to
detect the serv er's v ersion but will execute the command instead. This will
hang the serv er, but y ou will know f or certain whether the serv er has this
particular v ulnerability. This method is the lengthiest but also the most
reliable, because if the utility can break some serv ice, then a hacker can also
do it.
Alway s disable the f irewall when conducting a sy stem scan. It may block
access and the scan may not scan the necessary serv ice. In this case, it will
report no v ulnerabilities when they may exist. These v ulnerabilities are not
critical because they are protected by the f irewall, but if a hacker f inds a
loophole through the f irewall, they will become critical.
Giv e the scanner all it needs. For example, some people think that remote
scanning, when the scanner imitates an attack ov er the network, is the most
ef f ectiv e. Although this is so, it begets a question: How much time it will
take to check the strength of the account passwords? A lot? And such checks
as registry and f ile sy stem scans will become impossible. This is why local
scanning may be more productiv e and reliable.
In remote scanning, the scanner only attempts to enter the network. This ty pe
of analy sis can be used to ev aluate the serv er's capability to withstand
outside attacks. But statistically, most break-ins are inside jobs (carried out
by disgruntled employ ees or simply unscrupulous users) by a perpetrator
who already has some access rights but enlarges them and obtains access to
of f -limit areas. Hackers can also obtain an account with minimal access
rights, which they can then raise to take adv antage of the v ulnerabilities in
the access-rights assignment procedures. Consequently, y ou should apply
both remote scanning to detect loopholes that can be used to enter the sy stem
and local scanning to detect conf iguration errors that can be used to expand
access priv ileges.
Both hackers and administrators can use security analy zers. Hackers use
them to detect v ulnerabilities they can get hold of to penetrate the sy stem
and administrators use them to close such v ulnerabilities. If y ou are an
administrator, y our task is to f ind and patch the v ulnerabilities bef ore they
are f ound and used by hackers.
This command will f ind all f iles that hav e 02000 or 04000 rights, which
corresponds to the SUID or SGID bits set. The f ollowing is an example of
the command's execution: 130337 64 -rwsr-xr-x 130338 32 -rwsr-xr-x
130341 36 -rwsr-xr-x 130365 20 -rwsr-xr-x ...
1 root root 1 root root 1 root root 1 root root 60104 Jul 29 2002 /bin/mount
30664 Jul 29 2002 /bin/umount 35040 Jul 19 2002 /bin/ping 19072 Jul 10
2002 /bin/su
The most dangerous thing security -wise in this list is that all of the programs
hav e root permissions and can be executed by a user or a group member.
There are programs with SUID and SGID bits set that belong to other users in
the sy stem, but most hav e the root ownership.
If , af ter the initial paring, there are still many priv ileged programs lef t, I
recommend clearing the bits f or all programs. This will make it impossible f
or users to mount dev ices or change their passwords. But do they need these
serv ices? If some of them need some of these serv ices, y ou can alway s giv
e them these by resetting the SUID bit.
You can also change programs' ownerships to less priv ileged accounts. Ev en
though this is dif f icult to implement, because y ou will hav e to change quite
a f ew permissions, y ou will sleep better at night.
The LSAT program comes as the source code, and can be downloaded f rom
http://usat.sourceforge.net. When this book was written, v ersion 0.9.2 of
the program was av ailable. Both TGZ and ZIP archiv es are av ailable. I
recommend the f ormer, because the TGZ f ormat is nativ e to Linux and is
easier to install.
The f irst command unpacks the archiv e. Your f ile name can be dif f erent
depending on which v ersion of the program y ou download. The second
command starts conf iguration, and the last one builds one executable f ile f
rom the source code.
The program is launched by the f ollowing command:
./lsat-0.9.2.tgz/lsat
Now y ou can brew a pot of cof f ee and hav e a f ew cups of it. The checking
process is quite lengthy, especially on older machines. The utility can be run
with one of the f ollowing options:
-o <filename>— Specif ies the f ile, into which to place the report. The def
ault report f ile is lsat.out.
-v— Produce a v erbose report.
-s— Specif ies the silent mode, which is conv enient when running the utility
with the cronserv ice.
-r — Specif ies to check RPM integrity. This option is v alid f or the Red Hat
or Mandrake distributions only. The option is used to v erif y the distribution
package v alidity.
The LSAT utility is optimized f or running Red Hat sy stems because it has a
built-in f eature f or working with a database or RPM packages, which are a
distinctiv e f eature of Red Hat Linux and its clones.
When the utility is running, the check it display s messages like the f
ollowing: Starting LSAT...
Getting system information...
Running modules...
Running checkpkgs module...
...
...
Running checkx module...
Running checkftp module...
Finished.
Check lsat.out for details.
Don't forget to check your umask or file perms when modifying files on the
system.
These messages prov ide no security inf ormation and only inf orm y ou
which modules are being checked. The scanning results are sav ed to the
./lsat.out f ile. I ran the utility on my sy stem right af ter a f resh install and it
packed 190 KB of inf ormation into this f ile. That's plenty of inf ormation to
pore ov er and get to know y our sy stem better.
There are many recommendations in the output f ile. At the beginning, there
are recommendations about which packages should be deleted, as in the f
ollowing:
****************************************
Please consider removing these packages.
sendmail-8.11.6-15.asp
portmap-4.0-41
bind-utils-9.2.1-1.asp
nfs-utils-0.3.3-5
pidentd-3.0.14-5
sendmail-devel-8.11.6-15.asp
sendmail-cf-8.11.6-15.asp
ypbind-1.10-7
ypbind-1.10-7
Indeed, some packages are not reliable. For example, bugs are constantly
discov ered in the sendmail program; theref ore, LSAT suggests remov ing
this program.
There was the f ollowing comment in the output f ile that I especially liked:
default init level is not set to 5. Good.
The utility 's dev eloper reckoned that graphical operation mode is less
secure. Indeed, running a graphics shell means running additional programs,
and y ou already know that any additional program is an extra chance f or
something to go wrong. The text mode uses less memory, requires f ewer
resources, and runs f ewer programs, which means that it is a f aster and more
secure.
Further down the output f ile listing, there is a list of all SUID and SGID f
iles in the sy stem.
Still f urther, there is a list of f iles accessible to ev ery one:
**************************************** This is a list of world
writable files /var/lib/texmf/ls-R
/var/www/html/cache/archive/index.html
/var/www/html/cache/categories/category.cgi
/var/www/html/cache/categories/index,html
/var/www/html/cache/download/download-2-1.cgi
/var/www/html/cache/download/download-3-1.cgi
/var/www/html/cache/download/download-4-1.cgi
Any user, ev en the one with the humblest access rights, can modif y these f
iles. Right below this list, there is a list of f iles, to which users of any groups
can write. Check whether all of these f iles should be av ailable f or writing to
all users. Ideally, there should be no such f iles. Any f ile should be
accessible f or writing f or its owner only, or f or a user of the owner group at
the worst, but in no case should they be writeable f or ev ery one.
The output f ile is in a conv enient and easy -to-read f ormat; at the end,
howev er, there is a f ly in the ointment. Perhaps, it's more of a mosquito than
a f ly : The report section on the modif ications in the f ile sy stem detected
since the prev ious check is dif f icult to understand. All changes are heaped
into one pile without dif f erentiating, which are serious and which are
unimportant. For example, deleting or adding f iles to the /tmp directory is
not that important f rom the security standpoint, because this is done
constantly in this directory. Changes in the /etc directory are much more
important to security and ought to hav e been set of f .
The preceding directiv es redirect serv ices to the Klaxon utility and y ou can
log who and when attempts to access these serv ices.
This is usef ul because the remote command execution (REXEC) serv ice is
not needed f or regular users and is mostly sought by hackers to penetrate the
sy stem. If an attempt, ev en an unsuccessf ul one, to access the REXEC serv
ice was made f rom some address, y ou should make a note that someone f
rom this IP address is casing y our serv er f or v ulnerabilities, and keep y our
ey es open f or it.
I recommend installing Klaxon on no more than three serv ices, because too
many ports may cause the hackers to become suspicious. Moreov er, with
Klaxon installed on more than f iv e ports, repeated scanning can div ert sy
stem resources to Klaxon, resulting in a successf ul DoS attack.
The PortSentry Utility
This program comes in source codes and has to be extracted f rom the archiv
e at sourcef orge.net/projects/sentry tools and compiled. This should present
y ou with no dif f iculties.
In my case, the program was extracted into the portsenty _beta directory. The
directory name may be dif f erent on y our machine because the program v
ersion may hav e changed by the time this book is published. The extraction
directory and the f ile being extracted are display ed during the extraction
process in thedirectory_name/file_namef ormat.
Open the newly -created directory with the source codes and execute the f
ollowing command in it:
cd portsentry_beta
The PortSentry program works under all UNIX-like sy stem, such as Solaris,
FreeBSD, OpenBSD, and, of course, Linux. When compiling the program, y
ou hav e to explicitly specif y the operating sy stem installed: make linux
By def ault, the program is installed into the /usr/local/psionic directory ; the
install directory, howev er, can be changed by specif y ing the necessary
directory as the v alue f or theINSTALLDIRparameter in the Makef ile f ile.
The executable f ile is built by the f ollowing command:
make install
To v iew the logs created by the utility, y ou also hav e to install the
Logcheck program. It is av ailable f rom the same site as the PortSentry
program. It is installed in the same way as the PortSentry utility using the f
ollowing commands:
tar xzvf logcheck-1.1.1.tar.gz
cd logcheck-1.1.1
make linux
make install
By def ault, the Logcheck program installs into the /usr/local/etc directory.
The directory can be changed by editing theINSTALLDIRparameter in the
Makef ile f ile.
For example, f or monitoring ports the conf iguration f ile contains three
portmonitoring options. To enable monitoring of the selected ports, remov e
the pound sign (#) f rom the corresponding entry. For example, the
uncommented third port-monitoring option looks like the f ollowing:
TCP_PORTS="1,11,15,79,111,119,143,540,635,1080,1524,2000,5742,6667"
UDP_PORTS="1,7,9,69,161,162,513,635,640,641,700,32770,32771,32772"
The f irewall most of ten used in Linux is ipchains. It is conf igured by the f
ollowing directiv e:
KILL_ROUTE="/sbin/ipchains -I input -s $TARGET$ -j DENY -l"
Bef ore doing this, make sure that the f irewall is installed at the specif ied
directory (/sbin/ipchains). This can be done by executing the f ollowing
command:
which ipchains
The f irst command launches monitoring of the TCP ports, and the second
one starts monitoring of the UDP ports. All activ ities of the program are sav
ed in a log f ile, which can be v iewed using the Logcheck program. I
recommend that this program to be scheduled execute regularly (no less f
requently than ev ery 15 minutes) and inf orm the administrator about sy stem
happenings.
To test the program, I conf igured it as described prev iously and started the
Cy D NET Utils (www.cydsoft.com) port scanning utility. It showed only the
f irst two ports as opened. Ev en though more than one port had been open,
the rest of them were closed f or the port-scanner program. On the Linux serv
er, I executed thecat /etc/hosts.denycommand to v iew the /etc/hosts.deny f
ile, which stores the IP addresses of all computers prohibited to connect to
the serv er.
The last entry in the display ed f ile contents was the IP address of the
computer, f rom which I conducted the port scanning:
ALL: 192.168.77.10
It must be said that some ports can be used intensiv ely enough in the process
of normal operations f or the program to interpret this as a break-in attempt.
Such are the ident (113) and NetBIOS (139) ports. It is best if these ports are
not included in the list of ports to monitor. Find the
ADVANCED_EXCLUDE_TCPandADVANCED_EXCLUDE_UDPentries
in the /usr/local/psionic/portsentry /portsentry.conf f ile and add the necessary
ports to the lists. By def ault, the f ollowing ports are excluded f rom
monitoring: ADVANCED_EXCLUDE TCP="113,139"
ADVANCED_EXCLUDE UDP="520,138,137,67"
As y ou can see, ports 113 and 139 are already excluded f rom being
monitored.
Installing LIDS is not an easy task because it requires patching the kernel
source code, compiling the patched codes, and installing the kernel. Here is
where some problems may be encountered, because there is no guarantee that
the patched kernel will work as intended. The source codes may become
corrupted and not compile. When a new kernel v ersion is introduced, it
should be tested on a test machine bef ore installing it on the production sy
stem. There still is a chance that the new kernel will not work properly on the
production machine ev en af ter it has been checked on a test machine. But
not updating the kernel is not an option, because f ailure to do this may result
in f aulty operation in the f uture.
You can obtain detailed inf ormation on LIDS at the utility 's of f icial site
(www.lids.org).
12.5. Logging
Linux activ ities are recorded into sev eral logs, and the inf ormation logged
can rev eal many interesting things. For example, y ou can use the log inf
ormation to discov er hackers, when they entered y our sy stem, where they
came f rom, what they did in the sy stem, when they lef t, and other important
things. Because logs are one of the security tools, I will consider them in
more detail. This inf ormation will allow y ou to exercise tighter control ov er
y our domain.
Inf ormation about current sy stem users is stored in the /v ar/run/utmp f ile.
Howev er, try ing to v iew this f ile — using, f or example, thecatcommand
— will not produce any legible results. Data in the f ile are stored not in the
text but in the binary f ormat and can be v iewed only with the help of special
commands (programs). Some of these commands are giv en here.
The f irst entry tells y ou that user robert is using terminal one (tty l) and
entered the sy stem on December 8 at 10:15.
Most hackers execute this command when entering a sy stem to see whether
the administrator is logged in. If they see that the root user is in the sy stem,
beginning hackers hightail it because they are af raid their knowledge is not
suf f icient to remain in the sy stem undetected.
This is y et another reason y ou should not log into the sy stem as root. You
are better of f logging in as a regular user; y ou can alway s switch to a priv
ileged user when y ou need more rights. For a priv ileged user in my sy stem,
I created a user account named something other than root and set its UID to
zero. Using this account, I hav e complete access to the sy stem y et do not
adv ertise being there. This way I can lay in wait f or unsuspecting hackers
and observ e their actions to learn how they obtained access to my sy stem.
This inf ormation is also stored in the /v ar/run/utmp f ile, but only while the
user is logged in; it is deleted when the user logs out. The permanent history
of logins is stored in the /v ar/log/wtmp f ile. This is a binary f ile, and its
contents can only be v iewed using special programs.
The last Command
The lastcommand shows when a certain user logged into (and logged out of )
the sy stem. The command takes a user name as the parameter. For example,
the f ollowing command shows the login history f or user robert: last robert
The command's execution produces results looking like the f ollowing: robert
tty1 Thu Dec 2 12:17 - 12:50 (00:33)
From this entry, y ou can tell that the user took the tty l terminal, logged into
the sy stem on December 2, and remained logged f or 33 minutes, f rom
12:17 to 12:50. If a user logged into the sy stem ov er the network, inf
ormation about the host, f rom which the login was made, will also be shown.
Username root
bin
daemon
adm
lp
sync
shutdown halt
mail
news
uucp
operator games
gopher
ftp
nobody
vcsa
mailnull rpm
xfs
apache
ntp
rpc
gdm
rpcuser Port From Latest
ftpd2022 192.168.77.10 Mon Feb 21 12:05:06 +0300 2005
**Never logged in** **Never logged in** **Never logged in** **Never
logged in** **Never logged in** **Never logged in** **Never logged in**
**Never logged in** **Never logged in** **Never logged in** **Never
logged in** **Never logged in** **Never logged in** **Never logged in**
**Never logged in** **Never logged in** **Never logged in** **Never
logged in** **Never logged in** **Never logged in** **Never logged in**
**Never logged in** **Never logged in** **Never logged in** nscd
**Never logged in** ident **Never logged in** radvd **Never logged in**
squid **Never logged in** mysql **Never logged in** flenov ftpd2022
192.168.77.10 Mon Feb 21 12:05:06 +0300 2005 named **Never logged
in** robert tty1 Mon Feb 21 12:10:47 +0300 2005
User name taken f rom the /etc/passwd f ile The port or terminal, to which the
connection was made The computer's IP address f or network logins The
login time
This command can be used to control sy stem accounts. Their latest login
time is shown as**Never logged in**, because these accounts cannot be used
to log into the sy stem (they hav e dummy command-interpreter shells such
as /bin/f alse, /dev /null, and /sbin/nologin). If y ou notice that one of these
accounts was used to log into the sy stem, this means that hackers changed
the account's conf iguration settings and are using it to work in the sy stem.
Simply changing the command shell f or the /etc/passwd f ile will create a
back door unseen by the administrator. But executing the lastlogcommand
will bring these machinations with the sy stem accounts to light.
init 1 root txt REG init 1 root mem REG init 1 root 10u FIFO keventd 2 root
cwd DIR keventd 2 root rtd DIR kapmd 3 root 10u FIFO 3,2 26920 635256
/sbin/init 3,2 89547 553856 /lib/ld-2.2.5.so 3,2 195499 /dev/initctl 3,2 4096 2
/
3,2 4096 2 /
3,2 195499 /dev/initctl
But this list is f ar f rom being complete. Ev en if there is only one user
currently logged into the sy stem, there can be a couple of dozen f iles open.
But if there are sev eral users logged in, the number of open f iles increases,
because the same f ile can be opened more than once by dif f erent users.
These are mostly sy stem conf iguration f iles.
The /v ar/log/messages f ile contains the main inf ormation about user logins,
f ailed authorizations, launches and shutdown of serv ices, and so on. Inf
ormation about all of these ev ents cannot f it into one f ile and is split into
sev eral messages.X f iles, where X is the f ile number.
This is the most important log f or any administrator. If hackers try to pick
the password to some account, y ou will be able to notice this because the f
ile will grow rapidly and contain numerous f ailed authorization entries. Fig.
12.1 shows an example of the contents of this f ile.
Another text log is stored in the /v ar/log/secure f ile. This is the most
important f ile and y ou should check it as of ten as possible, pay ing close
attention to each entry. This f ile contains inf ormation about remote logins to
the sy stem: who, when, and f rom what IP address. For example, y ou may
discov er an entry of the chief accountant connecting to the FTP serv er but f
rom an address that does not belong to him. This is enough to sound the
alarm.
The same f ile contains inf ormation about changes to the user and group
lists. Hackers seldom use the root account f or their dirty deeds, creating an
inconspicuously -named but zero UID account. If such an account was
created not manually, by editing the corresponding f iles, but with the help of
Linux commands, this activ ity will be logged in the /v ar/log/secure f ile.
Hackers know about this and, theref ore, add users manually. Af ter all, this is
not that dif f icult: All it takes is to add a single entry to the /etc/passwd and
/etc/shadow f iles. But ev en then, spotting a user logging in that y ou did not
create, y ou can suspect something goes wrong.
The log of the sendmail mail serv er is stored in the /v ar/log/maillog f ile.
The inf ormation in the f ile is stored in the f ollowing f ormat:
Jan 16 13:01:01 FlenovM sendmail[1571]: J0GA11S01571: from=root,
size=151, class=0, nrcpts=l,
msgid=<[email protected]>, relay=root@localhost
The f ile contains inf ormation about by who, when, and to whom messages
were sent.
But although logs can be inf ormativ e, they cannot be relied on. Smart
hackers alway s clear away their tracks and delete incriminating records f rom
the logs; thus, inspecting directories manually may be usef ul, but check the
log f irst.
The f ollowing is an example of the contents of the log f ile: Sun Jan 16
13:21:28 2005 1 192.168.77.10 46668 /home/flenov/ sendmail.cf b _ o r
flenov ftp 0 * c
FTP is the most dangerous protocol because it can be used to download conf
idential data (f or example, password f iles), or upload a hacker's data to the
serv er (f or example, a rootkit or a Trojan horse). You should learn to
understand each record in the log to know what happens to f iles in the sy
stem. The f unction of each parameter in the log is as f ollows:
A f ull date showing the day of week, month, date, time, and y ear.
The session duration or time taken to download or upload the f ile.
The name and IP address of the remote host. The f ile size in by tes.
The f ull path of the uploaded or downloaded f ile. The transmission ty pe
—af or ASCII orbf or binary.
File manipulations — Cmeans the f ile was compressed,U means the f ile was
uncompressed,Tmeans the f ile was process with the tar program, and _
means no f ile processing took place.
If y ou hav e nev er worked with the FTP log bef ore, I recommend that y ou
do this now and study caref ully the example entry and entries f rom y our
own FTP log. You alway s hav e to approach a problem already prepared and
not study it af ter it arises; otherwise, y ou are doomed to lose.
The number of by tes receiv ed by the client. The request method —GET,
POST, HEAD,orICP_QUERY. The URL of the requested object. Theidentf
ield (- if not av ailable).
The ty pe of the MIME contents. There are two other proxy serv er logs.
These are the f ollowing:
cache.log — This log stores inf ormation about the cache, sav ed and deleted
object, and the like. I hav e nev er experienced a need to consult this log.
useragent.log — This log stores records of the User Agent f ield f rom
request headers. This inf ormation can be f aked easily, and I hav e already
shown that this f ile can be easily changed f or squid requests.
Apache serv er logs are stored in the access.log and error.log f iles located in
the /v ar/log/httpd directory. These logs contain inf ormation about user
accesses and activ ities.
Logs are in the text f ormat and can be v iewed by any one, including
hackers. Because logs contain user passwords, they constitute a security
danger.
It is impossible to dispense with keeping the logs, because they are necessary.
But y ou should do ev ery thing possible to make them inaccessible to
unauthorized people. At the least, I alway s change the logs' def ault
directory. From my experience, hackers seldom examine the httpd.conf f ile
but look f or the logs in their def ault directories. If the logs are not there,
hackers think that they are disabled.
To simplif y creating such f iles, y ou can temporarily enable the logs in the
def ault directory to hav e them collect some inf ormation and disable them af
terwards.
# Log anything (except mail) of level info or higher. # Don't log private
authentication messages!
#.info;mail.none;authpriv.none;cron.none /var/log/messages
# The authpriv file has restricted access. authpriv.*
/var/log/secure
# Log all the mail messages in one place. mail.*
/var/log/maillog
# Log cron stuff. cron.*
/var/log/cron
# Everybody gets emergency messages. *.emerg
*
# Save news errors of level crit and higher in a special file. uucp,news.crit
/var/log/spooler
# Save boot messages also to boot.log.
local7.* /var/log/boot.log
The directiv es' f unctions can easily be deduced f rom the corresponding
comments. All directiv es hav e the f ollowing f ormat:
name.level
The namepart is the name of the parameter to be logged. These are the f
ollowing:
Messages of the specif ied lev el and higher are logged. For example, specif y
ing theerrlev el means that messages of theerr, crit, andemerg lev els will be
logged.
The more errors logged, the greater the hard disk workload and the more
resources used. To enhance the sy stem's productiv ity, it is adv isable to
place the /v ar partition, in which the logs are stored, on a separate hard driv
e. In this way, sy stem ev ents can be logged in parallel with the sy stem's
operation. Make sure, howev er, that the /v ar partition is large enough to
hold all logs.
Moreov er, in my sy stems, I mov e logs f rom their def ault location to make
it more dif f icult f or hackers to f ind them and delete the inf ormation about
their activ ities in the sy stem. But this is not enough. An experienced hacker
will examine the /etc/sy slog.conf f ile and discov er the new location of logs.
But y ou can pull a better one on hackers with only standard Linux means. In
my sy stem, I hav e a task scheduled in the cronserv ice that ev ery hour
makes a backup copy of the /v ar directory. In this way, ev en if the hackers
clean up the log I can alway s f ind out about them f rom the backup log
copies.
To send the log ov er the network, the /etc/serv ices f ile has to contain the f
ollowing entry :
syslog 514/udp
Moreov er, the f ollowing entry has to be added to the /etc/sy slog.conf f ile:
messages @address
The messagesparameter specif ies, which messages are to be sent to the serv
er. Specif y ing it as*.*will send all messages. To send only critical messages,
this parameter has to be set to *.crit.
The @addressparameter is the address of the serv er, to which the messages
are to be sent. For example, the f ollowing entry sends all messages to the
log.myserver.com serv er:
*.* @log.myserver.com
Finally, the syslogserv ice has to be started with the -roption, which allows
the serv er to receiv e messages f rom the network and record them in its logs.
For this, the script f or launching the serv ice has to be changed on the serv
er. As y ou should remember, all scripts are stored in the /etc/rc.d/init.d
directory ; the script f or the syslogdserv ice is stored in the sy slog f ile.
Listing 12.3shows the main contents of this f ile.
# Source config
# Loading the configuration file if [ -f /etc/sysconfig/syslog ] ; then
. /etc/sysconfig/syslog
else
SYSLOGD_OPTIONS = "-m 0"
KLOGD_OPTIONS = "-2" fi
RETVAL=0
umask 077
start() {
echo -n $"Starting system logger: "
daemon syslogd $SYSLOGD_OPTIONS
RETVAL = $?
echo
echo -n $"Starting kernel logger: "
daemon klogd $KLOGD_OPTIONS
echo
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/syslog return $RETVAL
}
stop() {
# Commands to stop the service
}
rhstatus() {
# Commands to output the status }
restart() {
stop
start
}
...
...
. /etc/sysconfig/syslog
else
SYSLOGD_OPTIONS = "-m 0" KLOGD_OPTIONS = "-2"
fi
Here, in the ifblock, a check is perf ormed on whether the /etc/sy sconf ig/sy
slog f ile exists. If so, the loading parameters are taken f rom this f ile;
otherwise, they are specif ied explicitly in the elseblock:
SYSLOGD_OPTIONS = "-m 0"
The parameters are specif ied within the quotation marks. The -roption is
added, modif y ing the directiv e as f ollows:
SYSLOGD_OPTIONS = "-m 0 -r"
If the /etc/sy sconf ig/sy slog f ile exists, it will contain the
SYSLOGD_OPTIONS="-m 0"entry and y ou will only hav e to modif y this
entry, without hav ing to tamper with the /etc/rc.d/init.d/sy slog launch script.
This problem is easily solv ed by encry pting the message traf f ic, sending it
through an SSL tunnel. The simplest way of doing this is as f ollows:
1. In the conf iguration f ile of the serv er sending log messages, specif y the
local computer as the one, to which all messages should be sent as f ollows:
*.* @localhost
2. This will result in all messages being sent to the local computer to UDP
port 514. The serv er must not be operating in the message receiv ing mode;
that is, the -r option must not be specif ied in the launch script. Otherwise,
port 514 will be busy, which is not what y ou need.
All messages receiv ed at this port will be encry pted and sent to port 1050 of
the logservercomputer, where logserveris the address of y our log message
receiv ing serv er.
Now, all log messages will be sent ov er the network encry pted.
1. When the size of the /v ar/log/messages f ile exceeds the maximum size, or
when a certain period lapses, the contents of the current log are transf erred to
the /v ar/log/messages.1 f ile, and the /v ar/log/messages f ile is cleaned and
reused to log messages.
2. The next time one of the threshold v alues is reached, the contents of the /v
ar/log/messages.1 f ile are transf erred to the /v ar/log/messages.2 f ile and the
contents of the /v ar/log/messages f ile are transf erred to the
/v ar/log/messages.1 f ile. The process is repeated ev ery time one of the
critical v alues is reached.
In this way, log messages are stored in separate f iles, each of which does not
exceed a certain size, making logs conv enient to v iew.
The conf iguration f ile of the Logrotate utility (/etc/logrotate.conf ) is shown
in Listing 12.4.
Listing 12.4: The configuration file of the Logrotate utility
(/etc/logrotate.conf)
# See "man logrotate" for details.
# Rotate log files weekly. weekly
# Keep 4 weeks worth of backlogs. rotate 4
# Create new (empty) log files after rotating old ones. create
# Uncomment this if you want your log files compressed. #compress
# RPM packages drop log rotation information into this directory. include
/etc/logrotate.d
weekly — Specif ies that log f iles are to be rotated weekly. If the serv er's
workload is light, this v alue can be changed to monthly.
rotate — Indicates the number of f iles f or storing the logs. In this case it is f
our, meaning that there will be f our numbered log f iles — /etc/log/name. 1
through
/etc/log/name.4 — in addition to /etc/log/name.
create— Notes that a new log f ile is to be created immediately af ter the
rotation.
compress — Specif ies to compress the old v ersions of the log f iles. This
option is usef ul f or serv ers with heav y request workloads, generating bulky
logs. Because logs contain text inf ormation, compressing them reduces their
size by 70% and more.
The def ault v alues are described at the beginning of the f ile. Af terwards,
necessary v alues f or particular logs are specif ied. In this conf iguration f ile,
specif ic parameters are set f or the /v ar/log/wtmp log f ile:
/var/log/wtmp {
monthly
create 0664 root utmp
rotate 1
Here, the maximum log f ile size is not specif ied; this, howev er, can be done
using the sizeparameter. For instance, in the f ollowing example the
maximum size of the log f ile is set to 100 KB:
/var/log/wtmp {
monthly
size = 100k
create 0664 root utmp
rotate 1
}
Now the log f ile will be rotated whenev er one of the f ollowing two ev ents
occurs:
Monthly When the f ile size reaches 100 KB
Attempting to protect the log f ile by increasing its size is useless, because
hackers will not generate messages manually but can use a simple Perl
program or ev en a script containing shell commands. The latter program is
really simple. All it has to do is loop through the loggercommand (which logs
messages), as f ollows:
logger -p kern.alert "Message_text"
Running this command in an endless loop will make the sy stem to destroy
the log f ile.
To prev ent log data f rom being destroy ed, y ou can specif y a script to send
the log to the administrator's email address as f ollows:
/var/log/wtmp {
monthly
size = 100k
create 0664 root utmp
postrotate
In this case, af ter the log f ile is rotated and the main log f ile is renamed to
name.l, the script is executed to send the latter f ile to the administrator's
email address.
When emailing log f iles, make sure that y our mailbox is large enough. For
example, if the maximum size of the log f ile is 10 MB but y our mailbox can
only take 5 MB of messages, y ou will nev er receiv e this f ile because it will
be deleted by the sy stem.
All commands executed by users are logged in the .bash_history f ile (when
the /bin/bash command interpreter is used), which is located in the user's
home directory. If y ou know which user account hackers used to break in to
the sy stem, y ou can trace all their actions with the help of this log.
You will be able to tell what commands or programs were run, and this inf
ormation may be helpf ul in determining how the hackers penetrated the sy
stem and what they may hav e changed in it. If the hackers added a user or
modif ied some important sy stem f ile, y ou will be able to see this, return ev
ery thing back to normal, and close the holes in the sy stem used by the
hackers to get in.
Prof essional hackers who earn their liv ing breaking in to computer sy stems
know this and do ev ery thing possible to hide their tracks and regularly clean
up this f ile. Extraneous changes in the .bash_history f ile may serv e as an
indication that this account was used by the hackers to break in to the sy
stem.
You should also regularly check and clean user logs y ourself . Users,
including y ourself , may make a mistake when issuing a command and
include y our password with it. Hackers can discov er this password when
analy zing the .bash_history f ile and use it f or nef arious purposes.
If y ou specif ied the root password when entering a command, take y our
time to delete the corresponding entry f rom the user log. Leav ing it there
may cost y ou dearly.
Note
If y ou work with a My SQL serv er, there will be the .my sql_history f ile in
addition to the .bash_history f ile in y our home directory. This f ile stores all
commands executed in the My SQL conf iguration program. If any
passwords were entered during the My SQL conf iguration process, their
corresponding records must also be cleaned f rom the my sql log f ile. Ev en
though a database is not the sy stem, it can serv e as a beachhead f or
breaking in to the sy stem; moreov er, databases can contain conf idential
data, such as passwords to restricted sections of Web sites.
If logs started suddenly growing in size, it means that there is some irregular
activ ity going on. Perhaps a DoS attack is being perpetrated. You should
immediately react to and inv estigate the causes of this increased activ ity
without waiting f or the situation to dev elop to the point where the serv er
will be ov erwhelmed and cease serv icing v isitors. Moreov er, if logs f ill
the disk, the sy stem may crash, so make sure y ou hav e enough disk space f
or logs.
The computer should not reboot on its own. If this happens, check the logs to
f ind out why and when it rebooted. You can use theuptimecommand to f ind
out how long the sy stem has been running.
When analy zing logs, pay attention to ev ery little thing. For example, to
pick a password, hackers can use dif f erent camouf laging tricks, such as
making f alse log entries.
If hackers try to pick a password using the enumeration method, there will be
many unsuccessf ul entry attempts by a certain user in the log. An unsuccessf
ul sy stem login attempt generates the f ollowing entry in the /v
ar/log/messages log:
Feb 12 17:31:37 FlenovM login(pam_unix)[1238]: authentication failure;
logname=LOGIN uid=0 euid=0 tty=ttyl ruser= rhost= user=root
The login (pam_unix)parameter indicates that the hacker was only try ing to
login. If the hacker was already in the sy stem but used thesucommand
unsuccessf ully, thelognamef ield will contain the user name, under which the
hacker entered the sy stem, and thelogin (pam_unix)string will be replaced
withsu (pam_unix).
By this entry, y ou can easily determine that it was generated by hackers, and
easily locate them. But hackers can also easily insert f ake entries in the log
pointing to another user, making it dif f icult to pinpoint the real ones. For
example, executing the f ollowing command, hackers can add an entry to the
log identical to an authentication f ailure entry :
logger -p kern.alert -t 'su(pam_unix)' "authentication failure ; logname=robert
uid=0 euid=0 tty=tty1 ruser= rhost= user=root"
The preceding command will create an entry similar to the f ollowing in the
log:
Feb 12 17:31:37 FlenovM login(pam_unix)[1238]: authentication failure;
logname=robert uid=0 euid=0 tty=tty1 ruser= rhost= user=root
Now imagine that hackers executed many such commands but with a dif f
erentlognamef ield in each. It will be practically impossible to determine,
which log entries are real and which are f akes.
A less experienced hacker may mess up and not use the -toption when using
theloggerprogram, instead entering the command as f ollows: logger -p
kern.alert "authentication failure ;
logname=robert uid=0 euid=0 tty=tty1 ruser= rhost= user=root"
The key word loggerbef ore the error message tells y ou that the entry was
generated by the loggerprogram and is, most likely, a f ake.
But ev en if the hackers hav e no access to the loggerprogram, they can use a
program of their own to place f ake entries into the log. To prev ent this, only
the root administrator should hav e write rights f or the log f iles.
12.6. Handling Logs
By now, y ou know what sy stem logs there are, where they are stored, and
the nature and f ormat of their contents. All this inf ormation is usef ul, but
analy zing sev eral megaby tes of text is inconv enient and dif f icult.
The most ef f ectiv e log-analy zing programs are those that analy ze log
entries as they are recorded in the log. This is relativ ely simple to implement,
especially on a remote computer that receiv es log entries f rom the serv er ov
er the network. As entries come in, they are analy zed and recorded in the log
f iles f or storage and more detailed f uture analy zes. It is usually dif f icult to
detect an attack by one sy stem message, and sometimes a dy namic picture is
necessary. For example, one f ailed authorization attempt does not mean any
thing, while ten or more attempts look quite suspicious.
Unf ortunately, all known log-analy zing sof tware cannot do ef f ectiv e dy
namic analy sis. Most of this sof tware only create rules, according to which
certain entries are considered either suspicious or not. Theref ore, all f ailed
sy stem login entries are considered suspicious and are subsequently analy
zed manually. Ev ery day, at least one user hits the wrong key when entering
the password, especially if it is a complex one. It would make no sense to
react to all such messages.
There is another shortcoming to analy zing logs line by line. Suppose that the
log-analy zing utility issued a message inf orming of an attempt to access a
restricted disk area. Such log entries f or most serv ices will contain only inf
ormation about the attempt, not inf ormation about the user account used.
This command display s updates to the log f ile in real time; that is, whenev
er a new entry is added to the log, the utility display s it.
This is conv enient if only a f ew entries are recorded into the log. In this
way, y ou can work in one terminal and periodically switch to the other to
check the new log messages. But if there are too many sy stem messages
(e.g., many users are working with the serv er), checking all new entries
becomes impossible. In this case, y ou need a special utility to f ilter the
messages and display only those deemed suspicious.
The program can analy ze log entries on the schedule (if the program is
scheduled in thecrontask manager) or immediately upon their being entered
into the log.
The installation process is dif f erent because Swatch is a Perl program. This
is done by executing the f ollowing sequence of commands:
tar xzvf swatch-3.1.tgz cd swatch-3.1
perl Makefile.PL
make test
make install
make realclean
That the program is written in Perl is also its shortcoming. I had already
mentioned that any sof tware that can be used by hackers to enter the sy stem
should not be installed on the serv er unless necessary. The Perl interpreter is
necessary f or a Web serv er using scripts written in this language. In other
cases, I recommend against installing a Perl interpreter because hackers of ten
use this language f or writing their own rootkits.
The powerf ul f eatures of the program make it more dif f icult to conf igure.
This is a shortcoming, because conf iguration errors may result in an
important ev ent going undetected.
The program is user-f riendly, but I am concerned about its f uture. It looks
like there will be no more updates, and sooner or later the current f eatures
will not be enough and a substitution will be necessary.
But I hav e high hopes f or the prospects of the program. Its operation was
considered inSection 12.4, when considering the operation of the PortSentry
12.7. Log Security
I want to conclude the sy stem-message logging topic with a section about
their security. Ev en though the original purpose of logs was to monitor the sy
stem and detect attacks, they can also be used to break in to the sy stem.
The results produced by the command look similar to the f ollowing: drwxr-
xr-x 9 root root drwxr-xr-x 21 root root drwx-----2 root root
-rw-r----1 root root
-rw-r----1 root root
-rw-r----1 root root
-rw-r----1 root root 4096 Jan 12 13:18 .
4096 Jan 24 23:00 ..
4096 Jan 12 11:14 bclsecurity
The owner of all f iles should be root. Also, make sure that only the
administrator has f ull access rights, with the rest of the users unable to work
with the f iles.
By def ault, the read rights f or most f iles belong to the owners and the
members of the owner group. The logs most of ten belong to the root group.
If in y our sy stem only the administrator belongs to this group, y ou hav e no
cause f or alarm. But if this group comprises sev eral users, which I am
against, a special group with minimal rights has to be created and all logs
must be switched to this group.
Only the administrator should hav e the read and write rights to the f iles in
the /v ar/log directory. The group users should only hav e the read rights,
with the others hav ing no rights. To set these permissions to all log f iles,
execute the f ollowing sequence of commands:
cd /var/log
find . -type f | xargs chmod 640
The f irst line consists of two commands. The f irst command — find . type f
— searches the current directory f or all f-ty pe objects, that is, f or all f iles.
The second command — xargs chmod 640— changes the access permissions
of all objects f ound by the f irst command to 640. These permissions can ev
en be lowered to 600 to giv e the read and write rights to the administrator
only.
Moreov er, no user should hav e read rights to the /v ar/log/ directory, so as to
prev ent unauthorized deletion of the log f iles. If hackers cannot modif y log
records, they may settle f or the second best: deleting the logs themselv es.
True, deleted logs are a strong indication that someone unauthorized v isited
y our sy stem. But it's a small consolation, because without the log inf
ormation y ou will not be able to learn how the break-in was perpetrated and f
ind the culprit.
Remember, if hackers can read the logs, they can use the inf ormation
recorded in them accidentally to raise their rights in the sy stem. If hackers
can modif y the logs, they can cov er their tracks by deleting all entries
pertaining to their activ ities.
But it is not enough to prov ide maximum protection. The essence of logging
is that the operating sy stem only adds new entries to the log f iles; it neither
deletes the f iles nor modif ies the entries already logged in them. Thus, log f
iles can be f urther protected f rom being deleted or modif ied with the help of
f ile attributes. File attributes in the Ext2 and Ext3 f iles sy stems can be
expanded with the help of thechattrcommand. One such expanded attribute is
that the f ile can be only added to. It is set by executing the chattrcommand
with the+aoption. For example, the f ollowing command sets this attribute to
the /v ar/log/boot.log f ile:
chattr +a /var/log/boot.log
Now, try ing to delete or modif y the f ile will be unsuccessf ul. The only
shortcoming of this attribute is that y ou will not be able to clean the f ile.
Log f iles hav e a tendency to grow constantly and rather rapidly, but usually
it is not necessary to sav e a record of ev ents that took place a month or ev en
a y ear ago. To clean up, remov e the add-only attribute as f ollows: chattr -a
/var/log/boot.log
The easiest way of doing this is to use the nmaputility. It allows the ping
command to be executed f or the entire network, thus rev ealing, which serv
ers and computers are currently accessible. If some computer has not
responded, y ou hav e to inv estigate the causes of this. Perhaps, this is only
because of a power loss or unscheduled reboot. But it may also be caused by
a successf ul DoS attack, and y ou should be the f irst one to know about this.
Unf ortunately, despite my extensiv e search on the Internet, I hav e not been
able to f ind any comparable Linux program and I assume there is none.
Thus, until one is dev eloped, the nmaputility remains y our only choice f or
network monitoring under Linux. Despite its inconv enience, it is better than
nothing.
Many administrators are just too lazy and place their trust into equipment
instead of backing up their data. No argument: Modern equipment is more
reliable than that of just a f ew y ears ago. Howev er, in the last couple of y
ears, I witnessed sev eral hard driv es dy ing, f iv e computers stolen f rom
the of f ice, and ev en one serv er rack burned up — along with the room it
was housed in. And who among the occupants of the great New York towers
could hav e imagined that terrorists would decide to v ent their anger on their
of f ices? Of course, the loss of inf ormation doesn't come any where close to
comparing with the loss of human liv es. I am just using this case to call y our
attention to how data loss can result f rom unanticipated causes. You should
take ev ery precaution to preserv e it regardless of the situation.
Data backup copy ing, or simply backing up, inv olv es making a temporary
copy of digital inf ormation f or recov ery purposes. Backing up data
regularly allows y ou to restore lost data f rom the backup copy and continue
working with negligible losses.
Equipment failure — When I was just cutting my teeth in the computer f ield,
5-inch diskettes and hard driv es of no more than 20 MB were used to store
inf ormation. Although hard driv es were suf f iciently reliable, diskettes were
constantly f ailing. Switching to 3.5-inch diskettes did not change the
situation much, but the reliability of hard driv es continued to improv e.
When the capacity of hard driv es started measuring in gigaby tes, the bad
block problem arose. At one time, I had to change three hard driv es, f rom 10
GB to 20 GB, f rom dif f erent manuf acturers. This was like a data-destroy
ing locust incursion. Af ter a certain period of hard driv e f ailures, their
reliability began improv ing. It cannot, howev er, be called ideal, and there is
alway s a chance of a hard-driv e f ailure.
Natural disasters and equipment loss — Many destructiv e ev ents can cause
equipment loss. If y ou look at the period f rom the end of 2004 to beginning
of 2005, y ou will notice that natural disasters — f loods, tornados,
earthquakes, hurricanes, tsunamis — hav e been hitting our planet at an
increased rate and with a greater intensity. Natural disasters can destroy
houses, buildings, and ev en entire cities, as was the case with New Orleans.
You may say that against the background of lif e and property loss inf licted
by such disasters, data loss is insignif icant and irrelev ant. I disagree,
because ev ery little thing salv aged is of help. And if the data lost were
accumulated ov er y ears, their loss is quite signif icant.
Hacker and virus attacks — These are f acts of the inf ormation technology f
ield that cannot be ignored and hav e to be protected against. But no matter
what is done to f ight v iruses, they alway s hav e the upper hand. Why is this
so? Because the most common def ense against v iruses is to examine
suspicious sof tware f or code characteristic to known v iruses. The key word
here isknown.But hackers constantly keep dev eloping new v iruses and way s
to get around antiv irus sof tware. And it is new v iruses that inf lict the most
damage, because f or a certain period af ter they appear there is no def ense
against them. Losses inf licted by computer v iruses are becoming greater
each y ear. They can, howev er, be minimized with the help of data backup.
This list can hav e many items added to it, but I hope I hav e been able to
conv ince y ou of the necessity to hav e a backup copy of all of y our
important data. I consider important the f ollowing ty pes of data:
System configuration files — At f irst, it may seem that these f iles are not
important because they contain no conf idential company inf ormation. But
without such a backup, it will take y ou a long time to restore y our computer
or serv er f rom scratch. This means losses caused by serv ice unav ailability,
which f or some companies can amount to tens of thousands of dollars f or ev
ery hour of downtime.
Databases — Corporations keep their data in databases that make the inf
ormation conv enient to work with; should these data be lost, the corporation
would suf f er greatly.
Web sites — Any dy namically dev eloping Web site, f rom personal to
corporate, contains f iles and scripts, the loss of which can be f elt f
inancially.
Building a serv er cluster may be a more reliable choice. In this case, if one of
the cluster serv ers f ails, its workload is picked up by another serv er in the
cluster. This allows almost 100% f ailproof sy stem operation to be achiev ed.
But building serv er clusters is a rather complex and expensiv e task; theref
ore, companies try other, less expensiv e way s to make their data secure.
Most industrial sof tware already of f ers cluster operation tools, which are
easy and inexpensiv e to use. One of the network serv ers is assigned the role
of master, with one or more other serv ers being slav es. The master serv er
regularly sends inf ormation to the network about its operability status; it also
sends inf ormation about database changes to the slav e serv ers so that all
serv ers hav e an identical copy of the database. If the master serv er f ails,
the slav e serv ers take ov er the operation.
A less expensiv e way is to use reserv e serv ers equipped with a Redundant
Array of Independent Disks (RAID). In this case, the hard driv es of a serv er
are organized into mirroring RAID, that is, RAID 1 or RAID 1+0. Here, data
are protected by the RAID sy stem, which sav es data to two hard driv es in
parallel. If one of these driv es f ails, the second hard driv e is placed into
operation.
But what if the motherboard or processor f ails? Replacing these takes time,
which in this scenario was declared unacceptable. To minimize the downtime
in such a situation, a backup serv er of the same hardware conf iguration as
the main one is maintained. When some hardware of the main serv er f ails,
simply connect RAID to the backup serv er and switch the network cable to
continue operating. Because the hardware of the reserv e serv er is the same
as that of the main serv er, RAID will work on the backup serv er without f
orcing the administrator to edit the conf iguration f iles.
If there are sev eral identically -conf igured serv ers in y our network, one
backup serv er can be used f or any of them. Assuring data saf ety in this way
is much less expensiv e than building a serv er cluster.
The saddest part of the story is that the driv e had been f ailing f or some
time. The sy stem was issuing access errors when backups were perf ormed,
but these were simply ignored. The hard driv e started f ailing with the
partition used f or storing the backup copies, and with time all of the blocks
went bad.
The moral of this story is that y ou should alway s store the backup copy on a
separate medium. This can be a separate hard driv e, especially because their
prices are constantly dropping, or any remov able media of a suf f iciently
large capacity.
Another way is to take adv antage of one of the Internet serv ices of f ering
online storage, which lately hav e been picking up again. Hav ing placed y
our backup copy on such a driv e, y ou can be sure that it is saf e. The owners
of these serv ices use RAID technology on their serv ers, which giv es a high
degree of protection to the data stored on them.
I am conv inced that this ty pe of serv ice will continue to grow. One of the
reasons f or this is the iDisk technology f rom Apple, which of f ers easy -
touse Internet disks to MAC OS and Microsof t Windows sy stems users.
Other similar sy stems are being dev eloped and should be av ailable soon.
More inf ormation about the iDisk technology can be f ound on Apple's site
at www.mac.com/1/iTour/tour_idisk.html (see Fig. 13.1).
Figure 13.1: The
iDisk site
If y ou cannot af f ord to use online storage, y ou will hav e to prov ide media
f or storing y our backup copies y ourself .
You hav e a large choice of media f or this purpose, including remov able
hard driv es, magnetic tape, CD-R/RW, DVD-R/RW, and Jaz and ZIP disks.
Which of these y ou choose depends on the amount of data y ou must back up
and the speed, at which y ou must do this.
When planning the backup process, y ou should keep in mind that in case of a
hard driv e f ailure, all changes made since the last backup will be lost. This
means that especially important data should be backed up as of ten as
possible, but remembering that this process is burdensome f or the serv er.
The answers to the questions of how many media y ou will need f or backup
purposes, how of ten, and how to use them depends on many f actors,
including the f ollowing:
This list can be continued, but the items giv en here will suf f ice. I'll consider
them starting with the last one. You should hav e a clear idea of which data in
the sy stem are modif ied and how of ten. Group these data into three
categories: rarely modif ied, f requently modif ied, and those modif ied at
certain time interv als.
The f ollowing are the main directories that should be backed up:
Conf igurations f iles (those stored in the /etc directory ) can be placed into
the rarely -modif ied data category. They are rarely modif ied because in most
serv ers the main and the most extensiv e conf iguration changes take place at
the serv er installation stage. Af terwards, the serv er can work f or y ears
with the conf iguration changing only when the sof tware is updated or
corrections to the conf iguration are made.
To back up the conf iguration f iles, a slow, small rewritable medium will suf
f ice. I use ZIP or Jaz disks to back up the conf iguration f iles, which takes
only one diskette.
Because the conf iguration does not change of ten, modif ied f iles can be sav
ed right away. Only the modif ied f iles hav e to be sav ed to the disk.
The restoration process should start with restoring the conf iguration f iles,
with the /etc/passwd and /etc/shadow f iles being the f irst on the list. If these
f iles are not restored bef ore the other f iles, without the necessary users,
programs will not be able to set the proper access rights.
This will lead to the rights being restored incorrectly, especially if y ou are
using third-party right-assignment utilities. Bef ore making the restored sy
stem av ailable f or use, y ou should ascertain that all f iles are in the same
state they were in bef ore the f ailure; this especially concerns their
permissions.
Into the f requently modif ied data category can be placed databases and the
main user f iles and documents (those in the /home directory ). Most of these
are modif ied ev ery day. This data can and should be backed up ev ery day.
If the backup process takes too long, it should be perf ormed af ter work
hours or during lunch break, when the load on the serv er is reduced. The
backup can be perf ormed using scripts executed as scheduled tasks. Perf orm
backup twice a day (once at lunch time and once af ter work) so that in case
of a disk f ailure only half a day 's worth of data will be lost.
To back up this ty pe of data, I use sev en rewritable media, one f or each day
of the week. Ev ery Monday, data f rom all of the media is sav ed to a
readonly media, such as a CD-R or DVD-R, and the media is reused f or the
daily backup.
13.4.3. Periodically Modified Selected Data
Far f rom all f iles in the /home directory are changed ev ery day. Most of
them may not be changed f or y ears. So as not to waste y our time sav ing
these data, y ou can perf orm backup using commands that allow only the
changed data to be backed up. The simplest way of doing this is to select f or
backup only those f iles modif ied within a certain period.
When this policy is employ ed, the backup procedure is as f ollows: At the
end of week, the entire /home directory is backed up.
Only f iles that hav e been modif ied are included in the daily backups.
In this case, restoring should be carried out in the same order as the backup:
First, the weekly backup f iles are restored, and then each of the daily
backups, starting with the oldest. Not f ollowing the order carries a risk of
rewriting a f ile with its older v ersion.
Perf orming backup by the f ile modif ication date is conv enient but not
alway s possible. Most backup utilities only update an existing copy,
replacing the old v ersion of the f ile with the new one. In this case, f irst all f
iles are backed up and then the update is specif ied with a special key. Only f
iles that hav e been modif ied are updated in the complete backup in this way.
This is a handy method, but it replaces all old f iles. This makes it impossible
to roll back to the contents bef ore the last backup. To allow rollback, ev ery
day the complete backup is updated, it is sav ed to a separate medium. In this
way, the main backup copy ref lects the state of updates up to the current
date, and its daily copies allow rollback to a specif ic date.
Because only changed f iles are backed up ev ery day and f ew f iles are
modif ied ev ery day, backup can be perf ormed suf f iciently rapidly and ev
en during the regular serv er operation. But in the latter case, y ou are running
a danger of corrupting f iles. Suppose that there are two hard-linked f iles, inf
ormation in which has to be linked. For example, data written to one f ile also
hav e to be entered into the other f ile. If when one f ile is being backed up
another f ile is changed, the backup of the f irst f ile will not ref lect the
changes. This will cause serious problems af ter the restoration, because the
integrity of the f iles is disrupted.
Data that are modif ied periodically hav e to be backed up depending on the f
requency of the modif ications. For example, some f iles can be used when
monthly reports are prepared. As a rule, such f iles are quite large and it
makes no sense to back them up regularly. It is more ef f ectiv e to back them
up when the report-preparing activ ity is ov er and to not waste resources on
backing up data that do not change.
The most reliable way to back up is to create an image of the entire hard driv
e. In this case, the inf ormation is sav ed irrespectiv e of the disk's f ile sy
stem, because the f ile sy stem is by passed and the tracks are copied directly.
Restoring f rom an image guarantees that all access rights will be restored
properly and the sy stem is ready to use right away.
This method, howev er, has quite a f ew shortcomings, such as the f ollowing:
It takes lots of time to create a disk image, especially of large driv es.
It puts a great workload on the serv er. It cannot be implemented in Linux,
because most distributions do not of f er the necessary tools.
All f iles, ev en those that are not necessary, are backed up, such as f iles f
rom the /tmp directory.
Disk imaging is conv enient to use f or mov ing data to another computer or
to replicate the conf iguration on other computers. For example, y ou hav e to
set up sev eral client computers with the same conf iguration. Conf igure one
computer, create an image of its hard driv e, and then replicate the image on
the hard driv es of the other computers. This is more reliable than simply
copy ing f iles f rom one computer to another.
Now consider how many media y ou will need to store all of y our backup
copies. Each ty pe of data considered prev iously requires its own media,
because they are backed up at dif f erent f requencies. These are the f
ollowing:
Frequently modified data — In this case, the decisiv e f actor in choosing the
medium is the backup speed, because most of ten these data are bulky. The
backup should take as little time as possible, so as not to put a prolonged
extra workload on the serv er.
The simplest way to make a backup copy is to use the cp command, which is
used to copy f iles. Howev er, f ile permissions must be preserv ed in the
process. The f ollowing command sav es the /home directory to the
/mnt/bkupdisk dev ice used especially f or backup purposes:
cp -a /home /mnt/bkupdisk
In this case, the-aoption is used, which is equiv alent to specif y ing options
-dpR. The f unctions of these options are as f ollows:
-d— Nev er f ollow sy mbolic links. The directory is copied as is.
-p— Preserv e the specif ied attributes (mode, ownership, and time stamps).
-R— Copy directories recursiv ely to back up all subdirectories.
The sense of collecting sev eral f iles into one is that a single f ile is easier
than sev eral small f iles to control and compress using specialized programs.
Archiv ing f ile using the tarutility is perf ormed by executing the f ollowing
command:
tar cf archive.tar directory
When the cfoptions are used at archiv ing, the paths of the archiv ed f iles are
preserv ed. Extracting the archiv ed /home directory reconstructs the /home
directory hierarchy in the current directory. For example, if extraction is perf
ormed into the /home directory, the path to the extracted /home directory will
be /home/home. And if extraction is perf ormed into the /etc directory, the
path to the extracted /home directory will be /etc/home.
Thus, to restore f iles properly, extraction should be perf ormed into the root
directory. This is done by executing the f ollowing two commands: cd /
tar xf /home/backup.tar
Here, the f irst command changes the current directory to the root directory,
and the second command extracts the archiv ed backup f iles f rom the
/home/backup.tar f ile.
The tarutility also uses the f ollowing options: v— Lists v erbosely f iles
being processed.
P — Specif ies not to strip the leading / character f rom f ile names. In this
case, regardless of the directory, f rom which the extraction command is
executed, the f iles will be extracted into their initial directories.
The tarutility can be used to archiv e more than one directory at once. The f
ollowing command archiv es the /home and /etc directories into one f ile: tar
cf backup.tar /home /etc
This will list all directories and f iles contained in the archiv e, along with
their ownership and permissions. An example of such a list is shown in
Listing 13.1.
drwx------ 504/504
drwxr-xr-x 504/504
drwxr-xr-x 504/504
-rw-r--r-- 504/504
-rw-r--r-- 504/504
-rw-r--r-- 504/504
-rw-r--r-- 504/504
-rw-r--r-- 504/504
-rw-r--r-- 504/504
0 2004-11-27 20:24:05 home/adr/
0 2004-11-27 20:24:05 home/adr/.kde/ 0 2004-11-27 20:24:05
home/adr/.kde/share/ 118 2004-11-27 20:24:05 home/adr/.gtkrc 24 2004-11-
27 20:24:05 home/adr/.bash_logout 191 2004-11-27 20:24:05
home/adr/.bash_proflie 124 2004-11-27 20:24:05 home/adr/.bashrc 5 2004-
11-27 20:24:05 home/adr/text
2247 2004-11-27 20:24:05 home/adr/.emacs
Note that there is no leading / character in the paths of the archiv e f iles in
the last column. To properly restore f iles f rom this archiv e, the command to
extract it has to be executed f rom the root directory ; otherwise, the f iles will
be extracted into the current directory.
Unlike the tarutility, the gziputility compresses archiv ed f iles. The resulting
archiv es are of a much smaller size than the sum of the uncompressed f iles,
meaning that they can be stored on a smaller medium.
Most of ten, data that hav e to be backed up are documents, whose size can
be reduced by 90% by compressing them. Unlike programs, text f iles y ield
to compression extremely well.
Compressing, howev er, places a great workload on the processor, and it may
take a long time to f ully back up a large directory.
Because the size of a compressed archiv e is much smaller than that of a
noncompressed archiv e, it takes less time to copy the archiv e ov er the
network or to write it to remov able media.
Bef ore compressing f iles, y ou should place them into a tararchiv e. Then
compress the obtainedtarf ile as f ollows:
gzip -degree file.tar
Now list the contents of the directory (using the ls command). Note that there
is no more backup.tar f ile. It was replaced by the backup.tar.gz f ile, which is
much smaller.
The f irst command changes the current directory to root. The second
command f irst decompresses thegzipf ile and then extracts f iles f rom the
tararchiv e. To simply decompress agzipf ile without extracting f iles f rom
thetararchiv e, execute the f ollowing command:
gzip -d /home/backup.tar.gz
This will replace the backup.tar.gz compressed gzip f ile with the backup.tar
tar archiv e f ile.
Now y ou are ready to write a script to archiv e directories to be backed up in
atararchiv e and then compress this f ile into agzipf ile. You can redirect the
results of thetarcommand into thegzipcommand as f ollows:
Here, the command part bef ore the | character creates a tararchiv e of the
/home directory. The | character pipes the results to the second command
part, which then compresses thetarf ile and stores it as agzipf ile.
Another Linux compressing utility is compress. It, howev er, does not
compress as well asgzip; moreov er, it has been a subject of scandals and
litigations concerning the license. Most administrators hav e switched togzip,
and I recommend that y ou start using this utility f rom the get-go.
- n— This parameter takes v alues f rom 0 to 9 and specif ies the backup lev
el. The v alue of 0 means that a f ull backup is to be perf ormed. Lev els
higher than 0 specif y that only f iles newer than the last backup of a lower
lev el are to be backed up.
- u— This option specif ies that the /etc/dumpdates f ile, which records
backup dates, is to be updated af ter a successf ul backup.
-f file— This option specif ies the f ile or dev ice, to which the backup is to
be stored.
The simplest command to perf orm a f ull backup looks like the f ollowing:
dump -0u -f /home/backup.bak
To back up only f iles newer than the f ull backup, a lev el greater than 0 is
specif ied, f or example, as f ollows:
dump -lu -f /home/backup.bak
Files are restored by executing the restorecommand. Bef ore executing it,
howev er, make sure that y ou execute it f rom the directory that has to be
restored.
The only required parameter f or the restore command is -f file, which specif
ies the f ile to be restored. The -ioption runs the command in the interactiv e
mode, in which y ou can also specif y the f iles to restore. The interactiv e
mode is similar to the command line, in which y ou can browse the archiv e
and execute the f ollowing commands:
add directory— Adds the directory specif ied in the directory parameter to the
list of f iles to be extracted. cd directory— Changes the current directory to
the one specif ied in the directory argument.
delete directory— Deletes the directory specif ied in the directoryargument f
rom the list of f iles to be extracted. extract— Extracts all f iles on the
extraction list. quit— Quitsrestore.
In one company I witnessed the procedure, by which conf idential data f rom
a secure serv er were copied hourly to a simple user computer conf igured to
the def ault settings that could be compromised within 5 minutes.
You should approach the business of securing backup media with all due
responsibility. The simplest way to secure the media is to store them in a saf
e. But a better way is to encry pt the backup archiv e bef ore copy ing it to a
medium. You can use the OpenSSH package f or this by executing the f
ollowing command:
/usr/bin/openssl des -in /home/backup.tar.gz -out /home/backup.sec
This will create the backup.sec f ile, which should be the one to write to a
medium. Af terwards, don't f orget to delete backup.tar.gz and backup.sec f
rom the computer.
When restoring the backup archiv e, it f irst has to be decry pted as f ollows:
/usr/bin/openssl des -d -in /home/backup.sec \
-out /home/backup.tar.gz
Af ter the archiv e has been decry pted, the f iles can be restored as usual.
With the huge number of users and serv ers in the today 's Internet, there are
bound to be at least 1,000 computers whose users will be taken by the
simplest break-in techniques. This has to do with the low education lev el of
the av erage Internet user. By education, I don't mean f ormal school
education but rather computer security sav v y. Nobody teaches security to
regular users, and most administrators are either too lazy or just don't want to
spend money f or training to raise their security -lev el skills.
In this chapter, I intend to destroy some of the my ths concerning security and
will supply numerous examples f rom my personal experience as a network
administrator.
All sof tware has bugs because it is written by people and people hav e a
propensity to making mistakes. Ev en the most protected sof tware will hav e
bugs; it's only a matter of time bef ore they are f ound. Ask any hacker about
which Linux kernel is the most secure, and y ou will be told that the latest
kernel v ersion is excellence itself without any bugs. Ask the same question a
month later and y ou will f ind out that the kernel praised a month ago is
buggy and it is recommended that y ou patch it bef ore continuing working
with it.
With ev ery new Windows v ersion, the Microsof t people tell us how reliable
and secure it is, but a month later the same people tell us what a great serv ice
pack they 'v e created f or us to patch the holes and get rid of the bugs in this
so-called secure and reliable operating sy stem. Throw Internet Explorer and
Microsof t Of f ice applications into the mix and y ou get a good idea of the
extent of the problem. Sof tware bugs are as inev itable as death and taxes,
and y ou hav e to accept this. Accepting does not mean resigning, so be ready
to update regularly and religiously.
14.1.1. Responsibility
A spelling mistake of ev en one letter in a conf iguration f ile may hav e griev
ous consequences. Going through v oluminous conf iguration f iles, y ou may
f ail to see it because to speed up the check y ou tuned y our perception more
to the sounds of words and not to their spelling. Besides, when checking their
own work most people, no matter what they may think consciously,
subconsciously think that they did ev ery thing right and do only a perf
unctory check. It takes a special training to v iew one's own work as someone
else's. But someone who sees the text f or the f irst time and not in its primary
context will notice the error right away. It is pref erable that this someone be
a security specialist.
The administrator should conf igure and serv ice the sy stem f rom the perf
ormance standpoint, and the security specialist should check the conf
iguration f rom the security standpoint and test it f or v ulnerabilities. These
two specialists hav e to interact and cooperate with each other, because a perf
ectly secure sy stem may not necessarily be one that can deliv er any
meaningf ul perf ormance, and v ice v ersa. They can ev en substitute f or
each other when necessary, but no single person should be responsible f or
both areas, especially in large companies, meaning large networks.
Highly skilled security prof essionals demand a high price f or their serv ices,
but y ou should not scrimp on security. It is better to spend a f ew extra
dollars f or a security specialist's salary than a f ew thousand dollars to recov
er f rom a hacker attack.
Once hackers obtain any sort of access to the sy stem, they can raise their
priv ileges. This can be done using v arious exploits, which can be f ound on
the Internet in drov es. Ev ery day, new ones are created. If hackers hav e no
access to the sy stem, it will be much more dif f icult f or them to break into
it.
Currently, there aren't that many way s to break into a computer remotely, but
with local access hackers' chances of raising their access priv ileges increase
many f old. It is easier to protect against break-ins perpetrated ov er the
network; the main def ense method here is using a f irewall. But if hackers
obtain some sort of access, what they can do depends only on the accessrights
allocation policy. If it is not well thought out, hackers can ev en obtain
administrator priv ileges.
The main targets attacked by hackers af ter accessing a sy stem are the f
ollowing:
You can f ortif y the serv er containing restricted inf ormation and open
another one f or public use. In this case, howev er, there should be no trust
relationship between these two serv ers, and user names and passwords must
be dif f erent. But humans, being such a lazy bunch, ty pically make the root
passwords f or all serv ers the same or, if they dif f er, make them similar
enough that they will be easy to remember. If y ou can discipline y ourself to
f ollow all pertinent security rules, assigning dif f erent phy sical serv ers f or
dif f erent tasks is a correct approach to securing y our network.
You can start by strictly f ollowing the rule that the root user password
should be dif f erent f or each serv er.
Security means not only hardening y our sy stem against break-ins but also
making it imperv ious to improper user actions. The simplest example is what
I call the boss ef f ect. Many administrators consider that their direct boss or
the company director should hav e the right to v iew any inf ormation in the
sy stem. There may be a legitimate need f or this, but once a boss is giv en
rights to v iew inf ormation, he or she usually starts demanding the write
rights also. This is much more likely to create problems, especially if the boss
is a klutz with computers. And it is usually bosses of this ty pe who ask f or
the maximum rights. If y ou y ield to someone pulling rank, there is a good
chance that their use of these rights will result in serious data loss. Guess who
will be lef t holding the bag?
Another problem stemming f rom giv ing extra priv ileges to f riends and
bosses is that it is impossible to protect their passwords. If there is only one
maximum-priv ileges user in the sy stem, the root, it is relativ ely easy to
protect his or her password. But keeping track of the passwords of ten
highpriv ileged users is a more dif f icult task. Any of these users can select
an easy password or simply write a strong password on paper. In either case,
the password will become v ulnerable with the corresponding consequences
stemming f rom it being compromised.
Seemingly, I took good care to make the workstations secure, but when one
day I came to one of the shops to serv ice one of the computers I saw the
password written with a permanent marker on the monitor case. So, all my ef
f orts at creating strong passwords were nullif ied by one lazy computer
operator, who made the password av ailable f or any company worker or ev
en a stranger to see.
Nev er write down passwords on paper and, ev en more so, nev er leav e
these near monitors or key boards. Take a little time to memorize the main
passwords.
Leav ing the computer, block the key board (e.g., using the
vlockorxlockutility ) or log out of the sy stem, so that no one can use the
computer while y ou are away.
If y ou work in the graphical mode, nev er place any shortcuts other than the
def ault ones on the desktop. For example, a shortcut to another computer
prov ides a wealth of inf ormation f or hackers.
Put a password on BIOS. If hackers obtain phy sical access to the computer,
they will be able to reboot it in the singleuser mode and proceed to break the
root password.
Generate new passwords y ourself and distribute them to the users. This
approach is conv enient f or a large network to ensure that all passwords are
changed. Howev er, there could be problems distributing passwords.
Prepare a security memo instructing all users to change their passwords when
instructed by the administrator. All users should be f amiliarized with this
memo.
The security memo should also instruct users to create strong passwords of a
certain minimal length. Most importantly, y ou should ensure that users use
strong passwords.
Also, a f ired worker may decide to get ev en with the administration f or the
f iring and use his or her login parameters to do some unscheduled creativ e
maintenance on the sy stem. There are numerous examples of this happening.
I witnessed one such case when the network administrator was f ired but the
new administrator did not change the passwords. Two day s later he wished
that he had not had so much f aith in human decency : The serv er's hard disk
was wiped clean. At the time I worked as a programmer at that company and
had my share of ov ertime restoring the destroy ed data.
14.1.6. Passwords
Ev en though this adds certain inconv eniences when remember the new
passwords, the security this prov ides is worth it.
The only password I don't change is the Windows password on my notebook,
because I am the only one who uses it.
Once they obtain access to the sy stem, many hackers do not engage into any
malev olent activ ities. They simply explore the sy stem to f igure out its
organizations and way s f or stay ing undetected. Only those hackers intent
on destroy ing data will mov e f ast, because they don't intend to hang around
long. Fortunately, there aren't that many break-ins of this ty pe.
Changing passwords regularly makes cracking them more dif f icult. Here is
how. Many automated security sy stems can easily detect an attempt at
password cracking by sev eral unsuccessf ul authorization attempts in a row,
usually three. To circumv ent such protection, hackers insert some delay bef
ore try ing the next password. This makes the break-in process longer, but
unless the password is dif f icult and changed periodically, the attack will
ultimately succeed. If the password is periodically changed, the possibility to
pick it bef ore the next change becomes v ery low.
For example, suppose that the password contains only digits. Further,
suppose that the password is 7000000. By a brute-f orce search, the hacker
tried combinations f rom 0 to 6000000, at which point the password was
changed to 5000000. Further combination picking can go on indef initely
without any results, because the range, in which the new password is located,
has already been passed.
Another adv antage of f ered by regular password changes is that it may take
the hacker so long to pick a strong password that by the time he or she
succeeds the password will be changed, throwing the hacker back to stage
one.
How can y ou make users change passwords periodically ? You can make use
of thechageutility, executing it as f ollows:
chage parameter user
-E date — Sets the date, on which the user's account will no longer be
accessible.
-IN— Blocks the account if it has not been used f or Nday s. I recommend
setting the Nv alue to no f ewer than 3 day s but no more than 4 day s to
block the account while the owner is on v acation or sick leav e.
-l user — With this parameter, the command can be executed by any user but
only to f ind out when his or her password expires. For example, executing
chage -l root display s the expiration date of the root password and other
pertinent inf ormation. The execution results look similar to the f ollowing:
Minimum: -1
Maximum: 99999
Warning: -1
Inactive: -1
Last Change: Feb 04, 2004
Password Expires: Never
Password Inactive: Never
Account Expires: Never
The meanings of the entries in the preceding listing are as f ollows: Minimum
— The minimum number of day s between password changes
Maximum— The maximum number of day s bef ore the password change
Warning — The number of day s bef ore the password expiration that a
warning message starts to be issued Inactive— The number of day s the
account remains inactiv e bef ore it is blocked
Changing a password too of ten results in users simply not being able to
remember or get used to them. Consequently, they start writing strong
passwords down or simply change the new passwords to the old. To prev ent
this dev elopment, users should not be made to change passwords too of ten.
A period of 60 to 90 day s between password changes is considered
acceptable.
But how can y ou make sure that users select strong passwords or that they do
not simply reuse the old passwords? This can be achiev ed with the help of
thepam_cracklib.somodule. This module perf orms basic password checking
f or stronger passwords. For example, the module will not allow the user to
specif y the old password or a password containing too many characters f rom
the old password.
The f irst part tells the sy stem to use the pam_cracklib.so library. The retry
parameter sets the number of attempts to enter the new password to f iv e.
Theminlengthparameter sets the minimum password length.
14.1.7. BugTraq
To tell the truth, there aren't that many real hackers in the world. Most
breakins are perpetrated by teenagers who hav e nothing better to do and who
want to try their skills somewhere. This sort of hackers is not too strong on
the theory of programming and mainly uses ready -made techniques designed
and perf ected by real hackers. This means that y ou should keep track of new
break-in techniques and newly -discov ered v ulnerabilities. I use the
www.securityfocus.com or www.cert.org sites f or this purpose. They
regularly publish inf ormation about new security holes, how to use them,
and how to protect against their use.
The discussions concerning the need f or sites like www.securityfocus.com
hav e been carried on f or a long time. On one hand, they allow
administrators to protect their sy stems by learning about new v ulnerabilities,
but on the other the hackers can use this inf ormation f or diametrically
opposite purposes. I don't see any problems with such sites and, what is ev en
more, believ e they are a good idea. The problem is that most administrators
simply do not v isit these sites and they learn about the weak spots only when
their site, network, or serv er has been broken into. Ev en if y ou consider a
security hole discov ered in 1990s, computers and serv ers can still be f ound
on the Internet that hav e this hole unpatched. If I had my way, I would sack
such administrators without thinking twice.
If y ou think that regularly updating y our sy stem can make it imperv ious to
break-ins, y ou are sadly mistaken. A considerable length of time may pass f
rom the time a new security hole is discov ered until an update with a patch f
or it comes out, during which y our computer can be compromised. Any
hacker who has learned about the new hole can successf ully attack y our
computer. To keep this f rom happening, y ou must learn about the new v
ulnerability bef ore hackers do and undertake y our own security measures to
keep y our computer secure until the of f icial patch comes out.
Not only serv ices but also the kernel can contain bugs. Bugs in application
sof tware can be f ixed by installing a f resh v ersion. Fixing kernel bugs is
somewhat more complicated. Updating it inv olv es recompiling the kernel
source code, which is a rather intricate procedure. But updating using RPM is
no more dif f icult than installing any other program.
In addition to the of f icial kernel updates, there are many patches written by
third-party dev elopers (e.g., SELinux, lcap, and LIDS). All of them are
intended f or securing the sy stem on the kernel lev el. For example, the
kernel can prohibit executing code f rom the stack, which will make many
stack-ov erf low attacks impossible. There are kernel patches to prohibit v
iewing f iles in the /proc directory, monitor sy stem processes, protect against
port scanning, and so on.
You may ask why examples of third-party kernel patches weren't considered
earlier in the book. The reason is that most of such patches require y ou to
recompile the kernel, do not work with all Linux kernel v ersions, and require
serious ef f ort to install. Although kernel patches enhance sy stem security,
they may make the sy stem less stable because they are produced by
thirdparty dev elopers and Red Hat Linux may simply not support all of their
requirements.
This is why this subject is not included in the book. Howev er, y ou should
know that such patches exist; y ou may decide that the security f eatures of f
ered by a certain patch are just what y our sy stem needs, and install it. But y
ou should realize that y ou will be doing this at y our own risk. You should
also be aware that updating the kernel to a new v ersion may cause problems.
Moreov er, as with all new sof tware, new kernel v ersions hav e bugs that
will hav e to be patched.
Many computer specialists do not hav e special education and are self taught.
I hav e rather extensiv e experience dealing with administrators and can tell f
rom the contents of administrator's computer the prof essionalism lev el of its
owner. In a nutshell, if there are games on the administrator's computer, there
is a 90% chance that the administrator spends too much time f ighting
monsters. If the computer has no games and only administrating sof tware,
the administrator is a good one or on the way to becoming such.
The computer f ield is in the state of constant dev elopment, and if y ou spend
more time running through dark hallway s and machine-gunning monsters, y
our computer skills will become obsolete f aster than rapidly. You hav e to be
constantly raising the lev el of y our prof essional skill and learning
something new ev ery day.
Special education is a good thing, but it only giv es the base that y ou can
learn f rom prof essional literature in a month or so. Specif ic knowledge
becomes obsolete way bef ore y ou graduate f rom college, and unless y ou
constantly ref resh y our body of knowledge, y ou stand good chances of
becoming a simple adv anced user.
All work and no play makes Johnny a dull boy, so shooting a monster now
and then is no sin. But y ou should remember that computer-security
specialist responsibilities include not only taking care of present tasks but
also raising y our qualif ication lev el.
The preceding was just a general outline of security concepts. Other sections
of the book consider the operating sy stem and its v arious serv ices f rom the
security standpoint in more detail. But the general rules alway s apply
regardless of the operating sy stem and hardware.
This makes it possible to pass the program too much inf ormation, which will
simply not f it into the memory allocated to hold it and cause a program
crash.
How can too much passed inf ormation crash a program? I will not burden y
ou with programming and machine code intricacies, but simply consider a
simplest buf f er ov erf low example. A program can be thought of as occupy
ing a single continuous memory block as f ollows:
Code
Code
A 50-byte data buffer
Code
Code
In older Windows v ersions, some buf f er ov erf low bugs could crash the
operating sy stem itself . Windows 2000, XP, and Linux are hardened against
buf f er ov erf low errors and are more dif f icult to crash. But programs still
crash.
The program crashing itself is only half the trouble. The other half is that
experienced hackers can pass such data to the program, in which the f irst
part, corresponding to the buf f er size, is trash while the part f ollowing it is
executable code written by the hacker to perf orm certain operations. This
will make the program code look as f ollows:
Code
Code
A 50-byte data buffer
Hacker's code
Hacker's code
In this case, the buf f er ov erf low will cause much greater damage than a
simple program crash. If the program executes with root priv ileges, the
hacker's code can perf orm any operations that require root priv ileges.
Buf f er ov erf low bugs are becoming less common because of automatic
code-checking utilities, but many of them are still around. There aren't that
many good hackers able to use the buf f er-ov erf low bug to insert their own
code into a program. But programs exploiting the buf f er-ov erf low bug
written by such hackers can be used by any one, which presents a major
danger.
In addition to crashing the stack by exploiting the buf f er-ov erf low bug,
program code can be corrupted by improper f ormatting. Some f unctions
may present a security threat if used in a certain way. Hackers may pass to
them such inf ormation that when processed by the program will change the
program's code. The principles of prev enting the adv erse ef f ects of these
errors are the same as those f or prev enting buf f er-ov erf low ef f ects, so I
will not go into much detail on this aspect; moreov er, users and
administrators don't usually deal with machine codes.
What y ou should know is that when y ou f ind out that one of the serv ices is
v ulnerable to a buf f er-ov erf low attack and y ou can temporarily do
without it, y ou should disable the serv ice. If the serv ice is not a necessary
one, y ou can simply delete it.
If y ou need the serv ice, the f irst thing y ou should do is v isit the dev
eloper's site. Follow any recommendations on how to f ix the error that y ou
may f ind there. Sometimes, all y ou hav e to do is modif y some conf
iguration f iles, but sometimes a new v ersion of the program has to be
installed.
In 90% of cases, buf f er ov erf low errors are f ixed by updating the program.
This is because such errors stem f rom incorrect code logic that can only be f
ixed by correcting the source code and recompiling the program.
If the dev eloper of f ers no solution to f ix the problem, limit the program's
rights as much as possible. If a program belongs to root and its SUID or
SGID bit is set (that is, the program executes with the root priv ileges ev en if
run by a guest user), this bit must be cleared.
As univ ersal protection against buf f er ov erf low bugs, I can recommend
the libsafeutility (av ailable f rom
www.research.avayalabs.com/project/libsafe). This is a library that creates
a buf f er lay er between the application sof tware and the operating sy stem.
When sy stem f unctions that may cause buf f er ov erf low are called, the
library substitutes these f unctions with its own v ersions. These are f
unctional analogues of the sy stem f unctions but are protected against buf f
er ov erf low.
The library has one shortcoming: It causes a slight productiv ity drop. But the
library 's adv antages ov erweigh this shortcoming in many way s. The library
does not protect against a certain program or a certain error, but against most
potential problems. As y ou already know, it is impossible to protect against
ev ery thing, because hackers constantly come up with new tricks, so the
library does not prov ide 100% protection against buf f er ov erf low errors.
But the protection it does prov ide will allow y our sy stem to work
uninterruptedly f or a much longer period than it would otherwise.
14.3. Rootkits
Hav ing obtained access to the sy stem, hackers striv e to f ortif y their
positions and to obtain maximum priv ileges. Once in the sy stem, a hacker
will nev er be satisf ied with regular user priv ileges and will seek the
capability to execute commands with the root priv ileges.
The command has regular user permissions and is sent to the rootkit program.
The rootkit program has root permissions and executes the hacker's program
as the root.
But how does the rootkit program obtain root permissions? With the help of
the same notorious SUID or SGID bit.
Moreov er, the ownership of the rootkit program must belong to the root user.
There are two way s of changing a program's ownership to root and setting its
SUID or SGID bit. These are the f ollowing:
This is why SUID and SGID programs should be tightly controlled. Each
such program is a hole in sy stem security, but unf ortunately sometimes
these programs are necessary. You should closely monitor such programs and
immediately delete any new ones that are not installed by y ourself . You
should also monitor changes to the legitimate SUID and SGID programs. A
size change of an SUID or SGID program is a cause to sound the alarm,
because this may be an indication of the legitimate program hav ing been
substituted with a hacker v ersion.
Pay close attention when checking SUID and SGID programs. Hackers know
that administrators monitor such programs, and they resort to v arious tricks
to prev ent their inf iltrated or subv erted SUID and SGID programs f rom
being detected. For example, y ou may see nothing alarming in that the
/mnt/mount program has the SUID set because the mount program does
require this. Howev er, the legitimate mount program is located in the /bin
directory, and the one in the /mnt directory is without a doubt a cuckoo egg.
If y ou are going ov er the list of the SUID and SGID f iles in a hurry, y ou
may not notice the directory dif f erence or may not ev en be looking at the
directories in the f irst place.
Moreov er, hackers can substitute letters in the names of legitimate programs
with letters similar in appearance. For example, they can add the /bin/logon
program masquerading as the /bin/logon. The dif f erence is that the letter "1"
in the legitimate v ersion is substituted with the digit "1" in the counterf eit
one. You likely will not notice the dif f erence, because the legitimate v
ersion does not hav e the SUID and SGID bit set and only the f ake one will
show in the SUID and SGID list. And ev en though the login program should
not hav e this bit set, y ou, most likely, will not suspect this program is any
thing malicious.
Once hackers hav e a rootkit package installed in the sy stem, they can alway
s come back ev en if y ou f ind and patch the hole used to enter originally.
Thus, y ou should be able to locate and neutralize rootkit packages.
You can use the chkrootkitprogram f or this purpose (av ailable f rom
www.chkrootkit.org). Currently, it can detect more than 50 dif f erent
popular rootkit packages.
But, as usual, the protection f rom an automated tool is limited and a sweep
by chkrootkitwill not guarantee y our sy stem a clean bill of health. The
problem is that only beginning hackers use ready made rootkit packages. Prof
essional hackers are good programmers and create their own tools. It is not
that dif f icult; they only hav e to know some programming and the way
Linux operates. Theref ore, y ou should be able to detect and neutralize
rootkit packages manually y ourself .
One of the way s of detecting rootkit packages manually is to scan the ports,
because to open a back door to the sy stem a rootkit opens a port, which it
monitors f or the hacker to connect.
One of the best Linux scanning tools with extensiv e f unctionality is the
already -mentionednmaputility. To scan all 65,535 ports, the program is
launched as f ollows:
nmap -p 1-65535 localhost
The-pparameter sets the port range to be scanned. In this case, the entire
range of existing ports f rom 1 to 65,535 is specif ied.
The f ollowing parameters can also be used:
-sT — Standard TCP connect scan. This is the slowest scanning, opening a
connection to ev ery port on the scanned machine. Any antiscanning utility
will detect this scan (see Section 12.4). This is the def ault scanning mode if
the program is run with the regular user permissions.
-sS — TCP sy nchronization (SYN) scanning. This is the def ault scanning
mode f or root users. It is f aster than thesT mode and is detected by f ewer
antiscanning utilities.
-sF — TCP f inish (FIN) scanning. Pursuant to RFC 793 specif ications,
closed ports must reply to a FIN packet (sent by a client to the serv er to
initiate connection termination) with an reset (RST) packet. Consequently,
receiv ing no RST packet in response to a FIN packet indicates that the giv en
port is open. This, howev er, applies to Linux sy stems only. Windows
creators, as usual, decided to ignore the standard and do it their own way, so
the scan will not work against these sy stems.
-sX — TCP Xmas tree scanning. This scan is similar to the TCP scan, only
theURGandPUSHf lags are set in addition to theFINf lag.
-sN— TCP null scanning. This scan is similar to the prev ious two scans,
only no f lags are set.
-I— Ident scanning.
-sU— UDP scanning. UDP ports are dif f erent f rom TCP ports and must be
scanned separately.
The idea of scanning consists of obtaining some sort of reply f rom the serv
er. Depending on the scanning method employ ed, a positiv e or negativ e
reply indicates that the giv en port is closed or open.
A f aster way to determine open ports is to use the lsof -iornetstat command;
howev er, these can only be executed on the machine whose ports are being
scanned.
Combined use of all of these utilities will allow y ou to detect rootkits that
chkrootkitmisses.
When the hacker connects to this port, the program opens a command shell
on the port, thus giv ing the hacker the ability to execute commands.
The back-door operation is similar to the way Trojan programs work; howev
er, Trojans hav e to be launched by the user to be installed, and back doors
are uploaded to the target computer and installed by the hackers.
There is also a similarity with the way rootkit programs work. There is no
clear-cut distinction among dif f erent hacker tools, with one program hav ing
the f unctionality of what used to be separate utilities. Rootkit and back-door
utilities hav e been combined in a single package f or a long time, although
separate utilities can still be f ound.
Hacker utilities are not the ty pe of sof tware y ou can purchase at a store
where regular sof tware is sold. Hackers write these programs f or their own
use; nev ertheless, they can be downloaded f rom some priv ate sites.
Hackers do not like to make their utilities public, because in that case the
loopholes they use to penetrate sy stems will be closed.
Because the main goal of this book is to teach y ou how to create a secure sy
stem, I will not consider creating and installing back-door sof tware. What I
will consider is how to detect and neutralize it.
The simplest and quickest way to f ind a program that does not belong is to
check the current processes and open ports. As already stated, a back-door
utility waits f or the hacker to connect to the computer it is installed on,
meaning that there has to be a process f or this program. The current
processes can be v iewed by executing thepscommand. Open ports are
checked using a port-scanning utility or thenetstatprogram.
When using the psutility to check the current processes, make sure that it has
not been modif ied by hackers. Because Linux source codes are open, hackers
can modif y thepsutility in such a way that it will not display the process of
the back-door program. Thus, they can slip the doctored v ersion into y our sy
stem.
The source codes being open means that any other program can be modif ied
to perf orm other f unctions in addition to the legitimate ones. For example,
thetelnetdutility can be modif ied in such a way that it can be used to enter the
sy stem without hav ing to go through the regular login procedure. Thus,
make sure that the executable f iles f or all running processes hav e not been
modif ied.
Moreov er, some daemons can support loadable modules. Thus, hackers can
write and load their own module instead of or in addition to the standard
modules of a serv ice. Detecting this module will be more dif f icult, because
the main process f ile is not changed.
Modif y ing program source codes is a rather dif f icult task, and y ou hav e to
possess good programming knowledge; consequently, ev en though this
method is among the most dangerous ones, it is not that widespread. Still, it
should not be dismissed, because ev en though there are f ew high-class
hackers, they do exist.
Pay close attention when inspecting the process list. There may be two
utilities with the same name in y our sy stem, f or example,telnetd. One of
these will be the genuine utility, and the other will be a back door planted by
hackers.
If y ou serv er is nev er turned of f , hackers can simply start their back door
program and leav e the sy stem knowing that they can come back any time
they wish. But if the serv er is periodically turned of f or rebooted, they will
hav e to make arrangements f or the back door to start upon reboot to keep it f
unctioning.
Consequently, y ou should check all boot scripts f or changes. This may prov
e to be a complex task, because there are quite a f ew such scripts in Linux
and hackers can modif y any of them. Scripts f or loading serv ices are
located in the /etc/rc.d/init.d directory.
Ev en if y ou do not f ind any extraneous processes or any modif ied serv ice
or program f ile, there still may be a back door in y our sy stem. Processes
can be hidden f rom v iewing by kernel modules.
Of late, the Linux kernel has become truly modular. This is conv enient
because while earlier the kernel had to be recompiled to add a new f
unctionality, now this can be done by simply executing a f ew commands to
load the necessary module.
So how can the kernel be used to hide a process? The psprogram, and others
like it, uses the kernel to determine, which processes are running. The kernel
has all inf ormation about what is being currently executed. Hackers hav e
written v arious modules that prev ent the kernel f rom disclosing inf
ormation about certain processes, thus keeping those processes hidden f rom
the administrator's ey es. This is why y ou should not stop af ter inspecting
processes and executable f iles ev en if y ou don't f ind any thing suspicious.
The only sign of there being a snif f er in the sy stem is the increased
workload on the serv er because of all the packets that pass the network card
passed on to the operating sy stem f or processing.
The best protection against a back door is a properly -conf igured f irewall. If
y our def ault policy is to prohibit ev ery thing, allowing access to public
resources only, ev en if a malware program opens some port it will be
impossible to connect to it without changing the f irewall f ilters. Keep an ey
e on f irewall f ilter f iles to make sure that they are not modif ied, and all of a
hacker's ef f orts will be in v ain.
Snif f ers can work in activ e and passiv e modes, both of which are
considered in this chapter. Howev er, to hav e a better understanding of the
subject, y ou will hav e to learn the basic concepts of the Open Sy stems
Interconnection (OSI) model.
When data are sent ov er a network, they are directed f rom one computer to
another. But how exactly is it done? You may guess that a special network
protocol is used, and y ou would be right. But there are many protocol v
arieties. When is each of them used? How do they work? These and other
questions I will try to answer in this section.
Bef ore getting down to the protocols, y ou hav e to learn about the OSI
model, dev eloped by the International Standard Organization (ISO) to
describe how inf ormation mov es f rom one computer through a network
medium to another computer. According to this model, all network
interaction is broken down into the f ollowing sev en lay ers (Fig. 14.1):
2. The data linklay er prov ides transit of data between any nodes in ty pical
topology networks or between adjacent nodes in random topology networks.
Addressing employ s MAC addresses.
3. The networklay er def ines the network address, which dif f ers f rom the
MAC address. The lay er prov ides unreliable communication, meaning the
deliv ery of packets is not guaranteed.
6. The presentationlay er prov ides data coding and conv ersion f unctions.
7. The applicationlay er prov ides a set of network serv ices (FTP, email,
etc.) f or users and applications.
The process is rev ersed on the destination machine, with each lay er
stripping the header added by the corresponding lay er on the source machine
and passing the resulting data unit to the next lay er until only pure inf
ormation, without any serv ice data, is handed to the application lay er.
Data transmission does not necessarily start f rom the phy sical lay er. If the
protocol used works on the transport lay er, the packet's downward trav el
starts at this lay er. The number of lay ers used by a protocol def ines its
needs and data-transf er capabilities.
The higher a protocol (the closer to the application lay er), the more
capabilities it has and the more ov erhead inv olv ed in data transmission
(more headers, which are also more complex).
Passiv e snif f ing inv olv es monitoring packets that pass directly through y
our network card. This method can only be used on the common-bus and
startopology networks. (Network topologies are described inSection 5.2.)
Passiv e snif f ing is the easiest to implement. All network packets that pass
through a network card are checked f or being addressed to that card. The
network card compares the destination address in the packet header with its
own MAC address and, if they match, passes the packet to the operating sy
stem f or f urther processing. Packets whose address does not match are
rejected. The operating sy stem uses the header inf ormation to determine the
port, to which the packet is directed, and the program that opened the port
and must process the packet.
Processing to f ilter out packets addressed to a particular computer is carried
out on the network card lev el. But a network card can be placed into a
special mode, called promiscuous, in which all packets are passed to the
operating sy stem and can be processed using specialized programs. It should
be noted that not all network cards can be switched into the promiscuous
mode, but at least all modern cards can.
This trick, howev er, cannot be pulled on the Internet and networks using
routers, because only packets addressed to a particular network card reach
that card. All other packets are f iltered out by switches or the prov ider's
routers. In this case, activ e snif f ing is resorted to.
At f irst, it may seem that administrators cannot detect snif f ing, making
engaging in this activ ity saf e f or hackers. Acting on this belief , some
beginning hackers launch their snif f ing programs and keep them running all
day long, waiting f or secret passwords to start coming their way. But
administrators can and should detect snif f ing activ ity in their networks, ev
en passiv e snif f ing, and discov er and punish the perpetrator.
But hackers are not that stupid and operate f rom behind f irewalls. All the
hacker has to do is prohibit outgoing ICMP traf f ic, and his or her computer
will not reply to the administrator's ping requests.
If thePROMISCmode is set, y our card can monitor all network traf f ic.
Activ e snif f ers redirect other computers' traf f ic to themselv es. This is
done by modif y ing routing tables and f ooling network equipment, which is
more dif f icult to implement.
Here is where the OSI model comes into the play. Network cards, hubs, and
most switches operate on the lev el of the data link lay er. Receiv ing a
packet, they check its data link header, operating only with MAC addresses.
These dev ices can neither see nor understand other lay er headers. Routers
and more adv anced (third-lay er) switches disassemble packets to the
network lay er, where IP addresses are used.
Thus, within a network that has no third-lay er switches, packets can only be
addressed using MAC addresses. But how is it done exactly ? Users nev er
specif y the MAC address, and y ou cannot simply place a packet on the
network addressed using the IP address.
How, then, does the source computer f ind out the MAC address of the
destination computer? It f irst sends a broadcast request to all computers in
the network, asking something like this: Whose IP address is
XXX.XXX.XXX.XXX? The request is sent using ARP. Also, packets are
addressed using a special broadcast address as the destination MAC address,
and all network cards must accept such packets and pass them f or processing
to the operating sy stem. The operating sy stem examines the packet on the
network-lay er lev el, where ARP is employ ed. If the IP address being
inquired about belongs to the particular computer, the operating sy stem
replies to the requester inf orming it about its MAC address. Now the source
computer has the IP address mapped to the MAC address.
But what is to prev ent y our computer to answer ARP requests directed to
another computer and pass itself of f as that computer? Nothing. ARP does
not hav e any authentication mechanism. It blindly accepts any replies to any
ARP requests without f urther questions.
But this is not the worst thing. The source operating sy stem caches responses
to its ARP requests, and the next time it has a message to a resolv ed IP
address, it does not send a broadcast ARP request but uses the cached MAC-
mapping inf ormation. And here is the worst thing. Some operating sy stems
(I will not name names) cache not only replies to its own ARP requests but
also replies to ARP requests issued by any other host. Thus, a hacker's
computer can send ARP replies mapping its MAC address to another
computer's IP address to all network's computers, and they will cache this f
ake MAC-to-IP mapping inf ormation.
You can v iew the current ARP cache by executing the arpcommand. The
results of its execution look similar to the f ollowing:
Address HWtype HWaddress Flags Mask Iface 192.168.77.10 ether
00:03:0D:06:A4:6C C eth0
The most interesting columns are the f ollowing: Address— The computer's
IP address HWtype— The remote dev ice ty pe
HWaddress — The MAC address of the remote dev ice Iface— The network
interf ace
You can delete entries f rom the ARP table by executing the arpcommand
with the -doption and specif y ing the necessary IP address. For example, the
ARP entry in the preceding example can be deleted as f ollows: arp -d
192.168.77.10
This will result in the MAC address being replaced with (incomplete):
Address HWtype HWaddress Flags Mask Iface 192.168.77.10 (incomplete)
eth0
ARP table entries added to the cache by ARP are dy namic, meaning they are
periodically deleted. Hackers know this and may periodically mail f ake ARP
replies. So simply deleting f ake entries f rom the ARP table will not be ef f
ectiv e. You hav e to f ind and go af ter the miscreant.
You can use Rev erse ARP (RARP) f or this. This protocol requests the IP
address f rom a known MAC address. You should receiv e replies f rom all IP
addresses, f or which there are entries in y our ARP table. Keep in mind that
more than one IP address can be mapped to one MAC address. For example,
the network card on my computer has two IP addresses mapped to its MAC
address to work in two logical networks concurrently. So this is a normal
situation. But if a certain IP address does not answer, y ou should delete the
corresponding entry in the ARP table.
For working with ARP tables in Windows, I recommend using the Cy D NET
Utils utility (www.cydsoft.com).
Keep it in mind, howev er, that it is dif f icult to spoof ARP mapping in
Windows.Broadcasting f ake ARP replies mapping IP address 192.168.77.1
to y our MAC address will result in the computer with this IP address issuing
an error message that this address is already used by another network dev ice
and disconnecting f rom the network. This can be av oided by sending f ake
ARP replies to only one computer instead of broadcasting them.
Sending f ake ARP replies is a rather inv olv ed task. It is much easier to
simply change the network card's MAC address if its driv er supports this
operation. This can be done using the already f amiliarifconfigutility with
thewhoption f ollowed by the hardware class and the new MAC address.
If switches can be easily f ooled by using f ake ARP entries, this is not the
case with routers. Routing dev ices operate on the network lay er lev el, that
is, on the IP address lev el. To f ool routers, f aking MAC addresses will not
do; it takes f aking IP addresses. For this purpose, hackers break into routers
and reprogram them to serv e their needs.
The only way to resist f ake ARP inf ormation is by employ ing
programmable switches to organize the network. These switches can
permanently assign a certain MAC address to each of its ports. But this is
only a partial solution to the f ake ARP reply problem.
The complete solution is to use static ARP table entries, that is, to manually f
ill out the ARP table on each client computer. But this is not that conv enient
to put into practice, because ARP tables on all computers will hav e to be
edited when there is any network equipment change on a single computer. It's
alright if y ou hav e, say, f iv e or ev en ten computers in the network, but
what if there are dozens or ev en hundreds of them? Ev ery time y ou add or
replace a network card, y ou will hav e to update the ARP tables on all of the
network's computers.
To f acilitate the task of manually updating ARP tables, y ou can create a
script. The script is located on the serv er, and each client should run it at
booting.
Flooding Switches
Hubs are dev ices that replicate all traf f ic that arriv es to the incoming port
to all outgoing ports. Switches are intelligent dev ices that route incoming
packets to their corresponding MAC addresses. This means that a switch will
send an incoming packet only to the port, to which the packet's recipient is
connected, not to the rest of its ports.
Thus, snif f ing is impossible on a network built using switches. But switches
hav e one peculiar f eature: When a switch cannot analy ze all packets it
receiv es, it switches to operating as a simple concentrator, replicating all
incoming packets to all computers connected to it.
So y ou hav e to f lood the switch with so much traf f ic that it switches into
the broadcasting mode. The best way of doing this is by throwing a bunch of
packets with wrong MAC addresses at the switch. It takes too much of the
switch's resources to analy ze such packets, and it cannot handle the
workload.
The only way to def end against switch f looding is by using more powerf ul
equipment. At present, switches f rom 3Com and Cisco are suf f iciently
powerf ul to handle ev en the maximum load of f ake packets. I hav en't had
an opportunity to test equipment f rom other manuf acturers.
Fooling Routers
Routers can also be f ooled; to be more exact, computers acting as routers can
be f ooled. Suppose that y our network consists of sev eral subnetworks
connected using routers. Fig. 14.2 shows an example of such a network.
This parameter can also be changed by adding the f ollowing line to the
/etc/sy sctl.conf f ile:
nt.ipv4.conf.all.accept_redirection=0
If there is only one router in y our network, disabling routing redirection will
only enhance the sy stem's security. But ev en if there are more routers in the
network, the network operation will not be af f ected much. At the worst, traf
f ic will hav e to go through two routers instead of taking the direct route.
Because ICMP is necessary f or carry ing out the routing redirection attack,
this protocol can be prohibited by conf iguring the f irewall accordingly. This
will make it impossible f or hackers to send messages to redirect routing.
The f irst computer attack using connection hijack was carried out sev eral
decades ago. But ev en now, the only ef f ectiv e method to oppose this attack
is to encode packets. At the initial stage of establishing a TCP connection
between computers, two counters are created that are incremented with each
sent packet. These counters can be intercepted with the help of network snif f
ers, and at a certain moment hackers can hijack the connection, becoming its
owner and replacing the legitimate client in communications with the serv er.
The legitimate client loses the connection.
In this way, hackers circumv ent all authorization mechanisms. The legal
client is initially authorized at the serv er, but then its connection is hijacked
by hackers, who use it f or their own purposes.
The reason f or the connection v ulnerability lies in the TCP/IP suite being
obsolete. Its creators did not anticipate that someone may eav esdrop on
network traf f ic or try to take ov er the connection. The problem is expected
to be solv ed with the introduction of IPv 6.
Consequently, detecting snif f ing and going af ter the perpetrator is not ef f
ectiv e against snif f ing. You should make snif f ing unproductiv e f or
hackers so that they would not ev en think about resorting to it. The way to
achiev e this is to encry pt all traf f ic.
You cannot trust the network and send y our data in plaintext ov er it. The
times when networks were used only by prof essionals and only as intended
are long gone. Nowaday s, y ou can meet all kinds of people on the Internet, f
rom children to retirees, f rom school students to scientists. What is more
pertinent, there are not only good guy s out there but also those bent on
mischief .
Ev en if hackers intercept a packet with encry pted data, they will not be able
to decry pt it right away unless they hav e the priv ate key, which is
extremely unlikely. They can attempt to break the key, but this process will
take too much time; by the time the packet is decry pted, if it is decry pted, its
data will be of no v alue. Moreov er, the data may be of no interest to the
hackers to start with, but to f ind this out they will hav e to spend time decry
pting it.
Reading this chapter, y ou may get the impression that snif f ing is inherently
harmless and is exclusiv ely a tool of hackers. It may ev en seem that
hardware manuf acturers ought to make their equipment snif f ing-proof on
the hardware lev el.
This is not quite the case. Snif f er sof tware was initially dev eloped as a
programmer and administrator tool, and it is a handy means f or debugging v
arious protocols.
I will not consider all snif f er programs, because there are many of them and
each has its own adv antages and disadv antages. But I can recommend
taking a look at my f av orite and one of the most powerf ul of such
programs: hunt. It can be used to monitor traf f ic, replace ARP records, and
ev en intercept connections.
Another popular and in some cases more conv enient is the dsniffutility
package. This package comprises more than ten utilities and can be used to
solv e any task, both by administrators and hackers. A more detailed
description of the package is giv en in Appendix 2.
14.6. DoS and DDoS Attacks
One of the most destructiv e attacks is the DoS attack. In my opinion, this is
the stupidest thing that hackers could come up with. When they cannot break
into a serv er, they try to put it out of commission by v arious methods,
including f looding its communication links with trash messages.
The f ollowing are short descriptions of the main DoS and DDoS attacks and
way s of protecting against them.
You already know that the pingutility is used f or checking connections with
remote sy stems using ICMP. When the serv er being tested receiv es an
ICMP echo request message, it has to respond with an ICMP echo response
message.
Some operating sy stems could not handle certain ty pes of ping packets. The
reason is that dev elopers of ICMP nev er anticipated that it might be used in
way s other than intended and did not take any steps to protect against such
uses. In particular, the protocol expected users to send packets only of a
certain size. The reliance on users' conscientiousness turned out to be
misplaced and resulted in the Ping of Death attack. For this attack, packets
are f ormed that do not f ollow the protocol specif ications. Serv ers cannot
process such packets and hang. The most notorious attack was the one
implemented by sending a packet more than 64 KB in size. If only 64 KB are
reserv ed to receiv e data, this is not suf f icient to receiv e ov ersized packets
and the serv er hangs. Thus, this is essentially a v ariety of the buf f er ov erf
low attack.
The only def ense against such attacks is to use a f irewall conf igured to
prohibit receiv ing ICMP echo request packets. All new operating sy stems
and appropriately patched older ones are not susceptible to this attack.
Another v ariety of the DoS attack is ICMP f lood, in which, as the name
suggests, the serv er is simply f looding the target with ICMP packets. The
perpetrator only needs a channel half the bandwidth of the channel of the
attacked sy stem.
attacked sy stem.
The def ense against this attack is the same as against the Ping of Death
attack, namely, prohibiting ICMP traf f ic. This will not result in much
inconv enience, because this protocol is not really necessary, especially f or
incoming Internet traf f ic.
The attack's essence consists of sending numerous TCP packets with the SYN
f lag set to the serv er. Packets of this ty pe are used to establish serv er
connections. Once the limit on the number of in-progress open connections is
reached, the serv er stops responding to requests f or new connections.
This sort of attack is practically impossible to def end against by y our own
means. You can conf igure the f irewall to prohibit SYN packets, but this will
be of little use.
The best def ense can only be implemented programmatically. At the least,
the program should of f er an option to change the size of the in-progress
connection queue and the timeout f or partially -open connections. It should
also giv e an option f or prohibiting establishing sev eral connections f rom
the same IP address.
14.6.4. TCP Flood
This attack is similar to the ICMP f lood attack. If a hacker is not smart
enough to f ind a v ulnerability in the sy stem, he or she may decide to f lood
the serv er with trash TCP packets. The ef f iciency of TCP packets is
sometimes lower than that of ICMP packets. While with ping echo requests
the serv er pinged is required to answer with echo response messages, with
TCP the response messages are not alway s required. Consequently, the
hacker's channel must be of the same bandwidth or ev en wider than that of
the sy stem being attacked.
HTTP can be used to f lood a serv er with requests to download a large f ile.
Combined with inef f ectiv e caching, this can make the serv er unav ailable
to serv icing legitimate requests.
But TCP has an adv antage. In most networks, outside ICMP traf f ic is
blocked by f irewalls, but TCP traf f ic to public resources cannot be blocked
if such resources are to remain av ailable to the public.
14.6.5. UDP
Bugs in UDP programs are especially dangerous, because this protocol does
not establish a v irtual connection. This protocol simply sends packets into
the network and has no data authenticity -v erif ication mechanisms. While it
is dif f icult to f ake IP address in TCP communications, doing this with UDP
communications is too easy.
Fortunately, UDP is seldom used on public serv ers and it can be prohibited
by appropriate f irewall settings. If the protocol is necessary, protection can
only be implemented programmatically by creating some sort of UDP-based
authenticity check of receiv ed packets.
It can be said that DoS attacks with a f uture are the DDoS attacks. Bugs in
programs that made it possible to disable a serv er with a f ew packets are
getting f ewer ev ery day, because programmers are dev oting more attention
to security aspects when writing network programs. But DDoS attacks do not
rely that much on bugs, and there is no really ef f ectiv e and univ ersal def
ense against this ty pe of attack.
Howev er, it is dif f icult to implement a really massiv e DDoS attack, and
large companies ev en used to think that such attacks were practically
impossible. Ev en the largest hacker group with the widest bandwidth
channels cannot approach the computational resources of such serv ers as
www.yahoo.com or www.microsoft.com. But where is a will, there is a way,
and hackers keep on coming up with new tricks.
DDoS attacks of ten are carried out using powerf ul zombied machines with
wide bandwidth channels. This giv es hackers all they need f or successf ul
DDoS resources.
We can expect new, more ef f ectiv e, and original DDoS attacks in the f
uture. Administrators are powerless to prev ent such attacks, and here lawenf
orcement agencies should step in.
The buf f er-ov erf low issue was cov ered in Section 14.2, and y ou already
know that these errors can be dealt with without ev en waiting f or the sof
tware bugs to be f ixed. All that has to be done is to patch the kernel
prohibiting code f rom the stack to be executed.
A strange thing is that the number of bugs does not decrease with time.
Identical errors can be f ound in dif f erent programs — sometimes
committed by the same programmers. Buf f er-ov erf low problems are well
described in v oluminous literature, y et programmers continue to make the
same old mistakes. This is telling about the low quality of programmer
education.
The problem can be solv ed if sof tware-dev eloping companies start to use
higher-quality human resources.
As usual, the most ef f ectiv e def ense against DoS attacks based on sof
tware bugs is updating sof tware regularly. But attacks directed at ov
erloading serv er resources are dif f icult to def end against. Still, y ou can
make it more dif f icult f or the hacker.
First, the serv er's weakest point has to be determined. This is done by
making the serv er work at the maximum workload. This can be achiev ed by
recruiting lots of users to access the serv er as f requently as possible, or by
running a special program emulating this process.
Determine the spots in y our sy stem that can become bottlenecks, and take
steps to f ortif y them. It would make no sense to build up y our external
communication channels to 100-Mb/sec bandwidth if y ou local network
works only at 10 Mb/sec. Hitting the serv er with 10 Mb/sec of traf f ic will
consume all y our local network resources no matter how wide y our outside
channel is. This is why it is so important to determine the potential
bottlenecks in y our sy stem.
Conf igure y our network interf aces and the operating sy stem f or the
maximum productiv ity (see Section 14.11). This means that there should be
no resource waste, especially of the network resources. The expenditures f or
processing network traf f ic and the traf f ic itself can be reduced by
completely prohibiting ICMP traf f ic.
The IP address is f ollowed by the net mask specif y ing how many of the
address bits def ine the network ID. In this case, all computers in the network
are specif ied. This will make the program send a ping request to all IP
addresses in the network and will show, which of them are used by
computers.
Using the ping packets is a handy and quick way to scan a network, but it can
produce incorrect results if the target network is protected by a f irewall conf
igured to prohibit ping packets.
Af ter breaking into one of the network's computers, the network can be
scanned f or computers again, this time f rom the compromised machine.
This scanning may produce more precise results because it is not hindered by
the f irewall.
The computer broken into may hav e trusted relations with the serv er. In
Linux, computers can be specif ied that can be trusted; that is, they can
connect to the serv er without undergoing the authentication procedure. Nev
er use trusted relations, because this is a huge blow to security. This is why
the subject of using trusted relations is not considered in this book.
The login password f or the compromised computer may be the same as that f
or the main serv er. Also, the /etc/passwd f ile of ten contains inf ormation f
or users that work with the serv er. Users normally don't like remembering
the password f or each serv er or computer and use the same parameters f or
connecting to any computer in the network.
There is no guarantee that inf ormation will contain the login inf ormation f
or the main serv er administrator. But quite of ten all y ou need is to get y our
f oot in a cracked door to take ov er the whole sy stem.
Regular users are not the only ones using the same password f or accessing
dif f erent serv ers; administrators also are guilty of this practice. For
example, an administrator may change the user name f or a dif f erent serv er
but use the same password. Hackers collect all passwords they come across
and then use them to crack the root password.
To tell the truth, I am guilty of using the same password f or dif f erent serv
ices. I, howev er, use a dif f erent login password f or each sy stem. I only use
the same password when using harmless serv ices, f or example, when
registering on f orums or on sites collecting some statistics.
You should protect each computer equally well and use dif f erent passwords
f or users who hav e root priv ileges.
But, as I hav e already said, conv enience and security are two incompatible
things, and NFS is just too conv enient. NFS includes theshowmountutility to
show, which directories are mounted by which users. This is important inf
ormation f or administrators. Executing theshowmount -a localhost command
produces inf ormation similar to the f ollowing:
All mount points on localhost:
robert:/home/robert
econom:/home/john buh:/home/andrew
roberet:/usr/local/etc
econom:/usr/games
The entries consist of two f ields separated by a colon. The f irst f ield
contains the name of the computer, on which the partition is mounted; the
second f ield shows the path to the mounted resource on the serv er.
In the preceding example, v arious directories f rom the /home partition are
mounted. Most of ten, directory names coincide with user names. This makes
it easy to determine the actual user names on a giv en sy stem without
consulting the /etc/passwd f ile. Knowing user names makes it much easier to
pick passwords f or them.
The list shows the names of the network's computers. If y ou hav e gone to
great lengths to secure y our DNS serv er, y ou nullif y all of y our ef f orts by
running NFS on one of the serv ers. One command will show the names of
the network's computers. Ev en though not all computers will be shown, but
only those working with NFS, this inf ormation may be enough f or the
hacker. This makes probing the network with ping requests unnecessary,
because the computers in the network are already shown.
In Linux, program directories can be named as the program name and its v
ersion, f or example ./jail 1.0. If any of such directories is mounted, the
hacker can f ind out what programs users work with and, most important, the
program v ersions.
Depending on which directories are mounted, much more inf ormation can be
gathered. Thus, NFS utilities disclose too much inf ormation, which should
not be allowed.
If y ou decide to use NFS, take care that it is not av ailable f rom the Internet.
For this, y ou will hav e to conf igure the f irewall to prohibit outside
connections to the UDP and TCP port 2049. But the f irewall will only
protect the sy stem f rom outside connections. If hackers hav e already
broken into one of the network's computers and can execute commands
within the network, the f irewall will be of little use.
The /etc/exports f ile contains a list of directories that may be shared with
NFS clients, the clients that can share these directories, and the clients' access
rights. Nev er allow complete access to the entire sy stem. For this, make sure
that the f ile does not contain the f ollowing entry :
/ rw
The paths to the directories allowed to be mounted by a user should be
explicitly specif ied. If users are allowed to mount home directories, the
/home rwpermission is dangerous and should not be used.
Most security specialists share the opinion that NFS should not be used. If y
ou decided to use it only because sof tware on the workstations was centrally
installed, y ou should ov ercome y our laziness and install sof tware on each
computer indiv idually.
How can y ou go about this? There are many methods. I will consider the
most interesting and ef f ectiv e of them.
So, what does this method consist of ? Af ter entering the sy stem, the hacker
alway s starts looking around and try ing to f ind a way to f ortif y his or her
positions to remain in the sy stem as long as possible and unnoticeable to the
administrator. To this end, the hacker most of ten uses thewho, su, cat, and
similar commands. Your task is to place traps on these commands. For
example, the code of thesuprogram can be changed so that a message is
mailed to the administrator ev ery time it is inv oked.
A message that a high-risk command has been executed by a user other than
the administrator is a good cause to check the sy stem f or the presence of an
intruder in it.
Now create a dummy f or the who f ile. This will be a f ile named who in the
/usr/bin directory that will be executed when thewhocommand is called. This
is created by f irst executing the f ollowing command:
cat /usr/bin/who
Now, ev ery thing entered f rom the console will be recorded into the
/usr/bin/who f ile. Enter the f ollowing two lines:
/usr/bin/system_who
id | mail -n -s attack root@FlenovM
Exit the entry mode and sav e the f ile by pressing the <Ctrl>+<D> key
combination. Change the f ile permissions of the just-created who f ile to-
rwxr-xr-x,or 755 in the numerical notation.
Execute the whocommand. This will produce the expected results but also
will send a letter to the administrator's mailbox. The letter will contain all
parameters about the user who inv oked the command as returned by theid
command (Fig. 14.3).
Figure 14.3: An
example of an attack notif ication
email
The mechanism that produces this result f unctions as f ollows: When the
who command is inv oked, the custom who f ile is executed. This f ile
contains two commands.
In this way, all high-risk programs that should not be av ailable to regular
users can be modif ied.
Hackers most of ten do not check the utilities they launch, ev en though the
telltale inf ormation can be readily discov ered by executing the regularcat
command:
cat /usr/bin/who
This is where the shortcoming of using scripts becomes apparent: They can
be v iewed as regular text f iles. Programs written in C and then compiled
into an executable f ile can show only the queer garbage when v iewed in a
text editor or other text v iewers.
Fig. 14.4 shows how a classical honey -pot network is organized. This
network is protected f rom the Internet by a f irewall. Behind the f irewall are
public resources and sham serv ers and workstations. This sham network is
separated f rom the actual priv ate network by another f irewall.
When a hacker swallows the bait and starts rummaging in the honey -pot
network, administrators can inv estigate where he or she came f rom without
running the risk of destroy ing important data.
To prev ent y our trap f rom snatching ev ery one who touches, as well as f
rom generating f alse alarms, its protections should be hard enough not to be
circumv ented by hackers using exploit programs. Otherwise, there will be
hundreds, if not more, hackers caught in it ev ery day, because a popular
resource is scanned countless times daily.
I conf igure my honey -pot serv ers f or maximum security but let the f
irewall protecting them (Firewall 1 in Fig. 14.4) pass practically all traf f ic
into the public network. This kills sev eral birds with one stone:
If the honey -pot sy stem, which is protected as well as the real sy stem, has
been broken into, this means that the priv ate network is also v ulnerable. I
can learn about this v ulnerability by examining the techniques used by the
hacker to penetrate the honey -pot network. In this way, attacks unknown to
the security community until now can be detected and def ense methods
against such attacks can be dev ised.
As soon as I notice that the honey -pot serv er has been compromised, I
undertake the f ollowing steps:
Analy ze the v ulnerability used by the hacker to obtain access. Hav ing f
ound the weak spot, I look f or a patch and install it on the computers in the
priv ate network, to prev ent the hacker f rom using this v ulnerability to
break into the sensitiv e area.
Determine the source of the break-in, such as the IP address or street address,
and pass all this inf ormation on to lawenf orcement agencies.
Because honey -pot sy stems do not process actual user requests, they do not
require powerf ul hardware. Obsolete hardware that no longer can be used f
or modern applications will suf f ice. Any administrator alway s has old junk
piled up in the of f ice and used f or spare parts.
If y ou don't hav e any old computers, y ou can use public serv ers f or the
honey -pot network. In essence, public serv ers are already supposed to
maintain powerf ul monitoring and logging sy stems, dif f ering f rom honey -
pot serv ers only in that they should not hav e known v ulnerabilities and easy
passwords.
To prev ent hackers f rom suspecting trickery and make them interested in the
honey -pot sy stems, equipping such a sy stem with strong def ense is not
enough. The computers hav e to do something and process some traf f ic.
This can be achiev ed with the help of specially -dev eloped utilities that
imitate network operation on the honey -pot sy stem. A computer that is just
sitting there doing nothing sticks out like a sore thumb, and only a dummy
will try to break into it.
The adv antage of this method is that if the password is in the dictionary, it
can be f ound quite quickly. If the password is a simple word that can be f
ound in any English dictionary, the number of possible passwords will not
exceed 20,000, the approximate number of the most of ten used words in the
English language.
The hacker's task is to prepare the dictionary using the most ef f ectiv e
potential passwords. First, all possible inf ormation about the administrator is
collected: his or her name; the names of his or her spouse, f riend, relativ es,
and pets; hobbies; f av orite music and mov ies; and so on. Passwords built
based on this inf ormation are placed in the beginning of the dictionary.
Practice shows that most people use passwords of this ty pe, and most of ten
those related to their hobbies.
But the chance that a strong password, which is made up of digits and sy
mbols in addition to letter and uses both uppercase and lowercase characters,
will be included in the dictionary approaches zero; consequently, the time
spent picking the password using a dictionary will be wasted. In this case, the
enumeration, or brute-f orce, method is resorted to.
The program goes through all possible combinations of letters, digits, and sy
mbols in both uppercase and lowercase. There are billions of possible
combinations, the exact number depending on the password length. The
longer the password, the more possible combinations there are and the more
time needed to pick it.
The method is 100% successf ul. But this method is time-consuming; it can
take weeks to months, if not y ears, to crack a really strong password.
Moreov er, if passwords are changed monthly, when a hacker cracks a
password, it may no longer be v alid.
A hacker tries to crack the password when logging into a sy stem remotely.
This is the most dangerous method f or the hacker, because each unsuccessf
ul attempt is recorded in a security log. If the administrator at least
occasionally inspects the log, the break-in attempt will be discov ered in the
early stages and nipped in the bud by prohibiting connections f rom the
hacker's IP address.
Another problem with remote password cracking is that the password discov
ered will be to a certain serv ice only and there is no guarantee that another
serv ice will use the same password. To make password cracking more dif f
icult, most serv ices are conf igured to limit the number of password entry
attempts, f or example, to three. If no correct password is supplied within
three attempts, the connection is broken of f and has to be established again.
Establishing a connection takes extra time, which also increases the time
necessary to crack the password using the dictionary method.
To make password cracking a lengthy process, some serv ices insert a delay
af ter an incorrectly -entered password bef ore allowing another login
attempt. A good example of this is the operating sy stem. When an incorrect
login or password is supplied when logging into the sy stem, the v erif ication
process takes longer than when the correct parameters are prov ided. The
delay may seem insignif icant when y ou simply misty pe a parameter once,
but it adds up when y ou are going through thousands of v ariations.
The real names of the users registered on the serv er are known.
The serv er-protection mechanisms against password cracking are no longer
ef f ectiv e.
Because passwords in the f ile are encry pted, each possible password also
has to be encry pted bef ore it is compared with the password stored in the f
ile. The encry ption process adds to the ov erall time necessary to crack a
password; howev er, its negativ e ef f ects depend on the number of
passwords in the f ile. Instead of try ing all possible password combinations
against one encry pted password, each combination is f irst tried against all
entries in the password f ile. The greater the number of password entries in
the f ile, the higher the chances that the combination will f it one of them.
Also, the larger the password f ile is, the greater the chances are that at least
one of the users chose the account name f or the password.
Local password cracking is much f aster and saf er f or the hacker than the
remote method. But it has its own problem, which is obtaining the
/etc/shadow f ile. The only user that has the read and write rights to this f ile
is the administrator, with the rest of the users hav ing no rights to it.
In principle, there is not, and can't be, 100% protection against password
cracking. If a hacker obtains access to the /etc/shadow f ile, y ou can take it f
or granted that at least one password will be broken. But y ou can make
password cracking more dif f icult or prev ent its negativ e ef f ects by f
ollowing these rules:
Protect the /etc/shadow f ile by all possible means. Although all users hav e
to hav e read access rights to the /etc/passwd f ile to be able to use numerous
utilities, they hav e no need f or the /etc/shadow f ile.
Create a f ile named, f or example, pass.txt, and enter into it the text to be
used as the password. For example:echo "password" >> pass.txt.
Encry pt the f ile by executing the f ollowing command: openssl des -in
pass.txt -out pass.txt.s. The key to be used f or encry pting does not matter; y
ou can enter any word.
The text sav ed in the pass.txt f ile will be encry pted and sav ed in the
pass.txt.s f ile. Open this f ile, choose readable characters, and build a
password f rom them. This password cannot be cracked using the dictionary
method; the brutef orce method has to be used.
Fiv e is the optimal number. Giv ing users f ewer chances may cause
problems f or especially f orgetf ul users. But unless a user suf f ers f rom
amnesia, if the correct password is not entered af ter f iv e tries, there is a
good chance that password breaking is taking place.
John the Ripper is the most popular password-cracking program among most
hackers and administrators. The program supports the main encry ption
algorithms: MD5, DES, and Blowf ish.
The second command starts John the Ripper. If y ou want to use y our own
dictionary f ile, specif y it using the f ollowing command:
john -wordfile:filename pass.txt
Here, filenameis the name of the dictionary f ile. Linux has a built-in
dictionary, stored in the /usr/share/dict/words f ile. At the dawn of the
Internet, the f amous Morris worm broke into the largest, at the time, number
of computers using only the UNIX dictionary (there was no Linux y et). The
Linux built-in dictionary is specif ied by executing the f ollowing command:
john -wordfile: /usr/share/dict/words pass.txt
While John the Ripper is hard at work, pressing any key will display inf
ormation about the status of the process. To interrupt the program, press the
<Ctrl>+<C> key combination. To resume work, execute the f ollowing
command:
john -restore
The f ile with the cracked passwords can be v iewed by executing the f
ollowing command:
john -show pass.txt
I already stated that the best way to enhance security and ef f iciency is to
load only the most necessary programs and serv ices. The more serv ices
loaded, the more memory and processor resources consumed.
Af ter y ou hav e decided on the serv ices to use and cut their number to the
minimum, y ou hav e to conf igure each of these serv ices f or maximum
productiv ity. The minimization principle applies here. For example, the
Apache serv ice loads lots of modules that most sites do not need. Each
unnecessary module is a blow to security and ef f iciency.
Minimizing the number of modules f or each serv ice allows the greatest perf
ormance to be achiev ed. This said, consider how y ou can f ine-tune y our sy
stem.
Start by opening the /etc/sy sctl.conf f ile, which stores the kernel parameters.
Listing 14.1 shows an example of the f ile's contents.
Listing 14.1: The contents of the /etc/sysctl.conf configuration file
# Kernel sysctl configuration file for Red Hat Linux.
# For binary values, 0 is disabled, 1 is enabled. See sysctl(8) for # more
details.
kernel.sysrq = 1
kernel.core_uses_pid = 1
#net.ipv4.tcp_ecn = 0
kernel.grsecurity.fifo_restrictions = 1 kernel.grsecurity.linking_restrictions =
1
I'll consider the f unction of the parameters sav ed in the f ile, using as an
example thenet.ipv4.tcp_ecnparameter. This is a path, relativ e to the /proc/sy
s directory, to the tcp_ecn f ile, namely : /proc/sy s/net/ipv 4/tcp_ecn. Execute
the f ollowing command to v iew the contents of the f ile: cat
/proc/sys/net/ipv4/tcp_ecn
The sy stem will display 0 or 1, which is the v alue of this parameter. You
can change the v alue manually, but it's more conv enient to do this by
executing the f ollowing command:
The v alues of most parameters are Boolean, meaning they can be either 0
(disabled) or 1 (enabled).
The f ollowing are the parameters that should be changed. If they are not in
the sy sctl.conf f ile, they should be added to it.
The asterisk character is a wild card and stands f or any directory name.
There can be sev eral subdirectories in the net/ipv 4/conf directory, one f or
each network interf ace. There should be at least f our such subdirectories in
y our sy stem:
all — Contains conf iguration f iles f or all interf aces
The asterisk indicates that the parameter must be set f or all interf aces whose
parameter f iles are stored in the subdirectories of the net/ipv 4/conf
directory. In most cases, the all directory can be substituted f or the asterisk,
but sometimes all existing subdirectories hav e to be specif ied.
These are some of the main kernel parameters. There are too many of them f
or each to be considered in this book. I adv ise y ou to consult the pertinent
documentation f or inf ormation on parameters not included in the preceding
ov erv iew.
To display the parameters of the hard driv e, the partition is specif ied as the
parameter:
hdparm /dev/hda2
The results produced look similar to the f ollowing:
/dev/hda2:
multcount = 128 (on)
IO_support = 0 (default 16-bit)
unmaskirq = 0 (off)
using_dma = 1 (on)
keepsettings = 0 (off)
readonly = 0 (off)
readahead = 8 (on)
geometry = 2088/255/63, sectors = 32515560, start = 1028160
multcount — The number of words read in one cy cle. This parameter must
be enabled, and it adv isable to set its v alue to 128. Doing this can raise the
ef f iciency 30% to 50%. The v alue is changed using themXoption, whereXis
the new v alue.
IO_support — The driv e access mode. The def ault can be the 16-bit mode,
but currently the 32-bit mode can be used. This mode can be enabled by
thec3option.
The preceding three parameters can really enhance hard driv e ef f iciency.
To set them to the recommended v alues, execute the f ollowing command:
hdparm -m128d1c3/dev/hda
As y ou can see, I simply listed all necessary key s and specif ied the disk, to
which they apply. Note that there are no digits, f or example,hda1, in the disk
name. Digits used with a disk name specif y a disk partition, but access can
only be changed f or the whole disk and not its indiv idual partitions.
The modif ied parameters hav e to be sav ed as f ollows: hdparm -k1 /dev/hda
Now, execute the disk read speed-testing command:dhparm -t /dev/hda.
14.11.3. Automount
Because Linux is striv ing to mov e in to the home computer area, its latest
distributions include the def ault automatic mounting option. This is done
with the help of theautofsserv ice. Check that this serv ice runs on start-up; if
it does, y ou can start conf iguring it.
The serv ice's main conf iguration f ile is /etc/auto.master. The f ollowing are
its contents:
# $Id: auto.master,v 1.2 1997/10/06 21:52:03 hpa Exp $ # Sample
auto.master file
# Format of this file:
# mountpoint map options
# For details of the format, look at autofs(8).
/misc /etc/auto, misc --timeout=60
Only the last entry in the f ile is supposed to do something, the rest are only
explanatory comments. This entry may be commented out in y our sy stem;
uncomment it to use the automatic mounting f eature.
cd -fstype=iso9660,ro,nosuid,nodev :/dev/cdrom
:/dev/hdal :/dev/fd0
:/dev/fd0
:/dev/fd0
:/dev/sdcl :/dev/hdd
The last parameter, --timeout=60, is the idleness period. If during this period
there is no activ ity in the directory, into which the dev ice is mounted, the
dev ice is unmounted. The def ault timeout v alue is 60 seconds. In most
cases, this is an acceptable v alue.
There is only one entry not commented out in the /etc/auto.misc f ile. This
entry mounts the CD-ROM:
cd -fstype=iso9660,ro,nosuid,nodev :/dev/cdrom
The f irst parameter in the command specif ies the subdirectory in the /misc
directory, into which the dev ice will be mounted. The second parameter
specif ies the parameters of f ile sy stem of the dev ice to be mounted and the
options to be used f or mounting. For a CD-ROM, the iso9660f ile sy stem is
used; the f ile sy stem is mounted f or read only, and SUID and DEV are
prohibited. The last parameter specif ies the dev ice to be mounted.
14.12. Miscellaneous
Recommendations
In the course of the book, I hav e considered numerous aspects of the task of
creating a secure sy stem; howev er, some of the recommendations I would
like to of f er could not be placed into any of the topics considered. Theref
ore, I decided to place all of them at the end of the book.
Packet f ragmentation is of ten used to carry out attacks on serv ers. Linux
can be conf igured to def ragment incoming packets. If y our kernel is
monolithic (i.e., lacks module support), this can be achiev ed by writing 1 to
the /proc/sy s/net/ipv 4/ip_alway s_def rag f ile. This can be done by
executing the f ollowing command:
echo 1 > /proc/sys/net/ipv4/ip_always_defrag
Source routing inv olv es specif y ing the route, ov er which a packet is mov
ed f rom the source to the destination. Sometimes, this is a handy option, but,
as y ou already know, what is conv enient usually is not secure. The
sourcerouting f eature is better disabled, and it would be the best if it had nev
er been inv ented.
So how does source routing af f ect security ? Suppose that y ou detected an
attack attempt f rom address 192.168.1.1 and took countermeasures by conf
iguring the f irewall to prohibit connections f rom this address. Because
routers send all packets f rom the hackers through this address, the hackers
can no longer connect to y our sy stem. But they can use the source-routing f
eature to specif y the route, by which their packets are to be mov ed to y our
sy stem and to exclude the router, or a serv er play ing the role of a router,
with the disallowed address f rom this route.
14.12.3. SNMP
There are three v ersions of this protocol. The f irst v ersion was dev eloped a
long time ago and does not employ encry ption. The encry ption option was
added to SNMP in the second v ersion. Theref ore, y ou are recommended
not to use the f irst v ersion of the protocol; in the best case, it should be
disabled altogether.
Another drawback of SNMP is that it uses UDP as the transport. This means
that SNMP packets are transmitted as pay load inside of UDP packets.
Because UDP does not support v irtual connection and just send packets
without any authorization, any f ields of its packets can be f aked.
I recommend not using SNMP, because most tasks do not require it. The
encry ption f eature added in the second v ersion has raised the protocol's
security signif icantly, and it can be used f or especially important tasks. You
hav e to make sure, howev er, that the second or a higher v ersion of the
protocol is on hand bef ore using it f or tasks requiring data protection.
When running some utility, most users and ev en administrators simply enter
the command's name, which may lead to a break-in. Thus, y ou should specif
y the complete path when launching any program.
The script contains only three commands — or, rather, only two because the f
irst two commands are the same, just applied to dif f erent f iles. These f irst
two chmodcommands change access rights to the /etc/passwd and
/etc/shadow f iles. Moreov er, any sy stem messages that may be produced
when these commands are executed are redirected to the /dev /null dev ice
and are not display ed on the screen. The second command in the script f ile
executes the legitimate ls sy stem command f rom the /bin directory.
Now, set the f ile's execute permission so that it can be executed by any user:
chmod 777 /tmp/ls
The f ake lsf ile is ready. But now it has to be made to execute instead of the
sy stem's legitimatelsf ile. This is an easy enough task: Simply add the /tmp
directory at the beginning of thePATHsy stem env ironment v ariable. Now,
if thelscommand is executed without its f ull path specif ied, executed instead
of it will be the script f ile, which will try to change access rights to the
password f iles. If the user who executes the command has enough priv ileges
f or this, the attempt will be successf ul and y ou can consider the sy stem as
good as cracked.
The conclusion that should be drawn f rom this example is that y ou should
regularly check the contents of thePATHenv ironment v ariable f or potential
modif ications. If y ou f ind that the v ariable has been changed, y ou can
consider y our sy stem compromised and should initiate the post-break-in
procedure.
Bef ore installing any program, determine where it stores its passwords and
whether they are encry pted and how. Set such f ile permissions that only the
specif ic user and the administrator can hav e access to them. It is desirable
that groups are assigned zero rights, especially if there is more than one user
in a group.
If a separate group is created f or each user, the group may be giv en some
rights. Nev ertheless, I would recommend against this, because y ou nev er
know what may become of a group in the f uture. A hacker may add himself
or herself to a group, or y ou may join sev eral users into one group.
I recommend to all my users not to sav e passwords in programs. This means,
f or example, that the password has to be supplied ev ery time a user checks
his or her mail. This is inconv enient, especially if y ou hav e more than one
mailbox, which nowaday s is a norm. But ev en with only one mailbox, users
are dif f icult to conv ince to memorize passwords and not sav e them in the
sy stem.
But passwords hav e to be entered directly into the program; ideally, they
should not be display ed on the screen. This means that passwords should not
be specif ied in the command line, which display s all data entered into it.
One of the most common security threats presented by using standard ports is
that they can be scanned. For example, a hacker discov ers that there is a bug
in a particular database. Suppose that this database uses port 1457. All the
hacker needs to do to f ind v ulnerable databases is to scan the network f or
computers with port 1457 open. Hav ing detected such machines, the hacker
can write a program that exploits the v ulnerability on all of these machines.
The problem is easily solv ed by reconf iguring the serv ice to use another
port and remov ing any banners that may be display ed when a connection to
this port is being established. This will prev ent the hacker f rom learning
what port the program uses and how to work with it.
If serv ices are used by a limited number of people, the ports of the most v
ulnerable serv ices (e.g., those that allow users to upload f iles to or execute
commands on the serv er) can hav e their places switched. For example, make
the FTP serv ice work on port 80 and the Web serv ice on port 21. Unf
ortunately, public serv ices cannot be made to work on dif f erent ports. For
example, making a Web serv er work on port 81 instead of the standard port
80 would require that ev ery potential user of this serv ice be inf ormed of
this change. This def eats the purpose of port switching, because a hacker is
also a potential user.
Start log analy zes by checking the sy stem's conf iguration as explained in
Section 12.3. The reports of the log-analy zing programs bef ore and af ter the
break-in should be compared. This will help y ou determine what the hacker
has done in the sy stem. Remov e any rootkits y ou discov er.
As the next step, v erif y the checksums of all main f iles, especially of the
conf iguration f iles f rom the /etc directory and of the executable f iles f rom
the /bin directory. These f iles can be changed by hackers to plant a back door
to the sy stem and to remain in it unnoticed. Hav ing f ound all changes, try to
restore the af f ected f iles to their initial state.
Next, check the integrity of the installed modules. For this, execute the f
ollowing command:
rpm -qa | grep kernel
If y our serv er prov ides Web serv er serv ices, I would not put the serv er
back online until all of the Web scripts hav e been checked. Only then can y
ou put the serv er back online and start close monitoring of the sy stem.
Here is where y ou start analy zing logs to determine how exactly the hacker
perf ormed the break-in, simultaneously monitoring the running sy stem. If
the hacker tries to surreptitiously enter the sy stem again, y ou should be able
to detect this and stop this attempt bef ore it's carried out so that y ou would
not hav e to analy ze and clean the sy stem again.
While y ou are analy zing the logs, all users hav e to change their serv er
login passwords and their passwords to all serv ices.
You should determine the f ollowing f rom the log analy zes: The serv ices
used by the hacker and in which logs the hacker's activ ity in the serv er is
recorded
The parameters of the accounts the hacker was able to discov er and use
The commands the hacker has executed
It is desirable to obtain as much inf ormation as possible about the hacker and
to turn this inf ormation ov er to law-enf orcement agencies. Don't try to
alway s f ight hackers on y our own, because y ou cannot alway s win.
Feeling inv ulnerable, hackers will continue breaking in, and with each break-
in the chances increase that they will get what they are af ter. Ask the law enf
orcement agencies that hav e the appropriate jurisdiction and f acilities to f
ind and stop the hacker.
Part 1: Appendixes
Appendix List
Appendix 1: FTP Commands Appendix 2:Usef ul Programs Appendix
3:Internet Resources
cd path — Change the current directory to the specif ied one. The cd‥
command takes y ou one lev el up; thecd directorycommand takes y ou to the
specif ied directory on the next lev el down.
dsnif f — Intercepts passwords (the main utility ). The utility monitors the
network f or authorization packets. When it detects such a packet, the utility
extracts and display s the password. Authorization packets f or all of the main
protocols — Telnet, FTP, POP, etc. — are supported.
dnsspoof — Sends f ake DNS packets. If the target machine requests that a
host name be resolv ed to its IP address, y ou can switch the reply f rom the
DNS serv er to make the target connect to y our computer instead of the
requested host.
msgsnaf — Monitors Internet pager and chat messages, such as ICQ and
IRC. macof — Floods a switch with packets with generated MAC addresses.
If the switch f ails to handle the route-resolution workload, it starts f
unctioning as a simple hub, replicating the incoming traf f ic to all outgoing
ports.
Conclusion
I hope that this book has helped y ou to learn more about security in general
and about Linux security in particular. In it, I described at length v arious
computer attack methods and def enses f rom those attacks. This may make y
ou f orm an impression that all ev ery administrator is doing is f ighting of f
bad guy s try ing to break into his or her sy stem. My opinion is that there are
no hackers and crackers. This is a scary tale inv ented to f righten
administrators.
In any f ield of activ ity, there are strong and weak play ers. Most hackers are
y oung people who simply happen to know more than others and can use
their knowledge. For some reason, the inf ormation technologies f ield is
considered a domain of gurus possessing almost supernatural knowledge.
Perhaps, there was some truth to this conception at the dawn of the computer
era, but it ceased to be this way a long, long time ago. Computers hav e
become an inseparable part of our liv es, as commonplace as telephones and
telev ision sets. Thus, they should be treated accordingly.
When y ou soup up y our car, y ou may not be breaking any laws. The manuf
acturer certainly cannot prohibit y ou f rom doing this. The warranty, of
course, will be v oided, and there is no guarantee that the modif ications will
not kill the car way bef ore its time. But y ou likely will not be persecuted f or
being an auto hacker.
All this means is that the main weapon f or f ighting hackers should be
knowledge. If y our sy stem has been compromised, it does not necessarily
mean that y ou should dev ote y our outmost ef f orts to sending to prison the
person who did this. You simply should giv e more attention to y our serv er's
security. If the ov erall lev el of knowledge and expertise and,
correspondingly, the lev el of Internet serv ices can be increased, there will be
f ar f ewer break-ins.
Constantly enhance y our knowledge base, raise the lev el of y our expertise,
and expand y our inf ormation store. Don't just rely on ready solutions to
protect y our sy stem. Leav ing y our sy stem f ull of holes is the same as leav
ing the canary cage's door open in a room with a hungry cat. Don't rely on the
law to protect y our sy stem: The most lawenf orcement agencies can do is
catch the v illain who stole y our conf idential inf ormation or destroy ed it.
But other than giv ing y ou some moral satisf action, this will hardly be of
any help. So y ou should be the one to protect y our sy stem. Remember, God
helps those who help themselv es.