IIS Blocking My Request. Could not create SSL/TLS secure channel - vb.net

When i make third party request to some URL then IIS gives me error:
The request was aborted: Could not create SSL/TLS secure channel.
however i am able to make request to same URL from console application and Postman.
Dim certificates As X509Certificate2 = New X509Certificate2()
Dim uriPath As String = "D:\CertificateFolder\MyCert.cer"
Dim localPath As String = New Uri(uriPath).LocalPath
certificates.Import(localPath)
Dim sResult As String = ""
Dim activeProtocol As SecurityProtocolType =
ServicePointManager.SecurityProtocol
Try
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or
SecurityProtocolType.Tls11
Dim oRequest As HttpWebRequest =
WebRequest.Create("https://test.com/router.dll")
oRequest.KeepAlive = False
oRequest.Method = "POST"
oRequest.ContentType = "text/xml"
Dim Test As String = "some xml"
Dim bytes As Byte() = Text.Encoding.UTF8.GetBytes(Test)
oRequest.ContentLength = bytes.Length
oRequest.ClientCertificates = New X509CertificateCollection({certificates})
Dim oWriter As StreamWriter
Try
Dim streamToSend As Stream = oRequest.GetRequestStream()
oWriter = New StreamWriter(oRequest.GetRequestStream())
streamToSend.Write(bytes, 0, bytes.Length)
streamToSend.Close()
Catch up As Exception
Return
Finally
End Try
Dim oResponse As HttpWebResponse = oRequest.GetResponse()
Dim oReader As New StreamReader(oResponse.GetResponseStream())
sResult = oReader.ReadToEnd
oReader.Close()
Catch
' do nothing for now
Finally
ServicePointManager.SecurityProtocol = activeProtocol
End Try
Note* Method in URL is not file. Method name has .dll just as name of method.
I am using .net framework 4.5

Do you have access to the server management?
Could you first try to connect without providing the client certificate?
Remove the corresponding part from your code and turn off the client certificate requirement in the IIS management console.
If the error still persist, find out which cipher suits the client supports and which the server. If they don't much an error similar to yours would occur.
To check the client, rewrite your code to connect to the following site:
"https://howsmyssl.com/a/check"
If your server you are connection to is public (internet visible), you can use the following site to check its supported cipher suits:
https://www.ssllabs.com/ssltest/

Related

error 'The given key was not present in the dictionary' when trying to API HTTP request token with Blue Prism

Im trying to use the Blue Prism object HTTP request to get an access token for further processing the items. However, i couldn't manage to get the token due to the error 'The given key was not present in the dictionary'. I have looked all parameters and still didn't manage to solve the issue. I use a built in visual basic code to get the result as a collection which is later parsed to JSON to get the token.
The underlying visual basic code is:
Dim request As WebRequest = WebRequest.Create(addressURL)
If forcePreAuth Then
'Sometimes a web server will require the authorisation header in the initial request
'In which case we have to add the basic authorization header manually.
Dim bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}",username,password))
Dim base64 As String = Convert.ToBase64String(bytes)
request.Headers.Add("Authorization", "Basic " & base64)
Else
If Not String.IsNullOrEmpty(username) AndAlso Not String.IsNullOrEmpty(password) Then
request.Credentials = New NetworkCredential(username,password)
End If
End If
If useProxy Then
Dim proxyURI As New Uri(proxyURL)
Dim proxy As New WebProxy(proxyURI, True)
Dim proxyCred As New NetworkCredential(proxyUsername, proxyPassword)
Dim credCache As New CredentialCache()
credCache.Add(proxyURI, "Basic", proxyCred)
proxy.UseDefaultCredentials = False
proxy.Credentials = credCache
request.Proxy = proxy
End If
request.Method = method
request.ContentType = contentType
Dim httpRequest As HttpWebRequest = TryCast(request, HttpWebRequest)
If httpRequest IsNot Nothing Then
If Not String.IsNullOrEmpty(accept) Then
httpRequest.Accept = accept
End If
If Not String.IsNullOrEmpty(certID) Then
httpRequest.ClientCertificates.Add(m_Certificates(certID))
End If
End If
For Each r As DataRow In headers.Rows
For Each c As DataColumn In headers.Columns
Dim columnName As String = c.ColumnName
Dim val As String = r(columnName).ToString
request.Headers.Add(columnName,val)
Next
Exit For 'Only one row is allowed
Next
If Not String.IsNullOrEmpty(body) Then
Dim requestStream As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(requestStream, New Text.UTF8Encoding(False))
sw.Write(body)
End Using
End If
Using response As WebResponse = request.GetResponse()
Dim responseStream As IO.Stream = response.GetResponseStream()
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd()
End Using
Screenshots:
Input parameter
Input parameter request token
Request token:
Output parameter:
Blue Prism uses a bit of a peculiar pattern regarding Certificates. The way the Utility - HTTP object is designed is to allow for the loading of certificate files (.cer, etc) on-the-fly into a local Certificate Store, which assigns a new Certificate ID each time.
Before firing your HTTP Request, use the Load Certificate action within the same Utility - HTTP object to output a valid Certificate ID, which you can then pass to HTTP Request's Certificate ID parameter.

