14.3 Rendere sicuro FreeBSD

Comandi o Protocolli: In questo documento useremo testo grassetto per riferirci ad applicazioni e testo a spaziatura fissa per riferirci a specifici comandi. I protocolli useranno un font normale. Questa distinzione tipografica è utile per casi come ssh, che è un protocollo oltre che un comando.

Le sezioni seguenti descrivono i metodi per rendere sicuro il vostro sistema FreeBSD che sono stati menzionati nella sezione precedente di questo capitolo.

14.3.1 Rendere sicuro root e gli account dello staff.

Innanzitutto, non preoccuparti di rendere sicuri gli account di staff se non hai reso sicuro l'account root. La maggior parte dei sistemi hanno una password assegnata per l'account root. La prima cosa che devi dare per assunta è che la password è sempre compromessa. Questo non significa che devi togliere la password; la password è quasi sempre necessaria per l'accesso dalla console della macchina. Quello che questo significa è che non dovresti render possibile l'uso di questa password tranne che da console e possibilmente neanche dal comando su(1). Per esempio, assicurati che le tue pty siano specificate come insecure nel file /etc/ttys in modo che accessi diretti root tramite telnet o rlogin non siano permessi. Se usi altri servizi di login come ad esempio sshd, fai in modo che accessi diretti come root siano vietati anche per questi. Puoi farlo modificando il file /etc/ssh/sshd_config e assicurandoti che PermitRootLogin sia impostato a NO. Tieni conto di tutti i modi di accesso — servizi come ad esempio FTP vengono spesso trascurati. Login root diretti dovrebbero essere permessi solo tramite la console di sistema.

Ovviamente, come sysadmin (amministratore di sistema) hai bisogno di accesso a root, quindi apriremo alcuni passaggi; ci assicureremo però che questi passaggi richiedano ulteriori verifiche di password per funzionare. Un modo per accedere a root è aggiungere gli appropriati account di staff al gruppo wheel (in /etc/group). I membri del gruppo wheel possono accedere a root tramite su. Non dovresti mai dare ai membri dello staff accesso nativo al gruppo wheel mettendoli in quel gruppo nel file /etc/passwd; dovresti metterli nel gruppo staff e quindi aggiungerli al gruppo wheel tramite il file /etc/group. Solo i membri dello staff che hanno effettivo bisogno di accesso a root dovrebbero essere nel gruppo wheel group. Altra possibilità, quando si utilizzi Kerberos come metodo di autenticazione, ` quella di utilizzare il file .k5login dell'account root in modo da permettere l'accesso a root tramite ksu(1) senza bisogno di mettere nessuno nel gruppo wheel. Questa potrebbe essere la soluzione migliore dato che il meccanismo wheel permette all'attaccante di diventare root se è riuscito ad ottenere accesso ad un account di staff. Benché il meccanismo wheel sia meglio di niente, non è necessariamente la soluzione più sicura.

Un metodo indiretto per rendere sicuri gli account di staff e quindi l'accesso a root è quello di eseguire l'operazione nota come “starring” delle password cifrate. password for the staff accounts: utilizzando il comando vipw(8) si può rimpiazzare ogni password cifrata con un singolo carattere “*” (asterisco, in inglese “star”). Questo comando aggiorna il file /etc/master.passwd e il database utenti/password in modo da disabilitare i login autenticati da password.

Un account di staff come il seguente:

foobar:R9DT/Fa1/LV9U:1000:1000::0:0:Foo Bar:/home/foobar:/usr/local/bin/tcsh

Andrebbe modificato così:

foobar:*:1000:1000::0:0:Foo Bar:/home/foobar:/usr/local/bin/tcsh

Questo previene i normali login dato che la password cifrata non sarà mai “*”. Fatto questo i membri dello staff dovranno utilizzare un diverso meccanismo di autenticazione come ad esempio kerberos(1) o ssh(1) utilizzando una coppia di chiavi pubblica/privata. Utilizzando Kerberos bisogna generalmente rendere sicure sia le macchine su cui viene eseguito il server Kerberos che la propria workstation. Utilizzando una coppia di chiavi bisogna in generale rendere sicura la macchina da cui ci si sta collegando (in genere la propria workstation); si può aggiungere un ulteriore strato di protezione proteggendo la coppia di chiavi con una password all'atto della creazione con ssh-keygen(1). Eseguire lo “starring” degli account dello staff garantisce che questi possano eseguire il login solo tramite i metodi di accesso sicuri che sono stati configutati. Quest forze l'intero staff all'uso di connessioni sicure e cifrate in tutte le loro sessioni, chiudendo un importante falla di sicurezza utilizzata da molti attaccanti: ascoltare il traffico di rete da un'altra macchina meno sicura.

I meccanismi di sicurezza più indiretti assumono anche che ci si colleghi da un server più restrittivo a uno che lo è di meno; per esempio se il tuo server primario ha in esecuzione una grande varietà di servizi, la tua workstation non dovrebbe averne in esecuzione nessuno. Per fare in modo che la tua workstation sia ragionevolmente sicura dovresti eseguire meno servizi possibile, o perfino nessuno del tutto, e dovresti utilizzare uno screen saver protetto da password. Ovviamente, avendo accesso fisico alla workstation un attaccante può rompere qualsiasi protezione che tu possa aver importato, ma bisogna sempre considerare che la magior parte degli attacchi avviene remotamente, tramite una rete, da parte di persone che non hanno accesso fisico alle tue workstation o ai tuoi server.

L'uso di sistemi come Kerberos permette di disabilitare o cambiare la pasword ad un account di staff in un solo posto ed avere effeto immediato su tutte le macchine in cui il membro dello staff ha un account. Nel caso l'account di un membro dello staff venga compromesso, la possibilità di poter cambiare la sua password su tutte le macchine non ` cosa di poco conto. Con password separate, cambiare una password su molte macchine può essere un bel problema. Con Kerberos puoi anche imporre restrizioni di cambio password: non solo un ticket Kerberos può essere fatto per scadere dopo un tempo predeterminato, ma il sistema Kerberos può richiedere all'utente di scegliere una nuova passsword dopo un certo periodo di tempo (per esempio, una volta al mese).

