private static async Task TestInvalidServiceCertificate(ProvisioningTransportHandler transport)
        {
            using (var security =
                       new SecurityProviderX509Certificate(Configuration.Provisioning.GetIndividualEnrollmentCertificate()))
            {
                ProvisioningDeviceClient provisioningDeviceClient = ProvisioningDeviceClient.Create(
                    Configuration.Provisioning.GlobalDeviceEndpointInvalidServiceCertificate,
                    "0ne00000001",
                    security,
                    transport);

                await provisioningDeviceClient.RegisterAsync().ConfigureAwait(false);
            }
        }
        // Provision a device via DPS, by sending the PnP model Id as DPS payload.
        private static async Task <DeviceRegistrationResult> ProvisionDeviceAsync(Parameters parameters, CancellationToken cancellationToken)
        {
            SecurityProvider             symmetricKeyProvider = new SecurityProviderSymmetricKey(parameters.DeviceId, parameters.DeviceSymmetricKey, null);
            ProvisioningTransportHandler mqttTransportHandler = new ProvisioningTransportHandlerMqtt();
            ProvisioningDeviceClient     pdc = ProvisioningDeviceClient.Create(parameters.DpsEndpoint, parameters.DpsIdScope,
                                                                               symmetricKeyProvider, mqttTransportHandler);

            var pnpPayload = new ProvisioningRegistrationAdditionalData
            {
                JsonData = $"{{ \"modelId\": \"{ModelId}\" }}",
            };

            return(await pdc.RegisterAsync(pnpPayload, cancellationToken));
        }
//        [DataRow(nameof(ProvisioningTransportHandlerAmqp), nameof(SecurityClientTpm), null, TransportFallbackType.WebSocketOnly)]
//        [DataRow(nameof(ProvisioningTransportHandlerAmqp), nameof(SecurityClientX509), X509EnrollmentType.Individual, TransportFallbackType.WebSocketOnly)]
//        [DataRow(nameof(ProvisioningTransportHandlerAmqp), nameof(SecurityClientX509), X509EnrollmentType.Group, TransportFallbackType.WebSocketOnly)]
//        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientTpm), null, TransportFallbackType.TcpOnly)]
//        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientX509), X509EnrollmentType.Individual, TransportFallbackType.TcpOnly)]
//        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientX509), X509EnrollmentType.Group, TransportFallbackType.TcpOnly)]
//        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientTpm), null, TransportFallbackType.WebSocketOnly)]
//        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientX509), X509EnrollmentType.Individual, TransportFallbackType.WebSocketOnly)]
//        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientX509), X509EnrollmentType.Group, TransportFallbackType.WebSocketOnly)]
        public async Task ProvisioningDeviceClient_ValidRegistrationId_Register_Ok(
            string transportType,
            string securityType,
            X509EnrollmentType?x509EnrollmentType,
            TransportFallbackType?transportFallback)
        {
            if (string.IsNullOrWhiteSpace(Configuration.Provisioning.IdScope))
            {
                Assert.Inconclusive();
            }

            using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, transportFallback))
                using (SecurityClient security = CreateSecurityClientFromName(securityType, x509EnrollmentType))
                {
                    _verboseLog.WriteLine("Creating device");

                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                        Configuration.Provisioning.IdScope,
                        security,
                        transport);

                    var cts = new CancellationTokenSource(PassingTimeoutMiliseconds);

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

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

                    Assert.AreEqual(ProvisioningRegistrationStatusType.Assigned, result.Status);
                    Assert.IsNotNull(result.AssignedHub);
                    Assert.IsNotNull(result.DeviceId);

                    Client.IAuthenticationMethod auth =
                        await CreateAuthenticationMethodFromSecurityClient(security, result.DeviceId, result.AssignedHub);

                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, Client.TransportType.Mqtt_Tcp_Only))
                    {
                        _log.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync();

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

                        _log.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync();
                    }
                }
        }
