Whamcloud - gitweb
LU-17887 obd: do not update obd_memory from RCU
[fs/lustre-release.git] / lustre / ptlrpc / gss / sec_gss.c
1 /*
2  * Modifications for Lustre
3  *
4  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
5  *
6  * Copyright (c) 2011, 2015, Intel Corporation.
7  *
8  * Author: Eric Mei <ericm@clusterfs.com>
9  */
10
11 /*
12  * linux/net/sunrpc/auth_gss.c
13  *
14  * RPCSEC_GSS client authentication.
15  *
16  *  Copyright (c) 2000 The Regents of the University of Michigan.
17  *  All rights reserved.
18  *
19  *  Dug Song       <dugsong@monkey.org>
20  *  Andy Adamson   <andros@umich.edu>
21  *
22  *  Redistribution and use in source and binary forms, with or without
23  *  modification, are permitted provided that the following conditions
24  *  are met:
25  *
26  *  1. Redistributions of source code must retain the above copyright
27  *     notice, this list of conditions and the following disclaimer.
28  *  2. Redistributions in binary form must reproduce the above copyright
29  *     notice, this list of conditions and the following disclaimer in the
30  *     documentation and/or other materials provided with the distribution.
31  *  3. Neither the name of the University nor the names of its
32  *     contributors may be used to endorse or promote products derived
33  *     from this software without specific prior written permission.
34  *
35  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
36  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
37  *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  *  DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39  *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
40  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
41  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
42  *  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
43  *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
44  *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
45  *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46  *
47  */
48
49 #define DEBUG_SUBSYSTEM S_SEC
50 #include <linux/init.h>
51 #include <linux/module.h>
52 #include <linux/slab.h>
53 #include <linux/dcache.h>
54 #include <linux/fs.h>
55 #include <linux/mutex.h>
56 #include <asm/atomic.h>
57
58 #include <obd.h>
59 #include <obd_class.h>
60 #include <obd_support.h>
61 #include <obd_cksum.h>
62 #include <lustre_net.h>
63 #include <lustre_import.h>
64 #include <lustre_sec.h>
65
66 #include "gss_err.h"
67 #include "gss_internal.h"
68 #include "gss_api.h"
69
70 #include <linux/crypto.h>
71 #include <linux/crc32.h>
72
73 /*
74  * early reply have fixed size, respectively in privacy and integrity mode.
75  * so we calculate them only once.
76  */
77 static int gss_at_reply_off_integ;
78 static int gss_at_reply_off_priv;
79
80
81 static inline int msg_last_segidx(struct lustre_msg *msg)
82 {
83         LASSERT(msg->lm_bufcount > 0);
84         return msg->lm_bufcount - 1;
85 }
86 static inline int msg_last_seglen(struct lustre_msg *msg)
87 {
88         return msg->lm_buflens[msg_last_segidx(msg)];
89 }
90
91  /* wire data swabber */
92 static
93 void gss_header_swabber(struct gss_header *ghdr)
94 {
95         __swab32s(&ghdr->gh_flags);
96         __swab32s(&ghdr->gh_proc);
97         __swab32s(&ghdr->gh_seq);
98         __swab32s(&ghdr->gh_svc);
99         __swab32s(&ghdr->gh_pad1);
100         __swab32s(&ghdr->gh_handle.len);
101 }
102
103 struct gss_header *gss_swab_header(struct lustre_msg *msg, int segment,
104                                    int swabbed)
105 {
106         struct gss_header *ghdr;
107
108         ghdr = lustre_msg_buf(msg, segment, sizeof(*ghdr));
109         if (ghdr == NULL)
110                 return NULL;
111
112         if (swabbed)
113                 gss_header_swabber(ghdr);
114
115         if (sizeof(*ghdr) + ghdr->gh_handle.len > msg->lm_buflens[segment]) {
116                 CERROR("gss header has length %d, now %u received\n",
117                        (int) sizeof(*ghdr) + ghdr->gh_handle.len,
118                        msg->lm_buflens[segment]);
119                 return NULL;
120         }
121
122         return ghdr;
123 }
124
125 /*
126  * payload should be obtained from mechanism. but currently since we
127  * only support kerberos, we could simply use fixed value.
128  * krb5 "meta" data:
129  *  - krb5 header:      16
130  *  - krb5 checksum:    20
131  *
132  * for privacy mode, payload also include the cipher text which has the same
133  * size as plain text, plus possible confounder, padding both at maximum cipher
134  * block size.
135  */
136 #define GSS_KRB5_INTEG_MAX_PAYLOAD      (40)
137
138 static inline
139 int gss_mech_payload(struct gss_ctx *mechctx, int msgsize, int privacy)
140 {
141         if (privacy)
142                 return GSS_KRB5_INTEG_MAX_PAYLOAD + 16 + 16 + 16 + msgsize;
143         else
144                 return GSS_KRB5_INTEG_MAX_PAYLOAD;
145 }
146
147 /*
148  * return signature size, otherwise < 0 to indicate error
149  */
150 static int gss_sign_msg(struct lustre_msg *msg, struct gss_ctx *mechctx,
151                         enum lustre_sec_part sp, __u32 flags, __u32 proc,
152                         __u32 seq, __u32 svc, rawobj_t *handle)
153 {
154         struct gss_header      *ghdr;
155         rawobj_t                text[4], mic;
156         int                     textcnt, max_textcnt, mic_idx;
157         __u32                   major;
158
159         LASSERT(msg->lm_bufcount >= 2);
160
161         /* gss hdr */
162         LASSERT(msg->lm_buflens[0] >=
163                 sizeof(*ghdr) + (handle ? handle->len : 0));
164         ghdr = lustre_msg_buf(msg, 0, 0);
165
166         ghdr->gh_version = PTLRPC_GSS_VERSION;
167         ghdr->gh_sp = (__u8) sp;
168         ghdr->gh_flags = flags;
169         ghdr->gh_proc = proc;
170         ghdr->gh_seq = seq;
171         ghdr->gh_svc = svc;
172         if (!handle) {
173                 /* fill in a fake one */
174                 ghdr->gh_handle.len = 0;
175         } else {
176                 ghdr->gh_handle.len = handle->len;
177                 memcpy(ghdr->gh_handle.data, handle->data, handle->len);
178         }
179
180         /* no actual signature for null mode */
181         if (svc == SPTLRPC_SVC_NULL)
182                 return lustre_msg_size_v2(msg->lm_bufcount, msg->lm_buflens);
183
184         /* MIC */
185         mic_idx = msg_last_segidx(msg);
186         max_textcnt = (svc == SPTLRPC_SVC_AUTH) ? 1 : mic_idx;
187
188         for (textcnt = 0; textcnt < max_textcnt; textcnt++) {
189                 text[textcnt].len = msg->lm_buflens[textcnt];
190                 text[textcnt].data = lustre_msg_buf(msg, textcnt, 0);
191         }
192
193         mic.len = msg->lm_buflens[mic_idx];
194         mic.data = lustre_msg_buf(msg, mic_idx, 0);
195
196         major = lgss_get_mic(mechctx, textcnt, text, 0, NULL, &mic);
197         if (major != GSS_S_COMPLETE) {
198                 CERROR("fail to generate MIC: %08x\n", major);
199                 return -EPERM;
200         }
201         LASSERT(mic.len <= msg->lm_buflens[mic_idx]);
202
203         return lustre_shrink_msg(msg, mic_idx, mic.len, 0);
204 }
205
206 /*
207  * return gss error
208  */
209 static
210 __u32 gss_verify_msg(struct lustre_msg *msg, struct gss_ctx *mechctx,
211                      __u32 svc)
212 {
213         rawobj_t        text[4], mic;
214         int             textcnt, max_textcnt;
215         int             mic_idx;
216         __u32           major;
217
218         LASSERT(msg->lm_bufcount >= 2);
219
220         if (svc == SPTLRPC_SVC_NULL)
221                 return GSS_S_COMPLETE;
222
223         mic_idx = msg_last_segidx(msg);
224         max_textcnt = (svc == SPTLRPC_SVC_AUTH) ? 1 : mic_idx;
225
226         for (textcnt = 0; textcnt < max_textcnt; textcnt++) {
227                 text[textcnt].len = msg->lm_buflens[textcnt];
228                 text[textcnt].data = lustre_msg_buf(msg, textcnt, 0);
229         }
230
231         mic.len = msg->lm_buflens[mic_idx];
232         mic.data = lustre_msg_buf(msg, mic_idx, 0);
233
234         major = lgss_verify_mic(mechctx, textcnt, text, 0, NULL, &mic);
235         if (major != GSS_S_COMPLETE)
236                 CERROR("mic verify error: %08x\n", major);
237
238         return major;
239 }
240
241 /*
242  * return gss error code
243  */
244 static
245 __u32 gss_unseal_msg(struct gss_ctx *mechctx, struct lustre_msg *msgbuf,
246                      int *msg_len, int msgbuf_len)
247 {
248         rawobj_t                 clear_obj, hdrobj, token;
249         __u8                    *clear_buf;
250         int                      clear_buflen;
251         __u32                    major;
252         ENTRY;
253
254         if (msgbuf->lm_bufcount != 2) {
255                 CERROR("invalid bufcount %d\n", msgbuf->lm_bufcount);
256                 RETURN(GSS_S_FAILURE);
257         }
258
259         /* allocate a temporary clear text buffer, same sized as token,
260          * we assume the final clear text size <= token size
261          */
262         clear_buflen = lustre_msg_buflen(msgbuf, 1);
263         OBD_ALLOC_LARGE(clear_buf, clear_buflen);
264         if (!clear_buf)
265                 RETURN(GSS_S_FAILURE);
266
267         /* buffer objects */
268         hdrobj.len = lustre_msg_buflen(msgbuf, 0);
269         hdrobj.data = lustre_msg_buf(msgbuf, 0, 0);
270         token.len = lustre_msg_buflen(msgbuf, 1);
271         token.data = lustre_msg_buf(msgbuf, 1, 0);
272         clear_obj.len = clear_buflen;
273         clear_obj.data = clear_buf;
274
275         major = lgss_unwrap(mechctx, &hdrobj, &token, &clear_obj);
276         if (major != GSS_S_COMPLETE) {
277                 CERROR("unwrap message error: %08x\n", major);
278                 GOTO(out_free, major = GSS_S_FAILURE);
279         }
280         LASSERT(clear_obj.len <= clear_buflen);
281         LASSERT(clear_obj.len <= msgbuf_len);
282
283         /* now the decrypted message */
284         memcpy(msgbuf, clear_obj.data, clear_obj.len);
285         *msg_len = clear_obj.len;
286
287         major = GSS_S_COMPLETE;
288 out_free:
289         OBD_FREE_LARGE(clear_buf, clear_buflen);
290         RETURN(major);
291 }
292
293 /* gss client context manipulation helpers  */
294 int cli_ctx_expire(struct ptlrpc_cli_ctx *ctx)
295 {
296         LASSERT(atomic_read(&ctx->cc_refcount));
297
298         if (!test_and_set_bit(PTLRPC_CTX_DEAD_BIT, &ctx->cc_flags)) {
299                 if (!ctx->cc_early_expire)
300                         clear_bit(PTLRPC_CTX_UPTODATE_BIT, &ctx->cc_flags);
301
302                 CDEBUG(D_SEC, "ctx %p(%u->%s) get expired: %lld(%+llds)\n",
303                        ctx, ctx->cc_vcred.vc_uid, sec2target_str(ctx->cc_sec),
304                        ctx->cc_expire,
305                        ctx->cc_expire == 0 ? 0 :
306                        ctx->cc_expire - ktime_get_real_seconds());
307
308                 sptlrpc_cli_ctx_wakeup(ctx);
309                 return 1;
310         }
311
312         return 0;
313 }
314
315 /*
316  * return 1 if the context is dead.
317  */
318 int cli_ctx_check_death(struct ptlrpc_cli_ctx *ctx)
319 {
320         if (unlikely(cli_ctx_is_dead(ctx)))
321                 return 1;
322
323         /* expire is 0 means never expire. a newly created gss context
324          * which during upcall may has 0 expiration
325          */
326         if (ctx->cc_expire == 0)
327                 return 0;
328
329         /* check real expiration */
330         if (ctx->cc_expire > ktime_get_real_seconds())
331                 return 0;
332
333         cli_ctx_expire(ctx);
334         return 1;
335 }
336
337 void gss_cli_ctx_uptodate(struct gss_cli_ctx *gctx)
338 {
339         struct ptlrpc_cli_ctx *ctx = &gctx->gc_base;
340         time64_t ctx_expiry;
341
342         if (lgss_inquire_context(gctx->gc_mechctx, &ctx_expiry)) {
343                 CERROR("ctx %p(%u): unable to inquire, expire it now\n",
344                        gctx, ctx->cc_vcred.vc_uid);
345                 ctx_expiry = 1; /* make it expired now */
346         }
347
348         ctx->cc_expire = gss_round_ctx_expiry(ctx_expiry,
349                                               ctx->cc_sec->ps_flvr.sf_flags);
350
351         /* At this point this ctx might have been marked as dead by
352          * someone else, in which case nobody will make further use
353          * of it. we don't care, and mark it UPTODATE will help
354          * destroying server side context when it be destroyed.
355          */
356         set_bit(PTLRPC_CTX_UPTODATE_BIT, &ctx->cc_flags);
357
358         if (sec_is_reverse(ctx->cc_sec)) {
359                 CDEBUG(D_SEC, "server installed reverse ctx %p idx %#llx, expiry %lld(%+llds)\n",
360                        ctx, gss_handle_to_u64(&gctx->gc_handle),
361                        ctx->cc_expire,
362                        ctx->cc_expire - ktime_get_real_seconds());
363         } else {
364                 CDEBUG(D_SEC, "client refreshed ctx %p idx %#llx (%u->%s), expiry %lld(%+llds)\n",
365                        ctx, gss_handle_to_u64(&gctx->gc_handle),
366                        ctx->cc_vcred.vc_uid, sec2target_str(ctx->cc_sec),
367                        ctx->cc_expire,
368                        ctx->cc_expire - ktime_get_real_seconds());
369
370                 /* install reverse svc ctx for root context */
371                 if (ctx->cc_vcred.vc_uid == 0)
372                         gss_sec_install_rctx(ctx->cc_sec->ps_import,
373                                              ctx->cc_sec, ctx);
374         }
375
376         sptlrpc_cli_ctx_wakeup(ctx);
377 }
378
379 static void gss_cli_ctx_finalize(struct gss_cli_ctx *gctx)
380 {
381         LASSERT(gctx->gc_base.cc_sec);
382
383         if (gctx->gc_mechctx) {
384                 lgss_delete_sec_context(&gctx->gc_mechctx);
385                 gctx->gc_mechctx = NULL;
386         }
387
388         if (!rawobj_empty(&gctx->gc_svc_handle)) {
389                 /* forward ctx: mark buddy reverse svcctx soon-expire. */
390                 if (!sec_is_reverse(gctx->gc_base.cc_sec) &&
391                     !rawobj_empty(&gctx->gc_svc_handle))
392                         gss_svc_upcall_expire_rvs_ctx(&gctx->gc_svc_handle);
393
394                 rawobj_free(&gctx->gc_svc_handle);
395         }
396
397         rawobj_free(&gctx->gc_handle);
398 }
399
400 /**
401  * Based on sequence number algorithm as specified in RFC 2203.
402  *
403  * Modified for our own problem: arriving request has valid sequence number,
404  * but unwrapping request might cost a long time, after that its sequence
405  * are not valid anymore (fall behind the window). It rarely happen, mostly
406  * under extreme load.
407  *
408  * Note we should not check sequence before verifying the integrity of incoming
409  * request, because just one attacking request with high sequence number might
410  * cause all following requests be dropped.
411  *
412  * So here we use a multi-phase approach: prepare 2 sequence windows,
413  * "main window" for normal sequence and "back window" for fall behind sequence.
414  * and 3-phase checking mechanism:
415  *  0 - before integrity verification, perform an initial sequence checking in
416  *      main window, which only tries and doesn't actually set any bits. if the
417  *      sequence is high above the window or fits in the window and the bit
418  *      is 0, then accept and proceed to integrity verification. otherwise
419  *      reject this sequence.
420  *  1 - after integrity verification, check in main window again. if this
421  *      sequence is high above the window or fits in the window and the bit
422  *      is 0, then set the bit and accept; if it fits in the window but bit
423  *      already set, then reject; if it falls behind the window, then proceed
424  *      to phase 2.
425  *  2 - check in back window. if it is high above the window or fits in the
426  *      window and the bit is 0, then set the bit and accept. otherwise reject.
427  *
428  * \return       1:     looks like a replay
429  * \return       0:     is ok
430  * \return      -1:     is a replay
431  *
432  * Note phase 0 is necessary, because otherwise replay attacking request of
433  * sequence which between the 2 windows can't be detected.
434  *
435  * This mechanism can't totally solve the problem, but could help reduce the
436  * number of valid requests be dropped.
437  */
438 static
439 int gss_do_check_seq(unsigned long *window, __u32 win_size, __u32 *max_seq,
440                      __u32 seq_num, int phase)
441 {
442         LASSERT(phase >= 0 && phase <= 2);
443
444         if (seq_num > *max_seq) {
445                 /*
446                  * 1. high above the window
447                  */
448                 if (phase == 0)
449                         return 0;
450
451                 if (seq_num >= *max_seq + win_size) {
452                         memset(window, 0, win_size / 8);
453                         *max_seq = seq_num;
454                 } else {
455                         while (*max_seq < seq_num) {
456                                 (*max_seq)++;
457                                 __clear_bit((*max_seq) % win_size, window);
458                         }
459                 }
460                 __set_bit(seq_num % win_size, window);
461         } else if (seq_num + win_size <= *max_seq) {
462                 /*
463                  * 2. low behind the window
464                  */
465                 if (phase == 0 || phase == 2)
466                         goto replay;
467
468                 CWARN("seq %u is %u behind (size %d), check backup window\n",
469                       seq_num, *max_seq - win_size - seq_num, win_size);
470                 return 1;
471         } else {
472                 /*
473                  * 3. fit into the window
474                  */
475                 switch (phase) {
476                 case 0:
477                         if (test_bit(seq_num % win_size, window))
478                                 goto replay;
479                         break;
480                 case 1:
481                 case 2:
482                         if (__test_and_set_bit(seq_num % win_size, window))
483                                 goto replay;
484                         break;
485                 }
486         }
487
488         return 0;
489
490 replay:
491         CERROR("seq %u (%s %s window) is a replay: max %u, winsize %d\n",
492                seq_num,
493                seq_num + win_size > *max_seq ? "in" : "behind",
494                phase == 2 ? "backup " : "main",
495                *max_seq, win_size);
496         return -1;
497 }
498
499 /*
500  * Based on sequence number algorithm as specified in RFC 2203.
501  *
502  * if @set == 0: initial check, don't set any bit in window
503  * if @sec == 1: final check, set bit in window
504  */
505 int gss_check_seq_num(struct gss_svc_seq_data *ssd, __u32 seq_num, int set)
506 {
507         int rc = 0;
508
509         spin_lock(&ssd->ssd_lock);
510
511         if (set == 0) {
512                 /*
513                  * phase 0 testing
514                  */
515                 rc = gss_do_check_seq(ssd->ssd_win_main, GSS_SEQ_WIN_MAIN,
516                                       &ssd->ssd_max_main, seq_num, 0);
517                 if (unlikely(rc))
518                         gss_stat_oos_record_svc(0, 1);
519         } else {
520                 /*
521                  * phase 1 checking main window
522                  */
523                 rc = gss_do_check_seq(ssd->ssd_win_main, GSS_SEQ_WIN_MAIN,
524                                       &ssd->ssd_max_main, seq_num, 1);
525                 switch (rc) {
526                 case -1:
527                         gss_stat_oos_record_svc(1, 1);
528                         fallthrough;
529                 case 0:
530                         goto exit;
531                 }
532                 /*
533                  * phase 2 checking back window
534                  */
535                 rc = gss_do_check_seq(ssd->ssd_win_back, GSS_SEQ_WIN_BACK,
536                                       &ssd->ssd_max_back, seq_num, 2);
537                 if (rc)
538                         gss_stat_oos_record_svc(2, 1);
539                 else
540                         gss_stat_oos_record_svc(2, 0);
541         }
542 exit:
543         spin_unlock(&ssd->ssd_lock);
544         return rc;
545 }
546
547 /* cred APIs */
548 static inline int gss_cli_payload(struct ptlrpc_cli_ctx *ctx, int msgsize,
549                                   int privacy)
550 {
551         return gss_mech_payload(NULL, msgsize, privacy);
552 }
553
554 static int gss_cli_bulk_payload(struct ptlrpc_cli_ctx *ctx,
555                                 struct sptlrpc_flavor *flvr,
556                                 int reply, int read)
557 {
558         int payload = sizeof(struct ptlrpc_bulk_sec_desc);
559
560         LASSERT(SPTLRPC_FLVR_BULK_TYPE(flvr->sf_rpc) == SPTLRPC_BULK_DEFAULT);
561
562         if ((!reply && !read) || (reply && read)) {
563                 switch (SPTLRPC_FLVR_BULK_SVC(flvr->sf_rpc)) {
564                 case SPTLRPC_BULK_SVC_NULL:
565                         break;
566                 case SPTLRPC_BULK_SVC_INTG:
567                         payload += gss_cli_payload(ctx, 0, 0);
568                         break;
569                 case SPTLRPC_BULK_SVC_PRIV:
570                         payload += gss_cli_payload(ctx, 0, 1);
571                         break;
572                 case SPTLRPC_BULK_SVC_AUTH:
573                 default:
574                         LBUG();
575                 }
576         }
577
578         return payload;
579 }
580
581 int gss_cli_ctx_match(struct ptlrpc_cli_ctx *ctx, struct vfs_cred *vcred)
582 {
583         return (ctx->cc_vcred.vc_uid == vcred->vc_uid);
584 }
585
586 void gss_cli_ctx_flags2str(unsigned long flags, char *buf, int bufsize)
587 {
588         buf[0] = '\0';
589
590         if (flags & PTLRPC_CTX_NEW)
591                 strlcat(buf, "new, ", bufsize);
592         if (flags & PTLRPC_CTX_UPTODATE)
593                 strlcat(buf, "uptodate, ", bufsize);
594         if (flags & PTLRPC_CTX_DEAD)
595                 strlcat(buf, "dead, ", bufsize);
596         if (flags & PTLRPC_CTX_ERROR)
597                 strlcat(buf, "error, ", bufsize);
598         if (flags & PTLRPC_CTX_CACHED)
599                 strlcat(buf, "cached, ", bufsize);
600         if (flags & PTLRPC_CTX_ETERNAL)
601                 strlcat(buf, "eternal, ", bufsize);
602         if (buf[strlen(buf) - 2] == ',')
603                 buf[strlen(buf) - 2] = '\0';
604 }
605
606 int gss_cli_ctx_sign(struct ptlrpc_cli_ctx *ctx, struct ptlrpc_request *req)
607 {
608         struct gss_cli_ctx      *gctx = ctx2gctx(ctx);
609         __u32                    flags = 0, seq, svc;
610         int                      rc;
611         ENTRY;
612
613         LASSERT(req->rq_reqbuf);
614         LASSERT(req->rq_reqbuf->lm_bufcount >= 2);
615         LASSERT(req->rq_cli_ctx == ctx);
616
617         /* nothing to do for context negotiation RPCs */
618         if (req->rq_ctx_init)
619                 RETURN(0);
620
621         svc = SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc);
622         if (req->rq_pack_bulk)
623                 flags |= LUSTRE_GSS_PACK_BULK;
624         if (req->rq_pack_udesc)
625                 flags |= LUSTRE_GSS_PACK_USER;
626
627 redo:
628         seq = atomic_inc_return(&gctx->gc_seq);
629
630         rc = gss_sign_msg(req->rq_reqbuf, gctx->gc_mechctx,
631                           ctx->cc_sec->ps_part,
632                           flags, gctx->gc_proc, seq, svc,
633                           &gctx->gc_handle);
634         if (rc < 0)
635                 RETURN(rc);
636
637         /* gss_sign_msg() msg might take long time to finish, in which period
638          * more rpcs could be wrapped up and sent out. if we found too many
639          * of them we should repack this rpc, because sent it too late might
640          * lead to the sequence number fall behind the window on server and
641          * be dropped. also applies to gss_cli_ctx_seal().
642          *
643          * Note: null mode doesn't check sequence number.
644          */
645         if (svc != SPTLRPC_SVC_NULL &&
646             atomic_read(&gctx->gc_seq) - seq > GSS_SEQ_REPACK_THRESHOLD) {
647                 int behind = atomic_read(&gctx->gc_seq) - seq;
648
649                 gss_stat_oos_record_cli(behind);
650                 CWARN("req %p: %u behind, retry signing\n", req, behind);
651                 goto redo;
652         }
653
654         req->rq_reqdata_len = rc;
655         RETURN(0);
656 }
657
658 static
659 int gss_cli_ctx_handle_err_notify(struct ptlrpc_cli_ctx *ctx,
660                                   struct ptlrpc_request *req,
661                                   struct gss_header *ghdr)
662 {
663         struct gss_err_header *errhdr;
664         int rc;
665
666         LASSERT(ghdr->gh_proc == PTLRPC_GSS_PROC_ERR);
667
668         errhdr = (struct gss_err_header *) ghdr;
669
670         CWARN("%s: req x%llu/t%llu, ctx %p idx %#llx(%u->%s): %sserver respond (%08x/%08x)\n",
671               ctx->cc_sec->ps_import->imp_obd->obd_name,
672               req->rq_xid, req->rq_transno, ctx,
673               gss_handle_to_u64(&ctx2gctx(ctx)->gc_handle),
674               ctx->cc_vcred.vc_uid, sec2target_str(ctx->cc_sec),
675               sec_is_reverse(ctx->cc_sec) ? "reverse " : "",
676               errhdr->gh_major, errhdr->gh_minor);
677
678         /* context fini rpc, let it failed */
679         if (req->rq_ctx_fini) {
680                 CWARN("%s: context fini rpc failed: rc = %d\n",
681                       ctx->cc_sec->ps_import->imp_obd->obd_name, -EINVAL);
682                 return -EINVAL;
683         }
684
685         /* reverse sec, just return error, don't expire this ctx because it's
686          * crucial to callback rpcs. note if the callback rpc failed because
687          * of bit flip during network transfer, the client will be evicted
688          * directly. so more gracefully we probably want let it retry for
689          * number of times.
690          */
691         if (sec_is_reverse(ctx->cc_sec) &&
692             errhdr->gh_major != GSS_S_NO_CONTEXT)
693                 return -EINVAL;
694
695         if (errhdr->gh_major != GSS_S_NO_CONTEXT &&
696             errhdr->gh_major != GSS_S_BAD_SIG)
697                 return -EACCES;
698
699         /* server return NO_CONTEXT might be caused by context expire
700          * or server reboot/failover. we try to refresh a new ctx which
701          * be transparent to upper layer.
702          *
703          * In some cases, our gss handle is possible to be incidentally
704          * identical to another handle since the handle itself is not
705          * fully random. In krb5 case, the GSS_S_BAD_SIG will be
706          * returned, maybe other gss error for other mechanism.
707          *
708          * if we add new mechanism, make sure the correct error are
709          * returned in this case.
710          */
711         CWARN("%s: %s might have lost the context (%s), retrying\n",
712               ctx->cc_sec->ps_import->imp_obd->obd_name,
713               sec_is_reverse(ctx->cc_sec) ? "client" : "server",
714               errhdr->gh_major == GSS_S_NO_CONTEXT ?  "NO_CONTEXT" : "BAD_SIG");
715
716         sptlrpc_cli_ctx_expire(ctx);
717
718         /* we need replace the ctx right here, otherwise during
719          * resent we'll hit the logic in sptlrpc_req_refresh_ctx()
720          * which keep the ctx with RESEND flag, thus we'll never
721          * get rid of this ctx.
722          */
723         rc = sptlrpc_req_replace_dead_ctx(req, NULL);
724         if (rc == 0)
725                 req->rq_resend = 1;
726
727         return rc;
728 }
729
730 int gss_cli_ctx_verify(struct ptlrpc_cli_ctx *ctx, struct ptlrpc_request *req)
731 {
732         struct gss_cli_ctx     *gctx;
733         struct gss_header      *ghdr, *reqhdr;
734         struct lustre_msg      *msg = req->rq_repdata;
735         __u32                   major;
736         int                     pack_bulk, swabbed, rc = 0;
737         ENTRY;
738
739         LASSERT(req->rq_cli_ctx == ctx);
740         LASSERT(msg);
741
742         gctx = container_of(ctx, struct gss_cli_ctx, gc_base);
743
744         /* special case for context negotiation, rq_repmsg/rq_replen actually
745          * are not used currently. but early reply always be treated normally
746          */
747         if (req->rq_ctx_init && !req->rq_early) {
748                 req->rq_repmsg = lustre_msg_buf(msg, 1, 0);
749                 req->rq_replen = msg->lm_buflens[1];
750                 RETURN(0);
751         }
752
753         if (msg->lm_bufcount < 2 || msg->lm_bufcount > 4) {
754                 CERROR("unexpected bufcount %u\n", msg->lm_bufcount);
755                 RETURN(-EPROTO);
756         }
757
758         swabbed = req_capsule_rep_need_swab(&req->rq_pill);
759
760         ghdr = gss_swab_header(msg, 0, swabbed);
761         if (ghdr == NULL) {
762                 CERROR("can't decode gss header\n");
763                 RETURN(-EPROTO);
764         }
765
766         /* sanity checks */
767         reqhdr = lustre_msg_buf(msg, 0, sizeof(*reqhdr));
768         LASSERT(reqhdr);
769
770         if (ghdr->gh_version != reqhdr->gh_version) {
771                 CERROR("gss version %u mismatch, expect %u\n",
772                        ghdr->gh_version, reqhdr->gh_version);
773                 RETURN(-EPROTO);
774         }
775
776         switch (ghdr->gh_proc) {
777         case PTLRPC_GSS_PROC_DATA:
778                 pack_bulk = ghdr->gh_flags & LUSTRE_GSS_PACK_BULK;
779
780                 if (!req->rq_early &&
781                     !equi(req->rq_pack_bulk == 1, pack_bulk)) {
782                         CERROR("%s bulk flag in reply\n",
783                                req->rq_pack_bulk ? "missing" : "unexpected");
784                         RETURN(-EPROTO);
785                 }
786
787                 if (ghdr->gh_seq != reqhdr->gh_seq) {
788                         CERROR("seqnum %u mismatch, expect %u\n",
789                                ghdr->gh_seq, reqhdr->gh_seq);
790                         RETURN(-EPROTO);
791                 }
792
793                 if (ghdr->gh_svc != reqhdr->gh_svc) {
794                         CERROR("svc %u mismatch, expect %u\n",
795                                ghdr->gh_svc, reqhdr->gh_svc);
796                         RETURN(-EPROTO);
797                 }
798
799                 if (swabbed)
800                         gss_header_swabber(ghdr);
801
802                 major = gss_verify_msg(msg, gctx->gc_mechctx, reqhdr->gh_svc);
803                 if (major != GSS_S_COMPLETE) {
804                         CERROR("failed to verify reply: %x\n", major);
805                         RETURN(-EPERM);
806                 }
807
808                 if (req->rq_early && reqhdr->gh_svc == SPTLRPC_SVC_NULL) {
809                         __u32 cksum;
810
811                         cksum = crc32_le(!(__u32) 0,
812                                          lustre_msg_buf(msg, 1, 0),
813                                          lustre_msg_buflen(msg, 1));
814                         if (cksum != msg->lm_cksum) {
815                                 CWARN("early reply checksum mismatch: %08x != %08x\n",
816                                       cksum, msg->lm_cksum);
817                                 RETURN(-EPROTO);
818                         }
819                 }
820
821                 if (pack_bulk) {
822                         /* bulk checksum is right after the lustre msg */
823                         if (msg->lm_bufcount < 3) {
824                                 CERROR("Invalid reply bufcount %u\n",
825                                        msg->lm_bufcount);
826                                 RETURN(-EPROTO);
827                         }
828
829                         rc = bulk_sec_desc_unpack(msg, 2, swabbed);
830                         if (rc) {
831                                 CERROR("unpack bulk desc: %d\n", rc);
832                                 RETURN(rc);
833                         }
834                 }
835
836                 req->rq_repmsg = lustre_msg_buf(msg, 1, 0);
837                 req->rq_replen = msg->lm_buflens[1];
838                 break;
839         case PTLRPC_GSS_PROC_ERR:
840                 if (req->rq_early) {
841                         CERROR("server return error with early reply\n");
842                         rc = -EPROTO;
843                 } else {
844                         rc = gss_cli_ctx_handle_err_notify(ctx, req, ghdr);
845                 }
846                 break;
847         default:
848                 CERROR("unknown gss proc %d\n", ghdr->gh_proc);
849                 rc = -EPROTO;
850         }
851
852         RETURN(rc);
853 }
854
855 int gss_cli_ctx_seal(struct ptlrpc_cli_ctx *ctx, struct ptlrpc_request *req)
856 {
857         struct gss_cli_ctx      *gctx;
858         rawobj_t                 hdrobj, msgobj, token;
859         struct gss_header       *ghdr;
860         __u32                    buflens[2], major;
861         int                      wiresize, rc;
862         ENTRY;
863
864         LASSERT(req->rq_clrbuf);
865         LASSERT(req->rq_cli_ctx == ctx);
866         LASSERT(req->rq_reqlen);
867
868         gctx = container_of(ctx, struct gss_cli_ctx, gc_base);
869
870         /* final clear data length */
871         req->rq_clrdata_len = lustre_msg_size_v2(req->rq_clrbuf->lm_bufcount,
872                                                  req->rq_clrbuf->lm_buflens);
873
874         /* calculate wire data length */
875         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
876         buflens[1] = gss_cli_payload(&gctx->gc_base, req->rq_clrdata_len, 1);
877         wiresize = lustre_msg_size_v2(2, buflens);
878
879         /* allocate wire buffer */
880         if (req->rq_pool) {
881                 /* pre-allocated */
882                 LASSERT(req->rq_reqbuf);
883                 LASSERT(req->rq_reqbuf != req->rq_clrbuf);
884                 LASSERT(req->rq_reqbuf_len >= wiresize);
885         } else {
886                 OBD_ALLOC_LARGE(req->rq_reqbuf, wiresize);
887                 if (!req->rq_reqbuf)
888                         RETURN(-ENOMEM);
889                 req->rq_reqbuf_len = wiresize;
890         }
891
892         lustre_init_msg_v2(req->rq_reqbuf, 2, buflens, NULL);
893         req->rq_reqbuf->lm_secflvr = req->rq_flvr.sf_rpc;
894
895         /* gss header */
896         ghdr = lustre_msg_buf(req->rq_reqbuf, 0, 0);
897         ghdr->gh_version = PTLRPC_GSS_VERSION;
898         ghdr->gh_sp = (__u8) ctx->cc_sec->ps_part;
899         ghdr->gh_flags = 0;
900         ghdr->gh_proc = gctx->gc_proc;
901         ghdr->gh_svc = SPTLRPC_SVC_PRIV;
902         ghdr->gh_handle.len = gctx->gc_handle.len;
903         memcpy(ghdr->gh_handle.data, gctx->gc_handle.data, gctx->gc_handle.len);
904         if (req->rq_pack_bulk)
905                 ghdr->gh_flags |= LUSTRE_GSS_PACK_BULK;
906         if (req->rq_pack_udesc)
907                 ghdr->gh_flags |= LUSTRE_GSS_PACK_USER;
908
909 redo:
910         ghdr->gh_seq = atomic_inc_return(&gctx->gc_seq);
911
912         /* buffer objects */
913         hdrobj.len = PTLRPC_GSS_HEADER_SIZE;
914         hdrobj.data = (__u8 *) ghdr;
915         msgobj.len = req->rq_clrdata_len;
916         msgobj.data = (__u8 *) req->rq_clrbuf;
917         token.len = lustre_msg_buflen(req->rq_reqbuf, 1);
918         token.data = lustre_msg_buf(req->rq_reqbuf, 1, 0);
919
920         major = lgss_wrap(gctx->gc_mechctx, &hdrobj, &msgobj,
921                           req->rq_clrbuf_len, &token);
922         if (major != GSS_S_COMPLETE) {
923                 CERROR("priv: wrap message error: %08x\n", major);
924                 GOTO(err_free, rc = -EPERM);
925         }
926         LASSERT(token.len <= buflens[1]);
927
928         /* see explain in gss_cli_ctx_sign() */
929         if (unlikely(atomic_read(&gctx->gc_seq) - ghdr->gh_seq >
930                      GSS_SEQ_REPACK_THRESHOLD)) {
931                 int behind = atomic_read(&gctx->gc_seq) - ghdr->gh_seq;
932
933                 gss_stat_oos_record_cli(behind);
934                 CWARN("req %p: %u behind, retry sealing\n", req, behind);
935
936                 ghdr->gh_seq = atomic_inc_return(&gctx->gc_seq);
937                 goto redo;
938         }
939
940         /* now set the final wire data length */
941         req->rq_reqdata_len = lustre_shrink_msg(req->rq_reqbuf, 1, token.len,
942                                                 0);
943         RETURN(0);
944
945 err_free:
946         if (!req->rq_pool) {
947                 OBD_FREE_LARGE(req->rq_reqbuf, req->rq_reqbuf_len);
948                 req->rq_reqbuf = NULL;
949                 req->rq_reqbuf_len = 0;
950         }
951         RETURN(rc);
952 }
953
954 int gss_cli_ctx_unseal(struct ptlrpc_cli_ctx *ctx, struct ptlrpc_request *req)
955 {
956         struct gss_cli_ctx      *gctx;
957         struct gss_header       *ghdr;
958         struct lustre_msg       *msg = req->rq_repdata;
959         int                      msglen, pack_bulk, swabbed, rc;
960         __u32                    major;
961         ENTRY;
962
963         LASSERT(req->rq_cli_ctx == ctx);
964         LASSERT(req->rq_ctx_init == 0);
965         LASSERT(msg);
966
967         gctx = container_of(ctx, struct gss_cli_ctx, gc_base);
968         swabbed = req_capsule_rep_need_swab(&req->rq_pill);
969
970         ghdr = gss_swab_header(msg, 0, swabbed);
971         if (ghdr == NULL) {
972                 CERROR("can't decode gss header\n");
973                 RETURN(-EPROTO);
974         }
975
976         /* sanity checks */
977         if (ghdr->gh_version != PTLRPC_GSS_VERSION) {
978                 CERROR("gss version %u mismatch, expect %u\n",
979                        ghdr->gh_version, PTLRPC_GSS_VERSION);
980                 RETURN(-EPROTO);
981         }
982
983         switch (ghdr->gh_proc) {
984         case PTLRPC_GSS_PROC_DATA:
985                 pack_bulk = ghdr->gh_flags & LUSTRE_GSS_PACK_BULK;
986
987                 if (!req->rq_early && !equi(req->rq_pack_bulk == 1,
988                                             pack_bulk)) {
989                         CERROR("%s bulk flag in reply\n",
990                                req->rq_pack_bulk ? "missing" : "unexpected");
991                         RETURN(-EPROTO);
992                 }
993
994                 if (swabbed)
995                         gss_header_swabber(ghdr);
996
997                 /* use rq_repdata_len as buffer size, which assume unseal
998                  * doesn't need extra memory space. for precise control, we'd
999                  * better calculate out actual buffer size as
1000                  * (repbuf_len - offset - repdata_len)
1001                  */
1002                 major = gss_unseal_msg(gctx->gc_mechctx, msg, &msglen,
1003                                        req->rq_repdata_len);
1004                 if (major != GSS_S_COMPLETE) {
1005                         CERROR("failed to unwrap reply: %x\n", major);
1006                         rc = -EPERM;
1007                         break;
1008                 }
1009
1010                 swabbed = __lustre_unpack_msg(msg, msglen);
1011                 if (swabbed < 0) {
1012                         CERROR("Failed to unpack after decryption\n");
1013                         RETURN(-EPROTO);
1014                 }
1015
1016                 if (msg->lm_bufcount < 1) {
1017                         CERROR("Invalid reply buffer: empty\n");
1018                         RETURN(-EPROTO);
1019                 }
1020
1021                 if (pack_bulk) {
1022                         if (msg->lm_bufcount < 2) {
1023                                 CERROR("bufcount %u: missing bulk sec desc\n",
1024                                        msg->lm_bufcount);
1025                                 RETURN(-EPROTO);
1026                         }
1027
1028                         /* bulk checksum is the last segment */
1029                         if (bulk_sec_desc_unpack(msg, msg->lm_bufcount - 1,
1030                                                  swabbed))
1031                                 RETURN(-EPROTO);
1032                 }
1033
1034                 req->rq_repmsg = lustre_msg_buf(msg, 0, 0);
1035                 req->rq_replen = msg->lm_buflens[0];
1036
1037                 rc = 0;
1038                 break;
1039         case PTLRPC_GSS_PROC_ERR:
1040                 if (req->rq_early) {
1041                         CERROR("server return error with early reply\n");
1042                         rc = -EPROTO;
1043                 } else {
1044                         rc = gss_cli_ctx_handle_err_notify(ctx, req, ghdr);
1045                 }
1046                 break;
1047         default:
1048                 CERROR("unexpected proc %d\n", ghdr->gh_proc);
1049                 rc = -EPERM;
1050         }
1051
1052         RETURN(rc);
1053 }
1054
1055 /* reverse context installation */
1056 static inline
1057 int gss_install_rvs_svc_ctx(struct obd_import *imp, struct gss_sec *gsec,
1058                             struct gss_cli_ctx *gctx)
1059 {
1060         return gss_svc_upcall_install_rvs_ctx(imp, gsec, gctx);
1061 }
1062
1063 /* GSS security APIs */
1064 int gss_sec_create_common(struct gss_sec *gsec,
1065                           struct ptlrpc_sec_policy *policy,
1066                           struct obd_import *imp,
1067                           struct ptlrpc_svc_ctx *svcctx,
1068                           struct sptlrpc_flavor *sf)
1069 {
1070         struct ptlrpc_sec   *sec;
1071
1072         LASSERT(imp);
1073         LASSERT(SPTLRPC_FLVR_POLICY(sf->sf_rpc) == SPTLRPC_POLICY_GSS);
1074
1075         gsec->gs_mech =
1076                 lgss_subflavor_to_mech(SPTLRPC_FLVR_BASE_SUB(sf->sf_rpc));
1077         if (!gsec->gs_mech) {
1078                 CERROR("gss backend 0x%x not found\n",
1079                        SPTLRPC_FLVR_BASE_SUB(sf->sf_rpc));
1080                 return -EOPNOTSUPP;
1081         }
1082
1083         spin_lock_init(&gsec->gs_lock);
1084         gsec->gs_rvs_hdl = 0ULL;
1085
1086         /* initialize upper ptlrpc_sec */
1087         sec = &gsec->gs_base;
1088         sec->ps_policy = policy;
1089         atomic_set(&sec->ps_refcount, 0);
1090         atomic_set(&sec->ps_nctx, 0);
1091         sec->ps_id = sptlrpc_get_next_secid();
1092         sec->ps_flvr = *sf;
1093         sec->ps_import = class_import_get(imp);
1094         spin_lock_init(&sec->ps_lock);
1095         INIT_LIST_HEAD(&sec->ps_gc_list);
1096
1097         if (!svcctx) {
1098                 sec->ps_gc_interval = GSS_GC_INTERVAL;
1099         } else {
1100                 LASSERT(sec_is_reverse(sec));
1101
1102                 /* never do gc on reverse sec */
1103                 sec->ps_gc_interval = 0;
1104         }
1105
1106         if (SPTLRPC_FLVR_BULK_SVC(sec->ps_flvr.sf_rpc) == SPTLRPC_BULK_SVC_PRIV)
1107                 obd_pool_add_user();
1108
1109         CDEBUG(D_SEC, "create %s%s@%p\n", (svcctx ? "reverse " : ""),
1110                policy->sp_name, gsec);
1111         return 0;
1112 }
1113
1114 void gss_sec_destroy_common(struct gss_sec *gsec)
1115 {
1116         struct ptlrpc_sec       *sec = &gsec->gs_base;
1117         ENTRY;
1118
1119         LASSERT(sec->ps_import);
1120         LASSERT(atomic_read(&sec->ps_refcount) == 0);
1121         LASSERT(atomic_read(&sec->ps_nctx) == 0);
1122
1123         if (gsec->gs_mech) {
1124                 lgss_mech_put(gsec->gs_mech);
1125                 gsec->gs_mech = NULL;
1126         }
1127
1128         class_import_put(sec->ps_import);
1129         EXIT;
1130 }
1131
1132 void gss_sec_kill(struct ptlrpc_sec *sec)
1133 {
1134         sec->ps_dying = 1;
1135 }
1136
1137 int gss_cli_ctx_init_common(struct ptlrpc_sec *sec, struct ptlrpc_cli_ctx *ctx,
1138                             struct ptlrpc_ctx_ops *ctxops,
1139                             struct vfs_cred *vcred)
1140 {
1141         struct gss_cli_ctx      *gctx = ctx2gctx(ctx);
1142
1143         gctx->gc_win = 0;
1144         atomic_set(&gctx->gc_seq, 0);
1145
1146         INIT_HLIST_NODE(&ctx->cc_cache);
1147         atomic_set(&ctx->cc_refcount, 0);
1148         ctx->cc_sec = sec;
1149         ctx->cc_ops = ctxops;
1150         ctx->cc_expire = 0;
1151         ctx->cc_flags = PTLRPC_CTX_NEW;
1152         ctx->cc_vcred = *vcred;
1153         spin_lock_init(&ctx->cc_lock);
1154         ctx->cc_impgen = sec->ps_import->imp_generation;
1155         ctx->cc_impconncnt = sec->ps_import->imp_conn_cnt;
1156         INIT_LIST_HEAD(&ctx->cc_req_list);
1157         INIT_LIST_HEAD(&ctx->cc_gc_chain);
1158
1159         /* take a ref on belonging sec, balanced in ctx destroying */
1160         atomic_inc(&sec->ps_refcount);
1161         /* statistic only */
1162         atomic_inc(&sec->ps_nctx);
1163
1164         CDEBUG(D_SEC, "%s@%p: create ctx %p(%u->%s)\n",
1165                sec->ps_policy->sp_name, ctx->cc_sec,
1166                ctx, ctx->cc_vcred.vc_uid, sec2target_str(ctx->cc_sec));
1167         return 0;
1168 }
1169
1170 /*
1171  * return value:
1172  *   1: the context has been taken care of by someone else
1173  *   0: proceed to really destroy the context locally
1174  */
1175 int gss_cli_ctx_fini_common(struct ptlrpc_sec *sec, struct ptlrpc_cli_ctx *ctx)
1176 {
1177         struct gss_cli_ctx *gctx = ctx2gctx(ctx);
1178
1179         LASSERT(atomic_read(&sec->ps_nctx) > 0);
1180         LASSERT(atomic_read(&ctx->cc_refcount) == 0);
1181         LASSERT(ctx->cc_sec == sec);
1182
1183         /*
1184          * remove UPTODATE flag of reverse ctx thus we won't send fini rpc,
1185          * this is to avoid potential problems of client side reverse svc ctx
1186          * be mis-destroyed in various recovery senarios. anyway client can
1187          * manage its reverse ctx well by associating it with its buddy ctx.
1188          */
1189         if (sec_is_reverse(sec))
1190                 ctx->cc_flags &= ~PTLRPC_CTX_UPTODATE;
1191
1192         if (gctx->gc_mechctx) {
1193                 /* the final context fini rpc will use this ctx too, and it's
1194                  * asynchronous which finished by request_out_callback(). so
1195                  * we add refcount, whoever drop finally drop the refcount to
1196                  * 0 should responsible for the rest of destroy.
1197                  */
1198                 atomic_inc(&ctx->cc_refcount);
1199
1200                 gss_do_ctx_fini_rpc(gctx);
1201                 gss_cli_ctx_finalize(gctx);
1202
1203                 if (!atomic_dec_and_test(&ctx->cc_refcount))
1204                         return 1;
1205         }
1206
1207         if (sec_is_reverse(sec))
1208                 CDEBUG(D_SEC, "reverse sec %p: destroy ctx %p\n",
1209                        ctx->cc_sec, ctx);
1210         else
1211                 CDEBUG(D_SEC, "%s@%p: destroy ctx %p(%u->%s)\n",
1212                        sec->ps_policy->sp_name, ctx->cc_sec,
1213                        ctx, ctx->cc_vcred.vc_uid, sec2target_str(ctx->cc_sec));
1214
1215         return 0;
1216 }
1217
1218 static
1219 int gss_alloc_reqbuf_intg(struct ptlrpc_sec *sec, struct ptlrpc_request *req,
1220                           int svc, int msgsize)
1221 {
1222         int                       bufsize, txtsize;
1223         int                       bufcnt = 2;
1224         __u32                     buflens[5];
1225         ENTRY;
1226
1227         /*
1228          * on-wire data layout:
1229          * - gss header
1230          * - lustre message
1231          * - user descriptor (optional)
1232          * - bulk sec descriptor (optional)
1233          * - signature (optional)
1234          *   - svc == NULL: NULL
1235          *   - svc == AUTH: signature of gss header
1236          *   - svc == INTG: signature of all above
1237          *
1238          * if this is context negotiation, reserver fixed space
1239          * at the last (signature) segment regardless of svc mode.
1240          */
1241
1242         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
1243         txtsize = buflens[0];
1244
1245         buflens[1] = msgsize;
1246         if (svc == SPTLRPC_SVC_INTG)
1247                 txtsize += buflens[1];
1248
1249         if (req->rq_pack_udesc) {
1250                 buflens[bufcnt] = sptlrpc_current_user_desc_size();
1251                 if (svc == SPTLRPC_SVC_INTG)
1252                         txtsize += buflens[bufcnt];
1253                 bufcnt++;
1254         }
1255
1256         if (req->rq_pack_bulk) {
1257                 buflens[bufcnt] = gss_cli_bulk_payload(req->rq_cli_ctx,
1258                                                        &req->rq_flvr,
1259                                                        0, req->rq_bulk_read);
1260                 if (svc == SPTLRPC_SVC_INTG)
1261                         txtsize += buflens[bufcnt];
1262                 bufcnt++;
1263         }
1264
1265         if (req->rq_ctx_init)
1266                 buflens[bufcnt++] = GSS_CTX_INIT_MAX_LEN;
1267         else if (svc != SPTLRPC_SVC_NULL)
1268                 buflens[bufcnt++] = gss_cli_payload(req->rq_cli_ctx, txtsize,
1269                                                     0);
1270
1271         bufsize = lustre_msg_size_v2(bufcnt, buflens);
1272
1273         if (!req->rq_reqbuf) {
1274                 bufsize = size_roundup_power2(bufsize);
1275
1276                 OBD_ALLOC_LARGE(req->rq_reqbuf, bufsize);
1277                 if (!req->rq_reqbuf)
1278                         RETURN(-ENOMEM);
1279
1280                 req->rq_reqbuf_len = bufsize;
1281         } else {
1282                 LASSERT(req->rq_pool);
1283                 LASSERT(req->rq_reqbuf_len >= bufsize);
1284                 memset(req->rq_reqbuf, 0, bufsize);
1285         }
1286
1287         lustre_init_msg_v2(req->rq_reqbuf, bufcnt, buflens, NULL);
1288         req->rq_reqbuf->lm_secflvr = req->rq_flvr.sf_rpc;
1289
1290         req->rq_reqmsg = lustre_msg_buf(req->rq_reqbuf, 1, msgsize);
1291         LASSERT(req->rq_reqmsg);
1292
1293         /* pack user desc here, later we might leave current user's process */
1294         if (req->rq_pack_udesc)
1295                 sptlrpc_pack_user_desc(req->rq_reqbuf, 2);
1296
1297         RETURN(0);
1298 }
1299
1300 static
1301 int gss_alloc_reqbuf_priv(struct ptlrpc_sec *sec, struct ptlrpc_request *req,
1302                           int msgsize)
1303 {
1304         __u32                     ibuflens[3], wbuflens[2];
1305         int                       ibufcnt;
1306         int                       clearsize, wiresize;
1307         ENTRY;
1308
1309         LASSERT(req->rq_clrbuf == NULL);
1310         LASSERT(req->rq_clrbuf_len == 0);
1311
1312         /* Inner (clear) buffers
1313          *  - lustre message
1314          *  - user descriptor (optional)
1315          *  - bulk checksum (optional)
1316          */
1317         ibufcnt = 1;
1318         ibuflens[0] = msgsize;
1319
1320         if (req->rq_pack_udesc)
1321                 ibuflens[ibufcnt++] = sptlrpc_current_user_desc_size();
1322         if (req->rq_pack_bulk)
1323                 ibuflens[ibufcnt++] = gss_cli_bulk_payload(req->rq_cli_ctx,
1324                                                            &req->rq_flvr, 0,
1325                                                            req->rq_bulk_read);
1326
1327         clearsize = lustre_msg_size_v2(ibufcnt, ibuflens);
1328         /* to allow append padding during encryption */
1329         clearsize += GSS_MAX_CIPHER_BLOCK;
1330
1331         /* Wrapper (wire) buffers
1332          *  - gss header
1333          *  - cipher text
1334          */
1335         wbuflens[0] = PTLRPC_GSS_HEADER_SIZE;
1336         wbuflens[1] = gss_cli_payload(req->rq_cli_ctx, clearsize, 1);
1337         wiresize = lustre_msg_size_v2(2, wbuflens);
1338
1339         if (req->rq_pool) {
1340                 /* rq_reqbuf is preallocated */
1341                 LASSERT(req->rq_reqbuf);
1342                 LASSERT(req->rq_reqbuf_len >= wiresize);
1343
1344                 memset(req->rq_reqbuf, 0, req->rq_reqbuf_len);
1345
1346                 /* if the pre-allocated buffer is big enough, we just pack
1347                  * both clear buf & request buf in it, to avoid more alloc.
1348                  */
1349                 if (clearsize + wiresize <= req->rq_reqbuf_len) {
1350                         req->rq_clrbuf =
1351                                 (void *) (((char *) req->rq_reqbuf) + wiresize);
1352                 } else {
1353                         CWARN("pre-allocated buf size %d is not enough for both clear (%d) and cipher (%d) text, proceed with extra allocation\n",
1354                               req->rq_reqbuf_len, clearsize, wiresize);
1355                 }
1356         }
1357
1358         if (!req->rq_clrbuf) {
1359                 clearsize = size_roundup_power2(clearsize);
1360
1361                 OBD_ALLOC_LARGE(req->rq_clrbuf, clearsize);
1362                 if (!req->rq_clrbuf)
1363                         RETURN(-ENOMEM);
1364         }
1365         req->rq_clrbuf_len = clearsize;
1366
1367         lustre_init_msg_v2(req->rq_clrbuf, ibufcnt, ibuflens, NULL);
1368         req->rq_reqmsg = lustre_msg_buf(req->rq_clrbuf, 0, msgsize);
1369
1370         if (req->rq_pack_udesc)
1371                 sptlrpc_pack_user_desc(req->rq_clrbuf, 1);
1372
1373         RETURN(0);
1374 }
1375
1376 /*
1377  * NOTE: any change of request buffer allocation should also consider
1378  * changing enlarge_reqbuf() series functions.
1379  */
1380 int gss_alloc_reqbuf(struct ptlrpc_sec *sec, struct ptlrpc_request *req,
1381                      int msgsize)
1382 {
1383         int     svc = SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc);
1384
1385         LASSERT(!req->rq_pack_bulk ||
1386                 (req->rq_bulk_read || req->rq_bulk_write));
1387
1388         switch (svc) {
1389         case SPTLRPC_SVC_NULL:
1390         case SPTLRPC_SVC_AUTH:
1391         case SPTLRPC_SVC_INTG:
1392                 return gss_alloc_reqbuf_intg(sec, req, svc, msgsize);
1393         case SPTLRPC_SVC_PRIV:
1394                 return gss_alloc_reqbuf_priv(sec, req, msgsize);
1395         default:
1396                 LASSERTF(0, "bad rpc flavor %x\n", req->rq_flvr.sf_rpc);
1397                 return 0;
1398         }
1399 }
1400
1401 void gss_free_reqbuf(struct ptlrpc_sec *sec, struct ptlrpc_request *req)
1402 {
1403         int     privacy;
1404         ENTRY;
1405
1406         LASSERT(!req->rq_pool || req->rq_reqbuf);
1407         privacy = SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc) == SPTLRPC_SVC_PRIV;
1408
1409         if (!req->rq_clrbuf)
1410                 goto release_reqbuf;
1411
1412         /* release clear buffer */
1413         LASSERT(privacy);
1414         LASSERT(req->rq_clrbuf_len);
1415
1416         if (req->rq_pool == NULL || req->rq_clrbuf < req->rq_reqbuf ||
1417             (char *) req->rq_clrbuf >= (char *) req->rq_reqbuf +
1418             req->rq_reqbuf_len)
1419                 OBD_FREE_LARGE(req->rq_clrbuf, req->rq_clrbuf_len);
1420
1421         req->rq_clrbuf = NULL;
1422         req->rq_clrbuf_len = 0;
1423
1424 release_reqbuf:
1425         if (!req->rq_pool && req->rq_reqbuf) {
1426                 LASSERT(req->rq_reqbuf_len);
1427
1428                 OBD_FREE_LARGE(req->rq_reqbuf, req->rq_reqbuf_len);
1429                 req->rq_reqbuf = NULL;
1430                 req->rq_reqbuf_len = 0;
1431         }
1432
1433         EXIT;
1434 }
1435
1436 static int do_alloc_repbuf(struct ptlrpc_request *req, int bufsize)
1437 {
1438         bufsize = size_roundup_power2(bufsize);
1439
1440         OBD_ALLOC_LARGE(req->rq_repbuf, bufsize);
1441         if (!req->rq_repbuf)
1442                 return -ENOMEM;
1443
1444         req->rq_repbuf_len = bufsize;
1445         return 0;
1446 }
1447
1448 static
1449 int gss_alloc_repbuf_intg(struct ptlrpc_sec *sec, struct ptlrpc_request *req,
1450                           int svc, int msgsize)
1451 {
1452         int             txtsize;
1453         __u32           buflens[4];
1454         int             bufcnt = 2;
1455         int             alloc_size;
1456
1457         /*
1458          * on-wire data layout:
1459          * - gss header
1460          * - lustre message
1461          * - bulk sec descriptor (optional)
1462          * - signature (optional)
1463          *   - svc == NULL: NULL
1464          *   - svc == AUTH: signature of gss header
1465          *   - svc == INTG: signature of all above
1466          *
1467          * if this is context negotiation, reserver fixed space
1468          * at the last (signature) segment regardless of svc mode.
1469          */
1470
1471         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
1472         txtsize = buflens[0];
1473
1474         buflens[1] = msgsize;
1475         if (svc == SPTLRPC_SVC_INTG)
1476                 txtsize += buflens[1];
1477
1478         if (req->rq_pack_bulk) {
1479                 buflens[bufcnt] = gss_cli_bulk_payload(req->rq_cli_ctx,
1480                                                        &req->rq_flvr, 1,
1481                                                        req->rq_bulk_read);
1482                 if (svc == SPTLRPC_SVC_INTG)
1483                         txtsize += buflens[bufcnt];
1484                 bufcnt++;
1485         }
1486
1487         if (req->rq_ctx_init)
1488                 buflens[bufcnt++] = GSS_CTX_INIT_MAX_LEN;
1489         else if (svc != SPTLRPC_SVC_NULL)
1490                 buflens[bufcnt++] = gss_cli_payload(req->rq_cli_ctx, txtsize,
1491                                                     0);
1492
1493         alloc_size = lustre_msg_size_v2(bufcnt, buflens);
1494
1495         /* add space for early reply */
1496         alloc_size += gss_at_reply_off_integ;
1497
1498         return do_alloc_repbuf(req, alloc_size);
1499 }
1500
1501 static
1502 int gss_alloc_repbuf_priv(struct ptlrpc_sec *sec, struct ptlrpc_request *req,
1503                           int msgsize)
1504 {
1505         int             txtsize;
1506         __u32           buflens[2];
1507         int             bufcnt;
1508         int             alloc_size;
1509
1510         /* inner buffers */
1511         bufcnt = 1;
1512         buflens[0] = msgsize;
1513
1514         if (req->rq_pack_bulk)
1515                 buflens[bufcnt++] = gss_cli_bulk_payload(req->rq_cli_ctx,
1516                                                          &req->rq_flvr, 1,
1517                                                          req->rq_bulk_read);
1518         txtsize = lustre_msg_size_v2(bufcnt, buflens);
1519         txtsize += GSS_MAX_CIPHER_BLOCK;
1520
1521         /* wrapper buffers */
1522         bufcnt = 2;
1523         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
1524         buflens[1] = gss_cli_payload(req->rq_cli_ctx, txtsize, 1);
1525
1526         alloc_size = lustre_msg_size_v2(bufcnt, buflens);
1527         /* add space for early reply */
1528         alloc_size += gss_at_reply_off_priv;
1529
1530         return do_alloc_repbuf(req, alloc_size);
1531 }
1532
1533 int gss_alloc_repbuf(struct ptlrpc_sec *sec, struct ptlrpc_request *req,
1534                      int msgsize)
1535 {
1536         int     svc = SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc);
1537         ENTRY;
1538
1539         LASSERT(!req->rq_pack_bulk ||
1540                 (req->rq_bulk_read || req->rq_bulk_write));
1541
1542         switch (svc) {
1543         case SPTLRPC_SVC_NULL:
1544         case SPTLRPC_SVC_AUTH:
1545         case SPTLRPC_SVC_INTG:
1546                 return gss_alloc_repbuf_intg(sec, req, svc, msgsize);
1547         case SPTLRPC_SVC_PRIV:
1548                 return gss_alloc_repbuf_priv(sec, req, msgsize);
1549         default:
1550                 LASSERTF(0, "bad rpc flavor %x\n", req->rq_flvr.sf_rpc);
1551                 return 0;
1552         }
1553 }
1554
1555 void gss_free_repbuf(struct ptlrpc_sec *sec, struct ptlrpc_request *req)
1556 {
1557         OBD_FREE_LARGE(req->rq_repbuf, req->rq_repbuf_len);
1558         req->rq_repbuf = NULL;
1559         req->rq_repbuf_len = 0;
1560         req->rq_repdata = NULL;
1561         req->rq_repdata_len = 0;
1562 }
1563
1564 static int get_enlarged_msgsize(struct lustre_msg *msg, int segment,
1565                                 int newsize)
1566 {
1567         int save, newmsg_size;
1568
1569         LASSERT(newsize >= msg->lm_buflens[segment]);
1570
1571         save = msg->lm_buflens[segment];
1572         msg->lm_buflens[segment] = newsize;
1573         newmsg_size = lustre_msg_size_v2(msg->lm_bufcount, msg->lm_buflens);
1574         msg->lm_buflens[segment] = save;
1575
1576         return newmsg_size;
1577 }
1578
1579 static int get_enlarged_msgsize2(struct lustre_msg *msg, int segment1,
1580                                  int newsize1, int segment2, int newsize2)
1581 {
1582         int save1, save2, newmsg_size;
1583
1584         LASSERT(newsize1 >= msg->lm_buflens[segment1]);
1585         LASSERT(newsize2 >= msg->lm_buflens[segment2]);
1586
1587         save1 = msg->lm_buflens[segment1];
1588         save2 = msg->lm_buflens[segment2];
1589         msg->lm_buflens[segment1] = newsize1;
1590         msg->lm_buflens[segment2] = newsize2;
1591         newmsg_size = lustre_msg_size_v2(msg->lm_bufcount, msg->lm_buflens);
1592         msg->lm_buflens[segment1] = save1;
1593         msg->lm_buflens[segment2] = save2;
1594
1595         return newmsg_size;
1596 }
1597
1598 static
1599 int gss_enlarge_reqbuf_intg(struct ptlrpc_sec *sec, struct ptlrpc_request *req,
1600                             int svc, int segment, int newsize)
1601 {
1602         struct lustre_msg      *newbuf;
1603         int                     txtsize, sigsize = 0, i;
1604         int                     newmsg_size, newbuf_size;
1605
1606         /*
1607          * gss header is at seg 0;
1608          * embedded msg is at seg 1;
1609          * signature (if any) is at the last seg
1610          */
1611         LASSERT(req->rq_reqbuf);
1612         LASSERT(req->rq_reqbuf_len > req->rq_reqlen);
1613         LASSERT(req->rq_reqbuf->lm_bufcount >= 2);
1614         LASSERT(lustre_msg_buf(req->rq_reqbuf, 1, 0) == req->rq_reqmsg);
1615
1616         /* 1. compute new embedded msg size */
1617         newmsg_size = get_enlarged_msgsize(req->rq_reqmsg, segment, newsize);
1618         LASSERT(newmsg_size >= req->rq_reqbuf->lm_buflens[1]);
1619
1620         /* 2. compute new wrapper msg size */
1621         if (svc == SPTLRPC_SVC_NULL) {
1622                 /* no signature, get size directly */
1623                 newbuf_size = get_enlarged_msgsize(req->rq_reqbuf, 1,
1624                                                    newmsg_size);
1625         } else {
1626                 txtsize = req->rq_reqbuf->lm_buflens[0];
1627
1628                 if (svc == SPTLRPC_SVC_INTG) {
1629                         for (i = 1; i < req->rq_reqbuf->lm_bufcount; i++)
1630                                 txtsize += req->rq_reqbuf->lm_buflens[i];
1631                         txtsize += newmsg_size - req->rq_reqbuf->lm_buflens[1];
1632                 }
1633
1634                 sigsize = gss_cli_payload(req->rq_cli_ctx, txtsize, 0);
1635                 LASSERT(sigsize >= msg_last_seglen(req->rq_reqbuf));
1636
1637                 newbuf_size = get_enlarged_msgsize2(req->rq_reqbuf, 1,
1638                                                     newmsg_size,
1639                                                     msg_last_segidx(req->rq_reqbuf),
1640                                                     sigsize);
1641         }
1642
1643         /* request from pool should always have enough buffer */
1644         LASSERT(!req->rq_pool || req->rq_reqbuf_len >= newbuf_size);
1645
1646         if (req->rq_reqbuf_len < newbuf_size) {
1647                 newbuf_size = size_roundup_power2(newbuf_size);
1648
1649                 OBD_ALLOC_LARGE(newbuf, newbuf_size);
1650                 if (newbuf == NULL)
1651                         RETURN(-ENOMEM);
1652
1653                 /* Must lock this, so that otherwise unprotected change of
1654                  * rq_reqmsg is not racing with parallel processing of
1655                  * imp_replay_list traversing threads. See LU-3333
1656                  * This is a bandaid at best, we really need to deal with this
1657                  * in request enlarging code before unpacking that's already
1658                  * there
1659                  */
1660                 if (req->rq_import)
1661                         spin_lock(&req->rq_import->imp_lock);
1662
1663                 memcpy(newbuf, req->rq_reqbuf, req->rq_reqbuf_len);
1664
1665                 OBD_FREE_LARGE(req->rq_reqbuf, req->rq_reqbuf_len);
1666                 req->rq_reqbuf = newbuf;
1667                 req->rq_reqbuf_len = newbuf_size;
1668                 req->rq_reqmsg = lustre_msg_buf(req->rq_reqbuf, 1, 0);
1669
1670                 if (req->rq_import)
1671                         spin_unlock(&req->rq_import->imp_lock);
1672         }
1673
1674         /* do enlargement, from wrapper to embedded, from end to begin */
1675         if (svc != SPTLRPC_SVC_NULL)
1676                 _sptlrpc_enlarge_msg_inplace(req->rq_reqbuf,
1677                                              msg_last_segidx(req->rq_reqbuf),
1678                                              sigsize);
1679
1680         _sptlrpc_enlarge_msg_inplace(req->rq_reqbuf, 1, newmsg_size);
1681         _sptlrpc_enlarge_msg_inplace(req->rq_reqmsg, segment, newsize);
1682
1683         req->rq_reqlen = newmsg_size;
1684         RETURN(0);
1685 }
1686
1687 static
1688 int gss_enlarge_reqbuf_priv(struct ptlrpc_sec *sec, struct ptlrpc_request *req,
1689                             int segment, int newsize)
1690 {
1691         struct lustre_msg      *newclrbuf;
1692         int                     newmsg_size, newclrbuf_size, newcipbuf_size;
1693         __u32                   buflens[3];
1694
1695         /*
1696          * embedded msg is at seg 0 of clear buffer;
1697          * cipher text is at seg 2 of cipher buffer;
1698          */
1699         LASSERT(req->rq_pool ||
1700                 (req->rq_reqbuf == NULL && req->rq_reqbuf_len == 0));
1701         LASSERT(req->rq_reqbuf == NULL ||
1702                 (req->rq_pool && req->rq_reqbuf->lm_bufcount == 3));
1703         LASSERT(req->rq_clrbuf);
1704         LASSERT(req->rq_clrbuf_len > req->rq_reqlen);
1705         LASSERT(lustre_msg_buf(req->rq_clrbuf, 0, 0) == req->rq_reqmsg);
1706
1707         /* compute new embedded msg size */
1708         newmsg_size = get_enlarged_msgsize(req->rq_reqmsg, segment, newsize);
1709
1710         /* compute new clear buffer size */
1711         newclrbuf_size = get_enlarged_msgsize(req->rq_clrbuf, 0, newmsg_size);
1712         newclrbuf_size += GSS_MAX_CIPHER_BLOCK;
1713
1714         /* compute new cipher buffer size */
1715         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
1716         buflens[1] = gss_cli_payload(req->rq_cli_ctx, buflens[0], 0);
1717         buflens[2] = gss_cli_payload(req->rq_cli_ctx, newclrbuf_size, 1);
1718         newcipbuf_size = lustre_msg_size_v2(3, buflens);
1719
1720         /* handle the case that we put both clear buf and cipher buf into
1721          * pre-allocated single buffer.
1722          */
1723         if (unlikely(req->rq_pool) && req->rq_clrbuf >= req->rq_reqbuf &&
1724             (char *) req->rq_clrbuf < (char *) req->rq_reqbuf +
1725             req->rq_reqbuf_len) {
1726                 /* it couldn't be better we still fit into the
1727                  * pre-allocated buffer.
1728                  */
1729                 if (newclrbuf_size + newcipbuf_size <= req->rq_reqbuf_len) {
1730                         void *src, *dst;
1731
1732                         if (req->rq_import)
1733                                 spin_lock(&req->rq_import->imp_lock);
1734                         /* move clear text backward. */
1735                         src = req->rq_clrbuf;
1736                         dst = (char *) req->rq_reqbuf + newcipbuf_size;
1737
1738                         memmove(dst, src, req->rq_clrbuf_len);
1739
1740                         req->rq_clrbuf = (struct lustre_msg *) dst;
1741                         req->rq_clrbuf_len = newclrbuf_size;
1742                         req->rq_reqmsg = lustre_msg_buf(req->rq_clrbuf, 0, 0);
1743
1744                         if (req->rq_import)
1745                                 spin_unlock(&req->rq_import->imp_lock);
1746                 } else {
1747                         /* sadly we have to split out the clear buffer */
1748                         LASSERT(req->rq_reqbuf_len >= newcipbuf_size);
1749                         LASSERT(req->rq_clrbuf_len < newclrbuf_size);
1750                 }
1751         }
1752
1753         if (req->rq_clrbuf_len < newclrbuf_size) {
1754                 newclrbuf_size = size_roundup_power2(newclrbuf_size);
1755
1756                 OBD_ALLOC_LARGE(newclrbuf, newclrbuf_size);
1757                 if (newclrbuf == NULL)
1758                         RETURN(-ENOMEM);
1759
1760                 /* Must lock this, so that otherwise unprotected change of
1761                  * rq_reqmsg is not racing with parallel processing of
1762                  * imp_replay_list traversing threads. See LU-3333
1763                  * This is a bandaid at best, we really need to deal with this
1764                  * in request enlarging code before unpacking that's already
1765                  * there
1766                  */
1767                 if (req->rq_import)
1768                         spin_lock(&req->rq_import->imp_lock);
1769
1770                 memcpy(newclrbuf, req->rq_clrbuf, req->rq_clrbuf_len);
1771
1772                 if (req->rq_reqbuf == NULL || req->rq_clrbuf < req->rq_reqbuf ||
1773                     (char *) req->rq_clrbuf >= (char *) req->rq_reqbuf +
1774                     req->rq_reqbuf_len) {
1775                         OBD_FREE_LARGE(req->rq_clrbuf, req->rq_clrbuf_len);
1776                 }
1777
1778                 req->rq_clrbuf = newclrbuf;
1779                 req->rq_clrbuf_len = newclrbuf_size;
1780                 req->rq_reqmsg = lustre_msg_buf(req->rq_clrbuf, 0, 0);
1781
1782                 if (req->rq_import)
1783                         spin_unlock(&req->rq_import->imp_lock);
1784         }
1785
1786         _sptlrpc_enlarge_msg_inplace(req->rq_clrbuf, 0, newmsg_size);
1787         _sptlrpc_enlarge_msg_inplace(req->rq_reqmsg, segment, newsize);
1788         req->rq_reqlen = newmsg_size;
1789
1790         RETURN(0);
1791 }
1792
1793 int gss_enlarge_reqbuf(struct ptlrpc_sec *sec, struct ptlrpc_request *req,
1794                        int segment, int newsize)
1795 {
1796         int     svc = SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc);
1797
1798         LASSERT(!req->rq_ctx_init && !req->rq_ctx_fini);
1799
1800         switch (svc) {
1801         case SPTLRPC_SVC_NULL:
1802         case SPTLRPC_SVC_AUTH:
1803         case SPTLRPC_SVC_INTG:
1804                 return gss_enlarge_reqbuf_intg(sec, req, svc, segment, newsize);
1805         case SPTLRPC_SVC_PRIV:
1806                 return gss_enlarge_reqbuf_priv(sec, req, segment, newsize);
1807         default:
1808                 LASSERTF(0, "bad rpc flavor %x\n", req->rq_flvr.sf_rpc);
1809                 return 0;
1810         }
1811 }
1812
1813 int gss_sec_install_rctx(struct obd_import *imp, struct ptlrpc_sec *sec,
1814                          struct ptlrpc_cli_ctx *ctx)
1815 {
1816         struct gss_sec     *gsec;
1817         struct gss_cli_ctx *gctx;
1818         int                 rc;
1819
1820         gsec = container_of(sec, struct gss_sec, gs_base);
1821         gctx = container_of(ctx, struct gss_cli_ctx, gc_base);
1822
1823         rc = gss_install_rvs_svc_ctx(imp, gsec, gctx);
1824         return rc;
1825 }
1826
1827 /* server side API */
1828 static inline
1829 int gss_svc_reqctx_is_special(struct gss_svc_reqctx *grctx)
1830 {
1831         LASSERT(grctx);
1832         return (grctx->src_init || grctx->src_init_continue ||
1833                 grctx->src_err_notify);
1834 }
1835
1836 static
1837 void gss_svc_reqctx_free(struct gss_svc_reqctx *grctx)
1838 {
1839         if (grctx->src_ctx)
1840                 gss_svc_upcall_put_ctx(grctx->src_ctx);
1841
1842         sptlrpc_policy_put(grctx->src_base.sc_policy);
1843         OBD_FREE_PTR(grctx);
1844 }
1845
1846 static inline
1847 void gss_svc_reqctx_addref(struct gss_svc_reqctx *grctx)
1848 {
1849         LASSERT(atomic_read(&grctx->src_base.sc_refcount) > 0);
1850         atomic_inc(&grctx->src_base.sc_refcount);
1851 }
1852
1853 static inline
1854 void gss_svc_reqctx_decref(struct gss_svc_reqctx *grctx)
1855 {
1856         LASSERT(atomic_read(&grctx->src_base.sc_refcount) > 0);
1857
1858         if (atomic_dec_and_test(&grctx->src_base.sc_refcount))
1859                 gss_svc_reqctx_free(grctx);
1860 }
1861
1862 static
1863 int gss_svc_sign(struct ptlrpc_request *req, struct ptlrpc_reply_state *rs,
1864                  struct gss_svc_reqctx *grctx, __u32 svc)
1865 {
1866         __u32   flags = 0;
1867         int     rc;
1868         ENTRY;
1869
1870         LASSERT(rs->rs_msg == lustre_msg_buf(rs->rs_repbuf, 1, 0));
1871
1872         /* embedded lustre_msg might have been shrunk */
1873         if (req->rq_replen != rs->rs_repbuf->lm_buflens[1])
1874                 lustre_shrink_msg(rs->rs_repbuf, 1, req->rq_replen, 1);
1875
1876         if (req->rq_pack_bulk)
1877                 flags |= LUSTRE_GSS_PACK_BULK;
1878
1879         rc = gss_sign_msg(rs->rs_repbuf, grctx->src_ctx->gsc_mechctx,
1880                           LUSTRE_SP_ANY, flags, PTLRPC_GSS_PROC_DATA,
1881                           grctx->src_wirectx.gw_seq, svc, NULL);
1882         if (rc < 0)
1883                 RETURN(rc);
1884
1885         rs->rs_repdata_len = rc;
1886
1887         if (likely(req->rq_packed_final)) {
1888                 if (lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT)
1889                         req->rq_reply_off = gss_at_reply_off_integ;
1890                 else
1891                         req->rq_reply_off = 0;
1892         } else {
1893                 if (svc == SPTLRPC_SVC_NULL)
1894                         rs->rs_repbuf->lm_cksum = crc32_le(!(__u32) 0,
1895                                         lustre_msg_buf(rs->rs_repbuf, 1, 0),
1896                                         lustre_msg_buflen(rs->rs_repbuf, 1));
1897                 req->rq_reply_off = 0;
1898         }
1899
1900         RETURN(0);
1901 }
1902
1903 int gss_pack_err_notify(struct ptlrpc_request *req, __u32 major, __u32 minor)
1904 {
1905         struct gss_svc_reqctx     *grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
1906         struct ptlrpc_reply_state *rs;
1907         struct gss_err_header     *ghdr;
1908         int                        replen = sizeof(struct ptlrpc_body);
1909         int                        rc;
1910         ENTRY;
1911
1912         grctx->src_err_notify = 1;
1913         grctx->src_reserve_len = 0;
1914
1915         rc = lustre_pack_reply_v2(req, 1, &replen, NULL, 0);
1916         if (rc) {
1917                 CERROR("could not pack reply, err %d\n", rc);
1918                 RETURN(rc);
1919         }
1920
1921         /* gss hdr */
1922         rs = req->rq_reply_state;
1923         LASSERT(rs->rs_repbuf->lm_buflens[1] >= sizeof(*ghdr));
1924         ghdr = lustre_msg_buf(rs->rs_repbuf, 0, 0);
1925         ghdr->gh_version = PTLRPC_GSS_VERSION;
1926         ghdr->gh_flags = 0;
1927         ghdr->gh_proc = PTLRPC_GSS_PROC_ERR;
1928         ghdr->gh_major = major;
1929         ghdr->gh_minor = minor;
1930         ghdr->gh_handle.len = 0; /* fake context handle */
1931
1932         rs->rs_repdata_len = lustre_msg_size_v2(rs->rs_repbuf->lm_bufcount,
1933                                                 rs->rs_repbuf->lm_buflens);
1934
1935         CDEBUG(D_SEC, "prepare gss error notify(0x%x/0x%x) to %s\n", major,
1936                minor, libcfs_nidstr(&req->rq_peer.nid));
1937         RETURN(0);
1938 }
1939
1940 static
1941 int gss_svc_handle_init(struct ptlrpc_request *req, struct gss_wire_ctx *gw)
1942 {
1943         struct gss_svc_reqctx *grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
1944         struct lustre_msg *reqbuf = req->rq_reqbuf;
1945         struct obd_uuid *uuid;
1946         struct obd_device *target;
1947         rawobj_t uuid_obj, rvs_hdl, in_token;
1948         __u32 lustre_svc;
1949         __u32 *secdata, seclen;
1950         int swabbed, rc;
1951
1952         ENTRY;
1953         CDEBUG(D_SEC, "processing gss init(%d) request from %s\n", gw->gw_proc,
1954                libcfs_nidstr(&req->rq_peer.nid));
1955
1956         req->rq_ctx_init = 1;
1957
1958         if (gw->gw_flags & LUSTRE_GSS_PACK_BULK) {
1959                 rc = SECSVC_DROP;
1960                 CDEBUG(D_SEC, "unexpected bulk flag: rc = %d\n", rc);
1961                 RETURN(rc);
1962         }
1963
1964         if (gw->gw_proc == PTLRPC_GSS_PROC_INIT && gw->gw_handle.len != 0) {
1965                 rc = SECSVC_DROP;
1966                 CDEBUG(D_SEC, "proc %u: invalid handle length %u: rc = %d\n",
1967                        gw->gw_proc, gw->gw_handle.len, rc);
1968                 RETURN(rc);
1969         }
1970
1971         if (reqbuf->lm_bufcount < 3 || reqbuf->lm_bufcount > 4) {
1972                 rc = SECSVC_DROP;
1973                 CDEBUG(D_SEC, "Invalid bufcount %d: rc = %d\n",
1974                        reqbuf->lm_bufcount, rc);
1975                 RETURN(rc);
1976         }
1977
1978         swabbed = req_capsule_req_need_swab(&req->rq_pill);
1979
1980         /* ctx initiate payload is in last segment */
1981         secdata = lustre_msg_buf(reqbuf, reqbuf->lm_bufcount - 1, 0);
1982         seclen = reqbuf->lm_buflens[reqbuf->lm_bufcount - 1];
1983
1984         if (seclen < 4 + 4) {
1985                 rc = SECSVC_DROP;
1986                 CDEBUG(D_SEC, "sec size %d too small: rc = %d\n", seclen, rc);
1987                 RETURN(rc);
1988         }
1989
1990         /* lustre svc type */
1991         lustre_svc = le32_to_cpu(*secdata++);
1992         seclen -= 4;
1993
1994         /* extract target uuid, note this code is somewhat fragile
1995          * because touched internal structure of obd_uuid
1996          */
1997         if (rawobj_extract(&uuid_obj, &secdata, &seclen)) {
1998                 rc = SECSVC_DROP;
1999                 CDEBUG(D_SEC, "failed to extract target uuid: rc = %d\n", rc);
2000                 RETURN(rc);
2001         }
2002         uuid_obj.data[uuid_obj.len - 1] = '\0';
2003
2004         uuid = (struct obd_uuid *) uuid_obj.data;
2005         target = class_uuid2obd(uuid);
2006         if (!target || target->obd_stopping || !target->obd_set_up) {
2007                 char *target_start;
2008                 int target_len;
2009
2010                 if (gss_pack_err_notify(req, GSS_S_NO_CONTEXT, 0) == 0)
2011                         rc = SECSVC_COMPLETE;
2012                 else
2013                         rc = SECSVC_DROP;
2014
2015                 deuuidify(uuid->uuid, NULL, &target_start, &target_len);
2016                 LCONSOLE_ERROR("%.*s: not available for GSS context init from %s (%s).\n",
2017                                target_len, target_start,
2018                                libcfs_nidstr(&req->rq_peer.nid),
2019                                target ?
2020                                (target->obd_stopping ?
2021                                 "stopping" : "not set up") :
2022                                "no target");
2023                 RETURN(rc);
2024         }
2025
2026         /* extract reverse handle */
2027         if (rawobj_extract(&rvs_hdl, &secdata, &seclen)) {
2028                 rc = SECSVC_DROP;
2029                 CDEBUG(D_SEC, "%s: failed extract reverse handle: rc = %d\n",
2030                        target->obd_name, rc);
2031                 RETURN(rc);
2032         }
2033
2034         /* extract token */
2035         if (rawobj_extract(&in_token, &secdata, &seclen)) {
2036                 rc = SECSVC_DROP;
2037                 CDEBUG(D_SEC, "%s: can't extract token: rc = %d\n",
2038                        target->obd_name, rc);
2039                 RETURN(rc);
2040         }
2041
2042         rc = gss_svc_upcall_handle_init(req, grctx, gw, target, lustre_svc,
2043                                         &rvs_hdl, &in_token);
2044         if (rc != SECSVC_OK)
2045                 RETURN(rc);
2046
2047         if (grctx->src_ctx->gsc_usr_mds || grctx->src_ctx->gsc_usr_oss ||
2048             grctx->src_ctx->gsc_usr_root)
2049                 CDEBUG(D_SEC,
2050                        "%s: create svc ctx %p: user from %s authenticated as %s\n",
2051                        target->obd_name,
2052                        grctx->src_ctx, libcfs_nidstr(&req->rq_peer.nid),
2053                        grctx->src_ctx->gsc_usr_root ? "root" :
2054                        (grctx->src_ctx->gsc_usr_mds ? "mds" :
2055                         (grctx->src_ctx->gsc_usr_oss ? "oss" : "null")));
2056         else
2057                 CDEBUG(D_SEC, "%s: create svc ctx %p: accept user %u from %s\n",
2058                        target->obd_name,
2059                        grctx->src_ctx, grctx->src_ctx->gsc_uid,
2060                        libcfs_nidstr(&req->rq_peer.nid));
2061
2062         if (gw->gw_flags & LUSTRE_GSS_PACK_USER) {
2063                 if (reqbuf->lm_bufcount < 4) {
2064                         rc = SECSVC_DROP;
2065                         CDEBUG(D_SEC, "%s: missing user descriptor: rc = %d\n",
2066                                target->obd_name, rc);
2067                         RETURN(rc);
2068                 }
2069                 if (sptlrpc_unpack_user_desc(reqbuf, 2, swabbed)) {
2070                         rc = SECSVC_DROP;
2071                         CDEBUG(D_SEC,
2072                                "%s: Mal-formed user descriptor: rc = %d\n",
2073                                target->obd_name, rc);
2074                         RETURN(rc);
2075                 }
2076
2077                 req->rq_pack_udesc = 1;
2078                 req->rq_user_desc = lustre_msg_buf(reqbuf, 2, 0);
2079         }
2080
2081         req->rq_reqmsg = lustre_msg_buf(reqbuf, 1, 0);
2082         req->rq_reqlen = lustre_msg_buflen(reqbuf, 1);
2083
2084         RETURN(rc);
2085 }
2086
2087 /*
2088  * last segment must be the gss signature.
2089  */
2090 static
2091 int gss_svc_verify_request(struct ptlrpc_request *req,
2092                            struct gss_svc_reqctx *grctx,
2093                            struct gss_wire_ctx *gw, __u32 *major)
2094 {
2095         struct gss_svc_ctx *gctx = grctx->src_ctx;
2096         struct lustre_msg  *msg = req->rq_reqbuf;
2097         int                 offset = 2;
2098         int                 swabbed;
2099         ENTRY;
2100
2101         *major = GSS_S_COMPLETE;
2102
2103         if (msg->lm_bufcount < 2) {
2104                 CERROR("Too few segments (%u) in request\n", msg->lm_bufcount);
2105                 RETURN(-EINVAL);
2106         }
2107
2108         if (gw->gw_svc == SPTLRPC_SVC_NULL)
2109                 goto verified;
2110
2111         if (gss_check_seq_num(&gctx->gsc_seqdata, gw->gw_seq, 0)) {
2112                 CERROR("phase 0: discard replayed req: seq %u\n", gw->gw_seq);
2113                 *major = GSS_S_DUPLICATE_TOKEN;
2114                 RETURN(-EACCES);
2115         }
2116
2117         *major = gss_verify_msg(msg, gctx->gsc_mechctx, gw->gw_svc);
2118         if (*major != GSS_S_COMPLETE) {
2119                 CERROR("failed to verify request: %x\n", *major);
2120                 RETURN(-EACCES);
2121         }
2122
2123         if (gctx->gsc_reverse == 0 &&
2124             gss_check_seq_num(&gctx->gsc_seqdata, gw->gw_seq, 1)) {
2125                 CERROR("phase 1+: discard replayed req: seq %u\n", gw->gw_seq);
2126                 *major = GSS_S_DUPLICATE_TOKEN;
2127                 RETURN(-EACCES);
2128         }
2129
2130 verified:
2131         swabbed = req_capsule_req_need_swab(&req->rq_pill);
2132
2133         /* user descriptor */
2134         if (gw->gw_flags & LUSTRE_GSS_PACK_USER) {
2135                 if (msg->lm_bufcount < (offset + 1)) {
2136                         CERROR("no user desc included\n");
2137                         RETURN(-EINVAL);
2138                 }
2139
2140                 if (sptlrpc_unpack_user_desc(msg, offset, swabbed)) {
2141                         CERROR("Mal-formed user descriptor\n");
2142                         RETURN(-EINVAL);
2143                 }
2144
2145                 req->rq_pack_udesc = 1;
2146                 req->rq_user_desc = lustre_msg_buf(msg, offset, 0);
2147                 offset++;
2148         }
2149
2150         /* check bulk_sec_desc data */
2151         if (gw->gw_flags & LUSTRE_GSS_PACK_BULK) {
2152                 if (msg->lm_bufcount < (offset + 1)) {
2153                         CERROR("missing bulk sec descriptor\n");
2154                         RETURN(-EINVAL);
2155                 }
2156
2157                 if (bulk_sec_desc_unpack(msg, offset, swabbed))
2158                         RETURN(-EINVAL);
2159
2160                 req->rq_pack_bulk = 1;
2161                 grctx->src_reqbsd = lustre_msg_buf(msg, offset, 0);
2162                 grctx->src_reqbsd_size = lustre_msg_buflen(msg, offset);
2163         }
2164
2165         req->rq_reqmsg = lustre_msg_buf(msg, 1, 0);
2166         req->rq_reqlen = msg->lm_buflens[1];
2167         RETURN(0);
2168 }
2169
2170 static
2171 int gss_svc_unseal_request(struct ptlrpc_request *req,
2172                            struct gss_svc_reqctx *grctx,
2173                            struct gss_wire_ctx *gw, __u32 *major)
2174 {
2175         struct gss_svc_ctx *gctx = grctx->src_ctx;
2176         struct lustre_msg  *msg = req->rq_reqbuf;
2177         int                 swabbed, msglen, offset = 1;
2178         ENTRY;
2179
2180         if (gss_check_seq_num(&gctx->gsc_seqdata, gw->gw_seq, 0)) {
2181                 CERROR("phase 0: discard replayed req: seq %u\n", gw->gw_seq);
2182                 *major = GSS_S_DUPLICATE_TOKEN;
2183                 RETURN(-EACCES);
2184         }
2185
2186         *major = gss_unseal_msg(gctx->gsc_mechctx, msg, &msglen,
2187                                 req->rq_reqdata_len);
2188         if (*major != GSS_S_COMPLETE) {
2189                 CERROR("failed to unwrap request: %x\n", *major);
2190                 RETURN(-EACCES);
2191         }
2192
2193         if (gss_check_seq_num(&gctx->gsc_seqdata, gw->gw_seq, 1)) {
2194                 CERROR("phase 1+: discard replayed req: seq %u\n", gw->gw_seq);
2195                 *major = GSS_S_DUPLICATE_TOKEN;
2196                 RETURN(-EACCES);
2197         }
2198
2199         swabbed = __lustre_unpack_msg(msg, msglen);
2200         if (swabbed < 0) {
2201                 CERROR("Failed to unpack after decryption\n");
2202                 RETURN(-EINVAL);
2203         }
2204         req->rq_reqdata_len = msglen;
2205
2206         if (msg->lm_bufcount < 1) {
2207                 CERROR("Invalid buffer: is empty\n");
2208                 RETURN(-EINVAL);
2209         }
2210
2211         if (gw->gw_flags & LUSTRE_GSS_PACK_USER) {
2212                 if (msg->lm_bufcount < offset + 1) {
2213                         CERROR("no user descriptor included\n");
2214                         RETURN(-EINVAL);
2215                 }
2216
2217                 if (sptlrpc_unpack_user_desc(msg, offset, swabbed)) {
2218                         CERROR("Mal-formed user descriptor\n");
2219                         RETURN(-EINVAL);
2220                 }
2221
2222                 req->rq_pack_udesc = 1;
2223                 req->rq_user_desc = lustre_msg_buf(msg, offset, 0);
2224                 offset++;
2225         }
2226
2227         if (gw->gw_flags & LUSTRE_GSS_PACK_BULK) {
2228                 if (msg->lm_bufcount < offset + 1) {
2229                         CERROR("no bulk checksum included\n");
2230                         RETURN(-EINVAL);
2231                 }
2232
2233                 if (bulk_sec_desc_unpack(msg, offset, swabbed))
2234                         RETURN(-EINVAL);
2235
2236                 req->rq_pack_bulk = 1;
2237                 grctx->src_reqbsd = lustre_msg_buf(msg, offset, 0);
2238                 grctx->src_reqbsd_size = lustre_msg_buflen(msg, offset);
2239         }
2240
2241         req->rq_reqmsg = lustre_msg_buf(req->rq_reqbuf, 0, 0);
2242         req->rq_reqlen = req->rq_reqbuf->lm_buflens[0];
2243         RETURN(0);
2244 }
2245
2246 static
2247 int gss_svc_handle_data(struct ptlrpc_request *req, struct gss_wire_ctx *gw)
2248 {
2249         struct gss_svc_reqctx *grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
2250         __u32                  major = 0;
2251         int                    rc = 0;
2252         ENTRY;
2253
2254         grctx->src_ctx = gss_svc_upcall_get_ctx(req, gw);
2255         if (!grctx->src_ctx) {
2256                 major = GSS_S_NO_CONTEXT;
2257                 goto error;
2258         }
2259
2260         switch (gw->gw_svc) {
2261         case SPTLRPC_SVC_NULL:
2262         case SPTLRPC_SVC_AUTH:
2263         case SPTLRPC_SVC_INTG:
2264                 rc = gss_svc_verify_request(req, grctx, gw, &major);
2265                 break;
2266         case SPTLRPC_SVC_PRIV:
2267                 rc = gss_svc_unseal_request(req, grctx, gw, &major);
2268                 break;
2269         default:
2270                 CERROR("unsupported gss service %d\n", gw->gw_svc);
2271                 rc = -EINVAL;
2272         }
2273
2274         if (rc == 0)
2275                 RETURN(SECSVC_OK);
2276
2277         CERROR("svc %u failed: major 0x%08x: req xid %llu ctx %p idx %#llx(%u->%s)\n",
2278                gw->gw_svc, major, req->rq_xid, grctx->src_ctx,
2279                gss_handle_to_u64(&gw->gw_handle), grctx->src_ctx->gsc_uid,
2280                libcfs_nidstr(&req->rq_peer.nid));
2281 error:
2282         /* we only notify client in case of NO_CONTEXT/BAD_SIG, which
2283          * might happen after server reboot, to allow recovery.
2284          */
2285         if ((major == GSS_S_NO_CONTEXT || major == GSS_S_BAD_SIG) &&
2286             gss_pack_err_notify(req, major, 0) == 0)
2287                 RETURN(SECSVC_COMPLETE);
2288
2289         RETURN(SECSVC_DROP);
2290 }
2291
2292 static
2293 int gss_svc_handle_destroy(struct ptlrpc_request *req, struct gss_wire_ctx *gw)
2294 {
2295         struct gss_svc_reqctx  *grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
2296         __u32                   major;
2297         ENTRY;
2298
2299         req->rq_ctx_fini = 1;
2300         req->rq_no_reply = 1;
2301
2302         grctx->src_ctx = gss_svc_upcall_get_ctx(req, gw);
2303         if (!grctx->src_ctx) {
2304                 CDEBUG(D_SEC, "invalid gss context handle for destroy.\n");
2305                 RETURN(SECSVC_DROP);
2306         }
2307
2308         if (gw->gw_svc != SPTLRPC_SVC_INTG) {
2309                 CERROR("svc %u is not supported in destroy.\n", gw->gw_svc);
2310                 RETURN(SECSVC_DROP);
2311         }
2312
2313         if (gss_svc_verify_request(req, grctx, gw, &major))
2314                 RETURN(SECSVC_DROP);
2315
2316         CDEBUG(D_SEC, "destroy svc ctx %p idx %#llx (%u->%s)\n",
2317                grctx->src_ctx, gss_handle_to_u64(&gw->gw_handle),
2318                grctx->src_ctx->gsc_uid, libcfs_nidstr(&req->rq_peer.nid));
2319
2320         gss_svc_upcall_destroy_ctx(grctx->src_ctx);
2321
2322         if (gw->gw_flags & LUSTRE_GSS_PACK_USER) {
2323                 if (req->rq_reqbuf->lm_bufcount < 4) {
2324                         CERROR("missing user descriptor, ignore it\n");
2325                         RETURN(SECSVC_OK);
2326                 }
2327                 if (sptlrpc_unpack_user_desc(req->rq_reqbuf, 2,
2328                                 req_capsule_req_need_swab(&req->rq_pill))) {
2329                         CERROR("Mal-formed user descriptor, ignore it\n");
2330                         RETURN(SECSVC_OK);
2331                 }
2332
2333                 req->rq_pack_udesc = 1;
2334                 req->rq_user_desc = lustre_msg_buf(req->rq_reqbuf, 2, 0);
2335         }
2336
2337         RETURN(SECSVC_OK);
2338 }
2339
2340 int gss_svc_accept(struct ptlrpc_sec_policy *policy, struct ptlrpc_request *req)
2341 {
2342         struct gss_header      *ghdr;
2343         struct gss_svc_reqctx  *grctx;
2344         struct gss_wire_ctx    *gw;
2345         int                     swabbed, rc;
2346         ENTRY;
2347
2348         LASSERT(req->rq_reqbuf);
2349         LASSERT(req->rq_svc_ctx == NULL);
2350
2351         if (req->rq_reqbuf->lm_bufcount < 2) {
2352                 CERROR("buf count only %d\n", req->rq_reqbuf->lm_bufcount);
2353                 RETURN(SECSVC_DROP);
2354         }
2355
2356         swabbed = req_capsule_req_need_swab(&req->rq_pill);
2357
2358         ghdr = gss_swab_header(req->rq_reqbuf, 0, swabbed);
2359         if (ghdr == NULL) {
2360                 CERROR("can't decode gss header\n");
2361                 RETURN(SECSVC_DROP);
2362         }
2363
2364         /* sanity checks */
2365         if (ghdr->gh_version != PTLRPC_GSS_VERSION) {
2366                 CERROR("gss version %u, expect %u\n", ghdr->gh_version,
2367                        PTLRPC_GSS_VERSION);
2368                 RETURN(SECSVC_DROP);
2369         }
2370
2371         req->rq_sp_from = ghdr->gh_sp;
2372
2373         /* alloc grctx data */
2374         OBD_ALLOC_PTR(grctx);
2375         if (!grctx)
2376                 RETURN(SECSVC_DROP);
2377
2378         grctx->src_base.sc_policy = sptlrpc_policy_get(policy);
2379         atomic_set(&grctx->src_base.sc_refcount, 1);
2380         req->rq_svc_ctx = &grctx->src_base;
2381         gw = &grctx->src_wirectx;
2382
2383         /* save wire context */
2384         gw->gw_flags = ghdr->gh_flags;
2385         gw->gw_proc = ghdr->gh_proc;
2386         gw->gw_seq = ghdr->gh_seq;
2387         gw->gw_svc = ghdr->gh_svc;
2388         rawobj_from_netobj(&gw->gw_handle, &ghdr->gh_handle);
2389
2390         /* keep original wire header which subject to checksum verification */
2391         if (swabbed)
2392                 gss_header_swabber(ghdr);
2393
2394         switch (ghdr->gh_proc) {
2395         case PTLRPC_GSS_PROC_INIT:
2396         case PTLRPC_GSS_PROC_CONTINUE_INIT:
2397                 rc = gss_svc_handle_init(req, gw);
2398                 break;
2399         case PTLRPC_GSS_PROC_DATA:
2400                 rc = gss_svc_handle_data(req, gw);
2401                 break;
2402         case PTLRPC_GSS_PROC_DESTROY:
2403                 rc = gss_svc_handle_destroy(req, gw);
2404                 break;
2405         default:
2406                 CERROR("unknown proc %u\n", gw->gw_proc);
2407                 rc = SECSVC_DROP;
2408                 break;
2409         }
2410
2411         switch (rc) {
2412         case SECSVC_OK:
2413                 LASSERT (grctx->src_ctx);
2414
2415                 req->rq_auth_gss = 1;
2416                 req->rq_auth_usr_mdt = grctx->src_ctx->gsc_usr_mds;
2417                 req->rq_auth_usr_ost = grctx->src_ctx->gsc_usr_oss;
2418                 req->rq_auth_usr_root = grctx->src_ctx->gsc_usr_root;
2419                 req->rq_auth_uid = grctx->src_ctx->gsc_uid;
2420                 req->rq_auth_mapped_uid = grctx->src_ctx->gsc_mapped_uid;
2421                 break;
2422         case SECSVC_COMPLETE:
2423                 break;
2424         case SECSVC_DROP:
2425                 gss_svc_reqctx_free(grctx);
2426                 req->rq_svc_ctx = NULL;
2427                 break;
2428         }
2429
2430         RETURN(rc);
2431 }
2432
2433 void gss_svc_invalidate_ctx(struct ptlrpc_svc_ctx *svc_ctx)
2434 {
2435         struct gss_svc_reqctx  *grctx;
2436         ENTRY;
2437
2438         if (svc_ctx == NULL) {
2439                 EXIT;
2440                 return;
2441         }
2442
2443         grctx = gss_svc_ctx2reqctx(svc_ctx);
2444
2445         CWARN("gss svc invalidate ctx %p(%u)\n", grctx->src_ctx,
2446               grctx->src_ctx->gsc_uid);
2447         gss_svc_upcall_destroy_ctx(grctx->src_ctx);
2448
2449         EXIT;
2450 }
2451
2452 static inline
2453 int gss_svc_payload(struct gss_svc_reqctx *grctx, int early,
2454                     int msgsize, int privacy)
2455 {
2456         /* we should treat early reply normally, but which is actually sharing
2457          * the same ctx with original request, so in this case we should
2458          * ignore the special ctx's special flags
2459          */
2460         if (early == 0 && gss_svc_reqctx_is_special(grctx))
2461                 return grctx->src_reserve_len;
2462
2463         return gss_mech_payload(NULL, msgsize, privacy);
2464 }
2465
2466 static int gss_svc_bulk_payload(struct gss_svc_ctx *gctx,
2467                                 struct sptlrpc_flavor *flvr, int read)
2468 {
2469         int     payload = sizeof(struct ptlrpc_bulk_sec_desc);
2470
2471         if (read) {
2472                 switch (SPTLRPC_FLVR_BULK_SVC(flvr->sf_rpc)) {
2473                 case SPTLRPC_BULK_SVC_NULL:
2474                         break;
2475                 case SPTLRPC_BULK_SVC_INTG:
2476                         payload += gss_mech_payload(NULL, 0, 0);
2477                         break;
2478                 case SPTLRPC_BULK_SVC_PRIV:
2479                         payload += gss_mech_payload(NULL, 0, 1);
2480                         break;
2481                 case SPTLRPC_BULK_SVC_AUTH:
2482                 default:
2483                         LBUG();
2484                 }
2485         }
2486
2487         return payload;
2488 }
2489
2490 int gss_svc_alloc_rs(struct ptlrpc_request *req, int msglen)
2491 {
2492         struct gss_svc_reqctx       *grctx;
2493         struct ptlrpc_reply_state   *rs;
2494         int                          early, privacy, svc, bsd_off = 0;
2495         __u32                        ibuflens[2], buflens[4];
2496         int                          ibufcnt = 0, bufcnt;
2497         int                          txtsize, wmsg_size, rs_size;
2498         ENTRY;
2499
2500         LASSERT(msglen % 8 == 0);
2501
2502         if (req->rq_pack_bulk && !req->rq_bulk_read && !req->rq_bulk_write) {
2503                 CERROR("client request bulk sec on non-bulk rpc\n");
2504                 RETURN(-EPROTO);
2505         }
2506
2507         svc = SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc);
2508         early = (req->rq_packed_final == 0);
2509
2510         grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
2511         if (!early && gss_svc_reqctx_is_special(grctx))
2512                 privacy = 0;
2513         else
2514                 privacy = (svc == SPTLRPC_SVC_PRIV);
2515
2516         if (privacy) {
2517                 /* inner clear buffers */
2518                 ibufcnt = 1;
2519                 ibuflens[0] = msglen;
2520
2521                 if (req->rq_pack_bulk) {
2522                         LASSERT(grctx->src_reqbsd);
2523
2524                         bsd_off = ibufcnt;
2525                         ibuflens[ibufcnt++] = gss_svc_bulk_payload(
2526                                                         grctx->src_ctx,
2527                                                         &req->rq_flvr,
2528                                                         req->rq_bulk_read);
2529                 }
2530
2531                 txtsize = lustre_msg_size_v2(ibufcnt, ibuflens);
2532                 txtsize += GSS_MAX_CIPHER_BLOCK;
2533
2534                 /* wrapper buffer */
2535                 bufcnt = 2;
2536                 buflens[0] = PTLRPC_GSS_HEADER_SIZE;
2537                 buflens[1] = gss_svc_payload(grctx, early, txtsize, 1);
2538         } else {
2539                 bufcnt = 2;
2540                 buflens[0] = PTLRPC_GSS_HEADER_SIZE;
2541                 buflens[1] = msglen;
2542
2543                 txtsize = buflens[0];
2544                 if (svc == SPTLRPC_SVC_INTG)
2545                         txtsize += buflens[1];
2546
2547                 if (req->rq_pack_bulk) {
2548                         LASSERT(grctx->src_reqbsd);
2549
2550                         bsd_off = bufcnt;
2551                         buflens[bufcnt] = gss_svc_bulk_payload(
2552                                                         grctx->src_ctx,
2553                                                         &req->rq_flvr,
2554                                                         req->rq_bulk_read);
2555                         if (svc == SPTLRPC_SVC_INTG)
2556                                 txtsize += buflens[bufcnt];
2557                         bufcnt++;
2558                 }
2559
2560                 if ((!early && gss_svc_reqctx_is_special(grctx)) ||
2561                      svc != SPTLRPC_SVC_NULL)
2562                         buflens[bufcnt++] = gss_svc_payload(grctx, early,
2563                                                             txtsize, 0);
2564         }
2565
2566         wmsg_size = lustre_msg_size_v2(bufcnt, buflens);
2567
2568         rs_size = sizeof(*rs) + wmsg_size;
2569         rs = req->rq_reply_state;
2570
2571         if (rs) {
2572                 /* pre-allocated */
2573                 LASSERT(rs->rs_size >= rs_size);
2574         } else {
2575                 OBD_ALLOC_LARGE(rs, rs_size);
2576                 if (rs == NULL)
2577                         RETURN(-ENOMEM);
2578
2579                 rs->rs_size = rs_size;
2580         }
2581
2582         rs->rs_repbuf = (struct lustre_msg *) (rs + 1);
2583         rs->rs_repbuf_len = wmsg_size;
2584
2585         /* initialize the buffer */
2586         if (privacy) {
2587                 lustre_init_msg_v2(rs->rs_repbuf, ibufcnt, ibuflens, NULL);
2588                 rs->rs_msg = lustre_msg_buf(rs->rs_repbuf, 0, msglen);
2589         } else {
2590                 lustre_init_msg_v2(rs->rs_repbuf, bufcnt, buflens, NULL);
2591                 rs->rs_repbuf->lm_secflvr = req->rq_flvr.sf_rpc;
2592
2593                 rs->rs_msg = lustre_msg_buf(rs->rs_repbuf, 1, 0);
2594         }
2595
2596         if (bsd_off) {
2597                 grctx->src_repbsd = lustre_msg_buf(rs->rs_repbuf, bsd_off, 0);
2598                 grctx->src_repbsd_size = lustre_msg_buflen(rs->rs_repbuf,
2599                                                            bsd_off);
2600         }
2601
2602         gss_svc_reqctx_addref(grctx);
2603         rs->rs_svc_ctx = req->rq_svc_ctx;
2604
2605         LASSERT(rs->rs_msg);
2606         req->rq_reply_state = rs;
2607         RETURN(0);
2608 }
2609
2610 static int gss_svc_seal(struct ptlrpc_request *req,
2611                         struct ptlrpc_reply_state *rs,
2612                         struct gss_svc_reqctx *grctx)
2613 {
2614         struct gss_svc_ctx      *gctx = grctx->src_ctx;
2615         rawobj_t                 hdrobj, msgobj, token;
2616         struct gss_header       *ghdr;
2617         __u8                    *token_buf;
2618         int                      token_buflen;
2619         __u32                    buflens[2], major;
2620         int                      msglen, rc;
2621         ENTRY;
2622
2623         /* get clear data length. note embedded lustre_msg might
2624          * have been shrunk
2625          */
2626         if (req->rq_replen != lustre_msg_buflen(rs->rs_repbuf, 0))
2627                 msglen = lustre_shrink_msg(rs->rs_repbuf, 0, req->rq_replen, 1);
2628         else
2629                 msglen = lustre_msg_size_v2(rs->rs_repbuf->lm_bufcount,
2630                                             rs->rs_repbuf->lm_buflens);
2631
2632         /* temporarily use tail of buffer to hold gss header data */
2633         LASSERT(msglen + PTLRPC_GSS_HEADER_SIZE <= rs->rs_repbuf_len);
2634         ghdr = (struct gss_header *) ((char *) rs->rs_repbuf +
2635                         rs->rs_repbuf_len - PTLRPC_GSS_HEADER_SIZE);
2636         ghdr->gh_version = PTLRPC_GSS_VERSION;
2637         ghdr->gh_sp = LUSTRE_SP_ANY;
2638         ghdr->gh_flags = 0;
2639         ghdr->gh_proc = PTLRPC_GSS_PROC_DATA;
2640         ghdr->gh_seq = grctx->src_wirectx.gw_seq;
2641         ghdr->gh_svc = SPTLRPC_SVC_PRIV;
2642         ghdr->gh_handle.len = 0;
2643         if (req->rq_pack_bulk)
2644                 ghdr->gh_flags |= LUSTRE_GSS_PACK_BULK;
2645
2646         /* allocate temporary cipher buffer */
2647         token_buflen = gss_mech_payload(gctx->gsc_mechctx, msglen, 1);
2648         OBD_ALLOC_LARGE(token_buf, token_buflen);
2649         if (token_buf == NULL)
2650                 RETURN(-ENOMEM);
2651
2652         hdrobj.len = PTLRPC_GSS_HEADER_SIZE;
2653         hdrobj.data = (__u8 *) ghdr;
2654         msgobj.len = msglen;
2655         msgobj.data = (__u8 *) rs->rs_repbuf;
2656         token.len = token_buflen;
2657         token.data = token_buf;
2658
2659         major = lgss_wrap(gctx->gsc_mechctx, &hdrobj, &msgobj,
2660                           rs->rs_repbuf_len - PTLRPC_GSS_HEADER_SIZE, &token);
2661         if (major != GSS_S_COMPLETE) {
2662                 CERROR("wrap message error: %08x\n", major);
2663                 GOTO(out_free, rc = -EPERM);
2664         }
2665         LASSERT(token.len <= token_buflen);
2666
2667         /* we are about to override data at rs->rs_repbuf, nullify pointers
2668          * to which to catch further illegal usage.
2669          */
2670         if (req->rq_pack_bulk) {
2671                 grctx->src_repbsd = NULL;
2672                 grctx->src_repbsd_size = 0;
2673         }
2674
2675         /* now fill the actual wire data
2676          * - gss header
2677          * - gss token
2678          */
2679         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
2680         buflens[1] = token.len;
2681
2682         rs->rs_repdata_len = lustre_msg_size_v2(2, buflens);
2683         LASSERT(rs->rs_repdata_len <= rs->rs_repbuf_len);
2684
2685         lustre_init_msg_v2(rs->rs_repbuf, 2, buflens, NULL);
2686         rs->rs_repbuf->lm_secflvr = req->rq_flvr.sf_rpc;
2687
2688         memcpy(lustre_msg_buf(rs->rs_repbuf, 0, 0), ghdr,
2689                PTLRPC_GSS_HEADER_SIZE);
2690         memcpy(lustre_msg_buf(rs->rs_repbuf, 1, 0), token.data, token.len);
2691
2692         /* reply offset */
2693         if (req->rq_packed_final &&
2694             (lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT))
2695                 req->rq_reply_off = gss_at_reply_off_priv;
2696         else
2697                 req->rq_reply_off = 0;
2698
2699         /* to catch upper layer's further access */
2700         rs->rs_msg = NULL;
2701         req->rq_repmsg = NULL;
2702         req->rq_replen = 0;
2703
2704         rc = 0;
2705 out_free:
2706         OBD_FREE_LARGE(token_buf, token_buflen);
2707         RETURN(rc);
2708 }
2709
2710 int gss_svc_authorize(struct ptlrpc_request *req)
2711 {
2712         struct ptlrpc_reply_state *rs = req->rq_reply_state;
2713         struct gss_svc_reqctx     *grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
2714         struct gss_wire_ctx       *gw = &grctx->src_wirectx;
2715         int                        early, rc;
2716         ENTRY;
2717
2718         early = (req->rq_packed_final == 0);
2719
2720         if (!early && gss_svc_reqctx_is_special(grctx)) {
2721                 LASSERT(rs->rs_repdata_len != 0);
2722
2723                 req->rq_reply_off = gss_at_reply_off_integ;
2724                 RETURN(0);
2725         }
2726
2727         /* early reply could happen in many cases */
2728         if (!early && gw->gw_proc != PTLRPC_GSS_PROC_DATA &&
2729             gw->gw_proc != PTLRPC_GSS_PROC_DESTROY) {
2730                 CERROR("proc %d not support\n", gw->gw_proc);
2731                 RETURN(-EINVAL);
2732         }
2733
2734         LASSERT(grctx->src_ctx);
2735
2736         switch (gw->gw_svc) {
2737         case SPTLRPC_SVC_NULL:
2738         case SPTLRPC_SVC_AUTH:
2739         case SPTLRPC_SVC_INTG:
2740                 rc = gss_svc_sign(req, rs, grctx, gw->gw_svc);
2741                 break;
2742         case SPTLRPC_SVC_PRIV:
2743                 rc = gss_svc_seal(req, rs, grctx);
2744                 break;
2745         default:
2746                 CERROR("Unknown service %d\n", gw->gw_svc);
2747                 GOTO(out, rc = -EINVAL);
2748         }
2749         rc = 0;
2750
2751 out:
2752         RETURN(rc);
2753 }
2754
2755 void gss_svc_free_rs(struct ptlrpc_reply_state *rs)
2756 {
2757         struct gss_svc_reqctx *grctx;
2758
2759         LASSERT(rs->rs_svc_ctx);
2760         grctx = container_of(rs->rs_svc_ctx, struct gss_svc_reqctx, src_base);
2761
2762         gss_svc_reqctx_decref(grctx);
2763         rs->rs_svc_ctx = NULL;
2764
2765         if (!rs->rs_prealloc)
2766                 OBD_FREE_LARGE(rs, rs->rs_size);
2767 }
2768
2769 void gss_svc_free_ctx(struct ptlrpc_svc_ctx *ctx)
2770 {
2771         LASSERT(atomic_read(&ctx->sc_refcount) == 0);
2772         gss_svc_reqctx_free(gss_svc_ctx2reqctx(ctx));
2773 }
2774
2775 int gss_copy_rvc_cli_ctx(struct ptlrpc_cli_ctx *cli_ctx,
2776                          struct ptlrpc_svc_ctx *svc_ctx)
2777 {
2778         struct gss_cli_ctx     *cli_gctx = ctx2gctx(cli_ctx);
2779         struct gss_svc_ctx     *svc_gctx = gss_svc_ctx2gssctx(svc_ctx);
2780         struct gss_ctx         *mechctx = NULL;
2781
2782         LASSERT(cli_gctx);
2783         LASSERT(svc_gctx && svc_gctx->gsc_mechctx);
2784
2785         cli_gctx->gc_proc = PTLRPC_GSS_PROC_DATA;
2786         cli_gctx->gc_win = GSS_SEQ_WIN;
2787
2788         /* The problem is the reverse ctx might get lost in some recovery
2789          * situations, and the same svc_ctx will be used to re-create it.
2790          * if there's callback be sentout before that, new reverse ctx start
2791          * with sequence 0 will lead to future callback rpc be treated as
2792          * replay.
2793          *
2794          * each reverse root ctx will record its latest sequence number on its
2795          * buddy svcctx before be destroyed, so here we continue use it.
2796          */
2797         atomic_set(&cli_gctx->gc_seq, svc_gctx->gsc_rvs_seq);
2798
2799         if (gss_svc_upcall_dup_handle(&cli_gctx->gc_svc_handle, svc_gctx)) {
2800                 CERROR("failed to dup svc handle\n");
2801                 goto err_out;
2802         }
2803
2804         if (lgss_copy_reverse_context(svc_gctx->gsc_mechctx, &mechctx) !=
2805             GSS_S_COMPLETE) {
2806                 CERROR("failed to copy mech context\n");
2807                 goto err_svc_handle;
2808         }
2809
2810         if (rawobj_dup(&cli_gctx->gc_handle, &svc_gctx->gsc_rvs_hdl)) {
2811                 CERROR("failed to dup reverse handle\n");
2812                 goto err_ctx;
2813         }
2814
2815         cli_gctx->gc_mechctx = mechctx;
2816         gss_cli_ctx_uptodate(cli_gctx);
2817
2818         return 0;
2819
2820 err_ctx:
2821         lgss_delete_sec_context(&mechctx);
2822 err_svc_handle:
2823         rawobj_free(&cli_gctx->gc_svc_handle);
2824 err_out:
2825         return -ENOMEM;
2826 }
2827
2828 static void gss_init_at_reply_offset(void)
2829 {
2830         __u32 buflens[3];
2831         int clearsize;
2832
2833         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
2834         buflens[1] = lustre_msg_early_size;
2835         buflens[2] = gss_cli_payload(NULL, buflens[1], 0);
2836         gss_at_reply_off_integ = lustre_msg_size_v2(3, buflens);
2837
2838         buflens[0] = lustre_msg_early_size;
2839         clearsize = lustre_msg_size_v2(1, buflens);
2840         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
2841         buflens[1] = gss_cli_payload(NULL, clearsize, 0);
2842         buflens[2] = gss_cli_payload(NULL, clearsize, 1);
2843         gss_at_reply_off_priv = lustre_msg_size_v2(3, buflens);
2844 }
2845
2846 static int __init sptlrpc_gss_init(void)
2847 {
2848         int rc;
2849
2850         rc = gss_init_tunables();
2851         if (rc)
2852                 return rc;
2853
2854         rc = gss_init_cli_upcall();
2855         if (rc)
2856                 goto out_tunables;
2857
2858         rc = gss_init_svc_upcall();
2859         if (rc)
2860                 goto out_cli_upcall;
2861
2862         rc = init_null_module();
2863         if (rc)
2864                 goto out_svc_upcall;
2865
2866         rc = init_kerberos_module();
2867         if (rc)
2868                 goto out_null;
2869
2870         rc = init_sk_module();
2871         if (rc)
2872                 goto out_kerberos;
2873
2874         /* register policy after all other stuff be initialized, because it
2875          * might be in used immediately after the registration.
2876          */
2877         rc = gss_init_keyring();
2878         if (rc)
2879                 goto out_sk;
2880
2881         gss_init_at_reply_offset();
2882
2883         return 0;
2884
2885 out_sk:
2886         cleanup_sk_module();
2887 out_kerberos:
2888         cleanup_kerberos_module();
2889 out_null:
2890         cleanup_null_module();
2891 out_svc_upcall:
2892         gss_exit_svc_upcall();
2893 out_cli_upcall:
2894         gss_exit_cli_upcall();
2895 out_tunables:
2896         gss_exit_tunables();
2897         return rc;
2898 }
2899
2900 static void __exit sptlrpc_gss_exit(void)
2901 {
2902         gss_exit_keyring();
2903         cleanup_kerberos_module();
2904         gss_exit_svc_upcall();
2905         gss_exit_cli_upcall();
2906         gss_exit_tunables();
2907 }
2908
2909 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
2910 MODULE_DESCRIPTION("Lustre GSS security policy");
2911 MODULE_VERSION(LUSTRE_VERSION_STRING);
2912 MODULE_LICENSE("GPL");
2913
2914 module_init(sptlrpc_gss_init);
2915 module_exit(sptlrpc_gss_exit);