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