Ejemplo n.º 1
0
        public async Task <AccountEntity> Create(string password, AccountSecurityLevel securityLevel)
        {
            password = password?.ToUpperInvariant() ?? throw new ArgumentNullException(nameof(password));

            if (IsExists)
            {
                throw new AccountExistsException($"account {State.Name} already exists; cannot create account");
            }

            var random = GrainFactory.GetGrain <IRandomService>(0);

            using (var sha1 = new Digester(SHA1.Create()))
            {
                var salt = await random.GetRandomBigInteger(32);

                var identityHash = sha1.CalculateDigest($"{this.GetPrimaryKeyString()}:{password}");
                var secret       = BigIntegers.FromUnsignedByteArray(sha1.CalculateDigest(new byte[][] { salt.ToByteArray(32), identityHash }));
                var verifier     = BigInteger.ModPow(G, secret, N);

                State.Salt          = salt;
                State.Verifier      = verifier;
                State.Name          = this.GetPrimaryKeyString();
                State.Enabled       = true;
                State.SecurityLevel = securityLevel;
            }

            await WriteStateAsync();

            // orleans will automatically make a safe copy of this
            return(State);
        }
Ejemplo n.º 2
0
        public PhoneParserController(IConfiguration configuration, IWebHostEnvironment env, Digester digester)
        {
            _digester = digester;
            var digesterOptions = new DigesterOptions();

            configuration.GetSection(DigesterOptions.PhoneParser).Bind(digesterOptions);
            _digester.AcceptanceRules = digesterOptions.AcceptanceRules;
            _digester.CorrectionRules = digesterOptions.CorrectionRules;
            _digester.AllOtherRules   = digesterOptions.AllOtherRules;

            _env = env;
        }
Ejemplo n.º 3
0
        public IExpression Refine(Digester digest)
        {
            if (digest.Done)
            {
                return(this);
            }

            string accessor = digest.Digest();

            if (accessor.Equals("learnset") || accessor.Equals("ls"))
            {
                return(new LearnsetSelectorExpression(Pokemon).Refine(digest));
            }

            return(this);
        }
Ejemplo n.º 4
0
        public static ItemList GetItemList(string databaseSelect)
        {            
            string rule = databaseSelect + @"\DatabaseRule.xml";
            string data = databaseSelect + @"\DatabaseSelectorConfig.xml";

            Digester dig = new Digester();
            try
            {
                dig.Configure(rule);
            }
            catch (Exception e)
            {
                throw e;
            }
            var list = (ItemList)dig.Parse(data);
            return list;
        }
Ejemplo n.º 5
0
 private static void CreateBundleDataDigester()
 {
     if (_bundleDataDigester == null)
     {
         _bundleDataDigester = new Digester();
         _bundleDataDigester.Rules.NamespaceURI = "urn:uiosp-bundle-manifest-2.0";
         string pattern = string.Empty;
         pattern = "Bundle";
         _bundleDataDigester.AddObjectCreate(pattern, typeof(BundleData));
         _bundleDataDigester.AddRule(pattern, new SetManifestPropertiesRule());
         pattern = "Bundle/BundleInfo";
         _bundleDataDigester.AddObjectCreate(pattern, typeof(BundleInfoData));
         _bundleDataDigester.AddRule(pattern, new SetManifestPropertiesRule());
         _bundleDataDigester.AddRule(pattern, new NextPropertySetterRule("BundleInfo"));
         pattern = "Bundle/Activator";
         _bundleDataDigester.AddObjectCreate(pattern, typeof(ActivatorData));
         _bundleDataDigester.AddRule(pattern, new SetManifestPropertiesRule());
         _bundleDataDigester.AddRule(pattern, new NextPropertySetterRule("Activator"));
         pattern = "Bundle/Runtime";
         _bundleDataDigester.AddObjectCreate(pattern, typeof(RuntimeData));
         _bundleDataDigester.AddRule(pattern, new NextPropertySetterRule("Runtime"));
         pattern = "Bundle/Runtime/Assembly";
         _bundleDataDigester.AddObjectCreate(pattern, typeof(AssemblyData));
         _bundleDataDigester.AddRule(pattern, new SetManifestPropertiesRule());
         _bundleDataDigester.AddSetNext(pattern, "AddAssembly");
         pattern = "Bundle/Runtime/Dependency";
         _bundleDataDigester.AddObjectCreate(pattern, typeof(DependencyData));
         _bundleDataDigester.AddRule(pattern, new SetManifestPropertiesRule());
         _bundleDataDigester.AddSetNext(pattern, "AddDependency");
         pattern = "Bundle/Services/Service";
         _bundleDataDigester.AddObjectCreate(pattern, typeof(ServiceData));
         _bundleDataDigester.AddRule(pattern, new SetServicePropertiesRule());
         _bundleDataDigester.AddSetNext(pattern, "AddService");
         pattern = "Bundle/ExtensionPoint";
         _bundleDataDigester.AddObjectCreate(pattern, typeof(ExtensionPointData));
         _bundleDataDigester.AddRule(pattern, new SetManifestPropertiesRule());
         _bundleDataDigester.AddSetNext(pattern, "AddExtensionPoint");
         pattern = "Bundle/Extension";
         _bundleDataDigester.AddObjectCreate(pattern, typeof(ExtensionData));
         _bundleDataDigester.AddRule(pattern, new SetManifestPropertiesRule());
         _bundleDataDigester.AddSetNext(pattern, "AddExtension");
     }
 }
