Run Your Code in Different Security Zones


When you run your Visual Basic .NET application, the .NET code-access security system gives your application a set of permissions. For example, if you create an executable and run it on your own computer, the .NET code-access security system gives your application permission to execute, read values from the registry, create files, and so forth. In fact, your application is given all the permissions available. Because your application is given by the code-access security model full, unfettered access to the resources it needs, it will run without error as you would expect—so long as the application performs actions that you as a logged-on Windows user are allowed to perform. (Remember that OS security restrictions preempt any permissions granted by the code-access security system.)

Create an application that writes to and reads from a file

If you change the location, such as by copying your application to a network share, from which your application is run and your application attempts to use a restricted resource, you’ll encounter a security-related exception. To demonstrate:

  1. In Visual Basic .NET, create a new Console Application project named FileAccess.

  2. Add the following code to Sub Main in Module1.vb:

    Sub Main()
    Dim settings As String
    FileOpen(1, "MySettings.txt", OpenMode.Output)
    PrintLine(1, _
    "If you can see this you have file access permissions!")
    FileClose(1)
    FileOpen(1, "MySettings.txt", OpenMode.Input)
    settings = LineInput(1)
    FileClose(1)
    MsgBox(settings)
    End Sub

  3. Press F5 to run the application.

    The application will run without incident. A message box should be displayed as shown here:

Run the application from a network share

Now try changing the environment from which your application is run by copying the application—FileAccess.Exe—to a network share and running it.

Note

You can also simulate running your code on a network share by creating a network connection from your own computer to your own computer. For example, if your code lives in the C:\MyCode directory on your computer, you could share out the directory containing your code as \\MyComputerNameHere\MyCode. You could then connect to \\MyComputerNameHere\MyCode from the computer itself. For example, map drive Z: to \\MyComputerNameHere\MyCode and run the application from Z:\. For more information on how to map a network drive, select Help And Support from the Windows Start menu and search for the topic “Assign a drive letter to a network computer or folder.”

If you do not have access to a network share and do not have the ability to create a network connection to your own computer, perform the following steps to simulate running your application from a network share:

  1. Launch the Microsoft Visual Studio .NET Command Prompt. See the Introduction for more information on how to launch the command prompt.

  2. At the command prompt, enter ConfigWizards.exe. The Microsoft .NET Wizards dialog box will appear.

  3. Select Adjust .NET Security, and the Security Adjustment Wizard will display.

  4. Select the Make Changes For The Current User Only option—when you are logged in as a normal user, not as an administrator, this will be the only option available. If you are able to select the Make Changes To This Computer option, this is a signal that you are logged on with administrative privileges, which exposes you to added risks as explained in Chapter 11. If this is the case, remove yourself from the administrators group and start getting in the habit of logging in as a normal user—power to the normal user!

    click to expand

  5. Click Next. A list of icons showing the available security zones will be displayed.

  6. Change the trust level for My Computer to Medium Trust—that is, move the slider one notch down from Full Trust as shown in the following illustration.

    click to expand

  7. Click Next, and a summary of the security level for each zone will be displayed.

    Notice that the Medium Trust security level you set for My Computer matches the setting for Local Intranet. You have changed the trust level for all applications that will run on your computer to simulate running in a Local Intranet environment. Running your application in this environment gives you the same experience as if you were to run your application from a network share.

  8. Click Finish to close the dialog box.

  9. Run FileAccess.Exe, which you created earlier.

    This time when you run FileAccess.Exe, you’ll encounter a SecurityException as shown in the following illustration. Now that you’ve seen what happens, if you used the Security Adjustment Wizard to set the computer’s trust level to Medium Trust, retrace the steps just shown and reset the trust level for the My Computer zone to the original setting—normally this is Full Trust.

    click to expand

What Code-Access Security Is Meant To Protect

You might find the results of this small demonstration unsettling. “What the heck is going on? Can I not write applications that work when run from a network share?” you might be asking. Now imagine that a coworker of yours runs the same application from the same network share. If your application were to inadvertently overwrite an important file named “MySettings.txt” on the network share or on that person’s computer, your coworker might very well be furious with you (the author of the application), not Visual Basic .NET, for overwriting his important file (even if he knew you were using Visual Basic .NET). By restricting what your application can do in an open environment such as a network, Visual Basic .NET might not only have saved another person’s data, but it might have saved your reputation as well.

