C#Web Sec Oct27 2010 Final
Upcoming SlideShare
Loading in...5

Like this? Share it with your network


C#Web Sec Oct27 2010 Final

Uploaded on


More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. C# Web Security Class
    October 27, 2010
  • 2. Introduction
    • Please sign in
    • 3. Time: 8:30 AM – 4:00 PM
    • 4. Lunch Break: 11:30 – 12:30 P.M.
    • 5. See http://oitplaza.colorado.gov:8080/oitplaza/how-to/security-training for some sample classes.
    • 6. My personal website that contains some slides at http://www.s3curitys0lutions.com/
    • 7. Introductions, locations of facilities
    • 8. My background http://www.linkedin.com/pub/rich-helton/4/266/9a8
    • 9. My email rich.helton@state.co.us
  • General Disclaimer
    • Some of these tools and techniques in this training could be used to access and harm web systems.
    • 10. Only test a system with express written permission from the owner.
  • Some C# sites
    • Some websites with sample code:
    • 11. http://www.codeproject.com/
    • 12. http://www.c-sharpcorner.com/
    • 13. Microsoft Downloads:
    • 14. http://www.asp.net/downloads (SQL Express, VS Express)
    • 15. http://www.asp.net/ajaxlibrary/act.ashx (Ajax Toolkit)
    • 16. http://www.microsoft.com/express/Web/ (VS 2010 Web Express)
    • 17. http://www.microsoft.com/express/Downloads/ (VS 2010 C# Express)
  • Types of Web Hacking
  • 18. Web Attacks are the most common
    (from the 2010 ArcSight survey)
  • 19. There are many hacks….
    • And more are discovered every day. For 2010, the Open Web Application Security Project (OWASP) published the top ten web hacks, http://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project:
    Injection Flaws
    Cross Site Scripting (XSS)
    Broken Authentication and Session Management
    Insecure Direct Object Reference
    Cross Site Request Forgery (CSRF)
    Security Misconfiguration
    Insecure Cryptographic Storage
    Failure to Restrict URL Access
    Insufficient Transport Layer Protection
    Unvalidated Redirects and Forwards
  • 20. SANs 2010 Top Cyber Security Risks
  • 21. There are many Checklists….
    • Here are some checklists to help with the principles:
    • 22. The ASP.NET Security Checklist http://msdn.microsoft.com/en-us/library/ff648269.aspx
    • 23. WebAppSec Excel checklist http://img.a4apphack.com/dl/appsecchck-checklist.zip
    • 24. SANs reading Web Security Checklist http://www.sans.org/reading_room/whitepapers/securecode/security-checklist-web-application-design_1389
    • 25. The Open Web Application Security Project Application checklist is http://www.sans.org/reading_room/whitepapers/securecode/security-checklist-web-application-design_1389
  • Checklists Principles seem the same…
    • All the checklists, regardless of programming languages, have many of the same principles:
    • 26. Find and validate all input. This includes URL’s, JavaScript's, links, username and passwords, and especially any field calling a database.
    • 27. Never trust data in files, the network or database to be secure. Encrypt anything important, passwords, SSN’s, configurations.
    • 28. Never trust the source, be it customer or a service. Authenticate, Authorize and validate.
    • 29. Whenever a abnormal behavior occurs, error check and log.
    • 30. Keep testing, as people from all skills will be testing anything on line and may try common threats.
  • Finger Printing and Scanning
  • 31. Spiders, Bots, and Crawlers! Oh my...
    • All web sites on the Internet are constantly scanned.
    • 32. They are bots (automated scanners) from Virus vendors, Security organizations, search engines and more cataloging all web sites.
    • 33. There is the famous GoogleBot, http://en.wikipedia.org/wiki/Googlebot, that will look for the local robots.txt, see http://www.robotstxt.org/ , to define what to search for on the web site. Hackers usually don’t respect these gentlemen agreements on the Internet.
    • 34. There are so many scans on the Internet that many consider it white noise and careers have been built dedicated on sifting through the network traffics white noise.
    • 35. Hackers specializing in Google API’s (Google Hacking), search for hidden files, like etc/passwd, pdf’s, job announcements and more to define the web site coding.
  • Sometimes the spiders do damage
  • 36. Google Hacking
    • Google can be used to find out information about a web site using the Google API.
    • 37. A well known site containing a database of various keywords is found at http://www.hackersforcharity.org/ghdb/ .
    • 38. For example, “ext:asp” can be used to find pages ending in asp.
    • 39. For example,“ Hacking filetype:pdf” can be used to find PDFs that are about hacking.
    • 40. For example, “restaurants inanchor:menu” will find restaurants with menu links in them.
    • 41. intitle:index.of "web hacking”
  • Google Webcams
    • Google “165.127 inurl:/view/index.shtml” for Colorado Web Cams:
  • Google scans
    • Why scan when you can find others on the websites? Some scans can be found.
  • Googling for passwords
  • 42. Going beyond Google
    • There are now applications to combine search engine API’s to search for more items. http://midnightresearch.com/projects/search-engine-assessment-tool/
  • Being Anonymous
    There are entire networks of anonymous proxy sites,for tunneling through web sites, to mask the hacker. http://www.torproject.org
  • 43. Web sites watching Web sites….
    • Netcraft.com is one among many websites that will keep track of your uptime and server versions rather you know it or not:
  • http://www.zone-h.org/news/id/4735
    Defacement lookups
  • 44. Just because you changed the web site, doesn’t mean it went away, see www.archive.org,
  • 45. Wget
    (Open Source Web downloaders)
    • Open Source utilities, like wget, or VisualWgethttp://www.bebits.com/app/299, provide a means to download all available URL’s on a Web Site:
  • Wget
    (Open Source Web downloaders)
    • Results:
  • Web Scanners
    (The Community edition of NetSparker)
  • 46. Practicing the Web Hack….
    • There are many web server download builds to use that are intentionally broken for the purpose to practice web hacking.
    • 47. Some download applications to practice web hacking locally are:
    • 48. OWASP WebGoat (JSPs/Servlets) -http://www.owasp.org/index.php/OWASP_WebGoat_Project
    • 49. Hackme Bank (.Net) - http://www.foundstone.com/us/resources/proddesc/hacmebank.htm
    • 50. Hackme Books (JSPs/Servlets) –http://www.foundstone.com/us/resources/proddesc/hacmebooks.htm
    • 51. SecuriBench (Java Code) –
  • 52. Live sites…
    • There are also live web sites that simulate banks and other businesses to practice web hacking and test hacking tools against. They include:
    • 53. Spi Dynamics - http://zero.webappsecurity.com/
    • 54. Cenzic- http://crackme.cenzic.com/Kelev/view/home.php
    • 55. WatchFire - http://demo.testfire.net/
    • 56. HackThisSite - http://www.hackthissite.org/
    • 57. NTO - http://hackme.ntobjectives.com/
    • 58. Accunetix - http://testaspnet.acunetix.com/login.aspx
  • From Rich Helton’s October 2010 C# Web Security
    Defense against the Hacking Arts
  • 59. Are there many attacks?
  • 60. SQL Injection
    (Most common Injection Flaw)
  • 61. Intro to SQL Injection…
    • Many web pages communicate directly to a backend database for processing.
    • 62. For example, a username and password is asked for on the Web page and the web page will pass it to the database to validate the information.
    • 63. Some applications will not validate the field adequately before passing it to the database, and the database will process whatever it will receive.
    • 64. Hackers will pass SQL commands directly to the database, and in some cases tables like “passwords” are returned because the SQL commands are not being filtered adequately.
    • 65. SQL may return errors in the web page that even lists the correct tables to query so that the hacker may make more accurate attempts to get data.
  • SQL Injection
    • SQL Injection is the ability to inject malicious SQL commands into the backend code.
    • 66. For example:
    SELECT * FROM users WHERE username = ‘USRTEXT ' 