Ejemplo n.º 6
0
        public override void ExecuteCommand(AuthServer server, string[] arguments)
        {
            if (arguments.Length < 3)
            {
                log.ErrorFormat("{0} requires 2 arguments", Name);
            }
            else
            {
                string identity = arguments[1].ToUpperInvariant();
                string password = arguments[2].ToUpperInvariant();

                log.InfoFormat("creating new account '{0}'", identity);

                SecureRemotePasswordArgs srp = new SecureRemotePasswordArgs();
                using (Digester sha1 = new Digester(new SHA1CryptoServiceProvider()))
                {
                    BigInteger s = server.SecureRandom.GetRandomBigInteger(32);
                    BigInteger x = BigIntegers.FromUnsignedByteArray(sha1.CalculateDigest(new byte[][] { Arrays.Left(s.ToByteArray(), 32), sha1.CalculateDigest(identity + ':' + password) }));
                    BigInteger v = BigInteger.ModPow(srp.g, x, srp.N);

                    if (server.AuthDB.ExecuteQuery("select 1 from account where name = ?", identity, reader =>
                    {
                        if (reader.Read())
                        {
                            log.ErrorFormat("cannot create account '{0}': an account with this name already exists", identity);
                            return(false);
                        }
                        return(true);
                    }))
                    {
                        int result = server.AuthDB.ExecuteNonQuery("insert into account (name, salt, verifier) values (?, ?, ?)", new object[] { identity, string.Format("{0:X}", s), string.Format("{0:X}", v) });
                        if (result == 1)
                        {
                            log.InfoFormat("successfully created account '{0}'", identity);
                        }
                        else
                        {
                            log.ErrorFormat("failed to create account '{0}'. expected 1 update, got {1}", identity, result);
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public static ItemList GetItemList(string databaseSelect)
        {
            string rule = databaseSelect + @"\DatabaseRule.xml";
            string data = databaseSelect + @"\DatabaseSelectorConfig.xml";

            Digester dig = new Digester();

            try
            {
                dig.Configure(rule);
            }
            catch (Exception e)
            {
                throw e;
            }
            var list = (ItemList)dig.Parse(data);

            return(list);
        }
Ejemplo n.º 8
0
        public static IExpression Parse(string query)
        {
            Digester digest = new Digester(query);

            if (digest.Done)
            {
                return(new EmptyExpression());
            }

            string type = digest.Digest();

            if (Utils.IsPokemon(type))
            {
                return(new PokemonExpression(Data.Pokemons.Find(p => p.Name.Equals(type))).Refine(digest));
            }
            else
            {
            }

            return(new EmptyExpression());
        }
Ejemplo n.º 9
0
        public IExpression Refine(Digester digest)
        {
            if (digest.Done)
            {
                return(this);
            }

            string def = digest.Digest();

            //	if (Utils.IsGen(digest.Peek()) || Utils.IsGame(digest.Peek())) {
            //	}

            if (Utils.IsGen(def))
            {
                // default is level up when unspecified
                return(new LearnsetExpression(Pokemon, Data.GetMoveMethod("level up").Id, Utils.GetGen(def)));
            }
            else if (Utils.IsGame(def))
            {
                return(new LearnsetExpression(Pokemon, Data.GetMoveMethod("level up").Id, -1, Utils.GetGameId(def)));
            }

            return(this);
        }
Ejemplo n.º 10
0
        public static Asn1EncodableVector GenerateSignerInfo(X509Certificate2 cert,
                                                             String digestAlgorithmName,
                                                             byte[] datos,
                                                             AdESPolicy policy,
                                                             bool signingCertificateV2,
                                                             byte[] messageDigest,
                                                             DateTime signDate,
                                                             bool padesMode,
                                                             String contentType,
                                                             String contentDescription)
        {
            // ALGORITMO DE HUELLA DIGITAL
            AlgorithmIdentifier digestAlgorithmOID = SigUtils.MakeAlgId(AOAlgorithmID.GetOID(digestAlgorithmName));

            // // ATRIBUTOS

            // authenticatedAttributes
            Asn1EncodableVector contexExpecific = InitContexExpecific(
                digestAlgorithmName,
                datos,
                Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id,
                messageDigest,
                signDate,
                padesMode
                );

            // Serial Number
            // comentar lo de abajo para version del rfc 3852

            if (signingCertificateV2)
            {
                // INICIO SINGING CERTIFICATE-V2

                /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
                 * CertificateSerialNumber */



                TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
                    Asn1Object.FromByteArray(
                        new Org.BouncyCastle.X509.X509Certificate(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(
                                    cert.GetRawCertData()))).GetTbsCertificate()));

                GeneralNames gns = new GeneralNames(new GeneralName(tbs.Issuer));

                IssuerSerial isuerSerial = new IssuerSerial(gns, tbs.SerialNumber);

                /** ESSCertIDv2 ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier
                 * DEFAULT {algorithm id-sha256}, certHash Hash, issuerSerial
                 * IssuerSerial OPTIONAL }
                 * Hash ::= OCTET STRING */

                byte[]        certHash    = Digester.Digest(cert.GetRawCertData(), digestAlgorithmName);
                EssCertIDv2[] essCertIDv2 = { new EssCertIDv2(digestAlgorithmOID, certHash, isuerSerial) };

                /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
                 * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
                 * OPTIONAL }
                 * CertPolicyId ::= OBJECT IDENTIFIER
                 * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
                 * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

                SigningCertificateV2 scv2;
                if (policy.GetPolicyIdentifier() != null)
                {
                    /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
                     * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
                     * } */
                    scv2 = new SigningCertificateV2(essCertIDv2, GetPolicyInformation(policy)); // con politica
                }
                else
                {
                    scv2 = new SigningCertificateV2(essCertIDv2); // Sin politica
                }

                // Secuencia con singningCertificate
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2)));

                // FIN SINGING CERTIFICATE-V2
            }
            else
            {
                // INICIO SINGNING CERTIFICATE

                /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
                 * CertificateSerialNumber } */

                TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
                    Asn1Object.FromByteArray(
                        new Org.BouncyCastle.X509.X509Certificate(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(
                                    cert.GetRawCertData()))).GetTbsCertificate()));

                GeneralName  gn  = new GeneralName(tbs.Issuer);
                GeneralNames gns = new GeneralNames(gn);

                IssuerSerial isuerSerial = new IssuerSerial(gns, tbs.SerialNumber);

                /** ESSCertID ::= SEQUENCE { certHash Hash, issuerSerial IssuerSerial
                 * OPTIONAL }
                 * Hash ::= OCTET STRING -- SHA1 hash of entire certificate */
                byte[] certHash = Digester.Digest(cert.GetRawCertData(), digestAlgorithmName);

                EssCertID essCertID = new EssCertID(certHash, isuerSerial);

                /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
                 * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
                 * OPTIONAL }
                 * CertPolicyId ::= OBJECT IDENTIFIER
                 * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
                 * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

                SigningCertificate scv;
                if (policy.GetPolicyIdentifier() != null)
                {
                    /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
                     * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
                     * } */
                    /*
                     * HAY QUE HACER UN SEQUENCE, YA QUE EL CONSTRUCTOR DE BOUNCY
                     * CASTLE NO TIENE DICHO CONSTRUCTOR.
                     */
                    Asn1EncodableVector v = new Asn1EncodableVector();
                    v.Add(new DerSequence(essCertID));
                    v.Add(new DerSequence(GetPolicyInformation(policy)));
                    scv = SigningCertificate.GetInstance(new DerSequence(v)); // con politica
                }
                else
                {
                    scv = new SigningCertificate(essCertID); // Sin politica
                }

                /** id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
                 * member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16)
                 * id-aa(2) 12 } */
                // Secuencia con singningCertificate
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(scv)));
            }

            // INICIO SIGPOLICYID ATTRIBUTE

            if (policy.GetPolicyIdentifier() != null)
            {
                /**
                 * SigPolicyId ::= OBJECT IDENTIFIER Politica de firma.
                 */
                DerObjectIdentifier doiSigPolicyId = new DerObjectIdentifier(policy.GetPolicyIdentifier().ToLower().Replace("urn:oid:", ""));

                /**
                 *   OtherHashAlgAndValue ::= SEQUENCE {
                 *     hashAlgorithm    AlgorithmIdentifier,
                 *     hashValue        OCTET STRING }
                 *
                 */


                // Algoritmo para el hash
                AlgorithmIdentifier hashid;
                // si tenemos algoritmo de calculo de hash, lo ponemos
                if (policy.GetPolicyIdentifierHashAlgorithm() != null)
                {
                    hashid = SigUtils.MakeAlgId(
                        AOAlgorithmID.GetOID(
                            AOSignConstants.GetDigestAlgorithmName(
                                policy.GetPolicyIdentifierHashAlgorithm())));
                }
                // si no tenemos, ponemos el algoritmo de firma.
                else
                {
                    hashid = digestAlgorithmOID;
                }
                // hash del documento, descifrado en b64
                byte[] hashed;
                if (policy.GetPolicyIdentifierHash() != null)
                {
                    hashed = System.Convert.FromBase64String(policy.GetPolicyIdentifierHash());
                }
                else
                {
                    hashed = new byte[] { 0 };
                }

                DigestInfo otherHashAlgAndValue = new DigestInfo(hashid, hashed);

                /**
                 *   SigPolicyQualifierInfo ::= SEQUENCE {
                 *       SigPolicyQualifierId  SigPolicyQualifierId,
                 *       SigQualifier          ANY DEFINED BY policyQualifierId }
                 */

                AOSigPolicyQualifierInfo spqInfo = null;
                if (policy.GetPolicyQualifier() != null)
                {
                    spqInfo = new AOSigPolicyQualifierInfo(policy.GetPolicyQualifier().ToString());
                }

                /**
                 * SignaturePolicyId ::= SEQUENCE {
                 *  sigPolicyId           SigPolicyId,
                 *  sigPolicyHash         SigPolicyHash,
                 *  sigPolicyQualifiers   SEQUENCE SIZE (1..MAX) OF
                 *                          AOSigPolicyQualifierInfo OPTIONAL}
                 *
                 */
                Asn1EncodableVector v = new Asn1EncodableVector();
                // sigPolicyId
                v.Add(doiSigPolicyId);
                // sigPolicyHash
                v.Add(otherHashAlgAndValue.ToAsn1Object()); // como sequence
                // sigPolicyQualifiers
                if (spqInfo != null)
                {
                    v.Add(spqInfo.toASN1Primitive());
                }

                DerSequence ds = new DerSequence(v);

                // Secuencia con singningCertificate
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAAEtsSigPolicyID, new DerSet(ds.ToAsn1Object())));
                // FIN SIGPOLICYID ATTRIBUTE
            }

            /**
             * Secuencia con el tipo de contenido firmado. No se agrega en firmas PAdES.
             *
             * ContentHints ::= SEQUENCE {
             *	  contentDescription UTF8String (SIZE (1..MAX)) OPTIONAL,
             *	  contentType ContentType }
             */
            if (contentType != null && !padesMode)
            {
                ContentHints contentHints;
                if (contentDescription != null)
                {
                    contentHints = new ContentHints(new DerObjectIdentifier(contentType),
                                                    new DerUtf8String(contentDescription));
                }
                else
                {
                    contentHints = new ContentHints(new DerObjectIdentifier(contentType));
                }
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(
                                        Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAAContentHint,
                                        new DerSet(contentHints.ToAsn1Object())));
            }

            return(contexExpecific);
        }