14.3.2 Rendere sicuri i server Root e i binari SUID/SGID

Il sysadmin prudente esegue soltanto i server che gli sono necessari, n´ di più né di meno. Bisogna tenere conto del fatto che i server di terze parti sono generalmente i più affetti da bug. Per esempio, utilizzare una versione obsoleta di imapd o popper è equivalente a dare accesso root al mondo intero. Non eseguire mai un server senza controllarlo accuratamente. Molti server non hanno bisogno di essere eseguiti come root. Per esempio i demoni ntalk, comsat e finger possono essere eseguiti in speciali sandbox utente. Difficilmente una sandbox sarà una soluzione completa del problema, a meno di dedicarci parecchio tempo, ma resta valido l'approccio a cipolla alla sicurezza: se qualcuno riesce ad irrompere in un server eseguito in una sandbox, deve ancora riuscire ad evadere da quest'ultima. Più strati l'attaccante deve superare, minore la sua probabilità di successo. Storicamente sono state trovate falle di accesso a root in virtualmente ogni server mai eseguito come root, inclusi i server del sistema base. Se hai una macchina alla quale la gente accede solamente tramite sshd e mai tramite telnetd o rshd o rlogind, allora disattiva questi servizi!

FreeBSD attualmente esegue per default ntalkd, comsat e finger in una sandbox. Un altro programma candidato ad essere eseguito in una sandbox è named(8). /etc/defaults/rc.conf comprende le opzioni necessarie per eseguire named in una sandbox in forma comentata. A seconda se state installando un nuovo sistema o aggiornando un sistema esistente, gli speciali account utente utilizzati da queste sandbox potrebbero non essere presenti. Il sysadmin prudente dovrebbe cercar di utilizzare delle sandbox per i server ogniqualvolta possibile.

