Add support for ToolsVersion and correctly build msbuild+xbuild assemblies
[mono.git] / mono / metadata / security-core-clr.c
1 /*
2  * security-core-clr.c: CoreCLR security
3  *
4  * Authors:
5  *      Mark Probst <mark.probst@gmail.com>
6  *      Sebastien Pouliot  <sebastien@ximian.com>
7  *
8  * Copyright 2007-2010 Novell, Inc (http://www.novell.com)
9  */
10
11 #include <mono/metadata/class-internals.h>
12 #include <mono/metadata/security-manager.h>
13 #include <mono/metadata/assembly.h>
14 #include <mono/metadata/appdomain.h>
15 #include <mono/metadata/verify-internals.h>
16 #include <mono/metadata/object.h>
17 #include <mono/metadata/exception.h>
18 #include <mono/metadata/debug-helpers.h>
19 #include <mono/utils/mono-logger-internal.h>
20
21 #include "security-core-clr.h"
22
23 gboolean mono_security_core_clr_test = FALSE;
24
25 static MonoClass*
26 security_critical_attribute (void)
27 {
28         static MonoClass *class = NULL;
29
30         if (!class) {
31                 class = mono_class_from_name (mono_defaults.corlib, "System.Security", 
32                         "SecurityCriticalAttribute");
33         }
34         g_assert (class);
35         return class;
36 }
37
38 static MonoClass*
39 security_safe_critical_attribute (void)
40 {
41         static MonoClass *class = NULL;
42
43         if (!class) {
44                 class = mono_class_from_name (mono_defaults.corlib, "System.Security", 
45                         "SecuritySafeCriticalAttribute");
46         }
47         g_assert (class);
48         return class;
49 }
50
51 /*
52  * set_type_load_exception_type
53  *
54  *      Set MONO_EXCEPTION_TYPE_LOAD on the specified 'class' and provide
55  *      a descriptive message for the exception. This message is also, 
56  *      optionally, being logged (export MONO_LOG_MASK="security") for
57  *      debugging purposes.
58  */
59 static void
60 set_type_load_exception_type (const char *format, MonoClass *class)
61 {
62         char *type_name = mono_type_get_full_name (class);
63         char *parent_name = mono_type_get_full_name (class->parent);
64         char *message = g_strdup_printf (format, type_name, parent_name);
65
66         g_free (parent_name);
67         g_free (type_name);
68         
69         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
70         mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, message);
71         // note: do not free string given to mono_class_set_failure
72 }
73
74 /*
75  * set_type_load_exception_methods
76  *
77  *      Set MONO_EXCEPTION_TYPE_LOAD on the 'override' class and provide
78  *      a descriptive message for the exception. This message is also, 
79  *      optionally, being logged (export MONO_LOG_MASK="security") for
80  *      debugging purposes.
81  */
82 static void
83 set_type_load_exception_methods (const char *format, MonoMethod *override, MonoMethod *base)
84 {
85         char *method_name = mono_method_full_name (override, TRUE);
86         char *base_name = mono_method_full_name (base, TRUE);
87         char *message = g_strdup_printf (format, method_name, base_name);
88
89         g_free (base_name);
90         g_free (method_name);
91
92         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
93         mono_class_set_failure (override->klass, MONO_EXCEPTION_TYPE_LOAD, message);
94         // note: do not free string given to mono_class_set_failure
95 }
96
97 /* MonoClass is not fully initialized (inited is not yet == 1) when we 
98  * check the inheritance rules so we need to look for the default ctor
99  * ourselve to avoid recursion (and aborting)
100  */
101 static MonoMethod*
102 get_default_ctor (MonoClass *klass)
103 {
104         int i;
105
106         if (!klass->methods)
107                 return NULL;
108
109         for (i = 0; i < klass->method.count; ++i) {
110                 MonoMethodSignature *sig;
111                 MonoMethod *method = klass->methods [i];
112
113                 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) == 0)
114                         continue;
115                 if ((method->name[0] != '.') || strcmp (".ctor", method->name))
116                         continue;
117                 sig = mono_method_signature (method);
118                 if (sig && (sig->param_count == 0))
119                         return method;
120         }
121
122         return NULL;
123 }
124
125 /*
126  * mono_security_core_clr_check_inheritance:
127  *
128  *      Determine if the specified class can inherit from its parent using 
129  *      the CoreCLR inheritance rules.
130  *
131  *      Base Type       Allow Derived Type
132  *      ------------    ------------------
133  *      Transparent     Transparent, SafeCritical, Critical
134  *      SafeCritical    SafeCritical, Critical
135  *      Critical        Critical
136  *
137  *      Reference: http://msdn.microsoft.com/en-us/magazine/cc765416.aspx#id0190030
138  *
139  *      Furthermore a class MUST have a default constructor if its base 
140  *      class has a non-transparent default constructor. The same 
141  *      inheritance rule applies to both default constructors.
142  *
143  *      Reference: message from a SecurityException in SL4RC
144  */
145 void
146 mono_security_core_clr_check_inheritance (MonoClass *class)
147 {
148         MonoSecurityCoreCLRLevel class_level, parent_level;
149         MonoClass *parent = class->parent;
150
151         if (!parent)
152                 return;
153
154         class_level = mono_security_core_clr_class_level (class);
155         parent_level = mono_security_core_clr_class_level (parent);
156
157         if (class_level < parent_level) {
158                 set_type_load_exception_type (
159                         "Inheritance failure for type %s. Parent class %s is more restricted.",
160                         class);
161         } else {
162                 class_level = mono_security_core_clr_method_level (get_default_ctor (class), FALSE);
163                 parent_level = mono_security_core_clr_method_level (get_default_ctor (parent), FALSE);
164                 if (class_level < parent_level) {
165                         set_type_load_exception_type (
166                                 "Inheritance failure for type %s. Default constructor security mismatch with %s.",
167                                 class);
168                 }
169         }
170 }
171
172 /*
173  * mono_security_core_clr_check_override:
174  *
175  *      Determine if the specified override can "legally" override the 
176  *      specified base method using the CoreCLR inheritance rules.
177  *
178  *      Base (virtual/interface)        Allowed override
179  *      ------------------------        -------------------------
180  *      Transparent                     Transparent, SafeCritical
181  *      SafeCritical                    Transparent, SafeCritical
182  *      Critical                        Critical
183  *
184  *      Reference: http://msdn.microsoft.com/en-us/magazine/cc765416.aspx#id0190030
185  */
186 void
187 mono_security_core_clr_check_override (MonoClass *class, MonoMethod *override, MonoMethod *base)
188 {
189         MonoSecurityCoreCLRLevel base_level = mono_security_core_clr_method_level (base, FALSE);
190         MonoSecurityCoreCLRLevel override_level = mono_security_core_clr_method_level (override, FALSE);
191         /* if the base method is decorated with [SecurityCritical] then the overrided method MUST be too */
192         if (base_level == MONO_SECURITY_CORE_CLR_CRITICAL) {
193                 if (override_level != MONO_SECURITY_CORE_CLR_CRITICAL) {
194                         set_type_load_exception_methods (
195                                 "Override failure for %s over %s. Override MUST be [SecurityCritical].",
196                                 override, base);
197                 }
198         } else {
199                 /* base is [SecuritySafeCritical] or [SecurityTransparent], override MUST NOT be [SecurityCritical] */
200                 if (override_level == MONO_SECURITY_CORE_CLR_CRITICAL) {
201                         set_type_load_exception_methods (
202                                 "Override failure for %s over %s. Override must NOT be [SecurityCritical].", 
203                                 override, base);
204                 }
205         }
206 }
207
208 /*
209  * get_caller_no_reflection_related:
210  *
211  *      Find the first managed caller that is either:
212  *      (a) located outside the platform code assemblies; or
213  *      (b) not related to reflection and delegates
214  *
215  *      Returns TRUE to stop the stackwalk, FALSE to continue to the next frame.
216  */
217 static gboolean
218 get_caller_no_reflection_related (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
219 {
220         MonoMethod **dest = data;
221         const char *ns;
222
223         /* skip unmanaged frames */
224         if (!managed)
225                 return FALSE;
226
227         if (m->wrapper_type != MONO_WRAPPER_NONE)
228                 return FALSE;
229
230         /* quick out (any namespace not starting with an 'S' */
231         ns = m->klass->name_space;
232         if (!ns || (*ns != 'S')) {
233                 *dest = m;
234                 return TRUE;
235         }
236
237         /* stop if the method is not part of platform code */
238         if (!mono_security_core_clr_is_platform_image (m->klass->image)) {
239                 *dest = m;
240                 return TRUE;
241         }
242
243         /* any number of calls inside System.Reflection are allowed */
244         if (strcmp (ns, "System.Reflection") == 0)
245                 return FALSE;
246
247         /* any number of calls inside System.Reflection are allowed */
248         if (strcmp (ns, "System.Reflection.Emit") == 0)
249                 return FALSE;
250
251         /* calls from System.Delegate are also possible and allowed */
252         if (strcmp (ns, "System") == 0) {
253                 const char *kname = m->klass->name;
254                 if ((*kname == 'A') && (strcmp (kname, "Activator") == 0))
255                         return FALSE;
256
257                 /* unlike most Invoke* cases InvokeMember is not inside System.Reflection[.Emit] but is SecuritySafeCritical */
258                 if (((*kname == 'T') && (strcmp (kname, "Type") == 0)) || 
259                         ((*kname == 'M') && (strcmp (kname, "MonoType")) == 0)) {
260
261                         /* if calling InvokeMember then we can't stop the stackwalk here and need to look at the caller */
262                         if (strcmp (m->name, "InvokeMember") == 0)
263                                 return FALSE;
264                 }
265
266                 /* the security check on the delegate is made at creation time, not at invoke time */
267                 if (((*kname == 'D') && (strcmp (kname, "Delegate") == 0)) || 
268                         ((*kname == 'M') && (strcmp (kname, "MulticastDelegate")) == 0)) {
269
270                         /* if we're invoking then we can stop our stack walk */
271                         if (strcmp (m->name, "DynamicInvoke") != 0)
272                                 return FALSE;
273                 }
274         }
275
276         if (m == *dest) {
277                 *dest = NULL;
278                 return FALSE;
279         }
280
281         *dest = m;
282         return TRUE;
283 }
284
285 /*
286  * get_reflection_caller:
287  * 
288  *      Walk to the first managed method outside:
289  *      - System.Reflection* namespaces
290  *      - System.[MulticastDelegate]Delegate or Activator type
291  *      - platform code
292  *      and return a pointer to its MonoMethod.
293  *
294  *      This is required since CoreCLR checks needs to be done on this "real" caller.
295  */
296 static MonoMethod*
297 get_reflection_caller (void)
298 {
299         MonoMethod *m = NULL;
300         mono_stack_walk_no_il (get_caller_no_reflection_related, &m);
301         if (G_UNLIKELY (!m)) {
302                 mono_trace (G_LOG_LEVEL_ERROR, MONO_TRACE_SECURITY, "No caller outside reflection was found");
303         }
304         return m;
305 }
306
307 /*
308  * check_field_access:
309  *
310  *      Return TRUE if the caller method can access the specified field, FALSE otherwise.
311  */
312 static gboolean
313 check_field_access (MonoMethod *caller, MonoClassField *field)
314 {
315         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
316         if (caller) {
317                 MonoClass *klass = (mono_field_get_flags (field) & FIELD_ATTRIBUTE_STATIC) ? NULL : mono_field_get_parent (field);
318                 return mono_method_can_access_field_full (caller, field, klass);
319         }
320         return FALSE;
321 }
322
323 /*
324  * check_method_access:
325  *
326  *      Return TRUE if the caller method can access the specified callee method, FALSE otherwise.
327  */
328 static gboolean
329 check_method_access (MonoMethod *caller, MonoMethod *callee)
330 {
331         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
332         if (caller) {
333                 MonoClass *klass = (callee->flags & METHOD_ATTRIBUTE_STATIC) ? NULL : callee->klass;
334                 return mono_method_can_access_method_full (caller, callee, klass);
335         }
336         return FALSE;
337 }
338
339 /*
340  * get_argument_exception
341  *
342  *      Helper function to create an MonoException (ArgumentException in
343  *      managed-land) and provide a descriptive message for it. This 
344  *      message is also, optionally, being logged (export 
345  *      MONO_LOG_MASK="security") for debugging purposes.
346  */
347 static MonoException*
348 get_argument_exception (const char *format, MonoMethod *caller, MonoMethod *callee)
349 {
350         MonoException *ex;
351         char *caller_name = mono_method_full_name (caller, TRUE);
352         char *callee_name = mono_method_full_name (callee, TRUE);
353         char *message = g_strdup_printf (format, caller_name, callee_name);
354         g_free (callee_name);
355         g_free (caller_name);
356
357         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
358         ex = mono_get_exception_argument ("method", message);
359         g_free (message);
360
361         return ex;
362 }
363
364 /*
365  * get_field_access_exception
366  *
367  *      Helper function to create an MonoException (FieldAccessException
368  *      in managed-land) and provide a descriptive message for it. This
369  *      message is also, optionally, being logged (export 
370  *      MONO_LOG_MASK="security") for debugging purposes.
371  */
372 static MonoException*
373 get_field_access_exception (const char *format, MonoMethod *caller, MonoClassField *field)
374 {
375         MonoException *ex;
376         char *caller_name = mono_method_full_name (caller, TRUE);
377         char *field_name = mono_field_full_name (field);
378         char *message = g_strdup_printf (format, caller_name, field_name);
379         g_free (field_name);
380         g_free (caller_name);
381
382         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
383         ex = mono_get_exception_field_access_msg (message);
384         g_free (message);
385
386         return ex;
387 }
388
389 /*
390  * get_method_access_exception
391  *
392  *      Helper function to create an MonoException (MethodAccessException
393  *      in managed-land) and provide a descriptive message for it. This
394  *      message is also, optionally, being logged (export 
395  *      MONO_LOG_MASK="security") for debugging purposes.
396  */
397 static MonoException*
398 get_method_access_exception (const char *format, MonoMethod *caller, MonoMethod *callee)
399 {
400         MonoException *ex;
401         char *caller_name = mono_method_full_name (caller, TRUE);
402         char *callee_name = mono_method_full_name (callee, TRUE);
403         char *message = g_strdup_printf (format, caller_name, callee_name);
404         g_free (callee_name);
405         g_free (caller_name);
406
407         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
408         ex = mono_get_exception_method_access_msg (message);
409         g_free (message);
410
411         return ex;
412 }
413
414 /*
415  * mono_security_core_clr_ensure_reflection_access_field:
416  *
417  *      Ensure that the specified field can be used with reflection since 
418  *      Transparent code cannot access to Critical fields and can only use
419  *      them if they are visible from it's point of view.
420  *
421  *      A FieldAccessException is thrown if the field is cannot be accessed.
422  */
423 void
424 mono_security_core_clr_ensure_reflection_access_field (MonoClassField *field)
425 {
426         MonoMethod *caller = get_reflection_caller ();
427         /* CoreCLR restrictions applies to Transparent code/caller */
428         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
429                 return;
430
431         /* Transparent code cannot [get|set]value on Critical fields */
432         if (mono_security_core_clr_class_level (mono_field_get_parent (field)) == MONO_SECURITY_CORE_CLR_CRITICAL) {
433                 mono_raise_exception (get_field_access_exception (
434                         "Transparent method %s cannot get or set Critical field %s.", 
435                         caller, field));
436         }
437
438         /* also it cannot access a fields that is not visible from it's (caller) point of view */
439         if (!check_field_access (caller, field)) {
440                 mono_raise_exception (get_field_access_exception (
441                         "Transparent method %s cannot get or set private/internal field %s.", 
442                         caller, field));
443         }
444 }
445
446 /*
447  * mono_security_core_clr_ensure_reflection_access_method:
448  *
449  *      Ensure that the specified method can be used with reflection since
450  *      Transparent code cannot call Critical methods and can only call them
451  *      if they are visible from it's point of view.
452  *
453  *      A MethodAccessException is thrown if the field is cannot be accessed.
454  */
455 void
456 mono_security_core_clr_ensure_reflection_access_method (MonoMethod *method)
457 {
458         MonoMethod *caller = get_reflection_caller ();
459         /* CoreCLR restrictions applies to Transparent code/caller */
460         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
461                 return;
462
463         /* Transparent code cannot invoke, even using reflection, Critical code */
464         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
465                 mono_raise_exception (get_method_access_exception (
466                         "Transparent method %s cannot invoke Critical method %s.", 
467                         caller, method));
468         }
469
470         /* also it cannot invoke a method that is not visible from it's (caller) point of view */
471         if (!check_method_access (caller, method)) {
472                 mono_raise_exception (get_method_access_exception (
473                         "Transparent method %s cannot invoke private/internal method %s.", 
474                         caller, method));
475         }
476 }
477
478 /*
479  * can_avoid_corlib_reflection_delegate_optimization:
480  *
481  *      Mono's mscorlib use delegates to optimize PropertyInfo and EventInfo
482  *      reflection calls. This requires either a bunch of additional, and not
483  *      really required, [SecuritySafeCritical] in the class libraries or 
484  *      (like this) a way to skip them. As a bonus we also avoid the stack
485  *      walk to find the caller.
486  *
487  *      Return TRUE if we can skip this "internal" delegate creation, FALSE
488  *      otherwise.
489  */
490 static gboolean
491 can_avoid_corlib_reflection_delegate_optimization (MonoMethod *method)
492 {
493         if (!mono_security_core_clr_is_platform_image (method->klass->image))
494                 return FALSE;
495
496         if (strcmp (method->klass->name_space, "System.Reflection") != 0)
497                 return FALSE;
498
499         if (strcmp (method->klass->name, "MonoProperty") == 0) {
500                 if ((strcmp (method->name, "GetterAdapterFrame") == 0) || strcmp (method->name, "StaticGetterAdapterFrame") == 0)
501                         return TRUE;
502         } else if (strcmp (method->klass->name, "EventInfo") == 0) {
503                 if ((strcmp (method->name, "AddEventFrame") == 0) || strcmp (method->name, "StaticAddEventAdapterFrame") == 0)
504                         return TRUE;
505         }
506
507         return FALSE;
508 }
509
510 /*
511  * mono_security_core_clr_ensure_delegate_creation:
512  *
513  *      Return TRUE if a delegate can be created on the specified method. 
514  *      CoreCLR also affect the binding, so throwOnBindFailure must be 
515  *      FALSE to let this function return (FALSE) normally, otherwise (if
516  *      throwOnBindFailure is TRUE) it will throw an ArgumentException.
517  *
518  *      A MethodAccessException is thrown if the specified method is not
519  *      visible from the caller point of view.
520  */
521 gboolean
522 mono_security_core_clr_ensure_delegate_creation (MonoMethod *method, gboolean throwOnBindFailure)
523 {
524         MonoMethod *caller;
525
526         /* note: mscorlib creates delegates to avoid reflection (optimization), we ignore those cases */
527         if (can_avoid_corlib_reflection_delegate_optimization (method))
528                 return TRUE;
529
530         caller = get_reflection_caller ();
531         /* if the "real" caller is not Transparent then it do can anything */
532         if (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT)
533                 return TRUE;
534
535         /* otherwise it (as a Transparent caller) cannot create a delegate on a Critical method... */
536         if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
537                 /* but this throws only if 'throwOnBindFailure' is TRUE */
538                 if (!throwOnBindFailure)
539                         return FALSE;
540
541                 mono_raise_exception (get_argument_exception (
542                         "Transparent method %s cannot create a delegate on Critical method %s.", 
543                         caller, method));
544         }
545         
546         /* also it cannot create the delegate on a method that is not visible from it's (caller) point of view */
547         if (!check_method_access (caller, method)) {
548                 mono_raise_exception (get_method_access_exception (
549                         "Transparent method %s cannot create a delegate on private/internal method %s.", 
550                         caller, method));
551         }
552
553         return TRUE;
554 }
555
556 /*
557  * mono_security_core_clr_ensure_dynamic_method_resolved_object:
558  *
559  *      Called from mono_reflection_create_dynamic_method (reflection.c) to add some extra checks required for CoreCLR.
560  *      Dynamic methods needs to check to see if the objects being used (e.g. methods, fields) comes from platform code
561  *      and do an accessibility check in this case. Otherwise (i.e. user/application code) can be used without this extra
562  *      accessbility check.
563  */
564 MonoException*
565 mono_security_core_clr_ensure_dynamic_method_resolved_object (gpointer ref, MonoClass *handle_class)
566 {
567         /* XXX find/create test cases for other handle_class XXX */
568         if (handle_class == mono_defaults.fieldhandle_class) {
569                 MonoClassField *field = (MonoClassField*) ref;
570                 MonoClass *klass = mono_field_get_parent (field);
571                 /* fields coming from platform code have extra protection (accessibility check) */
572                 if (mono_security_core_clr_is_platform_image (klass->image)) {
573                         MonoMethod *caller = get_reflection_caller ();
574                         /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
575                         if (!check_field_access (caller, field)) {
576                                 return get_field_access_exception (
577                                         "Dynamic method %s cannot create access private/internal field %s.", 
578                                         caller, field);
579                         }
580                 }
581         } else if (handle_class == mono_defaults.methodhandle_class) {
582                 MonoMethod *method = (MonoMethod*) ref;
583                 /* methods coming from platform code have extra protection (accessibility check) */
584                 if (mono_security_core_clr_is_platform_image (method->klass->image)) {
585                         MonoMethod *caller = get_reflection_caller ();
586                         /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
587                         if (!check_method_access (caller, method)) {
588                                 return get_method_access_exception (
589                                         "Dynamic method %s cannot create access private/internal method %s.", 
590                                         caller, method);
591                         }
592                 }
593         }
594         return NULL;
595 }
596
597 /*
598  * mono_security_core_clr_can_access_internals
599  *
600  *      Check if we allow [InternalsVisibleTo] to work between two images.
601  */
602 gboolean
603 mono_security_core_clr_can_access_internals (MonoImage *accessing, MonoImage* accessed)
604 {
605         /* are we trying to access internals of a platform assembly ? if not this is acceptable */
606         if (!mono_security_core_clr_is_platform_image (accessed))
607                 return TRUE;
608
609         /* we can't let everyone with the right name and public key token access the internals of platform code.
610          * (Silverlight can rely on the strongname signature of the assemblies, but Mono does not verify them)
611          * However platform code is fully trusted so it can access the internals of other platform code assemblies */
612         if (mono_security_core_clr_is_platform_image (accessing))
613                 return TRUE;
614
615         /* catch-22: System.Xml needs access to mscorlib's internals (e.g. ArrayList) but is not considered platform code.
616          * Promoting it to platform code would create another issue since (both Mono/Moonlight or MS version of) 
617          * System.Xml.Linq.dll (an SDK, not platform, assembly) needs access to System.Xml.dll internals (either ). 
618          * The solution is to trust, even transparent code, in the plugin directory to access platform code internals */
619         if (!accessed->assembly->basedir || !accessing->assembly->basedir)
620                 return FALSE;
621         return (strcmp (accessed->assembly->basedir, accessing->assembly->basedir) == 0);
622 }
623
624 /*
625  * mono_security_core_clr_is_field_access_allowed
626  *
627  *      Return a MonoException (FieldccessException in managed-land) if
628  *      the access from "caller" to "field" is not valid under CoreCLR -
629  *      i.e. a [SecurityTransparent] method calling a [SecurityCritical]
630  *      field.
631  */
632 MonoException*
633 mono_security_core_clr_is_field_access_allowed (MonoMethod *caller, MonoClassField *field)
634 {
635         /* there's no restriction to access Transparent or SafeCritical fields, so we only check calls to Critical methods */
636         if (mono_security_core_clr_class_level (mono_field_get_parent (field)) != MONO_SECURITY_CORE_CLR_CRITICAL)
637                 return NULL;
638
639         /* caller is Critical! only SafeCritical and Critical callers can access the field, so we throw if caller is Transparent */
640         if (!caller || (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT))
641                 return NULL;
642
643         return get_field_access_exception (
644                 "Transparent method %s cannot call use Critical field %s.", 
645                 caller, field);
646 }
647
648 /*
649  * mono_security_core_clr_is_call_allowed
650  *
651  *      Return a MonoException (MethodAccessException in managed-land) if
652  *      the call from "caller" to "callee" is not valid under CoreCLR -
653  *      i.e. a [SecurityTransparent] method calling a [SecurityCritical]
654  *      method.
655  */
656 MonoException*
657 mono_security_core_clr_is_call_allowed (MonoMethod *caller, MonoMethod *callee)
658 {
659         /* there's no restriction to call Transparent or SafeCritical code, so we only check calls to Critical methods */
660         if (mono_security_core_clr_method_level (callee, TRUE) != MONO_SECURITY_CORE_CLR_CRITICAL)
661                 return NULL;
662
663         /* callee is Critical! only SafeCritical and Critical callers can call it, so we throw if the caller is Transparent */
664         if (!caller || (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT))
665                 return NULL;
666
667         return get_method_access_exception (
668                 "Transparent method %s cannot call Critical method %s.", 
669                 caller, callee);
670 }
671
672 /*
673  * mono_security_core_clr_level_from_cinfo:
674  *
675  *      Return the MonoSecurityCoreCLRLevel that match the attribute located
676  *      in the specified custom attributes. If no attribute is present it 
677  *      defaults to MONO_SECURITY_CORE_CLR_TRANSPARENT, which is the default
678  *      level for all code under the CoreCLR.
679  */
680 static MonoSecurityCoreCLRLevel
681 mono_security_core_clr_level_from_cinfo (MonoCustomAttrInfo *cinfo, MonoImage *image)
682 {
683         int level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
684
685         if (cinfo && mono_custom_attrs_has_attr (cinfo, security_safe_critical_attribute ()))
686                 level = MONO_SECURITY_CORE_CLR_SAFE_CRITICAL;
687         if (cinfo && mono_custom_attrs_has_attr (cinfo, security_critical_attribute ()))
688                 level = MONO_SECURITY_CORE_CLR_CRITICAL;
689
690         return level;
691 }
692
693 /*
694  * mono_security_core_clr_class_level_no_platform_check:
695  *
696  *      Return the MonoSecurityCoreCLRLevel for the specified class, without 
697  *      checking for platform code. This help us avoid multiple redundant 
698  *      checks, e.g.
699  *      - a check for the method and one for the class;
700  *      - a check for the class and outer class(es) ...
701  */
702 static MonoSecurityCoreCLRLevel
703 mono_security_core_clr_class_level_no_platform_check (MonoClass *class)
704 {
705         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
706         MonoCustomAttrInfo *cinfo = mono_custom_attrs_from_class (class);
707         if (cinfo) {
708                 level = mono_security_core_clr_level_from_cinfo (cinfo, class->image);
709                 mono_custom_attrs_free (cinfo);
710         }
711
712         if (level == MONO_SECURITY_CORE_CLR_TRANSPARENT && class->nested_in)
713                 level = mono_security_core_clr_class_level_no_platform_check (class->nested_in);
714
715         return level;
716 }
717
718 /*
719  * mono_security_core_clr_class_level:
720  *
721  *      Return the MonoSecurityCoreCLRLevel for the specified class.
722  */
723 MonoSecurityCoreCLRLevel
724 mono_security_core_clr_class_level (MonoClass *class)
725 {
726         /* non-platform code is always Transparent - whatever the attributes says */
727         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (class->image))
728                 return MONO_SECURITY_CORE_CLR_TRANSPARENT;
729
730         return mono_security_core_clr_class_level_no_platform_check (class);
731 }
732
733 /*
734  * mono_security_core_clr_method_level:
735  *
736  *      Return the MonoSecurityCoreCLRLevel for the specified method.
737  *      If with_class_level is TRUE then the type (class) will also be
738  *      checked, otherwise this will only report the information about
739  *      the method itself.
740  */
741 MonoSecurityCoreCLRLevel
742 mono_security_core_clr_method_level (MonoMethod *method, gboolean with_class_level)
743 {
744         MonoCustomAttrInfo *cinfo;
745         MonoSecurityCoreCLRLevel level = MONO_SECURITY_CORE_CLR_TRANSPARENT;
746
747         /* if get_reflection_caller returns NULL then we assume the caller has NO privilege */
748         if (!method)
749                 return level;
750
751         /* non-platform code is always Transparent - whatever the attributes says */
752         if (!mono_security_core_clr_test && !mono_security_core_clr_is_platform_image (method->klass->image))
753                 return level;
754
755         cinfo = mono_custom_attrs_from_method (method);
756         if (cinfo) {
757                 level = mono_security_core_clr_level_from_cinfo (cinfo, method->klass->image);
758                 mono_custom_attrs_free (cinfo);
759         }
760
761         if (with_class_level && level == MONO_SECURITY_CORE_CLR_TRANSPARENT)
762                 level = mono_security_core_clr_class_level (method->klass);
763
764         return level;
765 }
766
767 /*
768  * mono_security_core_clr_is_platform_image:
769  *
770  *   Return the (cached) boolean value indicating if this image represent platform code
771  */
772 gboolean
773 mono_security_core_clr_is_platform_image (MonoImage *image)
774 {
775         return image->core_clr_platform_code;
776 }
777
778 /*
779  * default_platform_check:
780  *
781  *      Default platform check. Always TRUE for current corlib (minimum 
782  *      trust-able subset) otherwise return FALSE. Any real CoreCLR host
783  *      should provide its own callback to define platform code (i.e.
784  *      this default is meant for test only).
785  */
786 static gboolean
787 default_platform_check (const char *image_name)
788 {
789         if (mono_defaults.corlib) {
790                 return (strcmp (mono_defaults.corlib->name, image_name) == 0);
791         } else {
792                 /* this can get called even before we load corlib (e.g. the EXE itself) */
793                 const char *corlib = "mscorlib.dll";
794                 int ilen = strlen (image_name);
795                 int clen = strlen (corlib);
796                 return ((ilen >= clen) && (strcmp ("mscorlib.dll", image_name + ilen - clen) == 0));
797         }
798 }
799
800 static MonoCoreClrPlatformCB platform_callback = default_platform_check;
801
802 /*
803  * mono_security_core_clr_determine_platform_image:
804  *
805  *      Call the supplied callback (from mono_security_set_core_clr_platform_callback) 
806  *      to determine if this image represents platform code.
807  */
808 gboolean
809 mono_security_core_clr_determine_platform_image (MonoImage *image)
810 {
811         return platform_callback (image->name);
812 }
813
814 /*
815  * mono_security_enable_core_clr:
816  *
817  *   Enable the verifier and the CoreCLR security model
818  */
819 void
820 mono_security_enable_core_clr ()
821 {
822         mono_verifier_set_mode (MONO_VERIFIER_MODE_VERIFIABLE);
823         mono_security_set_mode (MONO_SECURITY_MODE_CORE_CLR);
824 }
825
826 /*
827  * mono_security_set_core_clr_platform_callback:
828  *
829  *      Set the callback function that will be used to determine if an image
830  *      is part, or not, of the platform code.
831  */
832 void
833 mono_security_set_core_clr_platform_callback (MonoCoreClrPlatformCB callback)
834 {
835         platform_callback = callback;
836 }
837