Esempio n. 1
0
        public void TestInvalidConstructorInputs()
        {
            X509Certificate2 tlsCertificate        = CertificateHelper.GenerateSelfSignedCert("TestCert");
            var          transportSettings         = new DefaultTransportSettings(Scheme, HostName, Port, tlsCertificate);
            AmqpSettings amqpSettings              = AmqpSettingsProvider.GetDefaultAmqpSettings(IotHubHostName, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>(), Mock.Of <ILinkHandlerProvider>(), Mock.Of <IConnectionProvider>(), new NullCredentialsStore());
            var          transportListenerProvider = new Mock <ITransportListenerProvider>();

            Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(null, amqpSettings, transportListenerProvider.Object));
            Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(transportSettings, null, transportListenerProvider.Object));
            Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(transportSettings, amqpSettings, null));
            Assert.NotNull(new AmqpProtocolHead(transportSettings, amqpSettings, transportListenerProvider.Object));
        }
        public string Build(CertificateData data)
        {
            var userPath = GetUserPath();

            var filePath = Path.Combine(
                userPath,
                $"Certificate-{data.Fullname.Replace(' ', '-')}-{DateTime.Now.ToString("yyyyMMddss")}.{FileFormat.Jpg}");

            CertificateHelper.CreateCertificate(data, filePath);

            return(filePath);
        }
        [Ignore] // TODO #582
        public void X509CertificateMutipleClientAuthMechanism()
        {
            string hostName = "acme.azure-devices.net";
            var    amqpConnectionPoolSettings = new AmqpConnectionPoolSettings();
            var    transportSetting           = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings);
            var    authMethod1  = new DeviceAuthenticationWithRegistrySymmetricKey("device1", "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            var    deviceClient = DeviceClient.Create(hostName, authMethod1, new ITransportSettings[] { transportSetting });

            var cert          = CertificateHelper.InstallCertificateFromFile(LocalCertFilename, LocalCertPasswordFile);
            var authMethod2   = new DeviceAuthenticationWithX509Certificate("device2", cert);
            var device2Client = DeviceClient.Create(hostName, authMethod2, new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 100) });
        }
        private static X509Certificate2 GetCertificate()
        {
            X509Certificate2 cert = CertificateHelper.FindCertificateByThumbprint(TestConstants.AutomationTestThumbprint);

            if (cert == null)
            {
                throw new InvalidOperationException(
                          "Test setup error - cannot find a certificate in the My store for KeyVault. This is available for Microsoft employees only.");
            }

            return(cert);
        }
        /// <summary>
        /// Initializes static members of the <see cref="TestConstants"/> class.
        /// </summary>
        static TestConstants()
        {
#if OBA_DEV_ALEC
            string environmentName = "oba-dev-alec";
            ConfigFileName = environmentName + ".config";
#endif
#if OBA_DEV_SHARAD
            string environmentName = "oba-dev-sharad";
            ConfigFileName = environmentName + ".config";
#endif
#if OBA_PPE
            string environmentName = "oba-ppe";
            ConfigFileName = environmentName + ".config";
#endif
#if OBA_PROD
            string environmentName = "oba-prod";
            ConfigFileName = environmentName + ".config";
#endif

            // use the fsr to read values that are not secrets
            var fsr = new FileSettingsReader(ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + ConfigFileName);

            EmbeddedSocialAdminUserHandle = fsr.ReadValue("EmbeddedSocialAdminUserHandle");
            EmbeddedSocialAppKey          = fsr.ReadValue("EmbeddedSocialAppKey");
            EmbeddedSocialUri             = new Uri(fsr.ReadValue("EmbeddedSocialUri"));

            AADOBAAppId    = fsr.ReadValue("AADOBAAppId");
            AADOBAHomePage = fsr.ReadValue("AADOBAHomePage");
            AADTenantId    = fsr.ReadValue("AADTenantId");

            KeyVaultUri       = fsr.ReadValue("KeyVaultUri");
            OBACertThumbprint = fsr.ReadValue("OBACertThumbprint");
            OBARegionsListUri = fsr.ReadValue("OBARegionsListUri");

            // use the kvr to read secrets
            ICertificateHelper cert     = new CertificateHelper(OBACertThumbprint, AADOBAAppId, StoreLocation.CurrentUser);
            IKeyVaultClient    kvClient = new AzureKeyVaultClient(cert);
            var log = new Log(LogDestination.Debug, Log.DefaultCategoryName);
            var kv  = new KV(log, AADOBAAppId, KeyVaultUri, OBACertThumbprint, StoreLocation.CurrentUser, kvClient);
            var kvr = new KVSettingsReader(fsr, kv);

            AzureStorageConnectionString = kvr.ReadValueAsync("AzureStorageConnectionString").Result;
            OBAApiKey                  = kvr.ReadValueAsync("OBAApiKey").Result;
            SendGridEmailAddr          = kvr.ReadValueAsync("SendGridEmailAddr").Result;
            SendGridKey                = kvr.ReadValueAsync("SendGridKey").Result;
            ServiceBusConnectionString = kvr.ReadValueAsync("ServiceBusConnectionString").Result;

            // Obtain an AAD token using a cert from the local store for the current user
            AADSettings       aadSettings = new AADSettings(TestConstants.AADTenantId, TestConstants.AADOBAAppId, TestConstants.AADOBAHomePage, TestConstants.OBACertThumbprint);
            CertificateHelper certHelper  = new CertificateHelper(TestConstants.OBACertThumbprint, TestConstants.AADOBAAppId, StoreLocation.CurrentUser);
            EmbeddedSocialAADToken = certHelper.GetAccessToken(aadSettings.Authority, aadSettings.AppUri).Result;
        }
        /// <summary>
        /// Initializes static members of the <see cref="KVTests"/> class.
        /// </summary>
        static KVTests()
        {
            FileSettingsReader = new FileSettingsReader(ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + TestConstants.ConfigFileName);
            SigningKey         = FileSettingsReader.ReadValue(BearerTokenSigningKey);
            ClientId           = FileSettingsReader.ReadValue(EmbeddedSocialClientIdSetting);
            VaultUrl           = FileSettingsReader.ReadValue(SocialPlusVaultUrlSetting);
            CertThumbprint     = FileSettingsReader.ReadValue(SocialPlusCertThumbprint);
            StoreLoc           = StoreLocation.CurrentUser;
            var cert = new CertificateHelper(CertThumbprint, ClientId, StoreLoc);

            Client  = new AzureKeyVaultClient(cert);
            TestLog = new Log(LogDestination.Debug, Log.DefaultCategoryName);
        }
