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