AND password = ‘PASSTEXT’
    • Passing ' OR 1=1-- in the USRTEXT field generates:
    SELECT * FROM users WHERE username = ‘’ OR 1=1 -- ' 
AND password = ‘PASSTEXT’
    • The OR 1=1 returns true and the rest is commented out
  • ASP.NET HacmeBank(Let’s try it)
  • 67. ASP.NET HacmeBankAuthentication without username/password
  • 68. Types of SQL Injection…
    • There are really two types of SQL injection, “Blind” SQL Injection and “Directed” SQL Injection.
    • 69. Blind SQL Injection is performed when a hacker passes SQL commands into the web form and generic errors are returned to the user, for instance a “404” Error page or page not found. The hacker has to make more extensive guesses on the database behind the web server.
    • 70. Directed SQL Injection is when the web server returns SQL errors to the user that give information about the table that has issue processing the SQL command. Some web pages may return “users.password table incorrect SQL query”, which gives the hacker the name of the database to launch the attack against.
  • Common attack strings
    ‘ or 27(hex) – delineates SQL string values.
    “ or 22 (hex) – also delineates SQL string values.
    ; or 3B (hex) - terminates statements.
    # or 23(hex) - also terminates a statement. (Access DB)
    /* or 2F2A (hex) - comment delimiter.
    -- or 2D2D (hex) – also comment delimiter.
    ( or 28 (hex) or ) or 29 (hex) – logical sub clauses.
    { or 7B (hex) or } or 7D (hex) – terminates a question.
    exec – used to call MS-SQL stored procedures.
    union – a SQL command very common to SQL injection.
  • 71. HackmeBooks SQL Injection(shows org.hsqldb.jdbc connection)
  • 72. HackmeBooks SQL Injection(attacking)
    • HSQL DB, uses a SHUTDOWN to shut down the database, since the SEARCH field uses straight SQL commands, typing in ‘;+SHUTDOWN;-- will add ‘%’; SHUTDOWN; --%’ in the SQL statement, thus shutting down the database:
    • 73. Session is now closed because we shutdown the database:
  • Real life example
    • Start by identifying the SQL Server version, table name and fields in the error page:
    • 74. We see that it is SQL Server, and an “id” field into the “business.dbo.urltracking” table. An Attacker can now try inserting into the table.
  • Common fixes to SQL Injection…
    • SQL Injection is caused by “Dynamic SQL” with unconstrained validation.
    • 75. Constrain the validation to not pass SQL commands to Dynamic SQL.
    • 76. Use Stored Procedures.
    • 77. Use Parameterized, or Prepared statements.
    • 78. Use newer technology frameworks that are built using Parameterized statements like NHibernate and Spring.NET.
    • 79. Use the ADO.NET Entity framework.
  • Stored Procedures
    • A stored procedure is a precompiled subroutine that is stored in the data dictionary for use of applications accessing the SQL Server.
    • 80. A sample stored procedure for exec sp_GetInventory ‘FL’ :
  • Hacking Stored Procedures
    • Stored procedures can be just as dangerous as SQL Injection, if not properly configured.
    • 81. One the most dangerous Stored Procs in SQL Server is the default xp_cmd_shell.
    • 82. If you have admin permissions with SQL server, you can try this simple example: exec master..xp_cmdshell ‘dir c:’
    • 83. Extending this feature, dynamic SQL may allow, in the username form : MyUsername; exec xp_cmdshell '"echo open" >> c:hack.txt’;
    • 84. See http://www.informit.com/articles/article.aspx?p=30124&seqNum=3 for an example attack.
  • Stored Procedures Hacks(Who’s hacking them? From SANs )
  • 85. Entity Framework
    • With the ADO.NET Entity Framework, Visual Studio can be used to create Entity Relationship Models (ERM) in order to create a database.
    • 86. Entity Framework is part of .NET 4 and is often referred to as EF4.
  • Entity Framework(Generate from DB)
  • 87. Entity Framework(Selecting ADO.NET in VS 2010)
  • 88. A Sample Entity Framework(Model1.edmx with the VS Model Browser)
    Changes made to the model can propagate to the Database.
  • 89. Another Example(Has all the details of the data)
  • 90. A Database can be generated
  • 91. Customize the code generated by the Entity Designer with T4 (.tt) templates
    • T4 is the Text Template Transformation Toolkit.
    • 92. T4 is a means for creating code generated artifacts.
    • 93. T4 will generate a .tt file which looks like ASP classic syntax with the brackets.
    • 94. The .tt file is the Text Template file that will generate the background C# code from the Entity Model.
    • 95. Click on the model .edmx file and select “Add Code Generation File…”
  • Use a T4 Editor to highlight code
    • VS 2010 does not come with a T4 Visual Editor, so a plugin needs to be installed to offer IntelliSense.
    • 96. For VS 2010, I use the plugin at http://t4-editor.tangible-engineering.com
  • 97. T4 Editor
    • The .tt is just the template to generate the underlying .cs (C#) file:
  • PEM
    • Microsoft’s Portable Extension Metadata, a subset of shema metadata, can be installed to add validation to the Entity Module and its entities, http://visualstudiogallery.msdn.microsoft.com/en-us/e6467914-d48d-4075-8885-ce5a0dcb744d
  • PEM
    • After installing PEM, validation not only shows up in properties, but generation code can be generated through T4.
  • PEM
    • PemValidation.cs with the Validate method for Employee:
  • Object-Relational Mapping (ORM)
    • NHibernate, the .NET version of Hibernate, can be used as a object-relational mapping (ORM) and persistence framework that allows you to map .NET objects to relational database tables using (XML) configuration files.
    • 98. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.
    • 99. The main advantages of Hibernate is that maps database entities to objects and hides the details of the data access from the business logic.
    • 100. Hibernate uses prepared statements, so it is protected from direct SQL injection, but it could still be vulnerable to injecting HQL statements which are more complex to execute.
  • Sample Customer Mapping
  • 101. NHibernateValidator
    • NHibernate has it’s own Validatorpluginhttp://nhforge.org/wikis/validator/nhibernate-validator-1-0-0-documentation.aspx .
    • 102. This validator (or constraint) will not only validate the values but can also validate the size of the data before being persisted.
    • 103. Sample constraint annotations:
    public class Address {
    private string name; // Cannot be null
    [Length(Max = 5, Message = "{long}")]
    [Pattern(Regex = "[0-9]+")]// Regex for Digits
    private string zip; // 5 digits
  • 104. Recommendations
    • It is recommended to validate the data at the entity level, just in case the Front End is compromised.
    • 105. ORM’s not only make the coding of data easier to the Database, by not using SQL in multiple places, but also alleviates many of the Dynamic SQL issues.
  • XSS
    (Cross Site Scripting)
  • 106. XSS
    • Javascript is a scripting language originally from Netscape to provide browser side scripting in the HTML.
    • 107. The problem with using Javascript is the same as its purpose, the script can execute any script in the HTML browser, however, it may also execute any script put into its place.
    • 108. Hackers can use Javascript to alert the browser to go to a different website, input some extra data, or even access data on the browser itself like browser cookies or the session information in the browser.
    • 109. The hacker takes advantage of changing the information in the <script> … </script> tags.
    • 110. The Javascript can be told to encode its programming to avoid taking information from other sources than the web server.
  • XSS…
    While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code:
  • 111. Hacme Books XSS…
    • This URL is scripting a page from an Acunetix site as input.
  • Insecure Web App XSS…
    • This URL is does an alert when the mouse moves over the email box:
  • Microsoft fixes to XSS by default(Retry in .NET 4 ASP.NET MVC)
    • By default “ValidationRequest” is set to “true” on the pages and web.config to return an exception for many forms XSS’s:
  • Microsoft fixes to XSS by default(When .NET 4.0 is used in IIS on the site)
    • The fix:
  • Some applications have to turn it off
    • Microsoft doesn’t recommend turning it off because it blocks several security issues by default.
    • 112. If it has to be turned off because of legitimate reasons, it can be replaced by coding pieces of the Anti-XSS 3.1 library.
    • 113. To turn it off, the web.config has to have the following added:
  • It’s now vulnerable to XSS
    • After turning off the default validation, and running “<script>alert(document.cookie)</script>” again, we get:
  • XSS Library 3.1
    • Microsoft has a Anti-Cross Site Scripting Library V3.1 to resolve this issue. This library is also known as the Web Protection Library (WPL). http://www.microsoft.com/downloads/en/details.aspx?FamilyID=051ee83c-5ccf-48ed-8463-02f56a6bfc09
    • 114. The XSS Library can be broken down into two pieces, a library of protection routines (using Microsoft.Security.Application) and also a a Security Runtime Engine (SRE) Configuration Utility.
    • 115. The library routines will Encode the output so that it will not execute if passing from an external field.
    • 116. The SRE inspects ASP.NET as it is executing and mitigates the XSS, in a similar method to a Web Application Firewall.
  • using Microsoft.Security.Application(some encodes)
  • 117. XSS Microsoft Security Application(object viewer)
  • 118. using Microsoft.Security.Application
    • Wrapping some code with the library that has input:
    • 119. Executing as before with “<script>alert(document.cookie)</script>” only encodes the output without executing an alert:
  • Security Runtime Engine (SRE)(part of anti-XSS 3.1, acts like a Web Firewall)
    • This doesn’t require hard coding, it filters all input data.
    • 120. A “antixssmodule.config” has to be included to define what to check. the Conifguration Generator for SRE can be used.
  • antixssmodule.config(sample)
    • Add
    • 121. Also add the SRE Filter in the “web.config” to look for the filtering:
  • Security Runtime Engine (SRE)
    • Executing as before with “<script>alert(document.cookie)</script>” it returns the same results as the Microsoft Security Application Library:
  • Conclusion
    • XSS is a dangerous attack that morphed into many types of injection attacks.
    • 122. Different types of XSS have evolved so that new ones are being discovered in the wild constantly.
    • 123. The protection has to be as robust as the attacks, and techniques need to evolve easily as well so that there filters, WAFs and multiple techniques can be used to protect against new attacks.
  • Cross Site Request Forgery
  • 124. CSRF(XSS Evolving)
    • CSRF is when a hacker tricks a user into injecting a small request (Request Forgery), like an image, into a victim’s browser to redirect a portion of the victim's browser to a vulnerable site while they are still logged onto their original site (the Cross Site).
    • 125. The benefit to the attacker, is that if a hidden image is injected into a user’s browser, and their browser currently has their bank authentication cookie, then the hacker may hijack the victims authentication.
    • 126. Let’s try a test on a Sample Web site….
  • XSRF
    • XS – Cross the site, RF – Forge a request
  • XSRF
    • The object of the attacker is to tailgate the session to a bank or some other institution through an image or some other script.
  • A quick test…
    • CSRF differs from XSS in that it is not passing in a Script, like an “alert” but a reference to another site.
    • 127. A reference could be many items like an “image (<img>)” or even an XMLHTTP object. http://www.cgisecurity.com/csrf-faq.htm
    • 128. To test, I usually try images, like a Google img from their site. <imgsrc="http://www.google.com/images/logos/ps_logo2.png" width="80" height"80" border="0"/> gives me:
  • A quick test…
    • Passing in the Google image with 80 x 80 pixels:
  • A quick test…
    • Gives me :
    • 129. That’s easy to see.
  • A quick test…
    • You need to pass in 0 x 0 pixels to remain unseen:
    • 130. In the “( )” is actually an image linking to another website. If an img is now linked, so can other tags, even some pulling or referring information over.
  • The Fix
    • Putting back in the Anti-XSS 3.1 SRE from the XSS section, we now pass the 0 x 0 image and get (fixed):
  • The Fix(.NET 4.0 use in IIS)
    • Ensuring that “<pages validateRequest="true" />” is set in the web.config, we now pass the 0 x 0 image and get (fixed):
  • A Fix (XSRF Tokens)
    • Another type of fix is for the server to issue a token to the browser for a specific session. When the user interacts with server, the browser will associate with the user session to verify the interaction.
    • 131. The attacker doesn’t have access to the token in the browser to perform the transaction.
  • ValidateAntiForgeryToken
    • The Browser must initiate the token in the HTML,
    • 132. Then the server must validate the token before executing the code :
    • The “ValidateAntiForgeryToken” is not native to ASP.NET, it is part of ASP.NET MVC2.
    • 133. To understand this technology, a quick understanding of ASP.NET MVC2 is needed.
  • 134. MVC
    • The Model-View-Controller is the most common design pattern in Software Architecture.
    Here are the pieces:
  • 135. Microsoft Visual Web Developer 2010 Express
    • Creating an MVC Project:
  • Microsoft Visual Web Developer 2010 Express
    • The views will be aspx files.
    • 136. The Controllers classes will
    implement the :Controller
    (IController) interface.
    ActionResults are returned from
    the functions. The code is
    annotated with [HTTPPost] and
    [Authorize] definitions.
    • The model classes will contain
    getters and setters to the data in the
    form of { get; set; }. It is defined with
    a #region models area.
  • 137. Blocking CSRF in the Controller
    • The controller code accepts annotations for the functions and objects that can add validation.
    • 138. Microsoft offers a validation for CSRF, called “ValidateAntiForgeryToken”. Example code below shows it examining the data before returning it to the next view:
  • Test MVC App
    • Passing in the 0 x 0 (zero by zero) image into the MVC example:
  • ValidateAntiForgeryToken error(The Controller)
    • ValidateAntiForgeryToken doing its job:
  • ValidateRequest error(Otherwise .NET 4.0 doing its job)
    • ValidateRequest=“true” Form Validator doing its job:
  • JSON Hijacking
  • 139. JSON
    • Javascript Object Notation (JSON) is a human readable interchange of simple data structures and associative arrays in a notational language.
    • 140. Information on it can be found at http://json.org/ .
    • 141. JSON is sometimes used in transfer of data, like in Ajax, instead of XML.
    • 142. JSON is used instead of XML because it has a smaller file footprint and can be read easily into Javascript.
    • 143. JSON is normally defined by using the mime type “application/json” and also by using the file type “.json”.
    • 144. To understand JSON, a small understanding of AJAX must occur first.
  • Ajax
    • Asynchronous JavaScript and XML (Ajax) is a method of employing JavaScript, DHTML, and XML Http in a browser to provide truly dynamic content on a Web page without a page refresh.
    • 145. Data is usually retrieved using the XMLHttpRequest (XHR) object from the server asynchronously.
    • 146. Javascript (ECMAScript) is used for local processing, and the Document Object Model (DOM) is used to access the data inside the page or read XML from the server. This means that the browser only sends and receives the parts that it needs to change and tries to process some data locally.
    • 147. Ajax is server agnostic.
    • 148. Ajax is not a technology in itself, but a group of technologies.
  • Ajax (a walk through-javascript)
    • Let’s start by calling a validate() function in JavaScript with the onkeyup method:
    <input type="text” size="20” id="userid” name="id” onkeyup="validate();">
    • The validate() creates a XMLHttpRequest to pass to the server:
    function validate() {
    varidField = document.getElementById("userid");
    varurl = "validate?id=" + encodeURIComponent(idField.value);
    if (typeofXMLHttpRequest != "undefined") {
    req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.
    "); }
    req.open("GET", url, true);
    req.onreadystatechange = callback;
  • 149. Ajax (a walk through – Http POST)
    • The XMLHttp Request is sent to the server.
    • 150. The browser has to interpret the Javascript regardless of how it is encoded and decoded. If a browser can read the Javascript, then the Javascript can be debugged/monitored and manipulated using a JavaScript reverser to intercept the functions.
    • 151. The defense is to validate the Server code.
    • 152. The Page_Load ( ) will get the XML file and must parse through it.
  • Ajax (a walk through – Http POST)
    • Sample of Page_Load ( ) parsing out a Names.xslt in .cs :
  • Just plain old ASP.NET Validation
    • There are many Validators in ASP.NET, RequiredFieldValidator, RangeValidator, CompareValidator, CustomValidator and RegularExpressionValidator. A RegularExpressionValidator:
  • JQuery
    • JQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML.
    • 153. JQuery is the most popular JavaScript library in use today.
    • 154. JQuery syntax is designed to make it easier to navigate a document, select DOM elements, and develop Ajax applications.
  • JQuery
    • When creating a new ASP.NET
    MVC 2 solution, the following JQuery
    Scripts will be created.
    • Javascripts like jquery.validate.js
    can do form level validation.
  • 155. jquery.validate.js
    • JQuery offers validation rules where it will check items, like credit cards, email address, date, name, and more.
  • jquery.validate.js
  • 156. JSON example
  • 157. Similar XML example
  • 158. JSON Hijacking
    • JSON hijacking is an evolution of XSRF.
    • 159. It requires redirection to a new site and suing JSON through a GET interface.
  • JSON Hijacking
    • Like XSRF, the JSON attack is trying tail gate off the original session to the valid site.
  • JSON Fixes
    • In ASP.NET 2, the JsonResult object responds only to HTTP POST request to counter this issues, and also validating the Ajax. http://download.microsoft.com/download/F/1/6/F16F9AF9-8EF4-4845-BC97-639791D5699C/WhatIsNewInMVC_2.pdf
  • Intro to Flex and Silverlight
    • Flex and Silverlight adds more issues and protection.
    • 160. Flex uses the Flash plugin for running it’s GUI program. http://flex.org/
    • 161. Silverlight programs use the Silverlightplugin for running its environment. http://www.silverlight.net/
    • 162. So the hacking tools normally have to have the plugin in the client as well to talk to these technologies, including Web Scanners.
    • 163. Many of the attacks will now not only be limited to the Flex or Silverlightdeployement but also to the plugin as well.
    • 164. These technologies are platform agnostic as long as the plugin is supported in the browser.
  • Flex and Silverlight Hacking
    • They both use their own form of XML, so they are susceptible to XML attacks, especially any form of XML leaving the plugin.
    • 165. They both can communicate and work with Javascript, therefore they could be susceptible to any XSS form of attack.
    • 166. The best defense is to use WCF to Authenticate, Authorize and Encrypt any communication to the browser and server.
  • Adobe Flex
    • Adobe Flex is a Software Development Kit from Adobe to create Rich Internet Applications (RIA) that plug into the Web Browser’s Flash plugin.
    • 167. Flex uses MXML, the Macromedia XML, as a declarative layout of the interfaces to compile into the SWF file that is deployed.
    • 168. To extend the MXML, Flex uses a language called ActionScript, which is similar to Java. ActionScript can be called from the MXML file using the <mx:script> tag.
    • 169. <mx:script source = “code.as”/>
  • MXML Hello World Example
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Applicationxmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundGradientColors="[#000011, #333333]"> <mx:Label text="Hello World!" verticalCenter="0" horizontalCenter="0" fontSize="48" letterSpacing="1"> <mx:filters>
    <mx:GlowFilter color="#ffffdd"/> </mx:filters> </mx:Label>
  • 170. FlexBuilder 3 Example
  • 171. Example <mx:CreditCardValidator> tag
  • 172. SWFScan
    • HP’sSWFScan looks for specific vulnerabilities in the Adobe Flex SWF file.
  • Watcher(http://websecuritytool.codeplex.com)
    • Here’s a Watcher scan with both a Silverlight and Flex (Flash) issue
  • Watcher(http://websecuritytool.codeplex.com)
    • Silverlight checks:
  • Watcher(http://websecuritytool.codeplex.com)
    • Flash checks:
  • Creating Silverlight in Web Express
    • Creating a VS 2010 Web Express Silverlight Project will generate the following files:
  • Silverlight
    • Silverlight is the Microsoft competitor of Adobe Flex.
    • 173. Microsoft offers stripped down versions of Visual Studio to get started with Silverlight from http://www.silverlight.net/getstarted/ .
    • 174. The files created when creating a Silverlight project include:
  • Silverlight(walkthrough)
    • The user requests the HTML entry page in the browser.
    • 175. The browser loads the Silverlight plug-in.
    • 176. It then downloads the XAP file that contains your application. This file uses the standard .zip compression.
    • 177. The Silverlight plug-in reads the AppManifest.xml file from the XAP to find out what assemblies your application uses. It creates the Silverlight runtime environment and then loads your application assembly (along with any dependent assemblies).
    • 178. The Silverlight plug-in creates an instance of your custom application class (which is defined in the App.xaml and App.xaml.cs files).
    • 179. The default constructor of the application class raises the Startup event.
    • 180. Your application handles the Startup event and creates the root visual object for your application.
    • 181. XAML (eXtended Application Markup Language) is XML for Silverlight, mostly for graphics.
  • Silverlight(extra pages)
    • Silverlight.js – JavaScript helper functions for creating and initializing the Silverlight content region.
    • 182. SilverlightApplication3TestPage.aspx – This is a ASP page that will need to be deployed on a Web server to test the Silverlight project SilverlightApplication3. This can be used a entry point into the Silverlight Application.
    • 183. SilverlightApplication1TestPage.html – This is a HTML page that will need to be deployed on a Web server to test the Silverlight project SilverlightApplication3. This can be used a entry point into the Silverlight Application.
    • 184. Web.config - to allow configuration of the test pages.
  • A Silverlight example
  • 185. A Silverlight examplehttp://memorabilia.hardrock.com/
  • 186. XamlPad(A visual XAML editor)
    • This tool is part of the Microsoft 7 Windows SDK:
  • XamlPad(A visual XAML editor)
    • The XAML code:
  • Inkscape(From the MAC OSX for XAML)
  • 187. Some Silverlight Links
    • The Silverlight Toolkit, open source, for phones, plugins and many samples . http://silverlight.codeplex.com/
    • 188. MoonLight, the Open Source Silverlight project for Linux and Unix, http://www.mono-project.com/Moonlight
  • IIS Settings
  • 189. IIS 5.0 WebDav
    (A side note because it has caused hacks)
    • By default, programs like Web Distributed Authoring and Versioning (DAV) are enabled by default to administrate IIS remotely.
    • 190. Microsoft has instructions to disable WebDavhttp://support.microsoft.com/default.aspx?scid=kb;en-us;241520
  • Secret Writing
  • 191. Who’s seeing your data?
    • Data at rest and in transient can be at risk to prying eyes.
    • 192. When a system is in production, and especially on the Internet, there is no guarantee that you know who is watching the data transmitted between the user and the server. This may also apply to the Local Area Network as well.
    • 193. Never take it for granted that access cannot be broken.
    • 194. Always, use common algorithms that come with Java. Common algorithms are tested well and are vetted by millions.
    • 195. Keep the keys as secure as the data, because they can unlock the data.
    • 196. Homemade encryptions algorithms may end up costing more than standard encryptions if broken.
  • One-way Hash Algorithms
    • There are two common types of one-way hash algorithms, Message Digest 5 (md5), and Secure Hash Algorithm 1 (sha1).
    • 197. The one-way hash generates a fixed size hash some given any size data.
    • 198. The data cannot be reversed engineered from the hash, hence one-way.
    • 199. The same data generates the same hash sum.
    • 200. Different data generates different hash sums.
    (Note: In rare cases, collisions, different data generates the same sum).
  • 201. Md5
    • Message Digest 5 (md5) will take data input and generate 128 bit hash sum.
    • 202. The 128 bit hash sum can be used to ensure if there has been tampering of data or a file.
    • 203. A common comparison is to store passwords in a table, and instead of checking the password, compare the hash of the password, so that the password does not have to be stored.
  • Md5, C# code
  • 204. Sha1
    • Secure Hashing Algorithm 1 (Sha1) will take any size byte array and produce a 160 bit hash sum, sometimes called a message digest.
    • 205. Other SHA’s are SHA224,SHA256,SHA384, and SHA512, each one denoting the size in bits of the message digest.
  • Sha1, C# code
    C:>??PI?w??????H ?f?:
  • 206. AES
    • The National Security Agency (NSA) updated their algorithm in 2001 to the Advanced Encryption Algorithm (AES) for Top Secret information from the Data Encryption Standard in 1975.
    • 207. The Rijndael algorithm was selected, developed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen.
    • 208. The NIST adapted the variable key space into 128, 192, or 256 bits as FIPS 197 and called it AES.
    • 209. AES is a symmetric key algorithm, meaning that the same key is used to both encrypt and decrypt.
  • AES C# Code
    • Initialing an Initialization Vector for AES, and the password , Cipher Mode, and Salt. They must match on both sides. :
  • AES C# Code
    • The Encryption through a Memory Stream, a File Stream could be used instead:
  • AES C# Code
    • The Decryption through a Memory Stream, a File Stream could be used instead:
  • AES C# Code
    • The Output, with Key, Encryption and Decryption:
  • RSA
    • The most important Asymmetric algorithm to undertsand is the Rivest-Shamir-Adleman (RSA). So named after the MIT mathematician inventors in 1978.
    • 210. The Asymmetric algorithm can generate key pairs, one private key for encrypting, and its pair is handed out for decryption to more people, the public key.
    • 211. The key pair are formulated from a pair of prime numbers using a modulus equation that become linked to each other.
  • RSA Keys, a simple example
    1) Choose two prime numbers p and q.
    P = 61 and q = 53.
    2) Compute n = pq, n = 61 * 53 = 3233.
    3) Compute the totient(n) = (p – 1)(q – 1) =
    (61 -1) * (53 – 1) = 3120.
    4) Choose a coprimee(like 17) that is not a divisor of the totient.
    5) Compute d such that e*d mod (n) = 1.
    17 * 2753 (d) = 46801, 46801 mod 3120 = 1.
    public key = (e, n) = (17, 3233)
    private key = (d, n) = ( 2753, 3233)
  • 212. RSA Keys, a simple encrypt/decrypt
    public key = (e, n) = (17, 3233)
    private key = (d, n) = ( 2753, 3233)
    To compute the ciphertext we use
    C = Pe (mod n).
    For example, P = 65 and is the letter ‘H’.
    C = 2790 = 6517 mod 3233.
    Back to Plaintext, P = Cd mod n.
    P = 65 = 27902753 mod 3233. Which returns 65 for ‘H’.
  • 213. C# RSA Keys
  • 214. C# RSA Keys (output of private)
  • 215. C# RSA Encrypt/Decrypt
  • 216. Digital certificates
  • 217. Beyond Encryption
    • Now that we can encrypt and provide message digests, let’s do more by putting the pieces together.
    • 218. A larger, combined, piece is the Digital Certificate.
    • 219. A Digital Certificate is a protocol X509 structure that contains verification of the certificate, Non-repudiation (proof of receipt), and third party authentication through a Certificate Authority.
    • 220. The Digital Certificate is the heart of Hypertext Transfer Protocol over Secure Socket Layer (HTTPS) and Public Key Infrastructure (PKI).
    • 221. PKI is the process of authentication through a trusted party called Certificate Authority (CA). This could be a third party or self signed internally through a domain controller.
    • 222. HTTPS allows secure transport over Web Services and Web Servers, and in some cases secure file transport services.
  • X.509 Format
  • 223. Microsoft Tools
    • MakeCert.exe, that is part of the Windows SDK, can create certificates, http://msdn.microsoft.com/en-us/library/aa386968(VS.85).aspx
  • makecert
    • With makecert we will create a certificate on the localhost with the CurrentUser and store it in MySite:
  • certmgr
    • With certmgr.exe we read the certificate store and also add to the Certificate store, here we add the previous Certificate to the TrustedPeople store:
  • certmgr
    • List from the certmgr.exe, we read the certificate from the TrustedPeople store:
  • MMC
    • Certificates can be read in the Microsoft Management Console, http://technet.microsoft.com/en-us/library/aa997890(EXCHG.80).aspx but first a Snap-In needs to be installed:
  • MMC
    • We cane read, edit and save the file from the TrustedPeople store:
  • C# Certificates
    • After copying the previous Certificate to a local directory, we can manipulate it.
    • 224. The “using System.Security.Cryptography.X509Certificates” handles many of the certificate methods, lets show some certificate entries:
  • C# Certificates
    • With the X509Certifcates library, we can print out Certificate fields and even create our own certificate.
  • A word about passwords
    • Never use default passwords or simple passwords.
    • 225. Websites can get accessed by typing in “admin” “admin” at times, and auditors try a range of default and well known logins.
    • 226. Use complex and different passwords, if its hard to keep track of them then use something like keepass. http://keepass.info/
  • Windows Communication Frameworks (WCF)
  • 227. Intro to SOA
    • Web Services are a Application Programming Interface (API), Web APIs, that are accessed via Hypertext Transfer Protocol (HTTP) and executed on remote system hosting the requested services.
    • 228. The eXtensible Markup Language (XML) defines the interfaces and content of the message.
    • 229. A Service Oriented Architecture (SOA) is a flexible set of design principles to define a architecture to provide a loosely-integrated suite of services that can be used in multiple business domains. This architecture makes extensive use of XML.
  • SOA Stack
  • 230. Steps in Web Services
    • The first step when a client seeks to interface to a Web Service, is that it must find the Web Service, for this purpose, UDDI is used.
    • 231. UDDI provides for discovery of services and retrieval of their WSDL descriptions as a directory service. This service may require authentication and encrypt the HTTP protocol.
    • 232. The UDDI will return the WSDL and forward the client to the proxy that will contain the service, usually in the form of a URL.
    • 233. The WSDL will define the acceptable interface into the SOA.
    • 234. The client SOAP call will format the acceptable XML. SOAP will act as an envelope to the SOA.
    • 235. The SOA will accept the call if it meets the WSDL criteria and process the call.
    • 236. The SOA will respond based on the SOAP call to the corresponding client.
  • Steps to Web Services
  • 237. Sample WSDL
  • 238. SOAP
    • Simple Object Access Protocol (SOAP) is a protocol specification for exchanging structured information in Web Services.
    • 239. SOAP will normally have a Envelope of XML text that usually consists of a SOAP Header and SOAP Body. SOAP will also require a transport mechanism like HTTPS to transport the XML.
  • SOAP
  • 240. WS-Security
    • WS-Security (Web Services Security, or WSS for short) is an extension to SOAP to apply security to Web Services.
    • 241. Microsoft extends this framework with the Windows Communication Framework (WCF).
    • 242. A guide for writing Secure Web Services can be found at http://wcfsecurityguide.codeplex.com/releases/view/15892
    • 243. Like other frameworks, for example Apache’s Axis2, WCF also supports Authentication, Authorization, Secure Transport, Tokens and Signatures in Web Services. The difference is that WCF is fully integrated into .NET.
    • 244. These frameworks work on top of SOAP, WS-Security, and other known protocols.
  • WCF
    • According to http://msdn.microsoft.com/en-us/netframework/aa663324.aspx
  • Benefits of WCF
    • The ABC’s of WCF are Address, Binding and Contract.
    • 245. The Address is the server endpoints being exposed.
    • 246. There are several types of bindings, Http, MSMQ, TCP, etc. These are the communication protocols being used, for instance SOAP over TCP. The Bindings help support end-to-end security for the Web Service.
    • 247. The contract is the service contract that the service will expose for the various clients.
    • 248. WCF also is strongly typed, or even untyped messaging, built on top of .NET.
    • 249. WCF also has support for sessionlike state management.
  • WCF
    • WCF creates a service contract between clients and services:
  • Create a WCF Service(Visual Studio 2010 Web Express)
  • 250. Steps for creating a WCF( [ServiceContract] )
    • IIS has to be running and the service has to be deployed in a Virtual or Physical directory.
    • 251. The ServiceModel and ServiceModel.Web need to be applied, as well as the [ServiceContract] to define which interfaces are exposed to the client:
  • Steps for creating a WCF(.svc)
    • A .svc file needs to be created, Visual Studio created one. This file functions similarly to an .asmx file in IIS to identify the service code behind the file and class.
  • Steps for creating a WCF(.svc)
    • A .svc file itself:
  • Steps for creating a WCF(Web.conf)
    • The web.config can be used to define the service instead of the .svc file.
    • 252. It will typically lists the types that you want to expose in the service. It will also define the binding types used.
  • An Authentication Sample
    • A good sample can be found at http://www.codeproject.com/KB/WCF/WCFBasicHttpBinding.aspx
    • 253. Let’s start by publishing the example:
  • An Authentication Sample
    • This sample is a generic “BasicHttpBinding” service.
    • 254. Windows Authentication is required for the Service because of he setting in IIS to not allow Anonymous and use Integrated Windows Authentication. This is an IIS setting found by accessing the web site->Properties->Directory Security->Edit:
  • An Authentication Sample
    • Let’s call the exposed Service and we will get a Window’s Authentication dialog for Window’s Authentication. This is because we disabled Anonymous access in IIS:
  • An Authentication Sample
    • The Service requires a client to call it.
    • 255. Before forcing Windows Authentication, the Service will respond with a similar Page describing how to create a client:
  • Creating a client
    • A client can be created from the exposed WSDL, or SVC, using the Windows SDK svcutil.exe. See http://msdn.microsoft.com/en-us/library/ms733133.aspx
    • 256. Start by creating a Console Application in C#, then add the “System.ServiceModel” reference and associated “using System.ServiceModel” in the Program.cs.
    • 257. Generate a proxy with the svcutil:
    • 258. Add the generated proxy, generatedProxy.cs and app.config, to the console application.
    • 259. Then the client service is available to be coded in the console app:
  • Https
    • Https (Http Secure) is a protocol designed to implement the Secure Socket Library (SSL), or Transport Layer Security (TLS), at port 443.
    • 260. It is designed to provide a encrypted port, validate the Http Server, and in some cased validate the Http Client.
  • An HTTPS Sample
    • A good example can be found at http://www.codeproject.com/KB/WCF/7stepsWCF.aspx
    • 261. We make a certificate for the localhost:
    • 262. The web.config will specify a certificate:
  • An HTTPS Sample (IIS Config)
    • IIS has to be configured with the Certificate at the Default Web Service:
  • An HTTPS Sample (IIS Config)
    • Now you get this page unless you have a certificate:
  • Hacking
    Web Services
  • 263. Intro to Hacking SOA
    • Web Services are means to interface and transport SOAP calls through XML.
    • 264. The difference between hacking Web Services, is that the attacks are transmitted in the XML field, which is similar to HTML, instead of an HTML form field.
    • 265. In other words, the XML must be parsed out to enter an attack in the “username” text field in the XML format instead of the “username” GUI form field in HTML.
    • 266. Many of the attacks in Web Services are designed to attack the backend server application code that may not be validating.
  • SQL Injection with SOAP
    • Just as SQL Injection can be passed in the form field, it can also be passed in a SOAP call. Here is an example with passing a “ in the field:
  • XPATH Injection with SOAP
    • Xpath (XML Path Language) is a language defined to find information in an XML document.
    • 267. It uses path to traverse traverse through the nodes of an XML document to look for specific information.
    • 268. Xpath injection is similar to SQL injection except that the query strings are slightly different and it uses XML as its attack vector.
    • 269. One example is to pass ‘ or 1=1 or ‘ ‘=‘ as the username to fake the database into a valid username:
    • 270. string(//user[name/text()='' or 1=1 or ''=''
    and password/text()='foobar']/account/text())
  • 271. LDAP Injection with SOAP
    • The Lightweight Directory Access Protocol (LDAP) is a protocol for storing directory services for an organization that usually includes user, group and machine policies. An example of an LDAP server is Microsoft’s Active Directory.
    • 272. LDAP injection tries to get returned user information, or server information returning information in the error using “(“ in this example:
  • From Rich Helton’s October 2010 C# Web Security
  • 273. Security Testing
  • 274. White Box Testing
    • White-Box testing is testing the system based on the internal perspective of the system.
    • 275. In this case, this is also known as Static Analysis.
    • 276. These tools can find issues with the source code before the code is actually executed.
    • 277. A list of tools can be found at http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
  • CAT.NET(A plugin that can be added from the Windows SDK)
    • CAT.NET can be used with Visual Studio to analyze the current solution, here is a Visual Studio 2008 popup after selecting Tools->CAT.NET Analysis Tool from the menu:
  • CAT.NET(After pushing the Excel report button)
  • 278. FXCop
    • CAT.NET rules can can be run in FXCop instead of Visual Studio.
    • 279. FXCop examines the assemblies and object code and not the source. It can be downloaded as part of the Windows SDK.
    • White-Box testing is testing the system based on the internal perspective of the system.
    • 280. See www.nunit.org
    • 281. These tools can find issues with the source code before the code is actually executed.
    • 282. A list of tools can be found at http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
  • 283. Headless Browser
    • Headless Browser Automation
    • 284. Can replicate a real world browser.
    • 285. Can automate the test.
    • 286. Provides low-level control over the HTML and HTTP.
    • 287. Reference http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/
  • HTMLUnit steps
    • Download HTMLUnithttp://sourceforge.net/projects/htmlunit/
    • 288. Download IKVM http://sourceforge.net/projects/ikvm/files/
    • 289. Create the HTMLUnit DLL:
    • 290. Run “ikvmc –out:htmlunit-2.7.dll *.jar”
    • 291. Include the htmlunit, IKVM.OpenJDK, and nunitdll’s in the external assemblies.
    • 292. Can automate the test.
    • 293. Provides low-level control over the HTML and HTTP.
    • 294. Reference http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/
  • What about the HTML?
    • HTTPUnit is great for HTTP Requests and Responses, but what if I want to parse the HTML code directly from the Web Server and examine the HTML before doing any work.
    • 295. HTMLUnit allows a “getPage()” routine to examine the HTML source code.
    • 296. This allows the walking through of “HREF”, images, and others pieces of the HTML code before executing on the item.
    • 297. Selenium IDE is another Open Source concept that is a Integrated Development Environment running on top of the FireFox browser as a plugin.
    • 298. This allows a recording of the browser actions that can be played back execute buttons being pushed and actions inside the browser.
    • 299. Assertions can be executed on the HTML pages itself for checking specific information.
    • 300. The test itself can be exported into Junit Java code to execute in Java.
  • HtmlUnit on C#
  • 301. HtmlUnit on C# (Nunit Test)
    (Under Construction page)
  • 302. HtmlUnit on C# (Nunit Test)
    (Page not found)
  • 303. Selenium IDE
    • Selenium IDE is another Open Source concept that is a Integrated Development Environment running on top of the FireFox browser as a plugin.
    • 304. Supports load testing.
    • 305. This allows a recording of the browser actions that can be played back execute buttons being pushed and actions inside the browser.
    • 306. Assertions can be executed on the HTML pages itself for checking specific information.
    • 307. The test itself can be exported into Java, .NET, Perl, Ruby, etc, and then code to execute the tests in that language.
  • Selenium IDE Test
  • 308. Does the framework matter?
    • JWebUnit wraps both HTMLUnit and Selenium so that code can be written for either framework using a unified framwork.
    • 309. This way code can once in a single framework and executed using multiple HTML frameworks. http://jwebunit.sourceforge.net/
  • Security Debugging
    -Error Pages
  • 310. Has my system been compromised?
    • Logging and Error handling is one of the most important concept in Security.
    • 311. When an incident happens, the first questions are always “How did they get in?” and “What data was compromised?”.
    • 312. The least favorite answer is usually “No one knows.”
    • 313. With efficient logging of authorization, access to secure information, and any anomalous interaction with the system, a proper recovery of the system is usually insured.
    • 314. The logs should be store into a different system in case the Web system is ever compromised, one where the Web system sends them but never asks for them back.
    • 315. Logging is a fundamental API that comes with the Java and .NET languages.
  • Logging the C# way….
    using System;
    using System.Diagnostics;
    class EventLogExample
    static void Main(string[] args)
    string sSource = "my warning message";
    string sLog = "Application";
    string sEvent = "Sample Event";
    if (!EventLog.SourceExists(sSource))
    EventLog.CreateEventSource(sSource, sLog);
    EventLog.WriteEntry(sSource, sEvent);
    EventLog.WriteEntry(sSource, sEvent,
    EventLogEntryType.Warning, 234);
  • 316. The C# Logger output….
  • 317. Exception Handling
    • Exception handling has helped debugging immensely. It allows a programmer to code for anomalies and handle a bizarre behavior.
    • 318. There are 3 components of handling an exception, and they are the “try”, “catch” and “finally” blocks.
    • 319. The “try” block will throw an exception from normal code, the “catch” block will catch the exception and handle it, and the “finally” block will process the cleanup afterwards.
    • 320. The “catch” block can log the anomaly, stop the program, or process it in a hundred different ways.
    • 321. You can write your own custom exception classes to trace specific pieces of code.
  • C# Exception Handling code….
    class TestException{
    static void Main(string[] args){
    StreamReader myReader = null;
    // constructor will throw FileNotFoundException
    myReader = new StreamReader("IamNotHere.txt");
    }catch (FileNotFoundException e){
    Console.WriteLine("FileNotFoundException was {0}", e.Message);
    }catch (IOException e){
    Console.WriteLine("IOException was {0}" + e.Message);
    if (myReader != null){
    }catch (IOException e){
    Console.WriteLine("IOException was {0}" + e.Message);}}}}}
    Output-> FileNotFoundException was Could not find file ‘C:IamNotHere.txt'.
  • 322. Log4net
    • The previous logging and exception handling example has many hard coded pieces. Log4Net offers more de-coupling by being separated as highly configurable framework.
    • 323. http://logging.apache.org/log4net/
    • 324. Even though the basic CLR logging framework can accept changes on destination through its Handler in the “logging.properties”, Log4Net offers more advanced features in its XML use of its Appender class.
    • 325. Log4Net supports XML configuration and a text configuration in log4Net.properties.
    • 326. Log4Net supports Appenders that will append the logs to databases, emails, files, etc. http://logging.apache.org/log4net/release/config-examples.html
  • Log4Net ASP.NET code
  • 327. Log4j Console output
  • 328. Adding an Appender #1
    • Let’s read the XML Appender from app.config.
    • 329. Change the BasicConfigurator to XmlConfigurator:
  • Adding an Appender #2
    • Add app.config for "c:Loglog.txt”:
  • Adding an Appender Running
    • Reading "c:Loglog.txt”:
  • NLog
    • Nlog is similar to Log4Net. The difference is that Log4Net is a .Net version of Log4J and is a framework. NLog is a plugin to Visual Studio with templates.
    • 330. http://nlog-project.org/
  • NLog
    • Adding log configuration with Visual 2010 plugin:
  • NLog
    • When debugging from VS2010, the default logging directory maps to C:Program FilesCommon FilesMicrosoft SharedDevServer10.0 .
    • 331. This Nlog.config will append the logger in to a file named after the classname, i.e Webapplication1._Default.txt:
  • Nlog code
    • From the WebApplication1 Class, Default.aspx.cs code:
  • Nlog log file
    • Printing the Webapplication1._Default.txt:
  • Error Pages
    • Default Error pages may display unintentional information. For instance, some error pages may display database information in an exception.
    • 332. An error page giving details, like a database or table name, may be more than enough to give an attacker enough information launch an attack at the website.
    • 333. To correct bad error handling in pages, Tomcat, Struts and other Web engines will allow default configurations to throw a specific error page for any unknown exceptions. For instance, many Web Application Firewalls (WAFs) will generate a error page 500 “Internal Server Error” for blocking an attack.
  • Hackme Books
    (Bad error handling)
  • 334. Send something more generic
    (based on business input)
  • 335. Web Error pages….
    Many web sites use the default error pages that show the user exceptions and even exceptions into the database. The database exceptions have a tendency to display table names and invalid SQL statements that can be used for further probing.
    To send all errors to a custom Error page, the web.config file for IIS:
    <customErrors mode="On"
  • 336. Custom Errors in ASP.NET
    • A good resource on the issue is http://www.codeproject.com/KB/aspnet/customerrorsinaspnet.aspx
    • 337. The idea is to redirect the error to a generic error.html page by the web.config configuration.
  • Send something more generic
    (based on business input)