Ejemplo n.º 11
0
 public Sweeper(Digester <T> source)
 {
     this.source = source;
 }
Ejemplo n.º 12
0
        private void SetValues(String identifier,
                               String identifierHash,
                               String identifierHashAlgorithm,
                               String qualifier)
        {
            if (identifier == null || "".Equals(identifier))
            {
                throw new ArgumentNullException("El identificador de politica no puede ser nulo ni vacio");
            }

            this.policyIdentifier = identifier;

            if (identifierHash != null && (!"0".Equals(identifierHash)) && (identifierHashAlgorithm == null || "".Equals(identifierHashAlgorithm)))
            {
                throw new ArgumentNullException("Si se indica la huella digital del identificador de politica es obligatorio indicar tambien el algoritmo");
            }

            if (identifierHash == null)
            {
                try
                {
                    //this.policyIdentifierHash = System.Convert.ToBase64String(Digester.Digest(UrlReader.ReadUri(new Uri(identifier)), "SHA-512"));
                    //MODIFICACION DAL -> NO DEBERÍA SER "new Uri(qualifier)" EN VEZ DE "new Uri(identifier)" ????
                    if (qualifier != null)
                    {
                        this.policyIdentifierHash          = System.Convert.ToBase64String(Digester.Digest(UrlReader.ReadUri(new Uri(qualifier)), "SHA-512"));
                        this.policyIdentifierHashAlgorithm = "SHA-512";
                    }
                }
                catch (Exception e)
                {
                    throw new ArgumentNullException("Si no se especifica la huella digital de la politica es necesario que el identificador sea una URL accesible universalmente: " + e, e);
                }
            }
            else
            {
                if ("0".Equals(identifierHash))
                {
                    this.policyIdentifierHash = null;
                }
                else
                {
                    if (!AOUtil.IsBase64(new System.Text.UTF8Encoding().GetBytes(identifierHash)))
                    {
                        throw new ArgumentNullException("La huella digital de la politica debe estar en formato Base64");
                    }
                    try
                    {
                        this.policyIdentifierHashAlgorithm = AOSignConstants.GetDigestAlgorithmName(identifierHashAlgorithm);
                    }
                    catch (Exception e)
                    {
                        throw new ArgumentNullException("El algoritmo de huella digital no esta soportado: " + identifierHashAlgorithm, e);
                    }
                    this.policyIdentifierHash = identifierHash;
                }
            }

            if (qualifier != null && (!"".Equals(qualifier)))
            {
                try
                {
                    this.policyQualifier = new Uri(qualifier);
                }
                catch (Exception e)
                {
                    throw new ArgumentNullException("El calificador de la politica debe ser una URL valida", e);
                }
            }
        }
