Capítulo 4. Autenticação

Índice

4.1. Autenticação Unix normal
4.2. Gerir informação de conta e palavra-passe
4.3. Boa palavra-passe
4.4. Criando palavra-passe encriptada
4.5. PAM e NSS
4.5.1. Ficheiros de configuração acedidos pelo PAM e NSS
4.5.2. O moderno sistema de gestão centralizado
4.5.3. "Porque o su do GNU não suporta o grupo wheel"
4.5.4. Stricter password rule
4.6. Outros controles de acesso
4.6.1. sudo
4.6.2. SELinux
4.6.3. Restringindo acesso a alguns serviços de servidor
4.7. Segurança da autenticação
4.7.1. Palavra-passe segura sobre a Internet
4.7.2. Shell Segura
4.7.3. Medidas de segurança extra para a Internet
4.7.4. Tornar a palavra-passe do root segura

When a person (or a program) requests access to the system, authentication confirms the identity to be a trusted one.

[Atenção] Atenção

Configuration errors of PAM may lock you out of your own system. You must have a rescue CD handy or setup an alternative boot partition. To recover, boot the system with them and correct things from there.

4.1. Autenticação Unix normal

Normal Unix authentication is provided by the pam_unix(8) module under the PAM (Pluggable Authentication Modules). Its 3 important configuration files, with ":" separated entries, are the following.

Tabela 4.1. 3 ficheiros de configuração importantes para pam_unix(8)

ficheiro permissão utilizador grupo descrição
/etc/passwd -rw-r--r-- root root informação da conta do utilizador (higienizada)
/etc/shadow -rw-r----- root shadow informação segura da conta do utilizador
/etc/group -rw-r--r-- root root informação do grupo

"/etc/passwd" contém o seguinte.

 ...
utilizador1:x:1000:1000:Nome de Utilizador1,,,:/home/utilizador1:/bin/bash
utilizador2:x:1001:1001:Nome de Utilizador2,,,:/home/utilizador2:/bin/bash
 ...

Como explicado em passwd(5), cada entrada ":" separada neste ficheiro significa o seguinte.

  • Nome de login
  • Entrada de especificação de palavra-passe
  • ID numérico do utilizador
  • ID numérico do grupo
  • Nome de utilizador ou campo de comentários
  • Directório home do utilizador
  • Interpretador de comandos opcional do utilizador

A segunda entrada de "/etc/passwd" foi usada para a entrada de palavra-passe encriptada. Após a introdução de "/etc/shadow", esta entrada é usada para a entrada de especificação da palavra-passe.

Tabela 4.2. A segunda entrada no conteúdo de "/etc/passwd"

conteúdo significado
(vazio) conta sem palavra-passe
x a palavra-passe encriptada está em "/etc/shadow"
* nenhum login para esta conta
! nenhum login para esta conta

"/etc/shadow" contém o seguinte.

 ...
user1:$1$Xop0FYH9$IfxyQwBe9b8tiyIkt2P4F/:13262:0:99999:7:::
user2:$1$vXGZLVbS$ElyErNf/agUDsm1DehJMS/:13261:0:99999:7:::
 ...

Como explicado em shadow(5), cada entrada ":" separada neste ficheiro significa o seguinte.

  • Nome de login
  • Palavra-passe encriptada (O "$1$" inicial indica o uso de encriptação MD5. O "*" indica nenhum login.)
  • Dias desde Jan 1, 1970 que essa palavra-passe foi alterada
  • Dias antes da palavra-passe poder ser alterada
  • Dias após os quais a palavra-passe tem de ser alterada
  • Dias de aviso ao utilizador antes da palavra-passe expirar

"/etc/group" contém o seguinte.

grupo1:x:20:utilizador1,utilizador2

Como explicado em grupo(5), cada entrada ":" separada neste ficheiro significa o seguinte.

  • Nome do grupo
  • Palavra-passe encriptada (não usada na realidade)
  • ID numérico do grupo
  • lista separada por "," de nomes de utilizadores
