aboutsummaryrefslogtreecommitdiff
blob: 40729380be4da09f6788eca582b8d11bb093dd0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
#include <pwd.h> 
#include <netdb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <shadow.h>  

#ifndef MAXHOSTNAMELEN
# define MAXHOSTNAMELEN 256
#endif

#define PAM_SM_AUTH
#define PAM_SM_ACCOUNT
#define PAM_SM_PASSWORD
#define PAM_SM_SESSION



#define PASSWORD_HASH           "md5"
#define MAX_RETRIES 		3
#define DEFAULT_WARN            (2L * 7L * 86400L) /* two weeks */
#define SALTSIZE                32


#include <security/pam_modules.h>
#include <security/pam_appl.h>
#include <security/openpam.h>
#include <security/pam_mod_misc.h>


/*
 * Helper functions for internal use
 */

static int update_shadow( pam_handle_t * pamh , 
		const char * user , const char * newhashedpwd );
static int update_passwd( pam_handle_t * pamh ,
		const char * user ,const char * newhashedpwd ); 
static char * read_shadow(const char * user) ; 

static void to64(char *s, long v, int n); 
void makesalt(char salt[SALTSIZE]);

/*
 * User authentication
 */

PAM_EXTERN int
pam_sm_authenticate(pam_handle_t *pamh, int flags,
		int argc , const char *argv[] ) {
	struct passwd *pwd;
	const char *pass, *crypt_pass, *real_hash, *user;
	int pam_err;

	/* identify user */

	if (openpam_get_option(pamh, PAM_OPT_AUTH_AS_SELF)) {
		PAM_LOG("Authenticating as self.");
		pwd = getpwnam(getlogin());
	} else {
		if ((pam_err = pam_get_user(pamh, &user, NULL)) != PAM_SUCCESS) {
			PAM_ERROR("Authenticating with uname [%s] failed.", user);
	                return (pam_err);
		}

		pwd = getpwnam(user);
	}
	PAM_LOG("Authenticating user: [%s]", user);

	/* get password */

	if (pwd != NULL) {
		PAM_LOG("Doing real authentication");
		pass = pwd->pw_passwd; 
		if (pass[0] == '\0') {
			if (!(flags & PAM_DISALLOW_NULL_AUTHTOK) &&
					openpam_get_option(pamh, PAM_OPT_NULLOK)){
				PAM_LOG("User [%s] has empty password. \
						Authentication succesfull.", user);
				return (PAM_SUCCESS);
			}
		}			
		
		real_hash = "*";
		
	} else {
		PAM_LOG("Doing dummy authentication.");
		real_hash = "x";
	}

	pam_err = pam_get_authtok(pamh, PAM_AUTHTOK, (const char **) &pass, NULL);
	PAM_LOG("Got password for user [%s]", user);

        if (pam_err == PAM_CONV_ERR)
                return (pam_err);
	if (pam_err != PAM_SUCCESS)
	        return (PAM_AUTH_ERR);
	
	/* check passwd entry */

	if ( strncmp(real_hash, "x", sizeof(char)) != 0 ) {
		real_hash = read_shadow(user);
	}

	crypt_pass = crypt(pass,real_hash); 
	if ( strcmp(crypt_pass, real_hash) != 0 ) {
		PAM_ERROR("Wrong password. Authentication failed.");
		pam_err = PAM_AUTH_ERR;
	} else {
		PAM_LOG("Authentication completed succesfully.");
		pam_err = PAM_SUCCESS;
	}

	return (pam_err);
}

PAM_EXTERN int
pam_sm_setcred(pam_handle_t *pamh , int flags ,
		    int argc , const char *argv[] ) {
	
	/* 
	 * This functions takes care of renewing/initializing
	 * user credentials as well as gid/uids. Someday, it
	 * will be completed. For now, it's not very urgent. 
	 */

	return (PAM_SUCCESS);
}


/*
 * Account Management
 */

