Example #1
0
        static async Task Main(string[] args)
        {
            var invalidIotHubAddress = "invalid.azure.devices.com";
            var validGatewayAddress  = "localhost";
            var deviceId             = "valid-device-id";

            Console.WriteLine("Connecting to the TPM simulator...");
            var tpmDevice            = ConnectToTpmSimulator();
            var securityProvider     = new SecurityProviderTpmHsm(deviceId, tpmDevice);
            var authenticationMethod = new DeviceAuthenticationWithTpm(deviceId, securityProvider);

            Console.WriteLine("Connecting to invalid IoT Hub address directly...");
            using (var deviceClient = DeviceClient.Create(invalidIotHubAddress, authenticationMethod))
            {
                var cts = new CancellationTokenSource(1000);
                try { await deviceClient.OpenAsync(cts.Token); }
                catch (Exception ex) { Console.WriteLine($"Swallowed expected exception '{ex.Message}'."); }
                finally
                {
                    await deviceClient.CloseAsync();
                }
            }

            Console.WriteLine("Connecting to invalid IoT Hub address via valid gateway...");
            using (var deviceClient = DeviceClient.Create(invalidIotHubAddress, validGatewayAddress, authenticationMethod))
            {
                var cts = new CancellationTokenSource(1000);
                await deviceClient.OpenAsync(cts.Token); // This is the call that ultimately triggers the NullReferenceException.

                await deviceClient.CloseAsync();
            }
        }
Example #2
0
        static async Task Register(SecurityProviderTpmHsm security)
        {
            Console.WriteLine("Press ENTER when ready to execute Registration.");
            Console.WriteLine("------------------");
            Console.ReadLine();

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

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

                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("\tAssigned Hub: :  ");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write("{0} ", result.AssignedHub);
                    Console.WriteLine(Environment.NewLine);

                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("\tDeviceId: :  ");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write("{0} ", result.DeviceId);
                    Console.WriteLine(Environment.NewLine);
                }
                catch (Exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("The registration has failed");
                    Console.ForegroundColor = ConsoleColor.White;
                    throw;
                }
            }
        }
Example #3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Extracting endorsement key...");
            var    tpmProvider = new SecurityProviderTpmHsm(RegistrationId);
            string base64EK    = Convert.ToBase64String(tpmProvider.GetEndorsementKey());

            Console.WriteLine(base64EK);
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _innerClient?.Dispose();
                _innerClient = null;

                _tpmDevice?.Dispose();
                _tpmDevice = null;
            }
        }
Example #5
0
        public SecurityProviderTpmSimulator(string registrationId)
            : base(registrationId)
        {
            _tcpTpmDevice = new TcpTpmDevice(SimulatorAddress, SimulatorPort);
            _tcpTpmDevice.Connect();
            _tcpTpmDevice.PowerCycle();

            _tpm2 = new Tpm2(_tcpTpmDevice);
            _tpm2.Startup(Su.Clear);

            _innerClient = new SecurityProviderTpmHsm(GetRegistrationID(), _tcpTpmDevice);
        }
        public SecurityProviderTpmSimulator(string registrationId) : base(registrationId)
        {
            _tpmDevice = new TcpTpmDevice(SimulatorAddress, SimulatorPort);
            _tpmDevice.Connect();
            _tpmDevice.SetSocketTimeout(TcpTpmDeviceTimeoutSeconds);
            _tpmDevice.PowerCycle();

            using (var tpm2 = new Tpm2(_tpmDevice))
            {
                tpm2.Startup(Su.Clear);
            }

            _innerClient = new SecurityProviderTpmHsm(GetRegistrationID(), _tpmDevice);
        }
Example #7
0
        static int Main(string[] args)
        {
            // The CTOR of Tpm2Lib prints errors to STDOUT, not very nice
            var savedOutStream = Console.Out;

            Console.SetOut(Console.Error);
            using (var security = new SecurityProviderTpmHsm(string.Empty))
            {
                Console.SetOut(savedOutStream);

                string base64EK = Convert.ToBase64String(security.GetEndorsementKey());
                Console.WriteLine($"{base64EK}");
            }

            return(0);
        }
Example #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);
        }
        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);
        }
        public async Task RunSampleAsync()
        {
            Console.WriteLine("Initializing security using the local TPM...");
            using SecurityProviderTpm 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);

            await iotClient.CloseAsync();

            Console.WriteLine("Finished.");
        }
