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