SECMEC: Assistente para Instalação de Mecanismos de Segurança …cristina/SECMEC.pdf · 2007. 3....
Transcript of SECMEC: Assistente para Instalação de Mecanismos de Segurança …cristina/SECMEC.pdf · 2007. 3....
SECMEC:Assistente para Instalação de Mecanismos de Segurança voltado para
Administradores de Sistema
Trabalho de Conclusão de Curso apresentado à UTFPR como requisito parcial para obtenção do título de Tecnólogo em Informática.
Curitiba2007
Tiago Almeida Barboza de Souza
SECMEC:Assistente para Instalação de Mecanismos de Segurança voltado para
Administradores de Sistema
Trabalho de Conclusão de Curso apresentado à UTFPR como requisito parcial para obtenção do título de Tecnólogo em Informática.
Orientadora:Professora MSc. Ana Cristina Barreiras Kochem Vendramin
Co-Orientador:Professor Doutor Gustavo Alberto Gimenez Lugo
Curitiba2007
SECMEC:Assistente para Instalação de Mecanismos de Segurança voltado para
Administradores de Sistema
Trabalho de Conclusão de Curso apresentado à UTFPR como requisito parcial para obtenção do título de Tecnólogo em Informática.
Data de Aprovação:____/____/______
Banca Examinadora:
___________________Profª MSc. Ana Cristina Barreiras Kochem Vendramin (Orientadora) UTFPR-DAINF
___________________Prof. Dr. Gustavo Alberto Gimenez Lugo (Co-Orientador) UTFPR-DAINF
___________________Prof. Christian Carlos Souza Mendes UTFPR-DAINF___________________Profª Drª Gilda Maria Souza Friedlaender(Coordenadora de Trabalho de Conclusão de Curso)UTFPR-DAINF
Curitiba2007
“Não existe morte que possa permanecer eterna,
E com estranhos aeons, até a morte pode morrer”
H.P. Lovecraft
DEDICATÓRIA
A todos aqueles que importam
AGRADECIMENTOS
Meus agradecimentos vão para todas aquelas pessoas que me ajudaram no período de
desenvolvimento do projeto. Em particular, gostaria de agradecer a Louise Provin, por todo apoio
e por ter acreditado em mim, aos meus pais Humberto Cesar Costa de Souza e Maria José
Almeida Barboza de Souza por estarem sempre próximos, a Tiago Salem Herrmann e Paulo
Roberto Oliveira Junior pela ajuda no desenvolvimento e na preparação do projeto e a minha
orientadora Ana Cristina Barreiras Kochem Vendramin, por sempre ter arranjado tempo para
ajudar-me na preparação deste documento.
SUMÁRIO
1 INTRODUÇÃO............................................................................................................14
1.1 Objetivos................................................................................................................15
1.2 Trabalhos relacionados..........................................................................................15
1.2.1 Módulo de segurança do Mandriva Control Center.......................................15
1.2.2 Módulos de segurança do Yast......................................................................15
1.3 Organização do Documento..................................................................................16
2 SE-LINUX....................................................................................................................17
2.1 DAC (Discretionary Access Control)....................................................................17
2.2 MAC (Mandatory Access Control).......................................................................20
2.3 SE-Linux vs AppArmour......................................................................................20
2.4 Considerações Finais sobre o SE-Linux...............................................................21
3 ROOT-PLUG................................................................................................................22
3.1 Funcionamento e Utilização..................................................................................22
3.2 Segurança..............................................................................................................23
4 ROOTKITS...................................................................................................................24
4.1 Funcionamento......................................................................................................24
4.2 Rootkit Hunter.......................................................................................................25
5 SECMEC......................................................................................................................27
5.1 Análise do Sistema................................................................................................27
5.1.1 Diagrama de Contexto...................................................................................27
5.1.2 Diagrama de Fluxo de Dados Nível 1............................................................28
5.1.3 Diagrama de Fluxo de Dados Nível 2............................................................29
5.2 Requisitos para Funcionamento............................................................................29
5.3 Desenvolvimento...................................................................................................31
5.4 Telas do SecMec...................................................................................................33
6 CONCLUSÃO E TRABALHOS FUTUROS...............................................................52
6.1 Trabalhos Futuros..................................................................................................52
REFERÊNCIAS..............................................................................................................53
APÊNDICE A: CÓDIGO FONTE ./ETC/SECMEC/FUNCTIONS...............................55
APÊNDICE B: CÓDIGO FONTE ./ETC/SECMEC/ROOTKITHUNTER.MEC..........78
APÊNDICE C: CÓDIGO FONTE ./ETC/SECMEC/ROOTPLUG.MEC.......................81
APÊNDICE D: CÓDIGO FONTE ./ETC/SECMEC/SELINUX.MEC..........................88
APÊNDICE E: CÓDIGO FONTE ./USR/SBIN/SECMEC............................................95
LISTA DE FIGURAS
Figura 1. Permissões de um arquivo................................................................................18
Figura 2. Diagrama de Contexto......................................................................................28
Figura 3. Diagrama de Fluxo de Dados Nível 1..............................................................28
Figura 4. Diagrama de Fluxo de Dados Nível 2..............................................................29
Figura 5. Tela Principal....................................................................................................34
Figura 6. Tela Sobre.........................................................................................................34
Figura 7. Tela de Mecanismos Disponíveis.....................................................................35
Figura 8. Tela Instalação do Mecanismo Rootkit Hunter – Parte 1.................................36
Figura 9. Tela Instalação do Mecanismo Rootkit Hunter – Parte 2.................................36
Figura 10. Tela Instalação do Mecanismo Rootkit Hunter – Parte 3...............................37
Figura 11. Tela Instalação do Mecanismo Rootkit Hunter – Parte 4................................37
Figura 12. Tela Instalação do Mecanismo Rootplug – Parte 1........................................38
Figura 13. Tela Instalação do Mecanismo Rootplug – Parte 2........................................39
Figura 14. Tela Instalação do Mecanismo Rootplug – Parte 3........................................39
Figura 15. Tela Instalação do Mecanismo Rootplug – Parte 4........................................40
Figura 16. Tela Instalação do Mecanismo Rootplug – Parte 5.........................................41
Figura 17. Tela Instalação do Mecanismo Rootplug – Parte 6.........................................41
Figura 18. Tela Instalação do Mecanismo Rootplug – Parte 7........................................42
Figura 19. Tela Instalação do Mecanismo Rootplug – Parte 8........................................43
Figura 20. Tela Instalação do Mecanismo Rootplug – Parte 9........................................43
Figura 21. Tela Instalação do Mecanismo Rootplug – Parte 10.......................................44
Figura 22. Tela Instalação do Mecanismo Rootplug – Parte 11.......................................45
Figura 23. Tela Instalação do Mecanismo Rootplug – Parte 12......................................45
Figura 24. Tela Instalação do Mecanismo Rootplug – Parte 13......................................46
Figura 25. Tela Instalação do Mecanismo Rootplug – Parte 14......................................46
Figura 26. Tela Instalação do Mecanismo SE-Linux – Parte 1........................................47
Figura 27. Tela Instalação do Mecanismo SE-Linux – Parte 2........................................48
Figura 28. Tela Instalação do Mecanismo SE-Linux – Parte 3.......................................48
Figura 29. Tela Instalação do Mecanismo SE-Linux – Parte 4.......................................49
Figura 30. Tela Instalação do Mecanismo SE-Linux – Parte 5.......................................49
Figura 31. Tela Instalação do Mecanismo SE-Linux – Parte 6........................................50
Figura 32. Tela Instalação do Mecanismo SE-Linux – Parte 7.......................................50
LISTA DE SIGLAS
BASH Bourne Again Shell
DAC Discretionary Access Control
GID Group ID
LSM Linux Security Modules
MAC Mandatory Access Control
MD5 Message-Digest Algorithm 5
NSA National Security Agency
SE-LINUX Security Enhanced Linux
SSH Secure Shell
USB Universal Serial Bus
YAST Yet Another Setup Tool
RESUMO
Segurança de sistemas é um assunto complexo e essencial para qualquer máquina que
não esteja completamente isolada. Um sistema comprometido pode ser extremamente danoso
para uma empresa, podendo causar não apenas interrupção de serviços, mas também danos
financeiros e vazamento de dados críticos. Devido a essa complexidade, é necessário muito
tempo para se configurar mecanismos de segurança no sistema adequadamente, e, em boa
parte dos casos, muito tempo acaba sendo gasto também com a instalação dos mesmos, tempo
que poderia ser melhor aproveitado em outras tarefas. O objetivo desse trabalho é apresentar
um assistente para a instalação de mecanismos de segurança no sistema operacional Linux,
agilizando o processo de instalação e liberando o administrador para outras tarefas.
Palavras-chave: Segurança, SE-Linux, RootPlug, Rootkit, Kernel, Linux
ABSTRACT
System security is a complex and essential subject to any machine that's not completely
isolated. A compromised system can be extremely harmful to a company, possibly causing not
only service interruption, but also financial damage and leak of critical data. Due to that
complexity, a lot of time is necessary to properly configure security mechanisms on the system,
and, in most cases, a lot of that time is also used on the installation of those mechanisms, time
that would be better used in other tasks. The objective of this project is to present an assistant to
install security mechanisms on the Linux operational system, hastening the installation process
and freeing the administrator for more useful tasks.
Keywords: Security, SE-Linux, RootPlug, Rootkit, Linux
Capítulo 1 Introdução 14
1 INTRODUÇÃO
Segurança de sistemas é um assunto complexo e de extrema importância para qualquer
dispositivo que esteja conectado em uma rede, seja essa rede a Internet ou uma intranet
empresarial. Envolvendo não só políticas de controle de acesso mas também a instalação e
configuração de mecanismos de segurança no próprio sistema operacional, entre outros fatores.
Embora muitos administradores de redes acreditem que apenas um firewall bem
configurado seja mais do que suficiente para acabar com os riscos de invasão à uma rede,
existem diversos outros mecanismos de segurança que podem aumentar drasticamente a
segurança geral de um sistema, assim como minimizar o comprometimento do mesmo no caso
de uma invasão bem sucedida.
Programas possuem falhas, isso é um fato consumado. É impossível para um
programador prever todas as possíveis condições e usos de um programa ou uma determinada
função, isso sem contar com falhas do próprio programador. Nesse cenário que mecanismos
como o SE-Linux (Security Enhanced Linux) entram em ação.
O SE-Linux é uma implementação de MAC (Mandatory Access Control) que se utiliza
dos Módulos de Segurança do Linux (LSM - Linux Security Modules) para garantir o mínimo
possível de permissões de acesso aos processos do sistema. Os seus mecanismos forçam a
separação de informações com base em requerimentos de confidencialidade e integridade, o
que permite o confinamento de dados causados por aplicações com falhas ou maliciosas,
minimizando o seu efeito e diminuindo as chances de comprometimento do sistema como um
todo [SECURITY, 2007].
Outro mecanismo de segurança interessante é o Root Plug do kernel do Linux,
responsável por impedir que operações que necessitem de privilégios de superusuário (root)
funcionem a não ser que um determinado dispositivo USB (Universal Serial Bus) esteja
fisicamente conectado ao sistema [KROAH-HARTMAN, 2002]. Um exemplo de operação que
não funciona sem o dispositivo USB conectado é o login de usuários, barrando o acesso físico à
máquina.
Apesar de extremamente interessantes, muitos desses mecanismos demandam uma
grande quantidade de tempo do administrador de redes, seja configurando-os e/ou
Capítulo 1 Introdução 15
implementando-os , o que acaba por dificultar a adoção dos mesmos.
1.1 Objetivos
O objetivo desse trabalho é facilitar a instalação de mecanismos de segurança
diferenciados no sistema operacional Linux. Para isso um assistente de instalação, denominado
SecMec, foi desenvolvido. O SecMec tem por objetivo ser simples, leve e extensível, de modo
que novos módulos podem ser acrescentados para aumentar o número de mecanismos de
segurança que o assistente suporta instalar.
1.2 Trabalhos relacionados
1.2.1 Módulo de segurança do Mandriva Control Center
O Mandriva Control Center apresenta alguns assistentes para configuração de
parâmetros de segurança do Mandriva Linux, como serviços liberados pelo firewall e
configuração de firewall redundante. Como o nome indica, é o centro de controle do sistema
operacional Mandriva Linux, sendo bastante genérico. Nele são encontrados assistentes para
configurar diversas características do sistema, não sendo específico para parâmetros de
segurança. Ele pode ser encontrado no sistema operacional Mandriva Linux no pacote drakxtools
[DRAKXTOOLS, 2007].
1.2.2 Módulos de segurança do Yast
O Yast (Yet another setup tool) do SUSE Linux, assim como o Mandriva Control Center,
possui algumas funções para ajuste de certos parâmetros de segurança, como ajuste do nível do
firewall, etc. sendo também o centro de controle do sistema operacional. Um grande diferencial
do Yast em relação ao Mandriva Control Center é o módulo de configuração do AppArmour
[APPARMOUR, 2007]. O AppArmour é um mecanismo de segurança para o sistema Linux muito
semelhante ao SE-Linux, diferindo no foco. Enquanto o SE-Linux apresenta controles de
Capítulo 1 Introdução 16
segurança mais complexos e abrangentes no sistema como um todo, o AppArmour busca ser
mais simples de configurar, abrangendo apenas determinadas aplicações [SPENNEBERG,
2005]. O AppArmour pode ser encontrado no sistema operacional SUSE Linux (e derivados
como o OpenSUSE) nos pacotes do yast2.
1.3 Organização do Documento
O documento está organizando da seguinte forma: os capítulos 2, 3 e 4 explicam com
mais detalhes os mecanismos de segurança suportados pelo SecMec. O capítulo 2 descreve o
sistema de controle de permissões de acesso SE-Linux, o capítulo 3 o mecanismo para bloqueio
de atividades administrativas Root-Plug e o capítulo 4 o sistema para detecção de Rootkits
Rootkit-Hunter. O capítulo 5 é dedicado a mostrar o SecMec, suas funcionalidades, como foi o
seu desenvolvimento e demais informações pertinentes. E, finalmente, no capítulo 6 são
apresentadas as conclusões sobre o desenvolvimento do projeto e idéias para trabalhos futuros.
Nos apêndices são encontrados os códigos fonte do SecMec.
Capítulo 2 SE-Linux 17
2 SE-LINUX
O SE-Linux (Security Enhanced Linux) é um projeto desenvolvido pela NSA (National
Security Agency) dos Estados Unidos que implementa características de segurança no kernel do
Linux. Segundo a NSA, o SE-Linux força políticas de controle de acesso que confinam
programas do usuário e servidores à quantidade mínima de privilégios necessários para que
cumpram suas tarefas [NSA, 2007], isso acaba por diminuir bastante o dano que pode ser
causado por uma aplicação comprometida.
Nas seções a seguir estão descritos o funcionamento dos esquemas de controle de
acesso DAC (Discretionary Access Control), MAC e conclusões sobre o uso dos mesmos.
2.1 DAC (Discretionary Access Control)
O sistema Linux utiliza um conceito de segurança chamado de Discretionary Access
Control, ou DAC para garantir acesso aos recursos do sistema [SPENNEBERG, 2005]. No Linux
todos os tipos de recursos são representados por arquivos, sejam eles arquivos de texto ou
dispositivos de disco. Esse conceito de segurança é popularmente conhecido como “read (r),
write (w), execute (x)” (leitura, escrita, execução). Cada recurso, que a partir de agora será
chamado de arquivo, possui um conjunto de nove bits de permissões que são divididos em três
partes: permissões de acesso para o dono do recurso; para membros do grupo do qual o recurso
faz parte; e para os demais usuários. A representação dessas permissões está ilustrada na
Figura 1.
Capítulo 2 SE-Linux 18
Figura 1. Permissões de um arquivo
Cada um desses bits, quando ativado, garante uma permissão diferente, por exemplo,
um arquivo com o primeiro bit ativado irá dar permissão de leitura para o dono do arquivo.
Quando um usuário qualquer tenta acessar um arquivo, várias verificações são feitas, se o
usuário é o dono do arquivo, ele recebe as permissões de acordo com os primeiros três bits, se
ele é um membro do mesmo grupo do qual o arquivo faz parte, ele recebe as permissões de
acordo com os três bits subseqüentes e, finalmente, se o usuário não é o dono e não faz parte
do grupo do arquivo, ele recebe as permissões de acordo com os três últimos bits. A seguir um
pequeno exemplo desse funcionamento:
Imagine um arquivo com as seguintes características:
• Nome: notas.txt
• Dono: salvador
• Grupo: cefet
• Permissões (o símbolo “-” indica permissão desativada): rw-r-----
Digamos que o usuário salvador, membro do grupo cefet tente acessar o arquivo, os
seguintes passos irão acontecer:
1. O sistema recebe a requisição de acesso e os dados do usuário salvador;
2. O sistema confere se o usuário dono do arquivo é o mesmo que o usuário salvador;
3. Como o usuário que está acessando é o mesmo que o dono do arquivo, o sistema
Capítulo 2 SE-Linux 19
retorna para o usuário as permissões r e w, permitindo portanto os acessos de leitura e
escrita para o usuário salvador;
Agora, se a usuária cristina, membro do grupo cefet tentar acessar arquivo, os seguintes
passos irão acontecer:
1. O sistema recebe a requisição de acesso e os dados da usuária cristina;
2. O sistema confere se o usuário dono do arquivo é o mesmo que a usuária cristina;
3. Como a usuária cristina não é a mesma que o usuário dono do arquivo, o sistema
confere se a usuária cristina faz parte do grupo do arquivo (cefet no caso);
4. Como a usuária cristina faz parte do grupo cefet, o sistema retorna para a usuária a
permissão read (leitura), o que significa que cristina só pode acessar o conteúdo do
arquivo mas não alterá-lo.
Por último, se o usuário junior, que não é membro do grupo cefet tentar acessar o
arquivo, os seguintes passos irão acontecer:
1. O sistema recebe a requisição de acesso e os dados do usuário junior;
2. O sistema confere se o usuário dono do arquivo é o mesmo que o usuário junior;
3. Como o usuário junior não é o mesmo que o usuário dono do arquivo, o sistema confere
se o usuário junior é membro do grupo do arquivo (cefet no caso);
4. Como o usuário junior não é membro do grupo do arquivo, o sistema nega o seu acesso,
pois nenhuma permissão para “outros usuários” está ativa.
Esse conceito é simples e funciona bem em boa parte dos casos, mas possui uma falha
de design que pode comprometer o sistema como um todo. No Linux, cada processo é
executado com um usuário dono e um grupo, e as permissões de acesso ao sistema funcionam
do mesmo modo que para usuários normais, ou seja, uma aplicação que seja executada com o
usuário junior terá acesso a todos os arquivos que o usuário junior tiver. Logo, uma aplicação
que seja comprometida pode acabar afetando muito mais do que ela mesma.
Capítulo 2 SE-Linux 20
2.2 MAC (Mandatory Access Control)
Devido às falhas do DAC, o SE-Linux, assim como outros mecanismos se segurança,
utiliza o Mandatory Access Control (Controle de Acesso Mandatório), ou MAC, como esquema
de controle de acesso [SPENNEBERG, 2005]. Esse tipo de controle permite que o administrador
do sistema realize ajustes mais precisos nas permissões do sistema, não permitindo que um
processo tenha mais acesso do que necessita para realizar sua função. Por exemplo, num
sistema Linux padrão, todos os usuários tem acesso de leitura nos dispositivos de vídeo, de
modo que possam utilizar aplicações gráficas, isso é desejável para usuários comuns, mas
outros processos talvez não necessitem ter esse tipo de acesso.
A política padrão do SE-Linux é negar o acesso a todos os recursos, tudo que for
necessário deve ser explicitamente habilitado, o que diminui muito os riscos para o sistema caso
um aplicativo seja comprometido. Um processo não pode ter privilégios que não necessite.
Como pode-se concluir, a utilização de um mecanismo de controle de acesso do tipo
MAC é bastante interessante para administradores de sistemas que necessitam de um maior
controle sobre o acesso aos dados do sistema.
2.3 SE-Linux vs AppArmour
O AppArmour, assim como o SE-Linux, é uma implementação de MAC para o Linux,
tendo o objetivo comum de melhorar a segurança do sistema, mas com um foco diferente.
Segundo Crispin Cowan [ALSBIH, 2005], arquiteto de segurança da Novell, o AppArmour
assegura aplicativos individuais contra defeitos latentes, e protege um sistema inteiro contra uma
ameaça em particular, tal como ataques pela rede, protegendo todos os aplicativos que usam a
rede. O foco em aplicações, ao invés do sistema como um todo, trás a vantagem de ser mais
simples gerenciar, e conseqüentemente mais fácil de entender, tornando o gerenciamento de
políticas mais simples.
Por outro lado, o SE-Linux, apesar de ser mais complexo de gerenciar, é também mais
completo, focando no sistema como um todo ao invés de aplicativos individuais. Segundo Daniel
Capítulo 2 SE-Linux 21
Riek [ALSBIH, 2005], gerente de produtos do Red Hat Enterprise Linux, em comparação com o
SE-Linux, o AppArmour não garante a confidencialidade dos dados, além de não garantir o
mesmo nível de segurança provido por um sistema com SE-Linux bem configurado, sendo a
implementação mais consistente de MAC na atualidade.
2.4 Considerações Finais sobre o SE-Linux
O uso do SE-Linux é recomendado para servidores críticos. Devido a sua robustez ele é
capaz de minimizar boa parte dos danos que poderiam ser causados caso um sistema sem o
uso dessa tecnologia fosse comprometido. A complexidade da configuração de políticas pode
ser minimizada com o uso de políticas de exemplo prontas disponíveis na Internet [SELINUX ,
2007].
Capítulo 3 Root-Plug 22
3 ROOT-PLUG
O Root-Plug é um módulo do kernel do Linux desenvolvido a partir da versão 2.5.31 que
evita que qualquer processo com o GID (Group ID) igual a 0 (GID do usuário root) seja
executado, a não ser que um determinado dispositivo USB esteja fisicamente conectado ao
sistema local quando o processo for iniciado [KROAH-HARTMAN, 2002]. Esse módulo pode ter
diversas aplicações, por exemplo, bloquear o processo de login de usuários via console (o
programa que realiza o login de usuários possui GID igual a 0), efetivamente barrando o acesso
ao sistema por essa via.
Esse módulo foi inicialmente desenvolvido por Greg Kroah-Hartman, um dos
desenvolvedores do Kernel do Linux e autor do Livro Linux Kernel In A Nutshell [O'REILLY, 2005],
como um exemplo útil de uso do recém implementado projeto LSM (Linux Security Modules) em
2002. O projeto LSM surgiu de uma discussão no Linux Kernel Summit de 2001 entre
funcionários da NSA americana e desenvolvedores do kernel do Linux sobre a necessidade de
aumentar o suporte a implementações de segurança no kernel principal do Linux, de modo que
diferentes modelos de segurança pudessem funcionar sem modificações no código do kernel
[KROAH-HARTMAN, 2002]. O LSM se tornou parte do kernel na versão 2.6, de modo que
diversos mecanismos de segurança puderam ser desenvolvidos, como o próprio Root-Plug e o
SE-Linux.
3.1 Funcionamento e Utilização
Quando um processo é posto para ser executado, várias chamadas de sistema são
feitas até que o processo seja efetivamente iniciado. É durante essas chamadas de sistema
iniciais que o Root-Plug entra em ação. Quando o módulo é carregado, ele se posiciona antes da
chamada de sistema que carrega o processo na memória, desviando o fluxo para uma função do
próprio módulo que procura nas tabelas de sistema o dispositivo USB determinado pelo
administrador caso o GID do processo seja igual a 0. Se o dispositivo não for encontrado, então
o processo retorna para o kernel um código de erro, o que impede que o processo seja
executado [KROAH-HARTMAN, 2002].
Capítulo 3 Root-Plug 23
A utilização é bem simples, com o módulo compilado e o kernel preparado, o
administrador só precisa carregar o módulo no sistema com o comando modprobe, passando
como parâmetros o ProductID e o VendorID do dispositivo USB. Esses valores podem ser
descobertos com o comando lsub ou analisando o conteúdo do arquivo /proc/bus/usb/devices,
ambos mostram diversas informações sobre os dispositivos USB conectados no sistema. A partir
do momento que o módulo é carregado ele começa a funcionar, portanto é importante ter certeza
que o módulo foi carregado com os parâmetros corretos para não bloquear a máquina
errôneamente.
3.2 Segurança
O Root-Plug, apesar de ter sido desenvolvido como um exemplo de uso do LSM, é
bastante útil em barrar o acesso ao sistema. Programas que já estejam em execução não são
parados por ele (conforme foi citado anteriormente, a checagem é feita no momento que o
processo é iniciado no sistema), por exemplo, o serviço de login remoto SSH (Secure Shell) irá
continuar executando e permitindo o login de usuários normais (apenas o de root não irá
funcionar, pois esse programa abre um novo processo com o GID igual ao do usuário, que no
caso do root é 0). Processos que não funcionam como usuário root irão continuar funcionando
normalmente.
Esse módulo, por outro lado, não impede um processo com GID 0 de se clonar ou mudar
os privilégios de outros, normalmente isso não é preocupante, a não ser que o processo em
questão tenha sido comprometido de algum maneira, nesse caso uma combinação entre Root-
Plug e SE-Linux é bastante interessante, pois enquanto o Root-Plug impede novos processos de
serem iniciados com privilégios de root, o SE-Linux assegura que aplicativos que sejam
comprometidos não afetem o sistema, funcionando como uma dupla proteção.
Capítulo 4 Rootkits 24
4 ROOTKITS
Rootkits é como são chamados programas maliciosos que alteram o funcionamento do
sistema operacional para não serem detectados, sendo bastante usados em sistemas
comprometidos para esconder traços de uma invasão, garantindo acesso futuro ao sistema
[ALSBIH, 2005].
O nome rootkit teria surgido por esses programas terem sido inicialmente “kits” de
programas para a plataforma UNIX usados para se obter acesso total a um sistema previamente
comprometido. Como nesses sistemas o usuário root possui acesso total ao sistema, o nome
rootkit foi criado para denominar esse tipo de aplicativo [ROOTKIT, 2007]. Hoje o termo se tornou
geral, sendo usado também em sistemas não UNIX, como o Microsoft Windows, mesmo não
tendo conta de usuário root.
4.1 Funcionamento
Conforme mencionado anteriormente, o objetivo de um rootkit é esconder arquivos,
conexões de rede e endereços de memória do administrador do sistema. As técnicas usadas
para obter essa funcionalidade variam, dividindo os rootkits em quatro categorias: Virtualizado,
Kernel, Biblioteca e Aplicação.
Os rootkits virtualizados são aqueles que modificam a seqüência de inicialização da
máquina, iniciando primeiro o rootkit, que por sua vez inicia o sistema operacional como uma
máquina virtual, podendo interceptar todas as chamadas de sistema do sistema operacional. Os
de kernel funcionam adicionando ou alterando código do kernel (por exemplo a tabela de
chamada de sistemas) de modo que informações são escondidas diretamente no núcleo do
sistema operacional. Os rootkits de biblioteca geralmente alteram ou substituem chamadas de
sistema por chamadas alteradas e os de aplicação alteram diretamente aplicativos do sistema
[ROOTKIT, 2007].
Conforme se pode constatar, um sistema comprometido com um rootkit pode ser
bastante prejudicial para uma rede, podendo causar vazamento de dados e expondo a rede ao
atacante.
Capítulo 4 Rootkits 25
4.2 Rootkit Hunter
O Rootkit Hunter é um aplicativo que serve para varrer o sistema em busca de rootkits
conhecidos [ROOTKIT.NL, 2007]. Para encontrar rootkits, o Rootkit Hunter utiliza uma variedade
de técnicas e checagens, como:
• Checagem de MD5: O algoritmo MD5 (Message-Digest Algorithm 5) é uma função de
hash que quando utilizada em um arquivo, gera um valor único de 128 bits, que pode ser
usado como uma “impressão digital” para identificar o arquivo. Uma alteração mínima no
arquivo altera drasticamente o valor MD5 gerado pela função. Desse modo, fazendo
uma comparação com valores MD5 conhecidos como “bons” pode-se descobrir se um
aplicativo foi alterado ou não, como no caso de uma alteração realizada por um rootkit;
• Arquivos conhecidos: Procurando no sistema por arquivos e diretórios usados por
rootkits conhecidos;
• Arquivos ocultos: Procurando por arquivos ocultos em diretórios em que normalmente
não deveriam estar;
• Checagens no sistema operacional: No caso do Linux o sistema compara os
processos mostrados pelo aplicativo ps (aplicativo comum em todos os sistemas Linux
que lista os processos atualmente em execução no sistema) com as informações
disponíveis no diretório /proc, que é onde o Linux coloca todas as informações sobre o
sistema.
• Permissões de arquivos: Arquivos comuns do sistema normalmente possuem
permissões de acesso que não permitem que usuários normais do sistema possam
altera-los ou danifica-los de algum modo. Vários rootkits acabam alterando as
permissões de acesso desses arquivos, de modo que o Rootkit Hunter realiza uma
procura por arquivos com permissões incomuns.
• Módulos do Kernel: São checados os módulos do kernel em busca de alterações ou
funcionalidades suspeitas.
• Portas abertas: Alguns rootkits abrem portas no sistema para acesso remoto, o Rootkit
Capítulo 4 Rootkits 26
Hunter realiza uma busca por atividade suspeita nas portas abertas do sistema.
• Checagem de Strings: O programa realiza uma busca em vários diretórios por strings
suspeitas contidas em arquivos binários e de texto. As palavras suspeitas estão contidas
em um dicionário interno com strings contidas em aplicativos de vários rootkits
conhecidos.
O Rootkit Hunter é uma ferramenta bastante desejável para buscar possíveis sinais de
invasão e comprometimento do sistema, combinada com os outros mecanismos de segurança
apresentados nesse documento, pode aumentar sensivelmente a segurança geral de um
sistema.
Capítulo 5 SecMec 27
5 SECMEC
O programa SecMec foi desenvolvido com o objetivo de facilitar a instalação de
mecanismos de segurança diferenciados no Linux. Ele foi desenvolvido em shell script para
BASH (Bourne again shell), que é o interpretador de comandos padrão da maioria dos sistemas
Linux atuais, com a interface do usuário feita em Dialog, que é um programa que permite o
desenho de interfaces direto no console, sem a necessidade de um servidor gráfico. Esses dois
programas foram escolhidos pelos seguintes motivos:
1. Compatibilidade com diversos sistemas Linux;
2. Velocidade: os scripts são rápidos e a interface é leve;
3. Podem ser utilizados remotamente através de SSH (Secure Shell);
4. Facilidade pare desenvolvimento e correção de problemas.
O SecMec foi desenvolvido de forma modular, de modo que novas funcionalidades
possam ser facilmente adicionadas, contando com funções prontas para diversas tarefas
complexas como ajuste de opções de compilação de kernel. Foram desenvolvidos módulos,
chamados de mecanismos ou mecs (nome derivado de “Mecanismos de Segurança”), para a
instalação do SE-Linux, Root-Plug e Rootkit Hunter.
5.1 Análise do Sistema
Para um melhor entendimento do funcionamento do sistema e de suas principais
funções, foram elaborados três diagramas descritos a seguir, que mostram de maneira gradativa
o comportamento do programa. Iniciando com uma visão mais geral do programa e terminando
em uma visão mais detalhada do funcionamento.
5.1.1 Diagrama de Contexto
O Diagrama de Contexto ilustrado na figura 2 mostra o funcionamento geral e estabelece
os limites do sistema. Nele é possível ver de maneira simples a interação entre o administrador
Capítulo 5 SecMec 28
do sistema e o programa.
Figura 2. Diagrama de Contexto
Para utilizar o sistema, o administrador deve apenas selecionar a opção de instalar
mecanismos de segurança e entrar com as opções de instalação que são requisitadas pelo
programa. Ao final do uso o sistema retorna o resultado da operação (sucesso ou falha).
5.1.2 Diagrama de Fluxo de Dados Nível 1
O Diagrama de Fluxo de Dados Nível 1 (ver Figura 3), mostra com um nível de
detalhamento maior que o diagrama de contexto mostrado anteriormente o funcionamento do
programa.
Figura 3. Diagrama de Fluxo de Dados Nível 1
Nele pode-se ver duas macro funções (Mostrar Mecanismos e Instalar Mecanismos),
que interagem diretamente com o administrador do sistema e buscam os dados necessários para
o seu funcionamento de duas localizações: A base de dados em texto puro chamada de
Mecanismos, que contém a lista de mecanismos disponíveis para a instalação no sistema e a
Capítulo 5 SecMec 29
Internet, de onde são obtidos dinamicamente dados necessários pelos mecanismos de
segurança.
5.1.3 Diagrama de Fluxo de Dados Nível 2
No diagrama apresentado na Figura 4 pode-se ver com maiores detalhes a macro
função Instalar Mecanismo.
Figura 4. Diagrama de Fluxo de Dados Nível 2
Nesse diagrama estão detalhados todos os mecanismos de segurança que foram
desenvolvidos para esse projeto. Pode-se ver como funciona a interação de cada um dos
mecanismos com o sistema e como a Internet é utilizada para buscar dados necessários para a
instalação dos mecanismos.
5.2 Requisitos para Funcionamento
A seguir são descritos os requerimentos para o funcionamento do SecMec, note que as
versões de aplicativos citadas são as versões que foram usadas durante as fases de
desenvolvimento e testes, podendo funcionar com diferentes versões.
• Sistema Operacional Linux: Por ser um programa desenvolvido para Linux, o
Capítulo 5 SecMec 30
requisito mais básico é o do uso desse sistema operacional. Ele foi testado na
distribuição Slackware com o kernel 2.6.17 e pode funcionar em outras distribuições
com nenhuma ou pequenas adaptações;
• BASH (3.1.17) com suporte à DIALOG (3.1): BASH é o interpretador de linha de
comando padrão da grande maioria dos sistemas Linux atuais e, é a base do
desenvolvimento do SecMec, que foi desenvolvido utilizando-se scripts para esse
interpretador. O DIALOG é um programa que mostra interfaces em um terminal de
console, e foi usado para construir as telas do SecMec. Os dois formam a base de
todo o programa;
• Grep (2.5): Grep é uma ferramenta que realiza buscas por padrões de texto em
arquivos de maneira rápida;
• Util-Linux (2.12): Diversas ferramentas essenciais para o funcionamento de um
sistema Linux (como kill, more, mount, etc...);
• Wget (1.10.2): Ferramenta para fazer download de dados da Internet;
• Coreutils (5.97): Programas básicos para qualquer sistema Linux (ls, mkdir, rm,
etc...);
• Tar (1.15): Programa desenvolvido para concatenação de arquivos, também tendo
funções de compactação e descompactação em versões mais recentes.
• Make (3.81): Ferramenta criada para facilitar a compilação de programas,
determinando automaticamente quais pedaços de um programa devem ser
compilados e executando os comandos para compila-los;
• GCC (4.1.1): Compilador C para Linux. Utilizado no projeto para compilar o kernel;
• SED (4.1.5): O SED é um editor de fluxo de texto, usado para realizar
transformações em um texto;
• LILO (22.3.251): O LILO (Linux Loader) é um programa utilizado para iniciar o
sistema Linux presente em um disco rígido;
• Conexão com a Internet ativa: Uma conexão com a Internet ativa é necessária
para que o SecMec funcione corretamente, pois ele precisa fazer download de
pacotes disponíveis na Internet quando necessário.
Capítulo 5 SecMec 31
5.3 Desenvolvimento
Conforme citado anteriormente, o programa foi desenvolvido em shell script para BASH
com interfaces feitas com o programa Dialog. Isso permitiu o desenvolvimento de um programa
leve e rápido, que pode ser operado local ou remotamente sem a necessidade de uma interface
gráfica local.
Para garantir a consistência das telas e facilitar o desenvolvimento de scripts, foram
criadas uma série de funções, para serem utilizadas de maneira semelhante a uma biblioteca. A
Tabela 1 fornece a lista das funções disponíveis na biblioteca secmec-base-1.0 e uma breve
descrição de sua finalidade
Todas as funções tem sua documentação no próprio arquivo da biblioteca (ver Apêndice
A), com exemplos de uso, finalidade, códigos de retorno, lista de parâmetros etc. Na Tabela 1
podemos ver o nome de todas as funções desenvolvidas assim como uma breve descrição de
suas funcionalidades.
Capítulo 5 SecMec 32
Tabela 1. Funções da biblioteca secmec-base-1.0
Funções da biblioteca secmec-base-1.0
Função Descrição
error_screen Mostra uma mensagem de erro
success_screen Mostra uma mensagem de sucesso
message_screen Mostra uma mensagem
info_screen Mostra uma tela de informação
confirmation_screen Mostra uma tela de confirmação
text_screen Mostra uma tela com o conteúdo de um arquivo
numbered_menu_from_file_screen Mostra um menu com as entradas a partir de um arquivo
download_files Faz download de arquivos de um endereço na Internet
download_files_with_progress Faz download de arquivos de um endereço na Internet e mostra o progresso ao usuário
check_available_kernel_sources Procura pelo código fonte do kernel disponível no sistema
show_offical_kernel_sources Mostra lista de kernels 2.6 disponíveis em www.kernel.org
show_available_kernel_sources Mostra tela de seleção de kernel para o usuário
set_kernel_config Ajusta parâmetro de configuração do kernel para compilação
make_kernel Compila o kernel
available_mecs Procura os mecs disponíveis no sistema
list_available_mecs Mostra os mecs disponíveis no sistema para instalação
Capítulo 5 SecMec 33
Os arquivos do programa estão organizados da seguinte maneira, tomando como base a
estrutura de diretórios do Linux:
/|-etc/| |-secmec/| |-functions/ Funções do SecMec (biblioteca)| |-mecs/ Mecanismos disponíveis para uso||-usr/| |-sbin/ Executável do SecMec| || |-src/ Código fonte do kernel disponível|||-var/| |-cache/| | |-secmec/ Diretório de armazenamento temporário para o SecMec| || |-log/ Mensagens de log do SecMec
Essa organização de diretórios foi escolhida para facilitar o desenvolvimento e a
expansão do programa original. Por exemplo, novas bibliotecas de funções podem ser facilmente
adicionadas em /etc/secmec/functions para serem usadas pelos mecanismos e, por sua vez,
novos mecanismos podem ser adicionados no diretório /etc/secmec/mecs, tornando-se
disponíveis para uso logo que o programa for executado.
Na próxima seção são apresentadas as telas do assistente SecMec, ilustrando a
instalação dos três mecanismos de segurança desenvolvidos.
5.4 Telas do SecMec
A tela principal do assistente é ilustrada na Figura 5. De maneira simples e direta, a tela
mostra as opções Install (Instalar), About (Sobre) e Exit (Sair). A opção Install mostra a lista de
mecanismos disponíveis para a instalação, a opção About mostra uma tela com informações
sobre o programa, assim como informações de licenciamento, e finalmente a opção Exit, que
conforme o nome indica, sai do programa.
Capítulo 5 SecMec 34
Figura 5. Tela Principal
A figura 6 mostra a tela de About do programa, que contém uma explicação básica sobre
objetivo do SecMec e também mostra a licença em que o programa foi lançado (No caso, na
General Public License version 2).
Figura 6. Tela Sobre
Capítulo 5 SecMec 35
A Figura 7 ilustra a tela do SecMec que permite ao usuário selecionar um mecanismo de
segurança a ser instalado pelo sistema. Cada vez que um mecanismo é adicionado ao diretório
/etc/secmec/mecs ele irá aparecer nessa lista. O botão Cancel retorna para a tela principal (ver
Figura 5).
Figura 7. Tela de Mecanismos Disponíveis
Conforme ilustra a Figura 8, a primeira tela da instalação mostra informações sobre o
mecanismo e pede para o administrador confirmar se realmente deseja instalá-lo. O botão Yes
(Sim) irá iniciar o processo de instalação, o botão No (Não) irá voltar para a tela de mecanismos
disponíveis (ver Figura 7).
Capítulo 5 SecMec 36
Figura 8. Tela Instalação do Mecanismo Rootkit Hunter – Parte 1
Primeiramente, o sistema fará o download da versão 1.2.8 do Rootkit-Hunter do site
oficial (ver Figura 9). Após o download, o processo de instalação é efetuado automaticamente
conforme ilustra a Figura 10.
Figura 9. Tela Instalação do Mecanismo Rootkit Hunter – Parte 2
Capítulo 5 SecMec 37
Figura 10. Tela Instalação do Mecanismo Rootkit Hunter – Parte 3
Depois que o processo de instalação terminar, uma tela é mostrada ao administrador,
informando-o do sucesso do processo e como usar o programa (ver Figura 11).
Figura 11. Tela Instalação do Mecanismo Rootkit Hunter – Parte 4
A primeira tela da instalação do Rootplug mostra informações sobre ele e pede para o
Capítulo 5 SecMec 38
usuário confirmar se deseja realmente instalar esse mecanismo. O botão Yes (Sim) inicia o
processo de instalação, o botão No (Não) volta para a tela de seleção de mecanismos (ver
Figura 5).
Figura 12. Tela Instalação do Mecanismo Rootplug – Parte 1
Agora é mostrado para o usuário os códigos fontes do kernel do Linux disponíveis no
seu sistema (ver Figura 13). O botão Choose (Escolher), faz o programa usar o kernel
selecionado, o botão Download kernel (Download de kernel) inicia o processo de download de
uma versão do kernel do repositório oficial na Internet (http://www.kernel.org). Para efeito de
demonstração usaremos a função Download kernel.
Capítulo 5 SecMec 39
Figura 13. Tela Instalação do Mecanismo Rootplug – Parte 2
Na próxima fase da instalação o sistema faz o download da lista oficial de kernels e a
formata para poder ser exibida em tela (ver Figura 14).
Figura 14. Tela Instalação do Mecanismo Rootplug – Parte 3
A lista de kernels disponíveis para download é mostrada para o usuário (ver Figura 15).
Capítulo 5 SecMec 40
Ele deve selecionar um para continuar. O botão Cancel (Cancelar) volta para a tela inicial. Foi
selecionada a primeira opção linux-2.6.19.tar.bz2 para a demonstração do processo de
instalação.
Figura 15. Tela Instalação do Mecanismo Rootplug – Parte 4
Com o kernel selecionado, o sistema começa a fazer o download do mesmo, processo
que pode demorar dependendo da velocidade da conexão do administrador com a Internet (ver
Figura 16).
Capítulo 5 SecMec 41
Figura 16. Tela Instalação do Mecanismo Rootplug – Parte 5
Depois que o download é finalizado, o arquivo com o código fonte do kernel é
descompactado (ver Figura 17).
Figura 17. Tela Instalação do Mecanismo Rootplug – Parte 6
A tela mostrada na figura 18 aparece quando o programa consegue encontrar o arquivo
de configuração do kernel atual. Nesse caso, ele pergunta para o usuário se ele deseja usa-lo
Capítulo 5 SecMec 42
como base para a compilação do kernel. A opção No (Não) faz com que o programa use as
opções padrões do kernel que foi feito o download. Nesse caso foi escolhido Yes (Sim).
Figura 18. Tela Instalação do Mecanismo Rootplug – Parte 7
A próxima fase da instalação consiste na compilação do kernel (ver Figura 19).
Geralmente é um processo demorado (dependendo de vários fatores, incluindo a velocidade do
processador).
Capítulo 5 SecMec 43
Figura 19. Tela Instalação do Mecanismo Rootplug – Parte 8
Com o kernel compilando e instalado, o sistema avisa que vai mostrar a lista dos
dispositivos USB presentes no sistema e pede para o administrador anotar os valores de Vendor
e ProdID necessários para a operação (ver Figura 20).
Figura 20. Tela Instalação do Mecanismo Rootplug – Parte 9
Capítulo 5 SecMec 44
A lista de dispositivos USB é mostrada ao usuário (ver Figura 21), ele pode usar as
teclas de seta para cima e para baixo para ver toda a lista. O botão Yes (Sim), vai para o próximo
passo.
Figura 21. Tela Instalação do Mecanismo Rootplug – Parte 10
Agora o programa pede para o administrador deve entrar com o valor Vendor do
dispositivo escolhido (ver Figura 22). O botão OK confirma o valor, o botão Cancel (Cancelar)
volta para a tela inicial.
Capítulo 5 SecMec 45
Figura 22. Tela Instalação do Mecanismo Rootplug – Parte 11
Agora o administrador deve entrar com o valor de ProdID do dispositivo selecionado (ver
Figura 23). Como no passo anterior o botão OK confirma a seleção e o botão Cancel (Cancelar)
retorna para a tela inicial.
Figura 23. Tela Instalação do Mecanismo Rootplug – Parte 12
Para finalizar o sistema informa ao usuário que irá adicionar as informações de
Capítulo 5 SecMec 46
carregamento do módulo ao arquivo /etc/rc.d/rc.local, e que se necessário ele deve comentar
essa linha caso não queira mais usar o Rootplug (ver Figura 24) .
Figura 24. Tela Instalação do Mecanismo Rootplug – Parte 13
Por último o sistema informa o sucesso da instalação (ver Figura 25). O botão OK
retorna para a tela principal.
Figura 25. Tela Instalação do Mecanismo Rootplug – Parte 14
Capítulo 5 SecMec 47
Agora será mostrado o processo de instalação do SE-Linux. Como todos os
mecanismos, o programa primeiramente pergunta ao administrador se ele deseja instalar o
mecanismo (ver Figura 26). O botão Yes (Sim) inicia a instalação, o botão No (Não) volta para a
tela de seleção de mecanismos.
Figura 26. Tela Instalação do Mecanismo SE-Linux – Parte 1
Primeiramente, o programa mostra a lista de kernels disponíveis no sistema (ver Figura
27). O botão Download kernel (Fazer download do kernel) inicia o processo de download de um
kernel do site http://www.kernel.org, o botão Choose (Escolher), selecione um dos kernels já
disponíveis no sistema. Nesse caso escolheremos o kernel de número três na lista (linux-2.6.19-
rootplug), que foi o kernel utilizado para a demonstração da instalação do Rootplug.
Capítulo 5 SecMec 48
Figura 27. Tela Instalação do Mecanismo SE-Linux – Parte 2
Com o kernel selecionado, o processo de compilação começa (ver Figura 28). Esse
processo tende a ser demorado (dependendo de diversos fatores, como quantidade de memória
e velocidade do processador).
Figura 28. Tela Instalação do Mecanismo SE-Linux – Parte 3
Capítulo 5 SecMec 49
Depois que o kernel foi compilado e instalado com sucesso, o sistema faz o download
dos programas necessários para a configuração do SE-Linux (ver Figura 29).
Figura 29. Tela Instalação do Mecanismo SE-Linux – Parte 4
Depois que o download foi concluído, o sistema começa a descompactar os programas
(ver Figura 30) e os instala (ver Figura 31).
Figura 30. Tela Instalação do Mecanismo SE-Linux – Parte 5
Capítulo 5 SecMec 50
Figura 31. Tela Instalação do Mecanismo SE-Linux – Parte 6
Para finalizar a instalação, o sistema mostra uma tela informando o sucesso da
instalação ao usuário (ver Figura 32). O botão OK retorna para a tela principal (ver Figura 5).
Figura 32. Tela Instalação do Mecanismo SE-Linux – Parte 7
Capítulo 5 SecMec 51
Como pode-se ver pelas telas da aplicação, o processo de instalação desses
mecanismos foi bastante simplificado, requisitando do administrador do sistema apenas as
informações essenciais que não podem ser decididas automaticamente, de modo que o objetivo
principal do projeto foi atingido.
Capítulo 6 Conclusão e Trabalhos Futuros 52
6 CONCLUSÃO E TRABALHOS FUTUROS
O SecMec foi desenvolvido com sucesso. O seu objetivo é facilitar a instalação de
mecanismos de segurança em um sistema Linux de maneira simples, tirando do administrador o
ônus de ter que aprender o processo de instalação e liberando-o para outras tarefas. O programa
provou-se eficaz, instalando os mecanismos desenvolvidos de maneira simples e não exigindo
conhecimento do processo de instalação por parte do administrador do sistema.
As maiores dificuldades encontradas durante o desenvolvimento foram na automatização
do processo de compilação do kernel e no desenvolvimento das funções para evitar repetição de
código nos mecanismos (apesar de não ter sido possível evitar totalmente). Foi necessário
bastante estudo do processo de compilação do kernel para descobrir como habilitar as opções
desejadas e os requerimentos das mesmas, e como fazer isso sem ter que esperar por uma
intervenção do administrador. Quanto as funções, elas tiveram que ser reescritas várias vezes
até se chegar na forma final.
6.1 Trabalhos Futuros
Existem diversas aspectos que podem ser melhorados no programa como um todo.
Inicialmente, o desenvolvimento de novas funções para ajustar o processo de instalação de
mecanismos para outras distribuições Linux para, por exemplo, fazer uso dos repositórios da
distribuição para buscar pacotes e utilização da ferramenta de gerenciamento de pacotes das
mesmas (rpm, tgz, dpkg, etc...). Adicionar suporte ao bootloader GRUB que também faz parte de
várias distribuições Linux e a criação de um sistema de auto-detecção de hardware para a
criação de um kernel mais otimizado. Outra característica importante é implementar uma função
de checagem de domínio, para garantir mais segurança nos downloads, além de checagem de
assinatura e hashes.
Para facilitar o desenvolvimento futuro do projeto, ele foi colocado no SourceForge.net
[SOUZA, 2007], que é um site da Internet que provê diversas ferramentas para o
desenvolvimento de projetos de software de código aberto.
53
REFERÊNCIAS
ALSBIH, Amir. Arma Secreta. Revista do Linux, Brasil, #22, p. 28-33, ago 2005.
APPARMOUR Project, The. Disponível em: <http://en.opensuse.org/AppArmor>. Acesso em 01 de fev. 2007.
DRAKXCONF. Wikipedia. Disponível em <http://en.wikipedia.org/wiki/Drakconf>. Acesso em 30 jan. 2007.
KROAH-HARTMAN, Greg. Linux Kernel In A Nutshell. O'Reilly, 2005.
KROAH-HARTMAN, Greg. Using The Kernel Security Module Interface. Linux Journal. Disponível em: <http://www.linuxjournal.com/article/6279>. Acesso em 30 jan. 2007.
LEITNER, Achim. AppAmour x SELinux. Revista do Linux, Brasil, #22, p. 42-45, ago 2005.
MANDATORY, Access Control. Wikipedia. Disponível em: <http://en.wikipedia.org/wiki/Mandatory_access_control>. Acesso em 01 fev 2007.
NSA. Security-Enhanced Linux. NSA. Disponível em: <http://www.nsa.gov.org/selinux>. Acesso em 02 fev 2007.
ROOTKIT. Wikipedia. Disponível em: <http://en.wikipedia.org/wiki/Rootkit>. Acesso em 02 fev. 2007.
ROOTKIT.NL. Rootkit Hunter. ROOTKIT.NL. Disponível em: <http://www.rootkit.nl/projects/rootkit_hunter.html>. Acesso em 07 fev 2007.
SECURITY-Enhanced Linux. Wikipedia. Disponível em: <http://en.wikipedia.org/wiki/SELinux>. Acesso em 30 jan. 2007.
SELINUX Reference Policy. Tresys. Disponível em: <http://oss.tresys.com/projects/refpolicy>. Acesso em 14 fev. 2007.
54
SOUZA, Tiago Almeida Barboza, SecMec. Disponível em: <http://secmec.sourceforge.net>. Acesso em 14 fev 2007.
SPENNEBERG, Ralf. Armadura Segura. Revista do Linux, Brasil, #22, p. 34-37, ago 2005.
SPENNEBERG, Ralf. Acesso Sob Controle SELinux. Revista do Linux, Brasil, #22, p. 38-41, ago 2005.
55
APÊNDICE A: CÓDIGO FONTE ./ETC/SECMEC/FUNCTIONS
#!/bin/bash############ Functions for SecMec scripts.## SecMec can be found at http://secmec.sourceforge.net### Copyright (C) 2006 Tiago "Salvador" Souza <ts.salvadorATgmailDOTcom>### This file is part of SecMec.## SecMec is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License version 2 # published by the Free Software Foundation.## SecMec is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with SecMec; if not, write to the Free Software# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA##########
################################### Generic dialog message screens ###################################
## Shows an error information screen### Description:## This function presents an error screen with a confirmation button.#### Usage:## error_screen "error message" "back title" "window title" \# "button label" "extra dialog parameters" "window height" \# "window width"## All parameters but $1 are mandatory, all the remaining ones have# default values and don't need to be passed unless necessary,# although it is a good practice todo so. To use the default values# you can also pass "" in place of the parameter, for instance, to# use the default back title and title but change the button's label# the function can be called in the following manner:## error_screen "error message" "" "" "exit"#### Return codes:
56
## -1: Internal dialog error# 0: Ok button# 1: Ctrl+C key combo# 255: ESC key#### Internal Variables:## $1: Error message# $2: Screen's back title# $3: Window tittle# $4: Button label# $5: Extra parameters for dialog# $6: Window height# $7: Window width#### Misc:## Author: Tiago "Salvador" Souza# Date: 06/11/2006#### Changelog:##error_screen (){
"$DIALOG" --backtitle "${2:-$SECMEC_BACK_TITLE}" \--title "${3:-$MEC_NAME}" --ok-label "${4:-OK}" \--cr-wrap $5 --msgbox "$1" "${6-0}" "${7:-0}"
return "$?"}
## Shows a success information screen### Description:## This function presents a success screen with a confirmation button.#### Usage:## success_screen "success message" "back title" "window title" \# "button label" "extra dialog parameters" "window height" \# "window width"## All parameters but $1 are mandatory, all the remaining ones have# default values and don't need to be passed unless necessary,# although it is a good practice todo so. To use the default values# you can also pass "" in place of the parameter, for instance, to# use the default back title and title but change the button's label# the function can be called in the following manner:## success_screen "error message" "" "" "exit"##
57
## Return codes:## -1: Internal dialog error# 0: Ok button# 1: Ctrl+C key combo# 255: ESC key#### Internal Variables:## $1: Success message# $2: Screen's back title# $3: Window tittle# $4: Button label# $5: Extra parameters for dialog# $6: Window height# $7: Window width#### Misc:## Author: Tiago "Salvador" Souza# Date: 16/11/2006#### Changelog:##success_screen (){
"$DIALOG" --backtitle "${2:-$SECMEC_BACK_TITLE}" \--title "${3:-$MEC_NAME}" --ok-label "${4:-OK}" \--cr-wrap $5 --msgbox "$1" "${6-0}" "${7:-0}"
return "$?"}
## Shows a success information screen### Description:## This function presents a message screen with a confirmation button.#### Usage:## message_screen "message text" "back title" "window title" \# "button label" "extra dialog parameters" "window height" \# "window width"## All parameters but $1 are mandatory, all the remaining ones have# default values and don't need to be passed unless necessary,# although it is a good practice todo so. To use the default values# you can also pass "" in place of the parameter, for instance, to# use the default back title and title but change the button's label# the function can be called in the following manner:## message_screen "message text" "" "" "exit"#
58
### Return codes:## -1: Internal dialog error# 0: Ok button# 1: Ctrl+C key combo# 255: ESC key#### Internal Variables:## $1: Message text# $2: Screen's back title# $3: Window tittle# $4: Button label# $5: Extra parameters for dialog# $6: Window height# $7: Window width#### Misc:## Author: Tiago "Salvador" Souza# Date: 17/11/2006#### Changelog:##message_screen (){
"$DIALOG" --backtitle "${2:-$SECMEC_BACK_TITLE}" \--title "${3:-$MEC_NAME}" --ok-label "${4:-OK}" \--cr-wrap $5 --msgbox "$1" "${6-0}" "${7:-0}"
return "$?"}
## Shows an information screen### Description:## This function presents an information screen and exits.#### Usage:## info_screen "message" "back title" "window title" \# "extra dialog parameters" "window height" "window width"## All parameters but $1 are mandatory, all the remaining ones have# default values and don't need to be passed unless necessary,# although it is a good practice todo so. To use the default values# you can also pass "" in place of the parameter, for instance, to# use the default back title but change the window's title, the# function can be called in the following manner:## info_screen "message" "" "new window title"#
59
### Return codes:## -1: Internal dialog error# 0: Ok button#### Internal Variables:## $1: Message# $2: Screen's back title# $3: Window tittle# $4: Extra parameters for dialog# $5: Window height# $6: Window width#### Misc:## Author: Tiago "Salvador" Souza# Date: 06/11/2006#### Changelog:##info_screen (){
"$DIALOG" --backtitle "${2:-$SECMEC_BACK_TITLE}" \--title "${3:-$MEC_NAME}" --cr-wrap $4 \--infobox "$1" "${5:-0}" "${6:-0}"
return "$?"}
## Shows a confirmation screen### Description:## This function presents an confirmation screen with a yes and a no# button.#### Usage:## confirmation_screen "message" "back title" "window title" \# "yes button label" "no button label" \# "extra dialog parameters" "window height" \# "window width"## All parameters but $1 are mandatory, all the remaining ones have# default values and don't need to be passed unless necessary,# although it is a good practice todo so. To use the default values# you can also pass "" in place of the parameter, for instance, to# use all the default options but change the no label button, the# function can be called in the following manner:## confirmation_screen "message" "" "" "" "no button label"#
60
### Return codes:## -1: Internal dialog error# 0: Ok button# 1: No button or Ctrl+C key combo# 255: Esc key### Internal Variables:## $1: Message# $2: Screen's back title# $3: Window tittle# $4: Yes button label# $5: No button label# $6: Extra parameters for dialog# $7: Window height# $8: Window width#### Misc:## Author: Tiago "Salvador" Souza# Date: 06/11/2006#### Changelog:##confirmation_screen (){
"$DIALOG" --backtitle "${2:-$SECMEC_BACK_TITLE}" \--title "${3:-$MEC_NAME}" --ok-label "${4:-Yes}" \--cancel-label "${5:-No}" --clear --cr-wrap $6 \--yesno "$1" "${7:-0}" "${8:-0}"
return "$?"}
## Shows a screen with the contents of a text file### Description:## This function presents a screen with the contents of the file# passed in $1 and an exit button.#### Usage:## text_screen "text file" "back title" "window title" \# "exit button label" "extra dialog parameters" \# "window height" "window width"## All parameters but $1 are mandatory, all the remaining ones have# default values and don't need to be passed unless necessary,# although it is a good practice todo so. To use the default values# you can also pass "" in place of the parameter, for instance, to# use all the default options but change the exit label button, the# function can be called in the following manner:
61
## text_screen "text file" "" "" "exit button label"#### Return codes:## -1: Internal dialog error# 0: Ok button# 1: No button or Ctrl+C key combo#255: Esc key### Internal Variables:## $1: Text file# $2: Screen's back title# $3: Window tittle# $4: Exit button label# $5: Extra parameters for dialog# $6: Window height# $7: Window width#### Misc:## Author: Tiago "Salvador" Souza# Date: 17/11/2006#### Changelog:##text_screen (){
"$DIALOG" --backtitle "${2:-$SECMEC_BACK_TITLE}" \--title "${3:-$MEC_NAME}" --exit-label "${4:-Yes}" \--clear --cr-wrap $5 \--textbox "$1" "${6:-0}" "${7:-0}"
}
## Shows a numbered menu screen with values from a file### Description:## This function shows a menu dialog with numbered options. It takes # the list of choices from the file passed in $2.#### Usage:## numbered_menu_from_file_screen "description" "file name" \# "back title" "window title" "yes button label" \# "cancel button label" "extra dialog parameters" \# "window height" "window width" \# "number of visible menu entries"## All parameters but $1 and $2 are mandatory, all the remaining ones# have default values and don't need to be passed unless necessary,# although it is a good practice todo so. To use the default values
62
# you can also pass "" in place of the parameter, for instance, to# change only the back title, the function can be called in the# following manner:## numbered_menu_from_file_screen "description" "file.txt" "" \# "back title"## Especial considerations:## - The file entries must be formated in the following way:# Number OneWordEntry# For instance:# 1 Linux_Slackware# 2 BSD# You can make a file with more than 2 fields but the remaining ones# will be disregarded, for instance, "1 Linux Rocks" will generate a# "1 Linux" as menu entry# - Limit menu options to 254, since 255 is the maximum value bash# can return and that value is passed when the user hits the ESC# key or the cancel button# - The function will return the numeric value of the choice.### Return codes:## 0-254: Ok button# 255: Esc key### Internal Variables:## $1: Menu description# $2: Name of the file with the menu entries# $3: Screen's back title# $4: Window tittle# $5: Select button label# $6: Cancel button label# $7: Extra parameters for dialog# $8: Window height# $9: Window width# $10: Number of visible menu entries#### Misc:## Author: Tiago "Salvador" Souza# Date: 07/11/2006### Changelog:## 07/11/2006 by Tiago "Salvador" Souza: # No more extra parameters for file handling, leaving only the# default option. By the way it was made it was impossible to# pass file name parameters which contained spaces (including# file directories).numbered_menu_from_file_screen (){
local MENU_CHOICElocal MENU_OPTION
MENU_CHOICE=$("$DIALOG" --backtitle "${3:-$SECMEC_BACK_TITLE}" \
63
--title "${4:-$MEC_NAME}"\--ok-label "${5:-Choose}" \--cancel-label "${6:-Cancel}" \--clear --cr-wrap --stdout $7 \--menu "$1" "${8:-0}" "${9:-0}" "${10:-0}" \$(for MENU_OPTION in "$(cat "$2" | cut --delimiter=" "
--fields="1 2")"; \do echo "$MENU_OPTION";\done))
if [ "$MENU_CHOICE" == "" ]then
MENU_CHOICE=255fireturn "$MENU_CHOICE"
}
#################### Misc. Functions ####################
## Downloads files### Description:## This function shows shows a screen to the user and downloads files#### Usage:## download_files "download description" "file address" \# "extra wget paramaters" "back title" ""window title" \# "extra dialog parameters" "window height" \# "window width"## All parameters but $1 are mandatory, all the remaining ones have# default values and don't need to be passed unless necessary,# although it is a good practice todo so. To use the default values# you can also pass "" in place of the parameter, for instance, to# change only the back title, the function can be called in the# following manner:## download_files "download description" \# "http://file.to.be.downloadeds.address" "" \# "back title"#### Return codes:## 0: Download OK # Any other code: Download error### Internal Variables:## $1: Download Description# $2: Address of the file to be downloaded# $3: Extra wget parameters# $4: Back title
64
# $5: Window tittle# $6: Extra parameters for dialog# $7: Window height# $8: Window width#### Misc:## Author: Tiago "Salvador" Souza# Date: 07/11/2006### Changelog:## 09/11/2006 by Tiago "Salvador" Souza: # Added the --quiet parameter to wget# 10/11/2006 by Tiago "Salvador" Souza: # Minor documentation correctiondownload_files (){
"$DIALOG" --backtitle "${4:-$SECMEC_BACK_TITLE}" \--title "${5:-$MEC_NAME}" --cr-wrap $6 \--infobox "$1" "$7" "$8"
eval wget --tries=20 --quiet --timestamping --no-cache $3 "$2"
return "$?"}
## Downloads files showing the progress### Description:## This function downloads files and shows to the user the download's# progress. It should be used to download large files.#### Usage:## download_files_with_progress "file address" "extra wget parameters" \# "back title" "window title" \# "extra dialog parameters" ## All parameters but $1 are mandatory, all the remaining ones have# default values and don't need to be passed unless necessary,# although it is a good practice todo so. To use the default values# you can also pass "" in place of the parameter, for instance, to# change only the back title, the function can be called in the# following manner:## ddownload_files_with_progress http://file.to.be.downloadeds.address \# "" "back title"### Especial considerations:## This function's code was based on Dropline Gnome's installer for# Slackware Linux. So Thanks big thanks to them. Their internet# address is: www.dropline.net/gnome##
65
## Return codes:## 0: Download OK # Any other code: Download error### Internal Variables:## WGET_STATUS: Wget's return code# $1: Address of the file to be downloaded# $2: Extra wget parameters# $3: Back title# $4: Window tittle# $5: Extra parameters for dialog#### Misc:## Author: Tiago "Salvador" Souza# Date: 10/11/2006### Changelog:## 13/11/2006 by Tiago "Salvador" Souza: Fixed a re-definition of the# WGET_STATUS variable which was placed# after "reset" causing it to always# return 0, even if the download# failleddownload_files_with_progress (){
local WGET_STATUS
# First let's create some necessary temporary files, the# first one will recieve wget's output and the second one# will hold dialog's pid, it's necessary since dialog will# run on background and we will need this information to be# able to finish it.cat /dev/null > "$SECMEC_CACHE"/wget.outcat /dev/null > "$SECMEC_CACHE"/dialog.pid
"$DIALOG" --backtitle "${3:-$SECMEC_BACK_TITLE}" \--title "${4:-$MEC_NAME}" --no-kill $5 \--tailboxbg "$SECMEC_CACHE"/wget.out \15 75 2> "$SECMEC_CACHE"/dialog.pid
eval wget --tries=20 --timestamping --no-cache --progress=dot:binary -o "$SECMEC_CACHE"/wget.out $2 "$1"
# Now we finish the dialog process running on the backgroundkill -3 "$(cat $SECMEC_CACHE/dialog.pid)"
# Clean up the messrm -rf "$SECMEC_CACHE"/wget.outrm -rf "$SECMEC_CACHE"/dialog.pid
# Restore the terminal back to it's normal state, since# dialog --tailboxbg messes everything upreset
WGET_STATUS="$?"return "$WGET_STATUS"
66
}
############################# Kernel related functions #############################
## Creates a list with the available kernel sources## This function creates a list with the kernel sources found on the# system on the file pointed by $SECMEC_KERNEL_SOURCES_LIST. It will# search SECMEC_KERNEL_SOURCES_DIR for directories named linux-* and# check the makefile of each of those directories to get the name of # the kernel version contained in it.#### Usage:## check_available_kernel_sources#### Return codes:## 0-N: Number of available kernel sources### Internal Variables:## $KERNEL_SOURCES: Number of kernel sources found on the system# $AVAILABLE_KERNEL_SOURCE: Possible kernel source directory# $AVAILABLE_KERNEL_SOURCE_VERSION: Version of the kernel source# pointed by $AVAILABLE_KERNEL_SOURCE#### Misc:## Author: Tiago "Salvador" Souza# Date: 09/11/2006### Changelog:## 11/11/2006 by Tiago "Salvador" Souza: Changed the hardcoded# kernel source's directory patch (/usr/src) by the# SECMEC_KERNEL_SOURCES_DIR variablecheck_available_kernel_sources (){
local KERNEL_SOURCESlocal AVAILABLE_KERNEL_SOURCElocal AVAILABLE_KERNEL_SOURCE_VERSION
# Clean the previous kernel sources listcat /dev/null > "$SECMEC_KERNEL_SOURCES_LIST"
# Make sure the KERNEL_SOURCES variable isn't null, otherwise# if there are no kernel sources available on the system bash# will complain about a null return errorKERNEL_SOURCES="0"
# Create a temp list with the possible kernel source # directories
67
ls "$SECMEC_KERNEL_SOURCES_DIR" 2> /dev/null | grep linux- \| tr --delete "/" > "$SECMEC_KERNEL_SOURCES_LIST.temp"
# Check the entries on the temp list for real kenel source# directoresfor AVAILABLE_KERNEL_SOURCE in $(cat
"$SECMEC_KERNEL_SOURCES_LIST.temp")do
# Get the kernel version from the MakefileAVAILABLE_KERNEL_SOURCE_VERSION="$(head -4
$SECMEC_KERNEL_SOURCES_DIR/$AVAILABLE_KERNEL_SOURCE/Makefile 2> /dev/null | grep ^VERSION | tr --delete " " | cut --delimiter="=" --field=2).$(head -4 $SECMEC_KERNEL_SOURCES_DIR/$AVAILABLE_KERNEL_SOURCE/Makefile 2> /dev/null | grep ^PATCHLEVEL | tr --delete " " | cut --delimiter="=" --field=2).$(head -4 $SECMEC_KERNEL_SOURCES_DIR/$AVAILABLE_KERNEL_SOURCE/Makefile 2> /dev/null | grep ^SUBLEVEL | tr --delete " " | cut --delimiter="=" --field=2)$(head -4 $SECMEC_KERNEL_SOURCES_DIR/$AVAILABLE_KERNEL_SOURCE/Makefile 2> /dev/null | grep ^EXTRAVERSION | tr --delete " " | cut --delimiter="=" --field=2)"
# If no version information was found, then probably# it's not a real kernel source directory so jump to# the next iterationif [ "$AVAILABLE_KERNEL_SOURCE_VERSION" == "" ]then
continuefi
# Increment the number of real kernel sources found(( KERNEL_SOURCES++ ))
# Create an entry on the list real kernel listecho "$KERNEL_SOURCES"
linux-"$AVAILABLE_KERNEL_SOURCE_VERSION" "$AVAILABLE_KERNEL_SOURCE" >> "$SECMEC_KERNEL_SOURCES_LIST"
done
# Clean up the messrm -rf "$SECMEC_KERNEL_SOURCES_LIST.temp"
# Return the number of kernel sources foundreturn "$KERNEL_SOURCES"
}
## Shows 2.6 kernel souces list and downloads the selected one## This function shows the list of 2.6 kernel sources from # www.kernel.org, downloads the selected one and uncompresses it. # If any errors occur or the user hit's cancel on the kernel# selection it returns 255.#### Usage:## show_official_kernel_sources
68
## Just select a kernel version and wait for the download to finish#### Return codes:## 0-254: Number of available kernel sources# 255: Download error or Cancel### Internal Variables:## $SELECTED_KERNEL_VALUE: Number of the selected kernel on the kernel# sources list# $SELECTED_KERNEL_NAME: File name of the selected kernel on the# kernel sources list#### Misc:## Author: Tiago "Salvador" Souza# Date: 11/11/2006### Changelog:##show_official_kernel_sources (){
local SELECTED_KERNEL_VALUElocal SELECTED_KERNEL_NAME
# First we clean the previous kernel sources listcat /dev/null > "$SECMEC_OFFICIAL_KERNEL_SOURCE_LIST"
# Download the list of available kernelsdownload_files "Downloading kernel list from www.kernel.org,
please wait." \"http://www.kernel.org/pub/linux/kernel/v2.6/" \"--no-directories --output-
document=$SECMEC_OFFICIAL_KERNEL_SOURCE_LIST.html"
# Return to the caller if the download did not succeedif [ ! "$?" == 0 ]then
error_screen "Download of the kernel versions list from www.kernel.org failed. Check your network connection settings"
return 255fi
# Now we perform several adjustments to the kernel sources# list. There are probably better ways of doing this, this# was the way I found, maybe someday this can be made more# efficienttac "$SECMEC_OFFICIAL_KERNEL_SOURCE_LIST.html" \
| fgrep -v .sign | fgrep .bz2| fgrep linux- \| cut --delimiter=">" --field="2" \| cut --delimiter="<" --field="1" >
"$SECMEC_OFFICIAL_KERNEL_SOURCE_LIST.temp"
rm -rf "$SECMEC_OFFICIAL_KERNEL_SOURCE_LIST.html"
69
cat -n "$SECMEC_OFFICIAL_KERNEL_SOURCE_LIST.temp" | tr --delete " " \
| tr \\t " " > "$SECMEC_OFFICIAL_KERNEL_SOURCE_LIST"
rm -rf "$SECMEC_OFFICIAL_KERNEL_SOURCE_LIST.temp"
# Present the kernel selection list to the usernumbered_menu_from_file_screen "Choose a kernel verstion to
download" \"$SECMEC_OFFICIAL_KERNEL_SOURCE_LIST" \"" "" "Download" "" "" \"0" "40" "5"
# Save his choice's valueSELECTED_KERNEL_VALUE="$?"
# If the user hitted the cancel button, return to the callerif [ "$SELECTED_KERNEL_VALUE" == 255 ]then
return 255fi
# Translate that choice to a file nameSELECTED_KERNEL_NAME="$(cat "$SECMEC_OFFICIAL_KERNEL_SOURCE_LIST"
\| grep "^$SELECTED_KERNEL_VALUE " \| cut --delimiter=" " --field=2)"
# Download the selected kerneldownload_files_with_progress
"http://www.kernel.org/pub/linux/kernel/v2.6/$SELECTED_KERNEL_NAME" \"--no-directories --directory-
prefix=$SECMEC_CACHE"
# If the download failled, inform the user and return to the# callerif [ ! "$?" == 0 ]then
error_screen "Download of $SELECTED_KERNEL_NAME from www.kernel.org failed. Check your network connection settings"
return 255fi
# Uncompress the freshly downloaded kernel sourceinfo_screen "Uncompressing $SELECTED_KERNEL_NAME kernel source.
Please wait"tar -xjf "$SECMEC_CACHE"/"$SELECTED_KERNEL_NAME" -C
"$SECMEC_KERNEL_SOURCES_DIR" 2>> /dev/null
if [ ! "$?" == 0 ]then
error_screen "Failed to unconpress $SELECTED_KERNEL_NAME kernel source."
return 255fi
# Now if everything succeded, return the numeric value of the# freshly downloaded kernelreturn "$SELECTED_KERNEL_VALUE"
}
70
## Shows the available kernel sources to the user## This function shows the kernel sources found on the system. It uses# the check_available_kernel_sources function to generate a list of# the available sources and presents it to the user. The user can# choose any of the available sources or hit the "Download kernel"# to run show_official_kernel_sources and download an official kernel# source. This function will return a positive value with the# selected kernel's entry value on SECMEC_KERNEL_SOURCES_LIST and a# negative value with the downloaded kernel's entry value on# SECMEC_OFFICIAL_KERNEL_SOURCE_LIST, errors will be returned as 255#### Usage:## check_available_kernel_sources#### Return codes:## -255-0: Downloaded kernel's entry value on # SECMEC_OFFICIAL_KERNEL_SOURCE_LIST# 0-254: Selected kernel's entry value on SECMEC_KERNEL_SOURCES_LIST# 255: Error or Cancel### Internal Variables:## $KERNEL_SOURCES: Number of kernel sources found on the system# $AVAILABLE_KERNEL_SOURCE: Possible kernel source directory# $AVAILABLE_KERNEL_SOURCE_VERSION: Version of the kernel source# pointed by $AVAILABLE_KERNEL_SOURCE#### Misc:## Author: Tiago "Salvador" Souza# Date: 11/11/2006### Changelog:## 14/11/2006 by Tiago "Salvador" Souza: Having no kernel source# available no longer makes the functionr return 255, but it# makes it start the download official kernel source procedureshow_available_kernel_sources (){
local SELECTED_KERNELlocal DOWNLOADED_KERNEL
# First generate an up to date available kernel sources listcheck_available_kernel_sources
# If no kernels where found set SELECTED_KERNEL=255 so we can# proceed to download an official kernel source. If there are# available kernel sources, then present them to the userif [ "$?" == 0 ]then
# If no sources where found inform the user and set SELECTEDinfo_screen "No kernel sources were found on your system.
71
Please wait."sleep 3SELECTED_KERNEL="255"
else
numbered_menu_from_file_screen "The kernel versions listed bellow where found in your system. Select the one you want to use or hit the \"Download kernel\" button to select an official kernel source to download from www.kernel.org" \
"$SECMEC_KERNEL_SOURCES_LIST" \"" "" "Choose" \"Download kernel" "" "15" \"60" "3"
# Save the selected kernel valueSELECTED_KERNEL="$?"
fi
# Check if the user choosed to download an official kernel# source, if so, call show_official_kernel_sources. Notice# That there's a small bug here, well, not really a bug,# since it's just the way dialog works, but if the user# hits <ESC> on the previous screen it will also return# 255 and start the official kernel sources download.# Anyway, we need a way to tell the difference between# a downloaded kernel and one available on the system, so# since bash only allows a single numeric return we will# return negative values for downloaded kernelsif [ "$SELECTED_KERNEL" == "255" ]then
show_official_kernel_sources
DOWNLOADED_KERNEL="$?"
# Check if the user choosed to cancelif [ "$DOWNLOADED_KERNEL" == "255" ]then
return 255fi
# Return the downloaded kernel source entry number# with a - signreturn "-$DOWNLOADED_KERNEL"
fi
# Return the selected kernel sourcereturn "$SELECTED_KERNEL"
}
## Configures an option in the selected kernel configuration file### This function sets the configuration parameter passed in $1 on the# kernel .config file in the kernel source directory passed in $2# with the value passed in $3. By default, if the variable $4 is not
72
# set (or set to "y"), it substitutes the value of "# CONFIG_$1 is # not set" to CONFIG_$1=$3, if $4 is different than "y", it bypasses# the check and appends CONFIG_$1=$3 to the end of the .config file.# This is necessary in order to make options which are not mentioned# on the .config file by default to be set. The configuration option# named in $1 must must come exactly as in the kernel, without the # CONFIG_ part, for instance, to enable the CONFIG_EXT2_FS option # $1 must be EXT2_FS. Note that $2 should be only the directory name# as it uses $SECMEC_KERNEL_SOURCES_DIR/ as a directory prefix.#### Usage:## set_kernel_config "kernel config option" "kernel source address" \# "config value" "check kernel .config"## All parameters but $4 are mandatory. $4's default value is "y"# which makes it check if the passed kernel option is available on# the kernel source before adding it. Generally that's what you want,# but some kernel options don't appear on the default kernel config# option, if so, disable this check.#### Return codes:## 0: Ok, no errors# Any other code: Error#### Internal Variables:## $1 -> Kernel configuration parameter to be set# $2 -> Kernel source directory# $3 -> Value for the configuration parameter to be set to# $4 -> Check configuration switch, "y" by default.#### Misc:## Author: Tiago "Salvador" Souza# Date: 11/11/2006### Changelog:### 16/11/2006 by Tiago "Salvador" Souza: Fixed a bug that made the# cconfig set fail if check was enabled.set_kernel_config (){
if [ ! "$(grep ^CONFIG_$1= $SECMEC_KERNEL_SOURCES_DIR/$2/.config)" ] && [ "${4:-y}" == "y" ]
thensed "s/# CONFIG_$1 is not set/CONFIG_$1=$3/"
"$SECMEC_KERNEL_SOURCES_DIR/$2"/.config > "$SECMEC_KERNEL_SOURCES_DIR/$2"/.config.new
mv "$SECMEC_KERNEL_SOURCES_DIR/$2"/.config.new "$SECMEC_KERNEL_SOURCES_DIR/$2"/.config
elseif [ ! "$(grep ^CONFIG_$1=
$SECMEC_KERNEL_SOURCES_DIR/$2/.config)" ]
73
thenecho CONFIG_"$1"="$3" >>
"$SECMEC_KERNEL_SOURCES_DIR/$2"/.configfi
fireturn "$?"
}
## Compile kernel### This function compiles the kernel source passed in $1 and shows the# compilation progress to the user. This function return's make's# status code#### Usage:## make_kernel "kernel source directory" "make options" "back title"# "window title" "extra dialog parameters"## Only $1 is mandatory. It must contain the kernel's directory name# placed on $SECMEC_KERNEL_SOURCES_DIR. Use $2 to pass make options,# like "oldconfig" "defconfig" "modules" "modules_install". If# oldconfig is used as make option, then we use the "yes" command to# make make (that sounded odd) use all the default options to the# remaining unset options.#### Return codes:## 0: Ok, no errors# Any other code: Error#### Internal Variables:## $1 -> Kernel source directory# $2 -> Make option# $3 -> Back title# $4 -> Window title# $4 -> Extra dialog's parameters# $MAKE_STATUS -> Make's exit status code#### Misc:## Author: Tiago "Salvador" Souza# Date: 13/11/2006### Changelog:##make_kernel (){
local MAKE_STATUS
# First let's create some necessary temporary files, the# first one will recieve wget's output and the second one
74
# will hold dialog's pid, it's necessary since dialog will# run on background and we will need this information to be# able to finish it.cat /dev/null > "$SECMEC_CACHE"/make.outcat /dev/null > "$SECMEC_CACHE"/dialog.pid
"$DIALOG" --backtitle "${3:-$SECMEC_BACK_TITLE}" \--title "${4:-$MEC_NAME}" --no-kill $5 \--tailboxbg "$SECMEC_CACHE"/make.out \15 75 2> "$SECMEC_CACHE"/dialog.pid
if [ ! "$2" == "oldconfig" ]then
make $2 -C "$SECMEC_KERNEL_SOURCES_DIR/$1" 2> "$SECMEC_CACHE"/make.out 1>&2
elseyes "" | make oldconfig -C "$SECMEC_KERNEL_SOURCES_DIR/$1"
2> "$SECMEC_CACHE"/make.out 1>&2fi
# Save make's exit statusMAKE_STATUS="$?"
# Now we finish the dialog process running on the backgroundkill -3 "$(cat $SECMEC_CACHE/dialog.pid)"
# Clean up the messrm -rf "$SECMEC_CACHE"/make.outrm -rf "$SECMEC_CACHE"/dialog.pid
# Restore the terminal back to it's normal state, since# dialog --tailboxbg messes everything upreset
return "$MAKE_STATUS"
}
########################### Mecs related functions ###########################
## Creates list with the available security mechanisms## This function will search for *.mec files with executable# permission in $SECMEC_MECS_DIR, then it checks if the# MEC_SHORT_NAME variable is defined in it, if so, it adds the script# to $SECMEC_MECS_LIST in the following format:#### Usage:## available_mecs#### Return codes:## 0-255: Number of mecs found
75
#### Internal Variables:## MECS_FILES -> Possible mec scripts# MECS_SHORT_NAME -> A Mec script's short name#### Misc:## Author: Tiago "Salvador" Souza# Date: 11/11/2006### Changelog:##available_mecs (){
local MECS_FILESlocal MECS_SHORT_NAME
# First, let's clear previously existing mecs listcat /dev/null > "$SECMEC_MECS_LIST"
# Expliclity create the TOTAL_MECS variableTOTAL_MECS=0
# Now let's create the list of valid script filesfor MECS_FILES in "$SECMEC_MECS_DIR"/*.mecdo
# Test if the script file is not executable, if not# continue to the next fileif [ ! -x "$MECS_FILES" ]then
continuefi
# Get the mec's short name and make sure it has no# spaces or backslashes in itMEC_SHORT_NAME="$(fgrep MEC_SHORT_NAME "$MECS_FILES" \
| cut --delimiter="=" --field=2 \| tr --delete [:space:] \| tr --delete "\"")"
# Check if the variable was defined on the previous# step, if not, continue to the next fileif [ "$MEC_SHORT_NAME" == "" ]then
continuefi
# Add to the total mecs count(( TOTAL_MECS++ ))
# Now we add the script to the SECMEC_MECS_LIST fileecho "$TOTAL_MECS" "$MEC_SHORT_NAME" "$MECS_FILES" >>
"$SECMEC_MECS_LIST"done
return "$TOTAL_MECS"
76
}
## Shows the list of available mecs## This functions shows a screen with the available mec installation# scripts. It first runs the available_mecs function to generate an# up to date list and then presents it to the user for selection. It# returns 255 if the user hits the Cancel button or if no mecs are#found by the available_mecs function#### Usage:## list_available_mecs#### Return codes:## 0-254: Selected mec's entry value on $SECMEC_MECS_LIST# 255: Error or Cancel#### Internal Variables:## MEC_CHOICE -> Entry of the security mechanism selected by the user# on $SECMEC_MECS_LIST#### Misc:## Author: Tiago "Salvador" Souza# Date: 11/11/2006### Changelog:##list_available_mecs (){
local MEC_CHOICE
# First generate a list with the available mechanismsavailable_mecs
# Check if there are mecs to installif [ "$?" == "0" ]then
error_screen "No security mechanisms found on your system. Press \"OK\" to return to the main menu" \
"" "Error"fi
# Present the list of available mecs to the usernumbered_menu_from_file_screen "Select the security mechanism to
be installed" \"$SECMEC_MECS_LIST" "" \"Available security mechanisms" \"Install" "Cancel" "" \"15" "60" "3"
77
# Save his choiceMEC_CHOICE="$?"
# Check if the user choosed to cancel, if so, return to the# main_menuif [ "$MEC_CHOICE" == "255" ]then
main_menufi
# Run the selected script and let the show go on. $(cat "$SECMEC_MECS_LIST" | grep "^$MEC_CHOICE" \| cut --delimiter=" " --field=3)
}
78
APÊNDICE B: CÓDIGO FONTE ./ETC/SECMEC/ROOTKITHUNTER.MEC
#!/bin/bash############ Rootkit-Hunter 1.2.8 installer mechanism for SecMec. Rootkit-Hunter# along with it's licensing information can be found at the following# address: http://www.rootkit.nl/projects/rootkit_hunter.html## SecMec can be found at http://secmec.sourceforge.net### Copyright (C) 2006 Tiago "Salvador" Souza <ts.salvadorATgmailDOTcom>### This file is part of SecMec.## SecMec is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License version 2 # published by the Free Software Foundation.## SecMec is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with SecMec; if not, write to the Free Software# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA##########
###################################### Mec's Variables Definitions ######################################MEC_NAME="Rootkit Hunter Installer"MEC_SHORT_NAME="Rootkit-Hunter"MEC_CONFIGDIR="rootkithunter"
####################### Script Start #######################
# Create the needed cache directories in case they don't existif [ ! -d "$SEC_MEC_CACHE/$MEC_CONFIGDIR" ]then
mkdir -p "$SECMEC_CACHE"/"$MEC_CONFIGDIR"fi
# Confirm if the user wants to install Rootkit Hunter, if he does # not, return to the list of available mecs.confirmation_screen "This assistant will try to install Rootkit-Hunter 1.2.8 from http://www.rootkit.nl/projects/rootkit_hunter.html. Please note that by choosing \"Yes\" you will also be accepting Rootkit-Hunter's license. Do you wish to continue?"
79
if [ ! "$?" == 0 ]then
list_available_mecsfi
# If automode isn't enabled, use interactive modeif [ "$SECMEC_AUTO_MODE" == "" ]then
# Download Root Kit Hunterdownload_files "Downloading Root Kit Hunter 1.2.8 from
http://www.rootkit.nl/, please wait." \"http://downloads.rootkit.nl/rkhunter-1.2.8.tar.gz" \"--no-directories --directory-
prefix=$SECMEC_CACHE/$MEC_CONFIGDIR"
# Check if the download failedif [ ! "$?" == "0" ]then
error_screen "Download of Rootkit-Hunter 1.2.8 failed, please check your network connection. Returning to the Main Menu."
main_menufi
# Uncompress the big tarballinfo_screen "Uncompressing Rootkit-Hunter 1.2.8 installer. Please
wait"tar -xzf "$SECMEC_CACHE/$MEC_CONFIGDIR/rkhunter-1.2.8.tar.gz" -C
"$SECMEC_CACHE/$MEC_CONFIGDIR/"
# Check if the uncompression failedif [ ! "$?" == "0" ]then
error_screen "Failed to uncompress Rootkit-Hunter 1.2.8. Please check if you have enough permission to access and write to $SECMEC_CACHE/$MEC_CONFIGDIR directory. Returning to the Main Menu."
main_menufi
# Go to Rootkit-Hunter's installer directory. The installer # needs to be run from the same directory it's located
cd "$SECMEC_CACHE/$MEC_CONFIGDIR/"rkhunter
# Install itinfo_screen "Installing Rootkit-Hunter 1.2.8. Please wait."./installer.sh > /dev/null
# Return to the main menu if the installation failed.if [ ! "$?" == "0" ]then
error_screen "Failed to install Root Kit Hunter 1.2.8. Returning to the Main Menu."
main_menufi
# return to where we where beforecd -
80
# Inform the user of success and return to the main menusuccess_screen "Root Kit Hunter 1.2.8 installation succeeded. To
use it run \"rkhunter\" as root. Hit \"Ok\" to return to the Main Menu."main_menu
elseecho "Automode not available yet"
fi
81
APÊNDICE C: CÓDIGO FONTE ./ETC/SECMEC/ROOTPLUG.MEC
#!/bin/bash############ Linux Kernel Root-Plug installer mechanism for SecMec. Root-Plug is# a part of the Linux Kernel, which can be found, along with it's# licensing information at http://www.kernel.org## SecMec can be found at http://secmec.sourceforge.net### Copyright (C) 2006 Tiago "Salvador" Souza <ts.salvadorATgmailDOTcom>### This file is part of SecMec.## SecMec is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License version 2 # published by the Free Software Foundation.## SecMec is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with SecMec; if not, write to the Free Software# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA##########
###################################### Mec's Variables Definitions ######################################MEC_NAME="Root Plug Installer"MEC_SHORT_NAME="Root-Plug"MEC_CONFIGDIR="rootplug"
# This little function sets the kernel configuration parameters# needed by Root Plugrootplug_kernel_config (){
set_kernel_config "MODULES" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "MODULE_UNLOAD" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "MODULE_KMOD" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "EXT3_FS" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "REISERFS_FS" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "JFS_FS" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "XFS_FS" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "ARCH_HAS_HCD" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "ARCH_HAS_OHCI" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "ARCH_HAS_EHCI" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "USB" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "SYSFS" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "SECURITY" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "SECURITY_ROOTPLUG" "$KERNEL_CHOICE_NAME" "m"
82
}
####################### Script Start #######################
# Create the needed cache directories in case they don't existif [ ! -d "$SEC_MEC_CACHE/$MEC_CONFIGDIR" ]then
mkdir -p "$SECMEC_CACHE"/"$MEC_CONFIGDIR"fi
# Confirm if the user wants to install rootplug, if he does not,# return to the list of available mecs.confirmation_screen "This assistant will try to install the Root-Plug kernel module and select an USB device to be used as \"Root-Plug\". This device will need to be present on the system in order to perform any super-user operations. Do you wish to continue?"
if [ ! "$?" == 0 ]then
list_available_mecsfi
# If automode isn't enabled, use interactive modeif [ "$SECMEC_AUTO_MODE" == "" ]then
# Let the user select a kernel to useshow_available_kernel_sources
KERNEL_CHOICE_VALUE="$?"
# If the KERNEL_CHOICE_VALUE has a negative value it means# the user downloaded a kernelif [ "$KERNEL_CHOICE_VALUE" -lt 0 ]then
# Remove the minus sign from KERNEL_CHOICE_VALUEKERNEL_CHOICE_VALUE=${KERNEL_CHOICE_VALUE#-*}KERNEL_WAS_DOWNLOADED=y
fi
# If the kernel was downloaded them we need to perform some# changes to get the kernel's directory name rightif [ "$KERNEL_WAS_DOWNLOADED" == "y" ]then
KERNEL_CHOICE_NAME="$(cat $SECMEC_OFFICIAL_KERNEL_SOURCE_LIST \
| grep "^$KERNEL_CHOICE_VALUE " \| cut --delimiter=" " --field=2)"
KERNEL_CHOICE_NAME="${KERNEL_CHOICE_NAME%*.tar.bz2}"
elseKERNEL_CHOICE_NAME="$(cat $SECMEC_KERNEL_SOURCES_LIST \
| grep "^$KERNEL_CHOICE_VALUE " \| cut --delimiter=" " --field="3")"
fi
# Check if there's a kernel config file already available, if
83
# not create a default oneif [ ! -e
"$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config ]then
make_kernel "$KERNEL_CHOICE_NAME" "defconfig"
# If this step failed, return to the main menu# because it is unlikely anything else will work.if [ ! "$?" == "0" ]then
error_screen "Failed to generate default kernel configuration file. Returning to Main Menu."
main_menu
fi
fi
# Check if the currently running kernel has it's kernel# configuration file available, if so, check if the user# want's to use it on the kernel to be compiled. If it fails# to use the running kernel's configuration, it will fallback# to the previous oneif [ -e /proc/config.gz ]then
confirmation_screen "The kernel configuration file from $RUNNING_KERNEL was found on /proc/config.gz. Do you wish to use it?"
if [ "$?" == "0" ]then
cp /proc/config.gz "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME" 2> /dev/null
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongif [ ! "$?" == "0" ]then
RUNNING_KERNEL_CONFIG="1" figunzip
"$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/config.gz 2> /dev/null
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongif [ ! "$?" == "0" ]then
RUNNING_KERNEL_CONFIG="1" fi
cp "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config.orig 2> /dev/null
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongif [ ! "$?" == "0" ]
84
thenRUNNING_KERNEL_CONFIG="1"
fi
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongmv --force
"$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/config "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config 2> /dev/null
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongif [ ! "$?" == "0" ]then
RUNNING_KERNEL_CONFIG="1" fi
chmod 660 "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config 2> /dev/null
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongif [ ! "$?" == "0" ]then
RUNNING_KERNEL_CONFIG="1" fi
fi
if [ "$RUNNING_KERNEL_CONFIG" == "1" ]then
error_screen "Failed to use configuration file from $RUNNING_KERNEL. Using previously existing one"
mv --force "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config.orig "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config 2> /dev/null
fi
fi
# Set the needed kernel parametersrootplug_kernel_config
# Prepare the kernel to compile using the modified# configuration filemake_kernel "$KERNEL_CHOICE_NAME" "oldconfig"
# If this step failed, return to the main menu# because it is unlikely anything else will work.if [ ! "$?" == "0" ]then
error_screen "Failed to prepare configuration faile for compilation. Returning to Main Menu."
main_menu
fi
# Add version information to the Makefile if it isn't present
85
if [ ! "$(head -5 "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/Makefile | grep rootplug )" ]
thensed "s/EXTRAVERSION =*/&-rootplug/"
"$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/Makefile > "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/Makefile.new 2> /dev/null
mv --force "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/Makefile.new "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/Makefile 2> /dev/null
fi
# Compile the kernelmake_kernel "$KERNEL_CHOICE_NAME"
# If this step failed, return to the main menu# because it is unlikely anything else will work.if [ ! "$?" == "0" ]then
error_screen "Failed to compile the kernel. Returning to Main Menu."
main_menu
fi
# Compile the kernel modulesmake_kernel "$KERNEL_CHOICE_NAME" "modules"
# If this step failed, return to the main menu# because it is unlikely anything else will work.if [ ! "$?" == "0" ]then
error_screen "Failed to to compile the kernel modules. Returning to Main Menu."
main_menu
fi
# Install the kernel modulesmake_kernel "$KERNEL_CHOICE_NAME" "modules_install"
# If this step failed, return to the main menu# because it is unlikely anything else will work.if [ ! "$?" == "0" ]then
error_screen "Failed install the kernel modules. Make sure you are running this program as root. Returning to Main Menu."
main_menu
fi
# Copy the compiled kernel to the /boot directorycp --force
""$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/arch/i386/boot/bzImage" "/boot/vmlinuz-${KERNEL_CHOICE_NAME##linux-}-rootplug" 2> /dev/null
# Check if the system failed to copy the kernel to /bootif [ ! "$?" == "0" ]then
86
error_screen "Failed to copy kernel to /boot directory. Make sure you are running this program as root. Returning to Main Menu."
main_menu
fi
# Check if there is an entry for this kernel on lilo yetcat /etc/lilo.conf | grep vmlinuz-${KERNEL_CHOICE_NAME##linux-}-
rootplug > /dev/null
# If there isn't add an entry named rootplugif [ ! "$?" == "0" ]then
echo "image = /boot/vmlinuz-${KERNEL_CHOICE_NAME##linux-}-rootplug" >> /etc/lilo.conf
echo "label = RootPlug" >> /etc/lilo.confecho "root=$(cat /etc/fstab | fgrep " / " | tr -s [:space:]
| tr -s \t | cut --delimiter=" " --field=1)" >> /etc/lilo.confecho "read-only" >> /etc/lilo.conf
/sbin/lilo > /dev/null
# Check if the the program failed to add the new# kernel's entry to lilo.confif [ ! "$?" == "0" ]then
error_screen "Failed to add the new kernel to Lilo. Make sure you are running this program as root. Returning to Main Menu."
main_menu
fi
fi
# Inform the user that he is about to see a possibly very big# and confusing list of USB devicesmessage_screen "The next screen will show the list of USB devices
currently on your system (including the USB controler), look at it carefully and write down the \"Vendor\" and \"ProdID\" numbers."
# We need to copy the devices list, because since it's on# /proc it doesn't have EOF in it, cp /proc/bus/usb/devices "$SECMEC_CACHE/$MEC_CONFIGDIR"
# Show the devices listtext_screen "$SECMEC_CACHE/$MEC_CONFIGDIR"/devices
# Leave no traces behindrm -rf "$SECMEC_CACHE/$MEC_CONFIGDIR"/devices
# Ask the user to input the Vendor's ID valueVENDOR_ID="$(dialog --backtitle "$SECMEC_BACK_TITLE" --title
"$MEC_NAME" --ok-label "OK" --cancel-label "Cancel" --clear --cr-wrap --stdout --inputbox "Enter Vendor value" 0 0)"
# If no value was passed, inform the user and return to the# callerif [ "$?" == "" ]then
error_screen "No Vendor ID selected, returning to main menu"
87
main_menufi
# Ask the user to input the Prod's ID valuePROD_ID="$(dialog --backtitle "$SECMEC_BACK_TITLE" --title
"$MEC_NAME" --ok-label "OK" --cancel-label "Cancel" --clear --cr-wrap --stdout --inputbox "Enter ProdID value" 0 0)"
# If no value was passed, inform the user and return to the# callerif [ "$?" == "" ]then
error_screen "No Product ID selected, returning to main menu"
main_menufi
# Inform the user where the Root Plug's initialization# command will be placedmessage_screen "Root Plug's module load values are going to be
added to /etc/rc.d/rc.local. The values are: modprobe root_plug vendor_id=0x$VENDOR_ID product_id=0x$PROD_ID. Comment it out in case you don't want to use Root Plug anymore"
# Add RootPlug's module with the choosen values to #/etc/rc.d/rc.localcat "modprobe root_plug vendor_id=0x$VENDOR_ID
product_id=0x$PROD_ID" >> /etc/rc.d/rc.local
# Inform the user of successsuccess_screen "Root Plug installation succeeded. Reboot your
system and choose the RootPlug entry to test if everything is working."
elseecho Automode not available yet
fi
88
APÊNDICE D: CÓDIGO FONTE ./ETC/SECMEC/SELINUX.MEC
#!/bin/bash############ Linux SE-Linux installer mechanism for SecMec. SE-Linux is# a part of the Linux Kernel, which can be found, along with it's# licensing information at http://www.kernel.org## SecMec can be found at http://secmec.sourceforge.net### Copyright (C) 2006 Tiago "Salvador" Souza <ts.salvadorATgmailDOTcom>### This file is part of SecMec.## SecMec is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License version 2 # published by the Free Software Foundation.## SecMec is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with SecMec; if not, write to the Free Software# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA##########
###################################### Mec's Variables Definitions ######################################MEC_NAME="SE-Linux Installer"MEC_SHORT_NAME="SE-Linux"MEC_CONFIGDIR="selinux"
# This little function sets the kernel configuration parameters# needed by SE-Linuxselinux_kernel_config (){
set_kernel_config "MODULES" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "MODULE_UNLOAD" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "MODULE_KMOD" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "NET" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "INET" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "AUDIT" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "AUDITSYSCALL" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "EXT2_FS" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "EXT2_FS_XATTR" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "EXT2_FS_POSIX_ACL" "$KERNEL_CHOICE_NAME" "y"
"n"set_kernel_config "EXT2_FS_SECURITY" "$KERNEL_CHOICE_NAME" "y" "n"set_kernel_config "EXT2_FS_XIP" "$KERNEL_CHOICE_NAME" "y"
89
set_kernel_config "EXT3_FS" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "EXT3_FS_XATTR" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "EXT3_FS_POSIX_ACL" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "EXT3_FS_SECURITY" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "SYSFS" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "SECURITY" "$KERNEL_CHOICE_NAME" "y"set_kernel_config "SECURITY_CAPABILITIES" "$KERNEL_CHOICE_NAME"
"y" "n"set_kernel_config "SECURITY_NETWORK" "$KERNEL_CHOICE_NAME" "y" "n"set_kernel_config "SECURITY_SELINUX" "$KERNEL_CHOICE_NAME" "y" "n"set_kernel_config "SECURITY_SELINUX_BOOTPARAM"
"$KERNEL_CHOICE_NAME" "y" "n"set_kernel_config "SECURITY_SELINUX_BOOTPARAM_VALUE"
"$KERNEL_CHOICE_NAME" "1" "n"set_kernel_config "SECURITY_SELINUX_DEVELOP" "$KERNEL_CHOICE_NAME"
"y" "n"set_kernel_config "SECURITY_SELINUX_AVC_STATS"
"$KERNEL_CHOICE_NAME" "y" "n"set_kernel_config "SECURITY_SELINUX_CHECKREQPROT_VALUE"
"$KERNEL_CHOICE_NAME" "1" "n"
}
####################### Script Start #######################
# Create the needed cache directories in case they don't existif [ ! -d "$SEC_MEC_CACHE/$MEC_CONFIGDIR" ]then
mkdir -p "$SECMEC_CACHE"/"$MEC_CONFIGDIR"fi
# Confirm if the user wants to install SE-Linux, if he does not,# return to the Main Menu.confirmation_screen "This assistant will try to install SE-Linux modules and packages on your system, do you wish to continue?"
if [ ! "$?" == 0 ]then
main_menufi
# If automode isn't enabled, use interactive modeif [ "$SECMEC_AUTO_MODE" == "" ]then
# Let the user select a kernel to useshow_available_kernel_sources
KERNEL_CHOICE_VALUE="$?"
# If the KERNEL_CHOICE_VALUE has a negative value it means# the user downloaded a kernelif [ "$KERNEL_CHOICE_VALUE" -lt 0 ]then
KERNEL_CHOICE_VALUE=${KERNEL_CHOICE_VALUE#-*}KERNEL_WAS_DOWNLOADED=y
90
fi
# If the kernel was downloaded then we need to perform some# changes to get the kernel's directory name rightif [ "$KERNEL_WAS_DOWNLOADED" == "y" ]then
KERNEL_CHOICE_NAME="$(cat $SECMEC_OFFICIAL_KERNEL_SOURCE_LIST | grep "^$KERNEL_CHOICE_VALUE " | cut --delimiter=" " --field=2)"
KERNEL_CHOICE_NAME="${KERNEL_CHOICE_NAME%*.tar.bz2}"
elseKERNEL_CHOICE_NAME="$(cat $SECMEC_KERNEL_SOURCES_LIST | grep
"^$KERNEL_CHOICE_VALUE " | cut --delimiter=" " --field="3")"fi
# Check if there's a kernel config file already available, if# not create a default oneif [ ! -e
"$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config ]then
make_kernel "$KERNEL_CHOICE_NAME" "defconfig"
fi
# Check if the currently running kernel has it's kernel# configuration file available, if so, check if the user# want's to use it on the kernel to be compiledif [ -e /proc/config.gz ]then
if [ "$?" == "0" ]then
cp /proc/config.gz "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME" 2> /dev/null
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongif [ ! "$?" == "0" ]then
RUNNING_KERNEL_CONFIG="1" figunzip
"$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/config.gz 2> /dev/null
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongif [ ! "$?" == "0" ]then
RUNNING_KERNEL_CONFIG="1" fi
cp "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config.orig 2> /dev/null
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongif [ ! "$?" == "0" ]
91
thenRUNNING_KERNEL_CONFIG="1"
fi
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongmv --force
"$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/config "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config 2> /dev/null
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongif [ ! "$?" == "0" ]then
RUNNING_KERNEL_CONFIG="1" fi
chmod 660 "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config 2> /dev/null
# Set RUNNING_KERNEL_CONFIG to 1 in case# anything goes wrongif [ ! "$?" == "0" ]then
RUNNING_KERNEL_CONFIG="1" fi
fi
if [ "$RUNNING_KERNEL_CONFIG" == "1" ]then
error_screen "Failed to use configuration file from $RUNNING_KERNEL. Using previously existing one"
mv --force "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config.orig "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/.config 2> /dev/null
fi
fi
# Set the needed kernel parametersselinux_kernel_config
# Prepare the kernel to compile using the modified# configuration filemake_kernel "$KERNEL_CHOICE_NAME" "oldconfig"
# If this step failed, return to the main menu# because it is unlikely anything else will work.if [ ! "$?" == "0" ]then
error_screen "Failed to prepare configuration faile for compilation. Returning to Main Menu."
main_menu
fi
92
# Add version information to the Makefile if it isn't presentif [ ! "$(head -5
"$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/Makefile | grep selinux )" ]
thensed "s/EXTRAVERSION =*/&-selinux/"
"$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/Makefile > "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/Makefile.new
mv --force "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/Makefile.new "$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/Makefile
fi
# Compile the kernelmake_kernel "$KERNEL_CHOICE_NAME"
# If this step failed, return to the main menu# because it is unlikely anything else will work.if [ ! "$?" == "0" ]then
error_screen "Failed to compile the kernel. Returning to Main Menu."
main_menu
fi
# Compile the kernel modulesmake_kernel "$KERNEL_CHOICE_NAME" "modules"
# If this step failed, return to the main menu# because it is unlikely anything else will work.if [ ! "$?" == "0" ]then
error_screen "Failed to to compile the kernel modules. Returning to Main Menu."
main_menu
fi
# Install the kernel modulesmake_kernel "$KERNEL_CHOICE_NAME" "modules_install"
# If this step failed, return to the main menu# because it is unlikely anything else will work.if [ ! "$?" == "0" ]then
error_screen "Failed install the kernel modules. Make sure you are running this program as root. Returning to Main Menu."
main_menu
fi
# Copy the compiled kernel to the /boot directorycp --force
""$SECMEC_KERNEL_SOURCES_DIR"/"$KERNEL_CHOICE_NAME"/arch/i386/boot/bzImage" "/boot/vmlinuz-${KERNEL_CHOICE_NAME##linux-}-selinux"
# Check if the system failed to copy the kernel to /bootif [ ! "$?" == "0" ]
93
thenerror_screen "Failed to copy kernel to /boot directory. Make
sure you are running this program as root. Returning to Main Menu."main_menu
fi
# Check if there is an entry for this kernel on lilo yetcat /etc/lilo.conf | grep vmlinuz-${KERNEL_CHOICE_NAME##linux-}-
selinux > /dev/null
# If there isn't add an entry named SeLinuxif [ ! "$?" == "0" ]then
echo "image = /boot/vmlinuz-${KERNEL_CHOICE_NAME##linux-}-selinux" >> /etc/lilo.conf
echo "label = SeLinux" >> /etc/lilo.confecho "root=$(cat /etc/fstab | fgrep " / " | tr -s [:space:]
| tr -s \t | cut --delimiter=" " --field=1)" >> /etc/lilo.confecho "read-only" >> /etc/lilo.conf
/sbin/lilo > /dev/null
# Check if the the program failed to add the new# kernel's entry to lilo.confif [ ! "$?" == "0" ]then
error_screen "Failed to add the new kernel to Lilo. Make sure you are running this program as root. Returning to Main Menu."
main_menu
fifi
# Download the SE-Linux packages for slackware.# TODO: Compile the packages instead of using a pre made onedownload_files_with_progress
"http://projects.dimensionalstorm.net/selinux/selinux_all-slack-pkgs.tar.bz2" \
"--no-directories --directory-prefix=$SECMEC_CACHE/$MEC_CONFIGDIR"
if [ ! "$?" == "0" ]then
error_screen "Download of SE-Linux applications failed. Returning to the main screen"
main_menufi
# Uncompress the big tarballinfo_screen "Uncompressing SE-Linux applications. Please wait"tar -xjf "$SECMEC_CACHE/$MEC_CONFIGDIR/selinux_all-slack-
pkgs.tar.bz2" -C "$SECMEC_CACHE/$MEC_CONFIGDIR/"
# Check if the uncompression failedif [ ! "$?" == "0" ]then
error_screen "Failed to uncompress SE-Linux applications. Please check if you have enough permission to access and write to
94
$SECMEC_CACHE/$MEC_CONFIGDIR directory. Returning to the Main Menu."main_menu
fi
info_screen "Installing SE-Linux applications . Please wait"installpkg "$SECMEC_CACHE/$MEC_CONFIGDIR/selinux/pkgs/*tgz" 2>
/dev/null 1>&2
# Return to the main menu if the installation failed.if [ ! "$?" == "0" ]then
error_screen "SE-Linux installation applications failed. Returning to the main screen"
main_menufi
success_screen "SE-Linux installation succeeded. Reboot your system and choose the SeLinux entry to test if everything is working. Hit \"Ok\" to return to the Main Menu."else
echo Automode not available yetfi
95
APÊNDICE E: CÓDIGO FONTE ./USR/SBIN/SECMEC
#!/bin/bash############ SecMec's main program.## SecMec can be found at http://secmec.sourceforge.net### Copyright (C) 2006 Tiago "Salvador" Souza <ts.salvadorATgmailDOTcom>### This file is part of SecMec.## SecMec is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License version 2 # published by the Free Software Foundation.## SecMec is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with SecMec; if not, write to the Free Software# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA##########
################################################ SecMec's Global Variables Definitions ################################################SECMEC_PROGRAM_NAME="SecMec"SECMEC_PROGRAM_VERSION="0.8"SECMEC_BACK_TITLE="$SECMEC_PROGRAM_NAME - $SECMEC_PROGRAM_VERSION"SECMEC_CACHE="../../var/cache/secmec"SECMEC_ERROR_LOG="../../var/log/secmec"SECMEC_MECS_DIR="../../etc/secmec/mecs"SECMEC_BASE_DIR="../../etc/secmec"SECMEC_FUNCTIONS_DIR="../../etc/secmec/functions"SECMEC_MECS_LIST="$SECMEC_CACHE/available_mecs.txt"SECMEC_KERNEL_SOURCES_LIST="$SECMEC_CACHE/available_kernel_sources.txt"SECMEC_OFFICIAL_KERNEL_SOURCE_LIST="$SECMEC_CACHE/official_kernel_source_list.txt"SECMEC_KERNEL_SOURCES_DIR="../../usr/src"PGP_KEY_SERVER="wwwkeys.pgp.net"RUNNING_KERNEL="$(uname -a | cut --delimiter=" " --field=3)"DIALOG=dialog#SECMEC_PROGRAM_DEPS="dialog grep fgrep kill wget cut sort head cat mkdir tar make gcc installpkg sed bash"SECMEC_PROGRAM_DEPS="dialog grep fgrep kill wget cut sort head cat mkdir tar make gcc sed bash"
###################################### SecMec's Included Functions ######################################
96
. "$SECMEC_FUNCTIONS_DIR"/secmec-base-1.0
# SecMec's about screen, along with it's licensing information.about_screen (){
"$DIALOG" --backtitle "$SECMEC_BACK_TITLE" \--title "About SecMec" --ok-label "OK" \--cr-wrap --msgbox "SecMec is a security Mechanisms installer for
Linux. Currently it works well on Slackware Linux and Slackware based distros. \n\n SecMec is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 published by the Free Software Foundation. \n SecMec is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \n See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SecMec; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA" "0" "0"
# If the user hitted ctrl+c or <esc> exit.if [ ! "$?" == "0" ]then
exit 0fi
main_menu
}
# SecMec's menu.main_menu (){
MAIN_MENU_CHOICE=$("$DIALOG" --backtitle "$SECMEC_BACK_TITLE" \--title "SecMec: Security Mechanisms Installer" \--ok-label "Choose" --cancel-label "Exit" \--clear --cr-wrap --stdout \--menu "Welcome to SecMec, a security mechanisms
installer for Linux. Please choose your destination" \0 0 0 \"Install" "Install Security Mechanisms" \"About" "About SecMec" \"Exit" "Exit SecMec")
case "$MAIN_MENU_CHOICE" in"Install") list_available_mecs;;"About") about_screen;;"Exit") exit;;*) exit 0;;
esac}
####################### Script Start #######################
# Bash needs to be used for this program to work. Exit if the running# shell ain't BASH.
97
if [ "$BASH" = "" ]then
echo "ERROR: You need to use GNU's Bourne Again SHell (bash) to run this program. Aborting."
exit 1fi
# This program needs to be run as root for it to work.if [ "$EUID" != 0 ]then
echo "ERROR: You must be root to run $SECMEC_PROGRAM_NAME. Aborting."
exit 1fi
# Binaries dependency checking. Taken from Dropling Gnome 2.16# installer. Dropline Gnome can be found at the following address# http://www.dropline.net/gnomeSECMEC_PROGRAM_DEPS_NOT_MET="0"for SECMEC_DEP in $SECMEC_PROGRAM_DEPSdo
"$SECMEC_DEP" --version &> /dev/nullif [ "$?" == "127" ]then
echo $"$SECMEC_DEP not found. Please install it before running $SECMEC_PROGRAM_NAME."
SECMEC_PROGRAM_DEPS_NOT_MET="1"fi
done
if [ "$SECMEC_PROGRAM_DEPS_NOT_MET" == "1" ]then
echo "Some necessary programs where not found by the installer. Please install them before running $SECMEC_PROGRAM_NAME."
exit 1fi
main_menu
98
AUTORIZAÇÃO
Autorizo a reprodução e/ou divulgação total ou parcial da presente obra, por qualquer meio
convencional ou eletrônico, desde que citada a fonte.
Nome do autor: Tiago Almeida Barboza de Souza
Assinatura do autor: ____________________________
Instituição: Universidade Tecnológica Federal do Paraná
Local: Curitiba, Paraná
Endereço: Rua Mario Bueno Sobrinho, 1391-1
E-mail: [email protected]
99