示例#1
0
 static bool VerifyHash()
 {
     try
     {
         var csp = (RSACryptoServiceProvider)SERVERCERTIFICATE.PublicKey.Key;
         return(csp.VerifyHash(Sha256.ComputeHash(Encoding.UTF8.GetBytes(ENCRYPTIONKEY)), CryptoConfig.MapNameToOID("SHA256"),
                               Convert.FromBase64String(SERVERSIGNATURE)));
     }
     catch (Exception)
     {
         return(false);
     }
 }
示例#2
0
        private static byte[] SignRsaSha256(byte[] digest)
        {
            var oid = CryptoConfig.MapNameToOID("SHA256");

            return(CertificateStore.Instance.PrivateKey.SignHash(digest, oid));
        }
示例#3
0
 private static bool VerifyHash()
 {
     try
     {
         var csp = (RSACryptoServiceProvider)ServerCertificate.PublicKey.Key;
         return(csp.VerifyHash(Sha256.ComputeHash(Encoding.UTF8.GetBytes(Key)), CryptoConfig.MapNameToOID("SHA256"), Convert.FromBase64String(Serversignature)));
     }
     catch (Exception)
     {
         return(false);
     }
 }
        /// <summary>
        ///     Creates a signature value given a signature base and the consumer secret and a known token secret.
        /// </summary>
        /// <param name="signatureMethod">The hashing method</param>
        /// <param name="signatureTreatment">The treatment to use on a signature value</param>
        /// <param name="signatureBase">The signature base</param>
        /// <param name="consumerSecret">The consumer secret</param>
        /// <param name="tokenSecret">The token secret</param>
        /// <returns></returns>
        public static string GetSignature(OAuthSignatureMethod signatureMethod,
                                          OAuthSignatureTreatment signatureTreatment,
                                          string signatureBase, string consumerSecret, string tokenSecret)
        {
            if (tokenSecret.IsNullOrBlank())
            {
                tokenSecret = string.Empty;
            }

            var unencodedConsumerSecret = consumerSecret;

            consumerSecret = Uri.EscapeDataString(consumerSecret);
            tokenSecret    = Uri.EscapeDataString(tokenSecret);

            string signature;

            switch (signatureMethod)
            {
            case OAuthSignatureMethod.HmacSha1:
            {
                var crypto = new HMACSHA1();
                var key    = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

                crypto.Key = encoding.GetBytes(key);
                signature  = signatureBase.HashWith(crypto);
                break;
            }

            case OAuthSignatureMethod.HmacSha256:
            {
                var crypto = new HMACSHA256();
                var key    = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

                crypto.Key = encoding.GetBytes(key);
                signature  = signatureBase.HashWith(crypto);
                break;
            }

            case OAuthSignatureMethod.RsaSha1:
            {
                using (var provider = new RSACryptoServiceProvider {
                        PersistKeyInCsp = false
                    })
                {
                    provider.FromXmlString2(unencodedConsumerSecret);

                    SHA1Managed hasher = new SHA1Managed();
                    byte[]      hash   = hasher.ComputeHash(encoding.GetBytes(signatureBase));

                    signature = Convert.ToBase64String(provider.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")));
                }
                break;
            }

            case OAuthSignatureMethod.PlainText:
            {
                signature = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

                break;
            }

            default:
                throw new NotImplementedException("Only HMAC-SHA1, HMAC-SHA256, and RSA-SHA1 are currently supported.");
            }

            var result = signatureTreatment == OAuthSignatureTreatment.Escaped
                ? UrlEncodeRelaxed(signature)
                : signature;

            return(result);
        }
示例#5
0
        //private bool VerifySignature (ASN1 cs, byte[] calculatedMessageDigest, string hashName)
        private bool VerifySignature(PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha)
        {
            string contentType   = null;
            ASN1   messageDigest = null;

//			string spcStatementType = null;
//			string spcSpOpusInfo = null;

            for (int i = 0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++)
            {
                ASN1   attr = (ASN1)sd.SignerInfo.AuthenticatedAttributes [i];
                string oid  = ASN1Convert.ToOid(attr[0]);
                switch (oid)
                {
                case "1.2.840.113549.1.9.3":
                    // contentType
                    contentType = ASN1Convert.ToOid(attr[1][0]);
                    break;

                case "1.2.840.113549.1.9.4":
                    // messageDigest
                    messageDigest = attr[1][0];
                    break;

                case "1.3.6.1.4.1.311.2.1.11":
                    // spcStatementType (Microsoft code signing)
                    // possible values
                    // - individualCodeSigning (1 3 6 1 4 1 311 2 1 21)
                    // - commercialCodeSigning (1 3 6 1 4 1 311 2 1 22)
//						spcStatementType = ASN1Convert.ToOid (attr[1][0][0]);
                    break;

                case "1.3.6.1.4.1.311.2.1.12":
                    // spcSpOpusInfo (Microsoft code signing)

/*						try {
 *                                                      spcSpOpusInfo = System.Text.Encoding.UTF8.GetString (attr[1][0][0][0].Value);
 *                                              }
 *                                              catch (NullReferenceException) {
 *                                                      spcSpOpusInfo = null;
 *                                              }*/
                    break;

                default:
                    break;
                }
            }
            if (contentType != spcIndirectDataContext)
            {
                return(false);
            }

            // verify message digest
            if (messageDigest == null)
            {
                return(false);
            }
            if (!messageDigest.CompareValue(calculatedMessageDigest))
            {
                return(false);
            }

            // verify signature
            string hashOID = CryptoConfig.MapNameToOID(ha.ToString());

            // change to SET OF (not [0]) as per PKCS #7 1.5
            ASN1 aa = new ASN1(0x31);

            foreach (ASN1 a in sd.SignerInfo.AuthenticatedAttributes)
            {
                aa.Add(a);
            }
            ha.Initialize();
            byte[] p7hash = ha.ComputeHash(aa.GetBytes());

            byte[] signature = sd.SignerInfo.Signature;
            // we need to find the specified certificate
            string issuer = sd.SignerInfo.IssuerName;

            byte[] serial = sd.SignerInfo.SerialNumber;
            foreach (X509Certificate x509 in coll)
            {
                if (CompareIssuerSerial(issuer, serial, x509))
                {
                    // don't verify is key size don't match
                    if (x509.PublicKey.Length > (signature.Length >> 3))
                    {
                        // return the signing certificate even if the signature isn't correct
                        // (required behaviour for 2.0 support)
                        signingCertificate = x509;
                        RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.RSA;
                        if (rsa.VerifyHash(p7hash, hashOID, signature))
                        {
                            signerChain.LoadCertificates(coll);
                            trustedRoot = signerChain.Build(x509);
                            break;
                        }
                    }
                }
            }

            // timestamp signature is optional
            if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0)
            {
                trustedTimestampRoot = true;
            }
            else
            {
                for (int i = 0; i < sd.SignerInfo.UnauthenticatedAttributes.Count; i++)
                {
                    ASN1   attr = (ASN1)sd.SignerInfo.UnauthenticatedAttributes[i];
                    string oid  = ASN1Convert.ToOid(attr[0]);
                    switch (oid)
                    {
                    case PKCS7.Oid.countersignature:
                        // SEQUENCE {
                        //   OBJECT IDENTIFIER
                        //     countersignature (1 2 840 113549 1 9 6)
                        //   SET {
                        PKCS7.SignerInfo cs = new PKCS7.SignerInfo(attr[1]);
                        trustedTimestampRoot = VerifyCounterSignature(cs, signature);
                        break;

                    default:
                        // we don't support other unauthenticated attributes
                        break;
                    }
                }
            }

            return(trustedRoot && trustedTimestampRoot);
        }
