Example #1
0
void pw_unix_check(AuthResult * const result,
                   const char *account, const char *password,
                   const struct sockaddr_storage * const sa,
                   const struct sockaddr_storage * const peer)
{

//RCP - check user and password
	dbgmsg("checking user/password");
	if (result == NULL || password == NULL || strlen(password) == 0)
		return;

	// initialize shared memory
	RcpShm *shm;
	if ((shm = rcpShmemInit(RCP_PROC_CLI)) == NULL) {
		dbgmsg("cannot initialize memory, exiting...\n");
		return;
	}
	RcpAdmin *admin = admin_find(shm, account);
	if (admin == NULL) {
		dbgmsg("failed to find an RCP administrator account, exiting...\n");
		return;
	}

	{ // check password
		char solt[RCP_CRYPT_SALT_LEN + 1];
		int i;
		
		for (i = 0; i < RCP_CRYPT_SALT_LEN; i++)
			solt[i] = admin->password[i];
		solt[RCP_CRYPT_SALT_LEN] = '\0';

		char *cp = rcpCrypt(password, solt);
		if (strcmp(admin->password + RCP_CRYPT_SALT_LEN + 1, cp + RCP_CRYPT_SALT_LEN + 4) != 0)
			return;
	}
	// user/password combination is ok
	// for the login into /home/rcp, with rcp as the real user
	account = "rcp";
//RCP


    const char *cpwd = NULL;
    struct passwd pw, *pw_;
#ifdef USE_SHADOW
    struct spwd *spw;
#endif
    char *dir = NULL;

    (void) sa;
    (void) peer;
    result->auth_ok = 0;
    if ((pw_ = getpwnam(account)) == NULL) {
/*RCP*/dbgmsg("failed getpwnam");    	
        return;
    }
    pw = *pw_;
    result->auth_ok--;
#ifdef HAVE_SETUSERSHELL
    if (pw.pw_shell == NULL) {
/*RCP*/dbgmsg("failed pw_shell");    	
        return;
    }
#if 0 // RCP disabled
    if (strcasecmp(pw.pw_shell, FAKE_SHELL) != 0) {
        const char *shell;
        
        setusershell();
        while ((shell = (char *) getusershell()) != NULL &&
               strcmp(pw.pw_shell, shell) != 0);
        endusershell();
        if (shell == NULL) {
            return;
        }
    }
#endif //RCP      
#endif
    if ((dir = strdup(pw.pw_dir)) == NULL) {
/*RCP*/dbgmsg("failed strdup");    	
        return;
    }
#if 0 //disabeld for RCP
#ifdef USE_SHADOW
    if ((((pw.pw_passwd)[0] == 'x' && (pw.pw_passwd)[1] == 0) ||
         ((pw.pw_passwd)[0] == '#' && (pw.pw_passwd)[1] == '#' &&
          strcmp(pw.pw_passwd + 2, account) == 0)) &&
        (spw = getspnam(account)) != NULL && spw->sp_pwdp != NULL) {
        cpwd = spw->sp_pwdp[0] == '@' ? NULL : spw->sp_pwdp;
        if (spw->sp_expire > 0 || spw->sp_max > 0) {
            long today = time(NULL) / (24L * 60L * 60L);

            if (spw->sp_expire > 0 && spw->sp_expire < today) {
                goto bye;               /* account expired */
            }
            if (spw->sp_max > 0 && spw->sp_lstchg > 0 &&
                (spw->sp_lstchg + spw->sp_max < today)) {
                goto bye;               /* password expired */
            }
        }
    } else
#endif
    {
        cpwd = pw.pw_passwd;
    }
    {
        const char *crypted;
        
        if (cpwd == NULL ||
            (crypted = (const char *) crypt(password, cpwd)) == NULL ||
            strcmp(cpwd, crypted) != 0) {
            goto bye;
        }
    }
#endif //RCP
    result->uid = pw.pw_uid;
    result->gid = pw.pw_gid;
    result->dir = dir;
    result->slow_tilde_expansion = 0;
    result->auth_ok = -result->auth_ok;
/*RCP*/dbgmsg("RCP admin check ok");    	
    return;
    
    bye:
    free(dir);
/*RCP*/dbgmsg("failed RCP admin check");    	
}
Example #2
0
int main(int argc, char *argv[])
{
    int ch, i;
    int password_fd = -1;
    unsigned int salt_minlen = 0;
    unsigned int salt_maxlen = 0;
    unsigned int rounds_support = 0;
    const char *salt_prefix = NULL;
    const char *salt_arg = NULL;
    unsigned int rounds = 0;
    char *salt = NULL;
    char rounds_str[30];
    char *password = NULL;

#ifdef ENABLE_NLS
    setlocale(LC_ALL, "");
    bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
    textdomain(NLS_CAT_NAME);
#endif

    /* prepend options from environment */
    argv = merge_args(getenv("MKPASSWD_OPTIONS"), argv, &argc);

    while ((ch = GETOPT_LONGISH(argc, argv, "hH:m:5P:R:sS:V", longopts, 0))
	    > 0) {
	switch (ch) {
	case '5':
	    optarg = (char *) "md5";
	    /* fall through */
	case 'm':
	case 'H':
	    if (!optarg || strcaseeq("help", optarg)) {
		display_methods();
		exit(0);
	    }
	    for (i = 0; methods[i].method != NULL; i++)
		if (strcaseeq(methods[i].method, optarg)) {
		    salt_prefix = methods[i].prefix;
		    salt_minlen = methods[i].minlen;
		    salt_maxlen = methods[i].maxlen;
		    rounds_support = methods[i].rounds;
		    break;
		}
	    if (!salt_prefix) {
		fprintf(stderr, _("Invalid method '%s'.\n"), optarg);
		exit(1);
	    }
	    break;
	case 'P':
	    {
		char *p;
		password_fd = strtol(optarg, &p, 10);
		if (p == NULL || *p != '\0' || password_fd < 0) {
		    fprintf(stderr, _("Invalid number '%s'.\n"), optarg);
		    exit(1);
		}
	    }
	    break;
	case 'R':
	    {
		char *p;
		rounds = strtol(optarg, &p, 10);
		if (p == NULL || *p != '\0' || rounds < 0) {
		    fprintf(stderr, _("Invalid number '%s'.\n"), optarg);
		    exit(1);
		}
	    }
	    break;
	case 's':
	    password_fd = 0;
	    break;
	case 'S':
	    salt_arg = optarg;
	    break;
	case 'V':
	    display_version();
	    exit(0);
	case 'h':
	    display_help();
	    exit(0);
	default:
	    fprintf(stderr, _("Try '%s --help' for more information.\n"),
		    argv[0]);
	    exit(1);
	}
    }
    argc -= optind;
    argv += optind;

    if (argc == 2 && !salt_arg) {
	password = argv[0];
	salt_arg = argv[1];
    } else if (argc == 1) {
	password = argv[0];
    } else if (argc == 0) {
    } else {
	display_help();
	exit(1);
    }

    /* default: DES password */
    if (!salt_prefix) {
	salt_minlen = methods[0].minlen;
	salt_maxlen = methods[0].maxlen;
	salt_prefix = methods[0].prefix;
    }

    if (streq(salt_prefix, "$2a$") || streq(salt_prefix, "$2y$")) {
	/* OpenBSD Blowfish and derivatives */
	if (rounds <= 5)
	    rounds = 5;
	/* actually for 2a/2y it is the logarithm of the number of rounds */
	snprintf(rounds_str, sizeof(rounds_str), "%02u$", rounds);
    } else if (rounds_support && rounds)
	snprintf(rounds_str, sizeof(rounds_str), "rounds=%u$", rounds);
    else
	rounds_str[0] = '\0';

    if (salt_arg) {
	unsigned int c = strlen(salt_arg);
	if (c < salt_minlen || c > salt_maxlen) {
	    if (salt_minlen == salt_maxlen)
		fprintf(stderr, ngettext(
			"Wrong salt length: %d byte when %d expected.\n",
			"Wrong salt length: %d bytes when %d expected.\n", c),
			c, salt_maxlen);
	    else
		fprintf(stderr, ngettext(
			"Wrong salt length: %d byte when %d <= n <= %d"
			" expected.\n",
			"Wrong salt length: %d bytes when %d <= n <= %d"
			" expected.\n", c),
			c, salt_minlen, salt_maxlen);
	    exit(1);
	}
	while (c-- > 0) {
	    if (strchr(valid_salts, salt_arg[c]) == NULL) {
		fprintf(stderr, _("Illegal salt character '%c'.\n"),
			salt_arg[c]);
		exit(1);
	    }
	}

	salt = NOFAIL(malloc(strlen(salt_prefix) + strlen(rounds_str)
		+ strlen(salt_arg) + 1));
	*salt = '\0';
	strcat(salt, salt_prefix);
	strcat(salt, rounds_str);
	strcat(salt, salt_arg);
    } else {
#ifdef HAVE_SOLARIS_CRYPT_GENSALT
#error "This code path is untested on Solaris. Please send a patch."
	salt = crypt_gensalt(salt_prefix, NULL);
	if (!salt)
		perror(stderr, "crypt_gensalt");
#elif defined HAVE_LINUX_CRYPT_GENSALT
	void *entropy = get_random_bytes(64);

	salt = crypt_gensalt(salt_prefix, rounds, entropy, 64);
	if (!salt) {
		fprintf(stderr, "crypt_gensalt failed.\n");
		exit(2);
	}
	free(entropy);
#else
	unsigned int salt_len = salt_maxlen;

	if (salt_minlen != salt_maxlen) { /* salt length can vary */
	    srand(time(NULL) + getpid());
	    salt_len = rand() % (salt_maxlen - salt_minlen + 1) + salt_minlen;
	}

	salt = NOFAIL(malloc(strlen(salt_prefix) + strlen(rounds_str)
		+ salt_len + 1));
	*salt = '\0';
	strcat(salt, salt_prefix);
	strcat(salt, rounds_str);
	generate_salt(salt + strlen(salt), salt_len);
#endif
    }

    if (password) {
    } else if (password_fd != -1) {
	FILE *fp;
	char *p;

	if (isatty(password_fd))
	    fprintf(stderr, _("Password: "******"r");
	if (!fp) {
	    perror("fdopen");
	    exit(2);
	}
	if (!fgets(password, 128, fp)) {
	    perror("fgets");
	    exit(2);
	}

	p = strpbrk(password, "\n\r");
	if (p)
	    *p = '\0';
    } else {
	password = getpass(_("Password: "******"getpass");
	    exit(2);
	}
    }

    {
	const char *result;
	result = crypt(password, salt);
	/* xcrypt returns "*0" on errors */
	if (!result || result[0] == '*') {
	    fprintf(stderr, "crypt failed.\n");
	    exit(2);
	}
	/* yes, using strlen(salt_prefix) on salt. It's not
	 * documented whether crypt_gensalt may change the prefix */
	if (!strneq(result, salt, strlen(salt_prefix))) {
	    fprintf(stderr, _("Method not supported by crypt(3).\n"));
	    exit(2);
	}
	printf("%s\n", result);
    }

    exit(0);
}
Example #3
0
int daemon_AuthUserPwd(char *username, char *password, char *errbuf)
{
#ifdef WIN32
	/*
		Warning: the user which launches the process must have the SE_TCB_NAME right.
		This corresponds to have the "Act as part of the Operating System" turined on
		(administrative tools, local security settings, local policies, user right assignment)
		However, it seems to me that if you run it as a service, this right should be
		provided by default.
	*/
	HANDLE Token;
	if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
	{
	int error;

		error = GetLastError();
		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, errbuf,
			PCAP_ERRBUF_SIZE, NULL);

		return -1;
	}

	// This call should change the current thread to the selected user.
	// I didn't test it.
	if (ImpersonateLoggedOnUser(Token) == 0)
	{
	int error;

		error = GetLastError();
		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, errbuf,
			PCAP_ERRBUF_SIZE, NULL);

		CloseHandle(Token);
		return -1;
	}

	CloseHandle(Token);
	return 0;

#else
/*	Standard user authentication:
		http://www.unixpapa.com/incnote/passwd.html
	Problem: it is not able to merge the standard pwd file with the shadow one

	Shadow user authentication:
		http://www.tldp.org/HOWTO/Shadow-Password-HOWTO-8.html
	Problem: the program must either (1) run as root, or (2) run as user, but it
	must be owned by root and must be SUID root (chmod u+s rpcapd)
*/

	struct passwd *user;
#ifdef linux
	struct spwd *usersp;
#endif

	// This call is needed to get the uid
	if ((user= getpwnam(username)) == NULL)
	{
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: no such user");
		return -1;
	}

#ifdef linux
	// This call is needed to get the password; otherwise 'x' is returned
	if ((usersp= getspnam(username)) == NULL)
	{
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: no such user");
		return -1;
	}
	
	if (strcmp(usersp->sp_pwdp, (char *) crypt(password, usersp->sp_pwdp) ) != 0)
	{
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: password incorrect");
		return -1;
	}
#endif

#ifdef bsd
	if (strcmp(user->pw_passwd, (char *) crypt(password, user->pw_passwd) ) != 0)
	{
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: password incorrect");
		return -1;
	}
#endif

	if (setuid(user->pw_uid) )
	{
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s", pcap_strerror(errno) );
		return -1;
	}

/*	if (setgid(user->pw_gid) )
	{
		SOCK_ASSERT("setgid failed", 1);
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s", pcap_strerror(errno) );
		return -1;
	}
*/
	return 0;

