Ejemplo n.º 1
0
 /**
  * Constructs a new PRNG and seeds it with a byte array.
  * @param seed a seed
  * @param hashAlg the hash algorithm to use
  * @throws NtruException if the JRE doesn't implement the specified hash algorithm
  */
 public Prng(byte[] seed, string hashAlg)
 {
     counter = 0;
     this.seed = seed;
     try
     {
         this.hashAlg = new SHA256();// MessageDigest.getInstance(hashAlg);
     }
     catch (Exception e)
     {
         throw new NtruException(e.Message);
     }
 }
Ejemplo n.º 2
0
        private void Potvrdit_Click(object sender, EventArgs e)
        {
            string h = "";

            byte[] uJmeno = Encoding.GetEncoding("UTF-8").GetBytes(ujmeno.Text);
            SHA256 sha256 = SHA256.Create();

            byte[] HesloHash;
            HesloHash = sha256.ComputeHash(Encoding.UTF8.GetBytes(hesloA.Text));
            byte[] ujmenoHash = sha256.ComputeHash(uJmeno);
            string un         = Convert.ToString(ByteArrayToString(ujmenoHash));

            byte[] adminHash;
            adminHash = sha256.ComputeHash(Encoding.UTF8.GetBytes("admin"));
            string unA = Convert.ToString(ByteArrayToString(adminHash));

            string cesta      = Environment.CurrentDirectory + @"\Users\" + un + ".txt";
            string cestaAdmin = Environment.CurrentDirectory + @"\Users\" + unA + ".txt";

            if (File.Exists(cesta) == false)
            {
                label5.Visible = true;
            }
            else
            {
                using (StreamReader sr = new StreamReader(cestaAdmin))
                {
                    Regex  rg = new Regex(@"(?<=Heslo:)\S+");
                    string radek;
                    while ((radek = sr.ReadLine()) != null)
                    {
                        if (rg.IsMatch(radek))
                        {
                            h = Convert.ToString(rg.Match(radek));
                        }
                    }
                }
                if (BitConverter.ToString(HesloHash).Replace("-", "").ToLower() == h)
                {
                    using (StreamReader sr = new StreamReader(cesta))
                    {
                        string radek;
                        while ((radek = sr.ReadLine()) != null)
                        {
                            if (radek == "zmenaHesla")
                            {
                                label6.Visible = true;
                                zpet.Visible   = true;
                            }
                        }
                    }
                    if (label6.Visible == false)
                    {
                        using (StreamWriter sw = new StreamWriter(cesta, true))
                        {
                            sw.WriteLine("zmenaHesla");
                        }
                        this.Hide();
                        a.Show();
                    }
                }
            }
        }
Ejemplo n.º 3
0
 // encoding function
 public static string Hash(string value)
 {
     return(Convert.ToBase64String(SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(value))));
 }
Ejemplo n.º 4
0
        internal void InitRsa(RSAParameters rsaParam, RSAPKCS1SignatureFormatter rsaFormatter, SHA256 sha256)
        {
            JsonObject publicKey = new JsonObject();

            publicKey["rsa_n"] = BitConverter.ToString(rsaParam.Modulus).Replace("-", string.Empty);
            publicKey["rsa_e"] = rsaParam.Exponent[0].ToString();
            handshake.InitRsa(publicKey);

            _Sha256 = sha256;
            //Create an RSASignatureFormatter object and pass it the
            //RSACryptoServiceProvider to transfer the key information.
            _RSAFormatter = rsaFormatter;
            IsCrypto      = true;
        }
Ejemplo n.º 5
0
    /// <summary>
    /// Serialize this message to MAVLink v2 byte message.
    /// </summary>
    public byte[] toBytes(byte [] signingKey = null)
    {
        MAVLink.message_info message_info = MAVLink.MAVLINK_MESSAGE_INFOS.FirstOrDefault(info => info.msgid == message_id);
        byte[] payload_bytes = message_info.serializer(payload);

        // Truncate zero bytes at the end of the payload
        var length = payload_bytes.Length;

        while (length > 1 && payload_bytes[length - 1] == 0)
        {
            length--;
        }

        Span <byte> data = new Span <byte>(payload_bytes, 0, length);

        int extra = 0;

        if (signingKey != null)
        {
            extra = MAVLink.MAVLINK_SIGNATURE_BLOCK_LEN;
        }

        byte[] packet = new byte[data.Length + MAVLink.MAVLINK_NUM_NON_PAYLOAD_BYTES + extra];

        packet[0] = MAVLink.MAVLINK_STX;
        packet[1] = (byte)data.Length;
        packet[2] = 0;  //incompat  signing
        if (signingKey != null)
        {
            packet[2] |= MAVLink.MAVLINK_IFLAG_SIGNED;
        }

        packet[3] = 0;  //compat
        packet[4] = sequence;
        packet[5] = system_id;
        packet[6] = component_id;
        packet[7] = (byte)message_id;
        packet[8] = (byte)(message_id >> 8);
        packet[9] = (byte)(message_id >> 16);

        int i = MAVLink.MAVLINK_NUM_HEADER_BYTES;

        foreach (byte b in data)
        {
            packet[i] = b;
            i++;
        }

        ushort checksum = MAVLink.MavlinkCRC.crc_calculate(packet, data.Length + MAVLink.MAVLINK_NUM_HEADER_BYTES);

        checksum = MAVLink.MavlinkCRC.crc_accumulate(message_info.crc, checksum);

        byte ck_a = (byte)(checksum & 0xFF); ///< High byte
        byte ck_b = (byte)(checksum >> 8);   ///< Low byte

        packet[i] = ck_a;
        i        += 1;
        packet[i] = ck_b;
        i        += 1;

        if (signature != null)
        {
            //https://docs.google.com/document/d/1ETle6qQRcaNWAmpG2wz0oOpFKSF_bcTmYMQvtTGI8ns/edit

            /*
             * 8 bits of link ID
             * 48 bits of timestamp
             * 48 bits of signature
             */

            // signature = sha256_48(secret_key + header + payload + CRC + link-ID + timestamp)
            var timebytes = BitConverter.GetBytes(signature_timestamp);

            var sig = new byte[7];               // 13 includes the outgoing hash
            sig[0] = signature_link_id;
            Array.Copy(timebytes, 0, sig, 1, 6); // timestamp


            using (SHA256 signit = SHA256.Create())
            {
                MemoryStream ms = new MemoryStream();
                ms.Write(signingKey, 0, signingKey.Length);
                ms.Write(packet, 0, i);
                ms.Write(sig, 0, sig.Length);

                var ctx = signit.ComputeHash(ms.ToArray());
                // trim to 48
                Array.Resize(ref ctx, 6);

                foreach (byte b in sig)
                {
                    packet[i] = b;
                    i++;
                }

                foreach (byte b in ctx)
                {
                    packet[i] = b;
                    i++;
                }
            }
        }

        return(packet);
    }
Ejemplo n.º 6
0
 public static byte[] ToSHA256HashBytes(byte[] keyBytes)
 {
     return(SHA256.Create().ComputeHash(keyBytes));
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Hash a string value using SHA-256 hashing algorithm.
 /// </summary>
 /// <param name="digest">Provides the algorithm for SHA-256.</param>
 /// <param name="value">The string value (e.g. an email address) to hash.</param>
 /// <returns>The hashed value.</returns>
 private static string ToSha256String(SHA256 digest, string value)
 {
     byte[] digestBytes = digest.ComputeHash(Encoding.UTF8.GetBytes(value));
     // Convert the byte array into an unhyphenated hexadecimal string.
     return(BitConverter.ToString(digestBytes).Replace("-", string.Empty));
 }
Ejemplo n.º 8
0
        private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            var encrypt = SHA256.Create();

            return(Encoding.ASCII.GetString(encrypt.ComputeHash(Encoding.ASCII.GetBytes(password + Convert.ToBase64String(passwordSalt)))) == Encoding.ASCII.GetString(passwordHash));
        }
Ejemplo n.º 9
0
 protected override int HashData(Stream source, Span <byte> destination) =>
 SHA256.HashData(source, destination);
Ejemplo n.º 10
0
 protected override int HashData(ReadOnlySpan <byte> source, Span <byte> destination) =>
 SHA256.HashData(source, destination);
Ejemplo n.º 11
0
 protected override byte[] HashData(ReadOnlySpan <byte> source) => SHA256.HashData(source);
Ejemplo n.º 12
0
 protected override bool TryHashData(ReadOnlySpan <byte> source, Span <byte> destination, out int bytesWritten)
 {
     return(SHA256.TryHashData(source, destination, out bytesWritten));
 }
