Windows test ssl connection

SSL (Secure Sockets Layer) and its successor, TLS (Transport Layer Security), are protocols designed to secure communication over a computer network. They provide authentication, encryption, and data integrity between two communicating applications. Understanding how to test SSL connections effectively serves as a prerequisite for maintaining secure communications, diagnosing issues, and ensuring regulatory compliance.

OpenSSL is a widely-used toolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols. It includes several tools for managing SSL certificates and testing SSL connections. This guide will give you a comprehensive understanding of how to use OpenSSL for testing SSL connections, including installation, commands, and examples.

What Is OpenSSL?

OpenSSL is an open-source implementation of the SSL and TLS protocols. It provides libraries and utilities for secure communications over a computer network. As a toolkit, it allows you to perform a wide range of operations, including:

  • Generating SSL certificates
  • Managing public/private key pairs
  • Encrypting and decrypting data
  • Testing SSL connections

Why Test SSL Connections?

Testing SSL connections is crucial for several reasons:

  1. Security Verification: Ensuring that your SSL certificates are valid and configured correctly to protect against man-in-the-middle attacks.
  2. Diagnostics: Identifying potential misconfigurations or issues, such as weak ciphers or expired certificates.
  3. Compliance: Adhering to industry regulations, which may require regular SSL checks.
  4. Performance: Understanding the performance of SSL connections helps optimize the security and speed of applications.

Installation of OpenSSL

Before diving into testing, you need to install OpenSSL on your environment. OpenSSL comes pre-installed on many Unix/Linux systems, while Windows may require additional steps.

For Linux

You can usually install OpenSSL using package managers such as apt for Debian-based distributions or yum for Red Hat-based distributions.

Example for Debian/Ubuntu:

sudo apt update
sudo apt install openssl

Example for Red Hat/CentOS:

sudo yum install openssl

For macOS

If you are on macOS, OpenSSL can be installed using Homebrew:

brew install openssl

For Windows

For Windows users, you may want to download a precompiled binary distribution from the OpenSSL website. Follow the installer instructions to set it up.

Testing SSL Connection

Once OpenSSL is installed, you are ready to start testing SSL connections. Here are some key commands and their usage:

1. Basic SSL Connection Test

The simplest way to test an SSL connection is by using the s_client command. The s_client command establishes a connection to a secured host and shows the SSL connection details, including certificates presented.

openssl s_client -connect example.com:443

Understanding the Output

When you run the command, you’ll see a lot of information. Let’s break down some of the key components:

  • CONNECTED: Indicates whether the connection was successful.
  • depth: The length of the certificate chain.
  • Certificate: The SSL certificate chain, including the server’s certificate, any intermediate certificates, and the root certificate if applicable.

2. Testing for SSL v3 or TLS Versions

You may want to test specific versions of SSL/TLS. You can use the -ssl3, -tls1, -tls1_1, and -tls1_2 options to specify the protocol.

For example, testing for SSL 3.0:

openssl s_client -connect example.com:443 -ssl3

Note: SSL 3.0 is considered insecure today and should not be used in production environments.

3. Checking Certificate Expiration

When connecting to a server, you can check when the SSL certificate expires. The server will send the certificate’s end date when the connection is established. You can also extract this information by passing additional flags.

Example:

openssl s_client -connect example.com:443 -servername example.com | openssl x509 -noout -dates

This command will display output that includes notBefore and notAfter dates.

4. Testing with Different Cipher Suites

Different SSL/TLS configurations may support various cipher suites. You can test available cipher suites with the -cipher option.

Example:

openssl s_client -connect example.com:443 -cipher 'ECDHE-RSA-AES256-GCM-SHA384'

To list the supported ciphers, you can use:

openssl ciphers -v

5. Verifying a Certificate against a CA Bundle

If your server has a certificate signed by a Certificate Authority (CA), you can verify the chain of trust against a CA bundle.

Example:

openssl s_client -connect example.com:443 -CAfile /path/to/ca.pem

This command will check the server’s certificate against the specified CA file, ensuring that it is trustworthy.

6. Testing Server and Certificate Properties

You can also query additional server properties while testing an SSL connection. Use the -status option to request a stapled Online Certificate Status Protocol (OCSP) response:

openssl s_client -connect example.com:443 -status

7. Checking for Vulnerabilities

Although OpenSSL itself doesn’t necessarily identify all vulnerabilities, it is useful for checking specific configurations that may be vulnerable.

For example, to check for Heartbleed vulnerability (CVE-2014-0160):

