Esempio n. 1
0
static int
ndmp_get_password(char **password)
{
	char *pw1, pw2[257];
	int i;

	for (i = 0; i < NDMP_PASSWORD_RETRIES; i++) {
		/*
		 * getpassphrase use the same buffer to return password, so
		 * copy the result in different buffer, before calling the
		 * getpassphrase again.
		 */
		if ((pw1 =
		    getpassphrase(gettext("Enter new password: "******"Re-enter  password: "******"Both password did not "
					    "match.\n"));
				}
			}
		}
	}
	return (-1);
}
Esempio n. 2
0
/*
 * Prompt the user for a ldap bind password.
 */
static int
get_ldap_bindPassword(char **ret_bindPass) {

	char 	bindPassword[BUFSIZ];
	char	prompt[BUFSIZ];
	char	*bindPass = NULL;

	/* set the initial value for bindPassword buffer */
	(void) memset(bindPassword, 0, BUFSIZ);
	*ret_bindPass = NULL;

	(void) snprintf(prompt, BUFSIZ,
		"Please enter LDAP bind password: "******"Re-enter LDAP bind password to confirm: ");

	bindPass = getpassphrase(prompt);

	if (bindPass == NULL) {
		(void) memset(bindPassword, 0, BUFSIZ);
		return (PASSWD_UNMATCHED);
	}

	if (strcmp(bindPass, bindPassword) != 0) {
		(void) memset(bindPassword, 0, BUFSIZ);
		(void) memset(bindPass, 0, strlen(bindPass));
		return (PASSWD_UNMATCHED);
	} else {
		(void) memset(bindPass, 0, strlen(bindPass));
		if ((*ret_bindPass = (char *)malloc(strlen(bindPassword)+1))
			== NULL) {
			(void) memset(bindPassword, 0, BUFSIZ);
			return (PROMPTGET_MEMORY_FAIL);
		}

		(void) strlcpy(*ret_bindPass, bindPassword,
			strlen(bindPassword)+1);

		/* Clean up and erase the credential info */
		(void) memset(bindPassword, 0, BUFSIZ);

		return (PROMPTGET_SUCCESS);
	}
}
Esempio n. 3
0
static void GetPasswordText(wchar *Str,uint MaxLength)
{
  if (MaxLength==0)
    return;
#ifdef _WIN_ALL
  HANDLE hConIn=GetStdHandle(STD_INPUT_HANDLE);
  HANDLE hConOut=GetStdHandle(STD_OUTPUT_HANDLE);
  DWORD ConInMode,ConOutMode;
  DWORD Read=0;
  GetConsoleMode(hConIn,&ConInMode);
  GetConsoleMode(hConOut,&ConOutMode);
  SetConsoleMode(hConIn,ENABLE_LINE_INPUT);
  SetConsoleMode(hConOut,ENABLE_PROCESSED_OUTPUT|ENABLE_WRAP_AT_EOL_OUTPUT);

  ReadConsole(hConIn,Str,MaxLength-1,&Read,NULL);
  Str[Read]=0;
  SetConsoleMode(hConIn,ConInMode);
  SetConsoleMode(hConOut,ConOutMode);
#else
  char StrA[MAXPASSWORD];
#if defined(_EMX) || defined (__VMS) || defined(__AROS__)
  fgets(StrA,ASIZE(StrA)-1,stdin);
#elif defined(__sun)
  strncpyz(StrA,getpassphrase(""),ASIZE(StrA));
#else
  strncpyz(StrA,getpass(""),ASIZE(StrA));
#endif
  CharToWide(StrA,Str,MaxLength);
  cleandata(StrA,sizeof(StrA));
#endif
  Str[MaxLength-1]=0;
  RemoveLF(Str);
}
Esempio n. 4
0
APR_DECLARE(apr_status_t) apr_password_get(const char *prompt, char *pwbuf, apr_size_t *bufsiz)
{
    apr_status_t rv = APR_SUCCESS;
#if defined(HAVE_GETPASS_R)
    if (getpass_r(prompt, pwbuf, *bufsiz) == NULL)
        return APR_EINVAL;
#else
#if defined(HAVE_GETPASSPHRASE)
    char *pw_got = getpassphrase(prompt);
#elif defined(HAVE_GETPASS)
    char *pw_got = getpass(prompt);
#else /* use the replacement implementation above */
    char *pw_got = get_password(prompt);
#endif

    if (!pw_got)
        return APR_EINVAL;
    if (strlen(pw_got) >= *bufsiz) {
        rv = APR_ENAMETOOLONG;
    }
    apr_cpystrn(pwbuf, pw_got, *bufsiz);
    memset(pw_got, 0, strlen(pw_got));
#endif /* HAVE_GETPASS_R */
    return rv;
}
Esempio n. 5
0
static int
my_conv(int num_msg, PAM_CONST struct pam_message **msg, struct pam_response **response,
	void *appdata_ptr)
{
    PAM_CONST struct pam_message *m;
    struct pam_response *r;
    char *p;

    m = *msg;
    if (response) {
	*response = calloc(num_msg, sizeof(struct pam_response));
	if (*response == NULL)
	    return PAM_BUF_ERR;
	r = *response;
    } else {
	r = NULL;
    }

    while (num_msg--) {
	switch (m->msg_style) {
	case PAM_PROMPT_ECHO_OFF:
#ifdef __hpux
	    /* ON HP's we still read 8 chars */
	    if (r)
		r->resp = strdup(getpass(m->msg));
#else
	    if (r)
		r->resp = strdup(getpassphrase(m->msg));
#endif
	    break;
	case PAM_PROMPT_ECHO_ON:
	    fputs(m->msg, stdout);
	    if (r) {
		r->resp = malloc(PAM_MAX_RESP_SIZE);
		if (fgets(r->resp, PAM_MAX_RESP_SIZE, stdin) == NULL) {
		    fprintf(stderr, "fgets did not work as expected\n");
		    exit(1);
		}
		r->resp[PAM_MAX_RESP_SIZE - 1] = '\0';
		p = &r->resp[strlen(r->resp) - 1];
		while (*p == '\n' && p >= r->resp)
		    *(p--) = '\0';
	    }
	    break;
	case PAM_ERROR_MSG:
	    fputs(m->msg, stderr);
	    break;
	case PAM_TEXT_INFO:
	    fputs(m->msg, stdout);
	    break;
	default:
	    break;
	}
	m++;
	if (r)
	    r++;
    }
    return PAM_SUCCESS;
}
Esempio n. 6
0
wchar_t *isqlt_wgetpassphrase( const wchar_t * prompt )
{
  char *nret;
  char *nprompt = malloc_wide_as_narrow (prompt);

  nret = getpassphrase (nprompt);
  free (nprompt);

  return malloc_narrow_as_wide (nret);
}
Esempio n. 7
0
int pamtestConv(int num_msg, struct pam_message **msgv,
	struct pam_response **respv, void *appdata_ptr)
{
	int i;
	char buf[PAM_MAX_MSG_SIZE];

	fprintf(stderr, "%s:%d pamtestConv num_msg=%d\n",
		__FILE__, __LINE__, num_msg);

	*respv = (struct pam_response *)calloc(num_msg, sizeof(struct pam_response));
	if (*respv == NULL) {
		return PAM_BUF_ERR;
	}

	for (i = 0; i < num_msg; i++) {
		const struct pam_message *msg = msgv[i];
		struct pam_response *resp = &((*respv)[i]);

		char *p = NULL;

		switch (msg->msg_style) {
		case PAM_PROMPT_ECHO_OFF:
#if defined(__linux__) || defined(__APPLE__)
			p = getpass(msg->msg);
#else
			p = getpassphrase(msg->msg);
#endif
			break;
		case PAM_PROMPT_ECHO_ON:
			printf("%s", msg->msg);
			p = fgets(buf, sizeof(buf), stdin);
			if (p != NULL) p[strlen(p) - 1] = '\0';
			break;
		case PAM_ERROR_MSG:
			fprintf(stderr, "%s\n", msg->msg);
			break;
		case PAM_TEXT_INFO:
#ifdef PAM_MSG_NOCONF
		case PAM_MSG_NOCONF:
#endif
			printf("%s\n", msg->msg);
			break;
		default:
#ifdef PAM_CONV_INTERRUPT
		case PAM_CONV_INTERRUPT:
#endif
			return PAM_CONV_ERR;
		}

		resp->resp = (p == NULL) ? NULL : strdup(p);
		resp->resp_retcode = 0;
	}

