8. Code Access Security
8.1 What is Code Access Security (CAS)?
CAS is the part of the .NET security model that determines whether or not code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.
8.2 How does CAS work?
The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set. For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the
'Internet' named permission set represents a very restrictive range of permissions.)
8.3 Who defines the CAS code groups?
Microsoft defines some default ones, but you can modify these and even create your own. To see the code groups defined on your system, run 'caspol
-lg' from the command-line. On my system it looks like this:
Level = Machine
Code Groups:
1. All code: Nothing
1.1. Zone - MyComputer: FullTrust
1.1.1. Honor SkipVerification requests: SkipVerification
1.2. Zone - Intranet: LocalIntranet
1.3. Zone - Internet: Internet
1.4. Zone - Untrusted: Nothing
1.5. Zone - Trusted: Internet
1.6. StrongName -
0024000004800000940000000602000000240000525341310004000003
000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF834
8EBD06
F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B
465E08
07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D3856
1AABF5C
AC1DF1734633C602F8F2D5: Everything
Note the hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then sub-divided into several groups, each of which in turn can be sub-divided. Also note that (somewhat counter- intuitively) a sub-group can be associated with a more permissive permission set than its parent.
8.4 How do I define my own code group?
Use caspol. For example, suppose you trust code from www.mydomain.com and you want it have full access to your system, but you want to keep the default restrictions for all other internet sites. To achieve this, you would add a new code group as a sub-group of the 'Zone - Internet' group, like this:
caspol -ag 1.3 -site www.mydomain.com FullTrust
Now if you run caspol -lg you will see that the new group has been added as group 1.3.1:
...
1.3. Zone - Internet: Internet
1.3.1. Site - www.mydomain.com: FullTrust
...
Note that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to manipulate from the command-line. The underlying runtime never sees it.
8.5 How do I change the permission set for a code group?
Use caspol. If you are the machine administrator, you can operate at the
'machine' level - which means not only that the changes you make become the default for the machine, but also that users cannot change the permissions to be more permissive. If you are a normal (non-admin) user you can still modify the permissions, but only to make them more restrictive. For example, to allow intranet code to do what it likes you might do this:
caspol -cg 1.2 FullTrust
Note that because this is more permissive than the default policy (on a standard system), you should only do this at the machine level - doing it at the user level will have no effect.
8.6 Can I create my own permission set?
Yes. Use caspol -ap, specifying an XML file containing the permissions in the permission set. To save you some time, here is a sample file corresponding to the 'Everything' permission set - just edit to suit your needs. When you have edited the sample, add it to the range of available permission sets like this:
caspol -ap samplepermset.xml
<PermissionSet class="System.Security.NamedPermissionSet" version="1">
- <Permission class="System.Security.Permissions.SecurityPermission, mscorlib, Ver=2000.14.1812.10, SN=03689116d3a4ae33" version="1">
<Assertion />
<UnmanagedCode />
<Execution />
<ControlThread />
<ControlEvidence />
<ControlPolicy />
<SerializationFormatter />
<ControlDomainPolicy />
<ControlPrincipal />
</Permission>
- <Permission class="System.Security.Permissions.IsolatedStorageFilePermission, mscorlib, Ver=2000.14.1812.10, SN=03689116d3a4ae33" version="1">
<Unrestricted />
</Permission>
- <Permission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Ver=2000.14.1812.10, SN=03689116d3a4ae33" version="1">
<Unrestricted />
</Permission>
- <Permission class="System.Security.Permissions.FileDialogPermission, mscorlib, Ver=2000.14.1812.10, SN=03689116d3a4ae33" version="1">
<Unrestricted />
</Permission>
- <Permission class="System.Security.Permissions.FileIOPermission, mscorlib, Ver=2000.14.1812.10, SN=03689116d3a4ae33" version="1">
<Unrestricted />
</Permission>
- <Permission class="System.Security.Permissions.ReflectionPermission, mscorlib, Ver=2000.14.1812.10, SN=03689116d3a4ae33" version="1">
<Unrestricted />
</Permission>
- <Permission class="System.Security.Permissions.RegistryPermission, mscorlib, Ver=2000.14.1812.10, SN=03689116d3a4ae33" version="1">
<Unrestricted />
</Permission>
- <Permission class="System.Security.Permissions.UIPermission, mscorlib, Ver=2000.14.1812.10, SN=03689116d3a4ae33" version="1">
<Unrestricted />
</Permission>
<Name>SamplePermSet
<Description>By default this sample permission set is the same as the standard 'Everything' permission set - just edit to suit your needs.
</PermissionSet>
Then, to apply the permission set to a code group, do something like this:
caspol -cg 1.3 SamplePermSet
(By default, 1.3 is the 'Internet' code group)
8.7 I'm having some trouble with CAS. How can I troubleshoot the problem?
Caspol has a couple of options that might help. First, you can ask caspol to tell you what code group an assembly belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a particular assembly using caspol -rsp.
8.8 I can't be bothered with CAS. Can I turn it off?
Yes, as long as you are an administrator. Just run:
caspol -s off
9. Intermediate Language (IL)
9.1 Can I look at the IL for an assembly?
Yes. MS supply a tool called Ildasm that can be used to view the metadata and IL for an assembly.
9.2 Can source code be reverse-engineered from IL?
Yes, it is often relatively straightforward to regenerate high-level source from IL. Lutz Roeder's Reflector does a very good job of turning IL into C# or VB.NET.
9.3 How can I stop my code being reverse-engineered from IL?
You can buy an IL obfuscation tool. These tools work by 'optimising' the IL in such a way that reverse-engineering becomes much more difficult.
Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL.
9.4 Can I write IL programs directly?
Yes. Peter Drayton posted this simple example to the DOTNET mailing list:
.assembly MyAssembly {}
.class MyApp {
.method static void Main() {
.entrypoint
ldstr "Hello, IL!"
call void System.Console::WriteLine(class System.Object)
ret
}
}
Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.
9.5 Can I do things in IL that I can't do in C#?
Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays.
10. Implications for COM
10.1 Does .NET replace COM?
This subject causes a lot of controversy, as you'll see if you read the mailing list archives. Take a look at the following two threads:
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D=0& P=68241 http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R6
0761
COM is about introducing type into components, period. The primary theme of COM was that we loaded code based on types (CoCreateInstance) and that we resolved entry points based on types (QueryInterface). This was a big advance from the days when we loaded code based on files (LoadLibrary) and resolved entry points based on flat symbolic names (GetProcAddress). Nothing in CLR changes that. The context architecture of MTS made this loader extensible, allowing aspects of your implementation to be expressed via declarative attributes as well as executable statements.
Where classic COM has always fallen short was in the area of runtime type information. In classic COM, the TLB describes the EXPORTED types only. IMPORTED types are opaque, as are INTERNAL types used within the
component boundary. The former makes it impossible to perform dependency analysis for deployment, versioning, etc. The latter makes it
impossible for certain classes of services to do anything useful without massive programmer intervention. Thankfully, CLR provides the system with
"perfect" type information, which as you well know, enables tons of goodness from both MS and third parties.
Focusing on things like GC or IL/JIT performance is really a red herring, and it looks like you have avoided that trap. Your comment, however, really cuts to the chase in terms of the "soul of COM" - that is, the role of the interface.
In classic COM, all object references were interface-based. In CLR, object references can be either interface-based or class-based. Yes, many of the folks at MS now advocate using classes in many of the scenarios where interfaces were used in the past. In the intra-component case where incremental deployment is a non-issue, this shouldn't seem so radical, as most of today's COM components use class-based references internally (most ATL programmers work this way, I know I do). In fact, I am personally glad that the same technology I use for loading cross-component types is used for intra-component types. This solves tons of the old VB "New vs. CreateObject" bugs that today's COM programmers still battle.
For inter-component sharing of class-based references, the water is more murky. On the one hand, if you look at passing class-based references as parameters, your aren't that far off from passing structs, and as long as you stick to sealed, MBV, class definitions that are immutable, this should be pretty easy to swallow. The more problematic case is where abstract classes are used in lieu of interfaces. Personally, I am still skeptical about this one, but I see (but don't necessarily agree with) the arguments in favor of the approach. As is always the case, the community at large figures our which parts of a programming model make sense and which don't, so I am willing to be proven wrong. As far as I can tell, none of the ideas worth keeping from the IUnknown era have been dropped. Rather, the big four concepts of COM (contexts, attributes, classes and interfaces) simply have a better supporting implementation called CLR, which until not that long ago was called "COM+" (run REGASM.exe and look up your code in the registry ;-)).
So, is CLR COM? If you think COM is IUnknown and a set of APIs, then the answer is no*. If you think COM is a programming model based on typed components, interfaces, attributes and context, then the answer is yes. I fall firmly in the latter camp, so to me, CLR is just better plumbing for the same programming model I've spent years working with.
The bottom line is that .NET has its own mechanisms for type interaction, and they don't use COM. No IUnknown, no IDL, no typelibs, no registry- based activation. This is mostly good, as a lot of COM was ugly. Generally speaking, .NET allows you to package and use components in a similar way to COM, but makes the whole thing a bit easier.
10.2 Is DCOM dead?
Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on DCOM. DCOM was pretty much dead anyway, once firewalls became widespread and Microsoft got SOAP fever. Of course DCOM will still be used in interop scenarios.
10.3 Is COM+ dead?
Not immediately. The approach for .NET 1.0 was to provide access to the existing COM+ services (through an interop layer) rather than replace the services with native .NET ones. Various tools and attributes were provided to make this as painless as possible. Over time it is expected that interop will become more seamless - this may mean that some services become a core part of the CLR, and/or it may mean that some services will be rewritten as managed code which runs on top of the CLR.
For more on this topic, search for postings by Joe Long in the archives - Joe is the MS group manager for COM+. Start with this message:
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R6
8370
10.4 Can I use COM components from .NET programs?
Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to .NET- compatible types.
Here's a simple example for those familiar with ATL. First, create an ATL
component which implements the following IDL:
import "oaidl.idl";
import "ocidl.idl";
[
object,
uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206), helpstring("ICppName Interface"), pointer_default(unique),
oleautomation
]
interface ICppName : IUnknown
{
[helpstring("method SetName")] HRESULT SetName([in] BSTR name); [helpstring("method GetName")] HRESULT GetName([out,retval] BSTR *pName );
};
[
uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D), version(1.0),
helpstring("cppcomserver 1.0 Type Library")
]
library CPPCOMSERVERLib
{
importlib("stdole32.tlb");
importlib("stdole2.tlb"); [
uuid(600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70),
helpstring("CppName Class")
]
coclass CppName
{
[default] interface ICppName;
};
};
When you've built the component, you should get a typelibrary. Run the
TLBIMP utility on the typelibary, like this:
tlbimp cppcomserver.tlb
If successful, you will get a message like this:
Typelib imported successfully to CPPCOMSERVERLib.dll
You now need a .NET client - let's use C#. Create a .cs file containing the following code:
using System;
using CPPCOMSERVERLib;
public class MainApp
{
static public void Main()
{
CppName cppname = new CppName();
cppname.SetName( "bob" );
Console.WriteLine( "Name is " + cppname.GetName() );
}
}
Compile the C# code like this:
csc /r:cppcomserverlib.dll csharpcomclient.cs
Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using TLBIMP. You should now be able to run csharpcomclient.exe, and get the following output on the console:
Name is bob
10.5 Can I use .NET components from COM programs?
Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW (see previous question), but works in the opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW can be developed. Also, for COM to 'see' the .NET component, the .NET component must be registered in the registry.
Here's a simple example. Create a C# file called testcomserver.cs and put the following in it:
using System;
using System.Runtime.InteropServices;
namespace AndyMc
{
[ClassInterface(ClassInterfaceType.AutoDual)]
public class CSharpCOMServer
{
public CSharpCOMServer() {}
public void SetName( string name ) { m_name = name; }
public string GetName() { return m_name; }
private string m_name;
}
}
Then compile the .cs file as follows:
csc /target:library testcomserver.cs
You should get a dll, which you register like this:
regasm testcomserver.dll /tlb:testcomserver.tlb /codebase
Now you need to create a client to test your .NET COM component. VBScript will do - put the following in a file called comclient.vbs:
Dim dotNetObj
Set dotNetObj = CreateObject("AndyMc.CSharpCOMServer")
dotNetObj.SetName ("bob")
MsgBox "Name is " & dotNetObj.GetName()
and run the script like this:
wscript comclient.vbs
And hey presto you should get a message box displayed with the text "Name is bob".
An alternative to the approach above it to use the dm.net moniker developed by Jason Whittington and Don Box.
10.6 Is ATL redundant in the .NET world?
Yes. ATL will continue to be valuable for writing COM components for some time, but it has no place in the .NET world.
11. Miscellaneous
11.1 How does .NET remoting work?
.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet).
Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format.
There are a number of styles of remote access:
SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished. Singleton. All incoming requests from clients are processed by a single server object.
Client-activated object. This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it.
Distributed garbage collection of objects is managed by a system called
'leased based lifetime'. Each object has a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure. Objects have a default renew time - the lease is renewed when a successful call is made from the client to the object. The client can also explicitly renew the lease.
If you're interested in using XML-RPC as an alternative to SOAP, take a look at Charles Cook's XML-RPC.Net.
11.2 How can I get at the Win32 API from a .NET program?
Use P/Invoke. This uses similar technology to COM Interop, but is used to access static DLL entry points instead of COM objects. Here is an example of C# calling the Win32 MessageBox function:
using System;
using System.Runtime.InteropServices;
class MainApp
{
[DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true, CharSet=CharSet.Auto)]
public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType);
public static void Main()
{
MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 );
}
}
Pinvoke.net is a great resource for off-the-shelf P/Invoke signatures.
11.3 How do I write to the application configuration file at runtime?
Why Writing Into .NET Application Configuration Files Is a Bad Idea -
I seem to write about this often enough in news groups and mailing lists that
I thought I'd put it up here - that way I can just post a link next time...
.NET applications can have a configuration file associated with them. In web apps, the file is called web.config. For a normal Windows or console application, it is has the same name as the executable with .config tacked on
the end. So if your app is called Foo.exe, you would put the configuration file in the same directory and call it Foo.exe.config. In Visual Studio .NET projects, the file will be called App.config - VS.NET copies it into your build output directory and changes the name appropriately.
.NET itself looks for certain settings inside this file. For example, the assembly resolver can be configured this way. It can also be used to store some application-specific settings in its
How do I write settings into the application configuration file at runtime?
The short answer is: "Don't do that."
The slightly more informative but still fairly succinct answer is: "You quite often can't, and even when you can you don't want to."
Here's the long answer.
Why the Config File Might Not Be Writable
The configuration file is stored in the same directory as the executable itself. It's pretty common for users not to have permission to write to this directory. Indeed that's just common sense and good practice - ensuring that the user doesn't have permission to write into directories where executables are stored prevents a lot of viruses, spyware, and other malware from wreaking havoc.
This is why the Program Files directory is configured not to allow normal users to write to it.
Unfortunately, not everyone runs as a normal user - lots of people run as administrators on their Windows machines. This is a shame as it means they are throwing away a lot of the protection Windows can offer them. Of course one of the reasons so many people run as administrators is because of crappy applications that attempt to write into their installation directories.
Don't make your application one of those crappy applications. Don't try and write into the directory where your application is installed, because if you do that, your program won't run properly unless the user is an administrator.
Of course there may be other reasons that the file isn't writable. If your application is deployed via HTTP, the configuration file will live on the web server, and you are unlikely to be able to modify it.
No comments:
Post a Comment