async def test_send_sms_async_from_managed_identity(self):
        endpoint, access_key = parse_connection_str(self.connection_str)
        from devtools_testutils import is_live
        if not is_live():
            credential = FakeTokenCredential()
        else:
            credential = DefaultAzureCredential()
        sms_client = SmsClient(endpoint, credential)

        async with sms_client:
            # calling send() with sms values
            sms_responses = await sms_client.send(
                from_=self.phone_number,
                to=[self.phone_number],
                message="Hello World via SMS",
                enable_delivery_report=True,  # optional property
                tag="custom-tag")  # optional property

            assert len(sms_responses) is 1

            for sms_response in sms_responses:
                self.verify_sms_response(sms_response)
    def get_connect(self, secret_data):
        subscription_id = secret_data['subscription_id']

        os.environ['AZURE_SUBSCRIPTION_ID'] = subscription_id
        os.environ['AZURE_TENANT_ID'] = secret_data['tenant_id']
        os.environ["AZURE_CLIENT_ID"] = secret_data['client_id']
        os.environ["AZURE_CLIENT_SECRET"] = secret_data['client_secret']

        credential = DefaultAzureCredential()

        self.compute_client = ComputeManagementClient(
            credential=credential, subscription_id=subscription_id)
        self.vm_compute_client = ComputeManagementClient(
            credential=credential,
            subscription_id=subscription_id,
            api_version='2020-12-01')
        self.network_client = NetworkManagementClient(
            credential=credential, subscription_id=subscription_id)
        self.resource_client = ResourceManagementClient(
            credential=credential, subscription_id=subscription_id)
        self.subscription_client: SubscriptionClient = SubscriptionClient(
            credential=credential)
Example #3
0
    def authentication_with_azure_active_directory(self):
        """DefaultAzureCredential will use the values from the environment
        variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
        """
        # [START create_ta_client_with_aad]
        from azure.cognitiveservices.language.textanalytics import TextAnalyticsClient
        from azure.identity import DefaultAzureCredential

        endpoint = os.getenv("AZURE_TEXT_ANALYTICS_ENDPOINT")
        credential = DefaultAzureCredential()

        text_analytics_client = TextAnalyticsClient(endpoint,
                                                    credential=credential)
        # [END create_ta_client_with_aad]

        doc = ["I need to take my cat to the veterinarian."]
        result = text_analytics_client.detect_languages(doc)

        print("Language detected: {}".format(
            result[0].detected_languages[0].name))
        print("Confidence score: {}".format(
            result[0].detected_languages[0].score))
Example #4
0
    def set_connect(self, secret_data):
        subscription_id = secret_data['subscription_id']

        os.environ["AZURE_SUBSCRIPTION_ID"] = subscription_id
        os.environ["AZURE_TENANT_ID"] = secret_data['tenant_id']
        os.environ["AZURE_CLIENT_ID"] = secret_data['client_id']
        os.environ["AZURE_CLIENT_SECRET"] = secret_data['client_secret']

        credential = DefaultAzureCredential()

        self.compute_client = ComputeManagementClient(
            credential=credential, subscription_id=subscription_id)
        self.resource_client = ResourceManagementClient(
            credential=credential, subscription_id=subscription_id)
        self.network_client = NetworkManagementClient(
            credential=credential, subscription_id=subscription_id)
        self.subscription_client: SubscriptionClient = SubscriptionClient(
            credential=credential)
        self.sql_client = SqlManagementClient(credential=credential,
                                              subscription_id=subscription_id)
        self.monitor_client = MonitorManagementClient(
            credential=credential, subscription_id=subscription_id)
