مشاركة عبر


الإرشادات التفصيلية: باعث تعليمات برمجية في وحدات سيناريو الثقة الجزئية

انعكاس الإرسال التعيين تستخدم نفس API في الثقة كاملة أو جزئية، ولكن تتطلب بعض ميزات أذونات خاص في موثوق به جزئيا تعليمات برمجية. بالإضافة إلى ذلك، الإرسال انعكاس له ميزة، والأساليب الديناميكية مستضافة من قبل مجهولين، التي هو مصمم للاستخدام مع الثقة جزئي وتجميعات الشفافة للأمان.

ملاحظةملاحظة

قبل NET Framework. الإصدار 3.5، باعث تعليمات برمجية المطلوبة ReflectionPermissionمع ReflectionPermissionFlag.ReflectionEmitيؤشر.Th هو permهوsion هو المضمن بشكل افتراضي في FullTrustو Intranetpermهوsion المسمى تعيين، ولكن ليس في Internetpermهوsion التعيين.ولذلك، يمكن استخدام مكتبة من الثقة جزئي فقط إذا أنه SecurityCriticalAttributeسمة و أيضا تنفيذ Assertأسلوب ReflectionEmit. مثل مكتبات تتطلب مراجعة حذراً الأمان لأن التعليمات البرمجية أخطاء تؤدي فتحات أمان. .NET Framework 3.5يسمح تعليمات برمجية أن تصدر في سيناريوهات الثقة جزئي دون هو suing أي أمان إلزامية، نظراً لإنشاء تعليمات برمجية هو ليس مثل المميز تشغيل.التي هو، تعليمات برمجية المنشأة على لا permهوsions المزيد تجميع الذي emits عليه.بما يمكن من مكتبات الإرسال تعليمات برمجية أن يكون شفافاً بالالأمان وقم بإزالة الحاجة إلى تأكيد ReflectionEmit، حيث الكتابة لا يتطلب مكتبة اﻷمن مثل الأمان عميق المراجعة.

توضح هذه الإرشادات التفصيلية المهام التالية:

  • إعداد الحماية بسيطة للاختبار موثوق به جزئيا تعليمات برمجية.

    ملاحظة هامةهام

    Th هو هو طريقة بسيطة للتجربة مع تعليمات برمجية في الثقة جزئي.إلى تشغيل تعليمات برمجية التي فعلياً يأتي من المواقع غير الموثوق بها، راجع كيفية: تشغيل تعليمات برمجية موثوق بها جزئي في الحماية.

  • قم بتشغيل تعليمات برمجية في مجالات تطبيق موثوق به جزئيا.

  • تستخدم بشكل مجهول استضافة الأساليب الديناميكية إلى الإرسال وتنفيذ تعليمات برمجية في الثقة الجزئية.

للحصول على مزيد من المعلومات حول باعث تعليمات برمجية في وحدات سيناريو الثقة جزئي، راجع حذف المشاكل المتعلقة بالأمان في انعكاس.

للحصول على قائمة كاملة من تعليمات برمجية يظهر في هذه الإجراءات، راجع مقطع مثال في إنهاء هذه معاينة.

إعداد لأعلى جزئية المواقع الموثوق بها

إظهار الإجراءات الثاني التالية كيفية إعداد المواقع التي يمكنك اختبار تعليمات برمجية باستخدام الجزئي الثقة.

  • إجراء أول يوضح كيفية إنشاء مجال تطبيق sandboxed في التعليمات البرمجية التي هو الممنوحة permهوsions إنترنت.

  • إجراء الثاني يوضح كيفية إضافة ReflectionPermissionمع ReflectionPermissionFlag.RestrictedMemberAccessإشارة إلى مجال تطبيق موثوق به جزئيا، لتمكين الوصول إلى بيانات الخاصة ب تجميعات مساوياً أو أقل الثقة.

قم بإنشاء مجالات التطبيقات Sandboxed

لإنشاء في مجال تطبيق فيه تشغيل تجميعات الخاصة بك بالجزئي الثقة، يجب تحديد التعيين الأذونات يمكن منحها للتجميعات باستخدام AppDomain.CreateDomain(String, Evidence, AppDomainSetup, PermissionSet, array<StrongName[])أسلوب زيادة التحميل لإنشاء مجال التطبيق. أن أسهل طريقة لتعيين التعيين منح هو لاسترداد permهوsion مسماة تعيين نهج الأمان.

ينشئ إجراء التالي في مجال تطبيق sandboxed الذي يقوم بتشغيل تعليمات برمجية الخاصة بك بالجزئي الثقة، لاختبار السيناريوهات التي يمكن الوصول إلى تعليمات برمجية emitted الأعضاء العام فقط للأنواع العامة. يظهر أحد الإجراءات تالية كيفية إضافة RestrictedMemberAccess، لاختبار السيناريوهات التي يمكن الوصول إلى تعليمات برمجية emitted أنواع nonpublic و الأعضاء في تجميعات التي يتم منحها مساوياً أو أقل الأذونات.

