summary refs log tree commit diff
path: root/crypto/src/security/JksStore.cs
blob: c5ef92a70d579e624089f6402a5f2a47ee3aa99c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.IO;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Date;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.X509;

namespace Org.BouncyCastle.Security
{
    public class JksStore
    {
        private static readonly int Magic = unchecked((int)0xFEEDFEED);

        private static readonly AlgorithmIdentifier JksObfuscationAlg = new AlgorithmIdentifier(
            new DerObjectIdentifier("1.3.6.1.4.1.42.2.17.1.1"), DerNull.Instance);

        private readonly Dictionary<string, JksTrustedCertEntry> m_certificateEntries =
            new Dictionary<string, JksTrustedCertEntry>(StringComparer.OrdinalIgnoreCase);
        private readonly Dictionary<string, JksKeyEntry> m_keyEntries =
            new Dictionary<string, JksKeyEntry>(StringComparer.OrdinalIgnoreCase);

        public JksStore()
        {
        }

        /// <exception cref="IOException"/>
        public bool Probe(Stream stream)
        {
            using (var br = new BinaryReader(stream))
            try
            {
                return Magic == BinaryReaders.ReadInt32BigEndian(br);
            }
            catch (EndOfStreamException)
            {
                return false;
            }
        }

        /// <exception cref="IOException"/>
        public AsymmetricKeyParameter GetKey(string alias, char[] password)
        {
            if (alias == null)
                throw new ArgumentNullException(nameof(alias));
            if (password == null)
                throw new ArgumentNullException(nameof(password));

            if (!m_keyEntries.TryGetValue(alias, out JksKeyEntry keyEntry))
                return null;

            if (!JksObfuscationAlg.Equals(keyEntry.keyData.EncryptionAlgorithm))
                throw new IOException("unknown encryption algorithm");

            byte[] encryptedData = keyEntry.keyData.GetEncryptedData();

            // key length is encryptedData - salt - checksum
            int pkcs8Len = encryptedData.Length - 40;

            IDigest digest = DigestUtilities.GetDigest("SHA-1");

            // key decryption
            byte[] keyStream = CalculateKeyStream(digest, password, encryptedData, pkcs8Len);
            byte[] pkcs8Key = new byte[pkcs8Len];
            for (int i = 0; i < pkcs8Len; ++i)
            {
                pkcs8Key[i] = (byte)(encryptedData[20 + i] ^ keyStream[i]);
            }
            Array.Clear(keyStream, 0, keyStream.Length);

            // integrity check
            byte[] checksum = GetKeyChecksum(digest, password, pkcs8Key);

            if (!Arrays.FixedTimeEquals(20, encryptedData, pkcs8Len + 20, checksum, 0))
                throw new IOException("cannot recover key");

            return PrivateKeyFactory.CreateKey(pkcs8Key);
        }

        private byte[] GetKeyChecksum(IDigest digest, char[] password, byte[] pkcs8Key)
        {
            AddPassword(digest, password);

            return DigestUtilities.DoFinal(digest, pkcs8Key);
        }

        private byte[] CalculateKeyStream(IDigest digest, char[] password, byte[] salt, int count)
        {
            byte[] keyStream = new byte[count];
            byte[] hash = Arrays.CopyOf(salt, 20);

            int index = 0;
            while (index < count)
            {
                AddPassword(digest, password);

                digest.BlockUpdate(hash, 0, hash.Length);
                digest.DoFinal(hash, 0);

                int length = System.Math.Min(hash.Length, keyStream.Length - index);
                Array.Copy(hash, 0, keyStream, index, length);
                index += length;
            }

            return keyStream;
        }

        public X509Certificate[] GetCertificateChain(string alias)
        {
            if (m_keyEntries.TryGetValue(alias, out var keyEntry))
                return CloneChain(keyEntry.chain);

            return null;
        }

        public X509Certificate GetCertificate(string alias)
        {
            if (m_certificateEntries.TryGetValue(alias, out var certEntry))
                return certEntry.cert;

            if (m_keyEntries.TryGetValue(alias, out var keyEntry))
                return keyEntry.chain?[0];

            return null;
        }

        public DateTime? GetCreationDate(string alias)
        {
            if (m_certificateEntries.TryGetValue(alias, out var certEntry))
                return certEntry.date;

            if (m_keyEntries.TryGetValue(alias, out var keyEntry))
                return keyEntry.date;

            return null;
        }

        /// <exception cref="IOException"/>
        public void SetKeyEntry(string alias, AsymmetricKeyParameter key, char[] password, X509Certificate[] chain)
        {
            alias = ConvertAlias(alias);

            if (ContainsAlias(alias))
                throw new IOException("alias [" + alias + "] already in use");

            byte[] pkcs8Key = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key).GetEncoded();
            byte[] protectedKey = new byte[pkcs8Key.Length + 40];