	return PAM_SUCCESS;
}
Esempio n. 8
0
static int
read_password(const char *prompt, char *pwbuf, size_t pwbuf_len)
{
    char *pass;

#if HAVE_GETPASSPHRASE && !defined(PREFER_GETPASS)
    pass = getpassphrase(prompt);
#else
    pass = getpass(prompt);
#endif
    if (pass == NULL || strlen(pass) >= pwbuf_len)
        return 1;
    strcpy(pwbuf, pass);
    return 0;
}
Esempio n. 9
0
int main (int argc, char **argv)
{
	char *pass;

	if (argc !=2)
		err_quit ("Usage: passwd_comp username");

	pass = getpassphrase ("Password: "******"Password = \"%s\"\n", pass);

	if (compare_passwd (argv [1], pass))
		printf ("Passwords match\n");
	else
		printf ("Passwords don't match\n");

	return (0);
}
Esempio n. 10
0
int
cmd_crypt(int argc, char *argv[])
{
	char *cp, *psw;

	if (argc < 2)
		psw = getpassphrase(gettext("Password:"******"out of memory"));
	smb_simplecrypt(cp, psw);
	printf("%s\n", cp);
	free(cp);
	return (0);
}
Esempio n. 11
0
int main (int argc, char **argv)
{
	char *pass;
	char *salt;
	char *secret;
	struct passwd *pwd;

	if (argc !=2)
		err_quit ("Usage: new_crypt username");

	if ((pwd = getpwnam (argv [1])) == NULL)
		err_quit ("%s: No such user", argv [1]);

	pass = getpassphrase ("Password: "******"Password = \"%s\"\n", pass);
	printf ("Salt = \"%s\"\n", salt);
	printf ("Secret = \"%s\"\n", secret);

	return (0);
}
Esempio n. 12
0
static int interaction(
	unsigned flags,
	sasl_interact_t *interact,
	lutilSASLdefaults *defaults )
{
	const char *dflt = interact->defresult;
	char input[1024];

	int noecho=0;
	int challenge=0;

	switch( interact->id ) {
	case SASL_CB_GETREALM:
		if( defaults ) dflt = defaults->realm;
		break;
	case SASL_CB_AUTHNAME:
		if( defaults ) dflt = defaults->authcid;
		break;
	case SASL_CB_PASS:
		if( defaults ) dflt = defaults->passwd;
		noecho = 1;
		break;
	case SASL_CB_USER:
		if( defaults ) dflt = defaults->authzid;
		break;
	case SASL_CB_NOECHOPROMPT:
		noecho = 1;
		challenge = 1;
		break;
	case SASL_CB_ECHOPROMPT:
		challenge = 1;
		break;
	}

	if( dflt && !*dflt ) dflt = NULL;

	if( flags != LDAP_SASL_INTERACTIVE &&
		( dflt || interact->id == SASL_CB_USER ) )
	{
		goto use_default;
	}

	if( flags == LDAP_SASL_QUIET ) {
		/* don't prompt */
		return LDAP_OTHER;
	}

	if( challenge ) {
		if( interact->challenge ) {
			fprintf( stderr, _("Challenge: %s\n"), interact->challenge );
		}
	}

	if( dflt ) {
		fprintf( stderr, _("Default: %s\n"), dflt );
	}

	snprintf( input, sizeof input, "%s: ",
		interact->prompt ? interact->prompt : _("Interact") );

	if( noecho ) {
		interact->result = (char *) getpassphrase( input );
		interact->len = interact->result
			? strlen( interact->result ) : 0;

	} else {
		/* prompt user */
		fputs( input, stderr );

		/* get input */
		interact->result = fgets( input, sizeof(input), stdin );

		if( interact->result == NULL ) {
			interact->len = 0;
			return LDAP_UNAVAILABLE;
		}

		/* len of input */
		interact->len = strlen(input); 

		if( interact->len > 0 && input[interact->len - 1] == '\n' ) {
			/* input includes '\n', trim it */
			interact->len--;
			input[interact->len] = '\0';
		}
	}


	if( interact->len > 0 ) {
		/* duplicate */
		char *p = (char *)interact->result;
		ldap_charray_add(&defaults->resps, interact->result);
		interact->result = defaults->resps[defaults->nresps++];

		/* zap */
		memset( p, '\0', interact->len );

	} else {
use_default:
		/* input must be empty */
		interact->result = (dflt && *dflt) ? dflt : "";
		interact->len = strlen( interact->result );
	}

	return LDAP_SUCCESS;
}
Esempio n. 13
0
int
main( int argc, char **argv )
{
	int		i, j;
	char		*uri = NULL;
	char		*host = "localhost";
	char		*port = NULL;
	char		*manager = NULL;
	char		*passwd = NULL;
	char		*dirname = NULL;
	char		*progdir = NULL;
	int		loops = LOOPS;
	char		*outerloops = OUTERLOOPS;
	char		*retries = RETRIES;
	char		*delay = "0";
	DIR		*datadir;
	struct dirent	*file;
	int		friendly = 0;
	int		chaserefs = 0;
	int		noattrs = 0;
	int		nobind = 0;
	int		noinit = 1;
	char		*ignore = NULL;
	/* search */
	char		*sfile = NULL;
	char		*sreqs[MAXREQS];
	char		*sattrs[MAXREQS];
	char		*sbase[MAXREQS];
	LDAPURLDesc	*slud[MAXREQS];
	int		snum = 0;
	char		*sargs[MAXARGS];
	int		sanum;
	int		sextra_args = 0;
	char		scmd[MAXPATHLEN];
	int		swamp = 0;
	char		swampopt[sizeof("-SSS")];
	/* static so that its address can be used in initializer below. */
	static char	sloops[LDAP_PVT_INTTYPE_CHARS(unsigned long)];
	/* read */
	char		*rfile = NULL;
	char		*rreqs[MAXREQS];
	int		rnum = 0;
	char		*rargs[MAXARGS];
	char		*rflts[MAXREQS];
	int		ranum;
	int		rextra_args = 0;
	char		rcmd[MAXPATHLEN];
	static char	rloops[LDAP_PVT_INTTYPE_CHARS(unsigned long)];
	/* addel */
	char		*afiles[MAXREQS];
	int		anum = 0;
	char		*aargs[MAXARGS];
	int		aanum;
	char		acmd[MAXPATHLEN];
	static char	aloops[LDAP_PVT_INTTYPE_CHARS(unsigned long)];
	/* modrdn */
	char		*nfile = NULL;
	char		*nreqs[MAXREQS];
	int		nnum = 0;
	char		*nargs[MAXARGS];
	int		nanum;
	char		ncmd[MAXPATHLEN];
	static char	nloops[LDAP_PVT_INTTYPE_CHARS(unsigned long)];
	/* modify */
	char		*mfile = NULL;
	char		*mreqs[MAXREQS];
	char		*mdn[MAXREQS];
	int		mnum = 0;
	char		*margs[MAXARGS];
	int		manum;
	char		mcmd[MAXPATHLEN];
	static char	mloops[LDAP_PVT_INTTYPE_CHARS(unsigned long)];
	/* bind */
	char		*bfile = NULL;
	char		*breqs[MAXREQS];
	char		*bcreds[MAXREQS];
	char		*battrs[MAXREQS];
	int		bnum = 0;
	char		*bargs[MAXARGS];
	int		banum;
	char		bcmd[MAXPATHLEN];
	static char	bloops[LDAP_PVT_INTTYPE_CHARS(unsigned long)];
	char		**bargs_extra = NULL;

	char		*friendlyOpt = NULL;
	int		pw_ask = 0;
	char		*pw_file = NULL;

	/* extra action to do after bind... */
	typedef struct extra_t {
		char		*action;
		struct extra_t	*next;
	}		extra_t;

	extra_t		*extra = NULL;
	int		nextra = 0;

	tester_init( "slapd-tester", TESTER_TESTER );

	sloops[0] = '\0';
	rloops[0] = '\0';
	aloops[0] = '\0';
	nloops[0] = '\0';
	mloops[0] = '\0';
	bloops[0] = '\0';

	while ( ( i = getopt( argc, argv, "AB:CD:d:FH:h:Ii:j:L:l:NP:p:r:St:Ww:y:" ) ) != EOF )
	{
		switch ( i ) {
		case 'A':
			noattrs++;
			break;

		case 'B': {
			char	**p,
				**b = ldap_str2charray( optarg, "," );
			extra_t	**epp;

			for ( epp = &extra; *epp; epp = &(*epp)->next )
				;

			for ( p = b; p[0]; p++ ) {
				*epp = calloc( 1, sizeof( extra_t ) );
				(*epp)->action = p[0];
				epp = &(*epp)->next;
				nextra++;
			}

			ldap_memfree( b );
			} break;

		case 'C':
			chaserefs++;
			break;

		case 'D':		/* slapd manager */
			manager = ArgDup( optarg );
			break;

		case 'd':		/* data directory */
			dirname = strdup( optarg );
			break;

		case 'F':
			friendly++;
			break;

		case 'H':		/* slapd uri */
			uri = strdup( optarg );
			break;

		case 'h':		/* slapd host */
			host = strdup( optarg );
			break;

		case 'I':
			noinit = 0;
			break;

		case 'i':
			ignore = optarg;
			break;

		case 'j':		/* the number of parallel clients */
			if ( lutil_atoi( &maxkids, optarg ) != 0 ) {
				usage( argv[0], 'j' );
			}
			break;

		case 'l':		/* the number of loops per client */
			if ( !isdigit( (unsigned char) optarg[0] ) ) {
				char	**p,
					**l = ldap_str2charray( optarg, "," );

				for ( p = l; p[0]; p++) {
					struct {
						struct berval	type;
						char		*buf;
					} types[] = {
						{ BER_BVC( "add=" ),	aloops },
						{ BER_BVC( "bind=" ),	bloops },
						{ BER_BVC( "modify=" ),	mloops },
						{ BER_BVC( "modrdn=" ),	nloops },
						{ BER_BVC( "read=" ),	rloops },
						{ BER_BVC( "search=" ),	sloops },
						{ BER_BVNULL,		NULL }
					};
					int	c, n;

					for ( c = 0; types[c].type.bv_val; c++ ) {
						if ( strncasecmp( p[0], types[c].type.bv_val, types[c].type.bv_len ) == 0 ) {
							break;
						}
					}

					if ( types[c].type.bv_val == NULL ) {
						usage( argv[0], 'l' );
					}

					if ( lutil_atoi( &n, &p[0][types[c].type.bv_len] ) != 0 ) {
						usage( argv[0], 'l' );
					}

					snprintf( types[c].buf, sizeof( aloops ), "%d", n );
				}

				ldap_charray_free( l );

			} else if ( lutil_atoi( &loops, optarg ) != 0 ) {
				usage( argv[0], 'l' );
			}
			break;

		case 'L':		/* the number of outerloops per client */
			outerloops = strdup( optarg );
			break;

		case 'N':
			nobind++;
			break;

		case 'P':		/* prog directory */
			progdir = strdup( optarg );
			break;

		case 'p':		/* the servers port number */
			port = strdup( optarg );
			break;

		case 'r':		/* the number of retries in case of error */
			retries = strdup( optarg );
			break;

		case 'S':
			swamp++;
			break;

		case 't':		/* the delay in seconds between each retry */
			delay = strdup( optarg );
			break;

		case 'w':		/* the managers passwd */
			passwd = ArgDup( optarg );
			memset( optarg, '*', strlen( optarg ) );
			break;

		case 'W':
			pw_ask++;
			break;

		case 'y':
			pw_file = optarg;
			break;

		default:
			usage( argv[0], '\0' );
			break;
		}
	}

	if (( dirname == NULL ) || ( port == NULL && uri == NULL ) ||
			( manager == NULL ) || ( passwd == NULL ) || ( progdir == NULL ))
	{
		usage( argv[0], '\0' );
	}

#ifdef HAVE_WINSOCK
	children = malloc( maxkids * sizeof(HANDLE) );
#endif
	/* get the file list */
	if ( ( datadir = opendir( dirname )) == NULL ) {
		fprintf( stderr, "%s: couldn't open data directory \"%s\".\n",
					argv[0], dirname );
		exit( EXIT_FAILURE );
	}

	/*  look for search, read, modrdn, and add/delete files */
	for ( file = readdir( datadir ); file; file = readdir( datadir )) {

		if ( !strcasecmp( file->d_name, TSEARCHFILE )) {
			sfile = get_file_name( dirname, file->d_name );
			continue;
		} else if ( !strcasecmp( file->d_name, TREADFILE )) {
			rfile = get_file_name( dirname, file->d_name );
			continue;
		} else if ( !strcasecmp( file->d_name, TMODRDNFILE )) {
			nfile = get_file_name( dirname, file->d_name );
			continue;
		} else if ( !strcasecmp( file->d_name, TMODIFYFILE )) {
			mfile = get_file_name( dirname, file->d_name );
			continue;
		} else if ( !strncasecmp( file->d_name, TADDFILE, strlen( TADDFILE ))
			&& ( anum < MAXREQS )) {
			afiles[anum++] = get_file_name( dirname, file->d_name );
			continue;
		} else if ( !strcasecmp( file->d_name, TBINDFILE )) {
			bfile = get_file_name( dirname, file->d_name );
			continue;
		}
	}

	closedir( datadir );

	if ( pw_ask ) {
		passwd = getpassphrase( _("Enter LDAP Password: "******"no data files found.\n" );
		exit( EXIT_FAILURE );
	}

	/* look for search requests */
	if ( sfile ) {
		snum = get_search_filters( sfile, sreqs, sattrs, sbase, slud );
		if ( snum < 0 ) {
			fprintf( stderr,
				"unable to parse file \"%s\" line %d\n",
				sfile, -2*(snum + 1));
			exit( EXIT_FAILURE );
		}
	}

	/* look for read requests */
	if ( rfile ) {
		rnum = get_read_entries( rfile, rreqs, rflts );
		if ( rnum < 0 ) {
			fprintf( stderr,
				"unable to parse file \"%s\" line %d\n",
				rfile, -2*(rnum + 1) );
			exit( EXIT_FAILURE );
		}
	}

	/* look for modrdn requests */
	if ( nfile ) {
		nnum = get_read_entries( nfile, nreqs, NULL );
		if ( nnum < 0 ) {
			fprintf( stderr,
				"unable to parse file \"%s\" line %d\n",
				nfile, -2*(nnum + 1) );
			exit( EXIT_FAILURE );
		}
	}

	/* look for modify requests */
	if ( mfile ) {
		mnum = get_search_filters( mfile, mreqs, NULL, mdn, NULL );
		if ( mnum < 0 ) {
			fprintf( stderr,
				"unable to parse file \"%s\" line %d\n",
				mfile, -2*(mnum + 1) );
			exit( EXIT_FAILURE );
		}
	}

	/* look for bind requests */
	if ( bfile ) {
		bnum = get_search_filters( bfile, bcreds, battrs, breqs, NULL );
		if ( bnum < 0 ) {
			fprintf( stderr,
				"unable to parse file \"%s\" line %d\n",
				bfile, -2*(bnum + 1) );
			exit( EXIT_FAILURE );
		}
	}

	/* setup friendly option */
	switch ( friendly ) {
	case 0:
		break;

	case 1:
		friendlyOpt = "-F";
		break;

	default:
		/* NOTE: right now we don't need it more than twice */
	case 2:
		friendlyOpt = "-FF";
		break;
	}

	/* setup swamp option */
	if ( swamp ) {
		swampopt[0] = '-';
		if ( swamp > 3 ) swamp = 3;
		swampopt[swamp + 1] = '\0';
		for ( ; swamp-- > 0; ) swampopt[swamp + 1] = 'S';
	}

	/* setup loop options */
	if ( sloops[0] == '\0' ) snprintf( sloops, sizeof( sloops ), "%d", 10 * loops );
	if ( rloops[0] == '\0' ) snprintf( rloops, sizeof( rloops ), "%d", 20 * loops );
	if ( aloops[0] == '\0' ) snprintf( aloops, sizeof( aloops ), "%d", loops );
	if ( nloops[0] == '\0' ) snprintf( nloops, sizeof( nloops ), "%d", loops );
	if ( mloops[0] == '\0' ) snprintf( mloops, sizeof( mloops ), "%d", loops );
	if ( bloops[0] == '\0' ) snprintf( bloops, sizeof( bloops ), "%d", 20 * loops );

	/*
	 * generate the search clients
	 */

	sanum = 0;
	snprintf( scmd, sizeof scmd, "%s" LDAP_DIRSEP SEARCHCMD,
		progdir );
	sargs[sanum++] = scmd;
	if ( uri ) {
		sargs[sanum++] = "-H";
		sargs[sanum++] = uri;
	} else {
		sargs[sanum++] = "-h";
		sargs[sanum++] = host;
		sargs[sanum++] = "-p";
		sargs[sanum++] = port;
	}
	sargs[sanum++] = "-D";
	sargs[sanum++] = manager;
	sargs[sanum++] = "-w";
	sargs[sanum++] = passwd;
	sargs[sanum++] = "-l";
	sargs[sanum++] = sloops;
	sargs[sanum++] = "-L";
	sargs[sanum++] = outerloops;
	sargs[sanum++] = "-r";
	sargs[sanum++] = retries;
	sargs[sanum++] = "-t";
	sargs[sanum++] = delay;
	if ( friendly ) {
		sargs[sanum++] = friendlyOpt;
	}
	if ( chaserefs ) {
		sargs[sanum++] = "-C";
	}
	if ( noattrs ) {
		sargs[sanum++] = "-A";
	}
	if ( nobind ) {
		sargs[sanum++] = "-N";
	}
	if ( ignore ) {
		sargs[sanum++] = "-i";
		sargs[sanum++] = ignore;
	}
	if ( swamp ) {
		sargs[sanum++] = swampopt;
	}
	sargs[sanum++] = "-b";
	sargs[sanum++] = NULL;		/* will hold the search base */
	sargs[sanum++] = "-s";
	sargs[sanum++] = NULL;		/* will hold the search scope */
	sargs[sanum++] = "-f";
	sargs[sanum++] = NULL;		/* will hold the search request */

	sargs[sanum++] = NULL;
	sargs[sanum++] = NULL;		/* might hold the "attr" request */
	sextra_args += 2;

	sargs[sanum] = NULL;

	/*
	 * generate the read clients
	 */

	ranum = 0;
	snprintf( rcmd, sizeof rcmd, "%s" LDAP_DIRSEP READCMD,
		progdir );
	rargs[ranum++] = rcmd;
	if ( uri ) {
		rargs[ranum++] = "-H";
		rargs[ranum++] = uri;
	} else {
		rargs[ranum++] = "-h";
		rargs[ranum++] = host;
		rargs[ranum++] = "-p";
		rargs[ranum++] = port;
	}
	rargs[ranum++] = "-D";
	rargs[ranum++] = manager;
	rargs[ranum++] = "-w";
	rargs[ranum++] = passwd;
	rargs[ranum++] = "-l";
	rargs[ranum++] = rloops;
	rargs[ranum++] = "-L";
	rargs[ranum++] = outerloops;
	rargs[ranum++] = "-r";
	rargs[ranum++] = retries;
	rargs[ranum++] = "-t";
	rargs[ranum++] = delay;
	if ( friendly ) {
		rargs[ranum++] = friendlyOpt;
	}
	if ( chaserefs ) {
		rargs[ranum++] = "-C";
	}
	if ( noattrs ) {
		rargs[ranum++] = "-A";
	}
	if ( ignore ) {
		rargs[ranum++] = "-i";
		rargs[ranum++] = ignore;
	}
	if ( swamp ) {
		rargs[ranum++] = swampopt;
	}
	rargs[ranum++] = "-e";
	rargs[ranum++] = NULL;		/* will hold the read entry */

	rargs[ranum++] = NULL;
	rargs[ranum++] = NULL;		/* might hold the filter arg */
	rextra_args += 2;

	rargs[ranum] = NULL;

	/*
	 * generate the modrdn clients
	 */

	nanum = 0;
	snprintf( ncmd, sizeof ncmd, "%s" LDAP_DIRSEP MODRDNCMD,
		progdir );
	nargs[nanum++] = ncmd;
	if ( uri ) {
		nargs[nanum++] = "-H";
		nargs[nanum++] = uri;
	} else {
		nargs[nanum++] = "-h";
		nargs[nanum++] = host;
		nargs[nanum++] = "-p";
		nargs[nanum++] = port;
	}
	nargs[nanum++] = "-D";
	nargs[nanum++] = manager;
	nargs[nanum++] = "-w";
	nargs[nanum++] = passwd;
	nargs[nanum++] = "-l";
	nargs[nanum++] = nloops;
	nargs[nanum++] = "-L";
	nargs[nanum++] = outerloops;
	nargs[nanum++] = "-r";
	nargs[nanum++] = retries;
	nargs[nanum++] = "-t";
	nargs[nanum++] = delay;
	if ( friendly ) {
		nargs[nanum++] = friendlyOpt;
	}
	if ( chaserefs ) {
		nargs[nanum++] = "-C";
	}
	if ( ignore ) {
		nargs[nanum++] = "-i";
		nargs[nanum++] = ignore;
	}
	nargs[nanum++] = "-e";
	nargs[nanum++] = NULL;		/* will hold the modrdn entry */
	nargs[nanum] = NULL;
	
	/*
	 * generate the modify clients
	 */

	manum = 0;
	snprintf( mcmd, sizeof mcmd, "%s" LDAP_DIRSEP MODIFYCMD,
		progdir );
	margs[manum++] = mcmd;
	if ( uri ) {
		margs[manum++] = "-H";
		margs[manum++] = uri;
	} else {
		margs[manum++] = "-h";
		margs[manum++] = host;
		margs[manum++] = "-p";
		margs[manum++] = port;
	}
	margs[manum++] = "-D";
	margs[manum++] = manager;
	margs[manum++] = "-w";
	margs[manum++] = passwd;
	margs[manum++] = "-l";
	margs[manum++] = mloops;
	margs[manum++] = "-L";
	margs[manum++] = outerloops;
	margs[manum++] = "-r";
	margs[manum++] = retries;
	margs[manum++] = "-t";
	margs[manum++] = delay;
	if ( friendly ) {
		margs[manum++] = friendlyOpt;
	}
	if ( chaserefs ) {
		margs[manum++] = "-C";
	}
	if ( ignore ) {
		margs[manum++] = "-i";
		margs[manum++] = ignore;
	}
	margs[manum++] = "-e";
	margs[manum++] = NULL;		/* will hold the modify entry */
	margs[manum++] = "-a";;
	margs[manum++] = NULL;		/* will hold the ava */
	margs[manum] = NULL;

	/*
	 * generate the add/delete clients
	 */

	aanum = 0;
	snprintf( acmd, sizeof acmd, "%s" LDAP_DIRSEP ADDCMD,
		progdir );
	aargs[aanum++] = acmd;
	if ( uri ) {
		aargs[aanum++] = "-H";
		aargs[aanum++] = uri;
	} else {
		aargs[aanum++] = "-h";
		aargs[aanum++] = host;
		aargs[aanum++] = "-p";
		aargs[aanum++] = port;
	}
	aargs[aanum++] = "-D";
	aargs[aanum++] = manager;
	aargs[aanum++] = "-w";
	aargs[aanum++] = passwd;
	aargs[aanum++] = "-l";
	aargs[aanum++] = aloops;
	aargs[aanum++] = "-L";
	aargs[aanum++] = outerloops;
	aargs[aanum++] = "-r";
	aargs[aanum++] = retries;
	aargs[aanum++] = "-t";
	aargs[aanum++] = delay;
	if ( friendly ) {
		aargs[aanum++] = friendlyOpt;
	}
	if ( chaserefs ) {
		aargs[aanum++] = "-C";
	}
	if ( ignore ) {
		aargs[aanum++] = "-i";
		aargs[aanum++] = ignore;
	}
	aargs[aanum++] = "-f";
	aargs[aanum++] = NULL;		/* will hold the add data file */
	aargs[aanum] = NULL;

	/*
	 * generate the bind clients
	 */

	banum = 0;
	snprintf( bcmd, sizeof bcmd, "%s" LDAP_DIRSEP BINDCMD,
		progdir );
	bargs[banum++] = bcmd;
	if ( !noinit ) {
		bargs[banum++] = "-I";	/* init on each bind */
	}
	if ( uri ) {
		bargs[banum++] = "-H";
		bargs[banum++] = uri;
	} else {
		bargs[banum++] = "-h";
		bargs[banum++] = host;
		bargs[banum++] = "-p";
		bargs[banum++] = port;
	}
	bargs[banum++] = "-l";
	bargs[banum++] = bloops;
	bargs[banum++] = "-L";
	bargs[banum++] = outerloops;
#if 0
	bargs[banum++] = "-r";
	bargs[banum++] = retries;
	bargs[banum++] = "-t";
	bargs[banum++] = delay;
#endif
	if ( friendly ) {
		bargs[banum++] = friendlyOpt;
	}
	if ( chaserefs ) {
		bargs[banum++] = "-C";
	}
	if ( ignore ) {
		bargs[banum++] = "-i";
		bargs[banum++] = ignore;
	}
	if ( nextra ) {
		bargs[banum++] = "-B";
		bargs_extra = &bargs[banum++];
	}
	bargs[banum++] = "-D";
	bargs[banum++] = NULL;
	bargs[banum++] = "-w";
	bargs[banum++] = NULL;
	bargs[banum] = NULL;

#define	DOREQ(n,j) ((n) && ((maxkids > (n)) ? ((j) < maxkids ) : ((j) < (n))))

	for ( j = 0; j < MAXREQS; j++ ) {
		/* search */
		if ( DOREQ( snum, j ) ) {
			int	jj = j % snum;
			int	x = sanum - sextra_args;

			/* base */
			if ( sbase[jj] != NULL ) {
				sargs[sanum - 7] = sbase[jj];

			} else {
				sargs[sanum - 7] = slud[jj]->lud_dn;
			}

			/* scope */
			if ( slud[jj] != NULL ) {
				sargs[sanum - 5] = (char *)ldap_pvt_scope2str( slud[jj]->lud_scope );

			} else {
				sargs[sanum - 5] = "sub";
			}

			/* filter */
			if ( sreqs[jj] != NULL ) {
				sargs[sanum - 3] = sreqs[jj];

			} else if ( slud[jj]->lud_filter != NULL ) {
				sargs[sanum - 3] = slud[jj]->lud_filter;

			} else {
				sargs[sanum - 3] = "(objectClass=*)";
			}

			/* extras */
			sargs[x] = NULL;

			/* attr */
			if ( sattrs[jj] != NULL ) {
				sargs[x++] = "-a";
				sargs[x++] = sattrs[jj];
			}

			/* attrs */
			if ( slud[jj] != NULL && slud[jj]->lud_attrs != NULL ) {
				int	i;

				for ( i = 0; slud[jj]->lud_attrs[ i ] != NULL && x + i < MAXARGS - 1; i++ ) {
					sargs[x + i] = slud[jj]->lud_attrs[ i ];
				}
				sargs[x + i] = NULL;
			}

			fork_child( scmd, sargs );
		}

		/* read */
		if ( DOREQ( rnum, j ) ) {
			int	jj = j % rnum;
			int	x = ranum - rextra_args;

			rargs[ranum - 3] = rreqs[jj];
			if ( rflts[jj] != NULL ) {
				rargs[x++] = "-f";
				rargs[x++] = rflts[jj];
			}
			rargs[x] = NULL;
			fork_child( rcmd, rargs );
		}

		/* rename */
		if ( j < nnum ) {
			nargs[nanum - 1] = nreqs[j];
			fork_child( ncmd, nargs );
		}

		/* modify */
		if ( j < mnum ) {
			margs[manum - 3] = mdn[j];
			margs[manum - 1] = mreqs[j];
			fork_child( mcmd, margs );
		}

		/* add/delete */
		if ( j < anum ) {
			aargs[aanum - 1] = afiles[j];
			fork_child( acmd, aargs );
		}

		/* bind */
		if ( DOREQ( bnum, j ) ) {
			int	jj = j % bnum;

			if ( nextra ) {
				int	n = ((double)nextra)*rand()/(RAND_MAX + 1.0);
				extra_t	*e;

				for ( e = extra; n-- > 0; e = e->next )
					;
				*bargs_extra = e->action;
			}

			if ( battrs[jj] != NULL ) {
				bargs[banum - 3] = manager ? manager : "";
				bargs[banum - 1] = passwd ? passwd : "";

				bargs[banum + 0] = "-b";
				bargs[banum + 1] = breqs[jj];
				bargs[banum + 2] = "-f";
				bargs[banum + 3] = bcreds[jj];
				bargs[banum + 4] = "-a";
				bargs[banum + 5] = battrs[jj];
				bargs[banum + 6] = NULL;

			} else {
				bargs[banum - 3] = breqs[jj];
				bargs[banum - 1] = bcreds[jj];
				bargs[banum] = NULL;
			}

			fork_child( bcmd, bargs );
			bargs[banum] = NULL;
		}
	}

	wait4kids( -1 );

	exit( EXIT_SUCCESS );
}
Esempio n. 14
0
/*
 * Domains comprise a centrally administered group of computers and accounts
 * that share a common security and administration policy and database.
 * Computers must join a domain and become domain members, which requires
 * an administrator level account name.
 *
 * The '+' character is invalid within a username.  We allow the password
 * to be appended to the username using '+' as a scripting convenience.
 */
static int
smbadm_join_domain(const char *domain, const char *username)
{
	smb_joininfo_t jdi;
	uint32_t status;
	char *prompt;
	char *p;
	int len;

	bzero(&jdi, sizeof (jdi));
	jdi.mode = SMB_SECMODE_DOMAIN;
	(void) strlcpy(jdi.domain_name, domain, sizeof (jdi.domain_name));
	(void) strtrim(jdi.domain_name, " \t\n");

	if (smb_name_validate_domain(jdi.domain_name) != ERROR_SUCCESS) {
		(void) fprintf(stderr, gettext("domain name is invalid\n"));
		smbadm_usage(B_FALSE);
	}

	if (!smbadm_join_prompt(jdi.domain_name))
		return (0);

	if ((p = strchr(username, '+')) != NULL) {
		++p;

		len = (int)(p - username);
		if (len > sizeof (jdi.domain_name))
			len = sizeof (jdi.domain_name);

		(void) strlcpy(jdi.domain_username, username, len);
		(void) strlcpy(jdi.domain_passwd, p,
		    sizeof (jdi.domain_passwd));
	} else {
		(void) strlcpy(jdi.domain_username, username,
		    sizeof (jdi.domain_username));
	}

	if (smb_name_validate_account(jdi.domain_username) != ERROR_SUCCESS) {
		(void) fprintf(stderr,
		    gettext("username contains invalid characters\n"));
		smbadm_usage(B_FALSE);
	}

	if (*jdi.domain_passwd == '\0') {
		prompt = gettext("Enter domain password: "******"missing password\n"));
			smbadm_usage(B_FALSE);
		}

		(void) strlcpy(jdi.domain_passwd, p,
		    sizeof (jdi.domain_passwd));
	}

	(void) printf(gettext("Joining %s ... this may take a minute ...\n"),
	    jdi.domain_name);

	status = smb_join(&jdi);

	switch (status) {
	case NT_STATUS_SUCCESS:
		(void) printf(gettext("Successfully joined %s\n"),
		    jdi.domain_name);
		bzero(&jdi, sizeof (jdi));
		smbadm_restart_service();
		return (0);

	case NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND:
		(void) fprintf(stderr,
		    gettext("failed to find any domain controllers for %s\n"),
		    jdi.domain_name);
		bzero(&jdi, sizeof (jdi));
		return (1);

	default:
		(void) fprintf(stderr, gettext("failed to join %s: %s\n"),
		    jdi.domain_name, xlate_nt_status(status));
		(void) fprintf(stderr, gettext("Please refer to the system log"
		    " for more information.\n"));
		bzero(&jdi, sizeof (jdi));
		return (1);
	}
}
Esempio n. 15
0
int
main( int argc, char **argv )
{
	char		*rbuf = NULL, *rejbuf = NULL;
	FILE		*rejfp;
	struct LDIFFP *ldiffp, ldifdummy = {0};
	char		*matched_msg, *error_msg;
	int		rc, retval;
	int		len;
	int		i = 0;
	int		lineno, nextline = 0, lmax = 0;
	LDAPControl	c[1];

	prog = lutil_progname( "ldapmodify", argc, argv );

	/* strncmp instead of strcmp since NT binaries carry .exe extension */
	ldapadd = ( strncasecmp( prog, "ldapadd", sizeof("ldapadd")-1 ) == 0 );

	tool_init( ldapadd ? TOOL_ADD : TOOL_MODIFY );

	tool_args( argc, argv );

	if ( argc != optind ) usage();

	if ( rejfile != NULL ) {
		if (( rejfp = fopen( rejfile, "w" )) == NULL ) {
			perror( rejfile );
			return( EXIT_FAILURE );
		}
	} else {
		rejfp = NULL;
	}

	if ( infile != NULL ) {
		if (( ldiffp = ldif_open( infile, "r" )) == NULL ) {
			perror( infile );
			return( EXIT_FAILURE );
		}
	} else {
		ldifdummy.fp = stdin;
		ldiffp = &ldifdummy;
	}

	if ( debug ) ldif_debug = debug;

	ld = tool_conn_setup( dont, 0 );

	if ( !dont ) {
		if ( pw_file || want_bindpw ) {
			if ( pw_file ) {
				rc = lutil_get_filed_password( pw_file, &passwd );
				if( rc ) return EXIT_FAILURE;
			} else {
				passwd.bv_val = getpassphrase( _("Enter LDAP Password: "******"ldap_txn_start_s", rc, NULL, NULL, NULL, NULL );
			if( txn > 1 ) return EXIT_FAILURE;
			txn = 0;
		}
	}
#endif

	if ( 0
#ifdef LDAP_X_TXN
		|| txn
#endif
		)
	{
#ifdef LDAP_X_TXN
		if( txn ) {
			c[i].ldctl_oid = LDAP_CONTROL_X_TXN_SPEC;
			c[i].ldctl_value = *txn_id;
			c[i].ldctl_iscritical = 1;
			i++;
		}
#endif
	}

	tool_server_controls( ld, c, i );

	rc = 0;
	retval = 0;
	lineno = 1;
	while (( rc == 0 || contoper ) && ldif_read_record( ldiffp, &nextline,
		&rbuf, &lmax ))
	{
		if ( rejfp ) {
			len = strlen( rbuf );
			if (( rejbuf = (char *)ber_memalloc( len+1 )) == NULL ) {
				perror( "malloc" );
				exit( EXIT_FAILURE );
			}
			memcpy( rejbuf, rbuf, len+1 );
		}

		rc = process_ldif_rec( rbuf, lineno );
		lineno = nextline+1;

		if ( rc ) retval = rc;
		if ( rc && rejfp ) {
			fprintf(rejfp, _("# Error: %s (%d)"), ldap_err2string(rc), rc);

			matched_msg = NULL;
			ldap_get_option(ld, LDAP_OPT_MATCHED_DN, &matched_msg);
			if ( matched_msg != NULL ) {
				if ( *matched_msg != '\0' ) {
					fprintf( rejfp, _(", matched DN: %s"), matched_msg );
				}
				ldap_memfree( matched_msg );
			}

			error_msg = NULL;
			ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, &error_msg);
			if ( error_msg != NULL ) {
				if ( *error_msg != '\0' ) {
					fprintf( rejfp, _(", additional info: %s"), error_msg );
				}
				ldap_memfree( error_msg );
			}
			fprintf( rejfp, "\n%s\n", rejbuf );
		}

		if (rejfp) ber_memfree( rejbuf );
	}
	ber_memfree( rbuf );

#ifdef LDAP_X_TXN
	if( retval == 0 && txn ) {
		rc = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
		if ( rc != LDAP_OPT_SUCCESS ) {
			fprintf( stderr, "Could not unset controls for ldap_txn_end\n");
		}

		/* create transaction */
		rc = ldap_txn_end_s( ld, !txnabort, txn_id, NULL, NULL, NULL );
		if( rc != LDAP_SUCCESS ) {
			tool_perror( "ldap_txn_end_s", rc, NULL, NULL, NULL, NULL );
			retval = rc;
		}
	}
#endif

	if ( !dont ) {
		tool_unbind( ld );
	}

	if ( rejfp != NULL ) {
		fclose( rejfp );
	}

	tool_destroy();
	return( retval );
}
Esempio n. 16
0
int
slappasswd( int argc, char *argv[] )
{
#ifdef LUTIL_SHA1_BYTES
	char	*default_scheme = "{SSHA}";
#else
	char	*default_scheme = "{SMD5}";
#endif
	char	*scheme = default_scheme;

	char	*newpw = NULL;
	char	*pwfile = NULL;
	const char *text;
	const char *progname = "slappasswd";

	int		i;
	char		*newline = "\n";
	struct berval passwd = BER_BVNULL;
	struct berval hash;

	while( (i = getopt( argc, argv,
		"c:d:gh:ns:T:vu" )) != EOF )
	{
		switch (i) {
		case 'c':	/* crypt salt format */
			scheme = "{CRYPT}";
			lutil_salt_format( optarg );
			break;

		case 'g':	/* new password (generate) */
			if ( pwfile != NULL ) {
				fprintf( stderr, "Option -g incompatible with -T\n" );
				return EXIT_FAILURE;

			} else if ( newpw != NULL ) {
				fprintf( stderr, "New password already provided\n" );
				return EXIT_FAILURE;

			} else if ( lutil_passwd_generate( &passwd, 8 )) {
				fprintf( stderr, "Password generation failed\n" );
				return EXIT_FAILURE;
			}
			break;

		case 'h':	/* scheme */
			if ( scheme != default_scheme ) {
				fprintf( stderr, "Scheme already provided\n" );
				return EXIT_FAILURE;

			} else {
				scheme = ch_strdup( optarg );
			}
			break;

		case 'n':
			newline = "";
			break;

		case 's':	/* new password (secret) */
			if ( pwfile != NULL ) {
				fprintf( stderr, "Option -s incompatible with -T\n" );
				return EXIT_FAILURE;

			} else if ( newpw != NULL ) {
				fprintf( stderr, "New password already provided\n" );
				return EXIT_FAILURE;

			} else {
				char* p;
				newpw = ch_strdup( optarg );

				for( p = optarg; *p != '\0'; p++ ) {
					*p = '\0';
				}
			}
			break;

		case 'T':	/* password file */
			if ( pwfile != NULL ) {
				fprintf( stderr, "Password file already provided\n" );
				return EXIT_FAILURE;

			} else if ( newpw != NULL ) {
				fprintf( stderr, "Option -T incompatible with -s/-g\n" );
				return EXIT_FAILURE;

			}
			pwfile = optarg;
			break;

		case 'u':	/* RFC2307 userPassword */
			break;

		case 'v':	/* verbose */
			verbose++;
			break;

		default:
			usage ( progname );
		}
	}

	if( argc - optind != 0 ) {
		usage( progname );
	} 

	if( pwfile != NULL ) {
		if( lutil_get_filed_password( pwfile, &passwd )) {
			return EXIT_FAILURE;
		}
	} else if ( BER_BVISEMPTY( &passwd )) {
		if( newpw == NULL ) {
			/* prompt for new password */
			char *cknewpw;
			newpw = ch_strdup(getpassphrase("New password: "******"Re-enter new password: "******"Password values do not match\n" );
				return EXIT_FAILURE;
			}
		}

		passwd.bv_val = newpw;
		passwd.bv_len = strlen(passwd.bv_val);
	} else {
		hash = passwd;
		goto print_pw;
	}

	lutil_passwd_hash( &passwd, scheme, &hash, &text );
	if( hash.bv_val == NULL ) {
		fprintf( stderr,
			"Password generation failed for scheme %s: %s\n",
			scheme, text ? text : "" );
		return EXIT_FAILURE;
	}

	if( lutil_passwd( &hash, &passwd, NULL, &text ) ) {
		fprintf( stderr, "Password verification failed. %s\n",
			text ? text : "" );
		return EXIT_FAILURE;
	}

print_pw:;
	printf( "%s%s" , hash.bv_val, newline );
	return EXIT_SUCCESS;
}
Esempio n. 17
0
int
main( int argc, char *argv[] )
{
	int		rc;
	LDAP		*ld = NULL;
	char		*matcheddn = NULL, *text = NULL, **refs = NULL;
	int rcode;
	char * diag = NULL;
	struct berval	*scookie = NULL;
	struct berval	*scred = NULL;
	int		id, code = 0;
	LDAPMessage	*res;
	LDAPControl	**ctrls = NULL;
	LDAPControl	**vcctrls = NULL;
	int nvcctrls = 0;

	tool_init( TOOL_VC );
	prog = lutil_progname( "ldapvc", argc, argv );

	/* LDAPv3 only */
	protocol = LDAP_VERSION3;

	tool_args( argc, argv );

	if (argc - optind > 0) {
		dn = argv[optind++];
	}
	if (argc - optind > 0) {
		cred.bv_val = strdup(argv[optind++]);
		cred.bv_len = strlen(cred.bv_val);
	}
	if (argc - optind > 0) {
		usage();
	}
	if (dn 
#ifdef LDAP_API_FEATURE_VERIFY_CREDENTIALS_INTERACTIVE
           && !vc_sasl_mech 
#endif
           && !cred.bv_val)
	{
		cred.bv_val = strdup(getpassphrase(_("User's password: "******"ldap_verify_credentials_interactive", rc, NULL, NULL, text, NULL);
				ldap_memfree(text);
				tool_exit(ld, rc);
			}
		} while (rc == LDAP_SASL_BIND_IN_PROGRESS);

	    lutil_sasl_freedefs(defaults);

	    if( rc != LDAP_SUCCESS ) {
			ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*) &text);
		    tool_perror( "ldap_verify_credentials", rc, NULL, NULL, text, NULL );
		    rc = EXIT_FAILURE;
		    goto skip;
	    }

	} else