Example #11
0
        static int Main(string[] args)
        {
            if ((args.Length > 0))
            {
                _registrationId = args[0];

                var r = new Regex("^[a-z0-9-]*$");
                if (!r.IsMatch(_registrationId))
                {
                    throw new FormatException("Invalid registrationId: The registration ID is alphanumeric, lowercase, and may contain hyphens");
                }
            }

            if (string.IsNullOrWhiteSpace(_idScope) && (args.Length > 1))
            {
                _idScope = args[1];
            }

            using (var security = new SecurityProviderTpmHsm(_registrationId))
            {
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("$EndorsementKey=\"");
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("{0}", Convert.ToBase64String(security.GetEndorsementKey()));
                Console.Write("\"");
                Console.WriteLine(Environment.NewLine);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("$RegistrationId=\"");
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("{0}", security.GetRegistrationID());
                Console.Write("\"");
                Console.WriteLine(Environment.NewLine);

                if (!String.IsNullOrEmpty(_idScope))
                {
                    Register(security).Wait();
                }
            }
            return(0);
        }
Example #12
0
        public int OnExecute()
        {
            try
            {
                if (RegistrationId == "" || RegistrationId == null)
                {
                    RegistrationId = Prompt.GetString("Please type the RegistrationID: ", null, ConsoleColor.Red, ConsoleColor.Black);
                }


                using (var security = new SecurityProviderTpmHsm(RegistrationId))
                {
                    string base64EK = Convert.ToBase64String(security.GetEndorsementKey());
                    Console.WriteLine(base64EK);
                }

                return(0);
            }
            catch (Exception err)
            {
                Console.WriteLine($@"Error: {err}");
                return(-1);
            }
        }
