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