dt

package module
v0.0.0-...-b49bb9e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2021 License: MIT Imports: 18 Imported by: 0

README

Transparência de Domínios

Este é o repositório de Transparência de Domínios (Domain Transparency - DT). Transparência de Domínios é um protocolo proposto com o objetivo de facilitar a identificação confiável de certificados TLS fraudulentos.

As instruções para a demonstração dessa ferramenta podem ser encontradas aqui.

Instalação da Ferramenta

Para instalar a ferramenta num sistema Linux, siga as instruções abaixo:

  1. Instale em seu sistema a linguagem Go, versão 1.16 ou superior, conforme as instruções oficiais de instalação. Instale também o programa git (necessário para executar o git clone no próximo passo).

  2. Para compilar a ferramenta, execute os seguintes comandos no terminal:

    git clone https://github.com/fernandokm/transparencia-de-dominios
    cd transparencia-de-dominios
    go build github.com/fernandokm/transparencia-de-dominios/cmd/run-server
    go build github.com/fernandokm/transparencia-de-dominios/cmd/track-domain
    

    Esses comandos instalarão todas as bibliotecas de Go necessárias e gerarão dois binários (run-server e track-domain) no diretório atual.

  3. Por último, crie uma pasta "config" no diretório atual:

    mkdir config
    

    Essa pasta será utilizada para armazenar as chaves pública e privada do servidor.

Observação: as instruções dadas acima compilam a ferramenta com suporte aos logs públicos de CT conhecidos pelo Google. Para utilizar outros logs, é necessário modificar o arquivo util/loglist.json e recompilar a ferramenta.

Execução do Servidor de DT

  1. Primeiramente, escolha um ou mais logs que devem ser rastreados, e.g. nessa lista ou nessa lista.

  2. Copie as URLs dos logs escolhidos e execute o servidor com o seguinte comando:

    ./run-server --log https://link-do-log-1 --log https://link-do-log-2 ...
    

    Para indicar que um log ainda não está em operação, utilize o prefixo t: antes da URL, onde t é um número, para indicar que o log só entrará em operação após t segundos e, portanto, que ele só deve ser adicionado ao mapa nesse instante:

    ./run-server --log t1:https://link-do-log-1 --log t2:https://link-do-log-2 ...
    

    Note que a ordem dos logs no comando é a ordem que aparecerá na árvore fonte. Portanto, logs que entrarão em operação por último devem aparecer no final do comando.

    Além de --log, as seguintes flags podem ser úteis:

    • --ip IP: configura o endereço IP do servidor (valor padrão: 127.0.0.1)
    • --port: configura a porta utilizada pelo servidor (valor padrão: 8021)
    • --mmd MMD: configura o atraso máximo de mesclagem (valor padrão: 1m0s, i.e., 1 minuto)
    • --public_key ARQUIVO e --private_key ARQUIVO: indicam os arquivos em que as chaves pública e privada devem ser salvas (valores padrão: config/publickey.pem e config/privatekey.pem)
    • --sth_interval INTERVALO: indica o intervalo de tempo entre duas verificações subsequentes de um mesmo log de CT (as verificações são o momento em que o servidor verifica se há novos certificados no log) (valor padrão: 5s, i.e., 5 segundos)

O servidor pode demorar um pouco para começar a funcionar, pois o mapa só pode começar a operar quando todos os certificados dos logs forem recuperados.

Rastreamento de Domínios

O rastreamento de domínios pode ser feito tanto de forma manual, por meio da API disponibilizada, quanto por meio da ferramenta track-domain.

Rastreamento Manual

Uma API é disponibilizada em 127.0.0.1:8021. Para verificar que ela está funcionando, tente carregar a url http://127.0.0.1:8021/dt/v1/get-smh, que deve retornar um objeto JSON com a seguinte estrutura, correspondendo à última cabeça assinada de mapa disponível:

{
  "timestamp": 1111111111,
  "map_size": 111,
  "map_root_hash": "xxx",
  "source_tree_root_hash": "xxx",
  "source_log_revisions": [
    {
      "tree_size": 11,
      "root_hash": "xxx"
    }
  ],
  "map_head_signature": "xxx"
}

Uma lista completa de todas as consultas possíveis pode ser vista aqui. Por exemplo, para obter a raiz de uma árvore de domínio, pode-se utilizar a url http://127.0.0.1:8021/dt/v1/get-domain-root-and-proof?domain_map_size=TAMANHO_DO_MAPA&domain_name=NOME_DO_DOMINIO com valores apropriados para TAMANHO_DO_MAPA e NOME_DO_DOMINIO.

Rastreamento Automático

O programa track-domain simplifica o processo de verificação dos certificados de um domínio. Ele rastreia um mapa de domínios e notifica o usuário de quaisquer novos certificados em um dado domínio.

Para utilizá-lo, basta executar:

./track-domain --domain DOMINIO-DE-INTERESSE

