Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional ASP.NET Security - Jeff Ferguson

.pdf
Скачиваний:
28
Добавлен:
24.05.2014
Размер:
13.26 Mб
Скачать

Impersonation

[assembly:SecurityPermissionAttribute(SecurityAction.ReguestMinimum, UnrnanagedCode=true) ]

We can add it to the code file for a class just under the using statements. This will specify that our assembly requires permission to run unmanaged code in order to function. (See Chapter 13 for more about code access security and permissions)

Within our class, before the method where we want to do the logon, we include an attribute and declaration that will import a function from the Windows security API:

[Dlllmport("C:\\Windows\\System32\\advapi32.dll")]

public static extern bool LogonUser(String IpszUsername, String IpszDomain, String IpszPassword, int dwLogonType, int dwLogonProvider, out int phToken);

As you can see, the LogonUser function comes from advapi32 .dll and takes username, domain, password, logon type and logon provider input parameters along with an output parameter that allows us to access the token following a successful logon. The token will be placed in the variable that we specify as the last parameter when we call LogonUser. A Boolean result is returned to indicate whether the logon was successful.

Once we have imported this function, we can use it in our code like this:

int returnedToken; if(LogonUser(user,machine,password,3,0,out returnedToken))

IntPtr token = new IntPtr(returnedToken);

We have to convert the integer value returned by LogonUser into an IntPtr in order that we can use it with Windowsldentity. Impersonate

Doing the Impersonation

Once we have an account token, we can use Windows Identity. Impersonate to perform the impersonation. The following method will perform an impersonation given a username, machine name, and password.

