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