Access Denied issue when connecting to XERO using oAuth2.0 - vb.net

I am creating an application that will allow a user to send Invoices from a local database application to XERO.
Connection works fine when running on my machine at the office but when I port it to the clients terminal server I get this error.
System.Net.HttpListenerException (0x80004005): Access is denied
at System.Net.HttpListener.AddAllPrefixes()
at System.Net.HttpListener.Start()
at XeroConnectionTest.clsXeroAuth2.VB$StateMachine_6_oauth2.MoveNext() in Q:\XeroConnectionTest\XeroConnectionTest\clsXeroAuth2.vb:line 21
This is the code where it fails
Private callbackurl As String = "http://localhost:5000/signin/"
Public Async Function oauth2() As Task(Of Boolean)
Dim redirectUri As String = String.Format(callbackurl)
Dim listener = New HttpListener()
listener.Prefixes.Add(redirectUri)
Try
listener.Start()
stopListening = False
Catch hlex As HttpListenerException
'MsgBox(hlex.ToString)
Form1.TextBox1.Text = hlex.ToString
Return False
End Try
and the error occurs on listener.start() line.
Any help would be gratefully received
Thanks
Frostie

Related

vb.net WebClient.DownloadString fails with exception

I am working on a program in VS 2017 coding in VB.Net. The program downloads Web pages using Net.WebClient.DownloadString and then parses the data. It worked fine for a year or more then one day I started getting an exception when downloading the pages.
The ex.Message is: 'The underlying connection was closed: An unexpected error occurred on a send.'
The ex.InnerException.Message is: 'Unable to write data to the transport connection: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.'
I have VS 2017 installed on 2 other PC's at this location and on 1 at another location. They all continue to run the code without exception. It is only an issue on this PC.
The code is below (I changed the Web address but it fails for any valid URL).
Any ideas why this fails on my main PC only?
Public Function DownloadData() As Boolean
Dim strURL As String = "https://www.google.com/"
Dim strOutput As String
Try
Using WC As New Net.WebClient
strOutput = WC.DownloadString(strURL)
If strOutput.Length > 0 Then
If ParseData(strOutput) = True Then
Return True
End If
Else
Return False
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.InnerException.Message, "Error")
End Try
End Function

How can I solve the issue I have with PsExec?

A method in which I test the internet connection is not working when I execute the program using PsExec.
It shows this message:
"The remote server returned an error: (403) Forbidden"**
I need to execute the application remotely, that's why I use PsExec, but when I open the program without using PsExec the method runs ok.
The command I use to execute the program with PsExec:
"D:\PsExec.exe -s -i \\MK18455 D:\RemedyHealthCheck.exe "
The method:
Public Shared Function CheckForInternetConnection(link As String) As String
Try
Dim proxy As New WebProxy("ibproxy03.intranet.ibermatica:8080", True)
proxy.UseDefaultCredentials = True
Dim request As HttpWebRequest = WebRequest.Create(link)
request.Credentials = CredentialCache.DefaultCredentials
request.Proxy = proxy
Dim response As HttpWebResponse = request.GetResponse()
If response.StatusCode = HttpStatusCode.OK Then
Return "si"
Else
Return "no"
End If
Catch e As Exception
MsgBox(e.Message)
Return "no"
End Try
End Function
You are running psexec with the wrong user. when you set the -s flag you are actually running as the SYSTEM account, but your web server/proxy requires authentication. you should either allow that computer to bypass the authentication or remove the -s flag, assuming that the user running the psexec is allowed to access that webserver/proxy. another option is to manually set the -u flag to a user that is allowed. (needs a password if you are not running as that user)

vb.net async stream write/read problems

