Thread: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
wollman@LCS.MIT.EDU
Date:
The following set of patches (relative to 7.1.2 release) implement
SCM_CREDS authentication for local connections.  On systems which
support it, this mechanism should be used instead of `trust' for local
connections.

-GAWollman

------------------------------------------------------------------------
--- src/backend/libpq/auth.c    Wed Mar 21 22:59:30 2001
+++ src/backend/libpq/auth.c    Sun Aug 12 14:46:35 2001
@@ -26,6 +26,11 @@
 #include <ctype.h>

 #include <sys/types.h>            /* needed by in.h on Ultrix */
+#include <sys/socket.h>            /* for SCM_CREDS */
+#ifdef SCM_CREDS
+#include <sys/uio.h>            /* for struct iovec */
+#include <errno.h>
+#endif
 #include <netinet/in.h>
 #include <arpa/inet.h>

@@ -42,6 +47,7 @@
 static int    handle_done_auth(void *arg, PacketLen len, void *pkt);
 static int    handle_krb4_auth(void *arg, PacketLen len, void *pkt);
 static int    handle_krb5_auth(void *arg, PacketLen len, void *pkt);
+static int    handle_local_auth(void *arg, PacketLen len, void *pkt);
 static int    handle_password_auth(void *arg, PacketLen len, void *pkt);
 static int    readPasswordPacket(void *arg, PacketLen len, void *pkt);
 static int    pg_passwordv0_recvauth(void *arg, PacketLen len, void *pkt);
@@ -322,6 +328,98 @@
 #endif     /* KRB5 */


+#ifdef SCM_CREDS
+static int
+pg_local_recvauth(Port *port)
+{
+    struct msghdr msg;
+    struct {
+        struct cmsghdr hdr;
+        struct cmsgcred cred;
+    } cmsg;
+    struct iovec iov;
+    char buf;
+    char namebuf[SM_USER + 1];
+    struct passwd *pw;
+
+    msg.msg_name = NULL;
+    msg.msg_namelen = 0;
+    msg.msg_iov = &iov;
+    msg.msg_iovlen = 1;
+    msg.msg_control = (char *)&cmsg;
+    msg.msg_controllen = sizeof cmsg;
+    msg.msg_flags = 0;
+
+    /*
+     * The one character which is received here is not meaningful;
+     * its purposes is only to make sure that recvmsg() blocks
+     * long enough for the other side to send its credentials.
+     */
+    iov.iov_base = &buf;
+    iov.iov_len = 1;
+
+    if (recvmsg(port->sock, &msg, 0) < 0) {
+        snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+             "pg_local_recvauth: error receiving credentials: %s\n",
+             strerror(errno));
+errout:
+        fputs(PQerrormsg, stderr);
+        pqdebug("%s", PQerrormsg);
+
+        return STATUS_ERROR;
+    }
+
+    /*
+     * Make sure we got the right kind of message.
+     */
+    if (cmsg.hdr.cmsg_len != sizeof cmsg
+        || cmsg.hdr.cmsg_level != SOL_SOCKET
+        || cmsg.hdr.cmsg_type != SCM_CREDS) {
+        snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+             "pg_local_recvauth: protocol error receiving credentials\n");
+        goto errout;
+    }
+
+    snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+         "pg_local_recvauth: pid %lu, uid %lu\n",
+         (unsigned long)cmsg.cred.cmcred_pid,
+         (unsigned long)cmsg.cred.cmcred_uid);
+    pqdebug("%s", PQerrormsg);
+
+    strncpy(namebuf, port->user, SM_USER);
+    namebuf[SM_USER] = '\0';
+
+    pw = getpwnam(namebuf);
+    if (pw == NULL) {
+        snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+             "pg_local_recvauth: unknown local user %s\n",
+             namebuf);
+        goto errout;
+    }
+
+    if (pw->pw_uid != cmsg.cred.cmcred_uid) {
+        snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+             "pg_local_recvauth: %s's uid %lu != real uid %lu\n",
+             namebuf, (unsigned long)pw->pw_uid,
+             (unsigned long)cmsg.cred.cmcred_uid);
+        goto errout;
+    }
+    return STATUS_OK;
+}
+
+#else
+static int
+pg_local_recvauth(Port *port)
+{
+    snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+         "pg_local_recvauth: credential passing not implemented on this server.\n");
+    fputs(PQerrormsg, stderr);
+    pqdebug("%s", PQerrormsg);
+
+    return STATUS_ERROR;
+}
+#endif /* SCM_CREDS */
+
 /*
  * Handle a v0 password packet.
  */
@@ -439,6 +537,9 @@
         case uaCrypt:
             authmethod = "Password";
             break;
+        case uaLocalCred:
+            authmethod = "Local credential";
+            break;
     }

     sprintf(buffer, "%s authentication failed for user '%s'",
@@ -545,6 +646,10 @@
                 areq = AUTH_REQ_CRYPT;
                 auth_handler = handle_password_auth;
                 break;
+            case uaLocalCred:
+                areq = AUTH_REQ_LOCALCRED;
+                auth_handler = handle_local_auth;
+                break;
         }

         /* Tell the frontend what we want next. */
@@ -668,6 +773,24 @@


 /*
+ * Called when we have told the front end that it should use local
+ * credential authentication.
+ */
+
+static int
+handle_local_auth(void *arg, PacketLen len, void *pkt)
+{
+    Port       *port = (Port *) arg;
+
+    if (pg_local_recvauth(port) != STATUS_OK)
+        auth_failed(port);
+    else
+        sendAuthRequest(port, AUTH_REQ_OK, handle_done_auth);
+
+    return STATUS_OK;
+}
+
+/*
  * Called when we have received the password packet.
  */

@@ -777,6 +900,10 @@

         case uaTrust:
             status = STATUS_OK;
+            break;
+
+        case uaLocalCred: /* can't happen */
+            status = STATUS_ERROR;
             break;

         case uaIdent:
--- src/backend/libpq/hba.c    Fri Feb  9 21:31:26 2001
+++ src/backend/libpq/hba.c    Sun Aug 12 14:10:28 2001
@@ -125,6 +125,8 @@
         *userauth_p = uaReject;
     else if (strcmp(buf, "crypt") == 0)
         *userauth_p = uaCrypt;
+    else if (strcmp(buf, "local") == 0)
+        *userauth_p = uaLocalCred;
     else
     {
         *error_p = true;
@@ -279,6 +281,14 @@
          */

         read_hba_entry2(file, &port->auth_method, port->auth_arg, error_p);
+
+        /*
+         * Disallow authentication methods which require a PF_LOCAL
+         * socket.
+         */
+        if (!*error_p &&
+            (port->auth_method == uaLocalCred))
+            *error_p = true;

         if (*error_p)
             goto syntax;
--- src/backend/libpq/pg_hba.conf.sample    Tue Nov 21 15:44:32 2000
+++ src/backend/libpq/pg_hba.conf.sample    Sun Aug 12 14:17:41 2001
@@ -96,6 +96,12 @@
 #   trust:      No authentication is done. Trust that the user has the
 #           authority to use whatever username he specifies.
 #
+#   local:    Use the credential-passing feature of local-domain sockets
+#        (available only on certain operating systems) to
+#        authenticate the user.  Allow the user access if his
+#        real UID matches the UID in the system password file
+#        for the requested username.
+#
 #   password:    Authentication is done by matching a password supplied
 #           in clear by the host. If AUTH_ARGUMENT is specified then
 #           the password is compared with the user's entry in that
@@ -123,7 +129,7 @@
 #
 #   reject:     Reject the connection.
 #
-# Local (UNIX socket) connections support only AUTHTYPEs "trust",
+# Local (UNIX socket) connections support only AUTHTYPEs "trust", "local",
 # "password", "crypt", and "reject".


@@ -137,9 +143,18 @@
 #
 # host       all         127.0.0.1     255.255.255.255    trust
 #
-# The same, over Unix-socket connections:
+# Allow any user to connect to any database over a local socket,
+# provided that the user's real UID is the same as the requested
+# database username's UID:
+#
+# local      all                                          local
+#
+# On operating systems where credential passing over local sockets
+# is not available, allow any user to connect to any database over
+# a local socket under any username:
 #
 # local      all                                          trust
+#
 #
 # Allow any user from any host with IP address 192.168.93.x to
 # connect to database "template1" as the same username that ident on that
--- src/include/libpq/hba.h    Wed Mar 21 23:00:47 2001
+++ src/include/libpq/hba.h    Sun Aug 12 13:33:30 2001
@@ -35,7 +35,8 @@
     uaTrust,
     uaIdent,
     uaPassword,
-    uaCrypt
+    uaCrypt,
+    uaLocalCred
 } UserAuth;

 typedef struct Port hbaPort;
--- src/include/libpq/pqcomm.h    Wed Mar 21 23:00:48 2001
+++ src/include/libpq/pqcomm.h    Sun Aug 12 13:35:16 2001
@@ -90,7 +90,7 @@
 /* The earliest and latest frontend/backend protocol version supported. */

 #define PG_PROTOCOL_EARLIEST    PG_PROTOCOL(0,0)
-#define PG_PROTOCOL_LATEST    PG_PROTOCOL(2,0)
+#define PG_PROTOCOL_LATEST    PG_PROTOCOL(2,1)

 /*
  * All packets sent to the postmaster start with the length.  This is omitted
@@ -132,6 +132,7 @@
 #define AUTH_REQ_KRB5        2    /* Kerberos V5 */
 #define AUTH_REQ_PASSWORD    3    /* Password */
 #define AUTH_REQ_CRYPT        4    /* Encrypted password */
+#define    AUTH_REQ_LOCALCRED    5    /* PF_LOCAL credentials */

 typedef uint32 AuthRequest;

--- src/interfaces/libpq/fe-auth.c    Wed Mar 21 23:01:25 2001
+++ src/interfaces/libpq/fe-auth.c    Sun Aug 12 14:50:44 2001
@@ -43,6 +43,11 @@
 #ifndef  MAXHOSTNAMELEN
 #include <netdb.h>                /* for MAXHOSTNAMELEN on some */
 #endif
+#include <sys/socket.h>        /* for SCM_CREDS */
+#ifdef SCM_CREDS
+#include <sys/uio.h>
+#include <sys/errno.h>
+#endif
 #include <pwd.h>
 #endif

@@ -430,6 +435,52 @@

 #endif     /* KRB5 */

+#ifdef SCM_CREDS
+static int
+pg_local_sendauth(char *PQerrormsg, PGconn *conn)
+{
+    char buf;
+    struct iovec iov;
+    struct {
+        struct cmsghdr hdr;
+        struct cmsgcred cred;
+    } cmsg;
+    struct msghdr msg;
+
+    /*
+     * The backend doesn't care what we send here, but it wants
+     * exactly one character to force recvmsg() to block and wait
+     * for us.
+     */
+    buf = '\0';
+    iov.iov_base = &buf;
+    iov.iov_len = 1;
+
+    cmsg.hdr.cmsg_len = sizeof cmsg;
+    cmsg.hdr.cmsg_level = SOL_SOCKET;
+    cmsg.hdr.cmsg_type = SCM_CREDS;
+    /*
+     * cmsg.cred will get filled in with the correct information
+     * by the kernel when this message is sent.
+     */
+
+    msg.msg_name = NULL;
+    msg.msg_namelen = 0;
+    msg.msg_iov = &iov;
+    msg.msg_iovlen = 1;
+    msg.msg_control = &cmsg;
+    msg.msg_controllen = sizeof cmsg;
+    msg.msg_flags = 0;
+
+    if (sendmsg(conn->sock, &msg, 0) == -1) {
+        snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+             "pg_local_sendauth: sendmsg: %s", strerror(errno));
+        return STATUS_ERROR;
+    }
+    return STATUS_OK;
+}
+#endif
+
 static int
 pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
 {
@@ -507,6 +558,17 @@
             }

             break;
+
+        case AUTH_REQ_LOCALCRED:
+#ifdef SCM_CREDS
+            if (pg_local_sendauth(PQerrormsg, conn) != STATUS_OK)
+                return STATUS_ERROR;
+            break;
+#else
+            (void) sprintf(PQerrormsg,
+                     "fe_sendauth: local authentication not supported\n");
+            return STATUS_ERROR;
+#endif

         default:
             (void) sprintf(PQerrormsg,

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Tom Lane
Date:
wollman@LCS.MIT.EDU writes:
> The following set of patches (relative to 7.1.2 release) implement
> SCM_CREDS authentication for local connections.

Unfortunately, there's little chance that this will apply cleanly to
current sources, since we've restructured the postmaster's handling of
the authorization process.

A more significant objection is that you've extended the wire protocol
by adding a new authorization protocol, but have fixed only one client
library and not touched the protocol documentation at all.  There's a
lot more work needed to make this a complete patch.

BTW, current sources already contain support for using
getsockopt(SO_PEERCRED) where available --- AFAIK that's only Linux,
but perhaps that's all you need.

            regards, tom lane

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Garrett Wollman
Date:
<<On Mon, 13 Aug 2001 10:14:14 -0400, Tom Lane <tgl@sss.pgh.pa.us> said:

> A more significant objection is that you've extended the wire protocol
> by adding a new authorization protocol, but have fixed only one client
> library and not touched the protocol documentation at all.  There's a
> lot more work needed to make this a complete patch.

It works for me, in the applications that I care about, and that's all
matters to me.  If you don't want to take advantage of the work that
I've done (it took about an hour), that's not my concern.

> BTW, current sources already contain support for using
> getsockopt(SO_PEERCRED) where available --- AFAIK that's only Linux,
> but perhaps that's all you need.

I have no interest in Linux.

-GAWollman


Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Tom Lane
Date:
"Marc G. Fournier" <scrappy@hub.org> writes:
> Third, and more directed to Tom ... if applied, would this break the other
> client libraries, or only make it available to those that have been fixed?

Unextended clients should fail with reasonable grace, AFAIK.  I wasn't
objecting to the notion of adding an auth method on those grounds,
merely pointing out that there's more work to be done.

            regards, tom lane

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
"Marc G. Fournier"
Date:
On Mon, 13 Aug 2001, Garrett Wollman wrote:

> <<On Mon, 13 Aug 2001 10:14:14 -0400, Tom Lane <tgl@sss.pgh.pa.us> said:
>
> > A more significant objection is that you've extended the wire protocol
> > by adding a new authorization protocol, but have fixed only one client
> > library and not touched the protocol documentation at all.  There's a
> > lot more work needed to make this a complete patch.
>
> It works for me, in the applications that I care about, and that's all
> matters to me.  If you don't want to take advantage of the work that
> I've done (it took about an hour), that's not my concern.

First off, as Tom states, it won't apply to current sources ... can you
supply a patch that will work with -CURRENT?

Second, are you willing to provide patches for the protocol documentation?

Third, and more directed to Tom ... if applied, would this break the other
client libraries, or only make it available to those that have been fixed?



Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Peter Eisentraut
Date:
Tom Lane writes:

> BTW, current sources already contain support for using
> getsockopt(SO_PEERCRED) where available --- AFAIK that's only Linux,
> but perhaps that's all you need.

Is this feature any different from the fake local ident we've put it?

--
Peter Eisentraut   peter_e@gmx.net   http://funkturm.homeip.net/~peter


Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Tom Lane
Date:
Peter Eisentraut <peter_e@gmx.net> writes:
>> BTW, current sources already contain support for using
>> getsockopt(SO_PEERCRED) where available --- AFAIK that's only Linux,
>> but perhaps that's all you need.

> Is this feature any different from the fake local ident we've put it?

Yes.  Wollman's code uses an SCM_CREDS message, which means (a) it will
work on Solaris and one or two other Unixen, not only Linux; but (b)
it requires client-side code additions, not only server-side code.

            regards, tom lane

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> Peter Eisentraut <peter_e@gmx.net> writes:
> >> BTW, current sources already contain support for using
> >> getsockopt(SO_PEERCRED) where available --- AFAIK that's only Linux,
> >> but perhaps that's all you need.
>
> > Is this feature any different from the fake local ident we've put it?
>
> Yes.  Wollman's code uses an SCM_CREDS message, which means (a) it will
> work on Solaris and one or two other Unixen, not only Linux; but (b)
> it requires client-side code additions, not only server-side code.

BSD/OS supports it, and I assume FreeBSD too.
\
--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> Peter Eisentraut <peter_e@gmx.net> writes:
> >> BTW, current sources already contain support for using
> >> getsockopt(SO_PEERCRED) where available --- AFAIK that's only Linux,
> >> but perhaps that's all you need.
>
> > Is this feature any different from the fake local ident we've put it?
>
> Yes.  Wollman's code uses an SCM_CREDS message, which means (a) it will
> work on Solaris and one or two other Unixen, not only Linux; but (b)
> it requires client-side code additions, not only server-side code.

My upcoming MD5 patch will conflict with this anyway. Also, I just found
out that ODBC doesn't even do crypt authentication!  Anyway, I will
merge this into current sources.  Seems we can add it to ODBC and JDBC
later, just like the MD5 changes.

Is that OK with everyone.  Since we have peer with Linux, seems we
should add CRED_ in the same release.

--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> <<On Tue, 14 Aug 2001 20:54:42 -0400 (EDT), Bruce Momjian <pgman@candle.pha.pa.us> said:
>
> > Is that OK with everyone.  Since we have peer with Linux, seems we
> > should add CRED_ in the same release.
>
> One thing to be careful about: there are several different versions of
> this functionality, and not all of them use the same data structures.
> Probably you should include a configure test to figure out which
> version is available.

That is some information I really need.  I only have BSD/OS here.  I can
apply the patch and let you test it on your end, or if you can send over
some info, we can get it into configure.

--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> <<On Thu, 16 Aug 2001 00:34:14 -0400 (EDT), Bruce Momjian <pgman@candle.pha.pa.us> said:
>
> > OK, here is a cleaned up version of the patch that will apply to current
> > CVS.  I worked it into the SO_PEERCRED code.  I made some changes so it
> > compiles on BSD/OS.  I am getting "Invalid Argument" from libpq's
> > sending of the credentials on BSD/OS.
>
> There are some funky alignment macros that you probably need to use on
> BSD/OS.  Also, as written this will break on NetBSD and OpenBSD for
> reasons I have already noted (the structure is named something
> different there), and those systems will also require the alignment
> macros.  (Basically, putting the two structures in another larger
> structure is a shortcut in my implementation which only works because
> the compiler puts the right amount of padding in; on those other
> systems, more padding is required.)

I got some more information this morning.  First, BSD/OS doesn't like to
have the credentials record attached to the message.  I was getting
"Invalid argument" when I did that.  It just wants the packet.  Second,
BSD/OS has a LOCAL_CREDS call to pass the credentials.  I am working on
another patch but will get back to this shortly.

        "To get credentials sent (once on a stream socket, every time on
         a datagram socket) you just want to do a setsockopt() to set
         the LOCAL_CREDS option:

         int on = 1;
         error = setsockopt(s, 0, LOCAL_CREDS, &on, sizeof on);

--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> <<On Thu, 16 Aug 2001 00:34:14 -0400 (EDT), Bruce Momjian <pgman@candle.pha.pa.us> said:
>
> > OK, here is a cleaned up version of the patch that will apply to current
> > CVS.  I worked it into the SO_PEERCRED code.  I made some changes so it
> > compiles on BSD/OS.  I am getting "Invalid Argument" from libpq's
> > sending of the credentials on BSD/OS.
>
> There are some funky alignment macros that you probably need to use on
> BSD/OS.  Also, as written this will break on NetBSD and OpenBSD for
> reasons I have already noted (the structure is named something
> different there), and those systems will also require the alignment
> macros.  (Basically, putting the two structures in another larger
> structure is a shortcut in my implementation which only works because
> the compiler puts the right amount of padding in; on those other
> systems, more padding is required.)

OK, attached is my current version of the patch.  Would you download the
snapshot or CVS and let me know if this works on FreeBSD.  Even if you
can't run it, can you tell me if it compiles.

Also, attached is the BSD/OS manual page that shows the use of the
macros for retrieving SCM.  Can you add that and send me an updated
patch?  Also, can you check to see if FreeBSD requires you to send the
full struct with empty cred, or if you can just send the header without
the struct.  You will see in my patch for the libpq client part that
BSD/OS doesn't want the extra struct.

Looks like 7.2 is going to have overhauled authentication, and I would
really like to get this SCM stuff nailed down on as many platforms as
possible before going beta, which may happen as early as September 1.

--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026
Index: src/backend/libpq/auth.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/auth.c,v
retrieving revision 1.58
diff -c -r1.58 auth.c
*** src/backend/libpq/auth.c    2001/08/16 04:27:18    1.58
--- src/backend/libpq/auth.c    2001/08/16 14:56:42
***************
*** 15,24 ****

  #include "postgres.h"

! #include <sys/types.h>            /* needed by in.h on Ultrix */
  #include <netinet/in.h>
  #include <arpa/inet.h>
-
  #include "libpq/auth.h"
  #include "libpq/crypt.h"
  #include "libpq/hba.h"
--- 15,29 ----

  #include "postgres.h"

! #include <sys/types.h>
! #include <sys/socket.h>            /* for SCM_CREDS */
! #ifdef SCM_CREDS
! #include <sys/uio.h>            /* for struct iovec */
! #include <sys/ucred.h>
! #include <errno.h>
! #endif
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include "libpq/auth.h"
  #include "libpq/crypt.h"
  #include "libpq/hba.h"
***************
*** 28,39 ****
  #include "miscadmin.h"

  static void sendAuthRequest(Port *port, AuthRequest areq);
-
  static int    checkPassword(Port *port, char *user, char *password);
  static int    old_be_recvauth(Port *port);
  static int    map_old_to_new(Port *port, UserAuth old, int status);
  static void auth_failed(Port *port);
-
  static int    recv_and_check_password_packet(Port *port);
  static int    recv_and_check_passwordv0(Port *port);

--- 33,42 ----
***************
*** 493,498 ****
--- 496,507 ----
              break;

          case uaIdent:
+ #ifdef SCM_CREDS
+             /* If we are doing ident on unix-domain sockets,
+                we are going to use SCM_CREDS, if defined. */
+             if (port->raddr.sa.sa_family ==    AF_UNIX)
+                 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
+ #endif
              status = authident(port);
              break;

Index: src/backend/libpq/hba.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/hba.c,v
retrieving revision 1.63
diff -c -r1.63 hba.c
*** src/backend/libpq/hba.c    2001/08/16 04:27:18    1.63
--- src/backend/libpq/hba.c    2001/08/16 14:56:42
***************
*** 19,24 ****
--- 19,30 ----
  #include <errno.h>
  #include <pwd.h>
  #include <sys/types.h>
+ #include <sys/socket.h>            /* for SCM_CREDS */
+ #ifdef SCM_CREDS
+ #include <sys/uio.h>            /* for struct iovec */
+ #include <sys/ucred.h>
+ #include <errno.h>
+ #endif
  #include <fcntl.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
***************
*** 863,869 ****
  static bool
  ident_unix(int sock, char *ident_user)
  {
! #ifdef SO_PEERCRED
      /* Linux style: use getsockopt(SO_PEERCRED) */
      struct ucred    peercred;
      ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
--- 869,959 ----
  static bool
  ident_unix(int sock, char *ident_user)
  {
! #ifdef SCM_CREDS
!     struct msghdr msg;
!     struct {
!         struct cmsghdr hdr;
! #ifndef fc_uid
!         struct cmsgcred cred;
! #define cruid cmcred_uid
! #else
!         struct fcred cred;
! #define cruid fc_uid
! #endif
!     } cmsg;
!     struct iovec iov;
!     char buf;
!     char namebuf[SM_USER + 1];
!     struct passwd *pw;
!
!     msg.msg_name = NULL;
!     msg.msg_namelen = 0;
!     msg.msg_iov = &iov;
!     msg.msg_iovlen = 1;
!     msg.msg_control = (char *)&cmsg;
!     msg.msg_controllen = sizeof cmsg;
!     msg.msg_flags = 0;
!
!     /*
!      * The one character which is received here is not meaningful;
!      * its purposes is only to make sure that recvmsg() blocks
!      * long enough for the other side to send its credentials.
!      */
!     iov.iov_base = &buf;
!     iov.iov_len = 1;
!
!     if (recvmsg(sock, &msg, 0) < 0) {
!         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!              "ident_unix: error receiving credentials: %s\n",
!              strerror(errno));
! errout:
!         fputs(PQerrormsg, stderr);
!         pqdebug("%s", PQerrormsg);
!
!         return false;
!     }
!
!     /*
!      * Make sure we got the right kind of message.
!      */
!     if (cmsg.hdr.cmsg_len != sizeof cmsg
!         || cmsg.hdr.cmsg_level != SOL_SOCKET
!         || cmsg.hdr.cmsg_type != SCM_CREDS) {
!         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!              "ident_unix: protocol error receiving credentials\n");
!         goto errout;
!     }
!
!     snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!          "ident_unix: pid %lu, uid %lu\n",
! #ifndef fc_uid
!          (unsigned long)cmsg.cred.cmcred_pid,
! #else
!          (unsigned long)0, /* unavailable */
! #endif
!          (unsigned long)cmsg.cred.cruid);
!     pqdebug("%s", PQerrormsg);
!
!     strncpy(namebuf, ident_user, SM_USER);
!     namebuf[SM_USER] = '\0';
!
!     pw = getpwnam(namebuf);
!     if (pw == NULL) {
!         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!              "ident_unix: unknown local user %s\n",
!              namebuf);
!         goto errout;
!     }
!
!     if (pw->pw_uid != cmsg.cred.cruid) {
!         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!              "ident_unix: %s's uid %lu != real uid %lu\n",
!              namebuf, (unsigned long)pw->pw_uid,
!              (unsigned long)cmsg.cred.cruid);
!         goto errout;
!     }
!     return true;
! #elif SO_PEERCRED
      /* Linux style: use getsockopt(SO_PEERCRED) */
      struct ucred    peercred;
      ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
***************
*** 899,905 ****

      return true;

! #else /* not SO_PEERCRED */

      snprintf(PQerrormsg, PQERRORMSG_LENGTH,
               "IDENT auth is not supported on local connections on this platform\n");
--- 989,995 ----

      return true;

! #else

      snprintf(PQerrormsg, PQERRORMSG_LENGTH,
               "IDENT auth is not supported on local connections on this platform\n");
***************
*** 907,913 ****
      pqdebug("%s", PQerrormsg);
      return false;

! #endif /* SO_PEERCRED */
  }

  /*
--- 997,1003 ----
      pqdebug("%s", PQerrormsg);
      return false;

! #endif
  }

  /*
Index: src/backend/libpq/pg_hba.conf.sample
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/pg_hba.conf.sample,v
retrieving revision 1.24
diff -c -r1.24 pg_hba.conf.sample
*** src/backend/libpq/pg_hba.conf.sample    2001/08/15 18:42:15    1.24
--- src/backend/libpq/pg_hba.conf.sample    2001/08/16 14:56:47
***************
*** 125,136 ****
  #   ident:    For TCP/IP connections, authentication is done by contacting
  #        the ident server on the client host.  (CAUTION: this is only
  #        as secure as the client machine!)  On machines that support
! #        SO_PEERCRED socket requests, this method also works for
! #        local Unix-domain connections.  AUTH_ARGUMENT is required:
! #        it determines how to map remote user names to Postgres user
! #        names.  The AUTH_ARGUMENT is a map name found in the
! #        $PGDATA/pg_ident.conf file. The connection is accepted if
! #        that file contains an entry for this map name with the
  #        ident-supplied username and the requested Postgres username.
  #        The special map name "sameuser" indicates an implied map
  #        (not in pg_ident.conf) that maps each ident username to the
--- 125,136 ----
  #   ident:    For TCP/IP connections, authentication is done by contacting
  #        the ident server on the client host.  (CAUTION: this is only
  #        as secure as the client machine!)  On machines that support
! #        SO_PEERCRED or SCM_CREDS socket requests, this method also
! #        works for local Unix-domain connections.  AUTH_ARGUMENT is
! #        required: it determines how to map remote user names to
! #        Postgres user names.  The AUTH_ARGUMENT is a map name found
! #        in the $PGDATA/pg_ident.conf file. The connection is accepted
! #        if that file contains an entry for this map name with the
  #        ident-supplied username and the requested Postgres username.
  #        The special map name "sameuser" indicates an implied map
  #        (not in pg_ident.conf) that maps each ident username to the
Index: src/include/libpq/pqcomm.h
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/include/libpq/pqcomm.h,v
retrieving revision 1.57
diff -c -r1.57 pqcomm.h
*** src/include/libpq/pqcomm.h    2001/08/16 04:27:18    1.57
--- src/include/libpq/pqcomm.h    2001/08/16 14:56:48
***************
*** 133,138 ****
--- 133,139 ----
  #define AUTH_REQ_PASSWORD    3    /* Password */
  #define AUTH_REQ_CRYPT        4    /* crypt password */
  #define AUTH_REQ_MD5        5    /* md5 password */
+ #define AUTH_REQ_SCM_CREDS    6    /* transfer SCM credentials */

  typedef uint32 AuthRequest;

Index: src/interfaces/libpq/fe-auth.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/libpq/fe-auth.c,v
retrieving revision 1.50
diff -c -r1.50 fe-auth.c
*** src/interfaces/libpq/fe-auth.c    2001/08/15 21:08:21    1.50
--- src/interfaces/libpq/fe-auth.c    2001/08/16 14:56:49
***************
*** 40,50 ****
--- 40,57 ----
  #else
  #include <unistd.h>
  #include <fcntl.h>
+ #ifdef SCM_CREDS
+ #include <sys/uio.h>            /* for struct iovec */
+ #include <sys/ucred.h>
+ #include <errno.h>
+ #endif
  #include <sys/param.h>            /* for MAXHOSTNAMELEN on most */
  #ifndef  MAXHOSTNAMELEN
  #include <netdb.h>                /* for MAXHOSTNAMELEN on some */
  #endif
  #include <pwd.h>
+ #include <sys/types.h>
+ #include <sys/socket.h>            /* for SCM_CREDS */
  #endif

  #ifdef HAVE_CRYPT_H
***************
*** 432,437 ****
--- 439,490 ----

  #endif     /* KRB5 */

+ #ifdef SCM_CREDS
+ static int
+ pg_local_sendauth(char *PQerrormsg, PGconn *conn)
+ {
+     char buf;
+     struct iovec iov;
+     struct {
+         struct cmsghdr hdr;
+         /* We don't pass the credentials structure.   Kernel fills it in. */
+     } cmsg;
+     struct msghdr msg;
+
+     /*
+      * The backend doesn't care what we send here, but it wants
+      * exactly one character to force recvmsg() to block and wait
+      * for us.
+      */
+     buf = '\0';
+     iov.iov_base = &buf;
+     iov.iov_len = 1;
+
+     cmsg.hdr.cmsg_len = sizeof cmsg;
+     cmsg.hdr.cmsg_level = SOL_SOCKET;
+     cmsg.hdr.cmsg_type = SCM_CREDS;
+     /*
+      * cmsg.cred will get filled in with the correct information
+      * by the kernel when this message is sent.
+      */
+
+     msg.msg_name = NULL;
+     msg.msg_namelen = 0;
+     msg.msg_iov = &iov;
+     msg.msg_iovlen = 1;
+     msg.msg_control = &cmsg;
+     msg.msg_controllen = sizeof cmsg;
+     msg.msg_flags = 0;
+
+     if (sendmsg(conn->sock, &msg, 0) == -1) {
+         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+              "pg_local_sendauth: sendmsg: %s\n", strerror(errno));
+         return STATUS_ERROR;
+     }
+     return STATUS_OK;
+ }
+ #endif
+
  static int
  pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
  {
***************
*** 442,447 ****
--- 495,504 ----

      switch (areq)
      {
+         case AUTH_REQ_PASSWORD:
+             /* discard const so we can assign it */
+             crypt_pwd = (char *)password;
+             break;
          case AUTH_REQ_CRYPT:
              crypt_pwd = crypt(password, conn->salt);
              break;
***************
*** 472,482 ****
                  break;
              }
          default:
!             /* discard const so we can assign it */
!             crypt_pwd = (char *)password;
!             break;
      }
-
      ret = pqPacketSend(conn, crypt_pwd, strlen(crypt_pwd) + 1);
      if (areq == AUTH_REQ_MD5)
          free(crypt_pwd);
--- 529,536 ----
                  break;
              }
          default:
!             return STATUS_ERROR;
      }
      ret = pqPacketSend(conn, crypt_pwd, strlen(crypt_pwd) + 1);
      if (areq == AUTH_REQ_MD5)
          free(crypt_pwd);
***************
*** 549,554 ****
--- 603,620 ----
                  return STATUS_ERROR;
              }
              break;
+
+         case AUTH_REQ_SCM_CREDS:
+ #ifdef SCM_CREDS
+             if (pg_local_sendauth(PQerrormsg, conn) != STATUS_OK)
+                 return STATUS_ERROR;
+ #else
+             snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+                      libpq_gettext("SCM_CRED authentication method not supported\n"));
+             return STATUS_ERROR;
+ #endif
+             break;
+
          default:
              snprintf(PQerrormsg, PQERRORMSG_LENGTH,
                       libpq_gettext("authentication method %u not supported\n"), areq);
Index: src/interfaces/odbc/connection.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/odbc/connection.c,v
retrieving revision 1.33
diff -c -r1.33 connection.c
*** src/interfaces/odbc/connection.c    2001/08/15 18:42:16    1.33
--- src/interfaces/odbc/connection.c    2001/08/16 14:56:50
***************
*** 722,727 ****
--- 722,732 ----
                              self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
                              return 0;

+                         case AUTH_REQ_SCM_CREDS:
+                             self->errormsg = "Unix socket credential authentication not supported";
+                             self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
+                             return 0;
+
                          default:
                              self->errormsg = "Unknown authentication type";
                              self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
Index: src/interfaces/odbc/connection.h
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/odbc/connection.h,v
retrieving revision 1.25
diff -c -r1.25 connection.h
*** src/interfaces/odbc/connection.h    2001/08/15 18:42:16    1.25
--- src/interfaces/odbc/connection.h    2001/08/16 14:56:52
***************
*** 94,99 ****
--- 94,100 ----
  #define AUTH_REQ_PASSWORD                            3
  #define AUTH_REQ_CRYPT                                4
  #define AUTH_REQ_MD5                                5
+ #define AUTH_REQ_SCM_CREDS                            6

  /*    Startup Packet sizes */
  #define SM_DATABASE                                    64
RECV(2)            BSD Programmer's Manual            RECV(2)

NAME
     recv, recvfrom, recvmsg - receive a message from a socket

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     ssize_t
     recv(int s, void *buf, size_t len, int flags);

     ssize_t
     recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from,
         socklen_t *fromlen);

     ssize_t
     recvmsg(int s, struct msghdr *msg, int flags);

DESCRIPTION
     The recvfrom() and recvmsg() calls are used to receive messages from a
     socket, and may be used to receive data on a socket whether or not it is
     connection-oriented.

     If from is non-null, and the socket is not connection-oriented, the
     source address of the message is filled in.  The fromlen pointer refers
     to a value-result parameter; it should initially contain the amount of
     space pointed to by from; on return that location will contain the actual
     length (in bytes) of the address returned.    If the buffer provided is too
     small, the name is truncated and the full size is returned in the loca-
     tion to which fromlen points.  If from is null, the value pointed to by
     fromlen is not modified.  Otherwise, if the socket is connection-orient-
     ed, the address buffer will not be modified, and the value pointed to by
     fromlen will be set to zero.

     The recv() call is normally used only on a connected socket (see
     connect(2))  and is identical to recvfrom() with a nil from parameter.
     As it is redundant, it may not be supported in future releases.

     All three routines return the length of the message on successful comple-
     tion.  If a message is too long to fit in the supplied buffer, excess
     bytes may be discarded depending on the type of socket the message is re-
     ceived from (see socket(2)).

     If no messages are available at the socket, the receive call waits for a
     message to arrive, unless the socket is nonblocking (see fcntl(2))    in
     which case the value -1 is returned and the external variable errno set
     to EAGAIN. The receive calls normally return any data available, up to
     the requested amount, rather than waiting for receipt of the full amount
     requested; this behavior is affected by the socket-level options
     SO_RCVLOWAT and SO_RCVTIMEO described in getsockopt(2).

     The select(2) call may be used to determine when more data arrive.

     The flags argument to a recv call is formed by or'ing one or more of the
     values:

       MSG_OOB    process out-of-band data
       MSG_PEEK    peek at incoming message
       MSG_WAITALL    wait for full request or error

     The MSG_OOB flag requests receipt of out-of-band data that would not be
     received in the normal data stream.  Some protocols place expedited data
     at the head of the normal data queue, and thus this flag cannot be used
     with such protocols.  The MSG_PEEK flag causes the receive operation to
     return data from the beginning of the receive queue without removing that
     data from the queue.  Thus, a subsequent receive call will return the
     same data.    The MSG_WAITALL flag requests that the operation block until
     the full request is satisfied.  However, the call may still return less
     data than requested if a signal is caught, an error or disconnect occurs,
     or the next data to be received is of a different type than that re-
     turned.

     The recvmsg() call uses a msghdr structure to minimize the number of di-
     rectly supplied parameters.  This structure has the following form, as
     defined in <sys/socket.h>:

     struct msghdr {
         caddr_t msg_name;    /* optional address */
         u_int   msg_namelen;    /* size of address */
         struct  iovec *msg_iov; /* scatter/gather array */
         u_int   msg_iovlen;     /* # elements in msg_iov */
         caddr_t msg_control;    /* ancillary data, see below */
         u_int   msg_controllen; /* ancillary data buffer len */
         int     msg_flags;    /* flags on received message */
     };

     If msg_name is non-null, and the socket is not connection-oriented, the
     source address of the message is filled in.  The amount of space avail-
     able for the address is provided by msg_namelen, which is modified on re-
     turn to reflect the length of the stored address.    If the buffer is too
     small, the address is truncated; this is indicated when msg_namelen is
     less than the length embedded in the address (sa_len). If msg_name is
     null, msg_namelen is not modified.    Otherwise, if the socket is connec-
     tion-oriented, the address buffer will not be modified, and msg_namelen
     will be set to zero.

     Msg_iov and msg_iovlen describe scatter gather locations, as discussed in
     read(2).  Msg_control, which has length msg_controllen, points to a
     buffer for other protocol control related messages or other miscellaneous
     ancillary data.  The messages are of the form:

     struct cmsghdr {
         u_int   cmsg_len;    /* data byte count, including hdr */
         int     cmsg_level;     /* originating protocol */
         int     cmsg_type;    /* protocol-specific type */
     /* followed by
         u_char  cmsg_data[]; */
     };

     As an example, one could use this to learn of changes in the data-stream
     in XNS/SPP, or in ISO, to obtain user-connection-request data by request-
     ing a recvmsg with no data buffer provided immediately after an accept()
     call.

     Open file descriptors are now passed as ancillary data for AF_LOCAL do-
     main sockets, with cmsg_level set to SOL_SOCKET and cmsg_type set to
     SCM_RIGHTS.

     The msg_flags field is set on return according to the message received.
     MSG_EOR indicates end-of-record; the data returned completed a record
     (generally used with sockets of type SOCK_SEQPACKET). MSG_TRUNC indicates
     that the trailing portion of a datagram was discarded because the data-
     gram was larger than the buffer supplied.    MSG_CTRUNC indicates that some
     control data were discarded due to lack of space in the buffer for ancil-
     lary data.    MSG_OOB is returned to indicate that expedited or out-of-band
     data were received.

RETURN VALUES
     These calls return the number of bytes received, or -1 if an error oc-
     curred.

EXAMPLES
     The following code is an example of parsing the control information re-
     turned in the msg_control field.  This example shows how to parse the
     control messages for a localdomain(4) socket to obtain passed file de-
     scriptors and the sender's credentials.

     #include <sys/param.h>
     #include <sys/socket.h>
     #include <sys/ucred.h>

     struct msghdr msghdr;
     struct cmsghdr *cm;
     struct fcred *fc;    /* Pointer to the credentials */
     int fdcnt;        /* The number of file descriptors passed */
     int *fds;        /* The passed array of file descriptors */

     #define ENOUGH_CMSG(p, size)    ((p)->cmsg_len >= ((size) + sizeof(*(p))))

     fc = NULL;
     fdcnt = 0;
     fds = NULL;

     if (msghdr.msg_controllen >= sizeof (struct cmsghdr) &&
     (msghdr.msg_flags & MSG_CTRUNC) == 0) {

         for (cm = CMSG_FIRSTHDR(&msghdr);
         cm != NULL && cm->cmsg_len >= sizeof(*cm);
         cm = CMSG_NXTHDR(&msghdr, cm)) {

             if (cm->cmsg_level != SOL_SOCKET)
                 continue;

             switch (cm->cmsg_type) {
             case SCM_RIGHTS:
                 fdcnt = (cm->cmsg_len - sizeof(*cm)) / sizeof(int);
                 fds = (int *)CMSG_DATA(cm);
                 break;

             case SCM_CREDS:
                 if (ENOUGH_CMSG(cm, sizeof(*fc)))
                     fc = (struct fcred *)CMSG_DATA(cm);
                 break;
             }
         }
     }

ERRORS
     The calls fail if:

     [EBADF]    The argument s is an invalid descriptor.

     [ENOTCONN]    The socket is associated with a connection-oriented protocol
         and has not been connected (see connect(2) and accept(2)).

     [ENOTSOCK]    The argument s does not refer to a socket.

     [EAGAIN]    The socket is marked non-blocking, and the receive operation
         would block, or a receive timeout had been set, and the time-
         out expired before data were received.

     [EINTR]    The receive was interrupted by delivery of a signal before
         any data were available.

     [EFAULT]    The receive buffer pointer(s) point outside the process's ad-
         dress space.

SEE ALSO
     fcntl(2),    read(2),  select(2),  getsockopt(2),  socket(2),  ip(4),  lo-
     cal(4)

HISTORY
     The recv function call appeared in 4.2BSD.

4.3-Reno Berkeley Distribution February 21, 1994                 4

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> The following set of patches (relative to 7.1.2 release) implement
> SCM_CREDS authentication for local connections.  On systems which
> support it, this mechanism should be used instead of `trust' for local
> connections.