Let’s get back to the original question, but with a slight addition: “Can I not write applications that work when run from a network share in a secure manner?” The short answer is yes, you can. This chapter will demonstrate how you can use code-access security to not only protect your application in a shared environment, but to make your application useful as well.

Permissions—The Basis of What Your Code Can Do

Permissions are the foundation upon which .NET security is built. As demonstrated earlier in the chapter, when you run an application requiring file access in a network environment, the operations your application is allowed to perform depend on the location from which it is run—namely network share, intranet, or Internet vs. your local computer. The following section explains how the .NET security system determines which operations your application is allowed to perform.

Security Zones and Trust Levels

When .NET loads your application, it computes a set of permissions your application is allowed to have based on a number of factors—factors formally known as evidence. One of these factors is the zone from which your application is run. Each zone is assigned a default trust level. Table 3-1 lists the available zones and their default trust level. The My Computer zone, which applies to all .NET applications launched from a disk drive (or other similar device) attached to your computer, is the most highly trusted zone by default. This zone is given Full Trust—meaning that any application launched from your computer has access to all resources that you, as a user of the computer, have been granted permission to use. The zone symbols are shown in Figure 3-2.

click to expand
Figure 3-2: Standard symbols representing each zone

Note

Granting an application Full Trust doesn’t necessarily mean the application has full access to your computer. If, for example, as we said earlier your application is running on an operating system such as Microsoft Windows XP or Windows 2000, and you aren’t logged in as an administrator, the application has no more access to the computer than you do. If the application attempts to create a file in a directory for which you do not have access, the operation will fail.

Table 3-1: Available Zones and Levels of Trust

Zone

Default Trust Setting

Description

My Computer

Full Trust

The application can do whatever you as a user can do on the computer.

Local Intranet

Medium Trust

Limited permissions, such as the right to read and write files from a special, isolated place on your computer’s hard disk.

Trusted Sites

Low Trust

Limited UI, printing, and execution
permissions.

Internet

Low Trust or No Trust

The permissions depend on what version of the .NET Framework you have installed. See note below.

Untrusted Sites

No Trust

No permissions. Code is not allowed to run.

Note

In regard to the Internet zone default trust-level setting, .NET Framework version 1.1 provided with Visual Basic .NET 2003 sets the default trust level to Low Trust. The default trust level for .NET Framework version 1.0 provided with Visual Basic .NET 2002 is a little more complicated. The released version 1.0 provided a default setting of Low Trust. However, later .NET Framework 1.0 service pack releases—SP1 and SP2—set the default trust level to No Trust.

Note

The .NET security zone settings should not be confused with similar looking zone-setting dialog boxes found in Microsoft Internet Explorer. Each dialog box controls a different aspect of loading and running a Visual Basic .NET application. The Internet Explorer settings determine whether or not the application is allowed to load and run. If the application is allowed to run, those settings determine which zone is assigned to the application. The .NET security-zone settings determine what the application can do—based on the zone assigned by Internet Explorer—once it’s loaded and running. If, for example, you view a Web page in Internet Explorer containing a Visual Basic .NET Windows Forms user-control, zone settings for Internet Explorer determine whether the Visual Basic .NET component is allowed to load. In addition, Internet Explorer assigns the user control to a particular zone, such as the Internet zone. If Internet Explorer allows the Visual Basic .NET component to load, the .NET zone settings take over and dictate what the control can do. Internet Explorer might allow the control to load, but the .NET security system might prevent the control from performing certain actions, such as showing dialog boxes or writing to disk.

Security Zones and Permissions

As there is a level of trust associated with each zone, so there is a set of permissions associated with each level of trust. The higher the trust level, the more permissions; the lower the trust level, the fewer permissions, and in some cases no permissions are granted at all—not even the right to execute! Table 3-2 lists the default permissions associated with each zone. Note that the more highly trusted zones such as My Computer and Local Intranet are granted more permissions by default. Low-trust or nontrusted zones—such as Internet, Trusted Sites, and Untrusted Sites—are granted little to no permissions.

Table 3-2: Permissions for Each Zone

Permission Level

My Computer

Local Intranet

Internet & Trusted Sites

Untrusted Sites

Allows the application to

DnsPermission

