c#web sec oct27 2010 final

Post on 14-May-2015

5.393 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

C# Web Security ClassOctober 27, 2010

Introduction Please sign in Time: 8:30 AM – 4:00 PM Lunch Break: 11:30 – 12:30 P.M.

See http://oitplaza.colorado.gov:8080/oitplaza/how-to/security-training for some sample classes.

My personal website that contains some slides at http://www.s3curitys0lutions.com/

Introductions, locations of facilities My background

http://www.linkedin.com/pub/rich-helton/4/266/9a8

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.

Only test a system with express written permission from the owner.

Some C# sites

Some websites with sample code: http://www.codeproject.com/ http://www.c-sharpcorner.com/

Microsoft Downloads: http://www.asp.net/downloads (SQL Express, VS

Express) http://www.asp.net/ajaxlibrary/act.ashx (Ajax

Toolkit) http://www.microsoft.com/express/Web/ (VS 2010

Web Express) http://www.microsoft.com/express/Downloads/

(VS 2010 C# Express)

Types of Web Hacking

Web Attacks are the most common(from the 2010 ArcSight survey)

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 :

1) Injection Flaws

2) Cross Site Scripting (XSS)

3) Broken Authentication and Session Management

4) Insecure Direct Object Reference

5) Cross Site Request Forgery (CSRF)

6) Security Misconfiguration

7) Insecure Cryptographic Storage

8) Failure to Restrict URL Access

9) Insufficient Transport Layer Protection

10) Unvalidated Redirects and Forwards

SANs 2010 Top Cyber Security Risks

There are many Checklists….

Here are some checklists to help with the principles: The ASP.NET Security Checklist

http://msdn.microsoft.com/en-us/library/ff648269.aspx

WebAppSec Excel checklist http://img.a4apphack.com/dl/appsecchck-checklist.zip

SANs reading Web Security Checklist http://www.sans.org/reading_room/whitepapers/securecode/security-checklist-web-application-design_1389

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:

Find and validate all input. This includes URL’s, JavaScript's, links, username and passwords, and especially any field calling a database.

Never trust data in files, the network or database to be secure. Encrypt anything important, passwords, SSN’s, configurations.

Never trust the source, be it customer or a service. Authenticate, Authorize and validate.

Whenever a abnormal behavior occurs, error check and log.

Keep testing, as people from all skills will be testing anything on line and may try common threats.

Finger Printing and Scanning

Spiders, Bots, and Crawlers! Oh my...

All web sites on the Internet are constantly scanned.

They are bots (automated scanners) from Virus vendors, Security organizations, search engines and more cataloging all web sites.

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.

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.

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

Google Hacking

Google can be used to find out information about a web site using the Google API.

A well known site containing a database of various keywords is found at http://www.hackersforcharity.org/ghdb/ .

For example, “ext:asp” can be used to find pages ending in asp.

For example,“ Hacking filetype:pdf” can be used to find PDFs that are about hacking.

For example, “restaurants inanchor:menu” will find restaurants with menu links in them.

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

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

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/4735Defacement lookups

Just because you changed the web site, doesn’t mean it went away, see www.archive.org,

Wget (Open Source Web downloaders)

Open Source utilities, like wget, or VisualWget http://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)

http://www.mavitunasecurity.com/communityedition/

Practicing the Web Hack….

There are many web server download builds to use that are intentionally broken for the purpose to practice web hacking.

Some download applications to practice web hacking locally are: OWASP WebGoat (JSPs/Servlets) -

http://www.owasp.org/index.php/OWASP_WebGoat_Project

Hackme Bank (.Net) - http://www.foundstone.com/us/resources/proddesc/hacmebank.htm

Hackme Books (JSPs/Servlets) – http://www.foundstone.com/us/resources/proddesc/hacmebooks.htm

SecuriBench (Java Code) –

http://suif.stanford.edu/~livshits/securibench/

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: Spi Dynamics - http://zero.webappsecurity.com/ Cenzic -