[Nota] Nota

"/etc/gshadow" provides the similar function as "/etc/shadow" for "/etc/group" but is not really used.

[Nota] Nota

The actual group membership of a user may be dynamically added if "auth optional pam_group.so" line is added to "/etc/pam.d/common-auth" and set it in "/etc/security/group.conf". See pam_group(8).

[Nota] Nota

The base-passwd package contains an authoritative list of the user and the group: "/usr/share/doc/base-passwd/users-and-groups.html".

4.2. Gerir informação de conta e palavra-passe

Aqui estão alguns comandos notáveis para gerir informação de conta

Tabela 4.3. Lista de comandos para gerir informação de conta

comando função
getent passwd <nome_de_utilizador> navegar na informação da conta de "<nome_de_utilizador>"
getent shadow <unome_de_utilizador> browse shadowed account information of "<user_name>"
getent group <nome_de_grupo> navegar na informação do grupo de "<nome_do_grupo>"
passwd gere a palavra-passe da conta
passwd -e definir palavra-passe de uma-vez para a activação da conta
chage gerir a informação de envelhecimento da palavra-passe

You may need to have the root privilege for some functions to work. See crypt(3) for the password and data encryption.

[Nota] Nota

On the system set up with PAM and NSS as the Debian alioth machine, the content of local "/etc/passwd", "/etc/group" and "/etc/shadow" may not be actively used by the system. Above commands are valid even under such environment.

4.3. Boa palavra-passe

When creating an account during your system installation or with the passwd(1) command, you should choose a good password which consists of 6 to 8 characters including one or more characters from each of the following sets according to passwd(1).

  • Alfabéticos de minúsculas
  • Dígitos de 0 a 9
  • Marcas de pontuação
[Atenção] Atenção

Não escolha palavras que podem ser adivinhadas para a palavra-passe.

4.4. Criando palavra-passe encriptada

Existem ferramentas independentes para gerar palavras-passe encriptadas salgadas.

Tabela 4.4. Lista de ferramentas para gerar palavras-passe

pacote popcon tamanho comando função
whois * V:10, I:88 396 mkpasswd frontend cheiro de funcionalidades para a biblioteca crypt(3)
openssl * V:56, I:91 2380 openssl passwd compute password hashes (OpenSSL). passwd(1ssl)

4.5. PAM e NSS

Modern Unix-like systems such as the Debian system provide PAM (Pluggable Authentication Modules) and NSS (Name Service Switch) mechanism to the local system administrator to configure his system. The role of these can be summarizes as the following.

  • PAM offers a flexible authentication mechanism used by the application software thus involves password data exchange.
  • NSS offers a flexible name service mechanism which is frequently used by the C standard library to obtain the user and group name for programs such as ls(1) and id(1).

These PAM and NSS systems need to be configured consistently.

Os pacotes notáveis dos sistemas PAM e NSS são os seguintes.

Tabela 4.5. Lista de sistemas PAM e NSS notáveis

pacote popcon tamanho descrição
libpam-modules * V:88, I:99 1036 Pluggable Authentication Modules (serviço básico)
libpam-ldap * V:2, I:4 408 Pluggable Authentication Module que permite interfaces LDAP
libpam-cracklib * V:2, I:2 104 Pluggable Authentication Module para activar suporte a cracklib
libpam-doc * I:0.6 1208 Pluggable Authentication Modules (documentação em html e texto)
libc6 * V:97, I:99 10012 GNU C Library: Shared libraries which also provides "Name Service Switch" service
glibc-doc * I:3 2008 Biblioteca GNU C: Manuais (manpages)
glibc-doc-reference * I:1.4 12156 Biblioteca GNU C: Manual de referência em info, pdf e html (não-livre)
libnss-mdns * I:49 116 Módulo NSS para resolução de nomes Multicast DNS
libnss-ldap * I:4 268 NSS module for using LDAP as a naming service
libnss-ldapd * V:0.18, I:0.5 144 NSS module for using LDAP as a naming service (new folk of libnss-ldap)

  • "The Linux-PAM System Administrators' Guide" in libpam-doc is essential for learning PAM configuration.
  • "System Databases and Name Service Switch" section in glibc-doc-reference is essential for learning NSS configuration.
