HTTP Header Disclosure

Vulnerability overview/description

Due to unsanitized user input it is possible to inject arbitrary HTTP header values in certain HTTP responses of the Satellite Server. This can be exploited, for example, to perform session fixation and malicious redirection attacks via the Set-Cookie and the Refresh headers. Moreover, the Satellite Server caches these HTTP responses with the injected HTTP header resulting in all further requests to the same resource being served with the poisoned HTTP response, while these objects remain in cache.

Information Disclosure

Information disclosure enables an attacker to gain valuable information about a system. Therefore, always consider what information you are revealing and whether it can be used by a malicious user. The following lists possible information disclosure attacks and provides mitigations for each. 

Message Security and HTTP

If you are using message-level security over an HTTP transport layer, be aware that message-level security does not protect HTTP headers. The only way to protect HTTP headers is to use HTTPS transport instead of HTTP. HTTPS transport causes the entire message, including the HTTP headers, to be encrypted using the Secure Sockets Layer (SSL) protocol.

http://msdn.microsoft.com/en-us/library/aa738441/ 

Environment change

The web application returned information about itself in the HTTP header that could aid an attacker.  Default web server installations often include the vendor and version details of the web application, and possibly further information about scripting services also installed

User Enumeration – Login failure messages shouldn’t give out any information that results in vulnerabilities.

Is it possible to enumerate user account details within the Web application via the logon page?

Where an application requires account details to retrieve other information, it may be possible to enumerate the details based on the error message returned by the application.

In this case it was also possible to determine the state of the user account

Recommendation:

Messages which allow an attacker to enumerate account details should be removed. A generic error message which does not disclose information about account information should be used.

References:

OWASP Testing for user enumeration

https://www.owasp.org/index.php/Testing_for_user_enumeration_(OWASP-AT-002)

Enumeration

  • Enumeration is the first attack on target network, enumeration is the process to gather the information about a target machine by actively connecting to it.
  • Enumeration means to identify the user account, system account and admin account. Enumerating windows active directory to find out these stuffs.
  • Discovering NetBIOS name enumeration with NBTscan.
  • Establishing null sessions and connections. Null sessions tools like Dumpsec, Winfo and Sid2User or more, may used to perform this attack.

The login failure messages can give away too much information and it would be possible to enumerate user details via the log-on page. It reports on whether an account exists/not and if an account is locked out or not etc.

There should ideally be just one generic message that’s of no use to a potential hacker.

– See more at: http://www.ehacking.net/2011/04/scanning-and-enumeration-second-step-of.html#sthash.B3KW4Kcs.dpuf

Other Considerations

You’ll need to log somewhere in your application the actual reasons why the user could not login, this could be that the account is locked, suspened, deleted etc. 

By logging this information a system adminstrator or the like can see why a user could not get access to the application through the login page.

PenTest where to start

I would like to secure up an MVC application, and one way of insuring a secure application is to run through pentesting, Penetration Testing, but what is pentesting?

Wikipedia

A penetration test, occasionally pentest, is a method of evaluating computer and network security by simulating an attack on a computer system or network from external and internal threats. The process involves an active analysis of the system for any potential vulnerabilities that could result from poor or improper system configuration, both known and unknown hardware or software flaws, or operational weaknesses in process or technical countermeasures. This analysis is carried out from the position of a potential attacker and can involve active exploitation of security vulnerabilities.

Pentests should performed be by someone who has no involvement in the application lifecycle process, someone or some group of people who are independent and will try and penetrate the application.  They will uncover security issues through penetration tests which are presented to the system’s owner. Effective penetration tests will couple this information with an accurate assessment of the potential impacts to the application and outline a range of technical and procedural countermeasures to reduce risks.

Penetration tests are valuable for several reasons:

  1. Determining the feasibility of a particular set of attack vectors
  2. Identifying higher-risk vulnerabilities that result from a combination of lower-risk vulnerabilities exploited in a particular sequence
  3. Identifying vulnerabilities that may be difficult or impossible to detect with automated network or application vulnerability scanning software
  4. Assessing the magnitude of potential business and operational impacts of successful attacks
  5. Testing the ability of network defenders to successfully detect and respond to the attacks
  6. Providing evidence to support increased investments in security personnel and technology

In a series of blogs I will be going over everything that I find and document down how to overcome such vulnerabilities.

Elmah or Microsoft Enterprise Library for Exception logging

 

Enterprise Library Logging Application Block

The Enterprise Library Logging Application Block simplifies the implementation of common logging functions. You can use the Logging Application Block to write information to a variety of locations:

 

·         The event log