OK, here is a cleaned up version of the patch that will apply to current
CVS.  I worked it into the SO_PEERCRED code.  I made some changes so it
compiles on BSD/OS.  I am getting "Invalid Argument" from libpq's
sending of the credentials on BSD/OS.  I would be interested to know if
this works on FreeBSD.  Solaris uses this capability too.

Also, we are not updating the protocol version, so I hope it fails
gracefully on old clients.

--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026
Index: src/backend/libpq/auth.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/auth.c,v
retrieving revision 1.57
diff -c -r1.57 auth.c
*** src/backend/libpq/auth.c    2001/08/15 18:42:14    1.57
--- src/backend/libpq/auth.c    2001/08/16 03:41:10
***************
*** 15,24 ****

  #include "postgres.h"

! #include <sys/types.h>            /* needed by in.h on Ultrix */
  #include <netinet/in.h>
  #include <arpa/inet.h>
-
  #include "libpq/auth.h"
  #include "libpq/crypt.h"
  #include "libpq/hba.h"
--- 15,29 ----

  #include "postgres.h"

! #include <sys/types.h>
! #include <sys/socket.h>            /* for SCM_CREDS */
! #ifdef SCM_CREDS
! #include <sys/uio.h>            /* for struct iovec */
! #include <sys/ucred.h>
! #include <errno.h>
! #endif
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include "libpq/auth.h"
  #include "libpq/crypt.h"
  #include "libpq/hba.h"
