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