CodeItBetter Programming Another VB Programming Blog

How to change the permission settings for a folder in Windows OS

Posted on November 13, 2011
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
'System & API - How to change the permission settings for a folder in Windows OS
'The following code changes permissions on a folder to Add & Read or Change.
'The folder needs to be created on an NTFS partition.
'You need to be an Administrator on the machine and have read/write
'(READ_CONTROL and WRITE_DAC) access to the file or directory.

'1. Create a Standard EXE project in Visual Basic. Form1 is created by default.
'2. Add two Textboxes (Text1 and Text2) and two CommandButtons (Command1 and Command2) to Form1.
'3. Add the following code to the form and the module
'4. Run the application.
'5. In the Test1 TextBox, enter the name of the folder you want to change 
'   permissions on. (D:\test is entered by default.)
'   In the Test2 Textbox, enter the name of the user you want to give these permissions to.
'6. Click the Add & Read permissions button to give Add & Read permissions to 
'   the folder, or click the Change Permissions
'   button to give Change permissions to the folder.
'7. To check the permissions on the folder, right-click Explorer. Select the 
'   Properties menu item, and click the Security
'   Tab of the Properties dialog box. On the Security tab, click the 
'   Permissions button. The specific account should say
'   Add & Read or Change depending on which button you clicked in the preceding sample.

'Add this code to the form
Private Sub Command1_Click()
    Dim sUserName As String
    Dim sFolderName As String
    sUserName = Trim$(CStr(Text2.Text))
    sFolderName = Trim$(CStr(Text1.Text))
    SetAccess sUserName, sFolderName, GENERIC_READ Or GENERIC_EXECUTE Or Delete Or GENERIC_WRITE
End Sub
Private Sub Command2_Click()
    Dim sUserName As String
    Dim sFolderName As String
    sUserName = Trim$(Text2.Text)
    sFolderName = Trim$(Text1.Text)
    SetAccess sUserName, sFolderName, GENERIC_EXECUTE Or GENERIC_READ
End Sub
Private Sub Form_Load()
    Text1.Text = "enter folder name"
    Text2.Text = "enter username"
    Command1.Caption = "Change"
    Command2.Caption = "Read && Add"
End Sub
 
'Add this code to a module

' Constants used within our API calls. Refer to the MSDN for more
' information on how/what these constants are used for.

' Memory constants used through various memory API calls.
Public Const GMEM_MOVEABLE = &H2
Public Const LMEM_FIXED = &H0
Public Const LMEM_ZEROINIT = &H40
Public Const LPTR = (LMEM_FIXED + LMEM_ZEROINIT)
Public Const GENERIC_READ = &H80000000
Public Const GENERIC_ALL = &H10000000
Public Const GENERIC_EXECUTE = &H20000000
Public Const GENERIC_WRITE = &H40000000
 
' The file/security API call constants.
' Refer to the MSDN for more information on how/what these constants
' are used for.
Public Const DACL_SECURITY_INFORMATION = &H4
Public Const SECURITY_DESCRIPTOR_REVISION = 1
Public Const SECURITY_DESCRIPTOR_MIN_LENGTH = 20
Public Const SD_SIZE = (65536 + SECURITY_DESCRIPTOR_MIN_LENGTH)
Public Const ACL_REVISION2 = 2
Public Const ACL_REVISION = 2
Public Const MAXDWORD = &HFFFFFFFF
Public Const SidTypeUser = 1
Public Const AclSizeInformation = 2
 
' The following are the inherit flags that go into the AceFlags field
' of an Ace header.

Public Const OBJECT_INHERIT_ACE = &H1
Public Const CONTAINER_INHERIT_ACE = &H2
Public Const NO_PROPAGATE_INHERIT_ACE = &H4
Public Const INHERIT_ONLY_ACE = &H8
Public Const INHERITED_ACE = &H10
Public Const VALID_INHERIT_FLAGS = &H1F
Public Const DELETE = &H10000
 
' Structures used by our API calls.
' Refer to the MSDN for more information on how/what these
' structures are used for.
Type ACE_HEADER
    AceType As Byte
    AceFlags As Byte
    AceSize As Integer