I’m after some help with a problem i have been working on for the past few days but i can't seem to get it to work correctly.
I have multiple clients connecting to a server, the server needs to keep a list of connected clients and remove them from the list if the client disconnects, I have this bit working correctly.
Once a client is connected the server may call upon the client for some information about its state by sending a few bytes of data to which the client responds with 2 bytes of data. Based on this response the server will complete any one of number of different tasks.
I have had this working synchronously, though now I am trying to make the function asynchronous and I’m running in to an issue. The best I can tell my function that request the information from the client is completing before the client responds and is returning incorrect data, if I print the data received from the client I can see it is the correct information.
This is my 1st time working with asynchronous functions and connections so it’s highly likely I’ve got it completely wrong, I have looked at lots of example code but I can seem to find any that sheads any light on my issue.
This is what I have at the moment:
'create the collection instance to store connected clients
Private clients As New List(Of TcpClient)
'declare a variable to hold the listener instance
Private listener As TcpListener
'declare a variable to hold the cancellation token source instance
Private tokenSource As CancellationTokenSource
Private recvTsk As Task
Private Rreply As New List(Of Byte)
Private Async Sub startTCPListenerServer()
'get port from ini file
Dim netPort = SettingsIniFile.GetString("Setup", "NetworkPort", "")
While True
'create a new cancellation token source instance
tokenSource = New CancellationTokenSource
'create a new listener instance bound to the desired address and port
listener = New TcpListener(IPAddress.Any, netPort)
'start the listener
listener.Start()
While True
Try
Dim client As TcpClient = Await listener.AcceptTcpClientAsync
clients.Add(client)
Dim clientIP As String = client.Client.RemoteEndPoint.ToString
ListBox1.Items.Add(clientIP)
Try
'begin reading from the client's data stream
Using stream As NetworkStream = client.GetStream
Dim buffer(client.ReceiveBufferSize - 1) As Byte
Dim read As Integer = 1
'if read is 0 client has disconnected
While read > 0
recvTsk = New Task(Sub()
For i = 0 To read - 1
'data recived at this point is correct
Rreply.Add(buffer(i))
Next
End Sub, tokenSource.Token)
read = Await stream.ReadAsync(buffer, 0, buffer.Length, tokenSource.Token)
recvTsk.Start()
End While
'client gracefully closed the connection on the remote end
End Using
Catch ocex As OperationCanceledException
'the expected exception if this routines's async method calls honor signaling of the cancelation token
'*NOTE: NetworkStream.ReadAsync() will not honor the cancelation signal
Catch odex As ObjectDisposedException
'server disconnected client while reading
Catch ioex As IOException
'client terminated (remote application terminated without socket close) while reading
Finally
'ensure the client is closed - this is typically a redundant call, but in the
'case of an unhandled exception it may be necessary
'remove the client from the list of connected clients
clients.Remove(client)
client.Close()
ListBox1.Items.Remove(clientIP)
'remove the client's task from the list of running tasks
'clientTasks.Remove(client.Task)
End Try
Catch odex As ObjectDisposedException
'listener stopped, so server is shutting down
Exit While
End Try
End While
For i As Integer = clients.Count - 1 To 0 Step -1
clients(i).Close()
Next
tokenSource.Dispose()
End While
'signal any processing of current clients to cancel (if listening)
tokenSource.Cancel()
'abort the current listening operation/prevent any new connections
listener.Stop()
'End If
End Sub
Async Function sendToPod(message() As Byte, podNum As Integer) As Task(Of Byte)
If clients.Count = 0 Then
Else
Dim podIP As String
'get ip address as string from ini file
podIP = SettingsIniFile.GetString("NetworkSettings", "Pod" & podNum & "IP", "")
Dim currentClient As TcpClient = Nothing
For Each client As TcpClient In clients
Dim clientIP As String = (CType(client.Client.RemoteEndPoint, IPEndPoint).Address.ToString())
If clientIP = podIP Then
currentClient = client
End If
Next
If currentClient IsNot Nothing Then
'get the current client, stream, and data to write
Dim stream As NetworkStream = currentClient.GetStream
Dim buffer() As Byte = message
'wait for the data to be sent to the remote
Await stream.WriteAsync(buffer, 0, buffer.Length)
recvTsk.Wait()
Return Rreply(1)
End If
End If
End Function
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Me.TextBox1.Text = Await sendToPod({"&HAB", "&HAD", "&HFF", "&HFF"}, 1)
Catch
End Try
End Sub
End Class