http://crackme.cenzic.com/Kelev/view/home.php WatchFire - http://demo.testfire.net/ HackThisSite - http://www.hackthissite.org/ NTO - http://hackme.ntobjectives.com/ Accunetix - http://testaspnet.acunetix.com/login.aspx

Defense against the Hacking Arts

From Rich Helton’s October 2010 C# Web Security

Are there many attacks?

SQL Injection(Most common Injection

Flaw)

Intro to SQL Injection…

Many web pages communicate directly to a backend database for processing.

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.

Some applications will not validate the field adequately before passing it to the database, and the database will process whatever it will receive.

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.

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.

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 Hacme Bank(Let’s try it)

ASP.NET Hacme BankAuthentication without username/password

Types of SQL Injection…

There are really two types of SQL injection, “Blind” SQL Injection and “Directed” SQL Injection.

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.

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.

HackmeBooks SQL Injection(shows org.hsqldb.jdbc connection)

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:

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:

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.

Constrain the validation to not pass SQL commands to Dynamic SQL.

Use Stored Procedures.

Use Parameterized, or Prepared statements.

Use newer technology frameworks that are built using Parameterized statements like NHibernate and Spring.NET.

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.

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.

One the most dangerous Stored Procs in SQL Server is the default xp_cmd_shell.

If you have admin permissions with SQL server, you can try this simple example: exec master..xp_cmdshell ‘dir c:\’

Extending this feature, dynamic SQL may allow, in the username form : MyUsername; exec xp_cmdshell '"echo open 192.168.10.12" >> c:\hack.txt’;

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 )

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.

Entity Framework is part of .NET 4 and is often referred to as EF4.

Entity Framework(Generate from DB)

Entity Framework(Selecting ADO.NET in VS 2010)

A Sample Entity Framework(Model1.edmx with the VS Model Browser)

Changes made to the model can propagate to the Database.

Another Example(Has all the details of the data)

A Database can be generated

Customize the code generated by the Entity Designer with T4 (.tt) templates

T4 is the Text Template Transformation Toolkit. T4 is a means for creating code generated artifacts. T4 will generate a .tt file which looks like ASP classic syntax with the brackets. The .tt file is the Text Template file that will generate the background C# code from the Entity Model. 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. For VS 2010, I use the plugin at http://t4-editor.tangible-engineering.com

To

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.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks. The main advantages of Hibernate is that maps database entities to objects and hides the details of the data access from the business logic.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

NHibernate Validator

NHibernate has it’s own Validator plugin http://nhforge.org/wikis/validator/nhibernate-validator-1-0-0-documentation.aspx .This validator (or constraint) will not only validate the values but can also validate the size of the data before being persisted. Sample constraint annotations:

public class Address {

[NotNull]

private string name; // Cannot be null

[NotNull]

[Length(Max = 5, Message = "{long}")]

[Pattern(Regex = "[0-9]+")] // Regex for Digits

private string zip; // 5 digits

Recommendations

It is recommended to validate the data at the entity level, just in case the Front End is compromised. 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)

XSS

Javascript is a scripting language originally from Netscape to provide browser side scripting in the HTML.

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.

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.

The hacker takes advantage of changing the information in the <script> … </script> tags.

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: <applet> <body> <embed> <frame> <script> <frameset> <html> <iframe> <img> <style> <layer> <link> <ilayer> <meta> <object>

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.

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.

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

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.

The library routines will Encode the output so that it will not execute if passing from an external field.

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)

XSS Microsoft Security Application(object viewer)

using Microsoft.Security.Application

Wrapping some code with the library that has input:

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. A “antixssmodule.config” has to be included to define

what to check. the Conifguration Generator for SRE can be used.

Add

Also add the SRE Filter in the “web.config” to look for the filtering:

antixssmodule.config(sample)

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.

Different types of XSS have evolved so that new ones are being discovered in the wild constantly.

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

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

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.

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.

A reference could be many items like an “image (<img>)” or even an XMLHTTP object. http://www.cgisecurity.com/csrf-faq.htm

To test, I usually try images, like a Google img from their site. <img src="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 :

