How Deep are your Defenses?

Share this article

So, you have built your secured web application. You have enabled ASP.NET’s handy authentication and authorization features. But have you done enough? No, not at all. What happens if you forget to deploy the web.config controlling access to the application’s administrative folder? Or if an attacker gains access to the box by exploting your database and references your business logic layers? Or if an attacker finds a SQL injection and starts writing directly to the database? In many cases, the short answer is “bad things” oftentimes leading to unemployment.

But it need not be so easy for an attacker. There are a number of tactics one can use to extend security beyond the web interface. Like a good army, you must practice defense in depth in order to protect the application.

As noted above, hardening the surface is easy—ASP.NET provides some very robust and flexible authentication and authorization features. And with version 2.0 it even provides some limited end-to-end solutions in the MembershipProviders and RoleProviders. But that just protects the surface—much like an eggshell, your application is hardish on the outside but very easily penetrable beyond the shell. Rather than relying upon the shell to provide security, you should implement a defense in depth to mitigate any effects of the shell being cracked.

Diving into the Business Logic

Far and away the easiest way to defend the Business Logic Layer is to take advantage of the .NET Framework’s security feature, particularly the PrincipalPermissionAttribute. This attribute can be applied to any class, method, property. If the Principal Permission check fails, a SecurityException will be thrown. For example, lets say you have a Customer object which should not be accessed by an unauthenticated user. You could simply decorate the object with a principal permission like so:


[PrincipalPermission(SecurityAction.Demand, Authenticated=true)]
public class Customer
{
	//code for your customer object.
} 			

Or, lets say you had an application where the requirements state that only administrators should be able to add users to roles. A feature you encapsulated in the AddRole(string) method. You could make certain no user could, say, add themselves to the Admins group, with code like this:


[PrincipalPermission(SecurityAction.Demand, Role="Admins")]
public void AddRole(string role)
{
	//code to add the role
}

In addition to providing an easy way to backstop all security, the IPrincipal interface is very useful for situations such as logging and auditing user actions. Just capture a reference to the principal object where necessary and use the IPrincipal.Identity.Name property to capture just whom is doing what to what.

There is one other massive advantage to using techniques like the above to embed security into your business logic libraries: security becomes much more testable. Testing a web interface is generally a manual job, whereas there are a number of unit testing frameworks available for .NET—such as NUnit or MbUnit—which allow for very quick and easy tests of PrincipalPermissions. All you need do is to replace the System.Threading.Thread.CurrentPrincipal with a properly constructed GenericPrincipal and look for SecurityExceptions as appropriate. And, with NUnit GUI, you can even take a pretty screenshot for the boss to prove it.

Beyond the Business Logic and Into the Data

The final line of defense in most web applications lies in the underlying datastore, typically a RDBMS of some sort. With ASP.NET, more often than not, that data store is a Sql Server. In one of those accidents of history, Sql Server is capable of being very, very secure but oftentimes the floodgates are left open by a combination of administrative and developer error. And, especially with regards to Sql Server 2000, this can lead to very, very bad things. Look at this video [56k beware] for what the combination of a misconfigured Sql Server installation and a poorly-coded website can do for you.

Insofar as securing Sql Server, there are a few basic steps that need to be done on installation. The principal one is to make certain the database is not running in the LOCAL SYSTEM context but rather as a restricted user account. This limits the damage that can be done in worst case scenarios. But this task is oftentimes well beyond the responsibility of the developer and as such cannot quite be relied upon.

From an application development perspective, there are many things that can be done to prevent Sql Injection scenarios from ever taking place in your ASP.NET applications. First and foremost, make sure to restrict your web application’s user accounts. There are absolutely no scenarios where the web application’s user account needs db_owner rights; if it requires full read/write access on all tables, use db_datareader and db_datawriter—though one could argue that all INSERTs/UPDATEs/DELETEs  should take place through stored procedures. But under no circiumstances that I have seen has it been justified to give a web application rights to control access to a database. Nevermind some scenarios where pure developer laziness required the web application run with fully sysadmin rights.

Second, and possibly more important, one should always take advantage of ADO.NET parameters to pass data to the database. For example, this is bad:


public void badSql(SqlConnection conn, string input)
{
	string sql = "SELECT * FROM Beers WHERE Type='{0}'";
	SqlCommand cmd = conn.CreateCommand();
	cmd.CommandText = string.Format(sql, input);
	//execute command
}

And this is how the same method should be coded:


public void goodSql(SqlConnection conn, string input)
{
	string sql = "SELECT * FROM Beers WHERE Type=@Type";
	SqlParameter param = new SqlParameter("@Type", SqlDbType.VarChar);
	param.Value = input;
	DbCommand cmd = conn.CreateCommand();
	cmd.CommandText = sql;
	cmd.Parameters.Add(param);
	//execute command   
}

In addition to defending against Sql Injection, using parameterized statements is easier for your database server to digest and cache.

Finally, there is one more option for defending the database: using separate security contexts for access. For example, I develop many applications that have three front-ends: a public web application, which needs to SELECT a lot and INSERT very rarely. An application to manage the website, which needs full access to the database. And finally a web service application which needs to do a fair amount of both SELECTing and INSERTing, but only in limited ways. In the database server, I assign each application a different role and allow each of them access to the stored procedures and tables which they need. Meaning that, should I leave a data access method exposed which should not be exposed, it will still fail because it cannot access the data store.

Made it this far? First, go and secure your web applications from end to end. Second, remember to kick this post. And last, make sure to check out the handy ASP.NET security resources Scott Guthrie posted (scroll down to the bulleted lists).

Wyatt BarnettWyatt Barnett
View Author
Share this article
Read Next
From Idea to Prototype in Minutes: Claude Sonnet 3.5
From Idea to Prototype in Minutes: Claude Sonnet 3.5
Zain
Essential Plugins for WordPress Developers: Top Picks for 2024
Essential Plugins for WordPress Developers: Top Picks for 2024
SitePoint Sponsors
WebAssembly vs JavaScript: A Comparison
WebAssembly vs JavaScript: A Comparison
Kaan Güner
The Functional Depth of Docker and Docker Compose
The Functional Depth of Docker and Docker Compose
Vultr
How Top HR Agencies Build Trust Through Logo Designs
How Top HR Agencies Build Trust Through Logo Designs
Evan Brown
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
SitePoint Sponsors
10 Artificial Intelligence APIs for Developers
10 Artificial Intelligence APIs for Developers
SitePoint Sponsors
The Ultimate Guide to Navigating SQL Server With SQLCMD
The Ultimate Guide to Navigating SQL Server With SQLCMD
Nisarg Upadhyay
Retrieval-augmented Generation: Revolution or Overpromise?
Retrieval-augmented Generation: Revolution or Overpromise?
Kateryna ReshetiloOlexandr Moklyak
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form