openssl s_client -connect example.com:443 -tlsextdebug

You can also utilize additional testing frameworks suited for SSL/TLS vulnerability assessments, like Qualys SSL Labs' SSL Test.

Conclusion

Testing SSL connections using OpenSSL is a straightforward process that provides vital information about the security posture of your applications. By understanding the various commands and options available, you can diagnose issues efficiently, ensuring secure communication for your networked applications.

Final Thoughts

Regular testing and validation of SSL connections should be part of your organization’s cybersecurity protocols. As threats evolve, remaining proactive and informed about your encryption and security practices is essential for safeguarding sensitive information.

By mastering OpenSSL’s testing capabilities, you can enhance both the security and reliability of your website or web service, offering peace of mind to its users.

In a world increasingly reliant on internet security, knowledge of tools like OpenSSL is not just beneficial—it’s essential.

Вы часто вынуждены решать проблемы, связанные с SSL / TLS, если работаете веб-инженером, веб-мастером или системным администратором.

Существует множество онлайн-инструментов для работы с SSL-сертификатами, тестирования слабых мест в протоколах SSL/TLS, но когда дело доходит до тестирования внутренней сети на основе URL, VIP, IP, тогда они вряд ли будут полезны.

Для диагностики ресурсов внутренней сети, вам необходимо отдельное программное обеспечение/инструменты, которые вы можете установить в своей сети и провести необходимую проверку.

Возможны различные сценарии, например:

  • имеются проблемы при установке SSL-сертификата на веб-сервер;
  • требуется использовать новейший/конкретный шифр, протокол;
  • хочется проверить конфигурацию после ввода в работу;
  • обнаружена угроза безопасности в ходе проведения тестов на уязвимости.

Следующие инструменты будут полезны в устранении подобных проблем.

Инструменты с открытым кодом для устранения проблем с SSL/TLS:

  1. DeepViolet
  2. SSL Diagnos
  3. SSLyze
  4. OpenSSL
  5. SSL Labs Scan
  6. SSL Scan
  7. Test SSL
  8. TLS Scan
  9. Cipher Scan
  10. SSL Audit

1. DeepViolet

DeepViolet — это написанный на языке Java инструмент анализа SSL/TLS, доступный в бинарном коде, вы также можете скомпилировать его из исходного кода.

Если вы ищете альтернативу SSL Labs для использования во внутренней сети, то DeepViolet будет хорошим выбором. Он сканирует следующее:

  • использование слабого шифрования;
  • слабый алгоритм подписи;
  • статус отзыва сертификата;
  • статус срока действия сертификата;
  • визуализацию цепочки доверия, самоподписанного корневого сертификата.

2. SSL Diagnos

Быстро оценивает надежность SSL на вашем веб-сайте. SSL Diagnos анализирует протокол SSL, алгоритмы шифрования, уязвимости Heartbleed, BEAST.

Используется не только для HTTPS, можно проверить стабильность SSL для SMTP, SIP, POP3 и FTPS.

3. SSLyze

SSLyze — это библиотека Python и инструменты командной строки, которые подключаются к конечной точке SSL и осуществляют сканирование для обнаружения любой пропущенной конфигурации SSL/TLS.

Сканирование через SSLyze – это быстро, потому что осуществление проверки распределяется между несколькими процессами. Если вы разработчик или хотите интегрировать в ваше существующее приложение, то у вас есть возможность записать результат в формате XML или JSON.

SSLyze также доступен в Kali Linux.

4. OpenSSL

Не стоит недооценивать OpenSSL — один из самых мощных автономных инструментов, доступных для Windows или Linux для выполнения различных задач, относящихся к SSL, таких как верификация, генерация CSR, конвертация формата сертификатов и др.

5. SSL Labs Scan

Любите Qualys SSL Labs? Вы не одиноки – мне тоже нравится.

Если вы ищете инструмент командной строки для SSL Labs для автоматического или массового тестирования, то SSL Labs Scan будет, несомненно, полезен.

6. SSL Scan

SSL Scan совместим с Windows, Linux и Mac. SSL Scan помогает быстро определить следующие показатели:

  • подсветка SSLv2/SSLv3/CBC/3DES/RC4 шифрования;
  • сообщение о слабом (<40 бит), нулевом или неизвестном шифровании;
  • проверить компрессию TLS, уязвимость Heartbleed;
  • и многое другое…

Если вы работаете над проблемами, связанными с шифрованием, то SSL Scan станет полезным инструментом для ускорения поиска и устранения неполадок.

7. Test SSL