Example #4
0
        static async Task <EnrollmentDetails> EnrollDeviceAsync(string deviceId)
        {
            //we need a couple of parameters to start. How you get these values is up to you.
            //What is important is that the enrollment keys (Primary & secondary) should
            //be considered as secrets and stored as such. Just like certificate, it
            //will be the responsibility of Bell to deploy these credentials to the device
            //and keep them up to date
            string dpsEndpoint            = Environment.GetEnvironmentVariable("dpsEndpoint") ?? "global.azure-devices-provisioning.net";
            string dpsIdScope             = Environment.GetEnvironmentVariable("idscope") ?? "{Insert ID Scope Here}";
            string enrollmentKeyPrimary   = Environment.GetEnvironmentVariable("enrollmentKeyPrimary") ?? "{Insert Primary Enrollment Key Here}";
            string enrollmentKeySecondary = Environment.GetEnvironmentVariable("enrollmentKeySecondary") ?? "{Insert Seconday Enrollment Key Here}";

            //first, we need to create a device specific attestation key, derived from
            //the enrollment key. These attestation keys will ultimately become the credentials
            //for the device into Iot Hub when provisioned. They also serve as a way for
            //the DPS service to validate the device is trusted, without actually having to
            //send the enrollment group key across the network
            string attestationKeyPrimary   = ComputeDeviceAttestationKey(enrollmentKeyPrimary, deviceId);
            string attestationKeySecondary = ComputeDeviceAttestationKey(enrollmentKeySecondary, deviceId);

            //now, we can attempt to register this device with DPS
            using (SecurityProviderSymmetricKey keyProvider = new SecurityProviderSymmetricKey(deviceId, attestationKeyPrimary, attestationKeySecondary))
            {
                using (ProvisioningTransportHandlerAmqp transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provisioningClient = ProvisioningDeviceClient.Create(dpsEndpoint, dpsIdScope, keyProvider, transport);
                    DeviceRegistrationResult result             = await provisioningClient.RegisterAsync();

                    switch (result.Status)
                    {
                    case ProvisioningRegistrationStatusType.Assigned:
                        //device was successfully assigned by dps to an Iot Hub
                        return(new EnrollmentDetails()
                        {
                            DeviceId = deviceId,
                            IotHubEndpoint = result.AssignedHub,
                            Authentication = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, attestationKeyPrimary)
                        });

                    case ProvisioningRegistrationStatusType.Assigning:
                    case ProvisioningRegistrationStatusType.Disabled:
                    case ProvisioningRegistrationStatusType.Failed:
                    case ProvisioningRegistrationStatusType.Unassigned:
                    default:
                        return(null);
                    }
                }
            }
        }
        public async Task RunSampleAsync()
        {
            Console.WriteLine($"Initializing the device provisioning client...");

            // For individual enrollments, the first parameter must be the registration Id, where in the enrollment
            // the device Id is already chosen. However, for group enrollments the device Id can be requested by
            // the device, as long as the key has been computed using that value.
            // Also, the secondary could be included, but was left out for the simplicity of this sample.
            using var security = new SecurityProviderSymmetricKey(
                      _parameters.Id,
                      _parameters.PrimaryKey,
                      null);

            using var transportHandler = GetTransportHandler();

            ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                _parameters.GlobalDeviceEndpoint,
                _parameters.IdScope,
                security,
                transportHandler);

            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 symmetric key authentication for IoT Hub...");
            IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(
                result.DeviceId,
                security.GetPrimaryKey());

            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);

            Console.WriteLine("Finished.");
        }
Example #6
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("ProvisioningDeviceClientSymmetricKey <IDScope> <registrationID>");
                return(1);
            }

            if (string.IsNullOrWhiteSpace(s_registrationID) && (args.Length > 1))
            {
                s_registrationID      = args[1];
                s_certificateFileName = s_registrationID + ".pfx";
            }
            if (string.IsNullOrWhiteSpace(s_registrationID))
            {
                Console.WriteLine("ProvisioningDeviceClientSymmetricKey <IDScope> <registrationID>");
                return(1);
            }

            //X509Certificate2 certificate = LoadProvisioningCertificate();

            var myCertificate = new X509Certificate2(s_certificateFileName, "1234");
            var myChain       = new X509Certificate2Collection();

            //myChain.Import("azure-iot-test-only.chain.ca.cert.pem");

            using (var security = new SecurityProviderX509Certificate(myCertificate, myChain))

                // Select one of the available transports:
                // To optimize for size, reference only the protocols used by your application.
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                // using (var transport = new ProvisioningTransportHandlerHttp())
                // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
                // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.WebSocketOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);

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

            return(0);
        }
