public static TrustManager CreateSecureTrustManager(ILogger logger)
        {
            var trustManager = TrustManager.CreateChainTrust();

            trustManager.Logger = logger;
            return(trustManager);
        }
Example #2
0
        public async Task <IActionResult> DownloadPublicDER(string uuid)
        {
            if (string.IsNullOrEmpty(uuid))
            {
                return(NotFound());
            }

            var certificate = await DBContext.Certificate.
                              SingleOrDefaultAsync(m => m.Uuid == uuid && m.Revoked == false);

            if (certificate == null)
            {
                return(NotFound());
            }

            if (certificate.Revoked == true || certificate.ExpireDate < DateTime.UtcNow.Date)
            {
                return(NotFound());
            }

            var memory = new MemoryStream();

            using (var stream = new FileStream(
                       TrustManager.CertificatePath(
                           certificate.Uuid,
                           CertificateType.ReviewerCertificate,
                           StoreFormat.CRT), FileMode.Open)) {
                await stream.CopyToAsync(memory);
            }

            memory.Position = 0;
            return(File(memory, "application/x-x509-ca-cert", certificate.SerialNumber + ".der"));
        }
Example #3
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void startServer(boolean httpEnabled, boolean httpsEnabled) throws Exception
        private void StartServer(bool httpEnabled, bool httpsEnabled)
        {
            CommunityServerBuilder serverBuilder = serverOnRandomPorts().usingDataDir(Folder.directory(Name.MethodName).AbsolutePath);

            if (!httpEnabled)
            {
                serverBuilder.WithHttpDisabled();
            }
            if (httpsEnabled)
            {
                serverBuilder.WithHttpsEnabled();
            }

            _server = serverBuilder.Build();
            _server.start();

            // Because we are generating a non-CA-signed certificate, we need to turn off verification in the client.
            // This is ironic, since there is no proper verification on the CA side in the first place, but I digress.
            TrustManager[] trustAllCerts = new TrustManager[] { new InsecureTrustManager() };

            // Install the all-trusting trust manager
            SSLContext sc = SSLContext.getInstance("TLS");

            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.DefaultSSLSocketFactory = sc.SocketFactory;
        }
Example #4
0
        }                            // for test

        public EncryptionManager(EncryptionLevel level, TrustStrategy strategy, TrustManager trustManager, IDriverLogger logger)
        {
            _encryptionLevel = level;

            if (_encryptionLevel == EncryptionLevel.Encrypted)
            {
                if (trustManager == null)
                {
                    switch (strategy)
                    {
                    case V1.TrustStrategy.TrustAllCertificates:
                        trustManager = TrustManager.CreateInsecure(false);
                        break;

                    case V1.TrustStrategy.TrustSystemCaSignedCertificates:
                        trustManager = TrustManager.CreateChainTrust(true);
                        break;

                    default:
                        throw new InvalidOperationException($"Unknown trust strategy: {strategy}");
                    }
                }

                trustManager.Logger = logger;

                TrustManager = trustManager;
            }
        }
