Exemplo n.º 1
0
    def _get_azure_ad_access_token(self) -> str:
        """   https://msal-python.readthedocs.io/en/latest/#msal.ConfidentialClientApplication  """
        app = ConfidentialClientApplication(
            client_id=self.oauth_client_id,
            client_credential=self.oauth_client_secret,
            authority=self.oauth_client_authority)

        result = None

        config = {
            "scope": ["https://graph.microsoft.com/.default"],
        }

        if not result:
            result = app.acquire_token_for_client(scopes=config["scope"])

        if "access_token" not in result:
            print(result.get("error"))
            print(result.get("error_description"))
            print(result.get(
                "correlation_id"))  # You might need this when reporting a bug.
            raise dbt.exceptions.FailedToConnectException(
                'failed to connect to Azure')
        # print("ACCESS TOKEN:"+ result["access_token"])
        # return result["access_token"]
        return "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyIsImtpZCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyJ9.eyJhdWQiOiIyZmY4MTRhNi0zMzA0LTRhYjgtODVjYi1jZDBlNmY4NzljMWQiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC8yY2M0ZjZiZS1kMjMzLTQ5NjgtYTkyYy03NGNlMmQyNmFkYjEvIiwiaWF0IjoxNjEzOTEzNTk2LCJuYmYiOjE2MTM5MTM1OTYsImV4cCI6MTYxMzkxNzQ5NiwiYWNyIjoiMSIsImFpbyI6IkFVUUF1LzhUQUFBQWtlbWNtcGpGdEw2NzNEakJPOWtpdHg2eFZiTDVRalNqTExLaGtJa2hMUUE1Q3c0WVNIb0haWG5nc0FGbVdLeDJaV2JucTZkWFc1M2dhZnZRMnhxS2NnPT0iLCJhbHRzZWNpZCI6IjE6bGl2ZS5jb206MDAwM0JGRkQxM0FBQkU3RiIsImFtciI6WyJwd2QiXSwiYXBwaWQiOiI0NTRjZjY3OS1jOGMzLTQ0OTUtOTllMy1jZWMzMjAxNDU4MDkiLCJhcHBpZGFjciI6IjAiLCJlbWFpbCI6InZhbGRhc0BtYWtzaW1hdmljaXVzLmV1IiwiZmFtaWx5X25hbWUiOiIyZGRhMWYzYS0zMjExLTRjMjAtYTdjMC1jYzliMmY3ZmI4NzkiLCJnaXZlbl9uYW1lIjoiZjk1ZWQ5NzgtY2I0My00OThjLWIxNmUtMTU0MGQ5NWYzNDQxIiwiaWRwIjoibGl2ZS5jb20iLCJpcGFkZHIiOiI3OC41OC4yMzcuMTY2IiwibmFtZSI6ImY5NWVkOTc4LWNiNDMtNDk4Yy1iMTZlLTE1NDBkOTVmMzQ0MSAyZGRhMWYzYS0zMjExLTRjMjAtYTdjMC1jYzliMmY3ZmI4NzkiLCJvaWQiOiIwYjRmNWQ3OC03ZTBlLTQyMzItYmI2MS01NjNmZmVlNDlhNzQiLCJwdWlkIjoiMTAwMzAwMDBBQzAwN0U3NyIsInJoIjoiMC5BVEVBdnZiRUxEUFNhRW1wTEhUT0xTYXRzWG4yVEVYRHlKVkVtZVBPd3lBVVdBa3hBSm8uIiwic2NwIjoidXNlcl9pbXBlcnNvbmF0aW9uIiwic3ViIjoiVGNpaS16bXhDUTkxSjdCWVoxdGpKdkVSb0xLQ0FGQ2NPeGYtYmo3QzF3SSIsInRpZCI6IjJjYzRmNmJlLWQyMzMtNDk2OC1hOTJjLTc0Y2UyZDI2YWRiMSIsInVuaXF1ZV9uYW1lIjoibGl2ZS5jb20jdmFsZGFzQG1ha3NpbWF2aWNpdXMuZXUiLCJ1dGkiOiJNZ1JhczNXUVUwQ3R0d0I3cUVCQkFBIiwidmVyIjoiMS4wIn0.PGjS4bHZTMCFQnbBNUUg1w5G9YTem1dfjM3eiBf1-sVPRRyRyUlB28nB7PjYB_GnR235ZmaBkc3TF0mToGUqC43Zky2a0CWlAEmRyzUH85y8RIWzgnEx5cRi7SC46klzqHa78xnQWoihjPCG23VT8bo3nwKH0JziH6DFBmsrFc0wwqMBm4l_xjf_3MgPr5Fk-GzQ_LtryUvxdiATXAjqiK6Zcmm1fPKZZAdizP4EQImfGALbDwjoIdyggyInnZzOGWJjODXPaFMpbNnKM8LWGcpMgNfCeShfWchOSn5JqNvVBMIrsRkuVzo8eDOK_e63YTASncj4ncNRJ4EDtlBQGA"
