Product SiteDocumentation Site

Red Hat Enterprise Linux 5

Deployment Guide

Deployment, configuration and administration of Red Hat Enterprise Linux 5

Edição 8

Logo


Nota Legal

Copyright © 2007, 2008, 2009, 2010, 2011 Red Hat, Inc.
The text of and illustrations in this document are licensed by Red Hat under a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, JBoss, MetaMatrix, Fedora, the Infinity Logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.
Linux® is the registered trademark of Linus Torvalds in the United States and other countries.
Java® is a registered trademark of Oracle and/or its affiliates.
XFS® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries.
MySQL® is a registered trademark of MySQL AB in the United States, the European Union and other countries.
All other trademarks are the property of their respective owners.


1801 Varsity Drive
 RaleighNC 27606-2072 USA
 Phone: +1 919 754 3700
 Phone: 888 733 4281
 Fax: +1 919 754 3701

Resumo
The Deployment Guide documents relevant information regarding the deployment, configuration and administration of Red Hat Enterprise Linux 5.

Introdução
1. Convenções de Documentos
2. Envie-nos sua Opinião
I. Sistemas de Arquivos
1. File System Structure
1.1. Why Share a Common Structure?
1.2. Overview of File System Hierarchy Standard (FHS)
1.2.1. FHS Organization
1.3. Special File Locations Under Red Hat Enterprise Linux
2. Using the mount Command
2.1. Listing Currently Mounted File Systems
2.2. Mounting a File System
2.2.1. Specifying the File System Type
2.2.2. Specifying the Mount Options
2.2.3. Sharing Mounts
2.2.4. Moving a Mount Point
2.3. Unmounting a File System
2.4. Additional Resources
2.4.1. Installed Documentation
2.4.2. Useful Websites
3. O Sistema de Arquivo ext3
3.1. Características do ext3
3.2. Criando um Sistema de Arquivo ext3
3.3. Convertendo para um Sistema de Arquivo ext3
3.4. Revertendo para um Sistema de Arquivo ext2
4. The proc File System
4.1. A Virtual File System
4.1.1. Viewing Virtual Files
4.1.2. Changing Virtual Files
4.2. Top-level Files within the proc File System
4.2.1. /proc/apm
4.2.2. /proc/buddyinfo
4.2.3. /proc/cmdline
4.2.4. /proc/cpuinfo
4.2.5. /proc/crypto
4.2.6. /proc/devices
4.2.7. /proc/dma
4.2.8. /proc/execdomains
4.2.9. /proc/fb
4.2.10. /proc/filesystems
4.2.11. /proc/interrupts
4.2.12. /proc/iomem
4.2.13. /proc/ioports
4.2.14. /proc/kcore
4.2.15. /proc/kmsg
4.2.16. /proc/loadavg
4.2.17. /proc/locks
4.2.18. /proc/mdstat
4.2.19. /proc/meminfo
4.2.20. /proc/misc
4.2.21. /proc/modules
4.2.22. /proc/mounts
4.2.23. /proc/mtrr
4.2.24. /proc/partitions
4.2.25. /proc/pci
4.2.26. /proc/slabinfo
4.2.27. /proc/stat
4.2.28. /proc/swaps
4.2.29. /proc/sysrq-trigger
4.2.30. /proc/uptime
4.2.31. /proc/version
4.3. Directories within /proc/
4.3.1. Process Directories
4.3.2. /proc/bus/
4.3.3. /proc/driver/
4.3.4. /proc/fs
4.3.5. /proc/ide/
4.3.6. /proc/irq/
4.3.7. /proc/net/
4.3.8. /proc/scsi/
4.3.9. /proc/sys/
4.3.10. /proc/sysvipc/
4.3.11. /proc/tty/
4.3.12. /proc/<PID>/
4.4. Using the sysctl Command
4.5. Additional Resources
4.5.1. Installed Documentation
4.5.2. Useful Websites
5. Redundant Array of Independent Disks (RAID)
5.1. What is RAID?
5.1.1. Who Should Use RAID?
5.1.2. Hardware RAID versus Software RAID
5.1.3. RAID Levels and Linear Support
5.2. Configuring Software RAID
5.2.1. riando uma Nova Partição RAID
5.2.2. Creating the RAID Devices and Mount Points
5.3. Managing Software RAID
5.3.1. Reviewing RAID Configuration
5.3.2. Creating a New RAID Device
5.3.3. Replacing a Faulty Device
5.3.4. Extending a RAID Device
5.3.5. Removing a RAID Device
5.3.6. Preserving the Configuration
5.4. Additional Resources
5.4.1. Installed Documentation
6. Espaço Virtual (swap space)
6.1. O que é Espaço Virtual?
6.2. Adicionando Espaço Virtual
6.2.1. Extending Swap on an LVM2 Logical Volume
6.2.2. Creating an LVM2 Logical Volume for Swap
6.2.3. Creating a Swap File
6.3. Removendo Espaço Virtual
6.3.1. Reducing Swap on an LVM2 Logical Volume
6.3.2. Removing an LVM2 Logical Volume for Swap
6.3.3. Removing a Swap File
6.4. Movendo Espaço Virtual
7. Gerenciando o Armazenamento de Disco
7.1. Standard Partitions using parted
7.1.1. Visualizando a Tabela de Partições
7.1.2. Criando uma Partição
7.1.3. Removendo uma Partição
7.1.4. Redimensionando uma Partição
7.2. LVM Partition Management
8. Implementando Quotas de Disco
8.1. Configurando Quotas de Disco
8.1.1. Habilitando Quotas
8.1.2. Remontando os Sistemas de Arquivo
8.1.3. Criando Arquivos de Banco de Dados de Quota
8.1.4. Atribuindo Quotas por Usuário
8.1.5. Atribuindo Quotas por Grupo
8.1.6. Configurando o Tempo de Carência para Limites Suaves.
8.2. Administrando Quotas de Disco
8.2.1. Habilitando e Desabilitando
8.2.2. Reportando em Quotas de Disco
8.2.3. Mantendo as Quotas Exatas
8.3. Recursos Adicionais
8.3.1. Documentação Instalada
8.3.2. Livros Relacionados
9. Access Control Lists
9.1. Montando Sistemas de Arquivo
9.1.1. NFS
9.2. Definindo ACLs de Acesso
9.3. Definindo ACLs Default
9.4. Recuperando ACLs
9.5. Documentando Sistemas de Arquivo Com ACLs
9.6. Compatibilidade com Sistemas mais Antigos
9.7. Recursos Adicionais
9.7.1. Documentação Instalada
9.7.2. Sites Úteis
10. LVM (Logical Volume Manager)
10.1. What is LVM?
10.1.1. What is LVM2?
10.2. Configuração do LVM
10.3. Automatic Partitioning
10.4. Manual LVM Partitioning
10.4.1. Creating the /boot Partition
10.4.2. Creating the LVM Physical Volumes
10.4.3. Creating the LVM Volume Groups
10.4.4. Creating the LVM Logical Volumes
10.5. Using the LVM utility system-config-lvm
10.5.1. Utilizing uninitialized entities
10.5.2. Adding Unallocated Volumes to a volume group
10.5.3. Migrating extents
10.5.4. Adding a new hard disk using LVM
10.5.5. Adding a new volume group
10.5.6. Extending a volume group
10.5.7. Editing a Logical Volume
10.6. Additional Resources
10.6.1. Installed Documentation
10.6.2. Useful Websites
II. Gerenciamento de Pacotes
11. Gerenciamento de Pacotes com RPM
11.1. Objetivos de Desenvolvimento do RPM
11.2. Usando o RPM
11.2.1. Encontrando Pacotes RPM
11.2.2. Instalando
11.2.3. Desinstalando
11.2.4. Atualizando (upgrade)
11.2.5. Recarregando
11.2.6. Busca
11.2.7. Verificando
11.3. Verificando a Assinatura de um Pacote
11.3.1. Importando Chaves
11.3.2. Verificando a Assinatura de Pacotes
11.4. Exemplos Comuns e Práticos do Uso de RPM
11.5. Recursos Adicionais
11.5.1. Documentação Instalada
11.5.2. Sites Úteis
11.5.3. Livros Relacionados
12. Package Management Tool
12.1. Listando e Analisando Pacotes
12.2. Instalando e Removendo Pacotes
13. YUM (Yellowdog Updater Modified)
13.1. Setting Up a Yum Repository
13.2. yum Commands
13.3. yum Options
13.4. Configuring yum
13.4.1. [main] Options
13.4.2. [repository] Options
13.5. Useful yum Variables
14. Product Subscriptions and Entitlements
14.1. An Overview of Managing Subscriptions and Content
14.1.1. The Purpose of Subscription Management
14.1.2. Defining Subscriptions, Entitlements, and Products
14.1.3. Subscription Management Tools
14.1.4. Subscription and Content Architecture
14.1.5. Advanced Content Management: Extended Update Support
14.1.6. RHN Classic v. Certificate-based Red Hat Network
14.2. Using Red Hat Subscription Manager Tools
14.2.1. Launching Red Hat Subscription Manager
14.2.2. About subscription-manager
14.2.3. Looking at RHN Subscription Management
14.2.4. Looking at Subscription Asset Manager
14.3. Managing Special Deployment Scenarios
14.3.1. Local Subscription Services, Local Content Providers, and Multi-Tenant Organizations
14.3.2. Virtual Guests and Hosts
14.3.3. Domains
14.4. Registering, Unregistering, and Reregistering a System
14.4.1. Registering Consumers in the Hosted Environment
14.4.2. Registering Consumers to a Local Organization
14.4.3. Registering an Offline Consumer
14.4.4. Registering from the Command Line
14.4.5. Unregistering
14.4.6. Restoring a Registration
14.5. Migrating Systems from RHN Classic to Certificate-based Red Hat Network
14.5.1. Installing the Migration Tools
14.5.2. Migrating from RHN Classic to Certificate-based Red Hat Network
14.5.3. Unregistering from RHN Classic Only
14.5.4. Migrating a Disconnected System
14.5.5. Looking at Channel and Certificate Mappings
14.6. Handling Subscriptions
14.6.1. Subscribing and Unsubscribing through the Red Hat Subscription Manager GUI
14.6.2. Handling Subscriptions through the Command Line
14.6.3. Stacking Subscriptions
14.6.4. Manually Adding a New Subscription
14.7. Redeeming Subscriptions on a Machine
14.7.1. Redeeming Subscriptions through the GUI
14.7.2. Redeeming Subscriptions on a Machine through the Command Line
14.8. Viewing Available and Used Subscriptions
14.8.1. Viewing Subscriptions in the GUI
14.8.2. Listing Subscriptions with the Command Line
14.8.3. Viewing Subscriptions Used in Both RHN Classic and Certificate-based Red Hat Network
14.9. Working with Subscription yum Repos
14.10. Responding to Subscription Notifications
14.11. Healing Subscriptions
14.11.1. Enabling Healing
14.11.2. Changing the Healing Check Frequency
14.12. Working with Subscription Asset Manager
14.12.1. Configuring Subscription Manager to Work with Subscription Asset Manager
14.12.2. Viewing Organization Information
14.13. Updating Entitlements Certificates
14.13.1. Updating Entitlement Certificates
14.13.2. Updating Subscription Information
14.14. Configuring the Subscription Service
14.14.1. Red Hat Subscription Manager Configuration Files
14.14.2. Using the config Command
14.14.3. Using an HTTP Proxy
14.14.4. Changing the Subscription Server
14.14.5. Configuring Red Hat Subscription Manager to Use a Local Content Provider
14.14.6. Managing Secure Connections to the Subscription Server
14.14.7. Starting and Stopping the Subscription Service
14.14.8. Checking Logs
14.14.9. Showing and Hiding Incompatible Subscriptions
14.14.10. Checking and Adding System Facts
14.14.11. Regenerating Identity Certificates
14.14.12. Getting the System UUID
14.14.13. Viewing Package Profiles
14.14.14. Retrieving the Consumer ID, Registration Tokens, and Other Information
14.15. About Certificates and Managing Entitlements
14.15.1. The Structure of Identity Certificates
14.15.2. The Structure of Entitlement Certificates
14.15.3. The Structure of Product Certificates
14.15.4. Anatomy of Satellite Certificates
III. Configuração Relacionada à Rede de Trabalho
15. Network Interfaces
15.1. Network Configuration Files
15.2. Interface Configuration Files
15.2.1. Ethernet Interfaces
15.2.2. IPsec Interfaces
15.2.3. Channel Bonding Interfaces
15.2.4. Alias and Clone Files
15.2.5. Dialup Interfaces
15.2.6. Other Interfaces
15.3. Interface Control Scripts
15.4. Configuring Static Routes
15.5. Network Function Files
15.6. Additional Resources
15.6.1. Installed Documentation
16. Configuração de Rede
16.1. Visão Geral
16.2. Estabelecendo uma Conexão Ehternet
16.3. Estabelecendo uma Conexão ISDN
16.4. Estabelecendo uma Conexão de Modem
16.5. Estabelecendo uma Conexão xDSL
16.6. Estabelecendo uma Conexão Token Ring
16.7. Estabelecendo uma Conexão Sem-fio
16.8. Administrando a Configuração do DNS
16.9. Administrando Máquinas
16.10. Trabalhando com Perfis
16.11. Alias de Dispositivos
16.12. Salvando e Restaurando a Configuração de Rede
17. Controlando Acesso aos Serviços
17.1. Níveis de Execução (Runlevels)
17.2. TCP Wrappers
17.2.1. xinetd
17.3. Services Configuration Tool
17.4. ntsysv
17.5. chkconfig
17.6. Recursos Adicionais
17.6.1. Documentação Instalada
17.6.2. Websites Úteis
18. Berkeley Internet Name Domain (BIND)
18.1. Introduction to DNS
18.1.1. Nameserver Zones
18.1.2. Nameserver Types
18.1.3. BIND as a Nameserver
18.2. /etc/named.conf
18.2.1. Common Statement Types
18.2.2. Other Statement Types
18.2.3. Comment Tags
18.3. Zone Files
18.3.1. Zone File Directives
18.3.2. Zone File Resource Records
18.3.3. Example Zone File
18.3.4. Reverse Name Resolution Zone Files
18.4. Using rndc
18.4.1. Configuring /etc/named.conf
18.4.2. Configuring /etc/rndc.conf
18.4.3. Command Line Options
18.5. Advanced Features of BIND
18.5.1. DNS Protocol Enhancements
18.5.2. Multiple Views
18.5.3. Security
18.5.4. IP version 6
18.6. Common Mistakes to Avoid
18.7. Additional Resources
18.7.1. Installed Documentation
18.7.2. Useful Websites
18.7.3. Related Books
19. OpenSSH
19.1. Features of SSH
19.1.1. Why Use SSH?
19.2. SSH Protocol Versions
19.3. Event Sequence of an SSH Connection
19.3.1. Transport Layer
19.3.2. Authentication
19.3.3. Channels
19.4. Configurando um Servidor OpenSSH
19.4.1. Requiring SSH for Remote Connections
19.5. OpenSSH Configuration Files
19.6. Configurando um Cliente OpenSSH
19.6.1. Using the ssh Command
19.6.2. Using the scp Command
19.6.3. Using the sftp Command
19.7. More Than a Secure Shell
19.7.1. X11 Forwarding
19.7.2. Port Forwarding
19.7.3. Gerando Pares de Chaves
19.8. Recursos Adicionais
19.8.1. Documentação Instalada
19.8.2. Sites Úteis
20. Sistema de Arquivo de Rede (NFS - Network File System)
20.1. How It Works
20.1.1. Required Services
20.2. NFS Client Configuration
20.2.1. Mounting NFS File Systems using /etc/fstab
20.3. autofs
20.3.1. What's new in autofs version 5?
20.3.2. autofs Configuration
20.3.3. autofs Common Tasks
20.4. Common NFS Mount Options
20.5. Starting and Stopping NFS
20.6. NFS Server Configuration
20.6.1. Exporting or Sharing NFS File Systems
20.6.2. Configuração da Linha de Comando
20.6.3. Running NFS Behind a Firewall
20.6.4. Formatos de Nomes de Máquina
20.7. The /etc/exports Configuration File
20.7.1. The exportfs Command
20.8. Securing NFS
20.8.1. Host Access
20.8.2. File Permissions
20.9. NFS and portmap
20.9.1. Troubleshooting NFS and portmap
20.10. Using NFS over TCP
20.11. Recursos Adicionais
20.11.1. Documentação Instalada
20.11.2. Sites Úteis
20.11.3. Livros Relacionados
21. Samba
21.1. Introduction to Samba
21.1.1. Samba Features
21.2. Samba Daemons and Related Services
21.2.1. Samba Daemons
21.3. Connecting to a Samba Share
21.3.1. Command Line
21.3.2. Mounting the Share
21.4. Configuring a Samba Server
21.4.1. Graphical Configuration
21.4.2. Command Line Configuration
21.4.3. Encrypted Passwords
21.5. Starting and Stopping Samba
21.6. Samba Server Types and the smb.conf File
21.6.1. Stand-alone Server
21.6.2. Domain Member Server
21.6.3. Domain Controller
21.7. Samba Security Modes
21.7.1. User-Level Security
21.7.2. Share-Level Security
21.8. Samba Account Information Databases
21.9. Samba Network Browsing
21.9.1. Domain Browsing
21.9.2. WINS (Windows Internetworking Name Server)
21.10. Samba with CUPS Printing Support
21.10.1. Simple smb.conf Settings
21.11. Samba Distribution Programs
21.12. Additional Resources
21.12.1. Documentação Instalada
21.12.2. Related Books
21.12.3. Sites Úteis
22. Protocolo de Configuração Dinâmica de Máquina (Dynamic Host Configuration Protocol - DHCP)
22.1. Por que usar o DHCP?
22.2. Configurando um Servidor DHCP
22.2.1. Arquivo de Configuração
22.2.2. Banco de Dados de Aluguel
22.2.3. Iniciando e Parando o Servidor
22.2.4. Agente DHCP Relay
22.3. Configurando um Cliente DHCP
22.4. Configuring a Multihomed DHCP Server
22.4.1. Host Configuration
22.5. Recursos Adicionais
22.5.1. Documentação Instalada
23. Apache HTTP Server
23.1. Apache HTTP Server 2.2
23.1.1. Features of Apache HTTP Server 2.2
23.2. Migrating Apache HTTP Server Configuration Files
23.2.1. Migrating Apache HTTP Server 2.0 Configuration Files
23.2.2. Migrating Apache HTTP Server 1.3 Configuration Files to 2.0
23.3. Starting and Stopping httpd
23.4. Apache HTTP Server Configuration
23.4.1. Basic Settings
23.4.2. Default Settings
23.5. Configuration Directives in httpd.conf
23.5.1. General Configuration Tips
23.5.2. Configuration Directives for SSL
23.5.3. MPM Specific Server-Pool Directives
23.6. Adding Modules
23.7. Virtual Hosts
23.7.1. Setting Up Virtual Hosts
23.8. Apache HTTP Secure Server Configuration
23.8.1. An Overview of Security-Related Packages
23.8.2. An Overview of Certificates and Security
23.8.3. Using Pre-Existing Keys and Certificates
23.8.4. Types of Certificates
23.8.5. Generating a Key
23.8.6. How to configure the server to use the new key
23.9. Additional Resources
23.9.1. Useful Websites
24. FTP
24.1. The File Transfer Protocol
24.1.1. Multiple Ports, Multiple Modes
24.2. FTP Servers
24.2.1. vsftpd
24.3. Files Installed with vsftpd
24.4. Starting and Stopping vsftpd
24.4.1. Starting Multiple Copies of vsftpd
24.5. vsftpd Configuration Options
24.5.1. Daemon Options
24.5.2. Log In Options and Access Controls
24.5.3. Anonymous User Options
24.5.4. Local User Options
24.5.5. Directory Options
24.5.6. File Transfer Options
24.5.7. Logging Options
24.5.8. Network Options
24.6. Additional Resources
24.6.1. Installed Documentation
24.6.2. Useful Websites
25. Email
25.1. Email Protocols
25.1.1. Mail Transport Protocols
25.1.2. Mail Access Protocols
25.2. Email Program Classifications
25.2.1. Mail Transport Agent
25.2.2. Mail Delivery Agent
25.2.3. Mail User Agent
25.3. Mail Transport Agents
25.3.1. Sendmail
25.3.2. Postfix
25.3.3. Fetchmail
25.4. Mail Transport Agent (MTA) Configuration
25.5. Mail Delivery Agents
25.5.1. Procmail Configuration
25.5.2. Procmail Recipes
25.6. Mail User Agents
25.6.1. Securing Communication
25.7. Additional Resources
25.7.1. Installed Documentation
25.7.2. Useful Websites
25.7.3. Related Books
26. Lightweight Directory Access Protocol (LDAP)
26.1. Why Use LDAP?
26.1.1. OpenLDAP Features
26.2. LDAP Terminology
26.3. OpenLDAP Daemons and Utilities
26.3.1. NSS, PAM, and LDAP
26.3.2. PHP4, LDAP, and the Apache HTTP Server
26.3.3. LDAP Client Applications
26.4. OpenLDAP Configuration Files
26.5. The /etc/openldap/schema/ Directory
26.6. OpenLDAP Setup Overview
26.6.1. Editing /etc/openldap/slapd.conf
26.7. Configuring a System to Authenticate Using OpenLDAP
26.7.1. PAM and LDAP
26.7.2. Migrating Old Authentication Information to LDAP Format
26.8. Migrating Directories from Earlier Releases
26.9. Additional Resources
26.9.1. Installed Documentation
26.9.2. Useful Websites
26.9.3. Related Books
27. Configuração da Autenticação
27.1. User Information
27.2. Authentication
27.3. Options
27.4. Versão de Linha de Comando
28. Using and Caching Credentials with SSSD
28.1. About the sssd.conf File
28.2. Starting and Stopping SSSD
28.3. Configuring Services
28.3.1. Configuring the NSS Service
28.3.2. Configuring the PAM Service
28.4. Creating Domains
28.4.1. General Rules and Options for Configuring a Domain
28.4.2. Configuring an LDAP Domain
28.4.3. Configuring Kerberos Authentication with a Domain
28.4.4. Configuring a Proxy Domain
28.5. Configuring Access Control for SSSD Domains
28.5.1. Using the Simple Access Provider
28.5.2. Using the LDAP Access Filter
28.6. Configuring Domain Failover
28.6.1. Configuring Failover
28.6.2. Using SRV Records with Failover
28.7. Deleting Domain Cache Files
28.8. Using NSCD with SSSD
28.9. Troubleshooting SSSD
28.9.1. Using SSSD Log Files
28.9.2. Problems with SSSD Configuration
IV. Configuração de Sistema
29. Acesso ao Console
29.1. Disabling Shutdown Via Ctrl+Alt+Del
29.2. Desabilitando Acesso a Programas do Console
29.3. Definindo o Console
29.4. Tornando Arquivos Acessíveis Pelo Console
29.5. Habilitando o Acesso a Outras Aplicações pelo Console
29.6. The floppy Group
30. The sysconfig Directory
30.1. Files in the /etc/sysconfig/ Directory
30.1.1. /etc/sysconfig/amd
30.1.2. /etc/sysconfig/apmd
30.1.3. /etc/sysconfig/arpwatch
30.1.4. /etc/sysconfig/authconfig
30.1.5. /etc/sysconfig/autofs
30.1.6. /etc/sysconfig/clock
30.1.7. /etc/sysconfig/desktop
30.1.8. /etc/sysconfig/dhcpd
30.1.9. /etc/sysconfig/exim
30.1.10. /etc/sysconfig/firstboot
30.1.11. /etc/sysconfig/gpm
30.1.12. /etc/sysconfig/hwconf
30.1.13. /etc/sysconfig/i18n
30.1.14. /etc/sysconfig/init
30.1.15. /etc/sysconfig/ip6tables-config
30.1.16. /etc/sysconfig/iptables-config
30.1.17. /etc/sysconfig/irda
30.1.18. /etc/sysconfig/keyboard
30.1.19. /etc/sysconfig/kudzu
30.1.20. /etc/sysconfig/named
30.1.21. /etc/sysconfig/network
30.1.22. /etc/sysconfig/nfs
30.1.23. /etc/sysconfig/ntpd
30.1.24. /etc/sysconfig/radvd
30.1.25. /etc/sysconfig/samba
30.1.26. /etc/sysconfig/selinux
30.1.27. /etc/sysconfig/sendmail
30.1.28. /etc/sysconfig/spamassassin
30.1.29. /etc/sysconfig/squid
30.1.30. /etc/sysconfig/system-config-securitylevel
30.1.31. /etc/sysconfig/system-config-selinux
30.1.32. /etc/sysconfig/system-config-users
30.1.33. /etc/sysconfig/system-logviewer
30.1.34. /etc/sysconfig/tux
30.1.35. /etc/sysconfig/vncservers
30.1.36. /etc/sysconfig/xinetd
30.2. Directories in the /etc/sysconfig/ Directory
30.3. Recursos Adicionais
30.3.1. Documentação Instalada
31. Configuração de Data e Hora
31.1. Time and Date Properties
31.2. Propriedades do Protocolo de Horário de Rede (Network Time Protocol - NTP)
31.3. Configuração do Fuso Horário
32. Configuração do Teclado
33. O Sistema X Window
33.1. O Lançamento X11R7.1
33.2. Ambientes de Desktop e Gestores de Window
33.2.1. Ambientes de Desktop
33.2.2. Gestores de Janelas
33.3. Arquivos de Configuração de Servidor X
33.3.1. xorg.conf
33.4. Fontes
33.4.1. Fontconfig
33.4.2. Sistema de Fonte Central X
33.5. Níveis de Execução e X
33.5.1. Nível de Execução 3
33.5.2. Nível de Execução 5
33.6. Recursos Adicionais
33.6.1. Documentação Instalada
33.6.2. Sites Úteis
34. Configuração do Sistema X Window
34.1. Display Settings
34.2. Display Hardware Settings
34.3. Dual Head Display Settings
35. Usuários e Grupos
35.1. Configuração de Usuário e Grupo
35.1.1. Adicionando um Novo Usuário
35.1.2. Modificando Propriedades do Usuário
35.1.3. Adicionando um Novo Grupo
35.1.4. Modificando Propriedades de Grupo
35.2. Gerenciamento de Ferramentas de Usuário e Grupo
35.2.1. Configuração da Linha de Comando
35.2.2. Adicionando um Usuário
35.2.3. Adicionando um Grupo
35.2.4. Vencimento de Senhas
35.2.5. Explicando o Processo
35.3. Usuários Padrão
35.4. Grupos Padrão
35.5. Brupos Privados de Usuários
35.5.1. Diretórios de Grupo
35.6. Senhas Shadow
35.7. Recursos Adicionais
35.7.1. Documentação Instalada
36. Configuração da Impressora
36.1. Adicionando uma Impressora Local.
36.2. Adicionando uma Impressora IPP
36.3. Adicionando uma Impressora Samba (SMB)
36.4. Adding a JetDirect Printer
36.5. Selecionando o Modelo da Impressora e Finalizando
36.5.1. Confirmando a Configuração da Impressora
36.6. Imprimindo uma Página de Teste
36.7. Modificando Impressoras Existentes
36.7.1. A Aba Configurações
36.7.2. A Aba Políticas
36.7.3. A Aba Controle de Acesso
36.7.4. A Aba Impressora e a Aba Opções de Trabalho
36.8. Gerenciando Tarefas de Impressão
36.9. Recursos Adicionais
36.9.1. Documentação Instalada
36.9.2. Sites Úteis
37. Automated Tasks
37.1. Cron
37.1.1. Configurando Tarefas no Cron
37.1.2. Controlando Acesso ao Cron
37.1.3. Iniciando e Parando o Serviço
37.2. At e Batch
37.2.1. Configurando Trabalhos com At
37.2.2. Configurando Trabalhos com o Batch
37.2.3. Visualizando Trabalhos Pendentes
37.2.4. Opções Adicionais de Linha de Comando
37.2.5. Controlando o Acesso a At e Batch
37.2.6. Iniciando e Parando o Serviço
37.3. Recursos Adicionais
37.3.1. Documentação Instalada
38. Arquivos de Registro
38.1. Localizando Arquivos de Registro
38.2. Visualizando Arquivos de Registro
38.3. Adding a Log File
38.4. Localizando Arquivos de Registro
V. Monitoramento de Sistema
39. SystemTap
39.1. Introdução
39.2. Implementação
39.3. Usando o SystemTap
39.3.1. Rastrear
40. Coletando Informações do Sistema
40.1. Processos do Sistema
40.2. Uso da Memória
40.3. Sistemas de Arquivos
40.4. Hardware
40.5. Recursos Adicionais
40.5.1. Documentação Instalada
41. OProfile
41.1. Visão Geral das Ferramentas
41.2. Configurando o OProfile
41.2.1. Especificando o Kernel
41.2.2. Determinando os Eventos a Monitorar
41.2.3. Separando os Perfis do Kernel e do Espaço do Usuário
41.3. Iniciando e Parando o OProfile
41.4. Salvando Dados
41.5. Analisando os Dados
41.5.1. Using opreport
41.5.2. Using opreport on a Single Executable
41.5.3. Getting more detailed output on the modules
41.5.4. Using opannotate
41.6. Understanding /dev/oprofile/
41.7. Uso do Exemplo
41.8. Interface Gráfica
41.9. Recursos Adicionais
41.9.1. Documentação Instalada
41.9.2. Sites Úteis
VI. Kernel e Configuração de Driver
42. Atualizando o Kernel Manualmente
42.1. Visão Geral dos Pacotes do Kernel
42.2. Preparando para o Upgrade
42.3. Fazendo o download do Kernel Atualizado
42.4. Executando a Atualização
42.5. Verificando a Imagem de Disco RAM Inicial
42.6. Verificando o Carregador de Inicialização
42.6.1. Sistemas x86
42.6.2. Sistemas Itanium
42.6.3. Sistemas IBM S/390 e IBM System z
42.6.4. Sistemas IBM eServer iSeries
42.6.5. Sistemas IBM eServer pSeries
43. General Parameters and Modules
43.1. Kernel Module Utilities
43.2. Persistent Module Loading
43.3. Specifying Module Parameters
43.4. Storage parameters
43.5. Ethernet Parameters
43.5.1. Using Multiple Ethernet Cards
43.5.2. The Channel Bonding Module
43.6. Additional Resources
43.6.1. Installed Documentation
43.6.2. Useful Websites
44. The kdump Crash Recovery Service
44.1. Configuring the kdump Service
44.1.1. Configuring the kdump at First Boot
44.1.2. Using the Kernel Dump Configuration Utility
44.1.3. Configuring kdump on the Command Line
44.1.4. Testing the Configuration
44.2. Analyzing the Core Dump
44.2.1. Displaying the Message Buffer
44.2.2. Displaying a Backtrace
44.2.3. Displaying a Process Status
44.2.4. Displaying Virtual Memory Information
44.2.5. Displaying Open Files
44.3. Additional Resources
44.3.1. Installed Documentation
44.3.2. Useful Websites
VII. Autenticação e Segurança
45. Visão Geral de Segurança
45.1. Introdução à Segurança
45.1.1. What is Computer Security?
45.1.2. Security Controls
45.1.3. Conclusion
45.2. Avaliação de Vulnerabilidade
45.2.1. Pensando Como o Inimigo
45.2.2. Definindo Avaliação e Testes
45.2.3. Avaliando as Ferramentas
45.3. Atacantes e Vulnerabilidades
45.3.1. Uma Breve História sobre Hackers
45.3.2. Ameaças à Segurança da Rede
45.3.3. Ameaças à Segurança do Servidor
45.3.4. Ameaças à Segurança de Estações de Trabalho e PCs
45.4. Exploits e Ataques Freqüentes
45.5. Atualizações de Segurança
45.5.1. Atualizando Pacotes
46. Assegurando sua Rede de Trabalho
46.1. Segurança de Estações de Trabalho
46.1.1. Avaliando a Segurança de Estações de Trabalho
46.1.2. Segurança do BIOS e do Carregador de Inicialização
46.1.3. Segurança da Senha
46.1.4. Controles Administrativos
46.1.5. Serviços de Rede Disponíveis
46.1.6. Firewalls Pessoais
46.1.7. Ferramentas de Comunicação com Segurança Aprimorada
46.2. Segurança do Servidor
46.2.1. Protegendo Serviços com TCP Wrappers e xinetd
46.2.2. Protegendo o Portmap
46.2.3. Protegendo o NIS
46.2.4. Protegendo o NFS
46.2.5. Protegendo o Servidor HTTP Apache
46.2.6. Protegendo o FTP
46.2.7. Protegendo o Sendmail
46.2.8. Verificando Quais Portas estão Escutando
46.3. Single Sign-on (SSO)
46.3.1. Introdução
46.3.2. Iniciando seu Cartão Inteligente
46.3.3. Como Funciona o Registro do Cartão Inteligente
46.3.4. Como Funciona a Autenticação do Cartão Inteligente
46.3.5. Configurando o Firefox para usar o Kerberos para SSO.
46.4. Módulos de Autenticação Plugáveis (Pluggable Authentication Modules - PAM)
46.4.1. Vantagens do PAM
46.4.2. Arquivos de Configuração do PAM
46.4.3. Formato do Arquivo de Configuração do PAM
46.4.4. Exemplos de Arquivos de Configuração do PAM
46.4.5. Criando Módulos PAM
46.4.6. O PAM e o Caching de Credenciais Administrativas
46.4.7. O PAM e a Propriedade de Dispositivos
46.4.8. Recursos Adicionais
46.5. TCP Wrappers e xinetd
46.5.1. TCP Wrappers
46.5.2. Arquivos de Configuração do TCP Wrappers
46.5.3. xinetd
46.5.4. Arquivos de Configuração do xinetd
46.5.5. Recursos Adicionais
46.6. Kerberos
46.6.1. O que é o Kerberos?
46.6.2. Terminologia do Kerberos
46.6.3. Como o Kerberos Funciona
46.6.4. Kerberos e PAM
46.6.5. Configurando o Servidor Kerberos 5
46.6.6. Configurando um Cliente Kerberos 5
46.6.7. Mapeamento Domínio-para-território
46.6.8. Configurando KDCs Secundários
46.6.9. Configurando a Autenticação Cross-Realm - (Cross Realm Authentication)
46.6.10. Recursos Adicionais
46.7. Redes Privadas Virtuais (Virtual Private Networks - VPNs)
46.7.1. Como um VPN Funciona?
46.7.2. VPNs e o Red Hat Enterprise Linux
46.7.3. IPsec
46.7.4. Criando uma Conexão IPsec
46.7.5. Instalação do IPsec
46.7.6. Configuração Host-a-Host do IPsec
46.7.7. Configuração Rede-a-Rede do IPsec
46.7.8. Iniciando e Parando uma Conexão IPsecConnection
46.8. Firewalls
46.8.1. Netfilter 6
46.8.2. Configurações Básicas de Firewall
46.8.3. Usando IPTables
46.8.4. Filtros de IPTables Comuns
46.8.5. Regras FORWARD e NAT
46.8.6. Software Malicioso e Endereços IP Falsificados (spoofed)
46.8.7. IPTables e Rastreamento de Conexão
46.8.8. IPv6
46.8.9. Recursos Adicionais
46.9. IPTables
46.9.1. Filtragem de Pacotes
46.9.2. Diferenças entre IPTables e IPChains
46.9.3. Opções de Comando para o IPTables
46.9.4. Salvando Regras do IPTables
46.9.5. Scripts de Controle do IPTables
46.9.6. IPTables e IPv6
46.9.7. Recursos Adicionais
47. Segurança e SELinux
47.1. Mecanismos de Controle de Acesso (ACM)
47.1.1. Controle de Acesso Discricionário (DAC)
47.1.2. Lista de Controle de Acesso (ACLs)
47.1.3. Controle de Acesso Obrigatório (MAC)
47.1.4. Controle de Acesso baseado na Função (RBAC)
47.1.5. Segurança de Nível Múltiplo (MLS)
47.1.6. Segurança de Categoria Múltipla (MCS)
47.2. Introdução ao SELinux
47.2.1. Visão Geral do SELinux
47.2.2. Arquivos Relacionados ao SELinux
47.2.3. Recursos Adicionais
47.3. Breves Fundamentos e História do SELinux
47.4. Segurança de Categoria Múltipla (MCS)
47.4.1. Apresentação
47.4.2. Aplicativos para Segurança de Categoria Múltipla.
47.4.3. SELinux Conteúdo de Segurança
47.5. Iniciando com a Segurança de Categoria Múltipla (MCS)
47.5.1. Introdução
47.5.2. Comparing SELinux and Standard Linux User Identities
47.5.3. Configuring Categories
47.5.4. Assigning Categories to Users
47.5.5. Assigning Categories to Files
47.6. Segurança de Nível Múltiplo (MLS)
47.6.1. Porque Nível Múltiplo?
47.6.2. Níveis de Segurança, Objetos e Assuntos.
47.6.3. Política MLS
47.6.4. Certificação LSPP
47.7. Visão Geral da Política SELinux
47.7.1. O que é a Política SELinux?
47.7.2. Onde está a Política
47.7.3. A Função da Política no Processo de Inicialização
47.7.4. Classes de Objeto e Permissões
47.8. Visão Geral da Política Alvo
47.8.1. O que é Política Alvo?
47.8.2. Arquivos e Diretórios de Política Alvo.
47.8.3. Entendendo os Usuários e Funções na Política Alvo.
48. Trabalhando com SELinux
48.1. End User Control of SELinux
48.1.1. Moving and Copying Files
48.1.2. Checking the Security Context of a Process, User, or File Object
48.1.3. Relabeling a File or Directory
48.1.4. Creating Archives That Retain Security Contexts
48.2. Administrator Control of SELinux
48.2.1. Viewing the Status of SELinux
48.2.2. Relabeling a File System
48.2.3. Managing NFS Home Directories
48.2.4. Granting Access to a Directory or a Tree
48.2.5. Backing Up and Restoring the System
48.2.6. Enabling or Disabling Enforcement
48.2.7. Enable or Disable SELinux
48.2.8. Changing the Policy
48.2.9. Specifying the Security Context of Entire File Systems
48.2.10. Changing the Security Category of a File or User
48.2.11. Running a Command in a Specific Security Context
48.2.12. Useful Commands for Scripts
48.2.13. Changing to a Different Role
48.2.14. When to Reboot
48.3. Controle Analítico do SELinux
48.3.1. Habilitando a Auditoria Kernel
48.3.2. Despejo e Visualização de Logs.
49. Padronizando a Política do SELinux
49.1. Apresentação
49.1.1. Política modular
49.2. Construindo um Módulo de Política Local
49.2.1. Usar o audit2 permite a Construção de um Módulo de Política Local.
49.2.2. Analisando o Arquivo Tipo Enforcement (TE)
49.2.3. Carregando o Pacote de Política
50. Referências
VIII. Treinamento e Certificação Red Hat
51. Treinamento Red Hat e Certificação
51.1. Três Formas de Treinar
51.2. Centro de Recurso Profissional de Certificação Microsoft
52. Caminhos de Certificação
52.1. Testes de Avaliação Grátis
53. RH033: Red Hat Linux Essentials
53.1. Descrição do Curso
53.1.1. Pré-requisitos
53.1.2. Objetivo
53.1.3. Público
53.1.4. Objetivo dos Cursos
53.1.5. Cursos de acompanhamento
54. RH035: Red Hat Linux Essentials para Profissionais de Windows
54.1. Descrição do Curso
54.1.1. Pré-requisitos
54.1.2. Objetivo
54.1.3. Público
54.1.4. Objetivo dos Cursos
54.1.5. Cursos de acompanhamento
55. RH133: Administração de Sistemas da Red Hat Linux e Certificação (RHCT) Técnica da Red Hat Certificada.
55.1. Descrição do Curso
55.1.1. Pré-requisitos
55.1.2. Objetivo
55.1.3. Público
55.1.4. Objetivo dos Cursos
55.1.5. Cursos de acompanhamento
56. prova RH202 RHCT - A credencial que mais cresce em todo o Linux.
56.1. Descrição do Curso
56.1.1. Pré-requisitos
57. RH253 Administração de Segurança e Rede de Trabalho da Red Hat Linux
57.1. Descrição do Curso
57.1.1. Pré-requisitos
57.1.2. Objetivo
57.1.3. Público
57.1.4. Objetivo dos Cursos
57.1.5. Cursos de acompanhamento
58. RH300: O curso de rastreamento rápido do RHCE ( e exames do RHCE)
58.1. Descrição do Curso
58.1.1. Pré-requisitos
58.1.2. Objetivo
58.1.3. Público
58.1.4. Objetivo dos Cursos
58.1.5. Cursos de acompanhamento
59. AVALIAÇÃO RH302 RHCE
59.1. Descrição do Curso
59.1.1. Pré-requisistos
59.1.2. Conteúdo
60. RHSS333: Segurança empresarial da RED HAT: serviços de rede de trabalho
60.1. Descrição do Curso
60.1.1. Pré-requisitos
60.1.2. Objetivo
60.1.3. Público
60.1.4. Objetivo dos Cursos
60.1.5. Cursos de acompanhamento
61. RH401: Gerenciamento de Implementação e sistemas da Red Hat Enterprise
61.1. Descrição do Curso
61.1.1. Pré-requisitos
61.1.2. Objetivo
61.1.3. Público
61.1.4. Objetivo dos Cursos
61.1.5. Cursos de acompanhamento
62. RH423 Autenticação e Serviços de Diretório da Red Hat Enterprise
62.1. Descrição do Curso
62.1.1. Pré-requisitos
62.1.2. Objetivo
62.1.3. Público
62.1.4. Objetivo dos Cursos
62.1.5. Cursos de acompanhamento
63. SELinux Courses
63.1. RHS427: Introdução ao SELinux e Política Alvo da Red Hat
63.1.1. Público
63.1.2. Sumário do Curso
63.2. RHS429: Red Hat Enterprise SELinux Policy Administration
64. RH436 Gerenciamento de armazenamento da Red Hat Enterprise
64.1. Descrição do Curso
64.1.1. Pré-requisitos
64.1.2. Objetivo
64.1.3. Público
64.1.4. Objetivo dos Cursos
64.1.5. Cursos de acompanhamento
65. RH442: sistema de monitoração e ajuste de desempenho da Red Hat Enterprise
65.1. Descrição de Curso
65.1.1. Pré-requisitos
65.1.2. Objetivo
65.1.3. Público
65.1.4. Objetivo dos Cursos
65.1.5. Cursos de acompanhamento
66. Red Hat Enterprise Linux Cursos de Desenvolvedores
66.1. RHD143: Origens de Programação da Red Hat Linux
66.2. RHD221 Drivers de Dispositivo Red Hat Linux
66.3. RHD236 Red Hat Linux Kernel Internals
66.4. RHD256 Portal e Desenvolvimento de Aplicativo Red Hat Linux
67. Cursos JBoss
67.1. RHD161 JBoss e EJB3 para Java
67.1.1. Pré-requisitos
67.2. RHD163 JBoss para Desenvolvedores da Web
67.2.1. Pré-requisitos
67.3. RHD167: JBOSS - HIBERNATE ESSENTIALS
67.3.1. Pré-requisitos
67.3.2. Sumário do Curso
67.4. RHD267: JBOSS - HIBERNATE AVANÇADO
67.4.1. Pré-requisitos
67.5. RHD261:JBOSS para desenvolvedores de J2EE avançados
67.5.1. Pré-requisitos
67.6. RH336: JBOSS para Administradores
67.6.1. Pré-requisitos
67.6.2. Sumário do Curso
67.7. RHD439: JBoss Clustering
67.7.1. Pré-requisitos
67.8. RHD449: JBoss jBPM
67.8.1. Descrição
67.8.2. Pré-requisitos
67.9. Regras RHD451 JBoss
67.9.1. Pré-requisitos
A. Revision History
B. Colophon

Introdução

Bem-vindo ao Guia de Implementação do Red Hat Enterprise Linux .
O Guia de Implementação do Red Hat Enterprise Linux contém informações sobre como padronizar seu sistema do Red Hat Enterprise Linux para melhor se adequar às suas necessidades. Se você estiver à procura de um guia compreensivo e prático para configurar e padronizar seu sistema, este manual se adequa perfeitamente à você.
Este manual discute muitos tópicos intermediários tais como os seguintes:
  • Configurando uma placa de interface de rede (NIC)
  • Configurando uma Rede de Trabalho Privada Virtual (VPN)
  • Configurando Samba shares
  • Gerenciando seu software com RPM
  • Determinando informações sobre seu sistema
  • Atualizando seu kernel
Este manual está dividido nas seguintes categorias principais:
  • Sistemas de Arquivos
  • Gerenciamento de pacotes
  • Configuração relacionada à rede
  • Configuração de Sistema
  • Monitoração de Sistema
  • Kernel e Configuração de Drive
  • Segurança e Autenticação
  • Certificação e Treinamento Red Hat
Este guia presume que você possui um entendimento básico de seu sistema Red Hat Enterprise Linux. Se você precisar de ajuda para instalar o Red Hat Enterprise Linux, consulte o Guia de Instalação do Red Hat Enterprise Linux .

1. Convenções de Documentos

Neste manual, certas palavras são representadas em fontes diferentes, tipo de letras, tamanhos e pesos. Este realce é sistemático pois palavras diferentes são representadas no mesmo estilo para indicar sua inclusão em uma categoria específica. Os tipos de palavras que são representados desta forma incluem o seguinte:
command
Linux commands (and other operating system commands, when used) are represented this way. This style should indicate to you that you can type the word or phrase on the command line and press Enter to invoke a command. Sometimes a command contains words that would be displayed in a different style on their own (such as file names). In these cases, they are considered to be part of the command, so the entire phrase is displayed as a command. For example:
Use the cat testfile command to view the contents of a file, named testfile, in the current working directory.
file name
Nomes de arquivos, nomes de diretórios, caminhos e nomes de pacotes RPM são representados desta forma. Este estilo indica que um arquivo em particular ou diretório existem com aquele nome no seu sistema. Exemplos:
The .bashrc file in your home directory contains bash shell definitions and aliases for your own use.
The /etc/fstab file contains information about different system devices and file systems.
Install the webalizer RPM if you want to use a Web server log file analysis program.
application
Este estilo indica que o programa é um aplicativo de usuário final (oposto ao software de sistemas). Por exemplo:
Use Mozilla to browse the Web.
tecla
Uma tecla do teclado é apresentada neste estilo. Por exemplo:
Para usar a conclusão Tab, para listar arquivos específicos em um diretório, digite ls seguido de umcaractere e finalmente pressione a tecla Tab. Seu terminal mostrará a lista de arquivos no diretório que começar com esta letra.
key+combination
A combinação de teclas é representada da seguinte forma:
The Ctrl+Alt+Backspace key combination exits your graphical session and returns you to the graphical login screen or the console.
text found on a GUI interface
Um título, palavra ou frase, encontrada em uma tela ou janela de interface GUI são exibidos neste estilo. O texto exibido neste estilo indica uma tela ou um elemento GUI em específico em uma tela GUI (tal como o texto associado à caixa de seleção ou campo). Exemplo:
Select the Require Password checkbox if you would like your screensaver to require a password before stopping.
top level of a menu on a GUI screen or window
Uma palavra neste estilo indica que a palavra é o nível mais alto de um menu suspenso. Se você clicar em uma palavra na tela GUI, deverá aparecer o restante do menu.
Under File on a GNOME terminal, the New Tab option allows you to open multiple shell prompts in the same window.
As instruções para inserir uma sequência de comandos a partir do menu GUI, se parecem com o exemplo a seguir:
Go to Applications (the main menu on the panel) > Programming > Emacs Text Editor to start the Emacs text editor.
button on a GUI screen or window
Este estilo indica que um texto pode ser encontrado em um botão clicável em uma tela GUI. Por exemplo:
Click on the Back button to return to the webpage you last viewed.
computer output
O texto neste estilo indica o texto exibido para uma janela de comando, tais como mensagens de erro e respostas à comandos. Por exemplo:
The ls command displays the contents of a directory. For example:
Desktop    about.html    logs     paulwesterberg.png
Mail    backupfiles    mail     reports
A saída retornou em resposta ao comando (neste caso, o conteúdo do diretório) é apresentado neste estilo.
prompt
Um prompt, ou seja, uma forma do computador indicar que está pronto para você inserir algo, é apresentado neste estilo. Exemplos:
$
#
[stephen@maturin stephen]$
leopard login:
user input
Text that the user types, either on the command line or into a text box on a GUI screen, is displayed in this style. In the following example, text is displayed in this style:
To boot your system into the text based installation program, you must type in the text command at the boot: prompt.
<replaceable>
O texto utilizado em exemplos que precise ser substituído com dados fornecidos pelo usuário é apresentado neste estilo. No seguinte exemplo, <version-number> é apresentado neste estilo:
The directory for the kernel source is /usr/src/kernels/<version-number>/, where <version-number> is the version and type of kernel installed on this system.
Além disso, utilizamos de diferentes estratégias para chamar sua atenção sobre algumas informações específicas. Em ordem de urgência, estes ítens são marcados como uma nota, dica, importante, atenção ou aviso. Por exemplo:

Nota

Lembre-se que o Linux diferencia entre maiúsculas e minúsculas. Em outras palavras, uma rosa não é uma ROSA e nem uma rOsA.

Tip

The directory /usr/share/doc/ contains additional documentation for packages installed on your system.

Importante

Se você modificar o arquivo de configuração DHCP, as mudanças não surtem efeito até que você reinicie o daemon DHCP.

Atenção

Não realize as tarefas de rotina com uma conta de usuário root —, use uma conta de usuário regular, a não ser que você precise usar a conta root para realizar tarefas de administração de sistemas.

Aviso

Tenha cuidado para remover somente partições necessárias. A remoção de outras partições poderia resultar em perda de dados ou um ambiente de sistemas corrompido.

2. Envie-nos sua Opinião

If you find an error in the Red Hat Enterprise Linux Deployment Guide, or if you have thought of a way to make this manual better, we would like to hear from you! Submit a report in Bugzilla (http://bugzilla.redhat.com/bugzilla/) against the component Deployment_Guide.
Se você tiver alguma sugestão para melhorar a documentação, tente ser o mais específico possível. Se encontrou um erro, por favor inclua o número da seção e alguns trechos do texto próximo ao erro para que possamos encontrá-lo facilmente.

Parte I. Sistemas de Arquivos

File system refers to the files and directories stored on a computer. A file system can have different formats called file system types. These formats determine how the information is stored as files and directories. Some file system types store redundant copies of the data, while some file system types make hard drive access faster. This part discusses the ext3, swap, RAID, and LVM file system types. It also discusses the parted utility to manage partitions and access control lists (ACLs) to customize file permissions.

Índice

1. File System Structure
1.1. Why Share a Common Structure?
1.2. Overview of File System Hierarchy Standard (FHS)
1.2.1. FHS Organization
1.3. Special File Locations Under Red Hat Enterprise Linux
2. Using the mount Command
2.1. Listing Currently Mounted File Systems
2.2. Mounting a File System
2.2.1. Specifying the File System Type
2.2.2. Specifying the Mount Options
2.2.3. Sharing Mounts
2.2.4. Moving a Mount Point
2.3. Unmounting a File System
2.4. Additional Resources
2.4.1. Installed Documentation
2.4.2. Useful Websites
3. O Sistema de Arquivo ext3
3.1. Características do ext3
3.2. Criando um Sistema de Arquivo ext3
3.3. Convertendo para um Sistema de Arquivo ext3
3.4. Revertendo para um Sistema de Arquivo ext2
4. The proc File System
4.1. A Virtual File System
4.1.1. Viewing Virtual Files
4.1.2. Changing Virtual Files
4.2. Top-level Files within the proc File System
4.2.1. /proc/apm
4.2.2. /proc/buddyinfo
4.2.3. /proc/cmdline
4.2.4. /proc/cpuinfo
4.2.5. /proc/crypto
4.2.6. /proc/devices
4.2.7. /proc/dma
4.2.8. /proc/execdomains
4.2.9. /proc/fb
4.2.10. /proc/filesystems
4.2.11. /proc/interrupts
4.2.12. /proc/iomem
4.2.13. /proc/ioports
4.2.14. /proc/kcore
4.2.15. /proc/kmsg
4.2.16. /proc/loadavg
4.2.17. /proc/locks
4.2.18. /proc/mdstat
4.2.19. /proc/meminfo
4.2.20. /proc/misc
4.2.21. /proc/modules
4.2.22. /proc/mounts
4.2.23. /proc/mtrr
4.2.24. /proc/partitions
4.2.25. /proc/pci
4.2.26. /proc/slabinfo
4.2.27. /proc/stat
4.2.28. /proc/swaps
4.2.29. /proc/sysrq-trigger
4.2.30. /proc/uptime
4.2.31. /proc/version
4.3. Directories within /proc/
4.3.1. Process Directories
4.3.2. /proc/bus/
4.3.3. /proc/driver/
4.3.4. /proc/fs
4.3.5. /proc/ide/
4.3.6. /proc/irq/
4.3.7. /proc/net/
4.3.8. /proc/scsi/
4.3.9. /proc/sys/
4.3.10. /proc/sysvipc/
4.3.11. /proc/tty/
4.3.12. /proc/<PID>/
4.4. Using the sysctl Command
4.5. Additional Resources
4.5.1. Installed Documentation
4.5.2. Useful Websites
5. Redundant Array of Independent Disks (RAID)
5.1. What is RAID?
5.1.1. Who Should Use RAID?
5.1.2. Hardware RAID versus Software RAID
5.1.3. RAID Levels and Linear Support
5.2. Configuring Software RAID
5.2.1. riando uma Nova Partição RAID
5.2.2. Creating the RAID Devices and Mount Points
5.3. Managing Software RAID
5.3.1. Reviewing RAID Configuration
5.3.2. Creating a New RAID Device
5.3.3. Replacing a Faulty Device
5.3.4. Extending a RAID Device
5.3.5. Removing a RAID Device
5.3.6. Preserving the Configuration
5.4. Additional Resources
5.4.1. Installed Documentation
6. Espaço Virtual (swap space)
6.1. O que é Espaço Virtual?
6.2. Adicionando Espaço Virtual
6.2.1. Extending Swap on an LVM2 Logical Volume
6.2.2. Creating an LVM2 Logical Volume for Swap
6.2.3. Creating a Swap File
6.3. Removendo Espaço Virtual
6.3.1. Reducing Swap on an LVM2 Logical Volume
6.3.2. Removing an LVM2 Logical Volume for Swap
6.3.3. Removing a Swap File
6.4. Movendo Espaço Virtual
7. Gerenciando o Armazenamento de Disco
7.1. Standard Partitions using parted
7.1.1. Visualizando a Tabela de Partições
7.1.2. Criando uma Partição
7.1.3. Removendo uma Partição
7.1.4. Redimensionando uma Partição
7.2. LVM Partition Management
8. Implementando Quotas de Disco
8.1. Configurando Quotas de Disco
8.1.1. Habilitando Quotas
8.1.2. Remontando os Sistemas de Arquivo
8.1.3. Criando Arquivos de Banco de Dados de Quota
8.1.4. Atribuindo Quotas por Usuário
8.1.5. Atribuindo Quotas por Grupo
8.1.6. Configurando o Tempo de Carência para Limites Suaves.
8.2. Administrando Quotas de Disco
8.2.1. Habilitando e Desabilitando
8.2.2. Reportando em Quotas de Disco
8.2.3. Mantendo as Quotas Exatas
8.3. Recursos Adicionais
8.3.1. Documentação Instalada
8.3.2. Livros Relacionados
9. Access Control Lists
9.1. Montando Sistemas de Arquivo
9.1.1. NFS
9.2. Definindo ACLs de Acesso
9.3. Definindo ACLs Default
9.4. Recuperando ACLs
9.5. Documentando Sistemas de Arquivo Com ACLs
9.6. Compatibilidade com Sistemas mais Antigos
9.7. Recursos Adicionais
9.7.1. Documentação Instalada
9.7.2. Sites Úteis
10. LVM (Logical Volume Manager)
10.1. What is LVM?
10.1.1. What is LVM2?
10.2. Configuração do LVM
10.3. Automatic Partitioning
10.4. Manual LVM Partitioning
10.4.1. Creating the /boot Partition
10.4.2. Creating the LVM Physical Volumes
10.4.3. Creating the LVM Volume Groups
10.4.4. Creating the LVM Logical Volumes
10.5. Using the LVM utility system-config-lvm
10.5.1. Utilizing uninitialized entities
10.5.2. Adding Unallocated Volumes to a volume group
10.5.3. Migrating extents
10.5.4. Adding a new hard disk using LVM
10.5.5. Adding a new volume group
10.5.6. Extending a volume group
10.5.7. Editing a Logical Volume
10.6. Additional Resources
10.6.1. Installed Documentation
10.6.2. Useful Websites

Capítulo 1. File System Structure

1.1. Why Share a Common Structure?

The file system structure is the most basic level of organization in an operating system. Almost all of the ways an operating system interacts with its users, applications, and security model are dependent upon the way it organizes files on storage devices. Providing a common file system structure ensures users and programs are able to access and write files.
File systems break files down into two logical categories:
  • Shareable vs. unshareable files
  • Variable vs. static files
Shareable files are those that can be accessed locally and by remote hosts; unshareable files are only available locally. Variable files, such as documents, can be changed at any time; static files, such as binaries, do not change without an action from the system administrator.
The reason for looking at files in this manner is to help correlate the function of the file with the permissions assigned to the directories which hold them. The way in which the operating system and its users interact with a given file determines the directory in which it is placed, whether that directory is mounted with read-only or read/write permissions, and the level of access each user has to that file. The top level of this organization is crucial. Access to the underlying directories can be restricted or security problems could manifest themselves if, from the top level down, it does not adhere to a rigid structure.

1.2. Overview of File System Hierarchy Standard (FHS)

Red Hat Enterprise Linux uses the Filesystem Hierarchy Standard (FHS) file system structure, which defines the names, locations, and permissions for many file types and directories.
The FHS document is the authoritative reference to any FHS-compliant file system, but the standard leaves many areas undefined or extensible. This section is an overview of the standard and a description of the parts of the file system not covered by the standard.
Compliance with the standard means many things, but the two most important are compatibility with other compliant systems and the ability to mount a /usr/ partition as read-only. This second point is important because the directory contains common executables and should not be changed by users. Also, since the /usr/ directory is mounted as read-only, it can be mounted from the CD-ROM or from another machine via a read-only NFS mount.

1.2.1. FHS Organization

The directories and files noted here are a small subset of those specified by the FHS document. Refer to the latest FHS document for the most complete information.
The complete standard is available online at http://www.pathname.com/fhs/.

1.2.1.1. The /boot/ Directory

The /boot/ directory contains static files required to boot the system, such as the Linux kernel. These files are essential for the system to boot properly.

Warning

Do not remove the /boot/ directory. Doing so renders the system unbootable.

1.2.1.2. The /dev/ Directory

The /dev/ directory contains device nodes that either represent devices that are attached to the system or virtual devices that are provided by the kernel. These device nodes are essential for the system to function properly. The udev daemon takes care of creating and removing all these device nodes in /dev/.
Devices in the /dev directory and subdirectories are either character (providing only a serial stream of input/output) or block (accessible randomly). Character devices include mouse, keyboard, modem while block devices include hard disk, floppy drive etc. If you have GNOME or KDE installed in your system, devices such as external drives or cds are automatically detected when connected (e.g via usb) or inserted (e.g via CD or DVD drive) and a popup window displaying the contents is automatically displayed. Files in the /dev directory are essential for the system to function properly.
Tabela 1.1. Examples of common files in the /dev
File Description
/dev/hda The master device on primary IDE channel.
/dev/hdb The slave device on primary IDE channel.
/dev/tty0 The first virtual console.
/dev/tty1 The second virtual console.
/dev/sda The first device on primary SCSI or SATA channel.
/dev/lp0 The first parallel port.

1.2.1.3. The /etc/ Directory

The /etc/ directory is reserved for configuration files that are local to the machine. No binaries are to be placed in /etc/. Any binaries that were once located in /etc/ should be placed into /sbin/ or /bin/.
Examples of directories in /etc are the X11/ and skel/:
/etc
   |- X11/
   |- skel/
The /etc/X11/ directory is for X Window System configuration files, such as xorg.conf. The /etc/skel/ directory is for "skeleton" user files, which are used to populate a home directory when a user is first created. Applications also store their configuration files in this directory and may reference them when they are executed.

1.2.1.4. The /lib/ Directory

The /lib/ directory should contain only those libraries needed to execute the binaries in /bin/ and /sbin/. These shared library images are particularly important for booting the system and executing commands within the root file system.

1.2.1.5. The /media/ Directory

The /media/ directory contains subdirectories used as mount points for removable media such as usb storage media, DVDs, CD-ROMs, and Zip disks.

1.2.1.6. The /mnt/ Directory

The /mnt/ directory is reserved for temporarily mounted file systems, such as NFS file system mounts. For all removable media, please use the /media/ directory. Automatically detected removable media will be mounted in the /media directory.

Note

The /mnt directory must not be used by installation programs.

1.2.1.7. The /opt/ Directory

The /opt/ directory provides storage for most application software packages.
A package placing files in the /opt/ directory creates a directory bearing the same name as the package. This directory, in turn, holds files that otherwise would be scattered throughout the file system, giving the system administrator an easy way to determine the role of each file within a particular package.
For example, if sample is the name of a particular software package located within the /opt/ directory, then all of its files are placed in directories inside the /opt/sample/ directory, such as /opt/sample/bin/ for binaries and /opt/sample/man/ for manual pages.
Packages that encompass many different sub-packages, data files, extra fonts, clipart etc are also located in the /opt/ directory, giving that large package a way to organize itself. In this way, our sample package may have different tools that each go in their own sub-directories, such as /opt/sample/tool1/ and /opt/sample/tool2/, each of which can have their own bin/, man/, and other similar directories.

1.2.1.8. The /proc/ Directory

The /proc/ directory contains special files that either extract information from or send information to the kernel. Examples include system memory, cpu information, hardware configuration etc.
Due to the great variety of data available within /proc/ and the many ways this directory can be used to communicate with the kernel, an entire chapter has been devoted to the subject. For more information, refer to Capítulo 4, The proc File System.

1.2.1.9. The /sbin/ Directory

The /sbin/ directory stores executables used by the root user. The executables in /sbin/ are used at boot time, for system administration and to perform system recovery operations. Of this directory, the FHS says:
/sbin contains binaries essential for booting, restoring, recovering, and/or repairing the system in addition to the binaries in /bin. Programs executed after /usr/ is known to be mounted (when there are no problems) are generally placed into /usr/sbin. Locally-installed system administration programs should be placed into /usr/local/sbin.
At a minimum, the following programs should be in /sbin/:
arp, clock,
halt, init,
fsck.*, grub,
ifconfig, mingetty,
mkfs.*, mkswap,
reboot, route,
shutdown, swapoff,
swapon

1.2.1.10. The /srv/ Directory

The /srv/ directory contains site-specific data served by your system running Red Hat Enterprise Linux. This directory gives users the location of data files for a particular service, such as FTP, WWW, or CVS. Data that only pertains to a specific user should go in the /home/ directory.

1.2.1.11. The /sys/ Directory

The /sys/ directory utilizes the new sysfs virtual file system specific to the 2.6 kernel. With the increased support for hot plug hardware devices in the 2.6 kernel, the /sys/ directory contains information similarly held in /proc/, but displays a hierarchical view of specific device information in regards to hot plug devices.

1.2.1.12. The /usr/ Directory

The /usr/ directory is for files that can be shared across multiple machines. The /usr/ directory is often on its own partition and is mounted read-only. At a minimum, the following directories should be subdirectories of /usr/:
/usr
   |- bin/
   |- etc/
   |- games/
   |- include/
   |- kerberos/
   |- lib/
   |- libexec/
   |- local/
   |- sbin/
   |- share/
   |- src/
   |- tmp -> ../var/tmp/
Under the /usr/ directory, the bin/ subdirectory contains executables, etc/ contains system-wide configuration files, games is for games, include/ contains C header files, kerberos/ contains binaries and other Kerberos-related files, and lib/ contains object files and libraries that are not designed to be directly utilized by users or shell scripts. The libexec/ directory contains small helper programs called by other programs, sbin/ is for system administration binaries (those that do not belong in the /sbin/ directory), share/ contains files that are not architecture-specific, src/ is for source code.

1.2.1.13. The /usr/local/ Directory

The FHS says:
The /usr/local hierarchy is for use by the system administrator when installing software locally. It needs to be safe from being overwritten when the system software is updated. It may be used for programs and data that are shareable among a group of hosts, but not found in /usr.
The /usr/local/ directory is similar in structure to the /usr/ directory. It has the following subdirectories, which are similar in purpose to those in the /usr/ directory:
/usr/local
	|- bin/
	|- etc/
	|- games/
	|- include/
	|- lib/
	|- libexec/
	|- sbin/
	|- share/
	|- src/
In Red Hat Enterprise Linux, the intended use for the /usr/local/ directory is slightly different from that specified by the FHS. The FHS says that /usr/local/ should be where software that is to remain safe from system software upgrades is stored. Since software upgrades can be performed safely with RPM Package Manager (RPM), it is not necessary to protect files by putting them in /usr/local/. Instead, the /usr/local/ directory is used for software that is local to the machine.
For instance, if the /usr/ directory is mounted as a read-only NFS share from a remote host, it is still possible to install a package or program under the /usr/local/ directory.

1.2.1.14. The /var/ Directory

Since the FHS requires Linux to mount /usr/ as read-only, any programs that write log files or need spool/ or lock/ directories should write them to the /var/ directory. The FHS states /var/ is for:
...variable data files. This includes spool directories and files, administrative and logging data, and transient and temporary files.
Below are some of the directories found within the /var/ directory:
/var
   |- account/
   |- arpwatch/
   |- cache/
   |- crash/
   |- db/
   |- empty/
   |- ftp/
   |- gdm/
   |- kerberos/
   |- lib/
   |- local/
   |- lock/
   |- log/
   |- mail -> spool/mail/
   |- mailman/
   |- named/
   |- nis/
   |- opt/
   |- preserve/
   |- run/
   +- spool/
       |- at/
       |- clientmqueue/
       |- cron/
       |- cups/
       |- exim/
       |- lpd/
       |- mail/
       |- mailman/
       |- mqueue/
       |- news/
       |- postfix/
       |- repackage/
       |- rwho/
       |- samba/
       |- squid/
       |- squirrelmail/
       |- up2date/
       |- uucp
       |- uucppublic/
       |- vbox/
|- tmp/
|- tux/
|- www/
|- yp/
System log files, such as messages and lastlog, go in the /var/log/ directory. The /var/lib/rpm/ directory contains RPM system databases. Lock files go in the /var/lock/ directory, usually in directories for the program using the file. The /var/spool/ directory has subdirectories for programs in which data files are stored.

1.3. Special File Locations Under Red Hat Enterprise Linux

Red Hat Enterprise Linux extends the FHS structure slightly to accommodate special files.
Most files pertaining to RPM are kept in the /var/lib/rpm/ directory. For more information on RPM, refer to the chapter Capítulo 11, Gerenciamento de Pacotes com RPM.
The /var/cache/yum/ directory contains files used by the Package Updater, including RPM header information for the system. This location may also be used to temporarily store RPMs downloaded while updating the system. For more information about Red Hat Network, refer to Capítulo 14, Product Subscriptions and Entitlements.
Another location specific to Red Hat Enterprise Linux is the /etc/sysconfig/ directory. This directory stores a variety of configuration information. Many scripts that run at boot time use the files in this directory. Refer to Capítulo 30, The sysconfig Directory for more information about what is within this directory and the role these files play in the boot process.

Capítulo 2. Using the mount Command

On Linux, UNIX, and similar operating systems, file systems on different partitions and removable devices like CDs, DVDs, or USB flash drives can be attached to a certain point (that is, the mount point) in the directory tree, and detached again. To attach or detach a file system, you can use the mount or umount command respectively. This chapter describes the basic usage of these commands, and covers some advanced topics such as moving a mount point or creating shared subtrees.

2.1. Listing Currently Mounted File Systems

To display all currently attached file systems, run the mount command with no additional arguments:
mount
This command displays the list of known mount points. Each line provides important information about the device name, the file system type, the directory in which it is mounted, and relevant mount options in the following form:
device on directory type type (options)
By default, the output includes various virtual file systems such as sysfs, tmpfs, and others. To display only the devices with a certain file system type, supply the -t option on the command line:
mount -t type
For a list of common file system types, refer to Tabela 2.1, “Common File System Types”. For an example on how to use the mount command to list the mounted file systems, see Exemplo 2.1, “Listing Currently Mounted ext3 File Systems”.
Exemplo 2.1. Listing Currently Mounted ext3 File Systems
Usually, both / and /boot partitions are formatted to use ext3. To display only the mount points that use this file system, type the following at a shell prompt:
~]$ mount -t ext3
/dev/mapper/VolGroup00-LogVol00 on / type ext3 (rw)
/dev/vda1 on /boot type ext3 (rw)

2.2. Mounting a File System

To attach a certain file system, use the mount command in the following form:
mount [option] device directory
When the mount command is run, it reads the content of the /etc/fstab configuration file to see if the given file system is listed. This file contains a list of device names and the directory in which the selected file systems should be mounted, as well as the file system type and mount options. Because of this, when you are mounting a file system that is specified in this file, you can use one of the following variants of the command:
mount [option] directory
mount [option] device
Note that unless you are logged in as root, you must have permissions to mount the file system (see Seção 2.2.2, “Specifying the Mount Options”).

2.2.1. Specifying the File System Type

In most cases, mount detects the file system automatically. However, there are certain file systems, such as NFS (Network File System) or CIFS (Common Internet File System), that are not recognized, and need to be specified manually. To specify the file system type, use the mount command in the following form:
mount -t type device directory
Tabela 2.1, “Common File System Types” provides a list of common file system types that can be used with the mount command. For a complete list of all available file system types, consult the relevant manual page as referred to in Seção 2.4.1, “Installed Documentation”.
Tabela 2.1. Common File System Types
Type Description
ext2 The ext2 file system.
ext3 The ext3 file system.
iso9660 The ISO 9660 file system. It is commonly used by optical media, typically CDs.
jfs The JFS file system created by IBM.
nfs The NFS file system. It is commonly used to access files over the network.
nfs4 The NFSv4 file system. It is commonly used to access files over the network.
ntfs The NTFS file system. It is commonly used on machines that are running the Windows operating system.
udf The UDF file system. It is commonly used by optical media, typically DVDs.
vfat The FAT file system. It is commonly used on machines that are running the Windows operating system, and on certain digital media such as USB flash drives or floppy disks.

Exemplo 2.2. Mounting a USB Flash Drive
Older USB flash drives often use the FAT file system. Assuming that such drive uses the /dev/sdc1 device and that the /media/flashdisk/ directory exists, you can mount it to this directory by typing the following at a shell prompt as root:
~]# mount -t vfat /dev/sdc1 /media/flashdisk

2.2.2. Specifying the Mount Options

To specify additional mount options, use the command in the following form:
mount -o options
When supplying multiple options, do not insert a space after a comma, or mount will incorrectly interpret the values following spaces as additional parameters.
Tabela 2.2, “Common Mount Options” provides a list of common mount options. For a complete list of all available options, consult the relevant manual page as referred to in Seção 2.4.1, “Installed Documentation”.
Tabela 2.2. Common Mount Options
Option Description
async Allows the asynchronous input/output operations on the file system.
auto Allows the file system to be mounted automatically using the mount -a command.
defaults Provides an alias for async,auto,dev,exec,nouser,rw,suid.
exec Allows the execution of binary files on the particular file system.
loop Mounts an image as a loop device.
noauto Disallows the automatic mount of the file system using the mount -a command.
noexec Disallows the execution of binary files on the particular file system.
nouser Disallows an ordinary user (that is, other than root) to mount and unmount the file system.
remount Remounts the file system in case it is already mounted.
ro Mounts the file system for reading only.
rw Mounts the file system for both reading and writing.
user Allows an ordinary user (that is, other than root) to mount and unmount the file system.

See Exemplo 2.3, “Mounting an ISO Image” for an example usage.
Exemplo 2.3. Mounting an ISO Image
An ISO image (or a disk image in general) can be mounted by using the loop device. Assuming that the ISO image of the Fedora 14 installation disc is present in the current working directory and that the /media/cdrom/ directory exists, you can mount the image to this directory by running the following command as root:
~]# mount -o ro,loop Fedora-14-x86_64-Live-Desktop.iso /media/cdrom
Note that ISO 9660 is by design a read-only file system.

2.2.3. Sharing Mounts

Occasionally, certain system administration tasks require access to the same file system from more than one place in the directory tree (for example, when preparing a chroot environment). To address such requirements, the mount command implements the --bind option that provides a means for duplicating certain mounts. Its usage is as follows:
mount --bind old_directory new_directory
Although the above command allows a user to access the file system from both places, it does not apply on the file systems that are mounted within the original directory. To include these mounts as well, type:
mount --rbind old_directory new_directory
Additionally, to provide as much flexibility as possible, Red Hat Enterprise Linux 5.8 implements the functionality known as shared subtrees. This feature allows you to use the following four mount types:
Shared Mount
A shared mount allows you to create an exact replica of a given mount point. When a shared mount is created, any mount within the original mount point is reflected in it, and vice versa. To create a shared mount, type the following at a shell prompt:
mount --make-shared mount_point
Alternatively, you can change the mount type for the selected mount point and all mount points under it:
mount --make-rshared mount_point
Exemplo 2.4. Creating a Shared Mount Point
There are two places where other file systems are commonly mounted: the /media directory for removable media, and the /mnt directory for temporarily mounted file systems. By using a shared mount, you can make these two directories share the same content. To do so, as root, mark the /media directory as shared:
~]# mount --bind /media /media
~]# mount --make-shared /media
Then create its duplicate in /mnt by using the following command:
~]# mount --bind /media /mnt
You can now verify that a mount within /media also appears in /mnt. For example, if you have non-empty media in your CD-ROM drive and the /media/cdrom/ directory exists, run the following commands:
~]# mount /dev/cdrom /media/cdrom
~]# ls /media/cdrom
EFI  GPL  isolinux  LiveOS
~]# ls /mnt/cdrom
EFI  GPL  isolinux  LiveOS
Similarly, you can verify that any file system mounted in the /mnt directory is reflected in /media. For instance, if you have a non-empty USB flash drive that uses the /dev/sdc1 device plugged in and the /mnt/flashdisk/ directory is present, type:
~]# mount /dev/sdc1 /mnt/flashdisk
~]# ls /media/flashdisk
en-US  publican.cfg
~]# ls /mnt/flashdisk
en-US  publican.cfg

Slave Mount
A slave mount allows you to create a limited duplicate of a given mount point. When a slave mount is created, any mount within the original mount point is reflected in it, but no mount within a slave mount is reflected in its original. To create a slave mount, type the following at a shell prompt:
mount --make-slave mount_point
Alternatively, you can change the mount type for the selected mount point and all mount points under it:
mount --make-rslave mount_point
Exemplo 2.5. Creating a Slave Mount Point
Imagine you want the content of the /media directory to appear in /mnt as well, but you do not want any mounts in the /mnt directory to be reflected in /media. To do so, as root, first mark the /media directory as shared:
~]# mount --bind /media /media
~]# mount --make-shared /media
Then create its duplicate in /mnt, but mark it as slave:
~]# mount --bind /media /mnt
~]# mount --make-slave /mnt
You can now verify that a mount within /media also appears in /mnt. For example, if you have non-empty media in your CD-ROM drive and the /media/cdrom/ directory exists, run the following commands:
~]# mount /dev/cdrom /media/cdrom
~]# ls /media/cdrom
EFI  GPL  isolinux  LiveOS
~]# ls /mnt/cdrom
EFI  GPL  isolinux  LiveOS
You can also verify that file systems mounted in the /mnt directory are not reflected in /media. For instance, if you have a non-empty USB flash drive that uses the /dev/sdc1 device plugged in and the /mnt/flashdisk/ directory is present, type: :
~]# mount /dev/sdc1 /mnt/flashdisk
~]# ls /media/flashdisk
~]# ls /mnt/flashdisk
en-US  publican.cfg

Private Mount
A private mount allows you to create an ordinary mount. When a private mount is created, no subsequent mounts within the original mount point are reflected in it, and no mount within a private mount is reflected in its original. To create a private mount, type the following at a shell prompt:
mount --make-private mount_point
Alternatively, you can change the mount type for the selected mount point and all mount points under it:
mount --make-rprivate mount_point
Exemplo 2.6. Creating a Private Mount Point
Taking into account the scenario in Exemplo 2.4, “Creating a Shared Mount Point”, assume that you have previously created a shared mount point by using the following commands as root:
~]# mount --bind /media /media
~]# mount --make-shared /media
~]# mount --bind /media /mnt
To mark the /mnt directory as private, type:
~]# mount --make-private /mnt
You can now verify that none of the mounts within /media appears in /mnt. For example, if you have non-empty media in your CD-ROM drive and the /media/cdrom/ directory exists, run the following commands:
~]# mount /dev/cdrom /media/cdrom
~]# ls /media/cdrom
EFI  GPL  isolinux  LiveOS
~]# ls /mnt/cdrom
~]#
You can also verify that file systems mounted in the /mnt directory are not reflected in /media. For instance, if you have a non-empty USB flash drive that uses the /dev/sdc1 device plugged in and the /mnt/flashdisk/ directory is present, type:
~]# mount /dev/sdc1 /mnt/flashdisk
~]# ls /media/flashdisk
~]# ls /mnt/flashdisk
en-US  publican.cfg

Unbindable Mount
An unbindable mount allows you to prevent a given mount point from being duplicated whatsoever. To create an unbindable mount, type the following at a shell prompt:
mount --make-unbindable mount_point
Alternatively, you can change the mount type for the selected mount point and all mount points under it:
mount --make-runbindable mount_point
Exemplo 2.7. Creating an Unbindable Mount Point
To prevent the /media directory from being shared, as root, type the following at a shell prompt:
~]# mount --bind /media /media
~]# mount --make-unbindable /media
This way, any subsequent attempt to make a duplicate of this mount will fail with an error:
~]# mount --bind /media /mnt
mount: wrong fs type, bad option, bad superblock on /media/,
       missing code page or other error
       In some cases useful info is found in syslog - try
       dmesg | tail  or so

2.2.4. Moving a Mount Point

To change the directory in which a file system is mounted, use the following command:
mount --move old_directory new_directory
Exemplo 2.8. Moving an Existing NFS Mount Point
Imagine that you have an NFS storage that contains user directories. Assuming that this storage is already mounted in /mnt/userdirs/, as root, you can move this mount point to /home by using the following command:
~]# mount --move /mnt/userdirs /home
To verify the mount point has been moved, list the content of both directories:
~]# ls /mnt/userdirs
~]# ls /home
jill  joe

2.3. Unmounting a File System

To detach a previously mounted file system, use either of the following variants of the umount command:
umount directory
umount device
Note that unless you are logged in as root, you must have permissions to unmount the file system (see Seção 2.2.2, “Specifying the Mount Options”). See Exemplo 2.9, “Unmounting a CD” for an example usage.

Important: Make Sure the File System Is Not in Use

When a file system is in use (for example, when a process is reading a file on this file system), running the umount command will fail with an error. To determine which processes are accessing the file system, use the fuser command in the following form:
fuser -m directory
For example, to list the processes that are accessing a file system mounted to the /media/cdrom/ directory, type:
~]$ fuser -m /media/cdrom
/media/cdrom:         1793  2013  2022  2435 10532c 10672c
Exemplo 2.9. Unmounting a CD
To unmount a CD that was previously mounted to the /media/cdrom/ directory, type the following at a shell prompt:
~]$ umount /media/cdrom

2.4. Additional Resources

The following resources provide an in-depth documentation on the subject.

2.4.1. Installed Documentation

  • man 8 mount — The manual page for the mount command that provides a full documentation on its usage.
  • man 8 umount — The manual page for the umount command that provides a full documentation on its usage.
  • man 5 fstab — The manual page providing a thorough description of the /etc/fstab file format.

2.4.2. Useful Websites

  • Shared subtrees — An LWN article covering the concept of shared subtrees.
  • sharedsubtree.txt — Extensive documentation that is shipped with the shared subtrees patches.

Capítulo 3. O Sistema de Arquivo ext3

O sistema de arquivos default é o ext3 journaling.

3.1. Características do ext3

O sistema de arquivos ext3 é essencialmente uma versão melhorada do sistema de arquivo ext2. Estas melhorias oferecem as seguintes vantagens:
Disponibilidade
After an unexpected power failure or system crash (also called an unclean system shutdown), each mounted ext2 file system on the machine must be checked for consistency by the e2fsck program. This is a time-consuming process that can delay system boot time significantly, especially with large volumes containing a large number of files. During this time, any data on the volumes is unreachable.
O journaling provido pelo sistema de arquivos ext3 significa que este tipo de verificação não é mais necessário após um desligamento impróprio do sistema. Os únicos momentos em que ocorrem verificações de consistência usando o ext3 são em raros casos de falha de hardware, como falhas no disco rígido. O tempo para recuperar um sistema de arquivos ext3 após um desligamento impróprio do sistema não depende do tamanho do sistema de arquivos ou do número de arquivos, mas sim do tamanho do journal usado para manter a consistência. O journal de tamanho default leva aproximadamente um segundo para recuperar, dependendo da velocidade do hardware.
Integridade dos Dados
O sistema de arquivos ext3 oferece alta integridade dos dados no caso de um desligamento impróprio do sistema. Além disso, permite que você escolha o tipo e nível de proteção para seus dados. Por default, os volumes ext3 são configurados para manter um alto nível de consistência dos dados em relação ao estado do sistema de arquivos.
Velocidade
Apesar de gravar alguns dados mais de uma vez, o ext3 tem maior produtividade em relação ao ext2 na maioria dos casos, pois o journaling do ext3 otimiza a movimentação da cabeça do disco rígido. Você pode escolher dentre três modos de journaling para otimizar a velocidade, mas ao fazer isso diminui a integridade dos dados.
Transição Fácil
It is easy to migrate from ext2 to ext3 and gain the benefits of a robust journaling file system without reformatting. Refer to Seção 3.3, “Convertendo para um Sistema de Arquivo ext3” for more on how to perform this task.
The following sections walk you through the steps for creating and tuning ext3 partitions. For ext2 partitions, skip the partitioning and formatting sections below and go directly to Seção 3.3, “Convertendo para um Sistema de Arquivo ext3”.

3.2. Criando um Sistema de Arquivo ext3

Após a instalação, às vezes é necessário criar um novo sistema de arquivos ext3. Por exemplo: se você adicionar um novo drive de disco ao sistema, pode querer particionar o drive e usar o sistema de arquivos ext3.
Os passos para a criação de um sistema de arquivos ext3 são os seguintes:
  1. Format the partition with the ext3 file system using mkfs.
  2. Label the partition using e2label.

3.3. Convertendo para um Sistema de Arquivo ext3

The tune2fs allows you to convert an ext2 filesystem to ext3.

Nota

Use sempre o utilitário e2fsck para verificar seu sistema de arquivo antes e depois de usar o tune2fs. Uma instalação padrão do Red Hat Enterprise Linux usa o ext3 para todos os sistemas de arquivo.
Para converter um sistema de arquivos ext2 para ext3, autentique-se como root e digite:
tune2fs -j <block_device>
onde <block_device> contém o sistema de arquivo ext2 que você desejar converter.
Um dispositivo de bloqueio válido pode ser um ou dois tipos de entradas:
  • A mapped device — A logical volume in a volume group, for example, /dev/mapper/VolGroup00-LogVol02.
  • A static device — A traditional storage volume, for example, /dev/hdbX, where hdb is a storage device name and X is the partition number.
Issue the df command to display mounted file systems.
Como lembrete desta seção, os comandos de amostra usam o seguinte valor para o dipositivo de bloqueio:
/dev/mapper/VolGroup00-LogVol02
You must recreate the initrd image so that it will contain the ext3 kernel module. To create this, run the mkinitrd program. For information on using the mkinitrd command, type man mkinitrd. Also, make sure your GRUB configuration loads the initrd.
Se você não conseguir executar esta alteração, o sistema ainda inicializará, mas o sistema de arquivos será montado como ext2 ao invés de ext3.

3.4. Revertendo para um Sistema de Arquivo ext2

Para reverter uma partição, você deve primeiramente desmontar a partição se autenticando como root e digitando:
umount /dev/mapper/VolGroup00-LogVol02
Em seguida, mude o tipo do sistema de arquivos para ext2 digitando o seguinte comando como root:
tune2fs -O ^has_journal /dev/mapper/VolGroup00-LogVol02
Verifique se há erros na partição, digitando o seguinte comando como root:
e2fsck -y /dev/mapper/VolGroup00-LogVol02
Então, monte a partição novamente como sistema de arquivos ext2, digitando:
mount -t ext2 /dev/mapper/VolGroup00-LogVol02 /mount/point
No comando acima, substitua /mount/point pelo ponto de montagem da partição.
Next, remove the .journal file at the root level of the partition by changing to the directory where it is mounted and typing:
rm -f .journal
Agora você tem uma partição ext2.
If you want to permanently change the partition to ext2, remember to update the /etc/fstab file.

Capítulo 4. The proc File System

The Linux kernel has two primary functions: to control access to physical devices on the computer and to schedule when and how processes interact with these devices. The /proc/ directory — also called the proc file system — contains a hierarchy of special files which represent the current state of the kernel — allowing applications and users to peer into the kernel's view of the system.
Within the /proc/ directory, one can find a wealth of information detailing the system hardware and any processes currently running. In addition, some of the files within the /proc/ directory tree can be manipulated by users and applications to communicate configuration changes to the kernel.

4.1. A Virtual File System

Under Linux, all data are stored as files. Most users are familiar with the two primary types of files: text and binary. But the /proc/ directory contains another type of file called a virtual file. It is for this reason that /proc/ is often referred to as a virtual file system.
These virtual files have unique qualities. Most of them are listed as zero bytes in size and yet when one is viewed, it can contain a large amount of information. In addition, most of the time and date settings on virtual files reflect the current time and date, indicative of the fact they are constantly updated.
Virtual files such as /proc/interrupts, /proc/meminfo, /proc/mounts, and /proc/partitions provide an up-to-the-moment glimpse of the system's hardware. Others, like the /proc/filesystems file and the /proc/sys/ directory provide system configuration information and interfaces.
For organizational purposes, files containing information on a similar topic are grouped into virtual directories and sub-directories. For instance, /proc/ide/ contains information for all physical IDE devices. Likewise, process directories contain information about each running process on the system.

4.1.1. Viewing Virtual Files

By using the cat, more, or less commands on files within the /proc/ directory, users can immediately access enormous amounts of information about the system. For example, to display the type of CPU a computer has, type cat /proc/cpuinfo to receive output similar to the following:
processor	: 0
vendor_id	: AuthenticAMD
cpu family	: 5
model		: 9
model name	: AMD-K6(tm) 3D+
Processor stepping	: 1 cpu
MHz		: 400.919
cache size	: 256 KB
fdiv_bug	: no
hlt_bug		: no
f00f_bug	: no
coma_bug	: no
fpu		: yes
fpu_exception	: yes
cpuid level	: 1
wp		: yes
flags		: fpu vme de pse tsc msr mce cx8 pge mmx syscall 3dnow k6_mtrr
bogomips	: 799.53
When viewing different virtual files in the /proc/ file system, some of the information is easily understandable while some is not human-readable. This is in part why utilities exist to pull data from virtual files and display it in a useful way. Examples of these utilities include lspci, apm, free, and top.

Note

Some of the virtual files in the /proc/ directory are readable only by the root user.

4.1.2. Changing Virtual Files

As a general rule, most virtual files within the /proc/ directory are read-only. However, some can be used to adjust settings in the kernel. This is especially true for files in the /proc/sys/ subdirectory.
To change the value of a virtual file, use the echo command and a greater than symbol (>) to redirect the new value to the file. For example, to change the hostname on the fly, type:
echo www.example.com > /proc/sys/kernel/hostname 
Other files act as binary or Boolean switches. Typing cat /proc/sys/net/ipv4/ip_forward returns either a 0 or a 1. A 0 indicates that the kernel is not forwarding network packets. Using the echo command to change the value of the ip_forward file to 1 immediately turns packet forwarding on.

Tip

Another command used to alter settings in the /proc/sys/ subdirectory is /sbin/sysctl. For more information on this command, refer to Seção 4.4, “Using the sysctl Command”
For a listing of some of the kernel configuration files available in the /proc/sys/ subdirectory, refer to Seção 4.3.9, “ /proc/sys/.

4.2. Top-level Files within the proc File System

Below is a list of some of the more useful virtual files in the top-level of the /proc/ directory.

Note

In most cases, the content of the files listed in this section are not the same as those installed on your machine. This is because much of the information is specific to the hardware on which Red Hat Enterprise Linux is running for this documentation effort.

4.2.1. /proc/apm

This file provides information about the state of the Advanced Power Management (APM) system and is used by the apm command. If a system with no battery is connected to an AC power source, this virtual file would look similar to the following:
1.16 1.2 0x07 0x01 0xff 0x80 -1% -1 ?
Running the apm -v command on such a system results in output similar to the following:
APM BIOS 1.2 (kernel driver 1.16ac) AC on-line, no system battery
For systems which do not use a battery as a power source, apm is able do little more than put the machine in standby mode. The apm command is much more useful on laptops. For example, the following output is from the command cat /proc/apm on a laptop while plugged into a power outlet:
1.16 1.2 0x03 0x01 0x03 0x09 100% -1 ?
When the same laptop is unplugged from its power source for a few minutes, the content of the apm file changes to something like the following:
1.16 1.2 0x03 0x00 0x00 0x01 99% 1792 min
The apm -v command now yields more useful data, such as the following:
APM BIOS 1.2 (kernel driver 1.16) AC off-line, battery status high: 99% (1 day, 5:52)

4.2.2. /proc/buddyinfo

This file is used primarily for diagnosing memory fragmentation issues. Using the buddy algorithm, each column represents the number of pages of a certain order (a certain size) that are available at any given time. For example, for zone DMA (direct memory access), there are 90 of 2^(0*PAGE_SIZE) chunks of memory. Similarly, there are 6 of 2^(1*PAGE_SIZE) chunks, and 2 of 2^(2*PAGE_SIZE) chunks of memory available.
The DMA row references the first 16 MB on a system, the HighMem row references all memory greater than 4 GB on a system, and the Normal row references all memory in between.
The following is an example of the output typical of /proc/buddyinfo:
Node 0, zone      DMA     90      6      2      1      1      ...
Node 0, zone   Normal   1650    310      5      0      0      ...
Node 0, zone  HighMem      2      0      0      1      1      ...

4.2.3. /proc/cmdline

This file shows the parameters passed to the kernel at the time it is started. A sample /proc/cmdline file looks like the following:
ro root=/dev/VolGroup00/LogVol00 rhgb quiet 3
This output tells us the following:
ro
The root device is mounted read-only at boot time. The presence of ro on the kernel boot line overrides any instances of rw.
root=/dev/VolGroup00/LogVol00
This tells us on which disk device or, in this case, on which logical volume, the root filesystem image is located. With our sample /proc/cmdline output, the root filesystem image is located on the first logical volume (LogVol00) of the first LVM volume group (VolGroup00). On a system not using Logical Volume Management, the root file system might be located on /dev/sda1 or /dev/sda2, meaning on either the first or second partition of the first SCSI or SATA disk drive, depending on whether we have a separate (preceding) boot or swap partition on that drive.
For more information on LVM used in Red Hat Enterprise Linux, refer to http://www.tldp.org/HOWTO/LVM-HOWTO/index.html.
rhgb
A short lowercase acronym that stands for Red Hat Graphical Boot, providing "rhgb" on the kernel command line signals that graphical booting is supported, assuming that /etc/inittab shows that the default runlevel is set to 5 with a line like this:
id:5:initdefault:
quiet
Indicates that all verbose kernel messages except those which are extremely serious should be suppressed at boot time.

4.2.4. /proc/cpuinfo

This virtual file identifies the type of processor used by your system. The following is an example of the output typical of /proc/cpuinfo:
processor	: 0
vendor_id	: GenuineIntel
cpu family	: 15
model		: 2
model name	: Intel(R) Xeon(TM) CPU 2.40GHz
stepping	: 7 cpu
MHz		: 2392.371
cache size	: 512 KB
physical id	: 0
siblings	: 2
runqueue	: 0
fdiv_bug	: no
hlt_bug		: no
f00f_bug	: no
coma_bug	: no
fpu		: yes
fpu_exception	: yes
cpuid level	: 2
wp		: yes
flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca  cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm
bogomips	: 4771.02
  • processor — Provides each processor with an identifying number. On systems that have one processor, only a 0 is present.
  • cpu family — Authoritatively identifies the type of processor in the system. For an Intel-based system, place the number in front of "86" to determine the value. This is particularly helpful for those attempting to identify the architecture of an older system such as a 586, 486, or 386. Because some RPM packages are compiled for each of these particular architectures, this value also helps users determine which packages to install.
  • model name — Displays the common name of the processor, including its project name.
  • cpu MHz — Shows the precise speed in megahertz for the processor to the thousandths decimal place.
  • cache size — Displays the amount of level 2 memory cache available to the processor.
  • siblings — Displays the number of sibling CPUs on the same physical CPU for architectures which use hyper-threading.
  • flags — Defines a number of different qualities about the processor, such as the presence of a floating point unit (FPU) and the ability to process MMX instructions.

4.2.5. /proc/crypto

This file lists all installed cryptographic ciphers used by the Linux kernel, including additional details for each. A sample /proc/crypto file looks like the following:
name         : sha1
module       : kernel
type         : digest
blocksize    : 64
digestsize   : 20
name         : md5
module       : md5
type         : digest
blocksize    : 64
digestsize   : 16

4.2.6. /proc/devices

This file displays the various character and block devices currently configured (not including devices whose modules are not loaded). Below is a sample output from this file:
Character devices:
  1 mem
  4 /dev/vc/0
  4 tty
  4 ttyS
  5 /dev/tty
  5 /dev/console
  5 /dev/ptmx
  7 vcs
  10 misc
  13 input
  29 fb
  36 netlink
  128 ptm
  136 pts
  180 usb

Block devices:
  1 ramdisk
  3 ide0
  9 md
  22 ide1
  253 device-mapper
  254 mdp
The output from /proc/devices includes the major number and name of the device, and is broken into two major sections: Character devices and Block devices.
Character devices are similar to block devices, except for two basic differences:
  1. Character devices do not require buffering. Block devices have a buffer available, allowing them to order requests before addressing them. This is important for devices designed to store information — such as hard drives — because the ability to order the information before writing it to the device allows it to be placed in a more efficient order.
  2. Character devices send data with no preconfigured size. Block devices can send and receive information in blocks of a size configured per device.
For more information about devices refer to the following installed documentation:
/usr/share/doc/kernel-doc-<version>/Documentation/devices.txt

4.2.7. /proc/dma

This file contains a list of the registered ISA DMA channels in use. A sample /proc/dma files looks like the following:
4: cascade

4.2.8. /proc/execdomains

This file lists the execution domains currently supported by the Linux kernel, along with the range of personalities they support.
0-0   Linux           [kernel]
Think of execution domains as the "personality" for an operating system. Because other binary formats, such as Solaris, UnixWare, and FreeBSD, can be used with Linux, programmers can change the way the operating system treats system calls from these binaries by changing the personality of the task. Except for the PER_LINUX execution domain, different personalities can be implemented as dynamically loadable modules.

4.2.9. /proc/fb

This file contains a list of frame buffer devices, with the frame buffer device number and the driver that controls it. Typical output of /proc/fb for systems which contain frame buffer devices looks similar to the following:
0 VESA VGA

4.2.10. /proc/filesystems

This file displays a list of the file system types currently supported by the kernel. Sample output from a generic /proc/filesystems file looks similar to the following:
nodev   sysfs
nodev   rootfs
nodev   bdev
nodev   proc
nodev   sockfs
nodev   binfmt_misc
nodev   usbfs
nodev   usbdevfs
nodev   futexfs
nodev   tmpfs
nodev   pipefs
nodev   eventpollfs
nodev   devpts
	ext2
nodev   ramfs
nodev   hugetlbfs
	iso9660
nodev   mqueue
	ext3
nodev   rpc_pipefs
nodev   autofs
The first column signifies whether the file system is mounted on a block device. Those beginning with nodev are not mounted on a device. The second column lists the names of the file systems supported.
The mount command cycles through the file systems listed here when one is not specified as an argument.

4.2.11. /proc/interrupts

This file records the number of interrupts per IRQ on the x86 architecture. A standard /proc/interrupts looks similar to the following:
  CPU0
  0:   80448940          XT-PIC  timer
  1:     174412          XT-PIC  keyboard
  2:          0          XT-PIC  cascade
  8:          1          XT-PIC  rtc
 10:     410964          XT-PIC  eth0
 12:      60330          XT-PIC  PS/2 Mouse
 14:    1314121          XT-PIC  ide0
 15:    5195422          XT-PIC  ide1
NMI:          0
ERR:          0
For a multi-processor machine, this file may look slightly different:
	   CPU0       CPU1
  0: 1366814704          0          XT-PIC  timer
  1:        128        340    IO-APIC-edge  keyboard
  2:          0          0          XT-PIC  cascade
  8:          0          1    IO-APIC-edge  rtc
 12:       5323       5793    IO-APIC-edge  PS/2 Mouse
 13:          1          0          XT-PIC  fpu
 16:   11184294   15940594   IO-APIC-level  Intel EtherExpress Pro 10/100 Ethernet
 20:    8450043   11120093   IO-APIC-level  megaraid
 30:      10432      10722   IO-APIC-level  aic7xxx
 31:         23         22   IO-APIC-level  aic7xxx
NMI:          0
ERR:          0
The first column refers to the IRQ number. Each CPU in the system has its own column and its own number of interrupts per IRQ. The next column reports the type of interrupt, and the last column contains the name of the device that is located at that IRQ.
Each of the types of interrupts seen in this file, which are architecture-specific, mean something different. For x86 machines, the following values are common:
  • XT-PIC — This is the old AT computer interrupts.
  • IO-APIC-edge — The voltage signal on this interrupt transitions from low to high, creating an edge, where the interrupt occurs and is only signaled once. This kind of interrupt, as well as the IO-APIC-level interrupt, are only seen on systems with processors from the 586 family and higher.
  • IO-APIC-level — Generates interrupts when its voltage signal is high until the signal is low again.

4.2.12. /proc/iomem

This file shows you the current map of the system's memory for each physical device:
00000000-0009fbff : System RAM
0009fc00-0009ffff : reserved
000a0000-000bffff : Video RAM area
000c0000-000c7fff : Video ROM
000f0000-000fffff : System ROM
00100000-07ffffff : System RAM
00100000-00291ba8 : Kernel code
00291ba9-002e09cb : Kernel data
e0000000-e3ffffff : VIA Technologies, Inc. VT82C597 [Apollo VP3] e4000000-e7ffffff : PCI Bus #01
e4000000-e4003fff : Matrox Graphics, Inc. MGA G200 AGP
e5000000-e57fffff : Matrox Graphics, Inc. MGA G200 AGP
e8000000-e8ffffff : PCI Bus #01
e8000000-e8ffffff : Matrox Graphics, Inc. MGA G200 AGP
ea000000-ea00007f : Digital Equipment Corporation DECchip 21140 [FasterNet]
ea000000-ea00007f : tulip ffff0000-ffffffff : reserved
The first column displays the memory registers used by each of the different types of memory. The second column lists the kind of memory located within those registers and displays which memory registers are used by the kernel within the system RAM or, if the network interface card has multiple Ethernet ports, the memory registers assigned for each port.

4.2.13. /proc/ioports

The output of /proc/ioports provides a list of currently registered port regions used for input or output communication with a device. This file can be quite long. The following is a partial listing:
0000-001f : dma1
0020-003f : pic1
0040-005f : timer
0060-006f : keyboard
0070-007f : rtc
0080-008f : dma page reg
00a0-00bf : pic2
00c0-00df : dma2
00f0-00ff : fpu
0170-0177 : ide1
01f0-01f7 : ide0
02f8-02ff : serial(auto)
0376-0376 : ide1
03c0-03df : vga+
03f6-03f6 : ide0
03f8-03ff : serial(auto)
0cf8-0cff : PCI conf1
d000-dfff : PCI Bus #01
e000-e00f : VIA Technologies, Inc. Bus Master IDE
e000-e007 : ide0
e008-e00f : ide1
e800-e87f : Digital Equipment Corporation DECchip 21140 [FasterNet]
e800-e87f : tulip
The first column gives the I/O port address range reserved for the device listed in the second column.

4.2.14. /proc/kcore

This file represents the physical memory of the system and is stored in the core file format. Unlike most /proc/ files, kcore displays a size. This value is given in bytes and is equal to the size of the physical memory (RAM) used plus 4 KB.
The contents of this file are designed to be examined by a debugger, such as gdb, and is not human readable.

Caution

Do not view the /proc/kcore virtual file. The contents of the file scramble text output on the terminal. If this file is accidentally viewed, press Ctrl+C to stop the process and then type reset to bring back the command line prompt.

4.2.15. /proc/kmsg

This file is used to hold messages generated by the kernel. These messages are then picked up by other programs, such as /sbin/klogd or /bin/dmesg.

4.2.16. /proc/loadavg

This file provides a look at the load average in regard to both the CPU and IO over time, as well as additional data used by uptime and other commands. A sample /proc/loadavg file looks similar to the following:
0.20 0.18 0.12 1/80 11206
The first three columns measure CPU and IO utilization of the last one, five, and 15 minute periods. The fourth column shows the number of currently running processes and the total number of processes. The last column displays the last process ID used.
In addition, load average also refers to the number of processes ready to run (i.e. in the run queue, waiting for a CPU share.

4.2.17. /proc/locks

This file displays the files currently locked by the kernel. The contents of this file contain internal kernel debugging data and can vary tremendously, depending on the use of the system. A sample /proc/locks file for a lightly loaded system looks similar to the following:
1: POSIX  ADVISORY  WRITE 3568 fd:00:2531452 0 EOF
2: FLOCK  ADVISORY  WRITE 3517 fd:00:2531448 0 EOF
3: POSIX  ADVISORY  WRITE 3452 fd:00:2531442 0 EOF
4: POSIX  ADVISORY  WRITE 3443 fd:00:2531440 0 EOF
5: POSIX  ADVISORY  WRITE 3326 fd:00:2531430 0 EOF
6: POSIX  ADVISORY  WRITE 3175 fd:00:2531425 0 EOF
7: POSIX  ADVISORY  WRITE 3056 fd:00:2548663 0 EOF
Each lock has its own line which starts with a unique number. The second column refers to the class of lock used, with FLOCK signifying the older-style UNIX file locks from a flock system call and POSIX representing the newer POSIX locks from the lockf system call.
The third column can have two values: ADVISORY or MANDATORY. ADVISORY means that the lock does not prevent other people from accessing the data; it only prevents other attempts to lock it. MANDATORY means that no other access to the data is permitted while the lock is held. The fourth column reveals whether the lock is allowing the holder READ or WRITE access to the file. The fifth column shows the ID of the process holding the lock. The sixth column shows the ID of the file being locked, in the format of MAJOR-DEVICE:MINOR-DEVICE:INODE-NUMBER . The seventh and eighth column shows the start and end of the file's locked region.

4.2.18. /proc/mdstat

This file contains the current information for multiple-disk, RAID configurations. If the system does not contain such a configuration, then /proc/mdstat looks similar to the following:
Personalities :  read_ahead not set unused devices: <none>
This file remains in the same state as seen above unless a software RAID or md device is present. In that case, view /proc/mdstat to find the current status of mdX RAID devices.
The /proc/mdstat file below shows a system with its md0 configured as a RAID 1 device, while it is currently re-syncing the disks:
Personalities : [linear] [raid1] read_ahead 1024 sectors
md0: active raid1 sda2[1] sdb2[0] 9940 blocks [2/2] [UU] resync=1% finish=12.3min algorithm 2 [3/3] [UUU]
unused devices: <none>

4.2.19. /proc/meminfo

This is one of the more commonly used files in the /proc/ directory, as it reports a large amount of valuable information about the systems RAM usage.
The following sample /proc/meminfo virtual file is from a system with 256 MB of RAM and 512 MB of swap space:
MemTotal:       255908 kB
MemFree:         69936 kB
Buffers:         15812 kB
Cached:         115124 kB
SwapCached:          0 kB
Active:          92700 kB
Inactive:        63792 kB
HighTotal:           0 kB
HighFree:            0 kB
LowTotal:       255908 kB
LowFree:         69936 kB
SwapTotal:      524280 kB
SwapFree:       524280 kB
Dirty:               4 kB
Writeback:           0 kB
Mapped:          42236 kB
Slab:            25912 kB
Committed_AS:   118680 kB
PageTables:       1236 kB
VmallocTotal:  3874808 kB
VmallocUsed:      1416 kB
VmallocChunk:  3872908 kB
HugePages_Total:     0
HugePages_Free:      0
Hugepagesize:     4096 kB
Much of the information here is used by the free, top, and ps commands. In fact, the output of the free command is similar in appearance to the contents and structure of /proc/meminfo. But by looking directly at /proc/meminfo, more details are revealed:
  • MemTotal — Total amount of physical RAM, in kilobytes.
  • MemFree — The amount of physical RAM, in kilobytes, left unused by the system.
  • Buffers — The amount of physical RAM, in kilobytes, used for file buffers.
  • Cached — The amount of physical RAM, in kilobytes, used as cache memory.
  • SwapCached — The amount of swap, in kilobytes, used as cache memory.
  • Active — The total amount of buffer or page cache memory, in kilobytes, that is in active use. This is memory that has been recently used and is usually not reclaimed for other purposes.
  • Inactive — The total amount of buffer or page cache memory, in kilobytes, that are free and available. This is memory that has not been recently used and can be reclaimed for other purposes.
  • HighTotal and HighFree — The total and free amount of memory, in kilobytes, that is not directly mapped into kernel space. The HighTotal value can vary based on the type of kernel used.
  • LowTotal and LowFree — The total and free amount of memory, in kilobytes, that is directly mapped into kernel space. The LowTotal value can vary based on the type of kernel used.
  • SwapTotal — The total amount of swap available, in kilobytes.
  • SwapFree — The total amount of swap free, in kilobytes.
  • Dirty — The total amount of memory, in kilobytes, waiting to be written back to the disk.
  • Writeback — The total amount of memory, in kilobytes, actively being written back to the disk.
  • Mapped — The total amount of memory, in kilobytes, which have been used to map devices, files, or libraries using the mmap command.
  • Slab — The total amount of memory, in kilobytes, used by the kernel to cache data structures for its own use.
  • Committed_AS — The total amount of memory, in kilobytes, estimated to complete the workload. This value represents the worst case scenario value, and also includes swap memory.
  • PageTables — The total amount of memory, in kilobytes, dedicated to the lowest page table level.
  • VMallocTotal — The total amount of memory, in kilobytes, of total allocated virtual address space.
  • VMallocUsed — The total amount of memory, in kilobytes, of used virtual address space.
  • VMallocChunk — The largest contiguous block of memory, in kilobytes, of available virtual address space.
  • HugePages_Total — The total number of hugepages for the system. The number is derived by dividing Hugepagesize by the megabytes set aside for hugepages specified in /proc/sys/vm/hugetlb_pool. This statistic only appears on the x86, Itanium, and AMD64 architectures.
  • HugePages_Free — The total number of hugepages available for the system. This statistic only appears on the x86, Itanium, and AMD64 architectures.
  • Hugepagesize — The size for each hugepages unit in kilobytes. By default, the value is 4096 KB on uniprocessor kernels for 32 bit architectures. For SMP, hugemem kernels, and AMD64, the default is 2048 KB. For Itanium architectures, the default is 262144 KB. This statistic only appears on the x86, Itanium, and AMD64 architectures.

4.2.20. /proc/misc

This file lists miscellaneous drivers registered on the miscellaneous major device, which is device number 10:
63 device-mapper 175 agpgart 135 rtc 134 apm_bios
The first column is the minor number of each device, while the second column shows the driver in use.

4.2.21. /proc/modules

This file displays a list of all modules loaded into the kernel. Its contents vary based on the configuration and use of your system, but it should be organized in a similar manner to this sample /proc/modules file output:

Note

This example has been reformatted into a readable format. Most of this information can also be viewed via the /sbin/lsmod command.
nfs      170109  0 -          Live 0x129b0000
lockd    51593   1 nfs,       Live 0x128b0000
nls_utf8 1729    0 -          Live 0x12830000
vfat     12097   0 -          Live 0x12823000
fat      38881   1 vfat,      Live 0x1287b000
autofs4  20293   2 -          Live 0x1284f000
sunrpc   140453  3 nfs,lockd, Live 0x12954000
3c59x    33257   0 -          Live 0x12871000
uhci_hcd 28377   0 -          Live 0x12869000
md5      3777    1 -          Live 0x1282c000
ipv6     211845 16 -          Live 0x128de000
ext3     92585   2 -          Live 0x12886000
jbd      65625   1 ext3,      Live 0x12857000
dm_mod   46677   3 -          Live 0x12833000
The first column contains the name of the module.
The second column refers to the memory size of the module, in bytes.
The third column lists how many instances of the module are currently loaded. A value of zero represents an unloaded module.
The fourth column states if the module depends upon another module to be present in order to function, and lists those other modules.
The fifth column lists what load state the module is in: Live, Loading, or Unloading are the only possible values.
The sixth column lists the current kernel memory offset for the loaded module. This information can be useful for debugging purposes, or for profiling tools such as oprofile.

4.2.22. /proc/mounts

This file provides a list of all mounts in use by the system:
rootfs / rootfs rw 0 0
/proc /proc proc rw,nodiratime 0 0 none
/dev ramfs rw 0 0
/dev/mapper/VolGroup00-LogVol00 / ext3 rw 0 0
none /dev ramfs rw 0 0
/proc /proc proc rw,nodiratime 0 0
/sys /sys sysfs rw 0 0
none /dev/pts devpts rw 0 0
usbdevfs /proc/bus/usb usbdevfs rw 0 0
/dev/hda1 /boot ext3 rw 0 0
none /dev/shm tmpfs rw 0 0
none /proc/sys/fs/binfmt_misc binfmt_misc rw 0 0
sunrpc /var/lib/nfs/rpc_pipefs rpc_pipefs rw 0 0
The output found here is similar to the contents of /etc/mtab, except that /proc/mount is more up-to-date.
The first column specifies the device that is mounted, the second column reveals the mount point, and the third column tells the file system type, and the fourth column tells you if it is mounted read-only (ro) or read-write (rw). The fifth and sixth columns are dummy values designed to match the format used in /etc/mtab.

4.2.23. /proc/mtrr

This file refers to the current Memory Type Range Registers (MTRRs) in use with the system. If the system architecture supports MTRRs, then the /proc/mtrr file may look similar to the following:
reg00: base=0x00000000 (   0MB), size= 256MB: write-back, count=1
reg01: base=0xe8000000 (3712MB), size=  32MB: write-combining, count=1
MTRRs are used with the Intel P6 family of processors (Pentium II and higher) and control processor access to memory ranges. When using a video card on a PCI or AGP bus, a properly configured /proc/mtrr file can increase performance more than 150%.
Most of the time, this value is properly configured by default. More information on manually configuring this file can be found locally at the following location:
/usr/share/doc/kernel-doc-<version>/Documentation/mtrr.txt

4.2.24. /proc/partitions

This file contains partition block allocation information. A sampling of this file from a basic system looks similar to the following:
major minor  #blocks  name
  3     0   19531250 hda
  3     1     104391 hda1
  3     2   19422585 hda2
253     0   22708224 dm-0
253     1     524288 dm-1
Most of the information here is of little importance to the user, except for the following columns:
  • major — The major number of the device with this partition. The major number in the /proc/partitions, (3), corresponds with the block device ide0, in /proc/devices.
  • minor — The minor number of the device with this partition. This serves to separate the partitions into different physical devices and relates to the number at the end of the name of the partition.
  • #blocks — Lists the number of physical disk blocks contained in a particular partition.
  • name — The name of the partition.

4.2.25. /proc/pci

This file contains a full listing of every PCI device on the system. Depending on the number of PCI devices, /proc/pci can be rather long. A sampling of this file from a basic system looks similar to the following:
Bus  0, device 0, function 0: Host bridge: Intel Corporation 440BX/ZX - 82443BX/ZX Host bridge (rev 3). Master Capable. Latency=64. Prefetchable 32 bit memory at 0xe4000000 [0xe7ffffff].
Bus  0, device 1, function 0: PCI bridge: Intel Corporation 440BX/ZX - 82443BX/ZX AGP bridge (rev 3).   Master Capable. Latency=64. Min Gnt=128.
Bus  0, device 4, function 0: ISA bridge: Intel Corporation 82371AB PIIX4 ISA (rev 2).
Bus  0, device 4, function 1: IDE interface: Intel Corporation 82371AB PIIX4 IDE (rev 1). Master Capable. Latency=32. I/O at 0xd800 [0xd80f].
Bus  0, device 4, function 2: USB Controller: Intel Corporation 82371AB PIIX4 USB (rev 1). IRQ 5. Master Capable. Latency=32. I/O at 0xd400 [0xd41f].
Bus  0, device 4, function 3: Bridge: Intel Corporation 82371AB PIIX4 ACPI (rev 2). IRQ 9.
Bus  0, device 9, function 0: Ethernet controller: Lite-On Communications Inc LNE100TX (rev 33). IRQ 5. Master Capable. Latency=32. I/O at 0xd000 [0xd0ff].
Bus  0, device 12, function  0: VGA compatible controller: S3 Inc. ViRGE/DX or /GX (rev 1). IRQ 11. Master Capable. Latency=32. Min Gnt=4.Max Lat=255.
This output shows a list of all PCI devices, sorted in the order of bus, device, and function. Beyond providing the name and version of the device, this list also gives detailed IRQ information so an administrator can quickly look for conflicts.

Tip

To get a more readable version of this information, type:
lspci -vb

4.2.26. /proc/slabinfo

This file gives full information about memory usage on the slab level. Linux kernels greater than version 2.2 use slab pools to manage memory above the page level. Commonly used objects have their own slab pools.
Instead of parsing the highly verbose /proc/slabinfo file manually, the /usr/bin/slabtop program displays kernel slab cache information in real time. This program allows for custom configurations, including column sorting and screen refreshing.
A sample screen shot of /usr/bin/slabtop usually looks like the following example:
Active / Total Objects (% used)    : 133629 / 147300 (90.7%)
Active / Total Slabs (% used)      : 11492 / 11493 (100.0%)
Active / Total Caches (% used)     : 77 / 121 (63.6%)
Active / Total Size (% used)       : 41739.83K / 44081.89K (94.7%)
Minimum / Average / Maximum Object : 0.01K / 0.30K / 128.00K
OBJS   ACTIVE USE      OBJ   SIZE     SLABS OBJ/SLAB CACHE SIZE NAME
44814  43159  96%    0.62K   7469      6     29876K ext3_inode_cache
36900  34614  93%    0.05K    492     75      1968K buffer_head
35213  33124  94%    0.16K   1531     23      6124K dentry_cache
7364   6463  87%    0.27K    526      14      2104K radix_tree_node
2585   1781  68%    0.08K     55      47       220K vm_area_struct
2263   2116  93%    0.12K     73      31       292K size-128
1904   1125  59%    0.03K     16      119        64K size-32
1666    768  46%    0.03K     14      119        56K anon_vma
1512   1482  98%    0.44K    168       9       672K inode_cache
1464   1040  71%    0.06K     24      61        96K size-64
1320    820  62%    0.19K     66      20       264K filp
678    587  86%    0.02K      3      226        12K dm_io
678    587  86%    0.02K      3      226        12K dm_tio
576    574  99%    0.47K     72        8       288K proc_inode_cache
528    514  97%    0.50K     66        8       264K size-512
492    372  75%    0.09K     12       41        48K bio
465    314  67%    0.25K     31       15       124K size-256
452    331  73%    0.02K      2      226         8K biovec-1
420    420 100%    0.19K     21       20        84K skbuff_head_cache
305    256  83%    0.06K      5       61        20K biovec-4
290      4   1%    0.01K      1      290         4K revoke_table
264    264 100%    4.00K    264        1      1056K size-4096
260    256  98%    0.19K     13       20        52K biovec-16
260    256  98%    0.75K     52        5       208K biovec-64
Some of the more commonly used statistics in /proc/slabinfo that are included into /usr/bin/slabtop include:
  • OBJS — The total number of objects (memory blocks), including those in use (allocated), and some spares not in use.
  • ACTIVE — The number of objects (memory blocks) that are in use (allocated).
  • USE — Percentage of total objects that are active. ((ACTIVE/OBJS)(100))
  • OBJ SIZE — The size of the objects.
  • SLABS — The total number of slabs.
  • OBJ/SLAB — The number of objects that fit into a slab.
  • CACHE SIZE — The cache size of the slab.
  • NAME — The name of the slab.
For more information on the /usr/bin/slabtop program, refer to the slabtop man page.

4.2.27. /proc/stat

This file keeps track of a variety of different statistics about the system since it was last restarted. The contents of /proc/stat, which can be quite long, usually begins like the following example:
cpu  259246 7001 60190 34250993 137517 772 0
cpu0 259246 7001 60190 34250993 137517 772 0
intr 354133732 347209999 2272 0 4 4 0 0 3 1 1249247 0 0 80143 0 422626 5169433
ctxt 12547729
btime 1093631447
processes 130523
procs_running 1
procs_blocked 0
preempt 5651840
cpu  209841 1554 21720 118519346 72939 154 27168
cpu0 42536 798 4841 14790880 14778 124 3117
cpu1 24184 569 3875 14794524 30209 29 3130
cpu2 28616 11 2182 14818198 4020 1 3493
cpu3 35350 6 2942 14811519 3045 0 3659
cpu4 18209 135 2263 14820076 12465 0 3373
cpu5 20795 35 1866 14825701 4508 0 3615
cpu6 21607 0 2201 14827053 2325 0 3334
cpu7 18544 0 1550 14831395 1589 0 3447
intr 15239682 14857833 6 0 6 6 0 5 0 1 0 0 0 29 0 2 0 0 0 0 0 0 0 94982 0 286812
ctxt 4209609
btime 1078711415
processes 21905
procs_running 1
procs_blocked 0
Some of the more commonly used statistics include:
  • cpu — Measures the number of jiffies (1/100 of a second for x86 systems) that the system has been in user mode, user mode with low priority (nice), system mode, idle task, I/O wait, IRQ (hardirq), and softirq respectively. The IRQ (hardirq) is the direct response to a hardware event. The IRQ takes minimal work for queuing the "heavy" work up for the softirq to execute. The softirq runs at a lower priority than the IRQ and therefore may be interrupted more frequently. The total for all CPUs is given at the top, while each individual CPU is listed below with its own statistics. The following example is a 4-way Intel Pentium Xeon configuration with multi-threading enabled, therefore showing four physical processors and four virtual processors totaling eight processors.
  • page — The number of memory pages the system has written in and out to disk.
  • swap — The number of swap pages the system has brought in and out.
  • intr — The number of interrupts the system has experienced.
  • btime — The boot time, measured in the number of seconds since January 1, 1970, otherwise known as the epoch.

4.2.28. /proc/swaps

This file measures swap space and its utilization. For a system with only one swap partition, the output of /proc/swaps may look similar to the following:
Filename                          Type        Size     Used    Priority
/dev/mapper/VolGroup00-LogVol01   partition   524280   0       -1
While some of this information can be found in other files in the /proc/ directory, /proc/swaps provides a snapshot of every swap file name, the type of swap space, the total size, and the amount of space in use (in kilobytes). The priority column is useful when multiple swap files are in use. The lower the priority, the more likely the swap file is to be used.

4.2.29. /proc/sysrq-trigger

Using the echo command to write to this file, a remote root user can execute most System Request Key commands remotely as if at the local terminal. To echo values to this file, the /proc/sys/kernel/sysrq must be set to a value other than 0. For more information about the System Request Key, refer to Seção 4.3.9.3, “ /proc/sys/kernel/.
Although it is possible to write to this file, it cannot be read, even by the root user.

4.2.30. /proc/uptime

This file contains information detailing how long the system has been on since its last restart. The output of /proc/uptime is quite minimal:
350735.47 234388.90
The first number is the total number of seconds the system has been up. The second number is how much of that time the machine has spent idle, in seconds.

4.2.31. /proc/version

This file specifies the version of the Linux kernel and gcc in use, as well as the version of Red Hat Enterprise Linux installed on the system:
Linux version 2.6.8-1.523 (user@foo.redhat.com) (gcc version 3.4.1 20040714 \  (Red Hat Enterprise Linux 3.4.1-7)) #1 Mon Aug 16 13:27:03 EDT 2004
This information is used for a variety of purposes, including the version data presented when a user logs in.

4.3. Directories within /proc/

Common groups of information concerning the kernel are grouped into directories and subdirectories within the /proc/ directory.

4.3.1. Process Directories

Every /proc/ directory contains a number of directories with numerical names. A listing of them may be similar to the following:
dr-xr-xr-x    3 root     root            0 Feb 13 01:28 1
dr-xr-xr-x    3 root     root            0 Feb 13 01:28 1010
dr-xr-xr-x    3 xfs      xfs             0 Feb 13 01:28 1087
dr-xr-xr-x    3 daemon   daemon          0 Feb 13 01:28 1123
dr-xr-xr-x    3 root     root            0 Feb 13 01:28 11307
dr-xr-xr-x    3 apache   apache          0 Feb 13 01:28 13660
dr-xr-xr-x    3 rpc      rpc             0 Feb 13 01:28 637
dr-xr-xr-x    3 rpcuser  rpcuser         0 Feb 13 01:28 666
These directories are called process directories, as they are named after a program's process ID and contain information specific to that process. The owner and group of each process directory is set to the user running the process. When the process is terminated, its /proc/ process directory vanishes.
Each process directory contains the following files:
  • cmdline — Contains the command issued when starting the process.
  • cwd — A symbolic link to the current working directory for the process.
  • environ — A list of the environment variables for the process. The environment variable is given in all upper-case characters, and the value is in lower-case characters.
  • exe — A symbolic link to the executable of this process.
  • fd — A directory containing all of the file descriptors for a particular process. These are given in numbered links:
    total 0
    lrwx------    1 root     root           64 May  8 11:31 0 -> /dev/null
    lrwx------    1 root     root           64 May  8 11:31 1 -> /dev/null
    lrwx------    1 root     root           64 May  8 11:31 2 -> /dev/null
    lrwx------    1 root     root           64 May  8 11:31 3 -> /dev/ptmx
    lrwx------    1 root     root           64 May  8 11:31 4 -> socket:[7774817]
    lrwx------    1 root     root           64 May  8 11:31 5 -> /dev/ptmx
    lrwx------    1 root     root           64 May  8 11:31 6 -> socket:[7774829]
    lrwx------    1 root     root           64 May  8 11:31 7 -> /dev/ptmx
  • maps — A list of memory maps to the various executables and library files associated with this process. This file can be rather long, depending upon the complexity of the process, but sample output from the sshd process begins like the following:
    08048000-08086000 r-xp 00000000 03:03 391479     /usr/sbin/sshd
    08086000-08088000 rw-p 0003e000 03:03 391479	/usr/sbin/sshd
    08088000-08095000 rwxp 00000000 00:00 0
    40000000-40013000 r-xp 0000000 03:03 293205	/lib/ld-2.2.5.so
    40013000-40014000 rw-p 00013000 03:03 293205	/lib/ld-2.2.5.so
    40031000-40038000 r-xp 00000000 03:03 293282	/lib/libpam.so.0.75
    40038000-40039000 rw-p 00006000 03:03 293282	/lib/libpam.so.0.75
    40039000-4003a000 rw-p 00000000 00:00 0
    4003a000-4003c000 r-xp 00000000 03:03 293218	/lib/libdl-2.2.5.so
    4003c000-4003d000 rw-p 00001000 03:03 293218	/lib/libdl-2.2.5.so
  • mem — The memory held by the process. This file cannot be read by the user.
  • root — A link to the root directory of the process.
  • stat — The status of the process.
  • statm — The status of the memory in use by the process. Below is a sample /proc/statm file:
    263 210 210 5 0 205 0
    The seven columns relate to different memory statistics for the process. From left to right, they report the following aspects of the memory used:
    1. Total program size, in kilobytes.
    2. Size of memory portions, in kilobytes.
    3. Number of pages that are shared.
    4. Number of pages that are code.
    5. Number of pages of data/stack.
    6. Number of library pages.
    7. Number of dirty pages.
  • status — The status of the process in a more readable form than stat or statm. Sample output for sshd looks similar to the following:
    Name:	sshd
    State:	S (sleeping)
    Tgid:	797
    Pid:	797
    PPid:	1
    TracerPid:	0
    Uid:	0	0	0	0
    Gid:	0	0	0	0
    FDSize:	32
    Groups:
    VmSize:	    3072 kB
    VmLck:	       0 kB
    VmRSS:	     840 kB
    VmData:	     104 kB
    VmStk:	      12 kB
    VmExe:	     300 kB
    VmLib:	    2528 kB
    SigPnd:	0000000000000000
    SigBlk:	0000000000000000
    SigIgn:	8000000000001000
    SigCgt:	0000000000014005
    CapInh:	0000000000000000
    CapPrm:	00000000fffffeff
    CapEff:	00000000fffffeff
    The information in this output includes the process name and ID, the state (such as S (sleeping) or R (running)), user/group ID running the process, and detailed data regarding memory usage.

4.3.1.1. /proc/self/

The /proc/self/ directory is a link to the currently running process. This allows a process to look at itself without having to know its process ID.
Within a shell environment, a listing of the /proc/self/ directory produces the same contents as listing the process directory for that process.

4.3.2. /proc/bus/

This directory contains information specific to the various buses available on the system. For example, on a standard system containing PCI and USB buses, current data on each of these buses is available within a subdirectory within /proc/bus/ by the same name, such as /proc/bus/pci/.
The subdirectories and files available within /proc/bus/ vary depending on the devices connected to the system. However, each bus type has at least one directory. Within these bus directories are normally at least one subdirectory with a numerical name, such as 001, which contain binary files.
For example, the /proc/bus/usb/ subdirectory contains files that track the various devices on any USB buses, as well as the drivers required for them. The following is a sample listing of a /proc/bus/usb/ directory:
total 0 dr-xr-xr-x    1 root     root            0 May  3 16:25 001
-r--r--r--    1 root     root            0 May  3 16:25 devices
-r--r--r--    1 root     root            0 May  3 16:25 drivers
The /proc/bus/usb/001/ directory contains all devices on the first USB bus and the devices file identifies the USB root hub on the motherboard.
The following is a example of a /proc/bus/usb/devices file:
T:  Bus=01 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12  MxCh= 2
B:  Alloc=  0/900 us ( 0%), #Int=  0, #Iso=  0
D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
P:  Vendor=0000 ProdID=0000 Rev= 0.00
S:  Product=USB UHCI Root Hub
S:  SerialNumber=d400
C:* #Ifs= 1 Cfg#= 1 Atr=40 MxPwr=  0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
E:  Ad=81(I) Atr=03(Int.) MxPS=   8 Ivl=255ms

4.3.3. /proc/driver/

This directory contains information for specific drivers in use by the kernel.
A common file found here is rtc which provides output from the driver for the system's Real Time Clock (RTC), the device that keeps the time while the system is switched off. Sample output from /proc/driver/rtc looks like the following:
rtc_time        : 16:21:00
rtc_date        : 2004-08-31
rtc_epoch       : 1900
alarm           : 21:16:27
DST_enable      : no
BCD             : yes
24hr            : yes
square_wave     : no
alarm_IRQ       : no
update_IRQ      : no
periodic_IRQ    : no
periodic_freq   : 1024
batt_status     : okay
For more information about the RTC, refer to the following installed documentation:
/usr/share/doc/kernel-doc-<version>/Documentation/rtc.txt.

4.3.4. /proc/fs

This directory shows which file systems are exported. If running an NFS server, typing cat /proc/fs/nfsd/exports displays the file systems being shared and the permissions granted for those file systems. For more on file system sharing with NFS, refer to Capítulo 20, Sistema de Arquivo de Rede (NFS - Network File System).

4.3.5. /proc/ide/

This directory contains information about IDE devices on the system. Each IDE channel is represented as a separate directory, such as /proc/ide/ide0 and /proc/ide/ide1. In addition, a drivers file is available, providing the version number of the various drivers used on the IDE channels:
ide-floppy version 0.99.
newide ide-cdrom version 4.61
ide-disk version 1.18
Many chipsets also provide a file in this directory with additional data concerning the drives connected through the channels. For example, a generic Intel PIIX4 Ultra 33 chipset produces the /proc/ide/piix file which reveals whether DMA or UDMA is enabled for the devices on the IDE channels:
Intel PIIX4 Ultra 33 Chipset.
------------- Primary Channel ---------------- Secondary Channel -------------
		enabled                          enabled

------------- drive0 --------- drive1 -------- drive0 ---------- drive1 ------
DMA enabled:    yes              no              yes               no
UDMA enabled:   yes              no              no                no
UDMA enabled:   2                X               X                 X
UDMA DMA PIO
Navigating into the directory for an IDE channel, such as ide0, provides additional information. The channel file provides the channel number, while the model identifies the bus type for the channel (such as pci).

4.3.5.1. Device Directories

Within each IDE channel directory is a device directory. The name of the device directory corresponds to the drive letter in the /dev/ directory. For instance, the first IDE drive on ide0 would be hda.

Note

There is a symbolic link to each of these device directories in the /proc/ide/ directory.
Each device directory contains a collection of information and statistics. The contents of these directories vary according to the type of device connected. Some of the more useful files common to many devices include:
  • cache — The device cache.
  • capacity — The capacity of the device, in 512 byte blocks.
  • driver — The driver and version used to control the device.
  • geometry — The physical and logical geometry of the device.
  • media — The type of device, such as a disk.
  • model — The model name or number of the device.
  • settings — A collection of current device parameters. This file usually contains quite a bit of useful, technical information. A sample settings file for a standard IDE hard disk looks similar to the following:
    name                value          min          max          mode
    ----                -----          ---          ---          ----
    acoustic            0              0            254          rw
    address             0              0            2            rw
    bios_cyl            38752          0            65535        rw
    bios_head           16             0            255          rw
    bios_sect           63             0            63           rw
    bswap               0              0            1            r
    current_speed       68             0            70           rw
    failures            0              0            65535        rw
    init_speed          68             0            70           rw
    io_32bit            0              0            3            rw
    keepsettings        0              0            1            rw
    lun                 0              0            7            rw
    max_failures        1              0            65535        rw
    multcount           16             0            16           rw
    nice1               1              0            1            rw
    nowerr              0              0            1            rw
    number              0              0            3            rw
    pio_mode            write-only     0            255          w
    unmaskirq           0              0            1            rw
    using_dma           1              0            1            rw
    wcache              1              0            1            rw

4.3.6. /proc/irq/

This directory is used to set IRQ to CPU affinity, which allows the system to connect a particular IRQ to only one CPU. Alternatively, it can exclude a CPU from handling any IRQs.
Each IRQ has its own directory, allowing for the individual configuration of each IRQ. The /proc/irq/prof_cpu_mask file is a bitmask that contains the default values for the smp_affinity file in the IRQ directory. The values in smp_affinity specify which CPUs handle that particular IRQ.
For more information about the /proc/irq/ directory, refer to the following installed documentation:
/usr/share/doc/kernel-doc-<version>/Documentation/filesystems/proc.txt

4.3.7. /proc/net/

This directory provides a comprehensive look at various networking parameters and statistics. Each directory and virtual file within this directory describes aspects of the system's network configuration. Below is a partial list of the /proc/net/ directory:
  • arp — Lists the kernel's ARP table. This file is particularly useful for connecting a hardware address to an IP address on a system.
  • atm/ directory — The files within this directory contain Asynchronous Transfer Mode (ATM) settings and statistics. This directory is primarily used with ATM networking and ADSL cards.
  • dev — Lists the various network devices configured on the system, complete with transmit and receive statistics. This file displays the number of bytes each interface has sent and received, the number of packets inbound and outbound, the number of errors seen, the number of packets dropped, and more.
  • dev_mcast — Lists Layer2 multicast groups on which each device is listening.
  • igmp — Lists the IP multicast addresses which this system joined.
  • ip_conntrack — Lists tracked network connections for machines that are forwarding IP connections.
  • ip_tables_names — Lists the types of iptables in use. This file is only present if iptables is active on the system and contains one or more of the following values: filter, mangle, or nat.
  • ip_mr_cache — Lists the multicast routing cache.
  • ip_mr_vif — Lists multicast virtual interfaces.
  • netstat — Contains a broad yet detailed collection of networking statistics, including TCP timeouts, SYN cookies sent and received, and much more.
  • psched — Lists global packet scheduler parameters.
  • raw — Lists raw device statistics.
  • route — Lists the kernel's routing table.
  • rt_cache — Contains the current routing cache.
  • snmp — List of Simple Network Management Protocol (SNMP) data for various networking protocols in use.
  • sockstat — Provides socket statistics.
  • tcp — Contains detailed TCP socket information.
  • tr_rif — Lists the token ring RIF routing table.
  • udp — Contains detailed UDP socket information.
  • unix — Lists UNIX domain sockets currently in use.
  • wireless — Lists wireless interface data.

4.3.8. /proc/scsi/

This directory is analogous to the /proc/ide/ directory, but it is for connected SCSI devices.
The primary file in this directory is /proc/scsi/scsi, which contains a list of every recognized SCSI device. From this listing, the type of device, as well as the model name, vendor, SCSI channel and ID data is available.
For example, if a system contains a SCSI CD-ROM, a tape drive, a hard drive, and a RAID controller, this file looks similar to the following:
Attached devices:
Host: scsi1
Channel: 00
Id: 05
Lun: 00
Vendor: NEC
Model: CD-ROM DRIVE:466
Rev: 1.06
Type:   CD-ROM
ANSI SCSI revision: 02
Host: scsi1
Channel: 00
Id: 06
Lun: 00
Vendor: ARCHIVE
Model: Python 04106-XXX
Rev: 7350
Type:   Sequential-Access
ANSI SCSI revision: 02
Host: scsi2
Channel: 00
Id: 06
Lun: 00
Vendor: DELL
Model: 1x6 U2W SCSI BP
Rev: 5.35
Type:   Processor
ANSI SCSI revision: 02
Host: scsi2
Channel: 02
Id: 00
Lun: 00
Vendor: MegaRAID
Model: LD0 RAID5 34556R
Rev: 1.01
Type:   Direct-Access
ANSI SCSI revision: 02
Each SCSI driver used by the system has its own directory within /proc/scsi/, which contains files specific to each SCSI controller using that driver. From the previous example, aic7xxx/ and megaraid/ directories are present, since two drivers are in use. The files in each of the directories typically contain an I/O address range, IRQ information, and statistics for the SCSI controller using that driver. Each controller can report a different type and amount of information. The Adaptec AIC-7880 Ultra SCSI host adapter's file in this example system produces the following output:
Adaptec AIC7xxx driver version: 5.1.20/3.2.4
Compile Options:
TCQ Enabled By Default : Disabled
AIC7XXX_PROC_STATS     : Enabled
AIC7XXX_RESET_DELAY    : 5
Adapter Configuration:
SCSI Adapter: Adaptec AIC-7880 Ultra SCSI host adapter
Ultra Narrow Controller     PCI MMAPed
I/O Base: 0xfcffe000
Adapter SEEPROM Config: SEEPROM found and used.
Adaptec SCSI BIOS: Enabled
IRQ: 30
SCBs: Active 0, Max Active 1, Allocated 15, HW 16, Page 255
Interrupts: 33726
BIOS Control Word: 0x18a6
Adapter Control Word: 0x1c5f
Extended Translation: Enabled
Disconnect Enable Flags: 0x00ff
Ultra Enable Flags: 0x0020
Tag Queue Enable Flags: 0x0000
Ordered Queue Tag Flags: 0x0000
Default Tag Queue Depth: 8
Tagged Queue By Device array for aic7xxx
host instance 1:       {255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255}
Actual queue depth per device for aic7xxx host instance 1:       {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
Statistics:

(scsi1:0:5:0) Device using Narrow/Sync transfers at 20.0 MByte/sec, offset 15
Transinfo settings: current(12/15/0/0), goal(12/15/0/0), user(12/15/0/0)
Total transfers 0 (0 reads and 0 writes)
		< 2K      2K+     4K+     8K+    16K+    32K+    64K+   128K+
Reads:        0       0       0       0       0       0       0       0
Writes:       0       0       0       0       0       0       0       0

(scsi1:0:6:0) Device using Narrow/Sync transfers at 10.0 MByte/sec, offset 15
Transinfo settings: current(25/15/0/0), goal(12/15/0/0), user(12/15/0/0)
Total transfers 132 (0 reads and 132 writes)
		< 2K      2K+     4K+     8K+    16K+    32K+    64K+   128K+
Reads:        0       0       0       0       0       0       0       0
Writes:       0       0       0       1     131       0       0       0
This output reveals the transfer speed to the SCSI devices connected to the controller based on channel ID, as well as detailed statistics concerning the amount and sizes of files read or written by that device. For example, this controller is communicating with the CD-ROM at 20 megabytes per second, while the tape drive is only communicating at 10 megabytes per second.

4.3.9. /proc/sys/

The /proc/sys/ directory is different from others in /proc/ because it not only provides information about the system but also allows the system administrator to immediately enable and disable kernel features.

Caution

Use caution when changing settings on a production system using the various files in the /proc/sys/ directory. Changing the wrong setting may render the kernel unstable, requiring a system reboot.
For this reason, be sure the options are valid for that file before attempting to change any value in /proc/sys/.
A good way to determine if a particular file can be configured, or if it is only designed to provide information, is to list it with the -l option at the shell prompt. If the file is writable, it may be used to configure the kernel. For example, a partial listing of /proc/sys/fs looks like the following:
-r--r--r--    1 root     root            0 May 10 16:14 dentry-state
-rw-r--r--    1 root     root            0 May 10 16:14 dir-notify-enable
-r--r--r--    1 root     root            0 May 10 16:14 dquot-nr
-rw-r--r--    1 root     root            0 May 10 16:14 file-max
-r--r--r--    1 root     root            0 May 10 16:14 file-nr
In this listing, the files dir-notify-enable and file-max can be written to and, therefore, can be used to configure the kernel. The other files only provide feedback on current settings.
Changing a value within a /proc/sys/ file is done by echoing the new value into the file. For example, to enable the System Request Key on a running kernel, type the command:
echo 1 > /proc/sys/kernel/sysrq
This changes the value for sysrq from 0 (off) to 1 (on).
A few /proc/sys/ configuration files contain more than one value. To correctly send new values to them, place a space character between each value passed with the echo command, such as is done in this example:
echo 4 2 45 > /proc/sys/kernel/acct

Note

Any configuration changes made using the echo command disappear when the system is restarted. To make configuration changes take effect after the system is rebooted, refer to Seção 4.4, “Using the sysctl Command”.
The /proc/sys/ directory contains several subdirectories controlling different aspects of a running kernel.

4.3.9.1. /proc/sys/dev/

This directory provides parameters for particular devices on the system. Most systems have at least two directories, cdrom/ and raid/. Customized kernels can have other directories, such as parport/, which provides the ability to share one parallel port between multiple device drivers.
The cdrom/ directory contains a file called info, which reveals a number of important CD-ROM parameters:
CD-ROM information, Id: cdrom.c 3.20 2003/12/17
drive name:             hdc
drive speed:            48
drive # of slots:       1
Can close tray:         1
Can open tray:          1
Can lock tray:          1
Can change speed:       1
Can select disk:        0
Can read multisession:  1
Can read MCN:           1
Reports media changed:  1
Can play audio:         1
Can write CD-R:         0
Can write CD-RW:        0
Can read DVD:           0
Can write DVD-R:        0
Can write DVD-RAM:      0
Can read MRW:           0
Can write MRW:          0
Can write RAM:          0
This file can be quickly scanned to discover the qualities of an unknown CD-ROM. If multiple CD-ROMs are available on a system, each device is given its own column of information.
Various files in /proc/sys/dev/cdrom, such as autoclose and checkmedia, can be used to control the system's CD-ROM. Use the echo command to enable or disable these features.
If RAID support is compiled into the kernel, a /proc/sys/dev/raid/ directory becomes available with at least two files in it: speed_limit_min and speed_limit_max. These settings determine the acceleration of RAID devices for I/O intensive tasks, such as resyncing the disks.

4.3.9.2. /proc/sys/fs/

This directory contains an array of options and information concerning various aspects of the file system, including quota, file handle, inode, and dentry information.
The binfmt_misc/ directory is used to provide kernel support for miscellaneous binary formats.
The important files in /proc/sys/fs/ include:
  • dentry-state — Provides the status of the directory cache. The file looks similar to the following:
    57411	52939	45	0	0	0
    The first number reveals the total number of directory cache entries, while the second number displays the number of unused entries. The third number tells the number of seconds between when a directory has been freed and when it can be reclaimed, and the fourth measures the pages currently requested by the system. The last two numbers are not used and display only zeros.
  • dquot-nr — Lists the maximum number of cached disk quota entries.
  • file-max — Lists the maximum number of file handles that the kernel allocates. Raising the value in this file can resolve errors caused by a lack of available file handles.
  • file-nr — Lists the number of allocated file handles, used file handles, and the maximum number of file handles.
  • overflowgid and overflowuid — Defines the fixed group ID and user ID, respectively, for use with file systems that only support 16-bit group and user IDs.
  • super-max — Controls the maximum number of superblocks available.
  • super-nr — Displays the current number of superblocks in use.

4.3.9.3. /proc/sys/kernel/

This directory contains a variety of different configuration files that directly affect the operation of the kernel. Some of the most important files include:
  • acct — Controls the suspension of process accounting based on the percentage of free space available on the file system containing the log. By default, the file looks like the following:
    4	2	30
    The first value dictates the percentage of free space required for logging to resume, while the second value sets the threshold percentage of free space when logging is suspended. The third value sets the interval, in seconds, that the kernel polls the file system to see if logging should be suspended or resumed.
  • cap-bound — Controls the capability bounding settings, which provides a list of capabilities for any process on the system. If a capability is not listed here, then no process, no matter how privileged, can do it. The idea is to make the system more secure by ensuring that certain things cannot happen, at least beyond a certain point in the boot process.
    For a valid list of values for this virtual file, refer to the following installed documentation:
    /lib/modules/<kernel-version>/build/include/linux/capability.h.
  • ctrl-alt-del — Controls whether Ctrl+Alt+Delete gracefully restarts the computer using init (0) or forces an immediate reboot without syncing the dirty buffers to disk (1).
  • domainname — Configures the system domain name, such as example.com.
  • exec-shield — Configures the Exec Shield feature of the kernel. Exec Shield provides protection against certain types of buffer overflow attacks.
    There are two possible values for this virtual file:
    • 0 — Disables Exec Shield.
    • 1 — Enables Exec Shield. This is the default value.

    Important

    If a system is running security-sensitive applications that were started while Exec Shield was disabled, these applications must be restarted when Exec Shield is enabled in order for Exec Shield to take effect.
  • exec-shield-randomize — Enables location randomization of various items in memory. This helps deter potential attackers from locating programs and daemons in memory. Each time a program or daemon starts, it is put into a different memory location each time, never in a static or absolute memory address.
    There are two possible values for this virtual file:
    • 0 — Disables randomization of Exec Shield. This may be useful for application debugging purposes.
    • 1 — Enables randomization of Exec Shield. This is the default value. Note: The exec-shield file must also be set to 1 for exec-shield-randomize to be effective.
  • hostname — Configures the system hostname, such as www.example.com.
  • hotplug — Configures the utility to be used when a configuration change is detected by the system. This is primarily used with USB and Cardbus PCI. The default value of /sbin/hotplug should not be changed unless testing a new program to fulfill this role.
  • modprobe — Sets the location of the program used to load kernel modules. The default value is /sbin/modprobe which means kmod calls it to load the module when a kernel thread calls kmod.
  • msgmax — Sets the maximum size of any message sent from one process to another and is set to 8192 bytes by default. Be careful when raising this value, as queued messages between processes are stored in non-swappable kernel memory. Any increase in msgmax would increase RAM requirements for the system.
  • msgmnb — Sets the maximum number of bytes in a single message queue. The default is 16384.
  • msgmni — Sets the maximum number of message queue identifiers. The default is 16.
  • osrelease — Lists the Linux kernel release number. This file can only be altered by changing the kernel source and recompiling.
  • ostype — Displays the type of operating system. By default, this file is set to Linux, and this value can only be changed by changing the kernel source and recompiling.
  • overflowgid and overflowuid — Defines the fixed group ID and user ID, respectively, for use with system calls on architectures that only support 16-bit group and user IDs.
  • panic — Defines the number of seconds the kernel postpones rebooting when the system experiences a kernel panic. By default, the value is set to 0, which disables automatic rebooting after a panic.
  • printk — This file controls a variety of settings related to printing or logging error messages. Each error message reported by the kernel has a loglevel associated with it that defines the importance of the message. The loglevel values break down in this order:
    • 0 — Kernel emergency. The system is unusable.
    • 1 — Kernel alert. Action must be taken immediately.
    • 2 — Condition of the kernel is considered critical.
    • 3 — General kernel error condition.
    • 4 — General kernel warning condition.
    • 5 — Kernel notice of a normal but significant condition.
    • 6 — Kernel informational message.
    • 7 — Kernel debug-level messages.
    Four values are found in the printk file:
    6     4     1     7
    Each of these values defines a different rule for dealing with error messages. The first value, called the console loglevel, defines the lowest priority of messages printed to the console. (Note that, the lower the priority, the higher the loglevel number.) The second value sets the default loglevel for messages without an explicit loglevel attached to them. The third value sets the lowest possible loglevel configuration for the console loglevel. The last value sets the default value for the console loglevel.
  • random/ directory — Lists a number of values related to generating random numbers for the kernel.
  • rtsig-max — Configures the maximum number of POSIX real-time signals that the system may have queued at any one time. The default value is 1024.
  • rtsig-nr — Lists the current number of POSIX real-time signals queued by the kernel.
  • sem — Configures semaphore settings within the kernel. A semaphore is a System V IPC object that is used to control utilization of a particular process.
  • shmall— Sets the total amount of shared memory pages that can be used at one time, system-wide. By default, this value is 2097152.
  • shmmax — Sets the largest shared memory segment size allowed by the kernel. By default, this value is 33554432. However, the kernel supports much larger values than this.
  • shmmni — Sets the maximum number of shared memory segments for the whole system. By default, this value is 4096.
  • sysrq — Activates the System Request Key, if this value is set to anything other than zero (0), the default.
    The System Request Key allows immediate input to the kernel through simple key combinations. For example, the System Request Key can be used to immediately shut down or restart a system, sync all mounted file systems, or dump important information to the console. To initiate a System Request Key, type Alt+SysRq+ <system request code> . Replace <system request code> with one of the following system request codes:
    • r — Disables raw mode for the keyboard and sets it to XLATE (a limited keyboard mode which does not recognize modifiers such as Alt, Ctrl, or Shift for all keys).
    • k — Kills all processes active in a virtual console. Also called Secure Access Key (SAK), it is often used to verify that the login prompt is spawned from init and not a Trojan copy designed to capture usernames and passwords.
    • b — Reboots the kernel without first unmounting file systems or syncing disks attached to the system.
    • c — Crashes the system without first unmounting file systems or syncing disks attached to the system.
    • o — Shuts off the system.
    • s — Attempts to sync disks attached to the system.
    • u — Attempts to unmount and remount all file systems as read-only.
    • p — Outputs all flags and registers to the console.
    • t — Outputs a list of processes to the console.
    • m — Outputs memory statistics to the console.
    • 0 through 9 — Sets the log level for the console.
    • e — Kills all processes except init using SIGTERM.
    • i — Kills all processes except init using SIGKILL.
    • l — Kills all processes using SIGKILL (including init). The system is unusable after issuing this System Request Key code.
    • h — Displays help text.
    This feature is most beneficial when using a development kernel or when experiencing system freezes.

    Caution

    The System Request Key feature is considered a security risk because an unattended console provides an attacker with access to the system. For this reason, it is turned off by default.
    Refer to /usr/share/doc/kernel-doc-<version>/Documentation/sysrq.txt for more information about the System Request Key.
  • sysrq-key — Defines the key code for the System Request Key (84 is the default).
  • sysrq-sticky — Defines whether the System Request Key is a chorded key combination. The accepted values are as follows:
    • 0Alt+SysRq and the system request code must be pressed simultaneously. This is the default value.
    • 1Alt+SysRq must be pressed simultaneously, but the system request code can be pressed anytime before the number of seconds specified in /proc/sys/kernel/sysrq-timer elapses.
  • sysrq-timer — Specifies the number of seconds allowed to pass before the system request code must be pressed. The default value is 10.
  • tainted — Indicates whether a non-GPL module is loaded.
    • 0 — No non-GPL modules are loaded.
    • 1 — At least one module without a GPL license (including modules with no license) is loaded.
    • 2 — At least one module was force-loaded with the command insmod -f.
  • threads-max — Sets the maximum number of threads to be used by the kernel, with a default value of 2048.
  • version — Displays the date and time the kernel was last compiled. The first field in this file, such as #3, relates to the number of times a kernel was built from the source base.

4.3.9.4. /proc/sys/net/

This directory contains subdirectories concerning various networking topics. Various configurations at the time of kernel compilation make different directories available here, such as ethernet/, ipv4/, ipx/, and ipv6/. By altering the files within these directories, system administrators are able to adjust the network configuration on a running system.
Given the wide variety of possible networking options available with Linux, only the most common /proc/sys/net/ directories are discussed.
The /proc/sys/net/core/ directory contains a variety of settings that control the interaction between the kernel and networking layers. The most important of these files are:
  • message_burst — Sets the amount of time in tenths of a second required to write a new warning message. This setting is used to mitigate Denial of Service (DoS) attacks. The default setting is 50.
  • message_cost — Sets a cost on every warning message. The higher the value of this file (default of 5), the more likely the warning message is ignored. This setting is used to mitigate DoS attacks.
    The idea of a DoS attack is to bombard the targeted system with requests that generate errors and fill up disk partitions with log files or require all of the system's resources to handle the error logging. The settings in message_burst and message_cost are designed to be modified based on the system's acceptable risk versus the need for comprehensive logging.
  • netdev_max_backlog — Sets the maximum number of packets allowed to queue when a particular interface receives packets faster than the kernel can process them. The default value for this file is 300.
  • optmem_max — Configures the maximum ancillary buffer size allowed per socket.
  • rmem_default — Sets the receive socket buffer default size in bytes.
  • rmem_max — Sets the receive socket buffer maximum size in bytes.
  • wmem_default — Sets the send socket buffer default size in bytes.
  • wmem_max — Sets the send socket buffer maximum size in bytes.
The /proc/sys/net/ipv4/ directory contains additional networking settings. Many of these settings, used in conjunction with one another, are useful in preventing attacks on the system or when using the system to act as a router.

Caution

An erroneous change to these files may affect remote connectivity to the system.
The following is a list of some of the more important files within the /proc/sys/net/ipv4/ directory:
  • icmp_destunreach_rate, icmp_echoreply_rate, icmp_paramprob_rate, and icmp_timeexeed_rate — Set the maximum ICMP send packet rate, in 1/100 of a second, to hosts under certain conditions. A setting of 0 removes any delay and is not a good idea.
  • icmp_echo_ignore_all and icmp_echo_ignore_broadcasts — Allows the kernel to ignore ICMP ECHO packets from every host or only those originating from broadcast and multicast addresses, respectively. A value of 0 allows the kernel to respond, while a value of 1 ignores the packets.
  • ip_default_ttl — Sets the default Time To Live (TTL), which limits the number of hops a packet may make before reaching its destination. Increasing this value can diminish system performance.
  • ip_forward — Permits interfaces on the system to forward packets to one other. By default, this file is set to 0. Setting this file to 1 enables network packet forwarding.
  • ip_local_port_range — Specifies the range of ports to be used by TCP or UDP when a local port is needed. The first number is the lowest port to be used and the second number specifies the highest port. Any systems that expect to require more ports than the default 1024 to 4999 should use a range from 32768 to 61000.
  • tcp_syn_retries — Provides a limit on the number of times the system re-transmits a SYN packet when attempting to make a connection.
  • tcp_retries1 — Sets the number of permitted re-transmissions attempting to answer an incoming connection. Default of 3.
  • tcp_retries2 — Sets the number of permitted re-transmissions of TCP packets. Default of 15.
The file called
/usr/share/doc/kernel-doc-<version>/Documentation/networking/ ip-sysctl.txt
contains a complete list of files and options available in the /proc/sys/net/ipv4/ directory.
A number of other directories exist within the /proc/sys/net/ipv4/ directory and each covers a different aspect of the network stack. The /proc/sys/net/ipv4/conf/ directory allows each system interface to be configured in different ways, including the use of default settings for unconfigured devices (in the /proc/sys/net/ipv4/conf/default/ subdirectory) and settings that override all special configurations (in the /proc/sys/net/ipv4/conf/all/ subdirectory).
The /proc/sys/net/ipv4/neigh/ directory contains settings for communicating with a host directly connected to the system (called a network neighbor) and also contains different settings for systems more than one hop away.
Routing over IPV4 also has its own directory, /proc/sys/net/ipv4/route/. Unlike conf/ and neigh/, the /proc/sys/net/ipv4/route/ directory contains specifications that apply to routing with any interfaces on the system. Many of these settings, such as max_size, max_delay, and min_delay, relate to controlling the size of the routing cache. To clear the routing cache, write any value to the flush file.
Additional information about these directories and the possible values for their configuration files can be found in:
/usr/share/doc/kernel-doc-<version>/Documentation/filesystems/proc.txt

4.3.9.5. /proc/sys/vm/

This directory facilitates the configuration of the Linux kernel's virtual memory (VM) subsystem. The kernel makes extensive and intelligent use of virtual memory, which is commonly referred to as swap space.
The following files are commonly found in the /proc/sys/vm/ directory:
  • block_dump — Configures block I/O debugging when enabled. All read/write and block dirtying operations done to files are logged accordingly. This can be useful if diagnosing disk spin up and spin downs for laptop battery conservation. All output when block_dump is enabled can be retrieved via dmesg. The default value is 0.

    Tip

    If block_dump is enabled at the same time as kernel debugging, it is prudent to stop the klogd daemon, as it generates erroneous disk activity caused by block_dump.
  • dirty_background_ratio — Starts background writeback of dirty data at this percentage of total memory, via a pdflush daemon. The default value is 10.
  • dirty_expire_centisecs — Defines when dirty in-memory data is old enough to be eligible for writeout. Data which has been dirty in-memory for longer than this interval is written out next time a pdflush daemon wakes up. The default value is 3000, expressed in hundredths of a second.
  • dirty_ratio — Starts active writeback of dirty data at this percentage of total memory for the generator of dirty data, via pdflush. The default value is 40.
  • dirty_writeback_centisecs — Defines the interval between pdflush daemon wakeups, which periodically writes dirty in-memory data out to disk. The default value is 500, expressed in hundredths of a second.
  • laptop_mode — Minimizes the number of times that a hard disk needs to spin up by keeping the disk spun down for as long as possible, therefore conserving battery power on laptops. This increases efficiency by combining all future I/O processes together, reducing the frequency of spin ups. The default value is 0, but is automatically enabled in case a battery on a laptop is used.
    This value is controlled automatically by the acpid daemon once a user is notified battery power is enabled. No user modifications or interactions are necessary if the laptop supports the ACPI (Advanced Configuration and Power Interface) specification.
    For more information, refer to the following installed documentation:
    /usr/share/doc/kernel-doc-<version>/Documentation/laptop-mode.txt
  • lower_zone_protection — Determines how aggressive the kernel is in defending lower memory allocation zones. This is effective when utilized with machines configured with highmem memory space enabled. The default value is 0, no protection at all. All other integer values are in megabytes, and lowmem memory is therefore protected from being allocated by users.
    For more information, refer to the following installed documentation:
    /usr/share/doc/kernel-doc-<version>/Documentation/filesystems/proc.txt
  • max_map_count — Configures the maximum number of memory map areas a process may have. In most cases, the default value of 65536 is appropriate.
  • min_free_kbytes — Forces the Linux VM (virtual memory manager) to keep a minimum number of kilobytes free. The VM uses this number to compute a pages_min value for each lowmem zone in the system. The default value is in respect to the total memory on the machine.
  • nr_hugepages — Indicates the current number of configured hugetlb pages in the kernel.
    For more information, refer to the following installed documentation:
    /usr/share/doc/kernel-doc-<version>/Documentation/vm/hugetlbpage.txt
  • nr_pdflush_threads — Indicates the number of pdflush daemons that are currently running. This file is read-only, and should not be changed by the user. Under heavy I/O loads, the default value of two is increased by the kernel.
  • overcommit_memory — Configures the conditions under which a large memory request is accepted or denied. The following three modes are available:
    • 0 — The kernel performs heuristic memory over commit handling by estimating the amount of memory available and failing requests that are blatantly invalid. Unfortunately, since memory is allocated using a heuristic rather than a precise algorithm, this setting can sometimes allow available memory on the system to be overloaded. This is the default setting.
    • 1 — The kernel performs no memory over commit handling. Under this setting, the potential for memory overload is increased, but so is performance for memory intensive tasks (such as those executed by some scientific software).
    • 2 — The kernel fails requests for memory that add up to all of swap plus the percent of physical RAM specified in /proc/sys/vm/overcommit_ratio. This setting is best for those who desire less risk of memory overcommitment.

      Note

      This setting is only recommended for systems with swap areas larger than physical memory.
  • overcommit_ratio — Specifies the percentage of physical RAM considered when /proc/sys/vm/overcommit_memory is set to 2. The default value is 50.
  • page-cluster — Sets the number of pages read in a single attempt. The default value of 3, which actually relates to 16 pages, is appropriate for most systems.
  • swappiness — Determines how much a machine should swap. The higher the value, the more swapping occurs. The default value, as a percentage, is set to 60.
All kernel-based documentation can be found in the following locally installed location:
/usr/share/doc/kernel-doc-<version>/Documentation/, which contains additional information.

4.3.10. /proc/sysvipc/

This directory contains information about System V IPC resources. The files in this directory relate to System V IPC calls for messages (msg), semaphores (sem), and shared memory (shm).

4.3.11. /proc/tty/

This directory contains information about the available and currently used tty devices on the system. Originally called teletype devices, any character-based data terminals are called tty devices.
In Linux, there are three different kinds of tty devices. Serial devices are used with serial connections, such as over a modem or using a serial cable. Virtual terminals create the common console connection, such as the virtual consoles available when pressing Alt+<F-key> at the system console. Pseudo terminals create a two-way communication that is used by some higher level applications, such as XFree86. The drivers file is a list of the current tty devices in use, as in the following example:
serial               /dev/cua        5  64-127 serial:callout
serial               /dev/ttyS       4  64-127 serial
pty_slave            /dev/pts      136   0-255 pty:slave
pty_master           /dev/ptm      128   0-255 pty:master
pty_slave            /dev/ttyp       3   0-255 pty:slave
pty_master           /dev/pty        2   0-255 pty:master
/dev/vc/0            /dev/vc/0       4       0 system:vtmaster
/dev/ptmx            /dev/ptmx       5       2 system
/dev/console         /dev/console    5       1 system:console
/dev/tty             /dev/tty        5       0 system:/dev/tty
unknown              /dev/vc/%d      4    1-63 console
The /proc/tty/driver/serial file lists the usage statistics and status of each of the serial tty lines.
In order for tty devices to be used as network devices, the Linux kernel enforces line discipline on the device. This allows the driver to place a specific type of header with every block of data transmitted over the device, making it possible for the remote end of the connection to a block of data as just one in a stream of data blocks. SLIP and PPP are common line disciplines, and each are commonly used to connect systems to one other over a serial link.
Registered line disciplines are stored in the ldiscs file, and more detailed information is available within the ldisc/ directory.

4.3.12. /proc/<PID>/

Out of Memory (OOM) refers to a computing state where all available memory, including swap space, has been allocated. When this situation occurs, it will cause the system to panic and stop functioning as expected. There is a switch that controls OOM behavior in /proc/sys/vm/panic_on_oom. When set to 1 the kernel will panic on OOM. A setting of 0 instructs the kernel to call a function named oom_killer on an OOM. Usually, oom_killer can kill rogue processes and the system will survive.
The easiest way to change this is to echo the new value to /proc/sys/vm/panic_on_oom.
~]# cat /proc/sys/vm/panic_on_oom
1
~]# echo 0 > /proc/sys/vm/panic_on_oom
~]# cat /proc/sys/vm/panic_on_oom
0
It is also possible to prioritize which processes get killed by adjusting the oom_killer score. In /proc/<PID>/ there are two tools labelled oom_adj and oom_score. Valid scores for oom_adj are in the range -16 to +15. To see the current oom_killer score, view the oom_score for the process. oom_killer will kill processes with the highest scores first.
This example adjusts the oom_score of a process with a PID of 12465 to make it less likely that oom_killer will kill it.
~]# cat /proc/12465/oom_score
79872
~]# echo -5 > /proc/12465/oom_adj
~]# cat /proc/12465/oom_score
78
There is also a special value of -17, which disables oom_killer for that process. In the example below, oom_score returns a value of 0, indicating that this process would not be killed.
~]# cat /proc/12465/oom_score
78
~]# echo -17 > /proc/12465/oom_adj
~]# cat /proc/12465/oom_score
0
A function called badness() is used to determine the actual score for each process. This is done by adding up 'points' for each examined process. The process scoring is done in the following way:
  1. The basis of each process's score is its memory size.
  2. The memory size of any of the process's children (not including a kernel thread) is also added to the score
  3. The process's score is increased for 'niced' processes and decreased for long running processes.
  4. Processes with the CAP_SYS_ADMIN and CAP_SYS_RAWIO capabilities have their scores reduced.
  5. The final score is then bitshifted by the value saved in the oom_adj file.
Thus, a process with the highest oom_score value will most probably be a non-privileged, recently started process that, along with its children, uses a large amount of memory, has been 'niced', and handles no raw I/O.

4.4. Using the sysctl Command

The /sbin/sysctl command is used to view, set, and automate kernel settings in the /proc/sys/ directory.
For a quick overview of all settings configurable in the /proc/sys/ directory, type the /sbin/sysctl -a command as root. This creates a large, comprehensive list, a small portion of which looks something like the following:
net.ipv4.route.min_delay = 2 kernel.sysrq = 0 kernel.sem = 250     32000     32     128
This is the same information seen if each of the files were viewed individually. The only difference is the file location. For example, the /proc/sys/net/ipv4/route/min_delay file is listed as net.ipv4.route.min_delay, with the directory slashes replaced by dots and the proc.sys portion assumed.
The sysctl command can be used in place of echo to assign values to writable files in the /proc/sys/ directory. For example, instead of using the command
echo 1 > /proc/sys/kernel/sysrq
use the equivalent sysctl command as follows:
~]# sysctl -w kernel.sysrq="1"
kernel.sysrq = 1
While quickly setting single values like this in /proc/sys/ is helpful during testing, this method does not work as well on a production system as special settings within /proc/sys/ are lost when the machine is rebooted. To preserve custom settings, add them to the /etc/sysctl.conf file.
Each time the system boots, the init program runs the /etc/rc.d/rc.sysinit script. This script contains a command to execute sysctl using /etc/sysctl.conf to determine the values passed to the kernel. Any values added to /etc/sysctl.conf therefore take effect each time the system boots.

4.5. Additional Resources

Below are additional sources of information about proc file system.

4.5.1. Installed Documentation

Some of the best documentation about the proc file system is installed on the system by default.
  • /usr/share/doc/kernel-doc-<version>/Documentation/filesystems/proc.txt — Contains assorted, but limited, information about all aspects of the /proc/ directory.
  • /usr/share/doc/kernel-doc-<version>/Documentation/sysrq.txt — An overview of System Request Key options.
  • /usr/share/doc/kernel-doc-<version>/Documentation/sysctl/ — A directory containing a variety of sysctl tips, including modifying values that concern the kernel (kernel.txt), accessing file systems (fs.txt), and virtual memory use (vm.txt).
  • /usr/share/doc/kernel-doc-<version>/Documentation/networking/ip-sysctl.txt — A detailed overview of IP networking options.

4.5.2. Useful Websites

  • http://www.linuxhq.com/ — This website maintains a complete database of source, patches, and documentation for various versions of the Linux kernel.

Capítulo 5. Redundant Array of Independent Disks (RAID)

The basic idea behind RAID is to combine multiple small, inexpensive disk drives into an array to accomplish performance or redundancy goals not attainable with one large and expensive drive. This array of drives appears to the computer as a single logical storage unit or drive.

5.1. What is RAID?

RAID allows information to access several disks. RAID uses techniques such as disk striping (RAID Level 0), disk mirroring (RAID Level 1), and disk striping with parity (RAID Level 5) to achieve redundancy, lower latency, increased bandwidth, and maximized ability to recover from hard disk crashes.
RAID consistently distributes data across each drive in the array. RAID then breaks down the data into consistently-sized chunks (commonly 32K or 64k, although other values are acceptable). Each chunk is then written to a hard drive in the RAID array according to the RAID level employed. When the data is read, the process is reversed, giving the illusion that the multiple drives in the array are actually one large drive.

5.1.1. Who Should Use RAID?

System Administrators and others who manage large amounts of data would benefit from using RAID technology. Primary reasons to deploy RAID include:
  • Enhances speed
  • Increases storage capacity using a single virtual disk
  • Minimizes disk failure

5.1.2. Hardware RAID versus Software RAID

There are two possible RAID approaches: hardware RAID and software RAID.
Hardware RAID
The hardware-based array manages the RAID subsystem independently from the host. It presents a single disk per RAID array to the host.
A hardware RAID device connects to the SCSI controller and presents the RAID arrays as a single SCSI drive. An external RAID system moves all RAID handling intelligence into a controller located in the external disk subsystem. The whole subsystem is connected to the host via a normal SCSI controller and appears to the host as a single disk.
RAID controller cards function like a SCSI controller to the operating system, and handle all the actual drive communications. The user plugs the drives into the RAID controller (just like a normal SCSI controller) and then adds them to the RAID controllers configuration, and the operating system won't know the difference.
Software RAID
Software RAID implements the various RAID levels in the kernel disk (block device) code. It offers the cheapest possible solution, as expensive disk controller cards or hot-swap chassis[1] are not required. Software RAID also works with cheaper IDE disks as well as SCSI disks. With today's faster CPUs, software RAID outperforms hardware RAID.
The Linux kernel contains an MD driver that allows the RAID solution to be completely hardware independent. The performance of a software-based array depends on the server CPU performance and load.
To learn more about software RAID, here are the key features:
  • Threaded rebuild process
  • Kernel-based configuration
  • Portability of arrays between Linux machines without reconstruction
  • Backgrounded array reconstruction using idle system resources
  • Hot-swappable drive support
  • Automatic CPU detection to take advantage of certain CPU optimizations

5.1.3. RAID Levels and Linear Support

RAID supports various configurations, including levels 0, 1, 4, 5, and linear. These RAID types are defined as follows:
Level 0
RAID level 0, often called striping, is a performance-oriented striped data mapping technique. This means the data being written to the array is broken down into strips and written across the member disks of the array, allowing high I/O performance at low inherent cost but provides no redundancy. The storage capacity of a level 0 array is equal to the total capacity of the member disks in a hardware RAID or the total capacity of member partitions in a software RAID.
Level 1
RAID level 1, or mirroring, has been used longer than any other form of RAID. Level 1 provides redundancy by writing identical data to each member disk of the array, leaving a mirrored copy on each disk. Mirroring remains popular due to its simplicity and high level of data availability. Level 1 operates with two or more disks that may use parallel access for high data-transfer rates when reading but more commonly operate independently to provide high I/O transaction rates. Level 1 provides very good data reliability and improves performance for read-intensive applications but at a relatively high cost. The storage capacity of the level 1 array is equal to the capacity of one of the mirrored hard disks in a hardware RAID or one of the mirrored partitions in a software RAID.

Nota

RAID level 1 comes at a high cost because you write the same information to all of the disks in the array, which wastes drive space. For example, if you have RAID level 1 set up so that your root (/) partition exists on two 40G drives, you have 80G total but are only able to access 40G of that 80G. The other 40G acts like a mirror of the first 40G.
Level 4
RAID level 4 uses parity[2] concentrated on a single disk drive to protect data. It is better suited to transaction I/O rather than large file transfers. Because the dedicated parity disk represents an inherent bottleneck, level 4 is seldom used without accompanying technologies such as write-back caching. Although RAID level 4 is an option in some RAID partitioning schemes, it is not an option allowed in Red Hat Enterprise Linux RAID installations. The storage capacity of hardware RAID level 4 is equal to the capacity of member disks, minus the capacity of one member disk. The storage capacity of software RAID level 4 is equal to the capacity of the member partitions, minus the size of one of the partitions if they are of equal size.

Nota

RAID level 4 takes up the same amount of space as RAID level 5, but level 5 has more advantages. For this reason, level 4 is not supported.
Level 5
RAID level 5 is the most common type of RAID. By distributing parity across some or all of an array's member disk drives, RAID level 5 eliminates the write bottleneck inherent in level 4. The only performance bottleneck is the parity calculation process. With modern CPUs and software RAID, that usually is not a very big problem. As with level 4, the result is asymmetrical performance, with reads substantially outperforming writes. Level 5 is often used with write-back caching to reduce the asymmetry. The storage capacity of hardware RAID level 5 is equal to the capacity of member disks, minus the capacity of one member disk. The storage capacity of software RAID level 5 is equal to the capacity of the member partitions, minus the size of one of the partitions if they are of equal size.
Linear RAID
Linear RAID is a simple grouping of drives to create a larger virtual drive. In linear RAID, the chunks are allocated sequentially from one member drive, going to the next drive only when the first is completely filled. This grouping provides no performance benefit, as it is unlikely that any I/O operations will be split between member drives. Linear RAID also offers no redundancy and, in fact, decreases reliability — if any one member drive fails, the entire array cannot be used. The capacity is the total of all member disks.

5.2. Configuring Software RAID

Users can configure software RAID during the graphical installation process, the text-based installation process, or during a kickstart installation. This section discusses software RAID configuration during the installation process using the Disk Druid application, and covers the following steps:
  1. Creating software RAID partitions on physical hard drives.
  2. Creating RAID devices from the software RAID partitions.
  3. (Optional) Configuring LVM from the RAID devices.
  4. Creating file systems from the RAID devices.
To configure software RAID, select Create custom layout from the pulldown list on the Disk Partitioning Setup screen, click the Next button, and follow the instructions in the rest of this section. The example screenshots in this section use two 10 GB disk drives (/dev/hda and /dev/hdb) to illustrate the creation of simple RAID 1 and RAID 0 configurations, and detail how to create a simple RAID configuration by implementing multiple RAID devices.

5.2.1. riando uma Nova Partição RAID

In a typical situation, the disk drives are new or are formatted. Both drives are shown as raw devices with no partition configuration in Figura 5.1, “Two Blank Drives, Ready For Configuration”.
Two Blank Drives, Ready For Configuration
Two Blank Drives, Ready For Configuration
Figura 5.1. Two Blank Drives, Ready For Configuration

  1. In Disk Druid, click the RAID button to enter the software RAID creation screen.
  2. Choose Create a software RAID partition to create a RAID partition as shown in Figura 5.2, “RAID Partition Options”. Note that no other RAID options (such as entering a mount point) are available until RAID partitions, as well as RAID devices, are created. Click OK to confirm the choice.
    RAID Partition Options
    RAID Partition Options
    Figura 5.2. RAID Partition Options

  3. A software RAID partition must be constrained to one drive. For Allowable Drives, select the drive to use for RAID. If you have multiple drives, by default all drives are selected and you must deselect the drives you do not want.
    Adding a RAID Partition
    Adding a RAID Partition
    Figura 5.3. Adding a RAID Partition

  4. Edit the Size (MB) field, and enter the size that you want the partition to be (in MB).
  5. Select Fixed Size to specify partition size. Select Fill all space up to (MB) and enter a value (in MB) to specify partition size range. Select Fill to maximum allowable size to allow maximum available space of the hard disk. Note that if you make more than one space growable, they share the available free space on the disk.
  6. Select Force to be a primary partition if you want the partition to be a primary partition. A primary partition is one of the first four partitions on the hard drive. If unselected, the partition is created as a logical partition. If other operating systems are already on the system, unselecting this option should be considered. For more information on primary versus logical/extended partitions, refer to the appendix section of the Red Hat Enterprise Linux Installation Guide.
Repeat these steps to create as many partitions as needed for your RAID setup. Notice that all the partitions do not have to be RAID partitions. For example, you can configure only the /boot partition as a software RAID device, leaving the root partition (/), /home, and swap as regular file systems. Figura 5.4, “RAID 1 Partitions Ready, Pre-Device and Mount Point Creation” shows successfully allocated space for the RAID 1 configuration (for /boot), which is now ready for RAID device and mount point creation:
RAID 1 Partitions Ready, Pre-Device and Mount Point Creation
RAID 1 Partitions Ready, Pre-Device and Mount Point Creation
Figura 5.4. RAID 1 Partitions Ready, Pre-Device and Mount Point Creation

5.2.2. Creating the RAID Devices and Mount Points

Once you create all of your partitions as software RAID partitions, you must create the RAID device and mount point.
  1. On the main partitioning screen, click the RAID button. The RAID Options dialog appears as shown in Figura 5.5, “Opções do RAID”.
    Opções do RAID
    Opção de Seleção do RAID
    Figura 5.5. Opções do RAID

  2. Select the Create a RAID device option, and click OK. As shown in Figura 5.6, “Making a RAID Device and Assigning a Mount Point”, the Make RAID Device dialog appears, allowing you to make a RAID device and assign a mount point.
    Making a RAID Device and Assigning a Mount Point
    Making a RAID Device and Assigning a Mount Point
    Figura 5.6. Making a RAID Device and Assigning a Mount Point

  3. Select a mount point from the Mount Point pulldown list.
  4. Choose the file system type for the partition from the File System Type pulldown list. At this point you can either configure a dynamic LVM file system or a traditional static ext2/ext3 file system. For more information on LVM and its configuration during the installation process, refer to Capítulo 10, LVM (Logical Volume Manager). If LVM is not required, continue on with the following instructions.
  5. From the RAID Device pulldown list, select a device name such as md0.
  6. From the RAID Level, choose the required RAID level.

    Nota

    If you are making a RAID partition of /boot, you must choose RAID level 1, and it must use one of the first two drives (IDE first, SCSI second). If you are not creating a separate RAID partition of /boot, and you are making a RAID partition for the root file system (that is, /), it must be RAID level 1 and must use one of the first two drives (IDE first, SCSI second).
  7. The RAID partitions created appear in the RAID Members list. Select which of these partitions should be used to create the RAID device.
  8. If configuring RAID 1 or RAID 5, specify the number of spare partitions in the Number of spares field. If a software RAID partition fails, the spare is automatically used as a replacement. For each spare you want to specify, you must create an additional software RAID partition (in addition to the partitions for the RAID device). Select the partitions for the RAID device and the partition(s) for the spare(s).
  9. Click OK to confirm the setup. The RAID device appears in the Drive Summary list.
  10. Repeat this chapter's entire process for configuring additional partitions, devices, and mount points, such as the root partition (/), home partition (/home), or swap.
After completing the entire configuration, the figure as shown in Figura 5.7, “Sample RAID Configuration” resembles the default configuration, except for the use of RAID.
Sample RAID Configuration
Sample RAID Configuration
Figura 5.7. Sample RAID Configuration

The figure as shown in Figura 5.8, “Sample RAID With LVM Configuration” is an example of a RAID and LVM configuration.
Sample RAID With LVM Configuration
Sample RAID With LVM Configuration
Figura 5.8. Sample RAID With LVM Configuration

You can proceed with your installation process by clicking Next. Refer to the Red Hat Enterprise Linux Installation Guide for further instructions.

5.3. Managing Software RAID

This section discusses software RAID configuration and management after the installation, and covers the following topics:
  • Reviewing existing software RAID configuration.
  • Creating a new RAID device.
  • Replacing a faulty device in an array.
  • Adding a new device to an existing array.
  • Deactivating and removing an existing RAID device.
  • Saving the configuration.
All examples in this section use the software RAID configuration from the previous section.

5.3.1. Reviewing RAID Configuration

When a software RAID is in use, basic information about all presently active RAID devices are stored in the /proc/mdstat special file. To list these devices, display the content of this file by typing the following at a shell prompt:
cat /proc/mdstat
To determine whether a certain device is a RAID device or a component device, run the command in the following form as root:
mdadm --query device
In order to examine a RAID device in more detail, use the following command:
mdadm --detail raid_device
Similarly, to examine a component device, type:
mdadm --examine component_device
While the mdadm --detail command displays information about a RAID device, mdadm --examine only relays information about a RAID device as it relates to a given component device. This distinction is particularly important when working with a RAID device that itself is a component of another RAID device.
The mdadm --query command, as well as both mdadm --detail and mdadm --examine commands allow you to specify multiple devices at once.
Exemplo 5.1. Reviewing RAID configuration
Assume the system uses configuration from Figura 5.7, “Sample RAID Configuration”. You can verify that /dev/md0 is a RAID device by typing the following at a shell prompt:
~]# mdadm --query /dev/md0
/dev/md0: 125.38MiB raid1 2 devices, 0 spares. Use mdadm --detail for more detail.
/dev/md0: No md super block found, not an md component.
As you can see, the above command produces only a brief overview of the RAID device and its configuration. To display more detailed information, use the following command instead:
~]# mdadm --detail /dev/md0
/dev/md0:
        Version : 0.90
  Creation Time : Tue Jun 28 16:05:49 2011
     Raid Level : raid1
     Array Size : 128384 (125.40 MiB 131.47 MB)
  Used Dev Size : 128384 (125.40 MiB 131.47 MB)
   Raid Devices : 2
  Total Devices : 2
Preferred Minor : 0
    Persistence : Superblock is persistent

    Update Time : Thu Jun 30 17:06:34 2011
          State : clean
 Active Devices : 2
Working Devices : 2
 Failed Devices : 0
  Spare Devices : 0

           UUID : 49c5ac74:c2b79501:5c28cb9c:16a6dd9f
         Events : 0.6

    Number   Major   Minor   RaidDevice State
       0       3        1        0      active sync   /dev/hda1
       1       3       65        1      active sync   /dev/hdb1
Finally, to list all presently active RAID devices, type:
~]$ cat /proc/mdstat
Personalities : [raid0] [raid1]
md0 : active raid1 hdb1[1] hda1[0]
      128384 blocks [2/2] [UU]
      
md1 : active raid0 hdb2[1] hda2[0]
      1573888 blocks 256k chunks

md2 : active raid0 hdb3[1] hda3[0]
      19132928 blocks 256k chunks

unused devices: <none>

5.3.2. Creating a New RAID Device

To create a new RAID device, use the command in the following form as root:
mdadm --create raid_device --level=level --raid-devices=number component_device
This is the simplest way to create a RAID array. There are many more options that allow you to specify the number of spare devices, the block size of a stripe array, if the array has a write-intent bitmap, and much more. All these options can have a significant impact on the performance, but are beyond the scope of this document. For more detailed information, refer to the CREATE MODE section of the mdadm(8) manual page.
Exemplo 5.2. Creating a new RAID device
Assume that the system has two unused SCSI disk drives available, and that each of these devices has exactly one partition of the same size:
~]# ls /dev/sd*
/dev/sda  /dev/sda1  /dev/sdb  /dev/sdb1
To create /dev/md3 as a new RAID level 1 array from /dev/sda1 and /dev/sdb1, run the following command:
~]# mdadm --create /dev/md3 --level=1 --raid-devices=2 /dev/sda1 /dev/sdb1
mdadm: array /dev/md3 started.

5.3.3. Replacing a Faulty Device

To replace a particular device in a software RAID, first make sure it is marked as faulty by running the following command as root:
mdadm raid_device --fail component_device
Then remove the faulty device from the array by using the command in the following form:
mdadm raid_device --remove component_device
Once the device is operational again, you can re-add it to the array:
mdadm raid_device --add component_device
Exemplo 5.3. Replacing a faulty device
Assume the system has an active RAID device, /dev/md3, with the following layout (that is, the RAID device created in Exemplo 5.2, “Creating a new RAID device”):
~]# mdadm --detail /dev/md3 | tail -n 3
    Number   Major   Minor   RaidDevice State
       0       8        1        0      active sync   /dev/sda1
       1       8       17        1      active sync   /dev/sdb1
Imagine the first disk drive fails and needs to be replaced. To do so, first mark the /dev/sdb1 device as faulty:
~]# mdadm /dev/md3 --fail /dev/sdb1
mdadm: set /dev/sdb1 faulty in /dev/md3
Then remove it from the RAID device:
~]# mdadm /dev/md3 --remove /dev/sdb1
mdadm: hot removed /dev/sdb1
As soon as the hardware is replaced, you can add the device back to the array by using the following command:
~]# mdadm /dev/md3 --add /dev/sdb1
mdadm: added /dev/sdb1

5.3.4. Extending a RAID Device

To add a new device to an existing array, use the command in the following form as root:
mdadm raid_device --add component_device
This will add the device as a spare device. To grow the array to use this device actively, type the following at a shell prompt:
mdadm --grow raid_device --raid-devices=number
Exemplo 5.4. Extending a RAID device
Assume the system has an active RAID device, /dev/md3, with the following layout (that is, the RAID device created in Exemplo 5.2, “Creating a new RAID device”):
~]# mdadm --detail /dev/md3 | tail -n 3
    Number   Major   Minor   RaidDevice State
       0       8        1        0      active sync   /dev/sda1
       1       8       17        1      active sync   /dev/sdb1
Also assume that a new SCSI disk drive, /dev/sdc, has been added and has exactly one partition. To add it to the /dev/md3 array, type the following at a shell prompt:
~]# mdadm /dev/md3 --add /dev/sdc1
mdadm: added /dev/sdc1
This will add /dev/sdc1 as a spare device. To change the size of the array to actually use it, type:
~]# mdadm --grow /dev/md3 --raid-devices=3

5.3.5. Removing a RAID Device

To remove an existing RAID device, first deactivate it by running the following command as root:
mdadm --stop raid_device
Once deactivated, remove the RAID device itself:
mdadm --remove raid_device
Finally, zero superblocks on all devices that were associated with the particular array:
mdadm --zero-superblock component_device
Exemplo 5.5. Removing a RAID device
Assume the system has an active RAID device, /dev/md3, with the following layout (that is, the RAID device created in Exemplo 5.4, “Extending a RAID device”):
~]# mdadm --detail /dev/md3 | tail -n 4
    Number   Major   Minor   RaidDevice State
       0       8        1        0      active sync   /dev/sda1
       1       8       17        1      active sync   /dev/sdb1
       2       8       33        2      active sync   /dev/sdc1
In order to remove this device, first stop it by typing the following at a shell prompt:
~]# mdadm --stop /dev/md3
mdadm: stopped /dev/md3
Once stopped, you can remove the /dev/md3 device by running the following command:
~]# mdadm --remove /dev/md3
Finally, to remove the superblocks from all associated devices, type:
~]# mdadm --zero-superblock /dev/sda1 /dev/sdb1 /dev/sdc1

5.3.6. Preserving the Configuration

By default, changes made by the mdadm command only apply to the current session, and will not survive a system restart. At boot time, the mdmonitor service reads the content of the /etc/mdadm.conf configuration file to see which RAID devices to start. If the software RAID was configured during the graphical installation process, this file contains directives listed in Tabela 5.1, “Common mdadm.conf directives” by default.
Tabela 5.1. Common mdadm.conf directives
Option Description
ARRAY
Allows you to identify a particular array.
DEVICE
Allows you to specify a list of devices to scan for a RAID component (for example, /dev/hda1). You can also use the keyword partitions to use all partitions listed in /proc/partitions, or containers to specify an array container.
MAILADDR Allows you to specify an email address to use in case of an alert.

To list what ARRAY lines are presently in use regardless of the configuration, run the following command as root:
mdadm --detail --scan
Use the output of this command to determine which lines to add to the /etc/mdadm.conf file. You can also display the ARRAY line for a particular device:
mdadm --detail --brief raid_device
By redirecting the output of this command, you can add such a line to the configuration file with a single command:
mdadm --detail --brief raid_device >> /etc/mdadm.conf
Exemplo 5.6. Preserving the configuration
By default, the /etc/mdadm.conf contains the software RAID configuration created during the system installation:
# mdadm.conf written out by anaconda
DEVICE partitions
MAILADDR root
ARRAY /dev/md0 level=raid1 num-devices=2 UUID=49c5ac74:c2b79501:5c28cb9c:16a6dd9f
ARRAY /dev/md1 level=raid0 num-devices=2 UUID=76914c11:5bfa2c00:dc6097d1:a1f4506d
ARRAY /dev/md2 level=raid0 num-devices=2 UUID=2b5d38d0:aea898bf:92be20e2:f9d893c5
Assuming you have created the /dev/md3 device as shown in Exemplo 5.2, “Creating a new RAID device”, you can make it persistent by running the following command:
~]# mdadm --detail --brief /dev/md3 >> /etc/mdadm.conf

5.4. Additional Resources

For more information on RAID, refer to the following resources.

5.4.1. Installed Documentation

  • mdadm man page — A manual page for the mdadm utility.
  • mdadm.conf man page — A manual page that provides a comprehensive list of available /etc/mdadm.conf configuration options.


[1] A hot-swap chassis allows you to remove a hard drive without having to power-down your system.
[2] Parity information is calculated based on the contents of the rest of the member disks in the array. This information can then be used to reconstruct data when one disk in the array fails. The reconstructed data can then be used to satisfy I/O requests to the failed disk before it is replaced and to repopulate the failed disk after it has been replaced.

Capítulo 6. Espaço Virtual (swap space)

6.1. O que é Espaço Virtual?

Swap space in Linux is used when the amount of physical memory (RAM) is full. If the system needs more memory resources and the RAM is full, inactive pages in memory are moved to the swap space. While swap space can help machines with a small amount of RAM, it should not be considered a replacement for more RAM. Swap space is located on hard drives, which have a slower access time than physical memory.
O espaço virtual pode ser uma partição virtual (swap) dedicada (recomendado), um arquivo virtual ou uma combinação de partições e arquivos virtuais.
In years past, the recommended amount of swap space increased linearly with the amount of RAM in the system. But because the amount of memory in modern systems has increased into the hundreds of gigabytes, it is now recognized that the amount of swap space that a system needs is a function of the memory workload running on that system. However, given that swap space is usually designated at install time, and that it can be difficult to determine beforehand the memory workload of a system, we recommend determining system swap using the following table.

Important

File systems and LVM2 volumes assigned as swap space cannot be in use when being modified. For example, no system processes can be assigned the swap space, as well as no amount of swap should be allocated and used by the kernel. Use the free and cat /proc/swaps commands to verify how much and where swap is in use.
The best way to achieve swap space modifications is to boot your system in rescue mode, and then follow the instructions (for each scenario) in the remainder of this chapter. Refer to the Red Hat Enterprise Linux Installation Guide for instructions on booting into rescue mode. When prompted to mount the file system, select Skip.

6.2. Adicionando Espaço Virtual

Sometimes it is necessary to add more swap space after installation. For example, you may upgrade the amount of RAM in your system from 128 MB to 256 MB, but there is only 256 MB of swap space. It might be advantageous to increase the amount of swap space to 512 MB if you perform memory-intense operations or run applications that require a large amount of memory.
You have three options: create a new swap partition, create a new swap file, or extend swap on an existing LVM2 logical volume. It is recommended that you extend an existing logical volume.

6.2.1. Extending Swap on an LVM2 Logical Volume

To extend an LVM2 swap logical volume (assuming /dev/VolGroup00/LogVol01 is the volume you want to extend):
  1. Disable swapping for the associated logical volume:
    swapoff -v /dev/VolGroup00/LogVol01
  2. Resize the LVM2 logical volume by 256 MB:
    lvm lvresize /dev/VolGroup00/LogVol01 -L +256M
  3. Format the new swap space:
    mkswap /dev/VolGroup00/LogVol01
  4. Enable the extended logical volume:
    swapon -va
  5. Test that the logical volume has been extended properly:
    cat /proc/swaps
    free

6.2.2. Creating an LVM2 Logical Volume for Swap

To add a swap volume group (assuming /dev/VolGroup00/LogVol02 is the swap volume you want to add):
  1. Create the LVM2 logical volume of size 256 MB:
    lvm lvcreate VolGroup00 -n LogVol02 -L 256M
  2. Format the new swap space:
    mkswap /dev/VolGroup00/LogVol02
  3. Add the following entry to the /etc/fstab file:
    /dev/VolGroup00/LogVol02   swap     swap    defaults     0 0
  4. Enable the extended logical volume:
    swapon -va
  5. Test that the logical volume has been extended properly:
    cat /proc/swaps
    free

6.2.3. Creating a Swap File

Para adicionar um arquivo virtual:
  1. Determine the size of the new swap file in megabytes and multiply by 1024 to determine the number of blocks. For example, the block size of a 64 MB swap file is 65536.
  2. At a shell prompt as root, type the following command with count being equal to the desired block size:
    dd if=/dev/zero of=/swapfile bs=1024 count=65536
  3. Configure o arquivo virtual com o comando:
    mkswap /swapfile
  4. Para habilitar o arquivo virtual imediatamente, mas não automaticamente no momento da inicialização:
    swapon /swapfile
  5. To enable it at boot time, edit /etc/fstab to include the following entry:
    /swapfile          swap            swap    defaults        0 0
    Na próxima vez que o sistema for iniciado, habilitará o novo arquivo virtual.
  6. After adding the new swap file and enabling it, verify it is enabled by viewing the output of the command cat /proc/swaps or free.

6.3. Removendo Espaço Virtual

Sometimes it can be prudent to reduce swap space after installation. For example, say you downgraded the amount of RAM in your system from 1 GB to 512 MB, but there is 2 GB of swap space still assigned. It might be advantageous to reduce the amount of swap space to 1 GB, since the larger 2 GB could be wasting disk space.
You have three options: remove an entire LVM2 logical volume used for swap, remove a swap file, or reduce swap space on an existing LVM2 logical volume.

6.3.1. Reducing Swap on an LVM2 Logical Volume

To reduce an LVM2 swap logical volume (assuming /dev/VolGroup00/LogVol01 is the volume you want to reduce):
  1. Disable swapping for the associated logical volume:
    swapoff -v /dev/VolGroup00/LogVol01
  2. Reduce the LVM2 logical volume by 512 MB:
    lvm lvreduce /dev/VolGroup00/LogVol01 -L -512M
  3. Format the new swap space:
    mkswap /dev/VolGroup00/LogVol01
  4. Enable the extended logical volume:
    swapon -va
  5. Test that the logical volume has been reduced properly:
    cat /proc/swaps
    free

6.3.2. Removing an LVM2 Logical Volume for Swap

The swap logical volume cannot be in use (no system locks or processes on the volume). The easiest way to achieve this is to boot your system in rescue mode. Refer to the Red Hat Enterprise Linux Installation Guide for instructions on booting into rescue mode. When prompted to mount the file system, select Skip.
To remove a swap volume group (assuming /dev/VolGroup00/LogVol02 is the swap volume you want to remove):
  1. Disable swapping for the associated logical volume:
    swapoff -v /dev/VolGroup00/LogVol02
  2. Remove the LVM2 logical volume of size 512 MB:
    lvm lvremove /dev/VolGroup00/LogVol02
  3. Remove the following entry from the /etc/fstab file:
    /dev/VolGroup00/LogVol02   swap     swap    defaults     0 0
  4. Test that the logical volume has been removed:
    cat /proc/swaps
    free

6.3.3. Removing a Swap File

Para remover um arquivo virtual:
  1. At a shell prompt as root, execute the following command to disable the swap file (where /swapfile is the swap file):
    swapoff -v /swapfile
  2. Remove its entry from the /etc/fstab file.
  3. Remova o arquivo real:
    rm /swapfile

6.4. Movendo Espaço Virtual

Para mover espaço virtual entre duas localidades, siga os passos para remover o espaço virtual e então siga os passos para adicionar espaço virtual.

Capítulo 7. Gerenciando o Armazenamento de Disco

7.1. Standard Partitions using parted

The utility parted allows users to:
  • View the existing partition table
  • Change the size of existing partitions
  • Add partitions from free space or additional hard drives
If you want to view the system's disk space usage or monitor the disk space usage, refer to Seção 40.3, “Sistemas de Arquivos”.
By default, the parted package is included when installing Red Hat Enterprise Linux. To start parted, log in as root and type the command parted /dev/sda at a shell prompt (where /dev/sda is the device name for the drive you want to configure).
If you want to remove or resize a partition, the device on which that partition resides must not be in use. Creating a new partition on a device which is in use—while possible—is not recommended.
For a device to not be in use, none of the partitions on the device can be mounted, and any swap space on the device must not be enabled.
As well, the partition table should not be modified while it is in use because the kernel may not properly recognize the changes. If the partition table does not match the actual state of the mounted partitions, information could be written to the wrong partition, resulting in lost and overwritten data.
The easiest way to achieve this is to boot your system in rescue mode. When prompted to mount the file system, select Skip.
Alternately, if the drive does not contain any partitions in use (system processes that use or lock the file system from being unmounted), you can unmount them with the umount command and turn off all the swap space on the hard drive with the swapoff command.
Tabela 7.1, “parted commands” contains a list of commonly used parted commands. The sections that follow explain some of these commands and arguments in more detail.
Tabela 7.1. parted commands
Comando Descrição
check minor-num Executa uma verificação simples do sistema de arquivo
cp from to Copia o sistema de arquivo de uma partição para outra; de e para são os menores números das partições
help Exibe uma lista dos comandos disponíveis
mklabel label Cria uma etiqueta de disco para a tabela de partições
mkfs minor-num file-system-type Cria um sistema de arquivo do tipo file-system-type
mkpart part-type fs-type start-mb end-mb Cria uma partição sem criar um novo sistema de arquivo
mkpartfs part-type fs-type start-mb end-mb Cria uma partição e o sistema de arquivo especificado
move minor-num start-mb end-mb Move a partição
name minor-num name Nomeia a partição somente para etiquetas de disco do Mac e PC98
print Exibe a tabela de partições
quit Quit parted
rescue start-mb end-mb Recupera uma partição perdida de start-mb para end-mb
resize minor-num start-mb end-mb Redimensiona a partição de start-mb para end-mb
rm minor-num Remove a partição
select device Seleciona um dispositivo diferente para configurar
set minor-num flag state Define a bandeira de uma partição; o estado é ligado (on) ou desligado (off)
toggle [NUMBER [FLAG] Toggle the state of FLAG on partition NUMBER
unit UNIT Set the default unit to UNIT

7.1.1. Visualizando a Tabela de Partições

After starting parted, use the command print to view the partition table. A table similar to the following appears:
Model: ATA ST3160812AS (scsi)
Disk /dev/sda: 160GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End    Size    Type      File system  Flags
 1      32.3kB  107MB  107MB   primary   ext3         boot
 2      107MB   105GB  105GB   primary   ext3
 3      105GB   107GB  2147MB  primary   linux-swap
 4      107GB   160GB  52.9GB  extended		      root
 5      107GB   133GB  26.2GB  logical   ext3
 6      133GB   133GB  107MB   logical   ext3
 7      133GB   160GB  26.6GB  logical                lvm
The first line contains the disk type, manufacturer, model number and interface, and the second line displays the disk label type. The remaining output below the fourth line shows the partition table.
In the partition table, the Minor number is the partition number. For example, the partition with minor number 1 corresponds to /dev/sda1. The Start and End values are in megabytes. Valid Type are metadata, free, primary, extended, or logical. The Filesystem is the file system type, which can be any of the following:
  • ext2
  • ext3
  • fat16
  • fat32
  • hfs
  • jfs
  • linux-swap
  • ntfs
  • reiserfs
  • hp-ufs
  • sun-ufs
  • xfs
If a Filesystem of a device shows no value, this means that its file system type is unknown.
The Flags column lists the flags set for the partition. Available flags are boot, root, swap, hidden, raid, lvm, or lba.

Tip

To select a different device without having to restart parted, use the select command followed by the device name (for example, /dev/sda). Doing so allows you to view or configure the partition table of a device.

7.1.2. Criando uma Partição

Atenção

Não tente criar uma partição em um dispositivo que esteja em uso.
Antes de criar uma partição, inicialize no modo de recuperação (ou desmonte quaisquer partições do dispositivo e desabilite qualquer espaço virtual no dispositivo).
Start parted, where /dev/sda is the device on which to create the partition:
parted /dev/sda
Visualize a tabela de partições corrente para determinar se há espaço livre suficiente:
print
If there is not enough free space, you can resize an existing partition. Refer to Seção 7.1.4, “Redimensionando uma Partição” for details.

7.1.2.1. Criando a partição

From the partition table, determine the start and end points of the new partition and what partition type it should be. You can only have four primary partitions (with no extended partition) on a device. If you need more than four partitions, you can have three primary partitions, one extended partition, and multiple logical partitions within the extended. For an overview of disk partitions, refer to the appendix An Introduction to Disk Partitions in the Red Hat Enterprise Linux Installation Guide.
Por exemplo: para criar uma partição primária com um sistema de arquivo ext3 de 1024 megabytes até 2048 megabytes de um disco rígido, digite o seguinte comando:
mkpart primary ext3 1024 2048

Tip

If you use the mkpartfs command instead, the file system is created after the partition is created. However, parted does not support creating an ext3 file system. Thus, if you wish to create an ext3 file system, use mkpart and create the file system with the mkfs command as described later.
The changes start taking place as soon as you press Enter, so review the command before executing to it.
After creating the partition, use the print command to confirm that it is in the partition table with the correct partition type, file system type, and size. Also remember the minor number of the new partition so that you can label it. You should also view the output of
cat /proc/partitions
para garantir que o kernel reconheça a partição nova.

7.1.2.2. Formatting the Partition

A partição ainda não tem um sistema de arquivo. Crie o sistema de arquivo:
mkfs -t ext3 /dev/sda6

Atenção

Formatar a partição destrói permanentemente quaisquer dados que existam nesta partição.

7.1.2.3. Etiquetando a Partição

Next, give the partition a label. For example, if the new partition is /dev/sda6 and you want to label it /work:
e2label /dev/sda6 /work
Por default, o programa de instalação usa o ponto de montagem da partição como a etiqueta para garantir que esta seja única. Você pode usar qualquer etiqueta que quiser.

7.1.2.4. Criando o Ponto de Montagem

Como root, crie o ponto de montagem:
mkdir /work

7.1.2.5. Add to /etc/fstab

As root, edit the /etc/fstab file to include the new partition. The new line should look similar to the following:
LABEL=/work           /work                 ext3    defaults        1 2
The first column should contain LABEL= followed by the label you gave the partition. The second column should contain the mount point for the new partition, and the next column should be the file system type (for example, ext3 or swap). If you need more information about the format, read the man page with the command man fstab.
If the fourth column is the word defaults, the partition is mounted at boot time. To mount the partition without rebooting, as root, type the command:
mount /work

7.1.3. Removendo uma Partição

Atenção

Não tente remover uma partição de um dispositivo em uso.
Antes de remover a partição, inicialize no modo de recuperação (ou desmonte quaisquer partições do dispositivo e desabilite o espaço virtual do dispositivo).
Start parted, where /dev/sda is the device on which to remove the partition:
parted /dev/sda
Visualize a tabela de partições corrente para determinar o número menor da partição a remover:
print
Remove the partition with the command rm. For example, to remove the partition with minor number 3:
rm 3
The changes start taking place as soon as you press Enter, so review the command before committing to it.
After removing the partition, use the print command to confirm that it is removed from the partition table. You should also view the output of
cat /proc/partitions
para garantir que o kernel saiba da remoção da partição.
The last step is to remove it from the /etc/fstab file. Find the line that declares the removed partition, and remove it from the file.

7.1.4. Redimensionando uma Partição

Atenção

Não tente redimensionar uma partição de um dispositivo em uso.
Antes de redimensionar uma partição, inicialize no modo de recuperação (ou desmonte quaisquer partições do dispositivo e desabilite o espaço virtual no dispositivo).
Start parted, where /dev/sda is the device on which to resize the partition:
parted /dev/sda
Visualize a tabela de partições corrente para determinar o número menor da partição a redimensionar, assim como os pontos inicial e final da partição:
print
To resize the partition, use the resize command followed by the minor number for the partition, the starting place in megabytes, and the end place in megabytes. For example:
resize 3 1024 2048

Atenção

A partition cannot be made larger than the space available on the device
After resizing the partition, use the print command to confirm that the partition has been resized correctly, is the correct partition type, and is the correct file system type.
After rebooting the system into normal mode, use the command df to make sure the partition was mounted and is recognized with the new size.

7.2. LVM Partition Management

The following commands can be found by issuing lvm help at a command prompt.
Tabela 7.2. LVM commands
Comando Descrição
dumpconfig Dump the active configuration
formats List the available metadata formats
help Display the help commands
lvchange Change the attributes of logical volume(s)
lvcreate Create a logical volume
lvdisplay Display information about a logical volume
lvextend Add space to a logical volume
lvmchange Due to use of the device mapper, this command has been deprecated
lvmdiskscan List devices that may be used as physical volumes
lvmsadc Collect activity data
lvmsar Create activity report
lvreduce Reduce the size of a logical volume
lvremove Remove logical volume(s) from the system
lvrename Rename a logical volume
lvresize Resize a logical volume
lvs Display information about logical volumes
lvscan List all logical volumes in all volume groups
pvchange Change attributes of physical volume(s)
pvcreate Initialize physical volume(s) for use by LVM
pvdata Display the on-disk metadata for physical volume(s)
pvdisplay Display various attributes of physical volume(s)
pvmove Move extents from one physical volume to another
pvremove Remove LVM label(s) from physical volume(s)
pvresize Resize a physical volume in use by a volume group
pvs Display information about physical volumes
pvscan List all physical volumes
segtypes List available segment types
vgcfgbackup Backup volume group configuration
vgcfgrestore Restore volume group configuration
vgchange Change volume group attributes
vgck Check the consistency of a volume group
vgconvert Change volume group metadata format
vgcreate Create a volume group
vgdisplay Display volume group information
vgexport Unregister a volume group from the system
vgextend Add physical volumes to a volume group
vgimport Register exported volume group with system
vgmerge Merge volume groups
vgmknodes Create the special files for volume group devices in /dev/
vgreduce Remove a physical volume from a volume group
vgremove Remove a volume group
vgrename Rename a volume group
vgs Display information about volume groups
vgscan Search for all volume groups
vgsplit Move physical volumes into a new volume group
version Display software and driver version information

Capítulo 8. Implementando Quotas de Disco

O espaço em disco pode ser restrito através da implementação de quotas de disco, para que o administrador do sistema seja alertado antes de um usuário consumir muito espaço ou uma partição ficar cheia.
Quotas de disco podem ser configuradas para usuários individuais e também para grupos de usuários. Isto possibilita o gerenciamento do espaço disponível para arquivos de usuários específicos (como relatórios e e-mails), separado do espaço disponível para os projetos nos quais o usuário está trabalhando (pressupondo que os projetos tenham seus próprios grupos).
Além disso, as quotas podem ser definidas não só para controlar o número de blocos de disco consumidos, mas também para controlar o número de inodes (estruturas de dados que contém informações sobre arquivos nos sistemas de arquivos UNIX). Como os inodes são usados para guardar informações relacionadas aos arquivos, isto permite controle sobre o número de arquivos que podem ser criados.
The quota RPM must be installed to implement disk quotas.

Nota

For more information on installing RPM packages, refer to Parte II, “Gerenciamento de Pacotes”.

8.1. Configurando Quotas de Disco

Para implementar quotas de disco, use os seguintes passos:
  1. Enable quotas per file system by modifying the /etc/fstab file.
  2. Remonte o(s) sistema(s) de arquivo
  3. Crie os arquivos de quota e gere a tabela de uso do disco
  4. Atribua políticas de quotas
Cada um destes passos é abordado em detalhes nas seções seguintes.

8.1.1. Habilitando Quotas

As root, using a text editor, edit the /etc/fstab file. Add the usrquota and/or grpquota options to the file systems that require quotas:
/dev/VolGroup00/LogVol00 /         ext3    defaults        1 1
LABEL=/boot              /boot     ext3    defaults        1 2
none                     /dev/pts  devpts  gid=5,mode=620  0 0
none                     /dev/shm  tmpfs   defaults        0 0
none                     /proc     proc    defaults        0 0
none                     /sys      sysfs   defaults        0 0
/dev/VolGroup00/LogVol02 /home     ext3    defaults,usrquota,grpquota  1 2
/dev/VolGroup00/LogVol01 swap      swap    defaults        0 0 . . .
In this example, the /home file system has both user and group quotas enabled.

Nota

The following examples assume that a separate /home partition was created during the installation of Red Hat Enterprise Linux. The root (/) partition can be used for setting quota policies in the /etc/fstab file.

8.1.2. Remontando os Sistemas de Arquivo

After adding the usrquota and/or grpquota options, remount each file system whose fstab entry has been modified. If the file system is not in use by any process, use one of the following methods:
  • Issue the umount command followed by the mount command to remount the file system.(See the man page for both umount and mount for the specific syntax for mounting and unmounting various filesystem types.)
  • Issue the mount -o remount <file-system> command (where <file-system> is the name of the file system) to remount the file system. For example, to remount the /home file system, the command to issue is mount -o remount /home.
Se o sistema de arquivo estiver sendo usado, o método mais fácil para remontar o sistema de arquivo é reiniciar o sistema.

8.1.3. Criando Arquivos de Banco de Dados de Quota

After each quota-enabled file system is remounted, the system is capable of working with disk quotas. However, the file system itself is not yet ready to support quotas. The next step is to run the quotacheck command.
The quotacheck command examines quota-enabled file systems and builds a table of the current disk usage per file system. The table is then used to update the operating system's copy of disk usage. In addition, the file system's disk quota files are updated.
To create the quota files (aquota.user and aquota.group) on the file system, use the -c option of the quotacheck command. For example, if user and group quotas are enabled for the /home file system, create the files in the /home directory:
quotacheck -cug /home
A opção -c especifica que os arquivos de quota devem ser criados para cada sistema de arquivo que tenha quotas habilitadas; a opção -u pede a verificação de quotas de usuário e a opção -g pede a verificação de quotas de grupo.
Se nenhuma das opções -u ou -g for especificada, somente o arquivo de quota do usuário é criado. Se especificar somente a opção -g, somente o arquivo de quota do grupo é criado.
Após criar os arquivos, execute o seguinte comando para gerar a tabela de uso corrente do disco por sistema de arquivo com quotas habilitadas:
quotacheck -avug
As opções usadas são as seguintes:
  • a — Verifica todos os sistemas de arquivo montados localmente com quotas habilitadas
  • v — Exibe informações verbais de status enquanto a verificação de quotas procede
  • u — Verifica informações de quotas de disco do usuário
  • g — Verifica informações de quotas de disco do grupo
After quotacheck has finished running, the quota files corresponding to the enabled quotas (user and/or group) are populated with data for each quota-enabled locally-mounted file system such as /home.

8.1.4. Atribuindo Quotas por Usuário

The last step is assigning the disk quotas with the edquota command.
Para configurar a quota de um usuário, execute o seguinte comando, como root:
edquota username
Perform this step for each user who needs a quota. For example, if a quota is enabled in /etc/fstab for the /home partition (/dev/VolGroup00/LogVol02 in the example below) and the command edquota testuser is executed, the following is shown in the editor configured as the default for the system:
Disk quotas for user testuser (uid 501):
Filesystem                blocks     soft     hard    inodes   soft   hard
/dev/VolGroup00/LogVol02  440436        0        0     37418      0      0

Nota

The text editor defined by the EDITOR environment variable is used by edquota. To change the editor, set the EDITOR environment variable in your ~/.bash_profile file to the full path of the editor of your choice.
The first column is the name of the file system that has a quota enabled for it. The second column shows how many blocks the user is currently using. The next two columns are used to set soft and hard block limits for the user on the file system. The inodes column shows how many inodes the user is currently using. The last two columns are used to set the soft and hard inode limits for the user on the file system.
Um limite rígido é a quantidade máxima absoluta de espaço em disco que um usuário ou grupo pode usar. Uma vez alcançado este limite, não é possível usar mais espaço em disco.
O limite suave determina a quantidade máxima de espaço em disco que pode ser usada. No entanto, ao contrário do limite rígido, o limite suave pode ser ultrapassado por um determinado período de tempo. Este período é conhecido como período de carência (grace period). O período de carência pode ser expressado em segundos, minutos, horas, dias, semanas ou meses.
Se algum dos valores é 0, este limite não está definido. Altere os limites desejados em um editor de texto. Por exemplo:
Disk quotas for user testuser (uid 501):
Filesystem                blocks     soft     hard   inodes   soft   hard
/dev/VolGroup00/LogVol02  440436   500000   550000    37418      0      0
Para checar se a quota foi definida para o usuário, use o comando:
quota testuser

8.1.5. Atribuindo Quotas por Grupo

Quotas can also be assigned on a per-group basis. For example, to set a group quota for the devel group (the group must exist prior to setting the group quota), use the command:
edquota -g devel
Este comando exibe a quota existente para o grupo no editor de texto:
Disk quotas for group devel (gid 505):
Filesystem                blocks    soft     hard    inodes    soft    hard
/dev/VolGroup00/LogVol02  440400       0        0     37418       0       0
Modifique os limites, e depois salve o arquivo.
Para verificar se a quota do grupo foi definida, use o comando:
quota -g devel

8.1.6. Configurando o Tempo de Carência para Limites Suaves.

Se os limites suaves forem configurados para uma quota específica (seja ela inode ou bloco, para usuários ou grupos) o tempo de carência, ou a quantidade de tempo que um limite suave pode ser excedido, deve ser configurado com o comando:
edquota -t
Enquanto outros comandos edquota operam em uma quota de usuário ou de grupo específico, a opção -t opera em todos os sistemas de arquivos com quotas habilitadas.

8.2. Administrando Quotas de Disco

Se as quotas forem implementadas, elas precisarão de manutenção — principalmente para monitorá-las e observar se serão excedidas e para garantir que as quotas sejam precisas.
Obviamente, se os usuários ultrapassarem suas quotas repetidamente ou alcançarem seus limites suaves constantemente, um administrador de sistemas tem poucas alternativas, dependendo do tipo de usuários e o quanto o espaço em disco impacta suas atividades. O administrador pode ajudar o usuário a determinar como usar menos espaço ou aumentar seu espaço em disco, se necessário.

8.2.1. Habilitando e Desabilitando

É possível desabilitar quotas sem definí-las para 0. Para desligar todas as quotas de usuário e de grupo, use o seguinte comando:
quotaoff -vaug
Se não especificar as opções -u ou -g, somente as quotas de usuário são desabilitadas. Se especificar só a opção -g, somente as quotas de grupo são desabilitadas. A mudança para -v apresenta informação de status de verbosidade durante a execução do comando.
To enable quotas again, use the quotaon command with the same options.
Por exemplo: para habilitar as quotas de usuário e de grupo para todos os sistemas de arquivo, use o seguinte comando:
quotaon -vaug
To enable quotas for a specific file system, such as /home, use the following command:
quotaon -vug /home
Se não especificar as opções -u ou -g, somente as quotas de usuário são habilitadas. Se especificar só a opção -g, somente as quotas de grupo são habilitadas.

8.2.2. Reportando em Quotas de Disco

Creating a disk usage report entails running the repquota utility. For example, the command repquota /home produces this output:
*** Report for user quotas on device /dev/mapper/VolGroup00-LogVol02
Block grace time: 7days; Inode grace time: 7days
                        Block limits                File limits
User            used    soft    hard  grace    used  soft  hard  grace
----------------------------------------------------------------------
root      --      36       0       0              4     0     0
kristin   --     540       0       0            125     0     0
testuser  --  440400  500000  550000          37418     0     0
Para visualizar o relatório de uso do disco com todos os sistemas de arquivo habilitados com quotas (opção -a), use o comando:
repquota -a
While the report is easy to read, a few points should be explained. The -- displayed after each user is a quick way to determine whether the block or inode limits have been exceeded. If either soft limit is exceeded, a + appears in place of the corresponding -; the first - represents the block limit, and the second represents the inode limit.
The grace columns are normally blank. If a soft limit has been exceeded, the column contains a time specification equal to the amount of time remaining on the grace period. If the grace period has expired, none appears in its place.

8.2.3. Mantendo as Quotas Exatas

Whenever a file system is not unmounted cleanly (due to a system crash, for example), it is necessary to run quotacheck. However, quotacheck can be run on a regular basis, even if the system has not crashed. Safe methods for periodically running quotacheck include:
Ensuring quotacheck runs on next reboot

Best method for most systems

This method works best for (busy) multiuser systems which are periodically rebooted.
As root, place a shell script into the /etc/cron.daily/ or /etc/cron.weekly/ directory—or schedule one using the crontab -e command—that contains the touch /forcequotacheck command. This creates an empty forcequotacheck file in the root directory, which the system init script looks for at boot time. If it is found, the init script runs quotacheck. Afterward, the init script removes the /forcequotacheck file; thus, scheduling this file to be created periodically with cron ensures that quotacheck is run during the next reboot.
Refer to Capítulo 37, Automated Tasks for more information about configuring cron.
Running quotacheck in single user mode
An alternative way to safely run quotacheck is to (re-)boot the system into single-user mode to prevent the possibility of data corruption in quota files and run:
~]# quotaoff -vaug /<file_system>
~]# quotacheck -vaug /<file_system>
~]# quotaon -vaug /<file_system>
Running quotacheck on a running system
If necessary, it is possible to run quotacheck on a machine during a time when no users are logged in, and thus have no open files on the file system being checked. Run the command quotacheck -vaug <file_system> ; this command will fail if quotacheck cannot remount the given <file_system> as read-only. Note that, following the check, the file system will be remounted read-write.

Do not run quotacheck on a live file system

Running quotacheck on a live file system mounted read-write is not recommended due to the possibility of quota file corruption.
Refer to Capítulo 37, Automated Tasks for more information about configuring cron.

8.3. Recursos Adicionais

Para mais informações sobre quotas de disco, consulte os seguintes recursos.

8.3.1. Documentação Instalada

  • The quotacheck, edquota, repquota, quota, quotaon, and quotaoff man pages

Capítulo 9. Access Control Lists

Arquivos e diretórios têm permissões para o proprietário do arquivo, para o grupo associado ao arquivo e para todos os outros usuários do sistema. Entretanto, estas definições de permissões têm limitações. Por exemplo: permissões diferentes não podem ser configuradas para usuários diferentes. Consequentemente, as Listas de Controle de Acesso (ACLs) foram introduzidas.
O kernel do Red Hat Enterprise Linux 5 oferece suporte ACL para o sistema de arquivo ext3 e sistemas de arquivo NFS exportados. As ACLs também são reconhecidas no sistema de arquivo ext3, que pode ser acessado via Samba.
Along with support in the kernel, the acl package is required to implement ACLs. It contains the utilities used to add, modify, remove, and retrieve ACL information.
The cp and mv commands copy or move any ACLs associated with files and directories.

9.1. Montando Sistemas de Arquivo

Antes de usar ACLs para um arquivo ou diretório, sua partição deve ser montada com o suporte da ACL. Se for um sistema de arquivo ext3 local, pode ser montada com o seguinte comando:
mount -t ext3 -o acl <device-name> <partition>
Por exemplo:
mount -t ext3 -o acl /dev/VolGroup00/LogVol02 /work
Alternatively, if the partition is listed in the /etc/fstab file, the entry for the partition can include the acl option:
LABEL=/work      /work       ext3    acl        1 2
Se um sistema de arquivo ext3 é acessado via Samba, e as ACLS foram habilitadas para tal, as ACLs são reconhecidas porque o Samba foi compilado com a opção --with-acl-support. Não são necessárias bandeiras especiais ao acessar ou montar uma partilha do Samba.

9.1.1. NFS

Por default, se o sistema de arquivo exportado por um servidor NFS suporta ACLs e o cliente NFS pode ler ACLs, estas são utilizadas pelo sistema cliente.
To disable ACLs on NFS shares when configuring the server, include the no_acl option in the /etc/exports file. To disable ACLs on an NFS share when mounting it on a client, mount it with the no_acl option via the command line or the /etc/fstab file.

9.2. Definindo ACLs de Acesso

Há dois tipos de ACLs: ACLs de acesso e ACLs default. Uma ACL de acesso é a lista de controle de acesso a um arquivo ou diretório específico. Uma ACL default pode ser associada somente a um diretório; se um arquivo do diretório não tem uma ACL de acesso, usa as regras da ACL default do diretório. ACLs default são opcionais.
As ACLs podem ser configuradas:
  1. Por usuário
  2. Por grupo
  3. Através da máscara de direitos efetivos (effective rights mask)
  4. Para usuários fora do grupo de usuários do arquivo
The setfacl utility sets ACLs for files and directories. Use the -m option to add or modify the ACL of a file or directory:
setfacl -m <rules> <files>
Rules (<rules>) must be specified in the following formats. Multiple rules can be specified in the same command if they are separated by commas.
u:<uid>:<perms>
Defina a ACL de acesso para um usuário. Você pode especificar o nome ou ID do usuário. O usuário pode ser qualquer usuário válido do sistema.
g:<gid>:<perms>
Defina a ACL de acesso para um grupo. Você pode especificar o nome ou ID do grupo. O grupo pode ser qualquer grupo válido do sistema.
m:<perms>
Defina a máscara de direitos efetivos. A máscara é a união de todas as permissões do grupo proprietário e todas as entradas de usuário e grupo.
o:<perms>
Defina a ACL de acesso para usuários fora do grupo do arquivo.
White space is ignored. Permissions (<perms>) must be a combination of the characters r, w, and x for read, write, and execute.
If a file or directory already has an ACL, and the setfacl command is used, the additional rules are added to the existing ACL or the existing rule is modified.
Por exemplo: para dar permissões de leitura (read) e gravação (write) para o usuário andrius:
setfacl -m u:andrius:rw /project/somefile
To remove all the permissions for a user, group, or others, use the -x option and do not specify any permissions:
setfacl -x <rules> <files>
Por exemplo: para remover todas as permissões do usuário com UID 500:
setfacl -x u:500 /project/somefile

9.3. Definindo ACLs Default

To set a default ACL, add d: before the rule and specify a directory instead of a file name.
For example, to set the default ACL for the /share/ directory to read and execute for users not in the user group (an access ACL for an individual file can override it):
setfacl -m d:o:rx /share

9.4. Recuperando ACLs

To determine the existing ACLs for a file or directory, use the getfacl command. In the example below, the getfacl is used to determine the existing ACLs for a file.
getfacl home/john/picture.png
O comando acima retorna o seguinte resultado:
# file: home/john/picture.png
# owner: john
# group: john
user::rw-
group::r--
other::r--
Se um diretório é especificado e tem uma ACL padrão, esta também é exibida, tal como:
[john@main /]$ getfacl home/sales/
# file: home/sales/
# owner: john
# group: john
user::rw-
user:barryg:r--
group::r--
mask::r--
other::r--
default:user::rwx
default:user:john:rwx
default:group::r-x
default:mask::rwx
default:other::r-x

9.5. Documentando Sistemas de Arquivo Com ACLs

Atenção

The tar and dump commands do not backup ACLs.
The star utility is similar to the tar utility in that it can be used to generate archives of files; however, some of its options are different. Refer to Tabela 9.1, “Command Line Options for star for a listing of more commonly used options. For all available options, refer to the star man page. The star package is required to use this utility.
Tabela 9.1. Command Line Options for star
Opção Descrição
-c Cria um arquivo de documentação.
-n Não extrai os arquivos; use juntamente a -x para exibir o que a extração dos arquivos faz.
-r Substitui arquivos na documentação. Os arquivos são gravados no fim do arquivo de documentação, substituindo todos os arquivos com a mesma localidade e nome.
-t Exibe o conteúdo do arquivo de documentação.
-u Atualiza o arquivo de documentação. Estes arquivos são gravados no fim da documentação, caso já não existam na documentação ou se os arquivos são mais novos que aqueles com o mesmo nome na documentação. Esta opção funciona somente se a documentação é um arquivo ou uma fita com blocos de tamanhos diferentes que pode ser acessada em qualquer ponto.
-x Extrai arquivos da documentação. Se usado com -U e um arquivo da documentação for mais antigo que o correspondente no sistema de arquivo, o arquivo não é extraído.
-help Exibe as opções mais importantes.
-xhelp Exibe as opções menos importantes.
-/ Não remova as barras iniciais dos nomes de arquivos ao extraí-los de uma documentação. Por default, elas são removidas quando os arquivos são extraídos.
-acl Ao criar ou extrair, documentar ou armazenar todas as ACLs associadas a arquivos e diretórios.

9.6. Compatibilidade com Sistemas mais Antigos

If an ACL has been set on any file on a given file system, that file system has the ext_attr attribute. This attribute can be seen using the following command:
tune2fs -l <filesystem-device>
A file system that has acquired the ext_attr attribute can be mounted with older kernels, but those kernels do not enforce any ACLs which have been set.
Versions of the e2fsck utility included in version 1.22 and higher of the e2fsprogs package (including the versions in Red Hat Enterprise Linux 2.1 and 4) can check a file system with the ext_attr attribute. Older versions refuse to check it.

9.7. Recursos Adicionais

Consulte os seguinte recursos para mais informações.

9.7.1. Documentação Instalada

  • acl man page — Description of ACLs
  • getfacl man page — Discusses how to get file access control lists
  • setfacl man page — Explains how to set file access control lists
  • star man page — Explains more about the star utility and its many options

9.7.2. Sites Úteis

Capítulo 10. LVM (Logical Volume Manager)

10.1. What is LVM?

LVM is a tool for logical volume management which includes allocating disks, striping, mirroring and resizing logical volumes.
With LVM, a hard drive or set of hard drives is allocated to one or more physical volumes. LVM physical volumes can be placed on other block devices which might span two or more disks.
The physical volumes are combined into logical volumes, with the exception of the /boot partition. The /boot partition cannot be on a logical volume group because the boot loader cannot read it. If the root (/) partition is on a logical volume, create a separate /boot partition which is not a part of a volume group.
Since a physical volume cannot span over multiple drives, to span over more than one drive, create one or more physical volumes per drive.
Logical Volumes
LVM Group
Figura 10.1. Logical Volumes

The volume groups can be divided into logical volumes, which are assigned mount points, such as /home and / and file system types, such as ext2 or ext3. When "partitions" reach their full capacity, free space from the volume group can be added to the logical volume to increase the size of the partition. When a new hard drive is added to the system, it can be added to the volume group, and partitions that are logical volumes can be increased in size.
Logical Volumes
Logical Volumes
Figura 10.2. Logical Volumes

On the other hand, if a system is partitioned with the ext3 file system, the hard drive is divided into partitions of defined sizes. If a partition becomes full, it is not easy to expand the size of the partition. Even if the partition is moved to another hard drive, the original hard drive space has to be reallocated as a different partition or not used.
To learn how to configure LVM during the installation process, refer to Seção 10.2, “Configuração do LVM”.

10.1.1. What is LVM2?

LVM version 2, or LVM2, is the default for Red Hat Enterprise Linux 5, which uses the device mapper driver contained in the 2.6 kernel. LVM2 can be upgraded from versions of Red Hat Enterprise Linux running the 2.4 kernel.

10.2. Configuração do LVM

LVM can be configured during the graphical installation process, the text-based installation process, or during a kickstart installation. You can use the system-config-lvm utility to create your own LVM configuration post-installation. The next two sections focus on using Disk Druid during installation to complete this task. The third section introduces the LVM utility (system-config-lvm) which allows you to manage your LVM volumes in X windows or graphically.
Read Seção 10.1, “What is LVM?” first to learn about LVM. An overview of the steps required to configure LVM include:
  • Creating physical volumes from the hard drives.
  • Creating volume groups from the physical volumes.
  • Creating logical volumes from the volume groups and assign the logical volumes mount points.
Two 9.1 GB SCSI drives (/dev/sda and /dev/sdb) are used in the following examples. They detail how to create a simple configuration using a single LVM volume group with associated logical volumes during installation.

10.3. Automatic Partitioning

On the Disk Partitioning Setup screen, select Remove linux partitions on selected drives and create default layout from the pulldown list.
For Red Hat Enterprise Linux, LVM is the default method for disk partitioning. If you do not wish to have LVM implemented, or if you require RAID partitioning, manual disk partitioning through Disk Druid is required.
The following properties make up the automatically created configuration:
  • The /boot partition resides on its own non-LVM partition. In the following example, it is the first partition on the first drive (/dev/sda1). Bootable partitions cannot reside on LVM logical volumes.
  • A single LVM volume group (VolGroup00) is created, which spans all selected drives and all remaining space available. In the following example, the remainder of the first drive (/dev/sda2), and the entire second drive (/dev/sdb1) are allocated to the volume group.
  • Two LVM logical volumes (LogVol00 and LogVol01) are created from the newly created spanned volume group. In the following example, the recommended swap space is automatically calculated and assigned to LogVol01, and the remainder is allocated to the root file system, LogVol00.
Automatic LVM Configuration With Two SCSI Drives
Automatic LVM Configuration With Two SCSI Drives
Figura 10.3. Automatic LVM Configuration With Two SCSI Drives

Nota

If enabling quotas are of interest to you, it may be best to modify the automatic configuration to include other mount points, such as /home or /var, so that each file system has its own independent quota configuration limits.
In most cases, the default automatic LVM partitioning is sufficient, but advanced implementations could warrant modification or manual configuration of the partition tables.

Nota

If you anticipate future memory upgrades, leaving some free space in the volume group would allow for easy future expansion of the swap space logical volume on the system; in which case, the automatic LVM configuration should be modified to leave available space for future growth.

10.4. Manual LVM Partitioning

The following section explains how to manually configure LVM for Red Hat Enterprise Linux. Because there are numerous ways to manually configure a system with LVM, the following example is similar to the default configuration done in Seção 10.3, “Automatic Partitioning”.
On the Disk Partitioning Setup screen, select Create custom layout from the pulldown list and click the Next button in the bottom right corner of the screen.

10.4.1. Creating the /boot Partition

In a typical situation, the disk drives are new, or formatted clean. The following figure, Figura 10.4, “Two Blank Drives, Ready for Configuration”, shows both drives as raw devices with no partitioning configured.
Two Blank Drives, Ready for Configuration
Two Blank Drives, Ready for Configuration
Figura 10.4. Two Blank Drives, Ready for Configuration

Atenção

The /boot partition cannot reside on an LVM volume because the GRUB boot loader cannot read it.
  1. Select New.
  2. Select /boot from the Mount Point pulldown menu.
  3. Select ext3 from the File System Type pulldown menu.
  4. Select only the sda checkbox from the Allowable Drives area.
  5. Leave 100 (the default) in the Size (MB) menu.
  6. Leave the Fixed size (the default) radio button selected in the Additional Size Options area.
  7. Select Force to be a primary partition to make the partition be a primary partition. A primary partition is one of the first four partitions on the hard drive. If unselected, the partition is created as a logical partition. If other operating systems are already on the system, unselecting this option should be considered. For more information on primary versus logical/extended partitions, refer to the appendix section of the Red Hat Enterprise Linux Installation Guide.
Refer to Figura 10.5, “Creation of the Boot Partition” to verify your inputted values:
Creation of the Boot Partition
Creation of the Boot Partition
Figura 10.5. Creation of the Boot Partition

Click OK to return to the main screen. The following figure displays the boot partition correctly set:
The /boot Partition Displayed
The /boot Partition Displayed
Figura 10.6. The /boot Partition Displayed

10.4.2. Creating the LVM Physical Volumes

Once the boot partition is created, the remainder of all disk space can be allocated to LVM partitions. The first step in creating a successful LVM implementation is the creation of the physical volume(s).
  1. Select New.
  2. Select physical volume (LVM) from the File System Type pulldown menu as shown in Figura 10.7, “Creating a Physical Volume”.
    Creating a Physical Volume
    Creating a Physical Volume
    Figura 10.7. Creating a Physical Volume

  3. You cannot enter a mount point yet (you can once you have created all your physical volumes and then all volume groups).
  4. A physical volume must be constrained to one drive. For Allowable Drives, select the drive on which the physical volume are created. If you have multiple drives, all drives are selected, and you must deselect all but one drive.
  5. Indique o tamanho desejado para o volume físico.
  6. Select Fixed size to make the physical volume the specified size, select Fill all space up to (MB) and enter a size in MBs to give range for the physical volume size, or select Fill to maximum allowable size to make it grow to fill all available space on the hard disk. If you make more than one growable, they share the available free space on the disk.
  7. Select Force to be a primary partition if you want the partition to be a primary partition.
  8. Click OK to return to the main screen.
Repeat these steps to create as many physical volumes as needed for your LVM setup. For example, if you want the volume group to span over more than one drive, create a physical volume on each of the drives. The following figure shows both drives completed after the repeated process:
Two Physical Volumes Created
Two Physical Volumes Created, Ready for Volume Groups
Figura 10.8. Two Physical Volumes Created

10.4.3. Creating the LVM Volume Groups

Once all the physical volumes are created, the volume groups can be created:
  1. Click the LVM button to collect the physical volumes into volume groups. A volume group is basically a collection of physical volumes. You can have multiple logical volumes, but a physical volume can only be in one volume group.

    Nota

    There is overhead disk space reserved in the volume group. The volume group size is slightly less than the total of physical volume sizes.
    Creating an LVM Volume Group
    Creating an LVM Volume Group
    Figura 10.9. Creating an LVM Volume Group

  2. Change the Volume Group Name if desired.
  3. All logical volumes inside the volume group must be allocated in physical extent (PE) units. A physical extent is an allocation unit for data.
  4. Selecione quais volumes físicos usar para o grupo de volume.

10.4.4. Creating the LVM Logical Volumes

Create logical volumes with mount points such as /, /home, and swap space. Remember that /boot cannot be a logical volume. To add a logical volume, click the Add button in the Logical Volumes section. A dialog window as shown in Figura 10.10, “Creating a Logical Volume” appears.
Creating a Logical Volume
Creating a Logical Volume
Figura 10.10. Creating a Logical Volume

Repita estes passos para cada grupo de volume que deseja criar.

Tip

You may want to leave some free space in the volume group so you can expand the logical volumes later. The default automatic configuration does not do this, but this manual configuration example does — approximately 1 GB is left as free space for future expansion.
Pending Logical Volumes
Pending Logical Volumes
Figura 10.11. Pending Logical Volumes

Click OK to apply the volume group and all associated logical volumes.
The following figure shows the final manual configuration:
Final Manual Configuration
Final Manual Configuration
Figura 10.12. Final Manual Configuration

10.5. Using the LVM utility system-config-lvm

The LVM utility allows you to manage logical volumes within X windows or graphically. You can access the application by selecting from your menu panel System > Administration > Logical Volume Management. Alternatively you can start the Logical Volume Management utility by typing system-config-lvm from a terminal.
In the example used in this section, the following are the details for the volume group that was created during the installation:
/boot - (Ext3) file system. Displayed under 'Uninitialized Entities'. (DO NOT initialize this partition).
LogVol00 - (LVM) contains the (/) directory (312 extents).
LogVol02 - (LVM) contains the (/home) directory (128 extents).
LogVol03 - (LVM) swap (28 extents).
The logical volumes above were created in disk entity /dev/hda2 while /boot was created in /dev/hda1. The system also consists of 'Uninitialized Entities' which are illustrated in Figura 10.17, “Uninitialized Entities”. The figure below illustrates the main window in the LVM utility. The logical and the physical views of the above configuration are illustrated below. The three logical volumes exist on the same physical volume (hda2).
Main LVM Window
Main LVM Window
Figura 10.13. Main LVM Window

The figure below illustrates the physical view for the volume. In this window, you can select and remove a volume from the volume group or migrate extents from the volume to another volume group. Steps to migrate extents are discussed in Figura 10.22, “Migrate Extents”.
Physical View Window
Physical View Window
Figura 10.14. Physical View Window

The figure below illustrates the logical view for the selected volume group. The logical volume size is also indicated with the individual logical volume sizes illustrated.
Logical View Window
Logical View Window
Figura 10.15. Logical View Window

On the left side column, you can select the individual logical volumes in the volume group to view more details about each. In this example the objective is to rename the logical volume name for 'LogVol03' to 'Swap'. To perform this operation select the respective logical volume and click on the Edit Properties button. This will display the Edit Logical Volume window from which you can modify the Logical volume name, size (in extents) and also use the remaining space available in a logical volume group. The figure below illustrates this.
Please note that this logical volume cannot be changed in size as there is currently no free space in the volume group. If there was remaining space, this option would be enabled (see Figura 10.31, “Edit logical volume”). Click on the OK button to save your changes (this will remount the volume). To cancel your changes click on the Cancel button. To revert to the last snapshot settings click on the Revert button. A snapshot can be created by clicking on the Create Snapshot button on the LVM utility window. If the selected logical volume is in use by the system (for example) the / (root) directory, this task will not be successful as the volume cannot be unmounted.
Edit Logical Volume
Edit Logical Volume
Figura 10.16. Edit Logical Volume

10.5.1. Utilizing uninitialized entities

'Uninitialized Entities' consist of unpartitioned space and non LVM file systems. In this example partitions 3, 4, 5, 6 and 7 were created during installation and some unpartitioned space was left on the hard disk. Please view each partition and ensure that you read the 'Properties for Disk Entity' on the right column of the window to ensure that you do not delete critical data. In this example partition 1 cannot be initialized as it is /boot. Uninitialized entities are illustrated below.
Uninitialized Entities
Uninitialized Entities
Figura 10.17. Uninitialized Entities

In this example, partition 3 will be initialized and added to an existing volume group. To initialize a partition or unpartioned space, select the partition and click on the Initialize Entity button. Once initialized, a volume will be listed in the 'Unallocated Volumes' list.

10.5.2. Adding Unallocated Volumes to a volume group

Once initialized, a volume will be listed in the 'Unallocated Volumes' list. The figure below illustrates an unallocated partition (Partition 3). The respective buttons at the bottom of the window allow you to:
  • create a new volume group,
  • add the unallocated volume to an existing volume group,
  • remove the volume from LVM.
To add the volume to an existing volume group, click on the Add to Existing Volume Group button.
Unallocated Volumes
Unallocated Volumes
Figura 10.18. Unallocated Volumes

Clicking on the Add to Existing Volume Group button will display a pop up window listing the existing volume groups to which you can add the physical volume you are about to initialize. A volume group may span across one or more hard disks. In this example only one volume group exists as illustrated below.
Add physical volume to volume group
Add physical volume to volume group
Figura 10.19. Add physical volume to volume group

Once added to an existing volume group the new logical volume is automatically added to the unused space of the selected volume group. You can use the unused space to:
  • create a new logical volume (click on the Create New Logical Volume(s) button,
  • select one of the existing logical volumes and increase the extents (see Seção 10.5.6, “Extending a volume group”),
  • select an existing logical volume and remove it from the volume group by clicking on the Remove Selected Logical Volume(s) button. Please note that you cannot select unused space to perform this operation.
The figure below illustrates the logical view of 'VolGroup00' after adding the new volume group.
Logical view of volume group
Logical view of volume group
Figura 10.20. Logical view of volume group

In the figure below, the uninitialized entities (partitions 3, 5, 6 and 7) were added to 'VolGroup00'.
Logical view of volume group
Logical view of volume group
Figura 10.21. Logical view of volume group

10.5.3. Migrating extents

To migrate extents from a physical volume, select the volume and click on the Migrate Selected Extent(s) From Volume button. Please note that you need to have a sufficient number of free extents to migrate extents within a volume group. An error message will be displayed if you do not have a sufficient number of free extents. To resolve this problem, please extend your volume group (see Seção 10.5.6, “Extending a volume group”). If a sufficient number of free extents is detected in the volume group, a pop up window will be displayed from which you can select the destination for the extents or automatically let LVM choose the physical volumes (PVs) to migrate them to. This is illustrated below.
Migrate Extents
Migrate Extents
Figura 10.22. Migrate Extents

The figure below illustrates a migration of extents in progress. In this example, the extents were migrated to 'Partition 3'.
Migrating extents in progress
Migrating extents in progress
Figura 10.23. Migrating extents in progress

Once the extents have been migrated, unused space is left on the physical volume. The figure below illustrates the physical and logical view for the volume group. Please note that the extents of LogVol00 which were initially in hda2 are now in hda3. Migrating extents allows you to move logical volumes in case of hard disk upgrades or to manage your disk space better.
Logical and physical view of volume group
Logical and physical view of volume group
Figura 10.24. Logical and physical view of volume group

10.5.4. Adding a new hard disk using LVM

In this example, a new IDE hard disk was added. The figure below illustrates the details for the new hard disk. From the figure below, the disk is uninitialized and not mounted. To initialize a partition, click on the Initialize Entity button. For more details, see Seção 10.5.1, “Utilizing uninitialized entities”. Once initialized, LVM will add the new volume to the list of unallocated volumes as illustrated in Figura 10.26, “Create new volume group”.
Uninitialized hard disk
Uninitialized hard disk
Figura 10.25. Uninitialized hard disk

10.5.5. Adding a new volume group

Once initialized, LVM will add the new volume to the list of unallocated volumes where you can add it to an existing volume group or create a new volume group. You can also remove the volume from LVM. The volume if removed from LVM will be listed in the list of 'Uninitialized Entities' as illustrated in Figura 10.25, “Uninitialized hard disk”. In this example, a new volume group was created as illustrated below.
Create new volume group
Create new volume group
Figura 10.26. Create new volume group

Once created a new volume group will be displayed in the list of existing volume groups as illustrated below. The logical view will display the new volume group with unused space as no logical volumes have been created. To create a logical volume, select the volume group and click on the Create New Logical Volume button as illustrated below. Please select the extents you wish to use on the volume group. In this example, all the extents in the volume group were used to create the new logical volume.
Create new logical volume
Create new logical volume
Figura 10.27. Create new logical volume

The figure below illustrates the physical view of the new volume group. The new logical volume named 'Backups' in this volume group is also listed.
Physical view of new volume group
Physical view of new volume group
Figura 10.28. Physical view of new volume group

10.5.6. Extending a volume group

In this example, the objective was to extend the new volume group to include an uninitialized entity (partition). This was to increase the size or number of extents for the volume group. To extend the volume group, click on the Extend Volume Group button. This will display the 'Extend Volume Group' window as illustrated below. On the 'Extend Volume Group' window, you can select disk entities (partitions) to add to the volume group. Please ensure that you check the contents of any 'Uninitialized Disk Entities' (partitions) to avoid deleting any critical data (see Figura 10.25, “Uninitialized hard disk”). In the example, the disk entity (partition) /dev/hda6 was selected as illustrated below.
Select disk entities
Select disk entities
Figura 10.29. Select disk entities

Once added, the new volume will be added as 'Unused Space' in the volume group. The figure below illustrates the logical and physical view of the volume group after it was extended.
Logical and physical view of an extended volume group
Logical and physical view of an extended volume group
Figura 10.30. Logical and physical view of an extended volume group

10.5.7. Editing a Logical Volume

The LVM utility allows you to select a logical volume in the volume group and modify its name, size and specify filesystem options. In this example, the logical volume named 'Backups" was extended onto the remaining space for the volume group.
Clicking on the Edit Properties button will display the 'Edit Logical Volume' popup window from which you can edit the properties of the logical volume. On this window, you can also mount the volume after making the changes and mount it when the system is rebooted. Please note that you should indicate the mount point. If the mount point you specify does not exist, a popup window will be displayed prompting you to create it. The 'Edit Logical Volume' window is illustrated below.
Edit logical volume
Edit logical volume
Figura 10.31. Edit logical volume

If you wish to mount the volume, select the 'Mount' checkbox indicating the preferred mount point. To mount the volume when the system is rebooted, select the 'Mount when rebooted' checkbox. In this example, the new volume will be mounted in /mnt/backups. This is illustrated in the figure below.
Edit logical volume - specifying mount options
Edit logical volume - specifying mount options
Figura 10.32. Edit logical volume - specifying mount options

The figure below illustrates the logical and physical view of the volume group after the logical volume was extended to the unused space. Please note in this example that the logical volume named 'Backups' spans across two hard disks. A volume can be striped across two or more physical devices using LVM.
Edit logical volume
Edit logical volume
Figura 10.33. Edit logical volume

10.6. Additional Resources

Use these sources to learn more about LVM.

10.6.1. Installed Documentation

  • rpm -qd lvm2 — This command shows all the documentation available from the lvm package, including man pages.
  • lvm help — This command shows all LVM commands available.

10.6.2. Useful Websites

Parte II. Gerenciamento de Pacotes

Todos os programas no sistema Red Hat Enterprise Linux estão divididos em pacotes RPM que podem ser instalados, atualizados ou removidos. Esta parte descreve como gerenciar os pacotes RPM em um sistema Red Hat Enterprise Linux, utilizando ferramentas de linhas de comando e gráficas.

Índice

11. Gerenciamento de Pacotes com RPM
11.1. Objetivos de Desenvolvimento do RPM
11.2. Usando o RPM
11.2.1. Encontrando Pacotes RPM
11.2.2. Instalando
11.2.3. Desinstalando
11.2.4. Atualizando (upgrade)
11.2.5. Recarregando
11.2.6. Busca
11.2.7. Verificando
11.3. Verificando a Assinatura de um Pacote
11.3.1. Importando Chaves
11.3.2. Verificando a Assinatura de Pacotes
11.4. Exemplos Comuns e Práticos do Uso de RPM
11.5. Recursos Adicionais
11.5.1. Documentação Instalada
11.5.2. Sites Úteis
11.5.3. Livros Relacionados
12. Package Management Tool
12.1. Listando e Analisando Pacotes
12.2. Instalando e Removendo Pacotes
13. YUM (Yellowdog Updater Modified)
13.1. Setting Up a Yum Repository
13.2. yum Commands
13.3. yum Options
13.4. Configuring yum
13.4.1. [main] Options
13.4.2. [repository] Options
13.5. Useful yum Variables
14. Product Subscriptions and Entitlements
14.1. An Overview of Managing Subscriptions and Content
14.1.1. The Purpose of Subscription Management
14.1.2. Defining Subscriptions, Entitlements, and Products
14.1.3. Subscription Management Tools
14.1.4. Subscription and Content Architecture
14.1.5. Advanced Content Management: Extended Update Support
14.1.6. RHN Classic v. Certificate-based Red Hat Network
14.2. Using Red Hat Subscription Manager Tools
14.2.1. Launching Red Hat Subscription Manager
14.2.2. About subscription-manager
14.2.3. Looking at RHN Subscription Management
14.2.4. Looking at Subscription Asset Manager
14.3. Managing Special Deployment Scenarios
14.3.1. Local Subscription Services, Local Content Providers, and Multi-Tenant Organizations
14.3.2. Virtual Guests and Hosts
14.3.3. Domains
14.4. Registering, Unregistering, and Reregistering a System
14.4.1. Registering Consumers in the Hosted Environment
14.4.2. Registering Consumers to a Local Organization
14.4.3. Registering an Offline Consumer
14.4.4. Registering from the Command Line
14.4.5. Unregistering
14.4.6. Restoring a Registration
14.5. Migrating Systems from RHN Classic to Certificate-based Red Hat Network
14.5.1. Installing the Migration Tools
14.5.2. Migrating from RHN Classic to Certificate-based Red Hat Network
14.5.3. Unregistering from RHN Classic Only
14.5.4. Migrating a Disconnected System
14.5.5. Looking at Channel and Certificate Mappings
14.6. Handling Subscriptions
14.6.1. Subscribing and Unsubscribing through the Red Hat Subscription Manager GUI
14.6.2. Handling Subscriptions through the Command Line
14.6.3. Stacking Subscriptions
14.6.4. Manually Adding a New Subscription
14.7. Redeeming Subscriptions on a Machine
14.7.1. Redeeming Subscriptions through the GUI
14.7.2. Redeeming Subscriptions on a Machine through the Command Line
14.8. Viewing Available and Used Subscriptions
14.8.1. Viewing Subscriptions in the GUI
14.8.2. Listing Subscriptions with the Command Line
14.8.3. Viewing Subscriptions Used in Both RHN Classic and Certificate-based Red Hat Network
14.9. Working with Subscription yum Repos
14.10. Responding to Subscription Notifications
14.11. Healing Subscriptions
14.11.1. Enabling Healing
14.11.2. Changing the Healing Check Frequency
14.12. Working with Subscription Asset Manager
14.12.1. Configuring Subscription Manager to Work with Subscription Asset Manager
14.12.2. Viewing Organization Information
14.13. Updating Entitlements Certificates
14.13.1. Updating Entitlement Certificates
14.13.2. Updating Subscription Information
14.14. Configuring the Subscription Service
14.14.1. Red Hat Subscription Manager Configuration Files
14.14.2. Using the config Command
14.14.3. Using an HTTP Proxy
14.14.4. Changing the Subscription Server
14.14.5. Configuring Red Hat Subscription Manager to Use a Local Content Provider
14.14.6. Managing Secure Connections to the Subscription Server
14.14.7. Starting and Stopping the Subscription Service
14.14.8. Checking Logs
14.14.9. Showing and Hiding Incompatible Subscriptions
14.14.10. Checking and Adding System Facts
14.14.11. Regenerating Identity Certificates
14.14.12. Getting the System UUID
14.14.13. Viewing Package Profiles
14.14.14. Retrieving the Consumer ID, Registration Tokens, and Other Information
14.15. About Certificates and Managing Entitlements
14.15.1. The Structure of Identity Certificates
14.15.2. The Structure of Entitlement Certificates
14.15.3. The Structure of Product Certificates
14.15.4. Anatomy of Satellite Certificates

Capítulo 11. Gerenciamento de Pacotes com RPM

O Gestor de Pacotes RPM (RPM) é um sistema de empacotamento aberto, disponível para uso de todos, que roda no Red Hat Enterprise Linux assim como em outros sistemas Linux e UNIX. A Red Hat, Inc. incentiva outros fabricantes a usarem o RPM em seus produtos. O RPM pode ser distribuído sob os termos da GPL.
The utility works only with packages built for processing by the rpm package. For the end user, RPM makes system updates easy. Installing, uninstalling, and upgrading RPM packages can be accomplished with short commands. RPM maintains a database of installed packages and their files, so you can invoke powerful queries and verifications on your system. If you prefer a graphical interface, you can use the Package Management Tool to perform many RPM commands. Refer to Capítulo 12, Package Management Tool for details.

Importante

Ao instalar um pacote, assegure-se que seja compatível com seu sistema operacional e arquitetura. Isto pode geralmente ser determinado, verificando o nome do pacote.
During upgrades, RPM handles configuration files carefully, so that you never lose your customizations — something that you cannot accomplish with regular .tar.gz files.
Para o desenvolvedor, o RPM permite levar o código fonte do sotfware e empacotá-lo em uma fonte e pacotes binários para usuários finais. Este processo é bem simples e é iniciado a partir de um arquivo simples e consertos opcionais que você cria. Esta diferenciação clara entre recursos originais e seus consertos, junto a instruções para criação (build), facilita a manutenção do pacote conforme o lançamento de novas versões do software.

Nota

Como o RPM efetua alterações no seu sistema, você deve estar como root para instalar, remover ou atualizar um pacote RPM.

11.1. Objetivos de Desenvolvimento do RPM

Para entender o uso do RPM, pode ser útil entender seus objetivos de desenvolvimento:
Capacidade de Atualização (Upgradability)
Usando o RPM, você pode atualizar componentes individuais de seu sistema sem precisar reinstalá-los completamente. Quando você obtém uma nova versão de um sistema operacional baseado em RPMs (como o Red Hat Enterprise Linux), não precisa reinstalá-lo em sua máquina (como é o caso de sistemas operacionais baseados em outros sistemas de empacotamento). O RPM permite atualizações inteligentes, totalmente automatizadas e certeiras de seu sistema. Os arquivos de configuração dos pacotes são preservados ao longo das atualizações, para que você não perca sua personalização. Não há arquivos especiais necessários para a atualização de um pacote porque o mesmo arquivo RPM é usado para instalar e atualizar o pacote no seu sistema.
Busca (querying) Poderosa
O RPM é desenvolvido para prover opções poderosas de busca. Você pode procurar determinados pacotes ou arquivos no seu banco de dados inteiro. Você também pode descobrir a qual pacote um arquivo pertence e de onde o pacote veio. Os arquivos que o pacote RPM contém estão em um arquivo comprimido, com um cabeçalho binário personalizado contendo informações úteis sobre o pacote e seu conteúdo, permitindo que você procure pacotes individuais fácil e rapidamente.
Verificação do Sistema
Uma outra funcionalidade importante é a verificação de pacotes. Se você não sabe se apagou algum arquivo importante de algum pacote, verifique-o. Você será notificado de quaisquer anomalias, caso exista alguma —, neste momento, você pode reinstalar o pacote se necessário. Todos os arquivos de configuração que você modificou são preservados durante a reinstalação.
Recursos Originais
Um dos objetivos cruciais do desenvolvimento é permitir o uso de recursos originais de software, quando distribuídos pelos autores originais do software. Com o RPM, você tem os recursos originais junto a todos os consertos que foram usados, mais as instruções de criação (build). Esta é uma vantagem importante por diversas razões. Por exemplo: se uma nova versão do programa é lançada, você não precisa necessariamente começar do zero para compilá-la. Você pode verificar no conserto o que deve fazer. Todos os defaults que fazem parte da compilação e todas as alterações efetuadas para que o software fosse criado apropriadamente são facilmente visíveis através desta técnica.
O objetivo de manter os recursos originais talvez seja importante apenas para desenvolvedores, mas resulta em software de melhor qualidade para usuários finais também.

11.2. Usando o RPM

RPM has five basic modes of operation (not counting package building): installing, uninstalling, upgrading, querying, and verifying. This section contains an overview of each mode. For complete details and options, try rpm --help or man rpm. You can also refer to Seção 11.5, “Recursos Adicionais” for more information on RPM.

11.2.1. Encontrando Pacotes RPM

Antes de usar um RPM, você deve saber onde encontrá-los. Uma busca na Internet retorna muitos repositórios de RPM, mas se você procura por pacotes RPM compilados pela Red Hat, estes podem ser encontrados nas seguintes localidades:

11.2.2. Instalando

RPM packages typically have file names like foo-1.0-1.i386.rpm. The file name includes the package name (foo), version (1.0), release (1), and architecture (i386). To install a package, log in as root and type the following command at a shell prompt:
rpm -ivh foo-1.0-1.i386.rpm
Alternatively, the following command can also be used:
rpm -Uvh foo-1.0-1.i386.rpm
Se a instalação for bem-sucedida, será exibido o seguinte resultado:
Preparing...                ########################################### [100%]
   1:foo                    ########################################### [100%]
Como você pode observar, O RPM traz o nome do pacote e então uma sucessão de hífens como medida do progresso, conforme o pacote é instalado.
Iniciando com a versão 4.1 do RPM, a assinatura de um pacote é verificada automaticamente ao instalar ou atualizar um pacote. Se a verificação da assinatura falhar, é apresentada uma mensagem de erro parecida com a seguinte:
error: V3 DSA signature: BAD, key ID 0352860f
Se a assinatura é nova, somente com cabeçalho, aparece uma mensagem de erro parecida com a seguinte:
error: Header V3 DSA signature: BAD, key ID 0352860f
If you do not have the appropriate key installed to verify the signature, the message contains the word NOKEY such as:
warning: V3 DSA signature: NOKEY, key ID 0352860f
Refer to Seção 11.3, “Verificando a Assinatura de um Pacote” for more information on checking a package's signature.

Aviso

If you are installing a kernel package, you should use rpm -ivh instead. Refer to Capítulo 42, Atualizando o Kernel Manualmente for details.

11.2.2.1. Pacote Já Instalado

Se o pacote da mesma versão já está instalado, o seguinte é apresentado:
Preparing...                ########################################### [100%]
package foo-1.0-1 is already installed
However, if you want to install the package anyway, you can use the --replacepkgs option, which tells RPM to ignore the error:
rpm -ivh --replacepkgs foo-1.0-1.i386.rpm
Esta opção é útil se os arquivos instalados pelo RPM foram apagados ou se você deseja instalar os arquivos originais de configuração pelo RPM.

11.2.2.2. Arquivos Conflitantes

Se você tentar instalar um pacote que contém um arquivo que foi instalado por outro pacote ou por uma versão mais antiga do mesmo pacote, aparece o seguinte:
Preparing...                ########################################### [100%]
file /usr/bin/foo from install of foo-1.0-1 conflicts with file from package bar-2.0.20
To make RPM ignore this error, use the --replacefiles option:
rpm -ivh --replacefiles foo-1.0-1.i386.rpm

11.2.2.3. Dependência Não-resolvida

Os pacotes ROM podem depender de outros pacotes, o que significa que eles requerem a instalação de outros pacotes para rodarem apropriadamente. Se você tentar instalar um pacote que tem uma dependência não-resolvida, aparece um output similar ao seguinte:
error: Failed dependencies:
        bar.so.2 is needed by foo-1.0-1
Suggested resolutions:
	bar-2.0.20-3.i386.rpm
Se você instalar um pacote pelos CDs do Red Hat Enterprise Linux, geralmente sugere-se que resolva a dependência do(s) pacote(s). Encontre este pacote nos CDs do Red Hat Enterprise Linux ou pelo site (ou espelho) FTP da Red Hat Network e adicione-o ao comando:
rpm -ivh foo-1.0-1.i386.rpm bar-2.0.20-3.i386.rpm
Se a instalação dos dois pacotes for bem-sucedida, aparece um output similar ao seguinte:
Preparing...                ########################################### [100%]
   1:foo                    ########################################### [ 50%]
   2:bar                    ########################################### [100%]
If it does not suggest a package to resolve the dependency, you can try the -q --whatprovides option combination to determine which package contains the required file.
rpm -q --whatprovides bar.so.2
Para forçar a instalação de qualquer maneira (o que pode não contribuir para o pacote rodar corretamente), use a opção --nodeps.

11.2.3. Desinstalando

Desinstalar um pacote é tão simples quanto instalar um. Digite o seguinte em uma janela de comandos:
rpm -e foo

Nota

Notice that we used the package name foo, not the name of the original package file foo-1.0-1.i386.rpm. To uninstall a package, replace foo with the actual package name of the original package.
Você pode encontrar um erro de dependência ao desinstalar um pacote, caso um outro pacote instalado dependa daquele que tenta remover. Por exemplo:
error: Failed dependencies:
	foo is needed by (installed) bar-2.0.20-3.i386.rpm
Para fazer com que o RPM ignore este erro e desinstale o pacote de qualquer maneira (o que pode quebrar o pacote dependendo deste), use a opção --nodeps.

11.2.4. Atualizando (upgrade)

Atualizar um pacote é similar a instalar um. Digite o seguinte em uma janela de comandos:
rpm -Uvh foo-2.0-1.i386.rpm
As part of upgrading a package, RPM automatically uninstalls any old versions of the foo package. Note that -U will also install a package even when there are no previous versions of the package installed.

Tip

Você não quer usar a opção -U para instalar pacotes do kernel porque o RPM substitui o pacote do kernel anterior. Isso não afeta um sistema rodando, mas se o novo kernel não for capaz de inicializar durante sua próxima reinicialização, não haverá outro kernel para inicializar.
Using the -i option adds the kernel to your GRUB boot menu (/etc/grub.conf). Similarly, removing an old, unneeded kernel removes the kernel from GRUB.
Como o RPM executa a atualização inteligente de pacotes com arquivos de configuração, você talvez veja uma mensagem como esta:
saving /etc/foo.conf as /etc/foo.conf.rpmsave
Esta mensagem significa que suas alterações ao arquivo de configuração talvez não sejam compatíveis com o novo arquivo de configuração no pacote, portanto o RPM salvou o arquivo original e instalou um novo. Você deve investigar as diferenças entre os dois arquivos de configuração e resolvê-las o quanto antes para garantir o bom funcionamento do seu sistema.
Se você tentar atualizar um pacote com um número de versão antigo (ou seja, se uma versão mais atualizada do pacote já estiver instalada), o resultado é semelhante ao seguinte:
package foo-2.0-1 (which is newer than foo-1.0-1) is already installed
To force RPM to upgrade anyway, use the --oldpackage option:
rpm -Uvh --oldpackage foo-1.0-1.i386.rpm

11.2.5. Recarregando

Recarregar um pacote é similar a atualizar um. Digite o seguinte em uma janela de comandos:
rpm -Fvh foo-1.2-1.i386.rpm
A opção de recarregamento (freshen) do RPM verifica as versões dos pacotes especificados na linha de comando com as versões dos pacotes que já foram instalados no seu sistema. Quando uma versão mais recente de um pacote já instalado é processada pela opção de recarregamento do RPM, é atualizada para a versão mais nova. Entretanto, a opção de recarregamento do RPM não instala um pacote se não houver um outro previamente instalado com o mesmo nome. Isto difere da opção de atualização do RPM, já que a atualização instala os pacotes, independente do fato de haver uma versão mais antiga do pacote ou não.
A opção de recarregamento do RPM para pacotes simples ou um grupo de pacotes. Se você fez o download de um grande número de pacotes diferentes e só deseja atualizar os pacotes que já estão instalados no sistema, o recarregamento é a melhor opção. Se usar o recarregamento, não é necessário apagar pacotes não quistos do grupo baixado (download) antes de usar o RPM.
Neste caso, invoque o seguinte comando:
rpm -Fvh *.rpm
O RPM atualiza automaticamente somente aqueles pacotes que já estão instalados.

11.2.6. Busca

O banco de dados do RPM armazena informação sobre todos os pacotes RPM instalados em seu sistema. É armazenado no diretório /var/lib/rpm/, e é usado para consultar quais pacotes estão instalados, quais são suas versões e quaisquer mudanças em arquivos no pacote desde a instalação, entre outros.
To query this database, use the -q option. The rpm -q package name command displays the package name, version, and release number of the installed package package name . For example, using rpm -q foo to query installed package foo might generate the following output:
foo-2.0-1
You can also use the following Package Selection Options with -q to further refine or qualify your query:
  • -a — queries all currently installed packages.
  • -f <filename> — queries the RPM database for which package owns f<filename> . When specifying a file, specify the absolute path of the file (for example, rpm -qf /bin/ls ).
  • -p <packagefile> — queries the uninstalled package <packagefile> .
There are a number of ways to specify what information to display about queried packages. The following options are used to select the type of information for which you are searching. These are called Package Query Options.
  • -i displays package information including name, description, release, size, build date, install date, vendor, and other miscellaneous information.
  • -l displays the list of files that the package contains.
  • -s displays the state of all the files in the package.
  • -d displays a list of files marked as documentation (man pages, info pages, READMEs, etc.).
  • -c displays a list of files marked as configuration files. These are the files you edit after installation to adapt and customize the package to your system (for example, sendmail.cf, passwd, inittab, etc.).
For options that display lists of files, add -v to the command to display the lists in a familiar ls -l format.

11.2.7. Verificando

Verificar um pacote compara as informações sobre os arquivos instalados de um pacote às mesmas informações do pacote original. Dentre outras coisas, a verificação compara o tamanho, soma MD5, permissões, tipo, proprietário (owner) e o grupo de cada arquivo.
The command rpm -V verifies a package. You can use any of the Verify Options listed for querying to specify the packages you wish to verify. A simple use of verifying is rpm -V foo, which verifies that all the files in the foo package are as they were when they were originally installed. For example:
  • Para verificar um pacote contendo um determinado arquivo:
    rpm -Vf /usr/bin/foo
    Neste exemplo, /usr/bin/foo é o caminho completo para o arquivo usado para consultar um pacote.
  • Para verificar TODOS os pacotes instalados:
    rpm -Va
  • Para verificar um pacote instalado sobre um arquivo do pacote RPM:
    rpm -Vp foo-1.0-1.i386.rpm
    Este comando pode ser útil se você suspeitar que seus bancos de dados RPM estejam corrompidos.
If everything verified properly, there is no output. If there are any discrepancies, they are displayed. The format of the output is a string of eight characters (a c denotes a configuration file) and then the file name. Each of the eight characters denotes the result of a comparison of one attribute of the file to the value of that attribute recorded in the RPM database. A single period (.) means the test passed. The following characters denote specific discrepancies:
  • 5 — MD5 checksum
  • S — file size
  • L — symbolic link
  • T — file modification time
  • D — device
  • U — user
  • G — group
  • M — mode (includes permissions and file type)
  • ? — unreadable file
Se você ver algum resultado, use seu bom senso para determinar se deve remover ou reinstalar o pacote, ou então consertar o problema de outra maneira.

11.3. Verificando a Assinatura de um Pacote

Se você deseja verificar se um pacote foi corrompido ou modificado, examine somente a soma md5 digitando o seguinte comando em uma janela de comandos (<rpm-file> pelo nome do arquivo do pacote RPM):
rpm -K --nosignature <rpm-file>
The message <rpm-file>: md5 OK is displayed. This brief message means that the file was not corrupted by the download. To see a more verbose message, replace -K with -Kvv in the command.
Por outro lado, o quão confiável é o desenvolvedor que criou o pacote? Se o pacote é assinado com a chave GnuPG do desenvolvedor, você sabe que o desenvolvedor é realmente quem ele clama ser.
Um pacote RPM pode ser assinado usando o Gnu Privacy Guard (ou GnuPG), para que você tenha certeza de fazer o download de um pacote confiável.
O GnuPG é uma ferramenta para comunicação segura; é um substituto completo e gratuito da tecnologia de criptografia do PGP, um programa de privacidade eletrônica. Com o GnuPG, você pode autenticar a validade de documentos e criptografar/descriptografar dados de e para outros destinos. O GnuPG também é capaz de descriptografar e verificar arquivos PGP 5.x.
Durante a instalação, o GnuPG é instalado por default. Desta maneira, você pode começar a usar o GnuPG imediatamente para verificar todos os pacotes que receber da Red Hat. Primeiro, você precisa importar a chave pública da Red Hat.

11.3.1. Importando Chaves

Para verificar os pacotes da Red Hat, você deve importar a chave GPG da Red Hat. Para fazê-lo, execute o seguinte em uma janela de comandos:
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
Para exibir uma lista de todas as chaves instaladas para a verificação do RPM, execute o comando:
rpm -qa gpg-pubkey*
Para a chave da Red Hat, o resultado inclui:
gpg-pubkey-37017186-45761324
To display details about a specific key, use rpm -qi followed by the output from the previous command:
rpm -qi gpg-pubkey-37017186-45761324

11.3.2. Verificando a Assinatura de Pacotes

Para verificar a assinatura GnuPG de um arquivo RPM após importar a chave GnuPG do criador, use o seguinte comando (substitua <rpm-file> pelo nome do arquivo do pacote RPM):
rpm -K <rpm-file>
If all goes well, the following message is displayed: md5 gpg OK. This means that the signature of the package has been verified, and that it is not corrupt.

11.4. Exemplos Comuns e Práticos do Uso de RPM

O RPM é útil para administrar seu sistema e para diagnosticar e consertar problemas. A melhor maneira de entender todas as suas opções é dar uma olhada em alguns exemplos.
  • Talvez você tenha apagado alguns arquivos por acidente, mas não sabe ao certo o que foi apagado. Para verificar seu sistema inteiro e saber o que pode estar faltando, você pode tentar o seguinte comando:
    rpm -Va
    Se alguns arquivos estão faltando ou parecem estar corrompidos, você provavelmente deve reinstalar, ou desinstalar o pacote e então reinstalá-lo.
  • Em algum ponto, você deve ver um arquivo que não reconhece. Para descobrir a qual pacote pertence, insira o seguinte:
    rpm -qf /usr/bin/ggv
    O output será parecido com o seguinte:
    ggv-2.6.0-2
  • We can combine the above two examples in the following scenario. Say you are having problems with /usr/bin/paste. You would like to verify the package that owns that program, but you do not know which package owns paste. Enter the following command,
    rpm -Vf /usr/bin/paste
    e o pacote apropriado é verificado.
  • Você deseja descobrir mais informações sobre um determinado programa? Você pode tentar o seguinte comando para localizar a documentação que acompanha o pacote que detém o programa:
    rpm -qdf /usr/bin/free
    O resultado é similar ao seguinte:
    /usr/share/doc/procps-3.2.3/BUGS
    /usr/share/doc/procps-3.2.3/FAQ
    /usr/share/doc/procps-3.2.3/NEWS
    /usr/share/doc/procps-3.2.3/TODO
    /usr/share/man/man1/free.1.gz
    /usr/share/man/man1/pgrep.1.gz
    /usr/share/man/man1/pkill.1.gz
    /usr/share/man/man1/pmap.1.gz
    /usr/share/man/man1/ps.1.gz
    /usr/share/man/man1/skill.1.gz
    /usr/share/man/man1/slabtop.1.gz
    /usr/share/man/man1/snice.1.gz
    /usr/share/man/man1/tload.1.gz
    /usr/share/man/man1/top.1.gz
    /usr/share/man/man1/uptime.1.gz
    /usr/share/man/man1/w.1.gz
    /usr/share/man/man1/watch.1.gz
    /usr/share/man/man5/sysctl.conf.5.gz
    /usr/share/man/man8/sysctl.8.gz
    /usr/share/man/man8/vmstat.8.gz
  • Você pode encontrar um RPM novo, mas não sabe o que este faz. Para encontrar informações a respeito, use o seguinte comando:
    rpm -qip crontabs-1.10-7.noarch.rpm
    O resultado é similar ao seguinte:
    Name        : crontabs                     Relocations: (not relocatable)
    Version     : 1.10                              Vendor: Red Hat, Inc.
    Release     : 7                             Build Date: Mon 20 Sep 2004 05:58:10 PM EDT
    Install Date: (not installed)               Build Host: tweety.build.redhat.com
    Group       : System Environment/Base       Source RPM: crontabs-1.10-7.src.rpm
    Size        : 1004                             License: Public Domain
    Signature   : DSA/SHA1, Wed 05 Jan 2005 06:05:25 PM EST, Key ID 219180cddb42a60e
    Packager    : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla>
    Summary     : Root crontab files used to schedule the execution of programs.
    Description : The crontabs package contains root crontab files. Crontab is the
    program used to install, uninstall, or list the tables used to drive the
    cron daemon. The cron daemon checks the crontab files to see when
    particular commands are scheduled to be executed. If commands are
    scheduled, then it executes them.
  • Perhaps you now want to see what files the crontabs RPM installs. You would enter the following:
    rpm -qlp crontabs-1.10-5.noarch.rpm
    O output é similar ao seguinte:
    /etc/cron.daily
    /etc/cron.hourly
    /etc/cron.monthly
    /etc/cron.weekly
    /etc/crontab
    /usr/bin/run-parts
Estes são apenas alguns exemplos. Conforme usá-lo, você descobrirá muitos outros usos para o RPM.

11.5. Recursos Adicionais

O RPM é um utilitário extremamente complexo com muitas opções e métodos de busca, instalação, atualização e remoção de pacotes. Consulte os seguintes recursos para aprender mais sobre o RPM.

11.5.1. Documentação Instalada

  • rpm --help — This command displays a quick reference of RPM parameters.
  • man rpm — The RPM man page gives more detail about RPM parameters than the rpm --help command.

11.5.2. Sites Úteis

Capítulo 12. Package Management Tool

If you prefer to use a graphical interface to view and manage packages in your system, you can use the Package Management Tool, better known as pirut. This tool allows you to perform basic package management of your system through an easy-to-use interface to remove installed packages or download (and install) packages compatible to your system. It also allows you to view what packages are installed in your system and which ones are available for download from Red Hat Network. In addition, the Package Management Tool also automatically resolves any critical dependencies when you install or remove packages in the same way that the rpm command does.

Nota

While the Package Management Tool can automatically resolve dependencies during package installation and removal, it cannot perform a forced install / remove the same way that rpm -e --nodeps or rpm -U --nodeps can.
The X Window System is required to run the Package Management Tool. To start the application, go to Applications (the main menu on the panel) > Add/Remove Software. Alternatively, you can type the commands system-config-packages or pirut at shell prompt.
Package Management Tool
Package Management Tool
Figura 12.1. Package Management Tool

12.1. Listando e Analisando Pacotes

You can use the Package Management Tool to search and list all packages installed in your system, as well as any packages available for you to download. The Browse, Search, and List tabs present different options in viewing, analyzing, installing or removing packages.
The Browse tab allows you to view packages by group. In Figura 12.1, “Package Management Tool”, the left window shows the different package group types you can choose from (for example, Desktop Environments, Applications, Development and more). When a package group type is selected, the right window displays the different package groups of that type.
Para visualizar quais pacotes estão inclusos no grupo de pacotes, clique em O pções de pacotes Os pacotes instalados são checados.
Optional Packages
Optional Packages
Figura 12.2. Optional Packages

The List tab displays a list of packages installed or available for download. Packages already installed in your system are marked with a green check ( ).
Por padrão, a opção Todos os pacotes, acima da janela principal é selecionada. Isto especifica que todos os pacotes são expostos. Use a opção Pacotes Inslalados para mostrar somente os pacotes que já estejam instalados em seu sistema e a opção Pacotes Dis poníveis para visualizar quais os pacotes que você pode baixar e instalar.
A tab Procurar permite que você utilize palavras chaves para procurar por um pacote específico. Esta tab também permite que você visualize uma descrição curta de um pacote. Para tal, simplesmente selecione um pacote e clique no botão Detalhesdo Pacote.abaixo da janela principal

12.2. Instalando e Removendo Pacotes

To install a package available for download, click the checkbox beside the package name. When you do so, an installation icon ( ) appears beside its checkbox. This indicates that the package is queued for download and installation. You can select multiple packages to download and install; once you have made your selection, click the Apply button.
Package installation
Package installation
Figura 12.3. Package installation

If there are any package dependencies for your selected downloads, the Package Management Tool will notify you accordingly. Click Details to view what additional packages are needed. To proceed with downloading and installing the package (along with all other dependent packages) click Continue.
Package dependencies: installation
Package dependencies: installation
Figura 12.4. Package dependencies: installation

Removing a package can be done in a similar manner. To remove a package installed in your system, click the checkbox beside the package name. The green check appearing beside the package name will be replaced by a package removal icon ( ). This indicates that the package is queued for removal; you can also select multiple packages to be removed at the same time. Once you have selected the packages you want to remove, click the Apply button.
Package removal
Package removal
Figura 12.5. Package removal

Note that if any other installed packages are dependent on the package you are removing, they will be removed as well. The Package Management Tool will notify you if there are any such dependencies. Click Details to view what packages are dependent on the one you are removing. To proceed with removing your selected package/s (along with all other dependent packages) click Continue.
Package dependencies: removal
Package dependencies: removal
Figura 12.6. Package dependencies: removal

You can install and remove multiple packages by selecting packages to be installed / removed and then clicking Apply. The Package selections window displays the number of packages to be installed and removed.
Installing and removing packages simultaneously
Installing and removing packages simultaneously
Figura 12.7. Installing and removing packages simultaneously

Capítulo 13. YUM (Yellowdog Updater Modified)

Yellowdog Update, Modified (YUM) is a package manager that was developed by Duke University to improve the installation of RPMs. yum searches numerous repositories for packages and their dependencies so they may be installed together in an effort to alleviate dependency issues. Red Hat Enterprise Linux 5.8 uses yum to fetch packages and install RPMs.
up2date is now deprecated in favor of yum (Yellowdog Updater Modified). The entire stack of tools which installs and updates software in Red Hat Enterprise Linux 5.8 is now based on yum. This includes everything, from the initial installation via Anaconda to host software management tools like pirut.
yum also allows system administrators to configure a local (i.e. available over a local network) repository to supplement packages provided by Red Hat. This is useful for user groups that use applications and packages that are not officially supported by Red Hat.
Aside from being able to supplement available packages for local users, using a local yum repository also saves bandwidth for the entire network. Further, clients that use local yum repositories do not need to be registered individually to install or update the latest packages from Red Hat Network.

13.1. Setting Up a Yum Repository

To set up a repository for Red Hat Enterprise Linux packages, follow these steps:
  1. Install the createrepo package:
    ~]# yum install createrepo
  2. Copy all the packages you want to provide in the repository into one directory (/mnt/local_repo for example).
  3. Run createrepo on that directory (for example, createrepo /mnt/local_repo). This will create the necessary metadata for your Yum repository.

13.2. yum Commands

yum commands are typically run as yum <command> <package name/s> . By default, yum will automatically attempt to check all configured repositories to resolve all package dependencies during an installation/upgrade.
The following is a list of the most commonly-used yum commands. For a complete list of available yum commands, refer to man yum.
yum install <package name/s>
Used to install the latest version of a package or group of packages. If no package matches the specified package name(s), they are assumed to be a shell glob, and any matches are then installed.
yum update <package name/s>
Used to update the specified packages to the latest available version. If no package name/s are specified, then yum will attempt to update all installed packages.
If the --obsoletes option is used (i.e. yum --obsoletes <package name/s> , yum will process obsolete packages. As such, packages that are obsoleted across updates will be removed and replaced accordingly.
yum check-update
This command allows you to determine whether any updates are available for your installed packages. yum returns a list of all package updates from all repositories if any are available.
yum remove <package name/s>
Used to remove specified packages, along with any other packages dependent on the packages being removed.
yum provides <file name>
Used to determine which packages provide a specific file or feature.
yum search <keyword>
This command is used to find any packages containing the specified keyword in the description, summary, packager and package name fields of RPMs in all repositories.
yum localinstall <absolute path to package name/s>
Used when using yum to install a package located locally in the machine.

13.3. yum Options

yum options are typically stated before specific yum commands; i.e. yum <options> <command> <package name/s> . Most of these options can be set as default using the configuration file.
The following is a list of the most commonly-used yum options. For a complete list of available yum options, refer to man yum.
-y
Answer "yes" to every question in the transaction.
-t
Sets yum to be "tolerant" of errors with regard to packages specified in the transaction. For example, if you run yum update package1 package2 and package2 is already installed, yum will continue to install package1.
--exclude=<package name>
Excludes a specific package by name or glob in a specific transaction.

13.4. Configuring yum

By default, yum is configured through /etc/yum.conf. The following is an example of a typical /etc/yum.conf file:
[main]
cachedir=/var/cache/yum
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
distroverpkg=redhat-release
tolerant=1
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
metadata_expire=1800
[myrepo]
name=RHEL 5 $releasever - $basearch
baseurl=http://local/path/to/yum/repository/
enabled=1
A typical /etc/yum.conf file is made up of two types of sections: a [main] section, and a repository section. There can only be one [main] section, but you can specify multiple repositories in a single /etc/yum.conf.

13.4.1. [main] Options

The [main] section is mandatory, and there must only be one. For a complete list of options you can use in the [main] section, refer to man yum.conf.
The following is a list of the most commonly-used options in the [main] section.
cachedir
This option specifies the directory where yum should store its cache and database files. By default, the cache directory of yum is /var/cache/yum.
keepcache=<1 or 0>
Setting keepcache=1 instructs yum to keep the cache of headers and packages after a successful installation. keepcache=1 is the default.
reposdir=<absolute path to directory of .repo files>
This option allows you to specify a directory where .repo files are located. .repo files contain repository information (similar to the [repository] section of /etc/yum.conf).
yum collects all repository information from .repo files and the [repository] section of the /etc/yum.conf file to create a master list of repositories to use for each transaction. Refer to Seção 13.4.2, “ [repository] Options” for more information about options you can use for both the [repository] section and .repo files.
If reposdir is not set, yum uses the default directory /etc/yum.repos.d.
gpgcheck=<1 or 0>
This disables/enables GPG signature checking on packages on all repositories, including local package installation. The default is gpgcheck=0, which disables GPG checking.
If this option is set in the [main] section of the /etc/yum.conf file, it sets the GPG checking rule for all repositories. However, you can also set this on individual repositories instead; i.e., you can enable GPG checking on one repository while disabling it on another.
assumeyes=<1 or 0>
This determines whether or not yum should prompt for confirmation of critical actions. The default if assumeyes=0, which means yum will prompt you for confirmation.
If assumeyes=1 is set, yum behaves in the same way that the command line option -y does.
tolerant=<1 or 0>
When enabled (tolerant=1), yum will be tolerant of errors on the command line with regard to packages. This is similar to the yum command line option -t.
The default value for this is tolerant=0 (not tolerant).
exclude=<package name/s>
This option allows you to exclude packages by keyword during installation/updates. If you are specifying multiple packages, this is a space-delimited list. Shell globs using wildcards (for example, * and ?) are allowed.
retries=<number of retries>
This sets the number of times yum should attempt to retrieve a file before returning an error. Setting this to 0 makes yum retry forever. The default value is 6.

13.4.2. [repository] Options

The [repository] section of the /etc/yum.conf file contains information about a repository yum can use to find packages during package installation, updating and dependency resolution. A repository entry takes the following form:
[repository ID]
name=repository name
baseurl=url, file or ftp://path to repository
You can also specify repository information in a separate .repo files (for example, rhel5.repo). The format of repository information placed in .repo files is identical with the [repository] of /etc/yum.conf.
.repo files are typically placed in /etc/yum.repos.d, unless you specify a different repository path in the [main] section of /etc/yum.conf with reposdir=. .repo files and the /etc/yum.conf file can contain multiple repository entries.
Each repository entry consists of the following mandatory parts:
[repository ID]
The repository ID is a unique, one-word string that serves as a repository identifier.
name=repository name
This is a human-readable string describing the repository.
baseurl=http, file or ftp://path
This is a URL to the directory where the repodatadirectory of a repository is located. If the repository is local to the machine, use baseurl=file://path to local repository . If the repository is located online using HTTP, use baseurl=http://link . If the repository is online and uses FTP, use baseurl=ftp://link .
If a specific online repository requires basic HTTP authentication, you can specify your username and password in the baseurl line by prepending it as username:password@link. For example, if a repository on http://www.example.com/repo/ requires a username of "user" and a password os "password", then the baseurl link can be specified as baseurl=http://user:password@www.example.com/repo/.
The following is a list of options most commonly used in repository entries. For a complete list of repository entries, refer to man yum.conf.
gpgcheck=<1 or 0>
This disables/enables GPG signature checking a specific repository. The default is gpgcheck=0, which disables GPG checking.
gpgkey=URL
This option allows you to point to a URL of the ASCII-armoured GPG key file for a repository. This option is normally used if yum needs a public key to verify a package and the required key was not imported into the RPM database.
If this option is set, yum will automatically import the key from the specified URL. You will be prompted before the key is installed unless you set assumeyes=1 (in the [main] section of /etc/yum.conf) or -y (in a yum transaction).
exclude=<package name/s>
This option is similar to the exclude option in the [main] section of /etc/yum.conf. However, it only applies to the repository in which it is specified.
includepkgs=<package name/s>
This option is the opposite of exclude. When this option is set on a repository, yum will only be able to see the specified packages in that repository. By default, all packages in a repository are visible to yum.

13.5. Useful yum Variables

The following is a list of variables you can use for both yum commands and yum configuration files (i.e. /etc/yum.conf and .repo files).
$releasever
This is replaced with the package's version, as listed in distroverpkg. This defaults to the version of the redhat-release package.
$arch
This is replaced with your system's architecture, as listed by os.uname() in Python.
$basearch
This is replaced with your base architecture. For example, if $arch=i686 then $basearch=i386.
$YUM0-9
This is replaced with the value of the shell environment variable of the same name. If the shell environment variable does not exist, then the configuration file variable will not be replaced.

Capítulo 14. Product Subscriptions and Entitlements

14.1. An Overview of Managing Subscriptions and Content
14.1.1. The Purpose of Subscription Management
14.1.2. Defining Subscriptions, Entitlements, and Products
14.1.3. Subscription Management Tools
14.1.4. Subscription and Content Architecture
14.1.5. Advanced Content Management: Extended Update Support
14.1.6. RHN Classic v. Certificate-based Red Hat Network
14.2. Using Red Hat Subscription Manager Tools
14.2.1. Launching Red Hat Subscription Manager
14.2.2. About subscription-manager
14.2.3. Looking at RHN Subscription Management
14.2.4. Looking at Subscription Asset Manager
14.3. Managing Special Deployment Scenarios
14.3.1. Local Subscription Services, Local Content Providers, and Multi-Tenant Organizations
14.3.2. Virtual Guests and Hosts
14.3.3. Domains
14.4. Registering, Unregistering, and Reregistering a System
14.4.1. Registering Consumers in the Hosted Environment
14.4.2. Registering Consumers to a Local Organization
14.4.3. Registering an Offline Consumer
14.4.4. Registering from the Command Line
14.4.5. Unregistering
14.4.6. Restoring a Registration
14.5. Migrating Systems from RHN Classic to Certificate-based Red Hat Network
14.5.1. Installing the Migration Tools
14.5.2. Migrating from RHN Classic to Certificate-based Red Hat Network
14.5.3. Unregistering from RHN Classic Only
14.5.4. Migrating a Disconnected System
14.5.5. Looking at Channel and Certificate Mappings
14.6. Handling Subscriptions
14.6.1. Subscribing and Unsubscribing through the Red Hat Subscription Manager GUI
14.6.2. Handling Subscriptions through the Command Line
14.6.3. Stacking Subscriptions
14.6.4. Manually Adding a New Subscription
14.7. Redeeming Subscriptions on a Machine
14.7.1. Redeeming Subscriptions through the GUI
14.7.2. Redeeming Subscriptions on a Machine through the Command Line
14.8. Viewing Available and Used Subscriptions
14.8.1. Viewing Subscriptions in the GUI
14.8.2. Listing Subscriptions with the Command Line
14.8.3. Viewing Subscriptions Used in Both RHN Classic and Certificate-based Red Hat Network
14.9. Working with Subscription yum Repos
14.10. Responding to Subscription Notifications
14.11. Healing Subscriptions
14.11.1. Enabling Healing
14.11.2. Changing the Healing Check Frequency
14.12. Working with Subscription Asset Manager
14.12.1. Configuring Subscription Manager to Work with Subscription Asset Manager
14.12.2. Viewing Organization Information
14.13. Updating Entitlements Certificates
14.13.1. Updating Entitlement Certificates
14.13.2. Updating Subscription Information
14.14. Configuring the Subscription Service
14.14.1. Red Hat Subscription Manager Configuration Files
14.14.2. Using the config Command
14.14.3. Using an HTTP Proxy
14.14.4. Changing the Subscription Server
14.14.5. Configuring Red Hat Subscription Manager to Use a Local Content Provider
14.14.6. Managing Secure Connections to the Subscription Server
14.14.7. Starting and Stopping the Subscription Service
14.14.8. Checking Logs
14.14.9. Showing and Hiding Incompatible Subscriptions
14.14.10. Checking and Adding System Facts
14.14.11. Regenerating Identity Certificates
14.14.12. Getting the System UUID
14.14.13. Viewing Package Profiles
14.14.14. Retrieving the Consumer ID, Registration Tokens, and Other Information
14.15. About Certificates and Managing Entitlements
14.15.1. The Structure of Identity Certificates
14.15.2. The Structure of Entitlement Certificates
14.15.3. The Structure of Product Certificates
14.15.4. Anatomy of Satellite Certificates
Effective asset management requires a mechanism to handle the software inventory — both the type of products and the number of systems that the software is installed on. The subscription service provides that mechanism and gives transparency into both global allocations of subscriptions for an entire organization and the specific subscriptions assigned to a single system.
Red Hat Subscription Manager works with yum to unit content delivery with subscription management. The Subscription Manager handles only the subscription-system associations. yum or other package management tools handle the actual content delivery. Capítulo 13, YUM (Yellowdog Updater Modified) describes how to use yum.
This chapter provides an overview of subscription management in Red Hat Enterprise Linux and the Red Hat Subscription Manager tools which are available.

14.1. An Overview of Managing Subscriptions and Content

Red Hat Enterprise Linux and other Red Hat products are sold through subscriptions, which make packages available and provide support for a set number of systems. Subscription management clarifies the relationships between local systems and available software resources because it gives a view into where software subscriptions are assigned, apart from installing the packages.

14.1.1. The Purpose of Subscription Management

New government and industry regulations are setting new mandates for businesses to track how their infrastructure assets are used. These changes include legislation like Sarbanes-Oxley in the United States, standards like Payment Card Industry Data Security Standard (PCI-DSS), or accreditation like SAS-70. Software inventory maintenance is increasingly important to meet accounting and governmental standards.
That means that there is increasing pressure on IT administrators to have an accurate, current accounting of the software used on their systems. Generally, this is called software license management; with Red Hat's subscription model, this is subscription management.
Managing Subscriptions for Software Inventory
Figura 14.1. Managing Subscriptions for Software Inventory

Effective subscription management helps organizations achieve four primary goals:
  • Maintain regulatory compliance. One of the key responsibilities of administrators is software compliance in conformance with legal or industry requirements. Subscription management helps track both subscription assignments and contract expirations, which helps administrators manage both systems and software inventories in accordance to their regulatory requirements.
  • Simplify IT audits. Having a central and clear inventory of both current subscriptions and current systems, IT administrators can monitor and report on their infrastructure better.
  • Get better performance by doing better at assigning subscriptions. The subscription service maintains dual inventories of available product subscriptions and registered server systems, with clear associations between subscriptions and systems. This makes it easier for IT administrators to assign relevant subscriptions to systems, because they have a view of what is in the inventory and what the system is currently subscribed to.
  • Lower costs and streamline procurement. While under-subscribing systems can run afoul of regulations, over- subscribing systems can cause a significant impact on IT budgets. Subscription management helps subscriptions be assigned most efficiently, so costs could actually be lowered.
With Red Hat's commitment to free and open software, subscription management is focused on delivering tools that help IT administrators monitor their software/systems inventory for their own benefit. Subscription management does not enforce or restrict access to products.

Important

Most Red Hat products are licensed under a GNU General Public License (GPL), which allows free use of the software or code; this a different license than the Red Hat license agreement. A Red Hat license provides access to Red Hat services, like the Customer Portal and Content Delivery Network.
The Red Hat subscription requires that, as long as there is any active subscription for a product, then every system which uses the Red Hat product must have an active subscription assigned to it. Otherwise, the subscription is violated. See http://www.redhat.com/subscriptions/ and http://www.redhat.com/rhel/renew/faqs/#6 for more information on Red Hat's subscription model and terms.

14.1.2. Defining Subscriptions, Entitlements, and Products

The basis of everything is a subscription. A subscription contains both the products that are available, the support levels, and the quantities, or number of servers, that the product can be installed on.
Subscriptions are managed though the Certificate-Based Red Hat Network service, which ties into the Subscription and Content Delivery Network (CDN).
The subscription service maintains a complete list of subscriptions for an organization, identified by a unique ID (called a pool ID). A system is registered, or added, to the subscription service to allow it to manage the subscriptions for that system. Like the subscription, the system is also added to the subscription service inventory and is assigned a unique ID within the service. The subscriptions and system entries, together, comprise the inventory.
A system allocates one of the quantities of a product in a subscription to itself. When a subscription is consumed, it is an entitlement. (An entitlement is roughly analogous to a user license, in that it grants all of the rights to that product to that system. Unlike a user license, an entitlement does not grant the right to use the software; with the subscription model, an entitlement grants the ability to download the packages and receive updates.) Because the available quantity in a subscription lowers once a system subscribes to it, the system consumes the subscription.
Managing Subscriptions, Illustrated
Figura 14.2. Managing Subscriptions, Illustrated

The repository where the product software is located is organized according to the product. Each product group within the repository may contain the primary software packages and then any required dependencies or associated packages. Altogether, the product and its associated packages are called a content set. (A content set for a product even includes other versions of the product.) When a subscription grants access to a product, it includes access to all of the associated packages in that content set.
A single subscription can have multiple products, and each system can have multiple different subscriptions, depending on how many entitlement certificates are loaded on the machine.
Any number of products, for any number of different architectures, can be contained in a single subscription. The subscription options that are visible to a consumer are filtered, by default, according to whether the architecture for the product matches the architecture of the system. This is compatibility. Depending on compatible subscriptions makes sure that subscriptions are allocated efficiently, only to systems which can actually use the products.
The subscription tools can display even incompatible entitlements. Alternatively, the architecture definition for the system can be overridden by defining custom system facts for the subscription tools to use.
It's important to distinguish between subscribing to a product and installing a product. A subscription is essentially a statement of whatever products an organization has purchased. The act of subscribing to a subscription means that a system is allowed to install the product with a valid certificate, but subscribing doesn't actually perform any installation or updates. In the reverse, a product can also be installed apart from any entitlements for the system; the system is just does not have a valid product certificate. Certificate-Based Red Hat Network and the Content Delivery Network harmonize with content delivery and installation by using yum plug-ins that come with the Subscription Manager tools.

14.1.3. Subscription Management Tools

Subscriptions are managed through GUI and CLI tools called Red Hat Subscription Manager. The Subscription Manager tracks and displays what entitlements are available to the local system and what entitlements have been consumed by the local system. The Subscription Manager works as a conduit back to the subscription service to synchronize changes like available product quantities or subscription expiration and renewals.

Note

The Red Hat Subscription Manager tools are always run as root because of the nature of the changes to the system. However, Red Hat Subscription Manager connects to the subscription service as a user account for the Customer Service Portal.
The Subscription Manager handles both registration and subscriptions for a system. The Subscription Manager is part of the firstboot process for configuring content and updates, but the system can be registered at any time through the Red Hat Subscription Manager GUI or CLI. New subscriptions, new products, and updates can be viewed and applied to a system through the Red Hat Subscription Manager tools.
The different Subscription Manager clients are covered in Seção 14.2, “Using Red Hat Subscription Manager Tools”.

14.1.4. Subscription and Content Architecture

Content includes new downloads, ISOs, updates, and errata, anything that can be installed on a system.
Subscription management helps to clarify and to define the relationships between local server infrastructure and the content delivery systems. Subscription management and content delivery are tightly associated. Entitlements (assigned subscriptions) identify what a system is allowed to install and update. In other words, entitlements define access to content. The content delivery system actually provides the software packages.
There are three parties that are involved in subscriptions and content:
  • The subscription service
  • The Content Delivery Network
  • The system which uses the content
Relationship Among Systems, the Subscription Service, and Content Delivery Network
Figura 14.3. Relationship Among Systems, the Subscription Service, and Content Delivery Network

The subscription service handles the system registration (verifying that the system is allowed to access the content). It also supplies the system with information on what products are available and handles a central list of entitlements and remaining quantities for the entire organization.
The content delivery network is responsible for delivering the content to the system when requested. The content server is configured in the Red Hat Subscription Manager configuration and then tied into the system's yum service through the Red Hat Subscription Manager yum plug-in.
Both the subscription service and the content server used by a system's Red Hat Subscription Manager tools can be customized. The default settings use the public subscription service and Content Delivery Network, but either one can be changed to use organization-specific services.

Note

Systems have the option of using the older Red Hat Network and Satellite 5.x systems to deliver content. These content delivery mechanisms bypass the subscription service in Certificate-Based Red Hat Network, so there is no entitlement management. This is allowed for legacy infrastructures, but Red Hat strongly recommends registering new systems with the latest Certificate-based Red Hat Network.

14.1.5. Advanced Content Management: Extended Update Support

Sometimes software product installations are straightforward — you want to install a Red Hat Enterprise Linux server, so you install Red Hat Enterprise Linux. However, products can have dependencies with each other (product B is only worthwhile if product A is also installed) or products can interact with each other to provide extended functionality. There are two categories of these kinds of product interactions:
  • Dependencies, where one product requires or relies on another product directly
  • Modifiers, where a product provides enhanced functionality or services for existing products
Dependencies are common and can be handled directly when processing content through tools like yum.
Modifiers can be more subtle. A modifier subscription extends another entitlement and provides different repository access and support than the product entitlement alone.
If the system is subscribed to that product entitlement or combination of products, then the modifier subscription brings an enhanced content set for that product. The content set can include additional new products, new functionality, or extended service and support, depending on the product being modified.
One simple example of a modifier is extended update support (EUS), which extends support for a minor release of Red Hat Enterprise Linux from six months to 24 months. An EUS subscription provides an enhanced support path, rather than a new product. EUS works only in conjunction with another product, to extend its support profile; it does not stand alone.

Red Hat Enterprise Linux Add-ons and EUS Subscriptions

Red Hat Enterprise Linux add-ons have access to EUS streams as long as the underlying Red Hat Enterprise Linux product has an EUS subscription. For example, if an administrator has a Red Hat Enterprise Linux 2 Socket subscription, a File System subscription, and a Red Hat Enterprise Linux 2 Socket EUS subscription, then the system can access both non-EUS and EUS content for both the Red Hat Enterprise Linux server and the File System product.

14.1.6. RHN Classic v. Certificate-based Red Hat Network

During the firstboot process, there are two options given for the content server: (Certificate-based) Red Hat Network and RHN Classic. These systems are mutually exclusive, but they both handle software content and updates as well as subscriptions and system inventory.
In 5.7 and later versions, entitlements and subscriptions are defined by available and installed products. However, in older versions of Red Hat Enterprise Linux, subscriptions were defined by channel access. These are two different approaches to content and entitlement access. Red Hat Network uses the product-based subscription model, while RHN Classic uses the channel-based model.
Certificate-based Red Hat Network is focused on two things:
  • Subscription management
  • Content delivery
Certificate-based Red Hat Network integrates the Customer Portal, Content Delivery Network, and subscription service (subscription management). It uses simple and streamlined local tools (the Red Hat Subscription Manager client) to give greater visibility into how entitlements and subscriptions are used and assigned and to help control software subscriptions as they are added and expire.
Since the client tools for subscription management (the focus of Certificate-based Red Hat Network) are only available in Red Hat Enterprise Linux 5.7 systems and later, Certificate-based Red Hat Network can only be utilized by 5.7 and later systems.
RHN Classic uses the traditional channel entitlement model, which provides a global view of content access but does not provide insight into system-level subscription uses. Along with content and global subscription management, RHN Classic also provides some systems management functions:
  • Kickstarting systems
  • Managing configuration files
  • Running scripts
  • Taking system snapshots
Satellite 5.x systems use a channel-based model similar to RHN Classic.
While RHN Classic has an expanded systems management feature set, RHN Classic does not provide the system-level view into installed and subscribed products that the enhanced Red Hat Network and subscription service do. RHN Classic is provided for older Red Hat Enterprise Linux systems (Red Hat Enterprise Linux 4.x, Red Hat Enterprise Linux 5.x, and Satellite 5.x) to migrate systems over to Red Hat Enterprise Linux 5.7 and later versions.
The two subscription services are mututally exclusive, with separate inventories and using separate client tools. Both the RHN Classic and Red Hat Subscription Manager tools correctly identify which service a system is registered with. When a system is registered with RHN Classic, then the Red Hat Subscription Manager shows an error that the system is already registered and cannot be managed by the Subscription Manager tools. Likewise, similar errors are returned in the RHN Classic tools if a system is registered with Red Hat Network and the subscription service.
For information on migrating from RHN Classic to Certificate-based Red Hat Network, see Seção 14.5, “Migrating Systems from RHN Classic to Certificate-based Red Hat Network”.

14.2. Using Red Hat Subscription Manager Tools

The Red Hat Subscription Manager tool set encompasses three different tools:
  • A GUI-based local client to manage the local machine
  • A CLI client for advanced users and administrators to manage a local machine (and which can be tied into other applications and actions, like kickstarting machines)
  • A web-based client for organizational, multi-system views of the subscriptions and inventoried resources
All of these tools, both local clients and the web-based tools, allow administrators to perform three major tasks directly related to managing subscriptions: registering machines, assigning subscriptions to systems, and updating the certificates required for authentication. Some minor operations, like updating system facts, are available to help display and track what subscriptions are available.

Note

Both the Red Hat Subscription Manager GUI and CLI must be run as root.

14.2.1. Launching Red Hat Subscription Manager

Red Hat Subscription Manager is listed as one of the administrative tools in the System => Administration menu in the top management bar.
Red Hat Subscription Manager Menu Option
Figura 14.4. Red Hat Subscription Manager Menu Option

Alternatively, the Red Hat Subscription Manager GUI can be opened from the command line with a single command:
[root@server1 ~]# subscription-manager-gui
The Red Hat Subscription Manager UI has a single window with tabbed sections that offer quick views into the current state of the system, showing installed products, subscriptions for the system, and available subscriptions the system has access to. These tabs also allow administrators to manage subscriptions by subscribing and unsubscribing the system.
The Red Hat Subscription Manager has three main areas to manage products and subscriptions:
  • The My Subscriptions area shows all of the current entitlements that the system is subscribed to.
  • The All Available Subscriptions area shows all of the subscriptions that are available to the system. The default displays only entitlements that are compatible with the hardware, but these can be filtered to show entitlements corresponding to other installed programs, only subscriptions that have not been installed, and subscriptions based on date.
  • The My Installed Software area shows the currently installed products on the system, along with their subscription status. This does not allow administrators to install software, only to view installed software.
Red Hat Subscription Manager Main Screen
Figura 14.5. Red Hat Subscription Manager Main Screen

The top right box contains the tools required to perform maintenance tasks like changing the registration connection information and viewing system facts.

14.2.2. About subscription-manager

Any of the operations that can be performed through the Red Hat Subscription Manager UI can also be performed by running the subscription-manager tool. This tools has the following format:
[root@server1 ~]# subscription-manager command [options]
Each command has its own set of options that are used with it. The subscription-manager help and manpage have more information.
Tabela 14.1. subscription-manager Commands
Command Description
register Registers or identifies a new system to the subscription service.
unregister Unregisters a machine, which strips its subscriptions and removes the machine from the subscription service.
subscribe Allocates a specific subscription to the machine.
redeem Autosubscribes a machine to a pre-specified subscription that was purchased from a vendor, based on its hardware and BIOS information.
refresh Pulls the latest entitlement data from the server. Normally, the system polls the entitlement server at a set interval (4 hours by default) to check for any changes in the available subscriptions. The refresh command checks with the entitlement server right then, outside the normal interval.
unsubscribe Removes a specific subscription or all subscriptions from the machine.
list Lists all of the subscriptions that are compatible with a machine, either subscriptions that are actually consumed by the machine or unused subscriptions that are available to the machine.
identity Handles the identity certificate and registration ID for a system. This command can be used to return the current UUID or generate a new identity certificate.
facts Lists the system information, like the release version, number of CPUs, and other architecture information.
clean Removes all of the subscription and identity data from the local system, without affecting the consumer information in the subscription service. Any of the subscriptions consumed by the system are still consumed and are not available for other systems to use. The clean command is useful in cases where the local entitlement information is corrupted or lost somehow, and the system will be reregistered using the register --consumerid=EXISTING_ID command.
orgs, repos, environments Lists all of the configured organizations, environments, and content repositories that are available to the given user account or system. These commands are used to view information in a multi-org infrastructure. They are not used to configure the local machine or multi-org infrastructure.

14.2.3. Looking at RHN Subscription Management

The ultimate goal of entitlement management is to allow administrators to identify the relationship between their systems and the subscriptions used by those systems. This can be done from two different perspectives: from the perspective of the local system looking externally to potential subscriptions and from the perspective of the organization, looking down at the total infrastructure of systems and all subscriptions.
The Red Hat Subscription Manager GUI and CLI are both local clients which manage only the local machine. These tools are somewhat limited in their view; they only disclose information (such as available entitlements) from the perspective of that one system, so expired and depleted subscriptions or subscriptions for other architectures aren't displayed.
RHN Subscription Management in the Customer Portal is a global tool which is intended to give complete, organization-wide views into subscriptions and systems. It shows all subscriptions and all consumers for the entire organization. RHN Subscription Management can perform many of the tasks of the local tools, like registering consumers, assigning subscriptions, and viewing system facts and UUID. It can also manage the subscriptions themselves, such as viewing contract information and renewing subscriptions — a task not possible in the local clients.
RHN Subscription Management in the Customer Portal
Figura 14.6. RHN Subscription Management in the Customer Portal

Note

RHN Subscription Management gives a global view of all consumers, of all types, for an organization, which is crucial for planning and effectively assigning subscriptions. However, it does not provide any insight into what products are installed on a system and whether subscriptions are assigned for those products. To track the validity of installed products, you must use the local Subscription Manager tools.
RHN Subscription Management also provides a view of systems and subscriptions managed under RHN Classic and provides access to the RHN Classic web tools.
All of the subscriptions for an entire organization — the subscriptions that have been purchased and the systems to which they have been allocated — are viewable through the account pages at https://access.redhat.com/. Additional information about RHN Subscription Management is available with the portal documentation at https://access.redhat.com/knowledge/docs/Red_Hat_Customer_Portal/.

14.2.4. Looking at Subscription Asset Manager

Subscription Asset Manager provides a local site not only to view subscriptions and systems for an infrastructure (as with the Customer Portal) but also to manage all of those systems. Subscription Asset Manager has three major functional areas:
  • Works with the client machine's Subscription Manager to manage subscriptions and content. In that way, it is a centralized, global, web-based Subscription Manager.
  • Helps manage the subscriptions themselves. It receives a subscription manifest from Red Hat Network. The manifest allocates that Subscription Asset Manager service a subset of all of an organization's subscriptions. From there, the Subscription Asset Manager locally assigns subscriptions to individual systems and can create activation keys.
  • Works as a real-time proxy between the local system assets and the Red Hat content delivery network.
Subscription Asset Manager handles both client-side, local system management and backend subscription management. This allows Subscription Asset Manager to provide more in-depth information on the status of products and certificates through tools like its dashboard and activity reports.
Subscription Asset Manager Dashboard
Figura 14.7. Subscription Asset Manager Dashboard

Because of the insight Subscription Asset Manager has into the local server assets, it can be used to define multi-tenant organizations. Multi-tentant organizations allow completely separate silos of assets (organizations). Organizations can then be subdivided into environments; since a system can belong to multiple environments, it is possible to organize systems into overlapping circles according to the real-world infrastructure. This is covered more in Seção 14.3.1, “Local Subscription Services, Local Content Providers, and Multi-Tenant Organizations”.
Subscription Asset Manager is available with Red Hat Enterprise Linux, but it must be installed and configured before it can be used to manage assets.
For more information on configuring and using Subscription Asset Manager, see the documentation at http://docs.redhat.com/docs/en-US/Red_Hat_Subscription_Asset_Manager/1.0/html/Installation_Guide/index.html.

14.3. Managing Special Deployment Scenarios

There are different types of consumers and different ways of organizing consumers. The simplest environment has physical machines grouped together in one single, homogeneous group, connecting to Red Hat's hosted content and subscription services. While this is an easy arrangement to maintain, it does not accurately describe many enterprise environments, which have a lively mix of physical and virtual machines, divided across disparate organizational units and even subunits within those organizations and accessing locally-controlled content and subscription services.
The first change is the ability to group systems into divisions and subdivisions. This is called multi-tenancy, the ability create unrelated groups beneath the primary umbrella account. Multi-tenant (or multi-org) structures are for infrastructures which may have multiple content repositories or subscription services, and systems within the organization need to be grouped according to access to those repositories and services.
The other part of heterogeneous environments is recognizing consumers other than physical machines. Two special consumer types are common: virtual guests and server domains. The difference between these consumer types and physical, single-machine consumers is only in the type of information that the Red Hat Subscription Service uses and stores — not in any special configuration or management tasks.

14.3.1. Local Subscription Services, Local Content Providers, and Multi-Tenant Organizations

As Seção 14.1.4, “Subscription and Content Architecture” outlines, the subscription service, content repository, and client tools and inventory all work together to define the entitlements structure for a customer. The way that these elements are organized depends on a lot of factors, like who is maintaining the individual services, how systems in the inventory are group, and how user access to the different services is controlled.
The most simplistic structure is the hosted structure. The content and subscription services are hosted by Red Hat, and all systems within the inventory are contained in one monolithic group. User access is defined only by Red Hat Customer Portal account access.
Hosted Structure
Figura 14.8. Hosted Structure

The next step allows a customer to have its own, local subscription service (Subscription Asset Manager), while still using Red Hat's hosted content delivery network. At this point, user access can be defined locally, within the Subscription Asset Manager configuration. Subscription Asset Manager can define independent groups, called organizations. Systems belong to those organizations, and users are granted access to those organizations. Systems and users in one organization are essentially invisible to systems and users in other organizations.
Hosted Content/Local Subscriptions Structure
Figura 14.9. Hosted Content/Local Subscriptions Structure

The last style of infrastructure is almost entirely local, with a Subscription Asset Manager that provides locally-hosted content providers and an integrated local subscription service.
Local Subscriptions and Local Content Provider Structure
Figura 14.10. Local Subscriptions and Local Content Provider Structure

This allows the most control over how systems are grouped within the subscriptions/content. A customer's main account can be divided into separate and independent organizations. These organizations can use different content provider, can have different subscriptions allocated to them, and can have different users assigned to them with levels of access set per organization. Access control in this scenario is controlled entirely locally. The local Subscription Asset Manager, not the remote Red Hat Customer Portal, processes user authentication requests and applies local access control policies.
A system is assigned to one organization. Within an organization, there can be different environments which define access to product versions and content sets. There can be overlap between environments, with a system belonging to multiple environments.
Multi-Org
Figura 14.11. Multi-Org

When there is only one organization — such as a hosted environment (where the single organization is implicit) — then the systems all default to use that one organization. When there are multiple organizations, then the organization for a system to use must be defined for that system. This affects register operations, where the system is registered to subscription service and then joined to the organization. It also affects other operations tangentially. It may affect subscribe operations because it affects repository availability and subscription allocations, and it affects redeem operations (activation of existing subscriptions) because subscriptions must be redeemed from the organization which issued the subscription.
For more information on configuring and managing organizations, environments, and content repositories, see the Subscription Asset Manager documentation.

14.3.2. Virtual Guests and Hosts

When the Red Hat Subscription Manager process checks the system facts, it attempts to identify whether the system is a physical machine or a virtual guest. The Subscription Manager can detect guests for several different virtualization services, including:
  • KVM
  • Xen
  • HyperV
  • VMWare ESX
Subscription Manager records a unique identifier called a guest ID as one of the system facts for a virtual guest. A special process, libvirt-rhsm, checks VMWare, KVM, and Xen processes and then relays that information to Subscription Manager and any configured subscription service (Certificate-based Red Hat Network or a local Subscription Asset Manager). Each guest machine on a host is assigned a guest ID, and that guest ID is both associated with the host and used to generate the identity certificate for the guest when it is registered.
Some Red Hat Enterprise Linux variants are specifically planned for virtual hosts and guests. The corresponding subscriptions are divided into a certain quantity of physical hosts and then a quantity of allowed guests. Red Hat Enterprise Linux add-ons may even be inherited, so that when a host machine is subscribed to that entitlement, all of its guests are automatically included in that subscription. (Red Hat layered products usually do not draw any distinction between virtual and physical systems; the same type of subscription is used for both.) If the system is a guest, then virtual entitlements are listed with the available subscriptions. If no more virtual entitlements are available, then the subscription service will apply physical entitlements.
Virtual and physical subscriptions are identified in the Type column.
Virtual and Physical Subscription
Figura 14.12. Virtual and Physical Subscription

Nota

The distinction of being a physical machine versus virtual machine matters only in the priority of how entitlements are consumed. Virtual machines are recorded in the subscription service inventory as a regular system type of consumer.
Virtual guests are registered to the subscription service inventory as regular systems and subscribe to entitlements just like any other consumer.
Virtual entitlements can only be used by virtual machines. Physical entitlements can be used by both physical and virtual machines. When ascertaining what subscriptions are available for autosubscription, preference is given first to virtual entitlements (which are more restrictive in the type of consumer which can use them), and then to physical entitlements.

14.3.3. Domains

Consumers in the subscription service inventory are identified by type. Most consumers will have a type of system, meaning that each individual server subscribes to its own entitlements for its own use. There is another type of consumer, though, which is available for server groups, the domain type. domain-based entitlements are not allocated to a single system; they are distributed across the group of servers to govern the behavior of that group of servers. (That server group is called a domain.)
There are two things to keep in mind about domain entitlements:
  • Each member of the domain is still registered to the subscription service as a system consumer and added to the inventory individually.
  • The domain entitlements apply to the behavior of the entire server group, not to any one system.
The domain entitlement simply governs the behavior of the domain. A domain entitlement is not limited to a specific type of behavior. Domain entitlements can describe a variety of types of behavior, such as storage quotas or the maximum number of messages to process per day. The entire domain is bound to the subscriptions when one of the domain servers subscribes to the domain entitlements using the Red Hat Subscription Manager tools, and the entitlement certificate is replicated between the domain servers.

14.4. Registering, Unregistering, and Reregistering a System

Entitlements are managed by organizing and maintaining the systems which use entitlement subscriptions. The entitlements and subscriptions are managed by Red Hat through the subscription service. A system is recognized to the subscription service by being registered with the service. The subscription service assigns the system (called a consumer) a unique ID (essentially as an inventory number) and issues that system an identifying certificate (with the UUID in its subject CN) to identify that system.
Whenever a subscription is purchased by an organization, the consumer can subscribe to that subscription. This means that a portion of the subscription is allocated to that consumer ID; when the consumer contacts the content delivery network and downloads the software, the licenses have been already assigned to the system. The system has valid certificates for its subscriptions.
Systems can be registered with an subscription service during the firstboot process or as part of the kickstart setup (both described in the Installation Guide). Systems can also be registered after they've been configured or removed from the subscription service inventory (unregistered) if they will no longer be managed within that entitlement system.

14.4.1. Registering Consumers in the Hosted Environment

For infrastructures which use Red Hat's hosted subscription and content delivery network, all that is required to register the system is the username and password of the Red Hat Network account.
  1. Launch the Red Hat Subscription Manager GUI. For example:
    subscription-manager-gui
  2. If the system is not already registered, then there will be a Register button at the top of the window in the Tools area.
  3. Enter the username and password of the user account on the subscription service; this is the account used to access the Customer Portal.
  4. Optionally, select the Automatically subscribe... checkbox, so that the system is subscribed to the best matched subscription when it is registered. Otherwise, the system must be subscribed manually, as in Seção 14.6, “Handling Subscriptions”.

14.4.2. Registering Consumers to a Local Organization

Infrastructures which manage their own local content repository and subscription service must have a defined organization. This organization is essentially a group definition, and systems must be assigned to that group as part of the registration process. This allows there to be multiple, discrete organizations or tenants within the infrastructure.
When a system is registered using the Subscription Manager GUI, Subscription Manager automatically scans the local subscription and content service to see what organizations are configured.
  1. Make sure that the rhsm.conf configuration file points to the local subscription service (in the hostname parameter) and the local content server (in the baseurl parameter). The Subscription Manager configuration is described in Seção 14.14, “Configuring the Subscription Service”.
  2. Launch the Red Hat Subscription Manager GUI. For example:
    subscription-manager-gui
  3. Click the Register button at the top of the window in the Tools area.
  4. Enter the username and password of the user account on the subscription service; this is the account used to access the Customer Portal.
  5. Subscription Manager scans the network for available organizations.
    When the configured organizations are detected, Subscription Manager prompts for the organization for the system to join. It is only possible to register with one organization.
  6. If the selected organization has multiple environments available, then the Subscription Manager will detect them and provide a list. It is possible to join multiple environments. Use the Ctrl key to select multiple environments from the list.
    If no environment is selected, then Subscription Manager uses the default environment for the organization.

    NOTE

    It is only possible to join an environment during registration. The environments cannot be changed after registration.
  7. Optionally, select the Automatically subscribe... checkbox, so that the system is subscribed to the best matched subscription when it is registered. Otherwise, the system must be subscribed manually, as in Seção 14.6, “Handling Subscriptions”.

14.4.3. Registering an Offline Consumer

Some systems may not have internet connectivity, but administrators still want to assign and track the subscriptions for that system. This can be done by manually registering the system, rather than depending on Subscription Manager to perform the registration. This has two major steps, first to create an entry on the subscriptions service and then to configure the system.
  1. Open the Subscriptions tab in the Customer Portal, and select the Overview item under the Certificate-Based Management area.
  2. In the summary of consumers, click the Register New System link to create the new inventory entry.
  3. Fill in the required information for the new consumer type. A system requires information about the architecture and hardware in order to ascertain what subscriptions are available to that system.
  4. Once the system is created, assign the appropriate subscriptions to that system.
    1. Open the Available Subscriptions tab.
    2. Click the check boxes by all of the subscriptions to assign, and then click the Add button.
  5. Once the subscriptions are added, open the Applied Subscriptions tab.
  6. Click the Download All Certificates button. This exports all of the entitlements certificates, for each product, to a single .zip file. Save the file to some kind of portable media, like a flash drive.
  7. Optionally, click the Download Identity Certificate button. This saves the identity certificate for the registered consumer and could be used by the consumer to connect to the subscription service. If the consumer will permanently be offline, then this is not necessary, but if the consumer could ever be brought onto the network, then this is useful.
  8. Copy the entitlements certificates from the media device over to the consumer.
  9. If all entitlement certificates were downloaded in an archive file, then there are multiple archives in the downloaded certificates.zip file. Unzip the directories until the PEM files for the entitlement certificates are available.
  10. Import the entitlement certificates. This can be done using the Import Certificates button in the Subscription Manager GUI or using the import command. For example:
    # subscription-manager import --certificate=/tmp/export/entitlement_certificates/596576341785244687.pem --certificate=/tmp/export/entitlement_certificates/3195996649750311162.pem
    Successfully imported certificate 596576341785244687.pem
    Successfully imported certificate 3195996649750311162.pem
  11. If you downloaded an identity certificate, copy the cert.pem file directly into the /etc/pki/consumer directory. For example:
    cp /tmp/downloads/cert.pem /etc/pki/consumer

14.4.4. Registering from the Command Line

The simplest way to register a machine is to pass the register command with the user account information required to authenticate to the Certificate-Based Red Hat Network (the credentials used to access subscription service or the Customer Portal). When the system is successfully authenticated, it echoes back the newly-assigned consumer ID and the user account name which registered it.
The register options are listed in Tabela 14.2, “register Options”.
Exemplo 14.1. Registering a New Consumer
[root@server1 ~]# subscription-manager register --username admin-example --password secret

7d133d55-876f-4f47-83eb-0ee931cb0a97 admin-example (the new consumer UUID and the account used for registration)

In a multi-org environment, it is required that you specify which organization (essentially an independent group or unit within the main account) to join the system to. This is done by using the --org option in addition to the username and password. The given user must also have the access permissions to add systems to that organization. (See Seção 14.12, “Working with Subscription Asset Manager” for information about organizations and Subscription Asset Manager.)
Exemplo 14.2. Registering a New Consumer with an Organization
If there is more than one organization, then the system must be assigned to one specific organization:
[root@server1 ~]# subscription-manager register --username admin-example --password secret --org="IT Department"

7d133d55-876f-4f47-83eb-0ee931cb0a97 admin-example (the new consumer UUID and the account used for registration)
Organizations can be subdivided into environments, which define access to content based on repositories, product versions, and content sets. While a consumer can only belong to a single organization, it can be assigned to multiple environments within that organization. If no environment is given, the subscription service uses the default environment. See Seção 14.12, “Working with Subscription Asset Manager” for information about organizations and Subscription Asset Manager.
A system can only be added to an environment during registration.
[root@server1 ~]# subscription-manager register --username admin-example --password secret --org="IT Department" --environment=Dev1,ITall

Nota

If the system is in a multi-org environment and no organization is given, the register command returns a Remote Server error.
The register command has an option, --autosubscribe, which allows the system to be registered to the subscription service and immediately subscribed to the subscription which best matches its architecture in a single step.
Exemplo 14.3. Automatically Subscribing While Registering
[root@server1 ~]# subscription-manager register --username admin-example --password secret --autosubscribe

Exemplo 14.4. Applying Subscriptions During Registration
When using the command-line tools to register the system, there is an option that can pass the activation key to apply existing, already-assigned certificates along with the other registration information. The activation keys are set, in a comma-separated list, in the --activationkey option.
With an activation key, it is not necessary to give a username and password because the authentication is implicit in the activation key.
In hosted or single organization environments, it is not necessary to specify an organization with the --org option, but in multi-org environments, the --org option is required. The organization is not defined as part of the activation key. See Seção 14.12, “Working with Subscription Asset Manager” for information about activation keys and Subscription Asset Manager.
For example:
# subscription-manager register --activationkey=1234abcd --org="IT Dept"

Tabela 14.2. register Options
Options Description Required
--username=name Gives the content server user account name. Required
--password=password Gives the password for the user account. Required
--org=name Gives the organization to which to join the system. Required, except for hosted environments
--environment=name Registers the consumer to an environment within an organization. Optional
--name=machine_name Sets the name of the consumer (machine) to register. This defaults to be the same as the hostname. Optional
--autosubscribe Automatically subscribes this system to the best-matched compatible subscription. This is good for automated setup operations, since the system can be configured in a single step. Optional
--activation_key Applies existing subscriptions as part of the registration process. The subscriptions are pre-assigned by a vendor or by a systems administrator using Subscription Asset Manager. Optional
--force Registers the system even if it is already registered. Normally, any register operations will fail if the machine is already registered. Optional

14.4.5. Unregistering

The only thing required to unregister a machine is to run the unregister command. This removes the system's entry from the subscription service, unsubscribes it from any subscriptions, and, locally, deletes its identity and entitlement certificates.
In the Red Hat Subscription Manager GUI, there is an Unregister button at the top of the window in the Tools area.
From the command line, this requires only the unregister.
Exemplo 14.5. Unregistering a Consumer
[root@server1 ~]# subscription-manager unregister

14.4.6. Restoring a Registration

There are times when the local registration and subscription information could be lost or corrupted. There could be a hardware failure or system crash. Or other IT considerations may require that a system be moved to a different machine. Whatever the reason, the local subscription configuration is lost.
A system can be registered against an existing system entry in the Red Hat subscription service, which essentially restores or reregisters that consumer. The reregister operation uses the original consumer ID with the registration request, so that all of the previous subscriptions associated with the consumer entry are restored along with the registration.
Reregistering a system uses the register command. This command passes the original UUID for a system to issue a request to the subscription service to receive a new certificate using the same UUID. This essentially renews its previous registration.
Exemplo 14.6. Registering a System Against an Existing Identity Certificate
The register command uses the original ID to identify itself to the subscription service and restore its previous subscriptions.
[root@server1 ~]# subscription-manager register --username admin-example --password secret --consumerid=7d133d55-876f-4f47-83eb-0ee931cb0a97

Tabela 14.3. register Options to Reregister the System
Options Description Required
--consumerid Gives the consumer UUID used by an existing consumer. The system's consumer entry must exist in the Red Hat subscription service for the reregister operation to succeed. Required
--username=name Gives the content server user account name. Optional
--password=password Gives the password for the user account. Optional

14.5. Migrating Systems from RHN Classic to Certificate-based Red Hat Network

As described in Seção 14.1.6, “RHN Classic v. Certificate-based Red Hat Network” and https://access.redhat.com/kb/docs/DOC-45987, there are differences in how RHN Classic and Certificate-based Red Hat Network define and manage subscriptions.
As part of migration, the RHN Classic channels are mapped to Certificate-based Red Hat Network X.509 product certificates for every installed product. Subscription Manager can use those certificates to subscribe or autosubscribe the system to the appropriate subscriptions once it is registered.
Migration tools are available to transition system registration from RHN Classic to Certificate-based Red Hat Network and then re-apply its previous subscriptions. Product certificates in general are described in Seção 14.15.3, “The Structure of Product Certificates”.
There are two migration paths supported:
  • From being registered with RHN Classic Hosted to being registered with Certificate-based Red Hat Network, using rhn-migrate-classic-to-rhsm
  • From a disconnected (offline) system using RHN Classic-style channels to using Certificate-based Red Hat Network X.509 certificates for installed products, using install-num-migrate-to-rhsm

Important

There is no migration path from a Satellite system to Certificate-based Red Hat Network.

14.5.1. Installing the Migration Tools

The migration tools are contained in the subscription-manager-migration package. An additional package, subscription-manager-migration-data, is required to map the RHN Classic channels to Certificate-based Red Hat Network product certificates.
  1. The migration tools and data are in supplementary channels. If necessary, enable the supplementary repositories, as described in Seção 14.9, “Working with Subscription yum Repos”.
  2. Install the migration tool packages.
    [root@server ~]# yum install subscription-manager-migration subscription-manager-migration-data

14.5.2. Migrating from RHN Classic to Certificate-based Red Hat Network

A system which was registered against the hosted subscription service, RHN Classic, can be migrated to Certificate-based Red Hat Network using the rhn-migrate-classic-to-rhsm script.
The general action is that it unregisters the system from RHN Classic, registers it with Certificate-based Red Hat Network, and opens Subscription Manager (either GUI or CLI) to assign subscriptions.
The rhn-migrate-classic-to-rhsm script has this syntax:
rhn-migrate-classic-to-rhsm [--force|--cli-only|--help|--no-auto]
After running migration, the system facts list what script was used for migration and what the previous system ID was.
[root@server ~]# subscription-manager facts --list | grep migr
migration.classic_system_id: 09876
migration.migrated_from: rhn_hosted_classic
This makes it easy to track the migration process for systems within the infrastructure.
Exemplo 14.7. Basic RHN Classic to Certificate-based Red Hat Network Migration
Simply running the rhn-migrate-classic-to-rhsm tool migrates the system profile and then opens the Subscription Manager GUI so that administrators can assign subscriptions to the system.
While administrators only have to run the command, the script itself runs through a series of steps to migrate the account.
[root@server ~]# rhn-migrate-classic-to-rhsm
RHN Username: jsmith@example.com
Password:
The script prompts for the username and password to use to connect to Red Hat Network. It uses these credentials to authenticate to both Red Hat Network Classic and Certificatebased Red Hat Network, to verify the account settings.
Once the account is verified, the script creates a channel list for the system.
Retrieving existing RHN classic subscription information ...
+----------------------------------+
System is currently subscribed to:
+----------------------------------+
rhel-i386-client-5
Each discovered channel is then mapped to a corresponding product certificate (Seção 14.5.5, “Looking at Channel and Certificate Mappings”). Not every product has a product certificate, so not every channel may have a map. Only the channels with a certificate channel to a corresponding certificate map.
The matching certificates are copied into the /etc/pki/product directory.
List of channels for which certs are being copied
rhel-i386-client-5

Product Certificates copied successfully to /etc/pki/product !!
Then, the script unregisters the system from RHN Classic.
Preparing to unregister system from RHN classic ...
System successfully unregistered from RHN Classic.
Then, it registers the system with Certificate-based Red Hat Network.
Attempting to register system to Certificate-based RHN ...
The system has been registered with id: abcd1234
System server.example.com successfully registered to Certificate-based RHN.

Launching the GUI tool to manually subscribe the system ...
The last step opens the Subscription Manager GUI to the All Available Subscriptions tab so that the administrator can manually assign the subscriptions to the system.

Alternatively, the rhn-migrate-classic-to-rhsm can automatically subscribe the system to matching subscriptions.
Exemplo 14.8. All CLI-Based Migration
The --cli-only option tells the rhn-migrate-classic-to-rhsm to register the system with the autosubscribe option, so all of the migration process occurs in the command line.
The overall process is identical to the one in Exemplo 14.7, “Basic RHN Classic to Certificate-based Red Hat Network Migration” until the final step.
[root@server ~]# rhn-migrate-classic-to-rhsm --cli-only
RHN Username: jsmith@example.com
Password:

....

Attempting to auto-subscribe to appropriate subscriptions ...
Installed Product Current Status:
ProductName:            Red Hat Enterprise Linux Desktop
Status:                 Subscribed

Please visit https://access.redhat.com/management/consumers/abcd1234 to view the details, and to make changes if necessary.

14.5.3. Unregistering from RHN Classic Only

There may be an instance where a system should be unregistered from RHN Classic but is not yet ready to be registered to Certificate-based Red Hat Network. The rhn-migrate-classic-to-rhsm tool can be used simply to unregister a system from RHN Classic. This still copies over the product certificates for the classic channels to configure the system in the style of certificate-based subscriptions, but it does not register the machine with subscription service.
To unregister the system only, use the --no-auto option.
[root@server ~]# rhn-migrate-classic-to-rhsm --no-auto
RHN Username: jsmith@example.com
Password:

Retrieving existing RHN classic subscription information ...
+----------------------------------+
System is currently subscribed to:
+----------------------------------+
rhel-i386-client-5

List of channels for which certs are being copied
rhel-i386-client-5

Product Certificates copied successfully to /etc/pki/product !!

Preparing to unregister system from RHN classic ...
System successfully unregistered from RHN Classic.
Because there are product certificates, Subscription Manager will show a red, invalid status for the system and issue notifications until the system is registered and subscriptions applied.

14.5.4. Migrating a Disconnected System

Some systems may never be connected to an external network or may be prevented from accessing Red Hat Network or a Satellite system. These systems still require valid subscriptions and product certificates, though.
The rhn-migrate-classic-to-rhsm uses the information in /etc/sysconfig/rhn/systemid to get the previous registration information and map channels to certificates. If a system is disconnected, it may not have a systemid file.
Most systems, even ones never registered with RHN Classic, do have an installation number. When Red Hat software is purchased through a vendor, the purchased software is identified in an installation number or subscription number (described in https://access.redhat.com/kb/docs/DOC-15408) in the /etc/sysconfig/rhn/install-num file.
The installation number is in essence a code which contains all of the information about the products and versions purchased for the system. For example, this installation number shows that it is valid for RHEL Client and RHEL Workstation channels.
[root@server ~]# python /usr/lib/python2.4/site-packages/instnum.py da3122afdb7edd23
Product: RHEL Client
Type: Installer Only
Options: Eval FullProd Workstation
Allowed CPU Sockets: Unlimited
Allowed Virtual Instances: Unlimited
Package Repositories: Client Workstation

key: 14299426 "da3122"
checksum: 175 "af"
options: 4416 "Eval FullProd Workstation"
socklimit: -1 "Unlimited"
virtlimit: -1 "Unlimited"
type: 2 "Installer Only"
product: 1 "client"

{"Workstation": "Workstation", "Base": "Client"}
For a system which is not connected to either RHN Classic or a Satellite system, the installation number can be used to transition the product information from the older channel-based subscription model to the X.509 certificate model, managed by Subscription Manager.
The install-num-migrate-to-rhsm script identifies the channels that a disconnected system is subscribed to and then copies in the appropriate product certificates. Simply run the command:
[root@server ~]# install-num-migrate-to-rhsm
The script copies in the product certificates for the channels into the /etc/pki/product directory.
Once the system is migrated, it can be registered remotely and have entitlement certificates installed as described in Seção 14.4.3, “Registering an Offline Consumer”.
Even though the system is not registered, the system facts display what script was used for migration.
[root@server ~]# subscription-manager facts --list | grep migr
migration.migrated_from: install_number
Because the system was not previously registered with RHN Classic, the migration facts do not include a system ID number.

14.5.5. Looking at Channel and Certificate Mappings

The subscription-manager-migration-data package contains a mapping file that maps RHN Classic channels to Certificate-based Red Hat Network product certificates. This file (/usr/share/rhsm/product/RHEL-5/channel-cert-mapping.txt) uses simple keys to map the values:
channel_name: product_name-hash-product_cert.pem
For example, this maps the Red Hat Enterprise Linux Client channel to the corresponding product certificate:
rhel-i386-client-workstation-5: Client-Workstation-i386-b0d4c042-6e31-45a9-bd94-ff0b82e43b1a-71.pem
During migration, that mapping is translated into product_cert.pem and the product certificate is copied into the /etc/pki/product directory. For the rhel-i386-client-workstation-5, this migrates to the 71.pem product certificate (the last two digits of the mapping).
However, many channels are available for legacy systems only or have not yet released an X.509 product certificate. In that case, the channel has no mapping.
jbappplatform-4.3.0-fp-i386-server-5-rpm: none
This can create a situation where not all channels are migrated over to Certificate-based Red Hat Network or where products are not fully subscribed.

14.6. Handling Subscriptions

Assigning a subscription to a system gives the system the ability to install and update any Red Hat product in that subscription. A subscription is a list of all of the products, in all variations, that were purchased at one time, and it defines both the products and the number of times that subscription can be used (the quantity of that product). The quantity is roughly the number of user licenses available. When one of those licenses is allocated to a system, that system is subscribed to the subscription.
A subscription is available to a system based on the system's architecture and other installed products. Subscriptions that are available for a platform (based on its hardware and operating system) are compatible. When the subscription is actually assigned to the machine, the subscription is consumed.
A system can be subscribed to multiple subscriptions, a single subscription, or a single product. Subscribing a system requires the ID number of the subscription or the subscription key for the product.
Unsubscribing a machine removes the entitlement to any of the products in the subscription, but the machine remains registered with the subscription service. Unsubscribing one system frees the subscription so that it can be allocated to another system.

14.6.1. Subscribing and Unsubscribing through the Red Hat Subscription Manager GUI

14.6.1.1. Subscribing to a Product

  1. Launch the Red Hat Subscription Manager GUI. For example:
    subscription-manager-gui
  2. Open the All Available Subscriptions tab.
  3. Set the filters to use to search for available entitlements. Subscriptions can be filtered by their active date and by their name. The checkboxes provide more fine-grained filtering:
    • match my system shows only subscriptions which match the system architecture.
    • match my installed products shows subscriptions which work with currently installed products on the system.
    • have no overlap with existing subscriptions excludes subscriptions with duplicate products. If a system is already subscribed to an entitlement for a specific product or if multiple entitlements supply the same product, then the subscription service filters those subscriptions and shows only the best fit.
  4. Select the available entitlements. To select multiple subscriptions, use the Ctrl key.
  5. Click the Subscribe button.

14.6.1.2. Unsubscribing through the GUI

  1. Launch the Red Hat Subscription Manager GUI. For example:
    subscription-manager-gui
  2. Open the My Subscriptions tab.
    All of the active subscriptions to which the system is currently subscribed are listed. (The products available through the subscription may or may not be installed.)
  3. Select the entitlements to unsubscribe. To select multiple subscriptions, use the Ctrl key.
  4. Click the Unsubscribe button in the bottom right of the window.

14.6.2. Handling Subscriptions through the Command Line

14.6.2.1. Subscribing from the Command Line

Subscribing a machine through the command line requires specifying the individual product or subscription to subscribe to, using the --pool option.
[root@server1 ~]# subscription-manager subscribe --pool=XYZ01234567
The options for the subscribe command are listed in Tabela 14.4, “subscribe Options”.
The ID of the subscription pool for the purchased product must be specified, and this pool ID is listed with the product subscription information, from running the list command:
[root@server1 ~]# subscription-manager list --available

+-------------------------------------------+
    Available Subscriptions
+-------------------------------------------+


ProductName:            RHEL for Physical Servers
ProductId:              MKT-rhel-server
PoolId:                 ff8080812bc382e3012bc3845ca000cb
Quantity:               10
Expires:                2011-09-20
Alternatively, the system can be subscribed to the best-fitting subscriptions, as identified by the subscription service, by using the --auto option (which is analogous to the --autosubscribe option with the register command).
[root@server1 ~]# subscription-manager subscribe --auto
Tabela 14.4. subscribe Options
Options Description Required
--pool=pool-id Gives the ID for the subscription to subscribe the machine to. Required, unless --auto is used
--auto Automatically subscribes the system to the best-match subscription or subscriptions. Optional
--quantity Subscribes multiple counts of an entitlement to the system. This is used to cover subscriptions that define a count limit, like using two 2-socket server subscriptions to cover a 4-socket machine. Optional

14.6.2.2. Unsubscribing from the Command Line

A system can be subscribed to multiple subscriptions and products. The system can be unsubscribed from a single subscription or product or from every subscribed product.
Running the unsubscribe command with the --all unsubscribes the system from every product and subscription pool it is currently subscribed to.
[root@server1 ~]# subscription-manager unsubscribe --all
It is also possible to unsubscribe from a single product. Each product has an identifying X.509 certificate installed with it, and the product to unsubscribe from can be identified with the unsubscribe command to remove only that product subscription.
  1. Get the serial number for the product certificate, if you are unsubscribing from a single product. The serial number can be obtained from the cert.pem file or by using the list command. For example:
    [root@server1 ~]# subscription-manager list --consumed
    
    +-------------------------------------------+
        Consumed Product Subscriptions
    +-------------------------------------------+
    
    
    ProductName:         High availability (cluster suite)
    ContractNumber:      0
    SerialNumber:        11287514358600162
    Active:              True
    Begins:              2010-09-18
    Expires:             2011-11-18
  2. Run the subscription-manager tool with the --serial option to specify the certificate.
    [root@server1 ~]# subscription-manager unsubscribe --serial=11287514358600162

14.6.3. Stacking Subscriptions

Some subscriptions define a count which works as a restriction on the subscription. For example, counts can be set on the number of sockets or CPUs on a machine, the number of virtual guests on a host, or the number of clients in a domain.
The entire count must be covered for the system to be fully entitled. If there are four sockets on a machine, then the server subscriptions must cover four sockets, or if there are eight guests, then there must be enough to cover all eight guests.
Many subscriptions can be combined together to cover the count on the system. Two subscriptions for RHEL Server for 2-Sockets can be combined together to cover a four-socket machine. These subscriptions can be stacked.
There are some rules on what subscriptions can be stacked:
  • Subscriptions can be stacked by using multiple quantities from the same subscription set.
  • Subscriptions from different contracts can be stacked together.
  • Only the same product subscription can be stacked. RHEL Server for 2-Sockets can be stacked with another RHEL Server for 2-Sockets subscription, but not with RHEL Server for Virtualization, even if they both cover the socket count.
  • Stackable entitlements are indicated in the Subscription Manager UI with an asterisk (*). In the UI, available subscriptions are grouped first by what subscriptions are compatible for stacking, and then by other available subscriptions.
To stack subscriptions in the Subscription Manager UI, simply set the Quantity field to the required quantity to cover the count.
Stacking Quantities
Figura 14.13. Stacking Quantities

To stack subscriptions from the command line, use the --quantity option. The quantity taken applies to the product in the --pool option:
[root@server1 ~]# subscription-manager subscribe --pool=XYZ01234567 --quantity=2

14.6.4. Manually Adding a New Subscription

In certain situations, new product subscriptions can be added by uploading the X.509 entitlements certificate directly rather than polling the subscription service. For example, consumers which are offline must have subscriptions manually added because they cannot connect to the subscription service directly.
  1. Retrieve the certificate information for the consumer from the Customer Portal.
    1. Open the Subscriptions tab in the Customer Portal, and select the Overview item under the Certificate-Based Management area.
    2. In the summary of consumers, click the name of the offline consumer.
    3. If necessary, assign the subscriptions to the consumer.
    4. Open the Applied Subscriptions tab.
    5. Click the Download All Certificates button. This exports all of the entitlements certificates, for each product, to a single .zip file. Save the file to some kind of portable media, like a flash drive.
      To download individual entitlement certificates, click the Download link on the row for the subscription.
  2. Copy the certificates over to the consumer machine.
  3. If all certificates were downloaded in an archive file, then there are multiple archives in the downloaded certificates.zip file. Unzip the directories until the PEM files for the subscription certificates are available.
  4. Import the certificates.
    This can be done from the command line using the import command:
    # subscription-manager import --certificate=/tmp/export/entitlement_certificates/596576341785244687.pem --certificate=/tmp/export/entitlement_certificates/3195996649750311162.pem
    Successfully imported certificate 596576341785244687.pem
    Successfully imported certificate 3195996649750311162.pem
    This can also be performed through the Subscription Manager GUI:
    1. Launch the Red Hat Subscription Manager GUI. For example:
      subscription-manager-gui
    2. In the Tools area, click the Import Certificate button.
    3. Click the file folder icon at the right of the field to navigate to the .pem file of the product certificate.
    4. Click the Import Certificate button.
The consumer is then entitled for all of the subscription that were uploaded.

14.7. Redeeming Subscriptions on a Machine

Systems can be set up with pre-existing subscriptions already available to that system. For some systems which were purchased through third-party vendors, a subscription to Red Hat products is included with the purchase of the machine. Companies using the Subscription Asset Manager can allocate subscriptions to their own systems by creating activation keys which are used to claim those assigned subscriptions.
Red Hat Subscription Manager pulls information about the system hardware and the BIOS into the system facts to recognize the hardware vendor. If the vendor and BIOS information matches a certain configuration, then the subscription can be redeemed, which will allow the system to be automatically subscribed to the entitlements purchased with the machine.
This diverges from the normal subscription process by adding an extra step:
  1. The machine is registered first (Seção 14.4, “Registering, Unregistering, and Reregistering a System”). This can be done as normal or the activation keys can be submitted with command-line registrations.
  2. The subscriptions are redeemed using the given activation keys.
  3. The system is then subscribed to its subscriptions (Seção 14.6, “Handling Subscriptions”).

Nota

Activation keys may be generated by a hardware vendor (external to your organization). Activation keys may also be generated using the Subscription Asset Manager, which is a local subscription service, which is described in the Subscription Asset Manager documentation and Seção 14.12, “Working with Subscription Asset Manager”.

14.7.1. Redeeming Subscriptions through the GUI

The Activate Subscription Button

If the machine does not have any subscriptions to be redeemed, then the Activate Subscription button is not there.
  1. Launch the Red Hat Subscription Manager GUI. For example:
    subscription-manager-gui
  2. At the top of the main window, click the Activate Subscription button.
  3. In the pop-up window, enter the email address to send the notification to when the redemption is complete.
  4. Click the Activate button.
It can take up to ten minutes for the confirmation email to arrive.

14.7.2. Redeeming Subscriptions on a Machine through the Command Line

The machine subscriptions are redeemed by running the redeem command, with an email address to send the redemption email to when the process is complete.
# subscription-manager redeem --email=jsmith@example.com
In a multi-organization environment, it is also necessary to specify the organization which issued the activation keys. For example:
# subscription-manager redeem --email=jsmith@example.com --org="IT Dept"

Nota

The machine must be registered first so that the subscription service can properly identify the system and its subscriptions.

14.8. Viewing Available and Used Subscriptions

To manage subscriptions, administrators need to know both what subscriptions a system is currently consuming and what subscriptions are available to the system.

14.8.1. Viewing Subscriptions in the GUI

The Red Hat Subscription Manager tools give a more detailed view of subscriptions and entitlements than is available through the global tools of the Customer Portal. Three tabs summarize each of the subscriptions and products for the specific machine: installed products (with subscriptions), subscribed entitlements, and available subscriptions.
These summaries are always displayed in the Red Hat Subscription Manager UI.
Subscribed Entitlements
The My Subscriptions area shows all of the current entitlements that the system is subscribed to.
My Subscriptions Tab
Figura 14.14. My Subscriptions Tab

Available Subscriptions
The All Available Subscriptions area shows all of the subscriptions that are available to the system. The default displays only entitlements that are compatible with the hardware, but these can be filtered to show entitlements corresponding to other installed programs, only subscriptions that have not been installed, and subscriptions based on date.
All Available Subscriptions Tab
Figura 14.15. All Available Subscriptions Tab

The filters dynamically search for available entitlements. Subscriptions can be filtered by their active date and by their name. The checkboxes provide more fine-grained filtering:
  • match my system shows only subscriptions which match the system architecture.
  • match my installed products shows subscriptions which work with currently installed products on the system.
  • have no overlap with existing subscriptions excludes subscriptions with duplicate products. If a system is already subscribed to an entitlement for a specific product or if multiple entitlements supply the same product, then the subscription service filters those subscriptions and shows only the best fit.
My Installed Software
The My Installed Software area shows the currently installed products on the system, along with their subscription status. This doesn't allow administrators to install software, only to view installed software.
My Installed Software Tab
Figura 14.16. My Installed Software Tab

14.8.2. Listing Subscriptions with the Command Line

As with the three tabs in the UI, there are three different ways to use the list command to display different areas of the subscriptions and products on the system.
Tabela 14.5. subscription-manager list Options
Option Description
--installed (or nothing) Lists all of the installed and subscribed product on the system. If no option is given with list, it is the same as using the --installed argument.
--consumed Lists all of the subscriptions allocated to the system.
--available [--all] Using --available alone lists all of the compatible, active subscriptions for the system. Using --available --all lists all options, even ones not compatible with the system or with no more available quantities.
--ondate=YYYY-MM-DD Shows subscriptions which are active and available on the specified date. This is only used with the --available option. If this is not used, then the command uses the current date.
--installed Lists all of the products that are installed on the system (and whether they have a subscription) and it lists all of the product subscriptions which are assigned to the system (and whether those products are installed).

The list command shows all of the subscriptions that are currently allocated to the system by using the --consumed option.
[root@server1 ~]# subscription-manager list --consumed

+-------------------------------------------+
    Consumed Product Subscriptions
+-------------------------------------------+


ProductName:        	Red Hat Enterprise Linux Server
ContractNumber:     	1458961
SerialNumber:       	171286550006020205
Active:             	True
Begins:             	2009-01-01
Expires:            	2011-12-31
The list command shows all of the subscriptions that are compatible with and available to the system using the --available option. To include every subscription the organization has — both the ones that are compatible with the system and others for other platforms — use the --all option with the --available. The --ondate option shows only subscriptions which are active on that date, based on their activation and expiry dates.
[root@server1 ~]# subscription-manager list --available --all

+-------------------------------------------+
    Available Subscriptions
+-------------------------------------------+


ProductName:            RHEL for Physical Servers
ProductId:              MKT-rhel-server
PoolId:                 ff8080812bc382e3012bc3845ca000cb
Quantity:               10
Expires:                2011-09-20


ProductName:            RHEL Workstation
ProductId:              MKT-rhel-workstation-mkt
PoolId:                 5e09a31f95885cc4
Quantity:               10
Expires:                2011-09-20

[snip]
The --installed option correlates the products that are actually installed on the system (and their subscription status) and the products which could be installed on the system based on the assigned subscriptions (and whether those products are installed).
[root@server1 ~]# subscription-manager list --installed

+-------------------------------------------+
    Installed Product Status
+-------------------------------------------+
ProductName:         Red Hat Enterprise Linux
Status:              Not Subscribed
Expires:
Subscription:
ContractNumber:
AccountNumber:


ProductName:         Awesome OS Server
Status:              Not Installed
Expires:             2012-02-20
Subscription:        54129829316535230
ContractNumber:      39
AccountNumber:       12331131231

14.8.3. Viewing Subscriptions Used in Both RHN Classic and Certificate-based Red Hat Network

Administrators need to have a sense of all of the subscriptions allocated for their organization, altogether, regardless of whether the system is managed in RHN Classic or Certificate-based Red Hat Network. The Customer Portal provides a way of looking at the total consumed subscriptions.
In the Subscriptions Overview page, the Subscription Utilization area at the top gives the current count for every active subscription for the entire organization, and a total count of every used subscription, regardless of whether it is used in RHN Classic or Certificate-based Red Hat Network. These numbers are updated whenever the subscription count changes in the subscription server. (The subsequent Certificate-based Red Hat Network and RHN Classic sections gives usage subcounts based on system which are registered to that specific subscription service.)
Total Counts of Subscriptions for All Subscription Services
Figura 14.17. Total Counts of Subscriptions for All Subscription Services

NOTE

RHN Classic is provided for legacy systems. Red Hat Enterprise Linux 5.7 and 6.1 and later systems should use Certificate-based Red Hat Network to manage subscriptions for systems.

14.9. Working with Subscription yum Repos

As Seção 14.1.4, “Subscription and Content Architecture” says, Red Hat Subscription Manager works with package management tools like yum. Subscription Manager has its own yum plug-ins: product-id for subscription-related information for products and subscription-manager which is used for the content repositories.
As systems are subscribed to products, the associated content repositories (identified in the entitlement certificate) are made available to the system. The content repositories are based on the product and on the content delivery network, defined in the baseurl parameter of the rhsm.conf file.
A subscription may include access to optional content channels along with the default channels. This optional channels must be enabled before the packages in them can be installed (even if the system is fully entitled to the products in those channels).
  1. List all available repos for the system, including disabled repos.
    [root@server ~]# yum repolist all
    repo id                      repo name                           status
    rhel-5-server                Red Hat Enterprise Linux 5Server -  enabled:    1,749
    rhel-5-server-beta           Red Hat Enterprise Linux 5Server Be enabled:      869
    rhel-5-server-optional-rpms  Red Hat Enterprise Linux 5Server Op disabled
    rhel-5-server-supplementary  Red Hat Enterprise Linux 5Server Su disabled
    The optional and supplementary channels are named rhel-5-server-optional-rpms and rhel-5-server-supplementary, respectively.
  2. The repositories can be enabled using the yum-config-manager command:
    [root@server ~]# yum-config-manager --enable rhel-5-server-optional-rpms
Alternatively, simply specify the optional or supplementary repository when installing a package with yum. This uses the --enablerepo repo_name option. For example:
# yum install rubygems --enablerepo=rhel-5-server-optional-rpms
Loaded plugins: product-id, refresh-packagekit, subscription-manager
Updating Red Hat repositories.
....

14.10. Responding to Subscription Notifications

The Red Hat Subscription Manager provides a series of log and UI messages that indicate any changes to the valid certificates of any installed products for a system. In the Subscription Manager GUI, the status of the system entitlements is color-coded, where green means all products are fully subscribed, yellow means that some products may not be subscribed but updates are still in effect, and red means that updates are disabled.
Color-Coded Status Views
Figura 14.18. Color-Coded Status Views

The command-line tools also indicate that status of the machine. The green-yellow-red codes translate to text status messages of subscribed, partially subscribed, and expired/not subscribed, respectively.
[root@server ~]# subscription-manager list
+-------------------------------------------+
    Installed Product Status
+-------------------------------------------+

ProductName:            Red Hat Enterprise Linux Server
Status: Not Subscribed
Expires:
SerialNumber:
ContractNumber:
AccountNumber:
Whenever there is a warning about subscription changes, a small icon appears in the top menu bar, similar to a fuel gauge.
Subscription Notification Icon
Figura 14.19. Subscription Notification Icon

As any installed product nears the expiration date of the subscription, the Subscription Manager daemon will issue a warning. A similar message is given when the system has products without a valid certificate, meaning either the system is not subscribed to a subscription that entitles that product or the product is installed past the expiration of the subscription. Clicking the Manage My Subscriptions... button in the subscription notification window opens the Red Hat Subscription Manager GUI to view and update subscriptions.
Subscription Warning Message
Figura 14.20. Subscription Warning Message

When the Subscription Manager UI opens, whether it was opened through a notification or just opened normally, there is a box in the upper left corner that shows the number of products that lack a valid certificate. The easiest way to allocate subscriptions which match invalidated products is to click the Update Certificates button.
Update Certificates Button
Figura 14.21. Update Certificates Button

The Subscription Assistant pop-up window shows a targeted list of available subscriptions that apply to the specific products that do not have valid certificates (assuming subscriptions are available).
Subscription Assistant
Figura 14.22. Subscription Assistant

Alternatively, you can respond to entitlements notifications by managing subscriptions generally:

14.11. Healing Subscriptions

Subscription Manager can monitor all of the active entitlements for a system. Along with passively warning that a subscription is close to expiration (Seção 14.10, “Responding to Subscription Notifications”), Subscription Manager can be configured to re-subscribe to subscriptions, automatically and actively, as one nears its expiry. This is system healing.
System healing prevents a system from having unentitled products as long as any valid subscription is available for it.
System healing is configured as part of the Subscription Manager daemon, rhsmcertd. This daemon checks the certificate validity dates daily. If a subscription is within 24 hours of expiring, then Subscription Manager will check for any available compatible subscriptions and automatically re-subscribes the system, much like auto-subscribing during registration.

14.11.1. Enabling Healing

System healing is disabled by default. It can be enabled by manually adding the autoheal parameter to the Subscription Manager configuration.
  1. Open the Subscription Manager configuration file.
    vim /etc/rhsm/rhsm.conf
  2. In the [rhsmcertd] area, add the autoheal line, and set the value to true.
    [rhsmcertd]
    certFrequency = 240
    healFrequency = 1440
    autoheal = true
The configuration can also be updated using the config command:
[root@server1 ~]# subscription-manager config --rhsmcertd.autoheal=true

14.11.2. Changing the Healing Check Frequency

NOTE

Healing cannot be disabled by changing the time interval. Setting the healFrequency parameter to zero means that Subscription Manager simply uses the default time setting.
  1. Open the Subscription Manager configuration file:
    # vim /etc/rhsm/rhsm.conf
  2. In the [rhsmcertd] section, set the healFrequency parameter to the time, in minutes, to check for changed subscriptions.
    [rhsmcertd]
    certFrequency = 240
    healFrequency = 1440
  3. Restart the rhsmcertd daemon to reload the configuration.
    # service rhsmcertd start

14.12. Working with Subscription Asset Manager

Subscription Asset Manager works with the local Subscription Manager tools, but the local Subscription Manager must be configured to work with the given Subscription Asset Manager service.
This section covers the procedures for setting up Subscription Manager to work with Subscription Asset Manager.
The Subscription Asset Manager documentation details all the tasks for managing the infrastructure:
  • Creating organizations and environments.
  • Creating activation keys.
  • Managing subscription manifests from Red Hat.
  • Viewing notification and system reports.

14.12.1. Configuring Subscription Manager to Work with Subscription Asset Manager

Subscription Asset Manager performs two backend management functions:
  • Allocate subscriptions as a subscription service
  • Work as a real-time proxy for the content delivery network
That means that the local Subscription Manager client needs to be configured to use Subscription Asset Manager as its subcription service and content provider, rather than using the default Red Hat Network (hosted) configuration.
The subscription service URL is configured in the hostname parameter in the [server] area in the rhsm.conf configuration file. The content delivery network URL is configured in the baseurl parameter in the [rhsm] area. These values can be reset using the config command. For example:
[root@server1 ~]# subscription-manager config --server.hostname=sam.example.com --rhsm.baseurl=sam.example.com
Changing the Subscription Manager configuration with the config command is covered in Seção 14.14.2, “Using the config Command”.

14.12.2. Viewing Organization Information

Infrastructures that have their own local content and subscription services, such as Subscription Asset Manager, can define groups that organize their systems. The primary division is organizations, which create independent units. The systems and users in one organization are invisible to the systems and users in another organization. Organizations can be subdivided into environments, which provide associations with content repositories and allowed products, versions, and content sets. A system can belong to multiple environments.
Organizations, environments, and repositories are created and configured in the service application, such as Subscription Asset Manager. However, the organization structure for a system or for a user account can be viewed using the Subscription Manager command-line tools. The orgs, environments, and repos commands list the organization, environment, and repository information for the system, depending on the organization and environments it belongs to.
For example:
[root@server1 ~]# subscription-manager orgs --username=jsmith --password=secret
+-------------------------------------------+
           admin Organizations
+-------------------------------------------+

OrgName:         Admin Owner
OrgKey:         admin

OrgName:         Dev East
OrgKey:         deveast

OrgName:         Dev West
OrgKey:         devwest


[root@server1 ~]# subscription-manager environments --username=jsmith --password=secret --org=admin
+-------------------------------------------+
           Environments
+-------------------------------------------+

Name:                        Locker
Description:                 None

Name:                        Dev
Description:

Name:                        Prod
Description:


[root@server1 ~]# subscription-manager repos --list
+----------------------------------------------------------+
     Entitled Repositories in /etc/yum.repos.d/redhat.repo
+----------------------------------------------------------+

RepoName:                    never-enabled-content
RepoId:                      never-enabled-content
RepoUrl:                     https://content.example.com/repos/optional
Enabled:                     0


RepoName:                    always-enabled-content
RepoId:                      always-enabled-content
RepoUrl:                     https://content.example.com/repos/dev
Enabled:                     1


RepoName:                    content
RepoId:                      content-label
RepoUrl:                     https://content.example.com/repos/prod
Enabled:                     1

14.13. Updating Entitlements Certificates

An entitlement certificate represents a subscription that has been consumed by a given system. It includes all of the products which are included in the subscription for service and support, the subscription's start and end dates, and the number of entitlements included for each product. An entitlement certificate does not list products that are currently installed on the system; rather, it lists all of that products that are available to the system.
The entitlement certificate is an X.509 certificate and is stored in a base 64-encoded blob in a .pem file.
When a subscription expires or is changed, then the entitlement certificate must be updated to account for the changes. The Red Hat Subscription Manager polls the subscription service periodically to check for updated entitlement certificates; this can also be updated immediately or pulled down from the Customer Portal. The entitlement certificates are updated by revoking the previous entitlement certificate and generating a new one to replace it.

14.13.1. Updating Entitlement Certificates

  1. Open the Red Hat Customer Portal.
    https://access.redhat.com/
  2. Click the Subscriptions tab to open the subscriptions menu, and select the Consumers List option under Certificate-Based Management.
  3. Click the system name in the list of consumers.
  4. Open the Applied Subscriptions tab for the list of all active, assigned subscriptions for the consumer.
  5. Click the Download All Certificates button above the list of subscriptions. If there is only one subscription, then click the Download button by the certificate.
    To retrieve an individual entitlement certificate, click the Download link in the subscription row.
  6. If all entitlement certificates were downloaded in an archive file, then there are multiple archives in the downloaded certificates.zip file. Unzip the directories until the PEM files for the entitlement certificates are available.
  7. Import the certificate PEM file. This can be done using the Import Certificates button in the Subscription Manager GUI or using the import command:
    # subscription-manager import --certificate=/tmp/export/entitlement_certificates/596576341785244687.pem --certificate=/tmp/export/entitlement_certificates/3195996649750311162.pem
    Successfully imported certificate 596576341785244687.pem
    Successfully imported certificate 3195996649750311162.pem

14.13.2. Updating Subscription Information

The refresh command updates all of the subscription information that is available to the consumer. This removes expired subscriptions and adds new subscriptions to the list. This does not subscribe the machine, but it does pull in the newest data for administrators to use.
[root@server1 ~]# subscription-manager refresh

14.14. Configuring the Subscription Service

By default, Red Hat Subscription Manager (both GUI and CLI) talk to the subscription service and the Customer Portal for their subscription services and content delivery, respectively. Red Hat Subscription Manager can be configured to use different content servers or subscription services. Other aspects of the Red Hat Subscription Manager — like the locations to look for system and product certificates or the system information used by Red Hat Subscription Manager to identify compatible entitlements — can also be customized to fit the network environment.

14.14.1. Red Hat Subscription Manager Configuration Files

The primary configuration file for Red Hat Subscription Manager, both the GUI and CLI tools, is the rhsm.conf configuration file. There are other support files that either influence the Red Hat Subscription Manager service or can help administrators better use the Subscription Manager.

14.14.1.1. All Files Used by Red Hat Subscription Manager

All of the files related to the configuration of Red Hat Subscription Manager are used by both the GUI and CLI; there's no separate configuration.
Tabela 14.6. Red Hat Subscription Manager Files and Directories
File or Directory Description
/etc/rhsm The primary Red Hat Subscription Manager configuration directory.
/etc/rhsm/rhsm.conf The Red Hat Subscription Manager configuration file. This is used by both the GUI and the CLI.
/etc/rhsm/facts Any user-defined JSON files that override or add system facts to determine entitlement compatibility. Any facts files must end in .facts.
/var/lib/rhsm/cache/installed_products.json A master list of installed products, which is sent by Subscription Manager to a hosted content service, such as Subscription Asset Manager.
/var/lib/rhsm/facts/facts.facts The default system facts filed, gathered by the Subscription Manager.
/var/lib/rhsm/packages/ The package profile cache (a list of installed products) which is gathered and periodically updated by the Subscription Manager.
/var/log/rhsm The Red Hat Subscription Manager log directory.
/var/log/rhsm/rhsm.log The log for the Red Hat Subscription Manager tools.
/var/log/rhsm/rhsmcertd.log The log for the Red Hat Subscription Manager daemon, rhsmcertd.
/etc/pki/consumer The directory which contains the identity certificates used by the system to identify itself to the subscription service.
/etc/pki/consumer/cert.pem The base-64 consumer identity certificate file.
/etc/pki/consumer/key.pem The base-64 consumer identity key file.
/etc/pki/entitlement The directory which contains the entitlement certificates for the available subscriptions.
/etc/pki/product/product_serial#.pem The product certificates for installed software products.
/var/run/subsys/rhsm Runtime files for Red Hat Subscription Manager
/etc/init.d/rhsmcertd The subscription certificate daemon.
/etc/cron.daily/rhsm-complianced and /usr/libexec/rhsm-complianced Files to run daily checks and notifications for subscription validity.
/etc/yum/pluginconf.d/rhsmplugin.conf The configuration file to include the Red Hat Subscription Manager plug-in in the yum configuration.
/usr/share/rhsm All of the Python and script files used by both Red Hat Subscription Manager tool to perform subscription tasks.
/usr/share/rhsm/gui All of the Python script and image files used to render the Red Hat Subscription Manager GUI.

14.14.1.2. About the rhsm.conf File

The main configuration file for the Subscription Manager is rhsm.conf. This file configures several important aspects of how Red Hat Subscription Manager interacts with both entitlements and content services:
  • The subscription service connection information, including the server host and port
  • The content service to use, in the form of a web address
  • The location of all of the different certificates used by the subscription service, including CA certificates for SSL authentication, identity certificates for the system, and entitlement and product certificates
The rhsm.conf file is divided into three sections. Two major sections defined the subscription service ([server]) and content and product delivery ([rhsm]). The third section relates to the rhsmcertd daemon. Each assertion is a simple attribute= value pair. Any of the default values can be edited; all possible attributes are present and active in the default rhsm.conf file.
Exemplo 14.9. Default rhsm.conf File
# Red Hat Subscription Manager Configuration File:

# Unified Entitlement Platform Configuration
[server]
# Server hostname:
hostname = subscription.rhn.redhat.com

# Server prefix:
prefix = /subscription

# Server port:
port = 443

# Set to 1 to disable certificate validation:
insecure = 0

# Set the depth of certs which should be checked
# when validating a certificate
ssl_verify_depth = 3

# Server CA certificate location:
ca_cert_dir = /etc/rhsm/ca/

# an http proxy server to use
proxy_hostname =

# port for http proxy server
proxy_port =

# user name for authenticating to an http proxy, if needed
proxy_user =

# password for basic http proxy auth, if needed
proxy_password =

[rhsm]
# Content base URL:
baseurl= https://cdn.redhat.com

# Default CA cert to use when generating yum repo configs:
repo_ca_cert = %(ca_cert_dir)sredhat-uep.pem

# Where the certificates should be stored
productCertDir = /etc/pki/product
entitlementCertDir = /etc/pki/entitlement
consumerCertDir = /etc/pki/consumer

[rhsmcertd]
# Frequency of certificate refresh (in minutes):
certFrequency = 240
# Frequency of autoheal check (1440 min = 1 day):
healFrequency = 1440

Tabela 14.7. rhsm.conf Parameters
Parameter Description Default Value
[server] Parameters
hostname Gives the IP address or fully-qualified domain name of the subscription service. subscription.rhn.redhat.com
prefix Gives the directory, in the URL, to use to connect to the subscription service. /subscription
port Gives the port to use to connect to the subscription service. 443
insecure Sets whether to use a secure (0) or insecure (1) connection for connections between the Subscription Manager clients and the subscription service. 0
ssl_verify_depth Sets how far back in the certificate chain to verify the certificate. 3
proxy_hostname Gives the hostname of the proxy server. This is required.
proxy_port Gives the port of the proxy server. This is required.
proxy_user Gives the user account to use to access the proxy server. This may not be required, depending on the proxy server configuration.
proxy_password Gives the password credentials to access the proxy server. This may not be required, depending on the proxy server configuration.
ca_cert_dir Gives the location for the CA certificate for the CA which issued the subscription service's certificates. This allows the client to identify and trust the subscription service for authentication for establishing an SSL connection. /etc/rhsm/ca
[rhsm] Parameters
baseurl Gives the full URL to access the content delivery system. https://cdn.redhat.com
repo_ca_cert Identifies the default CA certificate to use to set the yum repo configuration. %(ca_cert_dir)sredhat-uep.pem
showIncompatiblePools
Sets whether to display subscription pools which are not compatible with the system's architecture but which have been purchased by an organization. By default, Subscription Manager only displays subscriptions which are compatible with, and therefore available to, the system.
This parameter only applies to the Subscription Manager GUI. Incompatible subscriptions can be displayed in the CLI by using the --all option with the list command.
0
productCertDir Sets the root directory where the product certificates are stored and can be accessed by Subscription Manager. /etc/pki/product
consumerCertDir Sets the directory where the identity certificate for the system is stored and can be accessed by Subscription Manager. /etc/pki/consumer
entitlementCertDir Sets the directory where the entitlement certificates for the system are stored and can be accessed by Subscription Manager. Each subscription has its own entitlement certificate. /etc/pki/entitlement
[rhsmcertd] Parameters
certFrequency Sets the interval, in minutes, to check and update entitlement certificates used by Subscription Manager. 240
healFrequency Sets the interval, in minutes, to check for change subscriptions and installed products and to allocate subscriptions, as necessary, to maintain subscription status for all products. 240

14.14.2. Using the config Command

subscription-manager has a subcommand that can change the rhsm.conf configuration file. Almost all of the connection information used by Subscription Manager to access the subscription server, content server, and any proxies is set in the configuration file, as well as general configuration parameters like the frequency Subscription Manager checks for entitlements updates. There are major divisions in the rhsm.conf file, such as [server] which is used to configure the subscription server. When changing the Subscription Manager configuration, the settings are identified with the format section.parameter and then the new value. For example:
server.hostname=newsubscription.example.com
When changing the value for a parameter, the parameter is passed as an argument to the config command:
[root@server1 ~]# subscription-manager config --section.parameter=newValue
For example, to change the hostname of the subscription service:
[root@server1 ~]# subscription-manager config --server.hostname=subscription.example.com
All of the rhsm.conf file parameters are listed in Tabela 14.7, “rhsm.conf Parameters”. This is most commonly used to change connection settings:
  • server.hostname (subscription server)
  • server.proxy
  • server.proxy_port
  • server.proxy_user
  • server.proxy_password
  • rhsm.baseurl (content server)
  • rhsm.certFrequency
The config command also has a --remove option. This deletes the the current value for the parameter without supplying a new parameter. A blank value tells Subscription Manager to use any default values that are set for that parameter rather than a user-defined value. For example:
[root@server1 ~]# subscription-manager config --remove=rhsm.certFrequency

The default value for rhsm.certFrequency will now be used.
If a value does not have a default, then the command returns simply that the value has been removed:
[root@server1 ~]# subscription-manager config --remove=server.proxy

You have removed the value in section server for parameter proxy.

14.14.3. Using an HTTP Proxy

Some network environments may only allow external Internet access or access to content servers by going through an HTTP proxy.

14.14.3.1. Configuring an HTTP Proxy for GUI Use

The Red Hat Subscription Manager GUI can be configured to use an HTTP proxy for all of its connections to the subscription service. (This is also an advanced configuration option at firstboot.) To configure the proxy:
  1. Launch the Red Hat Subscription Manager GUI. For example:
    subscription-manager-gui
  2. Click the Proxy Configuration button at the top of the window in the Tools area.
  3. Check the ...Connect to Red Hat Network via an HTTP Proxy checkbox and enter the server location, in the format hostname:port.
  4. If the proxy requires a username/password to allow access, then also select the User authentication checkbox and fill in the user credentials.
  5. The configuration is automatically applied, so when the proxy is configured, simply close the window.

14.14.3.2. Configuring HTTP Proxy in the rhsm.conf File

The HTTP proxy settings can be configured in the rhsm.conf file; this is the same as configuring it in the Subscription Manager GUI. The proxy configuration is stored and used for every connection between the subscription service and the local system.
  1. Open the Subscription Manager configuration file.
    vim /etc/rhsm/rhsm.conf
  2. Change the settings in the [server] section that relate to the HTTP proxy. All parameters are described in Tabela 14.7, “rhsm.conf Parameters”. There are four parameters directly related to the proxy:
    • proxy_hostname for the IP address or fully-qualified domain name of the proxy server; this is required.

      Note

      Leaving the proxy_hostname argument blank means that no HTTP proxy is used.
    • proxy_port for the proxy server port.
    • proxy_user for the user account to connect to the proxy; this may not be required, depending on the proxy server's configuration.
    • proxy_password for the password for the user account to connect to the proxy; this may not be required, depending on the proxy server's configuration.
    [server]
    
    # an http proxy server to use
    proxy_hostname = proxy.example.com
    
    # port for http proxy server
    proxy_port = 443
    
    # user name for authenticating to an http proxy, if needed
    proxy_user =
    
    # password for basic http proxy auth, if needed
    proxy_password =

14.14.3.3. Passing HTTP Proxy Information with subscription-manager Commands

Rather than using a permanently-configured HTTP proxy, as the GUI does, HTTP proxy information can be passed with a command invocations. The arguments listed in Tabela 14.8, “Proxy Arguments” are available to every command used with subscription-manager.
Tabela 14.8. Proxy Arguments
Argument Description Required for a Proxy Connection?
--proxy Gives the proxy server to connect to, in the format hostname:port. Yes
--proxyuser Gives the username to use to authenticate. This is only required if user authentication is required. No
--proxypass Gives the password to use with the user account. This is only required if user authentication is required. No

The proxy information can be passed with any subscription-manager operation. For example:
[root@server1 ~]# subscription-manager subscribe --pool=ff8080812bc382e3012bc3845ca000cb --proxy=proxy.example.com:8443 --proxyuser=jsmith --proxypass=secret

14.14.4. Changing the Subscription Server

The Subscription Manager usually connects to the subscription service, and the public server is configured in the rhsm.conf file. The subscription service connection settings are in the [server] section of the configuration file.
  1. Open the Subscription Manager configuration file.
    vim /etc/rhsm/rhsm.conf
  2. Change the settings in the [server] section that relate to the subscription service connection. All parameters are described in Tabela 14.7, “rhsm.conf Parameters”. There are three parameters directly related to the connection:
    • hostname for the IP address or fully-qualified domain name of the machine
    • prefix for the subscription service directory
    • port for the subscription service port
    [server]
    hostname=entitlements.server.example.com
    prefix=/candlepin
    port=8443

14.14.5. Configuring Red Hat Subscription Manager to Use a Local Content Provider

By default, the Subscription Manager is configured to use Red Hat's content delivery service, which is available at https://cdn.redhat.com. This can be changed to use a different external content delivery system or to use an organization-managed content system, such as Subscription Asset Manager.
  1. Open the Subscription Manager configuration file.
    vim /etc/rhsm/rhsm.conf
  2. Change the baseurl directive in the [rhsm] section. This is the full URL to the service.
    [rhsm]
    # Content base URL:
    baseurl= http://content.example.com/content

14.14.6. Managing Secure Connections to the Subscription Server

Red Hat Subscription Manager assumes, by default, that the subscription clients connect to the subscription service using a secure (SSL) connection. This requires that the CA certificate of the subscription service be downloaded and available locally for the client and that the appropriate connections be configured.
  1. Open the Subscription Manager configuration file.
    vim /etc/rhsm/rhsm.conf
  2. Change the settings in the [server] section that relate to a secure connection. All parameters are described in Tabela 14.7, “rhsm.conf Parameters”. There are three parameters directly related to the connection:
    • insecure to set whether to use a secure (0) or insecure (1) connection
    • ca_cert_dir for the directory location for the CA certificate for authentication and verification
    • port for the subscription service port; this should be an SSL port if a secure connection is required
    [server]
    port=8443
    insecure = 1
    ca_cert = /etc/rhsm/ca

14.14.7. Starting and Stopping the Subscription Service

The Red Hat Subscription Manager daemon, rhsmcertd, runs as a service on the system. The daemon, by default, starts with the system, and it can be started, stopped, or checked with the service command.
service rhsmcertd status
rhsmcertd (pid 13084) is running...
Red Hat Enterprise Linux has a tool called chkconfig which manages the automatic startup and shutdown settings for each process on the server, described in Seção 17.5, “chkconfig. When a system reboots, some services can be automatically restarted. chkconfig also defines startup settings for different run levels of the server.
The Red Hat Subscription Manager service, which runs routinely to check for changes in the entitlements for an organization, can be controlled by chkconfig. By default, the Red Hat Subscription Manager daemon, rhsmcertd, is configured to run at levels 3, 4, and 5, so that the service is started automatically when the server reboots.
The run level settings can be reset using chkconfig. For example, to enable run level 2:
chkconfig --level 2345 rhsmcertd on
To remove the rhsmcertd from the start list, change the run level settings off:
chkconfig --level 2345 rhsmcertd off
Red Hat Enterprise Linux also has a GUI console that can manage the service and chkconfig settings.
  1. In the main menu, select the System link and open the Administration submenu.
  2. Open the Services link.

    Note

    The system-config-services package must be installed for the Services wizard to be available.
  3. Scroll to the rhsmcertd item in the list of services on the left, and then edit the service as desired.

14.14.8. Checking Logs

There are two log files maintained for Red Hat Subscription Manager in the /var/log/rhsm directory:
  • rhsm.log shows every invocation and result of running the Subscription Manager GUI or CLI
  • rhsmcertd.log shows every time a new certificate is generated, which happens on a schedule defined by the certFrequency parameter in the rhsm.conf file.
The rhsm.log log contains the sequence of every Python call for every operation invoked through the Subscription Manager tools. Each entry has this format:
YYYY-MM-DD HH:MM:SS,process_id [MESSAGE_TYPE] call python_script response
The response in the log entry can be very complex, spanning multiple lines, or relatively simply, with just a status code.
Because each log entry in rhsm.log relates to the Python script or function that was called, there can be multiple log entries for a single operation.
Exemplo 14.10. rhsm.log Entry
2010-10-01 17:27:57,874 [INFO] _request() @connection.py:97 - status code: 200
2010-10-01 17:27:57,875 [INFO] perform() @certlib.py:132 - updated:
Total updates: 0
Found (local) serial# []
Expected (UEP) serial# []
Added (new)
  <NONE>
Deleted (rogue):
  <NONE>
Expired (not deleted):
  <NONE>
Expired (deleted):
  <NONE>
2010-10-01 17:27:57,878 [INFO] __init__() @connection.py:193 - Using certificate authentication: key = /etc/pki/consumer/key.pem, cert = /etc/pki/consumer/cert.pem, ca = /etc/pki/CA/candlepin.pem, insecure = True
2010-10-01 17:27:57,878 [INFO] __init__() @connection.py:196 - Connection Established: host: candlepin1.devlab.phx1.redhat.com, port: 443, handler: /candlepin

The entries in the rhsmcertd.log file are much simpler. The log only records when the rhsmcertd daemon starts or stops and every time a certificate is updated.
Exemplo 14.11. rhsmcertd.log Entry
Fri Oct  1 13:27:44 2010: started: interval = 240 minutes
Fri Oct  1 13:27:50 2010: certificates updated

14.14.9. Showing and Hiding Incompatible Subscriptions

The entitlements that are made available to a consumer are filtered, by default, according to whether the architecture for the product matches the architecture of the system. This is compatibility. The Red Hat Subscription Manager can be configured to display even incompatible entitlements.
When running the command-line tools, the incompatible facts can be displayed simply by using the --all option:
[root@server1 ~]# subscription-manager list --available --all
To have the incompatible subscriptions displayed in the GUI and through the command-line by default, edit the rhsm.conf configuration file.
  1. Open the Subscription Manager configuration file.
    vim /etc/rhsm/rhsm.conf
  2. Change the showIncompatiblePools directive in the [rhsm] section. A value of 0 shows only compatible entitlements.
    [rhsm]
    # Content base URL:
    showIncompatiblePools = 1

14.14.10. Checking and Adding System Facts

Entitlements are available to a system based on whether the software is compatible with the system's architecture. For example, there are different products and subscriptions for 32-bit and 64-bit platforms. Red Hat Subscription Manager determines compatibility by collecting a range of facts about the system's hardware and architecture and then comparing it with all available entitlements.
The collected facts can be viewed, updated to acknowledge a hardware or configuration change, or overridden to force compatibility in the specified areas.
The system facts are very similar to the information in /etc/redhat-release or /etc/sysconfig. In both the Red Hat Subscription Manager GUI and CLI, the facts are represented as simple attribute: value pairs.

Tip

Updating the facts resends the information about the system to the Red Hat subscription service so that it can update the list of subscriptions which match the system architecture. Updating the facts is a very good thing to do after hardware upgrades or other important system changes.

14.14.10.1. Checking Facts from the Red Hat Subscription Manager UI

  1. Launch the Red Hat Subscription Manager GUI. For example:
    subscription-manager-gui
  2. In the Tools at the top of the window, click the View System Facts button.
  3. All of the current facts for the system are listed in the table, broken down into categories. Each category is in a closed list; to reveal all of the facts in that category, click the arrow by the category name.
    To update the facts, click the Update Facts button in the bottom right of the window.

14.14.10.2. Checking Facts with subscription-manager

To simply list the facts, run the facts with the --list option.
[root@server1 ~]# subscription-manager facts --list

cpu.architecture: i686
cpu.core(s)_per_socket: 4
cpu.cpu(s): 4
cpu.cpu_family: 6
cpu.cpu_mhz: 2000.010
cpu.cpu_op-mode(s): 32-bit, 64-bit
cpu.cpu_socket(s): 1
cpu.l1d_cache: 32K
cpu.l1i_cache: 32K
cpu.l2_cache: 6144K
cpu.model: 23
cpu.stepping: 6
cpu.thread(s)_per_core: 1
cpu.vendor_id: GenuineIntel
cpu.virtualization: VT-x
distribution.id: Santiago
distribution.name: Red Hat Enterprise Linux Workstation
distribution.version: 5
dmi.baseboard.manufacturer: IBM
dmi.baseboard.product_name: Server Blade
... [snip] ...
To update the facts after a system change, use the --update option with the facts command.
[root@server1 ~]# subscription-manager facts --update

14.14.10.3. Overriding the Default System Facts

The system facts, as collected, are stored in /var/lib/rhsm/facts/facts.facts. These facts are stored as attribute: value pairs, in a comma-separated list.
{"fact1": "value1","fact2": "value2"}
The primary file is generated and maintained by the Subscription Manager service. However, these values can be overridden to force architecture or platform compatibility (and thereby widening the available compatible subscriptions) by creating additional JSON facts files and dropping them in the /etc/rhsm/facts directory. These JSON files can override existing facts or even add new facts to be used by the subscription service.
Exemplo 14.12. Example Facts Override File
vim /etc/rhsm/facts/my-example.facts

{"uname.machine": "x86","kernel_version": "2.6.32","physical_location": "MTV colo rack 5"}

14.14.11. Regenerating Identity Certificates

To regenerate the consumer's identity certificate (meaning it is revoked and replaced), use the identity command. Although not required, using the --force option will require the username and password and will cause the Subscription Manager to prompt for the credentials if they are not passed in the command:
[root@server1 ~]# subscription-manager identity --regenerate --force
Username: jsmith@example.com
Password:
Identity certificate has been regenerated.

14.14.12. Getting the System UUID

The consumer or system UUID is a unique identifier used in the inventory subscription service. This UUID can be used to re-register the system if there is some kind of corruption or for internal tracking. In the GUI (Seção 14.14.10.1, “Checking Facts from the Red Hat Subscription Manager UI”), this is listed as one of the system facts, under the system category:
From the command-line, use the identity command to return the current UUID. The UUID is the Current identity is value.
[root@server1 ~]# subscription-manager identity
Current identity is: 63701087-f625-4519-8ab2-633bb50cb261
name: server1.example.com
org name: 6340056
org id: 8a85f981302cbaf201302d89931e059a

14.14.13. Viewing Package Profiles

A package profile is the list of installed packages on a system (regardless of its subscription status). Red Hat Subscription Manager maintains a local list of installed packages to track the subscription status of the system. The package profile contains some general information about each package in the list:
  • Package name
  • Package version
  • Epoch
  • Publisher
This package manifest is always visible locally in the My Installed Software tab of the UI or by using the list --installed command with the command-line tools.
The Subscription Manager daemon, rhsmcertd, checks the system periodically — once when it is first registered and then when it runs a refresh operation every four hours — to get the most current list of installed products. When the system is registered and then whenever there is a change to the package list, Subscription Manager sends an updated package profile to the subscription service.
The package profile is stored in a cache file in /var/lib/rhsm/packages/.
Having an updated package profile for a system helps the subscription service identify compatible subscriptions.

14.14.14. Retrieving the Consumer ID, Registration Tokens, and Other Information

Some pieces of information are used frequently when managing entitlements using the subscription-manager script. Information like the consumer ID or subscription pool ID is pulled up and referenced automatically in the Red Hat Subscription Manager UI, but it has to be entered manually in the command line.
Tabela 14.9, “Locations and Descriptions of Entitlement Data” lists common information that is used to manage subscriptions, the operations they're used in, and the places to find the data.
Tabela 14.9. Locations and Descriptions of Entitlement Data
Information Description Operations Used In Find It In ...
Consumer ID A unique identifier for each system that is registered to the subscription service. identity The simplest method is to use the identity command to return the current UUID.
[root@server1 ~]# subscription-manager identity
Current identity is: 63701087-f625-4519-8ab2-633bb50cb261
name: consumer-1.example.com
org name: 6340056
org id: 8a85f981302cbaf201302d89931e059a
The Subject CN element of the identity certificate for the system, /etc/pki/consumer/cert.pem. The UUID can also be returned by using openssl to pretty-print the certificate.
openssl x509 -text -in /etc/pki/consumer/cert.pem

Certificate:
... snip ...
Subject: CN=7d133d55 876f 4f47 83eb 0ee931cb0a97
Pool ID An identifier for a specific set of subscriptions. This set is created when subscriptions are purchased. Whenever a system needs to subscribe to a product, it references a pool ID to identify which purchased set of subscriptions to use. subscribe The PoolID value given for a product when listing available subscriptions. For example:
[root@server1 ~]# subscription-manager list --available
+----------------------+
Available Subscriptions
+----------------------+
ProductName: Red Hat Enterprise Linux, Standard (up to 2 sockets) 3 year
ProductId: MCT0346F3
PoolId: ff8080812bc382e3012bc3845ca000cb
Quantity: 2
Expires: 2011-02-28
Product certificate serial number The identification used for a specific, installed product. A certificate with a unique serial number is generated when a product is installed; this serial number is used to identify that specific product installation when managing subscriptions. unsubscribe The SerialNumber line in the product subscription information. This can be returned by running list --consumed.
[root@server1 ~]# subscription-manager list --consumed

+-----------------------------+
Consumed Product Subscriptions
+-----------------------------+

ProductName: High availability (cluster suite)
ContractNumber: 0
SerialNumber: 11287514358600162
....
Product ID The internal identifier used to identify a type of product. The ProductID value given for a product when listing available subscriptions. For example:
[root@server1 ~]# subscription-manager list --available
+----------------------+
Available Subscriptions
+----------------------+

ProductName: RHEL for Physical Servers
ProductId: MKT-rhel-server
... snip ...

14.15. About Certificates and Managing Entitlements

Part of managing subscriptions requires verifying the identity of everything involved, such as the system, the subscription service, and the available products. The subscription service uses X.509 certificates to handle the identity and authentication aspects of the subscription service. These X.509 certificates also contain the actual data about available subscriptions and installed products.
The first time a system is subscribed to a subscription, it downloads a certificate from the subscription service. The entitlement certificate contains all of the information about products that are available through that subscription. The entitlement certificate is revoked and reissued any time there is a change in the subscriptions for an organization. Once a product is actually installed on a machine, then another certificate is issued to manage the entitlements for the product on the system.
Each certificate issued and used by the Subscription Manager services is a .pem formatted file. This file format stores both keys and certificates in a base-64 blob. For example:
-----BEGIN CERTIFICATE-----
MIIDaTCCAtKgAwIBAgICBZYwDQYJKoZIhvcNAQEFBQAwSzEqMCgGA1UEAxMhY2Fu
ZGxlcGluMS5kZXZsYWIucGh4MS5yZWRoYXQuY29tMQswCQYDVQQGEwJVUzEQMA4G
A1UEBxMHUmFsZWlnaDAeFw0xMDEwMDYxNjMyMDVaFw0xMTEwMDYyMzU5NTlaMC8x
LTArBgNVBAMMJDQ4ODFiZDJmLTg2OGItNDM4Yy1hZjk2LThiMWQyODNkYWZmYzCC
ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKNyLw6+IMtjY03F7Otxj2GL
GTz5VKx1kfWY7q4OD4w+XlBHTkt+2tQV9S+4TFkUZ7XoI80LDL/BONpy/gq5c5cw
yKvjv2gjSS/pihgYNXc5zUOIfSj1vb3fHGHOkzdCcZMyWq1z0N/zaLClp/zP/pcM
og4NTAg2niNPjFYvkQ+oIl16WmQpefM0y0SY7N7oJd2T8dZjOiuLV2cVZLfwjrwG
9UpkT2J03g+n1ZA9q95ibLD5NVOdTy9+2lfRhdDViZaVoFiQXvg86qBHQ0ieENuF
a6bCvGgpTxcBuVXmsnl2+9dnMiwoDqPZp1HB6G2uNmyNe/IvkTOPFJ/ZVbtBTYUC
AwEAAaOB8zCB8DARBglghkgBhvhCAQEEBAMCBaAwCwYDVR0PBAQDAgSwMHsGA1Ud
IwR0MHKAFGiY1N2UtulxcMFy0j6gQGLTyo6CoU+kTTBLMSowKAYDVQQDEyFjYW5k
bGVwaW4xLmRldmxhYi5waHgxLnJlZGhhdC5jb20xCzAJBgNVBAYTAlVTMRAwDgYD
VQQHEwdSYWxlaWdoggkA1s54sVacN0EwHQYDVR0OBBYEFGbB5fqOzh32g4Wqrwhc
/96IupIgMBMGA1UdJQQMMAoGCCsGAQUFBwMCMB0GA1UdEQQWMBSkEjAQMQ4wDAYD
VQQDDAV4ZW9wczANBgkqhkiG9w0BAQUFAAOBgQANxHRsev4fYfnHO9kYcHo4UeK7
owN+fq92gl76iRHRnhzkPlhWL+uV2tyqGG9zJASOX+qEDOqN5sVAB4iNQTDGiUbK
z757igD2hsQ4ewv9Vq3QtnajWnfdaUZH919GgWs09Etg6ucsKwgfx1fqjSRLBbOo
lZuvBTYROOX6W2vKXw==
-----END CERTIFICATE-----
Tools like openssl or pk12util can be used to extract and view information from these certificates, in a pretty-print format. The product- and subscription-related information is extracted and viewable in the Red Hat Subscription Manager GUI or command-line tools.
This section describes the different certificates used by the subscription service and the entitlement information contained in those certificates. A much more detailed description of X.509 certificates and a public key infrastructure (PKI) is given in the Red Hat Certificate System documentation in chapter 1, "Introduction to Public-Key Cryptography," in the Red Hat Certificate System Deployment Guide.
Tabela 14.10. Types of Certificates Used for Content and Entitlements
Certificate Type Description Default Location
Consumer Identity Certificate Used to identify the system (consumer) to the subscription service. This contains a unique ID which is assigned to the system when it is registered to the system. The identity certificate itself is generated by the subscription service when the system is registered and then sent to the consumer. /etc/pki/consumer
Entitlement Certificate Contains a list of products that are available to a system to install, based on the subscriptions that the system has been subscribed to. The entitlement certificate defines the software products, the content delivery location, and validity dates. The presence of an entitlement certificate means that the system has consumed one of the quantities from the subscription. /etc/pki/entitlement
Product Certificate Contains the information about a product after it has been installed. /etc/pki/product/product_serial#.pem
CA Certificate A certificate for the certificate authority which issued the SSL server certificate used by the subscription service. This must be installed on a system for the system to use SSl to connect to the subscription service. /etc/rhsm/ca/candlepin-ca.pem
Satellite Certificate An XML-formatted certificate which contains a product list. This is used by local Satellite 5.x systems, not the newer subscription service.

14.15.1. The Structure of Identity Certificates

An identity certificate is a standard SSL client certificate. This certificate is issued by the subscription service when the system registers to it. The system consumer subsequently uses this certificate to authenticate to the subscription service whenever it contacts the service after registration.
The certificate contains three important pieces of information:
  • The consumer UUID, in the subject CN of the certificate
  • The subscription service which the system is registered to, in the issuer field of the certificate
  • The user account which registered the system, as the DirName value in the Subject Alt Name
The validity period of this certificate is associated with the time when the system was registered, not to any subscription contract periods or user account settings.
Exemplo 14.13. Identity Certificate
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 1430 (0x596)
        Signature Algorithm: sha1WithRSAEncryption
        Issuer: CN=entitlement.server.example.com, C=US, L=Raleigh  
        Validity
            Not Before: Oct  6 16:32:05 2010 GMT
            Not After : Oct  6 23:59:59 2011 GMT
        Subject: CN=4881bd2f-868b-438c-af96-8b1d283daffc  
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:a3:72:2f:0e:be:20:cb:63:63:4d:c5:ec:eb:71:
                    8f:61:8b:19:3c:f9:54:ac:75:91:f5:98:ee:ae:0e:
                    0f:8c:3e:5e:50:47:4e:4b:7e:da:d4:15:f5:2f:b8:
                    4c:59:14:67:b5:e8:23:cd:0b:0c:bf:c1:38:da:72:
                    fe:0a:b9:73:97:30:c8:ab:e3:bf:68:23:49:2f:e9:
                    8a:18:18:35:77:39:cd:43:88:7d:28:f5:bd:bd:df:
                    1c:61:ce:93:37:42:71:93:32:5a:ad:73:d0:df:f3:
                    68:b0:a5:a7:fc:cf:fe:97:0c:a2:0e:0d:4c:08:36:
                    9e:23:4f:8c:56:2f:91:0f:a8:22:5d:7a:5a:64:29:
                    79:f3:34:cb:44:98:ec:de:e8:25:dd:93:f1:d6:63:
                    3a:2b:8b:57:67:15:64:b7:f0:8e:bc:06:f5:4a:64:
                    4f:62:74:de:0f:a7:d5:90:3d:ab:de:62:6c:b0:f9:
                    35:53:9d:4f:2f:7e:da:57:d1:85:d0:d5:89:96:95:
                    a0:58:90:5e:f8:3c:ea:a0:47:43:48:9e:10:db:85:
                    6b:a6:c2:bc:68:29:4f:17:01:b9:55:e6:b2:79:76:
                    fb:d7:67:32:2c:28:0e:a3:d9:a7:51:c1:e8:6d:ae:
                    36:6c:8d:7b:f2:2f:91:33:8f:14:9f:d9:55:bb:41:
                    4d:85
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            Netscape Cert Type:
                SSL Client, S/MIME
            X509v3 Key Usage:
                Digital Signature, Key Encipherment, Data Encipherment
            X509v3 Authority Key Identifier:
                keyid:68:98:D4:DD:94:B6:E9:71:70:C1:72:D2:3E:A0:40:62:D3:CA:8E:82
                DirName:/CN=entitlement.server.example.com/C=US/L=Raleigh
                serial:D6:CE:78:B1:56:9C:37:41

            X509v3 Subject Key Identifier:
                66:C1:E5:FA:8E:CE:1D:F6:83:85:AA:AF:08:5C:FF:DE:88:BA:92:20
            X509v3 Extended Key Usage:
                TLS Web Client Authentication
            X509v3 Subject Alternative Name:  
                DirName:/CN=admin-example  
    Signature Algorithm: sha1WithRSAEncryption
        0d:c4:74:6c:7a:fe:1f:61:f9:c7:3b:d9:18:70:7a:38:51:e2:
        bb:a3:03:7e:7e:af:76:82:5e:fa:89:11:d1:9e:1c:e4:3e:58:
        56:2f:eb:95:da:dc:aa:18:6f:73:24:04:8e:5f:ea:84:0c:ea:
        8d:e6:c5:40:07:88:8d:41:30:c6:89:46:ca:cf:be:7b:8a:00:
        f6:86:c4:38:7b:0b:fd:56:ad:d0:b6:76:a3:5a:77:dd:69:46:
        47:f7:5f:46:81:6b:34:f4:4b:60:ea:e7:2c:2b:08:1f:c7:57:
        ea:8d:24:4b:05:b3:a8:95:9b:af:05:36:11:38:e5:fa:5b:6b:
        ca:5f

14.15.2. The Structure of Entitlement Certificates

An entitlement is analogous to an assigned software license. Entitlement certificates contain a list of available products for a system — software that the system has been granted rights to download and update. When a system is subscribed to a subscription pool, the system pulls down the entitlement certificate from the subscription service, which contains all of the information about available products.
An entitlement certificate contains a list of every potential product from every potential content source. The structure of the entitlement certificate, then, allows multiple namespaces, each, for products, content servers, roles, orders, and systems. An entitlement certificate also contains complete information about the subscribed pool, even for products which may not be compatible with the specific system. In an entitlement certificate, the architecture and version definitions contain all of the allowed architectures and versions.

Note

The local Subscription Manager polls the subscription service routinely (every four hours by default) to check for changes in the entitlements. When a subscription is changed in some way, then the original entitlement certificate is revoked and is replaced with a new entitlement certificate.
The entitlement certificate is a *.pem file stored in the entitlement certificates directory, /etc/pki/entitlement. The name of the *.pem file is a generated numeric identifier that is generated by the subscription service. This ID is an inventory number that is used to associate a subscription quantity with the system in the software inventory.
The heading of the certificate contains the name of the subscription service which issued it, the validity period of the certificate (which is tied to the installation date of the product), and then the serial number of the installation of the product.
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            3c:da:6c:06:90:7f:ff
        Signature Algorithm: sha1WithRSAEncryption
        Issuer: CN=candlepin1.devlab.phx1.redhat.com, C=US, L=Raleigh
        Validity
            Not Before: Oct  8 17:55:28 2010 GMT
            Not After : Oct  2 23:59:59 2011 GMT
        Subject: CN=8a878c912b875189012b8cfbc3f2264a
... [snip] ...
The key definition of the product is given in custom certificate extensions that are appended to the certificate. Each namespace defines certain information about a product, including its name, content servers which can deliver it, the format of delivery, and a GPG key to identify the release. Every individual entry is identified by a numeric object identifier (OID) with the same basic format:
1.3.6.1.4.1.2312.9.2.product_#.config_#:
   ..config_value
The 2 indicates that it is a product entry. product_# is a unique ID which identifies the specific product or variant. config_# relates to the installation information for that product, like its content server or the quantity available.

Note

Every entitlements-related extension begins with the OID base 1.3.6.1.4.1.2312.9. The subsequent numbers identify different subscription areas:
  • .2. is the product-specific information
  • .1. is the subscription information
  • .4. contains the contract information, like its ID number and start and end dates
  • .5. contains the consumer information, like the consumer ID which installed a product
A product definition contains a series of entries which configure all of the information required to identify and install the product. Each type of information has its own ID, the config_# in the OID, that is used consistently for all products. An example product is listed in Exemplo 14.14, “Annotated Red Hat Enterprise Linux High Availability Product Extensions in an Entitlement Certificate”.
Exemplo 14.14. Annotated Red Hat Enterprise Linux High Availability Product Extensions in an Entitlement Certificate
            content repository type  
            1.3.6.1.4.1.2312.9.2.30393.1:
                ..yum
            product  
            1.3.6.1.4.1.2312.9.2.30393.1.1:
                .HRed Hat Enterprise Linux High Availability (for RHEL Entitlement) (RPMs)
            channel name  
            1.3.6.1.4.1.2312.9.2.30393.1.2:
                .Dred-hat-enterprise-linux-high-availability-for-rhel-entitlement-rpms
            vendor  
            1.3.6.1.4.1.2312.9.2.30393.1.5:
                ..Red Hat
            download URL  
            1.3.6.1.4.1.2312.9.2.30393.1.6:
                .Q/content/dist/rhel/entitlement/releases/$releasever/$basearch/highavailability/os
            key download URL  
            1.3.6.1.4.1.2312.9.2.30393.1.7:
                .2file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
            flex quantity  
            1.3.6.1.4.1.2312.9.2.30393.1.4:
                ..0
            quantity  
            1.3.6.1.4.1.2312.9.2.30393.1.3:
                ..25
            repo enabled setting  
            1.3.6.1.4.1.2312.9.2.30393.1.8:
                ..1

14.15.3. The Structure of Product Certificates

The products that are installed on a system through the subscriptions assigned to a system are identified by X.509 certificates. When an available product is installed, the subscription service generates a product certificate, which contains the information about the product contract and the specific installation.
Structurally, entitlement certificates and product certificates are very similar, because they both provide much of the same information about products. The main difference is that a product certificate contains information about a single product that has been installed, so no other subscription information (like other available products or other product versions) is included in a product certificate the way that it is in an entitlement certificate.
A product certificate contains a single product namespace (meaning, a single product definition) which shows only what is actually installed on the system. The architecture and version definitions in a product certificate reflect the architecture and version of the product that is actually installed.
The product certificate is a *.pem file stored in the entitlement certificates directory, /etc/pki/product/product_serial#.pem. The name of the *.pem file is a generated numeric identifier that is generated by the subscription service. As with entitlement tracking, the generated ID is an inventory number, used to track installed products and associate them with systems within the subscription service.

14.15.4. Anatomy of Satellite Certificates

Important

Satellite certificates are used by Satellite 5.x deployments. They are not used on Red Hat Enterprise Linux 5.7 or by the subscription service.
Every system has to have a secure, authoritative way to identify what subscriptions are available. For Satellite 5.x systems, this identification is done through a digitally-signed XML document that lists the products and quantities that a customer has purchased.
As with entitlement certificates, a Satellite certificate contains the information about the subscription that was purchased, including the total number of systems that can be registered against that subscription and its start and end dates.
There are two types of subscriptions:
  • System entitlements are subscriptions for services that can be performed, such as monitoring, provisioning, and virtualization.
  • Channel entitlements, or content entitlements, provide access to the different software product download channels on Red Hat Network. These include Red Hat Enterprise Linux add-ons like Supplementary and FastTrack and layered products like Red Hat Directory Server.
Both types can be included in a single Satellite certificate.
A system entitlement and the metadata for an entitlement are both configured similarly in the certificate:
<rhn-cert-field name="configuration_area">value</rhn-cert-field>
The name argument identifies what entity is being configured. This can be the organization which ordered the subscription (name="owner"), the start and end dates for the entitlement (name="issued" and name="expires"), or the entitlement itself. A system entitlement uses the name argument to set the service being entitled; every content entitlement is set as a name="channel-family" type, with the specific product identified in an additional family argument.
The first section of the Satellite certificate is the metadata. The metadata identifies the organization which purchased it and the start and end dates of the entitlement. The field being set is in the name argument, while the value is between the tags. The last lines of the certificate also set metadata for the subscription, including the version of the Satellite and the signature that signs the XML document (and allows the XML file to be used as a certificate).
  <rhn-cert-field name="product">RHN-SATELLITE-001</rhn-cert-field>
  <rhn-cert-field name="owner">Example Corp</rhn-cert-field>
  <rhn-cert-field name="issued">2009-04-07 10:18:33</rhn-cert-field>
  <rhn-cert-field name="expires">2009-11-25 00:00:00</rhn-cert-field>

... [snip] ...

  <rhn-cert-field name="satellite-version">5.3</rhn-cert-field>
  <rhn-cert-field name="generation">2</rhn-cert-field>
  <rhn-cert-signature>
-----BEGIN PGP SIGNATURE-----
Version: Crypt::OpenPGP 1.03

iQBGBAARAwAGBQJJ22C+AAoJEJ5ynaAAAAkyyZ0An18+4hK5Ozt4HWieFvahsTnF
aPcaAJ0e5neOfdDZRLOgDE+Tp/Im3Hc3Rg==
=gqP7
-----END PGP SIGNATURE-----
</rhn-cert-signature>
The name="slot" field lists how many total systems are allowed to use this Satellite certificate to receive content. It is a global quantity.
  <rhn-cert-field name="slots">119</rhn-cert-field>
The system entitlements are set by identifying the service type in the name argument and then setting the quantity as the value within the tags.
  <rhn-cert-field name="provisioning-slots">117</rhn-cert-field>
  <rhn-cert-field name="monitoring-slots">20</rhn-cert-field>
  <rhn-cert-field name="virtualization_host">67</rhn-cert-field>
The content entitlements can include any combination of products, including base Red Hat Enterprise Linux subscriptions, variations of Red Hat Enterprise Linux, Red Hat Enterprise Linux add-ons, and general software products. General Red Hat Enterprise Linux server subscriptions are listed in the rhel-server family, while a specific Virtualization Server subscription provides an additional rhel-server-vt family..
  <rhn-cert-field name="channel-families" quantity="95" family="rhel-server"/>
  <rhn-cert-field name="channel-families" quantity="67" family="rhel-server-vt"/>
Add-ons and products for Red Hat Enterprise Linux systems (but not necessarily operating system products) are also in a rhel-* family, because that refers to the platform the product is supported on. In this example, Red Hat Directory Server is in the rhel-rhdirserv family.
  <rhn-cert-field name="channel-families" quantity="3" family="rhel-rhdirserv"/>
Most subscriptions will also include a subscription tool set to manage and enable within clients features such as provisioning or configuration management when registered to RHN Classic or Satellite 5.x.
  <rhn-cert-field name="channel-families" quantity="212" family="rhn-tools"/>

Parte IV. Configuração de Sistema

Parte do trabalho do administrador de sistema é configurar o sistema para diversas tarefas, tipo de usuários e configurações de hardware. Esta seção explica como configurar o sistema do Red Hat Enterprise Linux.

Índice

29. Acesso ao Console
29.1. Disabling Shutdown Via Ctrl+Alt+Del
29.2. Desabilitando Acesso a Programas do Console
29.3. Definindo o Console
29.4. Tornando Arquivos Acessíveis Pelo Console
29.5. Habilitando o Acesso a Outras Aplicações pelo Console
29.6. The floppy Group
30. The sysconfig Directory
30.1. Files in the /etc/sysconfig/ Directory
30.1.1. /etc/sysconfig/amd
30.1.2. /etc/sysconfig/apmd
30.1.3. /etc/sysconfig/arpwatch
30.1.4. /etc/sysconfig/authconfig
30.1.5. /etc/sysconfig/autofs
30.1.6. /etc/sysconfig/clock
30.1.7. /etc/sysconfig/desktop
30.1.8. /etc/sysconfig/dhcpd
30.1.9. /etc/sysconfig/exim
30.1.10. /etc/sysconfig/firstboot
30.1.11. /etc/sysconfig/gpm
30.1.12. /etc/sysconfig/hwconf
30.1.13. /etc/sysconfig/i18n
30.1.14. /etc/sysconfig/init
30.1.15. /etc/sysconfig/ip6tables-config
30.1.16. /etc/sysconfig/iptables-config
30.1.17. /etc/sysconfig/irda
30.1.18. /etc/sysconfig/keyboard
30.1.19. /etc/sysconfig/kudzu
30.1.20. /etc/sysconfig/named
30.1.21. /etc/sysconfig/network
30.1.22. /etc/sysconfig/nfs
30.1.23. /etc/sysconfig/ntpd
30.1.24. /etc/sysconfig/radvd
30.1.25. /etc/sysconfig/samba
30.1.26. /etc/sysconfig/selinux
30.1.27. /etc/sysconfig/sendmail
30.1.28. /etc/sysconfig/spamassassin
30.1.29. /etc/sysconfig/squid
30.1.30. /etc/sysconfig/system-config-securitylevel
30.1.31. /etc/sysconfig/system-config-selinux
30.1.32. /etc/sysconfig/system-config-users
30.1.33. /etc/sysconfig/system-logviewer
30.1.34. /etc/sysconfig/tux
30.1.35. /etc/sysconfig/vncservers
30.1.36. /etc/sysconfig/xinetd
30.2. Directories in the /etc/sysconfig/ Directory
30.3. Recursos Adicionais
30.3.1. Documentação Instalada
31. Configuração de Data e Hora
31.1. Time and Date Properties
31.2. Propriedades do Protocolo de Horário de Rede (Network Time Protocol - NTP)
31.3. Configuração do Fuso Horário
32. Configuração do Teclado
33. O Sistema X Window
33.1. O Lançamento X11R7.1
33.2. Ambientes de Desktop e Gestores de Window
33.2.1. Ambientes de Desktop
33.2.2. Gestores de Janelas
33.3. Arquivos de Configuração de Servidor X
33.3.1. xorg.conf
33.4. Fontes
33.4.1. Fontconfig
33.4.2. Sistema de Fonte Central X
33.5. Níveis de Execução e X
33.5.1. Nível de Execução 3
33.5.2. Nível de Execução 5
33.6. Recursos Adicionais
33.6.1. Documentação Instalada
33.6.2. Sites Úteis
34. Configuração do Sistema X Window
34.1. Display Settings
34.2. Display Hardware Settings
34.3. Dual Head Display Settings
35. Usuários e Grupos
35.1. Configuração de Usuário e Grupo
35.1.1. Adicionando um Novo Usuário
35.1.2. Modificando Propriedades do Usuário
35.1.3. Adicionando um Novo Grupo
35.1.4. Modificando Propriedades de Grupo
35.2. Gerenciamento de Ferramentas de Usuário e Grupo
35.2.1. Configuração da Linha de Comando
35.2.2. Adicionando um Usuário
35.2.3. Adicionando um Grupo
35.2.4. Vencimento de Senhas
35.2.5. Explicando o Processo
35.3. Usuários Padrão
35.4. Grupos Padrão
35.5. Brupos Privados de Usuários
35.5.1. Diretórios de Grupo
35.6. Senhas Shadow
35.7. Recursos Adicionais
35.7.1. Documentação Instalada
36. Configuração da Impressora
36.1. Adicionando uma Impressora Local.
36.2. Adicionando uma Impressora IPP
36.3. Adicionando uma Impressora Samba (SMB)
36.4. Adding a JetDirect Printer
36.5. Selecionando o Modelo da Impressora e Finalizando
36.5.1. Confirmando a Configuração da Impressora
36.6. Imprimindo uma Página de Teste
36.7. Modificando Impressoras Existentes
36.7.1. A Aba Configurações
36.7.2. A Aba Políticas
36.7.3. A Aba Controle de Acesso
36.7.4. A Aba Impressora e a Aba Opções de Trabalho
36.8. Gerenciando Tarefas de Impressão
36.9. Recursos Adicionais
36.9.1. Documentação Instalada
36.9.2. Sites Úteis
37. Automated Tasks
37.1. Cron
37.1.1. Configurando Tarefas no Cron
37.1.2. Controlando Acesso ao Cron
37.1.3. Iniciando e Parando o Serviço
37.2. At e Batch
37.2.1. Configurando Trabalhos com At
37.2.2. Configurando Trabalhos com o Batch
37.2.3. Visualizando Trabalhos Pendentes
37.2.4. Opções Adicionais de Linha de Comando
37.2.5. Controlando o Acesso a At e Batch
37.2.6. Iniciando e Parando o Serviço
37.3. Recursos Adicionais
37.3.1. Documentação Instalada
38. Arquivos de Registro
38.1. Localizando Arquivos de Registro
38.2. Visualizando Arquivos de Registro
38.3. Adding a Log File
38.4. Localizando Arquivos de Registro

Capítulo 29. Acesso ao Console

Quando usuários normais (não root) se autenticam localmente em um computador, lhes são dados dois tipos de permissões especiais:
  1. Eles podem rodar determinados programas que, caso contrário, não poderiam rodar
  2. Eles podem acessar determinados arquivos (geralmente, arquivos de dispositivos especiais usados para acessar disquetes, CD-ROMs e assim por diante) que, caso contrário, não poderiam acessar.
Como há consoles múltiplos em um único computador e múltiplos usuários podem se autenticar (logar) ao computador localmente ao mesmo tempo, um dos usuários deve ganhar a corrida de acesso aos arquivos. O primeiro usuário a se autenticar no console possui estes arquivos. Uma vez que o primeiro usuário faz log out, o próximo usuário a se autenticar é que possui os arquivos.
In contrast, every user who logs in at the console is allowed to run programs that accomplish tasks normally restricted to the root user. If X is running, these actions can be included as menu items in a graphical user interface. As shipped, these console-accessible programs include halt, poweroff, and reboot.

29.1. Disabling Shutdown Via Ctrl+Alt+Del

By default, /etc/inittab specifies that your system is set to shutdown and reboot in response to a Ctrl+Alt+Del key combination used at the console. To completely disable this ability, comment out the following line in /etc/inittab by putting a hash mark (#) in front of it:
ca::ctrlaltdel:/sbin/shutdown -t3 -r now
Alternatively, you may want to allow certain non-root users the right to shutdown or reboot the system from the console using Ctrl+Alt+Del . You can restrict this privilege to certain users, by taking the following steps:
  1. Add the -a option to the /etc/inittab line shown above, so that it reads:
    ca::ctrlaltdel:/sbin/shutdown -a -t3 -r now
    The -a flag tells shutdown to look for the /etc/shutdown.allow file.
  2. Create a file named shutdown.allow in /etc. The shutdown.allow file should list the usernames of any users who are allowed to shutdown the system using Ctrl+Alt+Del . The format of the shutdown.allow file is a list of usernames, one per line, like the following:
    stephen
    jack
    sophie
According to this example shutdown.allow file, the users stephen, jack, and sophie are allowed to shutdown the system from the console using Ctrl+Alt+Del . When that key combination is used, the shutdown -a command in /etc/inittab checks to see if any of the users in /etc/shutdown.allow (or root) are logged in on a virtual console. If one of them is, the shutdown of the system continues; if not, an error message is written to the system console instead.
For more information on shutdown.allow, refer to the shutdown man page.

29.2. Desabilitando Acesso a Programas do Console

Para desabilitar o acesso de usuários a programas do console, execute o seguinte comando como root:
rm -f /etc/security/console.apps/*
In environments where the console is otherwise secured (BIOS and boot loader passwords are set, Ctrl+Alt+Delete is disabled, the power and reset switches are disabled, and so forth), you may not want to allow any user at the console to run poweroff, halt, and reboot, which are accessible from the console by default.
Para remover estas funções, execute os seguintes comandos como root:
rm -f /etc/security/console.apps/poweroff
rm -f /etc/security/console.apps/halt
rm -f /etc/security/console.apps/reboot

29.3. Definindo o Console

The pam_console.so module uses the /etc/security/console.perms file to determine the permissions for users at the system console. The syntax of the file is very flexible; you can edit the file so that these instructions no longer apply. However, the default file has a line that looks like this:
<console>=tty[0-9][0-9]* vc/[0-9][0-9]* :[0-9]\.[0-9] :[0-9]
When users log in, they are attached to some sort of named terminal, which can be either an X server with a name like :0 or mymachine.example.com:1.0, or a device like /dev/ttyS0 or /dev/pts/2. The default is to define that local virtual consoles and local X servers are considered local, but if you want to consider the serial terminal next to you on port /dev/ttyS1 to also be local, you can change that line to read:
<console>=tty[0-9][0-9]* vc/[0-9][0-9]* :[0-9]\.[0-9] :[0-9] /dev/ttyS1

29.4. Tornando Arquivos Acessíveis Pelo Console

As configurações padrão para definições de classes e permissões de dispositivos individuais, são definidos em /etc/security/console.perms.d/50-default.perms. Para editar permissões de arquivo e dispositivos, recomenda-se criar um novo arquivo padrão em /etc/security/console.perms.d/ contendo suas configurações de preferência para um conjunto específico de arquivos ou dipositivos. O nome de um arquivo novo padrão deve iniciar com um número mais alto do que 50 (por exemplo, 51-default.perms) para que sobrescreva o 50-default.perms.
Para fazer isto, crie um novo arquivo chamado 51-default.perms no/etc/security/console.perms.d/:
touch /etc/security/console.perms.d/51-default.perms
Abra o arquivo padrão original perms, 50-default.perms. A primeira seção define classes de dispositivos, com linhas semelhantes às seguintes:
<floppy>=/dev/fd[0-1]* \
          /dev/floppy/* /mnt/floppy*
<sound>=/dev/dsp* /dev/audio* /dev/midi* \ 
	  /dev/mixer* /dev/sequencer \ 
	  /dev/sound/* /dev/beep \ 
	  /dev/snd/*
<cdrom>=/dev/cdrom* /dev/cdroms/* /dev/cdwriter* /mnt/cdrom*
Os ítens anexados em parênteses, nomeiam o dipositivo, no exemplo acima, <cdrom> se refere ao drive de CD-ROM. Para adicionar um novo dispositivo, não o defina no arquivo padrão 50-default.perms, ao invés de definí-lo em 51-default.perms. Por exemplo, para definir um scanner, adicione a seguinte linha ao 51-default.perms:
<scanner>=/dev/scanner /dev/usb/scanner*
Of course, you must use the appropriate name for the device. Ensure that /dev/scanner is really your scanner and not some other device, such as your hard drive.
Quando já houver definido um dispositivo ou arquivo, o segundo passo é especificar suas definições de permissão.O segundo é definir o que é feito com estes arquivos. Procure na última seção do /etc/security/console.perms por linhas similares a:
<console> 0660 <floppy> 0660 root.floppy
<console> 0600 <sound>  0640 root
<console> 0600 <cdrom>  0600 root.disk
Para definir as permissões para um scanner, adicione uma linha semelhante a esta a seguir, em 51-default.perms:
<console> 0600 <scanner> 0600 root
Then, when you log in at the console, you are given ownership of the /dev/scanner device with the permissions of 0600 (readable and writable by you only). When you log out, the device is owned by root, and still has the permissions 0600 (now readable and writable by root only).

Aviso

Você nunca deve editar o arquivo padrão 50-default.perms. Para editar permissões para um dispositivo já definido em 50-default.perms, adicione a definição da permissão desejada para aquele dispositivo em 51-default.perms. Isto irá sobrescrever quais permissões são definidas em 50-default.perms.

29.5. Habilitando o Acesso a Outras Aplicações pelo Console

Para tornar outras aplicações acessíveis a usuários do console, é necessário um pouco mais de trabalho.
First of all, console access only works for applications which reside in /sbin/ or /usr/sbin/, so the application that you wish to run must be there. After verifying that, perform the following steps:
  1. Create a link from the name of your application, such as our sample foo program, to the /usr/bin/consolehelper application:
    cd /usr/bin
    ln -s consolehelper foo
  2. Create the file /etc/security/console.apps/foo:
    touch /etc/security/console.apps/foo
  3. Create a PAM configuration file for the foo service in /etc/pam.d/. An easy way to do this is to copy the PAM configuration file of the halt service, and then modify the copy if you want to change the behavior:
    cp /etc/pam.d/halt /etc/pam.d/foo
Now, when /usr/bin/foo is executed, consolehelper is called, which authenticates the user with the help of /usr/sbin/userhelper. To authenticate the user, consolehelper asks for the user's password if /etc/pam.d/foo is a copy of /etc/pam.d/halt (otherwise, it does precisely what is specified in /etc/pam.d/foo) and then runs /usr/sbin/foo with root permissions.
In the PAM configuration file, an application can be configured to use the pam_timestamp module to remember (or cache) a successful authentication attempt. When an application is started and proper authentication is provided (the root password), a timestamp file is created. By default, a successful authentication is cached for five minutes. During this time, any other application that is configured to use pam_timestamp and run from the same session is automatically authenticated for the user — the user does not have to enter the root password again.
This module is included in the pam package. To enable this feature, add the following lines to your PAM configuration file in etc/pam.d/:
auth            include         config-util
account         include         config-util
session         include         config-util
These lines can be copied from any of the /etc/pam.d/system-config-* configuration files. Note that these lines must be added below any other auth sufficient session optional lines in your PAM configuration file.
If an application configured to use pam_timestamp is successfully authenticated from the Applications (the main menu on the panel), the icon is displayed in the notification area of the panel if you are running the GNOME or KDE desktop environment. After the authentication expires (the default is five minutes), the icon disappears.
O usuário pode optar por esquecer a autenticação gravada no cache. Basta clicar no ícone e selecionar a opção para esquecer a autenticação.

29.6. The floppy Group

If, for whatever reason, console access is not appropriate for you and your non-root users require access to your system's diskette drive, this can be done using the floppy group. Add the user(s) to the floppy group using the tool of your choice. For example, the gpasswd command can be used to add user fred to the floppy group:
gpasswd -a fred floppy
Agora o usuário fred pode acessar o drive de disquete do sistema pelo console.

Capítulo 30. The sysconfig Directory

The /etc/sysconfig/ directory contains a variety of system configuration files for Red Hat Enterprise Linux.
This chapter outlines some of the files found in the /etc/sysconfig/ directory, their function, and their contents. The information in this chapter is not intended to be complete, as many of these files have a variety of options that are only used in very specific or rare circumstances.

30.1. Files in the /etc/sysconfig/ Directory

The following sections offer descriptions of files normally found in the /etc/sysconfig/ directory. Files not listed here, as well as extra file options, are found in the /usr/share/doc/initscripts-<version-number>/sysconfig.txt file (replace <version-number> with the version of the initscripts package). Alternatively, looking through the initscripts in the /etc/rc.d/ directory can prove helpful.

Nota

If some of the files listed here are not present in the /etc/sysconfig/ directory, then the corresponding program may not be installed.

30.1.1. /etc/sysconfig/amd

The /etc/sysconfig/amd file contains various parameters used by amd; these parameters allow for the automatic mounting and unmounting of file systems.

30.1.2. /etc/sysconfig/apmd

The /etc/sysconfig/apmd file is used by apmd to configure what power settings to start/stop/change on suspend or resume. This file configures how apmd functions at boot time, depending on whether the hardware supports Advanced Power Management (APM) or whether the user has configured the system to use it. The apm daemon is a monitoring program that works with power management code within the Linux kernel. It is capable of alerting users to low battery power on laptops and other power-related settings.

30.1.3. /etc/sysconfig/arpwatch

The /etc/sysconfig/arpwatch file is used to pass arguments to the arpwatch daemon at boot time. The arpwatch daemon maintains a table of Ethernet MAC addresses and their IP address pairings. By default, this file sets the owner of the arpwatch process to the user pcap and sends any messages to the root mail queue. For more information regarding available parameters for this file, refer to the arpwatch man page.

30.1.4. /etc/sysconfig/authconfig

The /etc/sysconfig/authconfig file sets the authorization to be used on the host. It contains one or more of the following lines:
  • USEMD5=<value>, where <value> is one of the following:
    • yes — MD5 is used for authentication.
    • no — MD5 is not used for authentication.
  • USEKERBEROS=<value>, where <value> is one of the following:
    • yes — Kerberos is used for authentication.
    • no — Kerberos is not used for authentication.
  • USELDAPAUTH=<value>, where <value> is one of the following:
    • yes — LDAP is used for authentication.
    • no — LDAP is not used for authentication.

30.1.5. /etc/sysconfig/autofs

The /etc/sysconfig/autofs file defines custom options for the automatic mounting of devices. This file controls the operation of the automount daemons, which automatically mount file systems when you use them and unmount them after a period of inactivity. File systems can include network file systems, CD-ROMs, diskettes, and other media.
The /etc/sysconfig/autofs file may contain the following:
  • LOCALOPTIONS="<value>", where <value> is a string for defining machine-specific automount rules. The default value is an empty string ("").
  • DAEMONOPTIONS="<value>", where <value> is the timeout length in seconds before unmounting the device. The default value is 60 seconds ("--timeout=60").
  • UNDERSCORETODOT=<value>, where <value> is a binary value that controls whether to convert underscores in file names into dots. For example, auto_home to auto.home and auto_mnt to auto.mnt. The default value is 1 (true).
  • DISABLE_DIRECT=<value>, where <value> is a binary value that controls whether to disable direct mount support, as the Linux implementation does not conform to the Sun Microsystems' automounter behavior. The default value is 1 (true), and allows for compatibility with the Sun automounter options specification syntax.

30.1.6. /etc/sysconfig/clock

The /etc/sysconfig/clock file controls the interpretation of values read from the system hardware clock.
Os valores corretos são:
  • UTC=<value>, where <value> is one of the following boolean values:
    • true or yes — The hardware clock is set to Universal Time.
    • false or no — The hardware clock is set to local time.
  • ARC=<value>, where <value> is the following:
    • false or no — This value indicates that the normal UNIX epoch is in use. Other values are used by systems not supported by Red Hat Enterprise Linux.
  • SRM=<value>, where <value> is the following:
    • false or no — This value indicates that the normal UNIX epoch is in use. Other values are used by systems not supported by Red Hat Enterprise Linux.
  • ZONE=<filename> — The time zone file under /usr/share/zoneinfo that /etc/localtime is a copy of. The file contains information such as:
    ZONE="America/New York"
    Observe que o parâmetro ZONE é lido pelo Time and Date Properties Tool (system-config-date), e editando manualmente ele não muda o sistema de fuso horário.
Lançamentos recentes do Red Hat Enterprise Linux usaram os seguintes valores (que são substituídas):
  • CLOCKMODE=<value>, where <value> is one of the following:
    • GMT — The clock is set to Universal Time (Greenwich Mean Time).
    • ARC — The ARC console's 42-year time offset is in effect (for Alpha-based systems only).

30.1.7. /etc/sysconfig/desktop

The /etc/sysconfig/desktop file specifies the desktop for new users and the display manager to run when entering runlevel 5.
Os valores corretos são:
  • DESKTOP="<value>", where "<value>" is one of the following:
    • GNOME — Selects the GNOME desktop environment.
    • KDE — Selects the KDE desktop environment.
  • DISPLAYMANAGER="<value>", where "<value>" is one of the following:
    • GNOME — Selects the GNOME Display Manager.
    • KDE — Selects the KDE Display Manager.
    • XDM — Selects the X Display Manager.
For more information, refer to Capítulo 33, O Sistema X Window.

30.1.8. /etc/sysconfig/dhcpd

The /etc/sysconfig/dhcpd file is used to pass arguments to the dhcpd daemon at boot time. The dhcpd daemon implements the Dynamic Host Configuration Protocol (DHCP) and the Internet Bootstrap Protocol (BOOTP). DHCP and BOOTP assign hostnames to machines on the network. For more information about what parameters are available in this file, refer to the dhcpd man page.

30.1.9. /etc/sysconfig/exim

The /etc/sysconfig/exim file allows messages to be sent to one or more clients, routing the messages over whatever networks are necessary. The file sets the default values for exim to run. Its default values are set to run as a background daemon and to check its queue each hour in case something has backed up.
Os valores incluem:
  • DAEMON=<value>, where <value> is one of the following:
    • yesexim should be configured to listen to port 25 for incoming mail. yes implies the use of the Exim's -bd options.
    • noexim should not be configured to listen to port 25 for incoming mail.
  • QUEUE=1h which is given to exim as -q$QUEUE. The -q option is not given to exim if /etc/sysconfig/exim exists and QUEUE is empty or undefined.

30.1.10. /etc/sysconfig/firstboot

The first time the system boots, the /sbin/init program calls the etc/rc.d/init.d/firstboot script, which in turn launches the Setup Agent. This application allows the user to install the latest updates as well as additional applications and documentation.
The /etc/sysconfig/firstboot file tells the Setup Agent application not to run on subsequent reboots. To run it the next time the system boots, remove /etc/sysconfig/firstboot and execute chkconfig --level 5 firstboot on.

30.1.11. /etc/sysconfig/gpm

The /etc/sysconfig/gpm file is used to pass arguments to the gpm daemon at boot time. The gpm daemon is the mouse server which allows mouse acceleration and middle-click pasting. For more information about what parameters are available for this file, refer to the gpm man page. By default, the DEVICE directive is set to /dev/input/mice.

30.1.12. /etc/sysconfig/hwconf

The /etc/sysconfig/hwconf file lists all the hardware that kudzu detected on the system, as well as the drivers used, vendor ID, and device ID information. The kudzu program detects and configures new and/or changed hardware on a system. The /etc/sysconfig/hwconf file is not meant to be manually edited. If edited, devices could suddenly show up as being added or removed.

30.1.13. /etc/sysconfig/i18n

The /etc/sysconfig/i18n file sets the default language, any supported languages, and the default system font. For example:
LANG="en_US.UTF-8"
SUPPORTED="en_US.UTF-8:en_US:en"
SYSFONT="latarcyrheb-sun16"

30.1.14. /etc/sysconfig/init

The /etc/sysconfig/init file controls how the system appears and functions during the boot process.
Os seguintes valores podem ser usados:
  • BOOTUP=<value>, where <value> is one of the following:
    • color — The standard color boot display, where the success or failure of devices and services starting up is shown in different colors.
    • verbose — An old style display which provides more information than purely a message of success or failure.
    • Qualquer outra coisa, significa um novo vídeo, mas sem a formatação ANSI
  • RES_COL=<value>, where <value> is the number of the column of the screen to start status labels. The default is set to 60.
  • MOVE_TO_COL=<value>, where <value> moves the cursor to the value in the RES_COL line via the echo -en command.
  • SETCOLOR_SUCCESS=<value>, where <value> sets the success color via the echo -en command. The default color is set to green.
  • SETCOLOR_FAILURE=<value>, where <value> sets the failure color via the echo -en command. The default color is set to red.
  • SETCOLOR_WARNING=<value>, where <value> sets the warning color via the echo -en command. The default color is set to yellow.
  • SETCOLOR_NORMAL=<value>, where <value> resets the color to "normal" via the echo -en.
  • LOGLEVEL=<value>, where <value> sets the initial console logging level for the kernel. The default is 3; 8 means everything (including debugging), while 1 means only kernel panics. The syslogd daemon overrides this setting once started.
  • PROMPT=<value>, where <value> is one of the following boolean values:
    • yes — Enables the key check for interactive mode.
    • no — Disables the key check for interactive mode.

30.1.15. /etc/sysconfig/ip6tables-config

The /etc/sysconfig/ip6tables-config file stores information used by the kernel to set up IPv6 packet filtering at boot time or whenever the ip6tables service is started.
Do not modify this file by hand unless familiar with how to construct ip6tables rules. Rules also can be created manually using the /sbin/ip6tables command. Once created, add the rules to the /etc/sysconfig/ip6tables file by typing the following command:
service ip6tables save
Uma vez criado este arquivo, quaisquer regras firewall, salvas nele, persiste através de uma reinicialização de sistema ou de serviço.
For more information on ip6tables, refer to Seção 46.9, “IPTables”.

30.1.16. /etc/sysconfig/iptables-config

The /etc/sysconfig/iptables-config file stores information used by the kernel to set up packet filtering services at boot time or whenever the service is started.
Do not modify this file by hand unless you are familiar with constructing iptables rules. The easiest way to add rules is to use the Security Level Configuration Tool (system-config-securitylevel) application to create a firewall. These applications automatically edit this file at the end of the process.
Rules can also be created manually using the /sbin/iptables command. Once created, add the rule(s) to the /etc/sysconfig/iptables file by typing the following command:
service iptables save
Uma vez criado este arquivo, quaisquer regras firewall, salvas nele, persiste através de uma reinicialização de sistema ou de serviço.
For more information on iptables, refer to Seção 46.9, “IPTables”.

30.1.17. /etc/sysconfig/irda

The /etc/sysconfig/irda file controls how infrared devices on the system are configured at startup.
Os seguintes valores podem ser usados:
  • IRDA=<value>, where <value> is one of the following boolean values:
    • yesirattach runs and periodically checks to see if anything is trying to connect to the infrared port, such as another notebook computer trying to make a network connection. For infrared devices to work on the system, this line must be set to yes.
    • noirattach does not run, preventing infrared device communication.
  • DEVICE=<value>, where <value> is the device (usually a serial port) that handles infrared connections. A sample serial device entry could be /dev/ttyS2.
  • DONGLE=<value>, where <value> specifies the type of dongle being used for infrared communication. This setting exists for people who use serial dongles rather than real infrared ports. A dongle is a device that is attached to a traditional serial port to communicate via infrared. This line is commented out by default because notebooks with real infrared ports are far more common than computers with add-on dongles. A sample dongle entry could be actisys+.
  • DISCOVERY=<value>, where <value> is one of the following boolean values:
    • yes — Starts irattach in discovery mode, meaning it actively checks for other infrared devices. This must be turned on for the machine to actively look for an infrared connection (meaning the peer that does not initiate the connection).
    • no — Does not start irattach in discovery mode.

30.1.18. /etc/sysconfig/keyboard

The /etc/sysconfig/keyboard file controls the behavior of the keyboard. The following values may be used:
  • KEYBOARDTYPE="sun|pc" where sun means a Sun keyboard is attached on /dev/kbd, or pc means a PS/2 keyboard connected to a PS/2 port.
  • KEYTABLE="<file>", where <file> is the name of a keytable file.
    For example: KEYTABLE="us". The files that can be used as keytables start in /lib/kbd/keymaps/i386 and branch into different keyboard layouts from there, all labeled <file>.kmap.gz. The first file found beneath /lib/kbd/keymaps/i386 that matches the KEYTABLE setting is used.

30.1.19. /etc/sysconfig/kudzu

The /etc/sysconfig/kuzdu file triggers a safe probe of the system hardware by kudzu at boot time. A safe probe is one that disables serial port probing.
  • SAFE=<value>, where <value> is one of the following:
    • yeskuzdu does a safe probe.
    • nokuzdu does a normal probe.

30.1.20. /etc/sysconfig/named

The /etc/sysconfig/named file is used to pass arguments to the named daemon at boot time. The named daemon is a Domain Name System (DNS) server which implements the Berkeley Internet Name Domain (BIND) version 9 distribution. This server maintains a table of which hostnames are associated with IP addresses on the network.
Atualmente, somente os seguintes valores podem ser usados:
  • ROOTDIR="</some/where>", where </some/where> refers to the full directory path of a configured chroot environment under which named runs. This chroot environment must first be configured. Type info chroot for more information.
  • OPTIONS="<value>", where <value> is any option listed in the man page for named except -t. In place of -t, use the ROOTDIR line above.
For more information about available parameters for this file, refer to the named man page. For detailed information on how to configure a BIND DNS server, refer to Capítulo 18, Berkeley Internet Name Domain (BIND). By default, the file contains no parameters.

30.1.21. /etc/sysconfig/network

The /etc/sysconfig/network file is used to specify information about the desired network configuration. The following values may be used:
  • NETWORKING=<value>, where <value> is one of the following boolean values:
    • yes — Networking should be configured.
    • no — Networking should not be configured.
  • HOSTNAME=<value>, where <value> should be the Fully Qualified Domain Name (FQDN), such as hostname.expample.com, but can be whatever hostname is necessary.
  • GATEWAY=<value>, where <value> is the IP address of the network's gateway.
  • GATEWAYDEV=<value>, where <value> is the gateway device, such as eth0. Configure this option if you have multiple interfaces on the same subnet, and require one of those interfaces to be the preferred route to the default gateway.
  • NISDOMAIN=<value>, where <value> is the NIS domain name.
  • NOZEROCONF=<valor>, onde configurar o <valor> paratrue exibe a rota zeroconf.
    By default, the zeroconf route (169.254.0.0) is enabled when the system boots. For more information about zeroconf, refer to http://www.zeroconf.org/.

Warning

Do not use custom initscripts to configure network settings. When performing a post-boot network service restart, custom initscripts configuring network settings that are run outside of the network init script lead to unpredictable results.

30.1.22. /etc/sysconfig/nfs

NFS requires portmap, which dynamically assigns ports for RPC services. This causes problems for configuring firewall rules. To overcome this problem, use the /etc/sysconfig/nfs file to control which ports the required RPC services run on.
The /etc/sysconfig/nfs may not exist by default on all systems. If it does not exist, create it and add the following variables (alternatively, if the file exists, un-comment and change the default entries as required):
MOUNTD_PORT=x
control which TCP and UDP port mountd (rpc.mountd) uses. Replace x with an unused port number.
STATD_PORT=x
control which TCP and UDP port status (rpc.statd) uses. Replace x with an unused port number.
LOCKD_TCPPORT=x
control which TCP port nlockmgr (rpc.lockd) uses. Replace x with an unused port number.
LOCKD_UDPPORT=x
control which UDP port nlockmgr (rpc.lockd) uses. Replace x with an unused port number.
If NFS fails to start, check /var/log/messages. Normally, NFS will fail to start if you specify a port number that is already in use. After editing /etc/sysconfig/nfs restart the NFS service by running the service nfs restart command. Run the rpcinfo -p command to confirm the changes.
To configure a firewall to allow NFS:
  1. Allow TCP and UDP port 2049 for NFS.
  2. Allow TCP and UDP port 111 (portmap/sunrpc).
  3. Allow the TCP and UDP port specified with MOUNTD_PORT="x"
  4. Allow the TCP and UDP port specified with STATD_PORT="x"
  5. Allow the TCP port specified with LOCKD_TCPPORT="x"
  6. Allow the UDP port specified with LOCKD_UDPPORT="x"

30.1.23. /etc/sysconfig/ntpd

The /etc/sysconfig/ntpd file is used to pass arguments to the ntpd daemon at boot time. The ntpd daemon sets and maintains the system clock to synchronize with an Internet standard time server. It implements version 4 of the Network Time Protocol (NTP). For more information about what parameters are available for this file, use a Web browser to view the following file: /usr/share/doc/ntp-<version>/ntpd.htm (where <version> is the version number of ntpd). By default, this file sets the owner of the ntpd process to the user ntp.

30.1.24. /etc/sysconfig/radvd

The /etc/sysconfig/radvd file is used to pass arguments to the radvd daemon at boot time. The radvd daemon listens for router requests and sends router advertisements for the IP version 6 protocol. This service allows hosts on a network to dynamically change their default routers based on these router advertisements. For more information about available parameters for this file, refer to the radvd man page. By default, this file sets the owner of the radvd process to the user radvd.

30.1.25. /etc/sysconfig/samba

The /etc/sysconfig/samba file is used to pass arguments to the smbd and the nmbd daemons at boot time. The smbd daemon offers file sharing connectivity for Windows clients on the network. The nmbd daemon offers NetBIOS over IP naming services. For more information about what parameters are available for this file, refer to the smbd man page. By default, this file sets smbd and nmbd to run in daemon mode.

30.1.26. /etc/sysconfig/selinux

The /etc/sysconfig/selinux file contains the basic configuration options for SELinux. This file is a symbolic link to /etc/selinux/config.

30.1.27. /etc/sysconfig/sendmail

The /etc/sysconfig/sendmail file allows messages to be sent to one or more clients, routing the messages over whatever networks are necessary. The file sets the default values for the Sendmail application to run. Its default values are set to run as a background daemon and to check its queue each hour in case something has backed up.
Os valores incluem:
  • DAEMON=<value>, where <value> is one of the following:
    • yesSendmail should be configured to listen to port 25 for incoming mail. yes implies the use of Sendmail's -bd options.
    • noSendmail should not be configured to listen to port 25 for incoming mail.
  • QUEUE=1h which is given to Sendmail as -q$QUEUE. The -q option is not given to Sendmail if /etc/sysconfig/sendmail exists and QUEUE is empty or undefined.

30.1.28. /etc/sysconfig/spamassassin

The /etc/sysconfig/spamassassin file is used to pass arguments to the spamd daemon (a daemonized version of Spamassassin) at boot time. Spamassassin is an email spam filter application. For a list of available options, refer to the spamd man page. By default, it configures spamd to run in daemon mode, create user preferences, and auto-create whitelists (allowed bulk senders).
For more information about Spamassassin, refer to Seção 25.5.2.6, “Spam Filters”.

30.1.29. /etc/sysconfig/squid

The /etc/sysconfig/squid file is used to pass arguments to the squid daemon at boot time. The squid daemon is a proxy caching server for Web client applications. For more information on configuring a squid proxy server, use a Web browser to open the /usr/share/doc/squid-<version>/ directory (replace <version> with the squid version number installed on the system). By default, this file sets squid to start in daemon mode and sets the amount of time before it shuts itself down.

30.1.30. /etc/sysconfig/system-config-securitylevel

The /etc/sysconfig/system-config-securitylevel file contains all options chosen by the user the last time the Security Level Configuration Tool (system-config-securitylevel) was run. Users should not modify this file by hand. For more information about the Security Level Configuration Tool, refer to Seção 46.8.2, “Configurações Básicas de Firewall ”.

30.1.31. /etc/sysconfig/system-config-selinux

The /etc/sysconfig/system-config-selinux file contains all options chosen by the user the last time the SELinux Administration Tool (system-config-selinux) was run. Users should not modify this file by hand. For more information about the SELinux Administration Tool and SELinux in general, refer to Seção 47.2, “Introdução ao SELinux”.

30.1.32. /etc/sysconfig/system-config-users

The /etc/sysconfig/system-config-users file is the configuration file for the graphical application, User Manager. This file is used to filter out system users such as root, daemon, or lp. This file is edited by the Preferences > Filter system users and groups pull-down menu in the User Manager application and should never be edited by hand. For more information on using this application, refer to Seção 35.1, “Configuração de Usuário e Grupo”.

30.1.33. /etc/sysconfig/system-logviewer

The /etc/sysconfig/system-logviewer file is the configuration file for the graphical, interactive log viewing application, Log Viewer. This file is edited by the Edit > Preferences pull-down menu in the Log Viewer application and should not be edited by hand. For more information on using this application, refer to Capítulo 38, Arquivos de Registro.

30.1.34. /etc/sysconfig/tux

The /etc/sysconfig/tux file is the configuration file for the Red Hat Content Accelerator (formerly known as TUX), the kernel-based Web server. For more information on configuring the Red Hat Content Accelerator, use a Web browser to open the /usr/share/doc/tux-<version>/tux/index.html file (replace <version> with the version number of TUX installed on the system). The parameters available for this file are listed in /usr/share/doc/tux-<version>/tux/parameters.html.

30.1.35. /etc/sysconfig/vncservers

The /etc/sysconfig/vncservers file configures the way the Virtual Network Computing (VNC) server starts up.
A VNC é um sitema de exibição remota que permite que os usuários visualizem o ambiente de desktop não somente na máquina em que estiver rodando mas em redes diferentes em uma variedade de arquiteturas.
Pode conter o seguinte:
  • VNCSERVERS=<value>, where <value> is set to something like "1:fred", to indicate that a VNC server should be started for user fred on display :1. User fred must have set a VNC password using the vncpasswd command before attempting to connect to the remote VNC server.

30.1.36. /etc/sysconfig/xinetd

The /etc/sysconfig/xinetd file is used to pass arguments to the xinetd daemon at boot time. The xinetd daemon starts programs that provide Internet services when a request to the port for that service is received. For more information about available parameters for this file, refer to the xinetd man page. For more information on the xinetd service, refer to Seção 46.5.3, “xinetd”.

30.2. Directories in the /etc/sysconfig/ Directory

The following directories are normally found in /etc/sysconfig/.
apm-scripts/
This directory contains the APM suspend/resume script. Do not edit the files directly. If customization is necessary, create a file called /etc/sysconfig/apm-scripts/apmcontinue which is called at the end of the script. It is also possible to control the script by editing /etc/sysconfig/apmd.
cbq/
This directory contains the configuration files needed to do Class Based Queuing for bandwidth management on network interfaces. CBQ divides user traffic into a hierarchy of classes based on any combination of IP addresses, protocols, and application types.
networking/
This directory is used by the Network Administration Tool (system-config-network), and its contents should not be edited manually. For more information about configuring network interfaces using the Network Administration Tool, refer to Capítulo 16, Configuração de Rede.
network-scripts/
This directory contains the following network-related configuration files:
  • Network configuration files for each configured network interface, such as ifcfg-eth0 for the eth0 Ethernet interface.
  • Scripts used to bring network interfaces up and down, such as ifup and ifdown.
  • Scripts used to bring ISDN interfaces up and down, such as ifup-isdn and ifdown-isdn.
  • Diversos scripts de funções de rede compartilhada, que não devem ser editadas diretamente.
For more information on the network-scripts directory, refer to Capítulo 15, Network Interfaces.
rhn/
Deprecated. This directory contains the configuration files and GPG keys used by the RHN Classic content service. No files in this directory should be edited by hand.
This directory is available for legacy systems which are still managed by RHN Classic. Systems which are registered against the Certificate-Based Red Hat Network do not use this directory.

30.3. Recursos Adicionais

This chapter is only intended as an introduction to the files in the /etc/sysconfig/ directory. The following source contains more comprehensive information.

30.3.1. Documentação Instalada

  • /usr/share/doc/initscripts-<version-number>/sysconfig.txt — This file contains a more authoritative listing of the files found in the /etc/sysconfig/ directory and the configuration options available for them. The <version-number> in the path to this file corresponds to the version of the initscripts package installed.

Capítulo 31. Configuração de Data e Hora

The Time and Date Properties Tool allows the user to change the system date and time, to configure the time zone used by the system, and to setup the Network Time Protocol (NTP) daemon to synchronize the system clock with a time server.
Você precisa estar rodando o Sistema de Janelas X e possuir privilégios root para usar a ferramenta, a qual pode ser iniciada de três maneiras:
  • From the desktop, go to Applications (the main menu on the panel) > System Settings > Date & Time
  • From the desktop, right-click on the time in the toolbar and select Adjust Date and Time.
  • Type the command system-config-date, system-config-time, or dateconfig at a shell prompt (for example, in an XTerm or a GNOME terminal).

31.1. Time and Date Properties

As shown in Figura 31.1, “Time and Date Properties”, the first tabbed window that appears is for configuring the system date and time.
Time and Date Properties
Time and Date Properties
Figura 31.1. Time and Date Properties

Para alterar a data, use as setas à direita e à esquerda do mês e do ano para manipular os mesmos; e clique diretamente no dia da semana para mudá-lo.
To change the time, use the up and down arrow buttons beside the Hour, Minute, and Second in the Time section.
Clicking the OK button applies any changes made to the date and time, the NTP daemon settings, and the time zone settings. It also exits the program.

31.2. Propriedades do Protocolo de Horário de Rede (Network Time Protocol - NTP)

As shown in Figura 31.2, “NTP Properties”, the second tabbed window that appears is for configuring NTP.
NTP Properties
NTP Properties
Figura 31.2. NTP Properties

The Network Time Protocol (NTP) daemon synchronizes the system clock with a remote time server or time source. The application allows you to configure an NTP daemon to synchronize your system clock with a remote server. To enable this feature, select Enable Network Time Protocol. This enables the NTP Servers list and other options. You can choose one of the predefined servers, edit a predefined server by clicking the Edit or add a new server name by clicking Add. Your system does not start synchronizing with the NTP server until you click OK. After clicking OK, the configuration is saved and the NTP daemon is started (or restarted if it is already running).
Clicking the OK button applies any changes made to the date and time, the NTP daemon settings, and the time zone settings. It also exits the program.

31.3. Configuração do Fuso Horário

As shown in Figura 31.3, “Timezone Properties”, the third tabbed window that appears is for configuring the system time zone.
To configure the system time zone, click the Time Zone tab. The time zone can be changed by either using the interactive map or by choosing the desired time zone from the list below the map. To use the map, click on the desired region. The map zooms into the region selected, after which you may choose the city specific to your time zone. A red X appears and the time zone selection changes in the list below the map.
Alternativamente, você também pode usar a lista abaixo do mapa. Da mesma maneira que o mapa lhe deixa escolher uma zona antes de ter que escolher uma cidade, a lista de zonas agora é estruturada como uma árvore, com países e cidades agrupados em seus respectivos continentes. Fuso horários não geográficos também foram adicionados para satisfazer as necessidades da comunidade científica.
Click OK to apply the changes and exit the program.
Timezone Properties
Timezone Properties
Figura 31.3. Timezone Properties

If your system clock is set to use UTC, select the System clock uses UTC option. UTC stands for the Universal Time, Coordinated, also known as Greenwich Mean Time (GMT). Other time zones are determined by adding or subtracting from the UTC time.

Capítulo 32. Configuração do Teclado

The installation program allows you to configure a keyboard layout for your system. To configure a different keyboard layout after installation, use the Keyboard Configuration Tool.
To start the Keyboard Configuration Tool, select System (on the panel) > Administration > Keyboard, or type the command system-config-keyboard at a shell prompt.
Keyboard Configuration Tool
Keyboard Configuration Tool
Figura 32.1. Keyboard Configuration Tool

Select a keyboard layout from the list (for example, U.S. English) and click OK.
As mudanças são aplicadas instantaneamente.

Capítulo 33. O Sistema X Window

Embora o coração do Red Hat Enterprise Linux seja o kernel, para muitos usuários, a face do sistema operacional é o ambiente gráfico oferecido pelo Sistema X Window System, também chamado de X.
Outros ambientes em window existiram no mundo UNIX, incluindo alguns que precedem o lançamento do Sistema X Window em Junho de 1984. No entanto, o X tem sido o ambiente gráfico padrão para a maioria dos sistemas operacionais como UNIX, incluindo Red Hat Enterprise Linux por vários anos.
O ambiente gráfico para Red Hat Enterprise Linux é fornecido pela Fundação X.Org, uma organização de código aberto criada para gerenciar desenvolvimento e estratégia para o Sistema X Window e tecnologias relacionadas. A X.Org é um projeto de rápido desenvolvimento em grande escala com centenas de desenvolvedores ao redor do mundo. Ele caracteriza o suporte para uma variedade de dispositivos hardware e arquiteturas, e pode rodar em uma variedade de sistemas operacionais diferentes e plataformas. Este lançamento do Red Hat Enterprise Linux inclui em particular o lançamento do X11R7.1 para o Sistema X Window.
The X Window System uses a client-server architecture. The X server (the Xorg binary) listens for connections from X client applications via a network or local loopback interface. The server communicates with the hardware, such as the video card, monitor, keyboard, and mouse. X client applications exist in the user-space, creating a graphical user interface (GUI) for the user and passing user requests to the X server.

33.1. O Lançamento X11R7.1

O Red Hat Enterprise Linux5.8 agora usa o lançamento X11R7.1 como base de Sistema X Window, que inclui diversos drivers de vídeo, EXA, e melhorias de suporte de plataforma no lançamento anterior, entre outros. Além disso, este lançamento também inclui diversos recursos de configuração automática para o servidor X.
X11R7.1 is the first release to take specific advantage of the modularization of the X Window System. This modularization, which splits X into logically distinct modules, makes it easier for open source developers to contribute code to the system.

Importante

O Red Hat Enterprise Linux não oferece mais os pacotes de servidor XFree86™. Antes de atualizar um sistema para a versão mais recente do Red Hat Enterprise Linux, esteja certo de que a placa de vídeo do sistema é compatível ao lançamento X11R7.1, checando a Lista de Compatibilidade do Hardware Red Hat, localizado online em http://hardware.redhat.com/.
In the X11R7.1 release, all libraries, headers, and binaries now live under /usr/ instead of /usr/X11R6. The /etc/X11/ directory contains configuration files for X client and server applications. This includes configuration files for the X server itself, the xfs font server, the X display managers, and many other base components.
The configuration file for the newer Fontconfig-based font architecture is still /etc/fonts/fonts.conf. For more on configuring and adding fonts, refer to Seção 33.4, “Fontes”.
Como o servidor X realiza tarefas avançadas em uma matriz ampla de hardware, ele solicita informações detalhadas sobre o hardware no qual ele está funcionando. O Servidor X detecta automaticamente algumas destas informações, outros detalhes devem ser configurados.
The installation program installs and configures X automatically, unless the X11R7.1 release packages are not selected for installation. However, if there are any changes to the monitor, video card or other devices managed by the X server, X must be reconfigured. The best way to do this is to use the X Configuration Tool (system-config-display), particularly for devices that are not detected manually.
In Red Hat Enterprise Linux's default graphical environment, the X Configuration Tool is available at System (on the panel) > Administration > Display.
Changes made with the X Configuration Tool take effect after logging out and logging back in.
For more information about X Configuration Tool, refer to Capítulo 34, Configuração do Sistema X Window.
In some situations, reconfiguring the X server may require manually editing its configuration file, /etc/X11/xorg.conf. For information about the structure of this file, refer to Seção 33.3, “Arquivos de Configuração de Servidor X”.

33.2. Ambientes de Desktop e Gestores de Window

Uma vez que o servidor X estiver rodando, os aplicativos de cliente X podem se conectar à ele e criar um GUI para o usuário. Existe uma variedade de GUIs que são possíveis com o Red Hat Enterprise Linux a partir do Gestor de Janela rudimentar, até o ambiente de desktop GNOME altamente desenvolvido e interativo, que a maioria dos usuários Red Hat Enterprise Linux reconhecem.
Para criar um GUI mais recente e mais compreensivo, é necessário que duas classes do aplicativo X se conectem ao servidor X: um ambiente de desktop e um gestor de janelas.

33.2.1. Ambientes de Desktop

Um ambiente de desktop integra diversos clientes X para criar um ambiente de usuário gráfico em comum e uma plataforma de desenvolvimento.
Ambientes de desktop possuem recursos avançados, que permitem que os clientes X, entre outros processos em execução,se comuniquem com outro, enquanto também permitem que os aplicativos gravados para trabalhar naquele ambiente, realizem tarefas avançadas, tais como arrastar e descartar operações.
Red Hat Enterprise Linux oferece dois ambientes de desktop:
  • GNOME — O ambiente de desktop padrão para o Red Hat Enterprise Linux baseado no kit de ferramentas gráficas GTK+2.
  • KDE — Um ambiente de desktop alternativo baseado no kit de ferramentas gráficas Qt 3.
Ambos os GNOME e KDE possuem aplicativos de produtividade avançada, tais como processadores word, planilhas, e navegadores da Web. Eles também oferecem ferramentas para padronizar o visual e conteúdo do GUI. Além disso, caso as bibliotecas dos GTK+ 2 e Qt estiverem presentes, os aplicativos KDE podem rodar em GNOME e vice-versa.

33.2.2. Gestores de Janelas

Os Gestores de Janelas são programas de clientes X que são parte de um ambiente de desktop ou, em alguns casos, são independentes. Seu propósito inicial é controlar a forma que as janelas gráficas são posicionadas, redimensionada, ou movida. Os gestores de janelas também controlam barras de título, comportamento de foco em janela, e vínculos de botão de mouse e chave de usuário específico.
Quatro gestores de janela estão inclusos no Red Hat Enterprise Linux:
kwin
O Gestor de janela KWin é o gestor de janela padrão para o KDE. É um gestor de janela eficiente que suporta temas personalizados.
metacity
O Gestor de janela Metacity é o gestor de janela padrão para GNOME. É um gestor de janela eficiente e simples, que também suporta os temas padronizados. Para rodar este gestor de janela, você precisará instalar o pacote metacity.
mwm
O Gestor de Janela Motif (mwm) é um gestor de janela independente e básico. Como é criado para ser um gestor de janela independente, ele não deve ser usado junto com um GNOME ou KDE. Para rodar este gestor de janela, você irá precisar instalar o pacote openmotif.
twm
A Aba de Gestro de Janela (twm que oferece o conjunto de ferramentas mais básico do que qualquer gestor de janelas, pode ser usado tanto como independente ou com um ambiente de desktop. É instalado como parte de um lançamento X11R7.1.
To run any of the aforementioned window managers, you will first need to boot into Runlevel 3. For instructions on how to do this, refer to Seção 17.1, “Níveis de Execução (Runlevels)”.
Once you are logged in to Runlevel 3, you will be presented with a terminal prompt, not a graphical environment. To start a window manager, type xinit -e <path-to-window-manager> at the prompt.
<path-to-window-manager> é o local do arquivo binário do gestor de janela. O arquivo binário pode ser localizado digitando whichwindow-manager-name, onde window-manager-name é o nome do gestor de janela que você quer rodar.
Por exemplo:
~]# which twm
/usr/bin/twm
~]# xinit -e /usr/bin/twm
O primeiro comando acima retorna o caminho absoluto para o gestor de janela twm, o segundo comando inicia o twm.
Para sair de um gestor de janela, feche a última janela ou pressione Ctrl+Alt+Backspace. Quando você já tiver saído do gestor de janela, você poderá retornar para o Nível de Execução 5, digitando startx na janela de comandos.

33.3. Arquivos de Configuração de Servidor X

O servidor X é um binário único executável (/usr/bin/Xorg). Arquivos de configuração associados estão armazenados no diretório /etc/X11/ ( como um link simbólico — X — que se refere ao /usr/bin/Xorg). O arquivo se configuração para o servidor X é /etc/X11/xorg.conf.
O diretório /usr/lib/xorg/modules/ contém módulos do servidor X que podem ser carregados dinamicamente em tempo de execução. Por padrão, somente alguns módulos no /usr/lib/xorg/modules/ são carregados automaticamente pelo servidor X.
To load optional modules, they must be specified in the X server configuration file, /etc/X11/xorg.conf. For more information about loading modules, refer to Seção 33.3.1.5, “Module.
When Red Hat Enterprise Linux 5.8 is installed, the configuration files for X are created using information gathered about the system hardware during the installation process.

33.3.1. xorg.conf

While there is rarely a need to manually edit the /etc/X11/xorg.conf file, it is useful to understand the various sections and optional parameters available, especially when troubleshooting.

33.3.1.1. A Estrutura

The /etc/X11/xorg.conf file is comprised of many different sections which address specific aspects of the system hardware.
Each section begins with a Section "<section-name>" line (where <section-name> is the title for the section) and ends with an EndSection line. Each section contains lines that include option names and one or more option values. These are sometimes enclosed in double quotes (").
Lines beginning with a hash mark (#) are not read by the X server and are used for human-readable comments.
Some options within the /etc/X11/xorg.conf file accept a boolean switch which turns the feature on or off. Acceptable boolean values are:
  • 1, on, true, or yes — Turns the option on.
  • 0, off, false, or no — Turns the option off.
The following are some of the more important sections in the order in which they appear in a typical /etc/X11/xorg.conf file. More detailed information about the X server configuration file can be found in the xorg.conf man page.

33.3.1.2. ServerFlags

The optional ServerFlags section contains miscellaneous global X server settings. Any settings in this section may be overridden by options placed in the ServerLayout section (refer to Seção 33.3.1.3, “ServerLayout for details).
Each entry within the ServerFlags section is on its own line and begins with the term Option followed by an option enclosed in double quotation marks (").
The following is a sample ServerFlags section:
Section "ServerFlags"
	Option "DontZap" "true"
EndSection
A seguir, uma lista de algumas das opções mais úteis:
  • "DontZap" "<boolean>" — When the value of <boolean> is set to true, this setting prevents the use of the Ctrl+Alt+Backspace key combination to immediately terminate the X server.
  • "DontZoom" "<boolean>" — When the value of <boolean> is set to true, this setting prevents cycling through configured video resolutions using the Ctrl+Alt+Keypad-Plus and Ctrl+Alt+Keypad-Minus key combinations.

33.3.1.3. ServerLayout

The ServerLayout section binds together the input and output devices controlled by the X server. At a minimum, this section must specify one output device and one input device. By default, a monitor (output device) and keyboard (input device) are specified.
The following example illustrates a typical ServerLayout section:
Section  "ServerLayout"
	Identifier     "Default Layout"
	Screen      0  "Screen0" 0 0
	InputDevice    "Mouse0" "CorePointer"
	InputDevice    "Keyboard0" "CoreKeyboard"
EndSection
The following entries are commonly used in the ServerLayout section:
  • Identifier — Specifies a unique name for this ServerLayout section.
  • Screen — Specifies the name of a Screen section to be used with the X server. More than one Screen option may be present.
    The following is an example of a typical Screen entry:
    Screen      0  "Screen0" 0 0
    The first number in this example Screen entry (0) indicates that the first monitor connector or head on the video card uses the configuration specified in the Screen section with the identifier "Screen0".
    An example of a Screen section with the identifier "Screen0" can be found in Seção 33.3.1.9, “Screen.
    If the video card has more than one head, another Screen entry with a different number and a different Screen section identifier is necessary .
    The numbers to the right of "Screen0" give the absolute X and Y coordinates for the upper-left corner of the screen (0 0 by default).
  • InputDevice — Specifies the name of an InputDevice section to be used with the X server.
    It is advisable that there be at least two InputDevice entries: one for the default mouse and one for the default keyboard. The options CorePointer and CoreKeyboard indicate that these are the primary mouse and keyboard.
  • Option "<option-name>" — An optional entry which specifies extra parameters for the section. Any options listed here override those listed in the ServerFlags section.
    Replace <option-name> with a valid option listed for this section in the xorg.conf man page.
Caso seja possível colocar mais de uma seção ServerLayout no arquivo /etc/X11/xorg.conf. No entanto, por padrão, o servidor somente lê o primeiro que ele encontra.
Se houver uma seção alternativa ServerLayout, ela pode especificar como um argumento de linha de comando ao iniciar uma sessão X.

33.3.1.4. Files

The Files section sets paths for services vital to the X server, such as the font path. This is an optional section, these paths are normally detected automatically. This section may be used to override any automatically detected defaults.
The following example illustrates a typical Files section:
Section "Files"
	RgbPath      "/usr/share/X11/rgb.txt"
	FontPath     "unix/:7100"
EndSection
The following entries are commonly used in the Files section:
  • RgbPath — Specifies the location of the RGB color database. This database defines all valid color names in X and ties them to specific RGB values.
  • FontPath — Specifies where the X server must connect to obtain fonts from the xfs font server.
    By default, the FontPath is unix/:7100. This tells the X server to obtain font information using UNIX-domain sockets for inter-process communication (IPC) on port 7100.
    Refer to Seção 33.4, “Fontes” for more information concerning X and fonts.
  • ModulePath — An optional parameter which specifies alternate directories which store X server modules.

33.3.1.5. Module

Por padrão, o servidor X carrega automaticamente os seguintes módulos a partir do diretório /usr/lib/xorg/modules/:
  • extmod
  • dbe
  • glx
  • freetype
  • type1
  • record
  • dri
The default directory for loading these modules can be changed by specifying a different directory with the optional ModulePath parameter in the Files section. Refer to Seção 33.3.1.4, “Files for more information on this section.
Adicionando uma seção Module para /etc/X11/xorg.conf instui o servidor X para carregar os módulos listados nesta seção ao invés dosmódulos padrão.
For example, the following typical Module section:
Section "Module"
	Load  "fbdevhw"
EndSection
instructs the X server to load the fbdevhw instead of the default modules.
Como tal, se você adicionar uma seção Module ao /etc/X11/xorg.conf, você precisará especificar quaisquer módulos padrão que você quiser para carregar, assim como módulos extras.

33.3.1.6. InputDevice

Each InputDevice section configures one input device for the X server. Systems typically have at least one InputDevice section for the keyboard. It is perfectly normal to have no entry for a mouse, as most mouse settings are automatically detected.
The following example illustrates a typical InputDevice section for a keyboard:
Section "InputDevice"
        Identifier  "Keyboard0"
        Driver      "kbd"
        Option      "XkbModel" "pc105"
        Option      "XkbLayout" "us"
EndSection
The following entries are commonly used in the InputDevice section:
  • Identifier — Specifies a unique name for this InputDevice section. This is a required entry.
  • Driver — Specifies the name of the device driver X must load for the device.
  • Option — Specifies necessary options pertaining to the device.
    Um mouse pode também ser especificado para sobrescrever quaisquer padrões auto-detectados para o dispositivo. As seguintes opções são tipicamente incluídas ao adicionar um mouse no xorg.conf:
    • Protocol — Specifies the protocol used by the mouse, such as IMPS/2.
    • Device — Specifies the location of the physical device.
    • Emulate3Buttons — Specifies whether to allow a two-button mouse to act like a three-button mouse when both mouse buttons are pressed simultaneously.
    Consult the xorg.conf man page for a list of valid options for this section.

33.3.1.7. Monitor

Each Monitor section configures one type of monitor used by the system. This is an optional entry as well, as most monitors are now automatically detected.
The easiest way to configure a monitor is to configure X during the installation process or by using the X Configuration Tool. For more information about using the X Configuration Tool, refer to Capítulo 34, Configuração do Sistema X Window.
This example illustrates a typical Monitor section for a monitor:
Section "Monitor"
	Identifier   "Monitor0"
	VendorName   "Monitor Vendor"
	ModelName    "DDC Probed Monitor - ViewSonic G773-2"
	DisplaySize  320	240
	HorizSync    30.0 - 70.0
	VertRefresh  50.0 - 180.0
EndSection

Aviso

Be careful when manually editing values in the Monitor section of /etc/X11/xorg.conf. Inappropriate values can damage or destroy a monitor. Consult the monitor's documentation for a listing of safe operating parameters.
The following are commonly entries used in the Monitor section:
  • Identifier — Specifies a unique name for this Monitor section. This is a required entry.
  • VendorName — An optional parameter which specifies the vendor of the monitor.
  • ModelName — An optional parameter which specifies the monitor's model name.
  • DisplaySize — An optional parameter which specifies, in millimeters, the physical size of the monitor's picture area.
  • HorizSync — Specifies the range of horizontal sync frequencies compatible with the monitor in kHz. These values help the X server determine the validity of built-in or specified Modeline entries for the monitor.
  • VertRefresh — Specifies the range of vertical refresh frequencies supported by the monitor, in kHz. These values help the X server determine the validity of built in or specified Modeline entries for the monitor.
  • Modeline — An optional parameter which specifies additional video modes for the monitor at particular resolutions, with certain horizontal sync and vertical refresh resolutions. Refer to the xorg.conf man page for a more detailed explanation of Modeline entries.
  • Option "<option-name>" — An optional entry which specifies extra parameters for the section. Replace <option-name> with a valid option listed for this section in the xorg.conf man page.

33.3.1.8. Device

Each Device section configures one video card on the system. While one Device section is the minimum, additional instances may occur for each video card installed on the machine.
The best way to configure a video card is to configure X during the installation process or by using the X Configuration Tool. For more about using the X Configuration Tool, refer to Capítulo 34, Configuração do Sistema X Window.
The following example illustrates a typical Device section for a video card:
Section "Device"
	Identifier  "Videocard0"
	Driver      "mga"
	VendorName  "Videocard vendor"
	BoardName   "Matrox Millennium G200"
	VideoRam    8192
	Option      "dpms"
EndSection
The following entries are commonly used in the Device section:
  • Identifier — Specifies a unique name for this Device section. This is a required entry.
  • Driver — Specifies which driver the X server must load to utilize the video card. A list of drivers can be found in /usr/share/hwdata/videodrivers, which is installed with the hwdata package.
  • VendorName — An optional parameter which specifies the vendor of the video card.
  • BoardName — An optional parameter which specifies the name of the video card.
  • VideoRam — An optional parameter which specifies the amount of RAM available on the video card in kilobytes. This setting is only necessary for video cards the X server cannot probe to detect the amount of video RAM.
  • BusID — An entry which specifies the bus location of the video card. On systems with only one video card a BusID entry is optional and may not even be present in the default /etc/X11/xorg.conf file. On systems with more than one video card, however, a BusID entry must be present.
  • Screen — An optional entry which specifies which monitor connector or head on the video card the Device section configures. This option is only useful for video cards with multiple heads.
    If multiple monitors are connected to different heads on the same video card, separate Device sections must exist and each of these sections must have a different Screen value.
    Values for the Screen entry must be an integer. The first head on the video card has a value of 0. The value for each additional head increments this value by one.
  • Option "<option-name>" — An optional entry which specifies extra parameters for the section. Replace <option-name> with a valid option listed for this section in the xorg.conf man page.
    One of the more common options is "dpms" (for Display Power Management Signaling, a VESA standard), which activates the Service Star energy compliance setting for the monitor.

33.3.1.9. Screen

Each Screen section binds one video card (or video card head) to one monitor by referencing the Device section and the Monitor section for each. While one Screen section is the minimum, additional instances may occur for each video card and monitor combination present on the machine.
The following example illustrates a typical Screen section:
Section "Screen"
	Identifier "Screen0"
	Device     "Videocard0"
	Monitor    "Monitor0"
	DefaultDepth     16
	SubSection "Display"
		Depth     24
		Modes    "1280x1024" "1280x960" "1152x864" "1024x768" "800x600" "640x480"
	EndSubSection
	SubSection "Display"
		Depth     16
		Modes    "1152x864" "1024x768" "800x600" "640x480"
	EndSubSection
EndSection
The following entries are commonly used in the Screen section:
  • Identifier — Specifies a unique name for this Screen section. This is a required entry.
  • Device — Specifies the unique name of a Device section. This is a required entry.
  • Monitor — Specifies the unique name of a Monitor section. This is only required if a specific Monitor section is defined in the xorg.conf file. Normally, monitors are automatically detected.
  • DefaultDepth — Specifies the default color depth in bits. In the previous example, 16 (which provides thousands of colors) is the default. Only one DefaultDepth is permitted, although this can be overridden with the Xorg command line option -depth <n>,where <n> is any additional depth specified.
  • SubSection "Display" — Specifies the screen modes available at a particular color depth. The Screen section can have multiple Display subsections, which are entirely optional since screen modes are automatically detected.
    Esta sub-seção é geralmente usada para sobrescrever os modos auto-detectados.
  • Option "<option-name>" — An optional entry which specifies extra parameters for the section. Replace <option-name> with a valid option listed for this section in the xorg.conf man page.

33.3.1.10. DRI

The optional DRI section specifies parameters for the Direct Rendering Infrastructure (DRI). DRI is an interface which allows 3D software applications to take advantage of 3D hardware acceleration capabilities built into most modern video hardware. In addition, DRI can improve 2D performance via hardware acceleration, if supported by the video card driver.
Esta seção raramente aparece, pois o Grupo DRI e Modo são inicializados automaticamente para valores padrão. Se um Grupo ou Mode for requisitado, então adicionar esta seção ao arquivo xorg.conf irá sobrescrever os padrões.
The following example illustrates a typical DRI section:
Section "DRI"
	Group        0
	Mode         0666
EndSection
Uma vez que placas de vídeo diferentes usam DRI de diferentes maneiras, não adicione à esta seção sem antes consultar http://dri.sourceforge.net/.

33.4. Fontes

Red Hat Enterprise Linux uses two subsystems to manage and display fonts under X: Fontconfig and xfs.
O subsistema da fonte Fontconfig simplifica o gerenciamento da fonte e oferece recursos de exibição avançada, tal como anti-aliasing. Este sistema é usado automaticamente para aplicativos programados, usando o kit de ferramentas gráfico Qt 3 or GTK+ 2.
Para compatibilidade, Red Hat Enterprise Linux inclui o subsistema de fonte original, chamado de subsistema de fonte X central. Este sistema, com mais de 15 anos, é baseado no Servidor de Fonte X (xfs).
Esta seção discute como configurar fontes para X usando os dois sistemas.

33.4.1. Fontconfig

O subsistema da fonte Fontconfig, permite que aplicativos acessem diretamente, fontes no sistema e usem Xft ou outros mecanismos de renderização para render as fontes Fontconfig com anti-aliasing avançado. Aplicativos gráficos podem usar a biblioteca Xft com Fontconfig para trazer o texto à tela.
Ao longo do tempo, o subsistema da fonte Fontconfig/Xft, substitui o subsistema de fonte X central.

Importante

The Fontconfig font subsystem does not yet work for OpenOffice.org, which uses its own font rendering technology.
It is important to note that Fontconfig uses the /etc/fonts/fonts.conf configuration file, which should not be edited by hand.

Tip

Due to the transition to the new font system, GTK+ 1.2 applications are not affected by any changes made via the Font Preferences dialog (accessed by selecting System (on the panel) > Preferences > Fonts). For these applications, a font can be configured by adding the following lines to the file ~/.gtkrc.mine:
style "user-font" {
	fontset = "<font-specification>"
}

widget_class "*" style "user-font"
Replace <font-specification> with a font specification in the style used by traditional X applications, such as -adobe-helvetica-medium-r-normal--*-120-*-*-*-*-*-*. A full list of core fonts can be obtained by running xlsfonts or created interactively using the xfontsel command.

33.4.1.1. Adicionando Fontes à Configuração de Fontes

Adicionar novas fontes ao subsistema Fontconfig, é um processo direto.
  1. To add fonts system-wide, copy the new fonts into the /usr/share/fonts/ directory. It is a good idea to create a new subdirectory, such as local/ or similar, to help distinguish between user-installed and default fonts.
    To add fonts for an individual user, copy the new fonts into the .fonts/ directory in the user's home directory.
  2. Use the fc-cache command to update the font information cache, as in the following example:
    fc-cache <path-to-font-directory>
    In this command, replace <path-to-font-directory> with the directory containing the new fonts (either /usr/share/fonts/local/ or /home/<user>/.fonts/).

Tip

Individual users may also install fonts graphically, by typing fonts:/// into the Nautilus address bar, and dragging the new font files there.

Importante

If the font file name ends with a .gz extension, it is compressed and cannot be used until uncompressed. To do this, use the gunzip command or double-click the file and drag the font to a directory in Nautilus.

33.4.2. Sistema de Fonte Central X

For compatibility, Red Hat Enterprise Linux provides the core X font subsystem, which uses the X Font Server (xfs) to provide fonts to X client applications.
The X server looks for a font server specified in the FontPath directive within the Files section of the /etc/X11/xorg.conf configuration file. Refer to Seção 33.3.1.4, “Files for more information about the FontPath entry.
The X server connects to the xfs server on a specified port to acquire font information. For this reason, the xfs service must be running for X to start. For more about configuring services for a particular runlevel, refer to Capítulo 17, Controlando Acesso aos Serviços.

33.4.2.1. xfs Configuration

The /etc/rc.d/init.d/xfs script starts the xfs server. Several options can be configured within its configuration file, /etc/X11/fs/config.
Segue uma lista de opções comuns:
  • alternate-servers — Specifies a list of alternate font servers to be used if this font server is not available. A comma must separate each font server in a list.
  • catalogue — Specifies an ordered list of font paths to use. A comma must separate each font path in a list.
    Use the string :unscaled immediately after the font path to make the unscaled fonts in that path load first. Then specify the entire path again, so that other scaled fonts are also loaded.
  • client-limit — Specifies the maximum number of clients the font server services. The default is 10.
  • clone-self — Allows the font server to clone a new version of itself when the client-limit is hit. By default, this option is on.
  • default-point-size — Specifies the default point size for any font that does not specify this value. The value for this option is set in decipoints. The default of 120 corresponds to a 12 point font.
  • default-resolutions — Specifies a list of resolutions supported by the X server. Each resolution in the list must be separated by a comma.
  • deferglyphs — Specifies whether to defer loading glyphs (the graphic used to visually represent a font). To disable this feature use none, to enable this feature for all fonts use all, or to turn this feature on only for 16-bit fonts use 16.
  • error-file — Specifies the path and file name of a location where xfs errors are logged.
  • no-listen — Prevents xfs from listening to particular protocols. By default, this option is set to tcp to prevent xfs from listening on TCP ports for security reasons.

    Tip

    If xfs is used to serve fonts over the network, remove this line.
  • port — Specifies the TCP port that xfs listens on if no-listen does not exist or is commented out.
  • use-syslog — Specifies whether to use the system error log.

33.4.2.2. Adding Fonts to xfs

To add fonts to the core X font subsystem (xfs), follow these steps:
  1. If it does not already exist, create a directory called /usr/share/fonts/local/ using the following command as root:
    mkdir /usr/share/fonts/local/
    If creating the /usr/share/fonts/local/ directory is necessary, it must be added to the xfs path using the following command as root:
    chkfontpath --add /usr/share/fonts/local/
  2. Copy the new font file into the /usr/share/fonts/local/ directory
  3. Atualize as informações da fonte enviando o seguinte comando como root:
    ttmkfdir -d /usr/share/fonts/local/ -o /usr/share/fonts/local/fonts.scale
  4. Reload the xfs font server configuration file by issuing the following command as root:
    service xfs reload

33.5. Níveis de Execução e X

Na maioria dos casos o instalador Red Hat Enterprise Linux configura uma máquina para inicializar no ambiente de registro gráfico, conhecido como Runlevel 5. É possível, no entanto, inicializar para dentro do modo somente texto, usuário múltiplo, chamado Runlevel 3 e inicia uma sessão X a partir daí.
For more information about runlevels, refer to Seção 17.1, “Níveis de Execução (Runlevels)”.
As subseções a seguir revêem como iniciar o X nos níveis de execução 3 e 5.

33.5.1. Nível de Execução 3

When in runlevel 3, the best way to start an X session is to log in and type startx. The startx command is a front-end to the xinit command, which launches the X server (Xorg) and connects X client applications to it. Because the user is already logged into the system at runlevel 3, startx does not launch a display manager or authenticate users. Refer to Seção 33.5.2, “Nível de Execução 5” for more information about display managers.
When the startx command is executed, it searches for the .xinitrc file in the user's home directory to define the desktop environment and possibly other X client applications to run. If no .xinitrc file is present, it uses the system default /etc/X11/xinit/xinitrc file instead.
The default xinitrc script then searches for user-defined files and default system files, including .Xresources, .Xmodmap, and .Xkbmap in the user's home directory, and Xresources, Xmodmap, and Xkbmap in the /etc/X11/ directory. The Xmodmap and Xkbmap files, if they exist, are used by the xmodmap utility to configure the keyboard. The Xresources file is read to assign specific preference values to applications.
After setting these options, the xinitrc script executes all scripts located in the /etc/X11/xinit/xinitrc.d/ directory. One important script in this directory is xinput.sh, which configures settings such as the default language.
Next, the xinitrc script attempts to execute .Xclients in the user's home directory and turns to /etc/X11/xinit/Xclients if it cannot be found. The purpose of the Xclients file is to start the desktop environment or, possibly, just a basic window manager. The .Xclients script in the user's home directory starts the user-specified desktop environment in the .Xclients-default file. If .Xclients does not exist in the user's home directory, the standard /etc/X11/xinit/Xclients script attempts to start another desktop environment, trying GNOME first and then KDE followed by twm.
Quando estiver em nível de execução 3, o usuário é retornado à sessão de usuário de modo texto após finalizar a sessão X.

33.5.2. Nível de Execução 5

Quando o sistema inicializa no nível de execução 5, um aplicativo de cliente X especial, chamado display manager, é lançado. Um usuário deve se autenticar usando o gestor de exibição antes de qualquer ambiente de desktop ou então os gestores de janela serão lançados.
Dependendo dos ambientes de desktop instalados em seu sistema, existirão três gestores de exibição disponíveis para manusear a autenticação do usuário.
  • GNOME — The default display manager for Red Hat Enterprise Linux, GNOME allows the user to configure language settings, shutdown, restart or log in to the system.
  • KDE — KDE's display manager which allows the user to shutdown, restart or log in to the system.
  • xdm — A very basic display manager which only lets the user log in to the system.
When booting into runlevel 5, the prefdm script determines the preferred display manager by referencing the /etc/sysconfig/desktop file. A list of options for this file is available in this file:
/usr/share/doc/initscripts-<version-number>/sysconfig.txt
where <version-number> is the version number of the initscripts package.
Each of the display managers reference the /etc/X11/xdm/Xsetup_0 file to set up the login screen. Once the user logs into the system, the /etc/X11/xdm/GiveConsole script runs to assign ownership of the console to the user. Then, the /etc/X11/xdm/Xsession script runs to accomplish many of the tasks normally performed by the xinitrc script when starting X from runlevel 3, including setting system and user resources, as well as running the scripts in the /etc/X11/xinit/xinitrc.d/ directory.
Users can specify which desktop environment they want to utilize when they authenticate using the GNOME or KDE display managers by selecting it from the Sessions menu item (accessed by selecting System (on the panel) > Preferences > More Preferences > Sessions). If the desktop environment is not specified in the display manager, the /etc/X11/xdm/Xsession script checks the .xsession and .Xclients files in the user's home directory to decide which desktop environment to load. As a last resort, the /etc/X11/xinit/Xclients file is used to select a desktop environment or window manager to use in the same way as runlevel 3.
When the user finishes an X session on the default display (:0) and logs out, the /etc/X11/xdm/TakeConsole script runs and reassigns ownership of the console to the root user. The original display manager, which continues running after the user logged in, takes control by spawning a new display manager. This restarts the X server, displays a new login window, and starts the entire process over again.
O usuário retorna ao gestor de exibição após sair do X a partir do nível de execução 5.
For more information on how display managers control user authentication, refer to the /usr/share/doc/gdm-<version-number>/README (where <version-number> is the version number for the gdm package installed) and the xdm man page.

33.6. Recursos Adicionais

Existe uma grande quantidade de informações detalhadas disponível sobre o servidor X, os clientes que se conectam à ele, e os ambientes de desktop varidados e gestores de janela.

33.6.1. Documentação Instalada

  • /usr/share/X11/doc/ — contains detailed documentation on the X Window System architecture, as well as how to get additional information about the Xorg project as a new user.
  • man xorg.conf — Contains information about the xorg.conf configuration files, including the meaning and syntax for the different sections within the files.
  • man Xorg — Describes the Xorg display server.

33.6.2. Sites Úteis

  • http://www.X.org/ — Home page do X.Org Foundation, que produz o lançamento do X11R7.1 do Sistema Window X. O lançamento X11R7.1 é vinculado ao Red Hat Enterprise Linux e controla hardware necessários e oferece um ambiente GUI.
  • http://dri.sourceforge.net/ — Home page do projeto DRI (Infraestrutura de Renderização Direta). O DRI é o componente de aceleração em 3D do harware central do X.
  • http://www.gnome.org/ — Diretório pessoal do projeto GNOME.
  • http://www.kde.org/ — Diretório pessoal do ambiente de desktop KDE.

Capítulo 34. Configuração do Sistema X Window

During installation, the system's monitor, video card, and display settings are configured. To change any of these settings after installation, use the X Configuration Tool.
To start the X Configuration Tool, go to System (on the panel) > Administration > Display, or type the command system-config-display at a shell prompt (for example, in an XTerm or GNOME terminal). If the X Window System is not running, a small version of X is started to run the program.
Após alterar alguma destas configurações, faça o log out da área de trabalho gráfica e autentique-se novamente para habilitar as alterações.

34.1. Display Settings

The Settings tab allows users to change the resolution and color depth. The display of a monitor consists of tiny dots called pixels. The number of pixels displayed at one time is called the resolution. For example, the resolution 1024x768 means that 1024 horizontal pixels and 768 vertical pixels are used. The higher the resolution values, the more images the monitor can display at one time.
A profundidade de cores da tela determina quantas cores possíveis são exibidas. Quanto maior a profundidade de cores, maior o contraste entre as cores.
Display Settings
Display Settings
Figura 34.1. Display Settings

34.2. Display Hardware Settings

When the X Configuration Tool is started, it probes the monitor and video card. If the hardware is probed properly, the information for it is shown on the Hardware tab as shown in Figura 34.2, “Display Hardware Settings”.
Display Hardware Settings
Display Hardware Settings
Figura 34.2. Display Hardware Settings

To change the monitor type or any of its settings, click the corresponding Configure button. To change the video card type or any of its settings, click the Configure button beside its settings.

34.3. Dual Head Display Settings

If multiple video cards are installed on the system, dual head monitor support is available and is configured via the Dual head tab, as shown in Figura 34.3, “Dual Head Display Settings”.
Dual Head Display Settings
Dual Head Display Settings
Figura 34.3. Dual Head Display Settings

To enable use of Dual head, check the Use dual head checkbox.
To configure the second monitor type, click the corresponding Configure button. You can also configure the other Dual head settings by using the corresponding drop-down list.
For the Desktop layout option, selecting Spanning Desktops allows both monitors to use an enlarged usable workspace. Selecting Individual Desktops shares the mouse and keyboard among the displays, but restricts windows to a single display.

Capítulo 35. Usuários e Grupos

O controle dos usuários e grupos é um elemento crucial da administração de sistemas do Red Hat Enterprise Linux
Os Usuários podem ser pessoas (ou seja, contas ligadas a usuários/pessoa física) ou contas que existem para aplicativos específicos para uso.
Os Grupos são expressões lógicas de organização, ligando usuários por um propósito em comum. Os usuários dentro de um determinado grupo, podem ler, escrever ou executar arquivos pertencentes a este grupo.
Cada usuário e grupo possui um número de identificação numérica único chamado de userid (UID) and a groupid (GID), respectivamente.
Um usuário que cria um arquivo é também o proprietário dele e do grupo do arquivo. O arquivo possui permissões de leitura, escrita e execução separado para o proprietário, o grupo e todos os outros. O arquivo proprietário pde ser modificado somente pelo usuário root, e o acesso à permissões pode ser modificado pelo usuário root ou pelo arquivo proprietário.
Red Hat Enterprise Linux also supports access control lists (ACLs) for files and directories which allow permissions for specific users outside of the owner to be set. For more information about ACLs, refer to Capítulo 9, Access Control Lists.

35.1. Configuração de Usuário e Grupo

The User Manager allows you to view, modify, add, and delete local users and groups.
To use the User Manager, you must be running the X Window System, have root privileges, and have the system-config-users RPM package installed. To start the User Manager from the desktop, go to System (on the panel) > Administration > Users & Groups. You can also type the command system-config-users at a shell prompt (for example, in an XTerm or a GNOME terminal).
User Manager
User Manager
Figura 35.1. User Manager

To view a list of local users on the system, click the Users tab. To view a list of local groups on the system, click the Groups tab.
To find a specific user or group, type the first few letters of the name in the Search filter field. Press Enter or click the Apply filter button. The filtered list is displayed.
Para classificar os usuários e grupos, clique no nome da coluna. Os usuários e grupos são classificados de acordo com o valor da coluna.
Red Hat Enterprise Linux reserves user IDs below 500 for system users. By default, User Manager does not display system users. To view all users, including the system users, go to Edit > Preferences and uncheck Hide system users and groups from the dialog box.

35.1.1. Adicionando um Novo Usuário

To add a new user, click the Add User button. A window as shown in Figura 35.2, “Novo Usuário” appears. Type the username and full name for the new user in the appropriate fields. Type the user's password in the Password and Confirm Password fields. The password must be at least six characters.

Tip

Recomenda-se usar uma senha com mais caracteres, pois dificulta que o intruso adivinhe a senha e acesse a conta sem permissão. Recomenda-se também que a senha não seja baseada em um termo de dicionário, use combinação de letras, números e caracteres especiais.
Select a login shell. If you are not sure which shell to select, accept the default value of /bin/bash. The default home directory is /home/<username>/. You can change the home directory that is created for the user, or you can choose not to create the home directory by unselecting Create home directory.
If you select to create the home directory, default configuration files are copied from the /etc/skel/ directory into the new home directory.
Red Hat Enterprise Linux uses a user private group (UPG) scheme. The UPG scheme does not add or change anything in the standard UNIX way of handling groups; it offers a new convention. Whenever you create a new user, by default, a unique group with the same name as the user is created. If you do not want to create this group, unselect Create a private group for the user.
To specify a user ID for the user, select Specify user ID manually. If the option is not selected, the next available user ID above 500 is assigned to the new user. Because Red Hat Enterprise Linux reserves user IDs below 500 for system users, it is not advisable to manually assign user IDs 1-499.
Click OK to create the user.
Novo Usuário
Criando um novo usuário
Figura 35.2. Novo Usuário

To configure more advanced user properties, such as password expiration, modify the user's properties after adding the user. Refer to Seção 35.1.2, “Modificando Propriedades do Usuário” for more information.

35.1.2. Modificando Propriedades do Usuário

To view the properties of an existing user, click on the Users tab, select the user from the user list, and click Properties from the menu (or choose File > Properties from the pulldown menu). A window similar to Figura 35.3, “Propriedades de Usuário” appears.
Propriedades de Usuário
Modificando propriedades de usuário
Figura 35.3. Propriedades de Usuário

The User Properties window is divided into multiple tabbed pages:
  • User Data — Shows the basic user information configured when you added the user. Use this tab to change the user's full name, password, home directory, or login shell.
  • Account Info Select Enable account expiration if you want the account to expire on a certain date. Enter the date in the provided fields. Select Local password is locked to lock the user account and prevent the user from logging into the system.
  • Password Info — Displays the date that the user's password last changed. To force the user to change passwords after a certain number of days, select Enable password expiration and enter a desired value in the Days before change required: field. The number of days before the user's password expires, the number of days before the user is warned to change passwords, and days before the account becomes inactive can also be changed.
  • Groups — Allows you to view and configure the Primary Group of the user, as well as other groups that you want the user to be a member of.

35.1.3. Adicionando um Novo Grupo

To add a new user group, click the Add Group button. A window similar to Figura 35.4, “Novo Grupo” appears. Type the name of the new group to create. To specify a group ID for the new group, select Specify group ID manually and select the GID. Note that Red Hat Enterprise Linux also reserves group IDs lower than 500 for system groups.
Novo Grupo
Criando um novo grupo
Figura 35.4. Novo Grupo

Click OK to create the group. The new group appears in the group list.

35.1.4. Modificando Propriedades de Grupo

To view the properties of an existing group, select the group from the group list and click Properties from the menu (or choose File > Properties from the pulldown menu). A window similar to Figura 35.5, “Propriedades de Grupo” appears.
Propriedades de Grupo
Modificando propriedades de grupo
Figura 35.5. Propriedades de Grupo

The Group Users tab displays which users are members of the group. Use this tab to add or remove users from the group. Click OK to save your changes.

35.2. Gerenciamento de Ferramentas de Usuário e Grupo

O gerenciamento de usuários e grupos pode ser uma tarefa um tanto tediosa. É por isso que o Red Hat Enterprise Linux oferece ferramentas e convenções que facilitam o gerenciamento.
The easiest way to manage users and groups is through the graphical application, User Manager (system-config-users). For more information on User Manager, refer to Seção 35.1, “Configuração de Usuário e Grupo”.
As seguintes ferramentas de linha de comando também podem ser usadas para gerenciar usuários e grupos:
  • useradd, usermod, and userdel — Industry-standard methods of adding, deleting and modifying user accounts
  • groupadd, groupmod, and groupdel — Industry-standard methods of adding, deleting, and modifying user groups
  • gpasswd — Industry-standard method of administering the /etc/group file
  • pwck, grpck — Tools used for the verification of the password, group, and associated shadow files
  • pwconv, pwunconv — Tools used for the conversion of passwords to shadow passwords and back to standard passwords

35.2.1. Configuração da Linha de Comando

Se você preferir ferramentas de linha de comando ou não tiver o Sistema Window X instalado, use esta seção para configurar usuários e grupos.

35.2.2. Adicionando um Usuário

Para adicionar um usuário a um sistema:
  1. Issue the useradd command to create a locked user account:
    useradd <username>
  2. Unlock the account by issuing the passwd command to assign a password and set password aging guidelines:
    passwd <username>
Command line options for useradd are detailed in Tabela 35.1, “useradd Command Line Options”.
Tabela 35.1. useradd Command Line Options
Opção Descrição
-c '<comment>' <comment> pode ser substituída por qualquer faixa. Esta opção é geralmente usada para especificar o nome completo de um usuário.
-d <home-dir> Home directory to be used instead of default /home/<username>/
-e <date> Data para a conta a ser desabilitada no formato YYYY-MM-DD
-f <days> Number of days after the password expires until the account is disabled. If 0 is specified, the account is disabled immediately after the password expires. If -1 is specified, the account is not be disabled after the password expires.
-g <group-name> Nome do grupo ou número do grupo para o grupo padrão do usuário. O grupo deve existir antes de ser especificado aqui.
-G <group-list> Lista de nomes de grupos adicionais (além do padrão), separado por vírgulas, do qual o usuário é membro. Os grupos devem existir antes de serem especificados aqui.
-m Criar o diretório pessoal se não existir.
-M Não criar o diretório pessoal.
-n Não criar o grupo privado de usuário para o mesmo.
-r Criar uma conta de sistema com um UID menor do que 500 e sem um diretório pessoal.
-p <password> The password encrypted with crypt
-s User's login shell, which defaults to /bin/bash
-u <uid> ID de usuário para o usuário, que deve ser único e maior do que 499.

35.2.3. Adicionando um Grupo

To add a group to the system, use the command groupadd:
groupadd <group-name>
Command line options for groupadd are detailed in Tabela 35.2, “groupadd Command Line Options”.
Tabela 35.2. groupadd Command Line Options
Opção Descrição
-g <gid> ID de Grupo para o grupo, que deve ser único e maior do que 499.
-r Criar um grupo de sistema com um GID menor do que 500.
-f Quando usado com -g <gid> e já existir o <gid>, ogroupadd escolherá outro <gid> único para o grupo.

35.2.4. Vencimento de Senhas

For security reasons, it is advisable to require users to change their passwords periodically. This can be done when adding or editing a user on the Password Info tab of the User Manager.
To configure password expiration for a user from a shell prompt, use the chage command with an option from Tabela 35.3, “chage Command Line Options”, followed by the username.

Importante

Shadow passwords must be enabled to use the chage command. For more information, see Seção 35.6, “Senhas Shadow”.
Tabela 35.3. chage Command Line Options
Opção Descrição
-m <days> Especifica uma quantia mínima de dias que o usuário deve trocar sua senha. Se o valor for 0, a senha não irá expirar.
-M <days> Especifica a quantia máxima de dias que uma senha é válida. Quando os dias especificados por esta opção mais os dias especificados na opção -d forem menores do que o dia atual, o usuário deve trocar as senhas antes de usar a conta.
-d <days> Especifica quantas vezes a senha foi trocada desde 1 de Janeiro de 1970
-I <days> Especifica quantos dias inativos se passaram desde que a senha expirou, antes de bloquear a conta. Se o valor for 0, a conta não será bloqueada após a senha expirar.
-E <date> Especifica a data em que a conta foi bloqueada, no formato AAAA-MM-DD. Ao invés da data, também pode ser usada a quantia de dias desde 1 de Janeiro de 1970.
-W <days> Especifica quantos dias antes da senha expirar, o usuário deve ser avisado.
-l Lists current account aging settings.

Tip

If the chage command is followed directly by a username (with no options), it displays the current password aging values and allows them to be changed interactively.
You can configure a password to expire the first time a user logs in. This forces users to change passwords immediately.
  1. Set up an initial password — There are two common approaches to this step. The administrator can assign a default password or assign a null password.
    To assign a default password, use the following steps:
    • Start the command line Python interpreter with the python command. It displays the following:
      Python 2.4.3 (#1, Jul 21 2006, 08:46:09)
      [GCC 4.1.1 20060718 (Red Hat 4.1.1-9)] on linux2
      Type "help", "copyright", "credits" or "license" for more information.
      >>>
    • Na janela de comandos, digite os seguintes comandos. Substitua <password> com a senha para criptografar <salt> e com uma combinação aleatória de ao menos 2 dos seguintes caractéres: qualquer um alfanumérico, a barra (/) ou um ponto (.):
      import crypt
      print crypt.crypt("<password>","<salt>")
      The output is the encrypted password, similar to '12CsGd8FRcMSM'.
    • Press Ctrl-D to exit the Python interpreter.
    • No shell, insira o seguinte comando (substituindo o <encrypted-password> com a saída criptografada do interpretador de Python):
      usermod -p "<encrypted-password>" <username>
    Como forma alternativa, você pode atribuir uma senha nula, ao invés de uma senha inicial. Para fazer isto, use o seguinte comando:
    usermod -p "" username

    Cuidado

    Usar uma senha nula, enquanto for conveniente, é uma prática altamente insegura, pois qualquer um pode se registrar primeiro para acessar o sistema usando um nome de usuário inseguro. Sempre tenha a certeza de que o usuário está pronto para se registrar antes de desbloquear uma conta com uma senha nula.
  2. Forçar expiração de senha imediatamente — Digite o seguinte comando:
    chage -d 0 username
    Este comando configura o valor para a última vez que a senha foi trocada para epoch (1 de Janeiro de 1970). Este valor força a expiração da senha imediatamente, não importando qual a política vigente de vencimento da senha, caso haja alguma.
Upon the initial log in, the user is now prompted for a new password.

35.2.5. Explicando o Processo

The following steps illustrate what happens if the command useradd juan is issued on a system that has shadow passwords enabled:
  1. A new line for juan is created in /etc/passwd. The line has the following characteristics:
    • It begins with the username juan.
    • There is an x for the password field indicating that the system is using shadow passwords.
    • É criado um UID maior do que 499. (sob o Red Hat Enterprise Linux, os UIDs e GIDs abaixo de 500 são reservados para uso do sistema.)
    • É criado um GID maior do que 499.
    • As informações GECOS opcionais são deixadas em branco.
    • The home directory for juan is set to /home/juan/.
    • The default shell is set to /bin/bash.
  2. A new line for juan is created in /etc/shadow. The line has the following characteristics:
    • It begins with the username juan.
    • Two exclamation points (!!) appear in the password field of the /etc/shadow file, which locks the account.

      Nota

      If an encrypted password is passed using the -p flag, it is placed in the /etc/shadow file on the new line for the user.
    • A senha é ajustada para nunca expirar.
  3. A new line for a group named juan is created in /etc/group. A group with the same name as a user is called a user private group. For more information on user private groups, refer to Seção 35.1.1, “Adicionando um Novo Usuário”.
    The line created in /etc/group has the following characteristics:
    • It begins with the group name juan.
    • An x appears in the password field indicating that the system is using shadow group passwords.
    • The GID matches the one listed for user juan in /etc/passwd.
  4. A new line for a group named juan is created in /etc/gshadow. The line has the following characteristics:
    • It begins with the group name juan.
    • An exclamation point (!) appears in the password field of the /etc/gshadow file, which locks the group.
    • Todos os outros campos permanecem em branco.
  5. A directory for user juan is created in the /home/ directory. This directory is owned by user juan and group juan. However, it has read, write, and execute privileges only for the user juan. All other permissions are denied.
  6. The files within the /etc/skel/ directory (which contain default user settings) are copied into the new /home/juan/ directory.
At this point, a locked account called juan exists on the system. To activate it, the administrator must next assign a password to the account using the passwd command and, optionally, set password aging guidelines.

35.3. Usuários Padrão

Tabela 35.4, “Usuários Padrão” lists the standard users configured in the /etc/passwd file by an Everything installation. The groupid (GID) in this table is the primary group for the user. See Seção 35.4, “Grupos Padrão” for a listing of standard groups.
Tabela 35.4. Usuários Padrão
Usuário UID GID Diretório Pessoal Shell
root 0 0 /root /bin/bash
bin 1 1 /bin /sbin/nologin
daemon 2 2 /sbin /sbin/nologin
adm 3 4 /var/adm /sbin/nologin
lp 4 7 /var/spool/lpd /sbin/nologin
sync 5 0 /sbin /bin/sync
fechar 6 0 /sbin /sbin/shutdown
saltar 7 0 /sbin /sbin/halt
correio 8 12 /var/spool/mail /sbin/nologin
notícias 9 13 /etc/news
uucp 10 14 /var/spool/uucp /sbin/nologin
operador 11 0 /root /sbin/nologin
jogos 12 100 /usr/games /sbin/nologin
gopher 13 30 /var/gopher /sbin/nologin
ftp 14 50 /var/ftp /sbin/nologin
ninguém 99 99 / /sbin/nologin
rpm 37 37 /var/lib/rpm /sbin/nologin
vcsa 69 69 /dev /sbin/nologin
dbus 81 81 / /sbin/nologin
ntp 38 38 /etc/ntp /sbin/nologin
canna 39 39 /var/lib/canna /sbin/nologin
nscd 28 28 / /sbin/nologin
rpc 32 32 / /sbin/nologin
postfix 89 89 /var/spool/postfix /sbin/nologin
carteiro 41 41 /var/mailman /sbin/nologin
chamado 25 25 /var/named /bin/false
amanda 33 6 var/lib/amanda/ /bin/bash
postgres 26 26 /var/lib/pgsql /bin/bash
exim 93 93 /var/spool/exim /sbin/nologin
sshd 74 74 /var/empty/sshd /sbin/nologin
rpcuser 29 29 /var/lib/nfs /sbin/nologin
nsfnobody 65534 65534 /var/lib/nfs /sbin/nologin
pvm 24 24 /usr/share/pvm3 /bin/bash
apache 48 48 /var/www /sbin/nologin
xfs 43 43 /etc/X11/fs /sbin/nologin
gdm 42 42 /var/gdm /sbin/nologin
htt 100 101 /usr/lib/im /sbin/nologin
mysql 27 27 /var/lib/mysql /bin/bash
webalizer 67 67 /var/www/usage /sbin/nologin
correio nulo 47 47 /var/spool/mqueue /sbin/nologin
smmsp 51 51 /var/spool/mqueue /sbin/nologin
squid 23 23 /var/spool/squid /sbin/nologin
ldap 55 55 /var/lib/ldap /bin/false
netdump 34 34 /var/crash /bin/bash
pcap 77 77 /var/arpwatch /sbin/nologin
radiusd 95 95 / /bin/false
radvd 75 75 / /sbin/nologin
quagga 92 92 /var/run/quagga /sbin/login
wnn 49 49 /var/lib/wnn /sbin/nologin
dovecot 97 97 /usr/libexec/dovecot /sbin/nologin

35.4. Grupos Padrão

Tabela 35.5, “Grupos Padrão” lists the standard groups configured by an Everything installation. Groups are stored in the /etc/group file.
Tabela 35.5. Grupos Padrão
Grupo GID Membros
root 0 root
bin 1 root, bin, daemon
daemon 2 root, bin, daemon
sys 3 root, bin, adm
adm 4 root, adm, daemon
tty 5
disco 6 root
lp 7 daemon, lp
mem 8
kmem 9
wheel 10 root
correio 12 mail, postfix, exim
notícias 13 notícias
uucp 14 uucp
man 15
jogos 20
gopher 30
dip 40
ftp 50
bloquear 54
ninguém 99
users 100
rpm 37
utmp 22
floppy 19
vcsa 69
dbus 81
ntp 38
canna 39
nscd 28
rpc 32
postdrop 90
postfix 89
carteiro 41
exim 93
chamado 25
postgres 26
sshd 74
rpcuser 29
nfsnobody 65534
pvm 24
apache 48
xfs 43
gdm 42
htt 101
mysql 27
webalizer 67
correio nulo 47
smmsp 51
squid 23
ldap 55
netdump 34
pcap 77
quaggavt 102
quagga 92
radvd 75
slocate 21
wnn 49
dovecot 97
radiusd 95

35.5. Brupos Privados de Usuários

O Red Hat Enterprise Linux usa um esquema de grupo de usuário privado (UPG), que facilita o gerenciamento dos grupos UNIX.
Será criado um UPG todas as vezes que um novo usuário for adicionado ao sistema. O UPG tem o mesmo nome do usuário para o qual foi criado, e este usuário é o único membro do UPG.
Os UPGs tornam as permissões padrão seguras, para arquivo ou diretórios recém criados, permitindo que o usuário e o grupo daquele usuário façam modificações ao arquivo ou diretório.
The setting which determines what permissions are applied to a newly created file or directory is called a umask and is configured in the /etc/bashrc file. Traditionally on UNIX systems, the umask is set to 022, which allows only the user who created the file or directory to make modifications. Under this scheme, all other users, including members of the creator's group, are not allowed to make any modifications. However, under the UPG scheme, this "group protection" is not necessary since every user has their own private group.

35.5.1. Diretórios de Grupo

Muitas empresas de TI gostam de criar um grupo para cada grande projeto e depois atribuir pessoas ao grupo, caso precisem acessar os arquivos daqueles projetos. O uso deste esquema tradicional pode dificultar o gerenciamento de arquivos. Quando alguém cria um arquivo ele está associado ao grupo primário ao qual ele pertence. Quando uma única pessoa trabalha com projetos múltiplos, é difícil de associar os arquivos corretos com o grupo correto. Usar um esquema UPG, no entanto, atribui automaticamente grupos aos arquivos criados com um diretório com o conjunto de bit setgid. O bit setgid faz projetos de grupo de gerenciamento que compartilham de um diretório muito simples em comum, pois qualquer arquivo que um usuário cria dentro de um diretório é de propriedade de um grupo que possui um diretório.
Let us say, for example, that a group of people need to work on files in the /usr/share/emacs/site-lisp/ directory. Some people are trusted to modify the directory, but certainly not everyone is trusted. First create an emacs group, as in the following command:
groupadd emacs
To associate the contents of the directory with the emacs group, type:
chown -R root.emacs /usr/share/emacs/site-lisp
Now, it is possible to add the proper users to the group with the gpasswd command:
gpasswd -a <username> emacs
Para permitir que usuários criem arquivos dentro do diretório, use o seguinte comando:
chmod 775 /usr/share/emacs/site-lisp
When a user creates a new file, it is assigned the group of the user's default private group. Next, set the setgid bit, which assigns everything created in the directory the same group permission as the directory itself (emacs). Use the following command:
chmod 2775 /usr/share/emacs/site-lisp
At this point, because the default umask of each user is 002, all members of the emacs group can create and edit files in the /usr/share/emacs/site-lisp/ directory without the administrator having to change file permissions every time users write new files.

35.6. Senhas Shadow

In multiuser environments it is very important to use shadow passwords (provided by the shadow-utils package). Doing so enhances the security of system authentication files. For this reason, the installation program enables shadow passwords by default.
A seguir listamos as vantagens que as senhas shadow possuem sob a forma tradicional de armazenar as senhas nos sistemas baseados em UNIX:
  • Improves system security by moving encrypted password hashes from the world-readable /etc/passwd file to /etc/shadow, which is readable only by the root user.
  • Armazena informações sobre o vencimento de senha.
  • Allows the use the /etc/login.defs file to enforce security policies.
Most utilities provided by the shadow-utils package work properly whether or not shadow passwords are enabled. However, since password aging information is stored exclusively in the /etc/shadow file, any commands which create or modify password aging information do not work.
Segue uma lista dos comandos que não funcionam sem primeiro habilitar senhas shadow:
  • chage
  • gpasswd
  • /usr/sbin/usermod -e or -f options
  • /usr/sbin/useradd -e or -f options

35.7. Recursos Adicionais

Para mais informações sobre usuários e grupos e ferramentas para gerenciá-las, consulte os seguintes recursos:

35.7.1. Documentação Instalada

  • Páginas man relacionadas — Existem diversas páginas man para diversos aplicativos e arquivos de configuração envolvidos com usuários de gerenciamento e grupos. Algumas das páginas man mais importantes foram listadas aqui:
    Aplicativos Administrativos de Usuários e Grupos
    • man chage — A command to modify password aging policies and account expiration.
    • man gpasswd — A command to administer the /etc/group file.
    • man groupadd — A command to add groups.
    • man grpck — A command to verify the /etc/group file.
    • man groupdel — A command to remove groups.
    • man groupmod — A command to modify group membership.
    • man pwck — A command to verify the /etc/passwd and /etc/shadow files.
    • man pwconv — A tool to convert standard passwords to shadow passwords.
    • man pwunconv — A tool to convert shadow passwords to standard passwords.
    • man useradd — A command to add users.
    • man userdel — A command to remove users.
    • man usermod — A command to modify users.
    Arquivos de Configuração
    • man 5 group — The file containing group information for the system.
    • man 5 passwd — The file containing user information for the system.
    • man 5 shadow — The file containing passwords and account expiration information for the system.

Capítulo 36. Configuração da Impressora

A Printer Configuration Tool permite que os usuários configurem uma impressora. Esta ferramenta ajuda a manter o arquivo de configuração da impressora, os diretórios spool e filtros de impressão.
Red Hat Enterprise Linux 5.8 uses the Common Unix Printing System (CUPS). If a system was upgraded from a previous Red Hat Enterprise Linux version that used CUPS, the upgrade process preserves the configured queues.
Using Printer Configuration Tool requires root privileges. To start the application, select System (on the panel) > Administration > Printing, or type the command system-config-printer at a shell prompt.
Printer Configuration Tool
Janela principal
Figura 36.1. Printer Configuration Tool

Os seguintes tipos de filas de impressão podem ser configurados:
  • JetDirect em Rede — uma impressora conectada diretamente à rede, através da HP JetDirect, ao invés de conectada ao computador.
  • Protocolo de Impressão de Internet (IPP) — uma impressora que pode ser acessada através de uma rede TCP/IP pelo Protocolo de Impressão da Internet, também conhecido como IPP (ex.: uma impressora conectada a um outro sistema Red Hat Enterprise Linux rodando o CUPS na rede).
  • Host LPD/LPR ou Impressora — uma impressora conectada a um sistema UNIX diferente, que pode ser acessado através de uma rede TCP/IP (ex.: uma impressora conectada a um outro sistema Red Hat Enterprise Linux rodando LPD na rede).
  • Windows em Rede (SMB) — uma impressora conectada a um sistema diferente, que compartilha uma impressora através de uma rede SMB (ex.: uma impressora conectada a uma máquina com Microsoft Windows™).
  • JetDirect em Rede — uma impressora conectada diretamente à rede, através da HP JetDirect, ao invés de conectada ao computador.

Importante

Se você adicionar uma nova fila de impressão ou modificar uma fila existente, deve aplicar as alterações para que tenham efeito.
Clique no botão Aplicarpara solicitar que o daemon da impressora reinicie com as mudanças que você configurou.
Clique em Reverter para discartar mudanças não aplicadas.

36.1. Adicionando uma Impressora Local.

To add a local printer, such as one attached through a parallel port or USB port on your computer, click the New Printer button in the main Printer Configuration Tool window to display the window in Figura 36.2, “Adding a Printer.
Adding a Printer
Adicionando uma Impressora
Figura 36.2. Adding a Printer

Clique em Próximo para continuar.
Entre um nome único para a impressora no campo Nome da Impressora. O nome de uma impressora pode conter letras, números, hífens (-) e sublinhados (_) no entanto, não deve conter espaços.
Você também pode usar os campos Descrição e Local para distinguir futuramente, esta impressora de outras que podem estar configuradas no seu sistema. Ambos os campos são opcionais, e podem conter espaços.
Click Forward to open the New Printer dialogue (refer to Figura 36.3, “Adicionando uma Impressora Local.”). If the printer has been automatically detected, the printer model appears in Select Connection. Select the printer model and click Forward to continue.
Se o dispositivo não aparecer automaticamente, selecione o dispositivo ao qual a impressora estiver conectada (tal como LPT #1 ou Porta Serial #1) em Selecione uma Conexão.
Adicionando uma Impressora Local.
Adicionando uma impressora local
Figura 36.3. Adicionando uma Impressora Local.

Next, select the printer type. Refer to Seção 36.5, “Selecionando o Modelo da Impressora e Finalizando” for details.

36.2. Adicionando uma Impressora IPP

Uma impressora IPP é uma impressora anexada a um sistema diferente na mesma rede TCP/IP. O sistema que esta impressora é anexada, pode estar rodando o CUPS ou simplesmete configurado para usar IPP.
Se você tiver um firewall configurado no servidor de impressão, deve ser capaz de enviar e receber conexões na porta UDP de entrada - 631. Se tiver um firewall configurado no cliente (o computador que envia o pedido de impressão), deve ser capaz de enviar e aceitar conexões na porta 631.
You can add a networked IPP printer by clicking the New Printer button in the main Printer Configuration Tool window to display the window in Figura 36.2, “Adding a Printer. Enter the Printer Name (printer names cannot contain spaces and may contain letters, numbers, dashes (-), and underscores (_)), Description, and Location to distinguish this printer from others that you may configure on your system. Click Forward to proceed.
In the window shown in Figura 36.4, “Adicionando uma Impressora IPP”, enter the hostname of the IPP printer in the Hostname field as well as a unique name for the printer in the Printername field.
Adicionando uma Impressora IPP
Impressora IPP em Rede
Figura 36.4. Adicionando uma Impressora IPP

Clique em Próximo para continuar.
Next, select the printer type. Refer to Seção 36.5, “Selecionando o Modelo da Impressora e Finalizando” for details.

36.3. Adicionando uma Impressora Samba (SMB)

You can add a Samba (SMB) based printer share by clicking the New Printer button in the main Printer Configuration Tool window to display the window in Figura 36.2, “Adding a Printer. Enter a unique name for the printer in the Printer Name field. The printer name can contain letters, numbers, dashes (-), and underscores (_); it must not contain any spaces.
Você também pode usar os campos Descrição e Local para distinguir futuramente, esta impressora de outras que podem estar configuradas no seu sistema. Ambos os campos são opcionais, e podem conter espaços.
Adicionando uma Impressora SMB
Impressora SMB
Figura 36.5. Adicionando uma Impressora SMB

As shown in Figura 36.5, “Adicionando uma Impressora SMB ”, available SMB shares are automatically detected and listed in the Share column. Click the arrow ( ) beside a Workgroup to expand it. From the expanded list, select a printer.
If the printer you are looking for does not appear in the list, enter the SMB address in the smb:// field. Use the format computer name/printer share. In Figura 36.5, “Adicionando uma Impressora SMB ”, the computer name is dellbox, while the printer share is r2.
No campo Nome de usuário, digite o nome de usuário a acessar a impressora. Este usuário deve existir no sistema Windows e deve ter permissões para acessar a impressora. O nome de usuário padrão geralmente é guest para servidores Windows ou nobody para servidores Samba.
Digite a Senha (se requisitada) para o usuário especificado no campo Usuário.
Agora você pode testar a conexão, clicando em Verificar. Em uma verificação bem sucedida, aparecerá uma caixa de diálogo confirmando a acessibilidade da cota de impressora.
Next, select the printer type. Refer to Seção 36.5, “Selecionando o Modelo da Impressora e Finalizando” for details.

Atenção

Os nomes de usuários e senhas da impressora Samba estão armazenadas no servidor da impressora como arquivos não criptografados pelo root e lpd. Assim, outros usuários que não possuam acesso root ao servidor da impressora, poderão visualizar o nome de usuário e senha que você usa para acessar a impressora Samba.
Como tal, ao escolher um nome de usuário e senha para acessar uma impressora Samba, recomenda-se que você escolha uma senha que seja diferente daquela que você utiliza para acessar seu sistema local Red Hat Enterprise Linux.
Caso existam arquivos compartilhados no servidor de impressão do Samba, recomenda-se que também utilizem uma senha diferente daquele que é usada pela fila de impressão.

36.4. Adding a JetDirect Printer

To add a JetDirect or AppSocket connected printer share, click the New Printer button in the main Printer Configuration Tool window to display the window in Figura 36.2, “Adding a Printer. Enter a unique name for the printer in the Printer Name field. The printer name can contain letters, numbers, dashes (-), and underscores (_); it must not contain any spaces.
Você também pode usar os campos Descrição e Local para distinguir futuramente, esta impressora de outras que podem estar configuradas no seu sistema. Ambos os campos são opcionais, e podem conter espaços.
Adding a JetDirect Printer
Adding a JetDirect Printer
Figura 36.6. Adding a JetDirect Printer

Clique em Próximo para continuar.
Aparecem os campos de texto das seguintes opções:
  • Nome da Máquina — O nome da máquina (hostname) ou o endereço IP da impressora JetDirect.
  • Número da Porta — A porta da impressora JetDirect que escuta (recebe) tarefas de impressão. A porta padrão é 9100.
Next, select the printer type. Refer to Seção 36.5, “Selecionando o Modelo da Impressora e Finalizando” for details.

36.5. Selecionando o Modelo da Impressora e Finalizando

Quando você tiver selecionado corretamente um tipo de fila de impressora, você poderá escolher qualquer uma dessas opções:
  • Selecione uma Impressora a partir do banco de dados - Se você selecionar esta opção, escolha a marca de sua impressora a partir da lista de Marcas. Se a marca da sua impressora não estiver listada, selecione Genérico.
  • Fornecer arquivo PPD - Um arquivo de Descrição de Impressora de PostScript (PPD) também pode ser fornecido com sua impressora. Este arquivo é geralmente fornecdio pelo fabricante. Se você receber um arquivo PPD, você poderá escolher esta opção e usar a barra de navegação abaixo da descrição da opção para selecionar o arquivo PPD.
Selecting a Printer Model
Selecting a Printer Model
Figura 36.7. Selecting a Printer Model

After choosing an option, click Forward to continue. Figura 36.7, “Selecting a Printer Model” appears. You now have to choose the corresponding model and driver for the printer.
O driver de impressão recomendado é selecionado baseado no modelo da impressora. O driver de impressão processa os dados que você deseja imprimir em um formato que a impressora possa entender. Como há uma impressora local conectada diretamente ao seu computador, você precisa de um driver de impressão para processar os dados que são enviados à impressora.
Se você tiver um arquivo PPD para o dispositivo (geralmente oferecido pelo fabricante), você pode selecioná-lo escolhendo o Forneça o arquivo PPD. Você então pode navegar através do sistema de arquivo do arquivo PPD clicando em Procurar.

36.5.1. Confirmando a Configuração da Impressora

O último passo é confirmar a configuração de sua impressora. Clique em Aplicar (Apply) para adicionar a fila de impressão se a configuração estiver correta. Clique em Voltar (Back) para modificar a configuração da impressora.
After applying the changes, print a test page to ensure the configuration is correct. Refer to Seção 36.6, “Imprimindo uma Página de Teste” for details.

36.6. Imprimindo uma Página de Teste

Após configurar sua impressora, você deve imprimir uma página de teste para garantir que a impressora esteja funcionando corretamente. Para fazer isso, selecione a impressora que deseja testar na lista de impressoras, e clique em Imprimir Página de Teste na aba Configurações da impressora.
Se você alterar o driver da impressora ou as opções do driver, deve imprimir uma página de teste para testar a configuração modificada.

36.7. Modificando Impressoras Existentes

Para apagar uma impressora existente, selecione-a e clique no botão Apagar na barra de ferramentas. A impressora é removida da lista da impressora quando você confirmar que retirou da configuração da impressora.
Para configurar a impressora padrão, selecione a impressora a partir da lista de impressora e clique no botão Tornar Impressora Padrão na aba Configurações

36.7.1. A Aba Configurações

Para mudar a configuração do driver, clique no nome correspondente na lista da Impressora e clique na aba Configurações.
Você pode modificar as configurações da impressora, tais como a marca e modelo, tornar uma impressora padrão, imprimir uma página de teste, mudar o local do dispositivo (URI) entre outras funções.
Settings Tab
Settings Tab
Figura 36.8. Settings Tab

36.7.2. A Aba Políticas

Para modificar as configurações na saída de impressão, clique na aba Políticas
Por exemplo, para criar uma página de banner (uma página que descreve aspectos do trabalho de impressão tal como originar uma impressora, o nome do usuário do qual o trabalho foi originado, e o status de segurança do documento sendo impresso) clique em Iniciar Banner ou Finalizar Banner, abra o menu e escolha a opção que melhor descreve a naturesa dos trabalhos de impressão (tais como,topsecret, classified, or confidential).
Policies Tab
Policies Tab
Figura 36.9. Policies Tab

Você também pode configurar a Política de Erros da impressora, selecionando uma opção a partir do menu suspenso. Você pode escolher abortar ou parar o trabalho de impressão.

36.7.3. A Aba Controle de Acesso

Você pode modificar o acesso de nível de usuário para a impressora configurada, clicando a aba Controle de Acesso
Adicione usuários usando a caixa de texto e clique no botão ao lado com Adicionar.
Access Control Tab
Access Control Tab
Figura 36.10. Access Control Tab

36.7.4. A Aba Impressora e a Aba Opções de Trabalho

A aba Opções de Impressora contém diversas opções de configuração para a mídia e saída.
Aba de Opções de Impressora
Aba de Trabalhos de Impressora
Figura 36.11. Aba de Opções de Impressora

  • Tamanho da Página — Permite que o tamanho do papel seja selecionado. As opções incluem US Letter, US Legal, A3, and A4.
  • Recurso de Mídia — configurado para Automático por padrão. Mude esta opção para usar papel de uma bandeja diferente.
  • Tipo de Mídia — Permite que você modifique o tipo de papel. Entre as opções constam: Simples, Espesso, bonde e transparência.
  • Resolução — Configura a qualidade e detalhe da impressão. O padrão é 300 pontos por polegadas (dpi).
  • Economia de Toner — Selecione a opção de uso de menos toner da impressora para conservar recursos.
Você também pode configurar as opções de trabalho de impressora usando a aba Opções de Trabalho. Use o menu suspenso e escolha as opções de trabalho que você desejar usar, tais como os modos Paisagem (impressões em horizontal ou vertical), cópias, ou escala (aumentar ou diminuir o tamanho da área de impressão, que geralmente ajusta a página à área de impressão).

36.8. Gerenciando Tarefas de Impressão

When you send a print job to the printer daemon, such as printing a text file from Emacs or printing an image from The GIMP, the print job is added to the print spool queue. The print spool queue is a list of print jobs that have been sent to the printer and information about each print request, such as the status of the request, the job number, and more.
During the printing process, the Printer Status icon appears in the Notification Area on the panel. To check the status of a print job, double click the Printer Status, which displays a window similar to Figura 36.12, “GNOME Print Status”.
GNOME Print Status
GNOME Print Status
Figura 36.12. GNOME Print Status

To cancel a specific print job listed in the GNOME Print Status, select it from the list and select Edit > Cancel Documents from the pulldown menu.
Para visualizar a lista das tarefas no spool de impressão a partir de uma janela de comandos, digite o comando lpq. As últimas linhas se parecerão com o seguinte:
Exemplo 36.1. Exemplo de saída do lpq
Rank   Owner/ID              Class  Job Files       Size Time 
active user@localhost+902    A      902 sample.txt  2050 01:20:46

If you want to cancel a print job, find the job number of the request with the command lpq and then use the command lprm job number. For example, lprm 902 would cancel the print job in Exemplo 36.1, “Exemplo de saída do lpq. You must have proper permissions to cancel a print job. You can not cancel print jobs that were started by other users unless you are logged in as root on the machine to which the printer is attached.
Você também pode imprimir um arquivo diretamente de uma janela de comandos. Por exemplo: o comando lpr sample.txt imprimirá o arquivo texto sample.txt. O filtro de impressão determina qual o tipo do arquivo e converte-o em um formato que a impressora possa entender.

36.9. Recursos Adicionais

Para aprender mais sobre a impressão no Red Hat Enterprise Linux, consulte os seguintes recursos:

36.9.1. Documentação Instalada

  • map lpr — The manual page for the lpr command that allows you to print files from the command line.
  • man lprm — A página do manual para o utilitário de linha de comando para remover tarefas de impressão da fila de impressão.
  • man mpage — A página do manual para o utilitário de linha de comando para imprimir páginas múltiplas em uma folha de papel.
  • man cupsd — A página do manual para o daemon da impressora CUPS.
  • man cupsd.conf — A página do manual para o arquivo de configuração do daemon da impressora CUPS.
  • man classes.conf — A página do manual para o arquivo de configuração de classe do CUPS.

36.9.2. Sites Úteis

Capítulo 37. Automated Tasks

In Linux, tasks can be configured to run automatically within a specified period of time, on a specified date, or when the system load average is below a specified number. Red Hat Enterprise Linux is pre-configured to run important system tasks to keep the system updated. For example, the slocate database used by the locate command is updated daily. A system administrator can use automated tasks to perform periodic backups, monitor the system, run custom scripts, and more.
Red Hat Enterprise Linux comes with several automated tasks utilities: cron, at, and batch.

37.1. Cron

O Cron é um daemon que pode ser utilizado para agendar a execução de tarefas recorrentes de acordo com uma combinação de hora, dia do mês, mês, dia da semana e semana.
Cron assumes that the system is on continuously. If the system is not on when a task is scheduled, it is not executed. To schedule one-time tasks, refer to Seção 37.2, “At e Batch”.
To use the cron service, the vixie-cron RPM package must be installed and the crond service must be running. To determine if the package is installed, use the rpm -q vixie-cron command. To determine if the service is running, use the command /sbin/service crond status.

37.1.1. Configurando Tarefas no Cron

The main configuration file for cron, /etc/crontab, contains the following lines:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root HOME=/
# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
The first four lines are variables used to configure the environment in which the cron tasks are run. The SHELL variable tells the system which shell environment to use (in this example the bash shell), while the PATH variable defines the path used to execute commands. The output of the cron tasks are emailed to the username defined with the MAILTO variable. If the MAILTO variable is defined as an empty string (MAILTO=""), email is not sent. The HOME variable can be used to set the home directory to use when executing commands or scripts.
Each line in the /etc/crontab file represents a task and has the following format:
minute   hour   day   month   dayofweek   command
  • minute — any integer from 0 to 59
  • hour — any integer from 0 to 23
  • day — any integer from 1 to 31 (must be a valid day if a month is specified)
  • month — any integer from 1 to 12 (or the short name of the month such as jan or feb)
  • dayofweek — any integer from 0 to 7, where 0 or 7 represents Sunday (or the short name of the week such as sun or mon)
  • command — the command to execute (the command can either be a command such as ls /proc >> /tmp/proc or the command to execute a custom script)
Para qualquer um dos valores acima, pode ser usado um asterisco (*) para especificar todos os valores válidos. Por exemplo: um asterisco no valor mês significa que o comando deve ser executado todo mês segundo as restrições dos outros valores.
A hyphen (-) between integers specifies a range of integers. For example, 1-4 means the integers 1, 2, 3, and 4.
A list of values separated by commas (,) specifies a list. For example, 3, 4, 6, 8 indicates those four specific integers.
The forward slash (/) can be used to specify step values. The value of an integer can be skipped within a range by following the range with /<integer>. For example, 0-59/2 can be used to define every other minute in the minute field. Step values can also be used with an asterisk. For instance, the value */3 can be used in the month field to run the task every third month.
Quaisquer linhas que iniciem com o jogo da velha (#) são comentários e não são processados.
As shown in the /etc/crontab file, the run-parts script executes the scripts in the /etc/cron.hourly/, /etc/cron.daily/, /etc/cron.weekly/, and /etc/cron.monthly/ directories on an hourly, daily, weekly, or monthly basis respectively. The files in these directories should be shell scripts.
If a cron task is required to be executed on a schedule other than hourly, daily, weekly, or monthly, it can be added to the /etc/cron.d/ directory. All files in this directory use the same syntax as /etc/crontab. Refer to Exemplo 37.1, “Exemplos de crontab” for examples.
Exemplo 37.1. Exemplos de crontab
# record the memory usage of the system every monday
# at 3:30AM in the file /tmp/meminfo
30 3 * * mon cat /proc/meminfo >> /tmp/meminfo
# run custom script the first day of every month at 4:10AM
10 4 1 * * /root/scripts/backup.sh

Users other than root can configure cron tasks by using the crontab utility. All user-defined crontabs are stored in the /var/spool/cron/ directory and are executed using the usernames of the users that created them. To create a crontab as a user, login as that user and type the command crontab -e to edit the user's crontab using the editor specified by the VISUAL or EDITOR environment variable. The file uses the same format as /etc/crontab. When the changes to the crontab are saved, the crontab is stored according to username and written to the file /var/spool/cron/username.
The cron daemon checks the /etc/crontab file, the /etc/cron.d/ directory, and the /var/spool/cron/ directory every minute for any changes. If any changes are found, they are loaded into memory. Thus, the daemon does not need to be restarted if a crontab file is changed.

37.1.2. Controlando Acesso ao Cron

The /etc/cron.allow and /etc/cron.deny files are used to restrict access to cron. The format of both access control files is one username on each line. Whitespace is not permitted in either file. The cron daemon (crond) does not have to be restarted if the access control files are modified. The access control files are read each time a user tries to add or delete a cron task.
O usuário root pode usar o cron sempre, independentemente dos nomes de usuário listados nos arquivos de controle de acesso.
If the file cron.allow exists, only users listed in it are allowed to use cron, and the cron.deny file is ignored.
If cron.allow does not exist, users listed in cron.deny are not allowed to use cron.

37.1.3. Iniciando e Parando o Serviço

To start the cron service, use the command /sbin/service crond start. To stop the service, use the command /sbin/service crond stop. It is recommended that you start the service at boot time. Refer to Capítulo 17, Controlando Acesso aos Serviços for details on starting the cron service automatically at boot time.

37.2. At e Batch

While cron is used to schedule recurring tasks, the at command is used to schedule a one-time task at a specific time and the batch command is used to schedule a one-time task to be executed when the systems load average drops below 0.8.
To use at or batch, the at RPM package must be installed, and the atd service must be running. To determine if the package is installed, use the rpm -q at command. To determine if the service is running, use the command /sbin/service atd status.

37.2.1. Configurando Trabalhos com At

To schedule a one-time job at a specific time, type the command at time, where time is the time to execute the command.
O argumento hora pode ser um dos seguintes:
  • Formato HH:MM — Por exemplo: 04:00 especifica 4:00AM. Se a hora já passou, será executado na hora especificada no dia seguinte.
  • midnight — Especifica 12:00AM.
  • noon — Especifica 12:00PM.
  • teatime — Especifica 4:00PM.
  • Formato nome-do-mês dia ano — Por exemplo: January 15 2004 especifica o 15o dia de Janeiro no ano 2004. O ano é opcional.
  • Formatos MMDDYY, MM/DD/YY, ou MM.DD.YY — Por exemplo: 011504 para o 15o dia de Janeiro no ano 2004.
  • now + time — hora em minutos, horas, dias ou semanas. Por exemplo: 'now + 5 days' especifica que o comando deve ser executado na mesma hora daqui cinco dias.
The time must be specified first, followed by the optional date. For more information about the time format, read the /usr/share/doc/at-<version>/timespec text file.
After typing the at command with the time argument, the at> prompt is displayed. Type the command to execute, press Enter, and type Ctrl+D . Multiple commands can be specified by typing each command followed by the Enter key. After typing all the commands, press Enter to go to a blank line and type Ctrl+D . Alternatively, a shell script can be entered at the prompt, pressing Enter after each line in the script, and typing Ctrl+D on a blank line to exit. If a script is entered, the shell used is the shell set in the user's SHELL environment, the user's login shell, or /bin/sh (whichever is found first).
Se o conjunto de comandos ou script tentar exibir informações para a saída default (standard out), o output é enviado por e-mail ao usuário.
Use the command atq to view pending jobs. Refer to Seção 37.2.3, “Visualizando Trabalhos Pendentes” for more information.
Usage of the at command can be restricted. For more information, refer to Seção 37.2.5, “Controlando o Acesso a At e Batch” for details.

37.2.2. Configurando Trabalhos com o Batch

To execute a one-time task when the load average is below 0.8, use the batch command.
After typing the batch command, the at> prompt is displayed. Type the command to execute, press Enter, and type Ctrl+D . Multiple commands can be specified by typing each command followed by the Enter key. After typing all the commands, press Enter to go to a blank line and type Ctrl+D . Alternatively, a shell script can be entered at the prompt, pressing Enter after each line in the script, and typing Ctrl+D on a blank line to exit. If a script is entered, the shell used is the shell set in the user's SHELL environment, the user's login shell, or /bin/sh (whichever is found first). As soon as the load average is below 0.8, the set of commands or script is executed.
Se o conjunto de comandos ou script tentar exibir informações para a saída default (standard out), o output é enviado por e-mail ao usuário.
Use the command atq to view pending jobs. Refer to Seção 37.2.3, “Visualizando Trabalhos Pendentes” for more information.
Usage of the batch command can be restricted. For more information, refer to Seção 37.2.5, “Controlando o Acesso a At e Batch” for details.

37.2.3. Visualizando Trabalhos Pendentes

To view pending at and batch jobs, use the atq command. The atq command displays a list of pending jobs, with each job on a line. Each line follows the job number, date, hour, job class, and username format. Users can only view their own jobs. If the root user executes the atq command, all jobs for all users are displayed.

37.2.4. Opções Adicionais de Linha de Comando

Additional command line options for at and batch include:
Tabela 37.1. at and batch Command Line Options
Opção Descrição
-f Lê os comandos ou script a partir de um arquivo ao invés de especificá-los na janela de comandos.
-m Envia e-mail ao usuário quando o trabalho estiver completo.
-v Exibe a hora em que o trabalho será executado.

37.2.5. Controlando o Acesso a At e Batch

The /etc/at.allow and /etc/at.deny files can be used to restrict access to the at and batch commands. The format of both access control files is one username on each line. Whitespace is not permitted in either file. The at daemon (atd) does not have to be restarted if the access control files are modified. The access control files are read each time a user tries to execute the at or batch commands.
The root user can always execute at and batch commands, regardless of the access control files.
If the file at.allow exists, only users listed in it are allowed to use at or batch, and the at.deny file is ignored.
If at.allow does not exist, users listed in at.deny are not allowed to use at or batch.

37.2.6. Iniciando e Parando o Serviço

To start the at service, use the command /sbin/service atd start. To stop the service, use the command /sbin/service atd stop. It is recommended that you start the service at boot time. Refer to Capítulo 17, Controlando Acesso aos Serviços for details on starting the cron service automatically at boot time.

37.3. Recursos Adicionais

Para aprender mais sobre a configuração de tarefas automatizadas, consulte os seguintes recursos.

37.3.1. Documentação Instalada

  • cron man page — overview of cron.
  • crontab man pages in sections 1 and 5 — The man page in section 1 contains an overview of the crontab file. The man page in section 5 contains the format for the file and some example entries.
  • /usr/share/doc/at-<version>/timespec contains more detailed information about the times that can be specified for cron jobs.
  • at man page — description of at and batch and their command line options.

Capítulo 38. Arquivos de Registro

Arquivos de registro são arquivos que contêm mensagens sobre o sistema, incluindo o kernel, os serviços e as aplicações rodando nele. Há arquivos de registro diferentes para informações diferentes. Por exemplo: há um arquivo de registro default do sistema, um arquivo de registro para mensagens de segurança e um outro para tarefas do cron.
Arquivos de registro podem ser muito úteis ao tentar solucionar um problema no sistema, como o carregamento de um driver do kernel ou ao procurar por tentativas de autenticação não-autorizadas no sistema. Este capítulo aponta onde encontrar os arquivos de registro, como visualizá-los e o que procurar nestes arquivos.
Some log files are controlled by a daemon called syslogd. A list of log messages maintained by syslogd can be found in the /etc/syslog.conf configuration file.

38.1. Localizando Arquivos de Registro

Most log files are located in the /var/log/ directory. Some applications such as httpd and samba have a directory within /var/log/ for their log files.
You may notice multiple files in the log file directory with numbers after them. These are created when the log files are rotated. Log files are rotated so their file sizes do not become too large. The logrotate package contains a cron task that automatically rotates log files according to the /etc/logrotate.conf configuration file and the configuration files in the /etc/logrotate.d/ directory. By default, it is configured to rotate every week and keep four weeks worth of previous log files.

38.2. Visualizando Arquivos de Registro

Most log files are in plain text format. You can view them with any text editor such as Vi or Emacs. Some log files are readable by all users on the system; however, root privileges are required to read most log files.
To view system log files in an interactive, real-time application, use the System Log Viewer. To start the application, go to Applications (the main menu on the panel) > System > System Logs, or type the command gnome-system-log at a shell prompt.
The application only displays log files that exist; thus, the list might differ from the one shown in Figura 38.1, “Visualizador de Registro de Sistemas.
Visualizador de Registro de Sistemas
System Log Viewer
Figura 38.1. Visualizador de Registro de Sistemas

To filter the contents of the selected log file, click on View from the menu and select Filter as illustrated below.
Visualizador de Registro de Sistemas - Menu de Visualização
System Log Viewer - View Menu
Figura 38.2. Visualizador de Registro de Sistemas - Menu de Visualização

Selecting the Filter menu item will display the Filter text field where you can type the keywords you wish to use for your filter. To clear your filter click on the Clear button.The figure below illustrates a sample filter.
Visualizador de Registro de Sistema - Filtro
System Log Viewer - Filter
Figura 38.3. Visualizador de Registro de Sistema - Filtro

38.3. Adding a Log File

To add a log file you wish to view in the list, select File > Open. This will display the Open Log window where you can select the directory and filename of the log file you wish to view.The figure below illustrates the Open Log window.
Adding a Log File
Adding a Log File
Figura 38.4. Adding a Log File

Click on the Open button to open the file. The file is immediately added to the viewing list where you can select it and view the contents.
Note também que o Visualizador de Registro de Sistema também possibilita que você abra registros zipados dos quais os nosmes de arquivos terminem em ".gz".

38.4. Localizando Arquivos de Registro

System Log Viewer monitors all opened logs by default. If a new line is added to a monitored log file, the log name appears in bold in the log list. If the log file is selected or displayed, the new lines appear in bold at the bottom of the log file and after five seconds are displayed in normal format. This is illustrated in the figures below. The figure below illustrates a new alert in the messages log file. The log file is listed in bold text.
Log File Alert
Log File Alert
Figura 38.5. Log File Alert

Clicking on the messages log file displays the logs in the file with the new lines in bold as illustrated below.
Log file contents
Log file contents
Figura 38.6. Log file contents

As novas linhas estão expostas em negritos por cinco segundos em fonte normal.
Log file contents after five seconds
Log file contents after five seconds
Figura 38.7. Log file contents after five seconds

Parte V. Monitoramento de Sistema

Capítulo 39. SystemTap

39.1. Introdução

O SystemTap oferece uma interface de linha de comando simples e linguagem de script para simplificar o montante de informações sobre como executar kernel Linux para que possa ser analizado mais tarde. Os dados são extraídos, filtrados e resumidos de forma rápida e segura para possibilitar o diagnóstico de desempenho complexo ou problemas funcionais.
O SystemTap permite que os scripts escrevam na linguage de script do SystemTap, que são então compilados aos módulos kernel de código C e inseridos no kernel.
A idéia principal que está por trás de um script systemtap é nomear eventos e fornecê-los manipuladores. Quando um evento em específico acontecer, o Linux kernel executa o manipulador como se fosse uma sub-rotina rápida e depois resume. Existem diversos tipos de eventos, tais como entrar ou sair de uma função, de um timer que esteja vencendo ou de uma sessão inteira de systemtap que esteja iniciando ou terminando. Um manipulador é uma série de instruções de linguagem de script que especifica o trabalho a ser realizado quando um evento ocorrer. Este trabalho, geralmente inclui dados extraídos de um contexto de evento, armazenando-os em variáveis internas ou imprimindo resultados.

39.2. Implementação

SystemTap takes a compiler-oriented approach to generating instrumentation. Refer to Figura 39.1, “Fluxo de Dados em SystemTap” "Flow of data in SystemTap" for an overall diagram of SystemTap used in this discussion. In the upper right hand corner of the diagram is the probe.stp, the probe script the developer has written. This is parsed by the translator into parse trees. During this time the input is checked for syntax errors. The translator then performs elaboration, pulling in additional code from the script library and determining locations of probe points and variables from the debug information. After the elaboration is complete the translator can generate the probe.c, the kernel module in C.
O arquivo de sonda.c é compilado em um módulo regular kernel, sonda.ko, usando um compilador GCC. A compilação pode retirar código de suporte de bibliotecas de tempo de execução. Depois que o GCC tiver gerado a sonda.ko, o daemon do SystemTap é iniciada para coletar o resultado do módulo de instrumentação. O módulo de instrumentação é carregado no kernel, e inicia-se a coleção de dados. Os dados a partir do módulo de intrumentação é transferido para o espaço do usuário, através do relayfs e demonstrado pelo daemon. Quando o usuário aperta Control-C, o daemon descarrega o módulo, que também encerra o processo de coleção de dados.
Fluxo de Dados em SystemTap
Fluxo de Dados em SystemTap
Figura 39.1. Fluxo de Dados em SystemTap

39.3. Usando o SystemTap

O Systemtap traduz um script SystemTap para C, executando o sistema C compilador para criar um módulo kernel a partir dele. Quando um módulo é carregado, ele ativa todos os eventos sondados, se conectando ao kernel. Depois, como os eventos ocorrem em qualquer processador, os manipuladores compilados rodam. Finalmente, a sessão para, os ganchos são desconectados, e o módulo removido. Este processo todo é efetuado através de somente um programa de linha de comando, stap.

39.3.1. Rastrear

O tipo mais simples de sondagem é simplesmente rastrear o evento. Este é o resultado de inserir instruções impressas, localizadas de forma estratégica, dentro de um programa. Este geralmente é o primeiro passo para solucionar problemas: explore-o vendo um histórico do que aconteceu.
Este estilo de instrumentação é o mais simples. Ele simplesmente pede ao systemtap para imprimir algo em cada evento. Para transferir isto para linguagem de script, você precisa dizer onde sondar e o que imprimir lá.

39.3.1.1. Onde Sondar

O Systemtap suporta diversos eventos embutidos. A biblioteca de scripts que vem com o systemtap, cada um chamando um "tapset", pode definir alguns extras, definido nos termos de família embutida. Veja na página principal stapprobes para maiores detalhes. Todos estes eventos são nomeados utilizando uma sintáxe unificada que parece identificadores com parâmetros parada por ponto.
Tabela 39.1. Eventos de SystemTap
Evento Descrição
begin O início da sessão systemtap
final O final da sessão sistemtap
kernel.function("sys_open") A entrada para a função chamada sys_abrir no kernel.
syscall.close.return O retorno da chamada de sistema fechada.
module("ext3").statement(0xdeadbeef) A instrução direcionada no driver ext3filesystem.
timer.ms(200) Um timer que inicia a cada 200 milisegundos.

Como demonstração, vamos supor que você deseje rastrear todas as entradas de funções e saídas em um arquivo fonte, por exemplo net/socket.c no kernel. O ponto da sonda kernel.function deixa você expressar isto facilmente, uma vez que o systemtap examina as informações depuradas do kernel para relatar o código do objeto ao código de fonte. Funciona como um depurador: se você puder nomear ou acomodá-lo, você poderá sondá-lo. Utilize o kernel.function("*@net/socket.c") para as entradas de funções e o kernel.function("*@net/socket.c").return para as saídas. Note o uso de curingas no nome da função, e a parte @FILENAME subsequente. Você também pode colocar curingas no nome de arquivo e até mesmo adicionar "dois pontos" (:) e um número de linha se você quiser restringir a procura de forma precisa. Como o systemtap irá colocar uma sonda separada em todos os lugares que combinar com um ponto de sonda, alguns curingas podem se expandir para cem, mil sondas, portanto tenha cuidado com o que você pede.
Uma vez que você identificou os pontos de sonda, aparecerá um esqueleto do script de systemtap. A palavra chave probe apresenta um ponto de sonda, ou uma lista deles separada por vírgula. Os seguintes {e}colchetes fecham o manipulador para todos os pontos de sonda listados.
Você poderá rodar este script como ele se apresenta, apesar de que não haverá resultado com manipuladores vazios. Coloque duas linhas no novo arquivo. Execute o stap -v FILE. Finalize-o a qualquer momento com ^C. (A opção - v informa ao systemtap para imprimir mais mensagens verbais durante seu processo. Tente a opção -h para ver mais opções).

39.3.1.2. O que imprimir

Já que você está interessado em cada função que foi inserida e retirada, uma linha deve ser impressa para cada uma, contendo o nome da função. Para facilitar a leitura da lista, o systemtap deve recuar as linhas para que as funções chamadas por outras funções rastreadas sejam aninhadas mais profundamente. Para informar cada processo individualmente, que possam estar sendo executados concorrentemente, o systemtap deve também imprimir o ID do processo na linha.

Capítulo 40. Coletando Informações do Sistema

Antes de aprender como configurar seu sistema, você deve aprender a coletar informações essenciais do sistema. Por exemplo, você deve saber como encontrar a quantidade de memória livre, a quantidade de espaço disponível no disco rígido, como o disco rígido foi particionado e quais processos estão sendo executados. Este capítulo aborda como obter este tipo de informação no seu sistema Red Hat Enterprise Linux usando alguns comandos e programas simples.

40.1. Processos do Sistema

The ps ax command displays a list of current system processes, including processes owned by other users. To display the owner alongside each process, use the ps aux command. This list is a static list; in other words, it is a snapshot of what was running when you invoked the command. If you want a constantly updated list of running processes, use top as described below.
The ps output can be long. To prevent it from scrolling off the screen, you can pipe it through less:
ps aux | less
You can use the ps command in combination with the grep command to see if a process is running. For example, to determine if Emacs is running, use the following command:
ps ax | grep emacs
The top command displays currently running processes and important information about them including their memory and CPU usage. The list is both real-time and interactive. An example of output from the top command is provided as follows:
top - 15:02:46 up 35 min,  4 users,  load average: 0.17, 0.65, 1.00
Tasks: 110 total,   1 running, 107 sleeping,   0 stopped,   2 zombie
Cpu(s): 41.1% us,  2.0% sy,  0.0% ni, 56.6% id,  0.0% wa,  0.3% hi,  0.0% si
Mem:    775024k total,   772028k used,     2996k free,    68468k buffers
Swap:  1048568k total,      176k used,  1048392k free,   441172k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 4624 root      15   0 40192  18m 7228 S 28.4  2.4   1:23.21 X
 4926 mhideo    15   0 55564  33m 9784 S 13.5  4.4   0:25.96 gnome-terminal
 6475 mhideo    16   0  3612  968  760 R  0.7  0.1   0:00.11 top
 4920 mhideo    15   0 20872  10m 7808 S  0.3  1.4   0:01.61 wnck-applet
    1 root      16   0  1732  548  472 S  0.0  0.1   0:00.23 init
    2 root      34  19     0    0    0 S  0.0  0.0   0:00.00 ksoftirqd/0
    3 root       5 -10     0    0    0 S  0.0  0.0   0:00.03 events/0
    4 root       6 -10     0    0    0 S  0.0  0.0   0:00.02 khelper
    5 root       5 -10     0    0    0 S  0.0  0.0   0:00.00 kacpid
   29 root       5 -10     0    0    0 S  0.0  0.0   0:00.00 kblockd/0
   47 root      16   0     0    0    0 S  0.0  0.0   0:01.74 pdflush
   50 root      11 -10     0    0    0 S  0.0  0.0   0:00.00 aio/0
   30 root      15   0     0    0    0 S  0.0  0.0   0:00.05 khubd
   49 root      16   0     0    0    0 S  0.0  0.0   0:01.44 kswapd0
To exit top, press the q key.
Tabela 40.1, “Interactive top commands” contains useful interactive commands that you can use with top. For more information, refer to the top(1) manual page.
Tabela 40.1. Interactive top commands
Comando Descrição
Space Atualizar a tela imediatamente
h Exibir uma tela de ajuda
k Matar (kill) um processo. Você deve indicar o ID do processo e o sinal a ser enviado para ele.
n Alterar o número de processos exibidos. Você deve indicar o número.
u Ordenar por usuário.
M Ordenar por uso da memória.
P Ordenar por uso da CPU.

If you prefer a graphical interface for top, you can use the GNOME System Monitor. To start it from the desktop, select System > Administration > System Monitor or type gnome-system-monitor at a shell prompt (such as an XTerm). Select the Process Listing tab.
The GNOME System Monitor allows you to search for a process in the list of running processes. Using the Gnome System Monitor, you can also view all processes, your processes, or active processes.
The Edit menu item allows you to:
  • Pare um processo.
  • Continue ou inicie um processo.
  • Termine um processo.
  • Mate (kill) um processo.
  • Altere a prioridade de um processo selecionado.
  • Edite as preferências do Monitor do Sistema. Isto inclui mudar o intervalo usado para atualizar a lista e selecionar campos de processos a serem exibidos na janela Monitor do Sistema.
The View menu item allows you to:
  • Visualize apenas os processos ativos.
  • Visualize todos os processos.
  • Visualize os seus processos.
  • Visualize dependências de processos.
  • Oculte um processo.
  • Visualize processos ocultos.
  • Visualize mapas de memória.
  • Visualize os arquivos abertos pelos processos selecionados.
To stop a process, select it and click End Process. Alternatively you can also stop a process by selecting it, clicking Edit on your menu and selecting Stop Process.
Para ordenar informações por uma coluna específica, clique no nome da coluna. Isto ordena as informações pela coluna selecionada em ordem crescente. Clique no nome da coluna novamente para alternar entre a ordem crescente e decrescente.
GNOME System Monitor
Listagem de Processos do Monitor do Sistema GNOME
Figura 40.1. GNOME System Monitor

40.2. Uso da Memória

The free command displays the total amount of physical memory and swap space for the system as well as the amount of memory that is used, free, shared, in kernel buffers, and cached.
             total       used       free     shared    buffers     cached
 Mem:        645712     549720      95992          0     176248     224452
 -/+ buffers/cache:     149020     496692
 Swap:      1310712          0    1310712
The command free -m shows the same information in megabytes, which are easier to read.
             total       used       free     shared    buffers     cached
Mem:           630        536         93          0        172        219
-/+ buffers/cache:        145        485
Swap:         1279          0       1279
If you prefer a graphical interface for free, you can use the GNOME System Monitor. To start it from the desktop, go to System > Administration > System Monitor or type gnome-system-monitor at a shell prompt (such as an XTerm). Click on the Resources tab.
GNOME System Monitor - Resources tab
Aba Recursos do gnome-system-monitor
Figura 40.2. GNOME System Monitor - Resources tab

40.3. Sistemas de Arquivos

The df command reports the system's disk space usage. If you type the command df at a shell prompt, the output looks similar to the following:
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/mapper/VolGroup00-LogVol00
                       11675568   6272120   4810348  57% / /dev/sda1
	                 100691      9281     86211  10% /boot
none                     322856         0    322856   0% /dev/shm
By default, this utility shows the partition size in 1 kilobyte blocks and the amount of used and available disk space in kilobytes. To view the information in megabytes and gigabytes, use the command df -h. The -h argument stands for human-readable format. The output looks similar to the following:
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup00-LogVol00
                        12G  6.0G  4.6G  57% / /dev/sda1
			99M  9.1M   85M  10% /boot
none 			316M     0  316M   0% /dev/shm
In the list of mounted partitions, there is an entry for /dev/shm. This entry represents the system's virtual memory file system.
The du command displays the estimated amount of space being used by files in a directory. If you type du at a shell prompt, the disk usage for each of the subdirectories is displayed in a list. The grand total for the current directory and subdirectories are also shown as the last line in the list. If you do not want to see the totals for all the subdirectories, use the command du -hs to see only the grand total for the directory in human-readable format. Use the du --help command to see more options.
To view the system's partitions and disk space usage in a graphical format, use the Gnome System Monitor by clicking on System > Administration > System Monitor or type gnome-system-monitor at a shell prompt (such as an XTerm). Select the File Systems tab to view the system's partitions. The figure below illustrates the File Systems tab.
GNOME System Monitor - File Systems
Aba sistemas de arquivos do the gnome-system-monitor
Figura 40.3. GNOME System Monitor - File Systems

40.4. Hardware

If you are having trouble configuring your hardware or just want to know what hardware is in your system, you can use the Hardware Browser application to display the hardware that can be probed. To start the program from the desktop, select System (the main menu on the panel) > Administration > Hardware or type hwbrowser at a shell prompt. As shown in Figura 40.4, “Hardware Browser, it displays your CD-ROM devices, diskette drives, hard drives and their partitions, network devices, pointing devices, system devices, and video cards. Click on the category name in the left menu, and the information is displayed.
Hardware Browser
hwbrowser
Figura 40.4. Hardware Browser

The Device Manager application can also be used to display your system hardware. This application can be started by selecting System (the main menu on the panel) > Administration > Hardware like the Hardware Browser. To start the application from a terminal, type hal-device-manager. Depending on your installation preferences, the graphical menu above may start this application or the Hardware Browser when clicked. The figure below illustrates the Device Manager window.
Gerente de Dispositivo
Device Manager
Figura 40.5. Gerente de Dispositivo

You can also use the lspci command to list all PCI devices. Use the command lspci -v for more verbose information or lspci -vv for very verbose output.
For example, lspci can be used to determine the manufacturer, model, and memory size of a system's video card:
00:00.0 Host bridge: ServerWorks CNB20LE Host Bridge (rev 06)
00:00.1 Host bridge: ServerWorks CNB20LE Host Bridge (rev 06)
00:01.0 VGA compatible controller: S3 Inc. Savage 4 (rev 04)
00:02.0 Ethernet controller: Intel Corp. 82557/8/9 [Ethernet Pro 100] (rev 08)
00:0f.0 ISA bridge: ServerWorks OSB4 South Bridge (rev 50)
00:0f.1 IDE interface: ServerWorks OSB4 IDE Controller
00:0f.2 USB Controller: ServerWorks OSB4/CSB5 OHCI USB Controller (rev 04)
01:03.0 SCSI storage controller: Adaptec AIC-7892P U160/m (rev 02)
01:05.0 RAID bus controller: IBM ServeRAID Controller
The lspci is also useful to determine the network card in your system if you do not know the manufacturer or model number.

40.5. Recursos Adicionais

Para aprender mais sobre a coleta de informações do sistema, consulte os seguintes recursos.

40.5.1. Documentação Instalada

  • ps --help — Displays a list of options that can be used with ps.
  • top manual page — Type man top to learn more about top and its many options.
  • free manual page — type man free to learn more about free and its many options.
  • df manual page — Type man df to learn more about the df command and its many options.
  • du manual page — Type man du to learn more about the du command and its many options.
  • lspci manual page — Type man lspci to learn more about the lspci command and its many options.
  • /proc/ directory — The contents of the /proc/ directory can also be used to gather more detailed system information.

Capítulo 41. OProfile

OProfile is a low overhead, system-wide performance monitoring tool. It uses the performance monitoring hardware on the processor to retrieve information about the kernel and executables on the system, such as when memory is referenced, the number of L2 cache requests, and the number of hardware interrupts received. On a Red Hat Enterprise Linux system, the oprofile RPM package must be installed to use this tool.
Many processors include dedicated performance monitoring hardware. This hardware makes it possible to detect when certain events happen (such as the requested data not being in cache). The hardware normally takes the form of one or more counters that are incremented each time an event takes place. When the counter value, essentially rolls over, an interrupt is generated, making it possible to control the amount of detail (and therefore, overhead) produced by performance monitoring.
O OProfile usa este hardware (ou um substituto baseado em timer nos casos em que não há hardware de monitoramento de desempenho) para coletar amostras de dados relacionados ao desempenho cada vez que um contador gera uma interrupção. Estas amostras são gravadas periodicamente no disco; posteriormente, os dados contidos nestas amostras podem então ser usados para gerar relatórios de desempenho dos sistemas e aplicações.
O OProfile é uma ferramenta útil, mas saiba de algumas limitações ao utilizá-lo:
  • Uso de bibliotecas compartilhadas — Amostras de código em bibliotecas compartilhadas não são atribuídos a uma determinada aplicação a não ser que a opção --separate=library seja usada.
  • As amostras de monitoramento do desempenho são imprecisas — Quando o registro do monitoramento de desempenho ativa uma amostra, a resolução da interrupção não é precisa como uma exceção 'divide by zero'. Devido à execução fora de ordem das instruções pelo processador, a amostra pode ser gravada em uma instrução próxima.
  • opreport does not associate samples for inline functions' properlyopreport uses a simple address range mechanism to determine which function an address is in. Inline function samples are not attributed to the inline function but rather to the function the inline function was inserted into.
  • OProfile accumulates data from multiple runs — OProfile is a system-wide profiler and expects processes to start up and shut down multiple times. Thus, samples from multiple runs accumulate. Use the command opcontrol --reset to clear out the samples from previous runs.
  • Problemas de desempenho não são limitados à CPU — O OProfile é orientado para encontrar problemas com processos limitados à CPU. OProfile não identifica processos adormecidos (asleep) porque estes aguardam bloqueios (locks) ou a ocorrência de algum outro evento (como o dispositivo I/O finanlizar uma operação).

41.1. Visão Geral das Ferramentas

Tabela 41.1, “Comandos do OProfile” provides a brief overview of the tools provided with the oprofile package.
Tabela 41.1. Comandos do OProfile
Comando Decrição
ophelp
Exibe eventos disponíveis do processador do sistema junto a uma breve descrição de cada.
opimport
Converte o arquivo do banco de dados de amostras de um formato diferente para o formato nativo do sistema. Use esta opção somente ao analisar um banco de dados de amostras de uma arquitetura diferente.
opannotate Creates annotated source for an executable if the application was compiled with debugging symbols. Refer to Seção 41.5.4, “Using opannotate for details.
opcontrol
Configures what data is collected. Refer to Seção 41.2, “Configurando o OProfile” for details.
opreport
Retrieves profile data. Refer to Seção 41.5.1, “Using opreport for details.
oprofiled
Roda como um daemon para gravar dados da amostra no disco periodicamente.

41.2. Configurando o OProfile

Before OProfile can be run, it must be configured. At a minimum, selecting to monitor the kernel (or selecting not to monitor the kernel) is required. The following sections describe how to use the opcontrol utility to configure OProfile. As the opcontrol commands are executed, the setup options are saved to the /root/.oprofile/daemonrc file.

41.2.1. Especificando o Kernel

Primeiro, configure se o OProfile deve monitorar o kernel. Esta é a única opção de configuração requisitada antes de iniciar o OProfile. Todas as outras são opcionais.
Para monitorar o kernel, execute o seguinte comando como root:
opcontrol --setup --vmlinux=/usr/lib/debug/lib/modules/`uname -r`/vmlinux

Nota

The debuginfo package must be installed (which contains the uncompressed kernel) in order to monitor the kernel.
Para configurar o OProfile para não monitorar o kernel, execute o seguinte comando como root:
opcontrol --setup --no-vmlinux
This command also loads the oprofile kernel module, if it is not already loaded, and creates the /dev/oprofile/ directory, if it does not already exist. Refer to Seção 41.6, “Understanding /dev/oprofile/ for details about this directory.

Nota

Even if OProfile is configured not to profile the kernel, the SMP kernel still must be running so that the oprofile module can be loaded from it.
Setting whether samples should be collected within the kernel only changes what data is collected, not how or where the collected data is stored. To generate different sample files for the kernel and application libraries, refer to Seção 41.2.3, “Separando os Perfis do Kernel e do Espaço do Usuário”.

41.2.2. Determinando os Eventos a Monitorar

Most processors contain counters, which are used by OProfile to monitor specific events. As shown in Tabela 41.2, “Processadores e Contadores do OProfile”, the number of counters available depends on the processor.
Tabela 41.2. Processadores e Contadores do OProfile
Processador cpu_type Número de Contadores
Pentium Pro i386/ppro 2
Pentium II i386/pii 2
Pentium III i386/piii 2
Pentium 4 (não-hyper-threaded) i386/p4 8
Pentium 4 (hyper-threaded) i386/p4-ht 4
Athlon i386/athlon 4
AMD64 x86-64/hammer 4
Itanium ia64/itanium 4
Itanium 2 ia64/itanium2 4
TIMER_INT timer 1
IBM eServer iSeries and pSeries timer 1
ppc64/power4 8
ppc64/power5 6
ppc64/970 8
IBM eServer S/390 and S/390x timer 1
IBM eServer zSeries timer 1

Use Tabela 41.2, “Processadores e Contadores do OProfile” to verify that the correct processor type was detected and to determine the number of events that can be monitored simultaneously. timer is used as the processor type if the processor does not have supported performance monitoring hardware.
If timer is used, events cannot be set for any processor because the hardware does not have support for hardware performance counters. Instead, the timer interrupt is used for profiling.
If timer is not used as the processor type, the events monitored can be changed, and counter 0 for the processor is set to a time-based event by default. If more than one counter exists on the processor, the counters other than counter 0 are not set to an event by default. The default events monitored are shown in Tabela 41.3, “Eventos Default”.
Tabela 41.3. Eventos Default
Processador Default Event for Counter Decrição
Pentium Pro, Pentium II, Pentium III, Athlon e AMD64 CPU_CLK_UNHALTED O relógio do processador não é desligado (halted)
Pentium 4 (HT and non-HT) GLOBAL_POWER_EVENTS O tempo durante o qual o processador não é parado
Itanium 2 CPU_CYCLES Ciclos da CPU
TIMER_INT (nenhum) Amostra de cada interrupção do timer
ppc64/power4 CYCLES Processor Cycles
ppc64/power5 CYCLES Processor Cycles
ppc64/970 CYCLES Processor Cycles

O número de eventos que podem ser monitorados de uma vez é determinado pelo número de contadores do processador. Entretanto, esta não é uma correlação um-pra-um; em alguns processadores, determinados eventos devem ser mapeados para contadores específicos. Para determinar o número de contadores disponíveis, execute o seguinte comando:
ls -d /dev/oprofile/[0-9]*
Os eventos disponíveis variam de acordo com o tipo de processador. Para determinar os eventos disponíveis para perfilamento, execute o seguinte comando como root (a lista é específica ao tipo de processador do sistema):
ophelp
The events for each counter can be configured via the command line or with a graphical interface. For more information on the graphical interface, refer to Seção 41.8, “Interface Gráfica”. If the counter cannot be set to a specific event, an error message is displayed.
To set the event for each configurable counter via the command line, use opcontrol:
opcontrol --event=<event-name>:<sample-rate>
Replace <event-name> with the exact name of the event from ophelp, and replace <sample-rate> with the number of events between samples.

41.2.2.1. Taxa de Amostragem

By default, a time-based event set is selected. It creates a sample every 100,000 clock cycles per processor. If the timer interrupt is used, the timer is set to whatever the jiffy rate is and is not user-settable. If the cpu_type is not timer, each event can have a sampling rate set for it. The sampling rate is the number of events between each sample snapshot.
Ao definir o evento para o contador, também é possível especificar uma taxa de amostragem:
opcontrol --event=<event-name>:<sample-rate>
Substitua <sample-rate> pelo número de eventos a aguardar antes de fazer o 'sampling' novamente. Quanto menor a contagem, mais frequentes as amostras. Para eventos que ocorrem esporadicamente, pode-se precisar de uma contagem menor para capturar as instâncias do evento.

Atenção

Seja muito cuidadoso ao determinar as taxas de amostragem. A amostragem muito frequente pode sobrecarregar o sistema, fazendo com que ele pareça estar congelado (frozen) ou fazendo com que realmente congele.

41.2.2.2. Máscaras de Unidade (Unit Masks)

Some user performance monitoring events may also require unit masks to further define the event.
Unit masks for each event are listed with the ophelp command. The values for each unit mask are listed in hexadecimal format. To specify more than one unit mask, the hexadecimal values must be combined using a bitwise or operation.
opcontrol --event=<event-name>:<sample-rate>:<unit-mask>

41.2.3. Separando os Perfis do Kernel e do Espaço do Usuário

By default, kernel mode and user mode information is gathered for each event. To configure OProfile to ignore events in kernel mode for a specific counter, execute the following command:
opcontrol --event=<event-name>:<sample-rate>:<unit-mask>:0
Execute o seguinte comando para iniciar novamente o perfilamento do modo do kernel para o contador:
opcontrol --event=<event-name>:<sample-rate>:<unit-mask>:1
To configure OProfile to ignore events in user mode for a specific counter, execute the following command:
opcontrol --event=<event-name>:<sample-rate>:<unit-mask>:<kernel>:0
Execute o seguinte comando para iniciar novamente o perfilamento do modo usuário para o contador:
opcontrol --event=<event-name>:<sample-rate>:<unit-mask>:<kernel>:1
Quando o daemon do OProfile grava os dados do perfil nos arquivos de amostra, pode separar os dados do perfil da biblioteca e do kernel em arquivos de amostra separados. Para configurar como o daemon grava os arquivos de amostra, execute o seguinte comando como root:
opcontrol --separate=<choice>
<choice> pode ser uma das seguintes:
  • none — do not separate the profiles (default)
  • library — generate per-application profiles for libraries
  • kernel — generate per-application profiles for the kernel and kernel modules
  • all — generate per-application profiles for libraries and per-application profiles for the kernel and kernel modules
Se --separate=library é usada, o nome do arquivo de amostras inclui os nomes dos executáveis, assim como o nome da biblioteca.

Nota

These configuration changes will take effect when oprofile is restarted.

41.3. Iniciando e Parando o OProfile

Para começar a monitorar o sistema com o OProfile, execute o seguinte comando como root:
opcontrol --start
Aparece um output similar ao seguinte:
Using log file /var/lib/oprofile/oprofiled.log Daemon started. Profiler running.
The settings in /root/.oprofile/daemonrc are used.
The OProfile daemon, oprofiled, is started; it periodically writes the sample data to the /var/lib/oprofile/samples/ directory. The log file for the daemon is located at /var/lib/oprofile/oprofiled.log.
To stop the profiler, execute the following command as root:
opcontrol --shutdown

41.4. Salvando Dados

Às vezes é útil salvar amostras numa hora específica. Por exemplo: quando perfilar um executável, é possível coletar amostras diferentes baseadas em conjuntos de dados de input diferentes. Se o número de eventos a ser monitorado excede o número de contadores disponíveis no processador, é possível rodar o OProfile diversas vezes para coletar dados, salvando os dados da amostra cada vez em um arquivo diferente.
Para salvar o conjunto corrente de arquivos de amostra, execute o seguinte comando, substituindo <name> por um nome descritivo único para a sessão corrente:
opcontrol --save=<name>
The directory /var/lib/oprofile/samples/name/ is created and the current sample files are copied to it.

41.5. Analisando os Dados

Periodically, the OProfile daemon, oprofiled, collects the samples and writes them to the /var/lib/oprofile/samples/ directory. Before reading the data, make sure all data has been written to this directory by executing the following command as root:
opcontrol --dump
Each sample file name is based on the name of the executable. For example, the samples for the default event on a Pentium III processor for /bin/bash becomes:
\{root\}/bin/bash/\{dep\}/\{root\}/bin/bash/CPU_CLK_UNHALTED.100000
As seguintes ferramentas estão disponíveis para perfilar os dados de amostra após terem sido coletados:
  • opreport
  • opannotate
Use estas ferramentas, juntamente aos binários perfilados, para gerar relatórios que podem ser analisados futuramente.

Atenção

The executable being profiled must be used with these tools to analyze the data. If it must change after the data is collected, backup the executable used to create the samples as well as the sample files. Please note that the sample file and the binary have to agree. Making a backup isn't going to work if they do not match. oparchive can be used to address this problem.
Samples for each executable are written to a single sample file. Samples from each dynamically linked library are also written to a single sample file. While OProfile is running, if the executable being monitored changes and a sample file for the executable exists, the existing sample file is automatically deleted. Thus, if the existing sample file is needed, it must be backed up, along with the executable used to create it before replacing the executable with a new version. The oprofile analysis tools use the executable file that created the samples during analysis. If the executable changes the analysis tools will be unable to analyze the associated samples. Refer to Seção 41.4, “Salvando Dados” for details on how to backup the sample file.

41.5.1. Using opreport

The opreport tool provides an overview of all the executables being profiled.
The following is part of a sample output:
Profiling through timer interrupt
TIMER:0|
samples|      %|
------------------
25926 97.5212 no-vmlinux
359  1.3504 pi
65  0.2445 Xorg
62  0.2332 libvte.so.4.4.0
56  0.2106 libc-2.3.4.so
34  0.1279 libglib-2.0.so.0.400.7
19  0.0715 libXft.so.2.1.2
17  0.0639 bash
8  0.0301 ld-2.3.4.so
8  0.0301 libgdk-x11-2.0.so.0.400.13
6  0.0226 libgobject-2.0.so.0.400.7
5  0.0188 oprofiled
4  0.0150 libpthread-2.3.4.so
4  0.0150 libgtk-x11-2.0.so.0.400.13
3  0.0113 libXrender.so.1.2.2
3  0.0113 du
1  0.0038 libcrypto.so.0.9.7a
1  0.0038 libpam.so.0.77
1  0.0038 libtermcap.so.2.0.8
1  0.0038 libX11.so.6.2
1  0.0038 libgthread-2.0.so.0.400.7
1  0.0038 libwnck-1.so.4.9.0
Each executable is listed on its own line. The first column is the number of samples recorded for the executable. The second column is the percentage of samples relative to the total number of samples. The third column is the name of the executable.
Refer to the opreport man page for a list of available command line options, such as the -r option used to sort the output from the executable with the smallest number of samples to the one with the largest number of samples.

41.5.2. Using opreport on a Single Executable

To retrieve more detailed profiled information about a specific executable, use opreport:
opreport <mode> <executable>
<executable> deve ser a localidade completa do executável a ser analisado. O <mode> deve ser um dos seguintes:
-l
List sample data by symbols. For example, the following is part of the output from running the command opreport -l /lib/tls/libc-<version>.so:
samples  %        symbol name
12       21.4286  __gconv_transform_utf8_internal
5         8.9286  _int_malloc
4         7.1429  malloc
3         5.3571  __i686.get_pc_thunk.bx
3         5.3571  _dl_mcount_wrapper_check
3         5.3571  mbrtowc
3         5.3571  memcpy
2         3.5714  _int_realloc
2         3.5714  _nl_intern_locale_data
2         3.5714  free
2         3.5714  strcmp
1         1.7857  __ctype_get_mb_cur_max
1         1.7857  __unregister_atfork
1         1.7857  __write_nocancel
1         1.7857  _dl_addr
1         1.7857  _int_free
1         1.7857  _itoa_word
1         1.7857  calc_eclosure_iter
1         1.7857  fopen@@GLIBC_2.1
1         1.7857  getpid
1         1.7857  memmove
1         1.7857  msort_with_tmp
1         1.7857  strcpy
1         1.7857  strlen
1         1.7857  vfprintf
1         1.7857  write
The first column is the number of samples for the symbol, the second column is the percentage of samples for this symbol relative to the overall samples for the executable, and the third column is the symbol name.
Para ordenar o output do maior número de amostras para o menor (ordem inversa), use -r em conjunto com a opção -l.
-i <symbol-name>
List sample data specific to a symbol name. For example, the following output is from the command opreport -l -i __gconv_transform_utf8_internal /lib/tls/libc-<version>.so:
samples  %        symbol name
12       100.000  __gconv_transform_utf8_internal
A primeira linha é um resumo da combinação símbolo/executável.
The first column is the number of samples for the memory symbol. The second column is the percentage of samples for the memory address relative to the total number of samples for the symbol. The third column is the symbol name.
-d
List sample data by symbols with more detail than -l. For example, the following output is from the command opreport -l -d __gconv_transform_utf8_internal /lib/tls/libc-<version>.so:
vma      samples  %        symbol name
00a98640 12       100.000  __gconv_transform_utf8_internal
00a98640 1         8.3333
00a9868c 2        16.6667
00a9869a 1         8.3333
00a986c1 1         8.3333
00a98720 1         8.3333
00a98749 1         8.3333
00a98753 1         8.3333
00a98789 1         8.3333
00a98864 1         8.3333
00a98869 1         8.3333
00a98b08 1         8.3333
Os dados são os mesmos que da opção -l, exceto que, para cada símbolo, é exibido um endereço usado da memória virtual. Para cada endereço da memória virtual, são apresentados o número de amostras e a porcentagem de amostras realativa ao número total de amostras do símbolo.
-x<symbol-name>
Exclui a lista de símbolos separada por vírgulas do output.
session:<name>
Specify the full path to the session or a directory relative to the /var/lib/oprofile/samples/ directory.

41.5.3. Getting more detailed output on the modules

OProfile collects data on a system-wide basis for kernel- and user-space code running on the machine. However, once a module is loaded into the kernel, the information about the origin of the kernel module is lost. The module could have come from the initrd file on boot up, the directory with the various kernel modules, or a locally created kernel module. As a result when OProfile records sample for a module, it just lists the samples for the modules for an executable in the root directory, but this is unlikely to be the place with the actual code for the module. You will need to take some steps to make sure that analysis tools get the executable.
For example on an AMD64 machine the sampling is set up to record "Data cache accesses" and "Data cache misses" and assuming you would like to see the data for the ext3 module:
~]$ opreport /ext3
CPU: AMD64 processors, speed 797.948 MHz (estimated)
Counted DATA_CACHE_ACCESSES events (Data cache accesses) with a unit mask of 0x00 (No unit mask) count 500000
Counted DATA_CACHE_MISSES events (Data cache misses) with a unit mask of 0x00 (No unit mask) count 500000
DATA_CACHE_ACC...|DATA_CACHE_MIS...|
samples|      %|  samples|      %|
------------------------------------
148721 100.000      1493 100.000 ext3
To get a more detailed view of the actions of the module, you will need to either have the module unstripped (e.g. installed from a custom build) or have the debuginfo RPM installed for the kernel.
Find out which kernel is running, "uname -a", get the appropriate debuginfo rpm, and install on the machine.
Then make a symbolic link so oprofile finds the code for the module in the correct place:
~]# ln -s /lib/modules/`uname -r`/kernel/fs/ext3/ext3.ko /ext3
Then the detailed information can be obtained with:
~]# opreport image:/ext3 -l|more
warning: could not check that the binary file /ext3 has not been modified since the profile was taken. Results may be inaccurate.
CPU: AMD64 processors, speed 797.948 MHz (estimated)
Counted DATA_CACHE_ACCESSES events (Data cache accesses) with a unit mask of 0x00 (No unit mask) count 500000
Counted DATA_CACHE_MISSES events (Data cache misses) with a unit mask of 0x00 (No unit mask) count 500000
samples  %        samples  %        symbol name
16728    11.2479  7         0.4689  ext3_group_sparse
16454    11.0637  4         0.2679  ext3_count_free_blocks
14583     9.8056  51        3.4159  ext3_fill_super
8281      5.5681  129       8.6403  ext3_ioctl
7810      5.2514  62        4.1527  ext3_write_info
7286      4.8991  67        4.4876  ext3_ordered_writepage
6509      4.3767  130       8.7073  ext3_new_inode
6378      4.2886  156      10.4488  ext3_new_block
5932      3.9887  87        5.8272  ext3_xattr_block_list
...

41.5.4. Using opannotate

The opannotate tool tries to match the samples for particular instructions to the corresponding lines in the source code. The resulting files generated should have the samples for the lines at the left. It also puts in a comment at the beginning of each function listing the total samples for the function.
For this utility to work, the executable must be compiled with GCC's -g option. By default, Red Hat Enterprise Linux packages are not compiled with this option.
The general syntax for opannotate is as follows:
opannotate --search-dirs <src-dir> --source <executable>
The directory containing the source code and the executable to be analyzed must be specified. Refer to the opannotate man page for a list of additional command line options.

41.6. Understanding /dev/oprofile/

The /dev/oprofile/ directory contains the file system for OProfile. Use the cat command to display the values of the virtual files in this file system. For example, the following command displays the type of processor OProfile detected:
cat /dev/oprofile/cpu_type
A directory exists in /dev/oprofile/ for each counter. For example, if there are 2 counters, the directories /dev/oprofile/0/ and dev/oprofile/1/ exist.
Cada diretório de um contador contém os seguintes arquivos:
  • count — The interval between samples.
  • enabled — If 0, the counter is off and no samples are collected for it; if 1, the counter is on and samples are being collected for it.
  • event — The event to monitor.
  • kernel — If 0, samples are not collected for this counter event when the processor is in kernel-space; if 1, samples are collected even if the processor is in kernel-space.
  • unit_mask — Defines which unit masks are enabled for the counter.
  • user — If 0, samples are not collected for the counter event when the processor is in user-space; if 1, samples are collected even if the processor is in user-space.
The values of these files can be retrieved with the cat command. For example:
cat /dev/oprofile/0/count

41.7. Uso do Exemplo

Apesar do OProfile ser usado para desenvolvedores analisarem o desempenho de aplicações, também serve para administradores de sistemas analisarem o sistema. Por exemplo:
  • Determine which applications and services are used the most on a systemopreport can be used to determine how much processor time an application or service uses. If the system is used for multiple services but is under performing, the services consuming the most processor time can be moved to dedicated systems.
  • Determine processor usage — The CPU_CLK_UNHALTED event can be monitored to determine the processor load over a given period of time. This data can then be used to determine if additional processors or a faster processor might improve system performance.

41.8. Interface Gráfica

Some OProfile preferences can be set with a graphical interface. To start it, execute the oprof_start command as root at a shell prompt. To use the graphical interface, you will need to have the oprofile-gui package installed.
After changing any of the options, save them by clicking the Save and quit button. The preferences are written to /root/.oprofile/daemonrc, and the application exits. Exiting the application does not stop OProfile from sampling.
On the Setup tab, to set events for the processor counters as discussed in Seção 41.2.2, “Determinando os Eventos a Monitorar”, select the counter from the pulldown menu and select the event from the list. A brief description of the event appears in the text box below the list. Only events available for the specific counter and the specific architecture are displayed. The interface also displays whether the profiler is running and some brief statistics about it.
Configuração do OProfile
oprof_start interface
Figura 41.1. Configuração do OProfile

On the right side of the tab, select the Profile kernel option to count events in kernel mode for the currently selected event, as discussed in Seção 41.2.3, “Separando os Perfis do Kernel e do Espaço do Usuário”. If this option is unselected, no samples are collected for the kernel.
Select the Profile user binaries option to count events in user mode for the currently selected event, as discussed in Seção 41.2.3, “Separando os Perfis do Kernel e do Espaço do Usuário”. If this option is unselected, no samples are collected for user applications.
Use the Count text field to set the sampling rate for the currently selected event as discussed in Seção 41.2.2.1, “Taxa de Amostragem”.
If any unit masks are available for the currently selected event, as discussed in Seção 41.2.2.2, “Máscaras de Unidade (Unit Masks)”, they are displayed in the Unit Masks area on the right side of the Setup tab. Select the checkbox beside the unit mask to enable it for the event.
On the Configuration tab, to profile the kernel, enter the name and location of the vmlinux file for the kernel to monitor in the Kernel image file text field. To configure OProfile not to monitor the kernel, select No kernel image.
OProfile Configuration
OProfile Configuration
Figura 41.2. OProfile Configuration

If the Verbose option is selected, the oprofiled daemon log includes more information.
If Per-application kernel samples files is selected, OProfile generates per-application profiles for the kernel and kernel modules as discussed in Seção 41.2.3, “Separando os Perfis do Kernel e do Espaço do Usuário”. This is equivalent to the opcontrol --separate=kernel command. If Per-application shared libs samples files is selected, OProfile generates per-application profiles for libraries. This is equivalent to the opcontrol --separate=library command.
To force data to be written to samples files as discussed in Seção 41.5, “Analisando os Dados”, click the Flush profiler data button. This is equivalent to the opcontrol --dump command.
To start OProfile from the graphical interface, click Start profiler. To stop the profiler, click Stop profiler. Exiting the application does not stop OProfile from sampling.

41.9. Recursos Adicionais

Este capítulo destaca somente o OProfile, como configurá-lo e usá-lo. Para aprender mais, consulte os seguintes recursos.

41.9.1. Documentação Instalada

  • /usr/share/doc/oprofile-<version>/oprofile.htmlOProfile Manual
  • oprofile man page — Discusses opcontrol, opreport, opannotate, and ophelp

41.9.2. Sites Úteis

Parte VI. Kernel e Configuração de Driver

Capítulo 42. Atualizando o Kernel Manualmente

O kernel do Red Hat Enterprise Linux é especialmente desenvolvido pela equipe do kernel do Red Hat Enterprise Linux para garantir sua integridade e compatibilidade com os componentes de hardware suportados. Antes que a Red Hat lançe um kernel, este passa primeiro por uma série de testes de qualidade rigorosos.
Red Hat Enterprise Linux kernels are packaged in RPM format so that they are easy to upgrade and verify using the Package Management Tool, or the yum command. The Package Management Tool automatically queries the Red Hat Enterprise Linux servers and determines which packages need to be updated on your machine, including the kernel. This chapter is only useful for those individuals that require manual updating of kernel packages, without using the yum command.

Atenção

A construção de um kernel padronizado não é suportada pela equipe do Global Services Support da Red Hat, e porisso este assunto não é explorado neste manual.

Tip

The use of yum is highly recommended by Red Hat for installing upgraded kernels.
For more information on Red Hat Network, the Package Management Tool, and yum, refer to Capítulo 14, Product Subscriptions and Entitlements.

42.1. Visão Geral dos Pacotes do Kernel

O Red Hat Enterprise Linux contém os seguintes pacotes do kernel (alguns talvez não se apliquem à arquitetura de sua máquina):
  • kernel — Contains the kernel for multi-processor systems. For x86 system, only the first 4GB of RAM is used. As such, x86 systems with over 4GB of RAM should use the kernel-PAE.
  • kernel-devel — Contains the kernel headers and makefiles sufficient to build modules against the kernel package.
  • kernel-PAE (only for i686 systems) — This package offers the following key configuration option (in addition to the options already enabled for the kernel package):
    • PAE (Physical Address Extension) support for systems with more than 4GB of RAM, and reliably up to 16GB.

      Importante

      Physical Address Extension allows x86 processors to address up to 64GB of physical RAM, but due to differences between the Red Hat Enterprise Linux 4 and 5 kernels, only Red Hat Enterprise Linux 4 (with the kernel-hugemem package) is able to reliably address all 64GB of memory. Additionally, the Red Hat Enterprise Linux 5 PAE variant does not allow 4GB of addressable memory per-process like the Red Hat Enterprise Linux 4 kernel-hugemem variant does. However, the x86_64 kernel does not suffer from any of these limitations, and is the suggested Red Hat Enterprise Linux 5 architecture to use with large-memory systems.
  • kernel-PAE-devel — Contains the kernel headers and makefiles required to build modules against the kernel-PAE package.
  • kernel-doc — Contains documentation files from the kernel source. Various portions of the Linux kernel and the device drivers shipped with it are documented in these files. Installation of this package provides a reference to the options that can be passed to Linux kernel modules at load time.
    By default, these files are placed in the /usr/share/doc/kernel-doc-<version>/ directory.
  • kernel-headers — Inclui os arquivos de cabeçalho C que especificam a interface entre o kernel Linux e as bibliotecas de userspace e programas. Os arquivos de cabeçalho definem as estruturas e constâncias que são necessárias para construir a maioria dos programas padrão.
  • kernel-xen — Inclui a versão do kernel do Linux que é necessária para rodar o componente de Virtualização.
  • kernel-xen-devel — Contém cabeçalhos do kernel e makefiles necessários para construir módulos no pacote kernel-xen.

Nota

The kernel-source package has been removed and replaced with an RPM that can only be retrieved from Red Hat Network. This *.src.rpm package must then be rebuilt locally using the rpmbuild command. For more information on obtaining and installing the kernel source package, refer to the latest updated Release Notes (including all updates) at http://www.redhat.com/docs/manuals/enterprise/

42.2. Preparando para o Upgrade

Antes de atualizar (upgrade) o kernel, tome algumas precauções. Se o sistema tiver um drive de disquete, o primeiro passo é garantir que você tenha um disquete boot funcionando no caso de algum problema. Se o carregador de inicialização não está configurado corretamente para iniciar o novo kernel, o sistema não pode ser inicializado no Red Hat Enterprise Linux sem um disquete boot operante.
To create a boot diskette, login as root, and run the command /sbin/mkbootdisk `uname -r` at a shell prompt.

Tip

Refer to the mkbootdisk man page for more options. You can create bootable media via CD-Rs, CD-RWs, and USB flash drives, provided that your system BIOS also supports it.
Reinicialize a máquina com o disquete boot e verifique se este funciona antes de continuar.
To determine which kernel packages are installed, execute the command rpm -qa | grep kernel at a shell prompt:
O output contém alguns dos ou todos os pacotes a seguir, dependendo da arquitetura do sistema (os números da versão e pacotes podem ser diferentes):
kernel-2.6.9-5.EL
kernel-devel-2.6.9-5.EL
kernel-utils-2.6.9-5.EL
kernel-doc-2.6.9-5.EL
kernel-smp-2.6.9-5.EL
kernel-smp-devel-2.6.9-5.EL
kernel-hugemem-devel-2.6.9-5.EL
From the output, determine which packages need to be download for the kernel upgrade. For a single processor system, the only required package is the kernel package. Refer to Seção 42.1, “Visão Geral dos Pacotes do Kernel” for descriptions of the different packages.
In the file name, each kernel package contains the architecture for which the package was built. The format is kernel-<variant>-<version>.<arch>.rpm, where <variant> is one of either PAE, xen, and so forth. The <arch> is one of the following:
  • x86_64 for the AMD64 and Intel EM64T architectures
  • ia64 for the Intel® Itanium™ architecture
  • ppc64 for the IBM® eServerpSeries™ architecture
  • s390 for the IBM® S/390® architecture
  • s390x for the IBM® eServerSystem z® architecture
  • i686 for Intel® Pentium® II, Intel® Pentium® III, Intel® Pentium® 4, AMD Athlon®, and AMD Duron® systems

42.3. Fazendo o download do Kernel Atualizado

Há diversas maneiras de determinar se há um kernel atualizado disponível para o sistema.
  • Security Errata — Refer to http://www.redhat.com/security/updates/ for information on security errata, including kernel upgrades that fix security issues.
  • Através do Red Hat Network Faça o Download e instale os pacotes RPM do kernel. O Red Hat Network pode baixar o kernel mais atualizado, atualizar o kernel no sistema, criar uma imagem de disco RAM inicial se necessário e configurar o carregador de inicialização para inicializar o kernel novo. Para mais informações, consulte http://www.redhat.com/docs/manuals/RHNetwork/.
If Red Hat Network was used to download and install the updated kernel, follow the instructions in Seção 42.5, “Verificando a Imagem de Disco RAM Inicial” and Seção 42.6, “Verificando o Carregador de Inicialização”, only do not change the kernel to boot by default. Red Hat Network automatically changes the default kernel to the latest version. To install the kernel manually, continue to Seção 42.4, “Executando a Atualização”.

42.4. Executando a Atualização

Após recuperar todos os pacotes necessários, é hora de atualizar o kernel existente.

Importante

É altamente recomendado que o kernel antigo seja guardado, caso ocorra problemas com o novo.
At a shell prompt, change to the directory that contains the kernel RPM packages. Use -i argument with the rpm command to keep the old kernel. Do not use the -U option, since it overwrites the currently installed kernel, which creates boot loader problems. For example:
rpm -ivh kernel-<kernel version>.<arch>.rpm
The next step is to verify that the initial RAM disk image has been created. Refer to Seção 42.5, “Verificando a Imagem de Disco RAM Inicial” for details.

42.5. Verificando a Imagem de Disco RAM Inicial

If the system uses the ext3 file system, a SCSI controller, or labels to reference partitions in /etc/fstab, an initial RAM disk is needed. The initial RAM disk allows a modular kernel to have access to modules that it might need to boot from before the kernel has access to the device where the modules normally reside.
On architectures other than IBM eServer iSeries, the initial RAM disk can be created with the mkinitrd command. However, this step is performed automatically if the kernel and its associated packages are installed or upgraded from the RPM packages distributed by Red Hat; in such cases, you do not need to create the initial RAM disk manually. To verify that an initial RAM disk already exists, use the command ls -l /boot to make sure the initrd-<version>.img file was created (the version should match the version of the kernel just installed).
On iSeries systems, the initial RAM disk file and vmlinux file are combined into one file, which is created with the addRamDisk command. This step is performed automatically if the kernel and its associated packages are installed or upgraded from the RPM packages distributed by Red Hat, Inc.; thus, it does not need to be executed manually. To verify that it was created, use the command ls -l /boot to make sure the /boot/vmlinitrd-<kernel-version> file already exists (the <kernel-version> should match the version of the kernel just installed).
The next step is to verify that the boot loader has been configured to boot the new kernel. Refer to Seção 42.6, “Verificando o Carregador de Inicialização” for details.

42.6. Verificando o Carregador de Inicialização

The kernel RPM package configures the boot loader to boot the newly installed kernel (except for IBM eServer iSeries systems). However, it does not configure the boot loader to boot the new kernel by default.
É sempre bom confirmar se o carregador de inicialização foi configurado corretamente. Este passo é crucial. Se o carregador de inicialização for configurado incorretamente, o sistema não será inicializado apropriadamante no Red Hat Enterprise Linux. Se isto ocorrer, inicialize o sistema com o disquete boot criado anteriormente e tente configurar o carregador de inicialização novamente.

42.6.1. Sistemas x86

Todos os sistemas x86 (incluindo todos os sistemas AMD64) usam GRUB como carregador de inicialização.

42.6.1.1. GRUB

Confirm that the file /boot/grub/grub.conf contains a title section with the same version as the kernel package just installed
# Note that you do not have to rerun grub after making changes to this file
# NOTICE:  You have a /boot partition.  This means that
#          all kernel and initrd paths are relative to /boot/, eg.
#          root (hd0,0)
#          kernel /vmlinuz-version ro root=/dev/hda2
#          initrd /initrd-version.img
#boot=/dev/hda
default=1 timeout=10
splashimage=(hd0,0)/grub/splash.xpm.gz
title Red Hat Enterprise Linux (2.6.9-5.EL)
         root (hd0,0)
	 kernel /vmlinuz-2.6.9-5.EL ro root=LABEL=/
	 initrd /initrd-2.6.9-5.EL.img
title Red Hat Enterprise Linux (2.6.9-1.906_EL)
         root (hd0,0)
	 kernel /vmlinuz-2.6.9-1.906_EL ro root=LABEL=/
	 initrd /initrd-2.6.9-1.906_EL.img
If a separate /boot/ partition was created, the paths to the kernel and initrd image are relative to /boot/.
Notice that the default is not set to the new kernel. To configure GRUB to boot the new kernel by default, change the value of the default variable to the title section number for the title section that contains the new kernel. The count starts with 0. For example, if the new kernel is the first title section, set default to 0.
Comece a testar o kernel novo reinicializando o computador e monitorando as mensagens para garantir que o hardware seja detectado apropriadamente.

42.6.2. Sistemas Itanium

Itanium systems use ELILO as the boot loader, which uses /boot/efi/EFI/redhat/elilo.conf as the configuration file. Confirm that this file contains an image section with the same version as the kernel package just installed:
prompt timeout=50 default=old  image=vmlinuz-2.6.9-5.EL
         label=linux
	 initrd=initrd-2.6.9-5.EL.img         read-only
	 append="root=LABEL=/" image=vmlinuz-2.6.9-1.906_EL
	 label=old
	 initrd=initrd-2.6.9-1.906.img         read-only
	 append="root=LABEL=/"
Notice that the default is not set to the new kernel. To configure ELILO to boot the new kernel, change the value of the default variable to the value of the label for the image section that contains the new kernel.
Comece a testar o kernel novo reinicializando o computador e monitorando as mensagens para garantir que o hardware seja detectado apropriadamente.

42.6.3. Sistemas IBM S/390 e IBM System z

The IBM S/390 and IBM System z systems use z/IPL as the boot loader, which uses /etc/zipl.conf as the configuration file. Confirm that the file contains a section with the same version as the kernel package just installed:
[defaultboot] default=old target=/boot/
[linux]
         image=/boot/vmlinuz-2.6.9-5.EL
	 ramdisk=/boot/initrd-2.6.9-5.EL.img
	 parameters="root=LABEL=/"
[old]
         image=/boot/vmlinuz-2.6.9-1.906_EL
	 ramdisk=/boot/initrd-2.6.9-1.906_EL.img
	 parameters="root=LABEL=/"
Notice that the default is not set to the new kernel. To configure z/IPL to boot the new kernel by default, change the value of the default variable to the name of the section that contains the new kernel. The first line of each section contains the name in brackets.
After modifying the configuration file, run /sbin/zipl as root to enable the changes.
Comece a testar o kernel novo reinicializando o computador e monitorando as mensagens para garantir que o hardware seja detectado apropriadamente.

42.6.4. Sistemas IBM eServer iSeries

The /boot/vmlinitrd-<kernel-version> file is installed when you upgrade the kernel. However, you must use the dd command to configure the system to boot the new kernel:
  1. As root, issue the command cat /proc/iSeries/mf/side to determine the default side (either A, B, or C).
  2. Como root, submeta o seguinte comando, onde <versão-do-kernel> é a versão do kernel novo e <lado> é o lado do comando anterior:
    dd if=/boot/vmlinitrd-<kernel-version> of=/proc/iSeries/mf/<side>/vmlinux bs=8k
Comece a testar o kernel novo reinicializando o computador e monitorando as mensagens para garantir que o hardware seja detectado apropriadamente.

42.6.5. Sistemas IBM eServer pSeries

IBM eServer pSeries systems use YABOOT as the boot loader, which uses /etc/aboot.conf as the configuration file. Confirm that the file contains an image section with the same version as the kernel package just installed:
boot=/dev/sda1 init-message=Welcome to Red Hat Enterprise Linux! Hit <TAB> for boot options
partition=2 timeout=30 install=/usr/lib/yaboot/yaboot delay=10 nonvram
image=/vmlinux--2.6.9-5.EL
         label=old
	 read-only
	 initrd=/initrd--2.6.9-5.EL.img
	 append="root=LABEL=/"
image=/vmlinux-2.6.9-5.EL
	 label=linux
	 read-only
	 initrd=/initrd-2.6.9-5.EL.img
	 append="root=LABEL=/"
Notice that the default is not set to the new kernel. The kernel in the first image is booted by default. To change the default kernel to boot either move its image stanza so that it is the first one listed or add the directive default and set it to the label of the image stanza that contains the new kernel.
Comece a testar o kernel novo reinicializando o computador e monitorando as mensagens para garantir que o hardware seja detectado apropriadamente.

Capítulo 43. General Parameters and Modules

This chapter is provided to illustrate some of the possible parameters available for common hardware device drivers [9], which under Red Hat Enterprise Linux are called kernel modules. In most cases, the default parameters do work. However, there may be times when extra module parameters are necessary for a device to function properly or to override the module's default parameters for the device.
During installation, Red Hat Enterprise Linux uses a limited subset of device drivers to create a stable installation environment. Although the installation program supports installation on many different types of hardware, some drivers (including those for SCSI adapters and network adapters) are not included in the installation kernel. Rather, they must be loaded as modules by the user at boot time.
Once installation is completed, support exists for a large number of devices through kernel modules.

Important

Red Hat provides a large number of unsupported device drivers in groups of packages called kernel-smp-unsupported-<kernel-version> and kernel-hugemem-unsupported-<kernel-version> . Replace <kernel-version> with the version of the kernel installed on the system. These packages are not installed by the Red Hat Enterprise Linux installation program, and the modules provided are not supported by Red Hat, Inc.

43.1. Kernel Module Utilities

A group of commands for managing kernel modules is available if the module-init-tools package is installed. Use these commands to determine if a module has been loaded successfully or when trying different modules for a piece of new hardware.
The command /sbin/lsmod displays a list of currently loaded modules. For example:
Module                  Size  Used by
tun                    11585  1
autofs4                21573  1
hidp                   16193  2
rfcomm                 37849  0
l2cap                  23873  10 hidp,rfcomm
bluetooth              50085  5 hidp,rfcomm,l2cap
sunrpc                153725  1
dm_mirror              29073  0
dm_mod                 57433  1 dm_mirror
video                  17221  0
sbs                    16257  0
i2c_ec                  5569  1 sbs
container               4801  0
button                  7249  0
battery                10565  0
asus_acpi              16857  0
ac                      5701  0
ipv6                  246113  12
lp                     13065  0
parport_pc             27493  1
parport                37001  2 lp,parport_pc
uhci_hcd               23885  0
floppy                 57317  1
sg                     34653  0
snd_ens1371            26721  1
gameport               16073  1 snd_ens1371
snd_rawmidi            24897  1 snd_ens1371
snd_ac97_codec         91360  1 snd_ens1371
snd_ac97_bus            2753  1 snd_ac97_codec
snd_seq_dummy           4293  0
snd_seq_oss            32705  0
serio_raw               7493  0
snd_seq_midi_event      8001  1 snd_seq_oss
snd_seq                51633  5 snd_seq_dummy,snd_seq_oss,snd_seq_midi_event
snd_seq_device          8781  4 snd_rawmidi,snd_seq_dummy,snd_seq_oss,snd_seq
snd_pcm_oss            42849  0
snd_mixer_oss          16833  1 snd_pcm_oss
snd_pcm                76485  3 snd_ens1371,snd_ac97_codec,snd_pcm_oss
snd_timer              23237  2 snd_seq,snd_pcm
snd                    52933  12 snd_ens1371,snd_rawmidi,snd_ac97_codec,snd_seq_oss,snd_seq,snd_seq_device,snd_pcm_oss,snd_mixer_oss,snd_pcm,snd_timer
soundcore              10145  1 snd
i2c_piix4               8909  0
ide_cd                 38625  3
snd_page_alloc         10569  1 snd_pcm
i2c_core               21697  2 i2c_ec,i2c_piix4
pcnet32                34117  0
cdrom                  34913  1 ide_cd
mii                     5825  1 pcnet32
pcspkr                  3521  0
ext3                  129737  2
jbd                    58473  1 ext3
mptspi                 17353  3
scsi_transport_spi     25025  1 mptspi
mptscsih               23361  1 mptspi
sd_mod                 20929  16
scsi_mod              134121  5 sg,mptspi,scsi_transport_spi,mptscsih,sd_mod
mptbase                52193  2 mptspi,mptscsih
For each line, the first column is the name of the module, the second column is the size of the module, and the third column is the use count.
The /sbin/lsmod output is less verbose and easier to read than the output from viewing /proc/modules.
To load a kernel module, use the /sbin/modprobe command followed by the kernel module name. By default, modprobe attempts to load the module from the /lib/modules/<kernel-version>/kernel/drivers/ subdirectories. There is a subdirectory for each type of module, such as the net/ subdirectory for network interface drivers. Some kernel modules have module dependencies, meaning that other modules must be loaded first for it to load. The /sbin/modprobe command checks for these dependencies and loads the module dependencies before loading the specified module.
For example, the command
modprobe e100
loads any module dependencies and then the e100 module.
To print to the screen all commands as /sbin/modprobe executes them, use the -v option. For example:
modprobe -v e100
Output similar to the following is displayed:
insmod /lib/modules/2.6.9-5.EL/kernel/drivers/net/e100.ko
Using /lib/modules/2.6.9-5.EL/kernel/drivers/net/e100.ko
Symbol version prefix 'smp_'
The /sbin/insmod command also exists to load kernel modules; however, it does not resolve dependencies. Thus, it is recommended that the /sbin/modprobe command be used.
To unload kernel modules, use the /sbin/rmmod command followed by the module name. The rmmod utility only unloads modules that are not in use and that are not a dependency of other modules in use.
For example, the command
rmmod e100
unloads the e100 kernel module.
Another useful kernel module utility is modinfo. Use the command /sbin/modinfo to display information about a kernel module. The general syntax is:
modinfo [options] <module>
Options include -d, which displays a brief description of the module, and -p, which lists the parameters the module supports. For a complete list of options, refer to the modinfo man page (man modinfo).

43.2. Persistent Module Loading

Kernel modules are usually loaded directly by the facility that requires them, which is given correct settings in the /etc/modprobe.conf file. However, it is sometimes necessary to explicitly force the loading of a module at boot time.
Red Hat Enterprise Linux checks for the existence of the /etc/rc.modules file at boot time, which contains various commands to load modules. The rc.modules should be used, and not rc.local because rc.modules is executed earlier in the boot process.
For example, the following commands configure loading of the foo module at boot time (as root):
echo modprobe foo >> /etc/rc.modules
chmod +x /etc/rc.modules

Tip

This approach is not necessary for network and SCSI interfaces because they have their own specific mechanisms.

43.3. Specifying Module Parameters

In some situations, it may be necessary to supply parameters to a module as it is loaded for it to function properly.
For instance, to enable full duplex at 100Mbps connection speed for an Intel Ether Express/100 card, load the e100 driver with the e100_speed_duplex=4 option.

Caution

When a parameter has commas, be sure not to put a space after a comma.

Tip

The modinfo command is also useful for listing various information about a kernel module, such as version, dependencies, parameter options, and aliases.

43.4. Storage parameters

Tabela 43.1. Storage Module Parameters
Hardware Module Parameters
3ware Storage Controller and 9000 series 3w-xxxx.ko, 3w-9xxx.ko
Adaptec Advanced Raid Products, Dell PERC2, 2/Si, 3/Si, 3/Di, HP NetRAID-4M, IBM ServeRAID, and ICP SCSI driver aacraid.ko
nondasd — Control scanning of hba for nondasd devices. 0=off, 1=on
dacmode — Control whether dma addressing is using 64 bit DAC. 0=off, 1=on
commit — Control whether a COMMIT_CONFIG is issued to the adapter for foreign arrays. This is typically needed in systems that do not have a BIOS. 0=off, 1=on
startup_timeout — The duration of time in seconds to wait for adapter to have it's kernel up and running. This is typically adjusted for large systems that do not have a BIOS
aif_timeout — The duration of time in seconds to wait for applications to pick up AIFs before deregistering them. This is typically adjusted for heavily burdened systems.
numacb — Request a limit to the number of adapter control blocks (FIB) allocated. Valid values are 512 and down. Default is to use suggestion from Firmware.
acbsize — Request a specific adapter control block (FIB) size. Valid values are 512, 2048, 4096 and 8192. Default is to use suggestion from Firmware.
Adaptec 28xx, R9xx, 39xx AHA-284x, AHA-29xx, AHA-394x, AHA-398x, AHA-274x, AHA-274xT, AHA-2842, AHA-2910B, AHA-2920C, AHA-2930/U/U2, AHA-2940/W/U/UW/AU/, U2W/U2/U2B/, U2BOEM, AHA-2944D/WD/UD/UWD, AHA-2950U2/W/B, AHA-3940/U/W/UW/, AUW/U2W/U2B, AHA-3950U2D, AHA-3985/U/W/UW, AIC-777x, AIC-785x, AIC-786x, AIC-787x, AIC-788x , AIC-789x, AIC-3860 aic7xxx.ko
verbose — Enable verbose/diagnostic logging
allow_memio — Allow device registers to be memory mapped
debug — Bitmask of debug values to enable
no_probe — Toggle EISA/VLB controller probing
probe_eisa_vl — Toggle EISA/VLB controller probing
no_reset — Supress initial bus resets
extended — Enable extended geometry on all controllers
periodic_otag — Send an ordered tagged transaction periodically to prevent tag starvation. This may be required by some older disk drives or RAID arrays.
tag_info:<tag_str> — Set per-target tag depth
global_tag_depth:<int> — Global tag depth for every target on every bus
seltime:<int> — Selection Timeout (0/256ms,1/128ms,2/64ms,3/32ms)
IBM ServeRAID ips.ko
LSI Logic MegaRAID Mailbox Driver megaraid_mbox.ko
unconf_disks — Set to expose unconfigured disks to kernel (default=0)
busy_wait — Max wait for mailbox in microseconds if busy (default=10)
max_sectors — Maximum number of sectors per IO command (default=128)
cmd_per_lun — Maximum number of commands per logical unit (default=64)
fast_load — Faster loading of the driver, skips physical devices! (default=0)
debug_level — Debug level for driver (default=0)
Emulex LightPulse Fibre Channel SCSI driver lpfc.ko
lpfc_poll — FCP ring polling mode control: 0 - none, 1 - poll with interrupts enabled 3 - poll and disable FCP ring interrupts
lpfc_log_verbose — Verbose logging bit-mask
lpfc_lun_queue_depth — Max number of FCP commands we can queue to a specific LUN
lpfc_hba_queue_depth — Max number of FCP commands we can queue to a lpfc HBA
lpfc_scan_down — Start scanning for devices from highest ALPA to lowest
lpfc_nodev_tmo — Seconds driver will hold I/O waiting for a device to come back
lpfc_topology — Select Fibre Channel topology
lpfc_link_speed — Select link speed
lpfc_fcp_class — Select Fibre Channel class of service for FCP sequences
lpfc_use_adisc — Use ADISC on rediscovery to authenticate FCP devices
lpfc_ack0 — Enable ACK0 support
lpfc_cr_delay — A count of milliseconds after which an interrupt response is generated
lpfc_cr_count — A count of I/O completions after which an interrupt response is generated
lpfc_multi_ring_support — Determines number of primary SLI rings to spread IOCB entries across
lpfc_fdmi_on — Enable FDMI support
lpfc_discovery_threads — Maximum number of ELS commands during discovery
lpfc_max_luns — Maximum allowed LUN
lpfc_poll_tmo — Milliseconds driver will wait between polling FCP ring
HP Smart Array cciss.ko
LSI Logic MPT Fusion mptbase.ko mptctl.ko mptfc.ko mptlan.ko mptsas.ko mptscsih.ko mptspi.ko
mpt_msi_enable — MSI Support Enable
mptfc_dev_loss_tmo — Initial time the driver programs the transport to wait for an rport to return following a device loss event.
mpt_pt_clear — Clear persistency table
mpt_saf_te — Force enabling SEP Processor
QLogic Fibre Channel Driver qla2xxx.ko
ql2xlogintimeout — Login timeout value in seconds.
qlport_down_retry — Maximum number of command retries to a port that returns a PORT-DOWN status
ql2xplogiabsentdevice — Option to enable PLOGI to devices that are not present after a Fabric scan.
ql2xloginretrycount — Specify an alternate value for the NVRAM login retry count.
ql2xallocfwdump — Option to enable allocation of memory for a firmware dump during HBA initialization. Default is 1 - allocate memory.
extended_error_logging — Option to enable extended error logging.
ql2xfdmienable — Enables FDMI registrations.
NCR, Symbios and LSI 8xx and 1010 sym53c8xx
cmd_per_lun — The maximum number of tags to use by default
tag_ctrl — More detailed control over tags per LUN
burst — Maximum burst. 0 to disable, 255 to read from registers
led — Set to 1 to enable LED support
diff — 0 for no differential mode, 1 for BIOS, 2 for always, 3 for not GPIO3
irqm — 0 for open drain, 1 to leave alone, 2 for totem pole
buschk — 0 to not check, 1 for detach on error, 2 for warn on error
hostid — The SCSI ID to use for the host adapters
verb — 0 for minimal verbosity, 1 for normal, 2 for excessive
debug — Set bits to enable debugging
settle — Settle delay in seconds. Default 3
nvram — Option currently not used
excl — List ioport addresses here to prevent controllers from being attached
safe — Set other settings to a "safe mode"

43.5. Ethernet Parameters

Important

Most modern Ethernet-based network interface cards (NICs), do not require module parameters to alter settings. Instead, they can be configured using ethtool or mii-tool. Only after these tools fail to work should module parameters be adjusted. Module parameters can be viewed using the modinfo command.

Note

For information about using these tools, consult the man pages for ethtool, mii-tool, and modinfo.
Tabela 43.2. Ethernet Module Parameters
Hardware Module Parameters
3Com EtherLink PCI III/XL Vortex (3c590, 3c592, 3c595, 3c597) Boomerang (3c900, 3c905, 3c595) 3c59x.ko
debug — 3c59x debug level (0-6)
options — 3c59x: Bits 0-3: media type, bit 4: bus mastering, bit 9: full duplex
global_options — 3c59x: same as options, but applies to all NICs if options is unset
full_duplex — 3c59x full duplex setting(s) (1)
global_full_duplex — 3c59x: same as full_duplex, but applies to all NICs if full_duplex is unset
hw_checksums — 3c59x Hardware checksum checking by adapter(s) (0-1)
flow_ctrl — 3c59x 802.3x flow control usage (PAUSE only) (0-1)
enable_wol — 3c59x: Turn on Wake-on-LAN for adapter(s) (0-1)
global_enable_wol — 3c59x: same as enable_wol, but applies to all NICs if enable_wol is unset
rx_copybreak — 3c59x copy breakpoint for copy-only-tiny-frames
max_interrupt_work — 3c59x maximum events handled per interrupt
compaq_ioaddr — 3c59x PCI I/O base address (Compaq BIOS problem workaround)
compaq_irq — 3c59x PCI IRQ number (Compaq BIOS problem workaround)
compaq_device_id — 3c59x PCI device ID (Compaq BIOS problem workaround)
watchdog — 3c59x transmit timeout in milliseconds
global_use_mmio — 3c59x: same as use_mmio, but applies to all NICs if options is unset
use_mmio — 3c59x: use memory-mapped PCI I/O resource (0-1)
RTL8139, SMC EZ Card Fast Ethernet, RealTek cards using RTL8129, or RTL8139 Fast Ethernet chipsets 8139too.ko
Broadcom 4400 10/100 PCI ethernet driver b44.ko
b44_debug — B44 bitmapped debugging message enable value
Broadcom NetXtreme II BCM5706/5708 Driver bnx2.ko
disable_msi — Disable Message Signaled Interrupt (MSI)
Intel Ether Express/100 driver e100.ko
debug — Debug level (0=none,...,16=all)
eeprom_bad_csum_allow — Allow bad eeprom checksums
Intel EtherExpress/1000 Gigabit e1000.ko
TxDescriptors — Number of transmit descriptors
RxDescriptors — Number of receive descriptors
Speed — Speed setting
Duplex — Duplex setting
AutoNeg — Advertised auto-negotiation setting
FlowControl — Flow Control setting
XsumRX — Disable or enable Receive Checksum offload
TxIntDelay — Transmit Interrupt Delay
TxAbsIntDelay — Transmit Absolute Interrupt Delay
RxIntDelay — Receive Interrupt Delay
RxAbsIntDelay — Receive Absolute Interrupt Delay
InterruptThrottleRate — Interrupt Throttling Rate
SmartPowerDownEnable — Enable PHY smart power down
KumeranLockLoss — Enable Kumeran lock loss workaround
Myricom 10G driver (10GbE) myri10ge.ko
myri10ge_fw_name — Firmware image name
myri10ge_ecrc_enable — Enable Extended CRC on PCI-E
myri10ge_max_intr_slots — Interrupt queue slots
myri10ge_small_bytes — Threshold of small packets
myri10ge_msi — Enable Message Signalled Interrupts
myri10ge_intr_coal_delay — Interrupt coalescing delay
myri10ge_flow_control — Pause parameter
myri10ge_deassert_wait — Wait when deasserting legacy interrupts
myri10ge_force_firmware — Force firmware to assume aligned completions
myri10ge_skb_cross_4k — Can a small skb cross a 4KB boundary?
myri10ge_initial_mtu — Initial MTU
myri10ge_napi_weight — Set NAPI weight
myri10ge_watchdog_timeout — Set watchdog timeout
myri10ge_max_irq_loops — Set stuck legacy IRQ detection threshold
NatSemi DP83815 Fast Ethernet natsemi.ko
mtu — DP8381x MTU (all boards)
debug — DP8381x default debug level
rx_copybreak — DP8381x copy breakpoint for copy-only-tiny-frames
options — DP8381x: Bits 0-3: media type, bit 17: full duplex
full_duplex — DP8381x full duplex setting(s) (1)
AMD PCnet32 and AMD PCnetPCI pcnet32.ko
PCnet32 and PCnetPCI pcnet32.ko
debug — pcnet32 debug level
max_interrupt_work — pcnet32 maximum events handled per interrupt
rx_copybreak — pcnet32 copy breakpoint for copy-only-tiny-frames
tx_start_pt — pcnet32 transmit start point (0-3)
pcnet32vlb — pcnet32 Vesa local bus (VLB) support (0/1)
options — pcnet32 initial option setting(s) (0-15)
full_duplex — pcnet32 full duplex setting(s) (1)
homepna — pcnet32 mode for 79C978 cards (1 for HomePNA, 0 for Ethernet, default Ethernet
RealTek RTL-8169 Gigabit Ethernet driver r8169.ko
media — force phy operation. Deprecated by ethtool (8).
rx_copybreak — Copy breakpoint for copy-only-tiny-frames
use_dac — Enable PCI DAC. Unsafe on 32 bit PCI slot.
debug — Debug verbosity level (0=none, ..., 16=all)
Neterion Xframe 10GbE Server Adapter s2io.ko
SIS 900/701G PCI Fast Ethernet sis900.ko
multicast_filter_limit — SiS 900/7016 maximum number of filtered multicast addresses
max_interrupt_work — SiS 900/7016 maximum events handled per interrupt
sis900_debug — SiS 900/7016 bitmapped debugging message level
Adaptec Starfire Ethernet driver starfire.ko
max_interrupt_work — Maximum events handled per interrupt
mtu — MTU (all boards)
debug — Debug level (0-6)
rx_copybreak — Copy breakpoint for copy-only-tiny-frames
intr_latency — Maximum interrupt latency, in microseconds
small_frames — Maximum size of receive frames that bypass interrupt latency (0,64,128,256,512)
options — Deprecated: Bits 0-3: media type, bit 17: full duplex
full_duplex — Deprecated: Forced full-duplex setting (0/1)
enable_hw_cksum — Enable/disable hardware cksum support (0/1)
Broadcom Tigon3 tg3.ko
tg3_debug — Tigon3 bitmapped debugging message enable value
ThunderLAN PCI tlan.ko
aui — ThunderLAN use AUI port(s) (0-1)
duplex — ThunderLAN duplex setting(s) (0-default, 1-half, 2-full)
speed — ThunderLAN port speen setting(s) (0,10,100)
debug — ThunderLAN debug mask
bbuf — ThunderLAN use big buffer (0-1)
Digital 21x4x Tulip PCI Ethernet cards SMC EtherPower 10 PCI(8432T/8432BT) SMC EtherPower 10/100 PCI(9332DST) DEC EtherWorks 100/10 PCI(DE500-XA) DEC EtherWorks 10 PCI(DE450) DEC QSILVER's, Znyx 312 etherarray Allied Telesis LA100PCI-T Danpex EN-9400, Cogent EM110 tulip.ko io io_port
VIA Rhine PCI Fast Ethernet cards with either the VIA VT86c100A Rhine-II PCI or 3043 Rhine-I D-Link DFE-930-TX PCI 10/100 via-rhine.ko
max_interrupt_work — VIA Rhine maximum events handled per interrupt
debug — VIA Rhine debug level (0-7)
rx_copybreak — VIA Rhine copy breakpoint for copy-only-tiny-frames
avoid_D3 — Avoid power state D3 (work-around for broken BIOSes)

43.5.1. Using Multiple Ethernet Cards

It is possible to use multiple Ethernet cards on a single machine. For each card there must be an alias and, possibly, options lines for each card in /etc/modprobe.conf.
For additional information about using multiple Ethernet cards, refer to the Linux Ethernet-HOWTO online at http://www.redhat.com/mirrors/LDP/HOWTO/Ethernet-HOWTO.html.

43.5.2. The Channel Bonding Module

Red Hat Enterprise Linux allows administrators to bind NICs together into a single channel using the bonding kernel module and a special network interface, called a channel bonding interface. Channel bonding enables two or more network interfaces to act as one, simultaneously increasing the bandwidth and providing redundancy.
To channel bond multiple network interfaces, the administrator must perform the following steps:
  1. Add the following line to /etc/modprobe.conf:
    alias bond<N> bonding
    Replace <N> with the interface number, such as 0. For each configured channel bonding interface, there must be a corresponding entry in /etc/modprobe.conf.
  2. Configure a channel bonding interface as outlined in Seção 15.2.3, “Channel Bonding Interfaces”.
  3. To enhance performance, adjust available module options to ascertain what combination works best. Pay particular attention to the miimon or arp_interval and the arp_ip_target parameters. Refer to Seção 43.5.2.1, “bonding Module Directives” for a list of available options and how to quickly determine the best ones for your bonded interface.

43.5.2.1. bonding Module Directives

It is a good idea to test which channel bonding module parameters work best for your bonded interfaces before adding them to the BONDING_OPTS="<bonding parameters>" directive in your bonding interface configuration file (ifcfg-bond0 for example). Parameters to bonded interfaces can be configured without unloading (and reloading) the bonding module by manipulating files in the sysfs file system.
sysfs is a virtual file system that represents kernel objects as directories, files and symbolic links. sysfs can be used to query for information about kernel objects, and can also manipulate those objects through the use of normal file system commands. The sysfs virtual file system has a line in /etc/fstab, and is mounted under /sys. All bonded interfaces can be configured dynamically by interacting with and manipulating files under the /sys/class/net/ directory.
After you have created a channel bonding interface file such as ifcfg-bond0 and inserted SLAVE=yes and MASTER=bond0 directives in the bonded interfaces following the instructions in Seção 15.2.3, “Channel Bonding Interfaces”, you can proceed to testing and determining the best parameters for your bonded interface.
First, bring up the bond you created by running ifconfig bond<N>  up as root:
ifconfig bond0 up
If you have correctly created the ifcfg-bond0 bonding interface file, you will be able to see bond0 listed in the output of running ifconfig (without any options):
~]# ifconfig
bond0     Link encap:Ethernet  HWaddr 00:00:00:00:00:00
          UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)
eth0      Link encap:Ethernet  HWaddr 52:54:00:26:9E:F1
          inet addr:192.168.122.251  Bcast:192.168.122.255  Mask:255.255.255.0
          inet6 addr: fe80::5054:ff:fe26:9ef1/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:207 errors:0 dropped:0 overruns:0 frame:0
          TX packets:205 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:70374 (68.7 KiB)  TX bytes:25298 (24.7 KiB)
[output truncated]
To view all existing bonds, even if they are not up, run:
~]# cat /sys/class/net/bonding_masters
bond0
You can configure each bond individually by manipulating the files located in the /sys/class/net/bond<N>/bonding/ directory. First, the bond you are configuring must be taken down:
ifconfig bond0 down
As an example, to enable MII monitoring on bond0 with a 1 second interval, you could run (as root):
echo 1000 > /sys/class/net/bond0/bonding/miimon
To configure bond0 for balance-alb mode, you could run either:
echo 6 > /sys/class/net/bond0/bonding/mode
...or, using the name of the mode:
echo balance-alb > /sys/class/net/bond0/bonding/mode
After configuring some options for the bond in question, you can bring it up and test it by running ifconfig bond<N> up . If you decide to change the options, take the interface down, modify its parameters using sysfs, bring it back up, and re-test.
Once you have determined the best set of parameters for your bond, add those parameters as a space-separated list to the BONDING_OPTS= directive of the /etc/sysconfig/network-scripts/ifcfg-bond<N> file for the bonded interface you are configuring. Whenever that bond is brought up (for example, by the system during the boot sequence if the ONBOOT=yes directive is set), the bonding options specified in the BONDING_OPTS will take effect for that bond. For more information on configuring bonded interfaces (and BONDING_OPTS), refer to Seção 15.2.3, “Channel Bonding Interfaces”.
The following is a list of available channel bonding module parameters for the bonding module. For more in-depth information on configuring channel bonding and the exhaustive list of bonding module parameters, install the kernel-doc package and then locating and opening the included bonding.txt file:
yum -y install kernel-doc
nano -w $(rpm -ql kernel-doc | grep bonding.txt)
Bonding Interface Parameters
arp_interval=<time_in_milliseconds>
Specifies (in milliseconds) how often ARP monitoring occurs.

Important

It is essential that both arp_interval and arp_ip_target parameters are specified, or, alternatively, the miimon parameter is specified. Failure to do so can cause degradation of network performance in the event that a link fails.
If using this setting while in mode=0 or mode=1 (the two load-balancing modes), the network switch must be configured to distribute packets evenly across the NICs. For more information on how to accomplish this, refer to /usr/share/doc/kernel-doc-<kernel_version>/Documentation/networking/bonding.txt
The value is set to 0 by default, which disables it.
arp_ip_target=<ip_address> [,<ip_address_2>,...<ip_address_16> ]
Specifies the target IP address of ARP requests when the arp_interval parameter is enabled. Up to 16 IP addresses can be specified in a comma separated list.
arp_validate=<value>
Validate source/distribution of ARP probes; default is none. Other valid values are active, backup, and all.
debug=<number>
Enables debug messages. Possible values are:
  • 0 — Debug messages are disabled. This is the default.
  • 1 — Debug messages are enabled.
downdelay=<time_in_milliseconds>
Specifies (in milliseconds) how long to wait after link failure before disabling the link. The value must be a multiple of the value specified in the miimon parameter. The value is set to 0 by default, which disables it.
lacp_rate=<value>
Specifies the rate at which link partners should transmit LACPDU packets in 802.3ad mode. Possible values are:
  • slow or 0 — Default setting. This specifies that partners should transmit LACPDUs every 30 seconds.
  • fast or 1 — Specifies that partners should transmit LACPDUs every 1 second.
miimon=<time_in_milliseconds>
Specifies (in milliseconds) how often MII link monitoring occurs. This is useful if high availability is required because MII is used to verify that the NIC is active. To verify that the driver for a particular NIC supports the MII tool, type the following command as root:
ethtool <interface_name> | grep "Link detected:"
In this command, replace <interface_name> with the name of the device interface, such as eth0, not the bond interface. If MII is supported, the command returns:
Link detected: yes
If using a bonded interface for high availability, the module for each NIC must support MII. Setting the value to 0 (the default), turns this feature off. When configuring this setting, a good starting point for this parameter is 100.

Important

It is essential that both arp_interval and arp_ip_target parameters are specified, or, alternatively, the miimon parameter is specified. Failure to do so can cause degradation of network performance in the event that a link fails.
mode=<value>
...where <value> is one of:
  • balance-rr or 0 — Sets a round-robin policy for fault tolerance and load balancing. Transmissions are received and sent out sequentially on each bonded slave interface beginning with the first one available.
  • active-backup or 1 — Sets an active-backup policy for fault tolerance. Transmissions are received and sent out via the first available bonded slave interface. Another bonded slave interface is only used if the active bonded slave interface fails.
  • balance-xor or 2 — Sets an XOR (exclusive-or) policy for fault tolerance and load balancing. Using this method, the interface matches up the incoming request's MAC address with the MAC address for one of the slave NICs. Once this link is established, transmissions are sent out sequentially beginning with the first available interface.
  • broadcast or 3 — Sets a broadcast policy for fault tolerance. All transmissions are sent on all slave interfaces.
  • 802.3ad or 4 — Sets an IEEE 802.3ad dynamic link aggregation policy. Creates aggregation groups that share the same speed and duplex settings. Transmits and receives on all slaves in the active aggregator. Requires a switch that is 802.3ad compliant.
  • balance-tlb or 5 — Sets a Transmit Load Balancing (TLB) policy for fault tolerance and load balancing. The outgoing traffic is distributed according to the current load on each slave interface. Incoming traffic is received by the current slave. If the receiving slave fails, another slave takes over the MAC address of the failed slave.
  • balance-alb or 6 — Sets an Active Load Balancing (ALB) policy for fault tolerance and load balancing. Includes transmit and receive load balancing for IPV4 traffic. Receive load balancing is achieved through ARP negotiation.
num_unsol_na=<number>
Specifies the number of unsolicited IPv6 Neighbor Advertisements to be issued after a failover event. One unsolicited NA is issued immediately after the failover.
The valid range is 0 - 255; the default value is 1. This option affects only the active-backup mode.
primary=<interface_name>
Specifies the interface name, such as eth0, of the primary device. The primary device is the first of the bonding interfaces to be used and is not abandoned unless it fails. This setting is particularly useful when one NIC in the bonding interface is faster and, therefore, able to handle a bigger load.
This setting is only valid when the bonding interface is in active-backup mode. Refer to /usr/share/doc/kernel-doc-<kernel-version>/Documentation/networking/bonding.txt for more information.
primary_reselect=<value>
Specifies the reselection policy for the primary slave. This affects how the primary slave is chosen to become the active slave when failure of the active slave or recovery of the primary slave occurs. This option is designed to prevent flip-flopping between the primary slave and other slaves. Possible values are:
  • always or 0 (default) — The primary slave becomes the active slave whenever it comes back up.
  • better or 1 — The primary slave becomes the active slave when it comes back up, if the speed and duplex of the primary slave is better than the speed and duplex of the current active slave.
  • failure or 2 — The primary slave becomes the active slave only if the current active slave fails and the primary slave is up.
The primary_reselect setting is ignored in two cases:
  • If no slaves are active, the first slave to recover is made the active slave.
  • When initially enslaved, the primary slave is always made the active slave.
Changing the primary_reselect policy via sysfs will cause an immediate selection of the best active slave according to the new policy. This may or may not result in a change of the active slave, depending upon the circumstances
updelay=<time_in_milliseconds>
Specifies (in milliseconds) how long to wait before enabling a link. The value must be a multiple of the value specified in the miimon parameter. The value is set to 0 by default, which disables it.
use_carrier=<number>
Specifies whether or not miimon should use MII/ETHTOOL ioctls or netif_carrier_ok() to determine the link state. The netif_carrier_ok() function relies on the device driver to maintains its state with netif_carrier_on/off ; most device drivers support this function.
The MII/ETHROOL ioctls tools utilize a deprecated calling sequence within the kernel. However, this is still configurable in case your device driver does not support netif_carrier_on/off .
Valid values are:
  • 1 — Default setting. Enables the use of netif_carrier_ok().
  • 0 — Enables the use of MII/ETHTOOL ioctls.

Tip

If the bonding interface insists that the link is up when it should not be, it is possible that your network device driver does not support netif_carrier_on/off .
xmit_hash_policy=<value>
Selects the transmit hash policy used for slave selection in balance-xor and 802.3ad modes. Possible values are:
  • 0 or layer2 — Default setting. This option uses the XOR of hardware MAC addresses to generate the hash. The formula used is:
    (<source_MAC_address> XOR <destination_MAC>) MODULO <slave_count>
    This algorithm will place all traffic to a particular network peer on the same slave, and is 802.3ad compliant.
  • 1 or layer3+4 — Uses upper layer protocol information (when available) to generate the hash. This allows for traffic to a particular network peer to span multiple slaves, although a single connection will not span multiple slaves.
    The formula for unfragmented TCP and UDP packets used is:
    ((<source_port> XOR <dest_port>) XOR
      ((<source_IP> XOR <dest_IP>) AND 0xffff)
        MODULO <slave_count>
    For fragmented TCP or UDP packets and all other IP protocol traffic, the source and destination port information is omitted. For non-IP traffic, the formula is the same as the layer2 transmit hash policy.
    This policy intends to mimic the behavior of certain switches; particularly, Cisco switches with PFC2 as well as some Foundry and IBM products.
    The algorithm used by this policy is not 802.3ad compliant.
  • 2 or layer2+3 — Uses a combination of layer2 and layer3 protocol information to generate the hash.
    Uses XOR of hardware MAC addresses and IP addresses to generate the hash. The formula is:
    (((<source_IP> XOR <dest_IP>) AND 0xffff) XOR
      ( <source_MAC> XOR <destination_MAC> ))
        MODULO <slave_count>
    This algorithm will place all traffic to a particular network peer on the same slave. For non-IP traffic, the formula is the same as for the layer2 transmit hash policy.
    This policy is intended to provide a more balanced distribution of traffic than layer2 alone, especially in environments where a layer3 gateway device is required to reach most destinations.
    This algorithm is 802.3ad compliant.

43.6. Additional Resources

For more information on kernel modules and their utilities, refer to the following resources.

43.6.1. Installed Documentation

  • lsmod man page — description and explanation of its output.
  • insmod man page — description and list of command line options.
  • modprobe man page — description and list of command line options.
  • rmmod man page — description and list of command line options.
  • modinfo man page — description and list of command line options.
  • /usr/share/doc/kernel-doc-<version>/Documentation/kbuild/modules.txt — how to compile and use kernel modules. Note you must have the kernel-doc package installed to read this file.

43.6.2. Useful Websites



[9] A driver is software which enables Linux to use a particular hardware device. Without a driver, the kernel cannot communicate with attached devices.

Capítulo 44. The kdump Crash Recovery Service

kdump is an advanced crash dumping mechanism. When enabled, the system is booted from the context of another kernel. This second kernel reserves a small amount of memory, and its only purpose is to capture the core dump image in case the system crashes. Since being able to analyze the core dump helps significantly to determine the exact cause of the system failure, it is strongly recommended to have this feature enabled.
This chapter explains how to configure, test, and use the kdump service in Red Hat Enterprise Linux, and provides a brief overview of how to analyze the resulting core dump using the crash debugging utility.

44.1. Configuring the kdump Service

Note

To use the kdump service, you must have the kexec-tools package installed. Refer to Parte II, “Gerenciamento de Pacotes” for more information on how to install new packages in Red Hat Enterprise Linux.
This section covers three common means of configuring the kdump service: at the first boot, using the Kernel Dump Configuration graphical utility, and doing so manually on the command line. It also describes how to test the configuration to verify that everything works as expected.

44.1.1. Configuring the kdump at First Boot

When the system boots for the first time, a firstboot application is launched allowing you to perform a basic configuration. This includes the kdump service.
The kdump configuration screen
The kdump configuration screen
Figura 44.1. The kdump configuration screen

Important

Unless the system has enough memory, this option will not be available. For the information on minimum memory requirements, refer to the Required minimums section of the Red Hat Enterprise Linux comparison chart. Note that when the kdump crash recovery is enabled, the minimum memory requirements increase by the amount of memory reserved for it. This value is determined by a user, and defaults to 128 MB.

44.1.1.1. Enabling the Service

To start the kdump daemon at boot time, select the Enable kdump? check box. This will enable the service for runlevels 2, 3, 4, and 5, and start it for the current session. Similarly, unselecting the check box will disable it for all runlevels and stop the service immediately.

44.1.1.2. Configuring the Memory Usage

To configure the amount of memory that is reserved for the kdump kernel, click the up and down arrow buttons next to the Kdump Memory field to increase or decrease the value. Notice that the Usable System Memory field changes accordingly showing you the remaining memory that will be available to the system.

44.1.2. Using the Kernel Dump Configuration Utility

To start the Kernel Dump Configuration utility, select ApplicationsSystem ToolsKdump from the panel, or type system-config-kdump at a shell prompt (for example, xterm or GNOME Terminal). Unless you are already authenticated, you will be prompted to enter the superuser password.
The Kernel Dump Configuration utility
Kernel Dump Configuration
Figura 44.2. The Kernel Dump Configuration utility

The utility allows you to configure kdump as well as to enable or disable starting the service at boot time. When you are done, click OK to save the changes. The system reboot will be requested.

Important

Unless the system has enough memory, the utility will not start, and you will be presented with an error message. For the information on minimum memory requirements, refer to the Required minimums section of the Red Hat Enterprise Linux comparison chart. Note that when the kdump crash recovery is enabled, the minimum memory requirements increase by the amount of memory reserved for it. This value is determined by a user, and defaults to 128 MB.

44.1.2.1. Enabling the Service

To start the kdump daemon at boot time, select the Enable kdump check box. This will enable the service for runlevels 2, 3, 4, and 5, and start it for the current session. Similarly, unselecting the check box will disable it for all runlevels and stop the service immediately.

44.1.2.2. Configuring the Memory Usage

To configure the amount of memory that is reserved for the kdump kernel, click the up and down arrow buttons next to the New kdump Memory field to increase or decrease the value. Notice that the Usable Memory field changes accordingly showing you the remaining memory that will be available to the system.

44.1.2.3. Configuring the Target Type

When a kernel crash is captured, the core dump can be either stored as a file in a local file system, written directly to a device, or sent over a network using the NFS (Network File System) or SSH (Secure Shell) protocol. To change this, click the Edit Location button, and select a location type as described below.
The Edit Location dialog
Edit Location
Figura 44.3. The Edit Location dialog

To save the dump to the local file system, select file from the pulldown list. Optionally, if you wish to write the file to a different partition, select ext3 or ext2 from the pulldown list according to the file system you are using, and enter a valid device name to the Enter location field. Note that after clicking OK, you can then customize the destination directory by changing the value in the Path field at the bottom.
To write the dump directly to a device, select raw from the pulldown list, and enter a valid device name (for example, /dev/sdb1). When you are done, click OK to confirm your choice.
To store the dump to a remote machine using the NFS protocol, select nfs from the pulldown list, and enter a valid target in the hostname:directory form (for example, penguin.example.com:/export). Clicking the OK button will confirm your changes. Finally, edit the value of the Path field to customize the destination directory (for instance, cores).
To store the dump to a remote machine using the SSH protocol, select ssh from the pulldown list, and enter a valid username and hostname in the username@hostname form (for example, john@penguin.example.com). Clicking the OK button will confirm your changes. Finally, edit the value of the Path field to customize the destination directory (for instance, /export/cores).
Refer to Capítulo 19, OpenSSH for information on how to configure an SSH server, and how to set up a key-based authentication.

44.1.2.4. Configuring the Core Collector

To reduce the size of the vmcore dump file, kdump allows you to specify an external application (that is, a core collector) to compress the data, and optionally leave out all irrelevant information. Currently, the only fully supported core collector is makedumpfile.
To enable the dump file compression, make sure the -c parameter is listed after the makedumpfile command in the Core Collector field (for example, makedumpfile -c).
To remove certain pages from the dump, add the -d value parameter after the makedumpfile command in the Core Collector field. The value is a sum of values of pages you want to omit as described in Tabela 44.1, “Supported filtering levels”. For example, to remove both zero and free pages, use makedumpfile -d 17.
Refer to the manual page for makedumpfile for a complete list of available options.

44.1.2.5. Changing the Default Action

To choose what action to perform when kdump fails to create a core dump, select the appropriate option from the Default Action pulldown list. Available options are mount rootfs and run /sbin/init (the default action), reboot (to reboot the system), shell (to present a user with an interactive shell prompt), and halt (to halt the system).

44.1.3. Configuring kdump on the Command Line

To perform actions described in this section, you have to be logged in as a superuser:
~]$ su -
Password:

44.1.3.1. Configuring the Memory Usage

To configure the amount of memory that is reserved for the kdump kernel, open the /boot/grub/grub.conf file in a text editor and add the crashkernel=<size>M@16M parameter to the list of kernel options as shown in Exemplo 44.1, “A sample /boot/grub/grub.conf file”.
Exemplo 44.1. A sample /boot/grub/grub.conf file
# grub.conf generated by anaconda
#
# Note that you do not have to rerun grub after making changes to this file
# NOTICE:  You have a /boot partition.  This means that
#          all kernel and initrd paths are relative to /boot/, eg.
#          root (hd0,0)
#          kernel /vmlinuz-version ro root=/dev/sda3
#          initrd /initrd-version.img
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title Red Hat Enterprise Linux Server (2.6.18-274.3.1.el5)
        root (hd0,0)
        kernel /vmlinuz-2.6.18-274.3.1.el5 ro root=/dev/sda3 crashkernel=128M@16M
        initrd /initrd-2.6.18-274.3.1.el5.img

Important

When the kdump crash recovery is enabled, the minimum memory requirements increase by the amount of memory reserved for it. This value is determined by a user, and defaults to 128 MB, as lower values proved to be unreliable. For more information on minimum memory requirements for Red Hat Enterprise Linux, refer to the Required minimums section of the Red Hat Enterprise Linux comparison chart.

44.1.3.2. Configuring the Target Type

When a kernel crash is captured, the core dump can be either stored as a file in a local file system, written directly to a device, or sent over a network using the NFS (Network File System) or SSH (Secure Shell) protocol. Note that only one of these options can be set at the moment. The default option is to store the vmcore file in the /var/crash/ directory of the local file system. To change this, open the /etc/kdump.conf configuration file in a text editor and edit the options as described below.
To change the local directory in which the core dump is to be saved, remove the hash sign (#) from the beginning of the #path /var/crash line, and replace the value with a desired directory path. Optionally, if you wish to write the file to a different partition, follow the same procedure with the #ext3 /dev/sda3 line as well, and change both the file system type and the device (a device name, a file system label, and UUID are all supported) accordingly. For example:
ext3 /dev/sda4
path /usr/local/cores
To write the dump directly to a device, remove the hash sign (#) from the beginning of the #raw /dev/sda5 line, and replace the value with a desired device name. For example:
raw /dev/sdb1
To store the dump to a remote machine using the NFS protocol, remove the hash sign (#) from the beginning of the #net my.server.com:/export/tmp line, and replace the value with a valid hostname and directory path. For example:
net penguin.example.com:/export/cores
To store the dump to a remote machine using the SSH protocol, remove the hash sign (#) from the beginning of the #net user@my.server.com line, and replace the value with a valid username and hostname. For example:
net john@penguin.example.com
Refer to Capítulo 19, OpenSSH for information on how to configure an SSH server, and how to set up a key-based authentication.

44.1.3.3. Configuring the Core Collector

To reduce the size of the vmcore dump file, kdump allows you to specify an external application (that is, a core collector) to compress the data, and optionally leave out all irrelevant information. Currently, the only fully supported core collector is makedumpfile.
To enable the core collector, open the /etc/kdump.conf configuration file in a text editor, remove the hash sign (#) from the beginning of the #core_collector makedumpfile -c --message-level 1 line, and edit the command line options as described below.
To enable the dump file compression, add the -c parameter. For example:
core_collector makedumpfile -c
To remove certain pages from the dump, add the -d value parameter, where value is a sum of values of pages you want to omit as described in Tabela 44.1, “Supported filtering levels”. For example, to remove both zero and free pages, use the following:
core_collector makedumpfile -d 17 -c
Refer to the manual page for makedumpfile for a complete list of available options.
Tabela 44.1. Supported filtering levels
Option Description
1 Zero pages
2 Cache pages
4 Cache private
8 User pages
16 Free pages

44.1.3.4. Changing the Default Action

By default, when kdump fails to create a core dump, the root file system is mounted and /sbin/init is run. To change this behavior, open the /etc/kdump.conf configuration file in a text editor, remove the hash sign (#) from the beginning of the #default shell line, and replace the value with a desired action as described in Tabela 44.2, “Supported actions”. For example:
default halt
Tabela 44.2. Supported actions
Option Action
reboot Reboot the system, losing the core in the process.
halt After failing to capture a core, halt the system.
shell Run the msh session from within the initramfs, allowing a user to record the core manually.

44.1.3.5. Enabling the Service

To start the kdump daemon at boot time, type the following at a shell prompt:
~]# chkconfig kdump on
This will enable the service for runlevels 2, 3, 4, and 5. Similarly, typing chkconfig kdump off will disable it for all runlevels. To start the service in the current session, use the following command:
~]# service kdump start
No kdump initial ramdisk found.                            [WARNING]
Rebuilding /boot/initrd-2.6.18-194.8.1.el5kdump.img
Starting kdump:                                            [  OK  ]
For more information on runlevels and configuring services in general, refer to Capítulo 17, Controlando Acesso aos Serviços.

44.1.4. Testing the Configuration

Caution

The commands below will cause the kernel to crash. Use caution when following these steps, and by no means use them on a production machine.
To test the configuration, reboot the system with kdump enabled, and make sure that the service is running:
~]# service kdump status
Kdump is operational
Then type the following commands at a shell prompt:
~]# echo 1 > /proc/sys/kernel/sysrq
~]# echo c > /proc/sysrq-trigger
This will force the Linux kernel to crash, and the YYYY-MM-DD-HH:MM/vmcore file will be copied to the location you have selected in the configuration (that is, to /var/crash/ by default).

44.2. Analyzing the Core Dump

Note

To analyze the vmcore dump file, you must have the crash and kernel-debuginfo packages installed. To do so, type the following at a shell prompt:
~]# yum install --enablerepo=rhel-debuginfo crash kernel-debuginfo
Refer to Parte II, “Gerenciamento de Pacotes” for more information on how to install new packages in Red Hat Enterprise Linux.
To determine the cause of the system crash, you can use the crash utility. This utility allows you to interactively analyze a running Linux system as well as a core dump created by netdump, diskdump, xendump, or kdump. When started, it presents you with an interactive prompt very similar to the GNU Debugger (GDB).
To start the utility, type the command in the following form at a shell prompt:
crash /var/crash/timestamp/vmcore /usr/lib/debug/lib/modules/kernel/vmlinux
Note that the kernel version should be the same as the one that was captured by kdump. To find out which kernel you are currently running, use the uname -r command.
Exemplo 44.2. Running the crash utility
~]# crash /var/crash/2010-08-04-17\:55/vmcore \
/usr/lib/debug/lib/modules/2.6.18-194.8.1.el5/vmlinux

crash 4.1.2-4.el5_5.1
Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009  Red Hat, Inc.
Copyright (C) 2004, 2005, 2006  IBM Corporation
Copyright (C) 1999-2006  Hewlett-Packard Co
Copyright (C) 2005, 2006  Fujitsu Limited
Copyright (C) 2006, 2007  VA Linux Systems Japan K.K.
Copyright (C) 2005  NEC Corporation
Copyright (C) 1999, 2002, 2007  Silicon Graphics, Inc.
Copyright (C) 1999, 2000, 2001, 2002  Mission Critical Linux, Inc.
This program is free software, covered by the GNU General Public License,
and you are welcome to change it and/or distribute copies of it under
certain conditions.  Enter "help copying" to see the conditions.
This program has absolutely no warranty.  Enter "help warranty" for details.
 
GNU gdb 6.1
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu"...

      KERNEL: /usr/lib/debug/lib/modules/2.6.18-194.8.1.el5/vmlinux
    DUMPFILE: /var/crash/2010-08-04-17:55/vmcore
        CPUS: 1
        DATE: Wed Aug  4 17:50:41 2010
      UPTIME: 00:56:53
LOAD AVERAGE: 0.47, 0.47, 0.55
       TASKS: 128
    NODENAME: localhost.localdomain
     RELEASE: 2.6.18-194.el5
     VERSION: #1 SMP Tue Mar 16 21:52:43 EDT 2010
     MACHINE: i686  (2702 Mhz)
      MEMORY: 1 GB
       PANIC: "SysRq : Trigger a crashdump"
         PID: 6042
     COMMAND: "bash"
        TASK: f09c7000  [THREAD_INFO: e1ba9000]
         CPU: 0
       STATE: TASK_RUNNING (SYSRQ)

crash>

To exit the interactive prompt and terminate crash, type exit.

44.2.1. Displaying the Message Buffer

To display the kernel message buffer, type the log command at the interactive prompt.
Exemplo 44.3. Displaying the kernel message buffer
crash> log
Linux version 2.6.18-194.el5 (mockbuild@x86-007.build.bos.redhat.com) (gcc version 4.1.2 20080704 (Red Hat 4.1.2-48)) #1 SMP Tue Mar 16 21:52:43 EDT 2010
BIOS-provided physical RAM map:
 BIOS-e820: 0000000000010000 - 000000000009fc00 (usable)
 BIOS-e820: 000000000009fc00 - 00000000000a0000 (reserved)
 BIOS-e820: 00000000000f0000 - 0000000000100000 (reserved)
 BIOS-e820: 0000000000100000 - 000000003fff0000 (usable)
 BIOS-e820: 000000003fff0000 - 0000000040000000 (ACPI data)
 BIOS-e820: 00000000fffc0000 - 0000000100000000 (reserved)
127MB HIGHMEM available.
896MB LOWMEM available.
Using x86 segment limits to approximate NX protection
On node 0 totalpages: 262128
  DMA zone: 4096 pages, LIFO batch:0
  Normal zone: 225280 pages, LIFO batch:31
  HighMem zone: 32752 pages, LIFO batch:7
DMI 2.5 present.
Using APIC driver default
... several lines omitted ...
SysRq : Trigger a crashdump

Type help log for more information on the command usage.

44.2.2. Displaying a Backtrace

To display the kernel stack trace, type the bt command at the interactive prompt. You can use bt pid to display the backtrace of the selected process.
Exemplo 44.4. Displaying the kernel stack trace
crash> bt
PID: 6042   TASK: f09c7000  CPU: 0   COMMAND: "bash"
 #0 [e1ba9d10] schedule at c061c738
 #1 [e1ba9d28] netlink_getsockopt at c05d50bb
 #2 [e1ba9d34] netlink_queue_skip at c05d40d5
 #3 [e1ba9d40] netlink_sock_destruct at c05d506d
 #4 [e1ba9d84] sock_recvmsg at c05b6cc8
 #5 [e1ba9dd4] enqueue_task at c041eed5
 #6 [e1ba9dec] try_to_wake_up at c041f798
 #7 [e1ba9e10] vsnprintf at c04efef2
 #8 [e1ba9ec0] machine_kexec at c0419bf0
 #9 [e1ba9f04] sys_kexec_load at c04448a1
#10 [e1ba9f4c] tty_audit_exit at c0549f06
#11 [e1ba9f50] tty_audit_add_data at c0549d5d
#12 [e1ba9f84] do_readv_writev at c0476055
#13 [e1ba9fb8] system_call at c0404f10
    EAX: ffffffda  EBX: 00000001  ECX: b7f7f000  EDX: 00000002 
    DS:  007b      ESI: 00000002  ES:  007b      EDI: b7f7f000
    SS:  007b      ESP: bf83f478  EBP: bf83f498
    CS:  0073      EIP: 009ac402  ERR: 00000004  EFLAGS: 00000246

Type help bt for more information on the command usage.

44.2.3. Displaying a Process Status

To display a status of processes in the system, type the ps command at the interactive prompt. You can use ps pid to display the status of the selected process.
Exemplo 44.5. Displaying status of processes in the system
crash> ps
   PID    PPID  CPU   TASK    ST  %MEM     VSZ    RSS  COMM
      0      0   0  c068a3c0  RU   0.0       0      0  [swapper]
      1      0   0  f7c81aa0  IN   0.1    2152    616  init
... several lines omitted ...
   6017      1   0  e39f6550  IN   1.2   40200  13000  gnome-terminal
   6019   6017   0  e39f6000  IN   0.1    2568    708  gnome-pty-helpe
   6020   6017   0  f0421550  IN   0.1    4620   1480  bash
   6021      1   0  f7f69aa0  ??   1.2   40200  13000  gnome-terminal
   6039   6020   0  e7e84aa0  IN   0.1    5004   1300  su
>  6042   6039   0  f09c7000  RU   0.1    4620   1464  bash

Type help ps for more information on the command usage.

44.2.4. Displaying Virtual Memory Information

To display basic virtual memory information, type the vm command at the interactive prompt. You can use vm pid to display information on the selected process.
Exemplo 44.6. Displaying virtual memory information of the current context
crash> vm
PID: 6042   TASK: f09c7000  CPU: 0   COMMAND: "bash"
   MM       PGD      RSS    TOTAL_VM
e275ee40  e2b08000  1464k    4620k  
  VMA       START      END    FLAGS  FILE
e315d764    1fe000    201000     75  /lib/libtermcap.so.2.0.8
e315de9c    201000    202000 100073  /lib/libtermcap.so.2.0.8
c9b040d4    318000    46a000     75  /lib/libc-2.5.so
e315da04    46a000    46c000 100071  /lib/libc-2.5.so
e315d7b8    46c000    46d000 100073  /lib/libc-2.5.so
e315de48    46d000    470000 100073  
e315dba8    9ac000    9ad000 8040075  
c9b04a04    a2f000    a4a000    875  /lib/ld-2.5.so
c9b04374    a4a000    a4b000 100871  /lib/ld-2.5.so
e315d6bc    a4b000    a4c000 100873  /lib/ld-2.5.so
e315d908    fa1000    fa4000     75  /lib/libdl-2.5.so
e315db00    fa4000    fa5000 100071  /lib/libdl-2.5.so
e315df44    fa5000    fa6000 100073  /lib/libdl-2.5.so
e315d320    ff0000    ffa000     75  /lib/libnss_files-2.5.so
e315d668    ffa000    ffb000 100071  /lib/libnss_files-2.5.so
e315def0    ffb000    ffc000 100073  /lib/libnss_files-2.5.so
e315d374   8048000   80f5000   1875  /bin/bash
c9b045c0   80f5000   80fa000 101873  /bin/bash
... several lines omitted ...

Type help vm for more information on the command usage.

44.2.5. Displaying Open Files

To display information about open files, type the files command at the interactive prompt. You can use files pid to display files opened by the selected process.
Exemplo 44.7. Displaying information about open files of the current context
crash> files
PID: 6042   TASK: f09c7000  CPU: 0   COMMAND: "bash"
ROOT: /    CWD: /root
 FD    FILE     DENTRY    INODE    TYPE  PATH
  0  e33be480  e609bf70  f0e1d880  CHR   /dev/pts/1
  1  e424d8c0  d637add8  f7809b78  REG   /proc/sysrq-trigger
  2  e33be480  e609bf70  f0e1d880  CHR   /dev/pts/1
 10  e33be480  e609bf70  f0e1d880  CHR   /dev/pts/1
255  e33be480  e609bf70  f0e1d880  CHR   /dev/pts/1

Type help files for more information on the command usage.

44.3. Additional Resources

44.3.1. Installed Documentation

man kdump.conf
The manual page for the /etc/kdump.conf configuration file containing the full documentation of available options.
man kexec
The manual page for kexec containing the full documentation on its usage.
man crash
The manual page for the crash utility containing the full documentation on its usage.
/usr/share/doc/kexec-tools-version/kexec-kdump-howto.txt
An overview of the kdump and kexec installation and usage.

44.3.2. Useful Websites

https://access.redhat.com/kb/docs/DOC-6039
The Red Hat Knowledgebase article about the kexec and kdump configuration.
http://people.redhat.com/anderson/
The crash utility homepage.

Parte VII. Autenticação e Segurança

A Red Hat Enterprise Linux oferece uma variedade de ferramentas e métodos para servir como parte de uma estratégia de segurança compreensiva, não importando se os administradores de sistema precisam assegurar seus sistemas de missão crítica, serviços ou dados.
Este capítulo oferece uma apresentação geral da segurança e especificamente a partir do ponto de vista do Red Hat Enterprise Linux. Ele oferece informação conceitual nas áreas de avaliação de segurança, exploits comuns e resposta à intrusão e incidentes. Também oferece informação sobre configuração específica e conceitual para incrementar a segurança de implementações Workstation, Server, VPN, firewall, dentre outras, utilizando o SELinux.
Este capítulo presume que os usuários já possuam um conhecimento básico de segurança de TI e conseqüentemente oferece somente cobertura mínima de práticas de segurança comum, tais como, controle de acesso físico, políticas e procedimentos profundos de contabilidade, auditoria, etc. Quando apropriado, a consulta é realizada nos recursos externos para esta e qualquer outra informação relacionada.

Índice

45. Visão Geral de Segurança
45.1. Introdução à Segurança
45.1.1. What is Computer Security?
45.1.2. Security Controls
45.1.3. Conclusion
45.2. Avaliação de Vulnerabilidade
45.2.1. Pensando Como o Inimigo
45.2.2. Definindo Avaliação e Testes
45.2.3. Avaliando as Ferramentas
45.3. Atacantes e Vulnerabilidades
45.3.1. Uma Breve História sobre Hackers
45.3.2. Ameaças à Segurança da Rede
45.3.3. Ameaças à Segurança do Servidor
45.3.4. Ameaças à Segurança de Estações de Trabalho e PCs
45.4. Exploits e Ataques Freqüentes
45.5. Atualizações de Segurança
45.5.1. Atualizando Pacotes
46. Assegurando sua Rede de Trabalho
46.1. Segurança de Estações de Trabalho
46.1.1. Avaliando a Segurança de Estações de Trabalho
46.1.2. Segurança do BIOS e do Carregador de Inicialização
46.1.3. Segurança da Senha
46.1.4. Controles Administrativos
46.1.5. Serviços de Rede Disponíveis
46.1.6. Firewalls Pessoais
46.1.7. Ferramentas de Comunicação com Segurança Aprimorada
46.2. Segurança do Servidor
46.2.1. Protegendo Serviços com TCP Wrappers e xinetd
46.2.2. Protegendo o Portmap
46.2.3. Protegendo o NIS
46.2.4. Protegendo o NFS
46.2.5. Protegendo o Servidor HTTP Apache
46.2.6. Protegendo o FTP
46.2.7. Protegendo o Sendmail
46.2.8. Verificando Quais Portas estão Escutando
46.3. Single Sign-on (SSO)
46.3.1. Introdução
46.3.2. Iniciando seu Cartão Inteligente
46.3.3. Como Funciona o Registro do Cartão Inteligente
46.3.4. Como Funciona a Autenticação do Cartão Inteligente
46.3.5. Configurando o Firefox para usar o Kerberos para SSO.
46.4. Módulos de Autenticação Plugáveis (Pluggable Authentication Modules - PAM)
46.4.1. Vantagens do PAM
46.4.2. Arquivos de Configuração do PAM
46.4.3. Formato do Arquivo de Configuração do PAM
46.4.4. Exemplos de Arquivos de Configuração do PAM
46.4.5. Criando Módulos PAM
46.4.6. O PAM e o Caching de Credenciais Administrativas
46.4.7. O PAM e a Propriedade de Dispositivos
46.4.8. Recursos Adicionais
46.5. TCP Wrappers e xinetd
46.5.1. TCP Wrappers
46.5.2. Arquivos de Configuração do TCP Wrappers
46.5.3. xinetd
46.5.4. Arquivos de Configuração do xinetd
46.5.5. Recursos Adicionais
46.6. Kerberos
46.6.1. O que é o Kerberos?
46.6.2. Terminologia do Kerberos
46.6.3. Como o Kerberos Funciona
46.6.4. Kerberos e PAM
46.6.5. Configurando o Servidor Kerberos 5
46.6.6. Configurando um Cliente Kerberos 5
46.6.7. Mapeamento Domínio-para-território
46.6.8. Configurando KDCs Secundários
46.6.9. Configurando a Autenticação Cross-Realm - (Cross Realm Authentication)
46.6.10. Recursos Adicionais
46.7. Redes Privadas Virtuais (Virtual Private Networks - VPNs)
46.7.1. Como um VPN Funciona?
46.7.2. VPNs e o Red Hat Enterprise Linux
46.7.3. IPsec
46.7.4. Criando uma Conexão IPsec
46.7.5. Instalação do IPsec
46.7.6. Configuração Host-a-Host do IPsec
46.7.7. Configuração Rede-a-Rede do IPsec
46.7.8. Iniciando e Parando uma Conexão IPsecConnection
46.8. Firewalls
46.8.1. Netfilter 6
46.8.2. Configurações Básicas de Firewall
46.8.3. Usando IPTables
46.8.4. Filtros de IPTables Comuns
46.8.5. Regras FORWARD e NAT
46.8.6. Software Malicioso e Endereços IP Falsificados (spoofed)
46.8.7. IPTables e Rastreamento de Conexão
46.8.8. IPv6
46.8.9. Recursos Adicionais
46.9. IPTables
46.9.1. Filtragem de Pacotes
46.9.2. Diferenças entre IPTables e IPChains
46.9.3. Opções de Comando para o IPTables
46.9.4. Salvando Regras do IPTables
46.9.5. Scripts de Controle do IPTables
46.9.6. IPTables e IPv6
46.9.7. Recursos Adicionais
47. Segurança e SELinux
47.1. Mecanismos de Controle de Acesso (ACM)
47.1.1. Controle de Acesso Discricionário (DAC)
47.1.2. Lista de Controle de Acesso (ACLs)
47.1.3. Controle de Acesso Obrigatório (MAC)
47.1.4. Controle de Acesso baseado na Função (RBAC)
47.1.5. Segurança de Nível Múltiplo (MLS)
47.1.6. Segurança de Categoria Múltipla (MCS)
47.2. Introdução ao SELinux
47.2.1. Visão Geral do SELinux
47.2.2. Arquivos Relacionados ao SELinux
47.2.3. Recursos Adicionais
47.3. Breves Fundamentos e História do SELinux
47.4. Segurança de Categoria Múltipla (MCS)
47.4.1. Apresentação
47.4.2. Aplicativos para Segurança de Categoria Múltipla.
47.4.3. SELinux Conteúdo de Segurança
47.5. Iniciando com a Segurança de Categoria Múltipla (MCS)
47.5.1. Introdução
47.5.2. Comparing SELinux and Standard Linux User Identities
47.5.3. Configuring Categories
47.5.4. Assigning Categories to Users
47.5.5. Assigning Categories to Files
47.6. Segurança de Nível Múltiplo (MLS)
47.6.1. Porque Nível Múltiplo?
47.6.2. Níveis de Segurança, Objetos e Assuntos.
47.6.3. Política MLS
47.6.4. Certificação LSPP
47.7. Visão Geral da Política SELinux
47.7.1. O que é a Política SELinux?
47.7.2. Onde está a Política
47.7.3. A Função da Política no Processo de Inicialização
47.7.4. Classes de Objeto e Permissões
47.8. Visão Geral da Política Alvo
47.8.1. O que é Política Alvo?
47.8.2. Arquivos e Diretórios de Política Alvo.
47.8.3. Entendendo os Usuários e Funções na Política Alvo.
48. Trabalhando com SELinux
48.1. End User Control of SELinux
48.1.1. Moving and Copying Files
48.1.2. Checking the Security Context of a Process, User, or File Object
48.1.3. Relabeling a File or Directory
48.1.4. Creating Archives That Retain Security Contexts
48.2. Administrator Control of SELinux
48.2.1. Viewing the Status of SELinux
48.2.2. Relabeling a File System
48.2.3. Managing NFS Home Directories
48.2.4. Granting Access to a Directory or a Tree
48.2.5. Backing Up and Restoring the System
48.2.6. Enabling or Disabling Enforcement
48.2.7. Enable or Disable SELinux
48.2.8. Changing the Policy
48.2.9. Specifying the Security Context of Entire File Systems
48.2.10. Changing the Security Category of a File or User
48.2.11. Running a Command in a Specific Security Context
48.2.12. Useful Commands for Scripts
48.2.13. Changing to a Different Role
48.2.14. When to Reboot
48.3. Controle Analítico do SELinux
48.3.1. Habilitando a Auditoria Kernel
48.3.2. Despejo e Visualização de Logs.
49. Padronizando a Política do SELinux
49.1. Apresentação
49.1.1. Política modular
49.2. Construindo um Módulo de Política Local
49.2.1. Usar o audit2 permite a Construção de um Módulo de Política Local.
49.2.2. Analisando o Arquivo Tipo Enforcement (TE)
49.2.3. Carregando o Pacote de Política
50. Referências

Capítulo 45. Visão Geral de Segurança

Indústrias de segurança de computadores pessoais e de rede formaram-se devido ao aumento na dependência de computadores potentes, em rede, para auxiliar na administração de negócios e manter controle sobre informações pessoais. Empresas angariaram o conhecimento e a perícia de especialistas em segurança para conduzir a auditoria de sistemas de forma adequada e fornecer soluções sob medida para as exigências operacionais da organização. Devido à natureza dinâmica da maioria das organizações, com funcionários acessando recursos de TI, tanto dentro da empresa quanto remotamente, houve uma maior demanda de ambientes seguros de computação.
Infelizmente, a maioria das organizações (assim como indivíduos) consideram aspectos de segurança tarde demais, ignorando este processo em favor de máquinas mais velozes, e por questões de produtividade e orçamentárias. Protocolos de segurança adequados são normalmente efetivados postmortem — após a ocorrência de uma intrusão não autorizada. Especialistas em segurança concordam que a tomada de medidas corretas antes de conectar um site à uma rede não confiável, como a internet, é uma forma eficiente de frustrar a maioria das tentativas de intrusão.

45.1. Introdução à Segurança

45.1.1. What is Computer Security?

Computer security is a general term that covers a wide area of computing and information processing. Industries that depend on computer systems and networks to conduct daily business transactions and access crucial information regard their data as an important part of their overall assets. Several terms and metrics have entered our daily business vocabulary, such as total cost of ownership (TCO) and quality of service (QoS). In these metrics, industries calculate aspects such as data integrity and high-availability as part of their planning and process management costs. In some industries, such as electronic commerce, the availability and trustworthiness of data can be the difference between success and failure.

45.1.1.1. How did Computer Security Come about?

Information security has evolved over the years due to the increasing reliance on public networks not to disclose personal, financial, and other restricted information. There are numerous instances such as the Mitnick and the Vladimir Levin cases that prompted organizations across all industries to rethink the way they handle information transmission and disclosure. The popularity of the Internet was one of the most important developments that prompted an intensified effort in data security.
An ever-growing number of people are using their personal computers to gain access to the resources that the Internet has to offer. From research and information retrieval to electronic mail and commerce transaction, the Internet has been regarded as one of the most important developments of the 20th century.
The Internet and its earlier protocols, however, were developed as a trust-based system. That is, the Internet Protocol was not designed to be secure in itself. There are no approved security standards built into the TCP/IP communications stack, leaving it open to potentially malicious users and processes across the network. Modern developments have made Internet communication more secure, but there are still several incidents that gain national attention and alert us to the fact that nothing is completely safe.

45.1.1.2. Security Today

In February of 2000, a Distributed Denial of Service (DDoS) attack was unleashed on several of the most heavily-trafficked sites on the Internet. The attack rendered yahoo.com, cnn.com, amazon.com, fbi.gov, and several other sites completely unreachable to normal users, as it tied up routers for several hours with large-byte ICMP packet transfers, also called a ping flood. The attack was brought on by unknown assailants using specially created, widely available programs that scanned vulnerable network servers, installed client applications called Trojans on the servers, and timed an attack with every infected server flooding the victim sites and rendering them unavailable. Many blame the attack on fundamental flaws in the way routers and the protocols used are structured to accept all incoming data, no matter where or for what purpose the packets are sent.
Currently, an estimated 945 million people use or have used the Internet worldwide (Computer Industry Almanac, 2004). At the same time:
  • On any given day, there are approximately 225 major incidences of security breach reported to the CERT Coordination Center at Carnegie Mellon University.[10]
  • In 2003, the number of CERT reported incidences jumped to 137,529 from 82,094 in 2002 and from 52,658 in 2001.[11]
  • The worldwide economic impact of the three most dangerous Internet Viruses of the last three years was estimated at US$13.2 Billion.[12]
Computer security has become a quantifiable and justifiable expense for all IT budgets. Organizations that require data integrity and high availability elicit the skills of system administrators, developers, and engineers to ensure 24x7 reliability of their systems, services, and information. Falling victim to malicious users, processes, or coordinated attacks is a direct threat to the success of the organization.
Unfortunately, system and network security can be a difficult proposition, requiring an intricate knowledge of how an organization regards, uses, manipulates, and transmits its information. Understanding the way an organization (and the people that make up the organization) conducts business is paramount to implementing a proper security plan.

45.1.1.3. Standardizing Security

Enterprises in every industry rely on regulations and rules that are set by standards making bodies such as the American Medical Association (AMA) or the Institute of Electrical and Electronics Engineers (IEEE). The same ideals hold true for information security. Many security consultants and vendors agree upon the standard security model known as CIA, or Confidentiality, Integrity, and Availability. This three-tiered model is a generally accepted component to assessing risks of sensitive information and establishing security policy. The following describes the CIA model in further detail:
  • Confidentiality — Sensitive information must be available only to a set of pre-defined individuals. Unauthorized transmission and usage of information should be restricted. For example, confidentiality of information ensures that a customer's personal or financial information is not obtained by an unauthorized individual for malicious purposes such as identity theft or credit fraud.
  • Integrity — Information should not be altered in ways that render it incomplete or incorrect. Unauthorized users should be restricted from the ability to modify or destroy sensitive information.
  • Availability — Information should be accessible to authorized users any time that it is needed. Availability is a warranty that information can be obtained with an agreed-upon frequency and timeliness. This is often measured in terms of percentages and agreed to formally in Service Level Agreements (SLAs) used by network service providers and their enterprise clients.

45.1.2. Security Controls

Computer security is often divided into three distinct master categories, commonly referred to as controls:
  • Physical
  • Technical
  • Administrative
These three broad categories define the main objectives of proper security implementation. Within these controls are sub-categories that further detail the controls and how to implement them.

45.1.2.1. Physical Controls

Physical control is the implementation of security measures in a defined structure used to deter or prevent unauthorized access to sensitive material. Examples of physical controls are:
  • Closed-circuit surveillance cameras
  • Motion or thermal alarm systems
  • Security guards
  • Picture IDs
  • Locked and dead-bolted steel doors
  • Biometrics (includes fingerprint, voice, face, iris, handwriting, and other automated methods used to recognize individuals)

45.1.2.2. Technical Controls

Technical controls use technology as a basis for controlling the access and usage of sensitive data throughout a physical structure and over a network. Technical controls are far-reaching in scope and encompass such technologies as:
  • Encryption
  • Smart cards
  • Network authentication
  • Access control lists (ACLs)
  • File integrity auditing software

45.1.2.3. Controles Administrativos

Administrative controls define the human factors of security. It involves all levels of personnel within an organization and determines which users have access to what resources and information by such means as:
  • Training and awareness
  • Disaster preparedness and recovery plans
  • Personnel recruitment and separation strategies
  • Personnel registration and accounting

45.1.3. Conclusion

Now that you have learned about the origins, reasons, and aspects of security, you can determine the appropriate course of action with regard to Red Hat Enterprise Linux. It is important to know what factors and conditions make up security in order to plan and implement a proper strategy. With this information in mind, the process can be formalized and the path becomes clearer as you delve deeper into the specifics of the security process.

45.2. Avaliação de Vulnerabilidade

Dados o tempo, os recursos e a motivação necessários, um cracker pode violar praticamente qualquer sistema. No final das contas, todos os procedimentos e tecnologias de segurança atualmente disponíveis não podem garantir que quaisquer sistemas estejam protegidos contra intrusos. Roteadores ajudam a proteger suas portas de comunicação (gateways) com a Internet. Firewalls ajudam a proteger os limites da rede. Redes Privadas Virtuais podem transferir dados com segurança através de informações criptografadas. Sistemas de detecção de intrusão podem alertá-lo sobre atividades maléficas. No entanto, o sucesso de cada uma destas tecnologias depende de diversas variáveis, incluindo:
  • A perícia dos funcionários responsáveis pela configuração, monitoração e manutenção das tecnologias
  • A habilidade em consertar e atualizar serviços e kernels eficiente e rapidamente
  • A habilidade dos responsáveis em manter vigília constante sobre a rede
Dado o dinamismo de sistemas e tecnologias de dados, proteger recursos corporativos pode ser bastante complexo. Devido à essa complexidade, geralmente é difícil encontrar peritos para todos os seus sistemas. Enquanto é possível ter pessoal com conhecimento em muitas áreas de segurança da informação em um alto nível, é difícil reter funcionários que são peritos em mais do que algumas áreas. Isto ocorre principalmente porque cada área de segurança da informação requer constante atenção e foco. A segurança da informação não para.

45.2.1. Pensando Como o Inimigo

Suponha que você administre uma rede corporativa. Essas redes são normalmente compostas de sistemas operacionais, aplicativos, servidores, monitores de rede, firewalls, sistemas de detecção de intrusão e outros. Agora imagine tentar manter-se atualizado com cada um destes. Dada a complexidade dos programas e ambientes de rede atuais, exploits e defeitos são uma certeza. Manter-se informado sobre consertos e atualizações para uma rede inteira pode ser uma tarefa perturbadora em uma grande empresa com sistemas heterogêneos.
Com a combinação da necessidade de contar com peritos e a tarefa de manter-se sempre atualizado, torna-se inevitável que incidentes adversos ocorram, sistemas sejam violados, dados corrompidos e serviços interrompidos.
Para aprimorar as tecnologias de segurança e auxiliar na proteção de sistemas, redes e dados, você deve pensar como um cracker e medir a segurança de seus sistemas verificando suas fraquezas. Avaliações preventivas de vulnerabilidades em seus próprios sistemas e recursos de rede podem revelar questões potenciais a serem consideradas antes de um cracker explorá-las.
A vulnerability assessment is an internal audit of your network and system security; the results of which indicate the confidentiality, integrity, and availability of your network (as explained in Seção 45.1.1.3, “Standardizing Security”). Typically, vulnerability assessment starts with a reconnaissance phase, during which important data regarding the target systems and resources is gathered. This phase leads to the system readiness phase, whereby the target is essentially checked for all known vulnerabilities. The readiness phase culminates in the reporting phase, where the findings are classified into categories of high, medium, and low risk; and methods for improving the security (or mitigating the risk of vulnerability) of the target are discussed.
Se tivesse que executar uma avaliação de vulnerabilidade da sua casa, você provavelmente verificaria cada uma das portas para certificar-se de que elas estão fechadas e trancadas. Você também checaria cada janela, assegurando que estão completamente fechadas e corretamente travadas. O mesmo conceito se aplica aos sistemas, redes e dados eletrônicos. Usuários maldosos são os ladrões e vândalos de seus dados. Foque em suas ferramentas, mentalidade e motivações, e você poderá reagir rapidamente às suas ações.

45.2.2. Definindo Avaliação e Testes

As avaliações de vulnerabilidade podem ser divididas em dois tipos: De fora olhando para dentro e de dentro olhando ao redor.
Ao executar uma avaliação de vulnerabilidade de fora olhando para dentro, você está tentando comprometer seus sistemas partindo do lado de fora. Quando você está fora de sua empresa você analisa a partir do ponto de vista de um cracker. Você vê o que o cracker vê — endereços IP publicamente roteáveis, sistemas em sua DMZ, interfaces externas de seu firewall e mais. DMZ significa "demilitarized zone" (zona desmilitarizada), que corresponde a um computador ou à uma pequena sub-rede situados na rede interna, tal como uma LAN privada corporativa, e uma rede externa não-confiável, como a Internet pública. Tipicamente, a DMZ contém dispositivos acessíveis ao tráfego da Internet, como servidores web (HTTP), servidores FTP, servidores SMTP (e-mail) e servidores DNS.
Ao executar uma avaliação de vulnerabilidade de dentro olhando ao redor, você está, de certa maneira, em vantagem já que você é interno e seu status é elevado a confiável. Esse é o ponto de vista que você e seus colegas de trabalho têm ao se autenticarem em seus sistemas. Você vê servidores de impressão, servidores de arquivos, bancos de dados e outros recursos.
Há diferenças notáveis entre estes dois tipos de avaliação de vulnerabilidade. Quando você está dentro de sua empresa, você possui privilégios mais elevados que qualquer entidade externa. Ainda hoje em algumas empresas, a segurança é configurada de modo a manter os intrusos fora. Muito pouco é feito para proteger os internos da empresa (tais como firewalls departamentais, controles de acesso no nível de usuário, procedimentos de autenticação para recursos internos e outros). Geralmente, há muito mais recursos quando estamos dentro olhando ao redor dado que a maioria dos sistemas são internos à uma empresa. Uma vez que você se coloca fora da empresa, imediatamente terá o status não confiável. Os sistemas e recursos disponíveis a você externamente são freqüentemente muito limitados.
Considere a diferença entre as avaliações de vulnerabilidade e testes de penetração. Pense em uma avaliação de vulnerabilidade como o primeiro passo de um teste de penetração. As informações obtidas na avaliação serão utilizadas nos testes. Enquanto a avaliação verifica deficiências e vulnerabilidades potenciais, os testes de penetração tentam explorar os resultados.
O processo de avaliação da infra-estrutura de rede é dinâmico. A segurança de ambos, da informação e física, é dinâmica. Executar uma avaliação traz uma visão geral, que pode incluir falsos positivos e falsos negativos.
Administradores de segurança são tão bons quanto as ferramentas que usam e o conhecimento que possuem. Pegue qualquer uma das ferramentas de avaliação disponíveis, execute-as em seu sistema, e é quase certo que haja pelo menos alguns falsos positivos. O resultado é o mesmo, seja por erro do programa ou do usuário. A ferramenta pode encontrar vulnerabilidades que na realidade não existem (falsos positivos) ou, pior ainda, ela pode não detectar vulnerabilidades que realmente existem (falsos negativos).
Agora que a diferença entre avaliação de vulnerabilidade e teste de penetração está definida, é recomendável revisar os resultados da avaliação cuidadosamente antes de conduzir um teste de penetração como parte de sua nova tática para as melhores práticas.

Atenção

Tentar explorar vulnerabilidades em recursos de produção pode resultar em efeitos adversos na produtividade e eficiência de seus sistemas e rede.
A lista a seguir examina alguns dos benefícios em executar avaliações de vulnerabilidade.
  • Cria foco pró-ativo na segurança da informação
  • Encontra exploits potenciais antes que os crackers os encontrem
  • Resulta em sistemas sendo mantidos atualizados e consertados
  • Promove o crescimento e ajuda a desenvolver as habilidades dos funcionários
  • Reduz perdas financeiras e publicidade negativa

45.2.2.1. Estabeleça uma Metodologia

Para auxiliar na seleção de ferramentas para a avaliação de vulnerabilidade, é útil estabelecer uma metodologia de avaliação de vulnerabilidade. Infelizmente, não há nenhuma metodologia pré-definida ou aprovada pelo setor no momento, porém bom senso e as melhores práticas podem agir suficientemente como guias.
Qual é o alvo? Nós estamos verificando um servidor, ou verificando nossa rede inteira e tudo que há nesta rede? Somos internos ou externos à empresa? As respostas à estas questões são importantes, pois ajudam a determinar não apenas quais ferramentas selecionar, mas também a maneira como são utilizadas.
Para aprender mais sobre o estabelecimento de metodologias, consulte os seguintes sites:

45.2.3. Avaliando as Ferramentas

Uma avaliação pode começar com o uso de alguma forma de ferramenta de coleta de informações. Ao avaliar a rede inteira, primeiramente mapeie o layout para encontrar máquinas que estejam rodando. Após localizá-las, examine cada máquina separadamente. O exame de cada uma destas máquinas requer um outro conjunto de ferramentas. Saber quais ferramentas utilizar pode ser o passo crucial para encontrar vulnerabilidades.
Assim como em qualquer aspecto do cotidiano, há muitas ferramentas diferentes que desempenham a mesma função. Este conceito também se aplica à execução das avaliações de vulnerabilidade. Há ferramentas específicas para sistemas operacionais, para aplicações e até mesmo para redes (baseadas nos protocolos utilizados). Algumas ferramentas são gratuitas e outras não. Algumas ferramentas são intuitivas e fáceis de utilizar, enquanto outras são enigmáticas e mal documentadas, mas possuem funcionalidades que outras não possuem.
Encontrar as ferramentas corretas pode ser uma tarefa desalentadora, e no final das contas, a experiência conta. Se possível, monte um laboratório de testes e experimente quantas ferramentas puder, anotando os pontos fortes e fracos de cada uma. Examine o arquivo README ou a página man da ferramenta. Além disso, procure na Internet por mais informações, como artigos, manuais passo-a-passo ou até mesmo listas de discussão específicas da ferramenta.
As ferramentas explanadas abaixo são apenas uma pequena amostra das ferramentas disponíveis.

45.2.3.1. Escaneando hosts com Nmap

Nmap é uma ferramenta popular incluída no Red Hat Enterprise Linux que pode ser usada para determinar o layout de uma rede. O Nmap já existe há muitos anos e é provavelmente a ferramenta mais utilizada na coleta de informações. Há uma página man excelente que oferece uma descrição detalhada de suas opções e usos. Administradores podem usar o Nmap em uma rede para encontrar sistemas host e portas abertas nestes sistemas.
O Nmap é um primeiro passo eficaz na avaliação de vulnerabilidade. Você pode mapear todas as máquinas dentro de sua rede, e inclusive passar uma opção que permite ao Nmap tentar identificar o sistema operacional rodando numa determinada máquina. O Nmap é uma boa base para estabelecer normas de uso de serviços seguros e para parar serviços não usados.
45.2.3.1.1. Usando o Nmap
O Nmap pode ser executado a partir de um prompt do shell, digitando nmap seguido do nome ou endereço IP da máquina que você deseja escanear.
nmap foo.example.com
Os resultados do scan (que podem levar até alguns minutos, dependendo de onde o host está localizado) devem se parecer com o seguinte:
Starting nmap V. 3.50 ( www.insecure.org/nmap/ )
Interesting ports on localhost.localdomain (127.0.0.1):
(The 1591 ports scanned but not shown below are in state: closed)
Port       State       Service
22/tcp     open        ssh
25/tcp     open        smtp
111/tcp    open        sunrpc
443/tcp    open        https
515/tcp    open        printer
950/tcp    open        oftep-rpc
6000/tcp   open        X11

Nmap run completed -- 1 IP address (1 host up) scanned in 71.825 seconds
O Nmap testa as portas de comunicação mais comuns numa rede por serviços de escuta ou de espera. Esse conhecimento pode ser útil a um administrador que deseja encerrar serviços desnecessários ou não usados.
Para mais informações sobre o uso do Nmap, consulte o site oficial no seguinte endereço:

45.2.3.2. Nessus

O Nessus é um scanner de segurança 'full-service'. Sua arquitetura plug-in permite que usuários o personalizem para seus sistemas e redes. Assim como qualquer scanner, o Nessus é tão bom quanto o banco de dados de assinaturas com o qual ele conta. Felizmente, o Nessus é freqüentemente atualizado e conta com relatório completo, escaneamento do host e buscas de vulnerabilidades em tempo real. Lembre-se que podem haver falsos positivos e falsos negativos, mesmo numa ferramenta tão poderosa e freqüentemente atualizada como o Nessus.

Nota

O Nessus não está incluído no Red Hat Enterprise Linux e não é suportado. Foi incluído neste documento como uma referência para usuários que possam se interessar por esta aplicação tão conhecida.
Para mais informações sobre o Nessus, consulte o site oficial no endereço:

45.2.3.3. Nikto

O Nikto é um excelente scanner de scripts CGI. O Nikto não tem apenas a capacidade de verificar vulnerabilidades CGI, mas também de fazê-lo de maneira evasiva, para enganar sistemas de detecção de intrusão. Acompanha uma documentação excelente que deve ser revisada cuidadosamente antes de executar o programa. Se você tem servidores Web servindo scripts CGI, o Nikto pode ser um excelente recurso para checar a segurança destes servidores.

Nota

O Nikto não está incluído no Red Hat Enterprise Linux e não é suportado. Foi incluído neste documento como uma referência para usuários que possam se interessar por esta aplicação tão conhecida.
Mais informações sobre o Nikto podem ser encontradas no seguinte endereço:

45.2.3.4. VLAD the Scanner

O VLAD é um scanner de vulnerabilidades desenvolvido pela equipe RAZOR na Bindview, Inc., que verifica a lista das dez questões mais comuns de segurança da SANS (questões do SNMP, compartilhamento de arquivos, etc.). Vale a pena investigar o VLAD, apesar de não ter tantas funcionalidades quanto o Nessus.

Nota

O VLAD não está incluído no Red Hat Enterprise Linux e não é suportado. Foi incluído neste documento como uma referência para usuários que possam se interessar por esta aplicação tão conhecida.
Mais informações sobre o VLAD podem ser encontradas no site da equipe RAZOR no seguinte endereço:

45.2.3.5. Antecipando suas Necessidades Futuras

Dependendo do seu objetivo e recursos, existe uma grande disponilidade de ferramentas. Há ferramentas para redes sem fio, redes Novell, sistemas Windows, sistemas Linux entre outros. Outra parte essencial ao executar avaliações é incluir uma revisão de segurança física, controle de pessoal ou avaliação da rede de voz/PBX. Conceitos novos como o escaneamento war walking no perímetro das estruturas físicas de sua empresa para encontrar vulnerabilidades da rede sem fio são conceitos emergentes que você pode considerar e, se necessário, incorporá-los às suas avaliações. Imaginação e exposição são os únicos limites para planejar e conduzir avaliações de vulnerabilidade.

45.3. Atacantes e Vulnerabilidades

Para planejar e implementar uma boa estratégia de segurança, comece entendendo algumas das questões que atacantes determinados e motivados exploram para comprometer sistemas. Mas antes de detalhar estas questões, precisamos definir a terminologia utilizada ao identificar um atacante.

45.3.1. Uma Breve História sobre Hackers

O significado moderno da palavra hacker tem origem nos anos 60 no Tech Model Railroad Club do Instituto de Tecnologia de Massachusetts (MIT), que desenvolveu modelos de trens de alta fidelidade e com detalhes complexos. Hacker era o nome usado para os membros do clube que vinham a descobrir um novo truque ou uma nova forma de resolver um problema.
Desde então o termo hacker descreve de tudo, desde entusiastas a programadores talentosos. Um aspecto comum dentre a maioria dos hackers é a vontade de explorar detalhadamente as funções dos sistemas e redes de computador com pouco ou nenhum estímulo exterior. Desenvolvedores de software de código aberto geralmente consideram-se hackers e utilizam esta palavra como um termo respeitável.
Tipicamente, os hackers seguem uma espécie de ética hacker, que dita que a missão por conhecimento e informação é essencial, e compartilhar este conhecimento é o dever dos hackers para com a comunidade. Durante esta missão em busca do conhecimento, alguns hackers entretem-se com desafios acadêmicos, como driblar controles de segurança em sistemas de computadores. Por esta razão, a imprensa freqüentemente usa o termo hacker para descrever aqueles que acessam sistemas e redes ilicitamente com intenções inescrupulosas, maldosas ou criminosas. O termo mais correto para este tipo de hacker é cracker — um termo criado por hackers em meados dos anos 80 para diferenciar as duas comunidades.

45.3.1.1. Tonalidades de Cinza

Há diversos grupos distintos de indivíduos que encontram e exploram vulnerabilidades em redes e sistemas. Estes grupos são normalmente descritos de acordo com a tonalidade do chapéu que "vestem" ao realizar suas investigações de segurança, e essa tonalidade indica suas intenções.
O hacker de chapéu branco é aquele que testa redes e sistemas para examinar a performance e a vulnerabilidade à potenciais intrusões. Geralmente, hackers de chapéu branco violam seus próprios sistemas ou sistemas de um cliente que os empregou especificamente para executar uma auditoria de segurança. Pesquisadores acadêmicos e profissionais da área de consultoria de segurança são dois exemplos de hackers de chapéu branco.
Um hacker de chapéu preto é sinônimo de um cracker. Em geral, crackers são menos focados em programação e no aspecto acadêmico de violar sistemas. Eles geralmente contam com programas de quebra de segurança e exploram vulnerabilidades conhecidas em sistemas para descobrir informações importantes para ganho pessoal ou para danificar o sistema ou rede alvos.
O hacker de chapéu cinza, por outro lado, tem as habilidades e intenções de um hacker de chapéu branco na maioria dos casos, mas por vezes utiliza seu conhecimento para propósitos menos nobres. Um hacker de chapéu cinza pode ser descrito como um hacker de chapéu branco que às vezes veste um chapéu preto para atingir seus próprios objetivos.
Hackers de chapéu cinza tipicamente se enquadram em outro tipo de ética, que diz ser aceitável violar sistemas desde que o hacker não cometa roubo ou viole a privacidade. Alguns argumentam, no entanto, que o ato de invadir um sistema por si só já é anti-ético.
Independentemente da intenção do intruso, é importante saber quais as fraquezas que um cracker geralmente tentará explorar. O resto do capítulo concentra-se nestas questões.

45.3.2. Ameaças à Segurança da Rede

Desatenção ao configurar os seguintes aspectos de uma rede podem aumentar os riscos de um ataque.

45.3.2.1. Arquiteturas Inseguras

Uma rede mal configurada é um ponto de entrada básico para usuários não autorizados. Deixar uma rede local baseada na confiança aberta e vulnerável à uma rede altamente insegura como a Internet, é o mesmo que deixar uma porta entreaberta em uma vizinhança perigosa — talvez nada aconteça por um período, mas eventualmente alguém explorará a oportunidade.
45.3.2.1.1. Redes de Transmissão
Administradores de sistemas freqüentemente não percebem a importância do hardware de rede em seus esquemas de segurança. Simples componentes de hardware como concentradores e roteadores baseiam-se no princípio da difusão ou não-comutação, ou seja, sempre que um nó transmitir dados através da rede para um nó receptor, o concentrador ou roteador difunde os pacotes de dados até que o nó receptor os receba e processe. Este método é o mais vulnerável à falsificação (spoofing) de endereços ARP (Address Resolution Protocol - Protocolo de Resolução de Endereço) e MAC (Media Access Control - Controle de Acesso a Mídia), tanto por parte de intrusos externos quanto por parte de usuários não autorizados em hosts locais.
45.3.2.1.2. Servidores Centralizados
Outra potencial armadilha na rede é o uso da computação centralizada. Uma forma comum de corte de gastos em muitas empresas é consolidar todos os serviços em apenas uma máquina potente. Isto pode ser conveniente, pois é mais fácil e bem mais barato gerenciar uma única máquina do que configurações em servidores múltiplos. Entretanto, um servidor centralizado também significa um ponto único de falha na rede. Se o servidor central for comprometido, pode danificar a rede ou inutilizá-la, ou pior ainda, torná-la vulnerável à manipulação ou roubo de dados. Nestas situações, um servidor central torna-se uma porta aberta permitindo acesso à toda a rede.

45.3.3. Ameaças à Segurança do Servidor

A segurança dos servidores é tão importante quanto a segurança da rede porque os servidores freqüentemente armazenam grande parte das informações vitais de uma organização. Se um servidor for comprometido, todo o seu conteúdo pode ficar disponível para o cracker roubar ou manipular como quiser. As seções a seguir detalham algumas das principais questões neste sentido.

45.3.3.1. Serviços Não Utilizados e Portas Abertas

Uma instalação completa do Red Hat Enterprise Linux contém mais de mil pacotes de aplicações e bibliotecas. No entanto, a maioria dos administradores de servidor optam por não instalar todos os pacotes da distribuição; preferindo ao invés disso instalar os pacotes básicos, incluindo diversas aplicações para servidor.
A common occurrence among system administrators is to install the operating system without paying attention to what programs are actually being installed. This can be problematic because unneeded services may be installed, configured with the default settings, and possibly turned on. This can cause unwanted services, such as Telnet, DHCP, or DNS, to run on a server or workstation without the administrator realizing it, which in turn can cause unwanted traffic to the server, or even, a potential pathway into the system for crackers. Refer To Seção 46.2, “Segurança do Servidor” for information on closing ports and disabling unused services.

45.3.3.2. Serviços Desatualizados

A maioria das aplicações de servidor inclusas em uma instalação padrão são sólidas unidades de software testadas exaustivamente. Tendo sido utilizadas em ambientes de produção por muitos anos, seus códigos vem tendo sido constantemente refinados e muitos dos erros (bugs) foram encontrados e consertados.
Entretanto, não existe software perfeito e sempre há espaço para mais aprimoramento. Além disso, programas mais novos freqüentemente não são rigorosamente testados como se espera, porque chegaram recentemente a ambientes de produção ou porque talvez não sejam tão populares quanto outros programas de servidor.
Desenvolvedores e administradores de sistemas freqüentemente encontram erros exploráveis em aplicações de servidor e publicam a informação em sites de rastreamento de erros e relacionados à segurança, como a lista de discussão 'Bugtraq' (http://www.securityfocus.com) ou o site do CERT, 'Computer Emergency Response Team' (http://www.cert.org). Apesar destes mecanismos serem maneiras efetivas de alertar a comunidade sobre vulnerabilidades de segurança, é responsabilidade dos administradores atualizarem seus sistemas prontamente. Isto porque os crackers têm acesso aos mesmos serviços de rastreamento de vulnerabilidades e utilizarão estas informações para violar sistemas desatualizados sempre que puderem. Uma boa administração de sistemas requer vigilância, constante rastreamento de erros, e manutenção apropriada para assegurar um ambiente computacional mais seguro.
Refer to Seção 45.5, “Atualizações de Segurança” for more information about keeping a system up-to-date.

45.3.3.3. Administração Desatenta

Administrators who fail to patch their systems are one of the greatest threats to server security. According to the System Administration Network and Security Institute (SANS), the primary cause of computer security vulnerability is to "assign untrained people to maintain security and provide neither the training nor the time to make it possible to do the job."[13] This applies as much to inexperienced administrators as it does to overconfident or amotivated administrators.
Alguns administradores não atualizam seus servidores e estações de trabalho, enquanto outros não monitoram as mensagens de registro do kernel do sistema ou tráfego de rede. Outro erro comum é deixar senhas ou chaves padrão de serviços inalteradas. Por exemplo, alguns bancos de dados têm senhas de administração padrão porque seus desenvolvedores assumem que o administrador de sistemas irá alterá-las imediatamente após a instalação. Se um administrador de banco de dados deixar de alterar esta senha, até mesmo um cracker inexperiente pode utilizar uma senha padrão conhecida para obter privilégios administrativos ao banco de dados. Estes são apenas alguns dos exemplos de como uma administração desatenta pode levar ao comprometimento de servidores.

45.3.3.4. Serviços Essencialmente Inseguros

Até a empresa mais atenta pode ser vítima de vulnerabilidades se os serviços de rede que elas optarem por usar forem essencialmente inseguros. Por exemplo, há muitos serviços desenvolvidos sob a suposição de que serão utilizados através de redes confiáveis, mas essa suposição deixa de ser verdadeira a partir do momento em que o serviço for disponibilizado através da Internet — que por si só é essencialmente não confiável.
Uma categoria de serviços de rede inseguros e composta por aqueles serviços que requerem nomes de usuário e senha não criptografados para autenticação. Telnet e FTP são dois exemplos deste tipo de serviço. Se um software de farejamento de pacotes está monitorando o tráfego entre o usuário remoto e um destes tipos de serviço, dados como nomes de usuário e senhas podem ser interceptados facilmente.
Tais serviços também podem mais facilmente tornarem-se vítimas do que o setor de segurança chama de ataque man-in-the-middle. Neste tipo de ataque um cracker redireciona o tráfego de rede, levando um servidor de nomes crackeado a apontar para sua máquina ao invés do servidor genuíno. Quando alguém abrir uma sessão remota para este servidor genuíno, a máquina do atacante age como um túnel invisível capturando as informações entre o serviço remoto e o crédulo usuário. Desta maneira um cracker consegue obter senhas administrativas e dados sem que o servidor ou o usuário percebam.
Outra categoria de serviços inseguros são sistemas de arquivos de rede e serviços de informação, como NFS ou NIS, desenvolvidos explicitamente para uso em redes locais mas que, infelizmente, têm seu uso estendido também para redes geograficamente distribuídas (para usuários remotos). O NFS não tem, de acordo com sua configuração padrão, nenhuma autenticação ou quaisquer mecanismos de segurança configurados para prevenir um cracker de montar o modo de compartilhamento e acessar qualquer coisa contida nele. O NIS também tem informações vitais que devem ser conhecidas por cada computador em uma rede, incluindo senhas e permissões de arquivo, em um banco de dados no formato somente-texto ASCII ou DBM (derivado do ASCII). Um cracker que obtém acesso a este banco de dados pode então acessar todas as contas de usuário de uma rede, inclusive a conta do administrador.
By default, Red Hat Enterprise Linux is released with all such services turned off. However, since administrators often find themselves forced to use these services, careful configuration is critical. Refer to Seção 46.2, “Segurança do Servidor” for more information about setting up services in a safe manner.

45.3.4. Ameaças à Segurança de Estações de Trabalho e PCs

Estações de trabalho e PCs podem não ser tão propensos a ataques quanto redes ou servidores, mas já que estes normalmente contém informações delicadas, tais como dados de cartões de crédito, também são alvos de crackers de sistemas. Atacantes também podem tomar posse de de estações de trabalho sem o conhecimento do usuário, e utilizadas como máquinas "escravas" em ataques coordenados. Por estas razões, saber das vulnerabilidades de uma estação de trabalho pode poupar os usuários da dor de cabeça de reinstalar o sistema operacional, ou pior, de terem que se recuperar do roubo de dados.

45.3.4.1. Senhas Inadequadas

Bad passwords are one of the easiest ways for an attacker to gain access to a system. For more on how to avoid common pitfalls when creating a password, refer to Seção 46.1.3, “Segurança da Senha”.

45.3.4.2. Aplicações Cliente Vulneráveis

Embora um administrador possa ter um servidor completamente seguro e atualizado, não significa que usuários remotos estejam seguros ao acessá-lo. Por exemplo, se o servidor oferece os serviços Telnet e FTP através de uma rede pública, um atacante pode capturar os caracteres de nomes de usuário e senhas enquanto estes são movimentados através da rede, e então usar as informações da conta para acessar a estação de trabalho do usuário remoto.
Mesmo ao utilizar protocolos seguros, como o SSH, um usuário remoto pode estar vulnerável a determinados ataques se ele não mantiver suas aplicações cliente atualizadas. Por exemplo, clientes SSH v.1 (versão 1) são vulneráveis a um ataque X-forwarding de servidores SSH maléficos. Uma vez conectado ao servidor, o atacante pode capturar, sem ser percebido, quaisquer teclas pressionadas e cliques de mouse efetuados pelo cliente através da rede. Este problema foi consertado na versão SSH v.2, mas ainda assim depende do usuário monitorar aplicações com tais vulnerabilidades e atualizá-las quando necessário.
Seção 46.1, “Segurança de Estações de Trabalho” discusses in more detail what steps administrators and home users should take to limit the vulnerability of computer workstations.

45.4. Exploits e Ataques Freqüentes

Tabela 45.1, “Exploits Freqüentes” details some of the most common exploits and entry points used by intruders to access organizational network resources. Key to these common exploits are the explanations of how they are performed and how administrators can properly safeguard their network against such attacks.
Tabela 45.1. Exploits Freqüentes
Exploit Descrição Notas
Senhas em Branco ou Padrão Deixar senhas administrativas em branco ou usar a senha padrão provida pelo fabricante. Isto é mais comum em hardware, como roteadores e firewalls, porém alguns dos serviços que rodam no Linux podem conter senhas padrão de administrador (apesar do Red Hat Enterprise Linux 5 não incluí-las).
Freqüentemente associadas com hardware de rede como roteadores, firewalls, VPNs, e equipamentos Network Attached Storage (NAS).
Freqüente em várias versões antigas de sistemas operacionais, especialmente aquelas que agrupam serviços (como UNIX e Windows).
Administradores às vezes criam contas de usuário privilegiadas às pressas e deixam a senha com valor nulo, o que apresenta um perfeito ponto de entrada para usuários maliciosos que venham a descobrir tal conta.
Chaves Compartilhadas Padrão Serviços seguros às vezes incluem chaves de segurança padrão com a finalidade de facilitar o exercício de desenvolvimento ou testes de avaliação. Se estas chaves permanecerem inalteradas e estiverem localizadas em um ambiente de produção na Internet, quaisquer usuários com as mesmas chaves padrão tem acesso àquele recurso de chave compartilhada assim como a quaisquer informações importantes lá contidas.
Mais comum em pontos de acesso de redes sem fio e equipamentos de servidor seguros preconfigurados.
Falsificação (Spoofing) do IP A remote machine acts as a node on your local network, finds vulnerabilities with your servers, and installs a backdoor program or Trojan horse to gain control over your network resources.
Falsificação do IP é um tanto quanto difícil, uma vez que requer que o atacante preveja os números TCP/IP SYN-ACK para coordenar conexões ao sistema alvo, entretanto algumas ferramentas estão disponíveis para assistir crackers em explorar tal vulnerabilidade.
Requer que sistemas alvo rodem serviços (tais como rsh, telnet, FTP e outros) que usem técnicas de autenticação baseadas na fonte, o que não é recomendado quando comparado ao PKI ou outras formas de autenticação criptografada usadas no ssh ou SSL/TLS.
Eavesdropping Coleta não autorizada de dados que trafegam entre dois nós ativos em uma rede através da prática do eavesdropping na conexão entre estes dois nós.
Esta forma de ataque funciona predominantemente com protocolos à base de transmissão de texto sem formatação, como Telnet, FTP e HTTP.
O atacante remoto deve obter acesso a um sistema comprometido em uma LAN de modo a perpetrar tal ataque; normalmente o cracker usou um ataque ativo (como a falsificação do IP ou o man-in-the-middle) para comprometer um sistema na LAN.
Medidas preventivas incluem serviços com troca de chave criptográfica, senhas de uso único, ou autenticação criptografada para prevenir que senhas fiquem vulneráveis à pratica do snooping. O uso de criptografia de alto nível durante a transmissão também é recomendado.
Vulnerabilidades em Serviços Um atacante encontra uma falha ou uma deficiência em um serviço executado através da Internet; através desta vulnerabilidade, o atacante compromete o sistema inteiro e quaisquer dados que este possa conter; e pode possivelmente comprometer outros sistemas na rede.
Serviços baseados no protocolo HTTP, tais como CGI são vulneráveis à execução remota de comandos e até mesmo acesso interativo à linha de comando. Mesmo que o serviço HTTP rode em um modo de usuário não privilegiado, tipo "nobody", informações como arquivos de configuração e mapas de rede podem ser lidos, ou o atacante pode começar um ataque de negação de serviço que esgota recursos do sistema ou torna o mesmo indisponível a outros usuários.
Services sometimes can have vulnerabilities that go unnoticed during development and testing; these vulnerabilities (such as buffer overflows, where attackers crash a service using arbitrary values that fill the memory buffer of an application, giving the attacker an interactive command prompt from which they may execute arbitrary commands) can give complete administrative control to an attacker.
Administradores devem ter certeza de que serviços não sejam executados como usuário root, e devem ficar alertas à atualizações e erratas de provedores ou organizações de segurança tais como CERT e CVE.
Vulnerabilidades em Aplicações Attackers find faults in desktop and workstation applications (such as e-mail clients) and execute arbitrary code, implant Trojan horses for future compromise, or crash systems. Further exploitation can occur if the compromised workstation has administrative privileges on the rest of the network.
Estações de trabalho e computadores pessoais são mais propensos à exploração porque os funcionários não têm a mesma perícia ou experiência para prevenir ou detectar um comprometimento; é essencial informar indivíduos sobre os riscos que correm ao instalar software não autorizado ou abrir arquivos anexos de e-mails não solicitados.
É possível implementar medidas de segurança para garantir que um software cliente de e-mail não abra ou execute anexos automaticamente. Além disso, a atualização automática de software de estações de trabalho através do Red Hat Network ou outros serviços de gerenciamento de sistemas podem aliviar as sobrecargas oriundas de implantações de segurança em ambientes multiusuário.
Ataques de Negação de Serviço (DoS) Um atacante ou grupo de atacantes executam uma ação coordenada contra os recursos de rede ou de servidores de uma organização através do envio de pacotes não autorizados para o host alvo (servidor, roteador, ou estação de trabalho). Isto força o recurso a tornar-se indisponível a usuários legítimos.
O caso de negação de serviço mais relatado nos EUA ocorreu no ano de 2000. Diversos sites comerciais e governamentais de alto tráfego foram tirados do ar por um ataque coordenado de envio em massa de comandos ping usando vários sistemas comprometidos com conexões de largura de banda alta agindo como zombies, ou nós de difusão redirecionados.
Pacotes oriundos da fonte são normalmente adulterados (assim como redifundidos), dificultando uma investigação em busca da verdadeira fonte do ataque.
Avanços em ingress filtering (IETF rfc2267) usando iptables e sistemas de detecção de intrusão (IDSes) de rede como o snort assistem administradores em descobrir e prevenir ataques distribuídos de negação de serviço.

45.5. Atualizações de Segurança

Conforme as vulnerabilidades de segurança são descobertas, o software afetado deve ser atualizado para limitar quaisquer potenciais riscos de segurança. Se o software é parte de um pacote de uma distribuição da Red Hat Enterprise Linux atualmente suportada, a Red Hat, Inc. compromete-se a lançar, assim que possível, pacotes atualizados que consertem as vulnerabilidades. Freqüentemente, comunicados referentes a um exploit de segurança são acompanhados de um conserto (ou código-fonte que conserte o problema). Este conserto é então aplicado ao pacote Red Hat Enterprise Linux, testado pela equipe de controle de qualidade da Red Hat e lançado como uma atualização de errata. Entretanto, se um comunicado não inclui um conserto, um desenvolvedor da Red Hat trabalha junto com o mantedor do software para resolver o problema. Após o problema ser resolvido, o pacote é testado e lançado como uma atualização de errata.
Se for lançada uma atualização de errata para um software utilizado em seu sistema, é altamente recomendável que você atualize os pacotes afetados assim que possível para minimizar o tempo durante o qual o seu sistema fique potencialmente vulnerável.

45.5.1. Atualizando Pacotes

Ao atualizar o software de um sistema, é importante fazer o download da atualização de uma fonte confiável. Um atacante pode facilmente reconstruir um pacote com o mesmo número de versão daquele que deveria resolver o problema, mas com um exploit de segurança diferente no pacote, e depois lançá-lo na Internet. Se isto acontecer, o uso de medidas de segurança como checar os arquivos contra o RPM original não servem para detectar o exploit. Portanto, é muito importante que se use apenas fontes confiáveis, como a Red Hat, para downloads de RPMs, e que se cheque a assinatura do pacote para verificar sua integridade.
A Red Hat oferece duas maneiras de encontrar informações sobre as atualizações de errata:
  1. Listadas e disponíveis para download no Red Hat Network
  2. Listadas mas sem link no site de Erratas da Red Hat

Nota

A partir da linha de produtos Red Hat Enterprise Linux, os pacotes atualizados podem ser baixados somente do Red Hat Network. Embora o site de Erratas da Red Hat contenha informações atualizadas, ele não contém os pacotes para download.

45.5.1.1. Using Automatic Updates with RHN Classic

Warning: Deprecate Feature

Automatic system updates are only available using RHN Classic, which basis subscription consumption on access to content repository channels. RHN Classic is available as a convenience for customer environments with legacy systems which have not updated to Certificate-Based Red Hat Network.
The update and content stream is different for Certificate-Based Red Hat Network, so automatic updates are not used.
The new Certificate-Based Red Hat Network and the differences between Certificate-Based Red Hat Network and RHN Classic are described in Capítulo 14, Product Subscriptions and Entitlements.
RHN Classic allows the majority of the update process to be automated. It determines which RPM packages are necessary for the system, downloads them from a secure repository, verifies the RPM signature to make sure they have not been tampered with, and updates them. The package install can occur immediately or can be scheduled during a certain time period.
RHN Classic requires a system profile for each machine, which contains hardware and software information about the system. This information is kept confidential and is not given to anyone else. It is only used to determine which errata updates are applicable to each system, and, without it, RHN Classic can not determine whether a given system needs updates. When a security errata (or any type of errata) is released, RHN Classic sends an email with a description of the errata as well as a list of systems which are affected. To apply the update, use the Red Hat Update Agent or schedule the package to be updated through the RHN Classic Subscription Management area of the Customer Portal.

Importante

Before installing any security errata, be sure to read any special instructions contained in the errata report and execute them accordingly. Refer to Seção 45.5.1.5, “Aplicando as Alterações” for general instructions about applying the changes made by an errata update.

45.5.1.2. Usando o Site de Erratas da Red Hat

When security errata reports are released, they are published on the Red Hat Errata website available at http://www.redhat.com/security/. From this page, select the product and version for your system, and then select security at the top of the page to display only Red Hat Enterprise Linux Security Advisories. If the synopsis of one of the advisories describes a package used on your system, click on the synopsis for more details.
A página de detalhes descreve o exploit de segurança e quaisquer instruções especiais a serem executadas para atualizar o pacote e consertar a brecha na segurança.
To download the updated package(s), click on the link to login to Red Hat Network, click the package name(s) and save to the hard drive. It is highly recommended that you create a new directory, such as /tmp/updates, and save all the downloaded packages to it.

45.5.1.3. Verificando Pacotes Assinados

Todos os pacotes do Red Hat Enterprise Linux são assinados com a chave GPG da Red Hat, Inc. GPG significa GNU Privacy Guard, ou GnuPG, um pacote de software livre usado para garantir a autenticidade de arquivos distribuídos. Por exemplo, uma chave privada (chave secreta) mantida pela Red Hat chaveia o pacote enquanto a chave pública abre e verifica. Se a chave pública distribuída pela Red Hat não confere com a chave privada durante a verificação do RPM, o pacote pode ter sido alterado e, portanto, não é confiável.
O utilitário RPM do Red Hat Enterprise Linux tenta automaticamente verificar a assinatura GPG de um pacote RPM antes de instalá-lo. Se a chave GPG da Red Hat não estiver instalada, instale-a a partir de uma localidade segura e estática, como o CD-ROM de instalação do Red Hat Enterprise Linux.
Assuming the CD-ROM is mounted in /mnt/cdrom, use the following command to import it into the keyring (a database of trusted keys on the system):
rpm --import /mnt/cdrom/RPM-GPG-KEY-redhat-release
Para exibir uma lista com todas as chaves instaladas para verificação de RPMs, execute o seguinte comando:
rpm -qa gpg-pubkey*
Para a chave da Red Hat, o resultado na tela inclui o seguinte:
gpg-pubkey-37017186-45761324
To display details about a specific key, use the rpm -qi command followed by the output from the previous command, as in this example:
rpm -qi gpg-pubkey-37017186-45761324
É extremamente importante verificar a assinatura dos arquivos RPM antes de instalá-los para ter certeza de que eles não foram alterados depois do lançamento dos pacotes pela Red Hat, Inc. Para verificar todos os pacotes baixados de uma só vez, submeta o seguinte comando:
rpm -K /tmp/updates/*.rpm
For each package, if the GPG key verifies successfully, the command returns gpg OK. If it doesn't, make sure you are using the correct Red Hat public key, as well as verifying the source of the content. Packages that do not pass GPG verifications should not be installed, as they may have been altered by a third party.
Após verificar as chaves GPG e fazer o download de todos os pacotes associados ao relatório da errata, instale os pacotes como root em uma janela de comandos.

45.5.1.4. Instalando Pacotes Assinados

A instalação da maioria dos pacotes pode ser feita com segurança (exceto pacotes do kernel) através do seguinte comando:
rpm -Uvh /tmp/updates/*.rpm
Para pacotes do kernel, use o seguinte comando:
rpm -ivh /tmp/updates/<kernel-package>
No exemplo anterior, substitua <pacote-de-kernel> pelo nome do RPM do kernel.
Após reinicializar a máquina com sucesso usando o novo kernel, o kernel antigo deve ser removido usando o seguinte comando:
rpm -e <old-kernel-package>
No exemplo anterior, substitua <pacote-de-kernel-antigo> pelo nome do RPM do kernel antigo.

Nota

Não é necessário remover o kernel antigo. O gerenciador de inicialização padrão, GRUB, permite que múltiplos kernels sejam instalados e depois escolhidos através de um menu durante a inicialização da máquina.

Importante

Before installing any security errata, be sure to read any special instructions contained in the errata report and execute them accordingly. Refer to Seção 45.5.1.5, “Aplicando as Alterações” for general instructions about applying the changes made by an errata update.

45.5.1.5. Aplicando as Alterações

Após fazer o download e instalar as erratas de segurança através da Red Hat Network ou do site de erratas da Red Hat, é importante parar de usar o software antigo e passar a usar o novo. O modo como isso é feito depende do tipo de software que foi atualizado. A lista a seguir aponta as categorias gerais de software e oferece instruções para usar as versões atualizadas após uma atualização de pacotes.

Nota

Em geral, reinicializar o sistema é a maneira mais certa de garantir que a versão mais recente de um pacote de software seja usada; entretanto, esta opção nem sempre está disponível ao administrador do sistema.
Aplicativos
Aplicativos em espaço de usuário são quaisquer programas que possam ser iniciados por um usuário do sistema. Geralmente, estes aplicativos são usados somente quando um usuário, um script ou um utilitário de tarefas automatizadas os lança, e não persistem por longos períodos.
Após tal aplicação em espaço de usuário ser atualizada, pare todas as instâncias da aplicação no sistema e lance o programa novamente a fim de usar a versão atualizada.
Núcleo
O kernel é o componente central do software do sistema operacional Red Hat Enterprise Linux. Ele gerencia o acesso à memória, ao processador, e a periféricos, e também agenda todas as tarefas.
Devido à sua função central, o kernel não pode ser reiniciado sem também parar o computador. Portanto, uma versão atualizada do kernel não pode ser usada até que o sistema seja reinicializado.
Bibliotecas Compartilhadas
Shared libraries are units of code, such as glibc, which are used by a number of applications and services. Applications utilizing a shared library typically load the shared code when the application is initialized, so any applications using the updated library must be halted and relaunched.
To determine which running applications link against a particular library, use the lsof command as in the following example:
lsof /usr/lib/libwrap.so*
This command returns a list of all the running programs which use TCP wrappers for host access control. Therefore, any program listed must be halted and relaunched if the tcp_wrappers package is updated.
Serviços SysV
SysV services are persistent server programs launched during the boot process. Examples of SysV services include sshd, vsftpd, and xinetd.
Because these programs usually persist in memory as long as the machine is booted, each updated SysV service must be halted and relaunched after the package is upgraded. This can be done using the Services Configuration Tool or by logging into a root shell prompt and issuing the /sbin/service command as in the following example:
service <service-name> restart
In the previous example, replace <service-name> with the name of the service, such as sshd.
Refer to Capítulo 16, Configuração de Rede for more information on the Services Configuration Tool.
xinetd Services
Services controlled by the xinetd super service only run when a there is an active connection. Examples of services controlled by xinetd include Telnet, IMAP, and POP3.
Because new instances of these services are launched by xinetd each time a new request is received, connections that occur after an upgrade are handled by the updated software. However, if there are active connections at the time the xinetd controlled service is upgraded, they are serviced by the older version of the software.
To kill off older instances of a particular xinetd controlled service, upgrade the package for the service then halt all processes currently running. To determine if the process is running, use the ps command and then use the kill or killall command to halt current instances of the service.
For example, if security errata imap packages are released, upgrade the packages, then type the following command as root into a shell prompt:
ps -aux | grep imap
Este comando retorna todas as sessões IMAP ativas. Sessões individuais podem então ser terminadas com o seguinte comando:
kill <PID>
Se este comando falhar em terminar a sessão, use o seguinte comando em seu lugar:
kill -9 <PID>
In the previous examples, replace <PID> with the process identification number (found in the second column of the ps command) for an IMAP session.
Para terminar todas as sessões IMAP ativas, submeta o seguinte comando:
killall imapd

Capítulo 46. Assegurando sua Rede de Trabalho

46.1. Segurança de Estações de Trabalho
46.1.1. Avaliando a Segurança de Estações de Trabalho
46.1.2. Segurança do BIOS e do Carregador de Inicialização
46.1.3. Segurança da Senha
46.1.4. Controles Administrativos
46.1.5. Serviços de Rede Disponíveis
46.1.6. Firewalls Pessoais
46.1.7. Ferramentas de Comunicação com Segurança Aprimorada
46.2. Segurança do Servidor
46.2.1. Protegendo Serviços com TCP Wrappers e xinetd
46.2.2. Protegendo o Portmap
46.2.3. Protegendo o NIS
46.2.4. Protegendo o NFS
46.2.5. Protegendo o Servidor HTTP Apache
46.2.6. Protegendo o FTP
46.2.7. Protegendo o Sendmail
46.2.8. Verificando Quais Portas estão Escutando
46.3. Single Sign-on (SSO)
46.3.1. Introdução
46.3.2. Iniciando seu Cartão Inteligente
46.3.3. Como Funciona o Registro do Cartão Inteligente
46.3.4. Como Funciona a Autenticação do Cartão Inteligente
46.3.5. Configurando o Firefox para usar o Kerberos para SSO.
46.4. Módulos de Autenticação Plugáveis (Pluggable Authentication Modules - PAM)
46.4.1. Vantagens do PAM
46.4.2. Arquivos de Configuração do PAM
46.4.3. Formato do Arquivo de Configuração do PAM
46.4.4. Exemplos de Arquivos de Configuração do PAM
46.4.5. Criando Módulos PAM
46.4.6. O PAM e o Caching de Credenciais Administrativas
46.4.7. O PAM e a Propriedade de Dispositivos
46.4.8. Recursos Adicionais
46.5. TCP Wrappers e xinetd
46.5.1. TCP Wrappers
46.5.2. Arquivos de Configuração do TCP Wrappers
46.5.3. xinetd
46.5.4. Arquivos de Configuração do xinetd
46.5.5. Recursos Adicionais
46.6. Kerberos
46.6.1. O que é o Kerberos?
46.6.2. Terminologia do Kerberos
46.6.3. Como o Kerberos Funciona
46.6.4. Kerberos e PAM
46.6.5. Configurando o Servidor Kerberos 5
46.6.6. Configurando um Cliente Kerberos 5
46.6.7. Mapeamento Domínio-para-território
46.6.8. Configurando KDCs Secundários
46.6.9. Configurando a Autenticação Cross-Realm - (Cross Realm Authentication)
46.6.10. Recursos Adicionais
46.7. Redes Privadas Virtuais (Virtual Private Networks - VPNs)
46.7.1. Como um VPN Funciona?
46.7.2. VPNs e o Red Hat Enterprise Linux
46.7.3. IPsec
46.7.4. Criando uma Conexão IPsec
46.7.5. Instalação do IPsec
46.7.6. Configuração Host-a-Host do IPsec
46.7.7. Configuração Rede-a-Rede do IPsec
46.7.8. Iniciando e Parando uma Conexão IPsecConnection
46.8. Firewalls
46.8.1. Netfilter 6
46.8.2. Configurações Básicas de Firewall
46.8.3. Usando IPTables
46.8.4. Filtros de IPTables Comuns
46.8.5. Regras FORWARD e NAT
46.8.6. Software Malicioso e Endereços IP Falsificados (spoofed)
46.8.7. IPTables e Rastreamento de Conexão
46.8.8. IPv6
46.8.9. Recursos Adicionais
46.9. IPTables
46.9.1. Filtragem de Pacotes
46.9.2. Diferenças entre IPTables e IPChains
46.9.3. Opções de Comando para o IPTables
46.9.4. Salvando Regras do IPTables
46.9.5. Scripts de Controle do IPTables
46.9.6. IPTables e IPv6
46.9.7. Recursos Adicionais

46.1. Segurança de Estações de Trabalho

A segurança de um ambiente Linux começa pela estação de trabalho. Na proteção de sua máquina pessoal ou sistema corporativo, uma boa política de segurança começa pelo computador individual. Afinal de contas, uma rede de computadores é tão segura quanto seu nó mais vulnerável.

46.1.1. Avaliando a Segurança de Estações de Trabalho

Ao avaliar a segurança de uma estação de trabalho do Red Hat Enterprise Linux, considere os seguintes fatores:
  • Segurança do BIOS e do Carregador de Inicialização — Um usuário não autorizado pode acessar fisicamente a máquina e inicializá-la como um usuário simples ou no modo de recuperação sem uma senha?
  • Segurança de Senhas — Até que ponto as senhas de conta de usuário na máquina estão seguras?
  • Controles Administrativos — Quem possui uma conta no sistema e qual o controle administrativo que estas contas possuem?
  • Serviços de Rede Disponíveis — Quais os serviços disponíveis para solicitações advindas da rede? Eles deveriam mesmo estar ativos?
  • Firewalls Pessoais — Caso seja necessário, que tipo de firewall devo escolher?
  • Ferramentas de Comunicação com Segurança Aprimorada — Quais ferramentas devem ser utilizadas para a comunicação entre estações de trabalho e quais devem ser evitadas?

46.1.2. Segurança do BIOS e do Carregador de Inicialização

A proteção de senhas para o BIOS (ou componente equivalente) e para o carregador de inicialização, pode evitar que usuários não autorizados, sem acesso físico a sistemas, inicializem a máquina com mídia removível ou obtenham privilégios root através do modo de usuário simples. As medidas de segurança a serem tomadas para proteger o sistema contra ataques deste tipo, dependem da confidencialidade das informações que a estação de trabalho armazena e da localização da mesma.
Por exemplo, se uma máquina é usada numa exposição ou feira e não contém informações confidenciais, talvez não seja crucial prevenir tais ataques. Entretanto, caso durante essa mesma feira, um funcionário descuidar de um laptop que contenha chaves SSH privadas não criptografadas da rede corporativa, poderá ocorrer uma trágica violação de segurança com conseqüências para a empresa inteira.
Por outro lado, se a estação de trabalho estiver localizada em um lugar onde somente pessoas confiáveis e autorizadas possuem acesso, então proteger o BIOS ou o carregador de inicialização pode não ser necessário.

46.1.2.1. Senhas do BIOS

As duas razões principais para proteger o BIOS de um computador através do uso de uma senha são [14]:
  1. Impedir Alterações na Configuração do BIOS — Se um intruso tem acesso ao BIOS, o mesmo pode configurá-lo para ser iniciado por um disquete ou CD-ROM. Isto possibilita que ele entre no modo de recuperação ou de usuário simples, o que por sua vez permite que ele inicie programas arbitrariamente no sistema ou copie informações confidenciais.
  2. Impedir a Inicialização do Sistema — Alguns BIOS permitem que você proteja o processo de inicialização da máquina com uma senha. Quando ativado, um atacante é forçado a inserir uma senha antes do BIOS executar o carregador de inicialização.
Como os métodos para definir uma senha para o BIOS variam de acordo com o fabricante do computador, consulte o manual do seu computador para obter instruções específicas.
Se você esquecer a senha do BIOS, ela pode ser restaurada com jumpers na placa-mãe ou desligando a bateria do CMOS. Por esta razão, é aconselhável prevenir (por exemplo, chavear) o acesso aos componentes internos do computador, se possível. Entretanto, consulte o manual do computador ou da placa-mãe antes de tentar desligar a bateria do CMOS.
46.1.2.1.1. Segurança de Plataformas Não-x86
Outras arquiteturas usam programas diferentes para executar tarefas de nível baixo, mais ou menos equivalentes àquelas do BIOS em sistemas x86. Por exemplo, computadores baseados na Intel® Itanium™ usam o shell EFI (Interface de Firmware Extensivo).
Para instruções sobre a senha para a proteção de programas como BIOS em outras arquiteturas, consulte as instruções do fabricante.

46.1.2.2. Senhas do Carregador de Inicialização

Veja a seguir as principais razões para proteger um carregador de inicialização Linux com senha:
  1. Impedir Acesso ao Modo de Usuário Simples — Se os atacantes puderem inicializar o sistema no modo de usuário simples, eles serão autenticados automaticamente como o usuário root sem que precisem digitar a senha root.
  2. Impedir Acesso ao Console do GRUB — Se uma máquina utilizar o GRUB como um carregador de inicialização, um atacante poderá usar a interface do editor para mudanças de configuração ou para obter informações através do comando cat.
  3. Impedir Acesso à Sistemas Operacionais Não-Seguros — Em sistemas de inicialização dupla, um atacante pode selecionar um sistema operacional na hora da inicialização (como o DOS, por exemplo), que ignora controles de acesso e permissões de arquivo.
O Red Hat Enterprise Linux para a plataforma x86 vem com o carregador de inicialização GRUB. Para informações detalhadas sobre o GRUB, consulte o Guia de Instalação Red Hat.
46.1.2.2.1. Senha para Proteção do GRUB
You can configure GRUB to address the first two issues listed in Seção 46.1.2.2, “Senhas do Carregador de Inicialização” by adding a password directive to its configuration file. To do this, first choose a strong password, open a shell, log in as root, and then type the following command:
grub-md5-crypt
Quando solicitado, digite a senha do GRUB e pressione Enter. Isto retornará um hash MD5 da senha.
Em seguida, edite o arquivo de configuração do GRUB /boot/grub/grub.conf. Abra o arquivo e, abaixo da linha de comando timeout na seção principal do documento, adicione a seguinte linha:
password --md5 <hash-da-senha>
Substitua <hash-da-senha> pelo valor retornado do /sbin/grub-md5-crypt[15].
De agora em diante, durante a inicialização do sistema, o menu do GRUB não permitirá acesso ao editor ou à interface de comandos sem que primeiro a tecla p seja pressionada, seguida da senha do GRUB.
Infelizmente, esta solução não impede que um atacante inicialize um sistema operacional não seguro em um ambiente de inicialização dupla. Para lidar com este cenário, outra parte do arquivo /boot/grub/grub.conf deve ser editada.
Procure a linha title do sistema operacional ao qual você deseja adicionar segurança, e adicione abaixo desta uma linha contendo a diretiva lock.
Para um sistema DOS, a estrofe deve começar da seguinte forma:
title DOS lock

Atenção

Para que este método funcione adequadamente, uma linha password deve constar na seção principal do arquivo /boot/grub/grub.conf. Do contrário, um atacante poderá acessar a interface de edição do GRUB e remover a linha lock.
Para criar uma senha diferente para um kernel ou sistema operacional específico, adicione uma linha lock na estrofe, seguida de uma linha para a senha.
Cada estrofe que você proteger com uma senha única deve começar com linhas similares ao exemplo seguinte:
title DOS lock password --md5 <password-hash>

46.1.3. Segurança da Senha

O uso de senhas é o método principal utilizado pelo Red Hat Enterprise Linux para verificar a identidade de um usuário. Por isto, a segurança de senhas é tão importante para a proteção do usuário, da estação de trabalho, e da rede.
Por motivos de segurança, o programa de instalação configura o sistema para usar o Algoritmo Message-Digest (MD5) e senhas shadow. É altamente recomendável que você não altere estas configurações.
Se durante a instalação, as senhas MD5 forem desativadas, será usado o formato Data Encryption Standard (DES). Este formato limita as senhas em até oito caracteres alfanuméricos (não permitindo caracteres especiais como pontuação e outros), e oferece um nível de criptografia modesto, de 56 bits.
If shadow passwords are deselected during installation, all passwords are stored as a one-way hash in the world-readable /etc/passwd file, which makes the system vulnerable to offline password cracking attacks. If an intruder can gain access to the machine as a regular user, they can copy the /etc/passwd file to their own machine and run any number of password cracking programs against it. If there is an insecure password in the file, it is only a matter of time before the password cracker discovers it.
Senhas shadow eliminam a ameaça deste tipo de ataque, armazenando as senhas em um arquivo /etc/shadow, legível somente pelo usuário root.
This forces a potential attacker to attempt password cracking remotely by logging into a network service on the machine, such as SSH or FTP. This sort of brute-force attack is much slower and leaves an obvious trail as hundreds of failed login attempts are written to system files. Of course, if the cracker starts an attack in the middle of the night on a system with weak passwords, the cracker may have gained access before dawn and edited the log files to cover their tracks.
In addition to format and storage considerations is the issue of content. The single most important thing a user can do to protect their account against a password cracking attack is create a strong password.

46.1.3.1. Criando Senhas Robustas

Ao criar uma senha robusta, é uma boa idéia seguir estas instruções:
  • Não Use Apenas Palavras ou Números — Nunca use somente palavras ou números em uma senha.
    Alguns exemplos de senhas inseguras:
    • 8675309
    • juan
    • hackme
  • Não Use Palavras Reconhecíveis — Palavras como nomes próprios, palavras de dicionário ou até termos de programas de televisão ou novelas devem ser evitados, mesmo que sejam finalizados com números.
    Alguns exemplos de senhas inseguras:
    • john1
    • DS-9
    • mentat123
  • Não Use Palavras em Idiomas Estrangeiros — Programas de quebra de senhas freqüentemente checam listas de palavras que incluem dicionários de muitos idiomas. Confiar em idiomas estrangeiros para proteger senhas não é seguro.
    Alguns exemplos de senhas inseguras:
    • cheguevara
    • bienvenido1
    • 1dumbKopf
  • Não Use Terminologia de Hacker — Se você se acha parte de uma elite por utilizar terminologia de hacker — também chamada de linguajar l337 (LEET) — em sua senha, repense. Muitas listas de palavras incluem palavras do linguajar LEET.
    Alguns exemplos de senhas inseguras:
    • H4X0R
    • 1337
  • Não Use Informações Pessoais — Não use informações pessoais em suas senhas. Se o atacante souber quem você é, ele terá mais facilidade em descobrir sua senha. A seguir, veja uma lista de tipos de informação a evitar na criação de uma senha:
    Alguns exemplos de senhas inseguras:
    • Seu nome
    • Nomes de animais de estimação
    • Nomes de familiares
    • Quaisquer datas de aniversário
    • Seu número de telefone ou código postal
  • Não Inverta Palavras Reconhecíveis — Bons verificadores de senha sempre revertem palavras comuns, portanto reverter uma senha ruim não a torna mais segura.
    Alguns exemplos de senhas inseguras:
    • R0X4H
    • nauj
    • 9-DS
  • Não Anote Sua Senha — Nunca guarde uma senha em papel. É bem mais seguro memorizá-la.
  • Não Use a Mesma Senha Para Todas as Máquinas — É importante criar senhas separadas para cada máquina. Desta maneira, se um sistema for comprometido, todas as outras máquinas não estarão em risco imediato.
As seguintes diretrizes lhe ajudarão a criar uma senha robusta:
  • Crie uma Senha de no Mínimo Oito Caracteres — Quanto mais longa a senha, melhor. Se você estiver usando senhas MD5, as mesmas devem ter 15 ou mais caracteres. Para senhas DES, use o tamanho máximo (oito caracteres).
  • Misture Letras Maiúsculas e Minúsculas — O Red Hat Enterprise Linuxdiferencia entre maiúsculas e minúsculas, portanto misture-as para criar uma senha mais robusta.
  • Misture Letras e Números — Adicionar números a senhas, especialmente no meio delas (não apenas no começo e fim), pode aumentar a robustez da senha.
  • Inclua Caracteres Não Alfa-numéricos — Caracteres especiais como &, $, e > podem aumentar bastante a robustez de uma senha (isto não é possível se senhas DES forem usadas).
  • Escolha uma Senha que Você Possa Lembrar — A melhor senha do mundo de nada adianta se você não conseguir lembrá-la. Então, use acrônimos ou outros dispositivos mnemônicos para ajudá-lo a memorizar senhas.
Com todas estas regras, parece difícil criar uma senha que siga todos os critérios e evitar as características de uma senha ruim. Felizmente, existem alguns passos simples que podem ser seguidos para gerar uma senha fácil de lembrar e segura.
46.1.3.1.1. Metodologia de Criação de Senhas Seguras
Há muitos métodos usados para criar senhas seguras. Um dos mais conhecidos envolve acrônimos. Por exemplo:
  • Pense em uma frase que seja fácil de lembrar, como:
    "e o sol da liberdade em raios fúlgidos, brilhou no céu da pátria neste instante."
  • Em seguida, transforme-a num acrônimo (incluindo a pontuação).
    otrattw,tghwg.
  • Adicione complexidade substituindo letras por números e símbolos no acrônimo. Por exemplo: substitua n por 9 e a letra d pelo símbolo arroba (@):
    o7r@77w,7ghwg.
  • Adicione mais complexidade colocando pelo menos uma das letras em maiúscula, como F.
    o7r@77w,7gHwg.
  • Finalmente, nunca use o exemplo acima em um de seus sistemas.
Criar senhas seguras é imperativo, mas gerenciá-las apropriadamente também é importante, especialmente para administradores de sistemas em grandes organizações. A próxima seção detalha boas práticas para criar e gerenciar senhas de usuários em uma organização.

46.1.3.2. Criando Senhas de Usuários Dentro de uma Empresa

Se houver um número significativo de usuários em uma organização, os administradores de sistemas têm duas opções básicas para forçar o uso de boas senhas. Eles podem criar senhas para os usuários, ou podem deixar que os usuários criem suas próprias senhas, enquanto verificam se as senhas têm qualidade aceitável.
Criar senhas para os usuários garante que as senhas sejam boas, mas torna-se uma tarefa complicada conforme a empresa cresce. Também aumenta o risco dos usuários anotarem suas senhas.
Por estas razões, a maioria dos administradores de sistema prefere que os usuários criem suas próprias senhas, mas ativamente verificam se as senhas são boas e, em alguns casos, forçam os usuários a trocarem suas senhas periodicamente conforme as senhas vão envelhecendo.
46.1.3.2.1. Forçando Senhas Robustas
To protect the network from intrusion it is a good idea for system administrators to verify that the passwords used within an organization are strong ones. When users are asked to create or change passwords, they can use the command line application passwd, which is Pluggable Authentication Manager (PAM) aware and therefore checks to see if the password is too short or otherwise easy to crack. This check is performed using the pam_cracklib.so PAM module. Since PAM is customizable, it is possible to add more password integrity checkers, such as pam_passwdqc (available from http://www.openwall.com/passwdqc/) or to write a new module. For a list of available PAM modules, refer to http://www.kernel.org/pub/linux/libs/pam/modules.html. For more information about PAM, refer to Seção 46.4, “Módulos de Autenticação Plugáveis (Pluggable Authentication Modules - PAM)”.
A verificação de senhas executada durante sua criação não descobre senhas fracas tão efetivamente quanto a verificação através da execução de um programa de quebra de senhas contra as mesmas.
Há muitos programas de quebra de senhas que rodam no Red Hat Enterprise Linux, embora nenhum seja distribuído junto com o sistema operacional. Abaixo há uma breve lista de alguns dos programas de cracking de senhas mais conhecidos:

Nota

Nenhuma destas ferramentas é fornecida com o Red Hat Enterprise Linux, e portanto não são suportadas pela Red Hat, Inc. de maneira nenhuma.
  • John The Ripper — Um programa de quebra de senhas rápido e flexível. Permite o uso de listas de palavras múltiplas e é capaz de quebrar senhas usando força bruta. Está disponível online em http://www.openwall.com/john/.
  • Crack — Perhaps the most well known password cracking software, Crack is also very fast, though not as easy to use as John The Ripper. It can be found online at http://www.openwall.com/john/.
  • Slurpie — O Slurpie é similar ao John The Ripper e ao Crack, mas foi criado para rodar em vários computadores simultaneamente, criando um ataque de quebra de senhas distribuído. Pode ser encontrado online, juntamente à outras ferramentas de avaliação de segurança contra ataques distribuídos, em http://www.ussrback.com/distributed.htm.

Atenção

Sempre obtenha autorizações por escrito antes de tentar quebrar senhas dentro de uma empresa.
46.1.3.2.2. Vencimento de Senhas
Password aging is another technique used by system administrators to defend against bad passwords within an organization. Password aging means that after a specified period (usually 90 days), the user is prompted to create a new password. The theory behind this is that if a user is forced to change their password periodically, a cracked password is only useful to an intruder for a limited amount of time. The downside to password aging, however, is that users are more likely to write their passwords down.
Existem dois programas principais usados para efetivar o uso do vencimento de senhas no Red Hat Enterprise Linux: o comando chage ou o aplicativo gráfico Gerenciador de Usuários (system-config-users).
A opção -M do comando chage especifica a validade máxima de uma senha (em número de dias). Por exemplo, para fazer com que a senha de um usuário vença em 90 dias, use o seguinte comando:
chage -M 90 <nome-de-usuário>
No comando acima, substitua <nome-de-usuário> pelo nome de usuário correspondente. Para fazer com que a senha nunca vença, é comum usar o valor 99999 após a opção -M (isto equivale a um pouco mais do que 273 anos).
Você também pode usar o comando chage em modo interativo para modificar o vencimento e detalhes de várias senhas ao mesmo tempo. Use o seguinte comando para entrar em modo interativo:
chage <nome-de-usuário>
O trecho a seguir é um exemplo de uma sessão interativa usando este comando:
~]# chage davido
Changing the aging information for davido
Enter the new value, or press ENTER for the default

        Minimum Password Age [0]: 10
        Maximum Password Age [99999]: 90
        Last Password Change (YYYY-MM-DD) [2006-08-18]:
        Password Expiration Warning [7]:
        Password Inactive [-1]:
        Account Expiration Date (YYYY-MM-DD) [1969-12-31]:
~]#
Consulte a página man do chage para maiores informações sobre as opções disponíveis.
Você também pode usar o gráfico do aplicativo Gerente de Usuário para criar uma política de vencimento de senha, como se segue. Note: você precisará dos privilégios do Administrador para aplicar este procedimento.
  1. Clique no menu Sistema no Painel, escolha Administração e clique em Usuários e Grupos para mostrar o Gerente de Usuário. Como outra alternativa, digite o comando system-config-users na janela de comandos.
  2. Clique na aba Usuários, e selecione o usuário requerido na lista de usuários.
  3. Clique em Propriedades na barra de ferramentas para mostrar a caixa de diálogo das Propriedades do Usuário ( ou escolha Propriedades no menu Arquivo).
  4. Em seguida, clique na aba Informações de Senhas e insira o número de dias antes da senha vencer, conforme mostra a Figura 46.1, “Especificando as opções de vencimento da senha”.
  5. Insira o valor solicitado no campo Dias antes da solicitação de mudança e clique em OK.
Especificando as opções de vencimento da senha
Ilustração da aba Informações de Senhas.
Figura 46.1. Especificando as opções de vencimento da senha

For more information about user and group configuration (including instructions on forcing first time passwords), refer to Capítulo 35, Usuários e Grupos.

46.1.4. Controles Administrativos

Durante a administração de máquinas de uso pessoal, o usuário precisa executar certas tarefas como usuário root, ou após obter privilégios pertinentes ao usuário root através de um programa setuid como o sudo ou o su. Um programa setuid roda com o ID (UID) do proprietário do programa, ao invés de usar o ID do usuário executando o programa. Tais programas são identificados por um s na seção do proprietário em uma listagem, como no exemplo seguinte:
-rwsr-xr-x    1 root     root        47324 May  1 08:09 /bin/su

Nota

O s pode ser maiúsculo ou minúsculo. Se for maiúsculo, significa que o bit de permissão adjacente não foi definido.
For the system administrators of an organization, however, choices must be made as to how much administrative access users within the organization should have to their machine. Through a PAM module called pam_console.so, some activities normally reserved only for the root user, such as rebooting and mounting removable media are allowed for the first user that logs in at the physical console (refer to Seção 46.4, “Módulos de Autenticação Plugáveis (Pluggable Authentication Modules - PAM)” for more information about the pam_console.so module.) However, other important system administration tasks, such as altering network settings, configuring a new mouse, or mounting network devices, are not possible without administrative privileges. As a result, system administrators must decide how much access the users on their network should receive.

46.1.4.1. Permitindo Acesso Root

Se os usuários de uma organização são de confiança e bem treinados em relação ao uso de computadores, permitir que eles gozem de acesso root talvez não seja uma preocupação. Permitir que usuários tenham acesso root significa que atividades corriqueiras, como a adição de dispositivos ou configuração de interfaces de rede, sejam administradas por cada usuário, deixando administradores de sistemas livres para lidar com a segurança de rede e outras questões importantes.
Por outro lado, a permissão de acesso root à usuários individuais pode levantar as seguintes questões:
  • Má Configuração da Máquina — Usuários com acesso root podem configurar suas máquinas incorretamente e precisar de assistência para resolver problemas, ou pior, abrir buracos na segurança sem saber.
  • Execução de Serviços Inseguros — Usuários com acesso root podem rodar serviços inseguros, como FTP ou Telnet, em suas máquinas, potencialmente colocando em risco nomes de usuários e senhas. Estes serviços transmitem informação através da rede usando modo texto sem formatação.
  • Execução de Anexos de E-mails como Root — Apesar de raros, existem vírus de e-mail que afetam o Linux. A única hora em que eles representam uma ameaça, no entanto, é quando são executados pelo usuário root.

46.1.4.2. Impedindo Acesso Root

If an administrator is uncomfortable allowing users to log in as root for these or other reasons, the root password should be kept secret, and access to runlevel one or single user mode should be disallowed through boot loader password protection (refer to Seção 46.1.2.2, “Senhas do Carregador de Inicialização” for more information on this topic.)
The following are four different ways that an administrator can further ensure that root logins are disallowed:
Changing the root shell
To prevent users from logging in directly as root, the system administrator can set the root account's shell to /sbin/nologin in the /etc/passwd file.
Tabela 46.1. Desativando o Shell do Root
Efeitos Não Afeta
Prevents access to the root shell and logs any such attempts. The following programs are prevented from accessing the root account:
  • login
  • gdm
  • kdm
  • xdm
  • su
  • ssh
  • scp
  • sftp
Programs that do not require a shell, such as FTP clients, mail clients, and many setuid programs. The following programs are not prevented from accessing the root account:
  • sudo
  • FTP clients
  • Email clients

Disabling root access via any console device (tty)
To further limit access to the root account, administrators can disable root logins at the console by editing the /etc/securetty file. This file lists all devices the root user is allowed to log into. If the file does not exist at all, the root user can log in through any communication device on the system, whether via the console or a raw network interface. This is dangerous, because a user can log in to their machine as root via Telnet, which transmits the password in plain text over the network.
By default, Red Hat Enterprise Linux's /etc/securetty file only allows the root user to log in at the console physically attached to the machine. To prevent the root user from logging in, remove the contents of this file by typing the following command at a shell prompt as root:
echo > /etc/securetty
To enable securetty support in the KDM, GDM, and XDM login managers, add the following line:
auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so
to the files listed below:
  • /etc/pam.d/gdm
  • /etc/pam.d/gdm-autologin
  • /etc/pam.d/gdm-fingerprint
  • /etc/pam.d/gdm-password
  • /etc/pam.d/gdm-smartcard
  • /etc/pam.d/kdm
  • /etc/pam.d/kdm-np
  • /etc/pam.d/xdm

Atenção

Um arquivo /etc/securetty em branco não impede que o usuário root autentique-se remotamente usando o conjunto de ferramentas OpenSSH porque o console só é aberto após a autenticação.
Tabela 46.2. Desabilitando Autenticações Root
Efeitos Não Afeta
Impede acesso à conta do root através do console ou rede. Os seguintes programas não tem acesso à conta do root:
  • login
  • gdm
  • kdm
  • xdm
  • Other network services that open a tty
Programs that do not log in as root, but perform administrative tasks through setuid or other mechanisms. The following programs are not prevented from accessing the root account:
  • su
  • sudo
  • ssh
  • scp
  • sftp

Disabling root SSH logins
To prevent root logins via the SSH protocol, edit the SSH daemon's configuration file, /etc/ssh/sshd_config, and change the line that reads:
#PermitRootLogin yes
para o seguinte:
PermitRootLogin no
Tabela 46.3. Desabilitando Autenticações do Root Através do SSH
Efeitos Não Afeta
Impede o acesso root através do conjunto de ferramentas Open SSH. Os seguintes programas não tem acesso à conta do root:
  • ssh
  • scp
  • sftp
Programs that are not part of the OpenSSH suite of tools.

Using PAM to limit root access to services
PAM, through the /lib/security/pam_listfile.so module, allows great flexibility in denying specific accounts. The administrator can use this module to reference a list of users who are not allowed to log in. To limit root access to a system service, edit the file for the target service in the /etc/pam.d/ directory and make sure the pam_listfile.so module is required for authentication.
The following is an example of how the module is used for the vsftpd FTP server in the /etc/pam.d/vsftpd PAM configuration file (the \ character at the end of the first line is not necessary if the directive is on a single line):
auth   required   /lib/security/pam_listfile.so   item=user \
 sense=deny file=/etc/vsftpd.ftpusers onerr=succeed
Isto diz ao PAM para consultar o arquivo /etc/vsftpd.ftpusers e recusar a qualquer usuário lá listado o acesso ao serviço. O administrador pode alterar o nome deste arquivo e pode manter listas separadas para cada serviço ou usar uma lista central para recusar o acesso a múltiplos serviços.
Se o administrador quiser recusar o acesso a múltiplos serviços, pode-se adicionar uma linha similar aos arquivos de configuração do PAM, como /etc/pam.d/pop e /etc/pam.d/imap para clientes de e-mail ou /etc/pam.d/ssh para clientes SSH.
Tabela 46.4. Desabilitando o Acesso do Root ao PAM
Efeitos Não Afeta
Prevents root access to network services that are PAM aware. The following services are prevented from accessing the root account:
  • login
  • gdm
  • kdm
  • xdm
  • ssh
  • scp
  • sftp
  • FTP clients
  • Email clients
  • Any PAM aware services
Programas e serviços que não ofereçam integração com o PAM.

46.1.4.3. Limitando o Acesso Root

Ao invés de recusar completamente o acesso ao usuário root, o administrador pode permitir o acesso apenas através de programas setuid, como o su ou o sudo.
46.1.4.3.1. O Comando su
Quando um usuário executa o comando su, o mesmo precisa entrar com a senha root e, após a autenticação, recebe uma solicitação de janela da root.
Uma vez autenticado através do comando su, o usuário é o usuário root e tem acesso administrativo total ao sistema[16]. Além disso, ao se tornar um usuário root, é possível que ele use o comando su para assumir a identidade de qualquer outro usuário no sistema sem precisar entrar com a respectiva senha.
Como este programa é tão poderoso, administradores dentro de uma empresa talvez queiram limitar quem pode acessá-lo.
Uma das maneiras mais simples de fazer isso é adicionar usuários ao grupo administrativo especial chamado wheel. Para fazer isso, digite o seguinte comando como root:
usermod -G wheel <nome-de-usuário>
No comando anterior, substitua <nome-de-usuário> pelo nome do usuário sendo adicionado ao grupo wheel.
Você também pode usar o Gerente de Usuário para modificar os membros do grupo, como se segue. Note: você precisará dos privilégios do Administrador para aplicar este procedimento.
  1. Clique no menu Sistema no Painel, escolha Administração e clique em Usuários e Grupos para mostrar o Gerente de Usuário. Como outra alternativa, digite o comando system-config-users na janela de comandos.
  2. Clique na aba Usuários, e selecione o usuário requerido na lista de usuários.
  3. Clique em Propriedades na barra de ferramentas para mostrar a caixa de diálogo das Propriedades do Usuário ( ou escolha Propriedades no menu Arquivo).
  4. Click the Groups tab, select the check box for the wheel group, and then click OK. Refer to Figura 46.2, “Adicionando usuários ao grupo "wheel".”.
  5. Em seguida, abra o arquivo de configuração do PAM para o su (/etc/pam.d/su) em um editor de texto e remova o comentário # da seguinte linha:
    auth  required /lib/security/$ISA/pam_wheel.so use_uid
    Isso permitirá que somente membros do grupo administrativo wheel usem o programa.
Adicionando usuários ao grupo "wheel".
Ilustração da seção Grupos
Figura 46.2. Adicionando usuários ao grupo "wheel".

Nota

O usuário root é parte do grupo wheel de acordo com a configuração padrão.
46.1.4.3.2. O Comando sudo
O comando sudo oferece outra abordagem para permitir que usuários tenham acesso administrativo. Quando um usuário confiável precede um comando administrativo com sudo, o sistema pede que o usuário entre a sua própria senha. Então, após a autenticação, e assumindo que seja permitido, o comando administrativo é executado como se o usuário fosse o root.
O formato básico do comando sudo é o seguinte:
sudo <comando>
No exemplo acima, <comando> seria substituído por um comando normalmente reservado apenas ao usuário root, como, por exemplo, mount.

Importante

Usuários do comando sudo devem tomar cuidado extra para fazer o logout antes de deixarem suas máquinas, já que é possível usar o comando novamente sem precisar indicar a senha, por um período de cinco minutos. Esta configuração pode ser alterada através do arquivo de configuração /etc/sudoers.
The sudo command allows for a high degree of flexibility. For instance, only users listed in the /etc/sudoers configuration file are allowed to use the sudo command and the command is executed in the user's shell, not a root shell. This means the root shell can be completely disabled, as shown in Seção 46.1.4.2, “Impedindo Acesso Root”.
O comando sudo também oferece um registro detalhado da seqüência de eventos. Cada autenticação bem-sucedida é registrada no arquivo /var/log/messages e os comandos submetidos são registrados com o nome do usuário no arquivo /var/log/secure.
Outra vantagem do comando sudo é que um administrador pode permitir que usuários acessem diferentes comandos específicos de acordo com suas necessidades.
Administradores que queiram editar o arquivo de configuração do sudo, o /etc/sudoers, devem usar o comando visudo.
Para que alguém tenha todos os privilégios administrativos, digite visudo e adicione uma linha similar na seguinte na seção de especificação de privilégios do usuário:
juan ALL=(ALL) ALL
Este exemplo estabelece que o usuário juan pode usar o sudo em qualquer máquina e executar qualquer comando.
O exemplo abaixo ilustra a granularidade possível ao configurar o sudo:
%users  localhost=/sbin/shutdown -h now
Este exemplo estabelece que qualquer usuário pode submeter o comando /sbin/shutdown -h now desde que o faça pelo console.
A página man do sudoers tem uma lista detalhada das opções para este arquivo.

46.1.5. Serviços de Rede Disponíveis

O controle administrativo de acesso dos usuários é uma questão séria para administradores de sistemas dentro de uma empresa. No entanto, o controle de quais serviços de rede estão ativos é de suma importância para qualquer administrador e operador do sistema Linux.
Muitos serviços comportam-se como servidores de rede sob o Red Hat Enterprise Linux. Se um serviço de rede estiver rodando em uma máquina, então consequentemente um aplicativo de servidor (ou daemon) estará ouvindo conexões em uma ou mais portas de rede. Cada um destes servidores deve ser tratado como uma potencial via de ataque.

46.1.5.1. Riscos aos Serviços

Serviços de rede podem representar muitos riscos aos sistemas Linux. Veja abaixo uma lista dos principais problemas:
  • Ataques de Negação de Serviço (Denial of Service, ou DoS) — Ao inundar um serviço com pedidos, um ataque de negação de serviço pode inutilizar um sistema enquanto este tenta registrar e responder à cada solicitação.
  • Ataques de Vulnerabilidade de Script — Se um servidor estiver usando scripts para executar ações no lado do servidor, como servidores Web geralmente fazem, um cracker pode montar um ataque contra scripts escritos inapropriadamente. Estes ataques de vulnerabilidade de script podem levar à condição de estouro de buffer ou permitir que o atacante altere arquivos no sistema.
  • Ataques de Estouro de Buffer — Serviços que se conectam à portas numeradas de 0 a 1023 devem ser executados por um usuário administrativo. Se o aplicativo tiver uma vulnerabilidade de estouro de buffer, um atacante pode obter acesso ao sistema como o usuário rodando o daemon. Devido à existência de vulnerabilidades de estouro de buffer, os crackers usam ferramentas automatizadas para identificar sistemas com vulnerabilidades, e após obterem acesso ao sistema, utilizam rootkits automatizados para mantê-lo.

Nota

A ameaça das vulnerabilidades de estouro de buffer é amenizada no Red Hat Enterprise Linux pelo ExecShield, uma tecnologia de segmentação e proteção da memória executável suportada pelos kernels de mono ou multi-processadores x86. O ExecShield reduz o risco de estouro de buffer dividindo a memória virtual em segmentos executáveis e não-executáveis. Qualquer código de programa que tentar executar fora do segmento executável (como código maléfico de um exploit baseado em estouro de buffer) aciona uma falha de segmentação e é terminado.
O Execshield também inclui suporte para a tecnologia No eXecute (NX) nas plataformas AMD64 e para a tecnologia eXecute Disable (XD) em sistemas Itanium e Intel® 64. Estas tecnologias trabalham em conjunto com o ExecShield para impedir que código maldoso rode na porção executável da memória virtual com uma granularidade de 4KB de código executável, diminuindo o risco de ataques exploits furtivos de estouro de buffer.

Tip

Para limitar a exposição a ataques através da rede, todos os serviços que não estiverem sendo usados, devem ser desligados.

46.1.5.2. Identificando e Configurando Serviços

Para aumentar a segurança, a maioria dos serviços de rede instalados com o Red Hat Enterprise Linux são desligados por meio da configuração padrão. No entanto, há algumas exceções notáveis:
  • cupsd — O servidor de impressão padrão do Red Hat Enterprise Linux.
  • lpd — Um servidor de impressão alternativo.
  • xinetd — Um super servidor que controla conexões à uma gama de servidores subordinados, como gssftp e telnet.
  • sendmail — O Agente de Transporte de Correio (Mail Transport Agent ou MTA) Sendmail é habilitado pela configuração padrão, mas somente escuta por conexões a partir do localhost.
  • sshd — O servidor OpenSSH, um substituto seguro para o Telnet.
Ao determinar se estes serviços devem ou não ser deixados rodando, é melhor usar o bom senso e pecar pela precaução. Por exemplo, se uma impressora não está disponível, não deixe o cupsd rodando. O mesmo vale para o portmap. Se você não monta volumes NFSv3 ou não usa o NIS (o serviço ypbind), então o portmap deve ser desabilitado.
Red Hat Enterprise Linux ships with three programs designed to switch services on or off. They are the Services Configuration Tool (system-config-services), ntsysv, and chkconfig. For information on using these tools, refer to Capítulo 17, Controlando Acesso aos Serviços.
Services Configuration Tool
Ilustração da Ferramenta de Configuração de Serviços
Figura 46.3. Services Configuration Tool

If unsure of the purpose for a particular service, the Services Configuration Tool has a description field, illustrated in Figura 46.3, “Services Configuration Tool, that provides additional information.
Checking which network services are available to start at boot time is only part of the story. You should also check which ports are open and listening. Refer to Seção 46.2.8, “Verificando Quais Portas estão Escutando” for more information.

46.1.5.3. Serviços Inseguros

Potentially, any network service is insecure. This is why turning off unused services is so important. Exploits for services are routinely revealed and patched, making it very important to regularly update packages associated with any network service. Refer to Seção 45.5, “Atualizações de Segurança” for more information.
Alguns protocolos de rede são essencialmente mais inseguros que outros. Estes incluem quaisquer serviços que:
  • Transmitam Nomes de Usuário e Senhas Não Criptografados através de uma Rede — Muitos protocolos antigos, como Telnet e FTP, não criptografam a seção de autenticação e devem ser evitados sempre que possível.
  • Passem Dados Confidenciais por uma Rede Não-Criptografada — Muitos protocolos passam dados não-criptografados através da rede. Estes protocolos incluem o Telnet, FTP, HTTP e o SMTP. Muitos sistemas de arquivos de rede, como o NFS e o SMB, também passam informações não-criptografadas através da rede. É responsabilidade do usuário limitar o tipo de dados transmitidos ao utilizar estes protocolos.
    Serviços remotos de despejo de memória, como o netdump, passam o conteúdo da memória não criptografado através da rede. Despejos de memória podem conter senhas ou, pior ainda, informações de bancos de dados ou outras informações confidenciais.
    Outros serviços como finger e rwhod revelam informações sobre os usuários do sistema.
Entre os exemplos de serviços inseguros herdados, incluem rlogin, rsh, telnet, and vsftpd.
All remote login and shell programs (rlogin, rsh, and telnet) should be avoided in favor of SSH. Refer to Seção 46.1.7, “Ferramentas de Comunicação com Segurança Aprimorada” for more information about sshd.
FTP is not as inherently dangerous to the security of the system as remote shells, but FTP servers must be carefully configured and monitored to avoid problems. Refer to Seção 46.2.6, “Protegendo o FTP” for more information about securing FTP servers.
Os seguintes serviços devem ser cuidadosamente implementados e colocados atrás de um firewall:
  • finger
  • authd (chamado de identd em lançamentos anteriores do Red Hat Enterprise Linux)
  • netdump
  • netdump-server
  • nfs
  • rwhod
  • sendmail
  • smb (Samba)
  • yppasswdd
  • ypserv
  • ypxfrd
More information on securing network services is available in Seção 46.2, “Segurança do Servidor”.
A próxima seção aborda as ferramentas disponíveis para a configuração de um firewall simples.

46.1.6. Firewalls Pessoais

Após o término da configuração de serviços de rede necessários, é importante que se implemente um firewall.

Importante

Você deve configurar os serviços necessários e implementar um firewall antes de se conectar à Internet ou qualquer outra rede não confiável.
Firewalls evitam que pacotes de rede acessem a interface de rede do sistema. Se uma solicitação for feita à uma porta que estiver bloqueada pelo firewall, tal solicitação será ignorada. Se um serviço estiver escutando em uma destas portas bloqueadas, o mesmo não receberá os pacotes e será efetivamente desabilitado. Por este motivo, ao configurar um firewall, certifique-se de bloquear o acesso à portas que não estejam sendo usadas e liberar o acesso à portas usadas por serviços configurados.
For most users, the best tool for configuring a simple firewall is the graphical firewall configuration tool which ships with Red Hat Enterprise Linux: the Security Level Configuration Tool (system-config-securitylevel). This tool creates broad iptables rules for a general-purpose firewall using a control panel interface.
Refer to Seção 46.8.2, “Configurações Básicas de Firewall ” for more information about using this application and its available options.
For advanced users and server administrators, manually configuring a firewall with iptables is probably a better option. Refer to Seção 46.8, “Firewalls” for more information. Refer to Seção 46.9, “IPTables” for a comprehensive guide to the iptables command.

46.1.7. Ferramentas de Comunicação com Segurança Aprimorada

Na mesma proporção em que cresceu o tamanho e a popularidade da Internet, cresceu também a ameaça da interceptação de comunicações. Através dos anos, ferramentas foram desenvolvidas para criptografar comunicações durante sua transmissão através de redes de comunicação.
O Red Hat Enterprise Linux é distribuído com duas ferramentas básicas que usam algoritmos de alto nível e baseados em criptografia de chave pública para proteger dados enquanto estes trafegam pela rede.
  • OpenSSH — Uma versão gratuita do protocolo SSH para criptografar comunicações de rede.
  • GNU Privacy Guard (GPG) — Uma implementação gratuita de aplicativo de criptografia PGP (Pretty Good Privacy) para criptografar dados.
OpenSSh é uma maneira mais segura de acessar uma máquina remota e substitui serviços não criptografados como telnet e rsh. OpenSSH inclui um serviço de rede chamado sshd, e três aplicações cliente de linha de comandos:
  • ssh — Um cliente de acesso seguro a consoles remotos.
  • scp — Um comando seguro de cópia remota.
  • sftp — Um cliente pseudo-ftp seguro que permite seções interativas de transferência de arquivos.

Importante

Although the sshd service is inherently secure, the service must be kept up-to-date to prevent security threats. Refer to Seção 45.5, “Atualizações de Segurança” for more information.
GPG é uma maneira de garantir a privacidade da comunicação por e-mail. Pode ser usado tanto para enviar e-mail com dados privativos através de redes públicas como para proteger dados confidenciais em discos rígidos.

46.2. Segurança do Servidor

Quando um sistema é usado como um servidor em um rede pública, torna-se um alvo de ataques. Por esta razão solidificar e trancar os serviços é de suma importância para o administrador de sistemas.
Antes de aprofundar em questões específicas, você deve revisar as seguintes dicas gerais para aumentar a segurança do servidor:
  • Mantenha todos os serviços atualizados para protegê-los contra as ameaças recentes.
  • Use protocolos seguros sempre que possível.
  • Ofereça apenas um tipo de serviço de rede por máquina sempre que possível.
  • Monitore todos os servidores cuidadosamente e atente para atividades suspeitas.

46.2.1. Protegendo Serviços com TCP Wrappers e xinetd

TCP wrappers oferecem controle de acesso a vários serviços. A maioria dos serviços de rede modernos, como SSH, Telnet e FTP, utilizam TCP wrappers, que ficam de guarda entre a entrada de um pedido e o serviço requisitado.
Os benefícios oferecidos por TCP wrappers aumentam quando este é usado junto ao xinetd, um super servidor que oferece acesso adicional, registro, vinculação, redirecionamento e controle de utilização de recursos.

Tip

It is a good idea to use iptables firewall rules in conjunction with TCP Wrappers and xinetd to create redundancy within service access controls. Refer to Seção 46.8, “Firewalls” for more information about implementing firewalls with iptables commands.
Refer to Seção 17.2, “TCP Wrappers” for more information on configuring TCP Wrappers and xinetd.
As sub-seções seguintes assumem um conhecimento básico de cada tópico e concentram-se nas opções de segurança específicas.

46.2.1.1. Aumentando a Segurança com TCP Wrappers

Os TCP wrappers são capazes de fazer muitas outras coisas além de simplesmente negar acesso aos serviços. Esta seção ilustra como eles podem ser utilizados para enviar banners de conexão, alertar ataques em hosts específicos e aprimorar a funcionalidade de autenticação. Consulte a página man hosts_options para obter uma lista completa das funcionalidades e linguagem de controle do TCP Wrapper.
46.2.1.1.1. TCP Wrappers e Banners de Conexão
Enviar um banner apropriado quando os usuários se conectarem a um serviço é uma boa forma de informar atacantes em potencial que o administrador de sistemas está sob vigília. Você também pode controlar se as informações sobre o sistema estão sendo disponibilizadas aos usuários.Para implementar um banner do TCP Wrappers para um serviço, use a opção banner.
Este exemplo implementa um banner para o vsftpd. Para começar, crie um arquivo de banner. Pode estar em qualquer lugar do sistema, mas deve levar o mesmo nome que o daemon. Neste exemplo, o arquivo é chamado /etc/banners/vsftpd e contém as seguintes linhas:
220-Hello, %c
220-All activity on ftp.example.com is logged.
220-Inappropriate use will result in your access privileges being removed.
A expressão %c oferece uma gama de informações do cliente, tais como nome de usuário e nome de host ou nome de usuário e endereço IP, para intimidar ainda mais a conexão.
Para que este banner seja apresentado em futuras conexões, adicione a seguinte linha ao arquivo /etc/hosts.allow:
vsftpd : ALL : banners /etc/banners/
46.2.1.1.2. TCP Wrappers e Alertas de Ataque
Se um determinado host ou rede for flagrado atacando o servidor, o TCP wrappers pode ser usado para alertar o administrador sobre ataques subseqüentes deste host ou rede através da diretiva spawn.
Neste exemplo, assuma que um cracker da rede 206.182.68.0/24 foi pego tentando atacar o servidor. Ao inserir a seguinte linha no arquivo /etc/hosts.deny, a tentativa de conexão a partir daquela rede é negada e registrada em um arquivo especial:
ALL : 206.182.68.0 : spawn /bin/ 'date' %c %d >> /var/log/intruder_alert
A expressão %d traz o nome do serviço que o atacante estava tentando acessar.
Para permitir a conexão e registrá-la, insira diretiva spawn no arquivo /etc/hosts.allow.

Nota

Já que a diretiva spawn executa qualquer comando de linha, crie um script especial para notificar o administrador ou para executar uma série de comandos quando um determinado cliente tentar conectar ao servidor.
46.2.1.1.3. TCP Wrappers e Registro Aprimorado
Se determinados tipos de conexões são mais preocupantes que outras, o nível de registro pode ser elevado para estes serviços através da opção severity.
Neste exemplo, considere que qualquer um tentando conectar à porta 23 (a porta do Telnet) em um servidor FTP é um cracker. Para denotar isso, insira um sinal emerg nos arquivos de registro ao invés do sinal padrão, info, e negue a conexão.
Para fazer isso, insira a seguinte linha no arquivo /etc/hosts.deny:
in.telnetd : ALL : severity emerg
Isto usa a facilidade de registro authpriv padrão, mas eleva a prioridade do valor padrão info para emerg, o que envia mensagens de registro diretamente ao console.

46.2.1.2. Aumentando a Segurança com o xinetd

Esta seção concentra-se no uso do xinetd para configurar um serviço armadilha e usá-lo para controlar níveis de recursos disponíveis para quaisquer serviços xinetd. Estabelecer limites de recursos para serviços pode ajudar a frustrar ataques de Negação de Serviço (Denial of Service, ou DoS). Consulte as páginas man para o xinetd e o xinetd.conf para uma lista de opções disponíveis.
46.2.1.2.1. Montando uma Armadilha
Uma importante característica do xinetd é sua habilidade em adicionar hosts à uma lista global no_access. Aos hosts desta lista são negadas as conexões subseqüentes aos serviços gerenciados pelo xinetd por um determinado período ou até o xinetd ser reiniciado. Isto é feito usando o atributo SENSOR. Esta técnica é uma maneira fácil de bloquear hosts que tentarem scanear o servidor.
O primeiro passo para definir um SENSOR é escolher um serviço que você não planeja utilizar. Neste exemplo, usamos o Telnet.
Edite o arquivo /etc/xinetd.d/telnet e altere a linha flags para:
flags           = SENSOR
Adicione a seguinte linha:
deny_time       = 30
Isto nega a conexão do host que tentou conectar à porta por 30 minutos. Outros valores aceitáveis para o atributo deny_time são FOREVER (sempre), que mantém o banimento efetivo até que o xinetd seja reiniciado, e NEVER (nunca), que permite a conexão e a registra.
Finalmente, a última linha deve ser:
disable         = no
Isto habilita a armadilha.
Apesar do uso do SENSOR ser uma boa maneira de detectar e parar conexões de hosts perigosos, há duas desvantagens:
  • Não funciona contra scans secretos.
  • Um atacante ciente de que você está rodando o SENSOR pode montar um ataque de Negação de Serviço contra determinados hosts forjando seus endereços IP e conectando à porta proibida.
46.2.1.2.2. Controlando Recursos de Servidor
Outra característica importante do xinetd é sua habilidade em controlar a quantidade de recursos que os serviços sob seu controle podem utilizar.
Ele o faz através das seguintes diretivas:
  • cps = <number_of_connections> <wait_period> — Limita a taxa de conexões de entrada. Esta diretiva leva dois argumentos:
    • <number_of_connections> — O número de conexões por segundo a serem manuseadas. Se a taxa de conexões de entrada for mais alta que isto, o serviço torna-se temporariamente desabilitado. O valor padrão é cinqüenta (50).
    • <wait_period> — O número de segundos a esperar antes de reabilitar o serviço após o mesmo tenha sido desabilitado. O intervalo padrão é dez (10) segundos.
  • instances = <number_of_connections> — Determina o número total de conexões permitidas a um serviço. Esta diretiva aceita tanto um valor inteiro como UNLIMITED.
  • per_source = <number_of_connections> — Determina as conexões permitidas a um serviço por cada host. Esta diretiva aceita tanto um valor inteiro como UNLIMITED.
  • rlimit_as = <number[K|M]> — Determina a quantidade de espaço de endereço de memória que o serviço pode ocupar em kilobytes ou megabytes. Esta diretiva aceita tanto um valor inteiro como UNLIMITED.
  • rlimit_cpu = <number_of_seconds> — Determina o tempo em segundos durante o qual um serviço pode ocupar a CPU. Esta diretiva aceita tanto um valor inteiro como UNLIMITED.
O uso destas diretivas pode ajudar a prevenir que qualquer serviço xinetd sobrecarregue o sistema, resultando em negação de serviço.

46.2.2. Protegendo o Portmap

O serviço portmap é um daemon de atribuição dinâmica de portas para serviços RPC, como o NIS e o NFS. Tem mecanismos de autenticação fracos e tem habilidade para delegar uma vasta gama de portas para os serviços que controla. Por estas razões, é difícil de proteger.

Nota

Proteger o portmap afeta somente as implementações do NFSv2 e NFSv3, já que o NFSv4 não o requer mais. Se você planeja implementar um servidor NFSv2 ou NFSv3, o portmap é necessário e a seção seguinte é válida.
Se você está rodando serviços RPC, siga estas regras básicas.

46.2.2.1. Proteja o portmap com TCP Wrappers

É importante usar TCP Wrappers para limitar quais redes ou hosts têm acesso ao serviço portmap já que este não possui uma forma de autenticação própria.
Além disso, use somente endereços IP ao limitar acesso para o serviço. Evite usar estes nomes de host, já que eles podem ser forjados através da adulteração do DNS e outros métodos.

46.2.2.2. Proteja o portmap com iptables

Para restringir ainda mais o acesso ao serviço portmap, é uma boa idéia adicionar regras do iptables ao servidor e restringir o acesso à redes específicas.
Abaixo encontram-se dois exemplos de comandos do iptables. O primeiro permite conexões TCP à porta 111 (usada pelo serviço portmap) a partir da rede 192.168.0.0/24. O segundo permite conexões TCP à mesma porta a partir do host local. Isto é necessário para o serviço sgi_fam usado pelo Nautilus. Todos os outros pacotes são descartados.
iptables -A INPUT -p tcp -s! 192.168.0.0/24 --dport 111 -j DROP
iptables -A INPUT -p tcp -s 127.0.0.1 --dport 111 -j ACCEPT
Para limitar o tráfego UDP similarmente, use o seguinte comando.
iptables -A INPUT -p udp -s! 192.168.0.0/24 --dport 111 -j DROP

Tip

Refer to Seção 46.8, “Firewalls” for more information about implementing firewalls with iptables commands.

46.2.3. Protegendo o NIS

The Network Information Service (NIS) is an RPC service, called ypserv,--> which is used in conjunction with portmap and other related services to distribute maps of usernames, passwords, and other sensitive information to any computer claiming to be within its domain.
Um servidor NIS é composto de diversas aplicações. Elas incluem as seguintes:
  • /usr/sbin/rpc.yppasswdd — Também chamado de serviço yppasswdd, esse daemon permite que os usuários alterem suas senhas NIS.
  • /usr/sbin/rpc.ypxfrd — Também chamado de serviço ypxfrd, esse daemon é responsável pelas transferências de mapa do NIS através da rede.
  • /usr/sbin/yppush — Essa aplicação propaga bancos de dados NIS alterados para servidores NIS múltiplos.
  • /usr/sbin/ypserv — Este é o servidor daemon do NIS.
O NIS é não é nada seguro para os padrões de hoje. Não possui mecanismos de autenticação de host e passa toda a sua informação sem criptografia através da rede, incluindo o hash de senhas. Como resultado, tenha muito cuidado ao configurar uma rede que usa o NIS. Para complicar ainda mais, a configuração padrão do NIS é essencialmente insegura.
It is recommended that anyone planning to implement an NIS server first secure the portmap service as outlined in Seção 46.2.2, “Protegendo o Portmap”, then address the following issues, such as network planning.

46.2.3.1. Planejar Cuidadosamente a Rede

Como o NIS passa informações confidenciais sem criptografia através da rede, é importante que o serviço seja executado por trás de uma firewall e numa rede segmentada e segura. Toda vez que informações do NIS são passadas através de uma rede insegura, há o risco de serem interceptadas. O design cuidadoso da rede neste aspecto pode ajudar a prevenir sérias violações à segurança.

46.2.3.2. Use um Nome de Domínio e Nome de Host NIS parecido com uma senha

Qualquer máquina com um domínio NIS pode usar comandos para extrair informações do servidor sem autenticação, desde que o usuário saiba o nome do host DNS e o nome de domínio NIS do servidor.
Por exemplo, se alguém conectar um laptop a uma rede ou violar a rede por fora (e conseguir falsificar um endereço IP interno), o seguinte comando revela o mapa de /etc/passwd:
ypcat -d <NIS_domain> -h <DNS_hostname> passwd
Se este atacante for um usuário root, poderá obter o arquivo /etc/shadow digitando o seguinte comando:
ypcat -d <NIS_domain> -h <DNS_hostname> shadow

Nota

Se o Kerberos for usado, o arquivo /etc/shadow não estará armazenado em um mapa NIS.
Para dificultar o acesso aos mapas NIS a um atacante, crie uma série randômica de caracteres para o nome de host DNS, tal como o7hfawtgmhwg.domain.com. Similarmente, crie um nome diferente de domínio NIS randomizado . Isto dificulta bastante o acesso de um atacante ao servidor NIS.

46.2.3.3. Edite o Arquivo /var/yp/securenets

Se o arquivo /var/yp/securenets estiver vazio, ou não existir (como é o caso logo após uma instalação padrão), o NIS escuta à todas as redes. Uma das primeiras coisas a serem feitas é colocar pares de rede/máscara de rede no arquivo para que o ypserv apenas responda à pedidos de redes apropriadas.
Veja abaixo um exemplo de entrada de um arquivo /var/yp/securenets:
255.255.255.0     192.168.0.0

Alerta

Nunca inicie um servidor NIS pela primeira vez sem criar o arquivo /var/yp/securenets.
Essa técnica não oferece proteção contra ataque de spoofing de IP, mas pelo menos impõe limites a quais redes o servidor NIS serve.

46.2.3.4. Atribuir Portas Estáticas e Usar Regras do iptables

Todos os servidores relacionados ao NIS podem ter portas específicas, exceto o rpc.yppasswdd — o daemon que permite a usuários alterarem suas senhas de autenticação. Atribuir portas para os outros dois daemons do servidor NIS, rpc.ypxfrd e ypserv, permite criar regras de firewall para proteger futuramente os daemons do servidor NIS contra intrusos.
Para fazer isto, adicione as seguintes linhas a /etc/sysconfig/network:
YPSERV_ARGS="-p 834" YPXFRD_ARGS="-p 835"
As seguintes regras do iptables podem ser determinadas para reforçar a qual rede o servidor escuta para estas portas:
iptables -A INPUT -p tcp -s! 192.168.0.0/24 --dport 834 -j DROP
iptables -A INPUT -p tcp -s! 192.168.0.0/24 --dport 835 -j DROP
iptables -A INPUT -p udp -s! 192.168.0.0/24 --dport 834 -j DROP
iptables -A INPUT -p udp -s! 192.168.0.0/24 --dport 835 -j DROP
This means that the server only allows connections to ports 834 and 835 if the requests come from the 192.168.0.0/24 network.

Tip

Refer to Seção 46.8, “Firewalls” for more information about implementing firewalls with iptables commands.

46.2.3.5. Use Autenticação do Kerberos

Uma das desvantagens mais gritantes ao usar NIS para autenticação é que sempre que um usuário se autentica numa máquina, um hash de senha é enviado do mapa /etc/shadow através da rede. Se um intruso obtiver acesso a um domínio NIS e bisbilhotar o tráfego de rede, os hashes de senha e nomes de usuários podem ser discretamente coletados. Com tempo suficiente, um programa de quebra de senhas pode adivinhar senhas fáceis e um atacante pode obter acesso a uma conta válida na rede.
Since Kerberos uses secret-key cryptography, no password hashes are ever sent over the network, making the system far more secure. Refer to Seção 46.6, “Kerberos” for more information about Kerberos.

46.2.4. Protegendo o NFS

The Network File System (NFS) is a service that provides network accessible file systems for client machines. Refer to Capítulo 20, Sistema de Arquivo de Rede (NFS - Network File System) for more information about NFS. The following subsections assume a basic knowledge of NFS.

Importante

The version of NFS included in Red Hat Enterprise Linux, NFSv4, no longer requires the portmap service as outlined in Seção 46.2.2, “Protegendo o Portmap”. NFS traffic now utilizes TCP in all versions, rather than UDP, and requires it when using NFSv4. NFSv4 now includes Kerberos user and group authentication, as part of the RPCSEC_GSS kernel module. Information on portmap is still included, since Red Hat Enterprise Linux supports NFSv2 and NFSv3, both of which utilize portmap.

46.2.4.1. Planejar Cuidadosamente a Rede

Agora que o NFSv4 tem a habilidade de passar todas as informações criptografadas usando o Kerberos através da rede, é importante que o serviço seja configurado corretamente se estiver atrás de um firewall ou numa rede segmentada. O NFSv2 e NFSv3 ainda passam dados de forma insegura e seus riscos devem ser considerados. Um planejamento cuidadoso da rede neste aspecto pode ajudar a prevenir violações à segurança.

46.2.4.2. Cuidado com Erros de Sintaxe

O servidor NFS determina quais sistemas de arquivo e quais hosts exportar para estes diretórios através do arquivo /etc/exports. Cuidado para não adicionar espaços extras ao editar este arquivo.
Por exemplo, a linha a seguir no arquivo /etc/exports compartilha o diretório /tmp/nfs/ com o host bob.example.com com permissões de leitura e escrita.
/tmp/nfs/     bob.example.com(rw)
Por outro lado, esta linha do arquivo /etc/exports compartilha o mesmo diretório com o host bob.example.com com permissão somente-leitura, e o compartilha com o mundo com permissões leitura e escrita devido um único caractere de espaço após o nome de host.
/tmp/nfs/     bob.example.com (rw)
É bom praticar a verificação de quaisquer compartilhamentos NFS usando o comando showmount para checar o que está sendo compartilhado:
showmount -e <hostname>

46.2.4.3. Não Use a Opção no_root_squash

Por padrão, compartilhamentos NFS alteram o usuário root para o usuário nfsnobody, uma conta de usuário sem privilégios. Isto muda o proprietário de todos os arquivos criados pelo root para nfsnobody, que previne o carregamento de programas com o setuid definido.
If no_root_squash is used, remote root users are able to change any file on the shared file system and leave applications infected by Trojans for other users to inadvertently execute.

46.2.5. Protegendo o Servidor HTTP Apache

O Servidor HTTP Apache é um dos serviços mais estáveis e seguros distribuídos com o Red Hat Enterprise Linux. Há um número exorbitante de opções e técnicas disponíveis para proteger o Servidor HTTP Apache — muito numerosos para serem explorados em detalhes aqui.
When configuring the Apache HTTP Server, it is important to read the documentation available for the application. This includes Capítulo 23, Apache HTTP Server, and the Stronghold manuals, available at http://www.redhat.com/docs/manuals/stronghold/.
Administradores de Sistemas devem ter cuidado ao utilizar as seguintes opções:

46.2.5.1. FollowSymLinks

Esta diretiva é habilitada por padrão, portanto tenha cuidado ao criar links simbólicos para a raiz dos documentos do servidor Web. Por exemplo, é uma má idéia prover um link simbólico para /.

46.2.5.2. A Diretiva Indexes

Esta diretiva é habilitada por padrão, mas pode não ser desejável. Para prevenir que visitantes naveguem pelos arquivos no servidor, remova esta diretiva.

46.2.5.3. A Diretiva UserDir

A diretiva UserDir é desabilitada por padrão porque esta pode confirmar a presença de uma conta de usuário no sistema. Para possibilitar a navegação pelos diretórios do usuário no servidor, use as seguintes diretivas:
UserDir enabled
UserDir disabled root
Estas diretivas ativam a navegação em todos os diretórios de usuário, exceto no /root/. Para adicionar usuários à lista de contas desativadas, adicione uma lista de usuários delimitada por espaço na linha UserDir disabled.

46.2.5.4. Não Remova a Diretiva IncludesNoExec

Por padrão, o módulo Server-Side Includes (SSI) não pode executar comandos. Não é recomendado alterar esta configuração a não ser que seja absolutamente necessário, já que pode, potencialmente, possibilitar que um atacante execute comandos no sistema.

46.2.5.5. Permissões Restritas para Diretórios Executáveis

Certifique-se de conceder permissões de gravação (write) apenas para o usuário root em todos os diretórios contendo scripts ou CGIs. Isto pode ser feito digitando os seguintes comandos:
chown root <directory_name>
chmod 755 <directory_name>

Importante

Também verifique sempre se todos os scripts rodando no sistema funcionam como planejado antes de colocá-los em produção.

46.2.6. Protegendo o FTP

The File Transfer Protocol (FTP) is an older TCP protocol designed to transfer files over a network. Because all transactions with the server, including user authentication, are unencrypted, it is considered an insecure protocol and should be carefully configured.
O Red Hat Enterprise Linux oferece três servidores FTP.
  • gssftpd — Um FTP daemon kerberizado baseado no xinetd que não passa informações de autenticação através da rede.
  • Red Hat Content Accelerator (tux) — Um servidor Web de espaço de kernel com capacidades de FTP.
  • vsftpd — Uma implementação auto-suficiente do serviço FTP orientada à segurança.
As orientações de segurança a seguir referem-se à configuração do serviço FTP vsftpd.

46.2.6.1. Banner de Saudação do FTP

Antes de submeter um nome de usuário e senha, é apresentado um banner de saudação a todos os usuários. Por padrão, este banner inclui informações da versão úteis para crackers tentando identificar fraquezas num sistema.
Para alterar o banner de saudação do vsftpd, adicione a seguinte diretiva ao arquivo /etc/vsftpd/vsftpd.conf:
ftpd_banner=<insira_saudação_aqui>
Substitua <insira_saudação_aqui> na diretiva acima pelo texto de sua mensagem de saudação.
Para banners com muitas linhas, é melhor usar um arquivo de banner. Para simplificar o gerenciamento de banners múltiplos, coloque todos os banners em um novo diretório chamado /etc/banners/. O arquivo de banners para conexões FTP, neste exemplo, é /etc/banners/ftp.msg. O exemplo abaixo mostra como este arquivo se parece:
########## Hello, all activity on ftp.example.com is logged. #########

Nota

It is not necessary to begin each line of the file with 220 as specified in Seção 46.2.1.1.1, “TCP Wrappers e Banners de Conexão”.
Para referenciar este arquivo de banners de saudação do vsftpd, adicione a seguinte diretiva ao arquivo /etc/vsftpd/vsftpd.conf:
banner_file=/etc/banners/ftp.msg

Importante

Make sure that you specify the path to the banner file correctly in /etc/vsftpd/vsftpd.conf, or else every attempt to connect to vsftpd will result in the connection being closed immediately and a 500 OOPS: cannot open banner <path_to_banner_file> error message.
Note that the banner_file directive in /etc/vsftpd/vfsftpd.conf takes precedence over any ftpd_banner directives in the configuration file: if banner_file is specified, then ftpd_banner is ignored.
It also is possible to send additional banners to incoming connections using TCP Wrappers as described in Seção 46.2.1.1.1, “TCP Wrappers e Banners de Conexão”.

46.2.6.2. Acesso Anônimo

A presença do diretório /var/ftp/ ativa a conta anônima.
A maneira mais fácil de criar este diretório é instalar o pacote vsftpd. Este pacote define uma árvore de diretório para usuários anônimos e configura as permissões dos diretórios para somente-leitura para usuários anônimos.
Por padrão, a conta do usuário anônimo não pode escrever em nenhum diretório.

Atenção

Se você possibilitar o acesso anônimo a um servidor FTP, tome cuidado onde armazena os dados importantes.
46.2.6.2.1. Upload Anônimo
Para permitir que usuários anônimos façam upload, é recomendado criar um diretório somente-gravação (write-only) em /var/ftp/pub/.
Para fazê-lo, use o seguinte comando:
mkdir /var/ftp/pub/upload
A seguir, modifique as permissões para que usuários anônimos não possam visualizar o conteúdo do diretório:
chmod 730 /var/ftp/pub/upload
Uma lista do diretório em formato longo deve se parecer com o seguinte:
drwx-wx---    2 root     ftp          4096 Feb 13 20:05 upload

Alerta

Administradores que permitem a usuários anônimos ler e gravar em diretórios, freqüentemente percebem que seu servidor se torna um depósito de software roubado.
Adicionalmente, abaixo de vsftpd, adicione a seguinte linha ao arquivo /etc/vsftpd/vsftpd.conf:
anon_upload_enable=YES

46.2.6.3. Contas de Usuário

Já que o FTP passa nomes de usuário e senhas não criptografados através de redes inseguras para autenticação, é uma boa idéia proibir usuários do sistema acessarem o servidor através de suas contas de usuário.
Para desativar contas de usuário em vsftpd, adicione a seguinte diretiva a /etc/vsftpd/vsftpd.conf:
local_enable=NO
46.2.6.3.1. Restringindo Contas de Usuário
To disable FTP access for specific accounts or specific groups of accounts, such as the root user and those with sudo privileges, the easiest way is to use a PAM list file as described in Seção 46.1.4.2, “Impedindo Acesso Root”. The PAM configuration file for vsftpd is /etc/pam.d/vsftpd.
Também é possível desativar contas de usuário dentro de cada serviço diretamente.
Para desativar contas de usuário específicas em vsftpd, adicione o nome do usuário a /etc/vsftpd.ftpusers.

46.2.6.4. Use TCP Wrappers para Controlar Acesso

Use TCP Wrappers to control access to either FTP daemon as outlined in Seção 46.2.1.1, “Aumentando a Segurança com TCP Wrappers”.

46.2.7. Protegendo o Sendmail

O Sendmail é um Agente de Transporte de Correspondência (Mail Transport Agent - MTA) que utiliza o Protocolo de Transporte de Correspondência Simples (Simple Mail Transport Protocol - SMTP) para entregar mensagens eletrônicas entre outros MTAs e para enviar e-mails a clientes ou agentes de entrega. Apesar de muitos MTAs serem capazes de criptografar tráfego entre eles, a maioria não o faz, portanto enviar e-mail através de qualquer rede pública é considerado uma forma de comunicação essencialmente insegura.
Refer to Capítulo 25, Email for more information about how email works and an overview of common configuration settings. This section assumes a basic knowledge of how to generate a valid /etc/mail/sendmail.cf by editing the /etc/mail/sendmail.mc and using the m4 command.
É recomendado a qualquer um planejando implementar um servidor Sendmail, resolver as seguintes questões.

46.2.7.1. Limitar um Ataque Denial of Service

Devido à natureza de e-mails, um determinado atacante pode facilmente mandar uma enxurrada de correspondência para o servidor e causar um ataque de negação de serviço. Ao determinar limites para as diretivas a seguir em /etc/mail/sendmail.mc, a efetividade de ataques deste tipo é limitada.
  • confCONNECTION_RATE_THROTTLE — O número de conexões que o servidor pode receber por segundo. Por padrão, o Sendmail não limita o número de conexões. Se um limite for definido e alcançado, conexões subseqüentes terão que esperar.
  • confMAX_DAEMON_CHILDREN — O número máximo de processos filho que podem ser gerados pelo servidor. Por padrão, o Sendmail não determina um número limite de processos filho. Se um limite for definido e alcançado, conexões futuras terão que esperar.
  • confMIN_FREE_BLOCKS — O número mínimo de blocos livres que devem estar disponíveis para que o servidor aceite correspondência. O valor padrão é 100 blocos.
  • confMAX_HEADERS_LENGTH — O tamanho máximo aceitável (em bytes) para o cabeçalho de uma mensagem.
  • confMAX_MESSAGE_SIZE — O tamanho máximo aceitável (em bytes) para qualquer mensagem.

46.2.7.2. NFS e Sendmail

Nunca coloque o diretório spool de correspondência, /var/spool/mail/, em um volume NFS compartilhado.
Como o NFSv2 e o NFSv3 não mantém controle sobre IDs de usuário e grupo, dois ou mais usuários podem ter o mesmo UID, e portanto receber e ler a correspondência do outro.

Nota

Isso não ocorre com o NFSv4 usando Kerberos, já que o módulo de kernel SECRPC_GSS não utiliza a autenticação baseada no UID. Entretanto, é uma boa idéia não colocar o diretório spool de correspondência em volumes NFS compartilhados.

46.2.7.3. Usuários Mail-only

Para ajudar a prevenir exploits locais no servidor Sendmail, é melhor que usuários de mail acessem o Sendmail usando apenas um programa de email. Contas shell não devem ser permitidas no servidor de correspondência e todos os usuários shell do arquivo /etc/passwd devem ser definidos para /sbin/nologin (com a possível exceção do usuário root).

46.2.8. Verificando Quais Portas estão Escutando

Após configurar os serviços de rede, é importante atentar para quais portas estão escutando as interfaces de rede do sistema. Quaisquer portas abertas podem ser evidências de uma intrusão.
Há duas formas básicas de listar as portas que estão escutando a rede. A menos confiável é questionar a lista da rede ao digitar comandos como netstat -an ou lsof -i. Este método é menos confiável já que estes programas não conectam à máquina pela rede, mas checam o que está sendo executado no sistema. Por esta razão, estas aplicações são alvos freqüentes de substituição por atacantes. Desta maneira, os crackers tentam cobrir seus passos se abrirem portas de rede não autorizadas através da substituição do netstat e do lsof pelas suas próprias versões modificadas.
Uma forma mais confiável de listar quais portas estão escutando a rede é usar um scanner de portas como o nmap.
O comando a seguir, submetido em um console, determina quais portas estão escutando conexões FTP pela rede:
nmap -sT -O localhost
O output deste comando se parece com o seguinte:
Starting nmap 3.55 ( http://www.insecure.org/nmap/ ) at 2004-09-24 13:49 EDT
Interesting ports on localhost.localdomain (127.0.0.1):
(The 1653 ports scanned but not shown below are in state: closed)
PORT      STATE SERVICE
22/tcp    open  ssh
25/tcp    open  smtp
111/tcp   open  rpcbind
113/tcp   open  auth
631/tcp   open  ipp
834/tcp   open  unknown
2601/tcp  open  zebra
32774/tcp open  sometimes-rpc11
Device type: general purpose
Running: Linux 2.4.X|2.5.X|2.6.X OS details: Linux 2.5.25 - 2.6.3 or Gentoo 1.2 Linux 2.4.19 rc1-rc7)
Uptime 12.857 days (since Sat Sep 11 17:16:20 2004)
Nmap run completed -- 1 IP address (1 host up) scanned in 5.190 seconds
Este output mostra que o sistema está rodando o portmap devido à presença do serviço sunrpc. No entanto, também há um serviço misterioso na porta 834. Para verificar se a porta está associada à lista oficial de serviços conhecidos, digite:
cat /etc/services | grep 834
Este comando não retorna nenhum output. Isto indica que enquanto a porta está no intervalo reservado (de 0 a 1023) e requer acesso root para abrir, não está associada a um serviço conhecido.
Em seguida, verifique as informações sobre a porta usando netstat ou lsof. Para verificar a porta 834 usando netstat, use o seguinte comando:
netstat -anp | grep 834
O comando retorna o seguinte output:
tcp   0    0 0.0.0.0:834    0.0.0.0:*   LISTEN   653/ypbind
A presença da porta aberta em netstat afirma que um cracker que abrir clandestinamente uma porta num sistema violado provavelmente não permitirá que esta seja revelada através deste comando. A opção [p] também revela o id do processo (PID) do serviço que abriu a porta. Neste caso, a porta aberta pertence ao ypbind (NIS), que é um serviço RPC administrado juntamente ao serviço portmap.
O comando lsof revela informações similares ao netstat já que é capaz de ligar portas abertas a serviços:
lsof -i | grep 834
Veja abaixo a parte relevante do output deste comando:
ypbind      653        0    7u  IPv4       1319                 TCP *:834 (LISTEN)
ypbind      655        0    7u  IPv4       1319                 TCP *:834 (LISTEN)
ypbind      656        0    7u  IPv4       1319                 TCP *:834 (LISTEN)
ypbind      657        0    7u  IPv4       1319                 TCP *:834 (LISTEN)
Estas ferramentas podem revelar muitas informações sobre o estado dos serviços rodando em uma máquina. Estas ferramentas são flexíveis e podem prover uma riqueza de informações sobre os serviços e configurações da rede. Consulte as páginas man do lsof, do netstat, do nmap, e do services para maiores informações.

46.3. Single Sign-on (SSO)

46.3.1. Introdução

A funcionalidade SSO de Red Hat Enterprise Linux, reduz a quantidade de vezes que os usuários de desktop Red Hat Enterprise Linux precisam inserir suas senhas. Muitos aplicativos aproveitam a mesma autenticação adjacente e mecanismos de autorização para os usuários se registrarem no Red Hat Enterprise Linux a partir da tela de registro, assim não precisarão reinserir suas senhas. Estes aplicativos estão detalhados abaixo:
Além disso, os usuários podem se registrar em suas máquinas até quando não houver rede de trabalho (módulo offline) ou onde a conectividade da rede de trabalho não for confiável, por exemplo, no acesso wireless. Nos casos mais recentes, os serviços irão degradar vagarosamente.

46.3.1.1. Aplicativos suportados

Os aplicativos seguintes são suportados atualmente pelo esquema de registro unificado em Red Hat Enterprise Linux:
  • Registro
  • Proteção de tela
  • Firefox e Thunderbird

46.3.1.2. Mecanismos de Autenticação Suportados

Red Hat Enterprise Linux atualmente suporta os seguintes mecanismos de autenticação:
  • Nome de Kerberos/registro de senha
  • Cartão Inteligente/ Registro de PIN

46.3.1.3. Cartões Inteligentes Suportados

Red Hat Enterprise Linux foi testado com o cartão e leitor e-gate Cyberflex, mas qualquer cartão que seja compatível ao cartão Java 2.1.1 e especificações de Plataforma Global 2.0.1, devem operar corretamente, como qualquer outro leitor que seja suportado pelo PCSC-lite.
Red Hat Enterprise Linux também foi testado com Cartões de Acesso Comuns (CAC). O leitor suportado para CAC é o Leitor SCM SCR 331 USB.
As of Red Hat Enterprise Linux 5.2, Gemalto smart cards (Cyberflex Access 64k v2, standard with DER SHA1 value configured as in PKCSI v2.1) are now supported. These smart cards now use readers compliant with Chip/Smart Card Interface Devices (CCID).

46.3.1.4. Vantagens do Single Sign-on Red Hat Enterprise Linux

Diversos mecanismos de segurança que existem atualmente, utilizam um grande número de protocolos e armazenamentos credenciais. Alguns exemplos incluem: SSL, SSH, IPsec e Kerberos. O SSO do Red Hat Enterprise Linux enfoca a unificação destes esquemas para suportar os requerimentos listados acima. Isto não significa substituir os Kerberos por certificados X.509v3, e sim uni-los para reduzir a carga, tanto dos usuários de sistemas e administradores como daqueles que os gerenciam.
Para atingir este objetivo , Red Hat Enterprise Linux
  • Oferece uma instância única compartilhada das bibliotecas criptográficas NSS em cada sistema operacional .
  • Distribui o Certificado Cliente de Segurança Empresarial de Sistemas (ESC) com o sistema operacional base. Os aplicativos ESC, monitoram os eventos de inserção do cartão inteligente. Caso seja detectado que o usuário inseriu um cartão inteligente, criado para ser usado com o produto de servidor do Certificado de Sistemas Red Hat Enterprise Linux, ele mostrará uma interface de usuário instruindo o usuário a como registrar este cartão inteligente.
  • Unifica o Kerberos e NSS, para os usuários que se registrarem no sistema operacional usando o cartão inteligente também obtenham uma credencial Kerberos (que permite que se registrem nos servidores de arquivo, etc.)

46.3.2. Iniciando seu Cartão Inteligente

Ante que você utilize seu cartão inteligente para se registrar em seu sistema e se beneficiar com as diversas opções de segurança que esta tecnologia oferece, você precisará fazer algumas instalações básicas e passos de configuração, como descrito abaixo:

Nota

Esta seção oferece uma ampla visão de como utilizar seu cartão inteligente. Maiores informações detalhadas estão disponíveis no Guia de Segurança do Cliente da Red Hat Certificate System Enterprise.
  1. Registre-se com seu nome e senha do Kerberos
  2. Tenha a certeza de que os pacotes nss-tools estão carregados.
  3. Faça o download e instalação dos certificados root específicos para empresas. Utilize o seguinte comando para instalar o certificado root CA:
    certutil -A -d /etc/pki/nssdb -n "root ca cert" -t "CT,C,C" \
    	-i ./ca_cert_in_base64_format.crt
  4. Verifique se você possui os seguintes RPMs instalados em seu sistema: esc, pam_pkcs11, coolkey, ifd-egate, ccid, gdm, authconfig, and authconfig-gtk.
  5. Habilite o Suporte de Registro do Cartão Inteligente
    1. On the Gnome Title Bar, select System->Administration->Authentication.
    2. Digite a senha root de sua máquina se necessário.
    3. No diálogo de Configuração de Autenticação, clique na aba Autenticação.
    4. Selecione o Habilitar o Suporte ao Cartão Inteligente
    5. Clique no botão Configurar o Cartão Inteligente... para obter o diálogo da Configuração do Cartão Inteligente e especifique as configurações solicitadas:
      • Solicitar um cartão inteligente para efetuar o registro— Desabilite a opção. Depois que você se registrar com seu cartão inteligente você pode selecionar esta opção para evitar que usuários se registrem sem um cartão inteligente.
      • Ação de Remoção do Cartão— Esta opção controla o que acontece quando você remove um cartão inteligente depois de ter se registrado. As opções disponíveis são as seguintes:
        • Bloquear — A remoção do cartão inteligente pode bloquear a tela X.
        • Ignorar — A remoção do cartão inteligente não tem efeito.
  6. Se você precisar habilitar o Protocolo de Status do Certificado Online (OCSP), abra o arquivo /etc/pam_pkcs11/pam_pkcs11.conf e procure pela seguinte linha:
    enable_ocsp = false;
    Mude este valor para verdadeiro, como segue abaixo:
    enable_ocsp = true;
  7. Registre seu cartão inteligente
  8. Se você estiver usando um cartão CAC, você também precisará aplicar estes passos a seguir:
    1. Mude para a conta root e crie um arquivo chamado /etc/pam_pkcs11/cn_map.
    2. Adicione a seguinte entrada ao arquivo cn_map:
      MY.CAC_CN.123454 -> myloginid
      onde o MY.CAC_CN.123454 é o Nome Comum em seu CAC e myloginid é seu ID de registro UNIX
  9. Sair

46.3.2.1. Resolvendo Problemas

Se você tiver problemas para colocar seu cartão inteligente em funcionamento, tente usar o seguinte comando para localizar a fonte do problema:
pklogin_finder debug
Se você executar a ferramenta pklogin_finder no modo depurador, enquanto um cartão inteligente registrado estiver conectado, ela tentará enviar informações sobre a validade dos certificados. Se a tarefa for bem sucedida, ela tentará mapear um ID de registro dos certificados que estiverem no cartão.

46.3.3. Como Funciona o Registro do Cartão Inteligente

Cartões inteligentes são registrados ao receberem um certificado apropriado, assinado por uma Autoridade de Certificado válida (CA). Isto envolve diversos passos que estão descritos a seguir.
  1. O usuário insere seus cartões inteligentes no leitor de cartão inteligente na estação de trabalho. Este evento é reconhecido pelo Cliente de Segurança Empresarial (ESC).
  2. A página de registro está disposta na área de trabalho do usuário. O usuário completa os detalhes requeridos e então, o sistema do usuário se conecta ao Sistema de Processamento de Token (TPS) e ao CA.
  3. O TPS registra o cartão inteligente usando um certificado assinado pelo CA.
Como Funciona o Registro do Cartão Inteligente
Como Funciona o Registro do Cartão Inteligente
Figura 46.4. Como Funciona o Registro do Cartão Inteligente

46.3.4. Como Funciona a Autenticação do Cartão Inteligente

Esta seção oferece uma visão geral breve do processo de autenticação ao utilizar um cartão inteligente.
  1. Quando o usuário inserir seu cartão inteligente no leitor de cartão inteligente, será reconhecido pela facilidade PAM, que solicita o PIN do usuário.
  2. O sistema então procura os certificados atuais do usuário e verifica suas validades. O certificado é então mapeado para o UID do usuário.
  3. Ele é validado pelo KDC e pelas autenticações adquiridas.
Como Funciona a Autenticação do Cartão Inteligente
Como Funciona a Autenticação do Cartão Inteligente
Figura 46.5. Como Funciona a Autenticação do Cartão Inteligente

Nota

Você não pode se autenticar com um cartão que não tenha sido registrado, mesmo que já tenha sido formatado. Você precisa se autenticar com um cartão registrado e formatado, ou então sem um cartão inteligente até que possa registrar um novo cartão.

46.3.5. Configurando o Firefox para usar o Kerberos para SSO.

Você pode configurar o Firefox para usar Kerberos para um Single Sign-on. Para que funcione corretamente, você precisa configurar seu navegador da web para enviar suas credenciais Kerberos para o KDC apropriado. A seção a seguir, descreve as mudanças de configuração e outros requerimentos para obter este resultado.
  1. Nesta barra de endereços do Firefox, digite about:config para exibir a lista de opções de configuração atual.
  2. No campo Filtro, digite negociate para restringir a lista de opções.
  3. Clique duas vezes na entrada network.negotiate-auth.trusted-uris para exibir a caixa de diálogo Digite o valor da faixa
  4. Digite o nome do domínio pelo qual queira autenticar, por exemplo, .exemplo.com.
  5. Repita o procedimento acima para a entrada network.negotiate-auth.delegation-uris usando o mesmo domínio.

    Nota

    Você pode deixar este valor em branco, pois permite a passagem do ticket do Kerberos, a qual não é requerida.
    Se você não puder visualizar estas duas opções de configuração listadas, a versão do Firefox que você possui pode ser muito antiga para suportar a autenticação Negotiate, e você deve considerar uma atualização.
Configurando o Firefox para o SSO com Kerberos
Configurando Firefox para utilizar Kerberos para SSO.
Figura 46.6. Configurando o Firefox para o SSO com Kerberos

Você agora precisa assegurar-se de que você possui os tickets do Kerberos. Em uma janela de comando, digite kinit para recuperar os tickets do Kerberos. Para obter a lista de permissões disponíveis, digite klist. A seguir veja um exemplo do resultado destes comandos:
~]$ kinit
Password for user@EXAMPLE.COM:

~]$ klist
Ticket cache: FILE:/tmp/krb5cc_10920
Default principal: user@EXAMPLE.COM

Valid starting     Expires            Service principal
10/26/06 23:47:54  10/27/06 09:47:54  krbtgt/USER.COM@USER.COM
        renew until 10/26/06 23:47:54

Kerberos 4 ticket cache: /tmp/tkt10920
klist: You have no tickets cached

46.3.5.1. Resolvendo Problemas

Se você tiver seguido os passos de configuração acima mencionados e a autenticação Negotiate ainda não estiver funcionando, você pode habilitar o login verbal do processo de autenticação. Isto pode ajudá-lo a encontrar a causa do problema. Para habilitá-lo, utilize o seguinte procedimento:
  1. Feche todas as instâncias do Firefox
  2. Abra uma janela de comando, e insira os seguintes comandos:
    export NSPR_LOG_MODULES=negotiateauth:5
    export NSPR_LOG_FILE=/tmp/moz.log
  3. Reinicie o Firefox a partir desta janela, e visite o website que você não conseguiu autenticar anteriormente. As informações serão registradas no arquivo /tmp/moz.log, e poderão lhe dar algumas pistas para a solução do problema. Por exemplo:
    -1208550944[90039d0]: entering nsNegotiateAuth::GetNextToken()
    -1208550944[90039d0]: gss_init_sec_context() failed: Miscellaneous failure
    Não foram encontrados cache de credenciais
    Isto indica que você não possui os tickets do Kerberos, e precisa executá-las kinit.
Se você conseguir executar o kinit com êxito a partir de sua máquina mas não conseguir autenticá-lo, procure por algo como isto no arquivo de registro:
-1208994096[8d683d8]: entering nsAuthGSSAPI::GetNextToken()
-1208994096[8d683d8]: gss_init_sec_context() failed: Miscellaneous failure
Server not found in Kerberos database
Isto geralmente indica um problema de configuração no Kerberos. Esteja certo de que você possui as entradas corretas na seção [domain_realm] do arquivo /etc/krb5.conf. Por exemplo:
.example.com = EXAMPLE.COM
example.com = EXAMPLE.COM
Se não aparecer nada no registro, é possível que você esteja atrás de um proxy e que o mesmo esteja apagando os cabeçalhos HTTP requeridos pela autenticação Negotiate. Para driblar este problema, você pode tentar conectar ao servidor usando o HTTPS, o que permitirá que as solicitações permaneçam intactas. Então proceda a depuração, utilizando o arquivo de registro, como descrito acima.

46.4. Módulos de Autenticação Plugáveis (Pluggable Authentication Modules - PAM)

Programas que concedem acesso de usuários à um sistema usam autenticação para verificação de identidade (ou seja, para determinar se um usuário é realmente quem ele diz ser).
Historicamente, cada programa possuía a sua própria maneira de autenticar usuários. No Red Hat Enterprise Linux, vários programas são configurados para usar um mecanismo de autenticação centralizado chamado Módulos de Autenticação Plugáveis (Pluggable Authentication Modules - PAM).
O PAM usa uma arquitetura modular plugável que permite que o administrador do sistemas tenha máxima flexibilidade ao estabelecer políticas de autenticação para o sistema.
In most situations, the default PAM configuration file for a PAM-aware application is sufficient. Sometimes, however, it is necessary to edit a PAM configuration file. Because misconfiguration of PAM can compromise system security, it is important to understand the structure of these files before making any modifications. Refer to Seção 46.4.3, “Formato do Arquivo de Configuração do PAM” for more information.

46.4.1. Vantagens do PAM

O PAM oferece as seguintes vantagens:
  • um esquema de autenticação comum que pode ser usado com uma variada gama de aplicativos.
  • flexibilidade e controle significativos da autenticação tanto para administradores de sistemas como para desenvolvedores de aplicativos.
  • uma biblioteca única e bem documentada que permite que desenvolvedores escrevam programas sem ter que criar seus próprios esquemas de autenticação.

46.4.2. Arquivos de Configuração do PAM

O diretório /etc/pam.d/ contém os arquivos de configuração do PAM para cada aplicativo que use o PAM. Em versões mais antigas do PAM, o /etc/pam.conf era usado, mas este arquivo agora está obsoleto e é usado apenas se o diretório /etc/pam.d/ não existir.

46.4.2.1. Arquivos de Serviço do PAM

Cada aplicativo, ou serviço que use o PAM possui um arquivo no diretório /etc/pam.d/. Cada arquivo neste diretório tem o mesmo nome que o serviço ao qual ele controla o acesso.
O programa que usa o PAM é responsável por definir o seu nome de serviço e instalar o seu próprio arquivo de configuração do PAM no diretório /etc/pam.d/. Por exemplo, o programa login define o seu nome de serviço como login e instala o arquivo de configuração do PAM /etc/pam.d/login.

46.4.3. Formato do Arquivo de Configuração do PAM

Cada arquivo de configuração do PAM contém um grupo de diretivas no seguinte formato:
<interface de módulo>  <sinalizador de controle>   <nome do módulo>   <argumentos do módulo>
Cada um destes elementos será explanado nas próximas seções.

46.4.3.1. Interface de Módulo

Existem atualmente quatro tipos de interfaces de módulo PAM. Cada uma destas corresponde a um aspecto diferente do processo de autorização:
  • auth — Esta interface de módulo autentica usuários. Por exemplo, ela pede por uma senha e então verifica a sua validade. Módulos com essa interface também podem estabelecer credenciais, tais como a associação à grupos, ou tickets do Kerberos.
  • account — Esta interface de módulo verifica se o acesso é permitido. Por exemplo, ela pode verificar se uma conta de usuário venceu ou se um usuário tem permissão para se autenticar durante um determinado período do dia.
  • password — Esta interface de módulo é usada para mudar as senhas dos usuários.
  • session — Esta interface de módulo configura e gerencia sessões de usuários. Módulos com esta interface também podem desempenhar tarefas adicionais que são necessárias para permitir acesso, como montar o diretório pessoal e disponibilizar a caixa de correio de um usuário.

Nota

Um módulo individual pode fornecer qualquer uma ou todas as interfaces de módulo. Por exemplo, pam_unix.so fornece todas as quatro interfaces de módulo.
Em um arquivo de configuração do PAM, o campo da interface de módulo é o primeiro a ser definido. Por exemplo, uma linha típica em uma configuração pode se parecer com o seguinte:
auth	required	pam_unix.so
Isto instrui o PAM a usar a interface auth do módulo pam_unix.so.
46.4.3.1.1. Agregando o Uso de Interfaces de Módulo
Module interface directives can be stacked, or placed upon one another, so that multiple modules are used together for one purpose. If a module's control flag uses the "sufficient" or "requisite" value (refer to Seção 46.4.3.2, “Sinalizador de Controle” for more information on these flags), then the order in which the modules are listed is important to the authentication process.
A agregação permite que um administrador exija a existência de certas condições antes de permitir que um usuário se autentique. Por exemplo, o comando reboot normalmente usa vários módulos agregados, o que pode ser verificado no seu arquivo de configuração do PAM:
~]# cat /etc/pam.d/reboot
#%PAM-1.0
auth	sufficient	pam_rootok.so
auth	required	pam_console.so
#auth	include	system-auth
account	required	pam_permit.so
  • A primeira linha é apenas um comentário e não é processada.
  • auth sufficient pam_rootok.so — Esta linha usa o módulo pam_rootok.so para determinar se o usuário atual é o root, verificando se a UID do usuário é 0. Se este teste for bem sucedido, nenhum outro módulo é consultado e o comando é executado. Se este teste falhar, o próximo módulo é consultado.
  • auth required pam_console.so — Esta linha usa o módulo pam_console.so para tentar autenticar o usuário. Se este usuário já estiver autenticado no console, o pam_console.so verifica se existe um arquivo no diretório /etc/security/console.apps/ com o mesmo nome do serviço em si (reboot). Se tal arquivo existir, a autenticação é efetuada com sucesso e o controle é passado ao próximo módulo.
  • #auth include system-auth — Esta linha é apenas um comentário e não é processada.
  • account required pam_permit.so — Esta linha usa o módulo pam_permit.so para permitir que o usuário root ou qualquer um que esteja conectado ao console possa reinicializar o sistema.

46.4.3.2. Sinalizador de Controle

Todos os módulos PAM geram um resultado de sucesso ou falha ao serem chamados. Sinalizadores de controle dizem ao PAM o que fazer com o resultado. Módulos podem ser agregados em uma certa ordem, e os sinalizadores de controle determinam a importância do sucesso ou da falha de um módulo específico em relação ao objetivo maior de efetuar a autenticação do usuário ao serviço.
Existem quatro sinalizadores de controle pré-definidos:
  • required — O resultado do módulo deve ser bem sucedido para que a autenticação continue. Se o teste falhar à esta altura, o usuário não é notificado até que os resultados dos testes de todos os módulos, que façam referência àquela interface, estejam completos.
  • requisite — O resultado do módulo deve ser bem sucedido para que a autenticação continue. Entretanto, se um teste falhar à esta altura, o usuário é notificado imediatamente com uma mensagem refletindo o primeiro teste de módulo required ou requisite que tenha falhado.
  • sufficient — O resultado do módulo é ignorado se falhar. Entretanto, se o resultado de um módulo sinalizado como sufficient é de sucesso e nenhum módulo prévio sinalizado como required falhou, então nenhum outro resultado é necessário e o usuário é autenticado ao servidor.
  • optional — O resultado do módulo é ignorado. Um módulo sinalizado como optional torna-se necessário à autenticação bem sucedida apenas quando nenhum outro módulo faz referência à interface.

Importante

A ordem na qual módulos required são chamados não é crítica. Apenas os sinalizadores de controle sufficient e requisite fazem com que a ordem torne-se importante.
Uma nova sintaxe para sinalizadores de controle que permite controle de maior precisão é agora disponível ao PAM.
A man page pam.d e a documentação do PAM, disponível no diretório /usr/share/doc/pam-<número-da-versão>/, onde <número-da-versão> é o número da versão do PAM no seu sistema, descrevem esta nova sintaxe em detalhes.

46.4.3.3. Nome do Módulo

O nome do módulo fornece ao PAM o nome do módulo plugável contendo a interface de módulo específica. Em versões mais antigas do Red Hat Enterprise Linux, o caminho completo para o módulo era fornecido no arquivo de configuração do PAM. Entretanto, desde a chegada dos sistemas multilib, os quais armazenam módulos PAM de 64 bits no diretório /lib64/security/, o nome do diretório é omitido porque o aplicativo é vinculado à versão certa do libpam, o qual é capaz de encontrar a versão correta do módulo.

46.4.3.4. Argumentos do Módulo

O PAM usa argumentos para passar informações a um módulo plugável durante a autenticação para alguns módulos.
Por exemplo, o módulo pam_userdb.so usa informações armazenadas em um arquivo Berkeley DB para autenticar o usuário. O Berkeley DB é um sistema banco de dados de código aberto incorporado a vários aplicativos. O módulo leva um argumento db de forma que o Berkeley DB saiba qual banco de dados usar para o serviço requisitado.
Veja a seguir uma linha pam_userdb.so típica em uma configuração PAM. O <caminho-para-o-arquivo> é o caminho completo para o arquivo de banco de dados Berkeley DB:
auth	required	pam_userdb.so db=<path-to-file>
Argumentos inválidos são geralmente ignorados e não afetam de maneira nenhuma o sucesso ou a falha do módulo PAM. Alguns módulos, entretanto, podem falhar ao encontrarem argumentos inválidos. A maioria dos módulos relatam erros no arquivo /var/log/secure.

46.4.4. Exemplos de Arquivos de Configuração do PAM

Veja a seguir um exemplo de arquivo de configuração do PAM para um aplicativo:
#%PAM-1.0
auth	required  pam_securetty.so
auth	required  pam_unix.so nullok
auth	required  pam_nologin.so
account	required  pam_unix.so
password	required  pam_cracklib.so retry=3
password	required  pam_unix.so shadow nullok use_authtok
session	required  pam_unix.so
  • A primeira linha é um comentário, conforme indicado pela cerquilha (#) no início da linha.
  • As linhas 2 à 4 agregam três módulos para a autenticação do login.
    auth required pam_securetty.so — Este módulo garante que se o usuário está tentando se autenticar como root, o tty ao qual o usuário está tentando se autenticar, está listado no arquivo /etc/securetty, se tal arquivo existir.
    Se o tty não estiver listado no arquivo, qualquer tentativa de autenticação como root, irá falhar com uma mensagem Autenticação Incorreta.
    auth required pam_unix.so nullok — Este módulo solicita que o usuário forneça uma senha e então verifica a senha, se ela existir, no /etc/shadow, usando a informação contida no /etc/passwd..
    In the authentication phase, the pam_unix.so module automatically detects whether the user's password is in the passwd file or the shadow file. Refer to Seção 35.6, “Senhas Shadow” for more information.
    • O argumento nullok faz com que o módulo pam_unix.so permita uma senha nula.
  • auth required pam_nologin.so — Este é o último passo da autenticação, e verifica se o arquivo /etc/nologin existe. Se existir, e o usuário não for o root, a autenticação iráfalhar.

    Nota

    Neste exemplo, todos os três módulos auth são verificados, mesmo se o primeiro módulo auth falhe. Isto impede que o usuário fique sabendo em qual estágio a sua autenticação falhou. Tal informação nas mãos de um atacante pode permitir que ele deduza mais facilmente como violar a segurança do sistema.
  • account required pam_unix.so — Este módulo executa quaisquer verificações de conta necessárias. Por exemplo, se senhas shadow foram habilitadas, a interface account do módulo pam_unix.so verifica se a conta venceu ou se o usuário não mudou sua senha dentro do período de carência permitido.
  • password required pam_cracklib.so retry=3 — Se uma senha estiver vencida, o componente de senha do módulo pam_cracklib.so solicita o fornecimento de uma nova senha. Logo após, testa a nova senha para ver se a mesma pode ser facilmente determinada por um programa de quebra de senhas baseado em um dicionário.
    • O argumento retry=3 especifica que se o teste falhar na primeira vez, o usuário tem mais duas chances para criar uma senha mais robusta.
  • password required pam_unix.so shadow nullok use_authtok — Esta linha especifica que se o programa mudar a senha do usuário, deve fazê-lo usando a interface password do módulo pam_unix.so.
    • O argumento shadow faz com que o módulo crie senhas shadow ao atualizar a senha de um usuário.
    • O argumento nullok faz com que o módulo permita que o usuário mude a sua senha a partir de uma senha em branco, caso contrário, uma senha em branco é tratada como um bloqueio para a conta.
    • O último argumento desta linha , use_authtok, fornece um bom exemplo da importância da ordem ao agregar módulos PAM. Este argumento faz com que o módulo não solicite que o usuário forneça uma nova senha. Ao invés disto, aceita qualquer senha que tenha sido registrada anteriormente por um módulo de senha. Desta forma, todas as novas senhas devem passar o teste pam_cracklib.so para senhas seguras antes de serem aceitas.
  • session required pam_unix.so — A última linha faz com que a interface session do módulo pam_unix.so gerencie a sessão. Este módulo registra o nome de usuário e o tipo de serviço em /var/log/secure no início e no fim de cada sessão. Este módulo pode ser suplementado com funcionalidades adicionais ao ser agregado a outros módulos de sessão.

46.4.5. Criando Módulos PAM

Você pode criar ou adicionar novos módulos PAM a qualquer momento para serem usados por aplicativos que utilizem o PAM.
Por exemplo, um desenvolvedor pode criar um método de criação de senhas de uso único e escrever um módulo PAM para suportá-lo. Programas que usem o PAM podem usar o módulo e método de senha novos imediatamente, sem serem recompilados ou modificados de qualquer maneira.
Isto permite que desenvolvedores e administradores de sistema usem e testem combinações de métodos de autenticação para programas diferentes sem precisar recompilá-los.
A documentação sobre como escrever módulos encontra-se no diretório /usr/share/doc/pam-<número-da-versão>/, onde <número-da-versão> é o número da versão do PAM instalado no seu sistema.

46.4.6. O PAM e o Caching de Credenciais Administrativas

Uma série de ferramentas administrativas gráficas do Red Hat Enterprise Linux permitem que usuários tenham privilégios elevados por até cinco minutos usando o módulo pam_timestamp.so. É importante entender como este mecanismo funciona, uma vez que se um usuário abandona um terminal enquanto o pam_timestamp.so estiver em funcionamento, deixa a máquina vulnerável à manipulação por parte de qualquer um que tenha acesso físico ao console.
No esquema de carimbo de data e hora (timestamp) do PAM, a interface gráfica do aplicativo administrativo solicita que o usuário forneça a senha do root ao ser lançado. Uma vez que o usuário tenha sido autenticado, o módulo pam_timestamp.so cria um arquivo de carimbo de data e hora. Por padrão, este arquivo é criado no diretório /var/run/sudo/. Se o arquivo de carimbo de data e hora já existir, programas administrativos gráficos não solicitam uma senha. Ao invés disto, o módulo pam_timestamp.so atualiza o arquivo de carimbo de data e hora, reservando mais cinco minutos de acesso administrativo inquestionável ao usuário.
Você pode verificar o estado atual do arquivo de carimbo de data e hora inspecionando o arquivo /var/run/sudo/<user>. Para a área de trabalho, o arquivo relevante é o unknown:root. Se o mesmo estiver presente e o seu carimbo de data e hora tiver sido feito há menos do que cinco minutos, as credencias são válidas.
A existência do arquivo de carimbo de data e hora é indicada através de um ícone de autenticação, o qual aparece na área de notificação do painel.
O Ícone de Autenticação
Ilustração do ícone de autenticação.
Figura 46.7. O Ícone de Autenticação

46.4.6.1. Removendo o Arquivo de Carimbo de Data e Hora

Antes de abandonar um console onde um carimbo de data e hora do PAM esteja ativo, é recomendável que o arquivo de carimbo de data e hora seja destruído. Para fazer isto em um ambiente gráfico, clique no ícone de autenticação no painel. Isto faz com que uma caixa de diálogo apareça. Clique no botão Desistir da Autorização para destruir o arquivo de carimbo de data e hora ativo.
Diálogo Cancelamento de Autenticação
Ilustração da caixa de diálogo de cancelamento de autenticação.
Figura 46.8. Diálogo Cancelamento de Autenticação

Note o seguinte em relação ao arquivo de carimbo de data e hora do PAM:
  • Se você estiver autenticado no sistema remotamente usando o ssh, use o comando /sbin/pam_timestamp_check -k root para destruir o arquivo de carimbo de data e hora.
  • Você precisa executar o comando /sbin/pam_timestamp_check -k root da mesma janela de terminal de onde o aplicativo com privilégios foi lançado.
  • Você deve estar autenticado como o usuário que originalmente invocou o módulo pam_timestamp.so para poder usar o comando /sbin/pam_timestamp_check -k. Não autentique-se como root para usar este comando.
  • Se você quiser terminar com as credencias na área de trabalho (sem usar o botão Desistir da Autorização), use o seguinte comando:
    pam_timestamp_check -k root </dev/null >/dev/null 2>/dev/null
    Se este comando não for executado, apenas as credenciais (se existirem) do pty onde você rodar o comando serão removidas.
Consulte a página man do pam_timestamp_check para maiores informações sobre a destruição de um arquivo de carimbo de data e hora usando o pam_timestamp_check.

46.4.6.2. Diretivas Comuns do pam_timestamp

O módulo pam_timestamp.so aceita várias diretivas. Veja a seguir as duas opções mais utilizadas:
  • timestamp_timeout — Especifica o período (em segundos) durante o qual o arquivo de carimbo de data e hora é válido. O valor padrão é 300 (cinco minutos).
  • timestampdir — Especifica o diretório no qual o arquivo de carimbo de data e hora é armazenado. O valor padrão é /var/run/sudo/.
Refer to Seção 46.4.8.1, “Documentação Instalada” for more information about controlling the pam_timestamp.so module.

46.4.7. O PAM e a Propriedade de Dispositivos

No Red Hat Enterprise Linux, o primeiro usuário que se autenticar no console físico da máquina pode manipular certos dispositivos e executar certas tarefas normalmente reservadas ao usuário root. Isto é controlado por um módulo PAM chamado pam_console.so.

46.4.7.1. Propriedade de Dispositivos

Quando um usuário se autentica em um sistema Red Hat Enterprise Linux, o módulo pam_console.so é invocado pelos programas login ou pelos programas gráficos de autenticação, gdm, kdm, e xdm. Se este usuário for o primeiro a se autenticar no console físico — também chamado de usuário do console — o módulo dá ao usuário a propriedade sobre uma gama de dispositivos normalmente de propriedade do root. O usuário do console torna-se o dono destes dispositivos até que a última sessão local para aquele usuário termine. Após este usuário ter feito o logoff, a propriedade dos dispositivos reverte novamente para o usuário root.
Os dispositivos afetados incluem, entre outros, placas de som, e drives de disquete e de CD-ROM.
Esta facilidade permite que um usuário local manipule estes dispositivos sem obter acesso root, simplificando assim tarefas comuns para o usuário do console.
Você pode modificar a lista de dispositivos controlados pelo pam_console.so editando os seguintes arquivos:
  • /etc/security/console.perms
  • /etc/security/console.perms.d/50-default.perms
Você pode mudar a permissão de dispositivos que não estejam listados nos arquivos acima, ou sobrescrever os padrões especificados. Ao invés de modificar o arquivo 50-default.perms, você deve criar um novo arquivo (por exemplo, xx-name.perms) e introduzir as modificações necessárias. O nome do novo arquivo padrão deve iniciar com um número maior do que 50 (por exemplo, 51-default.perms). Isto sobrescreverá os valores padrão no arquivo 50-default.perms.

Atenção

Se o arquivo de configuração do gerenciador de tela gdm, kdm, ou xdm foi alterado para permitir que usuários remotos se autentiquem e o host estiver configurado para rodar em nível de execução 5, é recomendável mudar as diretivas <console> e <xconsole> no /etc/security/console.perms para os seguintes valores:
<console>=tty[0-9][0-9]* vc/[0-9][0-9]* :0\.[0-9] :0
<xconsole>=:0\.[0-9] :0
Isto previne que usuários remotos ganhem acesso a dispositivos e aplicativos restritos na máquina.
Se o arquivo de configuração do gerenciador de tela gdm, kdm, ou xdm foi alterado para permitir que usuários remotos se autentiquem e o host estiver configurado para rodar em um nível de execução diferente de 5, é recomendável remover a diretiva <xconsole> e mudar a diretiva <console> para o seguinte valor:
<console>=tty[0-9][0-9]* vc/[0-9][0-9]*

46.4.7.2. Acesso a Aplicativos

O usuário do console também tem acesso a certos programas configurados no diretório /etc/security/console.apps/.
Este diretório contém arquivos de configuração que possibilitam que o usuário do console possa rodar certos aplicativos em /sbin e /usr/sbin.
Estes arquivos de configuração têm o mesmo nome dos aplicativos que eles configuram.
Um notável grupo de aplicativos aos quais o usuário do console tem acesso são três programas usados para desligar ou reinicializar o sistema:
  • /sbin/halt
  • /sbin/reboot
  • /sbin/poweroff
Uma vez que estes aplicativos usam o PAM, eles fazem com que uma chamada ao módulo pam_console.so seja obrigatória para o seu uso.
Refer to Seção 46.4.8.1, “Documentação Instalada” for more information.

46.4.8. Recursos Adicionais

Os seguintes recursos contém informações adicionais sobre a utilização do PAM. Além destes recursos, leia os arquivos de configuração do PAM do sistema para entender melhor a maneira como são estruturados.

46.4.8.1. Documentação Instalada

  • Páginas man relacionadas ao PAM — Existem várias páginas man para os diversos aplicativos e arquivos de configuração envolvidos com o PAM. Veja a seguir uma lista contendo algumas das páginas man mais importantes.
    Arquivos de Configuração
    • pam — Boas informações introdutórias sobre o PAM, incluindo a estrutura e a finalidade dos arquivos de configuração do PAM.
      Note que esta página man discute ambos tanto o /etc/pam.conf como arquivos de configuração individuais no diretório /etc/pam.d/. Por padrão, o Red Hat Enterprise Linux usa os arquivos de configuração individuais no diretório /etc/pam.d/, ignorando o /etc/pam.conf, caso exista.
    • pam_console — Descreve a finalidade do módulo pam_console.so, assim como a sintaxe adequada para uma entrada num arquivo de configuração do PAM.
    • console.apps — Descreve o formato e as opções disponíveis para o arquivo de configuração /etc/security/console.apps, o qual define quais aplicativos são acessíveis pelo usuário do console atribuído pelo PAM.
    • console.perms — Descreve o formato e as opções disponíveis par o arquivo de configuração /etc/security/console.perms, o qual especifica as permissões do usuário do console atribuídas pelo PAM.
    • pam_timestamp — Descreve o módulo pam_timestamp.so.
  • /usr/share/doc/pam-<número-da-versão> — Contém um System Administrator's Guide (Guia do Administrador de Sistemas), um Module Writer's Manual (Manual do Autor de Módulos), e o Application Developer's Manual (Manual do Desenvolvedor de Aplicativos), assim como uma cópia da norma DCE-RFC 86.0 do PAM, onde <número-da-versão> é o número da versão do PAM.
  • /usr/share/doc/pam-<número-da-versão>/txts/README.pam_timestamp — Contém informações sobre o módulo PAM pam_timestamp.so, onde <número-da-versão> é o número da versão do PAM.

46.4.8.2. Sites Úteis

  • http://www.kernel.org/pub/linux/libs/pam/ — O site de distribuição principal para o projeto Linux-PAM, contendo informações sobre vários módulos PAM, uma FAQ, e documentações adicionais do PAM.

    Nota

    A documentação do site acima aplica-se ao último lançamento do PAM e pode não ser 100% precisa em relação à versão do PAM incluída no Red Hat Enterprise Linux.

46.5. TCP Wrappers e xinetd

O controle de acesso a serviços de rede é uma das tarefas de segurança mais importantes para um administrador de servidor. O Red Hat Enterprise Linux oferece várias ferramentas para esta finalidade. Por exemplo, um firewall baseado no iptables filtra pacotes de rede não desejáveis na stack de rede do kernel. O TCP Wrappers adiciona uma camada de proteção adicional aos serviços de rede que o utilizam, definindo quais hosts tem ou não têm a permissão para conectar a serviços de rede "embrulhados" (wrapped). Um exemplo de tal serviço de rede embrulhado é o super servidor xinetd. Este serviço é chamado de super servidor porque ele controla conexões a um subconjunto de serviços de rede e refina ainda mais o controle de acesso.
Figura 46.9, “Controle de Acesso a Serviços de Rede” is a basic illustration of how these tools work together to protect network services.
Controle de Acesso a Serviços de Rede
Figura A: Fluxograma do Controle de Acesso a Serviços de Rede
Figura 46.9. Controle de Acesso a Serviços de Rede

This chapter focuses on the role of TCP Wrappers and xinetd in controlling access to network services and reviews how these tools can be used to enhance both logging and utilization management. Refer to Seção 46.9, “IPTables” for information about using firewalls with iptables.

46.5.1. TCP Wrappers

O pacote TCP Wrappers (tcp_wrappers) faz parte da instalação padrão e oferece controle de de acesso a serviços de rede baseado no host. O componente mais importante do pacote é a biblioteca /usr/lib/libwrap.a. Em termos gerais, um serviço que use o TCP Wrappers é um que foi compilado com vinculação à biblioteca libwrap.a.
Quando uma tentativa de conexão é feita a um serviço que use o TCP Wrappers, o serviço primeiro examina os arquivos de acesso do host (/etc/hosts.allow e /etc/hosts.deny) para determinar se um cliente tem permissão para conectar. Na maioria dos casos, o serviço então usa o daemon syslog (syslogd) para escrever o nome do cliente fazendo o pedido e o serviço requisitado em /var/log/secure ou /var/log/messages.
Se um cliente tiver permissão para conectar, o TCP Wrappers passa o controle da conexão ao serviço que fez o pedido e não participa mais na comunicação entre o cliente e o servidor.
Além de controle de acesso e registro, o TCP Wrappers pode executar comandos para interagir com o cliente antes de negar ou passar o controle da conexão ao serviço de rede requisitado.
A maioria dos serviços de rede do Red Hat Enterprise Linux são vinculados à biblioteca libwrap.a porque o TCP Wrappers é uma adição valiosa ao arsenal de segurança de qualquer administrador de sistemas. Algumas destas aplicações incluem o /usr/sbin/sshd, o /usr/sbin/sendmail, e o /usr/sbin/xinetd.

Nota

Para determinar se um binário de serviço de rede está vinculado à libwrap.a, digite o seguinte comando como usuário root.
ldd <binary-name> | grep libwrap
Substitua <nome-do-binário> pelo nome do binário de serviço de rede.
Se o comando não retornar nenhuma saída, o serviço de rede não está vinculado à libwrap.a.
O exemplo a seguir indica que o /usr/sbin/sshd está vinculado à libwrap.a:
~]# ldd /usr/sbin/sshd | grep libwrap
        libwrap.so.0 => /usr/lib/libwrap.so.0 (0x00655000)
~]#

46.5.1.1. Vantagens do TCP Wrappers

O TCP Wrappers oferece as seguintes vantagens em relação à outras técnicas de controle de serviços de rede:
  • Transparência tanto para o cliente como para o serviço de rede embrulhado — O cliente que está conectando e o serviço de rede embrulhado não estão cientes de que o TCP Wrappers está sendo usado. Usuários legítimos são autenticados e conectados ao serviço requisitado, enquanto conexões a partir de clientes banidos falham.
  • Gerenciamento centralizado de vários protocolos — O TCP Wrappers opera independentemente dos serviços de rede que protege, permitindo que vários aplicativos de servidor compartilhem um grupo comum de arquivos de configuração de controle de acesso, conseqüentemente facilitando o gerenciamento.

46.5.2. Arquivos de Configuração do TCP Wrappers

Para determinar se um cliente tem permissão para se conectar à um serviço, o TCP Wrappers consulta os dois arquivos seguintes, os quais são normalmente chamados de arquivos de acesso hosts:
  • /etc/hosts.allow
  • /etc/hosts.deny
Um serviço que use o TCP Wrappers executa os seguintes passos ao receber um pedido de um cliente:
  1. Consulta o /etc/hosts.allow. — O serviço usuário do TCP Wrappers analisa o arquivo /etc/hosts.allow seqüencialmente e aplica a primeira regra especificada para aquele serviço. Se encontra uma regra correspondente, permite a conexão. Caso contrário, continua com o próximo passo.
  2. Consulta o /etc/hosts.deny. — O serviço TCP Wrappers analisa o arquivo /etc/hosts.deny seqüencialmente. Se encontra uma regra correspondente, nega a conexão. Caso contrário, permite acesso ao serviço.
É importante considerar os seguintes pontos importantes ao contemplar o uso do TCP Wrappers para proteger serviços de rede:
  • As regras de acesso em hosts.allow tem precedência sobre as regras especificadas em hosts.deny porque elas são aplicadas primeiro. Conseqüentemente, se o acesso a um serviço for permitido em hosts.allow, uma regra negando o acesso aquele mesmo serviço em hosts.deny é ignorada.
  • As regras de cada arquivo são lidas de cima para baixo, e a primeira regra correspondente a um serviço é a única a ser aplicada. A ordem das regras é extremamente importante.
  • O acesso ao serviço é permitido se nenhuma regra para o serviço for encontrada em qualquer um dos dois arquivos, ou se nenhum dos dois arquivos existir.
  • Serviços usuários do TCP Wrappers não fazem o cache das regras dos arquivos de acesso hosts, portanto quaisquer mudanças ao hosts.allow ou hosts.deny tem efeito imediato sem precisar reiniciar serviços de rede.

Atenção

Se a última linha de um arquivo de acesso hosts não é um caractere de mudança de linha (criado pela tecla Enter), a última regra do arquivo falha e uma mensagem de erro é registrada em /var/log/messages ou /var/log/secure. Isto também aplica-se à regras que usem mais de uma linha sem usar o caractere de barra invertida. O seguinte exemplo ilustra a parte relevante de uma mensagem de registro para a falha de uma regra devido a qualquer uma destas circunstâncias.
warning: /etc/hosts.allow, line 20: missing newline or line too long

46.5.2.1. Formatando Regras de Acesso

O formato do /etc/hosts.allow e do /etc/hosts.deny é idêntico. Cada regra deve ser especificada na sua própria linha. Linhas em branco ou que comecem com uma cerquilha (#) são ignoradas.
Cada regra usa o seguinte formato básico para controlar o acesso aos serviços de rede:
<lista-de-daemons>: <lista-de-clientes> [: <opção>: <opção>: ...]
  • <daemon list> — A comma-separated list of process names (not service names) or the ALL wildcard. The daemon list also accepts operators (refer to Seção 46.5.2.1.4, “Operadores”) to allow greater flexibility.
  • <client list> — A comma-separated list of hostnames, host IP addresses, special patterns, or wildcards which identify the hosts affected by the rule. The client list also accepts operators listed in Seção 46.5.2.1.4, “Operadores” to allow greater flexibility.
  • <opção> — Uma ação opcional, ou lista de ações opcionais separadas por vírgulas, executadas quando a regra é invocada. Campos de opção suportam a expansão, lançam comandos shell, permitem ou negam o acesso, e alteram o comportamento da autenticação.

Nota

Mais informações sobre os termos específicos discutidos acima podem ser encontradas neste guia nas seguintes localizações:
Veja a seguir uma regra básica de acesso a hosts:
vsftpd : .example.com
Esta regra faz com que o TCP Wrappers procure por conexões ao daemon do FTP (vsftpd) a partir de qualquer host no domínio example.com. Se esta regra aparece no hosts.allow, a conexão é aceita. Se esta regra aparece no hosts.deny, a conexão é rejeitada.
A próxima regra de acesso a hosts é mais complexa e usa dois campos de opção:
sshd : .example.com  \ : spawn /bin/echo `/bin/date` access denied>>/var/log/sshd.log \ : deny
Note que cada campo de opção é precedido pela barra invertida (\). O uso da barra invertida previne a falha da regra devido ao comprimento.
This sample rule states that if a connection to the SSH daemon (sshd) is attempted from a host in the example.com domain, execute the echo command to append the attempt to a special log file, and deny the connection. Because the optional deny directive is used, this line denies access even if it appears in the hosts.allow file. Refer to Seção 46.5.2.2, “Campos de Opção” for a more detailed look at available options.
46.5.2.1.1. Curingas
Curingas permitem que o TCP Wrappers faça a correspondência de grupos de daemons ou hosts mais facilmente. Eles são usados mais freqüentemente no campo da lista de clientes de regras de acesso.
Os seguintes curingas estão disponíveis:
  • ALL — Corresponde a tudo. Pode ser usado tanto com a lista de daemons como com a lista de clientes.
  • LOCAL — Faz a correspondência de qualquer host que não contenha um ponto (.), como, por exemplo, localhost.
  • KNOWN — Faz a correspondência de qualquer host onde o nome e endereço do host ou o usuário são conhecidos.
  • UNKNOWN — Faz a correspondência de qualquer host onde o nome ou endereço do host são desconhecidos, ou o usuário é desconhecido.
  • PARANOID — Faz a correspondência de qualquer host onde o nome de host não corresponde ao endereço do host.

Atenção

Os curingas KNOWN, UNKNOWN, e PARANOID devem ser usados com cuidado porque eles baseiam-se na operação correta de um servidor DNS para operar corretamente. Qualquer interrupção à resolução de nomes pode impedir que usuários legítimos ganhem acesso a um serviço.
46.5.2.1.2. Padrões
Padrões podem ser usados no campo de clientes de regras de acesso para especificar grupos de hosts clientes mais precisamente.
Veja a seguir uma lista de padrões normalmente usados no campo de clientes:
  • Nome de host começando com um ponto (.) — Um ponto no começo de um nome de host faz a correspondência de todos os hosts compartilhando os componentes listados do nome. O seguinte exemplo aplica-se a qualquer host no domínio example.com:
    ALL : .example.com
  • Endereço IP terminando com um ponto (.) — Um ponto no fim de um endereço IP faz a correspondência de todos os hosts compartilhando os grupos numéricos iniciais de um endereço IP. O seguinte exemplo aplica-se a qualquer host dentro da rede 192.168.x.x:
    ALL : 192.168.
  • Um par endereço IP/máscara de rede — Expressões de máscara de rede também podem ser usadas como um padrão para controlar o acesso grupo específico de endereços IP. O seguinte exemplo aplica-se a qualquer host num intervalo de endereço de 192.168.0.0 a 192.168.1.255:
    ALL : 192.168.0.0/255.255.254.0

    Importante

    As declarações de endereço/comprimento de prefixo (prefixlen), (notação CIDR) não são suportadas no espaço de endereços IPv4. Apenas regras IPv6 podem usar este formato.
  • Um par [IPv6 address]/prefixlen — Pares [net]/prefixlen também podem ser usados como um padrão para controlar o acesso a um grupo específico de endereços IPv6. O seguinte exemplo aplica-se a qualquer host num intervalo de endereço de 3ffe:505:2:1:: a 3ffe:505:2:1:ffff:ffff:ffff:ffff:
    ALL : [3ffe:505:2:1::]/64
  • O asterisco (*) — Asteriscos podem ser usados para a correspondência de grupos inteiros de nomes de hosts ou endereços IP, sob a condição de que eles não sejam misturados em uma lista de clientes contendo outros tipos de padrões. O seguinte exemplo aplica-se a qualquer host dentro do domínio example.com:
    ALL : *.example.com
  • A barra (/) — Se uma lista de clientes começa com uma barra, é tratada como um nome de arquivo. Isto é útil se for necessário usar regras especificando um grande número de hosts. O seguinte exemplo encaminha o TCP Wrappers ao arquivo /etc/telnet.hosts para todas as conexões Telnet:
    in.telnetd : /etc/telnet.hosts
Outros padrões menos usados também são aceitos pelo TCP Wrappers. Consulte a página man do hosts_access(5) para maiores informações.

Atenção

Tenha muito cuidado ao usar nomes de host e nomes de domínio. Atacantes podem usar uma variedade de truques para driblar a resolução de nomes precisa. Além disso, a interrupção ao serviço de DNS previne que mesmo cliente autorizados possam usar serviços de rede. Por estas razões, é melhor usar endereços IP sempre que for possível.
46.5.2.1.3. Portmap e o TCP Wrappers
A implementação do TCP Wrappers pelo portmap não suporta a busca por hosts, o que significa que o portmap não pode usar nomes de hosts para identificar hosts. Conseqüentemente, regras de controle de acesso para o portmap no hosts.allow ou no hosts.deny devem usar endereços IP, ou a palavra-chave ALL para a especificação de hosts.
Mudanças às regras de controle de acesso do portmap podem não entrar em vigor imediatamente. Talvez você precise reiniciar o serviço portmap.
Serviços amplamente utilizados, como o NIS e o NFS, dependem do portmap para operar. Portanto, esteja ciente destas limitações.
46.5.2.1.4. Operadores
No momento, regras de controle de acesso aceitam um operador, EXCEPT. Este operador pode ser usado tanto na lista de daemons como na lista de clientes de uma regra.
O operador EXCEPT permite exceções específicas para correspondências mais genéricas na mesma regra.
No seguinte exemplo de um arquivo hosts.allow, todos os hosts example.com, exceto cracker.example.com, têm permissão para se conectar a todos os serviços:
ALL: .example.com EXCEPT cracker.example.com
Em outro exemplo de um arquivo hosts.allow, clientes da rede 192.168.0.x podem usar todos os serviços, exceto o FTP:
ALL EXCEPT vsftpd: 192.168.0.

Nota

Em termos organizacionais, é normalmente mais fácil evitar o uso de operadores EXCEPT. Isto permite que outros administradores inspecionem os arquivos apropriados para determinar quais hosts tem ou não permissão para acessar serviços sem ter que lidar com operadores EXCEPT.

46.5.2.2. Campos de Opção

Além das regras básicas que permitem e negam acesso, a implementação do TCP Wrappers no Red Hat Enterprise Linux suporta extensões à linguagem de controle de acesso através de campos de opção. O uso de campos de opção em regras de acesso de hosts permite que administradores de sistemas executem uma variedade de tarefas, como alterar o comportamento dos registros, consolidar o controle de acesso, e lançar comandos do shell.
46.5.2.2.1. Registros
Campos de opção permitem que os administradores alterem com facilidade o alvo de registro e o nível de prioridade de uma regra usando a diretiva severity.
No exemplo a seguir, conexões ao daemon do SSH a partir de qualquer host no domínio example.com são registradas no alvo padrão authpriv syslog (uma vez que nenhum valor de alvo é especificado) com prioridade emerg:
sshd : .example.com : severity emerg
Também é possível especificar um alvo usando a opção severity. O seguinte exemplo registra qualquer tentativa de conexão SSH a partir de hosts no domínio example.com no alvo local0 com prioridade alert:
sshd : .example.com : severity local0.alert

Nota

Na prática, este exemplo não funciona até que o daemon syslog syslogd) seja configurado para registrar no alvo local0. Consulte a página man syslog.conf para informações sobre configuração de alvos de registro personalizados.
46.5.2.2.2. Controle de Acesso
Campos de opção também permitem que administradores permitam ou neguem hosts explicitamente em uma única regra através da adição das diretivas allow ou deny como opção final.
Por exemplo, as duas regras seguintes permitem conexões SSH a partir de client-1.example.com, mas negam conexões a partir de client-2.example.com:
sshd : client-1.example.com : allow
sshd : client-2.example.com : deny
Ao possibilitar o controle de acesso regra por regra, o campo de opção permite que administradores consolidem todas as regras de acesso em um único arquivo: ou hosts.allow ou hosts.deny. Alguns administradores consideram isto uma maneira mais fácil de organizar regras de acesso.
46.5.2.2.3. Comandos do Shell
Campos de opção permitem que regras de acesso lancem comandos do shell através das seguintes duas diretivas:
  • spawn — Lança um comando do shell como um processo filho. Esta diretiva pode executar tarefas como usar o /usr/sbin/safe_finger para obter mais informações sobre o cliente fazendo o pedido ou criar arquivos de registro especiais usando o comando echo.
    No seguinte exemplo, clientes tentando acessar serviços Telnet a partir do domínio example.com são silenciosamente registrados em um arquivo especial:
    in.telnetd : .example.com \
    	: spawn /bin/echo `/bin/date` from %h>>/var/log/telnet.log \
    	: allow
  • twist — Substitui o serviço requisitado por um comando específico. Esta diretiva é normalmente usada para estabelecer armadilhas para invasores (também chamadas de "potes de mel"), e também pode ser usada para enviar mensagens a clientes que estejam se conectando. A diretiva twist deve aparecer no final da linha da regra.
    No exemplo a seguir, clientes tentando acessar serviços de FTP a partir do domínio example.com recebem mensagens criadas com o comando echo:
    vsftpd : .example.com \
    	: twist /bin/echo "421 This domain has been black-listed. Access denied!"
Para maiores informações sobre opções de comandos do shell, consulte a página man hosts_options.
46.5.2.2.4. Expansões
Expansões. quando usadas com as diretivas spawn e twist, oferecem informações sobre o cliente, o servidor, e os processos envolvidos.
A lista a seguir apresenta as expansões suportadas:
  • %a — Retorna o endereço IP do cliente.
  • %A — Retorna o endereço IP do servidor.
  • %c — Retorna uma variedade de informações sobre clientes, como o nome de usuário e o nome de host, ou o nome de usuário e o endereço IP.
  • %d — Retorna o nome do processo do daemon.
  • %h — Retorna o nome de host do cliente (ou endereço IP, caso o nome de host não esteja disponível).
  • %H — Retorna o nome de host do servidor (ou endereço IP, caso o nome de host não esteja disponível).
  • %n — Retorna o nome de host do cliente. Caso não esteja disponível, retorna unknown. Se o nome e endereço de host do cliente não corresponderem, retorna paranoid.
  • %N — Retorna o nome de host do servidor. Caso não esteja disponível, retorna unknown. Se o nome e endereço de host do servidor não corresponderem, retorna paranoid.
  • %p — Retorna o ID do processo do daemon.
  • %s — Retorna vários tipos de informações sobre o servidor, como o processo do daemon e o host ou endereço IP do servidor.
  • %u — Retorna o nome de usuário do cliente. Caso não esteja disponível, retorna unknown.
No exemplo a seguir, a regra usa uma expansão junto com o comando spawn para identificar o host cliente em um arquivo personalizado.
Quando conexões ao daemon do SSH (sshd) são tentadas a partir de um host no domínio example.com, o comando echo é executado para registrar a tentativa, incluindo o nome de host (obtido através do uso da expansão %h), em um arquivo especial:
sshd : .example.com  \
	: spawn /bin/echo `/bin/date` access denied to %h>>/var/log/sshd.log \
	: deny
De maneira semelhante, expansões podem ser usadas para personalizar mensagens enviadas de volta ao cliente. No exemplo seguinte, clientes que estejam tentando acessar serviços de FTP a partir do domínio example.com são informados que eles foram banidos do servidor.
vsftpd : .example.com \
: twist /bin/echo "421 %h has been banned from this server!"
Para uma explicação completa sobre todos as expansões disponíveis, bem como opções adicionais de controle de acesso, consulte a seção 5 das páginas man do hosts_access (man 5 hosts_access) e a página man do hosts_options.
Refer to Seção 46.5.5, “Recursos Adicionais” for more information about TCP Wrappers.

46.5.3. xinetd

O daemon xinetd é um super serviço usuário do TCP Wrappers que controla o acesso a um subconjunto de serviços de rede populares, incluindo o FTP, o IMAP, e o Telnet. O xinetd também oferece opções de configuração específicas a serviços para o controle de acesso, registro aprimorado, vinculação, redirecionamento, e controle de utilização de recursos.
Quando um cliente tenta conectar a um serviço de rede controlado pelo xinetd, o super serviço recebe o pedido e verifica a existência de quaisquer regras de controle de acesso do TCP Wrappers .
Se o acesso é permitido, o xinetd verifica se a conexão é permitida sob as suas próprias regras de acesso para o serviço em questão. O xinetd também verifica se o serviço pode ter mais recursos alocados e certifica-se de que o serviço não está violando nenhuma regra definida.
Se todas estas condições forem satisfeitas (ou seja, o acesso é permitido ao serviço, o serviço não atingiu seus limites de recursos, e o serviço não está violando nenhuma regra definida), o xinetd então inicia uma instância do serviço e passa o controle da conexão para o mesmo. Após a conexão ter sido estabelecida, o xinetd não participa mais da comunicação entre o cliente e o servidor.

46.5.4. Arquivos de Configuração do xinetd

Os arquivos de configuração do xinetd são os seguintes:
  • /etc/xinetd.conf — O arquivo de configuração global do xinetd.
  • /etc/xinetd.d/ — O diretório contendo todos os arquivos de serviços específicos.

46.5.4.1. O arquivo /etc/xinetd.conf

O arquivo /etc/xinetd.conf contém opções de configuração gerais que afetam todos os serviços sob o controle do xinetd. É lido quando o serviço xinetd é iniciado pela primeira vez, portanto, para que configurações entrem em vigor, você precisa reiniciar o serviço xinetd. Veja a seguir um exemplo de arquivo /etc/xinetd.conf:
defaults
{
         instances               = 60
	 log_type                = SYSLOG	authpriv
	 log_on_success          = HOST PID
	 log_on_failure          = HOST
	 cps                     = 25 30
}
includedir /etc/xinetd.d
Estas linhas controlam os seguintes aspectos do xinetd:
  • instances — Especifica o número máximo de pedidos simultâneos que o xinetd pode processar.
  • log_type — Configura xinetd para que use o alvo de registro authpriv, o qual escreve entradas de registro no arquivo /var/log/secure. A inclusão de uma diretiva como FILE /var/log/xinetdlog criaria um arquivo de registro personalizado chamado xinetdlog no diretório /var/log/.
  • log_on_success — Configura o xinetd para que registre tentativas de conexão bem-sucedidas. Por padrão, o endereço IP do host remoto e o ID do processo do servidor processando o pedido são registrados.
  • log_on_failure — Configura o xinetd para que registre tentativas de conexão mal-sucedidas ou recusadas.
  • cps — Configura o xinetd para que permita não mais do que 25 por segundo para qualquer serviço. Se este limite for excedido, o serviço é aposentado por 30 seconds.
  • includedir /etc/xinetd.d/ — Includes options declared in the service-specific configuration files located in the /etc/xinetd.d/ directory. Refer to Seção 46.5.4.2, “O Diretório /etc/xinetd.d/” for more information.

Nota

Often, both the log_on_success and log_on_failure settings in /etc/xinetd.conf are further modified in the service-specific configuration files. More information may therefore appear in a given service's log file than the /etc/xinetd.conf file may indicate. Refer to Seção 46.5.4.3.1, “Opções de Registro” for further information.

46.5.4.2. O Diretório /etc/xinetd.d/

O diretório /etc/xinetd.d/ contém os arquivos de configuração para cada serviço gerenciado pelo xinetd, e os nomes dos arquivos relacionados ao serviço. Assim como o xinetd.conf, este diretório é lido apenas quando o serviço xinetd é iniciado. Para que quaisquer alterações sejam efetivadas, o administrador deve reiniciar o serviço xinetd.
O formato dos arquivos no diretório /etc/xinetd.d/ usa a mesma convenção do que o /etc/xinetd.conf. A razão principal pela qual a configuração de cada serviço é armazenada em uma arquivo separado é para facilitar a personalização e reduzir o risco de interferência na configuração de outros serviços.
Para entender como estes arquivos são estruturados, considere o arquivo /etc/xinetd.d/krb5-telnet:
service telnet
{
         flags           = REUSE
	 socket_type     = stream
	 wait            = no
	 user            = root
	 server          = /usr/kerberos/sbin/telnetd
	 log_on_failure  += USERID
	 disable         = yes
}
Estas linhas controlam vários aspectos do serviço telnet:
  • service — Especifica o nome do serviço, normalmente um dos nomes listados no arquivo /etc/services.
  • flags — Estabelece uma série de atributos para a conexão. O REUSE informa ao xinetd para reutilizar o soquete para uma conexão Telnet.

    Nota

    O sinalizador REUSE é obsoleto, uma vez que todos os serviços agora o usam implicitamente..
  • socket_type — Estabelece o tipo de soquete de rede para stream.
  • wait — Especfica se o serviço é single-thread (yes) ou multi-thread (no).
  • user — Especifica o ID do usuário sob o qual o processo está rodando.
  • server — Especifica qual executável binário deve ser lançado.
  • log_on_failure — Especifica os parâmetros de registro para log_on_failure além daquela já definidos em xinetd.conf.
  • disable — Especifica se o serviço está desabilitado (yes) ou habilitado (no).
Consulte a página man do xinetd.conf para mais informações sobre o uso destas opções.

46.5.4.3. Alterando os Arquivos de Configuração do xinetd

Uma série de diretivas está disponível para os serviços protegidos pelo xinetd. Esta seção destaca algumas das opções mais usadas.
46.5.4.3.1. Opções de Registro
As seguintes opções de registro estão disponíveis para o /etc/xinetd.conf e para os arquivos de configuração de serviço específicos no diretório /etc/xinetd.d/.
Veja a seguir a lista de algumas das opções de registro mais usadas:
  • ATTEMPT — Registra o fato de que uma tentativa mal-sucedida foi feita (log_on_failure).
  • DURATION — Registra a duração do uso do serviço é usado por um sistema remoto (log_on_success).
  • EXIT — Registra o estado de saída ou sinal de término do serviço (log_on_success).
  • HOST — Registra o endereço IP do host remoto (log_on_failure e log_on_success).
  • PID — Registra o ID do processo do servidor recebendo o pedido (log_on_success).
  • USERID — Registra o usuário remoto usando o método definido no RFC 1413 para serviços multi-thread de fluxo (log_on_failure andlog_on_success).
Para uma lista completa de opções de registro, consulte a página man do xinetd.conf.
46.5.4.3.2. Opções de Controle de Acesso
Users of xinetd services can choose to use the TCP Wrappers hosts access rules, provide access control via the xinetd configuration files, or a mixture of both. Refer to Seção 46.5.2, “Arquivos de Configuração do TCP Wrappers” for more information about TCP Wrappers hosts access control files.
Esta seção discute o uso do xinetd para controlar o acesso a serviços.

Nota

Ao contrário do TCP Wrappers, mudanças ao controle de acesso entram em vigor apenas se o administrador do xinetd reiniciar o serviço.
Além disso, ao contrário do TCP Wrappers, controle de acesso através do xinetd afeta apenas os serviços controlados pelo xinetd.
O controle de acesso a hosts do xinetd difere do método usado pelo TCP Wrappers. Enquanto o TCP Wrappers organiza toda a configuração de acesso em dois arquivos, /etc/hosts.allow e /etc/hosts.deny, o controle de acesso do xinetd é encontrado no arquivo de configuração de cada serviço no diretório /etc/xinetd.d/.
As seguintes opções de acesso a hosts são suportadas pelo xinetd:
  • only_from — Permite que apenas os hosts especificados usem o serviço.
  • no_access — Não permite que os hosts listados usem o serviço
  • access_times — Especifica o intervalo de tempo durante o qual um determinado serviço pode ser usado. O intervalo de tempo deve ser especificado no formato 24 horas, HH:MM-HH:MM.
As opções only_from e no_access podem usar uma lista de endereços IP ou nomes de host, ou podem especificar um rede inteira. Assim como o TCP Wrappers, a combinação do controle de acesso através do xinetd com a configuração aprimorada de registros pode aumentar a segurança através do bloqueio de pedidos a partir de hosts e do registro detalhado de cada tentativa de conexão.
Por exemplo, o seguinte arquivo /etc/xinetd.d/telnet pode ser usado para bloquear acesso ao Telnet a partir de um determinado grupo de rede e para restringir o intervalo de tempo total que até mesmo usuários com permissão podem permanecer conectados:
service telnet
{
         disable         = no
	 flags           = REUSE
	 socket_type     = stream
	 wait            = no
	 user            = root
	 server          = /usr/kerberos/sbin/telnetd
	 log_on_failure  += USERID
	 no_access       = 172.16.45.0/24
	 log_on_success  += PID HOST EXIT
	 access_times    = 09:45-16:15
}
Neste exemplo, quando um sistema cliente da rede 10.0.1.0/24, como 10.0.1.2 tenta o acesso ao serviço Telnet, recebe a seguinte mensagem:
Conexão fechada pelo host remoto.
Além disso, as tentativas de autenticação do cliente são registradas no /var/log/messages da seguinte maneira:
Sep  7 14:58:33 localhost xinetd[5285]: FAIL: telnet address from=172.16.45.107
Sep  7 14:58:33 localhost xinetd[5283]: START: telnet pid=5285 from=172.16.45.107
Sep  7 14:58:33 localhost xinetd[5283]: EXIT: telnet status=0 pid=5285 duration=0(sec)
Ao usar o TCP Wrappers junto com os controles de acesso do xinetd, é importante entender a relação entre os dois mecanismos de controle de acesso.
Veja a seguir a seqüência de eventos seguida pelo xinetd quando um cliente solicita uma conexão:
  1. O daemon xinetd acessa as regras de acesso a hosts o TCP Wrappers usando uma chamada da biblioteca libwrap.a. Se uma regra de negação (deny rule) corresponde ao cliente, a conexão é abandonada. Se um regra de permissão (allow rule) corresponde ao cliente, a conexão é passada para o xinetd.
  2. O daemon xinetd verifica as suas próprias regras de controle de acesso tanto para o serviço xinetd como para o serviço requisitado. Se uma regra de negação corresponder ao cliente, a conexão é abandonada. Caso contrário, o xinetd inicia uma instância do serviço requisitado e passa o controle da conexão para aquele serviço.

Importante

Deve-se tomar cuidado ao usar os controles de acesso do TCP Wrappers junto com os controles de acesso do xinetd. A má configuração pode causar efeitos indesejáveis.
46.5.4.3.3. Opções de Vinculação e Redirecionamento
Os arquivos de configuração de serviços para o xinetd oferecem suporte à vinculação do serviço a um endereço IP e o redirecionamento de pedidos de entrada para aquele serviço para outro endereço IP, nome de host, ou porta.
A vinculação é controlada com a opção bind nos arquivos de configuração de serviço específicos e liga o serviço a um endereço IP no sistema. Quando configurado, a opção bind permite apenas que pedidos ao endereço IP correto acessem o serviço. Você pode usar este método para vincular vários serviços à várias interfaces de rede conforme for necessário.
Isto é especialmente útil para sistemas com vários adaptadores de rede ou com vários endereços IP. Em tais sistemas, serviços inseguros (por exemplo, o Telnet), podem ser configurados para que escutem somente na interface conectada à rede privativa e não na interface conectada à Internet.
A opção redirect aceita um endereço IP ou nome de host seguido por um número de porta. A opção configura o serviço para que redirecione quaisquer pedidos por este serviço para host e número de porta especificados. Esta funcionalidade pode ser usada para fazer o redirecionamento para outra porta no sistema, para redirecionar o pedido para um endereço IP diferente na mesma máquina, mandar o pedido para um sistema e um número de porta totalmente diferentes, ou qualquer combinação destas opções. Um usuário que esteja conectando a um sistema pode portanto ser redirecionado para outro sistema sem interrupção.
O daemon xinetd pode realizar este redirecionamento através da geração de um processo que mantém-se vivo por toda a duração da conexão entre a máquina cliente que fez o pedido e o host oferecendo o serviço, transferindo dados entre os dois sistemas.
As vantagens das opções bind e redirect são mais evidentes quando usadas ao mesmo tempo. Ao vincular um serviço a um endereço IP específico em um sistema, e então redirecionar pedidos por este serviço para uma segunda máquina que apenas a primeira máquina saiba que exista, um sistema interno pode ser usado para oferecer serviços para uma rede totalmente diferente. Alternativamente, estas opções podem ser usadas para limitar a exposição de um serviço específico em uma máquina com diversas bases a um endereço IP conhecido, bem como para redirecionar quaisquer pedidos por aquele serviço para outra máquina configurada especialmente para esta finalidade.
Por exemplo, considere um sistema que seja usado como um firewall com esta configuração para o serviço Telnet:
service telnet
{
         socket_type		= stream
	 wait			= no
	 server			= /usr/kerberos/sbin/telnetd
	 log_on_success		+= DURATION USERID
	 log_on_failure		+= USERID
	 bind                    = 123.123.123.123
	 redirect                = 10.0.1.13 23
}
As opções bind e redirect neste arquivo garantem que o serviço Telnet na máquina é vinculado ao endereço IP externo (123.123.123.123), o qual faz a interface com a Internet. Além disso, quaisquer pedidos por serviços Telnet enviados ao 123.123.123.123 são redirecionados através de um segundo adaptador de rede para um endereço IP interno (10.0.1.13) que apenas o firewall e sistemas internos podem acessar. O firewall então envia a conexão entre os dois sistemas, e o sistema que está se conectando pensa que está conectado ao 123.123.123.123, quando na verdade está conectado à uma máquina diferente.
Esta funcionalidade é útil especialmente para usuários com conexões de banda larga mas somente um endereço IP fixo. Ao usar a Conversão de Endereços de Rede (Network Address Translation - NAT), os sistemas atrás do firewall, os quais estão usando endereços IP de uso apenas interno, não ficam disponíveis no exterior do sistema de gateway. Entretanto, quando certos serviços controlados pelo xinetd são configurados com as opções bind e redirect, o gateway pode fazer o papel de proxy entre sistemas externos e uma máquina interna específica configurada para oferecer o serviço. Além disso, as várias opções de controle de acesso e registro do xinetd também estão disponíveis para proteção adicional.
46.5.4.3.4. Opções de Gerenciamento de Recursos
O daemon xinetd pode adicionar um nível de proteção básico contra ataques de Negação de Serviço (Denial of Service - DoS). Veja a seguir uma lista de diretivas que podem ajudar a limitar a efetividade de tais ataques:
  • per_source — Define o número máximo de instâncias para um serviço por endereço IP fonte. Aceita apenas valores inteiros como argumento e pode ser usado tanto no xinetd.conf como nos arquivos de configuração de serviço específicos no diretório xinetd.d/.
  • cps — Define o número máximo de conexões por segundo. esta diretiva usa dois argumentos (valores inteiros), separados por um espaço. O primeiro argumento é o número máximo de conexões por segundo permitidas ao serviço. O segundo argumento é o número de segundos que o xinetd deve deixar passar antes de reabilitar o serviço. A diretiva aceita apenas valores inteiros como argumento, e pode ser usada tanto no arquivo xinetd.conf como nos arquivos de configuração de serviço específicos no diretório xinetd.d/.
  • max_load — Define o uso da CPU ou o limiar de carga média para um serviço. A diretiva aceita um número de ponto flutuante como argumento.
    A carga média é uma medida aproximada de quantos processos estão ativos em um determinado momento. Consulte as páginas man dos comandos uptime, who, e procinfo para mais informações sobre a carga média (load average).
Existem ainda mais opções de gerenciamento de recursos disponíveis ao xinetd. Consulte a página man do xinetd.conf para mais informações.

46.5.5. Recursos Adicionais

Mais informações sobre o TCP Wrappers e o xinetd estão disponíveis na documentação do sistema e na Internet.

46.5.5.1. Documentação Instalada

A documentação do seu sistema é um bom lugar para começar a procurar por opções de configuração adicionais para o TCP Wrappers, xinetd, xinetd, controle de acesso.
  • /usr/share/doc/tcp_wrappers-<version>/ — este diretório contém o arquivo README que discute como o TCP Wrappers funciona e os vários riscos existentes em relação à falsificação de nomes e endereços de host .
  • /usr/share/doc/xinetd-<versão>/ — Este diretório contém um arquivo README que discute aspectos de controle de acesso e uma amostra de arquivo de configuração sample.conf com várias idéias sobre como modificar arquivos de configuração de serviço específicos no diretório /etc/xinetd.d/.
  • Páginas man relacionadas ao TCP Wrappers e ao xinetd — Uma série de páginas man existem para os vários aplicativos e arquivos de configuração relacionados ao TCP Wrappers e ao xinetd. Veja a seguir algumas das páginas man mais importantes:
    Aplicações de Servidor
    • man xinetd — A página man para o xinetd.
    Arquivos de Configuração
    • man 5 hosts_access — A página man dos arquivos de controle de acesso hosts do TCP Wrappers.
    • man hosts_options — A página man para os campos de opções do TCP Wrappers.
    • man xinetd.conf — A página man com a listagem das opções de configuração do xinetd.

46.5.5.2. Sites Úteis

46.6. Kerberos

A segurança e a integridade de sistemas dentro de uma rede podem ser difíceis de administrar. Acompanhar os serviços sendo executados em uma rede, assim como a maneira como os mesmos estejam sendo usados pode ocupar o tempo de vários administradores.
Além disso, a autenticação de usuários a serviços de rede pode representar um perigo quando o método usado pelo protocolo é inerentemente inseguro, conforme evidenciado pela transferência de senhas não criptografadas através de uma rede usando os protocolos FTP ou Telnet.
O Kerberos é uma maneira de eliminar a necessidade de usar protocolos que permitam métodos de autenticação inseguros, melhorando assim a segurança geral da rede.

46.6.1. O que é o Kerberos?

O Kerberos é um protocolo de autenticação de rede criado pelo MIT, que utiliza criptografia de chave simétrica [17] para autenticar usuários a serviços de rede, o que significa que as senhas em si nunca são enviadas através da rede.
Conseqüentemente, quando usuários se autenticam em serviços de rede usando o Kerberos, os usuários não autorizados, que estão tentando obter senhas através da monitoração do tráfego de rede, são impedidos de forma efetiva.

46.6.1.1. Vantagens do Kerberos

A maioria dos serviços de rede convencionais usa esquemas de autenticação de senhas. Estes esquemas requerem que o usuário se autentique em uma rede fornecendo seu nome de usuário e senha. Infelizmente, o envio de informações de autenticação para diversos serviços, é realizado sem criptografia. Para que um esquema destes seja seguro, a rede deve estar inacessível para pessoas de fora, assim como todos os computadores e usuários da rede devem ser confiáveis.
Mesmo se este for o caso, uma vez que a rede está conectada à Internet, não pode mais ser considerada segura. Qualquer atacante que obtiver acesso à rede pode usar um simples analisador de pacotes (também conhecido como 'packet sniffer') para interceptar nomes de usuários e senhas enviados desta maneira, assim comprometendo as contas de usuários e a integridade de toda a infraestrutura de segurança.
O objetivo principal do design do Kerberos é a eliminação da transmissão de senhas não criptografadas através da rede. Se for usado adequadamente, o Kerberos elimina efetivamente a ameaça que programas tipo packet sniffers representariam à rede caso o Kerberos não fosse usado.

46.6.1.2. Desvantagens do Kerberos

Apesar do Kerberos eliminar uma ameaça severa e comum, pode ser de difícil implementação devido à uma gama de motivos:
  • Migrar senhas de usuário de um banco de dados UNIX padrão, como o /etc/passwd ou o /etc/shadow, para um banco de dados de senhas Kerberos pode ser entediante, pois não há um mecanismo automatizado para executar esta tarefa. Para mais informações, consulte a Questão 2.23 no FAQ online do Kerberos:
  • Kerberos has only partial compatibility with the Pluggable Authentication Modules (PAM) system used by most Red Hat Enterprise Linux servers. Refer to Seção 46.6.4, “Kerberos e PAM” for more information about this issue.
  • O Kerberos presume que cada usuário é confiável e está usando uma máquina não confiável em uma rede não confiável. Seu objetivo principal é evitar que senhas não criptografadas sejam enviadas pela rede. No entanto, se alguém além do usuário legítimo tiver acesso à máquina que emite tickets usados para autenticação — chamada de centro de distribuição de chave (KDC) — o sistema de autenticação inteiro do Kerberos estará em risco.
  • Para que um aplicativo use o Kerberos, sua fonte deve ser alterada para fazer as chamadas apropriadas às bibliotecas do Kerberos. Os aplicativos modificados desta maneira são considerados kerberizados. Para alguns aplicativos, isto pode ser bastante problemático devido ao tamanho ou design do aplicativo. Para outros aplicativos incompatíveis, as alterações devem ser feitas na maneira como o lado servidor e cliente se comunicam. Vale frisar que isto pode requerer uma programação extensiva. Aplicativos de código fechado que não têm suporte ao Kerberos por padrão são geralmente os mais problemáticos.
  • O Kerberos é uma solução 'tudo ou nada'. Se ele for utilizado na rede, quaisquer senhas não criptografadas transferidas a um serviço não-kerberizado estão em risco. Portanto, a rede não se beneficia do uso do Kerberos. Para proteger uma rede com o Kerberos, deve-se utilizar versões kerberizadas de todos os aplicativos cliente/servidor que enviam senhas não criptografadas ou não usar nenhum aplicativo do tipo cliente/servidor.

46.6.2. Terminologia do Kerberos

O Kerberos tem sua própria terminologia para definir os diversos aspectos do serviço. Antes de aprender como o Kerberos funciona, é importante aprender os seguintes termos.
servidor de autenticações - (AS)
Um servidor que emite os tickets para um serviço desejado, que por sua vez são dados para usuários acessarem o serviço. O AS responde aos pedidos de clientes que não têm ou não enviam as credenciais com um pedido. É usado geralmente para obter acesso ao serviço Servidor de Concessão de Ticket (Ticket-Granting Server), ou simplesmente TGS, emitindo um Ticket de Concessão de Tickets (Ticket-Granting Ticket), ou TGT. O AS geralmente roda no mesmo host que o Centro de Distribuição de Chaves (Key Distribution Center), ou KDC.
texto criptografado (ciphertext)
Dados criptografados.
cliente
Uma entidade na rede (um usuário, uma máquina ou um aplicativo) que pode receber um ticket do Kerberos.
credenciais
Um conjunto temporário de credenciais eletrônicas que verificam a identidade de um cliente para um determinado serviço. Também chamadas de tickets.
cache das credenciais ou arquivo de tickets
Um arquivo que contém as chaves para criptografar as comunicações entre um usuário e vários serviços de rede. O Kerberos 5 suporta uma estrutura de trabalho para usar outros tipos de cache, como memória compartilhada, mas os arquivos são melhor suportados.
crypt hash
Um hash de mão única usado para autenticar usuários. Estes são mais seguros do que usar dados não criptografados, mas para um cracker experiente eles ainda são relativamente fáceis de decifrar. (AS) -
GSS-API
'The Generic Security Service Application Program Interface' (definida na RFC-2743 publicada pela The Internet Engineering Task Force) é um conjunto de funções, que oferece serviços de segurança usados por clientes para se autenticarem nos serviços. Esta API também é usada pelos clientes e serviços para autenticação mútua sem a necessidade de que os mesmos tenham conhecimento específico sobre o mecanismo subjacente de cada um. Se um serviço de rede (como o cyrus-IMAP) usa a GSS-API, o mesmo pode autenticar usando o Kerberos.
hash
Também chamado de valor de hash. Um valor gerado passando uma faixa por uma função de hash. Estes valores são tipicamente usados para garantir que os dados transmitidos não tenham sido adulterados.
função de hash
Uma forma de gerar uma "impressão digital" a partir de dados de entrada. Estas funções reorganizam, transpõem, ou de alguma outra forma alteram dados para produzir um valor de hash.
key
Informação usada ao criptografar ou descriptografar outros dados. Dados criptografados não podem ser descriptografados sem a chave apropriada ou através de muita sorte por parte do cracker.
centro de distribuição de chave (KDC)
Um serviço que emite tickets do Kerberos e geralmente roda no mesmo host que o servidor de concessão de ticket (TGS).
keytab (ou keytable)
Um arquivo que contém uma lista não criptografada de principais e suas chaves. Servidores obtém as chaves necessárias dos arquivos keytab ao invés de usar o kinit. O arquivo keytab padrão é o /etc/krb5.keytab. O servidor de administração do KDC, /usr/kerberos/sbin/kadmind, é o único serviço que usa qualquer outro arquivo (usa o /var/kerberos/krb5kdc/kadm5.keytab).
kinit
O comando kinit permite que um principal que já tenha se conectado obtenha o ticket de concessão de ticket (TGT) inicial e armazene-o no cache. Para mais informações sobre o uso do comando kinit, consulte sua página man.
principal (ou nome do principal)
O principal é o nome único de um usuário ou serviço com permissão para autenticar usando o Kerberos. Um principal segue o formato root[/instance]@REALM. Para um usuário típico, a raiz (root) é a mesmo que seu ID de autenticação. A instance (instância) é opcional. Se o principal tiver uma instância, a mesma será separada da raiz por uma barra ("/"). Uma faixa vazia ("") é considerada uma instância válida (a qual difere da instância padrão NULL), mas usá-la pode ser confuso. Todos os principais em um território (realm) têm suas próprias chaves que, para os usuários, são derivadas de uma senha, ou são definidas randomicamente para os serviços.
território (realm)
Uma rede que usa o Kerberos, composta de um ou mais servidores - chamados KDCs - e um número potencialmente grande de clientes.
serviço
Um programa acessado através da rede.
ticket
Um conjunto temporário de credenciais eletrônicas que verificam a identidade de um cliente para um determinado serviço. Também chamado de credenciais.
servidor de concessão de ticket (TGS)
Um servidor que emite tickets para um serviço desejado, que por sua vez são dados aos usuários para acessarem um serviço. O TGS geralmente roda na mesma máquina que o KDC.
ticket de concessão de ticket (TGT)
Um ticket especial que permite ao cliente obter tickets adicionais sem requisitá-los pelo KDC.
senha não criptografada
Uma senha em formato de texto simples, legível.

46.6.3. Como o Kerberos Funciona

O Kerberos difere dos métodos de autenticação nome do usuário/senha porque, ao invés de autenticar cada usuário para cada serviço de rede, o Kerberos utiliza criptografia simétrica e um terceiro elemento confiável (um KDC) para autenticar usuários a um conjunto de serviços de rede. Quando um usuário autenticar no KDC, este envia um ticket específico para esta sessão de volta para a máquina do usuário, e quaisquer serviços kerberizados procuram o ticket na máquina do usuário ao invés de pedir que o usuário se autentique usando uma senha.
Quando um usuário de uma rede kerberizada se autentica em sua estação de trabalho, seu principal é enviado ao KDC como parte de um pedido de TGT ao Servidor de Autenticação (AS). Este pedido pode ser enviado pelo programa de login, sendo assim transparente para o usuário, ou pode ser enviado pelo programa kinit após o usuário se logar.
O KDC então verifica o principal em seu banco de dados. Se o principal é encontrado, o KDC cria um TGT, que é criptografado usando a chave do usuário, e retornado para o usuário.
O programa de autenticação ou kinit no cliente,descriptografa então o TGT usando a chave do usuário, computada a partir da senha do usuário. A chave do usuário é usada somente na máquina cliente e não é enviada através da rede.
O TGT é configurado para expirar após um período de tempo determinado (geralmente dez horas) e armazenado no cache de credenciais da máquina cliente. A expiração é definida para que um TGT comprometido seja útil para um atacante por somente um curto período de tempo. Após o TGT ter sido emitido, o usuário não precisa fornecer a sua senha até que o TGT expire ou até efetuar o logoff e então efetuar o login novamente.
Sempre que um usuário precisar de acesso a um serviço de rede, o software cliente usa o TGT para pedir um novo ticket para este serviço específico ao TGS. O ticket do serviço é então usado para autenticar o usuário de forma transparente a este serviço.

Aviso

O sistema do Kerberos pode ser comprometido se um usuário da rede se autenticar em um serviço não-kerberizado enviando a senha em formato texto. O uso de serviços não-kerberizados é altamente desestimulado. Tais serviços incluem Telnet e FTP. Porém, o uso de outros protocolos criptografados, como os serviços protegidos SSH ou SSL, é aceitável apesar de não ser ideal.
This is only a broad overview of how Kerberos authentication works. Refer to Seção 46.6.10, “Recursos Adicionais” for links to more in-depth information.

Nota

O Kerberos depende dos seguintes serviços de rede para funcionar corretamente.
  • Sincronização aproximada de relógio, entre as máquinas da rede.
    Um programa de sincronização de relógio deve ser configurado para a rede, como o ntpd. Consulte /usr/share/doc/ntp-<version-number>/index.html para detalhes sobre como configurar servidores Protocolo de Horário de Rede (NTP), onde <version-number> é o número da versão do pacote ntp instalado no seu sistema.
  • Serviço de Nome do Domínio (DNS).
    Certifique-se de que as entradas de DNS e os hosts na rede estão todos configurados apropriadamente. Consulte o Guia do Administrador de Sistemas do Kerberos V5 em /usr/share/doc/krb5-server-<version-number> para mais informações (onde <version-number> é o número da versão do pacote krb5-server instalado no seu sistema).

46.6.4. Kerberos e PAM

Atualmente, os serviços kerberizados não utilizam Módulos de Autenticação Plugáveis (PAM) — os serviços kerberizados ignoram completamente o PAM. Entretanto, os aplicativos que usam PAM podem usar o Kerberos para autenticação se o módulo pam_krb5 (oferecido no pacote pam_krb5) está instalado. O pacote pam_krb5 contém arquivos de amostra de configuração que permitem a serviços como o login e o gdm autenticarem usuários e obterem as credenciais iniciais usando suas senhas. Se o acesso a serviços de rede é sempre executado usando serviços kerberizados ou serviços que usam GSS-API, como o IMAP, a rede pode ser considerada razoavelmente segura.

Tip

Os administradores devem ter cuidado para não permitir que usuários se autentiquem na maioria dos serviços de rede usando senhas do Kerberos. Muitos protocolos usados por estes serviços não criptografam a senha antes de enviá-la através da rede, destruindo os benefícios do sistema Kerberos. Por exemplo: usuários não devem ter a permissão de se autenticar no Telnet usando a mesma senha usada para o Kerberos.

46.6.5. Configurando o Servidor Kerberos 5

Antes de configurar o Kerberos, instale o KDC. Se for preciso configurar servidores escravos (secundários), instale primeiro um mestre (primários).
Para configurar um servidor Kerberos básico, siga estes passos:
  1. Certifique-se de que a sincronização do relógio e DNS estejam funcionando em todas as máquinas cliente e servidor antes de configurar o Kerberos. Preste atenção especial à sincronização do horário entre o servidor Kerberos e seus clientes. Se a diferença entre os relógios do servidor e do cliente for maior que cinco minutos (essa quantidade padrão é configurável no Kerberos 5), os clientes do Kerberos não poderão se autenticar no servidor. Essa sincronização do relógio se faz necessária para evitar que um atacante use um ticket antigo do Kerberos para se mascarar como um usuário válido.
    É aconselhável configurar um Protocolo de Horário de Rede (Network Time Protocol - NTP) compatível com a rede cliente/servidor mesmo se o Kerberos não estiver sendo usado. O Red Hat Enterprise Linux inclui o pacote ntp para este propósito. Consulte o /usr/share/doc/ntp-<version-number>/index.html (onde <version-number> é o número da versão do pacote ntp instalado no seu sistema) para obter detalhes sobre a configuração de servidores de Protocolo de Horário de Rede e http://www.ntp.org para informações adicionais sobre NTP.
  2. Instale os pacotes krb5-libs, krb5-server, e krb5-workstation na máquina dedicada que executa o KDC. Essa máquina precisa ser muito segura — se possível, não deve executar nenhum outro serviço além do KDC.
  3. Edite os arquivos de configuração /etc/krb5.conf e /var/kerberos/krb5kdc/kdc.conf para refletir o nome do território e o mapeamento de domínio-território. Um território simples pode ser construído substituindo as instâncias de EXEMPLO.COM e exemplo.com pelo nome de domínio correto — certificando de manter os nomes em caixas alta e baixa no formato correto — e alterando o KDC de kerberos.exemplo.com para o nome do servidor do Kerberos. Por convenção, todos os nomes de território são escritos em caixa alta e todos os nomes DNS de máquinas e de domínio são escritos em caixa baixa. Para uma explanação completa sobre os formatos destes arquivos, consulte as respectivas páginas man.
  4. Crie o banco de dados usando o utilitário kdb5_util em uma janela de comandos:
    /usr/kerberos/sbin/kdb5_util create -s
    O comando create cria o banco de dados usado para armazenar as chaves para o território do Kerberos. A opção -s força a criação de um arquivo stash no qual a chave do servidor mestre está armazenada. Se não houver nenhum arquivo stash a partir do qual pode-se ler a chave, o servidor do Kerberos (krb5kdc) pede ao usuário a senha do servidor mestre (que pode ser usada para recriar a chave) toda vez que este iniciar.
  5. Edite o arquivo /var/kerberos/krb5kdc/kadm5.acl. Este arquivo é usado pelo kadmind para determinar quais principais têm acesso administrativo ao banco de dados do Kerberos e seus níveis de acesso. A maioria das empresas podem fazer isso com uma única linha:
    */admin@EXAMPLE.COM  *
    A maioria dos usuários é representada no banco de dados por um único principal (com uma instância NULA ou vazia, como joe@EXEMPLO.COM). Com esta configuração, usuários com um segundo principal com a instância admin (joe/admin@EXEMPLO.COM, por exemplo) são capazes de exercer controle total sobre o banco de dados Kerberos do território.
    Uma vez iniciado o kadmind no servidor, qualquer usuário pode acessar seus serviços, executando kadmin em quaisquer clientes ou servidores no território. Entretanto, somente os usuários listados no arquivo kadm5.acl podem modificar o banco de dados de qualquer maneira, exceto alterar suas próprias senhas.

    Nota

    O utilitário kadmin se comunica com o servidor kadmind através da rede e usa o Kerberos para autenticação. Por este motivo, o primeiro principal já deve existir antes de conectar ao servidor através da rede para administrá-lo. Crie o primeiro principal com o comando kadmin.local, que é especificamente desenvolvido para ser usado na mesma máquina que o KDC e não utiliza o Kerberos para autenticação.
    Digite o seguinte comando kadmin.local no terminal do KDC para criar o primeiro principal:
    /usr/kerberos/sbin/kadmin.local -q "addprinc username/admin"
  6. Inicie o Kerberos usando os seguintes comandos:
    service krb5kdc start
    service kadmin start
    service krb524 start
  7. Adicione principais para os usuários com o comando addprinc do kadmin. O kadmin e o kadmin.local são interfaces de linha de comando do KDC. Conseqüentemente, muitos comandos — como o addprinc — tornam-se disponíveis após o lançamento do programa kadmin. Consulte a página man do kadmin para mais informações.
  8. Verifique se o KDC está emitindo tickets. Primeiro, execute kinit para obter um ticket e armazená-lo em um arquivo cache de credenciais. Em seguida, use o klist para visualizar a lista de credenciais no cache e use o kdestroy para destruir o cache e as credenciais ali contidas.

    Nota

    Por padrão, o kinit tenta autenticar usando o nome de login da conta usada ao logar no sistema (não no servidor do Kerberos). Se este nome não corresponde a um principal no banco de dados do Kerberos, o kinit emite uma mensagem de erro. Se isto ocorrer, forneça ao kinit o nome correto do principal como um argumento na linha de comando (kinit <principal>).
Uma vez que estes passos estejam completos, o servidor do Kerberos deve estar pronto e funcionando.

46.6.6. Configurando um Cliente Kerberos 5

Configurar um cliente Kerberos 5 é menos complexo que um servidor. No mínimo, deve-se instalar os pacotes de cliente e prover um arquivo de configuração krb5.conf válido para cada cliente. Apesar de se preferir os métodos de instalação remota ssh e slogin para sistemas de clientes, as versões kerberizadas de rsh e rlogin também requerem algumas alterações de configuração.
  1. Be sure that time synchronization is in place between the Kerberos client and the KDC. Refer to Seção 46.6.5, “Configurando o Servidor Kerberos 5” for more information. In addition, verify that DNS is working properly on the Kerberos client before configuring the Kerberos client programs.
  2. Instale os pacotes krb5-libs e krb5-workstation em todas as máquinas cliente. Forneça um arquivo /etc/krb5.conf válido para cada cliente (geralmente este pode ser o mesmo arquivo krb5.conf usado pelo KDC).
  3. Antes que uma estação de trabalho no território possa usar Kerberos para autenticar a conexão de usuários usando ssh ou rsh e rlogin kerberizados, ela deve ter seu principal da host no banco de dados de Kerberos. Os programas de servidores sshd,kshd e klogind também precisam de acesso às chaves para o principal dos serviços da host. Além disso, para usar os serviços rsh e rlogin, esta estação de trabalho deve ter um pacote xinetd instalado.
    Usar kadmin adiciona um principal para a estação de trabalho no KDC. Neste caso, a instância é o nome da máquina (estação de trabalho). Use a opção -randkey para o comando addprinc do kadmin para criar o principal e atribuí-lo com uma chave randômica:
    addprinc -randkey host/blah.example.com
    Agora que o principal foi criado, as chaves podem ser extraídas para a estação de trabalho executando o kadmin na própria estação de trabalho, e usando o comando ktadd no kadmin:
    ktadd -k /etc/krb5.keytab host/blah.example.com
  4. Para usar outros serviços de rede kerberizados é necessário iniciá-los. Veja abaixo uma lista com alguns dos serviços kerberizados mais comuns e instruções para habilitá-los:
    • O comando OpenSSH ssh — usa a GSS-API para autenticar usuários aos servidores, caso a configuração do client e server tenham o GSSAPIAuthentication habilitado. Se o client também possuir um GSSAPIDelegateCredentials habilitado, as credenciais do usuário serão disponibilizadas no sistema remoto.
    • rsh e rlogin — Para usar as versões kerberizadas do rsh e do rlogin, habilite klogin, eklogin, e kshell.
    • Telnet — Para usar o Telnet kerberizado, o krb5-telnet deve estar habilitado.
    • FTP — Para prover acesso ao FTP, crie e extraia uma chave para o principal com uma raiz de ftp. Certifique-se de definir a instância para o nome da máquina do servidor FTP, e então habilite o gssftp.
    • IMAP — Para usar um servidor IMAP kerberizado, o pacote cyrus-imap usa o Kerberos 5 se o pacote cyrus-sasl-gssapi também estiver instalado. O pacote cyrus-sasl-gssapi contém os plugins do Cyrus SASL os quais oferecem suporte à autenticação usando a GSS-API. O Cyrus IMAP deve funcionar adequadamente com o Kerberos conquanto o usuário cyrus possa encontrar a chave apropriada em /etc/krb5.keytab, e a root (raiz) para o principal esteja configurada para imap (criada com kadmin).
      Uma alternativa para o cyrus-imap pode ser o pacote dovecot, o qual também é incluído no Red Hat Enterprise Linux. Este pacote contém um servidor IMAP mas até o momento não suporta a GSS-API e o Kerberos.
    • CVS — Para usar um servidor CVS kerberizado, o gserver usa um principal com uma raiz (root) cvs e é idêntico ao CVS pserver em todos os outros aspectos.
    Refer to Capítulo 17, Controlando Acesso aos Serviços for details about how to enable services.

46.6.7. Mapeamento Domínio-para-território

Quando um client tenta acessar um serviço que esteja rodando em um server específico, ele sabe o nome do serviço (host) e o nome do server (foo.example.com), mas como é possível que mais de um território seja implementado na sua rede de trabalho, ele precisa adivinhar o nome do território, no qual o serviço se encontra.
Por padrão, o nome do território é o mesmo do domínio DNS do server, com letras maiúsculas.

foo.example.org → EXAMPLE.ORG
foo.example.com → EXAMPLE.COM
foo.hq.example.com → HQ.EXAMPLE.COM

In some configurations, this will be sufficient, but in others, the realm name which is derived will be the name of a non-existent realm. In these cases, the mapping from the server's DNS domain name to the name of its realm must be specified in the domain_realm section of the client system's krb5.conf. For example:
[domain_realm]
.example.com = EXAMPLE.COM
example.com = EXAMPLE.COM
The above configuration specifies two mappings. The first mapping specifies that any system in the "example.com" DNS domain belongs to the EXAMPLE.COM realm. The second specifies that a system with the exact name "example.com" is also in the realm. (The distinction between a domain and a specific host is marked by the presence or lack of an initial ".".) The mapping can also be stored directly in DNS.

46.6.8. Configurando KDCs Secundários

Por inúmeras razões, você pode preferir rodar KDCs múltiplos para um dado território. Nesse caso, um KDC (o master KDC) mantém uma cópia escrita do banco de dados do território e roda o kadmind ( também é o servidor administrativo do território), e um ou mais KDCs (KDCs escravos) mantém cópias de somente leitura do banco de dados e roda o kpropd.
O procedimento de propagação do mestre-escravo, faz com que o KDC mestre despeje seu banco de dados em um arquivo de despejo temporário e então transfira este arquivo para cada um de seus escravos, que irão por conseqüência sobrescrever suas cópias de somente leitura, previamente recebidas, do banco de dados com o conteúdo do arquivo de despejo.
Antes de mais nada, para configurar um KDC escravo, assegure-se que os arquivos krb5.conf e kdc.conf de KDC mestre sejam copiados para o KDC escravo.
Inicie o kadmin.local a partir de uma janela root no KDC mestre e use seu comando add_principal para criar uma entrada nova para o serviço host do KDC mestre. Depois disso, use seu comando ktadd para ajustar simultaneamente uma chave aleatória para o serviço e armazene a chave aleatória no arquivo keytab padrão do mestre. Esta chave será usada pelo comando kprop para autenticar servidores de escravo. Você precisará fazer isto somente uma vez, não importanto quantos servidores de escravos você instalar.
~]# kadmin.local -r EXAMPLE.COM
Authenticating as principal root/admin@EXAMPLE.COM with password.
kadmin: add_principal -randkey host/masterkdc.example.com
Principal "host/host/masterkdc.example.com@EXAMPLE.COM" created.
kadmin: ktadd host/masterkdc.example.com
Entry for principal host/masterkdc.example.com with kvno 3, encryption type Triple DES cbc mode with \
	HMAC/sha1 added to keytab WRFILE:/etc/krb5.keytab.
Entry for principal host/masterkdc.example.com with kvno 3, encryption type ArcFour with HMAC/md5 \
	added to keytab WRFILE:/etc/krb5.keytab.
Entry for principal host/masterkdc.example.com with kvno 3, encryption type DES with HMAC/sha1 added \
	to keytab WRFILE:/etc/krb5.keytab.
Entry for principal host/masterkdc.example.com with kvno 3, encryption type DES cbc mode with RSA-MD5 \
	added to keytab WRFILE:/etc/krb5.keytab.
kadmin: quit
Inicie o kadmin.local a partir de uma janela root no KDC escravo e use seu comando add_principal para criar uma entrada nova para o serviço host do KDC escravo. Depois disso, use o comando ktadd do kadmin para ajustar simultaneamente uma chave aleatória para o serviço e armazenar a chave aleatória no arquivo keytab padrão do escravo. Esta chave será usada pelo comando kprop para autenticar clients.
~]# kadmin -p jimbo/admin@EXAMPLE.COM -r EXAMPLE.COM
Authenticating as principal jimbo/admin@EXAMPLE.COM with password.
Password for jimbo/admin@EXAMPLE.COM:
kadmin: add_principal -randkey host/slavekdc.example.com
Principal "host/slavekdc.example.com@EXAMPLE.COM" created.
kadmin: ktadd host/slavekdc.example.com@EXAMPLE.COM
Entry for principal host/slavekdc.example.com with kvno 3, encryption type Triple DES cbc mode with \
	HMAC/sha1 added to keytab WRFILE:/etc/krb5.keytab.
Entry for principal host/slavekdc.example.com with kvno 3, encryption type ArcFour with HMAC/md5 added \
	to keytab WRFILE:/etc/krb5.keytab.
Entry for principal host/slavekdc.example.com with kvno 3, encryption type DES with HMAC/sha1 added \
	to keytab WRFILE:/etc/krb5.keytab.
Entry for principal host/slavekdc.example.com with kvno 3, encryption type DES cbc mode with RSA-MD5 added \
	to keytab WRFILE:/etc/krb5.keytab.
kadmin: quit
Com a chave de serviço do KDC escravo, é possível autenticar qualquer client que se conectar a ele. É claro que nem todos eles têm a permissão para oferecer o serviço kprop do escravo com um banco de dados de território novo. Para restringir acesso, o serviço kprop no KDC escravo somente aceitará atualizações de clients que tiverem nomes principais listados no /var/kerberos/krb5kdc/kpropd.acl. Adicione o nome de serviço host do KDC mestre a este arquivo.
~]# echo host/masterkdc.example.com@EXAMPLE.COM > /var/kerberos/krb5kdc/kpropd.acl
Quando o escravo obtiver uma cópia do banco de dados, ele também precisará da chave mestre, que foi utilizada para criptografá-lo. Se a chave mestre do banco de dados do KDC estiver armazenada em um arquivo stash no KDC mestre (geralmente chamado de /var/kerberos/krb5kdc/.k5.REALM), copie para o KDC escravo usando qualquer método seguro disponível, ou crie um banco de dados fictício e um arquivo stash no KDC escravo executando o kdb5_util create -s (o banco de dados fictíco será sobrescrito pela primeira propagação de banco de dados com sucesso) e fornecendo a mesma senha.
Assegure-se de que o firewall do KDC escravo permite que o KDC mestre o contate usando TCP na porta 754 (krb5_prop), e inicie o serviço kprop. Depois, verifique novamente se o serviço kadmin está desabilitado.
Agora faça um teste manual de propagação de banco de dados, despejando o banco de dados do território, dentro do KDC mestre, para o arquivo de dados padrão que será lido pelo comando kprop(/var/kerberos/krb5kdc/slave_datatrans) e use o comando kprop para transferir seu conteúdo para o KDC escravo.
~]# /usr/kerberos/sbin/kdb5_util dump /var/kerberos/krb5kdc/slave_datatrans
~]# kprop slavekdc.example.com
Usando o kinit, certifique-se que um sistema cliente contendo um krb5.conf que liste apenas o KDC escravo na sua lista de KDCs para o seu território, pode obter, corretamente, credenciais iniciais a partir do KDC escravo.
Concluindo isto, simplesmente crie um script que despeja o banco de dados do território e executa o comando kprop para transferir o banco de dados para cada KDC escravo, um de cada vez, e configure o serviço cron para executar o script periodicamente.

46.6.9. Configurando a Autenticação Cross-Realm - (Cross Realm Authentication)

Autenticação cross-realm é um termo utilizado para descrever situações em que os clientes (usuários comuns) de um território usam o Kerberos para autenticar serviços (geralmente processos de server rodando um um sistema server específico) que pertencem a um outro território.
No caso mais simples, para que um cliente de um território A.EXAMPLE.COM possa acessar um serviço no território B.EXAMPLE.COM, ambos devem ter uma chave de um principal krbtgt/B.EXAMPLE.COM@A.EXAMPLE.COM e ambas as chaves devem possuir o mesmo número de versão da chave associado a eles.
Para concluir esta tarefa, selecione uma senha segura e uma frase secreta, e crie uma entrada para o principal em ambos os territórios, usando o kadmin.
~]# kadmin -r A.EXAMPLE.COM
kadmin: add_principal krbtgt/B.EXAMPLE.COM@A.EXAMPLE.COM
Enter password for principal "krbtgt/B.EXAMPLE.COM@A.EXAMPLE.COM":
Re-enter password for principal "krbtgt/B.EXAMPLE.COM@A.EXAMPLE.COM":
Principal "krbtgt/B.EXAMPLE.COM@A.EXAMPLE.COM" created.
kadmin:	quit
~]# kadmin -r B.EXAMPLE.COM
kadmin: add_principal krbtgt/B.EXAMPLE.COM@A.EXAMPLE.COM
Enter password for principal "krbtgt/B.EXAMPLE.COM@A.EXAMPLE.COM":
Re-enter password for principal "krbtgt/B.EXAMPLE.COM@A.EXAMPLE.COM":
Principal "krbtgt/B.EXAMPLE.COM@A.EXAMPLE.COM" created.
kadmin: quit
Use o comando get_principal para se certificar que ambas as entradas possuem números de versões de chaves que combinem (valores kvno) e tipos de criptografia.

Despejando o Banco de Dados 'Doesn't do it'

Os administradores preocupados com a segurança podem tentar usar a opção -randkey do comando add_principal para atribuir uma chave aleatória ao invés de uma senha, despejar uma nova entrada a partir do banco de dados do primeiro território e importá-la para o segundo. Isto não irá funcionar, a não ser que as chaves mestras dos bancos de dados do território sejam idênticas, pois as chaves contidas em um despejo de banco de dados são criptografadas por si só, usando a chave mestra.
Clientes do território A.EXAMPLE.COM podem agora autenticar serviços no território B.EXAMPLE.COM. Ou seja, o território B.EXAMPLE.COM pode agora confiar no território A.EXAMPLE.COM ou ainda em outras palavras, B.EXAMPLE.COM agora confia no A.EXAMPLE.COM.
Isto nos leva a um ponto crucial: a confiança cross-realm é unidirecional por padrão. O KDC do território B.EXAMPLE.COM pode confiar em clientes do A.EXAMPLE.COM para se autenticarem em serviços no território B.EXAMPLE.COM, mas na verdade não importa se os clientes no território B.EXAMPLE.COM são confiáveis para se autenticarem em serviços no território A.EXAMPLE.COM ou não. Para estabelecer confiança no inverso, ambos os territórios deveriam precisar compartilhar chaves para o serviço krbtgt/A.EXAMPLE.COM@B.EXAMPLE.COM (observe a ordem inversa dos dois territórios comparado ao exemplo acima).
Se o relacionamento de confiança fosse somente um método para oferecer confiança aos dois territórios, seria muito difícil configurar as redes de trabalho que contém territórios múltiplos. Felizmente, a confiança cross-realm é transitiva. Se clientes de um A.EXAMPLE.COM puderem autenticar serviços no B.EXAMPLE.COM, e clientes do B.EXAMPLE.COM puderem autenticar serviços no C.EXAMPLE.COM, então os clientes do A.EXAMPLE.COM também podem autenticar serviços em C.EXAMPLE.COM, até mesmo se C.EXAMPLE.COM não confiar em A.EXAMPLE.COM. Isto significa que, em uma rede de trabalho com territórios múltiplos que precisem confiar uns nos outros, fazendo boas escolhas sobre quais relacionamentos confiar para configurar, podem reduzir relativamente os esforços requeridos.
Agora, você tratará dos problemas mais convencionais: o sistema do cliente deve ser configurado para que deduza melhor o território que pertence a um serviço específico, assim como precisa ser capaz de determinar como obter credenciais para serviços neste território.
Antes de mais nada: o nome principal para um serviço fornecido por um sistema de servidor específico em um território se parece com este a seguir:
service/server.example.com@EXAMPLE.COM
Neste exemplo, o serviço é o nome do protocolo em uso (outros valores comums incluem ldap, imap, cvs e HTTP), que pode ser substituído por host. O server.example.com é o nome do domínio do sistema totalmente qualificado, que executa o serviço e EXAMPLE.COM é o nome do território.
Para deduzir o território do serviço ao qual ele pertence, os clientes irão consultar o DNS ou a seção domain_realm do /etc/krb5.conf para mapear tanto um hostname (server.example.com) quanto um nome de domínio DNS (.example.com) para o nome de um território (EXAMPLE.COM).
Após determinar a que território o serviço pertence, um cliente precisa então determinar o conjunto de territórios que ele precisa para contatar, e em qual ordem ele deve fazê-lo para obter credenciais para o uso ao autenticar o serviço.
Isto pode ser feito de duas maneiras.
O método padrão, que não requer configuração explícita, deve nomear os territórios dentro de uma hierarquia compartilhada. Por exemplo, suponha que se tenha territórios chamados A.EXAMPLE.COM, B.EXAMPLE.COM e EXAMPLE.COM. Quando um cliente no território A.EXAMPLE.COM, tentar autenticar o serviço em B.EXAMPLE.COM, ele irá, por padrão, primeiro tentar obter credenciais para o território EXAMPLE.COM, e depois usar estas credenciais para obter outras, para usar no territórioB.EXAMPLE.COM.
O cliente nesta situação, trata o nome do território como se estivesse tratando de um nome DNS. Ele retira os componentes do seu próprio nome de território para gerar nomes de territórios que estejam "acima" dele na hierarquia até que alcance um ponto que também esteja "acima " do território dos serviços. Neste momento, ele começa a passar os componentes do nome do território do serviço na frente até que ele alcance o território do serviço. Cada território envolvido no processo é um outro "salto".
Por exemplo, usando credenciais em A.EXAMPLE.COM, autenticando um serviço em B.EXAMPLE.COM:


A.EXAMPLE.COM → EXAMPLE.COM → B.EXAMPLE.COM

  • A.EXAMPLE.COM e EXAMPLE.COM compartilha chave para krbtgt/EXAMPLE.COM@A.EXAMPLE.COM
  • EXAMPLE.COM e B.EXAMPLE.COM compartilha uma chave para krbtgt/B.EXAMPLE.COM@EXAMPLE.COM
Outro exemplo usando credenciais em SITE1.SALES.EXAMPLE.COM, autenticando um serviço em EVERYWHERE.EXAMPLE.COM:


SITE1.SALES.EXAMPLE.COM → SALES.EXAMPLE.COM → EXAMPLE.COM → EVERYWHERE.EXAMPLE.COM

  • SITE1.SALES.EXAMPLE.COM e SALES.EXAMPLE.COM compartilham uma chave para krbtgt/SALES.EXAMPLE.COM@SITE1.SALES.EXAMPLE.COM
  • SALES.EXAMPLE.COM e EXAMPLE.COMcompartilham uma chave para krbtgt/EXAMPLE.COM@SALES.EXAMPLE.COM
  • EXAMPLE.COM e EVERYWHERE.EXAMPLE.COM compartilham uma chave para krbtgt/EVERYWHERE.EXAMPLE.COM@EXAMPLE.COM
Outro exemplo, desta vez usando nomes de territórios que não compartilham de um sufixo em comum (DEVEL.EXAMPLE.COM e PROD.EXAMPLE.ORG):


DEVEL.EXAMPLE.COM → EXAMPLE.COM → COM → ORG → EXAMPLE.ORG → PROD.EXAMPLE.ORG

  • DEVEL.EXAMPLE.COM e EXAMPLE.COMcompartilham uma chave para krbtgt/EXAMPLE.COM@DEVEL.EXAMPLE.COM
  • EXAMPLE.COM e COM compartilham uma chave para krbtgt/COM@EXAMPLE.COM
  • COM e ORG compartilham uma chave para krbtgt/ORG@COM
  • ORG e EXAMPLE.ORG compartilham uma chave para krbtgt/EXAMPLE.ORG@ORG
  • EXAMPLE.ORG e PROD.EXAMPLE.ORG compartilham uma chave para krbtgt/PROD.EXAMPLE.ORG@EXAMPLE.ORG
O método mais complicado, porém mais flexível, envolve a configuração da seção capaths do /etc/krb5.conf, para que os clientes que tiverem credenciais para um território, possam procurar qual território é o próximo na corrente que irá finalmente levar à autenticação dos servidores.
O formato da seção capaths é relativamente direta: cada entrada na seção é nomeada com o nome de um território com cliente. Dentro desta subseção, o conjunto de territórios intermediários do qual o cliente deve obter credenciais, está listado como valores de chaves que corresponde a um território que possui um serviço. se não existir territórios intermediários, utiliza-se o valor "."
Segue abaixo um exemplo:
[capaths]
A.EXAMPLE.COM = {
	B.EXAMPLE.COM = .
	C.EXAMPLE.COM = B.EXAMPLE.COM
	D.EXAMPLE.COM = B.EXAMPLE.COM
	D.EXAMPLE.COM = C.EXAMPLE.COM
}
Neste exemplo, clientes no território A.EXAMPLE.COM podem obter credenciais cross-realm para B.EXAMPLE.COM diretamente do KDC A.EXAMPLE.COM.
Se estes clientes desejarem contatar um serviço no território C.EXAMPLE.COM, eles precisarão obter credenciais do território B.EXAMPLE.COM (a existência de um krbtgt/B.EXAMPLE.COM@A.EXAMPLE.COM é crucial) e então usar estascredenciais para obter credenciais a serem usadas no território C.EXAMPLE.COM (usando krbtgt/C.EXAMPLE.COM@B.EXAMPLE.COM).
Se estes clientes desejarem contatar um serviço no território D.EXAMPLE.COM eles primeiro precisarão obter credenciais do território B.EXAMPLE.COM, e então credenciais do território C.EXAMPLE.COM, antes de finalmente obter as credenciais para uso no território D.EXAMPLE.COM.

Nota

Sem uma entrada capath indicando o oposto, o Kerberos presume que os relacionamentos de confiança do cross-realm formam uma hierarquia.
Clientes no território A.EXAMPLE.COM podem obter credenciais cross-realm diretamente de um território B.EXAMPLE.COM. Sem o "." indicando isto, o cliente tentaria usar um caminho hierárquico, neste caso:


A.EXAMPLE.COM → EXAMPLE.COM → B.EXAMPLE.COM

46.6.10. Recursos Adicionais

Para mais informações sobre o Kerberos, consulte os seguintes recursos.

46.6.10.1. Documentação Instalada

  • O Guia de Instalação Kerberos V5 e o Guia do Administrador de Sistemas Kerberos V5 S nos formatos PostScript e HTML. Os mesmos podem ser encontrados no diretório /usr/share/doc/krb5-server-<version-number>/ (onde <version-number> é o número da versão do pacote krb5-server instalado no seu sistema.
  • O Guia do Usuário Kerberos V5 UNIX em formatos PostScript e HTML podem ser encontrados em/usr/share/doc/krb5-workstation-<version-number>/(onde <version-number> é o número da versão do pacote krb5-workstation instaladono seu sistema).
  • Páginas man do Kerberos — Há diversas páginas man para os diversos aplicativos e arquivos de configuração envolvidos na implementação do Kerberos. A seguir uma lista com algumas das páginas man mais importantes.
    Aplicativos de Cliente
    • man kerberos — Uma introdução ao sistema Kerberos que descreve o funcionamento das credenciais e fornece recomendações para obter e destruir tickets do Kerberos. O final da página man referencia diversas páginas man relacionadas.
    • man kinit — Descreve como usar este comando para obter e criar o cache de um ticket-granting ticket.
    • man kdestroy — Descreve como usar este comando para destruir credenciais do Kerberos.
    • man klist — Descreve como usar este comando para listar credenciais cacheadas do Kerberos.
    Aplicativos Administrativos
    • man kadmin — Descreve como usar este comando para administrar o banco de dados do Kerberos V5.
    • man kdb5_util — Descreve como usar este comando para criar e executar funções administrativas de nível baixo no banco de dados do Kerberos V5.
    Aplicativos de Servidor
    • man krb5kdc — Descreve as opções de linha de comando disponíveis para o Kerberos V5 KDC.
    • man kadmind — Descreve as opções de linha de comando do servidor de administração do Kerberos V5.
    Arquivos de Configuração
    • man krb5.conf — Descreve o formato e as opções do arquivo de configuração da biblioteca do Kerberos V5.
    • man kdc.conf — Descreve o formato e as opções disponíveis do arquivo de configuração do AS e do KDC do Kerberos V5.

46.6.10.2. Sites Úteis

46.7. Redes Privadas Virtuais (Virtual Private Networks - VPNs)

Empresas com vários escritórios satélite freqüentemente conectam-se com linhas dedicadas por razões de eficiência e de proteção de dados privativos em trânsito. Por exemplo, várias empresas usam linhas frame relay ou Asynchronous Transfer Mode (ATM) como uma solução de rede de ponta-a-ponta para interligar escritórios. Isto pode ser uma alternativa cara, especialmente para pequenas e médias empresas que queiram expandir sem arcar com os altos custos associados a circuitos digitais dedicados, de nível corporativo.
Para atender à esta necessidade, foram desenvolvidas as Redes Privadas Virtuais (Virtual Private Networks - VPNs). Seguindo os mesmos princípios funcionais dos circuitos dedicados, as VPNs permitem a comunicação digital protegida entre duas partes (ou redes), criando uma Rede Geograficamente Distribuída (Wide Area Network - WAN) a partir de Redes de Áreas Locais (LANs) existentes. Ela difere do frame relay ou do ATM em seu meio de transporte. As VPNs transmitem através de IP usando datagramas como a camada de transporte, tornando-o um condutor seguro através da Internet, para um determinado destino. A maioria das implementações VPN de software livre incorporam métodos de criptografia de padrão aberto para mascarar ainda mais os dados em trânsito.
Algumas empresas aplicam soluções VPN de hardware para aumentar a segurança, enquanto outras usam software ou implementações baseadas em protocolos. Há diversos fabricantes de soluções VPNde hardware como Cisco, Nortel, IBM e Checkpoint. Existe uma solução VPN baseada em software livre para Linux chamada FreeS/Wan, que utiliza uma implementação Internet Protocol Security (IPSec). Estas soluções VPN, independentemente de serem baseadas em hardware ou software, atuam como roteadores especializados situados entre as conexões IP de dois escritórios.

46.7.1. Como um VPN Funciona?

Quando um pacote é transmitido a partir de um cliente, é enviado através do roteador ou gateway VPN, o qual adiciona um Cabeçalho de Autenticação (Authentication Header - AH) para o roteamento e autenticação. Os dados são então criptografados e, finalmente, fechados com um Encapsulating Security Payload (ESP). Este último estabelece as instruções de descriptografia e manuseio.
O roteador VPN receptor depura as informações de cabeçalho, descriptografa os dados e os roteia ao destino pretendido (uma estação de trabalho ou um nó em uma rede). Usando uma conexão rede-a-rede, o nó receptor da rede local recebe os pacotes descriptografados e prontos para processar. O processo de criptografia/descriptografia numa conexão VPN rede-a-rede é transparente para o nó local.
Com um nível tão elevado de segurança, não basta ao cracker interceptar o pacote, mas também descriptografar o pacote. Intrusos que aplicarem um ataque man-in-the-middle entre um servidor e o cliente também devem ter acesso à pelo menos uma das chaves privadas para sessões de autenticação. Como aplicam diversas camadas de autenticação e criptografia, as VPNs são um meio seguro e efetivo para conectar múltiplos nós remotos para atuar como uma intranet unificada.

46.7.2. VPNs e o Red Hat Enterprise Linux

Os usuários do Red Hat Enterprise Linux têm várias opções em termos de implementação de uma solução de software para conectar à sua WAN com segurança. A Segurança do Protocolo de Internet, ou IPsec, é a implementação VPN suportada pelo Red Hat Enterprise Linux que atende às necessidades de usabilidade de empresas com filiais ou usuários remotos.

46.7.3. IPsec

O Red Hat Enterprise Linux suporta o IPsec para conectar hosts e redes remotos entre si usando um túnel seguro em uma rede de transporte comum, como a Internet. O IPsec pode ser implementado usando uma configuração host-a-host (uma estação de trabalho conectada a outra) ou rede-a-rede (uma LAN/WAN conectada à outra).
A implementação do IPsec no Red Hat Enterprise Linux usa Troca de Chave de Internet (Internet Key Exchange, IKE), um protocolo implementado pelo IETF (Internet Engineering Task Force) para ser usado em autenticação mútua e proteger associações entre sistemas conectados.

46.7.4. Criando uma Conexão IPsec

Uma conexão IPsec é dividida em duas fases lógicas. Na fase 1, um nó do IPsec inicia a conexão com o nó ou rede remota. O nó/rede remota verifica as credenciais do nó solicitante e ambas partes negociam o método de autenticação da conexão.
Nos sistemas Red Hat Enterprise Linux, uma conexão IPsec usa o método de chave pré-compartilhada (pre-shared key) para autenticação do nó IPsec. Numa conexão IPsec com chave pré-compartilhada, ambos hosts devem usar a mesma chave para prosseguir à segunda fase da conexão IPsec.
Durante a fase 2 de uma conexão IPsec é criada uma associação de segurança (security association, SA) entre os nós IPsec. Essa fase estabelece um banco de dados de SAs com informações de configuração, como o método de criptografia, parâmetros de troca de chaves de sessões secretas, dentre outras. Essa fase administra a conexão IPsec entre nós e redes remotas.
A implementação do IPsec no Red Hat Enterprise Linux usa IKE para compartilhar chaves entre hosts ao longo da Internet. O daemon do chaveiro racoon é responsável pela distribuição e troca de chaves IKE. Consulte a página man do racoon para maiores informações sobre este daemon.

46.7.5. Instalação do IPsec

A implementação do IPsec requer a instalação do pacote RPM ipsec-tools em todas os hosts IPsec (se usar uma configuração host-a-host) ou roteadores IPsec (se usar uma configuração rede-a-rede). O pacote RPM contém bibliotecas, daemons e arquivos de configuração essenciais para auxiliar na configuração da conexão IPsec , incluindo:
  • /sbin/setkey — manipula o gerenciamento da chave e atributos de segurança do IPsec no kernel. Este executável é controlado pelo daemon de gerenciamento da chave racoon. Para mais informações, consulte a página man (8) do setkey.
  • /usr/sbin/racoon — the IKE key management daemon, used to manage and control security associations and key sharing between IPsec-connected systems.
  • /etc/racoon/racoon.conf — o arquivo de configuração do daemon do racoon usado para configurar vários aspectos da conexão IPsec, incluindo métodos de autenticação e algoritmos de criptografia usados na conexão. Para uma lista completa das diretivas disponíveis, consulte a página man (5) do racoon.conf.
Para configurar o IPsec no Red Hat Enterprise Linux, você pode usar a Ferramenta de Administração de Rede, ou editar manualmente os arquivos de configuração de rede e do IPsec.

46.7.6. Configuração Host-a-Host do IPsec

O IPsec pode ser configurado para conectar um computador pessoal ou estação de trabalho a outra através de uma conexão host-a-HOST. Este tipo de conexão utiliza a rede à qual cada host está conectado para criar um túnel seguro entre eles. Os requisitos de uma conexão host-a-host são mínimos, assim como a configuração do IPsec em cada host. Os hosts precisam somente de uma conexão dedicada a uma rede de transporte (como a Internet) e do Red Hat Enterprise Linux para criar a conexão do IPsec.

46.7.6.1. Conexão Host-a-Host

Uma conexão host-a-host do IPsec é uma conexão criptografada entre dois sistemas ambos rodando o IPsec com a mesma chave de autenticação. Enquanto a conexão do IPsec estiver ativa, qualquer tráfego na rede entre os dois hosts é criptografado.
Para configurar um conexão host-a-host do IPsec, use os seguintes passos em cada host:

Nota

Você deve executar os seguintes procedimentos na máquina que você estiver configurando. Evite a tentar configurar e estabelecer conexões IPsec remotamente.
  1. Em uma janela de comandos, digite system-config-network para iniciar a Ferramenta de Administração de Rede.
  2. Na aba IPsec, clique no botão Nova para iniciar o assistente de configuração do IPsec.
  3. Clique em Avançar para iniciar a configuração de uma conexão host-a-host do IPsec.
  4. Enter a unique name for the connection, for example, ipsec0. If required, select the check box to automatically activate the connection when the computer starts. Click Forward to continue.
  5. Selecione Criptografia Host a Host como tipo de conexão, e então clique em Avançar.
  6. Selecione o tipo de criptografia a ser usado: manual ou automático.
    Se você selecionar criptografia manual, uma chave de criptografia deve ser fornecida mais tarde durante o processo. Se você selecionar criptografia automática, o daemon do racoon gerencia a chave de criptografia. O pacote ipsec-tools deve ser instalado se você quiser usar criptografia automática.
    Clique em Avançar para continuar.
  7. Digite o endereço IP do host remoto.
    Para determinar o endereço IP do host remoto, use o seguinte comandono host remoto:
    ifconfig <device>
    onde <device> é o dispositivo Ethernet que você deseja usar para a conexão VPN.
    Se houver apenas uma placa de Ethernet no sistema, o nome do dispositivo normalmente é eth0. O seguinte exemplo, mostra as informações relevantes deste comando (note que isto é apenas um exemplo de saída):
    eth0      Link encap:Ethernet  HWaddr 00:0C:6E:E8:98:1D
              inet addr:172.16.44.192  Bcast:172.16.45.255  Mask:255.255.254.0
    O endereço IP é o número que aparece após a etiqueta inet addr:.

    Nota

    Para conexões de host-to-host, ambos os hosts devem possuir um endereço rotável público. Como forma alternativa, ambos os hosts podem ter um endereço não-rotável privado (por exemplo, das classes 10.x.x.x or 192.168.x.x) desde que estejam na mesma LAN.
    If the hosts are on different LANs, or one has a public address while the other has a private address, refer to Seção 46.7.7, “Configuração Rede-a-Rede do IPsec”.
    Clique em Avançar para continuar.
  8. If manual encryption was selected in step 6, specify the encryption key to use, or click Generate to create one.
    1. Especifique um chave de autenticação ou clique em Gerar para criar uma. Pode ser qualquer combinação de números e letras.
    2. Clique em Avançar para continuar.
  9. Verifique a informação na página IPsec — Resumo e então clique em Aplicar.
  10. Click File > Save to save the configuration.
    Você pode precisar reiniciar a rede para que as mudanças surtam efeito. Para reiniciar a rede, use o seguinte comando:
    service network restart
  11. Selecione a conexão IPsec na lista e clique no botão Ativar.
  12. Repeat the entire procedure for the other host. It is essential that the same keys from step 8 be used on the other hosts. Otherwise, IPsec will not work.
After configuring the IPsec connection, it appears in the IPsec list as shown in Figura 46.10, “IPsec Connection”.
IPsec Connection
IPsec Connection
Figura 46.10. IPsec Connection

Os seguintes arquivos são criados quando a conexão IPsec for configurada:
  • /etc/sysconfig/network-scripts/ifcfg-<nickname>
  • /etc/sysconfig/network-scripts/keys-<nickname>
  • /etc/racoon/<remote-ip>.conf
  • /etc/racoon/psk.txt
Se a criptografia automática também for selecionada, /etc/racoon/racoon.conf também é criado.
Assim que a interface estiver ativa, o /etc/racoon/racoon.conf é modificado para incluir o <ip-remoto>.conf.

46.7.6.2. Configuração Manual Host-a-Host do IPsec

O primeiro passo para criar uma conexão é coletar as informações de sistemas e de rede de cada estação de trabalho. Para uma conexão host-a-host, você precisa das seguintes informações:
  • O endereço IP de cada host
  • Um nome único, por exemplo, ipsec1. Este nome é usado para identificar a conexão IPsec e para distinguí-la de outros dispositivos ou conexões.
  • Uma chave fixa de criptografia ou uma gerada automaticamente pelo racoon.
  • Uma chave de autenticação pré-compartilhada, usada durante o estágio inicial da conexão e para trocar chaves de criptografia durante a sessão.
Por exemplo, suponha que as estações de trabalho A e B queiram se interconectar através de um túnel IPsec. Elas querem se conectar usando uma chave pré-compartilhada com o valor Key_Value01 e os usuários concordam em deixar que o racoon gere automaticamente e compartilhe uma chave de autenticação entre cada host. Usuários de ambos os hosts decidem chamar suas conexões de ipsec1.

Nota

Você deve escolher uma PSK que use uma mistura de caracteres de caixa alta e baixa, números e pontuação. Uma PSK fácil de adivinhar constitui um risco à segurança.
Não é necessário usar a mesmo nome de conexão para cada host. Você deve escolher um nome que seja conveniente e significativo para a sua instalação.
Veja a seguir o arquivo de configuração do IPsec da Estação de Trabalho A para uma conexão host-a-host do IPsec com a Estação de Trabalho B. O nome único para identificar a conexão, neste exemplo, é ipsec1, e portanto o arquivo resultante é chamado /etc/sysconfig/network-scripts/ifcfg-ipsec1.
DST=X.X.X.X
TYPE=IPSEC
ONBOOT=no
IKE_METHOD=PSK
A Estação de Trabalho A substituirá X.X.X.X pelo endereço IP da estação de trabalho B, enquanto esta deve substituir X.X.X.X pelo endereço IP da estação de trabalho A. Esta conexão não está configurada para iniciar na inicialização (ONBOOT=no) e usa o método de autenticação de chave pré-compartilhada (IKE_METHOD=PSK).
Veja a seguir o conteúdo do arquivo da chave pré-compartilhada (chamado /etc/sysconfig/network-scripts/keys-ipsec1) que ambas estações de trabalho precisam para autenticarem-se entre si. O conteúdo deste arquivo deve ser idêntico nas duas estações de trabalho, e somente o usuário root deve poder acessar ou gravar (read or write) este arquivo.
IKE_PSK=Key_Value01

Importante

Para alterar o arquivo keys-ipsec1 para que somente o usuário root possa acessá-lo ou editá-lo, execute o seguinte comando após criar o arquivo:
chmod 600 /etc/sysconfig/network-scripts/keys-ipsec1
Para alterar a chave de autenticação a qualquer momento, edite o arquivo keys-ipsec1 nas duas estações de trabalho. As duas chaves devem ser idênticas para que a conexão funcione apropriadamente.
O próximo exemplo mostra a configuração específica para a conexão da fase 1 ao host remoto. O arquivo é nomeado como X.X.X.X.conf, onde X.X.X.X é substituído pelo endereço IP do host IPsec remoto. Note que este arquivo é gerado automaticamente quando o túnel IPsec é ativado e não deve ser editado diretamente.
remote X.X.X.X
{
         exchange_mode aggressive, main;
	 my_identifier address;
	 proposal {
	 	encryption_algorithm 3des;
		hash_algorithm sha1;
		authentication_method pre_shared_key;
		dh_group 2 ;
	}
}
O arquivo de configuração padrão da fase 1, criado quando uma conexão IPsec é iniciada, contém as seguintes declarações usadas pela implementação IPsec do Red Hat Enterprise Linux:
remote X.X.X.X
Especifica que as declarações subseqüentes deste arquivo de configuração aplicam-se somente ao nó remoto identificado pelo endereço IP X.X.X.X.
exchange_mode aggressive
A configuração padrão do IPsec no Red Hat Enterprise Linux usa um método de autenticação agressivo, que reduz a sobrecarga da conexão enquanto permite a configuração de diversas conexões IPsec com hosts múltiplos.
my_identifier address
Define o método de identificação a ser usado na autenticação dos nós. O Red Hat Enterprise Linux usa endereços IP para identificar os nós.
encryption_algorithm 3des
Define a cifra de criptografia usada durante a autenticação. Por padrão, o Triple Data Encryption Standard (3DES) é usado.
hash_algorithm sha1;
Especifica o algoritmo de hash usado durante a negociação entre nós da fase 1. Por padrão, usa-se o Secure Hash Algorithm versão 1.
authentication_method pre_shared_key
Define o método de autenticação usado durante a negociação dos nós. Por padrão, o Red Hat Enterprise Linux usa chaves pré-compartilhadas para autenticação.
dh_group 2
Especifica o número do grupo Diffie-Hellman para estabelecer chaves de sessões geradas dinamicamente. Por padrão, modp1024 (grupo 2) é usado.
46.7.6.2.1. O Arquivo de Configuração do Racoon
Os arquivos /etc/racoon/racoon.conf devem ser idênticos em todos os nós IPsec, exceto pela declaração include "/etc/racoon/X.X.X.X.conf". Esta declaração (e o arquivo que referencia) é gerada quando o túnel IPsec é ativado. Para a Estação de Trabalho A, X.X.X.X na declaração include é o endereço IP da Estação de Trabalho B. O oposto vale para a Estação de Trabalho B. Veja a seguir um arquivo racoon.conf típico quando a conexão IPsec é ativada.
# Racoon IKE daemon configuration file.
# See 'man racoon.conf' for a description of the format and entries.

path include "/etc/racoon";
path pre_shared_key "/etc/racoon/psk.txt";
path certificate "/etc/racoon/certs";

sainfo anonymous
{
        pfs_group 2;
        lifetime time 1 hour ;
        encryption_algorithm 3des, blowfish 448, rijndael ;
        authentication_algorithm hmac_sha1, hmac_md5 ;
        compression_algorithm deflate ;
}
include "/etc/racoon/X.X.X.X.conf";
Este arquivo racoon.conf padrão inclui localidades definidas para a configuração do IPsec, arquivos de chaves pré-compartilhadas e certificados. Os campos sainfo anonymous descrevem a SA da fase 2 entre os nós IPsec — a natureza da conexão IPsec (incluindo os algoritmos suportados de criptografia usados) e o método de troca de chaves. A lista a seguir define os campos da fase 2:
sainfo anonymous
Denota que a SA pode iniciar anonimamente com qualquer par desde que as credenciais IPsec coincidam.
pfs_group 2
Define o protocolo Diffie-Hellman de troca de chaves, o que determina o método através do qual os nós do IPsec estabelecem uma chave de sessão temporária mútua para a segunda fase da conectividade IPsec. Por padrão, a implementação IPsec do Red Hat Enterprise Linux usa o grupo 2 (ou modp1024) dos grupos de troca de chave criptográfica Diffie-Hellman. O grupo 2 usa uma exponenciação modular de 1024 bits, evitando que atacantes descriptografem transmissões IPsec anteriores, mesmo que uma chave privada seja comprometida.
lifetime time 1 hour
Este parâmetro especifica o ciclo de vida de uma SA e pode ser quantificado por hora ou bytes de dados. A implementação IPsec do Red Hat Enterprise Linux especifica o tempo de uma hora.
encryption_algorithm 3des, blowfish 448, rijndael
Especifica as cifras de criptografia suportadas para a fase 2. O Red Hat Enterprise Linux suporta 3DES, 448-bit Blowfish e Rijndael (a cifra usada no Advanced Encryption Standard ou AES).
authentication_algorithm hmac_sha1, hmac_md5
Lista os algoritmos de hash suportados para autenticação. Os modos suportados são os códigos de autenticação de mensagem sha1 e md5 hashed (HMAC).
compression_algorithm deflate
Define o algoritmo Deflate de compressão para suporte à IP Payload Compression (IPCOMP), que permite a transmissão potencialmente mais rápida de datagramas IP através de conexões lentas.
Para iniciar a conexão, execute o seguinte comando em cada host:
ifup <nickname>
onde <apelido> é o nome que você especificou para a conexão IPsec.
To test the IPsec connection, run the tcpdump utility to view the network packets being transferred between the hosts and verify that they are encrypted via IPsec. The packet should include an AH header and should be shown as ESP packets. ESP means it is encrypted. For example:
~]# tcpdump -n -i eth0 host <targetSystem>

IP 172.16.45.107 > 172.16.44.192: AH(spi=0x0954ccb6,seq=0xbb): ESP(spi=0x0c9f2164,seq=0xbb)

46.7.7. Configuração Rede-a-Rede do IPsec

IPsec can also be configured to connect an entire network (such as a LAN or WAN) to a remote network using a network-to-network connection. A network-to-network connection requires the setup of IPsec routers on each side of the connecting networks to transparently process and route information from one node on a LAN to a node on a remote LAN. Figura 46.11, “A network-to-network IPsec tunneled connection” shows a network-to-network IPsec tunneled connection.
A network-to-network IPsec tunneled connection
A network-to-network IPsec tunneled connection
Figura 46.11. A network-to-network IPsec tunneled connection

O diagrama mostra duas LANs separadas pela Internet. Estas LANs usam roteadores IPsec para autenticar e iniciar uma conexão, usando um túnel seguro através da Internet. Os pacotes interceptados em trânsito requerem descriptografia de força bruta para quebrar a cifra protegendo os pacotes entre estas LANs. O processo de comunicação entre um nó no intervalo de IP 192.168.1.0/24 e outro no 192.168.2.0/24 é completamente transparente aos nós, já que o processamento, criptografia/descriptografia e roteamento dos pacotes IPsec são executados inteiramente pelo roteador IPsec.
As informações necessárias para uma conexão rede-a-rede incluem:
  • Os endereços IP externamente acessíveis dos roteadores IPsec dedicados
  • Os intervalos de endereços de rede da LAN/WAN servida pelos roteadores IPsec, tal como 192.168.1.0/24 ou 10.0.1.0/24)
  • Os endereços IP dos dispositivos de gateway que roteiam os dados dos nós da rede para a Internet
  • Um nome único, por exemplo, ipsec1. Este nome é usado para identificar a conexão IPsec e para distinguí-la de outros dispositivos ou conexões.
  • Uma chave fixa de criptografia ou uma gerada automaticamente pelo racoon
  • Uma chave de autenticação pré-compartilhada, usada durante o estágio inicial da conexão e para trocar chaves de criptografia durante a sessão.

46.7.7.1. Configuração Rede-a-Rede (VPN)

Uma conexão IPsec rede-a-rede usa dois roteadores IPsec, um para cada rede, através dos quais o tráfego de rede para as sub-redes privadas é roteado.
For example, as shown in Figura 46.12, “Network-to-Network IPsec”, if the 192.168.1.0/24 private network sends network traffic to the 192.168.2.0/24 private network, the packets go through gateway0, to ipsec0, through the Internet, to ipsec1, to gateway1, and to the 192.168.2.0/24 subnet.
Roteadores IPsec devem ter endereços IP endereçáveis publicamente, bem como outro dispositivo de Ethernet conectado às suas respectivas redes privativas. O tráfego passa por um roteador IPsec apenas se for destinado ao outro roteador IPsec com o qual uma conexão criptografada existe.
Network-to-Network IPsec
Network-to-Network IPsec
Figura 46.12. Network-to-Network IPsec

Opções de configuração de rede alternativas incluem um firewall entre cada roteador de IP e a Internet, e um firewall de intranet entre cada roteador IPsec e gateway de sub-rede. O roteador IPsec e a gateway para a sub-rede podem ser um mesmo sistema com dois dispositivos de Ethernet: um com um endereço IP público que age como o roteador IPsec; e um com um endereço IP privativo que age como a gateway para a sub-rede privativa. Cada roteador IPsec pode usar a gateway para sua própria rede privativa ou uma gateway pública para enviar os pacotes para o outro roteador IPsec.
Use o seguinte procedimento para configurar uma conexão IPsec rede-a-rede:
  1. Em uma janela de comandos, digite system-config-network para iniciar a Ferramenta de Administração de Rede.
  2. Na aba IPsec, clique no botão Nova para iniciar o assistente de configuração do IPsec.
  3. Clique em Avançar para começar a configurar uma conexão IPsec rede-a-rede.
  4. Enter a unique nickname for the connection, for example, ipsec0. If required, select the check box to automatically activate the connection when the computer starts. Click Forward to continue.
  5. Selecione Criptografia de Rede-a-Rede (VPN) como tipo de conexão, e então clique em Avançar.
  6. Selecione o tipo de criptografia a ser usado: manual ou automático.
    Se você selecionar criptografia manual, uma chave de criptografia deve ser fornecida mais tarde durante o processo. Se você selecionar criptografia automática, o daemon do racoon gerencia a chave de criptografia. O pacote ipsec-tools deve ser instalado se você quiser usar criptografia automática.
    Clique em Avançar para continuar.
  7. Na página Rede Local, forneça as seguintes informações:
    • Endereço da Rede Local — O endereço IP do dispositivo no roteador IPsec conectado à rede privativa.
    • Máscara da Sub-Rede Local — A máscara da sub-rede do endereço IP da rede local.
    • Gateway da Rede Local — A gateway para a sub-rede privativa.
    Clique em Avançar para continuar.
    Local Network Information
    Local Network Information
    Figura 46.13. Local Network Information

  8. Na página Rede Remota, forneça as seguintes informações
    • Endereço IP Remoto — O endereço IP endereçável publicamente do roteador IPsec para a outra rede privativa. Em nosso exemplo, para o ipsec0, use o endereço IP endereçável publicamente do ipsec1, e vice versa.
    • Endereço da Rede Remota — O endereço de rede da sub-rede privativa atrás do outro roteador IPsec. No nosso exemplo, use 192.168.1.0 se estiver configurando o ipsec1, e use 192.168.2.0 se estiver configurando o ipsec0.
    • Máscara da Sub-Rede Remota — A máscara da sub-rede do endereço IP remoto.
    • Gateway da Rede Remota — O endereço IP da gateway do endereço de rede remoto.
    • If manual encryption was selected in step 6, specify the encryption key to use or click Generate to create one.
      Especifique uma chave de autenticação ou clique em Gerar para criar uma. Esta chave pode ser qualquer combinação de números e letras.
    Clique em Avançar para continuar.
    Remote Network Information
    Remote Network Information
    Figura 46.14. Remote Network Information

  9. Verifique a informação na página IPsec — Resumo e então clique em Aplicar.
  10. Select File > Save to save the configuration.
  11. Selecione a conexão IPsec da lista, e então clique em Ativar para ativar a conexão.
  12. Habilitar encaminhamento de IP:
    1. Edit /etc/sysctl.conf and set net.ipv4.ip_forward to 1.
    2. Execute o seguinte comando para habilitar a alteração:
      sysctl -p /etc/sysctl.conf
O script de rede para ativar a conexão IPsec cria as rotas de rede automaticamente para enviar pacotes através do roteador IPsec, se necessário.

46.7.7.2. Configuração Manual de IPsec Rede-a-Rede

Por exemplo, suponha que a LAN A (lana.example.com) e LAN B (lanb.example.com) queiram se interconectar através de um túnel IPsec. O endereço de rede da LAN A está no intervalo 192.168.1.0/24, enquanto a LAN B usa o intervalo 192.168.2.0/24. O endereço IP da gateway é 192.168.1.254 para a LAN A e 192.168.2.254 para a LAN B. Os roteadores IPsec estão separados de cada gateway da LAN e usam dois dispositivos de rede: à eth0 é atribuído um endereço IP estático acessível externamente, que acessa à Internet, enquanto a eth1 atua como um ponto de roteamento para processar e transmitir pacotes da LAN de um nó da rede a outros nós da rede remota.
A conexão IPsec entre as redes usa uma chave pré-compartilhada com o valor r3dh4tl1nux, e os administradores de A e B concordam em deixar que o racoon gere automaticamente e compartilhe uma chave de autenticação entre cada um dos roteadores IPsec. O administrador da LAN A decide nomear a conexão IPsec como ipsec0, enquanto o administrador da LAN B nomeia a conexão IPsec como ipsec1.
Veja o conteúdo do arquivo ifcfg para uma conexão IPsec rede-a-rede para a LAN A. O nome único para identificar a conexão neste exemplo é ipsec0, portanto o arquivo resultante é nomeado como /etc/sysconfig/network-scripts/ifcfg-ipsec0.
TYPE=IPSEC
ONBOOT=yes
IKE_METHOD=PSK
SRCGW=192.168.1.254
DSTGW=192.168.2.254
SRCNET=192.168.1.0/24
DSTNET=192.168.2.0/24
DST=X.X.X.X
A seguinte lista descreve o conteúdo deste arquivo:
TYPE=IPSEC
Especifica o tipo de conexão.
ONBOOT=yes
Especifica que a conexão deve ser iniciada durante a inicialização do sistema.
IKE_METHOD=PSK
Especifica que a conexão usa autenticação usa o método de autenticação de chaves pré-compartilhadas.
SRCGW=192.168.1.254
O endereço IP da gateway da fonte. Para a LAN A, é a gateway da LAN A, e para a LAN B, é a gateway da LAN B.
DSTGW=192.168.2.254
O endereço IP da gateway do destino. Para a LAN A, é a gateway da LAN B, e vice-versa.
SRCNET=192.168.1.0/24
Especifica a rede fonte para a conexão IPsec, a qual é, neste exemplo, o intervalo de rede da LAN A.
DSTNET=192.168.2.0/24
Especifica a rede de destino para a conexão IPsec, a qual é, neste exemplo, o intervalo de rede da LAN B.
DST=X.X.X.X
O endereço IP externamente acessível da LAN B.
Veja a seguir o conteúdo do arquivo da chave pré-compartilhada, chamado /etc/sysconfig/network-scripts/keys-ipsecX (onde X é 0 para a LAN A e 1 para a LAN B), que as duas redes usam para autenticarem-se entre si. O conteúdo destes arquivos deve ser idêntico e somente o usuário root deve poder acessar ou gravar este arquivo.
IKE_PSK=r3dh4tl1nux

Importante

Para alterar o arquivo keys-ipsecX para que somente o usuário root possa acessá-lo ou editá-lo, execute o seguinte comando após criar o arquivo:
chmod 600 /etc/sysconfig/network-scripts/keys-ipsec1
Para alterar a chave de autenticação a qualquer momento, edite o arquivo keys-ipsecX nos dois roteadores IPsec. As duas chaves devem ser idênticas para que a conexão funcione apropriadamente.
Veja o conteúdo do arquivo de configuração /etc/racoon/racoon.conf da conexão IPsec. Note que a linha include na parte inferior do arquivo é automaticamente gerada e aparece somente se o túnel IPsec está rodando.
# Racoon IKE daemon configuration file.
# See 'man racoon.conf' for a description of the format and entries.
path include "/etc/racoon";
path pre_shared_key "/etc/racoon/psk.txt";
path certificate "/etc/racoon/certs";

sainfo anonymous
{
	pfs_group 2;
	lifetime time 1 hour ;
	encryption_algorithm 3des, blowfish 448, rijndael ;
	authentication_algorithm hmac_sha1, hmac_md5 ;
	compression_algorithm deflate ;
}
include "/etc/racoon/X.X.X.X.conf"
Veja a seguir o arquivo de configuração específico da conexão à rede remota. O arquivo é nomeado como X.X.X.X.conf (onde X.X.X.X é o endereço IP do roteador IPsec remoto). Note que este arquivo é gerado automaticamente quando o túnel IPsec é ativado e não deve ser editado diretamente.
remote X.X.X.X
{
        exchange_mode aggressive, main;
	my_identifier address;
	proposal {
		encryption_algorithm 3des;
		hash_algorithm sha1;
		authentication_method pre_shared_key;
		dh_group 2 ;
	}
}
Antes de iniciar a conexão IPsec, o encaminhamento de IP deve ser habilitado no kernel. Para habilitar o encaminhamento de IP:
  1. Edit /etc/sysctl.conf and set net.ipv4.ip_forward to 1.
  2. Execute o seguinte comando para habilitar a alteração:
    sysctl -p /etc/sysctl.conf
Para iniciar a conexão IPsec, execute o seguinte comando em cada roteador:
ifup ipsec0
As conexões são ativadas e as duas LANs, A e B, agora podem se comunicar. As rotas são criadas automaticamente através do script de inicialização invocado pela execução do ifup na conexão IPsec. Para visualizar uma lista de rotas da rede, execute o seguinte comando:
ip route list
To test the IPsec connection, run the tcpdump utility on the externally-routable device (eth0 in this example) to view the network packets being transferred between the hosts (or networks), and verify that they are encrypted via IPsec. For example, to check the IPsec connectivity of LAN A, use the following command:
tcpdump -n -i eth0 host lana.example.com
O pacote deve incluir um cabeçalho AH e deve ser exibido como um pacote ESP. ESP significa que está criptografado. Por exemplo (barras invertidas denotam a continuação de uma linha):
12:24:26.155529 lanb.example.com > lana.example.com: AH(spi=0x021c9834,seq=0x358): \
	lanb.example.com > lana.example.com: ESP(spi=0x00c887ad,seq=0x358) (DF) \
	(ipip-proto-4)

46.7.8. Iniciando e Parando uma Conexão IPsecConnection

Se a conexão IPsec não foi configurada para ser ativada durante a inicialização, você pode controlá-la da linha de comandos.
Para iniciar a conexão, use o seguinte comando em cada host para IPsec host-a-host, ou cada roteador IPsec para IPsec rede-a-rede.
ifup <nickname>
onde <apelido> é o apelido configurado anteriormente, como por exemplo, ipsec0.
Para parar a conexão, use o seguinte comando:
ifdown <nickname>

46.8. Firewalls

A segurança da informação é comumente encarada como um processo e não como um produto. Entretanto, implementações de segurança padronizadas geralmente utilizam alguma forma de mecanismo dedicado a controlar os privilégios de acesso e a restringir recursos de rede a usuários que são autorizados, identificáveis e rastreáveis. O Red Hat Enterprise Linux inclui muitas ferramentas poderosas para auxiliar administradores e engenheiros de segurança em questões de controle de acesso em nível de rede.
Os firewalls são um dos componentes centrais da implementação de segurança na rede. Diversos fabricantes comercializam soluções de firewall para suprir todos os nichos do mercado: de usuários domésticos protegendo um PC até soluções de centro de dados para proteger informações corporativas vitais. Firewalls podem ser soluções de hardware ligados intermitentemente, como as aplicações de firewall da Cisco, Nokia e Sonicwall. Também há soluções de software de firewall proprietárias desenvolvidas para os mercados doméstico e corporativo por fabricantes como Checkpoint, McAfee e Symantec.
Apart from the differences between hardware and software firewalls, there are also differences in the way firewalls function that separate one solution from another. Tabela 46.5, “Tipos de Firewall” details three common types of firewalls and how they function:
Tabela 46.5. Tipos de Firewall
Método Descrição Vantagens Desvantagens
NAT Conversão de Endereços de Rede (Network Address Translation - NAT) insere sub-redes IP internas por trás de um ou um pequeno grupo de endereços IP públicos, mascarando todos os pedidos para uma fonte ao invés de várias.
· Pode ser configurado de forma transparente em máquinas de uma LAN
· A proteção de muitas máquinas e serviços atrás de uma ou mais endereços IT externos, simplificam tarefas de administração.
· A restrição de acesso ao usuário para e de uma LAN pode ser configurado ao abrir e fechar portas em um NAT firewall/gateway
· Não pode evitar atividades maldosas uma vez que usuários se conectam a um serviço fora do firewall
Filtro de Pacotes Um firewall de filtragem de pacotes lê cada pacote de dados que passa por dentro e por fora de uma LAN. Pode ler e processar pacotes pela informação do cabeçalho e filtrar o pacote baseado em conjuntos de regras programáveis implementadas pelo administrador do firewall. O kernel do Linux tem a funcionalidade embutida de filtragem de pacotes através do sub-sistema Netfilter do kernel.
· Padronizável através do utilitário de frente de linha iptables
· Não requer qualquer padronização no lado do cliente, assim como a atividade de rede é filtrada em nível roteador ao invés de nível de aplicativo
· Como os pacotes não são transmitidos através de um proxy, o desempenho da rede é mais rápido devido à conexão direta de cliente ao host remoto.
· Não filtra pacotes para conteúdo como o proxy firewalls
· Processa pacotes na camada de protocolo, mas não encontra pacotes de filtro em uma camada de aplicativo
· Arquiteturas de rede complexas podem fazer com que o estabelecimento de regras de filtragem de pacotes se torne difícil, especialmente se for usado com o mascaramento do IP ou sub-redes locais e redes DMZ.
Proxy Firewalls de proxy filtram todos os pedidos de um determinado protocolo ou tipo dos clientes LAN para uma máquina proxy, que então faz estes pedidos à Internet representando o cliente local. Uma máquina proxy atua como um buffer entre usuários remotos maldosos e as máquinas dos clientes internos da rede.
· Oferece aos administradores, controle sob quais aplicativos e protocolos funcionam fora da LAN
· Alguns servidores proxy podem efetuar o cache de dados acessados freqüentemente localmente ao invés de ter que usar uma conexão de Internet para solicitá-lo. Isto ajuda a reduzir o consumo da largura de banda.
· Os serviços proxy podem ser autenticados e monitorados de perto, permitindo um controle mais acirrado sob a utilização dos recursos na rede.
· Os proxies são geralmente aplicativos específicos (HTTP, Telnet, etc.) ou protocolos restritos ( a maioria dos proxies funcionam somente com serviços conectados TCP)
· Os serviços de aplicativos não podem rodar atrás de um proxy, pois seus servidores de aplicativos devem usar uma forma diferenciada de segurança de rede.
· Os proxies podem se tornar um gargalo de rede, pois todas as solicitações e transmissões são passadas através de uma fonte ao invés de vir diretamente de um cliente para um serviço remoto.

46.8.1. Netfilter 6

O kernel do Linux apresenta um sub-sistema de rede poderoso chamado Netfilter. O sub-sistema Netfilter oferece filtragem de pacote de estado (que guarda o estado das conexões inciadas pelos clientes) ou sem estado/'stateless' (na qual cada pacote é analisado individualmente, sem levar em conta pacotes anteriores trocados na mesma conexão), assim como NAT e serviços de mascaramento de IP. O Netfilter também tem a habilidade de danificar as informações do cabeçalho para roteamento avançado e gerenciamento do estado de conexão. O Netfilter é controlado através da funcionalidade iptables.

46.8.1.1. Visão Geral de IPTables

A potência e flexibilidade de Netfilter é implementada usando a ferramenta de administração iptables, uma ferramenta de linha de comando similar na sintáxe aos seus predecendentes, ipchains.
Uma sintáxe semelhante, não significa uma implementação semelhante. No entanto, o ipchains requer um jogo regras intrínsecas para: filtrar caminhos de fontes, filtrar caminhos de destino, filtrar ambas as fontes e portas de conexão de destino.
No entanto, iptables usa o sub-sistema do Netfilter para melhorar a conexão, inspeção e processamento de rede. O iptables inclui registro avançado, ações pré e pós-roteamento, conversão de endereços de rede e encaminhamento de porta; tudo em apenas uma interface de linha de comando.
This section provides an overview of iptables. For more detailed information, refer to Seção 46.9, “IPTables”.

46.8.2. Configurações Básicas de Firewall

Assim como uma parede em uma construção evita que o fogo se alastre, um firewall evita que softwares maliciosos se alastrem em seu computador. Isto também ajuda a evitar que usuários desautorizados acessem seu computador.
Em uma instalação Red Hat Enterprise Linux padrão, um firewall existe entre seu computador ou rede e qualquer rede não confiável, por exemplo a Internet. Isto determina quais serviços no seu computador podem ser acessados por usuários remotos. Um firewall configurado pode aumentar consideravelmente a segurança de seu sistema. É recomendável que você configure um firewall para qualquer sistema Red Hat Enterprise Linux que tenha conexão de Internet.

46.8.2.1. Security Level Configuration Tool

Durante a tela Configuração do Firewall na instalação do Red Hat Enterprise Linux, você teve a opção de habilitar um firewall básico assim como permitir alguns dispositivos básicos, serviços e portas.
After installation, you can change this preference by using the Security Level Configuration Tool.
Para iniciar este aplicativo, use o seguinte comando:
system-config-securitylevel
Security Level Configuration Tool
Configuração de Nível de Segurança
Figura 46.15. Security Level Configuration Tool

Nota

The Security Level Configuration Tool only configures a basic firewall. If the system needs more complex rules, refer to Seção 46.9, “IPTables” for details on configuring specific iptables rules.

46.8.2.2. Habilitando e Desabilitando o Firewall

Selecione uma das seguintes opções para o firewall:
  • Desabilitado — Desabilitar o firewall, oferece acesso completo ao seu sistema e não checa sua segurança. Este ítem deve ser selecionado somente se você estiver rodando em uma rede confiável (não na Internet) ou se precisar configurar um firewall padronizado usando ferramentas de linha de comando iptables.

    Atenção

    Configurações Firewall e qualquer regras firewall padronizadas estão armazenadas no arquivo /etc/sysconfig/iptables. Se você escolher Disabilitado e clicar em OK, estas configurações e regras de firewall serão perdidas.
  • Habilitado — Esta opção configura o sistema para rejeitar conexões recebidas que não estejam na resposta para solicitações de saída, assim como respostas de DNS ou solicitações de DHCP. Se for necessário acessar serviços que estejam rodando nesta máquina, você poderá escolher permitir serviços específicos através do firewall.
    Se você estiver conectando seu sistema à Internet, mas não planeja rodar um servidor, esta escolha é a mais rápida.

46.8.2.3. Serviços Confiáveis

Habilitar opções na lista de serviços Confiáveis permite que serviços específicos passem através do firewall.
WWW (HTTP)
O protocolo HTTP é utilizado pelo Apache ( e por outros servidores de Web) para servir páginas da web. Se você planeja disponibilizar seu servidor de Web ao público, selecione este ítem. Esta opção não é solicitada para visualizar páginas locais ou para desenvolver páginas na web. Este serviço requer a instalação de um pacote httpd.
Habilitar o WWW (HTTP) não abrirá uma porta para HTTPS, a versão SSL do HTTP. Se este serviço for solicitado, selecione Secure WWW (HTTPS).
FTP
O protocolo FTP é utilizado para transferir arquivos entre máquinas em uma rede. Se você planeja disponibilizar seu servidor FTP ao público, selecione este ítem. Este serviço requer a instalação de um pacote vsftpd.
SSH
Secure Shell (SSH) é um conjunto de ferramentas para comandos de registro e execução em uma máquina remota. Para permitir acesso remoto à uma máquina via ssh, selecione este ítem . Este serviço requer a instalação do pacote openssh-server.
Telnet
Telnet é um protocolo para registro de máquinas remotas. Telnet comunicações não são criptografadas e não oferecem nenhuma segurança de snooping de rede. Não é recomendável permitir o acesso de Telnet recebidas. Este serviço requer a instalação do pacote telnet-server.
Mail (SMTP)
SMTP é um protocolo que permite que as hosts remotas se conectem à sua máquina para enviar correio. Você não precisa habilitar este serviço se você coletar seu correio a partir do servidor ISP usando POP3 ou IMAP, ou se você utilizar uma ferramenta como fetchmail. Para permitir o envio de correio de sua máquina, selecione este ítem. Note que um servidor SMTP configurado de maneira imprópria, pode permitir que máquinas remotas usem seu servidor para enviar spam.
NFS4
O Sistema de Arquivo de Rede (NFS) é um arquivo que compartilha protocolos geralmente usados nos sistemas *NIX. Versão 4 deste protocolo é mais seguro do que seus precedentes. Se desejar compartilhar arquivos ou diretórios em seu sistema com outros usuários de rede, selecione este ítem.
Samba
Samba é uma implementação do protocolo de rede SMB do proprietário da Microsoft. Se você precisar compartilhar arquivos , diretórios ou impressoras conectadas localmente com as máquinas Microsoft Windows, selecione este ítem.

46.8.2.4. Outras Portas

The Security Level Configuration Tool includes an Other ports section for specifying custom IP ports as being trusted by iptables. For example, to allow IRC and Internet printing protocol (IPP) to pass through the firewall, add the following to the Other ports section:
194:tcp,631:tcp

46.8.2.5. Salvando Configurações

Clique em OK para salvar mudanças e habilitar ou desabilitar o firewall. Se o Habilitar firewall foi selecionado, as opções selecionadas são traduzidas para os comandos iptables e escritas para o arquivo /etc/sysconfig/iptables. O serviço iptables também é iniciado, assim o firewall é imediatamente ativado após salvar as opções selecionadas. Se o Desabilitar firewall foi selecionado, o arquivo /etc/sysconfig/iptables é removido e o serviço iptables é bloqueado imediatamente.
The selected options are also written to the /etc/sysconfig/system-config-securitylevel file so that the settings can be restored the next time the application is started. Do not edit this file by hand.
Even though the firewall is activated immediately, the iptables service is not configured to start automatically at boot time. Refer to Seção 46.8.2.6, “Ativando o Serviço IPTables” for more information.

46.8.2.6. Ativando o Serviço IPTables

As regras do firewall ficam ativas somente se o serviço iptables estiver rodando. Para iniciá-lo manualmente, use o seguinte comando:
service iptables restart
Para fazer com que o iptables inicie por padrão sempre que o sistema é inicializado, use o seguinte comando:
chkconfig --level 345 iptables on
O serviço ipchains não está incluso no Red Hat Enterprise Linux. No entanto, se o ipchains for instalado (por exemplo, se uma houve uma atualização e o sistema já possuia o ipchains instalado previamente.), os serviços ipchains e iptables não devem ser ativado simultaneamente. Para assegurar-se de que o serviço ipchains está desabilitado e configurado para não iniciar em tempo de inicialização, use os seguintes dois comandos:
service ipchains stop
chkconfig --level 345 ipchains off

46.8.3. Usando IPTables

O primeiro passo para usar o iptables é iniciá-lo. Isto pode ser feito com o comando:
service iptables start

Nota

Os serviços ip6tables devem ser desligados para usar o serviço iptables. Se você desativar o serviço ip6tables, lembre-se de desativar a rede IPv6 também. Nunca deixe um dispositivo de rede ativo sem um firewall compatível.
Para fazer com que o ip6tables inicie por padrão sempre que o sistema for inicializado, use o seguinte comando:
chkconfig --level 345 iptables on
Para fazer com que o iptables inicie sempre que o sistema é inicializado em nível de execução 3,4 ou 5.

46.8.3.1. Sintáxe de Comando IPTables

Os seguintes exemplos do comando iptables ilustram a sintáxe básica do comando:
iptables -A <chain> -j <target>
A opção -A especifica que a regra seja anexada à <chain>. Cada corrente é composta de uma ou mais regras, e portanto também conhecida como um conjunto de regras.
As três correntes internas são INPUT, OUTPUT e FORWARD. Estas correntes são permanentes e não podem ser deletadas. A corrente especifica o ponto no qual um pacote é manipulado.
A opção -j <target> especifica o alvo da regra, ou seja, o que fazer se um pacote combina com a regra. Exemplos de alvos internos são ACCEPT, DROP e REJECT.
A página man do iptables também contém um informações sobre correntes disponíveis, opções e alvos.

46.8.3.2. Normas Básicas de Firewall

Estabelecer normas básicas de firewall cria uma base para construir mais regras definidas pelo usuário detalhadamente.
Cada corrente iptables é composta por uma norma padrão e mais de uma regra que funcione de comum acordo com a norma padrão para definir um conjunto de regras gerais para o firewall.
A política padrão para uma corrente pode tanto derrubar (DROP) quanto aceitar (ACCEPT). Administradores com foco em segurança geralmente escolhem derrubar todos os pacotes como uma norma e só permitem pacotes específicos, analisando-os caso-a-caso. As seguintes regras bloqueiam todos os pacotes entrando e saindo de uma porta de comunicação (gateway) de rede:
iptables -P INPUT DROP
iptables -P OUTPUT DROP
Adicionalmente, é recomendado que qualquer pacote encaminhado — tráfego de rede roteado do firewall para seu nódulo de destino — seja negado também, para restringir os clientes internos da exposição inadvertida à Internet. Para fazer isso, use a seguinte regra:
iptables -P FORWARD DROP
Após definir as normas de correntes, você pode criar novas regras para a sua rede e seus requisitos de segurança em particular.
As seções a seguir descrevem como salvar regars iptables e sublimar algumas das regras que você pode implementar ao longo da construção de seu firewall iptables.

46.8.3.3. Salvando e Restaurando Regras do IPTables

As mudanças para iptables são transitórias. Se o sistema ou o serviço iptables forem reiniciados as regras serão automaticamente liberadas e redefinidas. Para salvar as regras de modo que elas sejam carregadas posteriormente, quando o serviço iptables for iniciado, use o seguinte comando:
service iptables save
As regras são armazenadas no arquivo /etc/sysconfig/iptables e são aplicadas sempre que o serviço é iniciado, reiniciado ou quando a máquina é reinicializada.

46.8.4. Filtros de IPTables Comuns

Prevenir ataques remotos ao acessar uma LAN é um dos mais importantes aspectos de segurança de rede. A integridade de uma LAN deveria ser protegida de usuários remotos maliciosos através do uso de regras severas de firewall.
No entanto, com uma política padrão ajustada para bloquear todos os pacotes de entrada, saída e enviados, é possível que o firewall/gateway e usuários de LAN internos se comunicarem uns com os outros ou com recursos externos.
Para permitir que usuários realizem funções relacionadas à rede e usem aplicativos de rede, os administradores devem abrir certas portas para comunicação.
Por exemplo: para permitir o acesso à porta 80 pelo firewall, adicione a seguinte regra:
iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
Isto permite que usuários naveguem as páginas da web que se comunicam utilizando a porta 80 padronizada. Para permitir o acesso a sites seguros (como https://www.example.com/), você deve abrir a porta 443 também, como se segue:
iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

Importante

Ao criar um conjunto de regras iptables, a ordem é muito importante.
Se uma regra especifica que qualquer pacote de sub-rede 192.168.100.0/24 pode ser derrubado, e é seguido de uma regra que permite os pacotes do 192.168.100.13 (que está dentro da sub-rede restrita derrubada), então a regra adicionada é ignorada.
A regra para permitir pacotes de 192.168.100.13 deve preceder a regra que derruba o lembrete do subnet.
Para inserir uma regra em um local específico em uma corrente existente, use a opção -I. Por exemplo:
iptables -I INPUT 1 -i lo -p all -j ACCEPT
A regra é inserida como a primeira no conjunto INPUT para permitir o tráfego do dispositivo loopback local.
Quando você solicitar acesso remoto à uma LAN, use serviços seguros como o SSH, para conexões remotas criptografadas à serviços LAN.
Administradores com recursos baseados em PPP (tais como, bancos de modem ou grupos de contas ISP) podem utilizar acesso discado para driblar as barreiras firewall de forma segura. Como as conexões são diretas, as conexões de modem estão sempre atrás de um firewall/gateway.
No entanto, para usuários remotos com conexões de banda larga existem exceções para casos especiais. Você pode configurar iptables para aceitar conexões de clientes SSH remotos. Por exemplo, as seguintes regras permitem um acesso remoto SSH:
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT
Estas regras permitem o acesso de entrada e saída para um único sistema, como um PC conectado diretamente à Internet ou firewall/porta de comunicação (gateway). No entanto, não permitem que os nódulos por trás do firewall/porta de comunicação acessem estes serviços. Para permitir o acesso LAN a estes serviços, você pode usar a Conversão de Endereços de Rede (Network Address Translation - NAT) com regras de filtragem do iptables.

46.8.5. Regras FORWARD e NAT

A maioria dos ISPs oferecem somente um número limitado de endereços IP rotáveis publicamente para as organizações que eles servem.
Os administradores devem portanto, encontrar formas alternativas de compartilhar acesso aos serviços de Internet sem disponibilizar os endereços IP públicos a todos os nós da LAN. Usar endereços IP privados é a forma mais comum de permitir que todos os nós em uma LAN acessem devidamente serviços de rede internos e externos.
Roteadores de borda (tais como os firewalls) podem receber transmissões de entrada da Internet e rotear os pacotes aos nós de LAN previstos. Da mesma forma, os firewalls/gateways podem também rotear solicitações de saída de um nó de LAN ao serviço de Internet remoto.
Este envio de trânsito de rede pode, muitas vezes, se tornar perigoso, especialmente com a disponibilidade de ferramentas modernas de quebra, que podem falsificar os endereços IP internos e fazer com que a máquina do atacante remoto aja como um nó em sua LAN.
Para evitar que isto aconteça, o comando iptables oferece um roteamento e envio de políticas que podem ser implementadas para evitar uso anormal de recursos de rede.
A norma FORWARD permite que um administrador controle onde os pacotes podem ser roteados em uma LAN. Por exemplo: para permitir o encaminhamento para a LAN inteira (assumindo que o firewall/porta de comunicação tenha um endereço IP interno na eth 1), as seguintes regras podem ser definidas:
iptables -A FORWARD -i eth1 -j ACCEPT
iptables -A FORWARD -o eth1 -j ACCEPT
Essa regra da acesso para a rede interna aos sistemas por trás do firewall/porta de comunicação. A porta de comuncação roteia os pacotes de um nódulo da LAN para o seu nódulo pretendido, passando todos os pacotes através de seu dispositivo eth1.

Nota

Por padrão, a norma IPV4 nos kernels do Red Hat Enterprise Linux desabilita o suporte para encaminhamento do IP, o que evita que caixas rodando o Red Hat Enterprise Linux funcionem como roteadores de borda dedicados. Para habilitar o encaminhamento do IP, execute o seguinte comando:
sysctl -w net.ipv4.ip_forward=1
A mudança desta configuração é válida somente para sessões atuais, ela não persiste além de um reboot ou uma reinicialização de serviço de rede. Para ajustar permanentemente o envio de IP, edite o arquivo /etc/sysctl.conf como se segue:
Localize a seguinte linha:
net.ipv4.ip_forward = 0
Edite-a para ler como se segue:
net.ipv4.ip_forward = 1
Execute o seguinte comando para ativar a alteração do arquivo sysctl.conf:
sysctl -p /etc/sysctl.conf

46.8.5.1. Pós-roteamento (Postrouting) e Mascaramento de IP

Aceitar pacotes enviados através de dispositivos IP internos de firewall, permite que os nós de LAN se comuniquem entre si. No entanto, eles ainda não podem se comunicar externamente com a Internet.
Para permitir que nódulos da LAN com endereços IP privados comuniquem-se com redes públicas externas, configure o firewall com o mascaramento do IP, que mascara pedidos de nódulos da LAN com endereços IP do dispositivo externo do firewall (neste caso, eth0):
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
A regra usa a tabela de pacotes coincidentes da NAT (-t nat) e especifica a corrente POSTROUTING embutida para a NAT (-A POSTROUTING) no dispositivo de rede externa do firewall (-o eth0).
O POSTROUTING (pós-roteamento) permite que os pacotes sejam alterados como são, deixando de lado os dipositivos externos do firewall.
O alvo -j MASQUERADE é especificado para mascarar o endereço IP privado de um nó com endereço IP externo do firewall/gateway

46.8.5.2. Prerouting (Pré-roteamento)

Se você tem um servidor em sua rede interna que deseja disponibilizar externamente, pode usar o alvo -j DNAT da corrente PREROUTING na NAT para especificar um endereço IP e porta de destino para onde encaminhar os pacotes de entrada requisitando uma conexão.
Por exemplo, se você deseja encaminhar os pedidos HTTP de entrada para seu Servidor HTTP Apache dedicado para 172.31.0.23, submeta o seguinte comando:
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to 172.31.0.23:80
Esta regra especifica que a tabela nat usa a corrente PREROUTING embutida para encaminhar pacotes HTTP de entrada exclusivamente para o endereço IP 172.31.0.23 listado.

Nota

Se você tem uma norma padrão DROP na sua corrente FORWARD, deve adicionar uma regra para permitir o encaminhamento de pedidos HTTP de entrada para possibilitar o roteamento do destino da NAT. Para fazer isso, submeta o seguinte comando:
iptables -A FORWARD -i eth0 -p tcp --dport 80 -d 172.31.0.23 -j ACCEPT
Esta regra permite o encaminhamento de pedidos de entrada HTTP do firewall para seu destino pretendido no ApacheHTTP por trás do firewall.

46.8.5.3. DMZs e IPTables

As regras do iptables também podem ser definidas para rotear tráfego para determinadas máquinas, como um servidor dedicado HTTP ou FTP, numa zona desmilitarizada (DMZ). A DMZ é uma sub-rede local especial dedicada a prover serviços num meio público como a Internet.
Por exemplo: para definir uma regra para rotear os pedidos HTTP externos para um servidor HTTP dedicado no endereço IP 10.0.4.2 (fora do intervalo 192.168.1.0/24 da LAN), a tradução de endereço de rede (NAT) evoca uma tabela PREROUTING para encaminhar os pacotes ao destino apropriado:
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to-destination 10.0.4.2:80
Com este comando, todas as conexões HTTP para a porta 80 de fora da LAN são roteadas ao servidor HTTP em uma rede separada do resto da rede interna. Esta forma de segmentação de rede pode ser mais segura que permitir conexões HTTP para uma máquina na rede.
Se o servidor HTTP estiver configurado para aceitar conexões seguras, então a porta 443 deve ser encaminhada também.

46.8.6. Software Malicioso e Endereços IP Falsificados (spoofed)

More elaborate rules can be created that control access to specific subnets, or even specific nodes, within a LAN. You can also restrict certain dubious applications or programs such as Trojans, worms, and other client/server viruses from contacting their server.
For example, some Trojans scan networks for services on ports from 31337 to 31340 (called the elite ports in cracking terminology).
Já que nao existe nenhum serviço legítimo que comunique através destas portas não padronizadas, ao bloqueá-las você pode diminuir consideravelmente as chances de nós, com vírus em sua rede, se comunicarem de forma independente com seus servidores master remotos.
As regras a seguir, derruban todo o trânsito de TCP que tentar usar a porta 31337:
iptables -A OUTPUT -o eth0 -p tcp --dport 31337 --sport 31337 -j DROP
iptables -A FORWARD -o eth0 -p tcp --dport 31337 --sport 31337 -j DROP
Você também poderá bloquear conexões exteriores que tentem falsificar a variedade de endereços IP privados para infiltrar em sua LAN.
Por exemplo: se uma LAN usa o intervalo 192.168.1.0/24, uma regra pode determinar que o dispositivo de rede, que faz a interface com a Internet (eth0, por exemplo), derrube quaisquer pacotes para este dispositivo com um endereço do intervalo de IP de sua LAN.
Como norma padrão, é recomendado rejeitar pacotes encaminhados, portanto qualquer outro endereço IP espionado ao dispositivo que faz a interface externa (eth0) é rejeitado automaticamente.
iptables -A FORWARD -s 192.168.1.0/24 -i eth0 -j DROP

Nota

Existe uma distinção entre os alvos DROP eREJECT ao lidar com as regrasadicionadas.
O alvo REJECT nega acesso e retorna um erro connection refused (conexão negada) para usuários que tentarem se conectar ao serviço. A ação DROP (derrubar) um alvo, como o nome sugere, derruba os pacotes sem nenhum aviso.
Administradores podem usar seu próprio bom senso ao lidar com estes alvos; entretanto, para evitar a confusão do usuário e tentativas para continuar conectando, recomenda-se usar o alvo REJECT.

46.8.7. IPTables e Rastreamento de Conexão

O iptables inclui um módulo que permite que osadministradores inspecionem e restrinjam conexões a serviços disponíveis numa rede interna, usando um método chamado registro de conexão (connection tracking). O registro de conexão armazena as conexões numa tabela, que possibilita os administradores permitir ou negar acesso baseado nos seguintes estados de conexão:
  • NEW (novo) — Um pacote requisitando uma nova conexão, como um pedido HTTP.
  • ESTABLISHED (estabelecido) — Um pacote que é parte de uma conexão existente.
  • RELATED (relacionado) — Um pacote solicitando uma nova conexão, mas que é parte de uma conexão existente. Por exemplo, conexões FTP usam a porta 21 para estabelecer conexão, mas os dados são transferidos para uma porta diferente (geralmente para a 20).
  • INVALID (inválido) — Um pacote que não faz parte de nenhuma das conexões da tabela de registro das conexões.
Você pode usar a funcionalidade de estado do registro de conexões do iptables com qualquer protocolo de rede, mesmo que o próprio protocolo seja sem estado (como o UDP). O exemplo a seguir mostra uma regra que usa o registro de conexão para encaminhar somente os pacotes associados a uma conexão estabelecida:
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

46.8.8. IPv6

A introdução do Protocolo de Internet de última geração chamado IPv6, vai além do limite de endereços de 32 bits do IPv4 (ou IP). IPv6 suporta endereços de 128 bits e, como tal, redes de transporte cientes do IPv6 são capazes de lidar com um número maior de endereços roteáveis que o IPv4.
O Red Hat Enterprise Linux suporta regras de firewall IPv6 usando o sub-sistema Netfilter 6 e o comando ip6tables. Em Red Hat Enterprise Linux 5, os serviços IPv4 e IPv6 são habilitados por padrão.
A sintáxe é idêntica à do iptables em todos os aspectos, exceto pelo fato do ip6tables suportar endereços de 128 bits. Por exemplo: as conexões SSH em um servidor de rede ciente do IPv6 podem ser possibilitadas pela seguinte regra:
ip6tables -A INPUT -i eth0 -p tcp -s 3ffe:ffff:100::1/128 --dport 22 -j ACCEPT
Para mais informações sobre redes com IPv6, consulte a página de informações sobre o IPv6: http://www.ipv6.org/.

46.8.9. Recursos Adicionais

Há diversos aspectos do firewall e do sub-sistema Netfilter do Linux que não foram abordados neste capítulo. Para mais informações, consulte os seguintes recursos.

46.8.9.1. Documentação Instalada

  • Refer to Seção 46.9, “IPTables” for more detailed information on the iptables command, including definitions for many command options.
  • A página man do iptables também contém um breve resumo das várias opções.

46.8.9.2. Páginas da Web Úteis

46.8.9.3. Documentação Relacionada

  • Red Hat Linux Firewalls, de Bill McCarty; Red Hat Press — uma referência detalhada para a criação de firewalls de rede e servidores usando tecnologia de filtragem de pacote de código aberto como Netfilter e iptables. Inclui tópicos como a análise de registros de firewalls, criação de regras de firewall e a personalização de seu firewall com ferramentas gráficas como lokkit.
  • Linux Firewalls, de Robert Ziegler; New Riders Press. — contém muitas informações sobre a criação de firewalls usando o ipchains do kernel 2.2, assim como o Netfilter e iptables. Tópicos adicionais de segurança, como questões de acesso remoto e sistemas de detecção de intrusão também são abordados.

46.9. IPTables

O Red Hat Enterprise Linux inclui ferramentas avançadas para a filtragem de pacotes de rede — o processo de controlar pacotes enquanto os mesmos, entram, trafegam, e saem da stack de rede do kernel. Versões do kernel anteriores à 2.4 dependiam do ipchains para a filtragem de pacotes e usava listas de regras para pacotes a cada passo do processo de filtragem. O kernel 2.4 introduziu iptables (também chamado de netfilter), que é similar ao ipchains mas expande significativamente o âmbito e o controle disponíveis para a filtragem de pacotes de rede.
Este capítulo trata de noções básicas de filtragem de pacotes, define as diferenças entre ipchains e iptables, explica várias opções disponíveis com os comandos do iptables, e detalha como regras de filtragem podem ser preservadas entre reinicializações do sistema.
Refer to Seção 46.9.7, “Recursos Adicionais” for instructions on how to construct iptables rules and setting up a firewall based on these rules.

Atenção

O mecanismo de firewall padrão nos kernels de versões 2.4 e mais recentes é o iptables, mas o iptables, não pode ser usado se o ipchains já estiver rodando. Se o ipchains estiver presente durante a inicialização do sistema, o kernel emite um erro e falha em iniciar o iptables.
A funcionalidade do ipchains não é afetada por esses erros.

46.9.1. Filtragem de Pacotes

O kernel do Linux usa o Netfilter para a filtragem de pacotes, permitindo que alguns pacotes alcancem ou passem pelo sistema, enquanto outros são barrados. Esta funcionalidade está embutida no kernel do Linux, e possui três tabelas ou listas de regras padrão:
  • filter — A tabela padrão usada para lidar com pacotes de rede.
  • nat — Usada para alterar pacotes que criem uma nova conexão, e também usado para Conversão de Endereços de Rede (Network Address Translation - NAT).
  • mangle — Usada para tipos específicos de alterações de pacotes.
Cada tabela tem um grupo de cadeias embutidas, as quais correspondem às ações executadas no pacote pelo netfilter.
As cadeias embutidas para a tabela filter são as seguintes:
  • INPUT — Aplicável a pacotes de rede que sejam destinados ao host.
  • OUTPUT — Aplicável a pacotes de rede gerados localmente.
  • FORWARD — Aplicável a pacotes de rede roteados através do host.
As cadeias embutidas para a tabela nat são as seguintes:
  • PREROUTING — Altera pacotes de rede assim que eles chegam.
  • OUTPUT — Altera pacotes de rede criados localmente antes que os mesmos sejam enviados.
  • POSTROUTING — Altera pacotes de rede antes que que os mesmos sejam enviados.
As cadeias embutidas para a tabela mangle são as seguintes:
  • INPUT — Altera pacotes de rede destinados ao host.
  • OUTPUT — Altera pacotes de rede criados localmente antes que os mesmos sejam enviados.
  • FORWARD — altera pacotes de rede roteados através do host.
  • PREROUTING — Altera pacotes de rede de entrada antes que eles sejam roteados.
  • POSTROUTING — Altera pacotes de rede antes que que os mesmos sejam enviados.
Cada pacote de rede recebido ou enviado por um sistema Linux está sujeito a pelo menos uma tabela. Entretanto, um pacote pode ser submetido à múltiplas regras em uma tabela antes de chegar ao fim da cadeia. A estrutura e o propósito destas regras podem variar, mas normalmente buscam identificar um pacote vindo de ou indo para um endereço IP específico, ou um grupo de endereços IP, ao usar certos protocolos ou serviços de rede.

Nota

De acordo com a configuração padrão, regras de firewall são salvas nos arquivos /etc/sysconfig/iptables ou /etc/sysconfig/ip6tables.
O serviço iptables inicia antes de qualquer serviço relacionado ao DNS durante a inicialização de um sistema Linux. Isto significa que regras de firewall podem apenas fazer referência a endereços IP numéricos (por exemplo, 192.168.0.1). Nestas regras, endereços não numéricos (por exemplo, host.exemplo.com) produzirão erros.
Independentemente do seu destino, quando pacotes correspondem a uma regra específica em uma das tabelas, um alvo (ou ação) é aplicado aos mesmos. Se a regra especifica um alvo ACCEPT para um pacote correspondente, o pacote ignora o resto das verificações de regras e ganha a permissão para continuar até o seu destino. Se uma regra especifica um alvo DROP, o pacote é negado acesso ao sistema e nada é mandado de volta ao host que emitiu o pacote. Se uma regra especifica um alvo QUEUE, o pacote é passado ao espaço do usuário. Se uma regra especifica o alvo opcional REJECT, o pacote é descartado, mas um pacote de erro é enviado ao emissor do pacote.
Cada cadeia tem uma diretiva padrão para ACCEPT, DROP, REJECT, ou QUEUE. Se nenhuma das regras da cadeia é aplicável ao pacote, o mesmo é tratado de acordo com a diretiva padrão.
O comando iptables configura estas tabelas, e cria novas tabelas se necessário.

46.9.2. Diferenças entre IPTables e IPChains

Tanto o ipchains quanto o iptables usam cadeias de regras que operam dentro do kernel do Linux filtrando pacotes com base na correspondência à certas regras ou conjuntos de regras. Entretanto, o iptables representa uma forma mais extensível de filtrar pacotes, dando ao administrador maior controle sem precisar agregar complexidades desnecessárias ao sistema.
Você deve estar ciente das seguintes diferenças significantes entre o ipchains e o iptables:
Using iptables, each filtered packet is processed using rules from only one chain rather than multiple chains.
Por exemplo, um pacote FORWARD entrando em um sistema usando o ipchains teria que passar pelas cadeias INPUT, FORWARD, e OUTPUT para continuar até o seu destino. Entretanto, o iptables apenas envia pacotes à cadeia INPUT se eles forem destinados ao sistema local, e apenas envia pacotes à cadeia OUTPUT se eles foram gerados pelo sistema local. Assim sendo, é importante colocar a regra projetada para apanhar um certo pacote dentro da cadeia que realmente lida com aquele pacote.
The DENY target has been changed to DROP.
No ipchains, pacotes que correspondessem a uma regra em uma cadeia podiam ser direcionados ao alvo DENY. Este alvo deve ser modificado para DROP no iptables.
Order matters when placing options in a rule.
No ipchains, a ordem das opções de uma regra não importa.
O comando iptables tem uma sintaxe mais rigorosa. O comando iptables solicita que o protocolo (ICMP, TCP, ou UDP) seja especificado antes das portas de origem ou destino.
Network interfaces must be associated with the correct chains in firewall rules.
Por exemplo, interfaces de entrada (opção -i) podem apenas ser usadas em cadeias INPUT ou FORWARD. Da mesma forma, interfaces de saída (opção -o) podem apenas ser usadas em cadeias FORWARD ou OUTPUT.
Ou seja, cadeias INPUT e interfaces de entrada trabalham juntas assim como cadeias OUTPUT e interfaces de saída trabalham juntas. Cadeias FORWARD funcionam tanto com interfaces de entrada quanto de saída.
Cadeias OUTPUT não são mais usadas por interfaces de entrada, e cadeias INPUT não são vistas por pacotes trafegando através das interfaces de saída.
This is not a comprehensive list of the changes. Refer to Seção 46.9.7, “Recursos Adicionais” for more specific information.

46.9.3. Opções de Comando para o IPTables

Regras para a filtragem de pacotes são criadas usando o comando iptables. As seguintes características de um pacote são as mais usadas como critérios:
  • Tipo de Pacote — Especifica o tipo dos pacotes que o comando deve filtrar.
  • Origem/Destino do Pacote — Especifica quais pacotes o comando filtra baseado na origem ou no destino do pacote.
  • Alvo — Especifica qual ação é tomada em relação a pacotes que correspondam aos critérios acima.
Refer to Seção 46.9.3.4, “Opções de Correspondência do IPTables” and Seção 46.9.3.5, “Opções de Alvo” for more information about specific options that address these aspects of a packet.
As opções usadas com regras específicas do iptables devem ser agrupadas de maneira lógica, com base no propósito e condições da regra, para que a mesma seja válida. O resto desta seção explica opções geralmente usadas com o comando iptables.

46.9.3.1. Estrutura das Opções de Comando do IPTables

Muitos dos comandos do iptables tem a seguinte estrutura:
iptables [-t <table-name>] <command> <chain-name> \
			<parameter-1> <option-1> \
			<parameter-n> <option-n>
<nome-da-tabela> — Especifica à qual tabela a regra pertence. Se omitido, a tabela filter é usada.
<comando> — Especifica a ação a ser executada, como acrescentar ou remover uma regra.
<nome-da-cadeia> — Especifica a cadeia a ser editada, criada, ou removida.
Pares <parâmetro>-<opção> — Parametros e ações associadas especificando como proceder quando um pacote corresponde à uma regra.
A extensão e a complexidade de um comando do iptables pode mudar bastante, de acordo com o seu propósito.
Por exemplo, um comando para remover uma regra de uma cadeia pode ser bem curto:
iptables -D <chain-name> <line-number>
Em contraste, um comando que adicione uma regra que filtre pacotes oriundos de uma subnet específica, usando uma variedade de parâmetros e opções específicos, pode ser bem longo. Ao construir comandos iptables, é importante lembrar que alguns parâmetros e opções necessitam parâmetros e opções adicionais para construir uma regra válida. Isto pode produzir um efeito cascata. A regra não é válida até que todos os parâmetros e opções que necessitem de outro grupo de opções estejam concluídos.
Digite iptables -h para ver uma lista abrangente de estruturas de comandos iptables.

46.9.3.2. Opções de Comando

Opções de comando fazem com que o iptables execute uma ação específica. Apenas uma opção de linha de comando é permitida em cada comando iptables. Com a exceção do comando help, todos os comandos são escritos em letras maiúsculas.
Os comandos do iptables são os seguintes:
  • -A — Acrescenta a regra ao final da cadeia especificada. Ao contrário da opção -I descrita abaixo, -A não aceita um número inteiro como argumento. Esta opção sempre acrescenta a regra ao final da cadeia especificada.
  • -C — Verifica uma regra específica antes de adicioná-la à cadeia especificada pelo usuário. Este comando pode lhe ajudar a construir regras complexas do iptables pedindo que você digite parâmetros e opções adicionais.
  • -D <número-inteiro> | <regra> — Remove uma regra da cadeia específica através de um número (por exemplo, 5 para a quinta regra da cadeia), ou através da especificação da regra. A especificação de uma regra deve corresponder exatamente à uma regra existente.
  • -E — Renomeia uma cadeia definida pelo usuário. Uma cadeia definida pelo usuário é qualquer uma que não seja uma das padrões ou pré-existentes (consulte a opção -N abaixo, para maiores informações sobre a criação de cadeias definidas pelo usuário). Esta é uma mudança apenas cosmética, e não afeta a estrutura da tabela.

    Nota

    Se você tentar renomear uma das cadeias padrão, o sistema relatará um erro do tipo Match not found (Correspondente não encontrado). Você não pode renomear as cadeias padrão.
  • -F — Esvazia a cadeia selecionada, o que na verdade remove todas as regras da cadeia. Se nenhuma cadeia for selecionada, este comando esvazia todas as regras de todas as cadeias.
  • -h — Oferece uma lista de estruturas de comandos, assim como um breve resumo dos parâmetros e opções dos comandos.
  • -I [<número-inteiro>] — Insere uma regra na cadeia especificada no lugar especificado pelo argumento inteiro definido pelo usuário. Se nenhum argumento é especificado, a regra é inserida no topo da cadeia.

    Atenção

    Conforme indicado acima, a ordem das regras em uma cadeia determina quais regras são aplicáveis a quais pacotes. É importante lembrar disto ao adicionar regras usando as opções -A ou -I.
    Isto é especialmente relevante ao se adicionar regras usando a opção -I como argumento. Se você especificar um número existente ao adicionar uma regra à uma cadeia, o iptables adiciona a nova regra antes (ou acima) da regra existente.
  • -L — Lista todas as regras da cadeia especificada após o comando. Para listar todas as regras em todas as cadeias na tabela padrão filter, não especifique uma cadeia ou tabela. Caso contrário, a seguinte sintaxe deve ser usada para listar as regras de uma específica cadeia em uma específica tabela:
    iptables -L <chain-name> -t <table-name>
    Additional options for the -L command option, which provide rule numbers and allow more verbose rule descriptions, are described in Seção 46.9.3.6, “Opções de Listagem”.
  • -N — Cria uma nova cadeia com um nome especificado pelo usuário. O nome da cadeia deve ser exclusivo, caso contrário uma mensagem de erro é exibida.
  • -P — Estabelece a diretiva padrão para a cadeia especificada, de modo que quando pacotes passam pela cadeia toda sem encontrar uma regra correspondente, os mesmos são enviados para o alvo específico, como ACCEPT ou DROP.
  • -R — Substitui uma regra na cadeia especificada. O número da regra deve ser especificado após o nome da cadeia. A primeira regra em uma cadeia corresponde à regra número um.
  • -X — Remove uma cadeia especificada pelo usuário. Você não pode remover uma cadeia padrão.
  • -Z — Configura os contadores de bytes e de pacotes de todas as tabelas para zero.

46.9.3.3. Opções de Parâmetros do IPTables

Alguns comandos do iptables, incluindo aqueles usados para adicionar, remover, inserir ou substituir regras em uma cadeia específica, requerem vários parâmetros para construir uma regra de filtragem de pacotes.
  • -c — Restaura os contadores para uma dada regra. Este parâmetro aceita as opções PKTS e BYTES para especificar quais contadores devem ser restaurados.
  • -d — Estabelece o nome de host, endereço IP, ou rede de destino de um pacote que corresponda à uma regra. Ao fazer a correspondência de uma rede, os seguintes formatos de endereços IP e máscaras de rede são suportados:
    • N.N.N.N/M.M.M.M — Onde N.N.N.N é o intervalo de endereços IP e M.M.M.M é a máscara de rede.
    • N.N.N.N/M — Onde N.N.N.N é o intervalo de endereços IP e M é a máscara de bits.
  • -f — Aplica esta regra apenas a pacotes fragmentados.
    Você pode usar a opção do caractere do ponto de exclamação (!) após este parâmetro para especificar que a regra seja aplicada apenas a pacotes não fragmentados.

    Nota

    É desejável que se faça a distinção entre pacotes fragmentados e não fragmentados, mesmo que pacotes fragmentados representem uma parte padrão do protocolo IP.
    A fragmentação hoje em dia é normalmente usada para gerar ataques de DoS usando pacotes mal formados, apesar de ser desenvolvida com o intuito original de permitir que pacotes IP trafegassem por redes com tamanhos de quadro variados. Vale também notar que o IPv6 proíbe totalmente o uso da fragmentação.
  • -i — Estabelece a interface de rede de entrada, como eth0 ou ppp0. Com o iptables, este parâmetro opcional pode ser usado apenas com as cadeias INPUT e FORWARD quando usado com a tabela filter e a cadeia PREROUTING quando usado com as tabelas nat e mangle.
    Este parâmetro também suporta as seguintes opções especiais:
    • Caractere do ponto de exclamação (!) — Reverte a diretiva, o que significa que quaisquer interfaces especificadas são excluídas desta regra.
    • Caractere de mais (+) — Um caractere curinga usado para fazer a correspondência de todas as interfaces que correspondam à string especificada. Por exemplo, o parâmetro -i eth+ aplicaria esta regra a quaisquer interfaces Ethernet, mas excluiria quaisquer outras interfaces, como ppp0.
    Se o parâmetro -i é usado, mas nenhuma interface é especificada, todas as interfaces são afetadas pela regra.
  • -j — Pula para o alvo especificado quando um pacote corresponde à uma regra específica.
    Os alvos padrão são ACCEPT, DROP, QUEUE, e RETURN.
    Opções adicionais estão disponíveis através de módulos carregados como padrão com o pacote RPM do iptables do Red Hat Enterprise Linux. Alvos válidos nestes módulos incluem LOG, MARK, e REJECT, entre outros. Consulte a página man do iptables para maiores informações sobre estes e outros alvos.
    esta opção também pode ser usada para direcionar um pacote correspondendo a uma regra específica para uma cadeia definida pelo usuário fora da cadeia atual para que outras regras também possam ser aplicadas ao pacote.
    Se nenhum alvo é especificado, o pacote passa pela regra sem que nenhuma ação seja executada. O contador desta regra, entretanto, é aumentado em uma unidade.
  • -o — Estabelece as interfaces de rede de saída para uma regra. Esta opção é válida apenas para as cadeias OUTPUT e FORWARD na tabela filter, e para a cadeia POSTROUTING nas tabelas nat e mangle. Este parâmetro aceita as mesmas opções que o parâmetro de interfaces de rede de entrada (-i).
  • -p <protocolo> — Estabelece o protocolo IP afetado pela regra. Pode ser icmp, tcp, udp, ou all (todos), ou pode ser um valor numérico, representando um destes ou um protocolo diferente. Você também pode usar quaisquer dos protocolos listados no arquivo /etc/protocols.
    O protocolo "all" significa que a regra aplica-se a todos os protocolos suportados. Se nenhum protocolo é listado com esta regra, o "all" é usado.
  • -s — Estabelece a origem para um determinado pacote usando a mesma sintaxe do parâmetro de destino (-d).

46.9.3.4. Opções de Correspondência do IPTables

Protocolos de rede diferentes oferecem opções de correspondência especializadas que podem ser configuradas para para corresponder a um determinado pacote usando o protocolo em questão. Entretanto, deve-se primeiro especificar o protocolo no comando iptables. Por exemplo, -p <nome-do-protocolo> habilita opções para o protocolo especificado. Note que você também pode usar a ID do protocolo, ao invés do seu nome. Veja, por exemplo, os seguintes exemplos, cada um dos quais tem o mesmo efeito:
iptables -A INPUT -p icmp --icmp-type any -j ACCEPT
iptables -A INPUT -p 5813 --icmp-type any -j ACCEPT
Definições de serviços aparecem no arquivo /etc/services. Por questões de legibilidade, é recomendável usar os nomes dos serviços ao invés dos números de portas.

Importante

Proteja o arquivo /etc/services para prevenir a edição não autorizada. Se este arquivo for editável, crackers podem usá-lo para habilitar portas na sua máquina as quais você tenha decidido deixar fechadas. Para proteger este arquivo, digite os seguintes comandos como root:
chown root.root /etc/services
chmod 0644 /etc/services
chattr +i /etc/services
Isto previne que o arquivo seja renomeado, removido, ou que tenha links estabelecidos até ele.
46.9.3.4.1. Protocolo TCP
Estas opções de correspondência estão disponíveis para o protocolo TCP (-p tcp):
  • --dport — Estabelece a porta de destino para o pacote.
    Para configurar esta opção, use um nome de serviço de rede (como www ou smtp), um número de porta, ou um intervalo de números de portas.
    Para especificar um intervalo de números de portas, separe os dois números com um dois pontos (:). Por exemplo: -p tcp --dport 3000:3200. O maior intervalo válido aceitável é 0:65535.
    Use um ponto de exclamação (!) após a opção --dport para causar a correspondência de todos os pacotes que não usem aquele serviço ou porta de rede.
    Para visualizar os nomes e aliases de serviços de rede assim como os números de portas que os mesmos usem, veja o arquivo /etc/services.
    A opção de correspondência --destination-port equivale a --dport.
  • --sport — Estabelece a porta de origem do pacote usando as mesmas opções que --dport. A opção de correspondência --source-port equivale a --sport.
  • --syn — Aplica-se a todos os pacotes TCP concebidos para iniciar a comunicação, normalmente chamados de pacotes SYN. Pacotes que carreguem dados não são manuseados.
    Use um ponto de exclamação (!) após a opção --syn para causar a correspondência de todos os pacotes que não sejam SYN.
  • --tcp-flags <tested flag list> <set flag list> — Permite que pacotes TCP que tenham bits (sinalizadores) específicos definidos, correspondam a uma regra.
    A opção de correspondência --tcp-flags aceita dois parâmetros. O primeiro parâmetro é a máscara, uma lista de sinalizadores separados por vírgulas a serem examinados no pacote. O segundo parâmetro é uma lista de sinalizadores separados por vírgulas que devem ser definidos para que a regra corresponda.
    Os sinalizadores possíveis são:
    • ACK
    • FIN
    • PSH
    • RST
    • SYN
    • URG
    • ALL
    • NONE
    Por exemplo, uma regra iptables que contenha a seguinte especificação corresponde apenas a pacotes TCP que tenham o sinalizador SYN definido e os sinalizadores ACK e FIN não definidos:
    --tcp-flags ACK,FIN,SYN SYN
    Use um ponto de exclamação (!) após --tcp-flags para reverter o efeito da opção de correspondência.
  • --tcp-option — Tenta corresponder à opções específicas de TCP que possam ser estabelecidas dentro de um pacote específico. Esta opção de correspondência também pode ser revertida usando o ponto de exclamação (!).
46.9.3.4.2. Protocolo UDP
Estas opções de correspondência estão disponíveis ao protocolo UDP (-p udp):
  • --dport — Especifica a porta de destino para o pacote UDP, usando o nome do serviço, número da porta, ou intervalo de números de portas. A opção de correspondência --destination-port equivale --dport.
  • --sport — Especifica a porta de origem para o pacote UDP, usando o nome do serviço, número da porta, ou intervalo de números de portas. A opção de correspondência --source-port equivale a --sport.
Para especificar um intervalo de números de portas para as opções --dport e --sport, separe os dois números usando dois pontos (:). Por exemplo: -p tcp --dport 3000:3200. O maior intervalo válido aceitável é 0:65535.
46.9.3.4.3. Protocolo ICMP
As seguintes opções de correspondência estão disponíveis para o Internet Control Message Protocol (ICMP) (-p icmp):
  • --icmp-type — Estabelece o nome ou o número do tipo de ICMP a corresponder à regra. Uma lista de nomes de ICMP válidos pode ser obtida digitando o comando iptables -p icmp -h.
46.9.3.4.4. Módulos Adicionais de Opções de Correspondência
Opções de correspondência adicionais estão disponíveis através de módulos carregados pelo comando iptables.
Para usar um módulo de opções de correspondência, carregue o módulo pelo nome, usando a opção -m <nome-do-módulo>, onde <nome-do-módulo> é o nome do módulo.
Vários módulos estão disponíveis por default. Você também pode criar módulos para oferecer funcionalidades adicionais.
A seguinte lista parcial indica os módulos geralmente mais usados:
  • Módulo limit — Coloca um limite no número de pacotes que podem corresponder à uma dada regra.
    Quando usado com o alvo LOG, o módulo limit pode prevenir que uma enxurrada de pacotes correspondentes encham o arquivo de registro do sistema com mensagens repetitivas ou utilizem recursos do sistema demasiadamente.
    Refer to Seção 46.9.3.5, “Opções de Alvo” for more information about the LOG target.
    O módulo limit habilita as seguintes opções:
    • --limit — Estabelece o número máximo de eventos de correspondência para um determinado período de tempo, especificado como um par <valor>/<período>. Por exemplo, o uso de --limit 5/hour permite cinco eventos de correspondência à regra por hora.
      Períodos podem ser especificados em segundos, minutos, horas ou dias.
      Se um modificador não for indicado, o valor padrão 3/hour é usado.
    • --limit-burst — Estabelece um limite ao número de pacotes que podem corresponder à uma regra ao mesmo tempo.
      Esta opção é especificada como um número inteiro e deve ser usada junto com a opção --limit.
      Se nenhum valor for especificado, o valor padrão (5) é usado.
  • Módulo state — Habilita a correspondência de estados.
    O módulo state habilita as seguintes opções:
    • --state — Faz a correspondência de um pacote com os seguintes estados de conexão:
      • ESTABLISHED — O pacote correspondente é associado a outros pacotes em uma conexão estabelecida. Você deve aceitar este estado se você quiser manter uma conexão entre um cliente e um servidor.
      • INVALID — O pacote correspondente não pode ser atrelado à uma conexão conhecida.
      • NEW — O pacote correspondente ou está criando uma nova conexão ou faz parte de uma conexão de duas mãos não vista antes. Você precisa aceitar este estado se você quiser permitir novas conexões a um serviço.
      • RELATED — O pacote correspondente está iniciando uma nova conexão relacionada de alguma forma à uma conexão existente. Um exemplo disto é o FTP, o qual usa uma conexão para controle de tráfego (porta 21), e uma conexão separada para transferência (porta 20).
      Estes estados de conexão podem ser usados um com o outro separando-os por vírgulas, como -m state --state INVALID,NEW.
  • Módulo mac — Habilita a correspondência de hardware usando endereços MAC.
    O módulo mac habilita a seguinte opção:
    • --mac-source — Faz a correspondência usando um endereço MAC da placa de interface de rede que enviou o pacote. Para excluir um endereço MAC de uma regra, coloque um ponto de exclamação (!) após a opção de correspondência --mac-source.
Consulte a página man do iptables para mais opções de correspondência disponíveis aos diversos módulos.

46.9.3.5. Opções de Alvo

Quando um pacote corresponde à uma regra específica, a regra pode direcionar o pacote para uma variedade de alvos diferentes, os quais determinam a ação adequada. Cada cadeia tem um alvo padrão, o qual é usado se nenhuma das regras daquela cadeia corresponde a um pacote, ou se nenhuma das regras que correspondem ao pacote possuem um alvo especificado.
Os seguintes são os alvos padrão:
  • <cadeia-definida-pelo-usuário> — Uma cadeia definida pelo usuário (user-defined chain) dentro da tabela. Nomes de cadeias definidas pelo usuário devem ser exclusivos. Este alvo envia o pacote para a cadeia especificada.
  • ACCEPT — Permite que o pacote chegue até o seu destino ou até outra cadeia.
  • DROP — Descarta o pacote sem responder ao solicitante. O sistema que enviou o pacote não fica sabendo da falha.
  • QUEUE — O pacote é enfileirado para ser posteriormente manuseado por um aplicativo do espaço do usuário.
  • RETURN — Para de verificar o pacote contra regras na cadeia atual. Se o pacote com o alvo RETURN corresponde à uma regra numa cadeia chamada a partir de outra cadeia, o pacote é devolvido à primeira cadeia para que a mesma continue com a verificação de regras a partir de onde tinha parado. Se a regra RETURN for usada em uma cadeia padrão e o pacote não puder retornar à sua cadeia anterior, o alvo padrão para a cadeia atual é usado.
In addition, extensions are available which allow other targets to be specified. These extensions are called target modules or match option modules and most only apply to specific tables and situations. Refer to Seção 46.9.3.4.4, “Módulos Adicionais de Opções de Correspondência” for more information about match option modules.
Existem vários módulos de alvos adicionais, a maioria dos quais são aplicáveis somente à tabelas e situações específicas. Alguns dos módulos de alvos mais populares incluídos por padrão no Red Hat Enterprise Linux são:
  • LOG — Faz um registro de todos os pacotes que correspondem à esta regra. Uma vez que os pacotes são registrados pelo kernel, o arquivo /etc/syslog.conf determina onde estas entradas de registro são escritas. Por padrão, elas são colocadas no arquivo /var/log/messages.
    Opções adicionais podem ser usadas após o alvo LOG para especificar a forma como os registros são feitos:
    • --log-level — estabelece o nível de prioridade de um evento de registro. Consulte a página man do syslog.conf para uma lista de níveis de prioridade.
    • --log-ip-options — Registra quaisquer opções configuradas no cabeçalho de um pacote IP.
    • --log-prefix — Coloca uma string de até 29 caracteres antes da linha do registro quando o mesmo for escrito. Isto pode ser útil ao usar filtros de syslog junto com o registro de pacotes.

      Nota

      Devido a um problema com esta opção, você deve adicionar um espaço após o valor de log-prefix.
    • --log-tcp-options — Registra quaisquer opções configuradas no cabeçalho de um pacote TCP.
    • --log-tcp-sequence — Escreve o número de seqüência TCP do pacote no registro do sistema.
  • REJECT — Manda um pacote de erro de volta ao sistema remoto e descarta o pacote.
    O alvo REJECT aceita --reject-with <tipo> (onde <tipo> é o tipo de rejeição), permitindo que informações mais detalhadas sejam retornadas com o pacote de erro. Caso nenhuma outra opção seja usada, a mensagem port-unreachable é o tipo de erro padrão utilizado. Consulte a página man do iptables para uma lista completa de opções para <tipo>.
Outros alvos adicionais, incluindo vários que são úteis para IP masquerading usando a tabela nat, ou para alteração de pacotes usando a tabela mangle, podem ser encontrados na página man do iptables.

46.9.3.6. Opções de Listagem

O comando de listagem padrão, iptables -L [<nome-da-cadeia>], oferece uma visão geral bem básica das cadeias atuais da tabela padrão filter. Opções adicionais oferecem mais informações:
  • -v — Gera informações detalhadas da saída, como o número de pacotes e bytes processado por cada cadeia, o número de pacotes e bytes que tenham correspondido a cada regra, e quais interfaces aplicam-se à uma dada regra.
  • -x — Expande números para seus valores exatos. Em um sistema de alta utilização, o número de pacotes e bytes processados por uma dada cadeia ou regra pode ser abreviado para Kilobytes, Megabytes (Megabytes) ou Gigabytes. Esta opção força a exibição do número por completo.
  • -n — Exibe endereços IP e números de porta em formato numérico, ao invés do formato padrão de nome de host e serviço de rede.
  • --line-numbers — Lista regras em cada cadeia precedidas por um número representando sua ordem numérica na cadeia. Esta opção é útil ao tentar remover uma regra específica de uma cadeia ou determinar onde inserir uma regra em uma cadeia.
  • -t <nome-da-tabela> — Especifica o nome de uma tabela. Se omitido, a tabela padrão filter é usada.
Os seguintes exemplos ilustram o uso de várias destas opções. Note a diferença na exibição de bytes ao incluir a opção -x.
~]# iptables -L OUTPUT -v -n -x
Chain OUTPUT (policy ACCEPT 64005 packets, 6445791 bytes)
    pkts      bytes target     prot opt in     out     source               destination
    1593   133812 ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0

~]# iptables -L OUTPUT -v -n
Chain OUTPUT (policy ACCEPT 64783 packets, 6492K bytes)
    pkts bytes target     prot opt in     out     source               destination
    1819  153K ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0
~]#

46.9.4. Salvando Regras do IPTables

Regras criadas com o comando iptables são armazenadas na memória. Se o sistema for reiniciado antes que o conjunto de regras do iptables seja salvo, todas as regras são perdidas. Para que as regras do netfilter persistam entre reinicializações do sistema, as mesmas precisam ser salvas. Para salvar as regras do netfilter, digite o seguinte comando como root:
service iptables save
Isto executa o script the inicialização do iptables, o qual roda o programa /sbin/iptables-save e escreve a configuração atual do iptables em /etc/sysconfig/iptables. O arquivo existente /etc/sysconfig/iptables é salvo como /etc/sysconfig/iptables.save.
A próxima vez que o sistema inicializar, o script de inicialização do iptables restaura as regras salvas em /etc/sysconfig/iptables usando o comando /sbin/iptables-restore.
Apesar de ser uma boa idéia testar uma nova regra do iptables antes de submetê-la ao arquivo /etc/sysconfig/iptables, é possível copiar regras do iptables encontradas em versões deste arquivo em um outro sistema para este arquivo. Isto permite a distribuição de grupos de regras do iptables para várias máquinas de forma rápida.
Você também pode salvar as regras do iptables em um arquivo específico para distribuição, backup, ou outros propósitos. Para salvar suas regras do iptables, digite o seguinte comando como root:
iptables-save > <filename>
where <filename> is a user-defined name for your ruleset.

Importante

Se você distribuir o arquivo /etc/sysconfig/iptables para outras máquinas, digite /sbin/service iptables restart para que as novas regras façam efeito.

Nota

Note a diferença entre o command iptables (/sbin/iptables), o qual é usado para manipular as tabelas e cadeias que fazem parte da funcionalidade do iptables, e o service iptables (/sbin/iptables service), o qual é usado para habilitar e desabilitar o iptables em si.

46.9.5. Scripts de Controle do IPTables

Existem dois métodos básicos para controlar o iptables no Red Hat Enterprise Linux:
  • Security Level Configuration Tool (system-config-securitylevel) — A graphical interface for creating, activating, and saving basic firewall rules. Refer to Seção 46.8.2, “Configurações Básicas de Firewall ” for more information.
  • /sbin/service iptables <opção> — Usado para manipular várias funções do iptables usando o seu script de inicialização. As seguintes opções estão disponíveis:
    • start — Se uma firewall estiver configurada (ou seja, /etc/sysconfig/iptables existir), todas as instâncias do iptables atualmente rodando são totalmente paradas e então reiniciadas usando o comando /sbin/iptables-restore. Esta opção apenas funciona caso o módulo de kernel ipchains não esteja carregado. Para verificar se este módulo encontra-se carregado, digite o seguinte comando como root:
      lsmod | grep ipchains
      Se este comando não gerar nenhuma saída, significa que o módulo não encontra-se carregado. Se for necessário, use o comando /sbin/rmmod para remover o módulo.
    • stop — Se uma firewall estiver rodando, as regras da firewall armazenadas na memória são liberadas, e todos os módulos e auxiliares do iptables são descarregados.
      Se a diretiva IPTABLES_SAVE_ON_STOP no arquivo de configuração /etc/sysconfig/iptables-config tiver seu valor padrão alterado para yes, as regras atuais são salvas em /etc/sysconfig/iptables e quaisquer regras existentes são movidas para o arquivo /etc/sysconfig/iptables.save.
      Refer to Seção 46.9.5.1, “Arquivo de Configuração de Scripts de Controle do IPTables” for more information about the iptables-config file.
    • restart — Se uma firewall estiver rodando, as regras da firewall armazenadas na memória são liberadas, e a firewall é reiniciada se estiver configurada em /etc/sysconfig/iptables. Esta opção funciona apenas se o módulo ipchains do kernel estiver carregado.
      Se a diretiva IPTABLES_SAVE_ON_RESTART no arquivo de configuração /etc/sysconfig/iptables-config tiver seu valor padrão alterado para yes, as regras atuais são salvas em /etc/sysconfig/iptables e quaisquer regras existentes são movidas para o arquivo /etc/sysconfig/iptables.save.
      Refer to Seção 46.9.5.1, “Arquivo de Configuração de Scripts de Controle do IPTables” for more information about the iptables-config file.
    • status — Exibe o estado da firewall e lista todas as regras ativas.
      The default configuration for this option displays IP addresses in each rule. To display domain and hostname information, edit the /etc/sysconfig/iptables-config file and change the value of IPTABLES_STATUS_NUMERIC to no. Refer to Seção 46.9.5.1, “Arquivo de Configuração de Scripts de Controle do IPTables” for more information about the iptables-config file.
    • panic — Limpa todas as regras da firewall. A diretiva de todas as tabelas configuradas é mudada para DROP.
      Esta opção pode ser útil se um servidor for comprometido. Ao invés de desconectar fisicamente da rede, ou desligar o sistema, você pode usar esta opção para parar todo e qualquer tráfego subseqüente na rede, mas deixar a máquina em um estado pronto para uma análise ou algum tipo de atividade forense.
    • save — Saves firewall rules to /etc/sysconfig/iptables using iptables-save. Refer to Seção 46.9.4, “Salvando Regras do IPTables” for more information.

Tip

To use the same initscript commands to control netfilter for IPv6, substitute ip6tables for iptables in the /sbin/service commands listed in this section. For more information about IPv6 and netfilter, refer to Seção 46.9.6, “IPTables e IPv6”.

46.9.5.1. Arquivo de Configuração de Scripts de Controle do IPTables

O comportamento dos scripts de inicialização do iptables é controlado pelo arquivo de configuração /etc/sysconfig/iptables-config. A seguir está uma lista de diretivas encontradas neste arquivo:
  • IPTABLES_MODULES — Especifica uma lista, separada por espaços, de módulos adicionais do iptables a serem carregados quando uma firewall for ativada. Estes podem incluir rastreamento de conexão e auxiliares de NAT.
  • IPTABLES_MODULES_UNLOAD — Descarrega módulos ao reiniciar e parar. Esta diretiva aceita os seguintes valores:
    • yes — O valor padrão. Esta opção deve ser usada para que um estado correto para as ações de parar ou reiniciar uma firewall possa ser atingido.
    • no — Esta opção deve ser usada apenas se houverem problemas ao descarregar os módulos do netfilter.
  • IPTABLES_SAVE_ON_STOP — Salva as regras atuais da firewall em /etc/sysconfig/iptables quando a firewall for parada. Esta diretiva aceita os seguintes valores:
    • yes — Salva regras existentes em /etc/sysconfig/iptables quando a firewall for parada, movendo a versão anterior para o arquivo /etc/sysconfig/iptables.save.
    • no — O valor padrão. Não salva regras existentes quando a firewall for parada.
  • IPTABLES_SAVE_ON_RESTART — Salva as regras atuais da firewall quando a firewall for reiniciada. Esta diretiva aceita os seguintes valores:
    • yes — Salva regras existentes em /etc/sysconfig/iptables quando a firewall for reiniciada, movendo a versão anterior para o arquivo /etc/sysconfig/iptables.save.
    • no — O valor padrão. Não salva regras existentes quando a firewall for reiniciada.
  • IPTABLES_SAVE_COUNTER — Salva e restaura todos os contadores de pacotes e de bytes em todas as cadeias e regras. Esta diretiva aceita os seguintes valores:
    • yes — Salva o valor dos contadores.
    • no — O valor padrão. Não salva o valor dos contadores.
  • IPTABLES_STATUS_NUMERIC — Exibe a saída de endereços IP em formato numérico ao invés de domínios e nomes de host. Esta diretiva aceita os seguintes valores:
    • yes — O valor padrão. Retorna apenas endereços IP numa saída de estado.
    • no — Retorna domínios ou nomes de host numa saída de estado.

46.9.6. IPTables e IPv6

Se o pacote iptables-ipv6 estiver instalado, o netfilter do Red Hat Enterprise Linux pode filtrar a versão da próxima geração do protocolo de Internet, o IPv6. O comando usado para manipular o netfilter IPv6 é o ip6tables.
A maioria das diretivas para este comando são idênticas àquelas usadas para o iptables, entretanto, a tabela nat ainda não é suportada. Isto significa que ainda não é possível executar tarefas de conversão de endereços IPv6 de rede, como masquerading e encaminhamento de portas.
As regras para o ip6tables são salvas no arquivo /etc/sysconfig/ip6tables. As regras anteriores salvas pelos scripts de inicialização do ip6tables são salvas no arquivo /etc/sysconfig/ip6tables.save.
Opções de configuração para o script de inicialização so ip6tables são armazenadas em /etc/sysconfig/ip6tables-config, e os nomes para cada diretiva variam um pouco em relação aos nomes das diretivas do iptables.
Por exemplo, a diretiva IPTABLES_MODULES no arquivo iptables-config equivale à diretiva IP6TABLES_MODULES no arquivo ip6tables-config.

46.9.7. Recursos Adicionais

Consulte os seguintes recursos para informações adicionais sobre a filtragem de pacotes usando o iptables.
  • Seção 46.8, “Firewalls” — Contains a chapter about the role of firewalls within an overall security strategy as well as strategies for constructing firewall rules.

46.9.7.1. Documentação Instalada

  • man iptables — Contém uma descrição do iptables, assim como uma lista abrangente de alvos, opções, e extensões de correspondência.

46.9.7.2. Sites Úteis

  • http://www.netfilter.org/ — Esta é a casa do projeto netfilter/iptables. O site contém informações variadas sobre o iptables, incluindo uma FAQ focada em problemas específicos e vários guias úteis escritos pelo Rusty Russell, o mantenedor da firewall IP do Linux. Os documentos HOWTO do site cobrem tópicos como conceitos básicos de rede, filtragem de pacotes no kernel, e configurações de NAT.
  • http://www.linuxnewbie.org/nhf/Security/IPtables_Basics.html — Uma introdução sobre como pacotes trafegam pelo kernel do Linux, além de uma introdução à construção de comandos iptables básicos.


[14] Uma vez que BIOS de sistemas variam de acordo com o fabricante, alguns podem não suportar qualquer tipo de proteção por senha, enquanto outros podem suportar um tipo mas não o outro.
[15] O GRUB também aceita senhas não criptografadas, mas recomendamos que use um hash MD5, para maior segurança.
[16] Este acesso ainda é sujeito às restrições impostas pelo SELinux, se disponível. Consulte a Seção 47.2, “Introdução ao SELinux” para maiores informações.
[17] Um sistema no qual ambos, cliente e servidor compartilham uma chave em comum, usada para criptografar e descriptografar comunicações de rede

Capítulo 47. Segurança e SELinux

47.1. Mecanismos de Controle de Acesso (ACM)

Segue nesta seção, uma apresentação básica dos Mecanismos de Controle de Acesso (ACMs). Os ACMs oferecem aos administradores de sistemas, um meio de controlar quais usuários e processos podem acessar diferentes arquivos, despositivos, interfaces, etc. em um sistema de computador. Isto é primordial quando se trata de assegurar um sistema de computadores ou rede de trabalho de qualquer tamanho.

47.1.1. Controle de Acesso Discricionário (DAC)

O Controle de Acesso Discricionário (DAC) define os controles de acesso básico para objetos em um sistema de arquivo. Este é um típico controle de acesso, oferecido pelas permissões de arquivo, compartilhamento, etc. Tal acesso, condiz geralmente ao dono do objeto (arquivo, diretório, dispositivo, etc.).
DAC provides a means of restricting access to objects based on the identity of the users or groups (subjects) that try to access those objects. Depending on a subject's access permissions, they may also be able to pass permissions to other subjects.

47.1.2. Lista de Controle de Acesso (ACLs)

Access Control Lists (ACLs) provide further control over which objects a subject can access. For more information, refer to Capítulo 9, Access Control Lists.

47.1.3. Controle de Acesso Obrigatório (MAC)

Controle de Acesso Obrigatório (MAC) é um mecanismo de segurança que restringe o nível de controle que os usuários (assuntos) possuem sob os objetos que eles criam. Diferente de uma implementação DAC , onde usuários possuem total controle sob seus próprios arquivos, diretórios, etc. O MAC adiciona rótulos, ou categorias, em todos os objetos de sistema de arquivo. Usuários e processos devem ter o acesso apropriado para estas categorias antes que eles possam interagir com estes objetos.
In Red Hat Enterprise Linux, MAC is enforced by SELinux. For more information, refer to Seção 47.2, “Introdução ao SELinux”.

47.1.4. Controle de Acesso baseado na Função (RBAC)

Controle de Acesso baseado na Função (RBAC) é um método alternativo de controlar o acesso do usuário à objetos de sistema de arquivo. Ao invés do acesso ser controlado pelas permissões de usuários, o administrador de sistemas estabelece Funções baseadas em requerimentos funcionais de negócios ou critérios similares. Estas Funções possuem diferentes tipos e níveis de acesso à objetos.
In contrast to DAC or MAC systems, where users have access to objects based on their own and the object's permissions, users in an RBAC system must be members of the appropriate group, or Role, before they can interact with files, directories, devices, etc.
De um ponto de vista administrativo, o simples controle dos membros do grupo facilita o controle de quem acessa diversas partes do sistema de arquivo.

47.1.5. Segurança de Nível Múltiplo (MLS)

Multi-Level Security (MLS) is a specific Mandatory Access Control (MAC) security scheme. Under this scheme, processes are called Subjects. Files, sockets and other passive operating system entities are called Objects. For more information, refer to Seção 47.6, “Segurança de Nível Múltiplo (MLS)”.

47.1.6. Segurança de Categoria Múltipla (MCS)

Multi-Category Security (MCS) is an enhancement to SELinux, and allows users to label files with categories. MCS is an adaptation of MLS and re-uses much of the MLS framework in SELinux. For more information, refer to Seção 47.4.1, “Apresentação”

47.2. Introdução ao SELinux

A Segurança Aprimorada Linux (SELinux) é uma arquitetura de segurança integrada no kernel 2.6.x usando os Módulos de Segurança Linux (LSM). É um projeto da National Security Agency (NSA) dos Estados Unidos e da comunidade SELinux. A integração do SELinux no Red Hat Enterprise Linux foi um esforço conjunto entre a NSA e a Red Hat.

47.2.1. Visão Geral do SELinux

O SELinux oferece um sistema de Controle de Acesso Obrigatório - MAC (Mandatory Access Control) flexível incorporado ao kernel do Linux. Sob o Controle de Acesso Discricionário - DAC (Discretionary Access Control) padrão do Linux, um aplicativo ou processo rodando como um usuário (UID ou SUID) tem as permissões do usuário em relação a objetos como arquivos, soquetes, e outros processos. Rodar um kernel com MAC protege o sistema de aplicativos maléficos ou defeituosos que possam danificar ou destruir um sistema.
O SELinux define os direitos de acesso e transição de cada usuário, aplicativo, processo e arquivo no sistema. O SELinux então governa as interações destas entidades usando uma política de segurança que especifica quão severa ou branda uma certa instalação do Red Hat Enterprise Linux deve ser.
No dia-a-dia, os usuários, em grande parte, mal perceberão a existência do SELinux. Apenas os administradores de sistemas precisam considerar o nível de rigidez a ser implementado para os seus ambiente de servidores. A política pode ser tão severa ou branda quanto for preciso, e é altamente detalhada. Este nível de detalhamento dá ao kernel SELinux o controle completo e granular sobre todo o sistema.
O Processo Decisório do SELinux
Quando uma entidade (por exemplo, um aplicativo) tenta acessar um objeto (por exemplo, um arquivo), o servidor de imposição de políticas no kernel verifica um cache do vetor de permissões de acesso (AVC), onde permissões de entidades e objetos são temporariamente armazenadas. Se uma decisão não pode ser efetivada com base nos dados do AVC, o pedido continua até o servidor de segurança, o qual busca o contexto de segurança do aplicativo e do arquivo em uma matriz. A permissão é então concedida ou negada, com uma mensagem avc: denied detalhada em /var/log/messages caso a permissão seja negada. O contexto de segurança de entidades e objetos é obtido a partir da política instalada, a qual também fornece a informação para povoar a matriz do servidor de segurança.
Consulte o seguinte diagrama:
O Processo Decisório do SELinux
O Processo Decisório do SELinux.
Figura 47.1. O Processo Decisório do SELinux

Modos Operacionais do SELinux
Ao invés de rodar em modo imposição, o SELinuxpode rodar em modo permissivo, onde o AVC é verificado, e negações são registradas, entretanto o SELinux não impõe a política. Isto pode ser útil para resolução de problemas e para o desenvolvimento ou o aprimoramento de políticas do SELinux.
For more information about how SELinux works, refer to Seção 47.2.3, “Recursos Adicionais”.

47.2.2. Arquivos Relacionados ao SELinux

As seções seguintes descrevem os arquivos de configuração e sistemas de arquivos referentes ao SELinux.

47.2.2.1. O Pseudo-Sistema de Arquivos do SELinux

O pseudo-sistema de arquivos /selinux/ contém comandos que são normalmente usados pelo subsistema do kernel. Este tipo de sistema de arquivos é similar ao pseudo-sistema de arquivos /proc/.
Administradores e usuários normalmente não precisam manipular este componente.
O seguinte exemplo oferece amostras do conteúdo do diretório /selinux/:
-rw-rw-rw-  1 root root 0 Sep 22 13:14 access
dr-xr-xr-x  1 root root 0 Sep 22 13:14 booleans
--w-------  1 root root 0 Sep 22 13:14 commit_pending_bools
-rw-rw-rw-  1 root root 0 Sep 22 13:14 context
-rw-rw-rw-  1 root root 0 Sep 22 13:14 create
--w-------  1 root root 0 Sep 22 13:14 disable
-rw-r--r--  1 root root 0 Sep 22 13:14 enforce
-rw-------  1 root root 0 Sep 22 13:14 load
-r--r--r--  1 root root 0 Sep 22 13:14 mls
-r--r--r--  1 root root 0 Sep 22 13:14 policyvers
-rw-rw-rw-  1 root root 0 Sep 22 13:14 relabel
-rw-rw-rw-  1 root root 0 Sep 22 13:14 user
Por exemplo, a execução do comando cat no arquivo enforce revela ou um 1, para modo imposição, ou um 0, para modo permissivo.

47.2.2.2. Arquivos de Configuração do SELinux

As seções seguintes descrevem os arquivos de configuração e política do SELinux, assim como os sistemas de arquivos relacionados localizados no diretório /etc/.
47.2.2.2.1. O Arquivo de Configuração /etc/sysconfig/selinux
There are two ways to configure SELinux under Red Hat Enterprise Linux: using the SELinux Administration Tool (system-config-selinux), or manually editing the configuration file (/etc/sysconfig/selinux).
O /etc/sysconfig/selinux é o arquivo de configuração principal usado para habilitar ou desabilitar o SELinux, determinar qual política deve ser imposta no sistema, e como impor tal política.

Nota

O /etc/sysconfig/selinux contém um link simbólico para o verdadeiro arquivo de configuração, o /etc/selinux/config.
Veja a seguir o conjunto completo de opções de configuração disponíveis:
  • SELINUX=enforcing|permissive|disabled — Define o estado de nível superior do SELinux em um sistema.
    • enforcing — A política de segurança do SELinux é imposta.
    • permissive — O sistema SELinux emite avisos mas não impõe a política.
      Isto pode ser útil para fins de depuração e resolução de problemas. Em modo permissivo, mais negações são registradas porque entidades podem continuar com ações que seriam negadas em modo imposição. Por exemplo, percorrer um diretório em modo permissivo produz uma mensagem avc: denied para cada nível de diretório lido. Em modo imposição, o SELinux pararia assim que a primeira negação ocorresse, prevenindo que mensagens de erro adicionais ocorressem.
    • disabled — O SELinux é totalmente desabilitado. O SELinux é desvinculado do kernel, e o pseudo-sistema de arquivos torna-se não registrado.

      Tip

      Ações tomadas enquanto o SELinux estiver desabilitado podem resultar em um arquivo não tendo mais o contexto de segurança correto. Ou seja, o contexto de segurança definido pela política. A melhor maneira de reetiquetar o sistema de arquivos é criar o arquivo sinalizador /.autorelabel e reinicializar a máquina. Isto faz com que a etiquetagem ocorra bem cedo durante o processo de inicialização, antes de qualquer processo estar rodando no sistema. O uso deste procedimento significa que processos não podem acidentalmente criar arquivos ou iniciar no contexto errado.
      É possível usar o comando fixfiles relabel para reetiquetar o sistema de arquivos antes de habilitar o SELinux. Entretanto, este método não é recomendável porque uma vez que for concluído, ainda é possível que processos rodem no contexto errado. Tais processos podem criar arquivos que também possuam o contexto errado.

    Nota

    Espaços adicionais no final de uma linha de configuração, ou linhas adicionais no final do arquivo podem causar comportamento inesperado. Para ficar imune a isto, remova espaços desnecessários.
  • SELINUXTYPE=targeted|strict — Especifica a política que o SELinux deve impor.
    • targeted — Apenas os daemons de rede visados (targeted) são protegidos.

      Importante

      Os seguintes daemons são protegidos pela política targeted padrão: dhcpd, httpd (apache.te), named, nscd, ntpd, portmap, snmpd, squid, e syslogd. O resto do sistema roda no domínio unconfined_t. Este domínio permite que entidades e objetos com aquele contexto de segurança operem usando a segurança padrão do Linux.
      Os arquivos de política para estes daemons estão localizados em /etc/selinux/targeted/src/policy/domains/program. Estes arquivos estão sujeitos à mudanças à medida que novas versões do Red Hat Enterprise Linux são lançadas.
      Policy enforcement for these daemons can be turned on or off, using Boolean values controlled by the SELinux Administration Tool (system-config-selinux).
      Setting a Boolean value for a targeted daemon to 1 disables SELinux protection for the daemon. For example, you can set dhcpd_disable_trans to 1 to prevent init, which executes apps labeled dhcpd_exec_t, from transitioning to the dhcpd_t domain.
      Use o comando getsebool -a para listar todos os Booleanos do SELinux. Veja a seguir um exemplo sobre o uso do comando setsebool para configurar um Booleano do SELinux. A opção -P faz com que a mudança torne-se permanente. Sem esta opção, o Booleano mudaria para 1 na reinicialização.
      setsebool -P dhcpd_disable_trans=0
    • strict — Total proteção do SELinux para todos os daemons. Contextos de segurança são definidos para todas as entidades e objetos, e todas as ações são processadas pelo servidor de imposição de políticas.
  • SETLOCALDEFS=0|1 — Controla como definições locais (usuários e Booleanos) são estabelecidas. Use 1 para fazer com que estas definições sejam controladas pelo load_policy de arquivos em /etc/selinux/<nome-da-política>, ou use 0 para fazer com que sejam controladas pelo semanage.

    Atenção

    Você não deve usar um valor que não seja o padrão (0) a não ser que você esteja completamente ciente do impacto de tal mudança.
47.2.2.2.2. O Diretório /etc/selinux/
O diretório /etc/selinux/ é a localização principal de todos os arquivos de política, bem como do principal arquivo de configuração.
O seguinte exemplo oferece amostras do conteúdo do diretório /etc/selinux/:
-rw-r--r--  1 root root  448 Sep 22 17:34 config
drwxr-xr-x  5 root root 4096 Sep 22 17:27 strict
drwxr-xr-x  5 root root 4096 Sep 22 17:28 targeted
Os dois subdiretórios, strict/ e targeted/, são os diretórios específicos onde os arquivos de política com o mesmo nome (ou seja, strict e targeted) são armazenados.

47.2.2.3. Utilitários SELinux

Veja a seguir os utilitários SELinux mais utilizados:
  • /usr/sbin/setenforce — Modifica, em tempo real, o modo de execução do SELinux.
    Por exemplo:
    setenforce 1 — O SELinux roda em modo imposição.
    setenforce 0 — O SELinux roda em modo permissivo.
    Para realmente desabilitar o SELinux, você precisa ou especificar o parâmetro do setenforce adequado em /etc/sysconfig/selinux ou passar o parâmetro selinux=0 para o kernel, ou em /etc/grub.conf ou durante a inicialização.
  • /usr/sbin/sestatus -v — Exibe o estado detalhado de um sistema rodando o SELinux. O exemplo a seguir mostra um trecho da saída do sestatus -v:
    SELinux status:                 enabled
    SELinuxfs mount:                /selinux
    Current mode:                   enforcing
    Mode from config file:          enforcing
    Policy version:                 21
    Policy from config file:        targeted
    
    Process contexts:
    Current context:                user_u:system_r:unconfined_t:s0
    Init context:                   system_u:system_r:init_t:s0
    /sbin/mingetty                  system_u:system_r:getty_t:s0
  • /usr/bin/newrole — Roda um novo shell em um novo contexto ou papel. A política deve permitir a transição para o novo papel..

    Nota

    Este comando está disponível apenas se você tiver o pacote policycoreutils-newrole instalado, o qual é necessário às políticas strict e MLS.
  • /sbin/restorecon — Estabelece o contexto de segurança de um ou mais arquivos através da marcação de atributos estendidos com o arquivo ou contexto de segurança apropriado.
  • /sbin/fixfiles — Verifica ou corrige o banco de dados de contextos de segurança no sistema de arquivos.
Consulte as páginas man associadas a estes utilitários para maiores informações.
Consulte o conteúdo dos pacotes setools ou policycoreutils para mais informações sobre todos os utilitários binários disponíveis. Para visualizar o conteúdo de um pacote, use o seguinte comando:
rpm -ql <package-name>

47.2.3. Recursos Adicionais

Consulte os seguintes recursos para obter informações mais detalhadas sobre o SELinux.

47.2.3.1. Documentação Instalada

  • /usr/share/doc/setools-<número-da-versão>/ Toda a documentação para os utilitários contidos no pacote setools. Isto inclui todos os scripts auxiliares arquivos de configuração, e a documentação em si.

47.2.3.2. Sites Úteis

47.3. Breves Fundamentos e História do SELinux

SELinux was originally a development project from the National Security Agency (NSA)[18] and others. It is an implementation of the Flask operating system security architecture.[19]The NSA integrated SELinux into the Linux kernel using the Linux Security Modules (LSM) framework. SELinux motivated the creation of LSM, at the suggestion of Linus Torvalds, who wanted a modular approach to security instead of just accepting SELinux into the kernel.
Originariamente, a implementação do SELinux usava IDs de segurança persistente (PSIDs) armazenadas em um campo vago do inode ext2. Estas representações numéricas (ou seja, ilegíveis para o usuário) eram associadas pelo SELinux à uma etiqueta de contexto de segurança. Infelizmente, isto implicava a modificação de cada tipo de sistema de arquivos para suportar PSIDs, e portanto não era uma solução redimensionável nem tampouco uma solução que seria suportada upstream no kernel do Linux.
The next evolution of SELinux was as a loadable kernel module for the 2.4.<x> series of Linux kernels. This module stored PSIDs in a normal file, and SELinux was able to support more file systems. This solution was not optimal for performance, and was inconsistent across platforms. Finally, the SELinux code was integrated upstream to the 2.6.x kernel, which has full support for LSM and has extended attributes (xattrs) in the ext3 file system. SELinux was moved to using xattrs to store security context information. The xattr namespace provides useful separation for multiple security modules existing on the same system.
Muito do trabalho despendido em aprontar o kernel para upstream, assim como o desenvolvimento subseqüente do SELinux tem sido um esforço conjunto entre a NSA, a Red Hat, e a comunidade de desenvolvedores do SELinux.
For more information about the history of SELinux, the definitive website is http://www.nsa.gov/research/selinux/index.shtml.

47.4. Segurança de Categoria Múltipla (MCS)

47.4.1. Apresentação

Segurança de Categoria Múltipla (MCS) é uma melhora para o SELinux, e permite que os usuários rotulem arquivos com categorias. Estas categorias são utilizadas para restrições futuras Discretionary Access Control (DAC) e TypeEnforcement (TE)
The term categories refers to the same non-hierarchical categories used by Multi-Level Security (MLS). Under MLS, objects and subjects are labeled with Security Levels. These Security Levels consist of a hierarchical sensitivity value (such as "Top Secret") and zero or more non-hierarchical categories (such as "Crypto"). Categories provide compartments within sensitivity levels and enforce the need-to-know security principle. Refer to Seção 47.6, “Segurança de Nível Múltiplo (MLS)” for more information about Multi-Level Security.

47.4.1.1. O que é Segurança de Categoria Múltipla

MCS é uma adaptação do MLS. Do ponto de vista técnico, MCS é uma mudança de política, combinada a algumas modificações de usuários para esconder algumas tecnologias MLS desnecessárias. Foram realizadas também, algumas mudanças kernel, mas somente para facilitar o upgrade para MCS (ou MLS) sem invocar novamente uma rotulação completa do sistema de arquivo.
Espera-se que a qualidade do sistema como um todo melhore, reduza custos, acione processos de cógido aberto, aumente a transparência e torne a base de tecnologia mais útil do que somente para um pequeno grupo de usuários de casos extremamente especiais.

47.4.2. Aplicativos para Segurança de Categoria Múltipla.

Além do controle de acesso, o MCS pode ser usado para mostrar as categorias do MCS no topo ou na parte inferior da página de impressão. Isto também inclui a folha de apresentação para indicar os procedimentos de manuseio do documento. Também é possível integrar o MCS com desenvolvimentos futuros no SELinux, tais como a Melhora de Segurança X. Uma integração com o servidor de diretório também facilita o suporte MCS para email, o que involve o fato dos usuários rolularem manualmente emails de saída ou anexarem arquivos rotulados propriamente. O cliente de email pode então, determinar se os recipientes são esvaziados para acessar as categorias associadas aos emails.

47.4.3. SELinux Conteúdo de Segurança

SELinux conteúdo de segurança de armazenamento como uma função estendida de um arquivo. O espaço de nome da "segurança.", é utilizado para módulos de segurança e o nome segurança.selinux é utilizado para armazenar rótulos de segurança SELinuxde forma persistente nos arquivos. O conteúdo desta função irá variar, dependendo do arquivo ou diretório que você inspecione e da política que a máquina esteja impondo.

Nota

Espera-se que isto mude no kernel 2.6.15 ( e que já tenha nos -mm kernels mais recentes), assim o getxattr(2) sempre retorna à versão do rótulo canonicalizado do kernel.
Você pode usar o comando ls -Z para visualizar o rótulo de categoria de um arquivo:
~]# ls -Z gravityControl.txt
-rw-r--r--  user     user     user_u:object_r:tmp_t:Moonbase_Plans gravityControl.txt
Você pode usar o comando gefattr(1) para visualizar o valor de categoria interna (c10):
~]# getfattr -n security.selinux gravityControl.txt
# file: gravityControl.txt
security.selinux="user_u:object_r:tmp_t:s0:c10\000"
Refer to Seção 47.5, “Iniciando com a Segurança de Categoria Múltipla (MCS)” for details on creating categories and assigning them to files.

47.5. Iniciando com a Segurança de Categoria Múltipla (MCS)

This section provides an introduction to using MCS labels to extend the Mandatory Access Control (MAC) capabilities of SELinux. It discusses MCS categories, SELinux user identities, and how they apply to Linux user accounts and files. It builds on the conceptual information provided in Seção 47.4, “Segurança de Categoria Múltipla (MCS)”, and introduces some basic examples of usage.

47.5.1. Introdução

A etiquetagem MCS a partir de um usuário e ponto do administrador de sistemas é bastante direta. Ela consiste em configurar um conjunto de categorias, os quais são basicamente etiquetas de texto, tais como "Confidencial_de_Empresa" ou "Registros_Médicos", e depois atribuir usuários à estas categorias. O administrador de sistemas primeiro configura as categorias, depois atribui usuários à eles de acordo com a solicitação. Os usuários podem então usar as etiquetas de acordo como as vêem.
The names of the categories and their meanings are set by the system administrator, and can be set to whatever is required for the specific deployment. A system in a home environment may have only one category of "Private", and be configured so that only trusted local users are assigned to this category.
In a corporate environment, categories could be used to identify documents confidential to specific departments. Categories could be established for "Finance", "Payroll", "Marketing", and "Personnel". Only users assigned to those categories can access resources labeled with the same category.
After users have been assigned to categories, they can label any of their own files with any of the categories to which they have been assigned. For example, a home user in the system described above could label all of their personal files as "Private", and no service such as Apache or vsftp would ever be able to access those files, because they don't have access to the "Private" category.
MCS works on a simple principle: to access a file, a user needs to be assigned to all of the categories with which the file is labeled. The MCS check is applied after normal Linux Discretionary Access Control (DAC) and Type Enforcement (TE) rules, so it can only further restrict security.

47.5.2. Comparing SELinux and Standard Linux User Identities

SELinux maintains its own user identity for processes, separately from Linux user identities. In the targeted policy (the default for Red Hat Enterprise Linux), only a minimal number of SELinux user identities exist:
  • system_u — System processes
  • root — System administrator
  • user_u — All login users
Use the semanage user -l command to list SELinux users:
~]# semanage user -l

                Labeling   MLS/       MLS/
SELinux User    Prefix     MCS Level  MCS Range            SELinux Roles

root            user       s0         s0-s0:c0.c1023       system_r sysadm_r user_r
system_u        user       s0         s0-s0:c0.c1023       system_r
user_u          user       s0         s0-s0:c0.c1023       system_r sysadm_r user_r
Refer to Seção 47.8.3, “Entendendo os Usuários e Funções na Política Alvo.” for more information about SELinux users and roles.
SELinux Logins
One of the properties of targeted policy is that login users all run in the same security context. From a TE point of view, in targeted policy, they are security-equivalent. To effectively use MCS, however, we need to be able to assign different sets of categories to different Linux users, even though they are all the same SELinux user (user_u). This is solved by introducing the concept of an SELinux login. This is used during the login process to assign MCS categories to Linux users when their shell is launched.
Use the semanage login -a command to assign Linux users to SELinux user identities:
~]# semanage login -a james
~]# semanage login -a daniel
~]# semanage login -a olga
Now when you list the SELinux users, you can see the Linux users assigned to a specific SELinux user identity:
~]# semanage login -l

Login Name                SELinux User              MLS/MCS Range

__default__               user_u                    s0
james                     user_u                    s0
daniel                    user_u                    s0
root                      root                      s0-s0:c0.c1023
olga                      user_u                    s0
Notice that at this stage only the root account is assigned to any categories. By default, the root account is configured with access to all categories.
Red Hat Enterprise Linux and SELinux are preconfigured with several default categories, but to make effective use of MCS, the system administrator typically modifies these or creates further categories to suit local requirements.

47.5.3. Configuring Categories

SELinux maintains a mapping between internal sensitivity and category levels and their human-readable representations in the setrans.conf file. The system administrator edits this file to manage and maintain the required categories.
Use the chcat -L command to list the current categories:
~]# chcat -L
s0
s0-s0:c0.c1023                 SystemLow-SystemHigh
s0:c0.c1023                    SystemHigh
To modify the categories or to start creating your own, modify the /etc/selinux/<selinuxtype>/setrans.conf file. For the example introduced above, add the Marketing, Finance, Payroll, and Personnel categories as follows (this example uses the targeted policy, and irrelevant sections of the file have been omitted):
~]# vi /etc/selinux/targeted/setrans.conf
s0:c0=Marketing
s0:c1=Finance
s0:c2=Payroll
s0:c3=Personnel
Use the chcat -L command to check the newly-added categories:
~]# chcat -L
s0:c0                          Marketing
s0:c1                          Finance
s0:c2                          Payroll
s0:c3                          Personnel
s0
s0-s0:c0.c1023                 SystemLow-SystemHigh
s0:c0.c1023                    SystemHigh

Nota

After you make any changes to the setrans.conf file, you need to restart the MCS translation service before those changes take effect. Use the following command to restart the service:
~]# service mcstrans restart

47.5.4. Assigning Categories to Users

Now that the required categories have been added to the system, you can start assigning them to SELinux users and files. To further develop the example above, assume that James is in the Marketing department, Daniel is in the Finance and Payroll departments, and Olga is in the Personnel department. Each of these users has already been assigned an SELinux login.
Use the chcat command to assign MCS categories to SELinux logins:
~]# chcat -l -- +Marketing james
~]# chcat -l -- +Finance,+Payroll daniel
~]# chcat -l -- +Personnel olga
You can also use the chcat command with additional command-line arguments to list the categories that are assigned to users:
~]# chcat -L -l daniel james olga
daniel: Finance,Payroll
james: Marketing
olga: Personnel
You can add further Linux users, assign them to SELinux user identities and then assign categories to them as required. For example, if the company director also requires a user account with access to all categories, follow the same procedure as above:
# Create a user account for the company director (Karl)
~]# useradd karl
~]# passwd karl
Changing password for user karl.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.

# Assign the user account to an SELinux login
~]# semanage login -a karl

# Assign all the MCS categories to the new login
~]# chcat -l -- +Marketing,+Finance,+Payroll,+Personnel karl
Use the chcat command to verify the addition of the new user:
~]# chcat -L -l daniel james olga karl
daniel: Finance,Payroll
james: Marketing
olga: Personnel
karl: Marketing,Finance,Payroll,Personnel

Nota

MCS category access is assigned during login. Consequently, a user does not have access to newly-assigned categories until they log in again. Similarly, if access to a category is revoked, this is only apparent to the user after the next login.

47.5.5. Assigning Categories to Files

At this point we have a system that has several user accounts, each of which is mapped to an SELinux user identity. We have also established a number of categories that are suitable for the particular deployment, and assigned those categories to different users.
All of the files on the system, however, still fall under the same category, and are therefore accessible by everyone (but still according to the standard Linux DAC and TE constraints). We now need to assign categories to the various files on the system so that only the appropriate users can access them.
For this example, we create a file in Daniel's home directory:
[daniel@dhcp-133 ~]$ echo "Financial Records 2006" > financeRecords.txt
Use the ls -Z command to check the initial security context of the file:
[daniel@dhcp-133 ~]$ ls -Z financeRecords.txt
-rw-r--r--  daniel daniel user_u:object_r:user_home_t      financeRecords.txt
Notice that at this stage the file has the default context for a file created in the user's home directory (user_home_t) and has no categories assigned to it. We can add the required category using the chcat command. Now when you check the security context of the file, you can see the category has been applied.
[daniel@dhcp-133 ~]$ chcat -- +Finance financeRecords.txt
[daniel@dhcp-133 ~]$ ls -Z financeRecords.txt
-rw-r--r--  daniel daniel root:object_r:user_home_t:Finance financeRecords.txt
In many cases, you need to assign more than one category to a file. For example, some files may need to be accessible to users from both the Finance and Payroll departments.
[daniel@dhcp-133 ~]$ chcat -- +Payroll financeRecords.txt
[daniel@dhcp-133 ~]$ ls -Z financeRecords.txt
-rw-r--r--  daniel daniel root:object_r:user_home_t:Finance,Payroll financeRecords.txt
Each of the categories that have been assigned to the file are displayed in the security context. You can add and delete categories to files as required. Only users assigned to those categories can access that file, assuming that Linux DAC and TE permissions would already allow the access.
If a user who is assigned to a different category tries to access the file, they receive an error message:
[olga@dhcp-133 ~]$ cat financeRecords.txt
cat: financeRecords.txt: Permission Denied

Nota

Refer to the man pages for semanage and chcat for more information on the available options for these commands.

47.6. Segurança de Nível Múltiplo (MLS)

Em muitos negócios, é de suma importância proteger dados sensíveis e confidenciais. Se uma informação torna-se pública, os negócios podem enfrentar ramificações financeiras ou legais. No mínimo, irão sofrer uma perda de confiança dos clientes. Na maioria dos casos, no entanto, eles não conseguem se recuperar destas perdas financeiras ou de outras perdas, com investimento ou compensação apropriada.
Não pode-se dizer o mesmo sobre comunidades de defesa e afins, as quais incluem serviços militares, organizações de inteligência e algumas áreas de serviço policial. Estas organizações não podem ser recuperadas facilmente caso estas informações confidenciais sejam vazadas, e podem nunca se recuperarem. Estas comunidades requerem maiores níveis de segurança do que aqueles utilizados pelos negócios e outras organizações.
Informações com níveis diferenciados de segurança no mesmo sistema de computador, representam uma verdadeira ameaça. Isolar informações de níveis de segurança diferentes não soluciona o problema, apesar de usuários diversos acessarem usando contas diferentes, com permissões diferentes e controles de acesso diferentes.
Algumas empresas vão mais adiante e compram sistemas dedicados para cada nível de segurança. No entanto, isto é geralmente extremamente caro. É necessário um mecanismo diferente para habilitar usuários com diferentes níveis de segurança para acessar sistemas simultaneamente, sem medo de contaminar informações.

47.6.1. Porque Nível Múltiplo?

O termo nível múltiplo deriva das classificações de segurança da comunidade de defesa. Confidencial, Secreto e Top Secret.
Indivíduos precisam receber espaços vazios apropriados antes que eles possam ver as informações classificadas. Aqueles com espaços vazios Confidenciais, são autorizados a somente visualizar documentos Confidenciais. Eles não estão autorizados a ver informações Secretas ou de Top Secret. As regras que se aplicam ao fluxo de dados, operam desde níveis mais baixos à níveis mais altos e nunca o oposto. Veja a ilustração a seguir:
Níveis de Segurança da Informação
A hierarquia dos Níveis de Segurança da Informação. A seta indica a direção que as regras permitem que os dados fluam.
Figura 47.2. Níveis de Segurança da Informação

47.6.1.1. O Modelo Bell-La Padula (BLP)

SELinux, como muitos outros sistemas que protegem os dados de nível múltiplo, utiliza o modelo BLP. Este modelo especifica como a informação pode fluir dentro de um sistema baseado em rótulos anexados a cada assunto ou objeto. Consulte o seguinte diagrama:
Dados disponíveis fluem utilizando um sistema MLS
Os processos podem ler o mesmo nível de segurança ou mais baixo, mas somente pode escrever para si próprios ou para níveis de segurança mais altos.
Figura 47.3. Dados disponíveis fluem utilizando um sistema MLS

Neste sistema, os usuários, computadores e redes de trabalho, utilizam rótulos para indicar os níveis de segurança. Os dados podem fluir entre níveis similares, por exemplo entre "Segredo" e "Segredo", ou de um nível mais baixo até um nível mais alto. Isto significa que os usuários de nível "Segredo" podem compartilhar dados entre si e também podem recuperar informações em um nível Confidencial (ou seja, nível mais baixo). No entanto, os dados não podem fluir de um nível mais alto para um mais baixo. Isto evita que processos em nível "Segredo", visualizem informações classificadas como "Top Secret". Ele também previne que processos em um nível mais alto escrevam informações, acidentalmente, para um nível mais baixo. Esta ação é chamada de modelo "não leia, não escreva".

47.6.1.2. Privilégios de MLS e Sistemas

O acesso à regras MLS combinam com as permissões de acesso convencionais (permissões de arquivo). Por exemplo, se um usuário com um nível de segurança de "Segredo", usar o Controle de Acesso Discreto (DAC) para bloquear o acesso de um arquivo à outros usuários, ele também bloqueia o acesso à usuários com nível de segurança de "Top Secret". Um espaço livre de segurança maior não dá permissão automática para navegar de forma arbitrária em um sistema de arquivo.
Usuários com espaços livres de nível máximo não adquirem automaticamente direitos administrativos em sistemas de nível múltiplo. Apesar de terem acesso à toda informação nos computadores, é diferente de ter direitos iguais.

47.6.2. Níveis de Segurança, Objetos e Assuntos.

Como já discutido anteriormente, os assuntos e objetos são rotulados com Níveis de Segurança (SLs) os quais são compostos por dois tipos de entidades:
  1. Confidencialidade: — Uma função hierárquica, tal como "Segredo" ou "Top Secret".
  2. Categorias: — Um conjunto de funções não hierárquicas tais como "Somente EUA" ou "UFO".
Um SL deve possuir uma confidencialidade e pode ter zero ou mais categorias.
Exemplos de SLs São { Secreto / UFO, Crypto }, { Top Secret / UFO, Crypto, Stargate } e { Não classificado }
Verifique a confidencialidade hierárquica seguida de zero ou mais categorias. A razão pela qual ela possui categorias, assim como confidencialidades, é que as confidencialidades podem ser divididas dependendo da necessidade. Por exemplo, embora o processo possa ser esvaziado para o nível de confidencialidade "Segredo", ele pode não precisar qualquer tipo de acesso ao projeto "Drive Distorcido" (que pode ser o nome de uma categoria).

Nota

  1. Níveis de Segurança em objetos são chamados de Classificações.
  2. Os Níveis de Segurança em assuntos são chamados de Áreas Livres
Dessa forma, os objetos são rotulados com a Classificação, enquanto assuntos operam com uma Área Livre específica. Os níveis de Segurança também podem ter Intervalos, mas isto ultrapassa o escopo desta apresentação.

47.6.3. Política MLS

O SELinux, utiliza o modelo Bell-La Padula BLP com Imposição de Tipo (TE) para sua integridade. Em outras palavras, a política MLS, assegura que um Assunto tenha uma área livre apropriada para acessar um Objeto de uma classificação específica.
Por exemplo, na MLS, o sistema precisa saber como processar uma solicitação tal como: Um processo rodando com uma área livre de { Top Secret / UFO, Rail gun } pode escrever para um arquivo classificado como { Top Secret / UFO } ?
O modelo MLS e a política implementada para ele, irá determinar a resposta. (Considere, por exemplo, o problema de informação vazando da categoria Rail gun no arquivo).
O MLS encontra um conjunto bastante estreito (ainda que crítico) de requerimentos de segurança, baseado na maneira que as informações e pessoas são gerenciadas em ambientes extremamente controlados, tal como o exército. Geralmente, é difícil trabalhar com a MLS além de não mapear bem em situações de casos gerais.
A Imposição de Tipo (TE) sob o SELinux é mais flexível e possui um esquema de segurança expressivo, o que em muitos casos é mais aceitável do que a MLS.
Existem, no entanto, diversas situações onde ainda requer-se a MLS tradicional. Por exemplo, um servidor de arquivo onde os dados armazenados podem conter classificações mixas e onde os clientes conectam em áreas livres diferentes. Isto resulta em diversos níveis de Segurança e de um isolamento significativo em um só sistema.
Este tipo de situação é a razão pela qual o SELinux inclui a MLS como um modelo de segurança, como um adjunto para TE.

47.6.4. Certificação LSPP

Efforts are being made to have Linux certified as an MLS operating system. The certification is equivalent to the old B1 rating, which has been reworked into the Labeled Security Protection Profile under the Common Criteria scheme.

47.7. Visão Geral da Política SELinux

This chapter is an overview of SELinux policy, some of its internals, and how it works. It discusses the policy in general terms, while Seção 47.8, “Visão Geral da Política Alvo” focuses on the details of the targeted policy as it ships in Red Hat Enterprise Linux. This chapter starts with a brief overview of what policy is and where it resides.
A partir daí, discute sobre a função do SELinux durante o processo de inicialização. Depois segue com discussões sobre contextos de segurança de arquivo, classes de objeto e permissões, atributos, tipos, vetores de acesso, macros, usuários e funções, restrições e termina com uma breve discussão sobre as interfaces kernel especiais.

47.7.1. O que é a Política SELinux?

A Política SELinux é o conjunto de regras que guia o mecanismo de segurança SELinux. Ela define os tipos para objetos de arquivo e os domínios para processos. Ela usa funções para limitar os domínios que podem ser inseridos, e possui identidades de usuário para especificar as funções que podem ser obtidas. Na teoria, tipos e domínios são equivalentes com a diferença de que os tipos se aplicam a objetos enquanto domínios se aplicam à processos.

47.7.1.1. Tipo de SELinux

O tipo é uma forma de agrupar ítens baseados na semelhança entre eles, do ponto de vista da segurança. Isto não necessariamente é relacionado a um único propósito de um aplicativo ou o conteúdo de um documento. Por exemplo, um arquivo pode ter qualquer tipo de conteúdo servindo a qualquer propósito, mas se ele pertencer a um usuário e existir no diretório home daquele usuário, será considerado como um tipo de segurança específica, user_home_t.
Estes tipos de objeto são considerados iguais, pois podem ser acessados da mesma forma que o conjunto de assuntos. Da mesma forma, processos tendem a ser do mesmo tipo se tiverem a mesma permissão como outros assuntos. Na política alvo, programas que rodem no domínio unconfined_t possuem um arquivo executável com um tipo, como o sbin_t. A partir da perpectiva do SELinux, isto significa que são todos equivalentes em relação a o que podem e não podem fazer no sistema.
Por exemplo, o objeto de arquivo binário executável em /usr/bin/postgres possui o tipo postgresql_exec_t. Todos os daemons alvo possuem seus próprios tipo *_exec_t para seus aplicativos executáveis. De fato, todo o conjunto de executáveis PostgreSQL tais como createlang, pg_dump, epg_restore possuem o mesmo tipo, postgresql_exec_t, e transitam para o mesmo domínio postgresql_t, na execução.
47.7.1.1.1. Usando as Regras de Política para Definir Acesso de Tipo
A política SELinux define diversas regras que determinam como cada domínio pode acessar cada tipo. Só é permitido o que for especificado pelas regras. Por padrão, todas as operações são negadas e auditadas, ou seja, são autenticadas no arquivo $AUDIT_LOG. No Red Hat Enterprise Linux, isto está configurado para /var/log/messages. A política é compilada em formato binário para carregar no servidor de segurança kernel e cada vez que o servidor de segurança toma uma decisão, ele é colocado no cache no AVC para optimizar o desempenho.
The policy can be defined either by modifying the existing files or by adding local Type Enforcement (TE) and File Context (FC) files to the policy tree. These new policies can be loaded into the kernel in real time. Otherwise, the policy is loaded during the boot process by init, as explained in Seção 47.7.3, “A Função da Política no Processo de Inicialização”. Ultimately, every system operation is determined by the policy and the type-labeling of the files.

Importante

After loading a new policy, it is recommended that you restart any services that may have new or changed labeling. Generally speaking, this is only the targeted daemons, as listed in Seção 47.8.1, “O que é Política Alvo?”.

47.7.1.2. SELinux e Controle de Acesso Obrigatório

SELinux is an implementation of Mandatory Access Control (MAC). Depending on the security policy type, SELinux implements either Type Enforcement (TE), Roles Based Access Control (RBAC) or Bell-La Padula Model Multi-Level Security (MLS).
A política especifica as regras no ambiente de implementação. Esta escrito em uma linguagem criada especificamente para a política de segurança escrita. Os autores da Política usam macros m4 para capturar conjuntos comuns de regras de nível baixo. Diversos macros m4 estão definidos na política existente, que facilita a escrita da nova política. Estas regras são processadas previamente em várias regras adicionais como parte da construção do arquivo policy.conf, o qual é compilado na política binária.
Access rights are divided differently among domains, and no domain is required to act as a master for all other domains. Moving between domains is controlled by the policy, through login programs, userspace programs such as newrole, or by requiring a new process execution in the new domain. This movement between domains is referred to as a transition.

47.7.2. Onde está a Política

Existem dois componentes para a política: a árvore binária e a árvore fonte. A árvore binária é apresentada pelo pacote selinux-policy-<policyname> e fornece um arquivo de política binária.
Como forma alternativa, a política binária pode ser construída a partir da fonte quando o pacote selinux-policy-devel for instalado.

Nota

Informações sobre como editar, escrever e compilar a política estão fora do escopo deste documento.

47.7.2.1. Arquivos de Árvores Binárias

  • /etc/selinux/targeted/ — este é o diretório raiz para a política alvo e contém a árvore binária.
  • /etc/selinux/targeted/policy/ — this is the location of the binary policy file policy.<xx>. In this guide, the variable SELINUX_POLICY is used for this directory.
  • /etc/selinux/targeted/contexts/ — este é o local das informações de contexto de segurança e arquivos de configuração, que são usados durante o tempo de execução por diversos aplicativos.
  • /etc/selinux/targeted/contexts/files/ — contains the default contexts for the entire file system. This is referenced by restorecon when performing relabeling operations.
  • /etc/selinux/targeted/contexts/users/ — na política alvo, somente o arquivo raiz se encontra neste diretório. Estes arquivos são usados para determinar contexto quando um usuário se autenticar. Por exemplo, para o usuário root, o contexto é user_u:system_r:unconfined_t.
  • /etc/selinux/targeted/modules/active/booleans* — é aqui que os Booleanos de tempo de execução são configurados.

    Nota

    Estes arquivos nunca devem ser modificados manualmente. Você deve usar um getsebool, setsebool ferramentas semanage para manipular os Booleanos de tempo de execução.

47.7.2.2. Arquivos de Árvores Fonte

Para módulos de políticas em desenvolvimento, o pacote selinux-policy-devel inclui todos os arquivos de interface para construir a política. Recomenda-se que aqueles que construirem a política, usem estes arquivos para construir módulos.
Este pacote instala os arquivos de interface da política sob o /usr/share/selinux/devel/include e possui arquivos make instalados em/usr/share/selinux/devel/Makefile.
Para aplicativos de ajuda, que precisem de diversos caminhos SELinux, o libselinux oferece uma gama de funções que retornam os caminhos aos arquivos de diretórios e configurações distintos. Isto anula a necessidade dos aplicativos de codificarem estritamente os caminhos, especialmente quando a localização da política depende da configuração de SELINUXTYPE em /etc/selinux/config.
Por exemplo, se SELINUXTYPE estiver configurado para strict, a localização da política ativa se encotra sob /etc/selinux/strict.
Para visualizar a lista de funções disponíveis, use o seguinte comando:
man 3 selinux_binary_policy_path

Nota

Esta página do manual estará disponível somente se possuir o RPM libselinux-devel instalado.
O uso do libselinux e funções afins, não está no escopo deste documento.

47.7.3. A Função da Política no Processo de Inicialização

SELinux tem um papel importante durante as fases iniciais da inicialização do sistema. Como todos os processos devem ser etiquetados com seus domínios corretos, init realiza operações essenciais no início do processo de inicialização para manter a sincronização entre a etiquetagem e a imposição de política.
  1. Despois que o kernel tiver sido carregado durante o processo de inicialização, o processo inicial é atribuído ao initial SELinux ID (initial SID) kernel pré-definido. As iniciais SIDs são usadas para obstáculos na inicialização antes que a política seja carregada.
  2. /sbin/init mounts /proc/, e então procura pelo tipo de sistema de arquivo selinuxfs. Se for encontrado, significa que SELinux está habilitado no kernel.
  3. Se o init não encontrar o SELinux no kernel, ou se estiver desabilitado através do parâmetro de inicialização selinux=0, ou ainda se o /etc/selinux/config especificar que SELINUX=disabled, o processo de inicialização procede com um sistema não-SELinux.
    At the same time, init sets the enforcing status if it is different from the setting in /etc/selinux/config. This happens when a parameter is passed during the boot process, such as enforcing=0 or enforcing=1. The kernel does not enforce any policy until the initial policy is loaded.
  4. Se o SELinux estiver presente, o /selinux/ será montado.
  5. init checks /selinux/policyvers for the supported policy version. The version number in /selinux/policyvers is the latest policy version your kernel supports. init inspects /etc/selinux/config to determine which policy is active, such as the targeted policy, and loads the associated file at $SELINUX_POLICY/policy.<version>.
    Se a política binária não for a versão suportada pelo kernel, o init tenta carregar o arquivo da política caso o arquivo de política seja uma versão anterior. Isto oferece compatibilidade com versões de políticas anteriores.
    Se as configurações locais em /etc/selinux/targeted/booleans forem diferentes daqueles compilados na política, o init modifica a política na memória baseada nas configurações locais anteriores ao carregamento da política no kernel.
  6. Nesta fase do processo, a política está totalmente carregada no kernel. As Iniciais SIDs são então mapeadas para os contextos de segurança na política. No caso da política alvo, o novo domínio é user_u:system_r:unconfined_t. O kernel pode agora começar a recuperar contextos de segurança de forma dinâmica do servidor de segurança kernel
  7. O init então reexecuta a si mesmo para que possa transitar para um domínio diferente, caso seja definido pela política. Para a política alvo, não há transição definida e portanto o init fica no domínio unconfined_t
  8. Neste ponto, o comando init continua com seu processo normal de inicialização.
The reason that init re-executes itself is to accommodate stricter SELinux policy controls. The objective of re-execution is to transition to a new domain with its own granular rules. The only way that a process can enter a domain is during execution, which means that such processes are the only entry points into the domains.
Por exemplo, se a política possuir um domínio específico para init, tal como o init_t, será solicitado um método mudar da inicial SID, tal como o kernel, e corrigir o domínio em tempo de execução para init. Como é bem provável que esta transição pode aconteça, o init é codificado para se reexecutar após o carregamento de política.
Esta trasição de init acontece caso a regra de domain_auto_trans(kernel_t, init_exec_t, <target_domain_t>) estiver na política. Esta regra informa que uma transição automática acontece em qualquer execução no domínio kernel_t que executa um arquivo do tipo init_exec_t. Quando esta execução acontece, o novo processo é atribuído ao domínio <target_domain_t>, usando um domínio alvo atual, tal como o init_t.

47.7.4. Classes de Objeto e Permissões

O SELinux define diversas classes para objetos, facilitando o agrupamento de certas permissões através de classes específicas. Por exemplo:
  • Classe relacionadas a arquivos incluem filesystem para arquivos de sistema, file para arquivos, e dir para diretórios. Cada classe possui seu próprio conjunto associado de permissões.
    A classe filesystem pode montar, desmontar, obter funções, ajustar quotas, reetiquetar e assim por diante. A classe file possui arquivos de permissões comuns, tais como ler, escrever, obter e ajustar funções, bloquiar, reetiquetar, ligar, renomear, acrescentar.
  • As classes relacionadas à rede incluem tcp_socket para soquetes TCP, netif para interfaces de rede, enode para nós de rede.
    A classe netif por exemplo, pode enviar e receber TCP, UDP e soquetes raw (tcp_recv, tcp_send, udp_send, udp_recv, rawip_recv, e rawip_send.)
As classes de objeto possuem declarações que se combinam no kernel, ou seja, não é simples adicionar ou mudar detalhes de classe de objeto. O mesmo acontece nas permissões. Existem trabalhos em desenvolvimento para tornar possível registrar e cancelar classes e permissões de forma dinâmica.
Permissões são as ações que o sujeito pode desempenhar em um objeto, se a política permitir isto. Estas permissões são as solicitações de acesso que o SELinux permite de forma ativa ou nega.

47.8. Visão Geral da Política Alvo

Este capítulo é uma visão geral e avaliação da política alvo do SELinux a política atual suportada por Red Hat Enterprise Linux.
A maior parte do conteúdo deste capítulo é aplicável à todos os tipos de políticas SELinux referente aos locais de arquivos e tipo de seus conteúdo. A diferença está em quais arquivos estão nos locais chaves e quais são seus conteúdos.

47.8.1. O que é Política Alvo?

The SELinux policy is highly configurable. For Red Hat Enterprise Linux 5, Red Hat supports a single policy, the targeted policy. Under the targeted policy, every subject and object runs in the unconfined_t domain except for the specific targeted daemons. Objects that are in the unconfined_t domain have no restrictions and fall back to using standard Linux security, that is, DAC. The daemons that are part of the targeted policy run in their own domains and are restricted in every operation they perform on the system. This way daemons that are exploited or compromised in any way are contained and can only cause limited damage.
Por exemplo, os daemons http e ntp são protegidos na política alvo padrão, e rodam nos domínios httpd_t e ntpd_t respectivamente. O daemon ssh, no entanto, não é protegido nesta política, e consequentemente roda no domínio unconfined_t
Consulte a seguinte amostra de resultado, que ilustra os diversos domínios para os daemons mencionados acima:
user_u:system_r:httpd_t         25129 ?        00:00:00 httpd
user_u:system_r:ntpd_t          25176 ?        00:00:00 ntpd
system_u:system_r:unconfined_t         25245 ? 00:00:00 sshd
A Política Severa
The opposite of the targeted policy is the strict policy. In the strict policy, every subject and object exists in a specific security domain, and all interactions and transitions are individually considered within the policy rules.
A política severa é um ambiente muito mais complexo, e não navega com Red Hat Enterprise Linux. Este guia foca em políticas alvo que navegam com Red Hat Enterprise Linux, e nos componentes de SELinux usado pelos daemons alvo.
Os daemons alvo seguem abaixo: dhcpd; httpd; mysqld; named; nscd; ntpd; portmap; postgres; snmpd; squid; syslogd; ewinbind.

Nota

Dependendo de sua instalação, somente alguns destes daemons podem estar presentes.

47.8.2. Arquivos e Diretórios de Política Alvo.

Refer to Seção 47.7.2, “Onde está a Política” for a list of the common files and directories used by SELinux.

47.8.3. Entendendo os Usuários e Funções na Política Alvo.

Esta seção cobre as funções específicas habilitadas para a política alvo. O tipo unconfined_t existe em todas as funções, que reduz de forma significante a usabilidade das funções na política alvo. Usos mais extensivos de funções, requerem uma mudança para um paradigma de política severa, onde todos os processos rodam em um domínio considerado individual.
Effectively, there are only two roles in the targeted policy: system_r and object_r. The initial role is system_r, and everything else inherits that role. The remaining roles are defined for compatibility purposes between the targeted policy and the strict policy.[20]
Três ou quatro funções são definidas pela política. A quarta função, object_r, é uma função implícita e não encontrada na fonte da política. Como as funções são criadas e populadas por tipos que utilizam uma ou mais declarações na política, não há nenhum arquivo que declare todas as funções. (Lembre-se que a própria política é gerada a partir de um número de arquivos separados).
system_r
Esta função é para todos os processos de sistemas,exceto para processos de usuários:
system_r (28 types)
    dhcpd_t
    httpd_helper_t
    httpd_php_t
    httpd_suexec_t
    httpd_sys_script_t
    httpd_t
    httpd_unconfined_script_t
    initrc_t
    ldconfig_t
    mailman_cgi_t
    mailman_mail_t
    mailman_queue_t
    mysqld_t
    named_t
    ndc_t
    nscd_t
    ntpd_t
    pegasus_t
    portmap_t
    postgresql_t
    snmpd_t
    squid_t
    syslogd_t
    system_mail_t
    unconfined_t
    winbind_helper_t
    winbind_t
    ypbind_t
user_r
Esta é a função do usuário padrão para usuários de Linux. Em uma política severa, os usuários podem ser utilizados, permitindo que eles tenham funções especiais para desempenhar operações privilegiadas. Em uma política alvo, todos os usuários rodam em um domínio unconfined_t.
object_r
Em um SELinux as funções não são utilizadas para objetos quando o RBAC estiver sendo usado. As funções são somente para assuntos. Isto se dá porque as funções são baseadas em tarefas e agrupam entidades que desempenhem ações (por exemplo, os processos). Todas estas entidades são referidas coletivamente como assuntos. Por esta razão, todos os objetos possuem uma função object_r, e sua função é somente usada como um espaço reservado no rótulo.
sysadm_r
Esta é a função do administrador de sistemas em uma política severa. Se você entrar diretamente como um usuário root, a função padrão pode na verdade ser staff_r. Se isto for verdade, use o comando newrole -r sysadm_r para mudar a função de administrador de sistemas SELinux, para desempenhar as tarefas de administração de sistemas. Na política alvo, o sysadm_r é retido por compatibilidade:
sysadm_r (6 types)
    httpd_helper_t
    httpd_sys_script_t
    initrc_t
    ldconfig_t
    ndc_t
    unconfined_t
There is effectively only one user identity in the targeted policy. The user_u identity was chosen because libselinux falls back to user_u as the default SELinux user identity. This occurs when there is no matching SELinux user for the Linux user who is logging in. Using user_u as the single user in the targeted policy makes it easier to change to the strict policy. The remaining users exist for compatibility with the strict policy.[21]
A única exceção é o usuário SELinuxroot. Você pode notar o root como a identidade de usuário em um conteúdo de processo. Isto ocorre quando o usuário SELinux root inicia os daemons a partir da linha de comando, ou reinicia um daemon originalmente iniciado por um init.


[18] The NSA is the cryptologic agency of the United States of America's Federal government, charged with information assurance and signals intelligence. You can read more about the NSA at their website, http://www.nsa.gov/about/.
[19] Flask grew out of a project that integrated the Distributed Trusted Operating System (DTOS) into the Fluke research operating system. Flask was the name of the architecture and the implementation in the Fluke operating system.
[20] Any role could have been chosen for the targeted policy, but system_r already had existing authorization for the daemon domains, simplifying the process. This was done because no mechanism currently exists to alias roles.
[21] A user aliasing mechanism would also work here, to alias all identities from the strict policy to a single user identity in the targeted policy.

Capítulo 48. Trabalhando com SELinux

SELinux apresenta tanto um novo paradigma de segurança quanto um novo conjunto de práticas e ferramentas para administradores e usuários finais. As ferramentas e técnicas discutidas neste capítulo focam em operações padrão, desempenhadas pelo usuário final, administradores e analistas.

48.1. End User Control of SELinux

In general, end users have little interaction with SELinux when Red Hat Enterprise Linux is running the targeted policy. This is because users are running in the domain of unconfined_t along with the rest of the system except the targeted daemons.
In most situations, standard DAC controls prevent you from performing tasks for which you do not have the required access or permissions before SELinux is consulted. Consequently, it is likely that you will never generate an avc: denied message.
The following sections cover the general tasks and practices that an end user might need to perform on a Red Hat Enterprise Linux system. These tasks apply to users of all privilege levels, not only to end users.

48.1.1. Moving and Copying Files

In file system operations, security context must now be considered in terms of the label of the file, the process accessing it, and the directories where the operation is happening. Because of this, moving and copying files with mv and cp may have unexpected results.
Copying Files: SELinux Options for cp
Unless you specify otherwise, cp follows the default behavior of creating a new file based on the domain of the creating process and the type of the target directory. Unless there is a specific rule to set the label, the file inherits the type from the target directory.
Use the -Z user:role:type option to specify the required label for the new file.
The -p (or --preserve=mode,ownership,timestamps) option preserves the specified attributes and, if possible, additional attributes such as links.
touch bar foo
ls -Z bar foo
-rw-rw-r--  auser   auser   user_u:object_r:user_home_t   bar
-rw-rw-r--  auser   auser   user_u:object_r:user_home_t   foo
If you use the cp command without any additional command-line arguments, a copy of the file is created in the new location using the default type of the creating process and the target directory. In this case, because there is no specific rule that applies to cp and /tmp, the new file has the type of the parent directory:
cp bar /tmp
ls -Z /tmp/bar
-rw-rw-r--  auser   auser   user_u:object_r:tmp_t   /tmp/bar
The type tmp_t is the default type for temporary files.
Use the -Z option to specify the label for the new file:
cp -Z user_u:object_r:user_home_t foo /tmp
ls -Z /tmp/foo
-rw-rw-r--  auser   auser   user_u:object_r:user_home_t   /tmp/foo
Moving Files: SELinux Options for mv
Moving files with mv retains the original type associated with the file. Care should be taken using this command as it can cause problems. For example, if you move files with the type user_home_t into ~/public_html, then the httpd daemon is not able to serve those files until you relabel them. Refer to Seção 48.1.3, “Relabeling a File or Directory” for more information about file labeling.
Tabela 48.1. Behavior of mv and cp Commands
Command Behavior
mv The file retains its original label. This may cause problems, confusion, or minor insecurity. For example, the tmpwatch program running in the sbin_t domain might not be allowed to delete an aged file in the /tmp directory because of the file's type.
cp Makes a copy of the file using the default behavior based on the domain of the creating process (cp) and the type of the target directory.
cp -p Makes a copy of the file, preserving the specified attributes and security contexts, if possible. The default attributes are mode, ownership, and timestamps. Additional attributes are links and all.
cp -Z <user:role:type> Makes a copy of the file with the specified labels. The -Z option is synonymous with --context.

48.1.2. Checking the Security Context of a Process, User, or File Object

Checking a Process ID
In Red Hat Enterprise Linux, the -Z option is equivalent to --context, and can be used with the ps, id, ls, and cp commands. The behavior of the cp command with respect to SELinux is explained in Tabela 48.1, “Behavior of mv and cp Commands”.
The following example shows a small sample of the output of the ps command. Most of the processes are running in the unconfined_t domain, with a few exceptions.
[user@localhost ~]$ ps auxZ
LABEL                           USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
system_u:system_r:init_t        root         1  0.0  0.1   2032   620 ?        Ss   15:09   0:00 init [5]
system_u:system_r:kernel_t      root         2  0.0  0.0      0     0 ?        S    15:09   0:00 [migration/0]
system_u:system_r:kernel_t      root         3  0.0  0.0      0     0 ?        SN   15:09   0:00 [ksoftirqd/0]

user_u:system_r:unconfined_t    user     3122  0.0  0.6   6908  3232 ?        S    16:47   0:01 /usr/libexec/gconfd-2 5
user_u:system_r:unconfined_t    user     3125  0.0  0.1   2540   588 ?        S    16:47   0:00 /usr/bin/gnome-keyring-daemon
user_u:system_r:unconfined_t    user     3127  0.0  1.4  33612  6988 ?        Sl   16:47   0:00 /usr/libexec/gnome-settings-daemon
user_u:system_r:unconfined_t    user     3144  0.1  1.4  16528  7360 ?        Ss   16:47   0:01 metacity --sm-client-id=default1
user_u:system_r:unconfined_t    user     3148  0.2  2.9  79544 14808 ?        Ss   16:47   0:03 gnome-panel --sm-client-id default2

Checking a User ID
You can use the -Z option with the id command to determine a user's security context. Note that with this command you cannot combine -Z with other options.
[root@localhost ~]# id -Z
user_u:system_r:unconfined_t
Note that you cannot use the -Z option with the id command to inspect the security context of a different user. That is, you can only display the security context of the currently logged-in user:
[user@localhost ~]$ id
uid=501(user) gid=501(user) groups=501(user) context=user_u:system_r:unconfined_t
[user@localhost ~]$ id root
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
[user@localhost ~]$ id -Z root
id: cannot display context when selinux not enabled or when displaying the id
of a different user
Check a File ID
You can use the -Z option with the ls command to group common long-format information. You can display mode, user, group, security context, and filename information.
cd /etc
ls -Z h* -d
drwxr-xr-x  root root  system_u:object_r:etc_t        hal
-rw-r--r--  root root  system_u:object_r:etc_t        host.conf
-rw-r--r--  root root  user_u:object_r:etc_t          hosts
-rw-r--r--  root root  system_u:object_r:etc_t        hosts.allow
-rw-r--r--  root root  system_u:object_r:etc_t        hosts.canna
-rw-r--r--  root root  system_u:object_r:etc_t        hosts.deny
drwxr-xr-x  root root  system_u:object_r:hotplug_etc_t  hotplug
drwxr-xr-x  root root  system_u:object_r:etc_t        hotplug.d
drwxr-xr-x  root root  system_u:object_r:httpd_sys_content_t htdig
drwxr-xr-x  root root  system_u:object_r:httpd_config_t httpd

48.1.3. Relabeling a File or Directory

You may need to relabel a file when moving or copying into special directories related to the targeted daemons, such as ~/public_html directories, or when writing scripts that work in directories outside of /home.
There are two general types of relabeling operations:
  • Deliberately changing the type of a file
  • Restoring files to the default state according to policy
There are also relabeling operations that an administrator performs. These are covered in Seção 48.2.2, “Relabeling a File System”.

Tip

The majority of SELinux permission control in the targeted policy is Type Enforcement (TE). Consequently, you can generally ignore the user and role information in a security label and focus on just changing the type. You do not normally need to consider the role and user settings on files.

Note

If relabeling affects the label on a daemon's executable, you should restart the daemon to be sure it is running in the correct domain. For example, if /usr/sbin/mysqld has the wrong security label, and you address this by using a relabeling operation such as restorecon, you must restart mysqld after the relabeling operation. Setting the executable file to have the correct type (mysqld_exec_t) ensures that it transitions to the proper domain when started.
Use the chcon command to change a file to the correct type. You need to know the correct type that you want to apply to use this command. The directories and files in the following example are labeled with the default type defined for file system objects created in /home:
cd ~
ls -Zd public_html/
drwxrwxr-x  auser  auser  user_u:object_r:user_home_t public_html/

ls -Z web_files/
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   1.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   2.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   3.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   4.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   5.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   index.html
If you move these files into the public_html directory, they retain the original type:
mv web_files/* public_html/
ls -Z public_html/
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   1.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   2.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   3.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   4.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   5.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t   index.html
To make these files viewable from a special user public HTML folder, they need to have a type that httpd has permissions to read, presuming the Apache HTTP Server is configured for UserDir and the Boolean value httpd_enable_homedirs is enabled.
chcon -R -t httpd_user_content_t public_html/
ls -Z public_html
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t   1.html
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t   2.html
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t   3.html
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t   4.html
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t   5.html
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t   index.html

ls -Z public_html/ -d
drwxrwxr-x  auser  auser  user_u:object_r:httpd_user_content_t  public_html/

Tip

If the file has no label, such as a file created while SELinux was disabled in the kernel, you need to give it a full label with chcon system_u:object_r:shlib_t foo.so. Otherwise, you will receive an error about applying a partial context to an unlabeled file.
Use the restorecon command to restore files to the default values according to the policy. There are two other methods for performing this operation that work on the entire file system: fixfiles or a policy relabeling operation. Each of these methods requires superuser privileges. Cautions against both of these methods appear in Seção 48.2.2, “Relabeling a File System”.
The following example demonstrates restoring the default user home directory context to a set of files that have different types. The first two sets of files have different types, and are being moved into a directory for archiving. Their contexts are different from each other, and are incorrect for a standard user's home directory:
ls -Z /tmp/
-rw-rw-r--  auser  auser  user_u:object_r:tmp_t            /tmp/file1
-rw-rw-r--  auser  auser  user_u:object_r:tmp_t            /tmp/file2
-rw-rw-r--  auser  auser  user_u:object_r:tmp_t            /tmp/file3

mv /tmp/{1,2,3} archives/
mv public_html/* archives/
ls -Z archives/
-rw-rw-r--  auser  auser  user_u:object_r:tmp_t            file1
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t    file1.html
-rw-rw-r--  auser  auser  user_u:object_r:tmp_t            file2
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t    file2.html
-rw-rw-r--  auser  auser  user_u:object_r:tmp_t            file3
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t    file3.html
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t    file4.html
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t    file5.html
-rw-rw-r--  auser  auser  user_u:object_r:httpd_user_content_t  index.html
The archives/ directory already has the default type because it was created in the user's home directory:
ls -Zd archives/
drwxrwxr-x  auser  auser  user_u:object_r:user_home_t  archives/
Using the restorecon command to relabel the files uses the default file contexts set by the policy, so these files are labeled with the default label for their current directory.
/sbin/restorecon -R archives/
ls -Z archives/
-rw-rw-r--  auser  auser  system_u:object_r:user_home_t    file1
-rw-rw-r--  auser  auser  system_u:object_r:user_home_t    file1.html
-rw-rw-r--  auser  auser  system_u:object_r:user_home_t    file2
-rw-rw-r--  auser  auser  system_u:object_r:user_home_t    file2.html
-rw-rw-r--  auser  auser  system_u:object_r:user_home_t    file3
-rw-rw-r--  auser  auser  system_u:object_r:user_home_t    file3.html
-rw-rw-r--  auser  auser  system_u:object_r:user_home_t    file4.html
-rw-rw-r--  auser  auser  system_u:object_r:user_home_t    file5.html
-rw-rw-r--  auser  auser  system_u:object_r:user_home_t    index.html

48.1.4. Creating Archives That Retain Security Contexts

You can use either the tar or star utilities to create archives that retain SELinux security contexts. The following example uses star to demonstrate how to create such an archive. You need to use the appropriate -xattr and -H=exustar options to ensure that the extra attributes are captured and that the header for the *.star file is of a type that fully supports xattrs. Refer to the man page for more information about these and other options.
The following example illustrates the creation and extraction of a set of html files and directories. Note that the two directories have different labels. Unimportant parts of the file context have been omitted for printing purposes (indicated by ellipses '...'):
ls -Z public_html/ web_files/

public_html/:
-rw-rw-r--  auser  auser  ...httpd_user_content_t 1.html
-rw-rw-r--  auser  auser  ...httpd_user_content_t 2.html
-rw-rw-r--  auser  auser  ...httpd_user_content_t 3.html
-rw-rw-r--  auser  auser  ...httpd_user_content_t 4.html
-rw-rw-r--  auser  auser  ...httpd_user_content_t 5.html
-rw-rw-r--  auser  auser  ...httpd_user_content_t index.html
web_files/:
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  1.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  2.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  3.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  4.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  5.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  index.html
The following command creates the archive, retaining all of the SELinux security contexts:
star -xattr -H=exustar -c -f all_web.star public_html/ web_files/
star: 11 blocks + 0 bytes (total of 112640 bytes = 110.00k).
Use the ls command with the -Z option to validate the security context:
ls -Z all_web.star
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t \  all_web.star
You can now copy the archive to a different directory. In this example, the archive is copied to /tmp. If there is no specific policy to make a derivative temporary type, the default behavior is to acquire the tmp_t type.
cp all_web.star /tmp/ cd /tmp/

ls -Z all_web.star
-rw-rw-r--  auser  auser  user_u:object_r:tmp_t  all_web.star
Now you can expand the archives using star and it restores the extended attributes:
star -xattr -x -f all_web.star
star: 11 blocks + 0 bytes (total of 112640 bytes = 110.00k).

ls -Z /tmp/public_html/ /tmp/web_files/
/tmp/public_html/:
-rw-rw-r--  auser  auser  ...httpd_sys_content_t 1.html
-rw-rw-r--  auser  auser  ...httpd_sys_content_t 2.html
-rw-rw-r--  auser  auser  ...httpd_sys_content_t 3.html
-rw-rw-r--  auser  auser  ...httpd_sys_content_t 4.html
-rw-rw-r--  auser  auser  ...httpd_sys_content_t 5.html
-rw-rw-r--  auser  auser  ...httpd_sys_content_t index.html
/tmp/web_files/:
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  1.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  2.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  3.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  4.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  5.html
-rw-rw-r--  auser  auser  user_u:object_r:user_home_t  \ index.html

Caution

If you use an absolute path when you create an archive using star, the archive expands on that same path. For example, an archive made with this command restores the files to /var/log/httpd/:
star -xattr -H=exustar -c -f httpd_logs.star /var/log/httpd/
If you attempt to expand this archive, star issues a warning if the files in the path are newer than the ones in the archive.

48.2. Administrator Control of SELinux

In addition to the tasks often performed by users in Seção 48.1, “End User Control of SELinux”, SELinux administrators could be expected to perform a number of additional tasks. These tasks typically require root access to the system. Such tasks are significantly easier under the targeted policy. For example, there is no need to consider adding, editing, or deleting Linux users from the SELinux users, nor do you need to consider roles.
This section covers the types of tasks required of an administrator who maintains Red Hat Enterprise Linux running SELinux.

48.2.1. Viewing the Status of SELinux

The sestatus command provides a configurable view into the status of SELinux. The simplest form of this command shows the following information:
~]# sestatus
SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   enforcing
Mode from config file:          enforcing
Policy version:                 21
Policy from config file:        targeted
The -v option includes information about the security contexts of a series of files that are specified in /etc/sestatus.conf:
~]# sestatus -v
SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   enforcing
Mode from config file:          enforcing
Policy version:                 21
Policy from config file:        targeted

Process contexts:
Current context:                user_u:system_r:unconfined_t
Init context:                   system_u:system_r:init_t
/sbin/mingetty                  system_u:system_r:getty_t
/usr/sbin/sshd                  system_u:system_r:unconfined_t:s0-s0:c0.c1023

File contexts:
Controlling term:               user_u:object_r:devpts_t
/etc/passwd                     system_u:object_r:etc_t
/etc/shadow                     system_u:object_r:shadow_t
/bin/bash                       system_u:object_r:shell_exec_t
/bin/login                      system_u:object_r:login_exec_t
/bin/sh                         system_u:object_r:bin_t -> system_u:object_r:shell_exec_t
/sbin/agetty                    system_u:object_r:getty_exec_t
/sbin/init                      system_u:object_r:init_exec_t
/sbin/mingetty                  system_u:object_r:getty_exec_t
/usr/sbin/sshd                  system_u:object_r:sshd_exec_t
/lib/libc.so.6                  system_u:object_r:lib_t -> system_u:object_r:lib_t
/lib/ld-linux.so.2              system_u:object_r:lib_t -> system_u:object_r:ld_so_t
The -b displays the current state of booleans. You can use this in combination with grep or other tools to determine the status of particular booleans:
~]# sestatus -b | grep httpd | grep on$
httpd_builtin_scripting           on
httpd_disable_trans               on
httpd_enable_cgi                  on
httpd_enable_homedirs             on
httpd_unified                     on

48.2.2. Relabeling a File System

You may never need to relabel an entire file system. This usually occurs only when labeling a file system for SELinux for the first time, or when switching between different types of policy, such as changing from the targeted to the strict policy.
Relabeling a File System Using init
The recommended method for relabeling a file system is to reboot the machine. This allows the init process to perform the relabeling, ensuring that applications have the correct labels when they are started and that they are started in the right order. If you relabel a file system without rebooting, some processes may continue running with an incorrect context. Manually ensuring that all the daemons are restarted and running in the correct context can be difficult.
Use the following procedure to relabel a file system using this method.
touch /.autorelabel
reboot
At boot time, init.rc checks for the existence of /.autorelabel. If this file exists, SELinux performs a complete file system relabel (using the /sbin/fixfiles -f -F relabel command), and then deletes /.autorelabel.
Relabeling a File System Using fixfiles
It is possible to relabel a file system using the fixfiles command, or to relabel based on the RPM database:
Use the following command to relabel a file system only using the fixfiles command:
fixfiles relabel
Use the following command to relabel a file system based on the RPM database:
fixfiles -R <packagename> restore
Using fixfiles to restore contexts from packages is safer and quicker.

Caution

Running fixfiles on the entire file system without rebooting may make the system unstable.
If the relabeling operation applies a new policy that is different from the policy that was in place when the system booted, existing processes may be running in incorrect and insecure domains. For example, a process could be in a domain that is not an allowed transition for that process in the new policy, granting unexpected permissions to that process alone.
In addition, one of the options to fixfiles relabel prompts for approval to empty /tmp/ because it is not possible to reliably relabel /tmp/. Since fixfiles is run as root, temporary files that applications are relying upon are erased. This could make the system unstable or behave unexpectedly.

48.2.3. Managing NFS Home Directories

In Red Hat Enterprise Linux 5, most targeted daemons do not interact with user data and are not affected by NFS-mounted home directories. One exception is the Apache HTTP Server. For example, CGI scripts that are on the mounted file system have the nfs_t type, which is not a type that httpd_t is allowed to execute.
If you are having problems with the default type of nfs_t, try mounting the home directories with a different context:
mount -t nfs -o context=user_u:object_r:user_home_dir_t \
	fileserver.example.com:/shared/homes/ /home

Caution

Seção 48.2.9, “Specifying the Security Context of Entire File Systems” explains how to mount a directory so that httpd can execute scripts. If you do this for user home directories, it gives the Apache HTTP Server increased access to those directories. Remember that a mountpoint label applies to the entire mounted file system.
Future versions of the SELinux policy address the functionality of NFS.

48.2.4. Granting Access to a Directory or a Tree

Similar to standard Linux DAC permissions, a targeted daemon must have SELinux permissions to be able to descend the directory tree. This does not mean that a directory and its contents need to have the same type. There are many types, such as root_t, tmp_t, and usr_t that grant read access for a directory. These types are suitable for directories that do not contain any confidential information, and that you want to be widely readable. They could also be used for a parent directory of more secured directories with different contexts.
If you are working with an avc: denied message, there are some common problems that arise with directory traversal. For example, many programs run a command equivalent to ls -l / that is not necessary to their operation but generates a denial message in the logs. For this you need to create a dontaudit rule in your local.te file.
When trying to interpret AVC denial messages, do not be misled by the path=/ component. This path is not related to the label for the root file system, /. It is actually relative to the root of the file system on the device node. For example, if your /var/ directory is located on an LVM (Logical Volume Management [22]) device, /dev/dm-0, the device node is identified in the message as dev=dm-0. When you see path=/ in this example, that is the top level of the LVM device dm-0, not necessarily the same as the root file system designation /.

48.2.5. Backing Up and Restoring the System

48.2.6. Enabling or Disabling Enforcement

You can enable and disable SELinux enforcement at runtime or configure it to start in the correct mode at boot time, using the command line or GUI. SELinux can operate in one of three modes: disabled, meaning not enabled in the kernel; permissive, meaning SELinux is running and logging but not controlling permissions; or enforcing, meaning SELinux is running and enforcing policy.
Use the setenforce command to change between permissive and enforcing modes at runtime. Use setenforce 0 to enter permissive mode; use setenforce 1 to enter enforcing mode.
The sestatus command displays the current mode and the mode from the configuration file referenced during boot:
~]# sestatus | grep -i mode
Current mode:           permissive
Mode from config file:  permissive
Note that changing the runtime enforcement does not affect the boot time configuration:
~]# setenforce 1
~]# sestatus | grep -i mode
Current mode:           enforcing
Mode from config file:  permissive
You can also disable enforcing mode for a single daemon. For example, if you are trying to troubleshoot the named daemon and SELinux, you can turn off enforcing for just that daemon.
Use the getsebool command to get the current status of the boolean:
~]# getsebool named_disable_trans
named_disable_trans --> off
Use the following command to disable enforcing mode for this daemon:
~]# setsebool named_disable_trans 1
~]# getsebool named_disable_trans
named_disable_trans --> on

Note

This sets the runtime value only. Use the -P option to make the change persistent across reboots.
Any *_disable_trans booleans that are set to "on" invoke the conditional that prevents the process from transitioning to the domain on execution.
Use the following command to find which of these booleans are set:
~]# getsebool -a | grep disable.*on
httpd_disable_trans=1
mysqld_disable_trans=1
ntpd_disable_trans=1
You can set any number of boolean values using the setsebool command:
setsebool -P httpd_disable_trans=1 mysqld_disable_trans=1 ntpd_disable_trans=1
You can also use togglesebool <boolean_name> to change the value of a specific boolean:
~]# getsebool httpd_disable_trans
httpd_disable_trans --> off
~]# togglesebool httpd_disable_trans
httpd_disable_trans: active
You can configure all of these settings using system-config-selinux. The same configuration files are used, so changes appear bidirectionally.
Changing a Runtime Boolean
Use the following procedure to change a runtime boolean using the GUI.

Note

Administrator privileges are required to perform this procedure.
  1. On the System menu, point to Administration and then click Security Level and Firewall to display the Security Level Configuration dialog box.
  2. Click the SELinux tab, and then click Modify SELinux Policy.
  3. In the selection list, click the arrow next to the Name Service entry, and select the Disable SELinux protection for named daemon check box.
  4. Click OK to apply the change. Note that it may take a short time for the policy to be reloaded.
Using the Security Level Configuration dialog box to change a runtime boolean.
Using the Security Level Configuration dialog box to change a runtime boolean.
Figura 48.1. Using the Security Level Configuration dialog box to change a runtime boolean.

If you want to control these settings with scripts, you can use the setenforce(1), getenforce(1), and selinuxenabled(1) commands.

48.2.7. Enable or Disable SELinux

Important

Changes you make to files while SELinux is disabled may give them an unexpected security label, and new files will not have a label. You may need to relabel part or all of the file system after re-enabling SELinux.
From the command line, you can edit the /etc/sysconfig/selinux file. This file is a symlink to /etc/selinux/config. The configuration file is self-explanatory. Changing the value of SELINUX or SELINUXTYPE changes the state of SELinux and the name of the policy to be used the next time the system boots.
~]# cat /etc/sysconfig/selinux
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - SELinux is fully disabled.
SELINUX=permissive
# SELINUXTYPE= type of policy in use. Possible values are:
#       targeted - Only targeted network daemons are protected.
#       strict - Full SELinux protection.
SELINUXTYPE=targeted

# SETLOCALDEFS= Check local definition changes
SETLOCALDEFS=0
Changing the Mode of SELinux Using the GUI
Use the following procedure to change the mode of SELinux using the GUI.

Note

You need administrator privileges to perform this procedure.
  1. On the System menu, point to Administration and then click Security Level and Firewall to display the Security Level Configuration dialog box.
  2. Click the SELinux tab.
  3. In the SELinux Setting select either Disabled, Enforcing or Permissive, and then click OK.
  4. If you changed from Enabled to Disabled or vice versa, you need to restart the machine for the change to take effect.
Changes made using this dialog box are immediately reflected in /etc/sysconfig/selinux.

48.2.8. Changing the Policy

This section provides a brief introduction to using customized policies on your system. A full discussion of this topic is beyond the scope of this document.
To load a different policy on your system, change the following line in /etc/sysconfig/selinux:
SELINUXTYPE=<policyname>
where <policyname> is the policy name directory under /etc/selinux/. This assumes that you have the custom policy installed. After changing the SELINUXTYPE parameter, run the following commands:
touch /.autorelabel
reboot
Use the following procedure to load a different policy using the system-config-selinux utility:

Note

You need administrator privileges to perform this procedure.
  1. Ensure that the complete directory structure for the required policy exists under /etc/selinux.
  2. On the System menu, point to Administration and then click Security Level and Firewall to display the Security Level Configuration dialog box.
  3. Click the SELinux tab.
  4. In the Policy Type list, select the policy that you want to load, and then click OK. This list is only visible if more than one policy is installed.
  5. Restart the machine for the change to take effect.
Using the Security Level Configuration dialog box to load a custom policy.
Using the Security Level Configuration dialog box to load a custom policy.
Figura 48.2. Using the Security Level Configuration dialog box to load a custom policy.

48.2.9. Specifying the Security Context of Entire File Systems

You can use the mount -o context= command to set a single context for an entire file system. This might be a file system that is already mounted and that supports xattrs, or a network file system that obtains a genfs label such as cifs_t or nfs_t.
For example, if you need the Apache HTTP Server to read from a mounted directory or loopback file system, you need to set the type to httpd_sys_content_t:
mount -t nfs -o context=system_u:object_r:httpd_sys_content_t \
	server1.example.com:/shared/scripts /var/www/cgi

Tip

When troubleshooting httpd and SELinux problems, reduce the complexity of your situation. For example, if you have the file system mounted at /mnt and then symbolically linked to /var/www/html/foo, you have two security contexts to be concerned with. Because one security context is of the object class file and the other of type lnk_file, they are treated differently by the policy and unexpected behavior may occur.

48.2.10. Changing the Security Category of a File or User

Refer to Seção 47.5.5, “Assigning Categories to Files” and Seção 47.5.4, “Assigning Categories to Users” for information about adding and changing the security categories of files and users.

48.2.11. Running a Command in a Specific Security Context

You can use the runcon command to run a command in a specific context. This is useful for scripting or for testing policy, but care should be taken to ensure that it is implemented correctly.
For example, you could use the following command to run a script to test for mislabeled content. The arguments that appear after the command are considered to be part of the command. (In this example, ~/bin/contexttest is a user-defined script.)
runcon -t httpd_t ~/bin/contexttest -ARG1 -ARG2
You can also specify the entire context, as follows:
runcon user_u:system_r:httpd_t ~/bin/contexttest

48.2.12. Useful Commands for Scripts

The following is a list of useful commands introduced with SELinux, and which you may find useful when writing scripts to help administer your system:
getenforce
This command returns the enforcing status of SELinux.
setenforce [ Enforcing | Permissive | 1 | 0 ]
This command controls the enforcing mode of SELinux. The option 1 or Enforcing tells SELinux to enter enforcing mode. The option 0 or Permissive tells SELinux to enter passive mode. Access violations are still logged, but not prevented.
selinuxenabled
This command exits with a status of 0 if SELinux is enabled, and 1 if SELinux is disabled.
~]# selinuxenabled
~]# echo $?
0
getsebool [-a] [boolean_name]
This command shows the status of all booleans (-a) or a specific boolean (<boolean_name>).
setsebool [-P] <boolean_name> value | bool1=val1 bool2=val2 ...
This command sets one or more boolean values. The -P option makes the changes persistent across reboots.
togglesebool boolean ...
This command toggles the setting of one or more booleans. This effects boolean settings in memory only; changes are not persistent across reboots.

48.2.13. Changing to a Different Role

You use the newrole command to run a new shell with the specified type and/or role. Changing roles is typically only meaningful in the strict policy; the targeted policy is generally restricted to a single role. Changing types may be useful for testing, validation, and development purposes.
newrole -r <role_r> -t <type_t> [-- [ARGS]...]
The ARGS are passed directly to the shell specified in the user's entry in the /etc/passwd file.

Note

The newrole command is part of the policycoreutils-newrole package, which is required if you install the strict or MLS policy. It is not installed by default in Red Hat Enterprise Linux.

48.2.14. When to Reboot

The primary reason for rebooting the system from an SELinux perspective is to completely relabel the file system. On occasion you might need to reboot the system to enable or disable SELinux.

48.3. Controle Analítico do SELinux

Esta seção descreve algumas tarefas comuns que um analista de segurança pode precisar trabalhar em um sistema SELinux

48.3.1. Habilitando a Auditoria Kernel

Como parte de um exercício de análise ou solução de problemas do SELinux, você pode escolher habilitar a auditoria em nível kernel completo. Esta escolha pode ser um tanto detalhada, pois gera uma ou mais mensagens de auditoria para cada mensagem de auditoria AVC. Para habilitar este nível de auditoria, acrescente o parâmetro audit=1 à sua linha de inicialização kernel, tanto no arquivo /etc/grub.conf quanto no menu GRUB no tempo de inicialização.
Este é um exemplo de uma entrada log de auditoria completa quando o httpd é negado o acesso do ~/public_html pois o diretório não está rotulado como conteúdo da Web. Note que o tempo e o carimbo com números em série no campo de auditoria (...), são idênticos. Isto facilita rastrear um evento em específico nos logs de auditoria:
Jan 15 08:03:56 hostname kernel: audit(1105805036.075:2392892): \
	avc:  denied  { getattr } for  pid=2239 exe=/usr/sbin/httpd \
	path=/home/auser/public_html dev=hdb2 ino=921135 \
	scontext=user_u:system_r:httpd_t \
	tcontext=system_u:object_r:user_home_t tclass=dir
As mensagens de auditoria a seguir, oferecem mais informações sobre a fonte, incluindo o tipo de chamada de sistema involvido, mostrando que o httpd tentou iniciar o diretório:
Jan 15 08:03:56 hostname kernel: audit(1105805036.075:2392892): \
	syscall=195 exit=4294967283 a0=9ef88e0 a1=bfecc0d4 a2=a97ff4 \
	a3=bfecc0d4 items=1 pid=2239 loginuid=-1 uid=48 gid=48 euid=48 \
	suid=48 fsuid=48 egid=48 sgid=48 fsgid=48
A mensagem a seguir oferece mais informações sobre o alvo:
Jan 15 08:03:56 hostname kernel: audit(1105805036.075:2392892): \
	item=0 name=/home/auser/public_html inode=921135 dev=00:00
O carimbo com número em série é sempre idêntico para um evento auditado em particular. O carimbo de data e hora pode ou não ser idêntico.

Nota

If you are using an audit daemon for troubleshooting, the daemon may capture audit messages into a location other than /var/log/messages, such as /var/log/audit/audit.log.

48.3.2. Despejo e Visualização de Logs.

A implementação Red Hat Enterprise Linux das rotas SELinux de mensagens de auditoria AVC para /var/log/messages. Você pode usar qualquer um dos utilitários de procura padrão (por exemplo,grep), para procurar por linhas que contenham avc or audit.


[22] LVM is the grouping of physical storage into virtual pools that are partitioned into logical volumes.

Capítulo 49. Padronizando a Política do SELinux

49.1. Apresentação

Nos lançamentos de Red Hat Enterprise Linuxanteriores, era necessário instalar os pacotes selinux-policy-targeted-sources e somente então criar um arquivo local.te no diretório /etc/selinux/targeted/src/policy/domains/misc. Você poderia usar o utilitário audit2allow para traduzir as mensagens AVC em regras de permissão e então reconstruir e recarregar a política.
O problema era que, todas as vezes que um pacote de política novo era lançado, o Makefile era executado para tentar manter a política local.
No Red Hat Enterprise Linux5, este processo foi completamente revisado. Os pacotes das "fontes" rpm foram completamente removidos, e os pacotes de política são tratados mais como um kernel. Para pesquisar nas fontes usadas para construir a política, você precisa instalar o rpm fonte selinux-policy-XYZ.src.rpm. Um pacote extra, selinux-policy-devel também foi adicionado, o qual oferece funcionalidade de padronização extra.

49.1.1. Política modular

Red Hat Enterprise Linux apresenta o conceito de política modular. Esta política permite que o fabricante envie a política SELinux separado da política do sistema de operações. Isto permite que os administradores façam mudanças locais na política sem se preocuparem com a próxima instalação da mesma. O comando adicionado mais importante é o semodule.
O semodule é a ferramenta utilizada para gerenciar o SELinux módulos de política, incluindo instalar, atualizar, listar e remover módulos. Você também pode utilizar o semodule para forçar uma reconstrução de política a partir do módulo armazenar e/ou forçar uma recarga de política sem desempenhar qualquer outra transação. O semodule age nos pacotes de módulo, criados pelo semodule_package. Geralmente, estes arquivos possuem um sufixo .pp (pacote de política), embora não seja obrigatório.

49.1.1.1. Listando Módulos de Política

Para listar os módulos de política em um sistema, use o comando semodule -l:
~]# semodule -l
amavis  1.1.0
ccs     1.0.0
clamav  1.1.0
dcc     1.1.0
evolution       1.1.0
iscsid  1.0.0
mozilla 1.1.0
mplayer 1.1.0
nagios  1.1.0
oddjob  1.0.1
pcscd   1.0.0
pyzor   1.1.0
razor   1.1.0
ricci   1.0.0
smartmon        1.1.0

Nota

Este comando não lista o módulo de política base, que também está instalado.
O diretório /usr/share/selinux/targeted/ contém diversos arquivos de pacote de política (*.pp). Estes arquivos estão inclusos no rpm selinux-policy e são utilizados para construir o arquivo de política.

49.2. Construindo um Módulo de Política Local

A seção a seguir, utiliza um exemplo atual para demonstrar a construção de um módulo de política local para apontar um problema com a política atual. Este problema envolve o script ypbind init, que executa o comando setsebool, que por sua vez, tenta utilizar o terminal. Isto gera a seguinte negação:
type=AVC msg=audit(1164222416.269:22): avc:  denied  { use } for  pid=1940 comm="setsebool" name="0" dev=devpts ino=2 \
	scontext=system_u:system_r:semanage_t:s0 tcontext=system_u:system_r:init_t:s0 tclass=fd
Embora tudo ainda funcione corretamente (ou seja, não evita que nenhum formulário de aplicativo rode como pretendido), ele interrompe o fluxo de trabalho normal do usuário. Ao criar um módulo de política local, você soluciona este problema.

49.2.1. Usar o audit2 permite a Construção de um Módulo de Política Local.

O utilitário audit2allow possui agora a habilidade de construir módulos de política . Use o seguinte comando para construir um módulo de política baseado em conteúdo específico do arquivo audit.log:
ausearch -m AVC --comm setsebool | audit2allow -M mysemanage
O utilitário audit2allow construiu um arquivo de imposição (mysemanage.te). Depois, ele executou o comando checkmodule para compilar um arquivo de módulo (mysemanage.mod). Por último, ele usa o comando semodule_package para criar um pacote de política (mysemanage.pp). O comando semodule_package combina arquivos de política diferentes (geralmente somente o módulo e potencialmente um arquivo de contexto) no pacote de política.

49.2.2. Analisando o Arquivo Tipo Enforcement (TE)

Use o comando cat para inspecionar o conteúdo do arquivo TE:
~]# cat mysemanag.te
module mysemanage 1.0;

require {
	class fd use;
	type init_t;
	type semanage_t;
	role system_r;
};

allow semanage_t init_t:fd use;
O arquivo TE é composto por três seções. A primeira seção é o comando module, que identifica o nome do módulo e versão. O nome do módulo deve ser único. Se você criar um módulo semanage usando o nome de um módulo pré-existente, o sistema tentaria substituir o pacote do módulo existente por uma versão nova. A última parte da linha do módulo é a versão. O semodule pode atualizar pacotes de módulo e checar a versão atualizada em relação à versão instalada atualmente.
O próximo bloco do arquivo TE é o bloco require. Este, informa o carregador de política, quais tipos, classes e papéis são necessários na política de sistema, antes que este módulo possa ser instalado. Se qualquer um destes campos forem indefinidos, o comando semodule irá falhar.
Por último, estão as regras de permissão. Neste exemplo, você poderia modificar esta linha para dontaudit, pois semodule não precisa acessar o descritor do arquivo.

49.2.3. Carregando o Pacote de Política

O último passo a ser dado neste processo de criação de um módulo de política local é carregar o pacote da política no kernel.
Use o comando semodule para carregar o pacote de política:
~]# semodule -i mysemanage.pp
Este comando recompila o arquivo de política e regenera o contexto do arquivo. As mudanças são permanentes e irão sobreviver a uma reinicialização. Você pode também copiar o arquivo com o pacote de política (mysemanage.pp) para outras máquinas e instalá-lo utilizando o semodule.
O comando audit2allow exibe a saída do comando que ele executou para criar um pacote de política onde você possa editar o arquivo TE. Isto significa que você pode adicionar novas regras como solicitado ou mudar a regra de permissão para dontaudit. Você pode então recompilar e reempacotar o pacote de política para ser novamente instalado.
Não existe limite para o número de pacotes de políticas, portanto, você pode criar um para cada modificação local, mas você precisa se assegurar de que as "instruções solicitadas combinem com todas as outras regras".

Capítulo 50. Referências

As seguintes referências são indicadores para informações adicionais relevantes para SELinux e Red Hat Enterprise Linux mas além do escopo deste guia. Note que devido ao rápido desenvolvimento de SELinux, uma parte deste material pode se aplicar somente à lançamentos específicos do Red Hat Enterprise Linux
Livros
SELinux por Exemplo
Mayer, MacMillan, e Caplan
Prentice Hall, 2007
Tutoriais e Ajuda
Entendendo e Padronizando a Política do Apache HTTP SELinux
Tutoriais e discussões sobre Russell Coker
Política HOWTO de Escrita Genérica SELinux
Base de Conhecimento da Red Hat
Informações Gerais
Website principal da SELInux NSA
NSA SELinux FAQ
Fedora SELinux FAQ
Segurança Aprimorada de Código Livre Linux da NSA SELinux
Tecnologia
Uma Visão Geral de Classes de Objetos e Permissões
Integrando Suporte Flexível para Políticas de Segurança em Sistemas de Operação Linux (uma história de Implementação Flask em Linux)
Implementando SELInux como um Módulo de Segurança Linux
Uma Configuração da Política de Segurança para a Segurança Aprimorada Linux
Comunidade
Página da Comunidade SELinux
IRC
irc.freenode.net, #rhel-selinux

Parte VIII. Treinamento e Certificação Red Hat

Os cursos e certificações Red Hat são sem dúvida considerados os melhores em Linux, e talvez em todo o setor de TI. Ministrado totalmente por peritos da Red Hat, nossos programas de certificação medem a competência em sistemas atuais e estão em grande demanda pelos empregadores e profissionais de TI.
A escolha da certificação mais apropriada para você, depende de sua prévia experiência e objetivos. Mesmo que você seja avançado, ou tenha experiência mínima ou nenhuma sobre o UNIX ou Linux, a Red Hat Treinamentos possui um treinamento e caminho de certificação que mais se adequa às suas necessidades.

Índice

51. Treinamento Red Hat e Certificação
51.1. Três Formas de Treinar
51.2. Centro de Recurso Profissional de Certificação Microsoft
52. Caminhos de Certificação
52.1. Testes de Avaliação Grátis
53. RH033: Red Hat Linux Essentials
53.1. Descrição do Curso
53.1.1. Pré-requisitos
53.1.2. Objetivo
53.1.3. Público
53.1.4. Objetivo dos Cursos
53.1.5. Cursos de acompanhamento
54. RH035: Red Hat Linux Essentials para Profissionais de Windows
54.1. Descrição do Curso
54.1.1. Pré-requisitos
54.1.2. Objetivo
54.1.3. Público
54.1.4. Objetivo dos Cursos
54.1.5. Cursos de acompanhamento
55. RH133: Administração de Sistemas da Red Hat Linux e Certificação (RHCT) Técnica da Red Hat Certificada.
55.1. Descrição do Curso
55.1.1. Pré-requisitos
55.1.2. Objetivo
55.1.3. Público
55.1.4. Objetivo dos Cursos
55.1.5. Cursos de acompanhamento
56. prova RH202 RHCT - A credencial que mais cresce em todo o Linux.
56.1. Descrição do Curso
56.1.1. Pré-requisitos
57. RH253 Administração de Segurança e Rede de Trabalho da Red Hat Linux
57.1. Descrição do Curso
57.1.1. Pré-requisitos
57.1.2. Objetivo
57.1.3. Público
57.1.4. Objetivo dos Cursos
57.1.5. Cursos de acompanhamento
58. RH300: O curso de rastreamento rápido do RHCE ( e exames do RHCE)
58.1. Descrição do Curso
58.1.1. Pré-requisitos
58.1.2. Objetivo
58.1.3. Público
58.1.4. Objetivo dos Cursos
58.1.5. Cursos de acompanhamento
59. AVALIAÇÃO RH302 RHCE
59.1. Descrição do Curso
59.1.1. Pré-requisistos
59.1.2. Conteúdo
60. RHSS333: Segurança empresarial da RED HAT: serviços de rede de trabalho
60.1. Descrição do Curso
60.1.1. Pré-requisitos
60.1.2. Objetivo
60.1.3. Público
60.1.4. Objetivo dos Cursos
60.1.5. Cursos de acompanhamento
61. RH401: Gerenciamento de Implementação e sistemas da Red Hat Enterprise
61.1. Descrição do Curso
61.1.1. Pré-requisitos
61.1.2. Objetivo
61.1.3. Público
61.1.4. Objetivo dos Cursos
61.1.5. Cursos de acompanhamento
62. RH423 Autenticação e Serviços de Diretório da Red Hat Enterprise
62.1. Descrição do Curso
62.1.1. Pré-requisitos
62.1.2. Objetivo
62.1.3. Público
62.1.4. Objetivo dos Cursos
62.1.5. Cursos de acompanhamento
63. SELinux Courses
63.1. RHS427: Introdução ao SELinux e Política Alvo da Red Hat
63.1.1. Público
63.1.2. Sumário do Curso
63.2. RHS429: Red Hat Enterprise SELinux Policy Administration
64. RH436 Gerenciamento de armazenamento da Red Hat Enterprise
64.1. Descrição do Curso
64.1.1. Pré-requisitos
64.1.2. Objetivo
64.1.3. Público
64.1.4. Objetivo dos Cursos
64.1.5. Cursos de acompanhamento
65. RH442: sistema de monitoração e ajuste de desempenho da Red Hat Enterprise
65.1. Descrição de Curso
65.1.1. Pré-requisitos
65.1.2. Objetivo
65.1.3. Público
65.1.4. Objetivo dos Cursos
65.1.5. Cursos de acompanhamento
66. Red Hat Enterprise Linux Cursos de Desenvolvedores
66.1. RHD143: Origens de Programação da Red Hat Linux
66.2. RHD221 Drivers de Dispositivo Red Hat Linux
66.3. RHD236 Red Hat Linux Kernel Internals
66.4. RHD256 Portal e Desenvolvimento de Aplicativo Red Hat Linux
67. Cursos JBoss
67.1. RHD161 JBoss e EJB3 para Java
67.1.1. Pré-requisitos
67.2. RHD163 JBoss para Desenvolvedores da Web
67.2.1. Pré-requisitos
67.3. RHD167: JBOSS - HIBERNATE ESSENTIALS
67.3.1. Pré-requisitos
67.3.2. Sumário do Curso
67.4. RHD267: JBOSS - HIBERNATE AVANÇADO
67.4.1. Pré-requisitos
67.5. RHD261:JBOSS para desenvolvedores de J2EE avançados
67.5.1. Pré-requisitos
67.6. RH336: JBOSS para Administradores
67.6.1. Pré-requisitos
67.6.2. Sumário do Curso
67.7. RHD439: JBoss Clustering
67.7.1. Pré-requisitos
67.8. RHD449: JBoss jBPM
67.8.1. Descrição
67.8.2. Pré-requisitos
67.9. Regras RHD451 JBoss
67.9.1. Pré-requisitos

Capítulo 51. Treinamento Red Hat e Certificação

51.1. Três Formas de Treinar

Inscrições Livres
Os cursos de Inscrição Livre são oferecidos continuamente em mais de 50 países da América do Norte e mais de 125 locais em todo o mundo. Os cursos da Red Hat são baseados— no desempenho—, ou seja, os alunos têm acesso à pelo menos um sistema dedicado e em alguns cursos, até cinco. Os instrutores são todos Engenheiros Certificados da Red Hat com vasta experiência (RHCE) e conhecem bem o curso.
O agendamento para os cursos está diponível em http://www.redhat.com/explore/training
Treinamento Na Empresa
O treinamento na empresa, é realizado pela Red Hat na sua empresa, para grupos de 12 à 16 pessoas por classe. Os funcionários técnicos da Red Hat assistirão seus funcionários técnicos antes do início da aula, para assegurar que o local de treinamento está preparado adequadamente para executar o Red Hat Enterprise Linux, Red Hat ou os cursos do JBoss, e/ou os exames de certificação da Red Hat. Estes treinamentos são uma ótima maneira de treinar grupos grandes de uma só vez. As inscrições livres podem ser acionadas mais tarde para incrementar o treinamento.
Para maiores informações, visite o site http://www.redhat.com/explore/onsite
e-Learning
Totalmente atualizado para o Red Hat Enterprise Linux 4! Não tem tempo para aulas? Os títulos de e-—Learning da Red Hat; são oferecidos online e cobrem as habilidades contidas no RHCT e RHCE. Nosso catálogo também inclui cursos das linguages, script e e-commerce de programação mais recentes.
Para obter uma lista dos cursos, visite o site http://www.redhat.com/explore/elearning

51.2. Centro de Recurso Profissional de Certificação Microsoft

Informações e ofertas sob medida para o Microsoft® Certified Professionals, com a possibilidade de adicionar a certificação Red Hat ao seu portfolio pessoal.
Pesquise hoje mesmo no site http://www.redhat.com/explore/manager

Capítulo 52. Caminhos de Certificação

Certificação de Técnicos da Red Hat ® (RHCT®)
Em seu terceiro ano, a Certificação de Técnicos da Red Hat, é a credencial mais rápida da Linux, contando com mais 15.000 técnicos certificados atualmente. A RHCT é a melhor em estabelecer credenciais básicas Linux e é uma certificação inicial ideal para aqueles em transição de um ambiente não UNIX®/Linux.
As certificações Red Hat são indiscutivelmente consideradas como as melhores em Linux e talvez, de acordo com algumas pessoas, a melhor em TI. Cem por cento ministrado por perítos da Red Hat, nossos programas de certificação mede competência em sistemas reais atuais e estão em grande demanda tanto pelos empregadores quanto pelos profissionais de TI.
A escolha da certificação ideal, depende de sua experiência prévia e objetivos. O fato de você ter um mínimo ou nenhuma experiência em UNIX ou Linux, não importa para a Red Hat Treinamentos, que possui um treinamento e caminho de certificação que mais se adapta às suas necessidades.
Certificação de Engenharia da Red Hat ® (RHCE ®)
A Certificação de Engenharia da Red Hat, iniciou em 1999 e conta hoje com mais de 20.000 perítos em Linux. Mais conhecido como "jóia real das certificações Linux" pelas pesquisas independentes, já lidera o rank do programa RHCE em todo setor de TI.
Certificação de Especialistas de Segurança da Red Hat (RHCSS)
Um RHCSS possui conhecimento sobre segurança RHCE, além de habilidades especializadas na Red Hat Enterprise Linux, Red Hat Directory Server e SELinux para se enquadras nas necessidades dos ambientes da empresa de hoje. RHCSS é a certificação mais recente da Red Hat, e a única deste tipo em Linux.
Certificação de Arquitetura da Red Hat (RHCA)
Os RHCE, que procuram treinamento avançado, podem se inscrever nos cursos de Arquitetura Empresarial e provar sua competência com a mais nova Certificação de Arquitetura da Red Hat. A RHCA é a certificação que leva à Certificação de Técnicos da Red Hat (RHCT) e à Certificação de Engenheiros da Red Hat (RHCE), as certificações mais aclamadas no espaço Linux.

52.1. Testes de Avaliação Grátis

Teste seu conhecimento em Linux e identifique o nível mais apropriado do curso da Red Hat com nossos testes de avaliação automatizados.
Totalmente grátis, sem compromisso, 10 minutos do seu tempo. http://www.redhat.com/explore/assess

Capítulo 53. RH033: Red Hat Linux Essentials

53.1. Descrição do Curso

O primeiro curso para os caminhos das certificações RHCT e RHCE, o RH033 é ideal para pessoas que nunca usaram o Linux ou UNIX e não possuem experiência com linha de comando em qualquer outro sistema operacional. Você aprenderá o básico sobre um ambiente Red Hat Enterprise Linux e lhe prepara para se tornar um adminsitrador de sistemas.

53.1.1. Pré-requisitos

Experiência de nível usuário com qualquer sistema de computação, uso de menus, uso de qualquer interface gráfica de usuário.

53.1.2. Objetivo

Um usuário do Red Hat Enterprise Linux em potencial pode ser produtivo ao usar e padronizar um sistema Red Hat para processos de linhas de comandos comuns e papéis de produtividade em área de trabalho e quem estiver pronto para aprender administração de sistemas (RH133).

53.1.3. Público

Usuários que sejam novos no uso do Linux e não possuam habilidades com linha de comando ou UNIX, que queiram desenvolver e práticar habilidades básicas para uso e controle de seus próprios sistemas Red Hat Linux.

53.1.4. Objetivo dos Cursos

  1. Entender os sistema de arquivos do Linux
  2. Desempenhar manutenção comum de arquivos
  3. Usar e padronizar a interface GNOME
  4. Editar comandos básicos do Linux a partir da linha de comando
  5. Desempenhar tarefas comuns usando GNOME GUI
  6. Abrir, Editar e salvar
  7. Permissões de acesso à arquivos
  8. Padronizar o Sistema X Windows
  9. Combinação de padrão de expressão regular e redireção I/O.
  10. Instalar, atualizar, deletar e consultar pacotes em seu sistema
  11. Utilitários de rede de trabalho para o usuário
  12. Utilitários de um forte usuário

53.1.5. Cursos de acompanhamento

RH133 Administração de Sistemas Red Hat Linux
RH253 Administração de Net. e Sec. da Red Hat Linux
RH300 Rastreamento Rápido da Red Hat Linux RHCE
" Recomendo fortemente este curso à todos aqueles interessados em Linux"——Mike Kimmel, Divisão de Sistemas de IT

Capítulo 54. RH035: Red Hat Linux Essentials para Profissionais de Windows

54.1. Descrição do Curso

Este curso foi criado para profissionais de Windows® sem experiência prévia em UNIX ou Linux e ensina habilidades fundamentais de administração de sistemas do Red Hat Enterprise Linux. O primeiro dia oferece uma transição conceitual e prática para que os participantes somem com sucesso, competências de gerenciamento do Linux aos seus portfolios. Os outros quatro dias restantes, combinam o curso RH033 altamente requisistado, com imersão de conhecimentos básicos de ambientes Linux da Red Hat Enterprise e preparando os participantes para se tornarem futuros administradores de sistemas de plataformas cruzadas. O curso também serve como uma inicialização ao RHCT e um caminho para o RHCE.

54.1.1. Pré-requisitos

É necessário que tenha experiência com tarefas de trabalho usando os produtos Windows OS em níveis técnicos ou de administrador de sistemas; experiência como um profissional de TI; não é necessário possuir experiência prévia em UNIX ou Linux.

54.1.2. Objetivo

Um usuário com fortes conhecimentos em Red Hat Enterprise Linux, familiar com processos de linhas de comando comuns, que possa desempenhar algumas tarefas de administração de sistemas usando ferramentas gráficas. O usuário também estará pronto para adquirir conhecimento profundo sobre administração de sistemas do Red Hat Enterprise Linux (RH133).

54.1.3. Público

O perfil de um aluno ideal é um técnico de Windows que prefere gerenciar servidores usando uma interface de usuário gráfico. Este mesmo aluno também deseja gerenciar efetivamente os sistemas do Red Hat Enterprise Linux e expandir sua habilidade pessoal.

54.1.4. Objetivo dos Cursos

  1. Aprenda a instalar um software, configure a rede de trabalho, configure autenticação e instale e configure vários serviços utilizando ferramentas gráficas.
  2. Entenda os sistema de arquivos do Linux
  3. Edite comandos básicos do Linux a partir da linha de comando
  4. Entenda as permissões de acesso à arquivos
  5. Padronize o Sistema X Windows
  6. Use uma combinação de padrão de expressão normal e redirecionamento I/O.

54.1.5. Cursos de acompanhamento

RH133 Administração de Sistemas Red Hat Linux (pg.8)
RH253 Red Hat Linux de Admin. de Net. e Sec.
RH300 Rastreamento rápido de RHCE Red Hat Linux (pg. 10)
"De forma geral, diria que esta experiência de treinamento foi a melhor que já tive e estou na indústria há mais de 15 anos." — Bill Legge, Consultor de TI

Capítulo 55. RH133: Administração de Sistemas da Red Hat Linux e Certificação (RHCT) Técnica da Red Hat Certificada.

55.1. Descrição do Curso

O RH133 foca nas habilidades em administração de sistemas na Red Hat Linux, em um nível que consiga anexar e configurar uma área de trabalho em uma rede de trabalho existente. Este curso de 4 ou 5 dias oferece um treinamento intensivo e prático na Red Hat Enterprise Linux e envolve o Exame de Laboratório de Certificação RH202 RHCT no último dia.

55.1.1. Pré-requisitos

Conhecimentos básicos do RH033 Red Hat Linux ou experiência equivalente com o Red Hat Linux.

55.1.2. Objetivo

Após o término do curso, os participantes terão conhecimento básico como administradores de sistema, que será provado ao passar o exame RHCT. Este é um exame de laboratório baseado em desempenho que testa a habilidade atual de instalar, configurar e anexar um sistema Red Hat Linux em uma rede de trabalho de produção existente.

55.1.3. Público

Usuários da Linux ou UNIX que possuem conhecimento básico da Red Hat Linux e desejam mais treinamento técnico para iniciar o processo de se tornarem um administrador de sistemas.

55.1.4. Objetivo dos Cursos

  1. Instala o Red Hat Linux de forma interativa e com o Kickstart
  2. Controla o hardware de sistemas comum; admnistrar o subsistema de impressão do Linux.
  3. Cria e mantém o sistema de arquivos da Linux
  4. Usuário de desempenho e administração de grupo
  5. Integra uma estação de trabalho com uma rede de trabalho existente.
  6. Configura uma estação de trabalho como um cliente para NIS, DNS, e serviços DHCP
  7. Automatiza tarefas com at, cron e anacron
  8. Faz o back up de sistemas de arquivo para arquivos de fitas e tar
  9. Manipula pacotes de software com RPM
  10. Configura o Sistema Window X e o GNOME d.e.
  11. Desempenha o desempenho, memória e gerenciamento de processo
  12. Configura segurança básica de host

55.1.5. Cursos de acompanhamento

RH253 Red Hat Linux de Admin. de Net. e Sec.

Capítulo 56. prova RH202 RHCT - A credencial que mais cresce em todo o Linux.

  1. A prova RHCT está inclusa no RH133. Ela também pode ser comprada em separado por $349.
  2. As provas RHCT acontecem no quinto dia das aulas do RH133

56.1. Descrição do Curso

O RHCT (Técnicos Certificados da Red Hat) é prático, suas provas são baseadas no desempenho e testa a habilidade atual do candidato em instalar, configurar e solucionar problemas do Red Hat Enterprise Linux. A prova de laboratório da Certificação é vinculada ao RH133, mas pessoas que possuem total conhecimento do RH033 e RH133 podem simplesmente fazer a prova.

56.1.1. Pré-requisitos

Os candidatos deveriam considerar a possibilidade de fazer o RH033 e RH133 para se prepararem para a prova, mas não é obrigatório.

Capítulo 57. RH253 Administração de Segurança e Rede de Trabalho da Red Hat Linux

57.1. Descrição do Curso

O RH253 arma os alunos com conhecimento profundo, necessário para configurar serviços comuns de rede de trabalho da Red Hat Enterprise. As tarefas de rede de trabalho o segurança local são também tópicos deste curso.

57.1.1. Pré-requisitos

A Administração do Sistema Red Hat Linux RH133 ou experiência equivalente com a Red Hat Enterpise Linux, conhecimento básico de LAN/WAN ou equivalente, trabalho de internet com TCP/IP ou equivalente.

57.1.2. Objetivo

Após o término deste curso, os participantes poderão configurar um servidor Red Hat Enterprise Linux e configurar serviços comuns de rede de trabalho e segurança em nível básico.

57.1.3. Público

Os administradores de sistema UNIX ou Linux, que já possuem alguma experiência de trabalho com a administração de sistemas do Red Hat Enterprise Linux, querem um curso inicial em serviços de rede de trabalho e seguraça e querem adquirir habilidades de configuração de serviços comuns de rede de trabalho e administração de segurança usando a Red Hat Enterprise Linux.

57.1.4. Objetivo dos Cursos

  1. Os serviço de Rede de Trabalho na instalação, configuração e administração básica de serviços de rede de trabalho comuns do lado do servidor da Red Hat Linux: DNS, NIS, Apache, SMB, DHCP, Sendmail, FTP. Outros serviços comuns: tftp, pppd, proxy.
  2. Introdução à segurança
  3. Desenvolvendo uma política de segurança
  4. Segurança local
  5. Arquivos e segurança de sistema de arquivos
  6. Segurança de Senha
  7. Segurança do Kernel
  8. Elementos básicos de um firewall
  9. Ferramentas de segurança baseadas em Red Hat Linux
  10. Respondendo a uma tentativa de invasão
  11. Fontes e Métodos de Segurança
  12. Visão Geral de ferramentas de segurança OSS

57.1.5. Cursos de acompanhamento

Exame de Certificação RH302 RHCE
"Este curso foi excelente. O professor é fantástico— seu profundo conhecimento é impressionante!" ——Greg Peters, Future Networks USA

Capítulo 58. RH300: O curso de rastreamento rápido do RHCE ( e exames do RHCE)

O caminho mais rápido para a certificação RHCE para usuários UNIX/Linux

58.1. Descrição do Curso

Com cinco dias de duração, este curso oferece um treinamento intensivo e prático na Red Hat Linux e envolve o Exame de Certificação RHCE no último dia.

58.1.1. Pré-requisitos

O RH033, RH133, RH253 ou experiência equivalente ao UNIX. Por favor, não se matricule no RH300 de não tiver experiência com administração de sistemas ou é um usuário em potencial do UNIX ou ambientes de Linux.

58.1.2. Objetivo

Após o término do curso com sucesso, os participantes se tornarão administradores de sistema da Red Hat Linux, pois foram treinados e então testados através do Exame do RHCE.

58.1.3. Público

Os administradores de sistema UNIX ou Linux, que possuem experiência de trabalho e que queiram um curso de rápido controle para se prepararem para o Exame do RHCE.

58.1.4. Objetivo dos Cursos

  1. Hardware e Instalação (arquitetura x86 )
  2. Configuração e administração
  3. Alternar métodos de instalação
  4. Serviços de Kernel e configuração
  5. Serviços de rede de trabalho Padrão
  6. Sistema X Window
  7. Usuário e segurança da máquina
  8. Routers, Firewalls, Clusters e Solucionador de Problemas

58.1.5. Cursos de acompanhamento

Currículo de Arquiteo Empresarial e certificação RHCA

Capítulo 59. AVALIAÇÃO RH302 RHCE

  1. As avaliações RHCE estão inclusas no RH300 e também pode ser comprada em separado.
  2. As examinações RHCE acontecem todo quinto dia de aula do RH300

59.1. Descrição do Curso

O RHCE é ministrado em separado de muitos outros programas de certificação no setor de TI, por causa da sua ênfase na praticidade, teste baseado em desempenho das habilidades atuais na instalação Red Hat Linux, configuração, depuração e configuração dos serviços chave de rede de trabalho.

59.1.1. Pré-requisistos

Veja os pré-requisitos do curso RH300. Para maiores informações, consulte o RHCE Exam Prep Guide: www.redhat.com/training/rhce/examprep.html

59.1.2. Conteúdo

  1. Seção I: Solução de problemas e Manutenção de Sistema (2.5hrs)
  2. Seção II: Instalação e Configuração (3hrs)
"Sem dúvida esta aula superou as expectativas. Me sinto muito bem preparada para o exame amanhã"— Logan Ingalls, Desenvolvedor da Web, Texterity Inc., USA

Capítulo 60. RHSS333: Segurança empresarial da RED HAT: serviços de rede de trabalho

Segurança para a maioria dos serviços implementados.

60.1. Descrição do Curso

A Red Hat Enterprise Linux ganhou um impulso considerável, assim como o sistema operacional, na escolha por serviços de rede de trabalho de implementação, tais como web, ftp, email e compartilhamento de arquivo. O currículo do RHCE da Red Hat, oferece treinamento para implementar estes serviços e nos elementos essenciais para suas seguranças.

60.1.1. Pré-requisitos

Para este curso, requer-se uma Certificação RH253, RH300 ou RHCE, ou experiência de trabalho equivalente. Os participantes do curso devem ter noções básicas de como configurar os serviços cobertos, pois este curso focará em tópicos iniciais mais avançados.

60.1.2. Objetivo

Esta classe vai além da cobertura de segurança essencial, oferecida no currículo RHCE e se aprofunda nos recursos de segurança, capacidades e riscos associados com a maioria dos serviços geralmente implementados.

60.1.3. Público

O público deste curso envolve administradores de sistemas, consultores, e outros profissionais de TI responsáveis pelo planejamento, implementação e manutenção de servidores de rede de trabalho. Embora o curso seja focado na na execução destes serviços na Red Hat Enterprise Linux, assim como se uso pelo conteúdo e laboratórios, os administradores de sistema e outros que utilizam formas de UNIX podem também se beneficiar de muitos fatores deste curso.

60.1.4. Objetivo dos Cursos

  1. Domínio do serviço de segurança básica
  2. Entendendo sobre criptografia
  3. Efetuando o logging dos registros de sistema
  4. Assegurando BIND e DNS
  5. Segurança de autenticação do usuário de rede de trabalho.
  6. Melhorando a segurança NFS
  7. Shell segura: OpenSSH
  8. Assegurando email com Sendmail e Postfix
  9. Gerenciando o acesso FTP
  10. Segurança Apache
  11. Conhecimentos básicos de resposta de intrusão.

60.1.5. Cursos de acompanhamento

RH401: A implementação e Gerenciamento de Sistema da Red Hat Enterprise. Os Serviços e Autenticação de Diretório da RH423 Red Hat Enterprise e o Gerenciamento de Armazenamento da RH436 Red Hat Enterprise. Monitoramento de Sistema e Ajuste de Desempenho da Red Hat Enterprise RH442.

Capítulo 61. RH401: Gerenciamento de Implementação e sistemas da Red Hat Enterprise

Gerenciar Implemetações Linux da Red Hat Enterprise

61.1. Descrição do Curso

RH401 é um curso de laborátorio intensivo e prático com duração de quatro dias sobre habilidades e métodos críticos para implementações em grande escala e gerenciamento de sistemas de missão crítica da Red Hat Enterprise, incluindo falhas e balanceamento de carga, CVS para administradores de sistema, Reconstrução RPM e ajuste de desempenho para aplicativos específicos.

61.1.1. Pré-requisitos

Solicita-se no mínimo o RH253, porém prefere-se uma certificação RHCE ou habilidade e habilidade comparável a esta. Todos os possíveis participantes que não possuem a certificação RHCE estão encorajados a checar suas habilidades através das avaliações de pré-seleção— online grátis da Red Hat. Nota: Aqueles que não possuem os pré-requisitos acima não devem se matricular no RH401.
Recomenda-se à todos os possíveis participantes do curso que não possuam a certificação RHCE, que entrem em contato com o Serviços de Apredizagem Red Hat Global para avaliaçõe

61.1.2. Objetivo

O RH401 treina os administradores de sistema sêniores para gerenciar diversos servidores Enterprise Linux com diversos papéis, e/ou gerenciá-los para aplicativos de missão— crítica, que requeiram falha e balanceamento de carga. Além disso, o RH401 é avaliado por competências de nível de perítos para papéis empresariais— O curso ensina como implementar e gerenciar implementações empresariais do Red Hat Enterprise Linux, de forma eficiente e efetiva tornando toda a implementação empresarial gerenciada por um time.

61.1.3. Público

Os administradores sêniores de sistema Linux da Red Hat Enterprise e outros profissionais de IT que trabalhem em ambientes empresariais e sistemas de missão crítica.

61.1.4. Objetivo dos Cursos

  1. Gerenciamento de Configuração usando CVS
  2. Construção de pacotes padronizados RPM
  3. Gerenciamento de software com o Servidor Red Hat Network Proxy
  4. Montando uma disponibilização de máquina e sistema de gerenciamento
  5. Ajuste e Análise de Desempenho
  6. Clusters de balanceamento de carga de rede de trabalho de Alta disponibilidade.
  7. clusters de falha de aplicativo com alta disponibilidade

61.1.5. Cursos de acompanhamento

RHS333 Segurança Empresarial: Assegurando Serviços de Rede de Trabalho
RH423 Autenticação e Serviços de Diretório da Red Hat Enterprise
RH436 Gerenciamento de Armazenamento da Red Hat Enterprise
RH442 Monitoramento de Sistema e Ajuste de Desempenho da Red Hat Enterprise
"Depois de concluir o RH401, estou completamente seguro que posso implementar uma empresa— em alta escala—soluções de disponibilidade de ponta a ponta."——Barry Brimer, Bunge América do Norte

Capítulo 62. RH423 Autenticação e Serviços de Diretório da Red Hat Enterprise

Gerenciar e Implementar serviços de diretórios para sistemas Linux da Red Hat Enterprise

62.1. Descrição do Curso

O RH423 é um curso intensivo que oferece quatro dias de instruções e laboratórios em integração de cross-platform de serviços de diretórios para oferecer autenticação ou serviço de informações na empresa.

62.1.1. Pré-requisitos

O RH253 no mínimo, porém prefere-se uma certificação RHCE ou habilidades e conhecimento comparável. Todos os possíveis participantes sem a certificação RHCE são encourajados a checar suas habilidades com as avaliações de pré-seleção— online grátis da Red Hat. Nota: Aqueles que não tiverem os pré-requisitos acima, não devem efetuar a matrícula para o RH423. Recomenda-se que todos os possíveis participantes que não tenham o RHCE, entrem em contato com os Serviços de Aprendizado da Red Hat Global para uma avaliação prévia à inscrição.

62.1.2. Objetivo

O RH423 treina administradores de sistema sêniores para gerenciar e implementar serviços de diretório em e para sistemas Linux da Red Hat Enterprise. É primordial para este curso que o aluno adquira conhecimento de conceitos básicos, configuração e gerenciamento de serviços baseados em LDAP—. Os alunos irão integrar clientes e serviços e clientes de rede de trabalho padrão com serviços de diretórios para que possam tirar proveito de suas capacidades. Também veremos em PAM, o sistema de Módulos de Autenticação Plugável, e como ele é integrado com serviços que requeiram autenticação e autorização.

62.1.3. Público

Administradores Sêniores do sistema Linux da Red Hat Enterprise e outros profissionais que trabalhem com ambientes empresariais e sistema de missão crítica.

62.1.4. Objetivo dos Cursos

  1. Conceitos básicos de LDAP
  2. Como configurar e gerenciar um servidor OpenLDAP
  3. Utilizando LDAP como um serviço de diretório "white pages"
  4. Utilizando LDAP para autenticação e gerenciamento de usuário
  5. Integrando servidores LDAP múltiplos

62.1.5. Cursos de acompanhamento

RHS333 Segurança Empresarial: Assegurando Serviços de Rede de Trabalho
RH401 Gerenciamento de Sistemas e Implementação da Red Hat Enterprise
RH436 Gerenciamento de Armazenamento da Red Hat Enterprise (pág. 16)
RH442 Monitoramento de Sistema e Ajuste de Desempenho da Red Hat Enterprise

Capítulo 63. SELinux Courses

63.1. RHS427: Introdução ao SELinux e Política Alvo da Red Hat

Introdução rápida de um dia para o SELinux, como operá-lo dentro da política alvo da Red Hat, as ferramentas disponíveis para se trabalhar com esta potente capacidade. O RHS427 é o primeiro dia do RH429.

63.1.1. Público

Especialistas de segurança da computação e outros responsáveis por implementar políticas de segurança em um computador Linux. O RHS429, requer um RHCE ou conhecimento comparável.

63.1.2. Sumário do Curso

Entre os recursos mais importantes do Red Hat Enterprise Linux, se encontra o SELinux (Segurança Destacada da Linux), uma camada de segurança de nível kernel potente que oferece controle de granulado fino sob o que os usuários e processos podem acessar e fazer com o sistema. Por padrão o SELinux está habilitado nos sistemas Red Hat Enterprise Linux, impondo um conjunto de controles de acessos obrigatórios que a Red Hat chama de política alvo. Estes controles de acesso melhoram altamente a segurança dos serviços de rede de trabalho alvo, porém eles podem às vezes afetar o comportamento de aplicativos e scripts de terceiros que funcionavam em versões anteriores do Red Hat Enterprise Linux.

63.2. RHS429: Red Hat Enterprise SELinux Policy Administration

Entre os recursos mais importantes do Red Hat Enterprise Linux, se encontra o SELinux (Segurança Destacada da Linux), uma camada de segurança de nível kernel potente que oferece controle de granulado fino sob o que os usuários e processos podem acessar e executar em um sistema. O RHS429 apresenta administradores de sistemas avançados, administradores de segurança, e programadores de aplicativos escrever a política do SELinux. Os que participarem neste curso, irão aprender como o SELinux funciona, como gerenciar um SELinux, e como escrever uma política de SELinux.

Capítulo 64. RH436 Gerenciamento de armazenamento da Red Hat Enterprise

Implementar e gerenciar a tecnologia do sistema de arquivo cluster da Red Hat
Equipamento intensivo:
  1. cinco servidores
  2. matriz de armazenamento

64.1. Descrição do Curso

O RH436 oferece uma experiência intensa e prática com a tecnologia emergente Armazenamento Compartilhado, entregue pelo Sistema de Arquivo da Red HatGlobal ™ (GFS). Este curso com duração de quatro dias, foca na implementação de tecnologias nativas do Red Hat Enterprise Linux, incluído no Red Hat Cluster Suite e GFS.

64.1.1. Pré-requisitos

Solicita-se no mínimo um RH253, com preferência de uma certificação RHCE ou habilidades e conhecimento comparável. Todos os possíveis participantes que não possuirem a certificação RHCE são encorajados a checar suas habilidades com a avaliação de pré-seleção online da Red Hat, grátis.

64.1.2. Objetivo

Este curso foi criado para treinar pessoas com competência de nível RHCE nas habilidades solicitadas para implementar e gerenciar dados de armazenamento disponíveis para um ambiente de computação corporativa de missão crítica. Complementando habilidades adquiridas no RH401, este curso consiste em um treinamento prático com sistema de arquivo cluster, GFS.

64.1.3. Público

Administradores de sistema Sênior do Red Hat Enterprise Linux e outros profissionais de TI, trabalhando em ambientes corporativos e sistemas de missão crítico.

64.1.4. Objetivo dos Cursos

  1. Revisão das tecnologias de gerenciamento de armazenamento da Red Hat Enterprise Linux
  2. Design de Armazenamento de dados: Compartilhamento de Dados
  3. Visão geral do Cluster Suite
  4. Visão geral do Sistema de Arquivo Global (GFS)
  5. Gerenciamento GFS
  6. Modifique o ambiente GFS online: Gerenciando a capacidade de dados
  7. Monitor GFS
  8. Implementar modificações GFS
  9. Migrando Cluster Suite NFS de DAS para GFS
  10. Visite novamente o Cluster suite usando GFS

64.1.5. Cursos de acompanhamento

RHS333 Segurança Empresarial: Assegurando Serviços de Rede de Trabalho
RH401 Gerenciamento de Sistemas e Implementação da Red Hat Enterprise
RH423 Autenticação e Serviços de Diretório da Red Hat Enterprise
RH442 Monitoramento de Sistema e Ajuste de Desempenho da Red Hat Enterprise
" A aula me deu a chance de utilizar algumas das ferramentas mais recentes existentes, assim como rever os benefícios de se utilizar o Linux devido aos sistemas de alta disponibilidade.——" Paul W. Frields, FBI – Divisão de Tecnologia Operacional Quantico, VA, USA

Capítulo 65. RH442: sistema de monitoração e ajuste de desempenho da Red Hat Enterprise

Ajuste de desempenho e planejamento de capacidade para a Red Hat Enterprise Linux

65.1. Descrição de Curso

A RH442 é um curso de laboratório prático e avançado com duração de quatro dias, que cobre a arquitetura de sistemas, características de desempenho, monitoramente, avaliações de desempenho e ajuste de desempenho de rede de trabalho.

65.1.1. Pré-requisitos

O RHCT no mínimo, certificação RHCE recomendada, ou habilidades comparáveis e conhecimento. Todos os possíveis participantes do curso sem uma certificação RHCE são encorajados a checar suas habilidades com os testes de pré seleção— online grátis.

65.1.2. Objetivo

O RH442 foi criado para ensinar a metodologia de ajuste de desempenho e capacidade de planejamento para a Red Hat Enterprise Linux. Esta classe irá cobrir:
  1. Uma discussão da arquitetura do sistema com ênfase na aprendizagem das implicações da arquitetura do sistema no desempenho do sistema
  2. Métodos para avaliar os efeitos de ajuste de desempenho (benchmarking)
  3. Utilitários de avaliação de desempenho de código aberto
  4. Métodos para análise de desempenho do sistem e desempenho da rede de trabalho.
  5. Ajuste de configurações para cargas de aplicativos específicos

65.1.3. Público

RH442 é focado em administradores de sistema sênior da Red Hat Enterprise Linux e em outros profissionais de TI que trabalhem em ambientes corporativos e sistemas de missão crítica.

65.1.4. Objetivo dos Cursos

  1. Visão Geral dos componentes de sistema e arquitetura, uma vez que eles relatam ao desempenho de sistema
  2. Traduzindo especificações de hardwares de fabricantes em informações úteis
  3. Utilizando as ferramentas de monitoramento padrão para reunir e analisar informações de tendência
  4. Reunindo dados relacionados ao desempenho com SNMP
  5. Utilizando utilitários de avaliação de desempenho de código aberto
  6. Ajuste de desempenho de rede de trabalho
  7. Considerações de ajuste de desempenho de aplicativo
  8. Ajuste para configurações específicas

65.1.5. Cursos de acompanhamento

RHS333 Segurança Empresarial: Assegurando Serviços de Rede de Trabalho
RH401 Gerenciamento de Sistemas e Implementação da Red Hat Enterprise
RH423 Autenticação e Serviços de Diretório da Red Hat Enterprise
RH436 Gerenciamento de Armazenamento da Red Hat Enterprise

Capítulo 66. Red Hat Enterprise Linux Cursos de Desenvolvedores

66.1. RHD143: Origens de Programação da Red Hat Linux

Um curso intensivo e prático, criado para treinar de forma rápida, os funcionários com habilidades chave para aplicativos de desenvolvimento e programas com a Red Hat Enterprise Linux. Este curso de cinco dias, oferece um treinamento prático, conceitos, demonstrações, com ênfase em laboratórios realísticos e exercícios de programação. Após o término do curso, os alunos terão aprendido e praticado as habilidades essenciais que se requer em programas de desenvolvimento para sistemas Linux.

66.2. RHD221 Drivers de Dispositivo Red Hat Linux

Este curso foi criado para ensinar programadores experientes, como desenvolver Drivers de Dispositivos para os sistemas Linux. Ao final do curso, os alunos entenderão a arquitetura do Linux, gerenciamento de memória e harware, modularização, e o layout da fonte kernel, e praticarão conceitos chave e habilidades para desenvolvimento de caráter, bloco e drivers de rede de trabalho.

66.3. RHD236 Red Hat Linux Kernel Internals

Este curso foi criado para oferecer uma examinação detalhada da arquitetura kernel da Linux, incluindo agendamento de processo, gerenciamento de memória, sistemas de arquivo e dispositivos periféricos de drivers. Este curso de cinco dias, oferece um treinamento prático, conceitos e demonstrações, com ênfase em laboratórios realísticos e exercícios de programação.

66.4. RHD256 Portal e Desenvolvimento de Aplicativo Red Hat Linux

Um curso de desenvolvedor de quatro dias para programadores experientes que já conhecem o desenvolvimento em um sistema como UNIX e queiram desenvolver novos aplicativos, assim como aplicativos existentes de portas para Red Hat Enterprise Linux.

Capítulo 67. Cursos JBoss

67.1. RHD161 JBoss e EJB3 para Java

Desenvolvedores JBoss e EJB3 para Desenvolvedores Java é focado em desenvolvedores de Java profissionais que desejam extender seus conhecimentos em programação de middleware EJB3 e J2EE usando o Servidor de Aplicativo JBoss. Este curso é uma introdução ao EJB3 e J2EE usando o Servidor de Aplicativo JBoss. É um curso prático de desenvolvimento do aplicativo EJB3 e J2EE, implementação e ferramentas necessárias para facilitar todos os processos.

67.1.1. Pré-requisitos

É necessário possuir habilidades de programação de Java Básico e conhecimento de conceitos de OOAD. O aluno deve possuir experiência prática e/ou conhecimento em:
  1. Os conceitos de objeto orientado de herança, polimorfismo e encapsulação.
  2. Sintáxe de Java, especialmente para tipos de datas, variáveis, operadores, instruções e fluxo de controle
  3. Gravar cursos de Java, assim como usar interfaces e cursos abstratos

67.2. RHD163 JBoss para Desenvolvedores da Web

JBoss para Desenvolvedores da Web focam em tecnologias de camada da Web na pilha do produto JBoss Enterprise Middleware System (JEMS). Nós cobrimos detalhes sobre o Portal JBoss, como criar e implemetar portlets, integrando portlets com outras estruturas de camada da Web, tais como JavaServer Faces (JSF) e configuração e ajuste do container da Web Tomcat, embutido no Servidor de Aplicativo da JBoss. Recomenda-se familiaridade com JSP e desenvolvimento de Servlet e especificações relacionadas. Não é necessária experiência prévia com Portlets ou JSF.

67.2.1. Pré-requisitos

As habilidades pré-requisitadas para este curso são as habilidades de programação de Container da Web J2EE (Servlet/JSP) e alguma experiência com J2EE baseado na Web e implementações de aplicativo de camada múltipla no Servidor de Aplicativo JBoss, em conjunto com o container Tomcat (anexado com o Apache ou integrado com o servidor de Aplicativo do JBoss). O aluno deve possuir experiência de desenvolvimento com as seguintes tecnologias:
  1. JNDI
  2. The Servlet 2.3/2.4 API
  3. The JSP 2.0 API
  4. O desenvolvimento do aplicativo J2EE e desenvolvimento do Servidor de Aplicativo JBoss
  5. Implementação de um Aplicativo da Web no Tomcat embutido
  6. Uma experiência de trabalho do JDBC e EJB2.1 ou EJB3.0
é util, caso não seja um pré-requisito

67.3. RHD167: JBOSS - HIBERNATE ESSENTIALS

67.3.1. Pré-requisitos

  1. Conhecimento prévio do modelo de persistência relacional
  2. Competência com a linguagem Java
  3. Conhecimento dos conceitos OOAD
  4. Familiaridade com o UML
  5. Experiência com o dialeto do SQL
  6. Usando o JDK e criando o ambiente necessário para a compilação e execução de um Java executável de uma linha de comando.
  7. Um conhecimento do JDB
Não é necessário conhecimento prévio do J2EE ou Hibernate. Este treinamento é baseado na série 3.2 do Hibernate.

67.3.2. Sumário do Curso

O Hibernate Essentials é destinado aos desenvolvedores de Java que precisam da competência do Hibernate ou Java Persistence API da persistência do objeto/relacional e implementação de serviço de consulta. A audiência primária pretende se tornar desenvolvedora de Java que trabalha com sistemas de banco de dados baseado em SQL ou desenvolvedores de banco de dados que estejam procurando por uma apresentação ao desenvolvimento de software de objeto orientado. Os administradores de banco de dados que estiverem interessados em como o ORM pode afetar o desempenho e como ajustar o desempenho do sistema de gerenciamento de banco de dados SQL e camada de persistência, também se interessarão por este curso. Este curso trata sobre a implementação do JBoss, Inc da sub-especificação do JSR-220 para Persistência Java e trata sobre os fundamentos das APIs da versão 3.x do produto JBoss, Inc Hibernate, ou simplesmente, Hibernate 3.

67.4. RHD267: JBOSS - HIBERNATE AVANÇADO

O treinamento do Hibernate Avançado do JBoss é destinado aos desenvolvedores de Java que desejam extrair tudo que a estrutura de Mapeamento do Hibernate O/R pode oferecer. A audiência inicial alvo consiste em desenvolvedores de Java que trabalham com banco de dados baseado em SQL, desenvolvedores de banco de dados que estejam procurando por uma apresentação ao desenvolvimento de software de objeto orientado e administradores de banco de dados que sejam interessados em saber como o ORM afeta o desempenho e como ajustar o desempenho do sistema de gerenciamento do banco de dados do SQL e camada de persistência. O treinamento cobre os três recursos novos do Hibernate.

67.4.1. Pré-requisitos

As habilidades pré-requisitadas para este curso são as seguintes:
  1. Conhecimento básico do Hibernate
  2. Competência com a linguagem Java
  3. Conhecimento dos conceitos OOAD
  4. Familiaridade com o UML
  5. Experiência com o dialeto do SQL
  6. Usando o JDK e criando o ambiente necessário para a compilação e execuação de um Java executável a partir do comando de linha.
  7. Experiência com, ou conhecimento considerável do JNDI e JDBC
  8. Entidade de conhecimento do EJB2.1 ou EJB3.0, desde que não seja um pré-requisito, é bastante útil.
  9. Recomenda-se uma leitura prévia do livro Hibernate in Action, escrito por Christian Bauer e Gavin King (publicado por Manning).
"A melhor parte do curso avançado do Hibernate Avançado foi a interação com engenheiros alunos que tinham problemas semelhantes aos meus, e trabalhar com um instrutor altamente capacitado para solucionar estes problemas"--Mike Pasternak, Engenheiro Consultor, United Switch & Signal

67.5. RHD261:JBOSS para desenvolvedores de J2EE avançados

O JBoss para Desenvolvedores de J2EE Avançado é destinado a profissionais de J2EE que desejam usufruir da arquitetura interna do Servidor de Aplicativo JBoss para aprimorar a funcionalidade e desempenho dos aplicativos J2EE no Servidor de Aplicativo JBoss. Este curso trata de tópicos como JMX e outros além da especificação do J2EE como a arquitetura Microkernel, Segurança, Clustering e Ajuste Fino.

67.5.1. Pré-requisitos

É altamente recomendável que os alunos completem o curso para Desenvolvedores de JBoss para Java OU façam a avaliação de Posicionamento de Middleware antes de se registrarem no curso do JBoss para Desenvolvedores de J2EE Avançado. É necessário que o desenvolvedor possua experiência prática em cada um dos seguintes tópicos:
  1. JNDI
  2. JDBC
  3. Servlets and JSPs
  4. Enterprise Java Beans
  5. JMS
  6. Modelo de Segurança J2EE
  7. O desenvolvimento e implementação do aplicativo J2EE no Aplicativo JBoss
  8. Experiência com o ANT e XDoclet ou tecnologias semilares.
Apesar do conhecimento prévio do JMX ser útil, ele não é necessário. Este treinamento é baseado nas séries 4.x do Servidor do Aplicativo do JBoss.
"Em minha opinião, os materiais de treinamento são bem organizados, incluindo as apostilas e sessões de laboratório. O instrutor pedia constantemente pelo feedback dos alunos quanto aos materiais e velocidade do curso e era clara sua preocupação quanto ao nosso entendimento do material." --Jeremy Prellwitz, SiRAS.com, EUA.

67.6. RH336: JBOSS para Administradores

67.6.1. Pré-requisitos

Experiência de trabalho básica do sistema operacional do Linux (baseado em Unix) e Windows. O aluno deve ter experiência nos seguintes tópicos:
  1. Criar diretórios, arquivos e modificar direitos à acesso ao armazenamento de arquivo
  2. Instalando o JDK
  3. Configurar variáveis de ambiente, tais como JAVA_HOME, para um sistema Operacional
  4. Lançando os aplicativos de Java e executando um script de OS-dependente que lança um aplicativo Java
  5. Criando e expandindo um arquivo Java (o utilitário jar)
Não é necessário conhecimento prévio do J2EE ou do Servidor de Aplicativo JBoss. Algumas familiaridades com aplicativos Java de suporte com configurações XML, no entanto, são altamente recomendáveis.

67.6.2. Sumário do Curso

O JBoss para Administradores é direcionado às pessoas de suporte de aplicativo, tais como administradores de sistema, gerenciamento de configuração e funcionários de controle de qualidade que desejam se tornar peritos em configuração e administração do servidor de aplicativo JBoss (séries 3.2.x e 4.x) e os aplicativos implementados no servidor de aplicativos.
"O curso JBoss para Administradores foi muito bem dividido entre aulas teóricas e práticas. É sempre muito bom obter aulas práticas dos tópicos para que se pareçam mais reais e aplicáveis" ——Thomas Skowronek, Palm Harbor Homes, EUA.

67.7. RHD439: JBoss Clustering

O Clustering é um treinamento de 4 dias, focado em serviços de alta disponibilidade do JBoss Enterprise Middleware System (JEMS). Você aprenderá como o Servidor de Aplicativo JBoss usufrui do JGroups e JBoss Cache para replicação e falhas, como configurar, ajustar e implementar a pilha de protocolo do JGroups, como usufruir do JBoss Cache em sua própria implementação de aplicativo middleware e como usar e configurar o mod_jk para balanceamento de carga HTTP. Também cobriremos alguns detalhes dos serviços de alta disponibilidade do Servidor de Aplicativo JBoss, tais como HA-JNDI, HA-JMS e HA-singleton.

67.7.1. Pré-requisitos

Antes de iniciar este curso, é altamente recomendada a conclusão do curso do JBoss para Desenvolvedores J2EE Avançado. Recomenda-se também que os alunos tenham um mínimo de 18 meses de experiência de desenvolvimento prático usando J2EE e outras tecnologias de middleware Java, e sugere-se que o aluno tenha alguma experiência prática com o Servidor de Aplicativo JBoss. É necessária uma sólida experiência em programação Java (mínimo de 3 anos) e um entendimento do tópico TCP/IP básico.
O aluno deve ter as seguintes habilidades:
  1. JTA, Transações, concorrencia Java
  2. EJB 2.1,JMS, tecnologias de mensagens confiáveis.
  3. Experiência prévia com o Apache httpd e alguma exposição ao mod_jk and/ou mod_proxy
  4. Familiar com o JBoss AS microkernel e JMX
  5. Familiaridade com o TCP/IP, UDP, Multicasting
"O curso JBoss para Administradores foi bastante informativo. Nosso instrutor fez um ótimo trabalho, respondendo nossas questões (algumas bastante específicas para o aluno) e ao mesmo tempo mantendo o foco do curso. Estou bastante ansioso para aplicar o que aprendi no curso." ——Andy Beier, Arizona Statue University, EUA

67.8. RHD449: JBoss jBPM

67.8.1. Descrição

O treinamento JBoss jBPM é direcionado aos arquitetos de sistema e desenvolvedores que trabalham com analistas de empresa e que sejam responsáveis por migrar processos de negócios para ambiente J2EE, usando jBPM como um motor BPM. Além disso, o treinamento JBoss jBPM irá oferecer aos alunos, uma visão geral do BPM, tipos de motores e posicionamento das palavras chave.
Os alunos irão adquirir prática em especialização e estarão prontos para iniciar processos de negócios em desenvolvimento com o JBoss jBPM após o curso. Outro objetivo do treinamento é oferecer uma preparação plena para motores de fluxo de trabalho comparativos.

67.8.2. Pré-requisitos

  1. O aluno deve possuir experiência prévia no desenvolvimento do aplicativo Hibernate. O aluno deve saber como configurar uma Session Factory simples para Hibernate, usar uma Sessão Hibernate e demarcação transacional e como realizar consultas básicas em assuntos do Hibernate.
  2. Competência de desenvolvimento do aplicativo Java
  3. Exposição prévia aos conceitos de fluxo de trabalho e modelagem de processos de empresas (BPM) não são necessários.
  4. Recomenda-se que tenha experiência com o JBoss Eclipse ou o Eclipse IDE com o plugin JBoss, porém não é obrigatório.
  5. Recomenda-se que tenha noções básicas de estrutura de teste JUnit.

67.9. Regras RHD451 JBoss

O curso trata sobre o motor central para Drools 3 (Regras JBoss 3.0), assim como diversas técnicas e linguagens que podem ser usadas para gerenciar regras de negócios, e como o motor de regra pode ser encapsulado nos aplicativos J2SE e J2EE. Este curso será um curso complementário para qualquer curso futuro em gerenciamento de regras, usando lançamentos futuros das Regras JBoss.

67.9.1. Pré-requisitos

  1. Competência de Java Básica
  2. Algum conhecimento sobre o que constitui um motor de regra inferenciada versus um motor de script
  3. Visualizando os webinars de Regras Jboss e demos é recomendado mas não obrigatório.
  4. Não é necessária experiência prévia específica em Java EE para iniciar o curso, mas os alunos precisam saber como integrar com Java EE.

Revision History

Histórico de Revisões
Revisão 10-0Thu Jul 21 2011Jaromír Hradílek
Resolve BZ#720382: MinorMod: Network Interfaces: LINKDELAY parameter needs to be added to "Interface Configuration Files".
Resolve BZ#632028: MajorMod: Redundant Array of Independent Disks (RAID): Document mdadm Usage.
Resolve BZ#720009: MinorMod: LVM: Update screenshots in the "Manual LVM Partitioning" section.
Resolve BZ#711162: MinorMod: Network Interfaces: Incorrect static routes configuration.
Resolve BZ#707238: broadcast is calculated with ipcalc, not ifcalc.
Resolve BZ#678316: HOTPLUG network config file option is not documented.
Resolve BZ#562018: Ch.4 Redundant Array of Independent Disks (RAID) - screenshots need updating.
Resolve BZ#485033: iptables -p ALL --dport not allowed according to man 8 iptables.
Revisão 9-0Thu Jan 13 2011Jaromír Hradílek
Resolve BZ#249485: 'fsid=num' is listed under NFS client options, but it is a server-only option.
Resolve BZ#253659: additional commands required when adding machines to domain.
Resolve BZ#453242: guide does not tell you which packages you need to run an NFS server.
Resolve BZ#504250: cell should have newline characters, it shouldn't be all on one line.
Resolve BZ#520650: /proc/loadavg documentation error.
Resolve BZ#584075: vsftp typo for text_userdb_names.
Resolve BZ#625384: bonding configuration SLAVE=bond0 is invalid.
Resolve BZ#644617: misspelled word.
Resolve BZ#645123: spelling Errors in Deployment Guide II.
Resolve BZ#595366: RFE: document Shared Subtrees.
Revisão 8-0Thu July 30 2010Douglas Silas
Resolve BZ#239313: document oom_adj and oom_score.
Resolve BZ#526502: correct quotaon instructions with proper, safe operating procedures.
Resolve BZ#551367: correct SELinux dhcpd_disable_trans description.
Resolve BZ#521215: clarify NFS interaction with portmapper, rpc.mountd, rpc.lockd and rpc.statd.
Resolve BZ#453875: various OpenSSH chapter corrections.
Resolve BZ#455162: correct zone example configuration file, description.
Resolve BZ#460767: make it a proper daemon.
Resolve BZ#600702: correct directories used for SSL key generation.
Revisão 7-0Wed Sep 30 2009Douglas Silas, Jarek Hradilek, Martin Prpic
Change heading titles to correspond with actual headings used in 'man rpm'.
Resolve BZ#499053: /usr/sbin/racoon is correct install path.
Remove any mention of 'pkgpolicy' in /etc/yum.conf as per BZ#237773.
Resolve BZ#455162: correct example zone file with regard to records, description.
Resolve BZ#510851: /proc/cmdline has confusing descriptions of sample output.
Resolve BZ#510847: page with multiple footnotes formatted incorrectly in online PDF.
Resolve BZ#214326: more detailed usage info concerning vsftpd banners and secueerity.
Resolve BZ#241314: formatting problems in screen elements.
Resolve BZ#466239: postfix connect-from-remote-host configuration fix.
Revisão 7-0Mon Sep 14 2009Douglas Silas
Resolve BZ#214326: Server Security FTP Banner instructions: questions re: vsftpd.conf.
Resolve BZ#466239: insert line into Postfix config file to allow connecting remotely.
Resolve BZ#499053: path for racoon daemon is /usr/sbin/racoon, not /sbin/racoon.
Resolve BZ#510847: missing footnotes in PDF output.
Resolve BZ#510851: rewrite /proc/cmdline minor section to make more sense.
Resolve BZ#515613: correct location of RHEL5 GPG keys and key details.
Resolve BZ#523070: various minor fixes; --redhatprovides to rpm -q --whatprovides.
Revisão 6-0Wed Sep 02 2009Douglas Silas
Resolve BZ#492539: "This directive is useful..." to "This directive must be used in machines containing more than one NIC to ensure...".
Resolve BZ#241314: re: kernel-pae and hugemem support on RHEL 4 and 5.
Resolve BZ#453071: incorrect tag use led to config files and other screen elements being displayed on single lines.
Resolve BZ#507987: clarify and correct statements about partitions being in use while resizing or removing.
Resolve BZ#462550: recommended amount of swap space, according to http://kbase.redhat.com/faq/docs/DOC-15252.
Resolve BZ#466239: line omitted from Postfix configuration meant connecting remotely failed
Resolving other MODIFIED BZs (fixed previously): 468483, 480324, 481246, 481247, 438823, 454841, 485187, 429989, 452065, 453466.
Revisão 5-0Wed Jan 28 2009Michael Hideo Smith
Resolves: #460981
Changing 64GB *tested* support to support for 16GB.

Colophon

Os manuais são escritos em formato DocBook XML v4.3.
Garrett LeSage criou os gráficos de aviso (nota, dica, importante, cuidado e aviso). Eles podem ser redistribuídos gratuitamente com a documentação Red Hat.
Contributing Writers: John Ha (System Administration, Filesystems, Kernel), Joshua Wulf (Installation and Booting), Brian Cleary (Virtualization), David O'Brien (Security and SELinux), Michael Hideo (System Administration), Don Domingo (System Administration), Michael Behm (System Administration), Paul Kennedy (Storage), Melissa Goldin (Red Hat Network)
Homenageando aqueles que já fizeram parte da equipe: Sandra Moore, Edward C. Bailey, Karsten Wade, Mark Johnson, Andrius Benokraitis, Lucy Ringland
Homenageando os esforços de engenharia: Jeffrey Fearn
Editoria técnica: Michael Behm
Artista gráfico: Andrew Fitzsimon
A equipe de Localização da Red Hat envolve as pessoas a seguir:
  • East Asian Languages
    • Simplified Chinese
      • Tony Tongjie Fu
      • Simon Xi Huang
      • Leah Wei Liu
      • Sarah Saiying Wang
    • Traditional Chinese
      • Chester Cheng
      • Terry Chuang
      • Ben Hung-Pin Wu
    • Japanese
      • Kiyoto Hashida
      • Junko Ito
      • Noriko Mizumoto
      • Takuro Nagamoto
    • Korean
      • Eun-ju Kim
      • Michelle Kim
  • Latin Languages
    • French
      • Jean-Paul Aubry
      • Fabien Decroux
      • Myriam Malga
      • Audrey Simons
      • Corina Roe
    • German
      • Jasna Dimanoski
      • Verena Furhuer
      • Bernd Groh
      • Daniela Kugelmann
      • Timo Trinks
    • Italian
      • Francesco Valente
    • Brazilian Portuguese
      • Glaucia de Freitas
      • Leticia de Lima
      • David Barzilay
    • Spanish
      • Angela Garcia
      • Gladys Guerrero
      • Yelitza Louze
      • Manuel Ospina
    • Russian
      • Yuliya Poyarkova
  • Indic Languages
    • Bengali
      • Runa Bhattacharjee
    • Gujarati
      • Ankitkumar Rameshchandra Patel
      • Sweta Kothari
    • Hindi
      • Rajesh Ranjan
    • Malayalam
      • Ani Peter
    • Marathi
      • Sandeep Shedmake
    • Punjabi
      • Amanpreet Singh Alam
      • Jaswinder Singh
    • Tamil
      • I Felix
      • N Jayaradha