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