Gentoo Websites Logo
Go to: Gentoo Home Documentation Forums Lists Bugs Planet Store Wiki Get Gentoo!
View | Details | Raw Unified | Return to bug 71211 | Differences between
and this patch

Collapse All | Expand All

(-)original/gentoo-security.xml (-3917 / +7 lines)
Lines 1-3936 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version='1.0' encoding='UTF-8'?>
2
<!-- $Header: /var/www/www.gentoo.org/raw_cvs/gentoo/xml/htdocs/doc/en/gentoo-security.xml,v 1.81 2005/05/23 19:34:03 swift Exp $ -->
2
<!-- $Header: /var/www/www.gentoo.org/raw_cvs/gentoo/xml/htdocs/doc/en/gentoo-security.xml,v 1.81 2005/05/23 19:34:03 swift Exp $ -->
3
3
<!DOCTYPE guide SYSTEM "/dtd/guide.dtd">
4
<!DOCTYPE guide SYSTEM "/dtd/guide.dtd">
4
<guide link="/doc/en/gentoo-security.xml">
5
<guide link = "/doc/en/gentoo-security.xml">
5
<title>Gentoo Linux Security Guide</title>
6
<title>Gentoo Linux Security Guide</title>
6
<author title="Author">
7
  <mail link="kn@insecurity.dk">Kim Nielsen</mail>
8
</author>
9
<author title="Editor"><!-- zhen@gentoo.org -->
10
  John P. Davis
11
</author>
12
<author title="Editor">
13
  <mail link="stocke2@gentoo.org">Eric R. Stockbridge</mail>
14
</author>
15
<author title="Editor">
16
  <mail link="carl@gentoo.org">Carl Anderson</mail>
17
</author>
18
<author title="Editor">
19
  <mail link="peesh@gentoo.org">Jorge Paulo</mail>
20
</author>
21
<author title="Editor">
22
  <mail link="swift@gentoo.org">Sven Vermeulen</mail>
23
</author>
24
<author title="Editor">
25
  <mail link="bennyc@gentoo.org">Benny Chuang</mail>
26
</author>
27
<author title="Editor">
28
  <mail link="jaervosz@itu.dk">Sune Jeppesen</mail>
29
</author>
30
<author title="Editor">
31
  <mail link="blubber@gentoo.org">Tiemo Kieft</mail>
32
</author>
33
<author title="Editor">
34
        <mail link="klasikahl@gentoo.org">Zack Gilburd</mail>
35
</author>
36
<author title="Editor">
37
  <mail link="krispykringle@gentoo.org">Dan Margolis</mail>
38
</author>
39
7
40
<abstract>
8
<abstract>
41
This is a step-by-step guide for hardening Gentoo Linux.
9
Deprecated.
42
</abstract>
10
</abstract>
43
11
44
<license/>
45
46
<version>0.4.48</version>
47
<date>2005-05-23</date>
48
49
<chapter>
12
<chapter>
50
<title>Introduction</title>
13
<title>Introduction</title>
51
<section>
14
<section>
52
<body>
15
<body>
53
16
54
<p>
17
<p>
55
This guide is intended for people who are using Gentoo Linux in a server based
18
This guide has been deprecated in favor of the 
56
environment or just feel the need for better security.
19
<uri link="/doc/en/security/index.xml">Gentoo Linux Security Handbook</uri>
57
</p>
58
59
<note>
60
If you are interested in even more Gentoo security stuff after reading this
61
guide then have a look at the <uri link="http://www.gentoo.org/proj/en/hardened/">Hardened Gentoo Project</uri>
62
</note>
63
64
</body>
65
</section>
66
67
<!-- 
68
<section>
69
<title>Enhancements for future releases of this Guide:</title>
70
<body>
71
72
<p>
73
In version 0.6 (Backup)
74
</p>
75
<ul>
76
<li>Arpwatch</li>
77
<li>Full system backup using Systemimager</li>
78
<li>Partial backup using tar</li>
79
<li>Backing up postgres</li>
80
</ul>
81
82
83
<p>
84
In version 0.8 (Penetration testing)
85
</p>
86
<ul>
87
<li>Remote audits</li>
88
<li>Network audits</li>
89
<li>Host audits</li>
90
<li>Software audits</li>
91
</ul>
92
93
<p>
94
In version 1.0 (After a compromise)
95
</p>
96
<ul>
97
<li>How to report an incident</li>
98
<li>Forensics analysis</li>
99
<li>Creating an image of the system without destroying evidence (Using dd)</li>
100
<li>Trap and trace (Using tcpdump)</li>
101
<li>.. More to come ..</li>
102
<li>Restoring system</li>
103
</ul>
104
105
<note>
106
Please note that each version concentrates on one subject at a time.  This is for
107
quality assurance purposes.
108
</note>
109
110
</body>
111
</section>
112
-->
113
</chapter>
114
115
<chapter>
116
<title>Pre-Installation Concerns</title>
117
<section>
118
<title>Physical Security</title>
119
<body>
120
121
<p>
122
No matter how many safeguards you implement, they can all be easily circumvented
123
by an attacker with physical access to your computer. Despite this, there are
124
at least some measures that can be taken to provide a degree of security against
125
an attacker with physical access to your machine. Putting your hardware in a
126
locked closet prevents an attacker from simply unplugging it and carting it
127
off. Locking your computer's case is also a good idea, to make sure that an
128
attacker cannot simply walk away with your hard drive. To prevent an attacker
129
from booting from another disk, nicely circumventing your permissions and login
130
restrictions, try setting the hard drive as the first boot device in your BIOS,
131
and setting a BIOS password. It is also important to set a LILO or GRUB boot
132
password, to prevent a malicious user from booting into single-user mode and
133
gaining complete access to your system. This is covered in more detail in
134
Chapter 3, under <uri link="#passwording_GRUB">Setting a GRUB password</uri>
135
and <uri link="#passwording_LILO">Setting a LILO password</uri>.
136
</p>
137
138
</body>
139
</section>
140
<section>
141
<title>Daemon/Service Planning</title>
142
<body>
143
<p>
144
Start by documenting what services this machine should run. This will help you
145
compose a better partition scheme for your system, and allow you to better plan
146
your security measures. Of course, this is unnecessary if the machine serves a
147
single simple purpose, such as a desktop, or a dedicated firewall. In those
148
cases, you should not be running <e>any</e> services, except perhaps sshd.
149
</p>
150
<p>
151
This list can also be used to aid system administration. By keeping a current
152
list of version information, you will find it much easier to keep everything up
153
to date if a remote vulnerability is discovered in one of your daemons.
154
</p>
155
156
</body>
157
</section>
158
<section>
159
<title>Partitioning Schemes</title>
160
<body>
161
162
<p>
163
Partitioning rules:
164
</p>
165
166
<ul>
167
<li>
168
  Any directory tree a user should be able to write to (e.g. <path>/home</path>, 
169
  <path>/tmp</path>) should be on a separate partition and use disk quotas. This
170
  reduces the risk of a user filling up your whole filesystem. Portage
171
  uses <path>/var/tmp</path> to compile files, so that partition should be large.
172
</li>
173
<li>
174
  Any directory tree where you plan to install non-distribution software on should
175
  be on a separate partition. According to the <uri link="http://www.pathname.com/fhs/">File Hierarchy Standard</uri>, this
176
  is <path>/opt</path> or <path>/usr/local</path>.  If these are separate
177
  partitions, they will not be erased if you have to reinstall the system.
178
</li>
179
<li>
180
  For extra security, static data can be put on a separate partition that is
181
  mounted read-only. For the truly paranoid, try using read-only media like
182
  CD-ROM.
183
</li>
184
</ul>
185
186
</body>
187
</section>
188
<section>
189
<title>The root user</title>
190
<body>
191
192
<p>
193
The user 'root' is the most vital user on the system and should not be
194
used for anything except when absolutely necessary. If an attacker gains root
195
access, the only way to ever trust your system again is to reinstall.
196
</p>
197
198
<p>
199
Golden rules about 'root'
200
</p>
201
202
<ul>
203
<li>
204
  Always create a user for everyday use and if this user needs to have root
205
  access, add the user to the group 'wheel'. This makes it possible for a normal
206
  user to <c>su</c> to root.
207
</li>
208
<li>
209
  Never run X or any other user application as root. root should only be used when
210
  absolutely necessary; if a vulnerability exists in an application running as a
211
  user, an attacker can gain user level access. But if that application is running
212
  as root, the attacker gains root access.
213
</li>
214
<li>
215
  Always use absolute paths when logged in as root (or always use <c>su -</c>,
216
  which replaces the environmental variables of the user with those of root,
217
  while being sure root's <c>PATH</c> only includes protected directories
218
  like <path>/bin</path> and <path>/sbin</path>). It's possible to trick
219
  root into running a different application rather than the one meant to be
220
  run. If root's <c>PATH</c> is protected or root only uses absolute paths, we can
221
  be sure this won't happen.
222
</li>
223
<li>
224
  If a user only needs to run a few commands as root, instead of everything that
225
  root normally can do, consider using <c>sudo</c> instead. Just be careful who
226
  you give this access to, as well!
227
</li>
228
<li>
229
  Never leave the terminal when you are logged in as root.
230
</li>
231
</ul>
232
233
<p>
234
Gentoo has some default protection against normal users trying to <c>su</c> to
235
root. The default PAM setting requires that a user be a member of the group
236
"wheel" in order to be able to <c>su</c>.
237
</p>
238
239
</body>
240
</section>
241
<section id="security_policies">
242
<title>Security policies</title>
243
<body>
244
245
<p>
246
There are several reasons to draft a security policy for your system(s) and
247
network.
248
</p> 
249
250
<ul>
251
<li>
252
  A good security policy allows you to outline security as a "system", rather
253
  than simply a jumble of different features. For example, without a policy an
254
  administrator might decide to turn off telnet, because it transmits
255
  unencrypted passwords, but leave on FTP access, which has the same weakness. A
256
  good security policy allows you to identify which security measures are
257
  worthwhile, and which are not.
258
</li>
259
<li>
260
  In order to diagnose problems, conduct audits, or track down intruders, it may
261
  be necessary to intercept network traffic, inspect the login and command
262
  history of users, and look in home directories. Without outlining this in
263
  print, and making users aware of this, such actions may actually be illegal
264
  and put <e>you</e> in legal jeopardy.
265
</li>
266
<li>
267
  Hijacked user accounts pose one of the most common threats to system
268
  security. Without explaining to users why security is important, and how to
269
  practice good security (such as not writing passwords on a Post-It note on
270
  their desks), it is unlikely you will have any hope of secure user accounts.
271
</li>
272
<li>
273
  A well-documented network and system layout will aid you, as well as law
274
  enforcement forensics examiners, if need be, in tracing an intrusion and
275
  identifying weaknesses after the fact. A security policy "issue" banner,
276
  stating that your system is a private network and all unauthorized access is
277
  prohibited, will also help ensure your ability to properly prosecute an
278
  intruder, once he is caught.
279
</li>
280
</ul>
281
282
<p>
283
The need for a good security policy is hopefully now more than clear.
284
</p>
285
286
<p>
287
The policy itself is a document, or several documents, that outlines the network
288
and system features (such as what services are provided), acceptable use and
289
forbidden use, security "best practices", and so forth. All users should be made
290
aware of your security policy, as well as changes you make to keep it up to
291
date. It is important that you take the time to help users understand your
292
policy and why that policy needs to be signed or what will happens if they act
293
directly against the policy (the policy should also state this). This should be
294
repeated at least once a year, since the policy can change (but also as a
295
reminder to the user of the policy itself).
296
</p>
297
298
<note>
299
Create policies that are easy to read and be very precise on every subject.
300
</note>
301
302
<p>
303
A security policy should at least contain the following subjects:
304
</p>
305
306
<ul>
307
<li>Acceptable use
308
  <ul>
309
  <li>Screen savers</li>
310
  <li>Password handling</li>
311
  <li>Software download and installation</li>
312
  <li>Information stating if the users are being monitored</li>
313
  <li>Use of anti-virus software</li>
314
  </ul>
315
</li>
316
<li>Handling of sensitive information (any written form, paper or digital)
317
  <ul>
318
  <li>Clean desk and locked up classified information</li>
319
  <li>PC shutdown before leaving</li>
320
  <li>Use of encryption</li>
321
  <li>Handling of keys to trusted co-workers</li>
322
  <li>Handling of confidential material when traveling</li>
323
  </ul>
324
</li>
325
<li>Handling of computer equipment when traveling
326
  <ul>
327
  <li>Laptop handling during travels and hotel stays</li>
328
  </ul>
329
</li>
330
</ul>
331
332
<p>
333
Different users may require different levels or types of access, and as such
334
your policy may vary to accommodate them all.
335
</p>
336
337
<p>
338
The security policy can become huge, and vital information can easily be
339
forgotten. The IT-staff's policy could contain information that is confidential
340
for the ordinary user, so it is wise to split it up into smaller policies;
341
e.g. Acceptable Use Policy, Password policy, Email policy and Remote Access
342
policy.
343
</p>
344
345
<p>
346
You can find example policies at <uri link="http://www.sans.org/resources/policies/">The SANS Security Policy
347
Project</uri>. If you have a small network and think these policies are too much
348
you should look at the <uri link="ftp://ftp.isi.edu/in-notes/rfc2196.txt">Site Security
349
Handbook</uri>.
350
</p>
351
352
</body>
353
</section>
354
</chapter>
355
356
<chapter>
357
<title>Tightening security during and after installation</title>
358
<section>
359
<title>USE flags</title>
360
<body>
361
362
<p>
363
The <path>make.conf</path> file contains user defined USE flags and
364
<path>/etc/make.profile/make.defaults</path> contains the default USE flags for
365
Gentoo Linux. For this guide's purposes, the important flags are <c>pam</c>
366
(Pluggable Authentication Modules), <c>tcpd</c> (TCP wrappers), and <c>ssl</c>
367
(Secure Socket Layer). These are all in the default USE flags.
368
</p>
369
370
</body>
371
</section>
372
<section id="passwording_GRUB">
373
<title>Password protecting GRUB</title>
374
<body>
375
376
<p>
377
GRUB supports two different ways of adding password protection to your boot
378
loader. The first uses plain text, while the latter uses md5+salt encryption.
379
</p>
380
381
<pre caption="/boot/grub/grub.conf">
382
timeout 5
383
password changeme
384
</pre>
385
386
<p>
387
This will add the password <c>changeme</c>. If no password is entered at boot,
388
GRUB will simply use the default boot setting.
389
</p>
390
391
<p>
392
When adding an md5 password, you must convert your password into crypt format,
393
which is the same format used in <path>/etc/shadow</path>. For more information
394
see <c>man crypt</c>. The encrypted password <e>changeme</e>, for example, could
395
look like this: <c>$1$T7/dgdIJ$dJM.n2wZ8RG.oEiIOwJUs</c>.
396
</p>
397
398
<p>
399
You can encrypt your password directly at the GRUB shell:
400
</p>
401
402
<pre caption="md5crypt in grub shell">
403
#<i>/sbin/grub</i>
404
405
GRUB version 0.92 (640K lower / 3072K upper memory)
406
407
   [ Minimal BASH-like line editing is supported. For the first word, TAB lists
408
     possible command completions. Anywhere else TAB lists the possible
409
     completions of a device/filename. ]
410
411
grub&gt; <i>md5crypt</i>
412
413
Password: <i>********</i>
414
<comment>(Typed changeme at the prompt)</comment> 
415
Encrypted: $1$T7/dgdIJ$dJM.n2wZ8RG.oEiIOwJUs.
416
417
grub&gt; <i>quit</i>
418
</pre>
419
420
<p>
421
Then, cut and paste your password to <path>/boot/grub/grub.conf</path>.
422
</p>
423
424
<pre caption="/boot/grub/grub.conf">
425
timeout 5 
426
password --md5 $1$T7/dgdIJ$dJM.n2wZ8RG.oEiIOwJUs.
427
</pre>
428
429
<p>
430
The 5 seconds timeout becomes handy if the system is remote and should be able
431
to reboot without any keyboard interaction. Learn more about GRUB passwords by
432
executing <c>info grub</c>.
433
</p>
434
435
</body>
436
</section>
437
<section id="passwording_LILO">
438
<title>Password protecting LILO</title>
439
<body>
440
441
<p>
442
LILO also supports two ways of handling passwords: global and per-image, both in
443
clear text.
444
</p>
445
446
<p>
447
The global password is set at the top of the configuration file, and applies to
448
every boot image:
449
</p>
450
451
<pre caption="/etc/lilo.conf">
452
password=changeme 
453
restricted 
454
delay=3
455
</pre>
456
457
<p>
458
The per-image password is set as below:
459
</p>
460
461
<pre caption="/etc/lilo.conf">
462
image=/boot/bzImage 
463
      read-only 
464
      password=changeme 
465
      restricted
