【问题标题】:Azure IoT Hub Unauthorized Access for Additional DevicesAzure IoT Hub 未经授权访问其他设备
【发布时间】:2020-04-05 04:43:34
【问题描述】:

我在尝试使用 x509 证书通过 DPS 将第二台设备注册到 IoT 中心时遇到问题。我的根证书颁发机构在 DPS 和 IoT 中心(通过 openssl 生成)上都存在并经过验证。至于客户端证书,一旦应用程序启动(如果不存在),我将在下面的代码中生成它。困扰我的是每台设备都正确注册到 Azure DPS,但只有第一台设备获得授权和注册。我在创建客户端证书期间可能正在做的事情搞砸了?在设备注册到 IoT 中心的过程中,也会在此行中发现错误:

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

添加错误:

2019/12/16 09:37:38.309|错误|尝试启动服务时发现错误设备无法注册@IoT Hub:设备无法正确配置:AMQP 传输异常 | Tidel.DeviceAgent.DeviceAgent |

客户端证书生成

        X509Certificate2 caRootCertificate;
        X509Store caStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
        caStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

        X509Certificate2Collection signerCollection = (X509Certificate2Collection)caStore.Certificates.Find(X509FindType.FindByIssuerName, "CERTNAME", true);

        caStore.Close();

        if (signerCollection.Count != 0)
        {
            caRootCertificate = signerCollection[0];

            using (var rsa = RSA.Create())
            {
                rsa.KeySize = 2048;

                var clientCertificateRequest = new CertificateRequest($"CN={_writableOptions.Value.RegistrationId}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

                clientCertificateRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));

                var issuerSubjectKey = caRootCertificate.Extensions["Subject Key Identifier"].RawData;
                var segment = new ArraySegment<byte>(issuerSubjectKey, 2, issuerSubjectKey.Length - 2);
                var authorityKeyIdentifier = new byte[segment.Count + 4];

                authorityKeyIdentifier[0] = 0x30;
                authorityKeyIdentifier[1] = 0x16;
                authorityKeyIdentifier[2] = 0x80;
                authorityKeyIdentifier[3] = 0x14; 
                segment.CopyTo(authorityKeyIdentifier, 4);
                clientCertificateRequest.CertificateExtensions.Add(new X509Extension("2.5.29.35", authorityKeyIdentifier, false));


                var sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddDnsName(_writableOptions.Value.RegistrationId);
                var sanExtension = sanBuilder.Build();
                clientCertificateRequest.CertificateExtensions.Add(sanExtension);

                clientCertificateRequest.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.2") }, false));
                clientCertificateRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(clientCertificateRequest.PublicKey, false));

                var notBefore = DateTimeOffset.UtcNow.AddDays(-1);

                if (notBefore < caRootCertificate.NotBefore)
                {
                    notBefore = new DateTimeOffset(caRootCertificate.NotBefore);
                }

                var notAfter = DateTimeOffset.UtcNow.AddDays(365);

                if (notAfter > caRootCertificate.NotAfter)
                {
                    notAfter = new DateTimeOffset(caRootCertificate.NotAfter);
                }

                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var unixTime = Convert.ToInt64((DateTime.UtcNow - epoch).TotalSeconds);
                var serial = BitConverter.GetBytes(unixTime);

                using (var cert = clientCertificateRequest.Create(caRootCertificate, notBefore, notAfter, serial))
                {
                    X509Certificate2 client = cert.CopyWithPrivateKey(rsa);

                    return await Task.FromResult(client);
                }
            }
        }
        else
        {
            throw new FileNotFoundException($"Could not find a root certificate.");
        }

设备注册到 DPS

    Attestation attestation = X509Attestation.CreateFromClientCertificates(new X509Certificate2(certificate.Export(X509ContentType.Cert)));

    IndividualEnrollment individualEnrollment = new IndividualEnrollment(_writableOptions.Value.RegistrationId, attestation)
    {
        DeviceId = _writableOptions.Value.DeviceId,
        ProvisioningStatus = ProvisioningStatus.Enabled
    };

    individualEnrollmentResult = await _provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

设备注册到 IOT HUB

using (var certificatePassword = new X509Certificate2(certificate.GetRawCertData(), _writableOptions.Value.CertPass))
{
    using (var security = new SecurityProviderX509Certificate(certificatePassword))
    {
        using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
        {
            ProvisioningDeviceClient provisioningDeviceClient = ProvisioningDeviceClient.Create(_writableOptions.Value.AzureEndpoint, _writableOptions.Value.IdScope, security, transport);
            DeviceRegistrationResult result = await provisioningDeviceClient.RegisterAsync().ConfigureAwait(false);
            IAuthenticationMethod authenticationMethod = new DeviceAuthenticationWithX509Certificate(result.DeviceId, certificate);
            DeviceClient deviceClient = DeviceClient.Create(result.AssignedHub, authenticationMethod, TransportType.Amqp_Tcp_Only);

            return await Task.FromResult(deviceClient);
       }
     }
}

【问题讨论】:

    标签: c# azure x509certificate .net-core-3.0


    【解决方案1】:

    我发现了这个问题。在商店中生成证书时,我使用 FindByIssuerName 来定位证书。

    X509Certificate2Collection signerCollection = (X509Certificate2Collection)caStore.Certificates.Find(X509FindType.FindByIssuerName, "CERTNAME", true);
    

    进一步调查后,商店中有两个名称完全相同的证书。问题:MMC 管理单元只显示一个证书。环顾四周后,有人建议在某个地方对商店运行 storerepair 命令。运行 store repair 命令后,我可以在 MMC 中看到这两个证书,并且能够删除有问题的证书,从而防止检测到有效证书。

    Windows 版本:Windows Embedded 8.1 Industry Pro

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 2017-04-15
      • 2021-06-07
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多