·         An e-mail message

·         A database

·         A message queue

·         A text file

·         A Windows® Management Instrumentation (WMI) event

·         Custom locations using application block extension points

Features

·         Multiple targets can be configured

·         Enterprise Library Configuration Console available for easy configuration

·         Large number of options to be configured may make it a bit daunting to start with

·         Invasive – requires code change to implement logging

·         Logs all kinds of events/information, not just for error logging

·         Formatters available for formatting the event message

·         Log filters allow filtering of log messages

·         Facilities for WCF integration

 

 

·         It will take you a bit to get up to speed with Enterprise Library – it’s not a 5 second install.

·         There’s a lot of configuration to do in the app.config/web.config file just to make it work. That said, once you understand it, it easier on other projects.

·         You must implement the Logging Block, not just the Exception Handling Block to log the information somewhere (event log, flat file, database, etc.)

·         It’s not just for logging exceptions. For example, you may want to get log events for when a user logs in or logs out of an application.

·         You can use the configuration file to change how logging works depending on the environment (i.e. Log exceptions for Production, log everything for Dev, etc.).

·         It’s not just for web, but for all kinds of applications.

 

 

ELMAH

 

ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.

 

Once ELMAH has been dropped into a running web application and configured appropriately, you get the following facilities without changing a single line of your code:

 

    Logging of nearly all unhandled exceptions.

    A web page to remotely view the entire log of recoded exceptions.

    A web page to remotely view the full details of any one logged exception, including coloured stack traces.

    In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.

    An e-mail notification of each error at the time it occurs.

    An RSS feed of the last 15 errors from the log.

 

Runs using the Apache License (open source)

 

 

Comparison with ELMAH

Feature/s

Logging Application Block

ELMAH

Scope

  • True enterprise level exception handling framework, across layers, tiers, processes and services (in tandem with Exception Handling Application Block)
  • Logs all kinds of events, not just exceptions
  • Lightweight logging framework with extension points for ASP.NET web applications
  • By default logs unhandled exceptions
  • Error signaling allows handled exceptions to be logged
  • No support for non-error messages

Targets supported

  • The event log
  • An e-mail message
  • A database (supports multiple)
  • A message queue
  • A text file
  • A Windows® Management Instrumentation (WMI) event
  • Custom locations using application block extension points
  • Microsoft SQL Server
  • Oracle (OracleErrorLog)
  • SQLite (version 3) database file
  • Microsoft Access (AccessErrorLog)
  • Loose XML files
  • RAM (in-memory)
  • SQL Server Compact Edition
  • MySQL
  • PostgreSQL

Pluggable?

No. Requires careful configuration and implementation in code

Fully pluggable out of the box, requires only configuration for basic features

Configuration

  • XML configuration in the app.config/web.config as applicable
  • Enterprise Library Configuration Console tool available for ease in configuration

XML configuration in the web.config

Intrusiveness

Requires code change for implementation

No code change required for basic features

Extensibility

  • Easily extensible with multiple points for extensibility
  • Easy to extend for log message formatting and contextual information
  • No source code change required
  • Requires change to source code for any kind of extensibility
  • Error message formatting and contextual information addition requires source code changes

Scalability

  • Easily scales for small to medium sized applications
  • Not enough data available for large sized applications

Requires more research

 

Summary

The Logging Application block beats ELMAH hands down in comprehensiveness. It can be used for logging all kinds of messages from all layers of various kinds of applications including ASP.NET, windows forms, WCF services etc. It can also be used for tracing for performance and debugging purposes.

On the other hand ELMAH is a light-weight framework for logging exceptions in ASP.NET applications.

ELMAH is very easy to configure and use. It is fully pluggable. Whereas implementation of the Logging Application block requires careful planning, configuration and is intrusive as it requires changes to code wherever logging is required.

One of the biggest benefits of the Enterprise Library is that it works in tandem with the Exception Handling block to implement a consistent strategy for processing exceptions in all the architectural tiers of an enterprise application including WCF Services.

While ELMAH is perfect for ASP.NET applications, for enterprise applications the Enterprise Library fulfils the comprehensiveness required.

Singleton Pattern the right way

The singleton pattern is used in almost all modern day programming languages, so why do I keep finding it written incorrectly in so many applications, so lets start with the right way

public sealed class SimpleNoLockLazy
    {
        static readonly SimpleNoLockLazy instance = new SimpleNoLockLazy();

        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static SimpleNoLockLazy()
        {
        }

        SimpleNoLockLazy()
        {
        }

        public static SimpleNoLockLazy Instance
        {
            get
            {
                return instance;
            }
        }
    }

