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