xref: /freebsd/sys/contrib/openzfs/contrib/pam_zfs_key/pam_zfs_key.c (revision 61145dc2b94f12f6a47344fb9aac702321880e43)
1 // SPDX-License-Identifier: BSD-3-Clause
2 /*
3  * Redistribution and use in source and binary forms, with or without
4  * modification, are permitted provided that the following conditions are met:
5  *     * Redistributions of source code must retain the above copyright
6  *       notice, this list of conditions and the following disclaimer.
7  *     * Redistributions in binary form must reproduce the above copyright
8  *       notice, this list of conditions and the following disclaimer in the
9  *       documentation and/or other materials provided with the distribution.
10  *     * Neither the name of the <organization> nor the
11  *       names of its contributors may be used to endorse or promote products
12  *       derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
18  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
23  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  *
25  * Copyright (c) 2020, Felix Dörre
26  * All rights reserved.
27  */
28 
29 #include <sys/dsl_crypt.h>
30 #include <sys/byteorder.h>
31 #include <libzfs.h>
32 
33 #include <syslog.h>
34 
35 #include <sys/zio_crypt.h>
36 #include <openssl/evp.h>
37 
38 #define	PAM_SM_AUTH
39 #define	PAM_SM_PASSWORD
40 #define	PAM_SM_SESSION
41 #include <security/pam_modules.h>
42 
43 #if	defined(__linux__)
44 #include <security/pam_ext.h>
45 #define	MAP_FLAGS MAP_PRIVATE | MAP_ANONYMOUS
46 #elif	defined(__FreeBSD__)
47 #include <security/pam_appl.h>
48 static void
pam_syslog(pam_handle_t * pamh,int loglevel,const char * fmt,...)49 pam_syslog(pam_handle_t *pamh, int loglevel, const char *fmt, ...)
50 {
51 	(void) pamh;
52 	va_list args;
53 	va_start(args, fmt);
54 	vsyslog(loglevel, fmt, args);
55 	va_end(args);
56 }
57 #define	MAP_FLAGS MAP_PRIVATE | MAP_ANON | MAP_NOCORE
58 #endif
59 
60 #include <string.h>
61 #include <unistd.h>
62 #include <fcntl.h>
63 #include <sys/stat.h>
64 #include <sys/file.h>
65 #include <sys/wait.h>
66 #include <pwd.h>
67 #include <lib/libzfs/libzfs_impl.h>
68 
69 #include <sys/mman.h>
70 
71 static const char PASSWORD_VAR_NAME[] = "pam_zfs_key_authtok";
72 static const char OLD_PASSWORD_VAR_NAME[] = "pam_zfs_key_oldauthtok";
73 
74 static libzfs_handle_t *g_zfs;
75 
76 static void destroy_pw(pam_handle_t *pamh, void *data, int errcode);
77 
78 typedef int (*mlock_func_t) (const void *, size_t);
79 
80 typedef struct {
81 	size_t len;
82 	char *value;
83 } pw_password_t;
84 
85 /*
86  * Try to mlock(2) or munlock(2) addr while handling EAGAIN by retrying ten
87  * times and sleeping 10 milliseconds in between for a total of 0.1
88  * seconds. lock_func must point to either mlock(2) or munlock(2).
89  */
90 static int
try_lock(mlock_func_t lock_func,const void * addr,size_t len)91 try_lock(mlock_func_t lock_func, const void *addr, size_t len)
92 {
93 	int err;
94 	int retries = 10;
95 	useconds_t sleep_dur = 10 * 1000;
96 
97 	if ((err = (*lock_func)(addr, len)) != EAGAIN) {
98 		return (err);
99 	}
100 	for (int i = retries; i > 0; --i) {
101 		(void) usleep(sleep_dur);
102 		if ((err = (*lock_func)(addr, len)) != EAGAIN) {
103 			break;
104 		}
105 	}
106 	return (err);
107 }
108 
109 
110 static pw_password_t *
alloc_pw_size(size_t len)111 alloc_pw_size(size_t len)
112 {
113 	pw_password_t *pw = malloc(sizeof (pw_password_t));
114 	if (!pw) {
115 		return (NULL);
116 	}
117 	pw->len = len;
118 	/*
119 	 * We use mmap(2) rather than malloc(3) since later on we mlock(2) the
120 	 * memory region. Since mlock(2) and munlock(2) operate on whole memory
121 	 * pages we should allocate a whole page here as mmap(2) does. Further
122 	 * this ensures that the addresses passed to mlock(2) an munlock(2) are
123 	 * on a page boundary as suggested by FreeBSD and required by some
124 	 * other implementations. Finally we avoid inadvertently munlocking
125 	 * memory mlocked by an concurrently running instance of us.
126 	 */
127 	pw->value = mmap(NULL, pw->len, PROT_READ | PROT_WRITE, MAP_FLAGS,
128 	    -1, 0);
129 
130 	if (pw->value == MAP_FAILED) {
131 		free(pw);
132 		return (NULL);
133 	}
134 	if (try_lock(mlock, pw->value, pw->len) != 0) {
135 		(void) munmap(pw->value, pw->len);
136 		free(pw);
137 		return (NULL);
138 	}
139 	return (pw);
140 }
141 
142 static pw_password_t *
alloc_pw_string(const char * source)143 alloc_pw_string(const char *source)
144 {
145 	size_t len = strlen(source) + 1;
146 	pw_password_t *pw = alloc_pw_size(len);
147 
148 	if (!pw) {
149 		return (NULL);
150 	}
151 	memcpy(pw->value, source, pw->len);
152 	return (pw);
153 }
154 
155 static void
pw_free(pw_password_t * pw)156 pw_free(pw_password_t *pw)
157 {
158 	memset(pw->value, 0, pw->len);
159 	if (try_lock(munlock, pw->value, pw->len) == 0) {
160 		(void) munmap(pw->value, pw->len);
161 	}
162 	free(pw);
163 }
164 
165 static pw_password_t *
pw_fetch(pam_handle_t * pamh,int tok)166 pw_fetch(pam_handle_t *pamh, int tok)
167 {
168 	const char *token;
169 	if (pam_get_authtok(pamh, tok, &token, NULL) != PAM_SUCCESS) {
170 		pam_syslog(pamh, LOG_ERR,
171 		    "couldn't get password from PAM stack");
172 		return (NULL);
173 	}
174 	if (!token) {
175 		pam_syslog(pamh, LOG_ERR,
176 		    "token from PAM stack is null");
177 		return (NULL);
178 	}
179 	return (alloc_pw_string(token));
180 }
181 
182 static const pw_password_t *
pw_fetch_lazy(pam_handle_t * pamh,int tok,const char * var_name)183 pw_fetch_lazy(pam_handle_t *pamh, int tok, const char *var_name)
184 {
185 	pw_password_t *pw = pw_fetch(pamh, tok);
186 	if (pw == NULL) {
187 		return (NULL);
188 	}
189 	int ret = pam_set_data(pamh, var_name, pw, destroy_pw);
190 	if (ret != PAM_SUCCESS) {
191 		pw_free(pw);
192 		pam_syslog(pamh, LOG_ERR, "pam_set_data failed");
193 		return (NULL);
194 	}
195 	return (pw);
196 }
197 
198 static const pw_password_t *
pw_get(pam_handle_t * pamh,int tok,const char * var_name)199 pw_get(pam_handle_t *pamh, int tok, const char *var_name)
200 {
201 	const pw_password_t *authtok = NULL;
202 	int ret = pam_get_data(pamh, var_name,
203 	    (const void**)(&authtok));
204 	if (ret == PAM_SUCCESS)
205 		return (authtok);
206 	if (ret == PAM_NO_MODULE_DATA)
207 		return (pw_fetch_lazy(pamh, tok, var_name));
208 	pam_syslog(pamh, LOG_ERR, "password not available");
209 	return (NULL);
210 }
211 
212 static int
pw_clear(pam_handle_t * pamh,const char * var_name)213 pw_clear(pam_handle_t *pamh, const char *var_name)
214 {
215 	int ret = pam_set_data(pamh, var_name, NULL, NULL);
216 	if (ret != PAM_SUCCESS) {
217 		pam_syslog(pamh, LOG_ERR, "clearing password failed");
218 		return (-1);
219 	}
220 	return (0);
221 }
222 
223 static void
destroy_pw(pam_handle_t * pamh,void * data,int errcode)224 destroy_pw(pam_handle_t *pamh, void *data, int errcode)
225 {
226 	(void) pamh, (void) errcode;
227 
228 	if (data != NULL) {
229 		pw_free((pw_password_t *)data);
230 	}
231 }
232 
233 static int
pam_zfs_init(pam_handle_t * pamh)234 pam_zfs_init(pam_handle_t *pamh)
235 {
236 	int error = 0;
237 	if ((g_zfs = libzfs_init()) == NULL) {
238 		error = errno;
239 		pam_syslog(pamh, LOG_ERR, "Zfs initialization error: %s",
240 		    libzfs_error_init(error));
241 	}
242 	return (error);
243 }
244 
245 static void
pam_zfs_free(void)246 pam_zfs_free(void)
247 {
248 	libzfs_fini(g_zfs);
249 }
250 
251 static pw_password_t *
prepare_passphrase(pam_handle_t * pamh,zfs_handle_t * ds,const char * passphrase,nvlist_t * nvlist)252 prepare_passphrase(pam_handle_t *pamh, zfs_handle_t *ds,
253     const char *passphrase, nvlist_t *nvlist)
254 {
255 	pw_password_t *key = alloc_pw_size(WRAPPING_KEY_LEN);
256 	if (!key) {
257 		return (NULL);
258 	}
259 	uint64_t salt;
260 	uint64_t iters;
261 	if (nvlist != NULL) {
262 		int fd = open("/dev/urandom", O_RDONLY);
263 		if (fd < 0) {
264 			pw_free(key);
265 			return (NULL);
266 		}
267 		int bytes_read = 0;
268 		char *buf = (char *)&salt;
269 		size_t bytes = sizeof (uint64_t);
270 		while (bytes_read < bytes) {
271 			ssize_t len = read(fd, buf + bytes_read, bytes
272 			    - bytes_read);
273 			if (len < 0) {
274 				close(fd);
275 				pw_free(key);
276 				return (NULL);
277 			}
278 			bytes_read += len;
279 		}
280 		close(fd);
281 
282 		if (nvlist_add_uint64(nvlist,
283 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), salt)) {
284 			pam_syslog(pamh, LOG_ERR,
285 			    "failed to add salt to nvlist");
286 			pw_free(key);
287 			return (NULL);
288 		}
289 		iters = DEFAULT_PBKDF2_ITERATIONS;
290 		if (nvlist_add_uint64(nvlist, zfs_prop_to_name(
291 		    ZFS_PROP_PBKDF2_ITERS), iters)) {
292 			pam_syslog(pamh, LOG_ERR,
293 			    "failed to add iters to nvlist");
294 			pw_free(key);
295 			return (NULL);
296 		}
297 	} else {
298 		salt = zfs_prop_get_int(ds, ZFS_PROP_PBKDF2_SALT);
299 		iters = zfs_prop_get_int(ds, ZFS_PROP_PBKDF2_ITERS);
300 	}
301 
302 	salt = LE_64(salt);
303 	if (!PKCS5_PBKDF2_HMAC_SHA1((char *)passphrase,
304 	    strlen(passphrase), (uint8_t *)&salt,
305 	    sizeof (uint64_t), iters, WRAPPING_KEY_LEN,
306 	    (uint8_t *)key->value)) {
307 		pam_syslog(pamh, LOG_ERR, "pbkdf failed");
308 		pw_free(key);
309 		return (NULL);
310 	}
311 	return (key);
312 }
313 
314 static int
is_key_loaded(pam_handle_t * pamh,const char * ds_name)315 is_key_loaded(pam_handle_t *pamh, const char *ds_name)
316 {
317 	zfs_handle_t *ds = zfs_open(g_zfs, ds_name, ZFS_TYPE_FILESYSTEM);
318 	if (ds == NULL) {
319 		pam_syslog(pamh, LOG_ERR, "dataset %s not found", ds_name);
320 		return (-1);
321 	}
322 	int keystatus = zfs_prop_get_int(ds, ZFS_PROP_KEYSTATUS);
323 	zfs_close(ds);
324 	return (keystatus != ZFS_KEYSTATUS_UNAVAILABLE);
325 }
326 
327 static int
change_key(pam_handle_t * pamh,const char * ds_name,const char * passphrase)328 change_key(pam_handle_t *pamh, const char *ds_name,
329     const char *passphrase)
330 {
331 	zfs_handle_t *ds = zfs_open(g_zfs, ds_name, ZFS_TYPE_FILESYSTEM);
332 	if (ds == NULL) {
333 		pam_syslog(pamh, LOG_ERR, "dataset %s not found", ds_name);
334 		return (-1);
335 	}
336 	nvlist_t *nvlist = fnvlist_alloc();
337 	pw_password_t *key = prepare_passphrase(pamh, ds, passphrase, nvlist);
338 	if (key == NULL) {
339 		nvlist_free(nvlist);
340 		zfs_close(ds);
341 		return (-1);
342 	}
343 	if (nvlist_add_string(nvlist,
344 	    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
345 	    "prompt")) {
346 		pam_syslog(pamh, LOG_ERR, "nvlist_add failed for keylocation");
347 		pw_free(key);
348 		nvlist_free(nvlist);
349 		zfs_close(ds);
350 		return (-1);
351 	}
352 	if (nvlist_add_uint64(nvlist,
353 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT),
354 	    ZFS_KEYFORMAT_PASSPHRASE)) {
355 		pam_syslog(pamh, LOG_ERR, "nvlist_add failed for keyformat");
356 		pw_free(key);
357 		nvlist_free(nvlist);
358 		zfs_close(ds);
359 		return (-1);
360 	}
361 	int ret = lzc_change_key(ds_name, DCP_CMD_NEW_KEY, nvlist,
362 	    (uint8_t *)key->value, WRAPPING_KEY_LEN);
363 	pw_free(key);
364 	if (ret) {
365 		pam_syslog(pamh, LOG_ERR, "change_key failed: %d", ret);
366 		nvlist_free(nvlist);
367 		zfs_close(ds);
368 		return (-1);
369 	}
370 	nvlist_free(nvlist);
371 	zfs_close(ds);
372 	return (0);
373 }
374 
375 typedef struct {
376 	char *homes_prefix;
377 	char *runstatedir;
378 	char *homedir;
379 	char *dsname;
380 	uid_t uid_min;
381 	uid_t uid_max;
382 	uid_t uid;
383 	const char *username;
384 	boolean_t unmount_and_unload;
385 	boolean_t force_unmount;
386 	boolean_t recursive_homes;
387 	boolean_t mount_recursively;
388 } zfs_key_config_t;
389 
390 static int
zfs_key_config_load(pam_handle_t * pamh,zfs_key_config_t * config,int argc,const char ** argv)391 zfs_key_config_load(pam_handle_t *pamh, zfs_key_config_t *config,
392     int argc, const char **argv)
393 {
394 	config->homes_prefix = strdup("rpool/home");
395 	if (config->homes_prefix == NULL) {
396 		pam_syslog(pamh, LOG_ERR, "strdup failure");
397 		return (PAM_SERVICE_ERR);
398 	}
399 	config->runstatedir = strdup(RUNSTATEDIR "/pam_zfs_key");
400 	if (config->runstatedir == NULL) {
401 		pam_syslog(pamh, LOG_ERR, "strdup failure");
402 		free(config->homes_prefix);
403 		return (PAM_SERVICE_ERR);
404 	}
405 	const char *name;
406 	if (pam_get_user(pamh, &name, NULL) != PAM_SUCCESS) {
407 		pam_syslog(pamh, LOG_ERR,
408 		    "couldn't get username from PAM stack");
409 		free(config->runstatedir);
410 		free(config->homes_prefix);
411 		return (PAM_SERVICE_ERR);
412 	}
413 	struct passwd *entry = getpwnam(name);
414 	if (!entry) {
415 		free(config->runstatedir);
416 		free(config->homes_prefix);
417 		return (PAM_USER_UNKNOWN);
418 	}
419 	config->uid_min = 1000;
420 	config->uid_max = MAXUID;
421 	config->uid = entry->pw_uid;
422 	config->username = name;
423 	config->unmount_and_unload = B_TRUE;
424 	config->force_unmount = B_FALSE;
425 	config->recursive_homes = B_FALSE;
426 	config->mount_recursively = B_FALSE;
427 	config->dsname = NULL;
428 	config->homedir = NULL;
429 	for (int c = 0; c < argc; c++) {
430 		if (strncmp(argv[c], "homes=", 6) == 0) {
431 			free(config->homes_prefix);
432 			config->homes_prefix = strdup(argv[c] + 6);
433 		} else if (strncmp(argv[c], "runstatedir=", 12) == 0) {
434 			free(config->runstatedir);
435 			config->runstatedir = strdup(argv[c] + 12);
436 		} else if (strncmp(argv[c], "uid_min=", 8) == 0) {
437 			sscanf(argv[c] + 8, "%u", &config->uid_min);
438 		} else if (strncmp(argv[c], "uid_max=", 8) == 0) {
439 			sscanf(argv[c] + 8, "%u", &config->uid_max);
440 		} else if (strcmp(argv[c], "nounmount") == 0) {
441 			config->unmount_and_unload = B_FALSE;
442 		} else if (strcmp(argv[c], "forceunmount") == 0) {
443 			config->force_unmount = B_TRUE;
444 		} else if (strcmp(argv[c], "recursive_homes") == 0) {
445 			config->recursive_homes = B_TRUE;
446 		} else if (strcmp(argv[c], "mount_recursively") == 0) {
447 			config->mount_recursively = B_TRUE;
448 		} else if (strcmp(argv[c], "prop_mountpoint") == 0) {
449 			if (config->homedir == NULL)
450 				config->homedir = strdup(entry->pw_dir);
451 		}
452 	}
453 	return (PAM_SUCCESS);
454 }
455 
456 typedef struct {
457 	pam_handle_t *pamh;
458 	zfs_key_config_t *target;
459 } mount_umount_dataset_data_t;
460 
461 static int
mount_dataset(zfs_handle_t * zhp,void * data)462 mount_dataset(zfs_handle_t *zhp, void *data)
463 {
464 	mount_umount_dataset_data_t *mount_umount_dataset_data = data;
465 
466 	zfs_key_config_t *target = mount_umount_dataset_data->target;
467 	pam_handle_t *pamh = mount_umount_dataset_data->pamh;
468 
469 	/* Refresh properties to get the latest key status */
470 	zfs_refresh_properties(zhp);
471 
472 	int ret = 0;
473 
474 	/* Check if dataset type is filesystem */
475 	if (zhp->zfs_type != ZFS_TYPE_FILESYSTEM) {
476 		pam_syslog(pamh, LOG_DEBUG,
477 		    "dataset is not filesystem: %s, skipping.",
478 		    zfs_get_name(zhp));
479 		return (0);
480 	}
481 
482 	/* Check if encryption key is available */
483 	if (zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS) ==
484 	    ZFS_KEYSTATUS_UNAVAILABLE) {
485 		pam_syslog(pamh, LOG_WARNING,
486 		    "key unavailable for: %s, skipping",
487 		    zfs_get_name(zhp));
488 		return (0);
489 	}
490 
491 	/* Check if prop canmount is on */
492 	if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) != ZFS_CANMOUNT_ON) {
493 		pam_syslog(pamh, LOG_INFO,
494 		    "canmount is not on for: %s, skipping",
495 		    zfs_get_name(zhp));
496 		return (0);
497 	}
498 
499 	/* Get mountpoint prop for check */
500 	char mountpoint[ZFS_MAXPROPLEN];
501 	if ((ret = zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
502 	    sizeof (mountpoint), NULL, NULL, 0, 1)) != 0) {
503 		pam_syslog(pamh, LOG_ERR,
504 		    "failed to get mountpoint prop: %d", ret);
505 		return (-1);
506 	}
507 
508 	/* Check if mountpoint isn't none or legacy */
509 	if (strcmp(mountpoint, ZFS_MOUNTPOINT_NONE) == 0 ||
510 	    strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
511 		pam_syslog(pamh, LOG_INFO,
512 		    "mountpoint is none or legacy for: %s, skipping",
513 		    zfs_get_name(zhp));
514 		return (0);
515 	}
516 
517 	/* Don't mount the dataset if already mounted */
518 	if (zfs_is_mounted(zhp, NULL)) {
519 		pam_syslog(pamh, LOG_INFO, "already mounted: %s",
520 		    zfs_get_name(zhp));
521 		return (0);
522 	}
523 
524 	/* Mount the dataset */
525 	ret = zfs_mount(zhp, NULL, 0);
526 	if (ret) {
527 		pam_syslog(pamh, LOG_ERR,
528 		    "zfs_mount failed for %s with: %d", zfs_get_name(zhp),
529 		    ret);
530 		return (ret);
531 	}
532 
533 	/* Recursively mount children if the recursive flag is set */
534 	if (target->mount_recursively) {
535 		ret = zfs_iter_filesystems_v2(zhp, 0, mount_dataset, data);
536 		if (ret != 0) {
537 			pam_syslog(pamh, LOG_ERR,
538 			    "child iteration failed: %d", ret);
539 			return (-1);
540 		}
541 	}
542 
543 	return (ret);
544 }
545 
546 static int
umount_dataset(zfs_handle_t * zhp,void * data)547 umount_dataset(zfs_handle_t *zhp, void *data)
548 {
549 	mount_umount_dataset_data_t *mount_umount_dataset_data = data;
550 
551 	zfs_key_config_t *target = mount_umount_dataset_data->target;
552 	pam_handle_t *pamh = mount_umount_dataset_data->pamh;
553 
554 	int ret = 0;
555 	/* Recursively umount children if the recursive flag is set */
556 	if (target->mount_recursively) {
557 		ret = zfs_iter_filesystems_v2(zhp, 0, umount_dataset, data);
558 		if (ret != 0) {
559 			pam_syslog(pamh, LOG_ERR,
560 			    "child iteration failed: %d", ret);
561 			return (-1);
562 		}
563 	}
564 
565 	/* Check if dataset type is filesystem */
566 	if (zhp->zfs_type != ZFS_TYPE_FILESYSTEM) {
567 		pam_syslog(pamh, LOG_DEBUG,
568 		    "dataset is not filesystem: %s, skipping",
569 		    zfs_get_name(zhp));
570 		return (0);
571 	}
572 
573 	/* Don't umount the dataset if already unmounted */
574 	if (zfs_is_mounted(zhp, NULL) == 0) {
575 		pam_syslog(pamh, LOG_INFO, "already unmounted: %s",
576 		    zfs_get_name(zhp));
577 		return (0);
578 	}
579 
580 	/* Unmount the dataset */
581 	ret = zfs_unmount(zhp, NULL, target->force_unmount ? MS_FORCE : 0);
582 	if (ret) {
583 		pam_syslog(pamh, LOG_ERR,
584 		    "zfs_unmount failed for %s with: %d", zfs_get_name(zhp),
585 		    ret);
586 		return (ret);
587 	}
588 
589 	return (ret);
590 }
591 
592 static int
decrypt_mount(pam_handle_t * pamh,zfs_key_config_t * config,const char * ds_name,const char * passphrase,boolean_t noop)593 decrypt_mount(pam_handle_t *pamh, zfs_key_config_t *config, const char *ds_name,
594 	const char *passphrase, boolean_t noop)
595 {
596 	zfs_handle_t *ds = zfs_open(g_zfs, ds_name, ZFS_TYPE_FILESYSTEM);
597 	if (ds == NULL) {
598 		pam_syslog(pamh, LOG_ERR, "dataset %s not found", ds_name);
599 		return (-1);
600 	}
601 	pw_password_t *key = prepare_passphrase(pamh, ds, passphrase, NULL);
602 	if (key == NULL) {
603 		zfs_close(ds);
604 		return (-1);
605 	}
606 	int ret = lzc_load_key(ds_name, noop, (uint8_t *)key->value,
607 	    WRAPPING_KEY_LEN);
608 	pw_free(key);
609 	if (ret && ret != EEXIST) {
610 		pam_syslog(pamh, LOG_ERR, "load_key failed: %d", ret);
611 		zfs_close(ds);
612 		return (-1);
613 	}
614 
615 	if (noop) {
616 		zfs_close(ds);
617 		return (0);
618 	}
619 
620 	mount_umount_dataset_data_t data;
621 	data.pamh = pamh;
622 	data.target = config;
623 
624 	ret = mount_dataset(ds, &data);
625 	if (ret != 0) {
626 		pam_syslog(pamh, LOG_ERR, "mount failed: %d", ret);
627 		zfs_close(ds);
628 		return (-1);
629 	}
630 
631 	zfs_close(ds);
632 	return (0);
633 }
634 
635 static int
unmount_unload(pam_handle_t * pamh,const char * ds_name,zfs_key_config_t * target)636 unmount_unload(pam_handle_t *pamh, const char *ds_name,
637     zfs_key_config_t *target)
638 {
639 	zfs_handle_t *ds = zfs_open(g_zfs, ds_name, ZFS_TYPE_FILESYSTEM);
640 	if (ds == NULL) {
641 		pam_syslog(pamh, LOG_ERR, "dataset %s not found", ds_name);
642 		return (-1);
643 	}
644 
645 	mount_umount_dataset_data_t data;
646 	data.pamh = pamh;
647 	data.target = target;
648 
649 	int ret = umount_dataset(ds, &data);
650 	if (ret) {
651 		pam_syslog(pamh, LOG_ERR,
652 		    "unmount_dataset failed with: %d", ret);
653 		zfs_close(ds);
654 		return (-1);
655 	}
656 
657 	ret = lzc_unload_key(ds_name);
658 	if (ret) {
659 		pam_syslog(pamh, LOG_ERR, "unload_key failed with: %d", ret);
660 		zfs_close(ds);
661 		return (-1);
662 	}
663 	zfs_close(ds);
664 	return (0);
665 }
666 
667 static void
zfs_key_config_free(zfs_key_config_t * config)668 zfs_key_config_free(zfs_key_config_t *config)
669 {
670 	free(config->homes_prefix);
671 	free(config->runstatedir);
672 	free(config->homedir);
673 	free(config->dsname);
674 }
675 
676 static int
find_dsname_by_prop_value(zfs_handle_t * zhp,void * data)677 find_dsname_by_prop_value(zfs_handle_t *zhp, void *data)
678 {
679 	zfs_type_t type = zfs_get_type(zhp);
680 	zfs_key_config_t *target = data;
681 	char mountpoint[ZFS_MAXPROPLEN];
682 
683 	/* Skip any datasets whose type does not match */
684 	if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
685 		zfs_close(zhp);
686 		return (0);
687 	}
688 
689 	/* Skip any datasets whose mountpoint does not match */
690 	(void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
691 	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
692 	if (strcmp(target->homedir, mountpoint) != 0) {
693 		if (target->recursive_homes) {
694 			(void) zfs_iter_filesystems_v2(zhp, 0,
695 			    find_dsname_by_prop_value, target);
696 		}
697 		zfs_close(zhp);
698 		return (target->dsname != NULL);
699 	}
700 
701 	target->dsname = strdup(zfs_get_name(zhp));
702 	zfs_close(zhp);
703 	return (1);
704 }
705 
706 static char *
zfs_key_config_get_dataset(pam_handle_t * pamh,zfs_key_config_t * config)707 zfs_key_config_get_dataset(pam_handle_t *pamh, zfs_key_config_t *config)
708 {
709 	if (config->homedir != NULL &&
710 	    config->homes_prefix != NULL) {
711 		if (strcmp(config->homes_prefix, "*") == 0) {
712 			(void) zfs_iter_root(g_zfs,
713 			    find_dsname_by_prop_value, config);
714 		} else {
715 			zfs_handle_t *zhp = zfs_open(g_zfs,
716 			    config->homes_prefix, ZFS_TYPE_FILESYSTEM);
717 			if (zhp == NULL) {
718 				pam_syslog(pamh, LOG_ERR,
719 				    "dataset %s not found",
720 				    config->homes_prefix);
721 				return (NULL);
722 			}
723 
724 			(void) zfs_iter_filesystems_v2(zhp, 0,
725 			    find_dsname_by_prop_value, config);
726 			zfs_close(zhp);
727 		}
728 		char *dsname = config->dsname;
729 		config->dsname = NULL;
730 		return (dsname);
731 	}
732 
733 	if (config->homes_prefix == NULL) {
734 		return (NULL);
735 	}
736 
737 	size_t len = ZFS_MAX_DATASET_NAME_LEN;
738 	size_t total_len = strlen(config->homes_prefix) + 1
739 	    + strlen(config->username);
740 	if (total_len > len) {
741 		return (NULL);
742 	}
743 	char *ret = malloc(len + 1);
744 	if (!ret) {
745 		return (NULL);
746 	}
747 	ret[0] = 0;
748 	(void) snprintf(ret, len + 1, "%s/%s", config->homes_prefix,
749 	    config->username);
750 	return (ret);
751 }
752 
753 static int
zfs_key_config_modify_session_counter(pam_handle_t * pamh,zfs_key_config_t * config,int delta)754 zfs_key_config_modify_session_counter(pam_handle_t *pamh,
755     zfs_key_config_t *config, int delta)
756 {
757 	const char *runtime_path = config->runstatedir;
758 	if (mkdir(runtime_path, S_IRWXU) != 0 && errno != EEXIST) {
759 		pam_syslog(pamh, LOG_ERR, "Can't create runtime path: %d",
760 		    errno);
761 		return (-1);
762 	}
763 	if (chown(runtime_path, 0, 0) != 0) {
764 		pam_syslog(pamh, LOG_ERR, "Can't chown runtime path: %d",
765 		    errno);
766 		return (-1);
767 	}
768 	if (chmod(runtime_path, S_IRWXU) != 0) {
769 		pam_syslog(pamh, LOG_ERR, "Can't chmod runtime path: %d",
770 		    errno);
771 		return (-1);
772 	}
773 
774 	char *counter_path;
775 	if (asprintf(&counter_path, "%s/%u", runtime_path, config->uid) == -1)
776 		return (-1);
777 
778 	const int fd = open(counter_path,
779 	    O_RDWR | O_CLOEXEC | O_CREAT | O_NOFOLLOW,
780 	    S_IRUSR | S_IWUSR);
781 	free(counter_path);
782 	if (fd < 0) {
783 		pam_syslog(pamh, LOG_ERR, "Can't open counter file: %d", errno);
784 		return (-1);
785 	}
786 	if (flock(fd, LOCK_EX) != 0) {
787 		pam_syslog(pamh, LOG_ERR, "Can't lock counter file: %d", errno);
788 		close(fd);
789 		return (-1);
790 	}
791 	char counter[20];
792 	char *pos = counter;
793 	int remaining = sizeof (counter) - 1;
794 	int ret;
795 	counter[sizeof (counter) - 1] = 0;
796 	while (remaining > 0 && (ret = read(fd, pos, remaining)) > 0) {
797 		remaining -= ret;
798 		pos += ret;
799 	}
800 	*pos = 0;
801 	long int counter_value = strtol(counter, NULL, 10);
802 	counter_value += delta;
803 	if (counter_value < 0) {
804 		counter_value = 0;
805 	}
806 	lseek(fd, 0, SEEK_SET);
807 	if (ftruncate(fd, 0) != 0) {
808 		pam_syslog(pamh, LOG_ERR, "Can't truncate counter file: %d",
809 		    errno);
810 		close(fd);
811 		return (-1);
812 	}
813 	snprintf(counter, sizeof (counter), "%ld", counter_value);
814 	remaining = strlen(counter);
815 	pos = counter;
816 	while (remaining > 0 && (ret = write(fd, pos, remaining)) > 0) {
817 		remaining -= ret;
818 		pos += ret;
819 	}
820 	close(fd);
821 	return (counter_value);
822 }
823 
824 __attribute__((visibility("default")))
825 PAM_EXTERN int
pam_sm_authenticate(pam_handle_t * pamh,int flags,int argc,const char ** argv)826 pam_sm_authenticate(pam_handle_t *pamh, int flags,
827     int argc, const char **argv)
828 {
829 	(void) flags;
830 
831 	if (geteuid() != 0) {
832 		pam_syslog(pamh, LOG_ERR,
833 		    "Cannot zfs_mount when not being root.");
834 		return (PAM_SERVICE_ERR);
835 	}
836 	zfs_key_config_t config;
837 	int config_err = zfs_key_config_load(pamh, &config, argc, argv);
838 	if (config_err != PAM_SUCCESS) {
839 		return (config_err);
840 	}
841 	if (config.uid < config.uid_min || config.uid > config.uid_max) {
842 		zfs_key_config_free(&config);
843 		return (PAM_SERVICE_ERR);
844 	}
845 
846 	const pw_password_t *token = pw_fetch_lazy(pamh,
847 	    PAM_AUTHTOK, PASSWORD_VAR_NAME);
848 	if (token == NULL) {
849 		zfs_key_config_free(&config);
850 		return (PAM_AUTH_ERR);
851 	}
852 	if (pam_zfs_init(pamh) != 0) {
853 		zfs_key_config_free(&config);
854 		return (PAM_SERVICE_ERR);
855 	}
856 	char *dataset = zfs_key_config_get_dataset(pamh, &config);
857 	if (!dataset) {
858 		pam_zfs_free();
859 		zfs_key_config_free(&config);
860 		return (PAM_SERVICE_ERR);
861 	}
862 	if (decrypt_mount(pamh, &config, dataset, token->value, B_TRUE) == -1) {
863 		free(dataset);
864 		pam_zfs_free();
865 		zfs_key_config_free(&config);
866 		return (PAM_AUTH_ERR);
867 	}
868 	free(dataset);
869 	pam_zfs_free();
870 	zfs_key_config_free(&config);
871 	return (PAM_SUCCESS);
872 }
873 
874 __attribute__((visibility("default")))
875 PAM_EXTERN int
pam_sm_setcred(pam_handle_t * pamh,int flags,int argc,const char ** argv)876 pam_sm_setcred(pam_handle_t *pamh, int flags,
877     int argc, const char **argv)
878 {
879 	(void) pamh, (void) flags, (void) argc, (void) argv;
880 	return (PAM_SUCCESS);
881 }
882 
883 __attribute__((visibility("default")))
884 PAM_EXTERN int
pam_sm_chauthtok(pam_handle_t * pamh,int flags,int argc,const char ** argv)885 pam_sm_chauthtok(pam_handle_t *pamh, int flags,
886     int argc, const char **argv)
887 {
888 	if (geteuid() != 0) {
889 		pam_syslog(pamh, LOG_ERR,
890 		    "Cannot zfs_mount when not being root.");
891 		return (PAM_PERM_DENIED);
892 	}
893 	zfs_key_config_t config;
894 	if (zfs_key_config_load(pamh, &config, argc, argv) != PAM_SUCCESS) {
895 		return (PAM_SERVICE_ERR);
896 	}
897 	if (config.uid < config.uid_min || config.uid > config.uid_max) {
898 		zfs_key_config_free(&config);
899 		return (PAM_SERVICE_ERR);
900 	}
901 	const pw_password_t *old_token = pw_get(pamh,
902 	    PAM_OLDAUTHTOK, OLD_PASSWORD_VAR_NAME);
903 	{
904 		if (pam_zfs_init(pamh) != 0) {
905 			zfs_key_config_free(&config);
906 			return (PAM_SERVICE_ERR);
907 		}
908 		char *dataset = zfs_key_config_get_dataset(pamh, &config);
909 		if (!dataset) {
910 			pam_zfs_free();
911 			zfs_key_config_free(&config);
912 			return (PAM_SERVICE_ERR);
913 		}
914 		if (!old_token) {
915 			pam_syslog(pamh, LOG_ERR,
916 			    "old password from PAM stack is null");
917 			free(dataset);
918 			pam_zfs_free();
919 			zfs_key_config_free(&config);
920 			return (PAM_SERVICE_ERR);
921 		}
922 		if (decrypt_mount(pamh, &config, dataset,
923 		    old_token->value, B_TRUE) == -1) {
924 			pam_syslog(pamh, LOG_ERR,
925 			    "old token mismatch");
926 			free(dataset);
927 			pam_zfs_free();
928 			zfs_key_config_free(&config);
929 			return (PAM_PERM_DENIED);
930 		}
931 	}
932 
933 	if ((flags & PAM_UPDATE_AUTHTOK) != 0) {
934 		const pw_password_t *token = pw_get(pamh, PAM_AUTHTOK,
935 		    PASSWORD_VAR_NAME);
936 		if (token == NULL) {
937 			pam_syslog(pamh, LOG_ERR, "new password unavailable");
938 			pam_zfs_free();
939 			zfs_key_config_free(&config);
940 			pw_clear(pamh, OLD_PASSWORD_VAR_NAME);
941 			return (PAM_SERVICE_ERR);
942 		}
943 		char *dataset = zfs_key_config_get_dataset(pamh, &config);
944 		if (!dataset) {
945 			pam_zfs_free();
946 			zfs_key_config_free(&config);
947 			pw_clear(pamh, OLD_PASSWORD_VAR_NAME);
948 			pw_clear(pamh, PASSWORD_VAR_NAME);
949 			return (PAM_SERVICE_ERR);
950 		}
951 		int was_loaded = is_key_loaded(pamh, dataset);
952 		if (!was_loaded && decrypt_mount(pamh, &config, dataset,
953 		    old_token->value, B_FALSE) == -1) {
954 			free(dataset);
955 			pam_zfs_free();
956 			zfs_key_config_free(&config);
957 			pw_clear(pamh, OLD_PASSWORD_VAR_NAME);
958 			pw_clear(pamh, PASSWORD_VAR_NAME);
959 			return (PAM_SERVICE_ERR);
960 		}
961 		int changed = change_key(pamh, dataset, token->value);
962 		if (!was_loaded) {
963 			unmount_unload(pamh, dataset, &config);
964 		}
965 		free(dataset);
966 		pam_zfs_free();
967 		zfs_key_config_free(&config);
968 		if (pw_clear(pamh, OLD_PASSWORD_VAR_NAME) == -1 ||
969 		    pw_clear(pamh, PASSWORD_VAR_NAME) == -1 || changed == -1) {
970 			return (PAM_SERVICE_ERR);
971 		}
972 	} else {
973 		zfs_key_config_free(&config);
974 	}
975 	return (PAM_SUCCESS);
976 }
977 
978 PAM_EXTERN int
pam_sm_open_session(pam_handle_t * pamh,int flags,int argc,const char ** argv)979 pam_sm_open_session(pam_handle_t *pamh, int flags,
980     int argc, const char **argv)
981 {
982 	(void) flags;
983 
984 	if (geteuid() != 0) {
985 		pam_syslog(pamh, LOG_ERR,
986 		    "Cannot zfs_mount when not being root.");
987 		return (PAM_SUCCESS);
988 	}
989 	zfs_key_config_t config;
990 	if (zfs_key_config_load(pamh, &config, argc, argv) != PAM_SUCCESS) {
991 		return (PAM_SESSION_ERR);
992 	}
993 
994 	if (config.uid < config.uid_min || config.uid > config.uid_max) {
995 		zfs_key_config_free(&config);
996 		return (PAM_SUCCESS);
997 	}
998 
999 	int counter = zfs_key_config_modify_session_counter(pamh, &config, 1);
1000 	if (counter != 1) {
1001 		zfs_key_config_free(&config);
1002 		return (PAM_SUCCESS);
1003 	}
1004 
1005 	const pw_password_t *token = pw_get(pamh,
1006 	    PAM_AUTHTOK, PASSWORD_VAR_NAME);
1007 	if (token == NULL) {
1008 		zfs_key_config_free(&config);
1009 		return (PAM_SESSION_ERR);
1010 	}
1011 	if (pam_zfs_init(pamh) != 0) {
1012 		zfs_key_config_free(&config);
1013 		return (PAM_SERVICE_ERR);
1014 	}
1015 	char *dataset = zfs_key_config_get_dataset(pamh, &config);
1016 	if (!dataset) {
1017 		pam_zfs_free();
1018 		zfs_key_config_free(&config);
1019 		return (PAM_SERVICE_ERR);
1020 	}
1021 	if (decrypt_mount(pamh, &config, dataset,
1022 	    token->value, B_FALSE) == -1) {
1023 		free(dataset);
1024 		pam_zfs_free();
1025 		zfs_key_config_free(&config);
1026 		return (PAM_SERVICE_ERR);
1027 	}
1028 	free(dataset);
1029 	pam_zfs_free();
1030 	zfs_key_config_free(&config);
1031 	if (pw_clear(pamh, PASSWORD_VAR_NAME) == -1) {
1032 		return (PAM_SERVICE_ERR);
1033 	}
1034 	return (PAM_SUCCESS);
1035 
1036 }
1037 
1038 __attribute__((visibility("default")))
1039 PAM_EXTERN int
pam_sm_close_session(pam_handle_t * pamh,int flags,int argc,const char ** argv)1040 pam_sm_close_session(pam_handle_t *pamh, int flags,
1041     int argc, const char **argv)
1042 {
1043 	(void) flags;
1044 
1045 	if (geteuid() != 0) {
1046 		pam_syslog(pamh, LOG_ERR,
1047 		    "Cannot zfs_mount when not being root.");
1048 		return (PAM_SUCCESS);
1049 	}
1050 	zfs_key_config_t config;
1051 	if (zfs_key_config_load(pamh, &config, argc, argv) != PAM_SUCCESS) {
1052 		return (PAM_SESSION_ERR);
1053 	}
1054 	if (config.uid < config.uid_min || config.uid > config.uid_max) {
1055 		zfs_key_config_free(&config);
1056 		return (PAM_SUCCESS);
1057 	}
1058 
1059 	int counter = zfs_key_config_modify_session_counter(pamh, &config, -1);
1060 	if (counter != 0) {
1061 		zfs_key_config_free(&config);
1062 		return (PAM_SUCCESS);
1063 	}
1064 
1065 	if (config.unmount_and_unload) {
1066 		if (pam_zfs_init(pamh) != 0) {
1067 			zfs_key_config_free(&config);
1068 			return (PAM_SERVICE_ERR);
1069 		}
1070 		char *dataset = zfs_key_config_get_dataset(pamh, &config);
1071 		if (!dataset) {
1072 			pam_zfs_free();
1073 			zfs_key_config_free(&config);
1074 			return (PAM_SESSION_ERR);
1075 		}
1076 		if (unmount_unload(pamh, dataset, &config) == -1) {
1077 			free(dataset);
1078 			pam_zfs_free();
1079 			zfs_key_config_free(&config);
1080 			return (PAM_SESSION_ERR);
1081 		}
1082 		free(dataset);
1083 		pam_zfs_free();
1084 	}
1085 
1086 	zfs_key_config_free(&config);
1087 	return (PAM_SUCCESS);
1088 }
1089