Exemplo n.º 2
0
class ApplicationCertificateTokenProvider(TokenProviderBase):
    """
    Acquire a token from MSAL using application certificate
    Passing the public certificate is optional and will result in Subject Name & Issuer Authentication
    """

    def __init__(self, kusto_uri: str, client_id: str, authority_uri: str, private_cert: str, thumbprint: str, public_cert: str = None):
        super().__init__(kusto_uri)
        self._msal_client = None
        self._auth = authority_uri
        self._client_id = client_id
        self._cert_credentials = {TokenConstants.MSAL_PRIVATE_CERT: private_cert, TokenConstants.MSAL_THUMBPRINT: thumbprint}
        if public_cert is not None:
            self._cert_credentials[TokenConstants.MSAL_PUBLIC_CERT] = public_cert

    @staticmethod
    def name() -> str:
        return "ApplicationCertificateTokenProvider"

    def context(self) -> dict:
        return {"authority": self._auth, "client_id": self._app_client_id, "thumbprint": self._cert_credentials[TokenConstants.MSAL_THUMBPRINT]}

    def _init_impl(self):
        self._msal_client = ConfidentialClientApplication(client_id=self._client_id, client_credential=self._cert_credentials, authority=self._auth)

    def _get_token_impl(self) -> dict:
        token = self._msal_client.acquire_token_for_client(scopes=self._scopes)
        return self._valid_token_or_throw(token)

    def _get_token_from_cache_impl(self) -> dict:
        token = self._msal_client.acquire_token_silent(scopes=self._scopes, account=None)
        return self._valid_token_or_none(token)
Exemplo n.º 3
0
class ApplicationKeyTokenProvider(TokenProviderBase):
    """ Acquire a token from MSAL with application Id and Key """

    def __init__(self, kusto_uri: str, authority_uri: str, app_client_id: str, app_key: str):
        super().__init__(kusto_uri)
        self._msal_client = None
        self._app_client_id = app_client_id
        self._app_key = app_key
        self._auth = authority_uri

    @staticmethod
    def name() -> str:
        return "ApplicationKeyTokenProvider"

    def context(self) -> dict:
        return {"authority": self._auth, "client_id": self._app_client_id}

    def _init_impl(self):
        self._msal_client = ConfidentialClientApplication(client_id=self._app_client_id, client_credential=self._app_key, authority=self._auth)

    def _get_token_impl(self) -> dict:
        token = self._msal_client.acquire_token_for_client(scopes=self._scopes)
        return self._valid_token_or_throw(token)

    def _get_token_from_cache_impl(self) -> dict:
        token = self._msal_client.acquire_token_silent(scopes=self._scopes, account=None)
        return self._valid_token_or_none(token)
Exemplo n.º 4
0
 def __init__(self, spn_tenant_id: str, spn_client_id: str, spn_client_secret: str):
     app_client = ConfidentialClientApplication(
         client_id=spn_client_id,
         authority=f"https://login.microsoftonline.com/{spn_tenant_id}",
         client_credential=spn_client_secret
     )
     token = app_client.acquire_token_for_client(scopes="https://cloudpartner.azure.com/.default")
     if 'error' in token:
         raise RuntimeError("Could not fetch token for Azure Marketplace client", token['error_description'])
     self.token = token['access_token']
