f30d5f184337ca8b147b433a3e69a50f6a986dbd
[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                 /* unlike most Invoke* cases InvokeMember is not inside System.Reflection[.Emit] but is SecuritySafeCritical */
159                 if (((*kname == 'T') && (strcmp (kname, "Type") == 0)) || 
160                         ((*kname == 'M') && (strcmp (kname, "MonoType")) == 0)) {
161
162                         /* if calling InvokeMember then we can't stop the stackwalk here and need to look at the caller */
163                         if (strcmp (m->name, "InvokeMember") == 0)
164                                 return FALSE;
165                 }
166
167                 /* the security check on the delegate is made at creation time, not at invoke time */
168                 if (((*kname == 'D') && (strcmp (kname, "Delegate") == 0)) || 
169                         ((*kname == 'M') && (strcmp (kname, "MulticastDelegate")) == 0)) {
170
171                         /* if we're invoking then we can stop our stack walk */
172                         if (strcmp (m->name, "DynamicInvoke") != 0)
173                                 return FALSE;
174                 }
175         }
176
177         if (m == *dest) {
178                 *dest = NULL;
179                 return FALSE;
180         }
181
182         *dest = m;
183         return TRUE;
184 }
185
186 /*
187  * get_reflection_caller:
188  * 
189  *      Walk to the first managed method outside:
190  *      - System.Reflection* namespaces
191  *      - System.[MulticastDelegate]Delegate or Activator type
192  *      - platform code
193  *      and return a pointer to its MonoMethod.
194  *
195  *      This is required since CoreCLR checks needs to be done on this "real" caller.
196  */
197 static MonoMethod*
198 get_reflection_caller (void)
199 {
200         MonoMethod *m = NULL;
201         mono_stack_walk_no_il (get_caller_no_reflection_related, &m);
202         if (!m)
203                 g_warning ("could not find a caller outside reflection");
204         return m;
205 }
206
207 /*
208  * check_field_access:
209  *
210  *      Return TRUE if the caller method can access the specified field, FALSE otherwise.
211  */
212 static gboolean
213 check_field_access (MonoMethod *caller, MonoClassField *field)
214 {
215         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
216         if (caller) {
217                 MonoClass *klass = (mono_field_get_flags (field) & FIELD_ATTRIBUTE_STATIC) ? NULL : mono_field_get_parent (field);
218                 return mono_method_can_access_field_full (caller, field, klass);
219         }
220         return FALSE;
221 }
222
223 /*
224  * check_method_access:
225  *
226  *      Return TRUE if the caller method can access the specified callee method, FALSE otherwise.
227  */
228 static gboolean
229 check_method_access (MonoMethod *caller, MonoMethod *callee)
230 {
231         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
232         if (caller) {
233                 MonoClass *klass = (callee->flags & METHOD_ATTRIBUTE_STATIC) ? NULL : callee->klass;
234                 return mono_method_can_access_method_full (caller, callee, klass);
235         }
236         return FALSE;
237 }
238
239 /*
240  * mono_security_core_clr_ensure_reflection_access_field:
241  *
242  *      Ensure that the specified field can be used with reflection since 
243  *      Transparent code cannot access to Critical fields and can only use
244  *      them if they are visible from it's point of view.
245  *
246  *      A FieldAccessException is thrown if the field is cannot be accessed.
247  */
248 void
249 mono_security_core_clr_ensure_reflection_access_field (MonoClassField *field)
250 {
251         MonoMethod *caller = get_reflection_caller ();
252         /* CoreCLR restrictions applies to Transparent code/caller */
253         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
254                 return;
255
256         /* Transparent code cannot [get|set]value on Critical fields */
257         if (mono_security_core_clr_class_level (mono_field_get_parent (field)) == MONO_SECURITY_CORE_CLR_CRITICAL)
258                 mono_raise_exception (mono_get_exception_field_access ());
259
260         /* also it cannot access a fields that is not visible from it's (caller) point of view */
261         if (!check_field_access (caller, field))
262                 mono_raise_exception (mono_get_exception_field_access ());
263 }
264
265 /*
266  * mono_security_core_clr_ensure_reflection_access_method:
267  *
268  *      Ensure that the specified method can be used with reflection since
269  *      Transparent code cannot call Critical methods and can only call them
270  *      if they are visible from it's point of view.
271  *
272  *      A MethodAccessException is thrown if the field is cannot be accessed.
273  */
274 void
275 mono_security_core_clr_ensure_reflection_access_method (MonoMethod *method)
276 {
277         MonoMethod *caller = get_reflection_caller ();
278         /* CoreCLR restrictions applies to Transparent code/caller */
279         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
280                 return;
281
282         /* Transparent code cannot invoke, even using reflection, Critical code */
283         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL)
284                 mono_raise_exception (mono_get_exception_method_access ());
285
286         /* also it cannot invoke a method that is not visible from it's (caller) point of view */
287         if (!check_method_access (caller, method))
288                 mono_raise_exception (mono_get_exception_method_access ());
289 }
290
291 /*
292  * can_avoid_corlib_reflection_delegate_optimization:
293  *
294  *      Mono's mscorlib use delegates to optimize PropertyInfo and EventInfo
295  *      reflection calls. This requires either a bunch of additional, and not
296  *      really required, [SecuritySafeCritical] in the class libraries or 
297  *      (like this) a way to skip them. As a bonus we also avoid the stack
298  *      walk to find the caller.
299  *
300  *      Return TRUE if we can skip this "internal" delegate creation, FALSE
301  *      otherwise.
302  */
303 static gboolean
304 can_avoid_corlib_reflection_delegate_optimization (MonoMethod *method)
305 {
306         if (!mono_security_core_clr_is_platform_image (method->klass->image))
307                 return FALSE;
308
309         if (strcmp (method->klass->name_space, "System.Reflection") != 0)
310                 return FALSE;
311
312         if (strcmp (method->klass->name, "MonoProperty") == 0) {
313                 if ((strcmp (method->name, "GetterAdapterFrame") == 0) || strcmp (method->name, "StaticGetterAdapterFrame") == 0)
314                         return TRUE;
315         } else if (strcmp (method->klass->name, "EventInfo") == 0) {
316                 if ((strcmp (method->name, "AddEventFrame") == 0) || strcmp (method->name, "StaticAddEventAdapterFrame") == 0)
317                         return TRUE;
318         }
319
320         return FALSE;
321 }
322
323 /*
324  * mono_security_core_clr_ensure_delegate_creation:
325  *
326  *      Return TRUE if a delegate can be created on the specified method. 
327  *      CoreCLR also affect the binding, so throwOnBindFailure must be 
328  *      FALSE to let this function return (FALSE) normally, otherwise (if
329  *      throwOnBindFailure is TRUE) it will throw an ArgumentException.
330  *
331  *      A MethodAccessException is thrown if the specified method is not
332  *      visible from the caller point of view.
333  */
334 gboolean
335 mono_security_core_clr_ensure_delegate_creation (MonoMethod *method, gboolean throwOnBindFailure)
336 {
337         MonoMethod *caller;
338
339         /* note: mscorlib creates delegates to avoid reflection (optimization), we ignore those cases */
340         if (can_avoid_corlib_reflection_delegate_optimization (method))
341                 return TRUE;
342
343         caller = get_reflection_caller ();
344         /* if the "real" caller is not Transparent then it do can anything */
345         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
346                 return TRUE;
347
348         /* otherwise it (as a Transparent caller) cannot create a delegate on a Critical method... */
349         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
350                 /* but this throws only if 'throwOnBindFailure' is TRUE */
351                 if (!throwOnBindFailure)
352                         return FALSE;
353
354                 mono_raise_exception (mono_get_exception_argument ("method", "Transparent code cannot call Critical code"));
355         }
356         
357         /* also it cannot create the delegate on a method that is not visible from it's (caller) point of view */
358         if (!check_method_access (caller, method))
359                 mono_raise_exception (mono_get_exception_method_access ());
360
361         return TRUE;
362 }
363
364 /*
365  * mono_security_core_clr_ensure_dynamic_method_resolved_object:
366  *
367  *      Called from mono_reflection_create_dynamic_method (reflection.c) to add some extra checks required for CoreCLR.
368  *      Dynamic methods needs to check to see if the objects being used (e.g. methods, fields) comes from platform code
369  *      and do an accessibility check in this case. Otherwise (i.e. user/application code) can be used without this extra
370  *      accessbility check.
371  */
372 MonoException*
373 mono_security_core_clr_ensure_dynamic_method_resolved_object (gpointer ref, MonoClass *handle_class)
374 {
375         /* XXX find/create test cases for other handle_class XXX */
376         if (handle_class == mono_defaults.fieldhandle_class) {
377                 MonoClassField *field = (MonoClassField*) ref;
378                 MonoClass *klass = mono_field_get_parent (field);
379                 /* fields coming from platform code have extra protection (accessibility check) */
380                 if (mono_security_core_clr_is_platform_image (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_field_access (caller, field))
384                                 return mono_get_exception_field_access ();
385                 }
386         } else if (handle_class == mono_defaults.methodhandle_class) {
387                 MonoMethod *method = (MonoMethod*) ref;
388                 /* methods coming from platform code have extra protection (accessibility check) */
389                 if (mono_security_core_clr_is_platform_image (method->klass->image)) {
390                         MonoMethod *caller = get_reflection_caller ();
391                         /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
392                         if (!check_method_access (caller, method))
393                                 return mono_get_exception_method_access ();
394                 }
395         }
396         return NULL;
397 }
398
399 /*
400  * mono_security_core_clr_can_access_internals
401  *
402  *      Check if we allow [InternalsVisibleTo] to work between two images.
403  */
404 gboolean
405 mono_security_core_clr_can_access_internals (MonoImage *accessing, MonoImage* accessed)
406 {
407         /* are we trying to access internals of a platform assembly ? if not this is acceptable */
408         if (!mono_security_core_clr_is_platform_image (accessed))
409                 return TRUE;
410
411         /* we can't let everyone with the right name and public key token access the internals of platform code.
412          * (Silverlight can rely on the strongname signature of the assemblies, but Mono does not verify them)
413          * However platform code is fully trusted so it can access the internals of other platform code assemblies */
414         if (mono_security_core_clr_is_platform_image (accessing))
415                 return TRUE;
416
417         /* catch-22: System.Xml needs access to mscorlib's internals (e.g. ArrayList) but is not considered platform code.
418          * Promoting it to platform code would create another issue since (both Mono/Moonlight or MS version of) 
419          * System.Xml.Linq.dll (an SDK, not platform, assembly) needs access to System.Xml.dll internals (either ). 
420          * The solution is to trust, even transparent code, in the plugin directory to access platform code internals */
421         return (strcmp (accessed->assembly->basedir, accessing->assembly->basedir) == 0);
422 }
423
424 /*
425  * mono_security_core_clr_level_from_cinfo:
426  *
427  *      Return the MonoSecurityCoreCLRLevel that match the attribute located
428  *      in the specified custom attributes. If no attribute is present it 
429  *      defaults to MONO_SECURITY_CORE_CLR_TRANSPARENT, which is the default
430  *      level for all code under the CoreCLR.
431  */
432 static MonoSecurityCoreCLRLevel
433 mono_security_core_clr_level_from_cinfo (MonoCustomAttrInfo *cinfo, MonoImage *image)
434 {
435         int level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
436
437         if (cinfo && mono_custom_attrs_has_attr (cinfo, security_safe_critical_attribute ()))
438                 level = MONO_SECURITY_CORE_CLR_SAFE_CRITICAL;
439         if (cinfo && mono_custom_attrs_has_attr (cinfo, security_critical_attribute ()))
440                 level = MONO_SECURITY_CORE_CLR_CRITICAL;
441
442         return level;
443 }
444
445 /*
446  * mono_security_core_clr_class_level_no_platform_check:
447  *
448  *      Return the MonoSecurityCoreCLRLevel for the specified class, without 
449  *      checking for platform code. This help us avoid multiple redundant 
450  *      checks, e.g.
451  *      - a check for the method and one for the class;
452  *      - a check for the class and outer class(es) ...
453  */
454 static MonoSecurityCoreCLRLevel
455 mono_security_core_clr_class_level_no_platform_check (MonoClass *class)
456 {
457         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
458         MonoCustomAttrInfo *cinfo = mono_custom_attrs_from_class (class);
459         if (cinfo) {
460                 level = mono_security_core_clr_level_from_cinfo (cinfo, class->image);
461                 mono_custom_attrs_free (cinfo);
462         }
463
464         if (level == MONO_SECURITY_CORE_CLR_TRANSPARENT && class->nested_in)
465                 level = mono_security_core_clr_class_level_no_platform_check (class->nested_in);
466
467         return level;
468 }
469
470 /*
471  * mono_security_core_clr_class_level:
472  *
473  *      Return the MonoSecurityCoreCLRLevel for the specified class.
474  */
475 MonoSecurityCoreCLRLevel
476 mono_security_core_clr_class_level (MonoClass *class)
477 {
478         /* non-platform code is always Transparent - whatever the attributes says */
479         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (class->image))
480                 return MONO_SECURITY_CORE_CLR_TRANSPARENT;
481
482         return mono_security_core_clr_class_level_no_platform_check (class);
483 }
484
485 /*
486  * mono_security_core_clr_method_level:
487  *
488  *      Return the MonoSecurityCoreCLRLevel for the specified method.
489  *      If with_class_level is TRUE then the type (class) will also be
490  *      checked, otherwise this will only report the information about
491  *      the method itself.
492  */
493 MonoSecurityCoreCLRLevel
494 mono_security_core_clr_method_level (MonoMethod *method, gboolean with_class_level)
495 {
496         MonoCustomAttrInfo *cinfo;
497         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
498
499         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
500         if (!method)
501                 return level;
502
503         /* non-platform code is always Transparent - whatever the attributes says */
504         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (method->klass->image))
505                 return level;
506
507         cinfo = mono_custom_attrs_from_method (method);
508         if (cinfo) {
509                 level = mono_security_core_clr_level_from_cinfo (cinfo, method->klass->image);
510                 mono_custom_attrs_free (cinfo);
511         }
512
513         if (with_class_level && level == MONO_SECURITY_CORE_CLR_TRANSPARENT)
514                 level = mono_security_core_clr_class_level (method->klass);
515
516         return level;
517 }
518
519 /*
520  * mono_security_core_clr_is_platform_image:
521  *
522  *   Return the (cached) boolean value indicating if this image represent platform code
523  */
524 gboolean
525 mono_security_core_clr_is_platform_image (MonoImage *image)
526 {
527         return image->core_clr_platform_code;
528 }
529
530 /*
531  * default_platform_check:
532  *
533  *      Default platform check. Always TRUE for current corlib (minimum 
534  *      trust-able subset) otherwise return FALSE. Any real CoreCLR host
535  *      should provide its own callback to define platform code (i.e.
536  *      this default is meant for test only).
537  */
538 static gboolean
539 default_platform_check (const char *image_name)
540 {
541         if (mono_defaults.corlib) {
542                 return (strcmp (mono_defaults.corlib->name, image_name) == 0);
543         } else {
544                 /* this can get called even before we load corlib (e.g. the EXE itself) */
545                 const char *corlib = "mscorlib.dll";
546                 int ilen = strlen (image_name);
547                 int clen = strlen (corlib);
548                 return ((ilen >= clen) && (strcmp ("mscorlib.dll", image_name + ilen - clen) == 0));
549         }
550 }
551
552 static MonoCoreClrPlatformCB platform_callback = default_platform_check;
553
554 /*
555  * mono_security_core_clr_determine_platform_image:
556  *
557  *      Call the supplied callback (from mono_security_set_core_clr_platform_callback) 
558  *      to determine if this image represents platform code.
559  */
560 gboolean
561 mono_security_core_clr_determine_platform_image (MonoImage *image)
562 {
563         return platform_callback (image->name);
564 }
565
566 /*
567  * mono_security_enable_core_clr:
568  *
569  *   Enable the verifier and the CoreCLR security model
570  */
571 void
572 mono_security_enable_core_clr ()
573 {
574         mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
575         mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
576 }
577
578 /*
579  * mono_security_set_core_clr_platform_callback:
580  *
581  *      Set the callback function that will be used to determine if an image
582  *      is part, or not, of the platform code.
583  */
584 void
585 mono_security_set_core_clr_platform_callback (MonoCoreClrPlatformCB callback)
586 {
587         platform_callback = callback;
588 }
589