mcts self paced training kit exam 70-536 microsoft net framework 3.5 application development foundation phần 8 ppt

82 295 0
  • Loading ...
1/82 trang

Thông tin tài liệu

Ngày đăng: 12/08/2014, 20:22

542 Chapter 12 User and Data Security // C# String[] myUser1Roles = new String[]{"IT", "Users", "Administrators"}; GenericPrincipal myPrincipal1 = new GenericPrincipal(myUser1, myUser1Roles); After creating the principal object in the previous code sample, myPrincipal1.IsIn- Role(“Users”) method would return true. How to Use RBS Demands with Custom Identities and Principals Whether you define custom IIdentity and IPrincipal interfaces or use GenericIdentity and GenericPrincipal, you can take advantage of the same declarative and imperative RBS techniques used for WindowsIdentity and WindowsPrincipal. To do this, perform the following steps in your application: 1. Create an IIdentity or GenericIdentity object representing the current user. 2. Create an IPrincipal or GenericPrincipal object based on your IIdentity object. 3. Set the Thread.CurrentPrincipal property to your IPrincipal object. 4. Add any declarative or imperative RBS demands required. The following Console application (which requires the System.Security.Permissions, Sys- tem.Security.Principal, and System.Threading namespaces) performs all these steps to demonstrate how to use declarative RBS demands with the GenericIdentity and Generic- Principal classes. In this example, only members of the IT role can run the TestSecurity method. Two identities and principals are created. The object myUser1, with the user- name JHealy, is a member of the IT role and should be able to run the method. The object myUser2, with the username TAdams, is not a member of that role: ' VB Sub Main() Dim myUser1 As GenericIdentity = New GenericIdentity("JHealy") Dim myUser1Roles As String() = _ New String() {"IT", "Users", "Administrators"} Dim myPrincipal1 As GenericPrincipal = _ New GenericPrincipal(myUser1, myUser1Roles) Dim myUser2 As GenericIdentity = New GenericIdentity("TAdams") Dim myUser2Roles As String() = New String() {"Users"} Dim myPrincipal2 As GenericPrincipal = _ New GenericPrincipal(myUser2, myUser2Roles) Try Thread.CurrentPrincipal = myPrincipal1 TestSecurity() Thread.CurrentPrincipal = myPrincipal2 TestSecurity() Lesson 1: Authenticating and Authorizing Users 543 Catch ex As Exception Console.WriteLine(ex.GetType.ToString + " caused by " + _ Thread.CurrentPrincipal.Identity.Name) End Try End Sub <PrincipalPermissionAttribute(SecurityAction.Demand, Role:="IT")> _ Private Sub TestSecurity() Console.WriteLine(Thread.CurrentPrincipal.Identity.Name + " is in IT.") End Sub // C# static void Main(string[] args) { GenericIdentity myUser1 = new GenericIdentity("JHealy"); String[] myUser1Roles = new String[]{"IT", "Users", "Administrators"}; GenericPrincipal myPrincipal1 = new GenericPrincipal(myUser1, myUser1Roles); GenericIdentity myUser2 = new GenericIdentity("TAdams"); String[] myUser2Roles = new String[]{"Users"}; GenericPrincipal myPrincipal2 = new GenericPrincipal(myUser2, myUser2Roles); try { Thread.CurrentPrincipal = myPrincipal1; TestSecurity(); Thread.CurrentPrincipal = myPrincipal2; TestSecurity(); } catch(Exception ex) { Console.WriteLine(ex.GetType().ToString() + " caused by " + Thread.CurrentPrincipal.Identity.Name); } } [PrincipalPermission(SecurityAction.Demand, Role = "IT")] private static void TestSecurity() { Console.WriteLine(Thread.CurrentPrincipal.Identity.Name + " is in IT."); } This application produces the following output, which verifies that the declarative RBS demand does protect the TestSecurity method from users who are not in the IT role: JHealy is in IT. System.Security.SecurityException caused by TAdams Handling Authentication Exceptions in Streams When authenticating to remote computers using the System.Net.Security.Negotiate- Stream or System.Net.Security.SslStream classes, the .NET Framework throws an excep- tion if either the client or server cannot be properly authenticated. Therefore, you 544 Chapter 12 User and Data Security should always be prepared to catch one of the following exceptions when using Nego- tiateStream or SslStream: Q System.Security.Authentication.AuthenticationException An exception of this type indicates that you should prompt the user to provide different credentials and then retry authentication. Q System.Security.Authentication.InvalidCredentialException An exception of this type indicates that the underlying stream is not in a valid state, and the user can- not retry authentication. Lab: Adding RBS to an Application In this lab, you will add RBS security to an application so that features are limited based on the user’s name and group membership. If you encounter a problem com- pleting an exercise, the completed projects are available along with the sample files. Exercise: Protect an Application with RBS In this exercise, you will update a Windows Forms calculator application to include RBS. You will use the most secure techniques possible to meet the following requirements: Q Only members of the Users group can run the method linked to the Add button. Q Only members of the Administrators group can run the multiply method. Q Only the CPhilips user can run the method linked to the Divide button. Q You must hide buttons to which users do not have access. 1. Navigate to the <InstallHome>\Chapter12\Lesson1\Exercise1\Partial folder and open either the C# version or the Visual Basic .NET version of the solu- tion file. 2. Add the System.Security.Permissions and System.Security.Principal namespaces to your code. 3. To enable you to check Windows group memberships, set the principal policy to Windows Policy. You should do this in a method that will run when the form opens, such as the form constructor (which might be hidden in a collapsed region titled Windows Forms Designer Generated Code). The following code works: ' VB Public Sub New() MyBase.New() InitializeComponent() Lesson 1: Authenticating and Authorizing Users 545 ' Set the security policy context to Windows security System.AppDomain.CurrentDomain.SetPrincipalPolicy( _ PrincipalPolicy.WindowsPrincipal) End Sub // C# public Form1() { InitializeComponent(); // Set the security policy context to Windows security System.AppDomain.CurrentDomain.SetPrincipalPolicy( PrincipalPolicy.WindowsPrincipal); } 4. Address the first requirement, “Only members of the Users group can run the method linked to the Add button.” The following code works for the addButton_Click method: ' VB Try ' Demand that user is member of the built-in Users group. ' Because this method is called by a Windows event, protect it ' with an imperative RBS demand. Dim userPermission As PrincipalPermission = _ New PrincipalPermission(Nothing, "BUILTIN\Users") userPermission.Demand() ' Perform calculations Dim answer As Integer = (Integer.Parse(integer1.Text) + _ Integer.Parse(integer2.Text)) answerLabel.Text = answer.ToString() Catch ex As System.Security.SecurityException ' Display message box explaining access denial MessageBox.Show("You have been denied access: " + ex.Message) ' TODO: Log error End Try // C# try { // Demand that user is member of the built-in Users group. // Because this method is called by a Windows event, protect it // with an imperative RBS demand. PrincipalPermission userPermission = new PrincipalPermission(null, @"BUILTIN\Users"); userPermission.Demand(); // Perform the calculation int answer = (int.Parse(integer1.Text) + int.Parse(integer2.Text)); answerLabel.Text = answer.ToString(); } 546 Chapter 12 User and Data Security catch (System.Security.SecurityException ex) { // Display message box explaining access denial MessageBox.Show("You have been denied access: " + ex.Message); // TODO: Log error } 5. Address the second requirement, “Only members of the Administrators group can run the multiply method.” Because the multiply method is not called directly by a Windows event, you can use declarative security. The following code declaration protects the multiply method: ' VB <PrincipalPermission(SecurityAction.Demand, _ Role:="BUILTIN\Administrators")> _ // C# [PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")] 6. Address the third requirement, “Only the CPhilips user can run the method linked to the Divide button.” The following code works for the divideButton_Click method: ' VB ' Concatenate the computer and username Dim allowUser As String = System.Environment.MachineName + "\cphilips" Try ' Demand that user has the username "cphilips" on the local ' computer. Because this method is called by a Windows event, ' protect it with an imperative RBS demand. Dim p As PrincipalPermission = _ New PrincipalPermission(allowUser, Nothing) p.Demand() ' Perform super-secret mathematical calculations Dim answer As Decimal = (Decimal.Parse(integer1.Text) _ / Decimal.Parse(integer2.Text)) answerLabel.Text = Decimal.Round(answer, 2).ToString() Catch ex As System.Security.SecurityException ' Display message box explaining access denial MessageBox.Show("You have been denied access: " + ex.Message) ' TODO: Log error End Try // C# // Concatenate the computer and username string allowUser = System.Environment.MachineName + @"\cphilips"; try { // Demand that user has the username "cphilips" on the local // computer. Because this method is called by a Windows event, Lesson 1: Authenticating and Authorizing Users 547 // protect it with an imperative RBS demand. PrincipalPermission p = new PrincipalPermission(allowUser, null); p.Demand(); // Perform super-secret mathematical calculations Decimal answer = (Decimal.Parse(integer1.Text) / Decimal.Parse(integer2.Text)); answerLabel.Text = Decimal.Round(answer, 2).ToString(); } catch (System.Security.SecurityException ex) { // Display message box explaining access denial MessageBox.Show("You have been denied access: " + ex.Message); // TODO: Log error } 7. Address the fourth requirement, “You must hide buttons to which users do not have access.” You should do this in a method that runs when the form opens, such as the form constructor. The following code works: ' VB Public Sub New() MyBase.New() InitializeComponent() ' Create a WindowsIdentity object representing the current user Dim currentIdentity As WindowsIdentity = WindowsIdentity.GetCurrent() ' Create a WindowsPrincipal object representing the current user Dim currentPrincipal As WindowsPrincipal = _ New WindowsPrincipal(currentIdentity) ' Set the security policy context to Windows security System.AppDomain.CurrentDomain.SetPrincipalPolicy( _ PrincipalPolicy.WindowsPrincipal) ' Hide the subtract and multiply buttons if the user ' is not an Administrator If Not currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator) Then subtractButton.Visible = False multiplyButton.Visible = False End If ' Hide the Add button if the user is not in the Users group If Not currentPrincipal.IsInRole(WindowsBuiltInRole.User) Then addButton.Visible = False End If ' Hide the Divide button if the user is not named CPhilips If Not (currentIdentity.Name.ToLower() = _ System.Environment.MachineName.ToLower() + "\cphilips") Then divideButton.Visible = False End If End Sub 548 Chapter 12 User and Data Security // C# public Form1() { InitializeComponent(); // Create a WindowsIdentity object representing the current user WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); // Create a WindowsPrincipal object representing the current user WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity); // Set the security policy context to Windows security System.AppDomain.CurrentDomain.SetPrincipalPolicy( PrincipalPolicy.WindowsPrincipal); // Hide the subtract and multiply buttons if the user // is not an Administrator if (!currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) { subtractButton.Visible = false; multiplyButton.Visible = false; } // Hide the Add button if the user is not in the Users group if (!currentPrincipal.IsInRole(WindowsBuiltInRole.User)) addButton.Visible = false; // Hide the Divide button if the user is not named CPhilips if (!(currentIdentity.Name.ToLower() == System.Environment.MachineName.ToLower() + @"\cphilips")) divideButton.Visible = false; } 8. Build and run your project. Test it when running with different user accounts, including a user account named Cphilips, a user account that is a member of the Administrators group, and a user account that is only a member of the Users group. Lesson Summary Q Authentication, such as checking your photo identification, verifies your identity by requiring you to provide unique credentials that are not easily impersonated. Authorization, such as checking your plane ticket, verifies that you have permis- sion to perform the action you are attempting. Authentication, which determines who you are, must happen before authorization, which determines whether you are allowed to access a resource. Lesson 1: Authenticating and Authorizing Users 549 Q The WindowsIdentity class provides .NET Framework applications access to a Windows user’s account properties. You can examine the current user’s user- name and authentication type by creating a new WindowsIdentity object using the WindowsIdentity.GetCurrent method. Q The WindowsPrincipal class enables assemblies to query the Windows security database to determine whether a user is a member of a particular group. To exam- ine the current user’s group memberships, create a WindowsPrincipal object by using the current user’s identity and then call the WindowsPrincipal.IsInRole method. Q You use the PrincipalPermission class to specify username, role, and authentication requirements. Q Declarative RBS demands restrict access to an entire method by throwing an excep- tion if the current principal does not meet the specified access requirements. Use declarative RBS demands by setting the principal policy, creating a try/catch block to handle users with insufficient privileges, and declaring a PrincipalPermission attribute to declare the method’s access requirements. Q Use imperative RBS demands by setting the principal policy, creating a try/catch block to handle users with insufficient privileges, creating a PrincipalPermission object to declare the method’s access requirements, and then calling the Principal- Permission.Demand method. Use the WindowsPrincipal.IsInRole method to make decisions based on group memberships. Declarative RBS demands are perfect for situations in which your application calls a method directly, and access to the entire method must be restricted. Use imperative RBS demands when you need to protect only a portion of a method or when you are protecting a method that can be called by a Windows event. Q To create custom identity and principal classes, extend the IIdentity and IPrincipal interfaces by overriding the existing properties and adding your custom methods and properties. To create simple custom user models, use the GenericIdentity and GenericPrincipal classes instead of the IIdentity and IPrincipal interfaces. To create declarative and imperative RBS demands with custom identities and principals, set the Thread.CurrentPrincipal property to your custom principal. Q If you are establishing an SslStream connection, you should catch two different types of exceptions. If you catch an AuthenticationException, you should prompt the user for different credentials. If you catch an InvalidCredentialException, some aspect of the stream is corrupted, and you cannot retry authentication. 550 Chapter 12 User and Data Security Lesson Review You can use the following questions to test your knowledge of the information in Lesson 1, “Authenticating and Authorizing Users.” The questions are also available on the companion CD if you prefer to review them in electronic form. NOTE Answers Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book. 1. You must restrict access to a method based on a user’s group memberships in the local user database. You want to use the most secure method possible. Which technique will you use? A. WindowsPrincipal.IsInRole B. WindowsIdentity.IsInRole C. Imperative RBS demands D. Declarative RBS demands 2. You must restrict access to a method that is called by a Windows event based on a user’s group memberships in the local user database. If the user lacks sufficient access, you want to log an event and display a message to the user. You want to use the most secure method possible. Which technique will you use? A. WindowsPrincipal.IsInRole B. WindowsIdentity.IsInRole C. Imperative RBS demands D. Declarative RBS demands 3. You are writing a method for a Console application that lists options available to a user based on the user’s group memberships. Which technique should you use? A. WindowsPrincipal.IsInRole B. WindowsIdentity.IsInRole C. Imperative RBS demands D. Declarative RBS demands 4. You are creating a front-end interface to a back-end database that stores user- names and groups within the database itself. The user database is very simple, storing only usernames and group memberships. You want to be able to use Lesson 1: Authenticating and Authorizing Users 551 imperative and declarative RBS demands within your application based on the custom user database. Which of the following classes meets your requirements and would be most efficient to implement? (Choose all that apply.) A. GenericIdentity B. GenericPrincipal C. IIdentity D. IPrincipal [...]... Encoding.ASCII.GetBytes("This is my sa1t"); Rfc 289 8DeriveBytes key = new Rfc 289 8DeriveBytes(password, salt); myAlg.Key = key.GetBytes(myAlg.KeySize / 8) ; myAlg.IV = key.GetBytes(myAlg.BlockSize / 8) ; How to Encrypt and Decrypt Messages Using Symmetric Keys After both the encryptor and decryptor have the same key, they can begin exchanging encrypted messages The NET Framework makes this process easy In fact,... spontaneous network communications For example, symmetric key encryption is not initially used between a Web client and Web server because users on the Internet aren’t typically willing to wait several days while the Web site physically mails them a secret key Instead, Web sessions are initially established by using asymmetric keys Symmetric Algorithm Classes in the NET Framework Most of the NET Framework s... them to the Rfc 289 8DeriveBytes constructor After initialization, you can retrieve a key by calling the Rfc 289 8DeriveBytes GetBytes method GetBytes accepts the number of bytes to return as an integer When deriving a key, determine the length based on the number of bits required by the algorithm object’s KeySize property Note that KeySize is defined as a number of bits, whereas the Rfc 289 8DeriveBytes.GetBytes... key and use it to define the algorithm Dim salt As Byte() = System.Text.Encoding.ASCII.GetBytes("This is my sa1t") Dim key As Rfc 289 8DeriveBytes = New Rfc 289 8DeriveBytes(password, salt) myAlg.Key = key.GetBytes(myAlg.KeySize / 8) myAlg.IV = key.GetBytes(myAlg.BlockSize / 8) // C# // In practice, the user would provide the password string password = "P@S5w0r]>"; // Create an algorithm object RijndaelManaged... Symmetric Cryptography Classes Class Key Length Description RijndaelManaged 1 28 through 256 bits, in 32-bit increments The NET Framework implementation of the Rijndael symmetric encryption algorithm Because this and AesManaged are fully managed implementations, they can be used in partially trusted environments AesManaged 1 28 bits The NET Framework implementation of the Rijndael symmetric encryption algorithm... sets the size in bits of the secret key used by the symmetric algorithm Asymmetric keys are much larger than symmetric keys For example, although a typical symmetric key is 182 bits, the NET Framework implementation of the RSA algorithm supports key lengths from 384 through 16, 384 bits KeySize A KeySizes array that gets the key sizes that are supported by the symmetric algorithm Each array member contains... the permissions assigned to the C:\Guest folder If your application worked properly, the Guest account should have Read permissions, and no other account should have access MORE INFO File Permissions in Windows XP For detailed instructions on how to view and edit file permissions in Windows XP, read http://technet .microsoft. com/library/bb456 988 .aspx Windows Vista uses a similar procedure 7 Before you... operating systems; otherwise, use Triple DES Of all symmetric key algorithms supported by the NET Framework, the U.S government–approved Rijndael algorithm is considered the most secure This algorithm supports 1 28- , 192-, and 256-bit keys Another reason to choose Rijndael is that it is natively supported by the NET Framework Other than the less flexible AesManaged class, the other algorithms must make calls... such as Certificate Services included with Windows Server 2003 and Windows Server 20 08 A PKI is an infrastructure for distributing, managing, and revoking certificates in an organization As a developer, you generally are not responsible for configuring a PKI Asymmetric Algorithm Classes in the NET Framework The NET Framework provides two classes for working with asymmetric encryption, and they are both... that need to be granted to a user to allow an application to run correctly A developer uses SACLs to track resources to which her application is denied access so that she can customize the application to allow it to run without problems under a less privileged account Exam Tip It’s important to understand the difference between SACLs and DACLs for the exam The difference between the two is also a common . vary. For example, the following code sam- ple (which requires the System.Security.AccessControl, System.Security.Principal, and 55 8 Chapter 12 User and Data Security Microsoft. Win32 namespaces). Authenticating and Authorizing Users 54 9 Q The WindowsIdentity class provides .NET Framework applications access to a Windows user’s account properties. You can examine the current user’s user- name. instructions on how to view and edit file permissions in Windows XP, read http://technet .microsoft. com/library/bb 456 988 .aspx. Windows Vista uses a similar procedure. 7. Before you can delete the C:Guest
- Xem thêm -

Xem thêm: mcts self paced training kit exam 70-536 microsoft net framework 3.5 application development foundation phần 8 ppt, mcts self paced training kit exam 70-536 microsoft net framework 3.5 application development foundation phần 8 ppt, mcts self paced training kit exam 70-536 microsoft net framework 3.5 application development foundation phần 8 ppt

Mục lục

Xem thêm

Gợi ý tài liệu liên quan cho bạn