Tag-Archive for ◊ Security ◊

Author:
Monday, May 20th, 2013

It could happen that you may have authentication and also authorization in your web application.
The authorization could be at page level and you need to enforce that in every page of your web application.

In these kind of scenarios httpmodule could turn out to be very handy. Httpmodule could be made
to behave like an gate keeper who on every request would check with the page being requested if the
request is from valid user or not. Below C# example would make it clear what I am talking about,

//Define interface which every page is required to implement
public interface IAuthorization
{
bool IsPageAccessible();
}

public partial class RequestedPage : Page, IAuthorization
{
public bool IsPageAccessible()
{
//Your authorization check logic goes here
}
}

public class AuthorizerHttpModule : IHttpModule
{
void httpModule_AuthorizeRequest(object sender, EventArgs e)

{

IAuthorization pageToAuthorize = HttpContext.Current.Handler as IAuthorization;

//Enforce authorization to be implemented.
if(pageToAuthorize == null) { //throw exception}

if(!pageToAuthorize.IsPageAccessible()){ //Redirect to unauthorized page}

}

}

Category: .Net, Security | Tags: , ,  | Leave a Comment
Friday, December 17th, 2010

Enterprise library security application block’s Authorization provider can be used to create an effective solution for rule based security implementation in your application code. The security application block can be used to configure an Authorization provider and use this to map task based authorization to complex combination of roles. Later you can use these rules to verify permissions on the current user to perform an action.

In this post, I’ll show a simple implementation of a rule based authorization provider and its uses. The data model used in our sample looks like

model

I have created some SQL scripts to insert data into the relevant tables.

INSERT INTO [dbo].[Role]([Id] ,[Name]) VALUES (NEWID() ,’SuperUser’)

INSERT INTO [dbo].[Role]([Id] ,[Name]) VALUES (NEWID() ,’Guest’)

INSERT INTO [dbo].[Role]([Id] ,[Name]) VALUES (NEWID() ,’NormalUser’)

GO

INSERT INTO [dbo].[User]([Id] ,[FirstName] ,[LastName] ,[Email] ,[Password])

VALUES (NEWID() ,’SuperUserFName’ ,’SuperUserLName’ , ‘SuperUser@Company.com’ , ‘SuperUserPassword’)

INSERT INTO [dbo].[User]([Id] ,[FirstName] ,[LastName] ,[Email] ,[Password])

VALUES (NEWID() ,’GuestFName’ ,’GuestLName’ , ‘Guest@Company.com’ , ‘GuestPassword’)

INSERT INTO [dbo].[User]([Id] ,[FirstName] ,[LastName] ,[Email] ,[Password])

VALUES (NEWID() ,’NormalUserFName’ ,’NormalUserLName’ , ‘NormalUser@Company.com’ , ‘NormalUserPassword’)

INSERT INTO [dbo].[User]([Id] ,[FirstName] ,[LastName] ,[Email] ,[Password])

VALUES (NEWID() ,’ITDeptFName’ ,’ITDeptLName’ , ‘ITDept@Company.com’ , ‘ITDeptPassword’)

GO

DECLARE @SuperUserId uniqueidentifier

DECLARE @SuperRoleId uniqueidentifier

SELECT @SuperUserId = Id FROM [User] WHERE [FirstName] = ‘SuperUserFName’

SELECT @SuperRoleId = Id FROM [Role] WHERE [Name] = ‘SuperUser’

INSERT INTO [dbo].[UserRole]([UserId], [RoleId] ,[Id])

VALUES(@SuperUserId ,@SuperRoleId ,NEWID())

GO

Next we’ll configure rules using the Enterprise Library security application block.

  • Open the App.Config file in the Enterprise Library Configuration editor and select Add Security Sections from the Blocks menu.
  • Add a new Authorization rule provider as shown in the image below.

AddAuthProvider

  • Give an appropriate name and add a new Authorization rule to the provider. In this sample I have used the name as MyBusinessRule
  • We will create two rules (AddProfile and ApproveProfileChanges).

Final

  • For the AddProfile rule add the Rule Expression as R:SuperUser AND R:NormalUser
  • For the ApproveProfile rule the rule expression is R:SuperUser
  • Save and close your config file.
  • The final output looks like

<configSections>

<section name=”securityConfiguration” type=”Microsoft.Practices.EnterpriseLibrary.Security.Configuration.SecuritySettings, Microsoft.Practices.EnterpriseLibrary.Security, Version=5.0.414.0, Culture=neutral, PublicKeyToken=null” requirePermission=”true” />

</configSections>

<securityConfiguration defaultAuthorizationInstance=”MyBusinessRule”>

<authorizationProviders>

<add type=”Microsoft.Practices.EnterpriseLibrary.Security.AuthorizationRuleProvider, Microsoft.Practices.EnterpriseLibrary.Security, Version=5.0.414.0, Culture=neutral, PublicKeyToken=null”

name=”MyBusinessRule”>

<rules>

<add expression=”R:SuperUser” name=”Approve Profile Changes” />

<add expression=”R:SuperUser AND R:NormalUser” name=”Add Profile” />

</rules>

</add>

</authorizationProviders>

</securityConfiguration>

  • In your business layer add references to the following assemblies
    • Microsoft.Practices.EnterpriseLibrary.Common.dll
    • Microsoft.Practices.EnterpriseLibrary.Security.dll
    • Microsoft.Practices.ServiceLocation.dll
  • Create a class RuleAuthorizationManager and add the authorization logic for the user role for a configured rule.

public class RuleAuthorizationManager

{

public static bool IsUserAuthorized(string ruleName)

{

var ruleProvider = EnterpriseLibraryContainer.Current.GetInstance<IAuthorizationProvider>();

return ruleProvider.Authorize(Thread.CurrentPrincipal, ruleName);

}

}

  • In the service class you can use the IsUserAuthorized method to check for permissions.

public void AddRoleToUser(Guid userId, Role role)

{

if(!RuleAuthorizationManager.IsUserAuthorized(RuleNames.AddProfile))

throw new SecurityException(“User not authorized to add profile”);

var repository = new Repository(new UserModelContainer());

var user = repository.GetSingle<User>(u => u.Id == userId);

//Code to add a role to user.

}

Unit tests

[TestMethod()]

[ExpectedException(typeof(SecurityException))]

public void ApproveProfileChanges_should_throw_security_exception_if_user_does_not_have_permission_to_add_profile()

{

UserService target = new UserService();

User user = new Repository(new UserModelContainer()).GetSingle<User>(u => u.FirstName == “GuestFName”);

IIdentity identity = new GenericIdentity(“Guest@Company.com”);

string[] roles = new string[] { “Guest” };

IPrincipal principal = new GenericPrincipal(identity, roles);

Thread.CurrentPrincipal = principal;

target.ApproveProfileChanges(user);

}

Category: .Net | Tags: ,  | 2 Comments
Author:
Monday, November 02nd, 2009

The usual security stuffs PHP developers handle are
1. Encryption / decryption
2. Validating the User with session Login

Since PHP is to develop web applications, the major secjurity issues with web applications are
1. Cross Site Scripting
2. SQL Injection
3. Trusting User Input
4. Check the referrer

These are the 4 major secutity issues we need to handle in our PHP scripts

1. Cross Site Scripting Prevention

Most of the developers won’t validate the incoming data like querystring and post data.As a result this leads to stealing of cookie or redirecting to different site, etc€¦ For eg, A user will post comment in a blog with a code €œNice Post <img src=€http://site.com/images/myimage.gif€ onload=€window.location=’http://mysite.com/’€ />

This results in redirection of site to €œhttp://mysite.com/€, whenever a user visits the blog.

To prevent from XSS attacks in PHP
Check and validate properly all user inputted data that you plan on using and dont allow html or javascript

code to be inserted from form.

you can Use htmlspecialchars() to convert HTML characters into HTML entities

you can use strip_tags() to only allow some tags

2. SQL Injection Prevention
For eg:

<?php

$firstname = €œJulien’); DELETE FROM mytable; INSERT INTO mytable (firstname) VALUES (’hacked€;

$sql = €œINSERT INTO mytable (firstname) VALUES (’$firstname’)€;

//€¦running the $sql query

?>

To Prevent in PHP

i. Use the addslashes() function which will escape both single and double quotes, by adding backslashes before them, to prevent multiple queries from being executed.

ii. Validate the data with the length of the input field. For eg:

<?php

//escape trouble characters
$firstname = addslashes(firstname);

//make sure not longer than expected length
$firstname = substr($firstname, 0, 32);

$sql = €œINSERT INTO mytable (firstname) VALUES (’$firstname’)€;

//€¦run the $sql query

?>

3. Check the referer: Check to make sure that the information being sent to your script is from your website and not from an outside source. While this information can be faked, it’s still a good idea to check.

For eg: If you have a Login form in your website with username and password textbox. There may be some other hacker who can create same type of form and can use form action to your website. To prevent this type of attack, we can get the referer using $_SERVER['HTTP_REFERER'] and validate before processing.

4. Don’t trust user input anytime. Don’t include, require, or otherwise open/delete a file with a filename based on user input, without thoroughly checking it first.

€œThe better way to reduce programming effort with better security is using a good framework to develop the project.

For eg: Symfony, CakePHP, Zend Framework, etc all these frameworks provides good solution for all the major security issues which we face and also you can maintain the standard in your code and deliverables.€