OAuth Example One - Azure AD Integration

Modified on: Wed, 27 Sep, 2023 at 7:08 PM

Overview

This example describes how OAuth integration can be configured in Maltego to get users to authorize access to resources on a third-party provider, [Azure is used here as an example] and how to write a Transform to access these resources.


We will create an Azure developer application, configure OAuth to allow the Maltego Desktop Client to redirect users to the Microsoft website to authorize Maltego access to make requests on the user's behalf. The third-party provider will return a token to Maltego which can then be used by the Transform to perform queries. We then show how developers can create Transforms which use the retrieved access token and get access to Azure resources using Microsoft Graph API.


This tutorial is broken into the following parts:

  1. Determine the data to access and the permissions required in the Microsoft Graph API.
  2. Create the Azure Developer App Registration
  3. Configure OAuth Settings in the Transform Distribution Server
  4. Develop and Deploy the Transform code
  5. Configure Seed and pair with Transform
  6. Run and Test Transform


Tutorial

1. Determine the data to access and the permissions required in the Microsoft Graph API.


The Microsoft Graph API (MS API) offers a single endpoint, https://graph.microsoft.com, to provide access to rich, people-centric data and insights exposed as resources of Microsoft 365 services.


Navigate to https://developer.microsoft.com/en-us/graph/graph-explorer where you will see the possible resources accessible via the Microsoft Graph API. There are numerous options which will vary depending on the needs of the developer. Our focus will be the Contacts API - https://graph.microsoft.com/v1.0/me/contacts, which returns a JSON object of the contacts for the authorized user.


We want to prompt the logged in user to grant our Transform access to his contact book and return those contacts to Maltego client. Our Transform will query the MS API and return the emails to Maltego, from there we can pivot to other Transforms. The process to be followed will also work for any other Azure OAuth accessible resources.


2. Create the Azure Developer app registration


2.1 Login into https://portal.azure.com

2.2 Navigate to Active directory - https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/Overview


Note: We are using the default AD but you can change the URL based on the number of ADs you have.


2.3 Go to App Registration and create and register a new Application


Add the following configurations and register the application:


Name: maltego-azure-oauth-tutorial

Redirect URI: https://127.0.0.1:63141/callback


Note: Maltego uses only 127.0.0.1 for loopback address. Do not use localhost here. This will be used later in the Maltego Client.



2.4 Add permissions to the maltego-azure-oauth-tutorial application.

2.5 We wish to add standard Microsoft Graph permissions. If you have other organizational APIs you can also select those if you were creating Transforms to consume those APIs.



2.6 Select the Delegated permissions option.



2.7 Select and add openid, profile and Contacts. Read permissions.

2.8 Create a client secret to be used to prove the application identity when requesting a token and choose how long the application secret will be usable.



2.9 Note down the created client secret and application id.



Note: These credentials will be important for configuring OAuth clients.


3. Configure OAuth settings in the Transform Distribution Server

3.1 Open your iTDS server or to the public TDS and create an account. Open OAuth Settings

3.1.1 iTDS OAuth Settings Image



3.1.2 Settings Configuration


Input the following OAuth settings as shown below, replace these with your values and save.


For base64 icon, download an icon for a provider and resize it to 64x64 using https://appiconmaker.co or https://www.websiteplanet.com/webtools/favicon-generator/ and encode it using https://www.base64-image.de/.


