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