Example #7
0
        public ProvisioningDeviceClientWrapper(string s_idScope, string registrationId, string enrollmentGroupPrimaryKey, string enrollmentGroupSecondaryKey)
        {
            //Group enrollment flow, the primary and secondary keys are derived from the enrollment group keys and from the desired registration id
            string primaryKey   = ComputeDerivedSymmetricKey(Convert.FromBase64String(enrollmentGroupPrimaryKey), registrationId);
            string secondaryKey = ComputeDerivedSymmetricKey(Convert.FromBase64String(enrollmentGroupSecondaryKey), registrationId);

            SecurityProviderSymmetricKey     security  = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey);
            ProvisioningTransportHandlerAmqp transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly);

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


            _provClient = provClient;
            _security   = security;
        }
        private static async Task <DeviceRegistrationResult> RegisterDeviceAsync(Configuration configuration, SecurityProviderX509Certificate security)
        {
            using var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly);
            var provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, configuration.DpsIdScope, security, transport);
            DeviceRegistrationResult registrationResult = await provClient.RegisterAsync();

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

            if (registrationResult.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                throw new Exception("IoT Hub not assigned!");
            }
            return(registrationResult);
        }
        private void ConnectViaDPSX509(SecureString password, TransportType transportType)
        {
            string certPath = Environment.GetEnvironmentVariable("DEVICE_CERTIFICATE");

            if (certPath == null)
            {
                certPath = ConfigurationManager.AppSettings["DEVICE_CERTIFICATE"];
            }

            string scopeId = Environment.GetEnvironmentVariable("DPS_IDSCOPE");

            if (scopeId == null)
            {
                scopeId = ConfigurationManager.AppSettings["DPS_IDSCOPE"];
            }

            System.Security.Cryptography.X509Certificates.X509Certificate2 myCert =
                new System.Security.Cryptography.X509Certificates.X509Certificate2(certPath, password);

            using (var security = new SecurityProviderX509Certificate(myCert)) {
                using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
                // using (var transport = new ProvisioningTransportHandlerHttp())
                // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
                // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.WebSocketOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, scopeId, security, transport);

                    Console.WriteLine($"RegistrationID = {security.GetRegistrationID()}");
                    VerifyRegistrationIdFormat(security.GetRegistrationID());

                    Console.Write("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = provClient.RegisterAsync().Result;
                    deviceId = result.DeviceId;
                    Console.WriteLine($"{result.Status}");
                    Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

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

                    var auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, (security as SecurityProviderX509).GetAuthenticationCertificate());

                    deviceClient = DeviceClient.Create(result.AssignedHub, auth, transportType);
                }
            }
        }
        public static async Task <DeviceRegistrationResult> RegisterToIoTHubAsync(string primaryKey, string secondKey, string registeredId)
        {
            using var security  = new SecurityProviderSymmetricKey(registeredId, primaryKey, secondKey);
            using var transport = new ProvisioningTransportHandlerHttp();
            var provClient = ProvisioningDeviceClient.Create(
                GlobalDeviceEndpoint,
                IdScope,
                security,
                transport);

            // register into IoTHub
            var result = await provClient.RegisterAsync();

            Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
            return(result);
        }
Example #11
0
        private async Task TestInvalidServiceCertificate(ProvisioningTransportHandler transport)
        {
            string certificateSubject = $"E2E_{nameof(ProvisioningCertificateValidationE2ETest)}-{Guid.NewGuid()}";

            X509Certificate2Helper.GenerateSelfSignedCertificateFiles(certificateSubject, s_x509CertificatesFolder, Logger);

            using X509Certificate2 cert = X509Certificate2Helper.CreateX509Certificate2FromPfxFile(certificateSubject, s_x509CertificatesFolder);
            using var security          = new SecurityProviderX509Certificate(cert);
            var provisioningDeviceClient = ProvisioningDeviceClient.Create(
                TestConfiguration.Provisioning.GlobalDeviceEndpointInvalidServiceCertificate,
                "0ne00000001",
                security,
                transport);

            await provisioningDeviceClient.RegisterAsync().ConfigureAwait(false);
        }
