Should code contracts be used for security?

Are there any reasons why you would not use Code Contracts to enforce business rules?

Imagine that you have a User class that represents one user of the system and defines actions that can be performed with other users. You can write a ChangePassword method like this ...

 public void ChangePassword(User requestingUser, string newPassword) { Contract.Requires<ArgumentNullException>(requestingUser); Contract.Requires<ArgumentNullException>(newPassword); // Users can always change their own password, but they must be an // administrator to change someone else's. if (requestingUser.UserId != this.UserId && !requestingUser.IsInRole("Administrator")) throw new SecurityException("You don't have permission to do that."); // Change the password. ... } 

Or you can implement a security check as a prerequisite using Contract.Requires ...

 public void ChangePassword(User requestingUser, string newPassword) { Contract.Requires<ArgumentNullException>(requestingUser != null); Contract.Requires<ArgumentNullException>(newPassword != null); // Users can always change their own password, but they must be an // administrator to change someone else's. Contract.Requires<SecurityException>( requestingUser.UserId == this.UserId || !requestingUser.IsInRole("Administrator"), "You don't have permission to do that."); // Change the password. ... } 

What are the advantages and disadvantages of these two methods?

+6
security code-contracts
source share
1 answer

I think the answer is no. Code contracts are designed for scenarios where their failure indicates a serious error in the code . They should not be something that can be restored due to incorrect user input.

Requires<T> intended for use only in public library methods that will be consumed by others who do not use code contracts, or if you have legacy code that should remain compatible in terms of what exceptions it may throw.

For new code, you should use Requires , not Requires<T> . Normal Requires by default Requires fatal exception to force you to deal with this problem.

In addition, if someone disables checking the execution of the contract code, all your security will disappear!

+2
source share

All Articles