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