Exemplo n.º 5
0
def fetch_from_sharepoint_list(table_name: str, sub_site_id: str, list_id: str,
                               **kwargs):
    s3 = S3Data(table_name, kwargs["ts_nodash"])
    app = ConfidentialClientApplication(
        DIT_SHAREPOINT_CREDENTIALS['client_id'],
        authority=
        f'https://login.microsoftonline.com/{DIT_SHAREPOINT_CREDENTIALS["tenant_id"]}',
        client_credential=DIT_SHAREPOINT_CREDENTIALS['client_secret'],
    )
    token_response = app.acquire_token_for_client(
        scopes=['https://graph.microsoft.com/.default'])
    if 'access_token' not in token_response:
        raise InvalidAuthCredentialsError(
            f'Failed to acquire token: {token_response.get("error_description")}'
        )

    access_token = token_response['access_token']
    tenant = DIT_SHAREPOINT_CREDENTIALS["tenant_domain"]
    sharepoint_site = (
        f':/sites/{DIT_SHAREPOINT_CREDENTIALS["site_name"]}:/sites/{sub_site_id}'
    )
    list_url = f'https://graph.microsoft.com/v1.0/sites/{tenant}{sharepoint_site}/lists/{list_id}'
    items_url = f'{list_url}/items'

    # Fetch a copy of the column names, this needs to be done separately from
    # fetching items as otherwise paging will not work.
    logger.info('Fetching column names from %s', list_url)
    graph_data = _make_request(list_url, access_token, {'expand': 'columns'})
    column_map = {
        col['name']: col['displayName']
        for col in graph_data['columns']
    }

    # Fetch the list item data
    page = 1
    while items_url is not None:
        logger.info('Fetching from %s', items_url)
        graph_data = _make_request(items_url, access_token,
                                   {'expand': 'fields'})
        records = [{
            **{
                column_map[col_id]: row['fields'][col_id]
                for col_id in row['fields'].keys() if col_id in column_map
            },
            'createdBy':
            row['createdBy']['user'],
            'lastModifiedBy':
            row['lastModifiedBy']['user']
            if row.get('lastModifiedBy') is not None else None,
        } for row in graph_data['value']]
        s3.write_key(f"{page:010}.json", records)
        page += 1
        items_url = graph_data.get('@odata.nextLink')

    logger.info('Finished fetching from sharepoint')
Exemplo n.º 6
0
def ms_graph_client_token():
    azure_tenant_id = os.environ["AZURE_TENANT_ID"]
    client_id = os.environ["MS_GRAPH_API_CLIENT_ID"]
    client_secret = os.environ["MS_GRAPH_API_CLIENT_SECRET"]
    context = ConfidentialClientApplication(
        client_id=client_id,
        client_credential=client_secret,
        authority="https://login.microsoftonline.com/{}".format(
            azure_tenant_id),
    )
    scope = "https://graph.microsoft.com/.default"
    return context.acquire_token_for_client(scope)
Exemplo n.º 7
0
 def __init__(self, spn_tenant_id: str, spn_client_id: str,
              spn_client_secret: str):
     app_client = ConfidentialClientApplication(
         spn_client_id,
         authority=f"https://login.microsoftonline.com/{spn_tenant_id}",
         client_credential=spn_client_secret)
     token = app_client.acquire_token_for_client(
         scopes="https://cloudpartner.azure.com/.default")
     self.req_headers = {
         "Authorization": f"Bearer {token['access_token']}",
         "Content-Type": "application/json",
     }
     self.req_params = {"api-version": "2017-10-31"}
Exemplo n.º 8
0
async def get_obo_token(
        auth_settings: AuthSettings = Depends(get_auth_settings),
        msal_app: msal.ConfidentialClientApplication = Depends(
            get_private_app),
):
    tenant = urlparse(auth_settings.b2c_endpoint).path.lstrip('/')
    scopes = [
        f'https://{tenant}/{auth_settings.elastic_client_id}/.default',
    ]
    token_resp = msal_app.acquire_token_for_client(scopes)
    try:
        return token_resp['access_token']
    except KeyError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail='Unable to acquire elastic access token',
            headers={'WWW-Authenticate': 'Bearer'},
        )
