public bool AddDeviceProvisioningService(string deviceId)
        {
            try
            {
                Console.WriteLine("Starting TPM simulator.");
                using (var security = new SecurityProviderTpmSimulator(RegistrationId))

                    using (var transport = new ProvisioningTransportHandlerAmqp())
                    {
                        Console.WriteLine("Extracting endorsement key.");
                        string base64EK = Convert.ToBase64String(Encoding.ASCII.GetBytes(TpmEndorsementKey));//security.GetEndorsementKey());

                        Console.WriteLine($"\tRegistration ID: {RegistrationId}");
                        Console.WriteLine($"\tEndorsement key: {base64EK}");
                        Console.WriteLine("\tDevice ID: iothubtpmdevice1");
                        Console.WriteLine();
                        Console.WriteLine("Press ENTER when ready.");
                        Console.ReadLine();

                        ProvisioningDeviceClient provClient =
                            ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, _dpsIdScope, security, transport);

                        var sample = new ProvisioningDeviceClientSample(provClient, security);
                        sample.RunSampleAsync().GetAwaiter().GetResult();

                        return(true);
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
Exemplo n.º 2
0
        public async Task ProvisioningDeviceClient_InvalidRegistrationId_TpmRegister_Fail(string transportType)
        {
            if (!ConfigurationFound())
            {
                _log.WriteLine("Provisioning test configuration not found. Result inconclusive.");
                return;
            }

            using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, TransportFallbackType.TcpOnly))
                using (SecurityProvider security = new SecurityProviderTpmSimulator("invalidregistrationid"))
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                        s_globalDeviceEndpoint,
                        Configuration.Provisioning.IdScope,
                        security,
                        transport);

                    var cts = new CancellationTokenSource(FailingTimeoutMiliseconds);

                    _log.WriteLine("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync(cts.Token).ConfigureAwait(false);

                    _log.WriteLine($"{result.Status}");

                    Assert.AreEqual(ProvisioningRegistrationStatusType.Failed, result.Status);
                    Assert.IsNull(result.AssignedHub);
                    Assert.IsNull(result.DeviceId);
                    Assert.AreEqual("Not Found", result.ErrorMessage);
                    Assert.AreEqual(0x00062ae9, result.ErrorCode);
                }
        }
Exemplo n.º 3
0
        public static int Main(string[] args)
        {
            if (string.IsNullOrWhiteSpace(s_idScope) && (args.Length > 0))
            {
                s_idScope = args[0];
            }

            if (string.IsNullOrWhiteSpace(s_idScope))
            {
                Console.WriteLine("ProvisioningDeviceClientTpm <IDScope>");
                return(1);
            }

            // Remove if a real TPM is being used.
            Console.WriteLine("Starting TPM simulator.");
            SecurityProviderTpmSimulator.StartSimulatorProcess();

            // Replace the following type with SecurityProviderTpmHsm() to use a real TPM2.0 device.
            using (var security = new SecurityProviderTpmSimulator(s_registrationID))

                // Select one of the available transports:
                // To optimize for size, reference only the protocols used by your application.
                using (var transport = new ProvisioningTransportHandlerHttp())
                // using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                // using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.WebSocketOnly))
                {
                    // Note that the TPM simulator will create an NVChip file containing the simulated TPM state.
                    Console.WriteLine("Extracting endorsement key.");
                    string base64EK = Convert.ToBase64String(security.GetEndorsementKey());

                    Console.WriteLine(
                        "In your Azure Device Provisioning Service please go to 'Manage enrollments' and select " +
                        "'Individual Enrollments'. Select 'Add' then fill in the following:");

                    Console.WriteLine("\tMechanism: TPM");
                    Console.WriteLine($"\tEndorsement key: {base64EK}");
                    Console.WriteLine($"\tRegistration ID: {s_registrationID}");
                    Console.WriteLine($"\tDevice ID: {s_registrationID} (or any other valid DeviceID)");
                    Console.WriteLine();
                    Console.WriteLine("Press ENTER once enrollment has been created.");
                    Console.ReadLine();

                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);

                    var sample = new ProvisioningDeviceClientSample(provClient, security);
                    sample.RunSampleAsync().GetAwaiter().GetResult();
                }

            // Remove if a real TPM is being used.
            Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Stopping TPM simulator.");
            SecurityProviderTpmSimulator.StopSimulatorProcess();

            return(0);
        }