Example #5
0
def run_sample():
    # Instantiate a secret client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = SecretClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create a secret holding storage account credentials.
        # if the secret already exists in the Key Vault, then a new version of the secret is created.
        print("\n1. Create Secret")
        secret = client.set_secret("secretName", "secretValue")
        print("Secret with name '{0}' created with value '{1}'".format(secret.name, secret.value))

        # Backups are good to have, if in case secrets gets deleted accidentally.
        # For long term storage, it is ideal to write the backup to a file.
        print("\n2. Create a backup for an existing Secret")
        secret_backup = client.backup_secret(secret.name)
        print("Backup created for secret with name '{0}'.".format(secret.name))

        # The storage account secret is no longer in use, so you delete it.
        client.delete_secret(secret.name)

        # To ensure secret is deleted on the server side.
        print("\nDeleting secret...")
        time.sleep(20)
        print("Deleted Secret with name '{0}'".format(secret.name))

        # In future, if the secret is required again, we can use the backup value to restore it in the Key Vault.
        print("\n3. Restore the secret using the backed up secret bytes")
        secret = client.restore_secret(secret_backup)
        print("Restored Secret with name '{0}'".format(secret.name))

    except HttpResponseError as e:
        print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
Example #6
0
    def delete_images(self):
        # Instantiate an instance of ContainerRegistryClient
        audience = "https://management.azure.com"
        endpoint = os.environ["CONTAINERREGISTRY_ENDPOINT"]

        with ContainerRegistryClient(endpoint,
                                     DefaultAzureCredential(),
                                     audience=audience) as client:
            for repository in client.list_repository_names():
                print(repository)

                # Keep the three most recent images, delete everything else
                manifest_count = 0
                for manifest in client.list_manifest_properties(
                        repository,
                        order_by=ArtifactManifestOrder.
                        LAST_UPDATED_ON_DESCENDING):
                    manifest_count += 1
                    if manifest_count > 3:
                        print("Deleting {}:{}".format(repository,
                                                      manifest.digest))
                        client.delete_manifest(repository, manifest.digest)
    def set_policy_aad_unsecured(self):
        """
        Demonstrates setting an attestation policy for OpenEnclave attestation
        operations.
        """

        write_banner("set_policy_aad_unsecured")
        print("Set an unsecured Policy on an AAD mode attestation instance.")
        # [BEGIN set_policy_unsecured]
        with AttestationAdministrationClient(
                os.environ.get("ATTESTATION_AAD_URL"),
                DefaultAzureCredential()) as admin_client:
            new_policy = """
version= 1.0;
authorizationrules
{
    [ type=="x-ms-sgx-is-debuggable", value==false ] &&
    [ type=="x-ms-sgx-product-id", value==1 ] &&
    [ type=="x-ms-sgx-svn", value>= 0 ] &&
    [ type=="x-ms-sgx-mrsigner", value=="2c1a44952ae8207135c6c29b75b8c029372ee94b677e15c20bd42340f10d41aa"]
        => permit();
};
issuancerules {
    c:[type=="x-ms-sgx-mrsigner"] => issue(type="My-MrSigner", value=c.value);
};
    """

            set_result, _ = admin_client.set_policy(
                AttestationType.OPEN_ENCLAVE, new_policy)
            print("Policy Set result: ", set_result.policy_resolution)
            # [END set_policy_unsecured]

            get_result, _ = admin_client.get_policy(
                AttestationType.OPEN_ENCLAVE)
            if new_policy != get_result:
                print("Policy does not match set policy.")

            # Attest an OpenEnclave using the new policy.
            self._attest_open_enclave(os.environ.get("ATTESTATION_AAD_URL"))
