Posts Tagged ‘TLS’

System.Security.Authentication.AuthenticationException

Friday, December 2nd, 2016

The token supplied to the function is invalid

Full exception looks like this:

System.Security.Authentication.AuthenticationException : A call to SSPI failed, see inner exception.
----> System.ComponentModel.Win32Exception : The token supplied to the function is invalid

Most likely your client tries to use TLS 1.2 but you are using old certificate on the server (e.g. signed using md5RSA algorithm).

There are 2 options for you:

  1. Regenerate the certificate (especially if it’s self-signed).
  2. Use older TLS/SSL version (TLS 1.1, TLS 1.0, SSL 3.0). You can force Mail.dll or Ftp.dll to use it using following code:

    using (XXX client = new XXX())
    {
        client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls11;
        //client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls; // TLS 1.0
        //client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3;
    
        client.ConnectSSL("host");
    
        client.Close();
    }
    
    

    Please contact your server administrator as TLS 1.1, TLS 1.0 and SSL 3.0 aren’t considered secure anymore.

The client and server cannot communicate, because they do not possess a common algorithm

Full exception looks like this:

System.Security.Authentication.AuthenticationException : A call to SSPI failed, see inner exception.
----> System.ComponentModel.Win32Exception : The client and server cannot communicate, because they do not possess a common algorithm

There are 2 possible scenarios:

  1. In most cases this means that the client is trying to use older SSL protocols like SSL 3.0, TLS 1.0 or TLS 1.1, but the remote server requires modern protocol – TLS 1.2.

    By default all our clients support TLS 1.2. Some older versions need to be told to use TLS 1.2, it is also a good practice to force TLS 1.2 only:

    using (XXX client = new XXX())
    {
        client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls12;
    
        client.ConnectSSL("host");
    
        client.Close();
    }
    
  2. Second option is the server is not supporting TLS 1.2 – you’ll need to use older protocol (TLS 1.1, TLS 1.0, SSL 3.0):
    using (XXX client = new XXX())
    {
        client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls11;
        // client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls; // TLS 1.0
        // client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3; 
    
        client.ConnectSSL("host");
    
        client.Close();
    }
    
  3. Please contact your server administrator as TLS 1.1, TLS 1.0 and SSL 3.0 aren’t considered secure anymore.

The message received was unexpected or badly formatted

Full exception looks like this:

System.Security.Authentication.AuthenticationException : A call to SSPI failed, see inner exception.
----> System.ComponentModel.Win32Exception : The message received was unexpected or badly formatted

This error generally means that something is incorrectly configured on your machine.

What you should try:

  1. Try forcing the latest TLS version (TLS 1.2):
    using (XXX client = new XXX())
    {
        client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls12;
    
        client.ConnectSSL("host");
    
        client.Close();
    }
    
  2. Use older TLS/SSL version (TLS 1.1, TLS 1.0, SSL 3.0). You can force Mail.dll or Ftp.dll to use it using following code:

    using (XXX client = new XXX())
    {
        client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls11;
        //client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls; // TLS 1.0
        //client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3;
    
        client.ConnectSSL("host");
    
        client.Close();
    }
    
    

    Please contact your server administrator as TLS 1.1, TLS 1.0 and SSL 3.0 aren’t considered secure anymore.

  3. Finally you can download IISCrypto and review “Schannel” and “Cipher Suites” tabs.

    For example we have seen clients that have TLS 1.0 turned on, but have TLS_RSA_WITH_3DES_EDE_CBC_SHA cypher suite turned off. If server requires this cypher, you’ll get this error message.

    Selecting “Best Practices” and restarting, should solve the issue.

    Please note that using TLS 1.2 and forcing your server administrator to enable TLS 1.2 is the only correct and secure way to go.

SSL vs TLS vs STARTTLS

Wednesday, October 9th, 2013

There’s often quite a confusion about the different terms: SSL, TLS, STARTTLS and STLS.

SSL and TLS

SSL and TLS are cryptographic protocols, both provide a way to encrypt communication channel between two machines over the Internet (e.g. client computer and a server). SSL stands for Secure Sockets Layer and current version is 3.0. TLS stands for Transport Layer Security and the current version is 1.2. TLS is the successor to SSL. The terms SSL and TLS can be used interchangeably, unless you’re referring to a specific protocol version.