Exemplo n.º 4
0
        public static async Task RunSample()
        {
            // Replace the following type with SecurityProviderTpmHsm() to use a real TPM2.0 device.
            Console.WriteLine("Starting TPM simulator.");
            SecurityProviderTpmSimulator.StartSimulatorProcess();

            using (var security = new SecurityProviderTpmSimulator(RegistrationId))
                using (var transport = new ProvisioningTransportHandlerHttp())
                // using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    // Note that the TPM simulator will create an NVChip file containing the simulated TPM state.
                    Console.WriteLine("Extracting endorsement key.");
                    string base64EK = Convert.ToBase64String(security.GetEndorsementKey());

                    Console.WriteLine(
                        "In your Azure Device Provisioning Service please go to 'Manage enrollments' and select " +
                        "'Individual Enrollments'. Select 'Add' then fill in the following:");

                    Console.WriteLine("\tMechanism: TPM");
                    Console.WriteLine($"\tRegistration ID: {RegistrationId}");
                    Console.WriteLine($"\tEndorsement key: {base64EK}");
                    Console.WriteLine("\tDevice ID: iothubtpmdevice1 (or any other valid DeviceID)");
                    Console.WriteLine();
                    Console.WriteLine("Press ENTER when ready.");
                    Console.ReadLine();

                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);

                    Console.Write("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync();

                    Console.WriteLine($"{result.Status}");
                    Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        return;
                    }

                    var auth = new DeviceAuthenticationWithTpm(result.DeviceId, security);

                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Http1))
                    {
                        Console.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync();

                        Console.WriteLine("DeviceClient SendEventAsync.");
                        await iotClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("TestMessage")));

                        Console.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync();
                    }
                }
        }
Exemplo n.º 5
0
        private async Task <IndividualEnrollment> CreateIndividualEnrollment(ProvisioningServiceClient provisioningServiceClient)
        {
            var    tpmSim      = new SecurityProviderTpmSimulator(Configuration.Provisioning.TpmDeviceRegistrationId);
            string base64Ek    = Convert.ToBase64String(tpmSim.GetEndorsementKey());
            var    attestation = new TpmAttestation(base64Ek);
            IndividualEnrollment individualEnrollment =
                new IndividualEnrollment(
                    RegistrationId,
                    attestation);

            IndividualEnrollment result = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

            return(result);
        }