Esempio n. 7
0
        public void Expect_CryptographicException_when_a_invalid_certificate_is_used_to_encrypt_credentials()
        {
            var certificate    = new CertificateHelper().GetCertificateOfServerByName("LocalhostCertificate.pfx");
            var cryptoProvider = new CollectServiceCryptoProvider();

            var encryptedCredentials =
                cryptoProvider
                .EncryptCredentialBasedOnCertificateOfServer(new CredentialFactory().GetCredential(), certificate);

            var plainCredentials =
                cryptoProvider
                .DecryptCredentialBasedOnCertificateOfServer(encryptedCredentials, certificate);
        }
Esempio n. 8
0
        [Ignore] // TODO #582
        public void DeviceClient_ValidCertHttp()
        {
            // arrange
            const string hostName   = "acme.azure-devices.net";
            var          authMethod = new DeviceAuthenticationWithX509Certificate(
                "device1",
                CertificateHelper.InstallCertificateFromFile(LocalCertFilename, LocalCertPasswordFile));

            // act
            _ = DeviceClient.Create(hostName, authMethod, new ITransportSettings[] { new Http1TransportSettings() });

            // assert?
        }
Esempio n. 9
0
        public void Should_be_possible_to_encrypt_credential_based_on_public_part_of_certificate_of_server()
        {
            var certificateInBytes = new CertificateHelper().GetCertificateOfServer().Export(X509ContentType.Cert);
            var otherCertificate   = new X509Certificate2(certificateInBytes);

            Assert.IsNotNull(otherCertificate);

            var credentialInBytes =
                new CollectServiceCryptoProvider()
                .EncryptCredentialBasedOnCertificateOfServer(new CredentialFactory().GetCredential(), otherCertificate);

            Assert.IsNotNull(credentialInBytes);
        }
        protected override void OnExecute(CertificateOptions option)
        {
            Option.Verbose = true;
            var certificates = CertificateHelper.GetCertificates();

            Info("Информация о сертификатах");
            foreach (var cert in certificates)
            {
                Info(string.Format("Субъект: {0}", cert.Subject));
                Info(string.Format("Отпечаток: {0}", cert.Thumbprint));
                Console.WriteLine();
            }
        }