***************
*** 28,39 ****
  #include "miscadmin.h"

  static void sendAuthRequest(Port *port, AuthRequest areq);
-
  static int    checkPassword(Port *port, char *user, char *password);
  static int    old_be_recvauth(Port *port);
  static int    map_old_to_new(Port *port, UserAuth old, int status);
  static void auth_failed(Port *port);
-
  static int    recv_and_check_password_packet(Port *port);
  static int    recv_and_check_passwordv0(Port *port);

--- 33,42 ----
***************
*** 493,498 ****
--- 496,507 ----
              break;

          case uaIdent:
+ #ifdef SCM_CREDS
+             /* If we are doing ident on unix-domain sockets,
+                we are going to use SCM_CREDS, if defined. */
+             if (port->raddr.sa.sa_family ==    AF_UNIX)
+                 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
+ #endif
              status = authident(port);
              break;

Index: src/backend/libpq/hba.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/hba.c,v
retrieving revision 1.62
diff -c -r1.62 hba.c
*** src/backend/libpq/hba.c    2001/08/15 18:42:15    1.62
--- src/backend/libpq/hba.c    2001/08/16 03:41:10
***************
*** 19,24 ****
--- 19,30 ----
  #include <errno.h>
  #include <pwd.h>
  #include <sys/types.h>