Exemplo n.º 6
0
        private async Task <SecurityProvider> CreateSecurityProviderFromName(string name, X509EnrollmentType?x509Type)
        {
            _verboseLog.WriteLine($"{nameof(CreateSecurityProviderFromName)}({name})");

            switch (name)
            {
            case nameof(SecurityProviderTpmHsm):
                var tpmSim = new SecurityProviderTpmSimulator(Configuration.Provisioning.TpmDeviceRegistrationId);

                string base64Ek       = Convert.ToBase64String(tpmSim.GetEndorsementKey());
                string registrationId = Configuration.Provisioning.TpmDeviceRegistrationId;


                var provisioningService = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString);

                _log.WriteLine($"Getting enrollment: RegistrationID = {registrationId}");
                IndividualEnrollment enrollment = await provisioningService.GetIndividualEnrollmentAsync(registrationId).ConfigureAwait(false);

                var attestation = new TpmAttestation(base64Ek);
                enrollment.Attestation = attestation;
                _log.WriteLine($"Updating enrollment: RegistrationID = {registrationId} EK = '{base64Ek}'");
                await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(enrollment).ConfigureAwait(false);

                return(tpmSim);

            case nameof(SecurityProviderX509Certificate):

                X509Certificate2           certificate = null;
                X509Certificate2Collection collection  = null;
                switch (x509Type)
                {
                case X509EnrollmentType.Individual:
                    certificate = Configuration.Provisioning.GetIndividualEnrollmentCertificate();
                    break;

                case X509EnrollmentType.Group:
                    certificate = Configuration.Provisioning.GetGroupEnrollmentCertificate();
                    collection  = Configuration.Provisioning.GetGroupEnrollmentChain();
                    break;

                default:
                    throw new NotSupportedException($"Unknown X509 type: '{x509Type}'");
                }

                return(new SecurityProviderX509Certificate(certificate, collection));
            }

            throw new NotSupportedException($"Unknown security type: '{name}'.");
        }
        public static async Task <IndividualEnrollment> CreateIndividualEnrollment(ProvisioningServiceClient provisioningServiceClient, AttestationType attestationType, ReprovisionPolicy reprovisionPolicy, AllocationPolicy allocationPolicy, CustomAllocationDefinition customAllocationDefinition, ICollection <string> iotHubsToProvisionTo, DeviceCapabilities capabilities)
        {
            string               registrationId = AttestationTypeToString(attestationType) + "-registration-id-" + Guid.NewGuid();
            Attestation          attestation;
            IndividualEnrollment individualEnrollment;

            switch (attestationType)
            {
            case AttestationType.Tpm:
                using (var tpmSim = new SecurityProviderTpmSimulator(registrationId))
                {
                    string base64Ek            = Convert.ToBase64String(tpmSim.GetEndorsementKey());
                    var    provisioningService = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString);
                    individualEnrollment = new IndividualEnrollment(registrationId, new TpmAttestation(base64Ek))
                    {
                        Capabilities               = capabilities,
                        AllocationPolicy           = allocationPolicy,
                        ReprovisionPolicy          = reprovisionPolicy,
                        CustomAllocationDefinition = customAllocationDefinition,
                        IotHubs = iotHubsToProvisionTo
                    };

                    IndividualEnrollment enrollment = await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

                    attestation            = new TpmAttestation(base64Ek);
                    enrollment.Attestation = attestation;
                    return(await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(enrollment).ConfigureAwait(false));
                }

            case AttestationType.SymmetricKey:
                string primaryKey   = CryptoKeyGenerator.GenerateKey(32);
                string secondaryKey = CryptoKeyGenerator.GenerateKey(32);
                attestation = new SymmetricKeyAttestation(primaryKey, secondaryKey);
                break;

            case AttestationType.x509:
            default:
                throw new NotSupportedException("Test code has not been written for testing this attestation type yet");
            }

            individualEnrollment = new IndividualEnrollment(registrationId, attestation);
            individualEnrollment.Capabilities = capabilities;
            individualEnrollment.CustomAllocationDefinition = customAllocationDefinition;
            individualEnrollment.ReprovisionPolicy          = reprovisionPolicy;
            individualEnrollment.IotHubs          = iotHubsToProvisionTo;
            individualEnrollment.AllocationPolicy = allocationPolicy;
            return(await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false));
        }
Exemplo n.º 8
0
        public static async Task <int> Main(string[] args)
        {
            // Parse application parameters
            Parameters parameters            = null;
            ParserResult <Parameters> result = Parser.Default.ParseArguments <Parameters>(args)
                                               .WithParsed(parsedParams =>
            {
                parameters = parsedParams;
            })
                                               .WithNotParsed(errors =>
            {
                Environment.Exit(1);
            });

            // This sample provides a way to get the endorsement key (EK) required in creation of the individual enrollment
            if (parameters.GetTpmEndorsementKey)
            {
                if (parameters.UseTpmSimulator)
                {
                    Console.WriteLine("Starting TPM simulator...");
                    SecurityProviderTpmSimulator.StartSimulatorProcess();
                }

                using var security = new SecurityProviderTpmHsm(null);
                Console.WriteLine($"Your EK is {Convert.ToBase64String(security.GetEndorsementKey())}");

                if (parameters.UseTpmSimulator)
                {
                    SecurityProviderTpmSimulator.StopSimulatorProcess();
                }

                return(0);
            }

            // For a normal run of this sample, IdScope and RegistrationId are required
            if (string.IsNullOrWhiteSpace(parameters.IdScope) ||
                string.IsNullOrWhiteSpace(parameters.RegistrationId))
            {
                Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(result, null, null));
                Environment.Exit(1);
            }

            var sample = new ProvisioningDeviceClientSample(parameters);
            await sample.RunSampleAsync();

            return(0);
        }