Esempio n. 11
0
        public static void AddSharedKestrelOptions(this KestrelServerOptions options, HostingConfiguration config)
        {
            options.AddServerHeader = false;

            if (!config.IsSslEnabled)
            {
                return;
            }

            var certificate = CertificateHelper.GetCertificate(config.CertificateFile, config.CertificatePassword, config.CertificateThumbprint);

            options.UseHttps(certificate);
        }
Esempio n. 12
0
        public static async Task <EdgeHubCertificates> LoadAsync(IConfigurationRoot configuration)
        {
            Preconditions.CheckNotNull(configuration, nameof(configuration));
            EdgeHubCertificates result;
            string edgeHubDevCertPath           = configuration.GetValue <string>(Constants.ConfigKey.EdgeHubDevServerCertificateFile);
            string edgeHubDevPrivateKeyPath     = configuration.GetValue <string>(Constants.ConfigKey.EdgeHubDevServerPrivateKeyFile);
            string edgeHubDockerCertPFXPath     = configuration.GetValue <string>(Constants.ConfigKey.EdgeHubServerCertificateFile);
            string edgeHubDockerCaChainCertPath = configuration.GetValue <string>(Constants.ConfigKey.EdgeHubServerCAChainCertificateFile);
            string edgeHubConnectionString      = configuration.GetValue <string>(Constants.ConfigKey.IotHubConnectionString);

            if (string.IsNullOrEmpty(edgeHubConnectionString))
            {
                // When connection string is not set it is edged mode as iotedgd is expected to set this.
                // In this case we reach out to the iotedged via the workload interface.
                (X509Certificate2 ServerCertificate, IEnumerable <X509Certificate2> CertificateChain)certificates;

                var      workloadUri     = new Uri(configuration.GetValue <string>(Constants.ConfigKey.WorkloadUri));
                string   edgeHubHostname = configuration.GetValue <string>(Constants.ConfigKey.EdgeDeviceHostName);
                string   moduleId        = configuration.GetValue <string>(Constants.ConfigKey.ModuleId);
                string   generationId    = configuration.GetValue <string>(Constants.ConfigKey.ModuleGenerationId);
                DateTime expiration      = DateTime.UtcNow.AddDays(Constants.CertificateValidityDays);
                certificates = await CertificateHelper.GetServerCertificatesFromEdgelet(workloadUri, Constants.WorkloadApiVersion, moduleId, generationId, edgeHubHostname, expiration);

                InstallCertificates(certificates.CertificateChain);
                result = new EdgeHubCertificates(certificates.ServerCertificate, certificates.CertificateChain?.ToList());
            }
            else if (!string.IsNullOrEmpty(edgeHubDevCertPath) &&
                     !string.IsNullOrEmpty(edgeHubDevPrivateKeyPath))
            {
                // If no connection string was set and we use iotedged workload style certificates for development
                (X509Certificate2 ServerCertificate, IEnumerable <X509Certificate2> CertificateChain)certificates;

                certificates = CertificateHelper.GetServerCertificateAndChainFromFile(edgeHubDevCertPath, edgeHubDevPrivateKeyPath);
                InstallCertificates(certificates.CertificateChain);
                result = new EdgeHubCertificates(certificates.ServerCertificate, certificates.CertificateChain?.ToList());
            }
            else if (!string.IsNullOrEmpty(edgeHubDockerCertPFXPath) &&
                     !string.IsNullOrEmpty(edgeHubDockerCaChainCertPath))
            {
                // If no connection string was set and we use iotedge devdiv style certificates for development
                List <X509Certificate2> certificateChain = CertificateHelper.GetServerCACertificatesFromFile(edgeHubDockerCaChainCertPath)?.ToList();
                InstallCertificates(certificateChain);
                result = new EdgeHubCertificates(new X509Certificate2(edgeHubDockerCertPFXPath), certificateChain);
            }
            else
            {
                throw new InvalidOperationException("Edge Hub certificate files incorrectly configured");
            }

            return(result);
        }
        private static async Task RenewCore(RenewalParameters renewalParams)
        {
            Trace.TraceInformation("Generating SSL certificate with parameters: {0}", renewalParams);

            var acmeConfig                 = GetAcmeConfig(renewalParams);
            var webAppEnvironment          = GetWebAppEnvironment(renewalParams);
            var certificateServiceSettings = new CertificateServiceSettings {
                UseIPBasedSSL = renewalParams.UseIpBasedSsl
            };
            var azureDnsEnvironment = GetAzureDnsEnvironment(renewalParams);

            var manager = azureDnsEnvironment == null
                ? CertificateManager.CreateKuduWebAppCertificateManager(webAppEnvironment, acmeConfig, certificateServiceSettings, new AuthProviderConfig())
                : CertificateManager.CreateAzureDnsWebAppCertificateManager(webAppEnvironment, acmeConfig, certificateServiceSettings, azureDnsEnvironment);

            Trace.TraceInformation("Adding SSL cert for '{0}'...", GetWebAppFullName(renewalParams));

            bool addNewCert = true;

            if (renewalParams.RenewXNumberOfDaysBeforeExpiration > 0)
            {
                var staging = acmeConfig.BaseUri.Contains("staging", StringComparison.OrdinalIgnoreCase);
                var letsEncryptHostNames = await CertificateHelper.GetLetsEncryptHostNames(webAppEnvironment, staging);

                Trace.TraceInformation("Let's Encrypt host names (staging: {0}): {1}", staging, String.Join(", ", letsEncryptHostNames));

                ICollection <string> missingHostNames = acmeConfig.Hostnames.Except(letsEncryptHostNames, StringComparer.OrdinalIgnoreCase).ToArray();
                if (missingHostNames.Count > 0)
                {
                    Trace.TraceInformation(
                        "Detected host name(s) with no associated Let's Encrypt certificates, will add a new certificate: {0}",
                        String.Join(", ", missingHostNames));
                }
                else
                {
                    Trace.TraceInformation("All host names associated with Let's Encrypt certificates, will perform cert renewal");
                    addNewCert = false;
                }
            }

            if (addNewCert)
            {
                await manager.AddCertificate();
            }
            else
            {
                await manager.RenewCertificate(false, renewalParams.RenewXNumberOfDaysBeforeExpiration);
            }

            Trace.TraceInformation("Let's Encrypt SSL certs & bindings renewed for '{0}'", renewalParams.WebApp);
        }