[Nota] Nota

You can see more extensive and current list by "aptitude search 'libpam-|libnss-'" command. The acronym NSS may also mean "Network Security Service" which is different from "Name Service Switch".

[Nota] Nota

PAM is the most basic way to initialize environment variables for each program with the system wide default value.

4.5.1. Ficheiros de configuração acedidos pelo PAM e NSS

Aqui estão alguns ficheiros de configuração notáveis acedidos pelo PAM.

Tabela 4.6. Lista de ficheiros de configuração acedidos pelo PAM

ficheiro de configuração função
/etc/pam.d/<nome_do_programa> set up PAM configuration for the "<program_name>" program; see pam(7) and pam.d(5)
/etc/nsswitch.conf set up NSS configuration with the entry for each service. See nsswitch.conf(5)
/etc/nologin limita o login de utilizador pelo módulo pam_nologin(8)
/etc/securetty limit the tty for the root access by the pam_securetty(8) module
/etc/security/access.conf define limites de acesso pelo módulo pam_access(8)
/etc/security/group.conf define a restrição baseada em grupo pelo módulo pam_group(8)
/etc/security/pam_env.conf define as variáveis de ambiente pelo módulo pam_env(8)
/etc/environment set additional environment variables by the pam_env(8) module with the "readenv=1" argument
/etc/default/locale set locale by pam_env(8) module with the "readenv=1 envfile=/etc/default/locale" argument. (Debian)
/etc/security/limits.conf set resource restraint (ulimit, core, …) by the pam_linits(8) module
/etc/security/time.conf set time restraint by the pam_time(8) module

The limitation of the password selection is implemented by the PAM modules, pam_unix(8) and pam_cracklib(8). They can be configured by their arguments.

[Dica] Dica

Os módulos PAM usam o sufixo ".so" para os seus nomes de ficheiros.

4.5.2. O moderno sistema de gestão centralizado

The modern centralized system management can be deployed using the centralized Lightweight Directory Access Protocol (LDAP) server to administer many Unix-like and non-Unix-like systems on the network. The open source implementation of the Lightweight Directory Access Protocol is OpenLDAP Software.

The LDAP server provides the account information through the use of PAM and NSS with libpam-ldap and libnss-ldap packages for the Debian system. Several actions are required to enable this (I have not used this setup and the following is purely secondary information. Please read this in this context.).

  • You set up a centralized LDAP server by running program such as stand-alone LDAP daemon, slapd(8).
  • You change the PAM configuration files in the "/etc/pam.d/" directory to use "pam_ldap.so" instead of the default "pam_unix.so".

    • Debian usa "/etc/pam_ldap.conf" como ficheiro de configuração para libpam-ldap e "/etc/pam_ldap.secret" como ficheiro para armazenar a palavra-passe do root.
  • You change the NSS configuration in the "/etc/nsswitch.conf" file to use "ldap" instead of the default ("compat" or "file").

    • Debian usa o "/etc/libnss-ldap.conf" como o ficheiro de configuração para libnss-ldap.
  • Você tem de fazer libpam-ldap para usar a ligação SSL (ou TLS) para a segurança da palavra-passe.
  • You may make libnss-ldap to use SSL (or TLS) connection to ensure integrity of data at the cost of the LDAP network overhead.
  • You should run nscd(8) locally to cache any LDAP search results in order to reduce the LDAP network traffic.

See documentations in pam_ldap.conf(5) and "/usr/share/doc/libpam-doc/html/" offered by the libpam-doc package and "info libc 'Name Service Switch'" offered by the glibc-doc package.