Example #12
0
        private async Task <DeviceRegistrationResult> RegisterDeviceAsync(SecurityProviderSymmetricKey security)
        {
            _logger.LogInformation("{time} - Register device...", DateTimeOffset.Now);

            using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
            {
                ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(_globalDeviceEndpoint, _scopeID, security, transport);
                _logger.LogInformation($"{DateTimeOffset.Now} - RegistrationID = {security.GetRegistrationID()}");

                DeviceRegistrationResult result = await provClient.RegisterAsync();

                _logger.LogInformation($"{DateTimeOffset.Now} - ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                return(result);
            }
        }
Example #13
0
        public async Task <IoTHubDeviceClient> ProvisionDeviceAsync()
        {
            string             connectionKey;
            IoTHubDeviceClient iotHubClient = null;

            Console.WriteLine("Provisioning...");

            if (!String.IsNullOrEmpty(_deviceId) && !String.IsNullOrEmpty(s_sasKey) && !String.IsNullOrEmpty(s_idScope))
            {
                connectionKey = GenerateSymmetricKey();
                Console.WriteLine($"Connection Key : {connectionKey}");

                using (var securityProvider = new SecurityProviderSymmetricKey(_deviceId, connectionKey, null))
                    using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
                    {
                        _provClient = ProvisioningDeviceClient.Create(s_global_endpoint, s_idScope, securityProvider, transport);

                        // Sanity check
                        Console.WriteLine($"Device ID      : {securityProvider.GetRegistrationID()}");

                        DeviceRegistrationResult result = await _provClient.RegisterAsync().ConfigureAwait(false);

                        if (result.Status == ProvisioningRegistrationStatusType.Assigned)
                        {
                            Console.WriteLine($"Provisioned    : {result.Status}");
                            Console.WriteLine($"  Device ID    : {result.DeviceId}");
                            Console.WriteLine($"  IoT Hub      : {result.AssignedHub}");

                            IAuthenticationMethod authenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, securityProvider.GetPrimaryKey());

                            iotHubClient = new IoTHubDeviceClient(result.AssignedHub, authenticationMethod);
                        }
                        else
                        {
                            Console.WriteLine($"Err : Provisioning Failed {result.Status}");
                        }
                    }
            }
            else
            {
                Console.WriteLine("Please set following Environment Variables");
                Console.WriteLine("DPS_IDSCOPE : ID Scope");
                Console.WriteLine("SAS_KEY     : SAS Key");
            }

            return(iotHubClient);
        }
        private static async Task Main(string[] args)
        {
            Console.WriteLine("DPS auto provisioned device");

            if (args.Length == 0)
            {
                Console.WriteLine("Please pass ID Scope as first command line argument");
                return;
            }

            var idScope = args[0];

            var certificate = LoadCertificate();
            DeviceAuthenticationWithX509Certificate auth;
            string iotHub;

            using (var security = new SecurityProviderX509Certificate(certificate))
            {
                using (var transport = new ProvisioningTransportHandlerMqtt())
                {
                    var provisioningClient = ProvisioningDeviceClient.Create("global.azure-devices-provisioning.net",
                                                                             idScope, security, transport);

                    var provisioningResult = await provisioningClient.RegisterAsync();

                    Console.WriteLine(
                        $"Provisioning done - Assigned Hub: {provisioningResult.AssignedHub} - DeviceID {provisioningResult.DeviceId}");

                    auth = new DeviceAuthenticationWithX509Certificate(provisioningResult.DeviceId,
                                                                       security.GetAuthenticationCertificate());
                    iotHub = provisioningResult.AssignedHub;
                }
            }

            using (var deviceClient = DeviceClient.Create(iotHub, auth, TransportType.Mqtt))
            {
                await deviceClient.OpenAsync();

                await deviceClient.SendEventAsync(
                    new Message(Encoding.UTF8.GetBytes("Auto provisioned device was here")));

                await deviceClient.CloseAsync();

                Console.WriteLine("Sent message");
            }
        }
        static async Task <DeviceClient> CreateForDPS(AuthType authType)
        {
            var dpsScope   = Environment.GetEnvironmentVariable("DPSScope");
            var security   = new SecurityProviderX509Certificate(LoadCertificate());
            var transport  = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly);
            var provClient = ProvisioningDeviceClient.Create(dpsEndpoint, dpsScope, security, transport);

            DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);

            if (result.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                throw new Exception("Device could not be provisioned.");
            }
            var auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, security.GetAuthenticationCertificate());

            return(DeviceClient.Create(result.AssignedHub, auth, transportType));
        }
        public async Task RunSampleAsync()
        {
            Console.WriteLine($"Loading the certificate...");
            using X509Certificate2 certificate = LoadProvisioningCertificate();
            using var security = new SecurityProviderX509Certificate(certificate);

            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 X509 authentication for IoT Hub...");
            IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate(
                result.DeviceId,
                certificate);

            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);

            await iotClient.CloseAsync();

            Console.WriteLine("Finished.");
        }
        public static int Main(string[] args)
        {
            if (string.IsNullOrWhiteSpace(dpsIdScope) && (args.Length > 0))
            {
                dpsIdScope = args[0];
            }

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

            string primaryKey   = string.Empty;
            string secondaryKey = string.Empty;

            if (!String.IsNullOrEmpty(registrationId) && !String.IsNullOrEmpty(individualEnrollmentPrimaryKey) && !String.IsNullOrEmpty(individualEnrollmentSecondaryKey))
            {
                //Individual enrollment flow, the primary and secondary keys are the same as the individual enrollment keys
                primaryKey   = individualEnrollmentPrimaryKey;
                secondaryKey = individualEnrollmentSecondaryKey;
            }
            else
            {
                Console.WriteLine("Invalid configuration provided, must provide individual enrollment keys");
                return(-1);
            }

            using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey))



                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, dpsIdScope, security, transport);


                    var provisioningDeviceLogic = new ProvisioningDeviceLogic(provClient, security);
                    provisioningDeviceLogic.RunAsync().GetAwaiter().GetResult();
                }


            return(0);
        }
