[runtime] Call error_init instead of mono_error_init (#4425)
[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  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
10  */
11
12 #include <mono/metadata/class-internals.h>
13 #include <mono/metadata/security-manager.h>
14 #include <mono/metadata/assembly.h>
15 #include <mono/metadata/appdomain.h>
16 #include <mono/metadata/verify-internals.h>
17 #include <mono/metadata/object.h>
18 #include <mono/metadata/exception.h>
19 #include <mono/metadata/debug-helpers.h>
20 #include <mono/utils/mono-logger-internals.h>
21
22 #include "security-core-clr.h"
23
24 gboolean mono_security_core_clr_test = FALSE;
25
26 static MonoSecurityCoreCLROptions security_core_clr_options = MONO_SECURITY_CORE_CLR_OPTIONS_DEFAULT;
27
28 /**
29  * mono_security_core_clr_set_options:
30  * @options: the new options for the coreclr system to use
31  *
32  * By default, the CoreCLRs security model forbids execution trough reflection of methods not visible from the calling code.
33  * Even if the method being called is not in a platform assembly. For non moonlight CoreCLR users this restriction does not
34  * make a lot of sense, since the author could have just changed the non platform assembly to allow the method to be called.
35  * This function allows specific relaxations from the default behaviour to be set.
36  *
37  * Use MONO_SECURITY_CORE_CLR_OPTIONS_DEFAULT for the default coreclr coreclr behaviour as used in Moonlight.
38  *
39  * Use MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_REFLECTION to allow transparent code to execute methods and access 
40  * fields that are not in platformcode, even if those methods and fields are private or otherwise not visible to the calling code.
41  *
42  * Use MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_DELEGATE to allow delegates to be created that point at methods that are not in
43  * platformcode even if those methods and fields are private or otherwise not visible to the calling code.
44  *
45  */
46 void
47 mono_security_core_clr_set_options (MonoSecurityCoreCLROptions options) {
48         security_core_clr_options = options;
49 }
50
51 /**
52  * mono_security_core_clr_get_options:
53  *
54  * Retrieves the current options used by the coreclr system.
55  */
56
57 MonoSecurityCoreCLROptions
58 mono_security_core_clr_get_options ()
59 {
60         return security_core_clr_options;
61 }
62
63 /*
64  * default_platform_check:
65  *
66  *      Default platform check. Always TRUE for current corlib (minimum 
67  *      trust-able subset) otherwise return FALSE. Any real CoreCLR host
68  *      should provide its own callback to define platform code (i.e.
69  *      this default is meant for test only).
70  */
71 static gboolean
72 default_platform_check (const char *image_name)
73 {
74         if (mono_defaults.corlib) {
75                 return (strcmp (mono_defaults.corlib->name, image_name) == 0);
76         } else {
77                 /* this can get called even before we load corlib (e.g. the EXE itself) */
78                 const char *corlib = "mscorlib.dll";
79                 int ilen = strlen (image_name);
80                 int clen = strlen (corlib);
81                 return ((ilen >= clen) && (strcmp ("mscorlib.dll", image_name + ilen - clen) == 0));
82         }
83 }
84
85 static MonoCoreClrPlatformCB platform_callback = default_platform_check;
86
87 /*
88  * mono_security_core_clr_determine_platform_image:
89  *
90  *  Call the supplied callback (from mono_security_set_core_clr_platform_callback) 
91  *  to determine if this image represents platform code.
92  */
93 gboolean
94 mono_security_core_clr_determine_platform_image (MonoImage *image)
95 {
96         return platform_callback (image->name);
97 }
98
99 /*
100  * mono_security_set_core_clr_platform_callback:
101  *
102  *  Set the callback function that will be used to determine if an image
103  *  is part, or not, of the platform code.
104  */
105 void
106 mono_security_set_core_clr_platform_callback (MonoCoreClrPlatformCB callback)
107 {
108         platform_callback = callback;
109 }
110
111 /*
112  * mono_security_core_clr_is_platform_image:
113  *
114  *   Return the (cached) boolean value indicating if this image represent platform code
115  */
116 gboolean
117 mono_security_core_clr_is_platform_image (MonoImage *image)
118 {
119         return image->core_clr_platform_code;
120 }
121
122 /* Note: The above functions are outside this guard so that the public API isn't affected. */
123
124 #ifndef DISABLE_SECURITY
125
126 /* Class lazy loading functions */
127 static GENERATE_GET_CLASS_WITH_CACHE (security_critical, "System.Security", "SecurityCriticalAttribute")
128 static GENERATE_GET_CLASS_WITH_CACHE (security_safe_critical, "System.Security", "SecuritySafeCriticalAttribute")
129
130 static MonoClass*
131 security_critical_attribute (void)
132 {
133         return mono_class_get_security_critical_class ();
134 }
135
136 static MonoClass*
137 security_safe_critical_attribute (void)
138 {
139         return mono_class_get_security_safe_critical_class ();
140
141 }
142
143 /* sometime we get a NULL (not found) caller (e.g. get_reflection_caller) */
144 static char*
145 get_method_full_name (MonoMethod * method)
146 {
147         return method ? mono_method_full_name (method, TRUE) : g_strdup ("'no caller found'");
148 }
149
150 /*
151  * set_type_load_exception_type
152  *
153  *      Set MONO_EXCEPTION_TYPE_LOAD on the specified 'class' and provide
154  *      a descriptive message for the exception. This message is also, 
155  *      optionally, being logged (export MONO_LOG_MASK="security") for
156  *      debugging purposes.
157  */
158 static void
159 set_type_load_exception_type (const char *format, MonoClass *klass)
160 {
161         char *type_name = mono_type_get_full_name (klass);
162         char *parent_name = mono_type_get_full_name (klass->parent);
163         char *message = mono_image_strdup_printf (klass->image, format, type_name, parent_name);
164
165         g_free (parent_name);
166         g_free (type_name);
167         
168         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
169         mono_class_set_type_load_failure (klass, "%s", message);
170         // note: do not free string given to mono_class_set_failure
171 }
172
173 /*
174  * set_type_load_exception_methods
175  *
176  *      Set MONO_EXCEPTION_TYPE_LOAD on the 'override' class and provide
177  *      a descriptive message for the exception. This message is also, 
178  *      optionally, being logged (export MONO_LOG_MASK="security") for
179  *      debugging purposes.
180  */
181 static void
182 set_type_load_exception_methods (const char *format, MonoMethod *override, MonoMethod *base)
183 {
184         char *method_name = get_method_full_name (override);
185         char *base_name = get_method_full_name (base);
186         char *message = mono_image_strdup_printf (override->klass->image, format, method_name, base_name);
187
188         g_free (base_name);
189         g_free (method_name);
190
191         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
192         mono_class_set_type_load_failure (override->klass, "%s", message);
193         // note: do not free string given to mono_class_set_failure
194 }
195
196 /* MonoClass is not fully initialized (inited is not yet == 1) when we 
197  * check the inheritance rules so we need to look for the default ctor
198  * ourselve to avoid recursion (and aborting)
199  */
200 static MonoMethod*
201 get_default_ctor (MonoClass *klass)
202 {
203         int i;
204
205         mono_class_setup_methods (klass);
206         if (!klass->methods)
207                 return NULL;
208
209         int mcount = mono_class_get_method_count (klass);
210         for (i = 0; i < mcount; ++i) {
211                 MonoMethodSignature *sig;
212                 MonoMethod *method = klass->methods [i];
213
214                 if (!method)
215                         continue;
216
217                 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) == 0)
218                         continue;
219                 if ((method->name[0] != '.') || strcmp (".ctor", method->name))
220                         continue;
221                 sig = mono_method_signature (method);
222                 if (sig && (sig->param_count == 0))
223                         return method;
224         }
225
226         return NULL;
227 }
228
229 /*
230  * mono_security_core_clr_check_inheritance:
231  *
232  *      Determine if the specified class can inherit from its parent using 
233  *      the CoreCLR inheritance rules.
234  *
235  *      Base Type       Allow Derived Type
236  *      ------------    ------------------
237  *      Transparent     Transparent, SafeCritical, Critical
238  *      SafeCritical    SafeCritical, Critical
239  *      Critical        Critical
240  *
241  *      Reference: http://msdn.microsoft.com/en-us/magazine/cc765416.aspx#id0190030
242  *
243  *      Furthermore a class MUST have a default constructor if its base 
244  *      class has a non-transparent, public or protected, default constructor. 
245  *      The same inheritance rule applies to both default constructors.
246  *
247  *      Reference: message from a SecurityException in SL4RC
248  *      Reference: fxcop CA2132 rule
249  */
250 void
251 mono_security_core_clr_check_inheritance (MonoClass *klass)
252 {
253         MonoSecurityCoreCLRLevel class_level, parent_level;
254         MonoClass *parent = klass->parent;
255
256         if (!parent)
257                 return;
258
259         class_level = mono_security_core_clr_class_level (klass);
260         parent_level = mono_security_core_clr_class_level (parent);
261
262         if (class_level < parent_level) {
263                 set_type_load_exception_type (
264                         "Inheritance failure for type %s. Parent class %s is more restricted.",
265                         klass);
266         } else {
267                 MonoMethod *parent_ctor = get_default_ctor (parent);
268                 if (parent_ctor && ((parent_ctor->flags & METHOD_ATTRIBUTE_PUBLIC) != 0)) {
269                         class_level = mono_security_core_clr_method_level (get_default_ctor (klass), FALSE);
270                         parent_level = mono_security_core_clr_method_level (parent_ctor, FALSE);
271                         if (class_level < parent_level) {
272                                 set_type_load_exception_type (
273                                         "Inheritance failure for type %s. Default constructor security mismatch with %s.",
274                                         klass);
275                         }
276                 }
277         }
278 }
279
280 /*
281  * mono_security_core_clr_check_override:
282  *
283  *      Determine if the specified override can "legally" override the 
284  *      specified base method using the CoreCLR inheritance rules.
285  *
286  *      Base (virtual/interface)        Allowed override
287  *      ------------------------        -------------------------
288  *      Transparent                     Transparent, SafeCritical
289  *      SafeCritical                    Transparent, SafeCritical
290  *      Critical                        Critical
291  *
292  *      Reference: http://msdn.microsoft.com/en-us/magazine/cc765416.aspx#id0190030
293  */
294 void
295 mono_security_core_clr_check_override (MonoClass *klass, MonoMethod *override, MonoMethod *base)
296 {
297         MonoSecurityCoreCLRLevel base_level = mono_security_core_clr_method_level (base, FALSE);
298         MonoSecurityCoreCLRLevel override_level = mono_security_core_clr_method_level (override, FALSE);
299         /* if the base method is decorated with [SecurityCritical] then the overrided method MUST be too */
300         if (base_level == MONO_SECURITY_CORE_CLR_CRITICAL) {
301                 if (override_level != MONO_SECURITY_CORE_CLR_CRITICAL) {
302                         set_type_load_exception_methods (
303                                 "Override failure for %s over %s. Override MUST be [SecurityCritical].",
304                                 override, base);
305                 }
306         } else {
307                 /* base is [SecuritySafeCritical] or [SecurityTransparent], override MUST NOT be [SecurityCritical] */
308                 if (override_level == MONO_SECURITY_CORE_CLR_CRITICAL) {
309                         set_type_load_exception_methods (
310                                 "Override failure for %s over %s. Override must NOT be [SecurityCritical].", 
311                                 override, base);
312                 }
313         }
314 }
315
316 /*
317  * get_caller_no_reflection_related:
318  *
319  *      Find the first managed caller that is either:
320  *      (a) located outside the platform code assemblies; or
321  *      (b) not related to reflection and delegates
322  *
323  *      Returns TRUE to stop the stackwalk, FALSE to continue to the next frame.
324  */
325 static gboolean
326 get_caller_no_reflection_related (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
327 {
328         MonoMethod **dest = (MonoMethod **)data;
329         const char *ns;
330
331         /* skip unmanaged frames */
332         if (!managed)
333                 return FALSE;
334
335         if (m->wrapper_type != MONO_WRAPPER_NONE)
336                 return FALSE;
337
338         /* quick out (any namespace not starting with an 'S' */
339         ns = m->klass->name_space;
340         if (!ns || (*ns != 'S')) {
341                 *dest = m;
342                 return TRUE;
343         }
344
345         /* stop if the method is not part of platform code */
346         if (!mono_security_core_clr_is_platform_image (m->klass->image)) {
347                 *dest = m;
348                 return TRUE;
349         }
350
351         /* any number of calls inside System.Reflection are allowed */
352         if (strcmp (ns, "System.Reflection") == 0)
353                 return FALSE;
354
355         /* any number of calls inside System.Reflection are allowed */
356         if (strcmp (ns, "System.Reflection.Emit") == 0)
357                 return FALSE;
358
359         /* calls from System.Delegate are also possible and allowed */
360         if (strcmp (ns, "System") == 0) {
361                 const char *kname = m->klass->name;
362                 if ((*kname == 'A') && (strcmp (kname, "Activator") == 0))
363                         return FALSE;
364
365                 /* unlike most Invoke* cases InvokeMember is not inside System.Reflection[.Emit] but is SecuritySafeCritical */
366                 if (((*kname == 'T') && (strcmp (kname, "Type") == 0)) || 
367                         ((*kname == 'R') && (strcmp (kname, "RuntimeType")) == 0)) {
368
369                         /* if calling InvokeMember then we can't stop the stackwalk here and need to look at the caller */
370                         if (strcmp (m->name, "InvokeMember") == 0)
371                                 return FALSE;
372                 }
373
374                 /* the security check on the delegate is made at creation time, not at invoke time */
375                 if (((*kname == 'D') && (strcmp (kname, "Delegate") == 0)) || 
376                         ((*kname == 'M') && (strcmp (kname, "MulticastDelegate")) == 0)) {
377
378                         /* if we're invoking then we can stop our stack walk */
379                         if (strcmp (m->name, "DynamicInvoke") != 0)
380                                 return FALSE;
381                 }
382         }
383
384         if (m == *dest) {
385                 *dest = NULL;
386                 return FALSE;
387         }
388
389         *dest = m;
390         return TRUE;
391 }
392
393 /*
394  * get_reflection_caller:
395  * 
396  *      Walk to the first managed method outside:
397  *      - System.Reflection* namespaces
398  *      - System.[Multicast]Delegate or Activator type
399  *      - platform code
400  *      and return a pointer to its MonoMethod.
401  *
402  *      This is required since CoreCLR checks needs to be done on this "real" caller.
403  */
404 static MonoMethod*
405 get_reflection_caller (void)
406 {
407         MonoMethod *m = NULL;
408         mono_stack_walk_no_il (get_caller_no_reflection_related, &m);
409         if (G_UNLIKELY (!m)) {
410                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "No caller outside reflection was found");
411         }
412         return m;
413 }
414
415 typedef struct {
416         int depth;
417         MonoMethod *caller;
418 } ElevatedTrustCookie;
419
420 /*
421  * get_caller_of_elevated_trust_code
422  *
423  *      Stack walk to find who is calling code requiring Elevated Trust.
424  *      If a critical method is found then the caller is platform code
425  *      and has elevated trust, otherwise (transparent) a check needs to
426  *      be done (on the managed side) to determine if the application is
427  *      running with elevated permissions.
428  */
429 static gboolean
430 get_caller_of_elevated_trust_code (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
431 {
432         ElevatedTrustCookie *cookie = (ElevatedTrustCookie *)data;
433
434         /* skip unmanaged frames and wrappers */
435         if (!managed || (m->wrapper_type != MONO_WRAPPER_NONE))
436                 return FALSE;
437
438         /* end stack walk if we find ourselves outside platform code (we won't find critical code anymore) */
439         if (!mono_security_core_clr_is_platform_image (m->klass->image)) {
440                 cookie->caller = m;
441                 return TRUE;
442         }
443
444         switch (cookie->depth) {
445         /* while depth == 0 look for SecurityManager::[Check|Ensure]ElevatedPermissions */
446         case 0:
447                 if (strcmp (m->klass->name_space, "System.Security"))
448                         return FALSE;
449                 if (strcmp (m->klass->name, "SecurityManager"))
450                         return FALSE;
451                 if ((strcmp (m->name, "EnsureElevatedPermissions")) && strcmp (m->name, "CheckElevatedPermissions"))
452                         return FALSE;
453                 cookie->depth = 1;
454                 break;
455         /* while depth == 1 look for the caller to SecurityManager::[Check|Ensure]ElevatedPermissions */
456         case 1:
457                 /* this frame is [SecuritySafeCritical] because it calls [SecurityCritical] [Check|Ensure]ElevatedPermissions */
458                 /* the next frame will contain the caller(s) we want to check */
459                 cookie->depth = 2;
460                 break;
461         /* while depth >= 2 look for [safe]critical caller, end stack walk if we find it  */
462         default:
463                 cookie->depth++;
464                 /* if the caller is transparent then we continue the stack walk */
465                 if (mono_security_core_clr_method_level (m, TRUE) == MONO_SECURITY_CORE_CLR_TRANSPARENT)
466                         break;
467
468                 /* Security[Safe]Critical code is always allowed to call elevated-trust code */
469                 cookie->caller = m;
470                 return TRUE;
471         }
472
473         return FALSE;
474 }
475
476 /*
477  * mono_security_core_clr_require_elevated_permissions:
478  *
479  *      Return TRUE if the caller of the current method (the code who 
480  *      called SecurityManager.get_RequiresElevatedPermissions) needs
481  *      elevated trust to perform an action.
482  *
483  *      A stack walk is done to find the callers. If one of the callers
484  *      is either [SecurityCritical] or [SecuritySafeCritical] then the
485  *      action is needed for platform code (i.e. no restriction). 
486  *      Otherwise (transparent) the requested action needs elevated trust
487  */
488 gboolean
489 mono_security_core_clr_require_elevated_permissions (void)
490 {
491         ElevatedTrustCookie cookie;
492         cookie.depth = 0;
493         cookie.caller = NULL;
494         mono_stack_walk_no_il (get_caller_of_elevated_trust_code, &cookie);
495
496         /* return TRUE if the stack walk did not reach far enough or did not find callers */
497         if (!cookie.caller || cookie.depth < 3)
498                 return TRUE;
499
500         /* return TRUE if the caller is transparent, i.e. if elevated trust is required to continue executing the method */
501         return (mono_security_core_clr_method_level (cookie.caller, TRUE) == MONO_SECURITY_CORE_CLR_TRANSPARENT);
502 }
503
504
505 /*
506  * check_field_access:
507  *
508  *      Return TRUE if the caller method can access the specified field, FALSE otherwise.
509  */
510 static gboolean
511 check_field_access (MonoMethod *caller, MonoClassField *field)
512 {
513         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
514         if (caller) {
515                 MonoError error;
516                 MonoClass *klass;
517
518                 /* this check can occur before the field's type is resolved (and that can fail) */
519                 mono_field_get_type_checked (field, &error);
520                 if (!mono_error_ok (&error)) {
521                         mono_error_cleanup (&error);
522                         return FALSE;
523                 }
524
525                 klass = (mono_field_get_flags (field) & FIELD_ATTRIBUTE_STATIC) ? NULL : mono_field_get_parent (field);
526                 return mono_method_can_access_field_full (caller, field, klass);
527         }
528         return FALSE;
529 }
530
531 /*
532  * check_method_access:
533  *
534  *      Return TRUE if the caller method can access the specified callee method, FALSE otherwise.
535  */
536 static gboolean
537 check_method_access (MonoMethod *caller, MonoMethod *callee)
538 {
539         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
540         if (caller) {
541                 MonoClass *klass = (callee->flags & METHOD_ATTRIBUTE_STATIC) ? NULL : callee->klass;
542                 return mono_method_can_access_method_full (caller, callee, klass);
543         }
544         return FALSE;
545 }
546
547 /*
548  * get_argument_exception
549  *
550  *      Helper function to create an MonoException (ArgumentException in
551  *      managed-land) and provide a descriptive message for it. This 
552  *      message is also, optionally, being logged (export 
553  *      MONO_LOG_MASK="security") for debugging purposes.
554  */
555 static MonoException*
556 get_argument_exception (const char *format, MonoMethod *caller, MonoMethod *callee)
557 {
558         MonoException *ex;
559         char *caller_name = get_method_full_name (caller);
560         char *callee_name = get_method_full_name (callee);
561         char *message = g_strdup_printf (format, caller_name, callee_name);
562         g_free (callee_name);
563         g_free (caller_name);
564
565         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
566         ex = mono_get_exception_argument ("method", message);
567         g_free (message);
568
569         return ex;
570 }
571
572 /*
573  * get_field_access_exception
574  *
575  *      Helper function to create an MonoException (FieldAccessException
576  *      in managed-land) and provide a descriptive message for it. This
577  *      message is also, optionally, being logged (export 
578  *      MONO_LOG_MASK="security") for debugging purposes.
579  */
580 static MonoException*
581 get_field_access_exception (const char *format, MonoMethod *caller, MonoClassField *field)
582 {
583         MonoException *ex;
584         char *caller_name = get_method_full_name (caller);
585         char *field_name = mono_field_full_name (field);
586         char *message = g_strdup_printf (format, caller_name, field_name);
587         g_free (field_name);
588         g_free (caller_name);
589
590         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
591         ex = mono_get_exception_field_access_msg (message);
592         g_free (message);
593
594         return ex;
595 }
596
597 /*
598  * get_method_access_exception
599  *
600  *      Helper function to create an MonoException (MethodAccessException
601  *      in managed-land) and provide a descriptive message for it. This
602  *      message is also, optionally, being logged (export 
603  *      MONO_LOG_MASK="security") for debugging purposes.
604  */
605 static MonoException*
606 get_method_access_exception (const char *format, MonoMethod *caller, MonoMethod *callee)
607 {
608         MonoException *ex;
609         char *caller_name = get_method_full_name (caller);
610         char *callee_name = get_method_full_name (callee);
611         char *message = g_strdup_printf (format, caller_name, callee_name);
612         g_free (callee_name);
613         g_free (caller_name);
614
615         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
616         ex = mono_get_exception_method_access_msg (message);
617         g_free (message);
618
619         return ex;
620 }
621
622 /*
623  * mono_security_core_clr_ensure_reflection_access_field:
624  *
625  *      Ensure that the specified field can be used with reflection since 
626  *      Transparent code cannot access to Critical fields and can only use
627  *      them if they are visible from it's point of view.
628  *
629  *      Returns TRUE if acess is allowed.  Otherwise returns FALSE and sets @error to a FieldAccessException if the field is cannot be accessed.
630  */
631 gboolean
632 mono_security_core_clr_ensure_reflection_access_field (MonoClassField *field, MonoError *error)
633 {
634         error_init (error);
635         MonoMethod *caller = get_reflection_caller ();
636         /* CoreCLR restrictions applies to Transparent code/caller */
637         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
638                 return TRUE;
639
640         if (mono_security_core_clr_get_options () & MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_REFLECTION) {
641                 if (!mono_security_core_clr_is_platform_image (mono_field_get_parent(field)->image))
642                         return TRUE;
643         }
644
645         /* Transparent code cannot [get|set]value on Critical fields */
646         if (mono_security_core_clr_class_level (mono_field_get_parent (field)) == MONO_SECURITY_CORE_CLR_CRITICAL) {
647                 mono_error_set_exception_instance (error, get_field_access_exception (
648                         "Transparent method %s cannot get or set Critical field %s.", 
649                         caller, field));
650                 return FALSE;
651         }
652
653         /* also it cannot access a fields that is not visible from it's (caller) point of view */
654         if (!check_field_access (caller, field)) {
655                 mono_error_set_exception_instance (error, get_field_access_exception (
656                         "Transparent method %s cannot get or set private/internal field %s.", 
657                         caller, field));
658                 return FALSE;
659         }
660         return TRUE;
661 }
662
663 /*
664  * mono_security_core_clr_ensure_reflection_access_method:
665  *
666  *      Ensure that the specified method can be used with reflection since
667  *      Transparent code cannot call Critical methods and can only call them
668  *      if they are visible from it's point of view.
669  *
670  *      If access is allowed returns TRUE.  Returns FALSE and sets @error to a MethodAccessException if the field is cannot be accessed.
671  */
672 gboolean
673 mono_security_core_clr_ensure_reflection_access_method (MonoMethod *method, MonoError *error)
674 {
675         error_init (error);
676         MonoMethod *caller = get_reflection_caller ();
677         /* CoreCLR restrictions applies to Transparent code/caller */
678         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
679                 return TRUE;
680
681         if (mono_security_core_clr_get_options () & MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_REFLECTION) {
682                 if (!mono_security_core_clr_is_platform_image (method->klass->image))
683                         return TRUE;
684         }
685
686         /* Transparent code cannot invoke, even using reflection, Critical code */
687         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
688                 mono_error_set_exception_instance (error, get_method_access_exception (
689                         "Transparent method %s cannot invoke Critical method %s.", 
690                         caller, method));
691                 return FALSE;
692         }
693
694         /* also it cannot invoke a method that is not visible from it's (caller) point of view */
695         if (!check_method_access (caller, method)) {
696                 mono_error_set_exception_instance (error, get_method_access_exception (
697                         "Transparent method %s cannot invoke private/internal method %s.", 
698                         caller, method));
699                 return FALSE;
700         }
701         return TRUE;
702 }
703
704 /*
705  * can_avoid_corlib_reflection_delegate_optimization:
706  *
707  *      Mono's mscorlib use delegates to optimize PropertyInfo and EventInfo
708  *      reflection calls. This requires either a bunch of additional, and not
709  *      really required, [SecuritySafeCritical] in the class libraries or 
710  *      (like this) a way to skip them. As a bonus we also avoid the stack
711  *      walk to find the caller.
712  *
713  *      Return TRUE if we can skip this "internal" delegate creation, FALSE
714  *      otherwise.
715  */
716 static gboolean
717 can_avoid_corlib_reflection_delegate_optimization (MonoMethod *method)
718 {
719         if (!mono_security_core_clr_is_platform_image (method->klass->image))
720                 return FALSE;
721
722         if (strcmp (method->klass->name_space, "System.Reflection") != 0)
723                 return FALSE;
724
725         if (strcmp (method->klass->name, "MonoProperty") == 0) {
726                 if ((strcmp (method->name, "GetterAdapterFrame") == 0) || strcmp (method->name, "StaticGetterAdapterFrame") == 0)
727                         return TRUE;
728         } else if (strcmp (method->klass->name, "EventInfo") == 0) {
729                 if ((strcmp (method->name, "AddEventFrame") == 0) || strcmp (method->name, "StaticAddEventAdapterFrame") == 0)
730                         return TRUE;
731         }
732
733         return FALSE;
734 }
735
736 /*
737  * mono_security_core_clr_ensure_delegate_creation:
738  *
739  *      Return TRUE if a delegate can be created on the specified
740  *      method.  CoreCLR can also affect the binding, this function may
741  *      return (FALSE) and set @error to an ArgumentException.
742  *
743  *      @error is set to a MethodAccessException 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, MonoError *error)
748 {
749         MonoMethod *caller;
750
751         error_init (error);
752
753         /* note: mscorlib creates delegates to avoid reflection (optimization), we ignore those cases */
754         if (can_avoid_corlib_reflection_delegate_optimization (method))
755                 return TRUE;
756
757         caller = get_reflection_caller ();
758         /* if the "real" caller is not Transparent then it do can anything */
759         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
760                 return TRUE;
761
762         /* otherwise it (as a Transparent caller) cannot create a delegate on a Critical method... */
763         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
764                 mono_error_set_exception_instance (error, get_argument_exception (
765                         "Transparent method %s cannot create a delegate on Critical method %s.", 
766                         caller, method));
767                 return FALSE;
768         }
769
770         if (mono_security_core_clr_get_options () & MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_DELEGATE) {
771                 if (!mono_security_core_clr_is_platform_image (method->klass->image))
772                         return TRUE;
773         }
774
775         /* also it cannot create the delegate on a method that is not visible from it's (caller) point of view */
776         if (!check_method_access (caller, method)) {
777                 mono_error_set_exception_instance (error, get_method_access_exception (
778                         "Transparent method %s cannot create a delegate on private/internal method %s.", 
779                         caller, method));
780                 return FALSE;
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 (MonoSecurityCoreCLRLevel)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 gboolean
1062 mono_security_core_clr_ensure_reflection_access_field (MonoClassField *field, MonoError *error)
1063 {
1064         error_init (error);
1065         return TRUE;
1066 }
1067
1068 gboolean
1069 mono_security_core_clr_ensure_reflection_access_method (MonoMethod *method, MonoError *error)
1070 {
1071         error_init (error);
1072         return TRUE;
1073 }
1074
1075 gboolean
1076 mono_security_core_clr_ensure_delegate_creation (MonoMethod *method, MonoError *error)
1077 {
1078         error_init (error);
1079         return TRUE;
1080 }
1081
1082 MonoException*
1083 mono_security_core_clr_ensure_dynamic_method_resolved_object (gpointer ref, MonoClass *handle_class)
1084 {
1085         return NULL;
1086 }
1087
1088 gboolean
1089 mono_security_core_clr_can_access_internals (MonoImage *accessing, MonoImage* accessed)
1090 {
1091         return TRUE;
1092 }
1093
1094 MonoException*
1095 mono_security_core_clr_is_field_access_allowed (MonoMethod *caller, MonoClassField *field)
1096 {
1097         return NULL;
1098 }
1099
1100 MonoException*
1101 mono_security_core_clr_is_call_allowed (MonoMethod *caller, MonoMethod *callee)
1102 {
1103         return NULL;
1104 }
1105
1106 MonoSecurityCoreCLRLevel
1107 mono_security_core_clr_class_level (MonoClass *klass)
1108 {
1109         return MONO_SECURITY_CORE_CLR_TRANSPARENT;
1110 }
1111
1112 MonoSecurityCoreCLRLevel
1113 mono_security_core_clr_field_level (MonoClassField *field, gboolean with_class_level)
1114 {
1115         return MONO_SECURITY_CORE_CLR_TRANSPARENT;
1116 }
1117
1118 MonoSecurityCoreCLRLevel
1119 mono_security_core_clr_method_level (MonoMethod *method, gboolean with_class_level)
1120 {
1121         return MONO_SECURITY_CORE_CLR_TRANSPARENT;
1122 }
1123
1124 void
1125 mono_security_enable_core_clr ()
1126 {
1127 }
1128
1129 #endif /* DISABLE_SECURITY */