Perform Domain Name System (DNS) operations such as resolve a URL name to an IP address.

EventLogPermission

Read or write to the event log.

EnvironmentPermission

Read or write environment variables.

FileDialogPermission

Show the open file and save file dialog boxes.

FileIOPermission

Read, write, or append files.

IsolatedStorageFilePermission

Read or write data to a special, reserved place on your computer’s hard disk.

PrintingPermission

Connect to local or network printers.

ReflectionPermission

Query the classes, modules, properties, methods, and events that make up the application.

RegistryPermission

Read and write to the system registry.

SecurityPermission

Perform security- related operations, such as turn off per mission checks. This includes so-called unmanaged code permissions such as the ability to call Windows API func tions or to use ActiveX controls or ActiveX components.

UIPermission

Show a UI and what type of UI can be shown, such as top- level windows. Also controls application access to the system clipboard.

- zone has permission;

- zone does not have permission;

- more details to come.

Note

Table 3-2 shows the default permissions granted to each zone. As demonstrated earlier, you can use the .NET Security Adjustment Wizard to adjust the level of trust associated with each zone—adding or removing permissions depending on the level of trust. For example, if you have full administrative rights, you could grant all zones all permissions by setting each zone to Full Trust. However, it’s critically important that you do not grant all zones Full Trust. You should either leave the security settings as-is or reduce permissions where needed. You should never expand the number of permissions granted to a particular zone. You will increase your risk of being attacked by applications running in that particular zone—for example, the Internet zone. If you need to get an application you trust running in a particular zone, you can grant the application additional permissions as demonstrated in Chapter 10.

Table 3-3 is an extension of Table 3-2, which lists permissions granted exclusively to the My Computer Zone by default and not granted to any other zone.

Table 3-3: Full Trust Permissions Granted to My Computer Zone

Permission Level

Allows the Application To

DirectoryServicesPermission

Browse, read, and write Active Directory entries

MessageQueuePermission

Locate available message queues, read messages in the queue, or send or receive messages

OleDbPermission

Access an OleDb provider or set a blank password in the connection string

PerformanceCounterPermission

Locate, change, or create performance-counter categories

ServiceControllerPermission

Locate or turn on or off Windows services such as the SQL service

SocketPermission

Read from or write to specific network sockets based on hostname, port, and transport

SqlClientPermission

Use a blank password as part of the connection string

WebPermission

Accept data from or transmit data to a particular URI

start sidebar
The Luring Attack

Code-based security provides an important defense against so-called luring attacks—when other .NET components or applications downloaded from an untrusted source such as the Internet lure Visual Basic .NET into performing destructive actions. For example, Visual Basic .NET (by means of the .NET Framework) provides a rich set of capabilities—such as the ability to read system registry values; read, write, and delete files on disk; and connect to any arbitrary Web address and send data to it. With these capabilities at your disposal, you might create a Visual Basic .NET application that calls Visual Basic .NET (or the .NET Framework) functions to read documents on your computer and send them to a Web site. Imagine if an attacker—such as a devious coworker—lured you into running the application from an intranet Web site. Could the application collect information from your computer and send it back to the attacker’s Web site?

Fortunately, with .NET code-access security working for you, the answer is no. Because the application you ran is from the Local Intranet zone, the application has the permissions granted to that zone. When a call is made from the application to a .NET Framework function, such as a function to open a file on the hard disk, the .NET common language runtime checks the permissions of the calling application. As you can see from Table 3-2, by default the Local Intranet–based application would not be granted the permission to open the file. The application also is not granted the Web or socket permissions it needs to send the contents of the file back to the attacker.

Code-access security is set up to check multiple applications (or components) calling from one to the other. For example, suppose you created a component that was called by the application you ran from your coworker’s intranet site; the component in turn calls into Visual Basic .NET (and in turn into the .NET Framework) to open a file on disk. The attempt would still fail because Visual Basic .NET would walk back through all calling methods (a so-called stack walk), checking the permissions of each method. Because your component is installed on your local computer, it will be associated with the My Computer security zone and will have the permission to open the file. However, the application that called into your component will not have that permission, because the application is in a different zone. Visual Basic .NET, upon seeing that not all callers along the call chain (or call stack) have sufficient permissions to open the file, will refuse to open the file and will instead throw a security exception.

end sidebar

