On 11/12/20 4:21 PM, Andrew Dunstan wrote: > On 11/12/20 8:37 AM, Daniel Gustafsson wrote: >>> On 11 Nov 2020, at 21:44, Andrew Dunstan <and...@dunslane.net> wrote: >>> If people like this idea I'll add tests and docco and add it to the next CF. >> Sounds like a good idea, please do. >> >> Can this case really happen in non-ancient OpenSSL version? >> + if (!x509name) > Probably not. I'll get rid of that. > > >> Doesn't this returnpath need a pfree(peer_cn)? >> + bio = BIO_new(BIO_s_mem()); >> + if (!bio) >> + { >> + return -1; >> + } >> > Yeah, I'll make another pass over the cleanups. >
OK, here's a new patch, including docco and tests. cheers andrew -- Andrew Dunstan EDB: https://www.enterprisedb.com
diff --git a/doc/src/sgml/client-auth.sgml b/doc/src/sgml/client-auth.sgml index bad3c3469c..b039522f96 100644 --- a/doc/src/sgml/client-auth.sgml +++ b/doc/src/sgml/client-auth.sgml @@ -604,7 +604,7 @@ hostnogssenc <replaceable>database</replaceable> <replaceable>user</replaceabl </para> <para> - In addition to the method-specific options listed below, there is one + In addition to the method-specific options listed below, there is a method-independent authentication option <literal>clientcert</literal>, which can be specified in any <literal>hostssl</literal> record. This option can be set to <literal>verify-ca</literal> or @@ -618,6 +618,19 @@ hostnogssenc <replaceable>database</replaceable> <replaceable>user</replaceabl the verification of client certificates with any authentication method that supports <literal>hostssl</literal> entries. </para> + <para> + On any record using client certificate authentication, that is one + using the <literal>cert</literal> authentication method or one + using the <literal>clientcert</literal> option, you can specify + which part of the client certificate credentials to match using + the <literal>clientname</literal> option. This option can have one + of two values. If you specify <literal>clientname=CN</literal>, which + is the default, the username is matched against the certificate's + <literal>Common Name (CN)</literal>. If instead you specify + <literal>clientname=DN</literal> the username is matched against the + entire <literal>Distinguished Name (DN)</literal> of the certificate. + This option is probably best used in comjunction with a username map. + </para> </listitem> </varlistentry> </variablelist> diff --git a/src/backend/libpq/auth.c b/src/backend/libpq/auth.c index d132c5cb48..7e40de82e0 100644 --- a/src/backend/libpq/auth.c +++ b/src/backend/libpq/auth.c @@ -2869,12 +2869,15 @@ static int CheckCertAuth(Port *port) { int status_check_usermap = STATUS_ERROR; + char *peer_username; Assert(port->ssl); /* Make sure we have received a username in the certificate */ - if (port->peer_cn == NULL || - strlen(port->peer_cn) <= 0) + peer_username = port->hba->clientcertname == clientCertCN ? port->peer_cn : port->peer_dn; + + if (peer_username == NULL || + strlen(peer_username) <= 0) { ereport(LOG, (errmsg("certificate authentication failed for user \"%s\": client certificate contains no user name", @@ -2882,8 +2885,8 @@ CheckCertAuth(Port *port) return STATUS_ERROR; } - /* Just pass the certificate cn to the usermap check */ - status_check_usermap = check_usermap(port->hba->usermap, port->user_name, port->peer_cn, false); + /* Just pass the certificate cn/dn to the usermap check */ + status_check_usermap = check_usermap(port->hba->usermap, port->user_name, peer_username, false); if (status_check_usermap != STATUS_OK) { /* @@ -2894,7 +2897,7 @@ CheckCertAuth(Port *port) if (port->hba->clientcert == clientCertFull && port->hba->auth_method != uaCert) { ereport(LOG, - (errmsg("certificate validation (clientcert=verify-full) failed for user \"%s\": CN mismatch", + (errmsg("certificate validation (clientcert=verify-full) failed for user \"%s\": CN/DN mismatch", port->user_name))); } } diff --git a/src/backend/libpq/be-secure-openssl.c b/src/backend/libpq/be-secure-openssl.c index e10260051f..6fe06c8d2a 100644 --- a/src/backend/libpq/be-secure-openssl.c +++ b/src/backend/libpq/be-secure-openssl.c @@ -520,22 +520,25 @@ aloop: /* Get client certificate, if available. */ port->peer = SSL_get_peer_certificate(port->ssl); - /* and extract the Common Name from it. */ + /* and extract the Common Name / Distinguished Name from it. */ port->peer_cn = NULL; + port->peer_dn = NULL; port->peer_cert_valid = false; if (port->peer != NULL) { int len; + X509_NAME *x509name = X509_get_subject_name(port->peer); + char *peer_cn; + char *peer_dn; + BIO *bio = NULL; + BUF_MEM *bio_buf = NULL; - len = X509_NAME_get_text_by_NID(X509_get_subject_name(port->peer), - NID_commonName, NULL, 0); + len = X509_NAME_get_text_by_NID(x509name, NID_commonName, NULL, 0); if (len != -1) { - char *peer_cn; - peer_cn = MemoryContextAlloc(TopMemoryContext, len + 1); - r = X509_NAME_get_text_by_NID(X509_get_subject_name(port->peer), - NID_commonName, peer_cn, len + 1); + r = X509_NAME_get_text_by_NID(x509name, NID_commonName, peer_cn, + len + 1); peer_cn[len] = '\0'; if (r != len) { @@ -559,6 +562,36 @@ aloop: port->peer_cn = peer_cn; } + + bio = BIO_new(BIO_s_mem()); + if (!bio) + { + pfree(port->peer_cn); + port->peer_cn = NULL; + return -1; + } + /* use commas instead of slashes */ + X509_NAME_print_ex(bio, x509name, 0, XN_FLAG_SEP_COMMA_PLUS); + BIO_get_mem_ptr(bio, &bio_buf); + peer_dn = MemoryContextAlloc(TopMemoryContext, bio_buf->length + 1); + memcpy(peer_dn, bio_buf->data, bio_buf->length); + peer_dn[bio_buf->length] = '\0'; + if (bio_buf->length != strlen(peer_dn)) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("SSL certificate's distinguished name contains embedded null"))); + BIO_free(bio); + pfree(peer_dn); + pfree(port->peer_cn); + port->peer_cn = NULL; + return -1; + } + + BIO_free(bio); + + port->peer_dn = peer_dn; + port->peer_cert_valid = true; } @@ -590,6 +623,12 @@ be_tls_close(Port *port) pfree(port->peer_cn); port->peer_cn = NULL; } + + if (port->peer_dn) + { + pfree(port->peer_dn); + port->peer_dn = NULL; + } } ssize_t diff --git a/src/backend/libpq/be-secure.c b/src/backend/libpq/be-secure.c index 2ae507a902..ef1320e686 100644 --- a/src/backend/libpq/be-secure.c +++ b/src/backend/libpq/be-secure.c @@ -120,7 +120,7 @@ secure_open_server(Port *port) ereport(DEBUG2, (errmsg("SSL connection from \"%s\"", - port->peer_cn ? port->peer_cn : "(anonymous)"))); + port->peer_dn ? port->peer_dn : "(anonymous)"))); #endif return r; diff --git a/src/backend/libpq/hba.c b/src/backend/libpq/hba.c index 3a78d2043e..5e17382085 100644 --- a/src/backend/libpq/hba.c +++ b/src/backend/libpq/hba.c @@ -1765,6 +1765,37 @@ parse_hba_auth_opt(char *name, char *val, HbaLine *hbaline, return false; } } + else if (strcmp(name, "clientname") == 0) + { + if (hbaline->conntype != ctHostSSL) + { + ereport(elevel, + (errcode(ERRCODE_CONFIG_FILE_ERROR), + errmsg("clientname can only be configured for \"hostssl\" rows"), + errcontext("line %d of configuration file \"%s\"", + line_num, HbaFileName))); + *err_msg = "clientname can only be configured for \"hostssl\" rows"; + return false; + } + + if (strcmp(val, "CN") == 0) + { + hbaline->clientcertname = clientCertCN; + } + else if (strcmp(val, "DN") == 0) + { + hbaline->clientcertname = clientCertDN; + } + else + { + ereport(elevel, + (errcode(ERRCODE_CONFIG_FILE_ERROR), + errmsg("invalid value for clientname: \"%s\"", val), + errcontext("line %d of configuration file \"%s\"", + line_num, HbaFileName))); + return false; + } + } else if (strcmp(name, "pamservice") == 0) { REQUIRE_AUTH_OPTION(uaPAM, "pamservice", "pam"); diff --git a/src/include/libpq/hba.h b/src/include/libpq/hba.h index 8f09b5638f..443b3560ef 100644 --- a/src/include/libpq/hba.h +++ b/src/include/libpq/hba.h @@ -69,7 +69,13 @@ typedef enum ClientCertMode clientCertOff, clientCertCA, clientCertFull -} ClientCertMode; +} ClientCertMode; + +typedef enum ClientCertName +{ + clientCertCN, + clientCertDN +} ClientCertName; typedef struct HbaLine { @@ -101,6 +107,7 @@ typedef struct HbaLine char *ldapprefix; char *ldapsuffix; ClientCertMode clientcert; + ClientCertName clientcertname; char *krb_realm; bool include_realm; bool compat_realm; diff --git a/src/include/libpq/libpq-be.h b/src/include/libpq/libpq-be.h index 0a23281ad5..bc56551d2e 100644 --- a/src/include/libpq/libpq-be.h +++ b/src/include/libpq/libpq-be.h @@ -189,6 +189,7 @@ typedef struct Port */ bool ssl_in_use; char *peer_cn; + char *peer_dn; bool peer_cert_valid; /* diff --git a/src/test/ssl/Makefile b/src/test/ssl/Makefile index 777ee39413..a65b96bffe 100644 --- a/src/test/ssl/Makefile +++ b/src/test/ssl/Makefile @@ -18,7 +18,7 @@ export with_openssl CERTIFICATES := server_ca server-cn-and-alt-names \ server-cn-only server-single-alt-name server-multiple-alt-names \ server-no-names server-revoked server-ss \ - client_ca client client-revoked \ + client_ca client client-dn client-revoked \ root_ca SSLFILES := $(CERTIFICATES:%=ssl/%.key) $(CERTIFICATES:%=ssl/%.crt) \ @@ -88,6 +88,13 @@ ssl/client.crt: ssl/client.key ssl/client_ca.crt openssl x509 -in ssl/temp.crt -out ssl/client.crt # to keep just the PEM cert rm ssl/client.csr ssl/temp.crt +# Client certificate with multi-parth DN, signed by the client CA: +ssl/client-dn.crt: ssl/client-dn.key ssl/client_ca.crt + openssl req -new -key ssl/client-dn.key -out ssl/client-dn.csr -config client-dn.config + openssl ca -name client_ca -batch -out ssl/temp.crt -config cas.config -infiles ssl/client-dn.csr + openssl x509 -in ssl/temp.crt -out ssl/client-dn.crt # to keep just the PEM cert + rm ssl/client-dn.csr ssl/temp.crt + # Another client certificate, signed by the client CA. This one is revoked. ssl/client-revoked.crt: ssl/client-revoked.key ssl/client_ca.crt client.config openssl req -new -key ssl/client-revoked.key -out ssl/client-revoked.csr -config client.config diff --git a/src/test/ssl/client-dn.config b/src/test/ssl/client-dn.config new file mode 100644 index 0000000000..75c42cf966 --- /dev/null +++ b/src/test/ssl/client-dn.config @@ -0,0 +1,16 @@ +# An OpenSSL format CSR config file for creating a client certificate. +# +# The certificate is for user "ssltestuser-dn" with a multi-part DN + +[ req ] +distinguished_name = req_distinguished_name +prompt = no + +[ req_distinguished_name ] +O = PGDG +OU = Engineering +OU = Testing +CN = ssltestuser-dn + +# no extensions in client certs +[ v3_req ] diff --git a/src/test/ssl/ssl/client-dn.crt b/src/test/ssl/ssl/client-dn.crt new file mode 100644 index 0000000000..938bf91422 --- /dev/null +++ b/src/test/ssl/ssl/client-dn.crt @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC8DCCAdgCAQMwDQYJKoZIhvcNAQELBQAwQjFAMD4GA1UEAww3VGVzdCBDQSBm +b3IgUG9zdGdyZVNRTCBTU0wgcmVncmVzc2lvbiB0ZXN0IGNsaWVudCBjZXJ0czAe +Fw0yMDExMTcxNTU2MDdaFw00ODA0MDQxNTU2MDdaMDoxDTALBgNVBAoMBFBHREcx +EDAOBgNVBAsMB1Rlc3RpbmcxFzAVBgNVBAMMDnNzbHRlc3R1c2VyLWRuMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwMJM/Yqo4k0+wUSR3ixF2zHyj3rm +AaWEUKp0E0bHW4SUr8FoPYUdDL0OidLPOe8hDNeZMdCxxlUZ+g7YmiEnRUJPb8G4 +GtCG9DwmMClSw3uDwqbPPfK4agw/Y4/XF26BCpz99GCKb24a6+Ub1cKOrz/82iKX +KJydOWDHvOK9dsbFeMqmNGfIO3Q3tzSUVUUOKclsd/91rMKztNMtej1zBJstDJvn +yAlpVZNg1CSosqqFhOiYKQhMs8uXr801U/np9b5cWTP3Umg8NRnvC6FYJ6jv7ynT +sF5mrwOiCFyCEtR2b01CJMEX5kULzivm/mAMtZ1iElciwSS3uRZ7JJM90QIDAQAB +MA0GCSqGSIb3DQEBCwUAA4IBAQCNgKjcLgkZmNgAuuPVNAE2o7KipfAyjYTaaipk +fcQH2mscJmVJmrdeOV9L7UMYBapcrHoYfSUmUZH6If1iRY5NR4c8TmvM889ko28c +eDG0+J2PRJCqA5Ynu3HecMS3CXFas2p+s5Wy0QVc/lku6sAyFg0GrxESWNTg8bCW +REBQGPBhyU7H+/FERMsn/cNjombcuCtzIHNxPwBkq1IZXXY0PfSgi/pq3XGFoqzn +8yO3WD6PdttQyHNJSkpqOZbe7rhQBkGtx1Es3KhP9Jegm+dXUnl0DNBIU029X5Z0 +9DlvKp/abrNjvKcC5k+/vZdBLoRTfOFCEMVM0Cj0zns17b4O +-----END CERTIFICATE----- diff --git a/src/test/ssl/ssl/client-dn.key b/src/test/ssl/ssl/client-dn.key new file mode 100644 index 0000000000..e020e0884b --- /dev/null +++ b/src/test/ssl/ssl/client-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3k342m+qhuGv +0JKbPebji15ehankbwzezCSsdodf3KBl6GnYvc8CgYEAtIvfvgdrKS3afz0etWQT +xPOMXBsh6+jrxA06JG9QTrCgbrSpB2+Lhu96BgmjSoFuXM5eVUQvRViVfVUwpLLa +/aosv/HUTzRkFVAhzSpkw9QTxKzVDrZ81xDuQQBChwuYBA0phd3zmcDx0fZbjRAA +asUFYKQaleb1WCf2oWZ17J8CgYEAlYEivr6RAws4xXpF9bCMn0AzuC9+NUTit2u+ +KyldplU56auNNPizLNIpM3iUSCocUSvrSrGkFiMdKEsH+ctBefDlHblfldreZ3Hx +ZNB+J5xlr/IVz0D7Xv3y75KlluXFa102KZAYcuuU9oZP1A+iokbLhFUIXJR/mSZ+ +h7K6E/cCgYBWPG81s8o0uwR953GgthZJx02+/ORs5rbAs5uUlpBXvoH1wBap1Ffd +8ZGhcaFBbQdmTtzUtei4kqggVg1jOQZ2hwhqlmQljQuOOEuS4mh/b+RVNGtj/Wnc +17uxEO1y6vTcxZ3aCqCXrkX5Q+FpQbyFRGMmUXC1UgE+b8rWHyr1oQ== +-----END RSA PRIVATE KEY----- diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl index fd2727b568..50d43e71b4 100644 --- a/src/test/ssl/t/001_ssltests.pl +++ b/src/test/ssl/t/001_ssltests.pl @@ -13,7 +13,7 @@ use SSLServer; if ($ENV{with_openssl} eq 'yes') { - plan tests => 93; + plan tests => 96; } else { @@ -40,7 +40,7 @@ my $common_connstr; my @keys = ( "client", "client-revoked", "client-der", "client-encrypted-pem", - "client-encrypted-der"); + "client-encrypted-der", "client-dn"); foreach my $key (@keys) { copy("ssl/${key}.key", "ssl/${key}_tmp.key") @@ -435,6 +435,37 @@ test_connect_fails( "certificate authorization fails with correct client cert and wrong password in encrypted PEM format" ); + +# correct client cert using whole DN +my $dn_connstr = $common_connstr; +$dn_connstr =~ s/certdb/certdb_dn/; + +test_connect_ok( + $dn_connstr, + "user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key", + "certificate authorization succeeds with DN mapping" +); + +# same thing but with a regex +$dn_connstr =~ s/certdb_dn/certdb_dn_re/; + +test_connect_ok( + $dn_connstr, + "user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key", + "certificate authorization succeeds with DN regex mapping" +); + +# same thing but using explicit CN +$dn_connstr =~ s/certdb_dn_re/certdb_cn/; + +test_connect_ok( + $dn_connstr, + "user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key", + "certificate authorization succeeds with CN mapping" +); + + + TODO: { # these tests are left here waiting on us to get better pty support diff --git a/src/test/ssl/t/SSLServer.pm b/src/test/ssl/t/SSLServer.pm index f5987a003e..0df40ea5da 100644 --- a/src/test/ssl/t/SSLServer.pm +++ b/src/test/ssl/t/SSLServer.pm @@ -109,6 +109,9 @@ sub configure_test_server_for_ssl $node->psql('postgres', "CREATE USER yetanotheruser"); $node->psql('postgres', "CREATE DATABASE trustdb"); $node->psql('postgres', "CREATE DATABASE certdb"); + $node->psql('postgres', "CREATE DATABASE certdb_dn"); + $node->psql('postgres', "CREATE DATABASE certdb_dn_re"); + $node->psql('postgres', "CREATE DATABASE certdb_cn"); $node->psql('postgres', "CREATE DATABASE verifydb"); # Update password of each user as needed. @@ -205,7 +208,20 @@ sub configure_hba_for_ssl "hostssl verifydb yetanotheruser $servercidr $authmethod clientcert=verify-ca\n"; print $hba "hostssl certdb all $servercidr cert\n"; + print $hba + "hostssl certdb_dn all $servercidr cert clientname=DN map=dn\n", + "hostssl certdb_dn_re all $servercidr cert clientname=DN map=dnre\n", + "hostssl certdb_cn all $servercidr cert clientname=CN map=cn\n"; close $hba; + + # Also set the ident maps. Note: fields with commas must be quoted + open my $map, ">", "$pgdata/pg_ident.conf"; + print $map + "# MAPNAME SYSTEM-USERNAME PG-USERNAME\n", + "dn \"O=PGDG,OU=Testing,CN=ssltestuser-dn\" ssltestuser\n", + "dnre \"/^.*OU=Testing,.*\$\" ssltestuser\n", + "cn ssltestuser-dn ssltestuser\n"; + return; }