That’s easy to see.

A quick test…

You need to pass in 0 x 0 pixels to remain unseen:

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.

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,

Then the server must validate the token before

executing the code :

ASP.NET MVC2

The “ValidateAntiForgeryToken” is not native to ASP.NET, it is part of ASP.NET MVC2.

To understand this technology, a quick understanding of ASP.NET MVC2 is needed.

ASP.NET MVC 2

MVC

The Model-View-Controller is the most common design pattern in Software Architecture.

Here are the pieces:

Microsoft Visual Web Developer 2010 Express

Creating an MVC Project:

Microsoft Visual Web Developer 2010 Express

The views will be aspx files. 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.

Blocking CSRF in the Controller

The controller code accepts annotations for the functions and objects that can add validation.

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

JSON

Javascript Object Notation (JSON) is a human readable interchange of simple data structures and associative arrays in a notational language.

Information on it can be found at http://json.org/ . JSON is sometimes used in transfer of data, like in Ajax,

instead of XML. JSON is used instead of XML because it has a smaller

file footprint and can be read easily into Javascript. JSON is normally defined by using the mime type

“application/json” and also by using the file type “.json”.

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. Data is usually retrieved using the XMLHttpRequest (XHR) object from the server asynchronously. 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.Ajax is server agnostic. 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:

var req;

function validate() {

var idField = document.getElementById("userid");

var url = "validate?id=" + encodeURIComponent(idField.value);

if (typeof XMLHttpRequest != "undefined") {

req = new XMLHttpRequest();

} else if (window.ActiveXObject) {

req = new ActiveXObject("Microsoft.

"); }

req.open("GET", url, true);

req.onreadystatechange = callback;

req.send(null);}

Ajax (a walk through – Http POST)

The XMLHttp Request is sent to the server. 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. The defense is to validate the Server code. 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. JQuery is the most popular JavaScript library in use today. 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.

jquery.validate.js

JQuery offers validation rules where it will check items, like credit cards, email address, date, name, and more.

jquery.validate.js

JSON example

Similar XML example

JSON Hijacking

JSON hijacking is an evolution of XSRF. 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. Flex uses the Flash plugin for running it’s GUI program. http://flex.org/ Silverlight programs use the Silverlight plugin for running its environment. http://www.silverlight.net/ So the hacking tools normally have to have the plugin in the client as well to talk to these technologies, including Web Scanners. Many of the attacks will now not only be limited to the Flex or Silverlight deployement but also to the plugin as well. 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. They both can communicate and work with Javascript, therefore they could be susceptible to any XSS form of attack.

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. Flex uses MXML, the Macromedia XML, as a declarative layout of the interfaces to compile into the SWF file that is deployed. 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.

<mx:script source = “code.as”/>

MXML Hello World Example

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns: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>

</mx:Application>

FlexBuilder 3 Example

Example <mx:CreditCardValidator> tag

SWFScan

HP’s SWFScan 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. Microsoft offers stripped down versions of Visual Studio to get started with Silverlight from http://www.silverlight.net/getstarted/ .The files created when creating a Silverlight project include:

Silverlight(walkthrough)

The user requests the HTML entry page in the browser. The browser loads the Silverlight plug-in. It then downloads the XAP file that contains your application. This file uses the standard .zip compression. 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). The Silverlight plug-in creates an instance of your custom application class (which is defined in the App.xaml and App.xaml.cs files). The default constructor of the application class raises the Startup event. Your application handles the Startup event and creates the root visual object for your application. 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.

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.

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.

Web.config - to allow configuration of the test pages.

A Silverlight example

A Silverlight examplehttp://memorabilia.hardrock.com/

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)

Some Silverlight Links

The Silverlight Toolkit, open source, for phones, plugins and many samples . http://silverlight.codeplex.com/ MoonLight, the Open Source Silverlight project for Linux and Unix, http://www.mono-project.com/Moonlight

IIS Settings

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.

Microsoft has instructions to disable WebDav http://support.microsoft.com/default.aspx?scid=kb;en-us;241520