Как видно из названия, TestSSL — это инструмент командной строки, совместимый с Linux и других ОS. Он проверяет все важнейшие показатели и показывает, что в порядке, а что нет.

Например

Testing protocols via sockets except SPDY+HTTP2

SSLv2 not offered (OK)
SSLv3 not offered (OK)
TLS 1 offered
TLS 1.1 offered
TLS 1.2 offered (OK)
SPDY/NPN h2, spdy/3.1, http/1.1 (advertised)
HTTP2/ALPN h2, spdy/3.1, http/1.1 (offered)

Testing ~standard cipher categories

NULL ciphers (no encryption) not offered (OK)
Anonymous NULL Ciphers (no authentication) not offered (OK)
Export ciphers (w/o ADH+NULL) not offered (OK)
LOW: 64 Bit + DES encryption (w/o export) not offered (OK)
Weak 128 Bit ciphers (SEED, IDEA, RC[2,4]) not offered (OK)
Triple DES Ciphers (Medium) not offered (OK)
High encryption (AES+Camellia, no AEAD) offered (OK)
Strong encryption (AEAD ciphers) offered (OK)

Testing server preferences

Has server cipher order? yes (OK)
Negotiated protocol TLSv1.2
Negotiated cipher ECDHE-ECDSA-CHACHA20-POLY1305-OLD, 256 bit ECDH (P-256)
Cipher order
TLSv1: ECDHE-RSA-AES128-SHA AES128-SHA ECDHE-RSA-AES256-SHA AES256-SHA DES-CBC3-SHA
TLSv1.1: ECDHE-RSA-AES128-SHA AES128-SHA ECDHE-RSA-AES256-SHA AES256-SHA
TLSv1.2: ECDHE-ECDSA-CHACHA20-POLY1305-OLD ECDHE-ECDSA-CHACHA20-POLY1305 ECDHE-ECDSA-AES128-GCM-SHA256
ECDHE-ECDSA-AES128-SHA ECDHE-ECDSA-AES128-SHA256 ECDHE-ECDSA-AES256-GCM-SHA384
ECDHE-ECDSA-AES256-SHA ECDHE-ECDSA-AES256-SHA384 ECDHE-RSA-CHACHA20-POLY1305-OLD
ECDHE-RSA-CHACHA20-POLY1305 ECDHE-RSA-AES128-GCM-SHA256 ECDHE-RSA-AES128-SHA
ECDHE-RSA-AES128-SHA256 AES128-GCM-SHA256 AES128-SHA AES128-SHA256
ECDHE-RSA-AES256-GCM-SHA384 ECDHE-RSA-AES256-SHA ECDHE-RSA-AES256-SHA384 AES256-GCM-SHA384
AES256-SHA AES256-SHA256

Testing vulnerabilities

Heartbleed (CVE-2014-0160) not vulnerable (OK), no heartbeat extension
CCS (CVE-2014-0224) not vulnerable (OK)
Ticketbleed (CVE-2016-9244), experiment. not vulnerable (OK)
Secure Renegotiation (CVE-2009-3555) not vulnerable (OK)
Secure Client-Initiated Renegotiation not vulnerable (OK)
CRIME, TLS (CVE-2012-4929) not vulnerable (OK)
BREACH (CVE-2013-3587) potentially NOT ok, uses gzip HTTP compression. - only supplied "/" tested
Can be ignored for static pages or if no secrets in the page
POODLE, SSL (CVE-2014-3566) not vulnerable (OK)
TLS_FALLBACK_SCSV (RFC 7507) Downgrade attack prevention supported (OK)
SWEET32 (CVE-2016-2183, CVE-2016-6329) not vulnerable (OK)
FREAK (CVE-2015-0204) not vulnerable (OK)
DROWN (CVE-2016-0800, CVE-2016-0703) not vulnerable on this host and port (OK)
make sure you don't use this certificate elsewhere with SSLv2 enabled services
https://censys.io/ipv4?q=EDF8A1A3D0FFCBE0D6EA4C44DB5F4BE1A7C2314D1458ADC925A30AA6235B9820 could help you to find out
LOGJAM (CVE-2015-4000), experimental not vulnerable (OK): no DH EXPORT ciphers, no DH key detected
BEAST (CVE-2011-3389) TLS1: ECDHE-RSA-AES128-SHA AES128-SHA ECDHE-RSA-AES256-SHA
AES256-SHA DES-CBC3-SHA
VULNERABLE -- but also supports higher protocols (possible mitigation): TLSv1.1 TLSv1.2
LUCKY13 (CVE-2013-0169) VULNERABLE, uses cipher block chaining (CBC) ciphers
RC4 (CVE-2013-2566, CVE-2015-2808) no RC4 ciphers detected (OK)

