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