Skip to content

Mutual TLS

Don Kackman edited this page Mar 11, 2022 · 3 revisions

Chia RPC uses Mutual TLS to secure and authenticate both the server and the client. This means that the client authenticates the connection with keys that the server knows about and trusts. mutualTLS is included in the OpenAPI 3.1.0 spec, but that version is not yet widely supported by tooling. March 2022

To secure and authenticate from the client it will need the private certificates generated on the server. For instance private_full_node.crt and private_full_node.key from the server are needed to connect to the full node interface.

Python example:

import ssl
from pathlib import Path

def ssl_context_for_client(
    ca_cert: Path,
    ca_key: Path,
    private_cert_path: Path,
    private_key_path: Path,
    *,
    check_permissions: bool = True,
    log: Optional[logging.Logger] = None,
) -> Optional[ssl.SSLContext]:
    ssl_context = ssl._create_unverified_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=str(ca_cert))
    ssl_context.check_hostname = False
    ssl_context.load_cert_chain(certfile=str(private_cert_path), keyfile=str(private_key_path))
    ssl_context.verify_mode = ssl.CERT_REQUIRED
    return ssl_context

C# example:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

public static X509Certificate2Collection GetCerts(string certPath, string keyPath)
{
    using X509Certificate2 cert = new(certPath);
    using StreamReader streamReader = new(keyPath);

    var base64 = new StringBuilder(streamReader.ReadToEnd())
        .Replace("-----BEGIN RSA PRIVATE KEY-----", string.Empty)
        .Replace("-----END RSA PRIVATE KEY-----", string.Empty)
        .Replace(Environment.NewLine, string.Empty)
        .ToString();

    using var rsa = RSA.Create();
    rsa.ImportRSAPrivateKey(Convert.FromBase64String(base64), out _);

    using var certWithKey = cert.CopyWithPrivateKey(rsa);
    var ephemeralCert = new X509Certificate2(certWithKey.Export(X509ContentType.Pkcs12));

    return new X509Certificate2Collection(ephemeralCert);
}
Clone this wiki locally