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