Как можно видеть, он охватывает большое количество уязвимостей, шифровальных предпочтений, протоколов и др.

TestSSL.sh также доступен в Docker-образе.

8. TLS Scan

Вы можете собрать TLS-Scan из исходного кода или загрузить бинарный код для Linux/OSX. Он извлекает информацию из сертификата с сервера и выводит следующие показатели в формате JSON:

  • верификация имени хоста;
  • проверка компрессии TLS;
  • проверка нумерации версий шифрования и TLS;
  • проверка повторного использования сессий.

Он поддерживает протоколы TLS, SMTP, STARTTLS и MySQL. Вы также можете интегрировать результаты в анализатор логов, например, такие как Splunk, ELK.

9. Cipher Scan

Быстрый инструмент для анализа того, какие типы шифрования поддерживаются на веб-сайтах с использованием протокола HTTPS. Cipher Scan также дает возможность отображать результаты в формате JSON. Это оболочка, использующая команды пакета OpenSSL.

10. SSL Audit

SSL Audit — это инструмент с открытым исходным кодом для проверки сертификата и поддержки протоколов, шифрования и стандартов на основе SSL Labs.

Я надеюсь, что упомянутые инструменты с открытым исходным кодом помогут вам интегрировать непрерывное сканирование в ваши действующие анализаторы логов и облегчат устранение неполадок.

Заглядывайте на VPS.today — сайт для поиска виртуальных серверов. 1500 тарифов от 130 хостеров, удобный интерфейс и большое число критериев для поиска самого лучшего виртуального сервера.

In today’s digital landscape, security is paramount. With the rise of cyber threats and the increasing importance of personal and organizational data, ensuring secure connections is no longer optional. At the forefront of this movement is SSL (Secure Socket Layer), a standard technology that establishes encrypted links between networked computers. This article serves as a comprehensive guide to testing an SSL connection using OpenSSL, a powerful tool that allows users to establish secure channels and ensure the integrity of their communications.

Understanding SSL/TLS

Before delving into the intricacies of testing an SSL connection, it’s essential to understand what SSL (and its successor, TLS – Transport Layer Security) is. SSL and TLS provide a secure framework for establishing encrypted links, protecting sensitive data as it travels over networks. They use cryptographic protocols to facilitate secure communication between a client and a server.

When a client attempts to connect to a server over HTTPS, SSL/TLS ensures that:

  1. Encryption: Data is encrypted to prevent eavesdroppers from accessing it during transmission.
  2. Authentication: The identities of the entities involved are validated, ensuring that data is sent to the correct server.
  3. Integrity: Data is not altered in transit, maintaining the integrity of the messages being exchanged.

What is OpenSSL?

OpenSSL is an open-source software library that implements the SSL and TLS protocols. It provides a robust toolkit for developing applications that require secure communication protocols. Additionally, it includes a command-line interface that allows users to perform a variety of tasks, such as generating SSL certificates, managing cryptographic keys, and testing SSL connections.

Installing OpenSSL

Before testing an SSL connection using OpenSSL, you need to ensure that the software is installed on your system. OpenSSL is compatible with several operating systems, including Windows, macOS, and Linux.

For Linux

Most Linux distributions come with OpenSSL pre-installed. You can check if it’s already on your system by running:

openssl version

If it’s not installed, you can usually install it using a package manager. For example, on Ubuntu or Debian-based systems, run:

sudo apt-get install openssl

For macOS

OpenSSL doesn’t come pre-installed on macOS directly. However, you can install it using Homebrew. If you don’t have Homebrew installed, you can install it from brew.sh. Once you have Homebrew, run:

brew install openssl

For Windows

To install OpenSSL on Windows, you can download a precompiled binary from a reliable source like Shining Light Productions. Follow these steps:

  1. Choose the appropriate installer for your system architecture (32-bit or 64-bit).
  2. Run the installer and follow the prompts to finish the installation.
  3. Add OpenSSL to your system’s PATH environment variable to use it from any command prompt window.

Basic OpenSSL Commands

Familiarizing yourself with some basic OpenSSL commands can greatly enhance your efficiency in testing SSL connections. Below are some essential commands:

  1. Check OpenSSL Version:

    openssl version
  2. Generate a Private Key:

    openssl genrsa -out private.key 2048
  3. Create a Certificate Signing Request (CSR):

    openssl req -new -key private.key -out request.csr
  4. Generate a Self-Signed Certificate:

    openssl req -x509 -new -nodes -key private.key -sha256 -days 365 -out certificate.crt

