aboutsummaryrefslogtreecommitdiff
path: root/plugins/ice
diff options
context:
space:
mode:
authorhrxi <hrrrxi@gmail.com>2023-11-24 20:53:50 +0100
committerMarvin W <git@larma.de>2026-10-23 16:58:30 +0200
commit76a91fca2fc7dd5975e8ff0e6695f27c98539dba (patch)
tree7829340be71fe60ef847247e578c4589571fecc5 /plugins/ice
parentb013d28182ce582f229185c23b6011f566f1f8cc (diff)
Add support for OpenSSL
Uses work by @hrxi in https://github.com/dino/dino/pull/1515 Co-Authored-By: hrxi <hrrrxi@gmail.com>
Diffstat (limited to 'plugins/ice')
-rw-r--r--plugins/ice/meson.build15
-rw-r--r--plugins/ice/src/dtls_srtp.vala297
-rw-r--r--plugins/ice/src/dtls_srtp_gnutls.vala245
-rw-r--r--plugins/ice/src/dtls_srtp_openssl.vala202
-rw-r--r--plugins/ice/src/module.vala2
-rw-r--r--plugins/ice/src/openssl_utils.c49
-rw-r--r--plugins/ice/src/openssl_utils.h8
-rw-r--r--plugins/ice/vapi/openssl.vapi218
8 files changed, 777 insertions, 259 deletions
diff --git a/plugins/ice/meson.build b/plugins/ice/meson.build
index 1cec8b38..5ed807bf 100644
--- a/plugins/ice/meson.build
+++ b/plugins/ice/meson.build
@@ -5,7 +5,6 @@ dependencies = [
dep_gio,
dep_glib,
dep_gmodule,
- dep_gnutls,
dep_nice,
dep_qlite,
dep_xmpp_vala,
@@ -24,6 +23,18 @@ c_args = vala_c_args + [
vala_args = [
'--vapidir', meson.current_source_dir() / 'vapi',
]
-lib_ice = shared_library('ice', sources, name_prefix: '', c_args: c_args, vala_args: vala_args, dependencies: dependencies, install: true, install_dir: get_option('libdir') / get_option('plugindir'), install_rpath: default_install_rpath)
+if crypto_backend == 'gnutls'
+ dependencies += [ dep_gnutls ]
+ sources += files(
+ 'src/dtls_srtp_gnutls.vala'
+ )
+else # openssl
+ dependencies += [ dep_openssl ]
+ sources += files(
+ 'src/dtls_srtp_openssl.vala',
+ 'src/openssl_utils.c',
+ )
+endif
+lib_ice = shared_library('ice', sources, name_prefix: '', c_args: c_args, vala_args: vala_args, include_directories: include_directories('src'), dependencies: dependencies, install: true, install_dir: get_option('libdir') / get_option('plugindir'), install_rpath: default_install_rpath)
dep_ice = declare_dependency(link_with: lib_ice, include_directories: include_directories('.'))
summary('Peer-to-peer communication (ice)', dep_ice.found(), bool_yn: true, section: 'Plugins')
diff --git a/plugins/ice/src/dtls_srtp.vala b/plugins/ice/src/dtls_srtp.vala
index c9813b7e..41918359 100644
--- a/plugins/ice/src/dtls_srtp.vala
+++ b/plugins/ice/src/dtls_srtp.vala
@@ -1,14 +1,10 @@
-using GnuTLS;
-
namespace Dino.Plugins.Ice.DtlsSrtp {
-public class CredentialsCapsule {
+public abstract class CredentialsCapsule : Object {
public uint8[] own_fingerprint;
- public X509.Certificate[] own_cert;
- public X509.PrivateKey private_key;
}
-public class Handler {
+public abstract class AbstractHandler {
public signal void send_data(uint8[] data);
@@ -21,18 +17,18 @@ public class Handler {
public uint8[] peer_fingerprint { get; set; }
public string peer_fp_algo { get; set; }
- private CredentialsCapsule credentials;
- private Cond buffer_cond = Cond();
- private Mutex buffer_mutex = Mutex();
- private Gee.LinkedList<Bytes> buffer_queue = new Gee.LinkedList<Bytes>();
+ protected CredentialsCapsule credentials;
+ protected Cond buffer_cond = Cond();
+ protected Mutex buffer_mutex = Mutex();
+ protected Gee.LinkedList<Bytes> buffer_queue = new Gee.LinkedList<Bytes>();
- private bool running = false;
- private bool stop = false;
- private bool restart = false;
+ protected bool running = false;
+ protected bool stop = false;
+ protected bool restart = false;
- private Crypto.Srtp.Session srtp_session = new Crypto.Srtp.Session();
+ protected Crypto.Srtp.Session srtp_session = new Crypto.Srtp.Session();
- public Handler.with_cert(CredentialsCapsule creds) {
+ protected AbstractHandler.with_cert(CredentialsCapsule creds) {
this.credentials = creds;
this.own_fingerprint = creds.own_fingerprint;
}
@@ -79,38 +75,6 @@ public class Handler {
buffer_mutex.unlock();
}
- internal static CredentialsCapsule generate_credentials() throws GLib.Error {
- int err = 0;
-
- X509.PrivateKey private_key = X509.PrivateKey.create();
- err = private_key.generate(PKAlgorithm.ECDSA, 256);
- throw_if_error(err);
-
- var start_time = new DateTime.now_local().add_days(-1);
- var end_time = start_time.add_days(2);
-
- X509.Certificate cert = X509.Certificate.create();
- cert.set_key(private_key);
- cert.set_version(1);
- cert.set_activation_time ((time_t) start_time.to_unix ());
- cert.set_expiration_time ((time_t) end_time.to_unix ());
-
- uint32 serial = 1;
- cert.set_serial(&serial, sizeof(uint32));
-
- cert.sign(cert, private_key);
-
- uint8[] own_fingerprint = get_fingerprint(cert, DigestAlgorithm.SHA256);
- X509.Certificate[] own_cert = new X509.Certificate[] { (owned)cert };
-
- var creds = new CredentialsCapsule();
- creds.own_fingerprint = own_fingerprint;
- creds.own_cert = (owned) own_cert;
- creds.private_key = (owned) private_key;
-
- return creds;
- }
-
public void stop_dtls_connection() {
buffer_mutex.lock();
stop = true;
@@ -118,228 +82,49 @@ public class Handler {
buffer_mutex.unlock();
}
- public async Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection() {
- MainContext context = MainContext.current_source().get_context();
- var thread = new Thread<Xmpp.Xep.Jingle.ContentEncryption>("dtls-connection", () => {
- var res = setup_dtls_connection_thread();
- Source source = new IdleSource();
- source.set_callback(setup_dtls_connection.callback);
- source.attach(context);
- return res;
- });
- yield;
- return thread.join();
- }
-
- private Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread() {
+ protected Bytes get_buffer_if_present () {
buffer_mutex.lock();
- if (stop) {
- restart = true;
+ if (buffer_queue.size == 0) {
buffer_mutex.unlock();
return null;
}
- if (running || ready) {
- buffer_mutex.unlock();
- return null;
- }
- running = true;
- restart = false;
- buffer_mutex.unlock();
-
- InitFlags server_or_client = mode == Mode.SERVER ? InitFlags.SERVER : InitFlags.CLIENT;
- debug("Setting up DTLS connection. We're %s", mode.to_string());
-
- CertificateCredentials cert_cred = CertificateCredentials.create();
- int err = cert_cred.set_x509_key(credentials.own_cert, credentials.private_key);
- throw_if_error(err);
-
- Session? session = Session.create(server_or_client | InitFlags.DATAGRAM);
- session.enable_heartbeat(1);
- session.set_srtp_profile_direct("SRTP_AES128_CM_HMAC_SHA1_80");
- session.set_credentials(GnuTLS.CredentialsType.CERTIFICATE, cert_cred);
- session.server_set_request(CertificateRequest.REQUEST);
- session.set_priority_from_string("NORMAL:!VERS-TLS-ALL:+VERS-DTLS-ALL:+CTYPE-CLI-X509");
-
- session.set_transport_pointer(this);
- session.set_pull_function(pull_function);
- session.set_pull_timeout_function(pull_timeout_function);
- session.set_push_function(push_function);
- session.set_verify_function(verify_function);
-
- DateTime maximum_time = new DateTime.now_utc().add_seconds(20);
- do {
- err = session.handshake();
-
- DateTime current_time = new DateTime.now_utc();
- if (maximum_time.compare(current_time) < 0) {
- warning("DTLS handshake timeouted");
- err = ErrorCode.APPLICATION_ERROR_MIN + 1;
- break;
- }
- if (stop) {
- debug("DTLS handshake stopped");
- err = ErrorCode.APPLICATION_ERROR_MIN + 2;
- break;
- }
- } while (err < 0 && !((ErrorCode)err).is_fatal());
-
- buffer_mutex.lock();
- if (stop) {
- stop = false;
- running = false;
- bool restart = restart;
- buffer_mutex.unlock();
- if (restart) {
- debug("Restarting DTLS handshake");
- return setup_dtls_connection_thread();
- }
- return null;
- }
+ Bytes res = buffer_queue.remove_at(0);
buffer_mutex.unlock();
- if (err != ErrorCode.SUCCESS) {
- warning("DTLS handshake failed: %s", ((ErrorCode)err).to_string());
- return null;
- }
-
- uint8[] km = new uint8[150];
- Datum? client_key, client_salt, server_key, server_salt;
- session.get_srtp_keys(km, km.length, out client_key, out client_salt, out server_key, out server_salt);
- if (client_key == null || client_salt == null || server_key == null || server_salt == null) {
- warning("SRTP client/server key/salt null");
- }
-
- debug("Finished DTLS connection. We're %s", mode.to_string());
- if (mode == Mode.SERVER) {
- srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract());
- srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract());
- } else {
- srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract());
- srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract());
- }
- return new Xmpp.Xep.Jingle.ContentEncryption(Xmpp.Xep.JingleIceUdp.DTLS_NS_URI, "DTLS-SRTP", credentials.own_fingerprint, peer_fingerprint);
+ return res;
}
- private static ssize_t pull_function(void* transport_ptr, uint8[] buffer) {
- Handler self = transport_ptr as Handler;
-
- self.buffer_mutex.lock();
- while (self.buffer_queue.size == 0) {
- self.buffer_cond.wait(self.buffer_mutex);
- if (self.stop) {
- self.buffer_mutex.unlock();
- debug("DTLS handshake pull_function stopped");
- return -1;
- }
- }
- Bytes data = self.buffer_queue.remove_at(0);
- self.buffer_mutex.unlock();
-
- uint8[] data_uint8 = Bytes.unref_to_data((owned) data);
- Memory.copy(buffer, data_uint8, data_uint8.length);
-
- // The callback should return 0 on connection termination, a positive number indicating the number of bytes received, and -1 on error.
- return (ssize_t)data_uint8.length;
- }
-
- private static int pull_timeout_function(void* transport_ptr, uint ms) {
- Handler self = transport_ptr as Handler;
-
- int64 end_time = get_monotonic_time() + ms * 1000;
-
- self.buffer_mutex.lock();
- while (self.buffer_queue.size == 0) {
- self.buffer_cond.wait_until(self.buffer_mutex, end_time);
- if (self.stop) {
- self.buffer_mutex.unlock();
- debug("DTLS handshake pull_timeout_function stopped");
- return -1;
- }
-
- if (get_monotonic_time() > end_time) {
- self.buffer_mutex.unlock();
- return 0;
+ public async Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection() {
+ MainContext context = MainContext.current_source().get_context();
+ var thread = new Thread<Xmpp.Xep.Jingle.ContentEncryption>("dtls-connection", () => {
+ // Check we can start working on the thread
+ buffer_mutex.lock();
+ if (stop) {
+ restart = true;
+ buffer_mutex.unlock();
+ return null;
}
- }
- self.buffer_mutex.unlock();
-
- // The callback should return 0 on timeout, a positive number if data can be received, and -1 on error.
- return 1;
- }
-
- private static ssize_t push_function(void* transport_ptr, uint8[] buffer) {
- Handler self = transport_ptr as Handler;
- self.send_data(buffer);
-
- // The callback should return a positive number indicating the bytes sent, and -1 on error.
- return (ssize_t)buffer.length;
- }
-
- private static int verify_function(Session session) {
- Handler self = session.get_transport_pointer() as Handler;
- try {
- bool valid = self.verify_peer_cert(session);
- if (!valid) {
- warning("DTLS certificate invalid. Aborting handshake.");
- return 1;
+ if (running || ready) {
+ buffer_mutex.unlock();
+ return null;
}
- } catch (Error e) {
- warning("Error during DTLS certificate validation: %s. Aborting handshake.", e.message);
- return 1;
- }
-
- // The callback function should return 0 for the handshake to continue or non-zero to terminate.
- return 0;
- }
-
- private bool verify_peer_cert(Session session) throws GLib.Error {
- unowned Datum[] cert_datums = session.get_peer_certificates();
- if (cert_datums.length == 0) {
- warning("No peer certs");
- return false;
- }
- if (cert_datums.length > 1) warning("More than one peer cert");
-
- X509.Certificate peer_cert = X509.Certificate.create();
- peer_cert.import(ref cert_datums[0], CertificateFormat.DER);
-
- DigestAlgorithm algo;
- switch (peer_fp_algo) {
- case "sha-256":
- algo = DigestAlgorithm.SHA256;
- break;
- default:
- warning("Unkown peer fingerprint algorithm: %s", peer_fp_algo);
- return false;
- }
-
- uint8[] real_peer_fp = get_fingerprint(peer_cert, algo);
-
- if (real_peer_fp.length != this.peer_fingerprint.length) {
- warning("Fingerprint lengths not equal %i vs %i", real_peer_fp.length, peer_fingerprint.length);
- return false;
- }
+ running = true;
+ restart = false;
+ buffer_mutex.unlock();
- for (int i = 0; i < real_peer_fp.length; i++) {
- if (real_peer_fp[i] != this.peer_fingerprint[i]) {
- warning("First cert in peer cert list doesn't equal advertised one: %s vs %s", format_fingerprint(real_peer_fp), format_fingerprint(peer_fingerprint));
- return false;
- }
- }
+ // Actual work
+ var res = setup_dtls_connection_thread();
- return true;
+ // Callback
+ Source source = new IdleSource();
+ source.set_callback(setup_dtls_connection.callback);
+ source.attach(context);
+ return res;
+ });
+ yield;
+ return thread.join();
}
-}
-
-private uint8[] get_fingerprint(X509.Certificate certificate, DigestAlgorithm digest_algo) {
- uint8[] buf = new uint8[512];
- size_t buf_out_size = 512;
- certificate.get_fingerprint(digest_algo, buf, ref buf_out_size);
- uint8[] ret = new uint8[buf_out_size];
- for (int i = 0; i < buf_out_size; i++) {
- ret[i] = buf[i];
- }
- return ret;
+ protected abstract Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread();
}
private string format_fingerprint(uint8[] fingerprint) {
diff --git a/plugins/ice/src/dtls_srtp_gnutls.vala b/plugins/ice/src/dtls_srtp_gnutls.vala
new file mode 100644
index 00000000..91a7cfb2
--- /dev/null
+++ b/plugins/ice/src/dtls_srtp_gnutls.vala
@@ -0,0 +1,245 @@
+using GnuTLS;
+
+namespace Dino.Plugins.Ice.DtlsSrtp {
+
+public class CredentialsCapsuleGnuTLS : CredentialsCapsule {
+ public X509.Certificate[] own_cert;
+ public X509.PrivateKey private_key;
+}
+
+private uint8[] get_fingerprint(X509.Certificate certificate, DigestAlgorithm digest_algo) {
+ uint8[] buf = new uint8[512];
+ size_t buf_out_size = 512;
+ certificate.get_fingerprint(digest_algo, buf, ref buf_out_size);
+
+ uint8[] ret = new uint8[buf_out_size];
+ for (int i = 0; i < buf_out_size; i++) {
+ ret[i] = buf[i];
+ }
+ return ret;
+}
+
+internal CredentialsCapsule generate_credentials () throws GLib.Error {
+ int err = 0;
+
+ X509.PrivateKey private_key = X509.PrivateKey.create ();
+ err = private_key.generate (PKAlgorithm.ECDSA, 256);
+ throw_if_error (err);
+
+ var start_time = new DateTime.now_local().add_days(-1);
+ var end_time = start_time.add_days (2);
+
+ X509.Certificate cert = X509.Certificate.create ();
+ cert.set_key (private_key);
+ cert.set_version (1);
+ cert.set_activation_time ((time_t) start_time.to_unix ());
+ cert.set_expiration_time ((time_t) end_time.to_unix ());
+
+ uint32 serial = 1;
+ cert.set_serial (&serial, sizeof(uint32));
+
+ cert.sign (cert, private_key);
+
+ uint8[] own_fingerprint = get_fingerprint (cert, DigestAlgorithm.SHA256);
+ X509.Certificate[] own_cert = new X509.Certificate[] { (owned)cert };
+
+ var creds = new CredentialsCapsuleGnuTLS();
+ creds.own_fingerprint = own_fingerprint;
+ creds.own_cert = (owned) own_cert;
+ creds.private_key = (owned) private_key;
+
+ return creds;
+}
+
+public class Handler : AbstractHandler {
+
+ public Handler.with_cert(CredentialsCapsule creds) {
+ base.with_cert(creds);
+ }
+
+ protected override Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread() {
+ InitFlags server_or_client = mode == Mode.SERVER ? InitFlags.SERVER : InitFlags.CLIENT;
+ debug("Setting up DTLS connection using GnuTLS. We're %s", mode.to_string());
+
+ CertificateCredentials cert_cred = CertificateCredentials.create();
+ int err = cert_cred.set_x509_key(((CredentialsCapsuleGnuTLS)credentials).own_cert, ((CredentialsCapsuleGnuTLS)credentials).private_key);
+ throw_if_error(err);
+
+ Session? session = Session.create(server_or_client | InitFlags.DATAGRAM);
+ session.enable_heartbeat(1);
+ session.set_srtp_profile_direct("SRTP_AES128_CM_HMAC_SHA1_80");
+ session.set_credentials(GnuTLS.CredentialsType.CERTIFICATE, cert_cred);
+ session.server_set_request(CertificateRequest.REQUEST);
+ session.set_priority_from_string("NORMAL:!VERS-TLS-ALL:+VERS-DTLS-ALL:+CTYPE-CLI-X509");
+
+ session.set_transport_pointer(this);
+ session.set_pull_function(pull_function);
+ session.set_pull_timeout_function(pull_timeout_function);
+ session.set_push_function(push_function);
+ session.set_verify_function(verify_function);
+
+ DateTime maximum_time = new DateTime.now_utc().add_seconds(20);
+ do {
+ err = session.handshake();
+
+ DateTime current_time = new DateTime.now_utc();
+ if (maximum_time.compare(current_time) < 0) {
+ warning("DTLS handshake timeouted");
+ err = ErrorCode.APPLICATION_ERROR_MIN + 1;
+ break;
+ }
+ if (stop) {
+ debug("DTLS handshake stopped");
+ err = ErrorCode.APPLICATION_ERROR_MIN + 2;
+ break;
+ }
+ } while (err < 0 && !((ErrorCode)err).is_fatal());
+
+ buffer_mutex.lock();
+ if (stop) {
+ stop = false;
+ running = false;
+ bool restart = restart;
+ buffer_mutex.unlock();
+ if (restart) {
+ debug("Restarting DTLS handshake");
+ return setup_dtls_connection_thread();
+ }
+ return null;
+ }
+ buffer_mutex.unlock();
+ if (err != ErrorCode.SUCCESS) {
+ warning("DTLS handshake failed: %s", ((ErrorCode)err).to_string());
+ return null;
+ }
+
+ uint8[] km = new uint8[150];
+ Datum? client_key, client_salt, server_key, server_salt;
+ session.get_srtp_keys(km, km.length, out client_key, out client_salt, out server_key, out server_salt);
+ if (client_key == null || client_salt == null || server_key == null || server_salt == null) {
+ warning("SRTP client/server key/salt null");
+ }
+
+ debug("Finished DTLS connection. We're %s", mode.to_string());
+ if (mode == Mode.SERVER) {
+ srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract());
+ srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract());
+ } else {
+ srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract());
+ srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract());
+ }
+ return new Xmpp.Xep.Jingle.ContentEncryption(Xmpp.Xep.JingleIceUdp.DTLS_NS_URI, "DTLS-SRTP", credentials.own_fingerprint, peer_fingerprint);
+ }
+
+ private static ssize_t pull_function(void* transport_ptr, uint8[] buffer) {
+ Handler self = transport_ptr as Handler;
+
+ self.buffer_mutex.lock();
+ while (self.buffer_queue.size == 0) {
+ self.buffer_cond.wait(self.buffer_mutex);
+ if (self.stop) {
+ self.buffer_mutex.unlock();
+ debug("DTLS handshake pull_function stopped");
+ return -1;
+ }
+ }
+ Bytes data = self.buffer_queue.remove_at(0);
+ self.buffer_mutex.unlock();
+
+ uint8[] data_uint8 = Bytes.unref_to_data((owned) data);
+ Memory.copy(buffer, data_uint8, data_uint8.length);
+
+ // The callback should return 0 on connection termination, a positive number indicating the number of bytes received, and -1 on error.
+ return (ssize_t)data_uint8.length;
+ }
+
+ private static int pull_timeout_function(void* transport_ptr, uint ms) {
+ Handler self = transport_ptr as Handler;
+
+ int64 end_time = get_monotonic_time() + ms * 1000;
+
+ self.buffer_mutex.lock();
+ while (self.buffer_queue.size == 0) {
+ self.buffer_cond.wait_until(self.buffer_mutex, end_time);
+ if (self.stop) {
+ self.buffer_mutex.unlock();
+ debug("DTLS handshake pull_timeout_function stopped");
+ return -1;
+ }
+
+ if (get_monotonic_time() > end_time) {
+ self.buffer_mutex.unlock();
+ return 0;
+ }
+ }
+ self.buffer_mutex.unlock();
+
+ // The callback should return 0 on timeout, a positive number if data can be received, and -1 on error.
+ return 1;
+ }
+
+ private static ssize_t push_function(void* transport_ptr, uint8[] buffer) {
+ Handler self = transport_ptr as Handler;
+ self.send_data(buffer);
+
+ // The callback should return a positive number indicating the bytes sent, and -1 on error.
+ return (ssize_t)buffer.length;
+ }
+
+ private static int verify_function(Session session) {
+ Handler self = session.get_transport_pointer() as Handler;
+ try {
+ bool valid = self.verify_peer_cert(session);
+ if (!valid) {
+ warning("DTLS certificate invalid. Aborting handshake.");
+ return 1;
+ }
+ } catch (Error e) {
+ warning("Error during DTLS certificate validation: %s. Aborting handshake.", e.message);
+ return 1;
+ }
+
+ // The callback function should return 0 for the handshake to continue or non-zero to terminate.
+ return 0;
+ }
+
+ private bool verify_peer_cert(Session session) throws GLib.Error {
+ unowned Datum[] cert_datums = session.get_peer_certificates();
+ if (cert_datums.length == 0) {
+ warning("No peer certs");
+ return false;
+ }
+ if (cert_datums.length > 1) warning("More than one peer cert");
+
+ X509.Certificate peer_cert = X509.Certificate.create();
+ peer_cert.import(ref cert_datums[0], CertificateFormat.DER);
+
+ DigestAlgorithm algo;
+ switch (peer_fp_algo) {
+ case "sha-256":
+ algo = DigestAlgorithm.SHA256;
+ break;
+ default:
+ warning("Unkown peer fingerprint algorithm: %s", peer_fp_algo);
+ return false;
+ }
+
+ uint8[] real_peer_fp = get_fingerprint(peer_cert, algo);
+
+ if (real_peer_fp.length != this.peer_fingerprint.length) {
+ warning("Fingerprint lengths not equal %i vs %i", real_peer_fp.length, peer_fingerprint.length);
+ return false;
+ }
+
+ for (int i = 0; i < real_peer_fp.length; i++) {
+ if (real_peer_fp[i] != this.peer_fingerprint[i]) {
+ warning("First cert in peer cert list doesn't equal advertised one: %s vs %s", format_fingerprint(real_peer_fp), format_fingerprint(peer_fingerprint));
+ return false;
+ }
+ }
+
+ return true;
+ }
+}
+
+} \ No newline at end of file
diff --git a/plugins/ice/src/dtls_srtp_openssl.vala b/plugins/ice/src/dtls_srtp_openssl.vala
new file mode 100644
index 00000000..86f080e5
--- /dev/null
+++ b/plugins/ice/src/dtls_srtp_openssl.vala
@@ -0,0 +1,202 @@
+using OpenSSL;
+
+namespace Dino.Plugins.Ice.DtlsSrtp {
+
+public class CredentialsCapsuleOpenSSL : CredentialsCapsule {
+ public X509.Certificate own_cert;
+ public EVP.Key private_key;
+}
+
+internal CredentialsCapsule generate_credentials () throws GLib.Error {
+ EVP.Key key = new EVP.Key.generate_ecdsa ("prime256v1");
+
+ var start_time = new DateTime.now_local().add_days(-1);
+ var end_time = start_time.add_days (2);
+
+ X509.Certificate cert = new X509.Certificate ();
+ cert.set_public_key (key);
+ cert.set_version (1);
+ cert.not_before.set ((time_t) start_time.to_unix ());
+ cert.not_after.set ((time_t) end_time.to_unix ());
+ cert.serial_number.set (1);
+
+ cert.sign (key, EVP.sha256 ());
+
+ CredentialsCapsuleOpenSSL credentials = new CredentialsCapsuleOpenSSL ();
+ credentials.own_fingerprint = cert.digest (EVP.sha256 ());
+ credentials.own_cert = (owned) cert;
+ credentials.private_key = (owned) key;
+ return credentials;
+}
+
+public class Handler : AbstractHandler {
+
+ public Handler.with_cert (CredentialsCapsule creds) {
+ base.with_cert (creds);
+ }
+
+ protected override Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread () {
+ debug("Setting up DTLS connection using OpenSSL. We're %s", mode.to_string());
+ SSL.Context context = new SSL.Context (mode == Mode.SERVER ? SSL.Method.DTLS_SERVER : SSL.Method.DTLS_CLIENT);
+ context.set_tlsext_use_srtp ("SRTP_AES128_CM_SHA1_80");
+ context.use_certificate (((CredentialsCapsuleOpenSSL) credentials).own_cert);
+ context.use_private_key (((CredentialsCapsuleOpenSSL) credentials).private_key);
+ SSL session = new SSL (context);
+ BIO<Handler> bio = new BIO<Handler>(get_handler_based_bio_method());
+ bio.data = this;
+ session.rbio = bio;
+ session.wbio = bio;
+
+ DateTime maximum_time = new DateTime.now_utc().add_seconds(20);
+ int err = 0;
+ if (mode == Mode.SERVER) {
+ session.set_accept_state ();
+ } else {
+ session.set_connect_state ();
+ }
+ do {
+ try {
+ SSL.Error ret = session.do_handshake();
+ switch (ret) {
+ case SSL.Error.NONE:
+ err = 1;
+ break;
+ case SSL.Error.WANT_READ:
+ debug ("DTLS wants to read, but nothing in queue, wait for buffer");
+ buffer_mutex.lock();
+ if (buffer_queue.size == 0) {
+ buffer_cond.wait_until(buffer_mutex, get_monotonic_time() + maximum_time.difference(new DateTime.now_utc()));
+ }
+ buffer_mutex.unlock();
+ err = -1;
+ break;
+ default:
+ warning ("DTLS Error: %s", @"$ret");
+ err = 4;
+ break;
+ }
+ } catch (Error e) {
+ warning ("DTLS Error: %s", e.message);
+ err = e.code;
+ }
+
+ DateTime current_time = new DateTime.now_utc();
+ if (maximum_time.compare(current_time) < 0) {
+ debug ("DTLS handshake timeouted");
+ err = 2;
+ break;
+ }
+ if (stop) {
+ debug ("DTLS handshake stopped");
+ err = 3;
+ break;
+ }
+ } while (err < 0);
+
+ buffer_mutex.lock();
+ if (stop) {
+ stop = false;
+ running = false;
+ bool restart = restart;
+ buffer_mutex.unlock();
+ if (restart) {
+ debug ("Restarting DTLS handshake");
+ return setup_dtls_connection_thread();
+ }
+ return null;
+ }
+ buffer_mutex.unlock();
+ if (err != 1) {
+ debug ("DTLS handshake failed");
+ return null;
+ }
+
+ // TODO: Check peer certificate
+
+ uint8[] km = new uint8[60];
+ session.export_keying_material (km, "EXTRACTOR-dtls_srtp");
+ uint8[] client_key = km[0:16];
+ uint8[] server_key = km[16:32];
+ uint8[] client_salt = km[32:46];
+ uint8[] server_salt = km[46:60];
+
+ debug ("Finished DTLS connection. We're %s", mode.to_string());
+ if (mode == Mode.SERVER) {
+ srtp_session.set_encryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key, server_salt);
+ srtp_session.set_decryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key, client_salt);
+ } else {
+ srtp_session.set_encryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key, client_salt);
+ srtp_session.set_decryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key, server_salt);
+ }
+ return new Xmpp.Xep.Jingle.ContentEncryption (Xmpp.Xep.JingleIceUdp.DTLS_NS_URI, "DTLS-SRTP", credentials.own_fingerprint, peer_fingerprint);
+ }
+
+ private int read_impl (BIO<Handler> bio, uint8[] out_buf) {
+ Bytes data = get_buffer_if_present ();
+ if (data == null) {
+ if (!stop) {
+ debug ("No pending buffer in queue, but end not reached yet, set_retry_read");
+ bio.set_retry_read ();
+ }
+ return -1;
+ }
+ if (data.length > out_buf.length) {
+ warning ("Buffer in queue does not fit in out_buf");
+ return -1;
+ }
+ debug ("Read %d bytes from queue", data.length);
+
+ uint8[] data_uint8 = Bytes.unref_to_data((owned) data);
+ Memory.copy (out_buf, data_uint8, data_uint8.length);
+ bio.clear_retry_flags ();
+ return data_uint8.length;
+ }
+
+ private int write_impl (BIO<Handler> bio, uint8[] buf) {
+ debug ("Write %d bytes to network", buf.length);
+ send_data (buf);
+ return buf.length;
+ }
+
+ private long ctrl_impl (BIO<Handler> bio, BIO.ControlCommand cmd, long num, void* ptr) {
+ switch (cmd) {
+ case BIO.ControlCommand.FLUSH:
+ // Datagrams are sent out immediately
+ return 1;
+ case BIO.ControlCommand.DGRAM_SET_NEXT_TIMEOUT:
+ // Datagrams are sent out immediately
+ return 1;
+ case BIO.ControlCommand.DGRAM_GET_MTU_OVERHEAD:
+ // Just some safe estimate
+ return 70;
+ case BIO.ControlCommand.DGRAM_QUERY_MTU:
+ // Just some safe estimate
+ return 1200;
+ case BIO.ControlCommand.WPENDING:
+ // Datagrams are sent out immediately
+ return 0;
+ case BIO.ControlCommand.POP:
+ case BIO.ControlCommand.PUSH:
+ // Ignored
+ return 0;
+ default:
+ warning (@"Unimplemented ctrl cmd:$cmd, num:$num");
+ return 0;
+ }
+ }
+
+ private static BIO.Method<Handler> _handler_based_bio_method_instance = null;
+
+ private static unowned BIO.Method<Handler> get_handler_based_bio_method () {
+ if (_handler_based_bio_method_instance != null) return _handler_based_bio_method_instance;
+ _handler_based_bio_method_instance = new BIO.Method<Handler> (BIO.Type.SOURCE_SINK | BIO.Type.DGRAM, "Dino DTLS Handler BIO");
+ _handler_based_bio_method_instance.read = (bio, out_buf) => bio.data.read_impl (bio, out_buf);
+ _handler_based_bio_method_instance.write = (bio, buf) => bio.data.write_impl (bio, buf);
+ _handler_based_bio_method_instance.ctrl = (bio, cmd, num, ptr) => bio.data.ctrl_impl (bio, cmd, num, ptr);
+ return _handler_based_bio_method_instance;
+ }
+}
+
+
+
+} \ No newline at end of file
diff --git a/plugins/ice/src/module.vala b/plugins/ice/src/module.vala
index 2645d7dc..ace62108 100644
--- a/plugins/ice/src/module.vala
+++ b/plugins/ice/src/module.vala
@@ -42,7 +42,7 @@ public class Dino.Plugins.Ice.Module : JingleIceUdp.Module {
private DtlsSrtp.CredentialsCapsule? get_create_credentials(Jid local_full_jid, Jid peer_full_jid) {
string from_to_id = local_full_jid.to_string() + peer_full_jid.to_string();
try {
- if (!cerds.has_key(from_to_id)) cerds[from_to_id] = DtlsSrtp.Handler.generate_credentials();
+ if (!cerds.has_key(from_to_id)) cerds[from_to_id] = DtlsSrtp.generate_credentials();
} catch (Error e) {
warning("Error creating dtls credentials: %s", e.message);
}
diff --git a/plugins/ice/src/openssl_utils.c b/plugins/ice/src/openssl_utils.c
new file mode 100644
index 00000000..7f4bf331
--- /dev/null
+++ b/plugins/ice/src/openssl_utils.c
@@ -0,0 +1,49 @@
+#include "openssl_utils.h"
+#include <openssl/opensslv.h>
+#include <openssl/ec.h>
+
+#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x30000000L
+// This is for OpenSSL 3.0.0 and newer
+
+EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve) {
+ // Generate EVP_PKEY directly
+ EVP_PKEY *pkey = EVP_EC_gen (curve);
+ return pkey;
+}
+
+#else
+// This is for OpenSSL before 3.0.0 and forks of earlier OpenSSL versions like LibreSSL
+
+EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve) {
+ // Get NID from curve name
+ int nid = OBJ_sn2nid (curve);
+ if (nid == NID_undef) return NULL;
+
+ // Create EC_KEY
+ EC_KEY *ec_key = EC_KEY_new_by_curve_name (nid);
+ if (!ec_key) return NULL;
+
+ // Generate key
+ if (!EC_KEY_generate_key (ec_key)) {
+ EC_KEY_free (ec_key);
+ return NULL;
+ }
+
+ // Create EVP_PKEY
+ EVP_PKEY *pkey = EVP_PKEY_new ();
+ if (!pkey) {
+ EC_KEY_free (ec_key);
+ return NULL;
+ }
+
+ // Assign EC_KEY to EVP_PKEY
+ if (!EVP_PKEY_assign_EC_KEY (pkey, ec_key)) {
+ EC_KEY_free (ec_key);
+ return NULL;
+ }
+
+ // EVP_PKEY_assign_EC_KEY takes ownership of ec_key, no need to free it explicitly
+ return pkey;
+}
+
+#endif
diff --git a/plugins/ice/src/openssl_utils.h b/plugins/ice/src/openssl_utils.h
new file mode 100644
index 00000000..bcc6f53a
--- /dev/null
+++ b/plugins/ice/src/openssl_utils.h
@@ -0,0 +1,8 @@
+#ifndef DINO_OPENSSL_UTILS_H
+#define DINO_OPENSSL_UTILS_H
+
+#include <openssl/evp.h>
+
+EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve);
+
+#endif //DINO_OPENSSL_UTILS_H \ No newline at end of file
diff --git a/plugins/ice/vapi/openssl.vapi b/plugins/ice/vapi/openssl.vapi
new file mode 100644
index 00000000..e0654869
--- /dev/null
+++ b/plugins/ice/vapi/openssl.vapi
@@ -0,0 +1,218 @@
+[CCode (cprefix = "")]
+namespace OpenSSL {
+ [CCode (cprefix = "ASN1_", lower_case_cprefix = "ASN1_", cheader_filename = "openssl/asn1.h")]
+ namespace ASN1 {
+ [Compact]
+ [CCode (cname = "ASN1_INTEGER", lower_case_cprefix = "ASN1_INTEGER_", cprefix = "ASN1_INTEGER_", free_function = "ASN1_INTEGER_free")]
+ public class Integer {
+ public bool @set (long v);
+ }
+
+ [Compact]
+ [CCode (cname = "ASN1_TIME", lower_case_cprefix = "ASN1_TIME_", cprefix = "ASN1_TIME_", copy_function = "ASN1_TIME_dup", free_function = "ASN1_STRING_free")]
+ public class Time {
+ public bool @set (time_t t);
+ }
+ }
+ [Compact]
+ [CCode (cname = "BIO", lower_case_cprefix = "BIO_", cprefix = "BIO_", ref_function = "BIO_up_ref", ref_function_void = true, unref_function = "BIO_free", cheader_filename = "openssl/bio.h", simple_generics = true)]
+ public class BIO<T> {
+ [Compact]
+ [CCode (cname = "BIO_METHOD", lower_case_cprefix = "BIO_meth_", cprefix = "BIO_meth_", unref_function = "BIO_meth_free", simple_generics = true)]
+ public class Method<T> {
+ public Method (Type type, string name);
+ [CCode (has_target = false)]
+ public delegate int WriteFunc<T> (BIO<T> bio, [CCode (type = "const char *", array_length_type = "int")] uint8[] buf);
+ [CCode (has_target = false)]
+ public delegate int ReadFunc<T> (BIO<T> bio, [CCode (type = "char *", array_length_type = "int")] uint8[] out_buf);
+ [CCode (has_target = false, simple_generics = true)]
+ public delegate long CtrlFunc<T> (BIO<T> bio, ControlCommand cmd, long num, void* ptr);
+ public WriteFunc<T> write { get; set; }
+ public ReadFunc<T> read { get; set; }
+ public CtrlFunc<T> ctrl { get; set; }
+ }
+
+ [Flags]
+ [CCode (cname = "int")]
+ public enum Type {
+ SOURCE_SINK,
+ DGRAM,
+ }
+
+ [CCode (cname = "int", cprefix = "BIO_CTRL_", has_type_id = false)]
+ public enum ControlCommand {
+ RESET,
+ EOF,
+ SET,
+ GET,
+ PUSH,
+ POP,
+ GET_CLOSE,
+ SET_CLOSE,
+ PENDING,
+ FLUSH,
+ DUP,
+ WPENDING,
+
+ DGRAM_QUERY_MTU,
+ DGRAM_GET_MTU,
+ DGRAM_SET_MTU,
+ DGRAM_SET_PEER,
+ DGRAM_SET_NEXT_TIMEOUT,
+ DGRAM_GET_PEER,
+ DGRAM_GET_FALLBACK_MTU,
+ DGRAM_SET_DONT_FRAG,
+ DGRAM_GET_MTU_OVERHEAD,
+ }
+
+ public BIO (Method<T> type);
+ public T data { get; set; }
+
+ public void clear_retry_flags ();
+ public void set_retry_read ();
+ public bool should_read ();
+ }
+
+ [CCode (cprefix = "ERR_", lower_case_cprefix = "ERR_", cheader_filename = "openssl/err.h")]
+ namespace ERR {
+ public ulong get_error ();
+ public unowned string lib_error_string (ulong error);
+ public unowned string reason_error_string (ulong error);
+ }
+
+ [CCode (cprefix = "EVP_", lower_case_cprefix = "EVP_", cheader_filename = "openssl/evp.h")]
+ namespace EVP {
+ [Compact]
+ [CCode (cname = "EVP_PKEY", lower_case_cprefix = "EVP_PKEY_", cprefix = "EVP_PKEY_", ref_function = "EVP_PKEY_up_ref", ref_function_void = true, unref_function = "EVP_PKEY_free")]
+ public class Key {
+ public Key ();
+ [CCode (cheader_filename = "openssl_utils.h")]
+ public Key.generate_ecdsa (string curve);
+ }
+ [Compact]
+ [CCode (cname = "EVP_MD", lower_case_cprefix = "EVP_MD_", cprefix = "EVP_MD_", ref_function = "EVP_MD_up_ref", ref_function_void = true, unref_function = "EVP_MD_free")]
+ public class MessageDigest {
+ }
+
+ public static unowned MessageDigest sha256 ();
+ }
+
+ [Compact]
+ [CCode (cname = "SSL", lower_case_cprefix = "SSL_", cprefix = "SSL_", ref_function = "SSL_up_ref", ref_function_void = true, unref_function = "SSL_free", cheader_filename = "openssl/ssl.h")]
+ class SSL {
+ [Compact]
+ [CCode (cname = "SSL_CTX", lower_case_cprefix = "SSL_CTX_", cprefix = "SSL_CTX_", ref_function = "SSL_CTX_up_ref", ref_function_void = true, unref_function = "SSL_CTX_free")]
+ public class Context {
+ public Context (Method method);
+ public int set_tlsext_use_srtp (string profiles);
+ public int use_certificate (X509.Certificate certificate);
+ [CCode (cname = "SSL_CTX_use_PrivateKey")]
+ public int use_private_key (EVP.Key private_key);
+ }
+
+ [CCode (cname = "const SSL_METHOD*")]
+ public enum Method {
+ [CCode (cname = "DTLS_client_method()")]
+ DTLS_CLIENT,
+ [CCode (cname = "DTLS_server_method()")]
+ DTLS_SERVER,
+ }
+
+ [CCode (cname = "int", has_type_id = false)]
+ public enum Error {
+ NONE,
+ ZERO_RETURN,
+ WANT_READ,
+ WANT_WRITE,
+ WANT_CONNECT,
+ WANT_ACCEPT,
+ WANT_X509_LOOKUP,
+ WANT_ASYNC,
+ WANT_ASYNC_JOB,
+ WANT_CLIENT_HELLO_CB,
+ SYSCALL,
+ SSL
+ }
+
+ public SSL (Context context);
+ public BIO rbio { get; [CCode (cname="SSL_set0_rbio")] owned set; }
+ public BIO wbio { get; [CCode (cname="SSL_set0_wbio")] owned set; }
+
+ [CCode (cname = "SSL_do_handshake")]
+ private int do_handshake_ ();
+ [CCode (cname = "SSL_do_handshake_")]
+ public Error do_handshake () throws GLib.Error {
+ int ret = throw_if_error (do_handshake_ ());
+ return get_error (ret);
+ }
+ [CCode (cname = "SSL_export_keying_material")]
+ private int export_keying_material_ (uint8[] out, string label, size_t llen, [CCode (type = "const unsigned char *")] string context, size_t contextlen, bool use_context);
+ [CCode (cname = "SSL_export_keying_material_")]
+ public void export_keying_material (uint8[] out, string label, string? context = null) throws GLib.Error {
+ throw_if_error (export_keying_material_ (@out, label, label.length, context, context == null ? 0 : context.length, context != null));
+ }
+ public Error get_error (int ret);
+ public void set_accept_state ();
+ public void set_connect_state ();
+ public int want ();
+ }
+
+ [CCode (cprefix = "X509_", lower_case_cprefix = "X509_", cheader_filename = "openssl/x509.h")]
+ namespace X509 {
+ [Compact]
+ [CCode (cname = "X509", lower_case_cprefix = "X509_", cprefix = "X509_", ref_function = "X509_up_ref", ref_function_void = true, unref_function = "X509_free")]
+ public class Certificate {
+ public Certificate ();
+ public ASN1.Time not_before {
+ [CCode (cname = "X509_get_notBefore")]
+ get;
+ [CCode (cname = "X509_set_notBefore")]
+ set;
+ }
+ public ASN1.Time not_after {
+ [CCode (cname = "X509_get_notAfter")]
+ get;
+ [CCode (cname = "X509_set_notAfter")]
+ set;
+ }
+ public ASN1.Integer serial_number {
+ [CCode (cname = "X509_get_serialNumber")]
+ get;
+ [CCode (cname = "X509_set_serialNumber")]
+ set;
+ }
+ [CCode (cname = "X509_digest")]
+ private int digest_ (EVP.MessageDigest type, uchar* md, ref uint len);
+ [CCode (cname = "X509_digest_")]
+ public uint8[] digest (EVP.MessageDigest type, size_t buf_len = 512) throws GLib.Error {
+ uint8[] buf = new uint8[buf_len];
+ uint buf_out_size = (uint) buf_len;
+ throw_if_error (digest_ (type, (uchar*) buf, ref buf_out_size));
+
+ uint8[] ret = new uint8[buf_out_size];
+ for (int i = 0; i < buf_out_size; i++) {
+ ret[i] = buf[i];
+ }
+ return ret;
+ }
+ [CCode (cname = "X509_set_pubkey")]
+ public int set_public_key (EVP.Key public_key);
+ public int set_version (long version);
+ [CCode (cname = "X509_sign")]
+ private int sign_ (EVP.Key private_key, EVP.MessageDigest md);
+ [CCode (cname = "X509_sign_")]
+ public void sign (EVP.Key private_key, EVP.MessageDigest md) throws GLib.Error {
+ throw_if_error (sign_ (private_key, md));
+ }
+ }
+ }
+
+ public int throw_if_error(int res) throws GLib.Error {
+ if (res <= 0) {
+ ulong error = ERR.get_error ();
+ if (error == 0) return res;
+ throw new GLib.Error (-1, (int) error, "%s:%s", ERR.lib_error_string (error), ERR.reason_error_string (error));
+ }
+ return res;
+ }
+} \ No newline at end of file