Cover V03, I02
Article
Figure 1
Figure 2
Listing 1
Listing 2
Listing 3
Table 1

mar94.tar


Listing 2: Obtaining an encrypted password entry

/*****************************************************************************
*                             Listing 2                                     *
*****************************************************************************/

/*
* Possible password versions:
*     ETCSECURITY    - For IBM AIX, needs -ls at load time (security library)
*     ETCSHADOW      - For Systems using the shadow password file
*     ETCPASSWD      - For Systems using the standard password file
*/

#include        <stdio.h>

#if ETCSECURITY
#include    <usersec.h>
#include    <userpw.h>

struct userpw *pass;
#endif

#define         SHADOWFILE       "/etc/shadow"
#define         PASSWDFILE       "/etc/passwd"

#define         SEPARATOR        ':'
#define         NULLCHAR         '\0'

#define         PASSWDLEN        13

#define         ENTRYFOUND       0
#define         NOENTRYFOUND     -1
#define         NOFILEACCESS     -2

static int  second_field     ();
static char *myindex         ();

int
get_encrypted (uname, password)
char *uname;
char *password;
{
int  ret;

ret = -1;

#if ETCSECURITY
/*
* Use AIX "security" routines to get entry
*/
if ((pass = getuserpw (uname)) != NULL)
{
if (pass->upw_passwd != (char *) NULL)
{
strcpy (password, pass->upw_passwd);
ret = 0;
}
}

return ret;

#endif

#if ETCSHADOW
/*
* If the shadow password file does not exist, then check the
* standard /etc/password file
*/
if (ret = second_field (uname, SHADOWFILE, password) == NOFILEACCESS)
ret = second_field (uname, PASSWDFILE, password);
#endif

#if ETCPASSWD
ret = second_field (uname, PASSWDFILE, password);
#endif

return ret;
}

static int
second_field (uname, filename, password)
char *uname;
char *filename;
char *password;
{
char buf [BUFSIZ];
char *cp1;
char *cp2;
int  ret;
FILE *ffd;

ret = NOENTRYFOUND;

if ((ffd = fopen (filename, "r")) != NULL)
{
/*
* Find the desired entry
*/
while (fgets (buf, BUFSIZ, ffd) != NULL)
{
if ((cp1 = myindex (buf, SEPARATOR)) != NULL)
{
*cp1 = NULLCHAR;
if (strcmp (buf, uname) == 0)
{
/*
* Found entry for user. Now get password in second field
*/
if ((cp2 = myindex (++cp1, SEPARATOR)) != NULL)
{
*cp2 = NULLCHAR;

/*
* Only take first PASSWLEN characters in order to
* ingore any possible password ageing information
*/
strncpy (password, cp1, PASSWDLEN);
password [PASSWDLEN] = NULLCHAR;

ret = ENTRYFOUND;
break;
}
}
}
}

fclose (ffd);
return ret;
}

else
ret = NOFILEACCESS;

return ret;
}

static char *
myindex (s, c)
char *s;
char  c;
{
while (*s)
{
if (*s == c)
return s;
s++;
}

return (*s == c) ? s : NULL;
}