470 likes | 614 Vues
Presented by Abhishek Kamalayagari. Enforcing Security in .NET based Web Services. Outline. Basics of web services Threats and counter measures Security based on WS-Security Security based on event logs. Basics of web services. What a web service is?
E N D
Presented by Abhishek Kamalayagari Enforcing Security in .NET based Web Services
Outline • Basics of web services • Threats and counter measures • Security based on WS-Security • Security based on event logs
Basics of web services • What a web service is? • An application stored on one machine that can be accessed from another machine. • A web service has several web methods • Three components: -service broker -service provider -service requester • Web methods are remotely invoked using a Remote Procedure Call • Does everything using XML. • Used by a computer , so XML.
Sample web service • [WebService(Namespace = "http://tempuri.org/")] • [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] • [ToolboxItem(false)] • public class add : System.Web.Services.WebService • { • [WebMethod] • public string HelloWorld() • { • return "Hello World"; • } • [WebMethod] • public string ad(string a, string b) • { • int r = Convert.ToInt32(a); • int s = Convert.ToInt32(b); • int p = r + s; • string q = p.ToString(); • return q; • }
Calling a web service • web1.add a = new web1.add(); • string op1=TextBox1.Text; • string op2=TextBox2.Text; • string re = a.ad(op1, op2); • int res = Convert.ToInt32(re); • TextBox3.Text = res.ToString(); • web1web reference name and • add-> web service name
Soap request Soap response
Note: Simple Object Access Protocol (SOAP) is an XML message format
Threats at web services • Unauthorized access • Parameter manipulation • Network eavesdropping • Disclosure of configuration data • Message replay
Unauthorized access vulnerabilities: ->No authentication used ->Passwords passed in plaintext in SOAP headers ->Basic authentication used over an unencrypted communication channel Counter measures: • Use password digests , Kerberos tickets , X.509 certificates in SOAP headers for authentication. • Use Windows authentication. • Use role-based authorization to restrict access to web services.
Parameter manipulation vulnerabilities: • Messages that are not digitally signed • Messages that are not encrypted Counter Proof: • Digitally sign the message. • Encrypt the message payload to provide privacy.
Network eavesdropping vulnerabilities: • Credentials passed in plaintext in SOAP headers • No message level encryption used • No transport level encryption used Counter measures: • Use transport level encryption such as SSL or IPSec. This is applicable only if you control both endpoints. • Encrypt the message payload to provide privacy. This approach works in scenarios where your message travels through intermediary nodes route to the final destination.
Disclosure of configuration data vulnerabilities: • Unrestricted WSDL files available for download from the Web server • A restricted Web service supports the dynamic generation of WSDL and allows unauthorized consumers to obtain Web service characteristics • Weak exception handling
Counter measures: • Authorize access to WSDL files using NTFS permissions. • Remove WSDL files from Web server. • Disable the documentation protocols to prevent the dynamic generation of WSDL. • Capture exceptions and throw a SoapException or SoapHeaderException that returns only minimal and harmless information back to the client.
Message replay vulnerabilities: • Messages are not encrypted • Messages are not digitally signed to prevent tampering • Duplicate messages are not detected because no unique message ID is used Common types of message replay attacks: • Basic replay attack. The attacker captures and copies a message, and then replays the same message and impersonates the client. This replay attack does not require the malicious user to know the contents of the message. • Man in the middle attack. The attacker captures the message and then changes some of its contents, for example, a shipping address, and then replays it to the Web service.
Counter measures: • Use an encrypted communication channel, for example, SSL. • Encrypt the message payload to provide message. Although this does not prevent basic replay attacks, it does prevent man in the middle attacks where the message contents are modified before being replayed. • Use a unique message ID or nonce with each request to detect duplicates, and digitally sign the message to provide tamperproofing.
Design considerations: • Authentication requirements • Privacy and integrity requirements • Resource access identities • Code access security
Input validation • Web methods can accept strongly typed or weakly typed parameters • Strong parameters have type description by XSD schema • Consumers use this information to access web services • System.Xml.Serialization.XmlSerializer class is used to convert soap messages to CLR objects. • Sql injection can be counter attacked by input validation
Example: • [WebMethod] public void CreateEmployee(string name, int age, decimal salary) {...} • Example of custom object data types: • using Employees; // Custom namespace [WebMethod] public void CreateEmployee(Employee emp) { ... } • If consumer is a .net client then using Employees; Employee emp = new Employee(); // Populate Employee fields // Send Employee to the Web service wsProxy.CreateEmployee(emp); Else //Construct XML input manually
Loosely typed parameters: Eg: string parameters or byte arrays • auto-generated WSDL simply describes the parameters as string input of type xsd:string. • type, length, format, and range ? [WebMethod] public void SomeEmployeeFunction(string dateofBirth, string SSN) { . . . // EXAMPLE 1: Type check the date try { DateTimedt = DateTime.Parse(dateofBirth).Date; } // If the type conversion fails, a FormatException is thrown catch( FormatException ex ) { // Invalid date } // EXAMPLE 2: Check social security number for length, format, and range if( !Regex.IsMatch(empSSN,@"\d{3}-\d{2}-\d{4}",RegexOptions.None)) { // Invalid social security number } }
Validating XML data • Web method can use the System.Xml.XmlValidatingReader class to validate the input data • using System.Xml; • using System.Xml.Schema; • [WebMethod] • public void OrderBooks(string xmlBookData) • { • try { // Create and load a validating reader • XmlValidatingReaderreader = new XmlValidatingReader(xmlBookData, XmlNodeType.Element, null); • // Attach the XSD schema to the reader • reader.Schemas.Add("urn:bookstore-schema", @"http://localhost/WSBooks/bookschema.xsd"); • // Set the validation type for XSD schema. • // XDR schemas and DTDs are also supported • reader.ValidationType= ValidationType.Schema; • // Create and register an event handler to handle validation errors • reader.ValidationEventHandler+= new ValidationEventHandler( ValidationErrors ); • // Process the input data • while (reader.Read()) { . . . } // Validation completed successfully } • catch { . . . } } // Validation error event handler • private static void ValidationErrors(object sender, ValidationEventArgsargs) { // Error details available from args.Message . . . }
Consumer calls it this way: • string xmlBookData = "<book xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" + "<title>Building Secure ASP.NET Applications</title>" + "<isbn>0735618909</isbn>" + "<orderQuantity>1</orderQuantity>" + "</book>"; • BookStore.BookServicebookService = new BookStore.BookService(); bookService.OrderBooks(xmlBookData));
XSD schema: • <?xml version="1.0" encoding="utf-8" ?> <xsd:schemaxmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:bookstore-schema" elementFormDefault="qualified" targetNamespace="urn:bookstore-schema"> <xsd:element name="book" type="bookData"/> <xsd:complexType name="bookData"> <xsd:sequence> <xsd:element name="title" type="xsd:string" /> <xsd:element name="isbn" type="xsd:integer" /> <xsd:element name="orderQuantity" type="xsd:integer"/> </xsd:sequence> </xsd:complexType> </xsd:schema>
Constraining individual elements: • Regular expressions: • <xsd:element name="zip"> <xsd:simpleType> <xsd:restriction base="xsd:string"> <xsd:pattern value="\d{5}(-\d{4})?" /> </xsd:restriction> </xsd:simpleType> </xsd:element> • Decimal value to 2 digits: • <xsd:element name="Salary"> <xsd:simpleType> <xsd:restriction base="xsd:decimal"> <xsd:fractionDigits value="2" /> </xsd:restriction> </xsd:simpleType> </xsd:element>
Message Level Authentication • User name and password: • <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext"> <wsse:UsernameToken> <wsse:Username>Bob</wsse:Username> <wsse:Password>YourStr0ngPassWord</wsse:Password> </wsse:UsernameToken> </wsse:Security>
Username and password digest: The digest is a Base64-encoded SHA1 hash value of the UTF8-encoded password. digest = SHA1(nonce + creation timestamp + password) Kerboros tickets: <wsse:Securityxmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext"> <wsse:BinarySecurityTokenValueType="wsse:Kerberosv5ST" EncodingType="wsse:Base64Binary"> U87GGH91TT ... </wsse:BinarySecurityToken> </wsse:Security>
X.509 certificates; • <wsse:Securityxmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext"> <wsse:BinarySecurityTokenValueType="wsse:Kerberosv5ST" EncodingType="wsse:Base64Binary"> U87GGH91TT ... </wsse:BinarySecurityToken> </wsse:Security>
authorization • Web service end point authorization -can use urlauthorization to control access to .asmx files • Web method authorization: Use declarative principal permission demands. [PrincipalPermission(SecurityAction.Demand, Role=@"Manager")] [WebMethod] public string QueryEmployeeDetails(string empID) { }
Digitally signing a soap message: http://msdn.microsoft.com/en-us/library/ms824659.aspx Disabling auto generation of wsdl: <webServices> <protocols> <add name="HttpSoap"/> <!-- <add name="Documentation"/> --> </protocols> </webServices>
XML encryption • Asymmetric encryption using X.509 certificates • Symmetric encryption using shared keys • Symmetric encryption using custom binary tokens
Exception management • Bad example: • System.Exception: User not in managers role at EmployeeService.employee.GiveBonus(Int32 empID, Int32 percentage) in c:\inetpub\wwwroot\employeesystem\employee.asmx.cs:line 207 • Web services can throw 3 types of exceptions: SoapException SoapHeaderException Exception (DivisionByZero,ArgumentOutOfRange)
Good example: • try { EmployeeService service = new EmployeeService(); Service.GiveBonus(empID,percentage); } catch (System.Web.Services.Protocols.SoapException se) { // Extract custom message from se.Detail.InnerTextConsole.WriteLine("Server threw a soap exception" + se.Detail.InnerText ); }
Security using event logs • Log exceptions in the event log • Event types: Information Warning Error Success Audit Failure Audit
Example: • [WebMethod] • public void DivideNumbers(intintNumerator, int • intDenominator) • { • double dResult; • try • { • dResult = intNumerator / intDenominator; • } • catch (Exception e) • { • //Write to Event Log • WriteToEventLog(e.Message, EventLogEntryType.Error); • } • }
Method to write to the Event Log • /// <summary> • /// Method to write to the Event Log • /// </summary> • /// <param name="strLogEntry">The message to be • logged</param> • /// <param name="eType">Event Log Type</param> • private void WriteToEventLog(string strLogEntry, • EventLogEntryTypeeType) • { • string strSource = "Division Web Service"; //name of the • source • string strLogType = "Application"; //type of the log • string strMachine = "."; //machine name • if (!EventLog.SourceExists(strSource, strMachine)) • { • EventLog.CreateEventSource(strSource, strLogType, • strMachine); • } • EventLogeLog = new EventLog(strLogType, strMachine, • strSource); • eLog.WriteEntry(strLogEntry, eType, 1000); • }
Result of writeToEventLog could be one of the following: • EventLogEntryType.Error • EventLogEntryType.FailureAudit • EventLogEntryType.Information • EventLogEntryType.SuccessAudit • EventLogEntryType.Warning
System.Security.SecurityException, will be thrown when we try to make an entry in to the log. • Problem is no event source found. • 2 approaches to solve the problem: • a) 1. Click Start -> Run, type regedit. • 2. Locate the registry subkey • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlS • et\Services\Eventlog\Application. • 3. Right-click the Application subkey, point to New and • then click Key. • 4. Type Division Web Service for the key name. • 5. Close Registry Editor
b) using the EventLogInstaller class in System.Diagnostics namespace
Listing 3: Event Log Installer • using System; • using System.Diagnostics; • using System.ComponentModel; • using System.Configuration.Install; • namespace EventLogSourceInstaller • { • [RunInstaller(true)] • public class MyEventLogInstaller: Installer • { • private EventLogInstallermyEventLogInstaller; • public MyEventLogInstaller() • { • //Create Instance of EventLogInstaller • myEventLogInstaller = new EventLogInstaller(); • // Set the Source of Event Log, to be created. • myEventLogInstaller.Source = “Division Web sevices”; • // Set the Log that source is created in • myEventLogInstaller.Log = “Application”; • // Add myEventLogInstaller to the Installers Collection. • Installers.Add(myEventLogInstaller); • } • } • }
conclusion • WS-Security is the emerging standard for Web services security. The specification defines options for authentication by passing security tokens in a standard way using SOAP headers. Tokens can include user name and password credentials, Kerberos tickets, X.509 certificates, or custom tokens. WS-Security also addresses message privacy and integrity issues. • Event logging :this security strategy work • out with Windows NT, windows 2000, windows XP and • windows Vista. In the future additional research work needs • to be carried out to implement the same concept in different • platform to prevent the system with invalid access
References • http://msdn.microsoft.com/en-us/library/ff648643.aspx • http://research.microsoft.com/enus/projects/samoa/webservicesandsecurity.pdf • http://www.15seconds.com/issue/010430.htm • http://www.luca.demon.co.uk/ • http://www.hannesmarais.com/ • http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4735939