Esempio n. 14
0
 public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args)
 .ConfigureWebHostDefaults(webBuilder =>
 {
     webBuilder.UseStartup <Startup>();
     webBuilder.UseSerilog();
     webBuilder.ConfigureKestrel(kestrel =>
     {
         kestrel.ConfigureHttpsDefaults(https =>
         {
             https.ServerCertificate = CertificateHelper.CreateCertificate(Configuration);
         });
     });
 });
Esempio n. 15
0
        // GET: Certificate
        public ActionResult Index()
        {
            var listOfEvent = EventHelper.GetAllEventCertificate();

            for (var i = 0; i < listOfEvent.Count; i++)
            {
                var certificate = CertificateHelper.GetAllCertificatesByEvent(listOfEvent[i].ID.ToString());
                if (certificate != null)
                {
                    listOfEvent[i].CertificateTemplate = true;
                }
            }
            return(View(listOfEvent));
        }
Esempio n. 16
0
        /// <summary>
        ///   对XmlDocument执行解密
        /// </summary>
        /// <param name="doc"> XmlDocument对象 </param>
        /// <param name="cername"> 证书名称 </param>
        /// <param name="cersn"> 证书的序列号(已被Asn1IntegerConverter转换过的) </param>
        /// <param name="keyname"> 加密的标签名 </param>
        public static void DecryptDocument(XmlDocument doc, string cername, string cersn, string keyname)
        {
            X509Certificate2 x      = CertificateHelper.GetCertificate(StoreName.My, StoreLocation.LocalMachine, cername);
            string           thisSN = Asn1IntegerConverter.Asn1IntegerToDecimalString(x.GetSerialNumber());

            if (thisSN != cersn)
            {
                throw new Exception("无法分析文本");
            }
            EncryptedXml exml = new EncryptedXml(doc);

            exml.AddKeyNameMapping(keyname, x.PrivateKey);
            exml.DecryptDocument();
        }
