1 / 46

Enforcing Security in .NET based Web Services

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?

korbin
Download Presentation

Enforcing Security in .NET based Web Services

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Presented by Abhishek Kamalayagari Enforcing Security in .NET based Web Services

  2. Outline • Basics of web services • Threats and counter measures • Security based on WS-Security • Security based on event logs

  3. 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.

  4. 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; • }

  5. 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(); • web1web reference name and • add-> web service name

  6. Soap request Soap response

  7. Note: Simple Object Access Protocol (SOAP) is an XML message format

  8. Web service technologies

  9. Threats at web services • Unauthorized access • Parameter manipulation • Network eavesdropping • Disclosure of configuration data • Message replay

  10. 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.

  11. 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.

  12. 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.

  13. 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

  14. 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.

  15. 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.

  16. 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.

  17. Design considerations: • Authentication requirements • Privacy and integrity requirements • Resource access identities • Code access security

  18. 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

  19. 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

  20. 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 } }

  21. 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 . . . }

  22. 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));

  23. 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>

  24. 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>

  25. 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>

  26. 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>

  27. 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>

  28. 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) { }

  29. 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>

  30. XML encryption • Asymmetric encryption using X.509 certificates • Symmetric encryption using shared keys • Symmetric encryption using custom binary tokens

  31. 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)

  32. 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 ); }

  33. Security using event logs • Log exceptions in the event log • Event types: Information Warning Error Success Audit Failure Audit

  34. 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); • } • }

  35. 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); • }

  36. Result of writeToEventLog could be one of the following: • EventLogEntryType.Error • EventLogEntryType.FailureAudit • EventLogEntryType.Information • EventLogEntryType.SuccessAudit • EventLogEntryType.Warning

  37. 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

  38. b) using the EventLogInstaller class in System.Diagnostics namespace

  39. 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); • } • } • }

  40. 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

  41. 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

  42. Thank you

More Related