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