PAM_EXTERN int
pam_sm_acct_mgmt(pam_handle_t *pamh, int flags ,
		    int argc , const char *argv[] ) {

	struct spwd *pwd;
	int pam_err;
	const char *user;
	time_t curtime;
	
	/* Sanity checks for uname,pwd,tty,host etc */

	pam_err = pam_get_user(pamh, &user, NULL);

	if (pam_err != PAM_SUCCESS)
		return (pam_err);

	if (user == NULL || (pwd = getspnam(user)) == NULL)
		return (PAM_SERVICE_ERR);


	PAM_LOG("Got user [%s]" , user );
	
	if (*pwd->sp_pwdp == '\0' &&
         	(flags & PAM_DISALLOW_NULL_AUTHTOK) != 0)
		return (PAM_NEW_AUTHTOK_REQD);

	/* Calculate current time */
	curtime = time(NULL) / (60 * 60 * 24);
	
	/* Check for account expiration */
	if (pwd->sp_expire > 0) {
		 fprintf(stdout, "Account expiration data value is %ld\n", pwd->sp_expire);
		if ( (curtime > pwd->sp_expire ) && ( pwd->sp_expire != -1 ) ) {
			PAM_ERROR("Account has expired!");
			return (PAM_ACCT_EXPIRED);
		} else if ( ( pwd->sp_expire - curtime < DEFAULT_WARN) ) {
			PAM_ERROR("Warning: your account expires on %s",
					ctime(&pwd->sp_expire));
		}
	

		if (pwd->sp_lstchg == 0 ) {
			return (PAM_NEW_AUTHTOK_REQD);
		}

		/* check all other possibilities (mostly stolen from pam_tcb) */
	
		if ((curtime > (pwd->sp_lstchg + pwd->sp_max + pwd->sp_inact)) &&
				(pwd->sp_max != -1) && (pwd->sp_inact != -1) &&
				(pwd->sp_lstchg != 0)) {
			PAM_ERROR("Account has expired!");
			return (PAM_ACCT_EXPIRED);
		}
	
		if (((pwd->sp_lstchg + pwd->sp_max) < curtime) &&
			        (pwd->sp_max != -1)) {
			PAM_ERROR("Account has expired!");
			return (PAM_ACCT_EXPIRED);
		}

		if ((curtime - pwd->sp_lstchg > pwd->sp_max)
				&& (curtime - pwd->sp_lstchg > pwd->sp_inact)
				&& (curtime - pwd->sp_lstchg > pwd->sp_max + pwd->sp_inact)
				&& (pwd->sp_max != -1) && (pwd->sp_inact != -1)) {
			PAM_ERROR("Account has expired!");
			return (PAM_ACCT_EXPIRED);
		}

	}
	pam_err = (PAM_SUCCESS);

	return (pam_err);

}

/*
 * Password Management
 */