466
</pre>
467
468
<p>
469
If the <c>restricted</c> option is not entered, it will prompt for a password
470
every time.
471
</p>
472
473
<p>
474
In order to store the new information in <path>lilo.conf</path>, you must run
475
<c>/sbin/lilo</c>.
476
</p>
477
478
</body>
479
</section>
480
<section>
481
<title>Restricting Console Usage</title>
482
<body>
483
484
<p>
485
The <path>/etc/securetty</path> file allows you to specify which <c>tty</c>
486
(terminal) devices root is allowed to login in from.
487
</p>
488
489
<p>
490
We suggest that you comment out all lines except <c>vc/1</c>. This will ensure
491
that root only can login once and only on one terminal.
492
</p>
493
494
<note>
495
Users in the group "wheel" can still <c>su -</c> to become root on other TTYs.
496
</note>
497
498
<pre caption="/etc/securetty">
499
vc/1
500
</pre>
501
502
</body>
503
</section>
504
</chapter>
505
506
<chapter>
507
<title>More logging</title>
508
<section>
509
<body>
510
511
<p>
512
Extra logging should be added to catch warnings or errors that might indicate
513
an ongoing attack or a successful compromise. Attackers often scan or probe
514
before attacking.
515
</p>
516
517
<p>
518
It's also vital that your log files are easily readable and manageable. Gentoo
519
Linux lets you choose between 3 different loggers when installing.
520
</p>
521
522
</body>
523
</section>
524
<section>
525
<title>Logging: Syslogd</title>
526
<body>
527
528
<p>
529
Syslogd is the most common logger for Linux and Unix in general. 
530
It has some log rotation facilities, but using 
531
<path>/usr/sbin/logrotate</path> in a cron job (logrotate is configured in
532
<path>/etc/logrotate.conf</path>) might prove to be more powerful as
533
<c>logrotate</c> has many features. How often 
534
log rotation should be done depends on the system load.
535
</p>
536
537
<p>
538
Below is the standard <path>syslog.conf</path> with some added features. We 
539
have uncommented the <c>cron</c> and <c>tty</c> lines and added a remote 
540
logging server. To further enhance security you could add logging to two places.
541
</p>
542
543
<pre caption="/etc/syslog.conf">
544
#  /etc/syslog.conf      Configuration file for syslogd.
545
#
546
#                       For more information see syslog.conf(5)
547
#                       manpage.
548
#                       This is from Debian, we are using it for now
549
#                       Daniel Robbins, 5/15/99
550
551
#
552
# First some standard logfiles.  Log by facility.
553
#
554
555
auth,authpriv.*                 /var/log/auth.log
556
*.*;auth,authpriv.none          -/var/log/syslog
557
cron.*                         /var/log/cron.log
558
daemon.*                        -/var/log/daemon.log
559
kern.*                          -/var/log/kern.log
560
lpr.*                           -/var/log/lpr.log
561
mail.*                          /var/log/mail.log
562
user.*                          -/var/log/user.log
563
uucp.*                          -/var/log/uucp.log
564
local6.debug                    /var/log/imapd.log
565
566
#
567
# Logging for the mail system. Split it up so that
568
# it is easy to write scripts to parse these files.
569
#
570
mail.info                       -/var/log/mail.info
571
mail.warn                       -/var/log/mail.warn
572
mail.err                        /var/log/mail.err
573
574
# Logging for INN news system
575
#
576
news.crit                       /var/log/news/news.crit
577
news.err                        /var/log/news/news.err
578
news.notice                     -/var/log/news/news.notice
579
580
#
581
# Some `catch-all' logfiles.
582
#
583
*.=debug;\
584
        auth,authpriv.none;\
585
        news.none;mail.none     -/var/log/debug
586
*.=info;*.=notice;*.=warn;\
587
        auth,authpriv.none;\
588
        cron,daemon.none;\
589
        mail,news.none          -/var/log/messages
590
591
#
592
# Emergencies and alerts are sent to everybody logged in.
593
#
594
*.emerg                         *
595
*.=alert                        *
596
597
#
598
# I like to have messages displayed on the console, but only on a virtual
599
# console I usually leave idle.
600
#
601
daemon,mail.*;\
602
       news.=crit;news.=err;news.=notice;\
603
       *.=debug;*.=info;\
604
       *.=notice;*.=warn       /dev/tty8
605
606
#Setup a remote logging server
607
*.*                        @logserver
608
609
# The named pipe /dev/xconsole is for the `xconsole' utility.  To use it,
610
# you must invoke `xconsole' with the `-file' option:
611
# 
612
#    $ xconsole -file /dev/xconsole [...]
613
#
614
# NOTE: adjust the list below, or you'll go crazy if you have a reasonably
615
#      busy site..
616
#
617
#daemon.*,mail.*;\
618
#       news.crit;news.err;news.notice;\
619
#       *.=debug;*.=info;\
620
#       *.=notice;*.=warn       |/dev/xconsole
621
622
local2.*                --/var/log/ppp.log
623
</pre>
624
625
<p>
626
Attackers will most likely try to erase their tracks by editing or deleting log
627
files. You can make it harder for them by logging to one or more remote logging
628
servers on other machines. Get more info about syslogd by executing <c>man
629
syslog</c>.
630
</p>
631
632
</body>
633
</section>
634
<section>
635
<title>Metalog</title>
636
<body>
637
638
<p>
639
<uri link="http://metalog.sourceforge.net">Metalog</uri> by Frank Dennis is not
640
able to log to a remote server, but it does have advantages when it comes to
641
performance and logging flexibility. It can log by program name, urgency,
642
facility (like syslogd), and comes with regular expression matching with which
643
you can launch external scripts when specific patterns are found. It is very good
644
at taking action when needed.
645
</p> 
646
647
<p>
648
The standard configuration is usually enough.  If you want to be notified by
649
email whenever a password failure occurs use one of the following scripts.
650
</p>
651
652
<p>
653
For postfix:
654
</p>
655
656
<pre caption="/usr/local/sbin/mail_pwd_failures.sh for postfix">
657
#! /bin/sh
658
echo "$3" | mail -s "Warning (program : $2)" root
659
</pre>
660
661
<p>
662
For qmail:
663
</p>
664
665
<pre caption="/usr/local/sbin/mail_pwd_failures.sh for qmail">
666
#!/bin/sh
667
echo "To: root
668
Subject:Failure (Warning: $2) 
669
$3
670
" | /var/qmail/bin/qmail-inject -f root
671
</pre>
672
673
<p>
674
Remember to make the script executable by issuing <c>/bin/chmod +x 
675
/usr/local/sbin/mail_pwd_failures.sh</c>
676
</p>
677
678
<p>
679
Then uncomment the command line under "Password failures" in 
680
<path>/etc/metalog/metalog.conf</path> like:
681
</p>
20
</p>
682
21
683
<pre caption="/etc/metalog/metalog.conf">
684
command  = "/usr/local/sbin/mail_pwd_failures.sh"
685
</pre>
686
687
</body>
22
</body>
688
</section>
23
</section>
689
<section>
690
<title>Syslog-ng</title>
691
<body>
692
693
<p>
694
Syslog-ng provides some of the same features as syslog and metalog with a small
695
difference. It can filter messages based on level and content (like metalog),
696
provide remote logging like syslog, handle logs from syslogd (even streams from
697
Solaris), write to a TTY, execute programs, and it can act as a logging server.
698
Basically it is the best of both loggers combined with advanced configuration.
699
</p>
700
701
<p>
702
Below is a classic configuration file slightly modified.
703
</p>
704
705
<pre caption="/etc/syslog-ng/syslog-ng.conf">
706
options { long_hostnames(off); sync(0); };
707
708
#source where to read log
709
source src { unix-stream("/dev/log"); internal(); };
710
source kernsrc { file("/proc/kmsg"); };
711
712
#define destinations
713
destination authlog { file("/var/log/auth.log"); };
714
destination syslog { file("/var/log/syslog"); };
715
destination cron { file("/var/log/cron.log"); };
716
destination daemon { file("/var/log/daemon.log"); };
717
destination kern { file("/var/log/kern.log"); };
718
destination lpr { file("/var/log/lpr.log"); };
719
destination user { file("/var/log/user.log"); };
720
destination mail { file("/var/log/mail.log"); };
721
722
destination mailinfo { file("/var/log/mail.info"); };
723
destination mailwarn { file("/var/log/mail.warn"); };
724
destination mailerr { file("/var/log/mail.err"); };
725
726
destination newscrit { file("/var/log/news/news.crit"); };
727
destination newserr { file("/var/log/news/news.err"); };
728
destination newsnotice { file("/var/log/news/news.notice"); };
729
730
destination debug { file("/var/log/debug"); };
731
destination messages { file("/var/log/messages"); };
732
destination console { usertty("root"); };
733
destination console_all { file("/dev/tty12"); };
734
destination xconsole { pipe("/dev/xconsole"); };
735
736
#create filters
737
filter f_auth { facility(auth); };
738
filter f_authpriv { facility(auth, authpriv); };
739
filter f_syslog { not facility(authpriv, mail); };
740
filter f_cron { facility(cron); };
741
filter f_daemon { facility(daemon); };
742
filter f_kern { facility(kern); };
743
filter f_lpr { facility(lpr); };
744
filter f_mail { facility(mail); };
745
filter f_user { facility(user); };
746
filter f_debug { not facility(auth, authpriv, news, mail); };
747
filter f_messages { level(info..warn) 
748
        and not facility(auth, authpriv, mail, news); };
749
filter f_emergency { level(emerg); };
750
751
filter f_info { level(info); };
752
filter f_notice { level(notice); };
753
filter f_warn { level(warn); };
754
filter f_crit { level(crit); };
755
filter f_err { level(err); };
756
filter f_failed { match("failed"); };
757
filter f_denied { match("denied"); };
758
759
#connect filter and destination
760
log { source(src); filter(f_authpriv); destination(authlog); };
761
log { source(src); filter(f_syslog); destination(syslog); };
762
log { source(src); filter(f_cron); destination(cron); };
763
log { source(src); filter(f_daemon); destination(daemon); };
764
log { source(kernsrc); filter(f_kern); destination(kern); };
765
log { source(src); filter(f_lpr); destination(lpr); };
766
log { source(src); filter(f_mail); destination(mail); };
767
log { source(src); filter(f_user); destination(user); };
768
log { source(src); filter(f_mail); filter(f_info); destination(mailinfo); };
769
log { source(src); filter(f_mail); filter(f_warn); destination(mailwarn); };
770
log { source(src); filter(f_mail); filter(f_err); destination(mailerr); };
771
772
log { source(src); filter(f_debug); destination(debug); };
773
log { source(src); filter(f_messages); destination(messages); };
774
log { source(src); filter(f_emergency); destination(console); };
775
776
#default log
777
log { source(src); destination(console_all); };
778
</pre>
779
780
<p>
781
Syslog-ng is very easy to configure, but it is also very easy to miss something
782
in the configuration file since it is huge. The author still promises some extra
783
features like encryption, authentication, compression and MAC (Mandatory Access
784
Control) control. With these options it will be a perfect for network logging,
785
since the attacker cannot spy on the log.
786
</p>
787
788
<p>
789
And syslog-ng does have one other advantage: it does not have to run as root!
790
</p>
791
24
792
</body>
793
</section>
794
795
<section>
796
<title>Log analysis with Logcheck</title>
797
<body>
798
799
<p>
800
Of course, keeping logs alone is only half the battle. An application such as
801
Logcheck can make regular log analysis much easier. Logcheck is a script,
802
accompanied by a binary called <c>logtail</c>, that runs from your cron daemon
803
and checks your logs against a set of rules for suspicious activity. It then
804
mails the output to root's mailbox.
805
</p>
806
<p>
807
Logcheck and logtail are part of the <c>app-admin/logsentry</c> package.
808
</p>
809
<p>
810
Logcheck uses four files to filter important log entries from the
811
unimportant. These files are <path>logcheck.hacking</path>, which contains known
812
hacking attack messages, <path>logcheck.violations</path>, which contains
813
patterns indicating security
814
violations, <path>logcheck.violations.ignore</path>, which contains keywords
815
likely to be matched by the violations file, allowing normal entries to be
816
ignored, and <path>logcheck.ignore</path>, which matches those entries to be
817
ignored.
818
</p>
819
820
<warn>
821
Do not leave <path>logcheck.violations.ignore</path> empty. Logcheck
822
uses <c>grep</c> to parse logs, some versions of which will take an empty file
823
to mean wildcard. All violations would thus be ignored.
824
</warn>
825
<!-- FIXME: Might want to add more details on logcheck here...I have to install
826
it on Gentoo to figure out how it's configured! -->
827
</body>
828
</section>
829
830
</chapter>
831
832
<chapter>
833
<title>Mounting partitions</title>
834
<section>
835
<body>
836
837
<p>
838
When mounting an <c>ext2</c>, <c>ext3</c>, or <c>reiserfs</c> partition, you
839
have several options you can apply to the file <path>/etc/fstab</path>. The
840
options are:
841
</p>
842
843
<ul>
844
<li>
845
  <c>nosuid</c> - Will ignore the SUID bit and make it just like an ordinary 
846
  file
847
</li>
848
<li>
849
  <c>noexec</c> - Will prevent execution of files from this partition
850
</li>
851
<li>
852
  <c>nodev</c> - Ignores devices
853
</li>
854
</ul>
855
856
<p>
857
Unfortunately, these settings can easily be circumvented by executing a
858
non-direct path. However, setting <path>/tmp</path> to noexec will stop the
859
majority of exploits designed to be executed directly from <path>/tmp</path>.
860
</p>
861
862
<pre caption="/etc/fstab">
863
/dev/sda1 /boot ext2 noauto,noatime 1 1
864
/dev/sda2 none swap sw 0 0
865
/dev/sda3 / reiserfs notail,noatime 0 0
866
/dev/sda4 /tmp reiserfs notail,noatime,nodev,nosuid,noexec 0 0
867
/dev/sda5 /var reiserfs notail,noatime,nodev 0 0
868
/dev/sda6 /home reiserfs notail,noatime,nodev,nosuid 0 0
869
/dev/sda7 /usr reiserfs notail,noatime,nodev,ro 0 0
870
/dev/cdroms/cdrom0 /mnt/cdrom iso9660 noauto,ro 0 0
871
proc /proc proc defaults 0 0
872
</pre>
873
874
<warn>
875
Placing <path>/tmp</path> in <c>noexec</c> mode can prevent certain scripts
876
from executing properly.
877
</warn>
878
879
<note>
880
For disk quotas see <uri link="#doc_chap6_sect3">the Quotas section</uri>.
881
</note>
882
883
<note>
884
I do not set <path>/var</path> to <c>noexec</c> or <c>nosuid</c>, even if files
885
normally are never executed from this mount point. The reason for this is that
886
qmail is installed in <path>/var/qmail</path> and must be allowed to execute 
887
and access one SUID file. I setup <path>/usr</path> in read-only mode since I 
888
never write anything there unless I want to update Gentoo. Then I remount the 
889
file system in read-write mode, update and remount again.
890
</note>
891
892
<note>
893
Even if you do not use qmail, Gentoo still needs the executable bit set on 
894
<path>/var/tmp</path> since ebuilds are made here. But an alternative path can
895
be setup if you insist on having <path>/var</path> mounted in <c>noexec</c>
896
mode.
897
</note>
898
899
</body>
900
</section>
901
</chapter>
902
903
<chapter>
904
<title>User/group limitations</title>
905
<section id="limits_conf">
906
<title>/etc/security/limits.conf</title>
907
<body>
908
909
<p>
910
Controlling resource usage can be very effective when trying to prevent a local
911
Denial of Service or restricting the maximum allowed logins for a group or user.
912
</p>
913
914
<pre caption="/etc/security/limits.conf">
915
*    soft core 0
916
*    hard core 0
917
*    hard nproc 15
918
*    hard rss 10000
919
*    -    maxlogins 2
920
@dev hard core 100000
921
@dev soft nproc 20
922
@dev hard nproc 35
923
@dev -    maxlogins 10
924
</pre>
925
926
<p>
927
If you find yourself trying to set <c>nproc</c> or <c>maxlogins</c> to 0, maybe
928
you should delete the user instead. The example above sets the group <c>dev</c>
929
settings for processes, core file and <c>maxlogins</c>. The rest is set to a
930
default value.
931
</p>
932
933
<note>
934
<path>/etc/security/limits.conf</path> is part of the PAM package and will 
935
only apply to packages that use PAM.
936
</note>
937
938
</body>
939
</section>
940
<section>
941
<title>/etc/limits</title>
942
<body>
943
944
<p>
945
<path>/etc/limits</path> is very similar to the limit file 
946
<path>/etc/security/limits.conf</path>. The only difference is the format and
947
that it only works on users or wild cards (not groups). Let's have a look at a
948
sample configuration:
949
</p>
950
951
<pre caption="/etc/limits">
952
*   L2 C0 U15 R10000
953
kn L10 C100000 U35
954
</pre>
955
956
<p>
957
Here we set the default settings and a specific setting for the user kn.  Limits
958
are part of the sys-apps/shadow package. It is not necessary to set any limits
959
in this file if you have disabled <c>pam</c> in
960
<path>make.conf</path> or not configured PAM properly.
961
</p>
962
963
</body>
964
</section>
965
<section>
966
<title>Quotas</title>
967
<body>
968
969
<warn>
970
Make sure the file systems you are working with support quotas. In order to use
971
quotas on ReiserFS, you must patch your kernel with patches available from <uri link="ftp://ftp.namesys.com/pub/reiserfs-for-2.4/testing/quota-2.4.20">Namesys</uri>. User
972
tools are available from <uri link="http://www.sf.net/projects/linuxquota/">the Linux DiskQuota
973
project</uri>. While quotas do work with ReiserFS, you may encounter other
974
issues while trying to use them--you have been warned!
975
</warn>
976
977
<p>
978
Putting quotas on a file system restricts disk usage on a per-user or per-group
979
basis.  Quotas are enabled in the kernel and added to a mount point
980
in <path>/etc/fstab</path>. The kernel option is enabled in the kernel
981
configuration under <c>File systems-&gt;Quota support</c>. Apply the following
982
settings, rebuild the kernel and reboot using the new kernel.
983
</p>
984
985
<p>
986
Start by installing quotas with <c>emerge quota</c>. Then modify your
987
<path>/etc/fstab</path> and add <c>usrquota</c> and <c>grpquota</c> to the 
988
partitions that you want to restrict disk usage on, like in the example below.
989
</p>
990
991
<pre caption="/etc/fstab">
992
/dev/sda1 /boot ext2 noauto,noatime 1 1
993
/dev/sda2 none swap sw 0 0
994
/dev/sda3 / reiserfs notail,noatime 0 0
995
/dev/sda4 /tmp ext3 noatime,nodev,nosuid,noexec,usrquota,grpquota 0 0
996
/dev/sda5 /var ext3 noatime,nodev,usrquota,grpquota 0 0
997
/dev/sda6 /home ext3 noatime,nodev,nosuid,usrquota,grpquota 0 0
998
/dev/sda7 /usr reiserfs notail,noatime,nodev,ro 0 0
999
/dev/cdroms/cdrom0 /mnt/cdrom iso9660 noauto,ro 0 0
1000
proc /proc proc defaults 0 0
1001
</pre>
1002
1003
<p>
1004
On every partition that you have enabled quotas, create the quota files
1005
(<path>aquota.user</path> and <path>aquota.group</path>) and place them in the
1006
root of the partition.
1007
</p>
1008
1009
<pre caption="Creating the quota files">
1010
# <i>touch /tmp/aquota.user</i>
1011
# <i>touch /tmp/aquota.group</i>
1012
# <i>chmod 600 /tmp/aquota.user</i>
1013
# <i>chmod 600 /tmp/aquota.group</i>
1014
</pre>
1015
1016
<p>
1017
This step has to be done on every partition where quotas are enabled. After
1018
adding and configuring the quota files, we need to add the <c>quota</c> script
1019
to the boot run level.
1020
</p>
1021
1022
<pre caption="Adding quota to the boot runlevel">
1023
# <i>rc-update add quota boot</i>
1024
</pre>
1025
1026
<p>
1027
We will now configure the system to check the quotas once a week by adding the
1028
following line to <path>/etc/crontab</path>:
1029
</p>
1030
1031
<pre caption="Adding quota check to crontab">
1032
0 3 * * 0 /usr/sbin/quotacheck -avug.
1033
</pre>
1034
1035
<p>
1036
After rebooting the machine, it is time to setup the quotas for users and
1037
groups. <c>edquota -u kn</c> will start the editor defined in $EDITOR (default
1038
is nano) and let you edit the quotas of the user kn. <c>edquota -g</c> will do
1039
the same thing for groups.
1040
</p>
1041
1042
<pre caption="Setting up quota's for user kn">
1043
Quotas for user kn: 
1044
/dev/sda4: blocks in use: 2594, limits (soft = 5000, hard = 6500) 
1045
         inodes in use: 356, limits (soft = 1000, hard = 1500)