def _get_identity_credentials(**kwargs):
    """
    Acquire Azure RM Credentials from the identity provider

    We basically set environment variables based upon incoming parameters and then pass off to
    the DefaultAzureCredential object to correctly parse those environment variables. See the
    `Microsoft Docs on EnvironmentCredential <https://aka.ms/azsdk-python-identity-default-cred-ref>`_
    for more information.
    """
    kwarg_map = {
        "tenant": "AZURE_TENANT_ID",
        "client_id": "AZURE_CLIENT_ID",
        "secret": "AZURE_CLIENT_SECRET",
        "client_certificate_path": "AZURE_CLIENT_CERTIFICATE_PATH",
        "username": "******",
        "password": "******",
    }

    for kw in kwarg_map:
        if kwargs.get(kw):
            os.environ[kwarg_map[kw]] = kwargs[kw]

    try:
        if kwargs.get("cloud_environment") and kwargs.get(
                "cloud_environment").startswith("http"):
            authority = kwargs["cloud_environment"]
        else:
            authority = getattr(
                KnownAuthorities,
                kwargs.get("cloud_environment", "AZURE_PUBLIC_CLOUD"))
        log.debug("AUTHORITY: %s", authority)
    except AttributeError as exc:
        log.error('Unknown authority presented for "cloud_environment": %s',
                  exc)
        authority = KnownAuthorities.AZURE_PUBLIC_CLOUD

    credential = DefaultAzureCredential(authority=authority)

    return credential
    def reset_policy_aad_secured(self):
        """Set a secured attestation policy on an AAD mode instance, specifying
        a default signing key and certificate to be used for all policy operations.
        """
        write_banner("reset_policy_aad_secured")
        # [BEGIN reset_aad_policy_secured]
        print("Set Secured Policy on an AAD mode attestation instance.")
        rsa_key = create_rsa_key()
        cert = create_x509_certificate(rsa_key, u"TestCertificate")

        # Create an administrative client, specifying a default key and certificate.
        # The key and certificate will be used for subsequent policy operations.
        with AttestationAdministrationClient(
                os.environ.get("ATTESTATION_AAD_URL"),
                DefaultAzureCredential(),
                signing_key=rsa_key,
                signing_certificate=cert,
        ) as admin_client:

            set_result, _ = admin_client.reset_policy(
                AttestationType.SGX_ENCLAVE)
            print("Policy Set Resolution: ", set_result.policy_resolution)
Example #10
0
def test_vscode_arguments(monkeypatch):
    monkeypatch.delenv(EnvironmentVariables.AZURE_AUTHORITY_HOST,
                       raising=False)
    monkeypatch.delenv(EnvironmentVariables.AZURE_TENANT_ID, raising=False)

    credential = DefaultAzureCredential.__module__ + ".VisualStudioCodeCredential"

    # DefaultAzureCredential shouldn't specify a default authority or tenant to VisualStudioCodeCredential
    with patch(credential) as mock_credential:
        DefaultAzureCredential()
    mock_credential.assert_called_once_with()

    tenant = {"tenant_id": "the-tenant"}

    with patch(credential) as mock_credential:
        DefaultAzureCredential(
            visual_studio_code_tenant_id=tenant["tenant_id"])
    mock_credential.assert_called_once_with(**tenant)

    # tenant id can also be specified in $AZURE_TENANT_ID
    with patch.dict(
            os.environ,
        {EnvironmentVariables.AZURE_TENANT_ID: tenant["tenant_id"]}):
        with patch(credential) as mock_credential:
            DefaultAzureCredential()
    mock_credential.assert_called_once_with(**tenant)

    # keyword argument should override environment variable
    with patch.dict(
            os.environ,
        {EnvironmentVariables.AZURE_TENANT_ID: "not-" + tenant["tenant_id"]}):
        with patch(credential) as mock_credential:
            DefaultAzureCredential(
                visual_studio_code_tenant_id=tenant["tenant_id"])
    mock_credential.assert_called_once_with(**tenant)

    # DefaultAzureCredential should pass the authority kwarg along
    authority = {"authority": "the-authority"}
    with patch(credential) as mock_credential:
        DefaultAzureCredential(**authority)
    mock_credential.assert_called_once_with(**authority)

    with patch(credential) as mock_credential:
        DefaultAzureCredential(
            visual_studio_code_tenant_id=tenant["tenant_id"], **authority)
    mock_credential.assert_called_once_with(**dict(authority, **tenant))
