Solved

Retrive shared folders from vb code

Posted on 2004-09-23
8
1,243 Views
Last Modified: 2010-05-18
hi, I have to find out shared folder from local system and i need to change the permissions from vb code please help me any one

Thank you.
0
Comment
Question by:rameshsamala
  • 3
  • 2
8 Comments
 
LVL 41

Accepted Solution

by:
graye earned 125 total points
ID: 12139182
That's acutally a tall order.  There are several ways to do this via API call, but probably the easiest is via Windows Management Instrumentation (WMI).

Here is a chunk of VB.Net code that will list all of the shares and their permissions.  It is not a complete solution... it's just cut from a working program.  This example does not set the permissions... so let us know if you need help doing that after you've looked at the code.


        If AppSettings("Shares.Checked") = "True" Then
            Dim perm_cnt As Integer
            If Not IsNothing(gui) Then
                gui.DoStatus("Shared Resources")
            End If
            Application.DoEvents()
            Try
                If RemotePC <> "" Then
                    MgmtPath = "\\" & RemotePC & "\root\cimv2:"
                End If
                wmi = New ManagementClass(MgmtPath & "Win32_Share")
                objs = wmi.GetInstances()
                For Each obj In objs
                    ' report only "non-administrative" shares
                    If Not obj("Name").ToString.EndsWith("$") Then
                        dr = ds.Tables("Shares").NewRow()
                        dr("ID_Share") = ID
                        dr("Share_Desc") = Left(obj("Name"), 100)
                        dr("Share_Path") = Left(obj("Path"), 150)
                        ' if "Type" is a single digit wide
                        If Not IsNothing(obj("Type")) AndAlso obj("type").ToString.Length = 1 Then
                            dr("Share_Type") = Choose(Convert.ToInt32(obj("Type")) + 1, "Disk", "Printer", "Device", "IPC")
                        End If
                        ds.Tables("Shares").Rows.Add(dr)
                        If AppSettings("Permissions.Checked") = "True" Then
                            ' MgmtPath contains the server and namespace
                            DoPerms(MgmtPath, dr("Share_Desc").ToString, perm_cnt)
                        End If
                    End If
                Next
                objs.Dispose()
            Catch e As Exception
                dr = ds.Tables("Shares").NewRow()
                dr("ID_Share") = ID
                dr("Share_Desc") = Left("Error: " & e.Message, 100)
                ds.Tables("Shares").Rows.Add(dr)
            End Try
        End If

