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