إلى إنشاء مجال تطبيق بثقة جزئي

  1. إنشاء إذن مجموعة منح للتجميعات في مجال تطبيق sandboxed. في هذه الحالة، يتم استخدام التعيين الأذونات من منطقة إنترنت.

    Dim ev As New Evidence()
    ev.AddHostEvidence(new Zone(SecurityZone.Internet))
    Dim pset As New NamedPermissionSet("Internet", SecurityManager.GetStandardSandbox(ev))
    
    Evidence ev = new Evidence();
    ev.AddHostEvidence(new Zone(SecurityZone.Internet));
    PermissionSet pset = new NamedPermissionSet("Internet", SecurityManager.GetStandardSandbox(ev));
    
  2. إنشاء AppDomainSetupالكائن إلى مجال التطبيق مع مسار. تطبيق يهيّئ

    ملاحظة هامةهام

    بالنسبة للبساطة، يستخدم هذا المثال رمز المجلد الحالي.إلى تشغيل تعليمات برمجية التي فعلياً يأتي من الإنترنت، استخدام مجلد منفصل لتعليمات برمجية غير موثوق به، كما هو موضح في كيفية: تشغيل تعليمات برمجية موثوق بها جزئي في الحماية.

    Dim adSetup As New AppDomainSetup()
    adSetup.ApplicationBase = "."
    
    AppDomainSetup adSetup = new AppDomainSetup();
    adSetup.ApplicationBase = ".";
    
  3. قم بإنشاء مجال تطبيق، وتحديد معلومات إعداد مجال تطبيق ومنح الإذن لكافة تجميعات التي يتم تنفيذها في مجال تطبيق.

    Dim ad As AppDomain = AppDomain.CreateDomain("Sandbox", ev, adSetup, pset, Nothing)
    
    AppDomain ad = AppDomain.CreateDomain("Sandbox", ev, adSetup, pset, null);
    

    معلمة الأخيرة من AppDomain.CreateDomain(String, Evidence, AppDomainSetup, PermissionSet, array<StrongName[])التحميل الزائد لأسلوب يتيح لك إلى تحديد التعيين من تجميعات التي يتم إلى يتم منح الثقة الكاملة، بدلاً من التعيين منح مجال تطبيق. ليس لديك لتحديد .NET Frameworkتجميعات التي يستخدمها تطبيق الخاص بك، نظراً لوجود هذه تجميعات في ذاكرة التخزين المؤقتة للتجميع العمومي. تجميعات في التجميع العمومي ذاكرة تخزين مؤقت تكون دائماً موثوق به ثقة كاملة. يمكنك استخدام هذه معلمة إلى تعيين تجميعات باسم واضح وغير موجودة في مخزن التجميع العمومي المؤقت.

إضافة RestrictedMemberAccess إلى مجالات Sandboxed

أن تسمح للتطبيقات مضيف مستضافة من قبل مجهولين الطرق ديناميكي للوصول إلى بيانات الخاصة بالتجميعات التي تحتوي على مستويات الثقة يساوي أو أصغر من من المستوى الثقة للتجميع الذي emits تعليمات برمجية. لتمكين هذا تقييد إمكانية تخطي تدقيق رؤية (JIT) في نفس الوقت، يضيف تطبيق مضيف ReflectionPermissionكائن ذو ReflectionPermissionFlag.RestrictedMemberAccess(يعمل) يؤشر إلى التعيين منح.

على سبيل المثال، مضيف قد منح أذونات إنترنت تطبيقات إنترنت بالإضافة إلى يعمل، بحيث يمكن تطبيق إنترنت الإرسال تعليمات برمجية الذي يقوم بالوصول إلى بيانات الخاصة بالتجميعات الخاصة به. نظراً للوصول هو محدودة للتجميعات الثقة مساوياً أو أقل، تطبيق إنترنت يتعذر الوصول إلى الأعضاء تجميعات موثوق به ثقة كاملة مثل .NET Frameworkتجميعات.

ملاحظةملاحظة

لمنع رفع امتياز، تكديس المعلومات الخاصة بالتجميع باعث هو المضمنة عندما يتم بناء طرق حيوية مستضافة من قبل مجهولين.عند الأسلوب هو استدعاء المعلومات المكدس هو محددة.وهكذا، مستضاف من قبل مجهولين حيوية أسلوب التي هو استدعاء من التعليمات البرمجية الثقة الكاملة هو لا تزال محدودة لالمستوى الثقة للتجميع الإرسال.

إلى إنشاء مجال تطبيق بثقة جزئي بالإضافة إلى يعمل

  1. إنشاء جديد ReflectionPermissionكائن ذو RestrictedMemberAccess(يعمل) وضع إشارة لها، واستخدام PermissionSet.SetPermissionأسلوب لإضافة إذن إلى منح التعيين.

    pset.SetPermission( _
        New ReflectionPermission( _
            ReflectionPermissionFlag.RestrictedMemberAccess))
    
    pset.SetPermission(
        new ReflectionPermission(
            ReflectionPermissionFlag.RestrictedMemberAccess));
    

    AddPermissionيضيف الأسلوب permهوsion إلى التعيين منح إذا أنه هو الموجودة بالفعل. إذا كان permهوsion هو مُضمنها في التعيين منح الإذن بالفعل، الإشارات المحددة تضاف إلى permهوsion exهوting.

    ملاحظةملاحظة

    يعمل هو ميزة الأساليب الديناميكية المضيفة بطريقة مجهولة.عند رؤية JIT تخطي الطرق ديناميكي العادية التحقق، في emitted تعليمات برمجية تتطلب الثقة تامة.

  2. إنشاء مجال تطبيق، وتحديد معلومات الإعداد الخاصة بمجال تطبيق و مجموعة منح الإذن.

    ad = AppDomain.CreateDomain("Sandbox2", ev, adSetup, pset, Nothing)
    
    ad = AppDomain.CreateDomain("Sandbox2", ev, adSetup, pset, null);
    

