
Footprinting de OSINT opinativo e centrado na organização, inspirado no recon-ng e no Maltego.
Aviso
Este projeto está apenas parcialmente completo e ainda não implementei muitas das funcionalidades descritas no seguinte artigo do blog que fiz: https://penafieljlm.com/2017/07/14/inquisitor/.
O Inquisitor é uma ferramenta simples para coletar informações sobre empresas e organizações através do uso de fontes de Inteligência de Fontes Abertas (OSINT). É fortemente inspirado na forma como Maltego e recon-ng operam, e a ferramenta basicamente reimplementa algumas das funcionalidades dessas ferramentas, mas adiciona uma camada adicional de semântica baseada em opinião sobre os tipos de ativos para criar um fluxo de trabalho fácil de usar.
As principais funcionalidades do Inquisitor incluem:
Todo o conceito do Inquisitor gira em torno da ideia de extrair informações de fontes abertas com base no que já se sabe sobre uma organização alvo. No contexto do Inquisitor, isso é chamado de "transforms". Informações relacionadas também podem ser imediatamente recuperadas de um ativo conhecido com base em metadados também recuperáveis de fontes abertas, como whois e registros de internet.
Os conceitos são discutidos em mais detalhes neste artigo do blog: https://penafieljlm.com/2017/07/14/inquisitor/
Para instalar o Inquisitor, basta clonar o repositório, entrar nele e executar o script de instalação.``` pip install Cython click git clone [email protected]:penafieljlm/inquisitor.git cd inquisitor python setup.py install
## Uso
O Inquisitor tem cinco comandos básicos que incluem `scan`, `status`, `classify`, `dump` e `visualize`.```
usage: inq [-h] {scan,status,classify,dump,visualize} ...
optional arguments:
-h, --help show this help message and exit
command:
{scan,status,classify,dump,visualize}
The action to perform.
scan Search OSINT sources for intelligence based on known
assets belonging to the target.
status Prints out the current status of the specified
intelligence database.
classify Classifies an existing asset as either belonging or
not belonging to the target. Adds a new asset with the
specified classification if none is present.
dump Dumps the contents of the database into a JSON file
visualize Create a D3.js visualization based on the contents of
the specified intelligence database.
No modo de scan, a ferramenta executa todas as transformações disponíveis para todos os ativos que você possui no seu Banco de Dados de Inteligência. Certifique-se de criar Chaves de API para as várias fontes OSINT indicadas abaixo e fornecê-las ao script para que as transformações que usam essas fontes não sejam ignoradas. Além disso, certifique-se de semear seu Banco de Dados de Inteligência com alguns ativos de destino conhecidos e próprios usando o comando classify primeiro, porque se o banco de dados não contiver nenhum ativo próprio, não haverá nada a ser transformado.```
usage: inq scan [-h] [--google-dev-key GOOGLE_DEV_KEY]
[--google-cse-id GOOGLE_CSE_ID]
[--google-limit GOOGLE_LIMIT]
[--shodan-api-key SHODAN_API_KEY]
[--shodan-limit SHODAN_LIMIT]
DATABASE
positional arguments: DATABASE The path to the intelligence database to use. If specified file does not exist, a new one will be created.
optional arguments: -h, --help show this help message and exit --google-dev-key GOOGLE_DEV_KEY Specifies the developer key to use to query Google Custom Search. Visit the Google APIs Console (http://code.google.com/apis/console) to get an API key. If notspecified, the script will simply skip asset transforms that involve Google Search. --google-cse-id GOOGLE_CSE_ID Specifies the custom search engine to query. Visit the Google Custom Search Console (https://cse.google.com/cse/all) to create your own Google Custom Search Engine. If not specified, the script will simply skip asset transforms that involve Google Search. --google-limit GOOGLE_LIMIT The number of pages to limit Google Search to. This is to avoid exhausting your daily quota. --shodan-api-key SHODAN_API_KEY Specifies the API key to use to query Shodan. Log into your Shodan account (https://www.shodan.io/) and look at the top right corner of the page in order to view your API key. If not specified, the script will simply skip asset transforms that involve Shodan. --shodan-limit SHODAN_LIMIT The number of pages to limit Shodan Search to. This is to avoid exhausting your daily quota.
### Status
No modo de status, a ferramenta simplesmente imprime um resumo rápido do status do seu banco de dados de varredura.```
usage: inq status [-h] [-s] DATABASE
positional arguments:
DATABASE The path to the intelligence database to use. If specified
file does not exist, a new one will be created.
optional arguments:
-h, --help show this help message and exit
-s, --strong Indicates if the status will be based on the strong ownership
classification.
No modo Classify, você poderá adicionar manualmente ativos e reclassificar ativos já existentes no Banco de Dados de Inteligência. Você deve usar este comando para semear seu Banco de Dados de Inteligência com ativos alvo conhecidos e de sua propriedade.``` usage: inq classify [-h] [-ar REGISTRANT [REGISTRANT ...]] [-ur REGISTRANT [REGISTRANT ...]] [-rr REGISTRANT [REGISTRANT ...]] [-ab BLOCK [BLOCK ...]] [-ub BLOCK [BLOCK ...]] [-rb BLOCK [BLOCK ...]] [-ah HOST [HOST ...]] [-uh HOST [HOST ...]] [-rh HOST [HOST ...]] [-ae EMAIL [EMAIL ...]] [-ue EMAIL [EMAIL ...]] [-re EMAIL [EMAIL ...]] [-al LINKEDIN [LINKEDIN ...]] [-ul LINKEDIN [LINKEDIN ...]] [-rl LINKEDIN [LINKEDIN ...]] DATABASE
positional arguments: DATABASE The path to the intelligence database to use. If specified file does not exist, a new one will be created.
optional arguments: -h, --help show this help message and exit -ar REGISTRANT [REGISTRANT ...], --accept-registrant REGISTRANT [REGISTRANT ...] Specifies a registrant to classify as accepted. -ur REGISTRANT [REGISTRANT ...], --unmark-registrant REGISTRANT [REGISTRANT ...] Specifies a registrant to classify as unmarked. -rr REGISTRANT [REGISTRANT ...], --reject-registrant REGISTRANT [REGISTRANT ...] Specifies a registrant to classify as rejected. -ab BLOCK [BLOCK ...], --accept-block BLOCK [BLOCK ...] Specifies a block to classify as accepted. -ub BLOCK [BLOCK ...], --unmark-block BLOCK [BLOCK ...] Specifies a block to classify as unmarked. -rb BLOCK [BLOCK ...], --reject-block BLOCK [BLOCK ...] Specifies a block to classify as rejected. -ah HOST [HOST ...], --accept-host HOST [HOST ...] Specifies a host to classify as accepted. -uh HOST [HOST ...], --unmark-host HOST [HOST ...] Specifies a host to classify as unmarked. -rh HOST [HOST ...], --reject-host HOST [HOST ...] Specifies a host to classify as rejected. -ae EMAIL [EMAIL ...], --accept-email EMAIL [EMAIL ...] Specifies a email to classify as accepted. -ue EMAIL [EMAIL ...], --unmark-email EMAIL [EMAIL ...] Specifies a email to classify as unmarked. -re EMAIL [EMAIL ...], --reject-email EMAIL [EMAIL ...] Specifies a email to classify as rejected. -al LINKEDIN [LINKEDIN ...], --accept-linkedin LINKEDIN [LINKEDIN ...] Specifies a LinkedIn Account to classify as accepted. -ul LINKEDIN [LINKEDIN ...], --unmark-linkedin LINKEDIN [LINKEDIN ...] Specifies a LinkedIn Account to classify as unmarked. -rl LINKEDIN [LINKEDIN ...], --reject-linkedin LINKEDIN [LINKEDIN ...] Specifies a LinkedIn Account to classify as rejected.
### Dump
No modo Dump, você poderá extrair o conteúdo do Intelligence Database para um arquivo JSON legível por humanos.```
usage: inq dump [-h] [-j FILE] [-a] DATABASE
positional arguments:
DATABASE The path to the intelligence database to use. If
specified file does not exist, a new one will be
created.
optional arguments:
-h, --help show this help message and exit
-j FILE, --json FILE The path to dump the JSON file to. Overwrites existing
files.
-a, --all Include rejected assets in dump.
No modo de visualização, você poderá adquirir uma visualização hierárquica do Repositório de Inteligência.``` usage: inq visualize [-h] [-l] DATABASE
positional arguments: DATABASE The path to the intelligence database to use. If specified file does not exist, a new one will be created.
optional arguments: -h, --help show this help message and exit -l, --last Simply open the last visualization generated instead of creating a new one.
## Fluxo de Trabalho
Agora que você conhece os recursos básicos do Inquisitor, é hora de aprender como *realmente* usá-lo. O Inquisitor foi projetado com as seguintes etapas em mente:
### Semeadura
Nesta etapa, seu Banco de Dados de Inteligência ainda não possui nada. Teremos que começar de algum lugar, então vá em frente e alimente o banco de dados com ativos que você sabe que pertencem à sua organização alvo. Você pode fazer isso usando o comando `classify`.
### Varredura
Agora que o banco de dados possui ativos conhecidos por pertencer à sua organização alvo. Você pode então prosseguir com a varredura. Você pode fazer isso usando o comando `scan`.
Quando você invoca o comando `scan` no seu Banco de Dados de Inteligência, o Inquisitor executa os métodos `transform` dos ativos classificados como `accepted`. Quando a varredura terminar, você terá mais ativos que podem potencialmente pertencer à sua organização alvo.
Se você não obtiver novos ativos, pode semear seu Banco de Dados de Inteligência com novas informações, ou simplesmente prosseguir para finalizar o processo seguindo para a etapa de Relatório.
### Classificação
Embora o Inquisitor realize a classificação automática de ativos para você, pode acabar perdendo alguns ativos que, de fato, pertencem à sua organização alvo.
Quando isso acontecer, você terá que verificar o conteúdo do banco de dados e classificar manualmente os ativos. Geralmente, você deve prestar atenção aos ativos **Registrant**, pois não há como determinar automaticamente a propriedade para esse tipo de ativo. Além disso, a maioria dos outros tipos de ativos depende da classificação de propriedade dos ativos Registrant para determinar se pertencem ao seu alvo ou não, por isso é definitivamente melhor prestar atenção aos seus ativos Registrant. Além disso, você não acaba com muitos ativos Registrant em primeiro lugar, então não será tão difícil examiná-los.
### Relatório
Você pode gerar uma visualização dos ativos que pertencem à sua organização alvo usando o comando `visualize` ou o comando `dump`.
## Demonstração
Eu tenho vídeos de demonstração da ferramenta em execução no seguinte link: https://drive.google.com/open?id=0B_O70BVu38TRclo5dWRBWkdTTWc
No entanto, não consegui gravar completamente a execução do comando scan, pois meu gravador de tela gratuito só grava até 10 minutos.
## Desenvolvimento
O projeto Inquisitor está organizado no seguinte formato:```
.
|-- README.md
|-- inquisitor
| |-- __init__.py
| |-- assets
| | |-- __init__.py
| | |-- block.py
| | |-- email.py
| | |-- host.py
| | |-- linkedin.py
| | `-- registrant.py
| |-- extractors
| | |-- __init__.py
| | `-- emails.py
| `-- sources
| |-- __init__.py
| |-- google_search.py
| `-- shodan_search.py
|-- inq
|-- report
| `-- index.html
|-- setup.py
`-- tests
|-- __init__.py
`-- test_inq.py
Ele possui três módulos principais chamados assets, extractors e sources. O script principal é chamado inq.
Como desenvolvedor, você estaria principalmente interessado em adicionar novos tipos de ativos ao sistema, então o guia do desenvolvedor se concentraria principalmente nisso.
Antes de passarmos a implementar classes de ativos, primeiro precisamos entender como interagir com o Banco de Dados de Inteligência, pois iremos interagir com ele ao derivar ativos relacionados de nossas classes de ativos.
O código fonte do Banco de Dados de Inteligência está armazenado no arquivo inquisitor/__init__.py. O nome real para o encapsulamento lógico do Banco de Dados de Inteligência é chamado IntelligenceRepository.
Você só precisa chamar a função IntelligenceRepository.get_asset_string das classes de ativos, pois anexar novos ativos ao Banco de Dados de Inteligência é responsabilidade do módulo scan no script inq. Você usaria principalmente esta função para criar instâncias de ativos ou recuperá-las do banco de dados se elas existirem. Esta função é importante ao retornar ativos das funções related e transform de suas classes de ativos, pois criar novos objetos de ativo é caro, já que alguns deles usam recursos de rede durante a inicialização.```
Function
IntelligenceRepository.get_asset_string(asset_type, identifier, create=False, store=False)
Description
Retrieves the primary key and asset object for the asset with the provided
type and identifier.
Parameters
asset_type: class, required
The type of the asset to retrieve from the Intelligence Database. You
will actually have to pass the class object of the asset type you want
to retrieve.
identifier: any, required
The identifier of the asset to retrieve. Consider the identifier as the
unique attribute of an asset object. As for which attribute is to be
used to identify an asset, it depends on the contents of the OBJECT_ID
variable in the asset module.
create: bool, optional, default=False
When no matching asset object is found, a new one will be created and
returned if this parameter is set to True. The new asset will not
necessarily be stored in the Intelligence Database unless specified
using the "store" parameter. However, I suggest you do not do this as
adding assets to the Intelligence Database is the responsibility of
another module.
store: bool, optional, default=False
When a new asset is created when none is found, the new one will be
stored in the Intelligence Database. As said previously, I suggest that
you do not do this as adding assets to the Intelligence Database is the
responsibility of another module.
Returns
A two-element tuple where the first element is the database primary key of
the element returned, and the second element is the deserialized asset
object retrieved from the database.
None if the asset was not found.
If the asset was not found and the create flag was set to True, the primary
key member of the tuple will be set to None.
### Ativos
Para criar um novo tipo de ativo, crie um novo arquivo dentro do diretório `inquisitor/assets` e cole o seguinte código esqueleto dentro:```python
import inquisitor.assets
class ASSET_NAMEValidateException(Exception):
pass
def canonicalize(ASSET_IDENTIFIER):
return ASSET_IDENTIFIER
def main_classify_args(parser):
parser.add_argument(
'-aASSET_NAME_LETTER', '--accept-ASSET_NAME',
metavar='ASSET_NAME',
type=canonicalize,
nargs='+',
help='Specifies a ASSET_NAME to classify as accepted.',
dest='ASSET_NAMEs_accepted',
default=list(),
)
parser.add_argument(
'-uASSET_NAME_LETTER', '--unmark-ASSET_NAME',
metavar='ASSET_NAME',
type=canonicalize,
nargs='+',
help='Specifies a ASSET_NAME to classify as unmarked.',
dest='ASSET_NAMEs_unmarked',
default=list(),
)
parser.add_argument(
'-rASSET_NAME_LETTER', '--reject-ASSET_NAME',
metavar='ASSET_NAME',
type=canonicalize,
nargs='+',
help='Specifies a ASSET_NAME to classify as rejected.',
dest='ASSET_NAME_rejected',
default=list(),
)
def main_classify_canonicalize(args):
accepted = set(args.ASSET_NAMEs_accepted)
unmarked = set(args.ASSET_NAMEs_unmarked)
rejected = set(args.ASSET_NAME_rejected)
redundant = set.intersection(accepted, unmarked, rejected)
if redundant:
raise ValueError(
('Conflicting classifications for ASSET_NAMEs '
': {}').format(list(redundant))
)
accepted = set([canonicalize(a) for a in accepted])
unmarked = set([canonicalize(a) for a in unmarked])
rejected = set([canonicalize(a) for a in rejected])
return (accepted, unmarked, rejected)
class ASSET_NAME(inquisitor.assets.Asset):
def __init__(self, ASSET_IDENTIFIER, owned=None):
super(self.__class__, self).__init__(owned=owned)
self.ASSET_IDENTIFIER = canonicalize(ASSET_IDENTIFIER)
# TODO: Perform other initialization actions here
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.ASSET_IDENTIFIER == other.ASSET_IDENTIFIER
def related(self, repo):
# Prepare the results
results = set()
# TODO: Create related assets here based on the attributes of this asset
# Return the results
return results
def transform(self, repo, sources):
# Prepare the results
assets = set()
# Google Transforms
if sources.get('google'):
subassets = self.cache_transform_get('google', repo)
if not subassets:
# Acquire API
google = sources['google']
# TODO: Perform Google queries here and the results to 'subassets'
# Cache The Transform
self.cache_transform_store('google', subassets)
assets.update(subassets)
# Shodan Transforms
if sources.get('shodan'):
subassets = self.cache_transform_get('shodan', repo)
if not subassets:
# Acquire API
shodan = sources['shodan']
# TODO: Perform Google queries here and the results to 'subassets'
# Cache The Transform
self.cache_transform_store('shodan', subassets)
assets.update(subassets)
# Return the results
return assets
def is_owned(self, repo):
if self.owned:
return True
# TODO: Automatically determine ownership based on repo contents
return False
def parent_asset(self, repo):
# TODO: Return parent asset based on repo contents
return None
REPOSITORY = 'ASSET_REPOSITORY'
ASSET_CLASS = ASSET_NAME
OBJECT_ID = 'ASSET_IDENTIFIER'
Agora substitua as seguintes strings pelos valores apropriados
ASSET_NAME : Nome próprio do seu ativo (ex.: Registrant, Host, etc.)ASSET_IDENTIFIER : O nome do atributo identificador do seu ativoASSET_NAME_LETTER : A primeira letra do seu ativo em minúsculasASSET_REPOSITORY : Minúsculas da forma plural do nome do seu ativoFinalmente, em inquisitor/__init__.py, registre o seu ativo na lista ASSET_MODULES. Certifique-se de importar o seu novo ativo a partir do arquivo em questão.
Parabéns! Neste ponto, você já tem um novo tipo de ativo funcional!
No entanto, você precisará implementar os seguintes métodos para garantir que seus ativos sejam correlacionados com outros tipos de ativos:``` Function
related
Description
Returns the set of assets directly related to the asset in question (i.e.
those that can be derived without querying a search engine).
When creating asset objects, make sure you use the
IntelligenceRepository.get_asset_string method instead of instatiating a
new one your self so the asset can be returned from the repository if it
exists.
Set the create flag to True when calling the method in question in order
to return a new object when one isn't found.
Set the store flag to False as appending assets is the job of another
module.
Parameters
repo: IntelligenceRepository
The Intelligence Repository that is being used in the current context.
Returns
Set of assets directly related to the asset in question.
Por exemplo, para executar uma verificação de caminhos presentes na wordlist `quickhits.txt` usando a técnica **all**, ativando a recursão.```
Function
transform
Description
Returns the set of assets potentially related to the asset in question
(i.e. those that can be derived by querying a search engine).
You may access search engine objects through the provided sources
parameter.
Each search engine object has a transform method which automatically
creates asset objects for you. You just need to provide it the repository
and your query string, and then append the objects it returns to the set
of assets to be returned by your asset's transform method.
Parameters
repo: IntelligenceRepository
The Intelligence Repository that is being used in the current context.
sources: dict
The list of search engine objects that are available for use.
Returns
Set of assets potentially related to the asset in question.
Saída e salve os resultados em um arquivo de saída:
python3 spiderfoot.py -s <target> -o <outputfile>
Se você quiser ignorar alvos individuais que possam estar relacionados a você (por exemplo, se você está pesquisando um alvo que também pode usar um serviço que você possui ou opera, e você não quer interagir com ele), você pode configurar uma lista de "alvos ignoráveis" através de -f <filename>:
python3 spiderfoot.py -s <target> -f /path/to/ignorelist.txt
O arquivo deve conter um alvo por linha.``` Function
is_owned
Description
Determines if there is high confidence that this asset does indeed belong
to the target. Usually checks for any "strong" classification tag first by
looking at the contents of the "owned" variable, before performing
automatic evaluation.
Automatic evaluation depends on what type of asset you're writing. For
example, for a Host asset, the secondary sources of determining ownership
would include looking if its registrant is owned by the target, if it's
parent domain is owned by the target. etc.
Parameters
repo: IntelligenceRepository
The Intelligence Repository that is being used in the current context.
Returns
True it is determined with high confidence that this asset does indeed
belong to the target.
### 4.1 Criar um Projeto
Para começar, crie um projeto usando `create-oxy-x-project`:
```bash
npx create-oxy-x-project
Ele solicitará:
✔ Project name: … test
✔ Pick a template › All Templates
? Pick target extension: » - Use arrow-keys. Return to submit.
> Chrome/Edge Extension
Firefox Addon
User Script
Interpretação: Não importa se você constrói a extensão do navegador ou o script de usuário, ambos compartilham a mesma infraestrutura. Vamos selecionar Chrome Extension por enquanto e continuar.
Function
parent_asset
Description
Returns the asset object that is considered the parent of this asset
object.
Parameters
repo: IntelligenceRepository
Returns
The asset object that this asset falls under (e.g. a Block is under a
Registrant, a Host is under a Block, a Host is under another Host, an Email
is under a Host, etc. This is primarily used for visualization.
Após implementar os métodos acima, certifique-se de definir as variáveis `REPOSITORY`, `ASSET_CLASS` e `OBJECT_ID` na parte inferior do código-fonte do seu ativo.
## Contato e Notas
O modo de varredura não foi totalmente testado devido às cotas relacionadas aos mecanismos de busca envolvidos. Além disso, este projeto foi feito às pressas como parte de um desafio de hackaton de uma semana, então pode haver muitos problemas por aí. Por favor, crie um ticket de issue ou entre em contato comigo em [email protected] se encontrar um bug ou tiver alguma dúvida.
## Aviso Legal
Este trabalho é derivado das abordagens implementadas pelas ferramentas de Inteligência de Código Aberto Maltego e recon-ng. Eu suplementei essas abordagens com ideias que já são de conhecimento comum (por exemplo, whois informa quem é o proprietário de um domínio, subdomínios são de propriedade da mesma organização que possui seu domínio pai - conforme implícito em ataques de força bruta de nomes de domínio, organizações são autoritativas sobre os nomes de domínio que possuem, etc.), ou são originais e foram concebidas por mim no meu tempo pessoal como parte do meu hobby (por exemplo, classificações de aceitabilidade, várias transformações, herança de classificação, etc.).
Nenhum componente deste trabalho foi derivado de qualquer trabalho que tenha feito para qualquer empregador no passado. Todo o projeto, incluindo a prova de conceito, foi escrito do zero e foi incrementado com ideias da comunidade de segurança da informação.