nss-shared-helper/db.c
author Wolfgang Rosenauer <wr@rosenauer.org>
Thu, 08 Dec 2011 21:55:40 +0100
changeset 1 98d01e6fd2bd
parent 0 262e1fb001a8
child 3 1d5c74914855
permissions -rw-r--r--
$HOME/.pki/nssdb is now considered automatically if /etc/pki/nssdb does not exist

/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */

/* db.c - Helper funcs for shared NSS database
 *
 * Copyright (C) 2008 Hans Petter Jansson
 *               2008-2011 Wolfgang Rosenauer
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Authors: Hans Petter Jansson <hpj@copyleft.no>
 *          Wolfgang Rosenauer <wr@rosenauer.org> */

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>

#include <nspr.h>
#include <nss.h>
#include <pk11priv.h>
#include <pk11pub.h>

#include "nss-shared-helper.h"

#define DEFAULT_RELATIVE_PATH ".pki/nssdb"
#define DEFAULT_PATH          "/etc/pki/nssdb"

typedef struct {
  enum {
    PW_NONE = 0,
    PW_FROMFILE = 1,
    PW_PLAINTEXT = 2,
    PW_EXTERNAL = 3
  } source;
  char *data;
} secuPWData;

char *
nsshelp_get_user_db_path (void)
{
  const char  *env;
  char        *path;
  char         system_path[] = DEFAULT_PATH;
  struct stat  sbuf;
  int          result;

  env = getenv ("NSS_SHARED_DB_PATH");

  /*
   * 1. use env NSS_SHARED_DB_PATH
   * 2. try /etc/pki/nssdb
   * 3. use $HOME/.pki/nssdb
   */
  if (env && *env) {
    path = strdup (env);
  } else {
    env = getenv ("HOME");
    if (env && *env)
    {
      path = malloc (strlen (env) + 1 + strlen (DEFAULT_RELATIVE_PATH) + 1);
      strcpy (path, env);
      strcat (path, "/");
      strcat (path, DEFAULT_RELATIVE_PATH);
    }
  }

  /* Create path if it doesn't exist */
  result = stat (path, &sbuf);
  if (result != 0)
  {
    const char *p0 = path;
    const char *p1;

    while (*p0 == '/')
      p0++;

    /* Try to create it with restrictive permissions */

    do
    {
      p1 = strchr (p0, '/');

      if (p1 == NULL)
        p1 = p0 + strlen (p0);

      if (p1 != p0)
      {
        char *path_part = strdup (path);

        *(path_part + (p1 - path)) = '\0';
        mkdir (path_part, 0700);
      }

      p0 = p1 + 1;
    }
    while (*p1 != '\0');
  }

  /* /etc/pki/nssdb */
  if (stat(system_path, &sbuf) == 0 && S_ISDIR (sbuf.st_mode))
    return system_path;

  /* $HOME/.pki/nssdb */
  if (stat(path, &sbuf) == 0 && S_ISDIR (sbuf.st_mode))
    return path;

  free (path);
  return NULL;
}

SECStatus
nsshelp_open_db (const char *app_id, const char *old_path, PRUint32 flags)
{
  char *new_path;
  char *sdb_path;
  struct stat sbuf;
  int result;
  SECStatus rv;
  PK11SlotInfo *slot;
  secuPWData pwdata = { PW_NONE, 0 };

  if (!getenv ("NSS_USE_SHARED_DB"))
  {
    //fprintf (stderr, "*** nss-shared-helper: Shared database disabled (set NSS_USE_SHARED_DB to enable).\n");

    rv = NSS_Initialize (old_path,
                         "", "", "secmod.db",
                         flags);
    return rv;
  }

  new_path = nsshelp_get_user_db_path ();
  if (!new_path)
    return SECFailure;

  fprintf (stderr, "*** nss-shared-helper: Using shared location %s\n", new_path);
  sdb_path = PR_smprintf ("sql:%s", new_path);

  /* simple update (application does not care about the
   * underlying state machine). */

  /* STEP 1: Signal that update/merge may be needed  */

  rv = NSS_InitWithMerge (sdb_path,
                          "", "", "secmod.db",
                          old_path, "", "",
                          app_id, app_id /* prompt name */,
                          flags);

  if (rv == SECFailure)
  {
    /* Don't migrate anything */

    fprintf (stderr, "*** nss-shared-helper: NSS_InitWithMerge failed. Trying NSS_Initialize.\n");

    rv = NSS_Initialize (sdb_path,
                         "", "", "secmod.db",
                         flags);
    PR_smprintf_free (sdb_path);

    if (rv == SECFailure)
      fprintf (stderr, "*** nss-shared-helper: NSS_Initialize failed.\n");

    return rv;
  }

  slot = PK11_GetInternalKeySlot();

  /* Step 2: Determine if update/merge is needed. */

  if (PK11_IsRemovable(slot))
  {
    /* need to update/Merge the database */

    /* Step 3: Authenticate to the token */

    rv = PK11_Authenticate(slot, PR_FALSE, &pwdata);
    if (rv == SECSuccess)
    {
      /* just update the state machine */

      /* Step 4: */
      PK11_IsLoggedIn(slot, &pwdata);
      /* Step 5: */
      PK11_IsPresent(slot);

      /* Step 6: */
      rv = PK11_Authenticate(slot, PR_FALSE, &pwdata);
      if (rv != SECSuccess)
      {
        fprintf (stderr, "*** nss-shared-helper: Second auth call failed: %u.\n",
                 PORT_GetError ());
      }
    }
    else
    {
      fprintf (stderr, "*** nss-shared-helper: First auth call failed: %u.\n",
               PORT_GetError ());
    }
  }

  /* Step 7: NSS is initialized and (possibly) merged, start using it */

  PR_smprintf_free (sdb_path);
  return SECSuccess;
}