Local Intranet, Internet, and Trusted Sites Zones

Table 3-4 provides more information on exactly what level of permissions are granted to the Local Intranet and Trusted Sites zones.

Table 3-4: Permissions for Local Intranet and Trusted Sites Zones

Permission

Local Intranet Permissions

Internet and Trusted Sites Permissions

DnsPermission

Allows the Visual Basic .NET application to obtain host names—such as www.mycompany.com—for a given IP address or obtain an IP address for a given host name.

No DNS permissions are granted.

EnvironmentPermission

Visual Basic .NET code is allowed to read the USERNAME environment variable. Any attempt to read or write to any other environment variable will result in a security exception.

No environment variable permissions are granted.

EventLogPermission

Allows the Visual Basic .NET application to read and write to and from the event log. The application is not allowed to delete entries.

No event log permissions are granted.

FileDialogPermission

Visual Basic .NET code is allowed to show all available file dialog boxes, including the open file and save file dialog boxes.

Visual Basic .NET code is allowed to show the file open dialog box, but not the file save dialog box.

IsolatedFileStorage

Visual Basic .NET applications are allowed to read and write files to and from a special area of the disk. A separate storage area is assigned to each user for each component that makes up the application. Disk space allocated to the application is not limited.

This has the same restrictions as LocalIntranet permission, but storage is restricted to 10,240 bytes (10 kilobytes or 10K) per user per application where all components (.DLLs) that make up the application share the same isolated storage 10K limited space.

PrintingPermission

Allows the Visual Basic .NET application to print to the default printer but not to any other printers connected to your computer. Also allows printing through a restricted print dialog box.

Allows Visual Basic .NET to support printing through a print dialog box, which is more restrictive than the dialog box available to the Local Intranet zone.

ReflectionPermission

Allows the application to generate .NET applications on the fly and to read public types from a .NET application.

No reflection permissions are granted.

SecurityPermission

Allows Visual Basic .NET code to execute and temporarily grant callers additional permissions that the calling application is not granted, but the Visual Basic .NET application itself is granted. Note that the ability to call unmanaged code such as call API functions or use ActiveX components is not allowed.

Allows Visual Basic .NET code to execute. API function calls. Use of ActiveX components is not allowed.

UIPermission

All UIPermissions, such as the ability to show any type of top-level window and full access to the clipboard, are granted.

Visual Basic .NET code is restricted to showing only safe top-level windows. Safe top- level windows are windows that meet certain restrictions so that they cannot imitate system dialog boxes such as user logon dialog boxes. This permission also includes access to the clipboard (Copy/Paste).

Note

As mentioned earlier, the Internet permissions listed here reflect the permissions set by the initial 1.0 .NET Framework release with Visual Basic .NET 2002, and the 1.1 .NET Framework release with Visual Basic .NET 2003. .NET Framework 1.0 service pack releases SP1 and SP2 grant no permissions to the Internet zone. You should treat all Visual Basic .NET 2002 applications targeted for the Internet zone and .NET Framework 1.0 release as having no permissions because you should assume that the latest service pack is installed on the target computer—you are installing the latest service packs containing the most recent security fixes on your computer, right? Treat all Visual Basic .NET 2003 applications targeted for the Internet zone and .NET Framework 1.1 release as having all of the permissions listed above.

How Visual Basic .NET Determines Zone

If your application is launched from a disk drive connected to your local computer, your application is identified by Visual Basic .NET as running in the My Computer zone. For all other zones—such as Local Intranet, Trusted Sites, Untrusted Sites, and Internet—permissions for your application are determined by the Microsoft Internet Explorer zone settings. By default, the Local Intranet zone includes the following:

  • Local intranet sites not listed in other zones such as the restricted sites zone

  • All sites that bypass the proxy server

  • All network paths

The Trusted Sites zone includes all Web sites including intranet sites that you list in the Microsoft Internet Explorer zone settings dialog box under Trusted Sites. By default, there are no Web sites listed; therefore, by default most users don’t access any Trusted Sites zones.

