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