End Type
 
 
Public Type ACCESS_DENIED_ACE
    Header As ACE_HEADER
    Mask As Long
    SidStart As Long
End Type
 
Type ACCESS_ALLOWED_ACE
    Header As ACE_HEADER
    Mask As Long
    SidStart As Long
End Type
 
Type ACL
    AclRevision As Byte
    Sbz1 As Byte
    AclSize As Integer
    AceCount As Integer
    Sbz2 As Integer
End Type
 
Type ACL_SIZE_INFORMATION
    AceCount As Long
    AclBytesInUse As Long
    AclBytesFree As Long
End Type
 
Type SECURITY_DESCRIPTOR
    Revision As Byte
    Sbz1 As Byte
    Control As Long
    Owner As Long
    Group As Long
    sACL As ACL
    Dacl As ACL
End Type
 
' API calls used within this sample. Refer to the MSDN for more
' information on how/what these APIs do.

Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" _
    (ByVal lpBuffer As String, nSize As Long) As Long
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
    (ByVal lpBuffer As String, nSize As Long) As Long
Declare Function LookupAccountName Lib "advapi32.dll" Alias "LookupAccountNameA" _
    (lpSystemName As String, ByVal lpAccountName As String, sid As Any, cbSid As Long, _
    ByVal ReferencedDomainName As String, cbReferencedDomainName As Long, peUse As Long) As Long
Declare Function InitializeSecurityDescriptor Lib "advapi32.dll" _
    (pSecurityDescriptor As SECURITY_DESCRIPTOR, ByVal dwRevision As Long) As Long
Declare Function GetSecurityDescriptorDacl Lib "advapi32.dll" (pSecurityDescriptor As Byte, _
    lpbDaclPresent As Long, pDacl As Long, lpbDaclDefaulted As Long) As Long
Declare Function GetFileSecurityN Lib "advapi32.dll" Alias "GetFileSecurityA" _
    (ByVal lpFileName As String, ByVal RequestedInformation As Long, _
    ByVal pSecurityDescriptor As Long, ByVal nLength As Long, lpnLengthNeeded As Long) As Long
Declare Function GetFileSecurity Lib "advapi32.dll" Alias "GetFileSecurityA" _
    (ByVal lpFileName As String, ByVal RequestedInformation As Long, pSecurityDescriptor As Byte, _
    ByVal nLength As Long, lpnLengthNeeded As Long) As Long
Declare Function GetAclInformation Lib "advapi32.dll" (ByVal pAcl As Long, pAclInformation As Any, _
    ByVal nAclInformationLength As Long, ByVal dwAclInformationClass As Long) As Long
Public Declare Function EqualSid Lib "advapi32.dll" (pSid1 As Byte, ByVal pSid2 As Long) As Long
Declare Function GetLengthSid Lib "advapi32.dll" (pSid As Any) As Long
Declare Function InitializeAcl Lib "advapi32.dll" (pAcl As Byte, ByVal nAclLength As Long, _
    ByVal dwAclRevision As Long) As Long
Declare Function GetAce Lib "advapi32.dll" (ByVal pAcl As Long, ByVal dwAceIndex As Long, _
    pace As Any) As Long
Declare Function AddAce Lib "advapi32.dll" (ByVal pAcl As Long, ByVal dwAceRevision As Long, _
    ByVal dwStartingAceIndex As Long, ByVal pAceList As Long, ByVal nAceListLength As Long) As Long
Declare Function AddAccessAllowedAce Lib "advapi32.dll" (pAcl As Byte, _
    ByVal dwAceRevision As Long, ByVal AccessMask As Long, pSid As Byte) As Long
Public Declare Function AddAccessDeniedAce Lib "advapi32.dll" (pAcl As Byte, _
    ByVal dwAceRevision As Long, ByVal AccessMask As Long, pSid As Byte) As Long
Declare Function SetSecurityDescriptorDacl Lib "advapi32.dll" _
    (pSecurityDescriptor As SECURITY_DESCRIPTOR, ByVal bDaclPresent As Long, pDacl As Byte, _
    ByVal bDaclDefaulted As Long) As Long
