Thursday, January 24, 2008

Using caspol.exe to change .NET security policy - done right

Maybe you know CASPOL.exe to modify or add your own security policy for the .NET Framework.

Most examples you will find on the internet will simply add a code group to the configuration and most people use it this way: Upon each installation, CASPOL.EXE is exeucted.

What most people not realize is that CASPOL does not remove the old group when adding a new one with the same name. See this screenshot:

This is no broken installation, for .NET everything is fine even if 100+ groups with the same name would exist. However, for the user this looks like a bug so he will call support. To make things even worse: When you have changed the group membership of your custom group later on you will end up with two groups with completely different membership conditions.

To avoid this, I developed the following batch file that you can use and customize. The basic trick is to first list all available groups and if the script finds one that has the same name, it will be deleted.

For more information about CasPol.exe, see MSDN.

Enjoy!


@echo off
Rem .NET Framework 2.0 CasPol.exe batch by TeX HeX
Rem http://texhex.blogspot.com
Rem Version 1.0

Rem Set this to the name of the group you want to create
SET GROUP=Testing123
Rem Set this to the description your group should have
SET GROUPDESC=Just testing group

SET CASPOL=%WINDIR%\Microsoft.Net\Framework\v2.0.50727\caspol.exe
SET ERRLVL=9

echo ---- Setting prompt off ----
%caspol% -polchgprompt off

Rem Check if this group exists already
echo ---- Check group existence ----
%caspol% -m -ld|find /C /I "%GROUP%"
IF NOT ERRORLEVEL 1 GOTO DELETE_GROUP
GOTO CREATE_GROUP


Rem Deleting old group (two times to make sure that we do not have one left over)
:delete_group
echo ---- Removing old group ----
CASPOL% -m -remgroup "%GROUP%"
CASPOL% -m -remgroup "%GROUP%" >NUL


:create_group
echo ---- Creating group ----
REM %CASPOL% -m -addgroup All_Code -url "\*" -zone MyComputer FullTrust -name "%GROUP%"
REM %CASPOL% -m -addgroup All_Code -strong -file c:\arg.dll -noname -noversion FullTrust -name "%GROUP%" -description "%GROUPDESC%"

%CASPOL% -m -addgroup All_Code -zone MyComputer FullTrust -name "%GROUP%" -description "%GROUPDESC%"
SET ERRLVL=%ERRORLEVEL%

echo Result is %ERRLVL%

Rem Patch prompting again
echo ---- Setting prompt on ----
%caspol% -polchgprompt on



Rem Now check the result
IF %ERRLVL% EQU 0 (
echo "All fine!"
exit 0
) ELSE (
echo "Error!"
exit -1
)




1 comment: