/*
 * Copyright (c) 2003-2011
 * Distributed Systems Software.  All rights reserved.
 * See the file LICENSE for redistribution information.
 */

/*****************************************************************************
 * COPYRIGHT AND PERMISSION NOTICE
 * 
 * Copyright (c) 2001-2003 The Queen in Right of Canada
 * 
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, and/or sell
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, provided that the above copyright notice(s) and this
 * permission notice appear in all copies of the Software and that both the
 * above copyright notice(s) and this permission notice appear in supporting
 * documentation.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE 
 * BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, 
 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS 
 * SOFTWARE.
 * 
 * Except as contained in this notice, the name of a copyright holder shall not
 * be used in advertising or otherwise to promote the sale, use or other
 * dealings in this Software without prior written authorization of the
 * copyright holder.
 ***************************************************************************/

/*
 * Unix password based authentication.
 * Installations that use shadow passwords and access them via getspnam()
 * must have HAVE_GETSPNAM defined.
 * On some Unix platforms, getpwnam() can be configured to use YP (NIS)
 * maps and so this program may inherit that capability.
 * This program will likely have to run as root to get at the (real) password
 * file.
 */

#ifndef lint
static const char copyright[] =
"Copyright (c) 2003-2011\n\
Distributed Systems Software.  All rights reserved.";
static const char revid[] =
  "$Id: local_unix_auth.c 2528 2011-09-23 21:54:05Z brachman $";
#endif

#include "dacs.h"

static const char *log_module_name = "local_unix_auth";

static char *get_encrypted_passwd_by_name(char *username);

#ifdef HAVE_GETSPNAM
#include <shadow.h>

static char *
get_encrypted_passwd_by_name(char *username)
{
  struct spwd *spwd;

  if ((spwd = getspnam(username)) == NULL) {
	log_err((LOG_ERROR_LEVEL, "getspnam() failed for '%s'", username));
	return(NULL);
  }

  return(strdup(spwd->sp_pwdp));
}
#else
#include <pwd.h>

static char *
get_encrypted_passwd_by_name(char *username)
{
  struct passwd *pwd;

  if ((pwd = getpwnam(username)) == NULL) {
	log_err((LOG_ERROR_LEVEL, "getpwnam() failed for '%s'", username));
	return(NULL);
  }

  return(strdup(pwd->pw_passwd));
}
#endif

/*
 * Simple Unix password authentication
 * This must have root privileges to retrieve the encrypted password,
 * otherwise the encrypted password won't be returned (although getpwnam()
 * will appear to be successful).
 * We assume the caller destroys the plaintext password as soon as we
 * return.
 * Return 0 if authentication succeeds, -1 otherwise.
 */
int
local_unix_auth(char *username, char *password, char *aux)
{
  char *encrypted_pass, *epwd, *salt;

  if (username == NULL || password == NULL || password[0] == '\0') {
	log_msg((LOG_DEBUG_LEVEL, "Missing username or password"));
	return(-1);
  }

  if ((epwd = get_encrypted_passwd_by_name(username)) == NULL) {
	log_msg((LOG_DEBUG_LEVEL, "Password lookup for \"%s\" failed", username));
	return(-1);
  }

  if (epwd[0] == '\0') {
	log_msg((LOG_ERROR_LEVEL, "Invalid encrypted password for \"%s\"",
			 username));
	return(-1);
  }
  salt = epwd;

  if ((encrypted_pass = crypt(password, salt)) == NULL) {
	log_msg((LOG_ERROR_LEVEL, "Can't compute encrypted password for \"%s\"",
			 username));
	return(-1);
  }

  if (streq(encrypted_pass, epwd)) {
	log_msg((LOG_INFO_LEVEL, "Auth succeeded for username=\"%s\"", username));
	return(0);
  }

  /* We failed, probably because we couldn't get the encrypted password. */
  if (geteuid() != 0)
	log_msg((LOG_ERROR_LEVEL, "Check that this program is running as root."));

  log_msg((LOG_TRACE_LEVEL, "Auth failed for username=\"%s\"", username));
  log_msg((LOG_TRACE_LEVEL | LOG_SENSITIVE_FLAG,
		   "Using password=\"%s\"", password));

  return(-1);
}

#ifdef PROG
int
main(int argc, char **argv)
{
  int emitted_dtd, i;
  char *errmsg, *jurisdiction, *username, *password, *aux;
  Auth_reply_ok ok;
  Kwv *kwv;

  errmsg = "internal";
  emitted_dtd = 0;
  username = password = aux = jurisdiction = NULL;

  if (dacs_init(DACS_LOCAL_SERVICE, &argc, &argv, &kwv, &errmsg) == -1) {
	/* If we fail here, we may not have a DTD with which to reply... */
  fail:
	if (password != NULL)
	  strzap(password);
	if (aux != NULL)
	  strzap(aux);
	if (emitted_dtd) {
	  printf("%s\n", make_xml_auth_reply_failed(NULL, NULL));
	  emit_xml_trailer(stdout);
	}
	if (errmsg != NULL)
	  log_msg((LOG_ERROR_LEVEL, "Failed: reason=%s", errmsg));

	exit(1);
  }

  /* This must go after initialization. */
  emitted_dtd = emit_xml_header(stdout, "auth_reply");

  if (argc > 1) {
	errmsg = "Usage: unrecognized parameter";
	goto fail;
  }

  for (i = 0; i < kwv->nused; i++) {
	if (streq(kwv->pairs[i]->name, "USERNAME") && username == NULL)
	  username = kwv->pairs[i]->val;
	else if (streq(kwv->pairs[i]->name, "PASSWORD") && password == NULL)
	  password = kwv->pairs[i]->val;
	else if (streq(kwv->pairs[i]->name, "AUXILIARY") && aux == NULL)
	  aux = kwv->pairs[i]->val;
	else if (streq(kwv->pairs[i]->name, "DACS_JURISDICTION")
			 && jurisdiction == NULL)
	  jurisdiction = kwv->pairs[i]->val;
	else if (streq(kwv->pairs[i]->name, "DACS_VERSION"))
	  ;
	else
	  log_msg((LOG_TRACE_LEVEL, "Parameter: '%s'", kwv->pairs[i]->name));
  }

  /* If possible, verify that we're truly responsible for DACS_JURISDICTION */
  if (dacs_verify_jurisdiction(jurisdiction) == -1) {
	errmsg = "Missing or incorrect DACS_JURISDICTION";
	goto fail;
  }

  if (local_unix_auth(username, password, aux) == -1) {
	errmsg = "Username/Password/Aux incorrect";
	goto fail;
  }

  if (password != NULL)
	strzap(password);
  if (aux != NULL)
	strzap(aux);

  ok.username = username;
  /* If this wasn't specified, dacs_authenticate will use the default. */
  ok.lifetime = kwv_lookup_value(kwv, "CREDENTIALS_LIFETIME_SECS");
  ok.roles_reply = NULL;
  printf("%s\n", make_xml_auth_reply_ok(&ok));

  emit_xml_trailer(stdout);
  exit(0);
}
#endif
