【简】
The proportion of computers and information crimes is gradually rising in a quite a long period of time in the past. The US Federal Investigation, computer security organization found 85% of corporate safety of 85% of enterprises in the 2001 research investigation. The property loss reports submitted after these companies were investigated, with a total loss of 300 million US dollars, an increase of 42% compared to 2000 million $ 200,000. It can be clearly seen that the number of hours of computers and information crimes is increasing, and the damage caused by it is increasingly, and the means of crime is increasingly rich, and the enterprise security personnel will prevent it. Therefore, companies must have actions to protect valuable information assets. Naturally, safety is increasingly incorporated in the current program development. Traditional security models provide isolation and access control to the mechanism of users and user groups. This means that the user can run all code, or it cannot be run. And this is now the safety model taken by most operating systems, even if this mechanism is now very effective, we can find that the assumption that this mechanism exists is that all code has the same trust. When all the code is from you or your system administrator, then this assumption is effective. But now most computers have been connected to the Internet, this kind of "all" or "all don't do" is not so good. The .NET framework provides a comprehensive security system enough to cope with most of the current security issues. The traditional model is provided in the .NET framework, but is a security model that is customized by the developer, called Role-based Security. The most important concept based on role is authorization (Identity).
Role-based security
Simply put, the purpose of program security is to prevent uncomfortable people or procedures cannot do things that administrators and developers don't allow. The traditional security mechanism mentioned earlier focuses on controlling the permissions of the user, limiting the user's operation by verifying the user's identity, so that a particular user can access the resources, in the past, Windows and Both the two most successful operating systems in Unix have taken this safety mechanism. Before discussing .NET security programming, we will first look at the security model provided by the .NET platform, only in-depth understanding of the security model, we can use the platform to provide better security guarantees (hereinafter discussed The operating system is dominated by Windows 2000 and Windows XP).
The security model of .NET is in the upper layer of the system's security model, and it is good to combine with some server programs (of course, these products are only limited to Microsoft's own products, such as SQL Server and Internet Information Services (IIS)). . Because .NET is different from the hierarchy of the operating system, the security of the .NET program depends on how such factors: .Net security is configured, how the program component is written, and some by Windows, network settings or The security features set by other programs.
The following figure illustrates how the .NET security model works on Windows security subsystem. Administrators use the management console Snap-Ins to set up user accounts and set security policies. At the same time, administrators are also responsible for managing .NET security configuration. When the user logs in the operating system and runs the .NET managed program, the CLR will verify the user and allow the program to perform some actions, then pass these operations to the operating system's security monitor.
However, there is a question that requires special attention, that is, no matter how you use .NET security, resources remain under the protection of operating system levels. For resource-specific resources, the security permissions of .NET platform are unable to force (in fact, this is also in line with the relationship between .NET and operating system). Let's take a detailed look at several concepts based on role-based security, and how these concepts are used in .NET.
Authentication refers to the process of determining the user's identity, and authorization refers to the permissions of the user to access a particular resource after passing the above process. Description Who is a little bit, verifying is "who you are", and authorization Is it "what can you do?" .NET provides Principal and Identity objects to implement these two processes, where role-based security base is established on the Principal object, which encapsulates the current user's information, which contains the user's identity, also contains the role he played. The user identity is indicated by Identity object, which not only contains the specified user identity information (user name or account), but also "how to verify this identity".
Identity object
The Identity object is an instance of a class that implements the IIDENTITY interface. The Iidentity interface consists of three readite properties:
String AuthenticationType {get;} Get the type of authentication used
Bool isauthenticated {get;} Get the Boolean value, indicating whether the login user is verified
String name {get;} Get the name of the current user
The following four classes of the .NET implementation:
1. GenericIdentity is used to represent a general user, which can be used to customize the login verification.
2, Windowsidentity is used to indicate a normal Windows user who has successfully logged in to the Windows system.
3, FormSidentity is used to represent users using Forms authentication in the ASP.NET application.
4. PassportIndentity is used to represent users in applications using Passport. However, pay attention to the PASSPORT SDK can be installed to use this class.
Because the most used in the current specific development is the top three, and the FormSIDENTITY class will specifically speak in the following article, so we will discuss the first two classes in detail.
GenericIdentity class
The GenericIdentity class is actually quite simple, it is not associated with any particular verification protocol. Therefore, it is often used in applications with custom landing mechanisms. For example, a program can prompt users to enter usernames and passwords, then go to custom user databases to query. If the username and password are valid, the program creates a Principal and (corresponding) Identity object based on matching records in the database.
The GenericIdentity class has no more things except for the three IIDENTITY interfaces defined. However, the GenericIdentity class provides two constructor. A constructor accepts a string parameter, which specifies the username; another constructor accepts two parameters: the first is a username string, the second is a given verification type string.
Public genericidentity (String name);
Public GenericIdentity (String Name, String Type);
Now let's talk more about the details of the GenericIdentity class, after we will see how you use GenericIdentity objects in an actual program.
The WindowsIdentity class acts as a derived class that implements the IIDENTITY interface, and the WindowsIdentity class is mainly used to indicate users who have successfully logged in to Windows. Let's take a look at the constructor, properties, and methods of the Windowsidentity class.
In the constructor, you will use the INTPTR type parameters, let's take a look at this data type, the intPtr type is usually used to represent the data type associated with the platform, such as a memory pointer or a handle. In our case, the intPtr parameter is usually used to represent a Win32 handle, and this handle points to an account tag for a 32-bit user (Account token). This tag is typically obtained by calling the unmanaged Win32 API.
Public WindowsIdentity (INTPTR USERTOKEN);
Public WindowsIdentity (INTPTR USERTOKEN, STRING Authtype);
Public WindowsIdentity (INTPTR USERTOKEN, STRING Authtype, WindowsAccountType AcctType);
Public WindowsIdentity (INTPTR USERTOKEN, STRING Authtype, WindowsAccountType AccTtype, Bool IsAuthentic);
Each constructor has the same INTPTR parameter, followed by some parameters with other information: verification type, Windows account type, and verification status. Note that the WindowsAcCountType parameter must use one of the following enumeration values: Anonymous, Guest, Normal, System.
For a reason, the Windowsidentity class also has three readite properties of the Iidentity interface: AuthenticationType, ISAUThenticated, and Name. In addition, the Windowsidentity class has its own unique properties: Isanonymous, ISGUEST, and ISSYSTEM, with these three properties can better determine user accounts.
Then come and see the method of the Windowsidentity class. In addition to the way to inherit in the Object class, the WindowsIdentity class has three ways: getanonymous, getcurrent, and impersonate.
1. The getanonymous method returns a WindowsIdentity object that represents an anonymous user.
2. The getCurrent method returns a WindowsIdentity object that represents the current user.
3, the Impersonate method allows you to temporarily simulate a user.
Both the GetAnonymous and getCurrent methods returns a WindowsIdentity object, which is also very simple, we need to pay attention to the Impersonate method, which has two versions: instance version (Instance Version) and static versions. The method of the instance version does not with the parameters, returns a WindowsimPersonationContext object based on the called WindowsIdentity object (Windows IMPERSOTIONContext class represents a Windows user before analog operation); static version requires an intPtr parameter. This simulation operation is useful for server programs, which can reduce the permissions of user accounts used by the client access server to a certain extent. Here is the specific syntax of the above method:
Public static windowsidentity getanonymous ();
Public static windowsidentity getcurrent ();
Public Virtual WindowsimpersonationContext Impersonate ();
Public Static WindowsimpersonationContext Impersonate (INTPTR USERTOKEN);
PRINCIPAL object
The Principal object is an instance of a class that implements the IPrInCIPAL interface, which is used to represent the user, and includes the user's identity information. System.security.principal namespace includes several types of Principal classes that encapsulate the security environment of the program code running. We will see later to check the username and role to determine if the user identity and the role can make the user to perform some of the sample code of certain specific operations.
For each thread is associated with a Principal object. This Principal object includes an IDENTITY object that represents a user running the current thread. We can use the static property of the Thread class CurrentPrincipal to get this Principal object.
Let's take a look at the iprincipal interface, which only has an Identity public property and isinrole public method:
1. The Identity property points to a IIDENTITY object associated with the Principal object.
2. Isinrole method requires a string parameter that is a name of a role and returns a Boolean value indicating whether the Principal object belongs to the specified role.
Due to the actual development needs, we have more contact with the WindowsPrincipal class. The WindowsPrincipal class will be discussed in detail. Relatively, the genericprincipal class is just a short.
GenericPrincipal class
GenericPrincipal class is used to represent a user that is customized, usually used with the GenericIdentity class. Here is a simple program that explains how these two classes use:
// Create a generiDentity object
Iidentity MyGenericIdentity = New GenericIdentity (StruserName); "MyAuthenticationType";
// Create a GenericPrincipal object
String [] Roles = NULL;
GenericPrincipal MyGenericPrincipal = new genericprincipal (myGenericIdentity, Roles);
// Additional GenericPrincipal objects that will be created onto the current thread
Thread.currentprincipal = mygenericprincipal;
Note that in the above example, we can change the virtual Kerberos authentication or NTLM authentication of MyAuthenticationType or NTLM authentication.
The following is the process of verification:
/ / Get the Principal object of the current thread
IPrincipal Principal = Thread.currentPrincipal;
IF (! Principal.Identity.name.equals ("trusteduser"))
{
Throw new securityException
STRUSERNAME "not permitted to proceed./n");
}
Console.writeline
STRUSERNAME "is permitted to proceed./n" ";windowsprincipal class
The WindowsPrincipal class is a class that we most frequently implemented in the development of the IPrincipal interface, and the constructor is quite simple:
Public WindowsPrincipal (WindowsIdentity Ntidentity);
The following code illustrates how to create a WindowsPrincipal object:
Windowsidentity Wi = WindowsIdentity.getCurrent ();
WindowsPrincipal WP = New WindowsPrincipal (Wi);
What needs to be noted in the WindowsPrincipal class is the following three overloaded Isinrole methods:
Public Virtual Bool IsinRole (int);
The first load function accepts an integer parameter that represents the RID corresponding to the user group (RID is also the Domain-Relative SubauThority ID associated with the domain). RID values are defined in the header file Winnt.h Platform SDK's, Winnt.h included some common users and groups, such as DOMAIN_USER_RID_ADMIN, DOMAIN_USER_RID_GUEST, DOMAIN_GROUP_RID_ADMINS, DOMAIN_GROUP_RID_USERS and DOMAIN_GROUP_RID_GUESTS etc., can ... / Microsoft Visual Studio .NET This file is found in the / VC7 / PlatformSDK / INCLUDE folder.
Public Virtual Bool Isinrole (String);
The second load function accepts a string parameter that represents a user group name, such as MyComputer / Developer (MachineName / Groupname) represents the developer user group on the computer name MyComputer. However, for the system built-in user group, it cannot be said, such as Administrators, cannot be represented as MyComputer / Administrators, and should be like Builtin / Administrators, but this always feels a bit of a bit, not natural. So we can use the following overload function.
Public Virtual Bool IsinRole (WindowsBuiltinrole);
The third load function accepts a WindowsBuiltinrole enumeration type parameter, below is the value defined in the WindowsBuiltinrole enumeration:
1, Accountoperator - Manage the user account on your computer or in the domain.
2, administrator - can access computer or domain arbitrarily
3, Backupoperator - You can perform backup and recovery operations on your file system.
4, Guest- and User, but there are more restrictions.
5, PowerUser- and administrator status, but there are some restrictions.
6, Printoperator - Perform a print operation.
7, replicator - execute file replication in the domain.
8, Systemoperator - Manage Computers.
9. User-users cannot perform hazards or affect the entire system. Permissions object
As two important branches of .NET security, role-based security and code access security are inseparable from an important concept - permission (Permissions). In role-based security, the PrincipalPerMission class is used to check the user identity of the calling thread; and in the code access security, the class derived from the CodeAccessPermission is used to check all threads that perform the current method. Permissions. Permissions objects are permitted or rejected by existing security policies. For code access security (but this does not apply to user rights), the NET CLR provides a stack traversal mechanism to determine if all call stack frames have permissions. It is important to note that if the Permission object is null, then we can treat it and permissionstate.none as equivalent, indicating that no permissions are provided. Permissions are commonly used in the following occasions:
1. Define the permissions required to execute the code.
2. The security policy of the system can recognize or reject the permission of the code request.
3. The code is guaranteed by the Demand method (requires) the code it calls has the required permissions.
4, code can also use Assert, Deny or Permitonly method to skip the security stack checking mechanism.
In addition, we can also use the group's permissions, we can use a variety of different permission groups in the Permissionset class.
Let's first take a look at the most commonly used PrincipalPermission class, as for another commonly used CodeAccessPermission class, will later introduce in the contents of the code access secure.
As one of the three interfaces implemented by the PrincipalPermission class, the iPermission interface has a pivotable role in the PrincipalPerMission class. The iPermission interface provides the following methods:
1. Copy created and returned the same copy of the current permissions.
2, Demand If the contents of the stack do not meet the permissions specified by the permission object, SECURITYEXCEPTION will be triggered at runtime. This method can make the current code will not be utilized by other malicious code.
3, INTERSECT creates and returns a permission, which is the intersection of current permissions and specified permissions.
4. Issubsetof determines if the current permissions are subset of specified permissions.
5, Union creates a permission that is the pane of current permissions and the specified permissions.
In the methods listed above, the Demand method is the most commonly used method. The Demand method checks all the calvity of the current method to determine if they have sufficient permission access to access specific resources in a specified manner (usually checking the latest calling method on the calling stack, starting through the full stack traversal To meet safety conditions, but the stack traversal is not necessary, PrincipalPermission.Demand does not make stack traverses), if check failed, the Demand method throws the securityException exception, only without any exception thrown, the Demand method successfully returned .
The following figure shows the inheritance level of the iPermission interface:
[IMGHTTP: //myArticle.net.com.cn/images/200407/1090981312024.gif [/ img]
Then we will discuss the PrincipalPermission class, here you need to talk about the Principal object in front, when executing the Demand method at the instance of the PrincipalPermission class, actually in determining whether the current Principal object matches the given PrincipalPermission object, if not match, I will throw SecurityException. In addition, the Demand method can also be used to force the Identity authentication of the Principal object so that it can do not throw an exception and perform normal operation. The following code snippet shows how to use the PrincipalPerMission object:
String User1 = "abbott";
String role1 = "strightman";
PrincipalPermission PrincipalPerM1 =
New PrincipalPermission (user1, role1);
String user2 = "costello";
String role2 = "funnyman";
PrincipalPermission PP =
New PrincipalPerMission (user2, role2);
PrincipalPerm1.union (PP) .demand ();
The above code illustrates how to use the two PrincipalPerMission objects, after the merge, if the user is the abbott of the Straightman role or the costello of the funnyman role, then Demand will successfully return.
The above is based on the basic class and some sample code required for role security. I hope that everyone can happen from the above content .NET security door hall, better application .NET security to develop security program of.