Subject: Support for NSS as a libpq TLS backend

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 15 May 2020 22:46:09 +0200

The attached patch implements NSS (Network Security Services) [0] with the
required NSPR runtime [1] as a TLS backend for PostgreSQL.

While all sslmodes are implemented and work for the most part, the patch is
*not* ready yet but I wanted to show progress early so that anyone interested
in this can help out with testing and maybe even hacking.

Why NSS?  Well.  It shares no lineage with OpenSSL making it not just an
alternative by fork but a 100% alternative.  It's also actively maintained, is
readily available on many platforms where PostgreSQL is popular and has a FIPS
mode which doesn't require an EOL'd library.  And finally, I was asked nicely
with the promise of a free beverage, an incentive as good as any.

Differences with OpenSSL
------------------------
NSS does not use certificates and keys on the filesystem, it instead uses a
certificate database in which all certificates, keys and CRL's are loaded.  A
set of tools are provided to work with the database, like: certutil, crlutil,
pk12util etc.  We could support plain PEM files as well, and load them into a
database ourselves but so far I've opted for just using what is already in the
database.

This does mean that new GUCs are needed to identify the database.  I've mostly
repurposed the existing ones for cert/key/crl, but had to invent a new one for
the database.  Maybe there should be an entirely new set?  This needs to be
discussed with not only NSS in mind but for additional as-of-yet unknown
backends we might get (SChannel comes to mind).

NSS also supports partial chain validation per default (as do many other TLS
libraries) where OpenSSL does not.  I haven't done anything about that just
yet, thus there is a failing test as a reminder to address it.

The documentation of NSS/NSPR is unfortunately quite poor and often times
outdated or simply nonexisting.  Cloning the repo and reading the source code
is the only option for parts of the API.

Featurewise there might be other things we can make use of in NSS which doesn't
exist in OpenSSL, but for now I've tried to keep them aligned.

Known Bugs and Limitations (in this version of the patch)
---------------------------------------------------------
The frontend doesn't attempt to verify whether the specified CRL exists in the
database or not.  This can be done with pretty much the same code as in the
backend, except that we don't have the client side certificate loaded so we
either need to read it back from the database, or parse a list of all CRLs
(which would save us from having the cert in local memory which generally is a
good thing to avoid).

pgtls_read is calling PR_Recv which works fine for communicating with an NSS
backend cluster, but hangs waiting for IO when communicating with an OpenSSL
backend cluster.  Using PR_Read reverses the situation.  This is probably a
simple bug but I haven't had time to track it down yet.  The below shifts
between the two for debugging.

-         nread = PR_Recv(conn->pr_fd, ptr, len, 0, PR_INTERVAL_NO_WAIT);
+         nread = PR_Read(conn->pr_fd, ptr, len);

Passphrase handling in the backend is broken, more on that under TODO.

There are a few failing tests and a few skipped ones for now, but the majority
of the tests pass.

Testing
-------
In order for the TAP framework to be able to handle backends with different
characteristics I've broken up SSLServer.pm into a set of modules:

    SSL::Server
    SSL::Backend::NSS
    SSL::Backend::OpenSSL

The SSL tests import SSL::Server which in turn imports the appropriate backend
module in order to perform backend specific setup tasks.  The backend used
should be transparent for the TAP code when it comes to switching server certs
etc.

So far I've used foo|bar in the matching regex to provide alternative output,
and SKIP blocks for tests that don't apply.  There might be neater ways to
achieve this, but I was trying to avoid having separate test files for the
different backends.

The certificate databases can be created with a new nssfiles make target in
src/test/ssl, which use the existing files (and also depend on OpenSSL which I
don't think is a problematic dependency for development environments).  To keep
it simple I've named the certificates in the NSS database after the filenames,
this isn't really NSS best-practices but it makes for an easier time reading
the tests IMO.

If this direction is of interest, extracting into to a separate patch for just
setting up the modules and implementing OpenSSL without a new backend is
probably the next step.

TODO
----
This patch is a work in progress, and there is work left to do, below is a dump
of what is left to fix before this can be considered a full implementation for
review. Most of these items have more documentation in the code comments.

* The split between init and open needs to be revisited, especially in frontend
  where we have a bit more freedom. It remains to be seen if we can do better in
  the backend part.

* Documentation, it's currently not even started

* Windows support.  I've hacked mostly using Debian and have tested versions of
  the patch on macOS, but not Windows so far.

* Figure out how to handle cipher configuration.  Getting a set of ciphers that
  result in a useable socket isn't as easy as with OpenSSL, and policies seem
  much more preferred.  At the very least this needs to be solidly documented.

* The rules in src/test/ssl/Makefile for generating certificate databases can
  probably be generalized into a smaller set of rules based on wildcards.

* The password callback on server-side won't be invoked at server start due to
  init happening in be_tls_open, so something needs to be figured out there.
  Maybe attempt to open the database with a throw-away context in init just to
  invoke the password callback?

* Identify code duplicated between frontend and backend and try to generalize.

* Make sure the handling the error codes correctly in the certificate and auth
  callbacks to properly handle self-signed certs etc.

* Tidy up the tests which are partially hardwired for NSS now to make sure
  there are no regressions for OpenSSL.

* All the code using OpenSSL which isn't the libpq communications parts, like
  pgcrypto, strong_random, sha2, SCRAM et.al

* Review language in code comments and run pgindent et.al

* Settle on a minimum required version.  I've been using NSS 3.42 and NSPR 4.20
  simply since they were the packages Debian wanted to install for me, but I'm
  quite convinced that we can go a bit lower (featurewise we can go much lower
  but there are bugfixes in recent versions that we might want to include).
  Anything lower than a version supporting TLSv1.3 seems like an obvious no-no.

I'd be surprised if this is all, but that's at least a start.  There isn't
really a playbook on how to add a new TLS backend, but I'm hoping to be able to
summarize the required bits and pieces in README.SSL once this is a bit closer
to completion.

My plan is to keep hacking at this to have it reviewable for the 14 cycle, so
if anyone has an interest in NSS, then I would love to hear feedback on how it
works (and doesn't work).

The 0001 patch contains the full NSS support, and 0002 is a fix for the pgstat
abstraction which IMO leaks backend implementation details.  This needs to go
on it's own thread, but since 0001 fails without it I've included it here for
simplicity sake for now.

cheers ./daniel

[0] https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS
[1] https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 25 Jun 2020 17:39:33 +0200

> On 15 May 2020, at 22:46, Daniel Gustafsson <[email-masked]> wrote:

> on it's own thread, but since 0001 fails without it I've included it here for

The attached 0001 and 0002 are the same patchseries as before, but with the
OpenSSL test module fixed and a rebase on top of the current master.

cheers ./daniel

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 3 Jul 2020 13:51:28 +0200

> On 25 Jun 2020, at 17:39, Daniel Gustafsson <[email-masked]> wrote:
> 

Another rebase to resolve conflicts with the recent fixes in the SSL tests, as
well as some minor cleanup.

cheers ./daniel

---

From: Thomas Munro <[email-masked]>
Date: Fri, 10 Jul 2020 17:10:59 +1200

> well as some minor cleanup.

Hi Daniel,

Thanks for blazing the trail for other implementations to coexist in
the tree.  I see that cURL (another project Daniel works on)
supports a lot of TLS implementations[1].  I recognise 4 other library
names from that table as having appeared on this mailing list as
candidates for PostgreSQL support complete with WIP patches, including
another one from you (Apple Secure Transport).  I don't have strong
views on how many and which libraries we should support, but I was
curious how many packages depend on libss1.1, libgnutls30 and libnss3
in the Debian package repos in my sources.list, and I came up with
OpenSSL = 820, GnuTLS = 342, and NSS = 87.

I guess Solution.pm needs at least USE_NSS => undef for this not to
break the build on Windows.

Obviously cfbot is useless for testing this code, since its build
script does --with-openssl and you need --with-nss, but it still shows
us one thing: with your patch, a --with-openssl build is apparently
broken:

/001_ssltests.pl .. 1/93 Bailout called.  Further testing stopped:
system pg_ctl failed

There are some weird configure-related hunks in the patch:

+  -runstatedir | --runstatedir | --runstatedi | --runstated \
...[more stuff like that]...

-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))

I see the same when I use Debian's autoconf, but not FreeBSD's or
MacPorts', despite all being version 2.69.  That seems to be due to
non-upstreamed changes added by the Debian maintainers (I see the
off_t thing mentioned in /usr/share/doc/autoconf/changelog.Debian.gz).
I think you need to build a stock autoconf 2.69 or run autoconf on a
non-Debian system.

I installed libnss3-dev on my Debian box and then configure had
trouble locating and understanding <ssl.h>, until I added
--with-includes=/usr/include/nss:/usr/include/nspr.  I suspect this is
supposed to be done with pkg-config nss --cflags somewhere in
configure (or alternatively nss-config --cflags, nspr-config --cflags,
I don't know, but we're using pkg-config for other stuff).

I installed the Debian package libnss3-tools (for certutil) and then,
in src/test/ssl, I ran make nssfiles (I guess that should be
automatic?), and make check, and I got this far:

Test Summary Report
-------------------
t/001_ssltests.pl (Wstat: 3584 Tests: 93 Failed: 14)
  Failed tests:  14, 16, 18-20, 24, 27-28, 54-55, 78-80
                91
  Non-zero exit status: 14

You mentioned some were failing in this WIP -- are those results you expect?

[1] https://curl.haxx.se/docs/ssl-compared.html

---

From: Daniel Gustafsson <[email-masked]>
Date: Sun, 12 Jul 2020 00:03:22 +0200

> On 10 Jul 2020, at 07:10, Thomas Munro <[email-masked]> wrote:
> 
> supports a lot of TLS implementations[1].

The list on that URL is also just a selection, the total count is 10 (not
counting OpenSSL forks) IIRC, after axing support for a few lately.  OpenSSL
clearly has a large mindshare but the gist of it is that there exist quite a
few alternatives each with their own strengths.

> I recognise 4 other library
> views on how many and which libraries we should support,

I think it's key to keep in mind *why* it's relevant to provide options in the
first place, after all, as they must be 100% interoperable one can easily argue
for a single one being enough.  We need to to look at what they offer users on
top of just a TLS connection, like: managed certificate storage like for
example macOS Keychains, FIPS certification, good platform availability and/or
OS integration etc.  If all a library offers is "not being OpenSSL" then it's
not clear that we're adding much value by spending the cycles to support it.

My personal opinion is that we should keep it pretty limited, not least to
lessen the burden of testing and during feature development.  Supporting a new
library comes with requirements on both the CFBot as well as the buildfarm, not
to mention on developers who dabble in that area of the code.  The goal should
IMHO be to make it trivial for every postgres installation to use TLS
regardless of platform and experience level with the person installing it.

The situation is a bit different for curl where we have as a goal to provide
enough alternatives such that every platform can have a libcurl/curl more or
less regardless of what it contains.  As a consequence, we have around 80 CI
jobs to test each pull request to provide ample coverage.  Being a kitchen-
sink is really hard work.

> but I was

I don't see a lot of excitement over GnuTLS lately, but Debian shipping it due
to (I believe) licensing concerns with OpenSSL does help it along.  In my
experience, platforms with GnuTLS easily available also have OpenSSL easily
available.

> break the build on Windows.

Thanks, I'll fix (I admittedly haven't tried this at all on Windows yet).

> script does --with-openssl and you need --with-nss,

Right, this is a CFBot problem with any patch that require specific autoconf
flags to be excercised.  I wonder if we can make something when we do CF app
integration which can inject flags to a Travis pipeline in a safe manner?

> but it still shows

Humm ..  I hate to say "it worked on my machine" but it did, but my TLS
environment is hardly standard.  Sorry for posting breakage, most likely this
is a bug in the new test module structure that the patch introduce in order to
support multiple backends for src/tests/ssl.  I'll fix.

> I think you need to build a stock autoconf 2.69 or run autoconf on a

Sigh, yes that's a Debianism that slipped through, again sorry about that.

> I don't know, but we're using pkg-config for other stuff).

Yeah, that's a good point, I should fix that.  Having a metric ton of TLS
libraries in various versions around in my environment I've been Stockholm
Syndromed to --with-includes to the point where I didn't even think to run
without it. It should clearly be as easy to use as OpenSSL wrt autoconf.

> automatic?)

Yes, it needs to run automatically for NSS builds on make check.

> , and make check, and I got this far:
> 
> Test Summary Report
> -------------------

I'm not on my dev box at the moment, and I don't remember off the cuff, but
that sounds higher than I remember.  I wonder if I fat-fingered the regexes in
the last version?

Thanks for taking a look at the patch, I'll fix up the reported issues Monday
at the latest.

cheers ./daniel

---

From: Thomas Munro <[email-masked]>
Date: Wed, 15 Jul 2020 21:26:27 +1200

> off_t thing mentioned in /usr/share/doc/autoconf/changelog.Debian.gz).

By the way, Dagfinn mentioned that these changes were in fact
upstreamed, and happened to be beta-released today[1], and are due out
in ~3 months as 2.70.  That'll be something for us to coordinate a bit
further down the road.

[1] https://lists.gnu.org/archive/html/autoconf/2020-07/msg00006.html

---

From: Andrew Dunstan <[email-masked]>
Date: Wed, 15 Jul 2020 14:35:40 -0400

> works (and doesn't work).

I'll be happy to help, particularly with Windows support and with some
of the callback stuff I've had a hand in.

cheers

andrew

-- 
Andrew Dunstan                https://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 16 Jul 2020 00:16:26 +0200

> On 12 Jul 2020, at 00:03, Daniel Gustafsson <[email-masked]> wrote:

> Thanks for taking a look at the patch, I'll fix up the reported issues Monday

A bit of life intervened, but attached is a new version of the patch which
should work for OpenSSL builds, and have the other issues addressed as well.  I
took the opportunity to clean up the NSS tests to be more like the OpenSSL ones
to lessen the impact on the TAP testcases.  On my Debian box, using the
standard NSS and NSPR packages, I get 6 failures which are essentially all
around CRL handling. I'm going to circle back and look at what is missing there.

This version also removes the required patch for statistics reporting as that
has been committed in 6a5c750f3f72899f4f982f921d5bf5665f55651e.

cheers ./daniel

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 16 Jul 2020 00:18:26 +0200

> On 15 Jul 2020, at 20:35, Andrew Dunstan <[email-masked]> wrote:
> 

That would be fantastic, thanks!  The password callback handling is still a
TODO so feel free to take a stab at that since you have a lot of context on
there.

For Windows, I've include USE_NSS in Solution.pm as Thomas pointed out in this
thread, but that was done blind as I've done no testing on Windows yet.

cheers ./daniel

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 20 Jul 2020 15:35:51 +0200

> On 16 Jul 2020, at 00:16, Daniel Gustafsson <[email-masked]> wrote:
> 

Taking a look at this, the issue was that I had fat-fingered the Makefile rules
for generating the NSS databases.  This is admittedly very messy at this point,
partly due to trying to mimick OpenSSL filepaths/names to minimize the impact
on tests and to keep OpenSSL/NSS tests as "optically" equivalent as I could.

With this, I have one failing test ("intermediate client certificate is
provided by client") which I've left failing since I believe the case should be
supported by NSS.  The issue is most likely that I havent figured out the right
certinfo incantation to make it so (Mozilla hasn't strained themselves when
writing documentation for this toolchain, or any part of NSS for that matter).

The failing test when running with OpenSSL also remains, the issue is that the
very first test for incorrect key passphrase fails, even though the server is
behaving exactly as it should.  Something in the test suite hackery breaks for
that test but I've been unable to pin down what it is, any help on would be
greatly appreciated.

This version adds support for sslinfo on NSS for most the functions.  In the
process I realized that sslinfo never got the memo about SSL support being
abstracted behind an API, so I went and did that as well.  This part of the
patch should perhaps be broken out into a separate patch/thread in case it's
deemed interesting regardless of the evetual conclusion on this patch.  Doing
this removed a bit of duplication with the backend code, and some errorhandling
moved to be-secure-openssl.c (originally added in d94c36a45ab45).  As the
original commit message states, they're mostly code hygiene with belts and
suspenders, but if we deemed them valuable enough for a contrib module ISTM
they should go into the backend as well.  Adding a testcase for sslinfo is a
TODO.

Support pg_strong_random, sha2 and pgcrypto has been started, but it's less
trivial as NSS/NSPR requires a lot more initialization and state than OpenSSL,
so it needs a bit more thought.

I've also done a rebase over todays HEAD, a pgindent pass and some cleanup here
and there.

cheers ./daniel

---

From: Andrew Dunstan <[email-masked]>
Date: Fri, 31 Jul 2020 16:44:46 -0400

> thread, but that was done blind as I've done no testing on Windows yet.

OK, here is an update of your patch that compiles and runs against NSS
under Windows (VS2019).

In addition to some work that was missing in src/tools/msvc, I had to
make a few adjustments, including:

  * strtok_r() isn't available on Windows. We don't use it elsewhere in
    the postgres code, and it seemed unnecessary to have reentrant calls
    here, so I just replaced it with equivalent strtok() calls.
  * We were missing an NSS implementation of
    pgtls_verify_peer_name_matches_certificate_guts(). I supplied a
    dummy that's enough to get it building cleanly, but that needs to be
    filled in properly.

There is still plenty of work to go, but this seemed a sufficient
milestone to report progress on.

cheers

andrew

---

From: Andrew Dunstan <[email-masked]>
Date: Mon, 3 Aug 2020 12:46:24 -0400

> milestone to report progress on.

OK, this version contains pre-generated nss files, and passes a full
buildfarm run including the ssl test module, with both openssl and NSS.
That should keep the cfbot happy :-)

cheers

andrew

---

From: Andrew Dunstan <[email-masked]>
Date: Mon, 3 Aug 2020 15:18:47 -0400

> That should keep the cfbot happy :-)

rebased on current master.

cheers

andrew

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 4 Aug 2020 23:42:16 +0200

> On 3 Aug 2020, at 21:18, Andrew Dunstan <[email-masked]> wrote:

>>> OK, here is an update of your patch that compiles and runs against NSS

Out of curiosity since I'm not familiar with Windows, how hard/easy is it to
install NSS for the purpose of a) hacking on postgres+NSS and b) using postgres
with NSS as the backend?

>>>    here, so I just replaced it with equivalent strtok() calls.

Fair enough, that makes sense.

>>>    dummy that's enough to get it building cleanly, but that needs to be

Interesting, not sure how I could've missed that one. 

>> That should keep the cfbot happy :-)

Exciting, thanks a lot for helping out on this!  I've started to look at the
required documentation changes during vacation, will hopefully be able to post
something soon.

cheers ./daniel

---

From: Andrew Dunstan <[email-masked]>
Date: Wed, 5 Aug 2020 16:38:38 -0400

> install NSS for the purpose of a) hacking on postgres+NSS and b) using postgres

I've laid out the process at
https://www.2ndquadrant.com/en/blog/nss-on-windows-for-postgresql-development/

> required documentation changes during vacation, will hopefully be able to post

Good. Having got the tests running cleanly on Linux, I'm now going back
to work on that for Windows.

After that I'll look at the hook/callback stuff.

cheers

andrew

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 1 Sep 2020 14:43:58 +0200

> On 5 Aug 2020, at 22:38, Andrew Dunstan <[email-masked]> wrote:
> 

That's fantastic, thanks for putting that together.

>>>> That should keep the cfbot happy :-)

Turns out the CFBot doesn't like the binary diffs.  They are included in this
version too but we should probably drop them again it seems.

> After that I'll look at the hook/callback stuff.

The attached v9 contains mostly a first stab at getting some documentation
going, it's far from completed but I'd rather share more frequently to not have
local trees deviate too much in case you've had time to hack as well.  I had a
few documentation tweaks in the code too, but no real functionality change for
now.

The 0001 patch isn't strictly necessary but it seems reasonable to address the
various ways OpenSSL was spelled out in the docs while at updating the SSL
portions.  It essentially ensures that markup around OpenSSL and SSL is used
consistently.  I didn't address the linelengths being too long in this patch to
make review easier instead.

cheers ./daniel

---

From: Andrew Dunstan <[email-masked]>
Date: Thu, 3 Sep 2020 15:26:03 -0400

> version too but we should probably drop them again it seems.

I did ask Thomas about this, he was going to try to fix it. In
principle we should want it to accept binary diffs exactly for this
sort of thing.

> make review easier instead.

I'll take a look.

cheers

andrew

---

From: Michael Paquier <[email-masked]>
Date: Fri, 4 Sep 2020 10:23:34 +0900

>> make review easier instead.

Adding a <productname> markup around OpenSSL in the docs makes things
consistent.  +1.
--
Michael

---

From: Michael Paquier <[email-masked]>
Date: Thu, 17 Sep 2020 16:41:34 +0900

> Adding a <productname> markup around OpenSSL in the docs makes things

I have looked at 0001, and applied it after fixing the line length
(thanks for not doing it to ease my lookup), and I found one extra
place in need of fix.  Patch 0002 is failing to apply.
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 17 Sep 2020 11:41:28 +0200

> On 17 Sep 2020, at 09:41, Michael Paquier <[email-masked]> wrote:
> 
> place in need of fix.  

Thanks!

> Patch 0002 is failing to apply.

Attached is a v10 rebased to apply on top of HEAD.

cheers ./daniel

---

From: Michael Paquier <[email-masked]>
Date: Tue, 29 Sep 2020 14:59:39 +0900

> Attached is a v10 rebased to apply on top of HEAD.

I am afraid that this needs a new rebase.  The patch is failing to
apply, per the CF bot. :/
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 29 Sep 2020 09:52:17 +0200

> On 29 Sep 2020, at 07:59, Michael Paquier <[email-masked]> wrote:
> 

It's failing on binary diffs due to the NSS certificate databases being
included to make hacking on the patch easier:

  File src/test/ssl/ssl/nss/server.crl: git binary diffs are not supported.

This is a limitation of the CFBot patch tester, the text portions of the patch
still applies with a tiny but of fuzz.

cheers ./daniel

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 2 Oct 2020 22:01:37 +0200

> On 29 Sep 2020, at 09:52, Daniel Gustafsson <[email-masked]> wrote:
> 

Attached is a new version which doesn't contain the NSS certificate databases
to keep the CFBot happy.

It also implements server-side passphrase callbacks as well as re-enables the
tests for those.  The callback works a bit differently from the OpenSSL one as
it must run in the forked process, so it can't run on server reload.  There's
also no default fallback reading from a TTY like in OpenSSL, so if no callback
it set the always-failing dummy is set.

cheers ./daniel

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 20 Oct 2020 14:24:24 +0200

The attached v12 adds support for pgcrypto as well as pg_strong_random, which I
believe completes the required subsystems where we have OpenSSL support today.
I opted for not adding code to handle the internal shaXXX implementations until
the dust settles around the proposal to change the API there.

Blowfish is not supported by NSS AFAICT, even though the cipher mechanism is
defined, so the internal implementation is used there instead.  CAST5 is
supported, but segfaults inside NSS on most inputs so support for that is not
included for now.

cheers ./daniel

---

From: Andres Freund <[email-masked]>
Date: Tue, 20 Oct 2020 12:15:29 -0700

Hi,

On 2020-10-20 14:24:24 +0200, Daniel Gustafsson wrote:
> From 0cb0e6a0ce9adb18bc9d212bd03e4e09fa452972 Mon Sep 17 00:00:00 2001
> From: Daniel Gustafsson <[email-masked]>
> Date: Thu, 8 Oct 2020 18:44:28 +0200
> Subject: [PATCH] Support for NSS as a TLS backend v12
> ---
>  configure                                     |  223 +++-
>  configure.ac                                  |   39 +-
>  contrib/Makefile                              |    2 +-
>  contrib/pgcrypto/Makefile                     |    5 +
>  contrib/pgcrypto/nss.c                        |  773 +++++++++++
>  contrib/pgcrypto/openssl.c                    |    2 +-
>  contrib/pgcrypto/px.c                         |    1 +
>  contrib/pgcrypto/px.h                         |    1 +

Personally I'd like to see this patch broken up a bit - it's quite
large. Several of the changes could easily be committed separately, no?

>  if test "$with_openssl" = yes ; then
> +  if test x"$with_nss" = x"yes" ; then
> +    AC_MSG_ERROR([multiple SSL backends cannot be enabled simultaneously"])
> +  fi

Based on a quick look there's no similar error check for the msvc
build. Should there be?

>  
> +if test "$with_nss" = yes ; then
> +  if test x"$with_openssl" = x"yes" ; then
> +    AC_MSG_ERROR([multiple SSL backends cannot be enabled simultaneously"])
> +  fi

Isn't this a repetition of the earlier check?

> +  CLEANLDFLAGS="$LDFLAGS"
> +  # TODO: document this set of LDFLAGS
> +  LDFLAGS="-lssl3 -lsmime3 -lnss3 -lplds4 -lplc4 -lnspr4 $LDFLAGS"

Shouldn't this use nss-config or such?

> +if test "$with_nss" = yes ; then
> +  AC_CHECK_HEADER(ssl.h, [], [AC_MSG_ERROR([header file <ssl.h> is required for NSS])])
> +  AC_CHECK_HEADER(nss.h, [], [AC_MSG_ERROR([header file <nss.h> is required for NSS])])
> +fi

Hm. For me, on debian, these headers are not directly in the default
include search path, but would be as nss/ssl.h. I don't see you adding
nss/ to CFLAGS anywhere? How does this work currently?

I think it'd also be better if we could include these files as nss/ssl.h
etc - ssl.h is a name way too likely to conflict imo.

> +++ b/src/backend/libpq/be-secure-nss.c
> @@ -0,0 +1,1158 @@
> +/*
> + * BITS_PER_BYTE is also defined in the NSPR header files, so we need to undef
> + * our version to avoid compiler warnings on redefinition.
> + */
> +#define pg_BITS_PER_BYTE BITS_PER_BYTE
> +#undef BITS_PER_BYTE

Most compilers/preprocessors don't warn about redefinitions when they
would result in the same value (IIRC we have some cases of redefinitions
in tree even). Does nspr's differ?

> +/*
> + * The nspr/obsolete/protypes.h NSPR header typedefs uint64 and int64 with
> + * colliding definitions from ours, causing a much expected compiler error.
> + * The definitions are however not actually used in NSPR at all, and are only
> + * intended for what seems to be backwards compatibility for apps written
> + * against old versions of NSPR.  The following comment is in the referenced
> + * file, and was added in 1998:
> + *
> + *		This section typedefs the old 'native' types to the new PR<type>s.
> + *		These definitions are scheduled to be eliminated at the earliest
> + *		possible time. The NSPR API is implemented and documented using
> + *		the new definitions.
> + *
> + * As there is no opt-out from pulling in these typedefs, we define the guard
> + * for the file to exclude it. This is incredibly ugly, but seems to be about
> + * the only way around it.
> + */
> +#define PROTYPES_H
> +#include <nspr.h>
> +#undef PROTYPES_H

Yuck :(.

> +int
> +be_tls_init(bool isServerStart)
> +{
> +	SECStatus	status;
> +	SSLVersionRange supported_sslver;
> +
> +	/*
> +	 * Set up the connection cache for multi-processing application behavior.

Hm. Do we necessarily want that? Session resumption is not exactly
unproblematic... Or does this do something else?

> +	 * If we are in ServerStart then we initialize the cache. If the server is
> +	 * already started, we inherit the cache such that it can be used for
> +	 * connections. Calling SSL_ConfigMPServerSIDCache sets an environment
> +	 * variable which contains enough information for the forked child to know
> +	 * how to access it.  Passing NULL to SSL_InheritMPServerSIDCache will
> +	 * make the forked child look it up by the default name SSL_INHERITANCE,
> +	 * if env vars aren't inherited then the contents of the variable can be
> +	 * passed instead.
> +	 */

Does this stuff work on windows / EXEC_BACKEND?

> +	 * The below parameters are what the implicit initialization would've done
> +	 * for us, and should work even for older versions where it might not be
> +	 * done automatically. The last parameter, maxPTDs, is set to various
> +	 * values in other codebases, but has been unused since NSPR 2.1 which was
> +	 * released sometime in 1998.
> +	 */
> +	PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0 /* maxPTDs */ );

https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PR_Init
says that currently all parameters are ignored?

> +	/*
> +	 * Import the already opened socket as we don't want to use NSPR functions
> +	 * for opening the network socket due to how the PostgreSQL protocol works
> +	 * with TLS connections. This function is not part of the NSPR public API,
> +	 * see the comment at the top of the file for the rationale of still using
> +	 * it.
> +	 */
> +	pr_fd = PR_ImportTCPSocket(port->sock);
> +	if (!pr_fd)
> +		ereport(ERROR,
> +				(errmsg("unable to connect to socket")));

I don't see the comment you're referring to?

> +	/*
> +	 * Most of the documentation available, and implementations of, NSS/NSPR
> +	 * use the PR_NewTCPSocket() function here, which has the drawback that it
> +	 * can only create IPv4 sockets. Instead use PR_OpenTCPSocket() which
> +	 * copes with IPv6 as well.
> +	 */
> +	model = PR_OpenTCPSocket(port->laddr.addr.ss_family);
> +	if (!model)
> +		ereport(ERROR,
> +				(errmsg("unable to open socket")));
> +
> +	/*
> +	 * Convert the NSPR socket to an SSL socket. Ensuring the success of this
> +	 * operation is critical as NSS SSL_* functions may return SECSuccess on
> +	 * the socket even though SSL hasn't been enabled, which introduce a risk
> +	 * of silent downgrades.
> +	 */
> +	model = SSL_ImportFD(NULL, model);
> +	if (!model)
> +		ereport(ERROR,
> +				(errmsg("unable to enable TLS on socket")));

It's confusing that these functions do not actually reference the socket
via some handle :(. What does opening a socket do here?

> +	/*
> +	 * Configure the allowed cipher. If there are no user preferred suites,

*ciphers?

> +
> +	port->pr_fd = SSL_ImportFD(model, pr_fd);
> +	if (!port->pr_fd)
> +		ereport(ERROR,
> +				(errmsg("unable to initialize")));
> +
> +	PR_Close(model);

A comment explaining why we first import a NULL into the model, and then
release the model, and import the real fd would be good.

> +ssize_t
> +be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
> +{
> +	ssize_t		n_read;
> +	PRErrorCode err;
> +
> +	n_read = PR_Read(port->pr_fd, ptr, len);
> +
> +	if (n_read < 0)
> +	{
> +		err = PR_GetError();

Yay, more thread global state :(.

> +		/* XXX: This logic seems potentially bogus? */
> +		if (err == PR_WOULD_BLOCK_ERROR)
> +			*waitfor = WL_SOCKET_READABLE;
> +		else
> +			*waitfor = WL_SOCKET_WRITEABLE;

Don't we need to handle failed connections somewhere here? secure_read()
won't know about PR_GetError() etc? How would SSL errors be signalled
upwards here?

Also, as you XXX, it's not clear to me that your mapping would always
result in waiting for the right event? A tls write could e.g. very well
require receiving data etc?

> +	/*
> +	 * At least one byte with password content was returned, and NSS requires
> +	 * that we return it allocated in NSS controlled memory. If we fail to
> +	 * allocate then abort without passing back NULL and bubble up the error
> +	 * on the PG side.
> +	 */
> +	password = (char *) PR_Malloc(len + 1);
> +	if (!password)
> +		ereport(ERROR,
> +				(errcode(ERRCODE_OUT_OF_MEMORY),
> +				 errmsg("out of memory")));
>
> +	strlcpy(password, buf, sizeof(password));
> +	explicit_bzero(buf, sizeof(buf));
> +

In case of error you're not bzero'ing out the password!

Separately, I wonder if we should introduce a function for throwing OOM
errors - which then e.g. could print the memory context stats in those
places too...

> +static SECStatus
> +pg_cert_auth_handler(void *arg, PRFileDesc * fd, PRBool checksig, PRBool isServer)
> +{
> +	SECStatus	status;
> +	Port	   *port = (Port *) arg;
> +	CERTCertificate *cert;
> +	char	   *peer_cn;
> +	int			len;
> +
> +	status = SSL_AuthCertificate(CERT_GetDefaultCertDB(), port->pr_fd, checksig, PR_TRUE);
> +	if (status == SECSuccess)
> +	{
> +		cert = SSL_PeerCertificate(port->pr_fd);
> +		len = strlen(cert->subjectName);
> +		peer_cn = MemoryContextAllocZero(TopMemoryContext, len + 1);
> +		if (strncmp(cert->subjectName, "CN=", 3) == 0)
> +			strlcpy(peer_cn, cert->subjectName + strlen("CN="), len + 1);
> +		else
> +			strlcpy(peer_cn, cert->subjectName, len + 1);
> +		CERT_DestroyCertificate(cert);
> +
> +		port->peer_cn = peer_cn;
> +		port->peer_cert_valid = true;

Hm. We either should have something similar to

			/*
			 * Reject embedded NULLs in certificate common name to prevent
			 * attacks like CVE-2009-4034.
			 */
			if (len != strlen(peer_cn))
			{
				ereport(COMMERROR,
						(errcode(ERRCODE_PROTOCOL_VIOLATION),
						 errmsg("SSL certificate's common name contains embedded null")));
				pfree(peer_cn);
				return -1;
			}
here, or a comment explaining why not.

Also, what's up with the CN= bit? Why is that needed here, but not for
openssl?

> +static PRFileDesc *
> +init_iolayer(Port *port, int loglevel)
> +{
> +	const		PRIOMethods *default_methods;
> +	PRFileDesc *layer;
> +
> +	/*
> +	 * Start by initializing our layer with all the default methods so that we
> +	 * can selectively override the ones we want while still ensuring that we
> +	 * have a complete layer specification.
> +	 */
> +	default_methods = PR_GetDefaultIOMethods();
> +	memcpy(&pr_iomethods, default_methods, sizeof(PRIOMethods));
> +
> +	pr_iomethods.recv = pg_ssl_read;
> +	pr_iomethods.send = pg_ssl_write;
> +
> +	/*
> +	 * Each IO layer must be identified by a unique name, where uniqueness is
> +	 * per connection. Each connection in a postgres cluster can generate the
> +	 * identity from the same string as they will create their IO layers on
> +	 * different sockets. Only one layer per socket can have the same name.
> +	 */
> +	pr_id = PR_GetUniqueIdentity("PostgreSQL");

Seems like it might not be a bad idea to append Server or something?

> +
> +	/*
> +	 * Create the actual IO layer as a stub such that it can be pushed onto
> +	 * the layer stack. The step via a stub is required as we define custom
> +	 * callbacks.
> +	 */
> +	layer = PR_CreateIOLayerStub(pr_id, &pr_iomethods);
> +	if (!layer)
> +	{
> +		ereport(loglevel,
> +				(errmsg("unable to create NSS I/O layer")));
> +		return NULL;
> +	}

Why is this accepting a variable log level? The only caller passes ERROR?

> +/*
> + * pg_SSLerrmessage
> + *		Create and return a human readable error message given
> + *		the specified error code
> + *
> + * PR_ErrorToName only converts the enum identifier of the error to string,
> + * but that can be quite useful for debugging (and in case PR_ErrorToString is
> + * unable to render a message then we at least have something).
> + */
> +static char *
> +pg_SSLerrmessage(PRErrorCode errcode)
> +{
> +	char		error[128];
> +	int			ret;
> +
> +	/* TODO: this should perhaps use a StringInfo instead.. */
> +	ret = pg_snprintf(error, sizeof(error), "%s (%s)",
> +					  PR_ErrorToString(errcode, PR_LANGUAGE_I_DEFAULT),
> +					  PR_ErrorToName(errcode));
> +	if (ret)
> +		return pstrdup(error);

> +	return pstrdup(_("unknown TLS error"));
> +}

Why not use psrintf() here?

> +++ b/src/include/common/pg_nss.h
> @@ -0,0 +1,141 @@
> +/*-------------------------------------------------------------------------
> + *
> + * pg_nss.h
> + *	  Support for NSS as a TLS backend
> + *
> + * These definitions are used by both frontend and backend code.
> + *
> + * Copyright (c) 2020, PostgreSQL Global Development Group
> + *
> + * IDENTIFICATION
> + *        src/include/common/pg_nss.h
> + *
> + *-------------------------------------------------------------------------
> + */
> +#ifndef PG_NSS_H
> +#define PG_NSS_H
> +
> +#ifdef USE_NSS
> +
> +#include <sslproto.h>
> +
> +PRUint16	pg_find_cipher(char *name);
> +
> +typedef struct
> +{
> +	const char *name;
> +	PRUint16	number;
> +}			NSSCiphers;
> +
> +#define INVALID_CIPHER	0xFFFF
> +
> +/*
> + * This list is a partial copy of the ciphers in NSS files lib/ssl/sslproto.h
> + * in order to provide a human readable version of the ciphers. It would be
> + * nice to not have to have this, but NSS doesn't provide any API addressing
> + * the ciphers by name. TODO: do we want more of the ciphers, or perhaps less?
> + */
> +static const NSSCiphers NSS_CipherList[] = {
> +
> +	{"TLS_NULL_WITH_NULL_NULL", TLS_NULL_WITH_NULL_NULL},

Hm. Is this whole business of defining array constants in a header just
done to avoid having a .c file that needs to be compiled both in
frontend and backend code?

> +/*
> + * The nspr/obsolete/protypes.h NSPR header typedefs uint64 and int64 with
> + * colliding definitions from ours, causing a much expected compiler error.
> + * The definitions are however not actually used in NSPR at all, and are only
> + * intended for what seems to be backwards compatibility for apps written
> + * against old versions of NSPR.  The following comment is in the referenced
> + * file, and was added in 1998:
> + *
> + *		This section typedefs the old 'native' types to the new PR<type>s.
> + *		These definitions are scheduled to be eliminated at the earliest
> + *		possible time. The NSPR API is implemented and documented using
> + *		the new definitions.
> + *
> + * As there is no opt-out from pulling in these typedefs, we define the guard
> + * for the file to exclude it. This is incredibly ugly, but seems to be about
> + * the only way around it.
> + */

There's a lot of duplicated comments here. Could we move either of the
files to reference the other for longer ones?

> +/*
> + * PR_ImportTCPSocket() is a private API, but very widely used, as it's the
> + * only way to make NSS use an already set up POSIX file descriptor rather
> + * than opening one itself. To quote the NSS documentation:
> + *
> + *		"In theory, code that uses PR_ImportTCPSocket may break when NSPR's
> + *		implementation changes. In practice, this is unlikely to happen because
> + *		NSPR's implementation has been stable for years and because of NSPR's
> + *		strong commitment to backward compatibility."
> + *
> + * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PR_ImportTCPSocket
> + *
> + * The function is declared in <private/pprio.h>, but as it is a header marked
> + * private we declare it here rather than including it.
> + */
> +NSPR_API(PRFileDesc *) PR_ImportTCPSocket(int);

Ugh. This is really the way to do this? How do other applications deal
with this problem?

> +#if defined(WIN32)
> +static const char *ca_trust_name = "nssckbi.dll";
> +#elif defined(__darwin__)
> +static const char *ca_trust_name = "libnssckbi.dylib";
> +#else
> +static const char *ca_trust_name = "libnssckbi.so";
> +#endif

There's really no pre-existing handling for this in nss???

> +	/*
> +	 * The original design of NSS was for a single application to use a single
> +	 * copy of it, initialized with NSS_Initialize() which isn't returning any
> +	 * handle with which to refer to NSS. NSS initialization and shutdown are
> +	 * global for the application, so a shutdown in another NSS enabled
> +	 * library would cause NSS to be stopped for libpq as well.  The fix has
> +	 * been to introduce NSS_InitContext which returns a context handle to
> +	 * pass to NSS_ShutdownContext.  NSS_InitContext was introduced in NSS
> +	 * 3.12, but the use of it is not very well documented.
> +	 * https://bugzilla.redhat.com/show_bug.cgi?id=738456
> +	 *
> +	 * The InitParameters struct passed can be used to override internal
> +	 * values in NSS, but the usage is not documented at all. When using
> +	 * NSS_Init initializations, the values are instead set via PK11_Configure
> +	 * calls so the PK11_Configure documentation can be used to glean some
> +	 * details on these.
> +	 *
> +	 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/PKCS11/Module_Specs

> +
> +	if (!nss_context)
> +	{
> +		char	   *err = pg_SSLerrmessage(PR_GetError());
> +
> +		printfPQExpBuffer(&conn->errorMessage,
> +						  libpq_gettext("unable to %s certificate database: %s"),
> +						  conn->cert_database ? "open" : "create",
> +						  err);
> +		free(err);
> +		return PGRES_POLLING_FAILED;
> +	}
> +
> +	/*
> +	 * Configure cipher policy.
> +	 */
> +	status = NSS_SetDomesticPolicy();

Why is "domestic" the right thing here?

> +
> +	PK11_SetPasswordFunc(PQssl_passwd_cb);

Is it actually OK to do stuff like this when other users of NSS might be
present? That's obviously more likely in the libpq case, compared to the
backend case (where it's also possible, of course). What prevents us
from overriding another user's callback?

> +ssize_t
> +pgtls_read(PGconn *conn, void *ptr, size_t len)
> +{
> +	PRInt32		nread;
> +	PRErrorCode status;
> +	int			read_errno = 0;
> +
> +	nread = PR_Recv(conn->pr_fd, ptr, len, 0, PR_INTERVAL_NO_WAIT);
> +
> +	/*
> +	 * PR_Recv blocks until there is data to read or the timeout expires. Zero
> +	 * is returned for closed connections, while -1 indicates an error within
> +	 * the ongoing connection.
> +	 */
> +	if (nread == 0)
> +	{
> +		read_errno = ECONNRESET;
> +		return -1;
> +	}

It's a bit confusing to talk about blocking when the socket presumably
is in non-blocking mode, and you're also asking to never wait?

> +	if (nread == -1)
> +	{
> +		status = PR_GetError();
> +
> +		switch (status)
> +		{
> +			case PR_WOULD_BLOCK_ERROR:
> +				read_errno = EINTR;
> +				break;

Uh, isn't this going to cause a busy-loop by the caller? EINTR isn't the
same as EAGAIN/EWOULDBLOCK?

> +			case PR_IO_TIMEOUT_ERROR:
> +				break;

What does this mean? We'll return with a 0 errno here, right? When is
this case reachable?

E.g. the comment in fe-misc.c:
				/* pqsecure_read set the error message for us */
for this case doesn't seem to be fulfilled by this.

> +/*
> + *	Verify that the server certificate matches the hostname we connected to.
> + *
> + * The certificate's Common Name and Subject Alternative Names are considered.
> + */
> +int
> +pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn,
> +												int *names_examined,
> +												char **first_name)
> +{
> +	return 1;
> +}

Uh, huh? Certainly doesn't verify anything...

> +/* ------------------------------------------------------------ */
> +/*			PostgreSQL specific TLS support functions			*/
> +/* ------------------------------------------------------------ */
> +
> +/*
> + * TODO: this a 99% copy of the same function in the backend, make these share
> + * a single implementation instead.
> + */
> +static char *
> +pg_SSLerrmessage(PRErrorCode errcode)
> +{
> +	const char *error;
> +
> +	error = PR_ErrorToName(errcode);
> +	if (error)
> +		return strdup(error);
> +
> +	return strdup("unknown TLS error");
> +}

Btw, why does this need to duplicate strings, instead of returning a
const char*?

Greetings,

Andres Freund

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 27 Oct 2020 21:07:01 +0100

> On 20 Oct 2020, at 21:15, Andres Freund <[email-masked]> wrote:
> 
> Hi,

Thanks for your review, much appreciated!

> large. Several of the changes could easily be committed separately, no?

Not sure how much of this makes sense committed separately (unless separately
means in quick succession), but it could certainly be broken up for the sake of
making review easier.  I will take a stab at that, but in a follow-up email as
I would like the split to be a version just doing the split and not also
introducing/fixing things.

> Based on a quick look there's no similar error check for the msvc

Thats a good question.  When embarking on this is seemed quite natural to me
that it should be, but now I'm not so sure.  Maybe there should be a
--with-openssl-preferred like how we handle readline/libedit or just allow
multiple and let the last one win?  Do you have any input on what would make
sense?

The only thing I think makes no sense is to allow multiple ones at the same
time given the current autoconf switches, even if it would just be to pick say
pg_strong_random from one and libpq TLS from another.

> Isn't this a repetition of the earlier check?

It is, and it we want to keep such a check it should be broken out into a
separate step performed before all library specific checks IMO.

> Shouldn't this use nss-config or such?

Indeed it should, where available.  I've added rudimentary support for that
without a fallback as of now.

> nss/ to CFLAGS anywhere? How does this work currently?

I had Stockholm-syndromed myself into passing --with-includes and hadn't really
realized. Sometimes the obvious is too obvious in a 4000+ LOC patch.

> etc - ssl.h is a name way too likely to conflict imo.

I've changed this to be nss/ssl.h and nspr/nspr.h etc, but the include path
will still need the direct path to the headers (from autoconf) since nss.h
includes NSPR headers as #include <nspr.h> and so on.

> in tree even). Does nspr's differ?

GCC 8.3 in my Debian installation throws the below warning:

    In file included from /usr/include/nspr/prtypes.h:26,
                     from /usr/include/nspr/pratom.h:14,
                     from /usr/include/nspr/nspr.h:9,
                     from be-secure-nss.c:45:
    /usr/include/nspr/prcpucfg.h:1143: warning: "BITS_PER_BYTE" redefined
     #define BITS_PER_BYTE  PR_BITS_PER_BYTE

    In file included from ../../../src/include/c.h:55,
                     from ../../../src/include/postgres.h:46,
                     from be-secure-nss.c:16:
    ../../../src/include/pg_config_manual.h:115: note: this is the location of the previous definition
     #define BITS_PER_BYTE  8

PR_BITS_PER_BYTE is defined per platform in pr/include/md/_<platform>.cfg and
is as expected 8. I assume it's that indirection which cause the warning?

>> + * the only way around it.

Thats not an understatement.  Taking another dive into the NSPR code I did
however find a proper way to deal with this.  Defining NO_NSPR_10_SUPPORT stops
NSPR from using the files in obsolete/. So fixed, yay!

> unproblematic... Or does this do something else?

From my reading of the docs, and experience with the code, a server application
must set up a connection cache in order to accept connections.  Not entirely
sure, and the docs aren't terribly clear for non SSLv2/v3 environments (it
seems to only cache for SSLv2/3 and not TLSv+) but it seems like it may have
other uses internally.  I will hunt down some more information on the NSS
mailing list.

> Does this stuff work on windows

According to the documentation it does, and Andrew had this working on Windows
in an earlier version of the patch.  I need to get a proper Windows env for
testing/dev up and running as mine has bitrotted to nothingness.

> / EXEC_BACKEND?

That's a good point, maybe we need to do a SSL_ConfigServerSessionIDCache
rather than the MP version for EXEC_BACKEND? Not sure.

> says that currently all parameters are ignored?

Right, my comment didn't reflect that they're all dead these days, only that
one of them has been unused since RUN DMC topped the charts with "It's like
that". Comment updated.

> I don't see the comment you're referring to?

It's referring to the comment discussing PR_ImportTCPSocket being a private API
call, yet still used by everyone (which is also discussed later in this review).

> via some handle :(. What does opening a socket do here?

This specific call converts the socket from a plain NSPR socket to an SSL/TLS
capable socket which NSS will work with.  This is a required step for
"activating" NSS on the socket.

>> +	 * Configure the allowed cipher. If there are no user preferred suites,

Yes, fixed.

> release the model, and import the real fd would be good.

I've added a small comment to explain how the model is a configuration template
for the actual socket.  This part of NSS/NSPR is a bit overcomplicated for how
we have connections, it's more geared towards having many open sockets in the
same process.

> Yay, more thread global state :(.

Sorry about that.

> require receiving data etc?

Fixed, but there might be more to be done here.

> In case of error you're not bzero'ing out the password!

Fixed.

> errors - which then e.g. could print the memory context stats in those

+1. I'd be happy to review such a patch.

> here, or a comment explaining why not.

We should, but it's proving rather difficult as there is no equivalent API call
to get the string as well as the expected length of it.

> Also, what's up with the CN= bit? Why is that needed here, but not for

OpenSSL returns only the value portion, whereas NSS returns key=value so we
need to skip over the key= part.

> Seems like it might not be a bad idea to append Server or something?

Fixed.

> Why is this accepting a variable log level? The only caller passes ERROR?

Good catch, that's a leftover from a previous version which no longer makes
sense.  loglevel param removed.

> Why not use psrintf() here?

Thats a good question to which I don't have a good answer.  Changed to doing
just that.

> frontend and backend code?

That was the original motivation, but I guess I should just bit the bullet and
make it a .c compiled in both frontend and backend?

> files to reference the other for longer ones?

I took a stab at this in the attached version.  The code is perhaps over-
commented in parts but I tried to encode my understanding of NSS into the
comments where documentation is lacking, since I assume I'm not the only one
who is new to NSS.  There might be a need to pare back to keep it focused in
case this patch goes futher.

> Ugh. This is really the way to do this? How do other applications deal

They either #include <private/pprio.h> or they do it like this (or vendor NSPR
which makes calling private APIs less problematic).  It sure is ugly, but there
is no alternative to using this function.

> There's really no pre-existing handling for this in nss???

NSS_Init does have more or less the above logic (see snippet below), but only
when there is a cert database defined.

    /*
     * The following code is an attempt to automagically find the external root
     * module.
     * Note: Keep the #if-defined chunks in order. HPUX must select before UNIX.
     */

    static const char *dllname =
    #if defined(XP_WIN32) || defined(XP_OS2)
        "nssckbi.dll";
    #elif defined(HPUX) && !defined(__ia64) /* HP-UX PA-RISC */
        "libnssckbi.sl";
    #elif defined(DARWIN)
        "libnssckbi.dylib";
    #elif defined(XP_UNIX) || defined(XP_BEOS)
        "libnssckbi.so"; 
    #else
    #error "Uh! Oh! I don't know about this platform."
    #endif

In the NSS_INIT_NOCERTDB case there is no such handling of the libname provided
by NSS so we need to do that ourselves.

> Why is "domestic" the right thing here?

Historically there are three cipher policies in NSS: Domestic, Export and
France.  These would enable a set of ciphers based on US export restrictions
(domest/export) or French import restrictions.  All ciphers would start
disabled and then the ciphers belonging to the chosen set would be enabled.
Long ago, that was however removed and they now all get enabled by calling
either of these three functions.  NSS_SetDomesticPolicy enables all implemented
ciphers, and the other calls just call NSS_SetDomesticPolicy, I guess that API
was kept for backwards compatibility.  The below bugzilla entry has a bit more
information on this:

   https://bugzilla.mozilla.org/show_bug.cgi?id=848384

That being said, the comment in the code did not reflect that, so I've reworded
it hoping it will be clearer now.

> from overriding another user's callback?

The password callback pointer is stored in a static variable in NSS (in the
file lib/pk11wrap/pk11auth.c).

> is in non-blocking mode, and you're also asking to never wait?

Fair enough, I can agree that the wording isn't spot on. The socket is
non-blocking while PR_Recv can block (which is what we ask it not to).  I've
reworded and moved the comment around to hopefully make it clearer.

> same as EAGAIN/EWOULDBLOCK?

Right, that's clearly not right.

> What does this mean? We'll return with a 0 errno here, right? When is

It should, AFAICT, only be reachable when PR_Recv is used with a timeout which
we don't do.  It mentioned somewhere that it had happened in no-wait calls due
to a bug, but I fail to find that reference now.  Either way, I've removed it
to fall into the default error handling which now sets errno correctly as that
was a paddle short here.

> for this case doesn't seem to be fulfilled by this.

Fixed, I hope.

> Uh, huh? Certainly doesn't verify anything...

Doh, the verification was done as part of the cert validation callback and I
had missed moving it to the stub.  Fixed and also expanded to closer match how
it's done in the OpenSSL implementation.

> Btw, why does this need to duplicate strings, instead of returning a

No, it doesn't, and no longer does.

The attached includes fixes for the above mentioned issues (and a few small
other ones I stumbled across), hopefully without introducing too many new.  As
mentioned, I'll perform the split into multiple patches in a separate version
which only performs a split to make it easier to diff the individual patchfile
versions.

cheers ./daniel

---

From: Heikki Linnakangas <[email-masked]>
Date: Tue, 27 Oct 2020 22:18:29 +0200

On 27/10/2020 22:07, Daniel Gustafsson wrote:
> /*
>  * Track whether the NSS database has a password set or not. There is no API
>  * function for retrieving password status, so we simply flip this to true in
>  * case NSS invoked the password callback - as that will only happen in case
>  * there is a password. The reason for tracking this is that there are calls
>  * which require a password parameter, but doesn't use the callbacks provided,
>  * so we must call the callback on behalf of these.
>  */
> static bool has_password = false;

This is set in PQssl_passwd_cb function, but never reset. That seems 
wrong. The NSS database used in one connection might have a password, 
while another one might not. Or have I completely misunderstood this?

- Heikki

---

From: Andres Freund <[email-masked]>
Date: Tue, 27 Oct 2020 23:39:57 -0700

Hi,

On 2020-10-27 21:07:01 +0100, Daniel Gustafsson wrote:
> making review easier.

Committing e.g. the pgcrypto pieces separately from the backend code
seems unproblematic. But yes, I would expect them to go in close to each
other. I'm mainly concerned with smaller review-able units.

Have you done testing to ensure that NSS PG cooperates correctly with
openssl PG? Is there a way we can make that easier to do? E.g. allowing
to build frontend with NSS and backend with openssl and vice versa?

> pg_strong_random from one and libpq TLS from another.

Maybe we should just have --with-ssl={openssl,nss}? That'd avoid needing
to check for errors.

Even better, of course, would be to allow switching of the SSL backend
based on config options (PGC_POSTMASTER GUC for backend, connection
string for frontend). Mainly because that would make testing of
interoperability so much easier.  Obviously still a few places like
pgcrypto, randomness, etc, where only a compile time decision seems to
make sense.

> without a fallback as of now.

When would we need a fallback?

> includes NSPR headers as #include <nspr.h> and so on.

Hm. Then it's probably not worth going there...

> to get the string as well as the expected length of it.

Hm. Should at least have a test to ensure that's not a problem then. I
hope/assume NSS rejects this somewhere internally...

> need to skip over the key= part.

Why is it a conditional path though?

> is no alternative to using this function.

Hm - in debian unstable's NSS this function appears to be in nss/ssl.h,
not pprio.h:

/*
** Imports fd into SSL, returning a new socket.  Copies SSL configuration
** from model.
*/
SSL_IMPORT PRFileDesc *SSL_ImportFD(PRFileDesc *model, PRFileDesc *fd);

and ssl.h starts with:
/*
 * This file contains prototypes for the public SSL functions.

> file lib/pk11wrap/pk11auth.c).

But, uh, how is that not a problem? What happens if a backend imports
libpq? What if plpython imports curl which then also uses nss?

> +	/*
> +	 * Finally we must configure the socket for being a server by setting the
> +	 * certificate and key.
> +	 */
> +	status = SSL_ConfigSecureServer(model, server_cert, private_key, kt_rsa);
> +	if (status != SECSuccess)
> +		ereport(ERROR,
> +				(errmsg("unable to configure secure server: %s",
> +						pg_SSLerrmessage(PR_GetError()))));
> +	status = SSL_ConfigServerCert(model, server_cert, private_key, NULL, 0);
> +	if (status != SECSuccess)
> +		ereport(ERROR,
> +				(errmsg("unable to configure server for TLS server connections: %s",
> +						pg_SSLerrmessage(PR_GetError()))));

Why do both of these need to get called? The NSS docs say:

/*
** Deprecated variant of SSL_ConfigServerCert.
**
...
SSL_IMPORT SECStatus SSL_ConfigSecureServer(
    PRFileDesc *fd, CERTCertificate *cert,
    SECKEYPrivateKey *key, SSLKEAType kea);

Greetings,

Andres Freund

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:56:26 +0100

> other. I'm mainly concerned with smaller review-able units.

Attached is a v14 where the logical units are separated into individual
commits.  I hope this split makes it easier to read.

The 0006 commit were things not really related to NSS at all that can be
submitted to -hackers independently of this work, but they're still there since
this version wasn't supposed to change anything.

Most of the changes to sslinfo in 0005 are really only needed in case OpenSSL
isn't the only TLS library, but I would argue that they should be considered
regardless.  There we are still accessing the ->ssl member directly and passing
it to OpenSSL rather than using the be_tls_* API that we have.  I can extract
that portion as a separate patch submission unless there are objections.

cheers ./daniel

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 29 Oct 2020 16:20:19 +0100

> On 28 Oct 2020, at 07:39, Andres Freund <[email-masked]> wrote:

> to build frontend with NSS and backend with openssl and vice versa?

When I wrote the Secure Transport patch I had a patch against PostgresNode
which allowed for overriding the server binaries like so:

   SSLTEST_SERVER_BIN=/path/bin/ make -C src/test/ssl/ check

I've used that coupled with manual testing so far to make sure that an openssl
client can talk to an NSS backend and so on.  Before any other backend is added
we clearly need *a* way of doing this, one which no doubt will need to be
improved upon to suit more workflows.

This is sort of the same situation as pg_upgrade, where two trees is needed to
really test it.

I can clean that patch up and post as a starting point for discussions.

> Maybe we should just have --with-ssl={openssl,nss}? That'd avoid needing

Thats another option, with --with-openssl being an alias for --with-ssl=openssl.

After another round of thinking I like this even better as it makes the build
infra cleaner, so the attached patch has this implemented.

> pgcrypto, randomness, etc, where only a compile time decision seems to

It would make testing easier, but the expense seems potentially rather high.
How would a GUC switch be allowed to operate, would we have mixed backends or
would be require all openssl connectins to be dropped before serving nss ones?

> When would we need a fallback?

One one of my boxes I have NSS/NSPR installed via homebrew and they don't ship
an nss-config AFAICT. I wouldn't be surprised if there are other cases.

> Hm. Then it's probably not worth going there...

It does however make visual parsing of the source files easer since it's clear
which ssl.h is being referred to.  I'm in favor of keeping it.

> hope/assume NSS rejects this somewhere internally...

Agreed, I'll try to hack up a testcase.

> Why is it a conditional path though?

It was mostly just a belts-and-suspenders thing, I don't have any hard evidence
that it's been a thing in any modern NSS version so it can be removed.

> * This file contains prototypes for the public SSL functions.

Right, but that's Import*FD*, not Import*TCPSocket*.  We use ImportFD as well
since it's the API for importing an NSPR socket into NSS and enabling SSL/TLS
on it.  Thats been a public API for a long time.  ImportTCPSocket is used to
import an already opened socket into NSPR, else NSPR must open the socket
itself.  That part has been kept private for reasons unknown, as it's
incredibly useful.

> libpq? What if plpython imports curl which then also uses nss?

Sorry, that sentence wasn't really finished.  What I meant to write was that I
don't really have good answers here.  The available implementation is via the
static var, and there are no alternative APIs.  I've tried googling for
insights but haven't come across any.

The only datapoint I have is that I can't recall there ever being a complaint
against libcurl doing this exact thing.  That of course doesn't mean it cannot
happen or cause problems.

>    PRFileDesc *fd, CERTCertificate *ce	rt,

They don't, I had missed the deprecation warning as it's not mentioned at all
in the online documentation:

https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/SSL_functions/sslfnc.html

(SSL_ConfigServerCert isn't at all mentioned there which dates it to before
this went it obsoleting SSL_ConfigSecureServer.)

Fixed by removing the superfluous call.

Thanks again for reviewing!

cheers ./daniel

---

From: Andrew Dunstan <[email-masked]>
Date: Sun, 1 Nov 2020 08:13:38 -0500

> Fixed by removing the superfluous call.

I've been looking through the new patch set, in particular the testing
setup.

The way it seems to proceed is to use the existing openssl generated
certificates and imports them into NSS certificate databases. That seems
fine to bootstrap testing, but it seems to me it would be more sound not
to rely on openssl at all. I'd rather see the Makefile containing
commands to create these from scratch, which mirror the openssl
variants. IOW you should be able to build and test this from scratch,
including certificate generation, without having openssl installed at all.

I also notice that the invocations to pk12util don't contain the "sql:"
prefix to the -d option, even though the database was created with that
prefix a few lines above. That seems like a mistake from my reading of
the pk12util man page.

cheers

andrew

---

From: Daniel Gustafsson <[email-masked]>
Date: Sun, 1 Nov 2020 23:04:18 +0100

> On 1 Nov 2020, at 14:13, Andrew Dunstan <[email-masked]> wrote:

Thanks!

> fine to bootstrap testing,

That's pretty much why I opted for using the existing certs: to bootstrap the
patch and ensure OpenSSL-backend compatibility.

> but it seems to me it would be more sound not

I don't disagree with this, but I do also believe there is value in testing all
TLS backends with exactly the same certificates to act as a baseline.  The
nssfiles target should definitely be able to generate from scratch, but maybe a
combination is the best option?

Being well versed in the buildfarm code, do you have an off-the-cuff idea on
how to do cross library testing such that OpenSSL/NSS compatibility can be
ensured?  Andres was floating the idea of making a single sourcetree be able to
have both for testing but more discussion is needed to settle on a way forward.

> prefix a few lines above. That seems like a mistake from my reading of

Fixed in the attached v16, which also drops the parts of the patchset which
have been submitted separately to -hackers (the sslinfo patch hunks are still
there are they are required).

cheers ./daniel

---

From: Andrew Dunstan <[email-masked]>
Date: Mon, 2 Nov 2020 09:17:00 -0500

> combination is the best option?

Yeah. I certainly think we need something that should how we would
generate them from scratch using nss. That said, the importation code is
also useful.

>
> Being well versed in the buildfarm code, do you have an off-the-cuff idea onIU

Well, I'd probably try to leverage the knowledge we have in doing
cross-version upgrade testing. It works like this: After the
install-check-C stage each branch saves its binaries and data files in a
special location, adjusting things like library locations to match. then
to test that version it uses that against all the older versions
similarly saved.

We could generalize that saving mechanism and do it if any module
required it. But instead of testing against a different branch, we'd
test against a different animal. So we'd have two animals, one building
with openssl and one with nss, and they would test against each other
(i.e. one as the client and one as the sever, and vice versa).

This would involve a deal of work on my part, but it's very doable, I
believe.

We'd need a way to run tests where we could specify the client and
server binary locations.

Anyway, those are my thoughts. Comments welcome.

cheers

andrew

-- 
Andrew Dunstan
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 4 Nov 2020 14:09:52 +0100

> On 27 Oct 2020, at 21:18, Heikki Linnakangas <[email-masked]> wrote:
> 
> This is set in PQssl_passwd_cb function, but never reset. That seems wrong. The NSS database used in one connection might have a password, while another one might not. Or have I completely misunderstood this?

(sorry for slow response).  You are absolutely right, the has_password flag
must be tracked per connection in PGconn.  The attached v17 implements this as
well a frontend bugfix which caused dropped connections and some smaller fixups
to make strings more translateable.

I've also included a WIP version of SCRAM channel binding in the attached
patch, it's currently failing to connect but someone here might spot the bug
before I do so I figured it's better to include it.

The 0005 patch is now, thanks to the sslinfo patch going in on master, only
containing NSS specific code. 

cheers ./daniel

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 4 Nov 2020 14:14:12 +0100

> On 2 Nov 2020, at 15:17, Andrew Dunstan <[email-masked]> wrote:

> (i.e. one as the client and one as the sever, and vice versa).

That seems like a very good plan.  It would also allow us to test a backend
compiled with OpenSSL 1.0.2 against a frontend with OpenSSL 1.1.1 which might
come in handy when OpenSSL 3.0.0 lands.

> This would involve a deal of work on my part, but it's very doable, I

I have no experience with the buildfarm code, but I'm happy to help if theres
anything I can do.

cheers ./daniel

---

From: Jacob Champion <[email-masked]>
Date: Fri, 6 Nov 2020 20:37:48 +0000

> to make strings more translateable.

Some initial notes from building and testing on macOS Mojave. I'm working with
both a brew-packaged NSS/NSPR (which includes basic nss-/nspr-config) and a
hand-built NSS/NSPR (which does not).

1. In configure.ac:

> +  LDFLAGS="$LDFLAGS $NSS_LIBS $NSPR_LIBS"
> +  CFLAGS="$CFLAGS $NSS_CFLAGS $NSPR_CFLAGS"
> +
> +  AC_CHECK_LIB(nss3, SSL_VersionRangeSet, [], [AC_MSG_ERROR([library 'nss3' is required for NSS])])

Looks like SSL_VersionRangeSet is part of libssl3, not libnss3. So this fails
with the hand-built stack, where there is no nss-config to populate LDFLAGS. I
changed the function to NSS_InitContext and that seems to work nicely.

2. Among the things to eventually think about when it comes to configuring, it
looks like some platforms [1] install the headers under <nspr4/...> and
<nss3/...> instead of <nspr/...> and <nss/...>. It's unfortunate that the NSS
maintainers never chose an official installation layout.

3. I need two more `#define NO_NSPR_10_SUPPORT` guards added in both

  src/include/common/pg_nss.h
  src/port/pg_strong_random.c

before the tree will compile for me. Both of those files include NSS headers.

4. be_tls_init() refuses to run correctly for me; I end up getting an NSPR
assertion that looks like

  sslMutex_Init not implemented for multi-process applications !

With assertions disabled, this ends up showing a somewhat unhelpful

  FATAL:  unable to set up TLS connection cache: security library failure. (SEC_ERROR_LIBRARY_FAILURE)

It looks like cross-process locking isn't actually enabled on macOS, which is a
long-standing bug in NSPR [2, 3]. So calls to SSL_ConfigMPServerSIDCache()
error out.

--Jacob

[1] https://github.com/erthink/ReOpenLDAP/issues/112
[2] https://bugzilla.mozilla.org/show_bug.cgi?id=538680
[3] https://bugzilla.mozilla.org/show_bug.cgi?id=1192500

---

From: Daniel Gustafsson <[email-masked]>
Date: Sat, 7 Nov 2020 00:11:15 +0100

> On 6 Nov 2020, at 21:37, Jacob Champion <[email-masked]> wrote:

> hand-built NSS/NSPR (which does not).

Thanks for looking!

> changed the function to NSS_InitContext and that seems to work nicely.

Ah yes, fixed.

> maintainers never chose an official installation layout.

Yeah, maybe we need to start with the most common path and have fallbacks in
case not found?

> before the tree will compile for me. Both of those files include NSS headers.

Odd that I was able to compile on Linux, but I've added these.

> long-standing bug in NSPR [2, 3]. So calls to SSL_ConfigMPServerSIDCache()

Thats unfortunate since the session cache is required for a server application
backed by NSS.  The attached switches to SSL_ConfigServerSessionIDCacheWithOpt
with which one can explicitly make the cache non-shared, which in turn backs
the mutexes with NSPR locks rather than the missing sem_init.  Can you test
this version and see if that makes it work?

This version also contains a channel binding bug that Heikki pointed out off-
list (sadly not The bug) and a few very minor cleanups as well as a rebase to
handle the new pg_strong_random_init.  Actually performing the context init
there is yet a TODO, but I wanted a version out that at all compiled.

cheers ./daniel

---

From: Jacob Champion <[email-masked]>
Date: Tue, 10 Nov 2020 20:11:19 +0000

On Nov 6, 2020, at 3:11 PM, Daniel Gustafsson <[email-masked]> wrote:
> 
> The attached switches to SSL_ConfigServerSessionIDCacheWithOpt

Yep, I get much farther through the tests with that patch. I'm currently
diving into another assertion failure during socket disconnection:

    Assertion failure: fd->secret == NULL, at prlayer.c:45

cURL has some ominously vague references to this [1], though I'm not
sure that we should work around it in the same way without knowing what
the cause is...

--Jacob

[1] https://github.com/curl/curl/blob/4d2f800/lib/vtls/nss.c#L1266

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 10 Nov 2020 23:28:14 +0100

> On 10 Nov 2020, at 21:11, Jacob Champion <[email-masked]> wrote:

> Yep, I get much farther through the tests with that patch.

Great, thanks for confirming.

> I'm currently

Digging through the archives from when this landed in curl, the assertion
failure was never fully identified back then but happened spuriously.  Which
version of NSPR is this happening with?

cheers ./daniel

---

From: Jacob Champion <[email-masked]>
Date: Wed, 11 Nov 2020 18:17:03 +0000

> version of NSPR is this happening with?

This is NSPR 4.29, with debugging enabled. The fd that causes the
assertion is the custom layer that's added during be_tls_open_server(),
which connects a Port as the layer secret. It looks like NSPR is trying
to help surface potential memory leaks by asserting if the secret is
non-NULL at the time the stack is being closed.

In this case, it doesn't matter since the Port lifetime is managed
elsewhere, but it looks easy enough to add a custom close in the way
that cURL and the NSPR test programs [1] do. Sample patch attached,
which gets me to the end of the tests without any assertions. (Two
failures left on my machine.)

--Jacob

[1] https://hg.mozilla.org/projects/nspr/file/bf6620c143/pr/tests/nblayer.c#l354

---

From: Jacob Champion <[email-masked]>
Date: Wed, 11 Nov 2020 18:57:02 +0000

On Nov 11, 2020, at 10:17 AM, Jacob Champion <[email-masked]> wrote:
> 
> (Two failures left on my machine.)

False alarm -- the stderr debugging I'd added in to track down the
assertion tripped up the "no stderr" tests. Zero failing tests now.

--Jacob

---

From: Jacob Champion <[email-masked]>
Date: Thu, 12 Nov 2020 22:12:42 +0000

> assertion tripped up the "no stderr" tests. Zero failing tests now.

I took a look at the OpenSSL interop problems you mentioned upthread. I
don't see a hang like you did, but I do see a PR_IO_TIMEOUT_ERROR during
connection.

I think pgtls_read() needs to treat PR_IO_TIMEOUT_ERROR as if no bytes
were read, in order to satisfy its API. There was some discussion on
this upthread:

> to fall into the default error handling which now sets errno correctly as that

PR_IO_TIMEOUT_ERROR is definitely returned in no-wait calls on my
machine. It doesn't look like the PR_Recv() API has a choice -- if
there's no data, it can't return a positive integer, and returning zero
means that the socket has been disconnected. So -1 with a timeout error
is the only option.

I'm not completely sure why this is exposed so easily with an OpenSSL
server -- I'm guessing the implementation slices up its packets
differently on the wire, causing a read event before NSS is able to
decrypt a full record -- but it's worth noting that this case also shows
up during NSS-to-NSS psql connections, when handling notifications at
the end of every query. PQconsumeInput() reports a hard failure with the
current implementation, but its return value is ignored by
PrintNotifications(). Otherwise this probably would have showed up
earlier.

(What's the best way to test this case? Are there lower-level tests for
the protocol/network layer somewhere that I'm missing?) 

While patching this case, I also noticed that pgtls_read() doesn't call
SOCK_ERRNO_SET() for the disconnection case. That is also in the
attached patch.

--Jacob

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 13 Nov 2020 13:14:58 +0100

> On 12 Nov 2020, at 23:12, Jacob Champion <[email-masked]> wrote:
> 
> I took a look at the OpenSSL interop problems you mentioned upthread.

Great, thanks!

> I don't see a hang like you did, but I do see a PR_IO_TIMEOUT_ERROR during
> connection.
> 

Right, that makes sense.

> PrintNotifications(). Otherwise this probably would have showed up

Should there perhaps be an Assert there to catch those?

> the protocol/network layer somewhere that I'm missing?)

Not AFAIK.  Having been knee-deep now, do you have any ideas on how to
implement?

> SOCK_ERRNO_SET() for the disconnection case. That is also in the

Ah yes, nice catch.

I've incorporated this patch as well as the previous patch for the assertion
failure on private callback data into the attached v19 patchset.  I also did a
spellcheck and pgindent run on it for ease of review.

cheers ./daniel

---

From: Jacob Champion <[email-masked]>
Date: Mon, 16 Nov 2020 20:00:47 +0000

> Should there perhaps be an Assert there to catch those?

Hm. From the perspective of helping developers out, perhaps, but from
the standpoint of "don't crash when an endpoint outside our control does
something strange", I think that's a harder sell. Should the error be
bubbled all the way up instead? Or perhaps, if psql isn't supposed to
treat notification errors as "hard" failures, it should at least warn
the user that something is fishy?

> Not AFAIK.  Having been knee-deep now, do you have any ideas on how to

I think that testing these sorts of important edge cases needs a
friendly DSL -- something that doesn't want to make devs tear their hair
out while building tests. I've been playing a little bit with Scapy [1]
to understand more of the libpq v3 protocol; I'll see if that can be
adapted for pieces of the TLS handshake in a way that's easy to
maintain. If it can be, maybe that'd be a good starting example.

> spellcheck and pgindent run on it for ease of review.

Commit 6be725e70 got rid of some psql error messaging that the tests
were keying off of, so there are a few new failures after a rebase onto
latest master.

I've attached a patch that gets the SCRAM tests a little further
(certificate hashing was caught in an infinite loop). I also added error
checks to those loops, along the lines of the existing OpenSSL
implementation: if a suitable digest can't be found, the user will see
an error like

    psql: error: could not find digest for OID 'PKCS #1 SHA-256 With RSA Encryption'

It's a little verbose but I don't think this case should come up in
normal practice.

--Jacob

[1] https://scapy.net/

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 17 Nov 2020 16:00:53 +0100

> On 16 Nov 2020, at 21:00, Jacob Champion <[email-masked]> wrote:

> It's a little verbose but I don't think this case should come up in

Nice, thanks for the fix!  I've incorporated your patch into the attached v20
which also fixes client side error reporting to be more readable.  The SCRAM
tests are now also hooked up, albeit with SKIP blocks for NSS, so they can
start getting fixed.

cheers ./daniel

---

From: Jacob Champion <[email-masked]>
Date: Fri, 4 Dec 2020 00:57:26 +0000

On Nov 17, 2020, at 7:00 AM, Daniel Gustafsson <[email-masked]> wrote:
> which also fixes client side error reporting to be more readable.

I was testing handshake failure modes and noticed that some FATAL
messages are being sent through to the client in cleartext. The OpenSSL
implementation doesn't do this, because it logs handshake problems at
COMMERROR level. Should we switch all those ereport() calls in the NSS
be_tls_open_server() to COMMERROR as well (and return explicitly), to
avoid this? Or was there a reason for logging at FATAL/ERROR level?

Related note, at the end of be_tls_open_server():

>     port->ssl_in_use = true;
>     return 0;
> error:
>     return 1;

This needs to return -1 in the error case; the only caller of
secure_open_server() does a direct `result == -1` comparison rather than
checking `result != 0`.

--Jacob

---

From: Jacob Champion <[email-masked]>
Date: Wed, 13 Jan 2021 17:07:53 +0000

> to get the string as well as the expected length of it.

I'm going to try to tackle this part next. It looks like NSS uses RFC
4514 (or something like it) backslash-quoting, which this code either
needs to undo or bypass before performing a comparison.

--Jacob

---

From: Michael Paquier <[email-masked]>
Date: Mon, 18 Jan 2021 16:08:44 +0900

> tests are now also hooked up, albeit with SKIP blocks for NSS, so they can

On top of the set of TODO items mentioned in the logs of the patches,
this patch set needs a rebase because it does not apply.  In order to
move on with this set, I would suggest to extract some parts of the
patch set independently of the others and have two buildfarm members
for the MSVC and non-MSVC cases to stress the parts that can be
committed.  Just seeing the size, we could move on with:
- The ./configure set, with the change to introduce --with-ssl=openssl. 
- 0004 for strong randoms.
- Support for cryptohashes.

+/*
+ * BITS_PER_BYTE is also defined in the NSPR header files, so we need to undef
+ * our version to avoid compiler warnings on redefinition.
+ */
+#define pg_BITS_PER_BYTE BITS_PER_BYTE
+#undef BITS_PER_BYTE
This could be done separately.

src/sgml/libpq.sgml needs to document PQdefaultSSLKeyPassHook_nss, no?
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 19 Jan 2021 21:21:41 +0100

> On 18 Jan 2021, at 08:08, Michael Paquier <[email-masked]> wrote:
> 
> this patch set needs a rebase because it does not apply.

Fixed in the attached, which also addresses the points raised earlier by Jacob
as well as adds certificates created entirely by NSS tooling as well as initial
cryptohash support.  There is something iffy with these certs (the test fails
on mismatching ciphers and/or signature algorithms) that I haven't been able to
pin down, but to get more eyes on this I'm posting the patch with the test
enabled.  The NSS toolchain requires interactive input which makes the Makefile
a bit hacky, ideas on cleaning that up are appreciated.

> In order to

I will leave it to others to decide the feasibility of this, I'm happy to slice
and dice the commits into smaller bits to for example separate out the
--with-ssl autoconf change into a non NSS dependent commit, if that's wanted.

> This could be done separately.

Based on an offlist discussion I believe this was a misunderstanding, but if I
instead misunderstood that feel free to correct me with how you think this
should be done.

> src/sgml/libpq.sgml needs to document PQdefaultSSLKeyPassHook_nss, no?

Good point, fixed.

cheers ./daniel

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 19 Jan 2021 21:23:50 +0100

> On 4 Dec 2020, at 01:57, Jacob Champion <[email-masked]> wrote:
> 

The ERROR logging made early development easier but then stuck around, I've
changed them to COMMERROR returning an error instead in the v21 patch just
sent to the list.

Fixed.

cheers ./daniel

---

From: Jacob Champion <[email-masked]>
Date: Wed, 20 Jan 2021 00:40:07 +0000

On Tue, 2021-01-19 at 21:21 +0100, Daniel Gustafsson wrote:
> There is something iffy with these certs (the test fails
> enabled.

Removing `--keyUsage keyEncipherment` from the native_server-* CSR
generation seems to let the tests pass for me, but I'm wary of just
pushing that as a solution because I don't understand why that would
have anything to do with the failure mode
(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM).

> The NSS toolchain requires interactive input which makes the Makefile

Hm. I got nothing, short of a feature request to NSS...

--Jacob

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 20 Jan 2021 12:58:13 +0100

> On 20 Jan 2021, at 01:40, Jacob Champion <[email-masked]> wrote:
> 

Aha, that was a good clue, I had overlooked the required extensions in the CSR.
Re-reading RFC 5280 it seems we need keyEncipherment, dataEncipherment and
digitalSignature to create a valid SSL Server certificate.  Adding those indeed
make the test pass.  Skimming the certutil code *I think* removing it as you
did cause a set of defaults to kick in that made it work based on the parameter
"--nsCertType sslServer", but it's not entirely easy to make out.  Either way,
relying on defaults in a test suite seems less than good, so I've extended the
Makefile to be explicit about the extensions.

The attached v22 rebase incorporates the fixup to the test Makefile, with not
further changes on top of that.

cheers ./daniel

---

From: Jacob Champion <[email-masked]>
Date: Wed, 20 Jan 2021 17:07:08 +0000

On Wed, 2021-01-20 at 12:58 +0100, Daniel Gustafsson wrote:
> "--nsCertType sslServer", but it's not entirely easy to make out.

Lovely. I didn't expect *removing* an extension to effectively *add*
more, but I'm glad it works now.

==

To continue the Subject Common Name discussion [1] from a different
part of the thread:

Attached is a v23 version of the patchset that peels the raw Common
Name out from a client cert's Subject. This allows the following cases
that the OpenSSL implementation currently handles:

- subjects that don't begin with a CN
- subjects with quotable characters
- subjects that have no CN at all
Embedded NULLs are now handled in a similar manner to the OpenSSL side,
though because this failure happens during the certificate
authentication callback, it results in a TLS alert rather than simply
closing the connection.

For easier review of just the parts I've changed, I've also attached a
since-v22.diff, which is part of the 0001 patch.

--Jacob

[1] 
https://www.postgresql.org/message-id/7d6a23a7e30540b486abc823f7ced7a93e1da1e8.camel%40vmware.com
commit cf6a3e49488b9e795e28713f81f6a4d32702de5d
Author: Jacob Champion <[email-masked]>
Date:   Tue Jan 19 10:32:27 2021 -0800

    NSS: handle client cert Common Names like be-secure-openssl
    
    Store an unquoted Common Name into port->peer_cn. This is the bulk of
    the patch, because CERT_GetCommonName() always performs RFC 4514
    quoting, and the authentication code in the core expects raw data for
    direct string comparison.
    
    These changes allow us to handle
    - usernames with quotable characters, such as backslashes
    - certificates with other name attributes besides Common Name (country
      code, organizational unit, etc.)
    - certificates without a Common Name
    
    Certificates with embedded NULL bytes in the Common Name will be
    rejected in the same manner as the OpenSSL implementation.

diff --git a/src/backend/libpq/be-secure-nss.c b/src/backend/libpq/be-secure-nss.c
index 111b46dea8..80d7598662 100644
--- a/src/backend/libpq/be-secure-nss.c
+++ b/src/backend/libpq/be-secure-nss.c
@@ -1051,6 +1051,69 @@ pg_bad_cert_handler(void *arg, PRFileDesc * fd)
 	return SECFailure;
 }
 
+/*
+ * Returns the Subject Common Name for the given certificate as a raw char
+ * buffer (that is, without any form of escaping for unprintable characters or
+ * embedded nulls), with the length of the buffer returned in the len parameter.
+ * The buffer is allocated in the TopMemoryContext and is given a NULL
+ * terminator so that callers are safe to call strlen() on it.
+ *
+ * This is used instead of CERT_GetCommonName(), which always performs quoting
+ * and/or escaping. NSS doesn't appear to give us a way to easily unescape the
+ * result, and we need to store the raw CN into port->peer_cn for compatibility
+ * with the OpenSSL implementation.
+ */
+static char *
+raw_subject_common_name(CERTCertificate *cert, unsigned int *len)
+{
+	CERTName	subject = cert->subject;
+	CERTRDN	  **rdn;
+
+	for (rdn = subject.rdns; *rdn; rdn++)
+	{
+		CERTAVA	  **ava;
+
+		for (ava = (*rdn)->avas; *ava; ava++)
+		{
+			SECItem	   *buf;
+			char	   *cn;
+
+			if (CERT_GetAVATag(*ava) != SEC_OID_AVA_COMMON_NAME)
+				continue;
+
+			/* Found a CN. Decode and copy it into a newly allocated buffer. */
+			buf = CERT_DecodeAVAValue(&(*ava)->value);
+			if (!buf)
+			{
+				/*
+				 * This failure case is difficult to test. (Since this code runs
+				 * after certificate authentication has otherwise succeeded,
+				 * you'd need to convince a CA implementation to sign a
+				 * corrupted certificate in order to get here.)
+				 *
+				 * Follow the behavior of CERT_GetCommonName() in this case and
+				 * simply return NULL, as if a Common Name had not been found.
+				 */
+				goto fail;
+			}
+
+			cn = MemoryContextAlloc(TopMemoryContext, buf->len + 1);
+			memcpy(cn, buf->data, buf->len);
+			cn[buf->len] = '\0';
+
+			*len = buf->len;
+
+			SECITEM_FreeItem(buf, PR_TRUE);
+			return cn;
+		}
+	}
+
+fail:
+	/* Not found. */
+	*len = 0;
+	return NULL;
+}
+
 static SECStatus
 pg_cert_auth_handler(void *arg, PRFileDesc * fd, PRBool checksig, PRBool isServer)
 {
@@ -1058,28 +1121,59 @@ pg_cert_auth_handler(void *arg, PRFileDesc * fd, PRBool checksig, PRBool isServe
 	Port	   *port = (Port *) arg;
 	CERTCertificate *cert;
 	char	   *peer_cn;
-	int			len;
+	unsigned int len;
 
 	status = SSL_AuthCertificate(CERT_GetDefaultCertDB(), port->pr_fd, checksig, PR_TRUE);
-	if (status == SECSuccess)
+	if (status != SECSuccess)
+		return status;
+
+	port->peer_cn = NULL;
+	port->peer_cert_valid = false;
+
+	cert = SSL_PeerCertificate(port->pr_fd);
+	if (!cert)
 	{
-		cert = SSL_PeerCertificate(port->pr_fd);
-		len = strlen(cert->subjectName);
-		peer_cn = MemoryContextAllocZero(TopMemoryContext, len + 1);
+		/* Shouldn't be possible; why did we get a client cert callback? */
+		Assert(cert != NULL);
 
-		/*
-		 * Skip over the key= portion of the key=value containing the peer CN.
-		 */
-		if (strncmp(cert->subjectName, "CN=", 3) == 0)
-			strlcpy(peer_cn, cert->subjectName + strlen("CN="), len + 1);
-		else
-			strlcpy(peer_cn, cert->subjectName, len + 1);
-		CERT_DestroyCertificate(cert);
+		PR_SetError(SEC_ERROR_LIBRARY_FAILURE, 0);
+		return SECFailure;
+	}
 
-		port->peer_cn = peer_cn;
+	peer_cn = raw_subject_common_name(cert, &len);
+	if (!peer_cn)
+	{
+		/* No Common Name, but the certificate otherwise checks out. */
 		port->peer_cert_valid = true;
+
+		status = SECSuccess;
+		goto cleanup;
 	}
 
+	/*
+	 * Reject embedded NULLs in certificate common name to prevent attacks like
+	 * CVE-2009-4034.
+	 */
+	if (len != strlen(peer_cn))
+	{
+		ereport(COMMERROR,
+				(errcode(ERRCODE_PROTOCOL_VIOLATION),
+				 errmsg("SSL certificate's common name contains embedded null")));
+
+		pfree(peer_cn);
+		PR_SetError(SEC_ERROR_CERT_NOT_VALID, 0);
+
+		status = SECFailure;
+		goto cleanup;
+	}
+
+	port->peer_cn = peer_cn;
+	port->peer_cert_valid = true;
+
+	status = SECSuccess;
+
+cleanup:
+	CERT_DestroyCertificate(cert);
 	return status;
 }
 
From 29d6390db3dd8d418c2abda24c285f621f1a5917 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:18:42 +0100
Subject: [PATCH v23 1/6] NSS Frontend, Backend and build infrastructure

TODO:
	* SCRAM channel binding is implemented but doesn't work
	* Frontend CRL configuration handling
	* Settle on a required version in autoconf
	* Move pg_nss.h to a .c file for both frontend and backend

Daniel Gustafsson, Andrew Dunstan, Jacob Champion
---
 configure                                     |  422 ++++-
 configure.ac                                  |   56 +-
 .../postgres_fdw/expected/postgres_fdw.out    |    2 +-
 src/Makefile.global.in                        |    2 +-
 src/backend/libpq/Makefile                    |    6 +-
 src/backend/libpq/auth.c                      |    7 +
 src/backend/libpq/be-secure-nss.c             | 1359 +++++++++++++++++
 src/backend/libpq/be-secure.c                 |    3 +
 src/backend/libpq/hba.c                       |    2 +-
 src/backend/utils/misc/guc.c                  |   20 +-
 src/common/Makefile                           |    2 +-
 src/include/common/pg_nss.h                   |  175 +++
 src/include/libpq/libpq-be.h                  |   15 +-
 src/include/libpq/libpq.h                     |    3 +
 src/include/pg_config.h.in                    |    3 +
 src/include/pg_config_manual.h                |    5 +-
 src/interfaces/libpq/Makefile                 |   13 +-
 src/interfaces/libpq/fe-connect.c             |    4 +
 src/interfaces/libpq/fe-secure-nss.c          | 1112 ++++++++++++++
 src/interfaces/libpq/fe-secure.c              |    5 +-
 src/interfaces/libpq/libpq-fe.h               |   13 +-
 src/interfaces/libpq/libpq-int.h              |   20 +-
 src/tools/msvc/Mkvcbuild.pm                   |   22 +-
 src/tools/msvc/Solution.pm                    |   20 +
 src/tools/msvc/config_default.pl              |    1 +
 25 files changed, 3216 insertions(+), 76 deletions(-)
 create mode 100644 src/backend/libpq/be-secure-nss.c
 create mode 100644 src/include/common/pg_nss.h
 create mode 100644 src/interfaces/libpq/fe-secure-nss.c

diff --git a/configure b/configure
index 8af4b99021..cc6088b545 100755
--- a/configure
+++ b/configure
@@ -653,6 +653,9 @@ LIBOBJS
 UUID_LIBS
 LDAP_LIBS_BE
 LDAP_LIBS_FE
+with_ssl
+NSPR_CONFIG
+NSS_CONFIG
 PTHREAD_CFLAGS
 PTHREAD_LIBS
 PTHREAD_CC
@@ -710,7 +713,6 @@ with_uuid
 with_readline
 with_systemd
 with_selinux
-with_openssl
 with_ldap
 with_krb_srvnam
 krb_srvtab
@@ -798,6 +800,7 @@ infodir
 docdir
 oldincludedir
 includedir
+runstatedir
 localstatedir
 sharedstatedir
 sysconfdir
@@ -855,7 +858,6 @@ with_pam
 with_bsd_auth
 with_ldap
 with_bonjour
-with_openssl
 with_selinux
 with_systemd
 with_readline
@@ -867,6 +869,8 @@ with_libxslt
 with_system_tzdata
 with_zlib
 with_gnu_ld
+with_ssl
+with_openssl
 enable_largefile
 '
       ac_precious_vars='build_alias
@@ -935,6 +939,7 @@ datadir='${datarootdir}'
 sysconfdir='${prefix}/etc'
 sharedstatedir='${prefix}/com'
 localstatedir='${prefix}/var'
+runstatedir='${localstatedir}/run'
 includedir='${prefix}/include'
 oldincludedir='/usr/include'
 docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
@@ -1187,6 +1192,15 @@ do
   | -silent | --silent | --silen | --sile | --sil)
     silent=yes ;;
 
+  -runstatedir | --runstatedir | --runstatedi | --runstated \
+  | --runstate | --runstat | --runsta | --runst | --runs \
+  | --run | --ru | --r)
+    ac_prev=runstatedir ;;
+  -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \
+  | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \
+  | --run=* | --ru=* | --r=*)
+    runstatedir=$ac_optarg ;;
+
   -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
     ac_prev=sbindir ;;
   -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
@@ -1324,7 +1338,7 @@ fi
 for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
 		datadir sysconfdir sharedstatedir localstatedir includedir \
 		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
-		libdir localedir mandir
+		libdir localedir mandir runstatedir
 do
   eval ac_val=\$$ac_var
   # Remove trailing slashes.
@@ -1477,6 +1491,7 @@ Fine tuning of the installation directories:
   --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
   --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
   --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
+  --runstatedir=DIR       modifiable per-process data [LOCALSTATEDIR/run]
   --libdir=DIR            object code libraries [EPREFIX/lib]
   --includedir=DIR        C header files [PREFIX/include]
   --oldincludedir=DIR     C header files for non-gcc [/usr/include]
@@ -1557,7 +1572,6 @@ Optional Packages:
   --with-bsd-auth         build with BSD Authentication support
   --with-ldap             build with LDAP support
   --with-bonjour          build with Bonjour support
-  --with-openssl          build with OpenSSL support
   --with-selinux          build with SELinux support
   --with-systemd          build with systemd support
   --without-readline      do not use GNU Readline nor BSD Libedit for editing
@@ -1571,6 +1585,8 @@ Optional Packages:
                           use system time zone data in DIR
   --without-zlib          do not use Zlib
   --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
+  --with-ssl=LIB          use LIB for SSL/TLS support (openssl, nss)
+  --with-openssl          obsolete spelling of --with-ssl=openssl
 
 Some influential environment variables:
   CC          C compiler command
@@ -8071,41 +8087,6 @@ fi
 $as_echo "$with_bonjour" >&6; }

-#
-# OpenSSL
-#
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build with OpenSSL support" >&5
-$as_echo_n "checking whether to build with OpenSSL support... " >&6; }
-
-
-
-# Check whether --with-openssl was given.
-if test "${with_openssl+set}" = set; then :
-  withval=$with_openssl;
-  case $withval in
-    yes)
-
-$as_echo "#define USE_OPENSSL 1" >>confdefs.h
-
-      ;;
-    no)
-      :
-      ;;
-    *)
-      as_fn_error $? "no argument expected for --with-openssl option" "$LINENO" 5
-      ;;
-  esac
-
-else
-  with_openssl=no
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_openssl" >&5
-$as_echo "$with_openssl" >&6; }
-
-
 #
 # SELinux
 #
@@ -12179,7 +12160,64 @@ fi
   fi
 fi
 
+#
+# SSL Library
+#
+# There are currently two supported SSL/TLS libraries, OpenSSL and NSS.
+#
+
+
+
+# Check whether --with-ssl was given.
+if test "${with_ssl+set}" = set; then :
+  withval=$with_ssl;
+  case $withval in
+    yes)
+      as_fn_error $? "argument required for --with-ssl option" "$LINENO" 5
+      ;;
+    no)
+      as_fn_error $? "argument required for --with-ssl option" "$LINENO" 5
+      ;;
+    *)
+
+      ;;
+  esac
+
+fi
+
+
+if test x"$with_ssl" = x"" ; then
+  with_ssl=no
+fi
+
+
+
+# Check whether --with-openssl was given.
+if test "${with_openssl+set}" = set; then :
+  withval=$with_openssl;
+  case $withval in
+    yes)
+      :
+      ;;
+    no)
+      :
+      ;;
+    *)
+      as_fn_error $? "no argument expected for --with-openssl option" "$LINENO" 5
+      ;;
+  esac
+
+else
+  with_openssl=no
+
+fi
+
+
 if test "$with_openssl" = yes ; then
+  with_ssl=openssl
+fi
+
+if test "$with_ssl" = openssl ; then
     # Minimum required OpenSSL version is 1.0.1
 
 $as_echo "#define OPENSSL_API_COMPAT 0x10001000L" >>confdefs.h
@@ -12440,8 +12478,280 @@ _ACEOF
 fi
 done
 
+
+$as_echo "#define USE_OPENSSL 1" >>confdefs.h
+
+elif test "$with_ssl" = nss ; then
+  # TODO: fallback in case nss-config/nspr-config aren't found.
+  if test -z "$NSS_CONFIG"; then
+  for ac_prog in nss-config
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_NSS_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $NSS_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_NSS_CONFIG="$NSS_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_NSS_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  ;;
+esac
+fi
+NSS_CONFIG=$ac_cv_path_NSS_CONFIG
+if test -n "$NSS_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NSS_CONFIG" >&5
+$as_echo "$NSS_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$NSS_CONFIG" && break
+done
+
+else
+  # Report the value of NSS_CONFIG in configure's output in all cases.
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for NSS_CONFIG" >&5
+$as_echo_n "checking for NSS_CONFIG... " >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NSS_CONFIG" >&5
+$as_echo "$NSS_CONFIG" >&6; }
+fi
+
+  if test -z "$NSPR_CONFIG"; then
+  for ac_prog in nspr-config
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_NSPR_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $NSPR_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_NSPR_CONFIG="$NSPR_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_NSPR_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  ;;
+esac
+fi
+NSPR_CONFIG=$ac_cv_path_NSPR_CONFIG
+if test -n "$NSPR_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NSPR_CONFIG" >&5
+$as_echo "$NSPR_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$NSPR_CONFIG" && break
+done
+
+else
+  # Report the value of NSPR_CONFIG in configure's output in all cases.
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for NSPR_CONFIG" >&5
+$as_echo_n "checking for NSPR_CONFIG... " >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NSPR_CONFIG" >&5
+$as_echo "$NSPR_CONFIG" >&6; }
+fi
+
+  if test -n "$NSS_CONFIG"; then
+    NSS_LIBS=`$NSS_CONFIG --libs`
+	NSS_CFLAGS=`$NSS_CONFIG --cflags`
+  fi
+  if test -n "$NSPR_CONFIG"; then
+	NSPR_LIBS=`$NSPR_CONFIG --libs`
+	NSPR_CFLAGS=`$NSPR_CONFIG --cflags`
+  fi
+
+  LDFLAGS="$LDFLAGS $NSS_LIBS $NSPR_LIBS"
+  CFLAGS="$CFLAGS $NSS_CFLAGS $NSPR_CFLAGS"
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for NSS_InitContext in -lnss3" >&5
+$as_echo_n "checking for NSS_InitContext in -lnss3... " >&6; }
+if ${ac_cv_lib_nss3_NSS_InitContext+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lnss3  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char NSS_InitContext ();
+int
+main ()
+{
+return NSS_InitContext ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_nss3_NSS_InitContext=yes
+else
+  ac_cv_lib_nss3_NSS_InitContext=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nss3_NSS_InitContext" >&5
+$as_echo "$ac_cv_lib_nss3_NSS_InitContext" >&6; }
+if test "x$ac_cv_lib_nss3_NSS_InitContext" = xyes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBNSS3 1
+_ACEOF
+
+  LIBS="-lnss3 $LIBS"
+
+else
+  as_fn_error $? "library 'nss3' is required for NSS" "$LINENO" 5
 fi
 
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PR_GetDefaultIOMethods in -lnspr4" >&5
+$as_echo_n "checking for PR_GetDefaultIOMethods in -lnspr4... " >&6; }
+if ${ac_cv_lib_nspr4_PR_GetDefaultIOMethods+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lnspr4  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char PR_GetDefaultIOMethods ();
+int
+main ()
+{
+return PR_GetDefaultIOMethods ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_nspr4_PR_GetDefaultIOMethods=yes
+else
+  ac_cv_lib_nspr4_PR_GetDefaultIOMethods=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nspr4_PR_GetDefaultIOMethods" >&5
+$as_echo "$ac_cv_lib_nspr4_PR_GetDefaultIOMethods" >&6; }
+if test "x$ac_cv_lib_nspr4_PR_GetDefaultIOMethods" = xyes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBNSPR4 1
+_ACEOF
+
+  LIBS="-lnspr4 $LIBS"
+
+else
+  as_fn_error $? "library 'nspr4' is required for NSS" "$LINENO" 5
+fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SSL_GetImplementedCiphers in -lssl3" >&5
+$as_echo_n "checking for SSL_GetImplementedCiphers in -lssl3... " >&6; }
+if ${ac_cv_lib_ssl3_SSL_GetImplementedCiphers+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lssl3  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char SSL_GetImplementedCiphers ();
+int
+main ()
+{
+return SSL_GetImplementedCiphers ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_ssl3_SSL_GetImplementedCiphers=yes
+else
+  ac_cv_lib_ssl3_SSL_GetImplementedCiphers=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ssl3_SSL_GetImplementedCiphers" >&5
+$as_echo "$ac_cv_lib_ssl3_SSL_GetImplementedCiphers" >&6; }
+if test "x$ac_cv_lib_ssl3_SSL_GetImplementedCiphers" = xyes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBSSL3 1
+_ACEOF
+
+  LIBS="-lssl3 $LIBS"
+
+else
+  as_fn_error $? "library 'ssl3' is required for NSS" "$LINENO" 5
+fi
+
+
+$as_echo "#define USE_NSS 1" >>confdefs.h
+
+elif test "$with_ssl" != no ; then
+  as_fn_error $? "--with-ssl must specify one of openssl or nss" "$LINENO" 5
+fi
+
+
 if test "$with_pam" = yes ; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pam_start in -lpam" >&5
 $as_echo_n "checking for pam_start in -lpam... " >&6; }
@@ -13327,7 +13637,7 @@ done
 
 fi
 
-if test "$with_openssl" = yes ; then
+if test "$with_ssl" = openssl ; then
   ac_fn_c_check_header_mongrel "$LINENO" "openssl/ssl.h" "ac_cv_header_openssl_ssl_h" "$ac_includes_default"
 if test "x$ac_cv_header_openssl_ssl_h" = xyes; then :
 
@@ -13344,6 +13654,25 @@ else
 fi

+fi
+
+if test "$with_ssl" = nss ; then
+  ac_fn_c_check_header_mongrel "$LINENO" "nss/ssl.h" "ac_cv_header_nss_ssl_h" "$ac_includes_default"
+if test "x$ac_cv_header_nss_ssl_h" = xyes; then :
+
+else
+  as_fn_error $? "header file <nss/ssl.h> is required for NSS" "$LINENO" 5
+fi
+
+
+  ac_fn_c_check_header_mongrel "$LINENO" "nss/nss.h" "ac_cv_header_nss_nss_h" "$ac_includes_default"
+if test "x$ac_cv_header_nss_nss_h" = xyes; then :
+
+else
+  as_fn_error $? "header file <nss/nss.h> is required for NSS" "$LINENO" 5
+fi
+
+
 fi
 
 if test "$with_pam" = yes ; then
@@ -14689,7 +15018,7 @@ else
     We can't simply define LARGE_OFF_T to be 9223372036854775807,
     since some C++ compilers masquerading as C compilers
     incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
   int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
 		       && LARGE_OFF_T % 2147483647 == 1)
 		      ? 1 : -1];
@@ -14735,7 +15064,7 @@ else
     We can't simply define LARGE_OFF_T to be 9223372036854775807,
     since some C++ compilers masquerading as C compilers
     incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
   int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
 		       && LARGE_OFF_T % 2147483647 == 1)
 		      ? 1 : -1];
@@ -14759,7 +15088,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
     We can't simply define LARGE_OFF_T to be 9223372036854775807,
     since some C++ compilers masquerading as C compilers
     incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
   int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
 		       && LARGE_OFF_T % 2147483647 == 1)
 		      ? 1 : -1];
@@ -14804,7 +15133,7 @@ else
     We can't simply define LARGE_OFF_T to be 9223372036854775807,
     since some C++ compilers masquerading as C compilers
     incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
   int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
 		       && LARGE_OFF_T % 2147483647 == 1)
 		      ? 1 : -1];
@@ -14828,7 +15157,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
     We can't simply define LARGE_OFF_T to be 9223372036854775807,
     since some C++ compilers masquerading as C compilers
     incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
   int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
 		       && LARGE_OFF_T % 2147483647 == 1)
 		      ? 1 : -1];
@@ -18106,6 +18435,9 @@ $as_echo_n "checking which random number source to use... " >&6; }
 if test x"$with_openssl" = x"yes" ; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: OpenSSL" >&5
 $as_echo "OpenSSL" >&6; }
+elif test x"$with_nss" = x"yes" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: NSS" >&5
+$as_echo "NSS" >&6; }
 elif test x"$PORTNAME" = x"win32" ; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: Windows native" >&5
 $as_echo "Windows native" >&6; }
diff --git a/configure.ac b/configure.ac
index 868a94c9ba..0da8cc9b0b 100644
--- a/configure.ac
+++ b/configure.ac
@@ -852,15 +852,6 @@ PGAC_ARG_BOOL(with, bonjour, no,
 AC_MSG_RESULT([$with_bonjour])

-#
-# OpenSSL
-#
-AC_MSG_CHECKING([whether to build with OpenSSL support])
-PGAC_ARG_BOOL(with, openssl, no, [build with OpenSSL support],
-              [AC_DEFINE([USE_OPENSSL], 1, [Define to build with OpenSSL support. (--with-openssl)])])
-AC_MSG_RESULT([$with_openssl])
-AC_SUBST(with_openssl)
-
 #
 # SELinux
 #
@@ -1209,7 +1200,21 @@ if test "$with_gssapi" = yes ; then
   fi
 fi
 
+#
+# SSL Library
+#
+# There are currently two supported SSL/TLS libraries, OpenSSL and NSS.
+#
+PGAC_ARG_REQ(with, ssl, [LIB], [use LIB for SSL/TLS support (openssl, nss)])
+if test x"$with_ssl" = x"" ; then
+  with_ssl=no
+fi
+PGAC_ARG_BOOL(with, openssl, no, [obsolete spelling of --with-ssl=openssl])
 if test "$with_openssl" = yes ; then
+  with_ssl=openssl
+fi
+
+if test "$with_ssl" = openssl ; then
   dnl Order matters!
   # Minimum required OpenSSL version is 1.0.1
   AC_DEFINE(OPENSSL_API_COMPAT, [0x10001000L],
@@ -1233,7 +1238,31 @@ if test "$with_openssl" = yes ; then
   # thread-safety. In 1.1.0, it's no longer required, and CRYPTO_lock()
   # function was removed.
   AC_CHECK_FUNCS([CRYPTO_lock])
+  AC_DEFINE([USE_OPENSSL], 1, [Define to 1 if you have OpenSSL support.])
+elif test "$with_ssl" = nss ; then
+  # TODO: fallback in case nss-config/nspr-config aren't found.
+  PGAC_PATH_PROGS(NSS_CONFIG, nss-config)
+  PGAC_PATH_PROGS(NSPR_CONFIG, nspr-config)
+  if test -n "$NSS_CONFIG"; then
+    NSS_LIBS=`$NSS_CONFIG --libs`
+	NSS_CFLAGS=`$NSS_CONFIG --cflags`
+  fi
+  if test -n "$NSPR_CONFIG"; then
+	NSPR_LIBS=`$NSPR_CONFIG --libs`
+	NSPR_CFLAGS=`$NSPR_CONFIG --cflags`
+  fi
+
+  LDFLAGS="$LDFLAGS $NSS_LIBS $NSPR_LIBS"
+  CFLAGS="$CFLAGS $NSS_CFLAGS $NSPR_CFLAGS"
+
+  AC_CHECK_LIB(nss3, NSS_InitContext, [], [AC_MSG_ERROR([library 'nss3' is required for NSS])])
+  AC_CHECK_LIB(nspr4, PR_GetDefaultIOMethods, [], [AC_MSG_ERROR([library 'nspr4' is required for NSS])])
+  AC_CHECK_LIB(ssl3, SSL_GetImplementedCiphers, [], [AC_MSG_ERROR([library 'ssl3' is required for NSS])])
+  AC_DEFINE([USE_NSS], 1, [Define to 1 if you have NSS support,])
+elif test "$with_ssl" != no ; then
+  AC_MSG_ERROR([--with-ssl must specify one of openssl or nss])
 fi
+AC_SUBST(with_ssl)
 
 if test "$with_pam" = yes ; then
   AC_CHECK_LIB(pam,    pam_start, [], [AC_MSG_ERROR([library 'pam' is required for PAM])])
@@ -1406,11 +1435,16 @@ if test "$with_gssapi" = yes ; then
 	[AC_CHECK_HEADERS(gssapi.h, [], [AC_MSG_ERROR([gssapi.h header file is required for GSSAPI])])])
 fi
 
-if test "$with_openssl" = yes ; then
+if test "$with_ssl" = openssl ; then
   AC_CHECK_HEADER(openssl/ssl.h, [], [AC_MSG_ERROR([header file <openssl/ssl.h> is required for OpenSSL])])
   AC_CHECK_HEADER(openssl/err.h, [], [AC_MSG_ERROR([header file <openssl/err.h> is required for OpenSSL])])
 fi
 
+if test "$with_ssl" = nss ; then
+  AC_CHECK_HEADER(nss/ssl.h, [], [AC_MSG_ERROR([header file <nss/ssl.h> is required for NSS])])
+  AC_CHECK_HEADER(nss/nss.h, [], [AC_MSG_ERROR([header file <nss/nss.h> is required for NSS])])
+fi
+
 if test "$with_pam" = yes ; then
   AC_CHECK_HEADERS(security/pam_appl.h, [],
                    [AC_CHECK_HEADERS(pam/pam_appl.h, [],
@@ -2165,6 +2199,8 @@ fi
 AC_MSG_CHECKING([which random number source to use])
 if test x"$with_openssl" = x"yes" ; then
   AC_MSG_RESULT([OpenSSL])
+elif test x"$with_nss" = x"yes" ; then
+  AC_MSG_RESULT([NSS])
 elif test x"$PORTNAME" = x"win32" ; then
   AC_MSG_RESULT([Windows native])
 else
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 1cad311436..1b0c5ce1fa 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -8923,7 +8923,7 @@ DO $d$
     END;
 $d$;
 ERROR:  invalid option "password"
-HINT:  Valid options in this context are: service, passfile, channel_binding, connect_timeout, dbname, host, hostaddr, port, options, application_name, keepalives, keepalives_idle, keepalives_interval, keepalives_count, tcp_user_timeout, sslmode, sslcompression, sslcert, sslkey, sslrootcert, sslcrl, requirepeer, ssl_min_protocol_version, ssl_max_protocol_version, gssencmode, krbsrvname, gsslib, target_session_attrs, use_remote_estimate, fdw_startup_cost, fdw_tuple_cost, extensions, updatable, fetch_size
+HINT:  Valid options in this context are: service, passfile, channel_binding, connect_timeout, dbname, host, hostaddr, port, options, application_name, keepalives, keepalives_idle, keepalives_interval, keepalives_count, tcp_user_timeout, sslmode, sslcompression, sslcert, sslkey, sslrootcert, sslcrl, requirepeer, ssl_min_protocol_version, ssl_max_protocol_version, gssencmode, krbsrvname, gsslib, target_session_attrs, cert_database, use_remote_estimate, fdw_startup_cost, fdw_tuple_cost, extensions, updatable, fetch_size
 CONTEXT:  SQL statement "ALTER SERVER loopback_nopw OPTIONS (ADD password 'dummypw')"
 PL/pgSQL function inline_code_block line 3 at EXECUTE
 -- If we add a password for our user mapping instead, we should get a different
diff --git a/src/Makefile.global.in b/src/Makefile.global.in
index 7ca1e9aac5..bdab2a6825 100644
--- a/src/Makefile.global.in
+++ b/src/Makefile.global.in
@@ -183,7 +183,7 @@ with_icu	= @with_icu@
 with_perl	= @with_perl@
 with_python	= @with_python@
 with_tcl	= @with_tcl@
-with_openssl	= @with_openssl@
+with_ssl	= @with_ssl@
 with_readline	= @with_readline@
 with_selinux	= @with_selinux@
 with_systemd	= @with_systemd@
diff --git a/src/backend/libpq/Makefile b/src/backend/libpq/Makefile
index efc5ef760a..045d2c2f6b 100644
--- a/src/backend/libpq/Makefile
+++ b/src/backend/libpq/Makefile
@@ -28,8 +28,12 @@ OBJS = \
 	pqmq.o \
 	pqsignal.o
 
-ifeq ($(with_openssl),yes)
+ifeq ($(with_ssl),openssl)
 OBJS += be-secure-openssl.o
+else
+ifeq ($(with_ssl),nss)
+OBJS += be-secure-nss.o
+endif
 endif
 
 ifeq ($(with_gssapi),yes)
diff --git a/src/backend/libpq/auth.c b/src/backend/libpq/auth.c
index 545635f41a..09ad2ad063 100644
--- a/src/backend/libpq/auth.c
+++ b/src/backend/libpq/auth.c
@@ -2849,7 +2849,14 @@ CheckCertAuth(Port *port)
 {
 	int			status_check_usermap = STATUS_ERROR;
 
+#if defined(USE_OPENSSL)
 	Assert(port->ssl);
+#elif defined(USE_NSS)
+	/* TODO: should we rename pr_fd to ssl, to keep consistency? */
+	Assert(port->pr_fd);
+#else
+	Assert(false);
+#endif
 
 	/* Make sure we have received a username in the certificate */
 	if (port->peer_cn == NULL ||
diff --git a/src/backend/libpq/be-secure-nss.c b/src/backend/libpq/be-secure-nss.c
new file mode 100644
index 0000000000..80d7598662
--- /dev/null
+++ b/src/backend/libpq/be-secure-nss.c
@@ -0,0 +1,1359 @@
+/*-------------------------------------------------------------------------
+ *
+ * be-secure-nss.c
+ *	  functions for supporting NSS as a TLS backend
+ *
+ *
+ * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ *	  src/backend/libpq/be-secure-nss.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres.h"
+
+#include <sys/stat.h>
+
+/*
+ * BITS_PER_BYTE is also defined in the NSPR header files, so we need to undef
+ * our version to avoid compiler warnings on redefinition.
+ */
+#define pg_BITS_PER_BYTE BITS_PER_BYTE
+#undef BITS_PER_BYTE
+
+/*
+ * The nspr/obsolete/protypes.h NSPR header typedefs uint64 and int64 with
+ * colliding definitions from ours, causing a much expected compiler error.
+ * Remove backwards compatibility with ancient NSPR versions to avoid this.
+ */
+#define NO_NSPR_10_SUPPORT
+#include <nspr/nspr.h>
+#include <nspr/prerror.h>
+#include <nspr/prio.h>
+#include <nspr/prmem.h>
+#include <nspr/prtypes.h>
+
+#include <nss/nss.h>
+#include <nss/base64.h>
+#include <nss/cert.h>
+#include <nss/certdb.h>
+#include <nss/hasht.h>
+#include <nss/keyhi.h>
+#include <nss/pk11pub.h>
+#include <nss/secder.h>
+#include <nss/secerr.h>
+#include <nss/secitem.h>
+#include <nss/secoidt.h>
+#include <nss/secport.h>
+#include <nss/ssl.h>
+#include <nss/sslerr.h>
+#include <nss/sslproto.h>
+
+/*
+ * Ensure that the colliding definitions match, else throw an error. In case
+ * NSPR has removed the definition for some reason, make sure to put ours
+ * back again.
+ */
+#if defined(BITS_PER_BYTE)
+#if BITS_PER_BYTE != pg_BITS_PER_BYTE
+#error "incompatible byte widths between NSPR and postgres"
+#endif
+#else
+#define BITS_PER_BYTE pg_BITS_PER_BYTE
+#endif
+#undef pg_BITS_PER_BYTE
+
+#include "common/pg_nss.h"
+#include "lib/stringinfo.h"
+#include "libpq/libpq.h"
+#include "nodes/pg_list.h"
+#include "miscadmin.h"
+#include "storage/fd.h"
+#include "utils/guc.h"
+#include "utils/memutils.h"
+
+
+/* default init hook can be overridden by a shared library */
+static void default_nss_tls_init(bool isServerStart);
+nss_tls_init_hook_type nss_tls_init_hook = default_nss_tls_init;
+
+static PRDescIdentity pr_id;
+
+static PRIOMethods pr_iomethods;
+static NSSInitContext * nss_context = NULL;
+static SSLVersionRange desired_sslver;
+
+static char *external_ssl_passphrase_cb(PK11SlotInfo *slot, PRBool retry, void *arg);
+static bool dummy_ssl_passwd_cb_called = false;
+static bool ssl_is_server_start;
+
+/*
+ * PR_ImportTCPSocket() is a private API, but very widely used, as it's the
+ * only way to make NSS use an already set up POSIX file descriptor rather
+ * than opening one itself. To quote the NSS documentation:
+ *
+ *		"In theory, code that uses PR_ImportTCPSocket may break when NSPR's
+ *		implementation changes. In practice, this is unlikely to happen because
+ *		NSPR's implementation has been stable for years and because of NSPR's
+ *		strong commitment to backward compatibility."
+ *
+ * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PR_ImportTCPSocket
+ *
+ * The function is declared in <private/pprio.h>, but as it is a header marked
+ * private we declare it here rather than including it.
+ */
+NSPR_API(PRFileDesc *) PR_ImportTCPSocket(int);
+
+/* NSS IO layer callback overrides */
+static PRInt32 pg_ssl_read(PRFileDesc * fd, void *buf, PRInt32 amount,
+						   PRIntn flags, PRIntervalTime timeout);
+static PRInt32 pg_ssl_write(PRFileDesc * fd, const void *buf, PRInt32 amount,
+							PRIntn flags, PRIntervalTime timeout);
+static PRStatus pg_ssl_close(PRFileDesc * fd);
+/* Utility functions */
+static PRFileDesc * init_iolayer(Port *port);
+static uint16 ssl_protocol_version_to_nss(int v, const char *guc_name);
+
+static char *pg_SSLerrmessage(PRErrorCode errcode);
+static char *ssl_protocol_version_to_string(int v);
+static SECStatus pg_cert_auth_handler(void *arg, PRFileDesc * fd,
+									  PRBool checksig, PRBool isServer);
+static SECStatus pg_bad_cert_handler(void *arg, PRFileDesc * fd);
+static char *dummy_ssl_passphrase_cb(PK11SlotInfo * slot, PRBool retry, void *arg);
+
+/* ------------------------------------------------------------ */
+/*						 Public interface						*/
+/* ------------------------------------------------------------ */
+
+/*
+ * be_tls_init
+ *			Initialize the nss TLS library in the postmaster
+ *
+ * The majority of the setup needs to happen in be_tls_open_server since the
+ * NSPR initialization must happen after the forking of the backend. We could
+ * potentially move some parts in under !isServerStart, but so far this is the
+ * separation chosen.
+ */
+int
+be_tls_init(bool isServerStart)
+{
+	SECStatus	status;
+	SSLVersionRange supported_sslver;
+
+	status = SSL_ConfigServerSessionIDCacheWithOpt(0, 0, NULL, 1, 0, 0, PR_FALSE);
+	if (status != SECSuccess)
+	{
+		ereport(isServerStart ? FATAL : LOG,
+				(errmsg("unable to connect to TLS connection cache: %s",
+						pg_SSLerrmessage(PR_GetError()))));
+		return -1;
+	}
+
+	if (!ssl_database || strlen(ssl_database) == 0)
+	{
+		ereport(isServerStart ? FATAL : LOG,
+				(errmsg("no certificate database specified")));
+		return -1;
+	}
+
+	/*
+	 * We check for the desired TLS version range here, even though we cannot
+	 * set it until be_open_server such that we can be compatible with how the
+	 * OpenSSL backend reports errors for incompatible range configurations.
+	 * Set either the default supported TLS version range, or the configured
+	 * range from ssl_min_protocol_version and ssl_max_protocol version. In
+	 * case the user hasn't defined the maximum allowed version we fall back
+	 * to the highest version TLS that the library supports.
+	 */
+	if (SSL_VersionRangeGetSupported(ssl_variant_stream, &supported_sslver) != SECSuccess)
+	{
+		ereport(isServerStart ? FATAL : LOG,
+				(errmsg("unable to get default protocol support from NSS")));
+		return -1;
+	}
+
+	/*
+	 * Set the fallback versions for the TLS protocol version range to a
+	 * combination of our minimal requirement and the library maximum. Error
+	 * messages should be kept identical to those in be-secure-openssl.c to
+	 * make translations easier.
+	 */
+	desired_sslver.min = SSL_LIBRARY_VERSION_TLS_1_0;
+	desired_sslver.max = supported_sslver.max;
+
+	if (ssl_min_protocol_version)
+	{
+		int			ver = ssl_protocol_version_to_nss(ssl_min_protocol_version,
+													  "ssl_min_protocol_version");
+
+		if (ver == -1)
+		{
+			ereport(isServerStart ? FATAL : LOG,
+					(errmsg("\"%s\" setting \"%s\" not supported by this build",
+							"ssl_min_protocol_version",
+							GetConfigOption("ssl_min_protocol_version",
+											false, false))));
+			return -1;
+		}
+
+		if (ver > 0)
+			desired_sslver.min = ver;
+	}
+
+	if (ssl_max_protocol_version)
+	{
+		int			ver = ssl_protocol_version_to_nss(ssl_max_protocol_version,
+													  "ssl_max_protocol_version");
+
+		if (ver == -1)
+		{
+			ereport(isServerStart ? FATAL : LOG,
+					(errmsg("\"%s\" setting \"%s\" not supported by this build",
+							"ssl_max_protocol_version",
+							GetConfigOption("ssl_max_protocol_version",
+											false, false))));
+			return -1;
+		}
+		if (ver > 0)
+			desired_sslver.max = ver;
+
+		if (ver < desired_sslver.min)
+		{
+			ereport(isServerStart ? FATAL : LOG,
+					(errmsg("could not set SSL protocol version range"),
+					 errdetail("\"%s\" cannot be higher than \"%s\"",
+							   "ssl_min_protocol_version",
+							   "ssl_max_protocol_version")));
+			return -1;
+		}
+	}
+
+	/*
+	 * Set the passphrase callback which will be used both to obtain the
+	 * passphrase from the user, as well as by NSS to obtain the phrase
+	 * repeatedly.
+	 */
+	ssl_is_server_start = isServerStart;
+	(*nss_tls_init_hook) (isServerStart);
+
+	return 0;
+}
+
+int
+be_tls_open_server(Port *port)
+{
+	SECStatus	status;
+	PRFileDesc *model;
+	PRFileDesc *pr_fd;
+	PRFileDesc *layer;
+	CERTCertificate *server_cert;
+	SECKEYPrivateKey *private_key;
+	CERTSignedCrl *crl;
+	SECItem		crlname;
+	char	   *cert_database;
+	NSSInitParameters params;
+
+	/*
+	 * The NSPR documentation states that runtime initialization via PR_Init
+	 * is no longer required, as the first caller into NSPR will perform the
+	 * initialization implicitly. The documentation doesn't however clarify
+	 * from which version this is holds true, so let's perform the potentially
+	 * superfluous initialization anyways to avoid crashing on older versions
+	 * of NSPR, as there is no difference in overhead.  The NSS documentation
+	 * still states that PR_Init must be called in some way (implicitly or
+	 * explicitly).
+	 *
+	 * The below parameters are what the implicit initialization would've done
+	 * for us, and should work even for older versions where it might not be
+	 * done automatically. The last parameter, maxPTDs, is set to various
+	 * values in other codebases, but has been unused since NSPR 2.1 which was
+	 * released sometime in 1998. In current versions of NSPR all parameters
+	 * are ignored.
+	 */
+	PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0 /* maxPTDs */ );
+
+	/*
+	 * The certificate path (configdir) must contain a valid NSS database. If
+	 * the certificate path isn't a valid directory, NSS will fall back on the
+	 * system certificate database. If the certificate path is a directory but
+	 * is empty then the initialization will fail. On the client side this can
+	 * be allowed for any sslmode but the verify-xxx ones.
+	 * https://bugzilla.redhat.com/show_bug.cgi?id=728562 For the server side
+	 * we won't allow this to fail however, as we require the certificate and
+	 * key to exist.
+	 *
+	 * The original design of NSS was for a single application to use a single
+	 * copy of it, initialized with NSS_Initialize() which isn't returning any
+	 * handle with which to refer to NSS. NSS initialization and shutdown are
+	 * global for the application, so a shutdown in another NSS enabled
+	 * library would cause NSS to be stopped for libpq as well.  The fix has
+	 * been to introduce NSS_InitContext which returns a context handle to
+	 * pass to NSS_ShutdownContext.  NSS_InitContext was introduced in NSS
+	 * 3.12, but the use of it is not very well documented.
+	 * https://bugzilla.redhat.com/show_bug.cgi?id=738456
+	 *
+	 * The InitParameters struct passed can be used to override internal
+	 * values in NSS, but the usage is not documented at all. When using
+	 * NSS_Init initializations, the values are instead set via PK11_Configure
+	 * calls so the PK11_Configure documentation can be used to glean some
+	 * details on these.
+	 *
+	 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/PKCS11/Module_Specs
+	 */
+	memset(&params, '\0', sizeof(params));
+	params.length = sizeof(params);
+
+	if (!ssl_database || strlen(ssl_database) == 0)
+		ereport(FATAL,
+				(errmsg("no certificate database specified")));
+
+	cert_database = psprintf("sql:%s", ssl_database);
+	nss_context = NSS_InitContext(cert_database, "", "", "",
+								  &params,
+								  NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
+	pfree(cert_database);
+
+	if (!nss_context)
+		ereport(FATAL,
+				(errmsg("unable to read certificate database \"%s\": %s",
+						ssl_database, pg_SSLerrmessage(PR_GetError()))));
+
+	/*
+	 * Import the already opened socket as we don't want to use NSPR functions
+	 * for opening the network socket due to how the PostgreSQL protocol works
+	 * with TLS connections. This function is not part of the NSPR public API,
+	 * see the comment at the top of the file for the rationale of still using
+	 * it.
+	 */
+	pr_fd = PR_ImportTCPSocket(port->sock);
+	if (!pr_fd)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to connect to socket")));
+		return -1;
+	}
+
+	/*
+	 * Most of the documentation available, and implementations of, NSS/NSPR
+	 * use the PR_NewTCPSocket() function here, which has the drawback that it
+	 * can only create IPv4 sockets. Instead use PR_OpenTCPSocket() which
+	 * copes with IPv6 as well.
+	 *
+	 * We use a model filedescriptor here which is a construct in NSPR/NSS in
+	 * order to create a configuration template for sockets which can then be
+	 * applied to new sockets created. This makes more sense in a server which
+	 * accepts multiple connections and want to perform the boilerplate just
+	 * once, but it does provide a nice abstraction here as well in that we
+	 * can error out early without having performed any operation on the real
+	 * socket.
+	 */
+	model = PR_OpenTCPSocket(port->laddr.addr.ss_family);
+	if (!model)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to open socket")));
+		return -1;
+	}
+
+	/*
+	 * Convert the NSPR socket to an SSL socket. Ensuring the success of this
+	 * operation is critical as NSS SSL_* functions may return SECSuccess on
+	 * the socket even though SSL hasn't been enabled, which introduce a risk
+	 * of silent downgrades.
+	 */
+	model = SSL_ImportFD(NULL, model);
+	if (!model)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to enable TLS on socket")));
+		return -1;
+	}
+
+	/*
+	 * Configure basic settings for the connection over the SSL socket in
+	 * order to set it up as a server.
+	 */
+	if (SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to configure TLS connection")));
+		return -1;
+	}
+
+	if (SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_TRUE) != SECSuccess ||
+		SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_FALSE) != SECSuccess)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to configure TLS connection as server")));
+		return -1;
+	}
+
+	/*
+	 * SSLv2 is disabled by default, and SSLv3 will be excluded from the range
+	 * of allowed protocols further down. Since we really don't want these to
+	 * ever be enabled, let's use belts and suspenders and explicitly turn
+	 * them off as well.
+	 */
+	SSL_OptionSet(model, SSL_ENABLE_SSL2, PR_FALSE);
+	SSL_OptionSet(model, SSL_ENABLE_SSL3, PR_FALSE);
+
+#ifdef SSL_CBC_RANDOM_IV
+
+	/*
+	 * Enable protection against the BEAST attack in case the NSS server has
+	 * support for that. While SSLv3 is disabled, we may still allow TLSv1
+	 * which is affected. The option isn't documented as an SSL option, but as
+	 * an NSS environment variable.
+	 */
+	SSL_OptionSet(model, SSL_CBC_RANDOM_IV, PR_TRUE);
+#endif
+
+	/*
+	 * Configure the allowed ciphers. If there are no user preferred suites,
+	 * set the domestic policy.
+	 *
+	 * Historically there were different cipher policies based on export (and
+	 * import) restrictions: Domestic, Export and France. These are since long
+	 * removed with all ciphers being enabled by default. Due to backwards
+	 * compatibility, the old API is still used even though all three policies
+	 * now do the same thing.
+	 *
+	 * If SSLCipherSuites define a policy of the user, we set that rather than
+	 * enabling all ciphers via NSS_SetDomesticPolicy.
+	 *
+	 * TODO: while this code works, the set of ciphers which can be set and
+	 * still end up with a working socket is woefully underdocumented for
+	 * anything more recent than SSLv3 (the code for TLS actually calls ssl3
+	 * functions under the hood for SSL_CipherPrefSet), so it's unclear if
+	 * this is helpful or not. Using the policies works, but may be too
+	 * coarsely grained.
+	 *
+	 * Another TODO: The SSL_ImplementedCiphers table returned with calling
+	 * SSL_GetImplementedCiphers is sorted in server preference order. Sorting
+	 * SSLCipherSuites according to the order of the ciphers therein could be
+	 * a way to implement ssl_prefer_server_ciphers - if we at all want to use
+	 * cipher selection for NSS like how we do it for OpenSSL that is.
+	 */
+
+	/*
+	 * If no ciphers are specified, enable them all.
+	 */
+	if (!SSLCipherSuites || strlen(SSLCipherSuites) == 0)
+	{
+		status = NSS_SetDomesticPolicy();
+		if (status != SECSuccess)
+		{
+			ereport(COMMERROR,
+					(errmsg("unable to set cipher policy: %s",
+							pg_SSLerrmessage(PR_GetError()))));
+			return -1;
+		}
+	}
+	else
+	{
+		char	   *ciphers,
+				   *c;
+
+		char	   *sep = ":;, ";
+		PRUint16	ciphercode;
+		const		PRUint16 *nss_ciphers;
+
+		/*
+		 * If the user has specified a set of preferred cipher suites we start
+		 * by turning off all the existing suites to avoid the risk of down-
+		 * grades to a weaker cipher than expected.
+		 */
+		nss_ciphers = SSL_GetImplementedCiphers();
+		for (int i = 0; i < SSL_GetNumImplementedCiphers(); i++)
+			SSL_CipherPrefSet(model, nss_ciphers[i], PR_FALSE);
+
+		ciphers = pstrdup(SSLCipherSuites);
+
+		for (c = strtok(ciphers, sep); c; c = strtok(NULL, sep))
+		{
+			ciphercode = pg_find_cipher(c);
+			if (ciphercode != INVALID_CIPHER)
+			{
+				status = SSL_CipherPrefSet(model, ciphercode, PR_TRUE);
+				if (status != SECSuccess)
+				{
+					ereport(COMMERROR,
+							(errmsg("invalid cipher-suite specified: %s", c)));
+					return -1;
+				}
+			}
+		}
+
+		pfree(ciphers);
+	}
+
+	if (SSL_VersionRangeSet(model, &desired_sslver) != SECSuccess)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to set requested SSL protocol version range")));
+		return -1;
+	}
+
+	/*
+	 * Set up the custom IO layer.
+	 */
+	layer = init_iolayer(port);
+	if (!layer)
+		return -1;
+
+	if (PR_PushIOLayer(pr_fd, PR_TOP_IO_LAYER, layer) != PR_SUCCESS)
+	{
+		PR_Close(layer);
+		ereport(COMMERROR,
+				(errmsg("unable to push IO layer")));
+		return -1;
+	}
+
+	server_cert = PK11_FindCertFromNickname(ssl_cert_file, (void *) port);
+	if (!server_cert)
+	{
+		if (dummy_ssl_passwd_cb_called)
+		{
+			ereport(COMMERROR,
+					(errmsg("unable to load certificate for \"%s\": %s",
+							ssl_cert_file, pg_SSLerrmessage(PR_GetError())),
+					 errhint("The certificate requires a password.")));
+			return -1;
+		}
+		else
+		{
+			ereport(COMMERROR,
+					(errmsg("unable to find certificate for \"%s\": %s",
+							ssl_cert_file, pg_SSLerrmessage(PR_GetError()))));
+			return -1;
+		}
+	}
+
+	private_key = PK11_FindKeyByAnyCert(server_cert, (void *) port);
+	if (!private_key)
+	{
+		if (dummy_ssl_passwd_cb_called)
+		{
+			ereport(COMMERROR,
+					(errmsg("unable to load private key for \"%s\": %s",
+							ssl_cert_file, pg_SSLerrmessage(PR_GetError())),
+					 errhint("The private key requires a password.")));
+			return -1;
+		}
+		else
+		{
+			ereport(COMMERROR,
+					(errmsg("unable to find private key for \"%s\": %s",
+							ssl_cert_file, pg_SSLerrmessage(PR_GetError()))));
+			return -1;
+		}
+	}
+
+	/*
+	 * NSS doesn't use CRL files on disk, so we use the ssl_crl_file guc to
+	 * contain the CRL nickname for the current server certificate in the NSS
+	 * certificate database. The main difference from the OpenSSL backend is
+	 * that NSS will use the CRL regardless, but being able to make sure the
+	 * CRL is loaded seems like a good feature.
+	 */
+	if (ssl_crl_file[0])
+	{
+		SECITEM_CopyItem(NULL, &crlname, &server_cert->derSubject);
+		crl = SEC_FindCrlByName(CERT_GetDefaultCertDB(), &crlname, SEC_CRL_TYPE);
+		if (!crl)
+		{
+			ereport(COMMERROR,
+					(errmsg("specified CRL not found in database")));
+			return -1;
+		}
+		SEC_DestroyCrl(crl);
+	}
+
+	/*
+	 * Finally we must configure the socket for being a server by setting the
+	 * certificate and key. The NULL parameter is an SSLExtraServerCertData
+	 * pointer with the final parameter being the size of the extra server
+	 * cert data structure pointed to. This is typically only used for
+	 * credential delegation.
+	 */
+	status = SSL_ConfigServerCert(model, server_cert, private_key, NULL, 0);
+	if (status != SECSuccess)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to configure server for TLS server connections: %s",
+						pg_SSLerrmessage(PR_GetError()))));
+		return -1;
+	}
+
+	ssl_loaded_verify_locations = true;
+
+	/*
+	 * At this point, we no longer have use for the certificate and private
+	 * key as they have been copied into the context by NSS. Destroy our
+	 * copies explicitly to clean out the memory as best we can.
+	 */
+	CERT_DestroyCertificate(server_cert);
+	SECKEY_DestroyPrivateKey(private_key);
+
+	status = SSL_AuthCertificateHook(model, pg_cert_auth_handler, (void *) port);
+	if (status != SECSuccess)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to install authcert hook: %s",
+						pg_SSLerrmessage(PR_GetError()))));
+		return -1;
+	}
+	SSL_BadCertHook(model, pg_bad_cert_handler, (void *) port);
+	SSL_OptionSet(model, SSL_REQUEST_CERTIFICATE, PR_TRUE);
+	SSL_OptionSet(model, SSL_REQUIRE_CERTIFICATE, PR_FALSE);
+
+	port->pr_fd = SSL_ImportFD(model, pr_fd);
+	if (!port->pr_fd)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to initialize")));
+		return -1;
+	}
+
+	PR_Close(model);
+
+	/*
+	 * Force a handshake on the next I/O request, the second parameter means
+	 * that we are a server, PR_FALSE would indicate being a client. NSPR
+	 * requires us to call SSL_ResetHandshake since we imported an already
+	 * established socket.
+	 */
+	status = SSL_ResetHandshake(port->pr_fd, PR_TRUE);
+	if (status != SECSuccess)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to initiate handshake: %s",
+						pg_SSLerrmessage(PR_GetError()))));
+		return -1;
+	}
+	status = SSL_ForceHandshake(port->pr_fd);
+	if (status != SECSuccess)
+	{
+		ereport(COMMERROR,
+				(errmsg("unable to handshake: %s",
+						pg_SSLerrmessage(PR_GetError()))));
+		return -1;
+	}
+
+	port->ssl_in_use = true;
+	return 0;
+}
+
+ssize_t
+be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
+{
+	ssize_t		n_read;
+	PRErrorCode err;
+
+	n_read = PR_Read(port->pr_fd, ptr, len);
+
+	if (n_read < 0)
+	{
+		err = PR_GetError();
+
+		if (err == PR_WOULD_BLOCK_ERROR)
+		{
+			*waitfor = WL_SOCKET_READABLE;
+			errno = EWOULDBLOCK;
+		}
+		else
+			errno = ECONNRESET;
+	}
+
+	return n_read;
+}
+
+ssize_t
+be_tls_write(Port *port, void *ptr, size_t len, int *waitfor)
+{
+	ssize_t		n_write;
+	PRErrorCode err;
+	PRIntn		flags = 0;
+
+	/*
+	 * The flags parameter to PR_Send is no longer used and is, according to
+	 * the documentation, required to be zero.
+	 */
+	n_write = PR_Send(port->pr_fd, ptr, len, flags, PR_INTERVAL_NO_WAIT);
+
+	if (n_write < 0)
+	{
+		err = PR_GetError();
+
+		if (err == PR_WOULD_BLOCK_ERROR)
+		{
+			*waitfor = WL_SOCKET_WRITEABLE;
+			errno = EWOULDBLOCK;
+		}
+		else
+			errno = ECONNRESET;
+	}
+
+	return n_write;
+}
+
+void
+be_tls_close(Port *port)
+{
+	if (!port)
+		return;
+
+	if (port->peer_cn)
+	{
+		SSL_InvalidateSession(port->pr_fd);
+		pfree(port->peer_cn);
+		port->peer_cn = NULL;
+	}
+
+	PR_Close(port->pr_fd);
+	port->pr_fd = NULL;
+	port->ssl_in_use = false;
+
+	if (nss_context)
+	{
+		NSS_ShutdownContext(nss_context);
+		nss_context = NULL;
+	}
+}
+
+void
+be_tls_destroy(void)
+{
+	/*
+	 * It reads a bit odd to clear a session cache when we are destroying the
+	 * context altogether, but if the session cache isn't cleared before
+	 * shutting down the context it will fail with SEC_ERROR_BUSY.
+	 */
+	SSL_ClearSessionCache();
+}
+
+int
+be_tls_get_cipher_bits(Port *port)
+{
+	SECStatus	status;
+	SSLChannelInfo channel;
+	SSLCipherSuiteInfo suite;
+
+	status = SSL_GetChannelInfo(port->pr_fd, &channel, sizeof(channel));
+	if (status != SECSuccess)
+		goto error;
+
+	status = SSL_GetCipherSuiteInfo(channel.cipherSuite, &suite, sizeof(suite));
+	if (status != SECSuccess)
+		goto error;
+
+	return suite.effectiveKeyBits;
+
+error:
+	ereport(WARNING,
+			(errmsg("unable to extract TLS session information: %s",
+					pg_SSLerrmessage(PR_GetError()))));
+	return 0;
+}
+
+/*
+ * be_tls_get_compression
+ *
+ * NSS disabled support for TLS compression in version 3.33 and removed the
+ * code in a subsequent release. The API for retrieving information about
+ * compression as well as enabling it is kept for backwards compatibility, but
+ * we don't need to consult it since it was only available for SSLv3 which we
+ * don't support.
+ *
+ * https://bugzilla.mozilla.org/show_bug.cgi?id=1409587
+ */
+bool
+be_tls_get_compression(Port *port)
+{
+	return false;
+}
+
+/*
+ * be_tls_get_version
+ *
+ * Returns the protocol version used for the current connection, or NULL in
+ * case of errors.
+ */
+const char *
+be_tls_get_version(Port *port)
+{
+	SECStatus	status;
+	SSLChannelInfo channel;
+
+	status = SSL_GetChannelInfo(port->pr_fd, &channel, sizeof(channel));
+	if (status != SECSuccess)
+	{
+		ereport(WARNING,
+				(errmsg("unable to extract TLS session information: %s",
+						pg_SSLerrmessage(PR_GetError()))));
+		return NULL;
+	}
+
+	return ssl_protocol_version_to_string(channel.protocolVersion);
+}
+
+const char *
+be_tls_get_cipher(Port *port)
+{
+	SECStatus	status;
+	SSLChannelInfo channel;
+	SSLCipherSuiteInfo suite;
+
+	status = SSL_GetChannelInfo(port->pr_fd, &channel, sizeof(channel));
+	if (status != SECSuccess)
+		goto error;
+
+	status = SSL_GetCipherSuiteInfo(channel.cipherSuite, &suite, sizeof(suite));
+	if (status != SECSuccess)
+		goto error;
+
+	return suite.cipherSuiteName;
+
+error:
+	ereport(WARNING,
+			(errmsg("unable to extract TLS session information: %s",
+					pg_SSLerrmessage(PR_GetError()))));
+	return NULL;
+}
+
+void
+be_tls_get_peer_subject_name(Port *port, char *ptr, size_t len)
+{
+	CERTCertificate *certificate;
+
+	certificate = SSL_PeerCertificate(port->pr_fd);
+	if (certificate)
+		strlcpy(ptr, CERT_NameToAscii(&certificate->subject), len);
+	else
+		ptr[0] = '\0';
+}
+
+void
+be_tls_get_peer_issuer_name(Port *port, char *ptr, size_t len)
+{
+	CERTCertificate *certificate;
+
+	certificate = SSL_PeerCertificate(port->pr_fd);
+	if (certificate)
+		strlcpy(ptr, CERT_NameToAscii(&certificate->issuer), len);
+	else
+		ptr[0] = '\0';
+}
+
+void
+be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
+{
+	CERTCertificate *certificate;
+
+	certificate = SSL_PeerCertificate(port->pr_fd);
+	if (certificate)
+		snprintf(ptr, len, "%li", DER_GetInteger(&(certificate->serialNumber)));
+	else
+		ptr[0] = '\0';
+}
+
+char *
+be_tls_get_certificate_hash(Port *port, size_t *len)
+{
+	CERTCertificate *certificate;
+	SECOidTag	signature_alg;
+	SECOidTag	digest_alg;
+	int			digest_len;
+	const NSSSignatureAlgorithms *candidate;
+	SECStatus	status;
+	PLArenaPool *arena = NULL;
+	SECItem		digest;
+	char	   *ret;
+
+	*len = 0;
+	certificate = SSL_LocalCertificate(port->pr_fd);
+	if (!certificate)
+		return NULL;
+
+	signature_alg = SECOID_GetAlgorithmTag(&certificate->signature);
+
+	candidate = NSS_SCRAMDigestAlgorithm;
+	while (candidate->signature)
+	{
+		if (signature_alg == candidate->signature)
+		{
+			digest_alg = candidate->hash;
+			digest_len = candidate->len;
+			break;
+		}
+
+		candidate++;
+	}
+
+	if (!candidate->signature)
+		elog(ERROR, "could not find digest for OID '%s'",
+			 SECOID_FindOIDTagDescription(signature_alg));
+
+	arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
+	digest.data = PORT_ArenaZAlloc(arena, sizeof(unsigned char) * digest_len);
+	digest.len = digest_len;
+
+	status = PK11_HashBuf(digest_alg, digest.data,
+						  certificate->derCert.data,
+						  certificate->derCert.len);
+
+	if (status != SECSuccess)
+	{
+		PORT_FreeArena(arena, PR_TRUE);
+		return NULL;
+	}
+
+	ret = palloc(digest.len);
+	memcpy(ret, digest.data, digest.len);
+	*len = digest_len;
+	PORT_FreeArena(arena, PR_TRUE);
+
+	return ret;
+}
+
+/* ------------------------------------------------------------ */
+/*						Internal functions						*/
+/* ------------------------------------------------------------ */
+
+/*
+ * default_nss_tls_init
+ *
+ * The default TLS init hook function which users can override for installing
+ * their own passphrase callbacks and similar actions. In case no callback has
+ * been configured, or the callback isn't reload capable during a server
+ * reload, the dummy callback will be installed.
+ *
+ * The private data for the callback is set differently depending on how it's
+ * invoked. For calls which may invoke the callback deeper in the callstack
+ * the private data is set with SSL_SetPKCS11PinArg. When the call is directly
+ * invoking the callback, like PK11_FindCertFromNickname, then the private
+ * data is passed as a parameter. Setting the data with SSL_SetPKCS11PinArg is
+ * thus not required but good practice.
+ *
+ * NSS doesn't provide a default callback like OpenSSL does, but a callback is
+ * required to be set.  The password callback can be installed at any time, but
+ * setting the private data with SSL_SetPKCS11PinArg requires a PR Filedesc.
+ */
+static void
+default_nss_tls_init(bool isServerStart)
+{
+	/*
+	 * No user-defined callback has been configured, install the dummy call-
+	 * back since we must set something.
+	 */
+	if (!ssl_passphrase_command[0])
+		PK11_SetPasswordFunc(dummy_ssl_passphrase_cb);
+	else
+	{
+		/*
+		 * There is a user-defined callback, set it unless we are in a restart
+		 * and cannot handle restarts due to an interactive callback.
+		 */
+		if (isServerStart)
+			PK11_SetPasswordFunc(external_ssl_passphrase_cb);
+		else
+		{
+			if (ssl_passphrase_command_supports_reload)
+				PK11_SetPasswordFunc(external_ssl_passphrase_cb);
+			else
+				PK11_SetPasswordFunc(dummy_ssl_passphrase_cb);
+		}
+	}
+}
+
+/*
+ * external_ssl_passphrase_cb
+ *
+ * Runs the callback configured by ssl_passphrase_command and returns the
+ * captured password back to NSS.
+ */
+static char *
+external_ssl_passphrase_cb(PK11SlotInfo *slot, PRBool retry, void *arg)
+{
+	/*
+	 * NSS use a hardcoded 256 byte buffer for reading the password so set the
+	 * same limit for our callback buffer.
+	 */
+	char		buf[256];
+	int			len;
+	char	   *password = NULL;
+	char	   *prompt;
+
+	/*
+	 * Since there is no password callback in NSS when the server starts up,
+	 * it makes little sense to create an interactive callback. Thus, if this
+	 * is a retry attempt then give up immediately.
+	 */
+	if (retry)
+		return NULL;
+
+	/*
+	 * Construct the same prompt that NSS uses internally even though it is
+	 * unlikely to serve much purpose, but we must set a prompt so we might as
+	 * well do it right.
+	 */
+	prompt = psprintf("Enter Password or Pin for \"%s\":",
+					  PK11_GetTokenName(slot));
+
+	len = run_ssl_passphrase_command(prompt, ssl_is_server_start, buf, sizeof(buf));
+	pfree(prompt);
+
+	if (!len)
+		return NULL;
+
+	/*
+	 * At least one byte with password content was returned, and NSS requires
+	 * that we return it allocated in NSS controlled memory. If we fail to
+	 * allocate then abort without passing back NULL and bubble up the error
+	 * on the PG side.
+	 */
+	password = (char *) PR_Malloc(len + 1);
+	if (!password)
+	{
+		explicit_bzero(buf, sizeof(buf));
+		ereport(ERROR,
+				(errcode(ERRCODE_OUT_OF_MEMORY),
+				 errmsg("out of memory")));
+	}
+	strlcpy(password, buf, sizeof(password));
+	explicit_bzero(buf, sizeof(buf));
+
+	return password;
+}
+
+/*
+ * dummy_ssl_passphrase_cb
+ *
+ * Return unsuccessful if we are asked to provide the passphrase for a cert or
+ * key, without having a passphrase callback installed.
+ */
+static char *
+dummy_ssl_passphrase_cb(PK11SlotInfo *slot, PRBool retry, void *arg)
+{
+	dummy_ssl_passwd_cb_called = true;
+	return NULL;
+}
+
+static SECStatus
+pg_bad_cert_handler(void *arg, PRFileDesc * fd)
+{
+	Port	   *port = (Port *) arg;
+
+	port->peer_cert_valid = false;
+	return SECFailure;
+}
+
+/*
+ * Returns the Subject Common Name for the given certificate as a raw char
+ * buffer (that is, without any form of escaping for unprintable characters or
+ * embedded nulls), with the length of the buffer returned in the len parameter.
+ * The buffer is allocated in the TopMemoryContext and is given a NULL
+ * terminator so that callers are safe to call strlen() on it.
+ *
+ * This is used instead of CERT_GetCommonName(), which always performs quoting
+ * and/or escaping. NSS doesn't appear to give us a way to easily unescape the
+ * result, and we need to store the raw CN into port->peer_cn for compatibility
+ * with the OpenSSL implementation.
+ */
+static char *
+raw_subject_common_name(CERTCertificate *cert, unsigned int *len)
+{
+	CERTName	subject = cert->subject;
+	CERTRDN	  **rdn;
+
+	for (rdn = subject.rdns; *rdn; rdn++)
+	{
+		CERTAVA	  **ava;
+
+		for (ava = (*rdn)->avas; *ava; ava++)
+		{
+			SECItem	   *buf;
+			char	   *cn;
+
+			if (CERT_GetAVATag(*ava) != SEC_OID_AVA_COMMON_NAME)
+				continue;
+
+			/* Found a CN. Decode and copy it into a newly allocated buffer. */
+			buf = CERT_DecodeAVAValue(&(*ava)->value);
+			if (!buf)
+			{
+				/*
+				 * This failure case is difficult to test. (Since this code runs
+				 * after certificate authentication has otherwise succeeded,
+				 * you'd need to convince a CA implementation to sign a
+				 * corrupted certificate in order to get here.)
+				 *
+				 * Follow the behavior of CERT_GetCommonName() in this case and
+				 * simply return NULL, as if a Common Name had not been found.
+				 */
+				goto fail;
+			}
+
+			cn = MemoryContextAlloc(TopMemoryContext, buf->len + 1);
+			memcpy(cn, buf->data, buf->len);
+			cn[buf->len] = '\0';
+
+			*len = buf->len;
+
+			SECITEM_FreeItem(buf, PR_TRUE);
+			return cn;
+		}
+	}
+
+fail:
+	/* Not found. */
+	*len = 0;
+	return NULL;
+}
+
+static SECStatus
+pg_cert_auth_handler(void *arg, PRFileDesc * fd, PRBool checksig, PRBool isServer)
+{
+	SECStatus	status;
+	Port	   *port = (Port *) arg;
+	CERTCertificate *cert;
+	char	   *peer_cn;
+	unsigned int len;
+
+	status = SSL_AuthCertificate(CERT_GetDefaultCertDB(), port->pr_fd, checksig, PR_TRUE);
+	if (status != SECSuccess)
+		return status;
+
+	port->peer_cn = NULL;
+	port->peer_cert_valid = false;
+
+	cert = SSL_PeerCertificate(port->pr_fd);
+	if (!cert)
+	{
+		/* Shouldn't be possible; why did we get a client cert callback? */
+		Assert(cert != NULL);
+
+		PR_SetError(SEC_ERROR_LIBRARY_FAILURE, 0);
+		return SECFailure;
+	}
+
+	peer_cn = raw_subject_common_name(cert, &len);
+	if (!peer_cn)
+	{
+		/* No Common Name, but the certificate otherwise checks out. */
+		port->peer_cert_valid = true;
+
+		status = SECSuccess;
+		goto cleanup;
+	}
+
+	/*
+	 * Reject embedded NULLs in certificate common name to prevent attacks like
+	 * CVE-2009-4034.
+	 */
+	if (len != strlen(peer_cn))
+	{
+		ereport(COMMERROR,
+				(errcode(ERRCODE_PROTOCOL_VIOLATION),
+				 errmsg("SSL certificate's common name contains embedded null")));
+
+		pfree(peer_cn);
+		PR_SetError(SEC_ERROR_CERT_NOT_VALID, 0);
+
+		status = SECFailure;
+		goto cleanup;
+	}
+
+	port->peer_cn = peer_cn;
+	port->peer_cert_valid = true;
+
+	status = SECSuccess;
+
+cleanup:
+	CERT_DestroyCertificate(cert);
+	return status;
+}
+
+static PRInt32
+pg_ssl_read(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
+			PRIntervalTime timeout)
+{
+	PRRecvFN	read_fn;
+	PRInt32		n_read;
+
+	read_fn = fd->lower->methods->recv;
+	n_read = read_fn(fd->lower, buf, amount, flags, timeout);
+
+	return n_read;
+}
+
+static PRInt32
+pg_ssl_write(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
+			 PRIntervalTime timeout)
+{
+	PRSendFN	send_fn;
+	PRInt32		n_write;
+
+	send_fn = fd->lower->methods->send;
+	n_write = send_fn(fd->lower, buf, amount, flags, timeout);
+
+	return n_write;
+}
+
+static PRStatus
+pg_ssl_close(PRFileDesc *fd)
+{
+	/*
+	 * Disconnect our private Port from the fd before closing out the stack.
+	 * (Debug builds of NSPR will assert if we do not.)
+	 */
+	fd->secret = NULL;
+	return PR_GetDefaultIOMethods()->close(fd);
+}
+
+static PRFileDesc *
+init_iolayer(Port *port)
+{
+	const		PRIOMethods *default_methods;
+	PRFileDesc *layer;
+
+	/*
+	 * Start by initializing our layer with all the default methods so that we
+	 * can selectively override the ones we want while still ensuring that we
+	 * have a complete layer specification.
+	 */
+	default_methods = PR_GetDefaultIOMethods();
+	memcpy(&pr_iomethods, default_methods, sizeof(PRIOMethods));
+
+	pr_iomethods.recv = pg_ssl_read;
+	pr_iomethods.send = pg_ssl_write;
+	pr_iomethods.close = pg_ssl_close;
+
+	/*
+	 * Each IO layer must be identified by a unique name, where uniqueness is
+	 * per connection. Each connection in a postgres cluster can generate the
+	 * identity from the same string as they will create their IO layers on
+	 * different sockets. Only one layer per socket can have the same name.
+	 */
+	pr_id = PR_GetUniqueIdentity("PostgreSQL Server");
+	if (pr_id == PR_INVALID_IO_LAYER)
+	{
+		ereport(ERROR,
+				(errmsg("out of memory when setting up TLS connection")));
+		return NULL;
+	}
+
+	/*
+	 * Create the actual IO layer as a stub such that it can be pushed onto
+	 * the layer stack. The step via a stub is required as we define custom
+	 * callbacks.
+	 */
+	layer = PR_CreateIOLayerStub(pr_id, &pr_iomethods);
+	if (!layer)
+	{
+		ereport(ERROR,
+				(errmsg("unable to create NSS I/O layer")));
+		return NULL;
+	}
+
+	/* Store the Port as private data available in callbacks */
+	layer->secret = (void *) port;
+
+	return layer;
+}
+
+static char *
+ssl_protocol_version_to_string(int v)
+{
+	switch (v)
+	{
+			/* SSL v2 and v3 are not supported */
+		case SSL_LIBRARY_VERSION_2:
+		case SSL_LIBRARY_VERSION_3_0:
+			Assert(false);
+			break;
+
+		case SSL_LIBRARY_VERSION_TLS_1_0:
+			return pstrdup("TLSv1.0");
+		case SSL_LIBRARY_VERSION_TLS_1_1:
+			return pstrdup("TLSv1.1");
+		case SSL_LIBRARY_VERSION_TLS_1_2:
+			return pstrdup("TLSv1.2");
+		case SSL_LIBRARY_VERSION_TLS_1_3:
+			return pstrdup("TLSv1.3");
+	}
+
+	return pstrdup("unknown");
+}
+
+
+/*
+ * ssl_protocol_version_to_nss
+ *			Translate PostgreSQL TLS version to NSS version
+ *
+ * Returns zero in case the requested TLS version is undefined (PG_ANY) and
+ * should be set by the caller, or -1 on failure.
+ */
+static uint16
+ssl_protocol_version_to_nss(int v, const char *guc_name)
+{
+	switch (v)
+	{
+			/*
+			 * There is no SSL_LIBRARY_ macro defined in NSS with the value
+			 * zero, so we use this to signal the caller that the highest
+			 * useful version should be set on the connection.
+			 */
+		case PG_TLS_ANY:
+			return 0;
+
+			/*
+			 * No guard is required here as there are no versions of NSS
+			 * without support for TLS1.
+			 */
+		case PG_TLS1_VERSION:
+			return SSL_LIBRARY_VERSION_TLS_1_0;
+		case PG_TLS1_1_VERSION:
+#ifdef SSL_LIBRARY_VERSION_TLS_1_1
+			return SSL_LIBRARY_VERSION_TLS_1_1;
+#else
+			break;
+#endif
+		case PG_TLS1_2_VERSION:
+#ifdef SSL_LIBRARY_VERSION_TLS_1_2
+			return SSL_LIBRARY_VERSION_TLS_1_2;
+#else
+			break;
+#endif
+		case PG_TLS1_3_VERSION:
+#ifdef SSL_LIBRARY_VERSION_TLS_1_3
+			return SSL_LIBRARY_VERSION_TLS_1_3;
+#else
+			break;
+#endif
+		default:
+			break;
+	}
+
+	return -1;
+}
+
+/*
+ * pg_SSLerrmessage
+ *		Create and return a human readable error message given
+ *		the specified error code
+ *
+ * PR_ErrorToName only converts the enum identifier of the error to string,
+ * but that can be quite useful for debugging (and in case PR_ErrorToString is
+ * unable to render a message then we at least have something).
+ */
+static char *
+pg_SSLerrmessage(PRErrorCode errcode)
+{
+	return psprintf("%s (%s)",
+					PR_ErrorToString(errcode, PR_LANGUAGE_I_DEFAULT),
+					PR_ErrorToName(errcode));
+}
diff --git a/src/backend/libpq/be-secure.c b/src/backend/libpq/be-secure.c
index 4cf139a223..5e0c27c134 100644
--- a/src/backend/libpq/be-secure.c
+++ b/src/backend/libpq/be-secure.c
@@ -49,6 +49,9 @@ bool		ssl_passphrase_command_supports_reload;
 #ifdef USE_SSL
 bool		ssl_loaded_verify_locations = false;
 #endif
+#ifdef USE_NSS
+char	   *ssl_database;
+#endif
 
 /* GUC variable controlling SSL cipher list */
 char	   *SSLCipherSuites = NULL;
diff --git a/src/backend/libpq/hba.c b/src/backend/libpq/hba.c
index 371dccb852..12b105bbd1 100644
--- a/src/backend/libpq/hba.c
+++ b/src/backend/libpq/hba.c
@@ -1041,7 +1041,7 @@ parse_hba_line(TokenizedLine *tok_line, int elevel)
 			ereport(elevel,
 					(errcode(ERRCODE_CONFIG_FILE_ERROR),
 					 errmsg("hostssl record cannot match because SSL is not supported by this build"),
-					 errhint("Compile with --with-openssl to use SSL connections."),
+					 errhint("Compile with --with-openssl or --with-nss to use SSL connections."),
 					 errcontext("line %d of configuration file \"%s\"",
 								line_num, HbaFileName)));
 			*err_msg = "hostssl record cannot match because SSL is not supported by this build";
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index 17579eeaca..0095a9980e 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -4308,7 +4308,11 @@ static struct config_string ConfigureNamesString[] =
 		},
 		&ssl_library,
 #ifdef USE_SSL
+#if defined(USE_OPENSSL)
 		"OpenSSL",
+#elif defined(USE_NSS)
+		"NSS",
+#endif
 #else
 		"",
 #endif
@@ -4366,6 +4370,18 @@ static struct config_string ConfigureNamesString[] =
 		check_canonical_path, assign_pgstat_temp_directory, NULL
 	},
 
+#ifdef USE_NSS
+	{
+		{"ssl_database", PGC_SIGHUP, CONN_AUTH_SSL,
+			gettext_noop("Location of the NSS certificate database."),
+			NULL
+		},
+		&ssl_database,
+		"",
+		NULL, NULL, NULL
+	},
+#endif
+
 	{
 		{"synchronous_standby_names", PGC_SIGHUP, REPLICATION_PRIMARY,
 			gettext_noop("Number of synchronous standbys and list of names of potential synchronous ones."),
@@ -4394,8 +4410,10 @@ static struct config_string ConfigureNamesString[] =
 			GUC_SUPERUSER_ONLY
 		},
 		&SSLCipherSuites,
-#ifdef USE_OPENSSL
+#if defined(USE_OPENSSL)
 		"HIGH:MEDIUM:+3DES:!aNULL",
+#elif defined (USE_NSS)
+		"",
 #else
 		"none",
 #endif
diff --git a/src/common/Makefile b/src/common/Makefile
index 93eb27a2aa..7a4b3dad5d 100644
--- a/src/common/Makefile
+++ b/src/common/Makefile
@@ -80,7 +80,7 @@ OBJS_COMMON = \
 	wait_error.o \
 	wchar.o
 
-ifeq ($(with_openssl),yes)
+ifeq ($(with_ssl),openssl)
 OBJS_COMMON += \
 	protocol_openssl.o \
 	cryptohash_openssl.o
diff --git a/src/include/common/pg_nss.h b/src/include/common/pg_nss.h
new file mode 100644
index 0000000000..008fee85f1
--- /dev/null
+++ b/src/include/common/pg_nss.h
@@ -0,0 +1,175 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_nss.h
+ *	  Support for NSS as a TLS backend
+ *
+ * These definitions are used by both frontend and backend code.
+ *
+ * Copyright (c) 2020, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ *        src/include/common/pg_nss.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_NSS_H
+#define PG_NSS_H
+
+#ifdef USE_NSS
+#define NO_NSPR_10_SUPPORT
+#include <nss/hasht.h>
+#include <nss/secoidt.h>
+#include <nss/sslproto.h>
+
+PRUint16	pg_find_cipher(char *name);
+
+typedef struct
+{
+	SECOidTag	signature;
+	SECOidTag	hash;
+	int			len;
+}			NSSSignatureAlgorithms;
+
+typedef struct
+{
+	const char *name;
+	PRUint16	number;
+}			NSSCiphers;
+
+#define INVALID_CIPHER	0xFFFF
+
+static const NSSSignatureAlgorithms NSS_SCRAMDigestAlgorithm[] = {
+
+	{SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION, SEC_OID_SHA256, SHA256_LENGTH},
+	{SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION, SEC_OID_SHA256, SHA256_LENGTH},
+	{SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE, SEC_OID_SHA256, SHA256_LENGTH},
+	{SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE, SEC_OID_SHA256, SHA256_LENGTH},
+	{SEC_OID_PKCS5_PBE_WITH_MD5_AND_DES_CBC, SEC_OID_SHA256, SHA256_LENGTH},
+
+	{SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE, SEC_OID_SHA224, SHA224_LENGTH},
+	{SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION, SEC_OID_SHA224, SHA224_LENGTH},
+	{SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST, SEC_OID_SHA224, SHA224_LENGTH},
+
+	{SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE, SEC_OID_SHA256, SHA256_LENGTH},
+	{SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION, SEC_OID_SHA256, SHA256_LENGTH},
+	{SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST, SEC_OID_SHA256, SHA256_LENGTH},
+
+	{SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE, SEC_OID_SHA384, SHA384_LENGTH},
+	{SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION, SEC_OID_SHA384, SHA384_LENGTH},
+
+	{SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE, SEC_OID_SHA512, SHA512_LENGTH},
+	{SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION, SEC_OID_SHA512, SHA512_LENGTH},
+
+	{0, 0}
+};
+
+/*
+ * This list is a partial copy of the ciphers in NSS files lib/ssl/sslproto.h
+ * in order to provide a human readable version of the ciphers. It would be
+ * nice to not have to have this, but NSS doesn't provide any API addressing
+ * the ciphers by name. TODO: do we want more of the ciphers, or perhaps less?
+ */
+static const NSSCiphers NSS_CipherList[] = {
+
+	{"TLS_NULL_WITH_NULL_NULL", TLS_NULL_WITH_NULL_NULL},
+
+	{"TLS_RSA_WITH_NULL_MD5", TLS_RSA_WITH_NULL_MD5},
+	{"TLS_RSA_WITH_NULL_SHA", TLS_RSA_WITH_NULL_SHA},
+	{"TLS_RSA_WITH_RC4_128_MD5", TLS_RSA_WITH_RC4_128_MD5},
+	{"TLS_RSA_WITH_RC4_128_SHA", TLS_RSA_WITH_RC4_128_SHA},
+	{"TLS_RSA_WITH_IDEA_CBC_SHA", TLS_RSA_WITH_IDEA_CBC_SHA},
+	{"TLS_RSA_WITH_DES_CBC_SHA", TLS_RSA_WITH_DES_CBC_SHA},
+	{"TLS_RSA_WITH_3DES_EDE_CBC_SHA", TLS_RSA_WITH_3DES_EDE_CBC_SHA},
+
+	{"TLS_DH_DSS_WITH_DES_CBC_SHA", TLS_DH_DSS_WITH_DES_CBC_SHA},
+	{"TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA", TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA},
+	{"TLS_DH_RSA_WITH_DES_CBC_SHA", TLS_DH_RSA_WITH_DES_CBC_SHA},
+	{"TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA", TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA},
+
+	{"TLS_DHE_DSS_WITH_DES_CBC_SHA", TLS_DHE_DSS_WITH_DES_CBC_SHA},
+	{"TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA},
+	{"TLS_DHE_RSA_WITH_DES_CBC_SHA", TLS_DHE_RSA_WITH_DES_CBC_SHA},
+	{"TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA},
+
+	{"TLS_DH_anon_WITH_RC4_128_MD5", TLS_DH_anon_WITH_RC4_128_MD5},
+	{"TLS_DH_anon_WITH_DES_CBC_SHA", TLS_DH_anon_WITH_DES_CBC_SHA},
+	{"TLS_DH_anon_WITH_3DES_EDE_CBC_SHA", TLS_DH_anon_WITH_3DES_EDE_CBC_SHA},
+
+	{"TLS_RSA_WITH_AES_128_CBC_SHA", TLS_RSA_WITH_AES_128_CBC_SHA},
+	{"TLS_DH_DSS_WITH_AES_128_CBC_SHA", TLS_DH_DSS_WITH_AES_128_CBC_SHA},
+	{"TLS_DH_RSA_WITH_AES_128_CBC_SHA", TLS_DH_RSA_WITH_AES_128_CBC_SHA},
+	{"TLS_DHE_DSS_WITH_AES_128_CBC_SHA", TLS_DHE_DSS_WITH_AES_128_CBC_SHA},
+	{"TLS_DHE_RSA_WITH_AES_128_CBC_SHA", TLS_DHE_RSA_WITH_AES_128_CBC_SHA},
+	{"TLS_DH_anon_WITH_AES_128_CBC_SHA", TLS_DH_anon_WITH_AES_128_CBC_SHA},
+
+	{"TLS_RSA_WITH_AES_256_CBC_SHA", TLS_RSA_WITH_AES_256_CBC_SHA},
+	{"TLS_DH_DSS_WITH_AES_256_CBC_SHA", TLS_DH_DSS_WITH_AES_256_CBC_SHA},
+	{"TLS_DH_RSA_WITH_AES_256_CBC_SHA", TLS_DH_RSA_WITH_AES_256_CBC_SHA},
+	{"TLS_DHE_DSS_WITH_AES_256_CBC_SHA", TLS_DHE_DSS_WITH_AES_256_CBC_SHA},
+	{"TLS_DHE_RSA_WITH_AES_256_CBC_SHA", TLS_DHE_RSA_WITH_AES_256_CBC_SHA},
+	{"TLS_DH_anon_WITH_AES_256_CBC_SHA", TLS_DH_anon_WITH_AES_256_CBC_SHA},
+	{"TLS_RSA_WITH_NULL_SHA256", TLS_RSA_WITH_NULL_SHA256},
+	{"TLS_RSA_WITH_AES_128_CBC_SHA256", TLS_RSA_WITH_AES_128_CBC_SHA256},
+	{"TLS_RSA_WITH_AES_256_CBC_SHA256", TLS_RSA_WITH_AES_256_CBC_SHA256},
+
+	{"TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", TLS_DHE_DSS_WITH_AES_128_CBC_SHA256},
+	{"TLS_RSA_WITH_CAMELLIA_128_CBC_SHA", TLS_RSA_WITH_CAMELLIA_128_CBC_SHA},
+	{"TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA", TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA},
+	{"TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA", TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA},
+	{"TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA", TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA},
+	{"TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA", TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA},
+	{"TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA", TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA},
+
+	{"TLS_DHE_DSS_WITH_RC4_128_SHA", TLS_DHE_DSS_WITH_RC4_128_SHA},
+	{"TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", TLS_DHE_RSA_WITH_AES_128_CBC_SHA256},
+	{"TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", TLS_DHE_DSS_WITH_AES_256_CBC_SHA256},
+	{"TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", TLS_DHE_RSA_WITH_AES_256_CBC_SHA256},
+
+	{"TLS_RSA_WITH_CAMELLIA_256_CBC_SHA", TLS_RSA_WITH_CAMELLIA_256_CBC_SHA},
+	{"TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA", TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA},
+	{"TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA", TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA},
+	{"TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA", TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA},
+	{"TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA", TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA},
+	{"TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA", TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA},
+
+	{"TLS_RSA_WITH_SEED_CBC_SHA", TLS_RSA_WITH_SEED_CBC_SHA},
+
+	{"TLS_RSA_WITH_AES_128_GCM_SHA256", TLS_RSA_WITH_AES_128_GCM_SHA256},
+	{"TLS_RSA_WITH_AES_256_GCM_SHA384", TLS_RSA_WITH_AES_256_GCM_SHA384},
+	{"TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", TLS_DHE_RSA_WITH_AES_128_GCM_SHA256},
+	{"TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", TLS_DHE_RSA_WITH_AES_256_GCM_SHA384},
+	{"TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", TLS_DHE_DSS_WITH_AES_128_GCM_SHA256},
+	{"TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", TLS_DHE_DSS_WITH_AES_256_GCM_SHA384},
+
+	{"TLS_AES_128_GCM_SHA256", TLS_AES_128_GCM_SHA256},
+	{"TLS_AES_256_GCM_SHA384", TLS_AES_256_GCM_SHA384},
+	{"TLS_CHACHA20_POLY1305_SHA256", TLS_CHACHA20_POLY1305_SHA256},
+	{NULL, 0}
+};
+
+/*
+ * pg_find_cipher
+ *			Translate an NSS ciphername to the cipher code
+ *
+ * Searches the configured ciphers for the corresponding cipher code to the
+ * name. Search is performed case insensitive.
+ */
+PRUint16
+pg_find_cipher(char *name)
+{
+	const		NSSCiphers *cipher_list = NSS_CipherList;
+
+	while (cipher_list->name)
+	{
+		if (pg_strcasecmp(cipher_list->name, name) == 0)
+			return cipher_list->number;
+
+		cipher_list++;
+	}
+
+	return 0xFFFF;
+}
+
+#endif							/* USE_NSS */
+
+#endif							/* PG_NSS_H */
diff --git a/src/include/libpq/libpq-be.h b/src/include/libpq/libpq-be.h
index 66a8673d93..ea373a0ae0 100644
--- a/src/include/libpq/libpq-be.h
+++ b/src/include/libpq/libpq-be.h
@@ -193,13 +193,18 @@ typedef struct Port
 	bool		peer_cert_valid;
 
 	/*
-	 * OpenSSL structures. (Keep these last so that the locations of other
-	 * fields are the same whether or not you build with OpenSSL.)
+	 * SSL backend specific structures. (Keep these last so that the locations
+	 * of other fields are the same whether or not you build with SSL
+	 * enabled.)
 	 */
 #ifdef USE_OPENSSL
 	SSL		   *ssl;
 	X509	   *peer;
 #endif
+
+#ifdef USE_NSS
+	void	   *pr_fd;
+#endif
 } Port;
 
 #ifdef USE_SSL
@@ -283,7 +288,7 @@ extern void be_tls_get_peer_serial(Port *port, char *ptr, size_t len);
  * This is not supported with old versions of OpenSSL that don't have
  * the X509_get_signature_nid() function.
  */
-#if defined(USE_OPENSSL) && defined(HAVE_X509_GET_SIGNATURE_NID)
+#if defined(USE_NSS) || (defined(USE_OPENSSL) && defined(HAVE_X509_GET_SIGNATURE_NID))
 #define HAVE_BE_TLS_GET_CERTIFICATE_HASH
 extern char *be_tls_get_certificate_hash(Port *port, size_t *len);
 #endif
@@ -293,6 +298,10 @@ extern char *be_tls_get_certificate_hash(Port *port, size_t *len);
 typedef void (*openssl_tls_init_hook_typ) (SSL_CTX *context, bool isServerStart);
 extern PGDLLIMPORT openssl_tls_init_hook_typ openssl_tls_init_hook;
 #endif
+#ifdef USE_NSS
+typedef void (*nss_tls_init_hook_type) (bool isServerStart);
+extern PGDLLIMPORT nss_tls_init_hook_type nss_tls_init_hook;
+#endif
 
 #endif							/* USE_SSL */
 
diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
index a55898c85a..d2860b852f 100644
--- a/src/include/libpq/libpq.h
+++ b/src/include/libpq/libpq.h
@@ -88,6 +88,9 @@ extern PGDLLIMPORT bool ssl_passphrase_command_supports_reload;
 #ifdef USE_SSL
 extern bool ssl_loaded_verify_locations;
 #endif
+#ifdef USE_NSS
+extern char *ssl_database;
+#endif
 
 extern int	secure_initialize(bool isServerStart);
 extern bool secure_loaded_verify_locations(void);
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index f4d9f3b408..67a9f90e5e 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -905,6 +905,9 @@
 /* Define to 1 to build with PAM support. (--with-pam) */
 #undef USE_PAM
 
+/* Define to build with NSS support (--with-nss) */
+#undef USE_NSS
+
 /* Define to 1 to use software CRC-32C implementation (slicing-by-8). */
 #undef USE_SLICING_BY_8_CRC32C
 
diff --git a/src/include/pg_config_manual.h b/src/include/pg_config_manual.h
index d27c8601fa..7861b94290 100644
--- a/src/include/pg_config_manual.h
+++ b/src/include/pg_config_manual.h
@@ -176,10 +176,9 @@
 
 /*
  * USE_SSL code should be compiled only when compiling with an SSL
- * implementation.  (Currently, only OpenSSL is supported, but we might add
- * more implementations in the future.)
+ * implementation.
  */
-#ifdef USE_OPENSSL
+#if defined(USE_OPENSSL) || defined(USE_NSS)
 #define USE_SSL
 #endif
 
diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile
index c4fde3f93d..837e105ffe 100644
--- a/src/interfaces/libpq/Makefile
+++ b/src/interfaces/libpq/Makefile
@@ -45,12 +45,21 @@ OBJS = \
 	pqexpbuffer.o \
 	fe-auth.o
 
-ifeq ($(with_openssl),yes)
+ifneq ($(with_ssl),no)
+OBJS += \
+	fe-secure-common.o
+endif
+
+ifeq ($(with_ssl),openssl)
 OBJS += \
-	fe-secure-common.o \
 	fe-secure-openssl.o
 endif
 
+ifeq ($(with_ssl), nss)
+OBJS += \
+	fe-secure-nss.o
+endif
+
 ifeq ($(with_gssapi),yes)
 OBJS += \
 	fe-gssapi-common.o \
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index 2b78ed8ec3..79d3a35009 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -355,6 +355,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = {
 		"Target-Session-Attrs", "", 11, /* sizeof("read-write") = 11 */
 	offsetof(struct pg_conn, target_session_attrs)},
 
+	{"cert_database", NULL, NULL, NULL,
+		"CertificateDatabase", "", 64,
+	offsetof(struct pg_conn, cert_database)},
+
 	/* Terminating entry --- MUST BE LAST */
 	{NULL, NULL, NULL, NULL,
 	NULL, NULL, 0}
diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
new file mode 100644
index 0000000000..dca0572e67
--- /dev/null
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -0,0 +1,1112 @@
+/*-------------------------------------------------------------------------
+ *
+ * fe-secure-nss.c
+ *	  functions for supporting NSS as a TLS backend for frontend libpq
+ *
+ * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ *	  src/interfaces/libpq/fe-secure-nss.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres_fe.h"
+
+#include "libpq-fe.h"
+#include "fe-auth.h"
+#include "fe-secure-common.h"
+#include "libpq-int.h"
+#include "common/pg_nss.h"
+
+/*
+ * BITS_PER_BYTE is also defined in the NSPR header files, so we need to undef
+ * our version to avoid compiler warnings on redefinition.
+ */
+#define pg_BITS_PER_BYTE BITS_PER_BYTE
+#undef BITS_PER_BYTE
+
+/*
+ * The nspr/obsolete/protypes.h NSPR header typedefs uint64 and int64 with
+ * colliding definitions from ours, causing a much expected compiler error.
+ * Remove backwards compatibility with ancient NSPR versions to avoid this.
+ */
+#define NO_NSPR_10_SUPPORT
+#include <nspr/nspr.h>
+#include <nspr/prerror.h>
+#include <nspr/prinit.h>
+#include <nspr/prio.h>
+#include <nss/hasht.h>
+#include <nss/nss.h>
+#include <nss/ssl.h>
+#include <nss/sslproto.h>
+#include <nss/pk11func.h>
+#include <nss/secerr.h>
+#include <nss/secoidt.h>
+#include <nss/secmod.h>
+
+/*
+ * Ensure that the colliding definitions match, else throw an error. In case
+ * NSPR remove the definition in a future version (however unlikely that may
+ * be, make sure to put ours back again.
+ */
+#if defined(BITS_PER_BYTE)
+#if BITS_PER_BYTE != pg_BITS_PER_BYTE
+#error "incompatible byte widths between NSPR and PostgreSQL"
+#endif
+#else
+#define BITS_PER_BYTE pg_BITS_PER_BYTE
+#endif
+#undef pg_BITS_PER_BYTE
+
+static SECStatus pg_load_nss_module(SECMODModule * *module, const char *library, const char *name);
+static SECStatus pg_bad_cert_handler(void *arg, PRFileDesc * fd);
+static const char *pg_SSLerrmessage(PRErrorCode errcode);
+static SECStatus pg_client_auth_handler(void *arg, PRFileDesc * socket, CERTDistNames * caNames,
+										CERTCertificate * *pRetCert, SECKEYPrivateKey * *pRetKey);
+static SECStatus pg_cert_auth_handler(void *arg, PRFileDesc * fd, PRBool checksig, PRBool isServer);
+static int	ssl_protocol_version_to_nss(const char *protocol);
+static bool cert_database_has_CA(PGconn *conn);
+
+static char *PQssl_passwd_cb(PK11SlotInfo * slot, PRBool retry, void *arg);
+
+/*
+ * PR_ImportTCPSocket() is a private API, but very widely used, as it's the
+ * only way to make NSS use an already set up POSIX file descriptor rather
+ * than opening one itself. To quote the NSS documentation:
+ *
+ *		"In theory, code that uses PR_ImportTCPSocket may break when NSPR's
+ *		implementation changes. In practice, this is unlikely to happen because
+ *		NSPR's implementation has been stable for years and because of NSPR's
+ *		strong commitment to backward compatibility."
+ *
+ * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PR_ImportTCPSocket
+ *
+ * The function is declared in <private/pprio.h>, but as it is a header marked
+ * private we declare it here rather than including it.
+ */
+NSPR_API(PRFileDesc *) PR_ImportTCPSocket(int);
+
+static SECMODModule * ca_trust = NULL;
+static NSSInitContext * nss_context = NULL;
+
+/*
+ * This logic exist in NSS as well, but it's only available for when there is
+ * a database to open, and not only using the system trust store. Thus, we
+ * need to keep our own copy.
+ */
+#if defined(WIN32)
+static const char *ca_trust_name = "nssckbi.dll";
+#elif defined(__darwin__)
+static const char *ca_trust_name = "libnssckbi.dylib";
+#else
+static const char *ca_trust_name = "libnssckbi.so";
+#endif
+
+static PQsslKeyPassHook_nss_type PQsslKeyPassHook = NULL;
+
+/* ------------------------------------------------------------ */
+/*			 Procedures common to all secure sessions			*/
+/* ------------------------------------------------------------ */
+
+/*
+ * pgtls_init_library
+ *
+ * There is no direct equivalent for PQinitOpenSSL in NSS/NSPR, with PR_Init
+ * being the closest match there is. PR_Init is however already documented to
+ * not be required so simply making this a noop seems like the best option.
+ */
+void
+pgtls_init_library(bool do_ssl, int do_crypto)
+{
+	/* noop */
+}
+
+int
+pgtls_init(PGconn *conn)
+{
+	conn->ssl_in_use = false;
+	conn->has_password = false;
+
+	return 0;
+}
+
+void
+pgtls_close(PGconn *conn)
+{
+	if (nss_context)
+	{
+		NSS_ShutdownContext(nss_context);
+		nss_context = NULL;
+	}
+}
+
+PostgresPollingStatusType
+pgtls_open_client(PGconn *conn)
+{
+	SECStatus	status;
+	PRFileDesc *pr_fd;
+	PRFileDesc *model;
+	NSSInitParameters params;
+	SSLVersionRange desired_range;
+
+	/*
+	 * The NSPR documentation states that runtime initialization via PR_Init
+	 * is no longer required, as the first caller into NSPR will perform the
+	 * initialization implicitly. See be-secure-nss.c for further discussion
+	 * on PR_Init.
+	 */
+	PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
+
+	/*
+	 * NSS initialization and the use of contexts is further discussed in
+	 * be-secure-nss.c
+	 */
+	memset(&params, 0, sizeof(params));
+	params.length = sizeof(params);
+
+	if (conn->cert_database && strlen(conn->cert_database) > 0)
+	{
+		char	   *cert_database_path = psprintf("sql:%s", conn->cert_database);
+
+		nss_context = NSS_InitContext(cert_database_path, "", "", "",
+									  &params,
+									  NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
+		pfree(cert_database_path);
+
+		if (!nss_context)
+		{
+			printfPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("unable to open certificate database \"%s\": %s"),
+							  conn->cert_database,
+							  pg_SSLerrmessage(PR_GetError()));
+			return PGRES_POLLING_FAILED;
+		}
+	}
+	else
+	{
+		nss_context = NSS_InitContext("", "", "", "", &params,
+									  NSS_INIT_READONLY | NSS_INIT_NOCERTDB |
+									  NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN |
+									  NSS_INIT_NOROOTINIT | NSS_INIT_PK11RELOAD);
+		if (!nss_context)
+		{
+			printfPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("unable to create certificate database: %s"),
+							  pg_SSLerrmessage(PR_GetError()));
+			return PGRES_POLLING_FAILED;
+		}
+	}
+
+	/*
+	 * Configure cipher policy.
+	 */
+	status = NSS_SetDomesticPolicy();
+	if (status != SECSuccess)
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("unable to configure cipher policy: %s"),
+						  pg_SSLerrmessage(PR_GetError()));
+
+		return PGRES_POLLING_FAILED;
+	}
+
+	/*
+	 * If we don't have a certificate database, the system trust store is the
+	 * fallback we can use. If we fail to initialize that as well, we can
+	 * still attempt a connection as long as the sslmode isn't verify*.
+	 */
+	if (!conn->cert_database && conn->sslmode[0] == 'v')
+	{
+		status = pg_load_nss_module(&ca_trust, ca_trust_name, "\"Root Certificates\"");
+		if (status != SECSuccess)
+		{
+			printfPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("WARNING: unable to load NSS trust module \"%s\" : %s"),
+							  ca_trust_name,
+							  pg_SSLerrmessage(PR_GetError()));
+
+			return PGRES_POLLING_FAILED;
+		}
+	}
+
+
+	PK11_SetPasswordFunc(PQssl_passwd_cb);
+
+	/*
+	 * Import the already opened socket as we don't want to use NSPR functions
+	 * for opening the network socket due to how the PostgreSQL protocol works
+	 * with TLS connections. This function is not part of the NSPR public API,
+	 * see the comment at the top of the file for the rationale of still using
+	 * it.
+	 */
+	pr_fd = PR_ImportTCPSocket(conn->sock);
+	if (!pr_fd)
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("unable to attach to socket: %s"),
+						  pg_SSLerrmessage(PR_GetError()));
+		return PGRES_POLLING_FAILED;
+	}
+
+	/*
+	 * Most of the documentation available, and implementations of, NSS/NSPR
+	 * use the PR_NewTCPSocket() function here, which has the drawback that it
+	 * can only create IPv4 sockets. Instead use PR_OpenTCPSocket() which
+	 * copes with IPv6 as well.
+	 */
+	model = SSL_ImportFD(NULL, PR_OpenTCPSocket(conn->laddr.addr.ss_family));
+	if (!model)
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("unable to enable TLS: %s"),
+						  pg_SSLerrmessage(PR_GetError()));
+		return PGRES_POLLING_FAILED;
+	}
+
+	/* Disable old protocol versions (SSLv2 and SSLv3) */
+	SSL_OptionSet(model, SSL_ENABLE_SSL2, PR_FALSE);
+	SSL_OptionSet(model, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
+	SSL_OptionSet(model, SSL_ENABLE_SSL3, PR_FALSE);
+
+#ifdef SSL_CBC_RANDOM_IV
+
+	/*
+	 * Enable protection against the BEAST attack in case the NSS library has
+	 * support for that. While SSLv3 is disabled, we may still allow TLSv1
+	 * which is affected. The option isn't documented as an SSL option, but as
+	 * an NSS environment variable.
+	 */
+	SSL_OptionSet(model, SSL_CBC_RANDOM_IV, PR_TRUE);
+#endif
+
+	/* Set us up as a TLS client for the handshake */
+	SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
+
+	/*
+	 * When setting the available protocols, we either use the user defined
+	 * configuration values, and if missing we accept whatever is the highest
+	 * version supported by the library as the max and only limit the range in
+	 * the other end at TLSv1.0. ssl_variant_stream is a ProtocolVariant enum
+	 * for Stream protocols, rather than datagram.
+	 */
+	SSL_VersionRangeGetSupported(ssl_variant_stream, &desired_range);
+	desired_range.min = SSL_LIBRARY_VERSION_TLS_1_0;
+
+	if (conn->ssl_min_protocol_version && strlen(conn->ssl_min_protocol_version) > 0)
+	{
+		int			ssl_min_ver = ssl_protocol_version_to_nss(conn->ssl_min_protocol_version);
+
+		if (ssl_min_ver == -1)
+		{
+			printfPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("invalid value \"%s\" for minimum version of SSL protocol\n"),
+							  conn->ssl_min_protocol_version);
+			return -1;
+		}
+
+		desired_range.min = ssl_min_ver;
+	}
+
+	if (conn->ssl_max_protocol_version && strlen(conn->ssl_max_protocol_version) > 0)
+	{
+		int			ssl_max_ver = ssl_protocol_version_to_nss(conn->ssl_max_protocol_version);
+
+		if (ssl_max_ver == -1)
+		{
+			printfPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("invalid value \"%s\" for maximum version of SSL protocol\n"),
+							  conn->ssl_max_protocol_version);
+			return -1;
+		}
+
+		desired_range.max = ssl_max_ver;
+	}
+
+	if (SSL_VersionRangeSet(model, &desired_range) != SECSuccess)
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("unable to set allowed SSL protocol version range: %s"),
+						  pg_SSLerrmessage(PR_GetError()));
+		return PGRES_POLLING_FAILED;
+	}
+
+	/*
+	 * Set up callback for verifying server certificates, as well as for how
+	 * to handle failed verifications.
+	 */
+	SSL_AuthCertificateHook(model, pg_cert_auth_handler, (void *) conn);
+	SSL_BadCertHook(model, pg_bad_cert_handler, (void *) conn);
+
+	/*
+	 * Convert the NSPR socket to an SSL socket. Ensuring the success of this
+	 * operation is critical as NSS SSL_* functions may return SECSuccess on
+	 * the socket even though SSL hasn't been enabled, which introduce a risk
+	 * of silent downgrades.
+	 */
+	conn->pr_fd = SSL_ImportFD(model, pr_fd);
+	if (!conn->pr_fd)
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("unable to configure client for TLS: %s"),
+						  pg_SSLerrmessage(PR_GetError()));
+		return PGRES_POLLING_FAILED;
+	}
+
+	/*
+	 * The model can now we closed as we've applied the settings of the model
+	 * onto the real socket. From hereon we should only use conn->pr_fd.
+	 */
+	PR_Close(model);
+
+	/* Set the private data to be passed to the password callback */
+	SSL_SetPKCS11PinArg(conn->pr_fd, (void *) conn);
+
+	/*
+	 * If a CRL file has been specified, verify if it exists in the database
+	 * but don't fail in case it doesn't.
+	 */
+	if (conn->sslcrl && strlen(conn->sslcrl) > 0)
+	{
+		/* XXX: Implement me.. */
+	}
+
+	status = SSL_ResetHandshake(conn->pr_fd, PR_FALSE);
+	if (status != SECSuccess)
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("unable to initiate handshake: %s"),
+						  pg_SSLerrmessage(PR_GetError()));
+		return PGRES_POLLING_FAILED;
+	}
+
+	/*
+	 * Set callback for client authentication when requested by the server.
+	 */
+	SSL_GetClientAuthDataHook(conn->pr_fd, pg_client_auth_handler, (void *) conn);
+
+	/*
+	 * Specify which hostname we are expecting to talk to. This is required,
+	 * albeit mostly applies to when opening a connection to a traditional
+	 * http server it seems.
+	 */
+	SSL_SetURL(conn->pr_fd, (conn->connhost[conn->whichhost]).host);
+
+	do
+	{
+		status = SSL_ForceHandshake(conn->pr_fd);
+	}
+	while (status != SECSuccess && PR_GetError() == PR_WOULD_BLOCK_ERROR);
+
+	if (status != SECSuccess)
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("SSL error: %s"),
+						  pg_SSLerrmessage(PR_GetError()));
+		return PGRES_POLLING_FAILED;
+	}
+
+	conn->ssl_in_use = true;
+	return PGRES_POLLING_OK;
+}
+
+ssize_t
+pgtls_read(PGconn *conn, void *ptr, size_t len)
+{
+	PRInt32		nread;
+	PRErrorCode status;
+	int			read_errno = 0;
+
+	/*
+	 * PR_Recv blocks until there is data to read or the timeout expires. We
+	 * don't want to sit blocked here, so the timeout is turned off by using
+	 * PR_INTERVAL_NO_WAIT which means "return immediately",  Zero is returned
+	 * for closed connections, while -1 indicates an error within the ongoing
+	 * connection.
+	 */
+	nread = PR_Recv(conn->pr_fd, ptr, len, 0, PR_INTERVAL_NO_WAIT);
+
+	if (nread == 0)
+	{
+		read_errno = ECONNRESET;
+		nread = -1;
+	}
+	else if (nread == -1)
+	{
+		status = PR_GetError();
+
+		switch (status)
+		{
+			case PR_IO_TIMEOUT_ERROR:
+				/* No data available yet. */
+				nread = 0;
+				break;
+
+			case PR_WOULD_BLOCK_ERROR:
+				read_errno = EWOULDBLOCK;
+				break;
+
+				/*
+				 * The error cases for PR_Recv are not documented, but can be
+				 * reverse engineered from _MD_unix_map_default_error() in the
+				 * NSPR code, defined in pr/src/md/unix/unix_errors.c.
+				 */
+			case PR_NETWORK_UNREACHABLE_ERROR:
+			case PR_CONNECT_RESET_ERROR:
+				read_errno = ECONNRESET;
+				break;
+
+			default:
+				break;
+		}
+
+		if (nread == -1)
+		{
+			printfPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("TLS read error: %s"),
+							  pg_SSLerrmessage(status));
+		}
+	}
+
+	SOCK_ERRNO_SET(read_errno);
+	return (ssize_t) nread;
+}
+
+/*
+ * pgtls_read_pending
+ *		Check for the existence of data to be read.
+ *
+ * This is part of the PostgreSQL TLS backend API.
+ */
+bool
+pgtls_read_pending(PGconn *conn)
+{
+	unsigned char c;
+	int			n;
+
+	/*
+	 * PR_Recv peeks into the stream with the timeount turned off, to see if
+	 * there is another byte to read off the wire. There is an NSS function
+	 * SSL_DataPending() which might seem like a better fit, but it will only
+	 * check already encrypted data in the SSL buffer, not still unencrypted
+	 * data, thus it doesn't guarantee that a subsequent call to
+	 * PR_Read/PR_Recv won't block.
+	 */
+	n = PR_Recv(conn->pr_fd, &c, 1, PR_MSG_PEEK, PR_INTERVAL_NO_WAIT);
+	return (n > 0);
+}
+
+ssize_t
+pgtls_write(PGconn *conn, const void *ptr, size_t len)
+{
+	PRInt32		n;
+	PRErrorCode status;
+	int			write_errno = 0;
+
+	n = PR_Write(conn->pr_fd, ptr, len);
+
+	if (n < 0)
+	{
+		status = PR_GetError();
+
+		switch (status)
+		{
+			case PR_WOULD_BLOCK_ERROR:
+#ifdef EAGAIN
+				write_errno = EAGAIN;
+#else
+				write_errno = EINTR;
+#endif
+				break;
+
+			default:
+				printfPQExpBuffer(&conn->errorMessage,
+								  libpq_gettext("TLS write error: %s"),
+								  pg_SSLerrmessage(status));
+				write_errno = ECONNRESET;
+				break;
+		}
+	}
+
+	SOCK_ERRNO_SET(write_errno);
+	return (ssize_t) n;
+}
+
+char *
+pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
+{
+	CERTCertificate *server_cert;
+	SECOidTag	signature_alg;
+	SECOidTag	digest_alg;
+	int			digest_len;
+	const NSSSignatureAlgorithms *candidate;
+	PLArenaPool *arena;
+	SECItem		digest;
+	char	   *ret;
+	SECStatus	status;
+
+	*len = 0;
+
+	server_cert = SSL_PeerCertificate(conn->pr_fd);
+	if (!server_cert)
+		return NULL;
+
+	signature_alg = SECOID_GetAlgorithmTag(&server_cert->signature);
+
+	candidate = NSS_SCRAMDigestAlgorithm;
+	while (candidate->signature)
+	{
+		if (signature_alg == candidate->signature)
+		{
+			digest_alg = candidate->hash;
+			digest_len = candidate->len;
+			break;
+		}
+
+		candidate++;
+	}
+
+	if (!candidate->signature)
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("could not find digest for OID '%s'\n"),
+						  SECOID_FindOIDTagDescription(signature_alg));
+		return NULL;
+	}
+
+	arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
+	digest.data = PORT_ArenaZAlloc(arena, sizeof(unsigned char) * digest_len);
+	digest.len = digest_len;
+
+	status = PK11_HashBuf(digest_alg, digest.data, server_cert->derCert.data,
+						  server_cert->derCert.len);
+
+	if (status != SECSuccess)
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("unable to generate peer certificate digest: %s"),
+						  pg_SSLerrmessage(PR_GetError()));
+		PORT_FreeArena(arena, PR_TRUE);
+		return NULL;
+	}
+
+	ret = pg_malloc(digest.len);
+	memcpy(ret, digest.data, digest.len);
+	*len = digest_len;
+	PORT_FreeArena(arena, PR_TRUE);
+
+	return ret;
+}
+
+/*
+ *	Verify that the server certificate matches the hostname we connected to.
+ *
+ * The certificate's Common Name and Subject Alternative Names are considered.
+ */
+int
+pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn,
+												int *names_examined,
+												char **first_name)
+{
+	char	   *server_hostname = NULL;
+	CERTCertificate *server_cert = NULL;
+	SECStatus	status = SECSuccess;
+	SECItem		altname_item;
+	PLArenaPool *arena = NULL;
+	CERTGeneralName *san_list;
+	CERTGeneralName *cn;
+
+	server_hostname = SSL_RevealURL(conn->pr_fd);
+	if (!server_hostname || server_hostname[0] == '\0')
+		goto done;
+
+	/*
+	 * CERT_VerifyCertName will internally perform RFC 2818 SubjectAltName
+	 * verification.
+	 */
+	server_cert = SSL_PeerCertificate(conn->pr_fd);
+	status = CERT_VerifyCertName(server_cert, server_hostname);
+	if (status != SECSuccess)
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("unable to verify server hostname: %s"),
+						  pg_SSLerrmessage(PR_GetError()));
+		goto done;
+	}
+
+	status = CERT_FindCertExtension(server_cert, SEC_OID_X509_SUBJECT_ALT_NAME,
+									&altname_item);
+	if (status == SECSuccess)
+	{
+		arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+		if (!arena)
+		{
+			status = SECFailure;
+			goto done;
+		}
+		san_list = CERT_DecodeAltNameExtension(arena, &altname_item);
+		if (!san_list)
+		{
+			status = SECFailure;
+			goto done;
+		}
+
+		for (cn = san_list; cn != san_list; cn = CERT_GetNextGeneralName(cn))
+		{
+			char	   *alt_name;
+			int			rv;
+			char		tmp[512];
+
+			status = CERT_RFC1485_EscapeAndQuote(tmp, sizeof(tmp),
+												 (char *) cn->name.other.data,
+												 cn->name.other.len);
+
+			if (status != SECSuccess)
+				goto done;
+
+			rv = pq_verify_peer_name_matches_certificate_name(conn, tmp,
+															  strlen(tmp),
+															  &alt_name);
+			if (alt_name)
+			{
+				if (!*first_name)
+					*first_name = alt_name;
+				else
+					free(alt_name);
+			}
+
+			if (rv == 1)
+				status = SECSuccess;
+			else
+			{
+				status = SECFailure;
+				break;
+			}
+		}
+	}
+	else if (PORT_GetError() == SEC_ERROR_EXTENSION_NOT_FOUND)
+		status = SECSuccess;
+	else
+		status = SECSuccess;
+
+done:
+	/* san_list will be freed by freeing the arena it was allocated in */
+	if (arena)
+		PORT_FreeArena(arena, PR_TRUE);
+	PR_Free(server_hostname);
+
+	if (status == SECSuccess)
+		return 1;
+
+	return 0;
+}
+
+/* ------------------------------------------------------------ */
+/*			PostgreSQL specific TLS support functions			*/
+/* ------------------------------------------------------------ */
+
+static const char *
+pg_SSLerrmessage(PRErrorCode errcode)
+{
+	const char *error;
+
+	/*
+	 * Try to get the user friendly error description, and if that fails try
+	 * to fall back on the name of the PRErrorCode.
+	 */
+	error = PR_ErrorToString(errcode, PR_LANGUAGE_I_DEFAULT);
+	if (!error)
+		error = PR_ErrorToName(errcode);
+	if (error)
+		return error;
+
+	return "unknown TLS error";
+}
+
+static SECStatus
+pg_load_nss_module(SECMODModule * *module, const char *library, const char *name)
+{
+	SECMODModule *mod;
+	char	   *modulespec;
+
+	modulespec = psprintf("library=\"%s\", name=\"%s\"", library, name);
+
+	/*
+	 * Attempt to load the specified module. The second parameter is "parent"
+	 * which should always be NULL for application code. The third parameter
+	 * defines if loading should recurse which is only applicable when loading
+	 * a module from within another module. This hierarchy would have to be
+	 * defined in the modulespec, and since we don't support anything but
+	 * directly addressed modules we should pass PR_FALSE.
+	 */
+	mod = SECMOD_LoadUserModule(modulespec, NULL, PR_FALSE);
+	pfree(modulespec);
+
+	if (mod && mod->loaded)
+	{
+		*module = mod;
+		return SECSuccess;
+	}
+
+	SECMOD_DestroyModule(mod);
+	return SECFailure;
+}
+
+/* ------------------------------------------------------------ */
+/*						NSS Callbacks							*/
+/* ------------------------------------------------------------ */
+
+/*
+ * pg_cert_auth_handler
+ *			Callback for authenticating server certificate
+ *
+ * This is pretty much the same procedure as the SSL_AuthCertificate function
+ * provided by NSS, with the difference being server hostname validation. With
+ * SSL_AuthCertificate there is no way to do verify-ca, it only does the -full
+ * flavor of our sslmodes, so we need our own implementation.
+ */
+static SECStatus
+pg_cert_auth_handler(void *arg, PRFileDesc *fd, PRBool checksig, PRBool isServer)
+{
+	SECStatus	status;
+	PGconn	   *conn = (PGconn *) arg;
+	CERTCertificate *server_cert;
+	void	   *pin;
+
+	Assert(!isServer);
+
+	pin = SSL_RevealPinArg(conn->pr_fd);
+	server_cert = SSL_PeerCertificate(conn->pr_fd);
+
+	status = CERT_VerifyCertificateNow((CERTCertDBHandle *) CERT_GetDefaultCertDB(),
+									   server_cert,
+									   checksig,
+									   certificateUsageSSLServer,
+									   pin,
+									   NULL);
+
+	/*
+	 * If we've already failed validation then there is no point in also
+	 * performing the hostname check for verify-full.
+	 */
+	if (status == SECSuccess)
+	{
+		if (!pq_verify_peer_name_matches_certificate(conn))
+			status = SECFailure;
+	}
+	else
+	{
+		printfPQExpBuffer(&conn->errorMessage,
+						  libpq_gettext("unable to verify certificate: %s"),
+						  pg_SSLerrmessage(PR_GetError()));
+	}
+
+	return status;
+}
+
+/*
+ * pg_client_auth_handler
+ *		Callback for client certificate validation
+ *
+ * The client auth callback is not on by default in NSS, so we need to invoke
+ * it ourselves to ensure we can do cert authentication. A TODO is to support
+ * running without a specified sslcert parameter. By retrieving all the certs
+ * via nickname from the cert database and see if we find one which apply with
+ * NSS_CmpCertChainWCANames() and PK11_FindKeyByAnyCert() we could support
+ * just running with a ssl database specified.
+ *
+ * For now, we use the default client certificate validation which requires a
+ * defined nickname to identify the cert in the database.
+ */
+static SECStatus
+pg_client_auth_handler(void *arg, PRFileDesc * socket, CERTDistNames * caNames,
+					   CERTCertificate * *pRetCert, SECKEYPrivateKey * *pRetKey)
+{
+	PGconn	   *conn = (PGconn *) arg;
+
+	return NSS_GetClientAuthData(conn->sslcert, socket, caNames, pRetCert, pRetKey);
+}
+
+/*
+ * pg_bad_cert_handler
+ *		Callback for failed certificate validation
+ *
+ * The TLS handshake will call this function iff the server certificate failed
+ * validation. Depending on the sslmode, we allow the connection anyways.
+ */
+static SECStatus
+pg_bad_cert_handler(void *arg, PRFileDesc * fd)
+{
+	PGconn	   *conn = (PGconn *) arg;
+	PRErrorCode err;
+
+	/*
+	 * This really shouldn't happen, as we've set the PGconn object as our
+	 * callback data, and at the callsite we know it will be populated. That
+	 * being said, the NSS code itself performs this check even when it should
+	 * not be required so let's use the same belts with our suspenders.
+	 */
+	if (!arg)
+		return SECFailure;
+
+	/*
+	 * For sslmodes other than verify-full and verify-ca we don't perform peer
+	 * validation, so return immediately.  sslmode require with a database
+	 * specified which contains a CA certificate will work like verify-ca to
+	 * be compatible with the OpenSSL implementation.
+	 */
+	if (strcmp(conn->sslmode, "require") == 0)
+	{
+		if (conn->cert_database && strlen(conn->cert_database) > 0 && cert_database_has_CA(conn))
+			return SECFailure;
+	}
+	if (conn->sslmode[0] == 'v')
+		return SECFailure;
+
+	err = PORT_GetError();
+
+	/*
+	 * TODO: these are relevant error codes that can occur in certificate
+	 * validation, figure out which we don't want for require/prefer etc.
+	 */
+	switch (err)
+	{
+		case SEC_ERROR_INVALID_AVA:
+		case SEC_ERROR_INVALID_TIME:
+		case SEC_ERROR_BAD_SIGNATURE:
+		case SEC_ERROR_EXPIRED_CERTIFICATE:
+		case SEC_ERROR_UNKNOWN_ISSUER:
+		case SEC_ERROR_UNTRUSTED_ISSUER:
+		case SEC_ERROR_UNTRUSTED_CERT:
+		case SEC_ERROR_CERT_VALID:
+		case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
+		case SEC_ERROR_CRL_EXPIRED:
+		case SEC_ERROR_CRL_BAD_SIGNATURE:
+		case SEC_ERROR_EXTENSION_VALUE_INVALID:
+		case SEC_ERROR_CA_CERT_INVALID:
+		case SEC_ERROR_CERT_USAGES_INVALID:
+		case SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION:
+			return SECSuccess;
+			break;
+		default:
+			return SECFailure;
+			break;
+	}
+
+	/* Unreachable */
+	return SECSuccess;
+}
+
+/* ------------------------------------------------------------ */
+/*					SSL information functions					*/
+/* ------------------------------------------------------------ */
+
+/*
+ * PQgetssl
+ *
+ * Return NULL as this is legacy and defined to always be equal to calling
+ * PQsslStruct(conn, "OpenSSL"); This should ideally trigger a logged warning
+ * somewhere as it's nonsensical to run in a non-OpenSSL build, but the color
+ * of said bikeshed hasn't yet been determined.
+ */
+void *
+PQgetssl(PGconn *conn)
+{
+	return NULL;
+}
+
+void *
+PQsslStruct(PGconn *conn, const char *struct_name)
+{
+	if (!conn)
+		return NULL;
+
+	/*
+	 * Return the underlying PRFileDesc which can be used to access
+	 * information on the connection details. There is no SSL context per se.
+	 */
+	if (strcmp(struct_name, "NSS") == 0)
+		return conn->pr_fd;
+	return NULL;
+}
+
+const char *const *
+PQsslAttributeNames(PGconn *conn)
+{
+	static const char *const result[] = {
+		"library",
+		"cipher",
+		"protocol",
+		"key_bits",
+		"compression",
+		NULL
+	};
+
+	return result;
+}
+
+const char *
+PQsslAttribute(PGconn *conn, const char *attribute_name)
+{
+	SECStatus	status;
+	SSLChannelInfo channel;
+	SSLCipherSuiteInfo suite;
+
+	if (!conn || !conn->pr_fd)
+		return NULL;
+
+	if (strcmp(attribute_name, "library") == 0)
+		return "NSS";
+
+	status = SSL_GetChannelInfo(conn->pr_fd, &channel, sizeof(channel));
+	if (status != SECSuccess)
+		return NULL;
+
+	status = SSL_GetCipherSuiteInfo(channel.cipherSuite, &suite, sizeof(suite));
+	if (status != SECSuccess)
+		return NULL;
+
+	if (strcmp(attribute_name, "cipher") == 0)
+		return suite.cipherSuiteName;
+
+	if (strcmp(attribute_name, "key_bits") == 0)
+	{
+		static char key_bits_str[8];
+
+		snprintf(key_bits_str, sizeof(key_bits_str), "%i", suite.effectiveKeyBits);
+		return key_bits_str;
+	}
+
+	if (strcmp(attribute_name, "protocol") == 0)
+	{
+		switch (channel.protocolVersion)
+		{
+#ifdef SSL_LIBRARY_VERSION_TLS_1_3
+			case SSL_LIBRARY_VERSION_TLS_1_3:
+				return "TLSv1.3";
+#endif
+#ifdef SSL_LIBRARY_VERSION_TLS_1_2
+			case SSL_LIBRARY_VERSION_TLS_1_2:
+				return "TLSv1.2";
+#endif
+#ifdef SSL_LIBRARY_VERSION_TLS_1_1
+			case SSL_LIBRARY_VERSION_TLS_1_1:
+				return "TLSv1.1";
+#endif
+			case SSL_LIBRARY_VERSION_TLS_1_0:
+				return "TLSv1.0";
+			default:
+				return "unknown";
+		}
+	}
+
+	/*
+	 * NSS disabled support for compression in version 3.33, and it was only
+	 * available for SSLv3 at that point anyways, so we can safely return off
+	 * here without checking.
+	 */
+	if (strcmp(attribute_name, "compression") == 0)
+		return "off";
+
+	return NULL;
+}
+
+static int
+ssl_protocol_version_to_nss(const char *protocol)
+{
+	if (pg_strcasecmp("TLSv1", protocol) == 0)
+		return SSL_LIBRARY_VERSION_TLS_1_0;
+
+#ifdef SSL_LIBRARY_VERSION_TLS_1_1
+	if (pg_strcasecmp("TLSv1.1", protocol) == 0)
+		return SSL_LIBRARY_VERSION_TLS_1_1;
+#endif
+
+#ifdef SSL_LIBRARY_VERSION_TLS_1_2
+	if (pg_strcasecmp("TLSv1.2", protocol) == 0)
+		return SSL_LIBRARY_VERSION_TLS_1_2;
+#endif
+
+#ifdef SSL_LIBRARY_VERSION_TLS_1_3
+	if (pg_strcasecmp("TLSv1.3", protocol) == 0)
+		return SSL_LIBRARY_VERSION_TLS_1_3;
+#endif
+
+	return -1;
+}
+
+/*
+ * cert_database_has_CA
+ *
+ * Returns true in case there is a CA certificate in the database connected
+ * to in the conn object, else false. This function only checks for the
+ * presence of a CA certificate, not it's validity and/or usefulness.
+ */
+static bool
+cert_database_has_CA(PGconn *conn)
+{
+	CERTCertList *certificates;
+	bool		hasCA;
+
+	/*
+	 * If the certificate database has a password we must provide it, since
+	 * this API doesn't invoke the standard password callback.
+	 */
+	if (conn->has_password)
+		certificates = PK11_ListCerts(PK11CertListCA, PQssl_passwd_cb(NULL, PR_FALSE, (void *) conn));
+	else
+		certificates = PK11_ListCerts(PK11CertListCA, NULL);
+	hasCA = !CERT_LIST_EMPTY(certificates);
+	CERT_DestroyCertList(certificates);
+
+	return hasCA;
+}
+
+PQsslKeyPassHook_nss_type
+PQgetSSLKeyPassHook_nss(void)
+{
+	return PQsslKeyPassHook;
+}
+
+void
+PQsetSSLKeyPassHook_nss(PQsslKeyPassHook_nss_type hook)
+{
+	PQsslKeyPassHook = hook;
+}
+
+/*
+ * Supply a password to decrypt a client certificate.
+ *
+ * This must match NSS type PK11PasswordFunc.
+ */
+static char *
+PQssl_passwd_cb(PK11SlotInfo *slot, PRBool retry, void *arg)
+{
+	PGconn	   *conn = (PGconn *) arg;
+
+	conn->has_password = true;
+
+	if (PQsslKeyPassHook)
+		return PQsslKeyPassHook(slot, (PRBool) retry, arg);
+	else
+		return PQdefaultSSLKeyPassHook_nss(slot, retry, arg);
+}
+
+/*
+ * The default password handler callback.
+ */
+char *
+PQdefaultSSLKeyPassHook_nss(PK11SlotInfo * slot, PRBool retry, void *arg)
+{
+	PGconn	   *conn = (PGconn *) arg;
+
+	/*
+	 * If the password didn't work the first time there is no point in
+	 * retrying as it hasn't changed.
+	 */
+	if (retry != PR_TRUE && conn->sslpassword && strlen(conn->sslpassword) > 0)
+		return PORT_Strdup(conn->sslpassword);
+
+	return NULL;
+}
diff --git a/src/interfaces/libpq/fe-secure.c b/src/interfaces/libpq/fe-secure.c
index 67b1e78512..0a1e47c5a2 100644
--- a/src/interfaces/libpq/fe-secure.c
+++ b/src/interfaces/libpq/fe-secure.c
@@ -427,6 +427,9 @@ PQsslAttributeNames(PGconn *conn)
 
 	return result;
 }
+#endif							/* USE_SSL */
+
+#ifndef USE_OPENSSL
 
 PQsslKeyPassHook_OpenSSL_type
 PQgetSSLKeyPassHook_OpenSSL(void)
@@ -445,7 +448,7 @@ PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
 {
 	return 0;
 }
-#endif							/* USE_SSL */
+#endif							/* USE_OPENSSL */
 
 /* Dummy version of GSSAPI information functions, when built without GSS support */
 #ifndef ENABLE_GSS
diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h
index c266ad5b13..aba32e6635 100644
--- a/src/interfaces/libpq/libpq-fe.h
+++ b/src/interfaces/libpq/libpq-fe.h
@@ -619,12 +619,23 @@ extern int	pg_valid_server_encoding_id(int encoding);
 
 /* === in fe-secure-openssl.c === */
 
-/* Support for overriding sslpassword handling with a callback. */
+/* Support for overriding sslpassword handling with a callback */
 typedef int (*PQsslKeyPassHook_OpenSSL_type) (char *buf, int size, PGconn *conn);
 extern PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
 extern void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook);
 extern int	PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn);
 
+/* == in fe-secure-nss.c === */
+typedef struct PK11SlotInfoStr PK11SlotInfo;
+typedef int PRIntn;
+typedef PRIntn PRBool;
+
+/* Support for overriding sslpassword handling with a callback */
+typedef char *(*PQsslKeyPassHook_nss_type) (PK11SlotInfo *slot, PRBool retry, void *arg);
+extern PQsslKeyPassHook_nss_type PQgetSSLKeyPassHook_nss(void);
+extern void PQsetSSLKeyPassHook_nss(PQsslKeyPassHook_nss_type hook);
+extern char *PQdefaultSSLKeyPassHook_nss(PK11SlotInfo *slot, PRBool retry, void *arg);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 4db498369c..a95450fbba 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -362,6 +362,7 @@ struct pg_conn
 	char	   *sslpassword;	/* client key file password */
 	char	   *sslrootcert;	/* root certificate filename */
 	char	   *sslcrl;			/* certificate revocation list filename */
+	char	   *cert_database;	/* NSS certificate/key database */
 	char	   *requirepeer;	/* required peer credentials for local sockets */
 	char	   *gssencmode;		/* GSS mode (require,prefer,disable) */
 	char	   *krbsrvname;		/* Kerberos service name */
@@ -485,6 +486,23 @@ struct pg_conn
 								 * OpenSSL version changes */
 #endif
 #endif							/* USE_OPENSSL */
+
+#ifdef USE_NSS
+	void	   *pr_fd;			/* NSPR file descriptor for the connection */
+
+	/*
+	 * Track whether the NSS database has a password set or not. There is no
+	 * API function for retrieving password status of a database, but we need
+	 * to know since some NSS API calls require the password passed in (they
+	 * don't call the callback themselves). To track, we simply flip this to
+	 * true in case NSS invoked the password callback - as that will only
+	 * happen in case there is a password. The reason for tracking this is
+	 * that there are calls which require a password parameter, but doesn't
+	 * use the callbacks provided, so we must call the callback on behalf of
+	 * these.
+	 */
+	bool		has_password;
+#endif							/* USE_NSS */
 #endif							/* USE_SSL */
 
 #ifdef ENABLE_GSS
@@ -759,7 +777,7 @@ extern ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len);
  * This is not supported with old versions of OpenSSL that don't have
  * the X509_get_signature_nid() function.
  */
-#if defined(USE_OPENSSL) && defined(HAVE_X509_GET_SIGNATURE_NID)
+#if defined(USE_NSS) || (defined(USE_OPENSSL) && defined(HAVE_X509_GET_SIGNATURE_NID))
 #define HAVE_PGTLS_GET_PEER_CERTIFICATE_HASH
 extern char *pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len);
 #endif
diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm
index 5634b2d40c..a21eb088b3 100644
--- a/src/tools/msvc/Mkvcbuild.pm
+++ b/src/tools/msvc/Mkvcbuild.pm
@@ -194,12 +194,19 @@ sub mkvcbuild
 	$postgres->FullExportDLL('postgres.lib');
 
 	# The OBJS scraper doesn't know about ifdefs, so remove appropriate files
-	# if building without OpenSSL.
-	if (!$solution->{options}->{openssl})
+	# if building without various options.
+	if (!$solution->{options}->{openssl} && !$solution->{options}->{nss})
 	{
 		$postgres->RemoveFile('src/backend/libpq/be-secure-common.c');
+	}
+	if (!$solution->{options}->{openssl})
+	{
 		$postgres->RemoveFile('src/backend/libpq/be-secure-openssl.c');
 	}
+	if (!$solution->{options}->{nss})
+	{
+		$postgres->RemoveFile('src/backend/libpq/be-secure-nss.c');
+	}
 	if (!$solution->{options}->{gss})
 	{
 		$postgres->RemoveFile('src/backend/libpq/be-gssapi-common.c');
@@ -257,12 +264,19 @@ sub mkvcbuild
 	$libpq->AddReference($libpgcommon, $libpgport);
 
 	# The OBJS scraper doesn't know about ifdefs, so remove appropriate files
-	# if building without OpenSSL.
-	if (!$solution->{options}->{openssl})
+	# if building without various options
+	if (!$solution->{options}->{openssl} && !$solution->{options}->{nss})
 	{
 		$libpq->RemoveFile('src/interfaces/libpq/fe-secure-common.c');
+	}
+	if (!$solution->{options}->{openssl})
+	{
 		$libpq->RemoveFile('src/interfaces/libpq/fe-secure-openssl.c');
 	}
+	if (!$solution->{options}->{nss})
+	{
+		$libpq->RemoveFile('src/interfaces/libpq/fe-secure-nss.c');
+	}
 	if (!$solution->{options}->{gss})
 	{
 		$libpq->RemoveFile('src/interfaces/libpq/fe-gssapi-common.c');
diff --git a/src/tools/msvc/Solution.pm b/src/tools/msvc/Solution.pm
index 59a42bea97..d3d0ea3c95 100644
--- a/src/tools/msvc/Solution.pm
+++ b/src/tools/msvc/Solution.pm
@@ -488,6 +488,7 @@ sub GenerateFiles
 		USE_LLVM                   => undef,
 		USE_NAMED_POSIX_SEMAPHORES => undef,
 		USE_OPENSSL                => undef,
+		USE_NSS                    => undef,
 		USE_PAM                    => undef,
 		USE_SLICING_BY_8_CRC32C    => undef,
 		USE_SSE42_CRC32C           => undef,
@@ -540,6 +541,10 @@ sub GenerateFiles
 			$define{HAVE_OPENSSL_INIT_SSL}      = 1;
 		}
 	}
+	if ($self->{options}->{nss})
+	{
+		$define{USE_NSS} = 1;
+	}
 
 	$self->GenerateConfigHeader('src/include/pg_config.h',     \%define, 1);
 	$self->GenerateConfigHeader('src/include/pg_config_ext.h', \%define, 0);
@@ -1005,6 +1010,21 @@ sub AddProject
 			}
 		}
 	}
+	if ($self->{options}->{nss})
+	{
+		$proj->AddIncludeDir($self->{options}->{nss} . '\..\public\nss');
+		$proj->AddIncludeDir($self->{options}->{nss} . '\include\nspr');
+		foreach my $lib (qw(plds4 plc4 nspr4))
+		{
+			$proj->AddLibrary($self->{options}->{nss} .
+							  '\lib\lib' . "$lib.lib", 0);
+		}
+		foreach my $lib (qw(ssl3 smime3 nss3))
+		{
+			$proj->AddLibrary($self->{options}->{nss} .
+							  '\lib' . "\\$lib.dll.lib", 0);
+		}
+	}
 	if ($self->{options}->{nls})
 	{
 		$proj->AddIncludeDir($self->{options}->{nls} . '\include');
diff --git a/src/tools/msvc/config_default.pl b/src/tools/msvc/config_default.pl
index 2ef2cfc4e9..49dc4d5864 100644
--- a/src/tools/msvc/config_default.pl
+++ b/src/tools/msvc/config_default.pl
@@ -17,6 +17,7 @@ our $config = {
 	perl      => undef,    # --with-perl=<path>
 	python    => undef,    # --with-python=<path>
 	openssl   => undef,    # --with-openssl=<path>
+	nss       => undef,    # --with-nss=<path>
 	uuid      => undef,    # --with-uuid=<path>
 	xml       => undef,    # --with-libxml=<path>
 	xslt      => undef,    # --with-libxslt=<path>
-- 
2.25.1

From cf3460f1ed6b24162e08ae9a17cfe2ffdd4418e8 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:22:26 +0100
Subject: [PATCH v23 2/6] NSS Testharness updates

TODO:
	* Generate certificate/keys with NSS tooling for NSS specific test
	* Add test for certificate with embedded nulls
	* Fix SCRAM tests when channel binding works
---
 src/test/Makefile                             |   2 +-
 src/test/modules/Makefile                     |   2 +-
 .../modules/ssl_passphrase_callback/Makefile  |   2 +-
 .../ssl_passphrase_callback/t/001_testfunc.pl |   4 +-
 src/test/ssl/Makefile                         | 235 +++++++++++-
 src/test/ssl/t/001_ssltests.pl                | 346 +++++++++++-------
 src/test/ssl/t/002_scram.pl                   |  97 +++--
 src/test/ssl/t/SSL/Backend/NSS.pm             |  73 ++++
 src/test/ssl/t/SSL/Backend/OpenSSL.pm         | 103 ++++++
 .../ssl/t/{SSLServer.pm => SSL/Server.pm}     |  80 +++-
 10 files changed, 749 insertions(+), 195 deletions(-)
 create mode 100644 src/test/ssl/t/SSL/Backend/NSS.pm
 create mode 100644 src/test/ssl/t/SSL/Backend/OpenSSL.pm
 rename src/test/ssl/t/{SSLServer.pm => SSL/Server.pm} (78%)

diff --git a/src/test/Makefile b/src/test/Makefile
index ab1ef9a475..cee4586eb5 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -28,7 +28,7 @@ ifneq (,$(filter ldap,$(PG_TEST_EXTRA)))
 SUBDIRS += ldap
 endif
 endif
-ifeq ($(with_openssl),yes)
+ifeq ($(with_ssl),yes)
 ifneq (,$(filter ssl,$(PG_TEST_EXTRA)))
 SUBDIRS += ssl
 endif
diff --git a/src/test/modules/Makefile b/src/test/modules/Makefile
index 59921b46cf..5391f461a2 100644
--- a/src/test/modules/Makefile
+++ b/src/test/modules/Makefile
@@ -28,7 +28,7 @@ SUBDIRS = \
 		  unsafe_tests \
 		  worker_spi
 
-ifeq ($(with_openssl),yes)
+ifeq ($(with_ssl),openssl)
 SUBDIRS += ssl_passphrase_callback
 else
 ALWAYS_SUBDIRS += ssl_passphrase_callback
diff --git a/src/test/modules/ssl_passphrase_callback/Makefile b/src/test/modules/ssl_passphrase_callback/Makefile
index f81265c296..a34d7ea46a 100644
--- a/src/test/modules/ssl_passphrase_callback/Makefile
+++ b/src/test/modules/ssl_passphrase_callback/Makefile
@@ -1,6 +1,6 @@
 # ssl_passphrase_callback Makefile
 
-export with_openssl
+export with_ssl
 
 MODULE_big = ssl_passphrase_func
 OBJS = ssl_passphrase_func.o $(WIN32RES)
diff --git a/src/test/modules/ssl_passphrase_callback/t/001_testfunc.pl b/src/test/modules/ssl_passphrase_callback/t/001_testfunc.pl
index dbc084f870..a2bed5336c 100644
--- a/src/test/modules/ssl_passphrase_callback/t/001_testfunc.pl
+++ b/src/test/modules/ssl_passphrase_callback/t/001_testfunc.pl
@@ -7,9 +7,9 @@ use TestLib;
 use Test::More;
 use PostgresNode;
 
-unless (($ENV{with_openssl} || 'no') eq 'yes')
+unless ($ENV{with_ssl} eq 'openssl')
 {
-	plan skip_all => 'SSL not supported by this build';
+	plan skip_all => 'OpenSSL not supported by this build';
 }
 
 my $clearpass = "FooBaR1";
diff --git a/src/test/ssl/Makefile b/src/test/ssl/Makefile
index 93335b1ea2..d275c89672 100644
--- a/src/test/ssl/Makefile
+++ b/src/test/ssl/Makefile
@@ -13,7 +13,7 @@ subdir = src/test/ssl
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
-export with_openssl
+export with_ssl
 
 CERTIFICATES := server_ca server-cn-and-alt-names \
 	server-cn-only server-single-alt-name server-multiple-alt-names \
@@ -30,6 +30,35 @@ SSLFILES := $(CERTIFICATES:%=ssl/%.key) $(CERTIFICATES:%=ssl/%.crt) \
 	ssl/client+client_ca.crt ssl/client-der.key \
 	ssl/client-encrypted-pem.key ssl/client-encrypted-der.key
 
+# Even though we in practice could get away with far fewer NSS databases, they
+# are generated to mimic the setup for the OpenSSL tests in order to ensure
+# we isolate the same behavior between the backends. The database name should
+# contain the files included for easier test suite code reading.
+NSSFILES := ssl/nss/client_ca.crt.db \
+	ssl/nss/server_ca.crt.db \
+	ssl/nss/root+server_ca.crt.db \
+	ssl/nss/root+client_ca.crt.db \
+	ssl/nss/client.crt__client.key.db \
+	ssl/nss/client-revoked.crt__client-revoked.key.db \
+	ssl/nss/server-cn-only.crt__server-password.key.db \
+	ssl/nss/server-cn-only.crt__server-cn-only.key.db \
+	ssl/nss/root.crl \
+	ssl/nss/server.crl \
+	ssl/nss/client.crl \
+	ssl/nss/server-multiple-alt-names.crt__server-multiple-alt-names.key.db \
+	ssl/nss/server-single-alt-name.crt__server-single-alt-name.key.db \
+	ssl/nss/server-cn-and-alt-names.crt__server-cn-and-alt-names.key.db \
+	ssl/nss/server-no-names.crt__server-no-names.key.db \
+	ssl/nss/server-revoked.crt__server-revoked.key.db \
+	ssl/nss/root+client.crl \
+	ssl/nss/client+client_ca.crt__client.key.db \
+	ssl/nss/client.crt__client-encrypted-pem.key.db \
+	ssl/nss/root+server_ca.crt__server.crl.db \
+	ssl/nss/root+server_ca.crt__root+server.crl.db \
+	ssl/nss/native_ca-root.db \
+	ssl/nss/native_server-root.db \
+	ssl/nss/native_client-root.db
+
 # This target re-generates all the key and certificate files. Usually we just
 # use the ones that are committed to the tree without rebuilding them.
 #
@@ -37,6 +66,10 @@ SSLFILES := $(CERTIFICATES:%=ssl/%.key) $(CERTIFICATES:%=ssl/%.crt) \
 #
 sslfiles: $(SSLFILES)
 
+# Generate NSS certificate databases corresponding to the OpenSSL certificates.
+# This target will fail unless preceded by nssfiles-clean.
+nssfiles: $(NSSFILES)
+
 # OpenSSL requires a directory to put all generated certificates in. We don't
 # use this for anything, but we need a location.
 ssl/new_certs_dir:
@@ -64,6 +97,24 @@ ssl/%_ca.crt: ssl/%_ca.key %_ca.config ssl/root_ca.crt ssl/new_certs_dir
 	rm ssl/temp_ca.crt ssl/temp_ca_signed.crt
 	echo "01" > ssl/$*_ca.srl
 
+ssl/nss/%_ca.crt.db: ssl/%_ca.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n $*_ca.crt -i ssl/$*_ca.crt -t "CT,C,C"
+
+ssl/nss/root+server_ca.crt__server.crl.db: ssl/root+server_ca.crt ssl/nss/server.crl
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/root+server_ca.crt -i ssl/root+server_ca.crt -t "CT,C,C"
+	crlutil -I -i ssl/nss/server.crl -d $@ -B
+
+ssl/nss/root+server_ca.crt__root+server.crl.db: ssl/root+server_ca.crt ssl/nss/root.crl ssl/nss/server.crl
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/root+server_ca.crt -i ssl/root+server_ca.crt -t "CT,C,C"
+	crlutil -I -i ssl/nss/root.crl -d $@ -B
+	crlutil -I -i ssl/nss/server.crl -d $@ -B
+
 # Server certificates, signed by server CA:
 ssl/server-%.crt: ssl/server-%.key ssl/server_ca.crt server-%.config
 	openssl req -new -key ssl/server-$*.key -out ssl/server-$*.csr -config server-$*.config
@@ -77,6 +128,78 @@ ssl/server-ss.crt: ssl/server-cn-only.key ssl/server-cn-only.crt server-cn-only.
 	openssl x509 -req -days 10000 -in ssl/server-ss.csr -signkey ssl/server-cn-only.key -out ssl/server-ss.crt  -extensions v3_req -extfile server-cn-only.config
 	rm ssl/server-ss.csr
 
+# pk12util won't preserve the password when importing the password protected
+# key, the password must be set on the database *before* importing it as the
+# password in the pkcs12 envelope will be dropped.
+ssl/nss/server-cn-only.crt__server-password.key.db: ssl/server-cn-only.crt
+	$(MKDIR_P) $@
+	echo "secret1" > password.txt
+	certutil -d "sql:$@" -N -f password.txt
+	certutil -d "sql:$@" -A -n ssl/server-cn-only.crt -i ssl/server-cn-only.crt -t "CT,C,C" -f password.txt
+	certutil -d "sql:$@" -A -n server_ca.crt -i ssl/server_ca.crt -t "CT,C,C" -f password.txt
+	certutil -d "sql:$@" -A -n root_ca.crt -i ssl/root_ca.crt -t "CT,C,C" -f password.txt
+	certutil -d "sql:$@" -A -n client_ca.crt -i ssl/client_ca.crt -t "CT,C,C" -f password.txt
+	openssl pkcs12 -export -out ssl/nss/server-password.pfx -inkey ssl/server-password.key -in ssl/server-cn-only.crt -certfile ssl/server_ca.crt -passin 'pass:secret1' -passout 'pass:secret1'
+	pk12util -i ssl/nss/server-password.pfx -d "sql:$@" -W 'secret1' -K 'secret1'
+
+ssl/nss/server-cn-only.crt__server-cn-only.key.db: ssl/server-cn-only.crt ssl/server-cn-only.key
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/server-cn-only.crt -i ssl/server-cn-only.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n server_ca.crt -i ssl/server_ca.crt -t "CT,C,C"
+	openssl pkcs12 -export -out ssl/nss/server-cn-only.pfx -inkey ssl/server-cn-only.key -in ssl/server-cn-only.crt -certfile ssl/server_ca.crt -passout pass:
+	pk12util -i ssl/nss/server-cn-only.pfx -d "sql:$@" -W ''
+
+ssl/nss/server-multiple-alt-names.crt__server-multiple-alt-names.key.db: ssl/server-multiple-alt-names.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/server-multiple-alt-names.crt -i ssl/server-multiple-alt-names.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n server_ca.crt -i ssl/server_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n root_ca.crt -i ssl/root_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n client_ca.crt -i ssl/client_ca.crt -t "CT,C,C"
+	openssl pkcs12 -export -out ssl/nss/server-multiple-alt-names.pfx -inkey ssl/server-multiple-alt-names.key -in ssl/server-multiple-alt-names.crt -certfile ssl/server-multiple-alt-names.crt -passout pass:
+	pk12util -i ssl/nss/server-multiple-alt-names.pfx -d "sql:$@" -W ''
+
+ssl/nss/server-single-alt-name.crt__server-single-alt-name.key.db: ssl/server-single-alt-name.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/server-single-alt-name.crt -i ssl/server-single-alt-name.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n server_ca.crt -i ssl/server_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n root_ca.crt -i ssl/root_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n client_ca.crt -i ssl/client_ca.crt -t "CT,C,C"
+	openssl pkcs12 -export -out ssl/nss/server-single-alt-name.pfx -inkey ssl/server-single-alt-name.key -in ssl/server-single-alt-name.crt -certfile ssl/server-single-alt-name.crt -passout pass:
+	pk12util -i ssl/nss/server-single-alt-name.pfx -d "sql:$@" -W ''
+
+ssl/nss/server-cn-and-alt-names.crt__server-cn-and-alt-names.key.db: ssl/server-cn-and-alt-names.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/server-cn-and-alt-names.crt -i ssl/server-cn-and-alt-names.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n server_ca.crt -i ssl/server_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n root_ca.crt -i ssl/root_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n client_ca.crt -i ssl/client_ca.crt -t "CT,C,C"
+	openssl pkcs12 -export -out ssl/nss/server-cn-and-alt-names.pfx -inkey ssl/server-cn-and-alt-names.key -in ssl/server-cn-and-alt-names.crt -certfile ssl/server-cn-and-alt-names.crt -passout pass:
+	pk12util -i ssl/nss/server-cn-and-alt-names.pfx -d $@ -W ''
+
+ssl/nss/server-no-names.crt__server-no-names.key.db: ssl/server-no-names.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/server-no-names.crt -i ssl/server-no-names.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n server_ca.crt -i ssl/server_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n root_ca.crt -i ssl/root_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n client_ca.crt -i ssl/client_ca.crt -t "CT,C,C"
+	openssl pkcs12 -export -out ssl/nss/server-no-names.pfx -inkey ssl/server-no-names.key -in ssl/server-no-names.crt -certfile ssl/server-no-names.crt -passout pass:
+	pk12util -i ssl/nss/server-no-names.pfx -d "sql:$@" -W ''
+
+ssl/nss/server-revoked.crt__server-revoked.key.db: ssl/server-revoked.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/server-revoked.crt -i ssl/server-revoked.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n server_ca.crt -i ssl/server_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n root_ca.crt -i ssl/root_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n client_ca.crt -i ssl/client_ca.crt -t "CT,C,C"
+	openssl pkcs12 -export -out ssl/nss/server-revoked.pfx -inkey ssl/server-revoked.key -in ssl/server-revoked.crt -certfile ssl/server-revoked.crt -passout pass:
+	pk12util -i ssl/nss/server-revoked.pfx -d "sql:$@" -W ''
+
 # Password-protected version of server-cn-only.key
 ssl/server-password.key: ssl/server-cn-only.key
 	openssl rsa -aes256 -in $< -out $@ -passout 'pass:secret1'
@@ -88,6 +211,27 @@ 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, signed by client CA
+ssl/nss/client.crt__client.key.db: ssl/client.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/client.crt -i ssl/client.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n client_ca.crt -i ssl/client_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n root+client_ca.crt -i ssl/root+client_ca.crt -t "CT,C,C"
+	openssl pkcs12 -export -out ssl/nss/client.pfx -inkey ssl/client.key -in ssl/client.crt -certfile ssl/client_ca.crt -passout pass:
+	pk12util -i ssl/nss/client.pfx -d "sql:$@" -W ''
+
+# Client certificate with encrypted key, signed by client CA
+ssl/nss/client.crt__client-encrypted-pem.key.db: ssl/client.crt
+	$(MKDIR_P) $@
+	echo 'dUmmyP^#+' > $@.pass
+	certutil -d "sql:$@" -N -f $@.pass
+	certutil -d "sql:$@" -A -f $@.pass -n ssl/client.crt -i ssl/client.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -f $@.pass -n client_ca.crt -i ssl/client_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -f $@.pass -n root+server_ca.crt -i ssl/root+server_ca.crt -t "CT,C,C"
+	openssl pkcs12 -export -out ssl/nss/client-encrypted-pem.pfx -inkey ssl/client-encrypted-pem.key -in ssl/client.crt -certfile ssl/client_ca.crt -passin pass:'dUmmyP^#+' -passout pass:'dUmmyP^#+'
+	pk12util -i ssl/nss/client-encrypted-pem.pfx -d "sql:$@" -W 'dUmmyP^#+' -k $@.pass
+
 # 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
@@ -95,6 +239,14 @@ ssl/client-revoked.crt: ssl/client-revoked.key ssl/client_ca.crt client.config
 	openssl x509 -in ssl/temp.crt -out ssl/client-revoked.crt # to keep just the PEM cert
 	rm ssl/client-revoked.csr ssl/temp.crt
 
+ssl/nss/client-revoked.crt__client-revoked.key.db: ssl/client-revoked.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/client-revoked.crt -i ssl/client-revoked.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n client_ca.crt -i ssl/client_ca.crt -t "CT,C,C"
+	openssl pkcs12 -export -out ssl/nss/client-revoked.pfx -inkey ssl/client-revoked.key -in ssl/client-revoked.crt -certfile ssl/client_ca.crt -passout pass:
+	pk12util -i ssl/nss/client-revoked.pfx -d "sql:$@" -W ''
+
 # Convert the key to DER, to test our behaviour there too
 ssl/client-der.key: ssl/client.key
 	openssl rsa -in ssl/client.key -outform DER -out ssl/client-der.key
@@ -127,19 +279,40 @@ ssl/root+client_ca.crt: ssl/root_ca.crt ssl/client_ca.crt
 ssl/client+client_ca.crt: ssl/client.crt ssl/client_ca.crt
 	cat $^ > $@
 
+# Client certificate, signed by client CA
+ssl/nss/client+client_ca.crt__client.key.db: ssl/client+client_ca.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/client+client_ca.crt -i ssl/client+client_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n ssl/root+server_ca.crt -i ssl/root+server_ca.crt -t "CT,C,C"
+	openssl pkcs12 -export -out ssl/nss/client.pfx -inkey ssl/client.key -in ssl/client.crt -certfile ssl/client_ca.crt -passout pass:
+	pk12util -i ssl/nss/client.pfx -d "sql:$@" -W ''
+
 #### CRLs
 
 ssl/client.crl: ssl/client-revoked.crt
 	openssl ca -config cas.config -name client_ca -revoke ssl/client-revoked.crt
 	openssl ca -config cas.config -name client_ca -gencrl -out ssl/client.crl
 
+ssl/nss/client.crl: ssl/client.crl
+	openssl crl -in $^ -outform der -out $@
+
 ssl/server.crl: ssl/server-revoked.crt
 	openssl ca -config cas.config -name server_ca -revoke ssl/server-revoked.crt
 	openssl ca -config cas.config -name server_ca -gencrl -out ssl/server.crl
 
+ssl/nss/server.crl: ssl/server.crl
+	openssl crl -in $^ -outform der -out $@
+
 ssl/root.crl: ssl/root_ca.crt
 	openssl ca -config cas.config -name root_ca -gencrl -out ssl/root.crl
 
+ssl/nss/root.crl: ssl/root.crl
+	openssl crl -in $^ -outform der -out $@
+
+ssl/nss/root+client.crl: ssl/root+client.crl
+	openssl crl -in $^ -outform der -out $@
+
 # If a CRL is used, OpenSSL requires a CRL file for *all* the CAs in the
 # chain, even if some of them are empty.
 ssl/root+server.crl: ssl/root.crl ssl/server.crl
@@ -147,13 +320,73 @@ ssl/root+server.crl: ssl/root.crl ssl/server.crl
 ssl/root+client.crl: ssl/root.crl ssl/client.crl
 	cat $^ > $@
 
+#### NSS specific certificates and keys
+
+#NSSFILES2 := ssl/nss/native_ca-root.db \
+#	ssl/nss/native_server-root.db \
+#	ssl/nss/native_client-root.db
+
+#nssfiles2: $(NSSFILES2)
+
+ssl/nss/native_ca-%.db:
+	$(MKDIR_P) ssl/nss/native_ca-$*.db
+	certutil -N -d "sql:ssl/nss/native_ca-$*.db/" --empty-password
+	echo y > nss_ca_params.txt
+	echo 10 >> nss_ca_params.txt
+	echo y >> nss_ca_params.txt
+	cat nss_ca_params.txt | certutil -S -d "sql:ssl/nss/native_ca-$*.db/" -n ca-$* \
+	-s "CN=Test CA for PostgreSQL SSL regression tests,OU=PostgreSQL test suite" \
+	-x -k rsa -g 2048 -m 5432 -t CTu,CTu,CTu \
+	--keyUsage certSigning -2 --nsCertType sslCA,smimeCA,objectSigningCA \
+	-z Makefile -Z SHA256
+	rm nss_ca_params.txt
+
+ssl/nss/native_ca-%.pem: ssl/nss/native_ca-%.db
+	certutil -L -d "sql:ssl/nss/native_ca-$*.db/" -n ca-$* -a > ssl/nss/native_ca-$*.pem
+
+# Create and sign a server certificate
+ssl/nss/native_server-%.db: ssl/nss/native_ca-%.pem
+	$(MKDIR_P) ssl/nss/native_server-$*.db
+	certutil -N -d "sql:ssl/nss/native_server-$*.db/" --empty-password
+	certutil -R -d "sql:ssl/nss/native_server-$*.db/" \
+		-s "CN=common-name.pg-ssltest.test,OU=PostgreSQL test suite" \
+		-o ssl/nss/native_server-$*.csr -g 2048 -Z SHA256 -z Makefile
+	echo 1 > nss_server_params.txt
+	echo 9 >> nss_server_params.txt
+	cat nss_server_params.txt | certutil -C -d "sql:ssl/nss/native_ca-$*.db/" -c ca-root -i ssl/nss/native_server-$*.csr \
+		-o ssl/nss/native_server_$*.der -m 5433 --keyUsage dataEncipherment,digitalSignature,keyEncipherment \
+		--nsCertType sslServer --certVersion 1 -Z SHA256
+	certutil -A -d "sql:ssl/nss/native_server-$*.db/" -n ca-$* -t CTu,CTu,CTu -a -i ssl/nss/native_ca-$*.pem
+	certutil -A -d "sql:ssl/nss/native_server-$*.db/" -n ssl/native_server-$*.crt -t CTu,CTu,CTu -i ssl/nss/native_server_$*.der
+	rm nss_server_params.txt
+
+# Create and sign a client certificate
+ssl/nss/native_client-%.db: ssl/nss/native_ca-%.pem
+	$(MKDIR_P) ssl/nss/native_client-$*.db
+	certutil -N -d "sql:ssl/nss/native_client-$*.db/" --empty-password
+	certutil -R -d "sql:ssl/nss/native_client-$*.db/" -s "CN=ssltestuser,OU=PostgreSQL test suite" \
+		-o ssl/nss/native_client-$*.csr -g 2048 -Z SHA256 -z Makefile
+	certutil -C -d "sql:ssl/nss/native_ca-$*.db/" -c ca-$* -i ssl/nss/native_client-$*.csr -o ssl/nss/native_client-$*.der \
+		-m 5434 --keyUsage keyEncipherment,dataEncipherment,digitalSignature --nsCertType sslClient \
+		--certVersion 1 -Z SHA256
+	certutil -A -d "sql:ssl/nss/native_client-$*.db" -n ca-$* -t CTu,CTu,CTu -a -i ssl/nss/native_ca-$*.pem
+	certutil -A -d "sql:ssl/nss/native_client-$*.db" -n native_client-$* -t CTu,CTu,CTu -i ssl/nss/native_client-$*.der
+
+nssfiles2clean:
+	rm -rf ssl/nss
+
 .PHONY: sslfiles-clean
 sslfiles-clean:
 	rm -f $(SSLFILES) ssl/client_ca.srl ssl/server_ca.srl ssl/client_ca-certindex* ssl/server_ca-certindex* ssl/root_ca-certindex* ssl/root_ca.srl ssl/temp_ca.crt ssl/temp_ca_signed.crt
 
+.PHONY: nssfiles-clean
+nssfiles-clean:
+	rm -rf ssl/nss
+
 clean distclean maintainer-clean:
 	rm -rf tmp_check
 	rm -rf ssl/*.old ssl/new_certs_dir ssl/client*_tmp.key
+	rm -rf ssl/nss
 
 # Doesn't depend on $(SSLFILES) because we don't rebuild them by default
 check:
diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl
index fd2727b568..6b8bca2846 100644
--- a/src/test/ssl/t/001_ssltests.pl
+++ b/src/test/ssl/t/001_ssltests.pl
@@ -4,17 +4,24 @@ use PostgresNode;
 use TestLib;
 use Test::More;
 
-use File::Copy;
-
 use FindBin;
 use lib $FindBin::RealBin;
 
-use SSLServer;
+use SSL::Server;
+
+my $openssl;
+my $nss;
 
-if ($ENV{with_openssl} eq 'yes')
+if ($ENV{with_ssl} eq 'openssl')
 {
+	$openssl = 1;
 	plan tests => 93;
 }
+elsif ($ENV{with_ssl} eq 'nss')
+{
+	$nss = 1;
+	plan tests => 99;
+}
 else
 {
 	plan skip_all => 'SSL not supported by this build';
@@ -32,32 +39,6 @@ my $SERVERHOSTCIDR = '127.0.0.1/32';
 # Allocation of base connection string shared among multiple tests.
 my $common_connstr;
 
-# The client's private key must not be world-readable, so take a copy
-# of the key stored in the code tree and update its permissions.
-#
-# This changes ssl/client.key to ssl/client_tmp.key etc for the rest
-# of the tests.
-my @keys = (
-	"client",     "client-revoked",
-	"client-der", "client-encrypted-pem",
-	"client-encrypted-der");
-foreach my $key (@keys)
-{
-	copy("ssl/${key}.key", "ssl/${key}_tmp.key")
-	  or die
-	  "couldn't copy ssl/${key}.key to ssl/${key}_tmp.key for permissions change: $!";
-	chmod 0600, "ssl/${key}_tmp.key"
-	  or die "failed to change permissions on ssl/${key}_tmp.key: $!";
-}
-
-# Also make a copy of that explicitly world-readable.  We can't
-# necessarily rely on the file in the source tree having those
-# permissions.  Add it to @keys to include it in the final clean
-# up phase.
-copy("ssl/client.key", "ssl/client_wrongperms_tmp.key");
-chmod 0644, "ssl/client_wrongperms_tmp.key";
-push @keys, 'client_wrongperms';
-
 #### Set up the server.
 
 note "setting up data directory";
@@ -72,36 +53,65 @@ $node->start;
 
 # Run this before we lock down access below.
 my $result = $node->safe_psql('postgres', "SHOW ssl_library");
-is($result, 'OpenSSL', 'ssl_library parameter');
+is($result, SSL::Server::ssl_library(), 'ssl_library parameter');
 
 configure_test_server_for_ssl($node, $SERVERHOSTADDR, $SERVERHOSTCIDR,
 	'trust');
 
 note "testing password-protected keys";
 
-open my $sslconf, '>', $node->data_dir . "/sslconfig.conf";
-print $sslconf "ssl=on\n";
-print $sslconf "ssl_cert_file='server-cn-only.crt'\n";
-print $sslconf "ssl_key_file='server-password.key'\n";
-print $sslconf "ssl_passphrase_command='echo wrongpassword'\n";
-close $sslconf;
+# Since the passphrase callbacks operate at different stages in OpenSSL and
+# NSS we have two separate blocks for them.
+SKIP:
+{
+	skip "Certificate passphrases aren't checked on server restart in NSS", 2
+	  if ($nss);
+
+	set_server_cert($node, 'server-cn-only', 'root+client_ca',
+					   'server-password', 'echo wrongpassword');
+	command_fails(
+		[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
+		'restart fails with password-protected key file with wrong password');
+	$node->_update_pid(0);
+
+	set_server_cert($node, 'server-cn-only', 'root+client_ca',
+					'server-password', 'echo secret1');
+	command_ok(
+		[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
+		'restart succeeds with password-protected key file');
+	$node->_update_pid(1);
+}
 
-command_fails(
-	[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
-	'restart fails with password-protected key file with wrong password');
-$node->_update_pid(0);
+SKIP:
+{
+	skip "Certificate passphrases are checked on connection in NSS", 5
+	  if ($openssl);
 
-open $sslconf, '>', $node->data_dir . "/sslconfig.conf";
-print $sslconf "ssl=on\n";
-print $sslconf "ssl_cert_file='server-cn-only.crt'\n";
-print $sslconf "ssl_key_file='server-password.key'\n";
-print $sslconf "ssl_passphrase_command='echo secret1'\n";
-close $sslconf;
+	set_server_cert($node, 'server-cn-only', 'root+client_ca',
+					   'server-password', 'echo wrongpassword');
+	command_ok(
+		[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
+		'restart fails with password-protected key file with wrong password');
+	$node->_update_pid(1);
 
-command_ok(
-	[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
-	'restart succeeds with password-protected key file');
-$node->_update_pid(1);
+	test_connect_fails(
+		"user=ssltestuser dbname=trustdb sslcert=invalid hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test",
+		"sslrootcert=invalid sslmode=require",
+		qr/\QSSL error\E/,
+		"connect to server with incorrect key password configured");
+
+	set_server_cert($node, 'server-cn-only', 'root+client_ca',
+					   'server-password', 'echo secret1');
+	command_ok(
+		[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
+		'restart fails with password-protected key file with wrong password');
+	$node->_update_pid(1);
+
+	test_connect_ok(
+		"user=ssltestuser dbname=trustdb sslcert=invalid hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test",
+		"sslrootcert=invalid sslmode=require",
+		"connect to server with correct key password configured");
+}
 
 # Test compatibility of SSL protocols.
 # TLSv1.1 is lower than TLSv1.2, so it won't work.
@@ -149,82 +159,105 @@ test_connect_ok(
 test_connect_fails(
 	$common_connstr,
 	"sslrootcert=invalid sslmode=verify-ca",
-	qr/root certificate file "invalid" does not exist/,
+	qr/root certificate file "invalid" does not exist|Peer's Certificate issuer is not recognized/,
 	"connect without server root cert sslmode=verify-ca");
 test_connect_fails(
 	$common_connstr,
 	"sslrootcert=invalid sslmode=verify-full",
-	qr/root certificate file "invalid" does not exist/,
+	qr/root certificate file "invalid" does not exist|Peer's Certificate issuer is not recognized/,
 	"connect without server root cert sslmode=verify-full");
 
 # Try with wrong root cert, should fail. (We're using the client CA as the
 # root, but the server's key is signed by the server CA.)
-test_connect_fails($common_connstr,
-	"sslrootcert=ssl/client_ca.crt sslmode=require",
-	qr/SSL error/, "connect with wrong server root cert sslmode=require");
-test_connect_fails($common_connstr,
-	"sslrootcert=ssl/client_ca.crt sslmode=verify-ca",
-	qr/SSL error/, "connect with wrong server root cert sslmode=verify-ca");
-test_connect_fails($common_connstr,
-	"sslrootcert=ssl/client_ca.crt sslmode=verify-full",
-	qr/SSL error/, "connect with wrong server root cert sslmode=verify-full");
-
-# Try with just the server CA's cert. This fails because the root file
-# must contain the whole chain up to the root CA.
-test_connect_fails($common_connstr,
-	"sslrootcert=ssl/server_ca.crt sslmode=verify-ca",
-	qr/SSL error/, "connect with server CA cert, without root CA");
+test_connect_fails(
+	$common_connstr,
+	"sslrootcert=ssl/client_ca.crt sslmode=require cert_database=ssl/nss/client_ca.crt.db",
+	qr/SSL error/,
+	"connect with wrong server root cert sslmode=require");
+test_connect_fails(
+	$common_connstr,
+	"sslrootcert=ssl/client_ca.crt sslmode=verify-ca cert_database=ssl/nss/client_ca.crt.db",
+	qr/SSL error/,
+	"connect with wrong server root cert sslmode=verify-ca");
+test_connect_fails(
+	$common_connstr,
+	"sslrootcert=ssl/client_ca.crt sslmode=verify-full cert_database=ssl/nss/client_ca.crt.db",
+	qr/SSL error/,
+	"connect with wrong server root cert sslmode=verify-full");
+
+SKIP:
+{
+	# NSS supports partial chain validation, so this test doesn't work there.
+	# This is similar to the OpenSSL option X509_V_FLAG_PARTIAL_CHAIN which
+	# we don't allow.
+	skip "NSS support partial chain validation", 2 if ($nss);
+	# Try with just the server CA's cert. This fails because the root file
+	# must contain the whole chain up to the root CA.
+	test_connect_fails($common_connstr,
+		"sslrootcert=ssl/server_ca.crt sslmode=verify-ca",
+		qr/SSL error/, "connect with server CA cert, without root CA");
+}
 
 # And finally, with the correct root cert.
 test_connect_ok(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=require",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=require cert_database=ssl/nss/root+server_ca.crt.db",
 	"connect with correct server CA cert file sslmode=require");
 test_connect_ok(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca cert_database=ssl/nss/root+server_ca.crt.db",
 	"connect with correct server CA cert file sslmode=verify-ca");
 test_connect_ok(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-full",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-full cert_database=ssl/nss/root+server_ca.crt.db",
 	"connect with correct server CA cert file sslmode=verify-full");
 
-# Test with cert root file that contains two certificates. The client should
-# be able to pick the right one, regardless of the order in the file.
-test_connect_ok(
-	$common_connstr,
-	"sslrootcert=ssl/both-cas-1.crt sslmode=verify-ca",
-	"cert root file that contains two certificates, order 1");
-test_connect_ok(
-	$common_connstr,
-	"sslrootcert=ssl/both-cas-2.crt sslmode=verify-ca",
-	"cert root file that contains two certificates, order 2");
+SKIP:
+{
+	skip "CA ordering is irrelevant in NSS databases", 2 if ($nss);
 
+	# Test with cert root file that contains two certificates. The client should
+	# be able to pick the right one, regardless of the order in the file.
+	test_connect_ok(
+		$common_connstr,
+		"sslrootcert=ssl/both-cas-1.crt sslmode=verify-ca",
+		"cert root file that contains two certificates, order 1");
+
+	# How about import the both-file into a database?
+	test_connect_ok(
+		$common_connstr,
+		"sslrootcert=ssl/both-cas-2.crt sslmode=verify-ca",
+		"cert root file that contains two certificates, order 2");
+}
 # CRL tests
 
 # Invalid CRL filename is the same as no CRL, succeeds
 test_connect_ok(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=invalid",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=invalid cert_database=ssl/nss/root+server_ca.crt.db",
 	"sslcrl option with invalid file name");
 
-# A CRL belonging to a different CA is not accepted, fails
-test_connect_fails(
-	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/client.crl",
-	qr/SSL error/,
-	"CRL belonging to a different CA");
+SKIP:
+{
+	skip "CRL's are verified when adding to NSS database", 2 if ($nss);
+	# A CRL belonging to a different CA is not accepted, fails
+	test_connect_fails(
+		$common_connstr,
+		"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/client.crl",
+		qr/SSL error/,
+		"CRL belonging to a different CA");
+}
 
 # With the correct CRL, succeeds (this cert is not revoked)
 test_connect_ok(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/root+server.crl",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/root+server.crl cert_database=ssl/nss/root+server_ca.crt__root+server.crl.db",
 	"CRL with a non-revoked cert");
 
 # Check that connecting with verify-full fails, when the hostname doesn't
 # match the hostname in the server's certificate.
 $common_connstr =
-  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR";
+  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR cert_database=ssl/nss/root+server_ca.crt.db";
 
 test_connect_ok(
 	$common_connstr,
@@ -237,14 +270,14 @@ test_connect_ok(
 test_connect_fails(
 	$common_connstr,
 	"sslmode=verify-full host=wronghost.test",
-	qr/\Qserver certificate for "common-name.pg-ssltest.test" does not match host name "wronghost.test"\E/,
+	qr/\Qserver certificate for "common-name.pg-ssltest.test" does not match host name "wronghost.test"\E|requested domain name does not match the server's certificate/,
 	"mismatch between host name and server certificate sslmode=verify-full");
 
 # Test Subject Alternative Names.
 switch_server_cert($node, 'server-multiple-alt-names');
 
 $common_connstr =
-  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full";
+  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full cert_database=ssl/nss/root+server_ca.crt.db";
 
 test_connect_ok(
 	$common_connstr,
@@ -262,12 +295,12 @@ test_connect_ok(
 test_connect_fails(
 	$common_connstr,
 	"host=wronghost.alt-name.pg-ssltest.test",
-	qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "wronghost.alt-name.pg-ssltest.test"\E/,
+	qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "wronghost.alt-name.pg-ssltest.test"\E|requested domain name does not match the server's certificate/,
 	"host name not matching with X.509 Subject Alternative Names");
 test_connect_fails(
 	$common_connstr,
 	"host=deep.subdomain.wildcard.pg-ssltest.test",
-	qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E/,
+	qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E|requested domain name does not match the server's certificate/,
 	"host name not matching with X.509 Subject Alternative Names wildcard");
 
 # Test certificate with a single Subject Alternative Name. (this gives a
@@ -275,7 +308,7 @@ test_connect_fails(
 switch_server_cert($node, 'server-single-alt-name');
 
 $common_connstr =
-  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full";
+  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full cert_database=ssl/nss/root+server_ca.crt.db";
 
 test_connect_ok(
 	$common_connstr,
@@ -285,12 +318,12 @@ test_connect_ok(
 test_connect_fails(
 	$common_connstr,
 	"host=wronghost.alt-name.pg-ssltest.test",
-	qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "wronghost.alt-name.pg-ssltest.test"\E/,
+	qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "wronghost.alt-name.pg-ssltest.test"\E|requested domain name does not match the server's certificate/,
 	"host name not matching with a single X.509 Subject Alternative Name");
 test_connect_fails(
 	$common_connstr,
 	"host=deep.subdomain.wildcard.pg-ssltest.test",
-	qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E/,
+	qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E|requested domain name does not match the server's certificate/,
 	"host name not matching with a single X.509 Subject Alternative Name wildcard"
 );
 
@@ -299,7 +332,7 @@ test_connect_fails(
 switch_server_cert($node, 'server-cn-and-alt-names');
 
 $common_connstr =
-  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full";
+  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full cert_database=ssl/nss/root+server_ca.crt.db";
 
 test_connect_ok(
 	$common_connstr,
@@ -312,14 +345,14 @@ test_connect_ok(
 test_connect_fails(
 	$common_connstr,
 	"host=common-name.pg-ssltest.test",
-	qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 1 other name) does not match host name "common-name.pg-ssltest.test"\E/,
+	qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 1 other name) does not match host name "common-name.pg-ssltest.test"\E|requested domain name does not match the server's certificate/,
 	"certificate with both a CN and SANs ignores CN");
 
 # Finally, test a server certificate that has no CN or SANs. Of course, that's
 # not a very sensible certificate, but libpq should handle it gracefully.
 switch_server_cert($node, 'server-no-names');
 $common_connstr =
-  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR";
+  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR cert_database=ssl/nss/root+server_ca.crt.db";
 
 test_connect_ok(
 	$common_connstr,
@@ -328,7 +361,7 @@ test_connect_ok(
 test_connect_fails(
 	$common_connstr,
 	"sslmode=verify-full host=common-name.pg-ssltest.test",
-	qr/could not get server's host name from server certificate/,
+	qr/could not get server's host name from server certificate|requested domain name does not match the server's certificate./,
 	"server certificate without CN or SANs sslmode=verify-full");
 
 # Test that the CRL works
@@ -340,11 +373,11 @@ $common_connstr =
 # Without the CRL, succeeds. With it, fails.
 test_connect_ok(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca cert_database=ssl/nss/root+server_ca.crt.db",
 	"connects without client-side CRL");
 test_connect_fails(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/root+server.crl",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/server.crl cert_database=ssl/nss/root+server_ca.crt__server.crl.db",
 	qr/SSL error/,
 	"does not connect with client-side CRL");
 
@@ -365,32 +398,50 @@ command_like(
 # Test min/max SSL protocol versions.
 test_connect_ok(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=TLSv1.2 ssl_max_protocol_version=TLSv1.2",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=TLSv1.2 ssl_max_protocol_version=TLSv1.2 cert_database=ssl/nss/root+server_ca.crt.db",
 	"connection success with correct range of TLS protocol versions");
 test_connect_fails(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=TLSv1.2 ssl_max_protocol_version=TLSv1.1",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=TLSv1.2 ssl_max_protocol_version=TLSv1.1 cert_database=ssl/nss/root+server_ca.crt.db",
 	qr/invalid SSL protocol version range/,
 	"connection failure with incorrect range of TLS protocol versions");
 test_connect_fails(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=incorrect_tls",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=incorrect_tls cert_database=ssl/nss/root+server_ca.crt.db",
 	qr/invalid ssl_min_protocol_version value/,
 	"connection failure with an incorrect SSL protocol minimum bound");
 test_connect_fails(
 	$common_connstr,
-	"sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_max_protocol_version=incorrect_tls",
+	"sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_max_protocol_version=incorrect_tls cert_database=ssl/nss/root+server_ca.crt.db",
 	qr/invalid ssl_max_protocol_version value/,
 	"connection failure with an incorrect SSL protocol maximum bound");
 
+# tests of NSS generated certificates/keys
+SKIP:
+{
+	skip "NSS specific tests",            1 if ($openssl);
+
+	switch_server_cert($node, 'native_server-root', 'native_ca-root');
+	$common_connstr =
+	  "user=ssltestuser dbname=trustdb hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test";
+
+	test_connect_ok(
+		$common_connstr,
+		"sslmode=require user=ssltestuser",
+		"NSS generated certificates"
+	);
+}
+
 ### Server-side tests.
 ###
 ### Test certificate authorization.
 
+switch_server_cert($node, 'server-revoked');
+
 note "running server tests";
 
 $common_connstr =
-  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=certdb hostaddr=$SERVERHOSTADDR";
+  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=certdb hostaddr=$SERVERHOSTADDR cert_database=ssl/nss/client.crt__client.key.db";
 
 # no client cert
 test_connect_fails(
@@ -406,32 +457,43 @@ test_connect_ok(
 	"certificate authorization succeeds with correct client cert in PEM format"
 );
 
-# correct client cert in unencrypted DER
-test_connect_ok(
-	$common_connstr,
-	"user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-der_tmp.key",
-	"certificate authorization succeeds with correct client cert in DER format"
-);
+$common_connstr =
+  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=certdb hostaddr=$SERVERHOSTADDR";
+
+SKIP:
+{
+	skip "NSS database not implemented in the Makefile", 1 if ($nss);
+	# correct client cert in unencrypted DER
+	test_connect_ok(
+		$common_connstr,
+		"user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-der_tmp.key",
+		"certificate authorization succeeds with correct client cert in DER format"
+	);
+}
 
 # correct client cert in encrypted PEM
 test_connect_ok(
 	$common_connstr,
-	"user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-pem_tmp.key sslpassword='dUmmyP^#+'",
+	"user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-pem_tmp.key sslpassword='dUmmyP^#+' cert_database=ssl/nss/client.crt__client-encrypted-pem.key.db",
 	"certificate authorization succeeds with correct client cert in encrypted PEM format"
 );
 
-# correct client cert in encrypted DER
-test_connect_ok(
-	$common_connstr,
-	"user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-der_tmp.key sslpassword='dUmmyP^#+'",
-	"certificate authorization succeeds with correct client cert in encrypted DER format"
-);
+SKIP:
+{
+	skip "NSS database not implemented in the Makefile", 1 if ($nss);
+	# correct client cert in encrypted DER
+	test_connect_ok(
+		$common_connstr,
+		"user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-der_tmp.key sslpassword='dUmmyP^#+'",
+		"certificate authorization succeeds with correct client cert in encrypted DER format"
+	);
+}
 
 # correct client cert in encrypted PEM with wrong password
 test_connect_fails(
 	$common_connstr,
-	"user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-pem_tmp.key sslpassword='wrong'",
-	qr!\Qprivate key file "ssl/client-encrypted-pem_tmp.key": bad decrypt\E!,
+	"user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-pem_tmp.key sslpassword='wrong' cert_database=ssl/nss/client.crt__client-encrypted-pem.key.db",
+	qr!connection requires a valid client certificate|\Qprivate key file "ssl/client-encrypted-pem_tmp.key": bad decrypt\E!,
 	"certificate authorization fails with correct client cert and wrong password in encrypted PEM format"
 );
 
@@ -471,18 +533,19 @@ command_like(
 		'-P',
 		'null=_null_',
 		'-d',
-		"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client_tmp.key",
+		"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client_tmp.key cert_database=ssl/nss/client.crt__client.key.db",
 		'-c',
 		"SELECT * FROM pg_stat_ssl WHERE pid = pg_backend_pid()"
 	],
 	qr{^pid,ssl,version,cipher,bits,compression,client_dn,client_serial,issuer_dn\r?\n
-				^\d+,t,TLSv[\d.]+,[\w-]+,\d+,f,/CN=ssltestuser,1,\Q/CN=Test CA for PostgreSQL SSL regression test client certs\E\r?$}mx,
+				^\d+,t,TLSv[\d.]+,[\w-]+,\d+,f,/?CN=ssltestuser,1,/?\QCN=Test CA for PostgreSQL SSL regression test client certs\E\r?$}mx,
 	'pg_stat_ssl with client certificate');
 
 # client key with wrong permissions
 SKIP:
 {
 	skip "Permissions check not enforced on Windows", 2 if ($windows_os);
+	skip "Key not on filesystem with NSS",            2 if ($nss);
 
 	test_connect_fails(
 		$common_connstr,
@@ -495,10 +558,13 @@ SKIP:
 test_connect_fails(
 	$common_connstr,
 	"user=anotheruser sslcert=ssl/client.crt sslkey=ssl/client_tmp.key",
-	qr/certificate authentication failed for user "anotheruser"/,
+	qr/unable to verify certificate|certificate authentication failed for user "anotheruser"/,
 	"certificate authorization fails with client cert belonging to another user"
 );
 
+$common_connstr =
+  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=certdb hostaddr=$SERVERHOSTADDR cert_database=ssl/nss/client-revoked.crt__client-revoked.key.db";
+
 # revoked client cert
 test_connect_fails(
 	$common_connstr,
@@ -510,7 +576,7 @@ test_connect_fails(
 # works, iff username matches Common Name
 # fails, iff username doesn't match Common Name.
 $common_connstr =
-  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=verifydb hostaddr=$SERVERHOSTADDR";
+  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=verifydb hostaddr=$SERVERHOSTADDR cert_database=ssl/nss/client.crt__client.key.db";
 
 test_connect_ok(
 	$common_connstr,
@@ -536,17 +602,23 @@ test_connect_ok(
 # intermediate client_ca.crt is provided by client, and isn't in server's ssl_ca_file
 switch_server_cert($node, 'server-cn-only', 'root_ca');
 $common_connstr =
-  "user=ssltestuser dbname=certdb sslkey=ssl/client_tmp.key sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR";
+  "user=ssltestuser dbname=certdb sslkey=ssl/client_tmp.key sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR cert_database=ssl/nss/client+client_ca.crt__client.key.db";
 
-test_connect_ok(
+TODO:
+{
+	local $TODO = "WIP failure cause currently unknown";
+	test_connect_ok(
+		$common_connstr,
+		"sslmode=require sslcert=ssl/client+client_ca.crt",
+		"intermediate client certificate is provided by client");
+}
+
+test_connect_fails(
 	$common_connstr,
-	"sslmode=require sslcert=ssl/client+client_ca.crt",
-	"intermediate client certificate is provided by client");
-test_connect_fails($common_connstr, "sslmode=require sslcert=ssl/client.crt",
-	qr/SSL error/, "intermediate client certificate is missing");
+	"sslmode=require sslcert=ssl/client.crt",
+	qr/connection requires a valid client certificate|SSL error/,
+	"intermediate client certificate is missing");
 
 # clean up
-foreach my $key (@keys)
-{
-	unlink("ssl/${key}_tmp.key");
-}
+
+SSL::Server::cleanup();
diff --git a/src/test/ssl/t/002_scram.pl b/src/test/ssl/t/002_scram.pl
index a088f71a1a..cf5714e544 100644
--- a/src/test/ssl/t/002_scram.pl
+++ b/src/test/ssl/t/002_scram.pl
@@ -11,24 +11,39 @@ use File::Copy;
 use FindBin;
 use lib $FindBin::RealBin;
 
-use SSLServer;
+use SSL::Server;
 
-if ($ENV{with_openssl} ne 'yes')
+my $openssl;
+my $nss;
+
+my $supports_tls_server_end_point;
+
+if ($ENV{with_ssl} eq 'no')
 {
 	plan skip_all => 'SSL not supported by this build';
 }
+else
+{
+	if ($ENV{with_ssl} eq 'openssl')
+	{
+		$openssl = 1;
+		# Determine whether build supports tls-server-end-point.
+		$supports_tls_server_end_point =
+			check_pg_config("#define HAVE_X509_GET_SIGNATURE_NID 1");
+		plan tests => $supports_tls_server_end_point ? 9 : 10;
+	}
+	elsif ($ENV{with_ssl} eq 'nss')
+	{
+		$nss = 1;
+		plan tests => 8;
+	}
+}
 
 # This is the hostname used to connect to the server.
 my $SERVERHOSTADDR = '127.0.0.1';
 # This is the pattern to use in pg_hba.conf to match incoming connections.
 my $SERVERHOSTCIDR = '127.0.0.1/32';
 
-# Determine whether build supports tls-server-end-point.
-my $supports_tls_server_end_point =
-  check_pg_config("#define HAVE_X509_GET_SIGNATURE_NID 1");
-
-my $number_of_tests = $supports_tls_server_end_point ? 9 : 10;
-
 # Allocation of base connection string shared among multiple tests.
 my $common_connstr;
 
@@ -66,20 +81,25 @@ test_connect_ok(
 	$common_connstr,
 	"user=ssltestuser channel_binding=disable",
 	"SCRAM with SSL and channel_binding=disable");
-if ($supports_tls_server_end_point)
-{
-	test_connect_ok(
-		$common_connstr,
-		"user=ssltestuser channel_binding=require",
-		"SCRAM with SSL and channel_binding=require");
-}
-else
+
+SKIP:
 {
-	test_connect_fails(
-		$common_connstr,
-		"user=ssltestuser channel_binding=require",
-		qr/channel binding is required, but server did not offer an authentication method that supports channel binding/,
-		"SCRAM with SSL and channel_binding=require");
+	skip "NSS support for TLS server endpoing is not implemented", 1 if ($nss);
+	if ($supports_tls_server_end_point)
+	{
+		test_connect_ok(
+			$common_connstr,
+			"user=ssltestuser channel_binding=require",
+			"SCRAM with SSL and channel_binding=require");
+	}
+	else
+	{
+		test_connect_fails(
+			$common_connstr,
+			"user=ssltestuser channel_binding=require",
+			qr/channel binding is required, but server did not offer an authentication method that supports channel binding/,
+			"SCRAM with SSL and channel_binding=require");
+	}
 }
 
 # Now test when the user has an MD5-encrypted password; should fail
@@ -89,20 +109,21 @@ test_connect_fails(
 	qr/channel binding required but not supported by server's authentication request/,
 	"MD5 with SSL and channel_binding=require");
 
-# Now test with auth method 'cert' by connecting to 'certdb'. Should fail,
-# because channel binding is not performed.  Note that ssl/client.key may
-# be used in a different test, so the name of this temporary client key
-# is chosen here to be unique.
-my $client_tmp_key = "ssl/client_scram_tmp.key";
-copy("ssl/client.key", $client_tmp_key);
-chmod 0600, $client_tmp_key;
-test_connect_fails(
-	"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR",
-	"dbname=certdb user=ssltestuser channel_binding=require",
-	qr/channel binding required, but server authenticated client without channel binding/,
-	"Cert authentication and channel_binding=require");
-
-# clean up
-unlink($client_tmp_key);
-
-done_testing($number_of_tests);
+SKIP:
+{
+	skip "NSS support not implemented yet", 1 if ($nss);
+	# Now test with auth method 'cert' by connecting to 'certdb'. Should fail,
+	# because channel binding is not performed.  Note that ssl/client.key may
+	# be used in a different test, so the name of this temporary client key
+	# is chosen here to be unique.
+	my $client_tmp_key = "ssl/client_scram_tmp.key";
+	copy("ssl/client.key", $client_tmp_key);
+	chmod 0600, $client_tmp_key;
+	test_connect_fails(
+		"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR",
+		"dbname=certdb user=ssltestuser channel_binding=require",
+		qr/channel binding required, but server authenticated client without channel binding/,
+		"Cert authentication and channel_binding=require");
+	# clean up
+	unlink($client_tmp_key);
+}
diff --git a/src/test/ssl/t/SSL/Backend/NSS.pm b/src/test/ssl/t/SSL/Backend/NSS.pm
new file mode 100644
index 0000000000..c5b31e584a
--- /dev/null
+++ b/src/test/ssl/t/SSL/Backend/NSS.pm
@@ -0,0 +1,73 @@
+package SSL::Backend::NSS;
+
+use strict;
+use warnings;
+use Exporter;
+
+our @ISA       = qw(Exporter);
+our @EXPORT_OK = qw(get_new_nss_backend);
+
+sub new
+{
+	my ($class) = @_;
+
+	my $self = { _library => 'NSS' };
+
+	bless $self, $class;
+
+	return $self;
+}
+
+sub get_new_nss_backend
+{
+	my $class = 'SSL::Backend::NSS';
+
+	return $class->new();
+}
+
+sub init
+{
+	# Make sure the certificate databases are in place?
+}
+
+sub get_library
+{
+	my ($self) = @_;
+
+	return $self->{_library};
+}
+
+sub set_server_cert
+{
+	my $self     = $_[0];
+	my $certfile = $_[1];
+	my $cafile   = $_[2];
+	my $keyfile  = $_[3];
+
+	my $cert_nickname;
+
+	if ($certfile =~ /native/)
+	{
+		$cert_nickname = $certfile;
+	}
+	else
+	{
+		$cert_nickname = $certfile . '.crt__' . $keyfile . '.key';
+	}
+	my $cert_database = $cert_nickname . '.db';
+
+	my $sslconf =
+	    "ssl_ca_file='$cafile.crt'\n"
+	  . "ssl_cert_file='ssl/$certfile.crt'\n"
+	  . "ssl_crl_file=''\n"
+	  . "ssl_database='nss/$cert_database'\n";
+
+	return $sslconf;
+}
+
+sub cleanup
+{
+	# Something?
+}
+
+1;
diff --git a/src/test/ssl/t/SSL/Backend/OpenSSL.pm b/src/test/ssl/t/SSL/Backend/OpenSSL.pm
new file mode 100644
index 0000000000..62b11b7632
--- /dev/null
+++ b/src/test/ssl/t/SSL/Backend/OpenSSL.pm
@@ -0,0 +1,103 @@
+package SSL::Backend::OpenSSL;
+
+use strict;
+use warnings;
+use Exporter;
+use File::Copy;
+
+our @ISA       = qw(Exporter);
+our @EXPORT_OK = qw(get_new_openssl_backend);
+
+our (@keys);
+
+INIT
+{
+	@keys = (
+		"client",     "client-revoked",
+		"client-der", "client-encrypted-pem",
+		"client-encrypted-der");
+}
+
+sub new
+{
+	my ($class) = @_;
+
+	my $self = { _library => 'OpenSSL' };
+
+	bless $self, $class;
+
+	return $self;
+}
+
+sub get_new_openssl_backend
+{
+	my $class = 'SSL::Backend::OpenSSL';
+
+	my $backend = $class->new();
+
+	return $backend;
+}
+
+sub init
+{
+	# The client's private key must not be world-readable, so take a copy
+	# of the key stored in the code tree and update its permissions.
+	#
+	# This changes ssl/client.key to ssl/client_tmp.key etc for the rest
+	# of the tests.
+	foreach my $key (@keys)
+	{
+		copy("ssl/${key}.key", "ssl/${key}_tmp.key")
+		  or die
+		  "couldn't copy ssl/${key}.key to ssl/${key}_tmp.key for permissions change: $!";
+		chmod 0600, "ssl/${key}_tmp.key"
+		  or die "failed to change permissions on ssl/${key}_tmp.key: $!";
+	}
+
+	# Also make a copy of that explicitly world-readable.  We can't
+	# necessarily rely on the file in the source tree having those
+	# permissions. Add it to @keys to include it in the final clean
+	# up phase.
+	copy("ssl/client.key", "ssl/client_wrongperms_tmp.key")
+	  or die
+	  "couldn't copy ssl/client.key to ssl/client_wrongperms_tmp.key: $!";
+	chmod 0644, "ssl/client_wrongperms_tmp.key"
+	  or die
+	  "failed to change permissions on ssl/client_wrongperms_tmp.key: $!";
+	push @keys, 'client_wrongperms';
+}
+
+# Change the configuration to use given server cert file, and reload
+# the server so that the configuration takes effect.
+sub set_server_cert
+{
+	my $self     = $_[0];
+	my $certfile = $_[1];
+	my $cafile   = $_[2] || "root+client_ca";
+	my $keyfile  = $_[3] || $certfile;
+
+	my $sslconf =
+	    "ssl_ca_file='$cafile.crt'\n"
+	  . "ssl_cert_file='$certfile.crt'\n"
+	  . "ssl_key_file='$keyfile.key'\n"
+	  . "ssl_crl_file='root+client.crl'\n";
+
+	return $sslconf;
+}
+
+sub get_library
+{
+	my ($self) = @_;
+
+	return $self->{_library};
+}
+
+sub cleanup
+{
+	foreach my $key (@keys)
+	{
+		unlink("ssl/${key}_tmp.key");
+	}
+}
+
+1;
diff --git a/src/test/ssl/t/SSLServer.pm b/src/test/ssl/t/SSL/Server.pm
similarity index 78%
rename from src/test/ssl/t/SSLServer.pm
rename to src/test/ssl/t/SSL/Server.pm
index f5987a003e..ee901855b5 100644
--- a/src/test/ssl/t/SSLServer.pm
+++ b/src/test/ssl/t/SSL/Server.pm
@@ -23,19 +23,39 @@
 # explicitly because an invalid sslcert or sslrootcert, respectively,
 # causes those to be ignored.)
 
-package SSLServer;
+package SSL::Server;
 
 use strict;
 use warnings;
 use PostgresNode;
+use RecursiveCopy;
 use TestLib;
 use File::Basename;
 use File::Copy;
 use Test::More;
+use SSL::Backend::OpenSSL qw(get_new_openssl_backend);
+use SSL::Backend::NSS qw(get_new_nss_backend);
+
+our ($openssl, $nss, $backend);
+
+# The TLS backend which the server is using should be mostly transparent for
+# the user, apart from individual configuration settings, so keep the backend
+# specific things abstracted behind SSL::Server.
+if ($ENV{with_ssl} eq 'openssl')
+{
+	$backend = get_new_openssl_backend();
+	$openssl = 1;
+}
+elsif ($ENV{with_ssl} eq 'nss')
+{
+	$backend = get_new_nss_backend();
+	$nss     = 1;
+}
 
 use Exporter 'import';
 our @EXPORT = qw(
   configure_test_server_for_ssl
+  set_server_cert
   switch_server_cert
   test_connect_fails
   test_connect_ok
@@ -144,12 +164,19 @@ sub configure_test_server_for_ssl
 	close $sslconf;
 
 	# Copy all server certificates and keys, and client root cert, to the data dir
-	copy_files("ssl/server-*.crt", $pgdata);
-	copy_files("ssl/server-*.key", $pgdata);
-	chmod(0600, glob "$pgdata/server-*.key") or die $!;
-	copy_files("ssl/root+client_ca.crt", $pgdata);
-	copy_files("ssl/root_ca.crt",        $pgdata);
-	copy_files("ssl/root+client.crl",    $pgdata);
+	if (defined($openssl))
+	{
+		copy_files("ssl/server-*.crt", $pgdata);
+		copy_files("ssl/server-*.key", $pgdata);
+		chmod(0600, glob "$pgdata/server-*.key") or die $!;
+		copy_files("ssl/root+client_ca.crt", $pgdata);
+		copy_files("ssl/root_ca.crt",        $pgdata);
+		copy_files("ssl/root+client.crl",    $pgdata);
+	}
+	elsif (defined($nss))
+	{
+		RecursiveCopy::copypath("ssl/nss", $pgdata . "/nss") if -e "ssl/nss";
+	}
 
 	# Stop and restart server to load new listen_addresses.
 	$node->restart;
@@ -157,26 +184,51 @@ sub configure_test_server_for_ssl
 	# Change pg_hba after restart because hostssl requires ssl=on
 	configure_hba_for_ssl($node, $servercidr, $authmethod);
 
+	# Finally, perform backend specific configuration
+	$backend->init();
+
 	return;
 }
 
-# Change the configuration to use given server cert file, and reload
-# the server so that the configuration takes effect.
-sub switch_server_cert
+sub ssl_library
+{
+	return $backend->get_library();
+}
+
+sub cleanup
+{
+	$backend->cleanup();
+}
+
+# Change the configuration to use given server cert file,
+sub set_server_cert
 {
 	my $node     = $_[0];
 	my $certfile = $_[1];
 	my $cafile   = $_[2] || "root+client_ca";
+	my $keyfile  = $_[3] || '';
+	my $pwcmd    = $_[4] || '';
 	my $pgdata   = $node->data_dir;
 
+	$keyfile = $certfile if $keyfile eq '';
+
 	open my $sslconf, '>', "$pgdata/sslconfig.conf";
 	print $sslconf "ssl=on\n";
-	print $sslconf "ssl_ca_file='$cafile.crt'\n";
-	print $sslconf "ssl_cert_file='$certfile.crt'\n";
-	print $sslconf "ssl_key_file='$certfile.key'\n";
-	print $sslconf "ssl_crl_file='root+client.crl'\n";
+	print $sslconf $backend->set_server_cert($certfile, $cafile, $keyfile);
+	print $sslconf "ssl_passphrase_command='$pwcmd'\n"
+	  unless $pwcmd eq '';
 	close $sslconf;
+	return;
+}
 
+# Change the configuration to use given server cert file, and reload
+# the server so that the configuration takes effect.
+# Takes the same arguments as set_server_cert, which it calls to do that
+# piece of the work.
+sub switch_server_cert
+{
+	my $node = $_[0];
+	set_server_cert(@_);
 	$node->restart;
 	return;
 }
-- 
2.25.1

From 7cb545431b5d392e986c81a6253e44b24fd8b8d1 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:24:02 +0100
Subject: [PATCH v23 3/6] NSS pg_strong_random support

---
 configure                   |  3 ++-
 configure.ac                |  3 ++-
 src/include/pg_config.h.in  |  3 +++
 src/port/pg_strong_random.c | 50 ++++++++++++++++++++++++++++++++++++-
 4 files changed, 56 insertions(+), 3 deletions(-)

diff --git a/configure b/configure
index cc6088b545..876a0ea839 100755
--- a/configure
+++ b/configure
@@ -18441,6 +18441,7 @@ $as_echo "NSS" >&6; }
 elif test x"$PORTNAME" = x"win32" ; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: Windows native" >&5
 $as_echo "Windows native" >&6; }
+
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: /dev/urandom" >&5
 $as_echo "/dev/urandom" >&6; }
@@ -18467,7 +18468,7 @@ fi
   if test x"$ac_cv_file__dev_urandom" = x"no" ; then
     as_fn_error $? "
 no source of strong random numbers was found
-PostgreSQL can use OpenSSL, native Windows API or /dev/urandom as a source of random numbers." "$LINENO" 5
+PostgreSQL can use OpenSSL, NSS, native Windows API or /dev/urandom as a source of random numbers." "$LINENO" 5
   fi
 fi
 
diff --git a/configure.ac b/configure.ac
index 0da8cc9b0b..6b6641a094 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2203,6 +2203,7 @@ elif test x"$with_nss" = x"yes" ; then
   AC_MSG_RESULT([NSS])
 elif test x"$PORTNAME" = x"win32" ; then
   AC_MSG_RESULT([Windows native])
+
 else
   AC_MSG_RESULT([/dev/urandom])
   AC_CHECK_FILE([/dev/urandom], [], [])
@@ -2210,7 +2211,7 @@ else
   if test x"$ac_cv_file__dev_urandom" = x"no" ; then
     AC_MSG_ERROR([
 no source of strong random numbers was found
-PostgreSQL can use OpenSSL, native Windows API or /dev/urandom as a source of random numbers.])
+PostgreSQL can use OpenSSL, NSS, native Windows API or /dev/urandom as a source of random numbers.])
   fi
 fi
 
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index 67a9f90e5e..0894ff2bef 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -908,6 +908,9 @@
 /* Define to build with NSS support (--with-nss) */
 #undef USE_NSS
 
+/* Define to use NSS for random number generation */
+#undef USE_NSS_RANDOM
+
 /* Define to 1 to use software CRC-32C implementation (slicing-by-8). */
 #undef USE_SLICING_BY_8_CRC32C
 
diff --git a/src/port/pg_strong_random.c b/src/port/pg_strong_random.c
index 07f24c0089..40de237628 100644
--- a/src/port/pg_strong_random.c
+++ b/src/port/pg_strong_random.c
@@ -137,7 +137,55 @@ pg_strong_random(void *buf, size_t len)
 	return false;
 }
 
-#else							/* not USE_OPENSSL or WIN32 */
+#elif defined(USE_NSS)
+
+#define pg_BITS_PER_BYTE BITS_PER_BYTE
+#undef BITS_PER_BYTE
+#define NO_NSPR_10_SUPPORT
+#include <nss/nss.h>
+#include <nss/pk11pub.h>
+#if defined(BITS_PER_BYTE)
+#if BITS_PER_BYTE != pg_BITS_PER_BYTE
+#error "incompatible byte widths between NSPR and postgres"
+#endif
+#else
+#define BITS_PER_BYTE pg_BITS_PER_BYTE
+#endif
+#undef pg_BITS_PER_BYTE
+
+void
+pg_strong_random_init(void)
+{
+	/* No initialization needed on NSS */
+}
+
+bool
+pg_strong_random(void *buf, size_t len)
+{
+	NSSInitParameters params;
+	NSSInitContext *nss_context;
+	SECStatus	status;
+
+	memset(&params, 0, sizeof(params));
+	params.length = sizeof(params);
+	nss_context = NSS_InitContext("", "", "", "", &params,
+								  NSS_INIT_READONLY | NSS_INIT_NOCERTDB |
+								  NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN |
+								  NSS_INIT_NOROOTINIT | NSS_INIT_PK11RELOAD);
+
+	if (!nss_context)
+		return false;
+
+	status = PK11_GenerateRandom(buf, len);
+	NSS_ShutdownContext(nss_context);
+
+	if (status == SECSuccess)
+		return true;
+
+	return false;
+}
+
+#else							/* not USE_OPENSSL, USE_NSS or WIN32 */
 
 /*
  * Without OpenSSL or Win32 support, just read /dev/urandom ourselves.
-- 
2.25.1

From 5d06d659a102948b5d69071749a3b463e354fb1f Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:26:31 +0100
Subject: [PATCH v23 4/6] NSS Documentation

---
 doc/src/sgml/acronyms.sgml     |  43 ++++++++++++
 doc/src/sgml/config.sgml       |  28 +++++++-
 doc/src/sgml/installation.sgml |  30 +++++++-
 doc/src/sgml/libpq.sgml        |  99 +++++++++++++++++++++++++-
 doc/src/sgml/runtime.sgml      | 123 +++++++++++++++++++++++++++++++--
 5 files changed, 311 insertions(+), 12 deletions(-)

diff --git a/doc/src/sgml/acronyms.sgml b/doc/src/sgml/acronyms.sgml
index 4e5ec983c0..7b02c8a622 100644
--- a/doc/src/sgml/acronyms.sgml
+++ b/doc/src/sgml/acronyms.sgml
@@ -441,6 +441,28 @@
     </listitem>
    </varlistentry>
 
+   <varlistentry>
+    <term><acronym>NSPR</acronym></term>
+    <listitem>
+     <para>
+      <ulink
+      url="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR">
+      Netscape Portable Runtime</ulink>
+     </para>
+    </listitem>
+   </varlistentry>
+
+   <varlistentry>
+    <term><acronym>NSS</acronym></term>
+    <listitem>
+     <para>
+      <ulink
+      url="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS">
+      Network Security Services</ulink>
+     </para>
+    </listitem>
+   </varlistentry>
+
    <varlistentry>
     <term><acronym>ODBC</acronym></term>
     <listitem>
@@ -539,6 +561,17 @@
     </listitem>
    </varlistentry>
 
+   <varlistentry>
+    <term><acronym>PKCS#12</acronym></term>
+    <listitem>
+     <para>
+      <ulink
+      url="https://en.wikipedia.org/wiki/PKCS_12">
+      Public-Key Cryptography Standards #12</ulink>
+     </para>
+    </listitem>
+   </varlistentry>
+
    <varlistentry>
     <term><acronym>PL</acronym></term>
     <listitem>
@@ -684,6 +717,16 @@
     </listitem>
    </varlistentry>
 
+   <varlistentry>
+    <term><acronym>TLS</acronym></term>
+    <listitem>
+     <para>
+      <ulink url="https://en.wikipedia.org/wiki/Transport_Layer_Security">
+      Transport Layer Security</ulink>
+     </para>
+    </listitem>
+   </varlistentry>
+
    <varlistentry>
     <term><acronym>TOAST</acronym></term>
     <listitem>
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 82864bbb24..6738f8001f 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -1236,6 +1236,23 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
+     <varlistentry id="guc-ssl-database" xreflabel="ssl_database">
+      <term><varname>ssl_database</varname> (<type>string</type>)
+      <indexterm>
+       <primary><varname>ssl_database</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+       <para>
+        Specifies the name of the file containing the server certificates and
+        keys when using <productname>NSS</productname> for <acronym>SSL</acronym>
+        connections. This parameter can only be set in the
+        <filename>postgresql.conf</filename> file or on the server command
+        line.
+       </para>
+      </listitem>
+     </varlistentry>
+
      <varlistentry id="guc-ssl-ciphers" xreflabel="ssl_ciphers">
       <term><varname>ssl_ciphers</varname> (<type>string</type>)
       <indexterm>
@@ -1252,7 +1269,9 @@ include_dir 'conf.d'
         connections using TLS version 1.2 and lower are affected.  There is
         currently no setting that controls the cipher choices used by TLS
         version 1.3 connections.  The default value is
-        <literal>HIGH:MEDIUM:+3DES:!aNULL</literal>.  The default is usually a
+        <literal>HIGH:MEDIUM:+3DES:!aNULL</literal> for servers which have
+        been built with <productname>OpenSSL</productname> as the
+        <acronym>SSL</acronym> library.  The default is usually a
         reasonable choice unless you have specific security requirements.
        </para>
 
@@ -1454,8 +1473,11 @@ include_dir 'conf.d'
        <para>
         Sets an external command to be invoked when a passphrase for
         decrypting an SSL file such as a private key needs to be obtained.  By
-        default, this parameter is empty, which means the built-in prompting
-        mechanism is used.
+        default, this parameter is empty. When the server is using
+        <productname>OpenSSL</productname>, this means the built-in prompting
+        mechanism is used. When using <productname>NSS</productname>, there is
+        no default prompting so a blank callback will be used returning an
+        empty password.
        </para>
        <para>
         The command must print the passphrase to the standard output and exit
diff --git a/doc/src/sgml/installation.sgml b/doc/src/sgml/installation.sgml
index 0ac1cb9999..bd09124fb0 100644
--- a/doc/src/sgml/installation.sgml
+++ b/doc/src/sgml/installation.sgml
@@ -250,7 +250,7 @@ su - postgres
 
     <listitem>
      <para>
-      You need <productname>OpenSSL</productname>, if you want to support
+      You need a supported <acronym>SSL</acronym> library, if you want to support
       encrypted client connections.  <productname>OpenSSL</productname> is
       also required for random number generation on platforms that do not
       have <filename>/dev/urandom</filename> (except Windows).  The minimum
@@ -966,6 +966,31 @@ build-postgresql:
        </listitem>
       </varlistentry>
 
+      <varlistentry>
+       <term><option>--with-nss</option>
+       <indexterm>
+        <primary>NSS</primary>
+        <secondary>NSPR</secondary>
+        <seealso>SSL</seealso>
+       </indexterm>
+       </term>
+       <listitem>
+        <para>
+         Build with support for <acronym>SSL</acronym> (encrypted)
+         connections using <productname>NSS</productname>. This requires the
+         <productname>NSS</productname> package to be installed. Additionally,
+         <productname>NSS</productname> requires <productname>NSPR</productname>
+         to be installed. <filename>configure</filename> will check for the
+         required header files and libraries to make sure that your
+         <productname>NSS</productname> installation is sufficient before
+         proceeding.
+        </para>
+        <para>
+         This option is incompatible with <literal>--with-openssl</literal>.
+        </para>
+       </listitem>
+      </varlistentry>
+
       <varlistentry>
        <term><option>--with-openssl</option>
        <indexterm>
@@ -982,6 +1007,9 @@ build-postgresql:
          your <productname>OpenSSL</productname> installation is sufficient
          before proceeding.
         </para>
+        <para>
+         This option is incompatible with <literal>--with-nss</literal>.
+        </para>
        </listitem>
       </varlistentry>
 
diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml
index 2bb3bf77e4..3225736f56 100644
--- a/doc/src/sgml/libpq.sgml
+++ b/doc/src/sgml/libpq.sgml
@@ -830,6 +830,12 @@ int callback_fn(char *buf, int size, PGconn *conn);
        <function>longjmp(...)</function>, etc. It must return normally.
       </para>
 
+      <para>
+        <function>PQsetSSLKeyPassHook_OpenSSL</function> is only available
+        when the server was compiled with <productname>OpenSSL</productname>
+        support.
+      </para>
+
      </listitem>
     </varlistentry>
 
@@ -846,6 +852,72 @@ PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
 </synopsis>
       </para>
 
+      <para>
+        <function>PQgetSSLKeyPassHook_OpenSSL</function> is only available
+        when the server was compiled with <productname>OpenSSL</productname>
+        support.
+      </para>
+
+     </listitem>
+    </varlistentry>
+
+    <varlistentry id="libpq-pqsetsslkeypasshook-nss">
+     <term><function>PQsetSSLKeyPassHook_nss</function><indexterm><primary>PQsetSSLKeyPassHook_nss</primary></indexterm></term>
+     <listitem>
+      <para>
+       <function>PQsetSSLKeyPassHook_nss</function> lets an application override
+       <application>libpq</application>'s default handling of password protected
+       objects in the <application>NSS</application> database using
+       <xref linkend="libpq-connect-sslpassword"/> or interactive prompting.
+
+<synopsis>
+void PQsetSSLKeyPassHook_nss(PQsslKeyPassHook_nss_type hook);
+</synopsis>
+
+       The application passes a pointer to a callback function with signature:
+<programlisting>
+char *callback_fn(PK11SlotInfo *slot, PRBool retry, void *arg);
+</programlisting>
+       which <application>libpq</application> will call
+       <emphasis>instead of</emphasis> its default
+       <function>PQdefaultSSLKeyPassHook_nss</function> password handler. The
+       callback should determine the password for the token and return a
+       pointer to it. The returned pointer should be allocated with the NSS
+       <function>PORT_Strdup</function> function. The token for which the
+       password is requested is recorded in the slot anc can be identified by
+       calling <function>PK11_GetTokenName</function>. If no password is
+       known, the callback should return <literal>NULL</literal>. The memory
+       will be owned by <productname>NSS</productname> and should not be
+       freed.
+      </para>
+
+      <para>
+        <function>PQsetSSLKeyPassHook_nss</function> is only available
+        when the server was compiled with <productname>NSS</productname>
+        support.
+      </para>
+     </listitem>
+    </varlistentry>
+
+    <varlistentry id="libpq-pqgetsslkeypasshook-nss">
+     <term><function>PQgetSSLKeyPassHook_nss</function><indexterm><primary>PQgetSSLKeyPassHook_nss</primary></indexterm></term>
+     <listitem>
+      <para>
+       <function>PQgetSSLKeyPassHook_nss</function> returns the current
+       <productname>NSS</productname> password hook, or <literal>NULL</literal>
+       if none has been set.
+
+<synopsis>
+PQsslKeyPassHook_nss_type PQgetSSLKeyPassHook_nss(void);
+</synopsis>
+      </para>
+
+      <para>
+        <function>PQgetSSLKeyPassHook_nss</function> is only available
+        when the server was compiled with <productname>nss</productname>
+        support.
+      </para>
+
      </listitem>
     </varlistentry>
 
@@ -2497,6 +2569,8 @@ void *PQsslStruct(const PGconn *conn, const char *struct_name);
       </para>
       <para>
        The struct(s) available depend on the SSL implementation in use.
+      </para>
+      <para>
        For <productname>OpenSSL</productname>, there is one struct,
        available under the name "OpenSSL", and it returns a pointer to the
        <productname>OpenSSL</productname> <literal>SSL</literal> struct.
@@ -2520,9 +2594,14 @@ void *PQsslStruct(const PGconn *conn, const char *struct_name);
 ]]></programlisting>
       </para>
       <para>
-       This structure can be used to verify encryption levels, check server
-       certificates, and more. Refer to the <productname>OpenSSL</productname>
-       documentation for information about this structure.
+       For <productname>NSS</productname>, there is one struct available under
+       the name "NSS", and it returns a pointer to the
+       <productname>NSS</productname> <literal>PRFileDesc</literal>.
+      </para>
+      <para>
+       These structures can be used to verify encryption levels, check server
+       certificates, and more. Refer to the <acronym>SSL</acronym> library
+       documentation for information about these structures.
       </para>
      </listitem>
     </varlistentry>
@@ -2549,6 +2628,10 @@ void *PQgetssl(const PGconn *conn);
        <xref linkend="libpq-PQsslInUse"/> instead, and for more details about the
        connection, use <xref linkend="libpq-PQsslAttribute"/>.
       </para>
+      <para>
+       This function returns <literal>NULL</literal> when <acronym>SSL</acronym>
+       librariaes other than <productname>OpenSSL</productname> are used.
+      </para>
      </listitem>
     </varlistentry>
 
@@ -7982,6 +8065,11 @@ void PQinitOpenSSL(int do_ssl, int do_crypto);
        before first opening a database connection.  Also be sure that you
        have done that initialization before opening a database connection.
       </para>
+
+      <para>
+       This function does nothing when using <productname>NSS</productname> as
+       the <acronym>SSL</acronym> library.
+      </para>
      </listitem>
     </varlistentry>
 
@@ -8008,6 +8096,11 @@ void PQinitSSL(int do_ssl);
        might be preferable for applications that need to work with older
        versions of <application>libpq</application>.
       </para>
+
+      <para>
+       This function does nothing when using <productname>NSS</productname> as
+       the <acronym>SSL</acronym> library.
+      </para>
      </listitem>
     </varlistentry>
    </variablelist>
diff --git a/doc/src/sgml/runtime.sgml b/doc/src/sgml/runtime.sgml
index 283352d3a4..0900ebf28f 100644
--- a/doc/src/sgml/runtime.sgml
+++ b/doc/src/sgml/runtime.sgml
@@ -2183,15 +2183,21 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
 
   <indexterm zone="ssl-tcp">
    <primary>SSL</primary>
+   <secondary>TLS</secondary>
   </indexterm>
 
   <para>
    <productname>PostgreSQL</productname> has native support for using
    <acronym>SSL</acronym> connections to encrypt client/server communications
    for increased security. This requires that
-   <productname>OpenSSL</productname> is installed on both client and
+   a supported TLS library is installed on both client and
    server systems and that support in <productname>PostgreSQL</productname> is
    enabled at build time (see <xref linkend="installation"/>).
+   Supported libraries are <productname>OpenSSL</productname> and
+   <productname>NSS</productname>. The terms <acronym>SSL</acronym> and
+   <acronym>TLS</acronym> are often used interchangeably to mean a secure
+   connection using a <acronym>TLS</acronym> protocol, even though
+   <acronym>SSL</acronym> protocols are no longer supported.
   </para>
 
   <sect2 id="ssl-setup">
@@ -2211,8 +2217,13 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </para>
 
   <para>
-   To start in <acronym>SSL</acronym> mode, files containing the server certificate
-   and private key must exist.  By default, these files are expected to be
+   To start in <acronym>SSL</acronym> mode, a server certificate
+   and private key must exist. The below sections on the different libraries
+   will discuss how to configure these.
+  </para>
+   
+  <para>
+   By default, these files are expected to be
    named <filename>server.crt</filename> and <filename>server.key</filename>, respectively, in
    the server's data directory, but other names and locations can be specified
    using the configuration parameters <xref linkend="guc-ssl-cert-file"/>
@@ -2302,6 +2313,18 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </note>
   </sect2>
 
+  <sect2 id="ssl-nss-config">
+   <title>NSS Configuration</title>
+
+  <para>
+   <productname>PostgreSQL</productname> will look for certificates and keys
+   in the <productname>NSS</productname> database specified by the parameter
+   <xref linkend="guc-ssl-database"/> in <filename>postgresql.conf</filename>.
+   The parameters for certificate and key filenames are used to identify the
+   nicknames in the database.
+  </para>
+  </sect2>
+
   <sect2 id="ssl-client-certificates">
    <title>Using Client Certificates</title>
 
@@ -2376,7 +2399,7 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </sect2>
 
   <sect2 id="ssl-server-files">
-   <title>SSL Server File Usage</title>
+   <title>SSL Server File Parameter Usage</title>
 
    <para>
     <xref linkend="ssl-file-usage"/> summarizes the files that are
@@ -2423,6 +2446,14 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
       <entry>client certificate must not be on this list</entry>
      </row>
 
+     <row>
+      <entry><xref linkend="guc-ssl-database"/></entry>
+      <entry>certificate database</entry>
+      <entry>contains server certificates, keys and revocation lists; only
+      used when <productname>PostgreSQL</productname> is built with support
+      for <productname>NSS</productname>.</entry>
+     </row>
+
     </tbody>
    </tgroup>
   </table>
@@ -2446,7 +2477,7 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </sect2>
 
   <sect2 id="ssl-certificate-creation">
-   <title>Creating Certificates</title>
+   <title>Creating Certificates with OpenSSL</title>
 
    <para>
      To create a simple self-signed certificate for the server, valid for 365
@@ -2550,6 +2581,88 @@ openssl x509 -req -in server.csr -text -days 365 \
    </para>
   </sect2>
 
+  <sect2 id="nss-certificate-database">
+   <title>NSS Certificate Databases</title>
+
+   <para>
+    When using <productname>NSS</productname>, all certificates and keys must
+    be loaded into an <productname>NSS</productname> certificate database.
+   </para>
+
+   <para>
+    To create a new <productname>NSS</productname> certificate database and
+    load the certificates created in <xref linkend="ssl-certificate-creation" />,
+    use the following <productname>NSS</productname> commands:
+<programlisting>
+certutil -d "sql:server.db" -N --empty-password
+certutil -d "sql:server.db" -A -n server.crt -i server.crt -t "CT,C,C"
+certutil -d "sql:server.db" -A -n root.crt -i root.crt -t "CT,C,C"
+</programlisting>
+    This will give the certificate the filename as the nickname identifier in
+    the database which is created as <filename>server.db</filename>.
+   </para>
+   <para>
+    Then load the server key, which require converting it to
+    <acronym>PKCS#12</acronym> format using the
+    <productname>OpenSSL</productname> tools:
+<programlisting>
+openssl pkcs12 -export -out server.pfx -inkey server.key -in server.crt \
+  -certfile root.crt -passout pass:
+pk12util -i server.pfx -d server.db -W ''
+</programlisting>
+   </para>
+   <para>
+    Finally a certificate revocation list can be loaded with the following
+    commands:
+<programlisting>
+crlutil -I -i server.crl -d server.db -B
+</programlisting>
+   </para>
+  </sect2>
+
+  <sect2 id="nss-ssl-certificate-creation" />
+   <title>Creating Certificates with NSS</title>
+
+   <para>
+    To create a simple self-signed CA and certificate for the server, use the
+    following NSS commands. Replace
+    <replaceable>*.yourdomain.com</replaceable> with the server's host
+    name. Remove <replaceable>--empty-password</replaceable> in order to set
+    a password protecting the databases. The password can be passed to
+    <application>certutil</certutil> with the <literal>-f</literal> parameter.
+    First create a self-signed CA. To use a different certificate validity
+    time than the default, use <replaceable>-v</replaceable> to specify the
+    number of months of validity.
+<programlisting>
+mkdir root_ca.db
+certutil -N -d "sql:root_ca.db/" --empty-password
+certutil -S -d "sql:root_ca.db/" -n root_ca -s "CN=<replaceable>ca.yourdomain.com</replaceable>" \
+  -x -k rsa -g 2048 -m <replaceable>5432</replaceable> -t CTu,CTu,CTu \
+  --keyUsage certSigning -2 --nsCertType sslCA,smimeCA,objectSigningCA \
+  -Z SHA256
+certutil -L -d "sql:root_ca.db/" -n root_ca -a > root_ca.pem
+</programlisting>
+    Now create a server certificate database, and create a certificate signing
+    request for the CA. Then sign the request with the already created CA and
+    insert the certificate chain into the certificate database.
+<programlisting>
+mkdir server_cert.db
+certutil -N -d "sql:server_cert.db/" --empty-password
+certutil -R -d "sql:server_cert.db/" -s "CN=dbhost.yourdomain.com" \
+  -o server_cert.csr -g 2048 -Z SHA256
+
+certutil -C -d "sql:root_ca.db/" -c root_ca -i server_cert.csr \
+  -o server_cert.der -m <replaceable>5433</replaceable> \
+  --keyUsage keyEncipherment,dataEncipherment,digitalSignature \
+  --nsCertType sslServer -Z SHA256
+
+certutil -A -d "sql:server_cert.db/" -n root_ca -t CTu,CTu,CTu -a -i root_ca.pem
+certutil -A -d "sql:server_cert.db/" -n server_cert -t CTu,CTu,CTu -i server_cert.der
+</programlisting>
+    The server certificate is loaded into the certificate database as well as
+    the CA certificate in order to provide the chain of certificates.
+  </sect2>
+
  </sect1>
 
  <sect1 id="gssapi-enc">
-- 
2.25.1

From 7cd09cd97fab9db08c1cc4079f718545da163076 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:34:37 +0100
Subject: [PATCH v23 5/6] NSS contrib modules

---
 contrib/Makefile            |   2 +-
 contrib/pgcrypto/Makefile   |   7 +-
 contrib/pgcrypto/nss.c      | 773 ++++++++++++++++++++++++++++++++++++
 contrib/sslinfo/sslinfo.c   |  32 ++
 doc/src/sgml/pgcrypto.sgml  |  38 +-
 doc/src/sgml/sslinfo.sgml   |  12 +-
 src/tools/msvc/Install.pm   |   3 +-
 src/tools/msvc/Mkvcbuild.pm |  12 +-
 8 files changed, 864 insertions(+), 15 deletions(-)
 create mode 100644 contrib/pgcrypto/nss.c

diff --git a/contrib/Makefile b/contrib/Makefile
index 7a4866e338..c2232e5a4d 100644
--- a/contrib/Makefile
+++ b/contrib/Makefile
@@ -52,7 +52,7 @@ SUBDIRS = \
 		unaccent	\
 		vacuumlo
 
-ifeq ($(with_openssl),yes)
+ifneq ($(with_ssl),no)
 SUBDIRS += sslinfo
 else
 ALWAYS_SUBDIRS += sslinfo
diff --git a/contrib/pgcrypto/Makefile b/contrib/pgcrypto/Makefile
index d881e85add..6f804bf032 100644
--- a/contrib/pgcrypto/Makefile
+++ b/contrib/pgcrypto/Makefile
@@ -7,11 +7,14 @@ INT_TESTS = sha2
 OSSL_SRCS = openssl.c pgp-mpi-openssl.c
 OSSL_TESTS = sha2 des 3des cast5
 
+NSS_SRCS = nss.c pgp-mpi-internal.c imath.c blf.c
+NSS_TESTS = sha2 des 3des
+
 ZLIB_TST = pgp-compression
 ZLIB_OFF_TST = pgp-zlib-DISABLED
 
-CF_SRCS = $(if $(subst no,,$(with_openssl)), $(OSSL_SRCS), $(INT_SRCS))
-CF_TESTS = $(if $(subst no,,$(with_openssl)), $(OSSL_TESTS), $(INT_TESTS))
+CF_SRCS = $(if $(findstring openssl, $(with_ssl)), $(OSSL_SRCS), $(if $(findstring nss, $(with_ssl)), $(NSS_SRCS), $(INT_SRCS)))
+CF_TESTS = $(if $(findstring openssl, $(with_ssl)), $(OSSL_TESTS), $(if $(findstring nss, $(with_ssl)), $(NSS_TESTS), $(INT_TESTS)))
 CF_PGP_TESTS = $(if $(subst no,,$(with_zlib)), $(ZLIB_TST), $(ZLIB_OFF_TST))
 
 SRCS = \
diff --git a/contrib/pgcrypto/nss.c b/contrib/pgcrypto/nss.c
new file mode 100644
index 0000000000..da66152d65
--- /dev/null
+++ b/contrib/pgcrypto/nss.c
@@ -0,0 +1,773 @@
+/*-------------------------------------------------------------------------
+ *
+ * nss.c
+ *	  Wrapper for using NSS as a backend for pgcrypto PX
+ *
+ *
+ * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ *	  contrib/pgcrypto/nss.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres.h"
+
+#include "px.h"
+#include "blf.h"
+#include "utils/memutils.h"
+
+/*
+ * BITS_PER_BYTE is also defined in the NSPR header files, so we need to undef
+ * our version to avoid compiler warnings on redefinition.
+ */
+#define pg_BITS_PER_BYTE BITS_PER_BYTE
+#undef BITS_PER_BYTE
+
+#include <nss/nss.h>
+#include <nss/hasht.h>
+#include <nss/pk11func.h>
+#include <nss/pk11pub.h>
+#include <nss/secitem.h>
+#include <nss/sechash.h>
+#include <nss/secoid.h>
+#include <nss/secerr.h>
+
+/*
+ * Ensure that the colliding definitions match, else throw an error. In case
+ * NSPR has removed the definition for some reason, make sure to put ours
+ * back again.
+ */
+#if defined(BITS_PER_BYTE)
+#if BITS_PER_BYTE != pg_BITS_PER_BYTE
+#error "incompatible byte widths between NSPR and postgres"
+#endif
+#else
+#define BITS_PER_BYTE pg_BITS_PER_BYTE
+#endif
+#undef pg_BITS_PER_BYTE
+
+/*
+ * Define our own mechanisms for Blowfish as it's not implemented by NSS.
+ */
+#define BLOWFISH_CBC	(1)
+#define BLOWFISH_ECB	(2)
+
+/*
+ * Data structures for recording cipher implementations as well as ongoing
+ * cipher operations.
+ */
+typedef struct nss_digest
+{
+	NSSInitContext *context;
+	PK11Context *hash_context;
+	HASH_HashType hash_type;
+}			nss_digest;
+
+typedef struct cipher_implementation
+{
+	/* Function pointers to cipher operations */
+	int			(*init) (PX_Cipher *pxc, const uint8 *key, unsigned klen, const uint8 *iv);
+	unsigned	(*get_block_size) (PX_Cipher *pxc);
+	unsigned	(*get_key_size) (PX_Cipher *pxc);
+	unsigned	(*get_iv_size) (PX_Cipher *pxc);
+	int			(*encrypt) (PX_Cipher *pxc, const uint8 *data, unsigned dlen, uint8 *res);
+	int			(*decrypt) (PX_Cipher *pxc, const uint8 *data, unsigned dlen, uint8 *res);
+	void		(*free) (PX_Cipher *pxc);
+
+	/* The mechanism describing the cipher used */
+	union
+	{
+		CK_MECHANISM_TYPE nss;
+		CK_ULONG	internal;
+	}			mechanism;
+	int			keylen;
+	bool		is_nss;
+}			cipher_implementation;
+
+typedef struct nss_cipher
+{
+	const cipher_implementation *impl;
+	NSSInitContext *context;
+	PK11Context *crypt_context;
+	SECItem    *params;
+
+	PK11SymKey *encrypt_key;
+	PK11SymKey *decrypt_key;
+}			nss_cipher;
+
+typedef struct internal_cipher
+{
+	const cipher_implementation *impl;
+	BlowfishContext context;
+}			internal_cipher;
+
+typedef struct nss_cipher_ref
+{
+	const char *name;
+	const cipher_implementation *impl;
+}			nss_cipher_ref;
+
+/*
+ * Prototypes
+ */
+static unsigned nss_get_iv_size(PX_Cipher *pxc);
+static unsigned nss_get_block_size(PX_Cipher *pxc);
+
+/*
+ * nss_GetHashOidTagByHashType
+ *
+ * Returns the corresponding SECOidTag for the passed hash type. NSS 3.43
+ * includes HASH_GetHashOidTagByHashType for this purpose, but at the time of
+ * writing is not commonly available so we need our own version till then.
+ */
+static SECOidTag
+nss_GetHashOidTagByHashType(HASH_HashType type)
+{
+	if (type == HASH_AlgMD2)
+		return SEC_OID_MD2;
+	if (type == HASH_AlgMD5)
+		return SEC_OID_MD5;
+	if (type == HASH_AlgSHA1)
+		return SEC_OID_SHA1;
+	if (type == HASH_AlgSHA224)
+		return SEC_OID_SHA224;
+	if (type == HASH_AlgSHA256)
+		return SEC_OID_SHA256;
+	if (type == HASH_AlgSHA384)
+		return SEC_OID_SHA384;
+	if (type == HASH_AlgSHA512)
+		return SEC_OID_SHA512;
+
+	return SEC_OID_UNKNOWN;
+}
+
+static unsigned
+nss_digest_block_size(PX_MD *pxmd)
+{
+	nss_digest *digest = (nss_digest *) pxmd->p.ptr;
+	const SECHashObject *object;
+
+	object = HASH_GetHashObject(digest->hash_type);
+	return object->blocklength;
+}
+
+static unsigned
+nss_digest_result_size(PX_MD *pxmd)
+{
+	nss_digest *digest = (nss_digest *) pxmd->p.ptr;
+	const SECHashObject *object;
+
+	object = HASH_GetHashObject(digest->hash_type);
+	return object->length;
+}
+
+static void
+nss_digest_free(PX_MD *pxmd)
+{
+	nss_digest *digest = (nss_digest *) pxmd->p.ptr;
+	PRBool		free_ctx = PR_TRUE;
+
+	PK11_DestroyContext(digest->hash_context, free_ctx);
+	NSS_ShutdownContext(digest->context);
+}
+
+static void
+nss_digest_update(PX_MD *pxmd, const uint8 *data, unsigned dlen)
+{
+	nss_digest *digest = (nss_digest *) pxmd->p.ptr;
+
+	PK11_DigestOp(digest->hash_context, data, dlen);
+}
+
+static void
+nss_digest_reset(PX_MD *pxmd)
+{
+	nss_digest *digest = (nss_digest *) pxmd->p.ptr;
+
+	PK11_DigestBegin(digest->hash_context);
+}
+
+static void
+nss_digest_finish(PX_MD *pxmd, uint8 *dst)
+{
+	unsigned int outlen;
+	nss_digest *digest = (nss_digest *) pxmd->p.ptr;
+	const SECHashObject *object;
+
+	object = HASH_GetHashObject(digest->hash_type);
+	PK11_DigestFinal(digest->hash_context, dst, &outlen, object->length);
+}
+
+int
+px_find_digest(const char *name, PX_MD **res)
+{
+	PX_MD	   *pxmd;
+	NSSInitParameters params;
+	NSSInitContext *nss_context;
+	bool		found = false;
+	nss_digest *digest;
+	SECStatus	status;
+	SECOidData *hash;
+	HASH_HashType t;
+
+	/*
+	 * Initialize our own NSS context without a database backing it.
+	 */
+	memset(&params, 0, sizeof(params));
+	params.length = sizeof(params);
+	nss_context = NSS_InitContext("", "", "", "", &params,
+								  NSS_INIT_READONLY | NSS_INIT_NOCERTDB |
+								  NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN |
+								  NSS_INIT_NOROOTINIT | NSS_INIT_PK11RELOAD);
+
+	/*
+	 * There is no API function for looking up a digest algorithm from a name
+	 * string, but there is a publicly accessible array which can be scanned
+	 * for the name.
+	 */
+	for (t = HASH_AlgNULL + 1; t < HASH_AlgTOTAL; t++)
+	{
+		SECOidTag	hash_oid;
+		char	   *p;
+
+		hash_oid = nss_GetHashOidTagByHashType(t);
+
+		if (hash_oid == SEC_OID_UNKNOWN)
+			return PXE_NO_HASH;
+
+		hash = SECOID_FindOIDByTag(hash_oid);
+		if (pg_strcasecmp(hash->desc, name) == 0)
+		{
+			found = true;
+			break;
+		}
+
+		/*
+		 * NSS saves the algorithm names using SHA-xxx notation whereas
+		 * OpenSSL use SHAxxx. To make sure the user finds the requested
+		 * algorithm let's remove the dash and compare that spelling as well.
+		 */
+		if ((p = strchr(hash->desc, '-')) != NULL)
+		{
+			char		tmp[12];
+
+			memcpy(tmp, hash->desc, p - hash->desc);
+			memcpy(tmp + (p - hash->desc), p + 1, strlen(hash->desc) - (p - hash->desc) + 1);
+			if (pg_strcasecmp(tmp, name) == 0)
+			{
+				found = true;
+				break;
+			}
+		}
+	}
+
+	if (!found)
+		return PXE_NO_HASH;
+
+	digest = palloc(sizeof(*digest));
+
+	digest->context = nss_context;
+	digest->hash_context = PK11_CreateDigestContext(hash->offset);
+	digest->hash_type = t;
+	if (digest->hash_context == NULL)
+	{
+		pfree(digest);
+		return -1;
+	}
+
+	status = PK11_DigestBegin(digest->hash_context);
+	if (status != SECSuccess)
+	{
+		PK11_DestroyContext(digest->hash_context, PR_TRUE);
+		pfree(digest);
+		return -1;
+	}
+
+	pxmd = palloc(sizeof(*pxmd));
+	pxmd->result_size = nss_digest_result_size;
+	pxmd->block_size = nss_digest_block_size;
+	pxmd->reset = nss_digest_reset;
+	pxmd->update = nss_digest_update;
+	pxmd->finish = nss_digest_finish;
+	pxmd->free = nss_digest_free;
+	pxmd->p.ptr = (void *) digest;
+
+	*res = pxmd;
+
+	return 0;
+}
+
+static int
+bf_init(PX_Cipher *pxc, const uint8 *key, unsigned klen, const uint8 *iv)
+{
+	internal_cipher *cipher = (internal_cipher *) pxc->ptr;
+
+	blowfish_setkey(&cipher->context, key, klen);
+	if (iv)
+		blowfish_setiv(&cipher->context, iv);
+
+	return 0;
+}
+
+static int
+bf_encrypt(PX_Cipher *pxc, const uint8 *data, unsigned dlen, uint8 *res)
+{
+	internal_cipher *cipher = (internal_cipher *) pxc->ptr;
+	uint8	   *buf;
+
+	if (dlen == 0)
+		return 0;
+
+	if (dlen & 7)
+		return PXE_NOTBLOCKSIZE;
+
+	buf = palloc(dlen);
+	memcpy(buf, data, dlen);
+
+	if (cipher->impl->mechanism.internal == BLOWFISH_ECB)
+		blowfish_encrypt_ecb(buf, dlen, &cipher->context);
+	else
+		blowfish_encrypt_cbc(buf, dlen, &cipher->context);
+
+	memcpy(res, buf, dlen);
+	pfree(buf);
+
+	return 0;
+}
+
+static int
+bf_decrypt(PX_Cipher *pxc, const uint8 *data, unsigned dlen, uint8 *res)
+{
+	internal_cipher *cipher = (internal_cipher *) pxc->ptr;
+
+	if (dlen == 0)
+		return 0;
+
+	if (dlen & 7)
+		return PXE_NOTBLOCKSIZE;
+
+	memcpy(res, data, dlen);
+	if (cipher->impl->mechanism.internal == BLOWFISH_ECB)
+		blowfish_decrypt_ecb(res, dlen, &cipher->context);
+	else
+		blowfish_decrypt_cbc(res, dlen, &cipher->context);
+
+	return 0;
+}
+
+static void
+bf_free(PX_Cipher *pxc)
+{
+	internal_cipher *cipher = (internal_cipher *) pxc->ptr;
+
+	pfree(cipher);
+	pfree(pxc);
+}
+
+static int
+nss_symkey_blockcipher_init(PX_Cipher *pxc, const uint8 *key, unsigned klen,
+							const uint8 *iv)
+{
+	nss_cipher *cipher = (nss_cipher *) pxc->ptr;
+	SECItem		iv_item;
+	unsigned char *iv_item_data;
+	SECItem		key_item;
+	int			keylen;
+	PK11SlotInfo *slot;
+
+	if (cipher->impl->mechanism.nss == CKM_AES_CBC ||
+		cipher->impl->mechanism.nss == CKM_AES_ECB)
+	{
+		if (klen <= 128 / 8)
+			keylen = 128 / 8;
+		else if (klen <= 192 / 8)
+			keylen = 192 / 8;
+		else if (klen <= 256 / 8)
+			keylen = 256 / 8;
+		else
+			return PXE_CIPHER_INIT;
+	}
+	else
+		keylen = cipher->impl->keylen;
+
+	key_item.type = siBuffer;
+	key_item.data = (unsigned char *) key;
+	key_item.len = keylen;
+
+	/*
+	 * If hardware acceleration is configured in NSS one can theoretically get
+	 * a better slot by calling PK11_GetBestSlot() with the mechanism passed
+	 * to it. Unless there are complaints, using the simpler API will make
+	 * error handling easier though.
+	 */
+	slot = PK11_GetInternalSlot();
+	if (!slot)
+		return PXE_CIPHER_INIT;
+
+	/*
+	 * The key must be set up for the operation, and since we don't know at
+	 * this point whether we are asked to encrypt or decrypt we need to store
+	 * both versions.
+	 */
+	cipher->decrypt_key = PK11_ImportSymKey(slot, cipher->impl->mechanism.nss,
+											PK11_OriginUnwrap,
+											CKA_DECRYPT, &key_item,
+											NULL);
+	cipher->encrypt_key = PK11_ImportSymKey(slot, cipher->impl->mechanism.nss,
+											PK11_OriginUnwrap,
+											CKA_ENCRYPT, &key_item,
+											NULL);
+	PK11_FreeSlot(slot);
+
+	if (!cipher->decrypt_key || !cipher->encrypt_key)
+		return PXE_CIPHER_INIT;
+
+	if (iv)
+	{
+		iv_item.type = siBuffer;
+		iv_item.data = (unsigned char *) iv;
+		iv_item.len = nss_get_iv_size(pxc);
+	}
+	else
+	{
+		/*
+		 * The documentation states that either passing .data = 0; .len = 0;
+		 * in the iv_item, or NULL as iv_item, to PK11_ParamFromIV should be
+		 * done when IV is missing. That however leads to segfaults in the
+		 * library, the workaround that works in modern  library versions is
+		 * to pass in a keysized zeroed out IV.
+		 */
+		iv_item_data = palloc0(nss_get_iv_size(pxc));
+		iv_item.type = siBuffer;
+		iv_item.data = iv_item_data;
+		iv_item.len = nss_get_iv_size(pxc);
+	}
+
+	cipher->params = PK11_ParamFromIV(cipher->impl->mechanism.nss, &iv_item);
+
+	/* If we had to make a mock IV, free it once made into a param */
+	if (!iv)
+		pfree(iv_item_data);
+
+	if (cipher->params == NULL)
+		return PXE_CIPHER_INIT;
+
+	return 0;
+}
+
+static int
+nss_decrypt(PX_Cipher *pxc, const uint8 *data, unsigned dlen, uint8 *res)
+{
+	nss_cipher *cipher = (nss_cipher *) pxc->ptr;
+	SECStatus	status;
+	int			outlen;
+
+	if (!cipher->crypt_context)
+	{
+		cipher->crypt_context =
+			PK11_CreateContextBySymKey(cipher->impl->mechanism.nss, CKA_DECRYPT,
+									   cipher->decrypt_key, cipher->params);
+	}
+
+	status = PK11_CipherOp(cipher->crypt_context, res, &outlen, dlen, data, dlen);
+	if (status != SECSuccess)
+		return PXE_DECRYPT_FAILED;
+
+	return 0;
+}
+
+static int
+nss_encrypt(PX_Cipher *pxc, const uint8 *data, unsigned dlen, uint8 *res)
+{
+	nss_cipher *cipher = (nss_cipher *) pxc->ptr;
+	SECStatus	status;
+	int			outlen;
+
+	if (!cipher->crypt_context)
+	{
+		cipher->crypt_context =
+			PK11_CreateContextBySymKey(cipher->impl->mechanism.nss, CKA_ENCRYPT,
+									   cipher->decrypt_key, cipher->params);
+	}
+
+	status = PK11_CipherOp(cipher->crypt_context, res, &outlen, dlen, data, dlen);
+
+	if (status != SECSuccess)
+		return PXE_DECRYPT_FAILED;
+
+	return 0;
+}
+
+static void
+nss_free(PX_Cipher *pxc)
+{
+	nss_cipher *cipher = pxc->ptr;
+	PRBool		free_ctx = PR_TRUE;
+
+	PK11_FreeSymKey(cipher->encrypt_key);
+	PK11_FreeSymKey(cipher->decrypt_key);
+	PK11_DestroyContext(cipher->crypt_context, free_ctx);
+	NSS_ShutdownContext(cipher->context);
+	pfree(cipher);
+
+	pfree(pxc);
+}
+
+static unsigned
+nss_get_block_size(PX_Cipher *pxc)
+{
+	nss_cipher *cipher = pxc->ptr;
+
+	return PK11_GetBlockSize(cipher->impl->mechanism.nss, NULL);
+}
+
+static unsigned
+nss_get_key_size(PX_Cipher *pxc)
+{
+	nss_cipher *cipher = pxc->ptr;
+
+	return cipher->impl->keylen;
+}
+
+static unsigned
+nss_get_iv_size(PX_Cipher *pxc)
+{
+	nss_cipher *cipher = pxc->ptr;
+
+	return PK11_GetIVLength(cipher->impl->mechanism.nss);
+}
+
+static unsigned
+bf_get_block_size(PX_Cipher *pxc)
+{
+	return 8;
+}
+
+static unsigned
+bf_get_key_size(PX_Cipher *pxc)
+{
+	return 448 / 8;
+}
+
+static unsigned
+bf_get_iv_size(PX_Cipher *pxc)
+{
+	return 8;
+}
+
+/*
+ * Cipher Implementations
+ */
+static const cipher_implementation nss_des_cbc = {
+	.init = nss_symkey_blockcipher_init,
+	.get_block_size = nss_get_block_size,
+	.get_key_size = nss_get_key_size,
+	.get_iv_size = nss_get_iv_size,
+	.encrypt = nss_encrypt,
+	.decrypt = nss_decrypt,
+	.free = nss_free,
+	.mechanism.nss = CKM_DES_CBC,
+	.keylen = 8,
+	.is_nss = true
+};
+
+static const cipher_implementation nss_des_ecb = {
+	.init = nss_symkey_blockcipher_init,
+	.get_block_size = nss_get_block_size,
+	.get_key_size = nss_get_key_size,
+	.get_iv_size = nss_get_iv_size,
+	.encrypt = nss_encrypt,
+	.decrypt = nss_decrypt,
+	.free = nss_free,
+	.mechanism.nss = CKM_DES_ECB,
+	.keylen = 8,
+	.is_nss = true
+};
+
+static const cipher_implementation nss_des3_cbc = {
+	.init = nss_symkey_blockcipher_init,
+	.get_block_size = nss_get_block_size,
+	.get_key_size = nss_get_key_size,
+	.get_iv_size = nss_get_iv_size,
+	.encrypt = nss_encrypt,
+	.decrypt = nss_decrypt,
+	.free = nss_free,
+	.mechanism.nss = CKM_DES3_CBC,
+	.keylen = 24,
+	.is_nss = true
+};
+
+static const cipher_implementation nss_des3_ecb = {
+	.init = nss_symkey_blockcipher_init,
+	.get_block_size = nss_get_block_size,
+	.get_key_size = nss_get_key_size,
+	.get_iv_size = nss_get_iv_size,
+	.encrypt = nss_encrypt,
+	.decrypt = nss_decrypt,
+	.free = nss_free,
+	.mechanism.nss = CKM_DES3_ECB,
+	.keylen = 24,
+	.is_nss = true
+};
+
+static const cipher_implementation nss_aes_cbc = {
+	.init = nss_symkey_blockcipher_init,
+	.get_block_size = nss_get_block_size,
+	.get_key_size = nss_get_key_size,
+	.get_iv_size = nss_get_iv_size,
+	.encrypt = nss_encrypt,
+	.decrypt = nss_decrypt,
+	.free = nss_free,
+	.mechanism.nss = CKM_AES_CBC,
+	.keylen = 32,
+	.is_nss = true
+};
+
+static const cipher_implementation nss_aes_ecb = {
+	.init = nss_symkey_blockcipher_init,
+	.get_block_size = nss_get_block_size,
+	.get_key_size = nss_get_key_size,
+	.get_iv_size = nss_get_iv_size,
+	.encrypt = nss_encrypt,
+	.decrypt = nss_decrypt,
+	.free = nss_free,
+	.mechanism.nss = CKM_AES_ECB,
+	.keylen = 32,
+	.is_nss = true
+};
+
+static const cipher_implementation nss_bf_ecb = {
+	.init = bf_init,
+	.get_block_size = bf_get_block_size,
+	.get_key_size = bf_get_key_size,
+	.get_iv_size = bf_get_iv_size,
+	.encrypt = bf_encrypt,
+	.decrypt = bf_decrypt,
+	.free = bf_free,
+	.mechanism.internal = BLOWFISH_ECB,
+	.keylen = 56,
+	.is_nss = false
+};
+
+static const cipher_implementation nss_bf_cbc = {
+	.init = bf_init,
+	.get_block_size = bf_get_block_size,
+	.get_key_size = bf_get_key_size,
+	.get_iv_size = bf_get_iv_size,
+	.encrypt = bf_encrypt,
+	.decrypt = bf_decrypt,
+	.free = bf_free,
+	.mechanism.internal = BLOWFISH_CBC,
+	.keylen = 56,
+	.is_nss = false
+};
+
+/*
+ * Lookup table for finding the implementation based on a name. CAST5 as well
+ * as BLOWFISH are defined as cipher mechanisms in NSS but error out with
+ * SEC_ERROR_INVALID_ALGORITHM. Blowfish is implemented using the internal
+ * implementation while CAST5 isn't supported at all at this time,
+ */
+static const nss_cipher_ref nss_cipher_lookup[] = {
+	{"des", &nss_des_cbc},
+	{"des-cbc", &nss_des_cbc},
+	{"des-ecb", &nss_des_ecb},
+	{"des3-cbc", &nss_des3_cbc},
+	{"3des", &nss_des3_cbc},
+	{"3des-cbc", &nss_des3_cbc},
+	{"des3-ecb", &nss_des3_ecb},
+	{"3des-ecb", &nss_des3_ecb},
+	{"aes", &nss_aes_cbc},
+	{"aes-cbc", &nss_aes_cbc},
+	{"aes-ecb", &nss_aes_ecb},
+	{"rijndael", &nss_aes_cbc},
+	{"rijndael-cbc", &nss_aes_cbc},
+	{"rijndael-ecb", &nss_aes_ecb},
+	{"blowfish", &nss_bf_cbc},
+	{"blowfish-cbc", &nss_bf_cbc},
+	{"blowfish-ecb", &nss_bf_ecb},
+	{"bf", &nss_bf_cbc},
+	{"bf-cbc", &nss_bf_cbc},
+	{"bf-ecb", &nss_bf_ecb},
+	{NULL}
+};
+
+/*
+ * px_find_cipher
+ *
+ * Search for the requested cipher and see if there is support for it, and if
+ * so return an allocated object containing the playbook for how to encrypt
+ * and decrypt using the cipher.
+ */
+int
+px_find_cipher(const char *alias, PX_Cipher **res)
+{
+	const nss_cipher_ref *cipher_ref;
+	PX_Cipher  *px_cipher;
+	NSSInitParameters params;
+	NSSInitContext *nss_context;
+	nss_cipher *cipher;
+	internal_cipher *int_cipher;
+
+	for (cipher_ref = nss_cipher_lookup; cipher_ref->name; cipher_ref++)
+	{
+		if (strcmp(cipher_ref->name, alias) == 0)
+			break;
+	}
+
+	if (!cipher_ref->name)
+		return PXE_NO_CIPHER;
+
+	/*
+	 * Fill in the PX_Cipher to pass back to PX describing the operations to
+	 * perform in order to use the cipher.
+	 */
+	px_cipher = palloc(sizeof(*px_cipher));
+	px_cipher->block_size = cipher_ref->impl->get_block_size;
+	px_cipher->key_size = cipher_ref->impl->get_key_size;
+	px_cipher->iv_size = cipher_ref->impl->get_iv_size;
+	px_cipher->free = cipher_ref->impl->free;
+	px_cipher->init = cipher_ref->impl->init;
+	px_cipher->encrypt = cipher_ref->impl->encrypt;
+	px_cipher->decrypt = cipher_ref->impl->decrypt;
+
+	/*
+	 * Set the private data, which is different for NSS and internal ciphers
+	 */
+	if (cipher_ref->impl->is_nss)
+	{
+		/*
+		 * Initialize our own NSS context without a database backing it. At
+		 * some point we might want to allow users to use stored keys in the
+		 * database rather than passing them via SELECT encrypt(), and then
+		 * this need to be changed to open a user specified database.
+		 */
+		memset(&params, 0, sizeof(params));
+		params.length = sizeof(params);
+		nss_context = NSS_InitContext("", "", "", "", &params,
+									  NSS_INIT_READONLY | NSS_INIT_NOCERTDB |
+									  NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN |
+									  NSS_INIT_NOROOTINIT | NSS_INIT_PK11RELOAD);
+
+		/* nss_cipher is the private state struct for the operation */
+		cipher = palloc(sizeof(*cipher));
+		cipher->context = nss_context;
+		cipher->impl = cipher_ref->impl;
+		cipher->crypt_context = NULL;
+
+		px_cipher->ptr = cipher;
+	}
+	else
+	{
+		int_cipher = palloc0(sizeof(*int_cipher));
+
+		int_cipher->impl = cipher_ref->impl;
+		px_cipher->ptr = int_cipher;
+	}
+
+	*res = px_cipher;
+	return 0;
+}
diff --git a/contrib/sslinfo/sslinfo.c b/contrib/sslinfo/sslinfo.c
index 30cae0bb98..3aadd90aa6 100644
--- a/contrib/sslinfo/sslinfo.c
+++ b/contrib/sslinfo/sslinfo.c
@@ -9,9 +9,11 @@
 
 #include "postgres.h"
 
+#ifdef USE_OPENSSL
 #include <openssl/x509.h>
 #include <openssl/x509v3.h>
 #include <openssl/asn1.h>
+#endif
 
 #include "access/htup_details.h"
 #include "funcapi.h"
@@ -21,6 +23,7 @@
 
 PG_MODULE_MAGIC;
 
+#ifdef USE_OPENSSL
 static Datum X509_NAME_field_to_text(X509_NAME *name, text *fieldName);
 static Datum ASN1_STRING_to_text(ASN1_STRING *str);
 
@@ -31,6 +34,7 @@ typedef struct
 {
 	TupleDesc	tupdesc;
 } SSLExtensionInfoContext;
+#endif
 
 /*
  * Indicates whether current session uses SSL
@@ -131,6 +135,7 @@ ssl_client_serial(PG_FUNCTION_ARGS)
 }

+#ifdef USE_OPENSSL
 /*
  * Converts OpenSSL ASN1_STRING structure into text
  *
@@ -282,7 +287,23 @@ ssl_issuer_field(PG_FUNCTION_ARGS)
 	else
 		return result;
 }
+#endif							/* USE_OPENSSL */
 
+#ifdef USE_NSS
+PG_FUNCTION_INFO_V1(ssl_client_dn_field);
+Datum
+ssl_client_dn_field(PG_FUNCTION_ARGS)
+{
+	PG_RETURN_NULL();
+}
+
+PG_FUNCTION_INFO_V1(ssl_issuer_field);
+Datum
+ssl_issuer_field(PG_FUNCTION_ARGS)
+{
+	PG_RETURN_NULL();
+}
+#endif							/* USE_NSS */
 
 /*
  * Returns current client certificate subject as one string
@@ -338,6 +359,7 @@ ssl_issuer_dn(PG_FUNCTION_ARGS)
 }

+#ifdef USE_OPENSSL
 /*
  * Returns information about available SSL extensions.
  *
@@ -471,3 +493,13 @@ ssl_extension_info(PG_FUNCTION_ARGS)
 	/* All done */
 	SRF_RETURN_DONE(funcctx);
 }
+#endif							/* USE_OPENSSL */
+
+#ifdef USE_NSS
+PG_FUNCTION_INFO_V1(ssl_extension_info);
+Datum
+ssl_extension_info(PG_FUNCTION_ARGS)
+{
+	PG_RETURN_NULL();
+}
+#endif							/* USE_NSS */
diff --git a/doc/src/sgml/pgcrypto.sgml b/doc/src/sgml/pgcrypto.sgml
index 3d74e15ec9..9eb8a3f74d 100644
--- a/doc/src/sgml/pgcrypto.sgml
+++ b/doc/src/sgml/pgcrypto.sgml
@@ -45,8 +45,9 @@ digest(data bytea, type text) returns bytea
     <literal>sha224</literal>, <literal>sha256</literal>,
     <literal>sha384</literal> and <literal>sha512</literal>.
     If <filename>pgcrypto</filename> was built with
-    <productname>OpenSSL</productname>, more algorithms are available, as
-    detailed in <xref linkend="pgcrypto-with-without-openssl"/>.
+    <productname>OpenSSL</productname> or <productname>NSS</productname>,
+    more algorithms are available, as
+    detailed in <xref linkend="pgcrypto-with-without-openssl-nss"/>.
    </para>
 
    <para>
@@ -764,7 +765,7 @@ pgp_sym_encrypt(data, psw, 'compress-algo=1, cipher-algo=aes256')
     Which cipher algorithm to use.
    </para>
 <literallayout>
-Values: bf, aes128, aes192, aes256 (OpenSSL-only: <literal>3des</literal>, <literal>cast5</literal>)
+Values: bf, aes128, aes192, aes256 (OpenSSL-only: <literal>3des</literal>, <literal>cast5</literal>; NSS-only: <literal>3des</literal>)
 Default: aes128
 Applies to: pgp_sym_encrypt, pgp_pub_encrypt
 </literallayout>
@@ -1153,8 +1154,8 @@ gen_random_uuid() returns uuid
    <para>
     <filename>pgcrypto</filename> configures itself according to the findings of the
     main PostgreSQL <literal>configure</literal> script.  The options that
-    affect it are <literal>--with-zlib</literal> and
-    <literal>--with-openssl</literal>.
+    affect it are <literal>--with-zlib</literal>,
+    <literal>--with-openssl</literal> and <literal>--with-nss</literal>.
    </para>
 
    <para>
@@ -1169,14 +1170,16 @@ gen_random_uuid() returns uuid
     BIGNUM functions.
    </para>
 
-   <table id="pgcrypto-with-without-openssl">
-    <title>Summary of Functionality with and without OpenSSL</title>
-    <tgroup cols="3">
+   <table id="pgcrypto-with-without-openssl-nss">
+    <title>Summary of Functionality with and without external cryptographic
+      library</title>
+    <tgroup cols="4">
      <thead>
       <row>
        <entry>Functionality</entry>
        <entry>Built-in</entry>
        <entry>With OpenSSL</entry>
+       <entry>With NSS</entry>
       </row>
      </thead>
      <tbody>
@@ -1184,51 +1187,67 @@ gen_random_uuid() returns uuid
        <entry>MD5</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>SHA1</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>SHA224/256/384/512</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>Other digest algorithms</entry>
        <entry>no</entry>
        <entry>yes (Note 1)</entry>
+       <entry>yes (Note 1)</entry>
       </row>
       <row>
        <entry>Blowfish</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>AES</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>DES/3DES/CAST5</entry>
        <entry>no</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
+      </row>
+      <row>
+       <entry>CAST5</entry>
+       <entry>no</entry>
+       <entry>yes</entry>
+       <entry>no</entry>
       </row>
       <row>
        <entry>Raw encryption</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>PGP Symmetric encryption</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>PGP Public-Key encryption</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
      </tbody>
     </tgroup>
@@ -1241,7 +1260,8 @@ gen_random_uuid() returns uuid
    <orderedlist>
     <listitem>
      <para>
-      Any digest algorithm <productname>OpenSSL</productname> supports
+      Any digest algorithm <productname>OpenSSL</productname> and
+      <productname>NSS</productname> supports
       is automatically picked up.
       This is not possible with ciphers, which need to be supported
       explicitly.
diff --git a/doc/src/sgml/sslinfo.sgml b/doc/src/sgml/sslinfo.sgml
index 3213c039ca..d2270cbe7c 100644
--- a/doc/src/sgml/sslinfo.sgml
+++ b/doc/src/sgml/sslinfo.sgml
@@ -22,7 +22,8 @@
 
  <para>
   This extension won't build at all unless the installation was
-  configured with <literal>--with-openssl</literal>.
+  configured with SSL support, such as <literal>--with-openssl</literal>
+  or <literal>--with-nss</literal>.
  </para>
 
  <sect2>
@@ -208,6 +209,9 @@ emailAddress
      the X.500 and X.509 standards, so you cannot just assign arbitrary
      meaning to them.
     </para>
+    <para>
+     This function is only available when using <productname>OpenSSL</productname>.
+    </para>
     </listitem>
    </varlistentry>
 
@@ -223,6 +227,9 @@ emailAddress
      Same as <function>ssl_client_dn_field</function>, but for the certificate issuer
      rather than the certificate subject.
     </para>
+    <para>
+     This function is only available when using <productname>OpenSSL</productname>.
+    </para>
     </listitem>
    </varlistentry>
 
@@ -238,6 +245,9 @@ emailAddress
      Provide information about extensions of client certificate: extension name,
      extension value, and if it is a critical extension.
     </para>
+    <para>
+     This function is only available when using <productname>OpenSSL</productname>.
+    </para>
     </listitem>
    </varlistentry>
   </variablelist>
diff --git a/src/tools/msvc/Install.pm b/src/tools/msvc/Install.pm
index ea3af48777..afe72a7e97 100644
--- a/src/tools/msvc/Install.pm
+++ b/src/tools/msvc/Install.pm
@@ -438,7 +438,8 @@ sub CopyContribFiles
 		{
 			# These configuration-based exclusions must match vcregress.pl
 			next if ($d eq "uuid-ossp"  && !defined($config->{uuid}));
-			next if ($d eq "sslinfo"    && !defined($config->{openssl}));
+			next if ($d eq "sslinfo"    && !defined($config->{openssl})
+			  && !defined($config->{nss}));
 			next if ($d eq "xml2"       && !defined($config->{xml}));
 			next if ($d =~ /_plperl$/   && !defined($config->{perl}));
 			next if ($d =~ /_plpython$/ && !defined($config->{python}));
diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm
index a21eb088b3..0c489f9f34 100644
--- a/src/tools/msvc/Mkvcbuild.pm
+++ b/src/tools/msvc/Mkvcbuild.pm
@@ -444,9 +444,14 @@ sub mkvcbuild
 		push @contrib_excludes, 'xml2';
 	}
 
+	if (!$solution->{options}->{openssl} && !$solution->{options}->{nss})
+	{
+		push @contrib_excludes, 'sslinfo';
+	}
+
 	if (!$solution->{options}->{openssl})
 	{
-		push @contrib_excludes, 'sslinfo', 'ssl_passphrase_callback';
+		push @contrib_excludes, 'ssl_passphrase_callback';
 	}
 
 	if (!$solution->{options}->{uuid})
@@ -476,6 +481,11 @@ sub mkvcbuild
 		$pgcrypto->AddFiles('contrib/pgcrypto', 'openssl.c',
 			'pgp-mpi-openssl.c');
 	}
+	elsif ($solution->{options}->{nss})
+	{
+		$pgcrypto->AddFiles('contrib/pgcrypto', 'nss.c',
+			'pgp-mpi-internal.c', 'imath.c', 'blf.c');
+	}
 	else
 	{
 		$pgcrypto->AddFiles(
-- 
2.25.1

From 1436b8b74f25c7a167cf78e7ef038de02f911bd8 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 18 Jan 2021 13:04:49 +0100
Subject: [PATCH v23 6/6] NSS cryptohash support

---
 src/common/Makefile         |   5 +
 src/common/cryptohash_nss.c | 243 ++++++++++++++++++++++++++++++++++++
 2 files changed, 248 insertions(+)
 create mode 100644 src/common/cryptohash_nss.c

diff --git a/src/common/Makefile b/src/common/Makefile
index 7a4b3dad5d..5a25e5b390 100644
--- a/src/common/Makefile
+++ b/src/common/Makefile
@@ -85,11 +85,16 @@ OBJS_COMMON += \
 	protocol_openssl.o \
 	cryptohash_openssl.o
 else
+ifeq ($(with_ssl),nss)
+OBJS_COMMON += \
+	cryptohash_nss.o
+else
 OBJS_COMMON += \
 	cryptohash.o \
 	md5.o \
 	sha2.o
 endif
+endif
 
 # A few files are currently only built for frontend, not server
 # (Mkvcbuild.pm has a copy of this list, too).  logging.c is excluded
diff --git a/src/common/cryptohash_nss.c b/src/common/cryptohash_nss.c
new file mode 100644
index 0000000000..9cd9c9f3f3
--- /dev/null
+++ b/src/common/cryptohash_nss.c
@@ -0,0 +1,243 @@
+/*-------------------------------------------------------------------------
+ *
+ * cryptohash_nss.c
+ *	  Set of wrapper routines on top of NSS to support cryptographic
+ *	  hash functions.
+ *
+ * This should only be used if code is compiled with NSS support.
+ *
+ * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ *		  src/common/cryptohash_nss.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef FRONTEND
+#include "postgres.h"
+#else
+#include "postgres_fe.h"
+#endif
+
+/*
+ * BITS_PER_BYTE is also defined in the NSPR header files, so we need to undef
+ * our version to avoid compiler warnings on redefinition.
+ */
+#define pg_BITS_PER_BYTE BITS_PER_BYTE
+#undef BITS_PER_BYTE
+
+#include <nss/nss.h>
+#include <nss/hasht.h>
+#include <nss/pk11func.h>
+#include <nss/pk11pub.h>
+#include <nss/secitem.h>
+#include <nss/sechash.h>
+#include <nss/secoid.h>
+#include <nss/secerr.h>
+
+/*
+ * Ensure that the colliding definitions match, else throw an error. In case
+ * NSPR has removed the definition for some reason, make sure to put ours
+ * back again.
+ */
+#if defined(BITS_PER_BYTE)
+#if BITS_PER_BYTE != pg_BITS_PER_BYTE
+#error "incompatible byte widths between NSPR and postgres"
+#endif
+#else
+#define BITS_PER_BYTE pg_BITS_PER_BYTE
+#endif
+#undef pg_BITS_PER_BYTE
+
+#include "common/cryptohash.h"
+#ifndef FRONTEND
+#include "utils/memutils.h"
+#include "utils/resowner.h"
+#include "utils/resowner_private.h"
+#endif
+
+/*
+ * Internal pg_cryptohash_ctx structure.
+ */
+struct pg_cryptohash_ctx
+{
+	pg_cryptohash_type type;
+
+	NSSInitContext *nss_context;
+	PK11Context *pk11_context;
+	HASH_HashType hash_type;
+
+#ifndef FRONTEND
+	ResourceOwner resowner;
+#endif
+};
+
+/*
+ * pg_cryptohash_create
+ *
+ * Create and allocate a new hash context. Returns NULL on failure in the
+ * frontend, and raise error without returning in the backend.
+ */
+pg_cryptohash_ctx *
+pg_cryptohash_create(pg_cryptohash_type type)
+{
+	NSSInitParameters params;
+	pg_cryptohash_ctx *ctx;
+	SECOidData *hash;
+
+#ifndef FRONTEND
+	/*
+	 * Make sure that the resource owner has space to remember this reference.
+	 * This can error out with "out of memory", so do this before any other
+	 * allocation to avoid leaking.
+	 */
+	ResourceOwnerEnlargeCryptoHash(CurrentResourceOwner);
+	ctx = MemoryContextAlloc(TopMemoryContext, sizeof(pg_cryptohash_ctx));
+#else
+	ctx = pg_malloc(sizeof(pg_cryptohash_ctx));
+#endif
+
+	if (!ctx)
+		goto error;
+
+	switch(type)
+	{
+		case PG_MD5:
+			ctx->hash_type = SEC_OID_MD5;
+			break;
+		case PG_SHA224:
+			ctx->hash_type = SEC_OID_SHA224;
+			break;
+		case PG_SHA256:
+			ctx->hash_type = SEC_OID_SHA256;
+			break;
+		case PG_SHA384:
+			ctx->hash_type = SEC_OID_SHA384;
+			break;
+		case PG_SHA512:
+			ctx->hash_type = SEC_OID_SHA512;
+			break;
+	}
+
+	/*
+	 * Initialize our own NSS context without a database backing it.
+	 */
+	memset(&params, 0, sizeof(params));
+	params.length = sizeof(params);
+	ctx->nss_context = NSS_InitContext("", "", "", "", &params,
+									   NSS_INIT_READONLY | NSS_INIT_NOCERTDB |
+									   NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN |
+									   NSS_INIT_NOROOTINIT | NSS_INIT_PK11RELOAD);
+	if (!ctx->nss_context)
+	{
+		explicit_bzero(ctx, sizeof(pg_cryptohash_ctx));
+		pfree(ctx);
+		goto error;
+	}
+	ctx->type = type;
+	hash = SECOID_FindOIDByTag(ctx->hash_type);
+	ctx->pk11_context = PK11_CreateDigestContext(hash->offset);
+	if (!ctx->pk11_context)
+	{
+		explicit_bzero(ctx, sizeof(pg_cryptohash_ctx));
+		pfree(ctx);
+		goto error;
+	}
+
+#ifndef FRONTEND
+	ctx->resowner = CurrentResourceOwner;
+	ResourceOwnerRememberCryptoHash(CurrentResourceOwner,
+									PointerGetDatum(ctx));
+#endif
+
+	return ctx;
+
+error:
+#ifndef FRONTEND
+	ereport(ERROR,
+			(errcode(ERRCODE_OUT_OF_MEMORY),
+			 errmsg("out of memory")));
+#endif
+	return NULL;
+}
+
+/*
+ * pg_cryptohash_init
+ *			Initialize the passed hash context
+ *
+ * Returns 0 on success, -1 on failure.
+ */
+int
+pg_cryptohash_init(pg_cryptohash_ctx *ctx)
+{
+	SECStatus		status;
+
+	status = PK11_DigestBegin(ctx->pk11_context);
+
+	if (status != SECSuccess)
+		return 1;
+	return 0;
+}
+
+/*
+ * pg_cryptohash_update
+ *
+ * Update a hash context.  Returns 0 on success, -1 on failure.
+ */
+int
+pg_cryptohash_update(pg_cryptohash_ctx *ctx, const uint8 *data, size_t len)
+{
+	SECStatus	status;
+
+	if (ctx == NULL)
+		return -1;
+	
+	status = PK11_DigestOp(ctx->pk11_context, data, len);
+	if (status != SECSuccess)
+		return -1;
+	
+	return 0;
+}
+
+/*
+ * pg_cryptohash_final
+ *
+ * Finalize a hash context.  Returns 0 on success, -1 on failure.
+ */
+int
+pg_cryptohash_final(pg_cryptohash_ctx *ctx, uint8 *dest)
+{
+	SECStatus	status;
+	unsigned int outlen;
+	const SECHashObject *object;
+
+	object = HASH_GetHashObject(ctx->hash_type);
+	status = PK11_DigestFinal(ctx->pk11_context, dest, &outlen, object->length);
+
+	if (status != SECSuccess)
+		return -1;
+	return 0;
+}
+
+/*
+ * pg_cryptohash_free
+ *
+ * Free a hash context and the associated NSS context.
+ */
+void
+pg_cryptohash_free(pg_cryptohash_ctx *ctx)
+{
+	PRBool		free_context = PR_TRUE;
+	if (!ctx)
+		return;
+	
+	PK11_DestroyContext(ctx->pk11_context, free_context);
+#ifndef FRONTEND
+	ResourceOwnerForgetCryptoHash(ctx->resowner, PointerGetDatum(ctx));
+#endif
+	NSS_ShutdownContext(ctx->nss_context);
+	explicit_bzero(ctx, sizeof(pg_cryptohash_ctx));
+	pfree(ctx);
+}
-- 
2.25.1

---

From: Michael Paquier <[email-masked]>
Date: Thu, 21 Jan 2021 14:21:27 +0900

> --with-ssl autoconf change into a non NSS dependent commit, if that's wanted.

IMO it makes sense to extract the independent pieces and build on top
of them.  The bulk of the changes is likely going to have a bunch of
comments if reviewed deeply, so I think that we had better remove from
the stack the small-ish problems to ease the next moves.  The
./configure part and replacement of with_openssl by with_ssl is mixed
in 0001 and 0002, which is actually confusing.  And, FWIW, I would be
fine with applying a patch that introduces a --with-ssl with a
compatibility kept for --with-openssl.  This is what 0001 is doing,
actually, similarly to the past switches for --with-uuid.

A point that has been mentioned offline by you, but not mentioned on
this list.  The structure of the modules in src/test/ssl/ could be
refactored to help with an easier integration of more SSL libraries.
This makes sense taken independently.

> instead misunderstood that feel free to correct me with how you think this

The point would be to rename BITS_PER_BYTE to PG_BITS_PER_BYTE in the
code and avoid conflicts.  I am not completely sure if others would
agree here, but this would remove quite some ifdef/undef stuff from
the code dedicated to NSS.

> > src/sgml/libpq.sgml needs to document PQdefaultSSLKeyPassHook_nss, no?

Please note that patch 0001 is failing to apply after the recent
commit b663a41.  There are conflicts in postgres_fdw.out.

Also, what's the minimum version of NSS that would be supported?  It
would be good to define an acceptable older version, to keep that
documented and to track that perhaps with some configure checks (?),
similarly to what is done for OpenSSL.

Patch 0006 has three trailing whitespaces (git diff --check
complains).  Running the regression tests of pgcrypto, I think that
the SHA2 implementation is not completely right.  Some SHA2 encoding
reports results from already-freed data.  I have spotted a second
issue within scram_HMAC_init(), where pg_cryptohash_create() remains
stuck inside NSS_InitContext(), freezing the regression tests where
password hashed for SCRAM are created.

+   ResourceOwnerEnlargeCryptoHash(CurrentResourceOwner);
+   ctx = MemoryContextAlloc(TopMemoryContext, sizeof(pg_cryptohash_ctx));
+#else
+   ctx = pg_malloc(sizeof(pg_cryptohash_ctx));
+#endif
cryptohash_nss.c cannot use pg_malloc() for frontend allocations.  On
OOM, your patch would call exit() directly, even within libpq.  But
shared library callers need to know about the OOM failure.

+   explicit_bzero(ctx, sizeof(pg_cryptohash_ctx));
+   pfree(ctx);
For similar reasons, pfree should not be used for the frontend code in
cryptohash_nss.c.  The fallback should be just a malloc/free set.

+   status = PK11_DigestBegin(ctx->pk11_context);
+
+   if (status != SECSuccess)
+       return 1;
+   return 0;
This needs to return -1 on failure, not 1.

I really need to study more the choide of the options chosen for
NSS_InitContext()...  But based on the docs I can read on the matter I
think that saving nsscontext in pg_cryptohash_ctx is right for each
cryptohash built.

src/tools/msvc/ is missing an update for cryptohash_nss.c.
--
Michael

---

From: Jacob Champion <[email-masked]>
Date: Thu, 21 Jan 2021 20:16:50 +0000

> writing documentation for this toolchain, or any part of NSS for that matter).

I think we're missing a counterpart to this piece of the OpenSSL
implementation, in be_tls_init():

    if (ssl_ca_file[0])
    {
        ...
        SSL_CTX_set_client_CA_list(context, root_cert_list);
    }

I think the NSS equivalent to SSL_CTX_set_client_CA_list() is probably
SSL_SetTrustAnchors() (which isn't called out in the online NSS docs,
as far as I can see).

What I'm less sure of is how we want the NSS counterpart to ssl_ca_file
to behave. The OpenSSL implementation allows a list of CA names to be
sent. Should the NSS side take a list of CA cert nicknames? a list of
Subjects? something else?

mod_nss for httpd had a proposed feature [1] to do this that
unfortunately withered on the vine, and Google returns ~500 results for
"SSL_SetTrustAnchors", so I'm unaware of any prior art in the wild...

--Jacob

[1] https://bugzilla.redhat.com/show_bug.cgi?id=719401

---

From: Jacob Champion <[email-masked]>
Date: Fri, 22 Jan 2021 01:14:27 +0000

> similarly to what is done for OpenSSL.

Some version landmarks:

- 3.21 adds support for extended master secret, which according to [1]
is required for SCRAM channel binding to actually be secure.
- 3.26 is Debian Stretch.
- 3.28 is Ubuntu 16.04, and RHEL6 (I think).
- 3.35 is Ubuntu 18.04.
- 3.36 is RHEL7 (I think).
- 3.39 gets us final TLS 1.3 support.
- 3.42 is Debian Buster.
- 3.49 is Ubuntu 20.04.

(I'm having trouble finding online package information for RHEL variants, so I've pulled those versions from online support docs. If someone notices that those are wrong please speak up.)
So 3.39 would guarantee TLS1.3 but exclude a decent chunk of still-
supported Debian-alikes. Anything less than 3.21 seems actively unsafe
unless we disable SCRAM with those versions.

Any other important landmarks (whether feature- or distro-related) we
need to consider?

--Jacob

[1] https://tools.ietf.org/html/rfc7677#section-4

---

From: Michael Paquier <[email-masked]>
Date: Wed, 27 Jan 2021 16:39:23 +0900

> more, but I'm glad it works now.

My apologies for chiming in.  I was looking at your patch set here,
and while reviewing the strong random and cryptohash parts I have
found a couple of mistakes in the ./configure part.  I think that the
switch from --with-openssl to --with-ssl={openssl} could just be done
independently as a building piece of the rest, then the first portion
based on NSS could just add the minimum set in configure.ac.

Please note that the patch set has been using autoconf from Debian, or
something forked from upstream.  There were also missing updates in
several parts of the code base, and a lack of docs for the new
switch.  I have spent time checking that with --with-openssl to make
sure that the obsolete grammar is still compatible, --with-ssl=openssl
and also without it.

Thoughts?
--
Michael
From b3e18564697bdb36a8eba4afe6434294676b528b Mon Sep 17 00:00:00 2001
From: Michael Paquier <[email-masked]>
Date: Wed, 27 Jan 2021 16:36:45 +0900
Subject: [PATCH] Introduce --with-ssl={openssl} in configure options

---
 src/include/pg_config.h.in                    |   2 +-
 src/backend/libpq/Makefile                    |   2 +-
 src/backend/libpq/hba.c                       |   2 +-
 src/common/Makefile                           |   2 +-
 src/interfaces/libpq/Makefile                 |   2 +-
 src/test/Makefile                             |   2 +-
 src/test/modules/Makefile                     |   2 +-
 .../modules/ssl_passphrase_callback/Makefile  |   2 +-
 .../ssl_passphrase_callback/t/001_testfunc.pl |   2 +-
 src/test/ssl/Makefile                         |   2 +-
 src/test/ssl/t/001_ssltests.pl                |   2 +-
 src/test/ssl/t/002_scram.pl                   |   2 +-
 doc/src/sgml/installation.sgml                |   5 +-
 doc/src/sgml/pgcrypto.sgml                    |   2 +-
 doc/src/sgml/sslinfo.sgml                     |   2 +-
 contrib/Makefile                              |   2 +-
 contrib/pgcrypto/Makefile                     |   4 +-
 configure                                     | 110 +++++++++++-------
 configure.ac                                  |  31 +++--
 src/Makefile.global.in                        |   2 +-
 src/tools/msvc/Solution.pm                    |   2 +-
 src/tools/msvc/config_default.pl              |   2 +-
 22 files changed, 113 insertions(+), 73 deletions(-)

diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index f4d9f3b408..55cab4d2bf 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -899,7 +899,7 @@
 /* Define to select named POSIX semaphores. */
 #undef USE_NAMED_POSIX_SEMAPHORES
 
-/* Define to build with OpenSSL support. (--with-openssl) */
+/* Define to build with OpenSSL support. (--with-ssl=openssl) */
 #undef USE_OPENSSL
 
 /* Define to 1 to build with PAM support. (--with-pam) */
diff --git a/src/backend/libpq/Makefile b/src/backend/libpq/Makefile
index efc5ef760a..8d1d16b0fc 100644
--- a/src/backend/libpq/Makefile
+++ b/src/backend/libpq/Makefile
@@ -28,7 +28,7 @@ OBJS = \
 	pqmq.o \
 	pqsignal.o

index 371dccb852..20bf1461ce 100644
+					 errhint("Compile with --with-ssl=openssl to use SSL connections."),
index 1a1d0d3406..5422579a6a 100644
 
-ifeq ($(with_openssl),yes)
+ifeq ($(with_ssl),openssl)
 OBJS_COMMON += \
 	protocol_openssl.o \
 	cryptohash_openssl.o
diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile
index c4fde3f93d..2b7ace52e4 100644
--- a/src/interfaces/libpq/Makefile
+++ b/src/interfaces/libpq/Makefile
@@ -45,7 +45,7 @@ OBJS = \
 	pqexpbuffer.o \
 	fe-auth.o
 
 	fe-secure-common.o \
index ab1ef9a475..f7859c2fd5 100644

-export with_openssl
+export with_ssl
 
 MODULE_big = ssl_passphrase_func
 OBJS = ssl_passphrase_func.o $(WIN32RES)
diff --git a/src/test/modules/ssl_passphrase_callback/t/001_testfunc.pl b/src/test/modules/ssl_passphrase_callback/t/001_testfunc.pl
index dbc084f870..d9838a5d5a 100644
--- a/src/test/modules/ssl_passphrase_callback/t/001_testfunc.pl
+++ b/src/test/modules/ssl_passphrase_callback/t/001_testfunc.pl
@@ -7,7 +7,7 @@ use TestLib;
 use Test::More;
 use PostgresNode;
 
index 93335b1ea2..d545382eea 100644
 
-export with_openssl
+export with_ssl
 
 CERTIFICATES := server_ca server-cn-and-alt-names \
 	server-cn-only server-single-alt-name server-multiple-alt-names \
diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl
index fd2727b568..9cf4ee24cb 100644
--- a/src/test/ssl/t/001_ssltests.pl
+++ b/src/test/ssl/t/001_ssltests.pl
@@ -11,7 +11,7 @@ use lib $FindBin::RealBin;
 
 use SSLServer;
 
-if ($ENV{with_openssl} eq 'yes')
+if ($ENV{with_ssl} eq 'openssl')
 {
 	plan tests => 93;
 }
diff --git a/src/test/ssl/t/002_scram.pl b/src/test/ssl/t/002_scram.pl
index a088f71a1a..2bdd638115 100644
--- a/src/test/ssl/t/002_scram.pl
+++ b/src/test/ssl/t/002_scram.pl
@@ -13,7 +13,7 @@ use lib $FindBin::RealBin;
 
 use SSLServer;
 
-if ($ENV{with_openssl} ne 'yes')
+if ($ENV{with_ssl} ne 'openssl')
 {
 	plan skip_all => 'SSL not supported by this build';
 }
diff --git a/doc/src/sgml/installation.sgml b/doc/src/sgml/installation.sgml
index a53389b728..2d52068310 100644
--- a/doc/src/sgml/installation.sgml
+++ b/doc/src/sgml/installation.sgml
@@ -967,7 +967,7 @@ build-postgresql:
       </varlistentry>
 
       <varlistentry>
-       <term><option>--with-openssl</option>
+       <term><option>--with-ssl=<replaceable>LIBRARY</replaceable></option>
        <indexterm>
         <primary>OpenSSL</primary>
         <seealso>SSL</seealso>
@@ -980,7 +980,8 @@ build-postgresql:
          package to be installed.  <filename>configure</filename> will check
          for the required header files and libraries to make sure that
          your <productname>OpenSSL</productname> installation is sufficient
-         before proceeding.
+         before proceeding. The only <replaceable>LIBRARY</replaceable>
+         supported now is <option>openssl</option>.
         </para>
        </listitem>
       </varlistentry>
diff --git a/doc/src/sgml/pgcrypto.sgml b/doc/src/sgml/pgcrypto.sgml
index 3d74e15ec9..b6bb23de0f 100644
--- a/doc/src/sgml/pgcrypto.sgml
+++ b/doc/src/sgml/pgcrypto.sgml
@@ -1154,7 +1154,7 @@ gen_random_uuid() returns uuid
     <filename>pgcrypto</filename> configures itself according to the findings of the
     main PostgreSQL <literal>configure</literal> script.  The options that
     affect it are <literal>--with-zlib</literal> and
-    <literal>--with-openssl</literal>.
+    <literal>--with-ssl=openssl</literal>.
    </para>
 
    <para>
diff --git a/doc/src/sgml/sslinfo.sgml b/doc/src/sgml/sslinfo.sgml
index 3213c039ca..2a9c45a111 100644
--- a/doc/src/sgml/sslinfo.sgml
+++ b/doc/src/sgml/sslinfo.sgml
@@ -22,7 +22,7 @@
 
  <para>
   This extension won't build at all unless the installation was
-  configured with <literal>--with-openssl</literal>.
+  configured with <literal>--with-ssl=openssl</literal>.
  </para>
 
  <sect2>
diff --git a/contrib/Makefile b/contrib/Makefile
index 7a4866e338..ae1fd64028 100644
--- a/contrib/Makefile
+++ b/contrib/Makefile
@@ -52,7 +52,7 @@ SUBDIRS = \
 		unaccent	\
 		vacuumlo
 
index 316a26e58d..c0b4f1fcf6 100644
@@ -10,8 +10,8 @@ OSSL_TESTS = sha2 des 3des cast5
 
-CF_SRCS = $(if $(subst no,,$(with_openssl)), $(OSSL_SRCS), $(INT_SRCS))
-CF_TESTS = $(if $(subst no,,$(with_openssl)), $(OSSL_TESTS), $(INT_TESTS))
+CF_SRCS = $(if $(subst openssl,,$(with_ssl)), $(INT_SRCS), $(OSSL_SRCS))
+CF_TESTS = $(if $(subst openssl,,$(with_ssl)), $(INT_TESTS), $(OSSL_TESTS))
 CF_PGP_TESTS = $(if $(subst no,,$(with_zlib)), $(ZLIB_TST), $(ZLIB_OFF_TST))
 
 SRCS = \
diff --git a/configure b/configure
index e202697bbf..092e03e8ed 100755
--- a/configure
+++ b/configure
@@ -653,6 +653,7 @@ LIBOBJS
 UUID_LIBS
 LDAP_LIBS_BE
 LDAP_LIBS_FE
+with_ssl
 PTHREAD_CFLAGS
 PTHREAD_LIBS
 PTHREAD_CC
@@ -709,7 +710,6 @@ with_uuid
 with_readline
 with_systemd
 with_selinux
-with_openssl
 with_ldap
 with_krb_srvnam
 krb_srvtab
@@ -854,7 +854,6 @@ with_pam
 with_bsd_auth
 with_ldap
 with_bonjour
-with_openssl
 with_selinux
 with_systemd
 with_readline
@@ -866,6 +865,8 @@ with_libxslt
 with_system_tzdata
 with_zlib
 with_gnu_ld
+with_ssl
+with_openssl
 enable_largefile
 '
       ac_precious_vars='build_alias
@@ -1556,7 +1557,6 @@ Optional Packages:
   --with-bsd-auth         build with BSD Authentication support
   --with-ldap             build with LDAP support
   --with-bonjour          build with Bonjour support
-  --with-openssl          build with OpenSSL support
   --with-selinux          build with SELinux support
   --with-systemd          build with systemd support
   --without-readline      do not use GNU Readline nor BSD Libedit for editing
@@ -1570,6 +1570,8 @@ Optional Packages:
                           use system time zone data in DIR
   --without-zlib          do not use Zlib
   --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
+  --with-ssl=LIB          use LIB for SSL/TLS support (openssl)
+  --with-openssl          obsolete spelling of --with-ssl=openssl
 
 Some influential environment variables:
   CC          C compiler command
@@ -8070,41 +8072,6 @@ fi
 $as_echo "$with_bonjour" >&6; }

-#
-# OpenSSL
-#
@@ -12174,7 +12141,64 @@ fi
   fi
 fi
 
+#
+# SSL Library
+#
+# There is currently one supported SSL/TLS libraries: OpenSSL.
+#
+
+
+
 
 $as_echo "#define OPENSSL_API_COMPAT 0x10001000L" >>confdefs.h
@@ -12435,8 +12459,14 @@ _ACEOF
 fi
 done
 
+
+$as_echo "#define USE_OPENSSL 1" >>confdefs.h
+
+elif test "$with_ssl" != no ; then
+  as_fn_error $? "--with-ssl must specify openssl" "$LINENO" 5
 fi
 
+
 if test "$with_pam" = yes ; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pam_start in -lpam" >&5
 $as_echo_n "checking for pam_start in -lpam... " >&6; }
@@ -13322,7 +13352,7 @@ done
 
 fi

@@ -18098,7 +18128,7 @@ fi
 # will be used.
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking which random number source to use" >&5
 $as_echo_n "checking which random number source to use... " >&6; }
-if test x"$with_openssl" = x"yes" ; then
+if test x"$with_ssl" = x"openssl" ; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: OpenSSL" >&5
 $as_echo "OpenSSL" >&6; }
 elif test x"$PORTNAME" = x"win32" ; then
diff --git a/configure.ac b/configure.ac
index a5ad072ee4..f7a2db2574 100644
--- a/configure.ac
+++ b/configure.ac
@@ -852,15 +852,6 @@ PGAC_ARG_BOOL(with, bonjour, no,
 AC_MSG_RESULT([$with_bonjour])

-#
-# OpenSSL
-#
@@ -1205,7 +1196,21 @@ if test "$with_gssapi" = yes ; then
   fi
 fi
 
+#
+# SSL Library
+#
+# There is currently one supported SSL/TLS libraries: OpenSSL.
+#
+PGAC_ARG_REQ(with, ssl, [LIB], [use LIB for SSL/TLS support (openssl)])
+if test x"$with_ssl" = x"" ; then
+  with_ssl=no
+fi
+PGAC_ARG_BOOL(with, openssl, no, [obsolete spelling of --with-ssl=openssl])
 if test "$with_openssl" = yes ; then
+  with_ssl=openssl
+fi
+
+if test "$with_ssl" = openssl ; then
   dnl Order matters!
   # Minimum required OpenSSL version is 1.0.1
   AC_DEFINE(OPENSSL_API_COMPAT, [0x10001000L],
@@ -1229,7 +1234,11 @@ if test "$with_openssl" = yes ; then
   # thread-safety. In 1.1.0, it's no longer required, and CRYPTO_lock()
   # function was removed.
   AC_CHECK_FUNCS([CRYPTO_lock])
+  AC_DEFINE([USE_OPENSSL], 1, [Define to 1 if you have OpenSSL support.])
+elif test "$with_ssl" != no ; then
+  AC_MSG_ERROR([--with-ssl must specify openssl])
 fi
+AC_SUBST(with_ssl)
 
 if test "$with_pam" = yes ; then
   AC_CHECK_LIB(pam,    pam_start, [], [AC_MSG_ERROR([library 'pam' is required for PAM])])
@@ -1402,7 +1411,7 @@ if test "$with_gssapi" = yes ; then
 	[AC_CHECK_HEADERS(gssapi.h, [], [AC_MSG_ERROR([gssapi.h header file is required for GSSAPI])])])
 fi
 
-if test "$with_openssl" = yes ; then
+if test "$with_ssl" = openssl ; then
   AC_CHECK_HEADER(openssl/ssl.h, [], [AC_MSG_ERROR([header file <openssl/ssl.h> is required for OpenSSL])])
   AC_CHECK_HEADER(openssl/err.h, [], [AC_MSG_ERROR([header file <openssl/err.h> is required for OpenSSL])])
 fi
@@ -2159,7 +2168,7 @@ fi
 # first choice, else the native platform sources (Windows API or /dev/urandom)
 # will be used.
 AC_MSG_CHECKING([which random number source to use])
-if test x"$with_openssl" = x"yes" ; then
+if test x"$with_ssl" = x"openssl" ; then
   AC_MSG_RESULT([OpenSSL])
 elif test x"$PORTNAME" = x"win32" ; then
   AC_MSG_RESULT([Windows native])
diff --git a/src/Makefile.global.in b/src/Makefile.global.in
index 9a1688c97c..74b3a6acd2 100644
--- a/src/Makefile.global.in
+++ b/src/Makefile.global.in
@@ -183,7 +183,7 @@ with_icu	= @with_icu@
 with_perl	= @with_perl@
 with_python	= @with_python@
 with_tcl	= @with_tcl@
-with_openssl	= @with_openssl@
+with_ssl	= @with_ssl@
 with_readline	= @with_readline@
 with_selinux	= @with_selinux@
 with_systemd	= @with_systemd@
diff --git a/src/tools/msvc/Solution.pm b/src/tools/msvc/Solution.pm
index 2f28de0355..1c0c92fcd2 100644
--- a/src/tools/msvc/Solution.pm
+++ b/src/tools/msvc/Solution.pm
@@ -1156,7 +1156,7 @@ sub GetFakeConfigure
 	$cfg .= ' --with-ldap'        if ($self->{options}->{ldap});
 	$cfg .= ' --without-zlib' unless ($self->{options}->{zlib});
 	$cfg .= ' --with-extra-version' if ($self->{options}->{extraver});
-	$cfg .= ' --with-openssl'       if ($self->{options}->{openssl});
+	$cfg .= ' --with-ssl=openssl'   if ($self->{options}->{openssl});
 	$cfg .= ' --with-uuid'          if ($self->{options}->{uuid});
 	$cfg .= ' --with-libxml'        if ($self->{options}->{xml});
 	$cfg .= ' --with-libxslt'       if ($self->{options}->{xslt});
diff --git a/src/tools/msvc/config_default.pl b/src/tools/msvc/config_default.pl
index 2ef2cfc4e9..5395e211eb 100644
--- a/src/tools/msvc/config_default.pl
+++ b/src/tools/msvc/config_default.pl
@@ -16,7 +16,7 @@ our $config = {
 	tcl       => undef,    # --with-tcl=<path>
 	perl      => undef,    # --with-perl=<path>
 	python    => undef,    # --with-python=<path>
-	openssl   => undef,    # --with-openssl=<path>
+	openssl   => undef,    # --with-ssl=openssl with <path>
 	uuid      => undef,    # --with-uuid=<path>
 	xml       => undef,    # --with-libxml=<path>
 	xslt      => undef,    # --with-libxslt=<path>
-- 
2.30.0

---

From: Jacob Champion <[email-masked]>
Date: Wed, 27 Jan 2021 18:47:17 +0000

> sure that the obsolete grammar is still compatible, --with-ssl=openssl

Seems good to me on Ubuntu; builds with both flavors.

>  	xslt      => undef,    # --with-libxslt=<path>

So to check understanding: the `openssl` config variable is still alive
for MSVC builds; it just turns that into `--with-ssl=openssl` in the
fake CONFIGURE_ARGS?

<bikeshed color="lightblue">

Since SSL is an obsolete term, and the choice of OpenSSL vs NSS vs
[nothing] affects server operation (such as cryptohash) regardless of
whether or not connection-level TLS is actually used, what would you
all think about naming this option --with-crypto? I.e.

    --with-crypto=openssl
    --with-crypto=nss

</bikeshed>

--Jacob

---

From: Michael Paquier <[email-masked]>
Date: Thu, 28 Jan 2021 15:06:32 +0900

> for MSVC builds; it just turns that into `--with-ssl=openssl` in the

Yeah, I think that keeping both variables separated in the MSVC
scripts is the most straight-forward option, as this passes down a
path.  Once there is a value for nss, we'd need to properly issue an
error if both OpenSSL and NSS are specified.

> all think about naming this option --with-crypto? I.e.

Looking around, curl has multiple switches for each lib with one named
--with-ssl for OpenSSL, but it needs to be able to use multiple
libraries at run time.  I can spot that libssh2 uses what you are
proposing.  It seems to me that --with-ssl is a bit more popular but
not by that much: wget, wayland, some apache stuff (it uses a path as
option value).  Anyway, what you are suggesting sounds like a good in
the context of Postgres.  Daniel?
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 29 Jan 2021 00:20:21 +0100

> On 28 Jan 2021, at 07:06, Michael Paquier <[email-masked]> wrote:

> libraries at run time.  

To be fair, if we started over in curl I would push back on --with-ssl meaning
OpenSSL but that ship has long since sailed.

> I can spot that libssh2 uses what you are

SSL is admittedly an obsolete technical term, but it's one that enough people
have decided is interchangeable with TLS that it's not a hill worth dying on
IMHO.  Since postgres won't allow for using libnss or OpenSSL for cryptohash
*without* compiling SSL/TLS support (used or not), I think --with-ssl=LIB is
more descriptive and less confusing.

--
Daniel Gustafsson		https://vmware.com/

---

From: Jacob Champion <[email-masked]>
Date: Fri, 29 Jan 2021 01:06:22 +0000

> implementation, in be_tls_init():

Never mind. Using SSL_SetTrustAnchor is something we could potentially
do if we wanted to further limit the CAs that are actually sent to the
client, but it shouldn't be necessary to get the tests to pass.

I now think that it's just a matter of making sure that the "server-cn-
only" DB has the root_ca.crt included, so that it can correctly
validate the client certificate. Incidentally I think this should also
fix the remaining failing SCRAM test. I'll try to get a patch out
tomorrow, if adding the root CA doesn't invalidate some other test
logic.

--Jacob

---

From: Michael Paquier <[email-masked]>
Date: Fri, 29 Jan 2021 15:01:40 +0900

> more descriptive and less confusing.

Okay, let's use --with-ssl then for the new switch name.  The previous
patch is backward-compatible, and will simplify the rest of the set,
so let's move on with it.  Once this is done, my guess is that it
would be cleaner to have a new patch that includes only the
./configure and MSVC changes, and then the rest: test refactoring,
cryptohash, strong random and lastly TLS (we may want to cut this a
bit more though and perhaps have some restrictions depending on the
scope of options a first patch set could support).

I'll wait a bit first to see if there are any objections to this
change.
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 29 Jan 2021 13:57:02 +0100

> On 21 Jan 2021, at 06:21, Michael Paquier <[email-masked]> wrote:
> 

This has been discussed elsewhere in the thread, so let's continue that there.
The attached v23 does however split off --with-ssl for OpenSSL in 0001, adding
the nss option in 0002.

> This makes sense taken independently.

This has been submitted in [email-masked].

> the code dedicated to NSS.

Aha, now I see what you mean, sorry for the confusion.  That can certainly be
done (and done so outside of this patchset), but it admittedly feels a bit
intrusive.  If there is consensus that we should namespace our version like
this I'll go ahead and do that.

Fixed.

> Patch 0006 has three trailing whitespaces (git diff --check complains).

Fixed.

> Running the regression tests of pgcrypto, I think that
> reports results from already-freed data.  

I've been unable to reproduce, can you shed some light on this?

> I have spotted a second

I think the freezing you saw comes from opening and closing NSS contexts per
cryptohash op (some patience on my part runs the test Ok in ~30s which is
clearly not in the wheelhouse of acceptable), more on that below.

> shared library callers need to know about the OOM failure.

Of course, fixed.

> This needs to return -1 on failure, not 1.

Doh, fixed.

> think that saving nsscontext in pg_cryptohash_ctx is right for each

It's a safe but slow option, NSS wasn't really made for running a single crypto
operation.  Since we are opening a context which isn't backed by an NSS
database we could have a static context, which indeed speeds up processing a
lot.  The problem with that is that there is no good callsite for closing the
context as the backend is closing down.  Since you are kneedeep in the
cryptohash code, do you have any thoughts on this?  I've included 0008 which
implements this, with a commented out dummy stub for cleaning up.

Making nss_context static in cryptohash_nss.c is
appealing but there is no good option for closing it there.  Any thoughts on
how to handle global contexts like this?

Fixed.

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 29 Jan 2021 14:13:30 +0100

> On 29 Jan 2021, at 07:01, Michael Paquier <[email-masked]> wrote:
> 

I'm still not convinced that adding --with-ssl=openssl is worth it before the
rest of NSS goes in (and more importantly, *if* it goes in).

On the one hand, we already have pluggable (for some value of) support for
adding TLS libraries, and adding --with-ssl is one more piece of that puzzle.
We could of course have endless --with-X options instead but as you say,
--with-uuid has set the tone here (and I believe that's good).  On the other
hand, if we never add any other library than OpenSSL then it's just complexity
without benefit.

As mentioned elsewhere in the thread, the current v23 patchset has the
--with-ssl change as a separate commit to at least make it visual what it looks
like.  The documentation changes are in the main NSS patch though since
documenting --with-ssl when there is only one possible value didn't seem to be
helpful to users whom are fully expected to use --with-openssl still.

---

From: Jacob Champion <[email-masked]>
Date: Fri, 29 Jan 2021 18:46:17 +0000

> how to handle global contexts like this?

I'm completely new to this code, so take my thoughts with a grain of
salt...

I think the bad news is that the static approach will need support for
ENABLE_THREAD_SAFETY. (It looks like the NSS implementation of
pgtls_close() needs some thread support too?)

The good(?) news is that I don't understand why OpenSSL's
implementation of cryptohash doesn't _also_ need the thread-safety
code. (Shouldn't we need to call CRYPTO_set_locking_callback() et al
before using any of its cryptohash implementation?) So maybe we can
implement the same global setup/teardown API for OpenSSL too and not
have to one-off it for NSS...

--Jacob

---

From: Michael Paquier <[email-masked]>
Date: Sat, 30 Jan 2021 10:27:22 +0900

> hand, if we never add any other library than OpenSSL then it's just complexity

IMO, one could say the same thing for any piece of refactoring we have
done in the past to make the TLS/crypto code more modular.  There is
demand for being able to choose among multiple SSL libs at build time,
and we are still in a phase where we evaluate the options at hand.
This refactoring is just careful progress, and this is one step in
this direction.  The piece about refactoring the SSL tests is
similar.

> helpful to users whom are fully expected to use --with-openssl still.

The documentation changes should be part of the patch introducing the
switch IMO: a description of the new switch, as well as a paragraph
about the old value being deprecated.  That's done this way for UUID.
--
Michael

---

From: Michael Paquier <[email-masked]>
Date: Mon, 1 Feb 2021 22:25:37 +0900

> The attached v23 does however split off --with-ssl for OpenSSL in 0001, adding

While going through 0001, I have found a couple of things.

-CF_SRCS = $(if $(subst no,,$(with_openssl)), $(OSSL_SRCS), $(INT_SRCS))
-CF_TESTS = $(if $(subst no,,$(with_openssl)), $(OSSL_TESTS), $(INT_TESTS))
+CF_SRCS = $(if $(subst openssl,,$(with_ssl)), $(OSSL_SRCS), $(INT_SRCS))
+CF_TESTS = $(if $(subst openssl,,$(with_ssl)), $(OSSL_TESTS), $(INT_TESTS))
It seems to me that this part is the opposite, aka here the OpenSSL
files and tests (OSSL*) would be used if with_ssl is not openssl.

-ifeq ($(with_openssl),yes)
+ifneq ($(with_ssl),no)
+OBJS += \
+       fe-secure-common.o
+endif
This split is better, good idea.

The two SSL tests still included a reference to with_openssl after
0001:
src/test/ssl/t/001_ssltests.pl:if ($ENV{with_openssl} eq 'yes')
src/test/ssl/t/002_scram.pl:if ($ENV{with_openssl} ne 'yes')

I have refreshed the docs on top to be consistent with the new
configuration, and applied it after more checks.  I'll try to look in
more details at the failures with cryptohashes I found upthread.
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 1 Feb 2021 21:49:20 +0100

> On 20 Jan 2021, at 18:07, Jacob Champion <[email-masked]> wrote:

> - subjects that have no CN at all

Nice, thanks for fixing this!

> authentication callback, it results in a TLS alert rather than simply

But returning SECFailure from the cert callback force NSS to terminate the
connection immediately doesn't it?

> since-v22.diff, which is part of the 0001 patch.

I confused my dev trees and missed to include this in the v23 that I sent out
(which should've been v24), sorry about that.  Attached is a v24 which is
rebased on top of todays --with-ssl commit, and now includes your changes.

Additionally I've added a shutdown callback such that we close the connection
immediately if NSS is shutting down from underneath us.  I can't imagine a
scenario in which that's benign, so let's take whatever precautions we can.

I've also changed the NSS initialization in the cryptohash code to closer match
what the NSS documentation recommends for similar scenarios, but more on that
downthread where that's discussed.

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 1 Feb 2021 21:49:26 +0100

> On 29 Jan 2021, at 19:46, Jacob Champion <[email-masked]> wrote:

> ENABLE_THREAD_SAFETY.

I did some more reading today and noticed that the NSS documentation (and their
sample code for doing crypto without TLS connections) says to use NSS_NoDB_Init
to perform a read-only init which don't require a matching close call.  Now,
the docs aren't terribly clear and also seems to have gone offline from MDN,
and skimming the code isn't entirelt self-explanatory, so I may well have
missed something.  The v24 patchset posted changes to this and at least passes
tests with decent performance so it seems worth investigating.

> (It looks like the NSS implementation of pgtls_close() needs some thread
> support too?)

Storing the context in conn would probably be better?

> have to one-off it for NSS...

No idea here, wouldn't that impact pgcrypto as well in that case?

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 1 Feb 2021 21:51:49 +0100

> On 1 Feb 2021, at 14:25, Michael Paquier <[email-masked]> wrote:

> configuration, and applied it after more checks.

Thanks, I was just about to send a rebased version earlier today with the doc
changes in the 0001 patch when this email landed in my inbox =) The v24 posted
upthread is now rebased on top of this.

> I'll try to look in more details at the failures with cryptohashes I found
> upthread.

Great, thanks.

---

From: Jacob Champion <[email-masked]>
Date: Tue, 2 Feb 2021 00:42:23 +0000

> tests with decent performance so it seems worth investigating.

Nice! Not having to close helps quite a bit.

(Looks like thread safety for NSS_Init was added in 3.13, so we have an
absolute version floor.)

> Storing the context in conn would probably be better?

Agreed.

> No idea here, wouldn't that impact pgcrypto as well in that case?

If pgcrypto is backend-only then I don't think it should need
multithreading protection; is that right?

--Jacob

---

From: Jacob Champion <[email-masked]>
Date: Tue, 2 Feb 2021 00:55:57 +0000

> connection immediately doesn't it?

IIRC NSS will send the alert first, whereas our OpenSSL implementation
will complete the handshake and then drop the connection. I'll rebuild
with the latest and confirm.

> rebased on top of todays --with-ssl commit, and now includes your changes.

No problem. Thanks!

--Jacob

---

From: Michael Paquier <[email-masked]>
Date: Tue, 2 Feb 2021 10:06:08 +0900

> (Looks like thread safety for NSS_Init was added in 3.13, so we have an

If that's the case, I would recommend to add at least something in the
section called install-requirements in the docs.

> multithreading protection; is that right?

No need for it in the backend, unless there are plans to switch from
processes to threads there :p

libpq, ecpg and anything using them have to care about that.  Worth
noting that OpenSSL also has some special handling in libpq with
CRYPTO_get_id_callback() and that it tracks the number of opened
connections.
--
Michael

---

From: Jacob Champion <[email-masked]>
Date: Tue, 2 Feb 2021 20:33:35 +0000

> with the latest and confirm.

I wasn't able to reproduce the behavior I thought I saw before. In any
case I think the current NSS implementation for embedded NULLs will
work correctly.

> > Attached is a v24 which is

I have a v25 attached which fixes and re-enables the skipped/todo'd
client certificate and SCRAM tests. (Changes between v24 and v25 are in
since-v24.diff.) The server-cn-only database didn't have the root CA
installed to be able to verify client certificates, so I've added it.

Note that this changes the error message printed during the invalid-
root tests, because NSS is now sending the root of the chain. So the
server's issuer is considered untrusted rather than unrecognized.

--Jacob
commit 093bb937736cdfc871d8fd479748f93f18108ae0
Author: Jacob Champion <[email-masked]>
Date:   Fri Jan 29 09:32:27 2021 -0800

    test/ssl: fix final TODOs and SKIPs
    
    The server-cn-only database didn't have the root CA installed to be able
    to verify client certificates. Note that this changes the error message
    printed during the invalid-root tests, because the server is now sending
    the root of the chain (so the issuer is untrusted rather than
    unrecognized).

diff --git a/src/test/ssl/Makefile b/src/test/ssl/Makefile
index d275c89672..c8032a2c13 100644
--- a/src/test/ssl/Makefile
+++ b/src/test/ssl/Makefile
@@ -147,6 +147,7 @@ ssl/nss/server-cn-only.crt__server-cn-only.key.db: ssl/server-cn-only.crt ssl/se
 	certutil -d "sql:$@" -N --empty-password
 	certutil -d "sql:$@" -A -n ssl/server-cn-only.crt -i ssl/server-cn-only.crt -t "CT,C,C"
 	certutil -d "sql:$@" -A -n server_ca.crt -i ssl/server_ca.crt -t "CT,C,C"
+	certutil -d "sql:$@" -A -n root_ca.crt -i ssl/root_ca.crt -t "CT,C,C"
 	openssl pkcs12 -export -out ssl/nss/server-cn-only.pfx -inkey ssl/server-cn-only.key -in ssl/server-cn-only.crt -certfile ssl/server_ca.crt -passout pass:
 	pk12util -i ssl/nss/server-cn-only.pfx -d "sql:$@" -W ''
 
diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl
index 6b8bca2846..5a83a1d277 100644
--- a/src/test/ssl/t/001_ssltests.pl
+++ b/src/test/ssl/t/001_ssltests.pl
@@ -159,12 +159,12 @@ test_connect_ok(
 test_connect_fails(
 	$common_connstr,
 	"sslrootcert=invalid sslmode=verify-ca",
-	qr/root certificate file "invalid" does not exist|Peer's Certificate issuer is not recognized/,
+	qr/root certificate file "invalid" does not exist|Peer's certificate issuer has been marked as not trusted by the user/,
 	"connect without server root cert sslmode=verify-ca");
 test_connect_fails(
 	$common_connstr,
 	"sslrootcert=invalid sslmode=verify-full",
-	qr/root certificate file "invalid" does not exist|Peer's Certificate issuer is not recognized/,
+	qr/root certificate file "invalid" does not exist|Peer's certificate issuer has been marked as not trusted by the user/,
 	"connect without server root cert sslmode=verify-full");
 
 # Try with wrong root cert, should fail. (We're using the client CA as the
@@ -604,14 +604,10 @@ switch_server_cert($node, 'server-cn-only', 'root_ca');
 $common_connstr =
   "user=ssltestuser dbname=certdb sslkey=ssl/client_tmp.key sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR cert_database=ssl/nss/client+client_ca.crt__client.key.db";
 
-TODO:
-{
-	local $TODO = "WIP failure cause currently unknown";
-	test_connect_ok(
-		$common_connstr,
+test_connect_ok(
 
 test_connect_fails(
 	$common_connstr,
diff --git a/src/test/ssl/t/002_scram.pl b/src/test/ssl/t/002_scram.pl
index 4d7874d420..43565bdf6e 100644
--- a/src/test/ssl/t/002_scram.pl
+++ b/src/test/ssl/t/002_scram.pl
@@ -29,7 +29,8 @@ if ($ENV{with_ssl} eq 'openssl')
 elsif ($ENV{with_ssl} eq 'nss')
 {
 	$nss = 1;
-	plan tests => 8;
+	$supports_tls_server_end_point = 1;
+	plan tests => 9;
 }
 else
 {
@@ -79,24 +80,20 @@ test_connect_ok(
 	"user=ssltestuser channel_binding=disable",
 	"SCRAM with SSL and channel_binding=disable");
 
-SKIP:
+if ($supports_tls_server_end_point)
 {
-	skip "NSS support for TLS server endpoing is not implemented", 1 if ($nss);
-	if ($supports_tls_server_end_point)
-	{
-		test_connect_ok(
-			$common_connstr,
-			"user=ssltestuser channel_binding=require",
-			"SCRAM with SSL and channel_binding=require");
-	}
-	else
-	{
-		test_connect_fails(
-			$common_connstr,
-			"user=ssltestuser channel_binding=require",
-			qr/channel binding is required, but server did not offer an authentication method that supports channel binding/,
-			"SCRAM with SSL and channel_binding=require");
-	}
+	test_connect_ok(
+		$common_connstr,
+		"user=ssltestuser channel_binding=require",
+		"SCRAM with SSL and channel_binding=require");
+}
+else
+{
+	test_connect_fails(
+		$common_connstr,
+		"user=ssltestuser channel_binding=require",
+		qr/channel binding is required, but server did not offer an authentication method that supports channel binding/,
+		"SCRAM with SSL and channel_binding=require");
 }
 
 # Now test when the user has an MD5-encrypted password; should fail
@@ -106,21 +103,17 @@ test_connect_fails(
 	qr/channel binding required but not supported by server's authentication request/,
 	"MD5 with SSL and channel_binding=require");
 
-SKIP:
-{
-	skip "NSS support not implemented yet", 1 if ($nss);
-	# Now test with auth method 'cert' by connecting to 'certdb'. Should fail,
-	# because channel binding is not performed.  Note that ssl/client.key may
-	# be used in a different test, so the name of this temporary client key
-	# is chosen here to be unique.
-	my $client_tmp_key = "ssl/client_scram_tmp.key";
-	copy("ssl/client.key", $client_tmp_key);
-	chmod 0600, $client_tmp_key;
-	test_connect_fails(
-		"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR",
-		"dbname=certdb user=ssltestuser channel_binding=require",
-		qr/channel binding required, but server authenticated client without channel binding/,
-		"Cert authentication and channel_binding=require");
-	# clean up
-	unlink($client_tmp_key);
-}
+# Now test with auth method 'cert' by connecting to 'certdb'. Should fail,
+# because channel binding is not performed.  Note that ssl/client.key may
+# be used in a different test, so the name of this temporary client key
+# is chosen here to be unique.
+my $client_tmp_key = "ssl/client_scram_tmp.key";
+copy("ssl/client.key", $client_tmp_key);
+chmod 0600, $client_tmp_key;
+test_connect_fails(
+	"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR cert_database=ssl/nss/client.crt__client.key.db",
+	"dbname=certdb user=ssltestuser channel_binding=require",
+	qr/channel binding required, but server authenticated client without channel binding/,
+	"Cert authentication and channel_binding=require");
+# clean up
+unlink($client_tmp_key);
From 0c00c0ba3a4197eddb7943c1098732384912d6cd Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:18:42 +0100
Subject: [PATCH v25 1/6] NSS Frontend, Backend and build infrastructure

TODO:

Daniel Gustafsson, Andrew Dunstan, Jacob Champion
---
 configure                                     |  294 +++-
 configure.ac                                  |   31 +-
 .../postgres_fdw/expected/postgres_fdw.out    |    2 +-
 src/backend/libpq/Makefile                    |    4 +
 src/backend/libpq/auth.c                      |    7 +
 src/backend/libpq/be-secure-nss.c             | 1402 +++++++++++++++++
 src/backend/libpq/be-secure.c                 |    3 +
 src/backend/libpq/hba.c                       |    2 +-
 src/backend/utils/misc/guc.c                  |   20 +-
 src/common/Makefile                           |    5 +
 src/include/common/pg_nss.h                   |  175 ++
 src/include/libpq/libpq-be.h                  |   15 +-
 src/include/libpq/libpq.h                     |    3 +
 src/include/pg_config.h.in                    |    3 +
 src/include/pg_config_manual.h                |    5 +-
 src/interfaces/libpq/Makefile                 |    5 +
 src/interfaces/libpq/fe-connect.c             |    4 +
 src/interfaces/libpq/fe-secure-nss.c          | 1112 +++++++++++++
 src/interfaces/libpq/fe-secure.c              |    5 +-
 src/interfaces/libpq/libpq-fe.h               |   13 +-
 src/interfaces/libpq/libpq-int.h              |   20 +-
 src/tools/msvc/Mkvcbuild.pm                   |   22 +-
 src/tools/msvc/Solution.pm                    |   20 +
 23 files changed, 3150 insertions(+), 22 deletions(-)
 create mode 100644 src/backend/libpq/be-secure-nss.c
 create mode 100644 src/include/common/pg_nss.h
 create mode 100644 src/interfaces/libpq/fe-secure-nss.c

diff --git a/configure b/configure
index ce9ea36999..143726c79c 100755
--- a/configure
+++ b/configure
@@ -654,6 +654,8 @@ UUID_LIBS
 LDAP_LIBS_BE
 LDAP_LIBS_FE
 with_ssl
+NSPR_CONFIG
+NSS_CONFIG
 PTHREAD_CFLAGS
 PTHREAD_LIBS
 PTHREAD_CC
@@ -1570,7 +1572,7 @@ Optional Packages:
                           use system time zone data in DIR
   --without-zlib          do not use Zlib
   --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
-  --with-ssl=LIB          use LIB for SSL/TLS support (openssl)
+  --with-ssl=LIB          use LIB for SSL/TLS support (openssl, nss)
   --with-openssl          obsolete spelling of --with-ssl=openssl
 
 Some influential environment variables:
@@ -12462,8 +12464,274 @@ done
 
 $as_echo "#define USE_OPENSSL 1" >>confdefs.h
 
 elif test "$with_ssl" != no ; then
-  as_fn_error $? "--with-ssl must specify openssl" "$LINENO" 5

@@ -13369,6 +13637,23 @@ else
 fi

 if test "$with_pam" = yes ; then
@@ -18131,6 +18416,9 @@ $as_echo_n "checking which random number source to use... " >&6; }
 if test x"$with_ssl" = x"openssl" ; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: OpenSSL" >&5
 $as_echo "OpenSSL" >&6; }
+elif test x"$with_ssl" = x"nss" ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: NSS" >&5
+$as_echo "NSS" >&6; }
 elif test x"$PORTNAME" = x"win32" ; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: Windows native" >&5
 $as_echo "Windows native" >&6; }
@@ -18160,7 +18448,7 @@ fi
   if test x"$ac_cv_file__dev_urandom" = x"no" ; then
     as_fn_error $? "
 no source of strong random numbers was found
-PostgreSQL can use OpenSSL, native Windows API or /dev/urandom as a source of random numbers." "$LINENO" 5
+PostgreSQL can use OpenSSL, NSS, native Windows API or /dev/urandom as a source of random numbers." "$LINENO" 5
   fi
 fi
 
diff --git a/configure.ac b/configure.ac
index 07da84d401..59657a6010 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1201,7 +1201,7 @@ fi
 #
 # There is currently only one supported SSL/TLS library: OpenSSL.
 #
-PGAC_ARG_REQ(with, ssl, [LIB], [use LIB for SSL/TLS support (openssl)])
+PGAC_ARG_REQ(with, ssl, [LIB], [use LIB for SSL/TLS support (openssl, nss)])
 if test x"$with_ssl" = x"" ; then
   with_ssl=no
 fi
@@ -1235,8 +1235,28 @@ if test "$with_ssl" = openssl ; then
   # function was removed.
   AC_CHECK_FUNCS([CRYPTO_lock])
   AC_DEFINE([USE_OPENSSL], 1, [Define to 1 if you have OpenSSL support.])
+elif test "$with_ssl" = nss ; then
+  # TODO: fallback in case nss-config/nspr-config aren't found.
+  PGAC_PATH_PROGS(NSS_CONFIG, nss-config)
+  PGAC_PATH_PROGS(NSPR_CONFIG, nspr-config)
+  if test -n "$NSS_CONFIG"; then
+    NSS_LIBS=`$NSS_CONFIG --libs`
+	NSS_CFLAGS=`$NSS_CONFIG --cflags`
+  fi
+  if test -n "$NSPR_CONFIG"; then
+	NSPR_LIBS=`$NSPR_CONFIG --libs`
+	NSPR_CFLAGS=`$NSPR_CONFIG --cflags`
+  fi
+
+  LDFLAGS="$LDFLAGS $NSS_LIBS $NSPR_LIBS"
+  CFLAGS="$CFLAGS $NSS_CFLAGS $NSPR_CFLAGS"
+
+  AC_CHECK_LIB(nss3, NSS_InitContext, [], [AC_MSG_ERROR([library 'nss3' is required for NSS])])
+  AC_CHECK_LIB(nspr4, PR_GetDefaultIOMethods, [], [AC_MSG_ERROR([library 'nspr4' is required for NSS])])
+  AC_CHECK_LIB(ssl3, SSL_GetImplementedCiphers, [], [AC_MSG_ERROR([library 'ssl3' is required for NSS])])
+  AC_DEFINE([USE_NSS], 1, [Define to 1 if you have NSS support,])
 elif test "$with_ssl" != no ; then
-  AC_MSG_ERROR([--with-ssl must specify openssl])
+  AC_MSG_ERROR([--with-ssl must specify one of openssl or nss])
 fi
 AC_SUBST(with_ssl)
 
@@ -1414,6 +1434,9 @@ fi
 if test "$with_ssl" = openssl ; then
 
 if test "$with_pam" = yes ; then
@@ -2170,6 +2193,8 @@ fi
 AC_MSG_CHECKING([which random number source to use])
 if test x"$with_ssl" = x"openssl" ; then
   AC_MSG_RESULT([OpenSSL])
+elif test x"$with_ssl" = x"nss" ; then
+  AC_MSG_RESULT([NSS])
 elif test x"$PORTNAME" = x"win32" ; then
   AC_MSG_RESULT([Windows native])
 else
@@ -2179,7 +2204,7 @@ else
   if test x"$ac_cv_file__dev_urandom" = x"no" ; then
     AC_MSG_ERROR([
 no source of strong random numbers was found
-PostgreSQL can use OpenSSL, native Windows API or /dev/urandom as a source of random numbers.])
+PostgreSQL can use OpenSSL, NSS, native Windows API or /dev/urandom as a source of random numbers.])
   fi
 fi
 
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index b09dce63f5..fbbe778217 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -8928,7 +8928,7 @@ DO $d$
     END;
 $d$;
 ERROR:  invalid option "password"
-HINT:  Valid options in this context are: service, passfile, channel_binding, connect_timeout, dbname, host, hostaddr, port, options, application_name, keepalives, keepalives_idle, keepalives_interval, keepalives_count, tcp_user_timeout, sslmode, sslcompression, sslcert, sslkey, sslrootcert, sslcrl, requirepeer, ssl_min_protocol_version, ssl_max_protocol_version, gssencmode, krbsrvname, gsslib, target_session_attrs, use_remote_estimate, fdw_startup_cost, fdw_tuple_cost, extensions, updatable, fetch_size, batch_size
+HINT:  Valid options in this context are: service, passfile, channel_binding, connect_timeout, dbname, host, hostaddr, port, options, application_name, keepalives, keepalives_idle, keepalives_interval, keepalives_count, tcp_user_timeout, sslmode, sslcompression, sslcert, sslkey, sslrootcert, sslcrl, requirepeer, ssl_min_protocol_version, ssl_max_protocol_version, gssencmode, krbsrvname, gsslib, target_session_attrs, cert_database, use_remote_estimate, fdw_startup_cost, fdw_tuple_cost, extensions, updatable, fetch_size, batch_size
 CONTEXT:  SQL statement "ALTER SERVER loopback_nopw OPTIONS (ADD password 'dummypw')"
 PL/pgSQL function inline_code_block line 3 at EXECUTE
 -- If we add a password for our user mapping instead, we should get a different
diff --git a/src/backend/libpq/Makefile b/src/backend/libpq/Makefile
index 8d1d16b0fc..045d2c2f6b 100644
--- a/src/backend/libpq/Makefile
+++ b/src/backend/libpq/Makefile
@@ -30,6 +30,10 @@ OBJS = \
 
 ifeq ($(with_ssl),openssl)
 OBJS += be-secure-openssl.o
+else
+ifeq ($(with_ssl),nss)
+OBJS += be-secure-nss.o
+endif
 endif

 
index 0000000000..876e54be51
@@ -0,0 +1,1402 @@
+static NSSInitContext *nss_context = NULL;
+static SECStatus pg_SSLShutdownFunc(void *private_data, void *nss_data);
+static PRInt32 pg_ssl_read(PRFileDesc *fd, void *buf, PRInt32 amount,
+static PRInt32 pg_ssl_write(PRFileDesc *fd, const void *buf, PRInt32 amount,
+static PRStatus pg_ssl_close(PRFileDesc *fd);
+static PRFileDesc *init_iolayer(Port *port);
+static SECStatus pg_cert_auth_handler(void *arg, PRFileDesc *fd,
+static SECStatus pg_bad_cert_handler(void *arg, PRFileDesc *fd);
+static char *dummy_ssl_passphrase_cb(PK11SlotInfo *slot, PRBool retry, void *arg);
+	/* Set up certificate authentication callback */
+	/* Register out shutdown callback */
+	NSS_RegisterShutdown(pg_SSLShutdownFunc, port);
+pg_bad_cert_handler(void *arg, PRFileDesc *fd)
+ * raw_subject_common_name
+ * embedded nulls), with the length of the buffer returned in the len param.
+			/* Found a CN, ecode and copy it into a newly allocated buffer */
+				 * This failure case is difficult to test. (Since this code
+				 * runs after certificate authentication has otherwise
+				 * succeeded, you'd need to convince a CA implementation to
+				 * sign a corrupted certificate in order to get here.)
+ * Callback for validation of incoming certificates. Returning SECFailure will
+ * cause NSS to terminate the connection immediately.
+ * pg_SSLShutdownFunc
+ *		Callback for NSS shutdown
+ * If NSS is terminated from the outside when the connection is still in use
+ * we must treat this as potentially hostile and immediately close to avoid
+ * leaking the connection in any way. Once this is called, NSS will shutdown
+ * regardless so we may as well clean up the best we can. Returning SECFailure
+ * will cause the NSS shutdown to return with an error, but it will shutdown
+ * nevertheless. nss_data is reserved for future use and is always NULL.
+pg_SSLShutdownFunc(void *private_data, void *nss_data)
+	Port *port = (Port *) private_data;
+	if (!port || !port->ssl_in_use)
+	 * There is a connection still open, close it and signal to whatever that
+	 * called the shutdown that it was erroneous.
+	be_tls_close(port);
+	be_tls_destroy();
 
index 20bf1461ce..9a04c093d5 100644
-					 errhint("Compile with --with-ssl=openssl to use SSL connections."),
+					 errhint("Compile with --with-ssl to use SSL connections."),
index eafdb1118e..b023b31c46 100644
 
+#ifdef USE_NSS
+	{
index 5422579a6a..be8b2583b2 100644
@@ -85,12 +85,17 @@ OBJS_COMMON += \
 	protocol_openssl.o \
 	cryptohash_openssl.o
 else
+ifeq ($(with_ssl),nss)
+OBJS_COMMON += \
+	cryptohash_nss.o
+else
 OBJS_COMMON += \
 	cryptohash.o \
 	md5.o \
 	sha1.o \
 	sha2.o
 endif
+endif

 	/*
 
 #ifdef USE_SSL
 
 #endif							/* USE_SSL */

index 55cab4d2bf..8856a33590 100644
 
+/* Define to build with NSS support (--with-ssl=nss) */
+#undef USE_NSS
+
 /* Define to 1 to use software CRC-32C implementation (slicing-by-8). */
 #undef USE_SLICING_BY_8_CRC32C

 /*
 
diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile
index f74677eaf9..e10d8bef42 100644
--- a/src/interfaces/libpq/Makefile
+++ b/src/interfaces/libpq/Makefile
@@ -56,6 +56,11 @@ OBJS += \
 	fe-secure-openssl.o
 endif
 
+ifeq ($(with_ssl), nss)
+OBJS += \
+	fe-secure-nss.o
+endif
+
index 8ca0583aa9..1eeeff54a8 100644
 
index 00b87bdc96..44385ee391 100644
@@ -421,6 +421,9 @@ PQsslAttributeNames(PGconn *conn)
 
 	return result;
 }
+#endif							/* USE_SSL */
+
+#ifndef USE_OPENSSL
 
 PQsslKeyPassHook_OpenSSL_type
 PQgetSSLKeyPassHook_OpenSSL(void)
@@ -439,7 +442,7 @@ PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
 {
 	return 0;
 }
-#endif							/* USE_SSL */
+#endif							/* USE_OPENSSL */

 

 #ifdef ENABLE_GSS
index 90328db04e..ff01acf3f6 100644
@@ -195,12 +195,19 @@ sub mkvcbuild
 
@@ -258,12 +265,19 @@ sub mkvcbuild
 
index 1c0c92fcd2..5148708969 100644

From f64fd9a6a6f03d2fb6eb1d5c2c4f31bccf8eaf8f Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:22:26 +0100
Subject: [PATCH v25 2/6] NSS Testharness updates

TODO:

Daniel Gustafsson, Jacob Champion
---
 src/test/ssl/Makefile                         | 234 ++++++++++++
 src/test/ssl/t/001_ssltests.pl                | 340 +++++++++++-------
 src/test/ssl/t/002_scram.pl                   |  37 +-
 src/test/ssl/t/SSL/Backend/NSS.pm             |  73 ++++
 src/test/ssl/t/SSL/Backend/OpenSSL.pm         | 103 ++++++
 .../ssl/t/{SSLServer.pm => SSL/Server.pm}     |  80 ++++-
 6 files changed, 704 insertions(+), 163 deletions(-)
 create mode 100644 src/test/ssl/t/SSL/Backend/NSS.pm
 create mode 100644 src/test/ssl/t/SSL/Backend/OpenSSL.pm
 rename src/test/ssl/t/{SSLServer.pm => SSL/Server.pm} (78%)

index d545382eea..c8032a2c13 100644

 
@@ -77,6 +128,79 @@ ssl/server-ss.crt: ssl/server-cn-only.key ssl/server-cn-only.crt server-cn-only.
 
@@ -88,6 +212,27 @@ ssl/client.crt: ssl/client.key ssl/client_ca.crt
 
@@ -95,6 +240,14 @@ ssl/client-revoked.crt: ssl/client-revoked.key ssl/client_ca.crt client.config
 
@@ -127,19 +280,40 @@ ssl/root+client_ca.crt: ssl/root_ca.crt ssl/client_ca.crt

 

@@ -147,13 +321,73 @@ ssl/root+server.crl: ssl/root.crl ssl/server.crl

+.PHONY: nssfiles-clean
+nssfiles-clean:
+	rm -rf ssl/nss
+
 
 # Doesn't depend on $(SSLFILES) because we don't rebuild them by default
 check:
diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl
index 7928de4e7c..5a83a1d277 100644
--- a/src/test/ssl/t/001_ssltests.pl
+++ b/src/test/ssl/t/001_ssltests.pl
@@ -4,20 +4,27 @@ use PostgresNode;
 use TestLib;
 use Test::More;
 
-use File::Copy;
-
 use FindBin;
 
-use SSLServer;
+use SSL::Server;
+
+my $openssl;
+my $nss;
 
-if ($ENV{with_ssl} ne 'openssl')
+if ($ENV{with_ssl} eq 'openssl')
+{
+	$openssl = 1;
+	plan tests => 93;
+}
+elsif ($ENV{with_ssl} eq 'nss')
 {
-	plan skip_all => 'OpenSSL not supported by this build';
+	$nss = 1;
+	plan tests => 99;
 }
 else
 {
-	plan tests => 93;
+	plan skip_all => 'SSL not supported by this build';
 }
 
 #### Some configuration

 

 
 
-command_fails(

-command_ok(
 
+	qr/root certificate file "invalid" does not exist|Peer's certificate issuer has been marked as not trusted by the user/,
+	qr/root certificate file "invalid" does not exist|Peer's certificate issuer has been marked as not trusted by the user/,

 

 

 
 test_connect_ok(
 	$common_connstr,

 $common_connstr =
 
 test_connect_ok(
 	$common_connstr,

 $common_connstr =
 
 test_connect_ok(
 	$common_connstr,

 $common_connstr =
 
 test_connect_ok(
 	$common_connstr,

 test_connect_ok(
 	$common_connstr,

 

 $common_connstr =
 
 # no client cert
 test_connect_fails(

 

 
 
 	test_connect_fails(
 		$common_connstr,
 
+$common_connstr =
 
 test_connect_ok(
 	$common_connstr,
@@ -536,17 +602,19 @@ test_connect_ok(
 
 test_connect_ok(
 	$common_connstr,
 	"sslmode=require sslcert=ssl/client+client_ca.crt",
 	"intermediate client certificate is provided by client");
-test_connect_fails($common_connstr, "sslmode=require sslcert=ssl/client.crt",
-	qr/SSL error/, "intermediate client certificate is missing");
+
+test_connect_fails(
+	$common_connstr,
+	"sslmode=require sslcert=ssl/client.crt",
+	qr/connection requires a valid client certificate|SSL error/,
+	"intermediate client certificate is missing");
 
 # clean up
-foreach my $key (@keys)
-{
-	unlink("ssl/${key}_tmp.key");
-}
+
+SSL::Server::cleanup();
diff --git a/src/test/ssl/t/002_scram.pl b/src/test/ssl/t/002_scram.pl
index 410b9e910d..43565bdf6e 100644
--- a/src/test/ssl/t/002_scram.pl
+++ b/src/test/ssl/t/002_scram.pl
@@ -11,11 +11,30 @@ use File::Copy;
 use FindBin;
 use lib $FindBin::RealBin;
 
-use SSLServer;
+use SSL::Server;
 
-if ($ENV{with_ssl} ne 'openssl')
+my $openssl;
+my $nss;
+
+my $supports_tls_server_end_point;
+
+if ($ENV{with_ssl} eq 'openssl')
+{
+	$openssl = 1;
+	# Determine whether build supports tls-server-end-point.
+	$supports_tls_server_end_point =
+		check_pg_config("#define HAVE_X509_GET_SIGNATURE_NID 1");
+	plan tests => $supports_tls_server_end_point ? 9 : 10;
+}
+elsif ($ENV{with_ssl} eq 'nss')
+{
+	$nss = 1;
+	$supports_tls_server_end_point = 1;
+	plan tests => 9;
+}
+else
 {
-	plan skip_all => 'OpenSSL not supported by this build';
+	plan skip_all => 'SSL not supported by this build';
 }
 
 # This is the hostname used to connect to the server.
@@ -23,12 +42,6 @@ my $SERVERHOSTADDR = '127.0.0.1';
 # This is the pattern to use in pg_hba.conf to match incoming connections.
 my $SERVERHOSTCIDR = '127.0.0.1/32';

@@ -66,6 +79,7 @@ test_connect_ok(
 	$common_connstr,
 if ($supports_tls_server_end_point)
@@ -97,12 +111,9 @@ my $client_tmp_key = "ssl/client_scram_tmp.key";
 copy("ssl/client.key", $client_tmp_key);
 chmod 0600, $client_tmp_key;
+	"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR cert_database=ssl/nss/client.crt__client.key.db",
 	"dbname=certdb user=ssltestuser channel_binding=require",
 	qr/channel binding required, but server authenticated client without channel binding/,
 	"Cert authentication and channel_binding=require");
 unlink($client_tmp_key);
 
-package SSLServer;
+package SSL::Server;
 
 use strict;
 use warnings;
 use PostgresNode;
+use RecursiveCopy;
 use TestLib;
 use File::Basename;
 use File::Copy;
 use Test::More;
 
 use Exporter 'import';
 our @EXPORT = qw(

 

 

From 61ebfcf1ab77a3e1b730601a8fa418353dc432ab Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:24:02 +0100
Subject: [PATCH v25 3/6] NSS pg_strong_random support

---
 configure                   |  1 +
 configure.ac                |  1 +
 src/include/pg_config.h.in  |  3 +++
 src/port/pg_strong_random.c | 50 ++++++++++++++++++++++++++++++++++++-
 4 files changed, 54 insertions(+), 1 deletion(-)

diff --git a/configure b/configure
index 143726c79c..2b83914289 100755
--- a/configure
+++ b/configure
@@ -18422,6 +18422,7 @@ $as_echo "NSS" >&6; }
 elif test x"$PORTNAME" = x"win32" ; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: Windows native" >&5
 $as_echo "Windows native" >&6; }
+
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: /dev/urandom" >&5
 $as_echo "/dev/urandom" >&6; }
diff --git a/configure.ac b/configure.ac
index 59657a6010..6533e10ffd 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2197,6 +2197,7 @@ elif test x"$with_ssl" = x"nss" ; then
   AC_MSG_RESULT([NSS])
 elif test x"$PORTNAME" = x"win32" ; then
   AC_MSG_RESULT([Windows native])
+
 else
   AC_MSG_RESULT([/dev/urandom])
   AC_CHECK_FILE([/dev/urandom], [], [])
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index 8856a33590..fa5a977617 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -908,6 +908,9 @@
 /* Define to build with NSS support (--with-ssl=nss) */
 #undef USE_NSS

 
 
 /*

From 6c23c72132419ed880793383e3efbf294ab4e218 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:26:31 +0100
Subject: [PATCH v25 4/6] NSS Documentation

---
 doc/src/sgml/acronyms.sgml     |  43 ++++++++++++
 doc/src/sgml/config.sgml       |  28 +++++++-
 doc/src/sgml/installation.sgml |  31 ++++++---
 doc/src/sgml/libpq.sgml        |  99 +++++++++++++++++++++++++-
 doc/src/sgml/runtime.sgml      | 123 +++++++++++++++++++++++++++++++--
 5 files changed, 305 insertions(+), 19 deletions(-)

+   <varlistentry>
 
+   <varlistentry>
 
+   <varlistentry>
+    <term><acronym>TLS</acronym></term>
+    <listitem>
+     <para>
+      <ulink url="https://en.wikipedia.org/wiki/Transport_Layer_Security">
+      Transport Layer Security</ulink>
+     </para>
+    </listitem>
+   </varlistentry>
+
    <varlistentry>
     <term><acronym>TOAST</acronym></term>
     <listitem>
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index e17cdcc816..b33cffb370 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -1238,6 +1238,23 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
@@ -1254,7 +1271,9 @@ include_dir 'conf.d'
 
@@ -1456,8 +1475,11 @@ include_dir 'conf.d'
        <para>
         Sets an external command to be invoked when a passphrase for
         decrypting an SSL file such as a private key needs to be obtained.  By
-        default, this parameter is empty, which means the built-in prompting
-        mechanism is used.
+        default, this parameter is empty. When the server is using
+        <productname>OpenSSL</productname>, this means the built-in prompting
+        mechanism is used. When using <productname>NSS</productname>, there is
+        no default prompting so a blank callback will be used returning an
+        empty password.
        </para>
        <para>
         The command must print the passphrase to the standard output and exit
diff --git a/doc/src/sgml/installation.sgml b/doc/src/sgml/installation.sgml
index 66ad4ba938..1b71881c6e 100644
--- a/doc/src/sgml/installation.sgml
+++ b/doc/src/sgml/installation.sgml
@@ -976,15 +976,30 @@ build-postgresql:
        <listitem>
         <para>
          Build with support for <acronym>SSL</acronym> (encrypted)
-         connections. The only <replaceable>LIBRARY</replaceable>
-         supported is <option>openssl</option>. This requires the
-         <productname>OpenSSL</productname> package to be installed.
-         <filename>configure</filename> will check for the required
-         header files and libraries to make sure that your
-         <productname>OpenSSL</productname> installation is sufficient
-         before proceeding. 
+         connections. <replaceable>LIBRARY</replaceable> must be one of:
         </para>
-       </listitem>
+        <itemizedlist>
+         <listitem>
+          <para>
+           <option>openssl</option> to build with <productname>OpenSSL</productname> support.
+            This requires the <productname>OpenSSL</productname>
+            package to be installed.  <filename>configure</filename> will check
+            for the required header files and libraries to make sure that
+            your <productname>OpenSSL</productname> installation is sufficient
+            before proceeding.
+          </para>
+         </listitem>
+         <listitem>
+          <para>
+           <option>nss</option> to build with <productname>libnss</productname> support.
+            This requires the <productname>NSS</productname> package to be installed. Additionally,
+            <productname>NSS</productname> requires <productname>NSPR</productname>
+            to be installed. <filename>configure</filename> will check for the
+            required header files and libraries to make sure that your
+            <productname>NSS</productname> installation is sufficient before
+            proceeding.
+          </para>
+         </listitem>
       </varlistentry>
 
       <varlistentry>
index b7a82453f0..89796de168 100644
 
+      <para>

+      <para>

 
index bf877c0e0c..2578ee8c06 100644
@@ -2185,15 +2185,21 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433

   <para>
 
   <sect2 id="ssl-setup">
@@ -2213,8 +2219,13 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </para>
 
   <para>
@@ -2304,6 +2315,18 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </note>
   </sect2>

@@ -2378,7 +2401,7 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </sect2>

    <para>
     <xref linkend="ssl-file-usage"/> summarizes the files that are
@@ -2425,6 +2448,14 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
       <entry>client certificate must not be on this list</entry>
      </row>
 
+     <row>
@@ -2448,7 +2479,7 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </sect2>

    <para>
      To create a simple self-signed certificate for the server, valid for 365
@@ -2552,6 +2583,88 @@ openssl x509 -req -in server.csr -text -days 365 \
    </para>
   </sect2>

  <sect1 id="gssapi-enc">
-- 
2.25.1

From 0424241820e08e9a7f660f476083898a6976468a Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Wed, 28 Oct 2020 11:34:37 +0100
Subject: [PATCH v25 5/6] NSS contrib modules

---
 7 files changed, 863 insertions(+), 14 deletions(-)

index c0b4f1fcf6..ede7a78146 100644

-CF_SRCS = $(if $(subst openssl,,$(with_ssl)), $(INT_SRCS), $(OSSL_SRCS))
-CF_TESTS = $(if $(subst openssl,,$(with_ssl)), $(INT_TESTS), $(OSSL_TESTS))
+CF_SRCS = $(if $(findstring openssl, $(with_ssl)), $(OSSL_SRCS), $(if $(findstring nss, $(with_ssl)), $(NSS_SRCS), $(INT_SRCS)))
+CF_TESTS = $(if $(findstring openssl, $(with_ssl)), $(OSSL_TESTS), $(if $(findstring nss, $(with_ssl)), $(NSS_TESTS), $(INT_TESTS)))
 CF_PGP_TESTS = $(if $(subst no,,$(with_zlib)), $(ZLIB_TST), $(ZLIB_OFF_TST))
 
 SRCS = \
 
 #include "postgres.h"
 
+#ifdef USE_OPENSSL

 PG_MODULE_MAGIC;
 
+#ifdef USE_OPENSSL

 /*

+#ifdef USE_OPENSSL
 /*
 
+#ifdef USE_NSS
 
 /*

+#ifdef USE_OPENSSL
 /*
index b6bb23de0f..bf486f0c07 100644
 
    <para>
-    <literal>--with-ssl=openssl</literal>.
+    <literal>--with-ssl=openssl</literal> and <literal>--with-ssl=nss</literal>.
    </para>
 
    <para>
 
index 2a9c45a111..f3ae2fc3b8 100644
 
  <para>
   This extension won't build at all unless the installation was
-  configured with <literal>--with-ssl=openssl</literal>.
+  configured with SSL support, such as <literal>--with-ssl=openssl</literal>
+  or <literal>--with-ssl=nss</literal>.
  </para>
 
  <sect2>

index ff01acf3f6..660387d0e8 100644
@@ -445,9 +445,14 @@ sub mkvcbuild

@@ -477,6 +482,11 @@ sub mkvcbuild

From 87f5997c5406f080b34ba5836ed197723bd0e28f Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 18 Jan 2021 13:04:49 +0100
Subject: [PATCH v25 6/6] NSS cryptohash support

---
 src/common/cryptohash_nss.c | 255 ++++++++++++++++++++++++++++++++++++
 src/tools/msvc/Mkvcbuild.pm |   4 +
 2 files changed, 259 insertions(+)
 create mode 100644 src/common/cryptohash_nss.c

index 0000000000..3e2b5776c1
@@ -0,0 +1,255 @@
+ * In the backend, use an allocation in TopMemoryContext to count for
+ * resowner cleanup handling.  In the frontend, use malloc to be able
+ * to return a failure status back to the caller.
+#define ALLOC(size) MemoryContextAlloc(TopMemoryContext, size)
+#define FREE(ptr) pfree(ptr)
+#define ALLOC(size) malloc(size)
+#define FREE(ptr) free(ptr)
+	ctx = ALLOC(sizeof(pg_cryptohash_ctx));
+		case PG_SHA1:
+			ctx->hash_type = SEC_OID_SHA1;
+	status = NSS_NoDB_Init(".");
+		FREE(ctx);
+		FREE(ctx);
+	FREE(ctx);
index 660387d0e8..180eb0aa3f 100644
@@ -132,6 +132,10 @@ sub mkvcbuild
 		push(@pgcommonallfiles, 'cryptohash_openssl.c');
 		push(@pgcommonallfiles, 'protocol_openssl.c');
+		push(@pgcommonallfiles, 'cryptohash_nss.c');
+	}
 	else
 	{
 		push(@pgcommonallfiles, 'cryptohash.c');
-- 
2.25.1

---

From: Michael Paquier <[email-masked]>
Date: Thu, 4 Feb 2021 16:30:37 +0900

> server's issuer is considered untrusted rather than unrecognized.

I think that it is not a good idea to attach the since-v*.diff patches
into the threads.  This causes the CF bot to fail in applying those
patches.

Could it be possible to split 0001 into two parts at least with one
patch that includes the basic changes for the build and ./configure,
and a second with the FE/BE changes?
--
Michael

---

From: Jacob Champion <[email-masked]>
Date: Thu, 4 Feb 2021 18:35:28 +0000

> into the threads.  This causes the CF bot to fail in applying those

Ah, sorry about that. Is there an extension I can use (or lack thereof)
that the CF bot will ignore, or does it scan the attachment contents?

--Jacob

---

From: Michael Paquier <[email-masked]>
Date: Fri, 5 Feb 2021 15:35:39 +0900

> that the CF bot will ignore, or does it scan the attachment contents?

The thing is smart, but there are ways to bypass it.  Here is the
code:
https://github.com/macdice/cfbot/

And here are the patterns looked at:
cfbot_commitfest_rpc.py:    groups = re.search('<a
href="(/message-id/attachment/[^"]*\\.(diff|diff\\.gz|patch|patch\\.gz|tar\\.gz|tgz|tar\\.bz2))">',
line)
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 9 Feb 2021 00:08:37 +0100

> On 4 Feb 2021, at 08:30, Michael Paquier <[email-masked]> wrote:

> and a second with the FE/BE changes?

Attached is a new patchset where I've tried to split the patches even further
to try and separate out changes for easier review.  While not a perfect split
I'm sure, and clearly only for review purposes, I do hope it helps a little.
There is one hunk in 0002 which moves some OpenSSL specific code from
underneath USE_SSL, but thats about the only non-NSS change left in this
patchset AFAICS.

Additionally, this version moves the code in thee shared header to a proper .c
file shared between frontend and backend as well as performs some general
cleanup around that.

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 9 Feb 2021 00:11:05 +0100

> On 4 Feb 2021, at 19:35, Jacob Champion <[email-masked]> wrote:
> 

Naming the file .patch.txt should work, and it serves the double purpose of
making it extra clear that this is not a patch intended to be applied but one
intended to be read for informational purposes.

---

From: Michael Paquier <[email-masked]>
Date: Tue, 9 Feb 2021 15:47:42 +0900

> underneath USE_SSL, but thats about the only non-NSS change left in this

I would have imagined 0010 to be either a 0001 or a 0002 :)

 }
+#endif                         /* USE_SSL */
+
+#ifndef USE_OPENSSL

PQsslKeyPassHook_OpenSSL_type
PQgetSSLKeyPassHook_OpenSSL(void)
Indeed.  Let's fix that on HEAD, as an independent thing.

     errmsg("hostssl record cannot match because SSL is not supported by this build"),
-    errhint("Compile with --with-ssl=openssl to use SSL connections."),
+    errhint("Compile with --with-ssl to use SSL connections."),
Actually, we could change that directly on HEAD as you suggest.  This
code area is surrounded with USE_SSL so there is no need to mention
openssl at all.

Makes sense.

 /*
  * USE_SSL code should be compiled only when compiling with an SSL
- * implementation.  (Currently, only OpenSSL is supported, but we might add
- * more implementations in the future.)
+ * implementation.
  */
Fine by me as well, meaning that 0002 could just be committed as-is.
I am also looking at 0003 a bit.
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 9 Feb 2021 10:30:52 +0100

> On 9 Feb 2021, at 07:47, Michael Paquier <[email-masked]> wrote:
> 

Well, 0010 is a 2 in binary =) Jokes aside, I just didn't want to have a patch
referencing files added by later patches in the series.

> code area is surrounded with USE_SSL so there is no need to mention

We could, the only reason it says =openssl today is that it's the only possible
value but thats an implementation detail.  Changing it now before it's shipped
anywhere means the translation will be stable even if another library is
supported.

> 0002 could just be committed as-is.

It can be, it's not the most pressing patch scope reduction but everything
helps of course.

> I am also looking at 0003 a bit.

Thanks.  That patch is slightly more interesting in terms of reducing scope
here, but I also think it makes the test code a bit easier to digest when
certificate management is abstracted into the API rather than the job of the
testfile to perform.

---

From: Michael Paquier <[email-masked]>
Date: Wed, 10 Feb 2021 16:23:24 +0900

> It can be, it's not the most pressing patch scope reduction but everything

Okay.  I have spent some time on this one and finished it.

> certificate management is abstracted into the API rather than the job of the

That's my impression.  Still, I am wondering if there could be a
different approach.  I need to think more about that first..
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 10 Feb 2021 13:17:33 +0100

> On 10 Feb 2021, at 08:23, Michael Paquier <[email-masked]> wrote:
> 

Thanks, I'll post a rebased version on top of this soon.

> different approach.  I need to think more about that first..

Another option could be to roll SSL config into PostgresNode and expose SSL
connections to every subsystem tested with TAP. Something like:

	$node = get_new_node(..);
	$node->setup_ssl(..);
	$node->set_certificate(..);

That is a fair bit more work though, but perhaps we could then easier find
(and/or prevent) bugs like the one fixed in a45bc8a4f6495072bc48ad40a5aa03.

---

From: Jacob Champion <[email-masked]>
Date: Wed, 17 Feb 2021 01:02:15 +0000

On Mon, 2020-07-20 at 15:35 +0200, Daniel Gustafsson wrote:
> This version adds support for sslinfo on NSS for most the functions.

I've poked around to see what can be done about the
unimplemented ssl_client_dn_field/ssl_issuer_field functions. There's a
nasty soup of specs to wade around in, and it's not really clear to me
which ones take precedence since they're mostly centered on LDAP.

My take on it is that OpenSSL has done its own thing here, with almost-
based-on-a-spec-but-not-quite semantics. NSS has no equivalents to many
of the field names that OpenSSL supports (e.g. "commonName"). Likewise,
OpenSSL doesn't support case-insensitivity (e.g. "cn" in addition to
"CN") as many of the relevant RFCs require. They do both support
dotted-decimal representations, so we could theoretically get feature
parity there without a huge amount of work.

For the few attributes that NSS has a public API for retrieving:
- common name
- country
- locality
- state
- organization
- domain component
- org. unit
- DN qualifier
- uid
- email address(es?)
we could hardcode the list of OpenSSL-compatible names, and just
translate manually in sslinfo. Then leave the rest up to dotted-decimal 
OIDs.

Would that be desirable, or do we want this interface to be something
more generally compatible with (some as-of-yet unspecified) spec?

--Jacob

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 17 Feb 2021 22:19:35 +0100

> On 17 Feb 2021, at 02:02, Jacob Champion <[email-masked]> wrote:

> which ones take precedence since they're mostly centered on LDAP.

Thanks for digging!

> more generally compatible with (some as-of-yet unspecified) spec?

Regardless of approach taken I think this sounds like something that should be
tackled in a follow-up patch if the NSS patch is merged - and probably only as
a follow-up to a patch that adds test coverage to sslinfo.  From the sounds of
things me may not be able to guarantee stability across OpenSSL versions as it
is right now?

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 17 Feb 2021 22:35:33 +0100

> On 10 Feb 2021, at 13:17, Daniel Gustafsson <[email-masked]> wrote:
> 

Attached is a rebase on top of this and the recent cryptohash changes to pass
in buffer lengths to the _final function.  On top of that, I fixed up and
expanded the documentation, improved SCRAM handling (by using NSS digest
operations which are better suited) and reworded and expanded comments.  This
patch version is, I think, feature complete with the OpenSSL implementation.

---

From: Jacob Champion <[email-masked]>
Date: Wed, 17 Feb 2021 22:02:38 +0000

On Wed, 2021-02-17 at 22:19 +0100, Daniel Gustafsson wrote:
> a follow-up to a patch that adds test coverage to sslinfo.

Sounds good, and +1 to adding coverage at the same time.

> From the sounds of

Yeah. I was going to write that OpenSSL would be unlikely to change
these once they're added for the first time, but after checking GitHub
it looks like they have done so recently [1], as part of a patch
release no less.

--Jacob

[1] https://github.com/openssl/openssl/pull/10029

---

From: Jacob Champion <[email-masked]>
Date: Thu, 18 Feb 2021 20:33:18 +0000

> patch version is, I think, feature complete with the OpenSSL implementation.

fe-secure-nss.c is no longer compiling as of this patchset; looks
like pgtls_open_client() has a truncated statement.

--Jacob

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 22 Feb 2021 14:31:13 +0100

> On 18 Feb 2021, at 21:33, Jacob Champion <[email-masked]> wrote:
> 

Ouch, I had a local mismerge that snuck in as I moved the branch around for
submission here.  The attached fixes that as well as implements the sslcrldir
support that was committed recently.  The crldir parameter isn't applicable to
NSS per se since all CRL's are loaded into the NSS database, but it does need
to be supported for the tests.

The crldir commit also made similar changes to the test harness as I had done
to support the NSS database, which made these incompatible.  To fix that I've
implemented named parameters in switch_server_cert to make it less magic with
multiple optional parameters.

---

From: Jacob Champion <[email-masked]>
Date: Wed, 24 Feb 2021 00:11:55 +0000

On Mon, 2021-02-22 at 14:31 +0100, Daniel Gustafsson wrote:
> The attached fixes that as well as implements the sslcrldir

The named parameters are a big improvement!

Couple things I've noticed with this patch, back on the OpenSSL side.
In SSL::Backend::OpenSSL's set_server_conf() implementation:

> +   my $sslconf =
> +       "ssl_ca_file='$params->{cafile}.crt'\n"
> +     . "ssl_cert_file='$params->{certfile}.crt'\n"
> +     . "ssl_key_file='$params->{keyfile}.key'\n"
> +     . "ssl_crl_file='$params->{crlfile}'\n";
> +   $sslconf .= "ssl_crl_dir='$params->{crldir}'\n" if defined $params->{crldir};
>  }

this is missing a `return $sslconf` at the end.

In 001_ssltests.pl:

> -set_server_cert($node, 'server-cn-only', 'root+client_ca',
> -                  'server-password', 'echo wrongpassword');
> -command_fails(
> +# NSS we have two separate blocks for them
> +SKIP:
> +{
> +   switch_server_cert($node,
> +       certfile => 'server-cn-only',
> +       cafile => 'root+client_ca',
> +       keyfile => 'server-password',
> +       nssdatabase => 'server-cn-only.crt__server-password.key.db',
> +       passphrase_cmd => 'echo wrongpassword');
> +
> +   command_fails(

The removal of set_server_cert() in favor of switch_server_cert()
breaks these tests in OpenSSL, because the restart that
switch_server_cert performs will fail as designed. (The new comment
above switch_server_cert() suggests maybe you had a switch in mind to
skip the restart?)

> +       'restart fails with password-protected key file with wrong password');

but I'd argue that that NSS test and the one after it should probably
be removed. We already know restart succeeded; otherwise
switch_server_cert() would have failed. (The test descriptions also
have the old "restart fails" verbiage.)

--Jacob

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 24 Feb 2021 13:23:32 +0100

> On 24 Feb 2021, at 01:11, Jacob Champion <[email-masked]> wrote:
> 

Yeah, I was clearly undercaffeinated and forgot to re-run the tests on OpenSSL
after some hackery.  Fixed.

> above switch_server_cert() suggests maybe you had a switch in mind to

I initially had a restart => 'yes' parameter which turned too repetetive since
nearly all calls wants a restart.  When I switched it to an opt-out I missed to
update the tests.  Fixed.

> have the old "restart fails" verbiage.)

Agreed, removed.

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 3 Mar 2021 09:52:13 +0100

Attached is a rebase which attempts to fix the cfbot Appveyor failure, there
were missing HAVE_ defines for MSVC.

---

From: Stephen Frost <[email-masked]>
Date: Sun, 21 Mar 2021 19:49:51 -0400

Greetings,

> Subject: [PATCH v30 1/9] nss: Support libnss as TLS library in libpq
> 
> This commit contains the frontend and backend portion of TLS support
> in libpq to allow encrypted connections. The implementation is done

maybe add 'using NSS' to that first sentence. ;)

> +	/* TODO: should we rename pr_fd to ssl, to keep consistency? */

Having thought about this TODO item for a bit, I tend to think it's
better to keep them distinct.  They aren't the same and it might not be
clear what's going on if one was to somehow mix them (at least if pr_fd
continues to sometimes be a void*, but I wonder why that's being
done..?  more on that later..).

> +++ b/src/backend/libpq/be-secure-nss.c
[...]

> +static PRIOMethods pr_iomethods;

Happy to be told I'm missing something, but the above two variables seem
to only be used in init_iolayer.. is there a reason they're declared
here instead of just being declared in that function?

> +	 * make translations easier.

Should we pull these error messages out into another header so that
they're in one place to make sure they're kept consistent, if we really
want to put the effort in to keep them the same..?  I'm not 100% sure
that it's actually necessary to do so, but defining these in one place
would help maintain this if we want to.  Also alright with just keeping
the comment, not that big of a deal.

> +be_tls_open_server(Port *port)

pr_fd here is materially different from port->pr_fd, no?  As in, one is
the NSS raw TCP fd while the other is the SSL fd, right?  Maybe we
should use two different variable names to try and make sure they don't
get confused?  Might even set this to NULL after we are done with it
too..  Then again, I see later on that when we do the dance with the
'model' PRFileDesc that we just use the same variable- maybe we should
do that?  That is, just get rid of this 'pr_fd' and use port->pr_fd
always?

> +	 * https://bugzilla.redhat.com/show_bug.cgi?id=738456

The above seems to indicate that we will be requiring at least 3.12,
right?  Yet above we have code to work with NSPR versions before 2.1?
Maybe we should put a stake in the ground that says "we only support
back to version X of NSS", test with that and a few more recent versions
and the most recent, and then rip out anything that's needed for
versions which are older than that?  I have a pretty hard time imagining
that someone is going to want to build PG v14 w/ NSS 2.0 ...

> +			if (!pg_find_cipher(c, &ciphercode))
> +			{

Maybe I'm a bit confused, but doesn't pg_find_cipher return *true* when
a cipher is found, and therefore the '!' above is saying "if we don't
find a matching cipher, then run the code to set the cipher ...".  Also-
we don't seem to complain at all about a cipher being specified that we
don't find?  Guess I would think that we might want to throw a WARNING
in such a case, but I could possibly be convinced otherwise.  Kind of
wonder just what happens with the current code, I'm guessing ciphercode
is zero and therefore doesn't complain but also doesn't do what we want.
I wonder if there's a way to test this?

I do think we should probably throw an error if we end up with *no*
ciphers being set, which doesn't seem to be happening here..?

> +	 * Set up the custom IO layer.

Might be good to mention that the IO Layer is what sets up the
read/write callbacks to be used.

> +				(errmsg("unable to initialize")));

Maybe a comment and a better error message for this?

> +	PR_Close(model);

This might deserve one also, the whole 'model' construct is a bit
different. :)

> +	/* Register out shutdown callback */

*our

> +					pg_SSLerrmessage(PR_GetError()))));

It doesn't have to be much, but I, at least, do prefer to see
function-header comments. :)  Not that the OpenSSL code has them
consistently, so obviously not that big of a deal.  Goes for a number of
the functions being added.

> +			/* Found a CN, ecode and copy it into a newly allocated buffer */

*decode

> +	return PR_GetDefaultIOMethods()->close(fd);

Regarding these, I find myself wondering how they're different from the
defaults..?  I mean, the above just directly called
PR_GetDefaultIOMethods() to then call it's close() function- are the
fd->lower_methods->recv/send not the default methods?  I don't quite get
what the point is from having our own callbacks here if they just do
exactly what the defaults would do (or are there actually no defined
defaults and you have to provide these..?).

> +ssl_protocol_version_to_nss(int v, const char *guc_name)

guc_name isn't actually used in this function..?  Is there some reason
to keep it or is it leftover?

Also, I get that they do similar jobs and that one is in the frontend
and the other is in the backend, but I'm not a fan of having two
'ssl_protocol_version_to_nss()'s functions that take different argument
types but have exact same name and do functionally different things..

> @@ -4377,6 +4381,18 @@ static struct config_string ConfigureNamesString[] =

We don't #ifdef out the various GUCs even if SSL isn't compiled in, so
it doesn't seem quite right to be doing so here?  Generally speaking,
GUCs that we expect people to use (rather than debugging ones and such)
are typically always built, even if we don't build support for that
capability, so we can throw a better error message than just some ugly
syntax or parsing error if we come across one being set in a non-enabled
build.

> +++ b/src/common/cipher_nss.c
> @@ -0,0 +1,192 @@
> + * cipher_nss.c
> + *	  NSS functionality shared between frontend and backend for working
> + *	  with ciphers
> + *
> + * This should only bse used if code is compiled with NSS support.

*be

> @@ -200,6 +200,10 @@ typedef struct Port
>  	SSL		   *ssl;
>  	X509	   *peer;
>  #endif
> +
> +#ifdef USE_NSS
> +	void	   *pr_fd;
> +#endif
>  } Port;

Given this is under a #ifdef USE_NSS, does it need to be / should it
really be a void*?

> @@ -359,6 +359,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = {
>  		"Target-Session-Attrs", "", 15, /* sizeof("prefer-standby") = 15 */

I mean, maybe nitpicking here, but all the other SSL stuff is
'sslsomething' and the backend version of this is 'ssl_database', so
wouldn't it be more consistent to have this be 'ssldatabase'?

> + * This logic exist in NSS as well, but it's only available for when there is

*exists

> +	PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);

See same comment I made above- and also there's a comment earlier in
this file that we don't need to PR_Init() even ...

> +	{
> +		conn->nss_context = NSS_InitContext("", "", "", "", &params,
> +		if (!conn->nss_context)
> +		{

That error message seems a bit ... off?  Surely we aren't trying to
actually create a certificate database here?

> +		return PGRES_POLLING_FAILED;

Probably good to pull over at least some parts of the comments made in
the backend code about SetDomesticPolicy() actually enabling everything
(just like all the policies apparently do)...

> +			return PGRES_POLLING_FAILED;

Maybe have something a bit more here about "maybe you should specifify a
cert_database" or such?

> +		desired_range.max = ssl_max_ver;

In the backend code, we have an additional check to make sure they
didn't set the min version higher than the max.. should we have that
here too?  Either way, seems like we should be consistent.

> +	 * The model can now we closed as we've applied the settings of the model

*be

> +	 * onto the real socket. From hereon we should only use conn->pr_fd.

*here on

Similar comments to the backend code- should we just always use
conn->pr_fd?  Or should we rename pr_fd to something else?

> +	SSL_SetURL(conn->pr_fd, (conn->connhost[conn->whichhost]).host);

We should probably also set SNI, if available (NSS 3.12.6 it seems?),
since it looks like that's going to be added to the OpenSSL code.

> +	while (status != SECSuccess && PR_GetError() == PR_WOULD_BLOCK_ERROR);

We don't seem to have this loop in the backend code..  Is there some
reason that we don't?  Is it possible that we need to have a loop here
too?  I recall in the GSS encryption code there were definitely things
during setup that had to be looped back over on both sides to make sure
everything was finished ...

> +	if (conn->sslmode[0] == 'v')

Seems a bit grotty to do this (though I see that the OpenSSL code does
too ... at least there we have a comment though, maybe add one here?).
I would have thought we'd actually do strcmp()'s like above.

> +	if (strcmp(struct_name, "NSS") == 0)

Is there never a reason someone might want the pointer returned by
NSS_InitContext?  I don't know that there is but it might be something
to consider (we could even possibly have our own structure returned by
this function which includes both, maybe..?).  Not sure if there's a
sensible use-case for that or not just wanted to bring it up as it's
something I asked myself while reading through this patch.

> +			case SSL_LIBRARY_VERSION_TLS_1_0:

Not sure that it really matters, but this seems like it might be useful
to have as its own function...  Maybe even a data structure that both
functions use just in oppostie directions.  Really minor tho. :)

> index c601071838..7f10da3010 100644
> @@ -448,6 +448,27 @@ PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
>  }
>  #endif							/* USE_OPENSSL */
>  
> +#ifndef USE_NSS
> +

Isn't this '!USE_NSS'?

> index 0c9e95f1a7..f15af39222 100644
> @@ -383,6 +383,7 @@ struct pg_conn
>  	char	   *sslcrldir;		/* certificate revocation list directory name */
> @@ -507,6 +508,28 @@ struct pg_conn
> + * The NSS/NSPR specific types aren't used to avoid pulling in the required
> + * headers here, as they are causing conflicts with PG definitions.
> + */

I'm a bit confused- what are the conflicts being caused here..?
Certainly under USE_OPENSSL we use the actual OpenSSL types..

> Subject: [PATCH v30 2/9] Refactor SSL testharness for multiple library
> 
> The SSL testharness was fully tied to OpenSSL in the way the server was
> set up and reconfigured. This refactors the SSLServer module into a SSL
> library agnostic SSL/Server module which in turn use SSL/Backend/<lib>
> modules for the implementation details.
> 
> No changes are done to the actual tests, this only change how setup and
> teardown is performed.

Presumably this could be committed ahead of the main NSS support?

> Subject: [PATCH v30 4/9] nss: pg_strong_random support

I don't know that it's an issue, but do we actually need to init the NSS
context and shut it down every time..?

>   * Without OpenSSL or Win32 support, just read /dev/urandom ourselves.

*or NSS

> Subject: [PATCH v30 5/9] nss: Documentation

We don't have this already..?  Surely we should..

> index 967de73596..1608e9a7c7 100644
> @@ -1272,6 +1272,23 @@ include_dir 'conf.d'
>        </listitem>
>       </varlistentry>
>  

*SSL/TLS maybe?

> @@ -1288,7 +1305,9 @@ include_dir 'conf.d'

Shouldn't we say something here wrt NSS?

> @@ -1490,8 +1509,11 @@ include_dir 'conf.d'
>         <para>

Maybe we should point out here that this requires the database to not
require a password..?  So if they have one, they need to set this, or
maybe we should provide a default one..

> +        <function>PQgetSSLKeyPassHook_nss</function> has no effect unless the
> +        server was compiled with <productname>nss</productname> support.
> +      </para>

We should try to be consistent- above should be NSS, not nss.

> +         <listitem>
> +          <para>
> +           <productname>NSS</productname>: specifying the parameter is required
> +           in case any password protected items are referenced in the
> +           <productname>NSS</productname> database, or if the database itself
> +           is password protected.  If multiple different objects are password
> +           protected, the same password is used for all.
> +          </para>
> +         </listitem>
> +        </itemizedlist>

Is this a statement about NSS databases (which I don't think it is) or
about the fact that we'll just use the password provided for all
attempts to decrypt something we need in the database?  Assuming the
latter, seems like we could reword this to be a bit more clear.

Maybe: 

All attempts to decrypt objects which are password protected in the
database will use this password.

?

> @@ -2620,9 +2791,14 @@ void *PQsslStruct(const PGconn *conn, const char *struct_name);

... SSL PRFileDesc associated with the connection, no?

> @@ -2552,6 +2583,89 @@ openssl x509 -req -in server.csr -text -days 365 \
>     </para>
>    </sect2>
>  

*requires

> Subject: [PATCH v30 6/9] nss: Support NSS in pgcrypto

Maybe this should mention that it's with the built-in implementation as
blowfish isn't available from NSS?

>         <entry>DES/3DES/CAST5</entry>

Surely CAST5 from the above should be removed, since it's given its own
entry now?

>        is automatically picked up.

*or?  Maybe something more specific though- "Any digest algorithm
included with the library that PostgreSQL is compiled with is
automatically picked up." ?

> Subject: [PATCH v30 7/9] nss: Support NSS in sslinfo
> 
> Since sslinfo to a large extent use the be_tls_* API this mostly

*uses

> Subject: [PATCH v30 8/9] nss: Support NSS in cryptohash

We take some pains to use NSS_InitContext elsewhere..  Are we sure that
we should be using NSS_NoDB_Init here..?

Just a, well, not so quick read-through.  Generally it's looking pretty
good to me.  Will see about playing with it this week.

Thanks!

Stephen

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 23 Mar 2021 00:38:50 +0100

> On 22 Mar 2021, at 00:49, Stephen Frost <[email-masked]> wrote:
> 
> Greetings,

Thanks for the review!  Below is a partial response, I haven't had time to
address all your review comments yet but I wanted to submit a rebased patchset
directly since the current version doesn't work after recent changes in the
tree. I will address the remaining comments tomorrow or the day after.

This rebase also includes a fix for pgtls_init which was sent offlist by Jacob.
The changes in pgtls_init can potentially be used to initialize the crypto
context for NSS to clean up this patch, Jacob is currently looking at that.

Fixed.

> better to keep them distinct.

I agree, which is why the TODO comment was there in the first place.  I've
removed the comment now.

> They aren't the same and it might not be

To paraphrase from a later in this email, there are collisions between nspr and
postgres on things like BITS_PER_BYTE, and there were also collisions on basic
types until I learned about NO_NSPR_10_SUPPORT.  By moving the juggling of this
into common/nss.h we can use proper types without introducing that pollution
everywhere. I will address these places.

> here instead of just being declared in that function?

They must be there since NSPR doesn't copy these but reference them.

> the comment, not that big of a deal.

It might make sense to pull them into common/nss.h, but seeing the error
message right there when reading the code does IMO make it clearer so it's a
doubleedged sword.  Not sure what is the best option, but I'm not married to
the current solution so if there is consensus to pull them out somewhere I'm
happy to do so.

> do that?  That is, just get rid of this 'pr_fd' and use port->pr_fd

Hmm, I think you're right. I will try that for the next patchset version.

> right?  Yet above we have code to work with NSPR versions before 2.1?

Well, not really.  The comment tries to explain the rationale for the
parameters passed.  Clearly the comment could be improved to make that point
clearer.

> versions which are older than that?  

Yes, right now there is very little in the patch which caters for old versions,
the PR_Init call might be one of the few offenders.  There has been discussion
upthread about settling for a required version, combining the insights learned
there with a survey of which versions are commonly available packaged.

Once we settle on a version we can confirm if PR_Init is/isn't needed and
remove all traces of it if not.

> I have a pretty hard time imagining that someone is going to want to build PG
> v14 w/ NSS 2.0 ...

Let alone compiling 2.0 at all on a recent system..

> find a matching cipher, then run the code to set the cipher ...".

Hmm, yes thats broken. Fixed.

> Also- we don't seem to complain at all about a cipher being specified that we
> don't find?  Guess I would think that we might want to throw a WARNING in such
> a case, but I could possibly be convinced otherwise.

No, I think you're right, we should throw WARNING there or possibly even a
higher elevel. Should that be a COMMERROR even?

> Kind of wonder just what happens with the current code, I'm guessing ciphercode
> is zero and therefore doesn't complain but also doesn't do what we want.  I
> wonder if there's a way to test this?

We could extend the test suite to set ciphers in postgresql.conf, I'll give it
a go.

> ciphers being set, which doesn't seem to be happening here..?

Yeah, that should be a COMMERROR. Fixed.

> read/write callbacks to be used.

Good point, will do in the next version of the patchset.

> Maybe a comment and a better error message for this?

Will do.

> This might deserve one also, the whole 'model' construct is a bit

Agreed. will do.

Fixed.

> the functions being added.

No disagreement from me, I've added comments on a few more functions and will
continue to go over the patchset to add them everywhere.  Some of these
comments are pretty uninteresting and could do with some wordsmithing.

Fixed.

> defaults and you have to provide these..?).

It's really just to cope with debug builds of NSPR which assert that fd->secret
is null before closing.

> to keep it or is it leftover?

It's a leftover from when the function was doing error reporting, fixed.

> types but have exact same name and do functionally different things..

Good point, I'll change that.

Of course, fixed.

Fixed.

> Given this is under a #ifdef USE_NSS, does it need to be / should it

It's to avoid the same BITS_PER_BYTE collision discussed elsewhere in this
email.

> wouldn't it be more consistent to have this be 'ssldatabase'?

Thats a good point, I was clearly Stockholm syndromed since I hadn't reflected
on that but it's clearly wrong.  Will fix.

Fixed.

> this file that we don't need to PR_Init() even ...

Right, once we can confirm that the minimum required versions are past the
PR_Init dependency then we should remove all of these calls.  If we can't
remove the calls, the comments should be updated to reflect why they are there.

> actually create a certificate database here?

Not really no, it does set up a transient database structure for the duration
of the connection AFAIK but thats clearly not the level of detail we should be
giving users.  I've reworded to indicate that NSS init failed, and ideally the
pg_SSLerrmessage call will provide appropriate detail.

> (just like all the policies apparently do)...

Good point, will do.

> Maybe have something a bit more here about "maybe you should specifify a

Good point, will expand with more detail.

> here too?  Either way, seems like we should be consistent.

We already test that in src/interfaces/libpq/fe-connect.c.

Fixed.

Fixed.

> conn->pr_fd?  Or should we rename pr_fd to something else?

Renaming is probably not a bad idea, will fix.

> since it looks like that's going to be added to the OpenSSL code.

Good point, will do.

> everything was finished ...

Off the cuff I can't remember, will look into it.

> I would have thought we'd actually do strcmp()'s like above.

That's admittedly copied from the OpenSSL code, and I agree that it's a bit too
clever.  Replaced with plain strcmp's to improve readability in both places it
occurred.

> something I asked myself while reading through this patch.

Not sure I understand what you're asking for here, did you mean "is there ever
a reason"?

> functions use just in oppostie directions.  Really minor tho. :)

I suppose that wouldn't be a bad thing, will fix.
	
>> +PQdefaultSSLKeyPassHook_nss(PK11SlotInfo * slot, PRBool retry, void *arg)

Technically it is, but using just /* USE_NSS */ is consistent with the rest of
blocks in the file.

> Certainly under USE_OPENSSL we use the actual OpenSSL types..

It's referring to collisions with for example BITS_PER_BYTE which is defined
both by postgres and nspr.  Since writing this I've introduced src/common/nss.h
to handle it in a single place, so we can indeed use the proper types without
polluting the file.  Fixed.

> Presumably this could be committed ahead of the main NSS support?

Correct, I think this has merits even if NSS support is ultimately rejected.

> context and shut it down every time..?

We need to have a context, and we should be able to set it like how the WIN32
code sets hProvider.  I don't remember if there was a reason against that, will
revisit.

Fixed.

> We don't have this already..?  Surely we should..

We really should, especially since we've had <acronym>TLS</acronym> in
config.sgml since 2014 (c6763156589).  That's another small piece that could be
committed on it's own to cut down the size of this patchset (even if only by a
tiny amount).

Fixed.

> Shouldn't we say something here wrt NSS?

We should, but I'm not entirely what just yet. Need to revisit that.

> maybe we should provide a default one..

I've added a sentence on not using a password for the cert database.  I'm not
sure if providing a default one is a good idea but it's no less insecure than
having no password really..

Fixed.

> attempts to decrypt something we need in the database?

Correct.

> Assuming the

Agreed, fixed.

> ... SSL PRFileDesc associated with the connection, no?

I was trying to be specific that it's an NSS-defined structure and not a
PostgreSQL one which is returned. Fixed.

Fixed.

> blowfish isn't available from NSS?

Fixed by adding a Note item.

> Surely CAST5 from the above should be removed, since it's given its own

Indeed, fixed.

> automatically picked up." ?

Good point, thats better. Fixed.

Fixed.

> we should be using NSS_NoDB_Init here..?

No, we should probably be using NSS_InitContext. Will fix.

> good to me.  Will see about playing with it this week.

Thanks again for reviewing, another version which addresses the remaining
issues will be posted soon but I wanted to get this out to give further reviews
something that properly works.

---

From: Stephen Frost <[email-masked]>
Date: Tue, 23 Mar 2021 15:04:27 -0400

Greetings,

Great, thanks!

> context for NSS to clean up this patch, Jacob is currently looking at that.

Ah, cool, sounds good.

> everywhere. I will address these places.

Ah, ok, and great, that sounds good.

> They must be there since NSPR doesn't copy these but reference them.

Ah, ok, interesting.

> the current solution so if there is consensus to pull them out somewhere I'm

My thought was to put them into some common/ssl.h or something along
those lines but I don't see it as a big deal either way really.  You
make a good point that having the error message there when reading the
code is nice.

> remove all traces of it if not.

I don't really see this as all that hard to do- I'd suggest we look at
what systems someone might reasonably deploy v14 on.  To that end, I'd
say "only systems which are presently supported", so: RHEL7+, Debian 9+,
Ubuntu 16.04+.  Looking at those, I see:

Ubuntu 16.04: 3.28.4
RHEL6: v3.28.4
Debian: 3.26.2

> Let alone compiling 2.0 at all on a recent system..

Indeed, and given the above, it seems entirely reasonable to make the
requirement be NSS v3+, no?  I wouldn't be against making that even
tighter if we thought it made sense to do so.

> higher elevel. Should that be a COMMERROR even?

I suppose the thought I was having was that we might want to allow some
string that covered all the OpenSSL and NSS ciphers that someone feels
comfortable with and we'd just ignore the ones that don't make sense for
the particular library we're currently built with.  Making it a
COMMERROR seems like overkill and I'm not entirely sure we actually want
any warning since we might then be constantly bleating about it.

> We could extend the test suite to set ciphers in postgresql.conf, I'll give it

That'd be great, thanks!

> Yeah, that should be a COMMERROR. Fixed.

I do think it makes sense to throw a COMMERROR here since the connection
is going to end up failing anyway.

> It's really just to cope with debug builds of NSPR which assert that fd->secret

And we have to override the recv/send functions for this too..?  Sorry,
my comment wasn't just about the close() method but about the others
too.

> Not sure I understand what you're asking for here, did you mean "is there ever

Eh, poor wording on my part.  You're right, the question, reworded
again, was "Would someone want to get the context returned by
NSS_InitContext?".  If we think there's a reason that someone might want
that context then perhaps we should allow getting it, in addition to the
pr_fd.  If there's really no reason to ever want the context from
NSS_InitContext then what you have here where we're returning pr_fd is
probably fine.

> Technically it is, but using just /* USE_NSS */ is consistent with the rest of

Hrmpf.  I guess it seems a bit confusing to me to have to go find the
opening #ifndef to realize that it's actally !USE_NSS..  In other words,
I would think we'd actually want to fix all of these, heh.  I only
actually see one case on a quick grep where it's wrong for USE_OPENSSL
and so that doesn't seem like it's really a precedent and is more of a
bug.  We certainly say 'not OPENSSL' in one place today too and also
have a number of places where we have: #endif ... /* ! WHATEVER */.

Great, thanks!

> Correct, I think this has merits even if NSS support is ultimately rejected.

Ok- could you break it out on to its own thread and I'll see about
committing it soonish, to get it out of the way?

> committed on it's own to cut down the size of this patchset (even if only by a

Ditto on this. :)

> We should, but I'm not entirely what just yet. Need to revisit that.

Not sure if we really want to do this but at least with ssllabs.com,
postgresql.org gets an 'A' rating with this set:

ECDHE-ECDSA-CHACHA20-POLY1305
ECDHE-RSA-CHACHA20-POLY1305
ECDHE-ECDSA-AES128-GCM-SHA256
ECDHE-RSA-AES128-GCM-SHA256
ECDHE-ECDSA-AES256-GCM-SHA384
ECDHE-RSA-AES256-GCM-SHA384
DHE-RSA-AES128-GCM-SHA256
DHE-RSA-AES256-GCM-SHA384
ECDHE-ECDSA-AES128-SHA256
ECDHE-RSA-AES128-SHA256
ECDHE-ECDSA-AES128-SHA
ECDHE-RSA-AES256-SHA384
ECDHE-RSA-AES128-SHA
ECDHE-ECDSA-AES256-SHA384
ECDHE-ECDSA-AES256-SHA
ECDHE-RSA-AES256-SHA
DHE-RSA-AES128-SHA256
DHE-RSA-AES128-SHA
DHE-RSA-AES256-SHA256
DHE-RSA-AES256-SHA
ECDHE-ECDSA-DES-CBC3-SHA
ECDHE-RSA-DES-CBC3-SHA
EDH-RSA-DES-CBC3-SHA
AES128-GCM-SHA256
AES256-GCM-SHA384
AES128-SHA256
AES256-SHA256
AES128-SHA
AES256-SHA
DES-CBC3-SHA
!DSS

Which also seems kinda close to what the default when built with OpenSSL
ends up being?  Thought the ssllabs report does list which ones it
thinks are weak and so we might consider excluding those by default too:

https://www.ssllabs.com/ssltest/analyze.html?d=postgresql.org&s=2a02%3a16a8%3adc51%3a0%3a0%3a0%3a0%3a50

> having no password really..

I was meaning a default callback to prompt, not sure if that was clear.

> something that properly works.

Fantastic, thanks again!

Stephen

---

From: Jacob Champion <[email-masked]>
Date: Wed, 24 Mar 2021 00:05:35 +0000

> context for NSS to clean up this patch, Jacob is currently looking at that.

I'm having a hell of a time trying to get the context stuff working.
Findings so far (I have patches in progress for many of these, but it's
all blowing up because of the last problem):

NSS_INIT_NOROOTINIT is hardcoded for NSS_InitContext(), so we probably
don't need to pass it explicitly. NSS_INIT_PK11RELOAD is apparently
meant to hack around libraries that do their own PKCS loading; do we
need it?

NSS_ShutdownContext() can (and does) fail if we've leaked handles to
objects, so we need to check its return value. Once this happens,
future NSS_InitContext() calls behave poorly. Currently we leak the
pr_fd as well as a handful of server_cert handles.

NSS_NoDB_Init() is going to pin NSS in memory. For the backend this is
probably okay, but for libpq clients that's probably not what we want.

The first database loaded by NSS_InitContext() becomes the "default"
database. This is what I'm currently hung up on. I can't figure out how
to get NSS to use the database that was loaded for the current
connection, so in my local patches for the issues above, client
certificates fail to load. I can work around it temporarily for the
tests, but this will be a problem if any libpq clients load up multiple
independent databases for use with separate connections. Anyone know if
this is a supported use case for NSS?

--Jacob

---

From: Michael Paquier <[email-masked]>
Date: Wed, 24 Mar 2021 09:28:10 +0900

> this is a supported use case for NSS?

Are you referring to the case of threading here?  This should be a
supported case, as threads created by an application through libpq
could perfectly use completely different connection strings.
--
Michael

---

From: Michael Paquier <[email-masked]>
Date: Wed, 24 Mar 2021 12:54:32 +0900

> something that properly works.

I have been looking at the infrastructure of the tests, patches 0002
(some refactoring) and 0003 (more refactoring with tests for NSS), and
I am a bit confused by its state.

First, I think that the split is not completely clear.  For example,
patch 0003 has changes for OpenSSL.pm and Server.pm, but wouldn't it
be better to have all the refactoring infrastructure only in 0002,
with 0003 introducing only the NSS pieces for its internal data and
NSS.pm?

+       keyfile => 'server-password',
+       nssdatabase => 'server-cn-only.crt__server-password.key.db',
+       passphrase_cmd => 'echo secret1',
001_ssltests.pl and 002_scram.pl have NSS-related parameters, which
does not look like a clean separation to me as there are OpenSSL tests
that use some NSS parts, and the main scripts should remain neutral in
terms setting contents, including only variables and callbacks that
should be filled specifically for each SSL implementation, no?  Aren't
we missing a second piece here with a set of callbacks for the
per-library test paths then?

+   if (defined($openssl))
+   {
+       copy_files("ssl/server-*.crt", $pgdata);
+       copy_files("ssl/server-*.key", $pgdata);
+       chmod(0600, glob "$pgdata/server-*.key") or die $!;
+       copy_files("ssl/root+client_ca.crt", $pgdata);
+       copy_files("ssl/root_ca.crt",        $pgdata);
+       copy_files("ssl/root+client.crl",    $pgdata);
+       mkdir("$pgdata/root+client-crldir");
+       copy_files("ssl/root+client-crldir/*",
"$pgdata/root+client-crldir/");
+   }
+   elsif (defined($nss))
+   {
+       RecursiveCopy::copypath("ssl/nss", $pgdata . "/nss") if -e
"ssl/nss";
+   }
This had better be in its own callback, for example.
--
Michael

---

From: Jacob Champion <[email-masked]>
Date: Wed, 24 Mar 2021 15:54:52 +0000

On Wed, 2021-03-24 at 09:28 +0900, Michael Paquier wrote:
> > I can work around it temporarily for the
Right, but to clarify -- I was asking if *NSS* supports loading and
using separate certificate databases as part of its API. It seems like
the internals make it possible, but I don't see the public interfaces
to actually use those internals.

--Jacob

---

From: Stephen Frost <[email-masked]>
Date: Wed, 24 Mar 2021 13:00:36 -0400

Greetings Jacob,

> to actually use those internals.

Yes, this is done using SECMOD_OpenUserDB, see:

https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/PKCS11_Functions#SECMOD_OpenUserDB

also there's info here:

https://groups.google.com/g/mozilla.dev.tech.crypto/c/Xz6Emfcue0E

We should document that, as mentioned in the link above, the NSS find
functions will find certs in all the opened databases.  As this would
all be under one application which is linked against libpq and passing
in different values for ssl_database for different connections, this
doesn't seem like it's really that much of an issue.

Thanks!

Stephen

---

From: Jacob Champion <[email-masked]>
Date: Wed, 24 Mar 2021 17:41:01 +0000

> https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/PKCS11_Functions#SECMOD_OpenUserDB

Ah, I had assumed that the DB-specific InitContext was using this
behind the scenes; apparently not. I will give that a try, thanks!

> doesn't seem like it's really that much of an issue.

I could see this being a problem if two client certificate nicknames
collide across multiple in-use databases, maybe?

--Jacob

---

From: Stephen Frost <[email-masked]>
Date: Wed, 24 Mar 2021 14:10:16 -0400

Greetings,

> collide across multiple in-use databases, maybe?

Right, in such a case either cert might get returned and it's possible
that the "wrong" one is returned and therefore the connection would end
up failing, assuming that they aren't actually the same and just happen
to be in both.

Seems like we could use SECMOD_OpenUserDB() and then pass the result
from that into PK11_ListCertsInSlot() and scan through the certs in just
the specified database to find the one we're looking for if we really
feel compelled to try and address this risk.  I've reached out to the
NSS folks to see if they have any thoughts about the best way to address
this.

Thanks,

Stephen

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 25 Mar 2021 00:00:30 +0100

> On 24 Mar 2021, at 04:54, Michael Paquier <[email-masked]> wrote:
> 

Yes.  Juggling a patchset of this size is errorprone.  This is why I opened the
separate thread for this where the patch can be held apart cleaner, so let's
take this discussion over there.  I will post an updated patch there shortly.

> per-library test paths then?

Well, then again, keyfile is an OpenSSL specific parameter, it just happens to
be named quite neutrally.  I'm not sure how to best express the certificate and
key requirements of a test since the testcase is the source of truth in terms
of what it requires.  If we introduce a standard set of cert/keys which all
backends are required to supply, we could refer to those.  Tests that need
something more specific can then go into 00X_<library>.pl.  There is a balance
to strike though, there is a single backend now with at most one on the horizon
which is yet to be decided upon, making it too generic may end up making test
writing overcomplicated. Do you have any concretee ideas?

> This had better be in its own callback, for example.

Yes, this one is a clearer case, fixed in the v2 patch which will be posted on
the separate thread.

---

From: Jacob Champion <[email-masked]>
Date: Wed, 24 Mar 2021 23:56:24 +0000

> NSS folks to see if they have any thoughts about the best way to address

Some additional findings (NSS 3.63), please correct me if I've made any mistakes:

The very first NSSInitContext created is special. If it contains a database, that database will be considered part of the "internal" slot and its certificates can be referenced directly by nickname. If it doesn't have a database, the internal slot has no certificates, and it will continue to have zero certificates until NSS is completely shut down and reinitialized with a new "first" context.

Databases that are opened *after* the first one are given their own separate slots. Any certificates that are part of those databases seemingly can't be referenced directly by nickname. They have to be prefixed by their token name -- a name which you don't have if you used NSS_InitContext() to create the database. You have to use SECMOD_OpenUserDB() instead. This explains some strange failures I was seeing in local testing, where the order of InitContext determined whether our client certificate selection succeeded or failed.

If you SECMOD_OpenUserDB() a database that is identical to the first (internal) database, NSS deduplicates for you and just returns the internal slot. Which seems like it's helpful, except you're not allowed to close that database, and you have to know not to close it by checking to see whether that slot is the "internal key slot". It appears to remain open until NSS is shut down entirely.
But if you open a database that is *not* the magic internal database,
and then open a duplicate of that one, NSS creates yet another new slot
for the duplicate. So SECMOD_OpenUserDB() may or may not be a resource
hog, depending on the global state of the process at the time libpq
opens its first connection. We won't be able to control what the parent
application will do before loading us up.

It also doesn't look like any of the SECMOD_* machinery that we're
looking at is thread-safe, but I'd really like to be wrong...

--Jacob

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 26 Mar 2021 00:22:33 +0100

> On 23 Mar 2021, at 20:04, Stephen Frost <[email-masked]> wrote:
> 
> Greetings,
> 

> make a good point that having the error message there when reading the

Thinking more on this, I think my vote will be to keep them duplicated in the
code for readability.  Unless there are strong feelings against I think we at
least should start there.

> Ubuntu 16.04+.

Sounds reasonable.

> Looking at those, I see:

I assume these have matching NSPR versions placing the Debian 9 NSPR package as
the lowest required version for that? 

> tighter if we thought it made sense to do so.

I think anything but doing that would be incredibly unreasonable.

> any warning since we might then be constantly bleating about it.

Right, with a string like that we'd induce WARNING fatigue quickly.  Catching
the case of *no* ciphers enabled with a COMMERROR is going some way towards
being helpful to the user in debugging the failed connection here.

> my comment wasn't just about the close() method but about the others

Ah, no we can ditch the .send and .recv functions and stick with the default
built-ins, I just confirmed this and removed them.  I think they are leftovers
from when I injected debug code there during development, they were as you say
copies of the default.

> NSS_InitContext then what you have here where we're returning pr_fd is

I can't think of any reason, maybe Jacob who has been knee-deep in NSS contexts
have insights which tell a different story?

> have a number of places where we have: #endif ... /* ! WHATEVER */.

No disagreement from me.  To cut down the size of this patchset however I
propose that we tackle this separately and leave this as is in this thread
since it's in line with the rest of the file (for now).

> committing it soonish, to get it out of the way?

It was already on it's own thread, as we discussed offlist.  I have since
rebased and expanded that patch over in that thread which has gotten review
that needs to be addressed.  As such, I will not update that patch in the
series in this thread but keep the changes on that thread, and then pull them
back into here when ready.

>> committed on it's own to cut down the size of this patchset (even if only by a

Done in https://postgr.es/m/[email-masked]

> https://www.ssllabs.com/ssltest/analyze.html?d=postgresql.org&s=2a02%3a16a8%3adc51%3a0%3a0%3a0%3a0%3a50

Agreed, maintaining parity (or thereabouts) with OpenSSL defaults taking
industry best practices into account is probably what we should aim for.

> I was meaning a default callback to prompt, not sure if that was clear.

Ah, no that's not what I thought you meant.  Do you have any thoughts on what
that callback would look like? Take a password on a TTY input?

Fixed.

Fixed.

Fixed.

Fixed.

Fixed.

> Renaming is probably not a bad idea, will fix.

Both fixed.

Additionally, a few other off-list reported issues are also fixed in this
version (such as fixing the silly markup doc error and testplan off-by-one etc).

---

From: Jacob Champion <[email-masked]>
Date: Thu, 25 Mar 2021 23:59:16 +0000

> have insights which tell a different story?

The only thing you can do with a context pointer is shut it down, and I
don't think that's something that should be exposed.

--Jacob

---

From: Stephen Frost <[email-masked]>
Date: Fri, 26 Mar 2021 15:33:38 -0400

Greetings,

> Databases that are opened *after* the first one are given their own separate slots. Any certificates that are part of those databases seemingly can't be referenced directly by nickname. They have t…

This is more-or-less what we would want though, right..?  If a user asks
for a connection with ssl_database=blah and sslcert=whatever, we'd want
to open database 'blah' and search (just) that database for cert
'whatever'.  We could possibly offer other options in the future but
certainly this would work and be the most straight-forward and expected
behavior.

> If you SECMOD_OpenUserDB() a database that is identical to the first (internal) database, NSS deduplicates for you and just returns the internal slot. Which seems like it's helpful, except you're n…

Seems like we shouldn't do that and should just use SECMOD_OpenUserDB()
for opening databases.

> application will do before loading us up.

I would think we'd want to avoid re-opening the same database multiple
times, to avoid the duplicate slots and such.  If the application code
does it themselves, well, there's not much we can do about that, but we
could at least avoid doing so in *our* code.  I wouldn't expect us to be
opening hundreds of databases either and so keeping a simple list around
of what we've opened and scanning it seems like it'd be workable.  Of
course, this could likely be improved in the future but I would think
that'd be good for an initial implementation.

We could also just generally caution users in our documentation against
using multiple databases.  The NSS folks discourage doing so and it
doesn't strike me as being a terribly useful thing to do anyway, at
least from within one invocation of an application.  Still, if we could
make it work reasonably well, then I'd say we should go ahead and do so.

> looking at is thread-safe, but I'd really like to be wrong...

That's unfortuante but solvable by using our own locks, similar
to what's done in fe-secure-openssl.c.

Thanks!

Stephen

---

From: Jacob Champion <[email-masked]>
Date: Fri, 26 Mar 2021 22:03:22 +0000

On Fri, 2021-03-26 at 15:33 -0400, Stephen Frost wrote:
> > Databases that are opened *after* the first one are given their own
> > separate slots. [...]
> 

Yes, but see below.

> > If you SECMOD_OpenUserDB() a database that is identical to the first
> > (internal) database, NSS deduplicates for you and just returns the
> > internal slot. Which seems like it's helpful, except you're not
> > allowed to close that database, and you have to know not to close it
> > by checking to see whether that slot is the "internal key slot". It
> > appears to remain open until NSS is shut down entirely.
> 

We don't have control over whether or not this happens. If the
application embedding libpq has already loaded the database into the
internal slot via its own NSS initialization, then when we call
SECMOD_OpenUserDB() for that same database, the internal slot will be
returned and we have to handle it accordingly.

It's not a huge amount of work, but it is magic knowledge that has to
be maintained, especially in the absence of specialized clientside
tests.

> to what's done in fe-secure-openssl.c.

Yeah. I was hoping to avoid implementing our own locks and refcounts,
but it seems like it's going to be required.

--Jacob

---

From: Stephen Frost <[email-masked]>
Date: Fri, 26 Mar 2021 18:05:40 -0400

Greetings,

> be maintained, especially in the absence of specialized clientside

Ah..  yeah, fair enough.  We could document that we discourage
applications from doing so, but I agree that we'll need to deal with it
since it could happen.

> but it seems like it's going to be required.

Yeah, afraid so.

Thanks!

Stephen

---

From: Jacob Champion <[email-masked]>
Date: Wed, 31 Mar 2021 22:15:15 +0000

> > but it seems like it's going to be required.

I think it gets worse, after having debugged some confusing crashes.

> remove all traces of it if not.

What the NSPR documentation omits is that implicit initialization is
not threadsafe. So NSS_InitContext() is technically "threadsafe"
because it's built on PR_CallOnce(), but if you haven't called
PR_Init() yet, multiple simultaneous PR_CallOnce() calls can crash into
each other.

So, fine. We just add our own locks around NSS_InitContext() (or around
a single call to PR_Init()). Well, the first thread to win and
successfully initialize NSPR gets marked as the "primordial" thread
using thread-local state. And it gets a pthread destructor that does...
something. So lazy initialization seems a bit dangerous regardless of
whether or not we add locks, but I can't really prove whether it's
dangerous or not in practice.

I do know that only the primordial thread is allowed to call
PR_Cleanup(), and of course we wouldn't be able to control which thread
does what for libpq clients. I don't know what other assumptions are
made about the primordial thread, or if there are any platform-specific 
behaviors with older versions of NSPR that we'd need to worry about. It
used to be that the primordial thread was not allowed to exit before
any other threads, but that restriction was lifted at some point [1].

I think we're going to need some analogue to PQinitOpenSSL() to help
client applications cut through the mess, but I'm not sure what it
should look like, or how we would maintain any sort of API
compatibility between the two flavors. And does libpq already have some
notion of a "main thread" that I'm missing?

--Jacob

[1] https://bugzilla.mozilla.org/show_bug.cgi?id=294955

---

From: Michael Paquier <[email-masked]>
Date: Thu, 1 Apr 2021 13:10:23 +0900

> notion of a "main thread" that I'm missing?

Nope as far as I recall.  With OpenSSL, the initialization of the SSL
mutex lock and the crypto callback initialization is done by the first
thread in.
--
Michael

---

From: Stephen Frost <[email-masked]>
Date: Thu, 1 Apr 2021 10:15:15 -0400

Greetings,

> mutex lock and the crypto callback initialization is done by the first

Yeah, we haven't got any such concept in libpq.  I do think that some of
this can simply be documented as "if you do this, then you need to make
sure to do this".

Thanks,

Stephen

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 2 Apr 2021 01:17:20 +0200

> On 23 Mar 2021, at 00:38, Daniel Gustafsson <[email-masked]> wrote:

Attached is a rebase on top of the recent SSL related commits with a few more
fixes from previous reviews.

> on that but it's clearly wrong.  Will fix.

Fixed

Fixed.

>> since it looks like that's going to be added to the OpenSSL code.

Actually, it turns out that NSS 3.12.6 introduced the serverside SNI handling
by providing callbacks to respond to hostname verification.  There was no
mention of clientside SNI in the NSS documentation that I could find, reading
the code however SSL_SetURL does actually set the SNI extension in the
ClientHello.  So, clientsidee SNI (which is what is proposed for the OpenSSL
backend) is already in.

> Off the cuff I can't remember, will look into it.

Thinking more about this, I don't think we should have the loop at all in the
frontend either.  The reason it was added was to cover cases where we're
confused about blocking but I can't actually see the case I was worried about
in the code so I think it's useless.  Removed.

> I suppose that wouldn't be a bad thing, will fix.

Moved this into a shared function as it's used by both frontend and backend.
It's moved mostly verbatim as it seemed simple enough to not warrant much
complication.

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 5 Apr 2021 00:13:43 +0200

Another rebase to cope with recent changes (hmac, ssl tests etc) that
conflicted and broke this patchset.

---

From: Michael Paquier <[email-masked]>
Date: Mon, 5 Apr 2021 11:12:22 +0900

> conflicted and broke this patchset.

Please find an updated set, v35, attached, and my apologies for
breaking again your patch set.  While testing this patch set and
adjusting the SSL tests with HEAD, I have noticed what looks like a
bug with the DN mapping that NSS does not run.  The connection strings
are the same in v35 and in v34, with dbname only changing in-between.

Just to be sure, because I could have done something wrong with the
rebase of v35, I have done the same test with v34 applied on top of
dfc843d and things are failing.  So it seems to me that there is an
issue with the DN mapping part.
--
Michael
From 5db9fbc12897b28d216a1480cd529f0158525a37 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:22 +0100
Subject: [PATCH v35 1/9] nss: Support libnss as TLS library in libpq

This commit contains the frontend and backend portion of TLS support
in libpq to allow encrypted connections using NSS. The implementation
is done as a drop-in replacement for the OpenSSL support and leverages
the same internal API for abstracting library specific details.

A new GUC, ssl_database, is used to identify the NSS database used for
the serverside certificates and keys. The existing certificate and key
GUCs are used for providing certificate and key nicknames.

Client side there is a new connection parameter, cert_database, to
identify the client cert and key. All existing sslmodes are supported
in the same way as with OpenSSL.

Authors: Daniel Gustafsson, Andrew Dunstan, Jacob Champion
Reviewed-by: Michael Paquier
---
 src/include/common/nss.h                      |   52 +
 src/include/libpq/libpq-be.h                  |   10 +-
 src/include/libpq/libpq.h                     |    1 +
 src/include/pg_config_manual.h                |    2 +-
 src/backend/libpq/auth.c                      |    6 +
 src/backend/libpq/be-secure-nss.c             | 1385 +++++++++++++++++
 src/backend/libpq/be-secure.c                 |    1 +
 src/backend/utils/misc/guc.c                  |   18 +-
 src/common/cipher_nss.c                       |  192 +++
 src/common/protocol_nss.c                     |   59 +
 src/interfaces/libpq/fe-connect.c             |    4 +
 src/interfaces/libpq/fe-secure-nss.c          | 1080 +++++++++++++
 src/interfaces/libpq/fe-secure.c              |   21 +
 src/interfaces/libpq/libpq-fe.h               |   11 +
 src/interfaces/libpq/libpq-int.h              |   29 +-
 .../postgres_fdw/expected/postgres_fdw.out    |    2 +-
 16 files changed, 2868 insertions(+), 5 deletions(-)
 create mode 100644 src/include/common/nss.h
 create mode 100644 src/backend/libpq/be-secure-nss.c
 create mode 100644 src/common/cipher_nss.c
 create mode 100644 src/common/protocol_nss.c
 create mode 100644 src/interfaces/libpq/fe-secure-nss.c

diff --git a/src/include/common/nss.h b/src/include/common/nss.h
new file mode 100644
index 0000000000..3385429f91
--- /dev/null
+++ b/src/include/common/nss.h
@@ -0,0 +1,52 @@
+/*-------------------------------------------------------------------------
+ *
+ * nss.h
+ *	  NSS supporting functionality shared between frontend and backend
+ *
+ * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ *		  src/include/common/nss.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef COMMON_NSS_H
+#define COMMON_NSS_H
+
+#ifdef USE_NSS
+
+/*
+ * BITS_PER_BYTE is also defined in the NSPR header files, so we need to undef
+ * our version to avoid compiler warnings on redefinition.
+ */
+#define pg_BITS_PER_BYTE BITS_PER_BYTE
+#undef BITS_PER_BYTE
+/*
+ * The nspr/obsolete/protypes.h NSPR header typedefs uint64 and int64 with
+ * colliding definitions from ours, causing a much expected compiler error.
+ * Remove backwards compatibility with ancient NSPR versions to avoid this.
+ */
+#define NO_NSPR_10_SUPPORT
+#include <nspr/nspr.h>
+#include <nspr/prerror.h>
+#include <nspr/prio.h>
+#include <nspr/prmem.h>
+#include <nspr/prtypes.h>
+
+
+#include <nss/nss.h>
+#include <nss/hasht.h>
+#include <nss/secoidt.h>
+#include <nss/sslproto.h>
+
+/* src/common/cipher_nss.c */
+bool pg_find_cipher(char *name, PRUint16 *cipher);
+bool pg_find_signature_algorithm(SECOidTag signature, SECOidTag *digest, int *len);
+
+/* src/common/protocol_nss.c */
+char *ssl_protocol_version_to_string(int version);
+
+#endif							/* USE_NSS */
+
+#endif							/* COMMON_NSS_H */
diff --git a/src/include/libpq/libpq-be.h b/src/include/libpq/libpq-be.h
index 713c34fedd..3507085a44 100644
--- a/src/include/libpq/libpq-be.h
+++ b/src/include/libpq/libpq-be.h
@@ -206,6 +206,10 @@ typedef struct Port
 	SSL		   *ssl;
 	X509	   *peer;
 #endif
+
+#ifdef USE_NSS
+	void	   *pr_fd;
+#endif
 } Port;
 
 #ifdef USE_SSL
@@ -288,7 +292,7 @@ extern void be_tls_get_peer_serial(Port *port, char *ptr, size_t len);
@@ -298,6 +302,10 @@ extern char *be_tls_get_certificate_hash(Port *port, size_t *len);
 
 #endif							/* USE_SSL */
 
diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
index 3ebbc8d665..15bb3c5d77 100644
--- a/src/include/libpq/libpq.h
+++ b/src/include/libpq/libpq.h
@@ -88,6 +88,7 @@ extern PGDLLIMPORT bool ssl_passphrase_command_supports_reload;
 #ifdef USE_SSL
 extern bool ssl_loaded_verify_locations;
 #endif
+extern char *ssl_database;
 
index e28c990382..d839738213 100644
@@ -185,7 +185,7 @@
  * implementation.
 
diff --git a/src/backend/libpq/auth.c b/src/backend/libpq/auth.c
index 9dc28e19aa..ba4321353e 100644
--- a/src/backend/libpq/auth.c
+++ b/src/backend/libpq/auth.c
@@ -2802,7 +2802,13 @@ CheckCertAuth(Port *port)
 	int			status_check_usermap = STATUS_ERROR;
 	char	   *peer_username = NULL;

 	/* select the correct field to compare */
 	switch (port->hba->clientcertname)
index 0000000000..d2222a680f
@@ -0,0 +1,1385 @@
+ * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
+#include "common/nss.h"
+static uint16 ssl_protocol_version_to_nss(int v);
+		int			ver = ssl_protocol_version_to_nss(ssl_min_protocol_version);
+		int			ver = ssl_protocol_version_to_nss(ssl_max_protocol_version);
+ * be_tls_open_server
+ * Since NSPR initialization must happen after forking, most of the actual
+ * setup of NSPR/NSS is done here rather than in be_tls_init. This introduce
+ * differences with the OpenSSL support where some errors are only reported
+ * at runtime with NSS where they are reported at startup with OpenSSL.
+	port->pr_fd = PR_ImportTCPSocket(port->sock);
+			if (pg_find_cipher(c, &ciphercode))
+					(errmsg("no cipher-suites found")));
+	 * Set up the custom IO layer in order to be able to provide custom call-
+	 * backs for IO operations which override the built-in behavior. For now
+	 * we need this in order to support debug builds of NSS/NSPR.
+	if (PR_PushIOLayer(port->pr_fd, PR_TOP_IO_LAYER, layer) != PR_SUCCESS)
+	 * Apply the configuration from the model template onto our actual socket
+	 * to set it up as a TLS server.
+	port->pr_fd = SSL_ImportFD(model, port->pr_fd);
+				(errmsg("unable to configure socket for TLS server mode: %s",
+	 * The intention with the model FD is to keep it as a template for coming
+	 * connections to amortize the cost and complexity across all client
+	 * sockets. Since we won't get another socket connected in this backend
+	 * we can however close the model immediately.
+	/* Register our shutdown callback */
+ * be_tls_close
+ * Callback for closing down the current connection, if any.
+ * be_tls_destroy
+ * Callback for destroying global contexts during SIGHUP.
+ * be_tls_get_cipher_bits
+ * be_tls_get_cipher
+ * Returns the cipher used for the current connection.
+ * be_tls_get_peer_subject_name
+ * Returns the subject name of the peer certificate.
+ * be_tls_get_peer_issuer_name
+ * Returns the issuer name of the peer certificate.
+ * be_tls_get_peer_serial
+ * Returns the serial of the peer certificate.
+ * be_tls_get_certificate_hash
+ * Returns the hash data of the server certificate for SCRAM channel binding.
+	SECOidTag	signature_tag;
+	PK11Context *ctx = NULL;
+	signature_tag = SECOID_GetAlgorithmTag(&certificate->signature);
+	if (!pg_find_signature_algorithm(signature_tag, &digest_alg, &digest_len))
+			 SECOID_FindOIDTagDescription(signature_tag));
+	 * The TLS server's certificate bytes need to be hashed with SHA-256 if
+	 * its signature algorithm is MD5 or SHA-1 as per RFC 5929
+	 * (https://tools.ietf.org/html/rfc5929#section-4.1).  If something else
+	 * is used, the same hash as the signature algorithm is used.
+	if (digest_alg == SEC_OID_SHA1 || digest_alg == SEC_OID_MD5)
+		digest_alg = SEC_OID_SHA256;
+		digest_len = SHA256_LENGTH;
+	ctx = PK11_CreateDigestContext(digest_alg);
+		elog(ERROR, "out of memory");
+	status |= PK11_DigestBegin(ctx);
+	status |= PK11_DigestOp(ctx, certificate->derCert.data, certificate->derCert.len);
+	status |= PK11_DigestFinal(ctx, digest.data, &outlen, digest_len);
+		PK11_DestroyContext(ctx, PR_TRUE);
+		elog(ERROR, "could not generate server certificate hash");
+	PK11_DestroyContext(ctx, PR_TRUE);
+ * Callback for handling certificate validation failure during handshake. It's
+ * called from SSL_AuthCertificate during failure cases.
+			/* Found a CN, decode and copy it into a newly allocated buffer */
+ssl_protocol_version_to_nss(int v)
index 8ef083200a..cf056f5364 100644
@@ -50,6 +50,7 @@ bool		ssl_passphrase_command_supports_reload;
 
 /* GUC variable controlling SSL cipher list */
 char	   *SSLCipherSuites = NULL;
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index c9c9da85f3..7a25f36cd1 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -4370,7 +4370,11 @@ static struct config_string ConfigureNamesString[] =
 		},
 		&ssl_library,
 #ifdef USE_SSL
+#if defined(USE_OPENSSL)
 		"OpenSSL",
+#elif defined(USE_NSS)
+		"NSS",
+#endif
 #else
 		"",
 #endif
@@ -4438,6 +4442,16 @@ static struct config_string ConfigureNamesString[] =
 		check_canonical_path, assign_pgstat_temp_directory, NULL
 	},
 
+	{
@@ -4466,8 +4480,10 @@ static struct config_string ConfigureNamesString[] =
diff --git a/src/common/cipher_nss.c b/src/common/cipher_nss.c
index 0000000000..30b32a7908
+ * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
+ *        src/common/cipher_nss.c
+#include "common/nss.h"
+}			NSSSignatureAlgorithm;
+static const NSSSignatureAlgorithm NSS_SCRAMDigestAlgorithm[] = {
+pg_find_cipher(char *name, PRUint16 *cipher)
+	const		NSSCiphers *cipher_list;
+	for (cipher_list = NSS_CipherList; cipher_list->name; cipher_list++)
+			*cipher = cipher_list->number;
+pg_find_signature_algorithm(SECOidTag signature, SECOidTag *algorithm, int *len)
+	const NSSSignatureAlgorithm *candidate;
+	for (candidate = NSS_SCRAMDigestAlgorithm; candidate->signature; candidate++)
+		if (signature == candidate->signature)
+			*algorithm = candidate->hash;
+			*len = candidate->len;
diff --git a/src/common/protocol_nss.c b/src/common/protocol_nss.c
index 0000000000..e8225a4d9d
+++ b/src/common/protocol_nss.c
@@ -0,0 +1,59 @@
+ * protocol_nss.c
+ *	  with protocols
+ * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
+ *		  src/common/protocol_nss.c
+#include "common/nss.h"
+ * ssl_protocol_version_to_string
+ *			Translate NSS TLS version to string
index 56a8266bc3..61d736fa7e 100644
@@ -341,6 +341,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = {
 
+	{"ssldatabase", NULL, NULL, NULL,
+	offsetof(struct pg_conn, ssldatabase)},
index 0000000000..5f4eb31535
@@ -0,0 +1,1080 @@
+ * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
+#include "common/nss.h"
+static SECStatus pg_load_nss_module(SECMODModule **module, const char *library, const char *name);
+static SECStatus pg_client_auth_handler(void *arg, PRFileDesc *socket, CERTDistNames *caNames,
+										CERTCertificate **pRetCert, SECKEYPrivateKey **pRetKey);
+static SECStatus pg_cert_auth_handler(void *arg, PRFileDesc *fd, PRBool checksig, PRBool isServer);
+static int	ssl_protocol_param_to_nss(const char *protocol);
+static bool certificate_database_has_CA(PGconn *conn);
+static char *PQssl_passwd_cb(PK11SlotInfo *slot, PRBool retry, void *arg);
+static SECMODModule *ca_trust = NULL;
+ * This logic exists in NSS as well, but it's only available for when there is
+pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)
+	if (do_ssl)
+		conn->nss_context = NULL;
+	if (conn->nss_context)
+		NSS_ShutdownContext(conn->nss_context);
+		conn->nss_context = NULL;
+	if (conn->ssldatabase && strlen(conn->ssldatabase) > 0)
+		char	   *ssldatabase_path = psprintf("sql:%s", conn->ssldatabase);
+		conn->nss_context = NSS_InitContext(ssldatabase_path, "", "", "",
+		pfree(ssldatabase_path);
+							  conn->ssldatabase,
+							  libpq_gettext("unable to initialize NSS: %s"),
+	 * Configure cipher policy by setting the domestic suite.
+	 * still attempt a connection as long as the sslmode isn't verify-*.
+	if (!conn->ssldatabase &&
+		(strcmp(conn->sslmode, "verify-ca") == 0 ||
+		 strcmp(conn->sslmode, "verify-full") == 0))
+							  libpq_gettext("WARNING: unable to load system NSS trust module \"%s\", create a local NSS database and retry : %s"),
+	conn->pr_fd = PR_ImportTCPSocket(conn->sock);
+		int			ssl_min_ver = ssl_protocol_param_to_nss(conn->ssl_min_protocol_version);
+		int			ssl_max_ver = ssl_protocol_param_to_nss(conn->ssl_max_protocol_version);
+	conn->pr_fd = SSL_ImportFD(model, conn->pr_fd);
+	 * The model can now be closed as we've applied the settings of the model
+	 * onto the real socket. From here on we should only use conn->pr_fd.
+	/* Set callback for client authentication when requested by the server */
+	 * Specify which hostname we are expecting to talk to for the ClientHello
+	 * SNI extension.
+	SECOidTag	signature_tag;
+	signature_tag = SECOID_GetAlgorithmTag(&server_cert->signature);
+	if (!pg_find_signature_algorithm(signature_tag, &digest_alg, &digest_len))
+						  SECOID_FindOIDTagDescription(signature_tag));
+pg_load_nss_module(SECMODModule **module, const char *library, const char *name)
+	 * VerifyCertificateNow verifies the validity using PR_now from NSPR as a
+	 * timestamp and will perform CRL and OSCP revocation checks. conn->sslcrl
+	 * does not impact NSS connections as any CRL in the NSS database will be
+	 * used automatically.
+pg_client_auth_handler(void *arg, PRFileDesc *socket, CERTDistNames *caNames,
+					   CERTCertificate **pRetCert, SECKEYPrivateKey **pRetKey)
+		if (conn->ssldatabase &&
+			strlen(conn->ssldatabase) > 0 &&
+			certificate_database_has_CA(conn))
+	else if (strcmp(conn->sslmode, "verify-full") == 0 ||
+			 strcmp(conn->sslmode, "verify-ca") == 0)
+ * somewhere as it's nonsensical to run in a non-OpenSSL build.
+ * ssl_protocol_param_to_nss
+ * Return the NSS internal representation of the protocol asked for by the
+ * user as a connection param.
+ssl_protocol_param_to_nss(const char *protocol)
+ * certificate_database_has_CA
+ *		 Check for the presence of a CA certificate
+certificate_database_has_CA(PGconn *conn)
+ * PQssl_passwd_cb
+ *		 Supply a password to decrypt an object
+ * If an object in the NSS database is password protected, or if the entire
+ * NSS database is itself password protected, this callback will be invoked.
+ * PQdefaultSSLKeyPassHook_nss
+ * 		 Default password handler callback
+ * If no user defined password callback has been set up, the callback below
+ * will try the password set by the sslpassword parameter. Since we by legacy
+ * only have support for a single password, there is little reason to inspect
+ * the slot for the object in question. A TODO is to support different
+ * passwords for different objects, either via a DSL in sslpassword or with a
+ * new key/value style parameter. Users can supply their own password hook to
+ * do this of course, but it would be nice to support something in core too.
+PQdefaultSSLKeyPassHook_nss(PK11SlotInfo *slot, PRBool retry, void *arg)
index b15d8d137c..d76eb4806f 100644
@@ -447,6 +447,27 @@ PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
 }
 #endif							/* USE_OPENSSL */
 
+#ifndef USE_NSS
+
 
diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h
index 227adde5a5..2ade6f8445 100644
--- a/src/interfaces/libpq/libpq-fe.h
+++ b/src/interfaces/libpq/libpq-fe.h
@@ -650,6 +650,17 @@ extern PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
 extern void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook);
 extern int	PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn);
 
index 3f7907127e..750afe54b3 100644
@@ -80,6 +80,10 @@ typedef struct
 #endif
 #endif							/* USE_OPENSSL */
 
+#ifdef USE_NSS
+#include "common/nss.h"
+#endif
+
 /*
  * POSTGRES backend dependent Constants.
  */
@@ -383,6 +387,7 @@ struct pg_conn
 	char	   *sslrootcert;	/* root certificate filename */
 	char	   *sslcrl;			/* certificate revocation list filename */
 	char	   *sslcrldir;		/* certificate revocation list directory name */
+	char	   *ssldatabase;	/* NSS certificate/key database */
 	char	   *requirepeer;	/* required peer credentials for local sockets */
 	char	   *gssencmode;		/* GSS mode (require,prefer,disable) */
 	char	   *krbsrvname;		/* Kerberos service name */
@@ -523,6 +528,28 @@ struct pg_conn
 								 * removed as this locking is handled
 								 * internally in OpenSSL >= 1.1.0. */
 #endif							/* USE_OPENSSL */
+
+/*
+ * The NSS/NSPR specific types aren't used to avoid pulling in the required
+ * headers here, as they are causing conflicts with PG definitions.
+ */
+#ifdef USE_NSS
+	NSSInitContext	   *nss_context;	/* NSS connection specific context */
+	PRFileDesc		   *pr_fd;			/* NSPR file descriptor for the connection */
+
+	/*
+	 * Track whether the NSS database has a password set or not. There is no
+	 * API function for retrieving password status of a database, but we need
+	 * to know since some NSS API calls require the password passed in (they
+	 * don't call the callback themselves). To track, we simply flip this to
+	 * true in case NSS invoked the password callback - as that will only
+	 * happen in case there is a password. The reason for tracking this is
+	 * that there are calls which require a password parameter, but doesn't
+	 * use the callbacks provided, so we must call the callback on behalf of
+	 * these.
+	 */
+	bool		has_password;
+#endif							/* USE_NSS */
 #endif							/* USE_SSL */
 
 #ifdef ENABLE_GSS
@@ -784,7 +811,7 @@ extern ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len);
  * This is not supported with old versions of OpenSSL that don't have
  * the X509_get_signature_nid() function.
  */
-#if defined(USE_OPENSSL) && defined(HAVE_X509_GET_SIGNATURE_NID)
+#if defined(USE_NSS) || (defined(USE_OPENSSL) && defined(HAVE_X509_GET_SIGNATURE_NID))
 #define HAVE_PGTLS_GET_PEER_CERTIFICATE_HASH
 extern char *pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len);
 #endif
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 59e4e27ffb..2d374f5040 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -8913,7 +8913,7 @@ DO $d$
     END;
 $d$;
 ERROR:  invalid option "password"
-HINT:  Valid options in this context are: service, passfile, channel_binding, connect_timeout, dbname, host, hostaddr, port, options, application_name, keepalives, keepalives_idle, keepalives_interval, keepalives_count, tcp_user_timeout, sslmode, sslcompression, sslcert, sslkey, sslrootcert, sslcrl, sslcrldir, requirepeer, ssl_min_protocol_version, ssl_max_protocol_version, gssencmode, krbsrvname, gsslib, target_session_attrs, use_remote_estimate, fdw_startup_cost, fdw_tuple_cost, extensions, updatable, fetch_size, batch_size, async_capable, keep_connections
+HINT:  Valid options in this context are: service, passfile, channel_binding, connect_timeout, dbname, host, hostaddr, port, options, application_name, keepalives, keepalives_idle, keepalives_interval, keepalives_count, tcp_user_timeout, sslmode, sslcompression, sslcert, sslkey, sslrootcert, sslcrl, sslcrldir, requirepeer, ssl_min_protocol_version, ssl_max_protocol_version, gssencmode, krbsrvname, gsslib, target_session_attrs, ssldatabase, use_remote_estimate, fdw_startup_cost, fdw_tuple_cost, extensions, updatable, fetch_size, batch_size, async_capable, keep_connections
 CONTEXT:  SQL statement "ALTER SERVER loopback_nopw OPTIONS (ADD password 'dummypw')"
 PL/pgSQL function inline_code_block line 3 at EXECUTE
 -- If we add a password for our user mapping instead, we should get a different
-- 
2.31.0

From de8baa6ebe0978c097303bcd04efd0a2a82f2474 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:34 +0100
Subject: [PATCH v35 2/9] Refactor SSL testharness for multiple library

No changes are done to the actual tests, this only change how setup and
teardown is performed.
---
 src/test/ssl/t/001_ssltests.pl                |  56 ++--------
 src/test/ssl/t/002_scram.pl                   |   6 +-
 src/test/ssl/t/SSL/Backend/OpenSSL.pm         | 103 ++++++++++++++++++
 .../ssl/t/{SSLServer.pm => SSL/Server.pm}     |  83 +++++++++++---
 4 files changed, 181 insertions(+), 67 deletions(-)
 create mode 100644 src/test/ssl/t/SSL/Backend/OpenSSL.pm
 rename src/test/ssl/t/{SSLServer.pm => SSL/Server.pm} (78%)

diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl
index 21865ac30f..3d5ede4366 100644
--- a/src/test/ssl/t/001_ssltests.pl
+++ b/src/test/ssl/t/001_ssltests.pl
@@ -4,12 +4,10 @@ use PostgresNode;
 use TestLib;
 use Test::More;
 
-use File::Copy;
-
 use FindBin;
 
-use SSLServer;
+use SSL::Server;
 
 if ($ENV{with_ssl} ne 'openssl')
 {
@@ -32,32 +30,6 @@ my $SERVERHOSTCIDR = '127.0.0.1/32';
 # Allocation of base connection string shared among multiple tests.
 my $common_connstr;
 
-	"client-encrypted-der", "client-dn");
 
 note "setting up data directory";
@@ -72,32 +44,22 @@ $node->start;

 
 
-open my $sslconf, '>', $node->data_dir . "/sslconfig.conf";
-print $sslconf "ssl=on\n";
-print $sslconf "ssl_cert_file='server-cn-only.crt'\n";
-print $sslconf "ssl_key_file='server-password.key'\n";
-print $sslconf "ssl_passphrase_command='echo wrongpassword'\n";
-close $sslconf;
-
+set_server_cert($node, 'server-cn-only', 'root+client_ca',
+				   'server-password', 'echo wrongpassword');
 command_fails(
 	[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
 	'restart fails with password-protected key file with wrong password');
 $node->_update_pid(0);
 
-open $sslconf, '>', $node->data_dir . "/sslconfig.conf";
-print $sslconf "ssl=on\n";
-print $sslconf "ssl_cert_file='server-cn-only.crt'\n";
-print $sslconf "ssl_key_file='server-password.key'\n";
-print $sslconf "ssl_passphrase_command='echo secret1'\n";
-close $sslconf;
-
+set_server_cert($node, 'server-cn-only', 'root+client_ca',
+				'server-password', 'echo secret1');
 command_ok(
 	[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
 	'restart succeeds with password-protected key file');
@@ -567,7 +529,5 @@ $node->connect_fails(
 	expected_stderr => qr/SSL error: sslv3 alert certificate revoked/);
 
 # clean up
-foreach my $key (@keys)
-{
-	unlink("ssl/${key}_tmp.key");
-}
+
+SSL::Server::cleanup();
diff --git a/src/test/ssl/t/002_scram.pl b/src/test/ssl/t/002_scram.pl
index 583b62b3a1..0901d3b2e5 100644
--- a/src/test/ssl/t/002_scram.pl
+++ b/src/test/ssl/t/002_scram.pl
@@ -11,11 +11,11 @@ use File::Copy;
 use FindBin;
 use lib $FindBin::RealBin;
 
-use SSLServer;
+use SSL::Server;
 
 if ($ENV{with_ssl} ne 'openssl')
 {
-	plan skip_all => 'OpenSSL not supported by this build';
+	plan skip_all => 'SSL not supported by this build';
 }
 
 # This is the hostname used to connect to the server.
@@ -104,5 +104,3 @@ $node->connect_fails(
 
 # clean up
 unlink($client_tmp_key);
-
index 129a7154a9..19ccdd95f9 100644
 
-package SSLServer;
+package SSL::Server;
 
 use strict;
 use warnings;
 use PostgresNode;
+use RecursiveCopy;
 use TestLib;
 use File::Basename;
 use File::Copy;
 use Test::More;
 
 use Exporter 'import';
 our @EXPORT = qw(
 
@@ -109,14 +129,21 @@ sub configure_test_server_for_ssl
 	close $sslconf;
 
-	mkdir("$pgdata/root+client-crldir");
-	copy_files("ssl/root+client-crldir/*", "$pgdata/root+client-crldir/");
+		copy_files("ssl/root+client-crldir/*", "$pgdata/root+client-crldir/");
 
 	# Stop and restart server to load new listen_addresses.
 	$node->restart;
@@ -124,20 +151,36 @@ sub configure_test_server_for_ssl
 	# Change pg_hba after restart because hostssl requires ssl=on
 	configure_hba_for_ssl($node, $servercidr, $authmethod);

 	my $crlfile  = "root+client.crl";
 	my $crldir;
 
+	$keyfile = $certfile if $keyfile eq '';
+
 	# defaults to use crl file
 	if (defined $_[3] || defined $_[4])
 	{
@@ -147,13 +190,23 @@ sub switch_server_cert
 
 	open my $sslconf, '>', "$pgdata/sslconfig.conf";
 	print $sslconf "ssl=on\n";
-	print $sslconf "ssl_ca_file='$cafile.crt'\n";
-	print $sslconf "ssl_cert_file='$certfile.crt'\n";
-	print $sslconf "ssl_key_file='$certfile.key'\n";
+	print $sslconf $backend->set_server_cert($certfile, $cafile, $keyfile);
 	print $sslconf "ssl_crl_file='$crlfile'\n" if defined $crlfile;
 	print $sslconf "ssl_crl_dir='$crldir'\n" if defined $crldir;
+	print $sslconf "ssl_passphrase_command='$pwcmd'\n"
+	  unless $pwcmd eq '';
 	close $sslconf;
+	return;
+}
 
2.31.0

From 6d28d68f1adc2041aef66ba3c70c269919002d8d Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:37 +0100
Subject: [PATCH v35 3/9] nss: Add NSS specific tests

This adds the SSL/Backend/NSS which implements the setup and teardown
required as well as adds the NSS configuration to the existing tests.

The OpenSSL testfiles are reused by repackaging them into NSS databases
in order for the tests to be cross-library. Additional testfiles are
generated by using only the NSS toolchain as well as rudimentary tests
using these.
---
 src/test/ssl/Makefile                 | 244 +++++++++++++++++
 src/test/ssl/t/001_ssltests.pl        | 372 ++++++++++++++++----------
 src/test/ssl/t/002_scram.pl           |  35 ++-
 src/test/ssl/t/SSL/Backend/NSS.pm     |  61 +++++
 src/test/ssl/t/SSL/Backend/OpenSSL.pm |  19 +-
 src/test/ssl/t/SSL/Server.pm          |  48 +---
 6 files changed, 585 insertions(+), 194 deletions(-)
 create mode 100644 src/test/ssl/t/SSL/Backend/NSS.pm

diff --git a/src/test/ssl/Makefile b/src/test/ssl/Makefile
index a517756c94..c2f783bd1b 100644
--- a/src/test/ssl/Makefile
+++ b/src/test/ssl/Makefile
@@ -33,6 +33,36 @@ SSLFILES := $(CERTIFICATES:%=ssl/%.key) $(CERTIFICATES:%=ssl/%.crt) \
 SSLDIRS := ssl/client-crldir ssl/server-crldir \
 	ssl/root+client-crldir ssl/root+server-crldir
 
+	ssl/nss/root+server_ca.crt__root+server.crldir.db \
@@ -40,6 +70,10 @@ SSLDIRS := ssl/client-crldir ssl/server-crldir \
 #
 sslfiles: $(SSLFILES) $(SSLDIRS)
 
@@ -67,6 +101,35 @@ ssl/%_ca.crt: ssl/%_ca.key %_ca.config ssl/root_ca.crt ssl/new_certs_dir
 
+ssl/nss/%_ca.crt.db: ssl/%_ca.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n $*_ca.crt -i ssl/$*_ca.crt -t "CT,C,C"
+
+ssl/nss/root+server_ca.crt__server.crl.db: ssl/root+server_ca.crt ssl/nss/server.crl
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/root+server_ca.crt -i ssl/root+server_ca.crt -t "CT,C,C"
+	crlutil -I -i ssl/nss/server.crl -d $@ -B
+
+ssl/nss/root+server_ca.crt__root+server.crl.db: ssl/root+server_ca.crt ssl/nss/root.crl ssl/nss/server.crl
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/root+server_ca.crt -i ssl/root+server_ca.crt -t "CT,C,C"
+	crlutil -I -i ssl/nss/root.crl -d $@ -B
+	crlutil -I -i ssl/nss/server.crl -d $@ -B
+
+ssl/nss/root+server_ca.crt__root+server.crldir.db: ssl/root+server_ca.crt
+	$(MKDIR_P) $@
+	certutil -d "sql:$@" -N --empty-password
+	certutil -d "sql:$@" -A -n ssl/root+server_ca.crt -i ssl/root+server_ca.crt -t "CT,C,C"
+	crlutil -I -i ssl/nss/root.crl -d $@ -B
+	for c in $(shell ls ssl/root+server-crldir) ; do \
+		echo $${c} ; \
+		openssl crl -in ssl/root+server-crldir/$${c} -outform der -out ssl/nss/$${c} ; \
+		crlutil -I -i ssl/nss/$${c} -d $@ -B ; \
+	done
+
 # Server certificates, signed by server CA:
 ssl/server-%.crt: ssl/server-%.key ssl/server_ca.crt server-%.config
 	openssl req -new -key ssl/server-$*.key -out ssl/server-$*.csr -config server-$*.config
@@ -80,6 +143,86 @@ ssl/server-ss.crt: ssl/server-cn-only.key ssl/server-cn-only.crt server-cn-only.
 	openssl x509 -req -days 10000 -in ssl/server-ss.csr -signkey ssl/server-cn-only.key -out ssl/server-ss.crt  -extensions v3_req -extfile server-cn-only.config
 	rm ssl/server-ss.csr
 
+ssl/nss/server-cn-only.crt__server-cn-only.key.crldir.db: ssl/nss/server-cn-only.crt__server-cn-only.key.db
+	for c in $(shell ls ssl/root+client-crldir) ; do \
+		echo $${c} ; \
+		openssl crl -in ssl/root+client-crldir/$${c} -outform der -out ssl/nss/$${c} ; \
+		crlutil -I -i ssl/nss/$${c} -d $@ -B ; \
@@ -98,6 +241,27 @@ ssl/client-dn.crt: ssl/client-dn.key ssl/client_ca.crt
 	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
 
@@ -105,6 +269,14 @@ ssl/client-revoked.crt: ssl/client-revoked.key ssl/client_ca.crt client.config
 
@@ -137,19 +309,40 @@ ssl/root+client_ca.crt: ssl/root_ca.crt ssl/client_ca.crt

 

+ssl/nss/root.crl: ssl/root.crl
+	openssl crl -in $^ -outform der -out $@
+
+ssl/nss/root+client.crl: ssl/root+client.crl
+	openssl crl -in $^ -outform der -out $@
+
 # If a CRL is used, OpenSSL requires a CRL file for *all* the CAs in the
 # chain, even if some of them are empty.
 ssl/root+server.crl: ssl/root.crl ssl/server.crl
@@ -175,14 +368,65 @@ ssl/client-crldir: ssl/client.crl
 	mkdir ssl/client-crldir
 	cp ssl/client.crl ssl/client-crldir/`openssl crl -hash -noout -in ssl/client.crl`.r0
 
 	rm -rf $(SSLDIRS)
 
+.PHONY: nssfiles-clean
+nssfiles-clean:
+	rm -rf ssl/nss
+
 
 # Doesn't depend on $(SSLFILES) because we don't rebuild them by default
 check:
diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl
index 3d5ede4366..74cf5dcd7c 100644
--- a/src/test/ssl/t/001_ssltests.pl
+++ b/src/test/ssl/t/001_ssltests.pl
@@ -9,13 +9,22 @@ use lib $FindBin::RealBin;
 
 use SSL::Server;
 
+	plan tests => 107;
+	plan tests => 107;
-	plan tests => 103;
 
 #### Some configuration
@@ -51,19 +60,68 @@ configure_test_server_for_ssl($node, $SERVERHOSTADDR, $SERVERHOSTCIDR,

 
-set_server_cert($node, 'server-cn-only', 'root+client_ca',
-				'server-password', 'echo secret1');
-command_ok(
-	[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
-	'restart succeeds with password-protected key file');
-$node->_update_pid(1);
+	switch_server_cert($node,
+		certfile => 'server-cn-only',
+		cafile => 'root+client_ca',
+		keyfile => 'server-password',
+		nssdatabase => 'server-cn-only.crt__server-password.key.db',
+		passphrase_cmd => 'echo wrongpassword',
+		restart => 'no' );
+
+	command_fails(
+		[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
+		'restart fails with password-protected key file with wrong password');
+	$node->_update_pid(0);
+
+	switch_server_cert($node,
+		certfile => 'server-cn-only',
+		cafile => 'root+client_ca',
+		keyfile => 'server-password',
+		nssdatabase => 'server-cn-only.crt__server-password.key.db',
+		passphrase_cmd => 'echo secret1',
+		restart => 'no');
+
+	command_ok(
+		[ 'pg_ctl', '-D', $node->data_dir, '-l', $node->logfile, 'restart' ],
+		'restart succeeds with password-protected key file');
+	$node->_update_pid(1);
+}
+
+SKIP:
+{
+	skip "Certificate passphrases are checked on connection in NSS", 3
+	  if ($openssl);
+
+	switch_server_cert($node,
+		certfile => 'server-cn-only',
+		cafile => 'root+client_ca',
+		keyfile => 'server-password',
+		nssdatabase => 'server-cn-only.crt__server-password.key.db',
+		passphrase_cmd => 'echo wrongpassword');
+
+	$node->connect_fails(
+		"user=ssltestuser dbname=trustdb sslcert=invalid hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test sslrootcert=invalid sslmode=require",
+		qr/\QSSL error\E/,
+		"connect to server with incorrect key password configured");
+
+	switch_server_cert($node,
+		certfile => 'server-cn-only',
+		cafile => 'root+client_ca',
+		keyfile => 'server-password',
+		nssdatabase => 'server-cn-only.crt__server-password.key.db',
+		passphrase_cmd => 'echo secret1');
+
+	$node->connect_ok(
+		"user=ssltestuser dbname=trustdb sslcert=invalid hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test sslrootcert=invalid sslmode=require",
+		"connect to server with correct key password configured");
+}
 
 # Test compatibility of SSL protocols.
 # TLSv1.1 is lower than TLSv1.2, so it won't work.
@@ -91,7 +149,7 @@ command_ok(
 
 note "running client tests";
 
-switch_server_cert($node, 'server-cn-only');
+switch_server_cert($node, certfile => 'server-cn-only', nssdatabase => 'server-cn-only.crt__server-cn-only.key.db');
 
 $common_connstr =
   "user=ssltestuser dbname=trustdb sslcert=invalid hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test";
@@ -110,87 +168,104 @@ $node->connect_ok(
 $node->connect_fails(
 	"$common_connstr sslrootcert=invalid sslmode=verify-ca",
 	"connect without server root cert sslmode=verify-ca",
-	expected_stderr => qr/root certificate file "invalid" does not exist/);
+	expected_stderr => qr/root certificate file "invalid" does not exist|Peer's certificate issuer has been marked as not trusted by the user/);
 $node->connect_fails(
 	"$common_connstr sslrootcert=invalid sslmode=verify-full",
 	"connect without server root cert sslmode=verify-full",
-	expected_stderr => qr/root certificate file "invalid" does not exist/);
+	expected_stderr => qr/root certificate file "invalid" does not exist|Peer's certificate issuer has been marked as not trusted by the user/);
 
 # Try with wrong root cert, should fail. (We're using the client CA as the
 # root, but the server's key is signed by the server CA.)
 $node->connect_fails(
-	"$common_connstr sslrootcert=ssl/client_ca.crt sslmode=require",
+	"$common_connstr sslrootcert=ssl/client_ca.crt sslmode=require ssldatabase=ssl/nss/client_ca.crt.db",
 	"connect with wrong server root cert sslmode=require",
-	expected_stderr => qr/SSL error: certificate verify failed/);
+	expected_stderr => qr/SSL error: certificate verify failed|Peer's certificate issuer has been marked as not trusted by the user/);
 $node->connect_fails(
-	"$common_connstr sslrootcert=ssl/client_ca.crt sslmode=verify-ca",
+	"$common_connstr sslrootcert=ssl/client_ca.crt sslmode=verify-ca ssldatabase=ssl/nss/client_ca.crt.db",
 	"connect with wrong server root cert sslmode=verify-ca",
-	expected_stderr => qr/SSL error: certificate verify failed/);
+	expected_stderr => qr/SSL error: certificate verify failed|Peer's certificate issuer has been marked as not trusted by the user/);
 $node->connect_fails(
-	"$common_connstr sslrootcert=ssl/client_ca.crt sslmode=verify-full",
+	"$common_connstr sslrootcert=ssl/client_ca.crt sslmode=verify-full ssldatabase=ssl/nss/client_ca.crt.db",
 	"connect with wrong server root cert sslmode=verify-full",
-	expected_stderr => qr/SSL error: certificate verify failed/);
+	expected_stderr => qr/SSL error: certificate verify failed|Peer's certificate issuer has been marked as not trusted by the user/);
 
-# Try with just the server CA's cert. This fails because the root file
-# must contain the whole chain up to the root CA.
-$node->connect_fails(
-	"$common_connstr sslrootcert=ssl/server_ca.crt sslmode=verify-ca",
-	"connect with server CA cert, without root CA",
-	expected_stderr => qr/SSL error: certificate verify failed/);
+SKIP:
+{
+	# NSS supports partial chain validation, so this test doesn't work there.
+	# This is similar to the OpenSSL option X509_V_FLAG_PARTIAL_CHAIN which
+	# we don't allow.
+	skip "NSS support partial chain validation", 2 if ($nss);
+	# Try with just the server CA's cert. This fails because the root file
+	# must contain the whole chain up to the root CA.
+	$node->connect_fails(
+		"$common_connstr sslrootcert=ssl/server_ca.crt sslmode=verify-ca",
+		"connect with server CA cert, without root CA",
+		expected_stderr => qr/SSL error: certificate verify failed/);
+}
 
 # And finally, with the correct root cert.
 $node->connect_ok(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssldatabase=ssl/nss/root+server_ca.crt.db",
 	"connect with correct server CA cert file sslmode=require");
 $node->connect_ok(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca ssldatabase=ssl/nss/root+server_ca.crt.db",
 	"connect with correct server CA cert file sslmode=verify-ca");
 $node->connect_ok(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-full",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-full ssldatabase=ssl/nss/root+server_ca.crt.db",
 	"connect with correct server CA cert file sslmode=verify-full");
 
-# Test with cert root file that contains two certificates. The client should
-# be able to pick the right one, regardless of the order in the file.
-$node->connect_ok(
-	"$common_connstr sslrootcert=ssl/both-cas-1.crt sslmode=verify-ca",
-	"cert root file that contains two certificates, order 1");
-$node->connect_ok(
-	"$common_connstr sslrootcert=ssl/both-cas-2.crt sslmode=verify-ca",
-	"cert root file that contains two certificates, order 2");
+SKIP:
+{
+	skip "CA ordering is irrelevant in NSS databases", 2 if ($nss);
 
+	# Test with cert root file that contains two certificates. The client should
+	# be able to pick the right one, regardless of the order in the file.
+	$node->connect_ok(
+		"$common_connstr sslrootcert=ssl/both-cas-1.crt sslmode=verify-ca",
+		"cert root file that contains two certificates, order 1");
+
+	# How about import the both-file into a database?
+	$node->connect_ok(
+		"$common_connstr sslrootcert=ssl/both-cas-2.crt sslmode=verify-ca",
+		"cert root file that contains two certificates, order 2");
+}
 # CRL tests
 
 # Invalid CRL filename is the same as no CRL, succeeds
 $node->connect_ok(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=invalid",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=invalid ssldatabase=ssl/nss/root+server_ca.crt.db",
 	"sslcrl option with invalid file name");
 
-# A CRL belonging to a different CA is not accepted, fails
-$node->connect_fails(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/client.crl",
-	"CRL belonging to a different CA",
-	expected_stderr => qr/SSL error: certificate verify failed/);
+SKIP:
+{
+	skip "CRL's are verified when adding to NSS database", 4 if ($nss);
+	# A CRL belonging to a different CA is not accepted, fails
+	$node->connect_fails(
+		"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/client.crl",
+		"CRL belonging to a different CA",
+		expected_stderr => qr/SSL error: certificate verify failed/);
 
-# The same for CRL directory
-$node->connect_fails(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrldir=ssl/client-crldir",
-	"directory CRL belonging to a different CA",
-	expected_stderr => qr/SSL error: certificate verify failed/);
+	# The same for CRL directory
+	$node->connect_fails(
+		"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrldir=ssl/client-crldir",
+		"directory CRL belonging to a different CA",
+		expected_stderr => qr/SSL error: certificate verify failed/);
+}
 
 # With the correct CRL, succeeds (this cert is not revoked)
 $node->connect_ok(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/root+server.crl",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/root+server.crl ssldatabase=ssl/nss/root+server_ca.crt__root+server.crl.db",
 	"CRL with a non-revoked cert");
 
 # The same for CRL directory
 $node->connect_ok(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrldir=ssl/root+server-crldir",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrldir=ssl/root+server-crldir ssldatabase=ssl/nss/root+server_ca.crt__root+server.crldir.db",
 	"directory CRL with a non-revoked cert");
 
 # Check that connecting with verify-full fails, when the hostname doesn't
 # match the hostname in the server's certificate.
 $common_connstr =
-  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR";
+  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR ssldatabase=ssl/nss/root+server_ca.crt.db";
 
 $node->connect_ok("$common_connstr sslmode=require host=wronghost.test",
 	"mismatch between host name and server certificate sslmode=require");
@@ -200,15 +275,13 @@ $node->connect_ok(
 $node->connect_fails(
 	"$common_connstr sslmode=verify-full host=wronghost.test",
 	"mismatch between host name and server certificate sslmode=verify-full",
-	expected_stderr =>
-	  qr/\Qserver certificate for "common-name.pg-ssltest.test" does not match host name "wronghost.test"\E/
-);
+	expected_stderr => qr/\Qserver certificate for "common-name.pg-ssltest.test" does not match host name "wronghost.test"\E|requested domain name does not match the server's certificate/);
 
 # Test Subject Alternative Names.
-switch_server_cert($node, 'server-multiple-alt-names');
+switch_server_cert($node, certfile => 'server-multiple-alt-names', nssdatabase => 'server-multiple-alt-names.crt__server-multiple-alt-names.key.db');
 
 $common_connstr =
-  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full";
+  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full ssldatabase=ssl/nss/root+server_ca.crt.db";
 
 $node->connect_ok(
 	"$common_connstr host=dns1.alt-name.pg-ssltest.test",
@@ -222,22 +295,18 @@ $node->connect_ok("$common_connstr host=foo.wildcard.pg-ssltest.test",
 $node->connect_fails(
 	"$common_connstr host=wronghost.alt-name.pg-ssltest.test",
 	"host name not matching with X.509 Subject Alternative Names",
-	expected_stderr =>
-	  qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "wronghost.alt-name.pg-ssltest.test"\E/
-);
+	expected_stderr => qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "wronghost.alt-name.pg-ssltest.test"\E|requested domain name does not match the server's certificate/);
 $node->connect_fails(
 	"$common_connstr host=deep.subdomain.wildcard.pg-ssltest.test",
 	"host name not matching with X.509 Subject Alternative Names wildcard",
-	expected_stderr =>
-	  qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E/
-);
+	expected_stderr => qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E|requested domain name does not match the server's certificate/);
 
 # Test certificate with a single Subject Alternative Name. (this gives a
 # slightly different error message, that's all)
-switch_server_cert($node, 'server-single-alt-name');
+switch_server_cert($node, certfile => 'server-single-alt-name', nssdatabase => 'server-single-alt-name.crt__server-single-alt-name.key.db');
 
 $common_connstr =
-  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full";
+  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full ssldatabase=ssl/nss/root+server_ca.crt.db";
 
 $node->connect_ok(
 	"$common_connstr host=single.alt-name.pg-ssltest.test",
@@ -246,22 +315,19 @@ $node->connect_ok(
 $node->connect_fails(
 	"$common_connstr host=wronghost.alt-name.pg-ssltest.test",
 	"host name not matching with a single X.509 Subject Alternative Name",
-	expected_stderr =>
-	  qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "wronghost.alt-name.pg-ssltest.test"\E/
-);
+	expected_stderr => qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "wronghost.alt-name.pg-ssltest.test"\E|requested domain name does not match the server's certificate/);
 $node->connect_fails(
 	"$common_connstr host=deep.subdomain.wildcard.pg-ssltest.test",
 	"host name not matching with a single X.509 Subject Alternative Name wildcard",
-	expected_stderr =>
-	  qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E/
+	expected_stderr => qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E|requested domain name does not match the server's certificate/
 );
 
 # Test server certificate with a CN and SANs. Per RFCs 2818 and 6125, the CN
 # should be ignored when the certificate has both.
-switch_server_cert($node, 'server-cn-and-alt-names');
+switch_server_cert($node, certfile => 'server-cn-and-alt-names', nssdatabase => 'server-cn-and-alt-names.crt__server-cn-and-alt-names.key.db');
 
 $common_connstr =
-  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full";
+  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR sslmode=verify-full ssldatabase=ssl/nss/root+server_ca.crt.db";
 
 $node->connect_ok("$common_connstr host=dns1.alt-name.pg-ssltest.test",
 	"certificate with both a CN and SANs 1");
@@ -270,44 +336,40 @@ $node->connect_ok("$common_connstr host=dns2.alt-name.pg-ssltest.test",
 $node->connect_fails(
 	"$common_connstr host=common-name.pg-ssltest.test",
 	"certificate with both a CN and SANs ignores CN",
-	expected_stderr =>
-	  qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 1 other name) does not match host name "common-name.pg-ssltest.test"\E/
-);
+	expected_stderr => qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 1 other name) does not match host name "common-name.pg-ssltest.test"\E|requested domain name does not match the server's certificate/);
 
 # Finally, test a server certificate that has no CN or SANs. Of course, that's
 # not a very sensible certificate, but libpq should handle it gracefully.
-switch_server_cert($node, 'server-no-names');
+switch_server_cert($node, certfile => 'server-no-names', nssdatabase => 'server-no-names.crt__server-no-names.key.db');
 $common_connstr =
-  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR";
+  "user=ssltestuser dbname=trustdb sslcert=invalid sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR ssldatabase=ssl/nss/root+server_ca.crt.db";
 
 $node->connect_ok(
 	"$common_connstr sslmode=verify-ca host=common-name.pg-ssltest.test",
 	"server certificate without CN or SANs sslmode=verify-ca");
 $node->connect_fails(
-	$common_connstr . " "
-	  . "sslmode=verify-full host=common-name.pg-ssltest.test",
+	"$common_connstr sslmode=verify-full host=common-name.pg-ssltest.test",
 	"server certificate without CN or SANs sslmode=verify-full",
-	expected_stderr =>
-	  qr/could not get server's host name from server certificate/);
+	expected_stderr => qr/could not get server's host name from server certificate|requested domain name does not match the server's certificate./);
 
 # Test that the CRL works
-switch_server_cert($node, 'server-revoked');
+switch_server_cert($node, certfile => 'server-revoked', nssdatabase => 'server-revoked.crt__server-revoked.key.db');
 
 $common_connstr =
   "user=ssltestuser dbname=trustdb sslcert=invalid hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test";
 
 # Without the CRL, succeeds. With it, fails.
 $node->connect_ok(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca ssldatabase=ssl/nss/root+server_ca.crt.db",
 	"connects without client-side CRL");
 $node->connect_fails(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/root+server.crl",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrl=ssl/server.crl ssldatabase=ssl/nss/root+server_ca.crt__server.crl.db",
 	"does not connect with client-side CRL file",
-	expected_stderr => qr/SSL error: certificate verify failed/);
+	expected_stderr => qr/SSL error: certificate verify failed|SSL error: Peer's Certificate has been revoked/);
 $node->connect_fails(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrldir=ssl/root+server-crldir",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=verify-ca sslcrldir=ssl/root+server-crldir ssldatabase=ssl/nss/root+server_ca.crt__root+server.crldir.db",
 	"does not connect with client-side CRL directory",
-	expected_stderr => qr/SSL error: certificate verify failed/);
+	expected_stderr => qr/SSL error: certificate verify failed|SSL error: Peer's Certificate has been revoked/);
 
 # pg_stat_ssl
 command_like(
@@ -325,29 +387,46 @@ command_like(
 
 # Test min/max SSL protocol versions.
 $node->connect_ok(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=TLSv1.2 ssl_max_protocol_version=TLSv1.2",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=TLSv1.2 ssl_max_protocol_version=TLSv1.2 ssldatabase=ssl/nss/root+server_ca.crt.db",
 	"connection success with correct range of TLS protocol versions");
 $node->connect_fails(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=TLSv1.2 ssl_max_protocol_version=TLSv1.1",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=TLSv1.2 ssl_max_protocol_version=TLSv1.1 ssldatabase=ssl/nss/root+server_ca.crt.db",
 	"connection failure with incorrect range of TLS protocol versions",
 	expected_stderr => qr/invalid SSL protocol version range/);
 $node->connect_fails(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=incorrect_tls",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_min_protocol_version=incorrect_tls ssldatabase=ssl/nss/root+server_ca.crt.db",
 	"connection failure with an incorrect SSL protocol minimum bound",
 	expected_stderr => qr/invalid ssl_min_protocol_version value/);
 $node->connect_fails(
-	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_max_protocol_version=incorrect_tls",
+	"$common_connstr sslrootcert=ssl/root+server_ca.crt sslmode=require ssl_max_protocol_version=incorrect_tls ssldatabase=ssl/nss/root+server_ca.crt.db",
 	"connection failure with an incorrect SSL protocol maximum bound",
 	expected_stderr => qr/invalid ssl_max_protocol_version value/);
 
+# tests of NSS generated certificates/keys
+SKIP:
+{
+	skip "NSS specific tests",            1 if ($openssl);
+
+	switch_server_cert($node, certfile => 'native_server-root', cafile => 'native_ca-root', nssdatabase => 'native_server-root.db');
+	$common_connstr =
+	  "user=ssltestuser dbname=trustdb hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test";
+
+	$node->connect_ok(
+		"$common_connstr sslmode=require user=ssltestuser",
+		"NSS generated certificates"
+	);
+}
+
 ### Server-side tests.
 ###
 ### Test certificate authorization.
 
+switch_server_cert($node, certfile => 'server-revoked', nssdatabase => 'server-revoked.crt__server-revoked.key.db');
+
 note "running server tests";
 
 $common_connstr =
-  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=certdb hostaddr=$SERVERHOSTADDR";
+  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=certdb hostaddr=$SERVERHOSTADDR ssldatabase=ssl/nss/client.crt__client.key.db";
 
 # no client cert
 $node->connect_fails(
@@ -361,55 +440,67 @@ $node->connect_ok(
 	"certificate authorization succeeds with correct client cert in PEM format"
 );
 
-# correct client cert in unencrypted DER
-$node->connect_ok(
-	"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-der_tmp.key",
-	"certificate authorization succeeds with correct client cert in DER format"
-);
+$common_connstr =
+  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=certdb hostaddr=$SERVERHOSTADDR";
+
+SKIP:
+{
+	skip "NSS database not implemented in the Makefile", 1 if ($nss);
+	# correct client cert in unencrypted DER
+	$node->connect_ok(
+		"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-der_tmp.key",
+		"certificate authorization succeeds with correct client cert in DER format"
+	);
+}
 
 # correct client cert in encrypted PEM
 $node->connect_ok(
-	"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-pem_tmp.key sslpassword='dUmmyP^#+'",
+	"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-pem_tmp.key sslpassword='dUmmyP^#+' ssldatabase=ssl/nss/client.crt__client-encrypted-pem.key.db",
 	"certificate authorization succeeds with correct client cert in encrypted PEM format"
 );
 
-# correct client cert in encrypted DER
-$node->connect_ok(
-	"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-der_tmp.key sslpassword='dUmmyP^#+'",
-	"certificate authorization succeeds with correct client cert in encrypted DER format"
-);
+SKIP:
+{
+	skip "NSS database not implemented in the Makefile", 1 if ($nss);
+	# correct client cert in encrypted DER
+	$node->connect_ok(
+		"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-der_tmp.key sslpassword='dUmmyP^#+'",
+		"certificate authorization succeeds with correct client cert in encrypted DER format"
+	);
+}
 
 # correct client cert in encrypted PEM with wrong password
 $node->connect_fails(
-	"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-pem_tmp.key sslpassword='wrong'",
+	"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-encrypted-pem_tmp.key sslpassword='wrong' ssldatabase=ssl/nss/client.crt__client-encrypted-pem.key.db",
 	"certificate authorization fails with correct client cert and wrong password in encrypted PEM format",
-	expected_stderr =>
-	  qr!\Qprivate key file "ssl/client-encrypted-pem_tmp.key": bad decrypt\E!
+	expected_stderr =>qr!connection requires a valid client certificate|\Qprivate key file "ssl/client-encrypted-pem_tmp.key": bad decrypt\E!
 );
 
+SKIP:
+{
+	skip "DN mapping not implemented in NSS",            3 if ($nss);
 
-# correct client cert using whole DN
-my $dn_connstr = "$common_connstr dbname=certdb_dn";
+	# correct client cert using whole DN
+	my $dn_connstr = "$common_connstr dbname=certdb_dn";
 
-$node->connect_ok(
-	"$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key",
-	"certificate authorization succeeds with DN mapping");
+	$node->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 = "$common_connstr dbname=certdb_dn_re";
+	# same thing but with a regex
+	$dn_connstr = "$common_connstr dbname=certdb_dn_re";
 
-$node->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 = "$common_connstr dbname=certdb_cn";
-
-$node->connect_ok(
-	"$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key",
-	"certificate authorization succeeds with CN mapping");
+	$node->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 = "$common_connstr dbname=certdb_cn";
 
+	$node->connect_ok(
+		"$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key",
+		"certificate authorization succeeds with CN mapping");
+}
 
 TODO:
 {
@@ -447,18 +538,19 @@ command_like(
 		'-P',
 		'null=_null_',
 		'-d',
-		"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client_tmp.key",
+		"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client_tmp.key ssldatabase=ssl/nss/client.crt__client.key.db",
 		'-c',
 		"SELECT * FROM pg_stat_ssl WHERE pid = pg_backend_pid()"
 	],
 	qr{^pid,ssl,version,cipher,bits,client_dn,client_serial,issuer_dn\r?\n
-				^\d+,t,TLSv[\d.]+,[\w-]+,\d+,/CN=ssltestuser,1,\Q/CN=Test CA for PostgreSQL SSL regression test client certs\E\r?$}mx,
+				^\d+,t,TLSv[\d.]+,[\w-]+,\d+,/?CN=ssltestuser,1,/?\QCN=Test CA for PostgreSQL SSL regression test client certs\E\r?$}mx,
 	'pg_stat_ssl with client certificate');

 	$node->connect_fails(
 		"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client_wrongperms_tmp.key",
@@ -472,20 +564,23 @@ SKIP:
 $node->connect_fails(
 	"$common_connstr user=anotheruser sslcert=ssl/client.crt sslkey=ssl/client_tmp.key",
 	"certificate authorization fails with client cert belonging to another user",
-	expected_stderr =>
-	  qr/certificate authentication failed for user "anotheruser"/);
+	expected_stderr => qr/unable to verify certificate|certificate authentication failed for user "anotheruser"/
+);
+
+$common_connstr =
+  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=certdb hostaddr=$SERVERHOSTADDR ssldatabase=ssl/nss/client-revoked.crt__client-revoked.key.db";
 
 # revoked client cert
 $node->connect_fails(
 	"$common_connstr user=ssltestuser sslcert=ssl/client-revoked.crt sslkey=ssl/client-revoked_tmp.key",
 	"certificate authorization fails with revoked client cert",
-	expected_stderr => qr/SSL error: sslv3 alert certificate revoked/);
+	expected_stderr => qr/SSL error: sslv3 alert certificate revoked|SSL error: Peer's certificate issuer has been marked as not trusted by the user/);
 
 # Check that connecting with auth-option verify-full in pg_hba:
 # works, iff username matches Common Name
 # fails, iff username doesn't match Common Name.
 $common_connstr =
-  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=verifydb hostaddr=$SERVERHOSTADDR";
+  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=verifydb hostaddr=$SERVERHOSTADDR ssldatabase=ssl/nss/client.crt__client.key.db";
 
 $node->connect_ok(
 	"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client_tmp.key",
@@ -506,9 +601,9 @@ $node->connect_ok(
 );
 
 # intermediate client_ca.crt is provided by client, and isn't in server's ssl_ca_file
-switch_server_cert($node, 'server-cn-only', 'root_ca');
+switch_server_cert($node, certfile => 'server-cn-only', cafile => 'root_ca', nssdatabase => 'server-cn-only.crt__server-cn-only.key.db');
 $common_connstr =
-  "user=ssltestuser dbname=certdb sslkey=ssl/client_tmp.key sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR";
+  "user=ssltestuser dbname=certdb sslkey=ssl/client_tmp.key sslrootcert=ssl/root+server_ca.crt hostaddr=$SERVERHOSTADDR ssldatabase=ssl/nss/client+client_ca.crt__client.key.db";
 
 $node->connect_ok(
 	"$common_connstr sslmode=require sslcert=ssl/client+client_ca.crt",
@@ -516,17 +611,16 @@ $node->connect_ok(
 $node->connect_fails(
 	$common_connstr . " " . "sslmode=require sslcert=ssl/client.crt",
 	"intermediate client certificate is missing",
-	expected_stderr => qr/SSL error: tlsv1 alert unknown ca/);
+	expected_stderr => qr/SSL error: tlsv1 alert unknown ca|connection requires a valid client certificate/);
 
 # test server-side CRL directory
-switch_server_cert($node, 'server-cn-only', undef, undef,
-	'root+client-crldir');
+switch_server_cert($node, certfile => 'server-cn-only', crldir => 'root+client-crldir', nssdatabase => 'server-cn-only.crt__server-cn-only.key.crldir.db');
 
 # revoked client cert
 $node->connect_fails(
-	"$common_connstr user=ssltestuser sslcert=ssl/client-revoked.crt sslkey=ssl/client-revoked_tmp.key",
+	"$common_connstr user=ssltestuser sslcert=ssl/client-revoked.crt sslkey=ssl/client-revoked_tmp.key ssldatabase=ssl/nss/client-revoked.crt__client-revoked.key.db",
 	"certificate authorization fails with revoked client cert with server-side CRL directory",
-	expected_stderr => qr/SSL error: sslv3 alert certificate revoked/);
+	expected_stderr => qr/SSL error: sslv3 alert certificate revoked|SSL error: Encountered end of file/);
 
 # clean up
 
diff --git a/src/test/ssl/t/002_scram.pl b/src/test/ssl/t/002_scram.pl
index 0901d3b2e5..c6c6674fc7 100644
--- a/src/test/ssl/t/002_scram.pl
+++ b/src/test/ssl/t/002_scram.pl
@@ -13,7 +13,26 @@ use lib $FindBin::RealBin;
 
 use SSL::Server;

 
@@ -47,7 +60,7 @@ $node->start;
 # Configure server for SSL connections, with password handling.
 configure_test_server_for_ssl($node, $SERVERHOSTADDR, $SERVERHOSTCIDR,
 	"scram-sha-256", "pass", "scram-sha-256");
-switch_server_cert($node, 'server-cn-only');
+switch_server_cert($node, certfile => 'server-cn-only', nssdatabase => 'server-cn-only.crt__server-cn-only.key.db');
 $ENV{PGPASSWORD} = "pass";
 $common_connstr =
   "dbname=trustdb sslmode=require sslcert=invalid sslrootcert=invalid hostaddr=$SERVERHOSTADDR";
@@ -96,11 +109,9 @@ my $client_tmp_key = "ssl/client_scram_tmp.key";
 copy("ssl/client.key", $client_tmp_key);
 chmod 0600, $client_tmp_key;
 $node->connect_fails(
-	"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR dbname=certdb user=ssltestuser channel_binding=require",
+	"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR ssldatabase=ssl/nss/client.crt__client.key.db dbname=certdb user=ssltestuser channel_binding=require",
 	"Cert authentication and channel_binding=require",
-	expected_stderr =>
-	  qr/channel binding required, but server authenticated client without channel binding/
-);
+	expected_stderr => qr/channel binding required, but server authenticated client without channel binding/);
 
 # clean up
 unlink($client_tmp_key);
diff --git a/src/test/ssl/t/SSL/Backend/NSS.pm b/src/test/ssl/t/SSL/Backend/NSS.pm
new file mode 100644
index 0000000000..20633fe41b
--- /dev/null
+++ b/src/test/ssl/t/SSL/Backend/NSS.pm
@@ -0,0 +1,61 @@
+package SSL::Backend::NSS;
+
+use strict;
+use warnings;
+use Exporter;
+
+our @ISA       = qw(Exporter);
+our @EXPORT_OK = qw(get_new_nss_backend);
+
+sub new
+{
+	my ($class) = @_;
+
+	my $self = { _library => 'NSS' };
+
+	bless $self, $class;
+
+	return $self;
+}
+
+sub get_new_nss_backend
+{
+	my $class = 'SSL::Backend::NSS';
+
+	return $class->new();
+}
+
+sub init
+{
+	# Make sure the certificate databases are in place?
+}
+
+sub get_library
+{
+	my ($self) = @_;
+
+	return $self->{_library};
+}
+
+sub set_server_cert
+{
+	my $self   = $_[0];
+	my $params = $_[1];
+
+	$params->{cafile} = 'root+client_ca' unless defined $params->{cafile};
+
+	my $sslconf =
+	    "ssl_ca_file='$params->{cafile}.crt'\n"
+	  . "ssl_cert_file='ssl/$params->{certfile}.crt'\n"
+	  . "ssl_crl_file=''\n"
+	  . "ssl_database='nss/$params->{nssdatabase}'\n";
+
+	return $sslconf;
+}
+
+sub cleanup
+{
+	# Something?
+}
+
+1;
diff --git a/src/test/ssl/t/SSL/Backend/OpenSSL.pm b/src/test/ssl/t/SSL/Backend/OpenSSL.pm
index 62b11b7632..f74caf67fe 100644
--- a/src/test/ssl/t/SSL/Backend/OpenSSL.pm
+++ b/src/test/ssl/t/SSL/Backend/OpenSSL.pm
@@ -71,16 +71,19 @@ sub init
 # the server so that the configuration takes effect.
 sub set_server_cert
 {
-	my $self     = $_[0];
-	my $certfile = $_[1];
-	my $cafile   = $_[2] || "root+client_ca";
-	my $keyfile  = $_[3] || $certfile;
+	my $self   = $_[0];
+	my $params = $_[1];
+
+	$params->{cafile} = 'root+client_ca' unless defined $params->{cafile};
+	$params->{crlfile} = 'root+client.crl' unless defined $params->{crlfile};
+	$params->{keyfile} = $params->{certfile} unless defined $params->{keyfile};
 
 	my $sslconf =
-	    "ssl_ca_file='$cafile.crt'\n"
-	  . "ssl_cert_file='$certfile.crt'\n"
-	  . "ssl_key_file='$keyfile.key'\n"
-	  . "ssl_crl_file='root+client.crl'\n";
+	    "ssl_ca_file='$params->{cafile}.crt'\n"
+	  . "ssl_cert_file='$params->{certfile}.crt'\n"
+	  . "ssl_key_file='$params->{keyfile}.key'\n"
+	  . "ssl_crl_file='$params->{crlfile}'\n";
+	$sslconf .= "ssl_crl_dir='$params->{crldir}'\n" if defined $params->{crldir};
 
 	return $sslconf;
 }
diff --git a/src/test/ssl/t/SSL/Server.pm b/src/test/ssl/t/SSL/Server.pm
index 19ccdd95f9..348e48af25 100644
--- a/src/test/ssl/t/SSL/Server.pm
+++ b/src/test/ssl/t/SSL/Server.pm
@@ -55,7 +55,6 @@ elsif ($ENV{with_ssl} eq 'nss')
 use Exporter 'import';
 our @EXPORT = qw(
   configure_test_server_for_ssl
-  set_server_cert
   switch_server_cert
 );
 
@@ -167,46 +166,25 @@ sub cleanup
 	$backend->cleanup();
 }
 
-# Change the configuration to use given server cert file,
-sub set_server_cert
+# Change the configuration to use the given set of certificate, key, ca and
+# CRL, and potentially reload the configuration by restarting the server so
+# that the configuration takes effect.  Restarting is the default, passing
+# restart => 'no' opts out of it leaving the server running.
+sub switch_server_cert
 {
-	my $node     = $_[0];
-	my $certfile = $_[1];
-	my $cafile   = $_[2] || "root+client_ca";
-	my $keyfile  = $_[3] || '';
-	my $pwcmd    = $_[4] || '';
-	my $crlfile  = "root+client.crl";
-	my $crldir;
-	my $pgdata   = $node->data_dir;
-
-	$keyfile = $certfile if $keyfile eq '';
-
-	# defaults to use crl file
-	if (defined $_[3] || defined $_[4])
-	{
-		$crlfile = $_[3];
-		$crldir = $_[4];
-	}
+	my $node   = shift;
+	my %params = @_;
+	my $pgdata = $node->data_dir;
 
 	open my $sslconf, '>', "$pgdata/sslconfig.conf";
 	print $sslconf "ssl=on\n";
-	print $sslconf $backend->set_server_cert($certfile, $cafile, $keyfile);
-	print $sslconf "ssl_crl_file='$crlfile'\n" if defined $crlfile;
-	print $sslconf "ssl_crl_dir='$crldir'\n" if defined $crldir;
-	print $sslconf "ssl_passphrase_command='$pwcmd'\n"
-	  unless $pwcmd eq '';
+	print $sslconf $backend->set_server_cert(\%params);
+	print $sslconf "ssl_passphrase_command='" . $params{passphrase_cmd} . "'\n"
+	  if defined $params{passphrase_cmd};
 	close $sslconf;
-	return;
-}
 
-# Change the configuration to use given server cert file, and reload
-# the server so that the configuration takes effect.
-# Takes the same arguments as set_server_cert, which it calls to do that
-# piece of the work.
-sub switch_server_cert
-{
-	my $node = $_[0];
-	set_server_cert(@_);
+	return if (defined($params{restart}) && $params{restart} eq 'no');
+
 	$node->restart;
 	return;
 }
-- 
2.31.0

From 6fdd9d715ee04ec337ca4f4602d99fe9c87d2394 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:39 +0100
Subject: [PATCH v35 4/9] nss: pg_strong_random support

This adds support for using the RNG in libnss as a backend for
pg_strong_random.
---
 src/port/pg_strong_random.c | 52 +++++++++++++++++++++++++++++++++++--
 1 file changed, 50 insertions(+), 2 deletions(-)

diff --git a/src/port/pg_strong_random.c b/src/port/pg_strong_random.c
index 07f24c0089..1f8441acff 100644
--- a/src/port/pg_strong_random.c
+++ b/src/port/pg_strong_random.c
@@ -137,10 +137,58 @@ pg_strong_random(void *buf, size_t len)
 	return false;
 }

 /*
- * Without OpenSSL or Win32 support, just read /dev/urandom ourselves.
+ * Without OpenSSL, NSS or Win32 support, just read /dev/urandom ourselves.
  */
 
 void
-- 
2.31.0

From 3a37e9ef8ce5e260ed391fb0b69862d4eaee6b5f Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:42 +0100
Subject: [PATCH v35 5/9] nss: Documentation

Basic documentation of the new API (keypass hooks) as well as config
parameters and installation. Additionally there is a section on how
to create certificate and keys using the NSS toolchain.
---
 doc/src/sgml/acronyms.sgml     |  33 ++++
 doc/src/sgml/config.sgml       |  30 ++-
 doc/src/sgml/installation.sgml |  31 ++-
 doc/src/sgml/libpq.sgml        | 339 +++++++++++++++++++++++++--------
 doc/src/sgml/runtime.sgml      | 124 +++++++++++-
 5 files changed, 464 insertions(+), 93 deletions(-)

diff --git a/doc/src/sgml/acronyms.sgml b/doc/src/sgml/acronyms.sgml
index 13bd819eb1..7b02c8a622 100644
--- a/doc/src/sgml/acronyms.sgml
+++ b/doc/src/sgml/acronyms.sgml
@@ -441,6 +441,28 @@
     </listitem>
    </varlistentry>
 
+   <varlistentry>
 
+   <varlistentry>
+    <term><acronym>PKCS#12</acronym></term>
+    <listitem>
+     <para>
+      <ulink
+      url="https://en.wikipedia.org/wiki/PKCS_12">
+      Public-Key Cryptography Standards #12</ulink>
+     </para>
+    </listitem>
+   </varlistentry>
+
    <varlistentry>
     <term><acronym>PL</acronym></term>
     <listitem>
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 0c9128a55d..6327c20faa 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -1309,6 +1309,24 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
+        keys when using <productname>NSS</productname> for
+        <acronym>SSL</acronym>/<acronym>TLS</acronym>
@@ -1325,7 +1343,9 @@ include_dir 'conf.d'
 
@@ -1527,8 +1547,12 @@ include_dir 'conf.d'
        <para>
+        empty password. This requires that the certificate database hasn't
+        been created with a password.
index 66ad4ba938..3cbd125d59 100644
@@ -976,14 +976,31 @@ build-postgresql:
 
diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml
index 3ec458ce09..d448d6284d 100644
--- a/doc/src/sgml/libpq.sgml
+++ b/doc/src/sgml/libpq.sgml
@@ -835,6 +835,12 @@ int callback_fn(char *buf, int size, PGconn *conn);
        <function>longjmp(...)</function>, etc. It must return normally.
       </para>
 
+      <para>
+        <function>PQsetSSLKeyPassHook_OpenSSL</function> has no effect unless
+        the server was compiled with <productname>OpenSSL</productname>
+        support.
+      </para>
+
      </listitem>
     </varlistentry>
 
@@ -851,6 +857,70 @@ PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
 </synopsis>
       </para>
 
+      <para>
+        <function>PQgetSSLKeyPassHook_OpenSSL</function> has no effect unless
+        the server was compiled with <productname>OpenSSL</productname>
+        support.
+      </para>
+
+     </listitem>
+    </varlistentry>
+
+        <function>PQsetSSLKeyPassHook_nss</function> has no effect unless
+        the server was compiled with <productname>NSS</productname> support.
+        server was compiled with <productname>NSS</productname> support.
+      </para>
+
      </listitem>
     </varlistentry>
 
@@ -1643,23 +1713,25 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
         If set to 1, data sent over SSL connections will be compressed.  If
         set to 0, compression will be disabled.  The default is 0.  This
         parameter is ignored if a connection without SSL is made.
-       </para>
-
-       <para>
         SSL compression is nowadays considered insecure and its use is no
-        longer recommended.  <productname>OpenSSL</productname> 1.1.0 disables
-        compression by default, and many operating system distributions
-        disable it in prior versions as well, so setting this parameter to on
-        will not have any effect if the server does not accept compression.
-        <productname>PostgreSQL</productname> 14 disables compression
-        completely in the backend.
-       </para>
+        longer recommended.
+        <itemizedlist>
+         <listitem>
+          <para>
+           <productname>OpenSSL</productname>: 1.1.0 disables compression by
+           default, and many operating system distributions disable it in prior
+           versions as well, so setting this parameter to on will not have any
+           effect if the server does not accept compression.
+          </para>
+         </listitem>
 
-       <para>
-        If security is not a primary concern, compression can improve
-        throughput if the network is the bottleneck.  Disabling compression
-        can improve response time and throughput if CPU performance is the
-        limiting factor.
+         <listitem>
+          <para>
+           <productname>NSS</productname>: SSL compression is not supported in
+           <productname>NSS</productname>, this parameter has no effect.
+          </para>
+         </listitem>
+        </itemizedlist>
        </para>
       </listitem>
      </varlistentry>
@@ -1668,10 +1740,24 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
       <term><literal>sslcert</literal></term>
       <listitem>
        <para>
-        This parameter specifies the file name of the client SSL
-        certificate, replacing the default
-        <filename>~/.postgresql/postgresql.crt</filename>.
-        This parameter is ignored if an SSL connection is not made.
+        This parameter specifies the name or location of the client SSL
+        certificate.  This parameter is ignored if an SSL connection is not
+        made.
+        <itemizedlist>
+         <listitem>
+          <para>
+           <productname>OpenSSL</productname>: can replace the default
+           <filename>~/.postgresql/postgresql.crt</filename>.
+          </para>
+         </listitem>
+
+         <listitem>
+          <para>
+           <productname>NSS</productname>: the nickname of the client SSL
+           certificate.
+          </para>
+         </listitem>
+        </itemizedlist>
        </para>
       </listitem>
      </varlistentry>
@@ -1680,15 +1766,30 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
       <term><literal>sslkey</literal></term>
       <listitem>
        <para>
-        This parameter specifies the location for the secret key used for
-        the client certificate. It can either specify a file name that will
-        be used instead of the default
-        <filename>~/.postgresql/postgresql.key</filename>, or it can specify a key
-        obtained from an external <quote>engine</quote> (engines are
-        <productname>OpenSSL</productname> loadable modules).  An external engine
-        specification should consist of a colon-separated engine name and
-        an engine-specific key identifier.  This parameter is ignored if an
-        SSL connection is not made.
+        This parameter specifies the name or location for the secret key used
+        for the client certificate. This parameter is ignored if an SSL
+        connection is not made.
+        <itemizedlist>
+         <listitem>
+          <para>
+           <productname>OpenSSL</productname>: can either specify a file name
+           that will be used instead of the default
+           <filename>~/.postgresql/postgresql.key</filename>, or it can specify
+           a key obtained from an external <quote>engine</quote> (engines are
+           <productname>OpenSSL</productname> loadable modules).  An external
+           engine specification should consist of a colon-separated engine name
+           and an engine-specific key identifier.
+          </para>
+         </listitem>
+
+         <listitem>
+          <para>
+           <productname>NSS</productname>: this parameter has no effect.  Keys
+           should be loaded into the <productname>NSS</productname>
+           database.
+          </para>
+         </listitem>
+        </itemizedlist>
        </para>
       </listitem>
      </varlistentry>
@@ -1699,28 +1800,44 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
        <para>
         This parameter specifies the password for the secret key specified in
         <literal>sslkey</literal>, allowing client certificate private keys
-        to be stored in encrypted form on disk even when interactive passphrase
+        to be stored in encrypted form even when interactive passphrase
         input is not practical.
-       </para>
-       <para>
-        Specifying this parameter with any non-empty value suppresses the
-        <literal>Enter PEM pass phrase:</literal>
-        prompt that <productname>OpenSSL</productname> will emit by default
-        when an encrypted client certificate key is provided to
-        <literal>libpq</literal>.
-       </para>
-       <para>
-        If the key is not encrypted this parameter is ignored. The parameter
-        has no effect on keys specified by <productname>OpenSSL</productname>
-        engines unless the engine uses the <productname>OpenSSL</productname>
-        password callback mechanism for prompts.
-       </para>
-       <para>
-        There is no environment variable equivalent to this option, and no
-        facility for looking it up in <filename>.pgpass</filename>. It can be
-        used in a service file connection definition. Users with
-        more sophisticated uses should consider using openssl engines and
-        tools like PKCS#11 or USB crypto offload devices.
+        <itemizedlist>
+         <listitem>
+          <para>
+           <productname>OpenSSL</productname>: specifying this parameter with
+           any non-empty value suppresses the
+           <literal>Enter PEM pass phrase:</literal> prompt that
+           <productname>OpenSSL</productname> will emit by default when an
+           encrypted client certificate key is provided to
+           <literal>libpq</literal>.
+          </para>
+          <para>
+           If the key is not encrypted this parameter is ignored. The parameter
+           has no effect on keys specified by <productname>OpenSSL</productname>
+           engines unless the engine uses the <productname>OpenSSL</productname>
+           password callback mechanism for prompts.
+          </para>
+          <para>
+           There is no environment variable equivalent to this option, and no
+           facility for looking it up in <filename>.pgpass</filename>. It can be
+           used in a service file connection definition. Users with
+           more sophisticated uses should consider using
+           <productname>OpenSSL</productname> engines and tools like PKCS#11 or
+           USB crypto offload devices.
+          </para>
+         </listitem>
+
+         <listitem>
+          <para>
+           <productname>NSS</productname>: specifying the parameter is required
+           in case any password protected items are referenced in the
+           <productname>NSS</productname> database, or if the database itself
+           is password protected. All attempts to decrypt objects which are
+           password protected in the database will use this password.
+          </para>
+         </listitem>
+        </itemizedlist>
        </para>
       </listitem>
      </varlistentry>
@@ -1729,11 +1846,27 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
       <term><literal>sslrootcert</literal></term>
       <listitem>
        <para>
-        This parameter specifies the name of a file containing SSL
-        certificate authority (<acronym>CA</acronym>) certificate(s).
-        If the file exists, the server's certificate will be verified
-        to be signed by one of these authorities.  The default is
-        <filename>~/.postgresql/root.crt</filename>.
+        This parameter specifies the name of SSL certificate authority
+        (<acronym>CA</acronym>) certificate(s).
+        <itemizedlist>
+         <listitem>
+          <para>
+           <productname>OpenSSL</productname>: specifies the name of a file
+           containing SSL certificate authority (<acronym>CA</acronym>)
+           certificate(s).  If the file exists, the server's certificate will
+           be verified to be signed by one of these authorities.  The default is
+           <filename>~/.postgresql/root.crt</filename>.
+          </para>
+         </listitem>
+
+         <listitem>
+          <para>
+           <productname>NSS</productname>: this parameter has no effect.  CA
+           certificates should be loaded into the <productname>NSS</productname>
+           database using the <application>certutil</application> tool.
+          </para>
+         </listitem>
+        </itemizedlist>
        </para>
       </listitem>
      </varlistentry>
@@ -1743,13 +1876,29 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
       <listitem>
        <para>
         This parameter specifies the file name of the SSL certificate
-        revocation list (CRL).  Certificates listed in this file, if it
-        exists, will be rejected while attempting to authenticate the
-        server's certificate.  If neither
-        <xref linkend='libpq-connect-sslcrl'/> nor
-        <xref linkend='libpq-connect-sslcrldir'/> is set, this setting is
-        taken as
-        <filename>~/.postgresql/root.crl</filename>.
+        revocation list (CRL).  
+
+        <itemizedlist>
+         <listitem>
+          <para>
+           <productname>OpenSSL</productname>: Certificates listed in this file,
+           if it exists, will be rejected while attempting to authenticate the
+           server's certificate.  If neither
+           <xref linkend='libpq-connect-sslcrl'/> nor
+           <xref linkend='libpq-connect-sslcrldir'/> is set, this setting is
+           taken as <filename>~/.postgresql/root.crl</filename>. 
+          </para>
+         </listitem>
+
+         <listitem>
+          <para>
+           <productname>NSS</productname>: This parameter has no effect.  CRL
+           files should be loaded into the <productname>NSS</productname>
+           database using the <application>crlutil</application> tool.
+          </para>
+         </listitem>
+        </itemizedlist>
+
        </para>
       </listitem>
      </varlistentry>
@@ -1762,18 +1911,30 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
         revocation list (CRL).  Certificates listed in the files in this
         directory, if it exists, will be rejected while attempting to
         authenticate the server's certificate.
+
+        <itemizedlist>
+         <listitem>
+          <para>
+           <productname>OpenSSL</productname>: the directory needs to be
+           prepared with the OpenSSL command <literal>openssl rehash</literal>
+           or <literal>c_rehash</literal>.  See its documentation for details.
+          </para>
+          <para>
+           Both <literal>sslcrl</literal> and <literal>sslcrldir</literal> can
+           be specified together.
+          </para>
+         </listitem>
+
+         <listitem>
+          <para>
+           <productname>NSS</productname>: This parameter has no effect.  CRL
+           files should be loaded into the <productname>NSS</productname>
+           database using the <application>crlutil</application> tool.
+          </para>
+         </listitem>
+        </itemizedlist>
        </para>
 
-       <para>
-        The directory needs to be prepared with the OpenSSL command
-        <literal>openssl rehash</literal> or <literal>c_rehash</literal>.  See
-        its documentation for details.
-       </para>
-
-       <para>
-        Both <literal>sslcrl</literal> and <literal>sslcrldir</literal> can be
-        specified together.
-       </para>
       </listitem>
      </varlistentry>
 
@@ -1808,8 +1969,8 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
         for the connection. Valid values are <literal>TLSv1</literal>,
         <literal>TLSv1.1</literal>, <literal>TLSv1.2</literal> and
         <literal>TLSv1.3</literal>. The supported protocols depend on the
-        version of <productname>OpenSSL</productname> used, older versions
-        not supporting the most modern protocol versions. If not specified,
+        version of the SSL library used, older versions may 
+        not support the most modern protocol versions. If not specified,
         the default is <literal>TLSv1.2</literal>, which satisfies industry
         best practices as of this writing.
        </para>
@@ -1824,8 +1985,8 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
         for the connection. Valid values are <literal>TLSv1</literal>,
         <literal>TLSv1.1</literal>, <literal>TLSv1.2</literal> and
         <literal>TLSv1.3</literal>. The supported protocols depend on the
-        version of <productname>OpenSSL</productname> used, older versions
-        not supporting the most modern protocol versions. If not set, this
+        version of the SSL library used, older versions
+        may not support the most modern protocol versions. If not set, this
         parameter is ignored and the connection will use the maximum bound
         defined by the backend, if set. Setting the maximum protocol version
         is mainly useful for testing or if some component has issues working
@@ -2587,6 +2748,8 @@ void *PQsslStruct(const PGconn *conn, const char *struct_name);
       </para>
       <para>
        The struct(s) available depend on the SSL implementation in use.
+      </para>
+      <para>
        For <productname>OpenSSL</productname>, there is one struct,
        available under the name "OpenSSL", and it returns a pointer to the
        <productname>OpenSSL</productname> <literal>SSL</literal> struct.
@@ -2610,9 +2773,15 @@ void *PQsslStruct(const PGconn *conn, const char *struct_name);
 ]]></programlisting>
       </para>
       <para>
-       This structure can be used to verify encryption levels, check server
-       certificates, and more. Refer to the <productname>OpenSSL</productname>
-       documentation for information about this structure.
+       For <productname>NSS</productname>, there is one struct available under
+       the name "NSS", and it returns a pointer to the
+       <productname>NSS</productname> <acronym>SSL</acronym>
+       <literal>PRFileDesc</literal> associated with the connection.
+      </para>
+      <para>
+       These structures can be used to verify encryption levels, check server
+       certificates, and more. Refer to the <acronym>SSL</acronym> library
+       documentation for information about these structures.
       </para>
      </listitem>
     </varlistentry>
@@ -2639,6 +2808,10 @@ void *PQgetssl(const PGconn *conn);
        <xref linkend="libpq-PQsslInUse"/> instead, and for more details about the
        connection, use <xref linkend="libpq-PQsslAttribute"/>.
       </para>
+      <para>
+       This function returns <literal>NULL</literal> when <acronym>SSL</acronym>
+       librariaes other than <productname>OpenSSL</productname> are used.
+      </para>
      </listitem>
     </varlistentry>
 
@@ -8600,6 +8773,11 @@ void PQinitOpenSSL(int do_ssl, int do_crypto);
 
@@ -8626,6 +8804,11 @@ void PQinitSSL(int do_ssl);
index 001d195b8e..89df316a68 100644

   <para>
 
   <sect2 id="ssl-setup">
 
   <para>

 
 
    <para>
 
+     <row>

    <para>
 
+    Then load the server key, which requires converting it to
+  <sect2 id="nss-ssl-certificate-creation">
+    <application>certutil</application> with the <literal>-f</literal> parameter.
 
  <sect1 id="gssapi-enc">
-- 
2.31.0

From 4274778a9b4a9eaecbd3efec34442fbaff786a59 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:45 +0100
Subject: [PATCH v35 6/9] nss: Support NSS in pgcrypto

This extends pgcrypto to be able to use libnss as a cryptographic
backend for pgcrypto much like how OpenSSL is a supported backend.
Blowfish is not a supported cipher in NSS, so the implementation
falls back on the built-in BF code to be compatible in terms of
cipher support.
---
 doc/src/sgml/pgcrypto.sgml |  55 ++-
 contrib/pgcrypto/Makefile  |   7 +-
 contrib/pgcrypto/nss.c     | 753 +++++++++++++++++++++++++++++++++++++
 3 files changed, 798 insertions(+), 17 deletions(-)
 create mode 100644 contrib/pgcrypto/nss.c

index b6bb23de0f..7d40b6009b 100644
 
    <para>
 
    <para>
 
-   <table id="pgcrypto-with-without-openssl">
-    <title>Summary of Functionality with and without OpenSSL</title>
-    <tgroup cols="3">
+   <table id="pgcrypto-with-without-openssl-nss">
+    <title>Summary of Functionality with and without external cryptographic
+      library</title>
+    <tgroup cols="4">
      <thead>
       <row>
        <entry>Functionality</entry>
        <entry>Built-in</entry>
        <entry>With OpenSSL</entry>
+       <entry>With NSS</entry>
       </row>
      </thead>
      <tbody>
@@ -1184,51 +1187,67 @@ gen_random_uuid() returns uuid
        <entry>MD5</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>SHA1</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>SHA224/256/384/512</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>Other digest algorithms</entry>
        <entry>no</entry>
        <entry>yes (Note 1)</entry>
+       <entry>yes (Note 1)</entry>
       </row>
       <row>
        <entry>Blowfish</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes (Note 2)</entry>
       </row>
       <row>
        <entry>AES</entry>
        <entry>yes</entry>
        <entry>yes</entry>
-      </row>
-      <row>
-       <entry>DES/3DES/CAST5</entry>
-       <entry>no</entry>
        <entry>yes</entry>
       </row>
+      <row>
+       <entry>DES/3DES</entry>
+       <entry>no</entry>
+       <entry>yes</entry>
+       <entry>yes</entry>
+      </row>
+      <row>
+       <entry>CAST5</entry>
+       <entry>no</entry>
+       <entry>yes</entry>
+       <entry>no</entry>
+      </row>
       <row>
        <entry>Raw encryption</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>PGP Symmetric encryption</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
       <row>
        <entry>PGP Public-Key encryption</entry>
        <entry>yes</entry>
        <entry>yes</entry>
+       <entry>yes</entry>
       </row>
      </tbody>
     </tgroup>
@@ -1241,12 +1260,18 @@ gen_random_uuid() returns uuid
    <orderedlist>
     <listitem>
      <para>
-      Any digest algorithm <productname>OpenSSL</productname> supports
-      is automatically picked up.
-      This is not possible with ciphers, which need to be supported
+      Any digest algorithm included with the library that
+      <productname>PostgreSQL</productname> is compiled with is automatically
+      picked up. This is not possible with ciphers, which need to be supported
       explicitly.
      </para>
     </listitem>
+    <listitem>
+     <para>
+      Blowfish is not supported by <productname>NSS</productname>, the
+      built-in implementation is used as a fallback.
+     </para>
+    </listitem>
    </orderedlist>
   </sect3>

 
 
 SRCS = \
index 0000000000..d4fd4680ec
@@ -0,0 +1,753 @@
+ * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
+#include "common/nss.h"
2.31.0

From e70018382ae097cfb8313fd9514ccb036d10f54e Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:48 +0100
Subject: [PATCH v35 7/9] nss: Support NSS in sslinfo

Since sslinfo to a large extent uses the be_tls_* API this mostly
disables functionality which currently is OpenSSL specific.
---
 doc/src/sgml/sslinfo.sgml | 12 +++++++++++-
 contrib/sslinfo/sslinfo.c | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 43 insertions(+), 1 deletion(-)

  <para>
 
  <sect2>

 
 #include "postgres.h"
 
+#ifdef USE_OPENSSL

 PG_MODULE_MAGIC;
 
+#ifdef USE_OPENSSL

 /*

+#ifdef USE_OPENSSL
 /*
 
+#ifdef USE_NSS
 
 /*

+#ifdef USE_OPENSSL
 /*
2.31.0

From 18f43ccdd24742c9da382a298accc8c4a4bec3d1 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:51 +0100
Subject: [PATCH v35 8/9] nss: Support NSS in cryptohash

This adds support for using libnss as a crypto backend for the built-
in cryptohash support. Much of this code is similar to the pgcrypto
support.
---
 src/common/cryptohash_nss.c | 264 ++++++++++++++++++++++++++++++++++++
 1 file changed, 264 insertions(+)
 create mode 100644 src/common/cryptohash_nss.c

index 0000000000..59ba9c1697
@@ -0,0 +1,264 @@
+ * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
+#include "common/nss.h"
+pg_cryptohash_final(pg_cryptohash_ctx *ctx, uint8 *dest, size_t len)
+	switch (ctx->type)
+			if (len < MD5_LENGTH)
+			if (len < SHA1_LENGTH)
+			if (len < SHA224_LENGTH)
+			if (len < SHA256_LENGTH)
+			if (len < SHA384_LENGTH)
+			if (len < SHA512_LENGTH)
+	status = PK11_DigestFinal(ctx->pk11_context, dest, &outlen, len);
2.31.0

From a11b265a057effeac31f666e0b1e2ac9f697050e Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:55 +0100
Subject: [PATCH v35 9/9] nss: Build infrastructure

Finally this adds the infrastructure to build a postgres installation
with libnss support.
---
 src/include/pg_config.h.in    |  12 ++
 src/backend/libpq/Makefile    |   4 +
 src/common/Makefile           |   8 +
 src/interfaces/libpq/Makefile |   5 +
 configure                     | 294 +++++++++++++++++++++++++++++++++-
 configure.ac                  |  31 +++-
 src/tools/msvc/Install.pm     |   3 +-
 src/tools/msvc/Mkvcbuild.pm   |  40 ++++-
 src/tools/msvc/Solution.pm    |  26 +++
 9 files changed, 411 insertions(+), 12 deletions(-)

diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index 783b8fc1ba..74b7d525eb 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -331,6 +331,12 @@
 /* Define to 1 if you have the `m' library (-lm). */
 #undef HAVE_LIBM
 
+/* Define to 1 if you have the `nspr4' library (-lnspr4). */
+#undef HAVE_LIBNSPR4
+
+/* Define to 1 if you have the `nss3' library (-lnss3). */
+#undef HAVE_LIBNSS3
+
 /* Define to 1 if you have the `pam' library (-lpam). */
 #undef HAVE_LIBPAM
 
@@ -343,6 +349,9 @@
 /* Define to 1 if you have the `ssl' library (-lssl). */
 #undef HAVE_LIBSSL
 
+/* Define to 1 if you have the `ssl3' library (-lssl3). */
+#undef HAVE_LIBSSL3
+
 /* Define to 1 if you have the `wldap32' library (-lwldap32). */
 #undef HAVE_LIBWLDAP32
 
@@ -920,6 +929,9 @@
 
+/* Define to 1 if you have NSS support, */
+#undef USE_NSS
+
 /* Define to 1 to build with OpenSSL support. (--with-ssl=openssl) */
 #undef USE_OPENSSL

 
 ifeq ($(with_gssapi),yes)
diff --git a/src/common/Makefile b/src/common/Makefile
index 38a8599337..3157d057bf 100644
--- a/src/common/Makefile
+++ b/src/common/Makefile
@@ -86,6 +86,13 @@ OBJS_COMMON += \
 	cryptohash_openssl.o \
 	hmac_openssl.o
 else
+ifeq ($(with_ssl),nss)
+OBJS_COMMON += \
+	hmac.o \
+	cipher_nss.o \
+	protocol_nss.o \
+	cryptohash_nss.o
+else
 OBJS_COMMON += \
 	cryptohash.o \
 	hmac.o \
@@ -93,6 +100,7 @@ OBJS_COMMON += \
 	sha1.o \
 	sha2.o
 endif
+endif
 
index 0c4e55b6ad..4d90235ab2 100644
 
+ifeq ($(with_ssl), nss)
+OBJS += \
+	fe-secure-nss.o
+endif
+
 ifeq ($(with_gssapi),yes)
 OBJS += \
 	fe-gssapi-common.o \
diff --git a/configure b/configure
index 70f4555264..6b823ecdcd 100755
--- a/configure
+++ b/configure
@@ -654,6 +654,8 @@ UUID_LIBS
 LDAP_LIBS_BE
 LDAP_LIBS_FE
 with_ssl
+NSPR_CONFIG
+NSS_CONFIG
 PTHREAD_CFLAGS
 PTHREAD_LIBS
 PTHREAD_CC
@@ -1577,7 +1579,7 @@ Optional Packages:
   --without-zlib          do not use Zlib
   --with-lz4              build with LZ4 support
   --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
-  --with-ssl=LIB          use LIB for SSL/TLS support (openssl)
+  --with-ssl=LIB          use LIB for SSL/TLS support (openssl, nss)
   --with-openssl          obsolete spelling of --with-ssl=openssl
 
 Some influential environment variables:
@@ -12671,8 +12673,274 @@ done

@@ -13645,6 +13913,23 @@ else
 fi

@@ -18424,6 +18709,9 @@ $as_echo_n "checking which random number source to use... " >&6; }
@@ -18453,7 +18741,7 @@ fi
 
index ba67c95bcc..8c75c42e12 100644
@@ -1230,7 +1230,7 @@ fi
@@ -1264,8 +1264,28 @@ if test "$with_ssl" = openssl ; then
   AC_DEFINE([USE_OPENSSL], 1, [Define to 1 to build with OpenSSL support. (--with-ssl=openssl)])
 
@@ -1451,6 +1471,9 @@ fi
 
@@ -2212,6 +2235,8 @@ fi
@@ -2221,7 +2246,7 @@ else
 
diff --git a/src/tools/msvc/Install.pm b/src/tools/msvc/Install.pm
index ffcd0e5095..e7fab94f6d 100644
--- a/src/tools/msvc/Install.pm
+++ b/src/tools/msvc/Install.pm
@@ -438,7 +438,8 @@ sub CopyContribFiles
 		{
 			# These configuration-based exclusions must match vcregress.pl
 			next if ($d eq "uuid-ossp"  && !defined($config->{uuid}));
-			next if ($d eq "sslinfo"    && !defined($config->{openssl}));
+			next if ($d eq "sslinfo"    && !defined($config->{openssl})
+			  && !defined($config->{nss}));
 			next if ($d eq "xml2"       && !defined($config->{xml}));
 			next if ($d =~ /_plperl$/   && !defined($config->{perl}));
 			next if ($d =~ /_plpython$/ && !defined($config->{python}));
diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm
index 58a99e4f10..e436d800d6 100644
--- a/src/tools/msvc/Mkvcbuild.pm
+++ b/src/tools/msvc/Mkvcbuild.pm
@@ -135,6 +135,12 @@ sub mkvcbuild
 		push(@pgcommonallfiles, 'hmac_openssl.c');
 		push(@pgcommonallfiles, 'protocol_openssl.c');
 	}
+	elsif ($solution->{options}->{nss})
+	{
+		push(@pgcommonallfiles, 'cryptohash_nss.c');
+		push(@pgcommonallfiles, 'cipher_nss.c');
+		push(@pgcommonallfiles, 'protocol_nss.c');
+	}
 	else
 	{
 		push(@pgcommonallfiles, 'cryptohash.c');
@@ -200,12 +206,19 @@ sub mkvcbuild
 	$postgres->FullExportDLL('postgres.lib');
 
@@ -263,12 +276,19 @@ sub mkvcbuild
 
@@ -436,9 +456,14 @@ sub mkvcbuild

 	if (!$solution->{options}->{uuid})
@@ -468,6 +493,11 @@ sub mkvcbuild
 		$pgcrypto->AddFiles('contrib/pgcrypto', 'openssl.c',
 			'pgp-mpi-openssl.c');
 	}
+	elsif ($solution->{options}->{nss})
+	{
+		$pgcrypto->AddFiles('contrib/pgcrypto', 'nss.c',
+			'pgp-mpi-internal.c', 'imath.c', 'blf.c');
+	}
 	else
 	{
 		$pgcrypto->AddFiles(
diff --git a/src/tools/msvc/Solution.pm b/src/tools/msvc/Solution.pm
index d2bc7abef0..846f0e8b76 100644
--- a/src/tools/msvc/Solution.pm
+++ b/src/tools/msvc/Solution.pm
@@ -302,10 +302,13 @@ sub GenerateFiles
 		HAVE_LIBLDAP_R                              => undef,
 		HAVE_LIBLZ4                                 => undef,
 		HAVE_LIBM                                   => undef,
+		HAVE_LIBNSPR4								=> undef,
+		HAVE_LIBNSS3								=> undef,
 		HAVE_LIBPAM                                 => undef,
 		HAVE_LIBREADLINE                            => undef,
 		HAVE_LIBSELINUX                             => undef,
 		HAVE_LIBSSL                                 => undef,
+		HAVE_LIBSSL3								=> undef,
 		HAVE_LIBWLDAP32                             => undef,
 		HAVE_LIBXML2                                => undef,
 		HAVE_LIBXSLT                                => undef,
@@ -495,6 +498,7 @@ sub GenerateFiles
 		USE_LLVM                   => undef,
 		USE_NAMED_POSIX_SEMAPHORES => undef,
 		USE_OPENSSL                => undef,
+		USE_NSS                    => undef,
 		USE_PAM                    => undef,
 		USE_SLICING_BY_8_CRC32C    => undef,
 		USE_SSE42_CRC32C           => undef,
@@ -549,6 +553,13 @@ sub GenerateFiles
 			$define{HAVE_OPENSSL_INIT_SSL}      = 1;
 		}
 	}
+	if ($self->{options}->{nss})
+	{
+		$define{USE_NSS} = 1;
+		$define{HAVE_LIBNSPR4} = 1;
+		$define{HAVE_LIBNSS3} = 1;
+		$define{HAVE_LIBSSL3} = 1;
+	}
 
@@ -1007,6 +1018,21 @@ sub AddProject
2.31.0

---

From: Michael Paquier <[email-masked]>
Date: Thu, 8 Apr 2021 17:10:43 +0900

> issue with the DN mapping part.

For now, I have marked this patch set as returned with feedback as it
is still premature for integration, and there are still bugs in it.
FWIW, I think that there is a future for providing an alternative to
OpenSSL, so, even if it could not make it for this release, I'd like
to push forward with this area more seriously as of 15.  The recent
libcrypto-related refactorings were one step in this direction, as
well.
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 27 May 2021 22:31:07 +0200

> On 25 Mar 2021, at 00:56, Jacob Champion <[email-masked]> wrote:

> Databases that are opened *after* the first one are given their own separate slots. Any certificates that are part of those databases seemingly can't be referenced directly by nickname. They have t…

Sorry for the latency is responding, but I'm now back from parental leave.

AFAICT the tokenname for the database can be set with the dbTokenDescription
member in the NSSInitParameters struct passed to NSS_InitContext() (documented
in nss.h).  Using this we can avoid the messier SECMOD machinery and use the
token in the auth callback to refer to the database we loaded.  I hacked this
up in my local tree (rebased patchset coming soon) and it seems to work as
intended.

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 28 May 2021 11:04:12 +0200

Attached is a rebase to keep bitrot at bay.  On top rebasing and smaller fixes
in comments etc, this version fixes/adds a number things:

* Performs DN resolution to support the DN mapping
* Locks the SECMOD parts and PR_Init call in the frontend as per Jacobs
  findings upthread
* Properly set the tokenname of the database to avoid ambigious lookups in case
  multiple databases are loaded (a better name to ensure uniqueness is a TODO)
* Adds a test for certificate lookup without sslcert set

---

From: Jeff Davis <[email-masked]>
Date: Thu, 03 Jun 2021 10:37:26 -0700

> Maybe we should just have --with-ssl={openssl,nss}? That'd avoid

[ apologies for the late reply ]

Would it be more proper to call it --with-tls={openssl,nss} ?

Regards,
	Jeff Davis

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 3 Jun 2021 19:47:45 +0200

> On 3 Jun 2021, at 19:37, Jeff Davis <[email-masked]> wrote:
> 

Well, we use SSL for everything else (GUCs, connection params and env vars etc)
so I think --with-ssl is sensible.

However, SSL and TLS are used quite interchangeably these days so I think it
makes sense to provide --with-tls as an alias.

---

From: Andrew Dunstan <[email-masked]>
Date: Thu, 3 Jun 2021 15:53:59 -0400

> makes sense to provide --with-tls as an alias.

Yeah, but it's annoying to have to start every talk I give touching this
subject with the slide that says "When we say SSL we really means TLS".
Maybe release 15 would be a good time to rename user-visible option
names etc, with support for legacy names.

cheers

andrew

--
Andrew Dunstan
EDB: https://www.enterprisedb.com

---

From: Jeff Davis <[email-masked]>
Date: Thu, 03 Jun 2021 13:14:15 -0700

> names etc, with support for legacy names.

Sounds good to me, though I haven't looked into how big of a diff that
will be.

Also, do we have precedent for GUC aliases? That might be a little
weird.

Regards,
	Jeff Davis

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 3 Jun 2021 22:49:02 +0200

> On 3 Jun 2021, at 22:14, Jeff Davis <[email-masked]> wrote:
> 

Perhaps.  Having spent some time in this space, SSL has IMHO become the de
facto term for an encrypted connection at the socket layer, with TLS being the
current protocol suite (additionally, often referred to SSL/TLS).  Offering
tls* counterparts to our ssl GUCs etc will offer a level of correctness but I
doubt we'll ever get rid of ssl* so we might not help too many users by the
added complexity.

It might also put us a hard spot if the next TLS spec ends up being called
something other than TLS?  It's clearly happened before =)

> Also, do we have precedent for GUC aliases? That might be a little

I don't think we do currently, but I have a feeling the topic has surfaced here
before.

If we end up settling on this being something we want I can volunteer to do the
legwork, but it seems a discussion best had before a patch is drafted.

---

From: Tom Lane <[email-masked]>
Date: Thu, 03 Jun 2021 16:55:45 -0400

> something other than TLS?  It's clearly happened before =)

Good point.  I'm inclined to just stick with the SSL terminology.

> I don't think we do currently, but I have a feeling the topic has surfaced here

We do, look for "sort_mem" in guc.c.  So it's not like it'd be
inconvenient to implement.  But I think user confusion and the
potential for the new terminology to fail to be any more
future-proof are good reasons to just leave the names alone.

			regards, tom lane

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 3 Jun 2021 22:58:17 +0200

> On 3 Jun 2021, at 22:55, Tom Lane <[email-masked]> wrote:

> We do, look for "sort_mem" in guc.c.

I knew it seemed familiar but I failed to find it, thanks for the pointer.

---

From: Bruce Momjian <[email-masked]>
Date: Thu, 3 Jun 2021 17:06:42 -0400

> Good point.  I'm inclined to just stick with the SSL terminology.

I wonder if we should use SSL/TLS in more places in our documentation.

-- 
  Bruce Momjian  <[email-masked]>        https://momjian.us
  EDB                                      https://enterprisedb.com

  If only the physical world exists, free will is an illusion.

---

From: Tom Lane <[email-masked]>
Date: Thu, 03 Jun 2021 17:11:41 -0400

> I wonder if we should use SSL/TLS in more places in our documentation.

No objection to doing that in the docs; I'm just questioning
switching the code-visible names.

			regards, tom lane

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 3 Jun 2021 23:13:50 +0200

> On 3 Jun 2021, at 23:11, Tom Lane <[email-masked]> wrote:
> 

As long as it's still searchable by "SSL", "TLS" and "SSL/TLS" and not just the
latter.

---

From: Magnus Hagander <[email-masked]>
Date: Fri, 4 Jun 2021 19:44:12 +0200

> > switching the code-visible names.

+1.

I also don't think it's worth changing the actual names, I think
that'll cause more problems than it solves. But we can, and probably
should, change the messaging around it, particularly the docs (but
probably also comments in the config file).

> As long as it's still searchable by "SSL", "TLS" and "SSL/TLS" and not just the

Agreed, making it searchable and easily cross-linkable.. And maybe
both terms should be in the glossary.

-- 
 Magnus Hagander
 Me: https://www.hagander.net/
 Work: https://www.redpill-linpro.com/

---

From: Jacob Champion <[email-masked]>
Date: Mon, 14 Jun 2021 22:15:47 +0000

On Fri, 2021-05-28 at 11:04 +0200, Daniel Gustafsson wrote:
> Attached is a rebase to keep bitrot at bay.

I get a failure during one of the CRL directory tests due to a missing
database -- it looks like the Makefile is missing an entry. (I'm
dusting off my build after a few months away, so I don't know if this
latest rebase introduced it or not.)

Attached is a quick patch; does it work on your machine?

--Jacob
From 7a7b8904ef22212190bb988fab1ef696fe1a59de Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Mon, 14 Jun 2021 15:04:26 -0700
Subject: [PATCH] test/ssl: fix NSS server-side CRL test

Make sure the database is created during `make nssfiles`, and expect a
revocation failure message.
---
 src/test/ssl/Makefile          | 2 ++
 src/test/ssl/t/001_ssltests.pl | 2 +-
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/src/test/ssl/Makefile b/src/test/ssl/Makefile
index 14ca1f8bf3..557cbe223f 100644
--- a/src/test/ssl/Makefile
+++ b/src/test/ssl/Makefile
@@ -45,6 +45,7 @@ NSSFILES := ssl/nss/client_ca.crt.db \
 	ssl/nss/client-revoked.crt__client-revoked.key.db \
 	ssl/nss/server-cn-only.crt__server-password.key.db \
 	ssl/nss/server-cn-only.crt__server-cn-only.key.db \
+	ssl/nss/server-cn-only.crt__server-cn-only.key.crldir.db \
 	ssl/nss/root.crl \
 	ssl/nss/server.crl \
 	ssl/nss/client.crl \
@@ -167,6 +168,7 @@ ssl/nss/server-cn-only.crt__server-cn-only.key.db: ssl/server-cn-only.crt ssl/se
 	pk12util -i ssl/nss/server-cn-only.pfx -d "sql:$@" -W ''
 
 ssl/nss/server-cn-only.crt__server-cn-only.key.crldir.db: ssl/nss/server-cn-only.crt__server-cn-only.key.db
+	cp -R $< $@
 	for c in $(shell ls ssl/root+client-crldir) ; do \
 		echo $${c} ; \
 		openssl crl -in ssl/root+client-crldir/$${c} -outform der -out ssl/nss/$${c} ; \
diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl
index 4105a67b94..aec99e7bf6 100644
--- a/src/test/ssl/t/001_ssltests.pl
+++ b/src/test/ssl/t/001_ssltests.pl
@@ -664,7 +664,7 @@ $node->connect_fails(
 	"$common_connstr user=ssltestuser sslcert=ssl/client-revoked.crt sslkey=ssl/client-revoked_tmp.key ssldatabase=ssl/nss/client-revoked.crt__client-revoked.key.db",
 	"certificate authorization fails with revoked client cert with server-side CRL directory",
 	expected_stderr =>
-	  qr/SSL error: sslv3 alert certificate revoked|SSL error: Encountered end of file/);
+	  qr/SSL error: sslv3 alert certificate revoked|SSL peer rejected your certificate as revoked/);
 
 # clean up
 
-- 
2.25.1

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 16 Jun 2021 00:08:58 +0200

> On 15 Jun 2021, at 00:15, Jacob Champion <[email-masked]> wrote:

> Attached is a quick patch; does it work on your machine?

It does, thanks!  I've included it in the attached v37 along with a few tiny
non-functional improvements in comment spelling etc.

---

From: Jacob Champion <[email-masked]>
Date: Tue, 15 Jun 2021 23:50:14 +0000

Great, thanks!

I've been tracking down reference leaks in the client. These open
references prevent NSS from shutting down cleanly, which then makes it
impossible to open a new context in the future. This probably affects
other libpq clients more than it affects psql.

The first step to fixing that is not ignoring failures during NSS
shutdown, so I've tried a patch to pgtls_close() that pushes any
failures through the pqInternalNotice(). That seems to be working well.
The tests were still mostly green, so I taught connect_ok() to fail if
any stderr showed up, and that exposed quite a few failures.

I am currently stuck on one last failing test. This leak seems to only
show up when using TLSv1.2 or below. There doesn't seem to be a
substantial difference in libpq code coverage between 1.2 and 1.3, so
I'm worried that either 1) there's some API we use that "requires"
cleanup, but only on 1.2 and below, or 2) there's some bug in my
version of NSS.

Attached are a few work-in-progress patches. I think the reference
cleanups themselves are probably solid, but the rest of it could use
some feedback. Are there better ways to test for this? and can anyone
reproduce the TLSv1.2 leak?

--Jacob
From 6976d15a4be50276ea2f77fd5c37d238493f9447 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Tue, 15 Jun 2021 10:01:14 -0700
Subject: [PATCH 1/3] nss: don't ignore failures during context shutdown

The biggest culprit of a shutdown failure so far seems to be object
leaks. A failure here may prevent future contexts from being created
(and they'll fail in confusing ways), so don't ignore it.

There's not a great way to signal errors from this layer of the stack,
but a notice will at least give us a chance of seeing the problem.
---
 src/interfaces/libpq/fe-secure-nss.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
index 1b9bd4f1a5..90f57e0d99 100644
--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -139,7 +139,16 @@ pgtls_close(PGconn *conn)
 {
 	if (conn->nss_context)
 	{
-		NSS_ShutdownContext(conn->nss_context);
+		SECStatus	status;
+		status = NSS_ShutdownContext(conn->nss_context);
+
+		if (status != SECSuccess)
+		{
+			pqInternalNotice(&conn->noticeHooks,
+							 "unable to shut down NSS context: %s",
+							 pg_SSLerrmessage(PR_GetError()));
+		}
+
 		conn->nss_context = NULL;
 	}
 }
-- 
2.25.1

From acabc4d51d38124db748a6be9dca0ff83693e039 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Tue, 15 Jun 2021 14:37:28 -0700
Subject: [PATCH 2/3] test: check for empty stderr during connect_ok()

...in a similar manner to command_like(), to catch notices-as-errors
coming from NSS.
---
 src/test/authentication/t/001_password.pl | 2 +-
 src/test/authentication/t/002_saslprep.pl | 2 +-
 src/test/kerberos/t/001_auth.pl           | 2 +-
 src/test/ldap/t/001_auth.pl               | 2 +-
 src/test/perl/PostgresNode.pm             | 5 ++++-
 src/test/ssl/t/001_ssltests.pl            | 4 ++--
 src/test/ssl/t/002_scram.pl               | 4 ++--
 7 files changed, 12 insertions(+), 9 deletions(-)

diff --git a/src/test/authentication/t/001_password.pl b/src/test/authentication/t/001_password.pl
index 427a360198..327dfb4ed9 100644
--- a/src/test/authentication/t/001_password.pl
+++ b/src/test/authentication/t/001_password.pl
@@ -20,7 +20,7 @@ if (!$use_unix_sockets)
 }
 else
 {
-	plan tests => 23;
+	plan tests => 32;
 }

diff --git a/src/test/authentication/t/002_saslprep.pl b/src/test/authentication/t/002_saslprep.pl
index f080a0ccba..d6508df8bd 100644
--- a/src/test/authentication/t/002_saslprep.pl
+++ b/src/test/authentication/t/002_saslprep.pl
@@ -17,7 +17,7 @@ if (!$use_unix_sockets)
 }
 else
 {
-	plan tests => 12;
+	plan tests => 20;
 }
 
 # Delete pg_hba.conf from the given node, add a new entry to it
diff --git a/src/test/kerberos/t/001_auth.pl b/src/test/kerberos/t/001_auth.pl
index b5594924ca..62015339a0 100644
--- a/src/test/kerberos/t/001_auth.pl
+++ b/src/test/kerberos/t/001_auth.pl
@@ -23,7 +23,7 @@ use Time::HiRes qw(usleep);
 
 if ($ENV{with_gssapi} eq 'yes')
 {
-	plan tests => 44;
+	plan tests => 54;
 }
 else
 {
diff --git a/src/test/ldap/t/001_auth.pl b/src/test/ldap/t/001_auth.pl
index 0ae14e4c85..e857c26258 100644
--- a/src/test/ldap/t/001_auth.pl
+++ b/src/test/ldap/t/001_auth.pl
@@ -9,7 +9,7 @@ use Test::More;
 
 if ($ENV{with_ldap} eq 'yes')
 {
-	plan tests => 28;
+	plan tests => 40;
 }
 else
 {
diff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm
index 2027cbf43d..4a1e151d7e 100644
--- a/src/test/perl/PostgresNode.pm
+++ b/src/test/perl/PostgresNode.pm
@@ -2018,8 +2018,11 @@ sub connect_ok
 
 	if (defined($params{expected_stdout}))
 	{
-		like($stdout, $params{expected_stdout}, "$test_name: matches");
+		like($stdout, $params{expected_stdout}, "$test_name: stdout matches");
 	}
+
+	is($stderr, "", "$test_name: no stderr");
+
 	if (@log_like or @log_unlike)
 	{
 		my $log_contents = TestLib::slurp_file($self->logfile, $log_location);
diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl
index aec99e7bf6..c80abc9ec9 100644
--- a/src/test/ssl/t/001_ssltests.pl
+++ b/src/test/ssl/t/001_ssltests.pl
@@ -18,12 +18,12 @@ my $nss;
 if ($ENV{with_ssl} eq 'openssl')
 {
 	$openssl = 1;
-	plan tests => 112;
+	plan tests => 144;
 }
 elsif ($ENV{with_ssl} eq 'nss')
 {
 	$nss = 1;
-	plan tests => 112;
+	plan tests => 138;
 }
 else
 {
diff --git a/src/test/ssl/t/002_scram.pl b/src/test/ssl/t/002_scram.pl
index adfdc55e1a..7976b2e5b1 100644
--- a/src/test/ssl/t/002_scram.pl
+++ b/src/test/ssl/t/002_scram.pl
@@ -27,13 +27,13 @@ if ($ENV{with_ssl} eq 'openssl')
 	# Determine whether build supports tls-server-end-point.
 	$supports_tls_server_end_point =
 		check_pg_config("#define HAVE_X509_GET_SIGNATURE_NID 1");
-	plan tests => $supports_tls_server_end_point ? 11 : 12;
+	plan tests => 15;
 }
 elsif ($ENV{with_ssl} eq 'nss')
 {
 	$nss = 1;
 	$supports_tls_server_end_point = 1;
-	plan tests => 11;
+	plan tests => 15;
 }
 else
 {
-- 
2.25.1

From 3141b29053a4b48289ebb7ee26d22e395c07ff31 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Tue, 15 Jun 2021 15:59:39 -0700
Subject: [PATCH 3/3] nss: clean up leaked resources

The NSPR file descriptor and a handful of certificate references were
preventing NSS from shutting down.

At least one leak is still on the loose, when forcing TLSv1.2 or lower
during client connections:

    $ psql 'host=localhost sslmode=require ssl_max_protocol_version=TLSv1.2'
    psql (14beta1)
    SSL connection (protocol: TLSv1.2, cipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, bits: 128, compression: off)
    Type "help" for help.

    postgres=# \q
    unable to shut down NSS context: NSS could not shutdown. Objects are still in use.
---
 src/interfaces/libpq/fe-secure-nss.c | 37 ++++++++++++++++++++++------
 1 file changed, 30 insertions(+), 7 deletions(-)

diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
index 90f57e0d99..7b92e89ecd 100644
--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -137,6 +137,22 @@ pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)
 void
 pgtls_close(PGconn *conn)
 {
+	/* All NSS references must be cleaned up before we close out the context. */
+	if (conn->pr_fd)
+	{
+		PRStatus	status;
+
+		status = PR_Close(conn->pr_fd);
+		if (status != PR_SUCCESS)
+		{
+			pqInternalNotice(&conn->noticeHooks,
+							 "unable to close NSPR fd: %s",
+							 pg_SSLerrmessage(PR_GetError()));
+		}
+
+		conn->pr_fd = NULL;
+	}
+
 	if (conn->nss_context)
 	{
 		SECStatus	status;
@@ -573,16 +589,16 @@ pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
 	SECOidTag	signature_tag;
 	SECOidTag	digest_alg;
 	int			digest_len;
-	PLArenaPool *arena;
+	PLArenaPool *arena = NULL;
 	SECItem		digest;
-	char	   *ret;
+	char	   *ret = NULL;
 	SECStatus	status;
 
 	*len = 0;
 
 	server_cert = SSL_PeerCertificate(conn->pr_fd);
 	if (!server_cert)
-		return NULL;
+		goto cleanup;
 
 	signature_tag = SECOID_GetAlgorithmTag(&server_cert->signature);
 	if (!pg_find_signature_algorithm(signature_tag, &digest_alg, &digest_len))
@@ -590,7 +606,7 @@ pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
 		printfPQExpBuffer(&conn->errorMessage,
 						  libpq_gettext("could not find digest for OID '%s'\n"),
 						  SECOID_FindOIDTagDescription(signature_tag));
-		return NULL;
+		goto cleanup;
 	}
 
 	arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
@@ -605,14 +621,18 @@ pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
 		printfPQExpBuffer(&conn->errorMessage,
 						  libpq_gettext("unable to generate peer certificate digest: %s"),
 						  pg_SSLerrmessage(PR_GetError()));
-		PORT_FreeArena(arena, PR_TRUE);
-		return NULL;
+		goto cleanup;
 	}
 
 	ret = pg_malloc(digest.len);
 	memcpy(ret, digest.data, digest.len);
 	*len = digest_len;
-	PORT_FreeArena(arena, PR_TRUE);
+
+cleanup:
+	if (arena)
+		PORT_FreeArena(arena, PR_TRUE);
+	if (server_cert)
+		CERT_DestroyCertificate(server_cert);
 
 	return ret;
 }
@@ -712,6 +732,8 @@ done:
 	/* san_list will be freed by freeing the arena it was allocated in */
 	if (arena)
 		PORT_FreeArena(arena, PR_TRUE);
+	if (server_cert)
+		CERT_DestroyCertificate(server_cert);
 	PR_Free(server_hostname);
 
 	if (status == SECSuccess)
@@ -826,6 +848,7 @@ pg_cert_auth_handler(void *arg, PRFileDesc *fd, PRBool checksig, PRBool isServer
 						  pg_SSLerrmessage(PR_GetError()));
 	}

-- 
2.25.1

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 16 Jun 2021 15:31:42 +0200

> On 16 Jun 2021, at 01:50, Jacob Champion <[email-masked]> wrote:

> other libpq clients more than it affects psql.

Ah, nice catch, that's indeed a bug in the frontend implementation.  The
problem is that the NSS trustdomain cache *must* be empty before shutting down
the context, else this very issue happens. Note this in be_tls_destroy():

    /*
     * It reads a bit odd to clear a session cache when we are destroying the
     * context altogether, but if the session cache isn't cleared before
     * shutting down the context it will fail with SEC_ERROR_BUSY.
     */
    SSL_ClearSessionCache();

Calling SSL_ClearSessionCache() in pgtls_close() fixes the error.

There is another resource leak left (visible in one test after the above is
added), the SECMOD module needs to be unloaded in case it's been loaded.
Implementing that with SECMOD_UnloadUserModule trips a segfault in NSS which I
have yet to figure out (when acquiring a lock with NSSRWLock_LockRead).

> failures through the pqInternalNotice(). That seems to be working well.

I'm keeping these in during hacking, with a comment that they need to be
revisited during review since they are mainly useful for debugging.

> any stderr showed up, and that exposed quite a few failures.

With your patches I'm seeing a couple of these:

  SSL error: The one-time function was previously called and failed. Its error code is no longer available

This is an error from NSPR, but it's not clear to me which PR_CallOnce call
it's coming from.  It seems to be hitting in the SAN and CRL tests, so it
smells of some form of caching implemented with NSPR API's to me but thats a
mere hunch.

> show up when using TLSv1.2 or below.

AFAICT the session cache is avoided for TLSv1.3 due to 1.3 not supporting
renegotiation.

---

From: Jacob Champion <[email-masked]>
Date: Wed, 16 Jun 2021 16:15:56 +0000

> Calling SSL_ClearSessionCache() in pgtls_close() fixes the error.

That's unfortunate. The session cache is global, right? So I'm guessing
we'll need to refcount and lock that call, to avoid cleaning up out
from under a thread that's actively using the the cache?

>   SSL error: The one-time function was previously called and failed. Its error code is no longer available

Hmm. Adding SSL_ClearSessionCache() (without thread-safety at the
moment) fixes all of the SSL tests for me, and I don't see either the
SECMOD leak or the "one-time function" error that you've mentioned.
What version of NSS are you running? I'm on 3.63.

I've attached my current patchset (based on v37) for comparison.

> AFAICT the session cache is avoided for TLSv1.3 due to 1.3 not supporting

Nice, at least that mystery is solved. :D

Thanks,
--Jacob

 

 

From 16cad09e1c534391c6aad5c8f552da6a7e6949fd Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Tue, 15 Jun 2021 15:59:39 -0700
Subject: [PATCH 3/3] nss: clean up leaked resources

The NSPR file descriptor, a handful of certificate references, and
session cache entries were preventing NSS from shutting down.
---
 src/interfaces/libpq/fe-secure-nss.c | 44 +++++++++++++++++++++++-----
 1 file changed, 37 insertions(+), 7 deletions(-)

diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
index 90f57e0d99..e9dacdc732 100644
--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -137,9 +137,32 @@ pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)
 void
 pgtls_close(PGconn *conn)
 {
+	/* All NSS references must be cleaned up before we close out the context. */
+	if (conn->pr_fd)
+	{
+		PRStatus	status;
+
+		status = PR_Close(conn->pr_fd);
+		if (status != PR_SUCCESS)
+		{
+			pqInternalNotice(&conn->noticeHooks,
+							 "unable to close NSPR fd: %s",
+							 pg_SSLerrmessage(PR_GetError()));
+		}
+
+		conn->pr_fd = NULL;
+	}
+
 	if (conn->nss_context)
 	{
 		SECStatus	status;
+
+		/*
+		 * The session cache must be cleared, or we'll leak references.
+		 * TODO: refcount maybe? This has a global effect.
+		 */
+		SSL_ClearSessionCache();
+
 		status = NSS_ShutdownContext(conn->nss_context);
 
 		if (status != SECSuccess)
@@ -573,16 +596,16 @@ pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
 	SECOidTag	signature_tag;
 	SECOidTag	digest_alg;
 	int			digest_len;
-	PLArenaPool *arena;
+	PLArenaPool *arena = NULL;
 	SECItem		digest;
-	char	   *ret;
+	char	   *ret = NULL;
 	SECStatus	status;
 
 	*len = 0;

@@ -590,7 +613,7 @@ pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
 
@@ -605,14 +628,18 @@ pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)

 	return ret;
 }
@@ -712,6 +739,8 @@ done:
 
 	if (status == SECSuccess)
@@ -826,6 +855,7 @@ pg_cert_auth_handler(void *arg, PRFileDesc *fd, PRBool checksig, PRBool isServer
 						  pg_SSLerrmessage(PR_GetError()));
 	}

-- 
2.25.1

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 16 Jun 2021 21:52:47 +0200

> On 16 Jun 2021, at 18:15, Jacob Champion <[email-masked]> wrote:
> 

I'm not sure, the documentation doesn't give any answers and implementations of
libnss tend to just clear the cache without consideration.  In libcurl we do
just that, and haven't had any complaints - which doesn't mean it's correct but
it's a datapoint.

> SECMOD leak or the "one-time function" error that you've mentioned.

Reading the code I don't think a loaded user module is considered a resource
that must've been released prior to closing the context.  I will dig for what
showed up in my tests, but I don't think it was caused by this.

> What version of NSS are you running? I'm on 3.63.

Right now I'm using what Debian 10 is packaging which is 3.42.  Admittedly not
hot off the press but I've been trying to develop off a packaged version which
we might see users wanting to deploy against should this get shipped.

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 23 Jun 2021 15:48:59 +0200

Attached is a rebased version which incorporates your recent patchset for
resource handling, as well as the connect_ok test patch.

I've implemented tracking the close_notify alert that you mentioned offlist,
but it turns out that the alert callbacks in NSS are of limited use so it
close_notify is currently the only checked description.  The enum which labels
the descriptions in the SSLAlert struct is private, so it's just sending over
an anonymous number apart from close_notify which is zero.

A few other fixups are included as well, like adapting the pending data read
function in the frontend to how the OpenSSL implementation does it.

---

From: Jacob Champion <[email-masked]>
Date: Mon, 19 Jul 2021 19:33:23 +0000

> resource handling, as well as the connect_ok test patch.

With v38 I do see the "one-time function was previously called and
failed" message you mentioned before, as well as some PR_Assert()
crashes. Looks like it's just due to the placement of
SSL_ClearSessionCache(); gating it behind the conn->nss_context check
ensures that we don't call it if no NSS context actually exists. Patch
attached (0001).

--

Continuing my jog around the patch... client connections will crash if
hostaddr is provided rather than host, because SSL_SetURL can't handle
a NULL argument. I'm running with 0002 to fix it for the moment, but
I'm not sure yet if it does the right thing for IP addresses, which the
OpenSSL side has a special case for.

Early EOFs coming from the server don't currently have their own error
message, which leads to a confusingly empty

    connection to server at "127.0.0.1", port 47447 failed: 

0003 adds one, to roughly match the corresponding OpenSSL message.

While I was fixing that I noticed that I was getting a "unable to
verify certificate" error message for the early EOF case, even with
sslmode=require. That error message is being printed to conn-
>errorMessage during pg_cert_auth_handler(), even if we're not
verifying certificates, and then that message is included in later
unrelated failures. 0004 patches that.

--Jacob
From a675f4b6808c695d3691ad8a1a5e004ed71312c3 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Tue, 15 Jun 2021 15:59:39 -0700
Subject: [PATCH 1/4] nss: move SSL_ClearSessionCache

Don't clear the cache if no context exists.
---
 src/interfaces/libpq/fe-secure-nss.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
index 613e7d6a1d..87e18fdde2 100644
--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -141,8 +141,6 @@ pgtls_close(PGconn *conn)
 	 * All NSS references must be cleaned up before we close out the
 	 * context.
 	 */
-	SSL_ClearSessionCache();
-
 	if (conn->pr_fd)
 	{
 		PRStatus	status;
@@ -161,6 +159,10 @@ pgtls_close(PGconn *conn)
 	if (conn->nss_context)
 	{
 		SECStatus	status;
+
+		/* The session cache must be cleared, or we'll leak references. */
+		SSL_ClearSessionCache();
+
 		status = NSS_ShutdownContext(conn->nss_context);

From 2a23b00084538d9d9849a1ca46d054c1c84c53c3 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Mon, 19 Jul 2021 10:29:45 -0700
Subject: [PATCH 2/4] nss: handle NULL host

...in the case that we're using a hostaddr instead.
---
 src/interfaces/libpq/fe-secure-nss.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
index 87e18fdde2..cc66f5bb8c 100644
--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -183,6 +183,7 @@ pgtls_open_client(PGconn *conn)
 	PRFileDesc *model;
 	NSSInitParameters params;
 	SSLVersionRange desired_range;
+	const char *host;
 
 #ifdef ENABLE_THREAD_SAFETY
 #ifdef WIN32
@@ -449,9 +450,11 @@ pgtls_open_client(PGconn *conn)
 
 	/*
 	 * Specify which hostname we are expecting to talk to for the ClientHello
-	 * SNI extension.
+	 * SNI extension. TODO: what if the host is an IP address?
 	 */
-	SSL_SetURL(conn->pr_fd, (conn->connhost[conn->whichhost]).host);
+	host = conn->connhost[conn->whichhost].host;
+	if (host && host[0])
+		SSL_SetURL(conn->pr_fd, host);
 
 	status = SSL_ForceHandshake(conn->pr_fd);
 
-- 
2.25.1

From 9caa50893fc3b8d3447ce14d4b93876aa7ffe91a Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Mon, 19 Jul 2021 12:14:00 -0700
Subject: [PATCH 3/4] nss: fix spurious "unable to verify certificate" message

That message gets written to conn->errorMessage even if sslmode isn't
verifying the certificate contents, which can lead to a confusing UX if
the connection later fails for some other reason.
---
 src/interfaces/libpq/fe-secure-nss.c | 25 ++++++++++++-------------
 1 file changed, 12 insertions(+), 13 deletions(-)

diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
index cc66f5bb8c..4490fb03e4 100644
--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -858,12 +858,6 @@ pg_cert_auth_handler(void *arg, PRFileDesc *fd, PRBool checksig, PRBool isServer
 		if (!pq_verify_peer_name_matches_certificate(conn))
 			status = SECFailure;
 	}
-	else
-	{
-		printfPQExpBuffer(&conn->errorMessage,
-						  libpq_gettext("unable to verify certificate: %s"),
-						  pg_SSLerrmessage(PR_GetError()));
-	}
 
 	CERT_DestroyCertificate(server_cert);
 	return status;
@@ -923,6 +917,8 @@ pg_bad_cert_handler(void *arg, PRFileDesc *fd)
 	if (!arg)
 		return SECFailure;
 
+	err = PORT_GetError();
+
 	/*
 	 * For sslmodes other than verify-full and verify-ca we don't perform peer
 	 * validation, so return immediately.  sslmode require with a database
@@ -934,13 +930,11 @@ pg_bad_cert_handler(void *arg, PRFileDesc *fd)
 		if (conn->ssldatabase &&
 			strlen(conn->ssldatabase) > 0 &&
 			certificate_database_has_CA(conn))
-			return SECFailure;
+			goto failure;
 	}
 	else if (strcmp(conn->sslmode, "verify-full") == 0 ||
 			 strcmp(conn->sslmode, "verify-ca") == 0)
-		return SECFailure;
-
-	err = PORT_GetError();
+		goto failure;
 
 	/*
 	 * TODO: these are relevant error codes that can occur in certificate
@@ -963,15 +957,20 @@ pg_bad_cert_handler(void *arg, PRFileDesc *fd)
 		case SEC_ERROR_CA_CERT_INVALID:
 		case SEC_ERROR_CERT_USAGES_INVALID:
 		case SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION:
-			return SECSuccess;
 			break;
 		default:
-			return SECFailure;
+			goto failure;
 			break;
 	}
 
-	/* Unreachable */
 	return SECSuccess;
+
+failure:
+	printfPQExpBuffer(&conn->errorMessage,
+					  libpq_gettext("unable to verify certificate: %s"),
+					  pg_SSLerrmessage(err));
+
+	return SECFailure;
 }
 
 /* ------------------------------------------------------------ */
-- 
2.25.1

From 17f0cfc86a9b458d4cc964b6a1736f3b2870cf23 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Mon, 19 Jul 2021 12:16:17 -0700
Subject: [PATCH 4/4] nss: add client error for unexpected-EOF

...to mirror that of the OpenSSL implementation.
---
 src/interfaces/libpq/fe-secure-nss.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
index 4490fb03e4..67dff8b724 100644
--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -488,6 +488,8 @@ pgtls_read(PGconn *conn, void *ptr, size_t len)
 
 	if (nread == 0)
 	{
+		appendPQExpBufferStr(&conn->errorMessage,
+							 libpq_gettext("TLS read error: EOF detected\n"));
 		read_errno = ECONNRESET;
 		nread = -1;
 	}
-- 
2.25.1

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 26 Jul 2021 15:26:16 +0200

> On 19 Jul 2021, at 21:33, Jacob Champion <[email-masked]> wrote:

> ..client connections will crash if

AFAICT the idea is to handle it in the cert auth callback, so I've added some
PoC code to check for sslsni there and updated the TODO comment to reflect
that.

I've applied your patches in the attached rebase which passes all tests for me.

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 10 Aug 2021 19:22:20 +0200

Another rebase to work around the recent changes in the ssl Makefile.

---

From: Jacob Champion <[email-masked]>
Date: Wed, 18 Aug 2021 00:06:59 +0000

> Another rebase to work around the recent changes in the ssl Makefile.

I have a local test suite that I've been writing against libpq. With
the new ssldatabase connection option, one tricky aspect is figuring
out whether it's supported or not. It doesn't look like there's any way
to tell, from a client application, whether NSS or OpenSSL (or neither)
is in use.

You'd mentioned that perhaps we should support a call like

    PQsslAttribute(NULL, "library"); /* returns "NSS", "OpenSSL", or NULL */

so that you don't have to have an actual connection first in order to
figure out what connection options you need to supply. Clients that
support multiple libpq versions would need to know whether that call is
reliable (older versions of libpq will always return NULL, whether SSL
is compiled in or not), so maybe we could add a feature macro at the
same time?

We could also add a new API (say, PQsslLibrary()) but I don't know if
that gives us anything in practice. Thoughts?

--Jacob

---

From: Michael Paquier <[email-masked]>
Date: Wed, 18 Aug 2021 09:32:37 +0900

> to tell, from a client application, whether NSS or OpenSSL (or neither)

That's about guessing which library libpq is compiled with, so yes
that's a problem.

> is compiled in or not), so maybe we could add a feature macro at the

Still, the problem is wider than that, no?  One cannot know either if
a version of libpq is able to work with GSSAPI until they attempt a
connection with gssencmode.  It seems to me that we should work on the
larger picture here.

> that gives us anything in practice. Thoughts?

Knowing that the GSSAPI stuff is part of fe-secure.c, we may want
instead a call that returns a list of supported secure libraries.
--
Michael

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 18 Aug 2021 11:48:23 +0200

> On 18 Aug 2021, at 02:32, Michael Paquier <[email-masked]> wrote:
> 

I think we should do both.  PQsslAttribute() already exists, and being able to
get the library attribute for NULL conn object when there are multiple
libraries makes a lot of sense to me.  That doesn’t exclude working on a better
way for apps to interrogate the libpq they have at hand for which capabilities
it has.  Personally I’m not sure what that API could look like, but we should
discuss that in a separate thread I guess.

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 8 Sep 2021 20:49:33 +0200

Attached is a rebased v41 to keep the patch from bitrot.

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 20 Sep 2021 11:38:16 +0200

Rebased on top of HEAD with off-list comment fixes by Kevin Burke.

---

From: Jacob Champion <[email-masked]>
Date: Tue, 21 Sep 2021 00:06:15 +0000

I dug a bit deeper into the SNI stuff:

> +		/* If SNI is enabled we must have a hostname set */
> +		if (conn->sslsni && conn->sslsni[0])
> +			status = SECFailure;

conn->sslsni can be explicitly set to "0" to disable it, so this should
probably be changed to a check for "1", but I'm not sure that would be
correct either. If the user has the default sslsni="1" and supplies an
IP address for the host parameter, I don't think we should fail the
connection.

> +	if (host && host[0] &&
> +		!(strspn(host, "0123456789.") == strlen(host) ||
> +		  strchr(host, ':')))

It looks like NSS may already have some code that prevents SNI from
being sent for IP addresses, so that part of the guard might not be
necessary. (And potentially counterproductive, because it looks like
NSS can perform verification against the certificate's SANs if you pass
an IP address to SSL_SetURL().)

Speaking of IP addresses in SANs, it doesn't look like our OpenSSL
backend can handle those. That's a separate conversation, but I might
take a look at a patch for next commitfest.

--Jacob

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 27 Sep 2021 15:44:30 +0200

> On 21 Sep 2021, at 02:06, Jacob Champion <[email-masked]> wrote:
> 
> probably be changed to a check for "1",

Agreed.

> but I'm not sure that would be

Maybe not, but doing so is at least in line with how the OpenSSL support will
handle the same config AFAICT. Or am I missing something?

> an IP address to SSL_SetURL().)

Skimming the NSS code I wasn't able find the countermeasures, can you provide a
reference to where I should look?

Feel free to post a new version of the NSS patch with these changes if you want.

> take a look at a patch for next commitfest.

Please do.

---

From: Jacob Champion <[email-masked]>
Date: Mon, 27 Sep 2021 16:29:43 +0000

> handle the same config AFAICT. Or am I missing something?

With OpenSSL, I don't see a connection failure when using sslsni=1 with
IP addresses. (verify-full can't work, but that's a separate problem.)

> reference to where I should look?

I see the check in ssl_ShouldSendSNIExtension(), in ssl3exthandle.c.

> Feel free to post a new version of the NSS patch with these changes if you want.

Will do!

Thanks,
--Jacob

---

From: Jacob Champion <[email-masked]>
Date: Mon, 27 Sep 2021 19:40:28 +0000

> > Feel free to post a new version of the NSS patch with these changes if you want.

Something like the attached, v43, I think. (since-v42.diff.txt has the
changes only.)

This fixes the interaction of IP addresses and SNI for me, and honors
sslsni=0.

--Jacob
commit ec0fb068da39236602e8e1de8bbf8487a1093590
Author: Jacob Champion <[email-masked]>
Date:   Mon Sep 27 12:26:29 2021 -0700

    squash! nss: Support libnss as TLS library in libpq
    
    Don't send SNI if the user has disabled it. We can remove the IP address
    check since NSS does that natively.

diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
index 0a9751c22b..51f09fb7fa 100644
--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -183,7 +183,6 @@ pgtls_open_client(PGconn *conn)
 	PRFileDesc *model;
 	NSSInitParameters params;
 	SSLVersionRange desired_range;
-	const char *host;
 
 #ifdef ENABLE_THREAD_SAFETY
 #ifdef WIN32
@@ -450,15 +449,16 @@ pgtls_open_client(PGconn *conn)
 
 	/*
 	 * Specify which hostname we are expecting to talk to for the ClientHello
-	 * SNI extension. TODO: if the hostname is a literal IP address we skip
-	 * setting it, and check for SNI status in the cert callback. Is this the
-	 * correct course of action?
+	 * SNI extension, unless the user has disabled it. NSS will suppress IP
+	 * addresses in SNIs, so we don't need to filter those explicitly like we do
+	 * for OpenSSL.
 	 */
-	host = conn->connhost[conn->whichhost].host;
-	if (host && host[0] &&
-		!(strspn(host, "0123456789.") == strlen(host) ||
-		  strchr(host, ':')))
-		SSL_SetURL(conn->pr_fd, host);
+	if (conn->sslsni && conn->sslsni[0] == '1')
+	{
+		const char *host = conn->connhost[conn->whichhost].host;
+		if (host && host[0])
+			SSL_SetURL(conn->pr_fd, host);
+	}

@@ -678,12 +678,16 @@ pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn,
 	CERTGeneralName *san_list;
 	CERTGeneralName *cn;
 
-	server_hostname = SSL_RevealURL(conn->pr_fd);
+	/*
+	 * In the "standard" NSS use case, we'd call SSL_RevealURL() to get the
+	 * hostname. In our case, SSL_SetURL() won't have been called if the user
+	 * has disabled SNI, so we always pull the hostname from connhost instead.
+	 */
+	server_hostname = conn->connhost[conn->whichhost].host;
 	if (!server_hostname || server_hostname[0] == '\0')
 	{
-		/* If SNI is enabled we must have a hostname set */
-		if (conn->sslsni && conn->sslsni[0])
-			status = SECFailure;
+		/* verify-full shouldn't progress this far without a hostname. */
+		status = SECFailure;
 		goto done;
 	}
 
@@ -762,7 +766,6 @@ done:
 		PORT_FreeArena(arena, PR_TRUE);
 	if (server_cert)
 		CERT_DestroyCertificate(server_cert);
-	PR_Free(server_hostname);
 
 	if (status == SECSuccess)
 		return 1;
From d6753e5970e5a610e579c4ca3a5ebc47897f1dc1 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:22 +0100
Subject: [PATCH v43 01/10] nss: Support libnss as TLS library in libpq

 src/backend/libpq/be-secure-nss.c             | 1574 +++++++++++++++++
 src/common/cipher_nss.c                       |  192 ++
 src/interfaces/libpq/fe-secure-nss.c          | 1200 +++++++++++++
 16 files changed, 3180 insertions(+), 7 deletions(-)

diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index c7b7db8065..6d63528954 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -9449,7 +9449,7 @@ DO $d$
     END;
 $d$;
 ERROR:  invalid option "password"
-HINT:  Valid options in this context are: service, passfile, channel_binding, connect_timeout, dbname, host, hostaddr, port, options, application_name, keepalives, keepalives_idle, keepalives_interval, keepalives_count, tcp_user_timeout, sslmode, sslcompression, sslcert, sslkey, sslrootcert, sslcrl, sslcrldir, sslsni, requirepeer, ssl_min_protocol_version, ssl_max_protocol_version, gssencmode, krbsrvname, gsslib, target_session_attrs, use_remote_estimate, fdw_startup_cost, fdw_tuple_cost, extensions, updatable, truncatable, fetch_size, batch_size, async_capable, keep_connections
+HINT:  Valid options in this context are: service, passfile, channel_binding, connect_timeout, dbname, host, hostaddr, port, options, application_name, keepalives, keepalives_idle, keepalives_interval, keepalives_count, tcp_user_timeout, sslmode, sslcompression, sslcert, sslkey, sslrootcert, sslcrl, sslcrldir, sslsni, requirepeer, ssl_min_protocol_version, ssl_max_protocol_version, gssencmode, krbsrvname, gsslib, target_session_attrs, ssldatabase, use_remote_estimate, fdw_startup_cost, fdw_tuple_cost, extensions, updatable, truncatable, fetch_size, batch_size, async_capable, keep_connections
 CONTEXT:  SQL statement "ALTER SERVER loopback_nopw OPTIONS (ADD password 'dummypw')"
 PL/pgSQL function inline_code_block line 3 at EXECUTE
 -- If we add a password for our user mapping instead, we should get a different
diff --git a/src/backend/libpq/auth.c b/src/backend/libpq/auth.c
index a317aef1c9..add92db87a 100644
--- a/src/backend/libpq/auth.c
+++ b/src/backend/libpq/auth.c
@@ -2752,7 +2752,13 @@ CheckCertAuth(Port *port)
 	int			status_check_usermap = STATUS_ERROR;
 	char	   *peer_username = NULL;

index 0000000000..ef8da8b3d4
@@ -0,0 +1,1574 @@
+static char *pg_CERT_GetDistinguishedName(CERTCertificate *cert);
+static const char *tag_to_name(SECOidTag tag);
+static void pg_SSLAlertSent(const PRFileDesc *fd, void *private_data, const SSLAlert *alert);
+	/* Register callback for TLS alerts */
+	SSL_AlertSentCallback(port->pr_fd, pg_SSLAlertSent, port);
+	 * Immediately signal to the rest of the backend that this connnection is
+	 * no longer to be considered to be using TLS encryption.
+ * Returns the number of bits in the encryption key used, or zero in case
+ * of errors.
+ * Returns the cipher used for the current connection, or NULL in case of
+ * errors.
+	if (!digest.data)
+ * tag_to_name
+ * Return the name of the RDN identified by the tag passed as parameter. NSS
+ * has this information in a struct, but the only publicly accessible API for
+ * using it is limited to retrieving the maximum length of the ava.
+tag_to_name(SECOidTag tag)
+	switch(tag)
+		case SEC_OID_AVA_COMMON_NAME:
+			return "CN";
+		case SEC_OID_AVA_STATE_OR_PROVINCE:
+			return "ST";
+		case SEC_OID_AVA_ORGANIZATION_NAME:
+			return "O";
+		case SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME:
+			return "OU";
+		case SEC_OID_AVA_COUNTRY_NAME:
+			return "C";
+		case SEC_OID_AVA_LOCALITY:
+			return "L";
+		case SEC_OID_AVA_SURNAME:
+			return "SN";
+		case SEC_OID_AVA_DC:
+			return "DC";
+		case SEC_OID_RFC1274_MAIL:
+			return "MAIL";
+		case SEC_OID_RFC1274_UID:
+			return "UID";
+		 * TODO: what would be the most appropriate thing to do here?
+			return "";
+ * pg_CERT_GetDistinguishedName
+ * NSS doesn't provide a DN equivalent of CERT_GetCommonName, so we have to
+ * keep our own.
+pg_CERT_GetDistinguishedName(CERTCertificate *cert)
+	StringInfoData	dnbuf;
+	char		   *dn = NULL;
+	initStringInfo(&dnbuf);
+		bool		first = true;
+			char	   *tmpstr;
+			char	   *dststr;
+			int			tmplen;
+			/* See raw_subject_common_name comment for discussion */
+			tmpstr = palloc0(buf->len + 1);
+			tmplen = buf->len;
+			memcpy(tmpstr, buf->data, buf->len);
+			/* Check for embedded null */
+			if (strlen(tmpstr) != tmplen)
+			/* Make room for the worst case escaping */
+			dststr = palloc0((tmplen * 3) + 1);
+			 * While the function name refers to RFC 1485, the underlying
+			 * quoting code conforms to the RFC 2253 rules.
+			status = CERT_RFC1485_EscapeAndQuote(dststr, tmplen * 3, tmpstr, tmplen);
+				pfree(dststr);
+				pfree(tmpstr);
+			appendStringInfo(&dnbuf, "%s%s=%s",
+							 (first ? "" : ","),
+							 tag_to_name(CERT_GetAVATag(*ava)), dststr);
+			first = false;
+			pfree(dststr);
+			pfree(tmpstr);
+	if (dnbuf.len)
+		dn = MemoryContextAllocZero(TopMemoryContext, dnbuf.len + 1);
+		strlcpy(dn, dnbuf.data, dnbuf.len + 1);
+	return dn;
+	/* Not found  */
+	port->peer_dn = pg_CERT_GetDistinguishedName(cert);
+	if  (!port->peer_dn)
+				 errmsg("unable to get SSL certificate's distinguished name")));
+ * pg_SSLAlertSent
+ *		Callback for TLS alerts sent from NSS
+ * The alert system is intended to provide information on ongoing issues to
+ * the TLS implementation such that they can be logged. It is not replacing
+ * error handling for the NSS API, but rather adds a more finegrained way of
+ * extracting information on errors during connection processing. The actual
+ * error names are however only accessible in a private NSS header and not
+ * exported. Thus, we only use it for close_notify which is defined as zero.
+ * See https://bugzilla.mozilla.org/show_bug.cgi?id=956866 for further
+ * discussion on this interface.
+pg_SSLAlertSent(const PRFileDesc *fd, void *private_data, const SSLAlert *alert)
+	 * close_notify is not an error, but an indication that the connection
+	 * was orderly closed. Since the backend is only closing connections where
+	 * TLS is no longer in use, log an error in case this wasn't the case.
+	 * close_notify is defined in the NSS private enum SSL3AlertDescription
+	 * as zero.
+	if (alert->description == 0)
+		if (port->ssl_in_use)
+					 errmsg("closing an active TLS connection"));
+	 * Any other alert received indicates an error, but since they can't be
+	 * made heads or tails with without reading the NSS source code let's
+	 * just log them as DEBUG information as they are of limited value in
+	 * any other circumstance.
+	ereport(DEBUG2,
+			(errmsg_internal("TLS alert received: %d", alert->description)));
 
 /* GUC variable controlling SSL cipher list */
 char	   *SSLCipherSuites = NULL;
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index d2ce4a8450..5febe83efb 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -4422,7 +4422,11 @@ static struct config_string ConfigureNamesString[] =
 		},
 		&ssl_library,
 #ifdef USE_SSL
+#if defined(USE_OPENSSL)
 		"OpenSSL",
+#elif defined(USE_NSS)
+		"NSS",
+#endif
 #else
 		"",
 #endif
@@ -4490,6 +4494,16 @@ static struct config_string ConfigureNamesString[] =
 		check_canonical_path, assign_pgstat_temp_directory, NULL
 	},
 
+	{
@@ -4518,8 +4532,10 @@ static struct config_string ConfigureNamesString[] =
index 02015efe13..c8388c5450 100644
@@ -212,13 +212,18 @@ typedef struct Port
 	bool		peer_cert_valid;
 
 	/*
-	 * OpenSSL structures. (Keep these last so that the locations of other
-	 * fields are the same whether or not you build with SSL enabled.)
+	 * TLS backend specific structures. (Keep these last so that the locations
+	 * of other fields are the same whether or not you build with SSL
+	 * enabled.)
 	 */
 #ifdef USE_OPENSSL
 	SSL		   *ssl;
 	X509	   *peer;
 #endif
+
+#ifdef USE_NSS
+	void	   *pr_fd;
+#endif
 } Port;
 
 #ifdef USE_SSL
@@ -301,7 +306,7 @@ extern void be_tls_get_peer_serial(Port *port, char *ptr, size_t len);
@@ -311,6 +316,10 @@ extern char *be_tls_get_certificate_hash(Port *port, size_t *len);
 
 #endif							/* USE_SSL */
 
diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
index 6c51b2f20f..0d5b15d823 100644
--- a/src/include/libpq/libpq.h
+++ b/src/include/libpq/libpq.h
@@ -97,6 +97,7 @@ extern PGDLLIMPORT bool ssl_passphrase_command_supports_reload;
 #ifdef USE_SSL
 extern bool ssl_loaded_verify_locations;
 #endif
+extern char *ssl_database;
 
index 614035e215..6af89d9e98 100644
 
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index b288d346f9..79016f912d 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -344,6 +344,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = {
 		"Target-Session-Attrs", "", 15, /* sizeof("prefer-standby") = 15 */
 	offsetof(struct pg_conn, target_session_attrs)},
 
index 0000000000..51f09fb7fa
@@ -0,0 +1,1200 @@
+#ifdef ENABLE_THREAD_SAFETY
+#ifdef WIN32
+#include "pthread-win32.h"
+#include <pthread.h>
+#ifdef ENABLE_THREAD_SAFETY
+#ifndef WIN32
+static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t ssl_config_mutex = NULL;
+static long win32_ssl_create_mutex = 0;
+#endif							/* ENABLE_THREAD_SAFETY */
+	 * All NSS references must be cleaned up before we close out the
+	 * context.
+		/* The session cache must be cleared, or we'll leak references */
+#ifdef ENABLE_THREAD_SAFETY
+#ifdef WIN32
+	/* This locking is modelled after fe-secure-openssl.c */
+	if (ssl_config_mutex == NULL)
+		while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
+			/* loop while another thread owns the lock */ ;
+		if (ssl_config_mutex == NULL)
+			if (pthread_mutex_init(&ssl_config_mutex, NULL))
+								  libpq_gettext("unable to lock thread"));
+		InterlockedExchange(&win32_ssl_create_mutex, 0);
+	if (pthread_mutex_lock(&ssl_config_mutex))
+						  libpq_gettext("unable to lock thread"));
+#endif							/* ENABLE_THREAD_SAFETY */
+	params.dbTokenDescription = strdup("postgres");
+#ifdef ENABLE_THREAD_SAFETY
+	pthread_mutex_unlock(&ssl_config_mutex);
+	 * SNI extension, unless the user has disabled it. NSS will suppress IP
+	 * addresses in SNIs, so we don't need to filter those explicitly like we do
+	 * for OpenSSL.
+	if (conn->sslsni && conn->sslsni[0] == '1')
+		const char *host = conn->connhost[conn->whichhost].host;
+ *		Check for the existence of data to be read
+ * SSL_DataPending will check for decrypted data in the receiving buffer, but
+ * does not reveal anything about still encrypted data which will be made
+ * available. Thus, if pgtls_read_pending returns zero it does not guarantee
+ * that a subsequent call to pgtls_read would block. This is modelled
+ * around how the OpenSSL implementation treats pending data. The equivalent
+ * to the OpenSSL SSL_has_pending function would be to call PR_Recv with no
+ * wait and PR_MSG_PEEK like so:
+ *     PR_Recv(conn->pr_fd, &c, 1, PR_MSG_PEEK, PR_INTERVAL_NO_WAIT);
+	return SSL_DataPending(conn->pr_fd) > 0;
+ * pgtls_write
+ *		Write data on the secure socket
+	if (!digest.data)
+						  libpq_gettext("out of memory"));
+	 * In the "standard" NSS use case, we'd call SSL_RevealURL() to get the
+	 * hostname. In our case, SSL_SetURL() won't have been called if the user
+	 * has disabled SNI, so we always pull the hostname from connhost instead.
+	server_hostname = conn->connhost[conn->whichhost].host;
+		/* verify-full shouldn't progress this far without a hostname. */
+ * it ourselves to ensure we can do cert authentication.
+	char	   *nnptr = NULL;
+	char		nickname[MAXPGPATH];
+	 * If we have an sslcert configured we use that combined with the token-
+	 * name as the nickname. When no sslcert is set we pass in NULL and let
+	 * NSS try to find the certificate among the ones present in the database.
+	 * Without an sslcert we cannot set the database token since NSS parses
+	 * the given string expecting to find a certificate nickname after the
+	 * colon.
+	if (conn->sslcert)
+		snprintf(nickname, sizeof(nickname), "postgres:%s", conn->sslcert);
+		nnptr = nickname;
+	return NSS_GetClientAuthData(nnptr, socket, caNames, pRetCert, pRetKey);
+	 * here without even checking.
+ * user as a connection parameter.
+ * presence of a CA certificate, not its validity and/or usefulness.
 
+#ifndef USE_NSS
+
 
diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h
index a6fd69aceb..186e0a28f4 100644
--- a/src/interfaces/libpq/libpq-fe.h
+++ b/src/interfaces/libpq/libpq-fe.h
@@ -665,6 +665,17 @@ extern PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
 extern void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook);
 extern int	PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn);
 
index 490458adef..ab0da13700 100644
@@ -81,6 +81,10 @@ typedef struct
 #endif
 #endif							/* USE_OPENSSL */
 
+#ifdef USE_NSS
+#include "common/nss.h"
+#endif
+
 /*
@@ -385,6 +389,7 @@ struct pg_conn
 	char	   *sslsni;			/* use SSL SNI extension (0 or 1) */
@@ -526,6 +531,28 @@ struct pg_conn
 
 #ifdef ENABLE_GSS
@@ -780,7 +807,7 @@ extern ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len);

From a7d0dff74a03148cceed539e9eb2e0257d734ec4 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:34 +0100
Subject: [PATCH v43 02/10] Refactor SSL testharness for multiple library

diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl
index 3bc711f4a7..35184cd80c 100644
--- a/src/test/ssl/t/001_ssltests.pl
+++ b/src/test/ssl/t/001_ssltests.pl
@@ -7,12 +7,10 @@ use PostgresNode;
 use TestLib;
 use Test::More;
 
-use File::Copy;
-
 use FindBin;
 
-use SSLServer;
+use SSL::Server;
 
 if ($ENV{with_ssl} ne 'openssl')
 {
@@ -35,32 +33,6 @@ my $SERVERHOSTCIDR = '127.0.0.1/32';
 # Allocation of base connection string shared among multiple tests.
 my $common_connstr;

 note "setting up data directory";
@@ -75,32 +47,22 @@ $node->start;

 

@@ -586,7 +548,5 @@ $node->connect_fails(
 
 # clean up
-foreach my $key (@keys)
-{
-	unlink("ssl/${key}_tmp.key");
-}
+
+SSL::Server::cleanup();
diff --git a/src/test/ssl/t/002_scram.pl b/src/test/ssl/t/002_scram.pl
index 1dfa2b91f3..e05e60f092 100644
--- a/src/test/ssl/t/002_scram.pl
+++ b/src/test/ssl/t/002_scram.pl
@@ -14,11 +14,11 @@ use File::Copy;
 use FindBin;
 use lib $FindBin::RealBin;
 
-use SSLServer;
+use SSL::Server;

 # This is the hostname used to connect to the server.
@@ -115,5 +115,3 @@ $node->connect_ok(
 
 # clean up
 unlink($client_tmp_key);
-
index 0000000000..e77ee25cc7
+		"client-encrypted-der", "client-dn");
+	my @keys = (
+		"client-encrypted-der", "client-dn");
+	copy("ssl/client.key", "ssl/client_wrongperms_tmp.key");
+	chmod 0644, "ssl/client_wrongperms_tmp.key";
index 804d008245..33bf351476 100644
@@ -26,19 +26,39 @@
 
-package SSLServer;
+package SSL::Server;
 
 use strict;
 use warnings;
 use PostgresNode;
+use RecursiveCopy;
 use TestLib;
 use File::Basename;
 use File::Copy;
 use Test::More;
 
 use Exporter 'import';
 our @EXPORT = qw(
 
@@ -112,14 +132,21 @@ sub configure_test_server_for_ssl
 	close $sslconf;

 	# Stop and restart server to load new listen_addresses.
 	$node->restart;
@@ -127,20 +154,36 @@ sub configure_test_server_for_ssl
 	# Change pg_hba after restart because hostssl requires ssl=on
 	configure_hba_for_ssl($node, $servercidr, $authmethod);

 
+	$keyfile = $certfile if $keyfile eq '';
+
 	# defaults to use crl file
 	if (defined $_[3] || defined $_[4])
 	{
@@ -150,13 +193,23 @@ sub switch_server_cert

From 310b47cb0c4de313d266f3531852c906fef3b70c Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:37 +0100
Subject: [PATCH v43 03/10] nss: Add NSS specific tests

The OpenSSL testfiles are reused by repackaging them into NSS databases
in order for the tests to be cross-library. Additional testfiles are
generated by using only the NSS toolchain as well as rudimentary tests
using these.
---
 src/test/ssl/Makefile                 | 246 ++++++++++++++++
 src/test/ssl/t/001_ssltests.pl        | 395 +++++++++++++++++---------
 src/test/ssl/t/002_scram.pl           |  33 ++-
 src/test/ssl/t/SSL/Backend/NSS.pm     |  61 ++++
 src/test/ssl/t/SSL/Backend/OpenSSL.pm |  19 +-
 src/test/ssl/t/SSL/Server.pm          |  46 +--
 6 files changed, 610 insertions(+), 190 deletions(-)
 create mode 100644 src/test/ssl/t/SSL/Backend/NSS.pm

diff --git a/src/test/ssl/Makefile b/src/test/ssl/Makefile
index c216560dcc..4628b24908 100644
--- a/src/test/ssl/Makefile
+++ b/src/test/ssl/Makefile
@@ -33,6 +33,37 @@ SSLFILES := $(CERTIFICATES:%=ssl/%.key) $(CERTIFICATES:%=ssl/%.crt) \
 SSLDIRS := ssl/client-crldir ssl/server-crldir \
 	ssl/root+client-crldir ssl/root+server-crldir
 
@@ -40,6 +71,10 @@ SSLDIRS := ssl/client-crldir ssl/server-crldir \
 
@@ -67,6 +102,35 @@ ssl/%_ca.crt: ssl/%_ca.key %_ca.config ssl/root_ca.crt ssl/new_certs_dir
 
@@ -74,6 +138,87 @@ ssl/server-%.crt: ssl/server-%.key ssl/server_ca.crt server-%.config
 	openssl x509 -in ssl/temp.crt -out ssl/server-$*.crt # to keep just the PEM cert
 	rm ssl/server-$*.csr
 
@@ -92,6 +237,27 @@ ssl/client-dn.crt: ssl/client-dn.key ssl/client_ca.crt
 
+	certutil -d "sql:$@" -A -n root+server_ca.crt -i ssl/root+server_ca.crt -t "CT,C,C"
@@ -99,6 +265,14 @@ ssl/client-revoked.crt: ssl/client-revoked.key ssl/client_ca.crt client.config
 
@@ -131,19 +305,40 @@ ssl/root+client_ca.crt: ssl/root_ca.crt ssl/client_ca.crt

 

@@ -169,14 +364,65 @@ ssl/client-crldir: ssl/client.crl

+.PHONY: nssfiles-clean
+nssfiles-clean:
+	rm -rf ssl/nss
+
 
 # Doesn't depend on $(SSLFILES) because we don't rebuild them by default
 check:
diff --git a/src/test/ssl/t/001_ssltests.pl b/src/test/ssl/t/001_ssltests.pl
index 35184cd80c..f961ba9737 100644
--- a/src/test/ssl/t/001_ssltests.pl
+++ b/src/test/ssl/t/001_ssltests.pl
@@ -12,13 +12,22 @@ use lib $FindBin::RealBin;
 
 use SSL::Server;
 
+	plan tests => 112;
+	plan tests => 112;
-	plan tests => 110;
 
 #### Some configuration
@@ -54,19 +63,68 @@ configure_test_server_for_ssl($node, $SERVERHOSTADDR, $SERVERHOSTCIDR,

 
+		"connect to server with incorrect key password configured",
+		expected_stderr => qr/\QSSL error\E/);
 
 # Test compatibility of SSL protocols.
 # TLSv1.1 is lower than TLSv1.2, so it won't work.
@@ -94,7 +152,7 @@ command_ok(

 
 $common_connstr =
   "user=ssltestuser dbname=trustdb sslcert=invalid hostaddr=$SERVERHOSTADDR host=common-name.pg-ssltest.test";
@@ -113,87 +171,104 @@ $node->connect_ok(
 $node->connect_fails(
 	"$common_connstr sslrootcert=invalid sslmode=verify-ca",
 	"connect without server root cert sslmode=verify-ca",
-	expected_stderr => qr/root certificate file "invalid" does not exist/);
+	expected_stderr => qr/root certificate file "invalid" does not exist|Peer's certificate issuer has been marked as not trusted by the user/);
 $node->connect_fails(
 	"$common_connstr sslrootcert=invalid sslmode=verify-full",
 	"connect without server root cert sslmode=verify-full",
-	expected_stderr => qr/root certificate file "invalid" does not exist/);
+	expcted_stderr => qr/root certificate file "invalid" does not exist|Peer's certificate issuer has been marked as not trusted by the user/);

 

 

 

 $node->connect_ok("$common_connstr sslmode=require host=wronghost.test",
 	"mismatch between host name and server certificate sslmode=require");
@@ -204,14 +279,14 @@ $node->connect_fails(
 	"$common_connstr sslmode=verify-full host=wronghost.test",
 	"mismatch between host name and server certificate sslmode=verify-full",
 	expected_stderr =>
-	  qr/\Qserver certificate for "common-name.pg-ssltest.test" does not match host name "wronghost.test"\E/
+	  qr/\Qserver certificate for "common-name.pg-ssltest.test" does not match host name "wronghost.test"\E|requested domain name does not match the server's certificate/
 );

 $common_connstr =
 
 $node->connect_ok(
 	"$common_connstr host=dns1.alt-name.pg-ssltest.test",
@@ -226,21 +301,22 @@ $node->connect_fails(
 	"$common_connstr host=wronghost.alt-name.pg-ssltest.test",
 	"host name not matching with X.509 Subject Alternative Names",
 	expected_stderr =>
-	  qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "wronghost.alt-name.pg-ssltest.test"\E/
+	  qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "wronghost.alt-name.pg-ssltest.test"\E|requested domain name does not match the server's certificate/
 );
+
 $node->connect_fails(
 	"$common_connstr host=deep.subdomain.wildcard.pg-ssltest.test",
 	"host name not matching with X.509 Subject Alternative Names wildcard",
 	expected_stderr =>
-	  qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E/
+	  qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 2 other names) does not match host name "deep.subdomain.wildcard.pg-ssltest.test"\E|requested domain name does not match the server's certificate/
 );

 $common_connstr =
 
 $node->connect_ok(
@@ -250,21 +326,21 @@ $node->connect_fails(
+	  qr/\Qserver certificate for "single.alt-name.pg-ssltest.test" does not match host name "wronghost.alt-name.pg-ssltest.test"\E|requested domain name does not match the server's certificate/

 $common_connstr =
 
 $node->connect_ok("$common_connstr host=dns1.alt-name.pg-ssltest.test",
 	"certificate with both a CN and SANs 1");
@@ -274,43 +350,43 @@ $node->connect_fails(
 	"$common_connstr host=common-name.pg-ssltest.test",
 	"certificate with both a CN and SANs ignores CN",
 	expected_stderr =>
-	  qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 1 other name) does not match host name "common-name.pg-ssltest.test"\E/
+	  qr/\Qserver certificate for "dns1.alt-name.pg-ssltest.test" (and 1 other name) does not match host name "common-name.pg-ssltest.test"\E|requested domain name does not match the server's certificate/
 );

 $node->connect_ok(
 	"$common_connstr sslmode=verify-ca host=common-name.pg-ssltest.test",
 	"server certificate without CN or SANs sslmode=verify-ca");
 $node->connect_fails(
 	$common_connstr . " "
-	  . "sslmode=verify-full host=common-name.pg-ssltest.test",
+	. "sslmode=verify-full host=common-name.pg-ssltest.test",
 	"server certificate without CN or SANs sslmode=verify-full",
 	expected_stderr =>
-	  qr/could not get server's host name from server certificate/);
+	  qr/could not get server's host name from server certificate|requested domain name does not match the server's certificate./);

 $common_connstr =

 # pg_stat_ssl
 command_like(
@@ -328,29 +404,46 @@ command_like(

 
 
 $common_connstr =
 
 # no client cert
 $node->connect_fails(
@@ -364,62 +457,82 @@ $node->connect_ok(
 	"certificate authorization succeeds with correct client cert in PEM format"
 );
 
-# correct client cert in unencrypted DER
-$node->connect_ok(
-	"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-der_tmp.key",
-	"certificate authorization succeeds with correct client cert in DER format"
-);
+SKIP:
+{
+	skip "Automatic certificate resolution is NSS specific", 1 if ($openssl);
+	# correct client cert in unencrypted PEM without a nickname (sslcert)
+	$node->connect_ok(
+		"$common_connstr user=ssltestuser",
+		"certificate authorization succeeds without correct client cert in connstring"
+	);
+}
+
+SKIP:
+{
+	skip "NSS database not implemented in the Makefile", 1 if ($nss);
+	# correct client cert in unencrypted DER
+	$node->connect_ok(
+		"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client-der_tmp.key",
+		"certificate authorization succeeds with correct client cert in DER format"
+	);
+}

 
 
-
-# correct client cert using whole DN
-my $dn_connstr = "$common_connstr dbname=certdb_dn";
-
-$node->connect_ok(
-	"$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key",
-	"certificate authorization succeeds with DN mapping",
-	log_like => [
-		qr/connection authenticated: identity="CN=ssltestuser-dn,OU=Testing,OU=Engineering,O=PGDG" method=cert/
-	],);
-
-# same thing but with a regex
-$dn_connstr = "$common_connstr dbname=certdb_dn_re";
-
-$node->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 = "$common_connstr dbname=certdb_cn";
-
-$node->connect_ok(
-	"$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key",
-	"certificate authorization succeeds with CN mapping",
-	# the full DN should still be used as the authenticated identity
-	log_like => [
-		qr/connection authenticated: identity="CN=ssltestuser-dn,OU=Testing,OU=Engineering,O=PGDG" method=cert/
-	],);
-
-
+SKIP:
+{
+	skip "DN mapping not implemented in NSS",            3 if ($nss);
+
+	# correct client cert using whole DN
+	my $dn_connstr = "$common_connstr dbname=certdb_dn";
+
+	$node->connect_ok(
+		"$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key",
+		"certificate authorization succeeds with DN mapping",
+		log_like => [
+			qr/connection authenticated: identity="CN=ssltestuser-dn,OU=Testing,OU=Engineering,O=PGDG" method=cert/
+		],);
+
+	# same thing but with a regex
+	$dn_connstr = "$common_connstr dbname=certdb_dn_re";
+
+	$node->connect_ok(
+		"$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key",
+		"certificate authorization succeeds with CN mapping",
+		# the full DN should still be used as the authenticated identity
+		log_like => [
+			qr/connection authenticated: identity="CN=ssltestuser-dn,OU=Testing,OU=Engineering,O=PGDG" method=cert/
+		],);
+
+	# same thing but using explicit CN
+	$dn_connstr = "$common_connstr dbname=certdb_cn";
+
+	$node->connect_ok(
+		"$dn_connstr user=ssltestuser sslcert=ssl/client-dn.crt sslkey=ssl/client-dn_tmp.key",
+		"certificate authorization succeeds with CN mapping");
+}
 
 TODO:
 {
@@ -457,18 +570,19 @@ command_like(
 		'-P',
 		'null=_null_',
 		'-d',

 	$node->connect_fails(
 		"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client_wrongperms_tmp.key",
@@ -483,16 +597,20 @@ $node->connect_fails(
 	"$common_connstr user=anotheruser sslcert=ssl/client.crt sslkey=ssl/client_tmp.key",
 	"certificate authorization fails with client cert belonging to another user",
 	expected_stderr =>
-	  qr/certificate authentication failed for user "anotheruser"/,
+	  qr/unable to verify certificate|certificate authentication failed for user "anotheruser"/,
 	# certificate authentication should be logged even on failure
 	log_like =>
 	  [qr/connection authenticated: identity="CN=ssltestuser" method=cert/],);
 
+$common_connstr =
+  "sslrootcert=ssl/root+server_ca.crt sslmode=require dbname=certdb hostaddr=$SERVERHOSTADDR ssldatabase=ssl/nss/client-revoked.crt__client-revoked.key.db";
+
 # revoked client cert
 $node->connect_fails(
 	"$common_connstr user=ssltestuser sslcert=ssl/client-revoked.crt sslkey=ssl/client-revoked_tmp.key",
 	"certificate authorization fails with revoked client cert",
-	expected_stderr => qr/SSL error: sslv3 alert certificate revoked/,
+	expected_stderr =>
+	  qr/SSL error: sslv3 alert certificate revoked|SSL error: Peer's certificate issuer has been marked as not trusted by the user/,
 	# revoked certificates should not authenticate the user
 	log_unlike => [qr/connection authenticated:/],);
 
@@ -500,7 +618,7 @@ $node->connect_fails(
 
 $node->connect_ok(
 	"$common_connstr user=ssltestuser sslcert=ssl/client.crt sslkey=ssl/client_tmp.key",
@@ -525,9 +643,9 @@ $node->connect_ok(
 	log_unlike => [qr/connection authenticated:/],);

 $node->connect_ok(
 	"$common_connstr sslmode=require sslcert=ssl/client+client_ca.crt",
@@ -535,17 +653,18 @@ $node->connect_ok(
 $node->connect_fails(
 	$common_connstr . " " . "sslmode=require sslcert=ssl/client.crt",
 	"intermediate client certificate is missing",
-	expected_stderr => qr/SSL error: tlsv1 alert unknown ca/);
+	expected_stderr =>
+	  qr/SSL error: tlsv1 alert unknown ca|connection requires a valid client certificate/);

 # revoked client cert
 $node->connect_fails(
+	expected_stderr =>
 
 # clean up
 
diff --git a/src/test/ssl/t/002_scram.pl b/src/test/ssl/t/002_scram.pl
index e05e60f092..2bfe0b3573 100644
--- a/src/test/ssl/t/002_scram.pl
+++ b/src/test/ssl/t/002_scram.pl
@@ -16,7 +16,26 @@ use lib $FindBin::RealBin;
 
 use SSL::Server;
 
+	plan tests => $supports_tls_server_end_point ? 11 : 12;
+	plan tests => 11;
@@ -26,12 +45,6 @@ my $SERVERHOSTADDR = '127.0.0.1';
 
-my $number_of_tests = $supports_tls_server_end_point ? 11 : 12;
 
@@ -50,7 +63,7 @@ $node->start;
 # Configure server for SSL connections, with password handling.
 configure_test_server_for_ssl($node, $SERVERHOSTADDR, $SERVERHOSTCIDR,
 	"scram-sha-256", "pass", "scram-sha-256");
-switch_server_cert($node, 'server-cn-only');
+switch_server_cert($node, certfile => 'server-cn-only', nssdatabase => 'server-cn-only.crt__server-cn-only.key.db');
 $ENV{PGPASSWORD} = "pass";
 $common_connstr =
   "dbname=trustdb sslmode=require sslcert=invalid sslrootcert=invalid hostaddr=$SERVERHOSTADDR";
@@ -99,7 +112,7 @@ my $client_tmp_key = "ssl/client_scram_tmp.key";
 copy("ssl/client.key", $client_tmp_key);
 chmod 0600, $client_tmp_key;
 $node->connect_fails(
-	"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR dbname=certdb user=ssltestuser channel_binding=require",
+	"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR ssldatabase=ssl/nss/client.crt__client.key.db dbname=certdb user=ssltestuser channel_binding=require",
 	"Cert authentication and channel_binding=require",
 	expected_stderr =>
 	  qr/channel binding required, but server authenticated client without channel binding/
@@ -107,7 +120,7 @@ $node->connect_fails(
 
 # Certificate verification at the connection level should still work fine.
 $node->connect_ok(
-	"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR dbname=verifydb user=ssltestuser",
+	"sslcert=ssl/client.crt sslkey=$client_tmp_key sslrootcert=invalid hostaddr=$SERVERHOSTADDR ssldatabase=ssl/nss/client.crt__client.key.db dbname=verifydb user=ssltestuser",
 	"SCRAM with clientcert=verify-full",
 	log_like => [
 		qr/connection authenticated: identity="ssltestuser" method=scram-sha-256/
diff --git a/src/test/ssl/t/SSL/Backend/NSS.pm b/src/test/ssl/t/SSL/Backend/NSS.pm
new file mode 100644
index 0000000000..20633fe41b
--- /dev/null
+++ b/src/test/ssl/t/SSL/Backend/NSS.pm
@@ -0,0 +1,61 @@
+package SSL::Backend::NSS;
+
+use strict;
+use warnings;
+use Exporter;
+
+our @ISA       = qw(Exporter);
+our @EXPORT_OK = qw(get_new_nss_backend);
+
+sub new
+{
+	my ($class) = @_;
+
+	my $self = { _library => 'NSS' };
+
+	bless $self, $class;
+
+	return $self;
+}
+
+sub get_new_nss_backend
+{
+	my $class = 'SSL::Backend::NSS';
+
+	return $class->new();
+}
+
+sub init
+{
+	# Make sure the certificate databases are in place?
+}
+
+sub get_library
+{
+	my ($self) = @_;
+
+	return $self->{_library};
+}
+
+sub set_server_cert
+{
+	my $self   = $_[0];
+	my $params = $_[1];
+
+	$params->{cafile} = 'root+client_ca' unless defined $params->{cafile};
+
+	my $sslconf =
+	    "ssl_ca_file='$params->{cafile}.crt'\n"
+	  . "ssl_cert_file='ssl/$params->{certfile}.crt'\n"
+	  . "ssl_crl_file=''\n"
+	  . "ssl_database='nss/$params->{nssdatabase}'\n";
+
+	return $sslconf;
+}
+
+sub cleanup
+{
+	# Something?
+}
+
+1;
diff --git a/src/test/ssl/t/SSL/Backend/OpenSSL.pm b/src/test/ssl/t/SSL/Backend/OpenSSL.pm
index e77ee25cc7..9e419b0e0f 100644
--- a/src/test/ssl/t/SSL/Backend/OpenSSL.pm
+++ b/src/test/ssl/t/SSL/Backend/OpenSSL.pm
@@ -71,16 +71,19 @@ sub init
 # the server so that the configuration takes effect.
 sub set_server_cert
 {
-	my $self     = $_[0];
-	my $certfile = $_[1];
-	my $cafile   = $_[2] || "root+client_ca";
-	my $keyfile  = $_[3] || $certfile;
+	my $self   = $_[0];
+	my $params = $_[1];
+
+	$params->{cafile} = 'root+client_ca' unless defined $params->{cafile};
+	$params->{crlfile} = 'root+client.crl' unless defined $params->{crlfile};
+	$params->{keyfile} = $params->{certfile} unless defined $params->{keyfile};
 
 	my $sslconf =
 
 	return $sslconf;
 }
diff --git a/src/test/ssl/t/SSL/Server.pm b/src/test/ssl/t/SSL/Server.pm
index 33bf351476..4972835bc4 100644
--- a/src/test/ssl/t/SSL/Server.pm
+++ b/src/test/ssl/t/SSL/Server.pm
@@ -58,7 +58,6 @@ elsif ($ENV{with_ssl} eq 'nss')
 use Exporter 'import';
 our @EXPORT = qw(
   configure_test_server_for_ssl
-  set_server_cert
   switch_server_cert
 );
 
@@ -170,46 +169,25 @@ sub cleanup
 	$backend->cleanup();
 }

 

From 6f4474c36886f38247189f5b1bac79222ae6e78d Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Sat, 19 Jun 2021 01:37:30 +0200
Subject: [PATCH v43 04/10] test: check for empty stderr during connect_ok()

index 16570a4e2c..bfea8bb8ae 100644

index acd379df31..9457277094 100644
 
index c484237d07..a5afdc8680 100644
 
index f670bc5e0d..d7f49739dd 100644
 
 if ($ENV{with_ldap} eq 'yes')
 {
-	plan tests => 28;
+	plan tests => 40;
 }
 else
 {
diff --git a/src/test/perl/PostgresNode.pm b/src/test/perl/PostgresNode.pm
index c59da758c7..01762be2ff 100644
--- a/src/test/perl/PostgresNode.pm
+++ b/src/test/perl/PostgresNode.pm
@@ -2055,8 +2055,11 @@ sub connect_ok
 
index f961ba9737..dc21ae9d1e 100644
index 2bfe0b3573..0dd286b339 100644

From eca6452fa47df64eeec7c9c38ce996e832ba233b Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:39 +0100
Subject: [PATCH v43 05/10] nss: pg_strong_random support

 
 
 /*
 
 void
-- 
2.25.1

From 2a75e981d45bfdb7a5e56ea77b9d3eb43a83ca96 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:42 +0100
Subject: [PATCH v43 06/10] nss: Documentation

Basic documentation of the new API (keypass hooks) as well as config
parameters and installation. Additionally there is a section on how
to create certificate and keys using the NSS toolchain.
---
 doc/src/sgml/acronyms.sgml     |  33 ++++
 doc/src/sgml/config.sgml       |  30 ++-
 doc/src/sgml/installation.sgml |  31 ++-
 doc/src/sgml/libpq.sgml        | 341 +++++++++++++++++++++++++--------
 doc/src/sgml/runtime.sgml      | 124 +++++++++++-
 src/backend/libpq/README.SSL   |  28 +++
 6 files changed, 494 insertions(+), 93 deletions(-)

diff --git a/doc/src/sgml/acronyms.sgml b/doc/src/sgml/acronyms.sgml
index 9ed148ab84..4da20cb4d3 100644
--- a/doc/src/sgml/acronyms.sgml
+++ b/doc/src/sgml/acronyms.sgml
@@ -452,6 +452,28 @@
     </listitem>
    </varlistentry>
 
+   <varlistentry>
@@ -550,6 +572,17 @@
     </listitem>
    </varlistentry>
 
+   <varlistentry>
+    <term><acronym>PKCS#12</acronym></term>
+    <listitem>
+     <para>
+      <ulink
+      url="https://en.wikipedia.org/wiki/PKCS_12">
+      Public-Key Cryptography Standards #12</ulink>
+     </para>
+    </listitem>
+   </varlistentry>
+
    <varlistentry>
     <term><acronym>PL</acronym></term>
     <listitem>
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 0a8e35c59f..fd1ba4d979 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -1310,6 +1310,24 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
@@ -1326,7 +1344,9 @@ include_dir 'conf.d'
 
@@ -1538,8 +1558,12 @@ include_dir 'conf.d'
        <para>
index 1ebe8482bf..6dab945e07 100644
@@ -999,14 +999,31 @@ build-postgresql:
+            for the required header files and libraries to make sure
 
index b449c834a9..5dbfe9f98c 100644
 
+      <para>

+      <para>

-       <para>
-        more sophisticated uses should consider using <productname>OpenSSL</productname> engines and
@@ -1762,19 +1911,31 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
 
-       <para>
-        The directory needs to be prepared with the
-        <productname>OpenSSL</productname> command
-        <literal>openssl rehash</literal> or <literal>c_rehash</literal>.  See
-        its documentation for details.
-       </para>
+        <itemizedlist>
+         <listitem>
+          <para>
+           <productname>OpenSSL</productname>: the directory needs to be
+           prepared with the <productname>OpenSSL</productname> command
+           <literal>openssl rehash</literal> or <literal>c_rehash</literal>.
+           See its documentation for details.
+          </para>
+          <para>
+           Both <literal>sslcrl</literal> and <literal>sslcrldir</literal> can
+           be specified together.
+          </para>
+         </listitem>
 
-       <para>
 
@@ -1829,8 +1990,8 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
@@ -1845,8 +2006,8 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
@@ -2608,6 +2769,8 @@ void *PQsslStruct(const PGconn *conn, const char *struct_name);
@@ -2631,9 +2794,15 @@ void *PQsslStruct(const PGconn *conn, const char *struct_name);
@@ -2660,6 +2829,10 @@ void *PQgetssl(const PGconn *conn);
 
@@ -8708,6 +8881,12 @@ void PQinitOpenSSL(int do_ssl, int do_crypto);
        before first opening a database connection.  Also be sure that you
        have done that initialization before opening a database connection.
       </para>
+
+      <para>
+       This function does nothing when using <productname>NSS</productname> as
+       the <acronym>SSL</acronym> library, no special initialization is
+       required for <productname>NSS</productname>.
+      </para>
      </listitem>
     </varlistentry>
 
@@ -8734,6 +8913,12 @@ void PQinitSSL(int do_ssl);
        might be preferable for applications that need to work with older
        versions of <application>libpq</application>.
       </para>
+
+      <para>
+       This function does nothing when using <productname>NSS</productname> as
+       the <acronym>SSL</acronym> library, no special initialization is
+       required for <productname>NSS</productname>.
+      </para>
      </listitem>
     </varlistentry>
    </variablelist>
diff --git a/doc/src/sgml/runtime.sgml b/doc/src/sgml/runtime.sgml
index d74d1ed7af..6318daa07f 100644
--- a/doc/src/sgml/runtime.sgml
+++ b/doc/src/sgml/runtime.sgml
@@ -2182,15 +2182,21 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433

   <para>
 
   <sect2 id="ssl-setup">
@@ -2210,8 +2216,13 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </para>
 
   <para>
@@ -2301,6 +2312,18 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </note>
   </sect2>

@@ -2375,7 +2398,7 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </sect2>

    <para>
     <xref linkend="ssl-file-usage"/> summarizes the files that are
@@ -2422,6 +2445,14 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
       <entry>client certificate must not be on this list</entry>
      </row>
 
+     <row>
@@ -2445,7 +2476,7 @@ pg_dumpall -p 5432 | psql -d postgres -p 5433
   </sect2>

    <para>
      To create a simple self-signed certificate for the server, valid for 365
@@ -2549,6 +2580,89 @@ openssl x509 -req -in server.csr -text -days 365 \
    </para>
   </sect2>

  <sect1 id="gssapi-enc">
diff --git a/src/backend/libpq/README.SSL b/src/backend/libpq/README.SSL
index d84a434a6e..c0722b558d 100644
--- a/src/backend/libpq/README.SSL
+++ b/src/backend/libpq/README.SSL
@@ -80,3 +80,31 @@ are unacceptable.
 The downside to EDH is that it makes it impossible to use ssldump(1)
 if there's a problem establishing an SSL session.  In this case you'll
 need to temporarily disable EDH (see initialize_dh()).
+
+
+Supporting a new TLS backend
+============================
+
+TLS support in PostgreSQL is implemented with an API which abstracts any
+knowledge about the library used from core server backend and frontend code.
+Adding support for a new TLS library can be done almost without changing any
+core PostgreSQL code. The modules which needs to be implemented are briefly
+described below.
+
+Each supported TLS library is implemented in its own file for the libpq
+frontend and backend. The API is defined in be-secure.c and fe-secure.c
+respectively. Each library can add relevant connection structures to the
+Port and PGConn objects.
+
+pg_cryptohash is an internal API for invoking cryptographic hash algorithms
+on data. Each supported TLS library implements the API defined in the header
+common/cryptohash.h, with the implementation used decided at build-time.
+
+pg_strong_random provide the backend with a source of cryptographically secure
+random numbers.
+
+contrib/sslinfo provide similar information to pg_stat_ssl, with a few library
+specific extensions.
+
+contrib/pgcrypto provide a larger selection of digest and hash algorithms
+when compiled against a TLS library.
-- 
2.25.1

From 1e9fc1c7003d17608d1307d69f46af5bed1b9075 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:45 +0100
Subject: [PATCH v43 07/10] nss: Support NSS in pgcrypto

This extends pgcrypto to be able to use libnss as a cryptographic
backend for pgcrypto much like how OpenSSL is a supported backend.
Blowfish is not a supported cipher in NSS, so the implementation
falls back on the built-in BF code to be compatible in terms of
cipher support.
---
 contrib/pgcrypto/Makefile  |   7 +-
 contrib/pgcrypto/nss.c     | 753 +++++++++++++++++++++++++++++++++++++
 doc/src/sgml/pgcrypto.sgml |  49 ++-
 3 files changed, 795 insertions(+), 14 deletions(-)
 create mode 100644 contrib/pgcrypto/nss.c

 
 
 SRCS = \
index bbaa2691fe..3cbe41fb9a 100644
 
    <para>
 
    <para>
 
@@ -1248,12 +1267,18 @@ gen_random_uuid() returns uuid
 
-- 
2.25.1

From db7f1345edab0458269923767077adb90d5a9e2e Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:48 +0100
Subject: [PATCH v43 08/10] nss: Support NSS in sslinfo

 
 #include "postgres.h"
 
+#ifdef USE_OPENSSL

 PG_MODULE_MAGIC;
 
+#ifdef USE_OPENSSL

 /*

+#ifdef USE_OPENSSL
 /*
 
+#ifdef USE_NSS
 
 /*

+#ifdef USE_OPENSSL
 /*
 
  <para>
 
  <sect2>

From e37c36ce077fb234a08aa17f21eaf0c4a1731ceb Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:51 +0100
Subject: [PATCH v43 09/10] nss: Support NSS in cryptohash

From 4dc2ae68e3a3fd9cb5ba6398362e8b518e4713e1 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:55 +0100
Subject: [PATCH v43 10/10] nss: Build infrastructure

index 7542fe30a1..3c984b0927 100755
 
 Some influential environment variables:
@@ -12709,8 +12711,274 @@ done

@@ -13681,6 +13949,23 @@ else
 fi

@@ -18540,6 +18825,9 @@ $as_echo_n "checking which random number source to use... " >&6; }
@@ -18569,7 +18857,7 @@ fi
 
index ed3cdb9a8e..68fcc8d4e5 100644
@@ -1234,7 +1234,7 @@ fi
@@ -1268,8 +1268,28 @@ if test "$with_ssl" = openssl ; then
 
@@ -1459,6 +1479,9 @@ fi
 
@@ -2251,6 +2274,8 @@ fi
@@ -2260,7 +2285,7 @@ else
 
diff --git a/src/backend/libpq/Makefile b/src/backend/libpq/Makefile
index 6d385fd6a4..344fdf2e58 100644
--- a/src/backend/libpq/Makefile
+++ b/src/backend/libpq/Makefile
@@ -31,6 +31,10 @@ OBJS = \

 ifeq ($(with_gssapi),yes)
diff --git a/src/common/Makefile b/src/common/Makefile
index 880722fcf5..8a75ca0df3 100644
--- a/src/common/Makefile
+++ b/src/common/Makefile
@@ -85,6 +85,13 @@ OBJS_COMMON += \
 	cryptohash_openssl.o \
 	hmac_openssl.o
 else
+ifeq ($(with_ssl),nss)
+OBJS_COMMON += \
+	hmac.o \
+	cipher_nss.o \
+	protocol_nss.o \
+	cryptohash_nss.o
+else
 OBJS_COMMON += \
 	cryptohash.o \
 	hmac.o \
@@ -92,6 +99,7 @@ OBJS_COMMON += \
 	sha1.o \
 	sha2.o
 endif
+endif
 
index 15ffdd895a..273b7f63d4 100644
@@ -340,6 +340,12 @@

@@ -352,6 +358,9 @@

@@ -926,6 +935,9 @@

index 7cbdeb589b..1fe6155e07 100644
 
+ifeq ($(with_ssl), nss)
+OBJS += \
+	fe-secure-nss.o
+endif
+
index c932322e35..d55611b024 100644
@@ -440,7 +440,8 @@ sub CopyContribFiles
index 4362bd44fd..7dc45c399e 100644
@@ -137,6 +137,12 @@ sub mkvcbuild
@@ -202,12 +208,19 @@ sub mkvcbuild
 
@@ -265,12 +278,19 @@ sub mkvcbuild
 
@@ -438,9 +458,14 @@ sub mkvcbuild

@@ -470,6 +495,11 @@ sub mkvcbuild
index 165a93987a..e2d0cfb1da 100644
@@ -307,10 +307,13 @@ sub GenerateFiles
 		HAVE_LIBLDAP                                => undef,
@@ -499,6 +502,7 @@ sub GenerateFiles
@@ -559,6 +563,13 @@ sub GenerateFiles
 
@@ -1017,6 +1028,21 @@ sub AddProject

---

From: Rachel Heaton <[email-masked]>
Date: Mon, 27 Sep 2021 16:07:19 -0700

> Rebased on top of HEAD with off-list comment fixes by Kevin Burke.

Hello Daniel,

I've been playing with your patch on Mac (OS 11.6 Big Sur) and have
run into a couple of issues so far.

1. I get 7 warnings while running make (truncated):
cryptohash_nss.c:101:21: warning: implicit conversion from enumeration
type 'SECOidTag' to different enumeration type 'HASH_HashType'
[-Wenum-conversion]
                        ctx->hash_type = SEC_OID_SHA1;
                                       ~ ^~~~~~~~~~~~
...
cryptohash_nss.c:134:34: warning: implicit conversion from enumeration
type 'HASH_HashType' to different enumeration type 'SECOidTag'
[-Wenum-conversion]
        hash = SECOID_FindOIDByTag(ctx->hash_type);
               ~~~~~~~~~~~~~~~~~~~ ~~~~~^~~~~~~~~
7 warnings generated.

2. libpq-refs-stamp fails -- it appears an exit is being injected into
libpq on Mac

Notes about my environment:
I've installed nss via homebrew (at version 3.70) and linked it.

Cheers,
Rachel

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 30 Sep 2021 14:17:29 +0200

> On 28 Sep 2021, at 01:07, Rachel Heaton <[email-masked]> wrote:

> type 'SECOidTag' to different enumeration type 'HASH_HashType'

Nice catch, fixed in the attached.

> 2. libpq-refs-stamp fails -- it appears an exit is being injected into

I spent some time investigating this, and there are two cases of _exit() and
one atexit() which are coming from the threading code in libnspr (which is the
runtime lib required by libnss).

On macOS the threading code registers an atexit handler [0] in order to work
around issues with __attribute__((destructor)) [1].  The pthreads code also
defines PR_ProcessExit [2] which does what it says on the tin, calls exit and
not much more [3].  Both of these uses are only compiled when building with
pthreads, which can be disabled in autoconf but that seems broken in recent
version of NSPR.  I'm fairly sure I've built NSPR with the user pthreads in the
past, but if packagers build it like this then we need to conform to that.  The
PR_CreateProcess() [4] call further calls _exit() [5] in a number of error
paths on failing syscalls.

The libpq libnss implementation doesn't call either of these, and neither does
libnss.

I'm not entirely sure what to do here, it clearly requires an exception in the
Makefile check of sorts if we deem we can live with this.

@Jacob: how did you configure your copy of NSPR?

[0] https://hg.mozilla.org/projects/nspr/file/tip/pr/src/pthreads/ptthread.c#l1034
[1] https://bugzilla.mozilla.org/show_bug.cgi?id=1399746#c99
[2] https://www-archive.mozilla.org/projects/nspr/reference/html/prinit.html#15859
[3] https://hg.mozilla.org/projects/nspr/file/tip/pr/src/pthreads/ptthread.c#l1181
[4] https://www-archive.mozilla.org/projects/nspr/reference/html/prprocess.html#24535
[5] https://hg.mozilla.org/projects/nspr/file/tip/pr/src/md/unix/uxproces.c#l268

---

From: Jacob Champion <[email-masked]>
Date: Thu, 30 Sep 2021 16:04:39 +0000

> The libpq libnss implementation doesn't call either of these, and neither does

I thought the refs check only searched for direct symbol dependencies;
is that piece of NSPR being statically included somehow?

> @Jacob: how did you configure your copy of NSPR?

I use the Ubuntu 20.04 builtin (NSPR 4.25.0), but it looks like the
reason I haven't been seeing this is because I've always used --enable-
coverage. If I take that out, I see the same exit check failure.

--Jacob

---

From: Jacob Champion <[email-masked]>
Date: Fri, 1 Oct 2021 00:02:06 +0000

> is that piece of NSPR being statically included somehow?

On my machine, at least, exit() is coming in due to a few calls to
psprintf(), pstrdup(), and pg_malloc() in the new NSS code.
(Disassembly via `objdump -S libpq.so` helped me track those down.) I'm
working on a patch.

--Jacob

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 1 Oct 2021 08:55:59 +0200

> On 1 Oct 2021, at 02:02, Jacob Champion <[email-masked]> wrote:

> (Disassembly via `objdump -S libpq.so` helped me track those down.) I'm

Ah, that makes perfect sense.  I was too focused on hunting in what new was
linked against that I overlooked the obvious.  Thanks for finding these.

---

From: Jacob Champion <[email-masked]>
Date: Mon, 4 Oct 2021 16:14:37 +0000

> linked against that I overlooked the obvious.  Thanks for finding these.

No problem at all :) The exit() check is useful but still a little
opaque, I think, especially since (from my newbie perspective) there's
so much of the pgcommon staticlib that is forbidden for use in libpq.

Fixed in v44, attached; changes in since-v43.diff.txt.

--Jacob
commit 5a9783fc2fdd9ea8723d2cd7c3737b854c12fc25
Author: Jacob Champion <[email-masked]>
Date:   Mon Oct 4 08:59:46 2021 -0700

    Don't use palloc() in front-end code.
    
    - ssl_protocol_version_to_string() returns static allocations for the
      OpenSSL implementation, so do the same here.
    - Use PQExpBuffers for sprintf-style allocation.
    - Use plain malloc() rather than pg_malloc().

diff --git a/src/common/protocol_nss.c b/src/common/protocol_nss.c
index e8225a4d9d..4d12c9f388 100644
--- a/src/common/protocol_nss.c
+++ b/src/common/protocol_nss.c
@@ -39,21 +39,21 @@ ssl_protocol_version_to_string(int v)
 			break;
 
 		case SSL_LIBRARY_VERSION_TLS_1_0:
-			return pstrdup("TLSv1.0");
+			return "TLSv1.0";
 #ifdef SSL_LIBRARY_VERSION_TLS_1_1
 		case SSL_LIBRARY_VERSION_TLS_1_1:
-			return pstrdup("TLSv1.1");
+			return "TLSv1.1";
 #endif
 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
 		case SSL_LIBRARY_VERSION_TLS_1_2:
-			return pstrdup("TLSv1.2");
+			return "TLSv1.2";
 #endif
 #ifdef SSL_LIBRARY_VERSION_TLS_1_3
 		case SSL_LIBRARY_VERSION_TLS_1_3:
-			return pstrdup("TLSv1.3");
+			return "TLSv1.3";
 #endif
 	}
 
-	return pstrdup("unknown");
+	return "unknown";
 }
 
diff --git a/src/interfaces/libpq/fe-secure-nss.c b/src/interfaces/libpq/fe-secure-nss.c
index 51f09fb7fa..e1574997ee 100644
--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -229,12 +229,22 @@ pgtls_open_client(PGconn *conn)
 
 	if (conn->ssldatabase && strlen(conn->ssldatabase) > 0)
 	{
-		char	   *ssldatabase_path = psprintf("sql:%s", conn->ssldatabase);
+		PQExpBufferData ssldatabase_path;
 
-		conn->nss_context = NSS_InitContext(ssldatabase_path, "", "", "",
+		initPQExpBuffer(&ssldatabase_path);
+		appendPQExpBuffer(&ssldatabase_path, "sql:%s", conn->ssldatabase);
+
+		if (PQExpBufferDataBroken(ssldatabase_path))
+		{
+			printfPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("out of memory\n"));
+			return PGRES_POLLING_FAILED;
+		}
+
+		conn->nss_context = NSS_InitContext(ssldatabase_path.data, "", "", "",
 											&params,
 											NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
-		pfree(ssldatabase_path);
+		termPQExpBuffer(&ssldatabase_path);
 
 		if (!conn->nss_context)
 		{
@@ -647,7 +657,14 @@ pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
 		goto cleanup;
 	}
 
-	ret = pg_malloc(digest.len);
+	ret = malloc(digest.len);
+	if (ret == NULL)
+	{
+		appendPQExpBufferStr(&conn->errorMessage,
+							 libpq_gettext("out of memory\n"));
+		goto cleanup;
+	}
+
 	memcpy(ret, digest.data, digest.len);
 	*len = digest_len;
 
@@ -799,9 +816,15 @@ static SECStatus
 pg_load_nss_module(SECMODModule **module, const char *library, const char *name)
 {
 	SECMODModule *mod;
-	char	   *modulespec;
+	PQExpBufferData modulespec;
 
-	modulespec = psprintf("library=\"%s\", name=\"%s\"", library, name);
+	initPQExpBuffer(&modulespec);
+	appendPQExpBuffer(&modulespec, "library=\"%s\", name=\"%s\"", library, name);
+	if (PQExpBufferDataBroken(modulespec))
+	{
+		PR_SetError(SEC_ERROR_NO_MEMORY, 0);
+		return SECFailure;
+	}
 
 	/*
 	 * Attempt to load the specified module. The second parameter is "parent"
@@ -811,8 +834,8 @@ pg_load_nss_module(SECMODModule **module, const char *library, const char *name)
 	 * defined in the modulespec, and since we don't support anything but
 	 * directly addressed modules we should pass PR_FALSE.
 	 */
-	mod = SECMOD_LoadUserModule(modulespec, NULL, PR_FALSE);
-	pfree(modulespec);
+	mod = SECMOD_LoadUserModule(modulespec.data, NULL, PR_FALSE);
+	termPQExpBuffer(&modulespec);
 
 	if (mod && mod->loaded)
 	{
From e8e8a2696e4814e90655ea83076cae6694930d4f Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:22 +0100
Subject: [PATCH v44 01/10] nss: Support libnss as TLS library in libpq

 src/interfaces/libpq/fe-secure-nss.c          | 1223 +++++++++++++
 16 files changed, 3203 insertions(+), 7 deletions(-)

 

+	{
index 0000000000..4d12c9f388
 
 	/*
 
 #ifdef USE_SSL
 
 #endif							/* USE_SSL */

 
 
index 0000000000..e1574997ee
@@ -0,0 +1,1223 @@
+		PQExpBufferData ssldatabase_path;
+		initPQExpBuffer(&ssldatabase_path);
+		appendPQExpBuffer(&ssldatabase_path, "sql:%s", conn->ssldatabase);
+		if (PQExpBufferDataBroken(ssldatabase_path))
+							  libpq_gettext("out of memory\n"));
+		conn->nss_context = NSS_InitContext(ssldatabase_path.data, "", "", "",
+		termPQExpBuffer(&ssldatabase_path);
+	ret = malloc(digest.len);
+	if (ret == NULL)
+							 libpq_gettext("out of memory\n"));
+	PQExpBufferData modulespec;
+	initPQExpBuffer(&modulespec);
+	appendPQExpBuffer(&modulespec, "library=\"%s\", name=\"%s\"", library, name);
+	if (PQExpBufferDataBroken(modulespec))
+		PR_SetError(SEC_ERROR_NO_MEMORY, 0);
+	mod = SECMOD_LoadUserModule(modulespec.data, NULL, PR_FALSE);
+	termPQExpBuffer(&modulespec);
 
+#ifndef USE_NSS
+

 
+#ifdef USE_NSS
+#include "common/nss.h"
+#endif
+
 /*
 
 #ifdef ENABLE_GSS

From 0208f2c2cdcae8eec53acc947f45b0090db34cf2 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:34 +0100
Subject: [PATCH v44 02/10] Refactor SSL testharness for multiple library

 
-use File::Copy;
-
 use FindBin;
 
-use SSLServer;
+use SSL::Server;

 

 

 
 # clean up
-foreach my $key (@keys)
-{
 
-use SSLServer;
+use SSL::Server;

 
 # clean up
 unlink($client_tmp_key);
-
 
-package SSLServer;
+package SSL::Server;
 
 use strict;
 use warnings;
 use PostgresNode;
+use RecursiveCopy;
 use TestLib;
 use File::Basename;
 use File::Copy;
 use Test::More;
 
 use Exporter 'import';
 our @EXPORT = qw(

 

 

From 18e3b2b2d175d44baa06299d2d721782ed9b7480 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:37 +0100
Subject: [PATCH v44 03/10] nss: Add NSS specific tests

 

 

 

 

 
+.PHONY: nssfiles-clean
+nssfiles-clean:
+	rm -rf ssl/nss
+

 use SSL::Server;

 #### Some configuration

 

 
 
 $common_connstr =

 

 

 

 
 
 $common_connstr =
 
 $node->connect_ok(

 $common_connstr =
 
 $node->connect_ok(

 $common_connstr =

 
 $node->connect_ok(

 $common_connstr =

 # pg_stat_ssl
 command_like(

 
 
 $common_connstr =
 
 # no client cert
 $node->connect_fails(

 

-
 
 TODO:
 {

 	$node->connect_fails(
 
+$common_connstr =

 $node->connect_ok(

 $node->connect_ok(

 # revoked client cert
 $node->connect_fails(
 
 # clean up

 use SSL::Server;

 

 	my $sslconf =
 
 	return $sslconf;
 }

 

From a563dc0cc91220edea03caae99c9fcb252979649 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email-masked]>
Date: Sat, 19 Jun 2021 01:37:30 +0200
Subject: [PATCH v44 04/10] test: check for empty stderr during connect_ok()

 

 

From f7c4c55b504448c04448360f0d5d65763abaca15 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:39 +0100
Subject: [PATCH v44 05/10] nss: pg_strong_random support

 
 
 /*
 
 void
-- 
2.25.1

From 5d33e163538c8b496afbc70848f7dbad8a47904e Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:42 +0100
Subject: [PATCH v44 06/10] nss: Documentation

 
+   <varlistentry>
 
+   <varlistentry>

 
 
+      <para>

+      <para>

-       <para>
 
-       <para>
 
-       <para>

 

   <para>
 
   <sect2 id="ssl-setup">
 
   <para>

 
 
    <para>
 
+     <row>

    <para>

  <sect1 id="gssapi-enc">

From c62658ee8b4c3e091c1e68b5063bf44c2bb2b841 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:45 +0100
Subject: [PATCH v44 07/10] nss: Support NSS in pgcrypto

 

 SRCS = \
 
    <para>
 
    <para>

-- 
2.25.1

From 24135e6d9e68131f3600935bf366b3eab6dd5829 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:48 +0100
Subject: [PATCH v44 08/10] nss: Support NSS in sslinfo

 
 #include "postgres.h"
 
+#ifdef USE_OPENSSL

 PG_MODULE_MAGIC;
 
+#ifdef USE_OPENSSL

 /*

+#ifdef USE_OPENSSL
 /*
 
+#ifdef USE_NSS
 
 /*

+#ifdef USE_OPENSSL
 /*
 
  <para>
 
  <sect2>

From a28fb8e265283ab7a3923297e623445ab9cd2891 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:51 +0100
Subject: [PATCH v44 09/10] nss: Support NSS in cryptohash

From 8c391f4a85fd0cd0c2e28d588e89298de838fdd1 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <[email-masked]>
Date: Mon, 8 Feb 2021 23:52:55 +0100
Subject: [PATCH v44 10/10] nss: Build infrastructure

 

 

@@ -1459,6 +1479,9 @@ fi

 

 
 
@@ -352,6 +358,9 @@

@@ -926,6 +935,9 @@

index d98bc07143..bf93498df1 100644
 
+ifeq ($(with_ssl), nss)
+OBJS += \
+	fe-secure-nss.o
+endif
+

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 5 Oct 2021 15:08:18 +0200

> On 4 Oct 2021, at 18:14, Jacob Champion <[email-masked]> wrote:
> 

Thanks!  These changes looks good.  Since you accidentally based this on v43
and not the v44 I posted with the cryptohash fix in, the attached is a v45 with
both your v44 and the previous one, all rebased over HEAD.

---

From: Jacob Champion <[email-masked]>
Date: Tue, 5 Oct 2021 15:05:31 +0000

> both your v44 and the previous one, all rebased over HEAD.

Thanks, and sorry about that.

--Jacob

---

From: Kevin Burke <[email-masked]>
Date: Thu, 28 Oct 2021 21:31:47 -0700

Hi all, apologies but I'm having trouble applying the latest patch (v45) to
the latest commit on master (6b0f6f79eef2168ce38a8ee99c3ed76e3df5d7ad)

I downloaded all of the patches to my local filesystem, and then ran:

for patch in
../../kevinburke/rustls-postgres/patchsets/2021-10-05-gustafsson-mailing-list/*.patch;
do git am $patch; done;

I get the following error on the second patch file:

Applying: Refactor SSL testharness for multiple library
error: patch failed: src/test/ssl/t/001_ssltests.pl:7
error: src/test/ssl/t/001_ssltests.pl: patch does not apply
error: patch failed: src/test/ssl/t/SSLServer.pm:26
error: src/test/ssl/t/SSLServer.pm: patch does not apply
Patch failed at 0001 Refactor SSL testharness for multiple library
hint: Use 'git am --show-current-patch=diff' to see the failed patch

I believe that these patches need to integrate the refactoring in
commit b3b4d8e68ae83f432f43f035c7eb481ef93e1583 - git is searching for the
wrong text in the existing file, but I'm not sure how to submit a patch
against a patch.

Thanks,
Kevin

---

From: Kevin Burke <[email-masked]>
Date: Thu, 28 Oct 2021 21:36:43 -0700

For anyone else trying to test out this branch I'm able to get the patches
to apply cleanly if I check out e.g. commit
92e6a98c3636948e7ece9a3260f9d89dd60da278.

Kevin

--
Kevin Burke
phone: 925-271-7005 | kevin.burke.dev

On Thu, Oct 28, 2021 at 9:31 PM Kevin Burke <[email-masked]> wrote:

> Hi all, apologies but I'm having trouble applying the latest patch (v45)
> to the latest commit on master (6b0f6f79eef2168ce38a8ee99c3ed76e3df5d7ad)
>

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 29 Oct 2021 13:54:29 +0200

> On 29 Oct 2021, at 06:31, Kevin Burke <[email-masked]> wrote:

Thanks for testing the patch!

> I believe that these patches need to integrate the refactoring in commit
> b3b4d8e68ae83f432f43f035c7eb481ef93e1583 - git is searching for the wrong text
> in the existing file

Correct, b3b4d8e68 as well as b4c4a00ea both created conflicts with this
patchset.  Attached is an updated patchset fixing both of those as well as
adding version checks for NSS and NSPR to autoconf (with fallbacks for
non-{nss|nspr}-config systems).  The versions picked are semi-arbitrary and
definitely up for discussion.  I chose them mainly as they were the oldest
commonly available packages I found, and they satisfy the requirements we have.

> I'm not sure how to submit a patch against a patch.

If you've done the work of fixing the conflicts in a rebase, the best option is
IMO to supply a whole new version of the patchset since that will make the CF
patch tester be able to build and test the version.

---

From: Daniel Gustafsson <[email-masked]>
Date: Fri, 5 Nov 2021 11:01:18 +0100

Attached is a rebase fixing a tiny bug in the documentation which prevented it
from being able to compile.

---

From: Joshua Brindle <[email-masked]>
Date: Tue, 9 Nov 2021 13:59:51 -0500

> from being able to compile.

Hello, I'm looking to help out with reviews for this CF and I'm
currently looking at this patchset.

currently I'm stuck trying to configure:

checking for nss-config... /usr/bin/nss-config
checking for nspr-config... /usr/bin/nspr-config
...
checking nss/ssl.h usability... no
checking nss/ssl.h presence... no
checking for nss/ssl.h... no
configure: error: header file <nss/ssl.h> is required for NSS

This is on fedora 33 and nss-devel is installed, nss-config is
available (and configure finds it) but the directory is different from
Ubuntu:
(base) [vagrant@fedora ~]$ nss-config --includedir
/usr/include/nss3
(base) [vagrant@fedora ~]$ ls -al /usr/include/nss3/ssl.h
-rw-r--r--. 1 root root 70450 Sep 30 05:41 /usr/include/nss3/ssl.h

So if nss-config --includedir is used then #include <ssl.h> should be
used, or if not then #include <nss3/ssl.h> but on this system #include
<nss/ssl.h> is not going to work.

Thanks

---

From: Joshua Brindle <[email-masked]>
Date: Tue, 9 Nov 2021 14:02:13 -0500

> <nss/ssl.h> is not going to work.

FYI, if I make a symlink to get past this, configure completes but
compilation fails because nspr/nspr.h cannot be found (I'm not sure
why configure doesn't discover this)
../../src/include/common/nss.h:31:10: fatal error: 'nspr/nspr.h' file not found
#include <nspr/nspr.h>In file included from protocol_nss.c:24:
../../src/include/common/nss.h:31:10: fatal error: 'nspr/nspr.h' file not found
#include <nspr/nspr.h>
 ^~~~~~~~~~~~~

It's a similar issue:
$ nspr-config --includedir
/usr/include/nspr4

---

From: Joshua Brindle <[email-masked]>
Date: Tue, 9 Nov 2021 16:22:59 -0500

> ../../src/include/common/nss.h:31:10: fatal error: 'nspr/nspr.h' file not found

If these get resolved the next issue is llvm bitcode doesn't compile
because the nss includedir is missing from CPPFLAGS:

/usr/bin/clang -Wno-ignored-attributes -fno-strict-aliasing -fwrapv
-O2  -I../../../src/include  -D_GNU_SOURCE -I/usr/include/libxml2
-I/usr/include -flto=thin -emit-llvm -c -o be-secure-nss.bc
be-secure-nss.c
In file included from be-secure-nss.c:20:
In file included from ../../../src/include/common/nss.h:38:
In file included from /usr/include/nss/nss.h:34:
/usr/include/nss/seccomon.h:17:10: fatal error: 'prtypes.h' file not found
#include "prtypes.h"
         ^~~~~~~~~~~
1 error generated.

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 10 Nov 2021 14:49:19 +0100

> On 9 Nov 2021, at 22:22, Joshua Brindle <[email-masked]> wrote:

>>> currently looking at this patchset.

Thanks, much appreciated!

>>> <nss/ssl.h> is not going to work.

Interesting rename, I doubt any version but NSS 3 and NSPR 4 is alive anywhere
and an incremented major version seems highly unlikely.  Going back to plain
#include <ssl.h> and have the includeflags sort out the correct directories
seems like the best option then.  Fixed in the attached.

Fixed.

Fixed.

The attached also resolves the conflicts in pgcrypto following db7d1a7b05.  PGP
elgamel and RSA pubkey functions aren't supported for now as there is no bignum
functions similar to the BN_* in OpenSSL.  I will look into more how hard it
would be to support, for now this gets us ahead.

---

From: Joshua Brindle <[email-masked]>
Date: Mon, 15 Nov 2021 14:51:33 -0500

> Fixed.

Apologies for the delay, this didn't go to my inbox and I missed it on list.

The bitcode generation is still broken, this time for nspr.h:

../../../src/include/common/nss.h:31:10: fatal error: 'nspr.h' file not found
#include <nspr.h>
         ^~~~~~~~
1 error generated.

FWIW I attached the Dockerfile I've been using to test this, primarily
to ensure that there were no openssl devel files lurking around during
compilation.

It expects a ./postgres directory with whatever patches already applied to it.

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 15 Nov 2021 22:44:19 +0100

> On 15 Nov 2021, at 20:51, Joshua Brindle <[email-masked]> wrote:

> The bitcode generation is still broken, this time for nspr.h:

Interesting, I am unable to replicate that in my tree but I'll investigate
further tomorrow using your Dockerfile.  For the sake of testing, does
compilation pass for you in the same place without using --with-llvm?

---

From: Joshua Brindle <[email-masked]>
Date: Mon, 15 Nov 2021 17:37:40 -0500

> compilation pass for you in the same place without using --with-llvm?

Yes, it builds and check-world passes. I'll continue testing with this
build. Thank you.

---

From: Joshua Brindle <[email-masked]>
Date: Tue, 16 Nov 2021 09:45:50 -0500

> Yes, it builds and check-world passes. I'll continue testing with this

The previous Dockerfile had some issues due to a hasty port from RHEL
to Fedora, attached is one that works with your patchset, llvm
currently disabled, and the llvm deps removed.

The service file is also attached since it's referenced in the
Dockerfile and you'd have had to reproduce it.

After building, run with:
docker run --name pg-test -p 5432:5432 --cap-add=SYS_ADMIN -v
/sys/fs/cgroup:/sys/fs/cgroup:ro -d <final docker hash>

---

From: Joshua Brindle <[email-masked]>
Date: Tue, 16 Nov 2021 13:26:37 -0500

> /sys/fs/cgroup:/sys/fs/cgroup:ro -d <final docker hash>

I think there it a typo in the docs here that prevents them from
building (this diff seems to fix it):

diff --git a/doc/src/sgml/pgcrypto.sgml b/doc/src/sgml/pgcrypto.sgml
index 56b73e033c..844aa31e86 100644
--- a/doc/src/sgml/pgcrypto.sgml
+++ b/doc/src/sgml/pgcrypto.sgml
@@ -767,7 +767,7 @@ pgp_sym_encrypt(data, psw, 'compress-algo=1,
cipher-algo=aes256')
    <para>
     Which cipher algorithm to use.  <literal>cast5</literal> is only available
     if <productname>PostgreSQL</productname> was built with
-    <productname>OpenSSL</productame>.
+    <productname>OpenSSL</productname>.
    </para>
 <literallayout>
 Values: bf, aes128, aes192, aes256, 3des, cast5

---

From: Joshua Brindle <[email-masked]>
Date: Wed, 17 Nov 2021 13:42:23 -0500

>  Values: bf, aes128, aes192, aes256, 3des, cast5

After a bit more testing, the server is up and running with an nss
database but before configuring the client database I tried connecting
and got a segfault:

#0  PR_Write (fd=0x0, buf=0x141ba60, amount=84) at
io/../../.././nspr/pr/src/io/priometh.c:114
#1  0x00007ff33dfdc62f in pgtls_write (conn=0x13cecb0, ptr=0x141ba60,
len=84) at fe-secure-nss.c:583
#2  0x00007ff33dfd6e18 in pqsecure_write (conn=0x13cecb0,
ptr=0x141ba60, len=84) at fe-secure.c:295
#3  0x00007ff33dfd04dc in pqSendSome (conn=0x13cecb0, len=84) at fe-misc.c:834
#4  0x00007ff33dfd06c8 in pqFlush (conn=0x13cecb0) at fe-misc.c:972
#5  0x00007ff33dfc257c in pqPacketSend (conn=0x13cecb0, pack_type=0
'\000', buf=0x1414c60, buf_len=80) at fe-connect.c:4619
#6  0x00007ff33dfbfadd in PQconnectPoll (conn=0x13cecb0) at fe-connect.c:2986
#7  0x00007ff33dfbe55c in connectDBComplete (conn=0x13cecb0) at
fe-connect.c:2218
#8  0x00007ff33dfbbaef in PQconnectdbParams (keywords=0x1427d10,
values=0x1427e60, expand_dbname=1) at fe-connect.c:668
#9  0x000000000043ebc7 in main (argc=2, argv=0x7ffdccd0e2f8) at startup.c:273

It looks like the ssl connection falls through to attempt a non-ssl
connection but at some point conn->ssl_in_use gets set to true,
despite pr_fd and nss_context being null.

This patch fixes the segfault but I suspect is not the correct fix,
due to the error when connecting saying "Success":

--- a/src/interfaces/libpq/fe-secure-nss.c
+++ b/src/interfaces/libpq/fe-secure-nss.c
@@ -498,6 +498,11 @@ pgtls_read(PGconn *conn, void *ptr, size_t len)
         * for closed connections, while -1 indicates an error within
the ongoing
         * connection.
         */
+       if (!conn->pr_fd) {
+               SOCK_ERRNO_SET(read_errno);
+               return -1;
+       }
+
        nread = PR_Recv(conn->pr_fd, ptr, len, 0, PR_INTERVAL_NO_WAIT);

        if (nread == 0)
@@ -580,6 +585,11 @@ pgtls_write(PGconn *conn, const void *ptr, size_t len)
        PRErrorCode status;
        int                     write_errno = 0;

+       if (!conn->pr_fd) {
+               SOCK_ERRNO_SET(write_errno);
+               return -1;
+       }
+
        n = PR_Write(conn->pr_fd, ptr, len);

        if (n < 0)

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 23 Nov 2021 15:12:45 +0100

> On 17 Nov 2021, at 19:42, Joshua Brindle <[email-masked]> wrote:

>> building (this diff seems to fix it):

Ah yes, thanks, I had noticed that one but forgot to send out a new version to
make the CFBot green.

> database but before configuring the client database I tried connecting

Interesting.  I'm unable to reproduce this crash, can you show the sequence of
commands which led to this?

> despite pr_fd and nss_context being null.

pgtls_close missed setting ssl_in_use to false, fixed in the attached.  I've
also added some assertions to the connection setup for debugging this.

> due to the error when connecting saying "Success":

Right, without an SSL enabled FD we should never get here.

---

From: Joshua Brindle <[email-masked]>
Date: Tue, 23 Nov 2021 17:39:12 -0500

> commands which led to this?

It no longer happens with v49, since it was a null deref of the pr_fd
which no longer happens.

I'll continue testing now, so far it's looking better.

Did the build issue with --with-llvm get fixed in this update also? I
haven't tried building with it yet.

> Right, without an SSL enabled FD we should never get here.

Thank you.

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 24 Nov 2021 12:59:56 +0100

> On 23 Nov 2021, at 23:39, Joshua Brindle <[email-masked]> wrote:

> I'll continue testing now, so far it's looking better.

Great, thanks for confirming.  I'm still keen on knowing how you triggered the
segfault so I can ensure there are no further bugs around there.

---

From: Joshua Brindle <[email-masked]>
Date: Wed, 24 Nov 2021 08:46:35 -0500

> segfault so I can ensure there are no further bugs around there.

It happened when I ran psql with hostssl on the server but before I'd
initialized my client certificate store.

---

From: Joshua Brindle <[email-masked]>
Date: Wed, 24 Nov 2021 08:49:10 -0500

> initialized my client certificate store.

I don't know enough about NSS to know if this is problematic or not
but if I try verify-full without having the root CA in the certificate
store I get:

$ /usr/pgsql-15/bin/psql "host=localhost sslmode=verify-full user=postgres"
psql: error: SSL error: Issuer certificate is invalid.
unable to shut down NSS context: NSS could not shutdown. Objects are
still in use.

---

From: Joshua Brindle <[email-masked]>
Date: Thu, 25 Nov 2021 08:39:29 -0500

> unable to shut down NSS context: NSS could not shutdown. Objects are

Something is strange with ssl downgrading and a bad ssldatabase
[postgres@11cdfa30f763 ~]$ /usr/pgsql-15/bin/psql "ssldatabase=oops
sslcert=client_cert host=localhost"
Password for user postgres:

<freezes here>

On the server side:
2021-11-25 01:52:01.984 UTC [269] LOG:  unable to handshake:
Encountered end of file (PR_END_OF_FILE_ERROR)

Other than that and I still haven't tested --with-llvm I've gotten
everything working, including with an openssl client. Attached is a
dockerfile that gets to the point where a client can connect with
clientcert=verify-full. I've removed some of the old cruft and
debugging from the previous versions.

Thank you.

---

From: Jacob Champion <[email-masked]>
Date: Tue, 30 Nov 2021 19:03:54 +0000

> > take a look at a patch for next commitfest.

Didn't get around to it for November, but I'm putting the finishing
touches on that now.

While I was looking at the new SAN code (in fe-secure-nss.c,
pgtls_verify_peer_name_matches_certificate_guts()), I noticed that code

> +        for (cn = san_list; cn != san_list; cn = CERT_GetNextGeneralName(cn))

That loop can never execute. But I wonder if all of that extra SAN code

> +	 * CERT_VerifyCertName will internally perform RFC 2818 SubjectAltName

and it seems like SAN verification is working in my testing, despite
the dead loop.

--Jacob

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 15 Dec 2021 23:05:43 +0100

> On 25 Nov 2021, at 14:39, Joshua Brindle <[email-masked]> wrote:

Fixed.

> Password for user postgres:

Also fixed.

> Encountered end of file (PR_END_OF_FILE_ERROR)

This is normal and expected, but to make it easier on users I've changed this
error message to be aligned with the OpenSSL implementation.

> debugging from the previous versions.

Very cool, thanks!  I've been unable to reproduce any issues with llvm but I'll
keep poking at that.  A new version will be posted shortly with the above and a
few more fixes.

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 15 Dec 2021 23:10:14 +0100

> On 30 Nov 2021, at 20:03, Jacob Champion <[email-masked]> wrote:
> 

Cool, thanks!

> and it seems like SAN verification is working in my testing, despite

Yeah, that's clearly bogus.  I followed the bouncing ball reading NSS code and
from what I can tell the comment is correct.  I removed the dead code, only
realizing after the fact that I might cause conflict with your tree doing so,
in that case sorry.

I've attached a v50 which fixes the issues found by Joshua upthread, as well as
rebases on top of all the recent SSL and pgcrypto changes.

---

From: Jacob Champion <[email-masked]>
Date: Thu, 16 Dec 2021 19:56:25 +0000

> > Didn't get around to it for November, but I'm putting the finishing

Done and registered in Commitfest.

> realizing after the fact that I might cause conflict with your tree doing so,

No worries, there weren't any issues with the rebase.

Thanks!

--Jacob

---

From: Joshua Brindle <[email-masked]>
Date: Mon, 20 Dec 2021 12:27:11 -0500

> keep poking at that.  A new version will be posted shortly with the above and a

For v50 this change was required for an llvm build to succeed on my
Fedora system:

diff --git a/configure b/configure
index 25388a75a2..62d554806a 100755
--- a/configure
+++ b/configure
@@ -13276,6 +13276,7 @@ fi

   LDFLAGS="$LDFLAGS $NSS_LIBS $NSPR_LIBS"
   CFLAGS="$CFLAGS $NSS_CFLAGS $NSPR_CFLAGS"
+  CPPFLAGS="$CPPFLAGS $NSS_CFLAGS $NSPR_CFLAGS"

 $as_echo "#define USE_NSS 1" >>confdefs.h

I'm not certain why configure didn't already have that, configure.ac
appears to, but nonetheless it builds, all tests succeed, and a quick
tire kicking looks good.

Thank you.