Example #5
0
        //----------------------------------------------------------------------------
        // GetTMEvidenceAndPolicy
        //----------------------------------------------------------------------------
        public bool GetTMEvidenceAndPolicy(ref Evidence securityEvidence, ref PolicyLevel appPolicy)
        {
            SecurityManifest sm = null;

            if (_sSecurityStatement != null)
            {
                sm = new SecurityManifest(_sSecurityStatement);
            }
            else
            {
                sm = new SecurityManifest();
            }

            // setup object for domain specifically to get trust.
            // for demo hack, securityEvidence = null at first, then set to additional evidence returned.
            TrustDecision trustDecision = TrustManager.EvaluateTrustRequest(sm, securityEvidence, "file://" + _sAppBase);

            if (trustDecision.Action == BasicTrustAction.Deny)
            {
                return(false);
            }

            appPolicy        = TrustManager.CreatePolicyLevel(trustDecision);
            securityEvidence = trustDecision.DomainEvidence;

            return(true);
        }
        /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
        /// <exception cref="Sharpen.KeyStoreException"></exception>
        public virtual Apache.Http.Conn.Ssl.SSLContextBuilder LoadTrustMaterial(KeyStore
                                                                                truststore, TrustStrategy trustStrategy)
        {
            TrustManagerFactory tmfactory = TrustManagerFactory.GetInstance(TrustManagerFactory
                                                                            .GetDefaultAlgorithm());

            tmfactory.Init(truststore);
            TrustManager[] tms = tmfactory.GetTrustManagers();
            if (tms != null)
            {
                if (trustStrategy != null)
                {
                    for (int i = 0; i < tms.Length; i++)
                    {
                        TrustManager tm = tms[i];
                        if (tm is X509TrustManager)
                        {
                            tms[i] = new SSLContextBuilder.TrustManagerDelegate((X509TrustManager)tm, trustStrategy
                                                                                );
                        }
                    }
                }
                for (int i_1 = 0; i_1 < tms.Length; i_1++)
                {
                    this.trustmanagers.AddItem(tms[i_1]);
                }
            }
            return(this);
        }
        private void VerifySuccess(Uri target, TrustManager trustManager)
        {
            var ex = Record.Exception(() => TestConnectivity(target,
                                                             Config.Builder.WithTrustManager(trustManager).ToConfig()
                                                             ));

            ex.Should().BeNull();
        }
 public TrustManagementService(ITrustManagementRepository repository, IAccountService accountService, IStatisticService statisticService)
 {
     Logger.Trace("TrustManagement service construction");
     this.repository        = repository;
     this.statisticService  = statisticService;
     this.accountService    = accountService;
     TrustManagementManager = new TrustManager(repository, accountService, statisticService);
 }
Example #9
0
        private async Task VerifySuccess(Uri target, TrustManager trustManager, EncryptionLevel encryptionLevel = EncryptionLevel.Encrypted)
        {
            var ex = await Record.ExceptionAsync(() => TestConnectivity(target,
                                                                        Config.Builder.WithTrustManager(trustManager).WithEncryptionLevel(encryptionLevel).Build()
                                                                        ));

            ex.Should().BeNull();
        }
        private void VerifyFailure(Uri target, TrustManager trustManager)
        {
            var ex = Record.Exception(() => TestConnectivity(target,
                                                             Config.Builder.WithTrustManager(trustManager).ToConfig()
                                                             ));

            ex.Should().BeOfType <SecurityException>().Which.Message.Should()
            .Contain("Failed to establish encrypted connection with server");
        }
Example #11
0
        private async Task VerifyFailure(Uri target, TrustManager trustManager)
        {
            var ex = await Record.ExceptionAsync(() => TestConnectivity(target,
                                                                        Config.Builder.WithTrustManager(trustManager).WithEncryptionLevel(EncryptionLevel.Encrypted).Build()
                                                                        ));

            ex.Should().BeOfType <SecurityException>().Which.Message.Should()
            .Contain("Failed to establish encrypted connection with server");
        }
Example #12
0
            public void WithTrustManagerShouldModifyTheSingleValue()
            {
                var config = Config.Builder.WithTrustManager(TrustManager.CreateChainTrust()).Build();

                config.EncryptionLevel.Should().Be(EncryptionLevel.None);
                config.TrustManager.Should().BeOfType <ChainTrustManager>();
                config.Logger.Should().BeOfType <NullLogger>();
                config.MaxIdleConnectionPoolSize.Should().Be(100);
            }
