terça-feira, 27 de setembro de 2016

Trusted Platform Module 1 - TPM


 1. O que é?

     O Trusted Platform Module é um módulo de segurança que visa entre outras funções garantir a integridade do hardware, do software e dele mesmo. O TPM é um chip que vem acoplado às placas mãe dos computadores modernos, entretanto ele tem total autonomia para trabalhar fora da placa, dependendo apenas da alimentação elétrica.

      Nesse artigo vou abordar especificamente como se trabalhar com garantia de integridade do hardware e do software, o TPM é um módulo muito poderoso com diversas possibilidades, em outra ocasião falo sobre todas elas. 

2. Benefícios do TPM
  •             Criptografia com assinatura do hardware
            Os modelos mais atuais de criptografia são feitos com softwares que criam uma chave pública e uma chave privada com a assinatura do próprio software. Através do chip TPM em comunicação com o Sistema Operacional, é possível tirar proveito de alguns recursos de segurança avançados do chip, o que incluí a capacidade de criar chaves de segurança com a assinatura do hardware, o hardware passa a ser a chave privada, e o que for criptografado com a chave pública gerada pelo TPM só poderá ser descriptografado no mesmo conjunto de hardware em que foi gerada a chave pública (explico no próximo item o motivo de só ser descriptografada no "conjunto de hardware")

  •            Garantir a integridade tanto do Hardware como do Software

            O chip atesta que o hardware e/ou o software não tenha/m sido/s alterado/s, isso ocorre através de medições próprias do chip que são chamadas de PCRs (uma espécie de hash do próprio chip), esses PCRs são geradas junto com uma senha na primeira vez que o chip é habilitado, os PCRs  são únicos para cada hardware e para o conjunto de arquivos e/ou software que será garantido pelo chip. Para uma maior segurança os PCRs são armazenados no próprio chip TPM e não no HD, o chip só pode ser resetado com a chave do proprietário do chip. Com essa função podemos garantir a integridade dos softwares mantidos, é uma boa função para servidores que possuem arquivos não voláteis.           
  •             Multiplataformas
            O chip é compatível com Sistemas operacionais Windows e Linux, a Microsoft já utiliza alguns recursos do chip através do BitLocker (apenas). Em sistemas Linux foi possível em laboratório explorar todos os recursos do chip, mas ainda é necessário compilar os binários e instalar algumas bibliotecas. Trabalhando em conjunto com o TrustedGrub (um grub criado para iteragir com o chip), foi possível gerar interferência no boot do equipamento caso o hardware ou o software medido através dos PCRs sejam violados.

  •             O TPM Possuí uma ISO que atesta sua eficácia
            O módulo de segurança TPM, é amparado pela ISO/IEC 11889 (http://www.iso.org/iso/catalogue_detail.htm?csnumber=50970), que assegura que o TPM é um módulo que garante a segurança para plataformas de computação em geral.

  •             Tecnologia pouco explorada
            Apesar dos benefícios não é uma tecnologia muito explorada no mercado de segurança digital, mas uma tecnologia muito visada estudada em universidades em todo mundo. Tive a oportunidade de trabalhar em uma pesquisa para implementação do módulo TPM em uma instituição nacional, o que indica que a procura por esse tipo de garantia de segurança e integridade vem crescendo.

3. Possibilidades com o TPM
  •             Bloqueio do BOOT do computador em caso de fraude
            Essa possibilidade só se mostrou possível trabalhando com o Trusted Grub, caso os PCRs gerados no equipamento sejam diferentes dos que estão armazenados no chip, ou seja, caso o software medido ou o hardware sofram algum tipo de intervenção, há a possibilidade de bloquear o boot do equipamento e exibir uma mensagem para o usuário.


4. Como funcionam os PCRs?

            Após instalar todos os pacotes do módulo TPM e instalar e configurar o trustedgrub (grup especifico para o TPM), teremos acesso as funções do módulo, agora podemos nos apropriar do módulo, cadastrar nossa senha e gerar os PCRs, segue gráfico de utilização dos PCRs:








        Observe na imagem que o PCR-13 está com status "not used", o PCR-13 é o PCR responsável por medir itens de software, neste artigo será explicado como fazer o PCR-13 funcionar.



4. Mão na massa!!


         Primeiro vou deixar uma lista com os códigos e descrição dos códigos gerados pelo chip:

TPM V1.2 Error Code Cheat Sheet
Error V1.1B (Dec) (Hex) Description

 
TPM_SUCCESS O 0 0x 00000000 Successful completion of the operation
TPM_AUTHFAIL O 1 0x 00000001 Authentication failed
TPM_BADINDEX O 2 0x 00000002 The index to a PCR, DIR or other register is incorrect
TPM_BAD_PARAMETER O 3 0x 00000003 One or more parameter is bad
TPM_AUDITFAILURE O 4 0x 00000004 An operation completed successfully but the auditing of that operation failed.
TPM_CLEAR_DISABLED O 5 0x 00000005 The clear disable flag is set and all clear operations now require physical access
TPM_DEACTIVATED O 6 0x 00000006 The TPM is deactivated
TPM_DISABLED O 7 0x 00000007 The TPM is disabled
TPM_DISABLED_CMD O 8 0x 00000008 The target command has been disabled
TPM_FAIL O 9 0x 00000009 The operation failed
TPM_BAD_ORDINAL O 10 0x 0000000A The ordinal was unknown or inconsistent
TPM_INSTALL_DISABLED O 11 0x 0000000B The ability to install an owner is disabled
TPM_INVALID_KEYHANDLE O 12 0x 0000000C The key handle can not be interpreted
TPM_KEYNOTFOUND O 13 0x 0000000D The key handle points to an invalid key
TPM_INAPPROPRIATE_ENC O 14 0x 0000000E Unacceptable encryption scheme
TPM_MIGRATEFAIL O 15 0x 0000000F Migration authorization failed
TPM_INVALID_PCR_INFO O 16 0x 00000010 PCR information could not be interpreted
TPM_NOSPACE O 17 0x 00000011 No room to load key.
TPM_NOSRK O 18 0x 00000012 There is no SRK set
TPM_NOTSEALED_BLOB O 19 0x 00000013 An encrypted blob is invalid or was not created by this TPM
TPM_OWNER_SET O 20 0x 00000014 There is already an Owner
TPM_RESOURCES O 21 0x 00000015 The TPM has insufficient internal resources to perform the requested action.
TPM_SHORTRANDOM O 22 0x 00000016 A random string was too short
TPM_SIZE O 23 0x 00000017 The TPM does not have the space to perform the operation.
TPM_WRONGPCRVAL O 24 0x 00000018 The named PCR value does not match the current PCR value.
TPM_BAD_PARAM_SIZE O 25 0x 00000019 The paramSize argument to the command has the incorrect value
TPM_SHA_THREAD O 26 0x 0000001A There is no existing SHA-1 thread.
TPM_SHA_ERROR O 27 0x 0000001B The calculation is unable to proceed because the existing SHA-1 thread has already encountered an error.
TPM_FAILEDSELFTEST O 28 0x 0000001C Self-test has failed and the TPM has shutdown.
TPM_AUTH2FAIL O 29 0x 0000001D The authorization for the second key in a 2 key function failed authorization
TPM_BADTAG O 30 0x 0000001E The tag value sent to for a command is invalid
TPM_IOERROR O 31 0x 0000001F An IO error occurred transmitting information to the TPM
TPM_ENCRYPT_ERROR O 32 0x 00000020 The encryption process had a problem.
TPM_DECRYPT_ERROR O 33 0x 00000021 The decryption process did not complete.
TPM_INVALID_AUTHHANDLE O 34 0x 00000022 An invalid handle was used.
TPM_NO_ENDORSEMENT O 35 0x 00000023 The TPM does not a EK installed
TPM_INVALID_KEYUSAGE O 36 0x 00000024 The usage of a key is not allowed
TPM_WRONG_ENTITYTYPE O 37 0x 00000025 The submitted entity type is not allowed
TPM_INVALID_POSTINIT O 38 0x 00000026 The command was received in the wrong sequence relative to TPM_Init and a subsequent TPM_Startup
TPM_INAPPROPRIATE_SIG O 39 0x 00000027 Signed data cannot include additional DER information
TPM_BAD_KEY_PROPERTY O 40 0x 00000028 The key properties in TPM_KEY_PARMs are not supported by this TPM
TPM_BAD_MIGRATION O 41 0x 00000029 The migration properties of this key are incorrect.
TPM_BAD_SCHEME O 42 0x 0000002A The signature or encryption scheme for this key is incorrect or not permitted in this situation.
TPM_BAD_DATASIZE O 43 0x 0000002B The size of the data (or blob) parameter is bad or inconsistent with the referenced key
TPM_BAD_MODE O 44 0x 0000002C A mode parameter is bad, such as capArea or subCapArea for TPM_GetCapability, physicalPresence parameter for TPM_PhysicalPresence, or
migrationType for TPM_CreateMigrationBlob.
TPM_BAD_PRESENCE O 45 0x 0000002D Either the physicalPresence or physicalPresenceLock bits have the wrong value
TPM_BAD_VERSION O 46 0x 0000002E The TPM cannot perform this version of the capability
TPM_NO_WRAP_TRANSPORT 47 0x 0000002F The TPM does not allow for wrapped transport sessions
TPM_AUDITFAIL_UNSUCCESSFUL 48 0x 00000030 TPM audit construction failed and the underlying command was returning a failure code also
TPM_AUDITFAIL_SUCCESSFUL 49 0x 00000031 TPM audit construction failed and the underlying command was returning success
TPM_NOTRESETABLE 50 0x 00000032 Attempt to reset a PCR register that does not have the resettable attribute
TPM_NOTLOCAL 51 0x 00000033 Attempt to reset a PCR register that requires locality and locality modifier not part of command transport
TPM_BAD_TYPE 52 0x 00000034 Make identity blob not properly typed
TPM_INVALID_RESOURCE 53 0x 00000035 When saving context identified resource type does not match actual resource
TPM_NOTFIPS 54 0x 00000036 The TPM is attempting to execute a command only available when in FIPS mode
TPM_INVALID_FAMILY 55 0x 00000037 The command is attempting to use an invalid family ID
TPM_NO_NV_PERMISSION 56 0x 00000038 The permission to manipulate the NV storage is not available
TPM_REQUIRES_SIGN 57 0x 00000039 The operation requires a signed command
TPM_KEY_NOTSUPPORTED 58 0x 0000003A Wrong operation to load an NV key
TPM_AUTH_CONFLICT 59 0x 0000003B NV_LoadKey blob requires both owner and blob authorization
TPM_AREA_LOCKED 60 0x 0000003C The NV area is locked and not writable
TPM_BAD_LOCALITY 61 0x 0000003D The locality is incorrect for the attempted operation
TPM_READ_ONLY 62 0x 0000003E The NV area is read only and can’t be written to
TPM_PER_NOWRITE 63 0x 0000003F There is no protection on the write to the NV area
TPM_FAMILYCOUNT 64 0x 00000040 The family count value does not match
TPM_WRITE_LOCKED 65 0x 00000041 The NV area has already been written to
TPM_BAD_ATTRIBUTES 66 0x 00000042 The NV area attributes conflict
TPM_INVALID_STRUCTURE 67 0x 00000043 The structure tag and version are invalid or inconsistent
TPM_KEY_OWNER_CONTROL 68 0x 00000044 The key is under control of the TPM Owner and can only be evicted by the TPM Owner.
TPM_BAD_COUNTER 69 0x 00000045 The counter handle is incorrect
TPM_NOT_FULLWRITE 70 0x 00000046 The write is not a complete write of the area
TPM_CONTEXT_GAP 71 0x 00000047 The gap between saved context counts is too large
TPM_MAXNVWRITES 72 0x 00000048 The maximum number of NV writes without an owner has been exceeded
TPM_NOOPERATOR 73 0x 00000049 No operator AuthData value is set
TPM_RESOURCEMISSING 74 0x 0000004A The resource pointed to by context is not loaded
TPM_DELEGATE_LOCK 75 0x 0000004B The delegate administration is locked
TPM_DELEGATE_FAMILY 76 0x 0000004C Attempt to manage a family other then the delegated family
TPM_DELEGATE_ADMIN 77 0x 0000004D Delegation table management not enabled
TPM_TRANSPORT_NOTEXCLUSIVE 78 0x 0000004E There was a command executed outside of an exclusive transport session
TPM_OWNER_CONTROL 79 0x 0000004F Attempt to context save a owner evict controlled key
TPM_DAA_RESOURCES 80 0x 00000050 The DAA command has no resources available to execute the command
TPM_DAA_INPUT_DATA0 81 0x 00000051 The consistency check on DAA parameter inputData0 has failed.
TPM_DAA_INPUT_DATA1 82 0x 00000052 The consistency check on DAA parameter inputData1 has failed.
TPM_DAA_ISSUER_SETTINGS 83 0x 00000053 The consistency check on DAA_issuerSettings has failed.
TPM_DAA_TPM_SETTINGS 84 0x 00000054 The consistency check on DAA_tpmSpecific has failed.
TPM_DAA_STAGE 85 0x 00000055 The atomic process indicated by the submitted DAA command is not the expected process.
TPM_DAA_ISSUER_VALIDITY 86 0x 00000056 The issuer’s validity check has detected an inconsistency
TPM_DAA_WRONG_W 87 0x 00000057 The consistency check on w has failed.
TPM_BAD_HANDLE 88 0x 00000058 The handle is incorrect
TPM_BAD_DELEGATE 89 0x 00000059 Delegation is not correct
TPM_BADCONTEXT 90 0x 0000005A The context blob is invalid
TPM_TOOMANYCONTEXTS 91 0x 0000005B Too many contexts held by the TPM
TPM_MA_TICKET_SIGNATURE 92 0x 0000005C Migration authority signature validation failure
TPM_MA_DESTINATION 93 0x 0000005D Migration destination not authenticated
TPM_MA_SOURCE 94 0x 0000005E Migration source incorrect
TPM_MA_AUTHORITY 95 0x 0000005F Incorrect migration authority
TPM_PERMANENTEK 97 0x 00000061 Attempt to revoke the EK and the EK is not revocable
TPM_BAD_SIGNATURE 98 0x 00000062 Bad signature of CMK ticket
TPM_NOCONTEXTSPACE 99 0x 00000063 There is no room in the context list for additional contexts
TPM_RETRY O 2048 0x 00000800 The TPM is too busy to respond to the command immediately, but the command could be resubmitted at a later time.The TPM MAY return
TPM_RETRY for any command at any time.
TPM_NEEDS_SELFTEST 2049 0x 00000801 TPM_ContinueSelfTest has not been run.
TPM_DOING_SELFTEST 2050 0x 00000802 The TPM is currently executing the actions of TPM_ContinueSelfTest because the ordinal required resources that have not been tested.
TPM_DEFEND_LOCK_RUNNING 2051 0x 00000803 The TPM is defending against dictionary attacks and is in some time-out period.






  • Preparando o ambiente
       A instalação foi realizada em um Debian8, utilizando repositórios do Debian7, isso ocorreu pois na ocasião em que o lab foi montado o Debian8 havia acabado de ser lançado e não localizamos todos os pacotes nos repositórios oficiais, seguem os repositórios utilizados:



deb http://archive.debian.org/debian/ lenny main non-free contrib
deb-src http://archive.debian.org/debian/ lenny main non-free contrib
deb http://archive.debian.org/debian-security/ lenny/updates main contrib non-free
deb-src http://archive.debian.org/debian-security/ lenny/updates main contrib non-free
deb http://archive.debian.org/debian-volatile lenny/volatile main contrib non-free
deb-src http://archive.debian.org/debian-volatile lenny/volatile main contrib non-free
deb http://archive.debian.org/debian-backports lenny-backports main contrib non-free
 


Pacotes necessários:

tpm-tools

automake
trousers 

GCC
autoconf  
make
trousers-dbg
tpm-tools-dbg



Para começar a instalação, habilite o módulo TPM no BIOS, localize no BIOS do equipamento o TCG ou TPM e ative.
         No SO é necessário primeiro verificar se o mesmo é compatível com o módulo TPM, para verificar se as bibliotecas estão disponíveis execute o comando:

#ls -la /lib/modules/`uname -r`/kernel/drivers/char/tpm



Bibliotecas necessárias:

A saída do comando anterior deve ser: 

-rw-rr 1 root root 9012 2008-06-18 20:13 tpm_atmel.ko
-rw-rr 1 root root 10960 2008-06-18 20:13 tpm_bios.ko
-rw-rr 1 root root 13440 2008-06-18 20:13 tpm_infineon.ko
-rw-rr 1 root root 20392 2008-06-18 20:13 tpm.ko
-rw-rr 1 root root 10712 2008-06-18 20:13 tpm_nsc.ko
-rw-rr 1 root root 17432 2008-06-18 20:13 tpm_tis.ko

Com o usuário administrador, siga os seguintes passos:
  • Instalação de Pacotes

Instale os pacotes descritos com o comando aptitude install:

#aptitude install tpm-tools automake trousers
#aptitude install trousers-dbg make autoconf gcc   



Módulos TPM

Insira os módulos com os comandos:

#modprobe tpm_bios
#modprobe tpm
#modprobe tpm_tis force=1 interrupts=0







Serviço TCSD no boot
 
  O serviço tcsd é o serviço do trousers, ele deve iniciar junto com o SO, nesta versão, o tcsd está em /usr/sbin/tcsd e pode ser chamado apenas com o comando:
#tcsd

  Em outras versões ele pode estar em /etc/init.d/tcsd ou em /etc/init.d/trousers
  Para que esse serviço inicie junto com o SO, Insira o caminho completo do tcsd no inicio do arquivo: /etc/bash.bashrc

  Edite o arquivo /etc/bash.bashrc
# vi /etc/bash.bashrc
  E insira:
/usr/sbin/tcsd


Se o comando a seguir funcionar, significa que o tcsd está funcionando:



#tpm_version




  Definir senha módulo TPM

 
  ATENÇÃO: A definição de senha só funciona uma vez, se tentar executar a definição de senha novamente será apresentada uma mensagem de erro, caso queira trocar a senha posteriormente, execute o comando tpm_clear, reinicie o equipamento, desabilite o módulo TPM no BIOS e inicie o SO novamente, só então reinicie novamente o sistema, habilite no BIOS o módulo TPM e realize o procedimento para definir senha novamente.

Execute o comando tpm_takeownership e insira a senha logo a seguir:
#tpm_takeownership
Enter owner password: xxxxxx
Confirm password: xxxxxx
Enter SRK password: yyyyyyyy
Confirm password: yyyyyyyy

OBS: Alguns chips fabricados pela IBM possuem uma senha de segurança padrão, ela é 87654321, após a senha padrão de segurança pode-se inserir sua nova senha.

Em seguida execute o comando tpm_createek e insira a senha novamente
#tpm_createek

A mensagem em tela será:
Tspi_TPM_GetPubEndorsementKey failed: 0x00000008 - layer=tpm, code=0008 (8),
                        The TPM target command has been disabled
 Enter owner password:
 Public Endorsement Key:
   Version:   01010000
   Usage:     0x0002 (Unknown)
   Flags:     0x00000000 (!VOLATILE, !MIGRATABLE, !REDIRECTION)
   AuthUsage: 0x00 (Never)
   Algorithm:         0x00000020 (Unknown)
   Encryption Scheme: 0x00000012 (Unknown)
   Signature Scheme:  0x00000010 (Unknown)
   Public Key:
        a71def6a f09b39cb e0e55779 b1e6dfe5 26ca2278 b6fce7cf f1c242c5 545694d8
        1a5804ad 5a3b1d5c c18c3d93 fda2e201 78a86e4e c93e4bb7 e1851eab ca98cbe5
        81c06522 1357777c e0e55779 1bac9e9c 8208f203 f1477705 0317fe2b db233d4d
        a71def6a f09b39cb e0e55779 b1e6dfe5 26ca2278 b6fce7cf f1c242c5 545694d8
        [...]

  Não se preocupe com a mensagem de “TPM target command has been disabled”. Apenas verifique se seu módulo TPM está ativado no BIOS após reiniciar o equipamento novamente
 

Instalando o TrustedGrub

  Realizei o download do TrustedGrub diretamente do site oficial:
 
  Download TrustedGrub
  Para realizar o download via linha de comando utilize:

 
  Após o download descompacte p arquivo:
#tar -xzvf TrustedGRUB-1.1.5.tgz

  Acesse a pasta:
#cd TrustedGRUB-1.1.5/

Observações:
Para realizar o dbug do tGrub, vá até /TrustedGRUB-1.1.5/stage2/Makefile.am e edite:
STAGE2_CFLAGS = $(INCLUDES)
para
STAGE2_CFLAGS = $(INCLUDES) -DDEBUG

  Após fazer isso, é necessário compilar, se já tiver realizado a compilação, deve compilar novamente o TrustedGRUB, remova o arquivo .tar antigo, compacte a pasta inteira que foi alterada, apague a pasta que permaneceu e execute o procedimento de Descompactação e compilação novamente (a seguir).

  Compilação do TrustedGrub
  O script “build_tgruib.sh” faz todo o trabalho de compilação e configuração, para compilar, execute o scritp:
#./build_tgruib.sh

  Com o usuário administrador acesse a pasta Trusted-1.1.5 dentro da atual pasta TrustedGRUB-1.1.5:
#cd TrustedGRUB-1.1.5
Em seguida execute:
#make

#make install

  Configurando o TrustedGrub
  Faça um backup do grub antigo:
#mv /boot/grub /boot/grub_old

  Remova seu grub atual:
#dpkg -r grub

  Considerando que já executou os processos anteriores e que está na pasta do TrustedGRUB, execute os seguintes comandos:

#mkdir /boot/grub
#cp ../default /boot/grub/
#cp /boot/grub_old/menu.lst /boot/grub
#cp stage1/stage1 /boot/grub
#cp stage2/stage2 /boot/grub




  •   Adicionando o checkfile (habilitando pcr-13)

        Gere o sha1 do arquivo que será verificado e encaminhe para o check.file, ex: 
#sha1sum /teste1.file >> /boot/check.file

Dentro do check.file terá algo assim:
edb1cff009e115f7f5f7b4533667a787798832d /test1.file

  Edite o arquivo com o vi para adicionar a localização do hd do arquivo, (veja se está de acordo com seu ambiente), neste exemplo a localização é hd0,0, deixe assim:
edb1cff009e115f7f5f7b4533667a787798832d (hd0,0)/test1.file

Observações:

Certifique-se que após o hash exista um espaço e que no final de cada linha exista um carácter vazio.

  Em seguida edite seu arquivo menu.lst, adicionando a chamada do checkfile
#vi /boot/grub/menu.lst

  Adicione:
checkfile (hd0,0)/boot/check.file

  Seu menu.lst ficará assim:
 title  TrustedGRUB Test
 root  (hd0,0)
 kernel  /boot/vmlinuz-2.6.xx ro quiet splash
 initrd  /boot/initrd.img-2.6.xx
 checkfile (hd0,0)/boot/check.file
 quiet


No ambiente atual, executamos a instalação do grub coforme:
#grub



grub> set prefix=(hd0,0)/boot/grub

grub> root=(hd0,0)

grub> setup=(hd0)

grub> quit



#grub-install /dev/sda
 





Documentações:
https://projects.sirrix.com/trac/trustedgrub/wiki/Documentation







Nenhum comentário:

Postar um comentário