Solved

creating users in ADS an setting security permissions on folder using vbs script

Posted on 2002-04-29
8
278 Views
Last Modified: 2007-12-19
Is it possible and does anybody have an example of how to create users in ADS an setting permission on the NTFS file system, using a vbs script.

Please help :)

/Carsten from Denmark.
0
Comment
Question by:cnh-dk
  • 4
  • 3
8 Comments
 
LVL 63

Expert Comment

by:SysExpert
ID: 6977667
WHy use VBS.

Win2k has plenty of command line tools for this.

See the win2k resource kit.

Addusers

----------
This 32-bit administrative tool for Windows 2000 uses a comma-delimited file to create, write, and delete user accounts. The easiest way to maintain such files is in a spreadsheet, such as Microsoft Excel, that can work with comma-delimited files.

The format for the comma-delimited file requires headings for users [User], global groups [Global], and local groups [Local]. Before you use the /c option to create user accounts, it is recommended that you first execute AddUsers with the /d switch, the dump accounts option, which writes the headings, user accounts, local groups, and global groups to a file. Viewing this file gives a clearer picture of the structure and headings of the comma-delimited file.

You must be a member of the Administrators group on the target computer to add accounts and a member of the Users group to write accounts.

AddUsers is 100 percent Unicode. The switch /p:, followed by l, c, e, d, or any combination of the four enables you to specify the four account-creation options available in User Manager: UserMustChangePasswordAtNextLogon, UserCannotChangePassword, PasswordNeverExpires, and AccountDisabled.

------------
xcacls filename [/T] [/E] [/C] [/G user:perm;spec] [/R user] [/P user:perm;spec [...]] [/D user [...]] [/Y]

Where:

filename
indicates the name of the file or directory to which the access control list (ACL) or access control entry (ACE) should be applied. All standard wildcard characters can be used.
/T
recursively walks through the current directory and all its subdirectories, applying the chosen access rights to the matching files and/or directories.
/E
edits the ACL instead of replacing it. If you specify the following command line:


XCACLS test.dat /G Administrator:F


only the Administrator has access to TEST.DAT. All ACEs applied earlier are lost.
/C
causes XcAcls to continue if an "access denied" error occurs. If /C is not specified, XcAcls stops on this error.
/G user:perm;spec
grants access to user to the matching file or directory. The perm variable applies the specified access right to files and represents the special file-access-right mask for directories. The Perm variable accepts the following values:
R
Read
C
Change (write)
F
Full Control
P
Change Permissions (special access)
O
Take Ownership (special access)
X
EXecute (special access)
E
REad (Special access)
W
Write (Special access)
D
D Delete (Special access)
The spec variable applies only to directories, and accepts the same values as perm, with the addition of the following special value:

T
NoT Specified. Sets an ACE for the directory itself without specifying an ACE that is applied to new files created in that directory. At least one access right has to follow. Entries between ; and T will be ignored.


Notes


The access options for files (for directories, special file access and special directory access) are identical. For detailed explanations of these options, see the Windows 2000 operating system documentation.
All other options, which can also be set in Windows Explorer, are subsets of all possible combinations of the basic access rights. Therefore, there are no special options for directory access rights like LIST or READ.

/R user
revokes all access rights for the specified user.
/P user:perm;spec
replaces access rights for user. The rules for specifying perm and spec are the same as for the /G option. See XcAcls Examples.
/D user
denies access to the file or directory for user.
/Y
disables confirmation when replacing user access rights. By default, CACLS asks for confirmation. Because of this feature, when CACLS is used in a batch routine, the routine hangs until the right answer is entered. The /Y option was introduced to avoid this confirmation, so XcAcls can be used in batch mode

----------------------------------------------
and similar should be all you need.

I hope this helps !
0
 

Author Comment

by:cnh-dk
ID: 6977686
I want to use vbs because i am building an vbs script to create web sites in IIS, and to set up the security right i need to create a new user, when i create the web site.
0
 
LVL 3

Expert Comment

by:Corvax021899
ID: 6979463
Here the CreateUser Function...

Function CreateUser(NewUser,NewPwd,DomainOrServer)

   Dim oDomain, oUser

   set oDomain = GetObject("WinNT://" & DomainOrServer)
   set oUser = oDomain.Create("User",NewUser)
   oUser.SetInfo

   oUser.SetPassword NewPwd
   oUser.Setinfo

   If err.Number = 0 then
      CreateUser = 0
   Else
      CreateUser = -1
   End if