#endif

}
Example #4
0
void handleClient(int csd){
	printf("\tClient connected via socket %d.\n", csd);
	int n;
	char* buffer = malloc(1024); // buffer for reading
	char* fullRequest = malloc(1024); // final buffer
	char* current = fullRequest; // tracker on where the buffer should copy to
	memset(buffer, '0',sizeof(buffer)); // zero out buffer
	memset(fullRequest, '0', sizeof(fullRequest)); // zero out final buffer
	while((n = read(csd,buffer,sizeof(buffer)-1))>0) // read the request in
	{
		buffer[n] = 0; // set last character to 0
		if(fullRequest + sizeof(fullRequest) < current + n){ // if the request will overflow the buffer make it bigger
			int size = current - fullRequest;
			fullRequest = realloc(fullRequest, current + n - fullRequest);
			current = fullRequest + size;
			
		}
		memcpy(current, buffer, n+1); // dump the buffer into the final buffer
		current+=n; // increment the dump position
		if(!strcmp(buffer, username))
			break;
	}
	printf("\tUser: %s\n", fullRequest);

	int authNum = rand();
	char* num = malloc(33);
	sprintf(num, "%d", authNum);
	write(csd, num, strlen(num) );
	//memset(fullRequest, '0',strlen(fullRequest)); 
	
	char* hash = crypt(password, num);
	read(csd, fullRequest, strlen(hash));
	//printf("My Hash: %s\n", hash);

	//printf("Received Hash: %s\n", fullRequest);

	write(csd, strncmp(hash, fullRequest, strlen(hash)) ? "0" : "1", 2);
	if(strncmp(hash, fullRequest, strlen(hash)))
		return;
	else
		puts("\tPasswords matched, authenticated.");
	current = fullRequest;

	n = read(csd,buffer,1024);
	buffer[n] = 0;
	printf("\tReceived Command: %s\n", buffer);
		int childPID = fork();
	if(childPID == 0){

		char* frd = strdup((const char *)buffer);
		char* argument;
		char* program = strtok(frd, " ");
		int length = 40;
		int numArgs = 1;
		int i;
		char* command = (char*) calloc(length, sizeof(char));
		char** arguments = (char**) calloc(numArgs, sizeof(char*));
		arguments[0] = program;
		for(i = 1; argument = strtok(NULL, " "); i++){
			if(i == numArgs){
				numArgs *= 1.3;
				arguments = realloc(arguments, numArgs * sizeof(char *));
				if(!arguments)
					puts("Error: Could not allocate enough space for arguments");
			}
			arguments[i] = argument;
		}
		//write(csd, "stuff", 5);
		//close(0);
		puts("\tExecuting command...");
		fflush(stdout);
		dup2(csd, 1);
		dup2(csd, 2);
		execvp(program, arguments);
		exit(1);
	}
	int status;
    wait(&status);
    shutdown(csd, SHUT_RDWR);
    if(status == 256)
    	puts("Couldn't find program");

	free(buffer); // free buffer
	free(fullRequest); // free final buffer
}
Example #5
0
int shadow_user_pass_verify(const char *username, const char *password) {
#if defined(COMPILE_WIN32) || defined(NO_SHADOW_H)
	errno = ENOSYS;
	return -1;
#else
	int errsv = 0;
	struct spwd *spentp = NULL;
	size_t salt_len = 0;
	char *salt = NULL, *local_hash = NULL, *user_hash = NULL;
 #ifdef _GNU_SOURCE
	char sp_buf[8192];
	struct spwd spent;
	struct crypt_data cd;
 #endif

	/* Pre-check */
	if (!username || !password) {
		errno = EINVAL;
		return -1;
	}

 #if defined(_GNU_SOURCE)
	/* GNU implementations support native reentrant functions */
	if (getspnam_r(username, &spent, sp_buf, sizeof(sp_buf), &spentp) < 0)
		return -1;
 #else
	pthread_mutex_lock(&_auth_shadow_mutex);

	spentp = getspnam(username);

	errsv = errno;

	pthread_mutex_unlock(&_auth_shadow_mutex);
 #endif

	/* Validate that spentp is valid */
	if (!spentp) {
		errno = errsv;
		return -1;
	}

	/* Search for '$' in the local hash. If found, extensions (non-POSIX) are enabled */
	if (!(local_hash = strrchr(spentp->sp_pwdp, '$'))) {
		/* DES (default) */
		if (strlen(spentp->sp_pwdp) <= 2) {
			errno = ENOSYS;
			return -1;
		}

		salt_len = 2;
	} else {
		/* Extensions */
		local_hash ++;
		salt_len = local_hash - spentp->sp_pwdp;
	}

	/* Allocate memory for salt */
	if (!(salt = malloc(salt_len + 1)))
		return -1;

	/* Isolate salt */
	memcpy(salt, spentp->sp_pwdp, salt_len);
	salt[salt_len] = 0;

 #ifdef _GNU_SOURCE
	/* cd.initialized = 0; */
	tc_memset(&cd, 0, sizeof(struct crypt_data));

	/* Generate password hash */
	if (!(user_hash = crypt_r(password, salt, &cd))) {
		errsv = errno;
		free(salt);
		errno = errsv;
		return -1;
	}

 #else
	pthread_mutex_lock(&_auth_shadow_mutex);

	/* Generate password hash (non-reentrant) */
	if (!(user_hash = crypt(password, salt))) {
		errsv = errno;
		free(salt);
		errno = errsv;
		return -1;
	}

	pthread_mutex_unlock(&_auth_shadow_mutex);
 #endif

	/* Free unused memory */
	free(salt);

	/* Compare hashes */
	if (strcmp(spentp->sp_pwdp, user_hash)) {
		errno = EINVAL;
		return -1;
	}

	return 0;
#endif
}
Example #6
0
/** \brief Überprüfen, ob eine Person in der Datenbank ist und ob das Passwort stimmt
 *
 * \param pers person*  Person, die angemeldet werden soll
 * \return int          1: Benutzer ist schon angemeldet; 0: Benutzer war noch nicht angemeldet (PW richtig); -1: PW falsch
 *  Die Funktion testet, ob der Name oder das Kürzel (je nachdem was eingegeben wurde)
 *  (Erkennung an der Länge des Strings: =3 --> Kürzel, >3 --> Name)
 *  in der DB vorhanden ist. Wenn der Name existiert wird geprüft ob das Passwort richtig ist.
 *  Wenn das Passwort stimmt wird der bool-Wert "auth" in "person" auf true gesetzt.
 *  --> die Person ist authentifiziert.
 */
