-
Notifications
You must be signed in to change notification settings - Fork 286
/
pam_google_authenticator.c
2212 lines (2010 loc) · 64.3 KB
/
pam_google_authenticator.c
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// PAM module for two-factor authentication.
//
// Copyright 2010 Google Inc.
// Author: Markus Gutschke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "config.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
#ifdef HAVE_SYS_FSUID_H
// We much rather prefer to use setfsuid(), but this function is unfortunately
// not available on all systems.
#include <sys/fsuid.h>
#endif
#ifndef PAM_EXTERN
#define PAM_EXTERN
#endif
#if !defined(LOG_AUTHPRIV) && defined(LOG_AUTH)
#define LOG_AUTHPRIV LOG_AUTH
#endif
#define PAM_SM_AUTH
#include <security/pam_appl.h>
#include <security/pam_modules.h>
#include "base32.h"
#include "hmac.h"
#include "sha1.h"
#include "util.h"
// Module name shortened to work with rsyslog.
// See https://github.com/google/google-authenticator-libpam/issues/172
#define MODULE_NAME "pam_google_auth"
#define SECRET "~/.google_authenticator"
#define CODE_PROMPT "Verification code: "
#define PWCODE_PROMPT "Password & verification code: "
typedef struct Params {
const char *secret_filename_spec;
const char *authtok_prompt;
enum { NULLERR=0, NULLOK, SECRETNOTFOUND } nullok;
int noskewadj;
int echocode;
int fixed_uid;
int no_increment_hotp;
uid_t uid;
enum { PROMPT = 0, TRY_FIRST_PASS, USE_FIRST_PASS } pass_mode;
int forward_pass;
int debug;
int no_strict_owner;
int allowed_perm;
time_t grace_period;
int allow_readonly;
} Params;
static char oom;
static const char* nobody = "nobody";
#if defined(DEMO) || defined(TESTING)
static char* error_msg = NULL;
const char *get_error_msg(void) __attribute__((visibility("default")));
const char *get_error_msg(void) {
if (!error_msg) {
return "";
}
return error_msg;
}
#endif
static void log_message(int priority, pam_handle_t *pamh,
const char *format, ...) {
char *service = NULL;
if (pamh)
pam_get_item(pamh, PAM_SERVICE, (void *)&service);
if (!service)
service = "";
char logname[80];
snprintf(logname, sizeof(logname), "%s(" MODULE_NAME ")", service);
va_list args;
va_start(args, format);
#if !defined(DEMO) && !defined(TESTING)
openlog(logname, LOG_CONS | LOG_PID, LOG_AUTHPRIV);
vsyslog(priority, format, args);
closelog();
#else
if (!error_msg) {
error_msg = strdup("");
}
{
char buf[1000];
vsnprintf(buf, sizeof buf, format, args);
const int newlen = strlen(error_msg) + 1 + strlen(buf) + 1;
char* n = malloc(newlen);
if (n) {
snprintf(n, newlen, "%s%s%s", error_msg, strlen(error_msg)?"\n":"",buf);
free(error_msg);
error_msg = n;
} else {
fprintf(stderr, "Failed to malloc %d bytes for log data.\n", newlen);
}
}
#endif
va_end(args);
if (priority == LOG_EMERG) {
// Something really bad happened. There is no way we can proceed safely.
_exit(1);
}
}
static int converse(pam_handle_t *pamh, int nargs,
PAM_CONST struct pam_message **message,
struct pam_response **response) {
struct pam_conv *conv;
int retval = pam_get_item(pamh, PAM_CONV, (void *)&conv);
if (retval != PAM_SUCCESS) {
return retval;
}
return conv->conv(nargs, message, response, conv->appdata_ptr);
}
static const char *get_user_name(pam_handle_t *pamh, const Params *params) {
// Obtain the user's name
const char *username;
if (pam_get_user(pamh, &username, NULL) != PAM_SUCCESS ||
!username || !*username) {
log_message(LOG_ERR, pamh,
"pam_get_user() failed to get a user name"
" when checking verification code");
return NULL;
}
if (params->debug) {
log_message(LOG_INFO, pamh, "debug: start of google_authenticator for \"%s\"", username);
}
return username;
}
/*
* Return rhost as a string. Return value must not be free()ed.
* Returns NULL if PAM_RHOST is not known.
*/
static const char *
get_rhost(pam_handle_t *pamh, const Params *params) {
// Get the remote host
PAM_CONST void *rhost;
if (pam_get_item(pamh, PAM_RHOST, &rhost) != PAM_SUCCESS) {
log_message(LOG_ERR, pamh, "pam_get_rhost() failed to get the remote host");
return NULL;
}
if (params->debug) {
log_message(LOG_INFO, pamh, "debug: google_authenticator for host \"%s\"",
rhost);
}
return (const char *)rhost;
}
static size_t
getpwnam_buf_max_size()
{
#ifdef _SC_GETPW_R_SIZE_MAX
const ssize_t len = sysconf(_SC_GETPW_R_SIZE_MAX);
if (len <= 0) {
return 4096;
}
return len;
#else
return 4096;
#endif
}
static char *get_secret_filename(pam_handle_t *pamh, const Params *params,
const char *username, uid_t *uid) {
if (!username) {
return NULL;
}
// Check whether the administrator decided to override the default location
// for the secret file.
const char *spec = params->secret_filename_spec
? params->secret_filename_spec : SECRET;
// Obtain the user's id and home directory
// NOTE: These variables need to be here because of their lifetimes.
struct passwd *pw = NULL; // Used
struct passwd pwbuf; // Here because `pw` points into it.
char *buf = NULL; // Here because `pw` members use it.
char *secret_filename = NULL; // Here because goto jumps.
if (!params->fixed_uid) {
const int len = getpwnam_buf_max_size();
buf = malloc(len);
*uid = -1;
if (buf == NULL) {
log_message(LOG_ERR, pamh, "Short (%d) mem allocation failed", len);
goto errout;
}
const int rc = getpwnam_r(username, &pwbuf, buf, len, &pw);
if (rc) {
log_message(LOG_ERR, pamh, "getpwnam_r(\"%s\")!=0: %d", username, rc);
goto errout;
}
if (!pw) {
log_message(LOG_ERR, pamh, "user(\"%s\") not found", username);
goto errout;
}
if (!pw->pw_dir) {
log_message(LOG_ERR, pamh, "user(\"%s\") has no home dir", username);
goto errout;
}
if (*pw->pw_dir != '/') {
log_message(LOG_ERR, pamh, "User \"%s\" home dir not absolute", username);
goto errout;
}
}
// Expand filename specification to an actual filename.
if ((secret_filename = strdup(spec)) == NULL) {
log_message(LOG_ERR, pamh, "Short (%d) mem allocation failed", strlen(spec));
goto errout;
}
int allow_tilde = 1;
for (int offset = 0; secret_filename[offset];) {
char *cur = secret_filename + offset;
char *var = NULL;
size_t var_len = 0;
const char *subst = NULL;
if (allow_tilde && *cur == '~') {
var_len = 1;
if (!pw) {
log_message(LOG_ERR, pamh,
"Home dir in 'secret' not implemented when 'user' set");
goto errout;
}
subst = pw->pw_dir;
var = cur;
} else if (secret_filename[offset] == '$') {
if (!memcmp(cur, "${HOME}", 7)) {
var_len = 7;
if (!pw) {
log_message(LOG_ERR, pamh,
"Home dir in 'secret' not implemented when 'user' set");
goto errout;
}
subst = pw->pw_dir;
var = cur;
} else if (!memcmp(cur, "${USER}", 7)) {
var_len = 7;
subst = username;
var = cur;
}
}
if (var) {
const size_t subst_len = strlen(subst);
if (subst_len > 1000000) {
log_message(LOG_ERR, pamh, "Unexpectedly large path name: %d", subst_len);
goto errout;
}
const int varidx = var - secret_filename;
char *resized = realloc(secret_filename,
strlen(secret_filename) + subst_len + 1);
if (!resized) {
log_message(LOG_ERR, pamh, "Short mem allocation failed");
goto errout;
}
var = resized + varidx;
secret_filename = resized;
memmove(var + subst_len, var + var_len, strlen(var + var_len) + 1);
memmove(var, subst, subst_len);
offset = var + subst_len - resized;
allow_tilde = 0;
} else {
allow_tilde = *cur == '/';
++offset;
}
}
*uid = params->fixed_uid ? params->uid : pw->pw_uid;
free(buf);
return secret_filename;
errout:
free(secret_filename);
free(buf);
return NULL;
}
static int setuser(int uid) {
#ifdef HAVE_SETFSUID
// The semantics for setfsuid() are a little unusual. On success, the
// previous user id is returned. On failure, the current user id is returned.
int old_uid = setfsuid(uid);
if (uid != setfsuid(uid)) {
setfsuid(old_uid);
return -1;
}
#else
#ifdef linux
#error "Linux should have setfsuid(). Refusing to build."
#endif
int old_uid = geteuid();
if (old_uid != uid && seteuid(uid)) {
return -1;
}
#endif
return old_uid;
}
static int setgroup(int gid) {
#ifdef HAVE_SETFSGID
// The semantics of setfsgid() are a little unusual. On success, the
// previous group id is returned. On failure, the current groupd id is
// returned.
int old_gid = setfsgid(gid);
if (gid != setfsgid(gid)) {
setfsgid(old_gid);
return -1;
}
#else
int old_gid = getegid();
if (old_gid != gid && setegid(gid)) {
return -1;
}
#endif
return old_gid;
}
// Drop privileges and return 0 on success.
static int drop_privileges(pam_handle_t *pamh, const char *username, int uid,
int *old_uid, int *old_gid) {
// Try to become the new user. This might be necessary for NFS mounted home
// directories.
// First, look up the user's default group
#ifdef _SC_GETPW_R_SIZE_MAX
int len = sysconf(_SC_GETPW_R_SIZE_MAX);
if (len <= 0) {
len = 4096;
}
#else
int len = 4096;
#endif
char *buf = malloc(len);
if (!buf) {
log_message(LOG_ERR, pamh, "Out of memory");
return -1;
}
struct passwd pwbuf, *pw;
if (getpwuid_r(uid, &pwbuf, buf, len, &pw) || !pw) {
log_message(LOG_ERR, pamh, "Cannot look up user id %d", uid);
free(buf);
return -1;
}
gid_t gid = pw->pw_gid;
free(buf);
int gid_o = setgroup(gid);
int uid_o = setuser(uid);
if (uid_o < 0) {
if (gid_o >= 0) {
if (setgroup(gid_o) < 0 || setgroup(gid_o) != gid_o) {
// Inform the caller that we were unsuccessful in resetting the group.
*old_gid = gid_o;
}
}
log_message(LOG_ERR, pamh, "Failed to change user id to \"%s\"",
username);
return -1;
}
if (gid_o < 0 && (gid_o = setgroup(gid)) < 0) {
// In most typical use cases, the PAM module will end up being called
// while uid=0. This allows the module to change to an arbitrary group
// prior to changing the uid. But there are many ways that PAM modules
// can be invoked and in some scenarios this might not work. So, we also
// try changing the group _after_ changing the uid. It might just work.
if (setuser(uid_o) < 0 || setuser(uid_o) != uid_o) {
// Inform the caller that we were unsuccessful in resetting the uid.
*old_uid = uid_o;
}
log_message(LOG_ERR, pamh,
"Failed to change group id for user \"%s\" to %d", username,
(int)gid);
return -1;
}
*old_uid = uid_o;
*old_gid = gid_o;
return 0;
}
// open secret file, return fd on success, or <0 on error.
static int open_secret_file(pam_handle_t *pamh, const char *secret_filename,
struct Params *params, const char *username,
int uid, struct stat *orig_stat) {
// Try to open "~/.google_authenticator"
const int fd = open(secret_filename, O_RDONLY);
if (fd < 0 ||
fstat(fd, orig_stat) < 0) {
if (params->nullok != NULLERR && errno == ENOENT) {
// The user doesn't have a state file, but the administrator said
// that this is OK. We still return an error from open_secret_file(),
// but we remember that this was the result of a missing state file.
params->nullok = SECRETNOTFOUND;
} else {
log_message(LOG_ERR, pamh, "Failed to read \"%s\" for \"%s\": %s",
secret_filename, username, strerror(errno));
}
error:
if (fd >= 0) {
close(fd);
}
return -1;
}
if (params->debug) {
log_message(LOG_INFO, pamh,
"debug: Secret file permissions are %04o."
" Allowed permissions are %04o",
orig_stat->st_mode & 03777, params->allowed_perm);
}
// Check permissions on "~/.google_authenticator".
if (!S_ISREG(orig_stat->st_mode)) {
log_message(LOG_ERR, pamh, "Secret file \"%s\" is not a regular file",
secret_filename);
goto error;
}
if (orig_stat->st_mode & 03777 & ~params->allowed_perm) {
log_message(LOG_ERR, pamh,
"Secret file \"%s\" permissions (%04o)"
" are more permissive than %04o", secret_filename,
orig_stat->st_mode & 03777, params->allowed_perm);
goto error;
}
if (!params->no_strict_owner && (orig_stat->st_uid != (uid_t)uid)) {
char buf[80];
if (params->fixed_uid) {
snprintf(buf, sizeof buf, "user id %d", params->uid);
username = buf;
}
log_message(LOG_ERR, pamh,
"Secret file \"%s\" must be owned by \"%s\"",
secret_filename, username);
goto error;
}
// Sanity check for file length
if (orig_stat->st_size < 1 || orig_stat->st_size > 64*1024) {
log_message(LOG_ERR, pamh,
"Invalid file size for \"%s\"", secret_filename);
goto error;
}
return fd;
}
// Read secret file contents.
// If there's an error the file is closed, NULL is returned, and errno set.
static char *read_file_contents(pam_handle_t *pamh,
const Params *params,
const char *secret_filename, int *fd,
off_t filesize) {
// Arbitrary limit to prevent integer overflow.
if (filesize > 1000000) {
close(*fd);
errno = E2BIG;
return NULL;
}
// Read file contents
char *buf = malloc(filesize + 1);
if (!buf) {
log_message(LOG_ERR, pamh, "Failed to malloc %d+1", filesize);
goto out;
}
if (filesize != read(*fd, buf, filesize)) {
log_message(LOG_ERR, pamh, "Could not read \"%s\"", secret_filename);
goto out;
}
close(*fd);
*fd = -1;
// The rest of the code assumes that there are no NUL bytes in the file.
if (memchr(buf, 0, filesize)) {
log_message(LOG_ERR, pamh, "Invalid file contents in \"%s\"",
secret_filename);
goto out;
}
// Terminate the buffer with a NUL byte.
buf[filesize] = '\000';
if(params->debug) {
log_message(LOG_INFO, pamh, "debug: \"%s\" read", secret_filename);
}
return buf;
out:
// If we have any data, erase it.
if (buf) {
explicit_bzero(buf, filesize);
}
free(buf);
if (*fd >= 0) {
close(*fd);
*fd = -1;
}
return NULL;
}
static int is_totp(const char *buf) {
return !!strstr(buf, "\" TOTP_AUTH");
}
// Wrap write() making sure that partial writes don't break everything.
// Return 0 on success, errno otherwise.
static int
full_write(int fd, const char* buf, size_t len) {
const char* p = buf;
int errors = 0;
for (;;) {
const ssize_t left = len - (p - buf);
const ssize_t rc = write(fd, p, left);
if (rc == left) {
return 0;
}
if (rc < 0) {
switch (errno) {
case EAGAIN:
case EINTR:
if (errors++ < 3) {
continue;
}
}
return errno;
}
p += rc;
}
}
// Safely overwrite the old secret file.
// Return 0 on success, errno otherwise.
static int write_file_contents(pam_handle_t *pamh,
const Params *params,
const char *secret_filename,
struct stat *orig_stat,
const char *buf) {
int err = 0;
int fd = -1;
const size_t fnlength = strlen(secret_filename) + 1 + 6 + 1;
char *tmp_filename = malloc(fnlength);
if (tmp_filename == NULL) {
err = errno;
goto cleanup;
}
if (fnlength - 1 != snprintf(tmp_filename, fnlength,
"%s~XXXXXX", secret_filename)) {
err = ERANGE;
goto cleanup;
}
const mode_t old_mask = umask(077);
fd = mkstemp(tmp_filename);
umask(old_mask);
if (fd < 0) {
err = errno;
log_message(LOG_ERR, pamh, "Failed to create tempfile \"%s\": %s",
tmp_filename, strerror(err));
// Couldn't open file; don't try to delete it later.
free(tmp_filename);
tmp_filename = NULL;
goto cleanup;
}
if (fchmod(fd, 0400)) {
err = errno;
goto cleanup;
}
// Make sure the secret file is still the same. This prevents attackers
// from opening a lot of pending sessions and then reusing the same
// scratch code multiple times.
//
// (except for the brief race condition between this stat and the
// `rename` below)
{
struct stat sb;
if (stat(secret_filename, &sb) != 0) {
err = errno;
log_message(LOG_ERR, pamh, "stat(): %s", strerror(err));
goto cleanup;
}
if (sb.st_ino != orig_stat->st_ino ||
sb.st_size != orig_stat->st_size ||
sb.st_mtime != orig_stat->st_mtime) {
err = EAGAIN;
log_message(LOG_ERR, pamh,
"Secret file \"%s\" changed while trying to use "
"scratch code\n", secret_filename);
goto cleanup;
}
}
// Write the new file contents.
if ((err = full_write(fd, buf, strlen(buf)))) {
log_message(LOG_ERR, pamh, "write(): %s", strerror(err));
goto cleanup;
}
if (fsync(fd)) {
err = errno;
log_message(LOG_ERR, pamh, "fsync(): %s", strerror(err));
goto cleanup;
}
if (close(fd)) {
err = errno;
log_message(LOG_ERR, pamh, "close(): %s", strerror(err));
goto cleanup;
}
fd = -1; // Prevent double-close.
// Double-check that the file size is correct.
{
struct stat st;
if (stat(tmp_filename, &st)) {
err = errno;
log_message(LOG_ERR, pamh, "stat(%s): %s", tmp_filename, strerror(err));
goto cleanup;
}
const off_t want = strlen(buf);
if (st.st_size == 0 || (want != st.st_size)) {
err = EAGAIN;
log_message(LOG_ERR, pamh, "temp file size %d. Should be non-zero and %d", st.st_size, want);
goto cleanup;
}
}
if (rename(tmp_filename, secret_filename) != 0) {
err = errno;
log_message(LOG_ERR, pamh, "rename(): %s", strerror(err));
goto cleanup;
}
free(tmp_filename);
tmp_filename = NULL; // Prevent unlink & double-free.
if (params->debug) {
log_message(LOG_INFO, pamh, "debug: \"%s\" written", secret_filename);
}
cleanup:
if (fd >= 0) {
close(fd);
}
if (tmp_filename) {
if (unlink(tmp_filename)) {
log_message(LOG_ERR, pamh, "Failed to delete tempfile \"%s\": %s",
tmp_filename, strerror(errno));
}
}
free(tmp_filename);
if (err) {
log_message(LOG_ERR, pamh, "Failed to update secret file \"%s\": %s",
secret_filename, strerror(err));
return err;
}
return 0;
}
// given secret file content (buf), extract the secret and base32 decode it.
//
// Return pointer to `malloc()`'d secret on success (caller frees),
// NULL on error. Length of secret stored in *secretLen.
static uint8_t *get_shared_secret(pam_handle_t *pamh,
const Params *params,
const char *secret_filename,
const char *buf, int *secretLen) {
if (!buf) {
return NULL;
}
// Decode secret key
const int base32Len = strcspn(buf, "\n");
// Arbitrary limit to prevent integer overflow.
if (base32Len > 100000) {
return NULL;
}
*secretLen = (base32Len*5 + 7)/8;
uint8_t *secret = malloc(base32Len + 1);
if (secret == NULL) {
*secretLen = 0;
return NULL;
}
memcpy(secret, buf, base32Len);
secret[base32Len] = '\000';
if ((*secretLen = base32_decode(secret, secret, base32Len)) < 1) {
log_message(LOG_ERR, pamh,
"Could not find a valid BASE32 encoded secret in \"%s\"",
secret_filename);
explicit_bzero(secret, base32Len);
free(secret);
return NULL;
}
memset(secret + *secretLen, 0, base32Len + 1 - *secretLen);
if(params->debug) {
log_message(LOG_INFO, pamh, "debug: shared secret in \"%s\" processed", secret_filename);
}
return secret;
}
#ifdef TESTING
static time_t current_time;
void set_time(time_t t) __attribute__((visibility("default")));
void set_time(time_t t) {
current_time = t;
}
static time_t get_time(void) {
return current_time;
}
#else
static time_t get_time(void) {
return time(NULL);
}
#endif
static int comparator(const void *a, const void *b) {
return *(unsigned int *)a - *(unsigned int *)b;
}
static char *get_cfg_value(pam_handle_t *pamh, const char *key,
const char *buf) {
const size_t key_len = strlen(key);
for (const char *line = buf; *line; ) {
const char *ptr;
if (line[0] == '"' && line[1] == ' ' && !strncmp(line+2, key, key_len) &&
(!*(ptr = line+2+key_len) || *ptr == ' ' || *ptr == '\t' ||
*ptr == '\r' || *ptr == '\n')) {
ptr += strspn(ptr, " \t");
size_t val_len = strcspn(ptr, "\r\n");
char *val = malloc(val_len + 1);
if (!val) {
log_message(LOG_ERR, pamh, "Out of memory");
return &oom;
} else {
memcpy(val, ptr, val_len);
val[val_len] = '\000';
return val;
}
} else {
line += strcspn(line, "\r\n");
line += strspn(line, "\r\n");
}
}
return NULL;
}
static int set_cfg_value(pam_handle_t *pamh, const char *key, const char *val,
char **buf) {
const size_t key_len = strlen(key);
char *start = NULL;
char *stop = NULL;
// Find an existing line, if any.
for (char *line = *buf; *line; ) {
char *ptr;
if (line[0] == '"' && line[1] == ' ' && !strncmp(line+2, key, key_len) &&
(!*(ptr = line+2+key_len) || *ptr == ' ' || *ptr == '\t' ||
*ptr == '\r' || *ptr == '\n')) {
start = line;
stop = start + strcspn(start, "\r\n");
stop += strspn(stop, "\r\n");
break;
} else {
line += strcspn(line, "\r\n");
line += strspn(line, "\r\n");
}
}
// If no existing line, insert immediately after the first line.
if (!start) {
start = *buf + strcspn(*buf, "\r\n");
start += strspn(start, "\r\n");
stop = start;
}
// Replace [start..stop] with the new contents.
const size_t val_len = strlen(val);
const size_t total_len = key_len + val_len + 4;
if (total_len <= stop - start) {
// We are decreasing out space requirements. Shrink the buffer and pad with
// NUL characters.
const size_t tail_len = strlen(stop);
memmove(start + total_len, stop, tail_len + 1);
memset(start + total_len + tail_len, 0, stop - start - total_len + 1);
} else {
// Must resize existing buffer. We cannot call realloc(), as it could
// leave parts of the buffer content in unused parts of the heap.
const size_t buf_len = strlen(*buf);
const size_t tail_len = buf_len - (stop - *buf);
char *resized = malloc(buf_len - (stop - start) + total_len + 1);
if (!resized) {
log_message(LOG_ERR, pamh, "Out of memory");
return -1;
}
memcpy(resized, *buf, start - *buf);
memcpy(resized + (start - *buf) + total_len, stop, tail_len + 1);
memset(*buf, 0, buf_len);
free(*buf);
start = start - *buf + resized;
*buf = resized;
}
// Fill in new contents.
start[0] = '"';
start[1] = ' ';
memcpy(start + 2, key, key_len);
start[2+key_len] = ' ';
memcpy(start+3+key_len, val, val_len);
start[3+key_len+val_len] = '\n';
// Check if there are any other occurrences of "value". If so, delete them.
for (char *line = start + 4 + key_len + val_len; *line; ) {
char *ptr;
if (line[0] == '"' && line[1] == ' ' && !strncmp(line+2, key, key_len) &&
(!*(ptr = line+2+key_len) || *ptr == ' ' || *ptr == '\t' ||
*ptr == '\r' || *ptr == '\n')) {
start = line;
stop = start + strcspn(start, "\r\n");
stop += strspn(stop, "\r\n");
size_t tail_len = strlen(stop);
memmove(start, stop, tail_len + 1);
memset(start + tail_len, 0, stop - start);
line = start;
} else {
line += strcspn(line, "\r\n");
line += strspn(line, "\r\n");
}
}
return 0;
}
static int step_size(pam_handle_t *pamh, const char *secret_filename,
const char *buf) {
const char *value = get_cfg_value(pamh, "STEP_SIZE", buf);
if (!value) {
// Default step size is 30.
return 30;
} else if (value == &oom) {
// Out of memory. This is a fatal error.
return 0;
}
char *endptr;
errno = 0;
const int step = (int)strtoul(value, &endptr, 10);
if (errno || !*value || value == endptr ||
(*endptr && *endptr != ' ' && *endptr != '\t' &&
*endptr != '\n' && *endptr != '\r') ||
step < 1 || step > 60) {
free((void *)value);
log_message(LOG_ERR, pamh, "Invalid STEP_SIZE option in \"%s\"",
secret_filename);
return 0;
}
free((void *)value);
return step;
}
static int get_timestamp(pam_handle_t *pamh, const char *secret_filename,
const char **buf) {
const int step = step_size(pamh, secret_filename, *buf);
if (!step) {
return 0;
}
return get_time()/step;
}
static long get_hotp_counter(pam_handle_t *pamh, const char *buf) {
if (!buf) {
return -1;
}
const char *counter_str = get_cfg_value(pamh, "HOTP_COUNTER", buf);
if (counter_str == &oom) {
// Out of memory. This is a fatal error
return -1;
}
long counter = 0;
if (counter_str) {
counter = strtol(counter_str, NULL, 10);
}
free((void *)counter_str);
return counter;
}
static int rate_limit(pam_handle_t *pamh, const char *secret_filename,
int *updated, char **buf) {
const char *value = get_cfg_value(pamh, "RATE_LIMIT", *buf);
if (!value) {
// Rate limiting is not enabled for this account
return 0;
} else if (value == &oom) {
// Out of memory. This is a fatal error.
return -1;
}
// Parse both the maximum number of login attempts and the time interval
// that we are looking at.
const char *endptr = value, *ptr;
int attempts, interval;
errno = 0;
if (((attempts = (int)strtoul(ptr = endptr, (char **)&endptr, 10)) < 1) ||
ptr == endptr ||
attempts > 100 ||
errno ||
(*endptr != ' ' && *endptr != '\t') ||
((interval = (int)strtoul(ptr = endptr, (char **)&endptr, 10)) < 1) ||
ptr == endptr ||
interval > 3600 ||
errno) {
free((void *)value);
log_message(LOG_ERR, pamh, "Invalid RATE_LIMIT option. Check \"%s\".",
secret_filename);
return -1;
}
// Parse the time stamps of all previous login attempts.
const unsigned int now = get_time();
unsigned int *timestamps = malloc(sizeof(int));
if (!timestamps) {
oom:
free((void *)value);
log_message(LOG_ERR, pamh, "Out of memory");
return -1;
}
timestamps[0] = now;
int num_timestamps = 1;
while (*endptr && *endptr != '\r' && *endptr != '\n') {
unsigned int timestamp;
errno = 0;
if ((*endptr != ' ' && *endptr != '\t') ||
((timestamp = (int)strtoul(ptr = endptr, (char **)&endptr, 10)),
errno) ||
ptr == endptr) {
free((void *)value);
free(timestamps);
log_message(LOG_ERR, pamh, "Invalid list of timestamps in RATE_LIMIT. "
"Check \"%s\".", secret_filename);
return -1;
}
num_timestamps++;
unsigned int *tmp = (unsigned int *)realloc(timestamps,
sizeof(int) * num_timestamps);
if (!tmp) {
free(timestamps);
goto oom;
}
timestamps = tmp;