DerivedKeySecurityToken.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Security.Tokens
  5. {
  6. using System.Collections;
  7. using System.ServiceModel;
  8. using System.Collections.Generic;
  9. using System.Collections.ObjectModel;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.IdentityModel.Claims;
  13. using System.IdentityModel.Policy;
  14. using System.IdentityModel.Tokens;
  15. using System.IdentityModel.Selectors;
  16. using System.Security.Cryptography;
  17. using System.Text;
  18. using System.Xml;
  19. sealed class DerivedKeySecurityToken : SecurityToken
  20. {
  21. // public const string DefaultLabel = "WS-SecureConversationWS-SecureConversation";
  22. static readonly byte[] DefaultLabel = new byte[]
  23. {
  24. (byte)'W', (byte)'S', (byte)'-', (byte)'S', (byte)'e', (byte)'c', (byte)'u', (byte)'r', (byte)'e',
  25. (byte)'C', (byte)'o', (byte)'n', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'a', (byte)'t', (byte)'i', (byte)'o', (byte)'n',
  26. (byte)'W', (byte)'S', (byte)'-', (byte)'S', (byte)'e', (byte)'c', (byte)'u', (byte)'r', (byte)'e',
  27. (byte)'C', (byte)'o', (byte)'n', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'a', (byte)'t', (byte)'i', (byte)'o', (byte)'n'
  28. };
  29. public const int DefaultNonceLength = 16;
  30. public const int DefaultDerivedKeyLength = 32;
  31. string id;
  32. byte[] key;
  33. string keyDerivationAlgorithm;
  34. string label;
  35. int length = -1;
  36. byte[] nonce;
  37. // either offset or generation must be specified.
  38. int offset = -1;
  39. int generation = -1;
  40. SecurityToken tokenToDerive;
  41. SecurityKeyIdentifierClause tokenToDeriveIdentifier;
  42. ReadOnlyCollection<SecurityKey> securityKeys;
  43. // create from scratch
  44. public DerivedKeySecurityToken(SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier, int length)
  45. : this(tokenToDerive, tokenToDeriveIdentifier, length, SecurityUtils.GenerateId())
  46. {
  47. }
  48. internal DerivedKeySecurityToken(SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier,
  49. int length, string id)
  50. {
  51. if (length != 16 && length != 24 && length != 32)
  52. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.Psha1KeyLengthInvalid, length * 8)));
  53. byte[] nonce = new byte[DefaultNonceLength];
  54. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
  55. rng.GetBytes(nonce);
  56. Initialize(id, -1, 0, length, null, nonce, tokenToDerive, tokenToDeriveIdentifier, SecurityAlgorithms.Psha1KeyDerivation);
  57. }
  58. internal DerivedKeySecurityToken(int generation, int offset, int length,
  59. string label, int minNonceLength, SecurityToken tokenToDerive,
  60. SecurityKeyIdentifierClause tokenToDeriveIdentifier,
  61. string derivationAlgorithm, string id)
  62. {
  63. byte[] nonce = new byte[minNonceLength];
  64. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
  65. rng.GetBytes(nonce);
  66. Initialize(id, generation, offset, length, label, nonce, tokenToDerive, tokenToDeriveIdentifier, derivationAlgorithm);
  67. }
  68. // create from xml
  69. internal DerivedKeySecurityToken(int generation, int offset, int length,
  70. string label, byte[] nonce, SecurityToken tokenToDerive,
  71. SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm, string id)
  72. {
  73. Initialize(id, generation, offset, length, label, nonce, tokenToDerive, tokenToDeriveIdentifier, derivationAlgorithm, false);
  74. }
  75. public override string Id
  76. {
  77. get { return this.id; }
  78. }
  79. public override DateTime ValidFrom
  80. {
  81. get { return this.tokenToDerive.ValidFrom; }
  82. }
  83. public override DateTime ValidTo
  84. {
  85. get { return this.tokenToDerive.ValidTo; }
  86. }
  87. public string KeyDerivationAlgorithm
  88. {
  89. get { return keyDerivationAlgorithm; }
  90. }
  91. public int Generation
  92. {
  93. get { return this.generation; }
  94. }
  95. public string Label
  96. {
  97. get { return this.label; }
  98. }
  99. public int Length
  100. {
  101. get { return this.length; }
  102. }
  103. internal byte[] Nonce
  104. {
  105. get { return this.nonce; }
  106. }
  107. public int Offset
  108. {
  109. get { return this.offset; }
  110. }
  111. internal SecurityToken TokenToDerive
  112. {
  113. get { return this.tokenToDerive; }
  114. }
  115. internal SecurityKeyIdentifierClause TokenToDeriveIdentifier
  116. {
  117. get { return this.tokenToDeriveIdentifier; }
  118. }
  119. public override ReadOnlyCollection<SecurityKey> SecurityKeys
  120. {
  121. get
  122. {
  123. if (this.securityKeys == null)
  124. {
  125. #pragma warning suppress 56503
  126. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.DerivedKeyNotInitialized)));
  127. }
  128. return this.securityKeys;
  129. }
  130. }
  131. public byte[] GetKeyBytes()
  132. {
  133. return SecurityUtils.CloneBuffer(this.key);
  134. }
  135. public byte[] GetNonce()
  136. {
  137. return SecurityUtils.CloneBuffer(this.nonce);
  138. }
  139. internal bool TryGetSecurityKeys(out ReadOnlyCollection<SecurityKey> keys)
  140. {
  141. keys = this.securityKeys;
  142. return (keys != null);
  143. }
  144. public override string ToString()
  145. {
  146. StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
  147. writer.WriteLine("DerivedKeySecurityToken:");
  148. writer.WriteLine(" Generation: {0}", this.Generation);
  149. writer.WriteLine(" Offset: {0}", this.Offset);
  150. writer.WriteLine(" Length: {0}", this.Length);
  151. writer.WriteLine(" Label: {0}", this.Label);
  152. writer.WriteLine(" Nonce: {0}", Convert.ToBase64String(this.Nonce));
  153. writer.WriteLine(" TokenToDeriveFrom:");
  154. using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
  155. {
  156. xmlWriter.Formatting = Formatting.Indented;
  157. SecurityStandardsManager.DefaultInstance.SecurityTokenSerializer.WriteKeyIdentifierClause(XmlDictionaryWriter.CreateDictionaryWriter(xmlWriter), this.TokenToDeriveIdentifier);
  158. }
  159. return writer.ToString();
  160. }
  161. void Initialize(string id, int generation, int offset, int length, string label, byte[] nonce,
  162. SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm)
  163. {
  164. Initialize(id, generation, offset, length, label, nonce, tokenToDerive, tokenToDeriveIdentifier, derivationAlgorithm, true);
  165. }
  166. void Initialize(string id, int generation, int offset, int length, string label, byte[] nonce,
  167. SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm,
  168. bool initializeDerivedKey)
  169. {
  170. if (id == null)
  171. {
  172. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("id");
  173. }
  174. if (tokenToDerive == null)
  175. {
  176. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenToDerive");
  177. }
  178. if (tokenToDeriveIdentifier == null)
  179. {
  180. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokentoDeriveIdentifier");
  181. }
  182. if (!SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, tokenToDerive))
  183. {
  184. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.DerivedKeyCannotDeriveFromSecret)));
  185. }
  186. if (nonce == null)
  187. {
  188. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("nonce");
  189. }
  190. if (length == -1)
  191. {
  192. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("length"));
  193. }
  194. if (offset == -1 && generation == -1)
  195. {
  196. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.DerivedKeyPosAndGenNotSpecified));
  197. }
  198. if (offset >= 0 && generation >= 0)
  199. {
  200. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.DerivedKeyPosAndGenBothSpecified));
  201. }
  202. this.id = id;
  203. this.label = label;
  204. this.nonce = nonce;
  205. this.length = length;
  206. this.offset = offset;
  207. this.generation = generation;
  208. this.tokenToDerive = tokenToDerive;
  209. this.tokenToDeriveIdentifier = tokenToDeriveIdentifier;
  210. this.keyDerivationAlgorithm = derivationAlgorithm;
  211. if (initializeDerivedKey)
  212. {
  213. InitializeDerivedKey(this.length);
  214. }
  215. }
  216. internal void InitializeDerivedKey(int maxKeyLength)
  217. {
  218. if (this.key != null)
  219. {
  220. return;
  221. }
  222. if (this.length > maxKeyLength)
  223. {
  224. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.DerivedKeyLengthTooLong, this.length, maxKeyLength));
  225. }
  226. this.key = SecurityUtils.GenerateDerivedKey(this.tokenToDerive, this.keyDerivationAlgorithm,
  227. (this.label != null ? Encoding.UTF8.GetBytes(this.label) : DefaultLabel), this.nonce, this.length * 8,
  228. ((this.offset >= 0) ? this.offset : this.generation * this.length));
  229. if ((this.key == null) || (this.key.Length == 0))
  230. {
  231. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.DerivedKeyCannotDeriveFromSecret));
  232. }
  233. List<SecurityKey> temp = new List<SecurityKey>(1);
  234. temp.Add(new InMemorySymmetricSecurityKey(this.key, false));
  235. this.securityKeys = temp.AsReadOnly();
  236. }
  237. internal void InitializeDerivedKey(ReadOnlyCollection<SecurityKey> securityKeys)
  238. {
  239. this.key = ((SymmetricSecurityKey)securityKeys[0]).GetSymmetricKey();
  240. this.securityKeys = securityKeys;
  241. }
  242. internal static void EnsureAcceptableOffset(int offset, int generation, int length, int maxOffset)
  243. {
  244. if (offset != -1)
  245. {
  246. if (offset > maxOffset)
  247. {
  248. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.DerivedKeyTokenOffsetTooHigh, offset, maxOffset)));
  249. }
  250. }
  251. else
  252. {
  253. int effectiveOffset = generation * length;
  254. if ((effectiveOffset < generation && effectiveOffset < length) || effectiveOffset > maxOffset)
  255. {
  256. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.DerivedKeyTokenGenerationAndLengthTooHigh, generation, length, maxOffset)));
  257. }
  258. }
  259. }
  260. }
  261. }