<------------------------------------>
Imports System.management
Imports System.Security
Module SharePerm
    Public Enum DirectoryAccessType 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_LIST_DIRECTORY = &H1
        FILE_ADD_FILE = &H2
        FILE_ADD_SUBDIRECTORY = &H4
        FILE_READ_EA = &H8
        FILE_WRITE_EA = &H10
        FILE_TRAVERSE = &H20
        FILE_DELETE_CHILD = &H40
        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_LIST_DIRECTORY Or FILE_READ_ATTRIBUTES Or FILE_READ_EA Or SYNCHRONIZE
        FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE Or FILE_ADD_FILE Or FILE_WRITE_ATTRIBUTES Or FILE_WRITE_EA Or FILE_ADD_SUBDIRECTORY Or SYNCHRONIZE
        FILE_GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE Or FILE_READ_ATTRIBUTES Or FILE_TRAVERSE Or SYNCHRONIZE
    End Enum

    Public Enum AceFlags As Byte
        OBJECT_INHERIT_ACE = &H1
        CONTAINER_INHERIT_ACE = &H2
        NO_PROPAGATE_INHERIT_ACE = &H4
        INHERIT_ONLY_ACE = &H8
        INHERITED_ACE = &H10
        VALID_INHERIT_FLAGS = &H1F
        SUCCESSFUL_ACCESS_ACE_FLAG = &H40
        FAILED_ACCESS_ACE_FLAG = &H80
    End Enum
    Public Sub DoPerms(ByVal MgmtPath As String, ByVal share As String, ByRef perm_cnt As Integer)
        Dim lsss As ManagementObject
        Dim opt As New InvokeMethodOptions(Nothing, New TimeSpan(0, 0, 0, 5))
        Dim out, sd, ace, trustee As ManagementBaseObject
        Dim dacl As ManagementBaseObject()
        Dim dr As DataRow

        Try
            ' For some reason, a share that has default permissions
            ' won't always show up... so we fake it
            Try
                lsss = New ManagementObject(MgmtPath & "Win32_LogicalShareSecuritySetting.Name=" & Chr(34) & share & Chr(34))
                out = lsss.InvokeMethod("GetSecurityDescriptor", Nothing, opt)
            Catch
                dr = ds.Tables("Permissions").NewRow()
                dr("ID_Perm") = ID
                dr("Perm_ID") = perm_cnt
                dr("Perm_Target") = share
                dr("Perm_Type") = "Allow"
                dr("Perm_Name") = "Everyone"
                dr("Perm_Permission") = "Full Control"
                dr("Perm_Flags") = "This folder only"
                ds.Tables("Permissions").Rows.Add(dr)
                perm_cnt += 1
                Exit Sub
            End Try

            sd = out("Descriptor")
            dacl = sd("DACL")
            For Each ace In dacl
                dr = ds.Tables("Permissions").NewRow()
                dr("ID_Perm") = ID
                dr("Perm_ID") = perm_cnt
                dr("Perm_Target") = share
                dr("Perm_Type") = Choose((Convert.ToInt64(ace("AceType")) + 1), "Allow", "Deny", "Audit")
                trustee = CType(ace("Trustee"), ManagementBaseObject)
                If Not IsNothing(trustee("Domain")) Then
                    dr("Perm_Name") = trustee("Domain").ToString & "\" & trustee("Name").ToString
                Else
                    dr("Perm_Name") = trustee("Name").ToString
                End If
                dr("Perm_Permission") = Left(DirectoryMaskToString(Convert.ToInt32(ace("AccessMask"))), 150)
                dr("Perm_Flags") = Left(ACEFlagToString(Convert.ToByte(ace("AceFlags"))), 150)
                ds.Tables("Permissions").Rows.Add(dr)
                perm_cnt += 1
            Next
        Catch e As Exception
            dr = ds.Tables("Permissions").NewRow()
            dr("ID_Perm") = ID
            dr("Perm_ID") = perm_cnt
            dr("Perm_Target") = share
            dr("Perm_Type") = Left("Error: " & e.Message, 100)
            ds.Tables("Permissions").Rows.Add(dr)
            perm_cnt += 1
        End Try

    End Sub
    Function DirectoryMaskToString(ByVal mask As Integer) As String
        Dim buf As String

        Select Case mask
            Case DirectoryAccessType.FILE_ALL_ACCESS
                Return ("Full Control")
            Case DirectoryAccessType.FILE_ALL_ACCESS And Not (DirectoryAccessType.WRITE_DAC Or DirectoryAccessType.WRITE_OWNER Or DirectoryAccessType.FILE_DELETE_CHILD)
                Return ("Modify")
            Case DirectoryAccessType.FILE_GENERIC_READ Or DirectoryAccessType.FILE_GENERIC_EXECUTE
                Return ("Read & Execute")
            Case DirectoryAccessType.FILE_GENERIC_EXECUTE
                Return ("List Folder Contents")
            Case DirectoryAccessType.FILE_GENERIC_READ
                Return ("Read")
            Case DirectoryAccessType.FILE_GENERIC_WRITE
                Return ("Write")
                ' generic permissions
            Case DirectoryAccessType.GENERIC_ALL
                Return ("Generic Full Control")
            Case DirectoryAccessType.GENERIC_READ Or DirectoryAccessType.GENERIC_WRITE Or DirectoryAccessType.GENERIC_EXECUTE Or DirectoryAccessType.DELETE
                Return ("Generic Modify")
            Case DirectoryAccessType.GENERIC_READ Or DirectoryAccessType.GENERIC_EXECUTE
                Return ("Generic Read & Execute")
            Case DirectoryAccessType.GENERIC_EXECUTE
                Return ("Generic List Folder Contents")
            Case DirectoryAccessType.GENERIC_READ
                Return ("Generic Read")
            Case DirectoryAccessType.GENERIC_WRITE
                Return ("Generic Write")
            Case Else
                ' ok... do it the hard way
                buf = "Special (0x" & Hex(mask) & "): "
                If mask And DirectoryAccessType.FILE_TRAVERSE Then
                    buf = buf & "Traverse Folder,"
                End If
                If mask And DirectoryAccessType.FILE_LIST_DIRECTORY Then
                    buf = buf & "List Folder,"
                End If
                If mask And DirectoryAccessType.FILE_READ_ATTRIBUTES Then
                    buf = buf & "Read Attributes,"
                End If
                If mask And DirectoryAccessType.FILE_READ_EA Then
                    buf = buf & "Read Extended Attributes,"
                End If
                If mask And DirectoryAccessType.FILE_ADD_FILE Then
                    buf = buf & "Create Files,"
                End If
                If mask And DirectoryAccessType.FILE_ADD_SUBDIRECTORY Then
                    buf = buf & "Create Folders,"
                End If
                If mask And DirectoryAccessType.FILE_WRITE_ATTRIBUTES Then
                    buf = buf & "Write Attributes,"
                End If
                If mask And DirectoryAccessType.FILE_WRITE_EA Then
                    buf = buf & "Write Extended Attributes,"
                End If
                If mask And DirectoryAccessType.DELETE Then
                    buf = buf & "Delete,"
                End If
                If mask And DirectoryAccessType.FILE_DELETE_CHILD Then
                    buf = buf & "Delete Subfolders & Files,"
                End If
                If mask And DirectoryAccessType.READ_CONTROL Then
                    buf = buf & "Read Permissions,"
                End If
                If mask And DirectoryAccessType.WRITE_DAC Then
                    buf = buf & "Change Permissions,"
                End If
                If mask And DirectoryAccessType.WRITE_OWNER Then
                    buf = buf & "Take Ownership,"
                End If
                If buf.EndsWith(",") Then
                    buf = buf.TrimEnd(",")
                End If
                Return (buf)
        End Select

    End Function
    Function ACEFlagToString(ByVal flag As Byte) As String
        Dim buf As String

        Select Case flag
            Case 0, AceFlags.INHERITED_ACE
                Return "This folder only"
            Case AceFlags.OBJECT_INHERIT_ACE Or AceFlags.CONTAINER_INHERIT_ACE, AceFlags.OBJECT_INHERIT_ACE Or AceFlags.CONTAINER_INHERIT_ACE Or AceFlags.INHERITED_ACE
                Return "This folder, subfolders and files"
            Case AceFlags.CONTAINER_INHERIT_ACE, AceFlags.CONTAINER_INHERIT_ACE Or AceFlags.INHERITED_ACE
                Return "This folder and subfolders"
            Case AceFlags.OBJECT_INHERIT_ACE, AceFlags.OBJECT_INHERIT_ACE Or AceFlags.INHERITED_ACE
                Return "This folder and files"
            Case AceFlags.OBJECT_INHERIT_ACE Or AceFlags.CONTAINER_INHERIT_ACE Or AceFlags.INHERIT_ONLY_ACE, AceFlags.OBJECT_INHERIT_ACE Or AceFlags.CONTAINER_INHERIT_ACE Or AceFlags.INHERIT_ONLY_ACE Or AceFlags.INHERITED_ACE
                Return "Subfolders and files only"
            Case AceFlags.CONTAINER_INHERIT_ACE Or AceFlags.INHERIT_ONLY_ACE, AceFlags.CONTAINER_INHERIT_ACE Or AceFlags.INHERIT_ONLY_ACE Or AceFlags.INHERITED_ACE
                Return "Subfolders only"
            Case AceFlags.OBJECT_INHERIT_ACE Or AceFlags.INHERIT_ONLY_ACE, AceFlags.OBJECT_INHERIT_ACE Or AceFlags.INHERIT_ONLY_ACE Or AceFlags.INHERITED_ACE
                Return "Files only"
            Case Else
                ' ok... do it the hard way
                buf = "Special (0x" & Hex(flag) & "): "
                If flag And AceFlags.OBJECT_INHERIT_ACE Then
                    buf = buf & "Object,"
                End If
                If flag And AceFlags.CONTAINER_INHERIT_ACE Then
                    buf = buf & "Container,"
                End If
                If flag And AceFlags.NO_PROPAGATE_INHERIT_ACE Then
                    buf = buf & "No Propagate,"
                End If
                If flag And AceFlags.INHERIT_ONLY_ACE Then
                    buf = buf & "Inherit Only,"
                End If
                If flag And AceFlags.INHERITED_ACE Then
                    buf = buf & "Inherited,"
                End If
                If flag And AceFlags.SUCCESSFUL_ACCESS_ACE_FLAG Then
                    buf = buf & "Successful,"
                End If
                If flag And AceFlags.FAILED_ACCESS_ACE_FLAG Then
                    buf = buf & "Failed,"
                End If
                Return buf
        End Select
    End Function