Esempio n. 17
0
 public void Configuration(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll);
     app.UseIdentityServer(new IdentityServerOptions
     {
         SiteName           = "Embedded IdentityServer",
         SigningCertificate = CertificateHelper.GetDefaultCertificate(),
         RequireSsl         = false,
         Factory            = new IdentityServerServiceFactory()
                              .UseInMemoryUsers(Users.Get())
                              .UseInMemoryClients(Clients.Get())
                              .UseInMemoryScopes(Scopes.Get())
     });
 }
Esempio n. 18
0
        private static List <X509Certificate> ReadCertificatesDirectory()
        {
            List <X509Certificate> certificates = new List <X509Certificate>();
            string certificatesPath             = GetCertificatesPath();

            string[] files = Directory.GetFiles(certificatesPath, "*.cer");
            foreach (string filePath in files)
            {
                byte[]          fileBytes   = File.ReadAllBytes(filePath);
                X509Certificate certificate = CertificateHelper.GetCertificatesFromBytes(fileBytes);
                certificates.Add(certificate);
            }
            return(certificates);
        }
Esempio n. 19
0
        private void InitializeModule([NotNull] CustomModule module)
        {
            if (module == null)
            {
                throw new ArgumentNullException(nameof(module));
            }

            LogProvider.Log.Info($"Initializing {module.ModuleName} module.");

            var moduleAssemblyPath = module.ModuleAssembly;

            if (!File.Exists(moduleAssemblyPath))
            {
                moduleAssemblyPath = Path.Combine(StringFormatter.GetModulesFolderPath(), module.ModuleAssembly);

                if (!File.Exists(moduleAssemblyPath))
                {
                    LogProvider.Log.Error($"Module {module.ModuleName} has not been found at '{moduleAssemblyPath}'.");
                    return;
                }
            }

            if (!CertificateHelper.Verify(moduleAssemblyPath))
            {
                LogProvider.Log.Error($"Module {module.ModuleName} isn't valid at '{moduleAssemblyPath}'.");
                return;
            }

            try
            {
                var moduleAssembly = Assembly.LoadFrom(moduleAssemblyPath);

                LogProvider.Log.Info($"Module {module.ModuleName} has been loaded.");

                var moduleInterfaceType = typeof(IDHModule);

                var moduleType = moduleAssembly.GetTypes()
                                 .FirstOrDefault(t => t.GetInterfaces().Contains(moduleInterfaceType) && t.GetConstructor(Type.EmptyTypes) != null);

                var moduleObject = Activator.CreateInstance(moduleType) as IDHModule;
                moduleObject.ConfigureContainer(container);

                LogProvider.Log.Info($"Module {module.ModuleName} has been configured.");
            }
            catch (Exception e)
            {
                LogProvider.Log.Error(this, $"Module {module.ModuleName} hasn't been loaded at '{moduleAssemblyPath}'.", e);
            }
        }