Secret Writing(Encryption)

Who’s seeing your data?

Data at rest and in transient can be at risk to prying eyes. 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.

Never take it for granted that access cannot be broken. Always, use common algorithms that come with Java.

Common algorithms are tested well and are vetted by millions.

Keep the keys as secure as the data, because they can unlock the data.

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

The one-way hash generates a fixed size hash some given any size data.

The data cannot be reversed engineered from the hash, hence one-way.

The same data generates the same hash sum.Different data generates different hash sums.

(Note: In rare cases, collisions, different data generates the same sum).

Md5

Message Digest 5 (md5) will take data input and generate 128 bit hash sum.

The 128 bit hash sum can be used to ensure if there has been tampering of data or a file.

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

C:\>m"?0↕eQ/☺???♀?

Sha1

Secure Hashing Algorithm 1 (Sha1) will take any size byte array and produce a 160 bit hash sum, sometimes called a message digest.

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?:

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.

The Rijndael algorithm was selected, developed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen.

The NIST adapted the variable key space into 128, 192, or 256 bits as FIPS 197 and called it AES.

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.

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.

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 coprime e (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)

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

 

C# RSA Keys

C# RSA Keys (output of private)

C# RSA Encrypt/Decrypt

Digital certificates

Beyond Encryption

Now that we can encrypt and provide message digests, let’s do more by putting the pieces together.

A larger, combined, piece is the Digital Certificate. 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.

The Digital Certificate is the heart of Hypertext Transfer Protocol over Secure Socket Layer (HTTPS) and Public Key Infrastructure (PKI).

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.

HTTPS allows secure transport over Web Services and Web Servers, and in some cases secure file transport services.

X.509 Format

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.

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. Websites can get accessed by typing in “admin” “admin”

at times, and auditors try a range of default and well known logins.

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)

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.

The eXtensible Markup Language (XML) defines the interfaces and content of the message.

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

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.

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.

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.

The WSDL will define the acceptable interface into the SOA. The client SOAP call will format the acceptable XML. SOAP

will act as an envelope to the SOA. The SOA will accept the call if it meets the WSDL criteria and

process the call. The SOA will respond based on the SOAP call to the

corresponding client.

Steps to Web Services

Sample WSDL

SOAP

Simple Object Access Protocol (SOAP) is a protocol specification for exchanging structured information in Web Services.

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

WS-Security

WS-Security (Web Services Security, or WSS for short) is an extension to SOAP to apply security to Web Services.

Microsoft extends this framework with the Windows Communication Framework (WCF).

A guide for writing Secure Web Services can be found at http://wcfsecurityguide.codeplex.com/releases/view/15892

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.

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. The Address is the server endpoints being exposed. 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.

The contract is the service contract that the service will expose for the various clients.

WCF also is strongly typed, or even untyped messaging, built on top of .NET.

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)

Steps for creating a WCF( [ServiceContract] )

IIS has to be running and the service has to be deployed in a Virtual or Physical directory.

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.

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

Let’s start by publishing the example:

An Authentication Sample

This sample is a generic “BasicHttpBinding” service. 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. 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

Start by creating a Console Application in C#, then add the “System.ServiceModel” reference and associated “using System.ServiceModel” in the Program.cs.

Generate a proxy with the svcutil:

Add the generated proxy, generatedProxy.cs and app.config, to the console application.

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.

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

We make a certificate for the localhost:

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

Intro to Hacking SOA

Web Services are means to interface and transport SOAP calls through XML.

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.

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.

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.

It uses path to traverse traverse through the nodes of an XML document to look for specific information.

Xpath injection is similar to SQL injection except that the query strings are slightly different and it uses XML as its attack vector.

One example is to pass ‘ or 1=1 or ‘ ‘=‘ as the username to fake the database into a valid username: string(//user[name/text()='' or 1=1 or ''=''

and password/text()='foobar']/account/text())

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.