def sample_cascade_delete():

    farmbeats_endpoint = os.environ['FARMBEATS_ENDPOINT']

    credential = DefaultAzureCredential()

    client = FarmBeatsClient(endpoint=farmbeats_endpoint,
                             credential=credential)

    job_id_prefix = "cascade-delete-job"

    # Getting list of farmers modified in the last 7 days
    print("Getting list of recently modified farmer id's... ",
          end="",
          flush=True)
    farmers = client.farmers.list(
        min_last_modified_date_time=datetime.now(tz=UTC) - timedelta(days=7))
    farmer_ids = [farmer.id for farmer in farmers]
    print("Done")

    # Ask for the id of the farmer which is to be deleted.
    print(f"Recentely modified farmer id's:")
    print(*farmer_ids, sep="\n")
    farmer_id_to_delete = input(
        "Please enter the id of the farmer you wish to delete resources for: "
    ).strip()
    if farmer_id_to_delete not in farmer_ids:
        raise SystemExit("Entered id for farmer does not exist.")

    # Deleting the farmer and it's associated resources. Queuing the cascade delete job.

    job_id = f"{job_id_prefix}-{randint(0, 1000)}"
    print(f"Queuing cascade delete job {job_id}... ", end="", flush=True)
    cascade_delete_job_poller = client.farmers.begin_create_cascade_delete_job(
        job_id=job_id, farmer_id=farmer_id_to_delete)
    print("Queued. Waiting for completion... ", end="", flush=True)
    cascade_delete_job_poller.result()
    print("The job completed with status", cascade_delete_job_poller.status())
    def delete_old_tags(self):
        from azure.containerregistry import ContainerRegistryClient, TagOrder
        from azure.identity import DefaultAzureCredential

        # [START list_repository_names]
        account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
        credential = DefaultAzureCredential()
        client = ContainerRegistryClient(account_url, credential)

        for repository in client.list_repository_names():
            print(repository)
            # [END list_repository_names]

            # [START list_tag_properties]
            # Keep the three most recent tags, delete everything else
            tag_count = 0
            tags = client.list_tag_properties(
                repository, order_by=TagOrder.LAST_UPDATE_TIME_DESCENDING)
            for tag in tags[3:]:
                client.delete_tag(repository, tag.name)
            # [END list_tag_properties]

        client.close()
    def create_attestation_client_shared(self):
        """
        Instantiate an attestation client using client secrets to access the shared attestation provider.
        """
        write_banner("create_attestation_client_shared")
        # [START sharedclient_create]
        from azure.identity import DefaultAzureCredential
        from azure.security.attestation import AttestationClient

        shared_short_name = os.getenv("ATTESTATION_LOCATION_SHORT_NAME")
        shared_url = (
            "https://shared"
            + shared_short_name
            + "."
            + shared_short_name
            + ".attest.azure.net"
        )

        with AttestationClient(shared_url, DefaultAzureCredential()) as client:
            print("Retrieve OpenID metadata from: ", shared_url)
            openid_metadata = client.get_open_id_metadata()
            print(" Certificate URI: ", openid_metadata["jwks_uri"])
            print(" Issuer: ", openid_metadata["issuer"])
Example #14
0
 def encrypt_secret(self, secret, vault_name, keyid, subscription_id,
                    region):
     logger.info("secret to encrypt: {0}".format(secret))
     logger.info("keyid: {0}".format(keyid))
     logger.info("Azure subscription id: {0}".format(subscription_id))
     logger.info("Azure region: {0}".format(region))
     # https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#defaultazurecredential
     vault_url = "https://{0}.vault.azure.net/".format(vault_name)
     logger.info("vault url: ".format(vault_url))
     byte_literal_value = secret.encode()  # convert string to byte literal
     credential = DefaultAzureCredential()
     key_client = KeyClient(vault_url=vault_url, credential=credential)
     key = key_client.get_key(keyid)
     crypto_client = CryptographyClient(key, credential=credential)
     # the result holds the ciphertext and identifies the encryption key and algorithm used
     result = crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep,
                                    byte_literal_value)
     ciphertext = result.ciphertext
     print("-" * 50)
     print("ciphertext: {0}".format(ciphertext))
     print("result: {0}".format(result.key_id))
     print(result.algorithm)
     print("-" * 50)
