Whamcloud - gitweb
LU-17705 ptlrpc: replace synchronize_rcu() with rcu_barrier()
[fs/lustre-release.git] / lustre / ptlrpc / gss / gss_svc_upcall.c
1 /*
2  * Modifications for Lustre
3  *
4  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
5  *
6  * Copyright (c) 2012, 2014, Intel Corporation.
7  *
8  * Author: Eric Mei <ericm@clusterfs.com>
9  */
10
11 /*
12  * Neil Brown <neilb@cse.unsw.edu.au>
13  * J. Bruce Fields <bfields@umich.edu>
14  * Andy Adamson <andros@umich.edu>
15  * Dug Song <dugsong@monkey.org>
16  *
17  * RPCSEC_GSS server authentication.
18  * This implements RPCSEC_GSS as defined in rfc2203 (rpcsec_gss) and rfc2078
19  * (gssapi)
20  *
21  * The RPCSEC_GSS involves three stages:
22  *  1/ context creation
23  *  2/ data exchange
24  *  3/ context destruction
25  *
26  * Context creation is handled largely by upcalls to user-space.
27  *  In particular, GSS_Accept_sec_context is handled by an upcall
28  * Data exchange is handled entirely within the kernel
29  *  In particular, GSS_GetMIC, GSS_VerifyMIC, GSS_Seal, GSS_Unseal are in-kernel.
30  * Context destruction is handled in-kernel
31  *  GSS_Delete_sec_context is in-kernel
32  *
33  * Context creation is initiated by a RPCSEC_GSS_INIT request arriving.
34  * The context handle and gss_token are used as a key into the rpcsec_init cache.
35  * The content of this cache includes some of the outputs of GSS_Accept_sec_context,
36  * being major_status, minor_status, context_handle, reply_token.
37  * These are sent back to the client.
38  * Sequence window management is handled by the kernel.  The window size if currently
39  * a compile time constant.
40  *
41  * When user-space is happy that a context is established, it places an entry
42  * in the rpcsec_context cache. The key for this cache is the context_handle.
43  * The content includes:
44  *   uid/gidlist - for determining access rights
45  *   mechanism type
46  *   mechanism specific information, such as a key
47  *
48  */
49
50 #define DEBUG_SUBSYSTEM S_SEC
51 #include <linux/types.h>
52 #include <linux/init.h>
53 #include <linux/module.h>
54 #include <linux/random.h>
55 #include <linux/slab.h>
56 #include <linux/mutex.h>
57 #include <linux/binfmts.h>
58 #include <net/sock.h>
59 #include <linux/un.h>
60
61 #include <obd.h>
62 #include <obd_class.h>
63 #include <obd_support.h>
64 #include <lustre_import.h>
65 #include <lustre_net.h>
66 #include <lustre_nodemap.h>
67 #include <lustre_sec.h>
68 #include <libcfs/linux/linux-hash.h>
69
70 #include "gss_err.h"
71 #include "gss_internal.h"
72 #include "gss_api.h"
73 #include "gss_crypto.h"
74
75 static DEFINE_SPINLOCK(__ctx_index_lock);
76 static __u64 __ctx_index;
77
78 unsigned int krb5_allow_old_client_csum;
79
80 __u64 gss_get_next_ctx_index(void)
81 {
82         __u64 idx;
83
84         spin_lock(&__ctx_index_lock);
85         idx = __ctx_index++;
86         spin_unlock(&__ctx_index_lock);
87
88         return idx;
89 }
90
91 static inline unsigned long hash_mem(char *buf, int length, int bits)
92 {
93         unsigned long hash = 0;
94         unsigned long l = 0;
95         int len = 0;
96         unsigned char c;
97
98         do {
99                 if (len == length) {
100                         c = (char) len;
101                         len = -1;
102                 } else
103                         c = *buf++;
104
105                 l = (l << 8) | c;
106                 len++;
107
108                 if ((len & (BITS_PER_LONG/8-1)) == 0)
109                         hash = cfs_hash_long(hash^l, BITS_PER_LONG);
110         } while (len);
111
112         return hash >> (BITS_PER_LONG - bits);
113 }
114
115 /* This is a little bit of a concern but we need to make our own hash64 function
116  * as the one from the kernel seems to be buggy by returning a u32:
117  * static __always_inline u32 hash_64_generic(u64 val, unsigned int bits)
118  */
119 #if BITS_PER_LONG == 64
120 static __always_inline __u64 gss_hash_64(__u64 val, unsigned int bits)
121 {
122         __u64 hash = val;
123         /*  Sigh, gcc can't optimise this alone like it does for 32 bits. */
124         __u64 n = hash;
125
126         n <<= 18;
127         hash -= n;
128         n <<= 33;
129         hash -= n;
130         n <<= 3;
131         hash += n;
132         n <<= 3;
133         hash -= n;
134         n <<= 4;
135         hash += n;
136         n <<= 2;
137         hash += n;
138
139         /* High bits are more random, so use them. */
140         return hash >> (64 - bits);
141 }
142
143 static inline unsigned long hash_mem_64(char *buf, int length, int bits)
144 {
145         __u64 hash = 0;
146         __u64 l = 0;
147         int len = 0;
148         unsigned char c;
149
150         do {
151                 if (len == length) {
152                         c = (char) len;
153                         len = -1;
154                 } else
155                         c = *buf++;
156
157                 l = (l << 8) | c;
158                 len++;
159
160                 if ((len & (BITS_PER_LONG / 8 - 1)) == 0)
161                         hash = gss_hash_64(hash ^ l, BITS_PER_LONG);
162         } while (len);
163
164         return hash >> (BITS_PER_LONG - bits);
165 }
166 #endif /* BITS_PER_LONG == 64 */
167
168 /****************************************
169  * rpc sec init (rsi) cache             *
170  ****************************************/
171
172 #define RSI_HASHBITS    (6)
173
174 static void rsi_entry_init(struct upcall_cache_entry *entry,
175                            void *args)
176 {
177         struct gss_rsi *rsi = &entry->u.rsi;
178         struct gss_rsi *tmp = args;
179
180         rsi->si_uc_entry = entry;
181         rawobj_dup(&rsi->si_in_handle, &tmp->si_in_handle);
182         rawobj_dup(&rsi->si_in_token, &tmp->si_in_token);
183         rsi->si_out_handle = RAWOBJ_EMPTY;
184         rsi->si_out_token = RAWOBJ_EMPTY;
185
186         rsi->si_lustre_svc = tmp->si_lustre_svc;
187         rsi->si_nid4 = tmp->si_nid4;
188         memcpy(rsi->si_nm_name, tmp->si_nm_name, sizeof(tmp->si_nm_name));
189 }
190
191 static void __rsi_free(struct gss_rsi *rsi)
192 {
193         rawobj_free(&rsi->si_in_handle);
194         rawobj_free(&rsi->si_in_token);
195         rawobj_free(&rsi->si_out_handle);
196         rawobj_free(&rsi->si_out_token);
197 }
198
199 static void rsi_entry_free(struct upcall_cache *cache,
200                            struct upcall_cache_entry *entry)
201 {
202         struct gss_rsi *rsi = &entry->u.rsi;
203
204         __rsi_free(rsi);
205 }
206
207 static inline int rsi_entry_hash(struct gss_rsi *rsi)
208 {
209 #if BITS_PER_LONG == 64
210         return hash_mem_64((char *)rsi->si_in_handle.data,
211                            rsi->si_in_handle.len, RSI_HASHBITS) ^
212                 hash_mem_64((char *)rsi->si_in_token.data,
213                             rsi->si_in_token.len, RSI_HASHBITS);
214 #else
215         return hash_mem((char *)rsi->si_in_handle.data, rsi->si_in_handle.len,
216                         RSI_HASHBITS) ^
217                 hash_mem((char *)rsi->si_in_token.data, rsi->si_in_token.len,
218                          RSI_HASHBITS);
219 #endif
220 }
221
222 static inline int __rsi_entry_match(rawobj_t *h1, rawobj_t *h2,
223                                     rawobj_t *t1, rawobj_t *t2)
224 {
225         return !(rawobj_equal(h1, h2) && rawobj_equal(t1, t2));
226 }
227
228 static inline int rsi_entry_match(struct gss_rsi *rsi, struct gss_rsi *tmp)
229 {
230         return __rsi_entry_match(&rsi->si_in_handle, &tmp->si_in_handle,
231                                  &rsi->si_in_token, &tmp->si_in_token);
232 }
233
234 /* Returns 0 to tell this is a match */
235 static inline int rsi_upcall_compare(struct upcall_cache *cache,
236                                      struct upcall_cache_entry *entry,
237                                      __u64 key, void *args)
238 {
239         struct gss_rsi *rsi1 = &entry->u.rsi;
240         struct gss_rsi *rsi2 = args;
241
242         return rsi_entry_match(rsi1, rsi2);
243 }
244
245 /* See handle_channel_request() userspace for where the upcall data is read */
246 static int rsi_do_upcall(struct upcall_cache *cache,
247                          struct upcall_cache_entry *entry)
248 {
249         int size, len, *blen;
250         char *buffer, *bp, **bpp;
251         char *argv[] = {
252                 [0] = cache->uc_upcall,
253                 [1] = "-c",
254                 [2] = cache->uc_name,
255                 [3] = "-r",
256                 [4] = NULL,
257                 [5] = NULL
258         };
259         char *envp[] = {
260                 [0] = "HOME=/",
261                 [1] = "PATH=/sbin:/usr/sbin",
262                 [2] = NULL
263         };
264         ktime_t start, end;
265         struct gss_rsi *rsi = &entry->u.rsi;
266         __u64 index = 0;
267         int rc;
268
269         ENTRY;
270         CDEBUG(D_SEC, "rsi upcall '%s' on '%s'\n",
271                cache->uc_upcall, cache->uc_name);
272
273         size = 24 + 1 + /* ue_key is uint64_t */
274                 12 + 1 + /* si_lustre_svc is __u32*/
275                 18 + 1 + /* si_nid4 is lnet_nid_t, hex with leading 0x */
276                 18 + 1 + /* index is __u64, hex with leading 0x */
277                 strlen(rsi->si_nm_name) + 1 +
278                 BASE64URL_CHARS(rsi->si_in_handle.len) + 1 +
279                 BASE64URL_CHARS(rsi->si_in_token.len) + 1 +
280                 1 + 1; /* eol */
281         if (size > MAX_ARG_STRLEN)
282                 RETURN(-E2BIG);
283         OBD_ALLOC_LARGE(buffer, size);
284         if (!buffer)
285                 RETURN(-ENOMEM);
286
287         bp = buffer;
288         bpp = &bp;
289         len = size;
290         blen = &len;
291
292         /* if in_handle is null, provide kernel suggestion */
293         if (rsi->si_in_handle.len == 0)
294                 index = gss_get_next_ctx_index();
295
296         /* entry->ue_key is put into args sent via upcall, so that it can be
297          * returned by userspace. This will help find cache entry at downcall,
298          * without unnecessary recomputation of the hash.
299          */
300         gss_u64_write_string(bpp, blen, entry->ue_key);
301         gss_u64_write_string(bpp, blen, rsi->si_lustre_svc);
302         gss_u64_write_hex_string(bpp, blen, rsi->si_nid4);
303         gss_u64_write_hex_string(bpp, blen, index);
304         gss_string_write(bpp, blen, (char *) rsi->si_nm_name);
305         gss_base64url_encode(bpp, blen, rsi->si_in_handle.data,
306                              rsi->si_in_handle.len);
307         gss_base64url_encode(bpp, blen, rsi->si_in_token.data,
308                              rsi->si_in_token.len);
309         (*bpp)[-1] = '\n';
310         (*bpp)[0] = '\0';
311
312         argv[4] = buffer;
313         down_read(&cache->uc_upcall_rwsem);
314         start = ktime_get();
315         rc = call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
316         end = ktime_get();
317         up_read(&cache->uc_upcall_rwsem);
318         if (rc < 0) {
319                 CERROR("%s: error invoking upcall %s %s (time %ldus): rc = %d\n",
320                        cache->uc_name, argv[0], argv[2],
321                        (long)ktime_us_delta(end, start), rc);
322         } else {
323                 CDEBUG(D_SEC, "%s: invoked upcall %s %s (time %ldus)\n",
324                        cache->uc_name, argv[0], argv[2],
325                        (long)ktime_us_delta(end, start));
326                 rc = 0;
327         }
328
329         OBD_FREE_LARGE(buffer, size);
330         RETURN(rc);
331 }
332
333 static inline int rsi_downcall_compare(struct upcall_cache *cache,
334                                        struct upcall_cache_entry *entry,
335                                        __u64 key, void *args)
336 {
337         struct gss_rsi *rsi = &entry->u.rsi;
338         struct rsi_downcall_data *sid = args;
339         char *mesg = sid->sid_val;
340         rawobj_t handle, token;
341         char *p = mesg;
342         int len;
343
344         /* sid_val starts with handle and token */
345
346         /* First, handle */
347         len = gss_buffer_get(&mesg, &handle.len, &handle.data);
348         sid->sid_offset = mesg - p;
349         p = mesg;
350
351         /* Second, token */
352         len = gss_buffer_get(&mesg, &token.len, &token.data);
353         sid->sid_offset += mesg - p;
354
355         return __rsi_entry_match(&rsi->si_in_handle, &handle,
356                                  &rsi->si_in_token, &token);
357 }
358
359 static int rsi_parse_downcall(struct upcall_cache *cache,
360                               struct upcall_cache_entry *entry,
361                               void *args)
362 {
363         struct gss_rsi *rsi = &entry->u.rsi;
364         struct rsi_downcall_data *sid = args;
365         int mlen = sid->sid_len;
366         char *mesg = sid->sid_val + sid->sid_offset;
367         char *buf = sid->sid_val;
368         int status = -EINVAL;
369         int len;
370
371         ENTRY;
372
373         if (mlen <= 0)
374                 goto out;
375
376         rsi->si_major_status = sid->sid_maj_stat;
377         rsi->si_minor_status = sid->sid_min_stat;
378
379         /* in_handle and in_token have already been consumed in
380          * rsi_downcall_compare(). sid_offset gives next field.
381          */
382
383         /* out_handle */
384         len = gss_buffer_read(&mesg, buf, mlen);
385         if (len < 0)
386                 goto out;
387         if (rawobj_alloc(&rsi->si_out_handle, buf, len)) {
388                 status = -ENOMEM;
389                 goto out;
390         }
391
392         /* out_token */
393         len = gss_buffer_read(&mesg, buf, mlen);
394         if (len < 0)
395                 goto out;
396         if (rawobj_alloc(&rsi->si_out_token, buf, len)) {
397                 status = -ENOMEM;
398                 goto out;
399         }
400
401         entry->ue_expire = 0;
402         status = 0;
403
404 out:
405         CDEBUG(D_OTHER, "rsi parse %p: %d\n", rsi, status);
406         RETURN(status);
407 }
408
409 struct gss_rsi *rsi_entry_get(struct upcall_cache *cache, struct gss_rsi *rsi)
410 {
411         struct upcall_cache_entry *entry;
412         int hash = rsi_entry_hash(rsi);
413
414         if (!cache)
415                 return ERR_PTR(-ENOENT);
416
417         entry = upcall_cache_get_entry(cache, (__u64)hash, rsi);
418         if (unlikely(!entry))
419                 return ERR_PTR(-ENOENT);
420         if (IS_ERR(entry))
421                 return ERR_CAST(entry);
422
423         return &entry->u.rsi;
424 }
425
426 void rsi_entry_put(struct upcall_cache *cache, struct gss_rsi *rsi)
427 {
428         if (!cache || !rsi)
429                 return;
430
431         upcall_cache_put_entry(cache, rsi->si_uc_entry);
432 }
433
434 struct upcall_cache_ops rsi_upcall_cache_ops = {
435         .init_entry       = rsi_entry_init,
436         .free_entry       = rsi_entry_free,
437         .upcall_compare   = rsi_upcall_compare,
438         .downcall_compare = rsi_downcall_compare,
439         .do_upcall        = rsi_do_upcall,
440         .parse_downcall   = rsi_parse_downcall,
441 };
442
443 struct upcall_cache *rsicache;
444
445 /****************************************
446  * rpc sec context (rsc) cache          *
447  ****************************************/
448
449 #define RSC_HASHBITS    (10)
450
451 static void rsc_entry_init(struct upcall_cache_entry *entry,
452                            void *args)
453 {
454         struct gss_rsc *rsc = &entry->u.rsc;
455         struct gss_rsc *tmp = args;
456
457         rsc->sc_uc_entry = entry;
458         rawobj_dup(&rsc->sc_handle, &tmp->sc_handle);
459
460         rsc->sc_target = NULL;
461         memset(&rsc->sc_ctx, 0, sizeof(rsc->sc_ctx));
462         rsc->sc_ctx.gsc_rvs_hdl = RAWOBJ_EMPTY;
463
464         memset(&rsc->sc_ctx.gsc_seqdata, 0, sizeof(rsc->sc_ctx.gsc_seqdata));
465         spin_lock_init(&rsc->sc_ctx.gsc_seqdata.ssd_lock);
466 }
467
468 void __rsc_free(struct gss_rsc *rsc)
469 {
470         rawobj_free(&rsc->sc_handle);
471         rawobj_free(&rsc->sc_ctx.gsc_rvs_hdl);
472         lgss_delete_sec_context(&rsc->sc_ctx.gsc_mechctx);
473 }
474
475 static void rsc_entry_free(struct upcall_cache *cache,
476                            struct upcall_cache_entry *entry)
477 {
478         struct gss_rsc *rsc = &entry->u.rsc;
479
480         __rsc_free(rsc);
481 }
482
483 static inline int rsc_entry_hash(struct gss_rsc *rsc)
484 {
485 #if BITS_PER_LONG == 64
486         return hash_mem_64((char *)rsc->sc_handle.data,
487                            rsc->sc_handle.len, RSC_HASHBITS);
488 #else
489         return hash_mem((char *)rsc->sc_handle.data,
490                         rsc->sc_handle.len, RSC_HASHBITS);
491 #endif
492 }
493
494 static inline int __rsc_entry_match(rawobj_t *h1, rawobj_t *h2)
495 {
496         return !(rawobj_equal(h1, h2));
497 }
498
499 static inline int rsc_entry_match(struct gss_rsc *rsc, struct gss_rsc *tmp)
500 {
501         return __rsc_entry_match(&rsc->sc_handle, &tmp->sc_handle);
502 }
503
504 /* Returns 0 to tell this is a match */
505 static inline int rsc_upcall_compare(struct upcall_cache *cache,
506                                      struct upcall_cache_entry *entry,
507                                      __u64 key, void *args)
508 {
509         struct gss_rsc *rsc1 = &entry->u.rsc;
510         struct gss_rsc *rsc2 = args;
511
512         return rsc_entry_match(rsc1, rsc2);
513 }
514
515 /* rsc upcall is a no-op, we just need a valid entry */
516 static inline int rsc_do_upcall(struct upcall_cache *cache,
517                                 struct upcall_cache_entry *entry)
518 {
519         upcall_cache_update_entry(cache, entry,
520                                   ktime_get_seconds() + cache->uc_entry_expire,
521                                   0);
522         return 0;
523 }
524
525 static inline int rsc_downcall_compare(struct upcall_cache *cache,
526                                        struct upcall_cache_entry *entry,
527                                        __u64 key, void *args)
528 {
529         struct gss_rsc *rsc = &entry->u.rsc;
530         struct rsc_downcall_data *scd = args;
531         char *mesg = scd->scd_val;
532         rawobj_t handle;
533         int len;
534
535         /* scd_val starts with handle */
536         len = gss_buffer_get(&mesg, &handle.len, &handle.data);
537         scd->scd_offset = mesg - scd->scd_val;
538
539         return __rsc_entry_match(&rsc->sc_handle, &handle);
540 }
541
542 static int rsc_parse_downcall(struct upcall_cache *cache,
543                               struct upcall_cache_entry *entry,
544                               void *args)
545 {
546         struct gss_api_mech *gm = NULL;
547         struct gss_rsc *rsc = &entry->u.rsc;
548         struct rsc_downcall_data *scd = args;
549         int mlen = scd->scd_len;
550         char *mesg = scd->scd_val + scd->scd_offset;
551         char *buf = scd->scd_val;
552         int status = -EINVAL;
553         time64_t ctx_expiry;
554         rawobj_t tmp_buf;
555         int len;
556
557         ENTRY;
558
559         if (mlen <= 0)
560                 goto out;
561
562         rsc->sc_ctx.gsc_remote = !!(scd->scd_flags & RSC_DATA_FLAG_REMOTE);
563         rsc->sc_ctx.gsc_usr_root = !!(scd->scd_flags & RSC_DATA_FLAG_ROOT);
564         rsc->sc_ctx.gsc_usr_mds = !!(scd->scd_flags & RSC_DATA_FLAG_MDS);
565         rsc->sc_ctx.gsc_usr_oss = !!(scd->scd_flags & RSC_DATA_FLAG_OSS);
566         rsc->sc_ctx.gsc_mapped_uid = scd->scd_mapped_uid;
567         rsc->sc_ctx.gsc_uid = scd->scd_uid;
568
569         rsc->sc_ctx.gsc_gid = scd->scd_gid;
570         gm = lgss_name_to_mech(scd->scd_mechname);
571         if (!gm) {
572                 status = -EOPNOTSUPP;
573                 goto out;
574         }
575
576         /* handle has already been consumed in rsc_downcall_compare().
577          * scd_offset gives next field.
578          */
579
580         /* context token */
581         len = gss_buffer_read(&mesg, buf, mlen);
582         if (len < 0)
583                 goto out;
584         tmp_buf.len = len;
585         tmp_buf.data = (unsigned char *)buf;
586         if (lgss_import_sec_context(&tmp_buf, gm,
587                                     &rsc->sc_ctx.gsc_mechctx))
588                 goto out;
589
590         if (lgss_inquire_context(rsc->sc_ctx.gsc_mechctx, &ctx_expiry))
591                 goto out;
592
593         /* ctx_expiry is the number of seconds since Jan 1 1970.
594          * We just want the number of seconds into the future.
595          */
596         entry->ue_expire = ktime_get_seconds() +
597                 (ctx_expiry - ktime_get_real_seconds());
598         status = 0;
599
600 out:
601         if (gm)
602                 lgss_mech_put(gm);
603         CDEBUG(D_OTHER, "rsc parse %p: %d\n", rsc, status);
604         RETURN(status);
605 }
606
607 struct gss_rsc *rsc_entry_get(struct upcall_cache *cache, struct gss_rsc *rsc)
608 {
609         struct upcall_cache_entry *entry;
610         int hash = rsc_entry_hash(rsc);
611
612         if (!cache)
613                 return ERR_PTR(-ENOENT);
614
615         entry = upcall_cache_get_entry(cache, (__u64)hash, rsc);
616         if (unlikely(!entry))
617                 return ERR_PTR(-ENOENT);
618         if (IS_ERR(entry))
619                 return ERR_CAST(entry);
620
621         return &entry->u.rsc;
622 }
623
624 void rsc_entry_put(struct upcall_cache *cache, struct gss_rsc *rsc)
625 {
626         if (!cache || !rsc)
627                 return;
628
629         upcall_cache_put_entry(cache, rsc->sc_uc_entry);
630 }
631
632 struct upcall_cache_ops rsc_upcall_cache_ops = {
633         .init_entry       = rsc_entry_init,
634         .free_entry       = rsc_entry_free,
635         .upcall_compare   = rsc_upcall_compare,
636         .downcall_compare = rsc_downcall_compare,
637         .do_upcall        = rsc_do_upcall,
638         .parse_downcall   = rsc_parse_downcall,
639 };
640
641 struct upcall_cache *rsccache;
642
643 /****************************************
644  * rsc cache flush                      *
645  ****************************************/
646
647 static struct gss_rsc *gss_svc_searchbyctx(rawobj_t *handle)
648 {
649         struct gss_rsc rsc;
650         struct gss_rsc *found;
651
652         memset(&rsc, 0, sizeof(rsc));
653         if (rawobj_dup(&rsc.sc_handle, handle))
654                 return NULL;
655
656         found = rsc_entry_get(rsccache, &rsc);
657         __rsc_free(&rsc);
658         if (IS_ERR_OR_NULL(found))
659                 return found;
660         if (!found->sc_ctx.gsc_mechctx) {
661                 rsc_entry_put(rsccache, found);
662                 return ERR_PTR(-ENOENT);
663         }
664         return found;
665 }
666
667 int gss_svc_upcall_install_rvs_ctx(struct obd_import *imp,
668                                    struct gss_sec *gsec,
669                                    struct gss_cli_ctx *gctx)
670 {
671         struct gss_rsc rsc, *rscp = NULL;
672         time64_t ctx_expiry;
673         __u32 major;
674         int rc;
675
676         ENTRY;
677         memset(&rsc, 0, sizeof(rsc));
678
679         if (!imp || !imp->imp_obd) {
680                 CERROR("invalid imp, drop\n");
681                 RETURN(-EPROTO);
682         }
683
684         if (rawobj_alloc(&rsc.sc_handle, (char *)&gsec->gs_rvs_hdl,
685                          sizeof(gsec->gs_rvs_hdl)))
686                 GOTO(out, rc = -ENOMEM);
687
688         rscp = rsc_entry_get(rsccache, &rsc);
689         __rsc_free(&rsc);
690         if (IS_ERR_OR_NULL(rscp))
691                 GOTO(out, rc = -ENOMEM);
692
693         major = lgss_copy_reverse_context(gctx->gc_mechctx,
694                                           &rscp->sc_ctx.gsc_mechctx);
695         if (major != GSS_S_COMPLETE)
696                 GOTO(out, rc = -ENOMEM);
697
698         if (lgss_inquire_context(rscp->sc_ctx.gsc_mechctx, &ctx_expiry)) {
699                 CERROR("%s: unable to get expire time, drop\n",
700                        imp->imp_obd->obd_name);
701                 GOTO(out, rc = -EINVAL);
702         }
703         rscp->sc_uc_entry->ue_expire = ktime_get_seconds() +
704                 (ctx_expiry - ktime_get_real_seconds());
705
706         switch (imp->imp_obd->u.cli.cl_sp_to) {
707         case LUSTRE_SP_MDT:
708                 rscp->sc_ctx.gsc_usr_mds = 1;
709                 break;
710         case LUSTRE_SP_OST:
711                 rscp->sc_ctx.gsc_usr_oss = 1;
712                 break;
713         case LUSTRE_SP_CLI:
714                 rscp->sc_ctx.gsc_usr_root = 1;
715                 break;
716         case LUSTRE_SP_MGS:
717                 /* by convention, all 3 set to 1 means MGS */
718                 rscp->sc_ctx.gsc_usr_mds = 1;
719                 rscp->sc_ctx.gsc_usr_oss = 1;
720                 rscp->sc_ctx.gsc_usr_root = 1;
721                 break;
722         default:
723                 break;
724         }
725
726         rscp->sc_target = imp->imp_obd;
727         rawobj_dup(&gctx->gc_svc_handle, &rscp->sc_handle);
728
729         CDEBUG(D_SEC, "%s: create reverse svc ctx %p to %s: idx %#llx\n",
730                imp->imp_obd->obd_name, &rscp->sc_ctx, obd2cli_tgt(imp->imp_obd),
731                gsec->gs_rvs_hdl);
732         rc = 0;
733 out:
734         if (!IS_ERR_OR_NULL(rscp))
735                 rsc_entry_put(rsccache, rscp);
736         if (rc)
737                 CERROR("%s: can't create reverse svc ctx idx %#llx: rc = %d\n",
738                        imp->imp_obd->obd_name, gsec->gs_rvs_hdl, rc);
739         RETURN(rc);
740 }
741
742 int gss_svc_upcall_expire_rvs_ctx(rawobj_t *handle)
743 {
744         const time64_t expire = 20;
745         struct gss_rsc *rscp;
746
747         rscp = gss_svc_searchbyctx(handle);
748         if (!IS_ERR_OR_NULL(rscp)) {
749                 CDEBUG(D_SEC,
750                        "reverse svcctx %p (rsc %p) expire in %lld seconds\n",
751                        &rscp->sc_ctx, rscp, expire);
752
753                 rscp->sc_uc_entry->ue_expire = ktime_get_seconds() + expire;
754                 rsc_entry_put(rsccache, rscp);
755         }
756         return 0;
757 }
758
759 int gss_svc_upcall_dup_handle(rawobj_t *handle, struct gss_svc_ctx *ctx)
760 {
761         struct gss_rsc *rscp = container_of(ctx, struct gss_rsc, sc_ctx);
762
763         return rawobj_dup(handle, &rscp->sc_handle);
764 }
765
766 int gss_svc_upcall_update_sequence(rawobj_t *handle, __u32 seq)
767 {
768         struct gss_rsc *rscp;
769
770         rscp = gss_svc_searchbyctx(handle);
771         if (!IS_ERR_OR_NULL(rscp)) {
772                 CDEBUG(D_SEC, "reverse svcctx %p (rsc %p) update seq to %u\n",
773                        &rscp->sc_ctx, rscp, seq + 1);
774
775                 rscp->sc_ctx.gsc_rvs_seq = seq + 1;
776                 rsc_entry_put(rsccache, rscp);
777         }
778         return 0;
779 }
780
781 int gss_svc_upcall_handle_init(struct ptlrpc_request *req,
782                                struct gss_svc_reqctx *grctx,
783                                struct gss_wire_ctx *gw,
784                                struct obd_device *target,
785                                __u32 lustre_svc,
786                                rawobj_t *rvs_hdl,
787                                rawobj_t *in_token)
788 {
789         struct gss_rsi rsi = { 0 }, *rsip = NULL;
790         struct ptlrpc_reply_state *rs;
791         struct gss_rsc *rscp = NULL;
792         int replen = sizeof(struct ptlrpc_body);
793         struct gss_rep_header *rephdr;
794         int rc, rc2;
795
796         ENTRY;
797
798         rsi.si_lustre_svc = lustre_svc;
799         /* In case of MR, rq_peer is not the NID from which request is received,
800          * but primary NID of peer.
801          * So we need LNetPrimaryNID(rq_source) to match what the clients uses.
802          */
803         LNetPrimaryNID(&req->rq_source.nid);
804         rsi.si_nid4 = lnet_nid_to_nid4(&req->rq_source.nid);
805         nodemap_test_nid(&req->rq_peer.nid, rsi.si_nm_name,
806                          sizeof(rsi.si_nm_name));
807
808         /* Note that context handle is always 0 for for INIT. */
809         rc2 = rawobj_dup(&rsi.si_in_handle, &gw->gw_handle);
810         if (rc2) {
811                 CERROR("%s: failed to duplicate context handle: rc = %d\n",
812                        target->obd_name, rc2);
813                 GOTO(out, rc = SECSVC_DROP);
814         }
815
816         rc2 = rawobj_dup(&rsi.si_in_token, in_token);
817         if (rc2) {
818                 CERROR("%s: failed to duplicate token: rc = %d\n",
819                        target->obd_name, rc2);
820                 rawobj_free(&rsi.si_in_handle);
821                 GOTO(out, rc = SECSVC_DROP);
822         }
823
824         rsip = rsi_entry_get(rsicache, &rsi);
825         __rsi_free(&rsi);
826         if (IS_ERR_OR_NULL(rsip)) {
827                 if (IS_ERR(rsip))
828                         rc2 = PTR_ERR(rsip);
829                 else
830                         rc2 = -EINVAL;
831                 CERROR("%s: failed to get entry from rsi cache (nid %s): rc = %d\n",
832                        target->obd_name,
833                        libcfs_nid2str(lnet_nid_to_nid4(&req->rq_source.nid)),
834                        rc2);
835
836                 if (!gss_pack_err_notify(req, GSS_S_FAILURE, 0))
837                         rc = SECSVC_COMPLETE;
838                 else
839                         rc = SECSVC_DROP;
840
841                 GOTO(out, rc);
842         }
843
844         rscp = gss_svc_searchbyctx(&rsip->si_out_handle);
845         if (IS_ERR_OR_NULL(rscp)) {
846                 /* gss mechanism returned major and minor code so we return
847                  * those in error message */
848
849                 if (!gss_pack_err_notify(req, rsip->si_major_status,
850                                          rsip->si_minor_status))
851                         rc = SECSVC_COMPLETE;
852                 else
853                         rc = SECSVC_DROP;
854
855                 CERROR("%s: authentication failed: rc = %d\n",
856                        target->obd_name, rc);
857                 GOTO(out, rc);
858         } else {
859                 /* we need to take an extra ref on the cache entry,
860                  * as a pointer to sc_ctx is stored in grctx
861                  */
862                 upcall_cache_get_entry_raw(rscp->sc_uc_entry);
863                 grctx->src_ctx = &rscp->sc_ctx;
864         }
865
866         if (gw->gw_flags & LUSTRE_GSS_PACK_KCSUM) {
867                 grctx->src_ctx->gsc_mechctx->hash_func = gss_digest_hash;
868         } else if (!strcmp(grctx->src_ctx->gsc_mechctx->mech_type->gm_name,
869                            "krb5") &&
870                    !krb5_allow_old_client_csum) {
871                 CWARN("%s: deny connection from '%s' due to missing 'krb_csum' feature, set 'sptlrpc.gss.krb5_allow_old_client_csum=1' to allow, but recommend client upgrade: rc = %d\n",
872                       target->obd_name, libcfs_nidstr(&req->rq_peer.nid),
873                       -EPROTO);
874                 GOTO(out, rc = SECSVC_DROP);
875         } else {
876                 grctx->src_ctx->gsc_mechctx->hash_func =
877                         gss_digest_hash_compat;
878         }
879
880         if (rawobj_dup(&rscp->sc_ctx.gsc_rvs_hdl, rvs_hdl)) {
881                 CERROR("%s: failed duplicate reverse handle\n",
882                        target->obd_name);
883                 GOTO(out, rc = SECSVC_DROP);
884         }
885
886         rscp->sc_target = target;
887
888         CDEBUG(D_SEC, "%s: server create rsc %p(%u->%s)\n",
889                target->obd_name, rscp, rscp->sc_ctx.gsc_uid,
890                libcfs_nidstr(&req->rq_peer.nid));
891
892         if (rsip->si_out_handle.len > PTLRPC_GSS_MAX_HANDLE_SIZE) {
893                 CERROR("%s: handle size %u too large\n",
894                        target->obd_name, rsip->si_out_handle.len);
895                 GOTO(out, rc = SECSVC_DROP);
896         }
897
898         grctx->src_init = 1;
899         grctx->src_reserve_len = round_up(rsip->si_out_token.len, 4);
900
901         rc = lustre_pack_reply_v2(req, 1, &replen, NULL, 0);
902         if (rc) {
903                 CERROR("%s: failed to pack reply: rc = %d\n",
904                        target->obd_name, rc);
905                 GOTO(out, rc = SECSVC_DROP);
906         }
907
908         rs = req->rq_reply_state;
909         LASSERT(rs->rs_repbuf->lm_bufcount == 3);
910         LASSERT(rs->rs_repbuf->lm_buflens[0] >=
911                 sizeof(*rephdr) + rsip->si_out_handle.len);
912         LASSERT(rs->rs_repbuf->lm_buflens[2] >= rsip->si_out_token.len);
913
914         rephdr = lustre_msg_buf(rs->rs_repbuf, 0, 0);
915         rephdr->gh_version = PTLRPC_GSS_VERSION;
916         rephdr->gh_flags = 0;
917         rephdr->gh_proc = PTLRPC_GSS_PROC_ERR;
918         rephdr->gh_major = rsip->si_major_status;
919         rephdr->gh_minor = rsip->si_minor_status;
920         rephdr->gh_seqwin = GSS_SEQ_WIN;
921         rephdr->gh_handle.len = rsip->si_out_handle.len;
922         memcpy(rephdr->gh_handle.data, rsip->si_out_handle.data,
923                rsip->si_out_handle.len);
924
925         memcpy(lustre_msg_buf(rs->rs_repbuf, 2, 0), rsip->si_out_token.data,
926                rsip->si_out_token.len);
927
928         rs->rs_repdata_len = lustre_shrink_msg(rs->rs_repbuf, 2,
929                                                rsip->si_out_token.len, 0);
930
931         rc = SECSVC_OK;
932
933 out:
934         if (!IS_ERR_OR_NULL(rsip)) {
935                 /* After rpcsec init request has been handled,
936                  * no need to keep rsi entry in cache, no matter the result.
937                  * So mark it invalid now.
938                  */
939                 UC_CACHE_SET_INVALID(rsip->si_uc_entry);
940                 rsi_entry_put(rsicache, rsip);
941         }
942         if (!IS_ERR_OR_NULL(rscp)) {
943                 /* if anything went wrong, we don't keep the context too */
944                 if (rc != SECSVC_OK)
945                         UC_CACHE_SET_INVALID(rscp->sc_uc_entry);
946                 else
947                         CDEBUG(D_SEC, "%s: create rsc with idx %#llx\n",
948                                target->obd_name,
949                                gss_handle_to_u64(&rscp->sc_handle));
950
951                 rsc_entry_put(rsccache, rscp);
952         }
953         RETURN(rc);
954 }
955
956 struct gss_svc_ctx *gss_svc_upcall_get_ctx(struct ptlrpc_request *req,
957                                            struct gss_wire_ctx *gw)
958 {
959         struct gss_rsc *rscp;
960
961         rscp = gss_svc_searchbyctx(&gw->gw_handle);
962         if (IS_ERR_OR_NULL(rscp)) {
963                 CWARN("Invalid gss ctx idx %#llx from %s\n",
964                       gss_handle_to_u64(&gw->gw_handle),
965                       libcfs_nidstr(&req->rq_peer.nid));
966                 return NULL;
967         }
968
969         return &rscp->sc_ctx;
970 }
971
972 void gss_svc_upcall_put_ctx(struct gss_svc_ctx *ctx)
973 {
974         struct gss_rsc *rscp = container_of(ctx, struct gss_rsc, sc_ctx);
975
976         rsc_entry_put(rsccache, rscp);
977 }
978
979 void gss_svc_upcall_destroy_ctx(struct gss_svc_ctx *ctx)
980 {
981         struct gss_rsc *rscp = container_of(ctx, struct gss_rsc, sc_ctx);
982
983         UC_CACHE_SET_INVALID(rscp->sc_uc_entry);
984         rscp->sc_uc_entry->ue_expire = 1;
985 }
986
987 /* Wait for userspace daemon to open socket, approx 1.5 s.
988  * If socket is not open, upcall requests might fail.
989  */
990 static int check_gssd_socket(void)
991 {
992         struct sockaddr_un *sun;
993         struct socket *sock;
994         int tries = 0;
995         int err;
996
997 #ifdef HAVE_SOCK_CREATE_KERN_USE_NET
998         err = sock_create_kern(current->nsproxy->net_ns,
999                                AF_UNIX, SOCK_STREAM, 0, &sock);
1000 #else
1001         err = sock_create_kern(AF_UNIX, SOCK_STREAM, 0, &sock);
1002 #endif
1003         if (err < 0) {
1004                 CDEBUG(D_SEC, "Failed to create socket: %d\n", err);
1005                 return err;
1006         }
1007
1008         OBD_ALLOC(sun, sizeof(*sun));
1009         if (!sun) {
1010                 sock_release(sock);
1011                 return -ENOMEM;
1012         }
1013         memset(sun, 0, sizeof(*sun));
1014         sun->sun_family = AF_UNIX;
1015         strncpy(sun->sun_path, GSS_SOCKET_PATH, sizeof(sun->sun_path));
1016
1017         /* Try to connect to the socket */
1018         while (tries++ < 6) {
1019                 err = kernel_connect(sock, (struct sockaddr *)sun,
1020                                      sizeof(*sun), 0);
1021                 if (!err)
1022                         break;
1023                 schedule_timeout_uninterruptible(cfs_time_seconds(1) / 4);
1024         }
1025         if (err < 0)
1026                 CDEBUG(D_SEC, "Failed to connect to socket: %d\n", err);
1027         else
1028                 kernel_sock_shutdown(sock, SHUT_RDWR);
1029
1030         sock_release(sock);
1031         OBD_FREE(sun, sizeof(*sun));
1032         return err;
1033 }
1034
1035 int __init gss_init_svc_upcall(void)
1036 {
1037         int rc;
1038
1039         /*
1040          * this helps reducing context index confliction. after server reboot,
1041          * conflicting request from clients might be filtered out by initial
1042          * sequence number checking, thus no chance to sent error notification
1043          * back to clients.
1044          */
1045         get_random_bytes(&__ctx_index, sizeof(__ctx_index));
1046
1047         rsicache = upcall_cache_init(RSI_CACHE_NAME, RSI_UPCALL_PATH,
1048                                      UC_RSICACHE_HASH_SIZE,
1049                                      600, /* entry expire: 10 mn */
1050                                      30, /* acquire expire: 30 s */
1051                                      false, /* can't replay acquire */
1052                                      &rsi_upcall_cache_ops);
1053         if (IS_ERR(rsicache)) {
1054                 rc = PTR_ERR(rsicache);
1055                 rsicache = NULL;
1056                 return rc;
1057         }
1058         rsccache = upcall_cache_init(RSC_CACHE_NAME, RSC_UPCALL_PATH,
1059                                      UC_RSCCACHE_HASH_SIZE,
1060                                      3600, /* replaced with one from mech */
1061                                      100, /* arbitrary, not used */
1062                                      false, /* can't replay acquire */
1063                                      &rsc_upcall_cache_ops);
1064         if (IS_ERR(rsccache)) {
1065                 upcall_cache_cleanup(rsicache);
1066                 rsicache = NULL;
1067                 rc = PTR_ERR(rsccache);
1068                 rsccache = NULL;
1069                 return rc;
1070         }
1071
1072         if (check_gssd_socket())
1073                 CDEBUG(D_SEC,
1074                        "Init channel not opened by lsvcgssd, GSS might not work on server side until daemon is active\n");
1075
1076         return 0;
1077 }
1078
1079 void gss_exit_svc_upcall(void)
1080 {
1081         upcall_cache_cleanup(rsicache);
1082         upcall_cache_cleanup(rsccache);
1083 }