Testing an SSL Connection

Once OpenSSL is installed, you can begin testing an SSL connection. This typically involves connecting to an SSL-enabled server, retrieving its certificate, and analyzing the SSL configuration. Let’s break down the process.

Establishing an SSL Connection

To test an SSL connection, you can use the s_client command in OpenSSL. This command initiates a connection to an SSL/TLS server and displays detailed information about the connection.

Here’s the basic syntax to connect to a server:

openssl s_client -connect example.com:443
  • Replace example.com with the domain name or IP address of the server you want to test.
  • The 443 port is the default for HTTPS traffic. If the server uses a different port, specify that instead.

Analyzing the Output

When you execute the s_client command, OpenSSL will provide detailed output regarding the SSL connection. Key components of this output include:

  • Certificate Chain: This section shows the server’s SSL certificate and any intermediate certificates. Each certificate will contain information such as the subject, issuer, and validity period.
  • Server Certificate: This part provides details about the server certificate, including the serial number, validity dates, and public key.
  • Session Parameters: This section lists details about the SSL session, including the session ID and master key.
  • Cipher suites: This displays the cipher suites that the server supports, indicating the encryption algorithms and key lengths.

Verifying the Certificate

One of the most important aspects of testing an SSL connection is ensuring that the SSL certificate presented by the server is valid. This includes checking:

  1. Validity Period: Ensure that the certificate is not expired and is still valid.
  2. Common Name (CN): Ensure that the CN in the certificate matches the domain name of the server you are trying to connect to.
  3. Issuing Authority: Verify that the certificate is signed by a trusted Certificate Authority (CA).
  4. Revocation Status: Check if the certificate has been revoked using methods like CRL (Certificate Revocation List) or OCSP (Online Certificate Status Protocol).

Testing Different Protocols

OpenSSL allows you to specify which SSL/TLS version to use during the connection. This is useful for verifying compatibility with different SSL/TLS versions supported by the server.

For example:

  • To test a connection using TLS 1.2:

    openssl s_client -connect example.com:443 -tls1_2
  • To test a connection using TLS 1.3:

    openssl s_client -connect example.com:443 -tls1_3

Performing Vulnerability Assessments

OpenSSL can also help identify potential security vulnerabilities in SSL configurations. By using the -tlsextdebug option, you can gain insight into how well the server maintains security standards.

To view the server’s supported protocols and extensions, run:

openssl s_client -connect example.com:443 -tlsextdebug

In addition, tools like testssl.sh can be used as a comprehensive framework for testing SSL/TLS vulnerabilities, including heartbleed, POODLE, and others.

Checking for HTTP Strict Transport Security (HSTS)

HSTS is a web security policy mechanism that helps to protect websites against man-in-the-middle attacks such as protocol downgrade attacks. You can check if a server supports HSTS by looking for the Strict-Transport-Security header in the response:

openssl s_client -connect example.com:443 -servername example.com

Once the connection is established, type GET / HTTP/1.1 followed by Host: example.com and then press Enter twice. Look for the Strict-Transport-Security header in the response.

Using OpenSSL to Debug SSL Issues

OpenSSL can also be a vital tool in debugging SSL issues. If you encounter connection problems, you can get verbose output by using the -msg option:

openssl s_client -connect example.com:443 -msg

This will provide a detailed breakdown of the SSL handshake process and can help identify where the issue lies.

Automating SSL Connection Testing

For system administrators and DevOps teams, automating the testing of SSL connections across multiple servers can be beneficial. You can create simple scripts using the OpenSSL command line to check SSL certificates on various domains. Here’s an example of a simple bash script:

#!/bin/bash

domains=("example.com" "example2.com")

for domain in "${domains[@]}"; do
    echo "Testing SSL certificate for $domain"
    openssl s_client -connect "$domain:443" -servername "$domain" &lt; /dev/null | grep -E &#039;BEGIN CERTIFICATE|subject=|issuer=|notAfter=|notBefore=&#039;
done

This script will iterate through a predefined list of domains, testing each SSL connection and displaying the relevant certificate details.

Conclusion

As we navigate through an increasingly digital world, the security of online communications remains a critical concern. SSL/TLS protocols act as the cornerstone for secure communication, and OpenSSL provides a robust toolkit for testing SSL connections.