ObjectDisposedException obtaining user name in SignalR event

I'm logging current SignalR connections in a sql server database. Records are added via the OnConnected and OnReconnected events and removed via the OnDisconnected event.
On deploying to our staging server I am now experiencing an intermittent issue fetching the username of the disconnected user.
This is using SignalR v2.0.3
Public Overrides Function OnDisconnected() As Threading.Tasks.Task
Try
Dim username As String = String.Empty
Try
username = Me.Context.User.Identity.Name ' this is where the error occurs
Catch ex As Exception
_logger.LogWarning(ex, EventLogEntryType.Warning)
End Try
Dim connId = Me.Context.ConnectionId
Dim referer = Me.Context.Headers("Referer")
_connService.RemoveConnection(connId)
Dim msg = New With {.username = username, .connectionId = connId, .referer = referer}
Dim hub = GlobalHost.ConnectionManager.GetHubContext(Of IncidentsHub)()
hub.Clients.All.disconnectionEvent(msg)
Catch ex As Exception
_logger.LogWarning(ex, EventLogEntryType.Error)
End Try
Return MyBase.OnDisconnected()
End Function
I have had to wrap the offending line in an additional try/catch and accept that sometimes there will be no username returned.
The exception seen is:
MOAE - System.ObjectDisposedException: Safe handle has been closed
at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
at Microsoft.Win32.Win32Native.GetTokenInformation(SafeTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength)
at System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeTokenHandle tokenHandle, TokenInformationClass tokenInformationClass)
at System.Security.Principal.WindowsIdentity.get_User()
at System.Security.Principal.WindowsIdentity.GetName()
at System.Security.Principal.WindowsIdentity.get_Name()
at MyProject.IncidentsHub.OnDisconnected() in C:\Projects\...\IncidentsHub.vb:line 95
Can anyone tell me why this is occurring and if there is a more reliable way to obtain this information?

SSHAuthenticationExcetion :No suitable authentication method found to complete authentication

I'm trying to connect on a server in vb.net win forms. I put a button and a text area to receive the data. But I'm unable to connect on the server. The server is open because i can ping it.
Private Sub SimpleButton1_Click(sender As System.Object, e As System.EventArgs) Handles SimpleButton1.Click
Dim PasswordConnection = New PasswordAuthenticationMethod("username", "pass")
Dim KeyboardInteractive = New KeyboardInteractiveAuthenticationMethod("username")
Dim ConnectionInfo = New ConnectionInfo("server.com", 22, "username", PasswordConnection, KeyboardInteractive)
Using client As New SshClient(ConnectionInfo)
client.Connect()
Dim cmd As SshCommand
Dim result As String
Dim result2 As String
cmd = client.CreateCommand("who")
cmd.CommandTimeout = TimeSpan.FromSeconds(10)
result = cmd.Execute
result2 = cmd.Error
MemoEdit1.Text = cmd.ExitStatus
If String.IsNullOrEmpty(result2) Then
MemoEdit1.Text = result2
End If
MemoEdit1.Text = result
client.Disconnect()
End Using
End Sub
Am I doing something wrong?
The program stuck directly on the "client.Connect()". As you can see im trying to connect on the event click of SimpleButton1
Normally No suitable authentication method found to complete authentication is used is returned from an SSH server when the server does not allow authentication by the offered methods by the client.
The SSH server could only allow public key authentication, or some form of two factor authentication in turn preventing password authentication. Download an SSH client like Putty and try to connect to the server directly and see what the result is.