The requested address is not valid in its context at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) - socketexception

I had purchased third party control for verify email addres From Cobisi.com. and i configured mail server ip address and port no. please see belowe.
EmailVerifier verifier = new EmailVerifier();
verifier.LocalHostFqdn = "mail.xyz.com";
verifier.LocalSenderAddress = "test#xyz.com";
verifier.LocalSmtpEndPoint = new IPEndPoint(IPAddress.Parse("10.0.0.9"), 25);
var result = verifier.Verify(objContact.ContactValue, VerificationLevel.Mailbox);
if (result.IsSuccess)
{
return true;
}
else
{
return false;
}
But when i run this code then give exception like "The requested address is not valid in its context at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) "

Related

MailKit 3.4.2 - "535: 5.7.3 Authentication unsuccessful"

I am trying to send mail to a client's Exchange server that uses NTLM authentication and am getting a "535: 5.7.3 Authentication unsuccessful" error when using port 587 and on port 465 I get this error "An error occurred while attempting to establish an SSL or TLS connection."
My development environment .Net 4.7.2
The code am using is below
// Add Content to Mime Message
var bodyBuider = new BodyBuilder();
message.Subject = subject;
bodyBuider.HtmlBody = body;
message.Body = bodyBuider.ToMessageBody();
#endregion
#region Send Mail
SmtpClient cli = new SmtpClient();
try
{
// mitigate signed exchange server certificate by an unknown certificate authority
cli.ServerCertificateValidationCallback = (s, c, h, e) => true;
cli.Connect(emailServerInfo.Host, emailServerInfo.Port, SecureSocketOptions.Auto);
// If username and Password is supplied
if (string.IsNullOrEmpty(emailServerInfo.UserName) == false)
{
if (cli.AuthenticationMechanisms.Contains("NTLM"))
{
var ntlm = new SaslMechanismNtlm(emailServerInfo.UserName, emailServerInfo.Password);
cli.Authenticate(ntlm);
}
else
{
cli.Authenticate(emailServerInfo.UserName, emailServerInfo.Password);
}
}
cli.Send(message);
}
catch (Exception ex)
{
this._audit.AddError(new Shared.Models.Audit.AuditErrorAddRequestInfo(ex));
ret.Add(ex.Message);
}
finally
{
cli.Disconnect(true);
}
#endregion
I think this code should work because I tried it with a Sendgrid and the email gets sent. I appreciate any help I can get
You probably need to disable SSL certificate revocation checks.
// mitigate signed exchange server certificate by an unknown certificate authority
cli.ServerCertificateValidationCallback = (s, c, h, e) => true;
cli.CheckCertificateRevocation = false;

Arduino UNO WiFi Rev 2 not posting to SSL connections

