Aug 30

Writing Secure Code, Second Edition

Some years ago i worked for a software house with over 30 developers, of which only one other had read the first edition of this book. I don’t think that was uncommon. Few developers cared about application security in general terms, their encounters with security being an inconvenience that either ‘broke’ code or (often post-exploit) resulted in ‘extra work’ bug-fixing. I use the past-tense, but i’ve really no evidence to suggest that things have changed all that much. Hopefully the wider distribution and publicity granted this second edition will help change that.

The book is organised into four major sections.

The first provides background material that outlines the need to secure systems and techniques for designing secure systems. It is carefully written, appropriately illustrated and has only two very small code examples (one of which pseudo-code, the other a couple of lines of asp), making it good for photocopying and distribution to project managers…

The second and third sections provide the bulk of the book – secure coding techniques. As you’d expect buffer overruns, acls, least privilege, crypto, canonical mistakes, sql injection, cross site scripting, dos attacks, to name a few are all covered, and there are chapters on internationalisation, sockets, rpc, and one – surprisingly small – on .net. I say surprisingly because a good part of the marketing for this book was that it was updated to cover .net, which it has – but not to the extent you’d think. If you’re looking for an in-depth analysis of .net security, this work doesn’t have it. But it doesnt needs it – if there is one single message in the second and third sections it is that there is no replacement for responsible, informed programming regardless of the syntax or technology used. The chapter entitled ‘All Input Is Evil’ makes that point well, it – like the others – applies whether you use .net or not.

The final section covers ‘everything else’ – testing, code reviews, installation, error messages, and a good – but brief – chapter on privacy and data security, and an excellent chapter on general good practises.

Part of what made the first edition a classic, to my mind, is that it addressed the security fundamentals *every* programmer on a microsoft platform should be aware of. After reading it i was in doubt of the importance of application security, the core principles, threats and coding countermeasures, and i went on to apply those in subsequent projects. This edition builds, updates and expands on the first and is, simply, required reading. unlike many sequels, it does not disappoint.

  • Share/Bookmark
Aug 02

vs.net naming conventions

The MSDN documentation on .NET standards and best practises is certainly comprehensive, but as a starting point it’s overwhelming. Naming conventions vary from organisation to organisation, and I am never happy committing hundred page, or more, tomes of (often) fiercely protected “standards” to memory.

I much prefer automated ‘code review’ tools which help maintain such standards, e.g. Enterprise Templates, FX Cop and the brilliant Compuware DevPartner Studio. This download is therefore a readily consumable list of the essential .NET naming conventions, good for initial developer orientation, that is (pretty much), industry standard.

  • Share/Bookmark
Aug 01

vs.net and xhtml

after a recent dissapointment with an e-book on xhtml compliance and vs.net, what else can be done to help with standards based dev?

vs.net’s ‘extensibility’ options include a DefaultTargetSchema property for a project which uses a prjTargetSchema enum value, which sort of limits the extensibility to that provided by microsoft: setting this property affects intellisense and compiler errors – though earlier versions of the doco claimed that it would also alter the choice of html controls in the toolbar. prjTargetSchema has only three values which map to three xml schemas installed under \Microsoft Visual Studio .NET\Common7\Packages\schemas\html.

Now, whilst you cant easily add to the prjTargetSchema, and so change settings at a project level, you can at a document level. webforms have a targetSchema property, which allows you to specify a schema for that document. by default you can choose from one of the three that map to prjTargetSchema. but there’s nothing stopping you adding your own, and if you do the IDE will helpfully display it as an option in the designer’s dropdown.

having looked over the three provided i was about to grab the xhtml schema and do a quick xslt to make it vs.net friendly, when i found out that Christoph Schneegans had already done so. top man.

I’ve only made a couple of minor, but i think useful, alterations. Christoph’s page also includes transitional and frameset schema’s too if you’re that way inclined. Now this still doesnt make things right – you’ll still experience vs.net pain and need a good xhtml validator, but it is an improvement. here then is my list of ways to ease the pain a little:

  • change the default webform template – i include an example in the download
  • change the default editor options under Tools|Options – in HHTML/XML to:
    • deselect all ‘Apply Automatic Formatting’ options, select all ‘Automatic Formatting Options’ and ensure that all ‘Capitalisation’ options are set to ‘As entered’
    • select all on the HTML Specific page
  • install the xhtml intellisense schema – included in the download
  • always check your ouptput with a decent validator
  • Share/Bookmark