The Untrusted Sites zone includes all Web sites that you list in the Microsoft Internet Explorer zone settings dialog box under Untrusted Sites. These are sites that you absolutely do not want either Internet Explorer or .NET to trust. For example, Internet Explorer will not allow any embedded script embedded in a Web page that comes from a site listed in the Untrusted Sites zone to execute, nor will .NET grant any .NET application run from such a site any permissions. By default, there are no Web sites listed. If you add the URL for an intranet Web site under Untrusted Sites zone—effectively removing the site from the Local Intranet zone—all applications run from that intranet site will be given permissions based on the Untrustred Sites zone (no permissions).

The Internet zone includes all locations not covered by the other zones. By default, it covers all non-intranet Web sites.

If your application is launched from a network share, the application is assigned to the Local Intranet zone. Another way your application or component can be assigned to the Local Intranet zone is if you view an intranet Web page that includes a .NET Windows Forms user control, for example. The Windows Forms user control will be downloaded as part of the Web page and installed in a special download cache—a special directory on your hard disk containing .NET components downloaded from the Internet or intranet.

Note

You can include Windows Forms user controls on a Web page by using the Object tag in HTML to refer to the user control. This is similar to how you include ActiveX controls on a Web page. A benefit of using Windows Forms user controls is that the .NET code-access security system protects a Windows Form user control contained on a Web page from performing unsafe operations. Embedding Windows Forms user controls on a Web page works best for intranet sites where all client computers are running Windows and .NET. We recommend that you do not embed Windows Forms user controls on a Web page intended for viewing on the Internet. See MSDN article http://msdn.microsoft.com/msdnmag/issues/02/01/UserCtrl/default.aspx for more information on how to embed a Windows Forms user control on a Web page.

Visual Basic .NET components that you create, such as class libraries and Windows Forms user controls, are also assigned a specific zone. In the case of a component, the zone is determined by where the component is instantiated from. If the component is directly instantiated from either the intranet or Internet as we mentioned earlier, the component is assigned the respective zone. If the component is already installed on the local computer—as is the case with system components such as the Windows Forms Button control, which is installed on the computer by the .NET Framework—the component is assigned to the My Computer zone. Table 3-5 summarizes the security zone assignment protocol for .NET applications.

Table 3-5: Security Zone Assignments for .NET Applications

Type of Application

How Installed and Run

Zone Assigned

Windows Forms EXE

Set up and run on computer, including set up by means of an installer application from an intranet or Internet page

My Computer

Windows Forms EXE

Run directly from a link pointing to the .EXE on an HTML page

Local Intranet or Internet, depending on whether the Web page containing the link is an intranet or Internet page, respectively

Windows Forms .DLL class library or user control

Set up and run on the computer, including set up by means of an installer application from an intranet or Internet page

My Computer

Windows Forms .DLL class library or user control

Run directly from link pointing to .DLL on HTML page

Local Intranet or Internet, depending on whether the Web page containing the link is an intranet or Internet page, respectively

ASP.NET Web Form or Web Service .DLL

Set up and run on a Windows Internet Information Server (IIS) computer

My Computer

Note

The zone assigned to an ASP.NET application or Web service is somewhat confusing. You naturally think of an ASP.NET application as being related to the Internet because it’s used to represent an Internet application. You would naturally conclude, therefore, that ASP.NET applications run in the Internet zone, but they do not. They run in the My Computer zone. Why? The Internet Explorer, client-side experience you have with an ASP.NET application is merely a reflection of processing that takes place by the ASP.NET application running on a server computer. The ASP.NET application is installed and run on a server computer much like you install and run a Windows Forms client application on a client computer. In either case, because the application is run directly from the hard disk on a computer and not launched across a network or Internet connection, the application is run in the My Computer zone.

Recall the example of trying to open a file when running in an environment that simulated the Local Intranet zone. In the example, a security exception is thrown. As you can see from Table 3-2, the exception is expected because the Local Intranet zone does not support the FileIOPermission. Attempting to perform any action that is not supported by the zone from which your application is running will lead to a security exception. The next section presents options that will allow you to work with the .NET security system to not only perform the actions your application needs to get done, but to perform those actions in a secure manner.

Ensuring That Your Code Will Run Safely

If your application needs to perform a critical operation, such as writing to a file that is not allowed in the zone from which you intend to run the application, you have the following choices:

  • Find an alternative way of performing the operation that works in the given zone.

  • Deploy your application to run in a different zone with more trust.

  • Modify the security policy to grant your application the needed permission.

