810 likes | 1.03k Views
Web Application Security & Session Control. Yingcai Xiao. Introduction to Web Security Categories Issues Components. Building a Secure Web Site. Three Categories of Web Security : Content freely available to everyone (public).
E N D
Web ApplicationSecurity & Session Control Yingcai Xiao
Building a Secure Web Site • Three Categories of Web Security: • Content freely available to everyone (public). • Serve the general population but require a login (application-level security, protected). • Intranet sites for a controlled population of users — a company’s employees (private). • Security Issues: • Application-level security (users). • Deployment security (programmers). • Web Security Components: • Authentication identifies the originator of requests (who). • Authorization defines who can access which pages (what).
Authorization • Common forms of authorization: ACL & URL • ACL (access control list) authorization, also known as file authorization, based on file system permissions. • E.g.: your pausch publishing directory • Usually set up by the system administrator
Authorization • Common forms of authorization: • URL authorization: determines which page a user can visit and which part of the data a user can see. • Base on application business logic. E.g: a professor can see students grades but not their financial information. • Most often used with forms authentication. E.g.: http://pausch.cs.uakron.edu/~xiao/php/usr-pwd.php http://pausch.cs.uakron.edu/~xiao/php/usr-pwd.html
Three Typical Security Scenarios for Web Applications • Pages can be freely browsed by any: no application-level security. http://pausch.cs.uakron.edu/~xiao/php/db-starter.html • Intranet application: use Windows authentication and ACL authorization. MySQL Workbench on winremote1.cs.uakron.edu • Internet application with secure page access: use forms authentication and URL authorization. http://pausch.cs.uakron.edu/~xiao/php/usr-pwd.html
Session Control • The Internet does not remember anything! It only transmits application data. • The World Wide Web does! • A web application as part of the World Wide Web needs to remember things.
Session Control • There are three places for a web application to remember things (that is to save data): • Server-side • Client-side • A database
Session Control • The only way a web application can write onto the hard drive of a client computer is through cookies. • But a user can disable cookies. Therefore web applications need to provide alternatives. • One alternative is to stored the data in a database.
Session Control • A session needs to be created after a user’s credential has been validated. • A session keeps the user logged in and allows the user go to other authorized pages without login again. • A session has a global memory for the application to store data that are shared among different pages of the same application. • One session per user per login.
Implementation of Security & Session Control in PHP http://pausch.cs.uakron.edu/~xiao/php/usr-pwd.html http://pausch.cs.uakron.edu/~xiao/php/usr-pwd.php
Validation & Encryption
Validation • Authentication cookies are created after users’ credentials being verified. • Validation works by appending a validation key to a cookie, the resulting value is hashed, and the hash is appended to the cookie. • When the cookie is returned in a request, it must be verified that it wasn’t tampered, usually done by rehashing the cookie and comparing the new hash to the one accompanying the cookie.
Validation • Validation consumes less CPU time than encryption and prevents tampering. It does not prevent someone from intercepting an authentication cookie and reading its contents. • A web application can validate but not encrypt authentication cookies.
Encryption • Encryption works by encrypting the cookie—hash value and all—with a decryption key. • Encryption provides insurance against tampering and prevents the cookie’s contents being read. • A web application can chose to encrypt but not validate cookies.
Encryption • Encrypted cookies can’t be read or altered, but can be stolen and used illicitly. Time-outs are the only protection. • The most reliable way to prevent someone from spoofing your site with a stolen authentication cookie is to use an encrypted communications link (HTTPS). • This assumes the server supports HTTPS and the web application has been set to be protected by HTTPS.
IIS Security • IIS (Internet Information Services) Server • a Web server • runs in process Inetinfo.exe as SYSTEM • accepts connections • responds to HTTP requests • Web applications are deployed in application directories. Remote clients can’t arbitrarily grab files outside application directories. • IIS assigns every request an access token representing a Windows security principal. The access token enables the operating system to perform ACL checks on resources targeted. • IIS supports IP address and domain name restrictions. • IIS supports encrypted HTTP connections using the Secure Sockets Layer (SSL) family of protocols.
IIS Security • Anonymous access (access by unauthenticated users) • Request from anonymous users are tagged with IUSR_machinename’s access token. IUSR_machinename is an Internet guest account created when IIS is installed, where machinename is usually the Web server’s machine name.
IIS 6.0 • IIS 6.0 has a driver named http.sys to listen all HTTP requests. • When an ASP.NET related request comes in, http.sys will stat w3wp.exe as an IIS 6.0 worker process. • W3wp now loads aspnet_isapi.dll as CLR host. • The rest is the same as before.
ASP.NET Security • Server Side Processing: (1) Client accesses .ASPX files => (2)Inetinfo.exe (IIS) generates an access token =>Aspnet_isapi.dll sents the request and the token through named pipe or local procedure calls (LPCs) => (3) Aspnet_wp.exe (ASP.NET) makes ACL checks on the requested resource and passes access token to the targeted application => (4) Targeted application uses a HTTP pipeline => HTTP modules => HTTP handlers (mapped in Machine.config).
Two types of access tokens: • Authenticated user: authenticated security principal • Unauthenticated user: IUSR_machinename for anonymous login • Start->Settings->Control Panel->Administrative Tools->Computer Management->Local Users and Groups->Users • Start->Settings->Control Panel->Administrative Tools->Computer Management->Event Viewer->Security
The ASPNET Account • Created when ASP.NET is installed. • A member of the “Users” group (hidden now). • Aspnet_wp.exe runs as ASPNET by default. • Requests executed by ASP.NET use Aspnet_wp.exe’s identity. • ASP.NET can impersonate to use the request’s access token. • To make Aspnet_wp.exe to run as SYSTEM, change processModel in Machine.config to <processModel userName="SYSTEM" ... />
The ASPNET Account • You can also run the ASP.NET worker process (aspnet_wp.exe or w3wp.exe) under a user account: https://msdn.microsoft.com/en-us/library/bakfs900.aspx
Forms Authentication • Forms authentication allows applications to setupweb authentications independently from the authentications of the operating systems. It works well with URL authorization, which relies on configuration directives in Web.config files. • Forms/URL security is useful to protect an e-commerce site (an external Internet application for servicing customs of a company).
Forms Authentication: Static Structure • Security settings in an ASP.NET-based web application are configured in the Web.config files. • The Web.config file in the root directory (which must be an application directory) specifies the authentication mode, application-specific login page. • The Web.config file in a subdirectory sets the authorization specifics for the directory. • User credentials can be stored in a database (preferred) or in the root Web.config file.
Forms Authentication : Dynamic Behavior • The first time a user accesses a protected resource, ASP.NET redirects the user to the login page. • If the login is successful, ASP.NET then issues the user an authentication ticket in the form of a cookie (cookies need to be enabled by the client) and redirects the user to the page originally requested. • The ticket allows that user to revisit protected portions without having to login again. • The ticket’s lifetime can be controlled to determine how long the login is good for.
A First Look at Forms Authentication • Forms1 Web Application • T:\Xiao\Windows Programming\Examples\C10\Forms1 • At the application root • PublicPage.aspx can be viewed by anyone • Web.config • LoginPage.aspx • In the Secret subdirectory • ProtectedPage.aspx is available only to authenticated users (wp/wp). • Web.config
Deploy Forms1 on Winserv1 • Create a web application (Forms1). C:\inetpub\wwwroot\xiaotest\Forms1 You need to have admin privilege. • On winserv1, use an existing web application directory already created for you. • Copy everything from T:\Xiao\Windows Programming\Examples\C10\Forms1 to the above directory. http://winserv1.cs.uakron.edu/xiaotest/Forms1/PublicPage.aspx can be viewed by everyone. (http://winserv1.cs.uakron.edu/Examples/C10/Forms1/PublicPage.aspx)
Deploy Forms1 on Winserv1 • http://winserv1.cs.uakron.edu/xiaotest/Forms1/Secret/ProtectedPage.aspx is available only to authenticated users (wp/wp). • “Authenticated users” means anyone who has successfully logged in through LoginPage.aspx. • Valid users are stored in Web.config. • The cookie containing the authentication ticket is a session cookie, destroyed when the browser is closed. • You are not prompted for password again during a session.
Programming Forms Security • Authentication in the root Web.config <authentication mode="Forms"> <forms loginUrl="LoginPage.aspx"> <credentials passwordFormat="Clear"> <user name="wp" password=“wp"/> <user name="John" password="redrover" /> • Authorization (directory-wise) in Secret/Web.config <authorization> <deny users="?" /> URL authorization to deny “?” (anonymous) users.
Programming Forms Security • PublicPage.aspx void OnViewSecret (Object sender, EventArgs e) { Response.Redirect ("Secret/ProtectedPage.aspx"); } • LoginPage.aspx. void OnLogIn (Object sender, EventArgs e) { if(FormsAuthentication.Authenticate(UserName.Text, Password.Text)) FormsAuthentication.RedirectFromLoginPage (UserName.Text, false); // “true” for persistent cookie else Output.Text = "Invalid login"; } System.Web.Security.FormsAuthentication.Authentic method returns true if the user name and password are in the credentials section of Web.config.
Internal Works • ASP.NET creates an authentication cookie, attaches it to the outgoing response, and redirects the user to the page that he or she originally requested. The lifetime of a persistent cookie is independent of the browser session. • Authorization is applied on a directory-by-directory basis. Web.config files in each directory specify exactly how the files are to be protected. • ASP.NET checks to see whether a valid authentication cookie is attached to the request. If the cookie exists, ASP.NET extracts identity information. If the cookie doesn’t exist, ASP.NET redirects the request to the login page.
Real-World Forms Authentication – (Forms2) • Storing user names and passwords in a database (MySQL). • Creating the database, creating the “users” table and adding users. • Logo on to winserv1. • Start->All Programs->My SQL->My SQL Query Browser. • Server Host: db1.cs.uakron.edu • Port 3306 • Username: yourLoginID • Password: yourPassword for MySQL • Default Schema: your DB name • File->Open Script: T:\Xiao\Windows Programming\Examples\C10\MySQL-Table-Creation\Weblogin.sql • Execute!
Real-World Forms Authentication Weblogin.sql CREATE TABLE users ( username varchar(32) NOT NULL, password varchar(32) NOT NULL, role varchar(32) ); INSERT INTO users (username, password, role) VALUES (‘dev', ‘dev', 'Developer'); INSERT INTO users (username, password, role) VALUES (‘mgr', ‘mgr', 'Manager'); … AddUsers.sql • INSERT INTO users (username, password, role) VALUES ('wpd1', 'wp2009', 'Developer'); • INSERT INTO users (username, password, role) VALUES ('wpd2', 'wp2009', 'Developer'); …
Deploy Forms2 on Winserv1 • Create a web application directory. C:\inetpub\wwwroot\xiaotest\Forms2 You need to have admin privilege. • On winserv1, use an existing web application directory already created for you. • Copy everything from T:\Xiao\Windows Programming\Examples\C10\Forms2 to the above directory.
Deploy Forms2 on Winserv1 • To access • http://winserv1.cs.uakron.edu/xiaotest/Forms2/PublicPage.aspx, can be viewed by anyone. • http://winserv1.cs.uakron.edu/xiaotest/Forms2/Secret/ProtectedPage.aspx and is available only to authenticated users (dev/dev).
Deploy Forms2 on Winserv1 • “Authenticated users” means anyone who has successfully logged in through LoginPage.aspx. • Valid users are stored in the database. • The cookie containing the authentication ticket is a session cookie, destroyed when the browser is closed. • You are not prompted for password again during a session.
Real-World Forms Authentication LoginPage.aspx • Credential Matching: SQL: select count(*) from users where username = ‘dev' and pwd = ‘dev’; It returns 0 if no matching credentials found. • MySQL notes: (1) count (*) works for SQL Server but not MySQL due to the extra space after count. (2) password is a keyword in MySQL (not SQL Server), therefore can’t be used as database column names. (3) ExecuteScalar returns Int64 for “count” query. • FormsAuthentication.RedirectFromLoginPage (UserName.Text, Persistent.Checked); Persistent authentication cookie: be able to get back without logging in again, even after shutting down. No expiration.
Authentication Cookie Lifetime • Session authentication cookie. Machine.config <forms ... timeout="30"> // 30 minutes Web.config <forms loginUrl="LoginPage.aspx" timeout="10080" /> // 7 days • Proramming cookies. HttpCookie cookie = Response.Cookies[FormsAuthentication.FormsCookieName]; cookie.Expires = DateTime.Now + new TimeSpan (7, 0, 0, 0); // 7 days • Removing cookies as a user. IE->Tools->Internet Options->General->Delete Cookies. Netscape->Tools->Cookie Manager->Manage stored cookies->Remove all. FireFox->Tools->Clear Recent History: check Cookies. Google Chrome->Customize->More Tools->Clear Browser Data->Cookies Safari -> Preferences ->Privacy -> Remove All Website Data
Forms AuthenticationRole-Based Securityhttp://winserv1.cs.uakron.edu/xiaotest/Forms3/PublicPage.aspxhttp://winserv1.cs.uakron.edu/xiaotest/Forms3/Secret/ProtectedPage.aspx
Forms Authentication and Role-Based Security (Forms3) • Use role membership to allow only some authenticated users to view Secret/ProtectedPage.aspx. • Without roles: Deny all unauthenticated users. <deny users="?" /> Deny all users (users=“*”) except John and Alice. <allow users="John, Alice" /> <deny users="*" /> Allow all except Jeff, Bob, and Mary: <deny users="Jeff, Bob, Mary" /> <allow users="*" /> <allow> and <deny> are order-sensitive. ASP.NET will stop at <…= “*”> and ignore any statements that appear after it.
Forms Authentication and Role-Based Security (Forms3) • With roles: • “Users” table has a field named “role” that stores each user’s role (group) membership. • Grant Developer access to Secret. <allow roles="Developer" /> <deny users="*" /> • Map the roles to user accounts so that ASP.NET can determine whether the requestor is a developer or not. • Place the mapping in the AuthenticateRequest event handler (invoked at the beginning of every request). • Can be done in a custom HTTP module or in Global.asax. http://winserv1.cs.uakron.edu/Examples/C10/Forms3/PublicPage.aspx http://winserv1.cs.uakron.edu/xiaotest/Forms3/PublicPage.aspx dev/dev/Developer can view ProtectedPage.aspx. mgr/mgr/Manager can’t.
Programming Role-based Authentication • Getting Information about Authenticated Users in Your Code • ASP.NET stores user information in the HttpContext.User property. • Access User through Page.Context.User or simply Page.User, or HttpApplication.User. • The “User” property is of the type IPrincipal (an interface defined in System.Security.Principal). • Implemented by the WindowsPrincipal class for Windows authentication and GenericPrincipal class for other forms of authentication (along with Windows authentication). • GenericPrincipal is a device for representing user identities independent of the authentication protocol being used. ASP.NET compares the role name in the GenericPrincipal to the roles granted access through Web.config. • User.Identity contains some usefull properties:
Properties in User.Identity if (User.Identity.IsAuthenticated) { string name = User.Identity.Name; … } Name is of the form domain-name\user-name for Windows authentication, user-typed login for forms authentication.
Programming Authentication - Roles Retrieve a user’s role and create a Principal for the user. <%@ Import Namespace="System.Security.Principal" %> <script language="C#" runat="server"> • void Application_AuthenticateRequest (Object sender, EventArgs e) • { • HttpApplication app = (HttpApplication) sender; • if (app.Request.IsAuthenticated && • app.User.Identity is FormsIdentity) { • FormsIdentity identity = (FormsIdentity) app.User.Identity; • // Find out what role (if any) the user belongs to • string role = GetUserRole (identity.Name); • // Create a GenericPrincipal containing the role name • // and assign it to the current request • if (role != null) • app.Context.User = new GenericPrincipal (identity, • new string[] { role }); • } • }
Programming Authentication - Roles string GetUserRole (string name) { MySqlConnection connection = new MySqlConnection ("server=db1.cs.uakron.edu;database=xiaotest;uid=xiaotest;pwd=wp2009; allow zero datetime=yes“) try { connection.Open (); StringBuilder builder = new StringBuilder (); builder.Append ("select role from users " + "where username = \'"); builder.Append (name); builder.Append ("\'"); MySqlCommand command = new MySqlCommand (builder.ToString (), connection); object role = command.ExecuteScalar (); if (role is DBNull) return null; return (string) role; } catch (MySqlException) { return null; } finally { connection.Close ();} }