Example #13
0
 public async Task ShouldBeAbleToConnectWithInsecureConfig()
 {
     using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken,
                                              o => o
                                              .WithEncryptionLevel(EncryptionLevel.Encrypted)
                                              .WithTrustManager(TrustManager.CreateInsecure())))
     {
         await VerifyConnectivity(driver);
     }
 }
        public static EncryptionManager Create(Uri uri, EncryptionLevel?level, TrustManager trustManager,
                                               ILogger logger)
        {
            var configured = level.HasValue || trustManager != null;

            if (configured)
            {
                AssertSimpleUriScheme(uri, level, trustManager);
                return(CreateFromConfig(level, trustManager, logger));
            }
            return(CreateFromUriScheme(uri, logger));
        }
        public async Task <IActionResult> VerifyDocument(string uuid)
        {
            if (string.IsNullOrEmpty(uuid))
            {
                return(NotFound());
            }

            var document = await DBContext.Document
                           .SingleOrDefaultAsync(m => m.Uuid == uuid);

            if (document == null)
            {
                return(NotFound());
            }

            var certificates = await DBContext.Certificate.ToListAsync();

            var signatureValidations = new List <SignatureValidation> ();

            foreach (var certificate in certificates)
            {
                var x509certificate = TrustManager.LoadX509Certificate(
                    certificate.Uuid,
                    CertificateType.ReviewerCertificate);

                SignatureValidation result = SignatureManager.VerifySignature(x509certificate, FileManager.DocumentRoot + "/" + document.Uuid);

                if (result != null)
                {
                    result.SignatureName = certificate.ReviewerName;
                    result.Certificate   = certificate;
                    if (certificate.Revoked == true && result.SignatureDate > certificate.RevokeDate)
                    {
                        result.SignatureRevoked = true;
                    }
                    else if (certificate.Revoked != true && result.SignatureDate > certificate.ExpireDate)
                    {
                        result.SignatureExpired = true;
                    }
                    signatureValidations.Add(result);
                }
            }

            DBContext.Document.Remove(document);
            DBContext.SaveChanges();

            return(View("DocumentResult", signatureValidations));
        }
        } // for test

        public EncryptionManager(EncryptionLevel level, TrustManager trustManager, ILogger logger)
        {
            _encryptionLevel = level;

            if (_encryptionLevel == EncryptionLevel.Encrypted)
            {
                if (trustManager == null)
                {
                    trustManager = TrustManager.CreateChainTrust();
                }

                trustManager.Logger = logger;

                TrustManager = trustManager;
            }
        }
Example #17
0
        private static void trustAllHosts()
        {
            ITrustManager[] trustAllCerts = new TrustManager[] { };


            try
            {
                SSLContext e = SSLContext.GetInstance("TLS");
                e.Init((IKeyManager[])null, trustAllCerts, new SecureRandom());
                HttpsURLConnection.DefaultSSLSocketFactory = e.SocketFactory;
            }
            catch (Java.Lang.Exception var2)
            {
                var2.PrintStackTrace();
            }
        }
Example #18
0
 /// <exception cref="System.IO.IOException"></exception>
 private void DisableSslVerify(URLConnection conn)
 {
     TrustManager[] trustAllCerts = new TrustManager[] { new TransportHttp.DummyX509TrustManager
                                                             () };
     try
     {
         SSLContext ctx = SSLContext.GetInstance("SSL");
         ctx.Init(null, trustAllCerts, null);
         HttpsURLConnection sslConn = (HttpsURLConnection)conn;
         sslConn.SetSSLSocketFactory(ctx.GetSocketFactory());
     }
     catch (KeyManagementException e)
     {
         throw new IOException(e.Message);
     }
     catch (NoSuchAlgorithmException e)
     {
         throw new IOException(e.Message);
     }
 }
Example #19
0
        public async Task <IActionResult> DownloadP12Store(string uuid)
        {
            if (string.IsNullOrEmpty(uuid))
            {
                return(NotFound());
            }

            var certificate = await DBContext.Certificate
                              .SingleOrDefaultAsync(m => m.Uuid == uuid && m.Revoked == false);

            if (certificate == null)
            {
                return(NotFound());
            }

            if (certificate.ExpireDate < DateTime.UtcNow.Date)
            {
                certificate.Revoked    = true;
                certificate.RevokeDate = DateTime.UtcNow.Date;
                DBContext.Certificate.Update(certificate);
                await DBContext.SaveChangesAsync();

                return(View(nameof(CertificateExpired)));
            }

            var memory = new MemoryStream();

            using (var stream = new FileStream(
                       TrustManager.CertificatePath(
                           certificate.Uuid,
                           CertificateType.ReviewerCertificate,
                           StoreFormat.P12Store), FileMode.Open)) {
                await stream.CopyToAsync(memory);
            }

            memory.Position = 0;

            return(File(memory, "application/x-pkcs12", certificate.SerialNumber + ".p12"));
        }
 private static void AssertSimpleUriScheme(Uri uri, EncryptionLevel?encryptionLevel, TrustManager trustManager)
 {
     if (!uri.IsSimpleUriScheme())
     {
         throw new ArgumentException(
                   "The encryption and trust settings cannot both be set via uri scheme and driver configuration. " +
                   $"uri scheme = {uri.Scheme}, encryption = {encryptionLevel}, trust = {trustManager}");
     }
 }