By following the steps outlined in this guide, you can effectively test SSL connections, verify the integrity of SSL certificates, and diagnose potential security vulnerabilities. Whether you’re a developer, system administrator, or cybersecurity professional, mastering OpenSSL is a valuable skill in today’s technology-driven environment.

Armed with knowledge of OpenSSL, you can ensure that your web applications and services maintain the highest standards of security, protecting both your data and your users.

OpenSSL is a general-purpose cryptography library and full-featured toolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols. It’s licensed under the Apache License 2.0, meaning that you are free to get and use it for both commercial and non-commercial purposes, subject to a few simple license conditions.

Using OpenSSL to check and verify secure connections

Today we’ll be focusing on the s_client tool, which can be used to connect, check and list SSL/TLS related information. In this article we’ll go through a few different use cases of s_client.

To end any command and return to the terminal, press Ctrl+D – also known as EOF or “End of File”, a special control character parameter of the terminal driver in the kernel (like Ctrl+C to interrupt). It tells the system that the file or transmission stream has finished and the current data stream has reached the end.

Check the SSL/TLS of a website

This is probably the most common and popular use for s_client. This command establishes a connection to the domain isscloud.io, port 443 for the HTTPS protocol.

openssl s_client -connect isscloud.io:443Code language: Shell Session (shell)

Check using IPv6

You can also check all connections forcing IPv6, by using the -6 option

openssl s_client -6 -connect isscloud.io:443Code language: Shell Session (shell)

Check the TLS/SSL against a specific Certificate Authority

In order for the certificates to by trusted by web browsers and applications, their require a valid signature from the Global Certificate Authorities.

While this is the standard on most organizations and public facing web servers and services, some pages or applications have certificates created in house.

Many times you’ll have a Certificate Authority file that can be use to check these connections, specifying its location with the following command:

openssl s_client -connect isscloud.io:443 -CAfile /etc/ssl/CA.crtCode language: Shell Session (shell)

Testing SMTP and TLS connection

We may also use the s_client tool to test the connection to an email server, testing the SMTP protocol and moving to a secure TLS connection. We can do it to test if the server is accepting new connections, or even to see if everything is alright with the security certificate, so clients can connect cleanly. To do so we use the -starttls smtp option.

openssl s_client -connect mail.isscloud.io:25 -starttls smtpCode language: Shell Session (shell)

Testing IMAP connectivity and certificates

Just like we did for checking the connection for an HTTPS website, or checking the SMTP service, we may also use the s_client tool to test an IMAP connection, and we can either do it by connecting directly to the TLS/SSL port, or by asking to negotiate just like we did with SMTP using the -starttls smtp option.

Using StartTLS:

openssl s_client  -connect mail.isscloud.io:143 -starttls imapCode language: Shell Session (shell)

Connecting directly to the secure port:

When connecting directly to a secure port, we should use the -crlf option. This option emulates the line feed of the terminal into CR+LF (carriage return/line feed) as required by some systems, and is usually recommended to use it while testing IMAP connections.

openssl s_client -connect mail.isscloud.io:993 -crlfCode language: Shell Session (shell)

Specify desired version or cipher

Security protocols have different versions and sub-versions, or use different hash algorithms. We can tell the s_client tool to choose a specific version to use or to only connect using a specific cipher.

Specifying or disabling TLS version

To use only TLS1.0, 1.1, or 1.2, we use the options -tls1 | -tls1_1 | -tls1_2 respectively. In the following example we’re selecting TLS1.2:

openssl s_client -connect isscloud.io:443 -tls1_2Code language: Shell Session (shell)

Or, disable the use of a specific TLS version with the options -no_tls1 | -no_tls1_1 | -no_tls1_2 | -no_ssl2 | -no_ssl3 respectively. In the following example we’ll be disabling TLS1.1:

openssl s_client -connect isscloud.io:443 -no_tls1_1Code language: Shell Session (shell)

Specifying Cipher

You can also specify the use of a determined hash algorithm for encryption. For example, if you want to test the RC4-SHA cipher, use the following command:

openssl s_client -connect isscloud.io:443 -cipher RC4-SHACode language: Shell Session (shell)

Debugging the connection

Most of the times you’ll be looking to the s_client tool will be to test SSL/TLS connections and check what’s going out under the wood. The s_client tool has many options that can help you successfully identify and fix most issues going on with a secure connection.

Among the various options available, you can use -pause to pause 1 second between each read/write call, -debug to get extensive debug information including an hex dump of all traffic, or -tlsextdebug to print a hex dump of any TLS extensions received from the server.

Should you have any questions left regarding this article, or if you want to discuss this article with other users, please leave a comment. Thank you.