1046
</pre>
1047
1048
<p>
1049
For more detail read <c>man edquota</c> or the <uri link="http://www.tldp.org/HOWTO/mini/Quota.html">Quota mini howto</uri>.
1050
</p>
1051
1052
</body>
1053
</section>
1054
<section>
1055
<title>/etc/login.defs</title>
1056
<body>
1057
            
1058
<p>
1059
If your security policy states that users should change their password
1060
every other week, change the value <c>PASS_MAX_DAYS</c> to 14
1061
and <c>PASS_WARN_AGE</c> to 7. It is recommended that you use password
1062
aging since brute force methods can find any password, given enough
1063
time. We also encourage you to set <c>LOG_OK_LOGINS</c> to yes.
1064
</p>
1065
1066
</body>
1067
</section>
1068
<section>
1069
<title>/etc/login.access</title>
1070
<body>
1071
1072
<p>
1073
The <path>login.access</path> file is also part of the sys-apps/shadow package,
1074
which provides a login access control table. This table is used to control who
1075
can and cannot login based on user name, group name or host name. By default,
1076
all users on the system are allowed to login, so the file consists only of
1077
comments and examples. Whether you are securing your server or workstation, we
1078
recommend that you setup this file so no one other than yourself (the admin) has
1079
access to the console.
1080
</p>
1081
1082
<note>
1083
These settings do not apply for root.
1084
</note>
1085
1086
<pre caption="/etc/login.access">
1087
-:ALL EXCEPT wheel sync:console
1088
-:wheel:ALL EXCEPT LOCAL .gentoo.org
1089
</pre>
1090
1091
<impo>
1092
Be careful when configuring these options, since mistakes will leave you 
1093
with no access to the machine if you do not have root access.
1094
</impo>
1095
1096
<note>
1097
These settings do not apply to SSH, since SSH does not execute 
1098
<c>/bin/login</c> per default. This can be enabled by setting <c>UseLogin 
1099
yes</c> in <path>/etc/ssh/sshd_config</path>. 
1100
</note>
1101
1102
<p>
1103
This will setup login access so members of the wheel group can login locally 
1104
or from the gentoo.org domain. Maybe too paranoid, but better to be safe than 
1105
sorry.
1106
</p>
1107
1108
</body>
1109
</section>
1110
</chapter>
1111
1112
<chapter>
1113
<title>File permissions</title>
1114
<section>
1115
<title>World readable</title>
1116
<body>
1117
1118
<p>
1119
Normal users should not have access to configuration files or passwords. An
1120
attacker can steal passwords from databases or web sites and use them to
1121
deface--or even worse, delete--data. This is why it is important that your file
1122
permissions are correct. If you are sure that a file is only used by root,
1123
assign it with the permissions <c>0600</c> and assign the file to the correct
1124
user with <c>chown</c>.
1125
</p>
1126
1127
</body>
1128
</section>
1129
<section>
1130
<title>World/Group writable</title>
1131
<body>
1132
1133
<pre caption="Finding world-writable files and directories">
1134
# <i>/usr/bin/find / -type f \( -perm -2 -o -perm -20 \) \ 
1135
   -exec ls -lg {} \; 2&gt;/dev/null &gt;writable.txt</i>
1136
# <i>/usr/bin/find / -type d \( -perm -2 -o -perm -20 \) \ 
1137
   -exec ls -ldg {} \; 2&gt;/dev/null &gt;&gt;writable.txt</i>
1138
</pre>
1139
1140
<p>
1141
This will create a huge file with permission of all files having either write
1142
permission set to the group or everybody. Check the permissions and eliminate
1143
world writable files to everyone, by executing <c>/bin/chmod o-w</c> on the
1144
files.
1145
</p>
1146
1147
</body>
1148
</section>
1149
<section>
1150
<title>SUID/SGID files</title>
1151
<body>
1152
1153
<p>
1154
Files with the SUID or SGID bit set execute with privileges of the <e>owning</e>
1155
user or group and not the user executing the file. Normally these bits are used
1156
on files that must run as root in order to do what they do. These files can lead
1157
to local root compromises (if they contain security holes). This is dangerous
1158
and files with the SUID or SGID bits set should be avoided at any cost. If you
1159
do not use these files, use <c>chmod 0</c> on them or unmerge the package that
1160
they came from (check which package they belong to by using <c>equery</c>; if
1161
you do not already have it installed simply type <c>emerge
1162
gentoolkit</c>). Otherwise just turn the SUID bit off with <c>chmod -s</c>.
1163
</p>
1164
1165
<pre caption="Finding setuid files">
1166
# <i>/usr/bin/find / -type f \( -perm -004000 -o -perm -002000 \) \ 
1167
   -exec ls -lg {} \; 2&gt;/dev/null &gt;suidfiles.txt</i>
