Page 2 of 2 <12
Topic Options
#58155 - 2001-08-12 09:08 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Kdyer Offline
KiX Supporter
*****

Registered: 2001-01-03
Posts: 6241
Loc: Tigard, OR
Shawn,

I will keep digging. However, it does appear that this topic is generating a boat-load of code!!

We'll keep you posted.

BTW, did you get a chance to roll through my first "KIX Port" from WSH?

Thanks!

- Kent

_________________________
Utilize these resources:
UDFs (Full List)
KiXtart FAQ & How to's

Top
#58156 - 2001-08-12 09:41 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Shawn Administrator Offline
Administrator
*****

Registered: 1999-08-13
Posts: 8611
Kent,

No I haven't - I'm @ home working from a
fleabag 9x gameboy without a printer. Will
be testing and looking (printing) it at the
office first thing Monday morning ( the
only way I can understand a script is to
read it on paper )

I want to take a closer look (print) at
DOC's code as well - it's always nice to
study these huge scripts to see how they're
structured and especially how error
handling is performed.

-Shawn

[ 12 August 2001: Message edited by: Shawn ]

Top
#58157 - 2001-08-13 03:51 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Kdyer Offline
KiX Supporter
*****

Registered: 2001-01-03
Posts: 6241
Loc: Tigard, OR
Shawn,

I know the feeling of running on 9x box. I won't even say in public what I am running. eeek! I will be able to test this more thoroughly when I get into work.

Lonkero - have you had a chance to test this?

Oh well - When I get into work, I will be downloading the WMI SDK from Microsoft.
http://msdn.microsoft.com/downloads/default.asp?URL=/code/sample.asp?url=/msdn-files/027/001/566/msdncompositedoc.xml

And the tutorial - http://msdn.microsoft.com/downloads/default.asp?URL=/code/sample.asp?url=/msdn-files/027/001/574/msdncompositedoc.xml

Hopefully, this will get the answer.

Thanks!

- Kent

_________________________
Utilize these resources:
UDFs (Full List)
KiXtart FAQ & How to's

Top
#58158 - 2001-08-13 04:37 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Lonkero Administrator Offline
KiX Master Guru
*****

Registered: 2001-06-05
Posts: 22346
Loc: OK
haven't tested it. and as long as I need to work with that kind of code monster I prefer my old way: RMTSHARE
and if I need to change manually some permissions on share I use the old winfile!!!!!
have you tested that. works on nt 4&5!
_________________________
!

download KiXnet

Top
#58159 - 2001-08-13 11:48 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
NTDOC Administrator Offline
Administrator
*****

Registered: 2000-07-28
Posts: 11624
Loc: CA
Kyder,

I tried your script, but the ADSI component failed to install propely on my Windows 2000 SP2 system. It gave an error about Incorrect INF file syntax in section "CheckForPrevVer"

Sorry, but at this time I can not really check your version out. I need to get another box to try it on.

Top
#58160 - 2001-08-14 10:11 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Shawn Administrator Offline
Administrator
*****

Registered: 1999-08-13
Posts: 8611
Kent,

Ok - I have to admit it - this was painfull to code. It took me about a half day to do it but looking back - it's not so bad ... It's basically ripped from here and there on the web - but I mostly used the WMI SDK and MSDN ...

This script will automatically create an NTFS SHARE and permission it as EVERYONE:FULLCONTROL ... sorry for the lack of comments, etc ... I need a coffee REAL bad ...

It requires Windows 2000 or WindowsNT/9x with retro WMI installed.

Give it a shot ... now to study your script

code:

break on


; SET YOUR SPECIFICS ...


$servername = @wksta
$sharename = "TEMP"
$sharepath = "C:\TEMP"
$sharedescription = "My Temp Share"


dim $aces[1]


$wmi = getobject('winmgmts:{impersonationlevel=impersonate}!//$servername')


$secdesc = $wmi.get("win32_securitydescriptor")
$trustee = $wmi.get("win32_trustee")
$trustee.domain = ""
$trustee.name = "everyone"
$trustee.sid = 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0
$ace = $wmi.get("win32_ace")
$ace.accessmask = 2032127
$ace.aceflags = 3
$ace.acetype = 0
$ace.trustee = $trustee


$aces[0] = $ace
$secdesc.dacl = $aces


$share = $wmi.get("win32_share")
$create = $share.methods_("create")
$inparms = $create.inparameters
$inparms.access = $secdesc
$inparms.description = $sharedescription
$inparms.name = $sharename
$inparms.path = $sharepath
$inparms.type = 0
$share.execmethod_("create",$inparms)


exit


-Shawn

p.s. The new share doesn't auto-refresh in NT explorer. Close re-open explorer or use NET share to check-out !

[ 14 August 2001: Message edited by: Shawn ]

Top
#58161 - 2001-08-15 07:10 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Kdyer Offline
KiX Supporter
*****

Registered: 2001-01-03
Posts: 6241
Loc: Tigard, OR
Shawn,

Well, I looked at my original code and there are still some issues to be worked out like I need to figure out the difference between & and +...

It now creates the share, but the perms are off..

code:

; -- createshare.kix
; -- 08/10/2001
; -- Kent Dyer
; -- Version .8a Release
; The basis of this is using code from - http://cwashington.netreach.net/script_repository/view_scripts.asp?Index=360&S criptType=vbscript
; It requires the ADSI SDK from - http://www.microsoft.com/NTWorkstation/downloads/Other/ADSI25.asp
; You will need to REGSVR32 the ADSSECURITY.DLL from the ADSI SDK
; KIX 4.x - is required for the UDFs (User-Defined Functions) and the use of FOR..EACH, and DIM, and CREATEOBJECT

Break ON
Cls

$kixv = InStr(@KIX, "4.") ; Check to see if KIX 4.x is being used
If $kixv = 0
? "Kix 4.00 is required - Sorry."
Sleep 2
Exit
EndIf

Dim $textusr
Dim $textshare

; Create objects
$ofs = CreateObject("Scripting.FileSystemObject")
$sec = CreateObject("ADsSecurity")

If $sec ; Check to see if ADSSECURITY.DLL is registered

; Capture the name of the person you are working with
COLOR g+/n
? "Enter the userid of the person - jdoe"
COLOR w+/n
?
GETS $textusr

IF $textusr = ""
COLOR r+/n
? "No UserID input provided. Stopping script now."
COLOR w+/n
SLEEP 2
EXIT
ENDIF

; Capture the name of the server are you adding the share to
COLOR g+/n
? "Enter the server - server"
COLOR w+/n

?
GETS $textshare

IF $textshare = ""
COLOR r+/n
? "No Server Name input provided. Stopping script now."
COLOR w+/n
SLEEP 2
EXIT
ENDIF

; Setting the user$ variable - jdoe$ - Hidden shares don't show when browsing to a server
$textsharen = $textusr & Chr(36)

; Path for user folders
$usershare = "\\" + $textshare + "\users"

; Now let;s create a variable to work with - \\SERVER\users\jdoe
; Directory to save
$userdir = "\\"+ $textshare + "\users\" + $textusr

; Create folder
;If Not $ofs.FolderExists($userdir) Then $ofs.CreateFolder $userdir
$createfolder = Exist($userdir)
IF $createfolder <> 1
MD $userdir
ENDIF

; Create share
$fservobj = GetObject("WinNT://"+ $textshare +"/lanmanserver")

; Create the share for the server jdoe$
$newshare = $fservobj.create("fileshare",$textsharen)
; Set the path for the share on the server - D:\Users
$newshare.path = "D:\Users\" & $textusr
$newshare.setinfo
$newshare = Nothing

; Set ACLs

$filenm = $userdir
$permspart = "add(" & $textusr & ":c)+add(domain admins:F)+add(Administrators:F)+del(everyone:F)"

;-- Replace ACL on single file or folder-------
$chkfile=$ofs.fileexists($filenm) ; make sure file exists

IF $chkfile=true
; changeacls $filenm, $permspart, "REPLACE", "FILE"
;ELSE
$chkfolder=$ofs.folderexists($filenm) ; if its not a file, is it a folder?
IF chkfolder=true
$changeacls $filenm, $permspart, "REPLACE", "FOLDER"
ENDIF
ENDIF

$ofs=nothing

FUNCTION ChangeAcls($file,$perms,$redit,$ffolder)
;- Edit ACLS of specified file -----
Const ADS_ACETYPE_ACCESS_ALLOWED = 0
Const ADS_ACETYPE_ACCESS_DENIED = 1
Const ADS_ACEFLAG_INHERIT_ACE = 2
Const ADS_ACEFLAG_SUB_NEW = 9