#endif
#endif
    {
	    rc = ldap_verify_credentials( ld,
		    NULL,
		    dn, NULL, cred.bv_val ? &cred: NULL, vcctrls,
		    NULL, NULL, &id ); 
    
	    if( rc != LDAP_SUCCESS ) {
			ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*) &text);
		    tool_perror( "ldap_verify_credentials", rc, NULL, NULL, text, NULL );
		    rc = EXIT_FAILURE;
		    goto skip;
	    }

	    for ( ; ; ) {
		    struct timeval	tv;

		    if ( tool_check_abandon( ld, id ) ) {
			    tool_exit( ld, LDAP_CANCELLED );
		    }

		    tv.tv_sec = 0;
		    tv.tv_usec = 100000;

		    rc = ldap_result( ld, LDAP_RES_ANY, LDAP_MSG_ALL, &tv, &res );
		    if ( rc < 0 ) {
			    tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
			    tool_exit( ld, rc );
		    }

		    if ( rc != 0 ) {
			    break;
		    }
	    }
	}

	ldap_controls_free(vcctrls);
	vcctrls = NULL;

	rc = ldap_parse_result( ld, res,
		&code, &matcheddn, &text, &refs, &ctrls, 0 );

	if (rc == LDAP_SUCCESS) rc = code;

	if (rc != LDAP_SUCCESS) {
		tool_perror( "ldap_parse_result", rc, NULL, matcheddn, text, refs );
		rc = EXIT_FAILURE;
		goto skip;
	}

	rc = ldap_parse_verify_credentials( ld, res, &rcode, &diag, &scookie, &scred, &vcctrls );
	ldap_msgfree(res);

	if (rc != LDAP_SUCCESS) {
		tool_perror( "ldap_parse_verify_credentials", rc, NULL, NULL, NULL, NULL );
		rc = EXIT_FAILURE;
		goto skip;
	}

	if (rcode != LDAP_SUCCESS) {
		printf(_("Failed: %s (%d)\n"), ldap_err2string(rcode), rcode);
	}

	if (diag && *diag) {
	    printf(_("Diagnostic: %s\n"), diag);
	}

	if (vcctrls) {
		tool_print_ctrls( ld, vcctrls );
	}