Ejemplo n.º 13
0
Archivo: Rule.cs Proyecto: yshulin/OSGi
 public Rule(Digester digester)
 {
     Digester = digester;
 }
        public static byte[] generateSignedData(
            P7ContentSignerParameters parameters,
            bool omitContent,
            AdESPolicy policy,
            bool signingCertificateV2,
            X509Certificate2 keyEntry,
            byte[] messageDigest,
            bool padesMode,
            String contentType,
            String contentDescription)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("Los parametros no pueden ser nulos");
            }
            String signatureAlgorithm = parameters.GetSignatureAlgorithm();

            X509Certificate2[] signerCertificateChain = parameters.GetSignerCertificateChain();

            DateTime signDate = DateTime.Now;

            // Ya que el contenido de la firma puede ser grande, lo obtenemos solo al principio
            byte[] content = parameters.GetContent();

            byte[] preSignature = CAdESTriPhaseSigner.PreSign(
                AOSignConstants.GetDigestAlgorithmName(signatureAlgorithm),
                (omitContent) ? null : content,
                signerCertificateChain,
                policy,
                signingCertificateV2,
                (messageDigest == null && content != null) ?
                Digester.Digest(content, AOSignConstants.GetDigestAlgorithmName(signatureAlgorithm)) : messageDigest,
                signDate,
                padesMode,
                contentType,
                contentDescription
                );

            byte[] signature = new AOPkcs1Signer().sign(preSignature, signatureAlgorithm, keyEntry);

            return(CAdESTriPhaseSigner.PostSign(
                       AOSignConstants.GetDigestAlgorithmName(signatureAlgorithm),
                       (omitContent) ? null : content,
                       signerCertificateChain,
                       signature,
                       // Volvemos a crear la prefirma simulando una firma trifasica en la que la postfirma no cuenta con el
                       // resultado de la prefirma
                       CAdESTriPhaseSigner.PreSign(
                           AOSignConstants.GetDigestAlgorithmName(signatureAlgorithm),
                           (omitContent) ? null : content,
                           signerCertificateChain,
                           policy,
                           signingCertificateV2,
                           (messageDigest == null && content != null) ?
                           Digester.Digest(content, AOSignConstants.GetDigestAlgorithmName(signatureAlgorithm)) : messageDigest,
                           signDate,
                           padesMode,
                           contentType,
                           contentDescription
                           )
                       ));
        }