Exemplo n.º 9
0
 def _get_msgraph_token() -> str:
     scopes = ["https://graph.microsoft.com/.default"]
     app = ConfidentialClientApplication(
         client_id=config.API_CLIENT_ID,
         client_credential=config.API_CLIENT_SECRET,
         authority=f"{config.AAD_INSTANCE}/{config.AAD_TENANT_ID}")
     result = app.acquire_token_silent(scopes=scopes, account=None)
     if not result:
         logging.info(
             'No suitable token exists in cache, getting a new one from AAD'
         )
         result = app.acquire_token_for_client(scopes=scopes)
     if "access_token" not in result:
         logging.debug(result.get('error'))
         logging.debug(result.get('error_description'))
         logging.debug(result.get('correlation_id'))
         raise Exception(result.get('error'))
     return result["access_token"]
Exemplo n.º 10
0
def generatetoken():
    with open('app/json_files/credential.json') as f:
        credentials = json.load(f)

    appMS = ConfidentialClientApplication(
        credentials.get('CLIENT_ID', {}),
        authority=credentials.get('AUTHORITY', {}),
        client_credential=credentials.get('CLIENT_SECRET', {}))
    result = None
    scope = credentials.get('SCOPE', {})
    result = appMS.acquire_token_silent(scopes=list(scope), account=None)
    if not result:
        logging.info(
            "No suitable token exists in cache. Let's get a new one from AAD.")
        result = appMS.acquire_token_for_client(scopes=scope)

    token = result.get('access_token', {})
    return token
Exemplo n.º 11
0
def patching_oms(plugin, date):
    AZURE_TENANT = plugin.params.get(name="AZURE_TENANT").value
    AZURE_APP_ID = plugin.params.get(name="AZURE_APP_ID").value
    AZURE_APP_SECRET = plugin.params.get(name="AZURE_APP_SECRET").value
    AZURE_LOG_WORKSPACE = plugin.params.get(name="AZURE_LOG_WORKSPACE").value
    LOG_ANALYTICS_BASE = "https://api.loganalytics.io"
    LOG_ANALYTICS_BASE_SCOPE = "{}/.default".format(LOG_ANALYTICS_BASE)
    LOG_ANALYTICS_QUERY = "{}/v1/workspaces/{}/query".format(
        LOG_ANALYTICS_BASE, AZURE_LOG_WORKSPACE)

    ctx = ConfidentialClientApplication(
        client_id=AZURE_APP_ID,
        client_credential=AZURE_APP_SECRET,
        authority=AZURE_TENANT,
    )
    token = ctx.acquire_token_for_client(LOG_ANALYTICS_BASE_SCOPE)
    headers = {"Authorization": "Bearer {}".format(token["access_token"])}

    patching = requests.get(
        LOG_ANALYTICS_QUERY,
        params={
            "query":
            "(ConfigurationData | project Computer, TimeGenerated, VMUUID | distinct Computer) | join kind=inner ( Heartbeat | project Computer, OSType, OSName, OSMajorVersion, OSMinorVersion, ComputerEnvironment, TimeGenerated, TenantId, ComputerIP | summarize arg_max (TimeGenerated, *) by Computer ) on Computer"
        },
        headers=headers,
    )
    results = patching.json()

    for computer in results["tables"][0]["rows"]:
        host_status = lookup(computer[0], date)
        if host_status is None:
            continue
        host_status.patching_info = {
            "id": computer[8],
            "os_type": computer[3],
            "os_name": computer[4],
            "os_major_version": computer[5],
            "os_minor_version": computer[6],
        }
        host_status.patching_plugin = plugin
        host_status.patching_output = "Server has been enrolled in OMS."
        host_status.patching_status = 3
        host_status.save()
        print("Updated patching status for {}".format(host_status))
