Пример #1
0
    public IStreamCalculator CreateCalculator()
    {
        ISigner signer = SignerUtilities.GetSigner(X509Utilities.GetSignatureName(algID));

        signer.Init(forSigning: false, publicKey);
        return(new VerifierCalculator(signer));
    }
Пример #2
0
        /// <summary>
        /// Generate an X509Certificate.
        /// </summary>
        /// <param name="privateKey">The private key of the issuer that is signing this certificate.</param>
        /// <param name="Extensions">Set of extensions to include in the certificate.</param>
        /// <returns>
        /// An X509Certificate.
        /// </returns>
        /// <exception cref="PolicyEnforcementException">CA policy violation</exception>
        /// <exception cref="CertificateEncodingException">
        /// Exception encoding TBS cert
        /// or
        /// Exception producing certificate object
        /// </exception>
        public virtual X509Certificate Generate(AsymmetricKeyParameter privateKey, X509Extensions Extensions)
        {
            TbsCertificateStructure tbsCert = GenerateTbsCert(Extensions);

            // Check this complies with policy
            if (policy != null)
            {
                TestAgainstPolicy test = new TestAgainstPolicy(policy);
                if (!test.report(tbsCert))
                {
                    throw new PolicyEnforcementException(test.status.ToString());
                }
            }

            byte[] signature;

            try
            {
                signature = X509Utilities.GetSignatureForObject(
                    sigOid, signatureAlgorithm, privateKey, null, tbsCert);
            }
            catch (Exception e)
            {
                throw new CertificateEncodingException("Exception encoding TBS cert", e);
            }

            try
            {
                return(new X509Certificate(new X509CertificateStructure(tbsCert, sigAlgId, new DerBitString(signature))));
            }
            catch (CertificateParsingException e)
            {
                throw new CertificateEncodingException("Exception producing certificate object", e);
            }
        }
Пример #3
0
    public Asn1VerifierFactory(string algorithm, AsymmetricKeyParameter publicKey)
    {
        DerObjectIdentifier algorithmOid = X509Utilities.GetAlgorithmOid(algorithm);

        this.publicKey = publicKey;
        algID          = X509Utilities.GetSigAlgID(algorithmOid, algorithm);
    }
Пример #4
0
        /// <summary>
        /// Generate a new X509Certificate specifying a SecureRandom instance that you would like to use.
        /// </summary>
        /// <param name="privateKey">The private key of the issuer used to sign this certificate.</param>
        /// <param name="random">The Secure Random you want to use.</param>
        /// <returns>An X509Certificate.</returns>
        private X509Certificate generate(SecureRandom random, AsymmetricKeyParameter privateKey)
        {
            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            byte[] signature;

            try
            {
                signature = X509Utilities.GetSignatureForObject(
                    sigOID, signatureAlgorithm, (AsymmetricKeyParameter)privateKey, random, tbsCert);
            }
            catch (Exception e)
            {
                throw new CertificateEncodingException("Exception encoding TBS cert", e);
            }

            try
            {
                return(GenerateJcaObject(tbsCert, signature));
            }
            catch (CertificateParsingException e)
            {
                throw new CertificateEncodingException("Exception producing certificate object", e);
            }
        }
    public Asn1SignatureFactory(string algorithm, AsymmetricKeyParameter privateKey, SecureRandom random)
    {
        DerObjectIdentifier algorithmOid = X509Utilities.GetAlgorithmOid(algorithm);

        this.algorithm  = algorithm;
        this.privateKey = privateKey;
        this.random     = random;
        algID           = X509Utilities.GetSigAlgID(algorithmOid, algorithm);
    }
Пример #6
0
        /// <summary>
        /// Set the signature algorithm that will be used to sign this certificate.
        /// </summary>
        /// <param name="signatureAlgorithm">Name of the signature algorithm</param>
        public void SetSignatureAlgorithm(string signatureAlgorithm)
        {
            this.signatureAlgorithm = signatureAlgorithm;

            try
            {
                sigOid = X509Utilities.GetAlgorithmOid(signatureAlgorithm);
            }
            catch (Exception)
            {
                throw new ArgumentException("Unknown signature type requested: " + signatureAlgorithm);
            }

            sigAlgId = X509Utilities.GetSigAlgID(sigOid, signatureAlgorithm);

            tbsGen.SetSignature(sigAlgId);
        }