Por exemplo, ao rastrear o domínio example.com, uma saída possível é:

2021/07/10 19:07:00 Domain tracker started...
2021/07/10 19:07:14 New SMH: timestamp=1630344141, size=41, rootHash=eedbed0a..., sourceRootHash=02d0d331..., sourceLogCount=1
2021/07/10 19:07:14 New certificate for example.com:
  SHA-256 Fingerprint: 200FCAFA767C8450ECE644879C062A0CDF52240FE05BB7EB284611C3AEF3EC2E
  Leaf Index: 40

Essa saída indica que às 19:07:14, foi identificado uma nova cabeça de mapa e que essa cabeça inclui um novo certificado para o domínio example.com.

Documentation

Index

Constants

View Source
const Version = 1

Version is the Domain Transparency version

Variables

This section is empty.

Functions

func StartWorker

func StartWorker(ctx context.Context, dm *DomainMap, config WorkerConfig) (chan<- WorkerTransaction, <-chan struct{})

StartWorker starts a new worker for this domain tree. There may only be one running worker per domain tree at any time and there should be no manual modifications while a worker is running. To ensure that a worker has exited after cancelling the context, wait for the <-chan struct{} to be closed.

Types

type DomainMap

type DomainMap struct {
	// contains filtered or unexported fields
}

A DomainMap maps domains to CT certificates.

func NewDomainMap

func NewDomainMap(signer crypto.Signer) *DomainMap

NewDomainMap creates a new DomainMap. The domain map starts with unsigned an empty SMH.

func (*DomainMap) AddDomainTree

func (dm *DomainMap) AddDomainTree(tree *DomainTree) error

AddDomainTree adds a new domain tree to this domain map. This means only that the tree can be found through dm.GetDomainTree(). In order to get this domain tree included in the sparse merkle tree, call dm.UpdateDomainTreeRoot().

func (*DomainMap) CheckAndPublishSMH

func (dm *DomainMap) CheckAndPublishSMH(root []byte, mapSize uint64, sourceRevisions []LogRevision) error

CheckAndPublishSMH checks the specified rootand publishes a new SMH.

func (*DomainMap) EntryToDomainTreeIndex

func (dm *DomainMap) EntryToDomainTreeIndex(entry DomainTreeEntry, domain string) (uint64, error)

EntryToDomainTreeIndex returns the index of a DomainTreeEntry in the domain tree for the specified domain (after domain name normalization).

Returns an error if the domain tree does not exist or if the specified certificate could not be found in the domain tree. has no such certificate.

func (*DomainMap) GetDomainTree

func (dm *DomainMap) GetDomainTree(domain string) (*DomainTree, error)

GetDomainTree returns the domain tree associated with the specified domain, after domain name normalization.

func (*DomainMap) GetDomainTreeRoot

func (dm *DomainMap) GetDomainTreeRoot(root []byte, domain string) (*DomainTreeRoot, error)

GetDomainTreeRoot returns the STH for the specified domain tree at the specified map head, after domain name normalization.

func (*DomainMap) GetLatestSMH

func (dm *DomainMap) GetLatestSMH() *SignedMapHead

GetLatestSMH returns the latest SMH, or nil if the tree is empty.

func (*DomainMap) GetProofForDomain

func (dm *DomainMap) GetProofForDomain(root []byte, domain string) (DomainProof, error)

GetProofForDomain returns a (non-)containment proof for the specified domain.

func (*DomainMap) GetSMH

func (dm *DomainMap) GetSMH(treeSize uint64) *SignedMapHead

GetSMH returns the specified SMH, or nil if the specified SMH does not exist.

func (*DomainMap) GetSourceTree

func (dm *DomainMap) GetSourceTree() *SourceTree

GetSourceTree returns this map's SourceTree

func (*DomainMap) HasDomain

func (dm *DomainMap) HasDomain(root []byte, domain string) (bool, error)

HasDomain checks if this map has the specified key.

func (*DomainMap) PublicKey

func (dm *DomainMap) PublicKey() crypto.PublicKey

PublicKey returns this map's public key.

func (*DomainMap) UpdateDomainTreeRoot

func (dm *DomainMap) UpdateDomainTreeRoot(root []byte, domain string, treeSize uint64) ([]byte, error)

UpdateDomainTreeRoot updates the DomainTreeRoot for the specified domain and returns the new map root.

type DomainProof

type DomainProof struct {
	Proof    [][]byte
	LeafHash []byte
}

A DomainProof proves the (non-)containment of a node.

type DomainTree

type DomainTree struct {
	DomainName string
	// contains filtered or unexported fields
}

A DomainTree stores certificates for a given domain, similarly to a CT log.

func NewDomainTree

func NewDomainTree(domain string) (*DomainTree, error)

NewDomainTree creates a new domain tree

func (*DomainTree) AddEntry

func (dtree *DomainTree) AddEntry(entry DomainTreeEntry) uint64