def get_sp_access_token(client_id,client_credential,tenant_name,scopes):
    logging.info('Attempting to obtain an access token...')
    result = None
    app = ConfidentialClientApplication(
        client_id = client_id,
        client_credential= client_credential,
        authority = f"https://login.microsoftonline.com/{tenant_name}"
    )
    result = app.acquire_token_for_client(scopes=scopes)

    if "access_token" in result:
        logging.info('Access token successfully acquired')
        return result['access_token']
    else:
        logging.error('Unable to obtain access token')
        logging.error(f"Error was: {result['error']}")
        logging.error(f"Error description was: {result['error_description']}")
        logging.error(f"Error correlation_id was: {result['correlation_id']}")
        raise Exception('Failed to obtain access token')
Exemplo n.º 13
0
def teams_session():
    client_id = ge('client_id')
    authority_id = ge('authority_id')
    client_credential = ge('client_credential')

    BASE_URL = "https://graph.microsoft.com/beta/"
    ms_s = sessions.BaseUrlSession(base_url=BASE_URL)

    app = ConfidentialClientApplication(
        client_id=client_id,
        authority=f"https://login.microsoftonline.com/{authority_id}",
        client_credential=client_credential)

    result = app.acquire_token_for_client(
        scopes=["https://graph.microsoft.com/.default"])
    token = result['access_token']
    sessions.BaseUrlSession(base_url='https://graph.microsoft.com/beta/')

    ms_s.headers.update({"Authorization": f"Bearer {token}"})
    return ms_s
Exemplo n.º 14
0
class Authenticator:
    app: ConfidentialClientApplication

    def __init__(self, config: Dict):
        client_id: str = config['GRAPH_API_AUTH_CLIENT_ID']
        authority: str = config['GRAPH_API_AUTH_AUTHORITY']
        thumprint: str = config['GRAPH_API_AUTH_PUBKEY_THUMBPRINT']
        priv_key_path: str = config['GRAPH_API_AUTH_PRIVKEY_PATH']

        client_credential: dict = {
            "thumbprint": thumprint,
            "private_key": open(priv_key_path).read()
        }

        self.app = ConfidentialClientApplication(
            client_id=client_id,
            authority=authority,
            client_credential=client_credential)

    def get_auth_token(self) -> str:
        """
        Returns a valid auth_token or throws a value exception
        """
        result = None
        # Check in cache
        result = self.app.acquire_token_silent(AUTHENTICATION_SCOPE,
                                               account=None)

        if not result:
            print("Getting new token")
            result = self.app.acquire_token_for_client(
                scopes=AUTHENTICATION_SCOPE)
        if "access_token" in result:
            return result["access_token"]

        print(result.get("error"))
        print(result.get("error_description"))
        # You may need this when reporting a bug
        print(result.get("correlation_id"))
        raise ValueError(result)
Exemplo n.º 15
0
class ApplicationKeyTokenProvider(CloudInfoTokenProvider):
    """Acquire a token from MSAL with application Id and Key"""
    def __init__(self,
                 kusto_uri: str,
                 authority_id: str,
                 app_client_id: str,
                 app_key: str,
                 is_async: bool = False):
        super().__init__(kusto_uri, is_async)
        self._msal_client = None
        self._app_client_id = app_client_id
        self._app_key = app_key
        self._auth = authority_id

    @staticmethod
    def name() -> str:
        return "ApplicationKeyTokenProvider"

    def _context_impl(self) -> dict:
        return {
            "authority": self._cloud_info.authority_uri(self._auth),
            "client_id": self._app_client_id
        }

    def _init_impl(self):
        self._msal_client = ConfidentialClientApplication(
            client_id=self._app_client_id,
            client_credential=self._app_key,
            authority=self._cloud_info.authority_uri(self._auth),
            proxies=self._proxy_dict)

    def _get_token_impl(self) -> Optional[dict]:
        token = self._msal_client.acquire_token_for_client(scopes=self._scopes)
        return self._valid_token_or_throw(token)

    def _get_token_from_cache_impl(self) -> dict:
        token = self._msal_client.acquire_token_silent(scopes=self._scopes,
                                                       account=None)
        return self._valid_token_or_none(token)
