Skip to content
This repository has been archived by the owner on May 27, 2024. It is now read-only.

Add support for scanning Azure accounts from cartography-service #42

Merged
merged 1 commit into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion cartography/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,22 @@ def _build_parser(self):
'The name of environment variable containing Azure Client Secret for Service Principal Authentication.'
),
)
parser.add_argument(
'--borneo-azure-federated-auth',
action='store_true',
help=(
'Use Service Principal authentication for Azure sync.'
),
)
parser.add_argument(
'--borneo-azure-client-secret',
type=str,
default=None,
help=(
'Azure Client Secret for Service Principal Authentication.'
),
)

parser.add_argument(
'--aws-requested-syncs',
type=str,
Expand Down Expand Up @@ -512,7 +528,10 @@ def main(self, argv: str) -> int:
parse_and_validate_aws_requested_syncs(config.aws_requested_syncs)

# Azure config
if config.azure_sp_auth and config.azure_client_secret_env_var:
if config.borneo_azure_federated_auth and config.borneo_azure_client_secret:
logger.info("Authenticating using a federated IAM connected to Borneo AWS Cognito Role")
config.azure_client_secret = config.borneo_azure_client_secret
elif config.azure_sp_auth and config.azure_client_secret_env_var:
logger.debug(
"Reading Client Secret for Azure Service Principal Authentication from environment variable %s",
config.azure_client_secret_env_var,
Expand Down Expand Up @@ -627,6 +646,10 @@ def main(argv=None, sync_flag=None):
result = CLI(sync, prog='cartography').main(argv)
elif(requested_sync.startswith("gcp")):
sync = cartography.sync.build_borneo_gcp_sync("skip_index" in requested_sync)
result = CLI(sync, prog='cartography').main(argv)
elif(requested_sync.startswith("azure")):
sync = cartography.sync.build_borneo_azure_sync("skip_index" in requested_sync)
result = CLI(sync, prog='cartography').main(argv)
elif(requested_sync.startswith("okta")):
sync = cartography.sync.build_borneo_okta_sync("skip_index" in requested_sync)
result = CLI(sync, prog='cartography').main(argv)
Expand Down
4 changes: 4 additions & 0 deletions cartography/intel/azure/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ def start_azure_ingestion(neo4j_session: neo4j.Session, config: Config) -> None:
credentials = Authenticator().authenticate_sp(
config.azure_tenant_id, config.azure_client_id, config.azure_client_secret,
)
elif config.borneo_azure_federated_auth:
credentials = Authenticator().authenticate_federated_principal(
config.azure_tenant_id, config.azure_client_id, config.azure_client_secret,
)
else:
credentials = Authenticator().authenticate_cli()

Expand Down
51 changes: 50 additions & 1 deletion cartography/intel/azure/util/credentials.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import logging
from datetime import datetime
from datetime import timedelta
import time
from typing import Any
from typing import Optional

import adal
import requests
from azure.common.credentials import get_azure_cli_credentials
from azure.common.credentials import get_cli_profile
from azure.core.credentials import TokenCredential, AccessToken
from azure.core.exceptions import HttpResponseError
from azure.identity import ClientSecretCredential
from azure.identity import AzureAuthorityHosts, ClientSecretCredential
from msrestazure.azure_active_directory import AADTokenCredentials
from msal import ConfidentialClientApplication
jhecking marked this conversation as resolved.
Show resolved Hide resolved

logger = logging.getLogger(__name__)
AUTHORITY_HOST_URI = 'https://login.microsoftonline.com'
Expand Down Expand Up @@ -91,6 +94,33 @@ def refresh_credential(self, credentials: Any) -> Any:
return new_credentials


# Create a custom class that acts as a credential.
class AssertionCredential(TokenCredential):
def __init__(
self,
tenant_id: str,
client_id: str,
client_secret: str,
) -> None:
self.tenant_id = tenant_id
self.client_id = client_id
self.client_secret = client_secret

self.app = ConfidentialClientApplication(
client_id,
client_credential={"client_assertion": client_secret},
authority=f"https://{AzureAuthorityHosts.AZURE_PUBLIC_CLOUD}/{tenant_id}",
)

def get_token(self, *scopes: str) -> AccessToken:
logger.info(f"Getting token for scopes: {scopes}, {type(scopes)}")
token = self.app.acquire_token_for_client(list(scopes))
if "error" in token:
raise Exception(token["error_description"])
expires_on = time.time() + token["expires_in"]
return AccessToken(token["access_token"], int(expires_on))


class Authenticator:

def authenticate_cli(self) -> Credentials:
Expand Down Expand Up @@ -170,3 +200,22 @@ def authenticate_sp(self, tenant_id: str = None, client_id: str = None, client_s
)

raise e

def authenticate_federated_principal(
self, tenant_id: str = None, client_id: str = None, client_secret: str = None
) -> AssertionCredential:
"""
Implements authentication for an Azure Federated Service Principal
"""

# Get a credential based on the identity token.
try:
creds = AssertionCredential(
tenant_id=tenant_id, client_id=client_id, client_secret=client_secret
)
return Credentials(
creds, None, tenant_id=tenant_id, current_user=client_id,
)
except Exception as e:
logger.error(f"Failed to get credentials: {e}")
raise e
11 changes: 11 additions & 0 deletions cartography/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,17 @@ def build_borneo_gcp_sync(skipIndex: bool) -> Sync:
])
return sync

def build_borneo_azure_sync(skipIndex: bool) -> Sync:
sync = Sync()
if skipIndex != True:
sync.add_stages([('create-indexes', cartography.intel.create_indexes.run)])
sync.add_stages([
('azure', cartography.intel.azure.start_azure_ingestion),
('analysis', cartography.intel.analysis.run)
])
return sync


def build_borneo_okta_sync(skipIndex: bool) -> Sync:
sync = Sync()
if skipIndex != True:
Expand Down
Loading