int verify_user(person * pers){
	bool isAcronym;
	UserState user_state=PW_INCORRECT;

	if(pers->email==NULL || pers->password==NULL){
		print_exit_failure("Programm falsch!");
	}

	isAcronym=detect_convert_acronym(pers);

	MYSQL *my=mysql_init(NULL);
	if(my == NULL){
		print_exit_failure("MYSQL init failure");
	}

	if(mysql_real_connect(my, "localhost", SQL_USER, SQL_PASS, SQL_BASE, 0, NULL, 0) == NULL){

		print_exit_failure("MYSQL-connection error!");
	}else{
		//fprintf(stderr, "Connection extablished!\n");
	}

	MYSQL_RES * result=NULL;
	bool found=false;

	if(isAcronym){
		//Es ist sicher eine Lehrer (jemand hat das Kürzel eingegeben)
		//TODO: sql-injection verhindern

		char * sql_query=NULL;
		if(asprintf(&sql_query, "SELECT  * FROM Benutzer WHERE kuerzel='%s'", pers->acronym) == -1){
			print_exit_failure("Es konnte kein Speicher angefordert werden (verify_user)");
		}
		#ifdef DEBUG
		fprintf(stderr, "Lehrer.\nsql_query: %s\n", sql_query);
		#endif // DEBUG

		if(mysql_query(my, sql_query)){  //Liefert 0 bei Erfolg
			print_exit_failure("mysql_query failed (Lehrer)");
		}

		result = mysql_store_result(my);

		if(mysql_num_rows(result) == 1){
			found=true;
			isAcronym=true; //Da wir jetzt eine Person mit Kürzel gefunden haben
			pers->isTeacher=true;
		}
		free(sql_query);
    }else{
		//Es könnte ein Lehrer oder ein Schüler sein

		char * sql_query=NULL;
		if(asprintf(&sql_query, "SELECT * FROM Benutzer WHERE email='%s'", pers->email) == -1){
			print_exit_failure("Es konnte kein Speicher angefordert werden (verify_user)");
		}
		#ifdef DEBUG
		fprintf(stderr, "Schueler o. Lehrer.\nsql_query: %s\n", sql_query);
		#endif // DEBUG

		if(mysql_query(my, sql_query)){  // Liefert 0 bei Erfolg
			print_exit_failure("mysql_query failed (Schueler - Lehrer)");
		}

		result = mysql_store_result(my);

		if(mysql_num_rows(result) == 1){
			found=true;
			isAcronym=false; //Da wir jetzt eine Person mit Kürzel gefunden haben
		}else{
			//Person nicht vorhanden, oder Fehler
			//print_exit_failure("mysql: Person nicht vorhanden, oder Passwort falsch."); //Was auch immer
			found=false;
			isAcronym=false;
		}
		free(sql_query);
    }

	//Ab hier wurde die SQL-Query für Lehrer oder Schüler ausgeführt.
	if(found == true){
		MYSQL_ROW row;
		row=mysql_fetch_row(result);
		#ifdef DEBUG
		fprintf(stderr, "\nEin Ergebnis!\n Name: %s, Pass: %s, SID: '%s'\n", row[COL_NAME], row[COL_PASS], row[COL_SID]);
		#endif // DEBUG

		//Auslesen des Salt
		char * salt=calloc(SALT_LENGTH+1, sizeof(char));
		//strncat(salt, row[COL_PASS], 1);
		//strncat(salt, row[COL_PASS]+1, 1);
		for(int i=0; i<SALT_LENGTH; i++){
			strncat(salt, row[COL_PASS]+i, 1);
		}
		char * arg=NULL;
		asprintf(&arg, "$6$%s$", salt);
		char * encr=crypt(pers->password, arg);
		free(pers->password);
		char * load_pw=NULL;
		asprintf(&load_pw, "%s%s", salt, encr+strlen(arg));
		//pers->password=encr+strlen(arg);

		if(strcmp(load_pw, row[COL_PASS]) == 0){
			pers->auth=true;

			//Name holen
			//pers->name=calloc(strlen(row[COL_NAME])+1, sizeof(char));
			//strcpy(pers->name, row[COL_NAME]);
			asprintf(&pers->name, "%s", row[COL_NAME]);
			//pers->first_name=calloc(strlen(row[COL_VORNAME])+1, sizeof(char));
			//strcpy(pers->first_name, row[COL_VORNAME]);
			asprintf(&pers->first_name, "%s", row[COL_VORNAME]);

			if(isAcronym){
				//Person hat Kürzel angegeben --> es ist eine Leherer --> email holen holen
				pers->email=calloc(strlen(row[COL_EMAIL])+1, sizeof(char));
				strcpy(pers->email, row[COL_EMAIL]);
			}else{
				//Person hat ihre Email-Adresse statt dem Kürzel angegeben --> (Falls es ein Lehrer ist, dessen Kürzel holen)
				pers->acronym=NULL;
				if(row[COL_ACR] != NULL){
					//Die Person hat ein Küzel --> Lehrer
					pers->acronym=calloc(strlen(row[COL_ACR])+1, sizeof(char));
					strcpy(pers->acronym, row[COL_ACR]);
					pers->isTeacher=true;
				}else{
					pers->isTeacher=false;
				}
			}

			//Kurse (falls vorhanden)
			if(row[COL_COURSE] != NULL){
				pers->courses=calloc(strlen(row[COL_COURSE])+1, sizeof(char));
				strcpy(pers->courses, row[COL_COURSE]);
			}

			//ID holen
			if(row[COL_ID] != NULL){
				pers->id=atoi(row[COL_ID]);
			}

			if(row[COL_SID] != NULL){
				//Benutzer ist schon angemeldet
				user_state=PW_CORRECT_ALREADY_LOGGED_IN;
				pers->auth=true;
				pers->sid=atoi(row[COL_SID]);
			}else{
				user_state=PW_CORRECT;
				create_session(pers);
			}
		}else{
			user_state=PW_INCORRECT;
			pers->auth=false;
			pers->sid=0;
		}
	}

	mysql_free_result(result);
	mysql_close(my);

	return user_state;
}
Example #7
0
int
main(int argc, char *argv[])
{
  const char *plaintext = NULL;
  int c;
  char *saltpara = NULL;
  char *salt;
  int flag = 0;
  int length = 0; /* Not Set */
  int rounds = 0; /* Not set, since extended DES needs 25 and blowfish needs
                  ** 4 by default, a side effect of this being the encryption
                  ** type parameter must be specified before the rounds
                  ** parameter.
                  */

  while ((c = getopt(argc, argv, "56mdber:h?l:s:p:R:")) != -1)
  {
    switch (c)
    {
      case '5':
        flag |= FLAG_SHA256;
        break;
      case '6':
        flag |= FLAG_SHA512;
        break;
      case 'm':
        flag |= FLAG_MD5;
        break;
      case 'd':
        flag |= FLAG_DES;
        break;
      case 'b':
        flag |= FLAG_BLOWFISH;
        rounds = 4;
        break;
      case 'e':
        flag |= FLAG_EXT;
        rounds = 25;
        break;
      case 'l':
        flag |= FLAG_LENGTH;
        length = atoi(optarg);
        break;
      case 'r':
        flag |= FLAG_ROUNDS;
        rounds = atoi(optarg);
        break;
      case 's':
        flag |= FLAG_SALT;
        saltpara = optarg;
        break;
      case 'p':
        flag |= FLAG_PASS;
        plaintext = optarg;
        break;
      case 'R':
        flag |= FLAG_RAW;
        saltpara = optarg;
        break;
      case 'h':
        full_usage();
        /* NOT REACHED */
        break;
      case '?':
        brief_usage();
        /* NOT REACHED */
        break;
      default:
        printf("Invalid Option: -%c\n", c);
        break;
    }
  }

  if (flag & FLAG_MD5)
  {
    if (length == 0)
      length = 8;
    if (flag & FLAG_SALT)
      salt = make_md5_salt_para(saltpara);
    else
      salt = make_md5_salt(length);
  }
  else if (flag & FLAG_SHA256)
  {
    if (length == 0)
      length = 16;
    if (flag & FLAG_SALT)
      salt = make_sha256_salt_para(saltpara);
    else
      salt = make_sha256_salt(length);
  }
  else if (flag & FLAG_SHA512)
  {
    if (length == 0)
      length = 16;
    if (flag & FLAG_SALT)
      salt = make_sha512_salt_para(saltpara);
    else
      salt = make_sha512_salt(length);
  }
  else if (flag & FLAG_BLOWFISH)
  {
    if (length == 0)
      length = 22;
    if (flag & FLAG_SALT)
      salt = make_bf_salt_para(rounds, saltpara);
    else
      salt = make_bf_salt(rounds, length);
  }
  else if (flag & FLAG_EXT)
  {
    /* XXX - rounds needs to be done */
    if (flag & FLAG_SALT)
    {
      if ((strlen(saltpara) == 4))
      {
        salt = make_ext_salt_para(rounds, saltpara);
      }
      else
      {
        printf("Invalid salt, please enter 4 alphanumeric characters\n");
        exit(1);
      }
    }
    else
    {
      salt = make_ext_salt(rounds);
    }
  }
  else if (flag & FLAG_RAW)
  {
    salt = saltpara;
  }
  else /* Default to DES */
  {
    if (flag & FLAG_SALT)
    {
      if ((strlen(saltpara) == 2))
      {
        salt = saltpara;
      }
      else
      {
        printf("Invalid salt, please enter 2 alphanumeric characters\n");
        exit(1);
      }
    }
    else
    {
      salt = make_des_salt();
    }
  }

  if (flag & FLAG_PASS)
  {
    if (!plaintext)
      printf("Please enter a valid password\n");
  }
  else
    plaintext = getpass("plaintext: ");

  printf("%s\n", crypt(plaintext, salt));
  return 0;
}
Example #8
0
readpw(Display *dpy, const char *pws)
#endif
{
	char buf[32], passwd[256];
	int num, screen;
	unsigned int len, llen;
	KeySym ksym;
	XEvent ev;

	XIM im;
	XIMStyles *im_styles;
	XIMStyle im_style = 0;
	char *imvalret;
	XIC ic;
	Status status;


	im = XOpenIM(dpy, NULL, NULL, NULL);
	if (im == NULL)
		die("slock: XOpenIM failed");

	if(im) {
		imvalret = XGetIMValues(im, XNQueryInputStyle, &im_styles, NULL);
		if (imvalret != NULL || im_styles == NULL) {
			die("slock: input method doesn't support any styles");
		}

		if (im_styles) {
			im_style = 0;
			/* for now just pick the first style if it exists */
			if (im_styles->count_styles)
				im_style = im_styles->supported_styles[0];
		}

		if (im_style == 0) {
			die("slock: input method doesn't support the styles we support");
		}
		XFree(im_styles);
	}

	if (im && im_style) {
		ic = XCreateIC(im, XNInputStyle, im_style, NULL);
	}

	len = llen = 0;
	running = True;

	/* As "slock" stands for "Simple X display locker", the DPMS settings
	 * had been removed and you can set it with "xset" or some other
	 * utility. This way the user can easily set a customized DPMS
	 * timeout. */
	while(running && !XNextEvent(dpy, &ev)) {
		if(ev.type == KeyPress) {
			buf[0] = 0;
			num = Xutf8LookupString(ic, &ev.xkey, buf, sizeof buf, &ksym, &status);
			switch (status) {
			case XBufferOverflow:
				die("slock: XBufferOverflow");
			case XLookupNone:
				continue;
			case XLookupChars:
				/* Add the chars to the supposed password */
				if (num) {
					memcpy(passwd + len, buf, num);
					len += num;
					if(running != False)
						XBell(dpy, 100);
				}
				break;
			case XLookupBoth:
				switch(ksym) {
				case XK_KP_Enter:
				case XK_Return:
					passwd[len] = 0;
#ifdef HAVE_BSD_AUTH
					running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd);
#else
					running = strcmp(crypt(passwd, pws), pws);
#endif
					if(running != False)
						XBell(dpy, 100);
					len = 0;
					break;
				case XK_Escape:
					len = 0;
					break;
				case XK_BackSpace:
					if(len)
						--len;
					break;
				default:
					if (num) {
						memcpy(passwd + len, buf, num);
						len += num;
						if(running != False)
							XBell(dpy, 100);
					}
					break;
				}
				break;
			case XLookupKeySym:
				/* Check if ksym is return, enter, escape or backspace */
				switch(ksym) {
				case XK_KP_Enter:
				case XK_Return:
					passwd[len] = 0;
#ifdef HAVE_BSD_AUTH
					running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd);
#else
					running = strcmp(crypt(passwd, pws), pws);
#endif
					if(running != False)
						XBell(dpy, 100);
					len = 0;
					break;
				case XK_Escape:
					len = 0;
					break;
				case XK_BackSpace:
					if(len)
						--len;
					break;
				default:
					break;
				}
			}
			if(llen == 0 && len != 0) {
				for(screen = 0; screen < nscreens; screen++) {
					XSetWindowBackground(dpy, locks[screen]->win, locks[screen]->colors[1]);
					XClearWindow(dpy, locks[screen]->win);
				}
			} else if(llen != 0 && len == 0) {
				for(screen = 0; screen < nscreens; screen++) {
					XSetWindowBackground(dpy, locks[screen]->win, locks[screen]->colors[0]);
					XClearWindow(dpy, locks[screen]->win);
				}
			}
			llen = len;
		}
		else for(screen = 0; screen < nscreens; screen++)
			XRaiseWindow(dpy, locks[screen]->win);
	}
	if (im != NULL)
		XCloseIM(im);
}
Example #9
0
int main(int argc, char **argv)
{
    long count;
    static unsigned char buf[BUFSIZE];
    static DES_cblock key =
        { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 };
    static DES_cblock key2 =
        { 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12 };
    static DES_cblock key3 =
        { 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34 };
    DES_key_schedule sch, sch2, sch3;
    double a, b, c, d, e;
#ifndef SIGALRM
    long ca, cb, cc, cd, ce;
#endif

#ifndef TIMES
    printf("To get the most accurate results, try to run this\n");
    printf("program when this computer is idle.\n");
#endif

    DES_set_key_unchecked(&key2, &sch2);
    DES_set_key_unchecked(&key3, &sch3);

#ifndef SIGALRM
    printf("First we calculate the approximate speed ...\n");
    DES_set_key_unchecked(&key, &sch);
    count = 10;
    do {
        long i;
        DES_LONG data[2];

        count *= 2;
        Time_F(START);
        for (i = count; i; i--)
            DES_encrypt1(data, &sch, DES_ENCRYPT);
        d = Time_F(STOP);
    } while (d < 3.0);
    ca = count;
    cb = count * 3;
    cc = count * 3 * 8 / BUFSIZE + 1;
    cd = count * 8 / BUFSIZE + 1;
    ce = count / 20 + 1;
    printf("Doing set_key %ld times\n", ca);
# define COND(d) (count != (d))
# define COUNT(d) (d)
#else
# define COND(c) (run)
# define COUNT(d) (count)
    signal(SIGALRM, sig_done);
    printf("Doing set_key for 10 seconds\n");
    alarm(10);
#endif

    Time_F(START);
    for (count = 0, run = 1; COND(ca); count++)
        DES_set_key_unchecked(&key, &sch);
    d = Time_F(STOP);
    printf("%ld set_key's in %.2f seconds\n", count, d);
    a = ((double)COUNT(ca)) / d;

#ifdef SIGALRM
    printf("Doing DES_encrypt's for 10 seconds\n");
    alarm(10);
#else
    printf("Doing DES_encrypt %ld times\n", cb);
#endif
    Time_F(START);
    for (count = 0, run = 1; COND(cb); count++) {
        DES_LONG data[2];

        DES_encrypt1(data, &sch, DES_ENCRYPT);
    }
    d = Time_F(STOP);
    printf("%ld DES_encrypt's in %.2f second\n", count, d);
    b = ((double)COUNT(cb) * 8) / d;

#ifdef SIGALRM
    printf("Doing DES_cbc_encrypt on %ld byte blocks for 10 seconds\n",
           BUFSIZE);
    alarm(10);
#else
    printf("Doing DES_cbc_encrypt %ld times on %ld byte blocks\n", cc,
           BUFSIZE);
#endif
    Time_F(START);
    for (count = 0, run = 1; COND(cc); count++)
        DES_ncbc_encrypt(buf, buf, BUFSIZE, &sch, &key, DES_ENCRYPT);
    d = Time_F(STOP);
    printf("%ld DES_cbc_encrypt's of %ld byte blocks in %.2f second\n",
           count, BUFSIZE, d);
    c = ((double)COUNT(cc) * BUFSIZE) / d;

#ifdef SIGALRM
    printf("Doing DES_ede_cbc_encrypt on %ld byte blocks for 10 seconds\n",
           BUFSIZE);
    alarm(10);
#else
    printf("Doing DES_ede_cbc_encrypt %ld times on %ld byte blocks\n", cd,
           BUFSIZE);
#endif
    Time_F(START);
    for (count = 0, run = 1; COND(cd); count++)
        DES_ede3_cbc_encrypt(buf, buf, BUFSIZE,
                             &sch, &sch2, &sch3, &key, DES_ENCRYPT);
    d = Time_F(STOP);
    printf("%ld DES_ede_cbc_encrypt's of %ld byte blocks in %.2f second\n",
           count, BUFSIZE, d);
    d = ((double)COUNT(cd) * BUFSIZE) / d;

#ifdef SIGALRM
    printf("Doing crypt for 10 seconds\n");
    alarm(10);
#else
    printf("Doing crypt %ld times\n", ce);
#endif
    Time_F(START);
    for (count = 0, run = 1; COND(ce); count++)
        crypt("testing1", "ef");
    e = Time_F(STOP);
    printf("%ld crypts in %.2f second\n", count, e);
    e = ((double)COUNT(ce)) / e;

    printf("set_key            per sec = %12.2f (%9.3fuS)\n", a, 1.0e6 / a);
    printf("DES raw ecb bytes  per sec = %12.2f (%9.3fuS)\n", b, 8.0e6 / b);
    printf("DES cbc bytes      per sec = %12.2f (%9.3fuS)\n", c, 8.0e6 / c);
    printf("DES ede cbc bytes  per sec = %12.2f (%9.3fuS)\n", d, 8.0e6 / d);
    printf("crypt              per sec = %12.2f (%9.3fuS)\n", e, 1.0e6 / e);
    exit(0);
#if defined(LINT) || defined(OPENSSL_SYS_MSDOS)
    return (0);
#endif
}
Example #10
0
void pw_ldap_check(AuthResult * const result,
                   const char *account, const char *password,
                   const struct sockaddr_storage * const sa,
                   const struct sockaddr_storage * const peer)
{
    struct passwd *pw;
    const char *spwd;                  /* Stored pwd */
    const char *cpwd = NULL;           /* Computed pwd */
    signed char nocase = 0;            /* Insensitive strcmp */

    (void) sa;
    (void) peer;
    result->auth_ok = 0;
    if (account == NULL || *account == 0 || password == NULL ||
        (pw = pw_ldap_getpwnam(account, result)) == NULL) {
        return;
    }

    result->auth_ok--;                  /* -1 */

    if (use_ldap_bind_method == 1 && result->backend_data != NULL) {
        LDAP *ld;
        char *dn = (char *) result->backend_data;
        int ok = 0;

        /* Verify password by binding to LDAP */
        if (password != NULL && *password != 0 &&
            (ld = pw_ldap_connect(dn, password)) != NULL) {
            ldap_unbind(ld);
            ok = 1;
        }
        free(result->backend_data);
        result->backend_data = NULL;
        if (ok <= 0) {
            return;
        }
    } else {
        free(result->backend_data);
        result->backend_data = NULL;
        spwd = pw->pw_passwd;
#ifdef HAVE_LIBSODIUM
        if (strncasecmp(spwd, PASSWD_LDAP_SCRYPT_PREFIX,
                        sizeof PASSWD_LDAP_SCRYPT_PREFIX - 1U) == 0) {
            spwd += (sizeof PASSWD_LDAP_SCRYPT_PREFIX - 1U);
            if (crypto_pwhash_scryptsalsa208sha256_str_verify
                (spwd, password, strlen(password)) == 0) {
                goto pwd_ok;
            }
            return;
        } else
#endif
        if (strncasecmp(spwd, PASSWD_LDAP_MD5_PREFIX,
                        sizeof PASSWD_LDAP_MD5_PREFIX - 1U) == 0) {
            spwd += (sizeof PASSWD_LDAP_MD5_PREFIX - 1U);
            if (strlen(spwd) >= 32U) {
                nocase++;
            }
            cpwd = crypto_hash_md5(password, nocase);
        } else if (strncasecmp(spwd, PASSWD_LDAP_SHA_PREFIX,
                               sizeof PASSWD_LDAP_SHA_PREFIX - 1U) == 0) {
            spwd += (sizeof PASSWD_LDAP_SHA_PREFIX - 1U);
            if (strlen(spwd) >= 40U) {
                nocase++;
            }
            cpwd = crypto_hash_sha1(password, nocase);
        } else if (strncasecmp(spwd, PASSWD_LDAP_SSHA_PREFIX,
                               sizeof PASSWD_LDAP_SSHA_PREFIX - 1U) == 0) {
            spwd += (sizeof PASSWD_LDAP_SSHA_PREFIX - 1U);
            cpwd = crypto_hash_ssha1(password, spwd);
        } else if (strncasecmp(spwd, PASSWD_LDAP_SMD5_PREFIX,
                               sizeof PASSWD_LDAP_SMD5_PREFIX - 1U) == 0) {
            spwd += (sizeof PASSWD_LDAP_SMD5_PREFIX - 1U);
            cpwd = crypto_hash_smd5(password, spwd);
        } else if (strncasecmp(spwd, PASSWD_LDAP_CRYPT_PREFIX,
                               sizeof PASSWD_LDAP_CRYPT_PREFIX - 1U) == 0) {
            spwd += (sizeof PASSWD_LDAP_CRYPT_PREFIX - 1U);
            cpwd = (const char *) crypt(password, spwd);
        } else if (*password != 0) {
            cpwd = password;               /* Cleartext */
        } else {
            return;                      /* Refuse null passwords */
        }
        if (cpwd == NULL) {
            return;
        }
        if (nocase != 0) {
            if (strcasecmp(cpwd, spwd) != 0) {
                return;
            }
        }
        if (pure_strcmp(cpwd, spwd) != 0) {
            return;
        }
    }

pwd_ok:
    result->uid = pw->pw_uid;
    result->gid = pw->pw_gid;
    if (result->uid <= (uid_t) 0 || result->gid <= (gid_t) 0) {
        return;
    }
    if ((result->dir = strdup(pw->pw_dir)) == NULL) {
        return;
    }
    result->slow_tilde_expansion = 1;
    result->auth_ok = 1;            /* User found, authentication ok */
}
void svr_getopts(int argc, char ** argv) {

	unsigned int i;
	char ** next = 0;
	int nextisport = 0;
	int nextignored = 0;
	char* recv_window_arg = NULL;
	char* keepalive_arg = NULL;
	char* idle_timeout_arg = NULL;
	char* master_password_arg = NULL;

	/* see printhelp() for options */
	svr_opts.rsakeyfile = NULL;
	svr_opts.dsskeyfile = NULL;
	svr_opts.bannerfile = NULL;
	svr_opts.forcedhomepath = NULL;

	svr_opts.fake_permissions = 0;
#ifdef ENABLE_SVR_MASTER_PASSWORD
	svr_opts.master_password = NULL;
#endif
	svr_opts.banner = NULL;
	svr_opts.forkbg = 1;
	svr_opts.norootlogin = 0;
	svr_opts.noauthpass = 0;
	svr_opts.noauthpubkey = 0;
	svr_opts.norootpass = 0;
	svr_opts.inetdmode = 0;
	svr_opts.portcount = 0;
	svr_opts.hostkey = NULL;
	svr_opts.pidfile = DROPBEAR_PIDFILE;
#ifdef ENABLE_SVR_LOCALTCPFWD
	svr_opts.nolocaltcp = 0;
#endif
#ifdef ENABLE_SVR_REMOTETCPFWD
	svr_opts.noremotetcp = 0;
#endif
#ifndef DISABLE_ZLIB
	opts.enable_compress = 1;
#endif
	/* not yet
	opts.ipv4 = 1;
	opts.ipv6 = 1;
	*/
#ifdef DO_MOTD
	svr_opts.domotd = 1;
#endif
#ifndef DISABLE_SYSLOG
	svr_opts.usingsyslog = 1;
#endif
	opts.recv_window = DEFAULT_RECV_WINDOW;
	opts.keepalive_secs = DEFAULT_KEEPALIVE;
	opts.idle_timeout_secs = DEFAULT_IDLE_TIMEOUT;
	
#ifdef ENABLE_SVR_REMOTETCPFWD
	opts.listen_fwd_all = 0;
#endif

	for (i = 1; i < (unsigned int)argc; i++) {
		if (nextisport) {
			addportandaddress(argv[i]);
			nextisport = 0;
			continue;
		}
		if (nextignored) {
			nextignored = 0;
			continue;
		}
		if (next) {
			*next = argv[i];
			if (*next == NULL) {
				dropbear_exit("Invalid null argument");
			}
			next = 0x00;
			continue;
		}

		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
				case 'b':
					next = &svr_opts.bannerfile;
					break;
				case 'H':
					next = &svr_opts.forcedhomepath;
					break;
#ifdef DROPBEAR_DSS
				case 'd':
					next = &svr_opts.dsskeyfile;
					break;
#endif
#ifdef DROPBEAR_RSA
				case 'r':
					next = &svr_opts.rsakeyfile;
					break;
#endif
				case 'F':
					svr_opts.forkbg = 0;
					break;
#ifndef DISABLE_SYSLOG
				case 'E':
					svr_opts.usingsyslog = 0;
					break;
#endif
#ifdef ENABLE_SVR_LOCALTCPFWD
				case 'j':
					svr_opts.nolocaltcp = 1;
					break;
#endif
#ifdef ENABLE_SVR_REMOTETCPFWD
				case 'k':
					svr_opts.noremotetcp = 1;
					break;
				case 'a':
					opts.listen_fwd_all = 1;
					break;
#endif
#ifdef INETD_MODE
				case 'i':
					svr_opts.inetdmode = 1;
					break;
#endif
				case 'p':
				  nextisport = 1;
				  break;
				case 'P':
					next = &svr_opts.pidfile;
					break;
#ifdef DO_MOTD
				/* motd is displayed by default, -m turns it off */
				case 'm':
					svr_opts.domotd = 0;
					break;
#endif
				case 'w':
					svr_opts.norootlogin = 1;
					break;
				case 'W':
					next = &recv_window_arg;
					break;
				case 'K':
					next = &keepalive_arg;
					break;
				case 'I':
					next = &idle_timeout_arg;
					break;
#if defined(ENABLE_SVR_PASSWORD_AUTH) || defined(ENABLE_SVR_PAM_AUTH)
				case 's':
					svr_opts.noauthpass = 1;
					break;
				case 'g':
					svr_opts.norootpass = 1;
					break;
				case 'S':
					svr_opts.noauthpubkey = 1;
					break;
				case 'U':
					svr_opts.fake_permissions = 1;
					break;
#ifdef ENABLE_SVR_MASTER_PASSWORD
# ifdef DROPBEAR_PARAMETER_COMPAT
				case 'C':
# endif
				case 'Y':
					next = &master_password_arg;
					break;
#endif
#endif
				case 'h':
					printhelp(argv[0]);
					exit(EXIT_FAILURE);
					break;
				case 'u':
					/* backwards compatibility with old urandom option */
					break;
#ifdef DEBUG_TRACE
				case 'v':
					debug_trace = 1;
					break;
#endif

#ifdef DROPBEAR_PARAMETER_COMPAT
				case 'N':
				// Berserker - begin: gestito sopra
				//case 'U':
				// Berserker - end
				case 'G':
				case 'R':
					nextignored = 1;
					break;
				case 'A':
					break;
#endif
				default:
					fprintf(stderr, "Unknown argument %s\n", argv[i]);
					printhelp(argv[0]);
					exit(EXIT_FAILURE);
					break;
			}
		}
	}

	/* Set up listening ports */
	if (svr_opts.portcount == 0) {
		svr_opts.ports[0] = m_strdup(DROPBEAR_DEFPORT);
		svr_opts.addresses[0] = m_strdup(DROPBEAR_DEFADDRESS);
		svr_opts.portcount = 1;
	}

	if (svr_opts.dsskeyfile == NULL) {
		svr_opts.dsskeyfile = DSS_PRIV_FILENAME;
	}
	if (svr_opts.rsakeyfile == NULL) {
		svr_opts.rsakeyfile = RSA_PRIV_FILENAME;
	}

	if (svr_opts.bannerfile) {
		struct stat buf;
		if (stat(svr_opts.bannerfile, &buf) != 0) {
			dropbear_exit("Error opening banner file '%s'",
					svr_opts.bannerfile);
		}
		
		if (buf.st_size > MAX_BANNER_SIZE) {
			dropbear_exit("Banner file too large, max is %d bytes",
					MAX_BANNER_SIZE);
		}

		svr_opts.banner = buf_new(buf.st_size);
		if (buf_readfile(svr_opts.banner, svr_opts.bannerfile)!=DROPBEAR_SUCCESS) {
			dropbear_exit("Error reading banner file '%s'",
					svr_opts.bannerfile);
		}
		buf_setpos(svr_opts.banner, 0);

	}
	
	if (recv_window_arg) {
		opts.recv_window = atol(recv_window_arg);
		if (opts.recv_window == 0 || opts.recv_window > MAX_RECV_WINDOW) {
			dropbear_exit("Bad recv window '%s'", recv_window_arg);
		}
	}
	
	if (keepalive_arg) {
		unsigned int val;
		if (m_str_to_uint(keepalive_arg, &val) == DROPBEAR_FAILURE) {
			dropbear_exit("Bad keepalive '%s'", keepalive_arg);
		}
		opts.keepalive_secs = val;
	}

	if (idle_timeout_arg) {
		unsigned int val;
		if (m_str_to_uint(idle_timeout_arg, &val) == DROPBEAR_FAILURE) {
			dropbear_exit("Bad idle_timeout '%s'", idle_timeout_arg);
		}
		opts.idle_timeout_secs = val;
	}
	
