Merge pull request #799 from kebby/master
[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         [ComVisible (true)]
41         public class WindowsIdentity : IIdentity, IDeserializationCallback, ISerializable, IDisposable {
42                 private IntPtr _token;
43                 private string _type;
44                 private WindowsAccountType _account;
45                 private bool _authenticated;
46                 private string _name;
47                 private SerializationInfo _info;
48
49                 static private IntPtr invalidWindows = IntPtr.Zero;
50
51                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
52                 public WindowsIdentity (IntPtr userToken) 
53                         : this (userToken, null, WindowsAccountType.Normal, false)
54                 {
55                 }
56
57                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
58                 public WindowsIdentity (IntPtr userToken, string type) 
59                         : this (userToken, type, WindowsAccountType.Normal, false)
60                 {
61                 }
62
63                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
64                 public WindowsIdentity (IntPtr userToken, string type, WindowsAccountType acctType)
65                         : this (userToken, type, acctType, false)
66                 {
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
80                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
81                 public WindowsIdentity (string sUserPrincipalName) 
82                         : this (sUserPrincipalName, null)
83                 {
84                 }
85
86                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
87                 public WindowsIdentity (string sUserPrincipalName, string type)
88                 {
89                         if (sUserPrincipalName == null)
90                                 throw new NullReferenceException ("sUserPrincipalName");
91
92                         // TODO: Windows 2003 compatibility should be done in runtime
93                         IntPtr token = GetUserToken (sUserPrincipalName);
94                         if ((!Environment.IsUnix) && (token == IntPtr.Zero)) {
95                                 throw new ArgumentException ("only for Windows Server 2003 +");
96                         }
97
98                         _authenticated = true;
99                         _account = WindowsAccountType.Normal;
100                         _type = type;
101                         // last - as it can override some fields
102                         SetToken (token);
103                 }
104
105                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
106                 public WindowsIdentity (SerializationInfo info, StreamingContext context)
107                 {
108                         _info = info;
109                 }
110
111                 [ComVisible (false)]
112                 public void Dispose ()
113                 {
114                         _token = IntPtr.Zero;
115                 }
116                 
117                 [ComVisible (false)]
118                 protected virtual void Dispose (bool disposing)
119                 {
120                         _token = IntPtr.Zero;
121                 }
122                 // static methods
123
124                 public static WindowsIdentity GetAnonymous ()
125                 {
126                         WindowsIdentity id = null;
127                         if (Environment.IsUnix) {
128                                 id = new WindowsIdentity ("nobody");
129                                 // special case
130                                 id._account = WindowsAccountType.Anonymous;
131                                 id._authenticated = false;
132                                 id._type = String.Empty;
133                         }
134                         else {
135                                 id = new WindowsIdentity (IntPtr.Zero, String.Empty, WindowsAccountType.Anonymous, false);
136                                 // special case (don't try to resolve the name)
137                                 id._name = String.Empty;
138                         }
139                         return id;
140                 }
141
142                 public static WindowsIdentity GetCurrent ()
143                 {
144                         return new WindowsIdentity (GetCurrentToken (), null, WindowsAccountType.Normal, true);
145                 }
146                 [MonoTODO ("need icall changes")]
147                 public static WindowsIdentity GetCurrent (bool ifImpersonating)
148                 {
149                         throw new NotImplementedException ();
150                 }
151
152                 [MonoTODO ("need icall changes")]
153                 public static WindowsIdentity GetCurrent (TokenAccessLevels desiredAccess)
154                 {
155                         throw new NotImplementedException ();
156                 }
157                 // methods
158
159                 public virtual WindowsImpersonationContext Impersonate ()
160                 {
161                         return new WindowsImpersonationContext (_token);
162                 }
163
164                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal=true)]
165                 public static WindowsImpersonationContext Impersonate (IntPtr userToken)
166                 {
167                         return new WindowsImpersonationContext (userToken);
168                 }
169
170                 // properties
171
172                 public string AuthenticationType {
173                         get { return _type; }
174                 }
175
176                 public virtual bool IsAnonymous
177                 {
178                         get { return (_account == WindowsAccountType.Anonymous); }
179                 }
180
181                 public virtual bool IsAuthenticated
182                 {
183                         get { return _authenticated; }
184                 }
185
186                 public virtual bool IsGuest
187                 {
188                         get { return (_account == WindowsAccountType.Guest); }
189                 }
190
191                 public virtual bool IsSystem
192                 {
193                         get { return (_account == WindowsAccountType.System); }
194                 }
195
196                 public virtual string Name
197                 {
198                         get {
199                                 if (_name == null) {
200                                         // revolve name (runtime)
201                                         _name = GetTokenName (_token);
202                                 }
203                                 return _name; 
204                         }
205                 }
206
207                 public virtual IntPtr Token
208                 {
209                         get { return _token; }
210                 }
211                 [MonoTODO ("not implemented")]
212                 public IdentityReferenceCollection Groups {
213                         get { throw new NotImplementedException (); }
214                 }
215
216                 [MonoTODO ("not implemented")]
217                 [ComVisible (false)]
218                 public TokenImpersonationLevel ImpersonationLevel {
219                         get { throw new NotImplementedException (); }
220                 }
221
222                 [MonoTODO ("not implemented")]
223                 [ComVisible (false)]
224                 public SecurityIdentifier Owner {
225                         get { throw new NotImplementedException (); }
226                 }
227
228                 [MonoTODO ("not implemented")]
229                 [ComVisible (false)]
230                 public SecurityIdentifier User {
231                         get { throw new NotImplementedException (); }
232                 }
233                 void IDeserializationCallback.OnDeserialization (object sender)
234                 {
235                         _token = (IntPtr) _info.GetValue ("m_userToken", typeof (IntPtr));
236                         // can't trust this alone - we must validate the token
237                         _name = _info.GetString ("m_name");
238                         if (_name != null) {
239                                 // validate token by comparing names
240                                 string name = GetTokenName (_token);
241                                 if (name != _name)
242                                         throw new SerializationException ("Token-Name mismatch.");
243                         }
244                         else {
245                                 // validate token by getting name
246                                 _name = GetTokenName (_token);
247                                 if (_name == null)
248                                         throw new SerializationException ("Token doesn't match a user.");
249                         }
250                         _type = _info.GetString ("m_type");
251                         _account = (WindowsAccountType) _info.GetValue ("m_acctType", typeof (WindowsAccountType));
252                         _authenticated = _info.GetBoolean ("m_isAuthenticated");
253                 }
254
255                 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) 
256                 {
257                         info.AddValue ("m_userToken", _token);
258                         // can be null when not resolved
259                         info.AddValue ("m_name", _name);
260                         info.AddValue ("m_type", _type);
261                         info.AddValue ("m_acctType", _account);
262                         info.AddValue ("m_isAuthenticated", _authenticated);
263                 }
264
265                 private void SetToken (IntPtr token) 
266                 {
267                         if (Environment.IsUnix) {
268
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
281                                 _token = token;
282                                 // apply defaults
283                                 if (_type == null)
284                                         _type = "NTLM";
285                         }
286                 }
287
288                 // see mono/mono/metadata/security.c for implementation
289
290                 // Many people use reflection to get a user's roles - so many 
291                 // that's it's hard to say it's an "undocumented" feature -
292                 // so we also implement it in Mono :-/
293                 // http://www.dotnet247.com/247reference/msgs/39/195403.aspx
294                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
295                 internal extern static string[] _GetRoles (IntPtr token);
296
297                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
298                 internal extern static IntPtr GetCurrentToken ();
299
300                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
301                 private extern static string GetTokenName (IntPtr token);
302
303                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
304                 private extern static IntPtr GetUserToken (string username);
305         }
306 }