Пример #7
0
        /// <summary>
        /// Issues the certificate.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="profile">The profile</param>
        /// <param name="notBefore">The not before.</param>
        /// <param name="notAfter">The not after.</param>
        /// <returns>
        /// Certificate
        /// </returns>
        /// <exception cref="System.ArgumentException">Invalid signature algorithm in request</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Invalid lifetime units in ValidityPeriod</exception>
        private X509Certificate issueCertificate(Pkcs10CertificationRequest request, Profile.Profile profile, DateTime notBefore, DateTime notAfter)
        {
            X509Certificate newCert;
            string          profileName = "";

            // Parse the request
            Pkcs10Parser p10 = new Pkcs10Parser(request);

            // Check that correct sig algorithm has been used
            DerObjectIdentifier sigAlgOid = X509Utilities.GetAlgorithmOid(signatureAlgorithm);

            if (!p10.SignatureAlgorithm.Equals(sigAlgOid))
            {
                logEvent(LogEvent.EventType.Error, "Invalid signature algorithm in request: " + p10.SignatureAlgorithm.ToString());
                throw new ArgumentException("Invalid signature algorithm in request", p10.SignatureAlgorithm.ToString());
            }

            // Create a Cert Generator according to the FIPS 140 policy and CA Type
            ICertGen certGen;

            if ((fips140) && (type == CA_Type.dhTA.ToString()))
            {
                certGen = new SysV1CertGen();
            }
            else if ((fips140) && (type != CA_Type.dhTA.ToString()))
            {
                certGen = new SysV3CertGen(policyEnforcement);
            }
            else
            {
                certGen = new BcV3CertGen(policyEnforcement);
            }

            // Setup the certificate
            certGen.SetSerialNumber(nextCertSerial());
            certGen.SetIssuerDN(caCertificate.SubjectDN);
            certGen.SetSubjectDN(p10.Subject);
            certGen.SetPublicKey(p10.PublicKey);
            certGen.SetSignatureAlgorithm(signatureAlgorithm);
            if (certGen.GetVersion() == X509ver.V3)
            {
                ((V3CertGen)certGen).AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCertificate.GetPublicKey()));
                ((V3CertGen)certGen).AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(p10.PublicKey));
            }

            // Add further extensions either from profile or request attributes
            // If a profile is specified ignore all attributes apart from SubjAltName
            if (profile != null)
            {
                // Add in SubjAltName if there is one
                if ((p10.SubjectAltNames != null) && (certGen.GetVersion() == X509ver.V3))
                {
                    bool critical = p10.IsCritical(X509Extensions.SubjectAlternativeName);
                    ((V3CertGen)certGen).AddExtension(X509Extensions.SubjectAlternativeName, critical, p10.SubjectAltNames);
                }

                // Capture the profile name for database
                profileName = profile.Name;

                // cut the cert
                newCert = generate(certGen, profile, notBefore, notAfter);
            }
            else    // No profile
            {
                // Set the validity period
                certGen.SetNotBefore(notBefore.ToUniversalTime());
                certGen.SetNotAfter(notAfter.ToUniversalTime());

                // Do what it says in the request
                newCert = generate(certGen, p10.Extensions);
            }

            // Add certificate to the CA DB
            Database.AddCertificate(newCert, request.GetDerEncoded(), profileName, dbFileLocation, caCertificate, cspParam);
            logEvent(LogEvent.EventType.DBAddCert, "DB: Certificate added: " + newCert.SerialNumber.ToString());

            return(newCert);
        }