The preferred solution—the first choice listed above—is to cooperate with the .NET security system permitting your application to run as expected. The default permissions granted to each zone are granted for a very good reason. The restrictions are in place to prevent applications from intentionally or unintentionally doing harm. Try to work with the security zone you are targeting, not against it.

If your application requires more permissions than a given zone provides, you can consider changing how your application is distributed. For example, if you package the application into an installation package such as a Microsoft Installer package (.MSI file), have a user install the application on his computer, and run the application in the My Computer zone, the application will be granted Full Trust. However, you’ll need to provide an installation process that reassures the user about the trustworthiness of your application and installation. One mechanism that can help the user trust your application is to attach a digital signature as described in Chapter 10, which describes deployment and digital signatures in more detail.

Note

When using the Internet or intranet, it’s sometimes difficult to tell when an application or component is installed on your machine and what permissions—based on the designated zone—the .NET code-access security system will assign the application or component. The main difference is if you click on a link that executes a setup program, the application or component will be installed on your computer in a traditional fashion; you might be prompted for setup related information, and you’ll likely see a progress bar at some point to show installation progress. In this case, any time the application runs, it is assigned to the My Computer zone. If, on the other hand, you click a link that directly runs an application executable (as opposed to running Setup.exe for the application) or brings up a Web page containing embedded components such as Windows Forms user controls, the application or components are first downloaded to a special .NET download cache and executed from the cache. In this case, the components are assigned to the Internet or intranet zone depending on what type of Web site you are viewing.

If neither of the first two choices is satisfactory, you can add to or change the rules—commonly referred to as the security policy—used by the .NET security system to grant your application needed permissions. Users of your application will need to apply your security policy updates to their computers before running your application. The security policy updates can be packaged in a deployment package, delivered to the users, and applied to their computers in a variety of ways. Chapter 10 demonstrates how to modify security policy to grant your application the permissions it needs, and it shows how to package and automatically deploy security policy updates companywide.

Cooperating with the Security System

Following the old adage “if you can’t beat ‘em, join ‘em,” you should design your application to work with the security system, not against it. For example, perhaps your application, which runs from a network share, needs to store application settings. Traditionally, you might have stored settings in the registry, but an application running from a network share won’t have permissions to read and write registry keys. Therefore, you must design your application to use a different mechanism to store settings, such as writing the settings to a file on disk or to a database. Worse yet, you might find, as is the case with the Local Intranet zone, that your application doesn’t have permissions to access the registry, a file, or a database. This is where isolated storage saves the day.

Modify your code to use isolated storage

Isolated storage is a special, reserved area of the hard disk managed by .NET from which your application can read and write information. In some cases, you might find that using isolated storage is a reasonable alternative to reading or writing information to disk or the registry. Although the Local Intranet zone does not support file or registry access, it does support reading and writing data to isolated storage. (See Table 3-4 in the previous section.) In the case of applications running in the Local Intranet zone, separate storage is allocated and maintained for each user who logs on to the computer. This prevents your application—and more importantly, prevents users of your application—from being able to read sensitive information stored by other users (or the operating system), and it prevents your application from being able to overwrite important files owned by other users (or the operating system).