+ #include <sys/socket.h>            /* for SCM_CREDS */
+ #ifdef SCM_CREDS
+ #include <sys/uio.h>            /* for struct iovec */
+ #include <sys/ucred.h>
+ #include <errno.h>
+ #endif
  #include <fcntl.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
***************
*** 870,876 ****
  static bool
  ident_unix(int sock, char *ident_user)
  {
! #ifdef SO_PEERCRED
      /* Linux style: use getsockopt(SO_PEERCRED) */
      struct ucred    peercred;
      ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
--- 876,966 ----
  static bool
  ident_unix(int sock, char *ident_user)
  {
! #ifdef SCM_CREDS
!     struct msghdr msg;
!     struct {
!         struct cmsghdr hdr;
! #ifndef fc_uid
!         struct cmsgcred cred;
! #define cruid cmcred_uid
! #else
!         struct fcred cred;
! #define cruid fc_uid
! #endif
!     } cmsg;
!     struct iovec iov;
!     char buf;
!     char namebuf[SM_USER + 1];
!     struct passwd *pw;
!
!     msg.msg_name = NULL;
!     msg.msg_namelen = 0;
!     msg.msg_iov = &iov;
!     msg.msg_iovlen = 1;
!     msg.msg_control = (char *)&cmsg;
!     msg.msg_controllen = sizeof cmsg;
!     msg.msg_flags = 0;
!
!     /*
!      * The one character which is received here is not meaningful;
!      * its purposes is only to make sure that recvmsg() blocks
!      * long enough for the other side to send its credentials.
!      */
!     iov.iov_base = &buf;
!     iov.iov_len = 1;
!
!     if (recvmsg(sock, &msg, 0) < 0) {
!         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!              "ident_unix: error receiving credentials: %s\n",
!              strerror(errno));
! errout:
!         fputs(PQerrormsg, stderr);
!         pqdebug("%s", PQerrormsg);
!
!         return false;
!     }
!
!     /*
!      * Make sure we got the right kind of message.
!      */
!     if (cmsg.hdr.cmsg_len != sizeof cmsg
!         || cmsg.hdr.cmsg_level != SOL_SOCKET
!         || cmsg.hdr.cmsg_type != SCM_CREDS) {
!         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!              "ident_unix: protocol error receiving credentials\n");
!         goto errout;
!     }
!
!     snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!          "ident_unix: pid %lu, uid %lu\n",
! #ifndef fc_uid
!          (unsigned long)cmsg.cred.cmcred_pid,
! #else
!          (unsigned long)0, /* unavailable */
! #endif
!          (unsigned long)cmsg.cred.cruid);
!     pqdebug("%s", PQerrormsg);
!
!     strncpy(namebuf, ident_user, SM_USER);
!     namebuf[SM_USER] = '\0';
!
!     pw = getpwnam(namebuf);
!     if (pw == NULL) {
!         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!              "ident_unix: unknown local user %s\n",
!              namebuf);
!         goto errout;
!     }
!
!     if (pw->pw_uid != cmsg.cred.cruid) {
!         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!              "ident_unix: %s's uid %lu != real uid %lu\n",
!              namebuf, (unsigned long)pw->pw_uid,
!              (unsigned long)cmsg.cred.cruid);
!         goto errout;
!     }
!     return true;
! #elif SO_PEERCRED
      /* Linux style: use getsockopt(SO_PEERCRED) */
      struct ucred    peercred;
      ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
