Index: postgresql/src/backend/libpq/pqcomm.c diff -c postgresql/src/backend/libpq/pqcomm.c:1.1.1.1 postgresql/src/backend/libpq/pqcomm.c:1.2 *** postgresql/src/backend/libpq/pqcomm.c:1.1.1.1 Thu May 23 22:56:05 2002 --- postgresql/src/backend/libpq/pqcomm.c Fri May 24 12:41:53 2002 *************** *** 29,35 **** * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * ! * $Id: pqcomm.c,v 1.1.1.1 2002/05/24 04:56:05 bear Exp $ * *------------------------------------------------------------------------- */ --- 29,35 ---- * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * ! * $Id: pqcomm.c,v 1.2 2002/05/24 18:41:53 bear Exp $ * *------------------------------------------------------------------------- */ *************** *** 80,85 **** --- 80,88 ---- #include "libpq/libpq.h" #include "miscadmin.h" + extern void secure_close(Port *); + extern ssize_t secure_read(Port *, void *, size_t); + extern ssize_t secure_write(Port *, const void *, size_t); static void pq_close(void); *************** *** 137,142 **** --- 140,146 ---- { if (MyProcPort != NULL) { + secure_close(MyProcPort); close(MyProcPort->sock); /* make sure any subsequent attempts to do I/O fail cleanly */ MyProcPort->sock = -1; *************** *** 489,502 **** { int r; ! #ifdef USE_SSL ! if (MyProcPort->ssl) ! r = SSL_read(MyProcPort->ssl, PqRecvBuffer + PqRecvLength, ! PQ_BUFFER_SIZE - PqRecvLength); ! else ! #endif ! r = recv(MyProcPort->sock, PqRecvBuffer + PqRecvLength, ! PQ_BUFFER_SIZE - PqRecvLength, 0); if (r < 0) { --- 493,500 ---- { int r; ! r = secure_read(MyProcPort, PqRecvBuffer + PqRecvLength, ! PQ_BUFFER_SIZE - PqRecvLength); if (r < 0) { *************** *** 664,675 **** { int r; ! #ifdef USE_SSL ! if (MyProcPort->ssl) ! r = SSL_write(MyProcPort->ssl, bufptr, bufend - bufptr); ! else ! #endif ! r = send(MyProcPort->sock, bufptr, bufend - bufptr, 0); if (r <= 0) { --- 662,668 ---- { int r; ! r = secure_write(MyProcPort, bufptr, bufend - bufptr); if (r <= 0) { Index: postgresql/src/backend/postmaster/Makefile diff -c postgresql/src/backend/postmaster/Makefile:1.1.1.1 postgresql/src/backend/postmaster/Makefile:1.2 *** postgresql/src/backend/postmaster/Makefile:1.1.1.1 Thu May 23 22:56:08 2002 --- postgresql/src/backend/postmaster/Makefile Fri May 24 12:41:53 2002 *************** *** 4,10 **** # Makefile for postmaster # # IDENTIFICATION ! # $Header: /usr/local/cvsroot/postgresql/src/backend/postmaster/Makefile,v 1.1.1.1 2002/05/24 04:56:08 bear Exp $ # #------------------------------------------------------------------------- --- 4,10 ---- # Makefile for postmaster # # IDENTIFICATION ! # $Header: /usr/local/cvsroot/postgresql/src/backend/postmaster/Makefile,v 1.2 2002/05/24 18:41:53 bear Exp $ # #------------------------------------------------------------------------- *************** *** 12,18 **** top_builddir = ../../.. include $(top_builddir)/src/Makefile.global ! OBJS = postmaster.o pgstat.o all: SUBSYS.o --- 12,18 ---- top_builddir = ../../.. include $(top_builddir)/src/Makefile.global ! OBJS = postmaster.o pgstat.o be-secure.o all: SUBSYS.o Index: postgresql/src/backend/postmaster/be-secure.c diff -c /dev/null postgresql/src/backend/postmaster/be-secure.c:1.4 *** /dev/null Fri May 24 21:52:23 2002 --- postgresql/src/backend/postmaster/be-secure.c Fri May 24 21:44:30 2002 *************** *** 0 **** --- 1,365 ---- + /*------------------------------------------------------------------------- + * + * be-connect.c + * functions related to setting up a secure connection to the frontend. + * Secure connections are expected to provide confidentiality, + * message integrity and endpoint authentication. + * + * + * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * + * IDENTIFICATION + * $Header: /usr/local/cvsroot/postgresql/src/backend/postmaster/be-secure.c,v 1.4 2002/05/25 03:44:30 bear Exp $ + * + * PATCH LEVEL + * milestone 1: fix basic coding errors + * [*] existing SSL code pulled out of existing files. + * [*] SSL_get_error() after SSL_read() and SSL_write(), + * SSL_shutdown(), default to TLSv1. + * + * milestone 2: provide endpoint authentication (server) + * [*] client verifies server cert + * [*] client verifies server hostname + * + * milestone 3: improve confidentially, support perfect forward secrecy + * [ ] use 'random' file, read from '/dev/urandom?' + * [ ] emphermal DH keys, default values + * [ ] periodic renegotiation + * + * milestone 4: provide endpoint authentication (client) + * [ ] server verifies client certificates + * + * milestone 5: provide informational callbacks + * [ ] provide informational callbacks + * + * other changes + * [ ] tcp-wrappers + * [ ] more informative psql + * + *------------------------------------------------------------------------- + */ + + #include "postgres.h" + + #include + #include + #include + #include + #include + + #include "libpq/libpq.h" + #include "libpq/pqsignal.h" + #include "miscadmin.h" + + #ifdef WIN32 + #include "win32.h" + #else + #include + #include + #include + #include + #ifdef HAVE_NETINET_TCP_H + #include + #endif + #include + #endif + + + #ifndef HAVE_STRDUP + #include "strdup.h" + #endif + + #ifdef USE_SSL + #include + #include + #endif + + extern void ExitPostmaster(int); + extern void postmaster_error(const char *fmt,...); + + int secure_initialize(void); + void secure_destroy(void); + int secure_open_server(Port *); + void secure_close(Port *); + ssize_t secure_read(Port *, void *ptr, size_t len); + ssize_t secure_write(Port *, const void *ptr, size_t len); + + #ifdef USE_SSL + static int initialize_SSL(void); + static void destroy_SSL(void); + static int open_server_SSL(Port *); + static void close_SSL(Port *); + static const char *SSLerrmessage(void); + #endif + + #ifdef USE_SSL + static SSL_CTX *SSL_context = NULL; + #endif + + /* ------------------------------------------------------------ */ + /* Procedures common to all secure sessions */ + /* ------------------------------------------------------------ */ + + /* + * Initialize global context + */ + int + secure_initialize (void) + { + int r = 0; + + #ifdef USE_SSL + r = initialize_SSL(); + #endif + + return r; + } + + /* + * Destroy global context + */ + void + secure_destroy (void) + { + #ifdef USE_SSL + destroy_SSL(); + #endif + } + + /* + * Attempt to negotiate secure session. + */ + int + secure_open_server (Port *port) + { + int r = 0; + + #ifdef USE_SSL + r = open_server_SSL(port); + #endif + + return r; + } + + /* + * Close secure session. + */ + void + secure_close (Port *port) + { + #ifdef USE_SSL + if (port->ssl) + close_SSL(port); + #endif + } + + /* + * Read data from a secure connection. + */ + ssize_t + secure_read (Port *port, void *ptr, size_t len) + { + ssize_t n; + + #ifdef USE_SSL + if (port->ssl) + { + n = SSL_read(port->ssl, ptr, len); + switch (SSL_get_error(port->ssl, n)) + { + case SSL_ERROR_NONE: + break; + case SSL_ERROR_WANT_READ: + break; + case SSL_ERROR_SYSCALL: + errno = get_last_socket_error(); + elog(ERROR, "SSL SYSCALL error: %s", strerror(errno)); + break; + case SSL_ERROR_SSL: + elog(ERROR, "SSL error: %s", SSLerrmessage()); + /* fall through */ + case SSL_ERROR_ZERO_RETURN: + secure_close(port); + errno = ECONNRESET; + n = -1; + break; + } + } + else + #endif + n = recv(port->sock, ptr, len, 0); + + return n; + } + + /* + * Write data to a secure connection. + */ + ssize_t + secure_write (Port *port, const void *ptr, size_t len) + { + ssize_t n; + + #ifndef WIN32 + pqsigfunc oldsighandler = pqsignal(SIGPIPE, SIG_IGN); + #endif + + #ifdef USE_SSL + if (port->ssl) + { + n = SSL_write(port->ssl, ptr, len); + switch (SSL_get_error(port->ssl, n)) + { + case SSL_ERROR_NONE: + break; + case SSL_ERROR_WANT_WRITE: + break; + case SSL_ERROR_SYSCALL: + errno = get_last_socket_error(); + elog(ERROR, "SSL SYSCALL error: %s", strerror(errno)); + break; + case SSL_ERROR_SSL: + elog(ERROR, "SSL error: %s", SSLerrmessage()); + /* fall through */ + case SSL_ERROR_ZERO_RETURN: + secure_close(port); + errno = ECONNRESET; + n = -1; + break; + } + } + else + #endif + n = send(port->sock, ptr, len, 0); + + #ifndef WIN32 + pqsignal(SIGPIPE, oldsighandler); + #endif + + return n; + } + + /* ------------------------------------------------------------ */ + /* SSL specific code */ + /* ------------------------------------------------------------ */ + #ifdef USE_SSL + /* + * Initialize global SSL context. + */ + static int + initialize_SSL (void) + { + char fnbuf[2048]; + + if (!SSL_context) + { + SSL_library_init(); + SSL_load_error_strings(); + SSL_context = SSL_CTX_new(TLSv1_method()); + if (!SSL_context) + { + postmaster_error("failed to create SSL context: %s", + SSLerrmessage()); + ExitPostmaster(1); + } + + /* + * Load and verify certificate and private key + */ + snprintf(fnbuf, sizeof(fnbuf), "%s/server.crt", DataDir); + if (!SSL_CTX_use_certificate_file(SSL_context, fnbuf, SSL_FILETYPE_PEM)) + { + postmaster_error("failed to load server certificate (%s): %s", + fnbuf, SSLerrmessage()); + ExitPostmaster(1); + } + snprintf(fnbuf, sizeof(fnbuf), "%s/server.key", DataDir); + if (!SSL_CTX_use_PrivateKey_file(SSL_context, fnbuf, SSL_FILETYPE_PEM)) + { + postmaster_error("failed to load private key file (%s): %s", + fnbuf, SSLerrmessage()); + ExitPostmaster(1); + } + if (!SSL_CTX_check_private_key(SSL_context)) + { + postmaster_error("check of private key failed: %s", + SSLerrmessage()); + ExitPostmaster(1); + } + } + + return 0; + } + + /* + * Destroy global SSL context. + */ + static void + destroy_SSL (void) + { + if (SSL_context) + { + SSL_CTX_free(SSL_context); + SSL_context = NULL; + } + } + + /* + * Attempt to negotiate SSL connection. + */ + static int + open_server_SSL (Port *port) + { + if (!(port->ssl = SSL_new(SSL_context)) || + !SSL_set_fd(port->ssl, port->sock) || + SSL_accept(port->ssl) <= 0) + { + elog(ERROR, "failed to initialize SSL connection: %s", SSLerrmessage()); + close_SSL(port); + return -1; + } + + return 0; + } + + /* + * Close SSL connection. + */ + static void + close_SSL (Port *port) + { + if (port->ssl) + { + SSL_shutdown(port->ssl); + SSL_free(port->ssl); + port->ssl = NULL; + } + } + + /* + * Obtain reason string for last SSL error + * + * Some caution is needed here since ERR_reason_error_string will + * return NULL if it doesn't recognize the error code. We don't + * want to return NULL ever. + */ + static const char * + SSLerrmessage(void) + { + unsigned long errcode; + const char *errreason; + static char errbuf[32]; + + errcode = ERR_get_error(); + if (errcode == 0) + return "No SSL error reported"; + errreason = ERR_reason_error_string(errcode); + if (errreason != NULL) + return errreason; + snprintf(errbuf, sizeof(errbuf), "SSL error code %lu", errcode); + return errbuf; + } + + #endif /* USE_SSL */ Index: postgresql/src/backend/postmaster/postmaster.c diff -c postgresql/src/backend/postmaster/postmaster.c:1.1.1.1 postgresql/src/backend/postmaster/postmaster.c:1.2 *** postgresql/src/backend/postmaster/postmaster.c:1.1.1.1 Thu May 23 22:56:08 2002 --- postgresql/src/backend/postmaster/postmaster.c Fri May 24 12:41:53 2002 *************** *** 37,43 **** * * * IDENTIFICATION ! * $Header: /usr/local/cvsroot/postgresql/src/backend/postmaster/postmaster.c,v 1.1.1.1 2002/05/24 04:56:08 bear Exp $ * * NOTES * --- 37,43 ---- * * * IDENTIFICATION ! * $Header: /usr/local/cvsroot/postgresql/src/backend/postmaster/postmaster.c,v 1.2 2002/05/24 18:41:53 bear Exp $ * * NOTES * *************** *** 165,174 **** static int ServerSock_UNIX = INVALID_SOCK; /* stream socket server */ #endif - #ifdef USE_SSL - static SSL_CTX *SSL_context = NULL; /* Global SSL context */ - #endif - /* * Set by the -o option */ --- 165,170 ---- *************** *** 242,248 **** static void CleanupProc(int pid, int exitstatus); static void LogChildExit(const char *procname, int pid, int exitstatus); static int DoBackend(Port *port); ! static void ExitPostmaster(int status); static void usage(const char *); static int ServerLoop(void); static int BackendStartup(Port *port); --- 238,244 ---- static void CleanupProc(int pid, int exitstatus); static void LogChildExit(const char *procname, int pid, int exitstatus); static int DoBackend(Port *port); ! void ExitPostmaster(int status); static void usage(const char *); static int ServerLoop(void); static int BackendStartup(Port *port); *************** *** 261,267 **** static int CountChildren(void); static bool CreateOptsFile(int argc, char *argv[]); static pid_t SSDataBase(int xlop); ! static void postmaster_error(const char *fmt,...) /* This lets gcc check the format string for consistency. */ __attribute__((format(printf, 1, 2))); --- 257,263 ---- static int CountChildren(void); static bool CreateOptsFile(int argc, char *argv[]); static pid_t SSDataBase(int xlop); ! void postmaster_error(const char *fmt,...) /* This lets gcc check the format string for consistency. */ __attribute__((format(printf, 1, 2))); *************** *** 271,279 **** #define ShutdownDataBase() SSDataBase(BS_XLOG_SHUTDOWN) #ifdef USE_SSL ! static void InitSSL(void); ! static const char *SSLerrmessage(void); ! #endif static void --- 267,277 ---- #define ShutdownDataBase() SSDataBase(BS_XLOG_SHUTDOWN) #ifdef USE_SSL ! extern int secure_initialize(void); ! extern void secure_destroy(void); ! extern int secure_open_server(Port *); ! extern void secure_close(Port *); ! #endif /* USE_SSL */ static void *************** *** 642,648 **** ExitPostmaster(1); } if (EnableSSL) ! InitSSL(); #endif /* --- 640,646 ---- ExitPostmaster(1); } if (EnableSSL) ! secure_initialize(); #endif /* *************** *** 1116,1127 **** #ifdef USE_SSL if (SSLok == 'S') { ! if (!(port->ssl = SSL_new(SSL_context)) || ! !SSL_set_fd(port->ssl, port->sock) || ! SSL_accept(port->ssl) <= 0) { - elog(DEBUG, "failed to initialize SSL connection: %s (%m)", - SSLerrmessage()); return STATUS_ERROR; } } --- 1114,1121 ---- #ifdef USE_SSL if (SSLok == 'S') { ! if (secure_open_server(port) == -1) { return STATUS_ERROR; } } *************** *** 1329,1336 **** ConnFree(Port *conn) { #ifdef USE_SSL ! if (conn->ssl) ! SSL_free(conn->ssl); #endif free(conn); } --- 1323,1329 ---- ConnFree(Port *conn) { #ifdef USE_SSL ! secure_close(conn); #endif free(conn); } *************** *** 2248,2254 **** * * Do NOT call exit() directly --- always go through here! */ ! static void ExitPostmaster(int status) { /* should cleanup shared memory and kill all backends */ --- 2241,2247 ---- * * Do NOT call exit() directly --- always go through here! */ ! void ExitPostmaster(int status) { /* should cleanup shared memory and kill all backends */ *************** *** 2426,2499 **** return cnt; } - #ifdef USE_SSL - /* - * Initialize SSL library and structures - */ - static void - InitSSL(void) - { - char fnbuf[2048]; - - SSL_load_error_strings(); - SSL_library_init(); - SSL_context = SSL_CTX_new(SSLv23_method()); - if (!SSL_context) - { - postmaster_error("failed to create SSL context: %s", - SSLerrmessage()); - ExitPostmaster(1); - } - snprintf(fnbuf, sizeof(fnbuf), "%s/server.crt", DataDir); - if (!SSL_CTX_use_certificate_file(SSL_context, fnbuf, SSL_FILETYPE_PEM)) - { - postmaster_error("failed to load server certificate (%s): %s", - fnbuf, SSLerrmessage()); - ExitPostmaster(1); - } - snprintf(fnbuf, sizeof(fnbuf), "%s/server.key", DataDir); - if (!SSL_CTX_use_PrivateKey_file(SSL_context, fnbuf, SSL_FILETYPE_PEM)) - { - postmaster_error("failed to load private key file (%s): %s", - fnbuf, SSLerrmessage()); - ExitPostmaster(1); - } - if (!SSL_CTX_check_private_key(SSL_context)) - { - postmaster_error("check of private key failed: %s", - SSLerrmessage()); - ExitPostmaster(1); - } - } - - /* - * Obtain reason string for last SSL error - * - * Some caution is needed here since ERR_reason_error_string will - * return NULL if it doesn't recognize the error code. We don't - * want to return NULL ever. - */ - static const char * - SSLerrmessage(void) - { - unsigned long errcode; - const char *errreason; - static char errbuf[32]; - - errcode = ERR_get_error(); - if (errcode == 0) - return "No SSL error reported"; - errreason = ERR_reason_error_string(errcode); - if (errreason != NULL) - return errreason; - snprintf(errbuf, sizeof(errbuf), "SSL error code %lu", errcode); - return errbuf; - } - - #endif /* USE_SSL */ - - /* * Fire off a subprocess for startup/shutdown/checkpoint. * * Return value is subprocess' PID, or 0 if failed to start subprocess --- 2419,2425 ---- *************** *** 2684,2690 **** } ! static void postmaster_error(const char *fmt,...) { va_list ap; --- 2610,2616 ---- } ! void postmaster_error(const char *fmt,...) { va_list ap; Index: postgresql/src/interfaces/libpq/Makefile diff -c postgresql/src/interfaces/libpq/Makefile:1.1.1.1 postgresql/src/interfaces/libpq/Makefile:1.2 *** postgresql/src/interfaces/libpq/Makefile:1.1.1.1 Thu May 23 22:56:22 2002 --- postgresql/src/interfaces/libpq/Makefile Fri May 24 12:41:53 2002 *************** *** 4,10 **** # # Copyright (c) 1994, Regents of the University of California # ! # $Header: /usr/local/cvsroot/postgresql/src/interfaces/libpq/Makefile,v 1.1.1.1 2002/05/24 04:56:22 bear Exp $ # #------------------------------------------------------------------------- --- 4,10 ---- # # Copyright (c) 1994, Regents of the University of California # ! # $Header: /usr/local/cvsroot/postgresql/src/interfaces/libpq/Makefile,v 1.2 2002/05/24 18:41:53 bear Exp $ # #------------------------------------------------------------------------- *************** *** 20,26 **** override CPPFLAGS := -I$(srcdir) $(CPPFLAGS) -DFRONTEND -DSYSCONFDIR='"$(sysconfdir)"' OBJS= fe-auth.o fe-connect.o fe-exec.o fe-misc.o fe-print.o fe-lobj.o \ ! pqexpbuffer.o dllist.o md5.o pqsignal.o \ $(INET_ATON) $(SNPRINTF) $(STRERROR) ifdef MULTIBYTE --- 20,26 ---- override CPPFLAGS := -I$(srcdir) $(CPPFLAGS) -DFRONTEND -DSYSCONFDIR='"$(sysconfdir)"' OBJS= fe-auth.o fe-connect.o fe-exec.o fe-misc.o fe-print.o fe-lobj.o \ ! pqexpbuffer.o dllist.o md5.o pqsignal.o fe-secure.o \ $(INET_ATON) $(SNPRINTF) $(STRERROR) ifdef MULTIBYTE Index: postgresql/src/interfaces/libpq/fe-connect.c diff -c postgresql/src/interfaces/libpq/fe-connect.c:1.1.1.1 postgresql/src/interfaces/libpq/fe-connect.c:1.2 *** postgresql/src/interfaces/libpq/fe-connect.c:1.1.1.1 Thu May 23 22:56:22 2002 --- postgresql/src/interfaces/libpq/fe-connect.c Fri May 24 12:41:53 2002 *************** *** 8,14 **** * * * IDENTIFICATION ! * $Header: /usr/local/cvsroot/postgresql/src/interfaces/libpq/fe-connect.c,v 1.1.1.1 2002/05/24 04:56:22 bear Exp $ * *------------------------------------------------------------------------- */ --- 8,14 ---- * * * IDENTIFICATION ! * $Header: /usr/local/cvsroot/postgresql/src/interfaces/libpq/fe-connect.c,v 1.2 2002/05/24 18:41:53 bear Exp $ * *------------------------------------------------------------------------- */ *************** *** 61,69 **** } #endif - #ifdef USE_SSL ! static SSL_CTX *SSL_context = NULL; #endif #define NOTIFYLIST_INITIAL_SIZE 10 --- 61,72 ---- } #endif #ifdef USE_SSL ! extern int secure_initialize(PGconn *); ! extern void secure_destroy(void); ! extern int secure_open_client(PGconn *); ! extern void secure_close(PGconn *); ! extern SSL * PQgetssl(PGconn *); #endif #define NOTIFYLIST_INITIAL_SIZE 10 *************** *** 186,196 **** static void defaultNoticeProcessor(void *arg, const char *message); static int parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage); - #ifdef USE_SSL - static const char *SSLerrmessage(void); - #endif - /* * Connecting to a Database * --- 189,195 ---- *************** *** 955,980 **** } if (SSLok == 'S') { ! if (!SSL_context) { - SSL_load_error_strings(); - SSL_library_init(); - SSL_context = SSL_CTX_new(SSLv23_method()); - if (!SSL_context) - { - printfPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not create SSL context: %s\n"), - SSLerrmessage()); - goto connect_errReturn; - } - } - if (!(conn->ssl = SSL_new(SSL_context)) || - !SSL_set_fd(conn->ssl, conn->sock) || - SSL_connect(conn->ssl) <= 0) - { - printfPQExpBuffer(&conn->errorMessage, - libpq_gettext("could not establish SSL connection: %s\n"), - SSLerrmessage()); goto connect_errReturn; } /* SSL connection finished. Continue to send startup packet */ --- 954,961 ---- } if (SSLok == 'S') { ! if (secure_initialize(conn) == -1 || secure_open_client(conn) == -1) { goto connect_errReturn; } /* SSL connection finished. Continue to send startup packet */ *************** *** 984,989 **** --- 965,971 ---- /* Received error - probably protocol mismatch */ if (conn->Pfdebug) fprintf(conn->Pfdebug, "Postmaster reports error, attempting fallback to pre-7.0.\n"); + secure_close(conn); #ifdef WIN32 closesocket(conn->sock); #else *************** *** 1025,1030 **** --- 1007,1013 ---- connect_errReturn: if (conn->sock >= 0) { + secure_close(conn); #ifdef WIN32 closesocket(conn->sock); #else *************** *** 1900,1907 **** return; pqClearAsyncResult(conn); /* deallocate result and curTuple */ #ifdef USE_SSL ! if (conn->ssl) ! SSL_free(conn->ssl); #endif if (conn->sock >= 0) { --- 1883,1889 ---- return; pqClearAsyncResult(conn); /* deallocate result and curTuple */ #ifdef USE_SSL ! secure_close(conn); #endif if (conn->sock >= 0) { *************** *** 1978,1983 **** --- 1960,1966 ---- */ if (conn->sock >= 0) { + secure_close(conn); #ifdef WIN32 closesocket(conn->sock); #else *************** *** 2619,2653 **** } - #ifdef USE_SSL - - /* - * Obtain reason string for last SSL error - * - * Some caution is needed here since ERR_reason_error_string will - * return NULL if it doesn't recognize the error code. We don't - * want to return NULL ever. - */ - static const char * - SSLerrmessage(void) - { - unsigned long errcode; - const char *errreason; - static char errbuf[32]; - - errcode = ERR_get_error(); - if (errcode == 0) - return "No SSL error reported"; - errreason = ERR_reason_error_string(errcode); - if (errreason != NULL) - return errreason; - snprintf(errbuf, sizeof(errbuf), "SSL error code %lu", errcode); - return errbuf; - } - - #endif /* USE_SSL */ - - /* =========== accessor functions for PGconn ========= */ char * PQdb(const PGconn *conn) --- 2602,2607 ---- *************** *** 2789,2804 **** PQsetClientEncoding(PGconn *conn, const char *encoding) { return -1; - } - #endif - - #ifdef USE_SSL - SSL * - PQgetssl(PGconn *conn) - { - if (!conn) - return NULL; - return conn->ssl; } #endif --- 2743,2748 ---- Index: postgresql/src/interfaces/libpq/fe-misc.c diff -c postgresql/src/interfaces/libpq/fe-misc.c:1.1.1.1 postgresql/src/interfaces/libpq/fe-misc.c:1.2 *** postgresql/src/interfaces/libpq/fe-misc.c:1.1.1.1 Thu May 23 22:56:22 2002 --- postgresql/src/interfaces/libpq/fe-misc.c Fri May 24 12:41:53 2002 *************** *** 25,31 **** * * * IDENTIFICATION ! * $Header: /usr/local/cvsroot/postgresql/src/interfaces/libpq/fe-misc.c,v 1.1.1.1 2002/05/24 04:56:22 bear Exp $ * *------------------------------------------------------------------------- */ --- 25,31 ---- * * * IDENTIFICATION ! * $Header: /usr/local/cvsroot/postgresql/src/interfaces/libpq/fe-misc.c,v 1.2 2002/05/24 18:41:53 bear Exp $ * *------------------------------------------------------------------------- */ *************** *** 57,62 **** --- 57,65 ---- #include "mb/pg_wchar.h" #endif + extern void secure_close(PGconn *); + extern ssize_t secure_read(PGconn *, void *, size_t); + extern ssize_t secure_write(PGconn *, const void *, size_t); #define DONOTICE(conn,message) \ ((*(conn)->noticeHook) ((conn)->noticeArg, (message))) *************** *** 459,472 **** /* OK, try to read some data */ tryAgain: ! #ifdef USE_SSL ! if (conn->ssl) ! nread = SSL_read(conn->ssl, conn->inBuffer + conn->inEnd, ! conn->inBufSize - conn->inEnd); ! else ! #endif ! nread = recv(conn->sock, conn->inBuffer + conn->inEnd, ! conn->inBufSize - conn->inEnd, 0); if (nread < 0) { if (SOCK_ERRNO == EINTR) --- 462,469 ---- /* OK, try to read some data */ tryAgain: ! nread = secure_read(conn, conn->inBuffer + conn->inEnd, ! conn->inBufSize - conn->inEnd); if (nread < 0) { if (SOCK_ERRNO == EINTR) *************** *** 545,558 **** * arrived. */ tryAgain2: ! #ifdef USE_SSL ! if (conn->ssl) ! nread = SSL_read(conn->ssl, conn->inBuffer + conn->inEnd, ! conn->inBufSize - conn->inEnd); ! else ! #endif ! nread = recv(conn->sock, conn->inBuffer + conn->inEnd, ! conn->inBufSize - conn->inEnd, 0); if (nread < 0) { if (SOCK_ERRNO == EINTR) --- 542,549 ---- * arrived. */ tryAgain2: ! nread = secure_read(conn, conn->inBuffer + conn->inEnd, ! conn->inBufSize - conn->inEnd); if (nread < 0) { if (SOCK_ERRNO == EINTR) *************** *** 593,598 **** --- 584,590 ---- "\tThis probably means the server terminated abnormally\n" "\tbefore or while processing the request.\n")); conn->status = CONNECTION_BAD; /* No more connection to backend */ + secure_close(conn); #ifdef WIN32 closesocket(conn->sock); #else *************** *** 629,651 **** /* while there's still data to send */ while (len > 0) { - /* Prevent being SIGPIPEd if backend has closed the connection. */ - #ifndef WIN32 - pqsigfunc oldsighandler = pqsignal(SIGPIPE, SIG_IGN); - #endif - int sent; - - #ifdef USE_SSL - if (conn->ssl) - sent = SSL_write(conn->ssl, ptr, len); - else - #endif - sent = send(conn->sock, ptr, len, 0); ! #ifndef WIN32 ! pqsignal(SIGPIPE, oldsighandler); ! #endif if (sent < 0) { --- 621,629 ---- /* while there's still data to send */ while (len > 0) { int sent; ! sent = secure_write(conn, ptr, len); if (sent < 0) { Index: postgresql/src/interfaces/libpq/fe-secure.c diff -c /dev/null postgresql/src/interfaces/libpq/fe-secure.c:1.5 *** /dev/null Fri May 24 21:52:25 2002 --- postgresql/src/interfaces/libpq/fe-secure.c Fri May 24 21:44:30 2002 *************** *** 0 **** --- 1,580 ---- + /*------------------------------------------------------------------------- + * + * fe-connect.c + * functions related to setting up a secure connection to the backend. + * Secure connections are expected to provide confidentiality, + * message integrity and endpoint authentication. + * + * + * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * + * IDENTIFICATION + * $Header: /usr/local/cvsroot/postgresql/src/interfaces/libpq/fe-secure.c,v 1.5 2002/05/25 03:44:30 bear Exp $ + * + * NOTES + * The client *requires* a valid server certificate. Since + * SSH tunnels provide anonymous confidentiality, the presumption + * is that sites that want endpoint authentication will use the + * direct SSL support, while sites that are comfortable with + * anonymous connections will use SSH tunnels. + * + * This code verifies the server certificate, to detect simple + * "man-in-the-middle" and "impersonation" attacks. The + * server certificate, or better yet the CA certificate used + * to sign the server certificate, should be present in the + * "$HOME/.postgresql/root.crt" file. If this file isn't + * readable, or the server certificate can't be validated, + * secure_open_client() will return an error code. + * + * Additionally, the server certificate's "common name" must + * resolve to the other end of the socket. This makes it + * substantially harder to pull off a "man-in-the-middle" or + * "impersonation" attack even if the server's private key + * has been stolen. This check limits acceptable network + * layers to Unix sockets (weird, but legal), TCPv4 and TCPv6. + * + * Unfortunately neither the current front- or back-end handle + * failure gracefully, resulting in the backend hiccupping. + * This points out problems in each (the frontend shouldn't even + * try to do SSL if secure_initialize() fails, and the backend + * shouldn't crash/recover if an SSH negotiation fails. The + * backend definitely needs to be fixed, to prevent a "denial + * of service" attack, but I don't know enough about how the + * backend works (especially that pre-SSL negotiation) to identify + * a fix. + * + * OS DEPENDENCIES + * The code currently assumes a POSIX password entry. How should + * Windows and Mac users be handled? + * + * PATCH LEVEL + * milestone 1: fix basic coding errors + * [*] existing SSL code pulled out of existing files. + * [*] SSL_get_error() after SSL_read() and SSL_write(), + * SSL_shutdown(), default to TLSv1. + * + * milestone 2: provide endpoint authentication (server) + * [*] client verifies server cert + * [*] client verifies server hostname + * + * milestone 3: improve confidentially, support perfect forward secrecy + * [ ] use 'random' file, read from '/dev/urandom?' + * [ ] emphermal DH keys, default values + * + * milestone 4: provide endpoint authentication (client) + * [ ] server verifies client certificates + * + * milestone 5: provide informational callbacks + * [ ] provide informational callbacks + * + * other changes + * [ ] tcp-wrappers + * [ ] more informative psql + * + *------------------------------------------------------------------------- + */ + + #include "postgres_fe.h" + + #include + #include + #include + #include + #include + #include + + #include "libpq-fe.h" + #include "libpq-int.h" + #include "fe-auth.h" + #include "pqsignal.h" + + #ifdef WIN32 + #include "win32.h" + #else + #include + #include + #include + #include + #ifdef HAVE_NETINET_TCP_H + #include + #endif + #include + #endif + + #ifndef HAVE_STRDUP + #include "strdup.h" + #endif + + #include + #include + + #ifdef USE_SSL + #include + #include + #endif /* USE_SSL */ + + int secure_initialize(PGconn *); + void secure_destroy(void); + int secure_open_client(PGconn *); + void secure_close(PGconn *); + ssize_t secure_read(PGconn *, void *ptr, size_t len); + ssize_t secure_write(PGconn *, const void *ptr, size_t len); + + #ifdef USE_SSL + static int verify_cb(int ok, X509_STORE_CTX *ctx); + static int verify_peer(PGconn *); + static int initialize_SSL(PGconn *); + static void destroy_SSL(void); + static int open_client_SSL(PGconn *); + static void close_SSL(PGconn *); + static const char *SSLerrmessage(void); + #endif + + #ifdef USE_SSL + static SSL_CTX *SSL_context = NULL; + #endif + + /* ------------------------------------------------------------ */ + /* Procedures common to all secure sessions */ + /* ------------------------------------------------------------ */ + + /* + * Initialize global context + */ + int + secure_initialize (PGconn *conn) + { + int r = 0; + + #ifdef USE_SSL + r = initialize_SSL(conn); + #endif + + return r; + } + + /* + * Destroy global context + */ + void + secure_destroy (void) + { + #ifdef USE_SSL + destroy_SSL(); + #endif + } + + /* + * Attempt to negotiate secure session. + */ + int + secure_open_client (PGconn *conn) + { + int r = 0; + + #ifdef USE_SSL + r = open_client_SSL(conn); + #endif + + return r; + } + + /* + * Close secure session. + */ + void + secure_close (PGconn *conn) + { + #ifdef USE_SSL + if (conn->ssl) + close_SSL(conn); + #endif + } + + /* + * Read data from a secure connection. + */ + ssize_t + secure_read (PGconn *conn, void *ptr, size_t len) + { + ssize_t n; + + #ifdef USE_SSL + if (conn->ssl) + { + n = SSL_read(conn->ssl, ptr, len); + switch (SSL_get_error(conn->ssl, n)) + { + case SSL_ERROR_NONE: + break; + case SSL_ERROR_WANT_READ: + break; + case SSL_ERROR_SYSCALL: + SOCK_ERRNO = get_last_socket_error(); + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("SSL SYSCALL error: %s\n"), + SOCK_STRERROR(SOCK_ERRNO)); + break; + case SSL_ERROR_SSL: + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("SSL error: %s\n"), SSLerrmessage()); + /* fall through */ + case SSL_ERROR_ZERO_RETURN: + secure_close(conn); + SOCK_ERRNO = ECONNRESET; + n = -1; + break; + } + } + else + #endif + n = recv(conn->sock, ptr, len, 0); + + return n; + } + + /* + * Write data to a secure connection. + */ + ssize_t + secure_write (PGconn *conn, const void *ptr, size_t len) + { + ssize_t n; + + #ifndef WIN32 + pqsigfunc oldsighandler = pqsignal(SIGPIPE, SIG_IGN); + #endif + + #ifdef USE_SSL + if (conn->ssl) + { + n = SSL_write(conn->ssl, ptr, len); + switch (SSL_get_error(conn->ssl, n)) + { + case SSL_ERROR_NONE: + break; + case SSL_ERROR_WANT_WRITE: + break; + case SSL_ERROR_SYSCALL: + SOCK_ERRNO = get_last_socket_error(); + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("SSL SYSCALL error: %s\n"), + SOCK_STRERROR(SOCK_ERRNO)); + break; + case SSL_ERROR_SSL: + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("SSL error: %s\n"), SSLerrmessage()); + /* fall through */ + case SSL_ERROR_ZERO_RETURN: + secure_close(conn); + SOCK_ERRNO = ECONNRESET; + n = -1; + break; + } + } + else + #endif + n = send(conn->sock, ptr, len, 0); + + #ifndef WIN32 + pqsignal(SIGPIPE, oldsighandler); + #endif + + return n; + } + + /* ------------------------------------------------------------ */ + /* SSL specific code */ + /* ------------------------------------------------------------ */ + #ifdef USE_SSL + /* + * Certificate verification callback + * + * This callback allows us to log intermediate problems during + * verification, but there doesn't seem to be a clean way to get + * our PGconn * structure. So we can't log anything! + * + * This callback also allows us to override the default acceptance + * criteria (e.g., accepting self-signed or expired certs), but + * for now we accept the default checks. + */ + static int + verify_cb (int ok, X509_STORE_CTX *ctx) + { + return ok; + } + + /* + * Verify that common name resolves to peer. + * This function is not thread-safe due to gethostbyname2(). + */ + static int + verify_peer (PGconn *conn) + { + struct hostent *h = NULL; + struct sockaddr addr; + struct sockaddr_in *sin; + struct sockaddr_in6 *sin6; + socklen_t len; + char **s; + unsigned long l; + + /* get the address on the other side of the socket */ + len = sizeof(addr); + if (getpeername(conn->sock, &addr, &len) == -1) + { + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("error querying socket: %s\n"), + SOCK_STRERROR(SOCK_ERRNO)); + return -1; + } + + /* weird, but legal case */ + if (addr.sa_family == AF_UNIX) + return 0; + + /* what do we know about the peer's common name? */ + if ((h = gethostbyname2(conn->peer_cn, addr.sa_family)) == NULL) + { + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("error getting information about host (%s): %s\n"), + conn->peer_cn, hstrerror(h_errno)); + return -1; + } + + /* does the address match? */ + switch (addr.sa_family) + { + case AF_INET: + sin = (struct sockaddr_in *) &addr; + for (s = h->h_addr_list; *s != NULL; s++) + { + if (!memcmp(&sin->sin_addr.s_addr, *s, h->h_length)) + return 0; + } + break; + + case AF_INET6: + sin6 = (struct sockaddr_in6 *) &addr; + for (s = h->h_addr_list; *s != NULL; s++) + { + if (!memcmp(sin6->sin6_addr.in6_u.u6_addr8, *s, h->h_length)) + return 0; + } + break; + + default: + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("sorry, this protocol not yet supported\n")); + return -1; + } + + /* the prior test should be definitive, but in practice + * it sometimes fails. So we also check the aliases. */ + for (s = h->h_aliases; *s != NULL; s++) + { + if (strcasecmp(conn->peer_cn, *s) == 0) + return 0; + } + + /* generate protocol-aware error message */ + switch (addr.sa_family) + { + case AF_INET: + sin = (struct sockaddr_in *) &addr; + l = ntohl(sin->sin_addr.s_addr); + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext( + "server common name '%s' does not resolve to %ld.%ld.%ld.%ld\n"), + conn->peer_cn, (l >> 24) % 0x100, (l >> 16) % 0x100, + (l >> 8) % 0x100, l % 0x100); + break; + default: + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext( + "server common name '%s' does not resolve to peer address\n"), + conn->peer_cn); + } + + return -1; + } + + /* + * Initialize global SSL context. + */ + static int + initialize_SSL (PGconn *conn) + { + struct stat buf; + struct passwd *pwd; + char fnbuf[2048]; + + if (!SSL_context) + { + SSL_library_init(); + SSL_load_error_strings(); + SSL_context = SSL_CTX_new(TLSv1_method()); + if (!SSL_context) + { + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not create SSL context: %s\n"), + SSLerrmessage()); + return -1; + } + } + + if ((pwd = getpwuid(getuid())) != NULL) + { + snprintf(fnbuf, sizeof fnbuf, "%s/.postgresql/root.crt", + pwd->pw_dir); + if (stat(fnbuf, &buf) == -1) + { + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not read root cert list(%s): %s"), + fnbuf, strerror(errno)); + return -1; + } + if (!SSL_CTX_load_verify_locations(SSL_context, fnbuf, 0)) + { + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not read root cert list (%s): %s"), + fnbuf, SSLerrmessage()); + return -1; + } + } + + SSL_CTX_set_verify(SSL_context, + SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb); + SSL_CTX_set_verify_depth(SSL_context, 1); + + return 0; + } + + /* + * Destroy global SSL context. + */ + static void + destroy_SSL (void) + { + if (SSL_context) + { + SSL_CTX_free(SSL_context); + SSL_context = NULL; + } + } + + /* + * Attempt to negotiate SSL connection. + */ + static int + open_client_SSL (PGconn *conn) + { + int r; + + if (!(conn->ssl = SSL_new(SSL_context)) || + !SSL_set_fd(conn->ssl, conn->sock) || + SSL_connect(conn->ssl) <= 0) + { + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("could not establish SSL connection: %s\n"), + SSLerrmessage()); + close_SSL(conn); + return -1; + } + + /* check the certificate chain of the server */ + /* this eliminates simple man-in-the-middle attacks and + * simple impersonations */ + r = SSL_get_verify_result(conn->ssl); + if (r != X509_V_OK) + { + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("certificate could not be validated: %s\n"), + X509_verify_cert_error_string(r)); + close_SSL(conn); + return -1; + } + + /* pull out server distinguished and common names */ + conn->peer = SSL_get_peer_certificate(conn->ssl); + if (conn->peer == NULL) + { + printfPQExpBuffer(&conn->errorMessage, + libpq_gettext("certificate could not be obtained: %s\n"), + SSLerrmessage()); + close_SSL(conn); + return -1; + } + + X509_NAME_oneline(X509_get_subject_name(conn->peer), + conn->peer_dn, sizeof(conn->peer_dn)); + conn->peer_dn[sizeof(conn->peer_dn)-1] = '\0'; + + X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer), + NID_commonName, conn->peer_cn, SM_USER); + conn->peer_cn[SM_USER] = '\0'; + + /* verify that the common name resolves to peer */ + /* this is necessary to eliminate man-in-the-middle attacks + * and impersonations where the attacker somehow learned + * the server's private key */ + if (verify_peer(conn) == -1) + { + close_SSL(conn); + return -1; + } + + return 0; + } + + /* + * Close SSL connection. + */ + static void + close_SSL (PGconn *conn) + { + if (conn->ssl) + { + SSL_shutdown(conn->ssl); + SSL_free(conn->ssl); + conn->ssl = NULL; + } + } + + /* + * Obtain reason string for last SSL error + * + * Some caution is needed here since ERR_reason_error_string will + * return NULL if it doesn't recognize the error code. We don't + * want to return NULL ever. + */ + static const char * + SSLerrmessage(void) + { + unsigned long errcode; + const char *errreason; + static char errbuf[32]; + + errcode = ERR_get_error(); + if (errcode == 0) + return "No SSL error reported"; + errreason = ERR_reason_error_string(errcode); + if (errreason != NULL) + return errreason; + snprintf(errbuf, sizeof(errbuf), "SSL error code %lu", errcode); + return errbuf; + } + + /* + * Return pointer to SSL object. + */ + SSL * + PQgetssl(PGconn *conn) + { + if (!conn) + return NULL; + return conn->ssl; + } + #endif /* USE_SSL */ Index: postgresql/src/interfaces/libpq/libpq-int.h diff -c postgresql/src/interfaces/libpq/libpq-int.h:1.1.1.1 postgresql/src/interfaces/libpq/libpq-int.h:1.2 *** postgresql/src/interfaces/libpq/libpq-int.h:1.1.1.1 Thu May 23 22:56:22 2002 --- postgresql/src/interfaces/libpq/libpq-int.h Fri May 24 19:58:03 2002 *************** *** 12,18 **** * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * ! * $Id: libpq-int.h,v 1.1.1.1 2002/05/24 04:56:22 bear Exp $ * *------------------------------------------------------------------------- */ --- 12,18 ---- * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * ! * $Id: libpq-int.h,v 1.2 2002/05/25 01:58:03 bear Exp $ * *------------------------------------------------------------------------- */ *************** *** 270,275 **** --- 270,278 ---- bool allow_ssl_try; /* Allowed to try SSL negotiation */ bool require_ssl; /* Require SSL to make connection */ SSL *ssl; /* SSL status, if have SSL connection */ + X509 *peer; /* X509 cert of server */ + char peer_dn[256+1]; /* peer distinguished name */ + char peer_cn[SM_USER+1]; /* peer common name */ #endif /* Buffer for current error message */