End Function
0
 
LVL 3

Expert Comment

by:Corvax021899
ID: 6979466
And here is a vbs script i got on the web for setting ACL on files and regestry...U will need the ADsSecurity.dll file from the sdk Ressource kit from MS...

=====================================

Option Explicit

' Set Filesystem and Registry ACL
' ===============================
'
' Author: Tobias Oetiker <oetiker@ee.ethz.ch>
'         based on code by Nick Pearce, Craig Paterson and Rich Ellis
'
' Version: 1.1 -- 2001/03/01
'
' Changes: 1.1 Handle non-existing registry keys gracefully.
'
' The purpose of this script is to allow ACL maniputlations
' to be performed by Microsoft Installer Packages (.msi)
'
' Add your ACL modification instructions to this script
' and integrate it as a Custom Action into the MSI.
'
' SETUP
' =====
'
' Note aclfix needs ADsSecurity.dll and RegObj.dll to work.
' You can get ADsSecurity from ADSI SDK 2.5 under (/ResourceKit/ADsSecurity.dll)
'
' Get the sdk from
' http://msdownload.microsoft.com:80/msdownload/adsi/2.5/sdk/x86/en/Sdk.zip
' copy the dll to a place in your path and run
'
' RegObj.dll is included in Office 2000 SR2 or also available directly from
' MS for registered VB users.
'
' regsvr32 regobj.dll
' regsvr32 adssecurity.dll
'
' Usage with WISE for Windows Installer
' =====================================
' * add a copy of the two dlls to the package and install them somewhere
'   below the INSTALLDIR of the package. Make sure you click Self register in
'   the file property dialog
'
' * customize the dacl.vbs according to the needs of the application and add it
'   to the msi somewhere below INSTALLDIR. Maybe next to the dlls
'
' * Add a custom action: Type:    Call Exe File
'                        Source:  File on destination machine
'                        Name:    DACL
'                        InstDir: SystemFolder
'                        Exe Cmd: wscript.exe "[!dacl.vbs]"  
'                        Sequenc: Install Execute Sequence (Before InstallFinalize)'                        
'                   Condition: NOT REMOVE~="ALL"
'                        I-S Opt: System Context
'                        Process: Asynch, Wait at end of sequence
'
' TODO
' ====
' Using Add with the Registry creates working results, but somehow the ACEs are
' not in the proper order, and regedt32 complains when you look at them ...
' it also seems that maybe I am not adding all the reg entries necessary ...
' lack of docu ... sorry ... help appreciated. I guess it has something todo
' with inheritance ...
'
' USAGE
' -----
'
' DACL function, url, "ace, ace, ..."
'
' function -- Add, Rm, Set
'
' url -- FILE://....       change this File/Folder
'        FILE://c:\home\   change this Folder and everything below
'        FILE://c:\home\\  change this Folder and Folders below
'        RGY://\HKEY_LOCAL_MACHINE\SOFTWARE    change this property
'        RGY://...\  and RGY://\...\\ are the same as indiviual
'                    registry values have no acls assigned
'
' ace -- account:rights
'
' account -- user or group
'
' rights (file) --  F - Full, C - Change, R - Read + Execute,
'                   S - Read + Write + Execute, L - List
'
' rights (registry) --  F - Full, R - Read
'
' EXAMPLES
' --------
' DACL "Add", "FILE://w:\hello.txt", "users:F,moetiker:F"
' DACL "Add", "FILE://w:\hello\",    "users:R,oetiker:F,moetiker:F"
' DACL "Rm",  "FILE://w:\oops.txt",  "everyone"
' DACL "Add", "RGY://\HKEY_CURRENT_USER\SOFTWARE\ipswitch\ws_ftp\", "users:F"
'=============================================================================

'=============================================================================
' Implementation
' --------------

DACL "Add","FILE://E:\Ftp Site\Nav2002.exe","Users:S"


Sub DumpAcl (url)
    Dim sd, dacl, ace, sec
    Print url
    Set sec = Wscript.CreateObject("ADsSecurity")
    Set sd = sec.GetSecurityDescriptor( CStr(url) )
    Set dacl = sd.DiscretionaryAcl
    For Each ace In dacl
        Print "   " & ace.trustee & _
              "   Type: " & ace.AceType & _
              "   Mask: " & ace.AccessMask & _
              "   Flags: " & ace.AceFlags
    Next
End Sub