Ejemplo n.º 15
0
        static Asn1EncodableVector InitContexExpecific(String digestAlgorithm,
                                                       byte[] datos,
                                                       String dataType,
                                                       byte[] messageDigest,
                                                       DateTime signDate,
                                                       bool padesMode)
        {
            // authenticatedAttributes
            Asn1EncodableVector contexExpecific = new Asn1EncodableVector();

            // tipo de contenido
            if (dataType != null)
            {
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.ContentType, new DerSet(new DerObjectIdentifier(dataType))));
            }

            // fecha de firma, no se anade en modo PAdES
            if (!padesMode)
            {
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.SigningTime, new DerSet(new DerUtcTime(signDate))));
            }

            // MessageDigest
            contexExpecific.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    CmsAttributes.MessageDigest,
                    new DerSet(new DerOctetString((messageDigest != null) ? messageDigest : Digester.Digest(datos, digestAlgorithm)))
                    )
                );

            return(contexExpecific);
        }
Ejemplo n.º 16
0
 public IExpression Refine(Digester digest)
 {
     return(this);
 }
Ejemplo n.º 17
0
        public unsafe override void ExecuteCommand(AuthSession session, AuthRequest request, LogonProof header)
        {
            log.DebugFormat("handling {0} opcode. securityflags = {1}, keycount = {2}", header.Opcode, header.SecurityFlags, header.KeyCount);

            using (Digester sha1 = new Digester(new SHA1CryptoServiceProvider()))
            {
                // client sends public ephemeral value A
                session.SRP.A = BigIntegers.FromUnsignedByteArray(FixedBuffers.ToArray(header.A, 32));

                log.DebugFormat("server N = {0:X}", session.SRP.N);
                log.DebugFormat("client A = {0:X}", session.SRP.A);
                log.DebugFormat("server B = {0:X}", session.SRP.B);
                log.DebugFormat("server s = {0:X}", session.SRP.s);
                log.DebugFormat("server v = {0:X}", session.SRP.v);

                // srp is required to abort if A or B is 0
                if (session.SRP.A.IsZero)
                {
                    throw new ArgumentException("security abort: SRP6.A = 0");
                }

                session.SRP.u = BigIntegers.FromUnsignedByteArray(sha1.CalculateDigest(session.SRP.A, session.SRP.B));
                session.SRP.S = BigInteger.ModPow(session.SRP.A * BigInteger.ModPow(session.SRP.v, session.SRP.u, session.SRP.N), session.SRP.b, session.SRP.N);

                log.DebugFormat("server u = {0:X}", session.SRP.u);
                log.DebugFormat("server S = {0:X}", session.SRP.S);

                // BigIntever.ToByteArrays are chopped/padded on the right (taking the 'Left' of the array) because of little endian. we're either killing the sign byte or padding with leading 0's in case of small number
                byte[] t  = Arrays.Left(session.SRP.S.ToByteArray(), 32);
                byte[] t1 = new byte[16];
                byte[] vK = new byte[40];

                // modified srp - uses a session key (vK, K) created by interleaving two hashes (tK) created from half (t1) of the shared secret (S)
                for (int i = 0; i < 16; ++i)
                {
                    t1[i] = t[i * 2];
                }
                byte[] tK = sha1.CalculateDigest(t1);
                for (int i = 0; i < 20; ++i)
                {
                    vK[i * 2] = tK[i];
                }

                for (int i = 0; i < 16; ++i)
                {
                    t1[i] = t[i * 2 + 1];
                }
                tK = sha1.CalculateDigest(t1);
                for (int i = 0; i < 20; ++i)
                {
                    vK[i * 2 + 1] = tK[i];
                }

                session.SRP.K = BigIntegers.FromUnsignedByteArray(vK);
                log.DebugFormat("server K = {0:X}", session.SRP.K);

                byte[] Nghash = sha1.CalculateDigest(Arrays.Left(session.SRP.N.ToByteArray(), 32));
                byte[] ghash  = sha1.CalculateDigest(Arrays.Left(session.SRP.g.ToByteArray(), 1));

                for (int i = 0; i < sha1.DigestSize; ++i)
                {
                    Nghash[i] ^= ghash[i];
                }

                // calculating M1
                byte[] M1S = sha1.CalculateDigest(new byte[][]
                {
                    Nghash,
                    sha1.CalculateDigest(session.SRP.I),
                    Arrays.Left(session.SRP.s.ToByteArray(), 32),
                    Arrays.Left(session.SRP.A.ToByteArray(), 32),
                    Arrays.Left(session.SRP.B.ToByteArray(), 32),
                    vK,
                });

                byte[] M1C = FixedBuffers.ToArray(header.M1, 20);

                BigInteger M1s = BigIntegers.FromUnsignedByteArray(M1S);
                BigInteger M1c = BigIntegers.FromUnsignedByteArray(M1C);

                log.DebugFormat("client M1 = {0:X}", M1c);
                log.DebugFormat("server M1 = {0:X}", M1s);

                // if client M1 matches server M1, then client and server have agreed on shared session key (vK, K), but only server knows that right now
                if (M1s == M1c)
                {
                    session.Status = AuthStatus.Authenticated;

                    // need to send M2 so client knows session key is shared also
                    byte[] M2S = sha1.CalculateDigest(new byte[][] {
                        Arrays.Left(session.SRP.A.ToByteArray(), 32),
                        M1C,
                        Arrays.Left(session.SRP.K.ToByteArray(), 40),
                    });
                    BigInteger M2s = BigIntegers.FromUnsignedByteArray(M2S);

                    log.InfoFormat("authentication successful for user {0}", session.SRP.I);
                    log.DebugFormat("server M2 = {0:X}", M2s);

                    int result = session.Server.AuthDB.ExecuteNonQuery("update account set last_login = now(), last_ip = ?, session_key = ? where name = ?", session.RemoteEndPoint.Address.ToString(), string.Format("{0:X}", session.SRP.K), session.SRP.I);
                    if (result != 1)
                    {
                        log.ErrorFormat("expected 1 result when updating account for login, but got {0}", result);
                    }

                    using (ByteBuffer response = new ByteBuffer())
                    {
                        response.Append((byte)AuthRequestOpcode.LogonProof);
                        response.Append((byte)AuthResponseOpcode.Success);
                        response.Append(Arrays.Left(M2S, 20));
                        response.Append(0);
                        session.Send(response.GetArraySegment());
                    }
                }
                else
                {
                    log.InfoFormat("authentication failed for user {0}", session.SRP.I);
                    using (ByteBuffer response = new ByteBuffer())
                    {
                        response.Append((byte)AuthRequestOpcode.LogonProof);
                        response.Append((byte)AuthResponseOpcode.FailBadCredentials);
                        session.Send(response.GetArraySegment());
                    }
                }
            }
        }