skip:
	if ( verbose || code != LDAP_SUCCESS ||
		( matcheddn && *matcheddn ) || ( text && *text ) || refs || ctrls )
	{
		printf( _("Result: %s (%d)\n"), ldap_err2string( code ), code );

		if( text && *text ) {
			printf( _("Additional info: %s\n"), text );
		}

		if( matcheddn && *matcheddn ) {
			printf( _("Matched DN: %s\n"), matcheddn );
		}

		if( refs ) {
			int i;
			for( i=0; refs[i]; i++ ) {
				printf(_("Referral: %s\n"), refs[i] );
			}
		}

		if (ctrls) {
			tool_print_ctrls( ld, ctrls );
			ldap_controls_free( ctrls );
		}
	}

	ber_memfree( text );
	ber_memfree( matcheddn );
	ber_memvfree( (void **) refs );
	ber_bvfree( scookie );
	ber_bvfree( scred );
	ber_memfree( diag );
	free( cred.bv_val );

	/* disconnect from server */
	tool_exit( ld, code == LDAP_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE );
}
Esempio n. 18
0
static int
prompt_pkcs11_pin(libzfs_handle_t *hdl, zfs_cmd_t *zc, zfs_crypto_zckey_t cmd,
    pkcs11_uri_t *p11uri, char **pin, uint32_t *pinlen)
{
	char prompt[MAXPROMPTLEN];
	char *input;
	char dsname[MAXNAMELEN];

	/*
	 * If the PKCS#11 uri has a pinfile argument read the pin from
	 * there.
	 *
	 * Otherwise if the libzfs_handle_t has crypto data we assume this is
	 * the PIN given we can only be in here with a PKCS#11 uri.
	 *
	 * Finally if that is empty then if we can prompt then do so using
	 * getpassphrase().
	 *
	 * Abuse zfs_can_prompt_if_needed() by pretending we are
	 * "passphrase,prompt".
	 */
	if (p11uri->pinfile) {
		struct stat sbuf;
		int pinfd = open(p11uri->pinfile, O_RDONLY);
		char *pbuf;

		if (pinfd == -1)
			return (-1);
		if (fstat(pinfd, &sbuf) != 0)
			return (-1);
		pbuf = zfs_alloc(hdl, sbuf.st_size);
		if (read(pinfd, pbuf, sbuf.st_size) != sbuf.st_size) {
			free(pbuf);
			return (-1);
		}
		(void) close(pinfd);
		pbuf[sbuf.st_size] = '\0';
		*pinlen = sbuf.st_size;
		if (pbuf[sbuf.st_size - 1] == '\n' ||
		    pbuf[sbuf.st_size - 1] == '\r') {
			*pinlen = *pinlen - 1;
		}
		*pin = pbuf;
		return (0);
	}

	if (hdl->libzfs_crypt.zc_key_data != NULL &&
	    hdl->libzfs_crypt.zc_key_data_len != 0) {
		*pinlen = hdl->libzfs_crypt.zc_key_data_len;
		*pin = zfs_alloc(hdl, *pinlen);
		bcopy(hdl->libzfs_crypt.zc_key_data, *pin, *pinlen);
		return (0);
	}
	if (!zfs_can_prompt_if_needed("passphrase,prompt")) {
		errno = ENOTTY;
		return (-1);
	}

	zfs_cmd_target_dsname(zc, cmd, dsname, sizeof (dsname));
	if (p11uri->token)  {
		(void) snprintf(prompt, MAXPROMPTLEN,
		    dgettext(TEXT_DOMAIN,
		    "Enter '%s' PKCS#11 token PIN for '%s': "),
		    p11uri->token, dsname);
	} else {
		(void) snprintf(prompt, MAXPROMPTLEN,
		    dgettext(TEXT_DOMAIN,
		    "Enter PKCS#11 token PIN for '%s': "), dsname);
	}
	input = getpassphrase(prompt);

	if (input != NULL) {
		*pin = strdup(input);
		*pinlen = strlen(*pin);
	} else {
		return (-1);
	}
	return (0);
}
Esempio n. 19
0
static int
get_passphrase(libzfs_handle_t *hdl, char **passphrase,
    size_t *passphraselen, key_format_t format, zfs_cmd_t *zc,
    zfs_crypto_zckey_t cmd)
{
	char prompt[MAXPROMPTLEN];
	char *tmpbuf = NULL;
	int min_psize = 8;
	char dsname[MAXNAMELEN];

    fprintf(stderr, "in get_assphrase\r\n");

	zfs_cmd_target_dsname(zc, cmd, dsname, sizeof (dsname));
	if (format == KEY_FORMAT_HEX) {
		min_psize = 2 *
		    zio_crypt_table[zc->zc_crypto.zic_crypt].ci_keylen;
		if (hdl->libzfs_crypt.zc_is_key_change) {
			(void) snprintf(prompt, MAXPROMPTLEN, "%s \'%s\': ",
			    dgettext(TEXT_DOMAIN,
			    "Enter new hexadecimal key for"),
			    dsname);
		} else {
			(void) snprintf(prompt, MAXPROMPTLEN, "%s \'%s\': ",
			    dgettext(TEXT_DOMAIN,
			    "Enter hexadecimal key for"), dsname);
		}
	} else {
		if (hdl->libzfs_crypt.zc_is_key_change) {
			(void) snprintf(prompt, MAXPROMPTLEN, "%s \'%s\': ",
			    dgettext(TEXT_DOMAIN,
			    "Enter new passphrase for"), dsname);
		} else {
			(void) snprintf(prompt, MAXPROMPTLEN, "%s \'%s\': ",
			    dgettext(TEXT_DOMAIN,
			    "Enter passphrase for"), dsname);
		}
	}

	tmpbuf = getpassphrase(prompt);
	if (tmpbuf == NULL && errno == ENXIO)
		return (EAGAIN);
	if (tmpbuf == NULL || strlen(tmpbuf) < min_psize) {
		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
		    "Must be at least %d characters.\n"), min_psize);
		return (EAGAIN);
	}

	*passphrase = strdup(tmpbuf);
	tmpbuf = NULL;

	/*
	 * A create/clone/recv or wrapping key change needs to reprompt.
	 * Loading the key is the only case were we don't reprompt.
	 */
	if (cmd != ZFS_CRYPTO_KEY_LOAD) {
		(void) snprintf(prompt, MAXPROMPTLEN,
		    dgettext(TEXT_DOMAIN, "Enter again: "));

		tmpbuf = getpassphrase(prompt);
		if (tmpbuf == NULL ||
		    strcmp(*passphrase, tmpbuf) != 0) {
			/* clean up */
			free(*passphrase);
			*passphrase = NULL;
			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
			    "They don't match.\n"));
			return (EAGAIN);
		}
	}

	*passphraselen = strlen(*passphrase);
	return (0);
}
Esempio n. 20
0
string g_GetPasswordFromConsole(const string& prompt)
{
    string      password;
    CMutex      lock;
    CMutexGuard guard(lock);

#if defined(NCBI_OS_UNIX)
    // UNIX implementation

#if defined(HAVE_READPASSPHRASE)

    char password_buffer[1024];
    char* raw_password = readpassphrase(prompt.c_str(), password_buffer,
                                        sizeof(password_buffer),
                                        RPP_ECHO_OFF | RPP_REQUIRE_TTY);

#elif defined(HAVE_GETPASSPHRASE)

    char* raw_password = getpassphrase(prompt.c_str());

#elif defined(HAVE_GETPASS)

    char* raw_password = getpass(prompt.c_str());

#else
#  error "Unsupported Unix platform; the getpass, getpassphrase, and readpassphrase functions are all absent"
#endif

    if (!raw_password)
        NCBI_THROW
            (CGetPasswordFromConsoleException, eGetPassError,
             "g_GetPasswordFromConsole(): error getting password");
    password = string(raw_password);

#elif defined(NCBI_OS_MSWIN)
    // Windows implementation

    for (size_t index = 0;  index < prompt.size();  ++index) {
        _putch(prompt[index]);
    }

    for (;;) {
        char ch;
        ch = _getch();
        if (ch == '\r'  ||  ch == '\n')
            break;
        if (ch == '\003')
            NCBI_THROW(CGetPasswordFromConsoleException, eKeyboardInterrupt,
                       "g_GetPasswordFromConsole(): keyboard interrupt");
        if (ch == '\b') {
            if ( !password.empty() ) {
                password.resize(password.size() - 1);
            }
        }
        else
            password.append(1, ch);
    }

    _putch('\r');
    _putch('\n');
#endif

    return password;
}
Esempio n. 21
0
// Get a password from the user
void getPW(char *pin, char *newPIN, CK_ULONG userType)
{
	// Keep a copy of the PIN because getpass/getpassphrase 
	// will overwrite the previous PIN.
	char password[MAX_PIN_LEN+1];

	int length = 0;

	if (pin)
	{
		length = strlen(pin);
	}

	while (length < MIN_PIN_LEN || length > MAX_PIN_LEN)
	{
		if (userType == CKU_SO)
		{
			printf("*** SO PIN (%i-%i characters) ***\n",
				MIN_PIN_LEN, MAX_PIN_LEN); 
		}
		else
		{
			printf("*** User PIN (%i-%i characters) ***\n",
				MIN_PIN_LEN, MAX_PIN_LEN); 
		}

#ifdef HAVE_GETPASSPHRASE
		if (userType == CKU_SO)
		{
			pin = getpassphrase("Please enter SO PIN: ");
		}
		else
		{
			pin = getpassphrase("Please enter user PIN: ");
		}
#else
		if (userType == CKU_SO)
		{
			pin = getpass("Please enter SO PIN: ");
		}
		else
		{
			pin = getpass("Please enter user PIN: ");
		}
#endif

		length = strlen(pin);
		if (length < MIN_PIN_LEN || length > MAX_PIN_LEN)
		{
			fprintf(stderr, "ERROR: The length of the PIN is out of range.\n");
			length = 0;
			continue;
		}
		strcpy(password, pin);

#ifdef HAVE_GETPASSPHRASE
		if (userType == CKU_SO)
		{
			pin = getpassphrase("Please reenter SO PIN: ");
		}
		else
		{
			pin = getpassphrase("Please reenter user PIN: ");
		}
#else
		if (userType == CKU_SO)
		{
			pin = getpass("Please reenter SO PIN: ");
		}
		else
		{
			pin = getpass("Please reenter user PIN: ");
		}
#endif

		if (strcmp(password, pin))
		{
			fprintf(stderr, "ERROR: The entered PINs are not equal.\n");
			length = 0;
			continue;
		}
	}

	strcpy(newPIN, pin);
}
Esempio n. 22
0
int
main(int argc, char *argv[]) {
	isc_result_t result;
	CK_RV rv;
	CK_SLOT_ID slot = 0;
	CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE;
	CK_OBJECT_HANDLE *hKey;
	CK_OBJECT_CLASS kClass = CKO_PUBLIC_KEY;
	CK_KEY_TYPE kType = CKK_RSA;
	CK_ATTRIBUTE kTemplate[] =
	{
		{ CKA_CLASS, &kClass, (CK_ULONG) sizeof(kClass) },
		{ CKA_KEY_TYPE, &kType, (CK_ULONG) sizeof(kType) },
		{ CKA_TOKEN, &falsevalue, (CK_ULONG) sizeof(falsevalue) },
		{ CKA_PRIVATE, &falsevalue, (CK_ULONG) sizeof(falsevalue) },
		{ CKA_LABEL, (CK_BYTE_PTR) label, (CK_ULONG) sizeof(label) },
		{ CKA_VERIFY, &truevalue, (CK_ULONG) sizeof(truevalue) },
		{ CKA_MODULUS, modulus, (CK_ULONG) sizeof(modulus) },
		{ CKA_PUBLIC_EXPONENT, exponent, (CK_ULONG) sizeof(exponent) }
	};
	pk11_context_t pctx;
	char *lib_name = NULL;
	char *pin = NULL;
	int error = 0;
	int c, errflg = 0;
	int ontoken  = 0;
	unsigned int count = 1000;
	unsigned int i;
	struct timespec starttime;
	struct timespec endtime;

	while ((c = isc_commandline_parse(argc, argv, ":m:s:p:tn:")) != -1) {
		switch (c) {
		case 'm':
			lib_name = isc_commandline_argument;
			break;
		case 's':
			slot = atoi(isc_commandline_argument);
			break;
		case 'p':
			pin = isc_commandline_argument;
			break;
		case 't':
			ontoken = 1;
			break;
		case 'n':
			count = atoi(isc_commandline_argument);
			break;
		case ':':
			fprintf(stderr,
				"Option -%c requires an operand\n",
				isc_commandline_option);
			errflg++;
			break;
		case '?':
		default:
			fprintf(stderr, "Unrecognised option: -%c\n",
				isc_commandline_option);
			errflg++;
		}
	}

	if (errflg) {
		fprintf(stderr, "Usage:\n");
		fprintf(stderr,
			"\tpubrsa [-m module] [-s slot] [-p pin] "
			"[-t] [-n count]\n");
		exit(1);
	}

	/* Allocate hanles */
	hKey = (CK_SESSION_HANDLE *)
		malloc(count * sizeof(CK_SESSION_HANDLE));
	if (hKey == NULL) {
		perror("malloc");
		exit(1);
	}
	for (i = 0; i < count; i++)
		hKey[i] = CK_INVALID_HANDLE;

	/* Initialize the CRYPTOKI library */
	if (lib_name != NULL)
		pk11_set_lib_name(lib_name);

	if (pin == NULL)
		pin = getpassphrase("Enter Pin: ");

	result = pk11_get_session(&pctx, OP_ANY, ISC_TRUE, ISC_TRUE,
				  (const char *) pin, slot);
	if (result != ISC_R_SUCCESS) {
		fprintf(stderr, "Error initializing PKCS#11: %s\n",
			isc_result_totext(result));
		free(hKey);
		exit(1);
	}

	if (pin != NULL)
		memset(pin, 0, strlen((char *)pin));

	hSession = pctx.session;

	if (ontoken)
		kTemplate[2].pValue = &truevalue;

	if (clock_gettime(CLOCK_REALTIME, &starttime) < 0) {
		perror("clock_gettime(start)");
		goto exit_objects;
	}

	for (i = 0; i < count; i++) {
		(void) snprintf(label, sizeof(label), "obj%u", i);
		kTemplate[4].ulValueLen = strlen(label);
		rv = pkcs_C_CreateObject(hSession, kTemplate, 8, &hKey[i]);
		if (rv != CKR_OK) {
			fprintf(stderr,
				"C_CreateObject[%u]: Error = 0x%.8lX\n",
				i, rv);
			error = 1;
			if (i == 0)
				goto exit_objects;
			break;
		}
	}

	if (clock_gettime(CLOCK_REALTIME, &endtime) < 0) {
		perror("clock_gettime(end)");
		goto exit_objects;
	}

	endtime.tv_sec -= starttime.tv_sec;
	endtime.tv_nsec -= starttime.tv_nsec;
	while (endtime.tv_nsec < 0) {
		endtime.tv_sec -= 1;
		endtime.tv_nsec += 1000000000;
	}
	printf("%u public RSA keys in %ld.%09lds\n", i,
	       endtime.tv_sec, endtime.tv_nsec);
	if (i > 0)
		printf("%g public RSA keys/s\n",
		       1024 * i / ((double) endtime.tv_sec +
				   (double) endtime.tv_nsec / 1000000000.));

    exit_objects:
	for (i = 0; i < count; i++) {
		/* Destroy objects */
		if (hKey[i] == CK_INVALID_HANDLE)
			continue;
		rv = pkcs_C_DestroyObject(hSession, hKey[i]);
		if ((rv != CKR_OK) && !errflg) {
			fprintf(stderr,
				"C_DestroyObject[%u]: Error = 0x%.8lX\n",
				i, rv);
			errflg = 1;
		}
	}

	free(hKey);

	pk11_return_session(&pctx);
	pk11_shutdown();

	exit(error);
}
Esempio n. 23
0
int
main(int argc, char **argv)
{
    char		*entrydn = NULL, *rdn = NULL, buf[ 4096 ];
    FILE		*fp;
    LDAP		*ld;
    int		rc, retval, havedn;

    prog = lutil_progname( "ldapmodrdn", argc, argv );

    tool_args( argc, argv );

    havedn = 0;
    if (argc - optind == 2) {
        if (( rdn = strdup( argv[argc - 1] )) == NULL ) {
            perror( "strdup" );
            return( EXIT_FAILURE );
        }
        if (( entrydn = strdup( argv[argc - 2] )) == NULL ) {
            perror( "strdup" );
            return( EXIT_FAILURE );
        }
        ++havedn;
    } else if ( argc - optind != 0 ) {
        fprintf( stderr, "%s: invalid number of arguments (%d), "
                 "only two allowed\n", prog, argc-optind );
        usage();
    }

    if ( infile != NULL ) {
        if (( fp = fopen( infile, "r" )) == NULL ) {
            perror( infile );
            return( EXIT_FAILURE );
        }
    } else {
        fp = stdin;
    }

    ld = tool_conn_setup( 0, 0 );

    if ( pw_file || want_bindpw ) {
        if ( pw_file ) {
            rc = lutil_get_filed_password( pw_file, &passwd );
            if( rc ) return EXIT_FAILURE;
        } else {
            passwd.bv_val = getpassphrase( "Enter LDAP Password: "******"strdup" );
                        return( EXIT_FAILURE );
                    }
                    rc = domodrdn(ld, entrydn, rdn, newSuperior, remove_old_RDN );
                    if ( rc != 0 )
                        retval = rc;
                    havedn = 0;
                } else if ( !havedn ) {	/* don't have DN yet */
                    if (( entrydn = strdup( buf )) == NULL ) {
                        perror( "strdup" );
                        return( EXIT_FAILURE );
                    }
                    ++havedn;
                }
            }
        }

    ldap_unbind( ld );

    return( retval );
}
Esempio n. 24
0
int
main( int argc, char *argv[] )
{
	int rc;
	char	*user = NULL;

	LDAP	       *ld = NULL;
	struct berval bv = {0, NULL};
	BerElement  *ber = NULL;

	int id, code = LDAP_OTHER;
	LDAPMessage *res;
	char *matcheddn = NULL, *text = NULL, **refs = NULL;
	char	*retoid = NULL;
	struct berval *retdata = NULL;
	LDAPControl **ctrls = NULL;

    tool_init( TOOL_PASSWD );
	prog = lutil_progname( "ldappasswd", argc, argv );

	/* LDAPv3 only */
	protocol = LDAP_VERSION3;

	tool_args( argc, argv );

	if( argc - optind > 1 ) {
		usage();
	} else if ( argc - optind == 1 ) {
		user = strdup( argv[optind] );
	} else {
		user = NULL;
	}

	if( oldpwfile ) {
		rc = lutil_get_filed_password( oldpwfile, &oldpw );
		if( rc ) {
			rc = EXIT_FAILURE;
			goto done;
		}
	}

	if( want_oldpw && oldpw.bv_val == NULL ) {
		/* prompt for old password */
		char *ckoldpw;
		oldpw.bv_val = strdup(getpassphrase(_("Old password: "******"Re-enter old password: "******"passwords do not match\n") );
			rc = EXIT_FAILURE;
			goto done;
		}

		oldpw.bv_len = strlen( oldpw.bv_val );
	}

	if( newpwfile ) {
		rc = lutil_get_filed_password( newpwfile, &newpw );
		if( rc ) {
			rc = EXIT_FAILURE;
			goto done;
		}
	}

	if( want_newpw && newpw.bv_val == NULL ) {
		/* prompt for new password */
		char *cknewpw;
		newpw.bv_val = strdup(getpassphrase(_("New password: "******"Re-enter new password: "******"passwords do not match\n") );
			rc = EXIT_FAILURE;
			goto done;
		}

		newpw.bv_len = strlen( newpw.bv_val );
	}

	ld = tool_conn_setup( 0, 0 );

	tool_bind( ld );

	if( user != NULL || oldpw.bv_val != NULL || newpw.bv_val != NULL ) {
		/* build the password modify request data */
		ber = ber_alloc_t( LBER_USE_DER );

		if( ber == NULL ) {
			perror( "ber_alloc_t" );
			rc = EXIT_FAILURE;
			goto done;
		}

		ber_printf( ber, "{" /*}*/ );

		if( user != NULL ) {
			ber_printf( ber, "ts",
				LDAP_TAG_EXOP_MODIFY_PASSWD_ID, user );
			free(user);
		}

		if( oldpw.bv_val != NULL ) {
			ber_printf( ber, "tO",
				LDAP_TAG_EXOP_MODIFY_PASSWD_OLD, &oldpw );
			free(oldpw.bv_val);
		}

		if( newpw.bv_val != NULL ) {
			ber_printf( ber, "tO",
				LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, &newpw );
			free(newpw.bv_val);
		}

		ber_printf( ber, /*{*/ "N}" );

		rc = ber_flatten2( ber, &bv, 0 );

		if( rc < 0 ) {
			perror( "ber_flatten2" );
			rc = EXIT_FAILURE;
			goto done;
		}
	}

	if ( dont ) {
		rc = LDAP_SUCCESS;
		goto done;
	}

	tool_server_controls( ld, NULL, 0);

	rc = ldap_extended_operation( ld,
		LDAP_EXOP_MODIFY_PASSWD, bv.bv_val ? &bv : NULL, 
		NULL, NULL, &id );

	ber_free( ber, 1 );

	if( rc != LDAP_SUCCESS ) {
		tool_perror( "ldap_extended_operation", rc, NULL, NULL, NULL, NULL );
		rc = EXIT_FAILURE;
		goto done;
	}

	for ( ; ; ) {
		struct timeval	tv;

		if ( tool_check_abandon( ld, id ) ) {
			tool_exit( ld, LDAP_CANCELLED );
		}

		tv.tv_sec = 0;
		tv.tv_usec = 100000;

		rc = ldap_result( ld, LDAP_RES_ANY, LDAP_MSG_ALL, &tv, &res );
		if ( rc < 0 ) {
			tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
			tool_exit( ld, rc );
		}

		if ( rc != 0 ) {
			break;
		}
	}

	rc = ldap_parse_result( ld, res,
		&code, &matcheddn, &text, &refs, &ctrls, 0 );
	if( rc != LDAP_SUCCESS ) {
		tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
		rc = EXIT_FAILURE;
		goto done;
	}

	rc = ldap_parse_extended_result( ld, res, &retoid, &retdata, 1 );
	if( rc != LDAP_SUCCESS ) {
		tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
		rc = EXIT_FAILURE;
		goto done;
	}

	if( retdata != NULL ) {
		ber_tag_t tag;
		char *s;
		ber = ber_init( retdata );

		if( ber == NULL ) {
			perror( "ber_init" );
			rc = EXIT_FAILURE;
			goto done;
		}

		/* we should check the tag */
		tag = ber_scanf( ber, "{a}", &s);

		if( tag == LBER_ERROR ) {
			perror( "ber_scanf" );
		} else {
			printf(_("New password: %s\n"), s);
			ber_memfree( s );
		}

		ber_free( ber, 1 );

	} else if ( code == LDAP_SUCCESS && newpw.bv_val == NULL ) {
		tool_perror( "ldap_parse_extended_result", LDAP_DECODING_ERROR,
			" new password expected", NULL, NULL, NULL );
	}

	if( verbose || code != LDAP_SUCCESS ||
		( matcheddn && *matcheddn ) || ( text && *text ) || refs || ctrls )
	{
		printf( _("Result: %s (%d)\n"), ldap_err2string( code ), code );

		if( text && *text ) {
			printf( _("Additional info: %s\n"), text );
		}

		if( matcheddn && *matcheddn ) {
			printf( _("Matched DN: %s\n"), matcheddn );
		}

		if( refs ) {
			int i;
			for( i=0; refs[i]; i++ ) {
				printf(_("Referral: %s\n"), refs[i] );
			}
		}

		if( ctrls ) {
			tool_print_ctrls( ld, ctrls );
			ldap_controls_free( ctrls );
		}
	}

	ber_memfree( text );
	ber_memfree( matcheddn );
	ber_memvfree( (void **) refs );
	ber_memfree( retoid );
	ber_bvfree( retdata );

	rc = ( code == LDAP_SUCCESS ) ? EXIT_SUCCESS : EXIT_FAILURE;

done:
	/* disconnect from server */
	tool_exit( ld, rc ); 
}
Esempio n. 25
0
int
slappasswd( int argc, char *argv[] )
{
	int rc = EXIT_SUCCESS;
#ifdef LUTIL_SHA1_BYTES
	char	*default_scheme = "{SSHA}";
#else
	char	*default_scheme = "{SMD5}";
#endif
	char	*scheme = default_scheme;

	char	*newpw = NULL;
	char	*pwfile = NULL;
	const char *text;
	const char *progname = "slappasswd";

	int		i;
	char		*newline = "\n";
	struct berval passwd = BER_BVNULL;
	struct berval hash;

#ifdef LDAP_DEBUG
	/* tools default to "none", so that at least LDAP_DEBUG_ANY
	 * messages show up; use -d 0 to reset */
	slap_debug = LDAP_DEBUG_NONE;
#endif
	ldap_syslog = 0;

	while( (i = getopt( argc, argv,
		"c:d:gh:no:s:T:vu" )) != EOF )
	{
		switch (i) {
		case 'c':	/* crypt salt format */
			scheme = "{CRYPT}";
			lutil_salt_format( optarg );
			break;

		case 'g':	/* new password (generate) */
			if ( pwfile != NULL ) {
				fprintf( stderr, "Option -g incompatible with -T\n" );
				return EXIT_FAILURE;

			} else if ( newpw != NULL ) {
				fprintf( stderr, "New password already provided\n" );
				return EXIT_FAILURE;

			} else if ( lutil_passwd_generate( &passwd, 8 )) {
				fprintf( stderr, "Password generation failed\n" );
				return EXIT_FAILURE;
			}
			break;

		case 'h':	/* scheme */
			if ( scheme != default_scheme ) {
				fprintf( stderr, "Scheme already provided\n" );
				return EXIT_FAILURE;

			} else {
				scheme = ch_strdup( optarg );
			}
			break;

		case 'n':
			newline = "";
			break;

		case 'o':
			if ( parse_slappasswdopt() ) {
				usage ( progname );
			}
			break;

		case 's':	/* new password (secret) */
			if ( pwfile != NULL ) {
				fprintf( stderr, "Option -s incompatible with -T\n" );
				return EXIT_FAILURE;

			} else if ( newpw != NULL ) {
				fprintf( stderr, "New password already provided\n" );
				return EXIT_FAILURE;

			} else {
				char* p;
				newpw = ch_strdup( optarg );

				for( p = optarg; *p != '\0'; p++ ) {
					*p = '\0';
				}
			}
			break;

		case 'T':	/* password file */
			if ( pwfile != NULL ) {
				fprintf( stderr, "Password file already provided\n" );
				return EXIT_FAILURE;

			} else if ( newpw != NULL ) {
				fprintf( stderr, "Option -T incompatible with -s/-g\n" );
				return EXIT_FAILURE;

			}
			pwfile = optarg;
			break;

		case 'u':	/* RFC2307 userPassword */
			break;

		case 'v':	/* verbose */
			verbose++;
			break;

		default:
			usage ( progname );
		}
	}

	if( argc - optind != 0 ) {
		usage( progname );
	}

#ifdef SLAPD_MODULES
	if ( module_init() != 0 ) {
		fprintf( stderr, "%s: module_init failed\n", progname );
		return EXIT_FAILURE;
	}

	if ( modulepath && module_path(modulepath) ) {
		rc = EXIT_FAILURE;
		goto destroy;
	}

	if ( moduleload && module_load(moduleload, 0, NULL) ) {
		rc = EXIT_FAILURE;
		goto destroy;
	}
#endif

	if( pwfile != NULL ) {
		if( lutil_get_filed_password( pwfile, &passwd )) {
			rc = EXIT_FAILURE;
			goto destroy;
		}
	} else if ( BER_BVISEMPTY( &passwd )) {
		if( newpw == NULL ) {
			/* prompt for new password */
			char *cknewpw;
			newpw = ch_strdup(getpassphrase("New password: "******"Re-enter new password: "******"Password values do not match\n" );
				rc = EXIT_FAILURE;
				goto destroy;
			}
		}

		passwd.bv_val = newpw;
		passwd.bv_len = strlen(passwd.bv_val);
	} else {
		hash = passwd;
		goto print_pw;
	}

	lutil_passwd_hash( &passwd, scheme, &hash, &text );
	if( hash.bv_val == NULL ) {
		fprintf( stderr,
			"Password generation failed for scheme %s: %s\n",
			scheme, text ? text : "" );
		rc = EXIT_FAILURE;
		goto destroy;
	}

	if( lutil_passwd( &hash, &passwd, NULL, &text ) ) {
		fprintf( stderr, "Password verification failed. %s\n",
			text ? text : "" );
		rc = EXIT_FAILURE;
		goto destroy;
	}

print_pw:;
	printf( "%s%s" , hash.bv_val, newline );

destroy:;
#ifdef SLAPD_MODULES
	module_kill();
#endif

	return rc;
}
Esempio n. 26
0
int
main( int argc, char *argv[] )
{
	int rc;
	char	*user = NULL;

	LDAP	       *ld = NULL;
	struct berval bv = {0, NULL};
	BerElement  *ber = NULL;

	int id, code = LDAP_OTHER;
	LDAPMessage *res;
	char *matcheddn = NULL, *text = NULL, **refs = NULL;
	char	*retoid = NULL;
	struct berval *retdata = NULL;

	prog = lutil_progname( "ldappasswd", argc, argv );

	/* LDAPv3 only */
	protocol = LDAP_VERSION3;

	tool_args( argc, argv );

	if( argc - optind > 1 ) {
		usage();
	} else if ( argc - optind == 1 ) {
		user = strdup( argv[optind] );
	} else {
		user = NULL;
	}

	if( oldpwfile ) {
		rc = lutil_get_filed_password( prog, &oldpw );
		if( rc ) return EXIT_FAILURE;
	}

	if( want_oldpw && oldpw.bv_val == NULL ) {
		/* prompt for old password */
		char *ckoldpw;
		oldpw.bv_val = strdup(getpassphrase("Old password: "******"Re-enter old password: "******"passwords do not match\n" );
			return EXIT_FAILURE;
		}

		oldpw.bv_len = strlen( oldpw.bv_val );
	}

	if( newpwfile ) {
		rc = lutil_get_filed_password( prog, &newpw );
		if( rc ) return EXIT_FAILURE;
	}

	if( want_newpw && newpw.bv_val == NULL ) {
		/* prompt for new password */
		char *cknewpw;
		newpw.bv_val = strdup(getpassphrase("New password: "******"Re-enter new password: "******"passwords do not match\n" );
			return EXIT_FAILURE;
		}

		newpw.bv_len = strlen( newpw.bv_val );
	}

	if( want_bindpw && passwd.bv_val == NULL ) {
		/* handle bind password */
		if ( pw_file ) {
			rc = lutil_get_filed_password( pw_file, &passwd );
			if( rc ) return EXIT_FAILURE;
		} else {
			passwd.bv_val = getpassphrase( "Enter LDAP Password: "******"ber_alloc_t" );
			ldap_unbind( ld );
			return EXIT_FAILURE;
		}

		ber_printf( ber, "{" /*}*/ );

		if( user != NULL ) {
			ber_printf( ber, "ts",
				LDAP_TAG_EXOP_MODIFY_PASSWD_ID, user );
			free(user);
		}

		if( oldpw.bv_val != NULL ) {
			ber_printf( ber, "tO",
				LDAP_TAG_EXOP_MODIFY_PASSWD_OLD, &oldpw );
			free(oldpw.bv_val);
		}

		if( newpw.bv_val != NULL ) {
			ber_printf( ber, "tO",
				LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, &newpw );
			free(newpw.bv_val);
		}

		ber_printf( ber, /*{*/ "N}" );

		rc = ber_flatten2( ber, &bv, 0 );

		if( rc < 0 ) {
			perror( "ber_flatten2" );
			ldap_unbind( ld );
			return EXIT_FAILURE;
		}
	}

	if ( not ) {
		rc = LDAP_SUCCESS;
		goto skip;
	}

	rc = ldap_extended_operation( ld,
		LDAP_EXOP_MODIFY_PASSWD, bv.bv_val ? &bv : NULL, 
		NULL, NULL, &id );

	ber_free( ber, 1 );

	if( rc != LDAP_SUCCESS ) {
		ldap_perror( ld, "ldap_extended_operation" );
		ldap_unbind( ld );
		return EXIT_FAILURE;
	}

	rc = ldap_result( ld, LDAP_RES_ANY, LDAP_MSG_ALL, NULL, &res );
	if ( rc < 0 ) {
		ldap_perror( ld, "ldappasswd: ldap_result" );
		return rc;
	}

	rc = ldap_parse_result( ld, res,
		&code, &matcheddn, &text, &refs, NULL, 0 );

	if( rc != LDAP_SUCCESS ) {
		ldap_perror( ld, "ldap_parse_result" );
		return rc;
	}

	rc = ldap_parse_extended_result( ld, res, &retoid, &retdata, 1 );

	if( rc != LDAP_SUCCESS ) {
		ldap_perror( ld, "ldap_parse_result" );
		return rc;
	}

	if( retdata != NULL ) {
		ber_tag_t tag;
		char *s;
		ber = ber_init( retdata );

		if( ber == NULL ) {
			perror( "ber_init" );
			ldap_unbind( ld );
			return EXIT_FAILURE;
		}

		/* we should check the tag */
		tag = ber_scanf( ber, "{a}", &s);

		if( tag == LBER_ERROR ) {
			perror( "ber_scanf" );
		} else {
			printf("New password: %s\n", s);
			free( s );
		}

		ber_free( ber, 1 );
	}

	if( verbose || code != LDAP_SUCCESS || matcheddn || text || refs ) {
		printf( "Result: %s (%d)\n", ldap_err2string( code ), code );

		if( text && *text ) {
			printf( "Additional info: %s\n", text );
		}

		if( matcheddn && *matcheddn ) {
			printf( "Matched DN: %s\n", matcheddn );
		}

		if( refs ) {
			int i;
			for( i=0; refs[i]; i++ ) {
				printf("Referral: %s\n", refs[i] );
			}
		}
	}

	ber_memfree( text );
	ber_memfree( matcheddn );
	ber_memvfree( (void **) refs );
	ber_memfree( retoid );
	ber_bvfree( retdata );

skip:
	/* disconnect from server */
	ldap_unbind (ld);

	return code == LDAP_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
}
Esempio n. 27
0
int
main(int argc, char *argv[]) {
	isc_result_t result;
	CK_RV rv;
	CK_SLOT_ID slot = 0;
	CK_SESSION_HANDLE hSession;
	CK_MECHANISM mech = { CKM_MD5, NULL, 0 };
	CK_ULONG len;
	pk11_context_t pctx;
	pk11_optype_t op_type = OP_DIGEST;
	char *lib_name = NULL;
	char *pin = NULL;
	int error = 0;
	isc_boolean_t logon = ISC_TRUE;
	int c, errflg = 0;
	size_t sum = 0;
	unsigned int i;

	while ((c = isc_commandline_parse(argc, argv, ":m:s:np:")) != -1) {
		switch (c) {
		case 'm':
			lib_name = isc_commandline_argument;
			break;
		case 's':
			slot = atoi(isc_commandline_argument);
			op_type = OP_ANY;
			break;
		case 'n':
			logon = ISC_FALSE;
			break;
		case 'p':
			pin = isc_commandline_argument;
			break;
		case ':':
			fprintf(stderr,
				"Option -%c requires an operand\n",
				isc_commandline_option);
			errflg++;
			break;
		case '?':
		default:
			fprintf(stderr, "Unrecognised option: -%c\n",
				isc_commandline_option);
			errflg++;
		}
	}

	if (errflg) {
		fprintf(stderr, "Usage:\n");
		fprintf(stderr,
			"\tpkcs11-md5sum [-m module] [-s slot] [-n|-p pin]\n");
		exit(1);
	}

	pk11_result_register();

	/* Initialize the CRYPTOKI library */
	if (lib_name != NULL)
		pk11_set_lib_name(lib_name);

	if (logon && pin == NULL)
		pin = getpassphrase("Enter Pin: ");

	result = pk11_get_session(&pctx, op_type, ISC_FALSE, ISC_FALSE, logon,
				  (const char *) pin, slot);
	if ((result != ISC_R_SUCCESS) &&
	    (result != PK11_R_NORANDOMSERVICE) &&
	    (result != PK11_R_NOAESSERVICE)) {
		fprintf(stderr, "Error initializing PKCS#11: %s\n",
			isc_result_totext(result));
		exit(1);
	}

	if (pin != NULL)
		memset(pin, 0, strlen((char *)pin));

	hSession = pctx.session;

	rv = pkcs_C_DigestInit(hSession, &mech);
	if (rv != CKR_OK) {
		fprintf(stderr, "C_DigestInit: Error = 0x%.8lX\n", rv);
		error = 1;
		goto exit_session;
	}

	for (;;) {
		size_t n;

		for (;;) {
			n = fread(buffer + sum, 1, BLOCKSIZE - sum, stdin);
			sum += n;
			if (sum == BLOCKSIZE)
				break;
			if (n == 0) {
				if (ferror(stdin)) {
					fprintf(stderr, "fread failed\n");
					error = 1;
					goto exit_session;
				}
				goto partial_block;
			}
			if (feof(stdin))
				goto partial_block;
		}

		rv = pkcs_C_DigestUpdate(hSession, (CK_BYTE_PTR) buffer,
					 (CK_ULONG) BLOCKSIZE);
		if (rv != CKR_OK) {
			fprintf(stderr,
				"C_DigestUpdate: Error = 0x%.8lX\n",
				rv);
			error = 1;
			goto exit_session;
		}
	}

partial_block:
	if (sum > 0) {
		rv = pkcs_C_DigestUpdate(hSession, (CK_BYTE_PTR) buffer,
					 (CK_ULONG) sum);
		if (rv != CKR_OK) {
			fprintf(stderr,
				"C_DigestUpdate: Error = 0x%.8lX\n",
				rv);
			error = 1;
			goto exit_session;
		}
	}

	len = 16;
	rv = pkcs_C_DigestFinal(hSession, (CK_BYTE_PTR) digest, &len);
	if (rv != CKR_OK) {
		fprintf(stderr, "C_DigestFinal: Error = 0x%.8lX\n", rv);
		error = 1;
		goto exit_session;
	}
	if (len != 16) {
		fprintf(stderr, "C_DigestFinal: bad length = %lu\n", len);
		error = 1;
	}

	for (i = 0; i < 16; i++)
		printf("%02x", digest[i] & 0xff);
	printf("\n");

    exit_session:
	pk11_return_session(&pctx);
	(void) pk11_finalize();

	exit(error);
}
Esempio n. 28
0
int
pk11_get_pin(char *dialog, char **pin)
	{
	/* Initialize as an error. */
	*pin = NULL;

	if (strcmp(dialog, BUILTIN_SPEC) == 0)
		{
		/* The getpassphrase() function is not MT safe. */
		(void) pthread_mutex_lock(uri_lock);
		/* Note that OpenSSL is not localized at all. */
		*pin = getpassphrase("Enter token PIN: ");
		if (*pin == NULL)
			{
			PK11err(PK11_F_GET_PIN, PK11_R_COULD_NOT_READ_PIN);
			(void) pthread_mutex_unlock(uri_lock);
			goto err;
			}
		else
			{
			char *pw;

			/*
			 * getpassphrase() uses an internal  buffer to hold the
			 * entered password. Note that it terminates the buffer
			 * with '\0'.
			 */
			if ((pw = strdup(*pin)) == NULL)
				{
				PK11err(PK11_F_GET_PIN, PK11_R_MALLOC_FAILURE);
				(void) pthread_mutex_unlock(uri_lock);
				goto err;
				}
			/* Zero the internal buffer to get rid of the PIN. */
			memset(*pin, 0, strlen(*pin));
			*pin = pw;
			(void) pthread_mutex_unlock(uri_lock);
			}
		}
	else
		{
		/*
		 * This is the "exec:" case. We will get the PIN from the output
		 * of an external command.
		 */
		if (strncmp(dialog, EXEC_SPEC, strlen(EXEC_SPEC)) == 0)
			{
			dialog += strlen(EXEC_SPEC);
			if ((*pin = run_askpass(dialog)) == NULL)
				goto err;
			}
		else
			{
			/*
			 * Invalid specification in the passphrasedialog
			 * keyword.
			 */
			PK11err(PK11_F_GET_PIN, PK11_R_BAD_PASSPHRASE_SPEC);
			goto err;
			}
		}

	return (1);
err:
	return (0);
	}