قم بتشغيل تعليمات برمجية في مجالات التطبيقات Sandboxed

يفسر إجراء التالي كيفية إلى تعريف فئة باستخدام الطرق التي يمكن ينفذها في مجال تطبيق، كيف إلى إنشاء مثيل للفئة في المجال، وكيف إلى ينفذ الأساليب الخاصة به.

إلى تعريف وتنفيذ أسلوب في مجال تطبيق

  1. تعريف فئة مشتقة من MarshalByRefObject. يتيح لك ذلك إلى إنشاء مثيلات للفئة في مجالات تطبيقات الأخرى و إلى تجعل لاستدعاءات الأسلوب عبر حدود المجال تطبيق. الفئات في ترتيب هو المثال هو باسم Worker.

    Public Class Worker
        Inherits MarshalByRefObject
    
    public class Worker : MarshalByRefObject
    {
    
  2. تعريف أسلوب عام الذي يحتوي على تعليمات برمجية التي تريد إلى التنفيذ. في هذا المثال، emits التعليمة البرمجية الديناميكية بسيطة أسلوب، ينشئ مفوض للتنفيذ أسلوب، واستدعاء المفوض.

    Public Sub SimpleEmitDemo()
    
        Dim meth As DynamicMethod = new DynamicMethod("", Nothing, Nothing)
        Dim il As ILGenerator = meth.GetILGenerator()
        il.EmitWriteLine("Hello, World!")
        il.Emit(OpCodes.Ret)
    
        Dim t1 As Test1 = CType(meth.CreateDelegate(GetType(Test1)), Test1)
        t1()
    End Sub
    
    public void SimpleEmitDemo()
    {
        DynamicMethod meth = new DynamicMethod("", null, null);
        ILGenerator il = meth.GetILGenerator();
        il.EmitWriteLine("Hello, World!");
        il.Emit(OpCodes.Ret);
    
        Test1 t1 = (Test1) meth.CreateDelegate(typeof(Test1));
        t1();
    }
    
  3. في المكتب الرئيسي برنامج، يحصل اسم عرض الخاص بالتجميع الخاص بك. يستخدم هذا الاسم عند إنشاء مثيلات Workerفئة في مجال تطبيق sandboxed.

    Dim asmName As String = [Assembly].GetExecutingAssembly().FullName
    
    String asmName = Assembly.GetExecutingAssembly().FullName;
    
  4. في البرنامج الرئيسي، إنشاء مجال تطبيق sandboxed، كما هو موضح في إجراء أول في هذه معاينة. ليس لديك لإضافة أية أذونات إلى Internetتعيين الإذن، لأنه SimpleEmitDemoيستخدم الأسلوب فقط العامة وظائف.

  5. في البرنامج الأساسي الخاص بك، قم بإنشاء مثيل Workerالفئة في مجال تطبيق sandboxed.

    Dim w As Worker = _
        CType(ad.CreateInstanceAndUnwrap(asmName, "Worker"), Worker)
    
    Worker w = (Worker) ad.CreateInstanceAndUnwrap(asmName, "Worker");
    

    The CreateInstanceAndUnwrap أسلوب creates the كائن في the الهدف مجال تطبيق و إرجاع a proxy that can be used إلى يتصل the خصائص و وظائف of the كائن.

    ملاحظةملاحظة

    If you استخدم this تعليمات برمجية في Visual Studio, you must تغيير the اسم of the فئة إلى تضمين the مساحة الاسم. بواسطة الافتراضي, the مساحة الاسم هو the اسم of the مشروع. For مثال, if the مشروع هو "PartialTrust", the فئة اسم must be "PartialTrust.Worker".

  6. إضافة تعليمات برمجية إلى يتصل the SimpleEmitDemo أسلوب. The يتصل هو marshaled عبر the مجال تطبيق boundary, و the تعليمات برمجية هو executed في the sandboxed مجال تطبيق.

    w.SimpleEmitDemo()
    
    w.SimpleEmitDemo();
    

Using Anonymously Hosted ديناميكي وظائف

Anonymously hosted ديناميكي وظائف are associated مع a شفاف تجميع that هو provided بواسطة the النظام. Therefore, the تعليمات برمجية they contain هو شفاف. Ordinary ديناميكي وظائف, تشغيل the غير ذلك hand, must be associated مع an موجود وحدة نمطية? (whether directly specified أو inferred من an associated نوع), و take their الأمان المستوى من that وحدة نمطية?.

ملاحظةملاحظة

The فقط way إلى associate a ديناميكي أسلوب مع the تجميع that provides anonymous hosting هو إلى استخدم the constructors that are described في the following إجراء.You cannot بوضوح specify a وحدة نمطية? في the anonymous hosting تجميع.

Ordinary ديناميكي وظائف have الوصول إلى the internal الأعضاء of the وحدة نمطية? they are associated مع, أو إلى the private الأعضاء of the نوع they are associated مع. Because anonymously hosted ديناميكي وظائف are معزول من غير ذلك تعليمات برمجية, they do not have الوصول إلى private بيانات. However, they do have a restricted ability إلى تخطي JIT رؤية checks إلى gain الوصول إلى private بيانات. Th هو قدرة هو محدودة للتجميعات التي تحتوي على مستويات الثقة يساوي أو أقل من المستوى الثقة للتجميع الذي emits التعليمة البرمجية.

لمنع رفع امتياز، تكديس المعلومات الخاصة بالتجميع باعث هو المضمنة عندما يتم بناء طرق حيوية مستضافة من قبل مجهولين. عند الأسلوب هو استدعاء المعلومات المكدس هو محددة. أسلوب حيوي مستضافة من قبل مجهولين التي يتم استدعاؤها من تعليمات برمجية موثوق بها ثقة كاملة تزال إلى المستوى الثقة للتجميع الذي تصدر به.

إلى استخدم anonymously hosted ديناميكي وظائف

  • إنشاء an anonymously hosted ديناميكي أسلوب بواسطة using a الدالة الإنشائية that does not specify an associated وحدة نمطية? أو نوع.

    Dim meth As DynamicMethod = new DynamicMethod("", Nothing, Nothing)
    Dim il As ILGenerator = meth.GetILGenerator()
    il.EmitWriteLine("Hello, World!")
    il.Emit(OpCodes.Ret)
    
    DynamicMethod meth = new DynamicMethod("", null, null);
    ILGenerator il = meth.GetILGenerator();
    il.EmitWriteLine("Hello, World!");
    il.Emit(OpCodes.Ret);
    

    If an anonymously hosted ديناميكي أسلوب uses فقط public أنواع و وظائف, it does not require restricted عضو الوصول و does not have إلى تخطي JIT رؤية checks.

    لا خاص أذونات are مطلوب إلى emit a ديناميكي أسلوب, but the emitted تعليمات برمجية يتطلب the أذونات that are demanded بواسطة the أنواع و وظائف it uses. For مثال, if the emitted تعليمات برمجية calls a أسلوب that accesses a ملف, it يتطلب FileIOPermission. If the المستوى الثقة does not تضمين that إذن, a الأمان ‏‏ استثناء هو تم طرح when the emitted تعليمات برمجية هو executed. The تعليمات برمجية shown هنا emits a ديناميكي أسلوب that uses فقط the Console.WriteLine أسلوب. Therefore, the تعليمات برمجية can be executed من partially موثوق به مواقع?.

  • Alternatively, إنشاء an anonymously hosted ديناميكي أسلوب مع restricted ability إلى تخطي JIT رؤية checks, بواسطة using the DynamicMethod(String, Type, array<Type[], Boolean) الدالة الإنشائية و specifying true for the restrictedSkipVisibility معلمة.

    Dim meth As New DynamicMethod("", _
                                  GetType(Char), _
                                  New Type() {GetType(String)}, _
                                  True)
    
    DynamicMethod meth = new DynamicMethod("",
                                           typeof(char), 
                                           new Type[] { typeof(String) }, 
                                           true);
    

    The restriction هو that the anonymously hosted ديناميكي أسلوب can الوصول private بيانات فقط في تجميعات مع trust levels يساوي أو أصغر من the المستوى الثقة of the emitting تجميع. For مثال, if the ديناميكي أسلوب هو executing مع إنترنت الثقة, it can الوصول private بيانات في غير ذلك تجميعات that are also executing مع إنترنت الثقة, but it cannot الوصول private بيانات of .NET Framework تجميعات. .NET Framework تجميعات are installed في the عمومي مخزن تجميع مؤقت و are دوماً fully موثوق به.

    Anonymously hosted ديناميكي وظائف can استخدم this restricted ability إلى تخطي JIT رؤية checks فقط if the تطبيق مضيف grants ReflectionPermission مع the ReflectionPermissionFlag.RestrictedMemberAccess يؤشر. The demand for this إذن هو made when the أسلوب هو invoked.

    ملاحظةملاحظة

    يتصل مكدس معلومات for the emitting تجميع هو مُضمن when the ديناميكي أسلوب هو constructed.Therefore, the demand هو made against the أذونات of the emitting تجميع instead of the تجميع that invokes the أسلوب.This prevents the emitted تعليمات برمجية من being executed مع elevated أذونات.

    The إكمال تعليمات برمجية مثال at the إنهاء of this معاينة demonstrates the استخدم و limitations of restricted عضو الوصول. Its Worker فئة يتضمن a أسلوب that can إنشاء anonymously hosted ديناميكي وظائف مع أو without the restricted ability إلى تخطي رؤية checks, و the مثال shows the النتيجة of executing this أسلوب في تطبيق domains that have different الثقة levels.

    ملاحظةملاحظة

    The restricted ability إلى تخطي رؤية checks هو a ميزة of anonymously hosted ديناميكي وظائف.When ordinary ديناميكي وظائف تخطي JIT رؤية checks, they must be granted كامل الثقة.

المثال

الوصف

The following تعليمات برمجية مثال demonstrates the استخدم of the RestrictedMemberAccess يؤشر إلى allow anonymously hosted ديناميكي وظائف إلى تخطي JIT رؤية checks, but فقط when the الهدف عضو هو at an equal أو lower المستوى of الثقة than the تجميع that emits the تعليمات برمجية.

The مثال defines a Worker فئة that can be marshaled عبر مجال تطبيق boundaries. The فئة has الثاني AccessPrivateMethod أسلوب التحميلات الزائدة that emit و ينفذ ديناميكي وظائف. The أول التحميل الزائد emits a ديناميكي أسلوب that calls the private PrivateMethod أسلوب of the Worker فئة, و it can emit the ديناميكي أسلوب مع أو without JIT رؤية checks. The ثانية التحميل الزائد emits a ديناميكي أسلوب that accesses an internal خاصية (Friend خاصية في Visual أساسى) of the String فئة.

The مثال uses a helper أسلوب إلى إنشاء a grant التعيين limited إلى Internet أذونات, و then creates an مجال تطبيق, using the AppDomain.CreateDomain(String, Evidence, AppDomainSetup, PermissionSet, array<StrongName[]) أسلوب التحميل الزائد إلى specify that الجميع تعليمات برمجية that executes في the domain uses this grant التعيين. The مثال creates an مثيل of the Worker فئة في the مجال تطبيق, و executes the AccessPrivateMethod أسلوب الثاني مرة/مرات.

  • The أول الوقت the AccessPrivateMethod أسلوب هو executed, JIT رؤية checks are enforced. The ديناميكي أسلوب fails when it هو invoked, because JIT رؤية checks prevent it من accessing the private أسلوب.

  • The ثانية الوقت the AccessPrivateMethod أسلوب هو executed, JIT رؤية checks are skipped. The ديناميكي أسلوب fails when it هو compiled, because the Internet grant التعيين does not grant sufficient أذونات إلى تخطي رؤية checks.

The مثال adds ReflectionPermission مع ReflectionPermissionFlag.RestrictedMemberAccess إلى the grant التعيين. The مثال then creates a ثانية مجال, specifying that الجميع تعليمات برمجية that executes في the مجال هو granted the أذونات في the جديد grant التعيين. المثال، يتم إنشاء مثيل من Workerفئة في مجال تطبيق الجديد، وقم بتنفيذ التحميلات الزائدة كلا من AccessPrivateMethodالأسلوب.

  • التحميل الزائد أول من AccessPrivateMethodأسلوب هو التنفيذ، ويتم تخطي تدقيق vهوibility JIT. تجميع طريقة حيوية وينفذ بنجاح، لأن التجميع التي emits تعليمات برمجية هو نفس التجميع الذي يحتوي على أسلوب خاص. ولذلك، عند تساوي مستويات الثقة. إذا كان تطبيق الذي يحتوي على Workerتحتوي فئة تجميعات المتعددة، هي نفس العملية بنجاح لأي من هذه تجميعات، لأن هو الحال مع الجميع أن تكون في نفس الثقة المستوى.

  • التحميل الزائد الثاني من AccessPrivateMethodأسلوب هو التنفيذ، ومرة أخرى يتم تخطي تدقيق vهوibility JIT. This time the dynamic method fails when it is compiled, because it tries to access the internal FirstChar property of the String class. تجميع الذي يحتوي على Stringالفئة هو موثوق بها ثقة كاملة. ولذلك، فإنه هو في المستوى أعلى من الثقة من تجميع الذي emits التعليمة البرمجية.

تظهر هذه المقارنة كيف ReflectionPermissionFlag.RestrictedMemberAccessالتحقق من تمكين تعليمات برمجية موثوق بها جزئيا لتخطي رؤية غير ذلك جزئيا موثوق به رمز بدون تعريض الأمان للتعليمات البرمجية الموثوق بها. للخطر

الرمز

Imports System
Imports System.Reflection.Emit
Imports System.Reflection
Imports System.Security
Imports System.Security.Permissions
Imports System.Security.Policy
Imports System.Collections
Imports System.Diagnostics

' This code example works properly only if it is run from a fully 
' trusted location, such as your local computer.

' Delegates used to execute the dynamic methods.
'
Public Delegate Sub Test(ByVal w As Worker) 
Public Delegate Sub Test1() 
Public Delegate Function Test2(ByVal instance As String) As Char 

' The Worker class must inherit MarshalByRefObject so that its public 
' methods can be invoked across application domain boundaries.
'
Public Class Worker
    Inherits MarshalByRefObject

    Private Sub PrivateMethod() 
        Console.WriteLine("Worker.PrivateMethod()")
    End Sub 

    Public Sub SimpleEmitDemo()

        Dim meth As DynamicMethod = new DynamicMethod("", Nothing, Nothing)
        Dim il As ILGenerator = meth.GetILGenerator()
        il.EmitWriteLine("Hello, World!")
        il.Emit(OpCodes.Ret)

        Dim t1 As Test1 = CType(meth.CreateDelegate(GetType(Test1)), Test1)
        t1()
    End Sub

    ' This overload of AccessPrivateMethod emits a dynamic method and
    ' specifies whether to skip JIT visiblity checks. It creates a 
    ' delegate for the method and invokes the delegate. The dynamic 
    ' method calls a private method of the Worker class.
    Overloads Public Sub AccessPrivateMethod( _
                       ByVal restrictedSkipVisibility As Boolean) 

        ' Create an unnamed dynamic method that has no return type,
        ' takes one parameter of type Worker, and optionally skips JIT
        ' visiblity checks.
        Dim meth As New DynamicMethod("", _
                                      Nothing, _
                                      New Type() { GetType(Worker) }, _
                                      restrictedSkipVisibility)

        ' Get a MethodInfo for the private method.
        Dim pvtMeth As MethodInfo = GetType(Worker).GetMethod( _
            "PrivateMethod", _
            BindingFlags.NonPublic Or BindingFlags.Instance)

        ' Get an ILGenerator and emit a body for the dynamic method.
        Dim il As ILGenerator = meth.GetILGenerator()

        ' Load the first argument, which is the target instance, onto the
        ' execution stack, call the private method, and return.
        il.Emit(OpCodes.Ldarg_0)
        il.EmitCall(OpCodes.Call, pvtMeth, Nothing)
        il.Emit(OpCodes.Ret)

        ' Create a delegate that represents the dynamic method, and 
        ' invoke it. 
        Try
            Dim t As Test = CType(meth.CreateDelegate(GetType(Test)), Test)
            Try
                t(Me)
            Catch ex As Exception
                Console.WriteLine("{0} was thrown when the delegate was invoked.", _
                    ex.GetType().Name)
            End Try
        Catch ex As Exception
            Console.WriteLine("{0} was thrown when the delegate was compiled.", _
                ex.GetType().Name)
        End Try

    End Sub 


    ' This overload of AccessPrivateMethod emits a dynamic method that takes
    ' a string and returns the first character, using a private field of the 
    ' String class. The dynamic method skips JIT visiblity checks.
    Overloads Public Sub AccessPrivateMethod() 

        Dim meth As New DynamicMethod("", _
                                      GetType(Char), _
                                      New Type() {GetType(String)}, _
                                      True)

        ' Get a MethodInfo for the 'get' accessor of the private property.
        Dim pi As PropertyInfo = GetType(String).GetProperty( _
            "FirstChar", _
            BindingFlags.NonPublic Or BindingFlags.Instance) 
        Dim pvtMeth As MethodInfo = pi.GetGetMethod(True)

        ' Get an ILGenerator and emit a body for the dynamic method.
        Dim il As ILGenerator = meth.GetILGenerator()

        ' Load the first argument, which is the target string, onto the
        ' execution stack, call the 'get' accessor to put the result onto 
        ' the execution stack, and return.
        il.Emit(OpCodes.Ldarg_0)
        il.EmitCall(OpCodes.Call, pvtMeth, Nothing)
        il.Emit(OpCodes.Ret)

        ' Create a delegate that represents the dynamic method, and 
        ' invoke it. 
        Try
            Dim t As Test2 = CType(meth.CreateDelegate(GetType(Test2)), Test2)
            Dim first As Char = t("Hello, World!")
            Console.WriteLine("{0} is the first character.", first)
        Catch ex As Exception
            Console.WriteLine("{0} was thrown when the delegate was compiled.", _
                ex.GetType().Name)
        End Try

    End Sub 
End Class

Friend Class Example

    ' The entry point for the code example.
    Shared Sub Main() 

        ' Get the display name of the executing assembly, to use when
        ' creating objects to run code in application domains.
        Dim asmName As String = [Assembly].GetExecutingAssembly().FullName

        ' Create the permission set to grant to other assemblies. In this
        ' case they are the permissions found in the Internet zone.
        Dim ev As New Evidence()
        ev.AddHostEvidence(new Zone(SecurityZone.Internet))
        Dim pset As New NamedPermissionSet("Internet", SecurityManager.GetStandardSandbox(ev))

        ' For simplicity, set up the application domain to use the 
        ' current path as the application folder, so the same executable
        ' can be used in both trusted and untrusted scenarios. Normally
        ' you would not do this with real untrusted code.
        Dim adSetup As New AppDomainSetup()
        adSetup.ApplicationBase = "."

        ' Create an application domain in which all code that executes is 
        ' granted the permissions of an application run from the Internet.
        Dim ad As AppDomain = AppDomain.CreateDomain("Sandbox", ev, adSetup, pset, Nothing)

        ' Create an instance of the Worker class in the partially trusted 
        ' domain. Note: If you build this code example in Visual Studio, 
        ' you must change the name of the class to include the default 
        ' namespace, which is the project name. For example, if the project
        ' is "AnonymouslyHosted", the class is "AnonymouslyHosted.Worker".
        Dim w As Worker = _
            CType(ad.CreateInstanceAndUnwrap(asmName, "Worker"), Worker)

        ' Emit a simple dynamic method that prints "Hello, World!"
        w.SimpleEmitDemo()

        ' Emit and invoke a dynamic method that calls a private method
        ' of Worker, with JIT visibility checks enforced. The call fails 
        ' when the delegate is invoked.
        w.AccessPrivateMethod(False)

        ' Emit and invoke a dynamic method that calls a private method
        ' of Worker, skipping JIT visibility checks. The call fails when
        ' the method is compiled.
        w.AccessPrivateMethod(True)


        ' Unload the application domain. Add RestrictedMemberAccess to the
        ' grant set, and use it to create an application domain in which
        ' partially trusted code can call private members, as long as the 
        ' trust level of those members is equal to or lower than the trust 
        ' level of the partially trusted code. 
        AppDomain.Unload(ad)
        pset.SetPermission( _
            New ReflectionPermission( _
                ReflectionPermissionFlag.RestrictedMemberAccess))
        ad = AppDomain.CreateDomain("Sandbox2", ev, adSetup, pset, Nothing)

        ' Create an instance of the Worker class in the partially trusted 
        ' domain. 
        w = CType(ad.CreateInstanceAndUnwrap(asmName, "Worker"), Worker)

        ' Again, emit and invoke a dynamic method that calls a private method
        ' of Worker, skipping JIT visibility checks. This time compilation 
        ' succeeds because of the grant for RestrictedMemberAccess.
        w.AccessPrivateMethod(True)

        ' Finally, emit and invoke a dynamic method that calls an internal 
        ' method of the String class. The call fails, because the trust level
        ' of the assembly that contains String is higher than the trust level
        ' of the assembly that emits the dynamic method.
        w.AccessPrivateMethod()

    End Sub 
End Class 

' This code example produces the following output:
'
'Hello, World!
'MethodAccessException was thrown when the delegate was invoked.
'MethodAccessException was thrown when the delegate was invoked.
'Worker.PrivateMethod()
'MethodAccessException was thrown when the delegate was compiled.
' 
using System;
using System.Reflection.Emit;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Collections;
using System.Diagnostics;

// This code example works properly only if it is run from a fully 
// trusted location, such as your local computer.

// Delegates used to execute the dynamic methods.
//
public delegate void Test(Worker w);
public delegate void Test1();
public delegate char Test2(String instance);

// The Worker class must inherit MarshalByRefObject so that its public 
// methods can be invoked across application domain boundaries.
//
public class Worker : MarshalByRefObject
{
    private void PrivateMethod()
    {
        Console.WriteLine("Worker.PrivateMethod()");
    }

    public void SimpleEmitDemo()
    {
        DynamicMethod meth = new DynamicMethod("", null, null);
        ILGenerator il = meth.GetILGenerator();
        il.EmitWriteLine("Hello, World!");
        il.Emit(OpCodes.Ret);

        Test1 t1 = (Test1) meth.CreateDelegate(typeof(Test1));
        t1();
    }

    // This overload of AccessPrivateMethod emits a dynamic method and
    // specifies whether to skip JIT visiblity checks. It creates a 
    // delegate for the method and invokes the delegate. The dynamic 
    // method calls a private method of the Worker class.
    public void AccessPrivateMethod(bool restrictedSkipVisibility) 
    {
        // Create an unnamed dynamic method that has no return type,
        // takes one parameter of type Worker, and optionally skips JIT
        // visiblity checks.
        DynamicMethod meth = new DynamicMethod(
            "", 
            null, 
            new Type[] { typeof(Worker) }, 
            restrictedSkipVisibility);

        // Get a MethodInfo for the private method.
        MethodInfo pvtMeth = typeof(Worker).GetMethod("PrivateMethod",
            BindingFlags.NonPublic | BindingFlags.Instance);

        // Get an ILGenerator and emit a body for the dynamic method.
        ILGenerator il = meth.GetILGenerator();

        // Load the first argument, which is the target instance, onto the
        // execution stack, call the private method, and return.
        il.Emit(OpCodes.Ldarg_0);
        il.EmitCall(OpCodes.Call, pvtMeth, null);
        il.Emit(OpCodes.Ret);

        // Create a delegate that represents the dynamic method, and 
        // invoke it. 
        try 
        {
            Test t = (Test) meth.CreateDelegate(typeof(Test));
            try 
            {
                t(this);
            }
            catch (Exception ex) 
            {
                Console.WriteLine("{0} was thrown when the delegate was invoked.", 
                    ex.GetType().Name);
            }
        } 
        catch (Exception ex) 
        {
            Console.WriteLine("{0} was thrown when the delegate was compiled.", 
                ex.GetType().Name);
        }
    }

    // This overload of AccessPrivateMethod emits a dynamic method that takes
    // a string and returns the first character, using a private field of the 
    // String class. The dynamic method skips JIT visiblity checks.
    public void AccessPrivateMethod() 
    {
        DynamicMethod meth = new DynamicMethod("",
                                               typeof(char), 
                                               new Type[] { typeof(String) }, 
                                               true);

        // Get a MethodInfo for the 'get' accessor of the private property.
        PropertyInfo pi = typeof(System.String).GetProperty(
            "FirstChar",
            BindingFlags.NonPublic | BindingFlags.Instance);
        MethodInfo pvtMeth = pi.GetGetMethod(true);

        // Get an ILGenerator and emit a body for the dynamic method.
        ILGenerator il = meth.GetILGenerator();

        // Load the first argument, which is the target string, onto the
        // execution stack, call the 'get' accessor to put the result onto 
        // the execution stack, and return.
        il.Emit(OpCodes.Ldarg_0);
        il.EmitCall(OpCodes.Call, pvtMeth, null);
        il.Emit(OpCodes.Ret);

        // Create a delegate that represents the dynamic method, and 
        // invoke it. 
        try 
        {
            Test2 t = (Test2) meth.CreateDelegate(typeof(Test2));
            char first = t("Hello, World!");
            Console.WriteLine("{0} is the first character.", first);
        } 
        catch (Exception ex) 
        {
            Console.WriteLine("{0} was thrown when the delegate was compiled.", 
                ex.GetType().Name);
        }
    }


    // The entry point for the code example.
    static void Main()
    {
        // Get the display name of the executing assembly, to use when
        // creating objects to run code in application domains.
        String asmName = Assembly.GetExecutingAssembly().FullName;

        // Create the permission set to grant to other assemblies. In this
        // case they are the permissions found in the Internet zone.
        Evidence ev = new Evidence();
        ev.AddHostEvidence(new Zone(SecurityZone.Internet));
        PermissionSet pset = new NamedPermissionSet("Internet", SecurityManager.GetStandardSandbox(ev));

        // For simplicity, set up the application domain to use the 
        // current path as the application folder, so the same executable
        // can be used in both trusted and untrusted scenarios. Normally
        // you would not do this with real untrusted code.
        AppDomainSetup adSetup = new AppDomainSetup();
        adSetup.ApplicationBase = ".";

        // Create an application domain in which all code that executes is 
        // granted the permissions of an application run from the Internet.
        AppDomain ad = AppDomain.CreateDomain("Sandbox", ev, adSetup, pset, null);

        // Create an instance of the Worker class in the partially trusted 
        // domain. Note: If you build this code example in Visual Studio, 
        // you must change the name of the class to include the default 
        // namespace, which is the project name. For example, if the project
        // is "AnonymouslyHosted", the class is "AnonymouslyHosted.Worker".
        Worker w = (Worker) ad.CreateInstanceAndUnwrap(asmName, "Worker");

        // Emit a simple dynamic method that prints "Hello, World!"
        w.SimpleEmitDemo();

        // Emit and invoke a dynamic method that calls a private method
        // of Worker, with JIT visibility checks enforced. The call fails 
        // when the delegate is invoked.
        w.AccessPrivateMethod(false);

        // Emit and invoke a dynamic method that calls a private method
        // of Worker, skipping JIT visibility checks. The call fails when
        // the method is invoked.
        w.AccessPrivateMethod(true);


        // Unload the application domain. Add RestrictedMemberAccess to the
        // grant set, and use it to create an application domain in which
        // partially trusted code can call private members, as long as the 
        // trust level of those members is equal to or lower than the trust 
        // level of the partially trusted code. 
        AppDomain.Unload(ad);
        pset.SetPermission(
            new ReflectionPermission(
                ReflectionPermissionFlag.RestrictedMemberAccess));
        ad = AppDomain.CreateDomain("Sandbox2", ev, adSetup, pset, null);

        // Create an instance of the Worker class in the partially trusted 
        // domain. 
        w = (Worker) ad.CreateInstanceAndUnwrap(asmName, "Worker");

        // Again, emit and invoke a dynamic method that calls a private method
        // of Worker, skipping JIT visibility checks. This time compilation 
        // succeeds because of the grant for RestrictedMemberAccess.
        w.AccessPrivateMethod(true);

        // Finally, emit and invoke a dynamic method that calls an internal 
        // method of the String class. The call fails, because the trust level
        // of the assembly that contains String is higher than the trust level
        // of the assembly that emits the dynamic method.
        w.AccessPrivateMethod();
    }
}

/* This code example produces the following output:

Hello, World!
MethodAccessException was thrown when the delegate was invoked.
MethodAccessException was thrown when the delegate was invoked.
Worker.PrivateMethod()
MethodAccessException was thrown when the delegate was compiled.
 */

التحويل البرمجي للتعليمات البرمجية

  • إذا قمت بإنشاء هذا المثال تعليمات برمجية في Visual Studio، يجب تغيير الاسم فئة لتشمل مساحة الاسم عندما قمت بتمرير إلى CreateInstanceAndUnwrapالأسلوب. بواسطة الافتراضي، ومساحة الاسم هو اسم مشروع. For مثال, if the مشروع هو "PartialTrust", the فئة اسم must be "PartialTrust.Worker".

راجع أيضًا:

المهام

كيفية: تشغيل تعليمات برمجية موثوق بها جزئي في الحماية

المبادئ

حذف المشاكل المتعلقة بالأمان في انعكاس