PAM_EXTERN int 
pam_sm_chauthtok(pam_handle_t *pamh, int flags,
		int argc, const char *argv[]) 
{

	/* 
	 * NIS support will be left for future implementation.
	 * This is standard unix passwd changing function. 
	 */
	struct passwd  *old_pwd;
        const char *user, *old_pass, *new_pass;
        char  *hashedpwd,  salt[SALTSIZE+1];

	int pam_err, retries;
	
	/* identify user */

	if (openpam_get_option(pamh, PAM_OPT_AUTH_AS_SELF)) {
		PAM_LOG("Authenticating as self.");
		user=getlogin();
		old_pwd = getpwnam(user);
	} else {
		if ((pam_err = pam_get_user(pamh, &user, NULL)) != PAM_SUCCESS) {
			PAM_ERROR("Authenticating with uname [%s] failed.", user);
	                return (pam_err);
		}

	        old_pwd = getpwnam(user);
	}
	
	PAM_LOG("Got user: [%s]", user);

	if (old_pwd == NULL) {
		PAM_ERROR("User [%s] either has a corrupted passwd entry or \
				is not in the selected database", user);
                return (PAM_AUTHTOK_RECOVERY_ERR);
	}

	/*
	 * When looking through the LinuxPAM code, I came across this : 
	 *
	 * ` Various libraries at various times have had bugs related to
	 * '+' or '-' as the first character of a user name. Don't
	 * allow them. `
	 *
	 * I don't know if the problem is still around but just in case... 
	 */

	if (user == NULL || user[0] == '-' || user[0] == '+' ) { 
		PAM_ERROR("Bad username [%s]", user);
		return (PAM_USER_UNKNOWN);
	}



	if (flags & PAM_PRELIM_CHECK) {
		PAM_LOG("Doing preliminary actions.");
		if (getuid() == 0 ) { 
			/* root doesn't need old passwd */
			return (pam_set_item(pamh, PAM_OLDAUTHTOK, ""));
		}

		if ( (old_pwd->pw_passwd[0] == '\0' ) &&
			( openpam_get_option(pamh, PAM_OPT_NULLOK) ) &&
			!(flags & PAM_DISALLOW_NULL_AUTHTOK) ) {		
			/*
			 * Something funny could happen here since we don't 
			 * ask for a password.
			 */
			old_pass = "";
		} else { 
			pam_err = pam_get_authtok(pamh,PAM_OLDAUTHTOK, 
					&old_pass, NULL);
			if (pam_err != PAM_SUCCESS ) 
				return (pam_err);

		} 
		
		PAM_LOG("Got old token for user [%s].",user);
		
		hashedpwd = crypt(old_pass, old_pwd->pw_passwd);
		
		if (old_pass[0] == '\0' && !openpam_get_option(pamh, PAM_OPT_NULLOK))
			return (PAM_PERM_DENIED);
		
		if (strcmp(hashedpwd, old_pwd->pw_passwd) != 0)
			return (PAM_PERM_DENIED);

	} else if ( flags & PAM_UPDATE_AUTHTOK ) {
		PAM_LOG("Doing actual update.");
		pam_err= pam_get_authtok(pamh, PAM_OLDAUTHTOK ,&old_pass, NULL);
                
		if (pam_err != PAM_SUCCESS)
			return (pam_err);
		
		PAM_LOG("Got old password");

		retries = 0;
		pam_err = PAM_AUTHTOK_ERR;

		while ((pam_err != PAM_SUCCESS) && ( retries++ <= MAX_RETRIES)) {
			
			pam_err = pam_get_authtok(pamh, PAM_AUTHTOK,
					&new_pass, NULL);

			PAM_ERROR("Unable to get new passwd. Please \
					 try again");

		}
		
		if (pam_err != PAM_SUCCESS) {
			PAM_ERROR("Unable to get new password!");
			return (pam_err);
		}

		PAM_LOG("Got new password");
		
		/* 
		 * checking has to be done (?) for the new passwd to 
		 * verify it's not weak. 
		 */
		
		if (getuid() != 0 && new_pass[0] == '\0' &&
				!openpam_get_option(pamh, PAM_OPT_NULLOK))
			return (PAM_PERM_DENIED);

		makesalt(salt);	
		/* Update shadow/passwd entries for Linux */
		pam_err = update_shadow( pamh ,user,crypt(new_pass, salt));
	 	if ( pam_err != PAM_SUCCESS) 
			return (pam_err);

		pam_err = update_passwd( pamh ,user,"x");
		update_passwd( pamh ,user,"x");
		if ( pam_err != PAM_SUCCESS) 
			return (pam_err);
	
		PAM_LOG("Password changed for user [%s]", user);
	} else {
		pam_err = PAM_ABORT;
		PAM_ERROR("Unrecognized flags.");
		return (pam_err);
	}
	
	return (PAM_SUCCESS);
}


PAM_EXTERN int
pam_sm_open_session( pam_handle_t * pamh, int flags, 
		int argc, const char * argv[]) 
{

	char *user, *service;
	int pam_err;

	pam_err = pam_get_item(pamh, PAM_USER, (void *) &user);
	if ( pam_err != PAM_SUCCESS || user == NULL || *user == '\0') {
		PAM_ERROR("Open session - Error recovering username");
		return (PAM_SESSION_ERR);
	}

	pam_err = pam_get_item(pamh, PAM_SERVICE, (void *) &service);
	if ( pam_err != PAM_SUCCESS || service == NULL || *service == '\0') { 
		PAM_ERROR("Open session - Error recovering service");
		return (PAM_SESSION_ERR);
	}

	PAM_LOG("Opened session for user [%s] by %s(uid=%lu)", user, getlogin(), 
			(unsigned long) getuid());

	return PAM_SUCCESS;

}