Example #18
0
        public static int Main(string[] args)
        {
            X509Certificate2 certificate = LoadProvisioningCertificate();

            using (var security = new SecurityProviderX509Certificate(certificate))
            {
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, dpsIdScope, security, transport);

                    var provisioningDeviceLogic = new ProvisioningDeviceLogic(provClient, security);
                    provisioningDeviceLogic.RunAsync().GetAwaiter().GetResult();
                }
            }

            return(0);
        }
        static async Task DeviceRegistration(string globalDeviceEndpoint, string IdScope, string enrollmentGroupSymmetricKey, string registrationId, string applicationId)
        {
            DeviceClient deviceClient;

            try
            {
                string deviceKey = ComputeDerivedSymmetricKey(Convert.FromBase64String(enrollmentGroupSymmetricKey), registrationId);

                using (var securityProvider = new SecurityProviderSymmetricKey(registrationId, deviceKey, null))
                {
                    using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                    {
                        ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(globalDeviceEndpoint, IdScope, securityProvider, transport);

                        DeviceRegistrationResult result = await provClient.RegisterAsync();

                        if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                        {
                            throw new ApplicationException($"DevID:{registrationId} AppID:{applicationId} Status:{result.Status} RegisterAsync failed");
                        }
                        Log.LogInformation("DevID:{registrationId} AppID:{applicationId} Assigned IoTHub:{assignedHub}", registrationId, applicationId, result.AssignedHub);

                        IAuthenticationMethod authentication = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (securityProvider as SecurityProviderSymmetricKey).GetPrimaryKey());

                        deviceClient = DeviceClient.Create(result.AssignedHub, authentication, TransportType.Amqp);

                        if (!DeviceClients.TryUpdate(registrationId, deviceClient, null))
                        {
                            Log.LogWarning("DevID:{registrationID} AppID:{applicationId} Device Registration TryUpdate failed", registrationId, applicationId);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (!DeviceClients.TryRemove(registrationId, out deviceClient))
                {
                    Log.LogWarning("DevID:{registrationID} AppID:{applicationId} Device Registration TryRemove failed", registrationId, applicationId);
                }

                Log.LogError(ex, "DevID:{registrationID} AppID:{applicationId} Device Registration failed", registrationId, applicationId);
                throw;
            }
        }
Example #20
0
        public static async Task <DeviceRegistrationResult> RegisterDeviceAsync(SecurityProviderSymmetricKey security)
        {
            Console.WriteLine("Register device...");

            using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
            {
                ProvisioningDeviceClient provClient =
                    ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, ScopeID, security, transport);

                Console.WriteLine($"RegistrationID = {security.GetRegistrationID()}");

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

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

                return(result);
            }
        }
Example #21
0
        internal static async Task <DeviceClient> ProvisionDeviceWithSasKeyAsync(string scopeId, string deviceId, string deviceKey, string modelId, ILogger log)
        {
            using (var transport = new ProvisioningTransportHandlerMqtt())
            {
                using (var security = new SecurityProviderSymmetricKey(deviceId, deviceKey, null))
                {
                    DeviceRegistrationResult provResult;
                    var provClient = ProvisioningDeviceClient.Create("global.azure-devices-provisioning.net", scopeId, security, transport);

                    if (!string.IsNullOrEmpty(modelId))
                    {
                        provResult = await provClient.RegisterAsync(GetProvisionPayload(modelId)).ConfigureAwait(false);
                    }
                    else
                    {
                        provResult = await provClient.RegisterAsync().ConfigureAwait(false);
                    }

                    log.LogInformation($"Provioning Result. Status [{provResult.Status}] SubStatus [{provResult.Substatus}]");

                    if (provResult.Status == ProvisioningRegistrationStatusType.Assigned)
                    {
                        log.LogWarning($"Device {provResult.DeviceId} in Hub {provResult.AssignedHub}");
                        log.LogInformation($"LastRefresh {provResult.LastUpdatedDateTimeUtc} RegistrationId {provResult.RegistrationId}");
                        var    csBuilder        = IotHubConnectionStringBuilder.Create(provResult.AssignedHub, new DeviceAuthenticationWithRegistrySymmetricKey(provResult.DeviceId, security.GetPrimaryKey()));
                        string connectionString = csBuilder.ToString();
                        return(await Task.FromResult(
                                   DeviceClient.CreateFromConnectionString(
                                       connectionString, TransportType.Mqtt,
                                       new ClientOptions()
                        {
                            ModelId = modelId
                        })));
                    }
                    else
                    {
                        string errorMessage = $"Device not provisioned. Message: {provResult.ErrorMessage}";
                        log.LogError(errorMessage);
                        throw new IotHubException(errorMessage);
                    }
                }
            }
        }
        private static async Task <DeviceRegistrationResult> RegisterDevice()
        {
            try
            {
                ConsoleWriteLine($"Will register device {deviceId}...", ConsoleColor.White);

                // using symmetric keys
                using var securityProvider = new SecurityProviderSymmetricKey(
                          registrationId: deviceId,
                          primaryKey: devicePrimaryKey,
                          secondaryKey: null);

                using var transportHandler = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly);

                // set up provisioning client for given device
                var provisioningDeviceClient = ProvisioningDeviceClient.Create(
                    globalDeviceEndpoint: provisioningGlobalDeviceEndpoint,
                    idScope: provisioningIdScope,
                    securityProvider: securityProvider,
                    transport: transportHandler);

                // register device
                var deviceRegistrationResult = await provisioningDeviceClient.RegisterAsync();

                ConsoleWriteLine($"Device {deviceId} registration result: {deviceRegistrationResult.Status}", ConsoleColor.White);

                if (deviceRegistrationResult.Status != ProvisioningRegistrationStatusType.Assigned)
                {
                    throw new Exception($"Failed to register device {deviceId}");
                }

                ConsoleWriteLine($"Device {deviceId} was assigned to hub '{deviceRegistrationResult.AssignedHub}'", ConsoleColor.White);
                ConsoleWriteLine();

                return(deviceRegistrationResult);
            }
            catch (Exception ex)
            {
                ConsoleWriteLine($"* ERROR * {ex.Message}", ConsoleColor.Red);
            }

            return(null);
        }
        private async Task <ProvisioningRegistrationStatusType> RunDeviceProvisioning()
        {
            ProvisioningRegistrationStatusType registrationStatus = ProvisioningRegistrationStatusType.Failed;
            string registrationId = Dns.GetHostName().ToLower();

            using (var security = new SecurityProviderTpmHsm(registrationId))
                using (var transport = new ProvisioningTransportHandlerHttp())
                {
                    Logger.Log($"ProvisioningClient RegisterAsync({registrationId})... ", LoggingLevel.Verbose);
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);

                    try
                    {
                        DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);

                        Logger.Log($"ProvisioningClient RegisterAsync Result = {result.Status}", LoggingLevel.Verbose);
                        Logger.Log($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}", LoggingLevel.Information);

                        if (result.Status == ProvisioningRegistrationStatusType.Assigned)
                        {
                            // The symmetric key of the assigned device identity is stored in TPM (this is done in ProvisioningDeviceClient.RegisterAsync()),
                            // for this use case (DM sample), we will need to store some other connection properties
                            // such as device Id and IoT Hub hostname in TPM for later use to establish IoTHub connection
                            try
                            {
                                var tpmDevice = new TpmDevice();
                                await tpmDevice.SetConnectionInfoAsync(-1, result.AssignedHub, result.DeviceId);
                            }
                            catch (Exception ex)
                            {
                                Logger.Log($"SetConnectionInfoAsync Error: Fail to set service Url in TPM. Exception: {ex.Message}", LoggingLevel.Error);
                            }
                        }
                        registrationStatus = result.Status;
                    }
                    catch (Exception ex)
                    {
                        Logger.Log($"ProvisioningClient Exception: {ex.Message}", LoggingLevel.Error);
                    }
                }
            return(registrationStatus);
        }