So why this implementation?   The reason for using a Singleton is for performance in a multi-threaded environment and this pattern is not only simple, but it is the fastest.  I have attached a benchmark application, which is based on Jon Skeet’s benchmark, but testing using a Parallel processes.

Benchmark.zip (9.98 kb)

I found Jon Skeet’s article very useful

Encrypting Web.config for the website

Security is always high for installation to customer so is it not about time you encripted the connection string in your web.config file?

This is how it looks like before encrypting:

<connectionStrings>
  <add name="Pubs" connectionString="Server=localhost;Integrated Security=True;Database=Pubs"
    providerName="System.Data.SqlClient" />
  <add name="Northwind" connectionString="Server=localhost;Integrated Security=True;Database=Northwind"
    providerName="System.Data.SqlClient" />
</connectionStrings>

We can encrypt any section of your Web.config file on-the-fly and programatically. If you have full access to your Web server, you can encrypt your connection strings with this single command-line located in the in the %windows%\Microsoft.NET\Framework\versionNumber folder:

aspnet_regiis -pe "connectionStrings" -app "/SampleApplication"

Now, the section in your Web.config file will look like this:

<connectionStrings>
  <EncryptedData>
    <CipherData>
      <CipherValue>AQAAANCMndjHoAw...</CipherValue>
    </CipherData>
  </EncryptedData>
</connectionStrings>

If you can’t execute commands in your web server, for example, when using shared hosting, you still can encrypt it programatically:

Configuration config = Configuration.GetWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.Sections["connectionStrings"]; 
section.ProtectSection ("DataProtectionConfigurationProvider"); 
config.Update();

References: Encrypting Web.Config Values in ASP.NET 2.0

Don’t and Do’s in C#

For a while now I have been reviewing developers code and performing code reviews and I have noticed some common mistakes are being repeated time and time again. These are mostly the mistakes, which once you point them, are quite easy to remember. However, if a developer is not aware of them, they can cause many problems with the efficiency and quality of the developed software. So what are these common mistakes and why are they wrong?

String concatenation instead of StringBuilder

String concatenation works in such a way that every time when you add something to a string, a new address in the memory is being allocated. The previous string is copied to a new location with the newly added part. This is inefficient. On the other hand we have StringBuilder which keeps the same position in the memory without performing the copy operation. Thanks to the strings’ appending by means of StringBuilder the process is much more efficient, especially in case of hundreds of append operations.

//Just wrong
List values = new List(){"This ","is ","Sparta ","!"};
string outputValue = string.Empty;
foreach (var value in values)
{
   outputValue += value;
}
//Correct
StringBuilder outputValueBuilder = new StringBuilder();
foreach (var value in values)
{
   outputValueBuilder.Append(value);
}

LINQ – ‘Where’ with ‘First’ instead of FirstOrDefault

A lot of programmers find a certain set of elements by means of ‘Where’ and then return the first occurrence. This is inappropriate, because the ‘First’ method can be also applied with the ‘Where’ condition. What’s more, it shouldn’t be taken for granted that the value will always be found. If “First” is used when no value is found, an exception will be thrown. Thus, it’s better to use FirstOrDefault instead. When using FirstOrDefault, if no value has been found, the default value for this type will be returned and no exception will be thrown.

//Wrong
List numbers = new List(){1,4,5,9,11,15,20,21,25,34,55};
return numbers.Where(x => Fibonacci.IsInFibonacciSequence(x)).First();
/Almost correct
return numbers.First(x => Fibonacci.IsInFibonacciSequence(x));
//Correct
return numbers.FirstOrDefault(x => Fibonacci.IsInFibonacciSequence(x));

Casting by means of ‘(T)’ instead of ‘as (T)’ when possibly not castable

It’s common that software developers use simple ‘(T)’ casting, instead of ‘as (T)’. And usually it doesn’t have any negative influence because casted objects are always castable. Yet, if there is even a very slight probability that an object can be under some circumstances not castable, „as (T)” casting should be used. See Difference Between C# Cast Syntax and the AS Operators for more details.

//Wrong
var woman = (Woman)person;
//Correct
var woman = person as Woman;

Not using mapping for rewriting properties

There are a lot of ready and very powerful C# mappers (e.g. AutoMapper). If a few lines of code are simply connected with rewriting properties, it’s definitely a place for a mapper. Even if some properties aren’t directly copied but some additional logic is performed, using a mapper is still a good choice (mappers enable defining the rules of rewriting properties to a big extend).

Incorrect exceptions re-throwing