PAM_EXTERN int
pam_sm_close_session( pam_handle_t * pamh, int flags, 
		int argc, const char * argv[]) 
{
	char *user, *service;
	int pam_err;

	pam_err = pam_get_item(pamh, PAM_USER, (void *) &user);
	if ( pam_err != PAM_SUCCESS || user == NULL || *user == '\0') {
		PAM_ERROR("Close session - Error recovering username");
		return (PAM_SESSION_ERR);
	}

	pam_err = pam_get_item(pamh, PAM_SERVICE, (void *) &service);
	if ( pam_err != PAM_SUCCESS || service == NULL || *service == '\0') { 
		PAM_ERROR("Close session - Error recovering service");
		return (PAM_SESSION_ERR);
	}

	PAM_LOG("Closed session for user [%s]", user);

	return PAM_SUCCESS;
}

#define NEW_SHADOW "/etc/.shadow"
/*
 * Update shadow with new user password
 */

static int update_shadow( pam_handle_t * pamh , const char * user,
		const char * newhashedpwd ) {
	FILE *oldshadow, *newshadow;
	struct spwd *pwd,*cur_pwd;
	struct stat filestat;


	if ( (pwd = getspnam(user)) == NULL) 
		return PAM_USER_UNKNOWN;

	if ( (oldshadow = fopen ("/etc/shadow", "r")) == NULL ) {
		PAM_ERROR("Could not open /etc/shadow. Updating shadow \
				database cancelled.");
		return (PAM_AUTHTOK_ERR);
	}

	if ( (newshadow = fopen (NEW_SHADOW, "w")) == NULL ) { 
		PAM_ERROR("Could not open temp file. Updating shadow \
				database cancelled.");
		fclose(oldshadow);
		return (PAM_AUTHTOK_ERR);
	} 
	
	if (fstat(fileno(oldshadow), &filestat) == -1 ) {
		PAM_ERROR("Could not get stat for /etc/shadow. \
				Updating shadow database cancelled.");
		fclose(oldshadow);
		fclose(newshadow);
		unlink(NEW_SHADOW);
		return (PAM_AUTHTOK_ERR);
	}

	if (fchown(fileno(newshadow), filestat.st_uid, filestat.st_gid) == -1 ) { 
		PAM_ERROR("Could not set uid/gid for new shadwow file. \
				Updating shadow database cancelled.");
		fclose(oldshadow);
		fclose(newshadow);
		unlink(NEW_SHADOW);
		return (PAM_AUTHTOK_ERR);
	}

	if (fchmod(fileno(newshadow), filestat.st_mode) == -1 ) { 
		PAM_ERROR("Could not chmod for new shadow file. \
				Updating shadow database cancelled.");
		fclose(oldshadow);
		fclose(newshadow);
		unlink(NEW_SHADOW);
		return (PAM_AUTHTOK_ERR);
	}

	while ( (cur_pwd = fgetspent(oldshadow)) ) { 
		if( strlen(user) == strlen(cur_pwd->sp_namp) 
				&& !strncmp(cur_pwd->sp_namp, user, strlen(user))) {
			cur_pwd->sp_pwdp = newhashedpwd; 
			cur_pwd->sp_lstchg = time(NULL) / (60 * 60 * 24);
			PAM_LOG("Updated password for user [%s]",user);
		}

		if(putspent(cur_pwd, newshadow)) { 
			PAM_ERROR("Error writing entry to new shadow file. \
					Updating shadow database cancelled.");
			fclose(oldshadow);
			fclose(newshadow);
			unlink(NEW_SHADOW);
			return (PAM_AUTHTOK_ERR);
		}
	}
	
	fclose(oldshadow);

	if (fclose(newshadow)) {
		PAM_ERROR("Error updating new shadow file.");
		unlink(NEW_SHADOW);
		return (PAM_AUTHTOK_ERR);
	}

	/* 
	 * If program flow has come up to here, all is good
	 * and it's safe to update the shadow file.
	 */

	if( rename(NEW_SHADOW, "/etc/shadow") == 0 ) {
		PAM_LOG("Password updated successfully for user [%s]",user);
	} else {
		PAM_ERROR("Error updating shadow file.");
		unlink(NEW_SHADOW);
		return (PAM_AUTHTOK_ERR);
	}
	
	return (PAM_SUCCESS);

}

/*
 * Update /etc/passwd with new user information
 */

#define NEW_PASSWD "/etc/.passwd"