***************
*** 906,912 ****

      return true;

! #else /* not SO_PEERCRED */

      snprintf(PQerrormsg, PQERRORMSG_LENGTH,
               "IDENT auth is not supported on local connections on this platform\n");
--- 996,1002 ----

      return true;

! #else

      snprintf(PQerrormsg, PQERRORMSG_LENGTH,
               "IDENT auth is not supported on local connections on this platform\n");
***************
*** 914,920 ****
      pqdebug("%s", PQerrormsg);
      return false;

! #endif /* SO_PEERCRED */
  }

  /*
--- 1004,1010 ----
      pqdebug("%s", PQerrormsg);
      return false;

! #endif
  }

  /*
Index: src/backend/libpq/pg_hba.conf.sample
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/pg_hba.conf.sample,v
retrieving revision 1.24
diff -c -r1.24 pg_hba.conf.sample
*** src/backend/libpq/pg_hba.conf.sample    2001/08/15 18:42:15    1.24
--- src/backend/libpq/pg_hba.conf.sample    2001/08/16 03:41:13
***************
*** 125,136 ****
  #   ident:    For TCP/IP connections, authentication is done by contacting
  #        the ident server on the client host.  (CAUTION: this is only
  #        as secure as the client machine!)  On machines that support
! #        SO_PEERCRED socket requests, this method also works for
! #        local Unix-domain connections.  AUTH_ARGUMENT is required:
! #        it determines how to map remote user names to Postgres user
! #        names.  The AUTH_ARGUMENT is a map name found in the
! #        $PGDATA/pg_ident.conf file. The connection is accepted if
! #        that file contains an entry for this map name with the
  #        ident-supplied username and the requested Postgres username.
  #        The special map name "sameuser" indicates an implied map
  #        (not in pg_ident.conf) that maps each ident username to the
--- 125,136 ----
  #   ident:    For TCP/IP connections, authentication is done by contacting
  #        the ident server on the client host.  (CAUTION: this is only
  #        as secure as the client machine!)  On machines that support
! #        SO_PEERCRED or SCM_CREDS socket requests, this method also
! #        works for local Unix-domain connections.  AUTH_ARGUMENT is
! #        required: it determines how to map remote user names to
! #        Postgres user names.  The AUTH_ARGUMENT is a map name found
! #        in the $PGDATA/pg_ident.conf file. The connection is accepted
! #        if that file contains an entry for this map name with the
  #        ident-supplied username and the requested Postgres username.
  #        The special map name "sameuser" indicates an implied map
  #        (not in pg_ident.conf) that maps each ident username to the
Index: src/include/libpq/pqcomm.h
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/include/libpq/pqcomm.h,v
retrieving revision 1.56
diff -c -r1.56 pqcomm.h
*** src/include/libpq/pqcomm.h    2001/08/15 18:42:15    1.56
--- src/include/libpq/pqcomm.h    2001/08/16 03:41:14
***************
*** 133,138 ****
--- 133,139 ----
  #define AUTH_REQ_PASSWORD    3    /* Password */
  #define AUTH_REQ_CRYPT        4    /* crypt password */
  #define AUTH_REQ_MD5        5    /* md5 password */
+ #define AUTH_REQ_SCM_CREDS    6    /* transfer SCM credentials */

  typedef uint32 AuthRequest;

Index: src/interfaces/libpq/fe-auth.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/libpq/fe-auth.c,v
retrieving revision 1.50
diff -c -r1.50 fe-auth.c
*** src/interfaces/libpq/fe-auth.c    2001/08/15 21:08:21    1.50
--- src/interfaces/libpq/fe-auth.c    2001/08/16 03:41:14
***************
*** 40,50 ****
--- 40,57 ----
  #else
  #include <unistd.h>
  #include <fcntl.h>
+ #ifdef SCM_CREDS
+ #include <sys/uio.h>            /* for struct iovec */
+ #include <sys/ucred.h>
+ #include <errno.h>
+ #endif
  #include <sys/param.h>            /* for MAXHOSTNAMELEN on most */
  #ifndef  MAXHOSTNAMELEN
  #include <netdb.h>                /* for MAXHOSTNAMELEN on some */
  #endif
  #include <pwd.h>
+ #include <sys/types.h>
+ #include <sys/socket.h>            /* for SCM_CREDS */
  #endif

  #ifdef HAVE_CRYPT_H
***************
*** 432,437 ****
--- 439,495 ----

  #endif     /* KRB5 */

+ #ifdef SCM_CREDS
+ static int
+ pg_local_sendauth(char *PQerrormsg, PGconn *conn)
+ {
+     char buf;
+     struct iovec iov;
+     struct {
+         struct cmsghdr hdr;
+ #ifndef fc_uid
+         struct cmsgcred cred;
+ #else
+         struct fcred cred;
+ #endif
+     } cmsg;
+     struct msghdr msg;
+
+     /*
+      * The backend doesn't care what we send here, but it wants
+      * exactly one character to force recvmsg() to block and wait
+      * for us.
+      */
+     buf = '\0';
+     iov.iov_base = &buf;
+     iov.iov_len = 1;
+
+     memset(&cmsg, 0, sizeof cmsg);
+     cmsg.hdr.cmsg_len = sizeof cmsg;
+     cmsg.hdr.cmsg_level = SOL_SOCKET;
+     cmsg.hdr.cmsg_type = SCM_CREDS;
+     /*
+      * cmsg.cred will get filled in with the correct information
+      * by the kernel when this message is sent.
+      */
+
+     msg.msg_name = NULL;
+     msg.msg_namelen = 0;
+     msg.msg_iov = &iov;
+     msg.msg_iovlen = 1;
+     msg.msg_control = &cmsg;
+     msg.msg_controllen = sizeof cmsg;
+     msg.msg_flags = 0;
+
+     if (sendmsg(conn->sock, &msg, 0) == -1) {
+         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+              "pg_local_sendauth: sendmsg: %s\n", strerror(errno));
+         return STATUS_ERROR;
+     }
+     return STATUS_OK;
+ }
+ #endif
+
  static int
  pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
  {
***************
*** 442,447 ****
--- 500,509 ----

      switch (areq)
      {
+         case AUTH_REQ_PASSWORD:
+             /* discard const so we can assign it */
+             crypt_pwd = (char *)password;
+             break;
          case AUTH_REQ_CRYPT:
              crypt_pwd = crypt(password, conn->salt);
              break;
***************
*** 472,482 ****
                  break;
              }
          default:
!             /* discard const so we can assign it */
!             crypt_pwd = (char *)password;
!             break;
      }
-
      ret = pqPacketSend(conn, crypt_pwd, strlen(crypt_pwd) + 1);
      if (areq == AUTH_REQ_MD5)
          free(crypt_pwd);
--- 534,541 ----
                  break;
              }
          default:
!             return STATUS_ERROR;
      }
      ret = pqPacketSend(conn, crypt_pwd, strlen(crypt_pwd) + 1);
      if (areq == AUTH_REQ_MD5)
          free(crypt_pwd);
***************
*** 549,554 ****
--- 608,625 ----
                  return STATUS_ERROR;
              }
              break;
+
+         case AUTH_REQ_SCM_CREDS:
+ #ifdef SCM_CREDS
+             if (pg_local_sendauth(PQerrormsg, conn) != STATUS_OK)
+                 return STATUS_ERROR;
+ #else
+             snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+                      libpq_gettext("SCM_CRED authentication method not supported\n"));
+             return STATUS_ERROR;
+ #endif
+             break;
+
          default:
              snprintf(PQerrormsg, PQERRORMSG_LENGTH,
                       libpq_gettext("authentication method %u not supported\n"), areq);
Index: src/interfaces/odbc/connection.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/odbc/connection.c,v
retrieving revision 1.33
diff -c -r1.33 connection.c
*** src/interfaces/odbc/connection.c    2001/08/15 18:42:16    1.33
--- src/interfaces/odbc/connection.c    2001/08/16 03:41:15
***************
*** 722,727 ****
--- 722,732 ----
                              self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
                              return 0;

+                         case AUTH_REQ_SCM_CREDS:
+                             self->errormsg = "Unix socket credential authentication not supported";
+                             self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
+                             return 0;
+
                          default:
                              self->errormsg = "Unknown authentication type";
                              self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
Index: src/interfaces/odbc/connection.h
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/odbc/connection.h,v
retrieving revision 1.25
diff -c -r1.25 connection.h
*** src/interfaces/odbc/connection.h    2001/08/15 18:42:16    1.25
--- src/interfaces/odbc/connection.h    2001/08/16 03:41:20
***************
*** 94,99 ****
--- 94,100 ----
  #define AUTH_REQ_PASSWORD                            3
  #define AUTH_REQ_CRYPT                                4
  #define AUTH_REQ_MD5                                5
+ #define AUTH_REQ_SCM_CREDS                            6

  /*    Startup Packet sizes */
  #define SM_DATABASE                                    64

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> There are some funky alignment macros that you probably need to use on
> BSD/OS.  Also, as written this will break on NetBSD and OpenBSD for
> reasons I have already noted (the structure is named something
> different there), and those systems will also require the alignment
> macros.  (Basically, putting the two structures in another larger
> structure is a shortcut in my implementation which only works because
> the compiler puts the right amount of padding in; on those other
> systems, more padding is required.)

OK, here is an even better version.  It handles the lack of alignment in
the the structure passing.  This works on BSD/OS and should work on
FreeBSD too.

I will apply it in a day or so unless someone finds a problem.

--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026
Index: src/backend/libpq/auth.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/auth.c,v
retrieving revision 1.62
diff -c -r1.62 auth.c
*** src/backend/libpq/auth.c    2001/08/17 15:44:17    1.62
--- src/backend/libpq/auth.c    2001/08/18 04:04:51
***************
*** 15,24 ****

  #include "postgres.h"

! #include <sys/types.h>            /* needed by in.h on Ultrix */
  #include <netinet/in.h>
  #include <arpa/inet.h>
-
  #include "libpq/auth.h"
  #include "libpq/crypt.h"
  #include "libpq/hba.h"
--- 15,29 ----

  #include "postgres.h"

! #include <sys/types.h>
! #include <sys/socket.h>            /* for SCM_CREDS */
! #ifdef SCM_CREDS
! #include <sys/uio.h>            /* for struct iovec */
! #include <sys/ucred.h>
! #include <errno.h>
! #endif
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include "libpq/auth.h"
  #include "libpq/crypt.h"
  #include "libpq/hba.h"
***************
*** 28,39 ****
  #include "miscadmin.h"

  static void sendAuthRequest(Port *port, AuthRequest areq);
-
  static int    checkPassword(Port *port, char *user, char *password);
  static int    old_be_recvauth(Port *port);
  static int    map_old_to_new(Port *port, UserAuth old, int status);
  static void auth_failed(Port *port);
-
  static int    recv_and_check_password_packet(Port *port);
  static int    recv_and_check_passwordv0(Port *port);

--- 33,42 ----
***************
*** 493,498 ****
--- 496,519 ----
              break;

          case uaIdent:
+ #ifdef SCM_CREDS
+ #ifdef fc_uid
+             /* If we are doing ident on unix-domain sockets,
+                we are going to use SCM_CREDS, if defined. BSD/OS */
+             /* Receive credentials on next message receipt, BSD/OS */
+             {
+                 int on = 1;
+                 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
+                 {
+                     elog(FATAL,
+                          "pg_local_sendauth: can't do setsockopt: %s\n", strerror(errno));
+                     return;
+                 }
+             }
+ #endif
+             if (port->raddr.sa.sa_family ==    AF_UNIX)
+                 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
+ #endif
              status = authident(port);
              break;

***************
*** 676,678 ****
--- 697,700 ----

      return status;
  }