            SecureRandom rnd = CryptoServicesRegistrar.GetSecureRandom();
            rnd.NextBytes(protectedKey, 0, 20);

            IDigest digest = DigestUtilities.GetDigest("SHA-1");

            byte[] checksum = GetKeyChecksum(digest, password, pkcs8Key);
            Array.Copy(checksum, 0, protectedKey, 20 + pkcs8Key.Length, 20);

            byte[] keyStream = CalculateKeyStream(digest, password, protectedKey, pkcs8Key.Length);
            for (int i = 0; i != keyStream.Length; i++)
            {
                protectedKey[20 + i] = (byte)(pkcs8Key[i] ^ keyStream[i]);
            }
            Array.Clear(keyStream, 0, keyStream.Length);

            try
            {
                var epki = new EncryptedPrivateKeyInfo(JksObfuscationAlg, protectedKey);
                m_keyEntries.Add(alias, new JksKeyEntry(DateTime.UtcNow, epki.GetEncoded(), CloneChain(chain)));
            }
            catch (Exception e)
            {
                throw new IOException("unable to encode encrypted private key", e);
            }
        }

        /// <exception cref="IOException"/>
        public void SetKeyEntry(string alias, byte[] key, X509Certificate[] chain)
        {
            alias = ConvertAlias(alias);

            if (ContainsAlias(alias))
                throw new IOException("alias [" + alias + "] already in use");

            m_keyEntries.Add(alias, new JksKeyEntry(DateTime.UtcNow, key, CloneChain(chain)));
        }

        /// <exception cref="IOException"/>
        public void SetCertificateEntry(string alias, X509Certificate cert)
        {
            alias = ConvertAlias(alias);

            if (ContainsAlias(alias))
                throw new IOException("alias [" + alias + "] already in use");

            m_certificateEntries.Add(alias, new JksTrustedCertEntry(DateTime.UtcNow, cert));
        }

        public void DeleteEntry(string alias)
        {
            if (!m_keyEntries.Remove(alias))
            {
                m_certificateEntries.Remove(alias);
            }
        }

        public IEnumerable<string> Aliases
        {
            get
            {
                var aliases = new HashSet<string>(m_certificateEntries.Keys);
                aliases.UnionWith(m_keyEntries.Keys);
                return CollectionUtilities.Proxy(aliases);
            }
        }

        public bool ContainsAlias(string alias)
        {
            return IsCertificateEntry(alias) || IsKeyEntry(alias);
        }

        public int Count
        {
            get { return m_certificateEntries.Count + m_keyEntries.Count; }
        }

        public bool IsKeyEntry(string alias)
        {
            return m_keyEntries.ContainsKey(alias);
        }

        public bool IsCertificateEntry(string alias)
        {
            return m_certificateEntries.ContainsKey(alias);
        }

        public string GetCertificateAlias(X509Certificate cert)
        {
            foreach (var entry in m_certificateEntries)
            {
                if (entry.Value.cert.Equals(cert))
                    return entry.Key;
            }
            return null;
        }

        /// <exception cref="IOException"/>
        public void Save(Stream stream, char[] password)
        {
            if (stream == null)
                throw new ArgumentNullException(nameof(stream));
            if (password == null)
                throw new ArgumentNullException(nameof(password));

            IDigest checksumDigest = CreateChecksumDigest(password);
            BinaryWriter bw = new BinaryWriter(new DigestStream(stream, null, checksumDigest));

            BinaryWriters.WriteInt32BigEndian(bw, Magic);
            BinaryWriters.WriteInt32BigEndian(bw, 2);

            BinaryWriters.WriteInt32BigEndian(bw, Count);

            foreach (var entry in m_keyEntries)
            {
                string alias = entry.Key;
                JksKeyEntry keyEntry = entry.Value;

                BinaryWriters.WriteInt32BigEndian(bw, 1);
                WriteUtf(bw, alias);
                WriteDateTime(bw, keyEntry.date);
                WriteBufferWithInt32Length(bw, keyEntry.keyData.GetEncoded());

                X509Certificate[] chain = keyEntry.chain;
                int chainLength = chain == null ? 0 : chain.Length;
                BinaryWriters.WriteInt32BigEndian(bw, chainLength);
                for (int i = 0; i < chainLength; ++i)
                {
                    WriteTypedCertificate(bw, chain[i]);
                }
            }

            foreach (var entry in m_certificateEntries) 
            {
                string alias = entry.Key;
                JksTrustedCertEntry certEntry = entry.Value;

                BinaryWriters.WriteInt32BigEndian(bw, 2);
                WriteUtf(bw, alias);
                WriteDateTime(bw, certEntry.date);
                WriteTypedCertificate(bw, certEntry.cert);
            }

            byte[] checksum = DigestUtilities.DoFinal(checksumDigest);
            bw.Write(checksum);
            bw.Flush();
        }