Version numbering is inconsistent between SSL and TLSs. When TLS took over SSL as the preferred protocol name, it began with a new version number. The ordering of protocols in terms of oldest to newest is: SSLv2, SSLv3, TLSv1.0, TLSv1.1, TLSv1.2.

STARTTLS and STLS

STARTTLS is a protocol command, that is issued by an email client. It indicates, that the client wants to upgrade existing, insecure connection to a secure connection using SSL/TLS cryptographic protocol. STARTTLS command name is used by SMTP and IMAP protocols, whereas POP3 protocol uses STLS as the command name.

Despite having TLS in the name, STARTTLS doesn’t mean TLS will be used. Both SSL and TLS are acceptable protocols for securing the communication.

Clear text/Plain text

No security protocol is used at all. All commands, responses and data are transferred in plain text.

client.Connect("mail.example.com");

Implict SSL mode

Implict SSL mode means, that you connect to SSL/TLS encrypted port.

client.ConnectSSL("mail.example.com");

Explicit SSL mode

Explicit SSL mode means, that you connect to plaint text port and secure the connection by issuing STARTTLS (or STLS) command afterwards (you explicitly secure the connection).

client.Connect("mail.example.com");
client.StartTLS();

Securing the connection

Regardless of whether you use implict (connecting to an SSL/TLS encrypted port) or explicit (using STARTTLS to upgrade an existing connection) mode, both sides will negotiate which protocol and which version to use. This negotiation is based on how client and server have been configured and what each side supports.

SSL/TLS support

Support for SSL/TLS is virtually universal, however which versions are supported is variable. Pretty much everything supports SSLv3. Most machines support TLSv1.0.

TLS vs STARTTLS naming problem

One significant complicating factor is that some email software incorrectly uses the term TLS when they should have used “STARTTLS” or “explicit SSL/TLS”. Older versions of Thunderbird used “TLS” to mean “enforce use of STARTTLS to upgrade the connection, and fail if STARTTLS is not supported” and “TLS, if available” to mean “use STARTTLS to upgrade the connection, if the server advertises support for it, otherwise just use an insecure connection” (very problematic, as we’ll see below).

Port numbers

To add security to some existing protocols (IMAP, POP3, SMTP), it was decided to just add SSL/TLS encryption as a layer underneath the existing protocol. However to distinguish that software should talk the SSL/TLS encrypted version of the protocol rather than the plaintext one, a different port number was used for each protocol:

Protocol Plain text SSL
IMAP 143 993
POP3 110 995
SMTP 587 or 25 465

Too many ports? Solution: Plain text + STARTTLS

At some point, it was decided that having 2 ports for every protocol was wasteful, and instead it’s better to have 1 port, that starts off as plain text, but clients can upgrade the connection to an SSL/TLS encrypted one using STARTTLS (or STLS for POP3 protocol) command.

STARTTLS problems

There were a few problems with this. There exists lots of software, that used the alternate port numbers with pure SSL/TLS connections. Client software can be very long lived, so you can’t just disable the encrypted ports until all software has been upgraded.

Each protocol received mechanisms to tell clients that the server supported upgrading to SSL/TLS (e.g. STARTTLS in IMAP’s CAPABILITY response), and that they should not attempt to login without doing the STARTTLS upgrade (LOGINDISABLED in IMAP’s CAPABILITY response). This created two unfortunate situations:

  • Some software just ignored the “login disabled until upgraded” announcement (LOGINDISABLED, STARTTLS) and just tried to log in anyway, sending the user login name and password over clear text channel. The server rejected the login and password, but the details had already been sent over the Internet in plain text.
  • Other software saw the “login disabled until upgraded” announcement, but then wouldn’t upgrade the connection automatically, and thus reported login errors back to the user, which caused confusion about what was wrong.
    • Both of these problems resulted in significant compatibility issues with existing clients, and so most system administrators continued to just use plain text connections on one port, and encrypted connections on a separate port number.

      Disable plain text for IMAP and POP3

      Many companies (e.g. Gmail, Outlook.com) disabled plain IMAP (port 143) and plain POP3 (port 110), so people must use a SSL/TLS encrypted connection – this removes the need for having STARTTLS command completely.

      SMTP STARTTLS stays

      The one real exception to the above is SMTP. Most email software used SMTP on port 25 to submit messages to the email server for onward transmission to the destination. However SMTP was originally designed for transfer, not submission. So yet another port (587) was defined for message submission.

      Port 587 doesn’t mandate requiring STARTTLS, however the use of port 587 became popular around the same time as the realization that SSL/TLS encryption of communications between clients and servers was an important issue. The result is that most systems, that offer message submission over port 587 require clients to use STARTLS to upgrade the connection. Login and password to authenticate is also required.

      There has been an additional benefit to this approach as well. By moving users away from using port 25 for email submission, ISPs can block outgoing port 25 connections from users’ computers, which were a significant source of spam, due to user computers infected with spam sending viruses.

      Further reads

      Using SSL/TLS with IMAP
      Using SSL/TLS with SMTP
      Using SSL/TLS with POP3

