Whamcloud - gitweb
LU-17662 osd-zfs: Support for ZFS 2.2.3
[fs/lustre-release.git] / lustre / ptlrpc / gss / gss_keyring.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2014, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/ptlrpc/gss/gss_keyring.c
32  *
33  * Author: Eric Mei <ericm@clusterfs.com>
34  */
35
36 #define DEBUG_SUBSYSTEM S_SEC
37 #include <linux/init.h>
38 #include <linux/module.h>
39 #include <linux/slab.h>
40 #include <linux/dcache.h>
41 #include <linux/fs.h>
42 #include <linux/crypto.h>
43 #include <linux/key.h>
44 #include <linux/keyctl.h>
45 #include <linux/key-type.h>
46 #include <linux/mutex.h>
47 #include <asm/atomic.h>
48
49 #include <libcfs/linux/linux-list.h>
50 #include <obd.h>
51 #include <obd_class.h>
52 #include <obd_support.h>
53 #include <uapi/linux/lustre/lustre_idl.h>
54 #include <lustre_sec.h>
55 #include <lustre_net.h>
56 #include <lustre_import.h>
57
58 #include "gss_err.h"
59 #include "gss_internal.h"
60 #include "gss_api.h"
61
62 #ifdef HAVE_GET_REQUEST_KEY_AUTH
63 #include <keys/request_key_auth-type.h>
64 #endif
65
66 static struct ptlrpc_sec_policy gss_policy_keyring;
67 static struct ptlrpc_ctx_ops gss_keyring_ctxops;
68 static struct key_type gss_key_type;
69
70 static int sec_install_rctx_kr(struct ptlrpc_sec *sec,
71                                struct ptlrpc_svc_ctx *svc_ctx);
72 static void request_key_unlink(struct key *key);
73
74 /*
75  * the timeout is only for the case that upcall child process die abnormally.
76  * in any other cases it should finally update kernel key.
77  *
78  * FIXME we'd better to incorporate the client & server side upcall timeouts
79  * into the framework of Adaptive Timeouts, but we need to figure out how to
80  * make sure that kernel knows the upcall processes is in-progress or died
81  * unexpectedly.
82  */
83 #define KEYRING_UPCALL_TIMEOUT  (obd_timeout + obd_timeout)
84
85 /* Check caller's namespace in gss_keyring upcall */
86 unsigned int gss_check_upcall_ns = 1;
87
88 /****************************************
89  * internal helpers                     *
90  ****************************************/
91
92 static inline void keyring_upcall_lock(struct gss_sec_keyring *gsec_kr)
93 {
94 #ifdef HAVE_KEYRING_UPCALL_SERIALIZED
95         mutex_lock(&gsec_kr->gsk_uc_lock);
96 #endif
97 }
98
99 static inline void keyring_upcall_unlock(struct gss_sec_keyring *gsec_kr)
100 {
101 #ifdef HAVE_KEYRING_UPCALL_SERIALIZED
102         mutex_unlock(&gsec_kr->gsk_uc_lock);
103 #endif
104 }
105
106 static inline void key_revoke_locked(struct key *key)
107 {
108         set_bit(KEY_FLAG_REVOKED, &key->flags);
109 }
110
111 static void ctx_upcall_timeout_kr(cfs_timer_cb_arg_t data)
112 {
113         struct gss_cli_ctx_keyring *gctx_kr = cfs_from_timer(gctx_kr,
114                                                              data, gck_timer);
115         struct ptlrpc_cli_ctx *ctx = &(gctx_kr->gck_base.gc_base);
116         struct obd_import *imp = ctx->cc_sec->ps_import;
117         struct key *key = gctx_kr->gck_key;
118
119         if (key)
120                 CDEBUG(D_SEC,
121                        "%s: GSS context (%p) negotiation timeout, revoking key (%p)\n",
122                        imp->imp_obd->obd_name, ctx, key);
123         else
124                 CDEBUG(D_SEC,
125                        "%s: GSS context (%p) negotiation timeout, ignoring already unlinked key\n",
126                        imp->imp_obd->obd_name, ctx);
127
128         cli_ctx_expire(ctx);
129         if (key)
130                 key_revoke_locked(key);
131 }
132
133 static void ctx_start_timer_kr(struct ptlrpc_cli_ctx *ctx, time64_t timeout)
134 {
135         struct gss_cli_ctx_keyring *gctx_kr = ctx2gctx_keyring(ctx);
136         struct timer_list *timer = &gctx_kr->gck_timer;
137
138         LASSERT(timer);
139
140         CDEBUG(D_SEC, "ctx %p: start timer %llds\n", ctx, timeout);
141
142         cfs_timer_setup(timer, ctx_upcall_timeout_kr,
143                         (unsigned long)gctx_kr, 0);
144         timer->expires = cfs_time_seconds(timeout) + jiffies;
145         add_timer(timer);
146 }
147
148 /*
149  * caller should make sure no race with other threads
150  */
151 static
152 void ctx_clear_timer_kr(struct ptlrpc_cli_ctx *ctx)
153 {
154         struct gss_cli_ctx_keyring *gctx_kr = ctx2gctx_keyring(ctx);
155         struct timer_list          *timer = &gctx_kr->gck_timer;
156
157         CDEBUG(D_SEC, "ctx %p, key %p\n", ctx, gctx_kr->gck_key);
158
159         timer_delete_sync(timer);
160 }
161
162 static
163 struct ptlrpc_cli_ctx *ctx_create_kr(struct ptlrpc_sec *sec,
164                                      struct vfs_cred *vcred)
165 {
166         struct ptlrpc_cli_ctx      *ctx;
167         struct gss_cli_ctx_keyring *gctx_kr;
168
169         OBD_ALLOC_PTR(gctx_kr);
170         if (gctx_kr == NULL)
171                 return NULL;
172
173         cfs_timer_setup(&gctx_kr->gck_timer, NULL, 0, 0);
174
175         ctx = &gctx_kr->gck_base.gc_base;
176
177         if (gss_cli_ctx_init_common(sec, ctx, &gss_keyring_ctxops, vcred)) {
178                 OBD_FREE_PTR(gctx_kr);
179                 return NULL;
180         }
181
182         ctx->cc_expire = ktime_get_real_seconds() + KEYRING_UPCALL_TIMEOUT;
183         clear_bit(PTLRPC_CTX_NEW_BIT, &ctx->cc_flags);
184         atomic_inc(&ctx->cc_refcount); /* for the caller */
185
186         return ctx;
187 }
188
189 static void ctx_destroy_kr(struct ptlrpc_cli_ctx *ctx)
190 {
191         struct ptlrpc_sec               *sec = ctx->cc_sec;
192         struct gss_cli_ctx_keyring      *gctx_kr = ctx2gctx_keyring(ctx);
193
194         CDEBUG(D_SEC, "destroying ctx %p\n", ctx);
195
196         /* at this time the association with key has been broken. */
197         LASSERT(sec);
198         LASSERT(atomic_read(&sec->ps_refcount) > 0);
199         LASSERT(atomic_read(&sec->ps_nctx) > 0);
200         LASSERT(test_bit(PTLRPC_CTX_CACHED_BIT, &ctx->cc_flags) == 0);
201         LASSERT(gctx_kr->gck_key == NULL);
202
203         ctx_clear_timer_kr(ctx);
204
205         if (gss_cli_ctx_fini_common(sec, ctx))
206                 return;
207
208         OBD_FREE_PTR(gctx_kr);
209
210         atomic_dec(&sec->ps_nctx);
211         sptlrpc_sec_put(sec);
212 }
213
214 static void ctx_release_kr(struct ptlrpc_cli_ctx *ctx, int sync)
215 {
216         if (sync) {
217                 ctx_destroy_kr(ctx);
218         } else {
219                 atomic_inc(&ctx->cc_refcount);
220                 sptlrpc_gc_add_ctx(ctx);
221         }
222 }
223
224 static void ctx_put_kr(struct ptlrpc_cli_ctx *ctx, int sync)
225 {
226         LASSERT(atomic_read(&ctx->cc_refcount) > 0);
227
228         if (atomic_dec_and_test(&ctx->cc_refcount))
229                 ctx_release_kr(ctx, sync);
230 }
231
232 /*
233  * key <-> ctx association and rules:
234  * - ctx might not bind with any key
235  * - key/ctx binding is protected by key semaphore (if the key present)
236  * - key and ctx each take a reference of the other
237  * - ctx enlist/unlist is protected by ctx spinlock
238  * - never enlist a ctx after it's been unlisted
239  * - whoever do enlist should also do bind, lock key before enlist:
240  *   - lock key -> lock ctx -> enlist -> unlock ctx -> bind -> unlock key
241  * - whoever do unlist should also do unbind:
242  *   - lock key -> lock ctx -> unlist -> unlock ctx -> unbind -> unlock key
243  *   - lock ctx -> unlist -> unlock ctx -> lock key -> unbind -> unlock key
244  */
245
246 static inline void spin_lock_if(spinlock_t *lock, int condition)
247 {
248         if (condition)
249                 spin_lock(lock);
250 }
251
252 static inline void spin_unlock_if(spinlock_t *lock, int condition)
253 {
254         if (condition)
255                 spin_unlock(lock);
256 }
257
258 static void ctx_enlist_kr(struct ptlrpc_cli_ctx *ctx, int is_root, int locked)
259 {
260         struct ptlrpc_sec       *sec = ctx->cc_sec;
261         struct gss_sec_keyring  *gsec_kr = sec2gsec_keyring(sec);
262
263         LASSERT(!test_bit(PTLRPC_CTX_CACHED_BIT, &ctx->cc_flags));
264         LASSERT(atomic_read(&ctx->cc_refcount) > 0);
265
266         spin_lock_if(&sec->ps_lock, !locked);
267
268         atomic_inc(&ctx->cc_refcount);
269         set_bit(PTLRPC_CTX_CACHED_BIT, &ctx->cc_flags);
270         hlist_add_head(&ctx->cc_cache, &gsec_kr->gsk_clist);
271         if (is_root)
272                 gsec_kr->gsk_root_ctx = ctx;
273
274         spin_unlock_if(&sec->ps_lock, !locked);
275 }
276
277 /*
278  * Note after this get called, caller should not access ctx again because
279  * it might have been freed, unless caller hold at least one refcount of
280  * the ctx.
281  *
282  * return non-zero if we indeed unlist this ctx.
283  */
284 static int ctx_unlist_kr(struct ptlrpc_cli_ctx *ctx, int locked)
285 {
286         struct ptlrpc_sec       *sec = ctx->cc_sec;
287         struct gss_sec_keyring  *gsec_kr = sec2gsec_keyring(sec);
288
289         /* if hashed bit has gone, leave the job to somebody who is doing it */
290         if (test_and_clear_bit(PTLRPC_CTX_CACHED_BIT, &ctx->cc_flags) == 0)
291                 return 0;
292
293         /* drop ref inside spin lock to prevent race with other operations */
294         spin_lock_if(&sec->ps_lock, !locked);
295
296         if (gsec_kr->gsk_root_ctx == ctx)
297                 gsec_kr->gsk_root_ctx = NULL;
298         hlist_del_init(&ctx->cc_cache);
299         atomic_dec(&ctx->cc_refcount);
300
301         spin_unlock_if(&sec->ps_lock, !locked);
302
303         return 1;
304 }
305
306 /*
307  * Get specific payload. Newer kernels support 4 slots.
308  */
309 static void *
310 key_get_payload(struct key *key, unsigned int index)
311 {
312         void *key_ptr = NULL;
313
314 #ifdef HAVE_KEY_PAYLOAD_DATA_ARRAY
315         key_ptr = key->payload.data[index];
316 #else
317         if (!index)
318                 key_ptr = key->payload.data;
319 #endif
320         return key_ptr;
321 }
322
323 /*
324  * Set specific payload. Newer kernels support 4 slots.
325  */
326 static int key_set_payload(struct key *key, unsigned int index,
327                            struct ptlrpc_cli_ctx *ctx)
328 {
329         int rc = -EINVAL;
330
331 #ifdef HAVE_KEY_PAYLOAD_DATA_ARRAY
332         if (index < 4) {
333                 key->payload.data[index] = ctx;
334 #else
335         if (!index) {
336                 key->payload.data = ctx;
337 #endif
338                 rc = 0;
339         }
340         return rc;
341 }
342
343 /*
344  * bind a key with a ctx together.
345  * caller must hold write lock of the key, as well as ref on key & ctx.
346  */
347 static void bind_key_ctx(struct key *key, struct ptlrpc_cli_ctx *ctx)
348 {
349         LASSERT(atomic_read(&ctx->cc_refcount) > 0);
350         LASSERT(ll_read_key_usage(key) > 0);
351         LASSERT(ctx2gctx_keyring(ctx)->gck_key == NULL);
352         LASSERT(!key_get_payload(key, 0));
353
354         /* at this time context may or may not in list. */
355         key_get(key);
356         atomic_inc(&ctx->cc_refcount);
357         ctx2gctx_keyring(ctx)->gck_key = key;
358         LASSERT(!key_set_payload(key, 0, ctx));
359 }
360
361 /*
362  * unbind a key and a ctx.
363  * caller must hold write lock, as well as a ref of the key.
364  */
365 static void unbind_key_ctx(struct key *key, struct ptlrpc_cli_ctx *ctx)
366 {
367         LASSERT(key_get_payload(key, 0) == ctx);
368         LASSERT(test_bit(PTLRPC_CTX_CACHED_BIT, &ctx->cc_flags) == 0);
369
370         /* must revoke the key, or others may treat it as newly created */
371         key_revoke_locked(key);
372         request_key_unlink(key);
373
374         key_set_payload(key, 0, NULL);
375         ctx2gctx_keyring(ctx)->gck_key = NULL;
376
377         /* once ctx get split from key, the timer is meaningless */
378         ctx_clear_timer_kr(ctx);
379
380         ctx_put_kr(ctx, 1);
381         key_put(key);
382 }
383
384 /*
385  * given a ctx, unbind with its coupled key, if any.
386  * unbind could only be called once, so we don't worry the key be released
387  * by someone else.
388  */
389 static void unbind_ctx_kr(struct ptlrpc_cli_ctx *ctx)
390 {
391         struct key      *key = ctx2gctx_keyring(ctx)->gck_key;
392
393         if (key) {
394                 LASSERT(key_get_payload(key, 0) == ctx);
395
396                 key_get(key);
397                 down_write(&key->sem);
398                 unbind_key_ctx(key, ctx);
399                 up_write(&key->sem);
400                 key_put(key);
401         }
402 }
403
404 /*
405  * given a key, unbind with its coupled ctx, if any.
406  * caller must hold write lock, as well as a ref of the key.
407  */
408 static void unbind_key_locked(struct key *key)
409 {
410         struct ptlrpc_cli_ctx *ctx = key_get_payload(key, 0);
411
412         if (ctx)
413                 unbind_key_ctx(key, ctx);
414 }
415
416 /*
417  * unlist a ctx, and unbind from coupled key
418  */
419 static void kill_ctx_kr(struct ptlrpc_cli_ctx *ctx)
420 {
421         if (ctx_unlist_kr(ctx, 0))
422                 unbind_ctx_kr(ctx);
423 }
424
425 /*
426  * given a key, unlist and unbind with the coupled ctx (if any).
427  * caller must hold write lock, as well as a ref of the key.
428  */
429 static void kill_key_locked(struct key *key)
430 {
431         struct ptlrpc_cli_ctx *ctx = key_get_payload(key, 0);
432
433         if (ctx && ctx_unlist_kr(ctx, 0))
434                 unbind_key_locked(key);
435 }
436
437 /*
438  * caller should hold one ref on contexts in freelist.
439  */
440 static void dispose_ctx_list_kr(struct hlist_head *freelist)
441 {
442         struct hlist_node *next;
443         struct ptlrpc_cli_ctx   *ctx;
444         struct gss_cli_ctx      *gctx;
445
446         hlist_for_each_entry_safe(ctx, next, freelist, cc_cache) {
447                 hlist_del_init(&ctx->cc_cache);
448
449                 /* reverse ctx: update current seq to buddy svcctx if exist.
450                  * ideally this should be done at gss_cli_ctx_finalize(), but
451                  * the ctx destroy could be delayed by:
452                  *  1) ctx still has reference;
453                  *  2) ctx destroy is asynchronous;
454                  * and reverse import call inval_all_ctx() require this be done
455                  * _immediately_ otherwise newly created reverse ctx might copy
456                  * the very old sequence number from svcctx. */
457                 gctx = ctx2gctx(ctx);
458                 if (!rawobj_empty(&gctx->gc_svc_handle) &&
459                     sec_is_reverse(gctx->gc_base.cc_sec)) {
460                         gss_svc_upcall_update_sequence(&gctx->gc_svc_handle,
461                                         (__u32) atomic_read(&gctx->gc_seq));
462                 }
463
464                 /* we need to wakeup waiting reqs here. the context might
465                  * be forced released before upcall finished, then the
466                  * late-arrived downcall can't find the ctx even. */
467                 sptlrpc_cli_ctx_wakeup(ctx);
468
469                 unbind_ctx_kr(ctx);
470                 ctx_put_kr(ctx, 0);
471         }
472 }
473
474 /*
475  * lookup a root context directly in a sec, return root ctx with a
476  * reference taken or NULL.
477  */
478 static
479 struct ptlrpc_cli_ctx * sec_lookup_root_ctx_kr(struct ptlrpc_sec *sec)
480 {
481         struct gss_sec_keyring  *gsec_kr = sec2gsec_keyring(sec);
482         struct ptlrpc_cli_ctx   *ctx = NULL;
483         time64_t now = ktime_get_real_seconds();
484
485         spin_lock(&sec->ps_lock);
486
487         ctx = gsec_kr->gsk_root_ctx;
488
489         if (ctx == NULL && unlikely(sec_is_reverse(sec))) {
490                 struct ptlrpc_cli_ctx   *tmp;
491
492                 /* For reverse context, browse list and pick the one with
493                  * shortest expire time and that has not expired yet.
494                  * This one is most likely to have an established peer context
495                  * on client side.
496                  */
497                 hlist_for_each_entry(tmp, &gsec_kr->gsk_clist, cc_cache) {
498                         if (ctx == NULL || ctx->cc_expire == 0 ||
499                             (tmp->cc_expire > now &&
500                              tmp->cc_expire < ctx->cc_expire) ||
501                             (ctx->cc_expire < now &&
502                              tmp->cc_expire > ctx->cc_expire)) {
503                                 ctx = tmp;
504                                 /* promote to be root_ctx */
505                                 gsec_kr->gsk_root_ctx = ctx;
506                         }
507                 }
508         }
509
510         if (ctx) {
511                 LASSERT(atomic_read(&ctx->cc_refcount) > 0);
512                 LASSERT(!hlist_empty(&gsec_kr->gsk_clist));
513                 atomic_inc(&ctx->cc_refcount);
514         }
515
516         spin_unlock(&sec->ps_lock);
517
518         return ctx;
519 }
520
521 #define RVS_CTX_EXPIRE_NICE    (10)
522
523 static
524 void rvs_sec_install_root_ctx_kr(struct ptlrpc_sec *sec,
525                                  struct ptlrpc_cli_ctx *new_ctx,
526                                  struct key *key)
527 {
528         struct gss_sec_keyring *gsec_kr = sec2gsec_keyring(sec);
529         struct ptlrpc_cli_ctx *ctx;
530         time64_t now;
531
532         ENTRY;
533         LASSERT(sec_is_reverse(sec));
534
535         spin_lock(&sec->ps_lock);
536
537         now = ktime_get_real_seconds();
538
539         /* set all existing ctxs short expiry */
540         hlist_for_each_entry(ctx, &gsec_kr->gsk_clist, cc_cache) {
541                 if (ctx->cc_expire > now + RVS_CTX_EXPIRE_NICE) {
542                         ctx->cc_early_expire = 1;
543                         ctx->cc_expire = now + RVS_CTX_EXPIRE_NICE;
544                 }
545         }
546
547         /* if there's root_ctx there, instead obsolete the current
548          * immediately, we leave it continue operating for a little while.
549          * hopefully when the first backward rpc with newest ctx send out,
550          * the client side already have the peer ctx well established. */
551         ctx_enlist_kr(new_ctx, gsec_kr->gsk_root_ctx ? 0 : 1, 1);
552
553         if (key)
554                 bind_key_ctx(key, new_ctx);
555
556         spin_unlock(&sec->ps_lock);
557 }
558
559 static void construct_key_desc(void *buf, int bufsize,
560                                struct ptlrpc_sec *sec, uid_t uid)
561 {
562         snprintf(buf, bufsize, "%d@%x", uid, sec->ps_id);
563         ((char *)buf)[bufsize - 1] = '\0';
564 }
565
566 /****************************************
567  * sec apis                             *
568  ****************************************/
569
570 static
571 struct ptlrpc_sec * gss_sec_create_kr(struct obd_import *imp,
572                                       struct ptlrpc_svc_ctx *svcctx,
573                                       struct sptlrpc_flavor *sf)
574 {
575         struct gss_sec_keyring  *gsec_kr;
576         ENTRY;
577
578         OBD_ALLOC(gsec_kr, sizeof(*gsec_kr));
579         if (gsec_kr == NULL)
580                 RETURN(NULL);
581
582         INIT_HLIST_HEAD(&gsec_kr->gsk_clist);
583         gsec_kr->gsk_root_ctx = NULL;
584         mutex_init(&gsec_kr->gsk_root_uc_lock);
585 #ifdef HAVE_KEYRING_UPCALL_SERIALIZED
586         mutex_init(&gsec_kr->gsk_uc_lock);
587 #endif
588
589         if (gss_sec_create_common(&gsec_kr->gsk_base, &gss_policy_keyring,
590                                   imp, svcctx, sf))
591                 goto err_free;
592
593         if (svcctx != NULL &&
594             sec_install_rctx_kr(&gsec_kr->gsk_base.gs_base, svcctx)) {
595                 gss_sec_destroy_common(&gsec_kr->gsk_base);
596                 goto err_free;
597         }
598
599         RETURN(&gsec_kr->gsk_base.gs_base);
600
601 err_free:
602         OBD_FREE(gsec_kr, sizeof(*gsec_kr));
603         RETURN(NULL);
604 }
605
606 static
607 void gss_sec_destroy_kr(struct ptlrpc_sec *sec)
608 {
609         struct gss_sec          *gsec = sec2gsec(sec);
610         struct gss_sec_keyring  *gsec_kr = sec2gsec_keyring(sec);
611
612         CDEBUG(D_SEC, "destroy %s@%p\n", sec->ps_policy->sp_name, sec);
613
614         LASSERT(atomic_read(&sec->ps_nctx) == 0);
615         LASSERT(hlist_empty(&gsec_kr->gsk_clist));
616         LASSERT(gsec_kr->gsk_root_ctx == NULL);
617
618         gss_sec_destroy_common(gsec);
619
620         OBD_FREE(gsec_kr, sizeof(*gsec_kr));
621 }
622
623 static inline int user_is_root(struct ptlrpc_sec *sec, struct vfs_cred *vcred)
624 {
625         /* except the ROOTONLY flag, treat it as root user only if real uid
626          * is 0, euid/fsuid being 0 are handled as setuid scenarios */
627         if (sec_is_rootonly(sec) || (vcred->vc_uid == 0))
628                 return 1;
629         else
630                 return 0;
631 }
632
633 /*
634  * When lookup_user_key is available use the kernel API rather than directly
635  * accessing the uid_keyring and session_keyring via the current process
636  * credentials.
637  */
638 #ifdef HAVE_LOOKUP_USER_KEY
639
640 #ifdef HAVE_KEY_NEED_UNLINK
641 /* from Linux security/keys/internal.h: */
642 #  ifndef KEY_LOOKUP_PARTIAL
643 #    define KEY_LOOKUP_PARTIAL 0x2
644 #  endif
645 #else
646 #  define KEY_NEED_UNLINK 0
647 #  ifndef KEY_LOOKUP_FOR_UNLINK
648 #    define KEY_LOOKUP_FOR_UNLINK 0x4
649 #  endif
650 #  define KEY_LOOKUP_PARTIAL KEY_LOOKUP_FOR_UNLINK
651 #endif /* HAVE_KEY_NEED_UNLINK */
652
653 static struct key *_user_key(key_serial_t id)
654 {
655         key_ref_t ref;
656
657         might_sleep();
658         ref = lookup_user_key(id, KEY_LOOKUP_PARTIAL, KEY_NEED_UNLINK);
659         if (IS_ERR(ref))
660                 return NULL;
661         return key_ref_to_ptr(ref);
662 }
663
664 static inline struct key *get_user_session_keyring(const struct cred *cred)
665 {
666         return _user_key(KEY_SPEC_USER_SESSION_KEYRING);
667 }
668
669 static inline struct key *get_user_keyring(const struct cred *cred)
670 {
671         return _user_key(KEY_SPEC_USER_KEYRING);
672 }
673
674 static inline struct key *get_session_keyring(const struct cred *cred)
675 {
676         return _user_key(KEY_SPEC_SESSION_KEYRING);
677 }
678 #else
679 static inline struct key *get_user_session_keyring(const struct cred *cred)
680 {
681         return key_get(cred->user->session_keyring);
682 }
683
684 static inline struct key *get_user_keyring(const struct cred *cred)
685 {
686         return key_get(cred->user->uid_keyring);
687 }
688
689 static inline struct key *get_session_keyring(const struct cred *cred)
690 {
691         return key_get(cred->session_keyring);
692 }
693 #endif
694
695 /*
696  * unlink request key from it's ring, which is linked during request_key().
697  * sadly, we have to 'guess' which keyring it's linked to.
698  */
699 static void request_key_unlink(struct key *key)
700 {
701         struct cred *cred = (struct cred *)current_cred(), *new_cred = NULL;
702         kuid_t kuid_orig = current_cred()->user->uid;
703 #ifdef HAVE_USER_UID_KEYRING
704         struct key *root_uid_keyring = NULL;
705 #endif
706         const struct cred *old_cred = NULL;
707         struct key *ring = NULL;
708         uid_t uid, key_uid;
709         int res;
710
711         uid = from_kuid(current_user_ns(), kuid_orig);
712         key_uid = from_kuid(&init_user_ns, key->uid);
713         /* unlink key with user's creds if it's a user key */
714         if (key_uid != uid) {
715                 new_cred = prepare_creds();
716                 if (new_cred == NULL)
717                         goto search;
718
719                 new_cred->uid = key->uid;
720                 new_cred->user->uid = key->uid;
721                 new_cred->user_ns = &init_user_ns;
722 #ifdef HAVE_USER_UID_KEYRING
723                 root_uid_keyring = current_cred()->user->uid_keyring;
724                 new_cred->user->uid_keyring = NULL;
725 #endif
726                 old_cred = override_creds(new_cred);
727                 cred = new_cred;
728         }
729
730         /* User keys are linked to the user keyring. So get it now. */
731         if (key_uid) {
732                 /* Getting a key(ring) normally increases its refcount by 1.
733                  * But if we overrode creds above, calling get_user_keyring()
734                  * will add one more ref, because of the user switch.
735                  */
736                 ring = get_user_keyring(cred);
737                 goto do_unlink;
738         }
739
740 search:
741         switch (cred->jit_keyring) {
742         case KEY_REQKEY_DEFL_DEFAULT:
743         case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
744 #ifdef HAVE_GET_REQUEST_KEY_AUTH
745                 if (cred->request_key_auth) {
746                         struct request_key_auth *rka;
747                         struct key *authkey = cred->request_key_auth;
748
749                         down_read(&authkey->sem);
750                         rka = get_request_key_auth(authkey);
751                         if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags))
752                                 ring = key_get(rka->dest_keyring);
753                         up_read(&authkey->sem);
754                         if (ring)
755                                 break;
756                 }
757 #endif
758                 fallthrough;
759         case KEY_REQKEY_DEFL_THREAD_KEYRING:
760                 ring = key_get(cred->thread_keyring);
761                 if (ring)
762                         break;
763                 fallthrough;
764         case KEY_REQKEY_DEFL_PROCESS_KEYRING:
765                 ring = key_get(cred->process_keyring);
766                 if (ring)
767                         break;
768                 fallthrough;
769         case KEY_REQKEY_DEFL_SESSION_KEYRING:
770                 rcu_read_lock();
771                 ring = key_get(rcu_dereference(cred->session_keyring));
772                 rcu_read_unlock();
773                 if (ring)
774                         break;
775                 fallthrough;
776         case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
777                 ring = get_user_session_keyring(cred);
778                 break;
779         case KEY_REQKEY_DEFL_USER_KEYRING:
780                 ring = get_user_keyring(cred);
781                 break;
782         case KEY_REQKEY_DEFL_GROUP_KEYRING:
783         default:
784                 LBUG();
785         }
786
787 do_unlink:
788         if (ring) {
789                 res = key_unlink(ring, key);
790                 CDEBUG(D_SEC,
791                        "Unlink key %08x (%p) from keyring %08x: %d\n",
792                        key->serial, key, ring->serial, res);
793                 /* matches key_get()/get_user_keyring() above */
794                 key_put(ring);
795         } else {
796                 CDEBUG(D_SEC,
797                        "Missing keyring, key %08x (%p) could not be unlinked, ignored\n",
798                        key->serial, key);
799         }
800
801         if (old_cred) {
802                 revert_creds(old_cred);
803                 put_cred(new_cred);
804                 current_cred()->user->uid = kuid_orig;
805 #ifdef HAVE_USER_UID_KEYRING
806                 /* We are switching creds back, so need to drop ref on keyring
807                  * for kernel implementation based on user keyring pinned from
808                  * the user_struct struct.
809                  */
810                 key_put(ring);
811                 if (root_uid_keyring)
812                         current_cred()->user->uid_keyring = root_uid_keyring;
813 #endif
814         }
815 }
816
817 /**
818  * \retval a valid context on success
819  * \retval -ev error number or NULL on error
820  */
821 static
822 struct ptlrpc_cli_ctx * gss_sec_lookup_ctx_kr(struct ptlrpc_sec *sec,
823                                               struct vfs_cred *vcred,
824                                               int create, int remove_dead)
825 {
826         struct obd_import *imp = sec->ps_import;
827         struct gss_sec_keyring *gsec_kr = sec2gsec_keyring(sec);
828         struct ptlrpc_cli_ctx *ctx = NULL;
829         unsigned int is_root = 0, create_new = 0;
830         const struct cred *old_cred = NULL;
831         struct cred *new_cred = NULL;
832         struct key *key;
833         char desc[24];
834         char *coinfo;
835         int coinfo_size;
836         const char *sec_part_flags = "";
837         char svc_flag = '-';
838         pid_t caller_pid;
839         struct lnet_nid primary;
840         ENTRY;
841
842         LASSERT(imp != NULL);
843
844         is_root = user_is_root(sec, vcred);
845
846         /* a little bit optimization for root context */
847         if (is_root) {
848                 ctx = sec_lookup_root_ctx_kr(sec);
849                 /*
850                  * Only lookup directly for REVERSE sec, which should
851                  * always succeed.
852                  */
853                 if (ctx || sec_is_reverse(sec))
854                         RETURN(ctx);
855         }
856
857         if (!create)
858                 RETURN(ERR_PTR(-ENODATA));
859
860         /* for root context, obtain lock and check again, this time hold
861          * the root upcall lock, make sure nobody else populated new root
862          * context after last check.
863          */
864         if (is_root) {
865                 mutex_lock(&gsec_kr->gsk_root_uc_lock);
866
867                 ctx = sec_lookup_root_ctx_kr(sec);
868                 if (ctx)
869                         goto out;
870
871                 /* update reverse handle for root user */
872                 sec2gsec(sec)->gs_rvs_hdl = gss_get_next_ctx_index();
873
874                 switch (sec->ps_part) {
875                 case LUSTRE_SP_MDT:
876                         sec_part_flags = "m";
877                         break;
878                 case LUSTRE_SP_OST:
879                         sec_part_flags = "o";
880                         break;
881                 case LUSTRE_SP_MGC:
882                         sec_part_flags = "rmo";
883                         break;
884                 case LUSTRE_SP_CLI:
885                         sec_part_flags = "r";
886                         break;
887                 case LUSTRE_SP_MGS:
888                 default:
889                         LBUG();
890                 }
891
892                 switch (SPTLRPC_FLVR_SVC(sec->ps_flvr.sf_rpc)) {
893                 case SPTLRPC_SVC_NULL:
894                         svc_flag = 'n';
895                         break;
896                 case SPTLRPC_SVC_AUTH:
897                         svc_flag = 'a';
898                         break;
899                 case SPTLRPC_SVC_INTG:
900                         svc_flag = 'i';
901                         break;
902                 case SPTLRPC_SVC_PRIV:
903                         svc_flag = 'p';
904                         break;
905                 default:
906                         LBUG();
907                 }
908         }
909
910         /* in case of setuid, key will be constructed as owner of fsuid/fsgid,
911          * but we do authentication based on real uid/gid. the key permission
912          * bits will be exactly as POS_ALL, so only processes who subscribed
913          * this key could have the access, although the quota might be counted
914          * on others (fsuid/fsgid).
915          *
916          * keyring will use fsuid/fsgid as upcall parameters, so we have to
917          * encode real uid/gid into callout info.
918          */
919
920         /* But first we need to make sure the obd type is supported */
921         if (strcmp(imp->imp_obd->obd_type->typ_name, LUSTRE_MDC_NAME) &&
922             strcmp(imp->imp_obd->obd_type->typ_name, LUSTRE_OSC_NAME) &&
923             strcmp(imp->imp_obd->obd_type->typ_name, LUSTRE_MGC_NAME) &&
924             strcmp(imp->imp_obd->obd_type->typ_name, LUSTRE_LWP_NAME) &&
925             strcmp(imp->imp_obd->obd_type->typ_name, LUSTRE_OSP_NAME)) {
926                 CERROR("obd %s is not a supported device\n",
927                        imp->imp_obd->obd_name);
928                 GOTO(out, ctx = NULL);
929         }
930
931         construct_key_desc(desc, sizeof(desc), sec, vcred->vc_uid);
932
933         /* callout info format:
934          * secid:mech:uid:gid:sec_flags:svc_flag:svc_type:peer_nid:target_uuid:
935          * self_nid:pid
936          */
937         coinfo_size = sizeof(struct obd_uuid) + MAX_OBD_NAME + 64;
938         OBD_ALLOC(coinfo, coinfo_size);
939         if (coinfo == NULL)
940                 goto out;
941
942         /* Last callout parameter is pid of process whose namespace will be used
943          * for credentials' retrieval.
944          */
945         if (gss_check_upcall_ns) {
946                 /* For user's credentials (in which case sec_part_flags is
947                  * empty), use current PID instead of import's reference
948                  * PID to get reference namespace.
949                  */
950                 if (sec_part_flags[0] == '\0')
951                         caller_pid = current->pid;
952                 else
953                         caller_pid = imp->imp_sec_refpid;
954         } else {
955                 /* Do not switch namespace in gss keyring upcall. */
956                 caller_pid = 0;
957         }
958         primary = imp->imp_connection->c_self;
959         LNetPrimaryNID(&primary);
960
961         /* FIXME !! Needs to support larger NIDs */
962         snprintf(coinfo, coinfo_size, "%d:%s:%u:%u:%s:%c:%d:%#llx:%s:%#llx:%d",
963                  sec->ps_id, sec2gsec(sec)->gs_mech->gm_name,
964                  vcred->vc_uid, vcred->vc_gid,
965                  sec_part_flags, svc_flag, import_to_gss_svc(imp),
966                  lnet_nid_to_nid4(&imp->imp_connection->c_peer.nid),
967                  imp->imp_obd->obd_name,
968                  lnet_nid_to_nid4(&primary),
969                  caller_pid);
970
971         CDEBUG(D_SEC, "requesting key for %s\n", desc);
972
973         if (vcred->vc_uid) {
974                 /* If the session keyring is revoked, it must not be used by
975                  * request_key(), otherwise we would get -EKEYREVOKED and
976                  * the user keyring would not even be searched.
977                  * So prepare new creds with no session keyring.
978                  */
979                 if (current_cred()->session_keyring &&
980                     test_bit(KEY_FLAG_REVOKED,
981                              &current_cred()->session_keyring->flags)) {
982                         new_cred = prepare_creds();
983                         if (new_cred) {
984                                 new_cred->session_keyring = NULL;
985                                 old_cred = override_creds(new_cred);
986                         }
987                 }
988         }
989
990         keyring_upcall_lock(gsec_kr);
991         key = request_key(&gss_key_type, desc, coinfo);
992         keyring_upcall_unlock(gsec_kr);
993         if (old_cred) {
994                 revert_creds(old_cred);
995                 put_cred(new_cred);
996         }
997
998         OBD_FREE(coinfo, coinfo_size);
999
1000         if (IS_ERR(key)) {
1001                 CERROR("%s: request key failed for uid %d: rc = %ld\n",
1002                        imp->imp_obd->obd_name, vcred->vc_uid,
1003                        PTR_ERR(key));
1004                 ctx = ERR_CAST(key);
1005                 goto out;
1006         }
1007         CDEBUG(D_SEC, "obtained key %08x for %s\n", key->serial, desc);
1008
1009         /* We want user keys to be linked to the user keyring (see call to
1010          * keyctl_instantiate() from prepare_and_instantiate() in userspace).
1011          * But internally request_key() tends to also link the key to the
1012          * session keyring. So do our best to avoid that by trying to unlink
1013          * the key from the session keyring right now. It will spare us pain
1014          * when we need to remove the key later on.
1015          */
1016         if (!is_root && current_cred()->session_keyring) {
1017                 key_get(current_cred()->session_keyring);
1018                 (void)key_unlink(current_cred()->session_keyring, key);
1019                 key_put(current_cred()->session_keyring);
1020         }
1021         /* once payload.data was pointed to a ctx, it never changes until
1022          * we de-associate them; but parallel request_key() may return
1023          * a key with payload.data == NULL at the same time. so we still
1024          * need wirtelock of key->sem to serialize them.
1025          */
1026         down_write(&key->sem);
1027
1028         ctx = key_get_payload(key, 0);
1029         if (likely(ctx)) {
1030                 LASSERT(atomic_read(&ctx->cc_refcount) >= 1);
1031                 LASSERT(ctx2gctx_keyring(ctx)->gck_key == key);
1032                 LASSERT(ll_read_key_usage(key) >= 2);
1033
1034                 /* simply take a ref and return. it's upper layer's
1035                  * responsibility to detect & replace dead ctx.
1036                  */
1037                 atomic_inc(&ctx->cc_refcount);
1038         } else {
1039                 /* pre initialization with a cli_ctx. this can't be done in
1040                  * key_instantiate() because we'v no enough information
1041                  * there.
1042                  */
1043                 ctx = ctx_create_kr(sec, vcred);
1044                 if (ctx != NULL) {
1045                         ctx_enlist_kr(ctx, is_root, 0);
1046                         bind_key_ctx(key, ctx);
1047
1048                         ctx_start_timer_kr(ctx, KEYRING_UPCALL_TIMEOUT);
1049
1050                         CDEBUG(D_SEC, "installed key %p <-> ctx %p (sec %p)\n",
1051                                key, ctx, sec);
1052                 } else {
1053                         /* we'd prefer to call key_revoke(), but we more like
1054                          * to revoke it within this key->sem locked period.
1055                          */
1056                         CDEBUG(D_SEC, "revoking key %08x (%p)\n",
1057                                key->serial, key);
1058                         key_revoke_locked(key);
1059                 }
1060
1061                 create_new = 1;
1062         }
1063
1064         up_write(&key->sem);
1065
1066         if (is_root && create_new)
1067                 request_key_unlink(key);
1068
1069         key_put(key);
1070 out:
1071         if (is_root)
1072                 mutex_unlock(&gsec_kr->gsk_root_uc_lock);
1073         RETURN(ctx);
1074 }
1075
1076 static
1077 void gss_sec_release_ctx_kr(struct ptlrpc_sec *sec,
1078                             struct ptlrpc_cli_ctx *ctx,
1079                             int sync)
1080 {
1081         LASSERT(atomic_read(&sec->ps_refcount) > 0);
1082         LASSERT(atomic_read(&ctx->cc_refcount) == 0);
1083         ctx_release_kr(ctx, sync);
1084 }
1085
1086 /*
1087  * flush context of normal user, we must resort to keyring itself to find out
1088  * contexts which belong to me.
1089  *
1090  * Note here we suppose only to flush _my_ context, the "uid" will
1091  * be ignored in the search.
1092  */
1093 static
1094 void flush_user_ctx_cache_kr(struct ptlrpc_sec *sec,
1095                              uid_t uid,
1096                              int grace, int force)
1097 {
1098         struct key              *key;
1099         char                     desc[24];
1100
1101         /* nothing to do for reverse or rootonly sec */
1102         if (sec_is_reverse(sec) || sec_is_rootonly(sec))
1103                 return;
1104
1105         construct_key_desc(desc, sizeof(desc), sec, uid);
1106
1107         /* there should be only one valid key, but we put it in the
1108          * loop in case of any weird cases */
1109         for (;;) {
1110                 key = request_key(&gss_key_type, desc, NULL);
1111                 if (IS_ERR(key)) {
1112                         CDEBUG(D_SEC, "No more key found for current user\n");
1113                         break;
1114                 }
1115
1116                 down_write(&key->sem);
1117
1118                 kill_key_locked(key);
1119
1120                 /* kill_key_locked() should usually revoke the key, but we
1121                  * revoke it again to make sure, e.g. some case the key may
1122                  * not well coupled with a context. */
1123                 key_revoke_locked(key);
1124
1125                 up_write(&key->sem);
1126                 key_put(key);
1127         }
1128 }
1129
1130 /*
1131  * flush context of root or all, we iterate through the list.
1132  */
1133 static
1134 void flush_spec_ctx_cache_kr(struct ptlrpc_sec *sec, uid_t uid, int grace,
1135                              int force)
1136 {
1137         struct gss_sec_keyring  *gsec_kr;
1138         struct hlist_head        freelist = HLIST_HEAD_INIT;
1139         struct hlist_node *next;
1140         struct ptlrpc_cli_ctx   *ctx;
1141         ENTRY;
1142
1143         gsec_kr = sec2gsec_keyring(sec);
1144
1145         spin_lock(&sec->ps_lock);
1146         hlist_for_each_entry_safe(ctx, next, &gsec_kr->gsk_clist,
1147                                   cc_cache) {
1148                 LASSERT(atomic_read(&ctx->cc_refcount) > 0);
1149
1150                 if (uid != -1 && uid != ctx->cc_vcred.vc_uid)
1151                         continue;
1152
1153                 /* at this moment there's at least 2 base reference:
1154                  * key association and in-list. */
1155                 if (atomic_read(&ctx->cc_refcount) > 2) {
1156                         if (!force)
1157                                 continue;
1158                         CWARN("flush busy ctx %p(%u->%s, extra ref %d)\n",
1159                               ctx, ctx->cc_vcred.vc_uid,
1160                               sec2target_str(ctx->cc_sec),
1161                               atomic_read(&ctx->cc_refcount) - 2);
1162                 }
1163
1164                 set_bit(PTLRPC_CTX_DEAD_BIT, &ctx->cc_flags);
1165                 if (!grace)
1166                         clear_bit(PTLRPC_CTX_UPTODATE_BIT, &ctx->cc_flags);
1167
1168                 atomic_inc(&ctx->cc_refcount);
1169
1170                 if (ctx_unlist_kr(ctx, 1)) {
1171                         hlist_add_head(&ctx->cc_cache, &freelist);
1172                 } else {
1173                         LASSERT(atomic_read(&ctx->cc_refcount) >= 2);
1174                         atomic_dec(&ctx->cc_refcount);
1175                 }
1176         }
1177         spin_unlock(&sec->ps_lock);
1178
1179         dispose_ctx_list_kr(&freelist);
1180         EXIT;
1181 }
1182
1183 static
1184 int gss_sec_flush_ctx_cache_kr(struct ptlrpc_sec *sec,
1185                                uid_t uid, int grace, int force)
1186 {
1187         ENTRY;
1188
1189         CDEBUG(D_SEC, "sec %p(%d, nctx %d), uid %d, grace %d, force %d\n",
1190                sec, atomic_read(&sec->ps_refcount),
1191                atomic_read(&sec->ps_nctx),
1192                uid, grace, force);
1193
1194         if (uid != -1 && uid != 0)
1195                 flush_user_ctx_cache_kr(sec, uid, grace, force);
1196         else
1197                 flush_spec_ctx_cache_kr(sec, uid, grace, force);
1198
1199         RETURN(0);
1200 }
1201
1202 static
1203 void gss_sec_gc_ctx_kr(struct ptlrpc_sec *sec)
1204 {
1205         struct gss_sec_keyring  *gsec_kr = sec2gsec_keyring(sec);
1206         struct hlist_head       freelist = HLIST_HEAD_INIT;
1207         struct hlist_node *next;
1208         struct ptlrpc_cli_ctx   *ctx;
1209         ENTRY;
1210
1211         CDEBUG(D_SEC, "running gc\n");
1212
1213         spin_lock(&sec->ps_lock);
1214         hlist_for_each_entry_safe(ctx, next, &gsec_kr->gsk_clist,
1215                                   cc_cache) {
1216                 LASSERT(atomic_read(&ctx->cc_refcount) > 0);
1217
1218                 atomic_inc(&ctx->cc_refcount);
1219
1220                 if (cli_ctx_check_death(ctx) && ctx_unlist_kr(ctx, 1)) {
1221                         hlist_add_head(&ctx->cc_cache, &freelist);
1222                         CWARN("unhashed ctx %p\n", ctx);
1223                 } else {
1224                         LASSERT(atomic_read(&ctx->cc_refcount) >= 2);
1225                         atomic_dec(&ctx->cc_refcount);
1226                 }
1227         }
1228         spin_unlock(&sec->ps_lock);
1229
1230         dispose_ctx_list_kr(&freelist);
1231         EXIT;
1232 }
1233
1234 static
1235 int gss_sec_display_kr(struct ptlrpc_sec *sec, struct seq_file *seq)
1236 {
1237         struct gss_sec_keyring *gsec_kr = sec2gsec_keyring(sec);
1238         struct hlist_node *next;
1239         struct ptlrpc_cli_ctx *ctx;
1240         struct gss_cli_ctx *gctx;
1241         struct ptlrpc_connection *conn;
1242         time64_t now = ktime_get_real_seconds();
1243
1244         ENTRY;
1245         spin_lock(&sec->ps_lock);
1246         hlist_for_each_entry_safe(ctx, next, &gsec_kr->gsk_clist,
1247                                   cc_cache) {
1248                 struct key *key;
1249                 char flags_str[40];
1250                 char mech[40];
1251
1252                 gctx = ctx2gctx(ctx);
1253                 key = ctx2gctx_keyring(ctx)->gck_key;
1254                 if (sec_is_reverse(sec) &&
1255                     ctx->cc_sec && ctx->cc_sec->ps_import &&
1256                     ctx->cc_sec->ps_import->imp_connection)
1257                         conn = ctx->cc_sec->ps_import->imp_connection;
1258                 else
1259                         conn = NULL;
1260
1261                 gss_cli_ctx_flags2str(ctx->cc_flags,
1262                                       flags_str, sizeof(flags_str));
1263
1264                 if (gctx->gc_mechctx)
1265                         lgss_display(gctx->gc_mechctx, mech, sizeof(mech));
1266                 else
1267                         snprintf(mech, sizeof(mech), "N/A");
1268                 mech[sizeof(mech) - 1] = '\0';
1269
1270                 seq_printf(seq,
1271                            "- { %s%s%suid: %u, ctxref: %d, expire: %lld, delta: %lld, flags: [%s], seq: %d, win: %u, key: %08x, keyref: %d, hdl: \"%#llx:%#llx\", mech: \"%s\" }\n",
1272                            conn ? "peer_nid: " : "",
1273                            conn ? libcfs_nidstr(&conn->c_peer.nid) : "",
1274                            conn ? ", " : "",
1275                            ctx->cc_vcred.vc_uid, atomic_read(&ctx->cc_refcount),
1276                            ctx->cc_expire,
1277                            ctx->cc_expire ?  ctx->cc_expire - now : 0,
1278                            flags_str, atomic_read(&gctx->gc_seq),
1279                            gctx->gc_win, key ? key->serial : 0,
1280                            key ? ll_read_key_usage(key) : 0,
1281                            gss_handle_to_u64(&gctx->gc_handle),
1282                            gss_handle_to_u64(&gctx->gc_svc_handle),
1283                            mech);
1284         }
1285         spin_unlock(&sec->ps_lock);
1286
1287         RETURN(0);
1288 }
1289
1290 /****************************************
1291  * cli_ctx apis                         *
1292  ****************************************/
1293
1294 static
1295 int gss_cli_ctx_refresh_kr(struct ptlrpc_cli_ctx *ctx)
1296 {
1297         /* upcall is already on the way */
1298         struct gss_cli_ctx *gctx = ctx ? ctx2gctx(ctx) : NULL;
1299
1300         /* record latest sequence number in buddy svcctx */
1301         if (gctx && !rawobj_empty(&gctx->gc_svc_handle) &&
1302             sec_is_reverse(gctx->gc_base.cc_sec)) {
1303                 return gss_svc_upcall_update_sequence(&gctx->gc_svc_handle,
1304                                              (__u32)atomic_read(&gctx->gc_seq));
1305         }
1306         return 0;
1307 }
1308
1309 static
1310 int gss_cli_ctx_validate_kr(struct ptlrpc_cli_ctx *ctx)
1311 {
1312         LASSERT(atomic_read(&ctx->cc_refcount) > 0);
1313         LASSERT(ctx->cc_sec);
1314
1315         if (cli_ctx_check_death(ctx)) {
1316                 kill_ctx_kr(ctx);
1317                 return 1;
1318         }
1319
1320         if (cli_ctx_is_ready(ctx))
1321                 return 0;
1322         return 1;
1323 }
1324
1325 static
1326 void gss_cli_ctx_die_kr(struct ptlrpc_cli_ctx *ctx, int grace)
1327 {
1328         LASSERT(atomic_read(&ctx->cc_refcount) > 0);
1329         LASSERT(ctx->cc_sec);
1330
1331         cli_ctx_expire(ctx);
1332         kill_ctx_kr(ctx);
1333 }
1334
1335 /****************************************
1336  * (reverse) service                    *
1337  ****************************************/
1338
1339 /*
1340  * reverse context could have nothing to do with keyrings. here we still keep
1341  * the version which bind to a key, for future reference.
1342  */
1343 #define HAVE_REVERSE_CTX_NOKEY
1344
1345 #ifdef HAVE_REVERSE_CTX_NOKEY
1346
1347 static
1348 int sec_install_rctx_kr(struct ptlrpc_sec *sec,
1349                         struct ptlrpc_svc_ctx *svc_ctx)
1350 {
1351         struct ptlrpc_cli_ctx *cli_ctx;
1352         struct vfs_cred vcred = { .vc_uid = 0 };
1353         int rc;
1354
1355         LASSERT(sec);
1356         LASSERT(svc_ctx);
1357
1358         cli_ctx = ctx_create_kr(sec, &vcred);
1359         if (cli_ctx == NULL)
1360                 return -ENOMEM;
1361
1362         rc = gss_copy_rvc_cli_ctx(cli_ctx, svc_ctx);
1363         if (rc) {
1364                 CERROR("failed copy reverse cli ctx: %d\n", rc);
1365
1366                 ctx_put_kr(cli_ctx, 1);
1367                 return rc;
1368         }
1369
1370         rvs_sec_install_root_ctx_kr(sec, cli_ctx, NULL);
1371
1372         ctx_put_kr(cli_ctx, 1);
1373
1374         return 0;
1375 }
1376
1377 #else /* ! HAVE_REVERSE_CTX_NOKEY */
1378
1379 static
1380 int sec_install_rctx_kr(struct ptlrpc_sec *sec,
1381                         struct ptlrpc_svc_ctx *svc_ctx)
1382 {
1383         struct ptlrpc_cli_ctx *cli_ctx = NULL;
1384         struct key *key;
1385         struct vfs_cred vcred = { .vc_uid = 0 };
1386         char desc[64];
1387         int rc;
1388
1389         LASSERT(sec);
1390         LASSERT(svc_ctx);
1391         CWARN("called\n");
1392
1393         construct_key_desc(desc, sizeof(desc), sec, 0);
1394
1395         key = key_alloc(&gss_key_type, desc, 0, 0,
1396                         KEY_POS_ALL | KEY_USR_ALL, 1);
1397         if (IS_ERR(key)) {
1398                 CERROR("failed to alloc key: %ld\n", PTR_ERR(key));
1399                 return PTR_ERR(key);
1400         }
1401
1402         rc = key_instantiate_and_link(key, NULL, 0, NULL, NULL);
1403         if (rc) {
1404                 CERROR("failed to instantiate key: %d\n", rc);
1405                 goto err_revoke;
1406         }
1407
1408         down_write(&key->sem);
1409
1410         LASSERT(!key_get_payload(key, 0));
1411
1412         cli_ctx = ctx_create_kr(sec, &vcred);
1413         if (cli_ctx == NULL) {
1414                 rc = -ENOMEM;
1415                 goto err_up;
1416         }
1417
1418         rc = gss_copy_rvc_cli_ctx(cli_ctx, svc_ctx);
1419         if (rc) {
1420                 CERROR("failed copy reverse cli ctx: %d\n", rc);
1421                 goto err_put;
1422         }
1423
1424         rvs_sec_install_root_ctx_kr(sec, cli_ctx, key);
1425
1426         ctx_put_kr(cli_ctx, 1);
1427         up_write(&key->sem);
1428
1429         rc = 0;
1430         CWARN("ok!\n");
1431 out:
1432         key_put(key);
1433         return rc;
1434
1435 err_put:
1436         ctx_put_kr(cli_ctx, 1);
1437 err_up:
1438         up_write(&key->sem);
1439 err_revoke:
1440         key_revoke(key);
1441         goto out;
1442 }
1443
1444 #endif /* HAVE_REVERSE_CTX_NOKEY */
1445
1446 /****************************************
1447  * service apis                         *
1448  ****************************************/
1449
1450 static
1451 int gss_svc_accept_kr(struct ptlrpc_request *req)
1452 {
1453         return gss_svc_accept(&gss_policy_keyring, req);
1454 }
1455
1456 static
1457 int gss_svc_install_rctx_kr(struct obd_import *imp,
1458                             struct ptlrpc_svc_ctx *svc_ctx)
1459 {
1460         struct ptlrpc_sec *sec;
1461         int                rc;
1462
1463         sec = sptlrpc_import_sec_ref(imp);
1464         LASSERT(sec);
1465
1466         rc = sec_install_rctx_kr(sec, svc_ctx);
1467         sptlrpc_sec_put(sec);
1468
1469         return rc;
1470 }
1471
1472 /****************************************
1473  * key apis                             *
1474  ****************************************/
1475
1476 static
1477 #ifdef HAVE_KEY_TYPE_INSTANTIATE_2ARGS
1478 int gss_kt_instantiate(struct key *key, struct key_preparsed_payload *prep)
1479 {
1480         const void *data = prep->data;
1481         size_t datalen = prep->datalen;
1482 #else
1483 int gss_kt_instantiate(struct key *key, const void *data, size_t datalen)
1484 {
1485 #endif
1486         struct key *keyring;
1487         int uid, rc;
1488
1489         ENTRY;
1490
1491         CDEBUG(D_SEC, "instantiating key %08x (%p)\n", key->serial, key);
1492
1493         if (data != NULL || datalen != 0) {
1494                 CERROR("invalid: data %p, len %lu\n", data, (long)datalen);
1495                 RETURN(-EINVAL);
1496         }
1497
1498         if (key_get_payload(key, 0)) {
1499                 CERROR("key already have payload\n");
1500                 RETURN(-EINVAL);
1501         }
1502
1503         /* link the key to session keyring, so following context negotiation
1504          * rpc fired from user space could find this key. This will be unlinked
1505          * automatically when upcall processes die.
1506          *
1507          * we can't do this through keyctl from userspace, because the upcall
1508          * might be neither possessor nor owner of the key (setuid).
1509          *
1510          * the session keyring is created upon upcall, and don't change all
1511          * the way until upcall finished, so rcu lock is not needed here.
1512          *
1513          * But for end users, link to the user keyring. This simplifies key
1514          * management, makes them shared accross all user sessions, and avoids
1515          * unfortunate key leak if lfs flushctx is not called at user logout.
1516          */
1517         uid = from_kuid(&init_user_ns, current_uid());
1518         if (uid == 0)
1519                 keyring = get_session_keyring(current_cred());
1520         else
1521                 keyring = get_user_keyring(current_cred());
1522
1523         lockdep_off();
1524         rc = key_link(keyring, key);
1525         lockdep_on();
1526         if (unlikely(rc)) {
1527                 CERROR("failed to link key %08x to keyring %08x: %d\n",
1528                        key->serial, keyring->serial, rc);
1529                 GOTO(out, rc);
1530         }
1531
1532         CDEBUG(D_SEC,
1533               "key %08x (%p) linked to keyring %08x and instantiated, ctx %p\n",
1534                key->serial, key, keyring->serial, key_get_payload(key, 0));
1535 out:
1536         key_put(keyring);
1537         RETURN(rc);
1538 }
1539
1540 /*
1541  * called with key semaphore write locked. it means we can operate
1542  * on the context without fear of loosing refcount.
1543  */
1544 static
1545 #ifdef HAVE_KEY_TYPE_INSTANTIATE_2ARGS
1546 int gss_kt_update(struct key *key, struct key_preparsed_payload *prep)
1547 {
1548         const void *data = prep->data;
1549         __u32 datalen32 = (__u32) prep->datalen;
1550 #else
1551 int gss_kt_update(struct key *key, const void *data, size_t datalen)
1552 {
1553         __u32 datalen32 = (__u32) datalen;
1554 #endif
1555         struct ptlrpc_cli_ctx *ctx = key_get_payload(key, 0);
1556         struct gss_cli_ctx *gctx;
1557         rawobj_t tmpobj = RAWOBJ_EMPTY;
1558         int rc;
1559         ENTRY;
1560
1561         CDEBUG(D_SEC, "updating key %08x (%p)\n", key->serial, key);
1562
1563         if (data == NULL || datalen32 == 0) {
1564                 CWARN("invalid: data %p, len %lu\n", data, (long)datalen32);
1565                 RETURN(-EINVAL);
1566         }
1567
1568         /* if upcall finished negotiation too fast (mostly likely because
1569          * of local error happened) and call kt_update(), the ctx
1570          * might be still NULL. but the key will finally be associate
1571          * with a context, or be revoked. if key status is fine, return
1572          * -EAGAIN to allow userspace sleep a while and call again. */
1573         if (ctx == NULL) {
1574                 CDEBUG(D_SEC, "update too soon: key %08x (%p) flags %lx\n",
1575                        key->serial, key, key->flags);
1576
1577                 rc = key_validate(key);
1578                 if (rc == 0)
1579                         RETURN(-EAGAIN);
1580                 else
1581                         RETURN(rc);
1582         }
1583
1584         LASSERT(atomic_read(&ctx->cc_refcount) > 0);
1585         LASSERT(ctx->cc_sec);
1586
1587         ctx_clear_timer_kr(ctx);
1588
1589         /* don't proceed if already refreshed */
1590         if (cli_ctx_is_refreshed(ctx)) {
1591                 CWARN("ctx already done refresh\n");
1592                 RETURN(0);
1593         }
1594
1595         sptlrpc_cli_ctx_get(ctx);
1596         gctx = ctx2gctx(ctx);
1597
1598         rc = buffer_extract_bytes(&data, &datalen32, &gctx->gc_win,
1599                                   sizeof(gctx->gc_win));
1600         if (rc) {
1601                 CERROR("failed extract seq_win\n");
1602                 goto out;
1603         }
1604
1605         if (gctx->gc_win == 0) {
1606                 __u32   nego_rpc_err, nego_gss_err;
1607
1608                 rc = buffer_extract_bytes(&data, &datalen32, &nego_rpc_err,
1609                                           sizeof(nego_rpc_err));
1610                 if (rc) {
1611                         CERROR("cannot extract RPC: rc = %d\n", rc);
1612                         goto out;
1613                 }
1614
1615                 rc = buffer_extract_bytes(&data, &datalen32, &nego_gss_err,
1616                                           sizeof(nego_gss_err));
1617                 if (rc) {
1618                         CERROR("failed to extract gss rc = %d\n", rc);
1619                         goto out;
1620                 }
1621
1622                 CERROR("negotiation: rpc err %d, gss err %x\n",
1623                        nego_rpc_err, nego_gss_err);
1624
1625                 rc = nego_rpc_err ? nego_rpc_err : -EACCES;
1626         } else {
1627                 rc = rawobj_extract_local_alloc(&gctx->gc_handle,
1628                                                 (__u32 **) &data, &datalen32);
1629                 if (rc) {
1630                         CERROR("failed extract handle\n");
1631                         goto out;
1632                 }
1633
1634                 rc = rawobj_extract_local(&tmpobj,
1635                                           (__u32 **) &data, &datalen32);
1636                 if (rc) {
1637                         CERROR("failed extract mech\n");
1638                         goto out;
1639                 }
1640
1641                 rc = lgss_import_sec_context(&tmpobj,
1642                                              sec2gsec(ctx->cc_sec)->gs_mech,
1643                                              &gctx->gc_mechctx);
1644                 if (rc != GSS_S_COMPLETE)
1645                         CERROR("failed import context\n");
1646                 else
1647                         rc = 0;
1648         }
1649 out:
1650         CDEBUG(D_SEC, "update of key %08x (%p): %d\n", key->serial, key, rc);
1651         /* we don't care what current status of this ctx, even someone else
1652          * is operating on the ctx at the same time. we just add up our own
1653          * opinions here. */
1654         if (rc == 0) {
1655                 gss_cli_ctx_uptodate(gctx);
1656         } else {
1657                 /* this will also revoke the key. has to be done before
1658                  * wakeup waiters otherwise they can find the stale key */
1659                 kill_key_locked(key);
1660
1661                 cli_ctx_expire(ctx);
1662
1663                 if (rc != -ERESTART)
1664                         set_bit(PTLRPC_CTX_ERROR_BIT, &ctx->cc_flags);
1665         }
1666
1667         /* let user space think it's a success */
1668         sptlrpc_cli_ctx_put(ctx, 1);
1669         RETURN(0);
1670 }
1671
1672 #ifndef HAVE_KEY_MATCH_DATA
1673 static int
1674 gss_kt_match(const struct key *key, const void *desc)
1675 {
1676         return strcmp(key->description, (const char *) desc) == 0 &&
1677                 !test_bit(KEY_FLAG_REVOKED, &key->flags);
1678 }
1679 #else /* ! HAVE_KEY_MATCH_DATA */
1680 static bool
1681 gss_kt_match(const struct key *key, const struct key_match_data *match_data)
1682 {
1683         const char *desc = match_data->raw_data;
1684
1685         return strcmp(key->description, desc) == 0 &&
1686                 !test_bit(KEY_FLAG_REVOKED, &key->flags);
1687 }
1688
1689 /*
1690  * Preparse the match criterion.
1691  */
1692 static int gss_kt_match_preparse(struct key_match_data *match_data)
1693 {
1694         match_data->lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT;
1695         match_data->cmp = gss_kt_match;
1696         return 0;
1697 }
1698 #endif /* HAVE_KEY_MATCH_DATA */
1699
1700 static
1701 void gss_kt_destroy(struct key *key)
1702 {
1703         ENTRY;
1704         LASSERT(!key_get_payload(key, 0));
1705         CDEBUG(D_SEC, "destroy key %08x %p\n", key->serial, key);
1706         EXIT;
1707 }
1708
1709 static
1710 void gss_kt_describe(const struct key *key, struct seq_file *s)
1711 {
1712         if (key->description == NULL)
1713                 seq_puts(s, "[null]");
1714         else
1715                 seq_puts(s, key->description);
1716 }
1717
1718 static void gss_kt_revoke(struct key *key)
1719 {
1720         CDEBUG(D_SEC, "revoking key %08x (%p) ref %d\n",
1721                key->serial, key, ll_read_key_usage(key));
1722         kill_key_locked(key);
1723         key_revoke_locked(key);
1724         key_put(key);
1725         CDEBUG(D_SEC, "key %08x (%p) revoked ref %d\n",
1726                key->serial, key, ll_read_key_usage(key));
1727 }
1728
1729 static struct key_type gss_key_type =
1730 {
1731         .name           = "lgssc",
1732         .def_datalen    = 0,
1733         .instantiate    = gss_kt_instantiate,
1734         .update         = gss_kt_update,
1735 #ifdef HAVE_KEY_MATCH_DATA
1736         .match_preparse = gss_kt_match_preparse,
1737 #else
1738         .match          = gss_kt_match,
1739 #endif
1740         .destroy        = gss_kt_destroy,
1741         .describe       = gss_kt_describe,
1742         .revoke         = gss_kt_revoke,
1743 };
1744
1745 /****************************************
1746  * lustre gss keyring policy            *
1747  ****************************************/
1748
1749 static struct ptlrpc_ctx_ops gss_keyring_ctxops = {
1750         .match                  = gss_cli_ctx_match,
1751         .refresh                = gss_cli_ctx_refresh_kr,
1752         .validate               = gss_cli_ctx_validate_kr,
1753         .die                    = gss_cli_ctx_die_kr,
1754         .sign                   = gss_cli_ctx_sign,
1755         .verify                 = gss_cli_ctx_verify,
1756         .seal                   = gss_cli_ctx_seal,
1757         .unseal                 = gss_cli_ctx_unseal,
1758         .wrap_bulk              = gss_cli_ctx_wrap_bulk,
1759         .unwrap_bulk            = gss_cli_ctx_unwrap_bulk,
1760 };
1761
1762 static struct ptlrpc_sec_cops gss_sec_keyring_cops = {
1763         .create_sec             = gss_sec_create_kr,
1764         .destroy_sec            = gss_sec_destroy_kr,
1765         .kill_sec               = gss_sec_kill,
1766         .lookup_ctx             = gss_sec_lookup_ctx_kr,
1767         .release_ctx            = gss_sec_release_ctx_kr,
1768         .flush_ctx_cache        = gss_sec_flush_ctx_cache_kr,
1769         .gc_ctx                 = gss_sec_gc_ctx_kr,
1770         .install_rctx           = gss_sec_install_rctx,
1771         .alloc_reqbuf           = gss_alloc_reqbuf,
1772         .free_reqbuf            = gss_free_reqbuf,
1773         .alloc_repbuf           = gss_alloc_repbuf,
1774         .free_repbuf            = gss_free_repbuf,
1775         .enlarge_reqbuf         = gss_enlarge_reqbuf,
1776         .display                = gss_sec_display_kr,
1777 };
1778
1779 static struct ptlrpc_sec_sops gss_sec_keyring_sops = {
1780         .accept                 = gss_svc_accept_kr,
1781         .invalidate_ctx         = gss_svc_invalidate_ctx,
1782         .alloc_rs               = gss_svc_alloc_rs,
1783         .authorize              = gss_svc_authorize,
1784         .free_rs                = gss_svc_free_rs,
1785         .free_ctx               = gss_svc_free_ctx,
1786         .prep_bulk              = gss_svc_prep_bulk,
1787         .unwrap_bulk            = gss_svc_unwrap_bulk,
1788         .wrap_bulk              = gss_svc_wrap_bulk,
1789         .install_rctx           = gss_svc_install_rctx_kr,
1790 };
1791
1792 static struct ptlrpc_sec_policy gss_policy_keyring = {
1793         .sp_owner               = THIS_MODULE,
1794         .sp_name                = "gss.keyring",
1795         .sp_policy              = SPTLRPC_POLICY_GSS,
1796         .sp_cops                = &gss_sec_keyring_cops,
1797         .sp_sops                = &gss_sec_keyring_sops,
1798 };
1799
1800
1801 int __init gss_init_keyring(void)
1802 {
1803         int rc;
1804
1805         rc = register_key_type(&gss_key_type);
1806         if (rc) {
1807                 CERROR("failed to register keyring type: %d\n", rc);
1808                 return rc;
1809         }
1810
1811         rc = sptlrpc_register_policy(&gss_policy_keyring);
1812         if (rc) {
1813                 unregister_key_type(&gss_key_type);
1814                 return rc;
1815         }
1816
1817         return 0;
1818 }
1819
1820 void __exit gss_exit_keyring(void)
1821 {
1822         unregister_key_type(&gss_key_type);
1823         sptlrpc_unregister_policy(&gss_policy_keyring);
1824 }