UPDATED: This article has been updated in July 2022 to include new commands and options.

How to Test HTTPS and IMAPS connection using OpenSSL

OpenSSL can be used in many ways, so not only keys and certificates for SSL/TLS encrypted connections can be generated, but also their analysis and testing is possible.

This article shows how to perform the usage of OpenSSL for verification and analysis, when accessing web servers via TCP port 443 and STARTTLS over TCP 587 or IMAPS TCP 993 to mail server, which requires OpenSSL on the computer.

The free online service SSL Labs provide deep analysis of the configuration of any SSL web server that can be performed, the connection is performed with many different browsers and displayed, and which encryption has been achieved. The evaluation shows which encryption methods and key exchange methods have been used.

HTTPS Connection Test with OpenSSL

If individual tests are to be performed, the following examples show how to do this. An encrypted connection to unblog.ch is established and then the Web page is retrieved.

$ openssl s_client -connect unblog.ch:443 -showcerts

In a situation where an alternate port is used instead of the default port 443 for HTTPS, for example, 4443, the command is the same, with :4443 specifying the port number.

Retrieve certificate in RAW text

If you want to retrieve the public certificate of a web page in the RAW text, the certificate can be issued by the following command line.

$ openssl s_client -connect think.unblog.ch:443 -showcerts | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

This command runs in a Linux terminal, in macOS terminal, in Git Bash or in a WSL session, the output between:
from: —–BEGIN CERTIFICATE—–
to —–END CERTIFICATE—–

-----BEGIN CERTIFICATE-----
MIIFajCCBFKgAwIBAgISAwYFPWKaEox8MgKHV5yqROeWMA0GCSqGSIb3DQEBCwUA
MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD
ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0yMDA3MTcwMzAyMTZaFw0y
...
-----END CERTIFICATE-----

copy paste in Notepad and save as PEM/CER file (.cer).

By double-clicking on the public certificate saved in this way, it opens and appears on Windows as follows.

SMTPS Connection Test with OpenSSL

Use OpenSSL you can determine whether a mail server (MTA) offers encrypted STARTTLS connections, with the following command line.

$ openssl s_client -connect smtp-gw-246.server.com:587 -starttls smtp

The query displays the public certificate, then the encryption strength, the algorithm (SHA256), the TLS version (TLSv1.2), and cipher (ECDHE-RSA-AES256-GCM-SHA384) and other status information.

subject=CN = smtp-gw-246.server.com

issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3

---
No client certificate CA names sent
Peer signing digest: SHA256
Peer signature type: RSA
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 3441 bytes and written 480 bytes
Verification: OK
---
New, TLSv1.2, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN
SSL session:
    Protocol : TLSv1.2
    Cipher : ECDHE-RSA-AES256-GCM-SHA384
    Session ID: E1528C64C3CC7A9B28C4E1C2EA33EA0BEF1BACB6602B066351A49C705E192EB5
    Session ID ctx:
    Master Key: 573AB776B9954B51B7FE4908171752874EFCC3DE5F35ECC42AA5F04E48B736290DECC948DE252AD61188B5A94A8BAE9A
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 7200 (seconds)
    TLS session ticket:
    0000 - 0b 99 b3 3a 91 90 66 a8-86 8d 0e 41 8a 90 61 9e ...:.. Q....A.. A.

IMAPS Connection Test use OpenSSL

Check IMAPs using OpenSSL in the command line, to perform the command line with IMAPS (SSL/TLS) connection can be checked over TCP port 993.

$ openssl s_client -crlf -connect imap.gmail.com:993

The output then as here with CONNECT to imap.gmail.com via the SSL port 993 the raw output will displaying as shown in shortened way.

CONNECTED(00000174)
depth=1 C = US, O = Google Trust Services, CN = GTS CA 1O1
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 C = US, ST = California, L = Mountain View, O = Google LLC, CN = imap.gmail.com
verify return:1
---
Certificate chain
 0 s:C = US, ST = California, L = Mountain View, O = Google LLC, CN = imap.gmail.com
   i:C = US, O = Google Trust Services, CN = GTS CA 1O1
 1 s:C = US, O = Google Trust Services, CN = GTS CA 1O1
   i:OU = GlobalSign Root CA - R2, O = GlobalSign, CN = GlobalSign
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIExjCCA66gAwIBAgIQN1SnMAZHJA0IAAAAAFMdITANBgkqhkiG9w0BAQsFADBC
MQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZpY2VzMRMw
...
Post-Handshake New Session Ticket arrived:
SSL session:
    Protocol : TLSv1.3
    Cipher : TLS_AES_256_GCM_SHA384
    Session ID: 6074E0D401DDD1E1DD5608CBC6F7CA4A2779A9AB4A9313732996D6C4DBD84BC68
    Session ID ctx:
    Resumption PSK:
...
read R BLOCK
* OK Gimap ready for requests from 12.34.56.78 t22mb67814ed
Q
Done

If you want to continue here, you can try to authenticate on the IMAP server and query for new mails.

A NO [ALERT] Application-specific password required: https://support.google.com/accounts/answer/185833 (Failure)

Gmail now responds with A NO [ALERT] which requires authentication security settings to have an application password because multi-factor authentication (MFA) is enabled.

* OK [CAPABILITY IMAP4rev1 SASL-IR LOGIN-REFERRALS ID ENABLE IDLE LITERAL+ AUTH=PLAIN AUTH=LOGIN] Dovecot (Debian) ready.

The following is a * OK with the output of the available functionalities (CAPABILITY). The IMAP Prompt is now waiting for input.

We can log in to our Dovecot IMAP server.

A login imap-user password

The login usually consists of the email address (imap-user) and a password.

After successful login, the output appears similar to this one.

A OK [CAPABILITY IMAP4rev1 SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS THREAD=ORDEREDSUBJECT MULTIAPPEND URL-PARTIAL CATENATE UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS BINARY MOVE SNIPPET=FUZZY LITERAL+ NOTIFY SPECIAL-USE QUOTA] Logged in

Now we’re going to the IMAP inbox (INBOX).

A select INBOX

The output of select INBOX is similar to the following.

* FLAGS (\Answered \Flagged \Deleted \Seen \Draft $Forwarded)
* OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen \Draft $Forwarded \*)] Flags permitted.
* 3 EXISTS
* 0 RECENT
* OK [UNSEEN 3] First unseen.
* OK [UIDVALIDITY 1590737718] UIDs valid
* OK [UIDNEXT 12197] Predicted next UID
* OK [HIGHESTMODSEQ 39953] Highest
A OK [READ-WRITE] Select completed (0.001 + 0.000 secs).

There are as seen 3 unread mails in the INBOX. From the first mail we open the header (starts with . dot).

. fetch 1 rfc822.header

The output of . fetch 1 rfc822.header (the first 6 lines).

* 1 FETCH (RFC822.HEADER {3338}
Return-Path: <maxmuster@server.com>
Delivered-To: maxmuster@server.com
Received: from mail.server.com
        by mail.server.com with LMTP
        id sbn9BAzYQF9sJBACykIyCA
        (envelope-from <maxmuster@server.com>)
..
. OK Fetch completed (0.001 + 0.000 secs).

The first unread mail opens with . fetch 1 rfc822.text

. fetch 1 rfc822.text

Output of . fetch 1 then similar to here with my mail.

* 1 FETCH (RFC822. TEXT {596297}

--Apple-Mail-3B8B8770-2CCE-4083-B331-2E1EDAF97C84
Content type: text/plain;
        charset=us-ascii
Content Transfer Encoding: 7bit

Good day.

Attached the PDF in the attachment.

Friendly greetings

--Apple-Mail-3B8C8770-2CCE-4083-B331-2E2EDBF97C94
Content type: application/pdf;
        name="Doc-21.08.2020-10-36.pdf";
        x-apple-part-url=CCDB9E0F-432F-2719-AE44-000259172822
Content disposition: inline;
        filename="Doc-21.08.2020-10-36.pdf"
Content Transfer Encoding: base64

JVBERi0jLjMKJbe+7aoKMSAwIG9iago8PA0vVHlwZSAvQ2F0YWxvZwozUGFnZXMgMiAwIFIKPj4K
ZW5kc2JqCjIgMCBvYmoKPDwKL1R5cGUgL1BhZ2VzCi9LaWRzIFsgNCFxIFIgXQovQ291bnQgMQo+
...
. OK Fetch completed (0.003 + 0.034 secs).

So this is a mail with PDF attachment, which is base64 encoded.
Enter Q will terminate the encrypted IMAP session.

Conclusion

OpenSSL as a versatile open-source toolkit offers numerous options, such as testing connections. Also including under Windows, as shown in this posting.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Ftp command windows command line
  • Средство создания мультимедиа windows 10
  • Seculauncher failed to start application 2000 gta 4 как исправить windows 10
  • Windows midi soundfont player
  • Создание разделов на жестком диске при установке windows