The handshake failed due to an unexpected packet format

Tuesday, August 13th, 2013

Most likely your server requires explicit SSL, sometimes also known as TLS.

It is called explicit SSL mode, because after the connection is established, client explicitly issues a command to the server that initiates SSL/TLS negotiation.

This is in contrast to implicit SSL mode, where SSL negotiation is initiated just after successful connection. In implicit mode server and client knows to use SSL, because client uses default protocol port, that is commonly used for secured traffic.

First try to connect to your server without SSL:

// C#

client.Connect("mail.example.com");
' VB.NET

client.Connect("mail.example.com")

Then, before logging-in, start explicit SSL negotiation. The command name differs for different protocols:

Explicit SSL (aka TLS)

The code is exactly the same no matter which protocol (IMAP, POP3 or SMTP) you use.

// C#

client.Connect("mail.example.com");
client.StartTLS();
' VB.NET

client.Connect("mail.example.com")
client.StartTLS()

StartTLS method negotiates security protocol with the server and secures the channel using SSL or TLS. Now, your connection is secured.

Here you can find more details on SSL vs TLS vs STARTTLS.

Please note, that your server may not need SSL/TLS at all. In such case simply use Connect method.

Enabled SSL Protocols

On very rare occasions “handshake failed…” error may indicate that TLS is incorrectly configured on the client machine or on the server.

It is possible to force SSL v3.0 usage instead of TLS in explicit mode:

// C#

client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3;
client.Connect("mail.example.com");
client.StartTLS();
' VB.NET

client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3;
client.Connect("mail.example.com");
client.StartTLS();

It is also possible to force SSL v3.0 usage instead of TLS in implicit mode:

// C#

client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3;
client.ConnectSSL("mail.example.com");
' VB.NET

client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3;
client.ConnectSSL("mail.example.com");

Self-signed certificates

Remember that you can ignore SSL certificate errors using ServerCertificateValidate event:

// C#

static void Validate(
    object sender,
    ServerCertificateValidateEventArgs e)
{
    const SslPolicyErrors ignoredErrors =
        SslPolicyErrors.RemoteCertificateChainErrors |
        SslPolicyErrors.RemoteCertificateNameMismatch;

    if ((e.SslPolicyErrors & ~ignoredErrors) == SslPolicyErrors.None)
    {
        e.IsValid = true;
        return;
    }
    e.IsValid = false;
}

client.ServerCertificateValidate += Validate;
client.Connect...
' VB.NET

Private Sub ValidateCerificate( _
    ByVal sender As Object, _
    ByVal e As ServerCertificateValidateEventArgs)

    Const ignoredErrors As SslPolicyErrors = _
        SslPolicyErrors.RemoteCertificateChainErrors Or _
        SslPolicyErrors.RemoteCertificateNameMismatch

    If (e.SslPolicyErrors And Not ignoredErrors) = SslPolicyErrors.None Then
        e.IsValid = True
        Return
    End If
    e.IsValid = False
End Sub

AddHandler client.ServerCertificateValidate, AddressOf Validate
client.Connect...

System.Net.Mail vs Mail.dll

Monday, December 17th, 2012

In this article we’ll try to describe advantages of Mail.dll over standard .NET System.Net.Mail namespace.

The fundamental difference is that with System.Net.Mail you can’t receive emails. System.Net.Mail does not have support for POP3 and IMAP protocols – two fundamental protocols for email retrieval, also .NET does not have any classes that would parse received email.