示例#6
0
            internal ASN1 GetASN1()
            {
                if ((key == null) || (hashAlgorithm == null))
                {
                    return(null);
                }
                byte[] ver        = { version };
                ASN1   signerInfo = new ASN1(0x30);

                // version Version -> Version ::= INTEGER
                signerInfo.Add(new ASN1(0x02, ver));
                // issuerAndSerialNumber IssuerAndSerialNumber,
                signerInfo.Add(PKCS7.IssuerAndSerialNumber(x509));
                // digestAlgorithm DigestAlgorithmIdentifier,
                string hashOid = CryptoConfig.MapNameToOID(hashAlgorithm);

                signerInfo.Add(AlgorithmIdentifier(hashOid));
                // authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
                ASN1 aa = null;

                if (authenticatedAttributes.Count > 0)
                {
                    aa = signerInfo.Add(new ASN1(0xA0));
                    authenticatedAttributes.Sort(new SortedSet());
                    foreach (ASN1 attr in authenticatedAttributes)
                    {
                        aa.Add(attr);
                    }
                }
                // digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
                if (key is RSA)
                {
                    signerInfo.Add(AlgorithmIdentifier(PKCS7.Oid.rsaEncryption));

                    if (aa != null)
                    {
                        // Calculate the signature here; otherwise it must be set from SignedData
                        RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter(key);
                        r.SetHashAlgorithm(hashAlgorithm);
                        byte[] tbs = aa.GetBytes();
                        tbs [0] = 0x31;                         // not 0xA0 for signature
                        HashAlgorithm ha      = HashAlgorithm.Create(hashAlgorithm);
                        byte[]        tbsHash = ha.ComputeHash(tbs);
                        signature = r.CreateSignature(tbsHash);
                    }
                }
                else if (key is DSA)
                {
                    throw new NotImplementedException("not yet");
                }
                else
                {
                    throw new CryptographicException("Unknown assymetric algorithm");
                }
                // encryptedDigest EncryptedDigest,
                signerInfo.Add(new ASN1(0x04, signature));
                // unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
                if (unauthenticatedAttributes.Count > 0)
                {
                    ASN1 ua = signerInfo.Add(new ASN1(0xA1));
                    unauthenticatedAttributes.Sort(new SortedSet());
                    foreach (ASN1 attr in unauthenticatedAttributes)
                    {
                        ua.Add(attr);
                    }
                }
                return(signerInfo);
            }
示例#7
0
        public bool verifyotp()
        {
            if (skipotp)
            {
                return(true);
            }
            // check if is a fmuv2 and bootloader >= 4 else fail;
            // 9 = fmuv2
            // 5 = px4 1.x
            if (board_type == 9) // &&up.bl_rev >= 4
            {
                try
                {
                    // get the device sn
                    byte[] sn = __get_sn();

                    string line = "";

                    line = "SN: ";
                    for (int s = 0; s < sn.Length; s += 1)
                    {
                        line += sn[s].ToString("X2");
                    }
                    print(line);

                    // 20 bytes - sha1
                    Array.Resize(ref sn, 20);

                    if (ByteArrayCompare(sn, new byte[] { 0x00, 0x23, 0x00, 0x30, 0x35, 0x32, 0x47, 0x18, 0x36, 0x34, 0x30, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }))
                    {
                        print("Libre bootloader");
                        libre = true;
                        print("Forged Key");
                        throw new InvalidKeyException("Invalid Board");
                    }

                    if (ByteArrayCompare(sn, new byte[] { 0x00, 0x38, 0x00, 0x1F, 0x34, 0x32, 0x47, 0x0D, 0x31, 0x32, 0x35, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }))
                    { // pixhawk lite
                        // please sign your board via the proper process.
                        // nuttx has an auth command. use it.
                        print("Forged Key");
                        throw new InvalidKeyException("Invalid Board");
                    }

                    if (ByteArrayCompare(sn, new byte[] { 0x00, 0x38, 0x00, 0x21, 0x31, 0x34, 0x51, 0x17, 0x33, 0x36, 0x38, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }))
                    { // pixfalcon
                        print("Forged Key");
                        throw new InvalidKeyException("Invalid Board");
                    }

                    object obj  = new otp();
                    byte[] test = __read_otp();

                    ByteArrayToStructure(test, ref obj);

                    otp otp = (otp)obj;

                    print("id: " + otp.id_type.ToString("X"));
                    print("vid: " + otp.vid.ToString("X"));
                    print("pid: " + otp.pid.ToString("X"));

                    if (otp.h1 == 'P' &&
                        otp.h2 == 'X' &&
                        otp.h3 == '4' &&
                        otp.h4 == '\0')
                    {
                        // no vendor checks yet
                        byte[] sig = otp.signature;

                        line = "";

                        for (int s = 0; s < 512; s += 1)
                        {
                            line += test[s].ToString("X2");
                            if (s % 16 == 15)
                            {
                                print(line);
                                line = "";
                            }
                        }

                        /*
                         *                                  byte[] PEMbuffer = Convert.FromBase64String(@"");
                         */
                        //   RSACryptoServiceProvider rsa = DecodeRsaPrivateKey(PEMbuffer);

                        //   RSAParameters rsapublic = rsa.ExportParameters(false);

                        foreach (var cert in certs)
                        {
                            byte[] pubpem = Convert.FromBase64String(cert.Value);

                            AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(pubpem);
                            RsaKeyParameters       rsaKeyParameters       = (RsaKeyParameters)asymmetricKeyParameter;
                            RSAParameters          rsaParameters          = new RSAParameters();
                            rsaParameters.Modulus  = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
                            rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
                            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                            rsa.ImportParameters(rsaParameters);

                            bool valid = rsa.VerifyHash(sn, CryptoConfig.MapNameToOID("SHA1"), otp.signature);

                            if (valid)
                            {
                                print("Valid Key");
                                return(true);
                            }
                        }

                        print("Invalid Key");
                        throw new InvalidKeyException("Invalid Board");
                    }
                    else
                    {
                        print("Failed Header Check");
                        throw new FormatException("Failed Header Check");
                    }
                }
                catch
                {
                    print("Failed to read Certificate of Authenticity");
                    throw;
                }
            }

            // not board type 9
            return(true);
        }