Example #24
0
        public static int Main(string[] args)
        {
            Console.WriteLine(ComputeDerivedSymmetricKey(Convert.FromBase64String("Iyppvm9WIbViax1XlyrqW+/5R1ZPf3hyhtXp2ctS+s5AbsvCvnH5ma0V1UxX2GBY+1MnVoQYtsrMppVn4H/I5Q=="), "10000000794b8d77"));
            if (string.IsNullOrWhiteSpace(idScope) && (args.Length > 0))
            {
                idScope = args[0];
            }

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

            string primaryKey   = "";
            string secondaryKey = "";

            if (!String.IsNullOrEmpty(registrationId) && !String.IsNullOrEmpty(enrollmentGroupPrimaryKey) && !String.IsNullOrEmpty(enrollmentGroupSecondaryKey))
            {
                primaryKey   = ComputeDerivedSymmetricKey(Convert.FromBase64String(enrollmentGroupPrimaryKey), registrationId);
                secondaryKey = ComputeDerivedSymmetricKey(Convert.FromBase64String(enrollmentGroupSecondaryKey), registrationId);
            }
            else
            {
                Console.WriteLine("Invalid configuration provided, must provide group enrollment keys or individual enrollment keys");
                return(-1);
            }

            using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey))

                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, idScope, security, transport);

                    var sample = new ProvisioningDevice(provClient, security);
                    sample.RunSampleAsync().GetAwaiter().GetResult();
                }
            Console.WriteLine("Enter any key to exit");
            Console.ReadLine();
            return(0);
        }
        static async Task Main(string[] args)
        {
            double temperature;

            using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey))
                using (var transport = new ProvisioningTransportHandlerMqtt())
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, idScope, security, transport);
                    DeviceRegistrationResult result     = await provClient.RegisterAsync();

                    IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (security as SecurityProviderSymmetricKey).GetPrimaryKey());

                    using (iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt))
                    {
                        await iotClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChangedAsync, null).ConfigureAwait(false); // callback for Device Twin updates
                        await DeviceTwinGetInitialState(iotClient);                                                                       // Get current cloud state of the device twin

                        while (true)
                        {
                            if (_temperature.IsAvailable)
                            {
                                try
                                {
                                    temperature = Math.Round(_temperature.Temperature.Celsius, 2);

                                    Console.WriteLine($"The CPU temperature is {temperature}");
                                    await SendMsgIotHub(temperature);

                                    roomState = (int)temperature > thermostat ? RoomAction.Cooling : (int)temperature < thermostat ? RoomAction.Heating : RoomAction.Green;
                                    await UpdateRoomAction(roomState);
                                    await UpdateRoomTemperature(temperature);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("exception msg: " + ex.Message);
                                }
                            }
                            Thread.Sleep(4000); // sleep for 10 seconds
                        }
                    }
                }
        }
        public bool AddDeviceWithDeviceProvisioningCertificateAsync(string deviceId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_dpsIdScope))
                {
                    Console.WriteLine("ProvisioningDeviceClientX509 <IDScope>");
                    return(false);
                }

                var certificate = LoadPrivateKey(@"C:/Users/abgaurav/IOT/solutions/device-provisioning/key.pfx");

                using (var security = new SecurityProviderX509Certificate(certificate))

                    using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                    {
                        ProvisioningDeviceClient provClient =
                            ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, _dpsIdScope, security, transport);

                        //var result = await provClient.RegisterAsync();

                        //Console.WriteLine($"Provisioning result: {result.Status}");

                        //if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                        //{
                        //    throw new InvalidOperationException("Something went wrong while trying to provision.");
                        //}

                        //this.assignedHub = result.AssignedHub;
                        //this.auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, security.GetAuthenticationCertificate());

                        var sample = new ProvisioningDeviceClientSample(provClient, security);
                        sample.RunSampleAsync().GetAwaiter().GetResult();
                    }
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
Example #27
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("ProvisioningDeviceClientX509 <IDScope>");
                return(1);
            }
