Example #1
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);
        }
Example #2
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 #3
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);
        }
Example #4
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 #5
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);
            }
        }
 public override byte[] GetEndorsementKey()
 {
     return(_innerClient.GetEndorsementKey());
 }
        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 #8
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 #10
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);
            }
        }
Example #11
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);
                    }
                }
        }