First set of licensing changes
[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  *      A FieldAccessException is thrown if the field is cannot be accessed.
629  */
630 void
631 mono_security_core_clr_ensure_reflection_access_field (MonoClassField *field)
632 {
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;
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;
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_raise_exception (get_field_access_exception (
646                         "Transparent method %s cannot get or set Critical field %s.", 
647                         caller, field));
648         }
649
650         /* also it cannot access a fields that is not visible from it's (caller) point of view */
651         if (!check_field_access (caller, field)) {
652                 mono_raise_exception (get_field_access_exception (
653                         "Transparent method %s cannot get or set private/internal field %s.", 
654                         caller, field));
655         }
656 }
657
658 /*
659  * mono_security_core_clr_ensure_reflection_access_method:
660  *
661  *      Ensure that the specified method can be used with reflection since
662  *      Transparent code cannot call Critical methods and can only call them
663  *      if they are visible from it's point of view.
664  *
665  *      A MethodAccessException is thrown if the field is cannot be accessed.
666  */
667 void
668 mono_security_core_clr_ensure_reflection_access_method (MonoMethod *method)
669 {
670         MonoMethod *caller = get_reflection_caller ();
671         /* CoreCLR restrictions applies to Transparent code/caller */
672         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
673                 return;
674
675         if (mono_security_core_clr_get_options () & MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_REFLECTION) {
676                 if (!mono_security_core_clr_is_platform_image (method->klass->image))
677                         return;
678         }
679
680         /* Transparent code cannot invoke, even using reflection, Critical code */
681         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
682                 mono_raise_exception (get_method_access_exception (
683                         "Transparent method %s cannot invoke Critical method %s.", 
684                         caller, method));
685         }
686
687         /* also it cannot invoke a method that is not visible from it's (caller) point of view */
688         if (!check_method_access (caller, method)) {
689                 mono_raise_exception (get_method_access_exception (
690                         "Transparent method %s cannot invoke private/internal method %s.", 
691                         caller, method));
692         }
693 }
694
695 /*
696  * can_avoid_corlib_reflection_delegate_optimization:
697  *
698  *      Mono's mscorlib use delegates to optimize PropertyInfo and EventInfo
699  *      reflection calls. This requires either a bunch of additional, and not
700  *      really required, [SecuritySafeCritical] in the class libraries or 
701  *      (like this) a way to skip them. As a bonus we also avoid the stack
702  *      walk to find the caller.
703  *
704  *      Return TRUE if we can skip this "internal" delegate creation, FALSE
705  *      otherwise.
706  */
707 static gboolean
708 can_avoid_corlib_reflection_delegate_optimization (MonoMethod *method)
709 {
710         if (!mono_security_core_clr_is_platform_image (method->klass->image))
711                 return FALSE;
712
713         if (strcmp (method->klass->name_space, "System.Reflection") != 0)
714                 return FALSE;
715
716         if (strcmp (method->klass->name, "MonoProperty") == 0) {
717                 if ((strcmp (method->name, "GetterAdapterFrame") == 0) || strcmp (method->name, "StaticGetterAdapterFrame") == 0)
718                         return TRUE;
719         } else if (strcmp (method->klass->name, "EventInfo") == 0) {
720                 if ((strcmp (method->name, "AddEventFrame") == 0) || strcmp (method->name, "StaticAddEventAdapterFrame") == 0)
721                         return TRUE;
722         }
723
724         return FALSE;
725 }
726
727 /*
728  * mono_security_core_clr_ensure_delegate_creation:
729  *
730  *      Return TRUE if a delegate can be created on the specified method. 
731  *      CoreCLR also affect the binding, so throwOnBindFailure must be 
732  *      FALSE to let this function return (FALSE) normally, otherwise (if
733  *      throwOnBindFailure is TRUE) it will throw an ArgumentException.
734  *
735  *      A MethodAccessException is thrown if the specified method is not
736  *      visible from the caller point of view.
737  */
738 gboolean
739 mono_security_core_clr_ensure_delegate_creation (MonoMethod *method, gboolean throwOnBindFailure)
740 {
741         MonoMethod *caller;
742
743         /* note: mscorlib creates delegates to avoid reflection (optimization), we ignore those cases */
744         if (can_avoid_corlib_reflection_delegate_optimization (method))
745                 return TRUE;
746
747         caller = get_reflection_caller ();
748         /* if the "real" caller is not Transparent then it do can anything */
749         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
750                 return TRUE;
751
752         /* otherwise it (as a Transparent caller) cannot create a delegate on a Critical method... */
753         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
754                 /* but this throws only if 'throwOnBindFailure' is TRUE */
755                 if (!throwOnBindFailure)
756                         return FALSE;
757
758                 mono_raise_exception (get_argument_exception (
759                         "Transparent method %s cannot create a delegate on Critical method %s.", 
760                         caller, method));
761         }
762
763         if (mono_security_core_clr_get_options () & MONO_SECURITY_CORE_CLR_OPTIONS_RELAX_DELEGATE) {
764                 if (!mono_security_core_clr_is_platform_image (method->klass->image))
765                         return TRUE;
766         }
767
768         /* also it cannot create the delegate on a method that is not visible from it's (caller) point of view */
769         if (!check_method_access (caller, method)) {
770                 mono_raise_exception (get_method_access_exception (
771                         "Transparent method %s cannot create a delegate on private/internal method %s.", 
772                         caller, method));
773         }
774
775         return TRUE;
776 }
777
778 /*
779  * mono_security_core_clr_ensure_dynamic_method_resolved_object:
780  *
781  *      Called from mono_reflection_create_dynamic_method (reflection.c) to add some extra checks required for CoreCLR.
782  *      Dynamic methods needs to check to see if the objects being used (e.g. methods, fields) comes from platform code
783  *      and do an accessibility check in this case. Otherwise (i.e. user/application code) can be used without this extra
784  *      accessbility check.
785  */
786 MonoException*
787 mono_security_core_clr_ensure_dynamic_method_resolved_object (gpointer ref, MonoClass *handle_class)
788 {
789         /* XXX find/create test cases for other handle_class XXX */
790         if (handle_class == mono_defaults.fieldhandle_class) {
791                 MonoClassField *field = (MonoClassField*) ref;
792                 MonoClass *klass = mono_field_get_parent (field);
793                 /* fields coming from platform code have extra protection (accessibility check) */
794                 if (mono_security_core_clr_is_platform_image (klass->image)) {
795                         MonoMethod *caller = get_reflection_caller ();
796                         /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
797                         if (!check_field_access (caller, field)) {
798                                 return get_field_access_exception (
799                                         "Dynamic method %s cannot create access private/internal field %s.", 
800                                         caller, field);
801                         }
802                 }
803         } else if (handle_class == mono_defaults.methodhandle_class) {
804                 MonoMethod *method = (MonoMethod*) ref;
805                 /* methods coming from platform code have extra protection (accessibility check) */
806                 if (mono_security_core_clr_is_platform_image (method->klass->image)) {
807                         MonoMethod *caller = get_reflection_caller ();
808                         /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
809                         if (!check_method_access (caller, method)) {
810                                 return get_method_access_exception (
811                                         "Dynamic method %s cannot create access private/internal method %s.", 
812                                         caller, method);
813                         }
814                 }
815         }
816         return NULL;
817 }
818
819 /*
820  * mono_security_core_clr_can_access_internals
821  *
822  *      Check if we allow [InternalsVisibleTo] to work between two images.
823  */
824 gboolean
825 mono_security_core_clr_can_access_internals (MonoImage *accessing, MonoImage* accessed)
826 {
827         /* are we trying to access internals of a platform assembly ? if not this is acceptable */
828         if (!mono_security_core_clr_is_platform_image (accessed))
829                 return TRUE;
830
831         /* we can't let everyone with the right name and public key token access the internals of platform code.
832          * (Silverlight can rely on the strongname signature of the assemblies, but Mono does not verify them)
833          * However platform code is fully trusted so it can access the internals of other platform code assemblies */
834         if (mono_security_core_clr_is_platform_image (accessing))
835                 return TRUE;
836
837         /* catch-22: System.Xml needs access to mscorlib's internals (e.g. ArrayList) but is not considered platform code.
838          * Promoting it to platform code would create another issue since (both Mono/Moonlight or MS version of) 
839          * System.Xml.Linq.dll (an SDK, not platform, assembly) needs access to System.Xml.dll internals (either ). 
840          * The solution is to trust, even transparent code, in the plugin directory to access platform code internals */
841         if (!accessed->assembly->basedir || !accessing->assembly->basedir)
842                 return FALSE;
843         return (strcmp (accessed->assembly->basedir, accessing->assembly->basedir) == 0);
844 }
845
846 /*
847  * mono_security_core_clr_is_field_access_allowed
848  *
849  *      Return a MonoException (FieldccessException in managed-land) if
850  *      the access from "caller" to "field" is not valid under CoreCLR -
851  *      i.e. a [SecurityTransparent] method calling a [SecurityCritical]
852  *      field.
853  */
854 MonoException*
855 mono_security_core_clr_is_field_access_allowed (MonoMethod *caller, MonoClassField *field)
856 {
857         /* there's no restriction to access Transparent or SafeCritical fields, so we only check calls to Critical methods */
858         if (mono_security_core_clr_class_level (mono_field_get_parent (field)) != MONO_SECURITY_CORE_CLR_CRITICAL)
859                 return NULL;
860
861         /* caller is Critical! only SafeCritical and Critical callers can access the field, so we throw if caller is Transparent */
862         if (!caller || (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT))
863                 return NULL;
864
865         return get_field_access_exception (
866                 "Transparent method %s cannot call use Critical field %s.", 
867                 caller, field);
868 }
869
870 /*
871  * mono_security_core_clr_is_call_allowed
872  *
873  *      Return a MonoException (MethodAccessException in managed-land) if
874  *      the call from "caller" to "callee" is not valid under CoreCLR -
875  *      i.e. a [SecurityTransparent] method calling a [SecurityCritical]
876  *      method.
877  */
878 MonoException*
879 mono_security_core_clr_is_call_allowed (MonoMethod *caller, MonoMethod *callee)
880 {
881         /* there's no restriction to call Transparent or SafeCritical code, so we only check calls to Critical methods */
882         if (mono_security_core_clr_method_level (callee, TRUE) != MONO_SECURITY_CORE_CLR_CRITICAL)
883                 return NULL;
884
885         /* callee is Critical! only SafeCritical and Critical callers can call it, so we throw if the caller is Transparent */
886         if (!caller || (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT))
887                 return NULL;
888
889         return get_method_access_exception (
890                 "Transparent method %s cannot call Critical method %s.", 
891                 caller, callee);
892 }
893
894 /*
895  * mono_security_core_clr_level_from_cinfo:
896  *
897  *      Return the MonoSecurityCoreCLRLevel that match the attribute located
898  *      in the specified custom attributes. If no attribute is present it 
899  *      defaults to MONO_SECURITY_CORE_CLR_TRANSPARENT, which is the default
900  *      level for all code under the CoreCLR.
901  */
902 static MonoSecurityCoreCLRLevel
903 mono_security_core_clr_level_from_cinfo (MonoCustomAttrInfo *cinfo, MonoImage *image)
904 {
905         int level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
906
907         if (cinfo && mono_custom_attrs_has_attr (cinfo, security_safe_critical_attribute ()))
908                 level = MONO_SECURITY_CORE_CLR_SAFE_CRITICAL;
909         if (cinfo && mono_custom_attrs_has_attr (cinfo, security_critical_attribute ()))
910                 level = MONO_SECURITY_CORE_CLR_CRITICAL;
911
912         return (MonoSecurityCoreCLRLevel)level;
913 }
914
915 /*
916  * mono_security_core_clr_class_level_no_platform_check:
917  *
918  *      Return the MonoSecurityCoreCLRLevel for the specified class, without 
919  *      checking for platform code. This help us avoid multiple redundant 
920  *      checks, e.g.
921  *      - a check for the method and one for the class;
922  *      - a check for the class and outer class(es) ...
923  */
924 static MonoSecurityCoreCLRLevel
925 mono_security_core_clr_class_level_no_platform_check (MonoClass *klass)
926 {
927         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
928         MonoCustomAttrInfo *cinfo = mono_custom_attrs_from_class (klass);
929         if (cinfo) {
930                 level = mono_security_core_clr_level_from_cinfo (cinfo, klass->image);
931                 mono_custom_attrs_free (cinfo);
932         }
933
934         if (level == MONO_SECURITY_CORE_CLR_TRANSPARENT && klass->nested_in)
935                 level = mono_security_core_clr_class_level_no_platform_check (klass->nested_in);
936
937         return level;
938 }
939
940 /*
941  * mono_security_core_clr_class_level:
942  *
943  *      Return the MonoSecurityCoreCLRLevel for the specified class.
944  */
945 MonoSecurityCoreCLRLevel
946 mono_security_core_clr_class_level (MonoClass *klass)
947 {
948         /* non-platform code is always Transparent - whatever the attributes says */
949         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (klass->image))
950                 return MONO_SECURITY_CORE_CLR_TRANSPARENT;
951
952         return mono_security_core_clr_class_level_no_platform_check (klass);
953 }
954
955 /*
956  * mono_security_core_clr_field_level:
957  *
958  *      Return the MonoSecurityCoreCLRLevel for the specified field.
959  *      If with_class_level is TRUE then the type (class) will also be
960  *      checked, otherwise this will only report the information about
961  *      the field itself.
962  */
963 MonoSecurityCoreCLRLevel
964 mono_security_core_clr_field_level (MonoClassField *field, gboolean with_class_level)
965 {
966         MonoCustomAttrInfo *cinfo;
967         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
968
969         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
970         if (!field)
971                 return level;
972
973         /* non-platform code is always Transparent - whatever the attributes says */
974         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (field->parent->image))
975                 return level;
976
977         cinfo = mono_custom_attrs_from_field (field->parent, field);
978         if (cinfo) {
979                 level = mono_security_core_clr_level_from_cinfo (cinfo, field->parent->image);
980                 mono_custom_attrs_free (cinfo);
981         }
982
983         if (with_class_level && level == MONO_SECURITY_CORE_CLR_TRANSPARENT)
984                 level = mono_security_core_clr_class_level (field->parent);
985
986         return level;
987 }
988
989 /*
990  * mono_security_core_clr_method_level:
991  *
992  *      Return the MonoSecurityCoreCLRLevel for the specified method.
993  *      If with_class_level is TRUE then the type (class) will also be
994  *      checked, otherwise this will only report the information about
995  *      the method itself.
996  */
997 MonoSecurityCoreCLRLevel
998 mono_security_core_clr_method_level (MonoMethod *method, gboolean with_class_level)
999 {
1000         MonoCustomAttrInfo *cinfo;
1001         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
1002
1003         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
1004         if (!method)
1005                 return level;
1006
1007         /* non-platform code is always Transparent - whatever the attributes says */
1008         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (method->klass->image))
1009                 return level;
1010
1011         cinfo = mono_custom_attrs_from_method (method);
1012         if (cinfo) {
1013                 level = mono_security_core_clr_level_from_cinfo (cinfo, method->klass->image);
1014                 mono_custom_attrs_free (cinfo);
1015         }
1016
1017         if (with_class_level && level == MONO_SECURITY_CORE_CLR_TRANSPARENT)
1018                 level = mono_security_core_clr_class_level (method->klass);
1019
1020         return level;
1021 }
1022
1023 /*
1024  * mono_security_enable_core_clr:
1025  *
1026  *   Enable the verifier and the CoreCLR security model
1027  */
1028 void
1029 mono_security_enable_core_clr ()
1030 {
1031         mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
1032         mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
1033 }
1034
1035 #else
1036
1037 void
1038 mono_security_core_clr_check_inheritance (MonoClass *klass)
1039 {
1040 }
1041
1042 void
1043 mono_security_core_clr_check_override (MonoClass *klass, MonoMethod *override, MonoMethod *base)
1044 {
1045 }
1046
1047 gboolean
1048 mono_security_core_clr_require_elevated_permissions (void)
1049 {
1050         return FALSE;
1051 }
1052
1053 void
1054 mono_security_core_clr_ensure_reflection_access_field (MonoClassField *field)
1055 {
1056 }
1057
1058 void
1059 mono_security_core_clr_ensure_reflection_access_method (MonoMethod *method)
1060 {
1061 }
1062
1063 gboolean
1064 mono_security_core_clr_ensure_delegate_creation (MonoMethod *method, gboolean throwOnBindFailure)
1065 {
1066         return TRUE;
1067 }
1068
1069 MonoException*
1070 mono_security_core_clr_ensure_dynamic_method_resolved_object (gpointer ref, MonoClass *handle_class)
1071 {
1072         return NULL;
1073 }
1074
1075 gboolean
1076 mono_security_core_clr_can_access_internals (MonoImage *accessing, MonoImage* accessed)
1077 {
1078         return TRUE;
1079 }
1080
1081 MonoException*
1082 mono_security_core_clr_is_field_access_allowed (MonoMethod *caller, MonoClassField *field)
1083 {
1084         return NULL;
1085 }
1086
1087 MonoException*
1088 mono_security_core_clr_is_call_allowed (MonoMethod *caller, MonoMethod *callee)
1089 {
1090         return NULL;
1091 }
1092
1093 MonoSecurityCoreCLRLevel
1094 mono_security_core_clr_class_level (MonoClass *klass)
1095 {
1096         return MONO_SECURITY_CORE_CLR_TRANSPARENT;
1097 }
1098
1099 MonoSecurityCoreCLRLevel
1100 mono_security_core_clr_field_level (MonoClassField *field, gboolean with_class_level)
1101 {
1102         return MONO_SECURITY_CORE_CLR_TRANSPARENT;
1103 }
1104
1105 MonoSecurityCoreCLRLevel
1106 mono_security_core_clr_method_level (MonoMethod *method, gboolean with_class_level)
1107 {
1108         return MONO_SECURITY_CORE_CLR_TRANSPARENT;
1109 }
1110
1111 void
1112 mono_security_enable_core_clr ()
1113 {
1114 }
1115
1116 #endif /* DISABLE_SECURITY */