#if false
            X509Certificate2 certificate = LoadProvisioningCertificate();
            using (var security = new SecurityProviderX509Certificate(certificate))
#else
            var myCertificate = new X509Certificate2(s_certificateFileName, "1234");
            var myChain       = new X509Certificate2Collection();

            // Comment out the below line if you do not have a .p7b file (e.g. if you generated certificates using the tool below)
            //myChain.Import("myChain.p7b");

            using (var security = new SecurityProviderX509Certificate(myCertificate, myChain))
#endif
                // Select one of the available transports:
                // To optimize for size, reference only the protocols used by your application.
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                // using (var transport = new ProvisioningTransportHandlerHttp())
                // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
                //using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.WebSocketOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);

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

            return(0);
        }
Example #28
0
        public async Task RunSampleAsync()
        {
            Console.WriteLine($"Initializing the device provisioning client...");

            using var security = new SecurityProviderSymmetricKey(
                      this.id,
                      this.key,
                      null);

            using var transportHandler = new ProvisioningTransportHandlerAmqp();

            ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                "global.azure-devices-provisioning.net",
                this.idScope,
                security,
                transportHandler);

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

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

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

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

            Console.WriteLine("Creating symmetric key authentication for IoT Hub...");
            IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(
                device.DeviceId,
                security.GetPrimaryKey());

            await SendDeviceToCloudMessagesAsync(device, auth);

            Console.WriteLine("Finished.");
        }