def main(tenant_id, client_id, client_secret):
    authority = "https://login.microsoftonline.com/{tenant_id}".format(
        tenant_id=tenant_id)
    app = ConfidentialClientApplication(client_id=client_id,
                                        authority=authority,
                                        client_credential=client_secret)

    token_response = app.acquire_token_for_client(
        ["https://graph.microsoft.com/.default"])
    print("Response: ", token_response)
    print("Access token: ", token_response['access_token'])

    api_endpoint = "https://management.azure.com/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions?api-version=2019-09-01"
    # The tenant id is the root management group
    api_endpoint = api_endpoint.format(managementGroupId=tenant_id)

    session = request_authenticated_azure_session(
        token_response['access_token'])
    with session as req:
        response = req.get(api_endpoint)
        if response.status_code in range(200, 299):
            print(response.json())
        else:
            print("Oops!")
Exemplo n.º 17
0
def backup_storagesync(plugin, date):
    AZURE_TENANT = plugin.params.get(name="AZURE_TENANT").value
    AZURE_APP_ID = plugin.params.get(name="AZURE_APP_ID").value
    AZURE_APP_SECRET = plugin.params.get(name="AZURE_APP_SECRET").value
    AZURE_SUBSCRIPTION_ID = plugin.params.get(
        name="AZURE_SUBSCRIPTION_ID").value
    AZURE_RESOURCE_GROUP = plugin.params.get(name="AZURE_RESOURCE_GROUP").value
    AZURE_STORAGE_SYNC_NAME = plugin.params.get(
        name="AZURE_STORAGE_SYNC_NAME").value

    AZURE_URL = "https://portal.azure.com/#resource/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorageSync/storageSyncServices/{}/syncGroups".format(
        AZURE_SUBSCRIPTION_ID, AZURE_RESOURCE_GROUP, AZURE_STORAGE_SYNC_NAME)
    MANAGEMENT_BASE = "https://management.azure.com"
    MANAGEMENT_BASE_SCOPE = "{}/.default".format(MANAGEMENT_BASE)

    backup_limit = (datetime.datetime.now(tz=datetime.timezone.utc) -
                    datetime.timedelta(days=1)).isoformat()

    ctx = ConfidentialClientApplication(
        client_id=AZURE_APP_ID,
        client_credential=AZURE_APP_SECRET,
        authority=AZURE_TENANT,
    )
    token = ctx.acquire_token_for_client(MANAGEMENT_BASE_SCOPE)
    headers = {"Authorization": "Bearer {}".format(token["access_token"])}

    # Get list of sync groups
    MANAGEMENT_SYNC_BASE = "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.StorageSync/storageSyncServices/{}".format(
        MANAGEMENT_BASE,
        AZURE_SUBSCRIPTION_ID,
        AZURE_RESOURCE_GROUP,
        AZURE_STORAGE_SYNC_NAME,
    )

    MANAGEMENT_SYNC_GROUPS = "{}/syncGroups?api-version=2019-03-01".format(
        MANAGEMENT_SYNC_BASE)

    sync_groups = {}

    group_list = _ms_api("GET", MANAGEMENT_SYNC_GROUPS, headers=headers)

    for group in group_list:
        sync_groups[group["name"]] = _ms_api(
            "GET",
            "{}/syncGroups/{}/serverEndpoints?api-version=2019-03-01".format(
                MANAGEMENT_SYNC_BASE, group["name"]),
            headers=headers,
        )

    server_map = {}
    for name, servers in sync_groups.items():
        for server in servers:
            key = server["properties"]["friendlyName"]
            if key not in server_map:
                server_map[key] = []
            server_map[key].append({
                "name":
                name,
                "path":
                server["properties"]["serverLocalPath"],
                "upload_health":
                server["properties"]["syncStatus"]["uploadHealth"],
                "download_health":
                server["properties"]["syncStatus"]["downloadHealth"],
                "files_not_syncing":
                server["properties"]["syncStatus"]
                ["totalPersistentFilesNotSyncingCount"],
                "last_upload":
                server["properties"]["syncStatus"]["uploadStatus"]
                ["lastSyncTimestamp"],
                "last_upload_success":
                server["properties"]["syncStatus"]["uploadStatus"]
                ["lastSyncSuccessTimestamp"],
                "last_download":
                server["properties"]["syncStatus"]["downloadStatus"]
                ["lastSyncTimestamp"],
                "last_download_success":
                server["properties"]["syncStatus"]["downloadStatus"]
                ["lastSyncSuccessTimestamp"],
                "id":
                server["id"],
            })

    for name, servers in server_map.items():
        host_status = lookup(name, date)
        if not host_status or host_status.backup_plugin:
            continue

        host_status.backup_plugin = plugin
        host_status.backup_url = AZURE_URL
        host_status.backup_info = servers

        for server in servers:
            if server["last_upload_success"] < backup_limit:
                host_status.backup_output = (
                    "File shares are being backed up, last backup older than 24 hours."
                )
                host_status.backup_status = 2
                host_status.save()
                return

            if server["upload_health"] != "Healthy":
                host_status.backup_output = (
                    "File shares are being backed up, uploads not marked as healthy."
                )
                host_status.backup_status = 2
                host_status.save()
                return

        host_status.backup_output = (
            "File shares are being backed up, last backup was successful.")
        host_status.backup_status = 3
        host_status.save()