I've been having an issue trying to get my UNO WiFi Rev 2 to make a POST request to my https azure server. I've been able to successfully POST to this server using a MKR1000 using the WiFi101 library, so it's weird that I can't get the UNO to POST using the WiFiNINA library. I've tried two approaches to this POST request, if anybody could offer a solution to either of them, I would appreciate it.
My first attempt was based off the WiFININA libary's example for HTTPS POST:
This example creates a client object that connects and transfers
data using always SSL.
It is compatible with the methods normally related to plain
connections, like client.connect(host, port).
Written by Arturo Guadalupi
last revision November 2015
*/
#include <SPI.h>
#include <WiFiNINA.h>
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "secret"; // your network SSID (name)
char pass[] = "secret"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key index number (needed only for WEP)
int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS)
char server[] = "secret"; // name address for Google (using DNS)
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
int HTTP_PORT = 443;
String HTTP_METHOD = "POST";
char HOST_NAME[] = "secret";
//IPAddress server(secret);
String PATH_NAME = "/wtid/logCovid";
WiFiSSLClient client;
String queryString = "uuid=5555&manufacturerID=6666";
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
Serial.println("Please upgrade the firmware");
}
// attempt to connect to WiFi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to WiFi");
printWiFiStatus();
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
if (client.connect(server, HTTP_PORT)) {
Serial.println("connected to server");
// Make a HTTP request:
// MUST HAVE THESE HEADERS AND IN THIS ORDER!!!
client.println(HTTP_METHOD + " " + PATH_NAME + " HTTP/1.1");
client.println("Host: " + String(HOST_NAME));
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(queryString.length());
client.println();
// Body AKA the data we are sending to the server
client.print(queryString);
}
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting from server.");
client.stop();
// do nothing forevermore:
while (true);
}
}
void printWiFiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
Here is the Serial monitor response whenever I upload that script:
Starting connection to server...
disconnecting from server.
My second approach was using the ArduinoHttpClient with a WiFiSSLClient, but again no luck:
#include <ArduinoHttpClient.h>
#include <WiFiNINA.h>
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// WiFi Settings ///////
char ssid[] = "secret"; // your network SSID (name)
char pass[] = "secret"; // your network password (use for WPA, or use as key for WEP)
char serverAddress[] = "secret"; // server address
int port = 443;
WiFiSSLClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making POST request");
String contentType = "application/x-www-form-urlencoded";
String postData = "uuid=4444&manufacturerID=5555";
client.post("/wtid/logCovid", contentType, postData);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}
Here is the Serial monitor response whenever I upload that script:
making POST request
Status code: -2
Response:
Wait five seconds
I've updated the WiFiNINA firmware and uploaded the SSL certificates via the arduino IDE to the board as well, and I am able to make SSL GET requests to sites like google.com without issue. I do get Serial responses ensuring that I connected to the wifi, just didn't want to put that part of the Serial monitor response.
Thank you to anyone who can help!
:)

SSL connectivity to Redis with StackExchange.Redis

