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