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