Esiste un certo numero di altri servizi che generalmente non vengono eseguiti in una sandbox: sendmail, popper, imapd, ftpd e altri. Ci sono software alternativi ad alcuni di questi ma installarli potrebbe richiedere più lavoro di quello che si intende dedicargli (il fattore convenienza colpisce ancora). Potresti dover eseguire questi servizi come root ed affidarti ad altri meccanismi per individuare le intrusioni che potrebbero essere fatte attraverso questi.

L'altra grande potenziale fonte di falle per l'accesso a root sono i binari suid-root e sgid installati nel sistema, come ad esempio rlogin, nelle directory /bin, /sbin, /usr/bin o /usr/sbin. Benché niente sia sicuro al 100%, i binari suid e sgid presenti nel sistema per default possono essere considerati ragionevolmente sicuri. In ogni caso, delle falle da root sono occasionalmente trovate anche in questi. Nel 1998 è stata trovata una falla da root in Xlib che rendeva vulnerabile xterm (che tipicamente è suid). It is better to be safe than sorry and the prudent sysadmin will restrict suid binaries, that only staff should run, to a special group that only staff can access, and get rid of (chmod 000) any suid binaries that nobody uses. A server with no display generally does not need an xterm binary. Sgid binaries can be almost as dangerous. If an intruder can break an sgid-kmem binary, the intruder might be able to read /dev/kmem and thus read the encrypted password file, potentially compromising any passworded account. Alternatively an intruder who breaks group kmem can monitor keystrokes sent through ptys, including ptys used by users who login through secure methods. An intruder that breaks the tty group can write to almost any user's tty. If a user is running a terminal program or emulator with a keyboard-simulation feature, the intruder can potentially generate a data stream that causes the user's terminal to echo a command, which is then run as that user.

14.3.3 Rendere sicuri gli account utente

Gli account utente sono generalmente i più difficili da rendere sicuri. Bench*eacute; tu possa imporre restrizioni d'accesso allo staff ed eseguire lo “starring” delle loro password, potresti non poter farlo con l'account di un generico utente. Se hai sufficiente controllo potesti farcela e rendere gli account utente sufficientemente sicuri, altrimenti dovrai essere più vigile nel controllo di questi account. L'uso di ssh e Kerberos per gli account utente è più problematico, a causa del maggiore supporto amministrativo e tecnico richiesto, ma è sempre un'ottima soluzione se confrontata all'uso di un file password cifrato.

14.3.4 Rendere sicuro il file password

L'unica strada sicura è quella di eseguire lo starring so più password possibile e utilizzare ssh o Kerberos per accedere a quegli account. Anche se il file di password cifrato (/etc/spwd.db) può essere letto solo da root, potrebbe essere possibile per un attaccante ottenere accesso in lettura a quel file anche senza aver ottenuto accesso in scrittura.