LDAP injection tries to get returned user information, or server information returning information in the error using “(“ in this example:

Security Testing/Debugging

From Rich Helton’s October 2010 C# Web Security

Security Testing-FXCop

-CAT.NET-Nunit

-HTMLUnit-Seleniumin

White Box Testing

White-Box testing is testing the system based on the internal perspective of the system.

In this case, this is also known as Static Analysis. These tools can find issues with the source code before

the code is actually executed. 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)

FXCop

CAT.NET rules can can be run in FXCop instead of Visual Studio.

FXCop examines the assemblies and object code and not the source. It can be downloaded as part of the Windows SDK.

NUNIT

White-Box testing is testing the system based on the internal perspective of the system.

See www.nunit.org These tools can find issues with the source code before

the code is actually executed. A list of tools can be found at

http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis

NUNIT

Headless Browser

Headless Browser Automation Can replicate a real world browser. Can automate the test. Provides low-level control over the HTML and HTTP. Reference

http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/

HTMLUnit steps

Download HTMLUnit http://sourceforge.net/projects/htmlunit/

Download IKVM http://sourceforge.net/projects/ikvm/files/

Create the HTMLUnit DLL: Run “ikvmc –out:htmlunit-2.7.dll *.jar”

Include the htmlunit, IKVM.OpenJDK, and nunit dll’s in the external assemblies.

Can automate the test. Provides low-level control over the HTML and HTTP. 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.

HTMLUnit allows a “getPage()” routine to examine the HTML source code. This allows the walking through of “HREF”, images, and others

pieces of the HTML code before executing on the item.

Selenium IDE is another Open Source concept that is a Integrated Development Environment running on top of the FireFox browser as a plugin. This allows a recording of the browser actions that can be played

back execute buttons being pushed and actions inside the browser. Assertions can be executed on the HTML pages itself for checking

specific information. The test itself can be exported into Junit Java code to execute in Java.

HtmlUnit on C#

HtmlUnit on C# (Nunit Test)(Under Construction page)

HtmlUnit on C# (Nunit Test)(Page not found)

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.

Supports load testing. This allows a recording of the browser actions that can be

played back execute buttons being pushed and actions inside the browser.

Assertions can be executed on the HTML pages itself for checking specific information.

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

Does the framework matter?

JWebUnit wraps both HTMLUnit and Selenium so that code can be written for either framework using a unified framwork.

This way code can once in a single framework and executed using multiple HTML frameworks. http://jwebunit.sourceforge.net/

Security Debugging-Logging

-Exceptions-Log4Net

-NLog-Error Pages

Has my system been compromised?

Logging and Error handling is one of the most important concept in Security.

When an incident happens, the first questions are always “How did they get in?” and “What data was compromised?”.

The least favorite answer is usually “No one knows.” 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.

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.

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

}

}

The C# Logger output….

Exception Handling

Exception handling has helped debugging immensely. It allows a programmer to code for anomalies and handle a bizarre behavior.

There are 3 components of handling an exception, and they are the “try”, “catch” and “finally” blocks.

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.

The “catch” block can log the anomaly, stop the program, or process it in a hundred different ways.

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;

try{

// 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);

}finally{

if (myReader != null){

try{

myReader.Close();

}catch (IOException e){

Console.WriteLine("IOException was {0}" + e.Message);}}}}}

Output-> FileNotFoundException was Could not find file ‘C:\IamNotHere.txt'.

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.

http://logging.apache.org/log4net/ 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.

Log4Net supports XML configuration and a text configuration in log4Net.properties.

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

Log4j Console output

Adding an Appender #1

Let’s read the XML Appender from app.config. Change the BasicConfigurator to XmlConfigurator:

Adding an Appender #2

Add app.config for "c:\\Log\\log.txt”:

Adding an Appender Running

Reading "c:\\Log\\log.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.

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 Files\Common Files\Microsoft Shared\DevServer\10.0 .

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.

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.

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)

Send something more generic(based on business input)

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"

defaultRedirect="errors/ErrorPage.aspx"></customErrors>

Custom Errors in ASP.NET

A good resource on the issue is http://www.codeproject.com/KB/aspnet/customerrorsinaspnet.aspx

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)

top related