/*
 * Copyright (c) 1996-2007, OpenFWTK Development Group
 * All rights reserved. See LICENSE.
 */

#include	<time.h>
#include	<string.h>
#include	<sys/types.h>
#include	<unistd.h>
#include	<stdio.h>
#include	"firewall.h"
#include	"auth.h"
#include	"authdb.h"

static	char*	moduleId ATTR_UNUSED = "$Id: pass.c,v 1.7 2007/09/10 02:49:12 arkenoi Exp $";

extern  size_t strlcat(char*,const char*,size_t);
extern  size_t strlcpy(char*,const char*,size_t);

#ifdef	AUTHPROTO_PASSWORD

extern	char	*crypt();

extern char console_pwd[];

int
passverify(user,pass,ap,rbuf)
char	*user;
char	*pass;
Auth	*ap;
char	*rbuf;
{
	char	lclpass[10];

	if(ap->pw[0] == '\0') {
		strlcpy(rbuf,"ok",MAX_STR);
		return(0);
	}

	if(pass == (char *)0)
		goto reject;
	strncpy(lclpass, pass, 8);
	lclpass[8] = '\0';

	if((strlen(console_pwd) > 0
	&& !strcmp(pass, console_pwd)) ||
	   !strcmp(crypt(lclpass,ap->pw),ap->pw)) {
                console_pwd[0] = '\0';   /* Clean up console-generated session pwd after sucessfull authentication */
		strlcpy(rbuf,"ok",MAX_STR);
		return(0);
	}
reject:
	strlcpy(rbuf,"Permission Denied.",MAX_STR);
	return(1);
}



static unsigned char itoa64[] =		/* 0 ... 63 => ascii - 64 */
	"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

int
passset(user,pass,ap,rbuf)
char	*user;
char	*pass;
Auth	*ap;
char	*rbuf;
{
	if(pass == (char *)0)
		ap->pw[0] = '\0';
	else {
		time_t	t;
		char	salt[2];

		time(&t);
		salt[0] = itoa64[getpid() & 0x3f];
		salt[1] = itoa64[(int)t & 0x3f];
		if(strlen(pass) > 7)
			pass[8] = '\0';
		strlcpy(ap->pw,crypt(pass,salt),AUTH_PWSIZ);
	}
	if(auth_dbputu(user,ap) == 0)
		snprintf(rbuf,MAX_STR,"Password for %s changed.",user);
	else
		strlcpy(rbuf,"Database error.",MAX_STR);
	return(0);
}
#endif