Declare Function SetFileSecurity Lib "advapi32.dll" Alias "SetFileSecurityA" _
    (ByVal lpFileName As String, ByVal SecurityInformation As Long, _
    pSecurityDescriptor As SECURITY_DESCRIPTOR) As Long
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (hpvDest As Any, _
    ByVal hpvSource As Long, ByVal cbCopy As Long)
 
Public Sub SetAccess(sUserName As String, sFileName As String, lMask As Long)
    Dim lResult As Long            ' Result of various API calls.
    Dim I As Integer               ' Used in looping.
    Dim bUserSid(255) As Byte      ' This will contain your SID.
    Dim bTempSid(255) As Byte      ' This will contain the Sid of each ACE in the ACL .
    Dim sSystemName As String      ' Name of this computer system.

    Dim lSystemNameLength As Long  ' Length of string that contains
    ' the name of this system.

    Dim lLengthUserName As Long    ' Max length of user name.

    'Dim sUserName As String * 255 ' String to hold the current user
    ' name.

 
    Dim lUserSID As Long           ' Used to hold the SID of the
    ' current user.

    Dim lTempSid As Long            ' Used to hold the SID of each ACE in the ACL
    Dim lUserSIDSize As Long          ' Size of the SID.
    Dim sDomainName As String * 255   ' Domain the user belongs to.
    Dim lDomainNameLength As Long     ' Length of domain name needed.

    Dim lSIDType As Long              ' The type of SID info we are
    ' getting back.

    Dim sFileSD As SECURITY_DESCRIPTOR   ' SD of the file we want.

    Dim bSDBuf() As Byte           ' Buffer that holds the security
    ' descriptor for this file.

    Dim lFileSDSize As Long           ' Size of the File SD.
    Dim lSizeNeeded As Long           ' Size needed for SD for file.

 
    Dim sNewSD As SECURITY_DESCRIPTOR    ' New security descriptor.

    Dim sACL As ACL                   ' Used in grabbing the DACL from
    ' the File SD.

    Dim lDaclPresent As Long          ' Used in grabbing the DACL from
    ' the File SD.

    Dim lDaclDefaulted As Long        ' Used in grabbing the DACL from
    ' the File SD.

    Dim sACLInfo As ACL_SIZE_INFORMATION  ' Used in grabbing the ACL
    ' from the File SD.

    Dim lACLSize As Long           ' Size of the ACL structure used
    ' to get the ACL from the File SD.

    Dim pAcl As Long               ' Current ACL for this file.
    Dim lNewACLSize As Long        ' Size of new ACL to create.
    Dim bNewACL() As Byte          ' Buffer to hold new ACL.

    Dim sCurrentACE As ACCESS_ALLOWED_ACE    ' Current ACE.
    Dim pCurrentAce As Long                  ' Our current ACE.

    Dim nRecordNumber As Long
 
    ' Get the SID of the user. (Refer to the MSDN for more information on SIDs
    ' and their function/purpose in the operating system.) Get the SID of this
    ' user by using the LookupAccountName API. In order to use the SID
    ' of the current user account, call the LookupAccountName API
    ' twice. The first time is to get the required sizes of the SID
    ' and the DomainName string. The second call is to actually get
    ' the desired information.

    lResult = LookupAccountName(vbNullString, sUserName, bUserSid(0), 255, _
        sDomainName, lDomainNameLength, lSIDType)
 
    ' Now set the sDomainName string buffer to its proper size before
    ' calling the API again.
    sDomainName = Space(lDomainNameLength)
 
    ' Call the LookupAccountName again to get the actual SID for user.
    lResult = LookupAccountName(vbNullString, sUserName, bUserSid(0), 255, _
        sDomainName, lDomainNameLength, lSIDType)
 
    ' Return value of zero means the call to LookupAccountName failed;
    ' test for this before you continue.
    If (lResult = 0) Then
        MsgBox "Error: Unable to Lookup the Current User Account: " & sUserName
        Exit Sub
    End If
 
    ' You now have the SID for the user who is logged on.
    ' The SID is of interest since it will get the security descriptor
    ' for the file that the user is interested in.
    ' The GetFileSecurity API will retrieve the Security Descriptor
    ' for the file. However, you must call this API twice: once to get
    ' the proper size for the Security Descriptor and once to get the
    ' actual Security Descriptor information.

    lResult = GetFileSecurityN(sFileName, DACL_SECURITY_INFORMATION, 0, 0, lSizeNeeded)
 
    ' Redimension the Security Descriptor buffer to the proper size.
    ReDim bSDBuf(lSizeNeeded)
 
    ' Now get the actual Security Descriptor for the file.
    lResult = GetFileSecurity(sFileName, DACL_SECURITY_INFORMATION, bSDBuf(0), _
        lSizeNeeded, lSizeNeeded)
 
    ' A return code of zero means the call failed; test for this
    ' before continuing.
    If (lResult = 0) Then
        MsgBox "Error: Unable to Get the File Security Descriptor"
        Exit Sub
    End If
 
    ' Call InitializeSecurityDescriptor to build a new SD for the
    ' file.
    lResult = InitializeSecurityDescriptor(sNewSD, SECURITY_DESCRIPTOR_REVISION)
 
    ' A return code of zero means the call failed; test for this
    ' before continuing.
    If (lResult = 0) Then
        MsgBox "Error: Unable to Initialize New Security Descriptor"
        Exit Sub
    End If
 
    ' You now have the file's SD and a new Security Descriptor
    ' that will replace the current one. Next, pull the DACL from
    ' the SD. To do so, call the GetSecurityDescriptorDacl API
    ' function.

    lResult = GetSecurityDescriptorDacl(bSDBuf(0), lDaclPresent, pAcl, lDaclDefaulted)
 
    ' A return code of zero means the call failed; test for this
    ' before continuing.
    If (lResult = 0) Then
        MsgBox "Error: Unable to Get DACL from File Security " & "Descriptor"
        Exit Sub
    End If
 
    ' You have the file's SD, and want to now pull the ACL from the
    ' SD. To do so, call the GetACLInformation API function.
    ' See if ACL exists for this file before getting the ACL
    ' information.
    If (lDaclPresent = False) Then
        MsgBox "Error: No ACL Information Available for this File"
        Exit Sub
    End If
 
    ' Attempt to get the ACL from the file's Security Descriptor.
    lResult = GetAclInformation(pAcl, sACLInfo, Len(sACLInfo), 2&)
 
    ' A return code of zero means the call failed; test for this
    ' before continuing.
    If (lResult = 0) Then
        MsgBox "Error: Unable to Get ACL from File Security Descriptor"
        Exit Sub
    End If
 
    ' Now that you have the ACL information, compute the new ACL size
    ' requirements.
    lNewACLSize = sACLInfo.AclBytesInUse + (Len(sCurrentACE) + GetLengthSid(bUserSid(0))) * 2 - 4
 
    ' Resize our new ACL buffer to its proper size.
    ReDim bNewACL(lNewACLSize)
 
    ' Use the InitializeAcl API function call to initialize the new
    ' ACL.
    lResult = InitializeAcl(bNewACL(0), lNewACLSize, ACL_REVISION)
 
    ' A return code of zero means the call failed; test for this
    ' before continuing.
    If (lResult = 0) Then
        MsgBox "Error: Unable to Initialize New ACL"
        Exit Sub
    End If
 
    ' If a DACL is present, copy it to a new DACL.
    If (lDaclPresent) Then
 
        ' Copy the ACEs from the file to the new ACL.
        If (sACLInfo.AceCount > 0) Then
 
            ' Grab each ACE and stuff them into the new ACL.
            nRecordNumber = 0
            For I = 0 To (sACLInfo.AceCount - 1)
 
                ' Attempt to grab the next ACE.
                lResult = GetAce(pAcl, I, pCurrentAce)
 
                ' Make sure you have the current ACE under question.
                If (lResult = 0) Then
                    MsgBox "Error: Unable to Obtain ACE (" & I & ")"
                    Exit Sub
                End If
 
                ' You have a pointer to the ACE. Place it
                ' into a structure, so you can get at its size.
                CopyMemory sCurrentACE, pCurrentAce, LenB(sCurrentACE)
 
                'Skip adding the ACE to the ACL if this is same usersid
                lTempSid = pCurrentAce + 8
                If EqualSid(bUserSid(0), lTempSid) = 0 Then
 
                    ' Now that you have the ACE, add it to the new ACL.
                    lResult = AddAce(VarPtr(bNewACL(0)), ACL_REVISION, MAXDWORD, _
                        pCurrentAce, sCurrentACE.Header.AceSize)
 
                    ' Make sure you have the current ACE under question.
                    If (lResult = 0) Then
                        MsgBox "Error: Unable to Add ACE to New ACL"
                        Exit Sub
                    End If
                    nRecordNumber = nRecordNumber + 1
                End If
 
            Next I
 
            ' You have now rebuilt a new ACL and want to add it to
            ' the newly created DACL.
            lResult = AddAccessAllowedAce(bNewACL(0), ACL_REVISION, lMask, bUserSid(0))
 
            ' Make sure added the ACL to the DACL.
            If (lResult = 0) Then
                MsgBox "Error: Unable to Add ACL to DACL"
                Exit Sub
            End If
 
            'If it's directory, we need to add inheritance staff.
            If GetAttr(sFileName) And vbDirectory Then
 
                ' Attempt to grab the next ACE which is what we just added.
                lResult = GetAce(VarPtr(bNewACL(0)), nRecordNumber, pCurrentAce)
 
                ' Make sure you have the current ACE under question.
                If (lResult = 0) Then
                    MsgBox "Error: Unable to Obtain ACE (" & I & ")"
                    Exit Sub
                End If
                ' You have a pointer to the ACE. Place it
                ' into a structure, so you can get at its size.
                CopyMemory sCurrentACE, pCurrentAce, LenB(sCurrentACE)
                sCurrentACE.Header.AceFlags = OBJECT_INHERIT_ACE + INHERIT_ONLY_ACE
                CopyMemory ByVal pCurrentAce, VarPtr(sCurrentACE), LenB(sCurrentACE)
 
                'add another ACE for files
                lResult = AddAccessAllowedAce(bNewACL(0), ACL_REVISION, lMask, bUserSid(0))
 
                ' Make sure added the ACL to the DACL.
                If (lResult = 0) Then
                    MsgBox "Error: Unable to Add ACL to DACL"
                    Exit Sub
                End If
 
                ' Attempt to grab the next ACE.
                lResult = GetAce(VarPtr(bNewACL(0)), nRecordNumber + 1, pCurrentAce)
 
                ' Make sure you have the current ACE under question.
                If (lResult = 0) Then
                    MsgBox "Error: Unable to Obtain ACE (" & I & ")"
                    Exit Sub
                End If
 
                CopyMemory sCurrentACE, pCurrentAce, LenB(sCurrentACE)
                sCurrentACE.Header.AceFlags = CONTAINER_INHERIT_ACE
                CopyMemory ByVal pCurrentAce, VarPtr(sCurrentACE), LenB(sCurrentACE)
            End If
 
 
            ' Set the file's Security Descriptor to the new DACL.
            lResult = SetSecurityDescriptorDacl(sNewSD, 1, bNewACL(0), 0)
 
            ' Make sure you set the SD to the new DACL.
            If (lResult = 0) Then
                MsgBox "Error: " & "Unable to Set New DACL to Security Descriptor"
                Exit Sub
            End If
 
            ' The final step is to add the Security Descriptor back to
            ' the file!
            lResult = SetFileSecurity(sFileName, DACL_SECURITY_INFORMATION, sNewSD)
 
            ' Make sure you added the Security Descriptor to the file!
            If (lResult = 0) Then
                MsgBox "Error: Unable to Set New Security Descriptor " & " to File : " & sFileName
                MsgBox Err.LastDllError
            Else
                MsgBox "Updated Security Descriptor on File: " & sFileName
            End If
        End If
    End If
End Sub
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.