+
Index: src/backend/libpq/hba.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/hba.c,v
retrieving revision 1.64
diff -c -r1.64 hba.c
*** src/backend/libpq/hba.c    2001/08/16 16:24:15    1.64
--- src/backend/libpq/hba.c    2001/08/18 04:04:52
***************
*** 19,24 ****
--- 19,30 ----
  #include <errno.h>
  #include <pwd.h>
  #include <sys/types.h>
+ #include <sys/socket.h>            /* for SCM_CREDS */
+ #ifdef SCM_CREDS
+ #include <sys/uio.h>            /* for struct iovec */
+ #include <sys/ucred.h>
+ #include <errno.h>
+ #endif
  #include <fcntl.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
***************
*** 864,870 ****
  static bool
  ident_unix(int sock, char *ident_user)
  {
! #ifdef SO_PEERCRED
      /* Linux style: use getsockopt(SO_PEERCRED) */
      struct ucred    peercred;
      ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
--- 870,942 ----
  static bool
  ident_unix(int sock, char *ident_user)
  {
! #ifdef SCM_CREDS
!     struct msghdr msg;
!
! /* Credentials structure */
! #ifndef fc_uid
!     typedef struct cmsgcred Cred;
! #define cruid cmcred_uid
! #else
!     typedef struct fcred Cred;
! #define cruid fc_uid
! #endif
!     Cred *cred;
!
!     /* Compute size without padding */
!     char cmsgmem[sizeof(struct cmsghdr) + sizeof(Cred)];
!     /* Point to start of first structure */
!     struct cmsghdr *cmsg = (struct cmsghdr *)cmsgmem;
!
!     struct iovec iov;
!     char buf;
!     struct passwd *pw;
!
!     memset(&msg, 0, sizeof(msg));
!     msg.msg_iov = &iov;
!     msg.msg_iovlen = 1;
!     msg.msg_control = (char *)cmsg;
!     msg.msg_controllen = sizeof(cmsgmem);
!     memset(cmsg, 0, sizeof(cmsgmem));
!
!     /*
!      * The one character which is received here is not meaningful;
!      * its purposes is only to make sure that recvmsg() blocks
!      * long enough for the other side to send its credentials.
!      */
!     iov.iov_base = &buf;
!     iov.iov_len = 1;
!
!     if (recvmsg(sock, &msg, 0) < 0 ||
!         cmsg->cmsg_len < sizeof(cmsgmem) ||
!         cmsg->cmsg_type != SCM_CREDS)
!     {
!         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!                  "ident_unix: error receiving credentials: %s\n",
!                  strerror(errno));
!         fputs(PQerrormsg, stderr);
!         pqdebug("%s", PQerrormsg);
!         return false;
!     }
!
!     cred = (Cred *)CMSG_DATA(cmsg);
!
!     pw = getpwuid(cred->fc_uid);
!     if (pw == NULL)
!     {
!         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!              "ident_unix: unknown local user with uid %d\n",
!              cred->fc_uid);
!         fputs(PQerrormsg, stderr);
!         pqdebug("%s", PQerrormsg);
!         return false;
!     }
!
!     StrNCpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX+1);
!
!     return true;
!
! #elif SO_PEERCRED
      /* Linux style: use getsockopt(SO_PEERCRED) */
      struct ucred    peercred;
      ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
***************
*** 888,894 ****

      if (pass == NULL)
      {
-         /* Error - no username with the given uid */
          snprintf(PQerrormsg, PQERRORMSG_LENGTH,
                   "There is no entry in /etc/passwd with the socket's uid\n");
          fputs(PQerrormsg, stderr);
--- 960,965 ----
***************
*** 896,914 ****
          return false;
      }

!     StrNCpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX);

      return true;

! #else /* not SO_PEERCRED */
!
      snprintf(PQerrormsg, PQERRORMSG_LENGTH,
               "IDENT auth is not supported on local connections on this platform\n");
      fputs(PQerrormsg, stderr);
      pqdebug("%s", PQerrormsg);
      return false;

! #endif /* SO_PEERCRED */
  }

  /*
--- 967,985 ----
          return false;
      }

!     StrNCpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX+1);

      return true;

! #else
      snprintf(PQerrormsg, PQERRORMSG_LENGTH,
               "IDENT auth is not supported on local connections on this platform\n");
      fputs(PQerrormsg, stderr);
      pqdebug("%s", PQerrormsg);
+
      return false;

! #endif
  }

  /*
Index: src/backend/libpq/pg_hba.conf.sample
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/pg_hba.conf.sample,v
retrieving revision 1.25
diff -c -r1.25 pg_hba.conf.sample
*** src/backend/libpq/pg_hba.conf.sample    2001/08/16 16:24:16    1.25
--- src/backend/libpq/pg_hba.conf.sample    2001/08/18 04:04:54
***************
*** 127,138 ****
  #   ident:    For TCP/IP connections, authentication is done by contacting
  #        the ident server on the client host.  (CAUTION: this is only
  #        as secure as the client machine!)  On machines that support
! #        SO_PEERCRED socket requests, this method also works for
! #        local Unix-domain connections.  AUTH_ARGUMENT is required:
! #        it determines how to map remote user names to Postgres user
! #        names.  The AUTH_ARGUMENT is a map name found in the
! #        $PGDATA/pg_ident.conf file. The connection is accepted if
! #        that file contains an entry for this map name with the
  #        ident-supplied username and the requested Postgres username.
  #        The special map name "sameuser" indicates an implied map
  #        (not in pg_ident.conf) that maps each ident username to the
--- 127,138 ----
  #   ident:    For TCP/IP connections, authentication is done by contacting
  #        the ident server on the client host.  (CAUTION: this is only
  #        as secure as the client machine!)  On machines that support
! #        SO_PEERCRED or SCM_CREDS socket requests, this method also
! #        works for local Unix-domain connections.  AUTH_ARGUMENT is
! #        required: it determines how to map remote user names to
! #        Postgres user names.  The AUTH_ARGUMENT is a map name found
! #        in the $PGDATA/pg_ident.conf file. The connection is accepted
! #        if that file contains an entry for this map name with the
  #        ident-supplied username and the requested Postgres username.
  #        The special map name "sameuser" indicates an implied map
  #        (not in pg_ident.conf) that maps each ident username to the
Index: src/include/libpq/pqcomm.h
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/include/libpq/pqcomm.h,v
retrieving revision 1.57
diff -c -r1.57 pqcomm.h
*** src/include/libpq/pqcomm.h    2001/08/16 04:27:18    1.57
--- src/include/libpq/pqcomm.h    2001/08/18 04:04:55
***************
*** 133,138 ****
--- 133,139 ----
  #define AUTH_REQ_PASSWORD    3    /* Password */
  #define AUTH_REQ_CRYPT        4    /* crypt password */
  #define AUTH_REQ_MD5        5    /* md5 password */
+ #define AUTH_REQ_SCM_CREDS    6    /* transfer SCM credentials */

  typedef uint32 AuthRequest;

Index: src/interfaces/libpq/fe-auth.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/libpq/fe-auth.c,v
retrieving revision 1.55
diff -c -r1.55 fe-auth.c
*** src/interfaces/libpq/fe-auth.c    2001/08/17 15:40:07    1.55
--- src/interfaces/libpq/fe-auth.c    2001/08/18 04:04:56
***************
*** 40,50 ****
--- 40,57 ----
  #else
  #include <unistd.h>
  #include <fcntl.h>
+ #ifdef SCM_CREDS
+ #include <sys/uio.h>            /* for struct iovec */
+ #include <sys/ucred.h>
+ #include <errno.h>
+ #endif
  #include <sys/param.h>            /* for MAXHOSTNAMELEN on most */
  #ifndef  MAXHOSTNAMELEN
  #include <netdb.h>                /* for MAXHOSTNAMELEN on some */
  #endif
  #include <pwd.h>
+ #include <sys/types.h>
+ #include <sys/socket.h>            /* for SCM_CREDS */
  #endif

  #ifdef HAVE_CRYPT_H
***************
*** 428,433 ****
--- 435,487 ----

  #endif     /* KRB5 */

+ #ifdef SCM_CREDS
+ static int
+ pg_local_sendauth(char *PQerrormsg, PGconn *conn)
+ {
+     char buf;
+     struct iovec iov;
+     struct msghdr msg;
+ #ifndef fc_uid
+     /* Prevent padding */
+     char cmsgmem[sizeof(struct cmsghdr) + sizeof(struct cmsgcred)];
+     /* Point to start of first structure */
+     struct cmsghdr *cmsg = (struct cmsghdr *)cmsgmem;
+ #endif
+
+     /*
+      * The backend doesn't care what we send here, but it wants
+      * exactly one character to force recvmsg() to block and wait
+      * for us.
+      */
+     buf = '\0';
+     iov.iov_base = &buf;
+     iov.iov_len = 1;
+
+     memset(&msg, 0, sizeof(msg));
+     msg.msg_iov = &iov;
+     msg.msg_iovlen = 1;
+
+ #ifndef fc_uid
+     /* Create control header, FreeBSD */
+     msg.msg_control = cmsg;
+     msg.msg_controllen = sizeof(cmsgmem);
+     memset(cmsg, 0, sizeof(cmsgmem));
+     cmsg.hdr.cmsg_len = sizeof(cmsgmem);
+     cmsg.hdr.cmsg_level = SOL_SOCKET;
+     cmsg.hdr.cmsg_type = SCM_CREDS;
+ #endif
+
+     if (sendmsg(conn->sock, &msg, 0) == -1)
+     {
+         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+              "pg_local_sendauth: sendmsg: %s\n", strerror(errno));
+         return STATUS_ERROR;
+     }
+     return STATUS_OK;
+ }
+ #endif
+
  static int
  pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
  {
***************
*** 473,484 ****
              crypt_pwd = crypt(password, salt);
              break;
          }
!         default:
              /* discard const so we can assign it */
              crypt_pwd = (char *)password;
              break;
      }
-
      ret = pqPacketSend(conn, crypt_pwd, strlen(crypt_pwd) + 1);
      if (areq == AUTH_REQ_MD5)
          free(crypt_pwd);
--- 527,539 ----
              crypt_pwd = crypt(password, salt);
              break;
          }
!         case AUTH_REQ_PASSWORD:
              /* discard const so we can assign it */
              crypt_pwd = (char *)password;
              break;
+         default:
+             return STATUS_ERROR;
      }
      ret = pqPacketSend(conn, crypt_pwd, strlen(crypt_pwd) + 1);
      if (areq == AUTH_REQ_MD5)
          free(crypt_pwd);
***************
*** 551,556 ****
--- 606,623 ----
                  return STATUS_ERROR;
              }
              break;
+
+         case AUTH_REQ_SCM_CREDS:
+ #ifdef SCM_CREDS
+             if (pg_local_sendauth(PQerrormsg, conn) != STATUS_OK)
+                 return STATUS_ERROR;
+ #else
+             snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+                      libpq_gettext("SCM_CRED authentication method not supported\n"));
+             return STATUS_ERROR;
+ #endif
+             break;
+
          default:
              snprintf(PQerrormsg, PQERRORMSG_LENGTH,
                       libpq_gettext("authentication method %u not supported\n"), areq);
Index: src/interfaces/odbc/connection.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/odbc/connection.c,v
retrieving revision 1.34
diff -c -r1.34 connection.c
*** src/interfaces/odbc/connection.c    2001/08/17 02:59:20    1.34
--- src/interfaces/odbc/connection.c    2001/08/18 04:04:57
***************
*** 724,729 ****
--- 724,734 ----
                              self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
                              return 0;

+                         case AUTH_REQ_SCM_CREDS:
+                             self->errormsg = "Unix socket credential authentication not supported";
+                             self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
+                             return 0;
+
                          default:
                              self->errormsg = "Unknown authentication type";
                              self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
Index: src/interfaces/odbc/connection.h
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/odbc/connection.h,v
retrieving revision 1.25
diff -c -r1.25 connection.h
*** src/interfaces/odbc/connection.h    2001/08/15 18:42:16    1.25
--- src/interfaces/odbc/connection.h    2001/08/18 04:05:00
***************
*** 94,99 ****
--- 94,100 ----
  #define AUTH_REQ_PASSWORD                            3
  #define AUTH_REQ_CRYPT                                4
  #define AUTH_REQ_MD5                                5