Retrieve API JSON (https) with VB.NET (ERROR: Canceled the request: Unable to create a secure SSL / TLS channel)

I'm trying to query an API from my vb.net code but at the time of executing the "GetResponse" it gives the error "Canceled the request: Unable to create a secure SSL / TLS channel"
I have modified many things of the code tried to solve my problem but nothing works ...
I attach the code that I have to see if someone can fix it
Dim request As HttpWebRequest = HttpWebRequest.Create("https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/1917/departing/2018/11/19?appId=583f892b&appKey=e960901ec7dcb40321306743b7a364d0")
request.Proxy = Nothing
request.UserAgent = "Test"
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
Dim response As HttpWebResponse = request.GetResponse
Dim response_stream As System.IO.Stream = response.GetResponseStream
Dim stream_reader As New System.IO.StreamReader(response_stream)
Dim Data As String = stream_reader.ReadToEnd
stream_reader.Close()
MsgBox(Data)
_
Public Function AcceptAllCertifications(ByVal sender As Object, ByVal certification As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
Return True
End Function
In the code you have the address of the api tal as I want to consult it
Add this before your request:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

Having trouple uploading to virtual directory via http in vb.net

Trying to upload an image to HTTP virtual directory and I keep getting this exception:
A first chance exception of type 'System.Net.WebException' occurred in System.dll
at System.Net.HttpWebRequest.GetResponse()
Dim mFileStream As New FileStream("/Image Location/", FileMode.Open)
Dim mRequest As WebRequest = WebRequest.Create("/URL/")
mRequest.Headers.Set("filename", "new name")
mRequest.Proxy = New WebProxy("/URL/", True)
mRequest.Method = "POST"
mRequest.ContentLength = mFileStream.Length
Dim mCredentials As New NetworkCredential
mCredentials.Password = "/pass/"
mCredentials.UserName = "/Login Name/"
mRequest.Credentials = mCredentials
Dim mData(mFileStream.Length - 1) As Byte
mFileStream.Read(mData, 0, mFileStream.Length)
mFileStream.Close()
Using dataStream As Stream = mRequest.GetRequestStream()
dataStream.Write(mData, 0, mData.Length)
dataStream.Close()
End Using
Dim mResponse As HttpWebResponse = CType(mRequest.GetResponse(), HttpWebResponse)
mResponse.Close()
Upon further investigation, I have found the reason for the WebException is:
ProtocolError The remote server returned an error: (405) Method Not Allowed.
The answer was quite simple despite everything i tried
you have to specify the file name in the url
Dim mRequest As WebRequest = WebRequest.Create("/URL/")
to
Dim mRequest As WebRequest = WebRequest.Create("/URL/" & FileName & FileExtention)
ex:
Dim mRequest As WebRequest = WebRequest.Create("http://1.1.1.1/niveimage.png")

ReCAPTCHA closing Underlying connection

Running my ReCAPTCHA routine in VS2012 (VB.Net), I get the error
The underlying connection was closed. An unexpected error occurred on
a receive
This code has been working for several weeks, and now this week has decided to give me the above error.
Can somebody give me an idea of what the problem is? Thanks!
Here is my code:
Dim recaptchaResponse As String = Request.Form("g-recaptcha-response")
If Not String.IsNullOrEmpty(recaptchaResponse) Then
Dim request As Net.WebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret={MySecretKey}&response=" + recaptchaResponse)
request.Method = "POST"
request.ContentType = "application/json; charset=utf-8"
Dim postData As String = ""
'get a reference to the request-stream, and write the postData to it
Using s As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(s)
sw.Write(postData)
End Using
End Using
'**This next line of code triggers the error**
Using s As IO.Stream = request.GetResponse().GetResponseStream()
Using sr As New IO.StreamReader(s)
'decode jsonData with javascript serializer
Dim jsonData = sr.ReadToEnd()
If jsonData.IndexOf("{" & vbLf & " ""success"": true,") > -1 Then
Return True
Else
lblError.Text = jsonData
End If
End Using
End Using
The inner exception is:
System.ComponentModel.Win32Exception (0x80004005): The client and server cannot communicate, because they do not possess a common algorithm at System.New.SSPIWrapper.AcquireCredentialsHandle
I discovered that the network admin guys decided to implement the ban on TLS 1.0 protocol without telling me.
The fix for this problem is to ensure that ReCAPTCHA communicates via TLS 1.2. This was accomplished with an extra line of code at the top of the routine:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

VB.NET - Salesforce POST Request returns 400 Bad Request Error

NOTE: I've never written vb.net code before this. I've googled for a solution but did not find anything that worked.
I'm trying to get access token from Salesforce. Below code worked just yesterday. And I have no idea why it is not working today. I've tried adding content-type as application/x-www-form-urlencoded but it did not work either. When I use curl I'm able to get access token. Also I'm able to get access token using advanced rest client in google chrome. Any ideas why it is returning 400 Bad Request unknown error retry your request?
Imports System.Collections.Specialized
Imports System.Net
Imports System.Text
Module Module1
Sub Main()
Dim clientId As String = "clientId"
Dim clientSecret As String = "clientSecret"
Dim redirectUri As String = "https://test.salesforce.com"
Dim environment As String = "https://test.salesforce.com"
Dim tokenUrl As String = ""
Dim username As String = "username#salesforce.com"
Dim password As String = "passwordtoken"
Dim accessToken As String = ""
Dim instanceUrl As String = ""
Console.WriteLine("Getting a token")
tokenUrl = environment + "/services/oauth2/token"
Dim request As WebRequest = WebRequest.Create(tokenUrl)
Dim values As NameValueCollection = New NameValueCollection()
values.Add("grant_type", "password")
values.Add("client_id", clientId)
values.Add("client_secret", clientSecret)
values.Add("redirect_uri", redirectUri)
values.Add("username", username)
values.Add("password", password)
request.Method = "POST"
Try
Dim client = New WebClient()
Dim responseBytes As Byte() = client.UploadValues(tokenUrl, "POST", values)
Dim response As String = Encoding.UTF8.GetString(responseBytes)
Console.WriteLine(response)
Console.ReadKey()
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.WriteLine("Press any key to close")
Console.ReadKey()
End Try
End Sub
End Module
Well, appearently problem was about TLS version mismatch. All Salesforce sandboxes refuse TLS 1.0 connections. Our vb.net test code was using TLS 1.0 thus returning an error. It would be great if Salesforce would return better error code.
All I needed to do was add a line of code on top of the code block:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11