Context.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. // Transport Security Layer (TLS)
  2. // Copyright (c) 2003-2004 Carlos Guzman Alvarez
  3. // Copyright (C) 2006 Novell, Inc (http://www.novell.com)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining
  6. // a copy of this software and associated documentation files (the
  7. // "Software"), to deal in the Software without restriction, including
  8. // without limitation the rights to use, copy, modify, merge, publish,
  9. // distribute, sublicense, and/or sell copies of the Software, and to
  10. // permit persons to whom the Software is furnished to do so, subject to
  11. // the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. //
  24. using System;
  25. using System.Text;
  26. using System.Collections;
  27. using System.Security.Cryptography;
  28. using System.Security.Cryptography.X509Certificates;
  29. using Mono.Security.Cryptography;
  30. using Mono.Security.Protocol.Tls.Handshake;
  31. namespace Mono.Security.Protocol.Tls
  32. {
  33. internal abstract class Context
  34. {
  35. #region Internal Constants
  36. internal const short MAX_FRAGMENT_SIZE = 16384; // 2^14
  37. internal const short TLS1_PROTOCOL_CODE = (0x03 << 8) | 0x01;
  38. internal const short SSL3_PROTOCOL_CODE = (0x03 << 8) | 0x00;
  39. internal const long UNIX_BASE_TICKS = 621355968000000000;
  40. #endregion
  41. #region Fields
  42. // Protocol version
  43. private SecurityProtocolType securityProtocol;
  44. // Sesison ID
  45. private byte[] sessionId;
  46. // Compression method
  47. private SecurityCompressionType compressionMethod;
  48. // Information sent and request by the server in the Handshake protocol
  49. private TlsServerSettings serverSettings;
  50. // Client configuration
  51. private TlsClientSettings clientSettings;
  52. // Cipher suite information
  53. private SecurityParameters current;
  54. private SecurityParameters negotiating;
  55. private SecurityParameters read;
  56. private SecurityParameters write;
  57. private CipherSuiteCollection supportedCiphers;
  58. // Last handshake message received
  59. private HandshakeType lastHandshakeMsg;
  60. // Handshake negotiation state
  61. private HandshakeState handshakeState;
  62. // Misc
  63. private bool abbreviatedHandshake;
  64. private bool receivedConnectionEnd;
  65. private bool sentConnectionEnd;
  66. private bool protocolNegotiated;
  67. // Sequence numbers
  68. private ulong writeSequenceNumber;
  69. private ulong readSequenceNumber;
  70. // Random data
  71. private byte[] clientRandom;
  72. private byte[] serverRandom;
  73. private byte[] randomCS;
  74. private byte[] randomSC;
  75. // Key information
  76. private byte[] masterSecret;
  77. private byte[] clientWriteKey;
  78. private byte[] serverWriteKey;
  79. private byte[] clientWriteIV;
  80. private byte[] serverWriteIV;
  81. // Handshake hashes
  82. private TlsStream handshakeMessages;
  83. // Secure Random generator
  84. private RandomNumberGenerator random;
  85. // Record protocol
  86. private RecordProtocol recordProtocol;
  87. #endregion
  88. #region Properties
  89. public bool AbbreviatedHandshake
  90. {
  91. get { return abbreviatedHandshake; }
  92. set { abbreviatedHandshake = value; }
  93. }
  94. public bool ProtocolNegotiated
  95. {
  96. get { return this.protocolNegotiated; }
  97. set { this.protocolNegotiated = value; }
  98. }
  99. public SecurityProtocolType SecurityProtocol
  100. {
  101. get
  102. {
  103. if ((this.securityProtocol & SecurityProtocolType.Tls) == SecurityProtocolType.Tls ||
  104. (this.securityProtocol & SecurityProtocolType.Default) == SecurityProtocolType.Default)
  105. {
  106. return SecurityProtocolType.Tls;
  107. }
  108. else
  109. {
  110. if ((this.securityProtocol & SecurityProtocolType.Ssl3) == SecurityProtocolType.Ssl3)
  111. {
  112. return SecurityProtocolType.Ssl3;
  113. }
  114. }
  115. throw new NotSupportedException("Unsupported security protocol type");
  116. }
  117. set { this.securityProtocol = value; }
  118. }
  119. public SecurityProtocolType SecurityProtocolFlags
  120. {
  121. get { return this.securityProtocol; }
  122. }
  123. public short Protocol
  124. {
  125. get
  126. {
  127. switch (this.SecurityProtocol)
  128. {
  129. case SecurityProtocolType.Tls:
  130. case SecurityProtocolType.Default:
  131. return Context.TLS1_PROTOCOL_CODE;
  132. case SecurityProtocolType.Ssl3:
  133. return Context.SSL3_PROTOCOL_CODE;
  134. case SecurityProtocolType.Ssl2:
  135. default:
  136. throw new NotSupportedException("Unsupported security protocol type");
  137. }
  138. }
  139. }
  140. public byte[] SessionId
  141. {
  142. get { return this.sessionId; }
  143. set { this.sessionId = value; }
  144. }
  145. public SecurityCompressionType CompressionMethod
  146. {
  147. get { return this.compressionMethod; }
  148. set { this.compressionMethod = value; }
  149. }
  150. public TlsServerSettings ServerSettings
  151. {
  152. get { return this.serverSettings; }
  153. }
  154. public TlsClientSettings ClientSettings
  155. {
  156. get { return this.clientSettings; }
  157. }
  158. public HandshakeType LastHandshakeMsg
  159. {
  160. get { return this.lastHandshakeMsg; }
  161. set { this.lastHandshakeMsg = value; }
  162. }
  163. public HandshakeState HandshakeState
  164. {
  165. get { return this.handshakeState; }
  166. set { this.handshakeState = value; }
  167. }
  168. public bool ReceivedConnectionEnd
  169. {
  170. get { return this.receivedConnectionEnd; }
  171. set { this.receivedConnectionEnd = value; }
  172. }
  173. public bool SentConnectionEnd
  174. {
  175. get { return this.sentConnectionEnd; }
  176. set { this.sentConnectionEnd = value; }
  177. }
  178. public CipherSuiteCollection SupportedCiphers
  179. {
  180. get { return supportedCiphers; }
  181. set { supportedCiphers = value; }
  182. }
  183. public TlsStream HandshakeMessages
  184. {
  185. get { return this.handshakeMessages; }
  186. }
  187. public ulong WriteSequenceNumber
  188. {
  189. get { return this.writeSequenceNumber; }
  190. set { this.writeSequenceNumber = value; }
  191. }
  192. public ulong ReadSequenceNumber
  193. {
  194. get { return this.readSequenceNumber; }
  195. set { this.readSequenceNumber = value; }
  196. }
  197. public byte[] ClientRandom
  198. {
  199. get { return this.clientRandom; }
  200. set { this.clientRandom = value; }
  201. }
  202. public byte[] ServerRandom
  203. {
  204. get { return this.serverRandom; }
  205. set { this.serverRandom = value; }
  206. }
  207. public byte[] RandomCS
  208. {
  209. get { return this.randomCS; }
  210. set { this.randomCS = value; }
  211. }
  212. public byte[] RandomSC
  213. {
  214. get { return this.randomSC; }
  215. set { this.randomSC = value; }
  216. }
  217. public byte[] MasterSecret
  218. {
  219. get { return this.masterSecret; }
  220. set { this.masterSecret = value; }
  221. }
  222. public byte[] ClientWriteKey
  223. {
  224. get { return this.clientWriteKey; }
  225. set { this.clientWriteKey = value; }
  226. }
  227. public byte[] ServerWriteKey
  228. {
  229. get { return this.serverWriteKey; }
  230. set { this.serverWriteKey = value; }
  231. }
  232. public byte[] ClientWriteIV
  233. {
  234. get { return this.clientWriteIV; }
  235. set { this.clientWriteIV = value; }
  236. }
  237. public byte[] ServerWriteIV
  238. {
  239. get { return this.serverWriteIV; }
  240. set { this.serverWriteIV = value; }
  241. }
  242. public RecordProtocol RecordProtocol
  243. {
  244. get { return this.recordProtocol; }
  245. set { this.recordProtocol = value; }
  246. }
  247. #endregion
  248. #region Constructors
  249. public Context(SecurityProtocolType securityProtocolType)
  250. {
  251. this.SecurityProtocol = securityProtocolType;
  252. this.compressionMethod = SecurityCompressionType.None;
  253. this.serverSettings = new TlsServerSettings();
  254. this.clientSettings = new TlsClientSettings();
  255. this.handshakeMessages = new TlsStream();
  256. this.sessionId = null;
  257. this.handshakeState = HandshakeState.None;
  258. this.random = RandomNumberGenerator.Create();
  259. }
  260. #endregion
  261. #region Methods
  262. public int GetUnixTime()
  263. {
  264. DateTime now = DateTime.UtcNow;
  265. return (int)((now.Ticks - UNIX_BASE_TICKS) / TimeSpan.TicksPerSecond);
  266. }
  267. public byte[] GetSecureRandomBytes(int count)
  268. {
  269. byte[] secureBytes = new byte[count];
  270. this.random.GetNonZeroBytes(secureBytes);
  271. return secureBytes;
  272. }
  273. public virtual void Clear()
  274. {
  275. this.compressionMethod = SecurityCompressionType.None;
  276. this.serverSettings = new TlsServerSettings();
  277. this.clientSettings = new TlsClientSettings();
  278. this.handshakeMessages = new TlsStream();
  279. this.sessionId = null;
  280. this.handshakeState = HandshakeState.None;
  281. this.ClearKeyInfo();
  282. }
  283. public virtual void ClearKeyInfo()
  284. {
  285. // Clear Master Secret
  286. if (masterSecret != null) {
  287. Array.Clear (masterSecret, 0, masterSecret.Length);
  288. masterSecret = null;
  289. }
  290. // Clear client and server random
  291. if (clientRandom != null) {
  292. Array.Clear (clientRandom, 0, clientRandom.Length);
  293. clientRandom = null;
  294. }
  295. if (serverRandom != null) {
  296. Array.Clear (serverRandom, 0, serverRandom.Length);
  297. serverRandom = null;
  298. }
  299. if (randomCS != null) {
  300. Array.Clear (randomCS, 0, randomCS.Length);
  301. randomCS = null;
  302. }
  303. if (randomSC != null) {
  304. Array.Clear (randomSC, 0, randomSC.Length);
  305. randomSC = null;
  306. }
  307. // Clear client keys
  308. if (clientWriteKey != null) {
  309. Array.Clear (clientWriteKey, 0, clientWriteKey.Length);
  310. clientWriteKey = null;
  311. }
  312. if (clientWriteIV != null) {
  313. Array.Clear (clientWriteIV, 0, clientWriteIV.Length);
  314. clientWriteIV = null;
  315. }
  316. // Clear server keys
  317. if (serverWriteKey != null) {
  318. Array.Clear (serverWriteKey, 0, serverWriteKey.Length);
  319. serverWriteKey = null;
  320. }
  321. if (serverWriteIV != null) {
  322. Array.Clear (serverWriteIV, 0, serverWriteIV.Length);
  323. serverWriteIV = null;
  324. }
  325. // Reset handshake messages
  326. this.handshakeMessages.Reset();
  327. // Clear MAC keys if protocol is different than Ssl3
  328. // SSLv3 needs them inside Mono.Security.Protocol.Tls.SslCipherSuite.Compute[Client|Server]RecordMAC
  329. if (this.securityProtocol != SecurityProtocolType.Ssl3)
  330. {
  331. // this.clientWriteMAC = null;
  332. // this.serverWriteMAC = null;
  333. }
  334. }
  335. public SecurityProtocolType DecodeProtocolCode(short code)
  336. {
  337. switch (code)
  338. {
  339. case Context.TLS1_PROTOCOL_CODE:
  340. return SecurityProtocolType.Tls;
  341. case Context.SSL3_PROTOCOL_CODE:
  342. return SecurityProtocolType.Ssl3;
  343. default:
  344. throw new NotSupportedException("Unsupported security protocol type");
  345. }
  346. }
  347. public void ChangeProtocol(short protocol)
  348. {
  349. SecurityProtocolType protocolType = this.DecodeProtocolCode(protocol);
  350. if ((protocolType & this.SecurityProtocolFlags) == protocolType ||
  351. (this.SecurityProtocolFlags & SecurityProtocolType.Default) == SecurityProtocolType.Default)
  352. {
  353. this.SecurityProtocol = protocolType;
  354. this.SupportedCiphers.Clear();
  355. this.SupportedCiphers = null;
  356. this.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(protocolType);
  357. }
  358. else
  359. {
  360. throw new TlsException(AlertDescription.ProtocolVersion, "Incorrect protocol version received from server");
  361. }
  362. }
  363. public SecurityParameters Current
  364. {
  365. get
  366. {
  367. if (current == null)
  368. current = new SecurityParameters ();
  369. if (current.Cipher != null)
  370. current.Cipher.Context = this;
  371. return current;
  372. }
  373. }
  374. public SecurityParameters Negotiating
  375. {
  376. get
  377. {
  378. if (negotiating == null)
  379. negotiating = new SecurityParameters ();
  380. if (negotiating.Cipher != null)
  381. negotiating.Cipher.Context = this;
  382. return negotiating;
  383. }
  384. }
  385. public SecurityParameters Read
  386. {
  387. get { return read; }
  388. }
  389. public SecurityParameters Write
  390. {
  391. get { return write; }
  392. }
  393. public void StartSwitchingSecurityParameters (bool client)
  394. {
  395. if (client) {
  396. // everything we write from now on is encrypted
  397. write = negotiating;
  398. // but we still read with the older cipher until we
  399. // receive the ChangeCipherSpec message
  400. read = current;
  401. } else {
  402. // everything we read from now on is encrypted
  403. read = negotiating;
  404. // but we still write with the older cipher until we
  405. // receive the ChangeCipherSpec message
  406. write = current;
  407. }
  408. current = negotiating;
  409. }
  410. public void EndSwitchingSecurityParameters (bool client)
  411. {
  412. SecurityParameters temp;
  413. if (client) {
  414. temp = read;
  415. // we now read with the new, negotiated, security parameters
  416. read = current;
  417. } else {
  418. temp = write;
  419. // we now write with the new, negotiated, security parameters
  420. write = current;
  421. }
  422. // so we clear the old one (last reference)
  423. if (temp != null)
  424. temp.Clear ();
  425. negotiating = temp;
  426. // and are now ready for a future renegotiation
  427. }
  428. #endregion
  429. }
  430. }