System.Net.Mail is great for sending simple emails, but Mail.dll gives you much more, even in terms of sending. You get appointments (iCal) and vCard support, you can send S/MIME signed and encrypted emails (if you plan to use EDI). It gives you easy to use template engine and VERP support out-of-the-box.

Here’s the comparison chart:

System.Net.Mail Mail.dll component
Send emails yes yes
SMTP protocol support (over SSL/TLS) yes yes
Send emails using VERP no yes
Send S/MIME encrypted emails no yes
Send S/MIME signed emails no yes
Send S/MIME signed emails (detached) no yes
Send DKIM (Domain Key Identified Mail) no yes
Templates support no yes
Receive emails no yes
IMAP protocol support (over SSL/TLS) no yes
POP3 protocol support (over SSL/TLS) no yes
Retrieve and parse emails no yes
Extract HTML, plain text, images no yes
Attachment retrieval no yes
Send and retrieve iCalendar appointments no yes
Send and retrieve vCards no yes
OAuth 1.1a/2.0 support no yes
Spam filter no yes
Bounce handling no yes
Convert HTML only emails to plain text no yes

If you need help or more information about any of these features visit Mail.dll samples.

A connection attempt failed

Monday, November 15th, 2010

If you are getting following or similar exception:
“A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond” or “No connection could be made because the target machine actively refused it.” most likely you provided incorrect server, port, and SSL usage configuration to Connect, or ConnectSSL methods.

Default ports for email protocols are:

Protocol Plain text SSL
IMAP 143 993
POP3 110 995
SMTP 587 or 25 465

Most email providers (like Gmail, Hotmail, Yahoo and others) use default ports. Connect() and ConnectSSL() and fluent interface use those ports by default.

Please ask your email server administrator for server, port, and SSL usage, if those are not standard there is no way you can guess them.

Please also make sure that:

  • your application has enough security permissions to establish connection to the server.
  • you are using correct client class with protocol you plan to use (Pop3 class with POP3 protocol, Imap class with IMAP, and Smtp class with SMTP protocol)
  • you use correct port numbers, and rely on parameter-less Connect() and ConnectSSL() methods (they use default ports) whenever possible
  • you are using ConnectSSL when you require SSL, and Connect when you don’t
  • firewall and antivirus software are disabled or configured correctly (this includes Windows Defender)
  • the protocol you are trying to use is enabled on the server. Exchange or Gmail can have some protocols disabled by default

Following articles can help you with that:

Connecting using default ports

Plain text mode

Establishing connection using default port is simple, you just need to use Connect method:

// C#

client.Connect("mail.example.com");
' VB.NET

client.Connect("mail.example.com")

Implicit SSL mode

If SSL encryption is required, use ConnectSSL method:

// C#

client.ConnectSSL("mail.example.com");
' VB.NET

client.ConnectSSL("mail.example.com")

Explicit SSL mode (aka TLS)

If your server requires explicit SSL/TLS (sometimes called TLS), you need to connect using Connect method and then use StartTLS method:

// C#

client.Connect("mail.example.com");
client.StartTLS();
' VB.NET

client.ConnectSSL("mail.example.com")
client.StartTLS()

Connecting using non-standard ports

If you need to specify different port just use overloaded version of Connect or ConnectSSL method:

// C#

client.Connect("mail.example.com", 999);
' VB.NET

client.Connect("mail.example.com", 999)

If SSL encryption is required:

// C#

client.ConnectSSL("mail.example.com", 999);
' VB.NET

client.ConnectSSL("mail.example.com", 999)

If you need to specify different port using fluent interface use OnPort() method:

// C# version

Mail.Text(@"Hello")
  .To("to@mail.com")
  .From("from@mail.com")
  .Subject("Subject")
  .UsingNewSmtp()
  .Server(_server)
  .WithSSL()
  .OnPort(443)
  .WithCredentials("user", "password")
  .Send();

SSL/TLS

Please look at following articles for details:

Some servers require explicit SSL/TLS (sometimes called TLS). Usually this triggers “The handshake failed due to an unexpected packet format” exception, when you try to connect without SSL.

If your server uses self-signed certificates you may be getting “The remote certificate is invalid according to the validation procedure” error.

Please read SSL vs TLS vs STARTTLS, if you are confused about those.

Again when in doubt please ask your email server administrator for server, port, and SSL usage.