Jul 11

Improving Web Application Security – Threats and Countermeasures is part of microsoft’s ‘patterns and practises’ group. Though much of the guidance is general best practise, specific guidance is given for .NET web apps. This really is an excellent paper complete with appendices of resource links, checklists and how-to’s. Which is appropriate to what is a very practically focused document, not the idealised theorising that it could so easily have been, and which certain other papers in the series indulge in. Simply put, it is an essential read.

  • Share/Bookmark
Jul 09

standard template 

A recurring theme on many of the projects I’ve worked on recently has been that of document templates. So I’ve decided to put my most commonly used here on the site. A few years ago standard templates became a big issue at the company I worked for – primarily because there wasn’t really any and this was affecting both individual productivity and client’s perceptions of the company. After much debate I persuaded the company to invest in a copy of the SPC’s EssentialSET, which formed the basis for most of the templates used thereafter. The EssentialSet templates are not pretty, but the are excellent in terms of providing a baseline of standards compliance.

The templates I’ll post here have been through so many revisions – over 40 to the base template alone – and have been used and improved on in so many projects – that they bear little resemblance to their originals, so I think its safe to make them public without stepping on anyone’s copyright.

What makes a good template? Apart from being based on standards and having survived numerous encounters with organisations both large and small, i’d say the ability to easily repurpose for the needs of the immediate project – and I think mine do that well. I know that some consulting architects consider templates part of their unique ‘grab-bag’ they take with them to projects, and as a result, guard them jealously. But I take a different view. I can bring these with me to projects, yes, but I think the ability to adapt and implement are more important qualities. I also hope that by publishing my templates I am in some way contributing to the body of knowledge for software architects, and as such I appreciate any feedback.

So, to kick things off – the most important template: the standard on which all others are based…

  • Share/Bookmark
Jul 06

config helper class

VS.NET’s out-of-the-box application configuration capabilities are a huge advance on VS6, but they don’t meet the needs of larger distributed systems. Where there are a number of load balanced or clustered production servers, let alone test and development environments, we ideally want a single point of application configuration – securely storing things such as database connection strings that would be a nightmare to manage in each individual web or app config file.

In a previous project I built a set of ‘common utilities’ that were packaged as a COM+ library; each application server had a proxy to it installed. One of these utilities was a class called XConfig (included in the download) which, essentially, loaded an encrypted xml document from an http stream. It was a wondrously useful little class, and one I miss in the framework. So, on a recent distributed .NET project I had one of the developers make something similar. I obviously won’t post that code here, but I will one that I did.

A common question in designing application configuration in large distributed environments is where to configure the configuration? For instance, if we stored the configuration data in a database, where do we store the connection string to it? There is no single answer to this (apart from ‘it depends’), but in many cases I think DNS is a strong candidate. If the configuration is stored in a file (easy to modify), delivered via HTTP (easy to setup, firewall rule friendly, can be load balanced for resilience), then the only configuration required is its address. This is easily managed by a DNS alias that resolves, say, a VIP. The config class can even have the alias hard-coded into it, since the environment into which it is installed will determine the physical location of the file.

The downside? Well, of all the protocols used in most projects, HTTP is perhaps the most latent, so this form of configuration is not going to be lightning fast. The consumers need to make sure they use it wisely – i.e. load it once and cache it – in asp.net pull the configuration on Application_Start; class libraries have several options, one is to use static variables populated from constructors,
as shown in the following example:

private static string _dbConn = null;public Constructor() {
if (_dbConn == null) loadConfig();
}

private void loadConfig() {
const string ERR_CFG_INVALID = "Configuration Not Loaded";
const string ERR_CFG_NOVALUE = "No config value found for: ";

try {
Config cfg = new Config();
_dbConn = cfg["Connection"];

// if the connect string is blank then, reset the static
// variable to null so that loadConfig will be called again
if ( _dbConn.Trim().Length == 0 ) {
_dbConn = null;
throw new Exception(ERR_CFG_NOVALUE) + "Connection";
}
}

catch (Exception ex) {
throw new Exception(ERR_CFG_INVALID, ex);
}
}

