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