Сборник статей Handbook inside ! : Linux не для идиотов inside ! : Версия 1 от 15. 07. 2007 2007

Pdf просмотр
Размер5.65 Mb.
ТипСборник статей
1   ...   26   27   28   29   30   31   32   33   ...   50
@dev - maxlogins 10
If you find yourself trying to set nproc or maxlogins to 0, maybe you should delete the user instead. The example above sets the group dev settings for processes, core file and maxlogins. The rest is set to a default value.
Примечание: /etc/security/limits.conf is part of the PAM package and will only apply to packages that use PAM.

5.b. /etc/limits
/etc/limits is very similar to the limit file /etc/security/limits.conf. The only difference is the format and that it only works on users or wild cards (not groups). Let's have a look at a sample configuration:
Листинг 2: /etc/limits
* L2 C0 U15 R10000
kn L10 C100000 U35
Here we set the default settings and a specific setting for the user kn. Limits are part of the sys-apps/shadow package. It is not necessary to set any limits in this file if you have disabled pam in make.conf or not configured PAM properly.
5.c. Quotas
Предупреждение: Make sure the file systems you are working with support quotas. In order to use quotas on ReiserFS, you must patch your kernel with patches available from
Namesys. User tools are available from the Linux DiskQuota project. While quotas do work with ReiserFS, you may encounter other issues while trying to use them--you have been warned!
Putting quotas on a file system restricts disk usage on a per-user or per-group basis.
Quotas are enabled in the kernel and added to a mount point in /etc/fstab. The kernel option is enabled in the kernel configuration under File systems->Quota support. Apply the following settings, rebuild the kernel and reboot using the new kernel.
Start by installing quotas with emerge quota. Then modify your /etc/fstab and add usrquota and grpquota to the partitions that you want to restrict disk usage on, like in the example below.
Листинг 3: /etc/fstab
/dev/sda1 /boot ext2 noauto,noatime 1 1
/dev/sda2 none swap sw 0 0
/dev/sda3 / reiserfs notail,noatime 0 0
/dev/sda4 /tmp ext3 noatime,nodev,nosuid,noexec,usrquota,grpquota 0 0
/dev/sda5 /var ext3 noatime,nodev,usrquota,grpquota 0 0
/dev/sda6 /home ext3 noatime,nodev,nosuid,usrquota,grpquota 0 0
/dev/sda7 /usr reiserfs notail,noatime,nodev,ro 0 0
/dev/cdroms/cdrom0 /mnt/cdrom iso9660 noauto,ro 0 0 367
proc /proc proc defaults 0 0
On every partition that you have enabled quotas, create the quota files (aquota.user and aquota.group) and place them in the root of the partition.
Листинг 4: Creating the quota files
# touch /tmp/aquota.user
# touch /tmp/aquota.group
# chmod 600 /tmp/aquota.user
# chmod 600 /tmp/aquota.group
This step has to be done on every partition where quotas are enabled. After adding and configuring the quota files, we need to add the quota script to the boot run level.
Листинг 5: Adding quota to the boot runlevel
# rc-update add quota boot
We will now configure the system to check the quotas once a week by adding the following line to /etc/crontab:
Листинг 6: Adding quota check to crontab
0 3 * * 0 /usr/sbin/quotacheck -avug.
After rebooting the machine, it is time to setup the quotas for users and groups. edquota -u kn will start the editor defined in $EDITOR (default is nano) and let you edit the quotas of the user kn. edquota -g will do the same thing for groups.
Листинг 7: Setting up quota's for user kn
Quotas for user kn:
/dev/sda4: blocks in use: 2594, limits (soft = 5000, hard = 6500)
inodes in use: 356, limits (soft = 1000, hard = 1500)
For more detail read man edquota or the Quota mini howto.

5.d. /etc/login.defs
If your security policy states that users should change their password every other week, change the value PASS_MAX_DAYS to 14 and PASS_WARN_AGE to 7. It is recommended that you use password aging since brute force methods can find any password, given enough time. We also encourage you to set LOG_OK_LOGINS to yes.
5.e. /etc/login.access
The login.access file is also part of the sys-apps/shadow package, which provides a login access control table. This table is used to control who can and cannot login based on user name, group name or host name. By default, all users on the system are allowed to login, so the file consists only of comments and examples. Whether you are securing your server or workstation, we recommend that you setup this file so no one other than yourself (the admin) has access to the console.
Примечание: These settings do not apply for root.
Листинг 8: /etc/login.access
-:ALL EXCEPT wheel sync:console
-:wheel:ALL EXCEPT LOCAL .gentoo.org
Важно: Be careful when configuring these options, since mistakes will leave you with no access to the machine if you do not have root access.
Примечание: These settings do not apply to SSH, since SSH does not execute /bin/login per default. This can be enabled by setting UseLogin yes in /etc/ssh/sshd_config.
This will setup login access so members of the wheel group can login locally or from the gentoo.org domain. Maybe too paranoid, but better to be safe than sorry.
6. Права доступа к файлам
6.a. World readable
Normal users should not have access to configuration files or passwords. An attacker can steal passwords from databases or web sites and use them to deface--or even worse, delete--data. This is why it is important that your file permissions are correct. If you are sure that a file is only used by root, assign it with the permissions 0600 and assign the file to the correct user with chown.
6.b. World/Group writable

Листинг 1: Finding world-writable files and directories
# find / -type f \( -perm -2 -o -perm -20 \) -exec ls -lg {} \; 2>/dev/null >writable.txt
# find / -type d \( -perm -2 -o -perm -20 \) -exec ls -ldg {} \; 2>/dev/null >>writable.txt
This will create a huge file with permission of all files having either write permission set to the group or everybody. Check the permissions and eliminate world writable files to everyone, by executing /bin/chmod o-w on the files.
6.c. SUID/SGID files
Files with the SUID or SGID bit set execute with privileges of the owning user or group and not the user executing the file. Normally these bits are used on files that must run as root in order to do what they do. These files can lead to local root compromises (if they contain security holes). This is dangerous and files with the SUID or SGID bits set should be avoided at any cost. If you do not use these files, use chmod 0 on them or unmerge the package that they came from (check which package they belong to by using equery; if you do not already have it installed simply type emerge gentoolkit). Otherwise just turn the
SUID bit off with chmod -s.
Листинг 2: Finding setuid files
# find / -type f \( -perm -004000 -o -perm -002000 \) -exec ls -lg {} \; 2>/dev/null
This will create a file containing a list of all the SUID/SGID files.
Листинг 3: List of setuid binaries
/usr/bin/sperl5.6.1 370