Esempio n. 20
0
        public static void ResignExecutable(MachObjectFile file, string bundleIdentifier, List <X509Certificate> certificateChain, AsymmetricKeyEntry privateKey, byte[] infoFileBytes, byte[] codeResourcesBytes, EntitlementsFile entitlements)
        {
            X509Certificate signingCertificate = certificateChain[certificateChain.Count - 1];
            string          certificateCN      = CertificateHelper.GetCertificateCommonName(signingCertificate);
            string          teamID             = CertificateHelper.GetCertificateOrganizationalUnit(signingCertificate);

            SegmentCommand linkEditSegment = SegmentCommandHelper.FindLinkEditSegment(file.LoadCommands);

            if (linkEditSegment == null)
            {
                throw new InvalidDataException("LinkEdit segment was not found");
            }

            if (file.LoadCommands[file.LoadCommands.Count - 1].CommandType != LoadCommandType.CodeSignature)
            {
                throw new NotImplementedException("The last LoadCommand entry is not CodeSignature");
            }

            CodeSignatureCommand command = (CodeSignatureCommand)file.LoadCommands[file.LoadCommands.Count - 1];
            int codeLength = (int)command.DataOffset;
            CodeDirectoryBlob    codeDirectory    = CreateCodeDirectoryBlob(codeLength, bundleIdentifier, teamID);
            CodeRequirementsBlob codeRequirements = CreateCodeRequirementsBlob(bundleIdentifier, certificateCN);
            EntitlementsBlob     entitlementsBlob = CreateEntitlementsBlob(entitlements);
            CmsSignatureBlob     cmsSignature     = new CmsSignatureBlob();

            // We create a dummy signature to determine the length required
            cmsSignature.Data = CMSHelper.GenerateSignature(certificateChain, privateKey, codeDirectory.GetBytes());

            CodeSignatureSuperBlob codeSignature = new CodeSignatureSuperBlob();

            codeSignature.Entries.Add(CodeSignatureEntryType.CodeDirectory, codeDirectory);
            codeSignature.Entries.Add(CodeSignatureEntryType.Requirements, codeRequirements);
            codeSignature.Entries.Add(CodeSignatureEntryType.Entitlements, entitlementsBlob);
            codeSignature.Entries.Add(CodeSignatureEntryType.CmsSignature, cmsSignature);

            command.DataSize = (uint)codeSignature.Length;
            uint finalFileSize = command.DataOffset + command.DataSize;

            SegmentCommandHelper.SetEndOffset(linkEditSegment, finalFileSize);

            byte[] codeToHash = ByteReader.ReadBytes(file.GetBytes(), 0, codeLength);
            UpdateHashes(codeDirectory, codeToHash, infoFileBytes, codeRequirements, codeResourcesBytes, entitlementsBlob);
            cmsSignature.Data = CMSHelper.GenerateSignature(certificateChain, privateKey, codeDirectory.GetBytes());

            // Store updated code signature:
            byte[] codeSignatureBytes = codeSignature.GetBytes();
            Array.Resize <byte>(ref file.Data, (codeLength - file.DataOffset) + (int)command.DataSize);
            ByteWriter.WriteBytes(file.Data, (int)command.DataOffset - file.DataOffset, codeSignatureBytes);
        }
Esempio n. 21
0
        public async Task <IActionResult> CertificatePreview(long id, bool isPreview)
        {
            var batch = await _certificateService.GetCertificateBatchByID(id, true);

            var data = batch.Certificates.OrderBy(e => e.SerialNo)
                       .Select(e => CertificateHelper.Convert(e))
                       .ToList();

            return(View("Certificate", new CertificateModel
            {
                IsPreview = isPreview,
                Title = batch.TemplateText,
                Certificates = data
            }));
        }
Esempio n. 22
0
        [Ignore] // TODO #582
        public void DeviceClient_InvalidX509Certificate()
        {
            // arrange
            const string     hostName         = "acme.azure-devices.net";
            var              transportSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, new AmqpConnectionPoolSettings());
            var              authMethod1      = new DeviceAuthenticationWithRegistrySymmetricKey("device1", "dGVzdFN0cmluZzE=");
            X509Certificate2 cert             = CertificateHelper.InstallCertificateFromFile(LocalCertFilename, LocalCertPasswordFile);
            var              authMethod2      = new DeviceAuthenticationWithX509Certificate("device2", cert);

            // act
            _ = DeviceClient.Create(hostName, authMethod1, new ITransportSettings[] { transportSetting });
            _ = DeviceClient.Create(hostName, authMethod2, new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 100) });

            // assert?
        }
        public void X509Certificate_MqttTransportSettingsTest()
        {
            string hostName   = "acme.azure-devices.net";
            var    cert       = CertificateHelper.InstallCertificateFromFile(LocalCertFilename, LocalCertPasswordFile);
            var    authMethod = new DeviceAuthenticationWithX509Certificate("device1", cert);

            var deviceClient = DeviceClient.Create(hostName, authMethod, new ITransportSettings[]
            {
                new MqttTransportSettings(TransportType.Mqtt)
                {
                    ClientCertificate = cert,
                    RemoteCertificateValidationCallback = (a, b, c, d) => true
                }
            });
        }
        public void should_fail_if_client_do_not_send_handshake_within_given_time_Frame()
        {
            var certificate   = CertificateHelper.Create();
            var clientServer  = ClientServerHelper.Create();
            var buffer        = new BufferSlice(new byte[65535], 0, 65535);
            var serverChannel = new TcpChannel(buffer, new FakeEncoder(), new FakeDecoder());


            var sut = new ServerSideSslStreamBuilder(certificate);

            sut.HandshakeTimeout = TimeSpan.FromMilliseconds(100);
            Action actual = () => sut.Build(serverChannel, clientServer.Server);

            actual.ShouldThrow <InvalidOperationException>();
        }
