]> git.sur5r.net Git - openldap/blobdiff - libraries/libldap/tls_o.c
ITS#8753 Public key pinning support in libldap
[openldap] / libraries / libldap / tls_o.c
index 95fb62890c58bc4a6bb8a7ea712c5796b7d38b2f..d3b6ceb35fae5752f8f2382a85b186bf930bc405 100644 (file)
@@ -835,6 +835,69 @@ tlso_session_peercert( tls_session *sess, struct berval *der )
        return 0;
 }
 
+static int
+tlso_session_pinning( LDAP *ld, tls_session *sess, char *hashalg, struct berval *hash )
+{
+       tlso_session *s = (tlso_session *)sess;
+       char *tmp, digest[EVP_MAX_MD_SIZE];
+       struct berval key,
+                                 keyhash = { .bv_val = digest, .bv_len = sizeof(digest) };
+       X509 *cert = SSL_get_peer_certificate(s);
+       int len, rc = LDAP_SUCCESS;
+
+       len = i2d_X509_PUBKEY( X509_get_X509_PUBKEY(cert), NULL );
+
+       key.bv_val = tmp = LDAP_MALLOC( len );
+       if ( !key.bv_val ) {
+               return -1;
+       }
+
+       key.bv_len = i2d_X509_PUBKEY( X509_get_X509_PUBKEY(cert), &tmp );
+
+       if ( hashalg ) {
+               const EVP_MD *md;
+               EVP_MD_CTX *mdctx;
+               unsigned int len = keyhash.bv_len;
+
+               md = EVP_get_digestbyname( hashalg );
+               if ( !md ) {
+                       Debug( LDAP_DEBUG_TRACE, "tlso_session_pinning: "
+                                       "hash %s not recognised by OpenSSL\n", hashalg, 0, 0 );
+                       rc = -1;
+                       goto done;
+               }
+
+               mdctx = EVP_MD_CTX_new();
+               if ( !mdctx ) {
+                       rc = -1;
+                       goto done;
+               }
+
+               EVP_DigestInit_ex( mdctx, md, NULL );
+               EVP_DigestUpdate( mdctx, key.bv_val, key.bv_len );
+               EVP_DigestFinal_ex( mdctx, (unsigned char *)keyhash.bv_val, &len );
+               keyhash.bv_len = len;
+               EVP_MD_CTX_free( mdctx );
+       } else {
+               keyhash = key;
+       }
+
+       if ( ber_bvcmp( hash, &keyhash ) ) {
+               rc = LDAP_CONNECT_ERROR;
+               Debug( LDAP_DEBUG_ANY, "tlso_session_pinning: "
+                               "public key hash does not match provided pin.\n", 0, 0, 0 );
+               if ( ld->ld_error ) {
+                       LDAP_FREE( ld->ld_error );
+               }
+               ld->ld_error = LDAP_STRDUP(
+                       _("TLS: public key hash does not match provided pin"));
+       }
+
+done:
+       LDAP_FREE( key.bv_val );
+       return rc;
+}
+
 /*
  * TLS support for LBER Sockbufs
  */
@@ -1368,6 +1431,7 @@ tls_impl ldap_int_tls_impl = {
        tlso_session_version,
        tlso_session_cipher,
        tlso_session_peercert,
+       tlso_session_pinning,
 
        &tlso_sbio,