If you have a number of such config values you should probably consider making your own internal class for your project that will load and hold them all. For more info see the documentation which is included in the download.

  • Share/Bookmark
Jul 04

I wasn’t going to do this, but I just can’t resist. Look carefully at the following…


// connect to the events web service
EventAccess eventAccessWS = new EventAccess();
EventSearchResults eventsResult = new EventSearchResults();

// return the results from the events web service
eventsResult = eventAccessWS.GetModifiedItems(updateTimeDate);
ParseXML.setXMLNodeValue(pathToXML,"/Indexer/collections/collection [@name='"+ repositoryToIndex +"']/lastindexed", DateTime.Now.ToString());

// convert the object into a serialized XML file
XmlSerializer serializer = new XmlSerializer(typeof (EventSearchResults));
tempXML = tempFilePath+ "\" + repositoryToIndex + srchTools.getUniqueFilename() + ".xml";
tempFiles.Add(tempXML);
Stream fs = new FileStream(tempXML, FileMode.Create);
XmlWriter writer = new XmlTextWriter(fs, new UTF8Encoding());

// Serialize using the XmlTextWriter
serializer.Serialize(writer, eventsResult);
writer.Close();
fs.Close();
...

This code snippet was part of a commercial .NET project developed by consultants that best remain unnamed. It calls a .NET web service, throws away the perfectly good returned .Net object, re-serializes it, manipulates the Xml directly (using a suite of custom Xml utility objects they built for that purpose), with the local file system standing in for temporary storage. No, really…

  • Share/Bookmark
Jul 04

soap trace helper

On a recent project, we had a number of ‘challenges’ getting our .net web services consumed by a java-based service. In order to even start debugging we needed to know exactly what was being being sent and received on the wire. The consuming application provided easy access to this information, but we needed a way for the .net developers to know this without loading that up or (worse) using a tool like netmon to inspect the network packets directly. Unable to find any immediate way to record this, I provided one using a SoapExtension. Turns out that this MSDN Online link (now) provides an implementation of what I wanted – it would’ve saved a lot of grief.

known issues

  • doesnt work with the autogenerated .net web service testrig (I’ve no idea why not)
  • this is only intended to be used in a development environment – applying the attribute will require a recompile
  • writing to the file system is a privileged operation – you may need to check your local security settings.

Using it is easy enough; adjust the namespace to suit, then simply apply the attribute with an optional path to the log file.

[WebMethod, SoapTrace("d:soap.log")]

  • Share/Bookmark
Jul 01

Hijacking .Net Vol 1: Role Based Security

I had to read this – touted as the first volume in a series that could be for .NET what Appleman’s books were for the Win32 API. A fair bit of the book is just a guided tour of windows role based security, well written though. The core of the ‘hijacking’ part could be boiled down to a couple of pages. Essentially it’s this:

Marking a class or method as private in .NET impacts its visibility, but not its security boundary – i.e. it is possible to invoke private methods. And vs.net provides all the means necessary to do so:

Step One – navigate to the library/class you want with ildasm and have a peek at the IL. From that its pretty straightforward to grok the private objects/methods you might be interested in.

Step Two – use the InvokeMember method of the Type class to make use of private class/method.

That’s it. Classic Win32 API Appleman this is not, how useful the technique is – I’m not sure (not in commercial work), but it’s still worth a read.

  • Share/Bookmark
Jul 01

Enforcing XHTML Compliance in ASP.NET Applications

Having spent the last few years working on government projects where the use of xhtml was required, it was very frustrating for me, and the project teams, that asp.net did not support the standard. You might argue that the asp.net environment is a visual ide where you drop your controls and, as Don Box put it at a conference a couple of years ago “let .net and let go” of the output. Even so, if you want to use asp.net on standards compliant projects – and I certainly do – something has to be done until (or if) vs.net more fully supports xhtml. So I had high hopes for this ‘eBook’.

Alas, it’s way more optimistic than I am about vs.net and xhtml, it doesn’t present real world problems, and whilst it’s true that we can always write our controls to produce xhtml output, it doesnt really address the issue. Has this person ever even run a simple aspx page through a validator? I think not. And writing a filter to ensure that the resulting output is valid xml is missing the point altogether. Finally the ‘eBook’ is really only an article from asptoday – it’s simply not worth the money.

  • Share/Bookmark
preload preload preload