Tuesday, June 28, 2016

Detect Administrator Privileges Within Batch File


I am almost done removing local admin privileges from all our users. This brought up some issues around batch files. Being a member of local admin this stuff will run with an elevation token. While we are migrating to Powershell, we have many batch files doing lots of things that require admin privileges and quite simply batch files can do many tasks simpler then a PS1.

This sample below has separate outcomes if they double click it vs if someone forces elevation by right clicking the BAT or CMD file and selecting 'Run as Administrator'.

Do whatever you want at the top. I use this for documentation and versioning. You can see many of my other blog posts with bits here. you could do this at the top right after '@ECHO OFF' even.

Then we detect if we are running with an elevation token via an IF then loop:
 NET SESSION >nul 2>&1  
 IF %ERRORLEVEL% EQU 0 (  
   GOTO DOSTUFFASADMIN  
   ) else (  
   GOTO NOADMINDETECTED  
   )  

If we are not then it will jump to the FAIL label and tells them to right click it then exits out with error level 1 (error). This can be fed into other workflow scripts etc.

 :NOADMINDETECTED  
 ECHO.  
 ECHO ####### WARNING: ADMINISTRATOR PRIVILEGES REQUIRED #########  
 ECHO This script must be run as administrator to work properly!  
 ECHO If you're seeing this then right click on the shortcut  
 ECHO and select "Run As Administrator".  
 ECHO ##########################################################  
 ECHO.  
 PAUSE  
 EXIT /B 1  

If successful then it jumps to the DOSTUFFASADMIN label to do the meat of the script. While this label is first in the loop I put it AFTER the failure as the main part of the script can be long so lets fail early if needed.

 :DOSTUFFASADMIN<br />  
 mycoolstuff.exe &nbsp;/dothis /dothat  

Obviously change the labels as you see fit.

So what is happening here? the command 'NET SESSION' shows remote sessions and needs to be ran as an admin in order to show output. When executed via an administrator command prompt it exits with ERRORLEVEL 0 so goto the DOSTUFFASADMIN label.


 Microsoft Windows [Version 10.0.10586]  
 (c) 2015 Microsoft Corporation. All rights reserved.  
   
 C:\WINDOWS\system32>net session  
 There are no entries in the list.  
   
 C:\WINDOWS\system32>echo %ERRORLEVEL%  
 0  

Yet if ran with a standard user token it errors out with ERRORLEVEL 2 so it jumps to the NOADMINDETECTED label. We are only looking for a zero as success so anything else will cause a failure.

 Microsoft Windows [Version 10.0.10586]  
 (c) 2015 Microsoft Corporation. All rights reserved.  
   
 C:\Users\Kevin>net session  
 System error 5 has occurred.  
   
 Access is denied.  
   
 C:\Users\Kevin>echo %ERRORLEVEL%  
 2  
   
 C:\Users\Kevin>  

-Kevin

No comments:

Post a Comment