[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

check write permission on c: drive on win xp

Posted on 2005-04-17
8
Medium Priority
?
1,069 Views
Last Modified: 2013-12-04
Hello All,

              I want to write a vb script for checking write permission on whole C-drive and also want to log the path where write permission is there to a text file..


              Hope anyone can help me with script. As I am new to it.

Hoping for best .....

Regards,
Pralay Desai
0
Comment
Question by:pralay
  • 4
  • 2
6 Comments
 
LVL 41

Expert Comment

by:graye
ID: 13803260
Tell us what you're trying to do...  what do you mean by "check write permission"?   Are you saying that you want to look at the entire C drive and find those files where a specific user has write permission?   Or are you saying that you want to record all of the permissions for all of the files in a text file?
0
 

Author Comment

by:pralay
ID: 13803649
Hello graye & all,

I want to look at entire c drive & find those file where a specific user has write permission. I also want to store that information in a file. I hope this time I am bit clear.

Can you help me out in this ?

Thanks in advance ......

Regards,
Pralay Desai
0
 
LVL 41

Expert Comment

by:graye
ID: 13805042
I've got a program that will do exactly what you're talking about.  It's not a script, it's a VB.Net application... and is only available as VB.Net source code (which means you'd have to have a copy of Visual Studio .Net 2003 in order to compile it into a complete applicaiton).

Would this be useful to you, or do you really, really need it to be done in a script?

0
Put Machine Learning to Work--Protect Your Clients

Machine learning means Smarter Cybersecurity™ Solutions.
As technology continues to advance, managing and analyzing massive data sets just can’t be accomplished by humans alone. It requires huge amounts of memory and storage, as well as the high-speed power of the cloud.

 

Author Comment

by:pralay
ID: 13805427
I want in script but you can give that code then I can try it out.

Hoping for best ....

Regards,
Pralay Desai
0
 
LVL 41

Accepted Solution

by:
graye earned 100 total points
ID: 13805903
The program consists of 2 files...

Form1.vb

Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports System.IO
Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents FolderBrowserDialog1 As System.Windows.Forms.FolderBrowserDialog
    Friend WithEvents SaveFileDialog1 As System.Windows.Forms.SaveFileDialog
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button2 As System.Windows.Forms.Button
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Button3 As System.Windows.Forms.Button
    Friend WithEvents Button4 As System.Windows.Forms.Button
    Friend WithEvents tb_StartingDir As System.Windows.Forms.TextBox
    Friend WithEvents tb_logfile As System.Windows.Forms.TextBox
    Friend WithEvents lb_Status As System.Windows.Forms.Label
    Friend WithEvents Button5 As System.Windows.Forms.Button
    Friend WithEvents cb_Permission As System.Windows.Forms.ComboBox
    Friend WithEvents Label3 As System.Windows.Forms.Label
    Friend WithEvents Label4 As System.Windows.Forms.Label
    Friend WithEvents tb_UserName As System.Windows.Forms.TextBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.tb_StartingDir = New System.Windows.Forms.TextBox
        Me.tb_logfile = New System.Windows.Forms.TextBox
        Me.FolderBrowserDialog1 = New System.Windows.Forms.FolderBrowserDialog
        Me.SaveFileDialog1 = New System.Windows.Forms.SaveFileDialog
        Me.Button1 = New System.Windows.Forms.Button
        Me.Button2 = New System.Windows.Forms.Button
        Me.Label1 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.Button3 = New System.Windows.Forms.Button
        Me.Button4 = New System.Windows.Forms.Button
        Me.lb_Status = New System.Windows.Forms.Label
        Me.Button5 = New System.Windows.Forms.Button
        Me.cb_Permission = New System.Windows.Forms.ComboBox
        Me.Label3 = New System.Windows.Forms.Label
        Me.Label4 = New System.Windows.Forms.Label
        Me.tb_UserName = New System.Windows.Forms.TextBox
        Me.SuspendLayout()
        '
        'tb_StartingDir
        '
        Me.tb_StartingDir.Location = New System.Drawing.Point(120, 24)
        Me.tb_StartingDir.Name = "tb_StartingDir"
        Me.tb_StartingDir.Size = New System.Drawing.Size(384, 20)
        Me.tb_StartingDir.TabIndex = 0
        Me.tb_StartingDir.Text = "d:\"
        '
        'tb_logfile
        '
        Me.tb_logfile.Location = New System.Drawing.Point(120, 64)
        Me.tb_logfile.Name = "tb_logfile"
        Me.tb_logfile.Size = New System.Drawing.Size(384, 20)
        Me.tb_logfile.TabIndex = 1
        Me.tb_logfile.Text = "c:\temp\CopyFail.txt"
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(512, 24)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(24, 24)
        Me.Button1.TabIndex = 2
        Me.Button1.Text = "..."
        '
        'Button2
        '
        Me.Button2.Location = New System.Drawing.Point(512, 64)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(24, 24)
        Me.Button2.TabIndex = 3
        Me.Button2.Text = "..."
        '
        'Label1
        '
        Me.Label1.Location = New System.Drawing.Point(24, 16)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(88, 32)
        Me.Label1.TabIndex = 4
        Me.Label1.Text = "Starting Directory:"
        Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        '
        'Label2
        '
        Me.Label2.Location = New System.Drawing.Point(24, 56)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(88, 32)
        Me.Label2.TabIndex = 5
        Me.Label2.Text = "Logfile:"
        Me.Label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        '
        'Button3
        '
        Me.Button3.Location = New System.Drawing.Point(136, 256)
        Me.Button3.Name = "Button3"
        Me.Button3.Size = New System.Drawing.Size(72, 48)
        Me.Button3.TabIndex = 6
        Me.Button3.Text = "Doit"
        '
        'Button4
        '
        Me.Button4.Location = New System.Drawing.Point(344, 256)
        Me.Button4.Name = "Button4"
        Me.Button4.Size = New System.Drawing.Size(72, 48)
        Me.Button4.TabIndex = 7
        Me.Button4.Text = "Quit"
        '
        'lb_Status
        '
        Me.lb_Status.Location = New System.Drawing.Point(16, 192)
        Me.lb_Status.Name = "lb_Status"
        Me.lb_Status.Size = New System.Drawing.Size(512, 40)
        Me.lb_Status.TabIndex = 8
        Me.lb_Status.Text = "Ready..."
        '
        'Button5
        '
        Me.Button5.Location = New System.Drawing.Point(240, 256)
        Me.Button5.Name = "Button5"
        Me.Button5.Size = New System.Drawing.Size(72, 48)
        Me.Button5.TabIndex = 9
        Me.Button5.Text = "View Log"
        '
        'cb_Permission
        '
        Me.cb_Permission.Items.AddRange(New Object() {"Full Control", "Modify", "Read & Execute", "Read", "Write", "Execute"})
        Me.cb_Permission.Location = New System.Drawing.Point(120, 104)
        Me.cb_Permission.Name = "cb_Permission"
        Me.cb_Permission.Size = New System.Drawing.Size(384, 21)
        Me.cb_Permission.TabIndex = 10
        Me.cb_Permission.Text = "Full Control"
        '
        'Label3
        '
        Me.Label3.Location = New System.Drawing.Point(24, 96)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(88, 32)
        Me.Label3.TabIndex = 11
        Me.Label3.Text = "Permission:"
        Me.Label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        '
        'Label4
        '
        Me.Label4.Location = New System.Drawing.Point(24, 136)
        Me.Label4.Name = "Label4"
        Me.Label4.Size = New System.Drawing.Size(88, 32)
        Me.Label4.TabIndex = 13
        Me.Label4.Text = "User Name:"
        Me.Label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        '
        'tb_UserName
        '
        Me.tb_UserName.Location = New System.Drawing.Point(120, 144)
        Me.tb_UserName.Name = "tb_UserName"
        Me.tb_UserName.Size = New System.Drawing.Size(384, 20)
        Me.tb_UserName.TabIndex = 12
        Me.tb_UserName.Text = ""
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(544, 326)
        Me.Controls.Add(Me.Label4)
        Me.Controls.Add(Me.tb_UserName)
        Me.Controls.Add(Me.Label3)
        Me.Controls.Add(Me.cb_Permission)
        Me.Controls.Add(Me.Button5)
        Me.Controls.Add(Me.lb_Status)
        Me.Controls.Add(Me.Button4)
        Me.Controls.Add(Me.Button3)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.Button2)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.tb_logfile)
        Me.Controls.Add(Me.tb_StartingDir)
        Me.Name = "Form1"
        Me.Text = "Check Permission"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Public Enum FileAccessType As Integer
        DELETE = &H10000
        READ_CONTROL = &H20000
        WRITE_DAC = &H40000
        WRITE_OWNER = &H80000
        SYNCHRONIZE = &H100000
        STANDARD_RIGHTS_REQUIRED = &HF0000
        STANDARD_RIGHTS_READ = READ_CONTROL
        STANDARD_RIGHTS_WRITE = READ_CONTROL
        STANDARD_RIGHTS_EXECUTE = READ_CONTROL
        STANDARD_RIGHTS_ALL = &H1F0000
        SPECIFIC_RIGHTS_ALL = &HFFFF
        ACCESS_SYSTEM_SECURITY = &H1000000
        MAXIMUM_ALLOWED = &H2000000
        'GENERIC_READ = &H80000000
        'GENERIC_WRITE = &H40000000
        'GENERIC_EXECUTE = &H20000000
        'GENERIC_ALL = &H10000000
        FILE_READ_DATA = &H1
        FILE_WRITE_DATA = &H2
        FILE_APPEND_DATA = &H4
        FILE_READ_EA = &H8
        FILE_WRITE_EA = &H10
        FILE_EXECUTE = &H20
        FILE_READ_ATTRIBUTES = &H80
        FILE_WRITE_ATTRIBUTES = &H100
        FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &H1FF
        FILE_GENERIC_READ = STANDARD_RIGHTS_READ Or FILE_READ_DATA Or FILE_READ_ATTRIBUTES Or FILE_READ_EA Or SYNCHRONIZE
        FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE Or FILE_WRITE_DATA Or FILE_WRITE_ATTRIBUTES Or FILE_WRITE_EA Or FILE_APPEND_DATA Or SYNCHRONIZE
        FILE_GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE Or FILE_READ_ATTRIBUTES Or FILE_EXECUTE Or SYNCHRONIZE
    End Enum

    Private sw As StreamWriter
    Private dirs, files, failures, mask As Integer
    Private cp As CheckPerm

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer
        FolderBrowserDialog1.ShowDialog()
        tb_StartingDir.Text = FolderBrowserDialog1.SelectedPath
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        SaveFileDialog1.AddExtension = True
        SaveFileDialog1.FileName = tb_logfile.Text
        SaveFileDialog1.DefaultExt = "txt"
        SaveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
        SaveFileDialog1.InitialDirectory = tb_logfile.Text
        SaveFileDialog1.CheckFileExists = False
        SaveFileDialog1.OverwritePrompt = True
        SaveFileDialog1.ShowDialog()
        tb_logfile.Text = SaveFileDialog1.FileName
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim fs As FileStream

        dirs = 0
        files = 0
        failures = 0

        ' create the logfile
        Try
            fs = New FileStream(tb_logfile.Text, FileMode.Create)
            sw = New StreamWriter(fs)
        Catch ex As Exception
            MsgBox("Can't open log file" & vbCr & ex.Message, MsgBoxStyle.Exclamation, "Error!")
            Exit Sub
        End Try

        ' create the CheckPerm class
        Try
            cp = New CheckPerm
            cp.UserName = tb_UserName.Text
        Catch ex As Exception
            MsgBox("Can't find the user account" & vbCr & ex.Message, MsgBoxStyle.Exclamation, "Error!")
            Exit Sub
        End Try

        ' create the permission mask
        Select Case cb_Permission.Text
            Case "Full Control"
                cp.AccessMask = FileAccessType.FILE_ALL_ACCESS
            Case "Modify"
                cp.AccessMask = FileAccessType.FILE_ALL_ACCESS And Not (FileAccessType.WRITE_DAC Or FileAccessType.WRITE_OWNER Or &H40)
            Case "Read & Execute"
                cp.AccessMask = FileAccessType.FILE_GENERIC_READ Or FileAccessType.FILE_GENERIC_EXECUTE
            Case "Read"
                cp.AccessMask = FileAccessType.FILE_GENERIC_READ
            Case "Write"
                cp.AccessMask = FileAccessType.FILE_GENERIC_WRITE
            Case "Execute"
                cp.AccessMask = FileAccessType.FILE_GENERIC_EXECUTE
        End Select

        ' do it...
        sw.WriteLine("Started: " & Now)
        Dim tick As Long
        tick = Environment.TickCount

        Traverse(tb_StartingDir.Text)

        ' clean up and go home
        lb_Status.Text = "Done!"
        sw.WriteLine("Finished: " & Now)
        sw.Close()
        fs.Close()
        MsgBox("Scanned " & dirs & " directories and " & files & " files" & vbCr & "and had " & failures & " failures" & vbCr & "in " & Math.Round((Environment.TickCount - tick) / 60000.0, 1) & " minutes")
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Me.Close()
    End Sub

    Private Sub Traverse(ByVal p As String)
        Dim fi As FileInfo
        Dim d, di As DirectoryInfo

        ' skip the recycle bin and other directories we don't want...
        If p.Substring(1).Equals(":\RECYCLER") Or p.Substring(1).Equals(":\System Volume Information") Then
            Exit Sub
        End If

        ' dress it up a wee bit...
        If Not p.EndsWith("\") Then
            p = p & "\"
        End If

        ' keep 'em entertained...
        lb_Status.Text = p
        Application.DoEvents()

        Try
            di = New DirectoryInfo(p)
        Catch ex As Exception
            sw.WriteLine("Error: " & ex.Message)
            failures += 1
            Exit Sub
        End Try

        Try
            For Each fi In di.GetFiles
                cp.Path = fi.FullName
                If cp.ErrorNum = 0 Then
                    If cp.HasAccess Then
                        sw.WriteLine(fi.FullName)
                    End If
                Else
                    sw.WriteLine("Error: " & cp.ErrorMsg)
                End If
                files += 1
            Next
        Catch ex As Exception
            sw.WriteLine("Error: " & ex.Message)
            failures += 1
            Exit Sub
        End Try

        ' Process the directories (and descend into dir structure)
        For Each d In di.GetDirectories
            dirs += 1

            ' a recursive call to this subroutine
            Traverse(d.FullName)
        Next
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        If [File].Exists(tb_logfile.Text) Then
            Shell("notepad.exe " & tb_logfile.Text, AppWinStyle.NormalFocus)
        End If
    End Sub
End Class
0
 
LVL 41

Expert Comment

by:graye
ID: 13805907
... and the 2nd file

CheckPerm.vb

Imports System.Runtime.InteropServices
Imports System.ComponentModel

Public Class CheckPerm
    Implements IDisposable

    'typedef struct _TRUSTEE {
    '  PTRUSTEE pMultipleTrustee;
    '  MULTIPLE_TRUSTEE_OPERATION MultipleTrusteeOperation;
    '  TRUSTEE_FORM TrusteeForm;
    '  TRUSTEE_TYPE TrusteeType;
    '  LPTSTR ptstrName;
    '} TRUSTEE, *PTRUSTEE;
    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto, Pack:=4)> _
    Private Structure TRUSTEE
        Dim pMultipleTrustee As Integer ' must be null, so no need for IntPtr
        Dim MultipleTrusteeOperation As Integer
        Dim TrusteeForm As Integer
        Dim TrusteeType As Integer
        Dim ptstrName As IntPtr
    End Structure

    'typedef enum _SE_OBJECT_TYPE {
    '  SE_UNKNOWN_OBJECT_TYPE = 0,
    '  SE_FILE_OBJECT,
    '  SE_SERVICE,
    '  SE_PRINTER,
    '  SE_REGISTRY_KEY,
    '  SE_LMSHARE,
    '  SE_KERNEL_OBJECT,
    '  SE_WINDOW_OBJECT,
    '  SE_DS_OBJECT,
    '  SE_DS_OBJECT_ALL,
    '  SE_PROVIDER_DEFINED_OBJECT,
    '  SE_WMIGUID_OBJECT,
    '  SE_REGISTRY_WOW64_32
    '} SE_OBJECT_TYPE;
    Private Enum SE_OBJECT_TYPE As Integer
        SE_UNKNOWN_OBJECT_TYPE = 0
        SE_FILE_OBJECT
        SE_SERVICE
        SE_PRINTER
        SE_REGISTRY_KEY
        SE_LMSHARE
        SE_KERNEL_OBJECT
        SE_WINDOW_OBJECT
        SE_DS_OBJECT
        SE_DS_OBJECT_ALL
        SE_PROVIDER_DEFINED_OBJECT
        SE_WMIGUID_OBJECT
        SE_REGISTRY_WOW64_32
    End Enum

    Private Enum SECURITY_INFORMATION As Integer
        OWNER_SECURITY_INFORMATION = 1
        GROUP_SECURITY_INFORMATION = 2
        DACL_SECURITY_INFORMATION = 4
        SACL_SECURITY_INFORMATION = 8
        PROTECTED_SACL_SECURITY_INFORMATION = 16
        PROTECTED_DACL_SECURITY_INFORMATION = 32
        UNPROTECTED_SACL_SECURITY_INFORMATION = 64
        UNPROTECTED_DACL_SECURITY_INFORMATION = 128
    End Enum

    'VOID BuildTrusteeWithSid(
    '  PTRUSTEE pTrustee,
    '  PSID pSid
    ');
    Private Declare Auto Sub BuildTrusteeWithSid Lib "advapi32.dll" ( _
        ByVal pTrustee As IntPtr, _
        ByVal pSid As IntPtr _
    )

    'DWORD GetNamedSecurityInfo(
    '  LPTSTR pObjectName,
    '  SE_OBJECT_TYPE ObjectType,
    '  SECURITY_INFORMATION SecurityInfo,
    '  PSID* ppsidOwner,
    '  PSID* ppsidGroup,
    '  PACL* ppDacl,
    '  PACL* ppSacl,
    '  PSECURITY_DESCRIPTOR* ppSecurityDescriptor
    ');
    Private Declare Auto Function GetNamedSecurityInfo Lib "advapi32.dll" ( _
        ByVal pObjectName As String, _
        ByVal ObjectType As SE_OBJECT_TYPE, _
        ByVal SecurityInfo As SECURITY_INFORMATION, _
        ByRef ppsidOwner As IntPtr, _
        ByRef ppsidGroup As IntPtr, _
        ByRef ppDacl As IntPtr, _
        ByRef ppSacl As IntPtr, _
        ByRef ppSecurityDescriptor As IntPtr _
    ) As Integer

    'DWORD GetEffectiveRightsFromAcl(
    '  PACL pacl,
    '  PTRUSTEE pTrustee,
    '  PACCESS_MASK pAccessRights
    ');
    Private Declare Auto Function GetEffectiveRightsFromAcl Lib "advapi32.dll" ( _
        ByVal pacl As IntPtr, _
        ByVal pTrustee As IntPtr, _
        ByRef pAccessRights As Integer _
    ) As Integer

    'BOOL LookupAccountName(
    '  LPCTSTR lpSystemName,
    '  LPCTSTR lpAccountName,
    '  PSID Sid,
    '  LPDWORD cbSid,
    '  LPTSTR ReferencedDomainName,
    '  LPDWORD cchReferencedDomainName,
    '  PSID_NAME_USE peUse
    ');
    Private Declare Auto Function LookupAccountName Lib "advapi32.dll" ( _
        ByVal lpSystemName As String, _
        ByVal lpAccountName As String, _
        ByVal Sid As IntPtr, _
        ByRef cbSid As Integer, _
        ByVal lpReferenceDomainName As String, _
        ByRef cchReferencedDomainName As Integer, _
        ByRef peUse As Integer _
    ) As Boolean

    Private _UserName As String
    Private _Path As String
    Private _AccessMask As Integer
    Private _ErrorNum As Integer
    Private _ErrorMsg As String
    Private pTrustee, pSID As IntPtr

    Public Enum FileAccessType As Integer
        DELETE = &H10000
        READ_CONTROL = &H20000
        WRITE_DAC = &H40000
        WRITE_OWNER = &H80000
        SYNCHRONIZE = &H100000
        STANDARD_RIGHTS_REQUIRED = &HF0000
        STANDARD_RIGHTS_READ = READ_CONTROL
        STANDARD_RIGHTS_WRITE = READ_CONTROL
        STANDARD_RIGHTS_EXECUTE = READ_CONTROL
        STANDARD_RIGHTS_ALL = &H1F0000
        SPECIFIC_RIGHTS_ALL = &HFFFF
        ACCESS_SYSTEM_SECURITY = &H1000000
        MAXIMUM_ALLOWED = &H2000000
        'GENERIC_READ = &H80000000
        'GENERIC_WRITE = &H40000000
        'GENERIC_EXECUTE = &H20000000
        'GENERIC_ALL = &H10000000
        FILE_READ_DATA = &H1
        FILE_WRITE_DATA = &H2
        FILE_APPEND_DATA = &H4
        FILE_READ_EA = &H8
        FILE_WRITE_EA = &H10
        FILE_EXECUTE = &H20
        FILE_READ_ATTRIBUTES = &H80
        FILE_WRITE_ATTRIBUTES = &H100
        FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &H1FF
        FILE_GENERIC_READ = STANDARD_RIGHTS_READ Or FILE_READ_DATA Or FILE_READ_ATTRIBUTES Or FILE_READ_EA Or SYNCHRONIZE
        FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE Or FILE_WRITE_DATA Or FILE_WRITE_ATTRIBUTES Or FILE_WRITE_EA Or FILE_APPEND_DATA Or SYNCHRONIZE
        FILE_GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE Or FILE_READ_ATTRIBUTES Or FILE_EXECUTE Or SYNCHRONIZE
    End Enum

    Public Sub New()
        UserName = Environment.UserDomainName & "\" & Environment.UserName
    End Sub

    Public Property UserName() As String
        Get
            Return _UserName
        End Get
        Set(ByVal Value As String)
            Dim Domain As String
            Dim lenDomain, lenSid, peUse, LastError As Integer
            Dim Win32Error As Win32Exception
            Dim t As TRUSTEE

            _UserName = Value

            ' do a "dry run" to get the size of the SID and Domain string
            LookupAccountName(Nothing, _UserName, Nothing, lenSid, Nothing, lenDomain, peUse)
            Domain = Space(lenDomain)
            pSID = Marshal.AllocHGlobal(lenSid)

            ' do it again, for real this time
            If LookupAccountName(Nothing, _UserName, pSID, lenSid, Domain, lenDomain, peUse) = False Then
                LastError = Marshal.GetLastWin32Error()
                Win32Error = New Win32Exception(LastError)
                Throw New Exception(Win32Error.Message)
            End If

            ' Build a trustee
            pTrustee = Marshal.AllocHGlobal(Marshal.SizeOf(t))
            BuildTrusteeWithSid(pTrustee, pSID)
        End Set
    End Property

    Public Property Path() As String
        Get
            Return _Path
        End Get
        Set(ByVal Value As String)
            _Path = Value
        End Set
    End Property

    Public Property AccessMask() As Integer
        Get
            Return _AccessMask
        End Get
        Set(ByVal Value As Integer)
            _AccessMask = Value
        End Set
    End Property

    Public ReadOnly Property ErrorNum() As Integer
        Get
            Return _ErrorNum
        End Get
    End Property

    Public ReadOnly Property ErrorMsg() As String
        Get
            Return _ErrorMsg
        End Get
    End Property

    Public Function HasAccess() As Boolean
        Dim pDACL, pSD As IntPtr
        Dim Mask, ret As Integer
        Dim Win32Error As Win32Exception

        ' Some quick sanity checks...
        If _Path = "" Then
            Throw New Exception("Missing Path information")
        End If
        If _AccessMask = 0 Then
            Throw New Exception("Missing AccessMask information")
        End If
        _ErrorNum = 0
        _ErrorMsg = ""

        ' Get the DACL from the file
        ret = GetNamedSecurityInfo(_Path, SE_OBJECT_TYPE.SE_FILE_OBJECT, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, Nothing, Nothing, pDACL, Nothing, pSD)
        If ret <> 0 Then
            _ErrorNum = ret
            Win32Error = New Win32Exception(_ErrorNum)
            _ErrorMsg = Win32Error.Message
            Return False
        End If

        ' Get the Access Mask using the supplied user account
        ret = GetEffectiveRightsFromAcl(pDACL, pTrustee, Mask)
        If ret <> 0 Then
            _ErrorNum = ret
            Win32Error = New Win32Exception(_ErrorNum)
            _ErrorMsg = Win32Error.Message
            Marshal.FreeHGlobal(pSD)
            Return False
        End If

        Marshal.FreeHGlobal(pSD)

        ' Let's see if we've got a match!
        If CBool(_AccessMask And Mask) Then
            Return True
        Else
            _ErrorNum = 5
            _ErrorMsg = "Permission Denied"
            Return False
        End If
    End Function

    Public Overloads Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    Protected Overloads Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            ' nothing comes to mind...
        End If
        If pSID.ToInt32 <> 0 Then
            Marshal.FreeHGlobal(pSID)
        End If
        If pTrustee.ToInt32 <> 0 Then
            Marshal.FreeHGlobal(pTrustee)
        End If
    End Sub

    Protected Overrides Sub Finalize()
        Dispose(False)
    End Sub
End Class
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: btan
The intent is not to repeat what many has know about Ransomware but more to join its dots of what is it, who are the victims, why it exists, when and how we respond on infection. Lastly, sum up in a glance to share such information with more to help…
Recently, I read that Microsoft has analysed statistics for their security intelligence report. It revealed: still, the clear majority of windows users do their daily work as administrator. An administrative account is a burden, security-wise. My ar…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses
Course of the Month19 days, 8 hours left to enroll

872 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