Example #29
0
        public async Task Provision()
        {
            var certificate = LoadPrivateKey("key.pfx");

            using (var securityProvider = new SecurityProviderX509Certificate(certificate))
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    var client = ProvisioningDeviceClient.Create("global.azure-devices-provisioning.net", this.scopeId, securityProvider, transport);

                    var result = await client.RegisterAsync();

                    Console.WriteLine($"Provisioning result: {result.Status}");

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        throw new InvalidOperationException("Something went wrong while trying to provision.");
                    }

                    this.assignedHub = result.AssignedHub;
                    this.auth        = new DeviceAuthenticationWithX509Certificate(result.DeviceId, securityProvider.GetAuthenticationCertificate());
                }
        }
Example #30
0
        //        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientTpm), null, TransportFallbackType.TcpOnly)]
        //        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientX509), X509EnrollmentType.Individual, TransportFallbackType.TcpOnly)]
        //        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientX509), X509EnrollmentType.Group, TransportFallbackType.TcpOnly)]
        //        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientTpm), null, TransportFallbackType.WebSocketOnly)]
        //        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientX509), X509EnrollmentType.Individual, TransportFallbackType.WebSocketOnly)]
        //        [DataRow(nameof(ProvisioningTransportHandlerMqtt), nameof(SecurityClientX509), X509EnrollmentType.Group, TransportFallbackType.WebSocketOnly)]
        public async Task ProvisioningDeviceClient_InvalidIdScope_Register_Fail(
            string transportType,
            string securityType,
            X509EnrollmentType?x509EnrollmentType,
            TransportFallbackType?transportFallback)
        {
            using (ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportType, transportFallback))
                using (SecurityClient security = CreateSecurityClientFromName(securityType, x509EnrollmentType))
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                        InvalidIDScope,
                        security,
                        transport);

                    var cts = new CancellationTokenSource(FailingTimeoutMiliseconds);

                    var exception = await Assert.ThrowsExceptionAsync <ProvisioningTransportException>(
                        () => provClient.RegisterAsync(cts.Token)).ConfigureAwait(false);

                    _log.WriteLine($"Exception: {exception}");
                }
        }