The following steps demonstrate how you can update the FileAccess application presented earlier in the chapter to use isolated storage:

  1. Run Visual Basic .NET, and open the FileAccess application you saved earlier.

    Note

    For a complete code listing, refer to the finished FileAccess.sln application located in the CH03_CodeAccess\FileAccess\Finish directory where you installed the book practice files.

  2. Delete the following code, created in previous steps, from Sub Main:

     Dim settings As String
    FileOpen(1, "MySettings.txt", OpenMode.Output)
    PrintLine(1, _
    "If you can see this you have file access permissions!")
    FileClose(1)
    FileOpen(1, "MySettings.txt", OpenMode.Input)
    settings = LineInput(1)
    FileClose(1)
    MsgBox(settings)

  3. Leave an empty Sub Main method body as follows:

    Sub Main()

    End Sub
  4. Insert the following code in Sub Main:

    Sub Main()
    Dim settings As String
    Dim secfile As SecureFile
    secfile = New SecureFile()
    secfile.Open("MySettings.txt", OpenMode.Output)
    secfile.PrintLine( _
    "If you can see this you have file access permissions!")
    secfile.Close()
    secfile.Open("MySettings.txt", OpenMode.Input)
    settings = secfile.LineInput()
    secfile.Close()
    MsgBox(settings)
    End Sub

  5. Add the following Imports statements to the top of Module1.vb:

    Imports System.Text
    Imports System.IO.IsolatedStorage
  6. Add the following code after the End Sub for Sub Main to define the SecureFile class, which allows you to read and write text to isolated storage:

    Public Class SecureFile
    Private m_storage As IsolatedStorageFileStream = Nothing
    Private m_buffer As String = ""
    Private m_EOF As Boolean = False
    Public Sub Open(ByVal Filename As String, ByVal mode As OpenMode)
    Select Case mode
    Case OpenMode.Append
    m_storage = New IsolatedSto"rageFileStream(Filename, _
    IO.FileMode.Append, IO.FileAccess.Write)
    Case OpenMode.Binary
    Throw New Exception("Binary mode not supported")
    Case OpenMode.Input
    m_storage = New IsolatedStorageFileStream(Filename, _
    IO.FileMode.Open, IO.FileAccess.Read)
    Case OpenMode.Output
    m_storage = New IsolatedStorageFileStream(Filename, _
    IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
    m_storage.SetLength(0)
    Case OpenMode.Random
    Throw New Exception("Random mode not supported")
    End Select
    m_buffer = ""
    m_EOF = False
    End Sub
    Public Sub Close()
    m_storage.Close()
    m_storage = Nothing
    End Sub
    Public Sub PrintLine(ByVal text As String)
    Dim utf8Array() As Byte
    text = text & vbCrLf
    utf8Array = Encoding.UTF8.GetBytes(text)
    m_storage.Write(utf8Array, 0, utf8Array.Length)
    End Sub
    Public Function LineInput() As String
    Dim utf8Array() As Byte
    Dim line As String = ""
    Dim iCrLf As Integer
    If m_EOF OrElse m_storage.Length = 0 Then Return ""
    If m_buffer = ""Then
    ReDim utf8Array(m_storage.Length - 1)
    m_storage.Read(utf8Array, 0, utf8Array.Length)
    m_buffer = Encoding.UTF8.GetString(utf8Array)
    End If
    iCrLf = InStr(m_buffer, vbCrLf)
    If iCrLf > 0 Then
    line = Left(m_buffer, iCrLf - 1)
    ‘ Remove the line from the buffer
    m_buffer = Mid(m_buffer, iCrLf + Len(vbCrLf))
    If m_buffer = ""Then m_EOF = True
    Else
    ‘ Return rest of the buffer
    line = m_buffer
    m_buffer = ""
    m_EOF = True
    End If
    Return line
    End Function
    End Class

    This code creates a SecureFile class, which implements functions equivalent to standard Visual Basic .NET file functions such as FileOpen, PrintLine, LineInput, and FileClose. However, instead of writing to a standard file, these functions write to isolated storage.

  7. Launch the Visual Studio .NET Command Prompt as demonstrated earlier in this chapter.

  8. Set the trust level of the My Computer zone to Medium Trust:

    1. At the command prompt, enter ConfigWizards.exe. The Microsoft .NET Wizards dialog box will appear.

    2. Select Adjust .NET Security, and the Security Adjustment Wizard will display.

    3. Select the Make Changes For The Current User Only option. In some cases, this might be the only option available.

    4. Click Next. A list of icons showing the available security zones will be displayed.

    5. Change the trust level for My Computer to Medium Trust—that is, move the slider one notch down.

    6. Click Next, and click Finish.

  9. Press F5 to run the application.

It works! And it’s secure in the sense that each person who runs the application on the network share will be assigned her own private storage of the file allocated on her local computer. There is no danger of a user overwriting the file created by another user.

Note

Be sure to set the trust level back to Full Trust for the My Computer zone. For the ultimate test, copy your application to a network share and run it from there. Although the application is run from a network share, the application data written to isolated storage is contained in a special file on your local computer created by .NET and nested several directories deep under the Documents And Settings directory for your Windows logged-on user account. You can use the Isolated Storage Administration tool—storeadm.exe—to view and manage isolated storage information stored on your computer. For more information, search Visual Basic .NET on-line help for “Isolated Storage tool.”




Security for Microsoft Visual Basic  .NET
Security for Microsoft Visual Basic .NET
ISBN: 735619190
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net