TlsSrpKeyExchange.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.IO;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Srp;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
  10. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  11. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  12. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
  13. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
  14. {
  15. /// <summary>(D)TLS SRP key exchange (RFC 5054).</summary>
  16. public class TlsSrpKeyExchange
  17. : AbstractTlsKeyExchange
  18. {
  19. protected static TlsSigner CreateSigner(int keyExchange)
  20. {
  21. switch (keyExchange)
  22. {
  23. case KeyExchangeAlgorithm.SRP:
  24. return null;
  25. case KeyExchangeAlgorithm.SRP_RSA:
  26. return new TlsRsaSigner();
  27. case KeyExchangeAlgorithm.SRP_DSS:
  28. return new TlsDssSigner();
  29. default:
  30. throw new ArgumentException("unsupported key exchange algorithm");
  31. }
  32. }
  33. protected TlsSigner mTlsSigner;
  34. protected TlsSrpGroupVerifier mGroupVerifier;
  35. protected byte[] mIdentity;
  36. protected byte[] mPassword;
  37. protected AsymmetricKeyParameter mServerPublicKey = null;
  38. protected Srp6GroupParameters mSrpGroup = null;
  39. protected Srp6Client mSrpClient = null;
  40. protected Srp6Server mSrpServer = null;
  41. protected BigInteger mSrpPeerCredentials = null;
  42. protected BigInteger mSrpVerifier = null;
  43. protected byte[] mSrpSalt = null;
  44. protected TlsSignerCredentials mServerCredentials = null;
  45. [Obsolete("Use constructor taking an explicit 'groupVerifier' argument")]
  46. public TlsSrpKeyExchange(int keyExchange, IList supportedSignatureAlgorithms, byte[] identity, byte[] password)
  47. : this(keyExchange, supportedSignatureAlgorithms, new DefaultTlsSrpGroupVerifier(), identity, password)
  48. {
  49. }
  50. public TlsSrpKeyExchange(int keyExchange, IList supportedSignatureAlgorithms, TlsSrpGroupVerifier groupVerifier,
  51. byte[] identity, byte[] password)
  52. : base(keyExchange, supportedSignatureAlgorithms)
  53. {
  54. this.mTlsSigner = CreateSigner(keyExchange);
  55. this.mGroupVerifier = groupVerifier;
  56. this.mIdentity = identity;
  57. this.mPassword = password;
  58. this.mSrpClient = new Srp6Client();
  59. }
  60. public TlsSrpKeyExchange(int keyExchange, IList supportedSignatureAlgorithms, byte[] identity,
  61. TlsSrpLoginParameters loginParameters)
  62. : base(keyExchange, supportedSignatureAlgorithms)
  63. {
  64. this.mTlsSigner = CreateSigner(keyExchange);
  65. this.mIdentity = identity;
  66. this.mSrpServer = new Srp6Server();
  67. this.mSrpGroup = loginParameters.Group;
  68. this.mSrpVerifier = loginParameters.Verifier;
  69. this.mSrpSalt = loginParameters.Salt;
  70. }
  71. public override void Init(TlsContext context)
  72. {
  73. base.Init(context);
  74. if (this.mTlsSigner != null)
  75. {
  76. this.mTlsSigner.Init(context);
  77. }
  78. }
  79. public override void SkipServerCredentials()
  80. {
  81. if (mTlsSigner != null)
  82. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  83. }
  84. public override void ProcessServerCertificate(Certificate serverCertificate)
  85. {
  86. if (mTlsSigner == null)
  87. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  88. if (serverCertificate.IsEmpty)
  89. throw new TlsFatalAlert(AlertDescription.bad_certificate);
  90. X509CertificateStructure x509Cert = serverCertificate.GetCertificateAt(0);
  91. SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;
  92. try
  93. {
  94. this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
  95. }
  96. catch (Exception e)
  97. {
  98. throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
  99. }
  100. if (!mTlsSigner.IsValidPublicKey(this.mServerPublicKey))
  101. throw new TlsFatalAlert(AlertDescription.certificate_unknown);
  102. TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);
  103. base.ProcessServerCertificate(serverCertificate);
  104. }
  105. public override void ProcessServerCredentials(TlsCredentials serverCredentials)
  106. {
  107. if ((mKeyExchange == KeyExchangeAlgorithm.SRP) || !(serverCredentials is TlsSignerCredentials))
  108. throw new TlsFatalAlert(AlertDescription.internal_error);
  109. ProcessServerCertificate(serverCredentials.Certificate);
  110. this.mServerCredentials = (TlsSignerCredentials)serverCredentials;
  111. }
  112. public override bool RequiresServerKeyExchange
  113. {
  114. get { return true; }
  115. }
  116. public override byte[] GenerateServerKeyExchange()
  117. {
  118. mSrpServer.Init(mSrpGroup, mSrpVerifier, TlsUtilities.CreateHash(HashAlgorithm.sha1), mContext.SecureRandom);
  119. BigInteger B = mSrpServer.GenerateServerCredentials();
  120. ServerSrpParams srpParams = new ServerSrpParams(mSrpGroup.N, mSrpGroup.G, mSrpSalt, B);
  121. DigestInputBuffer buf = new DigestInputBuffer();
  122. srpParams.Encode(buf);
  123. if (mServerCredentials != null)
  124. {
  125. /*
  126. * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
  127. */
  128. SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(
  129. mContext, mServerCredentials);
  130. IDigest d = TlsUtilities.CreateHash(signatureAndHashAlgorithm);
  131. SecurityParameters securityParameters = mContext.SecurityParameters;
  132. d.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length);
  133. d.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length);
  134. buf.UpdateDigest(d);
  135. byte[] hash = new byte[d.GetDigestSize()];
  136. d.DoFinal(hash, 0);
  137. byte[] signature = mServerCredentials.GenerateCertificateSignature(hash);
  138. DigitallySigned signed_params = new DigitallySigned(signatureAndHashAlgorithm, signature);
  139. signed_params.Encode(buf);
  140. }
  141. return buf.ToArray();
  142. }
  143. public override void ProcessServerKeyExchange(Stream input)
  144. {
  145. SecurityParameters securityParameters = mContext.SecurityParameters;
  146. SignerInputBuffer buf = null;
  147. Stream teeIn = input;
  148. if (mTlsSigner != null)
  149. {
  150. buf = new SignerInputBuffer();
  151. teeIn = new TeeInputStream(input, buf);
  152. }
  153. ServerSrpParams srpParams = ServerSrpParams.Parse(teeIn);
  154. if (buf != null)
  155. {
  156. DigitallySigned signed_params = ParseSignature(input);
  157. ISigner signer = InitVerifyer(mTlsSigner, signed_params.Algorithm, securityParameters);
  158. buf.UpdateSigner(signer);
  159. if (!signer.VerifySignature(signed_params.Signature))
  160. throw new TlsFatalAlert(AlertDescription.decrypt_error);
  161. }
  162. this.mSrpGroup = new Srp6GroupParameters(srpParams.N, srpParams.G);
  163. if (!mGroupVerifier.Accept(mSrpGroup))
  164. throw new TlsFatalAlert(AlertDescription.insufficient_security);
  165. this.mSrpSalt = srpParams.S;
  166. /*
  167. * RFC 5054 2.5.3: The client MUST abort the handshake with an "illegal_parameter" alert if
  168. * B % N = 0.
  169. */
  170. try
  171. {
  172. this.mSrpPeerCredentials = Srp6Utilities.ValidatePublicValue(mSrpGroup.N, srpParams.B);
  173. }
  174. catch (CryptoException e)
  175. {
  176. throw new TlsFatalAlert(AlertDescription.illegal_parameter, e);
  177. }
  178. this.mSrpClient.Init(mSrpGroup, TlsUtilities.CreateHash(HashAlgorithm.sha1), mContext.SecureRandom);
  179. }
  180. public override void ValidateCertificateRequest(CertificateRequest certificateRequest)
  181. {
  182. throw new TlsFatalAlert(AlertDescription.unexpected_message);
  183. }
  184. public override void ProcessClientCredentials(TlsCredentials clientCredentials)
  185. {
  186. throw new TlsFatalAlert(AlertDescription.internal_error);
  187. }
  188. public override void GenerateClientKeyExchange(Stream output)
  189. {
  190. BigInteger A = mSrpClient.GenerateClientCredentials(mSrpSalt, mIdentity, mPassword);
  191. TlsSrpUtilities.WriteSrpParameter(A, output);
  192. mContext.SecurityParameters.srpIdentity = Arrays.Clone(mIdentity);
  193. }
  194. public override void ProcessClientKeyExchange(Stream input)
  195. {
  196. /*
  197. * RFC 5054 2.5.4: The server MUST abort the handshake with an "illegal_parameter" alert if
  198. * A % N = 0.
  199. */
  200. try
  201. {
  202. this.mSrpPeerCredentials = Srp6Utilities.ValidatePublicValue(mSrpGroup.N, TlsSrpUtilities.ReadSrpParameter(input));
  203. }
  204. catch (CryptoException e)
  205. {
  206. throw new TlsFatalAlert(AlertDescription.illegal_parameter, e);
  207. }
  208. mContext.SecurityParameters.srpIdentity = Arrays.Clone(mIdentity);
  209. }
  210. public override byte[] GeneratePremasterSecret()
  211. {
  212. try
  213. {
  214. BigInteger S = mSrpServer != null
  215. ? mSrpServer.CalculateSecret(mSrpPeerCredentials)
  216. : mSrpClient.CalculateSecret(mSrpPeerCredentials);
  217. // TODO Check if this needs to be a fixed size
  218. return BigIntegers.AsUnsignedByteArray(S);
  219. }
  220. catch (CryptoException e)
  221. {
  222. throw new TlsFatalAlert(AlertDescription.illegal_parameter, e);
  223. }
  224. }
  225. protected virtual ISigner InitVerifyer(TlsSigner tlsSigner, SignatureAndHashAlgorithm algorithm,
  226. SecurityParameters securityParameters)
  227. {
  228. ISigner signer = tlsSigner.CreateVerifyer(algorithm, this.mServerPublicKey);
  229. signer.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length);
  230. signer.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length);
  231. return signer;
  232. }
  233. }
  234. }
  235. #pragma warning restore
  236. #endif