Reputation: 659
I'm trying to do an equivalent of this command in a .net core library for doing a TLS server where the private key is in TPM with a reference of 0x8100001:
openssl s_server -cert rsa.crt -key 0x8100001-keyform engine -engine tpm2tss -accept 8443
We need this to be running in Ubuntu on .net core. In Windows this is abstracted well by the cert store with crypto provider but the same doesn't exist in Ubuntu.
Does anyone have an example of using a package that works in Ubuntu? The below is the equivalent in windows that we use to get from cert store(the cert store abstracts the TPM access)
X509Store store = new X509Store(storeName, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, commonName,false);
Upvotes: 2
Views: 122
Reputation: 389
Try with Pkcs11Interop, you firts have to install tpm2-tools tpm2-pkcs11 libtss2-tcti-tabrmd0 on your ubuntu, configure the PKCS token for TPM and then import the Key.
On your .net project add the package Pkcs11Interop to access the certificate and private key from TPM:
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Net.Pkcs11Interop.HighLevelAPI;
using Net.Pkcs11Interop.HighLevelAPI.Factories;
using Net.Pkcs11Interop.Common;
public class TlsServer
{
public static void StartServer()
{
// Specify the path to your PKCS#11 library
string pkcs11LibraryPath = "/usr/lib/x86_64-linux-gnu/libtpm2_pkcs11.so";
using (var pkcs11Library = new Pkcs11(pkcs11LibraryPath, AppType.MultiThreaded))
{
// Initialize the library
var slot = pkcs11Library.GetSlotList(SlotsType.WithTokenPresent)[0];
var session = slot.OpenSession(SessionType.ReadOnly);
// Authenticate to the token
session.Login(CKU.CKU_USER, "1234"); // User PIN
// Find the private key by label
var searchTemplate = new List<ObjectAttribute>
{
new ObjectAttribute(CKA.CKA_LABEL, "tls-key"),
new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY)
};
var foundObjects = session.FindAllObjects(searchTemplate);
if (foundObjects.Count == 0)
{
Console.WriteLine("Private key not found");
return;
}
// Load certificate (for TLS handshake)
var certificate = new X509Certificate2("path/to/your_cert.crt");
// Configure the listener
var listener = new TcpListener(IPAddress.Any, 8443);
listener.Start();
Console.WriteLine("Server started on port 8443");
// Accept connections and handle with TLS
while (true)
{
var client = listener.AcceptTcpClient();
var sslStream = new SslStream(client.GetStream(), false);
sslStream.AuthenticateAsServer(certificate, clientCertificateRequired: false, enabledSslProtocols: SslProtocols.Tls12, checkCertificateRevocation: false);
Console.WriteLine("Client connected and authenticated");
}
}
}
}
Upvotes: 1