C# programmers usually forget that when they throw an exception using „throw ex” they loose the stack trace, how many times have I seen this? It is then considerably harder to debug an application and to achieve appropriate log messages. When simply using „throw” no data is lost and the whole exception together with the stack trace can be easily retrieved.

//So So wrong
try
{
   //some code that can throw exception [...]
}
catch (Exception ex)
{
   //some exception logic [...]
   throw ex;
}
//Correct
try
{
   //some code that can throw exception [...]
}
catch (Exception ex)
{
   //some exception logic [...]
   throw;
}

Not using ‘using’ for objects disposal

Many C# software developers don’t even know that ‘using’ keyword is not only used as a directive for adding namespaces, but also for disposing objects. If you know that a certain object should be disposed after performing some operations, always use the ‘using’ statement to make sure that the object will actually be disposed.

//the below code:
using(SomeDisposableClass someDisposableObject = new SomeDisposableClass())
{
   someDisposableObject.DoTheJob();
}
//does the same as:
SomeDisposableClass someDisposableObject = new SomeDisposableClass();
try
{
   someDisposableObject.DoTheJob();
}
finally
{
   someDisposableObject.Dispose();
}

Using ‘foreach’ instead of ‘for’ for anything else than collections

Remember that if you want to iterate through anything that is not a collection (so through e.g. an array), using the ‘for’ loop is much more efficient than using the ‘foreach’ loop. See Foreach vs For Performance for more details.

Retrieving or saving data to DB in more than 1 call

This is a very common mistake, especially among junior developers and especially when using ORMs like Entity Framework or NHibernate. Every DB call consumes some amount of time and therefore it’s crucial to decrease the amount of DB calls as much as possible. There are many ways to do so:

  • Using fetching (Eager Loading)
  • Enclosing DB operations in transactions
  • In case of a really complex logic, just moving it to the DB by building a stored procedure
With any SQL connections you can always use the SQL Profiler to see what is happening, and it is quite often easy to spot the excessive use of database connections and more so repeated tries of the same routine.
Just a few I know, but the more common mistakes that developer make when programming day to day.

Visual C# and .NET 4.0 samples

I came across some nice C# samples from Microsoft today providing everything from Hello World, to how to use Yield and how to program Attributes.

Official Visual Studio 2010 Samples for C# 4.0

Worth having a look at if you are a beginner or a seasoned programmer.

Language Samples

The C# 4.0-specific samples are called:

  • Named and Optional
  • Office Sample
  • Python Sample
  • Simple Variance.

