CAS 代码访问安全性 (翻译)

前言:

用vs2005 + vsto 开发一个outlook的addin的时候,碰到了一个问题,在我机器上运行的好好的程序,用vs自己的打包安装程序安装到别的机器的时候总是显示 not load, 加载程序的时候出错。google了一下,遇到了一个新名词, CAS: code access security. 找不到相关的中文文档。在codeproject上看到了这篇文章。文章比较长,有codeproject的文风,讲解的非常详细,就是一点基础都没有的人都知道他说什么,但是要耐心看。 ^_^

Role Based Security (not being discussed in this article) 基于角色的安全验证

Code Access Security代码访问安全性

CLR允许代码做那些只被授权的行为,所以,CAS是一种通过阻止未授权的访问来保护资源和操作的一种安全系统。运用CAS,你可以做到:

指定你的代码能够做的

指定那些代码可以代用你的代码

唯一标识你的代码

我们将在这篇文章讨论这些问题,你应该熟悉一些术语。

 

术语

 

CAS包含一下这些元素:

  • permissions  许可

  • permission sets 许可集

  • code groups 代码组

  • evidence 物证

  • policy 策略

Permissions

Permissions 声明对受保护的资源的访问或者是执行受保护的操作的能力。.Net Frameword提供了一些Permission 的类,像 FileIOPermission(对文件起作用),UIPermission(允许使用一些用户接口),SecurityPermission(对于执行代码甚至是绕过安全机制这是必须的)。我将不会列举所有的Permission类在这里,他们列举在下面。

Permission sets

一个Permission Set是一个permission的容器。你可以把FileIOPermissionUIPermission放到你的Permission set中,然后叫他“My_PermissionSet”。一个Permission set可以包含许多permissionsFullTrust, LocalIntranet, Internet, Execution Nothing .net framework内置的一些permission setsFullTrust包含所有的permissions,而Nothing则表示什么都不包括,甚至连执行的权利都没有。

Code groups

Code group是一个特定条件下的代码逻辑组。http://www.somewebsite.com/的代码可以属于一个代码组,包含一个特定的强类型名字的代码属于另一组,特定装配的代码又属于一个组。内置的代码组像My_Computer_Zone, LocalIntranet_Zone, Internet_Zone 等等。像permission sets,我们可以创建代码组来满足我们基于evidence的需求。Site, Strong Name, Zone, URL是一些evidence的类型。

Policy

Security policy是可配置的规则的集合,当我们决定赋予代码一定的许可。有4个机制的等级Enterprise, Machine, User Application Domain,每种操作不互相依赖。每个等级有它自己的code groupspermission sets。他们的层次如下:


【图一】

Ok,理论说完了,让我们把理论付诸实践。

 

小例子

 

让我们创建一个新的windows应用程序。添加2button到存在的form上。我们将用到文件系统,所以添加System.IO命名空间。

using System.IO;



【图二】

写下如下代码:

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> 1  private   void  btnWrite_click( object  sender, System.EventArgs e)
{    
StreamWriter myFile  =   new  StreamWriter( " c:\\Security.txt " );   
myFile.WriteLine( " Trust No One " );   
myFile.Close();
}

private   void  btnRead_click( object  sender, System.EventArgs e)
{    
StreamReader myFile  =   new  StreamReader( " c:\\Security.txt " );   
MessageBox.Show(myFile.ReadLine());  
myFile.Close()
}


完整的版本号我们的例子才能够工作。确定你设置了你的版本号为一个固定的值,否则它会随着你的编译次数自动增加。我们标记这个装配用一个强名字,这将被用做evidence时标识代码用。这就是为什么你需要设置你的版本号为一个固定的值。

[assembly: AssemblyVersion("<chsdate isrocdate="False" islunardate="False" day="30" month="12" year="1899" w:st="on">1.0.0</chsdate>.0")]

就这样。。。没有什么异常。它将会写一个名字为security.txt的文件到c:.现在跑起来你的代码,它将会创建一个文件并写下一行,每件事看起来都ok。。。除非你没有c盘。现在我们要做的事把我们的装备到一个code group,并且设置一些permissions。还不要删除security.txt文件,我们晚点会需要它。

NET Configuration Tool

我们可以用两种方式来做这个工作,从.NET Configuration Tool或者是用命令行调用caspol.exe。 首先我们用.NET Configuration Tool。从控制面板——》管理工具-》Microsoft .NET Framework Configuration。 你也可以用“mscorcfg.msc”在.net 命令行。你可以做很cool的事情通过这个工具。。但是目前我们只是对设置代码访问权限感兴趣。