Example #21
0
 // tag::config-trust[]
 public IDriver CreateDriverWithCustomizedTrustStrategy(string uri, string user, string password)
 {
     return(GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
                                 o => o.WithTrustManager(TrustManager.CreateInsecure())));
 }
        } // for test

        public EncryptionManager(bool useTls, TrustManager trustManager)
        {
            UseTls       = useTls;
            TrustManager = trustManager;
        }
 public TrustManagerHandshaker(Uri uri, X509Certificate2 certificate, TrustManager trustManager)
 {
     _uri          = uri;
     _certificate  = certificate;
     _trustManager = trustManager;
 }
 public void Init (object[] keyManager, TrustManager[] tm, object secureRandom)
 {
     // TODO
 }
Example #25
0
        public async Task <IActionResult> Issue(
            string requestId, string password, string code)
        {
            if (string.IsNullOrEmpty(requestId))
            {
                return(NotFound());
            }

            var request = await DBContext.CertificateRequest
                          .Include(s => s.Reviewer)
                          .SingleOrDefaultAsync(m => m.Uuid == requestId);

            if (request == null)
            {
                return(NotFound());
            }

            if (code != request.SecurityCode)
            {
                return(RedirectToAction("RequestExpired"));
            }

            var now = DateTime.UtcNow.Date;

            var certificate = new Certificate();

            certificate.Uuid          = Guid.NewGuid().ToString();
            certificate.CreationDate  = now;
            certificate.ExpireDate    = now.AddYears(1);
            certificate.Revoked       = false;
            certificate.ReviewerUuid  = request.ReviewerUuid;
            certificate.ReviewerName  = request.Reviewer.Name;
            certificate.ReviewerEmail = request.Reviewer.Email;

            DistinguishedName dn = new DistinguishedName();

            dn.CommonName         = request.Reviewer.Name;
            dn.Email              = request.Reviewer.Email;
            dn.Organization       = TrustManager.IssuerDN.Organization;
            dn.OrganizationalUnit = TrustManager.IssuerDN.OrganizationalUnit;
            dn.Country            = TrustManager.IssuerDN.Country;
            dn.Locality           = TrustManager.IssuerDN.Locality;
            dn.State              = TrustManager.IssuerDN.State;

            var x509certificate = TrustManager.IssueCertificate(
                certificate.Uuid.ToString(),
                password,
                dn,
                CertificateType.ReviewerCertificate,
                now, now.AddYears(1));

            certificate.SerialNumber = x509certificate.SerialNumber;

            DBContext.Add(certificate);
            await DBContext.SaveChangesAsync();

            request.CertificateUuid      = certificate.Uuid;
            request.Certificate          = certificate;
            request.Reviewer.Certificate = certificate;

            DBContext.Update(request);
            await DBContext.SaveChangesAsync();

            var message = await RenderService.RenderToStringAsync("Email/CertificateIssued", request.Reviewer);

            var attachments = new List <Attachment> ();

            attachments.Add(
                await EmailManager.LoadAttachment(
                    TrustManager.CertificatePath(
                        certificate.Uuid,
                        CertificateType.ReviewerCertificate,
                        StoreFormat.P12Store), "private.p12", "application/x-pkcs12"));

            attachments.Add(
                await EmailManager.LoadAttachment(
                    TrustManager.CertificatePath(
                        certificate.Uuid,
                        CertificateType.ReviewerCertificate,
                        StoreFormat.CRT), "public.crt", "application/x-x509-ca-cert"));

            attachments.Add(
                await EmailManager.LoadAttachment(
                    TrustManager.CertificatePath(
                        "root",
                        CertificateType.AuthorityCertificate,
                        StoreFormat.CRT), "authority.crt", "application/x-x509-ca-cert"));

            var response = await EmailManager.SendEmailHTML(
                message,
                EmailManager.Sender,
                request.Reviewer.Email,
                "Your new certificate is ready",
                attachments
                );

            if (!response.Successful)
            {
                return(View("ErrorSendingCertificate"));
            }

            return(RedirectToAction(nameof(CertificateSent)));
        }