De modo semelhante, você pode configurar sistemas centralizados alternativos com outros métodos.

4.5.3. "Porque o su do GNU não suporta o grupo wheel"

This is the famous phrase at the bottom of the old "info su" page by Richard M. Stallman. Not to worry: the current su command in Debian uses PAM, so that one can restrict the ability to use su to the root group by enabling the line with "pam_wheel.so" in "/etc/pam.d/su".

4.5.4. Stricter password rule

Installing the libpam-cracklib package enables you to force stricter password rule, for example, by having active lines in "/etc/pam.d/common-password" as the following.

Para lenny:

password required pam_cracklib.so retry=3 minlen=9 difok=3
password required pam_unix.so use_authtok nullok md5

Para squeeze:

password required pam_cracklib.so retry=3 minlen=9 difok=3
password [success=1 default=ignore] pam_unix.so use_authtok nullok md5
password requisite pam_deny.so
password required pam_permit.so

4.6. Outros controles de acesso

[Nota] Nota

See Secção 9.5.15, “Tecla Alt-SysRq” for restricting the kernel secure attention key (SAK) feature.

4.6.1. sudo

sudo(8) is a program designed to allow a sysadmin to give limited root privileges to users and log root activity. sudo requires only an ordinary user's password. Install sudo package and activate it by setting options in "/etc/sudoers". See configuration example at "/usr/share/doc/sudo/examples/sudoers".

My usage of sudo for the single user system (see Secção 1.1.12, “configuração do sudo”) is aimed to protect myself from my own stupidity. Personally, I consider using sudo a better alternative to using the system from the root account all the time. For example, the following changes the owner of "<some_file>" to "<my_name>".

$ sudo chown <meu_nome> <qualquer_ficheiro>

Of course if you know the root password (as self-installed Debian users do), any command can be run under root from any user's account using "su -c".

4.6.2. SELinux

Security-Enhanced Linux (SELinux) is a framework to tighten privilege model tighter than the ordinary Unix-like security model with the mandatory access control (MAC) policies. The root power may be restricted under some conditions.

4.6.3. Restringindo acesso a alguns serviços de servidor

For system security, It is a good idea to disable as much server programs as possible. This becomes critical for network servers. Having unused servers, activated either directly as daemon or via super-server program, are considered security risks.

Muito programas, como o sshd(8), usam controles de acesso baseados no PAM. Existem muitas maneiras de restringir o acesso a alguns serviços de servidor.

Veja Secção 3.5.3, “O exemplo de gestão do runlevel”, Secção 3.5.4, “O parâmetro predefinido para cada script de init”, Secção 4.5.1, “Ficheiros de configuração acedidos pelo PAM e NSS”, Secção 3.5.8, “Inicialização do serviço de rede”, e Secção 5.9, “Infraestrutura do netfilter”.

[Dica] Dica

os serviços Sun RPC precisam de estar activos para NFS e outros programas baseados em RPC.

[Dica] Dica

If you have problems with remote access in a recent Debian system, comment out offending configuration such as "ALL: PARANOID" in "/etc/hosts.deny" if it exists. (But you must be careful on security risks involved with this kind of action.)

4.7. Segurança da autenticação

A informação aqui pode não ser suficiente para as suas necessidades de segurança, mas deverá ser um bom começo.

4.7.1. Palavra-passe segura sobre a Internet

Many popular transportation layer services communicate messages including password authentication in the plain text. It is very bad idea to transmit password in the plain text over the wild Internet where it can be intercepted. You can run these services over "Transport Layer Security" (TLS) or its predecessor, "Secure Sockets Layer" (SSL) to secure entire communication including password by the encryption.

Tabela 4.7. Lista de serviços e portos inseguros e seguros

nome do serviço inseguro porto nome do serviço seguro porto
www (http) 80 https 443
smtp (mail) 25 ssmtp (smtps) 465
ftp-data 20 ftps-data 989
ftp 21 ftps 990
telnet 23 telnets 992
imap2 143 imaps 993
pop3 110 pop3s 995
ldap 389 ldaps 636