Exemplo n.º 18
0
def backup_azure(plugin, date):
    AZURE_TENANT = plugin.params.get(name="AZURE_TENANT").value
    AZURE_APP_ID = plugin.params.get(name="AZURE_APP_ID").value
    AZURE_APP_SECRET = plugin.params.get(name="AZURE_APP_SECRET").value
    AZURE_SUBSCRIPTION_ID = plugin.params.get(
        name="AZURE_SUBSCRIPTION_ID").value
    AZURE_VAULT_NAME = plugin.params.get(name="AZURE_VAULT_NAME").value
    AZURE_URL = "https://portal.azure.com/#resource{}/backupSetting"
    MANAGEMENT_BASE = "https://management.azure.com"
    MANAGEMENT_BASE_SCOPE = "{}/.default".format(MANAGEMENT_BASE)
    MANAGEMENT_SUB = "{}/subscriptions/{}".format(MANAGEMENT_BASE,
                                                  AZURE_SUBSCRIPTION_ID)

    ctx = ConfidentialClientApplication(
        client_id=AZURE_APP_ID,
        client_credential=AZURE_APP_SECRET,
        authority=AZURE_TENANT,
    )
    token = ctx.acquire_token_for_client(MANAGEMENT_BASE_SCOPE)
    headers = {"Authorization": "Bearer {}".format(token["access_token"])}

    # Get the ID of the specified vault.
    MANAGEMENT_LIST_VAULTS = "{}/providers/Microsoft.RecoveryServices/vaults?api-version=2016-06-01".format(
        MANAGEMENT_SUB)
    vaults = _ms_api("GET", MANAGEMENT_LIST_VAULTS, headers=headers)

    vault = None
    for v in vaults:
        if v["name"] == AZURE_VAULT_NAME:
            vault = v["id"]
            break
    if vault is None:
        return

    # Get backup protection container list.
    MANAGEMENT_LIST_CONTAINERS = "{}{}/backupProtectionContainers?api-version=2016-12-01&$filter=backupManagementType%20eq%20%27AzureIaasVM%27%20and%20status%20eq%20%27Registered%27".format(
        MANAGEMENT_BASE, vault)
    containers = _ms_api("GET", MANAGEMENT_LIST_CONTAINERS, headers=headers)

    vm_mapping = {}
    for container in containers:
        vm_id = container["properties"]["virtualMachineId"]
        if vm_id not in vm_mapping:
            vm_mapping[vm_id] = {}
        vm_mapping[vm_id]["id"] = vm_id
        vm_mapping[vm_id]["container_name"] = container["name"]
        vm_mapping[vm_id]["container_id"] = container["id"]
        vm_mapping[vm_id]["container_health"] = container["properties"][
            "healthStatus"]
        vm_mapping[vm_id]["ips"] = []

    # Get private IP addresses of each VM
    MANAGEMENT_LIST_NICS = "{}/providers/Microsoft.Network/networkInterfaces?api-version=2018-10-01".format(
        MANAGEMENT_SUB)
    nics = _ms_api("GET", MANAGEMENT_LIST_NICS, headers=headers)

    for nic in nics:
        if "virtualMachine" not in nic["properties"]:
            continue
        vm_id = nic["properties"]["virtualMachine"]["id"]
        if vm_id in vm_mapping:
            vm_mapping[vm_id]["ips"] = [
                x["properties"]["privateIPAddress"]
                for x in nic["properties"]["ipConfigurations"]
            ]

    for vm in vm_mapping.values():
        host_status = None
        for ip in vm["ips"]:
            host_status = lookup(ip, date)
            if host_status:
                break
        if not host_status:
            continue
        host_status.backup_plugin = plugin
        host_status.backup_url = AZURE_URL.format(vm["id"])
        host_status.backup_info = {
            "id": vm["id"],
            "container_name": vm["container_name"],
            "container_id": vm["container_id"],
            "container_health": vm["container_health"],
        }
        if vm["container_health"] == "Healthy":
            host_status.backup_output = "VM is enrolled for backups and is healthy."
            host_status.backup_status = 3
        else:
            host_status.backup_output = (
                "VM is enrolled for backups, but is not healthy.")
            host_status.backup_status = 2
        host_status.save()
        print("Updated Azure backup status for {}".format(host_status))
