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