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