Ejemplo n.º 18
0
 public abstract void AddRules(Digester digester);
Ejemplo n.º 19
0
        public Task <SrpResult> SrpHandshake(BigInteger a, BigInteger m1)
        {
            if (!IsExists)
            {
                throw new AccountDoesNotExistException($"account {this.GetPrimaryKeyString()} does not exist");
            }
            if (AuthState != AccountAuthState.ParametersGenerated)
            {
                throw new AccountStateException("cannot handshake without first generating SRP initial parameters");
            }
            if (a.IsZero)
            {
                throw new SrpException("A cannot be zero");
            }
            if (BPublic.IsZero)
            {
                throw new SrpException("B cannot be zero");
            }

            using (var sha1 = new Digester(SHA1.Create()))
            {
                var u = BigIntegers.FromUnsignedByteArray(sha1.CalculateDigest(a, BPublic));
                var s = BigInteger.ModPow(a * BigInteger.ModPow(State.Verifier, u, N), BPrivate, N);

                var t  = s.ToByteArray(32);
                var t1 = new byte[16];
                var vK = new byte[40];

                // modified srp - uses a session key (vK, K) created by interleaving two hashes (tK) created from half (t1) of the shared secret (s)
                for (int i = 0; i < 16; ++i)
                {
                    t1[i] = t[i * 2];
                }
                var tK = sha1.CalculateDigest(t1);
                for (int i = 0; i < 20; ++i)
                {
                    vK[i * 2] = tK[i];
                }

                for (int i = 0; i < 16; ++i)
                {
                    t1[i] = t[i * 2 + 1];
                }
                tK = sha1.CalculateDigest(t1);
                for (int i = 0; i < 20; ++i)
                {
                    vK[i * 2 + 1] = tK[i];
                }

                SessionKey = BigIntegers.FromUnsignedByteArray(vK);

                var nghash = sha1.CalculateDigest(N.ToByteArray(32));
                var ghash  = sha1.CalculateDigest(new[] { G });

                for (int i = 0; i < sha1.DigestSize; ++i)
                {
                    nghash[i] ^= ghash[i];
                }

                var serverM1Bytes = sha1.CalculateDigest(new byte[][]
                {
                    nghash,
                    sha1.CalculateDigest(State.Name),
                    State.Salt.ToByteArray(32),
                    a.ToByteArray(32),
                    BPublic.ToByteArray(32),
                    vK,
                });

                // if client M1 matches server M1, then client and server have agreed on shared SessionKey, but only server knows that right now
                var serverM1 = BigIntegers.FromUnsignedByteArray(serverM1Bytes);
                if (serverM1 == m1)
                {
                    // need to send M2 so client knows session key is shared also
                    var m2Bytes = sha1.CalculateDigest(new byte[][]
                    {
                        a.ToByteArray(32),
                        serverM1Bytes,
                        SessionKey.ToByteArray(40),
                    });

                    AuthState = AccountAuthState.Authenticated;
                    var m2 = BigIntegers.FromUnsignedByteArray(m2Bytes);
                    return(Task.FromResult(new SrpResult(true, m2)));
                }
                else
                {
                    Deauthenticate().Wait();
                    return(Task.FromResult(new SrpResult(false, BigInteger.Zero)));
                }
            }
        }