Exemplo n.º 9
0
        private SecurityProvider CreateSecurityProviderFromName(string name, X509EnrollmentType?x509Type)
        {
            _verboseLog.WriteLine($"{nameof(CreateSecurityProviderFromName)}({name})");

            switch (name)
            {
            case nameof(SecurityProviderTpmHsm):
                var tpmSim = new SecurityProviderTpmSimulator(Configuration.Provisioning.TpmDeviceRegistrationId);
                SecurityProviderTpmSimulator.StartSimulatorProcess();

                _log.WriteLine(
                    $"RegistrationID = {Configuration.Provisioning.TpmDeviceRegistrationId} " +
                    $"EK = '{Convert.ToBase64String(tpmSim.GetEndorsementKey())}'");

                return(tpmSim);

            case nameof(SecurityProviderX509Certificate):

                X509Certificate2           certificate = null;
                X509Certificate2Collection collection  = null;
                switch (x509Type)
                {
                case X509EnrollmentType.Individual:
                    certificate = Configuration.Provisioning.GetIndividualEnrollmentCertificate();
                    break;

                case X509EnrollmentType.Group:
                    certificate = Configuration.Provisioning.GetGroupEnrollmentCertificate();
                    collection  = Configuration.Provisioning.GetGroupEnrollmentChain();
                    break;

                default:
                    throw new NotSupportedException($"Unknown X509 type: '{x509Type}'");
                }

                return(new SecurityProviderX509Certificate(certificate, collection));
            }

            throw new NotSupportedException($"Unknown security type: '{name}'.");
        }
Exemplo n.º 10
0
        private async Task <SecurityProvider> CreateSecurityProviderFromName(AttestationType attestationType, EnrollmentType?enrollmentType, string groupId, ReprovisionPolicy reprovisionPolicy, AllocationPolicy allocationPolicy, CustomAllocationDefinition customAllocationDefinition, ICollection <string> iothubs, DeviceCapabilities capabilities = null)
        {
            _verboseLog.WriteLine($"{nameof(CreateSecurityProviderFromName)}({attestationType})");

            var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString);

            switch (attestationType)
            {
            case AttestationType.Tpm:
                string registrationId = AttestationTypeToString(attestationType) + "-registration-id-" + Guid.NewGuid();
                var    tpmSim         = new SecurityProviderTpmSimulator(registrationId);

                string base64Ek = Convert.ToBase64String(tpmSim.GetEndorsementKey());


                var provisioningService = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString);

                _log.WriteLine($"Getting enrollment: RegistrationID = {registrationId}");
                IndividualEnrollment individualEnrollment = new IndividualEnrollment(registrationId, new TpmAttestation(base64Ek))
                {
                    AllocationPolicy = allocationPolicy, ReprovisionPolicy = reprovisionPolicy, IotHubs = iothubs, CustomAllocationDefinition = customAllocationDefinition, Capabilities = capabilities
                };
                IndividualEnrollment enrollment = await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

                var attestation = new TpmAttestation(base64Ek);
                enrollment.Attestation = attestation;
                _log.WriteLine($"Updating enrollment: RegistrationID = {registrationId} EK = '{base64Ek}'");
                await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(enrollment).ConfigureAwait(false);

                return(tpmSim);

            case AttestationType.x509:

                X509Certificate2           certificate = null;
                X509Certificate2Collection collection  = null;
                switch (enrollmentType)
                {
                case EnrollmentType.Individual:
                    certificate = Configuration.Provisioning.GetIndividualEnrollmentCertificate();
                    break;

                case EnrollmentType.Group:
                    certificate = Configuration.Provisioning.GetGroupEnrollmentCertificate();
                    collection  = Configuration.Provisioning.GetGroupEnrollmentChain();
                    break;

                default:
                    throw new NotSupportedException($"Unknown X509 type: '{enrollmentType}'");
                }

                return(new SecurityProviderX509Certificate(certificate, collection));

            case AttestationType.SymmetricKey:
                switch (enrollmentType)
                {
                case EnrollmentType.Group:
                    EnrollmentGroup symmetricKeyEnrollmentGroup = await CreateEnrollmentGroup(provisioningServiceClient, AttestationType.SymmetricKey, groupId, reprovisionPolicy, allocationPolicy, customAllocationDefinition, iothubs, capabilities).ConfigureAwait(false);

                    Assert.IsTrue(symmetricKeyEnrollmentGroup.Attestation is SymmetricKeyAttestation);
                    SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation)symmetricKeyEnrollmentGroup.Attestation;
                    string registrationIdSymmetricKey  = IdPrefix + Guid.NewGuid();
                    string primaryKeyEnrollmentGroup   = symmetricKeyAttestation.PrimaryKey;
                    string secondaryKeyEnrollmentGroup = symmetricKeyAttestation.SecondaryKey;

                    string primaryKeyIndividual   = ProvisioningE2ETests.ComputeDerivedSymmetricKey(Convert.FromBase64String(primaryKeyEnrollmentGroup), registrationIdSymmetricKey);
                    string secondaryKeyIndividual = ProvisioningE2ETests.ComputeDerivedSymmetricKey(Convert.FromBase64String(secondaryKeyEnrollmentGroup), registrationIdSymmetricKey);

                    return(new SecurityProviderSymmetricKey(registrationIdSymmetricKey, primaryKeyIndividual, secondaryKeyIndividual));

                case EnrollmentType.Individual:
                    IndividualEnrollment symmetricKeyEnrollment = await CreateIndividualEnrollment(provisioningServiceClient, AttestationType.SymmetricKey, reprovisionPolicy, allocationPolicy, customAllocationDefinition, iothubs, capabilities).ConfigureAwait(false);

                    Assert.IsTrue(symmetricKeyEnrollment.Attestation is SymmetricKeyAttestation);
                    symmetricKeyAttestation = (SymmetricKeyAttestation)symmetricKeyEnrollment.Attestation;

                    registrationIdSymmetricKey = symmetricKeyEnrollment.RegistrationId;
                    string primaryKey   = symmetricKeyAttestation.PrimaryKey;
                    string secondaryKey = symmetricKeyAttestation.SecondaryKey;
                    return(new SecurityProviderSymmetricKey(registrationIdSymmetricKey, primaryKey, secondaryKey));

                default:
                    throw new NotSupportedException("Unrecognized enrollment type");
                }

            default:
                throw new NotSupportedException("Unrecognized attestation type");
            }

            throw new NotSupportedException($"Unknown security type: '{attestationType}'.");
        }