Example #15
0
def import_image(repository, tags):
    mgmt_client = ContainerRegistryManagementClient(
        DefaultAzureCredential(),
        os.environ["CONTAINERREGISTRY_SUBSCRIPTION_ID"])
    registry_uri = "registry.hub.docker.com"
    rg_name = os.environ["CONTAINERREGISTRY_RESOURCE_GROUP"]
    registry_name = os.environ["CONTAINERREGISTRY_REGISTRY_NAME"]

    import_source = ImportSource(source_image=repository,
                                 registry_uri=registry_uri)

    import_params = ImportImageParameters(mode=ImportMode.Force,
                                          source=import_source,
                                          target_tags=tags)

    result = mgmt_client.registries.begin_import_image(
        rg_name,
        registry_name,
        parameters=import_params,
    )

    while not result.done():
        pass
    def basic_sample(self):

        from azure.containerregistry import ContainerRegistryClient
        from azure.identity import DefaultAzureCredential
        account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]

        # Instantiate the client
        client = ContainerRegistryClient(account_url, DefaultAzureCredential())
        with client:
            # Iterate through all the repositories
            for repository_name in client.list_repository_names():
                if repository_name == "hello-world":
                    # Create a repository object from the registry client
                    container_repository = client.get_repository(
                        repository_name)

                    with container_repository:
                        # Show all tags
                        for manifest in container_repository.list_manifests():
                            print(manifest.tags)

                    # [START delete_repository]
                    client.delete_repository("hello-world")
    def set_image_properties(self):
        # Create a new ContainerRegistryClient
        account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
        audience = "https://management.azure.com"
        credential = DefaultAzureCredential()
        client = ContainerRegistryClient(account_url,
                                         credential,
                                         audience=audience)

        # [START update_manifest_properties]
        # Set permissions on the v1 image's "latest" tag
        client.update_manifest_properties("library/hello-world",
                                          "latest",
                                          can_write=False,
                                          can_delete=False)
        # [END update_manifest_properties]
        # After this update, if someone were to push an update to `myacr.azurecr.io\hello-world:v1`, it would fail.
        # It's worth noting that if this image also had another tag, such as `latest`, and that tag did not have
        # permissions set to prevent reads or deletes, the image could still be overwritten. For example,
        # if someone were to push an update to `<registry endpoint>\hello-world:latest`
        # (which references the same image), it would succeed.

        client.close()
    def basic_sample(self):

        from azure.containerregistry import ContainerRegistryClient
        from azure.identity import DefaultAzureCredential

        # Instantiate the client
        client = ContainerRegistryClient(self.account_url,
                                         DefaultAzureCredential())
        with client:
            # Iterate through all the repositories
            for repository_name in client.list_repositories():
                if repository_name == "hello-world":
                    # Create a repository client from the registry client
                    repository_client = client.get_repository_client(
                        repository_name)

                    with repository_client:
                        # Show all tags
                        for tag in repository_client.list_tags():
                            print(tag.digest)

                    # [START delete_repository]
                    client.delete_repository("hello-world")
Example #19
0
    async def sms_token_credential_auth_async(self):
        # To use Azure Active Directory Authentication (DefaultAzureCredential) make sure to have
        # AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET as env variables.
        sms_client = SmsClient(self.endpoint, DefaultAzureCredential())

        async with sms_client:
            try:
                # calling send() with sms values
                sms_responses = await sms_client.send(
                    from_="<leased-phone-number>",
                    to=["<to-phone-number>"],
                    message="Hello World via SMS")
                sms_response = sms_responses[0]
                
                if (sms_response.successful):
                    print("Message with message id {} was successful sent to {}"
                    .format(sms_response.message_id, sms_response.to))
                else:
                    print("Message failed to send to {} with the status code {} and error: {}"
                    .format(sms_response.to, sms_response.http_status_code, sms_response.error_message))
            except Exception:
                print(Exception)
                pass