Ejemplo n.º 20
0
        public async Task <BigInteger> Authenticate(AuthSessionRequest authRequest)
        {
            if (String.IsNullOrEmpty(authRequest.Identity))
            {
                throw new ArgumentNullException(nameof(authRequest.Identity));
            }

            if (seed == 0)
            {
                await Send(new AuthSessionResponse()
                {
                    Response = AuthResponseCode.Failed
                });

                throw new AuthenticationFailedException("cannot authenticate with a server seed of 0");
            }

            var account = GrainFactory.GetGrain <IAccount>(authRequest.Identity);

            if (await account.Exists())
            {
                try
                {
                    var sessionKey = await account.GetSessionKey();

                    using (var sha1 = new Digester(SHA1.Create()))
                    {
                        var serverDigest = BigIntegers.FromUnsignedByteArray(
                            sha1.CalculateDigest(new byte[][]
                        {
                            Encoding.UTF8.GetBytes(authRequest.Identity),
                            new byte[4],
                            BitConverter.GetBytes(authRequest.ClientSeed),
                            BitConverter.GetBytes(seed),
                            sessionKey.ToByteArray(40),
                        })
                            );

                        if (serverDigest == authRequest.ClientDigest)
                        {
                            GetLogger().Info($"{authRequest.Identity} successfully authenticated to {ShardName} {nameof(ShardSession)} {this.GetPrimaryKey()}");

                            // we can't just Send the Success response here, since the client expects the packet cipher to be initialized at this point
                            AuthenticatedIdentity = authRequest.Identity;
                            return(sessionKey);
                        }
                        else
                        {
                            await Send(new AuthSessionResponse()
                            {
                                Response = AuthResponseCode.Failed
                            });

                            throw new AuthenticationFailedException($"account {authRequest.Identity} failed authentication proof");
                        }
                    }
                }
                catch (AccountDoesNotExistException)
                {
                    await Send(new AuthSessionResponse()
                    {
                        Response = AuthResponseCode.UnknownAccount
                    });

                    throw new AuthenticationFailedException($"account {authRequest.Identity} does not exist");
                }
                catch (AccountStateException)
                {
                    GetLogger().Warn($"received {nameof(AuthSessionRequest)} with unauthenticated identity {authRequest.Identity}");
                    await Send(new AuthSessionResponse()
                    {
                        Response = AuthResponseCode.Failed
                    });

                    throw new AuthenticationFailedException($"account {authRequest.Identity} is not authenticated");
                }
            }
            else
            {
                await Send(new AuthSessionResponse()
                {
                    Response = AuthResponseCode.UnknownAccount
                });

                throw new AuthenticationFailedException($"account {authRequest.Identity} does not exist");
            }
        }
