コード例 #1
0
        public static int Main(string[] args)
        {
            if (string.IsNullOrWhiteSpace(s_idScope) && (args.Length > 0))
            {
                s_idScope = args[0];
            }

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

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

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

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

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

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

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

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

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

            return(0);
        }
コード例 #2
0
        public static async Task RunSample()
        {
            // Replace the following type with SecurityProviderTpmHsm() to use a real TPM2.0 device.
            Console.WriteLine("Starting TPM simulator.");
            SecurityProviderTpmSimulator.StartSimulatorProcess();

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

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

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

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

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

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

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

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

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

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

                        Console.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync();
                    }
                }
        }
コード例 #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);
        }
コード例 #4
0
        private SecurityProvider CreateSecurityProviderFromName(string name, X509EnrollmentType?x509Type)
        {
            _verboseLog.WriteLine($"{nameof(CreateSecurityProviderFromName)}({name})");

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

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

                return(tpmSim);

            case nameof(SecurityProviderX509Certificate):

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

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

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

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

            throw new NotSupportedException($"Unknown security type: '{name}'.");
        }
コード例 #5
0
        public static int Main(string[] args)
        {
            if (string.IsNullOrWhiteSpace(s_idScope) && (args.Length > 0))
            {
                s_idScope = args[0];
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                security?.Dispose();
            }

            Console.WriteLine("Finished.");
        }
コード例 #7
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);
                    }
                }
        }