Using BitAnd() for Application Security

From Hal Helms’ article on the subject.

Using the BitAnd function within ColdFusion is a great way to manage the security of parts of your website.

First agree a list of secure features and assign them a number in the range 2 to the power X, ie 0, 1, 2, 4, 8, 16, 32, …

0 = No access
1 = Login access
2 = Add entry
4 = Edit entry
8 = Delete entry

Next assign each user a security clearance value which is the sum of the features you wish them to have access to. For example.

  • A user with just login rights would have a security value of 1 (login = 1).
  • An author would have a value of 3 (login + add = 1 + 2).
  • An editor would have a value of 7 (login + add + edit = 1 + 2 +4).
  • An administrator would have a value of 15 (login + add + edit + delete = 1 + 2 + 4 +8).
  • The Helpdesk could have a value of 9 (login + delete = 1 + 8).

Finally bracket your code with with a CFIF which uses BitAnd to test the security clearance of the logged in user.

<cfif BitAnd(userPermissionLevel, requiredPermissionLevel)>
	<p>You are cleared to edit this entry</p>
	...
	...
<cfelse>
	<p>Sorry, but you don't have the permission to edit an entry.</p>
</cfif>

Where userPermissionLevel = 9 and requiredPermissionLevel = 4. Therefore BitAnd(9, 4) = 0 which is false. Visually, in binary, it looks like this.

2 ^ X  = 1 2 4 8
         -------
     9 = 1 0 0 1
     4 = 0 0 1 0
         -------
BitAnd = 0 0 0 0