# Build authority from tanenat
authority = "https://login.microsoftonline.com/{0}".format(config["tenant"])

# Setup the application with client id, client secret and tenant name
app = ConfidentialClientApplication(config["client_id"],
                                    authority=authority,
                                    client_credential=config["client_secret"])

# Try to get token from memory cache, can be expanded to use a more
# permanent storage like redis
token_result = app.acquire_token_silent(config["scope"], account=None)

if not token_result:
    # No token in cache, let's get a new one
    token_result = app.acquire_token_for_client(scopes=config["scope"])

# Check for token
if "access_token" in token_result:

    # Make a request to the api
    print("Authed successfully")

    # --------------- Example 1a- Get a list of assets from Asset API ---------------
    print("Making call to Asset API to get list of assets")
    api_response = requests.get(config["assetApiEndpoint"] + "me/Assets",
                                headers={
                                    'Authorization':
                                    'Bearer ' + token_result["access_token"],
                                    'Ocp-Apim-Subscription-Key':
                                    config["assetApiSubscriptionKey"]
clientSecret = ""
app = ConfidentialClientApplication(clientID, authority=authority, client_credential=clientSecret)

scope = ["https://graph.microsoft.com/.default"]

# The pattern to acquire a token looks like this.
result = None

# First, the code looks up a token from the cache.
# Because we're looking for a token for the current app, not for a user,
# use None for the account parameter.
result = app.acquire_token_silent(scope, account=None)

if not result:
    print("No suitable token exists in cache. Let's get a new one from AAD.")
    result = app.acquire_token_for_client(scopes=scope)

if "access_token" in result:
    # Call a protected API with the access token.
    curToken = result["access_token"]
    print(curToken)
    endpoint =  graphURI + "beta/conditionalAccess/policies"
 #   endpoint =  graphURI + "v1.0/users"
    http_headers = {'Authorization': 'Bearer ' + curToken,
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'}
    data = requests.get(endpoint, headers=http_headers, stream=False).json()
    print(data)

else:
    print(result.get("error"))
doConditionalAccessPolicyTestWithAdminConsentedSP = True
if doConditionalAccessPolicyTestWithAdminConsentedSP:

    curClientId = appId
    #TODO - un-hardcode the sleep to a error backoff like above
    print(
        f"This will use clientID: {curClientId}. Sleeping for 60 seconds for propagation"
    )
    time.sleep(60)
    app = ConfidentialClientApplication(curClientId,
                                        appPwd,
                                        authority=authority)

    capScopes = ["https://graph.microsoft.com/.default"]
    capToken = app.acquire_token_for_client(capScopes)["access_token"]
    capHeader = {
        "Authorization": "Bearer {}".format(capToken),
        "Content-Type": "application/json"
    }

    print("Now trying same creds against the policy endpoint")
    capURL = graphURI + "beta/conditionalAccess/policies"
    capResponse = requests.get(capURL, headers=capHeader)
    capJSON = json.loads(capResponse.content)
    print(
        f"Response of Graph 2.0 API query against {capURL} using ClientID {curClientId} : {capResponse.content}"
    )

print("All Done!")