Ejemplo n.º 13
0
 protected override HashAlgorithm Create()
 {
     return(SHA256.Create());
 }
Ejemplo n.º 14
0
        public static bool TrySignAdaptor(this ECPrivKey key, ReadOnlySpan <byte> msg32, ECPubKey adaptor, out SecpECDSAAdaptorSignature?adaptorSignature, out SecpECDSAAdaptorProof?proof)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (adaptor == null)
            {
                throw new ArgumentNullException(nameof(adaptor));
            }
            if (msg32.Length < 32)
            {
                throw new ArgumentException(paramName: nameof(msg32), message: "msg32 should be at least 32 bytes");
            }
            var    adaptor_ge = adaptor.Q;
            var    seckey32   = key.sec;
            SHA256 sha        = new SHA256();

            sha.Write(msg32.Slice(0, 32));
            Span <byte> buf33 = stackalloc byte[33];

            Internals.secp256k1_dleq_serialize_point(buf33, adaptor_ge);
            sha.Write(buf33);
            sha.GetHash(buf33);
            Span <byte> nonce32 = stackalloc byte[32];

            nonce_function_dleq(buf33, key.sec, "ECDSAAdaptorNon", nonce32);
            var k = new Scalar(nonce32);

            if (k.IsZero)
            {
                adaptorSignature = default;
                proof            = default;
                return(false);
            }
            var rpj = key.ctx.EcMultGenContext.MultGen(k);
            /* 2. R = k*Y; */
            var rj = adaptor_ge.MultConst(k, 256);

            /* 4. [sic] proof = DLEQ_prove((G,R'),(Y, R)) */
            if (!key.ctx.EcMultGenContext.secp256k1_dleq_proof("ECDSAAdaptorSig", k, adaptor_ge, out var dleq_proof_s, out var dleq_proof_e))
            {
                adaptorSignature = default;
                proof            = default;
                return(false);
            }

            /* 5. s' = k⁻¹(H(m) + x_coord(R)x) */
            var r   = rj.ToGroupElement();
            var msg = new Scalar(msg32);

            if (!secp256k1_ecdsa_adaptor_sign_helper(msg, k, r, key.sec, out var sp))
            {
                k = default;
                adaptorSignature = default;
                proof            = default;
                return(false);
            }

            /* 6. return (R, R', s', proof) */
            var rp = rpj.ToGroupElement();

            proof            = new SecpECDSAAdaptorProof(rp, dleq_proof_s, dleq_proof_e);
            adaptorSignature = new SecpECDSAAdaptorSignature(r, sp);
            k = default;
            return(true);
        }
Ejemplo n.º 15
0
 /**
  * Resets the engine for signing a message.
  * @param kp
  * @throws NtruException if the JRE doesn't implement the specified hash algorithm
  */
 public void initSign(SignatureKeyPair kp)
 {
     this.signingKeyPair = kp;
     try
     {
         hashAlg = new SHA256();// MessageDigest.getInstance(param.hashAlg);
     }
     catch (Exception e)
     {
         throw new NtruException(e.Message);
     }
     hashAlg.Reset();
 }
Ejemplo n.º 16
0
 /**
  * Resets the engine for verifying a signature.
  * @param pub the public key to use in the {@link #verify(byte[])} step
  * @throws NtruException if the JRE doesn't implement the specified hash algorithm
  */
 public void initVerify(SignaturePublicKey pub)
 {
     verificationKey = pub;
     try
     {
         hashAlg = new SHA256();
     }
     catch (Exception e)
     {
         throw new NtruException(e.Message);
     }
     hashAlg.Reset();
 }
Ejemplo n.º 17
0
 protected override byte[] HashData(Stream source) => SHA256.HashData(source);
 public IHasherWrapper Create()
 {
     return(new IHasherWrapper.Sha256HasherWrapperWrapper(SHA256.Create()));
 }
Ejemplo n.º 19
0
 protected override ValueTask <int> HashDataAsync(Stream source, Memory <byte> destination, CancellationToken cancellationToken) =>
 SHA256.HashDataAsync(source, destination, cancellationToken);
Ejemplo n.º 20
0
        public int Login(string username, string password, byte[] hwid)
        {
            try
            {
                if (Array.Exists(File.ReadAllLines("BannedHWIDs.txt"), x => x == Encoding.UTF8.GetString(hwid)))
                {
                    return(clsResults.BANNED);
                }

                if (isLoggedIn)
                {
                    if (isExpired)
                    {
                        return(clsResults.SUCCESS_EXPIRED);
                    }
                    else
                    {
                        return(clsResults.SUCCESS);
                    }
                }

                if (!File.Exists(string.Format("Clients\\{0}.xml", username)))
                {
                    return(clsResults.INVALID_USERNAME);
                }

                clsClient client = frmMain.ReadXML <clsClient>(string.Format("Clients\\{0}.xml", username));

                if (!SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).SequenceEqual(client.bPassword))
                {
                    return(clsResults.INVALID_PASSWORD);
                }

                if (!hwid.SequenceEqual(client.bHWID))
                {
                    return(clsResults.HWID_MISMATCH);
                }

                isLoggedIn = true;
                thisClient = client;

                foreach (clsUsedKey uKey in client.lHistory)
                {
                    if (DateTime.Now.CompareTo(uKey.dtActivation.Add(new TimeSpan(uKey.iValidFor, 0, 0, 0))) <= 0)
                    {
                        isExpired = false;
                        thisKey   = uKey;
                        UpdateInfo();
                        return(clsResults.SUCCESS);
                    }
                }

                isExpired = true;
                UpdateInfo();
                return(clsResults.SUCCESS_EXPIRED);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
                return(clsResults.UNKNOWN_ERROR);
            }
        }
Ejemplo n.º 21
0
 protected override ValueTask <byte[]> HashDataAsync(Stream source, CancellationToken cancellationToken) =>
 SHA256.HashDataAsync(source, cancellationToken);