I tuoi script di sicurezza dovrebbero sempre verificare che il file password non venga modificato e in caso riportarlo ad un amministratore (cfr. la sezione Verifica dell'integrità dei file sottostante).

14.3.5 Rendere sicuri il kernel, i raw device e i file system

Quando un attaccante irrompe nell'account di root può fare qualsiasi cosa, ma alcune cose sono più comode di altre. Per esempio, la maggior parte dei kernel moderni comprende un device per l'ascolto dei pacchetti di rete. In FreeBSD questo device si chiama bpf. Un intrusore generalmente cercherà di ascoltare i pacchetti delle reti a cui la macchina compromessa è collegata. Non ò obbligatorio dare all'intrusore questa possibilità e d'altro canto la maggior parte dei sistemi non ha bisogno di avere il device bpf.

Anche nel caso di aver disattivato il device bpf, bisogna comunque preoccuparsi di /dev/mem e /dev/kmem; tra l'altro l'intrusore ha anche la possibilità di scrivere sui device disco raw o utilizzare il comando di caricamento moduli del kernel, kldload(8). Un intrusore intraprendente può utilizzare un proprio modulo del kernel per l'ascolto dei pacchetti e caricarlo su un kernel in esecuzione. Per evitare questi problemi bisogna eseguire il kernel ad un livello di sicurezza più alto, almeno al livello 1. Il livello di sicurezza può essere impostato con sysctl modificando la variabile kern.securelevel. Se il livello di sicurezza è impostato ad 1, l'accesso in scrittura ai device raw sarà negato e alcuni chflags speciali, come ad esempio schg, verranno verificati. Devi anche verificare che il flag schg sia impostato sui binari, cartelle e script utilizzati all'avvio prima dell'impostazione del livello di sicurezza. L'uso di un livello di sicurezza superiore potrebbe essere una misura eccesiva, dato che rende l aggiornamento del sistema molto più complesso. You may compromise and run the system at a higher secure level but not set the schg flag for every system file and directory under the sun. Another possibility is to simply mount / and /usr read-only. It should be noted that being too draconian in what you attempt to protect may prevent the all-important detection of an intrusion.

14.3.6 Verifica dell'integrità dei file: binari, file di configurazione, etc.

TODO:When it comes right down to it, you can only protect your core system configuration and control files so much before the convenience factor rears its ugly head. For example, using chflags to set the schg bit on most of the files in / and /usr is probably counterproductive, because while it may protect the files, it also closes a detection window. The last layer of your security onion is perhaps the most important — detection. The rest of your security is pretty much useless (or, worse, presents you with a false sense of security) if you cannot detect potential intrusions. Half the job of the onion is to slow down the attacker, rather than stop him, in order to be able to catch him in the act.

The best way to detect an intrusion is to look for modified, missing, or unexpected files. The best way to look for modified files is from another (often centralized) limited-access system. Writing your security scripts on the extra-secure limited-access system makes them mostly invisible to potential attackers, and this is important. In order to take maximum advantage you generally have to give the limited-access box significant access to the other machines in the business, usually either by doing a read-only NFS export of the other machines to the limited-access box, or by setting up ssh key-pairs to allow the limited-access box to ssh to the other machines. Except for its network traffic, NFS is the least visible method — allowing you to monitor the file systems on each client box virtually undetected. If your limited-access server is connected to the client boxes through a switch, the NFS method is often the better choice. If your limited-access server is connected to the client boxes through a hub, or through several layers of routing, the NFS method may be too insecure (network-wise) and using ssh may be the better choice even with the audit-trail tracks that ssh lays.

Once you have given a limited-access box at least read access to the client systems it is supposed to monitor, you must write scripts to do the actual monitoring. Given an NFS mount, you can write scripts out of simple system utilities such as find(1) and md5(1). It is best to physically md5 the client-box files at least once a day, and to test control files such as those found in /etc and /usr/local/etc even more often. When mismatches are found, relative to the base md5 information the limited-access machine knows is valid, it should scream at a sysadmin to go check it out. A good security script will also check for inappropriate suid binaries and for new or deleted files on system partitions such as / and /usr.

When using ssh rather than NFS, writing the security script is much more difficult. You essentially have to scp the scripts to the client box in order to run them, making them visible, and for safety you also need to scp the binaries (such as find) that those scripts use. The ssh client on the client box may already be compromised. All in all, using ssh may be necessary when running over insecure links, but it is also a lot harder to deal with.

A good security script will also check for changes to user and staff members access configuration files: .rhosts, .shosts, .ssh/authorized_keys and so forth, files that might fall outside the purview of the MD5 check.

If you have a huge amount of user disk space, it may take too long to run through every file on those partitions. In this case, setting mount flags to disallow suid binaries and devices on those partitions is a good idea. The nodev and nosuid options (see mount(8)) are what you want to look into. You should probably scan them anyway, at least once a week, since the object of this layer is to detect a break-in attempt, whether or not the attempt succeeds.

Process accounting (see accton(8)) is a relatively low-overhead feature of the operating system which might help as a post-break-in evaluation mechanism. It is especially useful in tracking down how an intruder has actually broken into a system, assuming the file is still intact after the break-in has occured.

Finally, security scripts should process the log files, and the logs themselves should be generated in as secure a manner as possible — remote syslog can be very useful. An intruder will try to cover his tracks, and log files are critical to the sysadmin trying to track down the time and method of the initial break-in. One way to keep a permanent record of the log files is to run the system console to a serial port and collect the information to a secure machine monitoring the consoles.

14.3.7 Paranoia

Un po' di paranoia non fa mai male. Come regola, un sysadmin può aggiungere qualsiasi feature di sicurezza fintantoché non impattano la comodità e può aggiungerne altre che la impattano, ma solo dopo averci pensato bene. Even more importantly, a security administrator should mix it up a bit — if you use recommendations such as those given by this document verbatim, you give away your methodologies to the prospective attacker who also has access to this document.

14.3.8 Attacchi Denial of Service

Questa sezione parla degli attacchi Denial of Service, ovvero quelli atti ad interrompere i servizi in esecuzione su una macchina. Tipicamente un attacco DoS è un attacco a pacchetto; benché non si possa fare molto riguardo ad un attacco moderno che satura la vostra rete con pacchetti , si può cercare di limitare il danno assicurandosi che l'attacco non blocchi i vostri servizi, utilizzando le seguenti tecniche:

  1. Limitare le fork dei server.

  2. TODO:Limiting springboard attacks (ICMP response attacks, ping broadcast, etc.).

  3. Sovraccaricare la Kernel Route Cache.

Un comune scenario è l'attacco di un server che fa fork e fargli creare così tanti processi figli da esaurire le risorse della macchina, come ad esempio la memoria, i file descriptor o altri e costringerlo quindi a fermarsi. inetd (cfr. inetd(8)) ha molte opzioni per limitare questo tipo di attacchi. Si deve notare che benché sia possibile evitare che la macchina si fermi, non è generalmente possibile evitare che i servizi vengano resi non disponibili dall'attacco. Leggete attentamente la pagina del manuale di inetd, con particolare attenzione alle opzioni -c, -C e -R. Un attacco con IP aggira l'opzione -C quindi è bene utilizzare una combinazione di opzioni. Alcuni server indipendenti hanno meccanismi interni per la limitazione delle fork.

Sendmail ha l'opzione -OMaxDaemonChildren che generalmente funziona molto meglio che cercare di utilizzare le funzioni di limitazione basate sul carico della macchina, a causa del ritardo di aggiornamento del valore di carico. Quando lanci sendmail dovresti specificare un parametro MaxDaemonChildren abbastanza alto da gestire il carico previsto , ma non così alto da non essere gestibile dal computer. È anche prudente eseguire Sendmail in modalità queued (-ODeliveryMode=queued) ed eseguire il demone (sendmail -bd) separatamente dalla gestione code (sendmail -q15m). Se vuoi che i messaggi vengano consegnati in tempo reale puoi utilizzare un intervallo molto più breve, come ad esempio -q1m, ma assicurati di utilizzare un valore MaxDaemonChildren adatto per quel Sendmail, in modo da prevenire problemi a catena.

Syslogd può essere attaccato direttamente ed è fortemente consigliato l'uso dell'opzione -s quando possibile, o al limite l'opzione -a.

You should also be fairly careful with connect-back services such as TCP Wrapper's reverse-identd, which can be attacked directly. You generally do not want to use the reverse-ident feature of TCP Wrapper for this reason.

È un'ottima idea quella di proteggere i servizi interni dall'accesso esterno chiudendoli tramite regole del firewall ai bordi della vostra rete. L'idea è di prevenire gli attacchi a saturazione provenienti dall'esterno della vostra rete, non tanto di proteggere i servizi da attacchi di rete atti a compromettere root. Utilizza sempre un firewall , ovvero “blocca tutto tranne le porte A, B, C, D e M-Z”; puoi bloccare tutte le porte basse ad eccezione di specifici servizi quali named (se sei primario per una zona), ntalkd, sendmail e altri servizi accessibili da Internet. Se tu cercassi di configurare il firewall in maniera opposta (inclusivo o permissivo) c'è una buona probabilità che tu ti scordi di “chiudere” qualche servizio o che tu aggiunga un nuovo servizio interno e dimentichi di aggiornare il firewall. Puoi comunque lasciare aperte tutte le porte , permettendo un uso permissivo, senza però compromettere le porte . Nota anche che FreeBSD ti permette di controllare l'intervallo di porte utilizzate per il binding dinamico tramite vari sysctl net.inet.ip.portrange (sysctl -a | fgrep portrange), che possono semplificare la complessità di configurazione del tuo firewall.

Another common DoS attack is called a springboard attack — to attack a server in a manner that causes the server to generate responses which overloads the server, the local network, or some other machine. The most common attack of this nature is the ICMP ping broadcast attack. The attacker spoofs ping packets sent to your LAN's broadcast address with the source IP address set to the actual machine they wish to attack. If your border routers are not configured to stomp on ping packets to broadcast addresses, your LAN winds up generating sufficient responses to the spoofed source address to saturate the victim, especially when the attacker uses the same trick on several dozen broadcast addresses over several dozen different networks at once. Broadcast attacks of over a hundred and twenty megabits have been measured. A second common springboard attack is against the ICMP error reporting system. By constructing packets that generate ICMP error responses, an attacker can saturate a server's incoming network and cause the server to saturate its outgoing network with ICMP responses. This type of attack can also crash the server by running it out of memory, especially if the server cannot drain the ICMP responses it generates fast enough. Use the sysctl variable net.inet.icmp.icmplim to limit these attacks. The last major class of springboard attacks is related to certain internal inetd services such as the udp echo service. An attacker simply spoofs a UDP packet with the source address being server A's echo port, and the destination address being server B's echo port, where server A and B are both on your LAN. The two servers then bounce this one packet back and forth between each other. The attacker can overload both servers and their LANs simply by injecting a few packets in this manner. Similar problems exist with the internal chargen port. A competent sysadmin will turn off all of these inetd-internal test services.

Spoofed packet attacks may also be used to overload the kernel route cache. Refer to the net.inet.ip.rtexpire, rtminexpire, and rtmaxcache sysctl parameters. A spoofed packet attack that uses a random source IP will cause the kernel to generate a temporary cached route in the route table, viewable with netstat -rna | fgrep W3. These routes typically timeout in 1600 seconds or so. If the kernel detects that the cached route table has gotten too big it will dynamically reduce the rtexpire but will never decrease it to less than rtminexpire. There are two problems:

  1. The kernel does not react quickly enough when a lightly loaded server is suddenly attacked.

  2. The rtminexpire is not low enough for the kernel to survive a sustained attack.

If your servers are connected to the Internet via a T3 or better, it may be prudent to manually override both rtexpire and rtminexpire via sysctl(8). Never set either parameter to zero (unless you want to crash the machine). Setting both parameters to 2 seconds should be sufficient to protect the route table from attack.

14.3.9 Access Issues with Kerberos and SSH

There are a few issues with both Kerberos and ssh that need to be addressed if you intend to use them. Kerberos 5 is an excellent authentication protocol, but there are bugs in the kerberized telnet and rlogin applications that make them unsuitable for dealing with binary streams. Also, by default Kerberos does not encrypt a session unless you use the -x option. ssh encrypts everything by default.

Ssh works quite well in every respect except that it forwards encryption keys by default. What this means is that if you have a secure workstation holding keys that give you access to the rest of the system, and you ssh to an insecure machine, your keys are usable. The actual keys themselves are not exposed, but ssh installs a forwarding port for the duration of your login, and if an attacker has broken root on the insecure machine he can utilize that port to use your keys to gain access to any other machine that your keys unlock.

We recommend that you use ssh in combination with Kerberos whenever possible for staff logins. Ssh can be compiled with Kerberos support. This reduces your reliance on potentially exposed ssh keys while at the same time protecting passwords via Kerberos. Ssh keys should only be used for automated tasks from secure machines (something that Kerberos is unsuited to do). We also recommend that you either turn off key-forwarding in the ssh configuration, or that you make use of the from=IP/DOMAIN option that ssh allows in its authorized_keys file to make the key only usable to entities logging in from specific machines.

Questo, ed altri documenti, possono essere scaricati da ftp://ftp.FreeBSD.org/pub/FreeBSD/doc/.

Per domande su FreeBSD, leggi la documentazione prima di contattare <questions@FreeBSD.org>.
Per domande su questa documentazione, invia una e-mail a <doc@FreeBSD.org>.