Example #26
0
        protected override Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            var certificate = Context.Connection.ClientCertificate;

            if (certificate == null)
            {
                return(Task.FromResult(AuthenticateResult.Fail("Invalid Client Certificate")));
            }

            if (certificate.NotAfter < DateTime.Now)
            {
                return(Task.FromResult(AuthenticateResult.Fail("Certificate Expired or not ready for use")));
            }

            if (certificate.SerialNumber == Program.AdministratorCertificate.SerialNumber)
            {
                /* System Administrator Certificate */
                if (!certificate.RawData.SequenceEqual(Program.AdministratorCertificate.RawData))
                {
                    return(Task.FromResult(AuthenticateResult.Fail("Invalid System Administrator Certificate")));
                }

                var claims = new List <Claim>();
                claims.Add(new Claim(ClaimTypes.Role, "Admin"));
                claims.Add(new Claim(ClaimTypes.Role, "Operator"));
                claims.Add(new Claim(ClaimTypes.Role, "Reviewer"));

                var userIdentity  = new ClaimsIdentity(claims, Options.Challenge);
                var userPrincipal = new ClaimsPrincipal(userIdentity);
                var ticket        = new AuthenticationTicket(userPrincipal, new AuthenticationProperties(), Options.Challenge);

                return(Task.FromResult(AuthenticateResult.Success(ticket)));
            }
            else
            {
                /* User Created Certificates  */
                var dbcert = _context.Certificate
                             .SingleOrDefault(m => m.SerialNumber == certificate.SerialNumber);

                if (dbcert == null)
                {
                    return(Task.FromResult(AuthenticateResult.Fail("Invalid Client Certificate")));
                }

                var x509cert = TrustManager.LoadCertificate(
                    dbcert.Uuid,
                    null,
                    CertificateType.ReviewerCertificate,
                    StoreFormat.CRT);

                if (x509cert.Thumbprint == certificate.Thumbprint)
                {
                    var reviewer = _context.Reviewer.SingleOrDefault(m => m.Uuid == dbcert.ReviewerUuid);

                    if (reviewer == null)
                    {
                        return(Task.FromResult(AuthenticateResult.Fail("Wrong credentials")));
                    }

                    var claims = new List <Claim>();

                    if (reviewer.Role == "Admin")
                    {
                        claims.Add(new Claim(ClaimTypes.Role, "Admin"));
                        claims.Add(new Claim(ClaimTypes.Role, "Operator"));
                        claims.Add(new Claim(ClaimTypes.Role, "Reviewer"));
                    }
                    else if (reviewer.Role == "Operator")
                    {
                        claims.Add(new Claim(ClaimTypes.Role, "Operator"));
                        claims.Add(new Claim(ClaimTypes.Role, "Reviewer"));
                    }
                    else if (reviewer.Role == "Reviewer")
                    {
                        claims.Add(new Claim(ClaimTypes.Role, "Reviewer"));
                    }
                    else
                    {
                        return(Task.FromResult(AuthenticateResult.Fail("Wrong credentials")));
                    }

                    var userIdentity  = new ClaimsIdentity(claims, Options.Challenge);
                    var userPrincipal = new ClaimsPrincipal(userIdentity);
                    var ticket        = new AuthenticationTicket(userPrincipal, new AuthenticationProperties(), Options.Challenge);
                    return(Task.FromResult(AuthenticateResult.Success(ticket)));
                }
            }

            return(Task.FromResult(AuthenticateResult.Fail("Wrong credentials")));
        }
        public async Task <IActionResult> Sign(string uuid, string password, string description)
        {
            if (string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(password))
            {
                return(View("OperationNotAllowed"));
            }

            var document = await DBContext.Document
                           .SingleOrDefaultAsync(m => m.Uuid == uuid);

            if (document == null)
            {
                return(NotFound());
            }

            if (document.MimeType != "application/pdf")
            {
                return(View("InvalidDocument"));
            }

            var x509certificate = HttpContext.Connection.ClientCertificate;

            if (x509certificate == null)
            {
                return(View("OperationNotAllowed"));
            }

            var certificate = await DBContext.Certificate
                              .SingleOrDefaultAsync(r => r.SerialNumber == x509certificate.SerialNumber);

            if (certificate == null || certificate.ReviewerUuid != document.ReviewerUuid)
            {
                return(View("OperationNotAllowed"));
            }

            if (certificate.ExpireDate < DateTime.Now.Date)
            {
                certificate.Revoked    = true;
                certificate.RevokeDate = DateTime.UtcNow.Date;
                DBContext.Certificate.Update(certificate);
                await DBContext.SaveChangesAsync();
            }

            if (certificate.Revoked == true)
            {
                return(RedirectToAction("CertificateExpired", "Certificates"));
            }

            var pkcs12store = TrustManager.LoadPkcs12Store(certificate.Uuid, password, CertificateType.ReviewerCertificate);

            if (pkcs12store == null)
            {
                return(View("OperationNotAllowed"));
            }

            var reviewer = await DBContext.Reviewer
                           .SingleOrDefaultAsync(r => r.Uuid == certificate.ReviewerUuid);

            var metadata = new PDFMetadata()
            {
                Title    = "PDF Signed Document" + document.Name,
                Author   = certificate.Reviewer.Name,
                Creator  = certificate.Reviewer.Name,
                Producer = certificate.Reviewer.Name,
                Keywords = "UUID:" + document.Uuid,
                Subject  = "Signed Document"
            };

            var signature = new Signature()
            {
                Store      = pkcs12store,
                Reason     = "Document Aproved, Date:" + DateTime.UtcNow.Date,
                Page       = 1,
                Contact    = certificate.Reviewer.Email,
                CustomText = "Signed by " + reviewer.Name + " on " + DateTime.UtcNow.Date.ToString("dd-MM-yyyy") + " - " + description,
                Top        = 10,
                Left       = 10,
                Width      = 200,
                Height     = 50,

                Multi   = false,
                Visible = true
            };

            SignatureManager.Sign(
                signature,
                metadata,
                FileManager.DocumentRoot + "/" + document.Uuid,
                FileManager.DocumentRoot + "/" + document.Uuid + "-signed");

            document.SignatureDate = DateTime.UtcNow.Date;
            DBContext.Document.Update(document);
            await DBContext.SaveChangesAsync();

            var message = await RenderService
                          .RenderToStringAsync("Email/DocumentSigned", document);

            var attachments = new List <Attachment> ();

            attachments.Add(
                await EmailManager.LoadAttachment(
                    FileManager.DocumentRoot + "/" + document.Uuid + "-signed",
                    "Signed by " + reviewer.Name + "-" + document.Name,
                    document.MimeType));

            attachments.Add(
                await EmailManager.LoadAttachment(
                    TrustManager.CertificatePath(
                        certificate.Uuid,
                        CertificateType.ReviewerCertificate,
                        StoreFormat.CRT),
                    "public.crt",
                    "application/x-x509-ca-cert"));

            attachments.Add(
                await EmailManager.LoadAttachment(
                    TrustManager.CertificatePath(
                        "root",
                        CertificateType.AuthorityCertificate,
                        StoreFormat.CRT),
                    "authority.crt",
                    "application/x-x509-ca-cert"));

            var response = await EmailManager.SendEmailHTML(
                message,
                EmailManager.Sender,
                certificate.Reviewer.Email,
                "Your signed document is ready",
                attachments
                );

            if (!response.Successful)
            {
                return(View("ErrorSendingDocument", document));
            }

            return(View("DocumentSigned", document));
        }
        public static EncryptionManager CreateFromConfig(EncryptionLevel?nullableLevel, TrustManager trustManager,
                                                         ILogger logger)
        {
            var encrypted = ParseEncrypted(nullableLevel);

            if (encrypted && trustManager == null)
            {
                return(new EncryptionManager(true, CreateSecureTrustManager(logger)));
            }
            return(new EncryptionManager(encrypted, trustManager));
        }