I am having a very weird issue with StackExchange.Redis to connect with Redis.
I have enabled SSL on Redis database and I am not able to connect from client to Redis server with SSL certificate with below code.
static RedisConnectionFactory()
{
try
{
string connectionString = "rediscluster:13184";
var options = ConfigurationOptions.Parse(connectionString);
options.Password = "PASSWORD";
options.AllowAdmin = true;
options.AbortOnConnectFail = false;
options.Ssl = true;
options.SslHost = "HOSTNAME";
var certificate = GetCertificateFromThubprint();
options.CertificateSelection += delegate
{
return certificate;
};
Connection = new Lazy<ConnectionMultiplexer>(
() => ConnectionMultiplexer.Connect(options)
);
}
catch (Exception ex)
{
throw new Exception("Unable to connect to Cache Server " + ex);
}
}
public static ConnectionMultiplexer GetConnection() => Connection.Value;
public static IEnumerable<RedisKey> GetCacheKeys()
{
return GetConnection().GetServer("rediscluster", 13184).Keys();
}
// Find certificate based on Thumbprint
private static X509Certificate2 GetCertificateFromThubprint()
{
// Find certificate from "certificate store" based on thumbprint and return
StoreName CertStoreName = StoreName.Root;
string PFXThumbPrint = "NUMBER";
X509Store certLocalMachineStore = new X509Store(CertStoreName, StoreLocation.LocalMachine);
certLocalMachineStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certLocalMachineCollection = certLocalMachineStore.Certificates.Find(
X509FindType.FindByThumbprint, PFXThumbPrint, true);
certLocalMachineStore.Close();
return certLocalMachineCollection[0];
}
However, If I create a console application and connect to Redis with above code then I am able to connect, but If I used same code from my web application to connect to redis then I am not able to connect.
Not sure if I am missing something.
Also, I went through "mgravell" post
In that post he has configured "CertificateValidation" method, In my scenario I want Redis to validate SSL certificate. so I have not implementation validation. And implemented "CertificateSelection" method to provide client certificate.
You can try to validate the cert using CertificateValidation. I tried the following code and it worked for me:
options.CertificateValidation += ValidateServerCertificate;
...
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
return false;
}
In cases like this where you are using a client certificate and it works in a console app but does not work for some other application (you don't say but I guess from an IIS hosted web app), it almost always has to do with whether the account has permission to access the private key.
The console app runs with your account which probably has access to the private key.
To give an account access
open the Local Computer certificate store
find your client certificate
right click and choose "All tasks -> Manage Provate Keys..."
click "Add..." and add the account.
Note: if your adding an IIS App Pool account the format is:
IIS APPPOOL<my app pool name>
Location should be the local machine and not a domain.
I was able to ssl the Redis server I had started on a VM with the following codes.
add stackexchange.redis visual studio
try
{
ConfigurationOptions configurationOptions = new ConfigurationOptions
{
KeepAlive = 0,
AllowAdmin = true,
EndPoints = { { "SERVER IP ADDRESS", 6379 }, { "127.0.0.1", 6379 } },
ConnectTimeout = 5000,
ConnectRetry = 5,
SyncTimeout = 5000,
AbortOnConnectFail = false,
};
configurationOptions.CertificateSelection += delegate
{
var cert = new X509Certificate2("PFX FILE PATH", "");
return cert;
};
ConnectionMultiplexer connection =
ConnectionMultiplexer.Connect(configurationOptions);
IDatabase databaseCache = connection.GetDatabase();
//set value
databaseCache.StringSet("KEYNAME", "KEYVALUE");
//get Value
label_show_value.Text = databaseCache.StringGet("KEYNAME").ToString();
}
catch (Exception e1)
{
}

I'm trying to use Jsch to establish an SSH connection in Java.I got the Exception com.jcraft.jsch.jschexception unknownhostkey

jsch.setKnownHosts(new FileInputStream(SSHHostKey));
jsch.addIdentity(SSHKey);
session = jsch.getSession(user, host, port);
if (hostKey == null)
{
session.setConfig("StrictHostKeyChecking", "no");
}
session.setPassword(pass);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
still I get the same exception.
Can anybody tell me how to get/retrive HostKey? I am using Windows.

Making HTTPS Request and opening SSL socket in JAVA

I am trying to build a login page. For that, I want to open a SSL socket and make a HTTPS request,but I'm getting Unknown Host Exception in the line
SSLSocket skt = (SSLSocket)sslsf.createSocket("https://31.21.18.222/room_info/x.txt" , 443);
Could someone please tell me what I'm doing wrong? Also, I've turned off host verification because it wont be needed in my program.
`public void clickLogin() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
URL url = new URL ("https://31.21.18.222/room_info/x.txt");
HttpsURLConnection connection = null;
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null); //Make an empty store
InputStream fis = new FileInputStream("C:/Documents and Settings/user/Desktop/PK/localhost.crt");
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
java.security.cert.Certificate cert = cf.generateCertificate(bis);
keyStore.setCertificateEntry("localhost", cert);
}
// write code for turning off client verification
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(keyStore);
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, tmf.getTrustManagers() , null);
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
SSLSocketFactory sslsf = context.getSocketFactory();
SSLSocket skt = (SSLSocket)sslsf.createSocket("https://31.21.18.222/room_info/x.txt" , 443);
skt.setUseClientMode(true);
SSLSession s = skt.getSession(); // handshake implicitly done
skt.setKeepAlive(true);
connection = (HttpsURLConnection) url.openConnection();
// Host name verification off
connection.setHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}); `
If you want to open a socket with createSocket, you need to use the host name (or IP address), not the full URL:
example : sslsf.createSocket("31.21.18.222" , 443);
In addition:
Don't use Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()) (it's there by default).
It's probably better to use TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) instead of X.509, especially because the default algorithm for the TMF is PKIX, not X.509.
createSocket will verify the certificate against the trust anchors, but won't check the host name (which is also required to prevent MITM attacks). For this, it's also generally better to use a host name instead of an IP address.