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