SettingValue
Authenticator NameiTDS Azure OAuth
DescriptionAzure OAuth Config
VersionOAuth 2.0
Access Token Endpoint[https://login.microsoftonline.com/common/oauth2/v2.0/token]
Request Token Endpoint[https://login.microsoftonline.com/common/oauth2/v2.0/authorize]
Authorization URLhttps://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={apiKey}&response_type=code&redirect_uri={callback}&response_mode=query&scope=profile,openid,User.Read,Contacts.Read

Application Key

This is the Application ID from the step 2.9

Application Secret

This is the Client Secret from step 2.9

Icon

Please note to use a very small resolution image. The Maltego client does not accept very large b64 images. Use to 64X64 or less

iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABzUlEQVQ4T5WT
SyhEURjH/9cwYjEMgwlRJpJHnrHxyiMLj2ZhKSVFE7GQkqwsLNh5bEjZWCllkDyilLzy
WomM3Fh4lMd4m3GP7jHndube2biL0+073/c73/l//yMQQgj++ckFgqdGkAGMwI
LyHkvik33FKIAVqBuRCIHj+RtJoYEKkIfL/wpAveGWCOrXr1AQ7o+WdDMCdH4UQ
os8HWoAPKRuVcSc+ILuBB2K4sJQaolS7q3RQH362dMXkqfPkB8ZjIiXG8QbgzFUl
aUA2FUpSPJowLc1cHyP7t0bdKabMLm+C4PeH47OKt8ANgV+AgV2BzZv39GfaU
SPfYseeNRagQxzqGY6GhHvP9yInjrBDwHGckPQPLNDAX1lqegtSdHooBnj5Okjmj
aukRiix4HVgpjBeTg/XciONmLPVq5Mgeng1YEctC6LmBWdaEwyYqI4Fh0LhxjZPqf
5Ylc1Yg1BXhAvgEQA68ol3lwS2tNMqI034OTOidThJdr6aE02bHkWbx14Edl8XZKE
tYs7xZhtc4dwPLyiMtGMxYZCGme5Gg3kk96+3bDZ9zXO0+t0GLfmQBD+Ziav1A
e8B9gGbxZ1jH8zymtkPlD7nfeHL+gv3H7Uzc9uAmYAAAAASUVORK5CYII
Access Token Variable Namemaltego.web.api.key.azure
Access Token Variable DescriptionAzure OAuth Token

Public Key

For the key pair, you can generate your own pair or use the one provided by Maltego and copy it a secure place. We do have access to your Private Key
Private Key


4. Develop and Deploy the Transform Code


We will be using the Maltego open source maltego-trx library to develop the demo Transform. Upon completion this will need to be deployed to a publicly accessible server such as a VPS or VM.  You need to have Python3 and pip installed.


4.1 Install the Prerequisite Software


python3 -m pip install --user virtualenv
python3 -m venv oauth-venv 
(oauth-venv) pip install maltego-trx  // install version 1.3.7+ only

4.2 Create a maltego-trx Project

maltego-trx start azure_oauth_project 

This will create a folder azure_oauth_project  with the example project.



4.3 Adding a Transform


Add a new Transform by creating a new Python file titled Azure.py in the "transforms" folder. Any Python file in the "transforms" folder whose class name matches the filename from which the class inherits from Transform will automatically be discovered and added to your Transform server.


Add the following files and the corresponding code:


4.4 Create File: azure_oauth_project /transforms/Azure.py

import json
from pathlib import Path
 
import requests
from maltego_trx.entities import Phrase
from maltego_trx.maltego import UIM_TYPES
from maltego_trx.oauth import MaltegoOauth
from maltego_trx.transform import DiscoverableTransform
 
 
class Azure(DiscoverableTransform):
    """
    Uses Oauth token from the Microsoft Graph and Returns the current Loggedin person's contacts
    """
 
    @classmethod
    def create_entities(cls, request, response):
        try:
            cipher_token = request.getTransformSetting('maltego.web.api.key.azure')
            private_key_path = Path("private_key.pem").resolve()
            token_fields = MaltegoOauth.decrypt_secrets(private_key_path, cipher_token)
 
            api_url = "https://graph.microsoft.com/v1.0/me/contacts"
            headers = {'Authorization': 'Bearer {}'.format(token_fields['token'])}
            result = requests.get(api_url, headers=headers)
            content = json.loads(result.content)
            for value in content['value']:
                for entry in value['emailAddresses']:
                    response.addEntity('maltego.EmailAddress', entry['address'])
                    response.addEntity("maltego.Person", entry['name'])
            ciphertext = response.addEntity(Phrase, cipher_token)
            ciphertext.setNote("ciphertext")
            token = response.addEntity(Phrase, token_fields['token'])
            token.setNote("token")
        except Exception as e:
            response.addUIMessage("Error: " + str(e), UIM_TYPES["partial"])
4.5 Add the private key from step 3.1.3 for decryption

    4.5.1 Create file : azure_oauth_project /private key.pem

    Add the contents of the private key to this pem file. It is possible to simply upload/save the actual pem file to this location

    if you have it as a PEM file.

4.6 Navigate to azure_oauth_project /

4.7 Run the trx project using (oauth-venv)python3 -b project.py runserver


Should all have gone successfully you should see something like this:



4.8 Deploy the entire project folder / azure_oauth_project to a remote VPS/VM/Dockerized environment. More details on how to deploy for production can be found here for standard web deployment and here for Docker containerized deployment. The simplest method for this tutorial is to upload the folder to a remote server through Git or FTP.


4.9 Navigating to your VPS IP http://<ip-address>/run/azure in a browser you should the following output. If it doesn’t work check that you have opened port on the firewall.



5. Configure Seed and Pair with Transform


Now that we have our Transform up and running we need to create a Seed to distribute the Transform. The TDS will generate a random alphanumeric Seed name for you, but you can also use one of your own choosing.

 

 

5.1 Add Transform and OAuth Settings to Seed

Next, we need to add the Transform, so we add the OAuth setting and the Input Entity and Seed.

 


5.2 Install Seed in the Maltego Client


After we are done adding the Transform, we can now install our Seed in Maltego.



5.3 Verify the OAuth Settings in the Service Manager


We can view the OAuth Authenticator settings in the Service Manager by selecting the Manage Service options under the Transforms menu. Cross check that the protocol set in step 2.3 are the same as here. The settings the Service Manager correspond with should correspond to the callback URL set in the provider Application.



5.4 Run the Transform


Drag a Person Entity on an empty graph and then right click and run Person to Emails [Signed in User].



Upon running the Transform, a prompt will appear asking you to sign in to authorize the Transform. Click Sign In. A browser page will be opened with the URL https://127.0.0.1:63141/signin and we are redirected to the Azure login page, please note you might observe a warning sign in the browser, ignore it and proceed.



After redirecting we are now able to sign into the application and grant the permissions which we set when we were setting up out OAuth settings.



The application we created will accept logins from any Microsoft public email account. In an organizational setup the privileges will be set by the admin.


After successful login a user can now make a query and return the contacts for the logged in user. The same authentication flow can be used in Maltego to authenticate users and return JWT access or id tokens.


You can view a video of the Transform in Action here


Note: To shorten authorization urls and to reference the returned token, Maltego uses configuration placeholders as follows:

For OAuth 2, "apiKey" and "callback" can be used as replacement variables in the authorization URL, e.g. http://example.com/oauth2/authorize?client_id={apiKey}&redirect_uri={callback}.

For OAuth 1.0a, only "token" can be used as a replacement variable, e.g. http://example.com/oauth1/authorize?oauth_token={token}.

For further explanation regarding OAuth endpoint configuration, please read more here.


Did you find it helpful? Yes No

Send feedback
Sorry we couldn't be helpful. Help us improve this article with your feedback.