Example #20
0
    def attest_open_enclave_with_draft_policy(self):
        """
        Calls attest_open_enclave specifying a draft attestation policy.

        This functionality can be used to test attestation policies against real attestation
        collateral. This can be extremely helpful in debugging attestation policies.
        """
        write_banner("attest_open_enclave_with_draft_policy")
        oe_report = base64.urlsafe_b64decode(sample_open_enclave_report)
        runtime_data = base64.urlsafe_b64decode(sample_runtime_data)

        # [START attest_open_enclave_shared_draft]
        draft_policy = """
        version= 1.0;
        authorizationrules
        {
            [ type=="x-ms-sgx-is-debuggable", value==false ] &&
            [ type=="x-ms-sgx-product-id", value==1 ] &&
            [ type=="x-ms-sgx-svn", value>= 0 ] &&
            [ type=="x-ms-sgx-mrsigner", value=="2c1a44952ae8207135c6c29b75b8c029372ee94b677e15c20bd42340f10d41aa"]
                => permit();
        };
        issuancerules {
            c:[type=="x-ms-sgx-mrsigner"] => issue(type="My-MrSigner", value=c.value);
        };
        """
        print("Attest Open enclave using ", self.shared_url)
        print("Using draft policy:", draft_policy)
        with AttestationClient(self.shared_url,
                               DefaultAzureCredential()) as attest_client:
            response, token = attest_client.attest_open_enclave(
                oe_report,
                runtime_data=runtime_data,
                draft_policy=draft_policy)

            print("Token algorithm", token.algorithm)
            print("Issuer of token is: ", response.issuer)
def main():
    try:

        # Enable logging
        enable_logging()

        # Obtain a credential from the system-assigned managed identity
        msi_credential = DefaultAzureCredential()

        # Get the private key and certificate in PEM format from Key Vault
        secret_client = SecretClient(KEY_VAULT_URL, msi_credential)
        myazuresecret = secret_client.get_secret(CERTIFICATE_NAME)

        # Extract the private key and certificate from the response
        private_key = (re.findall("-----BEGIN.*END PRIVATE KEY-----",myazuresecret.value, re.DOTALL))[0]
        public_certificate = (re.findall("-----BEGIN CERTIFICATE.*END CERTIFICATE-----",myazuresecret.value, re.DOTALL))[0]

        # Create an X509 object and calculate the thumbprint
        cert = load_pem_x509_certificate(data=bytes(public_certificate, 'UTF-8'),backend=default_backend())
        thumbprint = (cert.fingerprint(hashes.SHA1()).hex())

        # Obtain an access token
        mytoken = get_sp_access_token(
            client_id = CLIENT_ID,
            client_credential = {
                "private_key":private_key,
                "thumbprint":thumbprint,
                "public_certificate":public_certificate
            },
            tenant_name = TENANT_NAME,
            scopes = SCOPES
        )

        print(mytoken)
    
    except Exception:
        logging.error('Execution error: ', exc_info=True)
Example #22
0
def start_round():
    matches = flask.request.get_json(
    )  # requires header content-type of "application/json"
    keyVaultName = os.environ["KEY_VAULT_NAME"]
    keyVault_URI = "https://" + keyVaultName + ".vault.azure.net"

    credential = DefaultAzureCredential()
    client = SecretClient(vault_url=keyVault_URI, credential=credential)
    data_access_key = client.get_secret("thecupstore-key")

    table_service = TableService(account_name='thecupstore',
                                 account_key=data_access_key.value)

    # Create the query string. Expects a list of matches, each of which is list containing 2 teams.
    query_string = ""
    for match in matches:
        for team in match:
            query_string += "Name eq \'" + team + "\' or "

    # Remove trailing ' or '
    query_string = query_string[:-4]

    team_stats = table_service.query_entities('Teams', filter=query_string)
    global current_round
    current_round = classes.round.Round(matches, team_stats)

    # Create the message queue for sending goal updates
    queue_name = "goalqueue"
    account_url = "https://thecupstore.queue.core.windows.net/"
    queueservice = QueueServiceClient(account_url=account_url,
                                      credential=credential)
    queueservice.create_queue(name=queue_name)
    global queueclient
    queueclient = QueueClient(account_url=account_url,
                              queue_name=queue_name,
                              credential=data_access_key.value)
    return '', 200
