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