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