/*checkpw.c - obtain a password from the user and check it by encrypting and
  comparing to the first password in the specified encrypted password file.
  If it matches, removed the corresponding entry from the encrypted password
  file and exec a shell.
  Use this in your .login script as follows:
	who am i | egrep -is `cat /etc/defaultdomain`; if ($status != 0) exec checkpw .pw
  By Matthew Belmonte, October 1997.
  Copyright (c) 1197 by the Howard Hughes Medical Institute.*/

#include <stdio.h>
#include <unistd.h>
#include <errno.h>

static char temp_pw_file[] = "pw.tmp";

/*read a password from standard input*/
void get_password(s)
char *s;
  {
  register int i, c;
  i = 0;
  printf("Password: ");
  while((i != 8) && ((c=getchar()) != EOF) && (c != '\n') && (c != '\r'))
    s[i++] = c;
  if(i == 8)
    while(((c=getchar()) != EOF) && (c != '\n') && (c != '\r'))
      ;
  s[i] = '\0';
  }

void main(argc, argv)
int argc;
char **argv;
  {
  register int num_passwords_remaining;
  int old_umask;
  FILE *cipherfile, *newcipherfile;
  char salt[3], ciphertext[81], cleartext[9];
  if(argc != 2)
    {
    fprintf(stderr, "usage: %s <encrypted_passwd_file>\n", *argv);
    exit(1);
    }
  cipherfile = fopen(argv[1], "r");
  if(cipherfile == NULL)
    {
    perror(argv[1]);
    exit(errno);
    }
  if(fscanf(cipherfile, "%s", ciphertext) != 1)
    {
    fprintf(stderr, "No passwords left!\n");
    fclose(cipherfile);
    exit(1);
    }
  salt[0] = ciphertext[0];
  salt[1] = ciphertext[1];
  salt[2] = '\0';
  get_password(cleartext);
  if(strcmp(crypt(cleartext, salt), ciphertext))
    {
    fclose(cipherfile);
    fprintf(stderr, "Wrong.\n");
    exit(1);
    }
  old_umask = umask(0177);
  newcipherfile = fopen(temp_pw_file, "w");
  num_passwords_remaining = 0;
  while(fscanf(cipherfile, "%s", ciphertext) == 1)
    {
    fprintf(newcipherfile, "%s\n", ciphertext);
    num_passwords_remaining++;
    }
  fclose(newcipherfile);
  if(rename(temp_pw_file, argv[1]))
    perror(temp_pw_file);
  printf("%d passwords remaining\n", num_passwords_remaining);
  if(num_passwords_remaining == 0)
    printf("run \"genpw %s\" to get more passwords\n", argv[1]);
  umask(old_umask);
  execl("/bin/csh", "csh", (char *)0);
  perror((char *)0);
  exit(errno);
  }