End Module
0
 

Expert Comment

by:HStrix
ID: 12378404
Hello graye,
I tried to use your code
but I get some compilation errors.
"ds" and "ID" are not defined.
Can you help me out?

  Thank you.
 
   HStrix
0
 
LVL 41

Expert Comment

by:graye
ID: 12385624
Yeah, I just did a "cut-and-paste" from one of my programs... so it's not a complete solution.  That also means that it contains a lot of stuff that doesn't really pertain to the context of the example.

For example, ds is a DataSet and ID is a string...  Neither are required in the context of this example, so I'd recommend that you just comment out all of the database-related sections of the example.  Or change all of the database assignments into debug.writeline statements.  Something like:

Before:
                dr = ds.Tables("Permissions").NewRow()
                dr("ID_Perm") = ID
                dr("Perm_ID") = perm_cnt
                dr("Perm_Target") = share

After:
                'dr = ds.Tables("Permissions").NewRow()
                'dr("ID_Perm") = ID
                debug.writeline("Perm_ID: " & perm_cnt)
                debug.writeline("Perm_Target: " & share)

   
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Expert Comment

by:HStrix
ID: 12399340
Thank graye.
To get it working I also needed to insert the following definitions:
        Dim wmi As ManagementClass                
        Dim objs As ManagementObjectCollection        
        Dim obj As ManagementObject                  
        Dim MgmtPath As String                        
        Dim RemotePC As String                        
