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