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