1168
</pre>
1169
1170
<p>
1171
This will create a file containing a list of all the SUID/SGID files.
1172
</p>
1173
1174
<pre caption="List of setuid binaries">
1175
/bin/su
1176
/bin/ping
1177
/bin/mount
1178
/bin/umount
1179
/var/qmail/bin/qmail-queue
1180
/usr/bin/chfn
1181
/usr/bin/chsh
1182
/usr/bin/crontab
1183
/usr/bin/chage
1184
/usr/bin/expiry
1185
/usr/bin/sperl5.6.1
1186
/usr/bin/newgrp
1187
/usr/bin/passwd
1188
/usr/bin/gpasswd
1189
/usr/bin/procmail
1190
/usr/bin/suidperl
1191
/usr/lib/misc/pt_chown
1192
/usr/sbin/unix_chkpwd
1193
/usr/sbin/traceroute
1194
/usr/sbin/pwdb_chkpwd
1195
</pre>
1196
1197
<p>
1198
By default Gentoo Linux does not have a lot of SUID files (though this depends
1199
on what you installed), but you might get a list like the one above. Most of the
1200
commands should not be used by normal users, only root. Switch off the SUID bit
1201
on <c>ping</c>, <c>mount</c>, <c>umount</c>, <c>chfn</c>, <c>chsh</c>, <c>newgrp</c>, <c>suidperl</c>, <c>pt_chown</c>
1202
and <c>traceroute</c> by executing <c>chmod -s</c> on every file. Don't
1203
remove the bit on <c>su</c>, <c>qmail-queue</c> or <c>unix_chkpwd</c>. Removing
1204
setuid from those files will prevent you from <c>su</c>'ing and receiving
1205
mail. By removing the bit (where it is safe to do so) you remove the possibility
1206
of a normal user (or an attacker) gaining root access through any of these
1207
files.
1208
</p>
1209
1210
<p>
1211
The only SUID files that I have on my system are <c>su</c>, <c>passwd</c>,
1212
<c>gpasswd</c>, <c>qmail-queue</c>, <c>unix_chkpwd</c> and <c>pwdb_chkpwd</c>.
1213
But if you are running X, you might have some more, since X needs the elevated
1214
access afforded by SUID.
1215
</p>
1216
</body>
1217
</section>
1218
<section>
1219
<title>SUID/SGID binaries and Hard links</title>
1220
<body>
1221
1222
<p>
1223
A file is only considered deleted when there are no more links pointing to it. 
1224
This might sound like a strange concept, but consider that a filename like 
1225
<path>/usr/bin/perl</path> is actually a link to the inode where the data is 
1226
stored. Any number of links can point to the file, and until all of them are
1227
gone, the file still exists.
1228
</p>
1229
1230
<p>
1231
If your users have access to a partition that isn't mounted with <c>nosuid</c>
1232
or <c>noexec</c> (for example, if <path>/tmp</path>, <path>/home</path>, or 
1233
<path>/var/tmp</path> are not separate partitions) you should take care to 
1234
ensure your users don't create hard links to SUID or SGID binaries, so that 
1235
after Portage updates they still have access to the old versions.
1236
</p>
1237
1238
<warn>
1239
if you have received a warning from portage about remaining hard links, and your 
1240
users can write to a partition that allows executing SUID/SGID files, you 
1241
should read this section carefully. One of your users may be attempting to 
1242
circumvent your update by keeping an outdated version of a program. If your 
1243
users cannot create their own SUID files, or can only execute programs using
1244
the dynamic loader (partitions mounted <c>noexec</c>), you do not have to 
1245
worry.
1246
</warn>
1247
1248
<note>
1249
Users do not need read access to a file to create a link to it, they only need 
1250
read permission to the directory that contains it.
1251
</note>
1252
1253
<p>
1254
To check how many links a file has, you can use the <c>stat</c> command.
1255
</p>
1256
1257
<pre caption="Stat command">
1258
$ stat /bin/su    
1259
  File: `/bin/su'
1260
  Size: 29350           Blocks: 64         IO Block: 131072 regular file
1261
Device: 900h/2304d      Inode: 2057419     Links: 1
1262
Access: (4711/-rws--x--x)  Uid: (    0/    root)   Gid: (    0/    root)
1263
Access: 2005-02-07 01:59:35.000000000 +0000
1264
Modify: 2004-11-04 01:46:17.000000000 +0000
1265
Change: 2004-11-04 01:46:17.000000000 +0000
1266
</pre>
1267
1268
<p>
1269
To find the SUID and SGID files with multiple links, you can use <c>find</c>.
1270
</p>
1271
1272
<pre caption="Finding multiply linked suid/sgid binaries">
1273
$ find / -type f \( -perm -004000 -o -perm -002000 \) -links +1 -ls
1274
</pre>
1275
1276
</body>
1277
</section>
1278
</chapter>
1279
1280
<chapter>
1281
<title>PAM (Pluggable Authentication Modules)</title>
1282
<section>
1283
<body>
1284
1285
<p>
1286
PAM is a suite of shared libraries that provide an alternative way providing
1287
user authentication in programs. The <c>pam</c> USE flag is turned on by
1288
default. Thus the PAM settings on Gentoo Linux are pretty reasonable, but there
1289
is always room for improvement. First install cracklib.
1290
</p>
1291
1292
<pre caption="Installing cracklib">
1293
# <i>emerge cracklib</i>
1294
</pre>
1295
1296
<pre caption="/etc/pam.d/passwd">
1297
auth     required pam_unix.so shadow nullok
1298
account  required pam_unix.so
1299
password required pam_cracklib.so difok=3 retry=3 minlen=8 dcredit=2 ocredit=2 
1300
password required pam_unix.so md5 use_authtok
1301
session  required pam_unix.so
1302
</pre>
1303
1304
<p>
1305
This will add the cracklib which will ensure that the user passwords are at
1306
least 8 characters and contain a minimum of 2 digits, 2 other characters, and
1307
are more than 3 characters different from the last password. This forces the
1308
user to choose a good password (password policy). Check the <uri link="http://www.kernel.org/pub/linux/libs/pam/Linux-PAM-html/pam-6.html#ss6.3">PAM</uri>
1309
documentation for more options.
1310
</p>
1311
1312
<pre caption="/etc/pam.d/sshd">
1313
auth     required pam_unix.so nullok 
1314
auth     required pam_shells.so
1315
auth     required pam_nologin.so
1316
auth     required pam_env.so
1317
account  required pam_unix.so
1318
password required pam_cracklib.so difok=3 retry=3 minlen=8 dcredit=2 ocredit=2 use_authtok
1319
password required pam_unix.so shadow md5
1320
session  required pam_unix.so
1321
session  required pam_limits.so
1322
</pre>
1323
1324
<p>
1325
Every service not configured with a PAM file in <path>/etc/pam.d</path> will use
1326
the rules in <path>/etc/pam.d/other</path>. The defaults are set to <c>deny</c>,
1327
as they should be. But I like to have a lot of logs, which is why I
1328
added <c>pam_warn.so</c>. The last configuration is <c>pam_limits</c>, which is
1329
controlled by <path>/etc/security/limits.conf</path>. See <uri link="#limits_conf">/etc/security/limits.conf section</uri> for more on these
1330
settings.
1331
</p>
1332
1333
<pre caption="/etc/pam.d/other">
1334
auth     required pam_deny.so 
1335
auth     required pam_warn.so 
1336
account  required pam_deny.so 
1337
account  required pam_warn.so 
1338
password required pam_deny.so 
1339
password required pam_warn.so 
1340
session  required pam_deny.so 
1341
session  required pam_warn.so
1342
</pre>
1343
1344
</body>
1345
</section>
1346
</chapter>
1347
1348
<chapter>
1349
<title>TCP Wrappers</title>
1350
<section>
1351
<body>
1352
1353
<p>
1354
This is a way of controlling access to services normally run by inetd (which
1355
Gentoo does not have), but it can also be used by xinetd and other services.
1356
</p>
1357
1358
<note>
1359
The service should be executing tcpd in its server argument (in xinetd). See the
1360
chapter on xinetd for more information.
1361
</note>
1362
1363
<pre caption="/etc/hosts.deny">
1364
ALL:PARANOID
1365
</pre>
1366
1367
<pre caption="/etc/hosts.allow">
1368
ALL: LOCAL @wheel
1369
time: LOCAL, .gentoo.org
1370
</pre>
1371
1372
<p>
1373
As you can see the format is very similar to the one
1374
in <path>/etc/login.access</path>. Tcpd supports a specific service; it does not
1375
overlap with <path>/etc/login.access</path>. These settings only apply to
1376
services using tcp wrappers.
1377
</p>
1378
1379
<p>
1380
It is also possible to execute commands when a service is accessed (this can be
1381
used when activating relaying for dial-in users) but it is not recommended,
1382
since people tend to create more problems than they are trying to solve. An
1383
example could be that you configure a script to send an e-mail every time
1384
someone hits the deny rule, but then an attacker could launch a DoS attack by
1385
keep hitting the deny rule. This will create a lot of I/O and e-mails so
1386
don't do it!. Read the <c>man 5 hosts_access</c> for more information.
1387
</p>
1388
1389
</body>
1390
</section>
1391
</chapter>
1392
1393
<chapter>
1394
<title>Kernel security</title>
1395
<section>
1396
<title>Removing functionality</title>
1397
<body>
1398
1399
<p>
1400
The basic rule when configuring the kernel is to remove everything that you do
1401
not need. This will not only create a small kernel but also remove the
1402
vulnerabilities that may lie inside drivers and other features.
1403
</p>
1404
1405
<p>
1406
Also consider turning off loadable module support. Even though it is possible to
1407
add root kits without this features, it does make it harder for normal attackers
1408
to install root kits via kernel modules.
1409
</p>
1410
1411
</body>
1412
</section>
1413
<section>
1414
<title>The proc filesystem</title>
1415
<body>
1416
1417
<p>
1418
Many kernel parameters can be altered through the <path>/proc</path> file system
1419
or by using <c>sysctl</c>.
1420
</p>
1421
1422
<p>
1423
To dynamically change kernel parameters and variables on the fly, you need
1424
<c>CONFIG_SYSCTL</c> defined in your kernel. This is on by default in
1425
a standard 2.4 kernel. 
1426
</p>
1427
1428
<pre caption="Deactivate IP forwarding">
1429
# <i>/bin/echo "0" &gt; /proc/sys/net/ipv4/ip_forward</i>
1430
</pre>
1431
1432
<p>
1433
Make sure that IP forwarding is turned off. We only want this for a
1434
multi-homed host. It's advised to set or unset this flag before all other flags
1435
since it enabled/disables other flags as well.
1436
</p>
1437
1438
<pre caption="Drop ping packets">
1439
# <i>/bin/echo "1" &gt; /proc/sys/net/ipv4/icmp_echo_ignore_all</i>
1440
</pre>
1441
1442
<p>
1443
This will cause the kernel to simply ignore all ping messages (also known as
1444
ICMP type 0 messages). The reason for this is that an IP packet carrying an ICMP
1445
message can contain a payload with information other than you think.
1446
Administrators use ping as a diagnostic tool and often complain if it is
1447
disabled, but there is no reason for an outsider to be able to ping. However,
1448
since it sometimes can be handy for insiders to be able to ping, you can disable
1449
ICMP type 0 messages in the firewall (allowing local administrators to continue
1450
to use this tool).
1451
</p>
1452
1453
<pre caption="Ignore broadcast pings">
1454
# <i>/bin/echo "1" &gt; /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts</i>
1455
</pre>
1456
1457
<p>
1458
This disables response to ICMP broadcasts and will prevent Smurf attacks. The
1459
Smurf attack works by sending an ICMP type 0 (ping) message to the broadcast
1460
address of a network. Typically the attacker will use a spoofed source
1461
address. All the computers on the network will respond to the ping message and
1462
thereby flood the host at the spoofed source address.
1463
</p>
1464
1465
<pre caption="Disable source routed packets">
1466
# <i>/bin/echo "0" &gt; /proc/sys/net/ipv4/conf/all/accept_source_route</i>
1467
</pre>
1468
1469
<p>
1470
Do not accept source routed packets. Attackers can use source routing to
1471
generate traffic pretending to originate from inside your network, but that is
1472
actually routed back along the path from which it came, so attackers can
1473
compromise your network. Source routing is rarely used for legitimate purposes,
1474
so it is safe to disable it.
1475
</p>
1476
1477
<pre caption="Disable redirect acceptance">
1478
# <i>/bin/echo "0" &gt; /proc/sys/net/ipv4/conf/all/accept_redirects</i>
1479
# <i>/bin/echo "0" &gt; /proc/sys/net/ipv4/conf/all/secure_redirects</i>
1480
</pre>
1481
1482
<p>
1483
Do not accept ICMP redirect packets. ICMP redirects can be used to alter your
1484
routing tables, possibly to a malicious end.
1485
</p>
1486
1487
<pre caption="Protect against bad error messages">
1488
# <i>/bin/echo "1" &gt; /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses</i>
1489
</pre>
1490
1491
<p>
1492
Enable protection against bogus error message responses.
1493
</p>
1494
1495
<pre caption="Enable reverse path filtering">
1496
# <i>for i in /proc/sys/net/ipv4/conf/*; do
1497
        /bin/echo "1" &gt; $i/rp_filter
1498
done</i>
1499
</pre>
1500
1501
<p>
1502
Turn on reverse path filtering. This helps make sure that packets use legitimate
1503
source addresses by automatically rejecting incoming packets if the routing
1504
table entry for their source address does not match the network interface they
1505
are arriving on. This has security advantages because it prevents IP spoofing.
1506
We need to enable it for each <path>net/ipv4/conf/*</path> otherwise source
1507
validation isn't fully functional.
1508
</p>
1509
1510
<warn>
1511
However turning on reverse path filtering can be a problem if you use asymmetric
1512
routing (packets from you to a host take a different path than packets from that
1513
host to you) or if you operate a non-routing host which has several IP addresses
1514
on different interfaces.
1515
</warn>
1516
1517
<pre caption="Log all spoofed, source routed and redirect packets">
1518
# <i>/bin/echo "1" &gt; /proc/sys/net/ipv4/conf/all/log_martians</i>
1519
</pre>
1520
1521
<p>
1522
Log spoofed packets, source routed packets and redirect packets.
1523
</p>
1524
1525
<p>
1526
All these settings will be reset when the machine is rebooted. I suggest that
1527
you add them to <path>/etc/sysctl.conf</path>, which is automatically sourced by
1528
the <path>/etc/init.d/bootmisc</path> init script.
1529
</p>
1530
1531
<p>
1532
The syntax for <path>/etc/sysctl.conf</path> is pretty straightforward. Strip
1533
off the <path>/proc/sys/</path> from the previously mentioned paths and
1534
substitute <path>/</path> with <path>.</path>:
1535
</p>
1536
1537
<pre caption="Translating to sysctl.conf">
1538
<comment>(Manual using echo):</comment>
1539
/bin/echo "0" &gt; /proc/sys/net/ipv4/ip_forward
1540
1541
<comment>(Automatic in sysctl.conf:)</comment>
1542
net.ipv4.ip_forward = 0
1543
</pre>
1544
1545
</body>
1546
</section>
1547
<section>
1548
<title>Grsecurity</title>
1549
<body>
1550
1551
<p>
1552
The patch from <uri link="http://grsecurity.net">Grsecurity</uri> is standard in
1553
the Gentoo kernel sources but is disabled by default. Configure your kernel as
1554
you normally do and then configure the Grsecurity options. An in-depth
1555
explanation on the available Grsecurity options (version 1.9) is available on
1556
the <uri link="/proj/en/hardened">Gentoo Hardened</uri> project page.
1557
</p>
1558
1559
<p>
1560
Recent <c>grsec-sources</c> provide the 2.* version of Grsecurity. For more
1561
information on this improved Grsecurity patch set, please consult the
1562
documentation available on the <uri link="http://www.grsecurity.net/">Grsecurity
1563
home page</uri>.
1564
</p>
1565
1566
</body>
1567
</section>
1568
<section>
1569
<title>Kerneli</title>
1570
<body>
1571
1572
<p>
1573
<uri link="http://www.Kerneli.org">Kerneli</uri> is a patch that adds encryption
1574
to the existing kernel. By patching your kernel you will get new options such as
1575
cryptographic ciphers, digest algorithms and cryptographic loop filters.
1576
</p>
1577
1578
<warn>
1579
The kerneli patch is currently not in a stable version for the latest kernel, so
1580
be careful when using it.
1581
</warn>
1582
1583
</body>
1584
</section>
1585
<section>
1586
<title>Other kernel patches</title>
1587
<body>
1588
1589
<ul>
1590
<li><uri link="http://www.openwall.com">The OpenWall Project</uri></li>
1591
<li><uri link="http://www.lids.org">Linux Intrusion Detection System</uri></li>
1592
<li><uri link="http://www.rsbac.org">Rule Set Based Access Control</uri></li>
1593
<li>
1594
  <uri link="http://www.nsa.gov/selinux">NSA's security enhanced kernel</uri>
1595
</li>
1596
<li><uri link="http://sourceforge.net/projects/wolk/">Wolk</uri></li>
1597
</ul>
1598
1599
<p>
1600
And there are probably a lot more. 
1601
</p>
1602
1603
</body>
1604
</section>
1605
</chapter>
1606
1607
<chapter>
1608
<title>Securing Services</title>
1609
<section>
1610
<title>Apache</title>
1611
<body>
1612
1613
<p>
1614
Apache (1.3.26) comes with a pretty decent configuration file but again, we need
1615
to improve some things, like binding Apache to one address and preventing it
1616
from leaking information. Below are the options that you should apply the
1617
configuration file.
1618
</p>
1619
1620
<p>
1621
If you did not disable <c>ssl</c> in your <path>/etc/make.conf</path> before
1622
installing Apache, you should have access to an ssl enabled server. Just add the
1623
following line to enable it.
1624
</p>
1625
1626
<pre caption="/etc/conf.d/apache">
1627
HTTPD_OPTS="-D SSL"
1628
</pre>
1629
1630
<pre caption="/etc/apache/conf/apache.conf">
1631
#Make it listen on your ip
1632
Listen 127.0.0.1
1633
BindAddress 127.0.0.1
1634
#It is not a good idea to use nobody or nogroup - 
1635
#for every service not running as root 
1636
#(just add the user apache with group apache)
1637
User apache
1638
Group apache
1639
#Will keep apache from telling about the version
1640
ServerSignature Off
1641
ServerTokens Prod
1642
</pre>
1643
1644
<p>
1645
Apache is compiled with <c>--enable-shared=max</c> and 
1646
<c>--enable-module=all</c>. This will by default enable all modules, so you
1647
should comment out all modules in the <c>LoadModule</c> section
1648
(<c>LoadModule</c> and <c>AddModule</c>) that you do not use. Restart the
1649
service by executing <c>/etc/init.d/apache restart</c>.
1650
</p>
1651
1652
<p>
1653
Documentation is available at <uri>http://www.apache.org</uri>.
1654
</p>
1655
1656
</body>
1657
</section>
1658
1659
<section>
1660
<title>Bind</title>
1661
<body>
1662
1663
<p>
1664
One can find documentation at the <uri link="http://www.isc.org/products/BIND/bind9.html">Internet Software
1665
Consortium</uri>. The BIND 9 Administrator Reference Manual is also in
1666
the <path>doc/arm</path>.
1667
</p>
1668
1669
<p>
1670
The newer BIND ebuilds support chrooting out of the box. After emerging 
1671
<c>bind</c> follow these simple instructions:
1672
</p>
1673
1674
<pre caption="Chrooting BIND">
1675
ebuild /var/db/pkg/net-dns/bind-9.2.2-r2/bind-9.2.2-r2.ebuild config\`"
1676
<comment>(Before running the above command you might want to change the chroot 
1677
directory in /etc/conf.d/named. Otherwise /chroot/dns will be used.)</comment>
1678
<comment>(You might need to substitute the version number with the current version number )</comment>
1679
</pre>
1680
</body>
1681
</section>
1682
<section>
1683
<title>Djbdns</title>
1684
<body>
1685
1686
<p>
1687
Djbdns is a DNS implementation on the security of which its author is willing to
1688
bet <uri link="http://cr.yp.to/djbdns/guarantee.html">money</uri>. It is very
1689
different from how Bind 9 works but worth a try.  More information can be
1690
obtained from <uri>http://www.djbdns.org</uri>.
1691
</p>
1692
1693
</body>
1694
</section>
1695
1696
<section>
1697
<title>FTP</title>
1698
<body>
1699
1700
<p>
1701
Generally, using FTP (File Transfer Protocol) is a bad idea. It uses unencrypted
1702
data (ie. passwords are sent in clear text), listens on 2 ports (normally port
1703
20 and 21), and attackers are frequently looking for anonymous logins for
1704
trading warez. Since the FTP protocol contains several security problems you
1705
should instead use <c>sftp</c> or HTTP. If this is not possible, secure your
1706
services as well as you can and prepare yourself.
1707
</p>
1708
1709
</body>
1710
</section>
1711
<section>
1712
<title>Mysql</title>
1713
<body>
1714
1715
<p>
1716
If you only need local applications to access the <c>mysql</c> database, 
1717
uncomment the following line in <path>/etc/mysql/my.cnf</path>.
1718
</p>
1719
1720
<pre caption="Disable network access">
1721
skip-networking
1722
</pre>
1723
1724
<p>
1725
Then we disable the use of the LOAD DATA LOCAL INFILE command. This is to
1726
prevent against unauthorized reading from local files. This is relevant when new
1727
SQL Injection vulnerabilities in PHP applications are found.
1728
</p>
1729
1730
<pre caption="Disable LOAD DATA LOCAL INFILE in the [mysqld] section">
1731
set-variable=local-infile=0
1732
</pre>
1733
1734
<p>
1735
Next, we must remove the sample database (test) and all accounts except the
1736
local <c>root</c> account.
1737
</p>
1738
1739
<pre caption="Removing sample database and all unnecessary users">
1740
mysql&gt; <i>drop database test;</i>
1741
mysql&gt; <i>use mysql;</i>
1742
mysql&gt; <i>delete from db;</i>
1743
mysql&gt; <i>delete from user where not (host="localhost" and user="root");</i>
1744
mysql&gt; <i>flush privileges;</i>
1745
</pre>
1746
1747
<warn>
1748
Be careful with the above if you have already configured user accounts.
1749
</warn>
1750
1751
<note>
1752
If you have been changing passwords from the MySQL prompt, you should always
1753
clean out <path>~/.mysql_history</path> and
1754
<path>/var/log/mysql/mysql.log</path> as they store the executed SQL commands
1755
with passwords in clear text.
1756
</note>
1757
1758
</body>
1759
</section>
1760
<section>
1761
<title>Proftpd</title>
1762
<body>
1763
1764
<p>
1765
Proftpd has had several security problems, but most of them seem to have been
1766
fixed. Nonetheless, it is a good idea to apply some enhancements:
1767
</p>
1768
1769
<pre caption="/etc/proftpd/proftpd.conf">
1770
ServerName "My ftp daemon"
1771
#Don't show the ident of the server
1772
ServerIdent on "Go away"
1773
1774
#Makes it easier to create virtual users
1775
RequireValidShell off
1776
1777
#Use alternative password and group file (passwd uses crypt format)
1778
AuthUserFile "/etc/proftpd/passwd"
1779
AuthGroupFile "/etc/proftpd/group"
1780
1781
# Permissions
1782
Umask 077
1783
1784
# Timeouts and limitations
1785
MaxInstances 30
1786
MaxClients 10 "Only 10 connections allowed"
1787
MaxClientsPerHost 1 "You have already logged on once"
1788
MaxClientsPerUser 1 "You have already logged on once"
1789
TimeoutStalled 10
1790
TimeoutNoTransfer 20
1791
TimeoutLogin 20
1792
1793
#Chroot everyone
1794
DefaultRoot ~
1795
1796
#don't run as root
1797
User  nobody
1798
Group nogroup
1799
1800
#Log every transfer
1801
TransferLog /var/log/transferlog
1802
1803
#Problems with globbing
1804
DenyFilter \*.*/
1805
</pre>
1806
1807
<p>
1808
One can find documentation at <uri>http://www.proftpd.org</uri>.
1809
</p>
1810
1811
</body>
1812
</section>
1813
<section>
1814
<title>Pure-ftpd</title>
1815
<body>
1816
1817
<p>
1818
Pure-ftpd is an branch of the original trollftpd, modified for security reasons
1819
and functionality by Frank Dennis.
1820
</p>
1821
1822
<p>
1823
Use virtual users (never system accounts) by enabling the <c>AUTH</c> option.
1824
Set this to <c>-lpuredb:/etc/pureftpd.pdb</c> and create your users by using
1825
<c>/usr/bin/pure-pw</c>. 
1826
</p>
1827
1828
<pre caption="/etc/conf.d/pure-ftpd">
1829
AUTH="-lpuredb:/etc/pureftpd.pdb"
1830
1831
## Misc. Others ##
1832
MISC_OTHER="-A -E -X -U 177:077 -d -4 -L100:5 -I 15"
1833
</pre>
1834
1835
<p>
1836
Configure your <c>MISC_OTHER</c> setting to deny anonymous logins (<c>-E</c>),
1837
chroot everyone (<c>-A</c>), prevent users from reading or writing to files
1838
beginning with a . (dot) (<c>-X</c>), max idle time (<c>-I</c>), limit recursion
1839
(<c>-L</c>), and a reasonable <c>umask</c>.
1840
</p>
1841
1842
<warn>
1843
Do <e>not</e> use the <c>-w</c> or <c>-W</c> options! If you want to have a
1844
warez site, stop reading this guide!
1845
</warn>
1846
1847
<p>
1848
One can find documentation at <uri>http://www.pureftpd.org</uri>.
1849
</p>
1850
1851
</body>
1852
</section>
1853
<section>
1854
<title>Vsftpd</title>
1855
<body>
1856
1857
<p>
1858
Vsftpd (short for very secure ftp) is a small ftp daemon running a reasonably
1859
default configuration. It is simple and does not have as many features as 
1860
pureftp and proftp.
1861
</p>
1862
1863
<pre caption="/etc/vsftpd">
1864
anonymous_enable=NO
1865
local_enable=YES
1866
1867
#read only
1868
write_enable=NO
1869
1870
#enable logging of transfers
1871
xferlog_std_format=YES
1872
1873
idle_session_timeout=20
1874
data_connection_timeout=20
1875
nopriv_user=nobody
1876
1877
chroot_list_enable=YES
1878
chroot_list_file=/etc/vsftpd/chrootlist
1879
1880
ls_recurse_enable=NO
1881
</pre>
1882
1883
<p>
1884
As you can see, there is no way for this service to have individual permissions,
1885
but when it comes to anonymous settings it is
1886
quite good. Sometimes it can be nice to have an anonymous ftp server (for
1887
sharing open source), and vsftpd does a really good job at this.
1888
</p>
1889
1890
</body>
1891
</section>
1892
<section>
1893
<title>Qmail</title>
1894
<body>
1895
1896
<p>
1897
Qmail is often considered to be a very secure mail server. It is written with
1898
security (and paranoia) in mind. It does not allow relaying by default and has
1899
not had a security hole since 1996. Simply <c>emerge qmail</c> and go configure!
1900
</p>
1901
</body>
1902
</section>
1903
<section>
1904
<title>Samba</title>
1905
<body>
1906
1907
<p>
1908
Samba is a protocol to share files with Microsoft/Novell networks and it
1909
should <e>not</e> be used over the Internet. Nonetheless, it still needs
1910
securing.
1911
</p>
1912
1913
<pre caption="/etc/samba/smb.conf">
1914
[global]
1915
  #Bind to an interface
1916
  interfaces = eth0 10.0.0.1/32
1917
1918
  #Make sure to use encrypted password
1919
  encrypt passwords = yes
1920
  directory security mask = 0700
1921
1922
  #allow traffic from 10.0.0.*
1923
  hosts allow = 10.0.0.
1924
1925
  #Enables user authentication 
1926
  #(don't use the share mode)
1927
  security = user
1928
1929
  #Disallow privileged accounts
1930
  invalid users = root @wheel
1931
1932
  #Maximum size smb shows for a share (not a limit)
1933
  max disk size = 102400
1934
1935
  #Uphold the password policy
1936
  min password length = 8
1937
  null passwords = no
1938
1939
  #Use PAM (if added support)
1940
  obey pam restrictions = yes
1941
  pam password change = yes
1942
</pre>
1943
1944
<p>
1945
Make sure that permissions are set correct on every share and remember to read
1946
the <uri link="http://www.samba.org">documentation</uri>.
1947
</p>
1948
1949
<p>
1950
Now restart the server and add the users who should have access to this
1951
service. This is done though the command <path>/usr/bin/smbpasswd</path> with
1952
the parameter <c>-a</c>.
1953
</p>
1954
1955
</body>
1956
</section>
1957
<section>
1958
<title>ssh</title>
1959
<body>
1960
1961
<p>
1962
The only securing that OpenSSH needs is turning on a stronger authentication
1963
based on public key encryption. Too many sites (like
1964
<uri>http://www.sourceforge.net</uri>, <uri>http://www.php.net</uri> and 
1965
<uri>http://www.apache.org</uri>) have suffered unauthorized intrusion
1966
due to password leaks or bad passwords.
1967
</p>
1968
1969
<pre caption="/etc/ssh/sshd_config">
1970
#Only enable version 2
1971
Protocol 2
1972
1973
#Disable root login. Users have to su to root
1974
PermitRootLogin no
1975
1976
#Turn on Public key authentication
1977
PubkeyAuthentication yes
1978
AuthorizedKeysFile      .ssh/authorized_keys
1979
1980
#Disable .rhost and normal password authentication
1981
RhostsAuthentication no
1982
PasswordAuthentication no
1983
PermitEmptyPasswords no
1984
1985
#Only allow userin the wheel or admin group to login
1986
AllowGroups wheel admin
1987
1988
#In those groups only allow the following users
1989
#The @&lt;domainname&gt; is optional but replaces the 
1990
#older AllowHosts directive
1991
AllowUsers kn@gentoo.org bs@gentoo.org
1992
1993
#Logging 
1994
SyslogFacility AUTH
1995
LogLevel INFO
1996
1997
ListenAddress 127.0.0.1
1998
</pre>
1999
2000
<p>
2001
Also verify that you don't have <c>UsePAM yes</c> in your configuration file as
2002
it overrides the public key authentication mechanism.
2003
</p>
2004
2005
<p>
2006
Now all that your users have to do is create a key (on the machine
2007
they want to login from) with the following command:
2008
</p>
2009
2010
<pre caption="Create a DSA keypair">
2011
# <i>/usr/bin/ssh-keygen -t dsa</i>
2012
</pre>
2013
2014
<p>
2015
And type in a pass phrase.
2016
</p>
2017
2018
<pre caption="Output of ssh-keygen">
2019
Generating public/private dsa key pair.
2020
Enter file in which to save the key (/home/kn/.ssh/id_dsa):<i>[Press enter]</i>
2021
Created directory '/home/kn/.ssh'.
2022
Enter passphrase (empty for no passphrase): <i>[Enter passphrase]</i>
2023
Enter same passphrase again: <i>[Enter passphrase again]</i>
2024
Your identification has been saved in /home/kn/.ssh/id_dsa.
2025
Your public key has been saved in /home/kn/.ssh/id_dsa.pub.
2026
The key fingerprint is:
2027
07:24:a9:12:7f:83:7e:af:b8:1f:89:a3:48:29:e2:a4 kn@knielsen
2028
</pre>
2029
2030
<p>
2031
This will add two files in your <path>~/.ssh/</path> directory called 
2032
<path>id_dsa</path> and <path>id_dsa.pub</path>. The file called 
2033
<path>id_dsa</path> is your private key and should be kept from other people
2034
than yourself. The other file <path>id_dsa.pub</path> is to be distributed to
2035
every server that you have access to. Add the key to the users home directory
2036
in <path>~/.ssh/authorized_keys</path> and the user should be able to login.
2037
</p>
2038
2039
<p>
2040
Now your users should guard this private key well. Put it on a media that they
2041
always carry with them or keep it on their workstation (put this in the <uri link="#security_policies">password</uri> policy).
2042
</p>
2043
2044
<p>
2045
For more information go to the <uri link="http://www.openssh.org">OpenSSH</uri> web site.
2046
</p>
2047
2048
</body>
2049
</section>
2050
<section>
2051
<title>Using xinetd</title>
2052
<body>
2053
2054
<p>
2055
xinetd is a replacement for <c>inetd</c> (which Gentoo does not have), 
2056
the Internet services daemon. It supports access control based on the address of
2057
the remote host and the time of access. It also provide extensive logging 
2058
capabilities, including server start time, remote host address, remote user 
2059
name, server run time, and actions requested.
2060
</p>
2061
2062
<p>
2063
As with all other services it is important to have a good default configuration.
2064
But since <c>xinetd</c> is run as root and supports protocols
2065
that you might not know how they work, we recommend not to use it. But if you
2066
want to use it anyway, here is how you can add some security to it:
2067
</p>
2068
2069
<pre caption="Install xinetd">
2070
# <i>emerge xinetd tcp-wrappers</i>
2071
</pre>
2072
2073
<p>
2074
And edit the configuration file:
2075
</p>
2076
2077
<pre caption="/etc/xinetd.conf">
2078
defaults
2079
{
2080
 only_from = localhost
2081
 instances = 10
2082
 log_type = SYSLOG authpriv info
2083
 log_on_success = HOST PID
2084
 log_on_failure = HOST
2085
 cps = 25 30
2086
}
2087
2088
# This will setup pserver (cvs) via xinetd with the following settings:
2089
# max 10 instances (10 connections at a time)
2090
# limit the pserver to tcp only
2091
# use the user cvs to run this service
2092
# bind the interfaces to only 1 ip
2093
# allow access from 10.0.0.*
2094
# limit the time developers can use cvs from 8am to 5pm
2095
# use tpcd wrappers (access control controlled in 
2096
# <i>/etc/hosts.allow</i> and <i>/etc/hosts.deny</i>)
2097
# max_load on the machine set to 1.0
2098
# The disable flag is per default set to no but I like having 
2099
# it in case of it should be disabled
2100
service cvspserver
2101
{
2102
 socket_type = stream
2103
 protocol = tcp
2104
 instances = 10
2105
 protocol = tcp
2106
 wait = no
2107
 user = cvs
2108
 bind = 10.0.0.2
2109
 only_from = 10.0.0.0
2110
 access_times = 8:00-17:00
2111
 server = /usr/sbin/tcpd
2112
 server_args = /usr/bin/cvs --allow-root=/mnt/cvsdisk/cvsroot pserver
2113
 max_load = 1.0
2114
 log_on_failure += RECORD
2115
 disable = no
2116
}
2117
</pre>
2118
2119
<p>
2120
For more information read <c>man 5 xinetd.conf</c>.
2121
</p>
2122
2123
</body>
2124
</section>
2125
2126
<section>
2127
<title>X</title>
2128
<body>
2129
2130
<p>
2131
By default Xorg is configured to act as an Xserver. This can be dangerous since
2132
X uses unencrypted TCP connections and listens for xclients.
2133
</p>
2134
2135
<impo>
2136
If you do not need this service disable it! 
2137
</impo>
2138
2139
<p>
2140
But if you depend on using your workstation as a Xserver use the 
2141
<c>/usr/X11R6/bin/xhost</c> command with caution. This command allows clients 
2142
from other hosts to connect and use your display. This can become handy if you 
2143
need an X application from a different machine and the only way is through the 
2144
network, but it can also be exploited by an attacker. The syntax of this
2145
command is <c>/usr/X11R6/bin/xhost +hostname</c>
2146
</p>
2147
2148
<warn>
2149
Do not ever use the <c>xhost +</c> feature! This will allow any client to 
2150
connect and take control of your X. If an attacker can get access to your X, 
2151
he can log your keystrokes and take control over your desktop. If you have to 
2152
use it always remember to specify a host.
2153
</warn>
2154
2155
<p>
2156
A more secure solution is to disable this feature completely by starting X with 
2157
<c>startx -- -nolisten tcp</c> or disable it permanently in the configuration. 
2158
</p>
2159
2160
<pre caption="/usr/X11R6/bin/startx">
2161
defaultserverargs="-nolisten tcp"
2162
</pre>
2163
2164
<p>
2165
To make sure that <path>startx</path> does not get overwritten when emerging a
2166
new version of Xorg you must protect it. Add the following line to
2167
<path>/etc/make.conf</path>:
2168
</p>
2169
2170
<pre caption="/etc/make.conf">
2171
CONFIG_PROTECT_MASK="/usr/X11R6/bin/startx"
2172
</pre>
2173
2174
<p>
2175
If you use a graphical login manager you need a different approach.
2176
</p>
2177
2178
<p>
2179
For <c>gdm</c> (Gnome Display Manager)
2180
</p>
2181
2182
<pre caption="/etc/X11/gdm/gdm.conf">
2183
[server-Standard]
2184
command=/usr/X11R6/bin/X -nolisten tcp
2185
</pre>
2186
2187
<p>
2188
For <c>xdm</c> (X Display Manager) and <c>kdm</c> (Kde Display Manager)
2189
</p>
2190
2191
<pre caption="/etc/X11/xdm/Xservers">
2192
:0 local /usr/bin/X11/X -nolisten tcp 
2193
</pre>
2194
2195
</body>
2196
</section>
2197
</chapter>
2198
2199
<chapter>
2200
<title>Chrooting and virtual servers</title>
2201
<section>
2202
<title>Chrooting</title>
2203
<body>
2204
2205
<p>
2206
Chrooting a service is a way of limiting a service (or user) environment to
2207
only accessing what it should and not gaining access (or information) that
2208
could lead to root access. By running the service as another user than
2209
<c>root</c> (<c>nobody</c>, <c>apache</c>, <c>named</c>) an attacker can only
2210
access files with the permissions of this user. This means that an attacker
2211
cannot gain <c>root</c> access even if the services has a security flaw.
2212
</p>
2213
2214
<p>
2215
Some services like <c>pure-ftpd</c> and <c>bind</c> have features for
2216
chrooting, and other services do not. If the service supports it, use it,
2217
otherwise you have to figure out how to create your own. Lets see how to create
2218
a chroot, for a basic understanding of how chroots work, we will test it with
2219
<c>bash</c> (easy way of learning).
2220
</p>
2221
2222
<p>
2223
Create the <path>/chroot</path> directory with <c>mkdir chroot</c>. And find what 
2224
dynamic libraries that <c>bash</c> is compiled with (if it is compiled with 
2225
<c>-static</c> this step is not necessary):
2226
</p>
2227
2228
<p>
2229
The following command will create a list of libraries used by <c>bash</c>. 
2230
</p>
2231
2232
<pre caption="Get listing of used libraries">
2233
# <i>ldd /bin/bash</i>
2234
  libncurses.so.5 =&gt; /lib/libncurses.so.5 (0x4001b000)
2235
  libdl.so.2 =&gt; /lib/libdl.so.2 (0x40060000)
2236
  libc.so.6 =&gt; /lib/libc.so.6 (0x40063000)
2237
  /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
2238
</pre>
2239
2240
<p>
2241
Now lets create the environment for <c>bash</c>.
2242
</p>
2243
2244
<pre caption="Create chroot-environment for bash">
2245
# <i>mkdir /chroot/bash</i>
2246
# <i>mkdir /chroot/bash/bin</i>
2247
# <i>mkdir /chroot/bash/lib</i>
2248
</pre>
2249
2250
<p>
2251
Next copy the files used by <c>bash</c> (<path>/lib</path>) to the chrooted
2252
<path>lib</path> and copy the bash command to the chrooted <path>bin</path>
2253
directory. This will create the exact same environment, just with less
2254
functionality. After copying try it out: <c>chroot /chroot/bash /bin/bash</c>. 
2255
If you get an prompt saying <path>/</path> it works! Otherwise it will properly
2256
tell you what a file is missing. Some shared libraries depend on each other.
2257
</p>
2258
2259
<p>
2260
You will notice that inside the chroot nothing works except <c>echo</c>. This 
2261
is because we have no other commands in out chroot environment than bash and 
2262
<c>echo</c> is a build-in functionality.
2263
</p>
2264
2265
<p>
2266
This is basically the same way you would create a chrooted service. The only 
2267
difference is that services sometimes rely on devices and configuration files 
2268
in <path>/etc</path>. Simply copy them (devices can be copied with <c>cp 
2269
-a</c>) to the chrooted environment, edit the init script to use chroot before 
2270
executing. It can be difficult to find what devices and configuration files a 
2271
services need. This is where the <c>strace</c> command becomes handy. Start 
2272
the service with <c>/usr/bin/strace</c> bash and look for open, read, stat and 
2273
maybe connect. This will give you a clue on what files to copy. But in most 
2274
cases just copy the passwd file (edit the copy and remove users that has 
2275
nothing to do with the service), <path>/dev/zero</path>, <path>/dev/log</path> 
2276
and <path>/dev/random</path>.
2277
</p>
2278
2279
</body>
2280
</section>
2281
<section>
2282
<title>User Mode Linux</title>
2283
<body>
2284
2285
<p>
2286
Another way of creating a more secure environment is by running a virtual
2287
machine. A virtual machine, as the name implies, is a process that runs on top
2288
of your real operating system providing a hardware and operating system
2289
environment that appears to be its own unique machine. The security benefit is
2290
that if the server running on the virtual machine is compromised, only the
2291
virtual server is affected and not the parent installation.
2292
</p>
2293
2294
<p>
2295
For more information about how to setup User Mode Linux consult the
2296
<uri link="http://www.gentoo.org/doc/en/uml.xml">User Mode Linux
2297
Guide</uri>.
2298
</p>
2299
2300
</body>
2301
</section>
2302
</chapter>
2303
2304
<chapter>
2305
<title>Firewalls</title>
2306
<section>
2307
<title>A firewall</title>
2308
<body>
2309
2310
<p>
2311
People often think that a firewall provides the ultimate security, but they 
2312
are wrong. In most cases a misconfigured firewall gives less security than 
2313
not having one at all. A firewall is also a piece of software and should be 
2314
treated the same way as any other piece of software, because it is just as likely 
2315
to contain bugs.
2316
</p>
2317
2318
<p>
2319
So think before implementing a firewall! Do you really need one? If you think
2320
you need one write a policy on how it should work, what type of firewall, and
2321
who should operate it. But first read this guide.
2322
</p>
2323
2324
<p>
2325
Firewalls are used for two purposes:
2326
</p>
2327
2328
<ul>
2329
<li>To keep users (worms/attackers) out</li>
2330
<li>To keep users (employees/children) in</li>
2331
</ul>
2332
2333
<p>
2334
Basically there are three types of firewalls:
2335
</p>
2336
2337
<ul>
2338
<li>Packet filtering</li>
2339
<li>Circuit relay</li>
2340
<li>Application gateway</li>
2341
</ul>
2342
2343
<p>
2344
A firewall should be a dedicated machine running no services (or <c>sshd</c> as
2345
the only one) and secured the way this guide recommends it be.
2346
</p>
2347
2348
</body>
2349
</section>
2350
<section>
2351
<title>Packet filtering</title>
2352
<body>
2353
2354
<p>
2355
All network traffic is sent in the form of packets. Large amounts of traffic is
2356
split up into small packets for easy handling and then reassembled when it
2357
arrives at its destination. In the packet header every packet contains
2358
information on how and where it should be delivered. And this information is
2359
exactly what a packing filtering firewall uses. Filtering is based on:
2360
</p>
2361
2362
<ul>
2363
<li>Allow or disallow packets based on source/destination IP address</li>
2364
<li>Allow or disallow packets based on source/destination port</li>
2365
<li>Allow or disallow packets based on protocol</li>
2366
<li>Allow or disallow packets based on flags within a specific protocol</li>
2367
</ul>
2368
2369
<p>
2370
In other words, this filtering is based on all the data within the header of a
2371
packet and not its content.
2372
</p>
2373
2374
<p>
2375
Weaknesses:
2376
</p>
2377
2378
<ul>
2379
<li>
2380
  Address information in a packet can potentially be a bogus IP address (or as we
2381
  say <e>spoofed</e>) by the sender.
2382
</li>
2383
<li>
2384
  Data or requests within the allowed packet may contain unwanted data that the
2385
  attacker can use to exploit known bugs in the services on or behind the firewall
2386
</li>
2387
<li>Usually single point of failure</li>
2388
</ul>
2389
2390
<p>
2391
Advantages:
2392
</p>
2393
2394
<ul>
2395
<li>Simple and easy to implement</li>
2396
<li>
2397
  Can give warnings of a possible attack before it happens (ie. by detecting 
2398
  port scans)
2399
</li>
2400
<li>Good for stopping SYN attacks</li>
2401
</ul>
2402
2403
<p>
2404
Examples of free packet filters on Linux:
2405
</p>
2406
2407
<ul>
2408
<li><uri link="http://www.iptables.org">Iptables</uri></li>
2409
<li>
2410
  <uri link="http://www.linuxdocs.org/HOWTOs/IPCHAINS-HOWTO.html">Ipchains</uri>
2411
</li>
2412
<li><uri link="http://www.smoothwall.org">SmoothWall</uri></li>
2413
</ul>
2414
<!--FIXME: should SmoothWall really be included, since it uses iptables?-->
2415
<note>
2416
It is recommended that you use iptables. Ipchains is obsoleted. 
2417
</note>
2418
2419
</body>
2420
</section>
2421
<section>
2422
<title>Circuit relay</title>
2423
<body>
2424
2425
<p>
2426
A circuit level gateway is a firewall that validates connections before allowing
2427
data to be exchanged. This means that it does not simply allow or deny packets
2428
based on the packet header but determines whether the connection between both
2429
ends is valid according to configurable rules before it opens a session and
2430
allows data to be exchanged. Filtering is based on:
2431
</p>
2432
2433
<ul>
2434
<li>Source/destination IP address</li>
2435
<li>Source/destination port</li>
2436
<li>A period of time</li>
2437
<li>Protocol</li>
2438
<li>User</li>
2439
<li>Password</li>
2440
</ul>
2441
2442
<p>
2443
All traffic is validated and monitored, and unwanted traffic can be dropped.
2444
</p>
2445
2446
<p>
2447
Weakness:
2448
</p>
2449
2450
<ul>
2451
<li>
2452
  Operates at the Transport Layer and may require substantial modification of the
2453
  programs that normally provide transport functions.
2454
</li>
2455
</ul>
2456
2457
</body>
2458
</section>
2459
<section>
2460
<title>Application gateway</title>
2461
<body>
2462
2463
<p>
2464
The application level gateway is a proxy for applications, exchanging data with
2465
remote systems on behalf of the clients. It is kept away from the public safely
2466
behind a DMZ (De-Militarized Zone: the portion of a private network that is
2467
visible through the firewall) or a firewall allowing no connections from the
2468
outside. Filtering is based on:
2469
</p>
2470
2471
<ul>
2472
<li>Allow or disallow based on source/destination IP address</li>
2473
<li>Based on the packet's content</li>
2474
<li>Limiting file access based on file type or extension</li>
2475
</ul>
2476
2477
<p>
2478
Advantages:
2479
</p>
2480
2481
<ul>
2482
<li>Can cache files, increasing network performance</li>
2483
<li>Detailed logging of all connections</li>
2484
<li>Scales well (some proxy servers can "share" the cached data)</li>
2485
<li>No direct access from the outside</li>
2486
<li>Can even alter the packet content on the fly</li>
2487
</ul>
2488
2489
<p>
2490
Weakness:
2491
</p>
2492
2493
<ul>
2494
<li>Configuration is complex</li>
2495
</ul>
2496
2497
<p>
2498
Application gateways are considered to be the most secure solution since they do
2499
not have to run as root and the hosts behind them are not reachable from the
2500
Internet.
2501
</p>
2502
2503
<p>
2504
Example of a free application gateway:
2505
</p>
2506
2507
<ul>
2508
<li><uri link="http://www.squid-cache.org/">Squid</uri></li>
2509
</ul>
2510
2511
</body>
2512
</section>
2513
<section>
2514
<title>Iptables</title>
2515
<body>
2516
2517
<p>
2518
In order to use iptables, it must be enabled in the kernel. I have added
2519
iptables as modules (the <c>iptables</c> command will load them as they are
2520
needed) and recompiled my kernel (but you may want to compile iptables in, if
2521
you intend to disable Loadable Kernel Modules as discussed previously). For more
2522
information on how to configure your kernel for iptables go to the <uri link="http://iptables-tutorial.frozentux.net/chunkyhtml/kernelsetup.html">Iptables
2523
Tutorial Chapter 2: Preparations</uri>. After you have compiled your new kernel 
2524
(or while compiling the kernel), you must add the <c>iptables</c> command.
2525
Just <c>emerge iptables</c> and it should work.
2526
</p>
2527
2528
<p>
2529
Now test that it works by running <c>iptables -L</c>. If this fails something
2530
is wrong and you have to check you configuration once more.
2531
</p>
2532
2533
<p>
2534
Iptables is the new and heavily improved packet filter in the Linux 2.4.x
2535
kernel. It is the successor of the previous ipchains packet filter in the Linux
2536
2.2.x kernel. One of the major improvements is that iptables is able to perform 
2537
stateful packet filtering. With stateful packet filtering it is possible to
2538
keep track of each established TCP connection.
2539
</p>
2540
2541
<p>
2542
A TCP connection consists of a series of packets containing information about
2543
source IP address, destination IP address, source port, destination port, and a
2544
sequence number so the packets can be reassembled without losing data. TCP is a
2545
connection-oriented protocol, in contrast to UDP, which is connectionless.
2546
</p>
2547
2548
<p>
2549
By examining the TCP packet header, a stateful packet filter can determine if a
2550
received TCP packet is part of an already established connection or not and
2551
decide either to accept or drop the packet.
2552
</p>
2553
2554
<p>
2555
With a stateless packet filter it is possible to fool the packet filter into
2556
accepting packets that should be dropped by manipulating the TCP packet headers.
2557
This could be done by manipulating the SYN flag or other flags in the TCP header
2558
to make a malicious packet appear to be a part of an established connection
2559
(since the packet filter itself does not do connection tracking). With stateful
2560
packet filtering it is possible to drop such packets, as they are not part of an
2561
already established connection. This will also stop the possibility of
2562
"stealth scans", a type of port scan in which the scanner sends packets
2563
with flags that are far less likely to be logged by a firewall than ordinary SYN
2564
packets.
2565
</p>
2566
2567
<p>
2568
Iptables provides several other features like NAT (Network Address Translation) 
2569
and rate limiting. Rate limiting is extremely useful when trying to prevent 
2570
certain DoS (Denial of Service) attacks like SYN floods.
2571
</p>
2572
2573
<p>
2574
A TCP connection is established by a so called three-way handshake. When 
2575
establishing a TCP connection the client-side sends a packet to the server 
2576
with the SYN flag set. When the server-side receives the SYN packet it 
2577
responds by sending a SYN+ACK packet back to the client-side. When the SYN+ACK 
2578
is received the client-side responds with a third ACK packet in effect 
2579
acknowledging the connection.
2580
</p>
2581
2582
<p>
2583
A SYN flood attack is performed by sending the SYN packet but failing to 
2584
respond to the SYN+ACK packet. The client-side can forge a packet with a fake 
2585
source IP address because it does not need a reply. The server-side system will
2586
add an entry to a queue of half-open connections when it receives the SYN 
2587
packet and then wait for the final ACK packet before deleting the entry from 
2588
the queue. The queue has a limited number of slots and if all the slots are 
2589
filled it is unable to open any further connections. If the ACK packet is not 
2590
received before a specified timeout period the entry will automatically be 
2591
deleted from the queue. The timeout settings vary but will typically be 30-60 
2592
seconds or even more. The client-side initiates the attack by forging a lot of 
2593
SYN packets with different source IP addresses and sends them to the target IP 
2594
address as fast as possible and thereby filling up the queue of half-open 
2595
connections and thus preventing other clients from establishing a legitimate
2596
connection with the server.
2597
</p>
2598
2599
<p>
2600
This is where the rate limit becomes handy. It is possible to limit the rate 
2601
of accepted SYN packets by using the <c>-m limit --limit 1/s</c>. This will 
2602
limit the number of SYN packets accepted to one per second and therefore 
2603
restricting the SYN flood on our resources.
2604
</p>
2605
2606
<note>
2607
Another option for preventing SYN floods are <uri link="http://cr.yp.to/syncookies.html">SYN cookies</uri>, which allow your computer
2608
to respond to SYN packets without filling space in the connection queue. SYN
2609
cookies can be enabled in the Linux kernel configuration, but they are
2610
considered experimental at this time.
2611
</note>
2612
2613
<p>
2614
Now some practical stuff!
2615
</p>
2616
2617
<p>
2618
When iptables is loaded in the kernel it has 5 hooks where you can place your 
2619
rules. They are called <c>INPUT</c>, <c>OUTPUT</c>, <c>FORWARD</c>, 
2620
<c>PREROUTING</c> and <c>POSTROUTING</c>. Each of these is called a chain and 
2621
consists of a list of rules. Each rule says if the packet header looks like 
2622
this, then here is what to do with the packet. If the rule does not match the 
2623
packet the next rule in the chain is consulted.
2624
</p>
2625
2626
<p>
2627
You can place rules directly in the 5 main chains or create new chains and add 
2628
them to as a rule to an existing chain. Iptables supports the following options.
2629
</p>
2630
2631
<table>
2632
<tr>
2633
  <th>Option:</th>
2634
  <th>Description:</th>
2635
</tr>
2636
<tr>
2637
  <ti>-A</ti>
2638
  <ti>Append</ti>
2639
</tr>
2640
<tr>
2641
  <ti>-D</ti>
2642
  <ti>Delete</ti>
2643
</tr>
2644
<tr>
2645
  <ti>-I</ti>
2646
  <ti>Insert</ti>
2647
</tr>
2648
<tr>
2649
  <ti>-R</ti>
2650
  <ti>Replace</ti>
2651
</tr>
2652
<tr>
2653
  <ti>-L</ti>
2654
  <ti>List</ti>
2655
</tr>
2656
<tr>
2657
  <ti>-F</ti>
2658
  <ti>Delete all rules in chain or all chains</ti>
2659
</tr>
2660
<tr>
2661
  <ti>-Z</ti>
2662
  <ti>Zero counters in chain or all chains</ti>
2663
</tr>
2664
<tr>
2665
  <ti>-C</ti>
2666
  <ti>Test this packet on chain</ti>
2667
</tr>
2668
<tr>
2669
  <ti>-N</ti>
2670
  <ti>Create a new user-defined chain</ti>
2671
</tr>
2672
<tr>
2673
  <ti>-X</ti>
2674
  <ti>Delete a user-defined chain</ti>
2675
</tr>
2676
<tr>
2677
  <ti>-P</ti>
2678
  <ti>Change policy on chain to target</ti>
2679
</tr>
2680
<tr>
2681
  <ti>-E</ti>
2682
  <ti>Change chain name</ti>
2683
</tr>
2684
<tr>
2685
  <ti>-p</ti>
2686
  <ti>Protocol</ti>
2687
</tr>
2688
<tr>
2689
  <ti>-s</ti>
2690
  <ti>Source address/mask</ti>
2691
</tr>
2692
<tr>
2693
  <ti>-d</ti>
2694
  <ti>Destination address/mask</ti>
2695
</tr>
2696
<tr>
2697
  <ti>-i</ti>
2698
  <ti>Input name (Ethernet name)</ti>
2699
</tr>
2700
<tr>
2701
  <ti>-o</ti>
2702
  <ti>Output name (Ethernet name)</ti>
2703
</tr>
2704
<tr>
2705
  <ti>-j</ti>
2706
  <ti>Jump (target for rule)</ti>
2707
</tr>
2708
<tr>
2709
  <ti>-m</ti>
2710
  <ti>Extended match (might use extension)</ti>
2711
</tr>
2712
<tr>
2713
  <ti>-n</ti>
2714
  <ti>Numeric output of addresses and ports</ti>
2715
</tr>
2716
<tr>
2717
  <ti>-t</ti>
2718
  <ti>Table to manipulate</ti>
2719
</tr>
2720
<tr>
2721
  <ti>-v</ti>
2722
  <ti>Verbose mode</ti>
2723
</tr>
2724
<tr>
2725
  <ti>-x</ti>
2726
  <ti>Expand numbers (display exact values)</ti>
2727
</tr>
2728
<tr>
2729
  <ti>-f</ti>
2730
  <ti>Match second or further fragments only</ti>
2731
</tr>
2732
<tr>
2733
  <ti>-V</ti>
2734
  <ti>Packet version</ti>
2735
</tr>
2736
<tr>
2737
  <ti>--line-numbers</ti>
2738
  <ti>Print line numbers when listing</ti>
2739
</tr>
2740
</table>
2741
2742
<p>
2743
First we will try to block all ICMP packets to our machine, just to get familiar
2744
with iptables.
2745
</p>
2746
2747
<pre caption="Block all ICMP packets">
2748
# <i>iptables -A INPUT -p icmp -j DROP</i>
2749
</pre>
2750
2751
<p>
2752
First we specify the chain our rule should be appended to, then the protocol of
2753
the packets to match, and finally the target. The target can be the name of a
2754
user specified chain or one of the special targets <c>ACCEPT</c>, <c>DROP</c>,
2755
 <c>REJECT</c>, <c>LOG</c>, <c>QUEUE</c>, or <c>MASQUERADE</c>. In this case we
2756
 use <c>DROP</c>, which will drop the packet without responding to the client.
2757
</p>
2758
2759
<note>
2760
The <c>LOG</c> target is what's known as "non-terminating". If a packet matches
2761
a rule with the <c>LOG</c> target, rather than halting evaluation, the packet
2762
will continue to be matched to further rules. This allows you to log packets
2763
while still processing them normally.
2764
</note>
2765
2766
<p>
2767
Now try <c>ping localhost</c>. You will not get any response, since iptables
2768
will drop all incoming ICMP messages. You will also not be able to ping other
2769
machines, since the ICMP reply packet will be dropped as well. Now flush the
2770
chain to get ICMP flowing again.
2771
</p>
2772
2773
<pre caption="Flush all rules">
2774
# <i>iptables -F</i>
2775
</pre>
2776
2777
<p>
2778
Now lets look at the stateful packet filtering in iptables. If we wanted to
2779
enable stateful inspection of packets incoming on eth0 we would issue the
2780
command:
2781
</p>
2782
2783
<pre caption="Accept packets that originate from an already established connection">
2784
# <i>iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT</i>
2785
</pre>
2786
2787
<p>
2788
This will accept any packet from an already established connection or related in
2789
the INPUT chain. And you could drop any packet that is not in the state table by
2790
issuing <c>iptables -A INPUT -i eth0 -m state --state INVALID -j DROP</c> just
2791
before the previous command. This enables the stateful packet filtering in
2792
iptables by loading the extension "state". If you wanted to allow others to
2793
connect to your machine, you could use the flag <c>--state NEW</c>. Iptables
2794
contains some modules for different purposes. Some of them are:
2795
</p>
2796
2797
<table>
2798
<tr>
2799
  <th>Module/Match</th>
2800
  <th>Description</th>
2801
  <th>Extended options</th>
2802
</tr>
2803
<tr>
2804
  <ti>mac</ti>
2805
  <ti>Matching extension for incoming packets mac address.</ti>
2806
  <ti>--mac-source</ti>
2807
</tr>
2808
<tr>
2809
  <ti>state</ti>
2810
  <ti>Enables stateful inspection</ti>
2811
  <ti>--state (states are ESTABLISHED,RELATED, INVALID, NEW)</ti>
2812
</tr>
2813
<tr>
2814
  <ti>limit</ti>
2815
  <ti>Rate matching limiting</ti>
2816
  <ti>--limit, --limit-burst</ti>
2817
</tr>
2818
<tr>
2819
  <ti>owner</ti>
2820
  <ti>Attempt to match various characteristics of the packet creator</ti>
2821
  <ti>
2822
    --uid-owner userid --gid-owner groupid --pid-owner processid --sid-owner 
2823
    sessionid
2824
  </ti>
2825
</tr>
2826
<tr>
2827
  <ti>unclean</ti>
2828
  <ti>Various random sanity checks on packets</ti><ti/>
2829
</tr>
2830
</table>
2831
2832
<p>
2833
Lets try to create a user-defined chain and apply it to one of the existing 
2834
chains:
2835
</p>
2836
2837
<pre caption="Creating a user defined chain">
2838
<comment>(Create a new chain with one rule)</comment>
2839
# <i>iptables -X mychain</i>
2840
# <i>iptables -N mychain</i>
2841
# <i>iptables -A mychain -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT</i>
2842
<comment>(The default policy is all outgoing traffic is allowed. Incoming is dropped.)</comment>
2843
# <i>iptables -P OUTPUT ACCEPT</i>
2844
# <i>iptables -P INPUT DROP</i>
2845
<comment>(And add it to the INPUT chain)</comment>
2846
# <i>iptables -A INPUT -j mychain</i>
2847
</pre>
2848
2849
<p>
2850
By applying the rule to the input chain we get the policy: All outgoing packets 
2851
are allowed and all incoming packets are dropped.
2852
</p>
2853
2854
<p>
2855
One can find documentation at <uri link="http://www.iptables.org/documentation/index.html#HOWTO">Netfilter/iptables
2856
documentation</uri>.
2857
</p>
2858
2859
<p>
2860
Lets see a full blown example. In this case my firewall/gateway policy states:
2861
</p>
2862
2863
<ul>
2864
<li>Connections to the firewall are only allowed through SSH (port 22)</li>
2865
<li>
2866
  The local network should have access to HTTP, HTTPS and SSH (DNS should also 
2867
  be allowed)
2868
</li>
2869
<li>
2870
  ICMP traffic can contain payload and should not be allowed. Of course we have 
2871
  to allow some ICMP traffic.
2872
</li>
2873
<li>Port scans should be detected and logged</li>
2874
<li>SYN attacks should be avoided</li>
2875
<li>All other traffic should be dropped and logged</li>
2876
</ul>
2877
2878
<pre caption="/etc/init.d/firewall">
2879
#!/sbin/runscript
2880
IPTABLES=/sbin/iptables
2881
IPTABLESSAVE=/sbin/iptables-save
2882
IPTABLESRESTORE=/sbin/iptables-restore
2883
FIREWALL=/etc/firewall.rules
2884
DNS1=212.242.40.3
2885
DNS2=212.242.40.51
2886
#inside
2887
IIP=10.0.0.2
2888
IINTERFACE=eth0
2889
LOCAL_NETWORK=10.0.0.0/24
2890
#outside
2891
OIP=217.157.156.144
2892
OINTERFACE=eth1
2893
2894
opts="${opts} showstatus panic save restore showoptions rules"
2895
2896
depend() {
2897
  need net
2898
}
2899
2900
rules() {
2901
  stop
2902
  ebegin "Setting internal rules"
2903
2904
  einfo "Setting default rule to drop"
2905
  $IPTABLES -P FORWARD DROP
2906
  $IPTABLES -P INPUT   DROP
2907
  $IPTABLES -P OUTPUT  DROP
2908
2909
  #default rule
2910
  einfo "Creating states chain"
2911
  $IPTABLES -N allowed-connection
2912
  $IPTABLES -F allowed-connection
2913
  $IPTABLES -A allowed-connection -m state --state ESTABLISHED,RELATED -j ACCEPT
2914
  $IPTABLES -A allowed-connection -i $IINTERFACE -m limit -j LOG --log-prefix \ 
2915
      "Bad packet from ${IINTERFACE}:"
2916
  $IPTABLES -A allowed-connection -j DROP
2917
2918
  #ICMP traffic
2919
  einfo "Creating icmp chain"
2920
  $IPTABLES -N icmp_allowed
2921
  $IPTABLES -F icmp_allowed
2922
  $IPTABLES -A icmp_allowed -m state --state NEW -p icmp --icmp-type \ 
2923
      time-exceeded -j ACCEPT
2924
  $IPTABLES -A icmp_allowed -m state --state NEW -p icmp --icmp-type \ 
2925
      destination-unreachable -j ACCEPT
2926
  $IPTABLES -A icmp_allowed -p icmp -j LOG --log-prefix "Bad ICMP traffic:"
2927
  $IPTABLES -A icmp_allowed -p icmp -j DROP
2928
2929
  #Incoming traffic
2930
  einfo "Creating incoming ssh traffic chain"
2931
  $IPTABLES -N allow-ssh-traffic-in
2932
  $IPTABLES -F allow-ssh-traffic-in
2933
  #Flood protection
2934
  $IPTABLES -A allow-ssh-traffic-in -m limit --limit 1/second -p tcp --tcp-flags \ 
2935
      ALL RST --dport ssh -j ACCEPT
2936
  $IPTABLES -A allow-ssh-traffic-in -m limit --limit 1/second -p tcp --tcp-flags \ 
2937
      ALL FIN --dport ssh -j ACCEPT
2938
  $IPTABLES -A allow-ssh-traffic-in -m limit --limit 1/second -p tcp --tcp-flags \ 
2939
      ALL SYN --dport ssh -j ACCEPT
2940
  $IPTABLES -A allow-ssh-traffic-in -m state --state RELATED,ESTABLISHED -p tcp --dport ssh -j ACCEPT
2941
2942
  #outgoing traffic
2943
  einfo "Creating outgoing ssh traffic chain"
2944
  $IPTABLES -N allow-ssh-traffic-out
2945
  $IPTABLES -F allow-ssh-traffic-out
2946
  $IPTABLES -A allow-ssh-traffic-out -p tcp --dport ssh -j ACCEPT
2947
2948
  einfo "Creating outgoing dns traffic chain"
2949
  $IPTABLES -N allow-dns-traffic-out
2950
  $IPTABLES -F allow-dns-traffic-out
2951
  $IPTABLES -A allow-dns-traffic-out -p udp -d $DNS1 --dport domain \ 
2952
      -j ACCEPT
2953
  $IPTABLES -A allow-dns-traffic-out -p udp -d $DNS2 --dport domain \ 
2954
     -j ACCEPT
2955
2956
  einfo "Creating outgoing http/https traffic chain"
2957
  $IPTABLES -N allow-www-traffic-out
2958
  $IPTABLES -F allow-www-traffic-out
2959
  $IPTABLES -A allow-www-traffic-out -p tcp --dport www -j ACCEPT
2960
  $IPTABLES -A allow-www-traffic-out -p tcp --dport https -j ACCEPT
2961
2962
  #Catch portscanners
2963
  einfo "Creating portscan detection chain"
2964
  $IPTABLES -N check-flags
2965
  $IPTABLES -F check-flags
2966
  $IPTABLES -A check-flags -p tcp --tcp-flags ALL FIN,URG,PSH -m limit \ 
2967
      --limit 5/minute -j LOG --log-level alert --log-prefix "NMAP-XMAS:" 
2968
  $IPTABLES -A check-flags -p tcp --tcp-flags ALL FIN,URG,PSH -j DROP
2969
  $IPTABLES -A check-flags -p tcp --tcp-flags ALL ALL -m limit --limit \ 
2970
      5/minute -j LOG --log-level 1 --log-prefix "XMAS:"
2971
  $IPTABLES -A check-flags -p tcp --tcp-flags ALL ALL -j DROP
2972
  $IPTABLES -A check-flags -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG \ 
2973
      -m limit --limit 5/minute -j LOG --log-level 1 --log-prefix "XMAS-PSH:"
2974
  $IPTABLES -A check-flags -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP
2975
  $IPTABLES -A check-flags -p tcp --tcp-flags ALL NONE -m limit \ 
2976
      --limit 5/minute -j LOG --log-level 1 --log-prefix "NULL_SCAN:"
2977
  $IPTABLES -A check-flags -p tcp --tcp-flags ALL NONE -j DROP
2978
  $IPTABLES -A check-flags -p tcp --tcp-flags SYN,RST SYN,RST -m limit \ 
2979
      --limit 5/minute -j LOG --log-level 5 --log-prefix "SYN/RST:"
2980
  $IPTABLES -A check-flags -p tcp --tcp-flags SYN,RST SYN,RST -j DROP
2981
  $IPTABLES -A check-flags -p tcp --tcp-flags SYN,FIN SYN,FIN -m limit \ 
2982
      --limit 5/minute -j LOG --log-level 5 --log-prefix "SYN/FIN:"
2983
  $IPTABLES -A check-flags -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP
2984
2985
  # Apply and add invalid states to the chains
2986
  einfo "Applying chains to INPUT"
2987
  $IPTABLES -A INPUT -m state --state INVALID -j DROP
2988
  $IPTABLES -A INPUT -j icmp_allowed 
2989
  $IPTABLES -A INPUT -j check-flags
2990
  $IPTABLES -A INPUT -i lo -j ACCEPT
2991
  $IPTABLES -A INPUT -j allow-ssh-traffic-in
2992
  $IPTABLES -A INPUT -j allowed-connection
2993
2994
  einfo "Applying chains to FORWARD"
2995
  $IPTABLES -A FORWARD -m state --state INVALID -j DROP
2996
  $IPTABLES -A FORWARD -j icmp_allowed 
2997
  $IPTABLES -A FORWARD -j check-flags
2998
  $IPTABLES -A FORWARD -o lo -j ACCEPT
2999
  $IPTABLES -A FORWARD -j allow-ssh-traffic-in
3000
  $IPTABLES -A FORWARD -j allow-www-traffic-out
3001
  $IPTABLES -A FORWARD -j allowed-connection
3002
3003
  einfo "Applying chains to OUTPUT"
3004
  $IPTABLES -A OUTPUT -m state --state INVALID -j DROP
3005
  $IPTABLES -A OUTPUT -j icmp_allowed
3006
  $IPTABLES -A OUTPUT -j check-flags
3007
  $IPTABLES -A OUTPUT -o lo -j ACCEPT
3008
  $IPTABLES -A OUTPUT -j allow-ssh-traffic-out
3009
  $IPTABLES -A OUTPUT -j allow-dns-traffic-out
3010
  $IPTABLES -A OUTPUT -j allow-www-traffic-out
3011
  $IPTABLES -A OUTPUT -j allowed-connection
3012
3013
  #Allow client to route through via NAT (Network Address Translation)
3014
  $IPTABLES -t nat -A POSTROUTING -o $IINTERFACE -j MASQUERADE 
3015
  eend $?
3016
}
3017
3018
start() {
3019
  ebegin "Starting firewall"
3020
  if [ -e "${FIREWALL}" ]; then
3021
    restore
3022
  else
3023
    einfo "${FIREWALL} does not exists. Using default rules."
3024
    rules
3025
  fi
3026
  eend $?
3027
}
3028
3029
stop() {
3030
  ebegin "Stopping firewall"
3031
  $IPTABLES -F
3032
  $IPTABLES -t nat -F
3033
  $IPTABLES -X
3034
  $IPTABLES -P FORWARD ACCEPT
3035
  $IPTABLES -P INPUT   ACCEPT
3036
  $IPTABLES -P OUTPUT  ACCEPT
3037
  eend $?
3038
}
3039
3040
showstatus() {
3041
  ebegin "Status"
3042
  $IPTABLES -L -n -v --line-numbers
3043
  einfo "NAT status"
3044
  $IPTABLES -L -n -v --line-numbers -t nat
3045
  eend $?
3046
}
3047
3048
panic() {
3049
  ebegin "Setting panic rules"
3050
  $IPTABLES -F
3051
  $IPTABLES -X
3052
  $IPTABLES -t nat -F
3053
  $IPTABLES -P FORWARD DROP
3054
  $IPTABLES -P INPUT   DROP
3055
  $IPTABLES -P OUTPUT  DROP
3056
  $IPTABLES -A INPUT -i lo -j ACCEPT
3057
  $IPTABLES -A OUTPUT -o lo -j ACCEPT
3058
  eend $?
3059
}
3060
3061
save() {
3062
  ebegin "Saving Firewall rules"
3063
  $IPTABLESSAVE &gt; $FIREWALL
3064
  eend $?
3065
}
3066
3067
restore() {
3068
  ebegin "Restoring Firewall rules"
3069
  $IPTABLESRESTORE &lt; $FIREWALL
3070
  eend $?
3071
}
3072
3073
restart() {
3074
  svc_stop; svc_start
3075
}
3076
3077
showoptions() {
3078
  echo "Usage: $0 {start|save|restore|panic|stop|restart|showstatus}"
3079
  echo "start)      will restore setting if exists else force rules"
3080
  echo "stop)       delete all rules and set all to accept"
3081
  echo "rules)      force settings of new rules"
3082
  echo "save)       will store settings in ${FIREWALL}"
3083
  echo "restore)    will restore settings from ${FIREWALL}"
3084
  echo "showstatus) Shows the status" 
3085
}
3086
</pre>
3087
3088
<p>
3089
Some advice when creating a firewall:
3090
</p>
3091
3092
<ol>
3093
<li>Create your firewall policy before implementing it</li>
3094
<li>Keep it simple</li>
3095
<li>
3096
Know how each protocol works (read the relevant <uri link="http://www.ietf.org/">RFC</uri>(Request For Comments))
3097
</li>
3098
<li>
3099
Keep in mind that a firewall is just another piece of software running as root.
3100
</li>
3101
<li>Test your firewall</li>
3102
</ol>
3103
3104
<p>
3105
If you think that iptables is hard to understand or takes to long to setup a
3106
decent firewall you could use <uri link="http://www.shorewall.net">Shorewall</uri>. It basically uses iptables to
3107
generate firewall rules, but concentrates on rules and not specific protocols.
3108
</p>
3109
3110
</body>
3111
</section>
3112
<section>
3113
<title>Squid</title>
3114
<body>
3115
3116
<p>
3117
Squid is a very powerful proxy server. It can filter traffic based on time,
3118
regular expressions on path/URI, source and destination IP addresses, domain,
3119
browser, authenticated user name, MIME type, and port number (protocol). I
3120
probably forgot some features, but it can be hard to cover the entire list right
3121
here.
3122
</p> 
3123
3124
<p>
3125
In the following example I have added a banner filter instead of a filter based
3126
on porn sites. The reason for this is that Gentoo.org should <e>not</e> be
3127
listed as some porn site. And I do not want to waste my time trying to find some
3128
good sites for you.
3129
</p>
3130
3131
<p>
3132
In this case, my policy states:
3133
</p>
3134
3135
<ul>
3136
<li>
3137
Surfing (HTTP/HTTPS) is allowed during work hours (mon-fri 8-17 and sat 8-13),
3138
but if employees are here late they should work, not surf
3139
</li>
3140
<li>
3141
Downloading files is not allowed (.exe, .com, .arj, .zip, .asf, .avi, .mpg,
3142
.mpeg, etc)
3143
</li>
3144
<li>
3145
We do not like banners, so they are filtered and replaced with a transparent gif
3146
(this is where you get creative!).
3147
</li>
3148
<li>
3149
All other connections to and from the Internet are denied.
3150
</li>
3151
</ul>
3152
3153
<p>
3154
This is implemented in 4 <e>easy</e> steps.
3155
</p>
3156
3157
<pre caption="/etc/squid/squid.conf">
3158
# Bind to a ip and port
3159
http_port 10.0.2.1:3128
3160
3161
# Standard configuration
3162
hierarchy_stoplist cgi-bin ?
3163
acl QUERY urlpath_regex cgi-bin \?
3164
no_cache deny QUERY
3165
3166
# Add basic access control lists
3167
acl all src 0.0.0.0/0.0.0.0
3168
acl manager proto cache_object
3169
acl localhost src 127.0.0.1/255.255.255.255
3170
3171
# Add who can access this proxy server
3172
acl localnet src 10.0.0.0/255.255.0.0
3173
3174
# And ports
3175
acl SSL_ports port 443
3176
acl Safe_ports port 80
3177
acl Safe_ports port 443
3178
acl purge method PURGE
3179
3180
# Add access control list based on regular
3181
# expressions within urls
3182
acl archives urlpath_regex "/etc/squid/files.acl"
3183
acl url_ads url_regex "/etc/squid/banner-ads.acl"
3184
3185
# Add access control list based on time and day
3186
acl restricted_weekdays time MTWHF 8:00-17:00
3187
acl restricted_weekends time A 8:00-13:00
3188
3189
acl CONNECT method CONNECT
3190
3191
#allow manager access from localhost
3192
http_access allow manager localhost
3193
http_access deny manager
3194
3195
# Only allow purge requests from localhost
3196
http_access allow purge localhost
3197
http_access deny purge
3198
3199
# Deny requests to unknown ports
3200
http_access deny !Safe_ports
3201
3202
# Deny CONNECT to other than SSL ports
3203
http_access deny CONNECT !SSL_ports
3204
3205
# My own rules
3206
3207
# Add a page do be displayed when
3208
# a banner is removed
3209
deny_info NOTE_ADS_FILTERED url_ads
3210
3211
# Then deny them
3212
http_access deny url_ads
3213
3214
# Deny all archives
3215
http_access deny archives
3216
3217
# Restrict access to work hours
3218
http_access allow localnet restricted_weekdays
3219
http_access allow localnet restricted_weekends
3220
3221
# Deny the rest
3222
http_access deny all
3223
</pre>
3224
3225
<p>
3226
Next fill in the files you do not want your users to download files. I have
3227
added zip, viv, exe, mp3, rar, ace, avi, mov, mpg, mpeg, au, ra, arj, tar, gz
3228
and z files.
3229
</p>
3230
3231
<pre caption="/etc/squid/files.acl">
3232
\.[Zz][Ii][pP]$
3233
\.[Vv][Ii][Vv].*
3234
\.[Ee][Xx][Ee]$
3235
\.[Mm][Pp]3$
3236
\.[Rr][Aa][Rr]$
3237
\.[Aa][Cc][Ee]$
3238
\.[Aa][Ss][Ff]$
3239
\.[Aa][Vv][Ii]$
3240
\.[Mm][Oo][Vv]$
3241
\.[Mm][Pp][Gg]$
3242
\.[Mm][Pp][Ee][Gg]$
3243
\.[Aa][Uu]$
3244
\.[Rr][Aa]$
3245
\.[Aa][Rr][Jj]$
3246
\.[Tt][Aa][Rr]$
3247
\.[Gg][Zz]$
3248
\.[Zz]$
3249
</pre>
3250
3251
<note>
3252
Please note the [] with upper and lowercase of every character. This is done so
3253
no one can fool our filter by accessing a file called AvI instead of avi
3254
</note>
3255
3256
<p>
3257
Next we add the regular expressions for identifying banners. You will probably
3258
be a lot more creative than I:
3259
</p>
3260
3261
<pre caption="/etc/squid/banner-ads.acl">
3262
/adv/.*\.gif$
3263
/[Aa]ds/.*\.gif$
3264
/[Aa]d[Pp]ix/
3265
/[Aa]d[Ss]erver
3266
/[Aa][Dd]/.*\.[GgJj][IiPp][FfGg]$
3267
/[Bb]annerads/
3268
/adbanner.*\.[GgJj][IiPp][FfGg]$
3269
/images/ad/
3270
/reklame/
3271
/RealMedia/ads/.*
3272
^http://www\.submit-it.*
3273
^http://www\.eads.*
3274
^http://ads\.
3275
^http://ad\.
3276
^http://ads02\.
3277
^http://adaver.*\.
3278
^http://adforce\.
3279
adbot\.com
3280
/ads/.*\.gif.*
3281
_ad\..*cgi
3282
/Banners/
3283
/SmartBanner/
3284
/Ads/Media/Images/
3285
^http://static\.wired\.com/advertising/
3286
^http://*\.dejanews\.com/ads/
3287
^http://adfu\.blockstackers\.com/
3288
^http://ads2\.zdnet\.com/adverts
3289
^http://www2\.burstnet\.com/gifs/
3290
^http://www.\.valueclick\.com/cgi-bin/cycle
3291
^http://www\.altavista\.com/av/gifs/ie_horiz\.gif
3292
</pre>
3293
3294
<p>
3295
And as the last part we want this file to be displayed when a banner is removed.
3296
It is basically a half html file with a 4x4 transparent gif image.
3297
</p>
3298
3299
<pre caption="/etc/squid/errors/NOTE_ADS_FILTERED">
3300
&lt;HTML&gt;
3301
&lt;HEAD&gt;
3302
&lt;META HTTP-EQUIV="REFRESH" CONTENT="0; URL=http://localhost/images/4x4.gif"&gt;
3303
&lt;TITLE&gt;ERROR: The requested URL could not be retrieved&lt;/TITLE&gt;
3304
&lt;/HEAD&gt;
3305
&lt;BODY&gt;
3306
&lt;H1&gt;Add filtered!&lt;/H1&gt;
3307
</pre>
3308
3309
<note>
3310
Do not close the &lt;HTML&gt; &lt;BODY&gt; tags. This will be done by squid.
3311
</note>
3312
3313
<p>
3314
As you can see, Squid has a lot of possibilities and it is very effective at
3315
both filtering and proxying. It can even use alternative Squid proxies to scale
3316
on very large networks. The configuration I have listed here is mostly suited
3317
for a small network with 1-20 users.
3318
</p>
3319
3320
<p>
3321
But combining the packet filter (iptables) and the application gateway (Squid)
3322
is probably the best solution, even if Squid is located somewhere safe and
3323
nobody can access it from the outside. We still need to be concerned about
3324
attacks from the inside.
3325
</p>
3326
3327
<p>
3328
Now you have to configure your clients browsers to use the proxy server. The
3329
gateway will prevent the users from having any contact with the outside unless
3330
they use the proxy.
3331
</p>
3332
3333
<note>
3334
In Mozilla this is done in Edit-&gt;Preferences-&gt;Advanced-&gt;Proxies.
3335
</note>
3336
3337
<p>
3338
It can also be done transparently by using iptables to forward all outbound
3339
traffic to a Squid proxy. This can be done by adding a forwarding/prerouting
3340
rule on the gateway:
3341
</p>
3342
3343
<pre caption="Enable portforwarding to our proxyserver">
3344
# <i>iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to proxyhost:3128</i>
3345
# <i>iptables -t nat -A PREROUTING -p tcp --dport 443 -j DNAT --to proxyhost:3128</i>
3346
</pre>
3347
3348
<note>
3349
If the proxy is running on the packet filtering host--though this is not
3350
recommended, it may be necessary if you do not have enough spare machines--use
3351
a <c>REDIRECT</c> target instead of <c>DNAT</c> (<c>REDIRECT</c> directs packets
3352
to the localhost).
3353
</note>
3354
3355
</body>
3356
</section>
3357
<section>
3358
<title>Lessons learned</title>
3359
<body>
3360
3361
<p>
3362
We have learned that:
3363
</p>
3364
3365
<ol>
3366
<li>
3367
A firewall can be a risk in itself. A badly configured firewall is worse than
3368
not having one at all.
3369
</li>
3370
<li>How to setup a basic gateway and a transparent proxy.</li>
3371
<li>The key to a good firewall is to know the protocols you want do allow.</li>
3372
<li>
3373
That IP traffic does not always contain legitimate data, e.g. ICMP packets,
3374
which can contain a malicious payload.
3375
</li>
3376
<li>How to prevent SYN attack.</li>
3377
<li>Filtering HTTP traffic by removing offensive pictures and downloads of viruses.</li>
3378
<li>
3379
Combining packet filters and application gateways provides better control.
3380
</li>
3381
</ol>
3382
3383
<p>
3384
Now, if you <e>really</e> need to, go create a firewall that matches
3385
your needs.
3386
</p>
3387
3388
</body>
3389
</section>
3390
</chapter>
3391
3392
<chapter>
3393
<title>Intrusion detection</title>
3394
<section>
3395
<title>AIDE (Advanced Intrusion Detection Environment)</title>
3396
<body>
3397
3398
<p>
3399
AIDE is a Host-Based Intrusion Detection System (HIDS), a free alternative to
3400
Tripwire (if you already know Tripwire you should have no difficulties learning
3401
the configuration file for AIDE). HIDS are used to detect changes to important
3402
system configuration files and binaries, generally by making a unique
3403
cryptographic hash for the files to be checked and storing it in a secure
3404
place. On a regular basis (such as once a day), the stored "known-good" hash is
3405
compared to the one generated from the current copy of each file, to determine
3406
if that file has changed. HIDS are a great way to detect disallowed changes to
3407
your system, but they take a little work to implement properly and make good use
3408
of.
3409
</p>
3410
3411
<p>
3412
The configuration file is based on regular expressions, macros and rules for
3413
files and directories. We have the following macros:
3414
</p>
3415
3416
<table>
3417
<tr>
3418
  <th>Macro</th>
3419
  <th>Description</th>
3420
  <th>Syntax</th>
3421
</tr>
3422
<tr>
3423
  <ti>ifdef</ti>
3424
  <ti>If definded</ti>
3425
  <ti>@@ifdef "name"</ti>
3426
</tr>
3427
<tr>
3428
  <ti>ifndef</ti>
3429
  <ti>If not defined</ti>
3430
  <ti>@@ifndef "name"</ti>
3431
</tr>
3432
<tr>
3433
  <ti>define</ti>
3434
  <ti>Define a variable </ti>
3435
  <ti>@@define "name" "value"</ti>
3436
</tr>
3437
<tr>
3438
  <ti>undef</ti>
3439
  <ti>Undefine a variable</ti>
3440
  <ti>@@undef "name"</ti>
3441
</tr>
3442
<tr>
3443
  <ti>ifhost</ti>
3444
  <ti>if "hostname"</ti>
3445
  <ti>@@ifhost "hostname"</ti>
3446
</tr>
3447
<tr>
3448
  <ti>ifnhost</ti>
3449
  <ti>if not "hostname"</ti>
3450
  <ti>@@ifnhost "hostname"</ti>
3451
</tr>
3452
<tr>
3453
  <ti>endif</ti>
3454
<ti>
3455
Endif must be used after any of the above macros except define and undef
3456
</ti>
3457
<ti>@@endif</ti>
3458
</tr>
3459
</table>
3460
3461
<p>
3462
These macros become very handy if you have more than one Gentoo box and want to
3463
use AIDE on all of them. But not all machines run the same services or even have
3464
the same users.
3465
</p>
3466
3467
<p>
3468
Next we have sets of flags to check for on files and directories. These are a
3469
combination of permissions, file properties and cryptographic hashes
3470
(i.e. checksums).
3471
</p>
3472
3473
<table>
3474
<tr>
3475
  <th>Flag</th>
3476
  <th>Description</th>
3477
</tr>
3478
<tr>
3479
  <ti>p</ti>
3480
  <ti>permissions</ti>
3481
</tr>
3482
<tr>
3483
  <ti>i</ti>
3484
  <ti>inode</ti>
3485
</tr>
3486
<tr>
3487
  <ti>n</ti>
3488
  <ti>number of links</ti>
3489
</tr>
3490
<tr>
3491
  <ti>u</ti>
3492
  <ti>user</ti>
3493
</tr>
3494
<tr>
3495
  <ti>g</ti>
3496
  <ti>group</ti>
3497
</tr>
3498
<tr>
3499
  <ti>s</ti>
3500
  <ti>size</ti>
3501
</tr>
3502
<tr>
3503
  <ti>b</ti>
3504
  <ti>block count</ti>
3505
</tr>
3506
<tr>
3507
  <ti>m</ti>
3508
  <ti>mtime</ti>
3509
</tr>
3510
<tr>
3511
  <ti>a</ti>
3512
  <ti>atime</ti>
3513
</tr>
3514
<tr>
3515
  <ti>c</ti>
3516
  <ti>ctime</ti>
3517
</tr>
3518
<tr>
3519
  <ti>S</ti>
3520
  <ti>check for growing size</ti>
3521
</tr>
3522
<tr>
3523
  <ti>md5</ti>
3524
  <ti>md5 checksum</ti>
3525
</tr>
3526
<tr>
3527
  <ti>sha1</ti>
3528
  <ti>sha1 checksum</ti>
3529
</tr>
3530
<tr>
3531
  <ti>rmd160</ti>
3532
  <ti>rmd160 checksum</ti>
3533
</tr>
3534
<tr>
3535
  <ti>tiger</ti>
3536
  <ti>tiger checksum</ti>
3537
</tr>
3538
<tr>
3539
  <ti>R</ti>
3540
  <ti>p+i+n+u+g+s+m+c+md5</ti>
3541
</tr>
3542
<tr>
3543
  <ti>L</ti>
3544
  <ti>p+i+n+u+g</ti>
3545
</tr>
3546
<tr>
3547
  <ti>E</ti>
3548
  <ti>Empty group</ti>
3549
</tr>
3550
<tr>
3551
  <ti>&gt;</ti>
3552
  <ti>Growing logfile p+u+g+i+n+S</ti>
3553
</tr>
3554
</table>
3555
3556
<p>
3557
And if AIDE is compiled with mhash support it supports a few other features:
3558
</p>
3559
3560
<table>
3561
<tr>
3562
<th>Flag</th>
3563
<th>Description</th>
3564
</tr>
3565
<tr>
3566
<ti>haval</ti>
3567
<ti>haval checksum</ti>
3568
</tr>
3569
<tr>
3570
<ti>gost</ti>
3571
<ti>gost checksum</ti>
3572
</tr>
3573
<tr>
3574
<ti>crc32</ti>
3575
<ti>crc32 checksum</ti>
3576
</tr>
3577
</table>
3578
3579
<p>
3580
Now you can create you own rules based on the above flags by combining them 
3581
like this:
3582
</p>
3583
3584
<pre caption="Create a ruleset for AIDE">
3585
All=R+a+sha1+rmd160
3586
Norm=s+n+b+md5+sha1+rmd160
3587
</pre>
3588
3589
<p>
3590
The last thing we need to create our own configuration file is to see how to add
3591
a rule to a file or directory. To enter a rule, combine the file or directory
3592
name and the rule. AIDE will add all files recursively unless you specify an
3593
alternate rule.
3594
</p>
3595
3596
<table>
3597
<tr>
3598
<th>Flag</th>
3599
<th>Description</th>
3600
</tr>
3601
<tr>
3602
<ti>!</ti>
3603
<ti>Don't add this file or directory.</ti>
3604
</tr>
3605
<tr>
3606
<ti>=</ti>
3607
<ti>Add this directory, but not recursively.</ti>
3608
</tr>
3609
</table>
3610
3611
<p>
3612
So lets watch a full blown example:
3613
</p>
3614
3615
<pre caption="/etc/aide/aide.conf">
3616
@@ifndef TOPDIR 
3617
@@define TOPDIR /
3618
@@endif
3619
3620
@@ifndef AIDEDIR 
3621
@@define AIDEDIR /etc/aide
3622
@@endif
3623
3624
@@ifhost smbserv
3625
@@define smbactive
3626
@@endif
3627
3628
# The location of the database to be read.
3629
database=file:@@{AIDEDIR}/aide.db
3630
3631
# The location of the database to be written.
3632
database_out=file:aide.db.new
3633
3634
verbose=20
3635
report_url=stdout
3636
3637
# Rule definition
3638
All=R+a+sha1+rmd160
3639
Norm=s+n+b+md5+sha1+rmd160
3640
3641
@@{TOPDIR} Norm
3642
!@@{TOPDIR}etc/aide
3643
!@@{TOPDIR}dev
3644
!@@{TOPDIR}proc
3645
!@@{TOPDIR}root
3646
!@@{TOPDIR}tmp
3647
!@@{TOPDIR}var/log
3648
!@@{TOPDIR}var/run
3649
!@@{TOPDIR}usr/portage
3650
@@ifdef smbactive
3651
!@@{TOPDIR}etc/smb/private/secrets.tdb
3652
@@endif
3653
=@@{TOPDIR}home Norm
3654
</pre>
3655
3656
<p>
3657
In the above example we specify with some macros where the topdir starts and
3658
where the AIDE directory is. AIDE checks the <path>/etc/aide/aide.db</path> file
3659
when checking for file integrity. But when updating or creating a new file it
3660
stores the information in <path>/etc/aide/aide.db.new</path>. This is done so it
3661
won't automatically overwrite the old db file. The option
3662
<c>report_URL</c> is not yet implemented, but the author's intention was that 
3663
it should be able to e-mail or maybe even execute scripts.
3664
</p>
3665
3666
<p>
3667
After editing the configuration you should create your db file by executing
3668
<c>aide -i</c> and then copy the file <path>/etc/aide/aide.db.new</path> to 
3669
<path>/etc/aide/aide.db</path> and add the check to cron by executing 
3670
<c>crontab -e</c> as root.
3671
</p>
3672
3673
<note>
3674
Depending on your CPU, disk access speed, and the flags you have set on files,
3675
this can take some time.
3676
</note>
3677
3678
<pre caption="Shedule aide as a cronjob">
3679
0 3 * * * /usr/bin/aide -u
3680
</pre>
3681
3682
<note>
3683
Remember to set an alias so you get roots mail. Otherwise you will never know
3684
what AIDE reports.
3685
</note>
3686
3687
<p>
3688
In this case it runs once at 3am. This is done since I do not want to disturb
3689
the users when they are working. Note I am using the <c>-u</c> (Update) option
3690
instead of the <c>-C</c> (Check). Since <c>-u</c> also checks the files and does
3691
not overwrite the original db file it saves some time since all you need to do
3692
is to copy a file when it detects some changes. Just check the changes to see if
3693
it was you who made the changes instead of some attacker before you copy it!
3694
</p>
3695
3696
<p>
3697
Now there is some risk inherent with storing the db files locally, since the
3698
attacker will (if they know that AIDE is installed) most certainly try to alter
3699
the db file, update the db file or modify <path>/usr/bin/aide</path>. So you
3700
should create a CD or other media and put on it a copy of the .db file and the
3701
AIDE binaries.
3702
</p>
3703
3704
<p>
3705
One can find information at the <uri link="http://www.cs.tut.fi/~rammer/aide.html">AIDE</uri> project page.
3706
</p>
3707
3708
</body>
3709
</section>
3710
<section>
3711
<title>Snort</title>
3712
<body>
3713
3714
<p>
3715
Snort is a Network Intrusion Detection System (NIDS). To install and configure
3716
it use the following examples.
3717
</p>
3718
3719
<pre caption="Add a user snort to the system">
3720
# useradd snort -d /var/log/snort -s /dev/null
3721
# chown -R snort /var/log/snort
3722
</pre>
3723
3724
<pre caption="/etc/conf.d/snort">
3725
PIDFILE=/var/run/snort_eth0.pid
3726
MODE="full"
3727
NETWORK="10.0.0.0/24"
3728
LOGDIR="/var/log/snort"
3729
CONF=/etc/snort/snort.conf
3730
SNORT_OPTS="-D -s -u snort -dev -l $LOGDIR -h $NETWORK -c $CONF"
3731
</pre>
3732
3733
<pre caption="/etc/snort/snort.conf">
3734
<comment>(Step 1)</comment>
3735
var HOME_NET 10.0.0.0/24
3736
var EXTERNAL_NET any
3737
var SMTP $HOME_NET
3738
var HTTP_SERVERS $HOME_NET
3739
var SQL_SERVERS $HOME_NET
3740
var DNS_SERVERS [10.0.0.2/32,212.242.40.51/32]
3741
var RULE_PATH ./
3742
3743
<comment>(Step 2)</comment>
3744
preprocessor frag2
3745
preprocessor stream4: detect_scans detect_state_problems detect_scans disable_evasion_alerts
3746
preprocessor stream4_reassemble: ports all
3747
preprocessor http_decode: 80 8080 unicode iis_alt_unicode double_encode iis_flip_slash full_whitespace
3748
preprocessor rpc_decode: 111 32771
3749
preprocessor bo: -nobrute
3750
preprocessor telnet_decode
3751
3752
<comment>(Step 3)</comment>
3753
include classification.config
3754
3755
<comment>(Step 4)</comment>
3756
include $RULE_PATH/bad-traffic.rules
3757
include $RULE_PATH/exploit.rules
3758
include $RULE_PATH/scan.rules
3759
include $RULE_PATH/finger.rules
3760
include $RULE_PATH/ftp.rules
3761
include $RULE_PATH/telnet.rules
3762
include $RULE_PATH/smtp.rules
3763
include $RULE_PATH/rpc.rules
3764
include $RULE_PATH/rservices.rules
3765
include $RULE_PATH/dos.rules
3766
include $RULE_PATH/ddos.rules
3767
include $RULE_PATH/dns.rules
3768
include $RULE_PATH/tftp.rules
3769
include $RULE_PATH/web-cgi.rules
3770
include $RULE_PATH/web-coldfusion.rules
3771
include $RULE_PATH/web-iis.rules
3772
include $RULE_PATH/web-frontpage.rules
3773
include $RULE_PATH/web-misc.rules
3774
include $RULE_PATH/web-attacks.rules
3775
include $RULE_PATH/sql.rules
3776
include $RULE_PATH/x11.rules
3777
include $RULE_PATH/icmp.rules
3778
include $RULE_PATH/netbios.rules
3779
include $RULE_PATH/misc.rules
3780
include $RULE_PATH/attack-responses.rules
3781
include $RULE_PATH/backdoor.rules
3782
include $RULE_PATH/shellcode.rules
3783
include $RULE_PATH/policy.rules
3784
include $RULE_PATH/porn.rules
3785
include $RULE_PATH/info.rules
3786
include $RULE_PATH/icmp-info.rules
3787
include $RULE_PATH/virus.rules
3788
# include $RULE_PATH/experimental.rules
3789
include $RULE_PATH/local.rules
3790
</pre>
3791
3792
<pre caption="/etc/snort/classification.config">
3793
config classification: not-suspicious,Not Suspicious Traffic,3
3794
config classification: unknown,Unknown Traffic,3
3795
config classification: bad-unknown,Potentially Bad Traffic, 2
3796
config classification: attempted-recon,Attempted Information Leak,2
3797
config classification: successful-recon-limited,Information Leak,2
3798
config classification: successful-recon-largescale,Large Scale Information Leak,2
3799
config classification: attempted-dos,Attempted Denial of Service,2
3800
config classification: successful-dos,Denial of Service,2
3801
config classification: attempted-user,Attempted User Privilege Gain,1
3802
config classification: unsuccessful-user,Unsuccessful User Privilege Gain,1
3803
config classification: successful-user,Successful User Privilege Gain,1
3804
config classification: attempted-admin,Attempted Administrator Privilege Gain,1
3805
config classification: successful-admin,Successful Administrator Privilege Gain,1
3806
3807
# NEW CLASSIFICATIONS
3808
config classification: rpc-portmap-decode,Decode of an RPC Query,2
3809
config classification: shellcode-detect,Executable code was detected,1
3810
config classification: string-detect,A suspicious string was detected,3
3811
config classification: suspicious-filename-detect,A suspicious filename was detected,2
3812
config classification: suspicious-login,An attempted login using a suspicious username was detected,2
3813
config classification: system-call-detect,A system call was detected,2
3814
config classification: tcp-connection,A TCP connection was detected,4
3815
config classification: trojan-activity,A Network Trojan was detected, 1
3816
config classification: unusual-client-port-connection,A client was using an unusual port,2
3817
config classification: network-scan,Detection of a Network Scan,3
3818
config classification: denial-of-service,Detection of a Denial of Service Attack,2
3819
config classification: non-standard-protocol,Detection of a non-standard protocol or event,2
3820
config classification: protocol-command-decode,Generic Protocol Command Decode,3
3821
config classification: web-application-activity,access to a potentially vulnerable web application,2
3822
config classification: web-application-attack,Web Application Attack,1
3823
config classification: misc-activity,Misc activity,3
3824
config classification: misc-attack,Misc Attack,2
3825
config classification: icmp-event,Generic ICMP event,3
3826
config classification: kickass-porn,SCORE! Get the lotion!,1
3827
</pre>
3828
3829
<p>
3830
More information is at the <uri link="http://www.snort.org">Snort</uri> web site.
3831
</p>
3832
3833
</body>
3834
</section>
3835
3836
<section>
3837
<title>Detecting malware with chkrootkit</title>
3838
3839
<body>
3840
3841
<p>
3842
HIDS like AIDE are a great way to detect changes to your system, but it never
3843
hurts to have another line of defence. <c>chkrootkit</c> is a utility that scans
3844
common system files for the presence of rootkits--software designed to hide an
3845
intruder's actions and allow him to retain his access--and scans your system for
3846
likely traces of key loggers and other "malware". While <c>chkrootkit</c> (and
3847
alternatives like <c>rkhunter</c>) are useful tools, both for system
3848
maintenance and for tracking an intruder after an attack has occurred, they
3849
cannot guarantee your system is secure.
3850
</p>
3851
3852
<p>
3853
The best way to use <c>chkrootkit</c> to detect an intrusion is to run it
3854
routinely from <c>cron</c>. To start, emerge <path>app-admin/chkrootkit</path>. 
3855
<c>chkrootkit</c> can be run from the command line by the command of the same
3856
name, or from <c>cron</c> with an entry such as this:
3857
</p>
3858
3859
<pre caption="Schedule chkrootkit as a cronjob">
3860
0 3 * * * /usr/sbin/chkrootkit
3861
</pre>
3862
3863
</body>
3864
</section>
3865
3866
</chapter>
3867
3868
<chapter>
3869
<title>Keeping up to date</title>
3870
<section>
3871
<body>
3872
3873
<p>
3874
Once you have successfully installed your system and ensured a good level of
3875
security you are not done. Security is an ongoing process; the vast majority of
3876
intrusions result from known vulnerabilities in unpatched systems. Keeping your
3877
system up-to-date is the single most valuable step you can take to greater
3878
security.
3879
</p>
3880
3881
<p>
3882
If you have a recent version of <c>portage</c> installed, you can first sync
3883
your portage tree with <c>emerge --sync</c> and then issue the command
3884
<c>glsa-check --list</c> to check if your system is up to date security-wise.
3885
<c>glsa-check</c> is part of <c>app-portage/gentoolkit</c>.
3886
</p>
3887
3888
<pre caption="Example output of glsa-check -l">
3889
# <i>glsa-check -l</i>
3890
WARNING: This tool is completely new and not very tested, so it should not be
3891
used on production systems. It's mainly a test tool for the new GLSA release
3892
and distribution system, it's functionality will later be merged into emerge
3893
and equery.
3894
Please read http://www.gentoo.org/proj/en/portage/glsa-integration.xml
3895
before using this tool AND before reporting a bug.
3896
3897
[A] means this GLSA was already applied,
3898
[U] means the system is not affected and
3899
[N] indicates that the system might be affected.
3900
3901
200406-03 [N] sitecopy: Multiple vulnerabilities in included libneon ( net-misc/sitecopy )
3902
200406-04 [U] Mailman: Member password disclosure vulnerability ( net-mail/mailman )
3903
.......
3904
</pre>
3905
3906
<warn>
3907
The <c>glsa-check</c> is still experimental, so if security really is your top
3908
priority it would be wise to double check the list with other sources.
3909
</warn>
3910
3911
<p>
3912
All lines with a <c>[A]</c> and <c>[U]</c> can be almost safely ignored as the
3913
system is not affected by this GLSA.
3914
</p>
3915
3916
<p>
3917
Some people still prefer to use <c>emerge packagename</c> instead of
3918
<c>glsa-check -f</c> so all GLSAs are listed as <c>[N]</c>.
3919
</p>
3920
3921
<p>
3922
If you want an email each time a GLSA is released subscribe to the 
3923
<c>gentoo-announce</c> mailing list. Instructions for joining it and many other
3924
great mailing lists can be found <uri link="/main/en/lists.xml">Gentoo Linux
3925
Mailing List Overview</uri>.
3926
</p>
3927
3928
<p>
3929
Another great security resource is the <uri link="http://www.securityfocus.com/archive/1">Bugtraq
3930
mailing list</uri>.
3931
</p>
3932
3933
</body>
3934
</section>
3935
</chapter>
25
</chapter>
3936
</guide>
26
</guide>

Return to bug 71211