Also I removed everything related to
       ' AppSettings' and 'gui'.    

That works for the local environment.

But if I want to access mapped shares I get during execution of the following code
   RemotePC = "myremotecomputername"
   MgmtPath = "\\" & RemotePC & "\root\cimv2:"
   wmi = New ManagementClass(MgmtPath & "Win32_Share")
   objs = wmi.GetInstances()            ' <== message "System.UnAuthorizedAccesException" occurs
                                                     
I'm having mapped some shares from myremotecomputername on mylocacomputer
using user/password where user/password does not exist on the local computer.
It there a way to enumerate these mapped shares too?

HStrix


0
 

Expert Comment

by:HStrix
ID: 12401298
Sorry, that was not my target.
I thought it should be discussed if they're any outstandings.
 HStrix
0
 

Expert Comment

by:jtokach
ID: 23636454
This doesn't work correctly on Windows 2000 clients.  I was getting an math overflow.  I changed to INT64.
Public Shared Function DirectoryMaskToString(ByVal mask As Int64) As String

Also, some NTFS permissions are not resolved in the ENUM on Win2k. Share permissions are fine.
This should be LIST or READ?

  <Path>C:\Program Files</Path>
  <DACLType>NTFS</DACLType>
  <Account>BUILTIN\Users</Account>
  <Type>Allow</Type>
  <Permission>Special (0xA0000000):</Permission>

And this should be LIST or READ?

 <Path>C:\Program Files</Path>
  <DACLType>NTFS</DACLType>
  <Account>BUILTIN\Users</Account>
  <Type>Allow</Type>
  <Permission>Special (0x100000):</Permission>

Read & Execute is picked up.

  <Path>C:\Program Files</Path>
  <DACLType>NTFS</DACLType>
  <Account>BUILTIN\Users</Account>
  <Type>Allow</Type>
  <Permission>Read & Execute</Permission>
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
fix34  challenge 9 96
Order table with macro 3 75
wordsWithout 49 79
How  do I get an older program to run in Windows 10? 20 79
Here we come across an interesting topic of coding guidelines while designing automation test scripts. The scope of this article will not be limited to QTP but to an overall extent of using VB Scripting for automation projects. Introduction Now…
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

707 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

13 Experts available now in Live!

Get 1:1 Help Now