Exemplo n.º 11
0
        public static int Main(string[] args)
        {
            if (string.IsNullOrWhiteSpace(s_idScope) && (args.Length > 0))
            {
                s_idScope = args[0];
            }

            if (string.IsNullOrWhiteSpace(s_idScope))
            {
                Console.WriteLine("ProvisioningDeviceClientTpm <IDScope>");
                return(1);
            }

            // DPS registration Id should be unique among enrollments.
            // Such registration Id could be from TPM or any other unique identity, such as device serial number
            // As an example, we use hostname in this sample as the unique registration Id
            // A valid DPS registration Id contains only lower case alphanumeric letters and hyphens
            var    culture        = new CultureInfo("en-US", false);
            string RegistrationId = Dns.GetHostName().ToLower(culture).Select(i => (Char.IsLetterOrDigit(i) || (i == '-'))? i.ToString(culture): "-").ToArray().Aggregate((a, b) => a + b);

#if _USE_TPMSIMULATOR
            // Remove if a real TPM is being used.
            Console.WriteLine("Starting TPM simulator.");
            SecurityProviderTpmSimulator.StartSimulatorProcess();

            // Replace the following type with SecurityProviderTpmHsm() to use a real TPM2.0 device.
            using (var security = new SecurityProviderTpmSimulator(RegistrationId))
#else
            using (var security = new SecurityProviderTpmHsm(RegistrationId))
#endif

                // Select one of the available transports:
                // To optimize for size, reference only the protocols used by your application.
                using (var transport = new ProvisioningTransportHandlerHttp())
                // using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                // using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.WebSocketOnly))
                {
                    // Note that the TPM simulator will create an NVChip file containing the simulated TPM state.
                    Console.WriteLine("Extracting endorsement key.");
                    string base64EK = Convert.ToBase64String(security.GetEndorsementKey());

                    Console.WriteLine(
                        "In your Azure Device Provisioning Service please go to 'Manage enrollments' and select " +
                        "'Individual Enrollments'. Select 'Add' then fill in the following:");

                    Console.WriteLine("\tMechanism: TPM");
                    Console.WriteLine($"\tRegistration ID: {RegistrationId}");
                    Console.WriteLine($"\tEndorsement key: {base64EK}");
                    Console.WriteLine($"\tDevice ID: {RegistrationId} (or any other valid DeviceID)");
                    Console.WriteLine();
                    Console.WriteLine("Press ENTER when ready.");
                    Console.ReadLine();

                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);

                    var sample = new ProvisioningDeviceClientSample(provClient, security);
                    sample.RunSampleAsync().GetAwaiter().GetResult();
                }

            return(0);
        }
        public async Task RunSampleAsync()
        {
            SecurityProviderTpm security = null;

            try
            {
                if (_parameters.UseTpmSimulator)
                {
                    Console.WriteLine("Starting TPM simulator...");
                    SecurityProviderTpmSimulator.StartSimulatorProcess();
                    security = new SecurityProviderTpmSimulator(_parameters.RegistrationId);
                }
                else
                {
                    Console.WriteLine("Initializing security using the local TPM...");
                    security = new SecurityProviderTpmHsm(_parameters.RegistrationId);
                }

                Console.WriteLine($"Initializing the device provisioning client...");

                using var transport = GetTransportHandler();
                ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                    _parameters.GlobalDeviceEndpoint,
                    _parameters.IdScope,
                    security,
                    transport);

                Console.WriteLine($"Initialized for registration Id {security.GetRegistrationID()}.");

                Console.WriteLine("Registering with the device provisioning service... ");
                DeviceRegistrationResult result = await provClient.RegisterAsync();

                Console.WriteLine($"Registration status: {result.Status}.");
                if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                {
                    Console.WriteLine($"Registration status did not assign a hub, so exiting this sample.");
                    return;
                }

                Console.WriteLine($"Device {result.DeviceId} registered to {result.AssignedHub}.");

                Console.WriteLine("Creating TPM authentication for IoT Hub...");
                IAuthenticationMethod auth = new DeviceAuthenticationWithTpm(result.DeviceId, security);

                Console.WriteLine($"Testing the provisioned device with IoT Hub...");
                using DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, _parameters.TransportType);

                Console.WriteLine("Sending a telemetry message...");
                using var message = new Message(Encoding.UTF8.GetBytes("TestMessage"));
                await iotClient.SendEventAsync(message);
            }
            finally
            {
                if (_parameters.UseTpmSimulator)
                {
                    SecurityProviderTpmSimulator.StopSimulatorProcess();
                }

                security?.Dispose();
            }

            Console.WriteLine("Finished.");
        }
        public static async Task <IndividualEnrollment> CreateIndividualEnrollmentAsync(
            ProvisioningServiceClient provisioningServiceClient,
            string registrationId,
            AttestationMechanismType attestationType,
            X509Certificate2 authenticationCertificate,
            ReprovisionPolicy reprovisionPolicy,
            AllocationPolicy allocationPolicy,
            CustomAllocationDefinition customAllocationDefinition,
            ICollection <string> iotHubsToProvisionTo,
            DeviceCapabilities capabilities,
            MsTestLogger logger)
        {
            Attestation          attestation;
            IndividualEnrollment individualEnrollment;
            IndividualEnrollment createdEnrollment = null;

            switch (attestationType)
            {
            case AttestationMechanismType.Tpm:
                using (var tpmSim = new SecurityProviderTpmSimulator(registrationId))
                {
                    string base64Ek = Convert.ToBase64String(tpmSim.GetEndorsementKey());
                    individualEnrollment = new IndividualEnrollment(registrationId, new TpmAttestation(base64Ek))
                    {
                        Capabilities               = capabilities,
                        AllocationPolicy           = allocationPolicy,
                        ReprovisionPolicy          = reprovisionPolicy,
                        CustomAllocationDefinition = customAllocationDefinition,
                        IotHubs = iotHubsToProvisionTo
                    };

                    IndividualEnrollment temporaryCreatedEnrollment = null;
                    await RetryOperationHelper
                    .RetryOperationsAsync(
                        async() =>
                    {
                        temporaryCreatedEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
                    },
                        s_provisioningServiceRetryPolicy,
                        s_retryableExceptions,
                        logger)
                    .ConfigureAwait(false);

                    if (temporaryCreatedEnrollment == null)
                    {
                        throw new ArgumentException($"The enrollment entry with registration Id {registrationId} could not be created, exiting test.");
                    }

                    attestation = new TpmAttestation(base64Ek);
                    temporaryCreatedEnrollment.Attestation = attestation;

                    await RetryOperationHelper
                    .RetryOperationsAsync(
                        async() =>
                    {
                        createdEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(temporaryCreatedEnrollment).ConfigureAwait(false);
                    },
                        s_provisioningServiceRetryPolicy,
                        s_retryableExceptions,
                        logger)
                    .ConfigureAwait(false);

                    if (createdEnrollment == null)
                    {
                        throw new ArgumentException($"The enrollment entry with registration Id {registrationId} could not be updated, exiting test.");
                    }

                    return(createdEnrollment);
                }

            case AttestationMechanismType.SymmetricKey:
                string primaryKey   = CryptoKeyGenerator.GenerateKey(32);
                string secondaryKey = CryptoKeyGenerator.GenerateKey(32);
                attestation = new SymmetricKeyAttestation(primaryKey, secondaryKey);
                break;

            case AttestationMechanismType.X509:
                attestation = X509Attestation.CreateFromClientCertificates(authenticationCertificate);
                break;

            default:
                throw new NotSupportedException("Test code has not been written for testing this attestation type yet");
            }

            individualEnrollment = new IndividualEnrollment(registrationId, attestation)
            {
                Capabilities               = capabilities,
                AllocationPolicy           = allocationPolicy,
                ReprovisionPolicy          = reprovisionPolicy,
                CustomAllocationDefinition = customAllocationDefinition,
                IotHubs = iotHubsToProvisionTo,
            };

            await RetryOperationHelper
            .RetryOperationsAsync(
                async() =>
            {
                createdEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
            },
                s_provisioningServiceRetryPolicy,
                s_retryableExceptions,
                logger)
            .ConfigureAwait(false);

            if (createdEnrollment == null)
            {
                throw new ArgumentException($"The enrollment entry with registration Id {registrationId} could not be created, exiting test.");
            }

            return(createdEnrollment);
        }