+ #define AUTH_REQ_SCM_CREDS                            6

  /*    Startup Packet sizes */
  #define SM_DATABASE                                    64

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Peter Eisentraut
Date:
Bruce Momjian writes:

> OK, here is an even better version.  It handles the lack of alignment in
> the the structure passing.  This works on BSD/OS and should work on
> FreeBSD too.

Since this patch overwrites the previous SO_PEERCRED patch I assume you
want it to work on Linux, too.  On Linux SCM_CREDS is called
SCM_CREDENTIALS.  There's no sys/ucred.h (use sys/socket.h instead), and
there's no fc_uid, though I don't know what that does.  The invocation
changes to StrNCpy look suspicious; see the comment at StrNCpy in c.h.  In
one place you include errno.h twice.

--
Peter Eisentraut   peter_e@gmx.net   http://funkturm.homeip.net/~peter


Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Tom Lane
Date:
Peter Eisentraut <peter_e@gmx.net> writes:
> Since this patch overwrites the previous SO_PEERCRED patch I assume you
> want it to work on Linux, too.  On Linux SCM_CREDS is called
> SCM_CREDENTIALS.

Overwrite?  It looks like an addition to me.  I think the #ifdef tests
in ident_unix are in the wrong order, however: we should prefer
SO_PEERCRED if available, since that works with old clients.  As written
the postmaster code will select SCM_CREDS if both methods are available,
which is the wrong choice IMHO.

> The invocation
> changes to StrNCpy look suspicious; see the comment at StrNCpy in c.h.  In
> one place you include errno.h twice.

These are good points.

            regards, tom lane

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> Bruce Momjian writes:
>
> > OK, here is an even better version.  It handles the lack of alignment in
> > the the structure passing.  This works on BSD/OS and should work on
> > FreeBSD too.
>
> Since this patch overwrites the previous SO_PEERCRED patch I assume you
> want it to work on Linux, too.  On Linux SCM_CREDS is called

Actually, I made the test for CRED's before PEER because I thought
CRED's was more portable, and because there is a test where I ask for a
dummy send so I can get the creds and if I did PEER first, I would have
to do an #ifdef PEER then #ifdef SCM which seemed kind of weird.  I did
document that I was defining CRED first.  I can easily prefer PEER if
people think that is better.

> SCM_CREDENTIALS.  There's no sys/ucred.h (use sys/socket.h instead), and

Interesting.  Should we remove PEER and go with some kind of CRED's on
all platforms?  Remember, PEER hasn't been released yet in our code.  It
came from Debian and was only used there in a beta release.

> there's no fc_uid, though I don't know what that does.  The invocation
> changes to StrNCpy look suspicious; see the comment at StrNCpy in c.h.  In
> one place you include errno.h twice.

I see:

    char        ident_user[IDENT_USERNAME_MAX + 1];

with StrNCpy as:

    StrNCpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX+1);

Am I missing something?

--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> Peter Eisentraut <peter_e@gmx.net> writes:
> > Since this patch overwrites the previous SO_PEERCRED patch I assume you
> > want it to work on Linux, too.  On Linux SCM_CREDS is called
> > SCM_CREDENTIALS.
>
> Overwrite?  It looks like an addition to me.  I think the #ifdef tests
> in ident_unix are in the wrong order, however: we should prefer
> SO_PEERCRED if available, since that works with old clients.  As written
> the postmaster code will select SCM_CREDS if both methods are available,
> which is the wrong choice IMHO.

Yes, but I mentioned PEERCRED is new in 7.2 and wasn't widely
distributed by Debian, so we should decide which we want first.  Also,
let me mention that this could turn out to be a portability headache.
We currently support two SCM_CRED implementations, FreeBSD and BSD/OS,
and they are both different.  I found:

    Linux : SO_PEERCRED
    FreeBSD: SCM_CREDS
    BSD/OS: SCM_CREDS (different from FreeBSD)
    NetBSD: LOCAL_CREDS
    Solaris: Doors

from a 1999 message:

    http://cert.uni-stuttgart.de/archive/bugtraq/1999/01/msg00098.html

I also found this mention:

      BSD/OS, FreeBSD and other BSD derived operating systems also
      have SCM_CREDS that sends credential information through a UNIX
      domain socket. [ Ok, someone point me to some standard that
      documents the semantics. Every BSD camp is doing it differently
      ":( ]

in a 1999 FAQ:

    http://www.attrition.org/~modify/texts/unix/secure-faq.txt

I am slightly concerned that a platform will define SCM_CREDS but not
have an interface we support.  However, from the list above, it seems we
may be safe but not support NetBSD or Solaris versions.

FYI, this email states why BSD/OS and FreeBSD are different.  The
implementor didn't know of the BSD/OS implementation:


http://groups.google.com/groups?q=scm_creds+freebsd+bsd/os&hl=en&safe=off&rnum=1&selm=6n5vnk%24p5k%242%40apakabar.cc.columbia.edu

I think this is a valuable feature to reduce the need to configure local
users as 'trust' or use 'ident' on local tcp/ip sockets.  One possible
solution would be to enable SCM_CREDS _only_ on BSD/OS and FreeBSD and
wait for others to verify it works on their platforms or submit a patch.

> > The invocation
> > changes to StrNCpy look suspicious; see the comment at StrNCpy in c.h.  In
> > one place you include errno.h twice.
>
> These are good points.

Removed the duplicate errno.  Thanks.  I checked the StrNCpy call and I
can't see the problem.  I wrote the thing.  Have I been away from this
too long?  :-)

--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Tom Lane
Date:
Bruce Momjian <pgman@candle.pha.pa.us> writes:
> Yes, but I mentioned PEERCRED is new in 7.2 and wasn't widely
> distributed by Debian, so we should decide which we want first.  Also,
> let me mention that this could turn out to be a portability headache.

Based on your other message, SCM_CREDS will be much more of a
portability headache than PEERCRED.  All the more reason to prefer
the latter if available.

            regards, tom lane

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> Bruce Momjian <pgman@candle.pha.pa.us> writes:
> > Yes, but I mentioned PEERCRED is new in 7.2 and wasn't widely
> > distributed by Debian, so we should decide which we want first.  Also,
> > let me mention that this could turn out to be a portability headache.
>
> Based on your other message, SCM_CREDS will be much more of a
> portability headache than PEERCRED.  All the more reason to prefer
> the latter if available.

Agreed.  Patch attached.  Seems I had socket.h included twice too. Also,
is there a reason fe-auth has the PostgreSQL includes before the system
ones.

And also, there is #ifdef, but there is no version of #elif for #ifdef,
right?  Nothing like #eldef, so I have to use #elif defined().

--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026
Index: src/backend/libpq/auth.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/auth.c,v
retrieving revision 1.62
diff -c -r1.62 auth.c
*** src/backend/libpq/auth.c    2001/08/17 15:44:17    1.62
--- src/backend/libpq/auth.c    2001/08/19 16:37:30
***************
*** 15,24 ****

  #include "postgres.h"

! #include <sys/types.h>            /* needed by in.h on Ultrix */
  #include <netinet/in.h>
  #include <arpa/inet.h>
-
  #include "libpq/auth.h"
  #include "libpq/crypt.h"
  #include "libpq/hba.h"
--- 15,29 ----

  #include "postgres.h"

! #include <sys/types.h>
! #include <sys/socket.h>            /* for SCM_CREDS */
! #ifdef SCM_CREDS
! #include <sys/uio.h>            /* for struct iovec */
! #include <sys/ucred.h>
! #include <errno.h>
! #endif
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include "libpq/auth.h"
  #include "libpq/crypt.h"
  #include "libpq/hba.h"
***************
*** 28,39 ****
  #include "miscadmin.h"

  static void sendAuthRequest(Port *port, AuthRequest areq);
-
  static int    checkPassword(Port *port, char *user, char *password);
  static int    old_be_recvauth(Port *port);
  static int    map_old_to_new(Port *port, UserAuth old, int status);
  static void auth_failed(Port *port);
-
  static int    recv_and_check_password_packet(Port *port);
  static int    recv_and_check_passwordv0(Port *port);

--- 33,42 ----
***************
*** 493,498 ****
--- 496,521 ----
              break;

          case uaIdent:
+ #if !defined(SO_PEERCRED) && defined(SCM_CREDS)
+             /*
+              *    If we are doing ident on unix-domain sockets,
+              *    use SCM_CREDS only if it is defined and SO_PEERCRED isn't.
+              */
+ #ifdef fc_uid
+             /* Receive credentials on next message receipt, BSD/OS */
+             {
+                 int on = 1;
+                 if (setsockopt(port->sock, 0, LOCAL_CREDS, &on, sizeof(on)) < 0)
+                 {
+                     elog(FATAL,
+                          "pg_local_sendauth: can't do setsockopt: %s\n", strerror(errno));
+                     return;
+                 }
+             }
+ #endif
+             if (port->raddr.sa.sa_family ==    AF_UNIX)
+                 sendAuthRequest(port, AUTH_REQ_SCM_CREDS);
+ #endif
              status = authident(port);
              break;

***************
*** 676,678 ****
--- 699,702 ----

      return status;
  }
+
Index: src/backend/libpq/hba.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/hba.c,v
retrieving revision 1.64
diff -c -r1.64 hba.c
*** src/backend/libpq/hba.c    2001/08/16 16:24:15    1.64
--- src/backend/libpq/hba.c    2001/08/19 16:37:30
***************
*** 18,26 ****

  #include <errno.h>
  #include <pwd.h>
- #include <sys/types.h>
  #include <fcntl.h>
! #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <unistd.h>
--- 18,30 ----

  #include <errno.h>
  #include <pwd.h>
  #include <fcntl.h>
! #include <sys/types.h>
! #include <sys/socket.h>            /* for SCM_CREDS */
! #ifdef SCM_CREDS
! #include <sys/uio.h>            /* for struct iovec */
! #include <sys/ucred.h>
! #endif
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <unistd.h>
***************
*** 876,914 ****
      {
          /* We didn't get a valid credentials struct. */
          snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!                  "Could not get valid credentials from the UNIX socket: %s\n",
                   strerror(errno));
          fputs(PQerrormsg, stderr);
          pqdebug("%s", PQerrormsg);
          return false;
      }

-     /* Convert UID to user login name */
      pass = getpwuid(peercred.uid);

      if (pass == NULL)
      {
-         /* Error - no username with the given uid */
          snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!                  "There is no entry in /etc/passwd with the socket's uid\n");
          fputs(PQerrormsg, stderr);
          pqdebug("%s", PQerrormsg);
          return false;
      }

!     StrNCpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX);

      return true;

! #else /* not SO_PEERCRED */

      snprintf(PQerrormsg, PQERRORMSG_LENGTH,
               "IDENT auth is not supported on local connections on this platform\n");
      fputs(PQerrormsg, stderr);
      pqdebug("%s", PQerrormsg);
      return false;