Esempio n. 25
0
        public async Task <FileServiceJwt> VerifyJwt(AuthJwt auth)
        {
            try
            {
                // check signature
                var publicKey = await this._configService.Get("JWTPublicKeys");

                //var cer = new X509Certificate2(Convert.FromBase64String(publicKey));
                var rsa = CertificateHelper.GetPublicKey(auth.Jwt, publicKey);//  (RSA)(cer.PublicKey.Key);
                var validationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                    IssuerSigningKey = new RsaSecurityKey(rsa),
                    ValidateIssuer   = false,
                };
                var      result        = new JwtSecurityTokenHandler().ValidateToken(auth.Jwt, validationParameters, out SecurityToken securityToken);
                var      validateToken = securityToken as JwtSecurityToken;
                string   scopeStr      = validateToken.Claims.FirstOrDefault(c => c.Type == "scope")?.Value;
                string   jti           = validateToken.Claims.FirstOrDefault(c => c.Type == "jti")?.Value;
                string   iss           = validateToken.Claims.FirstOrDefault(c => c.Type == "iss")?.Value;
                ScopeDto scope         = new ScopeDto();
                if (!string.IsNullOrEmpty(scopeStr))
                {
                    scope = JsonConvert.DeserializeObject <ScopeDto>(scopeStr);
                }
                //LogHelper.Info($"Check ip: JWT->{scope.ip}, FileService->{auth.IP}");
                //此处ip校验,在对部分域名使用vpn加速情况下,可能造成ip不一致,所以暂时去掉

                /*
                 * if (scope.ip != auth.IP && scope.ip != "127.0.0.1")
                 * {
                 *  throw new UnauthorizedException();
                 * }
                 */
                VerifyJti(jti);
                return(new FileServiceJwt()
                {
                    ExpireInDays = scope.fileExpireInDays,
                    SiteId = scope.siteId,
                    AppId = iss
                });
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, ex.Message);
                throw new UnauthorizedException();
            }
        }