Sub AclEdit( action, url, acl, UType )
    Dim acls, dacl, dummy, sec, sd, ace, acea, usera, user, perm, acsplit
    Const ADS_ACETYPE_ACCESS_ALLOWED = 0
    Const ADS_ACETYPE_ACCESS_DENIED = 1
    Const ADS_ACEFLAG_INHERIT_ACE = 2
    Const ADS_ACEFLAG_SUB_NEW = 9

    Print "Edit: " & action & " " & url & " " & acl & " " & utype
    acls = split(acl,",")
   
    Set sec = Wscript.CreateObject("ADsSecurity")
    on error resume Next

    ' without cstr this will break ... !!!
    Set sd = sec.GetSecurityDescriptor( CStr(url) )

    If ErrHandler("Get SD for " & url ) Then
        On Error GoTo 0
        Exit Sub
    End If

    Set dacl = sd.DiscretionaryAcl
    dummy = dacl.AceCount ' this will throw an error if there is no DACL    
    If ErrHandler("Get DACL for " & url ) Then
        On Error GoTo 0
        Exit Sub
    End If

    ' DumpAcl url

    If action = "Rm" Or action = "Add" Then
        ' for Add we remove the ACEs for the folks which need new ones
        For Each ace In dacl
            acea = split (LCase(ace.trustee & "\" & ace.trustee),"\")
            If acea(0) <> "nt authority" Then
                For Each user In acls
                    usera = split (LCase(user),":")        
                    If acea(1) = usera(0) Then
                        Print "Remove ACE: " & ace.trustee
                        dacl.RemoveACE ace                    
                        ErrHandler("Remove ACE for " & ace.trustee & _
                                   " from " & url)
                    End If
                Next
            End if
        Next

    ElseIf action = "Set" Then
        For Each ace In dacl
            acea = split (LCase(ace.trustee & "\" & ace.trustee),"\")
            If acea(0) <> "nt authority" Then
                dacl.RemoveACE ace
                ErrHandler("Remove ACE for " & ace.Trustee & " from " & url)
                Print "Remove ACE: " & ace.trustee
            End if
        Next    
    Else
        Wscript.Echo "Unknown Action: " & action
    End If
   
    If action = "Set" Or action = "Add" Then
        For Each dummy In acls
            acsplit = split (dummy,":")
            user = acsplit(0)
            perm = acsplit(1)
            Print action & " " & utype & " " & user & " " & perm
            Select Case UType
                Case "DIRECTORY"
                    ' folders require 2 aces for user (to do with inheritance)
                    AddFileAce dacl, user, perm, _
                               ADS_ACETYPE_ACCESS_ALLOWED, _
                               ADS_ACEFLAG_SUB_NEW
                    AddFileAce dacl, user, perm, _
                               ADS_ACETYPE_ACCESS_ALLOWED, _
                               ADS_ACEFLAG_INHERIT_ACE
                case "FILE"
                    AddFileAce dacl, user, perm, _
                               ADS_ACETYPE_ACCESS_ALLOWED,0
                case "REGISTRY"
                    AddRegAce dacl, user, perm, _
                              ADS_ACETYPE_ACCESS_ALLOWED, _
                              ADS_ACEFLAG_INHERIT_ACE
            End Select
        Next

    End If

   
    sd.DiscretionaryAcl = dacl
    If ErrHandler("Get SD for " & url ) Then    
        On Error GoTo 0
        Exit Sub
    End If

    sec.SetSecurityDescriptor sd    
    If ErrHandler("Get SD for " & url ) Then
        On Error GoTo 0
        Exit Sub
    End If
   
    Set sd = Nothing
    Set dacl = Nothing
    Set sec = Nothing

    ' DumpAcl url

    On Error GoTo 0  
End Sub

Sub AddRegACE(dacl, user, perm , acetype, aceflags)
    ' Add registry ACE
    Dim ace
   
    Const ADS_ACETYPE_ACCESS_ALLOWED = 0
    Const RIGHT_REG_READ = &H20019
    Const RIGHT_REG_FULL = &HF003F

   
    Set ace = CreateObject("AccessControlEntry")
    ace.Trustee = user
   
    Select Case UCase(perm)
        ' specified rights so far only include FC & R. Could be expanded though
        Case "F"
            ace.AccessMask = RIGHT_REG_FULL
        Case "R"
            ace.AccessMask = RIGHT_REG_READ
    End Select
   
    ace.AceType = acetype
    ace.AceFlags = aceflags
    dacl.AddAce ace
    ErrHandler("Add Ace for " & user )

    set ace=Nothing

End Sub

Sub AddFileAce(dacl,user, perm, acetype, aceflags)
    ' add ace to the specified dacl
    Dim ace
   
    Const RIGHT_LIST = &H4
    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

   
    Set ace = CreateObject("AccessControlEntry")
    ace.Trustee = user
   
    select case ucase(perm)
        ' 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
        case "S" 'Special
            ace.AccessMask = RIGHT_READ or RIGHT_WRITE or RIGHT_EXECUTE
        case "L" 'List
            ace.AccessMask = RIGHT_LIST
    end select
   
    ace.AceType = acetype
    ace.AceFlags = aceflags
    dacl.AddAce ace
    ErrHandler("Add Ace for " & user )

    set ace=Nothing

End Sub
   
Sub DACL(action,url,acl)
    Dim argarry, utype, upath, walk, ftype, fs, rfldr, file, sfldr
    Dim ro, rk, regval,skey
    argarry = split(url,"://")
    utype = argarry(0)
    upath = argarry(1)

    Print "Action: " & action & " " & utype & "--" & upath & " " & acl

    If Right(upath,2) = "\\" Then
        walk = "\\" ' folders only
        upath = Left(upath, Len(upath)-2)
    ElseIf Right(upath,1) = "\" Then
        walk = "\" ' files and folders
        upath = left(upath, len(upath)-1)      
    End If
   
    If utype = "FILE" Then
       
        Set fs=Wscript.CreateObject("Scripting.FileSystemObject")
        Print "---" & upath
        If fs.FileExists(upath) Then
            Set rfldr=fs.GetFile(upath)
            ftype = "FILE" 'directory
        ElseIf fs.FolderExists(upath) Then
            Set rfldr=fs.GetFolder(upath)
            ftype = "DIRECTORY" 'file
        Else
            ' its neither file nor folder ... maybe it does not exist ...
            wscript.echo "Can't find " & upath
            Exit Sub
        End If
       
        AclEdit action, "FILE://" & rfldr.path, acl, ftype

        If ftype = "FILE" Then 'if this is a file our work is done
            Exit Sub
        End If
       
        If walk = "\" then
            For Each file In rfldr.files
                AclEdit action, "FILE://" & file , acl, "FILE"
            Next
        End If
       
        if walk = "\" or walk = "\\" then
            for each sfldr in rfldr.subfolders
                DACL action, "FILE://" & sfldr & walk, acl
            next
        end if
       
    elseif utype = "RGY" Then

        Set ro = CreateObject("RegObj.Registry")
        on error resume Next
        Set rk = ro.RegKeyFromString( upath )
        If ErrHandler("Get Registry Key " & upath ) Then
            On Error GoTo 0
            Exit Sub
        End If
       
        AclEdit action, "RGY://" & rk.FullName, acl,"REGISTRY"  
                       
        if walk = "\" or walk = "\\" then
            for each skey in rk.Subkeys
                DACL action,"RGY://" &  skey.FullName & walk, acl
            next
        end If
       
    else
        Wscript.Echo "Unsupported URL Type: " & utype
    end If
    On Error GoTo 0
   
End Sub

Function ErrHandler(what)
    If Err.Number > 0 Then
        WScript.Echo what & " Error " & Err.Number & ": " & Err.Description
        Err.Clear
        Return True
    End If
    ErrHandler = False
End Function

Sub Print(Str)
    'strip when debugging
    'wscript.echo Str
End Sub
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:cnh-dk
ID: 6980156
Corvax >> Could you give me an example of the use of the security functions ? for an example, how to set read, read & execute and list folder contents on the path c:\testdir\ to the user testuser ?
0
 
LVL 3

Accepted Solution

by:
Corvax021899 earned 200 total points
ID: 6982064
DACL "Add", "FILE://C:\Testdir\","Testuser:R"
0
 

Author Comment

by:cnh-dk
ID: 6983324
Tnx for the help :=)
0
 
LVL 3

Expert Comment

by:Corvax021899
ID: 6984742
My pleasure :-)
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

NTFS file system has been developed by Microsoft that is widely used by Windows NT operating system and its advanced versions. It is the mostly used over FAT file system as it provides superior features like reliability, security, storage, efficienc…
For cloud, the “train has left the station” and in the Microsoft ERP & CRM world, that means the next generation of enterprise software from Microsoft is here: Dynamics 365 is Microsoft’s new integrated business solution that unifies CRM and ERP fun…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video discusses moving either the default database or any database to a new volume.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now