summary refs log tree commit diff
path: root/crypto/src/crypto/tls/TlsSrpKeyExchange.cs
blob: 09fa72348ecc3789da7f5710bc20a137dc3133d9 (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
using System;
using System.Collections;
using System.IO;

using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Agreement.Srp;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.IO;

namespace Org.BouncyCastle.Crypto.Tls
{
    /// <summary>(D)TLS SRP key exchange (RFC 5054).</summary>
    public class TlsSrpKeyExchange
        :   AbstractTlsKeyExchange
    {
        protected static TlsSigner CreateSigner(int keyExchange)
        {
            switch (keyExchange)
            {
                case KeyExchangeAlgorithm.SRP:
                    return null;
                case KeyExchangeAlgorithm.SRP_RSA:
                    return new TlsRsaSigner();
                case KeyExchangeAlgorithm.SRP_DSS:
                    return new TlsDssSigner();
                default:
                    throw new ArgumentException("unsupported key exchange algorithm");
            }
        }

        protected TlsSigner mTlsSigner;
        protected TlsSrpGroupVerifier mGroupVerifier;
        protected byte[] mIdentity;
        protected byte[] mPassword;

        protected AsymmetricKeyParameter mServerPublicKey = null;

        protected Srp6GroupParameters mSrpGroup = null;
        protected Srp6Client mSrpClient = null;
        protected Srp6Server mSrpServer = null;
        protected BigInteger mSrpPeerCredentials = null;
        protected BigInteger mSrpVerifier = null;
        protected byte[] mSrpSalt = null;

        protected TlsSignerCredentials mServerCredentials = null;

        [Obsolete("Use constructor taking an explicit 'groupVerifier' argument")]
        public TlsSrpKeyExchange(int keyExchange, IList supportedSignatureAlgorithms, byte[] identity, byte[] password)
            :   this(keyExchange, supportedSignatureAlgorithms, new DefaultTlsSrpGroupVerifier(), identity, password)
        {
        }

        public TlsSrpKeyExchange(int keyExchange, IList supportedSignatureAlgorithms, TlsSrpGroupVerifier groupVerifier,
            byte[] identity, byte[] password)
            :   base(keyExchange, supportedSignatureAlgorithms)
        {
            this.mTlsSigner = CreateSigner(keyExchange);
            this.mGroupVerifier = groupVerifier;
            this.mIdentity = identity;
            this.mPassword = password;
            this.mSrpClient = new Srp6Client();
        }

        public TlsSrpKeyExchange(int keyExchange, IList supportedSignatureAlgorithms, byte[] identity,
            TlsSrpLoginParameters loginParameters)
            :   base(keyExchange, supportedSignatureAlgorithms)
        {
            this.mTlsSigner = CreateSigner(keyExchange);
            this.mIdentity = identity;
            this.mSrpServer = new Srp6Server();
            this.mSrpGroup = loginParameters.Group;
            this.mSrpVerifier = loginParameters.Verifier;
            this.mSrpSalt = loginParameters.Salt;
        }

        public override void Init(TlsContext context)
        {
            base.Init(context);

            if (this.mTlsSigner != null)
            {
                this.mTlsSigner.Init(context);
            }
        }

        public override void SkipServerCredentials()
        {
            if (mTlsSigner != null)
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
        }

        public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (mTlsSigner == null)
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            if (serverCertificate.IsEmpty)
                throw new TlsFatalAlert(AlertDescription.bad_certificate);

            X509CertificateStructure x509Cert = serverCertificate.GetCertificateAt(0);

            SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;
            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
            }

            if (!mTlsSigner.IsValidPublicKey(this.mServerPublicKey))
                throw new TlsFatalAlert(AlertDescription.certificate_unknown);

            TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);

            base.ProcessServerCertificate(serverCertificate);
        }

        public override void ProcessServerCredentials(TlsCredentials serverCredentials)
        {
            if ((mKeyExchange == KeyExchangeAlgorithm.SRP) || !(serverCredentials is TlsSignerCredentials))
                throw new TlsFatalAlert(AlertDescription.internal_error);

            ProcessServerCertificate(serverCredentials.Certificate);

            this.mServerCredentials = (TlsSignerCredentials)serverCredentials;
        }

        public override bool RequiresServerKeyExchange
        {
            get { return true; }
        }

        public override byte[] GenerateServerKeyExchange()
        {
            mSrpServer.Init(mSrpGroup, mSrpVerifier, TlsUtilities.CreateHash(HashAlgorithm.sha1), mContext.SecureRandom);
            BigInteger B = mSrpServer.GenerateServerCredentials();

            ServerSrpParams srpParams = new ServerSrpParams(mSrpGroup.N, mSrpGroup.G, mSrpSalt, B);

            DigestInputBuffer buf = new DigestInputBuffer();

            srpParams.Encode(buf);

            if (mServerCredentials != null)
            {
                /*
                 * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
                 */
                SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(
                    mContext, mServerCredentials);

                IDigest d = TlsUtilities.CreateHash(signatureAndHashAlgorithm);

                SecurityParameters securityParameters = mContext.SecurityParameters;
                d.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length);
                d.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length);
                buf.UpdateDigest(d);

                byte[] hash = new byte[d.GetDigestSize()];
                d.DoFinal(hash, 0);

                byte[] signature = mServerCredentials.GenerateCertificateSignature(hash);

                DigitallySigned signed_params = new DigitallySigned(signatureAndHashAlgorithm, signature);
                signed_params.Encode(buf);
            }

            return buf.ToArray();
        }

        public override void ProcessServerKeyExchange(Stream input)
        {
            SecurityParameters securityParameters = mContext.SecurityParameters;

            SignerInputBuffer buf = null;
            Stream teeIn = input;

            if (mTlsSigner != null)
            {
                buf = new SignerInputBuffer();
                teeIn = new TeeInputStream(input, buf);
            }

            ServerSrpParams srpParams = ServerSrpParams.Parse(teeIn);

            if (buf != null)
            {
                DigitallySigned signed_params = ParseSignature(input);

                ISigner signer = InitVerifyer(mTlsSigner, signed_params.Algorithm, securityParameters);
                buf.UpdateSigner(signer);
                if (!signer.VerifySignature(signed_params.Signature))
                    throw new TlsFatalAlert(AlertDescription.decrypt_error);
            }

            this.mSrpGroup = new Srp6GroupParameters(srpParams.N, srpParams.G);

            if (!mGroupVerifier.Accept(mSrpGroup))
                throw new TlsFatalAlert(AlertDescription.insufficient_security);

            this.mSrpSalt = srpParams.S;

            /*
             * RFC 5054 2.5.3: The client MUST abort the handshake with an "illegal_parameter" alert if
             * B % N = 0.
             */
            try
            {
                this.mSrpPeerCredentials = Srp6Utilities.ValidatePublicValue(mSrpGroup.N, srpParams.B);
            }
            catch (CryptoException e)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter, e);
            }

            this.mSrpClient.Init(mSrpGroup, TlsUtilities.CreateHash(HashAlgorithm.sha1), mContext.SecureRandom);
        }

        public override void ValidateCertificateRequest(CertificateRequest certificateRequest)
        {
            throw new TlsFatalAlert(AlertDescription.unexpected_message);
        }

        public override void ProcessClientCredentials(TlsCredentials clientCredentials)
        {
            throw new TlsFatalAlert(AlertDescription.internal_error);
        }

        public override void GenerateClientKeyExchange(Stream output)
        {
            BigInteger A = mSrpClient.GenerateClientCredentials(mSrpSalt, mIdentity, mPassword);
            TlsSrpUtilities.WriteSrpParameter(A, output);

            mContext.SecurityParameters.srpIdentity = Arrays.Clone(mIdentity);
        }

        public override void ProcessClientKeyExchange(Stream input)
        {
            /*
             * RFC 5054 2.5.4: The server MUST abort the handshake with an "illegal_parameter" alert if
             * A % N = 0.
             */
            try
            {
                this.mSrpPeerCredentials = Srp6Utilities.ValidatePublicValue(mSrpGroup.N, TlsSrpUtilities.ReadSrpParameter(input));
            }
            catch (CryptoException e)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter, e);
            }

            mContext.SecurityParameters.srpIdentity = Arrays.Clone(mIdentity);
        }

        public override byte[] GeneratePremasterSecret()
        {
            try
            {
                BigInteger S = mSrpServer != null
                    ?   mSrpServer.CalculateSecret(mSrpPeerCredentials)
                    :   mSrpClient.CalculateSecret(mSrpPeerCredentials);

                // TODO Check if this needs to be a fixed size
                return BigIntegers.AsUnsignedByteArray(S);
            }
            catch (CryptoException e)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter, e);
            }
        }

        protected virtual ISigner InitVerifyer(TlsSigner tlsSigner, SignatureAndHashAlgorithm algorithm,
            SecurityParameters securityParameters)
        {
            ISigner signer = tlsSigner.CreateVerifyer(algorithm, this.mServerPublicKey);
            signer.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length);
            signer.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length);
            return signer;
        }
    }
}