New test.
[mono.git] / mcs / class / corlib / System.Security.Principal / WindowsIdentity.cs
1 //
2 // System.Security.Principal.WindowsIdentity
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //      Sebastien Pouliot (sebastien@ximian.com)
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
32 using System.Runtime.CompilerServices;
33 using System.Runtime.InteropServices;
34 using System.Runtime.Serialization;
35 using System.Security.Permissions;
36
37 namespace System.Security.Principal {
38
39         [Serializable]
40 #if NET_1_0
41         public class WindowsIdentity : IIdentity, IDeserializationCallback {
42 #elif NET_2_0
43         [ComVisible (true)]
44         public class WindowsIdentity : IIdentity, IDeserializationCallback, ISerializable, IDisposable {
45 #else
46         public class WindowsIdentity : IIdentity, IDeserializationCallback, ISerializable {
47 #endif
48                 private IntPtr _token;
49                 private string _type;
50                 private WindowsAccountType _account;
51                 private bool _authenticated;
52                 private string _name;
53                 private SerializationInfo _info;
54
55                 static private IntPtr invalidWindows = IntPtr.Zero;
56
57                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
58                 public WindowsIdentity (IntPtr userToken) 
59                         : this (userToken, null, WindowsAccountType.Normal, false)
60                 {
61                 }
62
63                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
64                 public WindowsIdentity (IntPtr userToken, string type) 
65                         : this (userToken, type, WindowsAccountType.Normal, false)
66                 {
67                 }
68
69                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
70                 public WindowsIdentity (IntPtr userToken, string type, WindowsAccountType acctType)
71                         : this (userToken, type, acctType, false)
72                 {
73                 }
74
75                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
76                 public WindowsIdentity (IntPtr userToken, string type, WindowsAccountType acctType, bool isAuthenticated)
77                 {
78                         _type = type;
79                         _account = acctType;
80                         _authenticated = isAuthenticated;
81                         _name = null;
82                         // last - as it can override some fields
83                         SetToken (userToken);
84                 }
85 #if !NET_1_0
86                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
87                 public WindowsIdentity (string sUserPrincipalName) 
88                         : this (sUserPrincipalName, null)
89                 {
90                 }
91
92                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
93                 public WindowsIdentity (string sUserPrincipalName, string type)
94                 {
95                         if (sUserPrincipalName == null)
96                                 throw new NullReferenceException ("sUserPrincipalName");
97
98                         // TODO: Windows 2003 compatibility should be done in runtime
99                         IntPtr token = GetUserToken (sUserPrincipalName);
100                         if ((!IsPosix) && (token == IntPtr.Zero)) {
101                                 throw new ArgumentException ("only for Windows Server 2003 +");
102                         }
103
104                         _authenticated = true;
105                         _account = WindowsAccountType.Normal;
106                         _type = type;
107                         // last - as it can override some fields
108                         SetToken (token);
109                 }
110
111                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
112                 public WindowsIdentity (SerializationInfo info, StreamingContext context)
113                 {
114                         _info = info;
115                 }
116 #endif
117
118 #if NET_2_0
119                 [ComVisible (false)]
120                 public void Dispose ()
121                 {
122                         _token = IntPtr.Zero;
123                 }
124                 
125                 [ComVisible (false)]
126                 protected virtual void Dispose (bool disposing)
127                 {
128                         _token = IntPtr.Zero;
129                 }
130 #else
131                 ~WindowsIdentity ()
132                 {
133                         // clear our copy but don't close it
134                         // http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
135                         _token = IntPtr.Zero;
136                 }
137 #endif
138                 // static methods
139
140                 public static WindowsIdentity GetAnonymous ()
141                 {
142                         WindowsIdentity id = null;
143                         if (IsPosix) {
144                                 id = new WindowsIdentity ("nobody");
145                                 // special case
146                                 id._account = WindowsAccountType.Anonymous;
147                                 id._authenticated = false;
148                                 id._type = String.Empty;
149                         }
150                         else {
151                                 id = new WindowsIdentity (IntPtr.Zero, String.Empty, WindowsAccountType.Anonymous, false);
152                                 // special case (don't try to resolve the name)
153                                 id._name = String.Empty;
154                         }
155                         return id;
156                 }
157
158                 public static WindowsIdentity GetCurrent ()
159                 {
160                         return new WindowsIdentity (GetCurrentToken (), null, WindowsAccountType.Normal, true);
161                 }
162 #if NET_2_0
163                 [MonoTODO ("need icall changes")]
164                 public static WindowsIdentity GetCurrent (bool ifImpersonating)
165                 {
166                         throw new NotImplementedException ();
167                 }
168
169                 [MonoTODO ("need icall changes")]
170                 public static WindowsIdentity GetCurrent (TokenAccessLevels desiredAccess)
171                 {
172                         throw new NotImplementedException ();
173                 }
174 #endif
175                 // methods
176
177                 public virtual WindowsImpersonationContext Impersonate ()
178                 {
179                         return new WindowsImpersonationContext (_token);
180                 }
181
182                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
183                 public static WindowsImpersonationContext Impersonate (IntPtr userToken)
184                 {
185                         return new WindowsImpersonationContext (userToken);
186                 }
187
188                 // properties
189
190 #if NET_2_0
191                 public string AuthenticationType {
192 #else
193                 public virtual string AuthenticationType {
194 #endif
195                         get { return _type; }
196                 }
197
198                 public virtual bool IsAnonymous
199                 {
200                         get { return (_account == WindowsAccountType.Anonymous); }
201                 }
202
203                 public virtual bool IsAuthenticated
204                 {
205                         get { return _authenticated; }
206                 }
207
208                 public virtual bool IsGuest
209                 {
210                         get { return (_account == WindowsAccountType.Guest); }
211                 }
212
213                 public virtual bool IsSystem
214                 {
215                         get { return (_account == WindowsAccountType.System); }
216                 }
217
218                 public virtual string Name
219                 {
220                         get {
221                                 if (_name == null) {
222                                         // revolve name (runtime)
223                                         _name = GetTokenName (_token);
224                                 }
225                                 return _name; 
226                         }
227                 }
228
229                 public virtual IntPtr Token
230                 {
231                         get { return _token; }
232                 }
233 #if NET_2_0
234                 [MonoTODO ("not implemented")]
235                 public IdentityReferenceCollection Groups {
236                         get { throw new NotImplementedException (); }
237                 }
238
239                 [MonoTODO ("not implemented")]
240                 [ComVisible (false)]
241                 public TokenImpersonationLevel ImpersonationLevel {
242                         get { throw new NotImplementedException (); }
243                 }
244
245                 [MonoTODO ("not implemented")]
246                 [ComVisible (false)]
247                 public SecurityIdentifier Owner {
248                         get { throw new NotImplementedException (); }
249                 }
250
251                 [MonoTODO ("not implemented")]
252                 [ComVisible (false)]
253                 public SecurityIdentifier User {
254                         get { throw new NotImplementedException (); }
255                 }
256 #endif
257                 void IDeserializationCallback.OnDeserialization (object sender)
258                 {
259                         _token = (IntPtr) _info.GetValue ("m_userToken", typeof (IntPtr));
260                         // can't trust this alone - we must validate the token
261                         _name = _info.GetString ("m_name");
262                         if (_name != null) {
263                                 // validate token by comparing names
264                                 string name = GetTokenName (_token);
265                                 if (name != _name)
266                                         throw new SerializationException ("Token-Name mismatch.");
267                         }
268                         else {
269                                 // validate token by getting name
270                                 _name = GetTokenName (_token);
271                                 if ((_name == String.Empty) || (_name == null))
272                                         throw new SerializationException ("Token doesn't match a user.");
273                         }
274                         _type = _info.GetString ("m_type");
275                         _account = (WindowsAccountType) _info.GetValue ("m_acctType", typeof (WindowsAccountType));
276                         _authenticated = _info.GetBoolean ("m_isAuthenticated");
277                 }
278 #if !NET_1_0
279                 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) 
280                 {
281                         info.AddValue ("m_userToken", _token);
282                         // can be null when not resolved
283                         info.AddValue ("m_name", _name);
284                         info.AddValue ("m_type", _type);
285                         info.AddValue ("m_acctType", _account);
286                         info.AddValue ("m_isAuthenticated", _authenticated);
287                 }
288 #endif
289                 private static bool IsPosix {
290                         get { return ((int) Environment.Platform == 128) || ((int)Environment.Platform == 4); }
291                 }
292
293                 private void SetToken (IntPtr token) 
294                 {
295                         if (IsPosix) {
296
297                                 _token = token;
298                                 // apply defaults
299                                 if (_type == null)
300                                         _type = "POSIX";
301                                 // override user choice in this specific case
302                                 if (_token == IntPtr.Zero)
303                                         _account = WindowsAccountType.System;
304                         }
305                         else {
306                                 if ((token == invalidWindows) && (_account != WindowsAccountType.Anonymous))
307                                         throw new ArgumentException ("Invalid token");
308
309                                 _token = token;
310                                 // apply defaults
311                                 if (_type == null)
312                                         _type = "NTLM";
313                         }
314                 }
315
316                 // see mono/mono/metadata/security.c for implementation
317
318                 // Many people use reflection to get a user's roles - so many 
319                 // that's it's hard to say it's an "undocumented" feature -
320                 // so we also implement it in Mono :-/
321                 // http://www.dotnet247.com/247reference/msgs/39/195403.aspx
322                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
323                 internal extern static string[] _GetRoles (IntPtr token);
324
325                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
326                 internal extern static IntPtr GetCurrentToken ();
327
328                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
329                 private extern static string GetTokenName (IntPtr token);
330
331                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
332                 private extern static IntPtr GetUserToken (string username);
333         }
334 }