Esempio n. 26
0
        static async Task <LeafDevice> CreateWithCaCertAsync(
            string leafDeviceId,
            string parentId,
            CertificateAuthority ca,
            IotHub iotHub,
            ITransportSettings transport,
            string edgeHostname,
            CancellationToken token,
            ClientOptions options)
        {
            Device edge = await GetEdgeDeviceIdentityAsync(parentId, iotHub, token);

            Device leaf = new Device(leafDeviceId)
            {
                Authentication = new AuthenticationMechanism
                {
                    Type = AuthenticationType.CertificateAuthority
                },
                Scope = edge.Scope
            };

            leaf = await iotHub.CreateDeviceIdentityAsync(leaf, token);

            return(await DeleteIdentityIfFailedAsync(
                       leaf,
                       iotHub,
                       token,
                       async() =>
            {
                IdCertificates certFiles = await ca.GenerateIdentityCertificatesAsync(leafDeviceId, token);

                (X509Certificate2 leafCert, IEnumerable <X509Certificate2> trustedCerts) =
                    CertificateHelper.GetServerCertificateAndChainFromFile(certFiles.CertificatePath, certFiles.KeyPath);
                // .NET runtime requires that we install the chain of CA certs, otherwise it can't
                // provide them to a server during authentication.
                OsPlatform.Current.InstallTrustedCertificates(trustedCerts);

                return await CreateLeafDeviceAsync(
                    leaf,
                    () => DeviceClient.Create(
                        iotHub.Hostname,
                        edgeHostname,
                        new DeviceAuthenticationWithX509Certificate(leaf.Id, leafCert),
                        new[] { transport },
                        options),
                    iotHub,
                    token);
            }));
        /// <summary>
        /// Retrieves SendGrid key from KV
        /// </summary>
        /// <param name="configFile">config file path</param>
        /// <returns>SendGrid key</returns>
        public static string GetSendGridKey(string configFile)
        {
            var sr                    = new FileSettingsReader(configFile);
            var certThumbprint        = sr.ReadValue(TestConstants.SocialPlusCertThumbprint);
            var clientID              = sr.ReadValue(TestConstants.EmbeddedSocialClientIdSetting);
            var storeLocation         = StoreLocation.CurrentUser;
            var vaultUrl              = sr.ReadValue(TestConstants.SocialPlusVaultUrlSetting);
            ICertificateHelper cert   = new CertificateHelper(certThumbprint, clientID, storeLocation);
            IKeyVaultClient    client = new AzureKeyVaultClient(cert);

            var log      = new Log(LogDestination.Console, Log.DefaultCategoryName);
            var kv       = new KV(log, clientID, vaultUrl, certThumbprint, storeLocation, client);
            var kvReader = new KVSettingsReader(sr, kv);

            return(kvReader.ReadValueAsync("SendGridInstrumentationKey").Result);
        }
Esempio n. 28
0
        protected void SetupMutualAuth()
        {
            if (_spineOptionsDelegate.CurrentValue.SdsUseMutualAuth)
            {
                var clientCertData        = CertificateHelper.ExtractCertInstances(_spineOptionsDelegate.CurrentValue.ClientCert);
                var clientPrivateKeyData  = CertificateHelper.ExtractKeyInstance(_spineOptionsDelegate.CurrentValue.ClientPrivateKey);
                var x509ClientCertificate = new X509Certificate2(clientCertData.FirstOrDefault());

                var privateKey = RSA.Create();
                privateKey.ImportRSAPrivateKey(clientPrivateKeyData, out _);
                var x509CertificateWithPrivateKey = x509ClientCertificate.CopyWithPrivateKey(privateKey);
                var pfxFormattedCertificate       = new X509Certificate(x509CertificateWithPrivateKey.Export(X509ContentType.Pfx, string.Empty), string.Empty);

                _clientCertificate = pfxFormattedCertificate;
            }
        }
Esempio n. 29
0
        public void Should_be_possible_to_use_ServerCertificate_to_do_assimetric_cryptography()
        {
            var certificate          = new CertificateHelper().GetCertificateOfServer();
            var cryptoProvider       = new CollectServiceCryptoProvider();
            var encryptedCredentials =
                cryptoProvider
                .EncryptCredentialBasedOnCertificateOfServer(new CredentialFactory().GetCredential(), certificate);
            var plainCredentials =
                cryptoProvider
                .DecryptCredentialBasedOnCertificateOfServer(encryptedCredentials, certificate);

            Assert.IsNotNull(plainCredentials, "The credentials after decryptation cannot be nuul.");
            Assert.AreEqual("fake_domain", plainCredentials.Domain);
            Assert.AreEqual("john_doe", plainCredentials.UserName);
            Assert.AreEqual("******", plainCredentials.Password);
        }
Esempio n. 30
0
        public void TestInvalidConstructorInputs()
        {
            const bool       clientCertsAllowed    = true;
            X509Certificate2 tlsCertificate        = CertificateHelper.GenerateSelfSignedCert("TestCert");
            var          transportSettings         = new DefaultTransportSettings(Scheme, HostName, Port, tlsCertificate, clientCertsAllowed, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>(), SslProtocols.Tls12);
            AmqpSettings amqpSettings              = AmqpSettingsProvider.GetDefaultAmqpSettings(IotHubHostName, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>(), Mock.Of <ILinkHandlerProvider>(), Mock.Of <IConnectionProvider>(), new NullCredentialsCache());
            var          transportListenerProvider = new Mock <ITransportListenerProvider>();
            var          webSockerListenerRegistry = new Mock <IWebSocketListenerRegistry>();

            Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(null, amqpSettings, transportListenerProvider.Object, webSockerListenerRegistry.Object, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>()));
            Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(transportSettings, null, transportListenerProvider.Object, webSockerListenerRegistry.Object, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>()));
            Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(transportSettings, amqpSettings, null, webSockerListenerRegistry.Object, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>()));
            Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(transportSettings, amqpSettings, transportListenerProvider.Object, null, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>()));
            Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(transportSettings, amqpSettings, transportListenerProvider.Object, webSockerListenerRegistry.Object, null, Mock.Of <IClientCredentialsFactory>()));
            Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(transportSettings, amqpSettings, transportListenerProvider.Object, webSockerListenerRegistry.Object, Mock.Of <IAuthenticator>(), null));
            Assert.NotNull(new AmqpProtocolHead(transportSettings, amqpSettings, transportListenerProvider.Object, webSockerListenerRegistry.Object, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>()));
        }