The encryption costs CPU time. As a CPU friendly alternative, you can keep communication in plain text while securing just password with the secure authentication protocol such as "Authenticated Post Office Protocol" (APOP) for POP and "Challenge-Response Authentication Mechanism MD5" (CRAM-MD5) for SMTP and IMAP. (For sending mail messages over the Internet to your mail server from your mail client, it is recently popular to use new message submission port 587 instead of traditional SMTP port 25 to avoid port 25 blocking by the network provider while authenticating yourself with CRAM-MD5.)

4.7.2. Shell Segura

The Secure Shell (SSH) program provides secure encrypted communications between two untrusted hosts over an insecure network with the secure authentication. It consists of the OpenSSH client, ssh(1), and the OpenSSH daemon, sshd(8). This SSH can be used to tunnel the insecure protocol communication such as POP and X securely over the Internet with the port forwarding feature.

The client tries to authenticate itself using host-based authentication, public key authentication, challenge-response authentication, or password authentication. The use of public key authentication enables the remote password-less login. See Secção 6.9, “O servidor de acesso remoto e utilitário (SSH)”.

4.7.3. Medidas de segurança extra para a Internet

Even when you run secure services such as Secure Shell (SSH) and Point-to-point tunneling protocol (PPTP) servers, there are still chances for the break-ins using brute force password guessing attack etc. from the Internet. Use of the firewall policy (see Secção 5.9, “Infraestrutura do netfilter”) together with the following secure tools may improve the security situation.

Tabela 4.8. Lista de ferramentas para disponibilizar medidas de segurança extra

pacote popcon tamanho descrição
knockd * V:0.15, I:0.3 164 pequeno daemon port-knock knockd(1) e cliente konck(1)
denyhosts * V:2, I:2 356 utility to help sysadmins thwart ssh hackers
fail2ban * V:4, I:5 660 banir IPs que causam erros de autenticação múltipla
libpam-shield * V:0.01, I:0.05 104 bloquear atacantes remotos que tentam adivinhar a palavra-passe

4.7.4. Tornar a palavra-passe do root segura

Para prevenir que pessoas acedam à sua máquina com privilégios de root, você precisa de tomar as seguintes acções.

  • Prevenir acesso físico ao disco rijo
  • Bloquear a BIOS e prevenir o arranque a partir de medias amovíveis
  • Define palavra-passe para sessão interactiva do GRUB
  • Bloquear o menu do GRUB de ser editado

With physical access to hard disk, resetting the password is relatively easy with following steps.

  1. Mover o disco rijo para um PC com uma BIOS com arranque a partir de CD.
  2. Arrancar o sistema com uma media de recuperação (disco de arranque Debian, CD Knoppix, CD GRUB, ...)
  3. Montar a partição raiz com acesso de leitura/escrita.
  4. Edit "/etc/passwd" in the root partition and make the second entry for the root account empty.

If you have the edit access to the GRUB menu entry (see Secção 3.3, “Estágio 2: o gestor de arranque”) for grub-rescue-pc at the boot time, it is even easier with following steps.

  1. Boot system with the kernel parameter changed to something like "root=/dev/hda6 rw init=/bin/sh".
  2. Edit "/etc/passwd" and make the second entry for the root account empty.
  3. Reiniciar o sistema.

A shell de root do sistema está agora acessível sem palavra-passe.

[Nota] Nota

Once one has root shell access, he can access everything on the system and reset any passwords on the system. Further more, he may compromise password for all user accounts using brute force password cracking tools such as john and crack packages (see Secção 9.6.11, “Segurança do sistema e verificação de integridade”). This cracked password may lead to compromise other systems.

The only reasonable software solution to avoid all these concerns is to use software encrypted root partition (or "/etc" partition) using dm-crypt and initramfs (see Secção 9.4, “Dicas de encriptação de dados”). You always need password to boot the system, though.