I have successfully managed to run an EWS service on a non Office 365 account,
however, using an internal office 365
public ExchangeService connectToExchange()
{
var ews = new ExchangeService(ExchangeVersion.Exchange2010_SP1)
{Credentials = new WebCredentials(authenticate.ExchangeUsername,
authenticate.ExchangePassword) };
}
try
{
ews.AutodiscoverUrl(authenticate.ExchangeURL);
}
The URL does not get set and when i hardcode a URL, where can we get this from in Office365? When I hardcode the following
url:https://mail.domain.com/EWS/Exchange.asmx");
I get the error that proxy needs to be authenticated, how can one achieve this?
Thanks:
I have managed to get this so far but still get authentication required error, how do i authenticate here?
public ExchangeService connectToExchange()
{
var ews = new ExchangeService(ExchangeVersion.Exchange2010_SP1) {Credentials = new WebCredentials(authenticate.ExchangeUsername, authenticate.ExchangePassword) };
try
{
WebProxy myproxy = new WebProxy("proxyurl", port);
myproxy.BypassProxyOnLocal = false;
myproxy.Credentials = new NetworkCredential("user","pass");
ews.WebProxy = myproxy;
ews.Url = new Uri("exchangeurl");
}
catch
{
}
return ews;
}
Almost there... proxy is correct now, the error is now:
"The request failed. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
You must create a certificate validation callback method for your application. See explanation here.
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
// Validate the server certificate.
ServicePointManager.ServerCertificateValidationCallback =
delegate(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{ return true; };
Related
From my code below, I should be getting the certificate of the mail server "mailgw.th-nuernberg.de".
That didn't work and I get the error "the handshake failed due to an unexpected packet format" by calling the method "AuthenticateAsClient".
I tried the same code with the mail server "smtp.gmail.com" on port 993. That works and I get the full certificate.
The mail server "mailgw.th-nuernberg.de" exists but I don't know why Google's mail server is working and it isn't.
Here is my Code:
X509Certificate2 cert = null;
var client = new TcpClient("mailgw.th-nuernberg.de", 25);
var certValidation = new RemoteCertificateValidationCallback(delegate (object snd, X509Certificate certificate,
X509Chain chainLocal, SslPolicyErrors sslPolicyErrors)
{
return true; //Accept every certificate, even if it's invalid
});
// Create an SSL stream and takeover client's stream
using (var sslStream = new SslStream(client.GetStream(), true, certValidation))
{
sslStream.AuthenticateAsClient("mailgw.th-nuernberg.de", null, System.Security.Authentication.SslProtocols.Tls13 | System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11, true);
var serverCertificate = sslStream.RemoteCertificate;
cert = new X509Certificate2(serverCertificate);
//System.Diagnostics.Debug.WriteLine("Heruntergeladenes Zertifikat: " + cert);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
//throw some fancy exception ;-)
}
Does anyone know what the problem is? What's the difference using the Google mail server instead of using the mail server from my University?
Hello!
I want connect to private repository. I have login and password, but program stopped in SSL Verification..
Error: Additional information: this remote has never connected
How i can fix this error?
My code:
String urls = "url";
HttpWebRequest request = HttpWebRequest.CreateHttp(urls);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => false;
Console.WriteLine(request.AuthenticationLevel);
var credentials = new UsernamePasswordCredentials
{
Username = "user",
Password = "password"
};
var remote = Repository.ListRemoteReferences("url", (url, fromUrl, types) => credentials);
foreach (var reference in remote)
{
Console.WriteLine(reference.TargetIdentifier);
}
Can you suggest how to disable the check properly when connected to a repository?
All is decided!
The error was in ignorance of the full server repository!
I am using IIS in my local machine for testing FTP with SSL connection. I am using the FluentFTP library for connecting to the FTP. I am using the following code to connect to the Server.
FtpClient conn = new FtpClient();
conn.Host = firewallSslDetails.Address;
conn.Credentials = new NetworkCredential(firewallSslDetails.UserName, firewallSslDetails.Password);
conn.SslProtocols = System.Security.Authentication.SslProtocols.Default;
X509Certificate2 cert = new X509Certificate2(#"C:\Users\BizTalk360\Desktop\FtpSites\ServerCert.cer");
conn.EncryptionMode = FtpEncryptionMode.Implicit;
conn.DataConnectionType = FtpDataConnectionType.AutoActive;
conn.DataConnectionEncryption = true;
conn.EnableThreadSafeDataConnections = false;
conn.ClientCertificates.Add(cert);
conn.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
conn.Connect();
The server is returning me with the following error.
FluentFTP.FtpCommandException: Policy requires SSL.; Win32 error: Access is denied.; Error details: SSL policy requires SSL for control channel.;
For connecting over FTP the above code is working fine and for FTP with SSL it is not working.
As you seem to be connecting to the default port 21 (no explicit port specified anywhere), you need to use the "Explicit" mode:
conn.EncryptionMode = FtpEncryptionMode.Explicit;
If the server uses a self-signed certificate, you may need to verify it programmatically. Do not blindly accept any certificate, as the answer by #Ivan does. That's a security flaw. Validate the specific certificate, e.g. by checking its fingerprint.
See FtpWebRequest "The remote certificate is invalid according to the validation procedure".
//try this ,
var cl = new FtpClient(Server, Port, User, Password);
cl.EncryptionMode = FtpEncryptionMode.Implicit;
cl.DataConnectionType = FtpDataConnectionType.AutoPassive;
cl.DataConnectionEncryption = true;
cl.SslProtocols = protocol;
cl.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
var cer = new X509Certificate2(certificate);
cl.ClientCertificates.Add(cer);
System.Net.ServicePointManager.ServerCertificateValidationCallback = ServerCertificateValidationCallback;
client.Connect();
void OnValidateCertificate(FtpClient control, FtpSslValidationEventArgs e)
{
// add logic to test if certificate is valid here
e.Accept = true;
}
private bool ServerCertificateValidationCallback(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
Currently I am working in POC with CRUD operations using AmazonS3 Sdk for .net 3.5 version 3. I am trying to retrieve the Region Endpoint(Location) of the specific bucket name using secret key and Access Key and bucket name( has Location: EU (Frankfurt) (eu-central-1)). in order to establish connection
with AmazonS3 and perform CRUD operations
So I get the A WebException with status TrustFailure was thrown when I tried to get the Region Endpoint from share point(web page I create my own page using the master page of SharePoint) in order to create AmazonS3Client instance with Region Retrieve.
with the following code:
private string defaultAmazonHttpsHost = "https://s3.amazonaws.com";
private string defaultAmazonHttpHost = "http://s3.amazonaws.com";
private Amazon.RegionEndpoint GetRegionEndpoint(string bucket, BasicAWSCredentials amazonCredentials, bool useSSL)
{
Amazon.RegionEndpoint regiongEndpoint = null;
AmazonS3Config configurationClient = new AmazonS3Config();
configurationClient.UseHttp = !useSSL;
configurationClient.ServiceURL = useSSL ? defaultAmazonHttpsHost : defaultAmazonHttpHost;
try
{
using (AmazonS3Client clientConnection = new AmazonS3Client(amazonCredentials, configurationClient))
{
GetBucketLocationRequest locationRequest = new GetBucketLocationRequest();
locationRequest.BucketName = bucket;
string locationName = clientConnection.GetBucketLocation(locationRequest).Location.Value;
if (locationName.Equals("EU", StringComparison.InvariantCultureIgnoreCase))
{
regiongEndpoint = Amazon.RegionEndpoint.EUWest1;
}
else if (string.IsNullOrEmpty(locationName))
{
regiongEndpoint = Amazon.RegionEndpoint.USEast1;
}
else
{
regiongEndpoint = Amazon.RegionEndpoint.GetBySystemName(locationName);
}
}
}
catch (AmazonS3Exception amazonS3Exception)
{
throw amazonS3Exception;
}
catch (Exception unExpectedException)
{
throw unExpectedException;
}
return regiongEndpoint;
}
BasicAWSCredentials credentials = new BasicAWSCredentials("my access Key", "my secret key");
AmazonS3Config configurationAmazon = new AmazonS3Config();
configurationAmazon.RegionEndpoint = GetRegionEndpoint("bucketName", credentials, false);
AmazonS3Client _s3 = new AmazonS3Client(credentials, configurationAmazon );
My task Perform CRUD operations + test connection with AmazonS3 Sdk .net 3.5 version 3 , with the source information :
-secret key
- access key
- bucket Name
the strange is if this part code run(execute) since another Project (without share point interaction for example: Console Project) I do not get this exception) Do you know what is the problem?
I used the following before execute any request to amazonS3 and now it works as expected I think the problem was with the certificates that sharepoint is using .
ServicePointManager.ServerCertificateValidationCallback +=
delegate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
};
the post provide a explanation about it
The key point here is "TrustFailure". There's something wrong with the certificate. In my case, this error was caused because my company uses Websense, a web filter/security suite that intercepts and reissues https certificates for web traffic so it can spy on you. Even if you don't use anything like that, the bottom line is that your computer doesn't trust the issuer of the certificate being used by the remote computer. The server on which I was receiving this error did not have the correct certificate in its Trusted Root Certification Authorities. After importing the correct trusted root cert (Add trusted root certificate authority to local computer), I no longer received the error.
If you don't think this is the case, you can get more details on what the exception is by either writing the details to console or putting a breakpoint on the Console.WriteLine here and actually inspect the certificate and ssl errors:
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
.....
.....
//before you make the request
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
delegate (
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
Console.WriteLine("Subject: " + certificate.Subject + ", Issuer: " + certificate.Issuer + ". SSL Errors: " + sslPolicyErrors.ToString());
return false;
};
The key point here is that you need to find the certificate issue and resolve it instead of leaving yourself vulnerable by ignoring all ssl errors.
TrustFailure can also be caused by the date being incorrect on the machine.
I have seen code samples of how to use WebRequestHandler with HttpClient to embed a certificate in my http request (see snippet below). However, I just tested this with a self-signed cert and it is not working. According to this post this method will not work without a trusted certificate.
I can see the certificate on the server if I send it through the browser or Postman, but not programmatically.
Can someone confirm or deny if HttpClient or WebRequestHandlerperform any kind of certificate validation before sending it as part of the request?
A quick de-compile did not show anything obvious, but there are many things in play along the request pipeline.
Sample code:
var cert = new X509Certificate2(rawCert);
//This call fails, cannot check revocation authority.
//Specific error: The revocation function was unable to check
//revocation for the certificate.
//X509CertificateValidator.ChainTrust.Validate(cert);
var certHandler = new WebRequestHandler()
{
ClientCertificateOptions = ClientCertificateOption.Manual,
UseDefaultCredentials = false
};
certHandler.ClientCertificates.Add(cert);
var Certificateclient = new HttpClient(certHandler)
{
BaseAddress = new Uri("https://web.local")
};
var response = await Certificateclient.GetAsync("somepath");
To use a self signed cert, you can add using System.Net.Security;
add a handler callback method
public static bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
and set before invoke the API:
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
See:
https://es.stackoverflow.com/a/153207/86150
https://social.msdn.microsoft.com/Forums/es-ES/130308da-4092-4f21-8355-ee3c77a22f97/llamar-web-service-con-certificado?forum=netfxwebes