示例#8
0
        private void WriteSettings(AssemblyDefinition asmDef)
        {
            var key               = Methods.GetRandomString(32);
            var aes               = new Aes256(key);
            var caCertificate     = new X509Certificate2(Settings.CertificatePath, "", X509KeyStorageFlags.Exportable);
            var serverCertificate = new X509Certificate2(caCertificate.Export(X509ContentType.Cert));

            byte[] signature;
            using (var csp = (RSACryptoServiceProvider)caCertificate.PrivateKey)
            {
                var hash = Sha256.ComputeHash(Encoding.UTF8.GetBytes(key));
                signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256"));
            }

            foreach (var typeDef in asmDef.Modules[0].Types)
            {
                if (typeDef.FullName == "Client.Settings")
                {
                    foreach (var methodDef in typeDef.Methods)
                    {
                        if (methodDef.Name == ".cctor")
                        {
                            for (int i = 0; i < methodDef.Body.Instructions.Count; i++)
                            {
                                if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                                {
                                    string operand = methodDef.Body.Instructions[i].Operand.ToString();

                                    if (operand == "%Ports%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = aes.Encrypt(textPort.Text);
                                    }

                                    if (operand == "%Hosts%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = aes.Encrypt(textIP.Text);
                                    }

                                    if (operand == "%Install%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = checkBox1.Checked.ToString().ToLower();
                                    }

                                    if (operand == "%Folder%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = comboBoxFolder.Text;
                                    }

                                    if (operand == "%File%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = textFilename.Text;
                                    }

                                    if (operand == "%Key%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = Convert.ToBase64String(Encoding.UTF8.GetBytes(key));
                                    }

                                    if (operand == "%MTX%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = txtMutex.Text;
                                    }

                                    if (operand == "%Anti%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = chkAnti.Checked.ToString().ToLower();
                                    }

                                    if (operand == "%Certificate%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(serverCertificate.Export(X509ContentType.Cert)));
                                    }

                                    if (operand == "%Serversignature%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(signature));
                                    }

                                    if (operand == "%BDOS%")
                                    {
                                        methodDef.Body.Instructions[i].Operand = chkBdos.Checked.ToString().ToLower();
                                    }

                                    if (operand == "%Pastebin%")
                                    {
                                        if (chkPastebin.Checked)
                                        {
                                            methodDef.Body.Instructions[i].Operand = aes.Encrypt(txtPastebin.Text);
                                        }
                                        else
                                        {
                                            methodDef.Body.Instructions[i].Operand = aes.Encrypt("null");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
示例#9
0
        private bool VerifySignature(PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha)
        {
            string str = null;
            ASN1   asn = null;
            string str3;
            Dictionary <string, int> dictionary;

            for (int i = 0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++)
            {
                ASN1 asn2 = (ASN1)sd.SignerInfo.AuthenticatedAttributes[i];
                str3 = ASN1Convert.ToOid(asn2[0]);
                if (str3 != null)
                {
                    if (__f__switch_map1 == null)
                    {
                        dictionary = new Dictionary <string, int>(4)
                        {
                            {
                                "1.2.840.113549.1.9.3",
                                0
                            },
                            {
                                "1.2.840.113549.1.9.4",
                                1
                            },
                            {
                                "1.3.6.1.4.1.311.2.1.11",
                                2
                            },
                            {
                                "1.3.6.1.4.1.311.2.1.12",
                                3
                            }
                        };
                        __f__switch_map1 = dictionary;
                    }
                    if (__f__switch_map1.TryGetValue(str3, out int num2))
                    {
                        switch (num2)
                        {
                        case 0:
                            str = ASN1Convert.ToOid(asn2[1][0]);
                            break;

                        case 1:
                            asn = asn2[1][0];
                            break;
                        }
                    }
                }
            }

            if (str != "1.3.6.1.4.1.311.2.1.4")
            {
                return(false);
            }

            if (asn == null)
            {
                return(false);
            }

            if (!asn.CompareValue(calculatedMessageDigest))
            {
                return(false);
            }

            string      str4       = CryptoConfig.MapNameToOID(ha.ToString());
            ASN1        asn3       = new ASN1(0x31);
            IEnumerator enumerator = sd.SignerInfo.AuthenticatedAttributes.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    ASN1 current = (ASN1)enumerator.Current;
                    asn3.Add(current);
                }
            }
            finally
            {
                if (enumerator is IDisposable disposable)
                {
                    disposable.Dispose();
                }
            }

            ha.Initialize();
            byte[] rgbHash    = ha.ComputeHash(asn3.GetBytes());
            byte[] signature  = sd.SignerInfo.Signature;
            string issuerName = sd.SignerInfo.IssuerName;

            byte[] serialNumber = sd.SignerInfo.SerialNumber;
            X509CertificateCollection.X509CertificateEnumerator enumerator2 = this.coll.GetEnumerator();
            try
            {
                while (enumerator2.MoveNext())
                {
                    X509Certificate current = enumerator2.Current;
                    if (this.CompareIssuerSerial(issuerName, serialNumber, current) &&
                        (current.PublicKey.Length > (signature.Length >> 3)))
                    {
                        this.signingCertificate = current;
                        RSACryptoServiceProvider rSA = (RSACryptoServiceProvider)current.RSA;
                        if (rSA.VerifyHash(rgbHash, str4, signature))
                        {
                            this.signerChain.LoadCertificates(this.coll);
                            this.trustedRoot = this.signerChain.Build(current);
                            goto Label_0295;
                        }
                    }
                }
            }
            finally
            {
                if (enumerator2 is IDisposable disposable2)
                {
                    disposable2.Dispose();
                }
            }

Label_0295:
            if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0)
            {
                this.trustedTimestampRoot = true;
            }
            else
            {
                for (int j = 0; j < sd.SignerInfo.UnauthenticatedAttributes.Count; j++)
                {
                    ASN1 asn5 = (ASN1)sd.SignerInfo.UnauthenticatedAttributes[j];
                    str3 = ASN1Convert.ToOid(asn5[0]);
                    if (str3 != null)
                    {
                        if (__f__switch_map2 == null)
                        {
                            dictionary = new Dictionary <string, int>(1)
                            {
                                {
                                    "1.2.840.113549.1.9.6",
                                    0
                                }
                            };
                            __f__switch_map2 = dictionary;
                        }
                        if (__f__switch_map2.TryGetValue(str3, out int num2) && (num2 == 0))
                        {
                            PKCS7.SignerInfo cs = new PKCS7.SignerInfo(asn5[1]);
                            this.trustedTimestampRoot = this.VerifyCounterSignature(cs, signature);
                        }
                    }
                }
            }

            return(this.trustedRoot && this.trustedTimestampRoot);
        }
示例#10
0
        public bool IsValidateLicense()
        {
            // how to get cert public key
            // X509Certificate2 cert = new X509Certificate2(@"c:\inetpub\wwwroot\ro\web\modules\rintagi_signer.cer");
            // string xx = cert.GetRawCertDataString();
            // string zz = "0x" + BitConverter.ToString(cert.Export(X509ContentType.Cert)).Replace("-", ",0x");
            // paste as raw hex value for raw_cert
            X509Certificate2         cert = new X509Certificate2(SignerCert);
            RSACryptoServiceProvider csp  = (RSACryptoServiceProvider)cert.PublicKey.Key;
            SHA1Managed sha1 = new SHA1Managed();

            byte[] hash    = sha1.ComputeHash(UTF8Encoding.UTF8.GetBytes(GetInstallID()));
            string license = Config.RintagiLicense;

            try
            {
                byte[] signature = Convert.FromBase64String(license);

                //how to sign
                //string sig = RO.Common3.Utils.SignData(UTF8Encoding.UTF8.GetBytes(GetInstallID()), @"c:\inetpub\wwwroot\ro\web\modules\rintagi_signer.pfx");
                //bool x = csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String(sig));

                // Verify the signature with the hash
                bool hasPermLicense = csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
                if (!hasPermLicense)
                {
                    throw new Exception("no perm license");
                }
                return(hasPermLicense);
            }
            catch {
                try
                {
                    System.Collections.Generic.Dictionary <string, string> signedLicense = GetLicense(GetInstallID(), "RO", "RO");
                    System.Web.Script.Serialization.JavaScriptSerializer   jss           = new System.Web.Script.Serialization.JavaScriptSerializer();
                    string licenseJSON = signedLicense["License"];
                    string licenseSig  = signedLicense["LicenseSig"];
                    if (csp.VerifyHash(sha1.ComputeHash(UTF8Encoding.UTF8.GetBytes(licenseJSON)), CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String((licenseSig))))
                    {
                        System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, string> > licenseDetail = jss.Deserialize <System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, string> > >(licenseJSON);
                        foreach (var l in licenseDetail)
                        {
                            if (l["InstallID"] == GetInstallID() &&
                                l["AppID"] == "RO" &&
                                DateTime.Parse(l["Expiry"]) >= DateTime.Today.ToUniversalTime())
                            {
                                return(true);
                            }
                        }
                    }
                    return(false);
                }
                catch
                {
                    return(false);
                }
            }
        }
示例#11
0
        private System.Collections.Generic.Dictionary <string, string> GetLicense(string installID, string appID, string moduleName)
        {
            X509Certificate2         cert = new X509Certificate2(SignerCert);
            RSACryptoServiceProvider csp  = (RSACryptoServiceProvider)cert.PublicKey.Key;
            SHA1Managed sha1 = new SHA1Managed();

            System.Collections.Generic.Dictionary <string, string> signedLicense = System.Web.HttpRuntime.Cache["InstallationLicense"] as System.Collections.Generic.Dictionary <string, string>;
            try
            {
                string licenseJSON = signedLicense["License"];
                string licenseSig  = signedLicense["LicenseSig"];
                if (csp.VerifyHash(sha1.ComputeHash(UTF8Encoding.UTF8.GetBytes(licenseJSON)), CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String((licenseSig))))
                {
                    return(signedLicense);
                }
                else
                {
                    throw new Exception("no cached license");
                }
            }
            catch
            {
                string licenseServerUrl = (System.Configuration.ConfigurationManager.AppSettings["LicenseServer"] ?? "https://www.rintagi.com") + "/AdminWs.asmx/GetLicenseDetail";
                var    httpWebRequest   = (HttpWebRequest)WebRequest.Create(licenseServerUrl);
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                httpWebRequest.Accept      = "application/json; charset=utf-8";
                httpWebRequest.Method      = "POST";

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = "{ installID: '" + installID + "',appID:'" + appID + "',moduleName:'" + moduleName + "'}";

                    streamWriter.Write(json);
                }
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var responseText = streamReader.ReadToEnd();
                    System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                    System.Collections.Generic.Dictionary <string, System.Collections.Generic.Dictionary <string, string> > result = jss.Deserialize <System.Collections.Generic.Dictionary <string, System.Collections.Generic.Dictionary <string, string> > >(responseText);
                    string licenseJSON = result["d"]["License"];
                    string licenseSig  = result["d"]["LicenseSig"];

                    if (csp.VerifyHash(sha1.ComputeHash(UTF8Encoding.UTF8.GetBytes(licenseJSON)), CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String((licenseSig))))
                    {
                        System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, string> > licenseDetail = jss.Deserialize <System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, string> > >(licenseJSON);
                        foreach (var l in licenseDetail)
                        {
                            if (l["InstallID"] == installID &&
                                l["AppID"] == appID &&
                                DateTime.Parse(l["Expiry"]) >= DateTime.Today.ToUniversalTime())
                            {
                                try
                                {
                                    DateTime cacheUntil = DateTime.Now.ToUniversalTime().AddDays((DateTime.Parse(l["Expiry"]).Date - DateTime.Now.ToUniversalTime().Date).TotalDays);
                                    System.Web.HttpRuntime.Cache.Add("InstallationLicense", result["d"], null, cacheUntil, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                                }
                                catch { }
                            }
                            return(result["d"]);
                        }
                        return(null);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
        }
示例#12
0
        public System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, string> > GetLicenseDetail(string installID, string appID, string moduleName)
        {
            System.Collections.Generic.Dictionary <string, string> signedLicense = GetLicense(GetInstallID(), "RO", "RO");
            System.Web.Script.Serialization.JavaScriptSerializer   jss           = new System.Web.Script.Serialization.JavaScriptSerializer();
            string                   licenseJSON = signedLicense["License"];
            string                   licenseSig  = signedLicense["LicenseSig"];
            X509Certificate2         cert        = new X509Certificate2(SignerCert);
            RSACryptoServiceProvider csp         = (RSACryptoServiceProvider)cert.PublicKey.Key;
            SHA1Managed              sha1        = new SHA1Managed();

            byte[] hash = sha1.ComputeHash(UTF8Encoding.UTF8.GetBytes(GetInstallID()));
            if (csp.VerifyHash(sha1.ComputeHash(UTF8Encoding.UTF8.GetBytes(licenseJSON)), CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String((licenseSig))))
            {
                System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, string> > licenseDetail = jss.Deserialize <System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, string> > >(licenseJSON);

                return(licenseDetail);
            }
            else
            {
                return(new System.Collections.Generic.List <System.Collections.Generic.Dictionary <string, string> >());
            }
        }
示例#13
0
 public static byte[] Sign(byte[] sha1)
 {
     byte[] b = Secure.RSA.SignHash(sha1, CryptoConfig.MapNameToOID("SHA1"));
     return(b);
 }
示例#14
0
        /// <summary>
        /// Digitaly Sign the OVF
        /// </summary>
        /// <param name="x509">Signing Certificate</param>
        /// <param name="pathToOvf">Absolute path to the OVF files</param>
        /// <param name="ovfFileName">OVF file name (file.ovf)</param>
        public static void Sign(X509Certificate2 Certificate, string PackageFolder, string PackageFileName)
        {
            if (Certificate == null)
            {
                throw new ArgumentException(Messages.CERTIFICATE_IS_INVALID);
            }

            string PackageName = PackageNameFromFileName(PackageFileName);

            string ManifestPath = Path.Combine(PackageFolder, PackageName) + Properties.Settings.Default.manifestFileExtension;

            // Create the manifest if it doesn't exist.
            if (!File.Exists(ManifestPath))
            {
                Manifest(PackageFolder, PackageFileName);
            }

            // Compute the SHA1 hash of the manifest.
            byte[] hash = null;

            using (FileStream stream = new FileStream(ManifestPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (SHA1 sha1 = SHA1.Create())
                {
                    hash = sha1.ComputeHash(stream);
                }

            // Describe the file to sign.
            ManifestFileEntry signed = new ManifestFileEntry();

            signed.Algorithm = Properties.Settings.Default.securityAlgorithm;
            signed.Filename  = Path.GetFileName(ManifestPath);

            // Compute the signature.
            try
            {
                RSACryptoServiceProvider csp = (RSACryptoServiceProvider)Certificate.PrivateKey;

                signed.Digest = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
            }
            catch (Exception exception)
            {
                string message = exception.Message;
            }

            // Create the signature file.
            string SignaturePath = Path.Combine(PackageFolder, PackageName) + Properties.Settings.Default.certificateFileExtension;

            if (File.Exists(SignaturePath))
            {
                File.Delete(SignaturePath);
            }

            using (FileStream stream = new FileStream(SignaturePath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    // Describe the signed file.
                    writer.WriteLine(signed.ToString());

                    // Export the certificate encoded in Base64 using DER.
                    writer.WriteLine("-----BEGIN CERTIFICATE-----");
                    string b64Cert = Convert.ToBase64String(Certificate.Export(X509ContentType.SerializedCert));
                    writer.WriteLine(b64Cert);
                    writer.WriteLine("-----END CERTIFICATE-----");
                    writer.WriteLine("\r\n");
                    writer.Flush();
                }
        }
示例#15
0
 public bool Verify(string signedtext, string originalText)
 {
     byte[] dataSigned   = System.Text.Encoding.UTF8.GetBytes(signedtext);
     byte[] dataUnsigned = System.Text.Encoding.UTF8.GetBytes(originalText);
     return(rsa.VerifyData(dataSigned, CryptoConfig.MapNameToOID("SHA512"), dataUnsigned));
 }
 public void MapNameToOIDNull()
 {
     CryptoConfig.MapNameToOID(null);
 }
 public string GetHashAlgorithm(string HashAlgorithm) => CryptoConfig.MapNameToOID(HashAlgorithm);
 private void MapNameToOID(string name, string oid)
 {
     Assert.AreEqual(oid, CryptoConfig.MapNameToOID(name), "oid(" + name + ")");
 }
示例#19
0
            internal ASN1 GetASN1()
            {
                // SignedData ::= SEQUENCE {
                ASN1 signedData = new ASN1(0x30);

                // version Version -> Version ::= INTEGER
                byte[] ver = { version };
                signedData.Add(new ASN1(0x02, ver));
                // digestAlgorithms DigestAlgorithmIdentifiers -> DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
                ASN1 digestAlgorithms = signedData.Add(new ASN1(0x31));

                if (hashAlgorithm != null)
                {
                    string hashOid = CryptoConfig.MapNameToOID(hashAlgorithm);
                    digestAlgorithms.Add(AlgorithmIdentifier(hashOid));
                }

                // contentInfo ContentInfo,
                ASN1 ci = contentInfo.ASN1;

                signedData.Add(ci);
                if (!signed && (hashAlgorithm != null))
                {
                    if (mda)
                    {
                        // Use authenticated attributes for signature

                        // Automatically add the contentType authenticated attribute
                        ASN1 ctattr = Attribute(Oid.contentType, ci[0]);
                        signerInfo.AuthenticatedAttributes.Add(ctattr);

                        // Automatically add the messageDigest authenticated attribute
                        HashAlgorithm ha      = HashAlgorithm.Create(hashAlgorithm);
                        byte[]        idcHash = ha.ComputeHash(ci[1][0].Value);
                        ASN1          md      = new ASN1(0x30);
                        ASN1          mdattr  = Attribute(Oid.messageDigest, md.Add(new ASN1(0x04, idcHash)));
                        signerInfo.AuthenticatedAttributes.Add(mdattr);
                    }
                    else
                    {
                        // Don't use authenticated attributes for signature -- signature is content
                        RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter(signerInfo.Key);
                        r.SetHashAlgorithm(hashAlgorithm);
                        HashAlgorithm ha  = HashAlgorithm.Create(hashAlgorithm);
                        byte[]        sig = ha.ComputeHash(ci[1][0].Value);
                        signerInfo.Signature = r.CreateSignature(sig);
                    }
                    signed = true;
                }

                // certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL,
                if (certs.Count > 0)
                {
                    ASN1 a0 = signedData.Add(new ASN1(0xA0));
                    foreach (X509Certificate x in certs)
                    {
                        a0.Add(new ASN1(x.RawData));
                    }
                }
                // crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
                if (crls.Count > 0)
                {
                    ASN1 a1 = signedData.Add(new ASN1(0xA1));
                    foreach (byte[] crl in crls)
                    {
                        a1.Add(new ASN1(crl));
                    }
                }
                // signerInfos SignerInfos -> SignerInfos ::= SET OF SignerInfo
                ASN1 signerInfos = signedData.Add(new ASN1(0x31));

                if (signerInfo.Key != null)
                {
                    signerInfos.Add(signerInfo.ASN1);
                }
                return(signedData);
            }
 public static byte[] DigitalnoPotpisi(byte[] sadrzajDatoteke)
 {
     byte[] izracunatSazetak = IzracunajSazetakDatoteke(sadrzajDatoteke);
     return(rsaOperator.SignHash(izracunatSazetak, CryptoConfig.MapNameToOID("SHA256")));
 }
 public override void SetHashAlgorithm(string strName)
 {
     base.SetHashAlgorithm(strName);
     this.m_strOID = CryptoConfig.MapNameToOID(strName);
 }
 public static bool ProvjeraValjanostiDigitalnogPotpisa(byte[] ucitanaDatoteka, byte[] digitalniPotpisDatoteke)
 {
     byte[] sazetakDatoteke = IzracunajSazetakDatoteke(ucitanaDatoteka);
     return(rsaOperator.VerifyHash(sazetakDatoteke, CryptoConfig.MapNameToOID("SHA256"), digitalniPotpisDatoteke));
 }
        private void WriteSettings(ModuleDefMD asmDef)
        {
            try
            {
                var    key               = Methods.GetRandomString(32);
                var    aes               = new Aes256(key);
                var    caCertificate     = new X509Certificate2(Settings.CertificatePath, "", X509KeyStorageFlags.Exportable);
                var    serverCertificate = new X509Certificate2(caCertificate.Export(X509ContentType.Cert));
                byte[] signature;
                using (var csp = (RSACryptoServiceProvider)caCertificate.PrivateKey)
                {
                    var hash = Sha256.ComputeHash(Encoding.UTF8.GetBytes(key));
                    signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256"));
                }

                foreach (TypeDef type in asmDef.Types)
                {
                    if (type.Name == "Settings")
                    {
                        foreach (MethodDef method in type.Methods)
                        {
                            if (method.Body == null)
                            {
                                continue;
                            }
                            for (int i = 0; i < method.Body.Instructions.Count(); i++)
                            {
                                if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                                {
                                    if (method.Body.Instructions[i].Operand.ToString() == "%Ports%")
                                    {
                                        if (chkPastebin.Enabled && chkPastebin.Checked)
                                        {
                                            method.Body.Instructions[i].Operand = aes.Encrypt("null");
                                        }
                                        else
                                        {
                                            List <string> LString = new List <string>();
                                            foreach (string port in listBoxPort.Items)
                                            {
                                                LString.Add(port);
                                            }
                                            method.Body.Instructions[i].Operand = aes.Encrypt(string.Join(",", LString));
                                        }
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%Hosts%")
                                    {
                                        if (chkPastebin.Enabled && chkPastebin.Checked)
                                        {
                                            method.Body.Instructions[i].Operand = aes.Encrypt("null");
                                        }
                                        else
                                        {
                                            List <string> LString = new List <string>();
                                            foreach (string ip in listBoxIP.Items)
                                            {
                                                LString.Add(ip);
                                            }
                                            method.Body.Instructions[i].Operand = aes.Encrypt(string.Join(",", LString));
                                        }
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%Install%")
                                    {
                                        method.Body.Instructions[i].Operand = aes.Encrypt(checkBox1.Checked.ToString().ToLower());
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%Folder%")
                                    {
                                        method.Body.Instructions[i].Operand = comboBoxFolder.Text;
                                    }


                                    if (method.Body.Instructions[i].Operand.ToString() == "%File%")
                                    {
                                        method.Body.Instructions[i].Operand = textFilename.Text;
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%Version%")
                                    {
                                        method.Body.Instructions[i].Operand = aes.Encrypt(Settings.Version.Replace("AsyncRAT ", ""));
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%Key%")
                                    {
                                        method.Body.Instructions[i].Operand = Convert.ToBase64String(Encoding.UTF8.GetBytes(key));
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%MTX%")
                                    {
                                        method.Body.Instructions[i].Operand = aes.Encrypt(txtMutex.Text);
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%Anti%")
                                    {
                                        method.Body.Instructions[i].Operand = aes.Encrypt(chkAnti.Checked.ToString().ToLower());
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%Certificate%")
                                    {
                                        method.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(serverCertificate.Export(X509ContentType.Cert)));
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%Serversignature%")
                                    {
                                        method.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(signature));
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%BDOS%")
                                    {
                                        method.Body.Instructions[i].Operand = aes.Encrypt(chkBdos.Checked.ToString().ToLower());
                                    }

                                    if (method.Body.Instructions[i].Operand.ToString() == "%Pastebin%")
                                    {
                                        if (chkPastebin.Checked)
                                        {
                                            method.Body.Instructions[i].Operand = aes.Encrypt(txtPastebin.Text);
                                        }
                                        else
                                        {
                                            method.Body.Instructions[i].Operand = aes.Encrypt("null");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ArgumentException("WriteSettings: " + ex.Message);
            }
        }
示例#24
0
        public string CreateEncryptedMessage(string principalName)
        {
            string concatenatedSecretMessages = (((long)SecretMessage << 32) | _secretMessages[principalName]).ToString();

            byte[] concatenatedSecretMessageBytes = Encoding.Unicode.GetBytes(concatenatedSecretMessages);
            byte[] signedSecretMessageBytes       = rsa.SignData(concatenatedSecretMessageBytes, CryptoConfig.MapNameToOID("SHA512"));
            string signedSecretMessage            = Convert.ToBase64String(signedSecretMessageBytes);

            string encryptedMessage = Encryption.Encrypt(signedSecretMessage, _symmetricKeys[principalName]);

            Console.WriteLine($"{Name} is creating encrypted message Ek(S({SecretMessage}, {_secretMessages[principalName]}))");
            Console.WriteLine($"{Name}, {SecretMessage}, {_secretMessages[principalName]}: {concatenatedSecretMessages}");
            Console.WriteLine($"{Name}, Signed message: {signedSecretMessage}");
            Console.WriteLine($"{Name}, Encrypted message: {encryptedMessage}");
            Console.WriteLine($"{Name} created encrypted message successfully.");

            return(encryptedMessage);
        }
示例#25
0
 public static void AddOID_MapNameToOID_ReturnsMapped()
 {
     CryptoConfig.AddOID("1.3.14.3.2.28", "SHAFancy");
     Assert.Equal("1.3.14.3.2.28", CryptoConfig.MapNameToOID("SHAFancy"));
 }
示例#26
0
        /// <summary>
        /// Verifies the manifest against it's recorded signature
        /// </summary>
        /// <returns><c>true</c>, if manifest was verifyed, <c>false</c> otherwise.</returns>
        /// <param name="manifest">Manifest.</param>
        protected bool VerifyPackage(AppletPackage package)
        {
            // First check: Hash - Make sure the HASH is ok
            if (Convert.ToBase64String(SHA256.Create().ComputeHash(package.Manifest)) != Convert.ToBase64String(package.Meta.Hash))
            {
                throw new InvalidOperationException($"Package contents of {package.Meta.Id} appear to be corrupt!");
            }

            if (package.Meta.Signature != null)
            {
                this.m_tracer.TraceInfo("Will verify package {0}", package.Meta.Id.ToString());

                // Get the public key - first, is the publisher in the trusted publishers store?
                var x509Store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
                try
                {
                    x509Store.Open(OpenFlags.ReadOnly);
                    var cert = x509Store.Certificates.Find(X509FindType.FindByThumbprint, package.Meta.PublicKeyToken, false);

                    // Not in the central store, perhaps the cert is embedded?
                    if (cert.Count == 0)
                    {
                        // Embedded CER
                        if (package.PublicKey != null)
                        {
                            // Attempt to load
                            cert = new X509Certificate2Collection(new X509Certificate2(package.PublicKey));
                            var config = ApplicationContext.Current.Configuration.GetSection <AppletConfigurationSection>();
                            // Build the certificate chain
                            if (!config.Security.TrustedPublishers.Contains(cert[0].Thumbprint))
                            {
                                var chain = new X509Chain();
                                chain.Build(cert[0]);

                                // Validate the chain elements
                                bool isTrusted = false;
                                foreach (var itm in chain.ChainElements)
                                {
                                    isTrusted |= config.Security.TrustedPublishers.Contains(itm.Certificate.Thumbprint);
                                }

                                if (!isTrusted || chain.ChainStatus.Any(o => o.Status != X509ChainStatusFlags.RevocationStatusUnknown))
                                {
                                    if (!ApplicationContext.Current.Confirm(String.Format(Strings.locale_untrustedPublisherPrompt, package.Meta.Names.First().Value, this.ExtractDNPart(cert[0].Subject, "CN"))))
                                    {
                                        return(false);
                                    }
                                    else
                                    {
                                        ApplicationContext.Current.Configuration.GetSection <AppletConfigurationSection>().Security.TrustedPublishers.Add(cert[0].Thumbprint);
                                        if (ApplicationContext.Current.ConfigurationPersister.IsConfigured)
                                        {
                                            ApplicationContext.Current.ConfigurationPersister.Save(ApplicationContext.Current.Configuration);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            this.m_tracer.TraceError($"Cannot find public key of publisher information for {package.Meta.PublicKeyToken} or the local certificate is invalid");
                            throw new SecurityException(Strings.locale_invalidSignature);
                        }
                    }

                    // Certificate is not yet valid or expired
                    if ((cert[0].NotAfter <DateTime.Now || cert[0].NotBefore> DateTime.Now) &&
                        !ApplicationContext.Current.Confirm(String.Format(Strings.locale_certificateExpired, this.ExtractDNPart(cert[0].Subject, "CN"), cert[0].NotAfter)))
                    {
                        this.m_tracer.TraceError($"Cannot find public key of publisher information for {package.Meta.PublicKeyToken} or the local certificate is invalid");
                        throw new SecurityException(Strings.locale_invalidSignature);
                    }

                    RSACryptoServiceProvider rsa = cert[0].PublicKey.Key as RSACryptoServiceProvider;

                    var retVal = rsa.VerifyData(package.Manifest, CryptoConfig.MapNameToOID("SHA1"), package.Meta.Signature);
                    if (!retVal)
                    {
                        throw new SecurityException(Strings.locale_invalidSignature);
                    }
                    return(retVal);
                }
                finally
                {
                    x509Store.Close();
                }
            }
            else if (ApplicationContext.Current.Configuration.GetSection <AppletConfigurationSection>().Security.AllowUnsignedApplets)
            {
                return(ApplicationContext.Current.Confirm(String.Format(Strings.locale_unsignedAppletPrompt, package.Meta.Names.First().Value)));
            }
            else
            {
                this.m_tracer.TraceError("Package {0} v.{1} (publisher: {2}) is not signed and cannot be installed", package.Meta.Id, package.Meta.Version, package.Meta.Author);
                throw new SecurityException(String.Format(Strings.locale_unsignedAppletsNotAllowed, package.Meta.Id));
            }
        }
示例#27
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (!request.Headers.Contains("Signature") || !request.Headers.Contains("SignatureCertChainUrl"))
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            var signatureCertChainUrl = request.Headers.GetValues("SignatureCertChainUrl").First().Replace("/../", "/");

            if (string.IsNullOrWhiteSpace(signatureCertChainUrl))
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            var certUrl = new Uri(signatureCertChainUrl);

            if (!((certUrl.Port == 443 || certUrl.IsDefaultPort) &&
                  certUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) &&
                  certUrl.Host.Equals("s3.amazonaws.com", StringComparison.OrdinalIgnoreCase) &&
                  certUrl.AbsolutePath.StartsWith("/echo.api/")))
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            using (var web = new WebClient())
            {
                var certificate = web.DownloadData(certUrl);
                var cert        = new X509Certificate2(certificate);

                var effectiveDate = DateTime.MinValue;
                var expiryDate    = DateTime.MinValue;

                if (!((DateTime.TryParse(cert.GetExpirationDateString(), out expiryDate) &&
                       expiryDate > DateTime.UtcNow) &&
                      (DateTime.TryParse(cert.GetEffectiveDateString(), out effectiveDate) &&
                       effectiveDate < DateTime.UtcNow)))
                {
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
                }

                if (!cert.Subject.Contains("CN=echo-api.amazon.com") || !cert.Issuer.Contains("CN=Symantec Class 3 Secure Server CA"))
                {
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
                }

                var signatureString = request.Headers.GetValues("Signature").First();

                byte[] signature = Convert.FromBase64String(signatureString);

                using (var sha1 = new SHA1Managed())
                {
                    var body = await request.Content.ReadAsStringAsync();

                    var data = sha1.ComputeHash(Encoding.UTF8.GetBytes(body));

                    var rsa = (RSACryptoServiceProvider)cert.PublicKey.Key;

                    if (rsa == null || !rsa.VerifyHash(data, CryptoConfig.MapNameToOID("SHA1"), signature))
                    {
                        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
                    }
                }
            }

            return(await base.SendAsync(request, cancellationToken));
        }
示例#28
0
        private bool VerifySignature(PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha)
        {
            string a   = null;
            ASN1   asn = null;
            int    i   = 0;

            while (i < sd.SignerInfo.AuthenticatedAttributes.Count)
            {
                ASN1   asn2  = (ASN1)sd.SignerInfo.AuthenticatedAttributes[i];
                string text  = ASN1Convert.ToOid(asn2[0]);
                string text2 = text;
                switch (text2)
                {
                case "1.2.840.113549.1.9.3":
                    a = ASN1Convert.ToOid(asn2[1][0]);
                    break;

                case "1.2.840.113549.1.9.4":
                    asn = asn2[1][0];
                    break;
                }
IL_F1:
                i++;
                continue;
                goto IL_F1;
            }
            if (a != "1.3.6.1.4.1.311.2.1.4")
            {
                return(false);
            }
            if (asn == null)
            {
                return(false);
            }
            if (!asn.CompareValue(calculatedMessageDigest))
            {
                return(false);
            }
            string str  = CryptoConfig.MapNameToOID(ha.ToString());
            ASN1   asn3 = new ASN1(49);

            foreach (object obj in sd.SignerInfo.AuthenticatedAttributes)
            {
                ASN1 asn4 = (ASN1)obj;
                asn3.Add(asn4);
            }
            ha.Initialize();
            byte[] rgbHash    = ha.ComputeHash(asn3.GetBytes());
            byte[] signature  = sd.SignerInfo.Signature;
            string issuerName = sd.SignerInfo.IssuerName;

            byte[] serialNumber = sd.SignerInfo.SerialNumber;
            foreach (X509Certificate x509Certificate in this.coll)
            {
                if (this.CompareIssuerSerial(issuerName, serialNumber, x509Certificate) && x509Certificate.PublicKey.Length > signature.Length >> 3)
                {
                    this.signingCertificate = x509Certificate;
                    RSACryptoServiceProvider rsacryptoServiceProvider = (RSACryptoServiceProvider)x509Certificate.RSA;
                    if (rsacryptoServiceProvider.VerifyHash(rgbHash, str, signature))
                    {
                        this.signerChain.LoadCertificates(this.coll);
                        this.trustedRoot = this.signerChain.Build(x509Certificate);
                        break;
                    }
                }
            }
            if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0)
            {
                this.trustedTimestampRoot = true;
            }
            else
            {
                int j = 0;
                while (j < sd.SignerInfo.UnauthenticatedAttributes.Count)
                {
                    ASN1   asn5  = (ASN1)sd.SignerInfo.UnauthenticatedAttributes[j];
                    string text3 = ASN1Convert.ToOid(asn5[0]);
                    string text2 = text3;
                    if (text2 != null)
                    {
                        if (AuthenticodeDeformatter.< > f__switch$map2 == null)
                        {
                            AuthenticodeDeformatter.< > f__switch$map2 = new Dictionary <string, int>(1)
                            {
                                {
                                    "1.2.840.113549.1.9.6",
                                    0
                                }
                            };
                        }
                        int num;
                        if (AuthenticodeDeformatter.< > f__switch$map2.TryGetValue(text2, out num))
                        {
                            if (num == 0)
                            {
                                PKCS7.SignerInfo cs = new PKCS7.SignerInfo(asn5[1]);
                                this.trustedTimestampRoot = this.VerifyCounterSignature(cs, signature);
                            }
                        }
                    }
IL_35D:
                    j++;
                    continue;
                    goto IL_35D;
                }
            }
            return(this.trustedRoot && this.trustedTimestampRoot);
        }
        /// <summary>
        /// Perform the comparison of the message data with the signature
        /// </summary>
        /// <param name="data"></param>
        /// <param name="signature"></param>
        /// <returns>true if successful</returns>
        private bool VerifyMsgMatchesSignatureWithPublicCert(byte[] data, byte[] signature)
        {
            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)GetPublicKey();

            return(csp.VerifyData(data, CryptoConfig.MapNameToOID("SHA1"), signature));
        }
示例#30
0
        public byte[] HandleRequest(byte[] requestBytes)
        {
            object request = TrIncRequest.ParseRequest(requestBytes);

            if (request is Common.GetQuoteRequest)
            {
                GetQuoteResponse getQuoteResponse = new GetQuoteResponse(0, key_pair);
                return(getQuoteResponse.Encode());
            }
            if (request is CreateCounterRequest)
            {
                CreateCounterRequest     r          = (CreateCounterRequest)request;
                RSACryptoServiceProvider public_key = CommonRoutines.DecodePublicKey(r.public_key);
                if (public_key == null)
                {
                    return(TrIncSrvResponse.EncodeCreateCounterResponse(3, 0));
                }
                TrIncCounter counter = new TrIncCounter(public_key);
                counters.Add(counter);
                UInt32 counter_index = (UInt32)(counters.Count - 1);
                return(TrIncSrvResponse.EncodeCreateCounterResponse(0, counter_index));
            }
            if (request is AdvanceCounterRequest)
            {
                AdvanceCounterRequest r = (AdvanceCounterRequest)request;
                if (r.counter_index < 0 || r.counter_index >= counters.Count)
                {
                    Console.Error.WriteLine("Received request for invalid counter index {0}", r.counter_index);
                    return(TrIncSrvResponse.EncodeAdvanceCounterResponse(1, new byte[0], new byte[0]));
                }

                TrIncCounter counter = counters[(int)r.counter_index];
                byte[]       req     = CommonRoutines.CombineByteArrays(r.new_counter_value, r.message);
                if (!counter.PublicKey.VerifyData(req, CryptoConfig.MapNameToOID("SHA256"), r.request_attestation))
                {
                    Console.Error.WriteLine("Received invalid request attestation");
                    return(TrIncSrvResponse.EncodeAdvanceCounterResponse(5, new byte[0], new byte[0]));
                }

                int        offset            = 0;
                BigInteger new_counter_value = CommonRoutines.DecodeMPBigInteger(r.new_counter_value, ref offset);
                if (new_counter_value < 0 || offset != r.new_counter_value.Length)
                {
                    Console.Error.WriteLine("Received invalid new counter value encoding");
                    return(TrIncSrvResponse.EncodeAdvanceCounterResponse(6, new byte[0], new byte[0]));
                }

                if (new_counter_value < counter.Value)
                {
                    Console.Error.WriteLine("New counter value requested {0} is smaller than current counter value {1}", new_counter_value, counter.Value);
                    return(TrIncSrvResponse.EncodeAdvanceCounterResponse(7, new byte[0], new byte[0]));
                }

                BigInteger old_counter_value = counter.Value;
                counter.Value = new_counter_value;

                byte[] header = new byte[1];
                header[0] = 34;
                byte[] counter_index_encoding     = CommonRoutines.EncodeBEWord(r.counter_index);
                byte[] old_counter_value_encoding = CommonRoutines.EncodeMPBigInteger(old_counter_value);
                byte[] new_counter_value_encoding = CommonRoutines.EncodeMPBigInteger(new_counter_value);
                byte[] trinc_statement            = CommonRoutines.CombineByteArrays(header, counter_index_encoding, old_counter_value_encoding, new_counter_value_encoding, r.message);
                byte[] trinc_attestation          = key_pair.SignData(trinc_statement, CryptoConfig.MapNameToOID("SHA256"));
                return(TrIncSrvResponse.EncodeAdvanceCounterResponse(0, trinc_statement, trinc_attestation));
            }
            return(InvalidResponse.Encode());
        }