Solved

Attempt to connect to network share with wnetaddconnection2 fails error 1326

Posted on 2010-08-31
9
2,645 Views
Last Modified: 2012-05-10
I am trying to connect to a network resource using WNETaddconnection2. The function keeps returning error 1326 which is LOGON FAILURE, when I try to connect to \\COMPUTER\SHARE.  I am using VB .NET 2003.

I can run NET USE \\COMPUTER\SHARE /USER:myuname  from the command line and it succeeds.  The default user name and password combination (myuname, mypass) is a valid user on the network resource.  

Following is all of the declarations and code that I used.  In the procedure, CONNECT_SH(), the variable DBPATH a string and is set to "\\COMPUTER\SHARE" .  The user name is pulled from windows using the GETUSERNAME API and I can see that is set to myuname when I am debugging.    

<StructLayout(LayoutKind.Sequential)> _
    Public Structure NetResource
        Public Scope As Integer
        Public dType As Integer
        Public dDispType As Integer
        Public dUsage As Integer
        <MarshalAs(UnmanagedType.LPTStr)> _
        Public localname As String
        <MarshalAs(UnmanagedType.LPTStr)> _
        Public remotename As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=50)> _
        Public comment As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=10)> _
       Public provider As String
    End Structure

    Public Const NO_ERROR As Integer = 0
    Public Const CONNECT_LOCALDRIVE As Integer = 256
    Public Const CONNECT_REDIRECT As Integer = 128
    'DWSCOPE
    Public Const RESOURCE_CONNECTED As Integer = &H1
    Public Const RESOURCE_GLOBALNET As Integer = &H2
    Public Const RESOURCE_REMEMBERED As Integer = &H3
    'DWTYPE
    Public Const RESOURCETYPE_ANY As Integer = &H0
    Public Const RESOURCETYPE_DISK As Integer = &H1
    Public Const RESOURCETYPE_PRINT As Integer = &H2
    'DWDISPLAYTYPE
    Public Const RESOURCEDISPLAYTYPE_GENERIC As Integer = &H0
    Public Const RESOURCEDISPLAYTYPE_DOMAIN As Integer = &H1
    Public Const RESOURCEDISPLAYTYPE_SERVER As Integer = &H2
    Public Const RESOURCEDISPLAYTYPE_SHARE As Integer = &H3
    Public Const RESOURCEDISPLAYTYPE_FILE As Integer = &H4
    Public Const RESOURCEDISPLAYTYPE_GROUP As Integer = &H5

    Public Const RESOURCEUSAGE_CONNECTABLE As Integer = &H1
    Public Const RESOURCEUSAGE_CONTAINER As Integer = &H2
    Public Const CONNECT_UPDATE_PROFILE As Integer = 1

  Public Declare Auto Function WNetAddConnection2 Lib "mpr.dll" _
       Alias "WNetAddConnection2" (ByRef lpNetResource As NetResource, _
                                    ByVal lpPassword As String, _
                                    ByVal lpUsername As String, _
                                    ByVal dwFlags As Integer) As Integer

    Public Declare Function GetUserName Lib "advapi32.dll" Alias _
         "GetUserNameA" (ByVal lpbuffer As String, _
                         ByRef nsize As Integer) As Integer

  Public Function ConnectSh() As Boolean

        Dim x, lans As Integer
        Dim lclu, lclp, dsource As String
        Dim ldate As Date
        Dim netrs As Win32API.NetResource
      Dim nullstr, lpw, lun, utemp As String
        nullstr = Chr(0)

        netrs.localname = nullstr
        netrs.provider = nullstr
        netrs.remotename = dbpath + Chr(0)
        netrs.comment = nullstr
        netrs.dType = Win32API.RESOURCETYPE_DISK
      '  netrs.Scope = Win32API.RESOURCE_GLOBALNET
      netrs.Scope = 0
      netrs.dDispType = Win32API.RESOURCEDISPLAYTYPE_SHARE
        netrs.dUsage = Win32API.RESOURCEUSAGE_CONNECTABLE

         utemp = New String(CChar(" "), 50)
         lans = Win32API.GetUserName(utemp, 50)
         lun = utemp
         lpw = ""
 
      lans = Win32API.WNetAddConnection2(netrs, lpw, lun, 0)
      If lans = 0 Then
         Return True
      Else
         Return False
      End If
    End Function

I have tried numerous variations of the code

   1. Setting lun to "myuname"

   2. Setting lun to "myuname" + nullstr

   3. Setting lpw to nullstr (With each of the combinations above)

Again I can go to the command line and type

   NET USE \\COMPUTER\SHARE /USER:myuname  and it connects to the resource.

Any ideas???????????

 

0
Comment
Question by:knk53
  • 6
  • 3
9 Comments
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33567538
Try using something like this..

Imports System.Runtime.InteropServices

Imports System.ComponentModel