public static WindowsImpersonationContext Impersonate(string user,

string

machine,

string password) {

 

int

token;

 

if(!LogonUser(user.machine,password,3,0,out token)) return null;

IntPtr tokenPtr = new IntPtr(token);

WindowsImpersonationContext context = Windowsldentity.Impersonate(tokenPtr);

return context;

377

If the logon fails, we return null:

if ( ILogonUser (user, machine, password, 3 , 0 , out token) ) return null;

Otherwise, we return the Windowslmpersonationcontext object that is returned by

Windowsldentity . Impersonate:

Windowslmpersonationcontext context = Windowsldentity. Impersonate (tokenPtr) ; return

context;

The Windowslmpersonationcontext object is important because it provides us with the ability to revert back to our original identity by using its Undo method. Here is some code that uses the Impersonate method we just created:

private void

Page_Load( object

sender,

System.

EventArgs

e) {

 

 

 

//output

the

identity before impersonation

Response. Write ( "Before Impersonation:

" +

 

Windowsldentity .GetCurrent () .Name) ;

//do the

impersonation

 

 

Windowslmpersonationcontext

context =

Impersonate ( "aUser" ,

 

"syzygy", "test" ) ;

 

 

//check that

impersonation has worked

 

if (context

1= null)

 

 

{

Response. Write (@"<BR>" ) ;

//output the identity during impersonation Response. Write ( "During Impersonation: " +

Windowsldentity. GetCurrent () .Name) ;

//revert context . Undo ( ) ;

Response. Write (@"<BR>" ) ;

//output the identity after reverting Response. Write ( "After Impersonation: " +

Windowsldentity. GetCurrent () .Name) ;

First we output the current identity by using the static method Windowsldentity .GetCurrent:

Response. Write ( "Before Impersonation: " +

Windowsldentity. GetCurrent () .Name) ;

378

impersonation

We then do the impersonation:

WindowsImpersonationContext context = Impersonate("aUser", "syzygy", "test");

If the impersonation was successful and an impersonation context was returned, we output the current identity again:

if(context != null) { Response.Write(@"<BR>"); Response.Write("During Impersonation: " +

WindowsIdentity.GetCurrent().Name);

We then revert to the original user again by using WindowsImpersonationContext .Undo and output the current identity for a final time:

context.Undo();

Response.Write(@"<BR>");

Response.Write("After Impersonation: " +

WindowsIdentity.GetCurrent().Name);

This code will produce output like this:

>| default - Microsoft Internet Explorer provided by Freeserve

File

Edit

View

Favorites

Tools

Help

Address J jg http://LOCALHOST/security/twidows/temporaryimpersonatio

Before Impersonation: SYZYGYlASPNET

During Impersonation: SYZYGY\aUser

After Impersonation: SYZYGYXASPNET

*j Local intranet

This shows that we have successfully run some code under the identity of aUser.

Problems with Accessing Network Resources

In order to access networked resources such as shared folders, a user must have a 'network interactive' logon type. This is represented in the call to LogonUser with the value 2 (rather than the value 3 we have been using up until now). Unfortunately, using this value seems to cause a problem with Windowsldentity. Impersonate. The solution to this problem is to do the impersonation ourself, with another platform invoke of the Windows API.

The function we want to use is called ImpersonateLoggedOnUser and is found in advapi32 . dll along with LogonUser. We can import it with the following code:

379

tDlllmport("C:\\Windows\\System32\\advapi32.dll")]public staticextern bool ImpersonateLoggedOnUser ( int hToken) ;

Here is an alternative to the Impersonate method we created earlier:

public static bool Networklmpersonate (string user, string machine, string password)

{

int token;

iff! LogonUser (user .machine, password, 3,0, out token) ) return false;

return ImpersonateLoggedOnUser (token) ;

Remember that the Dlllmport and declaration for ImpersonateLoggedOnUser must be included before this method.

If the call to LogonUser fails, we return false; otherwise we return the value returned by calling ImpersonateLoggedOnUser and passing it the token that LogonUser returns.

We cannot use Undo to revert back to the original identity in this case, as we do not have a WindowsImpersonationContext object. We have to use another Windows API call, this time to the RevertToSelf function. This is imported as follows:

[Dlllmport("C:\\Windows\\System32\\advapi32.dll")]public static extern bool RevertToSelf ();

Here is some code that demonstrates our new method and how we revert:

private void Page_Load( object sender, System. EventArgs e) { Response. Write (Windowsldentity . GetCurrent () .Name) ;

Response. Write (@"<BR>" ) ;

if (Networklmpersonate ( "aUser" , "syzygy", "test")) { Response. Write (Windowsldentity .GetCurrent () .Name) ; RevertToSelf(),-Response. Write (@"<BR>" ) ; Response. Write

(Windowsldentity .GetCurrent () .Name) ;

This is very similar to the code we used earlier to demonstrate Impersonate.

380

Summary

In this chapter, we have looked at how we can use impersonation to change the security context that our ASP.NET code runs under. We have seen that we can:

D Configure ASP.NET to impersonate the account that IIS passes to it Q Configure ASP.NET to impersonate a specific account

Q Obtain account tokens by calling the LogonUser function in the Win32 API Q Programmatically impersonate another account within our own code

G Use the Win32 API to do impersonation directly for network access, when the Windowsldentity. Impersonate method will not work.

381

Configuring IIS for Security

Internet Information Server (or IIS) has received lot of attention recently because of security vulnerabilities (and the high profile of worms such as Code Red and Nimda). Magazines, pundits, and competitors of Microsoft have expended much energy in scrutinizing and criticizing its security features. Research firm Gartner has gone even further, suggesting that companies that have been hit by both Code Red and Nimda abandon the use of IIS altogether (see the article Nimda Worm Shows You Can't Always Patch Fast Enough: http://www3.gartner.com/DisplayDocument?doc_cd=101034).

Security vulnerabilities and viruses are not just of concern for users of IIS. In fact, the first recorded Internet worm was released in 1987 for Unix systems, and exploited a buffer overflow problem. According to the 2001 annual report of the CERT Coordination Center, among the most serious security vulnerabilities were multiple vulnerabilities in BIND (Berkeley Internet Name Domain) - the full CERT 2001 annual report may be found at http://www.cert.org/advisories/CA-2001-02.html. This affects most operating systems including OpenLinux 2.3, RedHat Linux, Tru64 UNIX, AIX 5L, HP-UX Hi, SGI, Sun Solaris, FreeBSD, NetBSD, and OpenBSD. However, IIS was not affected, since Microsoft's implementation of DNS is not based on BIND. The second most serious vulnerability, according to the CERT Coordination Center, was the sadmind/IIS Worm. This affects both IIS and Sun Solaris systems.

Security vulnerabilities are also a concern for Open Source products. There have been a number of cases of hackers managing to compromise the security of even high profile open source systems, including a public server of the Apache Software Foundation (http://www.apache.org/info/20010519-hack.html).

IIS gets a great deal of attention because it is one of the most widely used web servers after the Apache web server (based on the Netcraft's survey at http://www.netcraft.com/survey/), and, of course, Microsoft products in general come in for a lot of scrutiny.

Most of the IIS security vulnerabilities can be fixed by applying appropriate service packs and patches. In this chapter, we'll investigate how to minimize the risk of IIS being vulnerable to attack, and how to use the ASP.NET configuration options to maximize security.

Security and the Server Infrastructure

There is no such thing as a 100% secure system or application. Security is a journey, rather than a destination, demanding an ongoing effort.

Consider typical Windows web application architecture: there are many components in the architecture, including a router, firewall, load balancing and clustering technologies, the operating system, and IIS.

Internet

T1,T3, DSL,etcv ;

[^ Router ;

Load Balancing/

Clustering

IIS/FTP/SMTP

 

*

IIS/FTP/SMTP

 

 

 

Windows Server

]

Windows

Server 1

Server

! Server n

 

 

 

Each of these components plays its part in securing the server infrastructure. For example, the firewall filters network traffic such as ports, packets, and protocols before it reaches the web server. Let's assume our web site is going to use HTTP and HTTPS, and that we've blocked all the ports other than 80 and 443. Although we might have closed all the ports other than 80 and 443 in our firewall, and so increased security massively, our site isn't necessarily secure (a welcome addition to Windows has been the addition of the Internet Connection Firewall Feature with Windows XP).

It is very important to configure each of these components to maximize their security.

Security Planning

Like application development, security has many phases, such as planning, implementation, testing, and monitoring:

384

Configuring IIS for Security

Q The planning phase for security should start no later than the application design time, and this should consider all the aspects of application security, as discussed in the next section.

Q The implementation phase of security deals with implementing security - including developing the application and/or configuring security settings in the server or application environment - such as creating user accounts and roles, removing or disabling unwanted accounts, and so on.

G The testing phase of security deals with testing the application after security has been configured, and making sure that the application functions properly and has enough privileges to connect to external resources such as a database or another server hosting middle-tier components.

G The monitoring phase may be thought of as a rolling out and supporting phase, dealing with supporting the security that has been implemented, and monitoring security for any possible attacks or break-ins.

Securing IIS

IIS security starts at the planning level, even before installing the operating system and IIS. Prior to installing and configuring the operating system and IIS, we should ask ourselves how the server will be used. For instance, we should ask the following types of questions:

G What kind of presence will the server have: Internet web applications, or intranet web applications?

G How will IIS be used: with single web applications per server, or as shared web application host? G What kind of authentication will be supported: either anonymous user or authenticated users? Q Will SSL (or Secure Socket Layers) be supported?

G Will the IIS server act as an FTP and NNTP host? Q Will the IIS server support SMTP services?

Q Will users be allowed to create, modify, and delete files on the web server? Q Will the server interact with other servers?

Q What services need to be installed? For example, do FTP services need to be installed on the server?

G What ports need to be opened? For example, if FTP services are going to be implemented, then we have to open port 21.

G How will the IIS directories and files be configured?

Q What user accounts and profiles will be created and disabled?

G Do the WebDev and Microsoft FrontPage extensions need to be installed on the IIS server?

Once we have provided answers to these questions, we can begin to define how we may want to configure the server. For example, if we know that we are not going to use NNTP, FTP, and SMTP services on the server, then we can remove or stop these services, which will reduce the possibility of an attack.

385

Securing IIS is a matter of following a few basic steps, disabling the features that you are not going to use. These include:

Q Assigning appropriate Access Control Lists (ACLs) for web sites and virtual directories Q Disabling or removing all sample applications

a Removing the IIS Admin virtual directory and unused script mappings Q Setting appropriate ACLs for the IIS Log file, and enabling logging

In this section, we'll investigate these steps in detail.

Configuring Access Control Lists

Setting the Access Control List is the first step involved in securing IIS. We can set both Windows ACLs and US-based ACLs for different types of files. These allow us to grant particular users certain types of permissions to certain types of files.

ACLs may be managed in a number of different ways, but one of the most straightforward ways of managing access to particular directories for specific users is by simply accessing the Properties dialog box for a particular directory, selecting the Sharing tab, and selecting Permissions.

I wwwroot Pioperties

General | Web Sharing Sharing |

IP YOM can ihare this folder among other users on your network To enable sharing for tNs fdder, click Share this folder

f* Do not share tNs folder

<•" Share tNs folder ...

Share name:

Used for file share access to web ptoie

Comment

Userimfc

Users

 

To set permissions for how users access this

Permissions:

folder over the network, click Permissions.

------*...... .»..,..

To configure settings for Offline access to this

Caching

shared folder, click Caching.

 

1I Permissions foi wwwroot$

Share Permis-:iom

New Shafe

OK

Cancel

OK

Cancel

Apply

We should try to allow users to access only those resources that they need to, and no more. The following table provides some recommendations for permission settings for specific file types.

386

Configuring IIS for Security

File Type

Script files such as . asp, . aspx, . asmx, .ascx, etc.

Include files (. inc, . shtm, and . shtml)

Static files (.htm, .html, .gif, . jpg, .jpeg, . txt, .doc, .pdf, etc.)

Executable CGI kind of files (. cgi, . dll, .cmd and .pi)

Access Control Lists

Internet Guest Account (Execute) Everyone (Execute) System (Full Control) Administrators (Full Control) Internet Guest Account (Read only) Everyone (Read only) System (Full Control) Administrators (Full Control) Internet Guest Account (Read only) Everyone (Read only) System (Full Control) Administrators (Full Control) Internet Guest Account (Execute) Everyone (Execute) System (Full Control) Administrators (Full Control)

As an aside, in classic ASP, many people wouldn't place any code in include files, since users can request them directly, and gain access to our code.

By default, the FTP (C: \inetpub\ftproot) and SMTP (c: \inetpub\mailroot) folders grant Full Control to Everyone. This needs to be changed, depending on the application's requirements. For example, if we're going to provide Write permissions for the Everyone and Internet Guest Account accounts, it is advisable to move these folders to a volume other than then the IIS volume, and enforce Windows disk quota to limit the amount of data that can be written to these directories. In this way, if someone gains access to these folders, they can't upload vast quantities of information (thus using up all the disk space available on the server, and forcing the server to become unstable, or bringing it down altogether).

We should disable the Directory Browsing option. This will prevent attackers from navigating to the directories in which they might access potentially dangerous tools. If you are not going to use CGI applications, then select the Scripts only option to provide execute permissions.

387

Соседние файлы в предмете Программирование