Example #23
0
    def attest_open_enclave_with_draft_failing_policy(self):
        """
        Sets a draft policy which is guaranteed to fail attestation with the
        sample test collateral to show how to manage attestation failures.
        """
        write_banner("attest_open_enclave_with_draft_failing_policy")
        oe_report = base64.urlsafe_b64decode(sample_open_enclave_report)
        runtime_data = base64.urlsafe_b64decode(sample_runtime_data)

        draft_policy = """
version= 1.0;
authorizationrules
{
    [ type=="x-ms-sgx-is-debuggable", value == false] => deny();
    [ type=="x-ms-sgx-product-id", value==1 ] &&
    [ type=="x-ms-sgx-svn", value>= 0 ] &&
    [ type=="x-ms-sgx-mrsigner", value=="2c1a44952ae8207135c6c29b75b8c029372ee94b677e15c20bd42340f10d41aa"]
        => permit();
};
issuancerules {
    c:[type=="x-ms-sgx-mrsigner"] => issue(type="My-MrSigner", value=c.value);
};
"""

        print("Attest Open enclave using ", self.shared_url)
        print("Using draft policy which will fail.:", draft_policy)
        with AttestationClient(self.shared_url,
                               DefaultAzureCredential()) as attest_client:
            try:
                attest_client.attest_open_enclave(oe_report,
                                                  runtime_data=runtime_data,
                                                  draft_policy=draft_policy)
                print("Unexpectedly passed attestation.")
            except HttpResponseError as err:
                print("Caught expected exception: ", err.message)
                print("Error is:", err.error.code)
                pass
Example #24
0
def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create a Key of type RSA.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create Key")
        key = client.create_key("keyName", "RSA")
        print("Key with name '{0}' created with key type '{1}'".format(
            key.name, key.key_material.kty))

        # Backups are good to have, if in case keys gets deleted accidentally.
        # For long term storage, it is ideal to write the backup to a file.
        print("\n1. Create a backup for an existing Key")
        key_backup = client.backup_key(key.name)
        print("Backup created for key with name '{0}'.".format(key.name))

        # The rsa key is no longer in use, so you delete it.
        client.delete_key(key.name)
        print("Deleted Key with name '{0}'".format(key.name))

        # In future, if the key is required again, we can use the backup value to restore it in the Key Vault.
        print("\n2. Restore the key using the backed up key bytes")
        key = client.restore_key(key_backup)
        print("Restored Key with name '{0}'".format(key.name))

    except HttpResponseError as e:
        print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
    def delete_tags(self):
        # [START list_repository_names]
        audience = "https://management.azure.com"
        account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
        credential = DefaultAzureCredential()
        client = ContainerRegistryClient(account_url,
                                         credential,
                                         audience=audience)

        for repository in client.list_repository_names():
            print(repository)
            # [END list_repository_names]

            # [START list_tag_properties]
            # Keep the three most recent tags, delete everything else
            tag_count = 0
            for tag in client.list_tag_properties(
                    repository, order_by=TagOrder.LAST_UPDATE_TIME_DESCENDING):
                tag_count += 1
                if tag_count > 3:
                    client.delete_tag(repository, tag.name)
            # [END list_tag_properties]

        client.close()
Example #26
0
    def __init__(
        self,
        credential=None,
        resource_id="https://management.azure.com/.default",
        **kwargs,
    ):
        """
        Wrap azure-identity credential to work with SDK that needs ADAL.

        Parameters
        ----------
        credential : [type], optional
            Any azure-identity credential, by default DefaultAzureCredential
        resource_id : str, optional
            The scope to use to get the token, by default
            "https://management.azure.com/.default"

        """
        super().__init__(None)
        self.token: Dict[str, Any] = {}
        if credential is None:
            credential = DefaultAzureCredential()
        self._policy = BearerTokenCredentialPolicy(credential, resource_id,
                                                   **kwargs)
    def set_policy_isolated_secured(self):
        """
        Set a secured attestation policy on an Isolated mode instance.

        This sample sets the signing key on the admin client object directly, rather
        than providing the signing key to individual APIs.

        For an isolated attestation instance, the new attestation policy must
        be signed with one of the existing policy management certificates.

        """
        write_banner("set_policy_isolated_secured")
        print("Set Secured Policy on an AAD mode attestation instance.")
        endpoint = os.environ.get("ATTESTATION_ISOLATED_URL")
        with AttestationAdministrationClient(
                endpoint,
                DefaultAzureCredential(),
                signing_key=self.isolated_key,
                signing_certificate=self.isolated_certificate,
        ) as admin_client:
            set_result, _ = admin_client.set_policy(
                AttestationType.SGX_ENCLAVE,
                """version= 1.0;authorizationrules{=> permit();};issuancerules {};""",
                validation_slack=1.0,
            )
            print("Policy Set Resolution: ", set_result.policy_resolution)
            print(
                "Resulting policy signer should match the input certificate:")
            print("Policy Signer: ", set_result.policy_signer.certificates[0])
            print("Certificate:   ", self.isolated_certificate)

            print(
                "Reset the attestation policy to the default now to avoid side effects."
            )
            # Reset the policy now that we're done.
            admin_client.reset_policy(AttestationType.SGX_ENCLAVE)