Public Class Form1



    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Try

            WNet.AddConnection("user", "password", "\\192.168.1.101\share", "r:\")

            Debug.Print("AddConnection - Success")

        Catch ex As Win32Exception

            Debug.Print("code={0} message={1}", ex.ErrorCode, ex.Message)

        End Try



    End Sub

End Class



Public Class WNet

    Private Const NO_ERROR As Integer = 0



    Private Enum WNetType As Integer

        RESOURCETYPE_ANY

        RESOURCETYPE_DISK

        RESOURCETYPE_PRINT

        RESOURCETYPE_RESERVED

    End Enum



    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _

    Public Structure NETRESOURCE

        Dim dwScope As Integer

        Dim dwType As Integer

        Dim dwDisplayType As Integer

        Dim dwUsage As Integer

        Dim lpLocalName As String

        Dim lpRemoteName As String

        Dim lpComment As String

        Dim lpProvider As String

    End Structure



    <DllImport("mpr.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _

    Private Shared Function WNetAddConnection2(ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUsername As String, ByVal dwFlags As Integer) As Integer

    End Function



    <DllImport("mpr.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _

    Private Shared Function WNetCancelConnection2(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer

    End Function





    Private Shared _pRemote As String = String.Empty

    Private Shared _pLocal As String = String.Empty



    Public Shared Sub AddConnection(ByVal userName As String, ByVal password As String, ByVal remoteName As String, ByVal localName As String)



        Dim nr As NETRESOURCE = Nothing

        Dim dwResult As Integer = NO_ERROR



        _pLocal = localName

        _pRemote = remoteName



        nr.lpRemoteName = remoteName

        nr.lpLocalName = localName

        nr.dwType = WNetType.RESOURCETYPE_ANY



        dwResult = WNetAddConnection2(nr, password, userName, 0)



        If dwResult <> NO_ERROR Then

            Throw New Win32Exception(Marshal.GetLastWin32Error)

        End If



    End Sub



    Public Shared Sub CancelConnection(ByVal szName As String)

   

        Dim dwResult As Integer = NO_ERROR



        dwResult = WNetCancelConnection2(szName, 0, 1)



        If dwResult <> NO_ERROR Then

            Throw New Win32Exception(Marshal.GetLastWin32Error)

        End If



    End Sub



    Public Shared ReadOnly Property LocalName() As String

        Get

            Return _pLocal

        End Get

    End Property



    Public Shared ReadOnly Property RemoteName() As String

        Get

            Return _pRemote

        End Get

    End Property



End Class

Open in new window

0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33567677
My bad.. There shouldn't be a trailing backslash in the example. (See code section)
WNet.AddConnection("username", "password", "\\192.168.1.104\share", "R:")

Open in new window

0
 
LVL 2

Author Comment

by:knk53
ID: 33568371
eql1044,
   That responded with the same error.  1326.   How should I call the function if I want to use the default user name and password?   Also, I dont want a drive letter just the resource.    
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33568623
If you don't want a drive letter you dont have to specify the local name (see code section)
There is a couple of things you will want to make sure that your credentials are correct. It wouldn't hurt either to go to the computer that is hosting the share and remove it then re-enable. Then try again with the correct credentials.

' To add resource without drive.

WNet.AddConnection("user", "password", "\\192.168.1.104\shared", Nothing)



' To close that connection

WNet.CancelConnection(WNet.RemoteName)

Open in new window

0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 2

Author Comment

by:knk53
ID: 33568747
I sent
   WNET.AddConnection("myusername","","\\mycomputer\share","")
this responds with error 1326.
******************************************************
 I can go to the command line and type
NET USE \\mycomputer\share /user:myusername <enter>  then type
NET USE  <enter>   and see
STATUS                                  LOCAL                     REMOTE
  OK                                                                              \\mycomputer\share
 
I know the credentials are working, but why does wnetaddconnection2 return an error???
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33568937
You might have to specify a password if you didnt add the everyone group or anonymous logon group permissions to the share. How is your share setup with groups/permissions?
Everyone group does not include anonymous security identifier.
http://support.microsoft.com/kb/278259
0
 
LVL 29

Accepted Solution

by:
nffvrxqgrcfqvvc earned 500 total points
ID: 33569052
BTW: I noticed your using "" which might cause the function to fail. Use the example in the code block.
' Correct way to call this method.

WNet.AddConnection("user", Nothing, "\\192.168.1.104\shared", Nothing)

Open in new window

0
 
LVL 2

Author Comment

by:knk53
ID: 33569380
I tried your calling method and it did work with the word NOTHING.  Then I replaced the word Nothing with the "" and it still passed.   I think the NOTHING is the correct answer.   It is possible that, once you have logged onto a share using the API the next time you logon it may accept the "".
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33569481
That appears to be the case because you are already connected so it might not even verify the password in that case. If you cancel the connection then it wouldn't already exists and would most likely fail using "" when working with the API you need make sure you pass NULL string which can be accomplished using Nothing OR vbNullString.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

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