【图三】

Creating a new permission set创建一个新的permission set

展开runtime security policy节点。你可以看到安全机制级别Enterprise, Machine User。我们将改变Machine机制的安全集合。首先我们创建我们自定义的permission set。右击permission sets节点选择new。因为我到别的易记住的名字,我命名它为MyPermissionSet.


【图四】

我将在下一个屏幕添加permissionspermission set。在左边的panel,我们可以看到.NET Framework支持的所有的permissions。现在我们得到File IOpermission属性。设置File path c:\ 然后只选上read。所以我们没有赋予写的权限。请注意那里还有另一个选项说“准许装备自由的访问文件系统”如果这个被选上,任何事情都可以做,没有任何限制。


【图五】

现在我们多添加2p’ermissions Security User Interface只需要添加记住添加“准许装备自由的访问文件系统”。我很快将会解释这些属性。没有Security permission。我们没有权限去执行我们的代码,没有User Interface p’ermission,我们将不会看到UI。如果你添加了这3permissions,你会看到有一个新的permission set被创建,命名为MyPermissionSet.

 

Creating a new code group创建一个新的代码组

现在我们创建一个code group然后设置一些条件,所以我们的装配将会是这个code group的一员。注意在code group机电,All_Code是父节点。右击All_Code节点选择new。创建code group向导将呈现在你面前。我将命名它为MyCodeGroup.




【图六】

下一个屏幕,你需要提供一个condition类型给code group。这些就是之前提到过的evidence。在这个例子中,我们用strong name类型。首先标识你的装配用一个strong name然后编译它。现在我们按import(导入)按钮选择你的装配。Public key,名字和版本将从装配中萃取出来,我们不需要考虑它。现在我们到下一个页面。我们必须为我们的code group指定一个permission set。因为我们已经创建了一个MyPermissionSet,,我们从list box中选他。


【图七】

Exclusive and LevelFinal

如果你还没有被。NET configuration默认的安全设置搞混淆,你的装配已经属于另一个内置的code group My_Computer_Zone。当permission被计算,如果一个特别的装配属于多个code group在相同的机制级别,最后的permissions将是所有的code grouppermissions的集合。我将晚点解释怎么计算permissions,现在我们只需要跑我们的装配用我们的permission set,就是用MyPermissionSet关联的MyCodeGroup. 所以我们必须设置其他的属性来达到这个目的。右击新创建的MyCodeGroup节点选择属性。选择check box "This policy level will only have the permissions from the permission set associated with this code group." 这个机制等级的permission只包含与这个code group关联的permission set。这个叫Exclusive属性。如果这个被选上了,运行时将不会允许除关联到这个code grouppermissions。另一个选项叫做LevelFinal.这两个属性将在计算permissions的时候起作用,我们将详细解释它在下面。


【图八】

我们已经设置了许多属性,但是它将在最后讲得通。 :-<

 

好了,现在我们来跑我们得代码。我们现在做得就是把我们得代码放到一个code group中,并且给她对c盘得只读得权限,跑它并按那两个按钮,read工作得很好,但是当你按write得时候,一个exception抛出了,因为我们没有对c盘写得权限。下面时出错得信息。


【图九】

所以多谢code access security,这种对资源得限制是可行的。通过CAS你可以做很多事情,我们讲在余下得文章中讨论。

Functions of Code Access Security

根据文档,CAS充当了一下这些功能:(直接从文档上复制过来的)

  • Defines permissions and permission sets that represent the right to access various system resources.

  • Enables administrators to configure security policy by associating sets of permissions with groups of code (code groups).

  • Enables code to request the permissions it requires in order to run, as well as the permissions that would be useful to have, and specifies which permissions the code must never have.

  • Grants permissions to each assembly that is loaded, based on the permissions requested by the code and on the operations permitted by security policy.

  • Enables code to demand that its callers have specific permissions. Enables code to demand that its callers possess a digital signature, thus allowing only callers from a particular organization or site to call the protected code.

  • Enforces restrictions on code at run time by comparing the granted permissions of every caller on the call stack to the permissions that callers must have.

我们已经做了最顶上的2个,那是管理的部分。有一个独立的命名空间我们还没有看过System.Security,这个是用来实现安全的。

 

Security Namespace

System.Security命名空间下的主要的类有:

Classes

Description

CodeAccessPermission

定义下面的结构所有的代码访问权限

PermissionSet

申明一个包含不同permissions的集合

SecurityException

当检测到安全错误的时候抛出的异常

System.Security.Permissions 命名空间下的主要的类有:

Classes

Description

EnvironmentPermission