Ejemplo n.º 22
0
 /// <summary>
 /// Returns the SHA256 hash of the given byte array.
 /// </summary>
 /// <param name="data">The byte array to get the hash of</param>
 public static string CalculateSHA256Hash(byte[] data)
 {
     using (SHA256 sha256 = SHA256.Create())
         return(Convert.ToBase64String(sha256.ComputeHash(data)));
 }
 public static byte[] buildKey(string key)
 {
     byte[] res = Encoding.Unicode.GetBytes(key);
     return(SHA256.Create().ComputeHash(res));
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Hashes a string
        /// </summary>
        /// <param name="inputString"></param>
        /// <returns></returns>
        public static byte[] GetHash(string inputString)
        {
            HashAlgorithm algorithm = SHA256.Create();

            return(algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
        }
Ejemplo n.º 25
0
 public static byte[] SHA256H(byte[] block)
 {
     using SHA256 hash = SHA256.Create();
     return(hash.ComputeHash(block));
 }
Ejemplo n.º 26
0
 public static byte[] ComputeHash(string name, string reduceKey)
 {
     using (var sha256 = SHA256.Create())
         return(sha256.ComputeHash(Encoding.UTF8.GetBytes(name + "/" + reduceKey)));
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Return the SHA 256 hash of a string
        /// </summary>
        /// <returns>The SHA 256.</returns>
        /// <param name="text">Text.</param>
        public static string ToSHA256(this string text)
        {
            SHA256 sha = System.Security.Cryptography.SHA256.Create();

            return(HashToHexString(text, sha));
        }
Ejemplo n.º 28
0
 private Md5SingletonHelper()
 {
     this.md5    = MD5.Create();
     this.sha1   = SHA1.Create();
     this.sha256 = SHA256.Create();
 }
Ejemplo n.º 29
0
        private static ActionResult _installStateTool(Session session, out string stateToolPath)
        {
            Error.ResetErrorDetails(session);

            var paths = GetPaths();
            string stateURL = "https://state-tool.s3.amazonaws.com/update/state/release/";
            string jsonURL = stateURL + paths.JsonDescription;
            string timeStamp = DateTime.Now.ToFileTime().ToString();
            string tempDir = Path.Combine(Path.GetTempPath(), timeStamp);
            string stateToolInstallDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ActiveState", "bin");
            stateToolPath = Path.Combine(stateToolInstallDir, "state.exe");

            if (File.Exists(stateToolPath))
            {
                session.Log("Using existing State Tool executable at install path");
                Status.ProgressBar.Increment(session, 200);
                return ActionResult.Success;
            }

            session.Log(string.Format("Using temp path: {0}", tempDir));
            try
            {
                Directory.CreateDirectory(tempDir);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not create temp directory at: {0}, encountered exception: {1}", tempDir, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            string versionInfoString = "unset";
            session.Log(string.Format("Downloading JSON from URL: {0}", jsonURL));
            try
            {
                RetryHelper.RetryOnException(session, 3, TimeSpan.FromSeconds(2), () =>
                {
                    var client = new WebClient();
                    versionInfoString = client.DownloadString(jsonURL);
                });
            }
            catch (WebException e)
            {
                string msg = string.Format("Encountered exception downloading state tool json info file: {0}", e.ToString());
                session.Log(msg);
                new NetworkError().SetDetails(session, e.Message);
                return ActionResult.Failure;
            }

            VersionInfo info;
            try
            {
                info = JsonConvert.DeserializeObject<VersionInfo>(versionInfoString);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not deserialize version info. Version info string {0}, exception {1}", versionInfoString, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            string zipPath = Path.Combine(tempDir, paths.ZipFile);
            string zipURL = stateURL + info.version + "/" + paths.ZipFile;
            session.Log(string.Format("Downloading zip file from URL: {0}", zipURL));
            Status.ProgressBar.StatusMessage(session, "Downloading State Tool...");

            var tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;

            Task incrementTask = Task.Run(() =>
            {
                incrementProgressBar(session, 50, token);
            });

            Task<ActionResult> downloadTask = Task.Run(() =>
            {
                try
                {
                    RetryHelper.RetryOnException(session, 3, TimeSpan.FromSeconds(2), () =>
                    {
                        var client = new WebClient();
                        client.DownloadFile(zipURL, zipPath);
                    });
                }
                catch (WebException e)
                {
                    string msg = string.Format("Encountered exception downloading state tool zip file. URL to zip file: {0}, path to save zip file to: {1}, exception: {2}", zipURL, zipPath, e.ToString());
                    session.Log(msg);
                    new NetworkError().SetDetails(session, e.Message);
                    return ActionResult.Failure;
                }

                return ActionResult.Success;
            });

            ActionResult result = downloadTask.Result;
            tokenSource.Cancel();
            incrementTask.Wait();
            if (result.Equals(ActionResult.Failure))
            {
                return result;
            }


            SHA256 sha = SHA256.Create();
            FileStream fInfo = File.OpenRead(zipPath);
            string zipHash = BitConverter.ToString(sha.ComputeHash(fInfo)).Replace("-", string.Empty).ToLower();
            if (zipHash != info.sha256v2)
            {
                string msg = string.Format("SHA256 checksum did not match, expected: {0} actual: {1}", info.sha256v2, zipHash.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            Status.ProgressBar.StatusMessage(session, "Extracting State Tool executable...");
            Status.ProgressBar.Increment(session, 50);
            try
            {
                ZipFile.ExtractToDirectory(zipPath, tempDir);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not extract State Tool, encountered exception. Path to zip file: {0}, path to temp directory: {1}, exception {2})", zipPath, tempDir, e);
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            try
            {
                Directory.CreateDirectory(stateToolInstallDir);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not create State Tool install directory at: {0}, encountered exception: {1}", stateToolInstallDir, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            try
            {
                File.Move(Path.Combine(tempDir, paths.ExeFile), stateToolPath);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not move State Tool executable to: {0}, encountered exception: {1}", stateToolPath, e);
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }


            string configDirCmd = " export" + " config" + " --filter=dir";
            string output;
            ActionResult runResult = ActiveState.Command.Run(session, stateToolPath, configDirCmd, out output);
            session.Log("Writing install file...");
            // We do not fail the installation if writing the installsource.txt file fails
            if (runResult.Equals(ActionResult.Failure))
            {
                string msg = string.Format("Could not get config directory from State Tool");
                session.Log(msg);
                RollbarReport.Error(msg, session);
            }
            else
            {
                string contents = "msi-ui";
                if (session.CustomActionData["UI_LEVEL"] == "2")
                {
                    contents = "msi-silent";
                }
                try
                {
                    string installFilePath = Path.Combine(output.Trim(), "installsource.txt");
                    File.WriteAllText(installFilePath, contents, Encoding.ASCII);
                }
                catch (Exception e)
                {
                    string msg = string.Format("Could not write install file at path: {0}, encountered exception: {1}", output, e.ToString());
                    session.Log(msg);
                    RollbarReport.Error(msg, session);
                }
            }

            session.Log("Updating PATH environment variable");
            Status.ProgressBar.Increment(session, 50);
            string oldPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
            if (oldPath.Contains(stateToolInstallDir))
            {
                session.Log("State tool installation already on PATH");
            }
            else
            {
                var newPath = string.Format("{0};{1}", stateToolInstallDir, oldPath);
                session.Log(string.Format("updating PATH to {0}", newPath));
                try
                {
                    Environment.SetEnvironmentVariable("PATH", newPath, EnvironmentVariableTarget.Machine);
                }
                catch (Exception e)
                {
                    string msg = string.Format("Could not update PATH. Encountered exception: {0}", e.Message);
                    session.Log(msg);
                    new SecurityError().SetDetails(session, msg);
                    return ActionResult.Failure;
                }
            }

            session.Log("Running prepare step...");
            string prepareCmd = " _prepare";
            string prepareOutput;
            ActionResult prepareRunResult = ActiveState.Command.Run(session, stateToolPath, prepareCmd, out prepareOutput);
            if (prepareRunResult.Equals(ActionResult.Failure))
            {
                string msg = string.Format("Preparing environment caused error: {0}", prepareOutput);
                session.Log(msg);
                RollbarReport.Critical(msg, session);

                Record record = new Record();
                var errorOutput = Command.FormatErrorOutput(prepareOutput);
                record.FormatString = msg;

                session.Message(InstallMessage.Error | (InstallMessage)MessageBoxButtons.OK, record);
                return ActionResult.Failure;
            }
            else
            {
                session.Log(string.Format("Prepare Output: {0}", prepareOutput));
            }

            Status.ProgressBar.Increment(session, 50);
            return ActionResult.Success;
        }
Ejemplo n.º 30
0
        private static string ComputeHash(string data, string algorithm)
        {
            // Disable MD5 insecure warning.
#pragma warning disable CA5351
            using (HashAlgorithm hash = algorithm.StartsWith(Sha256, StringComparison.OrdinalIgnoreCase) ? SHA256.Create() : (HashAlgorithm)MD5.Create())
#pragma warning restore CA5351
            {
                Span <byte> result       = stackalloc byte[hash.HashSize / 8]; // HashSize is in bits
                bool        hashComputed = hash.TryComputeHash(Encoding.UTF8.GetBytes(data), result, out int bytesWritten);
                Debug.Assert(hashComputed && bytesWritten == result.Length);

                return(HexConverter.ToString(result, HexConverter.Casing.Lower));
            }
        }
Ejemplo n.º 31
0
        public async Task <AttestationVerificationSuccess> VerifyAsync(CredentialCreateOptions originalOptions, string expectedOrigin, IsCredentialIdUniqueToUserAsyncDelegate isCredentialIdUniqueToUser, IMetadataService metadataService, byte[] requestTokenBindingId)
        {
            AttestationType attnType;

            X509Certificate2[] trustPath = null;
            BaseVerify(expectedOrigin, originalOptions.Challenge, requestTokenBindingId);
            // verify challenge is same as we expected
            // verify origin
            // done in baseclass

            if (Type != "webauthn.create")
            {
                throw new Fido2VerificationException("AttestationResponse is not type webauthn.create");
            }

            if (Raw.Id == null || Raw.Id.Length == 0)
            {
                throw new Fido2VerificationException("AttestationResponse is missing Id");
            }

            if (Raw.Type != "public-key")
            {
                throw new Fido2VerificationException("AttestationResponse is missing type with value 'public-key'");
            }

            if (null == AttestationObject.AuthData || 0 == AttestationObject.AuthData.Length)
            {
                throw new Fido2VerificationException("Missing or malformed authData");
            }
            AuthenticatorData authData = new AuthenticatorData(AttestationObject.AuthData);

            // 6
            //todo:  Verify that the value of C.tokenBinding.status matches the state of Token Binding for the TLS connection over which the assertion was obtained.If Token Binding was used on that TLS connection, also verify that C.tokenBinding.id matches the base64url encoding of the Token Binding ID for the connection.
            // This id done in BaseVerify.
            // todo: test that implmentation

            // 7
            // Compute the hash of response.clientDataJSON using SHA - 256.
            byte[] hashedClientDataJson;
            byte[] hashedRpId;
            using (var sha = SHA256.Create())
            {
                hashedClientDataJson = sha.ComputeHash(Raw.Response.ClientDataJson);
                hashedRpId           = sha.ComputeHash(Encoding.UTF8.GetBytes(originalOptions.Rp.Id));
            }

            // 9
            // Verify that the RP ID hash in authData is indeed the SHA - 256 hash of the RP ID expected by the RP.
            if (false == authData.RpIdHash.SequenceEqual(hashedRpId))
            {
                throw new Fido2VerificationException("Hash mismatch RPID");
            }

            // 10
            // Verify that the User Present bit of the flags in authData is set.
            if (false == authData.UserPresent)
            {
                throw new Fido2VerificationException("User Present flag not set in authenticator data");
            }

            // 11
            // If user verification is required for this registration, verify that the User Verified bit of the flags in authData is set.
            var userVerified = authData.UserVerified;

            // 12
            // Verify that the values of the client extension outputs in clientExtensionResults and the authenticator extension outputs in the extensions in authData are as expected
            // todo: Implement sort of like this: ClientExtensions.Keys.Any(x => options.extensions.contains(x);

            // A COSEAlgorithmIdentifier containing the identifier of the algorithm used to generate the attestation signature
            var alg = AttestationObject.AttStmt["alg"];
            // A byte string containing the attestation signature
            var sig = AttestationObject.AttStmt["sig"];
            // The elements of this array contain attestnCert and its certificate chain, each encoded in X.509 format
            var x5c = AttestationObject.AttStmt["x5c"];
            // The identifier of the ECDAA-Issuer public key
            var ecdaaKeyId = AttestationObject.AttStmt["ecdaaKeyId"];

            if (false == authData.AttestedCredentialDataPresent)
            {
                throw new Fido2VerificationException("Attestation flag not set on attestation data");
            }
            var credentialId             = authData.AttData.CredentialID;
            var credentialPublicKeyBytes = authData.AttData.CredentialPublicKey.ToArray();

            PeterO.Cbor.CBORObject credentialPublicKey = null;
            var coseKty = 0;
            var coseAlg = 0;

            try
            {
                credentialPublicKey = PeterO.Cbor.CBORObject.DecodeFromBytes(authData.AttData.CredentialPublicKey);
                coseKty             = credentialPublicKey[PeterO.Cbor.CBORObject.FromObject(1)].AsInt32();
                coseAlg             = credentialPublicKey[PeterO.Cbor.CBORObject.FromObject(3)].AsInt32();
            }
            catch (PeterO.Cbor.CBORException)
            {
                throw new Fido2VerificationException("Malformed credentialPublicKey");
            }
            byte[] data = new byte[AttestationObject.AuthData.Length + hashedClientDataJson.Length];
            Buffer.BlockCopy(AttestationObject.AuthData, 0, data, 0, AttestationObject.AuthData.Length);
            Buffer.BlockCopy(hashedClientDataJson, 0, data, AttestationObject.AuthData.Length, hashedClientDataJson.Length);
            // 13
            // Determine the attestation statement format by performing a USASCII case-sensitive match on fmt against the set of supported WebAuthn Attestation Statement Format Identifier values. The up-to-date list of registered WebAuthn Attestation Statement Format Identifier values is maintained in the in the IANA registry of the same name [WebAuthn-Registries].
            // https://www.w3.org/TR/webauthn/#defined-attestation-formats
            switch (AttestationObject.Fmt)
            {
            // 14
            // validate the attStmt

            case "none":
            {
                // https://www.w3.org/TR/webauthn/#none-attestation

                if (0 != AttestationObject.AttStmt.Keys.Count && 0 != AttestationObject.AttStmt.Values.Count)
                {
                    throw new Fido2VerificationException("Attestation format none should have no attestation statement");
                }
                attnType  = AttestationType.None;
                trustPath = null;
            }
            break;

            case "tpm":
            {
                // https://www.w3.org/TR/webauthn/#tpm-attestation

                if (null == sig || PeterO.Cbor.CBORType.ByteString != sig.Type || 0 == sig.GetByteString().Length)
                {
                    throw new Fido2VerificationException("Invalid TPM attestation signature");
                }
                if ("2.0" != AttestationObject.AttStmt["ver"].AsString())
                {
                    throw new Fido2VerificationException("FIDO2 only supports TPM 2.0");
                }

                // Verify that the public key specified by the parameters and unique fields of pubArea is identical to the credentialPublicKey in the attestedCredentialData in authenticatorData
                PubArea pubArea = null;
                if (null != AttestationObject.AttStmt["pubArea"] && PeterO.Cbor.CBORType.ByteString == AttestationObject.AttStmt["pubArea"].Type && 0 != AttestationObject.AttStmt["pubArea"].GetByteString().Length)
                {
                    pubArea = new PubArea(AttestationObject.AttStmt["pubArea"].GetByteString());
                }
                if (null == pubArea || null == pubArea.Unique || 0 == pubArea.Unique.Length)
                {
                    throw new Fido2VerificationException("Missing or malformed pubArea");
                }
                if (3 == coseKty)                                                                             // RSA
                {
                    var coseMod = credentialPublicKey[PeterO.Cbor.CBORObject.FromObject(-1)].GetByteString(); // modulus
                    var coseExp = credentialPublicKey[PeterO.Cbor.CBORObject.FromObject(-2)].GetByteString(); // exponent

                    if (!coseMod.ToArray().SequenceEqual(pubArea.Unique.ToArray()))
                    {
                        throw new Fido2VerificationException("Public key mismatch between pubArea and credentialPublicKey");
                    }
                    if ((coseExp[0] + (coseExp[1] << 8) + (coseExp[2] << 16)) != pubArea.Exponent)
                    {
                        throw new Fido2VerificationException("Public key exponent mismatch between pubArea and credentialPublicKey");
                    }
                }
                else if (2 == coseKty)         // ECC
                {
                    var curve = credentialPublicKey[PeterO.Cbor.CBORObject.FromObject(-1)].AsInt32();
                    var X     = credentialPublicKey[PeterO.Cbor.CBORObject.FromObject(-2)].GetByteString();
                    var Y     = credentialPublicKey[PeterO.Cbor.CBORObject.FromObject(-3)].GetByteString();

                    if (pubArea.EccCurve != AuthDataHelper.CoseCurveToTpm[curve])
                    {
                        throw new Fido2VerificationException("Curve mismatch between pubArea and credentialPublicKey");
                    }
                    if (!pubArea.ECPoint.X.SequenceEqual(X))
                    {
                        throw new Fido2VerificationException("X-coordinate mismatch between pubArea and credentialPublicKey");
                    }
                    if (!pubArea.ECPoint.Y.SequenceEqual(Y))
                    {
                        throw new Fido2VerificationException("Y-coordinate mismatch between pubArea and credentialPublicKey");
                    }
                }
                // Concatenate authenticatorData and clientDataHash to form attToBeSigned.
                // see data variable

                // Validate that certInfo is valid
                CertInfo certInfo = null;
                if (null != AttestationObject.AttStmt["certInfo"] && PeterO.Cbor.CBORType.ByteString == AttestationObject.AttStmt["certInfo"].Type && 0 != AttestationObject.AttStmt["certInfo"].GetByteString().Length)
                {
                    certInfo = new CertInfo(AttestationObject.AttStmt["certInfo"].GetByteString());
                }
                if (null == certInfo || null == certInfo.ExtraData || 0 == certInfo.ExtraData.Length)
                {
                    throw new Fido2VerificationException("CertInfo invalid parsing TPM format attStmt");
                }
                // Verify that magic is set to TPM_GENERATED_VALUE and type is set to TPM_ST_ATTEST_CERTIFY
                // handled in parser, see certInfo.Magic

                // Verify that extraData is set to the hash of attToBeSigned using the hash algorithm employed in "alg"
                if (null == alg || PeterO.Cbor.CBORType.Number != alg.Type || false == AuthDataHelper.algMap.ContainsKey(alg.AsInt32()))
                {
                    throw new Fido2VerificationException("Invalid TPM attestation algorithm");
                }
                if (!AuthDataHelper.GetHasher(AuthDataHelper.algMap[alg.AsInt32()]).ComputeHash(data).SequenceEqual(certInfo.ExtraData))
                {
                    throw new Fido2VerificationException("Hash value mismatch extraData and attToBeSigned");
                }

                // Verify that attested contains a TPMS_CERTIFY_INFO structure, whose name field contains a valid Name for pubArea, as computed using the algorithm in the nameAlg field of pubArea
                if (false == AuthDataHelper.GetHasher(AuthDataHelper.algMap[(int)certInfo.Alg]).ComputeHash(pubArea.Raw).SequenceEqual(certInfo.AttestedName))
                {
                    throw new Fido2VerificationException("Hash value mismatch attested and pubArea");
                }

                // If x5c is present, this indicates that the attestation type is not ECDAA
                if (null != x5c && PeterO.Cbor.CBORType.Array == x5c.Type && 0 != x5c.Count)
                {
                    if (null == x5c.Values || 0 == x5c.Values.Count || PeterO.Cbor.CBORType.ByteString != x5c.Values.First().Type || 0 == x5c.Values.First().GetByteString().Length)
                    {
                        throw new Fido2VerificationException("Malformed x5c in TPM attestation");
                    }

                    // Verify the sig is a valid signature over certInfo using the attestation public key in aikCert with the algorithm specified in alg.
                    var aikCert = new X509Certificate2(x5c.Values.First().GetByteString());

                    PeterO.Cbor.CBORObject coseKey = AuthDataHelper.CoseKeyFromCertAndAlg(aikCert, alg.AsInt32());

                    if (true != AuthDataHelper.VerifySigWithCoseKey(certInfo.Raw, coseKey, sig.GetByteString()))
                    {
                        throw new Fido2VerificationException("Bad signature in TPM with aikCert");
                    }

                    // Verify that aikCert meets the TPM attestation statement certificate requirements
                    // https://www.w3.org/TR/webauthn/#tpm-cert-requirements
                    // Version MUST be set to 3
                    if (3 != aikCert.Version)
                    {
                        throw new Fido2VerificationException("aikCert must be V3");
                    }

                    // Subject field MUST be set to empty - they actually mean subject name
                    if (0 != aikCert.SubjectName.Name.Length)
                    {
                        throw new Fido2VerificationException("aikCert subject must be empty");
                    }

                    // The Subject Alternative Name extension MUST be set as defined in [TPMv2-EK-Profile] section 3.2.9.
                    // https://www.w3.org/TR/webauthn/#tpm-cert-requirements
                    var SAN = AuthDataHelper.SANFromAttnCertExts(aikCert.Extensions);
                    if (null == SAN || 0 == SAN.Length)
                    {
                        throw new Fido2VerificationException("SAN missing from TPM attestation certificate");
                    }
                    // From https://www.trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf
                    // The issuer MUST include TPM manufacturer, TPM part number and TPM firmware version, using the directoryNameform within the GeneralName structure. The ASN.1 encoding is specified in section 3.1.2 TPM Device Attributes. In accordance with RFC 5280[11], this extension MUST be critical if subject is empty and SHOULD be non-critical if subject is non-empty.  
                    // Best I can figure to do for now?
                    if (false == SAN.Contains("TPMManufacturer") || false == SAN.Contains("TPMModel") || false == SAN.Contains("TPMVersion"))
                    {
                        throw new Fido2VerificationException("SAN missing TPMManufacturer, TPMModel, or TPMVersopm from TPM attestation certificate");
                    }
                    // The Extended Key Usage extension MUST contain the "joint-iso-itu-t(2) internationalorganizations(23) 133 tcg-kp(8) tcg-kp-AIKCertificate(3)" OID.
                    // OID is 2.23.133.8.3
                    var EKU = AuthDataHelper.EKUFromAttnCertExts(aikCert.Extensions);
                    if (null == EKU || 0 != EKU.CompareTo("Attestation Identity Key Certificate (2.23.133.8.3)"))
                    {
                        throw new Fido2VerificationException("Invalid EKU on AIK certificate");
                    }

                    // The Basic Constraints extension MUST have the CA component set to false.
                    if (AuthDataHelper.IsAttnCertCACert(aikCert.Extensions))
                    {
                        throw new Fido2VerificationException("aikCert Basic Constraints extension CA component must be false");
                    }

                    // If aikCert contains an extension with OID 1.3.6.1.4.1.45724.1.1.4 (id-fido-gen-ce-aaguid) verify that the value of this extension matches the aaguid in authenticatorData
                    var aaguid = AuthDataHelper.AaguidFromAttnCertExts(aikCert.Extensions);
                    if ((null != aaguid) && (!aaguid.SequenceEqual(Guid.Empty.ToByteArray())) && (!aaguid.SequenceEqual(authData.AttData.Aaguid.ToArray())))
                    {
                        throw new Fido2VerificationException("aaguid malformed");
                    }

                    // If successful, return attestation type AttCA and attestation trust path x5c.
                    attnType  = AttestationType.AttCa;
                    trustPath = x5c.Values
                                .Select(x => new X509Certificate2(x.GetByteString()))
                                .ToArray();
                }
                // If ecdaaKeyId is present, then the attestation type is ECDAA
                else if (null != ecdaaKeyId)
                {
                    // Perform ECDAA-Verify on sig to verify that it is a valid signature over certInfo
                    // https://www.w3.org/TR/webauthn/#biblio-fidoecdaaalgorithm
                    throw new Fido2VerificationException("ECDAA support for TPM attestation is not yet implemented");
                    // If successful, return attestation type ECDAA and the identifier of the ECDAA-Issuer public key ecdaaKeyId.
                    //attnType = AttestationType.ECDAA;
                    //trustPath = ecdaaKeyId;
                }
                else
                {
                    throw new Fido2VerificationException("Neither x5c nor ECDAA were found in the TPM attestation statement");
                }
            }
            break;

            case "android-key":
            {
                // https://www.w3.org/TR/webauthn/#android-key-attestation

                // Verify that attStmt is valid CBOR conforming to the syntax defined above and perform CBOR decoding on it to extract the contained fields
                if (0 == AttestationObject.AttStmt.Keys.Count || 0 == AttestationObject.AttStmt.Values.Count)
                {
                    throw new Fido2VerificationException("Attestation format packed must have attestation statement");
                }
                if (null == sig || PeterO.Cbor.CBORType.ByteString != sig.Type || 0 == sig.GetByteString().Length)
                {
                    throw new Fido2VerificationException("Invalid packed attestation signature");
                }
                // 2a. Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
                // using the attestation public key in attestnCert with the algorithm specified in alg
                if (null == x5c && PeterO.Cbor.CBORType.Array != x5c.Type && 0 == x5c.Count)
                {
                    throw new Fido2VerificationException("Malformed x5c in android-key attestation");
                }
                if (null == x5c.Values || 0 == x5c.Values.Count || PeterO.Cbor.CBORType.ByteString != x5c.Values.First().Type || 0 == x5c.Values.First().GetByteString().Length)
                {
                    throw new Fido2VerificationException("Malformed x5c in android-key attestation");
                }
                X509Certificate2 androidKeyCert   = null;
                ECDsaCng         androidKeyPubKey = null;
                try
                {
                    androidKeyCert   = new X509Certificate2(x5c.Values.First().GetByteString());
                    androidKeyPubKey = (ECDsaCng)androidKeyCert.GetECDsaPublicKey();         // attestation public key
                }
                catch (Exception ex)
                {
                    throw new Fido2VerificationException("Failed to extract public key from android key" + ex.Message);
                }
                if (null == alg || PeterO.Cbor.CBORType.Number != alg.Type || false == AuthDataHelper.algMap.ContainsKey(alg.AsInt32()))
                {
                    throw new Fido2VerificationException("Invalid attestation algorithm");
                }
                if (true != androidKeyPubKey.VerifyData(data, AuthDataHelper.SigFromEcDsaSig(sig.GetByteString()), AuthDataHelper.algMap[alg.AsInt32()]))
                {
                    throw new Fido2VerificationException("Invalid android key signature");
                }
                var cng = ECDsaCng.Create(new ECParameters
                    {
                        Curve = ECCurve.NamedCurves.nistP256,
                        Q     = new ECPoint
                        {
                            X = credentialPublicKey[PeterO.Cbor.CBORObject.FromObject(-2)].GetByteString(),
                            Y = credentialPublicKey[PeterO.Cbor.CBORObject.FromObject(-3)].GetByteString()
                        }
                    });
                // Verify that the public key in the first certificate in in x5c matches the credentialPublicKey in the attestedCredentialData in authenticatorData.
                if (true != cng.VerifyData(data, AuthDataHelper.SigFromEcDsaSig(sig.GetByteString()), AuthDataHelper.algMap[alg.AsInt32()]))
                {
                    throw new Fido2VerificationException("Invalid android key signature");
                }

                // Verify that in the attestation certificate extension data:
                var attExtBytes = AuthDataHelper.AttestationExtensionBytes(androidKeyCert.Extensions);

                // 1. The value of the attestationChallenge field is identical to clientDataHash.
                var attestationChallenge = AuthDataHelper.GetAttestationChallenge(attExtBytes);
                if (false == hashedClientDataJson.SequenceEqual(attestationChallenge))
                {
                    throw new Fido2VerificationException("Mismatched between attestationChallenge and hashedClientDataJson verifying android key attestation certificate extension");
                }

                // 2. The AuthorizationList.allApplications field is not present, since PublicKeyCredential MUST be bound to the RP ID.
                if (true == AuthDataHelper.FindAllApplicationsField(attExtBytes))
                {
                    throw new Fido2VerificationException("Found all applications field in android key attestation certificate extension");
                }

                // 3. The value in the AuthorizationList.origin field is equal to KM_ORIGIN_GENERATED ( which == 0).
                if (false == AuthDataHelper.IsOriginGenerated(attExtBytes))
                {
                    throw new Fido2VerificationException("Found origin field not set to KM_ORIGIN_GENERATED in android key attestation certificate extension");
                }

                // 4. The value in the AuthorizationList.purpose field is equal to KM_PURPOSE_SIGN (which == 2).
                if (false == AuthDataHelper.IsPurposeSign(attExtBytes))
                {
                    throw new Fido2VerificationException("Found purpose field not set to KM_PURPOSE_SIGN in android key attestation certificate extension");
                }

                attnType  = AttestationType.Basic;
                trustPath = x5c.Values
                            .Select(x => new X509Certificate2(x.GetByteString()))
                            .ToArray();
            }
            break;

            case "android-safetynet":
            {
                // https://www.w3.org/TR/webauthn/#android-safetynet-attestation

                // Verify that attStmt is valid CBOR conforming to the syntax defined above and perform CBOR decoding on it to extract the contained fields
                if ((PeterO.Cbor.CBORType.TextString != AttestationObject.AttStmt["ver"].Type) || (0 == AttestationObject.AttStmt["ver"].AsString().Length))
                {
                    throw new Fido2VerificationException("Invalid version in SafetyNet data");
                }

                // Verify that response is a valid SafetyNet response of version ver
                var ver = AttestationObject.AttStmt["ver"].AsString();

                if ((PeterO.Cbor.CBORType.ByteString != AttestationObject.AttStmt["response"].Type) || (0 == AttestationObject.AttStmt["response"].GetByteString().Length))
                {
                    throw new Fido2VerificationException("Invalid response in SafetyNet data");
                }
                var response = AttestationObject.AttStmt["response"].GetByteString();
                var signedAttestationStatement = Encoding.UTF8.GetString(response);
                var jwtToken           = new JwtSecurityToken(signedAttestationStatement);
                X509SecurityKey[] keys = (jwtToken.Header["x5c"] as JArray)
                                         .Values <string>()
                                         .Select(x => new X509SecurityKey(
                                                     new X509Certificate2(Convert.FromBase64String(x))))
                                         .ToArray();
                if ((null == keys) || (0 == keys.Count()))
                {
                    throw new Fido2VerificationException("SafetyNet attestation missing x5c");
                }
                var validationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKeys        = keys
                };

                var           tokenHandler = new JwtSecurityTokenHandler();
                SecurityToken validatedToken;

                tokenHandler.ValidateToken(
                    signedAttestationStatement,
                    validationParameters,
                    out validatedToken);

                if (false == (validatedToken.SigningKey is X509SecurityKey))
                {
                    throw new Fido2VerificationException("Safetynet signing key invalid");
                }

                var nonce   = "";
                var payload = false;
                foreach (var claim in jwtToken.Claims)
                {
                    if (("nonce" == claim.Type) && ("http://www.w3.org/2001/XMLSchema#string" == claim.ValueType) && (0 != claim.Value.Length))
                    {
                        nonce = claim.Value;
                    }
                    if (("ctsProfileMatch" == claim.Type) && ("http://www.w3.org/2001/XMLSchema#boolean" == claim.ValueType))
                    {
                        payload = bool.Parse(claim.Value);
                    }
                    if (("timestampMs" == claim.Type) && ("http://www.w3.org/2001/XMLSchema#integer64" == claim.ValueType))
                    {
                        DateTime dt = DateTimeHelper.UnixEpoch.AddMilliseconds(double.Parse(claim.Value));
                        if ((DateTime.UtcNow < dt) || (DateTime.UtcNow.AddMinutes(-1) > dt))
                        {
                            throw new Fido2VerificationException("Android SafetyNet timestampMs must be between one minute ago and now");
                        }
                    }
                }

                // Verify that the nonce in the response is identical to the SHA-256 hash of the concatenation of authenticatorData and clientDataHash
                if ("" == nonce)
                {
                    throw new Fido2VerificationException("Nonce value not found in Android SafetyNet attestation");
                }
                if (!AuthDataHelper.GetHasher(HashAlgorithmName.SHA256).ComputeHash(data).SequenceEqual(Convert.FromBase64String(nonce)))
                {
                    throw new Fido2VerificationException("Android SafetyNet hash value mismatch");
                }

                // Verify that the attestation certificate is issued to the hostname "attest.android.com"
                if (false == ("attest.android.com").Equals((validatedToken.SigningKey as X509SecurityKey).Certificate.GetNameInfo(X509NameType.DnsName, false)))
                {
                    throw new Fido2VerificationException("Safetynet DnsName is not attest.android.com");
                }

                // Verify that the ctsProfileMatch attribute in the payload of response is true
                if (true != payload)
                {
                    throw new Fido2VerificationException("Android SafetyNet ctsProfileMatch must be true");
                }

                attnType  = AttestationType.Basic;
                trustPath = (jwtToken.Header["x5c"] as JArray)
                            .Values <string>()
                            .Select(x => new X509Certificate2(Convert.FromBase64String(x)))
                            .ToArray();
            }
            break;

            case "fido-u2f":
            {
                // https://www.w3.org/TR/webauthn/#fido-u2f-attestation

                // verify that aaguid is 16 empty bytes (note: required by fido2 conformance testing, could not find this in spec?)
                if (false == authData.AttData.Aaguid.SequenceEqual(Guid.Empty.ToByteArray()))
                {
                    throw new Fido2VerificationException("Aaguid was not empty parsing fido-u2f atttestation statement");
                }

                // 1. Verify that attStmt is valid CBOR conforming to the syntax defined above and perform CBOR decoding on it to extract the contained fields.
                if (null == x5c || PeterO.Cbor.CBORType.Array != x5c.Type || x5c.Count != 1)
                {
                    throw new Fido2VerificationException("Malformed x5c in fido - u2f attestation");
                }

                // 2a. the attestation certificate attestnCert MUST be the first element in the array
                if (null == x5c.Values || 0 == x5c.Values.Count || PeterO.Cbor.CBORType.ByteString != x5c.Values.First().Type || 0 == x5c.Values.First().GetByteString().Length)
                {
                    throw new Fido2VerificationException("Malformed x5c in fido-u2f attestation");
                }
                var cert = new X509Certificate2(x5c.Values.First().GetByteString());

                // 2b. If certificate public key is not an Elliptic Curve (EC) public key over the P-256 curve, terminate this algorithm and return an appropriate error
                var pubKey = (ECDsaCng)cert.GetECDsaPublicKey();
                if (CngAlgorithm.ECDsaP256 != pubKey.Key.Algorithm)
                {
                    throw new Fido2VerificationException("attestation certificate public key is not an Elliptic Curve (EC) public key over the P-256 curve");
                }

                // 3. Extract the claimed rpIdHash from authenticatorData, and the claimed credentialId and credentialPublicKey from authenticatorData
                // done above

                // 4. Convert the COSE_KEY formatted credentialPublicKey (see Section 7 of [RFC8152]) to CTAP1/U2F public Key format
                var publicKeyU2F = AuthDataHelper.U2FKeyFromCOSEKey(credentialPublicKey);

                // 5. Let verificationData be the concatenation of (0x00 || rpIdHash || clientDataHash || credentialId || publicKeyU2F)
                var verificationData = new byte[1] {
                    0x00
                };
                verificationData = verificationData.Concat(hashedRpId).Concat(hashedClientDataJson).Concat(credentialId).Concat(publicKeyU2F.ToArray()).ToArray();

                // 6. Verify the sig using verificationData and certificate public key
                if (null == sig || PeterO.Cbor.CBORType.ByteString != sig.Type || 0 == sig.GetByteString().Length)
                {
                    throw new Fido2VerificationException("Invalid fido-u2f attestation signature");
                }
                var ecsig = AuthDataHelper.SigFromEcDsaSig(sig.GetByteString());
                if (null == ecsig)
                {
                    throw new Fido2VerificationException("Failed to decode fido-u2f attestation signature from ASN.1 encoded form");
                }
                if (true != pubKey.VerifyData(verificationData, ecsig, AuthDataHelper.algMap[coseAlg]))
                {
                    throw new Fido2VerificationException("Invalid fido-u2f attestation signature");
                }
                attnType  = AttestationType.Basic;
                trustPath = x5c.Values
                            .Select(x => new X509Certificate2(x.GetByteString()))
                            .ToArray();
            }
            break;

            case "packed":
            {
                // https://www.w3.org/TR/webauthn/#packed-attestation

                // Verify that attStmt is valid CBOR conforming to the syntax defined above and perform CBOR decoding on it to extract the contained fields.
                if (0 == AttestationObject.AttStmt.Keys.Count || 0 == AttestationObject.AttStmt.Values.Count)
                {
                    throw new Fido2VerificationException("Attestation format packed must have attestation statement");
                }
                if (null == sig || PeterO.Cbor.CBORType.ByteString != sig.Type || 0 == sig.GetByteString().Length)
                {
                    throw new Fido2VerificationException("Invalid packed attestation signature");
                }
                if (null == alg || PeterO.Cbor.CBORType.Number != alg.Type)
                {
                    throw new Fido2VerificationException("Invalid packed attestation algorithm");
                }

                // If x5c is present, this indicates that the attestation type is not ECDAA
                if (null != x5c)
                {
                    if (PeterO.Cbor.CBORType.Array != x5c.Type || 0 == x5c.Count || null != ecdaaKeyId)
                    {
                        throw new Fido2VerificationException("Malformed x5c array in packed attestation statement");
                    }
                    IEnumerator <PeterO.Cbor.CBORObject> enumerator = x5c.Values.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        if (null == enumerator || null == enumerator.Current || PeterO.Cbor.CBORType.ByteString != enumerator.Current.Type || 0 == enumerator.Current.GetByteString().Length)
                        {
                            throw new Fido2VerificationException("Malformed x5c cert found in packed attestation statement");
                        }
                        var x5ccert = new X509Certificate2(enumerator.Current.GetByteString());
                        if (DateTime.UtcNow < x5ccert.NotBefore || DateTime.UtcNow > x5ccert.NotAfter)
                        {
                            throw new Fido2VerificationException("Packed signing certificate expired or not yet valid");
                        }
                    }

                    // The attestation certificate attestnCert MUST be the first element in the array.
                    var attestnCert = new X509Certificate2(x5c.Values.First().GetByteString());

                    // 2a. Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
                    // using the attestation public key in attestnCert with the algorithm specified in alg
                    var packedPubKey = (ECDsaCng)attestnCert.GetECDsaPublicKey();         // attestation public key
                    if (false == AuthDataHelper.algMap.ContainsKey(alg.AsInt32()))
                    {
                        throw new Fido2VerificationException("Invalid attestation algorithm");
                    }

                    var coseKey = AuthDataHelper.CoseKeyFromCertAndAlg(attestnCert, alg.AsInt32());

                    if (true != AuthDataHelper.VerifySigWithCoseKey(data, coseKey, sig.GetByteString()))
                    {
                        throw new Fido2VerificationException("Invalid full packed signature");
                    }

                    // Verify that attestnCert meets the requirements in https://www.w3.org/TR/webauthn/#packed-attestation-cert-requirements
                    // 2b. Version MUST be set to 3
                    if (3 != attestnCert.Version)
                    {
                        throw new Fido2VerificationException("Packed x5c attestation certificate not V3");
                    }

                    // Subject field MUST contain C, O, OU, CN
                    // OU must match "Authenticator Attestation"
                    if (true != AuthDataHelper.IsValidPackedAttnCertSubject(attestnCert.Subject))
                    {
                        throw new Fido2VerificationException("Invalid attestation cert subject");
                    }

                    // 2c. If the related attestation root certificate is used for multiple authenticator models,
                    // the Extension OID 1.3.6.1.4.1.45724.1.1.4 (id-fido-gen-ce-aaguid) MUST be present, containing the AAGUID as a 16-byte OCTET STRING
                    // verify that the value of this extension matches the aaguid in authenticatorData
                    var aaguid = AuthDataHelper.AaguidFromAttnCertExts(attestnCert.Extensions);
                    if (aaguid != null && !aaguid.SequenceEqual(authData.AttData.Aaguid.ToArray()))
                    {
                        throw new Fido2VerificationException("aaguid present in packed attestation but does not match aaguid from authData");
                    }

                    // 2d. The Basic Constraints extension MUST have the CA component set to false
                    if (AuthDataHelper.IsAttnCertCACert(attestnCert.Extensions))
                    {
                        throw new Fido2VerificationException("Attestion certificate has CA cert flag present");
                    }

                    // id-fido-u2f-ce-transports
                    var u2ftransports = AuthDataHelper.U2FTransportsFromAttnCert(attestnCert.Extensions);
                    attnType  = AttestationType.Basic;
                    trustPath = x5c.Values
                                .Select(x => new X509Certificate2(x.GetByteString()))
                                .ToArray();
                }
                // If ecdaaKeyId is present, then the attestation type is ECDAA
                else if (null != ecdaaKeyId)
                {
                    // Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
                    // using ECDAA-Verify with ECDAA-Issuer public key identified by ecdaaKeyId
                    // https://www.w3.org/TR/webauthn/#biblio-fidoecdaaalgorithm

                    throw new Fido2VerificationException("ECDAA is not yet implemented");
                    // If successful, return attestation type ECDAA and attestation trust path ecdaaKeyId.
                    //attnType = AttestationType.ECDAA;
                    //trustPath = ecdaaKeyId;
                }
                // If neither x5c nor ecdaaKeyId is present, self attestation is in use
                else
                {
                    // Validate that alg matches the algorithm of the credentialPublicKey in authenticatorData
                    if (alg.AsInt32() != coseAlg)
                    {
                        throw new Fido2VerificationException("Algorithm mismatch between credential public key and authenticator data in self attestation statement");
                    }
                    // Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash using the credential public key with alg
                    if (true != AuthDataHelper.VerifySigWithCoseKey(data, credentialPublicKey, sig.GetByteString()))
                    {
                        throw new Fido2VerificationException("Failed to validate signature");
                    }

                    // If successful, return attestation type Self and empty attestation trust path.
                    attnType  = AttestationType.Self;
                    trustPath = null;
                }
            }
            break;

            default: throw new Fido2VerificationException("Missing or unknown attestation type");
            }

            /*
             * 15
             * If validation is successful, obtain a list of acceptable trust anchors (attestation root certificates or ECDAA-Issuer public keys) for that attestation type and attestation statement format fmt, from a trusted source or from policy. For example, the FIDO Metadata Service [FIDOMetadataService] provides one way to obtain such information, using the aaguid in the attestedCredentialData in authData.
             * */
            // MetadataService

            /*
             * 16
             * Assess the attestation trustworthiness using the outputs of the verification procedure in step 14, as follows: https://www.w3.org/TR/webauthn/#registering-a-new-credential
             * */
            // todo: implement (this is not for attfmt none)
            // use aaguid (authData.AttData.Aaguid) to find root certs in metadata
            // use root plus trustPath to build trust chain

            if (null != metadataService)
            {
                MetadataTOCPayloadEntry entry = metadataService.GetEntry(authData.AttData.GuidAaguid);

                if (null != entry)
                {
                    if (entry.Hash != entry.MetadataStatement.Hash)
                    {
                        throw new Fido2VerificationException("Authenticator metadata statement has invalid hash");
                    }
                    if (null != entry.MetadataStatement)
                    {
                        var hasBasicFull = entry.MetadataStatement.AttestationTypes.Contains((ushort)MetadataAttestationType.ATTESTATION_BASIC_FULL);
                        if (false == hasBasicFull &&
                            null != trustPath && trustPath.FirstOrDefault().Subject != trustPath.FirstOrDefault().Issuer)
                        {
                            throw new Fido2VerificationException("Attestation with full attestation from authentictor that does not support full attestation");
                        }
                        if (true == hasBasicFull && null != trustPath && trustPath.FirstOrDefault().Subject != trustPath.FirstOrDefault().Issuer)
                        {
                            var root  = new X509Certificate2(Convert.FromBase64String(entry.MetadataStatement.AttestationRootCertificates.FirstOrDefault()));
                            var chain = new X509Chain();
                            chain.ChainPolicy.ExtraStore.Add(root);
                            if (trustPath.Length > 1)
                            {
                                foreach (X509Certificate2 cert in trustPath.Skip(1).Reverse())
                                {
                                    chain.ChainPolicy.ExtraStore.Add(cert);
                                }
                            }
                            var valid = chain.Build(trustPath[0]);
                            if (false == valid)
                            {
                            }
                        }
                    }

                    foreach (StatusReport report in entry.StatusReports)
                    {
                        if (true == Enum.IsDefined(typeof(UndesiredAuthenticatorStatus), (UndesiredAuthenticatorStatus)report.Status))
                        {
                            throw new Fido2VerificationException("Authenticator found with undesirable status");
                        }
                    }
                }
            }

            /*
             * 17
             * Check that the credentialId is not yet registered to any other user.
             * If registration is requested for a credential that is already registered to a different user, the Relying Party SHOULD fail this registration ceremony, or it MAY decide to accept the registration, e.g. while deleting the older registration.
             * */
            if (false == await isCredentialIdUniqueToUser(new IsCredentialIdUniqueToUserParams(credentialId, originalOptions.User)))
            {
                throw new Fido2VerificationException("CredentialId is not unique to this user");
            }

            /*
             * 18
             * If the attestation statement attStmt verified successfully and is found to be trustworthy, then register the new credential with the account that was denoted in the options.user passed to create(), by associating it with the credentialId and credentialPublicKey in the attestedCredentialData in authData, as appropriate for the Relying Party's system.
             * */
            // This is handled by code att call site and result object.


            /*
             * 19
             * If the attestation statement attStmt successfully verified but is not trustworthy per step 16 above, the Relying Party SHOULD fail the registration ceremony.
             * NOTE: However, if permitted by policy, the Relying Party MAY register the credential ID and credential public key but treat the credential as one with self attestation (see §6.3.3 Attestation Types). If doing so, the Relying Party is asserting there is no cryptographic proof that the public key credential has been generated by a particular authenticator model. See [FIDOSecRef] and [UAFProtocol] for a more detailed discussion.
             * */
            // todo: implement (this is not for attfmt none)

            var result = new AttestationVerificationSuccess()
            {
                CredentialId = credentialId,
                PublicKey    = credentialPublicKeyBytes,
                User         = originalOptions.User,
                Counter      = BitConverter.ToUInt32(authData.SignCount.ToArray().Reverse().ToArray(), 0)
            };

            return(result);
        }
Ejemplo n.º 32
0
 /**
  * Signs a message.<br/>
  * This is a "one stop" method and does not require <code>initSign</code> to be called. Only the message supplied via
  * the parameter <code>m</code> is signed, regardless of prior calls to {@link #update(byte[])}.
  * @param m the message to sign
  * @param kp a key pair (the public key is needed to ensure there are no signing failures)
  * @return a signature
  * @throws NtruException if the JRE doesn't implement the specified hash algorithm
  */
 public byte[] sign(byte[] m, SignatureKeyPair kp)
 {
     try
     {
         // EESS directly passes the message into the MRGM (message representative
         // generation method). Since that is inefficient for long messages, we work
         // with the hash of the message.
         hashAlg = new SHA256();
         byte[] msgHash = hashAlg.ComputeHash(m);
         return signHash(msgHash, kp);
     }
     catch (Exception e)
     {
         throw new NtruException(e.Message);
     }
 }
Ejemplo n.º 33
0
        public static PrivateKey FromSeed(string seed)
        {
            var hash = SHA256.Create().HashAndDispose(Encoding.UTF8.GetBytes(seed));

            return(FromBuffer(hash));
        }
Ejemplo n.º 34
0
		public SHA256CryptoServiceProvider ()
		{
			// note: we don't use SHA256.Create since CryptoConfig could, 
			// if set to use this class, result in a endless recursion
			hash = new SHA256Managed ();
		}
Ejemplo n.º 35
0
        private static ExitCode RunHashOptionsAndReturnExitCode(HashOptions hashOptions)
        {
            GenericHashResult hashResult = null;

            switch (hashOptions.InputType.ToLower())
            {
            case "string":
            {
                switch (hashOptions.Algorithm.ToLower())
                {
                case "md5":
                    hashResult = new MD5().ComputeHash(hashOptions.InputToComputeHash);
                    break;

                case "sha1":
                    hashResult = new SHA1().ComputeHash(hashOptions.InputToComputeHash);
                    break;

                case "sha256":
                    hashResult = new SHA256().ComputeHash(hashOptions.InputToComputeHash);
                    break;

                case "sha384":
                    hashResult = new SHA384().ComputeHash(hashOptions.InputToComputeHash);
                    break;

                case "sha512":
                    hashResult = new SHA512().ComputeHash(hashOptions.InputToComputeHash);
                    break;

                case "pbkdf2":
                    hashResult = new PBKDF2_HMAC_SHA_1().ComputeHash(hashOptions.InputToComputeHash);
                    break;

                case "bcrypt":
                    hashResult = new Hash.BCrypt().ComputeHash(hashOptions.InputToComputeHash);
                    break;

                default:
                    hashResult = new GenericHashResult()
                    {
                        Success = false, Message = $"Unknown algorithm \"{hashOptions.Algorithm}\"."
                    };
                    break;
                }
            }
            break;

            case "file":
            {
                switch (hashOptions.Algorithm.ToLower())
                {
                case "md5":
                    //hashResult = new MD5().HashFile(hashOptions.InputToBeHashed);

                    using (var progressBar = new ProgressBar())
                    {
                        var md5 = new MD5();
                        md5.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); };

                        hashResult = md5.ComputeFileHash(hashOptions.InputToComputeHash);
                    }
                    break;

                case "sha1":
                    //hashResult = new SHA1().HashFile(hashOptions.InputToBeHashed);

                    using (var progressBar = new ProgressBar())
                    {
                        var sha1 = new SHA1();
                        sha1.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); };

                        hashResult = sha1.ComputeFileHash(hashOptions.InputToComputeHash);
                    }
                    break;

                case "sha256":
                    //hashResult = new SHA256().HashFile(hashOptions.InputToBeHashed);

                    using (var progressBar = new ProgressBar())
                    {
                        var sha256 = new SHA256();
                        sha256.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); };

                        hashResult = sha256.ComputeFileHash(hashOptions.InputToComputeHash);
                    }
                    break;

                case "sha384":
                    //hashResult = new SHA384().HashFile(hashOptions.InputToBeHashed);

                    using (var progressBar = new ProgressBar())
                    {
                        var sha384 = new SHA384();
                        sha384.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); };

                        hashResult = sha384.ComputeFileHash(hashOptions.InputToComputeHash);
                    }
                    break;

                case "sha512":
                    //hashResult = new SHA512().HashFile(hashOptions.InputToBeHashed);

                    using (var progressBar = new ProgressBar())
                    {
                        var sha512 = new SHA512();
                        sha512.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); };

                        hashResult = sha512.ComputeFileHash(hashOptions.InputToComputeHash);
                    }
                    break;

                case "pbkdf2":
                case "bcrypt":
                    hashResult = new GenericHashResult()
                    {
                        Success = false, Message = $"Algorithm \"{hashOptions.Algorithm}\" currently not available for file hashing."
                    };
                    break;

                default:
                    hashResult = new GenericHashResult()
                    {
                        Success = false, Message = $"Unknown algorithm \"{hashOptions.Algorithm}\"."
                    };
                    break;
                }
            }
            break;

            default:
                hashResult = new GenericHashResult()
                {
                    Success = false, Message = $"Unknown input type \"{hashOptions.InputType}\"."
                };
                break;
            }

            if (hashResult.Success && !string.IsNullOrWhiteSpace(hashOptions.CompareHash))
            {
                bool hashesMatch = (
                    hashOptions.Algorithm.ToLower() != "bcrypt" && hashOptions.Algorithm.ToLower() != "pbkdf2"
                        ? (hashResult.HashString).Equals(hashOptions.CompareHash, StringComparison.InvariantCultureIgnoreCase)
                        : (hashOptions.Algorithm.ToLower() == "bcrypt"
                            ? new Hash.BCrypt().VerifyHash(hashOptions.InputToComputeHash, hashOptions.CompareHash).Success
                            : new Hash.PBKDF2_HMAC_SHA_1().VerifyHash(hashOptions.InputToComputeHash, hashOptions.CompareHash).Success
                           )
                    );

                var outputMessage = (
                    hashesMatch
                        ? $"Computed hash MATCH with given hash: {(hashOptions.Algorithm.ToLower() != "bcrypt" ? hashResult.HashString : hashOptions.CompareHash)}"
                        : $"Computed hash DOES NOT MATCH with given hash." +
                    (
                        hashOptions.Algorithm.ToLower() != "bcrypt"
                                ? $"\nComputed hash: {hashResult.HashString}\nGiven hash: {hashOptions.CompareHash}"
                                : ""
                    )
                    );

                Console.WriteLine(outputMessage);

                return(hashesMatch ? ExitCode.Sucess : ExitCode.Error);
            }
            else if (hashResult.Success && string.IsNullOrWhiteSpace(hashOptions.CompareHash))
            {
                Console.WriteLine(hashResult.HashString);

                return(ExitCode.Sucess);
            }
            else
            {
                Console.WriteLine(hashResult.Message);

                return(ExitCode.Error);
            }
        }