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