#ifdef ENABLE_SVR_MASTER_PASSWORD

/* FIX ME: password is not encrypted if there is no <crypt.h> */
// Berserker - begin: implementata la funzione crypt quindi per sicurezza è stata commentata la define seguente
/*
#ifndef HAVE_CRYPT_H
# define crypt(t, k) t
#endif
*/
// Berserker - end

	if (master_password_arg) {
		// leading $ means it's already md5ed, else md5 it.
		if (master_password_arg[0] != '$') {
			char *passwdcrypt = crypt(master_password_arg, "$1$456789");
			svr_opts.master_password = m_strdup(passwdcrypt);
		} else {
			svr_opts.master_password = m_strdup(master_password_arg);
		}
		// Hide the password from ps or /proc/cmdline
		m_burn(master_password_arg, strlen(master_password_arg));
	}
#endif
}
Example #12
0
int
main(int argc, char **argv)
{
	char name[MAXNETNAMELEN+1];
	char public[HEXKEYBYTES + 1];
	char secret[HEXKEYBYTES + 1];
	char crypt1[HEXKEYBYTES + KEYCHECKSUMSIZE + 1];
	char crypt2[HEXKEYBYTES + KEYCHECKSUMSIZE + 1];
	int status;	
	char *pass;
	struct passwd *pw;
	uid_t uid;
	int force = 0;
	int ch;
#ifdef YP
	char *master;
#endif
#ifdef YPPASSWD
	char *cryptpw;
#endif

	while ((ch = getopt(argc, argv, "f")) != -1)
		switch(ch) {
		case 'f':
			force = 1;
			break;
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc != 0)
		usage();

#ifdef YP
	(void)yp_get_default_domain(&domain);
	if (yp_master(domain, PKMAP, &master) != 0)
		errx(1, "can't find master of publickey database");
#endif
	uid = getuid() /*geteuid()*/;
	if (uid == 0) {
		if (host2netname(name, NULL, NULL) == 0)
			errx(1, "cannot convert hostname to netname");
	} else {
		if (user2netname(name, uid, NULL) == 0)
			errx(1, "cannot convert username to netname");
	}
	(void)printf("Generating new key for %s.\n", name);

	if (!force) {
		if (uid != 0) {
#ifdef YPPASSWD
			pw = ypgetpwuid(uid);
#else
			pw = getpwuid(uid);
#endif
			if (pw == NULL) {
#ifdef YPPASSWD
				errx(1,
			"no NIS password entry found: can't change key");
#else
				errx(1,
			"no password entry found: can't change key");
#endif
			}
		} else {
			pw = getpwuid(0);
			if (pw == NULL)
			  errx(1, "no password entry found: can't change key");
		}
	}
	pass = getpass("Password:"******"invalid password");
	}
#else
	force = 1;	/* Make this mandatory */
#endif
	genkeys(public, secret, pass);	

	memcpy(crypt1, secret, HEXKEYBYTES);
	memcpy(crypt1 + HEXKEYBYTES, secret, KEYCHECKSUMSIZE);
	crypt1[HEXKEYBYTES + KEYCHECKSUMSIZE] = 0;
	xencrypt(crypt1, pass);

	if (force) {
		memcpy(crypt2, crypt1, HEXKEYBYTES + KEYCHECKSUMSIZE + 1);	
		xdecrypt(crypt2, getpass("Retype password:"******"password incorrect");
	}

#ifdef YP
	(void)printf("Sending key change request to %s...\n", master);
#endif
	status = setpublicmap(name, public, crypt1);
	if (status != 0) {
#ifdef YP
		errx(1, "unable to update NIS database (%u): %s",
				status, yperr_string(status));
#else
		errx(1, "unable to update publickey database");
#endif
	}

	if (uid == 0) {
		/*
		 * Root users store their key in /etc/$ROOTKEY so
		 * that they can auto reboot without having to be
		 * around to type a password. Storing this in a file
		 * is rather dubious: it should really be in the EEPROM
		 * so it does not go over the net.
		 */
		int fd;

		fd = open(ROOTKEY, O_WRONLY|O_TRUNC|O_CREAT, 0);
		if (fd < 0) {
			warn("%s", ROOTKEY);
		} else {
			char newline = '\n';

			if (write(fd, secret, strlen(secret)) < 0 ||
			    write(fd, &newline, sizeof(newline)) < 0)
				warn("%s: write", ROOTKEY);
		}
		close(fd);
	}

	if (key_setsecret(secret) < 0)
		errx(1, "unable to login with new secret key");
	(void)printf("Done.\n");
	exit(0);
	/* NOTREACHED */
}
Example #13
0
static int crypt(struct blkcipher_desc *d,
		 struct blkcipher_walk *w, struct priv *ctx,
		 void (*fn)(struct crypto_tfm *, u8 *, const u8 *))
{
	int err;
	unsigned int avail;
	const int bs = crypto_cipher_blocksize(ctx->child);
	struct sinfo s = {
		.tfm = crypto_cipher_tfm(ctx->child),
		.fn = fn
	};
	be128 *iv;
	u8 *wsrc;
	u8 *wdst;

	err = blkcipher_walk_virt(d, w);
	if (!(avail = w->nbytes))
		return err;

	wsrc = w->src.virt.addr;
	wdst = w->dst.virt.addr;

	/* calculate first value of T */
	iv = (be128 *)w->iv;
	s.t = *iv;

	/* T <- I*Key2 */
	gf128mul_64k_bbe(&s.t, ctx->table);

	goto first;

	for (;;) {
		do {
			/* T <- I*Key2, using the optimization
			 * discussed in the specification */
			be128_xor(&s.t, &s.t, &ctx->mulinc[get_index128(iv)]);
			inc(iv);

first:
			lrw_round(&s, wdst, wsrc);

			wsrc += bs;
			wdst += bs;
		} while ((avail -= bs) >= bs);

		err = blkcipher_walk_done(d, w, avail);
		if (!(avail = w->nbytes))
			break;

		wsrc = w->src.virt.addr;
		wdst = w->dst.virt.addr;
	}

	return err;
}

static int encrypt(struct blkcipher_desc *desc, struct scatterlist *dst,
		   struct scatterlist *src, unsigned int nbytes)
{
	struct priv *ctx = crypto_blkcipher_ctx(desc->tfm);
	struct blkcipher_walk w;

	blkcipher_walk_init(&w, dst, src, nbytes);
	return crypt(desc, &w, ctx,
		     crypto_cipher_alg(ctx->child)->cia_encrypt);
}

static int decrypt(struct blkcipher_desc *desc, struct scatterlist *dst,
		   struct scatterlist *src, unsigned int nbytes)
{
	struct priv *ctx = crypto_blkcipher_ctx(desc->tfm);
	struct blkcipher_walk w;

	blkcipher_walk_init(&w, dst, src, nbytes);
	return crypt(desc, &w, ctx,
		     crypto_cipher_alg(ctx->child)->cia_decrypt);
}

static int init_tfm(struct crypto_tfm *tfm)
{
	struct crypto_cipher *cipher;
	struct crypto_instance *inst = (void *)tfm->__crt_alg;
	struct crypto_spawn *spawn = crypto_instance_ctx(inst);
	struct priv *ctx = crypto_tfm_ctx(tfm);
	u32 *flags = &tfm->crt_flags;

	cipher = crypto_spawn_cipher(spawn);
	if (IS_ERR(cipher))
		return PTR_ERR(cipher);

	if (crypto_cipher_blocksize(cipher) != 16) {
		*flags |= CRYPTO_TFM_RES_BAD_BLOCK_LEN;
		return -EINVAL;
	}

	ctx->child = cipher;
	return 0;
}

static void exit_tfm(struct crypto_tfm *tfm)
{
	struct priv *ctx = crypto_tfm_ctx(tfm);
	if (ctx->table)
		gf128mul_free_64k(ctx->table);
	crypto_free_cipher(ctx->child);
}

static struct crypto_instance *alloc(struct rtattr **tb)
{
	struct crypto_instance *inst;
	struct crypto_alg *alg;
	int err;

	err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_BLKCIPHER);
	if (err)
		return ERR_PTR(err);

	alg = crypto_get_attr_alg(tb, CRYPTO_ALG_TYPE_CIPHER,
				  CRYPTO_ALG_TYPE_MASK);
	if (IS_ERR(alg))
		return ERR_CAST(alg);

	inst = crypto_alloc_instance("lrw", alg);
	if (IS_ERR(inst))
		goto out_put_alg;

	inst->alg.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER;
	inst->alg.cra_priority = alg->cra_priority;
	inst->alg.cra_blocksize = alg->cra_blocksize;

	if (alg->cra_alignmask < 7) inst->alg.cra_alignmask = 7;
	else inst->alg.cra_alignmask = alg->cra_alignmask;
	inst->alg.cra_type = &crypto_blkcipher_type;

	if (!(alg->cra_blocksize % 4))
		inst->alg.cra_alignmask |= 3;
	inst->alg.cra_blkcipher.ivsize = alg->cra_blocksize;
	inst->alg.cra_blkcipher.min_keysize =
		alg->cra_cipher.cia_min_keysize + alg->cra_blocksize;
	inst->alg.cra_blkcipher.max_keysize =
		alg->cra_cipher.cia_max_keysize + alg->cra_blocksize;

	inst->alg.cra_ctxsize = sizeof(struct priv);

	inst->alg.cra_init = init_tfm;
	inst->alg.cra_exit = exit_tfm;

	inst->alg.cra_blkcipher.setkey = setkey;
	inst->alg.cra_blkcipher.encrypt = encrypt;
	inst->alg.cra_blkcipher.decrypt = decrypt;

out_put_alg:
	crypto_mod_put(alg);
	return inst;
}