        /// <exception cref="IOException"/>
        public void Load(Stream stream, char[] password)
        {
            if (stream == null)
                throw new ArgumentNullException(nameof(stream));

            m_certificateEntries.Clear();
            m_keyEntries.Clear();

            using (var storeStream = ValidateStream(stream, password))
            {
                BinaryReader br = new BinaryReader(storeStream);

                int magic = BinaryReaders.ReadInt32BigEndian(br);
                int storeVersion = BinaryReaders.ReadInt32BigEndian(br);

                if (!(magic == Magic && (storeVersion == 1 || storeVersion == 2)))
                    throw new IOException("Invalid keystore format");

                int numEntries = BinaryReaders.ReadInt32BigEndian(br);

                for (int t = 0; t < numEntries; t++)
                {
                    int tag = BinaryReaders.ReadInt32BigEndian(br);

                    switch (tag)
                    {
                    case 1: // keys
                    {
                        string alias = ReadUtf(br);
                        DateTime date = ReadDateTime(br);

                        // encrypted key data
                        byte[] keyData = ReadBufferWithInt32Length(br);

                        // certificate chain
                        int chainLength = BinaryReaders.ReadInt32BigEndian(br);
                        X509Certificate[] chain = null;
                        if (chainLength > 0)
                        {
                            var certs = new List<X509Certificate>(System.Math.Min(10, chainLength));
                            for (int certNo = 0; certNo != chainLength; certNo++)
                            {
                                certs.Add(ReadTypedCertificate(br, storeVersion));
                            }
                            chain = certs.ToArray();
                        }
                        m_keyEntries.Add(alias, new JksKeyEntry(date, keyData, chain));
                        break;
                    }
                    case 2: // certificate
                    {
                        string alias = ReadUtf(br);
                        DateTime date = ReadDateTime(br);

                        X509Certificate cert = ReadTypedCertificate(br, storeVersion);

                        m_certificateEntries.Add(alias, new JksTrustedCertEntry(date, cert));
                        break;
                    }
                    default:
                        throw new IOException("unable to discern entry type");
                    }
                }

                if (storeStream.Position != storeStream.Length)
                    throw new IOException("password incorrect or store tampered with");
            }
        }

        /*
         * Validate password takes the checksum of the store and will either.
         * 1. If password is null, load the store into memory, return the result.
         * 2. If password is not null, load the store into memory, test the checksum, and if successful return
         * a new input stream instance of the store.
         * 3. Fail if there is a password and an invalid checksum.
         *
         * @param inputStream The input stream.
         * @param password    the password.
         * @return Either the passed in input stream or a new input stream.
         */
        /// <exception cref="IOException"/>
        private ErasableByteStream ValidateStream(Stream inputStream, char[] password)
        {
            byte[] rawStore = Streams.ReadAll(inputStream);
            int checksumPos = rawStore.Length - 20;

            if (password != null)
            {
                byte[] checksum = CalculateChecksum(password, rawStore, 0, checksumPos);

                if (!Arrays.FixedTimeEquals(20, checksum, 0, rawStore, checksumPos))
                {
                    Array.Clear(rawStore, 0, rawStore.Length);
                    throw new IOException("password incorrect or store tampered with");
                }
            }

            return new ErasableByteStream(rawStore, 0, checksumPos);
        }

        private static void AddPassword(IDigest digest, char[] password)
        {
            // Encoding.BigEndianUnicode
            for (int i = 0; i < password.Length; ++i)
            {
                digest.Update((byte)(password[i] >> 8));
                digest.Update((byte)password[i]);
            }
        }

        private static byte[] CalculateChecksum(char[] password, byte[] buffer, int offset, int length)
        {
            IDigest checksumDigest = CreateChecksumDigest(password);
            checksumDigest.BlockUpdate(buffer, offset, length);
            return DigestUtilities.DoFinal(checksumDigest);
        }

        private static X509Certificate[] CloneChain(X509Certificate[] chain)
        {
            return (X509Certificate[])chain?.Clone();
        }

        private static string ConvertAlias(string alias)
        {
            return alias.ToLowerInvariant();
        }

        private static IDigest CreateChecksumDigest(char[] password)
        {
            IDigest digest = DigestUtilities.GetDigest("SHA-1");
            AddPassword(digest, password);

            //
            // This "Mighty Aphrodite" string goes all the way back to the
            // first java betas in the mid 90's, why who knows? But see
            // https://cryptosense.com/mighty-aphrodite-dark-secrets-of-the-java-keystore/
            //
            byte[] prefix = Encoding.UTF8.GetBytes("Mighty Aphrodite");
            digest.BlockUpdate(prefix, 0, prefix.Length);
            return digest;
        }