By default Gentoo Linux does not have a lot of SUID files (though this depends on what you installed), but you might get a list like the one above. Most of the commands should not be used by normal users, only root. Switch off the SUID bit on ping, mount, umount, chfn, chsh, newgrp, suidperl, pt_chown and traceroute by executing chmod -s on every file. Don't remove the bit on su, qmail-queue or unix_chkpwd. Removing setuid from those files will prevent you from su'ing and receiving mail. By removing the bit (where it is safe to do so) you remove the possibility of a normal user (or an attacker) gaining root access through any of these files.
The only SUID files that I have on my system are su, passwd, gpasswd, qmail-queue, unix_chkpwd and pwdb_chkpwd. But if you are running X, you might have some more, since X needs the elevated access afforded by SUID.
6.d. SUID/SGID binaries and Hard links
A file is only considered deleted when there are no more links pointing to it. This might sound like a strange concept, but consider that a filename like /usr/bin/perl is actually a link to the inode where the data is stored. Any number of links can point to the file, and until all of them are gone, the file still exists.
If your users have access to a partition that isn't mounted with nosuid or noexec (for example, if /tmp, /home, or /var/tmp are not separate partitions) you should take care to ensure your users don't create hard links to SUID or SGID binaries, so that after Portage updates they still have access to the old versions.
Предупреждение: if you have received a warning from portage about remaining hard links, and your users can write to a partition that allows executing SUID/SGID files, you should read this section carefully. One of your users may be attempting to circumvent your update by keeping an outdated version of a program. If your users cannot create their own
SUID files, or can only execute programs using the dynamic loader (partitions mounted noexec), you do not have to worry.
Примечание: Users do not need read access to a file to create a link to it, they only need read permission to the directory that contains it.