Пример #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            Config.Version = Configuration.GetSection("Misc").GetSection("Version").Value;

            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
            });

            /*
             * Identity Server 4
             * http://docs.identityserver.io
             *
             * Used for client credentials and authorisation access
             *
             * OpenID/oAuth2 based for ASP.net
             */

            //START =-=-= DO NOT MODIFY UNLESS DISCUSSED USER AUTH IS HERE =-=-= START

            X509Certificate2 signingCert;

            if (File.Exists(Configuration.GetSection("X509Details").GetSection("PathToFile").Value))
            {
                signingCert = new X509Certificate2(
                    Configuration.GetSection("X509Details").GetSection("PathToFile").Value,
                    Configuration.GetSection("X509Details").GetSection("DecryptionPassword").Value);
            }
            else
            {
                signingCert = X509Utilities.BuildSelfSignedServerCertificate(
                    Configuration.GetSection("X509Details").GetSection("CertificateName").Value,
                    Configuration.GetSection("X509Details").GetSection("DecryptionPassword").Value);

                File.WriteAllBytes(Configuration.GetSection("X509Details").GetSection("PathToFile").Value,
                                   signingCert.Export(X509ContentType.Pkcs12,
                                                      Configuration.GetSection("X509Details").GetSection("DecryptionPassword").Value));
            }

            Console.WriteLine("ConfigureServices Start");

            var appUri = Configuration.GetSection("Hosts").GetSection("APPFqdn").Value;
            var apiUri = Configuration.GetSection("Hosts").GetSection("APIFqdn").Value;

            ApplicationInfo.AppUrl = appUri;
            ApplicationInfo.ApiUrl = apiUri;

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                {
                    builder.WithOrigins(appUri)
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
            });

            //Startup Autofac
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <ApplicationIdentityDbContext>(options
                                                                 => options.UseMySql(Configuration.GetConnectionString("ApplicationDatabase"),
                                                                                     optionsBuilder => optionsBuilder.MigrationsAssembly(migrationsAssembly)));

            services.AddMvcCore()
            .AddAuthorization();

            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationIdentityDbContext>()
            .AddDefaultTokenProviders();

            services
            .AddIdentityServer(options =>
            {
                options.PublicOrigin = apiUri;
            })
            .AddOperationalStore(options =>
            {
                options
                .ConfigureDbContext = optionsBuilder => optionsBuilder
                                      .UseMySql(Configuration.GetConnectionString("ApplicationDatabase"),
                                                sqlOptions => sqlOptions.MigrationsAssembly(migrationsAssembly));
                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = 604800;     //stay logged in for 1 week
            })
            .AddConfigurationStore(options => options
                                   .ConfigureDbContext = optionsBuilder => optionsBuilder
                                                         .UseMySql(Configuration.GetConnectionString("ApplicationDatabase"), sqlOptions => sqlOptions.MigrationsAssembly(migrationsAssembly)))
            .AddSigningCredential(signingCert);

            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority            = Configuration.GetSection("Hosts").GetSection("APIFqdn").Value;
                options.Audience             = "carbon.api";
                options.RequireHttpsMetadata = false;
                options.IncludeErrorDetails  = true;
                options.Events = new JwtBearerEvents()
                {
                    OnChallenge = context =>
                    {
                        context.Response.StatusCode = 401;
                        return(Task.CompletedTask);
                    }
                };
            });

            //TODO this is soon to be deprecated. Find a new solution.
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            //  END =-=-= DO NOT MODIFY UNLESS DISCUSSED USER AUTH IS HERE =-=-= END

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version        = "v1",
                    Title          = "CoEuS API",
                    Description    = "Carbon Event Scout",
                    TermsOfService = new Uri(appUri + "/privacy"),
                    Contact        = new OpenApiContact
                    {
                        Name  = "Owen Holloway",
                        Email = string.Empty,
                        Url   = new Uri("https://zeryter.xyz"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url  = new Uri(appUri + "/privacy"),
                    }
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] {}
                    }
                });

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows()
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri($"{apiUri}/connect/authorize"),
                            TokenUrl         = new Uri($"{apiUri}/connect/token"),

                            Scopes = new Dictionary <string, string>()
                            {
                                { "carbon.read", "carbon API read" },
                                { "carbon.write", "carbon API write" }
                            }
                        }
                    }
                });
            });

            Console.WriteLine("ConfigureServices Completed");
        }