WindowsIdentity.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. //
  2. // System.Security.Principal.WindowsIdentity
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. // Sebastien Pouliot ([email protected])
  7. //
  8. // (C) 2002 Ximian, Inc (http://www.ximian.com)
  9. // Portions (C) 2003 Motus Technologies Inc. (http://www.motus.com)
  10. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System.Runtime.CompilerServices;
  32. using System.Runtime.InteropServices;
  33. using System.Runtime.Serialization;
  34. using System.Security.Permissions;
  35. namespace System.Security.Principal {
  36. [Serializable]
  37. #if NET_1_0
  38. public class WindowsIdentity : IIdentity, IDeserializationCallback {
  39. #elif NET_2_0
  40. [ComVisible (true)]
  41. public class WindowsIdentity : IIdentity, IDeserializationCallback, ISerializable, IDisposable {
  42. #else
  43. public class WindowsIdentity : IIdentity, IDeserializationCallback, ISerializable {
  44. #endif
  45. private IntPtr _token;
  46. private string _type;
  47. private WindowsAccountType _account;
  48. private bool _authenticated;
  49. private string _name;
  50. private SerializationInfo _info;
  51. static private IntPtr invalidWindows = IntPtr.Zero;
  52. // that seems to be the value used for (at least) AIX and MacOSX
  53. static private IntPtr invalidPosix = (IntPtr) unchecked (-2);
  54. [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
  55. public WindowsIdentity (IntPtr userToken)
  56. : this (userToken, null, WindowsAccountType.Normal, false)
  57. {
  58. }
  59. [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
  60. public WindowsIdentity (IntPtr userToken, string type)
  61. : this (userToken, type, WindowsAccountType.Normal, false)
  62. {
  63. }
  64. [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
  65. public WindowsIdentity (IntPtr userToken, string type, WindowsAccountType acctType)
  66. : this (userToken, type, acctType, false)
  67. {
  68. }
  69. [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
  70. public WindowsIdentity (IntPtr userToken, string type, WindowsAccountType acctType, bool isAuthenticated)
  71. {
  72. _type = type;
  73. _account = acctType;
  74. _authenticated = isAuthenticated;
  75. _name = null;
  76. // last - as it can override some fields
  77. SetToken (userToken);
  78. }
  79. #if !NET_1_0
  80. [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
  81. public WindowsIdentity (string sUserPrincipalName)
  82. : this (sUserPrincipalName, null)
  83. {
  84. }
  85. [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
  86. public WindowsIdentity (string sUserPrincipalName, string type)
  87. {
  88. if (sUserPrincipalName == null)
  89. throw new NullReferenceException ("sUserPrincipalName");
  90. // TODO: Windows 2003 compatibility should be done in runtime
  91. IntPtr token = GetUserToken (sUserPrincipalName);
  92. if ((!IsPosix) && (token == IntPtr.Zero)) {
  93. throw new ArgumentException ("only for Windows Server 2003 +");
  94. }
  95. _authenticated = true;
  96. _account = WindowsAccountType.Normal;
  97. _type = type;
  98. // last - as it can override some fields
  99. SetToken (token);
  100. }
  101. [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
  102. public WindowsIdentity (SerializationInfo info, StreamingContext context)
  103. {
  104. _info = info;
  105. }
  106. #endif
  107. #if NET_2_0
  108. [ComVisible (false)]
  109. public void Dispose ()
  110. {
  111. _token = IntPtr.Zero;
  112. }
  113. [ComVisible (false)]
  114. protected virtual void Dispose (bool disposing)
  115. {
  116. _token = IntPtr.Zero;
  117. }
  118. #else
  119. ~WindowsIdentity ()
  120. {
  121. // clear our copy but don't close it
  122. // http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
  123. _token = IntPtr.Zero;
  124. }
  125. #endif
  126. // static methods
  127. public static WindowsIdentity GetAnonymous ()
  128. {
  129. WindowsIdentity id = null;
  130. if (IsPosix) {
  131. id = new WindowsIdentity ("nobody");
  132. // special case
  133. id._account = WindowsAccountType.Anonymous;
  134. id._authenticated = false;
  135. id._type = String.Empty;
  136. }
  137. else {
  138. id = new WindowsIdentity (IntPtr.Zero, String.Empty, WindowsAccountType.Anonymous, false);
  139. // special case (don't try to resolve the name)
  140. id._name = String.Empty;
  141. }
  142. return id;
  143. }
  144. public static WindowsIdentity GetCurrent ()
  145. {
  146. return new WindowsIdentity (GetCurrentToken (), null, WindowsAccountType.Normal, true);
  147. }
  148. #if NET_2_0
  149. [MonoTODO ("need icall changes")]
  150. public static WindowsIdentity GetCurrent (bool ifImpersonating)
  151. {
  152. throw new NotImplementedException ();
  153. }
  154. [MonoTODO ("need icall changes")]
  155. public static WindowsIdentity GetCurrent (TokenAccessLevels desiredAccess)
  156. {
  157. throw new NotImplementedException ();
  158. }
  159. #endif
  160. // methods
  161. public virtual WindowsImpersonationContext Impersonate ()
  162. {
  163. return new WindowsImpersonationContext (_token);
  164. }
  165. [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
  166. public static WindowsImpersonationContext Impersonate (IntPtr userToken)
  167. {
  168. return new WindowsImpersonationContext (userToken);
  169. }
  170. // properties
  171. #if NET_2_0
  172. public string AuthenticationType {
  173. #else
  174. public virtual string AuthenticationType {
  175. #endif
  176. get { return _type; }
  177. }
  178. public virtual bool IsAnonymous
  179. {
  180. get { return (_account == WindowsAccountType.Anonymous); }
  181. }
  182. public virtual bool IsAuthenticated
  183. {
  184. get { return _authenticated; }
  185. }
  186. public virtual bool IsGuest
  187. {
  188. get { return (_account == WindowsAccountType.Guest); }
  189. }
  190. public virtual bool IsSystem
  191. {
  192. get { return (_account == WindowsAccountType.System); }
  193. }
  194. public virtual string Name
  195. {
  196. get {
  197. if (_name == null) {
  198. // revolve name (runtime)
  199. _name = GetTokenName (_token);
  200. }
  201. return _name;
  202. }
  203. }
  204. public virtual IntPtr Token
  205. {
  206. get { return _token; }
  207. }
  208. #if NET_2_0
  209. [MonoTODO ("not implemented")]
  210. public IdentityReferenceCollection Groups {
  211. get { throw new NotImplementedException (); }
  212. }
  213. [MonoTODO ("not implemented")]
  214. [ComVisible (false)]
  215. public TokenImpersonationLevel ImpersonationLevel {
  216. get { throw new NotImplementedException (); }
  217. }
  218. [MonoTODO ("not implemented")]
  219. [ComVisible (false)]
  220. public SecurityIdentifier Owner {
  221. get { throw new NotImplementedException (); }
  222. }
  223. [MonoTODO ("not implemented")]
  224. [ComVisible (false)]
  225. public SecurityIdentifier User {
  226. get { throw new NotImplementedException (); }
  227. }
  228. #endif
  229. void IDeserializationCallback.OnDeserialization (object sender)
  230. {
  231. _token = (IntPtr) _info.GetValue ("m_userToken", typeof (IntPtr));
  232. // can't trust this alone - we must validate the token
  233. _name = _info.GetString ("m_name");
  234. if (_name != null) {
  235. // validate token by comparing names
  236. string name = GetTokenName (_token);
  237. if (name != _name)
  238. throw new SerializationException ("Token-Name mismatch.");
  239. }
  240. else {
  241. // validate token by getting name
  242. _name = GetTokenName (_token);
  243. if ((_name == String.Empty) || (_name == null))
  244. throw new SerializationException ("Token doesn't match a user.");
  245. }
  246. _type = _info.GetString ("m_type");
  247. _account = (WindowsAccountType) _info.GetValue ("m_acctType", typeof (WindowsAccountType));
  248. _authenticated = _info.GetBoolean ("m_isAuthenticated");
  249. }
  250. #if !NET_1_0
  251. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  252. {
  253. info.AddValue ("m_userToken", _token);
  254. // can be null when not resolved
  255. info.AddValue ("m_name", _name);
  256. info.AddValue ("m_type", _type);
  257. info.AddValue ("m_acctType", _account);
  258. info.AddValue ("m_isAuthenticated", _authenticated);
  259. }
  260. #endif
  261. private static bool IsPosix {
  262. get { return ((int) Environment.Platform == 128); }
  263. }
  264. private void SetToken (IntPtr token)
  265. {
  266. if (IsPosix) {
  267. if (token == invalidPosix)
  268. throw new ArgumentException ("Invalid token");
  269. _token = token;
  270. // apply defaults
  271. if (_type == null)
  272. _type = "POSIX";
  273. // override user choice in this specific case
  274. if (_token == IntPtr.Zero)
  275. _account = WindowsAccountType.System;
  276. }
  277. else {
  278. if ((token == invalidWindows) && (_account != WindowsAccountType.Anonymous))
  279. throw new ArgumentException ("Invalid token");
  280. _token = token;
  281. // apply defaults
  282. if (_type == null)
  283. _type = "NTLM";
  284. }
  285. }
  286. // see mono/mono/metadata/security.c for implementation
  287. // Many people use reflection to get a user's roles - so many
  288. // that's it's hard to say it's an "undocumented" feature -
  289. // so we also implement it in Mono :-/
  290. // http://www.dotnet247.com/247reference/msgs/39/195403.aspx
  291. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  292. internal extern static string[] _GetRoles (IntPtr token);
  293. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  294. internal extern static IntPtr GetCurrentToken ();
  295. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  296. private extern static string GetTokenName (IntPtr token);
  297. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  298. private extern static IntPtr GetUserToken (string username);
  299. }
  300. }