asp.net CAS, sandboxing privileged code, practice


asp.net 1.0, 1.1, 2.0 web app's default TrustLevel is Full, we could access current trust level through  this  property: System.Web.Management.WebBaseEvent.ApplicationInformation.TrustLevel

for the security consideration, we should set Trust level to Medium or High, to mitigate the damage if the app was compromised and reduce the attack surface.
<trust level="Medium"/>

any app's runs under non Full trust level is called partial trust app. So in this kind of scenario, we should apply Permission Demand/Assert Pattern to access secured resource and privilege operations.
For example, to access EventLog, we should wrap EventLog access code in another assemblies:
//Code Start!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public sealed class EventLogWriter    // seal this class to prevent other classes inherit from it.
    {
        public static string WriteEventLog(string source, string eventText)
        {
            try
            {

                //REMARK: EventLogPermissionAccess can only be set to Administer right now, otherwise StackWalk can NOT stop at this method calling. I still don't know what the exact problem is.  TO BE DONE later!!!!!!
                new EventLogPermission(EventLogPermissionAccess.Administer, ".").Assert();  // make the permission assert!
                if (EventLog.SourceExists(source) == false)
                {
                    EventLog.CreateEventSource(source, source);
                }
                EventLog.WriteEntry(source, eventText);
                return string.Empty;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
            finally
            {
                EventLogPermission.RevertAssert();         // Never forget RevertAssert.
            }

        }
    }
//Code end!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

in AssemblyInfo.cs, add this line to enable APTCA
[assembly: AllowPartiallyTrustedCallersAttribute()]

in command prompt, generate a key pair and use it to strong name the assembly:
sn -k "myKey.snk"

!IMPORTANT NOTEs!

now grant this assembly with full trust, the way is add this assembly to GAC( Global assembly cache)
gacutil -i "assembly full path" //we could use post build event feature in vs.net to do this step automatically.

!IMPORTANT NOTEs!
GAC assembly seems has some latency, so use iisreset in command prompt to force GAC refreshing. or your web app may use the old assembly from the cache.