        private static byte[] ReadBufferWithInt16Length(BinaryReader br)
        {
            int length = BinaryReaders.ReadInt16BigEndian(br);
            return BinaryReaders.ReadBytesFully(br, length);
        }

        private static byte[] ReadBufferWithInt32Length(BinaryReader br)
        {
            int length = BinaryReaders.ReadInt32BigEndian(br);
            return BinaryReaders.ReadBytesFully(br, length);
        }

        private static DateTime ReadDateTime(BinaryReader br)
        {
            long unixMS = BinaryReaders.ReadInt64BigEndian(br);
            return DateTimeUtilities.UnixMsToDateTime(unixMS);
        }

        private static X509Certificate ReadTypedCertificate(BinaryReader br, int storeVersion)
        {
            if (storeVersion == 2)
            {
                string certFormat = ReadUtf(br);
                if ("X.509" != certFormat)
                    throw new IOException("Unsupported certificate format: " + certFormat);
            }

            byte[] certData = ReadBufferWithInt32Length(br);
            try
            {
                return new X509Certificate(certData);
            }
            finally
            {
                Array.Clear(certData, 0, certData.Length);
            }
        }

        private static string ReadUtf(BinaryReader br)
        {
            byte[] utfBytes = ReadBufferWithInt16Length(br);

            /*
             * FIXME JKS actually uses a "modified UTF-8" format. For the moment we will just support single-byte
             * encodings that aren't null bytes.
             */
            for (int i = 0; i < utfBytes.Length; ++i)
            {
                byte utfByte = utfBytes[i];
                if (utfByte == 0 || (utfByte & 0x80) != 0)
                    throw new NotSupportedException("Currently missing support for modified UTF-8 encoding in JKS");
            }

            return Encoding.UTF8.GetString(utfBytes);
        }

        private static void WriteBufferWithInt16Length(BinaryWriter bw, byte[] buffer)
        {
            BinaryWriters.WriteInt16BigEndian(bw, Convert.ToInt16(buffer.Length));
            bw.Write(buffer);
        }

        private static void WriteBufferWithInt32Length(BinaryWriter bw, byte[] buffer)
        {
            BinaryWriters.WriteInt32BigEndian(bw, buffer.Length);
            bw.Write(buffer);
        }

        private static void WriteDateTime(BinaryWriter bw, DateTime dateTime)
        {
            long unixMS = DateTimeUtilities.DateTimeToUnixMs(dateTime);
            BinaryWriters.WriteInt64BigEndian(bw, unixMS);
        }

        private static void WriteTypedCertificate(BinaryWriter bw, X509Certificate cert)
        {
            WriteUtf(bw, "X.509");
            WriteBufferWithInt32Length(bw, cert.GetEncoded());
        }

        private static void WriteUtf(BinaryWriter bw, string s)
        {
            byte[] utfBytes = Encoding.UTF8.GetBytes(s);

            /*
             * FIXME JKS actually uses a "modified UTF-8" format. For the moment we will just support single-byte
             * encodings that aren't null bytes.
             */
            for (int i = 0; i < utfBytes.Length; ++i)
            {
                byte utfByte = utfBytes[i];
                if (utfByte == 0 || (utfByte & 0x80) != 0)
                    throw new NotSupportedException("Currently missing support for modified UTF-8 encoding in JKS");
            }

            WriteBufferWithInt16Length(bw, utfBytes);
        }

        /**
         * JksTrustedCertEntry is a internal container for the certificate entry.
         */
        private sealed class JksTrustedCertEntry
        {
            internal readonly DateTime date;
            internal readonly X509Certificate cert;

            internal JksTrustedCertEntry(DateTime date, X509Certificate cert)
            {
                this.date = date;
                this.cert = cert;
            }
        }

        private sealed class JksKeyEntry
        {
            internal readonly DateTime date;
            internal readonly EncryptedPrivateKeyInfo keyData;
            internal readonly X509Certificate[] chain;

            internal JksKeyEntry(DateTime date, byte[] keyData, X509Certificate[] chain)
            {
                this.date = date;
                this.keyData = EncryptedPrivateKeyInfo.GetInstance(Asn1Sequence.GetInstance(keyData));
                this.chain = chain;
            }
        }

        private sealed class ErasableByteStream
            : MemoryStream
        {
            internal ErasableByteStream(byte[] buffer, int index, int count)
                : base(buffer, index, count, false, true)
            {
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    Position = 0L;

                    byte[] rawStore = GetBuffer();
                    Array.Clear(rawStore, 0, rawStore.Length);
                }
                base.Dispose(disposing);
            }
        }
    }
}