Esempio n. 29
0
int
main(int argc, char *argv[]) {
	isc_result_t result;
	CK_RV rv;
	CK_SLOT_ID slot = 0;
	CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE;
	CK_ULONG len;
	CK_ULONG slen;
	CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE;
	CK_OBJECT_CLASS kClass = CKO_PUBLIC_KEY;
	CK_KEY_TYPE kType = CKK_RSA;
	CK_ATTRIBUTE kTemplate[] =
	{
		{ CKA_CLASS, &kClass, (CK_ULONG) sizeof(kClass) },
		{ CKA_KEY_TYPE, &kType, (CK_ULONG) sizeof(kType) },
		{ CKA_TOKEN, &falsevalue, (CK_ULONG) sizeof(falsevalue) },
		{ CKA_PRIVATE, &falsevalue, (CK_ULONG) sizeof(falsevalue) },
		{ CKA_VERIFY, &truevalue, (CK_ULONG) sizeof(truevalue) },
		{ CKA_MODULUS, modulus, (CK_ULONG) sizeof(modulus) },
		{ CKA_PUBLIC_EXPONENT, exponent, (CK_ULONG) sizeof(exponent) }
	};
	CK_MECHANISM mech = { CKM_SHA1_RSA_PKCS, NULL, 0 };
	pk11_context_t pctx;
	pk11_optype_t op_type = OP_RSA;
	char *lib_name = NULL;
	char *pin = NULL;
	int error = 0;
	int c, errflg = 0;
	int ontoken  = 0;
	unsigned int count = 1000;
	unsigned int i;
	struct timespec starttime;
	struct timespec endtime;

	while ((c = isc_commandline_parse(argc, argv, ":m:s:p:tn:")) != -1) {
		switch (c) {
		case 'm':
			lib_name = isc_commandline_argument;
			break;
		case 's':
			slot = atoi(isc_commandline_argument);
			op_type = OP_ANY;
			break;
		case 'p':
			pin = isc_commandline_argument;
			break;
		case 't':
			ontoken = 1;
			break;
		case 'n':
			count = atoi(isc_commandline_argument);
			break;
		case ':':
			fprintf(stderr,
				"Option -%c requires an operand\n",
				isc_commandline_option);
			errflg++;
			break;
		case '?':
		default:
			fprintf(stderr, "Unrecognised option: -%c\n",
				isc_commandline_option);
			errflg++;
		}
	}

	if (errflg) {
		fprintf(stderr, "Usage:\n");
		fprintf(stderr,
			"\tverify [-m module] [-s slot] [-p pin] "
			"[-t] [-n count]\n");
		exit(1);
	}

	pk11_result_register();

	/* Initialize the CRYPTOKI library */
	if (lib_name != NULL)
		pk11_set_lib_name(lib_name);

	if (pin == NULL)
		pin = getpassphrase("Enter Pin: ");

	result = pk11_get_session(&pctx, op_type, ISC_FALSE, ISC_TRUE,
				  ISC_TRUE, (const char *) pin, slot);
	if ((result != ISC_R_SUCCESS) &&
	    (result != PK11_R_NORANDOMSERVICE) &&
	    (result != PK11_R_NODIGESTSERVICE) &&
	    (result != PK11_R_NOAESSERVICE)) {
		fprintf(stderr, "Error initializing PKCS#11: %s\n",
			isc_result_totext(result));
		exit(1);
	}

	if (pin != NULL)
		memset(pin, 0, strlen((char *)pin));

	hSession = pctx.session;

	/* Create the private RSA key */
	if (ontoken)
		kTemplate[2].pValue = &truevalue;

	rv = pkcs_C_CreateObject(hSession, kTemplate, 7, &hKey);
	if (rv != CKR_OK) {
		fprintf(stderr, "C_CreateObject: Error = 0x%.8lX\n", rv);
		error = 1;
		goto exit_key;
	}

	/* Randomize the buffer */
	len = (CK_ULONG) sizeof(buf);
	rv = pkcs_C_GenerateRandom(hSession, buf, len);
	if (rv != CKR_OK) {
		fprintf(stderr, "C_GenerateRandom: Error = 0x%.8lX\n", rv);
		goto exit_key;
	}

	if (clock_gettime(CLOCK_REALTIME, &starttime) < 0) {
		perror("clock_gettime(start)");
		goto exit_key;
	}

	for (i = 0; i < count; i++) {
		/* Initialize Verify */
		rv = pkcs_C_VerifyInit(hSession, &mech, hKey);
		if (rv != CKR_OK) {
			fprintf(stderr,
				"C_VerifyInit[%u]: Error = 0x%.8lX\n",
				i, rv);
			error = 1;
			break;
		}

		/* Perform Verify */
		slen = (CK_ULONG) sizeof(sig);
		rv = pkcs_C_Verify(hSession, buf, len, sig, slen);
		if ((rv != CKR_OK) && (rv != CKR_SIGNATURE_INVALID)) {
			fprintf(stderr,
				"C_Verify[%u]: Error = 0x%.8lX\n",
				i, rv);
			error = 1;
			break;
		}
	}

	if (clock_gettime(CLOCK_REALTIME, &endtime) < 0) {
		perror("clock_gettime(end)");
		goto exit_key;
	}

	endtime.tv_sec -= starttime.tv_sec;
	endtime.tv_nsec -= starttime.tv_nsec;
	while (endtime.tv_nsec < 0) {
		endtime.tv_sec -= 1;
		endtime.tv_nsec += 1000000000;
	}
	printf("%u RSA verify in %ld.%09lds\n", i,
	       endtime.tv_sec, endtime.tv_nsec);
	if (i > 0)
		printf("%g RSA verify/s\n",
		       1024 * i / ((double) endtime.tv_sec +
				   (double) endtime.tv_nsec / 1000000000.));

    exit_key:
	if (hKey != CK_INVALID_HANDLE) {
		rv = pkcs_C_DestroyObject(hSession, hKey);
		if (rv != CKR_OK) {
			fprintf(stderr,
				"C_DestroyObject: Error = 0x%.8lX\n",
				rv);
			errflg = 1;
		}
	}

	pk11_return_session(&pctx);
	(void) pk11_finalize();

	exit(error);
}
Esempio n. 30
0
int
main(int argc, char *argv[]) {
	isc_result_t result;
	CK_RV rv;
	CK_SLOT_ID slot = 0;
	CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE;
	CK_ATTRIBUTE sTemplate[] =
	{
		{ CKA_LABEL, label, (CK_ULONG) sizeof(label) },
	};
	CK_OBJECT_HANDLE sKey = CK_INVALID_HANDLE;
	CK_ULONG found = 0;
	pk11_context_t pctx;
	char *lib_name = NULL;
	char *pin = NULL;
	int error = 0;
	int c, errflg = 0;
	unsigned int count = 1000;
	unsigned int i;
	struct timespec starttime;
	struct timespec endtime;

	while ((c = isc_commandline_parse(argc, argv, ":m:s:p:n:")) != -1) {
		switch (c) {
		case 'm':
			lib_name = isc_commandline_argument;
			break;
		case 's':
			slot = atoi(isc_commandline_argument);
			break;
		case 'p':
			pin = isc_commandline_argument;
			break;
		case 'n':
			count = atoi(isc_commandline_argument);
			break;
		case ':':
			fprintf(stderr,
				"Option -%c requires an operand\n",
				isc_commandline_option);
			errflg++;
			break;
		case '?':
		default:
			fprintf(stderr, "Unrecognised option: -%c\n",
				isc_commandline_option);
			errflg++;
		}
	}

	if (errflg) {
		fprintf(stderr, "Usage:\n");
		fprintf(stderr,
			"\tfind [-m module] [-s slot] [-p pin] [-n count]\n");
		exit(1);
	}

	/* Initialize the CRYPTOKI library */
	if (lib_name != NULL)
		pk11_set_lib_name(lib_name);

	if (pin == NULL)
		pin = getpassphrase("Enter Pin: ");

	result = pk11_get_session(&pctx, OP_ANY, ISC_FALSE, ISC_TRUE,
				  (const char *) pin, slot);
	if (result != ISC_R_SUCCESS) {
		fprintf(stderr, "Error initializing PKCS#11: %s\n",
			isc_result_totext(result));
		exit(1);
	}

	if (pin != NULL)
		memset(pin, 0, strlen((char *)pin));

	hSession = pctx.session;

	if (clock_gettime(CLOCK_REALTIME, &starttime) < 0) {
		perror("clock_gettime(start)");
		goto exit_objects;
	}

	for (i = 0; !error && (i < count); i++) {
		rv = pkcs_C_FindObjectsInit(hSession, sTemplate, 1);
		if (rv != CKR_OK) {
			fprintf(stderr,
				"C_FindObjectsInit[%u]: Error = 0x%.8lX\n",
				i, rv);
			error = 1;
			break;
		}

		rv = pkcs_C_FindObjects(hSession, &sKey, 1, &found);
		if (rv != CKR_OK) {
			fprintf(stderr,
				"C_FindObjects[%u]: Error = 0x%.8lX\n",
				i, rv);
			error = 1;
			/* no break here! */
		}

		rv = pkcs_C_FindObjectsFinal(hSession);
		if (rv != CKR_OK) {
			fprintf(stderr,
				"C_FindObjectsFinal[%u]: Error = 0x%.8lX\n",
				i, rv);
			error = 1;
			break;
		}
	}

	if (clock_gettime(CLOCK_REALTIME, &endtime) < 0) {
		perror("clock_gettime(end)");
		goto exit_objects;
	}

	endtime.tv_sec -= starttime.tv_sec;
	endtime.tv_nsec -= starttime.tv_nsec;
	while (endtime.tv_nsec < 0) {
		endtime.tv_sec -= 1;
		endtime.tv_nsec += 1000000000;
	}
	printf("%u object searches in %ld.%09lds\n", i,
	       endtime.tv_sec, endtime.tv_nsec);
	if (i > 0)
		printf("%g object searches/s\n",
		       1024 * i / ((double) endtime.tv_sec +
				   (double) endtime.tv_nsec / 1000000000.));

    exit_objects:
	pk11_return_session(&pctx);
	pk11_shutdown();

	exit(error);
}