AddEntry adds an entry to the tree and returns its current leaf count.

func (*DomainTree) EntryToDomainTreeIndex

func (dtree *DomainTree) EntryToDomainTreeIndex(entry DomainTreeEntry) (uint64, error)

EntryToDomainTreeIndex returns the index of a DomainTreeEntry in this domain tree.

Returns an error if the specified entry could not be found in this domain tree.

func (DomainTree) GetAuditProof

func (t DomainTree) GetAuditProof(treeSize, leafIndex uint64) ([][]byte, error)

GetAuditProof returns a proof of containment for the specified index, for the given tree size.

func (DomainTree) GetConsistencyProof

func (t DomainTree) GetConsistencyProof(firstSize, secondSize uint64) [][]byte

GetConsistencyProof returns a consistency proof between two trees identified by their sizes.

func (*DomainTree) GetEntries

func (dtree *DomainTree) GetEntries(start, end uint64) ([]DomainTreeEntry, error)

GetEntries returns the entries in the specified interval, inclusive.

func (*DomainTree) GetEntryAndProof

func (dtree *DomainTree) GetEntryAndProof(treeSize, leafIndex uint64) (DomainTreeEntry, [][]byte, error)

GetEntryAndProof returns the specified entry and its proof.

func (*DomainTree) GetRoot

func (dtree *DomainTree) GetRoot(treeSize uint64) (*DomainTreeRoot, error)

GetRoot retrieves the DomainTreeRoot with the specified size.

type DomainTreeEntry

type DomainTreeEntry struct {
	LogIndex         uint64
	CertificateIndex uint64
}

A DomainTreeEntry points to a certificate in a CT log. The LogIndex refers to the index of the CT log in the domain map's source tree.

type DomainTreeRoot

type DomainTreeRoot struct {
	DomainTreeSize     uint64
	DomainTreeRootHash ct.SHA256Hash
}

A DomainTreeRoot stores information about a domain tree.

type LogRevision

type LogRevision struct {
	TreeSize uint64        `json:"tree_size"`
	RootHash ct.SHA256Hash `json:"root_hash"`
}

LogRevision is used in MapHead to identify a source log revision

type MapHead

type MapHead struct {
	Version   ct.Version `json:"-" tls:"maxval:255"`
	Timestamp uint64     `json:"timestamp"`
	MapSize   uint64     `json:"map_size"`

	MapRootHash        ct.SHA256Hash `json:"map_root_hash"`
	SourceTreeRootHash ct.SHA256Hash `json:"source_tree_root_hash"`

	SourceLogRevisions []LogRevision `json:"source_log_revisions" tls:"minlen:40,maxlen:16777215"` // 40 = size(LogRevision), 16777215=2^24-1 (419k elements)
}

MapHead is the structure which is signed to produce the SignedMapHead.

type SignedMapHead

type SignedMapHead struct {
	MapHead
	MapHeadSignature []byte `json:"map_head_signature"`
}

An SignedMapHead (SMH) certifies the root of a domain map.

type SourceTree

type SourceTree struct {
	// contains filtered or unexported fields
}

A SourceTree lists the source logs tracked by a DomainMap.

func NewSourceTree

func NewSourceTree() *SourceTree

NewSourceTree creates a new source tree

func (*SourceTree) AddEntry

func (st *SourceTree) AddEntry(entry logid.LogID) uint64

AddEntry adds an entry to the tree and returns its current leaf count.

func (SourceTree) GetAuditProof

func (t SourceTree) GetAuditProof(treeSize, leafIndex uint64) ([][]byte, error)

GetAuditProof returns a proof of containment for the specified index, for the given tree size.

func (SourceTree) GetConsistencyProof

func (t SourceTree) GetConsistencyProof(firstSize, secondSize uint64) [][]byte

GetConsistencyProof returns a consistency proof between two trees identified by their sizes.

func (*SourceTree) GetEntries

func (st *SourceTree) GetEntries(start, end uint64) ([]logid.LogID, error)

GetEntries returns the entries in the specified interval, inclusive.

func (*SourceTree) GetEntryAndProof

func (st *SourceTree) GetEntryAndProof(treeSize, leafIndex uint64) (logid.LogID, [][]byte, error)

GetEntryAndProof returns the specified entry and its proof.

func (SourceTree) GetRoot

func (t SourceTree) GetRoot(treeSize uint64) ([]byte, error)

GetRoot returns the tree root at the specified size

type WorkerConfig

type WorkerConfig struct {
	BufferSize   int
	UpdatePeriod time.Duration
	MMD          time.Duration // This value should be slightly less than the actual MMD
}

type WorkerTransaction

type WorkerTransaction struct {
	LogIndex               uint64
	LogID                  logid.LogID
	LogRevision            LogRevision
	NewCertificatesIndices map[string][]uint64
}

A WorkerTransaction specified the actions to be taken by the worker.

Directories

Path Synopsis
cmd
demo

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL