2009-05-18 Miguel de Icaza <miguel@novell.com>
[mono.git] / mono / metadata / security-core-clr.c
1 /*
2  * security-core-clr.c: CoreCLR security
3  *
4  * Authors:
5  *      Mark Probst <mark.probst@gmail.com>
6  *      Sebastien Pouliot  <sebastien@ximian.com>
7  *
8  * Copyright 2007-2009 Novell, Inc (http://www.novell.com)
9  */
10
11 #include <mono/metadata/class-internals.h>
12 #include <mono/metadata/security-manager.h>
13 #include <mono/metadata/assembly.h>
14 #include <mono/metadata/appdomain.h>
15 #include <mono/metadata/verify-internals.h>
16 #include <mono/metadata/object.h>
17 #include <mono/metadata/exception.h>
18
19 #include "security-core-clr.h"
20
21 gboolean mono_security_core_clr_test = FALSE;
22
23 static MonoClass*
24 security_critical_attribute (void)
25 {
26         static MonoClass *class = NULL;
27
28         if (!class) {
29                 class = mono_class_from_name (mono_defaults.corlib, "System.Security", 
30                         "SecurityCriticalAttribute");
31         }
32         g_assert (class);
33         return class;
34 }
35
36 static MonoClass*
37 security_safe_critical_attribute (void)
38 {
39         static MonoClass *class = NULL;
40
41         if (!class) {
42                 class = mono_class_from_name (mono_defaults.corlib, "System.Security", 
43                         "SecuritySafeCriticalAttribute");
44         }
45         g_assert (class);
46         return class;
47 }
48
49 /*
50  * mono_security_core_clr_check_inheritance:
51  *
52  *      Determine if the specified class can inherit from its parent using 
53  *      the CoreCLR inheritance rules.
54  *
55  *      Base Type       Allow Derived Type
56  *      ------------    ------------------
57  *      Transparent     Transparent, SafeCritical, Critical
58  *      SafeCritical    SafeCritical, Critical
59  *      Critical        Critical
60  *
61  *      Reference: http://msdn.microsoft.com/en-us/magazine/cc765416.aspx#id0190030
62  */
63 void
64 mono_security_core_clr_check_inheritance (MonoClass *class)
65 {
66         MonoSecurityCoreCLRLevel class_level, parent_level;
67         MonoClass *parent = class->parent;
68
69         if (!parent)
70                 return;
71
72         class_level = mono_security_core_clr_class_level (class);
73         parent_level = mono_security_core_clr_class_level (parent);
74
75         if (class_level < parent_level)
76                 mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
77 }
78
79 /*
80  * mono_security_core_clr_check_override:
81  *
82  *      Determine if the specified override can "legally" override the 
83  *      specified base method using the CoreCLR inheritance rules.
84  *
85  *      Base (virtual/interface)        Allowed override
86  *      ------------------------        -------------------------
87  *      Transparent                     Transparent, SafeCritical
88  *      SafeCritical                    Transparent, SafeCritical
89  *      Critical                        Critical
90  *
91  *      Reference: http://msdn.microsoft.com/en-us/magazine/cc765416.aspx#id0190030
92  */
93 void
94 mono_security_core_clr_check_override (MonoClass *class, MonoMethod *override, MonoMethod *base)
95 {
96         MonoSecurityCoreCLRLevel base_level = mono_security_core_clr_method_level (base, FALSE);
97         MonoSecurityCoreCLRLevel override_level = mono_security_core_clr_method_level (override, FALSE);
98         /* if the base method is decorated with [SecurityCritical] then the overrided method MUST be too */
99         if (base_level == MONO_SECURITY_CORE_CLR_CRITICAL) {
100                 if (override_level != MONO_SECURITY_CORE_CLR_CRITICAL)
101                         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
102         } else {
103                 /* base is [SecuritySafeCritical] or [SecurityTransparent], override MUST NOT be [SecurityCritical] */
104                 if (override_level == MONO_SECURITY_CORE_CLR_CRITICAL)
105                         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
106         }
107 }
108
109 /*
110  * get_caller_no_reflection_related:
111  *
112  *      Find the first managed caller that is either:
113  *      (a) located outside the platform code assemblies; or
114  *      (b) not related to reflection and delegates
115  *
116  *      Returns TRUE to stop the stackwalk, FALSE to continue to the next frame.
117  */
118 static gboolean
119 get_caller_no_reflection_related (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
120 {
121         MonoMethod **dest = data;
122         const char *ns;
123
124         /* skip unmanaged frames */
125         if (!managed)
126                 return FALSE;
127
128         if (m->wrapper_type != MONO_WRAPPER_NONE)
129                 return FALSE;
130
131         /* quick out (any namespace not starting with an 'S' */
132         ns = m->klass->name_space;
133         if (!ns || (*ns != 'S')) {
134                 *dest = m;
135                 return TRUE;
136         }
137
138         /* stop if the method is not part of platform code */
139         if (!mono_security_core_clr_is_platform_image (m->klass->image)) {
140                 *dest = m;
141                 return TRUE;
142         }
143
144         /* any number of calls inside System.Reflection are allowed */
145         if (strcmp (ns, "System.Reflection") == 0)
146                 return FALSE;
147
148         /* any number of calls inside System.Reflection are allowed */
149         if (strcmp (ns, "System.Reflection.Emit") == 0)
150                 return FALSE;
151
152         /* calls from System.Delegate are also possible and allowed */
153         if (strcmp (ns, "System") == 0) {
154                 const char *kname = m->klass->name;
155                 if ((*kname == 'A') && (strcmp (kname, "Activator") == 0))
156                         return FALSE;
157
158                 // the security check on the delegate is made at creation time, not at invoke time
159                 if (((*kname == 'D') && (strcmp (kname, "Delegate") == 0)) || 
160                         ((*kname == 'M') && (strcmp (kname, "MulticastDelegate")) == 0)) {
161
162                         // if we're invoking then we can stop our stack walk
163                         if (strcmp (m->name, "DynamicInvoke") != 0)
164                                 return FALSE;
165                 }
166         }
167
168         if (m == *dest) {
169                 *dest = NULL;
170                 return FALSE;
171         }
172
173         *dest = m;
174         return TRUE;
175 }
176
177 /*
178  * get_reflection_caller:
179  * 
180  *      Walk to the first managed method outside:
181  *      - System.Reflection* namespaces
182  *      - System.[MulticastDelegate]Delegate or Activator type
183  *      - platform code
184  *      and return a pointer to its MonoMethod.
185  *
186  *      This is required since CoreCLR checks needs to be done on this "real" caller.
187  */
188 static MonoMethod*
189 get_reflection_caller (void)
190 {
191         MonoMethod *m = NULL;
192         mono_stack_walk_no_il (get_caller_no_reflection_related, &m);
193         if (!m)
194                 g_warning ("could not find a caller outside reflection");
195         return m;
196 }
197
198 /*
199  * check_field_access:
200  *
201  *      Return TRUE if the caller method can access the specified field, FALSE otherwise.
202  */
203 static gboolean
204 check_field_access (MonoMethod *caller, MonoClassField *field)
205 {
206         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
207         if (caller) {
208                 MonoClass *klass = (mono_field_get_flags (field) & FIELD_ATTRIBUTE_STATIC) ? NULL : mono_field_get_parent (field);
209                 return mono_method_can_access_field_full (caller, field, klass);
210         }
211         return FALSE;
212 }
213
214 /*
215  * check_method_access:
216  *
217  *      Return TRUE if the caller method can access the specified callee method, FALSE otherwise.
218  */
219 static gboolean
220 check_method_access (MonoMethod *caller, MonoMethod *callee)
221 {
222         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
223         if (caller) {
224                 MonoClass *klass = (callee->flags & METHOD_ATTRIBUTE_STATIC) ? NULL : callee->klass;
225                 return mono_method_can_access_method_full (caller, callee, klass);
226         }
227         return FALSE;
228 }
229
230 /*
231  * mono_security_core_clr_ensure_reflection_access_field:
232  *
233  *      Ensure that the specified field can be used with reflection since 
234  *      Transparent code cannot access to Critical fields and can only use
235  *      them if they are visible from it's point of view.
236  *
237  *      A FieldAccessException is thrown if the field is cannot be accessed.
238  */
239 void
240 mono_security_core_clr_ensure_reflection_access_field (MonoClassField *field)
241 {
242         MonoMethod *caller = get_reflection_caller ();
243         /* CoreCLR restrictions applies to Transparent code/caller */
244         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
245                 return;
246
247         /* Transparent code cannot [get|set]value on Critical fields */
248         if (mono_security_core_clr_class_level (mono_field_get_parent (field)) == MONO_SECURITY_CORE_CLR_CRITICAL)
249                 mono_raise_exception (mono_get_exception_field_access ());
250
251         /* also it cannot access a fields that is not visible from it's (caller) point of view */
252         if (!check_field_access (caller, field))
253                 mono_raise_exception (mono_get_exception_field_access ());
254 }
255
256 /*
257  * mono_security_core_clr_ensure_reflection_access_method:
258  *
259  *      Ensure that the specified method can be used with reflection since
260  *      Transparent code cannot call Critical methods and can only call them
261  *      if they are visible from it's point of view.
262  *
263  *      A MethodAccessException is thrown if the field is cannot be accessed.
264  */
265 void
266 mono_security_core_clr_ensure_reflection_access_method (MonoMethod *method)
267 {
268         MonoMethod *caller = get_reflection_caller ();
269         /* CoreCLR restrictions applies to Transparent code/caller */
270         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
271                 return;
272
273         /* Transparent code cannot invoke, even using reflection, Critical code */
274         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL)
275                 mono_raise_exception (mono_get_exception_method_access ());
276
277         /* also it cannot invoke a method that is not visible from it's (caller) point of view */
278         if (!check_method_access (caller, method))
279                 mono_raise_exception (mono_get_exception_method_access ());
280 }
281
282 /*
283  * can_avoid_corlib_reflection_delegate_optimization:
284  *
285  *      Mono's mscorlib use delegates to optimize PropertyInfo and EventInfo
286  *      reflection calls. This requires either a bunch of additional, and not
287  *      really required, [SecuritySafeCritical] in the class libraries or 
288  *      (like this) a way to skip them. As a bonus we also avoid the stack
289  *      walk to find the caller.
290  *
291  *      Return TRUE if we can skip this "internal" delegate creation, FALSE
292  *      otherwise.
293  */
294 static gboolean
295 can_avoid_corlib_reflection_delegate_optimization (MonoMethod *method)
296 {
297         if (!mono_security_core_clr_is_platform_image (method->klass->image))
298                 return FALSE;
299
300         if (strcmp (method->klass->name_space, "System.Reflection") != 0)
301                 return FALSE;
302
303         if (strcmp (method->klass->name, "MonoProperty") == 0) {
304                 if ((strcmp (method->name, "GetterAdapterFrame") == 0) || strcmp (method->name, "StaticGetterAdapterFrame") == 0)
305                         return TRUE;
306         } else if (strcmp (method->klass->name, "EventInfo") == 0) {
307                 if ((strcmp (method->name, "AddEventFrame") == 0) || strcmp (method->name, "StaticAddEventAdapterFrame") == 0)
308                         return TRUE;
309         }
310
311         return FALSE;
312 }
313
314 /*
315  * mono_security_core_clr_ensure_delegate_creation:
316  *
317  *      Return TRUE if a delegate can be created on the specified method. 
318  *      CoreCLR also affect the binding, so throwOnBindFailure must be 
319  *      FALSE to let this function return (FALSE) normally, otherwise (if
320  *      throwOnBindFailure is TRUE) itwill throw an ArgumentException.
321  *
322  *      A MethodAccessException is thrown if the specified method is not
323  *      visible from the caller point of view.
324  */
325 gboolean
326 mono_security_core_clr_ensure_delegate_creation (MonoMethod *method, gboolean throwOnBindFailure)
327 {
328         MonoMethod *caller;
329
330         /* note: mscorlib creates delegates to avoid reflection (optimization), we ignore those cases */
331         if (can_avoid_corlib_reflection_delegate_optimization (method))
332                 return TRUE;
333
334         caller = get_reflection_caller ();
335         /* if the "real" caller is not Transparent then it do can anything */
336         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
337                 return TRUE;
338
339         /* otherwise it (as a Transparent caller) cannot create a delegate on a Critical method... */
340         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
341                 /* but this throws only if 'throwOnBindFailure' is TRUE */
342                 if (!throwOnBindFailure)
343                         return FALSE;
344
345                 mono_raise_exception (mono_get_exception_argument ("method", "Transparent code cannot call Critical code"));
346         }
347         
348         /* also it cannot create the delegate on a method that is not visible from it's (caller) point of view */
349         if (!check_method_access (caller, method))
350                 mono_raise_exception (mono_get_exception_method_access ());
351
352         return TRUE;
353 }
354
355 /*
356  * mono_security_core_clr_ensure_dynamic_method_resolved_object:
357  *
358  *      Called from mono_reflection_create_dynamic_method (reflection.c) to add some extra checks required for CoreCLR.
359  *      Dynamic methods needs to check to see if the objects being used (e.g. methods, fields) comes from platform code
360  *      and do an accessibility check in this case. Otherwise (i.e. user/application code) can be used without this extra
361  *      accessbility check.
362  */
363 MonoException*
364 mono_security_core_clr_ensure_dynamic_method_resolved_object (gpointer ref, MonoClass *handle_class)
365 {
366         /* XXX find/create test cases for other handle_class XXX */
367         if (handle_class == mono_defaults.fieldhandle_class) {
368                 MonoClassField *field = (MonoClassField*) ref;
369                 MonoClass *klass = mono_field_get_parent (field);
370                 /* fields coming from platform code have extra protection (accessibility check) */
371                 if (mono_security_core_clr_is_platform_image (klass->image)) {
372                         MonoMethod *caller = get_reflection_caller ();
373                         /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
374                         if (!check_field_access (caller, field))
375                                 return mono_get_exception_field_access ();
376                 }
377         } else if (handle_class == mono_defaults.methodhandle_class) {
378                 MonoMethod *method = (MonoMethod*) ref;
379                 /* methods coming from platform code have extra protection (accessibility check) */
380                 if (mono_security_core_clr_is_platform_image (method->klass->image)) {
381                         MonoMethod *caller = get_reflection_caller ();
382                         /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
383                         if (!check_method_access (caller, method))
384                                 return mono_get_exception_method_access ();
385                 }
386         }
387         return NULL;
388 }
389
390 /*
391  * mono_security_core_clr_level_from_cinfo:
392  *
393  *      Return the MonoSecurityCoreCLRLevel that match the attribute located
394  *      in the specified custom attributes. If no attribute is present it 
395  *      defaults to MONO_SECURITY_CORE_CLR_TRANSPARENT, which is the default
396  *      level for all code under the CoreCLR.
397  */
398 static MonoSecurityCoreCLRLevel
399 mono_security_core_clr_level_from_cinfo (MonoCustomAttrInfo *cinfo, MonoImage *image)
400 {
401         int level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
402
403         if (cinfo && mono_custom_attrs_has_attr (cinfo, security_safe_critical_attribute ()))
404                 level = MONO_SECURITY_CORE_CLR_SAFE_CRITICAL;
405         if (cinfo && mono_custom_attrs_has_attr (cinfo, security_critical_attribute ()))
406                 level = MONO_SECURITY_CORE_CLR_CRITICAL;
407
408         return level;
409 }
410
411 /*
412  * mono_security_core_clr_class_level_no_platform_check:
413  *
414  *      Return the MonoSecurityCoreCLRLevel for the specified class, without 
415  *      checking for platform code. This help us avoid multiple redundant 
416  *      checks, e.g.
417  *      - a check for the method and one for the class;
418  *      - a check for the class and outer class(es) ...
419  */
420 static MonoSecurityCoreCLRLevel
421 mono_security_core_clr_class_level_no_platform_check (MonoClass *class)
422 {
423         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
424         MonoCustomAttrInfo *cinfo = mono_custom_attrs_from_class (class);
425         if (cinfo) {
426                 level = mono_security_core_clr_level_from_cinfo (cinfo, class->image);
427                 mono_custom_attrs_free (cinfo);
428         }
429
430         if (level == MONO_SECURITY_CORE_CLR_TRANSPARENT && class->nested_in)
431                 level = mono_security_core_clr_class_level_no_platform_check (class->nested_in);
432
433         return level;
434 }
435
436 /*
437  * mono_security_core_clr_class_level:
438  *
439  *      Return the MonoSecurityCoreCLRLevel for the specified class.
440  */
441 MonoSecurityCoreCLRLevel
442 mono_security_core_clr_class_level (MonoClass *class)
443 {
444         /* non-platform code is always Transparent - whatever the attributes says */
445         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (class->image))
446                 return MONO_SECURITY_CORE_CLR_TRANSPARENT;
447
448         return mono_security_core_clr_class_level_no_platform_check (class);
449 }
450
451 /*
452  * mono_security_core_clr_method_level:
453  *
454  *      Return the MonoSecurityCoreCLRLevel for the specified method.
455  *      If with_class_level is TRUE then the type (class) will also be
456  *      checked, otherwise this will only report the information about
457  *      the method itself.
458  */
459 MonoSecurityCoreCLRLevel
460 mono_security_core_clr_method_level (MonoMethod *method, gboolean with_class_level)
461 {
462         MonoCustomAttrInfo *cinfo;
463         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
464
465         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
466         if (!method)
467                 return level;
468
469         /* non-platform code is always Transparent - whatever the attributes says */
470         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (method->klass->image))
471                 return level;
472
473         cinfo = mono_custom_attrs_from_method (method);
474         if (cinfo) {
475                 level = mono_security_core_clr_level_from_cinfo (cinfo, method->klass->image);
476                 mono_custom_attrs_free (cinfo);
477         }
478
479         if (with_class_level && level == MONO_SECURITY_CORE_CLR_TRANSPARENT)
480                 level = mono_security_core_clr_class_level (method->klass);
481
482         return level;
483 }
484
485 /*
486  * mono_security_core_clr_is_platform_image:
487  *
488  *   Return the (cached) boolean value indicating if this image represent platform code
489  */
490 gboolean
491 mono_security_core_clr_is_platform_image (MonoImage *image)
492 {
493         return image->core_clr_platform_code;
494 }
495
496 /*
497  * default_platform_check:
498  *
499  *      Default platform check. Always return FALSE.
500  */
501 static gboolean
502 default_platform_check (const char *image_name)
503 {
504         return FALSE;
505 }
506
507 static MonoCoreClrPlatformCB platform_callback = default_platform_check;
508
509 /*
510  * mono_security_core_clr_determine_platform_image:
511  *
512  *      Call the supplied callback (from mono_security_set_core_clr_platform_callback) 
513  *      to determine if this image represents platform code.
514  */
515 gboolean
516 mono_security_core_clr_determine_platform_image (MonoImage *image)
517 {
518         return platform_callback (image->name);
519 }
520
521 /*
522  * mono_security_enable_core_clr:
523  *
524  *   Enable the verifier and the CoreCLR security model
525  */
526 void
527 mono_security_enable_core_clr ()
528 {
529         mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
530         mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
531 }
532
533 /*
534  * mono_security_set_core_clr_platform_callback:
535  *
536  *      Set the callback function that will be used to determine if an image
537  *      is part, or not, of the platform code.
538  */
539 void
540 mono_security_set_core_clr_platform_callback (MonoCoreClrPlatformCB callback)
541 {
542         platform_callback = callback;
543 }
544