Exemplo n.º 14
0
        public static async Task RunSample()
        {
            // DPS registration Id should be unique among enrollments.
            // Such registration Id could be from TPM or any other unique identity, such as device serial number
            // As an example, we use hostname in this sample as the unique registration Id
            // A valid DPS registration Id contains only lower case alphanumeric letters and '-'
            string RegistrationId = Dns.GetHostName().ToLower().Select(i => (Char.IsLetterOrDigit(i) || (i == '-'))? i.ToString(): "-").ToArray().Aggregate((a, b) => a + b);

#if _USE_TPMSIMULATOR
            Console.WriteLine("Starting TPM simulator.");
            SecurityProviderTpmSimulator.StartSimulatorProcess();

            // Replace the following type with SecurityProviderTpmHsm() to use a real TPM2.0 device.
            using (var security = new SecurityProviderTpmSimulator(RegistrationId))
#else
            using (var security = new SecurityProviderTpmHsm(RegistrationId))
#endif
                using (var transport = new ProvisioningTransportHandlerHttp())
                // using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    // Note that the TPM simulator will create an NVChip file containing the simulated TPM state.
                    Console.WriteLine("Extracting endorsement key.");
                    string base64EK       = Convert.ToBase64String(security.GetEndorsementKey());
                    string registrationId = security.GetRegistrationID();

                    Console.WriteLine(
                        "In your Azure Device Provisioning Service please go to 'Manage enrollments' and select " +
                        "'Individual Enrollments'. Select 'Add' then fill in the following:");

                    Console.WriteLine("\tMechanism: TPM");
                    Console.WriteLine($"\tRegistration ID: {registrationId}");
                    Console.WriteLine($"\tEndorsement key: {base64EK}");
                    Console.WriteLine();
                    Console.WriteLine("Press ENTER when ready.");
                    Console.ReadLine();

                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);

                    Console.Write("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);

                    Console.WriteLine($"{result.Status}");
                    Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        return;
                    }

                    var auth = new DeviceAuthenticationWithTpm(result.DeviceId, security);

                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Http1))
                    {
                        Console.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync().ConfigureAwait(false);

                        Console.WriteLine("DeviceClient SendEventAsync.");
                        await iotClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false);

                        Console.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync().ConfigureAwait(false);
                    }
                }
        }