Example #13
0
        public static async Task <int> Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Environment.CurrentDirectory)
                                .AddJsonFile("appSettings.json", optional: false)
                                .AddJsonFile("appSettings.development.json", optional: true)
                                .Build();

            var dpsConnection = configuration.GetConnectionString("Dps");

            if (String.IsNullOrWhiteSpace(dpsConnection))
            {
                Console.WriteLine("The connectionstring of the DPS service is not provided");
                Console.WriteLine("Make sure that the appsettings.json file contains an entry for the ConnectionStrings:Dps setting");

                return(-1);
            }

            Console.WriteLine("Provision your TPM");
            Console.WriteLine("------------------");
            Console.WriteLine("Usage: ProvisionTpm <IDScope> <RegistrationID> <DeviceID> <SkipTest:Y|N>");
            Console.WriteLine("Run this 'As Adminsitrator' or 'SU'");

            if (string.IsNullOrWhiteSpace(_idScope) && (args.Length > 0))
            {
                _idScope = args[0];
            }

            if (string.IsNullOrWhiteSpace(_registrationId) && (args.Length > 1))
            {
                _registrationId = args[1];
            }

            if (string.IsNullOrWhiteSpace(_deviceId) && (args.Length > 2))
            {
                _deviceId = args[2].ToUpper();
            }

            if (string.IsNullOrWhiteSpace(_skipTest) && (args.Length > 3))
            {
                _skipTest = args[3].ToUpper();
            }

            if (string.IsNullOrWhiteSpace(_idScope) ||
                string.IsNullOrWhiteSpace(_registrationId) ||
                string.IsNullOrWhiteSpace(_deviceId) ||
                string.IsNullOrWhiteSpace(_skipTest))
            {
                Console.WriteLine("Check if the parameters are corrent: ProvisionTpm <IDScope> <RegistrationID> <DeviceID> <SkipTest:Y|N>");
                return(1);
            }

            if (RegistrationId.IsValid(_registrationId) == false)
            {
                Console.WriteLine("Invalid registrationId: The registration ID is alphanumeric, lowercase, and may contain hyphens");
                return(1);
            }

            using (var security = new SecurityProviderTpmHsm(_registrationId))
            {
                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 individual enrollment' then fill in the following:");

                    Console.WriteLine($"\tMechanism: TPM");
                    Console.WriteLine($"\tEndorsement key: {base64EK}");
                    Console.WriteLine($"\tRegistration ID: {_registrationId}");
                    Console.WriteLine($"\tSwitch over to the IoT Edge device enrollemnt is needed");
                    Console.WriteLine($"\tIoT Hub Device ID: {_registrationId} (or any other valid DeviceID)");

                    Console.WriteLine("Press enter to enroll this device in DPS");
                    Console.ReadLine();

                    await EnrollDeviceInDpsAsync(dpsConnection, _registrationId, base64EK, _deviceId);

                    Console.WriteLine("");
                    Console.WriteLine("The device is enrolled in DPS");
                    Console.WriteLine($"\tCheck if the correct IoT Hub is selected");
                    Console.WriteLine($"\tFinally, Save this individual enrollment");
                    Console.WriteLine();
                    Console.WriteLine("Press ENTER when ready. This will start finalizing the registration on your TPM");
                    Console.ReadLine();

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

                    var client = new ProvisioningDeviceTpmClient(provClient, security, _skipTest);
                    await client.RunTestAsync();

                    Console.WriteLine("The registration is finalized on the TPM");

                    if (_skipTest != "Y")
                    {
                        Console.WriteLine("The connection is tested by sending a test message");
                    }
                }

                return(0);
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            DeviceRegistrationResult result;

            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                using (var security = new SecurityProviderTpmHsm(RegistrationId))
                    using (var transport = new ProvisioningTransportHandlerHttp())
                    {
                        string base64EK = Convert.ToBase64String(security.GetEndorsementKey());

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

                        result = provClient.RegisterAsync().ConfigureAwait(false).GetAwaiter().GetResult();

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

                        azureIoTHubClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt);
                    }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"DeviceClient.Create with TPM info failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("Restart", RestartAsync, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device method handler configuration failed:{ex.Message}");
                return;
            }

            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                Debug.Print($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                if (deviceTwin.Properties.Desired.Contains("TimerDue"))
                {
                    timerDue = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerDue"].ToString());
                }

                if (deviceTwin.Properties.Desired.Contains("TimerPeriod"))
                {
                    timerPeriod = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerPeriod"].ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Sensor due or period configuration retrieval failed using default:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            //enable task to continue running in background
            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
Example #15
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 static int Main(string[] args)
        {
            Console.WriteLine("Provision your TPM");
            Console.WriteLine("------------------");
            Console.WriteLine("Usage: ProvisionTpm <IDScope> <RegistrationID> <SkipTest:Y|N>");
            Console.WriteLine("Run this 'As Adminsitrator' or 'SU'");

            if (string.IsNullOrWhiteSpace(_idScope) && (args.Length > 0))
            {
                _idScope = args[0];
            }

            if (string.IsNullOrWhiteSpace(_registrationId) && (args.Length > 1))
            {
                _registrationId = args[1];
            }

            if (string.IsNullOrWhiteSpace(_skipTest) && (args.Length > 2))
            {
                _skipTest = args[2].ToUpper();
            }

            if (string.IsNullOrWhiteSpace(_idScope) ||
                string.IsNullOrWhiteSpace(_registrationId) ||
                string.IsNullOrWhiteSpace(_skipTest))
            {
                Console.WriteLine("Check if the parameters are corrent: ProvisionTpm <IDScope> <RegistrationID> <SkipTest:Y|N>");
                return(1);
            }

            using (var security = new SecurityProviderTpmHsm(_registrationId))
                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 individual enrollment' then fill in the following:");

                    Console.WriteLine($"\tMechanism: TPM");
                    Console.WriteLine($"\tEndorsement key: {base64EK}");
                    Console.WriteLine($"\tRegistration ID: {_registrationId}");
                    Console.WriteLine($"\tSwitch over to the IoT Edge device enrollemnt is needed");
                    Console.WriteLine($"\tIoT Hub Device ID: {_registrationId} (or any other valid DeviceID)");
                    Console.WriteLine($"\tCheck if the correct IoT Hub is selected");
                    Console.WriteLine($"\tFinally, Save this individual enrollment");
                    Console.WriteLine();
                    Console.WriteLine("Press ENTER when ready. This will start finalizing the registration on your TPM");
                    Console.ReadLine();

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

                    var client = new ProvisioningDeviceTpmClient(provClient, security, _skipTest);
                    client.RunTestAsync().GetAwaiter().GetResult();

                    Console.WriteLine("The registration is finalized on the TPM");

                    if (_skipTest != "Y")
                    {
                        Console.WriteLine("The connection is tested by sending a test message");
                    }
                }

            return(0);
        }
Example #17
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);
                    }
                }
        }