$sd = GetSecurityDescriptor("FILE://"+$file+")"
$dacl = $sd.discretionaryacl

;if flagged Replace then remove all existing aces from dacl first
IF ucase($redit)="REPLACE"
FOR EACH $existingace IN $dacl
$dacl.removeace $existingace
NEXT
ENDIF

;break up Perms into individual actions
$cmdarray=split($perms,"+")

FOR x=0 TO ubound($cmdarray)
$tmpvar1=$cmdarray(x)
IF ucase(left($tmpvar1,3))="DEL"
$aclaction="DEL"
ELSE
$aclaction="ADD"
ENDIF

$tmpcmdvar=left($tmpvar1,len($tmpvar1)-1)
$tmpcmdvar=right($tmpcmdvar,len($tmpcmdvar)-4)
$cmdparts=split($tmpcmdvar,":")
$namevar=$cmdparts(0)
$rightvar=$cmdparts(1)

; if flagged edit, delete ACE;s belonging to user about to add an ace for

IF ucase($redit)="EDIT"
FOR EACH $existingAce IN $dacl
$trusteevar=$existingAce.trustee
IF instr(trusteeVar,"\")
$trunamevar=right($trusteevar,len($trusteevar)-instr($trusteevar,"\"))
ELSE
$trunamevar=$trusteevar
ENDIF

$uctrunamevar=ucase($trunamevar)
$ucnamevar=ucase($namevar)

IF $uctrunamevar=$ucnamevar
$dacl.removeace $existingace
ENDIF
NEXT
ENDIF

; if action is to del ace then following clause skips addace
IF $aclaction="ADD"
IF ucase($ffolder)="FOLDER"
; folders require 2 aces for user (to do with inheritance)
addace $dacl, $namevar, $rightvar, ADS_ACETYPE_ACCESS_ALLOWED, ADS_ACEFLAG_SUB_NEW
addace $dacl, $namevar, $rightvar, ADS_ACETYPE_ACCESS_ALLOWED, ADS_ACEFLAG_INHERIT_ACE
ELSE
addace $dacl, $namevar, $rightvar, ADS_ACETYPE_ACCESS_ALLOWED,0
ENDIF
ENDIF
NEXT

FOR EACH $ace IN $dacl
; for some reason if ace includes "NT AUTHORITY" then existing ace does not get readded to dacl

IF instr(ucase($ace.trustee),"NT AUTHORITY\")
$newtrustee=right($ace.trustee, len($ace.trustee)-instr($ace.trustee, "\"))
$ace.trustee=newtrustee
ENDIF
NEXT

; final sets and cleanup
$sd.discretionaryacl = $dacl
$sec.setsecuritydescriptor $sd

$sd=nothing
$dacl=nothing
$sec=nothing
ENDFUNCTION

FUNCTION addace($dacl, $trustee, $maskvar, $acetype, $aceflags)
; add ace to the specified dacl
Const RIGHT_READ = &H80000000
Const RIGHT_EXECUTE = &H20000000
Const RIGHT_WRITE = &H40000000
Const RIGHT_DELETE = &H10000
Const RIGHT_FULL = &H10000000
Const RIGHT_CHANGE_PERMS = &H40000
Const RIGHT_TAKE_OWNERSHIP = &H80000

$ace = CreateObject("AccessControlEntry")
$ace.trustee = $trustee

SELECT
CASE
ucase($maskvar)
; specified rights so far only include FC & R. Could be expanded though
CASE
"F"
$ace.accessmask = RIGHT_FULL
CASE
"C"
$ace.accessmask = RIGHT_READ OR RIGHT_WRITE OR RIGHT_EXECUTE OR RIGHT_DELETE
CASE
"R"
$ace.accessmask = RIGHT_READ OR RIGHT_EXECUTE
ENDSELECT

$ace.acetype = $acetype
$ace.aceflags = $aceflags
$dacl.addace $ace
$ace=nothing
ENDFUNCTION
ELSE
COLOR r+/n
?"ADsSecurity not installed on this machine"
COLOR w+/n
SLEEP 2
EXIT
ENDIF

EXIT


Oh well..

- Kent

[ 15 August 2001: Message edited by: kdyer ]

[ 15 August 2001: Message edited by: kdyer ]

_________________________
Utilize these resources:
UDFs (Full List)
KiXtart FAQ & How to's

Top
#58162 - 2001-08-15 08:14 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Shawn Administrator Offline
Administrator
*****

Registered: 1999-08-13
Posts: 8611
Kent,

Downloading ...

Converting (opps... bad conversion ... bad bulletin board... bad, naughty bulletin board) ...

Printing ....

Studying ...

Question ...

In this function ...

FUNCTION ChangeAcls($file,$perms,$redit,$ffolder)

...what is this line all about ...

$sd = GetSecurityDescriptor("FILE://"+$file+")"


~Shawn

Top
#58163 - 2001-08-16 12:15 AM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Kdyer Offline
KiX Supporter
*****

Registered: 2001-01-03
Posts: 6241
Loc: Tigard, OR
Shawn,

The line has to do with the Port-over from VBS.

In VBS, it is -

code:

$sd = GetSecurityDescriptor("FILE://"+$file+")"

Converting it to KIX, it should be -

code:

$sd = $sec.GetSecurityDescriptor("FILE://"+$file+")"

Thanks for catching that one..

I have done some more cleanup and it appears that I was missing some strings....

code:

; -- createshare.kix
; -- 08/15/2001
; -- Kent Dyer
; -- Version .8a Release
; The basis of this is using code from - http://cwashington.netreach.net/script_repository/view_scripts.asp?Index=360&ScriptType=vbscript
; It requires the ADSI SDK from - http://www.microsoft.com/NTWorkstation/downloads/Other/ADSI25.asp
; You will need to REGSVR32 the ADSSECURITY.DLL from the ADSI SDK
; KIX 4.x - is required for the UDFs (User-Defined Functions) and the use of FOR..EACH, and DIM, and CREATEOBJECT

Break ON
Cls

$kixv = InStr(@KIX, "4.") ; Check to see if KIX 4.x is being used
If $kixv = 0
? "Kix 4.00 is required - Sorry."
Sleep 2
Exit
EndIf

Dim $textusr
Dim $textshare

; Create objects
$ofs = CreateObject("Scripting.FileSystemObject")
$sec = CreateObject("ADsSecurity")

If $sec ; Check to see if ADSSECURITY.DLL is registered

; Capture the name of the person you are working with
COLOR g+/n
? "Enter the userid of the person - jdoe"
COLOR w+/n
?
GETS $textusr

IF $textusr = ""
COLOR r+/n
? "No UserID input provided. Stopping script now."
COLOR w+/n
SLEEP 2
EXIT
ENDIF

; Capture the name of the server are you adding the share to
COLOR g+/n
? "Enter the server - server"
COLOR w+/n

?
GETS $textshare

IF $textshare = ""
COLOR r+/n
? "No Server Name input provided. Stopping script now."
COLOR w+/n
SLEEP 2
EXIT
ENDIF

; Setting the user$ variable - jdoe$ - Hidden shares don't show when browsing to a server
$textsharen = $textusr + Chr(36)

; Path for user folders
$usershare = "\\" + $textshare + "\users"

; Now let;s create a variable to work with - \\SERVER\users\jdoe
; Directory to save
$userdir = "\\"+ $textshare + "\users\" + $textusr

; Create folder
;If Not $ofs.FolderExists($userdir) Then $ofs.CreateFolder $userdir
$createfolder = Exist($userdir)
IF $createfolder <> 1
MD $userdir
ENDIF

; Create share
$fservobj = GetObject("WinNT://"+ $textshare +"/lanmanserver")

; Create the share for the server jdoe$
$newshare = $fservobj.create("fileshare",$textsharen)
; Set the path for the share on the server - D:\Users
$newshare.path = "D:\Users\" + $textusr
$newshare.setinfo
$newshare = Nothing

; Set ACLs

$filenm = $userdir
$permspart = "add(" + $textusr + ":c)+add(domain admins:F)+add(Administrators:F)+del(everyone:F)"

;-- Replace ACL on single file or folder-------
$chkfile=$ofs.fileexists($filenm) ; make sure file exists

IF $chkfile=true
; changeacls $filenm, $permspart, "REPLACE", "FILE"
;ELSE
$chkfolder=$ofs.folderexists($filenm) ; if its not a file, is it a folder?
IF $chkfolder=true
$changeacls $filenm, $permspart, "REPLACE", "FOLDER"
ENDIF
ENDIF

$ofs=nothing

FUNCTION ChangeAcls($file,$perms,$redit,$ffolder)
;- Edit ACLS of specified file -----
Const ADS_ACETYPE_ACCESS_ALLOWED = 0
Const ADS_ACETYPE_ACCESS_DENIED = 1
Const ADS_ACEFLAG_INHERIT_ACE = 2
Const ADS_ACEFLAG_SUB_NEW = 9

$sd = $sec.GetSecurityDescriptor("FILE://"+$file+")"
$dacl = $sd.discretionaryacl

;if flagged Replace then remove all existing aces from dacl first
IF ucase($redit)="REPLACE"
FOR EACH $existingace IN $dacl
$dacl.removeace $existingace
NEXT
ENDIF

;break up Perms into individual actions
$cmdarray=split($perms,"+")

FOR x=0 TO ubound($cmdarray)
$tmpvar1=$cmdarray(x)
IF ucase(left($tmpvar1,3))="DEL"
$aclaction="DEL"
ELSE
$aclaction="ADD"
ENDIF

$tmpcmdvar=left($tmpvar1,len($tmpvar1)-1)
$tmpcmdvar=right($tmpcmdvar,len($tmpcmdvar)-4)
$cmdparts=split($tmpcmdvar,":")
$namevar=$cmdparts(0)
$rightvar=$cmdparts(1)

; if flagged edit, delete ACE;s belonging to user about to add an ace for

IF ucase($redit)="EDIT"
FOR EACH $existingAce IN $dacl
$trusteevar=$existingAce.trustee
IF instr($trusteeVar,"\")
$trunamevar=right($trusteevar,len($trusteevar)-instr($trusteevar,"\"))
ELSE
$trunamevar=$trusteevar
ENDIF

$uctrunamevar=ucase($trunamevar)
$ucnamevar=ucase($namevar)

IF $uctrunamevar=$ucnamevar
$dacl.removeace $existingace
ENDIF
NEXT
ENDIF

; if action is to del ace then following clause skips addace
IF $aclaction="ADD"
IF ucase($ffolder)="FOLDER"
; folders require 2 aces for user (to do with inheritance)
addace $dacl, $namevar, $rightvar, ADS_ACETYPE_ACCESS_ALLOWED, ADS_ACEFLAG_SUB_NEW
addace $dacl, $namevar, $rightvar, ADS_ACETYPE_ACCESS_ALLOWED, ADS_ACEFLAG_INHERIT_ACE
ELSE
addace $dacl, $namevar, $rightvar, ADS_ACETYPE_ACCESS_ALLOWED,0
ENDIF
ENDIF
NEXT

FOR EACH $ace IN $dacl
; for some reason if ace includes "NT AUTHORITY" then existing ace does not get readded to dacl

IF instr(ucase($ace.trustee),"NT AUTHORITY\")
$newtrustee=right($ace.trustee, len($ace.trustee)-instr($ace.trustee, "\"))
$ace.trustee=newtrustee
ENDIF
NEXT

; final sets and cleanup
$sd.discretionaryacl = $dacl
$sec.setsecuritydescriptor $sd

$sd=nothing
$dacl=nothing
$sec=nothing
ENDFUNCTION

FUNCTION addace($dacl, $trustee, $maskvar, $acetype, $aceflags)
; add ace to the specified dacl
Const RIGHT_READ = &H80000000
Const RIGHT_EXECUTE = &H20000000
Const RIGHT_WRITE = &H40000000
Const RIGHT_DELETE = &H10000
Const RIGHT_FULL = &H10000000
Const RIGHT_CHANGE_PERMS = &H40000
Const RIGHT_TAKE_OWNERSHIP = &H80000

$ace = CreateObject("AccessControlEntry")
$ace.trustee = $trustee

SELECT
CASE
ucase($maskvar)
; specified rights so far only include FC & R. Could be expanded though
CASE
"F"
$ace.accessmask = RIGHT_FULL
CASE
"C"
$ace.accessmask = RIGHT_READ OR RIGHT_WRITE OR RIGHT_EXECUTE OR RIGHT_DELETE
CASE
"R"
$ace.accessmask = RIGHT_READ OR RIGHT_EXECUTE
ENDSELECT

$ace.acetype = $acetype
$ace.aceflags = $aceflags
$dacl.addace $ace
$ace=nothing
ENDFUNCTION
ELSE
COLOR r+/n
?"ADsSecurity not installed on this machine"
COLOR w+/n
SLEEP 2
EXIT
ENDIF

EXIT


So, it appears to create the share now, but does not apply perms...

- Kent

_________________________
Utilize these resources:
UDFs (Full List)
KiXtart FAQ & How to's

Top
#58164 - 2002-02-21 12:05 AM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Alex.H Offline
Seasoned Scripter

Registered: 2001-04-10
Posts: 406
Loc: France
i'm bringing this one from deep hole.
Dunno how i caught this thread, but i found some stuff.

Kent,
ignore the following line if you alreay manage to correct the script.

should'nt it be :
Const RIGHT_READ = &80000000
Const RIGHT_EXECUTE = &20000000
Const RIGHT_WRITE = &40000000
Const RIGHT_DELETE = &10000
Const RIGHT_FULL = &10000000
Const RIGHT_CHANGE_PERMS = &40000
Const RIGHT_TAKE_OWNERSHIP = &80000

in your addace function ?


also, if this call is working ?
addace $dacl, $namevar, $rightvar, ADS_ACETYPE_ACCESS_ALLOWED, ADS_ACEFLAG_SUB_NEW

It always seems to me that any calls in kixtart should be done in this way :
addace ($dacl, $namevar, $rightvar, ADS_ACETYPE_ACCESS_ALLOWED, ADS_ACEFLAG_SUB_NEW )
whatever the function return a value or not

_________________________
? getobject(Kixtart.org.Signature)

Top
#58165 - 2002-02-20 03:35 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Kdyer Offline
KiX Supporter
*****

Registered: 2001-01-03
Posts: 6241
Loc: Tigard, OR
Alex,

Thanks for the insight. I know that Shawn and I played badminton with this one for quite a spell. This was about the time I started going over to http://cwashington.netreach.net and "stealing" code!!!

Thanks again!

- Kent

_________________________
Utilize these resources:
UDFs (Full List)
KiXtart FAQ & How to's

Top
#58166 - 2002-05-31 04:52 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Anonymous
Unregistered


Hey guys! I recently used the XCACLS command to give "USERS" Full access to a folder on their Windows 2000 workstations.

Run this from a command line:
code:
\\server\share\xcacls.exe c:\targetfolder /P USERS:F /E /Y /C /T

The permissions get set perfect everytime, however, if you right click on any of the files in the folder, select properties, and click on the SECURITY tab, you get the following error message:
quote:
The permissions on "file" are incorrectly ordered, which may cause some entries to be ineffective. Press OK to continue and sort the permissions correctly, or Cancel to reset the permissions.
This does not cause any permissions problems because I used /T "Recursively walk through the current directory and all its subdirectories, applying the chosen access rights to the matching files or directories".

If you elect not to use /T the ACE added to the directory is also an inherit ACE for new files created in this directory. But, since 'The permissions on "directory" are incorrectly ordered', the file permissions are not correctly inherited.

So, the question here is "How do you use XCACLS to set file/folder permissions and correctly sort their order?

Top
#58167 - 2002-05-31 09:59 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Kdyer Offline
KiX Supporter
*****

Registered: 2001-01-03
Posts: 6241
Loc: Tigard, OR
3MGrant5,

The thing is that is cool about this thread is all you need is to register a DLL and do all of this in code. However, if you want to do this with XCACLS.EXE, try this script:

http://cwashington.netreach.net/depo/view.asp?Index=355&ScriptType=kixtart

HTH,

- Kent
_________________________
Utilize these resources:
UDFs (Full List)
KiXtart FAQ & How to's

Top
#58168 - 2002-08-06 02:26 AM Re: OFF TOPIC - Shawn can you review a WSH script for me?
NTDOC Administrator Offline
Administrator
*****

Registered: 2000-07-28
Posts: 11624
Loc: CA
Here is some VB script code that replaces the XCACLS.EXE file. I posted this a while back, but the search engine here on the board was not able to find it so... I'm reposting it. Requires WSH 5.6

My HATS OFF to anyone that successfully converts this to KiXtart code. [Cool]

code:
'***********************************************************************************
'*
'* File: XCACLS.VBS
'* Created: April 18, 2001
'* Last Modified: August 31, 2001
'* Version: 1.8
'*
'* Main Function: List/Change ACLS for files and directories
'*
'*
'* Copyright (C) 2001 Microsoft Corporation
'*
'* Written by David B.
'*
'***********************************************************************************

OPTION EXPLICIT

'********************************************************************
'* Declare main variables
'********************************************************************

Dim intOpMode, blnQuiet, strOutputFile, objOutputFile, debug_on
Dim a_Used, t_Used, e_Used, g_Used, r_used
Dim p_Used, d_used, i_used, o_used, filename_var
Dim l_Used, q_Used, debug_Used, strDefaultDomain, strSystemDomainSid, strSystemDomainName, intPermUpdateCount
Dim g_var_User(), ObjTrustee_g_var_User(), g_Var_Perm(), g_Var_Spec()
dim r_Var_User(), ObjTrustee_r_var_User()
Dim p_var_User(), ObjTrustee_p_var_User(), p_Var_Perm(), p_Var_Spec()
Dim d_Var_User(), ObjTrustee_d_var_User(), d_Var_Perm(), d_Var_Spec()
ReDim g_var_User(0), ObjTrustee_g_var_User(0), g_Var_Perm(0), g_Var_Spec(0)
Redim r_Var_User(0), ObjTrustee_r_var_User(0)
ReDim p_var_User(0), ObjTrustee_p_var_User(0), p_Var_Perm(0), p_Var_Spec(0)
ReDim d_Var_User(0), ObjTrustee_d_var_User(0), d_Var_Perm(0), d_Var_Spec(0)
Dim i_Var, o_Var
Dim fso, InitialfilenameAbsPath, QryBaseNameHasWildcards, QryExtensionHasWildcards
Dim objService, objLocalService, objLocator
Dim strRemoteServerName, strRemoteShareName, strRemoteUserName, strRemotePassword
Dim RemoteServer_Used, RemoteUserName_Used
Dim DisplayDirPath, ActualDirPath

'This const value is for any use referenced without a domain, if this is TRUE, we will use the local machine name
'for the domain if its a non-dc. For DC's we will always use the Domain name unless you specify the actual domain to use.
'If this is FALSE, we will default to the Domain name.

CONST CONST_USE_LOCAL_FOR_NON_DCs = TRUE

'These are specific to this Script
CONST CONST_SHOW_USAGE = 3
CONST CONST_PROCEED = 4
CONST CONST_ERROR = 1

'When working with NTFS Security, we use constants that match the API documentation
'********************* ControlFlags *********************
CONST ALLOW_INHERIT = 33796 'Used in ControlFlag to turn on Inheritance
'Same as:
'SE_SELF_RELATIVE + SE_DACL_AUTO_INHERITED + SE_DACL_PRESENT
CONST DENY_INHERIT = 37892 'Used in ControlFlag to turn off Inheritance
'Same as:
'SE_SELF_RELATIVE + SE_DACL_PROTECTED + SE_DACL_AUTO_INHERITED + SE_DACL_PRESENT
Const SE_OWNER_DEFAULTED = 1 'A default mechanism, rather than the the original provider of the security
'descriptor, provided the security descriptor's owner security identifier (SID).

Const SE_GROUP_DEFAULTED = 2 'A default mechanism, rather than the the original provider of the security
'descriptor, provided the security descriptor's group SID.

Const SE_DACL_PRESENT = 4 'Indicates a security descriptor that has a DACL. If this flag is not set,
'or if this flag is set and the DACL is NULL, the security descriptor allows
'full access to everyone.

Const SE_DACL_DEFAULTED = 8 'Indicates a security descriptor with a default DACL. For example, if an
'object's creator does not specify a DACL, the object receives the default
'DACL from the creator's access token. This flag can affect how the system
'treats the DACL, with respect to ACE inheritance. The system ignores this
'flag if the SE_DACL_PRESENT flag is not set.

Const SE_SACL_PRESENT = 16 'Indicates a security descriptor that has a SACL.

Const SE_SACL_DEFAULTED = 32 'A default mechanism, rather than the the original provider of the security
'descriptor, provided the SACL. This flag can affect how the system treats
'the SACL, with respect to ACE inheritance. The system ignores this flag if
'the SE_SACL_PRESENT flag is not set.

Const SE_DACL_AUTO_INHERIT_REQ = 256 'Requests that the provider for the object protected by the security descriptor
'automatically propagate the DACL to existing child objects. If the provider
'supports automatic inheritance, it propagates the DACL to any existing child
'objects, and sets the SE_DACL_AUTO_INHERITED bit in the security descriptors
'of the object and its child objects.

Const SE_SACL_AUTO_INHERIT_REQ = 512 'Requests that the provider for the object protected by the security descriptor
'automatically propagate the SACL to existing child objects. If the provider
'supports automatic inheritance, it propagates the SACL to any existing child
'objects, and sets the SE_SACL_AUTO_INHERITED bit in the security descriptors of
'the object and its child objects.

Const SE_DACL_AUTO_INHERITED = 1024 'Windows 2000 only. Indicates a security descriptor in which the DACL is set up
'to support automatic propagation of inheritable ACEs to existing child objects.
'The system sets this bit when it performs the automatic inheritance algorithm
'for the object and its existing child objects. This bit is not set in security
'descriptors for Windows NT versions 4.0 and earlier, which do not support
'automatic propagation of inheritable ACEs.

Const SE_SACL_AUTO_INHERITED = 2048 'Windows 2000: Indicates a security descriptor in which the SACL is set up to
'support automatic propagation of inheritable ACEs to existing child objects.
'The system sets this bit when it performs the automatic inheritance algorithm
'for the object and its existing child objects. This bit is not set in security
'descriptors for Windows NT versions 4.0 and earlier, which do not support automatic
'propagation of inheritable ACEs.

Const SE_DACL_PROTECTED = 4096 'Windows 2000: Prevents the DACL of the security descriptor from being modified
'by inheritable ACEs.

Const SE_SACL_PROTECTED = 8192 'Windows 2000: Prevents the SACL of the security descriptor from being modified
'by inheritable ACEs.

Const SE_SELF_RELATIVE = 32768 'Indicates a security descriptor in self-relative format with all the security
'information in a contiguous block of memory. If this flag is not set, the security
'descriptor is in absolute format. For more information, see Absolute and
'Self-Relative Security Descriptors in the Platform SDK topic Low-Level Access-Control.

'********************* ACE Flags *********************
CONST OBJECT_INHERIT_ACE = 1 'Noncontainer child objects inherit the ACE as an effective ACE. For child
'objects that are containers, the ACE is inherited as an inherit-only ACE
'unless the NO_PROPAGATE_INHERIT_ACE bit flag is also set.

CONST CONTAINER_INHERIT_ACE = 2 'Child objects that are containers, such as directories, inherit the ACE
'as an effective ACE. The inherited ACE is inheritable unless the
'NO_PROPAGATE_INHERIT_ACE bit flag is also set.

CONST NO_PROPAGATE_INHERIT_ACE = 4 'If the ACE is inherited by a child object, the system clears the
'OBJECT_INHERIT_ACE and CONTAINER_INHERIT_ACE flags in the inherited ACE.
'This prevents the ACE from being inherited by subsequent generations of objects.

CONST INHERIT_ONLY_ACE = 8 'Indicates an inherit-only ACE which does not control access to the object
'to which it is attached. If this flag is not set, the ACE is an effective
'ACE which controls access to the object to which it is attached. Both
'effective and inherit-only ACEs can be inherited depending on the state of
'the other inheritance flags.

CONST INHERITED_ACE = 16 'Windows NT 5.0 and later, Indicates that the ACE was inherited. The system sets
'this bit when it propagates an inherited ACE to a child object.

CONST ACEFLAG_VALID_INHERIT_FLAGS = 31 'Indicates whether the inherit flags are valid.


'Two special flags that pertain only to ACEs that are contained in a SACL are listed below.

CONST SUCCESSFUL_ACCESS_ACE_FLAG = 64 'Used with system-audit ACEs in a SACL to generate audit messages for successful
'access attempts.

CONST FAILED_ACCESS_ACE_FLAG = 128 'Used with system-audit ACEs in a SACL to generate audit messages for failed
'access attempts.

'********************* ACE Types *********************
CONST ACCESS_ALLOWED_ACE_TYPE = 0 'Used with Win32_Ace AceTypes
CONST ACCESS_DENIED_ACE_TYPE = 1 'Used with Win32_Ace AceTypes
CONST AUDIT_ACE_TYPE = 2 'Used with Win32_Ace AceTypes


'********************* Access Masks *********************

Dim Perms_LStr, Perms_SStr, Perms_Const
'Permission LongNames
Perms_LStr=Array("Synchronize" , _
"Take Ownership" , _
"Change Permissions" , _
"Read Permissions" , _
"Delete" , _
"Write Attributes" , _
"Read Attributes" , _
"Delete Subfolders and Files" , _
"Traverse Folder / Execute File", _
"Write Extended Attributes" , _
"Read Extended Attributes" , _
"Create Folders / Append Data" , _
"Create Files / Write Data" , _
"List Folder / Read Data" )
'Permission Single Character codes
Perms_SStr=Array("" , _
"D" , _
"C" , _
"B" , _
"A" , _
"9" , _
"8" , _
"7" , _
"6" , _
"5" , _
"4" , _
"3" , _
"2" , _
"1" )
'Permission Integer
Perms_Const=Array(1048576 , _
&H80000 , _
&H40000 , _
&H20000 , _
&H10000 , _
&H100 , _
&H80 , _
&H40 , _
&H20 , _
&H10 , _
&H8 , _
&H4 , _
&H2 , _
&H1 )


'Initializing Default values
a_Used = FALSE
t_Used = FALSE
e_Used = FALSE
g_Used = FALSE
r_used = FALSE
p_Used = FALSE
d_used = FALSE
i_used = FALSE
l_Used = FALSE
q_Used = FALSE
RemoteServer_Used = FALSE
strRemoteServerName = ""
strRemoteShareName = ""
RemoteUserName_Used = FALSE
strRemoteUserName = ""
strRemotePassword = ""
debug_Used = FALSE 'Parameter Passed
filename_var = ""
DisplayDirPath = ""
ActualDirPath = ""

debug_on = FALSE 'Actual value checked in script
blnQuiet = FALSE
strOutputFile = "XCACLS.Log"

'Parse the command line
intOpMode = intParseCmdLine()
If Err.Number Then
Wscript.Echo "Error while parsing the command line."
Wscript.Echo "Error " & Err.Number & ": " & Err.Description
WScript.Quit
End if

'Open the output file so we can use it through out the script
If l_Used then Call OpenOutputFile()

Call PrintMsg("Starting Script at " & now)

'FSO is used in several funcitons, so lets set it globally.
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
If blnErrorOccurred(" occurred in getting FileSystemObject.") Then WScript.Quit

'Put statements in loop to be able to drop out and clear variables
Do
If debug_on then Call PrintMsg("Main: Enter")

Call PrintArguments() 'Show the arguments entered

'Now lets do the work based upon the arguments entered.
Select Case intOpMode
Case CONST_SHOW_USAGE
Call ShowUsage()
Case CONST_PROCEED
strRemoteServerName = ""
'Lets get the objService object which is used throughout the script

If Not SetMainVars(filename_var) then Exit Do

Call PrintMsg("")
Call CheckTrustees()

If QryBaseNameHasWildcards or QryExtensionHasWildcards then
If debug_on then Call PrintMsg("Wildcard characters detected in """ & InitialfilenameAbsPath & """")
Select Case DoesPathNameExist(fso.GetParentFolderName(InitialfilenameAbsPath))
Case 1 'Directory
Call DoTheWorkOnEverythingUnderDirectory(fso.GetParentFolderName(InitialfilenameAbsPath))
Case Else
Call PrintMsg("Error: Directory """ & fso.GetParentFolderName(InitialfilenameAbsPath) & """ not found.")
End select
Else
If debug_on then Call PrintMsg("No Wildcard characters detected for """ & filename_var & """")
'If a folder is found with the same name, then we work it as a folder and include files under it.
Select Case DoesPathNameExist(InitialfilenameAbsPath)
Case 1 'Directory
If a_used then
Call DoTheWorkOnEverythingUnderDirectory(InitialfilenameAbsPath)
Else
Call DoTheWorkOnThisItem(InitialfilenameAbsPath, TRUE)
End if
Case 2 'File
Call DoTheWorkOnThisItem(InitialfilenameAbsPath, FALSE)
Case Else
Call PrintMsg("Error: File/Directory """ & InitialfilenameAbsPath & """ not found.")
End select
End if
Case Else
Call PrintMsg("")
Call PrintMsg(intOpMode)
End Select

Call blnErrorOccurred(" occurred while in the main routine of the script.")
If debug_on then Call PrintMsg("Main: Exit")

Exit Do 'We really didn't want to loop
Loop
'ClearObjects that could be set and aren't needed now
Set objService = Nothing
Set objLocalService = Nothing
Set objLocator = Nothing
Call ClearObjectArray(ObjTrustee_g_var_User)
Call ClearObjectArray(ObjTrustee_r_var_User)
Call ClearObjectArray(ObjTrustee_p_var_User)
Call ClearObjectArray(ObjTrustee_d_var_User)

Call PrintMsg("")
Call PrintMsg("Ending Script at " & now)
Call PrintMsg("")
Call PrintMsg("")
If l_Used then
If strOutputFile <> "" Then
objOutputFile.Close
End if
End if

'********************************************************************
'* End of Main Script
'********************************************************************


'********************************************************************
'*
'* Sub DoTheWorkOnEverythingUnderDirectory()
'* Purpose: Work on Directory path passed to it, and pass paths to DoTheWorkOnThisItem sub
'* Input: ThisPath - Path to directory
'* Output: None
'* Notes: This sub will process every file and folder under the directory passed to it.
'*
'********************************************************************

Sub DoTheWorkOnEverythingUnderDirectory(ThisPath)

ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("DoTheWorkOnEverythingUnderDirectory: Enter")

Dim objFileSystemSet, objPath, objFileSystemSet2, objPath2, strQuery, strTempPath, booltempItsAFolder
Do
If debug_on then Call PrintMsg("DoTheWorkOnEverythingUnderDirectory: Directory passed: """ & ThisPath & """")

'We already checked for existance so we will assume it exists.


strQuery = "Select * from Cim_LogicalFile Where Name='" & Replace(ThisPath,"\","\\") & "'"
Set objFileSystemSet = objService.ExecQuery(strQuery,,0)
If blnErrorOccurred(" occurred setting objFileSystemSet = objService.ExecQuery(" & strQuery & ",,0).") Then Exit Do

strTempPath = ""
for each objPath in objFileSystemSet
If objPath.Drive <> "" then
strTempPath = objPath.Path & objPath.FileName & "\"
strTempPath = Replace(strTempPath, "\\", "\")
Exit For
End if
next

strQuery = "Select * from Cim_LogicalFile Where Path='" & Replace(strTempPath,"\","\\") & "'"
Set objFileSystemSet2 = objService.ExecQuery(strQuery,,0)
If blnErrorOccurred(" occurred setting objFileSystemSet2 = objService.ExecQuery(" & strQuery & ",,0).") Then Exit Do

for each objPath2 in objFileSystemSet2
strTempPath = ""
booltempItsAFolder = False
If objPath2.Drive <> "" then
If UCASE(objPath2.FileType) = "FILE FOLDER" then booltempItsAFolder = True
strTempPath = objPath2.Name
If QryBaseNameHasWildcards Or QryExtensionHasWildcards then
If DoesItMatch(strTempPath) then
Call DoTheWorkOnThisItem(strTempPath, booltempItsAFolder)
End if
Else
'If there are no wildcards, then we are here because a /T was used or initial filename was a directory, so we do all files.
Call DoTheWorkOnThisItem(strTempPath, booltempItsAFolder)
End if
If booltempItsAFolder then
If t_Used then 'We should pass the same check to all sub folders
Call DoTheWorkOnEverythingUnderDirectory(strTempPath)
End if
End if
End if
next

Exit Do 'We really didn't want to loop
Loop
'ClearObjects that could be set and aren't needed now
Set objPath = Nothing
Set objFileSystemSet = Nothing
Set objPath2 = Nothing
Set objFileSystemSet2 = Nothing

Call blnErrorOccurred(" occurred while in the DoTheWorkOnEverythingUnderDirectory routine.")
If debug_on then Call PrintMsg("DoTheWorkOnEverythingUnderDirectory: Exit")
End Sub

'********************************************************************
'*
'* Sub DoTheWorkOnThisItem()
'* Purpose: Work on File/Folder passed to it, and pass to Work routine
'* Input: ABSPath - Path to File/Folder
'* Output: TRUE if Successful, FALSE if not
'*
'********************************************************************

Sub DoTheWorkOnThisItem(AbsPath, IsItAFolder)

ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("DoTheWorkOnThisItem: Enter")

Dim DisplayIt

Do
DisplayIt = TRUE

Call PrintMsg("")
Call PrintMsg("**************************************************************************")
If IsItAFolder then
Call PrintMsg("Directory: " & DisplayPathString(AbsPath))
Else
Call PrintMsg("File: " & DisplayPathString(AbsPath))
End if
'We already checked for existance so we will assume it exists.
If g_Used or r_Used or p_Used or d_Used or o_used or i_used then
Call SetACLForObject(AbsPath, IsItAFolder)
DisplayIt = FALSE
End If
If DisplayIt then
Call DisplayThisACL(AbsPath)
End if
Call PrintMsg("**************************************************************************")
If t_used then Call DoTheWorkOnEverythingUnderDirectory(AbsPath)
Exit Do
Loop

Call blnErrorOccurred(" occurred while in the DoTheWorkOnThisItem routine.")
If debug_on then Call PrintMsg("DoTheWorkOnThisItem: Exit")

End Sub

'********************************************************************
'*
'* Sub DisplayThisACL()
'* Purpose: Shows ACL's that are applied to strPath
'* Input: strPath - string containing path of file or folder, ShowLong - If TRUE, permissions are in long form
'* Output: prints the acls
'*
'********************************************************************

Sub DisplayThisACL(strPath)

ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("DisplayThisACL: Enter")

Dim objFileSecSetting, objOutParams, objSecDescriptor, objOwner, objDACL_Member
Dim objtrustee, numAceFlags, strAceFlags, x, strAceType, numControlFlags
ReDim arraystrACLS(0)

'Put statements in loop to be able to drop out and clear variables
Do
set objFileSecSetting = objService.Get("Win32_LogicalFileSecuritySetting.Path='" & strPath & "'")
If blnErrorOccurred(" occurred setting Win32_LogicalFileSecuritySetting object.") Then Exit Do

Set objOutParams = objFileSecSetting.ExecMethod_("GetSecurityDescriptor")
If blnErrorOccurred(" occurred when this command was issued: GetSecurityDescriptor.") Then Exit Do

set objSecDescriptor = objOutParams.Descriptor
If blnErrorOccurred(" occurred setting objSecDescriptor = objOutParams.Descriptor.") Then Exit Do

numControlFlags = objSecDescriptor.ControlFlags

If IsArray(objSecDescriptor.DACL) then
Call PrintMsg("")
Call PrintMsg("Permissions:")
Call PrintMsg( strPackString("Type", 9, 1, TRUE) & strPackString("Username", 24, 1, TRUE) & strPackString("Permissions", 22, 1, TRUE) & strPackString("Inheritance", 22, 1, TRUE))
For Each objDACL_Member in objSecDescriptor.DACL
Select Case objDACL_Member.AceType
Case ACCESS_ALLOWED_ACE_TYPE
strAceType = "Allowed"
Case ACCESS_DENIED_ACE_TYPE
strAceType = "Denied"
Case else
strAceType = "Unknown"
End select
Set objtrustee = objDACL_Member.Trustee
numAceFlags = objDACL_Member.AceFlags
strAceFlags = StringAceFlag(numAceFlags, numControlFlags, SE_DACL_AUTO_INHERITED, FALSE)
Call AddStringToArray(arraystrACLS, strPackString(strAceType, 9, 1, TRUE) & strPackString(objtrustee.Domain & "\" & objtrustee.Name, 24, 1, TRUE) & strPackString(SECString(objDACL_Member.AccessMask,TRUE), 22, 1, TRUE) & strPackString(strAceFlags, 22, 1, TRUE),-1)
Set objtrustee = Nothing
Next
For x = LBound(arraystrACLS) to UBound(arraystrACLS)
Call PrintMsg(arraystrACLS(x))
Next
Else
Call PrintMsg("")
Call PrintMsg("No Permissions set")
End if
ReDim arraystrACLS(0)
If IsArray(objSecDescriptor.SACL) then
Call PrintMsg("")
Call PrintMsg("Auditing:")
Call PrintMsg(strPackString("Type", 9, 1, TRUE) & strPackString("Username", 24, 1, TRUE) & strPackString("Access", 22, 1, TRUE) & strPackString("Inheritance", 22, 1, TRUE))
For Each objDACL_Member in objSecDescriptor.SACL
Set objtrustee = objDACL_Member.Trustee
numAceFlags = objDACL_Member.AceFlags
strAceType = StringSACLAceFlag(numAceFlags)
strAceFlags = StringAceFlag(numAceFlags, numControlFlags, SE_SACL_AUTO_INHERITED, FALSE)
Call AddStringToArray(arraystrACLS, strPackString(strAceType, 9, 1, TRUE) & strPackString(objtrustee.Domain & "\" & objtrustee.Name, 24, 1, TRUE) & strPackString(SECString(objDACL_Member.AccessMask,TRUE), 22, 1, TRUE) & strPackString(strAceFlags, 22, 1, TRUE),-1)
Set objtrustee = Nothing
Next
For x = LBound(arraystrACLS) to UBound(arraystrACLS)
Call PrintMsg(arraystrACLS(x))
Next
Else
Call PrintMsg("")
Call PrintMsg("No Auditing set")
End if

Set objOwner = objSecDescriptor.Owner
If blnErrorOccurred(" occurred setting objOwner = objSecDescriptor.Owner.") Then Exit Do
Call PrintMsg("")
Call PrintMsg("Owner: " & objOwner.Domain & "\" & objOwner.Name)

Exit Do 'We really didn't want to loop
Loop
'ClearObjects that could be set and aren't needed now
Set objOwner = Nothing
Set objSecDescriptor = Nothing
Set objDACL_Member = Nothing
Set objtrustee = Nothing
Set objOutParams = Nothing
Set objFileSecSetting = Nothing

Call blnErrorOccurred(" occurred while in the DisplayThisACL routine.")
If debug_on then Call PrintMsg("DisplayThisACL: Exit")

End Sub

'********************************************************************
'*
'* Sub SetACLForObject()
'* Purpose: Set the ACL for the file/folder passed
'* Input: strPath - string containing path of file or folder, IsItAFolder,
'* Output: None
'*
'********************************************************************

Sub SetACLForObject(strPath, IsItAFolder)
ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("SetACLForObject: Enter")

Dim objFileSecSetting, objmethod, objSecDescriptor
Dim objtrustee, objInParam, objOutParams, objOwner
Dim objParentFileSecSetting, objParentOutParams, objParentSecDescriptor

Dim OldAceObj, ObjNewAce, NewobjDescriptor, RetVal, i_Var_Copy_Temp
Dim BlankDaclObj, OldDaclObj(), NewDaclObj(), ImpDenyDaclObj()
Dim ImpAllowDaclObj(), ImpDenyObjectDaclObj()

Dim objTempTrustee, i, t, ThisUserAccess, RightsToGive, NewRights
Dim intTempAccessMask, boolDoTheUpdate
Dim strOldAccount, strThisAccount, NewArraySize, NewArrayMember, BoolDoThisOne
Dim ControlFlagsVar, BoolAllowInherited, BoolGetInherited, BoolInitialInheritRightsPresent, numControlFlags

'Put statements in loop to be able to drop out and clear variables
Do

'Initialize all of the new ACL objects
ReDim OldDaclObj(0)
ReDim NewDaclObj(0)
ReDim ImpDenyDaclObj(0)
ReDim ImpAllowDaclObj(0)
ReDim InheritedObjectDaclObj(0)
ReDim BlankDaclObj(0)
BoolAllowInherited = FALSE
BoolGetInherited = FALSE
BoolInitialInheritRightsPresent = FALSE

If debug_on then Call PrintMsg("SetACLForObject: Working on """ & strPath & """")

set objFileSecSetting = objService.Get("Win32_LogicalFileSecuritySetting.Path='" & strPath & "'")
If blnErrorOccurred(" occurred setting Win32_LogicalFileSecuritySetting object.") Then Exit Do

Set objOutParams = objFileSecSetting.ExecMethod_("GetSecurityDescriptor")
If blnErrorOccurred(" occurred Setting objOutParams = objFileSecSetting.ExecMethod_(""GetSecurityDescriptor"")") Then Exit Do

set objSecDescriptor = objOutParams.Descriptor
If blnErrorOccurred(" occurred setting objSecDescriptor = objOutParams.Descriptor.") Then Exit Do

Set objOwner = objSecDescriptor.Owner
If blnErrorOccurred(" occurred setting objOwner = objSecDescriptor.Owner.") Then Exit Do

numControlFlags = objSecDescriptor.ControlFlags

If debug_on then Call PrintMsg("SetACLForObject: Getting DACL array")

Call GetDaclArray(OldDaclObj,objSecDescriptor, FALSE)
If blnErrorOccurred(" occurred after Calling GetDaclArray(OldDaclObj,objSecDescriptor, FALSE)") Then Exit Do

If UBound(OldDaclObj) = 0 then
'If the array is empty and we need to Copy or Enable Inheritance, we need to set Inheritance and get array again.
If i_used then
If i_var < 3 then BoolGetInherited = TRUE
End if
Else
'If Copy or Enable Inheritance is set and there was no Inherited Properties, we need to set Inheritance and get array again.
If i_used then
If i_var < 3 then BoolGetInherited = TRUE
For i = 1 to UBound(OldDaclObj)
If blnErrorOccurred(" occurred looping through OldDaclObj.") Then Exit Do
Set OldAceObj = OldDaclObj(i)
If StringAceFlag(OldAceObj.AceFlags, numControlFlags, SE_DACL_AUTO_INHERITED, TRUE) = "Inherited" then
BoolInitialInheritRightsPresent = TRUE
BoolGetInherited = FALSE
Exit For
End if
Next
End if
End if
If BoolGetInherited Then 'We need the inherited ACE's so lets get them.

If debug_on then Call PrintMsg("SetACLForObject: Inherited ACL's not found and needed, getting from Parent Directory")

'Any existing ACE's will remain in array
Set NewobjDescriptor = objService.Get("Win32_SecurityDescriptor").Spawninstance_
If blnErrorOccurred(" occurred Setting NewobjDescriptor = objService.Get(""Win32_SecurityDescriptor"").Spawninstance_") Then Exit Do

NewobjDescriptor.ControlFlags = ALLOW_INHERIT
If blnErrorOccurred(" occurred setting objSecDescriptor.ControlFlags = ALLOW_INHERIT") Then Exit Do

Set objmethod = objFileSecSetting.Methods_("SetSecurityDescriptor")
If blnErrorOccurred(" occurred setting objmethod = objFileSecSetting.Methods_(""SetSecurityDescriptor"")") Then Exit Do

Set objInParam = objmethod.inParameters.SpawnInstance_()
If blnErrorOccurred(" occurred Setting objInParam = objmethod.inParameters.SpawnInstance_()") Then Exit Do

objInParam.Properties_.item("Descriptor") = NewobjDescriptor
If blnErrorOccurred(" occurred setting objInParam.Properties_.item(""Descriptor"") = NewobjDescriptor") Then Exit Do

Set RetVal = objFileSecSetting.ExecMethod_("SetSecurityDescriptor", objInParam)
If blnErrorOccurred(" occurred setting RetVal = objFileSecSetting.ExecMethod_(""SetSecurityDescriptor"", objInParam)") Then Exit Do

'Now we need to get only the Inherited ACE's (Everyone group may be set if DACL array was empty)
Set objOutParams = objFileSecSetting.ExecMethod_("GetSecurityDescriptor")
If blnErrorOccurred(" occurred Setting objOutParams = objFileSecSetting.ExecMethod_(""GetSecurityDescriptor"")") Then Exit Do

set objSecDescriptor = objOutParams.Descriptor
If blnErrorOccurred(" occurred setting objSecDescriptor = objOutParams.Descriptor.") Then Exit Do

Call GetDaclArray(OldDaclObj,objSecDescriptor, TRUE)
If blnErrorOccurred(" occurred when Calling GetDaclArray(OldDaclObj,objSecDescriptor, TRUE)") Then Exit Do

Set NewobjDescriptor = Nothing
Set objmethod = Nothing
Set objInParam = Nothing
Set RetVal = Nothing
boolDoTheUpdate = TRUE
End if
'Now we have the inherited rights, if one of the revoked users is in the list, then we need to copy the list and turn off inheritance.
If debug_on then Call PrintMsg("SetACLForObject: Looking for Revoke users in Inherited list, if found, Inherited list will be copied to Effective list and inheritance turned off, so we can revoke user")
i_Var_Copy_Temp = FALSE
If r_Used then 'Revoke user if present in Inherited Allowed or Denied lists
If UBound(OldDaclObj) > 0 then
For i = 1 to UBound(OldDaclObj)
If blnErrorOccurred(" occurred looping through OldDaclObj.") Then Exit Do
Set OldAceObj = OldDaclObj(i)
If StringAceFlag(OldAceObj.AceFlags, numControlFlags, SE_DACL_AUTO_INHERITED, TRUE) = "Inherited" then
For t = LBound(r_var_User) to UBound(r_var_User)
If r_Var_User(t) <> "" then
If TrusteesMatch(ObjTrustee_r_var_User(t), OldAceObj.Trustee) then
'We found a match
i_Var_Copy_Temp = TRUE
Call PrintMsg(" - One of the Revoked Users is listed under Inherited permissions.")
Call PrintMsg(" Copying Inherited Permissions and turning off inheritance.")
Exit For
End if
End if
Next
End if
Next
End If
End If

If debug_on then Call PrintMsg("SetACLForObject: Sorting DACL array and modifying rights if needed")

If UBound(OldDaclObj) > 0 then
For i = 1 to UBound(OldDaclObj)
BoolDoThisOne = TRUE
If blnErrorOccurred(" occurred looping through OldDaclObj.") Then Exit Do
Set OldAceObj = OldDaclObj(i)
Set objTempTrustee = OldAceObj.Trustee

intTempAccessMask = OldAceObj.AccessMask
If debug_on then Call PrintMsg("SetACLForObject: """ & TrusteesDisplay(objTempTrustee) & """ current rights = " & SECString(OldAceObj.AccessMask,TRUE))
If StringAceFlag(OldAceObj.AceFlags, numControlFlags, SE_DACL_AUTO_INHERITED, TRUE) = "Inherited" then
If i_Var_Copy_Temp then 'This makes sure that inherited users that are revoked can be revoked...
OldAceObj.AceFlags = OBJECT_INHERIT_ACE + CONTAINER_INHERIT_ACE
Else
BoolDoThisOne = FALSE
If i_used then 'We should make them effective ACL's
Select Case i_var
Case 1 'Inherit
Call AddObjectToArray(InheritedObjectDaclObj, OldAceObj, -1)
Case 2 'Copy to Effective
OldAceObj.AceFlags = OBJECT_INHERIT_ACE + CONTAINER_INHERIT_ACE
BoolDoThisOne = TRUE
End Select
Else
Call AddObjectToArray(InheritedObjectDaclObj, OldAceObj, -1)
End If
End if
End if
If p_Used then 'Replace user rights if present
For t = LBound(p_var_User) to UBound(p_var_User)
If p_Var_User(t) <> "" then
If TrusteesMatch(ObjTrustee_p_var_User(t), objTempTrustee) then
'We found a match so skip it.
BoolDoThisOne = FALSE
Call PrintMsg("Replacing rights for existing user """ & p_Var_User(t) & """")
End if
End if
Next
Else

End If
If r_Used then 'Revoke user if present in Allowed or Denied lists
For t = LBound(r_var_User) to UBound(r_var_User)
If r_Var_User(t) <> "" then
If TrusteesMatch(ObjTrustee_r_var_User(t), objTempTrustee) then
'We found a match so skip it.
BoolDoThisOne = FALSE
Call PrintMsg("Revoking rights for existing user """ & r_Var_User(t) & """")
End if
End if
Next
End if
If BoolDoThisOne then
Select Case OldAceObj.AceType
Case ACCESS_ALLOWED_ACE_TYPE
Call AddObjectToArray(ImpAllowDaclObj, OldAceObj, -1)
Case ACCESS_DENIED_ACE_TYPE
Call AddObjectToArray(ImpDenyDaclObj, OldAceObj, -1)
Case Else
Call PrintMsg("Error: Bad ace...." & Hex(OldAceObj.AceType))
End Select
End if
Next
End If
'Add ACE's that need to be added:

If g_Used then 'Grant rights for these users

If debug_on then Call PrintMsg("SetACLForObject: Granting Rights for Users (that haven't been granted already)")

Call AccessMask_New(ImpAllowDaclObj, ObjTrustee_g_var_User, g_var_User, g_var_Perm, ACCESS_ALLOWED_ACE_TYPE, INHERIT_ONLY_ACE + OBJECT_INHERIT_ACE, "Granting")
If blnErrorOccurred(" occurred when Building Granted (File) Rights array") Then Exit Do

If IsItAFolder then
Call AccessMask_New(ImpAllowDaclObj, ObjTrustee_g_var_User, g_var_User, g_var_Spec, ACCESS_ALLOWED_ACE_TYPE, CONTAINER_INHERIT_ACE, "Granting")
If blnErrorOccurred(" occurred when Building Granted (Folder) Rights array") Then Exit Do
End if

End if
If p_Used then 'Grant rights for these users (Replace rights)

If debug_on then Call PrintMsg("SetACLForObject: Replacing Rights for Users (that haven't been granted already)")

Call AccessMask_New(ImpAllowDaclObj, ObjTrustee_p_var_User, p_var_User, p_var_Perm, ACCESS_ALLOWED_ACE_TYPE, INHERIT_ONLY_ACE + OBJECT_INHERIT_ACE , "Replacing")
If blnErrorOccurred(" occurred when Building Replace (File) Rights array") Then Exit Do

If IsItAFolder then
Call AccessMask_New(ImpAllowDaclObj, ObjTrustee_p_var_User, p_var_User, p_var_Spec, ACCESS_ALLOWED_ACE_TYPE, CONTAINER_INHERIT_ACE, "Replacing")
If blnErrorOccurred(" occurred when Building Replace (Folder) Rights array") Then Exit Do
End if

End if

If d_Used then 'Deny rights for these users

If debug_on then Call PrintMsg("SetACLForObject: Denying Rights for Users (that haven't been denied already)")

Call AccessMask_New(ImpDenyDaclObj, ObjTrustee_d_var_User, d_var_User, d_var_Perm, ACCESS_DENIED_ACE_TYPE, INHERIT_ONLY_ACE + OBJECT_INHERIT_ACE , "Denying")
If blnErrorOccurred(" occurred when Building Denied (File) Rights array") Then Exit Do

If IsItAFolder then
Call AccessMask_New(ImpDenyDaclObj, ObjTrustee_d_var_User, d_var_User, d_var_Spec, ACCESS_DENIED_ACE_TYPE, CONTAINER_INHERIT_ACE, "Denying")
If blnErrorOccurred(" occurred when Building Denied (Folder) Rights array") Then Exit Do
End if

End if

' Combine the ACEs in the proper order
' Implicit Deny
' Implicit Allow
' Inherited Aces

If debug_on then Call PrintMsg("SetACLForObject: Forming new DACL array")

boolDoTheUpdate = FALSE
ReDim NewDaclObj(0)
If UBound(ImpDenyDaclObj) > 0 then '0 member is always blank
For i = (LBound(ImpDenyDaclObj) + 1) to UBound(ImpDenyDaclObj)
boolDoTheUpdate = TRUE
Call AddObjectToArray(NewDaclObj, ImpDenyDaclObj(i), 0)
Next
If blnErrorOccurred(" occurred when Building Implicit Deny array") Then Exit Do
End if
If UBound(ImpAllowDaclObj) > 0 then
For i = (LBound(ImpAllowDaclObj) + 1) to UBound(ImpAllowDaclObj)
boolDoTheUpdate = TRUE
Call AddObjectToArray(NewDaclObj, ImpAllowDaclObj(i), 0)
Next
If blnErrorOccurred(" occurred when Building Implicit Allow array") Then Exit Do
End if
If UBound(InheritedObjectDaclObj) > 0 then
BoolAllowInherited = TRUE
For i = (LBound(InheritedObjectDaclObj) + 1) to UBound(InheritedObjectDaclObj)
boolDoTheUpdate = TRUE
InheritedObjectDaclObj(i).AccessMask = 0
Call AddObjectToArray(NewDaclObj, InheritedObjectDaclObj(i), 0)
Next
If blnErrorOccurred(" occurred when Building Inherited Object array") Then Exit Do
End if
If Not boolDoTheUpdate Then
Set NewDaclObj(0) = CreateObject("AccessControlEntry")
If blnErrorOccurred(" occurred Setting NewDaclObj(0) = CreateObject(""AccessControlEntry"").") Then Exit Do
End if

If i_Var_Copy_Temp then
If debug_on then Call PrintMsg("SetACLForObject: Inheritance turned off because one of the inherited users is revoked on this object.")
ControlFlagsVar = SE_DACL_PRESENT
Else
If i_used then
Select Case i_var
Case 1
ControlFlagsVar = ALLOW_INHERIT
Case 3
ControlFlagsVar = DENY_INHERIT
case Else '2 and non matching
ControlFlagsVar = SE_DACL_PRESENT
End Select
Else
If BoolAllowInherited or BoolInitialInheritRightsPresent then
ControlFlagsVar = ALLOW_INHERIT
Else
ControlFlagsVar = DENY_INHERIT
End if
End if
End if

If debug_on then Call PrintMsg("SetACLForObject: Saving new Descriptor")

Set NewobjDescriptor = objService.Get("Win32_SecurityDescriptor").Spawninstance_
If blnErrorOccurred(" occurred Setting NewobjDescriptor = objService.Get(""Win32_SecurityDescriptor"").Spawninstance_") Then Exit Do

If boolDoTheUpdate then
NewobjDescriptor.Properties_.item("DACL") = NewDaclObj
If blnErrorOccurred(" occurred setting NewobjDescriptor.Properties_.item(""DACL"") = NewDaclObj") Then Exit Do

Else 'Making DACL Blank
Set BlankDaclObj(0) = objService.Get("Win32_Ace").Spawninstance_
If blnErrorOccurred(" occurred Setting BlankDaclObj(0) = objService.Get(""Win32_Ace"").Spawninstance_") Then Exit Do

NewobjDescriptor.Properties_.item("DACL") = BlankDaclObj
If blnErrorOccurred(" occurred setting NewobjDescriptor.Properties_.item(""DACL"") = BlankDaclObj") Then Exit Do

End if
If o_Used then 'Change Ownership

If debug_on then Call PrintMsg("SetACLForObject: Changing Ownership")

If o_Var <> "" then
Set objTempTrustee = Nothing
Set objTempTrustee = SetTrustee(o_var)
If Not objTempTrustee Is Nothing then
If TrusteesMatch(objOwner, objTempTrustee) then
Call PrintMsg("Ownership not changed, owner is already set to """ & TrusteesDisplay(objTempTrustee) & """")
Else
NewobjDescriptor.Properties_.item("Owner") = objTempTrustee
If blnErrorOccurred(" occurred setting NewobjDescriptor.Properties_.item(""Owner"") = objTempTrustee") Then Exit Do
Call PrintMsg("Changed Ownership to """ & TrusteesDisplay(objTempTrustee) & """")
End if
Else
Call PrintMsg("Failed to Change Ownership to user """ & o_var & """")
End if
End if
End if

NewobjDescriptor.ControlFlags = ControlFlagsVar
If blnErrorOccurred(" occurred setting NewobjDescriptor.ControlFlags = ControlFlagsVar") Then Exit Do

Set objmethod = objFileSecSetting.Methods_("SetSecurityDescriptor")
If blnErrorOccurred(" occurred setting objmethod = objFileSecSetting.Methods_(""SetSecurityDescriptor"")") Then Exit Do

Set objInParam = objmethod.inParameters.SpawnInstance_()
If blnErrorOccurred(" occurred Setting objInParam = objmethod.inParameters.SpawnInstance_()") Then Exit Do

objInParam.Properties_.item("Descriptor") = NewobjDescriptor
If blnErrorOccurred(" occurred setting objInParam.Properties_.item(""Descriptor"") = NewobjDescriptor") Then Exit Do

Set RetVal = objFileSecSetting.ExecMethod_("SetSecurityDescriptor", objInParam)
If blnErrorOccurred(" occurred setting RetVal = objFileSecSetting.ExecMethod_(""SetSecurityDescriptor"", objInParam)") Then Exit Do

Call PrintMsg("Completed successfully.")

Exit Do 'We really didn't want to loop
Loop
'ClearObjects that could be set and aren't needed now

Set objOwner = Nothing
Set objFileSecSetting = Nothing
Set objmethod = Nothing
Set objSecDescriptor = Nothing
Set objtrustee = Nothing
Set objInParam = Nothing
Set objOutParams = Nothing
Set OldAceObj = Nothing
Set ObjNewAce = Nothing
Set NewobjDescriptor = Nothing
Set objTempTrustee = Nothing
Set RetVal = Nothing

Call blnErrorOccurred(" occurred while in the SetACLForObject routine.")
If debug_on then Call PrintMsg("SetACLForObject: Exit")

End Sub


'********************************************************************
'*
'* Function AccessMask_New()
'* Purpose: Takes a list of users with permissions and adds them to the list
'* Input: Array_ACLobj : DACL Array
'* Array_Users : Array of users
'* Array_Perm : Array of permissions
'* AceType : Type of Permissions (Allow or Deny)
'* AceFlag : Apply to what (Files or Folders)
'* strAction : String saying what the action was (Grant, Replace, or Deny)
'* Output: Acl Array Object
'*
'********************************************************************

Function AccessMask_New(byref Array_ACLobj, byref Array_ObjTrustee, Array_Users, Array_Perm, AceType, AceFlag, strAction)
ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("AccessMask_New: Enter")

Dim t, objNEWACE, RightsToGive, AceTypeString

'Put statements in loop to be able to drop out and clear variables

Do
AccessMask_New = FALSE
If AceFlag = CONTAINER_INHERIT_ACE then
AceTypeString = """This Folder and Subfolders"""
Else
AceTypeString = """Files Only"""
End if
For t = LBound(Array_Users) to UBound(Array_Users)
If blnErrorOccurred(" occurred while " & strAction & " permissions.") Then Exit Do
If Array_Users(t) <> "" and Array_Perm(t) <> "" then
If IsObject(Array_ObjTrustee(t)) then
RightsToGive = SECBitMask(Array_Perm(t))
If blnErrorOccurred(" occurred getting rights for " & Array_Users(t) & ".") Then Exit Do

Set objNEWACE = SetACE(RightsToGive, AceFlag, AceType, Array_ObjTrustee(t))
If blnErrorOccurred(" occurred creating ""ACE Object"" for " & Array_Users(t) & ".") Then Exit Do

Call AddObjectToArray(Array_ACLobj, objNEWACE, -1)
If blnErrorOccurred(" occurred adding (" & strAction & ") New ACE object to array.") Then Exit Do

Set objNEWACE = Nothing
Call PrintMsg(strAction & " NTFS rights (" & SECString(RightsToGive,TRUE) & " access for " & AceTypeString & ") for """ & Array_Users(t) & """")
Else
Call PrintMsg("Failed " & strAction & " NTFS rights (" & AceTypeString & ") for """ & Array_Users(t) & """")
End if
End if
Next

AccessMask_New = TRUE

Exit Do 'We really didn't want to loop
Loop

Set objNEWACE = Nothing

If debug_on then Call PrintMsg("AccessMask_New: Return = " & AccessMask_New)

Call blnErrorOccurred(" occurred while in the AccessMask_New routine.")
If debug_on then Call PrintMsg("AccessMask_New: Exit")

End Function


'********************************************************************
'*
'* Sub TrusteesMatch()
'* Purpose: Checks the Trustee to the Name and Domain and returns boolean TRUE if they match
'* Input: objTrusteeA, objTrusteeB
'* Output: Boolean
'* Notes: This is a nice way to check if one trustee matches another, the procedure can change
'* and compare different values and only needs to be changed here, not in the rest of the code.
'*
'********************************************************************

Function TrusteesMatch(ByRef objTrusteeA, ByRef objTrusteeB)
ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("TrusteesMatch: Enter")

'Put statements in loop to be able to drop out and clear variables

Do
TrusteesMatch = FALSE
If debug_on then Call PrintMsg("TrusteesMatch: Checking Users to see if they match")

If NOT IsObject(objTrusteeA) then
Exit Do
End if

If NOT IsObject(objTrusteeB) then
Exit Do
End if

If objTrusteeA.SIDString = objTrusteeB.SIDString then
TrusteesMatch = TRUE
End if

Exit Do 'We really didn't want to loop
Loop

Call blnErrorOccurred(" occurred while in the TrusteesMatch routine.")
If debug_on then Call PrintMsg("TrusteesMatch: Exit")

End Function

'********************************************************************
'*
'* Sub TrusteesDisplay()
'* Purpose: Returns a Display ready string of trustee passed in
'* Input: objTrustee
'* Output: String
'* Notes: This makes the display of a trustee a standard throughout the code
'*
'********************************************************************

Function TrusteesDisplay(ByRef objTrustee)
ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("TrusteesDisplay: Enter")

'Put statements in loop to be able to drop out and clear variables

Do
TrusteesDisplay = ""

If NOT IsObject(objTrustee) then
Exit Do
End if

If objTrustee.Domain = "" then
TrusteesDisplay = objTrustee.Name
Else
TrusteesDisplay = objTrustee.Domain & "\" & objTrustee.Name
End if

Exit Do 'We really didn't want to loop
Loop

Call blnErrorOccurred(" occurred while in the TrusteesDisplay routine.")
If debug_on then Call PrintMsg("TrusteesDisplay: Exit")

End Function

'********************************************************************
'*
'* Sub CheckTrustees()
'* Purpose: Checks the list of entered users and makes them valid, run only once
'* Input: Global Variables only
'* Output: None
'* Notes: This function is called only one time in the code to get a trustee object for
'* every user entered, and if we can't find one then the user is deleted from the list.
'*
'********************************************************************

Sub CheckTrustees()
ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("CheckTrustees: Enter")

'Put statements in loop to be able to drop out and clear variables

Do
If debug_on then Call PrintMsg("CheckTrustees: Checking Users to make sure they are proper Trustee's")

Call GetDefaultNames()
Call GetDefaultDomainSid()

If g_Used then 'Add to users
If debug_on then Call PrintMsg("CheckTrustees: Checking /G users")
If FixListOfTrustees(g_Var_User, ObjTrustee_g_var_User, "/G") = FALSE then exit Do
End if
If p_Used then 'Replace users
If debug_on then Call PrintMsg("CheckTrustees: Checking /P users")
If FixListOfTrustees(p_Var_User, ObjTrustee_p_var_User, "/P") = FALSE then exit Do
End if
If d_Used then 'Change users
If debug_on then Call PrintMsg("CheckTrustees: Checking /D users")
If FixListOfTrustees(d_Var_User, ObjTrustee_d_var_User, "/D") = FALSE then exit Do
End if
If r_Used then 'Revoke users
If debug_on then Call PrintMsg("CheckTrustees: Checking /R users")
If FixListOfTrustees(r_Var_User, ObjTrustee_r_var_User, "/R") = FALSE then exit Do
End if

Exit Do 'We really didn't want to loop
Loop

Call blnErrorOccurred(" occurred while in the CheckTrustees routine.")
If debug_on then Call PrintMsg("CheckTrustees: Exit")

End Sub


'********************************************************************
'*
'* Function FixListOfTrustees()
'* Purpose: Takes a list of users and changes to a valid trustee if found, else sets string to ""
'* Input: Array_Users, strAction
'* Output: Dacl Array Object
'*
'********************************************************************

Function FixListOfTrustees(byref Array_Users, byref Array_ObjTrustee, strAction)
ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("FixListOfTrustees: Enter")

Dim t, objTempTrustee, strTempName

'Put statements in loop to be able to drop out and clear variables

Do
FixListOfTrustees = FALSE
For t = LBound(Array_Users) to UBound(Array_Users)
strTempName = ""
If Array_Users(t) <> "" then
'First, lets remove any special quotes in the string
'Quotation mark (") 34
Array_Users(t) = Replace(Array_Users(t),chr(34),"")
'Single turned comma quotation mark 145
Array_Users(t) = Replace(Array_Users(t),chr(145),"")
'Single comma quotation mark 146
Array_Users(t) = Replace(Array_Users(t),chr(146),"")
'Double turned comma quotation mark 147
Array_Users(t) = Replace(Array_Users(t),chr(147),"")
'Double comma quotation mark 148
Array_Users(t) = Replace(Array_Users(t),chr(148),"")

Set objTempTrustee = SetTrustee(Array_Users(t))
If blnErrorOccurred(" occurred Setting objTempTrustee = SetTrustee(Array_Users(t))") Then Exit Do

If objTempTrustee Is Nothing then
Call PrintMsg("Could not find " & strAction & " user/group: """ & Array_Users(t) & """ removing from list.")
Array_Users(t) = ""
Else
strTempName = TrusteesDisplay(objTempTrustee)
Call AddObjectToArray(Array_ObjTrustee, objTempTrustee, t)
If IsNull(objTempTrustee.Domain) then objTempTrustee.Domain = ""
If UCase(Array_Users(t)) <> UCASE(strTempName) then
Call PrintMsg(" - Changing " & strAction & " user/group: """ & Array_Users(t) & """ to """ & strTempName & """")
End if
Array_Users(t) = strTempName
Set objTempTrustee = Nothing
End if
End if
Next

FixListOfTrustees = TRUE 'Means we didn't have an error and went through the entire list

Exit Do 'We really didn't want to loop
Loop

Set objTempTrustee = Nothing
If debug_on then Call PrintMsg("FixListOfTrustees: Return = " & FixListOfTrustees)

Call blnErrorOccurred(" occurred while in the FixListOfTrustees routine.")
If debug_on then Call PrintMsg("FixListOfTrustees: Exit")

End Function


'********************************************************************
'*
'* Sub GetDaclArray()
'* Purpose: Return Dacl Array object if found
'* Input: objArrayPassedIn, objSecDescriptor, getonlyInherited
'* Output: Dacl Array Object
'*
'********************************************************************

Sub GetDaclArray(DACL_Array, objSecDescriptor, getonlyInherited)
ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("GetDaclArray: Enter")

Dim TempDACL_Array, objDACL_Member, numControlFlags

'Put statements in loop to be able to drop out and clear variables

Do
numControlFlags = objSecDescriptor.ControlFlags
If blnErrorOccurred(" occurred getting ControlFlags.") Then Exit Do


TempDACL_Array = objSecDescriptor.DACL
If blnErrorOccurred(" occurred getting Temporary DACL array.") Then Exit Do

If IsArray(TempDACL_Array) then
For Each objDACL_Member in TempDACL_Array
If blnErrorOccurred(" occurred while looping through TempDACL_Array.") Then Exit Do
If getonlyInherited then
If StringAceFlag(objDACL_Member.AceFlags, numControlFlags, SE_DACL_AUTO_INHERITED, TRUE) = "Inherited" then Call AddObjectToArray(DACL_Array, objDACL_Member, -1)
Else
Call AddObjectToArray(DACL_Array, objDACL_Member, -1)
End If
Next
End if
If (UBound(DACL_Array) = 0) Then
Set DACL_Array(0) = CreateObject("AccessControlEntry")
If blnErrorOccurred(" occurred Setting DACL_Array(0) = CreateObject(""AccessControlEntry"").") Then Exit Do
End if
Exit Do 'We really didn't want to loop
Loop
'ClearObjects that could be set and aren't needed now
Set objDACL_Member = Nothing

Call blnErrorOccurred(" occurred while in the GetDaclArray routine.")
If debug_on then Call PrintMsg("GetDaclArray: Exit")

End Sub


'********************************************************************
'* Function SetTrustee()
'* Purpose: Returns Win32_Trustee object for User/group or Nothing if not found
'* Input: strFullName
'* Output: Win32_Trustee object is returned, Nothing if not found
'********************************************************************
Function SetTrustee(strFullName)
ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("SetTrustee: Enter")

Dim objTrustee, objAccount, objSID, strSid, strDomain, strName

'Put statements in loop to be able to drop out and clear variables
Do
Set SetTrustee = Nothing
strSid = ""

Set objTrustee = objService.Get("Win32_Trustee").Spawninstance_

'GetStandardSid will parse the strFullname into strDomain and strName
strSid = GetStandardSid(strFullName, strDomain, strName)
If strSid <> "" then
objTrustee.Domain = strDomain
objTrustee.Name = strName
If blnErrorOccurred(" occurred setting Domain and Name for Trustee object.") Then
Exit Do
End if
Else
Set objAccount = GetAccountObj(strDomain, strName)
If blnErrorOccurred(" occurred getting Account Object.") Then
Exit Do
End if

If objAccount Is Nothing then
Call PrintMsg("Can't find Sid for: """ & strFullName & """")
Exit Do
Else
strSid = objAccount.Sid
End If
objTrustee.Domain = objAccount.Domain
objTrustee.Name = objAccount.Name
If blnErrorOccurred(" occurred setting Domain and Name for Trustee object.") Then
Exit Do
End if
End If

If strSid = "" then 'This means it doesn't exist
Call PrintMsg("Can't find Sid for: """ & strFullName & """")
Exit Do
End if

set objSID = objService.Get("Win32_SID.SID='" & strSid &"'")
If blnErrorOccurred(" occurred getting Win32_SID.SID Object.") Then
Exit Do
End if


objTrustee.Properties_.item("SID") = objSID.BinaryRepresentation
objTrustee.Properties_.item("SidLength") = objSID.SidLength
objTrustee.Properties_.item("SIDString") = objSID.Sid

set objSID = nothing
Set objAccount = Nothing

set SetTrustee = objTrustee
Exit Do 'We really didn't want to loop
Loop
'ClearObjects that could be set and aren't needed now
Set objTrustee = Nothing
Set objAccount = Nothing
Set objSID = Nothing

If debug_on then
If SetTrustee is Nothing then
Call PrintMsg("SetTrustee: Return = " & "Nothing")
Else
Call PrintMsg("SetTrustee: Return = " & "Win32_Trustee object")
End if
End if

Call blnErrorOccurred(" occurred while in the SetTrustee routine.")
If debug_on then Call PrintMsg("SetTrustee: Exit")

End Function

'********************************************************************
'* Function GetStandardSid()
'* Purpose: Returns Sid if the account is a special account
'* Input: strFullName
'* Output: String Value of Sid
'********************************************************************
Function GetStandardSid(ByRef strFullName, ByRef strDomain, ByRef strName)
ON ERROR RESUME NEXT

If debug_on then Call PrintMsg("GetStandardSid: Enter")
Dim strSpecialDomain

'Put statements in loop to be able to drop out and clear variables
Do
strDomain = ""
strName = ""
If InStr(1, strFullName, "\",1) > 0 then
strDomain = Left(strFullName, InStr(1, strFullName, "\",1) - 1)
strName = Mid(strFullName, InStr(1, strFullName, "\",1) + 1)
Else
If InStr(1, strFullName, "/",1) > 0 then
strDomain = Left(strFullName, InStr(1, strFullName, "/",1) - 1)
strName = Mid(strFullName, InStr(1, strFullName, "/",1) + 1)
Else
strName = strFullName
End if
End if
strSpecialDomain = ""
'List
Top
#58169 - 2002-08-06 02:11 PM Re: OFF TOPIC - Shawn can you review a WSH script for me?
Kdyer Offline
KiX Supporter
*****

Registered: 2001-01-03
Posts: 6241
Loc: Tigard, OR
Sure Doc..

Would you like fries with that?

Kent

[ 06. August 2002, 22:08: Message edited by: kdyer ]
_________________________
Utilize these resources:
UDFs (Full List)
KiXtart FAQ & How to's

Top
Page 2 of 2 <12


Moderator:  Glenn Barnas, NTDOC, Arend_, Jochen, Radimus, Allen, ShaneEP, Ruud van Velsen, Mart 
Hop to:
Shout Box

Who's Online
0 registered and 369 anonymous users online.
Newest Members
rrosell, PatrickPinto, Raoul, Timothy, Jojo67
17877 Registered Users

Generated in 0.19 seconds in which 0.111 seconds were spent on a total of 14 queries. Zlib compression enabled.

Search the board with:
superb Board Search
or try with google:
Google
Web kixtart.org