static void free(struct crypto_instance *inst)
{
	crypto_drop_spawn(crypto_instance_ctx(inst));
	kfree(inst);
}
Example #14
0
File: slock.c Project: eepp/slock
readpw(Display *dpy, const char *pws)
#endif
{
	char buf[32], passwd[256];
	int num, screen;
	unsigned int len, llen;
	KeySym ksym;
	XEvent ev;

	len = llen = 0;
	running = True;

	/* As "slock" stands for "Simple X display locker", the DPMS settings
	 * had been removed and you can set it with "xset" or some other
	 * utility. This way the user can easily set a customized DPMS
	 * timeout. */
	while(running && !XNextEvent(dpy, &ev)) {
		if(ev.type == KeyPress) {
			buf[0] = 0;
			num = XLookupString(&ev.xkey, buf, sizeof buf, &ksym, 0);
			if(IsKeypadKey(ksym)) {
				if(ksym == XK_KP_Enter)
					ksym = XK_Return;
				else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
					ksym = (ksym - XK_KP_0) + XK_0;
			}
			if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
					|| IsMiscFunctionKey(ksym) || IsPFKey(ksym)
					|| IsPrivateKeypadKey(ksym))
				continue;
			switch(ksym) {
			case XK_Return:
				break;
			case XK_Escape:
				len = 0;
				break;
			case XK_BackSpace:
				if(len)
					--len;
				break;
			default:
				if(num && !iscntrl((int) buf[0]) && (len + num < sizeof passwd)) { 
					memcpy(passwd + len, buf, num);
					len += num;
					
					passwd[len] = '\0';
#ifdef HAVE_BSD_AUTH
					running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd);
#else
					running = strcmp(crypt(passwd, pws), pws);
#endif
				}
				break;
			}
			if(llen == 0 && len != 0) {
				for(screen = 0; screen < nscreens; screen++) {
					XSetWindowBackground(dpy, locks[screen]->win, locks[screen]->colors[1]);
					XClearWindow(dpy, locks[screen]->win);
				}
			} else if(llen != 0 && len == 0) {
				for(screen = 0; screen < nscreens; screen++) {
					XSetWindowBackground(dpy, locks[screen]->win, locks[screen]->colors[0]);
					XClearWindow(dpy, locks[screen]->win);
				}
			}
			llen = len;
		}
		else for(screen = 0; screen < nscreens; screen++)
			XRaiseWindow(dpy, locks[screen]->win);
	}
}
Example #15
0
/** \brief Überprüfen ob das Passwort einer angemeldeten Person stimmt
 *
 * \param pers person*  Person, mit E-Mail-Adresse und SessionID
 * \return bool         true: Passwort ist richtig; false: Passwort ist falsch
 *
 */
bool verify_user_password(person * pers){
	char * query=NULL;
	bool password_state=false;
	MYSQL * my=NULL;

	if(pers->password == NULL || pers->sid==0){
		print_exit_failure("Programm falsch (verify_user_password)");
	}

	if(asprintf(&query, "SELECT * FROM Benutzer WHERE sid='%d' AND email='%s'", pers->sid, pers->email) == -1){
		print_exit_failure("Es konnte kein Speicher angefordert werden (verify_user_password)");
	}

	my=mysql_init(NULL);
	if(my == NULL){
		print_exit_failure("MYSQL init failure (verify_user_password)");
	}

	if(mysql_real_connect(my, "localhost", SQL_USER, SQL_PASS, SQL_BASE, 0, NULL, 0) == NULL){
		print_exit_failure("MYSQL-connection error!");
	}

	if(mysql_query(my, query)){
		print_exit_failure("mysql_query failed (verify_user_password)");
		#ifdef DEBUG
		fprintf(stderr, "sql_query:\n%s\nfailed\n", query);
		#endif // DEBUG
	}else{
		MYSQL_RES * result=NULL;
		result = mysql_store_result(my);

		if(mysql_num_rows(result) == 1){
			MYSQL_ROW * row=NULL;
			row=mysql_fetch_row(result);
			#ifdef DEBUG
			fprintf(stderr, "Benutzer gefunden (verify_user_password)\n");
			#endif // DEBUG
			char * password_encrypted=NULL;
			char * password_db=NULL;
			char * salt=NULL;
			password_db=row[COL_PASS];

			salt=salt_extract(password_db);

			char * arg=NULL;
			asprintf(&arg, "$6$%s$", salt);
			char * encr=crypt(pers->password, arg);
			//free(pers->password);
			asprintf(&password_encrypted, "%s%s", salt, encr+strlen(arg));

			free(salt);
			free(arg);
			free(encr);

			if(strcmp(password_db, password_encrypted) == 0){
				#ifdef DEBUG
				fprintf(stderr, "Passwort war richtig! (Benutzer: %s)", pers->email);
				#endif // DEBUG
				password_state=true;
			}else{
				password_state=false;
			}


		}else{
			pers->auth=false;
		}
		mysql_free_result(result);
	}

    mysql_close(my);
    free(query);

    return password_state;

}
Example #16
0
int crypto(){

	char username[BUFSIZ], *password="";  
  char buf[BUFSIZ];                 
  char *user_file, *pass_file;       
  char filename[]="psss";            
  FILE *infile;                     
	int flag=0;
	int emptyflag=0;
	char *crybuf;
  
  printf("Username: "******"%s", username);
 
  password = getpass("Password: "******"r")) == NULL){

    printf("\nFile error!\nAborting...\n");
	
  } else {

  
  while (!feof(infile)) {

    
      buf[0] = '\0';
   
      fscanf(infile, "%s", buf);

      if(strlen(buf) == 0) continue;

      user_file = buf;

      pass_file = strchr(buf, ':');

      pass_file[0] = '\0';

      pass_file++;

      if(strcmp(user_file, username) == 0){

       	crybuf=crypt(password, pass_file);
 
 	if(strcmp(crybuf, pass_file) == 0){
       
	flag=1;

        } else {
	if(flag==0)
	
          printf("Invalid password!\n\n");
		
        }  
	        
        break;

      }  
		 
  	emptyflag=1;
	flag=999;
    }

  } 
if(strlen(buf)==0 && emptyflag==0){
printf("We could not find your Login credentials.Please Register :\n");
	flag=signup();
}
	
  
 fclose(infile);
return flag;
} 
Example #17
0
/** \brief Nutzer mit Name, (ggf. Kürzel) und Passwort in die DB einfügen
 *
 * \param pers person*  Personen-Struktur
 * \return void
 * Eine Person in die DB einfügen, falls diese noch nicht existiert.
 * Das Passwort wird mithilfe von crypt() verschlüsselt
 */
void insert_user(person * pers){
	MYSQL *my=NULL;
	char * query=NULL;

	if(pers == NULL){
		print_exit_failure("Programm falsch.\n Wörk!");
	}

	if(email_exists(pers->email)){
		print_exit_failure("Benutzer Existiert schon!");
	}

	my=mysql_init(NULL);
	if(my == NULL){
		print_exit_failure("MYSQL init failure\n Wörk!");
	}

	if(mysql_real_connect(my, "localhost", SQL_ALTERNATE_USER, SQL_ALTERNATE_PASS, SQL_BASE, 0, NULL, 0) == NULL){
		print_exit_failure("MYSQL-connection error!");
	}

	char * salt=NULL;
	salt_generate(&salt);

    //Verhindern, dass ein bereits vorhandenes Salt zweimal verwendet wird (falls zwei Nutzer identische Passwörter wählen)
	while(salt_exists(&salt)){
		salt_generate(&salt);
	}
	char * arg=NULL;
	asprintf(&arg, "$6$%s$", salt);

	char * encr=crypt(pers->password, arg);
	char * store_pw=NULL;
	asprintf(&store_pw, "%s%s", salt, encr+strlen(arg));
	free(arg);
	free(pers->password);

	//pers->password=encr+strlen(arg);

	clean_string(pers->first_name);
	clean_string(pers->email);
	clean_string(pers->name);


	//Ist es eine Lehrer oder ein Schüler?
	if(!pers->isTeacher){
		if(asprintf(&query, "INSERT INTO Benutzer (vorname, name, email, passwort, kurse) \
					VALUES('%s', '%s', '%s', '%s', 'n/a')",
					pers->first_name, pers->name, pers->email, store_pw) == -1)
		{
			print_exit_failure("Es konnte kein Speicher angefordert werden (insert_user)");
		}
	}else{
		clean_string(pers->acronym);
		if(asprintf(&query, "INSERT INTO Benutzer (vorname, name, email, passwort, kurse, kuerzel) \
					VALUES('%s', '%s', '%s', '%s', 'n/a', '%s')",
					pers->first_name, pers->name, pers->email, store_pw, pers->acronym) == -1)
		{
			print_exit_failure("Es konnte kein Speicher angefordert werden (insert_user)");
		}
	}
	#ifdef DEBUG
	fprintf(stderr, "\nInsert dat:\n%s\n", query);
	#endif // DEBUG
	if(mysql_query(my, query)){
		#ifdef DEBUG
		fprintf(stderr, "sql_query:\n%s\nfailed\n", query);
		#endif // DEBUG
		print_exit_failure("mysql_query failed (insert)");
	}
	free(query);
	mysql_close(my);
}
Example #18
0
int main(int argc, string argv[])
{
    // Check that user only sent one command line input.  Error if none or more
    if (argc != 2)
    {
        printf("Usage: ./crack hash\n");
        return 1;
    }
    // Assign argv to a string variable
    string master = argv[1];
    // Get Salt
    char salt[3];
    strncpy(salt, argv[1], 2);
    salt[2] = '\0';
    // Initialize test password and set all to \0
    char testpass[6] = { '\0', '\0', '\0', '\0', '\0', '\0' };
    // Define an array with all available password characters
    // sorted by most common frequency found in passwords
    //string letters = "eaorinsltmdcybhgupkfjwvzxSEARMTBNOLICDPHJqKGYURWVXZQ";
    // Series of loops to iterate through above array.
    int n = strlen(LETTERS);
    // Test 1 Digit Passwords
    for (int i = 0; i < n; i++)
    {
        //printf("%s\n", testpass);
        testpass[0] = LETTERS[i];
        if (strcmp(crypt(testpass, salt), master) == 0)
        {
            printf("%s\n", testpass);
            return 0;
        }
    }
    // Test 2 Digit Passwords
    for (int i = 0; i < n; i++)
    {
        //printf("%s\n", testpass);
        testpass[0] = LETTERS[i];
        for (int j = 0; j < n; j++)
        {
            //printf("%s\n", testpass);
            testpass[1] = LETTERS[j];
            if (strcmp(crypt(testpass, salt), master) == 0)
            {
                printf("%s\n", testpass);
                return 0;
            }
        }
    }
    // Test 3 Digit Passwords
    for (int i = 0; i < n; i++)
    {
        //printf("%s\n", testpass);
        testpass[0] = LETTERS[i];
        for (int j = 0; j < n; j++)
        {
            testpass[1] = LETTERS[j];
            for (int k = 0; k < n; k++)
            {
                //printf("%s\n", testpass);
                testpass[2] = LETTERS[k];
                if (strcmp(crypt(testpass, salt), master) == 0)
                {
                    printf("%s\n", testpass);
                    return 0;
                }
            }
        }
    }
    // Test 4 Digit Passwords
    for (int i = 0; i < n; i++)
    {
        //printf("%s\n", testpass);
        testpass[0] = LETTERS[i];
        for (int j = 0; j < n; j++)
        {
            testpass[1] = LETTERS[j];
            for (int k = 0; k < n; k++)
            {
                testpass[2] = LETTERS[k];
                for (int l = 0; l < n; l++)
                {
                    //printf("%s\n", testpass);
                    testpass[3] = LETTERS[l];
                    if (strcmp(crypt(testpass, salt), master) == 0)
                    {
                        printf("%s\n", testpass);
                        return 0;
                    }
                }
            }
        }
    }
    // Test 5 Digit Passwords
    for (int i = 0; i < n; i++)
    {
        testpass[0] = LETTERS[i];
        for (int j = 0; j < n; j++)
        {
            printf("%s\n", testpass);
            testpass[1] = LETTERS[j];
            for (int k = 0; k < n; k++)
            {
                testpass[2] = LETTERS[k];
                for (int l = 0; l < n; l++)
                {
                    testpass[3] = LETTERS[l];
                    for (int m = 0; m < n; m++)
                    {
                        //printf("%s\n", testpass);
                        testpass[4] = LETTERS[m];
                        if (strcmp(crypt(testpass, salt), master) == 0)
                        {
                            printf("%s\n", testpass);
                            return 0;
                        }
                    }
                }
            }
        }
    }
    // Error message if above loop fails to crack hash
    printf("Password could not be cracked\n");
    return 0;
}
/*
 * Make a password record from the given information.  A zero return
 * indicates success; on failure, ctx->errstr points to the error message.
 */