Example #28
0
def azkms_obj(key_id):
    """
    Return Azure Key Vault Object
    """
    # e.g of key_id https://kapitanbackend.vault.azure.net/keys/myKey/deadbeef
    if not cached.azkms_obj:

        url = urlparse(key_id)
        # ['', 'keys', 'myKey', 'deadbeef'] or ['kapitanbackend.vault.azure.net', 'keys', 'myKey', 'deadbeef']
        # depending on if key_id is prefixed with https://
        attrs = url.path.split("/")
        key_vault_uri = url.hostname or attrs[0]
        key_name = attrs[-2]
        key_version = attrs[-1]

        # If --verbose is set, show requests from azure
        if logger.getEffectiveLevel() > logging.DEBUG:
            logging.getLogger("azure").setLevel(logging.ERROR)
        credential = DefaultAzureCredential()
        key_client = KeyClient(vault_url=f"https://{key_vault_uri}", credential=credential)
        key = key_client.get_key(key_name, key_version)
        cached.azkms_obj = CryptographyClient(key, credential)

    return cached.azkms_obj
Example #29
0
    def setup_sample(self):
        """
        Provides common setup for Key Vault samples, such as creating rest clients, creating a sample resource group
        if needed, and ensuring proper access for the service principal.
         
        :return: None 
        """
        if not self._setup_complete:
            self.credential = DefaultAzureCredential()

            self.resource_mgmt_client = ResourceManagementClient(
                credential=self.credential,
                subscription_id=self.config.subscription_id
            )

            # ensure the intended resource group exists
            self.resource_mgmt_client.resource_groups.create_or_update(self.config.group_name, {'location': self.config.location})

            self.keyvault_mgmt_client = KeyVaultManagementClient(
                credential=self.credential,
                subscription_id=self.config.subscription_id
            )

            self._setup_complete = True
Example #30
0
def test_exclude_options():
    def assert_credentials_not_present(chain, *excluded_credential_classes):
        actual = {c.__class__ for c in chain.credentials}
        assert len(actual)

        # no unexpected credential is in the chain
        excluded = set(excluded_credential_classes)
        assert len(actual & excluded) == 0

        # only excluded credentials have been excluded from the default
        default = {c.__class__ for c in DefaultAzureCredential().credentials}
        assert actual <= default  # n.b. we know actual is non-empty
        assert default - actual <= excluded

    # when exclude_managed_identity_credential is set to True, check if ManagedIdentityCredential instance is not present
    credential = DefaultAzureCredential(
        exclude_managed_identity_credential=True)
    assert_credentials_not_present(credential, ManagedIdentityCredential)

    if SharedTokenCacheCredential.supported():
        credential = DefaultAzureCredential(
            exclude_shared_token_cache_credential=True)
        assert_credentials_not_present(credential, SharedTokenCacheCredential)

    credential = DefaultAzureCredential(exclude_cli_credential=True)
    assert_credentials_not_present(credential, AzureCliCredential)

    credential = DefaultAzureCredential(
        exclude_visual_studio_code_credential=True)
    assert_credentials_not_present(credential, VSCodeCredential)

    # interactive auth is excluded by default
    credential = DefaultAzureCredential(
        exclude_interactive_browser_credential=False)
    actual = {c.__class__ for c in credential.credentials}
    default = {c.__class__ for c in DefaultAzureCredential().credentials}
    assert actual - default == {InteractiveBrowserCredential}