Example #29
0
        }        public static void Main(string[] args)
        {
            var build = WebHost.CreateDefaultBuilder(args);

            Environment = build.GetSetting("environment");

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile($"appsettings.{Environment}.json", optional: false);

            Configuration = builder.Build();
            TrustManager.Init(Configuration);
            EmailManager.Init(Configuration);
            FileManager.Init(Configuration);

            DateTime now = DateTime.UtcNow.Date;

            if (!TrustManager
                .CertificateAvailable(
                    "webserver", CertificateType.ServerCertificate, StoreFormat.PFX))
            {
                ServerDN = new DistinguishedName();

                ServerDN.CommonName         = Configuration["WebServer:ServerCertificate:CommonName"];
                ServerDN.Organization       = Configuration["WebServer:ServerCertificate:Org"];
                ServerDN.OrganizationalUnit = Configuration["WebServer:ServerCertificate:OrgUnit"];
                ServerDN.Locality           = Configuration["WebServer:ServerCertificate:Locality"];
                ServerDN.Country            = Configuration["WebServer:ServerCertificate:Country"];
                ServerDN.State = Configuration["WebServer:ServerCertificate:State"];
                ServerDN.Email = Configuration["WebServer:ServerCertificate:Email"];

                ServerCertificate = TrustManager.IssueCertificate(
                    "webserver",
                    Configuration["WebServer:ServerCertificate:Password"],
                    ServerDN,
                    CertificateType.ServerCertificate,
                    now,
                    now.AddYears(50));
            }
            else
            {
                ServerCertificate = TrustManager.LoadCertificate(
                    "webserver",
                    Configuration["WebServer:ServerCertificate:Password"],
                    CertificateType.ServerCertificate,
                    StoreFormat.PFX);
            }

            if (!TrustManager
                .CertificateAvailable(
                    "administrator", CertificateType.AdministratorCertificate, StoreFormat.PFX))
            {
                AdministratorDN = new DistinguishedName();

                AdministratorDN.CommonName         = Configuration["WebServer:AdministratorCertificate:CommonName"];
                AdministratorDN.Organization       = Configuration["WebServer:AdministratorCertificate:Org"];
                AdministratorDN.OrganizationalUnit = Configuration["WebServer:AdministratorCertificate:OrgUnit"];
                AdministratorDN.Locality           = Configuration["WebServer:AdministratorCertificate:Locality"];
                AdministratorDN.Country            = Configuration["WebServer:AdministratorCertificate:Country"];
                AdministratorDN.State = Configuration["WebServer:AdministratorCertificate:State"];
                AdministratorDN.Email = Configuration["WebServer:AdministratorCertificate:Email"];

                AdministratorCertificate =
                    TrustManager.IssueCertificate(
                        "administrator",
                        Configuration["WebServer:AdministratorCertificate:Password"],
                        AdministratorDN,
                        CertificateType.AdministratorCertificate,
                        now,
                        now.AddYears(50));
            }
            else
            {
                AdministratorCertificate =
                    TrustManager.LoadCertificate(
                        "administrator",
                        Configuration["WebServer:AdministratorCertificate:Password"],
                        CertificateType.AdministratorCertificate,
                        StoreFormat.PFX);
            }

            var kestrelopts    = new KestrelServerOptions();
            var adapterOptions = new HttpsConnectionAdapterOptions();

            adapterOptions.ClientCertificateMode       = ClientCertificateMode.AllowCertificate;
            adapterOptions.ClientCertificateValidation = TrustManager.ValidateCertificate;
            adapterOptions.SslProtocols      = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
            adapterOptions.ServerCertificate = Program.ServerCertificate;

            var host = build
                       .UseKestrel(options => {
                options.Listen(IPAddress.Any, Port,
                               listenOptions => {
                    listenOptions
                    .UseHttps(adapterOptions);
                });
            }
                                   )
                       .UseStartup <Startup>()
                       .Build();

            host.Run();
        }
 public void init(KeyManager[] km, TrustManager[] tm, SecureRandom sr)
 {
 }