Ejemplo n.º 21
0
        public override void ExecuteCommand(ShardSession session, ShardRequest request, ClientPacketHeader header)
        {
            int    clientBuild = BitConverter.ToInt32(request.Packet, 6);
            int    identityLength;
            string identity   = Strings.FromNullTerminated(request.Packet, 14, Encoding.UTF8, out identityLength);
            int    clientSeed = BitConverter.ToInt32(request.Packet, 14 + identityLength + 1); // + 1 for null terminator

            byte[] clientDigest = new byte[20];
            Array.Copy(request.Packet, 14 + identityLength + 1 + 4, clientDigest, 0, 20);

            log.DebugFormat("read {0} packet. client build = {1}, identity = {2}, client seed = {3:X}, packet size = {4}", header.Opcode, clientBuild, identity, clientSeed, request.Size);

            int    accountId  = -1;
            string sessionKey = null;

            if (!session.Server.AuthDB.ExecuteQuery("select name, session_key, id from account where name = ? and enabled = true", identity, result =>
            {
                if (result.Read())
                {
                    identity = result.GetString(0);
                    sessionKey = result.GetString(1);
                    accountId = result.GetInt32(2);
                    return(true);
                }
                return(false);
            }))
            {
                // no identity match
                log.DebugFormat("account {0} not found. sending {1} response", identity, AuthResponse.UnknownAccount);
                session.Send(ShardServerOpcode.AuthResponse, (byte)AuthResponse.UnknownAccount);
                return;
            }

            BigInteger sessionKeyInt = BigInteger.Parse(sessionKey, NumberStyles.AllowHexSpecifier);

            // verify client/server identity and session key match
            using (Digester sha1 = new Digester(new SHA1CryptoServiceProvider()))
            {
                byte[] serverDigest = sha1.CalculateDigest(new byte[][]
                {
                    Encoding.UTF8.GetBytes(identity),
                    new byte[4],
                    BitConverter.GetBytes(clientSeed),
                    BitConverter.GetBytes(session.Seed),
                    Arrays.Left(sessionKeyInt.ToByteArray(), 40)
                });

                log.DebugFormat("client digest = {0}", Strings.HexOf(clientDigest));
                log.DebugFormat("server digest = {0}", Strings.HexOf(serverDigest));

                if (Arrays.AreEqual(clientDigest, serverDigest))
                {
                    log.InfoFormat("client {0} successfully authenticated from {1}", identity, session.RemoteEndPoint.Address.ToString());

                    session.AccountID = accountId;
                    session.Status    = SessionStatus.Authenticated;
                    session.InitializeCipher(sessionKeyInt);

                    using (ByteBuffer authPacket = new ByteBuffer())
                    {
                        authPacket.Append((byte)AuthResponse.Success);
                        authPacket.Append(0);
                        authPacket.Append((byte)0);
                        authPacket.Append(0);

                        session.Send(ShardServerOpcode.AuthResponse, authPacket);
                    }

                    using (ByteBuffer addonPacket = BuildAddonPacket(new ArraySegment <byte>(request.Packet, 14 + identityLength + 1 + 4 + 20, request.Size - (14 + identityLength + 1 + 4 + 20))))
                        session.Send(ShardServerOpcode.AddonInfo, addonPacket);
                }
                else
                {
                    // digest mismatch
                    log.DebugFormat("client digest did not match server digest for account {0}. sending {1} response", identity, AuthResponse.Failed);
                    session.Send(ShardServerOpcode.AuthResponse, (byte)AuthResponse.Failed);
                    return;
                }
            }
        }