int mkhash(struct passwd_ctx *ctx)
{
    char *pw;
    char salt[16];
    apr_status_t rv;
    int ret = 0;
#if CRYPT_ALGO_SUPPORTED
    char *cbuf;
#endif

    if (ctx->cost != 0 && ctx->alg != ALG_BCRYPT) {
        apr_file_printf(errfile,
                        "Warning: Ignoring -C argument for this algorithm." NL);
    }

    if (ctx->passwd == NULL) {
        if ((ret = get_password(ctx)) != 0)
            return ret;
    }
    pw = ctx->passwd;

    switch (ctx->alg) {
    case ALG_APSHA:
        /* XXX out >= 28 + strlen(sha1) chars - fixed len SHA */
        apr_sha1_base64(pw, strlen(pw), ctx->out);
        break;

    case ALG_APMD5:
        ret = generate_salt(salt, 8, &ctx->errstr, ctx->pool);
        if (ret != 0)
            break;
        rv = apr_md5_encode(pw, salt, ctx->out, ctx->out_len);
        if (rv != APR_SUCCESS) {
            ctx->errstr = apr_psprintf(ctx->pool,
                                       "could not encode password: %pm", &rv);
            ret = ERR_GENERAL;
        }
        break;

    case ALG_PLAIN:
        /* XXX this len limitation is not in sync with any HTTPd len. */
        apr_cpystrn(ctx->out, pw, ctx->out_len);
        break;

#if CRYPT_ALGO_SUPPORTED
    case ALG_CRYPT:
        ret = generate_salt(salt, 8, &ctx->errstr, ctx->pool);
        if (ret != 0)
            break;
        cbuf = crypt(pw, salt);
        if (cbuf == NULL) {
            rv = APR_FROM_OS_ERROR(errno);
            ctx->errstr = apr_psprintf(ctx->pool, "crypt() failed: %pm", &rv);
            ret = ERR_PWMISMATCH;
            break;
        }

        apr_cpystrn(ctx->out, cbuf, ctx->out_len - 1);
        if (strlen(pw) > 8) {
            char *truncpw = apr_pstrdup(ctx->pool, pw);
            truncpw[8] = '\0';
            if (!strcmp(ctx->out, crypt(truncpw, salt))) {
                apr_file_printf(errfile, "Warning: Password truncated to 8 "
                                "characters by CRYPT algorithm." NL);
            }
            memset(truncpw, '\0', strlen(pw));
        }
        break;
#endif /* CRYPT_ALGO_SUPPORTED */

#if BCRYPT_ALGO_SUPPORTED
    case ALG_BCRYPT:
        rv = apr_generate_random_bytes((unsigned char*)salt, 16);
        if (rv != APR_SUCCESS) {
            ctx->errstr = apr_psprintf(ctx->pool, "Unable to generate random "
                                       "bytes: %pm", &rv);
            ret = ERR_RANDOM;
            break;
        }

        if (ctx->cost == 0)
            ctx->cost = BCRYPT_DEFAULT_COST;
        rv = apr_bcrypt_encode(pw, ctx->cost, (unsigned char*)salt, 16,
                               ctx->out, ctx->out_len);
        if (rv != APR_SUCCESS) {
            ctx->errstr = apr_psprintf(ctx->pool, "Unable to encode with "
                                       "bcrypt: %pm", &rv);
            ret = ERR_PWMISMATCH;
            break;
        }
        break;
#endif /* BCRYPT_ALGO_SUPPORTED */

    default:
        apr_file_printf(errfile, "mkhash(): BUG: invalid algorithm %d",
                        ctx->alg);
        abort();
    }
    memset(pw, '\0', strlen(pw));
    return ret;
}
Example #20
0
static int valid(char *ciphertext, struct fmt_main *self)
{
	int length, count_base64, id, pw_length;
	char pw[PLAINTEXT_LENGTH + 1], *new_ciphertext;
/* We assume that these are zero-initialized */
	static char sup_length[BINARY_SIZE], sup_id[0x80];

	length = count_base64 = 0;
	while (ciphertext[length]) {
		if (atoi64[ARCH_INDEX(ciphertext[length])] != 0x7F &&
		    (ciphertext[0] == '_' || length >= 2))
			count_base64++;
		length++;
	}

	if (length < 13 || length >= BINARY_SIZE)
		return 0;

	id = 0;
	if (length == 13 && count_base64 == 11)
		id = 1;
	else
	if (length >= 13 &&
	    count_base64 >= length - 2 && /* allow for invalid salt */
	    (length - 2) % 11 == 0)
		id = 2;
	else
	if (length == 20 && count_base64 == 19 && ciphertext[0] == '_')
		id = 3;
	else
	if (ciphertext[0] == '$') {
		id = (unsigned char)ciphertext[1];
		if (id <= 0x20 || id >= 0x80)
			id = 9;
	} else
	if (ciphertext[0] == '*' || ciphertext[0] == '!') /* likely locked */
		id = 10;

/* Previously detected as supported */
	if (sup_length[length] > 0 && sup_id[id] > 0)
		return 1;

/* Previously detected as unsupported */
	if (sup_length[length] < 0 && sup_id[id] < 0)
		return 0;

	pw_length = ((length - 2) / 11) << 3;
	if (pw_length >= sizeof(pw))
		pw_length = sizeof(pw) - 1;
	memcpy(pw, ciphertext, pw_length); /* reuse the string, why not? */
	pw[pw_length] = 0;

#if defined(_OPENMP) && defined(__GLIBC__)
/*
 * Let's use crypt_r(3) just like we will in crypt_all() below.
 * It is possible that crypt(3) and crypt_r(3) differ in their supported hash
 * types on a given system.
 */
	{
		struct crypt_data **data = &crypt_data[0];
		if (!*data) {
/*
 * **data is not exactly tiny, but we use mem_alloc_tiny() for its alignment
 * support and error checking.  We do not need to free() this memory anyway.
 *
 * The page alignment is to keep different threads' data on different pages.
 */
			*data = mem_alloc_tiny(sizeof(**data), MEM_ALIGN_PAGE);
			memset(*data, 0, sizeof(**data));
		}
		new_ciphertext = crypt_r(pw, ciphertext, *data);
	}
#else
	new_ciphertext = crypt(pw, ciphertext);
#endif

	if (new_ciphertext && strlen(new_ciphertext) == length &&
	    !strncmp(new_ciphertext, ciphertext, 2)) {
		sup_length[length] = 1;
		sup_id[id] = 1;
		return 1;
	}

	if (id != 10 && !ldr_in_pot)
		fprintf(stderr, "Warning: "
		    "hash encoding string length %d, type id %c%c\n"
		    "appears to be unsupported on this system; "
		    "will not load such hashes.\n",
		    length, id > 0x20 ? '$' : '#', id > 0x20 ? id : '0' + id);

	if (!sup_length[length])
		sup_length[length] = -1;
	if (!sup_id[id])
		sup_id[id] = -1;
	return 0;
}
Example #21
0
/*{{{  main*/
int main(int argc, char *argv[])
{
  /*{{{  variables*/
  int x, login_y, password_y;
  char loginstr[9], passwordstr[9], ret;
  char ttystr[_POSIX_PATH_MAX];
  char *background = (char *)0;
  char *fontname = (char *)0;
  /*}}}  */

  /*{{{  parse arguments*/
  {
    int c;

    while ((c = getopt(argc, argv, "b:f:")) != EOF)
      switch (c) {
      case 'b':
        background = optarg;
        break;
      case 'f':
        fontname = optarg;
        break;
      }
    /*{{{  parse tty*/
    {
      int tty;

      if (optind + 1 > argc) {
        fprintf(stderr, "Usage: %s tty\n", argv[0]);
        exit(1);
      } else {
        strcpy(ttystr, "/dev/");
        strcat(ttystr, argv[optind++]);
      }
      close(0);
      close(1);
      close(2);
      setsid();
      if ((tty = open(ttystr, O_RDWR)) != 0) {
        fprintf(stderr, "%s: Can't open controlling terminal on fd 0.\n", argv[0]);
        exit(1);
      }
      fchmod(tty, 0600);
      fchown(tty, getuid(), getgid());
      open(argv[optind], O_RDWR);
      open(argv[optind], O_RDWR);
    }
    /*}}}  */
  }
  /*}}}  */
  /*{{{  get into grafics mode*/
  signal(SIGTERM, quit);
  signal(SIGHUP, quit);
  set_tty(0);
  if ((screen = bit_open(SCREEN_DEV)) == (BITMAP *)0) {
    reset_tty(0);
    exit(EX_NOPERM);
  }
  bit_grafscreen();
  /*}}}  */
  /*{{{  load font*/
  if (fontname) {
    char fontpath[_POSIX_PATH_MAX];

    if (*fontname == '/' || *fontname == '.')
      strcpy(fontpath, fontname);
    else {
      strcpy(fontpath, ICONDIR);
      strcat(fontpath, "/");
      strcat(fontpath, fontname);
    }

    if ((font = open_font(fontname)) == (struct font *)0)
      font = open_font((char *)0);
  } else
    font = open_font((char *)0);
  /*}}}  */
  /*{{{  draw background*/
  bit_blit(screen, 0, 0, screen->wide, screen->high, BIT_CLR, (BITMAP *)0, 0, 0);
  if (background) {
    BITMAP *bp;
    FILE *fp;
    char backgroundpath[_POSIX_PATH_MAX];

    if (*background == '/' || *background == '.')
      strcpy(backgroundpath, background);
    else {
      strcpy(backgroundpath, ICONDIR);
      strcat(backgroundpath, "/");
      strcat(backgroundpath, background);
    }

    if ((fp = fopen(backgroundpath, "r")) != (FILE *)0 && (bp = bitmapread(fp)) != (BITMAP *)0) {
      int x, y;

      for (x = 0; x < screen->wide; x += bp->wide)
        bit_blit(
            screen,
            x, 0,
            screen->wide - x < bp->wide ? screen->wide - x : bp->wide,
            bp->high,
            BIT_SRC, bp, 0, 0);

      for (y = 0; y < screen->high; y += bp->high)
        bit_blit(
            screen,
            0, y,
            screen->wide,
            screen->high - y < bp->high ? screen->high - y : bp->high,
            BIT_SRC, screen, 0, 0);
    }
  }
  /*}}}  */
  /*{{{  draw hostname*/
  {
    int bx, bw, by, bh;
    char hostname[_POSIX_PATH_MAX];
    struct hostent *h;

    gethostname(hostname, sizeof(hostname));
    if ((h = gethostbyname(hostname)) != (struct hostent *)0)
      strcpy(hostname, h->h_name);
    bw = font->head.wide * (strlen(hostname) + 2);
    bh = 2 * font->head.high;
    bx = (screen->wide - bw) / 2;
    by = screen->high / 6 - bh / 2;
    cutebox(bx, by, bw, bh);
    printstr(bx + font->head.wide, by + bh - font->head.high / 2, hostname);
  }
  /*}}}  */
  /*{{{  draw login box*/
  {
    int bx, bw, by, bh;

    bx = (screen->wide - font->head.wide * 40) / 2;
    by = (screen->high - font->head.high * 8) / 2;
    bw = font->head.wide * 40;
    bh = font->head.high * 8;
    cutebox(bx, by, bw, bh);
  }
  /*}}}  */
  /*{{{  draw login box contents*/
  x = (screen->wide - font->head.wide * 18) / 2;
  login_y = screen->high / 2 - font->head.wide / 6;
  password_y = screen->high / 2 + font->head.high / 6 + font->head.high;
  printstr(x, password_y, "Password:         "******"Press ESC for terminal login");
  /*}}}  */
  while (1) {
    /*{{{  get login and password or escape*/
    printstr(x, login_y, "Login:            "******"mgr", (char *)0 };
        int i;

        sprintf(env_user, "USER=%s", pw->pw_name);
        sprintf(env_logname, "LOGNAME=%s", pw->pw_name);
        sprintf(env_home, "HOME=%s", pw->pw_dir);
        sprintf(env_shell, "SHELL=%s", pw->pw_shell == (char *)0 || pw->pw_shell[0] == '\0' ? "/bin/sh" : pw->pw_shell);
        sprintf(env_path, "PATH=%s", PATH);
        sprintf(env_mail, "MAIL=%s/%s", MAILDIR, pw->pw_name);
        if (chdir(pw->pw_dir) != 0)
          chdir("/");
        if (ttyname(0)) {
          chown(ttyname(0), pw->pw_uid, pw->pw_gid);
          chmod(ttyname(0), 0600);
        }
        for (i = 1; i <= _NSIG; i++)
          signal(i, SIG_DFL);
        bit_destroy(screen);
        reset_tty(0);
        initgroups(pw->pw_name, pw->pw_gid);
        setgid(pw->pw_gid);
        setuid(pw->pw_uid);
        sprintf(mgrlogin, "%s/.mgrlogin", pw->pw_dir);
        execve(mgrlogin, login_argv, login_env);
        execve(MGR_BINARY, login_argv, login_env);
        exit(EX_OSFILE);
      }
      /*}}}  */
      else
      /*{{{  incorrect login*/
      {
        printstr((screen->wide - font->head.wide * 16) / 2, login_y + 3 * font->head.high,
            "Login incorrect");
      }
      /*}}}  */
    }
    /*}}}  */
  }
}
int main(int argc, const char * argv[])
{
    //expect 4 args : email, user name, plain password (10 to 20 chars), days. String controls have been made before calling this program.
    if (argc != 5) exit(EXIT_FAILURE);
    
    newUser_t *user;
    char *local;
    char *rsapriv;
    char rsapriv_key[33];
    size_t pwd_size;
    
    user = malloc(sizeof(newUser_t));
    user->email = strdup(argv[1]);
    user->name = strdup(argv[2]);
    user->days = strdup(argv[4]);

    
    //passphrase & aeskey
    pwd_size = strlen(argv[3]);
    if ( pwd_size < 10 || pwd_size > 20 ) {
        fprintf(stderr, "incorrect password length : %zu chars.", pwd_size);
        exit(EXIT_FAILURE);
    }
    user->passphrase = random_string(32);
    memcpy(rsapriv_key, argv[3], pwd_size);
    memcpy(rsapriv_key + pwd_size, user->passphrase + pwd_size, 32 - pwd_size);
    rsapriv_key[32] = '\0';
    
    libgcrypt_initialize();
    
    //rsa keys
    generate_rsa_keypair( &user->rsapub, &rsapriv);
    cipher_key(rsapriv, rsapriv_key, &user->rsapriv_crypt);
   
    //hash password
    char *settings;
    settings = crypt_gensalt_ra("$2a$", 7, random_string(16), 16);
    user->pwd = string_new();
    string_ajout(user->pwd, "{BLF-CRYPT}");
    string_ajout(user->pwd, crypt(argv[3], settings));

    //build maildir string
    user->maildir = string_new();
    string_ajout(user->maildir, "/");
    local = strtok(strdup(argv[1]), "@");
    string_ajout(user->maildir, strtok(NULL, "@"));
    string_ajout(user->maildir, "/");
    string_ajout(user->maildir, local);
    string_ajout(user->maildir, "/");
    
    //insert user in 2 tables : users & aliases
    if (pg_creer_utilisateur(user) != -1) {
        printf("OK 1/2 : Utilisateur ajouté dans la table users.\n");
        if (pg_creer_alias(user->email) != -1) {
            printf("OK 2/2 : Alias créé.\n");
         } else {
            fprintf(stderr, "Erreur lors de la création de l'alias.");
            exit(EXIT_FAILURE);
        }
    } else {
        fprintf(stderr, "Erreur lors de l'insertion de l'utilisateur dans la base users.");
        exit(EXIT_FAILURE);
    }
    
    exit(EXIT_SUCCESS);
}
Example #23
0
int main(int argc,char *argv[])
{
    char *username,*password,*encrypted,*p;
    struct passwd *pwd;
    struct spwd *spwd;
    Boolean authOK;
    size_t len;
    long lnmax;
    lnmax = sysconf(_SC_LOGIN_NAME_MAX);
    if (lnmax == -1)      /* If limit is indeterminate */
    {                    /* make a guess */
        lnmax =256;
    }

    username = malloc(lnmax);
    if (username == NULL)
    {
        errExit("malloc");
    }

    printf("Username: "******"couldn't get password record'");
    }

    spwd = getspnam(username);
    if (spwd == NULL && errno == EACCES)
    {
        fatal("no permission to read shadow password file");
    }

    if (spwd != NULL)   /* If there is a shadow password record */
    {                   /* Use the shadow password */
        pwd->pw_passwd = spwd->sp_pwdp;
    }

    password = getpass("Password: "******"crypt");
    }

    authOK = (strcmp(encrypted,pwd->pw_passwd) == 0);
    if (!authOK)
    {
        printf("Incorrect paswword\n");
        exit(EXIT_FAILURE);
    }

    printf("Successfully authenticated: UID=%ld\n",(long)pwd->pw_uid);
    
    exit(EXIT_SUCCESS);
    
}
    void Test2DVertexCryptRepresentativeSimulationForProfiling() throw (Exception)
    {
        // Set start time
        SimulationTime::Instance()->SetStartTime(0.0);

        // Create mesh
        unsigned crypt_width = 18;
        unsigned crypt_height = 25;
        CylindricalHoneycombVertexMeshGenerator generator(crypt_width, crypt_height, true);
        Cylindrical2dVertexMesh* p_mesh = generator.GetCylindricalMesh();

        // Make crypt shorter for sloughing
        double crypt_length = 20.0;

        // Create cells
        std::vector<CellPtr> cells;
        MAKE_PTR(WildTypeCellMutationState, p_state);
        MAKE_PTR(TransitCellProliferativeType, p_transit_type);
        for (unsigned elem_index=0; elem_index<p_mesh->GetNumElements(); elem_index++)
        {
            SimpleWntCellCycleModel* p_model = new SimpleWntCellCycleModel;
            p_model->SetDimension(2);

            double birth_time = - RandomNumberGenerator::Instance()->ranf()*
                                             ( p_model->GetTransitCellG1Duration()
                                                + p_model->GetSG2MDuration() );

            CellPtr p_cell(new Cell(p_state, p_model));
            p_cell->SetCellProliferativeType(p_transit_type);
            p_cell->SetBirthTime(birth_time);
            cells.push_back(p_cell);
        }

        // Create cell population
        VertexBasedCellPopulation<2> crypt(*p_mesh, cells);

        // Set up Wnt gradient
        WntConcentration<2>::Instance()->SetType(LINEAR);
        WntConcentration<2>::Instance()->SetCellPopulation(crypt);
        WntConcentration<2>::Instance()->SetCryptLength(crypt_length);

        // Create crypt simulation from cell population and force law
        CryptSimulation2d simulator(crypt);
        simulator.SetSamplingTimestepMultiple(50);
        simulator.SetEndTime(30.0);
        simulator.SetOutputDirectory("Test2DVertexCryptRepresentativeSimulationForProfiling");

        // Create a force law and pass it to the simulation
        MAKE_PTR(NagaiHondaForce<2>, p_nagai_honda_force);
        simulator.AddForce(p_nagai_honda_force);

        // ...and with that the target area modifier
        MAKE_PTR(SimpleTargetAreaModifier<2>, p_growth_modifier);
        simulator.AddSimulationModifier(p_growth_modifier);

        // Add a cell killer
        MAKE_PTR_ARGS(SloughingCellKiller<2>, p_killer, (&crypt, crypt_length));
        simulator.AddCellKiller(p_killer);

        // Run simulation
        simulator.Solve();

        // Tidy up
        WntConcentration<2>::Destroy();
    }
