#include <unistd.h>
...
char * password = getpass( "password : " );
...
#define _GNU_SOURCE
#include <stdio.h> #include <stdlib.h> #include <string.h>
#include <unistd.h> #include <termios.h> #include <pwd.h> #include <crypt.h>
static struct termios stored_settings;
void restore_term_setting( void ) {
tcsetattr( 0, TCSANOW, &stored_settings);
}
int main( void ) {
struct termios new_settings;
char * cryptpw; char * my_login = getlogin();
fprintf( stdout, "Password : " );
if( atexit( restore_term_setting ) != 0 ) {
fprintf( stderr, "error on atexit\n" );
exit(1);
}
tcgetattr( 0, &stored_settings );
new_settings = stored_settings;
new_settings.c_lflag &= (~ECHO); tcsetattr( 0, TCSANOW, &new_settings );
char * passwd = NULL;
size_t size = 0;
ssize_t ret;
if( (ret = getline( &passwd, &size, stdin )) == -1 )
exit(1);
char *p = strchr( passwd, '\n' );
*p = 0;
FILE * fp;
if( (fp = fopen( "/etc/shadow", "r" )) == NULL ) {
perror("fopen");
exit(1);
}
struct passwd * shadow_pwd_ent;
cryptpw = NULL;
while( (shadow_pwd_ent = fgetpwent(fp)) != NULL ) {
if( strcmp( my_login, shadow_pwd_ent->pw_name ) == 0 ) {
cryptpw = shadow_pwd_ent->pw_passwd;
break;
}
}
fclose(fp);
int match = strcmp( crypt(passwd, cryptpw), cryptpw );
free(passwd), passwd = NULL;
puts( "" );
if( match == 0 )
printf( "Welcome, %s\n", my_login );
else
printf( "You are not %s\n", my_login );
return 0;
} |