Here is the complete list of language samples:

  • Anonymous Delegates: Demonstrates the use of unnamed delegates to reduce application complexity.
  • Arrays: Shows how to use arrays.
  • Attributes: Shows how to create custom attribute classes, use them in code, and query them through reflection.
  • Collection Classes: Shows how to make non-generic collection classes that can be used with the foreach statement.
  • COM Interop Part I: Shows how to use C# to interoperate with COM objects.
  • COM Interop Part II: Shows how to a use a C# server together with a C++ COM client.
  • Commandline: Demonstrates simple command-line processing and array indexing.
  • Condiational Methods: Demonstrates conditional methods, which provide a powerful mechanism by which calls to methods can be included or omitted depending on whether a symbol is defined.
  • Delegates: Shows how delegates are declared, mapped to static and instance methods, and combined into multicast delegates.
  • Events: Shows how to declare, invoke, and configure events in C#.
  • Explicit Interface: Demonstrates how to explicitly implement interface members and how to access those members from interface instances.
  • Generics: Shows how to make generic collection classes that can be used with the foreach statement.
  • Hello World: A Hello World application.
  • Indexers Part I: Shows how C# classes can declare indexers to provide array-like access to objects.
  • Indexers Part II: Shows how to implement a class that uses indexed properties. Indexed properties enable you to use a class that represents an array-like collection.
  • Libraries: Shows how to use compiler options to create a DLL from multiple source files; also, how to use the library in other programs
  • Named and Optional (C# 4.0): Demonstrates Named and Optional parameters, an alternative to method overloads
  • Nullable: Demonstrates value types, such as double and bool, that can be set to null
  • Office Sample (C# 4.0): Demonstrates how Dynamic and COM Interop make it easy to call Microsoft Office in C# 4.0
  • OLEDB: Demonstrates how to use a Microsoft Access database from C# by creating a dataset and adding tables to it.
  • Operator Overloading: Shows how user-defined classes can overload operators
  • Partial Types: Demonstrates how classes and structures can be defined in multiple C# source-code files
  • PInvokeShows how to call exported DLL functions from C#
  • Properties: Shows how properties are declared and used; also demonstrates abstract properties
  • Python Sample (C# 4.0): Learn how to call a Python script by using the Dynamic feature in C# 4.0
  • Security: Discusses .NET Framework security and shows two ways to modify security permissions in C#: using permission classes and permission attributes
  • Simple Variance (C# 4.0): See how Covariance and Contravariance are supported in generic interfaces and delegates
  • Structs: Shows how to use structs in C#.
  • Threading: Demonstrates various thread activities such as creating and executing a thread, synchronizing threads, interacting between threads, and using a thread pool
  • Unsafe: Shows how to use unmanaged code (code that uses pointers) in C#
  • User Conversions: Shows how to define conversions to and from user-defined types
  • Versioning: Demonstrates versioning in C# by using the override and new keywords
  • XML Documents: Shows how to document code by using XML
  • Yield: Demonstrates how to use the yield keyword to filter items in a collection

LinqSamples

These samples help you learn LINQ quickly. They also act as a reference and guide for those with existing LINQ experience. A few handy utilities are also included. They are available in the LinqSamples folder.

  • DynamicQuery: Code to create LINQ queries at run time.
  • LinqToNorthwind: A basic example of how to use LINQ To SQL to query a database
  • LinqToXmlDataBinding: Bind LINQ to XML code to WPF controls
  • ObjectDumper: A utility for writing the output from a LINQ query to the screen in text mode
  • PasteXmlAsLinq: A Visual Studio addin that automatically converts XML to LINQ to XML.
  • QueryVisualizer: Allows LINQ to SQL developers to see the SQL for their query, and also to see the results of the query in a grid.
  • Reflector: Use LINQ to right queries against the objects in your code using the Reflection APIs
  • RSS: This sample acts as a tiny web server that aggregates several RSS feeds
  • SampleQueries: This is the most important sample and contains about 500 examples of how to use each of the query operators in LINQ to Objects, LINQ to SQL, LINQ to XML and LINQ to DataSet.
  • SimpleLambdas: Several examples of how to write and use lambda expressions
  • SimpleLinqToObjects: The hello world of the LINQ samples. This shows you how easy it is to do simple queries of in-memory objects using LINQ to Objects.
  • SimpleLinqToXml: Get started using LINQ to XML.
  • WebServiceLinqProvider(TerraService): A custom LINQ provider and client for the TerraServer-USA Web service.
  • Whitepapers: The following papers are stored in this directory in Word format:
    • LINQ Project Overview
    • LINQ to SQL Overview for C# and VB
    • Standard Query Operators
    • LINQ to XML Overview
  • WinFormsDataBinding: Learn how to display LINQ queries with grids in a Windows form. It includes a one to many query example.
  • XQuery: Another simple LINQ to XML sample query. This sample shows the minimal code necessary to write a LINQ to XML query

Workflow with TFS

I’ve been working with TFS for sometime and when you are using the process flows you need to understand how the workflows work with the work items types.

There are two main types I have worked with Agile and CMMI Process Improvements.

I’m not an expert on these workflows but you can get access to the full guidance from:

The diagrams below are taken from VSTS blog site, but you must remember thes eare just starting points and they can be changed to suit your own workflow within your business

MSF for Agile Software Development

featuring 5 work item types: Bug, Requirement, Quality of Service Requirement (QoS), Risk and Task.

Work Item Type: Bug

 

Work Item Type: Scenario


 

Work Item Type: Quality of Service Requirement (also known as “technical requirement”)

 

Work Item Type: Risk

 

Work Item Type: Task

 

MSF for CMMI Process Improvement

featuring 7 work item types: Bug, Requirement, Change Request, Issue, Review, Risk, Task

Work Item Type: Bug

 

Work Item Type: Requirement

 

Work Item Type: Change Request

 

Work Item Type: Issue

 

Work Item Type: Review

 

Work Item Type: Risk

 

Work Item Type: Task

Lifestyles of the Castle Windsor IoC Containers

It’s worth knowing how the Castle Windsor IoC work, by default it uses Singletons, where this will work for the most of the time, there are a lot more options available to you depending on your needs.  These lifestyles that are available in Castle Windsor are:

  • Singleton: components are instantiated once, and shared between all clients
  • Transient: components are created on demand
  • PerWebRequest: components are created once per Http Request
  • Thread: components have a unique instance per thread
  • Pooled: Optimization of transient components that keeps instance in a pool instead of always creating them
  • Custom: allows you to specify a custom lifestyle… you’d have to specify a type that implements the ILifeStyleManager interface

For further information on this take a look at Castle Windsors Lifestyles or  Windsor and component instance lifetimes