! #endif /* SO_PEERCRED */
  }

  /*
--- 880,982 ----
      {
          /* We didn't get a valid credentials struct. */
          snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!                  "ident_unix: error receiving credentials: %s\n",
                   strerror(errno));
          fputs(PQerrormsg, stderr);
          pqdebug("%s", PQerrormsg);
          return false;
      }

      pass = getpwuid(peercred.uid);

      if (pass == NULL)
      {
          snprintf(PQerrormsg, PQERRORMSG_LENGTH,
!              "ident_unix: unknown local user with uid %d\n",
          fputs(PQerrormsg, stderr);
          pqdebug("%s", PQerrormsg);
          return false;
      }

!     StrNCpy(ident_user, pass->pw_name, IDENT_USERNAME_MAX+1);

      return true;
+
+ #elif defined(SCM_CREDS)
+     struct msghdr msg;
+
+ /* Credentials structure */
+ #ifndef fc_uid
+     typedef struct cmsgcred Cred;
+ #define cruid cmcred_uid
+ #else
+     typedef struct fcred Cred;
+ #define cruid fc_uid
+ #endif
+     Cred *cred;
+
+     /* Compute size without padding */
+     char cmsgmem[sizeof(struct cmsghdr) + sizeof(Cred)];
+     /* Point to start of first structure */
+     struct cmsghdr *cmsg = (struct cmsghdr *)cmsgmem;
+
+     struct iovec iov;
+     char buf;
+     struct passwd *pw;
+
+     memset(&msg, 0, sizeof(msg));
+     msg.msg_iov = &iov;
+     msg.msg_iovlen = 1;
+     msg.msg_control = (char *)cmsg;
+     msg.msg_controllen = sizeof(cmsgmem);
+     memset(cmsg, 0, sizeof(cmsgmem));
+
+     /*
+      * The one character which is received here is not meaningful;
+      * its purposes is only to make sure that recvmsg() blocks
+      * long enough for the other side to send its credentials.
+      */
+     iov.iov_base = &buf;
+     iov.iov_len = 1;
+
+     if (recvmsg(sock, &msg, 0) < 0 ||
+         cmsg->cmsg_len < sizeof(cmsgmem) ||
+         cmsg->cmsg_type != SCM_CREDS)
+     {
+         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+                  "ident_unix: error receiving credentials: %s\n",
+                  strerror(errno));
+         fputs(PQerrormsg, stderr);
+         pqdebug("%s", PQerrormsg);
+         return false;
+     }
+
+     cred = (Cred *)CMSG_DATA(cmsg);
+
+     pw = getpwuid(cred->fc_uid);
+     if (pw == NULL)
+     {
+         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+              "ident_unix: unknown local user with uid %d\n",
+              cred->fc_uid);
+         fputs(PQerrormsg, stderr);
+         pqdebug("%s", PQerrormsg);
+         return false;
+     }
+
+     StrNCpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX+1);

!     return true;

+ #else
      snprintf(PQerrormsg, PQERRORMSG_LENGTH,
               "IDENT auth is not supported on local connections on this platform\n");
      fputs(PQerrormsg, stderr);
      pqdebug("%s", PQerrormsg);
+
      return false;

! #endif
  }

  /*
Index: src/backend/libpq/pg_hba.conf.sample
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/backend/libpq/pg_hba.conf.sample,v
retrieving revision 1.25
diff -c -r1.25 pg_hba.conf.sample
*** src/backend/libpq/pg_hba.conf.sample    2001/08/16 16:24:16    1.25
--- src/backend/libpq/pg_hba.conf.sample    2001/08/19 16:37:33
***************
*** 127,138 ****
  #   ident:    For TCP/IP connections, authentication is done by contacting
  #        the ident server on the client host.  (CAUTION: this is only
  #        as secure as the client machine!)  On machines that support
! #        SO_PEERCRED socket requests, this method also works for
! #        local Unix-domain connections.  AUTH_ARGUMENT is required:
! #        it determines how to map remote user names to Postgres user
! #        names.  The AUTH_ARGUMENT is a map name found in the
! #        $PGDATA/pg_ident.conf file. The connection is accepted if
! #        that file contains an entry for this map name with the
  #        ident-supplied username and the requested Postgres username.
  #        The special map name "sameuser" indicates an implied map
  #        (not in pg_ident.conf) that maps each ident username to the
--- 127,138 ----
  #   ident:    For TCP/IP connections, authentication is done by contacting
  #        the ident server on the client host.  (CAUTION: this is only
  #        as secure as the client machine!)  On machines that support
! #        SO_PEERCRED or SCM_CREDS socket requests, this method also
! #        works for local Unix-domain connections.  AUTH_ARGUMENT is
! #        required: it determines how to map remote user names to
! #        Postgres user names.  The AUTH_ARGUMENT is a map name found
! #        in the $PGDATA/pg_ident.conf file. The connection is accepted
! #        if that file contains an entry for this map name with the
  #        ident-supplied username and the requested Postgres username.
  #        The special map name "sameuser" indicates an implied map
  #        (not in pg_ident.conf) that maps each ident username to the
Index: src/include/libpq/pqcomm.h
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/include/libpq/pqcomm.h,v
retrieving revision 1.57
diff -c -r1.57 pqcomm.h
*** src/include/libpq/pqcomm.h    2001/08/16 04:27:18    1.57
--- src/include/libpq/pqcomm.h    2001/08/19 16:37:34
***************
*** 133,138 ****
--- 133,139 ----
  #define AUTH_REQ_PASSWORD    3    /* Password */
  #define AUTH_REQ_CRYPT        4    /* crypt password */
  #define AUTH_REQ_MD5        5    /* md5 password */
+ #define AUTH_REQ_SCM_CREDS    6    /* transfer SCM credentials */

  typedef uint32 AuthRequest;

Index: src/interfaces/libpq/fe-auth.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/libpq/fe-auth.c,v
retrieving revision 1.55
diff -c -r1.55 fe-auth.c
*** src/interfaces/libpq/fe-auth.c    2001/08/17 15:40:07    1.55
--- src/interfaces/libpq/fe-auth.c    2001/08/19 16:37:35
***************
*** 30,35 ****
--- 30,36 ----

  #include "postgres_fe.h"

+ /* XXX is there a reason these appear before the system defines? */
  #include "libpq-fe.h"
  #include "libpq-int.h"
  #include "fe-auth.h"
***************
*** 40,45 ****
--- 41,53 ----
  #else
  #include <unistd.h>
  #include <fcntl.h>
+ #include <errno.h>
+ #include <sys/types.h>
+ #include <sys/socket.h>            /* for SCM_CREDS */
+ #ifdef SCM_CREDS
+ #include <sys/uio.h>            /* for struct iovec */
+ #include <sys/ucred.h>
+ #endif
  #include <sys/param.h>            /* for MAXHOSTNAMELEN on most */
  #ifndef  MAXHOSTNAMELEN
  #include <netdb.h>                /* for MAXHOSTNAMELEN on some */
***************
*** 428,433 ****
--- 436,488 ----

  #endif     /* KRB5 */

+ #ifdef SCM_CREDS
+ static int
+ pg_local_sendauth(char *PQerrormsg, PGconn *conn)
+ {
+     char buf;
+     struct iovec iov;
+     struct msghdr msg;
+ #ifndef fc_uid
+     /* Prevent padding */
+     char cmsgmem[sizeof(struct cmsghdr) + sizeof(struct cmsgcred)];
+     /* Point to start of first structure */
+     struct cmsghdr *cmsg = (struct cmsghdr *)cmsgmem;
+ #endif
+
+     /*
+      * The backend doesn't care what we send here, but it wants
+      * exactly one character to force recvmsg() to block and wait
+      * for us.
+      */
+     buf = '\0';
+     iov.iov_base = &buf;
+     iov.iov_len = 1;
+
+     memset(&msg, 0, sizeof(msg));
+     msg.msg_iov = &iov;
+     msg.msg_iovlen = 1;
+
+ #ifndef fc_uid
+     /* Create control header, FreeBSD */
+     msg.msg_control = cmsg;
+     msg.msg_controllen = sizeof(cmsgmem);
+     memset(cmsg, 0, sizeof(cmsgmem));
+     cmsg.hdr.cmsg_len = sizeof(cmsgmem);
+     cmsg.hdr.cmsg_level = SOL_SOCKET;
+     cmsg.hdr.cmsg_type = SCM_CREDS;
+ #endif
+
+     if (sendmsg(conn->sock, &msg, 0) == -1)
+     {
+         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+              "pg_local_sendauth: sendmsg: %s\n", strerror(errno));
+         return STATUS_ERROR;
+     }
+     return STATUS_OK;
+ }
+ #endif
+
  static int
  pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
  {
***************
*** 473,484 ****
              crypt_pwd = crypt(password, salt);
              break;
          }
!         default:
              /* discard const so we can assign it */
              crypt_pwd = (char *)password;
              break;
      }
-
      ret = pqPacketSend(conn, crypt_pwd, strlen(crypt_pwd) + 1);
      if (areq == AUTH_REQ_MD5)
          free(crypt_pwd);
--- 528,540 ----
              crypt_pwd = crypt(password, salt);
              break;
          }
!         case AUTH_REQ_PASSWORD:
              /* discard const so we can assign it */
              crypt_pwd = (char *)password;
              break;
+         default:
+             return STATUS_ERROR;
      }
      ret = pqPacketSend(conn, crypt_pwd, strlen(crypt_pwd) + 1);
      if (areq == AUTH_REQ_MD5)
          free(crypt_pwd);
***************
*** 551,556 ****
--- 607,624 ----
                  return STATUS_ERROR;
              }
              break;
+
+         case AUTH_REQ_SCM_CREDS:
+ #ifdef SCM_CREDS
+             if (pg_local_sendauth(PQerrormsg, conn) != STATUS_OK)
+                 return STATUS_ERROR;
+ #else
+             snprintf(PQerrormsg, PQERRORMSG_LENGTH,
+                      libpq_gettext("SCM_CRED authentication method not supported\n"));
+             return STATUS_ERROR;
+ #endif
+             break;
+
          default:
              snprintf(PQerrormsg, PQERRORMSG_LENGTH,
                       libpq_gettext("authentication method %u not supported\n"), areq);
Index: src/interfaces/odbc/connection.c
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/odbc/connection.c,v
retrieving revision 1.34
diff -c -r1.34 connection.c
*** src/interfaces/odbc/connection.c    2001/08/17 02:59:20    1.34
--- src/interfaces/odbc/connection.c    2001/08/19 16:37:36
***************
*** 724,729 ****
--- 724,734 ----
                              self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
                              return 0;

+                         case AUTH_REQ_SCM_CREDS:
+                             self->errormsg = "Unix socket credential authentication not supported";
+                             self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
+                             return 0;
+
                          default:
                              self->errormsg = "Unknown authentication type";
                              self->errornumber = CONN_AUTH_TYPE_UNSUPPORTED;
Index: src/interfaces/odbc/connection.h
===================================================================
RCS file: /home/projects/pgsql/cvsroot/pgsql/src/interfaces/odbc/connection.h,v
retrieving revision 1.25
diff -c -r1.25 connection.h
*** src/interfaces/odbc/connection.h    2001/08/15 18:42:16    1.25
--- src/interfaces/odbc/connection.h    2001/08/19 16:37:36
***************
*** 94,99 ****
--- 94,100 ----
  #define AUTH_REQ_PASSWORD                            3
  #define AUTH_REQ_CRYPT                                4
  #define AUTH_REQ_MD5                                5
+ #define AUTH_REQ_SCM_CREDS                            6

  /*    Startup Packet sizes */
  #define SM_DATABASE                                    64

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Garrett Wollman
Date:
<<On Tue, 14 Aug 2001 20:54:42 -0400 (EDT), Bruce Momjian <pgman@candle.pha.pa.us> said:

> Is that OK with everyone.  Since we have peer with Linux, seems we
> should add CRED_ in the same release.

One thing to be careful about: there are several different versions of
this functionality, and not all of them use the same data structures.
Probably you should include a configure test to figure out which
version is available.

-GAWollman


Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Bruce Momjian
Date:
> <<On Tue, 14 Aug 2001 20:54:42 -0400 (EDT), Bruce Momjian <pgman@candle.pha.pa.us> said:
>
> > Is that OK with everyone.  Since we have peer with Linux, seems we
> > should add CRED_ in the same release.
>
> One thing to be careful about: there are several different versions of
> this functionality, and not all of them use the same data structures.
> Probably you should include a configure test to figure out which
> version is available.

Well, I already can test between FreeBSD and BSD/OS with an existing
define that is only in BSD/OS.  When we get another platform, I can
either add a configure test or another define test.

Is there any value to a configure test if I don't know what to test for
other than SCM_CREDS?

--
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026

Re: Patch: use SCM_CREDS authentication over PF_LOCAL sockets

From
Garrett Wollman
Date:
<<On Mon, 20 Aug 2001 10:36:01 -0400 (EDT), Bruce Momjian <pgman@candle.pha.pa.us> said:

> Well, I already can test between FreeBSD and BSD/OS with an existing
> define that is only in BSD/OS.  When we get another platform, I can
> either add a configure test or another define test.

I thought I already mentioned this.  NetBSD and OpenBSD have a different
name for the credential structure.  So you need to check which structure
<sys/socket.h> defines.

-GAWollman