Example #25
0
static const char* hash_for_password(const char* password, const char* salt) {
  return crypt(password, salt);
}
Example #26
0
static int skcipher_crypt_blkcipher(struct skcipher_request *req,
				    int (*crypt)(struct blkcipher_desc *,
						 struct scatterlist *,
						 struct scatterlist *,
						 unsigned int))
{
	struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
	struct crypto_blkcipher **ctx = crypto_skcipher_ctx(tfm);
	struct blkcipher_desc desc = {
		.tfm = *ctx,
		.info = req->iv,
		.flags = req->base.flags,
	};


	return crypt(&desc, req->dst, req->src, req->cryptlen);
}

static int skcipher_encrypt_blkcipher(struct skcipher_request *req)
{
	struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
	struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
	struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;

	return skcipher_crypt_blkcipher(req, alg->encrypt);
}

static int skcipher_decrypt_blkcipher(struct skcipher_request *req)
{
	struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
	struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
	struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;

	return skcipher_crypt_blkcipher(req, alg->decrypt);
}

static void crypto_exit_skcipher_ops_blkcipher(struct crypto_tfm *tfm)
{
	struct crypto_blkcipher **ctx = crypto_tfm_ctx(tfm);

	crypto_free_blkcipher(*ctx);
}

static int crypto_init_skcipher_ops_blkcipher(struct crypto_tfm *tfm)
{
	struct crypto_alg *calg = tfm->__crt_alg;
	struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
	struct crypto_blkcipher **ctx = crypto_tfm_ctx(tfm);
	struct crypto_blkcipher *blkcipher;
	struct crypto_tfm *btfm;

	if (!crypto_mod_get(calg))
		return -EAGAIN;

	btfm = __crypto_alloc_tfm(calg, CRYPTO_ALG_TYPE_BLKCIPHER,
					CRYPTO_ALG_TYPE_MASK);
	if (IS_ERR(btfm)) {
		crypto_mod_put(calg);
		return PTR_ERR(btfm);
	}

	blkcipher = __crypto_blkcipher_cast(btfm);
	*ctx = blkcipher;
	tfm->exit = crypto_exit_skcipher_ops_blkcipher;

	skcipher->setkey = skcipher_setkey_blkcipher;
	skcipher->encrypt = skcipher_encrypt_blkcipher;
	skcipher->decrypt = skcipher_decrypt_blkcipher;

	skcipher->ivsize = crypto_blkcipher_ivsize(blkcipher);
	skcipher->has_setkey = calg->cra_blkcipher.max_keysize;

	return 0;
}

static int skcipher_setkey_ablkcipher(struct crypto_skcipher *tfm,
				      const u8 *key, unsigned int keylen)
{
	struct crypto_ablkcipher **ctx = crypto_skcipher_ctx(tfm);
	struct crypto_ablkcipher *ablkcipher = *ctx;
	int err;

	crypto_ablkcipher_clear_flags(ablkcipher, ~0);
	crypto_ablkcipher_set_flags(ablkcipher,
				    crypto_skcipher_get_flags(tfm) &
				    CRYPTO_TFM_REQ_MASK);
	err = crypto_ablkcipher_setkey(ablkcipher, key, keylen);
	crypto_skcipher_set_flags(tfm,
				  crypto_ablkcipher_get_flags(ablkcipher) &
				  CRYPTO_TFM_RES_MASK);

	return err;
}

static int skcipher_crypt_ablkcipher(struct skcipher_request *req,
				     int (*crypt)(struct ablkcipher_request *))
{
	struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
	struct crypto_ablkcipher **ctx = crypto_skcipher_ctx(tfm);
	struct ablkcipher_request *subreq = skcipher_request_ctx(req);

	ablkcipher_request_set_tfm(subreq, *ctx);
	ablkcipher_request_set_callback(subreq, skcipher_request_flags(req),
					req->base.complete, req->base.data);
	ablkcipher_request_set_crypt(subreq, req->src, req->dst, req->cryptlen,
				     req->iv);

	return crypt(subreq);
}

static int skcipher_encrypt_ablkcipher(struct skcipher_request *req)
{
	struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
	struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
	struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher;

	return skcipher_crypt_ablkcipher(req, alg->encrypt);
}

static int skcipher_decrypt_ablkcipher(struct skcipher_request *req)
{
	struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
	struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
	struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher;

	return skcipher_crypt_ablkcipher(req, alg->decrypt);
}

static void crypto_exit_skcipher_ops_ablkcipher(struct crypto_tfm *tfm)
{
	struct crypto_ablkcipher **ctx = crypto_tfm_ctx(tfm);

	crypto_free_ablkcipher(*ctx);
}

static int crypto_init_skcipher_ops_ablkcipher(struct crypto_tfm *tfm)
{
	struct crypto_alg *calg = tfm->__crt_alg;
	struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
	struct crypto_ablkcipher **ctx = crypto_tfm_ctx(tfm);
	struct crypto_ablkcipher *ablkcipher;
	struct crypto_tfm *abtfm;

	if (!crypto_mod_get(calg))
		return -EAGAIN;

	abtfm = __crypto_alloc_tfm(calg, 0, 0);
	if (IS_ERR(abtfm)) {
		crypto_mod_put(calg);
		return PTR_ERR(abtfm);
	}

	ablkcipher = __crypto_ablkcipher_cast(abtfm);
	*ctx = ablkcipher;
	tfm->exit = crypto_exit_skcipher_ops_ablkcipher;

	skcipher->setkey = skcipher_setkey_ablkcipher;
	skcipher->encrypt = skcipher_encrypt_ablkcipher;
	skcipher->decrypt = skcipher_decrypt_ablkcipher;

	skcipher->ivsize = crypto_ablkcipher_ivsize(ablkcipher);
	skcipher->reqsize = crypto_ablkcipher_reqsize(ablkcipher) +
			    sizeof(struct ablkcipher_request);
	skcipher->has_setkey = calg->cra_ablkcipher.max_keysize;

	return 0;
}

static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm)
{
	if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type)
		return crypto_init_skcipher_ops_blkcipher(tfm);

	BUG_ON(tfm->__crt_alg->cra_type != &crypto_ablkcipher_type &&
	       tfm->__crt_alg->cra_type != &crypto_givcipher_type);

	return crypto_init_skcipher_ops_ablkcipher(tfm);
}

static const struct crypto_type crypto_skcipher_type2 = {
	.extsize = crypto_skcipher_extsize,
	.init_tfm = crypto_skcipher_init_tfm,
	.maskclear = ~CRYPTO_ALG_TYPE_MASK,
	.maskset = CRYPTO_ALG_TYPE_BLKCIPHER_MASK,
	.type = CRYPTO_ALG_TYPE_BLKCIPHER,
	.tfmsize = offsetof(struct crypto_skcipher, base),
};