To check how many links a file has, you can use the stat command.
Листинг 4: Stat command
$ stat /bin/su
File: `/bin/su'
Size: 29350 Blocks: 64 IO Block: 131072 regular file
Device: 900h/2304d Inode: 2057419 Links: 1
Access: (4711/-rws--x--x) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2005-02-07 01:59:35.000000000 +0000
Modify: 2004-11-04 01:46:17.000000000 +0000
Change: 2004-11-04 01:46:17.000000000 +0000
To find the SUID and SGID files with multiple links, you can use find.
Листинг 5: Finding multiply linked suid/sgid binaries
$ find / -type f \( -perm -004000 -o -perm -002000 \) -links +1 -ls
7. PAM
7.a. PAM
PAM is a suite of shared libraries that provide an alternative way providing user authentication in programs. The pam USE flag is turned on by default. Thus the PAM settings on Gentoo Linux are pretty reasonable, but there is always room for improvement.
First install cracklib.
Листинг 1: Installing cracklib
# emerge cracklib
Листинг 2: /etc/pam.d/passwd auth required pam_unix.so shadow nullok account required pam_unix.so password required pam_cracklib.so difok=3 retry=3 minlen=8 dcredit=-2 ocredit=-2
password required pam_unix.so md5 use_authtok
session required pam_unix.so
This will add the cracklib which will ensure that the user passwords are at least 8 characters and contain a minimum of 2 digits, 2 other characters, and are more than 3 characters different from the last password. This forces the user to choose a good password (password policy). Check the PAM documentation for more options.
Листинг 3: /etc/pam.d/sshd auth required pam_unix.so nullok auth required pam_shells.so auth required pam_nologin.so auth required pam_env.so account required pam_unix.so password required pam_cracklib.so difok=3 retry=3 minlen=8 dcredit=-2 ocredit=-2 use_authtok password required pam_unix.so shadow md5
session required pam_unix.so session required pam_limits.so
Every service not configured with a PAM file in /etc/pam.d will use the rules in
/etc/pam.d/other. The defaults are set to deny, as they should be. But I like to have a lot of logs, which is why I added pam_warn.so. The last configuration is pam_limits, which is controlled by /etc/security/limits.conf. See the /etc/security/limits.conf section for more on these settings.
Листинг 4: /etc/pam.d/other auth required pam_deny.so auth required pam_warn.so account required pam_deny.so account required pam_warn.so password required pam_deny.so password required pam_warn.so session required pam_deny.so session required pam_warn.so
8. Упаковщики TCP
8.a. TCP Wrappers

This is a way of controlling access to services normally run by inetd (which Gentoo does not have), but it can also be used by xinetd and other services.
Примечание: The service should be executing tcpd in its server argument (in xinetd). See the chapter on xinetd for more information.
Листинг 1: /etc/hosts.deny
Листинг 2: /etc/hosts.allow
ALL: LOCAL @wheel time: LOCAL, .gentoo.org
As you can see the format is very similar to the one in /etc/login.access. Tcpd supports a specific service; it does not overlap with /etc/login.access. These settings only apply to services using tcp wrappers.
It is also possible to execute commands when a service is accessed (this can be used when activating relaying for dial-in users) but it is not recommended, since people tend to create more problems than they are trying to solve. An example could be that you configure a script to send an e-mail every time someone hits the deny rule, but then an attacker could launch a DoS attack by keep hitting the deny rule. This will create a lot of
I/O and e-mails so don't do it!. Read the man 5 hosts_access for more information.
9. Безопасность ядра
9.a. Removing functionality
The basic rule when configuring the kernel is to remove everything that you do not need.
This will not only create a small kernel but also remove the vulnerabilities that may lie inside drivers and other features.
Also consider turning off loadable module support. Even though it is possible to add root kits without this features, it does make it harder for normal attackers to install root kits via kernel modules.
9.b. The proc filesystem
Many kernel parameters can be altered through the /proc file system or by using sysctl.

To dynamically change kernel parameters and variables on the fly, you need
CONFIG_SYSCTL defined in your kernel. This is on by default in a standard 2.4 kernel.
Листинг 1: Deactivate IP forwarding
# /bin/echo "0" > /proc/sys/net/ipv4/ip_forward
Make sure that IP forwarding is turned off. We only want this for a multi-homed host. It's advised to set or unset this flag before all other flags since it enabled/disables other flags as well.
Листинг 2: Drop ping packets
# /bin/echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_all
This will cause the kernel to simply ignore all ping messages (also known as ICMP type 0 messages). The reason for this is that an IP packet carrying an ICMP message can contain a payload with information other than you think. Administrators use ping as a diagnostic tool and often complain if it is disabled, but there is no reason for an outsider to be able to ping. However, since it sometimes can be handy for insiders to be able to ping, you can disable ICMP type 0 messages in the firewall (allowing local administrators to continue to use this tool).
Листинг 3: Ignore broadcast pings
# /bin/echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
This disables response to ICMP broadcasts and will prevent Smurf attacks. The Smurf attack works by sending an ICMP type 0 (ping) message to the broadcast address of a network. Typically the attacker will use a spoofed source address. All the computers on the network will respond to the ping message and thereby flood the host at the spoofed source address.
Листинг 4: Disable source routed packets
# /bin/echo "0" > /proc/sys/net/ipv4/conf/all/accept_source_route
Do not accept source routed packets. Attackers can use source routing to generate traffic pretending to originate from inside your network, but that is actually routed back along the path from which it came, so attackers can compromise your network. Source routing is rarely used for legitimate purposes, so it is safe to disable it.

Листинг 5: Disable redirect acceptance
# /bin/echo "0" > /proc/sys/net/ipv4/conf/all/accept_redirects
# /bin/echo "0" > /proc/sys/net/ipv4/conf/all/secure_redirects
Do not accept ICMP redirect packets. ICMP redirects can be used to alter your routing tables, possibly to a malicious end.
Листинг 6: Protect against bad error messages
# /bin/echo "1" > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses
Enable protection against bogus error message responses.
Листинг 7: Enable reverse path filtering
# for i in /proc/sys/net/ipv4/conf/*; do
/bin/echo "1" > $i/rp_filter done
Turn on reverse path filtering. This helps make sure that packets use legitimate source addresses by automatically rejecting incoming packets if the routing table entry for their source address does not match the network interface they are arriving on. This has security advantages because it prevents IP spoofing. We need to enable it for each net/ipv4/conf/* otherwise source validation isn't fully functional.
Предупреждение: However turning on reverse path filtering can be a problem if you use asymmetric routing (packets from you to a host take a different path than packets from that host to you) or if you operate a non-routing host which has several IP addresses on different interfaces.
Листинг 8: Log all spoofed, source routed and redirect packets
# /bin/echo "1" > /proc/sys/net/ipv4/conf/all/log_martians
Log spoofed packets, source routed packets and redirect packets.
All these settings will be reset when the machine is rebooted. I suggest that you add them to /etc/sysctl.conf, which is automatically sourced by the /etc/init.d/bootmisc init script.

The syntax for /etc/sysctl.conf is pretty straightforward. Strip off the /proc/sys/ from the previously mentioned paths and substitute / with .:
Листинг 9: Translating to sysctl.conf
(Manual using echo):
/bin/echo "0" > /proc/sys/net/ipv4/ip_forward
(Automatic in sysctl.conf:)
net.ipv4.ip_forward = 0 9.c. Grsecurity
The patch from Grsecurity is standard in the sys-kernel/hardened-sources but is disabled by default. Configure your kernel as you normally do and then configure the Grsecurity options. An in-depth explanation on the available Grsecurity options is available on the
Gentoo Hardened project page.
Recent hardened-sources provide the 2.* version of Grsecurity. For more information on this improved Grsecurity patch set, please consult the documentation available on the
Grsecurity home page.
9.d. Kerneli
Kerneli is a patch that adds encryption to the existing kernel. By patching your kernel you will get new options such as cryptographic ciphers, digest algorithms and cryptographic loop filters.
Предупреждение: The kerneli patch is currently not in a stable version for the latest kernel, so be careful when using it.
9.e. Other kernel patches
The OpenWall Project
Linux Intrusion Detection System
Rule Set Based Access Control
NSA's security enhanced kernel
And there are probably a lot more.

10. Безопасность служб
10.a. Apache
Apache (1.3.26) comes with a pretty decent configuration file but again, we need to improve some things, like binding Apache to one address and preventing it from leaking information. Below are the options that you should apply the configuration file.
If you did not disable ssl in your /etc/make.conf before installing Apache, you should have access to an ssl enabled server. Just add the following line to enable it.
Листинг 1: /etc/conf.d/apache
Листинг 2: /etc/apache/conf/apache.conf
#Make it listen on your ip
#It is not a good idea to use nobody or nogroup -
#for every service not running as root
#(just add the user apache with group apache)
User apache
Group apache
#Will keep apache from telling about the version
ServerSignature Off
ServerTokens Prod
Apache is compiled with --enable-shared=max and --enable-module=all. This will by default enable all modules, so you should comment out all modules in the LoadModule section (LoadModule and AddModule) that you do not use. Restart the service by executing /etc/init.d/apache restart.
Documentation is available at http://www.apache.org.
10.b. Bind
One can find documentation at the Internet Software Consortium. The BIND 9
Administrator Reference Manual is also in the doc/arm.

The newer BIND ebuilds support chrooting out of the box. After emerging bind follow these simple instructions:
Листинг 3: Chrooting BIND
ebuild /var/db/pkg/net-dns/bind-9.2.2-r2/bind-9.2.2-r2.ebuild config\`"
(Before running the above command you might want to change the chroot directory in /etc/conf.d/named. Otherwise /chroot/dns will be used.)
(You might need to substitute the version number with the current version number )
10.c. Djbdns
Djbdns is a DNS implementation on the security of which its author is willing to bet money.
It is very different from how Bind 9 works but worth a try. More information can be obtained from http://www.djbdns.org.
10.d. FTP
Generally, using FTP (File Transfer Protocol) is a bad idea. It uses unencrypted data (ie. passwords are sent in clear text), listens on 2 ports (normally port 20 and 21), and attackers are frequently looking for anonymous logins for trading warez. Since the FTP protocol contains several security problems you should instead use sftp or HTTP. If this is not possible, secure your services as well as you can and prepare yourself.
10.e. Mysql
If you only need local applications to access the mysql database, uncomment the following line in /etc/mysql/my.cnf.
Листинг 4: Disable network access skip-networking
Then we disable the use of the LOAD DATA LOCAL INFILE command. This is to prevent against unauthorized reading from local files. This is relevant when new SQL Injection vulnerabilities in PHP applications are found.
Листинг 5: Disable LOAD DATA LOCAL INFILE in the [mysqld] section set-variable=local-infile=0 379

Next, we must remove the sample database (test) and all accounts except the local root account.
Листинг 6: Removing sample database and all unnecessary users mysql> drop database test;
mysql> use mysql;
mysql> delete from db;
mysql> delete from user where not (host="localhost" and user="root");
mysql> flush privileges;
Предупреждение: Be careful with the above if you have already configured user accounts.
Примечание: If you have been changing passwords from the MySQL prompt, you should always clean out
/.mysql_history and /var/log/mysql/mysql.log as they store the executed
SQL commands with passwords in clear text.
10.f. Proftpd
Proftpd has had several security problems, but most of them seem to have been fixed.
Nonetheless, it is a good idea to apply some enhancements:
Листинг 7: /etc/proftpd/proftpd.conf
ServerName "My ftp daemon"
#Don't show the ident of the server
ServerIdent on "Go away"
#Makes it easier to create virtual users
RequireValidShell off
#Use alternative password and group file (passwd uses crypt format)
AuthUserFile "/etc/proftpd/passwd"
AuthGroupFile "/etc/proftpd/group"
# Permissions
Umask 077 380

# Timeouts and limitations
MaxInstances 30
MaxClients 10 "Only 10 connections allowed"
MaxClientsPerHost 1 "You have already logged on once"
MaxClientsPerUser 1 "You have already logged on once"
TimeoutStalled 10
TimeoutNoTransfer 20
TimeoutLogin 20
#Chroot everyone
#don't run as root
User nobody
Group nogroup
#Log every transfer
TransferLog /var/log/transferlog
#Problems with globbing
DenyFilter \*.*/
One can find documentation at http://www.proftpd.org.
10.g. Pure-ftpd
Pure-ftpd is an branch of the original trollftpd, modified for security reasons and functionality by Frank Dennis.
Use virtual users (never system accounts) by enabling the AUTH option. Set this to
-lpuredb:/etc/pureftpd.pdb and create your users by using /usr/bin/pure-pw.
Листинг 8: /etc/conf.d/pure-ftpd
## Misc. Others ##

MISC_OTHER="-A -E -X -U 177:077 -d -4 -L100:5 -I 15"
Configure your MISC_OTHER setting to deny anonymous logins (-E), chroot everyone
(-A), prevent users from reading or writing to files beginning with a . (dot) (-X), max idle time (-I), limit recursion (-L), and a reasonable umask.
Предупреждение: Do not use the -w or -W options! If you want to have a warez site, stop reading this guide!
One can find documentation at http://www.pureftpd.org.
10.h. Vsftpd
Vsftpd (short for very secure ftp) is a small ftp daemon running a reasonably default configuration. It is simple and does not have as many features as pureftp and proftp.
Листинг 9: /etc/vsftpd anonymous_enable=NO
#read only write_enable=NO
#enable logging of transfers xferlog_std_format=YES
nopriv_user=nobody chroot_list_enable=YES
chroot_list_file=/etc/vsftpd/chrootlist ls_recurse_enable=NO
As you can see, there is no way for this service to have individual permissions, but when it comes to anonymous settings it is quite good. Sometimes it can be nice to have an
anonymous ftp server (for sharing open source), and vsftpd does a really good job at this.
10.i. Qmail
Qmail is often considered to be a very secure mail server. It is written with security (and paranoia) in mind. It does not allow relaying by default and has not had a security hole since 1996. Simply emerge qmail and go configure!
10.j. Samba
Samba is a protocol to share files with Microsoft/Novell networks and it should not be used over the Internet. Nonetheless, it still needs securing.
Листинг 10: /etc/samba/smb.conf
#Bind to an interface interfaces = eth0
#Make sure to use encrypted password encrypt passwords = yes directory security mask = 0700
#allow traffic from 10.0.0.*
hosts allow = 10.0.0.
#Enables user authentication
#(don't use the share mode)
security = user
#Disallow privileged accounts invalid users = root @wheel
#Maximum size smb shows for a share (not a limit)
max disk size = 102400
#Uphold the password policy min password length = 8
null passwords = no

#Use PAM (if added support)
obey pam restrictions = yes pam password change = yes
Make sure that permissions are set correct on every share and remember to read the documentation.
Now restart the server and add the users who should have access to this service. This is done though the command /usr/bin/smbpasswd with the parameter -a.
10.k. ssh
The only securing that OpenSSH needs is turning on a stronger authentication based on public key encryption. Too many sites (like http://www.sourceforge.net, http://www.php.net and http://www.apache.org) have suffered unauthorized intrusion due to password leaks or bad passwords.
Листинг 11: /etc/ssh/sshd_config
#Only enable version 2
Protocol 2
#Disable root login. Users have to su to root
PermitRootLogin no
#Turn on Public key authentication
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
#Disable .rhost and normal password authentication
RhostsAuthentication no
PasswordAuthentication no
PermitEmptyPasswords no
#Only allow userin the wheel or admin group to login
AllowGroups wheel admin
#In those groups only allow the following users

#The @ is optional but replaces the
#older AllowHosts directive
AllowUsers kn@gentoo.org bs@gentoo.org
SyslogFacility AUTH
LogLevel INFO
Also verify that you don't have UsePAM yes in your configuration file as it overrides the public key authentication mechanism.
Now all that your users have to do is create a key (on the machine they want to login from) with the following command:
Листинг 12: Create a DSA keypair
# /usr/bin/ssh-keygen -t dsa
And type in a pass phrase.
Листинг 13: Output of ssh-keygen
Generating public/private dsa key pair.
Enter file in which to save the key (/home/kn/.ssh/id_dsa):[Press enter]
Created directory '/home/kn/.ssh'.
Enter passphrase (empty for no passphrase): [Enter passphrase]
Enter same passphrase again: [Enter passphrase again]
Your identification has been saved in /home/kn/.ssh/id_dsa.
Your public key has been saved in /home/kn/.ssh/id_dsa.pub.
The key fingerprint is:
07:24:a9:12:7f:83:7e:af:b8:1f:89:a3:48:29:e2:a4 kn@knielsen
This will add two files in your
/.ssh/ directory called id_dsa and id_dsa.pub. The file called id_dsa is your private key and should be kept from other people than yourself. The other file id_dsa.pub is to be distributed to every server that you have access to. Add the key to the users home directory in
/.ssh/authorized_keys and the user should be able to login:

Листинг 14: Adding the id_dsa.pub file to the authorized_keys file
$ scp id_dsa.pub other-host:/var/tmp/currenthostname.pub
$ ssh other-host password:
$ cat /var/tmp/currenthostname.pub >>
Now your users should guard this private key well. Put it on a media that they always carry with them or keep it on their workstation (put this in the password policy).
For more information go to the OpenSSH web site.
10.l. Using xinetd xinetd is a replacement for inetd (which Gentoo does not have), the Internet services daemon. It supports access control based on the address of the remote host and the time of access. It also provide extensive logging capabilities, including server start time, remote host address, remote user name, server run time, and actions requested.
As with all other services it is important to have a good default configuration. But since xinetd is run as root and supports protocols that you might not know how they work, we recommend not to use it. But if you want to use it anyway, here is how you can add some security to it:
Листинг 15: Install xinetd
# emerge xinetd tcp-wrappers
And edit the configuration file:
Листинг 16: /etc/xinetd.conf defaults
only_from = localhost instances = 10
log_type = SYSLOG authpriv info log_on_success = HOST PID
log_on_failure = HOST
cps = 25 30 386

# This will setup pserver (cvs) via xinetd with the following settings:
# max 10 instances (10 connections at a time)
# limit the pserver to tcp only
# use the user cvs to run this service
# bind the interfaces to only 1 ip
# allow access from 10.0.0.*
# limit the time developers can use cvs from 8am to 5pm
# use tpcd wrappers (access control controlled in
# /etc/hosts.allow and /etc/hosts.deny)
# max_load on the machine set to 1.0
# The disable flag is per default set to no but I like having
# it in case of it should be disabled service cvspserver
socket_type = stream protocol = tcp instances = 10
protocol = tcp wait = no user = cvs bind =
only_from =
access_times = 8:00-17:00
server = /usr/sbin/tcpd server_args = /usr/bin/cvs --allow-root=/mnt/cvsdisk/cvsroot pserver max_load = 1.0
log_on_failure += RECORD
disable = no
For more information read man 5 xinetd.conf.
10.m. X

By default Xorg is configured to act as an Xserver. This can be dangerous since X uses unencrypted TCP connections and listens for xclients.
Важно: If you do not need this service disable it!
But if you depend on using your workstation as a Xserver use the /usr/X11R6/bin/xhost command with caution. This command allows clients from other hosts to connect and use your display. This can become handy if you need an X application from a different machine and the only way is through the network, but it can also be exploited by an attacker. The syntax of this command is /usr/X11R6/bin/xhost +hostname
Предупреждение: Do not ever use the xhost + feature! This will allow any client to connect and take control of your X. If an attacker can get access to your X, he can log your keystrokes and take control over your desktop. If you have to use it always remember to specify a host.
A more secure solution is to disable this feature completely by starting X with startx --
-nolisten tcp or disable it permanently in the configuration.
Листинг 17: /usr/X11R6/bin/startx defaultserverargs="-nolisten tcp"
To make sure that startx does not get overwritten when emerging a new version of Xorg you must protect it. Add the following line to /etc/make.conf:
Листинг 18: /etc/make.conf
If you use a graphical login manager you need a different approach.
For gdm (Gnome Display Manager)
Листинг 19: /etc/X11/gdm/gdm.conf
command=/usr/X11R6/bin/X -nolisten tcp
For xdm (X Display Manager) and kdm (Kde Display Manager)

Листинг 20: /etc/X11/xdm/Xservers
:0 local /usr/bin/X11/X -nolisten tcp
11. Подмена корневого каталога и виртуальные серверы
11.a. Chrooting
Chrooting a service is a way of limiting a service (or user) environment to only accessing what it should and not gaining access (or information) that could lead to root access. By running the service as another user than root (nobody, apache, named) an attacker can only access files with the permissions of this user. This means that an attacker cannot gain root access even if the services has a security flaw.
Some services like pure-ftpd and bind have features for chrooting, and other services do not. If the service supports it, use it, otherwise you have to figure out how to create your own. Lets see how to create a chroot, for a basic understanding of how chroots work, we will test it with bash (easy way of learning).
Create the /chroot directory with mkdir /chroot. And find what dynamic libraries that bash is compiled with (if it is compiled with -static this step is not necessary):
The following command will create a list of libraries used by bash.
Листинг 1: Get listing of used libraries
# ldd /bin/bash libncurses.so.5 => /lib/libncurses.so.5 (0x4001b000)
libdl.so.2 => /lib/libdl.so.2 (0x40060000)
libc.so.6 => /lib/libc.so.6 (0x40063000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
Now lets create the environment for bash.
Листинг 2: Create chroot-environment for bash
# mkdir /chroot/bash
# mkdir /chroot/bash/bin
# mkdir /chroot/bash/lib

Next copy the files used by bash (/lib) to the chrooted lib and copy the bash command to the chrooted bin directory. This will create the exact same environment, just with less functionality. After copying try it out: chroot /chroot/bash /bin/bash. If you get an prompt saying / it works! Otherwise it will properly tell you what a file is missing. Some shared libraries depend on each other.
You will notice that inside the chroot nothing works except echo. This is because we have no other commands in out chroot environment than bash and echo is a build-in functionality.
This is basically the same way you would create a chrooted service. The only difference is that services sometimes rely on devices and configuration files in /etc. Simply copy them
(devices can be copied with cp -a) to the chrooted environment, edit the init script to use chroot before executing. It can be difficult to find what devices and configuration files a services need. This is where the strace command becomes handy. Start the service with
/usr/bin/strace bash and look for open, read, stat and maybe connect. This will give you a clue on what files to copy. But in most cases just copy the passwd file (edit the copy and remove users that has nothing to do with the service), /dev/zero, /dev/log and
11.b. User Mode Linux
Another way of creating a more secure environment is by running a virtual machine. A virtual machine, as the name implies, is a process that runs on top of your real operating system providing a hardware and operating system environment that appears to be its own unique machine. The security benefit is that if the server running on the virtual machine is compromised, only the virtual server is affected and not the parent installation.
For more information about how to setup User Mode Linux consult the User Mode Linux
12. Межсетевые экраны
12.a. A firewall
People often think that a firewall provides the ultimate security, but they are wrong. In most cases a misconfigured firewall gives less security than not having one at all. A firewall is also a piece of software and should be treated the same way as any other piece of software, because it is just as likely to contain bugs.
So think before implementing a firewall! Do you really need one? If you think you need one write a policy on how it should work, what type of firewall, and who should operate it. But first read this guide.
Firewalls are used for two purposes:
To keep users (worms/attackers) out

To keep users (employees/children) in
Basically there are three types of firewalls:
Packet filtering
Circuit relay
Application gateway
A firewall should be a dedicated machine running no services (or sshd as the only one) and secured the way this guide recommends it be.
12.b. Packet filtering
All network traffic is sent in the form of packets. Large amounts of traffic is split up into small packets for easy handling and then reassembled when it arrives at its destination. In the packet header every packet contains information on how and where it should be delivered. And this information is exactly what a packing filtering firewall uses. Filtering is based on:
Allow or disallow packets based on source/destination IP address
Allow or disallow packets based on source/destination port
Allow or disallow packets based on protocol
Allow or disallow packets based on flags within a specific protocol
In other words, this filtering is based on all the data within the header of a packet and not its content.
Address information in a packet can potentially be a bogus IP address (or as we say spoofed by the sender).
Data or requests within the allowed packet may contain unwanted data that the attacker can use to exploit known bugs in the services on or behind the firewall
Usually single point of failure
Simple and easy to implement
Can give warnings of a possible attack before it happens (ie. by detecting port scans)
Good for stopping SYN attacks
Examples of free packet filters on Linux:

Примечание: It is recommended that you use iptables. Ipchains is obsoleted.
12.c. Circuit relay
A circuit level gateway is a firewall that validates connections before allowing data to be exchanged. This means that it does not simply allow or deny packets based on the packet header but determines whether the connection between both ends is valid according to configurable rules before it opens a session and allows data to be exchanged. Filtering is based on:
Source/destination IP address
Source/destination port
A period of time
All traffic is validated and monitored, and unwanted traffic can be dropped.
Operates at the Transport Layer and may require substantial modification of the programs that normally provide transport functions.
12.d. Application gateway
The application level gateway is a proxy for applications, exchanging data with remote systems on behalf of the clients. It is kept away from the public safely behind a DMZ (De-
Militarized Zone: the portion of a private network that is visible through the firewall) or a firewall allowing no connections from the outside. Filtering is based on:
Allow or disallow based on source/destination IP address
Based on the packet's content
Limiting file access based on file type or extension
Can cache files, increasing network performance
Detailed logging of all connections
Scales well (some proxy servers can "share" the cached data)
No direct access from the outside
Can even alter the packet content on the fly

Configuration is complex
Application gateways are considered to be the most secure solution since they do not have to run as root and the hosts behind them are not reachable from the Internet.
Example of a free application gateway:
12.e. Iptables
In order to use iptables, it must be enabled in the kernel. I have added iptables as modules
(the iptables command will load them as they are needed) and recompiled my kernel (but you may want to compile iptables in, if you intend to disable Loadable Kernel Modules as discussed previously). For more information on how to configure your kernel for iptables go to the Iptables Tutorial Chapter 5: Preparations. After you have compiled your new kernel (or while compiling the kernel), you must add the iptables command. Just emerge iptables and it should work.
Now test that it works by running iptables -L. If this fails something is wrong and you have to check you configuration once more.
Iptables is the new and heavily improved packet filter in the Linux 2.4.x kernel. It is the successor of the previous ipchains packet filter in the Linux 2.2.x kernel. One of the major improvements is that iptables is able to perform stateful packet filtering. With stateful packet filtering it is possible to keep track of each established TCP connection.
A TCP connection consists of a series of packets containing information about source IP address, destination IP address, source port, destination port, and a sequence number so the packets can be reassembled without losing data. TCP is a connection-oriented protocol, in contrast to UDP, which is connectionless.
By examining the TCP packet header, a stateful packet filter can determine if a received
TCP packet is part of an already established connection or not and decide either to accept or drop the packet.
With a stateless packet filter it is possible to fool the packet filter into accepting packets that should be dropped by manipulating the TCP packet headers. This could be done by manipulating the SYN flag or other flags in the TCP header to make a malicious packet appear to be a part of an established connection (since the packet filter itself does not do connection tracking). With stateful packet filtering it is possible to drop such packets, as they are not part of an already established connection. This will also stop the possibility of
"stealth scans", a type of port scan in which the scanner sends packets with flags that are
far less likely to be logged by a firewall than ordinary SYN packets.
Iptables provides several other features like NAT (Network Address Translation) and rate limiting. Rate limiting is extremely useful when trying to prevent certain DoS (Denial of
Service) attacks like SYN floods.
A TCP connection is established by a so called three-way handshake. When establishing a TCP connection the client-side sends a packet to the server with the SYN flag set. When the server-side receives the SYN packet it responds by sending a SYN+ACK packet back to the client-side. When the SYN+ACK is received the client-side responds with a third
ACK packet in effect acknowledging the connection.
A SYN flood attack is performed by sending the SYN packet but failing to respond to the
SYN+ACK packet. The client-side can forge a packet with a fake source IP address because it does not need a reply. The server-side system will add an entry to a queue of half-open connections when it receives the SYN packet and then wait for the final ACK packet before deleting the entry from the queue. The queue has a limited number of slots and if all the slots are filled it is unable to open any further connections. If the ACK packet is not received before a specified timeout period the entry will automatically be deleted from the queue. The timeout settings vary but will typically be 30-60 seconds or even more. The client-side initiates the attack by forging a lot of SYN packets with different source IP addresses and sends them to the target IP address as fast as possible and thereby filling up the queue of half-open connections and thus preventing other clients from establishing a legitimate connection with the server.
This is where the rate limit becomes handy. It is possible to limit the rate of accepted SYN packets by using the -m limit --limit 1/s. This will limit the number of SYN packets accepted to one per second and therefore restricting the SYN flood on our resources.
Примечание: Another option for preventing SYN floods are SYN cookies, which allow your computer to respond to SYN packets without filling space in the connection queue.
SYN cookies can be enabled in the Linux kernel configuration, but they are considered experimental at this time.
Now some practical stuff!
When iptables is loaded in the kernel it has 5 hooks where you can place your rules. They are called INPUT, OUTPUT, FORWARD, PREROUTING and POSTROUTING. Each of these is called a chain and consists of a list of rules. Each rule says if the packet header looks like this, then here is what to do with the packet. If the rule does not match the packet the next rule in the chain is consulted.
You can place rules directly in the 5 main chains or create new chains and add them to as a rule to an existing chain. Iptables supports the following options. Option:

Delete all rules in chain or all chains
Zero counters in chain or all chains
Test this packet on chain
Create a new user-defined chain
Delete a user-defined chain
Change policy on chain to target
Change chain name
Source address/mask
Destination address/mask
Input name (Ethernet name)
Output name (Ethernet name)
Jump (target for rule)
Extended match (might use extension)
Numeric output of addresses and ports
Table to manipulate
Verbose mode
Expand numbers (display exact values)
Match second or further fragments only
Packet version
Print line numbers when listing
First we will try to block all ICMP packets to our machine, just to get familiar with iptables.
Листинг 1: Block all ICMP packets
# iptables -A INPUT -p icmp -j DROP
First we specify the chain our rule should be appended to, then the protocol of the packets to match, and finally the target. The target can be the name of a user specified chain or one of the special targets ACCEPT, DROP, REJECT, LOG, QUEUE, or MASQUERADE.
In this case we use DROP, which will drop the packet without responding to the client.
Примечание: The LOG target is what's known as "non-terminating". If a packet matches a rule with the LOG target, rather than halting evaluation, the packet will continue to be
matched to further rules. This allows you to log packets while still processing them normally.
Now try ping localhost. You will not get any response, since iptables will drop all incoming
ICMP messages. You will also not be able to ping other machines, since the ICMP reply packet will be dropped as well. Now flush the chain to get ICMP flowing again.
Листинг 2: Flush all rules
# iptables -F
Now lets look at the stateful packet filtering in iptables. If we wanted to enable stateful inspection of packets incoming on eth0 we would issue the command:
Листинг 3: Accept packets that originate from an already established connection
# iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
This will accept any packet from an already established connection or related in the INPUT chain. And you could drop any packet that is not in the state table by issuing iptables -A
INPUT -i eth0 -m state --state INVALID -j DROP just before the previous command. This enables the stateful packet filtering in iptables by loading the extension "state". If you wanted to allow others to connect to your machine, you could use the flag --state NEW.
Iptables contains some modules for different purposes. Some of them are: Module/Match
Description Extended options mac Matching extension for incoming packets mac address.
--mac-source state Enables stateful inspection
--state (states are ESTABLISHED,RELATED,
Rate matching limiting
--limit, --limit-burst owner Attempt to match various characteristics of the packet creator
--uid-owner userid --gid-owner groupid --pid-owner processid --sid-owner sessionid unclean
Various random sanity checks on packets
Lets try to create a user-defined chain and apply it to one of the existing chains:
Листинг 4: Creating a user defined chain
(Create a new chain with one rule)
# iptables -X mychain
# iptables -N mychain

# iptables -A mychain -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
(The default policy is all outgoing traffic is allowed. Incoming is dropped.)
# iptables -P OUTPUT ACCEPT
# iptables -P INPUT DROP
(And add it to the INPUT chain)
# iptables -A INPUT -j mychain
By applying the rule to the input chain we get the policy: All outgoing packets are allowed and all incoming packets are dropped.
One can find documentation at Netfilter/iptables documentation.
Lets see a full blown example. In this case my firewall/gateway policy states:
Connections to the firewall are only allowed through SSH (port 22)
The local network should have access to HTTP, HTTPS and SSH (DNS should also be allowed)
ICMP traffic can contain payload and should not be allowed. Of course we have to allow some ICMP traffic.
Port scans should be detected and logged
SYN attacks should be avoided
All other traffic should be dropped and logged
Листинг 5: /etc/init.d/firewall
opts="${opts} showstatus panic save restore showoptions rules"
depend() {
need net
rules() {
stop ebegin "Setting internal rules"
einfo "Setting default rule to drop"
#default rule einfo "Creating states chain"
$IPTABLES -N allowed-connection
$IPTABLES -F allowed-connection
$IPTABLES -A allowed-connection -m state --state ESTABLISHED,RELATED -j
$IPTABLES -A allowed-connection -i $IINTERFACE -m limit -j LOG --log-prefix \
"Bad packet from ${IINTERFACE}:"
$IPTABLES -A allowed-connection -j DROP
#ICMP traffic einfo "Creating icmp chain"
$IPTABLES -N icmp_allowed
$IPTABLES -F icmp_allowed
$IPTABLES -A icmp_allowed -m state --state NEW -p icmp --icmp-type \
time-exceeded -j ACCEPT
$IPTABLES -A icmp_allowed -m state --state NEW -p icmp --icmp-type \
destination-unreachable -j ACCEPT
$IPTABLES -A icmp_allowed -p icmp -j LOG --log-prefix "Bad ICMP traffic:"
$IPTABLES -A icmp_allowed -p icmp -j DROP
#Incoming traffic
einfo "Creating incoming ssh traffic chain"
$IPTABLES -N allow-ssh-traffic-in
$IPTABLES -F allow-ssh-traffic-in
#Flood protection
$IPTABLES -A allow-ssh-traffic-in -m limit --limit 1/second -p tcp --tcp-flags \
ALL RST --dport ssh -j ACCEPT
$IPTABLES -A allow-ssh-traffic-in -m limit --limit 1/second -p tcp --tcp-flags \
ALL FIN --dport ssh -j ACCEPT
$IPTABLES -A allow-ssh-traffic-in -m limit --limit 1/second -p tcp --tcp-flags \
ALL SYN --dport ssh -j ACCEPT
$IPTABLES -A allow-ssh-traffic-in -m state --state RELATED,ESTABLISHED -p tcp -- dport ssh -j ACCEPT
#outgoing traffic einfo "Creating outgoing ssh traffic chain"
$IPTABLES -N allow-ssh-traffic-out
$IPTABLES -F allow-ssh-traffic-out
$IPTABLES -A allow-ssh-traffic-out -p tcp --dport ssh -j ACCEPT
einfo "Creating outgoing dns traffic chain"
$IPTABLES -N allow-dns-traffic-out
$IPTABLES -F allow-dns-traffic-out
$IPTABLES -A allow-dns-traffic-out -p udp -d $DNS1 --dport domain \
$IPTABLES -A allow-dns-traffic-out -p udp -d $DNS2 --dport domain \
einfo "Creating outgoing http/https traffic chain"
$IPTABLES -N allow-www-traffic-out
$IPTABLES -F allow-www-traffic-out
$IPTABLES -A allow-www-traffic-out -p tcp --dport www -j ACCEPT
$IPTABLES -A allow-www-traffic-out -p tcp --dport https -j ACCEPT
#Catch portscanners einfo "Creating portscan detection chain"
$IPTABLES -N check-flags
$IPTABLES -F check-flags
$IPTABLES -A check-flags -p tcp --tcp-flags ALL FIN,URG,PSH -m limit \

--limit 5/minute -j LOG --log-level alert --log-prefix "NMAP-XMAS:"
$IPTABLES -A check-flags -p tcp --tcp-flags ALL FIN,URG,PSH -j DROP
$IPTABLES -A check-flags -p tcp --tcp-flags ALL ALL -m limit --limit \
5/minute -j LOG --log-level 1 --log-prefix "XMAS:"
$IPTABLES -A check-flags -p tcp --tcp-flags ALL ALL -j DROP
$IPTABLES -A check-flags -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG \
-m limit --limit 5/minute -j LOG --log-level 1 --log-prefix "XMAS-PSH:"
$IPTABLES -A check-flags -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP
$IPTABLES -A check-flags -p tcp --tcp-flags ALL NONE -m limit \
--limit 5/minute -j LOG --log-level 1 --log-prefix "NULL_SCAN:"
$IPTABLES -A check-flags -p tcp --tcp-flags ALL NONE -j DROP
$IPTABLES -A check-flags -p tcp --tcp-flags SYN,RST SYN,RST -m limit \
--limit 5/minute -j LOG --log-level 5 --log-prefix "SYN/RST:"
$IPTABLES -A check-flags -p tcp --tcp-flags SYN,RST SYN,RST -j DROP
$IPTABLES -A check-flags -p tcp --tcp-flags SYN,FIN SYN,FIN -m limit \
--limit 5/minute -j LOG --log-level 5 --log-prefix "SYN/FIN:"
$IPTABLES -A check-flags -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP
# Apply and add invalid states to the chains einfo "Applying chains to INPUT"
$IPTABLES -A INPUT -m state --state INVALID -j DROP
$IPTABLES -A INPUT -p icmp -j icmp_allowed
$IPTABLES -A INPUT -j check-flags
$IPTABLES -A INPUT -j allow-ssh-traffic-in
$IPTABLES -A INPUT -j allowed-connection einfo "Applying chains to FORWARD"
$IPTABLES -A FORWARD -p icmp -j icmp_allowed
$IPTABLES -A FORWARD -j check-flags
$IPTABLES -A FORWARD -j allow-ssh-traffic-in
$IPTABLES -A FORWARD -j allow-www-traffic-out
$IPTABLES -A FORWARD -j allowed-connection einfo "Applying chains to OUTPUT"

$IPTABLES -A OUTPUT -m state --state INVALID -j DROP
$IPTABLES -A OUTPUT -p icmp -j icmp_allowed
$IPTABLES -A OUTPUT -j check-flags
$IPTABLES -A OUTPUT -j allow-ssh-traffic-out
$IPTABLES -A OUTPUT -j allow-dns-traffic-out
$IPTABLES -A OUTPUT -j allow-www-traffic-out
$IPTABLES -A OUTPUT -j allowed-connection
#Allow client to route through via NAT (Network Address Translation)
eend $?
start() {
ebegin "Starting firewall"
if [ -e "${FIREWALL}" ]; then restore else einfo "${FIREWALL} does not exists. Using default rules."
rules fi eend $?
stop() {
ebegin "Stopping firewall"
$IPTABLES -t nat -F
eend $?
showstatus() {
ebegin "Status"
$IPTABLES -L -n -v --line-numbers einfo "NAT status"
$IPTABLES -L -n -v --line-numbers -t nat eend $?
panic() {
ebegin "Setting panic rules"
$IPTABLES -t nat -F
eend $?
save() {
ebegin "Saving Firewall rules"
eend $?
restore() {
ebegin "Restoring Firewall rules"
eend $?
restart() {
svc_stop; svc_start
showoptions() {
echo "Usage: $0 {start|save|restore|panic|stop|restart|showstatus}"
echo "start) will restore setting if exists else force rules"
echo "stop) delete all rules and set all to accept"
echo "rules) force settings of new rules"
echo "save) will store settings in ${FIREWALL}"
echo "restore) will restore settings from ${FIREWALL}"
echo "showstatus) Shows the status"
Some advice when creating a firewall:
Create your firewall policy before implementing it
Keep it simple
Know how each protocol works (read the relevant RFC(Request For Comments))
Keep in mind that a firewall is just another piece of software running as root.
Test your firewall
If you think that iptables is hard to understand or takes to long to setup a decent firewall you could use Shorewall. It basically uses iptables to generate firewall rules, but concentrates on rules and not specific protocols.
12.f. Squid
Squid is a very powerful proxy server. It can filter traffic based on time, regular expressions on path/URI, source and destination IP addresses, domain, browser, authenticated user name, MIME type, and port number (protocol). I probably forgot some features, but it can be hard to cover the entire list right here.
In the following example I have added a banner filter instead of a filter based on porn sites.
The reason for this is that Gentoo.org should not be listed as some porn site. And I do not want to waste my time trying to find some good sites for you.
In this case, my policy states:
Surfing (HTTP/HTTPS) is allowed during work hours (mon-fri 8-17 and sat 8-13), but if employees are here late they should work, not surf
Downloading files is not allowed (.exe, .com, .arj, .zip, .asf, .avi, .mpg, .mpeg, etc)
We do not like banners, so they are filtered and replaced with a transparent gif (this is where you get creative!).
All other connections to and from the Internet are denied.

This is implemented in 4 easy steps.
Листинг 6: /etc/squid/squid.conf
# Bind to a ip and port http_port
# Standard configuration hierarchy_stoplist cgi-bin ?
acl QUERY urlpath_regex cgi-bin \?
no_cache deny QUERY
# Add basic access control lists acl all src
acl manager proto cache_object acl localhost src
# Add who can access this proxy server acl localnet src
# And ports acl SSL_ports port 443
acl Safe_ports port 80
acl Safe_ports port 443
acl purge method PURGE
# Add access control list based on regular
# expressions within urls acl archives urlpath_regex "/etc/squid/files.acl"
acl url_ads url_regex "/etc/squid/banner-ads.acl"
# Add access control list based on time and day acl restricted_weekdays time MTWHF 8:00-17:00
acl restricted_weekends time A 8:00-13:00
#allow manager access from localhost
http_access allow manager localhost http_access deny manager
# Only allow purge requests from localhost http_access allow purge localhost http_access deny purge
# Deny requests to unknown ports http_access deny !Safe_ports
# Deny CONNECT to other than SSL ports http_access deny CONNECT !SSL_ports
# My own rules
# Add a page do be displayed when
# a banner is removed deny_info NOTE_ADS_FILTERED url_ads
# Then deny them http_access deny url_ads
# Deny all archives http_access deny archives
# Restrict access to work hours http_access allow localnet restricted_weekdays http_access allow localnet restricted_weekends
# Deny the rest http_access deny all
Next fill in the files you do not want your users to download files. I have added zip, viv, exe, mp3, rar, ace, avi, mov, mpg, mpeg, au, ra, arj, tar, gz and z files.
Листинг 7: /etc/squid/files.acl

Примечание: Please note the [] with upper and lowercase of every character. This is done so no one can fool our filter by accessing a file called AvI instead of avi.
Next we add the regular expressions for identifying banners. You will probably be a lot more creative than I:
Листинг 8: /etc/squid/banner-ads.acl

And as the last part we want this file to be displayed when a banner is removed. It is basically a half html file with a 4x4 transparent gif image.
Листинг 9: /etc/squid/errors/NOTE_ADS_FILTERED

ERROR: The requested URL could not be retrieved

Каталог: pub -> docs books -> Linux -> Linux 2
pub -> Буланов С. В. Кудрявцева Е. Л. Развитие креативности билингвов: путь от интеркультурности к формированию «человека мира»
pub -> «октябрьский лицей»
pub -> Самообследование гоу сош «Школа надомного обучения» №196 по направлениям деятельности. Общие вопросы
pub -> Занятие для математического кружка. Задачи работы
pub -> Доклад муниципальное образовательное
pub -> Публичный доклад. 2013 год Общая характеристика образовательного учреждения. Место расположения
pub -> Публичный доклад муниципального общеобразовательного учреждения средней общеобразовательной школы №13

Поделитесь с Вашими друзьями:
1   ...   26   27   28   29   30   31   32   33   ...   50

База данных защищена авторским правом ©nethash.ru 2019
обратиться к администрации

войти | регистрация
    Главная страница

загрузить материал