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