控制对系统和用户环境变量的访问权限

FileDialogPermission

通过文件对话框控制对文件和文件夹的访问权限

FileIOPermission

控制对文件和文件夹的访问权限

IsolatedStorageFilePermission

指定对私有的虚拟文件系统的使用方式.

IsolatedStoragePermission

指定对普通的独立存储的访问权限

ReflectionPermission

控制对metadata访问通过System.Reflection APIs.

RegistryPermission

控制对注册表的访问

SecurityPermission

描叙安全的permissions应用到code

UIPermission

控制UI和键盘的权限

你能找到更多的permission 类 在其他的命名空间,例如,SocketPermission WebPermission System.NetSqlClientPermission System.Data.SqlClient 命名空间, PerformanceCounterPermission System.Diagnostics 命名空间等等。

下一步,我们将看到怎么使用这些类。

Declarative vs. Imperative(声明和命令)

你在写代码的时候可以用两种不同的语法,声明和命令。

Declarative syntax声明语法

生命语法用需要的安全信息属性去标识方法,类或者是装配。所以当编译的时候,他们替换相应的元数据章节。


<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->  1  [FileIOPermission(SecurityAction.Demand, Unrestricted = true )]
 2 
 3  public  calss MyClass
 5  {
 7       public  MyClass() {}    //  all these methods
 9       public   void  MyMethod_A() { //  demands unrestricted access to 
11       public   void  MyMethod_B() { //  the file system
13  }

命令语法

命令语法用运行时方法调用创建一个新的实例。


<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> public  calss MyClass 

{
    
public  MyClass() { }

    
public   void  Method_A() 
    {

        
//  Do Something

        FileIOPermission myPerm 
=  
          
new  FileIOPermission(PermissionState.Unrestricted);
        myPerm.Demand(); 
        
//  rest of the code won't get executed if this failed
 
        
//  Do Something
    }

    
//  No demands
     public   void  Method_B()
    {
        
//  Do Something
    }
}

他们2个的主要的不同是,声明调用是在编译的时候调用而命令调用是在运行时的时候。请注意编译的时候指的是在jit编译的时候。

这里有一些行为可能与permissions冲突。


首先,我们看一下声明的语法。用UIPermission来说,声明语法意思使用属性,所以我们实际使用UIPermissionAttribute,当你打开msdn你会看到这些属性:

  • Action - SecurityAction 枚举的一个值

  • Unrestricted – 自由访问

  • Clipboard – 对键盘的访问权限,UIPermissionClipboard 枚举的一个值 (UIPermission specific)

  • Window – 对窗体的访问权限 UIPermissionWindow 的一个值。

Action Unrestricted属性是通常类的permissionClipboard Window用来指明UIPermission。你必须提供action你使用其他属性的你用到的permission类。所以在这种情况下,你可以像这样写:


<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> [UIPermission(SecurityAction.Demand,
Clipboard
= UIPermissionClipboard.AllClipboard)]

或者添加Clipboard Window两个属性:


<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> [UIPermission(SecurityAction.Demand,
    Clipboard
= UIPermissionClipboard.AllClipboard, 
      Window
= UIPermissionWindow.AllWindows)]

如果你想要声明一个permission用自由访问,你可以这样做:

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> [UIPermission(SecurityAction.Demand, Unrestricted = true )]

当你使用命令语法,你可以使用构造函数来传递这些值,然后在属性中调用它的action。我们用RegistryPermission


<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> RegistryPermission myRegPerm  =  
   
new  RegistryPermission(RegistryPermissionAccess.AllAccess,
   
" HKEY_LOCAL_MACHINE\\Software " );
myRegPerm.Demand();

如果你想自由访问这些资源,你可是使用PermissionState枚举用如下的方法:


<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> RegistryPermission myRegPerm  =   new  
RegistryPermission(PermissionState.Unrestricted);
myRegPerm.Demand();

这是你调用任何permissions类所需要知道的在.NET Framework.。现在,我们将详细讨论actions

Security Demands

需求用来保证每一个调用你代码的调用者(间接的或者是直接的),已经得到需要的permission。这个通过一个栈来完成。什么...一个老鼠道?不,那是你女朋友做的,我的意思是一个栈道。请求一个permission,运行时安全系统浏览栈,比较每个调用者准许的permissions和被请求的permission。如果任何一个调用栈不能找到请求的permission,然后SecurityException抛出。请看如下的图:


图十】

不同的装配和不同的方法在相同的装配通过栈道来检查。

现在回到需求。这里有3种类型的需求。

  • Demand

  • Link Demand

  • Inheritance Demand




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值