static int update_passwd( pam_handle_t * pamh, const char * user,
		const char * newhashedpwd ) {
	FILE *oldpasswd, *newpasswd;
	struct passwd *pwd,*cur_pwd;
	struct stat filestat;


	if ( (pwd = getpwnam(user)) == NULL) 
		return PAM_USER_UNKNOWN;

	if ( (oldpasswd = fopen ("/etc/passwd", "r")) == NULL ) {
		PAM_ERROR("Could not open /etc/passwd. Updating passwd \
				database cancelled.");
		return (PAM_AUTHTOK_ERR);
	}

	if ( (newpasswd = fopen (NEW_PASSWD, "w")) == NULL ) { 
		PAM_ERROR("Could not open temp file. Updating passwd \
				database cancelled.");
		fclose(oldpasswd);
		return (PAM_AUTHTOK_ERR);
	} 
	
	if (fstat(fileno(oldpasswd), &filestat) == -1 ) {
		PAM_ERROR("Could not get stat for /etc/passwd. \
				Updating passwd database cancelled.");
		fclose(oldpasswd);
		fclose(newpasswd);
		unlink(NEW_PASSWD);
		return (PAM_AUTHTOK_ERR);
	}

	if (fchown(fileno(newpasswd), filestat.st_uid, filestat.st_gid) == -1 ) { 
		PAM_ERROR("Could not set uid/gid for new shadwow file. \
				Updating passwd database cancelled.");
		fclose(oldpasswd);
		fclose(newpasswd);
		unlink(NEW_PASSWD);
		return (PAM_AUTHTOK_ERR);
	}

	if (fchmod(fileno(newpasswd), filestat.st_mode) == -1 ) { 
		PAM_ERROR("Could not chmod for new passwd file. \
				Updating passwd database cancelled.");
		fclose(oldpasswd);
		fclose(newpasswd);
		unlink(NEW_PASSWD);
		return (PAM_AUTHTOK_ERR);
	}

	while ( (cur_pwd = fgetpwent(oldpasswd)) ) { 
		if( strlen(user) == strlen(cur_pwd->pw_name) 
				&& !strncmp(cur_pwd->pw_name, user, strlen(user))) {
			cur_pwd->pw_passwd = newhashedpwd; 
			PAM_LOG("Updated password for user [%s]",user);
		}

		if(putpwent(cur_pwd, newpasswd)) { 
			PAM_ERROR("Error writing entry to new passwd file. \
					Updating passwd database cancelled.");
			fclose(oldpasswd);
			fclose(newpasswd);
			unlink(NEW_PASSWD);
			return (PAM_AUTHTOK_ERR);
		}
	}
	
	fclose(oldpasswd);

	if (fclose(newpasswd)) {
		PAM_ERROR("Error updating new passwd file.");
		unlink(NEW_PASSWD);
		return (PAM_AUTHTOK_ERR);
	}

	/* 
	 * If program flow has come up to here, all is good
	 * and it's safe to update the passwd file.
	 */

	if( rename(NEW_PASSWD, "/etc/passwd") == 0 ) {
		PAM_LOG("Password updated successfully for user [%s]",user);
	} else {
		PAM_ERROR("Error updating passwd file.");
		unlink(NEW_PASSWD);
		return (PAM_AUTHTOK_ERR);
	}
	
	return (PAM_SUCCESS);

}


/* 
 * Read hashed password for user from shadow entry.
 * This is for use on Linux machines only.
 */
static char * read_shadow(const char * user) { 

	struct spwd * pwd;
	/* 
	 * No error checking. Everything has been tested prior to 
	 * calling this function. Nothing can go wrong, right?
	 */
	pwd = getspnam(user);

	return (pwd->sp_pwdp);
}



/* 
 * Mostly stolen from freebsd-lib's pam_unix module which was mostly 
 * stolen from passwd(1)'s local_passwd.c
 *
 * Good ideas are meant to be reused ;)
 */

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

static void to64(char *s, long v, int n) {
	        while (--n >= 0) {
			*s++ = itoa64[v&0x3f];
			v >>= 6;
		}
}

/* Salt suitable for traditional DES and MD5 */
void
makesalt(char salt[SALTSIZE]) {
	        int i;
		/* These are not really random numbers, they are just
		 * numbers that change to thwart construction of a
		 * dictionary. This is exposed to the public.
		 */
		
		for (i = 0; i < SALTSIZE; i += 4)
			to64(&salt[i], random(), 4);

		salt[SALTSIZE] = '\0';
}
PAM_MODULE_ENTRY("pam_unix")