change documentation to be in the right format for public api, and document the meani...
[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-2010 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 #include <mono/metadata/debug-helpers.h>
19 #include <mono/utils/mono-logger-internal.h>
20
21 #include "security-core-clr.h"
22
23 gboolean mono_security_core_clr_test = FALSE;
24
25 static MonoClass*
26 security_critical_attribute (void)
27 {
28         static MonoClass *class = NULL;
29
30         if (!class) {
31                 class = mono_class_from_name (mono_defaults.corlib, "System.Security", 
32                         "SecurityCriticalAttribute");
33         }
34         g_assert (class);
35         return class;
36 }
37
38 static MonoClass*
39 security_safe_critical_attribute (void)
40 {
41         static MonoClass *class = NULL;
42
43         if (!class) {
44                 class = mono_class_from_name (mono_defaults.corlib, "System.Security", 
45                         "SecuritySafeCriticalAttribute");
46         }
47         g_assert (class);
48         return class;
49 }
50
51 /* sometime we get a NULL (not found) caller (e.g. get_reflection_caller) */
52 static char*
53 get_method_full_name (MonoMethod * method)
54 {
55         return method ? mono_method_full_name (method, TRUE) : g_strdup ("'no caller found'");
56 }
57
58 /*
59  * set_type_load_exception_type
60  *
61  *      Set MONO_EXCEPTION_TYPE_LOAD on the specified 'class' and provide
62  *      a descriptive message for the exception. This message is also, 
63  *      optionally, being logged (export MONO_LOG_MASK="security") for
64  *      debugging purposes.
65  */
66 static void
67 set_type_load_exception_type (const char *format, MonoClass *class)
68 {
69         char *type_name = mono_type_get_full_name (class);
70         char *parent_name = mono_type_get_full_name (class->parent);
71         char *message = g_strdup_printf (format, type_name, parent_name);
72
73         g_free (parent_name);
74         g_free (type_name);
75         
76         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
77         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, message);
78         // note: do not free string given to mono_class_set_failure
79 }
80
81 /*
82  * set_type_load_exception_methods
83  *
84  *      Set MONO_EXCEPTION_TYPE_LOAD on the 'override' class and provide
85  *      a descriptive message for the exception. This message is also, 
86  *      optionally, being logged (export MONO_LOG_MASK="security") for
87  *      debugging purposes.
88  */
89 static void
90 set_type_load_exception_methods (const char *format, MonoMethod *override, MonoMethod *base)
91 {
92         char *method_name = get_method_full_name (override);
93         char *base_name = get_method_full_name (base);
94         char *message = g_strdup_printf (format, method_name, base_name);
95
96         g_free (base_name);
97         g_free (method_name);
98
99         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
100         mono_class_set_failure (override->klass, MONO_EXCEPTION_TYPE_LOAD, message);
101         // note: do not free string given to mono_class_set_failure
102 }
103
104 /* MonoClass is not fully initialized (inited is not yet == 1) when we 
105  * check the inheritance rules so we need to look for the default ctor
106  * ourselve to avoid recursion (and aborting)
107  */
108 static MonoMethod*
109 get_default_ctor (MonoClass *klass)
110 {
111         int i;
112
113         mono_class_setup_methods (klass);
114         if (!klass->methods)
115                 return NULL;
116
117         for (i = 0; i < klass->method.count; ++i) {
118                 MonoMethodSignature *sig;
119                 MonoMethod *method = klass->methods [i];
120
121                 if (!method)
122                         continue;
123
124                 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) == 0)
125                         continue;
126                 if ((method->name[0] != '.') || strcmp (".ctor", method->name))
127                         continue;
128                 sig = mono_method_signature (method);
129                 if (sig && (sig->param_count == 0))
130                         return method;
131         }
132
133         return NULL;
134 }
135
136 /*
137  * mono_security_core_clr_check_inheritance:
138  *
139  *      Determine if the specified class can inherit from its parent using 
140  *      the CoreCLR inheritance rules.
141  *
142  *      Base Type       Allow Derived Type
143  *      ------------    ------------------
144  *      Transparent     Transparent, SafeCritical, Critical
145  *      SafeCritical    SafeCritical, Critical
146  *      Critical        Critical
147  *
148  *      Reference: http://msdn.microsoft.com/en-us/magazine/cc765416.aspx#id0190030
149  *
150  *      Furthermore a class MUST have a default constructor if its base 
151  *      class has a non-transparent, public or protected, default constructor. 
152  *      The same inheritance rule applies to both default constructors.
153  *
154  *      Reference: message from a SecurityException in SL4RC
155  *      Reference: fxcop CA2132 rule
156  */
157 void
158 mono_security_core_clr_check_inheritance (MonoClass *class)
159 {
160         MonoSecurityCoreCLRLevel class_level, parent_level;
161         MonoClass *parent = class->parent;
162
163         if (!parent)
164                 return;
165
166         class_level = mono_security_core_clr_class_level (class);
167         parent_level = mono_security_core_clr_class_level (parent);
168
169         if (class_level < parent_level) {
170                 set_type_load_exception_type (
171                         "Inheritance failure for type %s. Parent class %s is more restricted.",
172                         class);
173         } else {
174                 MonoMethod *parent_ctor = get_default_ctor (parent);
175                 if (parent_ctor && ((parent_ctor->flags & METHOD_ATTRIBUTE_PUBLIC) != 0)) {
176                         class_level = mono_security_core_clr_method_level (get_default_ctor (class), FALSE);
177                         parent_level = mono_security_core_clr_method_level (parent_ctor, FALSE);
178                         if (class_level < parent_level) {
179                                 set_type_load_exception_type (
180                                         "Inheritance failure for type %s. Default constructor security mismatch with %s.",
181                                         class);
182                         }
183                 }
184         }
185 }
186
187 /*
188  * mono_security_core_clr_check_override:
189  *
190  *      Determine if the specified override can "legally" override the 
191  *      specified base method using the CoreCLR inheritance rules.
192  *
193  *      Base (virtual/interface)        Allowed override
194  *      ------------------------        -------------------------
195  *      Transparent                     Transparent, SafeCritical
196  *      SafeCritical                    Transparent, SafeCritical
197  *      Critical                        Critical
198  *
199  *      Reference: http://msdn.microsoft.com/en-us/magazine/cc765416.aspx#id0190030
200  */
201 void
202 mono_security_core_clr_check_override (MonoClass *class, MonoMethod *override, MonoMethod *base)
203 {
204         MonoSecurityCoreCLRLevel base_level = mono_security_core_clr_method_level (base, FALSE);
205         MonoSecurityCoreCLRLevel override_level = mono_security_core_clr_method_level (override, FALSE);
206         /* if the base method is decorated with [SecurityCritical] then the overrided method MUST be too */
207         if (base_level == MONO_SECURITY_CORE_CLR_CRITICAL) {
208                 if (override_level != MONO_SECURITY_CORE_CLR_CRITICAL) {
209                         set_type_load_exception_methods (
210                                 "Override failure for %s over %s. Override MUST be [SecurityCritical].",
211                                 override, base);
212                 }
213         } else {
214                 /* base is [SecuritySafeCritical] or [SecurityTransparent], override MUST NOT be [SecurityCritical] */
215                 if (override_level == MONO_SECURITY_CORE_CLR_CRITICAL) {
216                         set_type_load_exception_methods (
217                                 "Override failure for %s over %s. Override must NOT be [SecurityCritical].", 
218                                 override, base);
219                 }
220         }
221 }
222
223 /*
224  * get_caller_no_reflection_related:
225  *
226  *      Find the first managed caller that is either:
227  *      (a) located outside the platform code assemblies; or
228  *      (b) not related to reflection and delegates
229  *
230  *      Returns TRUE to stop the stackwalk, FALSE to continue to the next frame.
231  */
232 static gboolean
233 get_caller_no_reflection_related (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
234 {
235         MonoMethod **dest = data;
236         const char *ns;
237
238         /* skip unmanaged frames */
239         if (!managed)
240                 return FALSE;
241
242         if (m->wrapper_type != MONO_WRAPPER_NONE)
243                 return FALSE;
244
245         /* quick out (any namespace not starting with an 'S' */
246         ns = m->klass->name_space;
247         if (!ns || (*ns != 'S')) {
248                 *dest = m;
249                 return TRUE;
250         }
251
252         /* stop if the method is not part of platform code */
253         if (!mono_security_core_clr_is_platform_image (m->klass->image)) {
254                 *dest = m;
255                 return TRUE;
256         }
257
258         /* any number of calls inside System.Reflection are allowed */
259         if (strcmp (ns, "System.Reflection") == 0)
260                 return FALSE;
261
262         /* any number of calls inside System.Reflection are allowed */
263         if (strcmp (ns, "System.Reflection.Emit") == 0)
264                 return FALSE;
265
266         /* calls from System.Delegate are also possible and allowed */
267         if (strcmp (ns, "System") == 0) {
268                 const char *kname = m->klass->name;
269                 if ((*kname == 'A') && (strcmp (kname, "Activator") == 0))
270                         return FALSE;
271
272                 /* unlike most Invoke* cases InvokeMember is not inside System.Reflection[.Emit] but is SecuritySafeCritical */
273                 if (((*kname == 'T') && (strcmp (kname, "Type") == 0)) || 
274                         ((*kname == 'M') && (strcmp (kname, "MonoType")) == 0)) {
275
276                         /* if calling InvokeMember then we can't stop the stackwalk here and need to look at the caller */
277                         if (strcmp (m->name, "InvokeMember") == 0)
278                                 return FALSE;
279                 }
280
281                 /* the security check on the delegate is made at creation time, not at invoke time */
282                 if (((*kname == 'D') && (strcmp (kname, "Delegate") == 0)) || 
283                         ((*kname == 'M') && (strcmp (kname, "MulticastDelegate")) == 0)) {
284
285                         /* if we're invoking then we can stop our stack walk */
286                         if (strcmp (m->name, "DynamicInvoke") != 0)
287                                 return FALSE;
288                 }
289         }
290
291         if (m == *dest) {
292                 *dest = NULL;
293                 return FALSE;
294         }
295
296         *dest = m;
297         return TRUE;
298 }
299
300 /*
301  * get_reflection_caller:
302  * 
303  *      Walk to the first managed method outside:
304  *      - System.Reflection* namespaces
305  *      - System.[Multicast]Delegate or Activator type
306  *      - platform code
307  *      and return a pointer to its MonoMethod.
308  *
309  *      This is required since CoreCLR checks needs to be done on this "real" caller.
310  */
311 static MonoMethod*
312 get_reflection_caller (void)
313 {
314         MonoMethod *m = NULL;
315         mono_stack_walk_no_il (get_caller_no_reflection_related, &m);
316         if (G_UNLIKELY (!m)) {
317                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "No caller outside reflection was found");
318         }
319         return m;
320 }
321
322 typedef struct {
323         int depth;
324         MonoMethod *caller;
325 } ElevatedTrustCookie;
326
327 /*
328  * get_caller_of_elevated_trust_code
329  *
330  *      Stack walk to find who is calling code requiring Elevated Trust.
331  *      If a critical method is found then the caller is platform code
332  *      and has elevated trust, otherwise (transparent) a check needs to
333  *      be done (on the managed side) to determine if the application is
334  *      running with elevated permissions.
335  */
336 static gboolean
337 get_caller_of_elevated_trust_code (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
338 {
339         ElevatedTrustCookie *cookie = data;
340
341         /* skip unmanaged frames and wrappers */
342         if (!managed || (m->wrapper_type != MONO_WRAPPER_NONE))
343                 return FALSE;
344
345         /* end stack walk if we find ourselves outside platform code (we won't find critical code anymore) */
346         if (!mono_security_core_clr_is_platform_image (m->klass->image)) {
347                 cookie->caller = m;
348                 return TRUE;
349         }
350
351         switch (cookie->depth) {
352         /* while depth == 0 look for SecurityManager::[Check|Ensure]ElevatedPermissions */
353         case 0:
354                 if (strcmp (m->klass->name_space, "System.Security"))
355                         return FALSE;
356                 if (strcmp (m->klass->name, "SecurityManager"))
357                         return FALSE;
358                 if ((strcmp (m->name, "EnsureElevatedPermissions")) && strcmp (m->name, "CheckElevatedPermissions"))
359                         return FALSE;
360                 cookie->depth = 1;
361                 break;
362         /* while depth == 1 look for the caller to SecurityManager::[Check|Ensure]ElevatedPermissions */
363         case 1:
364                 /* this frame is [SecuritySafeCritical] because it calls [SecurityCritical] [Check|Ensure]ElevatedPermissions */
365                 /* the next frame will contain the caller(s) we want to check */
366                 cookie->depth = 2;
367                 break;
368         /* while depth >= 2 look for [safe]critical caller, end stack walk if we find it  */
369         default:
370                 cookie->depth++;
371                 /* if the caller is transparent then we continue the stack walk */
372                 if (mono_security_core_clr_method_level (m, TRUE) == MONO_SECURITY_CORE_CLR_TRANSPARENT)
373                         break;
374
375                 /* Security[Safe]Critical code is always allowed to call elevated-trust code */
376                 cookie->caller = m;
377                 return TRUE;
378         }
379
380         return FALSE;
381 }
382
383 /*
384  * mono_security_core_clr_require_elevated_permissions:
385  *
386  *      Return TRUE if the caller of the current method (the code who 
387  *      called SecurityManager.get_RequiresElevatedPermissions) needs
388  *      elevated trust to perform an action.
389  *
390  *      A stack walk is done to find the callers. If one of the callers
391  *      is either [SecurityCritical] or [SecuritySafeCritical] then the
392  *      action is needed for platform code (i.e. no restriction). 
393  *      Otherwise (transparent) the requested action needs elevated trust
394  */
395 gboolean
396 mono_security_core_clr_require_elevated_permissions (void)
397 {
398         ElevatedTrustCookie cookie;
399         cookie.depth = 0;
400         cookie.caller = NULL;
401         mono_stack_walk_no_il (get_caller_of_elevated_trust_code, &cookie);
402
403         /* return TRUE if the stack walk did not reach far enough or did not find callers */
404         if (!cookie.caller || cookie.depth < 3)
405                 return TRUE;
406
407         /* return TRUE if the caller is transparent, i.e. if elevated trust is required to continue executing the method */
408         return (mono_security_core_clr_method_level (cookie.caller, TRUE) == MONO_SECURITY_CORE_CLR_TRANSPARENT);
409 }
410
411
412 static MonoSecurityCoreCLROptions security_core_clr_options = MONO_SECURITY_CORE_CLR_OPTIONS_DEFAULT;
413
414 /**
415  * mono_security_core_clr_set_options:
416  * @options: the new options for the coreclr system to use
417  *
418  * By default, the CoreCLRs security model forbids execution trough reflection of methods not visible from the calling code.
419  * Even if the method being called is not in a platform assembly. For non moonlight CoreCLR users this restriction does not
420  * make a lot of sense, since the author could have just changed the non platform assembly to allow the method to be called.
421  * This function allows specific relaxations from the default behaviour to be set.
422  *
423  * Use MONO_SECURITY_CORE_CLR_OPTIONS_DEFAULT for the default coreclr coreclr behaviour as used in Moonlight.
424  *
425  * Use MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_REFLECTION to allow transparent code to execute methods and access 
426  * fields that are not in platformcode, even if those methods and fields are private or otherwise not visible to the calling code.
427  *
428  * Use MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_DELEGATE to allow delegates to be created that point at methods that are not in
429  * platformcode even if those methods and fields are private or otherwise not visible to the calling code.
430  *
431  */
432
433 void 
434 mono_security_core_clr_set_options (MonoSecurityCoreCLROptions options) {
435         security_core_clr_options = options;
436 }
437
438 /**
439  * mono_security_core_clr_get_options:
440  *
441  * Retrieves the current options used by the coreclr system.
442  */
443
444 MonoSecurityCoreCLROptions
445 mono_security_core_clr_get_options ()
446 {
447         return security_core_clr_options;
448 }
449
450
451 /*
452  * check_field_access:
453  *
454  *      Return TRUE if the caller method can access the specified field, FALSE otherwise.
455  */
456 static gboolean
457 check_field_access (MonoMethod *caller, MonoClassField *field)
458 {
459         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
460         if (caller) {
461                 MonoError error;
462                 MonoClass *klass;
463
464                 /* this check can occur before the field's type is resolved (and that can fail) */
465                 mono_field_get_type_checked (field, &error);
466                 if (!mono_error_ok (&error)) {
467                         mono_error_cleanup (&error);
468                         return FALSE;
469                 }
470
471                 klass = (mono_field_get_flags (field) & FIELD_ATTRIBUTE_STATIC) ? NULL : mono_field_get_parent (field);
472                 return mono_method_can_access_field_full (caller, field, klass);
473         }
474         return FALSE;
475 }
476
477 /*
478  * check_method_access:
479  *
480  *      Return TRUE if the caller method can access the specified callee method, FALSE otherwise.
481  */
482 static gboolean
483 check_method_access (MonoMethod *caller, MonoMethod *callee)
484 {
485         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
486         if (caller) {
487                 MonoClass *klass = (callee->flags & METHOD_ATTRIBUTE_STATIC) ? NULL : callee->klass;
488                 return mono_method_can_access_method_full (caller, callee, klass);
489         }
490         return FALSE;
491 }
492
493 /*
494  * get_argument_exception
495  *
496  *      Helper function to create an MonoException (ArgumentException in
497  *      managed-land) and provide a descriptive message for it. This 
498  *      message is also, optionally, being logged (export 
499  *      MONO_LOG_MASK="security") for debugging purposes.
500  */
501 static MonoException*
502 get_argument_exception (const char *format, MonoMethod *caller, MonoMethod *callee)
503 {
504         MonoException *ex;
505         char *caller_name = get_method_full_name (caller);
506         char *callee_name = get_method_full_name (callee);
507         char *message = g_strdup_printf (format, caller_name, callee_name);
508         g_free (callee_name);
509         g_free (caller_name);
510
511         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
512         ex = mono_get_exception_argument ("method", message);
513         g_free (message);
514
515         return ex;
516 }
517
518 /*
519  * get_field_access_exception
520  *
521  *      Helper function to create an MonoException (FieldAccessException
522  *      in managed-land) and provide a descriptive message for it. This
523  *      message is also, optionally, being logged (export 
524  *      MONO_LOG_MASK="security") for debugging purposes.
525  */
526 static MonoException*
527 get_field_access_exception (const char *format, MonoMethod *caller, MonoClassField *field)
528 {
529         MonoException *ex;
530         char *caller_name = get_method_full_name (caller);
531         char *field_name = mono_field_full_name (field);
532         char *message = g_strdup_printf (format, caller_name, field_name);
533         g_free (field_name);
534         g_free (caller_name);
535
536         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
537         ex = mono_get_exception_field_access_msg (message);
538         g_free (message);
539
540         return ex;
541 }
542
543 /*
544  * get_method_access_exception
545  *
546  *      Helper function to create an MonoException (MethodAccessException
547  *      in managed-land) and provide a descriptive message for it. This
548  *      message is also, optionally, being logged (export 
549  *      MONO_LOG_MASK="security") for debugging purposes.
550  */
551 static MonoException*
552 get_method_access_exception (const char *format, MonoMethod *caller, MonoMethod *callee)
553 {
554         MonoException *ex;
555         char *caller_name = get_method_full_name (caller);
556         char *callee_name = get_method_full_name (callee);
557         char *message = g_strdup_printf (format, caller_name, callee_name);
558         g_free (callee_name);
559         g_free (caller_name);
560
561         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
562         ex = mono_get_exception_method_access_msg (message);
563         g_free (message);
564
565         return ex;
566 }
567
568 /*
569  * mono_security_core_clr_ensure_reflection_access_field:
570  *
571  *      Ensure that the specified field can be used with reflection since 
572  *      Transparent code cannot access to Critical fields and can only use
573  *      them if they are visible from it's point of view.
574  *
575  *      A FieldAccessException is thrown if the field is cannot be accessed.
576  */
577 void
578 mono_security_core_clr_ensure_reflection_access_field (MonoClassField *field)
579 {
580         MonoMethod *caller = get_reflection_caller ();
581         /* CoreCLR restrictions applies to Transparent code/caller */
582         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
583                 return;
584
585         if (mono_security_core_clr_get_options () & MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_REFLECTION) {
586                 if (!mono_security_core_clr_is_platform_image (mono_field_get_parent(field)->image))
587                         return;
588         }
589
590         /* Transparent code cannot [get|set]value on Critical fields */
591         if (mono_security_core_clr_class_level (mono_field_get_parent (field)) == MONO_SECURITY_CORE_CLR_CRITICAL) {
592                 mono_raise_exception (get_field_access_exception (
593                         "Transparent method %s cannot get or set Critical field %s.", 
594                         caller, field));
595         }
596
597         /* also it cannot access a fields that is not visible from it's (caller) point of view */
598         if (!check_field_access (caller, field)) {
599                 mono_raise_exception (get_field_access_exception (
600                         "Transparent method %s cannot get or set private/internal field %s.", 
601                         caller, field));
602         }
603 }
604
605 /*
606  * mono_security_core_clr_ensure_reflection_access_method:
607  *
608  *      Ensure that the specified method can be used with reflection since
609  *      Transparent code cannot call Critical methods and can only call them
610  *      if they are visible from it's point of view.
611  *
612  *      A MethodAccessException is thrown if the field is cannot be accessed.
613  */
614 void
615 mono_security_core_clr_ensure_reflection_access_method (MonoMethod *method)
616 {
617         MonoMethod *caller = get_reflection_caller ();
618         /* CoreCLR restrictions applies to Transparent code/caller */
619         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
620                 return;
621
622         if (mono_security_core_clr_get_options () & MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_REFLECTION) {
623                 if (!mono_security_core_clr_is_platform_image (method->klass->image))
624                         return;
625         }
626
627         /* Transparent code cannot invoke, even using reflection, Critical code */
628         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
629                 mono_raise_exception (get_method_access_exception (
630                         "Transparent method %s cannot invoke Critical method %s.", 
631                         caller, method));
632         }
633
634         /* also it cannot invoke a method that is not visible from it's (caller) point of view */
635         if (!check_method_access (caller, method)) {
636                 mono_raise_exception (get_method_access_exception (
637                         "Transparent method %s cannot invoke private/internal method %s.", 
638                         caller, method));
639         }
640 }
641
642 /*
643  * can_avoid_corlib_reflection_delegate_optimization:
644  *
645  *      Mono's mscorlib use delegates to optimize PropertyInfo and EventInfo
646  *      reflection calls. This requires either a bunch of additional, and not
647  *      really required, [SecuritySafeCritical] in the class libraries or 
648  *      (like this) a way to skip them. As a bonus we also avoid the stack
649  *      walk to find the caller.
650  *
651  *      Return TRUE if we can skip this "internal" delegate creation, FALSE
652  *      otherwise.
653  */
654 static gboolean
655 can_avoid_corlib_reflection_delegate_optimization (MonoMethod *method)
656 {
657         if (!mono_security_core_clr_is_platform_image (method->klass->image))
658                 return FALSE;
659
660         if (strcmp (method->klass->name_space, "System.Reflection") != 0)
661                 return FALSE;
662
663         if (strcmp (method->klass->name, "MonoProperty") == 0) {
664                 if ((strcmp (method->name, "GetterAdapterFrame") == 0) || strcmp (method->name, "StaticGetterAdapterFrame") == 0)
665                         return TRUE;
666         } else if (strcmp (method->klass->name, "EventInfo") == 0) {
667                 if ((strcmp (method->name, "AddEventFrame") == 0) || strcmp (method->name, "StaticAddEventAdapterFrame") == 0)
668                         return TRUE;
669         }
670
671         return FALSE;
672 }
673
674 /*
675  * mono_security_core_clr_ensure_delegate_creation:
676  *
677  *      Return TRUE if a delegate can be created on the specified method. 
678  *      CoreCLR also affect the binding, so throwOnBindFailure must be 
679  *      FALSE to let this function return (FALSE) normally, otherwise (if
680  *      throwOnBindFailure is TRUE) it will throw an ArgumentException.
681  *
682  *      A MethodAccessException is thrown if the specified method is not
683  *      visible from the caller point of view.
684  */
685 gboolean
686 mono_security_core_clr_ensure_delegate_creation (MonoMethod *method, gboolean throwOnBindFailure)
687 {
688         MonoMethod *caller;
689
690         /* note: mscorlib creates delegates to avoid reflection (optimization), we ignore those cases */
691         if (can_avoid_corlib_reflection_delegate_optimization (method))
692                 return TRUE;
693
694         caller = get_reflection_caller ();
695         /* if the "real" caller is not Transparent then it do can anything */
696         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
697                 return TRUE;
698
699         /* otherwise it (as a Transparent caller) cannot create a delegate on a Critical method... */
700         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
701                 /* but this throws only if 'throwOnBindFailure' is TRUE */
702                 if (!throwOnBindFailure)
703                         return FALSE;
704
705                 mono_raise_exception (get_argument_exception (
706                         "Transparent method %s cannot create a delegate on Critical method %s.", 
707                         caller, method));
708         }
709
710         if (mono_security_core_clr_get_options () & MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_DELEGATE) {
711                 if (!mono_security_core_clr_is_platform_image (method->klass->image))
712                         return TRUE;
713         }
714
715         /* also it cannot create the delegate on a method that is not visible from it's (caller) point of view */
716         if (!check_method_access (caller, method)) {
717                 mono_raise_exception (get_method_access_exception (
718                         "Transparent method %s cannot create a delegate on private/internal method %s.", 
719                         caller, method));
720         }
721
722         return TRUE;
723 }
724
725 /*
726  * mono_security_core_clr_ensure_dynamic_method_resolved_object:
727  *
728  *      Called from mono_reflection_create_dynamic_method (reflection.c) to add some extra checks required for CoreCLR.
729  *      Dynamic methods needs to check to see if the objects being used (e.g. methods, fields) comes from platform code
730  *      and do an accessibility check in this case. Otherwise (i.e. user/application code) can be used without this extra
731  *      accessbility check.
732  */
733 MonoException*
734 mono_security_core_clr_ensure_dynamic_method_resolved_object (gpointer ref, MonoClass *handle_class)
735 {
736         /* XXX find/create test cases for other handle_class XXX */
737         if (handle_class == mono_defaults.fieldhandle_class) {
738                 MonoClassField *field = (MonoClassField*) ref;
739                 MonoClass *klass = mono_field_get_parent (field);
740                 /* fields coming from platform code have extra protection (accessibility check) */
741                 if (mono_security_core_clr_is_platform_image (klass->image)) {
742                         MonoMethod *caller = get_reflection_caller ();
743                         /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
744                         if (!check_field_access (caller, field)) {
745                                 return get_field_access_exception (
746                                         "Dynamic method %s cannot create access private/internal field %s.", 
747                                         caller, field);
748                         }
749                 }
750         } else if (handle_class == mono_defaults.methodhandle_class) {
751                 MonoMethod *method = (MonoMethod*) ref;
752                 /* methods coming from platform code have extra protection (accessibility check) */
753                 if (mono_security_core_clr_is_platform_image (method->klass->image)) {
754                         MonoMethod *caller = get_reflection_caller ();
755                         /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
756                         if (!check_method_access (caller, method)) {
757                                 return get_method_access_exception (
758                                         "Dynamic method %s cannot create access private/internal method %s.", 
759                                         caller, method);
760                         }
761                 }
762         }
763         return NULL;
764 }
765
766 /*
767  * mono_security_core_clr_can_access_internals
768  *
769  *      Check if we allow [InternalsVisibleTo] to work between two images.
770  */
771 gboolean
772 mono_security_core_clr_can_access_internals (MonoImage *accessing, MonoImage* accessed)
773 {
774         /* are we trying to access internals of a platform assembly ? if not this is acceptable */
775         if (!mono_security_core_clr_is_platform_image (accessed))
776                 return TRUE;
777
778         /* we can't let everyone with the right name and public key token access the internals of platform code.
779          * (Silverlight can rely on the strongname signature of the assemblies, but Mono does not verify them)
780          * However platform code is fully trusted so it can access the internals of other platform code assemblies */
781         if (mono_security_core_clr_is_platform_image (accessing))
782                 return TRUE;
783
784         /* catch-22: System.Xml needs access to mscorlib's internals (e.g. ArrayList) but is not considered platform code.
785          * Promoting it to platform code would create another issue since (both Mono/Moonlight or MS version of) 
786          * System.Xml.Linq.dll (an SDK, not platform, assembly) needs access to System.Xml.dll internals (either ). 
787          * The solution is to trust, even transparent code, in the plugin directory to access platform code internals */
788         if (!accessed->assembly->basedir || !accessing->assembly->basedir)
789                 return FALSE;
790         return (strcmp (accessed->assembly->basedir, accessing->assembly->basedir) == 0);
791 }
792
793 /*
794  * mono_security_core_clr_is_field_access_allowed
795  *
796  *      Return a MonoException (FieldccessException in managed-land) if
797  *      the access from "caller" to "field" is not valid under CoreCLR -
798  *      i.e. a [SecurityTransparent] method calling a [SecurityCritical]
799  *      field.
800  */
801 MonoException*
802 mono_security_core_clr_is_field_access_allowed (MonoMethod *caller, MonoClassField *field)
803 {
804         /* there's no restriction to access Transparent or SafeCritical fields, so we only check calls to Critical methods */
805         if (mono_security_core_clr_class_level (mono_field_get_parent (field)) != MONO_SECURITY_CORE_CLR_CRITICAL)
806                 return NULL;
807
808         /* caller is Critical! only SafeCritical and Critical callers can access the field, so we throw if caller is Transparent */
809         if (!caller || (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT))
810                 return NULL;
811
812         return get_field_access_exception (
813                 "Transparent method %s cannot call use Critical field %s.", 
814                 caller, field);
815 }
816
817 /*
818  * mono_security_core_clr_is_call_allowed
819  *
820  *      Return a MonoException (MethodAccessException in managed-land) if
821  *      the call from "caller" to "callee" is not valid under CoreCLR -
822  *      i.e. a [SecurityTransparent] method calling a [SecurityCritical]
823  *      method.
824  */
825 MonoException*
826 mono_security_core_clr_is_call_allowed (MonoMethod *caller, MonoMethod *callee)
827 {
828         /* there's no restriction to call Transparent or SafeCritical code, so we only check calls to Critical methods */
829         if (mono_security_core_clr_method_level (callee, TRUE) != MONO_SECURITY_CORE_CLR_CRITICAL)
830                 return NULL;
831
832         /* callee is Critical! only SafeCritical and Critical callers can call it, so we throw if the caller is Transparent */
833         if (!caller || (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT))
834                 return NULL;
835
836         return get_method_access_exception (
837                 "Transparent method %s cannot call Critical method %s.", 
838                 caller, callee);
839 }
840
841 /*
842  * mono_security_core_clr_level_from_cinfo:
843  *
844  *      Return the MonoSecurityCoreCLRLevel that match the attribute located
845  *      in the specified custom attributes. If no attribute is present it 
846  *      defaults to MONO_SECURITY_CORE_CLR_TRANSPARENT, which is the default
847  *      level for all code under the CoreCLR.
848  */
849 static MonoSecurityCoreCLRLevel
850 mono_security_core_clr_level_from_cinfo (MonoCustomAttrInfo *cinfo, MonoImage *image)
851 {
852         int level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
853
854         if (cinfo && mono_custom_attrs_has_attr (cinfo, security_safe_critical_attribute ()))
855                 level = MONO_SECURITY_CORE_CLR_SAFE_CRITICAL;
856         if (cinfo && mono_custom_attrs_has_attr (cinfo, security_critical_attribute ()))
857                 level = MONO_SECURITY_CORE_CLR_CRITICAL;
858
859         return level;
860 }
861
862 /*
863  * mono_security_core_clr_class_level_no_platform_check:
864  *
865  *      Return the MonoSecurityCoreCLRLevel for the specified class, without 
866  *      checking for platform code. This help us avoid multiple redundant 
867  *      checks, e.g.
868  *      - a check for the method and one for the class;
869  *      - a check for the class and outer class(es) ...
870  */
871 static MonoSecurityCoreCLRLevel
872 mono_security_core_clr_class_level_no_platform_check (MonoClass *class)
873 {
874         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
875         MonoCustomAttrInfo *cinfo = mono_custom_attrs_from_class (class);
876         if (cinfo) {
877                 level = mono_security_core_clr_level_from_cinfo (cinfo, class->image);
878                 mono_custom_attrs_free (cinfo);
879         }
880
881         if (level == MONO_SECURITY_CORE_CLR_TRANSPARENT && class->nested_in)
882                 level = mono_security_core_clr_class_level_no_platform_check (class->nested_in);
883
884         return level;
885 }
886
887 /*
888  * mono_security_core_clr_class_level:
889  *
890  *      Return the MonoSecurityCoreCLRLevel for the specified class.
891  */
892 MonoSecurityCoreCLRLevel
893 mono_security_core_clr_class_level (MonoClass *class)
894 {
895         /* non-platform code is always Transparent - whatever the attributes says */
896         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (class->image))
897                 return MONO_SECURITY_CORE_CLR_TRANSPARENT;
898
899         return mono_security_core_clr_class_level_no_platform_check (class);
900 }
901
902 /*
903  * mono_security_core_clr_method_level:
904  *
905  *      Return the MonoSecurityCoreCLRLevel for the specified method.
906  *      If with_class_level is TRUE then the type (class) will also be
907  *      checked, otherwise this will only report the information about
908  *      the method itself.
909  */
910 MonoSecurityCoreCLRLevel
911 mono_security_core_clr_method_level (MonoMethod *method, gboolean with_class_level)
912 {
913         MonoCustomAttrInfo *cinfo;
914         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
915
916         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
917         if (!method)
918                 return level;
919
920         /* non-platform code is always Transparent - whatever the attributes says */
921         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (method->klass->image))
922                 return level;
923
924         cinfo = mono_custom_attrs_from_method (method);
925         if (cinfo) {
926                 level = mono_security_core_clr_level_from_cinfo (cinfo, method->klass->image);
927                 mono_custom_attrs_free (cinfo);
928         }
929
930         if (with_class_level && level == MONO_SECURITY_CORE_CLR_TRANSPARENT)
931                 level = mono_security_core_clr_class_level (method->klass);
932
933         return level;
934 }
935
936 /*
937  * mono_security_core_clr_is_platform_image:
938  *
939  *   Return the (cached) boolean value indicating if this image represent platform code
940  */
941 gboolean
942 mono_security_core_clr_is_platform_image (MonoImage *image)
943 {
944         return image->core_clr_platform_code;
945 }
946
947 /*
948  * default_platform_check:
949  *
950  *      Default platform check. Always TRUE for current corlib (minimum 
951  *      trust-able subset) otherwise return FALSE. Any real CoreCLR host
952  *      should provide its own callback to define platform code (i.e.
953  *      this default is meant for test only).
954  */
955 static gboolean
956 default_platform_check (const char *image_name)
957 {
958         if (mono_defaults.corlib) {
959                 return (strcmp (mono_defaults.corlib->name, image_name) == 0);
960         } else {
961                 /* this can get called even before we load corlib (e.g. the EXE itself) */
962                 const char *corlib = "mscorlib.dll";
963                 int ilen = strlen (image_name);
964                 int clen = strlen (corlib);
965                 return ((ilen >= clen) && (strcmp ("mscorlib.dll", image_name + ilen - clen) == 0));
966         }
967 }
968
969 static MonoCoreClrPlatformCB platform_callback = default_platform_check;
970
971 /*
972  * mono_security_core_clr_determine_platform_image:
973  *
974  *      Call the supplied callback (from mono_security_set_core_clr_platform_callback) 
975  *      to determine if this image represents platform code.
976  */
977 gboolean
978 mono_security_core_clr_determine_platform_image (MonoImage *image)
979 {
980         return platform_callback (image->name);
981 }
982
983 /*
984  * mono_security_enable_core_clr:
985  *
986  *   Enable the verifier and the CoreCLR security model
987  */
988 void
989 mono_security_enable_core_clr ()
990 {
991         mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
992         mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
993 }
994
995 /*
996  * mono_security_set_core_clr_platform_callback:
997  *
998  *      Set the callback function that will be used to determine if an image
999  *      is part, or not, of the platform code.
1000  */
1001 void
1002 mono_security_set_core_clr_platform_callback (MonoCoreClrPlatformCB callback)
1003 {
1004         platform_callback = callback;
1005 }
1006