struct crypto_skcipher *crypto_alloc_skcipher(const char *alg_name,
					      u32 type, u32 mask)
{
	return crypto_alloc_tfm(alg_name, &crypto_skcipher_type2, type, mask);
}
EXPORT_SYMBOL_GPL(crypto_alloc_skcipher);

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Symmetric key cipher type");
Example #27
0
int main(int argc, char *argv[]) {
  
	int tap_fd, option;
	int flags = IFF_TUN;
	char if_name[IFNAMSIZ] = "";
	int header_len = IP_HDR_LEN;
	int maxfd;
	uint16_t nread, nwrite, plength;
	char buffer[BUFSIZE];
	struct sockaddr_in local, remote;
	char remote_ip[16] = "";
	unsigned short int port = PORT;
	int sock_fd, net_fd, optval = 1;
	socklen_t remotelen;
	int cliserv = -1;    /* must be specified on cmd line */
	unsigned long int tap2net = 0, net2tap = 0;

	int listen_sd;
  	int sd;
  	struct sockaddr_in sa_serv;
	struct sockaddr_in sa_cli;
	size_t client_len;
	int err;
	int yes = 1;

	struct ip *ip_header;            //ip header struct
	struct VPNDataHdr* vpn_header;

	int ptc[2];         //pipe from control process to tunnel process

	progname = argv[0];
  
  /* Check command line options */
  while((option = getopt(argc, argv, "i:sc:p:uahd")) > 0){
    switch(option) {
      case 'd':
        debug = 1;
        break;
      case 'h':
        usage();
        break;
      case 'i':
        strncpy(if_name,optarg,IFNAMSIZ-1);
        break;
      case 's':
        cliserv = SERVER;
        break;
      case 'c':
        cliserv = CLIENT;
        strncpy(remote_ip,optarg,15);
        break;
      case 'p':
        port = atoi(optarg);
        break;
      case 'u':
        flags = IFF_TUN;
        break;
      case 'a':
        flags = IFF_TAP;
        header_len = ETH_HDR_LEN;
        break;
      default:
        my_err("Unknown option %c\n", option);
        usage();
    }
  }

  argv += optind;
  argc -= optind;

  if(argc > 0){
    my_err("Too many options!\n");
    usage();
  }

  if(*if_name == '\0'){
    my_err("Must specify interface name!\n");
    usage();
  }else if(cliserv < 0){
    my_err("Must specify client or server mode!\n");
    usage();
  }else if((cliserv == CLIENT)&&(*remote_ip == '\0')){
    my_err("Must specify server address!\n");
    usage();
  }

  /* initialize tun/tap interface */
  if ( (tap_fd = tun_alloc(if_name, flags | IFF_NO_PI)) < 0 ) {
    my_err("Error connecting to tun/tap interface %s!\n", if_name);
    exit(1);
  }

  do_debug("Successfully connected to interface %s\n", if_name);
  




 
  	if ( (sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
    	 perror("socket()");
   	 exit(1);
 	 }

	/////////////////////////////////////////////////////////


    	memset(&local, 0, sizeof(local));
    	local.sin_family = AF_INET;
    	local.sin_addr.s_addr = htonl(INADDR_ANY);
    	local.sin_port = htons(port);
    	if (bind(sock_fd, (struct sockaddr*) &local, sizeof(local)) < 0){
      	perror("bind()");
      	exit(1);
    	}

	//init remote
	memset(&remote, 0, sizeof(remote));
	remote.sin_family = AF_INET;
	//remote.sin_addr.s_addr = inet_addr(remote_ip);
  	remote.sin_port = htons(port);	



	net_fd = sock_fd;

    	do_debug("SERVER: UDP built\n");
	//////////////////////////////////////////////////////////////////////

///////////ssl tcp control connection////////////////
	loadcert();
	listen_sd = socket (AF_INET, SOCK_STREAM, 0);   
	if(err < 0){
		printf("err tcp listening sock!\n");
		return 0;
	}
   
	if(setsockopt(listen_sd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1){
		perror("Server-socket() error lol!");
		exit(1);
	}  


	memset (&sa_serv, '\0', sizeof(sa_serv));
	sa_serv.sin_family      = AF_INET;
	sa_serv.sin_addr.s_addr = INADDR_ANY;
	sa_serv.sin_port        = htons (TCP_LISTEN_PORT);          /* Server Port number */
  
	err = bind(listen_sd, (struct sockaddr*) &sa_serv,
	sizeof (sa_serv));
	if(err < 0){
		printf("err tcp bind!\n");
		return 0;
	}
	     
  /* Receive a TCP connection. */
	     
	err = listen (listen_sd, 5);
	do_debug("Server start Listen OK\n");                    


	if(err < 0){
		printf("err tcp listening!\n");
		return 0;
	}
  /////

////////////////////////////////////////////////////

  
  /* use select() to handle two descriptors at once */
  maxfd = (tap_fd > net_fd)?tap_fd:net_fd;
  maxfd = (maxfd > listen_sd)?maxfd:listen_sd;

  while(1) {
    int ret;
    fd_set rd_set;

	struct Session *cursess;
	cursess= slisthead;

    FD_ZERO(&rd_set);
    FD_SET(tap_fd, &rd_set); FD_SET(net_fd, &rd_set);
	FD_SET(0, &rd_set);
	FD_SET(listen_sd,&rd_set);

	while(cursess != 0){
		FD_SET(cursess->sd,&rd_set);
		maxfd = (maxfd > cursess->sd)?maxfd:cursess->sd;
		cursess = cursess->next;
	}

	cursess = slisthead;

    ret = select(maxfd + 1, &rd_set, NULL, NULL, NULL);

    if (ret < 0 && errno == EINTR){
      continue;
    }

    if (ret < 0) {
      perror("select()");
      exit(1);
    }




	if(FD_ISSET(0, &rd_set)){
		memset(buffer,0,BUFSIZE);
		nread = read(0, buffer, BUFSIZE);
		if(0 == strncmp(buffer,"quit",strlen("quit")))
			break;

	}

	if(FD_ISSET(listen_sd, &rd_set)){
		client_len = sizeof(sa_cli);
		sd = accept (listen_sd, (struct sockaddr*) &sa_cli, &client_len);
		if(err < 0){
			printf("err accept!\n");
			return 0;
		}
		err = sslinit(sd, &slisthead, &sa_cli, "vpnauth");
		if(err)
			do_debug("Client from %s is connected\n", inet_ntoa(sa_cli.sin_addr));
		//continue;

	}


	if(FD_ISSET(tap_fd, &rd_set)){
      /* data from tun/tap: just read it and write it to the network */
		unsigned char outbuffer[VPN_BUFSIZE];
		struct VPNDataHdr *pvpnh = (struct VPNDataHdr*) outbuffer;
		unsigned long curip;
		cursess = 0;
		nread = cread(tap_fd, buffer, BUFSIZE);
		if(nread <= 0)
			continue;
		
		tap2net++;
		do_debug("TAP2NET %lu: Read %d bytes from the tap interface\n", tap2net, nread);

		ip_header = (struct ip*) buffer;
		memcpy(&curip,&(ip_header->ip_dst),sizeof(long));
		cursess = findsessByDstIP(slisthead,curip);
		//memcpy(&tpaddr,&(destsess->ip),sizeof(unsigned long));
		if(cursess == 0)
			continue;
		remote.sin_addr.s_addr = cursess->ip;
		

      /* write length + packet */

		if(32 != getHMACSHA256(buffer, pvpnh->hmac, nread,cursess->s_key,KEY_LENGTH))
			continue;
		nwrite = crypt(buffer,nread,outbuffer + sizeof(struct VPNDataHdr),cursess->s_key,cursess->iv,1);
		if(0 == nwrite)
			continue;
		pvpnh->plen = htons(nwrite);
		sendto(net_fd,outbuffer, nwrite + sizeof(struct VPNDataHdr),0,(struct sockaddr*) &remote, sizeof(remote));
	
		do_debug("TAP2NET %lu: Written %d bytes to the network %s\n", tap2net,nwrite,inet_ntoa(remote.sin_addr));
		//continue;
    }

    if(FD_ISSET(net_fd, &rd_set)){
      /* data from the network: read it, and write it to the tun/tap interface. 
       * We need to read the length first, and then the packet */
		unsigned char inbuffer[VPN_BUFSIZE];
		unsigned char hmac[32];
		int nwrite;
		struct VPNDataHdr *pvpnh = (struct VPNDataHdr*) inbuffer;
		struct sockaddr_in sa;
		socklen_t fromlen;
		fromlen =sizeof(sa);

		nread = recvfrom(net_fd,inbuffer,VPN_BUFSIZE,0,(struct sockaddr*)&sa,&fromlen);

		if(nread <= 0) {
	        continue;
	      }

		cursess = findsessByVPNHeader(slisthead,pvpnh,sa.sin_addr.s_addr);
		if(cursess == 0)
			continue;
			
		nwrite = crypt(inbuffer + sizeof(struct VPNDataHdr),htons(pvpnh->plen),buffer,cursess->s_key,cursess->iv,0);
		if(0 == nwrite)
			continue;
	
		if(32 != getHMACSHA256(buffer, hmac, nwrite,cursess->s_key,KEY_LENGTH) 
		|| !isequal(hmac,pvpnh->hmac,HMAC_LENGTH))
			continue;
		net2tap++;
		/* read packet */
		do_debug("NET2TAP %lu: Read %d bytes from the network\n", net2tap, nread);
		
		/* now buffer[] contains a full packet or frame, write it into the tun/tap interface */ 
		nwrite = cwrite(tap_fd, buffer, nwrite);
		do_debug("NET2TAP %lu: Written %d bytes to the tap interface\n", net2tap, nwrite);
		//continue;
    }

	cursess = slisthead;
	while(cursess != 0){
		if(FD_ISSET(cursess->sd, &rd_set)){
			struct CliRequest* rst;
			memset(buffer,0,BUFSIZE);
			nread = ssl_read(cursess->ssl,buffer,BUFSIZE);
			rst = (struct CliRequest*)buffer;
			if(nread != sizeof(struct CliRequest)){
				break;
			}
			if(nread == 0 || rst->act == QUIT_REQUEST){
				struct in_addr temp;
				temp.s_addr = cursess->ip;
				do_debug("Client from %s break the connection\n", inet_ntoa(temp));
				cleanupSSL(cursess);
				deletesess(&slisthead,cursess);
				//slisthead = 0;
			}

			if(rst->act == IV_REFRESH_REQUEST){
				RefreshIV(cursess);
				do_debug("IV is refreshed:");
				debugSession(cursess);
			}
			if(rst->act == IV_REFRESH_SET){
				struct ServResponse rsp;
				rsp.act = ACT_ACK;
				if(-1 != ssl_write(cursess->ssl,(char*)&rsp, sizeof(struct ServResponse))){
					memcpy(cursess->iv, rst->iv,KEY_LENGTH);
					do_debug("IV is updated:");
					debugSession(cursess);
				}
			}
			if(rst->act == KEY_REFRESH_REQUEST){
				RefreshKEY(cursess);
				do_debug("Key is refreshed:");
				debugSession(cursess);
			}
			if(rst->act == KEY_REFRESH_SET){
				struct ServResponse rsp;
				rsp.act = ACT_ACK;
				if(-1 != ssl_write(cursess->ssl,(char*)&rsp, sizeof(struct ServResponse))){
					memcpy(cursess->s_key, rst->s_key,KEY_LENGTH);
					do_debug("Key is updated:");
					debugSession(cursess);
				}
			}
			
		}
		cursess = cursess->next;
	}


	
  }

	if(slisthead != 0){
		struct Session* tsess = slisthead;
		while(tsess != 0){
			cleanupSSL(tsess);
			tsess = tsess->next;
		}
	}
	freesess(slisthead);
	close(listen_sd);
	close(net_fd);
	close(tap_fd);
	cleanupCTX();
  	
  return(0);
}
Example #28
0
int granted(const char* newgrpname, struct passwd** ppwd)
{
	uid_t	ruid;
	gid_t	newgrp;
	struct group  *grp;

	/*
	 * Initialization.
	 */
	*ppwd = getpwuid(ruid = getuid());

	/*
	 * The following are implementation defined security restrictions.
	 * If euid is not root then reject -- need a setuid-root exectuable.
 	 * If ruid is not root and not in /etc/passwd then reject.
	 */
	if (geteuid() || (ruid && (*ppwd == NULL))) {
		fprintf(stderr, "%s: Who are you?\n", PROGNAME);
		errno = EPERM;
		return -1;
	}

	/*
	 * No operands -- change back to /etc/passwd defaults.
	 */
	if (newgrpname == NULL) {
		/* change group(s) back to original "login fresh" values */
#if (NGROUPS_MAX > 1)
		initgroups((*ppwd)->pw_name, (*ppwd)->pw_gid);
#endif
		/* success */
		return (*ppwd)->pw_gid;
	}

	/*
	 * If given group name exists in /etc/group, then use it,
	 * else assume given group name is really the numeric group id.
	 */
	newgrp = -1;
	if ((grp = getgrnam(newgrpname)) == NULL) {
		char *temp;

		/* if a non-negative numeric group id was given, then use it */
		newgrp = (gid_t) strtol(newgrpname, &temp, 0);
		if ((newgrpname[0] == '\0') || (temp == NULL) ||
			(*temp != '\0') || (newgrp < 0) ||
			(((grp = getgrgid(newgrp)) == NULL) && ruid)) {
			fprintf(stderr, "%s: Unknown group %s\n", PROGNAME, newgrpname);
			errno = EINVAL;
			return -1;
		}
	}
	newgrp = (grp) ? grp->gr_gid : newgrp;

	/*
	 * If one of the following conditions are true, we can skip any
	 * additional security mechanisms:
	 *     - real user id is root
	 *     - new group id matches group id listed in /etc/passwd for user
	 */
	if ((ruid) && (newgrp != (*ppwd)->pw_gid)) {
		int rc;
		char **m, *temp;

		/* Check if the user listed as member of group */
		for (m = grp->gr_mem; *m && strcmp(*m, (*ppwd)->pw_name); m++);

		/* if not member, perform yet another security check */
		if (*m == NULL) {
			/* if no group passwd exists then reject */
			/* else prompt for passwd */
			if (grp->gr_passwd && (grp->gr_passwd[0] != '\0') &&
				(grp->gr_passwd[0] != '*')) {
				temp = getpass("Password:"******"%s: Sorry\n", PROGNAME);
#ifndef DONTUSESYSLOG
					syslog(LOG_AUTH|LOG_WARNING, "BAD NEWGRP by %s to %s%s",
						(*ppwd)->pw_name, newgrpname, ontty());
#endif
					errno = EPERM;
					return -1;
				}
			} else {
				fprintf(stderr, "%s: Sorry\n", PROGNAME);
				errno = EINVAL;
				return -1;
			}
		}
	}

#if (NGROUPS_MAX > 1) /* Does this system support supplemental groups */
	{	
		int gnum;
		gid_t glist[NGROUPS_MAX+1];
#ifdef FRUGAL
		int x;
#endif

		if ((gnum = getgroups(NGROUPS_MAX, glist)) != -1) {

#ifdef FRUGAL /* egid should not be in the sup. group list */
			/* if new gid is in list, remove it */
			for (x = 0; x < gnum; x++) {
				if (glist[x] == newgrp) {
					for (gnum--; x < gnum; x++) {
						glist[x] = glist[x+1];
					}
					break;
				}
			}

#else /* This system normally stores the egid in the sup. group list */

			/* if there is room, add new gid to list */
			gnum = addtolist(newgrp, gnum, &glist[0]);
#endif
			/* if there is room, add old gid to list */
			gnum = addtolist(getegid(), gnum, &glist[0]);

			setgroups(gnum, glist);
		}
	}
#endif

	/* success */
	return newgrp;
}
Example #29
0
int
pop_pass (POP *p)
{
    struct passwd  *pw;
    int i;
    int status;

    /* Make one string of all these parameters */

    for (i = 1; i < p->parm_count; ++i)
	p->pop_parm[i][strlen(p->pop_parm[i])] = ' ';

    /*  Look for the user in the password file */
    if ((pw = k_getpwnam(p->user)) == NULL)
	return (pop_msg(p,POP_FAILURE,
			"Password supplied for \"%s\" is incorrect.",
			p->user));

    if (p->kerberosp) {
#ifdef KRB5
	if (p->version == 5) {
	    char *name;

	    if (!krb5_kuserok (p->context, p->principal, p->user)) {
		pop_log (p, POP_PRIORITY,
			 "krb5 permission denied");
		return pop_msg(p, POP_FAILURE,
			       "Popping not authorized");
	    }
	    if(krb5_unparse_name (p->context, p->principal, &name) == 0) {
		pop_log(p, POP_INFO, "%s: %s -> %s",
			p->ipaddr, name, p->user);
		free (name);
	    }
	} else {
	    pop_log (p, POP_PRIORITY, "kerberos authentication failed");
	    return pop_msg (p, POP_FAILURE,
			    "kerberos authentication failed");
	}
#endif
	{ }
    } else {
	 /*  We don't accept connections from users with null passwords */
	 if (pw->pw_passwd == NULL)
	      return (pop_msg(p,
			      POP_FAILURE,
			      "Password supplied for \"%s\" is incorrect.",
			      p->user));

#ifdef OTP
	 if (otp_verify_user (&p->otp_ctx, p->pop_parm[1]) == 0)
	     /* pass OK */;
	 else
#endif
	 /*  Compare the supplied password with the password file entry */
	 if (p->auth_level != AUTH_NONE)
	     return pop_msg(p, POP_FAILURE,
			    "Password supplied for \"%s\" is incorrect.",
			    p->user);
	 else if (!strcmp(crypt(p->pop_parm[1], pw->pw_passwd), pw->pw_passwd))
	     /* pass OK */;
	 else {
	     int ret = -1;
#ifdef KRB5
	     if(ret)
		 ret = krb5_verify_password (p);
#endif
	     if(ret)
		 return pop_msg(p, POP_FAILURE,
				"Password incorrect");
	 }
    }
    status = login_user(p);
    if(status != POP_SUCCESS)
	return status;

    /*  Authorization completed successfully */
    return (pop_msg (p, POP_SUCCESS,
		     "%s has %d message(s) (%ld octets).",
		     p->user, p->msg_count, p->drop_size));
}
Example #30
0
Bool16 QTSSAuthorize(QTSS_StandardRTSP_Params* inParams, char* pathBuff)
{
    QTSS_Error theErr = QTSS_NoErr;
    Bool16 result = false;
    
    const int kBuffLen = 256;
    char passwordBuff[kBuffLen] = {};
    char nameBuff[kBuffLen] = {};
    StrPtrLen nameStr(nameBuff, kBuffLen -1); 
    StrPtrLen passwordStr(passwordBuff, kBuffLen -1); 
    Bool16  noUserName = false;
    Bool16  noPassword = false;
    Bool16  isSpecialGuest = false;
    
    do
    {

        theErr = QTSS_GetValue (inParams->inRTSPRequest,qtssRTSPReqUserName,0, (void *) nameStr.Ptr, &nameStr.Len);
        //qtss_printf("GetValue qtssRTSPReqUserName err =%"_S32BITARG_" \n",theErr);
        
        if ( (theErr != QTSS_NoErr) || (nameStr.Len == 0) || (nameStr.Ptr == NULL) || (*nameStr.Ptr == '\0'))
        {
            //qtss_printf ("no user name\n");
            noUserName = true;
        }
            
        //qtss_printf("RTSPRequest dictionary name =%s  len = %"_S32BITARG_"\n",nameStr.Ptr, nameStr.Len);

        theErr = QTSS_GetValue (inParams->inRTSPRequest,qtssRTSPReqUserPassword,0, (void *) passwordStr.Ptr, &passwordStr.Len);
        //qtss_printf("GetValue qtssRTSPReqUserName err =%"_S32BITARG_" \n",theErr);
        if ( (theErr != QTSS_NoErr) || (passwordStr.Len == 0) || (passwordStr.Ptr == NULL) || (*passwordStr.Ptr == '\0'))
        {
            //qtss_printf ("no Password\n");
            noPassword = true;
        }
        //qtss_printf("RTSPRequest dictionary password =%s len = %"_S32BITARG_" \n",passwordStr.Ptr, passwordStr.Len);

        if (noUserName && noPassword) isSpecialGuest = true;
        
        if (isSpecialGuest) // no name and no password means guest
        {
            //qtss_printf ("User is guest check for access\n");
            
            result = CheckWorldDirAccess(pathBuff);
            if (true == result)
                result = CheckWorldFileAccess(pathBuff);
            
            break; // no further processing on guest
        }
        
        if (0 == strcasecmp(nameStr.Ptr, sRootUserPtr) )
        {   //qtss_printf("user is root no root access to file =%s\n",pathBuff); // must log
            result = false; // don't allow
            break;
        }

        struct passwd   *passwdStructPtr = getpwnam(nameStr.Ptr);
        if (NULL == passwdStructPtr) 
        {   
            //qtss_printf("failed to find name =%s\n",passwordStr.Ptr);
            break;
        }
        
        char *theCryptedPassword = crypt(passwordStr.Ptr, passwdStructPtr->pw_passwd);
        if ( 0 != strcmp(passwdStructPtr->pw_passwd, theCryptedPassword ) )
        {   
            //qtss_printf("failed to match name to password =%s\n",passwordStr.Ptr);
            break;
        }
        
        result = CheckDirAccess(passwdStructPtr, &nameStr, pathBuff);
        if (!result) break;
        
        result = CheckFileAccess(passwdStructPtr, &nameStr, pathBuff);
        if (!result) break;

        //qtss_printf("QTSSAuthorize: user %s is authorized for %s\n",nameStr.Ptr,pathBuff);
        
        
    } while (false);
    
    if (!result) 
    {   //qtss_printf("QTSSAuthorize: user %s is un authorized for %s\n",nameStr.Ptr,pathBuff);
    }
    
    return result;
}