Whamcloud - gitweb
555ab73251a73f76d4dec8696aae36a18d43341e
[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  2008 Sun Microsystems, Inc. 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
1615         req->rq_repmsg = NULL;
1616 }
1617
1618 static int get_enlarged_msgsize(struct lustre_msg *msg,
1619                                 int segment, int newsize)
1620 {
1621         int save, newmsg_size;
1622
1623         LASSERT(newsize >= msg->lm_buflens[segment]);
1624
1625         save = msg->lm_buflens[segment];
1626         msg->lm_buflens[segment] = newsize;
1627         newmsg_size = lustre_msg_size_v2(msg->lm_bufcount, msg->lm_buflens);
1628         msg->lm_buflens[segment] = save;
1629
1630         return newmsg_size;
1631 }
1632
1633 static int get_enlarged_msgsize2(struct lustre_msg *msg,
1634                                  int segment1, int newsize1,
1635                                  int segment2, int newsize2)
1636 {
1637         int save1, save2, newmsg_size;
1638
1639         LASSERT(newsize1 >= msg->lm_buflens[segment1]);
1640         LASSERT(newsize2 >= msg->lm_buflens[segment2]);
1641
1642         save1 = msg->lm_buflens[segment1];
1643         save2 = msg->lm_buflens[segment2];
1644         msg->lm_buflens[segment1] = newsize1;
1645         msg->lm_buflens[segment2] = newsize2;
1646         newmsg_size = lustre_msg_size_v2(msg->lm_bufcount, msg->lm_buflens);
1647         msg->lm_buflens[segment1] = save1;
1648         msg->lm_buflens[segment2] = save2;
1649
1650         return newmsg_size;
1651 }
1652
1653 static
1654 int gss_enlarge_reqbuf_intg(struct ptlrpc_sec *sec,
1655                             struct ptlrpc_request *req,
1656                             int svc,
1657                             int segment, int newsize)
1658 {
1659         struct lustre_msg      *newbuf;
1660         int                     txtsize, sigsize = 0, i;
1661         int                     newmsg_size, newbuf_size;
1662
1663         /*
1664          * gss header is at seg 0;
1665          * embedded msg is at seg 1;
1666          * signature (if any) is at the last seg
1667          */
1668         LASSERT(req->rq_reqbuf);
1669         LASSERT(req->rq_reqbuf_len > req->rq_reqlen);
1670         LASSERT(req->rq_reqbuf->lm_bufcount >= 2);
1671         LASSERT(lustre_msg_buf(req->rq_reqbuf, 1, 0) == req->rq_reqmsg);
1672
1673         /* 1. compute new embedded msg size */
1674         newmsg_size = get_enlarged_msgsize(req->rq_reqmsg, segment, newsize);
1675         LASSERT(newmsg_size >= req->rq_reqbuf->lm_buflens[1]);
1676
1677         /* 2. compute new wrapper msg size */
1678         if (svc == SPTLRPC_SVC_NULL) {
1679                 /* no signature, get size directly */
1680                 newbuf_size = get_enlarged_msgsize(req->rq_reqbuf,
1681                                                    1, newmsg_size);
1682         } else {
1683                 txtsize = req->rq_reqbuf->lm_buflens[0];
1684
1685                 if (svc == SPTLRPC_SVC_INTG) {
1686                         for (i = 1; i < req->rq_reqbuf->lm_bufcount; i++)
1687                                 txtsize += req->rq_reqbuf->lm_buflens[i];
1688                         txtsize += newmsg_size - req->rq_reqbuf->lm_buflens[1];
1689                 }
1690
1691                 sigsize = gss_cli_payload(req->rq_cli_ctx, txtsize, 0);
1692                 LASSERT(sigsize >= msg_last_seglen(req->rq_reqbuf));
1693
1694                 newbuf_size = get_enlarged_msgsize2(
1695                                         req->rq_reqbuf,
1696                                         1, newmsg_size,
1697                                         msg_last_segidx(req->rq_reqbuf),
1698                                         sigsize);
1699         }
1700
1701         /* request from pool should always have enough buffer */
1702         LASSERT(!req->rq_pool || req->rq_reqbuf_len >= newbuf_size);
1703
1704         if (req->rq_reqbuf_len < newbuf_size) {
1705                 newbuf_size = size_roundup_power2(newbuf_size);
1706
1707                 OBD_ALLOC(newbuf, newbuf_size);
1708                 if (newbuf == NULL)
1709                         RETURN(-ENOMEM);
1710
1711                 memcpy(newbuf, req->rq_reqbuf, req->rq_reqbuf_len);
1712
1713                 OBD_FREE(req->rq_reqbuf, req->rq_reqbuf_len);
1714                 req->rq_reqbuf = newbuf;
1715                 req->rq_reqbuf_len = newbuf_size;
1716                 req->rq_reqmsg = lustre_msg_buf(req->rq_reqbuf, 1, 0);
1717         }
1718
1719         /* do enlargement, from wrapper to embedded, from end to begin */
1720         if (svc != SPTLRPC_SVC_NULL)
1721                 _sptlrpc_enlarge_msg_inplace(req->rq_reqbuf,
1722                                              msg_last_segidx(req->rq_reqbuf),
1723                                              sigsize);
1724
1725         _sptlrpc_enlarge_msg_inplace(req->rq_reqbuf, 1, newmsg_size);
1726         _sptlrpc_enlarge_msg_inplace(req->rq_reqmsg, segment, newsize);
1727
1728         req->rq_reqlen = newmsg_size;
1729         RETURN(0);
1730 }
1731
1732 static
1733 int gss_enlarge_reqbuf_priv(struct ptlrpc_sec *sec,
1734                             struct ptlrpc_request *req,
1735                             int segment, int newsize)
1736 {
1737         struct lustre_msg      *newclrbuf;
1738         int                     newmsg_size, newclrbuf_size, newcipbuf_size;
1739         __u32                   buflens[3];
1740
1741         /*
1742          * embedded msg is at seg 0 of clear buffer;
1743          * cipher text is at seg 2 of cipher buffer;
1744          */
1745         LASSERT(req->rq_pool ||
1746                 (req->rq_reqbuf == NULL && req->rq_reqbuf_len == 0));
1747         LASSERT(req->rq_reqbuf == NULL ||
1748                 (req->rq_pool && req->rq_reqbuf->lm_bufcount == 3));
1749         LASSERT(req->rq_clrbuf);
1750         LASSERT(req->rq_clrbuf_len > req->rq_reqlen);
1751         LASSERT(lustre_msg_buf(req->rq_clrbuf, 0, 0) == req->rq_reqmsg);
1752
1753         /* compute new embedded msg size */
1754         newmsg_size = get_enlarged_msgsize(req->rq_reqmsg, segment, newsize);
1755
1756         /* compute new clear buffer size */
1757         newclrbuf_size = get_enlarged_msgsize(req->rq_clrbuf, 0, newmsg_size);
1758         newclrbuf_size += GSS_MAX_CIPHER_BLOCK;
1759
1760         /* compute new cipher buffer size */
1761         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
1762         buflens[1] = gss_cli_payload(req->rq_cli_ctx, buflens[0], 0);
1763         buflens[2] = gss_cli_payload(req->rq_cli_ctx, newclrbuf_size, 1);
1764         newcipbuf_size = lustre_msg_size_v2(3, buflens);
1765
1766         /* handle the case that we put both clear buf and cipher buf into
1767          * pre-allocated single buffer. */
1768         if (unlikely(req->rq_pool) &&
1769             req->rq_clrbuf >= req->rq_reqbuf &&
1770             (char *) req->rq_clrbuf <
1771             (char *) req->rq_reqbuf + req->rq_reqbuf_len) {
1772                 /* it couldn't be better we still fit into the
1773                  * pre-allocated buffer. */
1774                 if (newclrbuf_size + newcipbuf_size <= req->rq_reqbuf_len) {
1775                         void *src, *dst;
1776
1777                         /* move clear text backward. */
1778                         src = req->rq_clrbuf;
1779                         dst = (char *) req->rq_reqbuf + newcipbuf_size;
1780
1781                         memmove(dst, src, req->rq_clrbuf_len);
1782
1783                         req->rq_clrbuf = (struct lustre_msg *) dst;
1784                         req->rq_clrbuf_len = newclrbuf_size;
1785                         req->rq_reqmsg = lustre_msg_buf(req->rq_clrbuf, 0, 0);
1786                 } else {
1787                         /* sadly we have to split out the clear buffer */
1788                         LASSERT(req->rq_reqbuf_len >= newcipbuf_size);
1789                         LASSERT(req->rq_clrbuf_len < newclrbuf_size);
1790                 }
1791         }
1792
1793         if (req->rq_clrbuf_len < newclrbuf_size) {
1794                 newclrbuf_size = size_roundup_power2(newclrbuf_size);
1795
1796                 OBD_ALLOC(newclrbuf, newclrbuf_size);
1797                 if (newclrbuf == NULL)
1798                         RETURN(-ENOMEM);
1799
1800                 memcpy(newclrbuf, req->rq_clrbuf, req->rq_clrbuf_len);
1801
1802                 if (req->rq_reqbuf == NULL ||
1803                     req->rq_clrbuf < req->rq_reqbuf ||
1804                     (char *) req->rq_clrbuf >=
1805                     (char *) req->rq_reqbuf + req->rq_reqbuf_len) {
1806                         OBD_FREE(req->rq_clrbuf, req->rq_clrbuf_len);
1807                 }
1808
1809                 req->rq_clrbuf = newclrbuf;
1810                 req->rq_clrbuf_len = newclrbuf_size;
1811                 req->rq_reqmsg = lustre_msg_buf(req->rq_clrbuf, 0, 0);
1812         }
1813
1814         _sptlrpc_enlarge_msg_inplace(req->rq_clrbuf, 0, newmsg_size);
1815         _sptlrpc_enlarge_msg_inplace(req->rq_reqmsg, segment, newsize);
1816         req->rq_reqlen = newmsg_size;
1817
1818         RETURN(0);
1819 }
1820
1821 int gss_enlarge_reqbuf(struct ptlrpc_sec *sec,
1822                        struct ptlrpc_request *req,
1823                        int segment, int newsize)
1824 {
1825         int     svc = SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc);
1826
1827         LASSERT(!req->rq_ctx_init && !req->rq_ctx_fini);
1828
1829         switch (svc) {
1830         case SPTLRPC_SVC_NULL:
1831         case SPTLRPC_SVC_AUTH:
1832         case SPTLRPC_SVC_INTG:
1833                 return gss_enlarge_reqbuf_intg(sec, req, svc, segment, newsize);
1834         case SPTLRPC_SVC_PRIV:
1835                 return gss_enlarge_reqbuf_priv(sec, req, segment, newsize);
1836         default:
1837                 LASSERTF(0, "bad rpc flavor %x\n", req->rq_flvr.sf_rpc);
1838                 return 0;
1839         }
1840 }
1841
1842 int gss_sec_install_rctx(struct obd_import *imp,
1843                          struct ptlrpc_sec *sec,
1844                          struct ptlrpc_cli_ctx *ctx)
1845 {
1846         struct gss_sec     *gsec;
1847         struct gss_cli_ctx *gctx;
1848         int                 rc;
1849
1850         gsec = container_of(sec, struct gss_sec, gs_base);
1851         gctx = container_of(ctx, struct gss_cli_ctx, gc_base);
1852
1853         rc = gss_install_rvs_svc_ctx(imp, gsec, gctx);
1854         return rc;
1855 }
1856
1857 /********************************************
1858  * server side API                          *
1859  ********************************************/
1860
1861 static inline
1862 int gss_svc_reqctx_is_special(struct gss_svc_reqctx *grctx)
1863 {
1864         LASSERT(grctx);
1865         return (grctx->src_init || grctx->src_init_continue ||
1866                 grctx->src_err_notify);
1867 }
1868
1869 static
1870 void gss_svc_reqctx_free(struct gss_svc_reqctx *grctx)
1871 {
1872         if (grctx->src_ctx)
1873                 gss_svc_upcall_put_ctx(grctx->src_ctx);
1874
1875         sptlrpc_policy_put(grctx->src_base.sc_policy);
1876         OBD_FREE_PTR(grctx);
1877 }
1878
1879 static inline
1880 void gss_svc_reqctx_addref(struct gss_svc_reqctx *grctx)
1881 {
1882         LASSERT(cfs_atomic_read(&grctx->src_base.sc_refcount) > 0);
1883         cfs_atomic_inc(&grctx->src_base.sc_refcount);
1884 }
1885
1886 static inline
1887 void gss_svc_reqctx_decref(struct gss_svc_reqctx *grctx)
1888 {
1889         LASSERT(cfs_atomic_read(&grctx->src_base.sc_refcount) > 0);
1890
1891         if (cfs_atomic_dec_and_test(&grctx->src_base.sc_refcount))
1892                 gss_svc_reqctx_free(grctx);
1893 }
1894
1895 static
1896 int gss_svc_sign(struct ptlrpc_request *req,
1897                  struct ptlrpc_reply_state *rs,
1898                  struct gss_svc_reqctx *grctx,
1899                  __u32 svc)
1900 {
1901         __u32   flags = 0;
1902         int     rc;
1903         ENTRY;
1904
1905         LASSERT(rs->rs_msg == lustre_msg_buf(rs->rs_repbuf, 1, 0));
1906
1907         /* embedded lustre_msg might have been shrinked */
1908         if (req->rq_replen != rs->rs_repbuf->lm_buflens[1])
1909                 lustre_shrink_msg(rs->rs_repbuf, 1, req->rq_replen, 1);
1910
1911         if (req->rq_pack_bulk)
1912                 flags |= LUSTRE_GSS_PACK_BULK;
1913
1914         rc = gss_sign_msg(rs->rs_repbuf, grctx->src_ctx->gsc_mechctx,
1915                           LUSTRE_SP_ANY, flags, PTLRPC_GSS_PROC_DATA,
1916                           grctx->src_wirectx.gw_seq, svc, NULL);
1917         if (rc < 0)
1918                 RETURN(rc);
1919
1920         rs->rs_repdata_len = rc;
1921
1922         if (likely(req->rq_packed_final)) {
1923                 if (lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT)
1924                         req->rq_reply_off = gss_at_reply_off_integ;
1925                 else
1926                         req->rq_reply_off = 0;
1927         } else {
1928                 if (svc == SPTLRPC_SVC_NULL)
1929                         rs->rs_repbuf->lm_cksum = crc32_le(!(__u32) 0,
1930                                         lustre_msg_buf(rs->rs_repbuf, 1, 0),
1931                                         lustre_msg_buflen(rs->rs_repbuf, 1));
1932                 req->rq_reply_off = 0;
1933         }
1934
1935         RETURN(0);
1936 }
1937
1938 int gss_pack_err_notify(struct ptlrpc_request *req, __u32 major, __u32 minor)
1939 {
1940         struct gss_svc_reqctx     *grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
1941         struct ptlrpc_reply_state *rs;
1942         struct gss_err_header     *ghdr;
1943         int                        replen = sizeof(struct ptlrpc_body);
1944         int                        rc;
1945         ENTRY;
1946
1947         //if (OBD_FAIL_CHECK_ORSET(OBD_FAIL_SVCGSS_ERR_NOTIFY, OBD_FAIL_ONCE))
1948         //      RETURN(-EINVAL);
1949
1950         grctx->src_err_notify = 1;
1951         grctx->src_reserve_len = 0;
1952
1953         rc = lustre_pack_reply_v2(req, 1, &replen, NULL, 0);
1954         if (rc) {
1955                 CERROR("could not pack reply, err %d\n", rc);
1956                 RETURN(rc);
1957         }
1958
1959         /* gss hdr */
1960         rs = req->rq_reply_state;
1961         LASSERT(rs->rs_repbuf->lm_buflens[1] >= sizeof(*ghdr));
1962         ghdr = lustre_msg_buf(rs->rs_repbuf, 0, 0);
1963         ghdr->gh_version = PTLRPC_GSS_VERSION;
1964         ghdr->gh_flags = 0;
1965         ghdr->gh_proc = PTLRPC_GSS_PROC_ERR;
1966         ghdr->gh_major = major;
1967         ghdr->gh_minor = minor;
1968         ghdr->gh_handle.len = 0; /* fake context handle */
1969
1970         rs->rs_repdata_len = lustre_msg_size_v2(rs->rs_repbuf->lm_bufcount,
1971                                                 rs->rs_repbuf->lm_buflens);
1972
1973         CDEBUG(D_SEC, "prepare gss error notify(0x%x/0x%x) to %s\n",
1974                major, minor, libcfs_nid2str(req->rq_peer.nid));
1975         RETURN(0);
1976 }
1977
1978 static
1979 int gss_svc_handle_init(struct ptlrpc_request *req,
1980                         struct gss_wire_ctx *gw)
1981 {
1982         struct gss_svc_reqctx     *grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
1983         struct lustre_msg         *reqbuf = req->rq_reqbuf;
1984         struct obd_uuid           *uuid;
1985         struct obd_device         *target;
1986         rawobj_t                   uuid_obj, rvs_hdl, in_token;
1987         __u32                      lustre_svc;
1988         __u32                     *secdata, seclen;
1989         int                        swabbed, rc;
1990         ENTRY;
1991
1992         CDEBUG(D_SEC, "processing gss init(%d) request from %s\n", gw->gw_proc,
1993                libcfs_nid2str(req->rq_peer.nid));
1994
1995         req->rq_ctx_init = 1;
1996
1997         if (gw->gw_flags & LUSTRE_GSS_PACK_BULK) {
1998                 CERROR("unexpected bulk flag\n");
1999                 RETURN(SECSVC_DROP);
2000         }
2001
2002         if (gw->gw_proc == PTLRPC_GSS_PROC_INIT && gw->gw_handle.len != 0) {
2003                 CERROR("proc %u: invalid handle length %u\n",
2004                        gw->gw_proc, gw->gw_handle.len);
2005                 RETURN(SECSVC_DROP);
2006         }
2007
2008         if (reqbuf->lm_bufcount < 3 || reqbuf->lm_bufcount > 4){
2009                 CERROR("Invalid bufcount %d\n", reqbuf->lm_bufcount);
2010                 RETURN(SECSVC_DROP);
2011         }
2012
2013         swabbed = ptlrpc_req_need_swab(req);
2014
2015         /* ctx initiate payload is in last segment */
2016         secdata = lustre_msg_buf(reqbuf, reqbuf->lm_bufcount - 1, 0);
2017         seclen = reqbuf->lm_buflens[reqbuf->lm_bufcount - 1];
2018
2019         if (seclen < 4 + 4) {
2020                 CERROR("sec size %d too small\n", seclen);
2021                 RETURN(SECSVC_DROP);
2022         }
2023
2024         /* lustre svc type */
2025         lustre_svc = le32_to_cpu(*secdata++);
2026         seclen -= 4;
2027
2028         /* extract target uuid, note this code is somewhat fragile
2029          * because touched internal structure of obd_uuid */
2030         if (rawobj_extract(&uuid_obj, &secdata, &seclen)) {
2031                 CERROR("failed to extract target uuid\n");
2032                 RETURN(SECSVC_DROP);
2033         }
2034         uuid_obj.data[uuid_obj.len - 1] = '\0';
2035
2036         uuid = (struct obd_uuid *) uuid_obj.data;
2037         target = class_uuid2obd(uuid);
2038         if (!target || target->obd_stopping || !target->obd_set_up) {
2039                 CERROR("target '%s' is not available for context init (%s)\n",
2040                        uuid->uuid, target == NULL ? "no target" :
2041                        (target->obd_stopping ? "stopping" : "not set up"));
2042                 RETURN(SECSVC_DROP);
2043         }
2044
2045         /* extract reverse handle */
2046         if (rawobj_extract(&rvs_hdl, &secdata, &seclen)) {
2047                 CERROR("failed extract reverse handle\n");
2048                 RETURN(SECSVC_DROP);
2049         }
2050
2051         /* extract token */
2052         if (rawobj_extract(&in_token, &secdata, &seclen)) {
2053                 CERROR("can't extract token\n");
2054                 RETURN(SECSVC_DROP);
2055         }
2056
2057         rc = gss_svc_upcall_handle_init(req, grctx, gw, target, lustre_svc,
2058                                         &rvs_hdl, &in_token);
2059         if (rc != SECSVC_OK)
2060                 RETURN(rc);
2061
2062         if (grctx->src_ctx->gsc_usr_mds || grctx->src_ctx->gsc_usr_root)
2063                 CWARN("create svc ctx %p: user from %s authenticated as %s\n",
2064                       grctx->src_ctx, libcfs_nid2str(req->rq_peer.nid),
2065                       grctx->src_ctx->gsc_usr_mds ? "mds" : "root");
2066         else
2067                 CWARN("create svc ctx %p: accept user %u from %s\n",
2068                       grctx->src_ctx, grctx->src_ctx->gsc_uid,
2069                       libcfs_nid2str(req->rq_peer.nid));
2070
2071         if (gw->gw_flags & LUSTRE_GSS_PACK_USER) {
2072                 if (reqbuf->lm_bufcount < 4) {
2073                         CERROR("missing user descriptor\n");
2074                         RETURN(SECSVC_DROP);
2075                 }
2076                 if (sptlrpc_unpack_user_desc(reqbuf, 2, swabbed)) {
2077                         CERROR("Mal-formed user descriptor\n");
2078                         RETURN(SECSVC_DROP);
2079                 }
2080
2081                 req->rq_pack_udesc = 1;
2082                 req->rq_user_desc = lustre_msg_buf(reqbuf, 2, 0);
2083         }
2084
2085         req->rq_reqmsg = lustre_msg_buf(reqbuf, 1, 0);
2086         req->rq_reqlen = lustre_msg_buflen(reqbuf, 1);
2087
2088         RETURN(rc);
2089 }
2090
2091 /*
2092  * last segment must be the gss signature.
2093  */
2094 static
2095 int gss_svc_verify_request(struct ptlrpc_request *req,
2096                            struct gss_svc_reqctx *grctx,
2097                            struct gss_wire_ctx *gw,
2098                            __u32 *major)
2099 {
2100         struct gss_svc_ctx *gctx = grctx->src_ctx;
2101         struct lustre_msg  *msg = req->rq_reqbuf;
2102         int                 offset = 2;
2103         int                 swabbed;
2104         ENTRY;
2105
2106         *major = GSS_S_COMPLETE;
2107
2108         if (msg->lm_bufcount < 2) {
2109                 CERROR("Too few segments (%u) in request\n", msg->lm_bufcount);
2110                 RETURN(-EINVAL);
2111         }
2112
2113         if (gw->gw_svc == SPTLRPC_SVC_NULL)
2114                 goto verified;
2115
2116         if (gss_check_seq_num(&gctx->gsc_seqdata, gw->gw_seq, 0)) {
2117                 CERROR("phase 0: discard replayed req: seq %u\n", gw->gw_seq);
2118                 *major = GSS_S_DUPLICATE_TOKEN;
2119                 RETURN(-EACCES);
2120         }
2121
2122         *major = gss_verify_msg(msg, gctx->gsc_mechctx, gw->gw_svc);
2123         if (*major != GSS_S_COMPLETE) {
2124                 CERROR("failed to verify request: %x\n", *major);
2125                 RETURN(-EACCES);
2126         }
2127
2128         if (gctx->gsc_reverse == 0 &&
2129             gss_check_seq_num(&gctx->gsc_seqdata, gw->gw_seq, 1)) {
2130                 CERROR("phase 1+: discard replayed req: seq %u\n", gw->gw_seq);
2131                 *major = GSS_S_DUPLICATE_TOKEN;
2132                 RETURN(-EACCES);
2133         }
2134
2135 verified:
2136         swabbed = ptlrpc_req_need_swab(req);
2137
2138         /* user descriptor */
2139         if (gw->gw_flags & LUSTRE_GSS_PACK_USER) {
2140                 if (msg->lm_bufcount < (offset + 1)) {
2141                         CERROR("no user desc included\n");
2142                         RETURN(-EINVAL);
2143                 }
2144
2145                 if (sptlrpc_unpack_user_desc(msg, offset, swabbed)) {
2146                         CERROR("Mal-formed user descriptor\n");
2147                         RETURN(-EINVAL);
2148                 }
2149
2150                 req->rq_pack_udesc = 1;
2151                 req->rq_user_desc = lustre_msg_buf(msg, offset, 0);
2152                 offset++;
2153         }
2154
2155         /* check bulk_sec_desc data */
2156         if (gw->gw_flags & LUSTRE_GSS_PACK_BULK) {
2157                 if (msg->lm_bufcount < (offset + 1)) {
2158                         CERROR("missing bulk sec descriptor\n");
2159                         RETURN(-EINVAL);
2160                 }
2161
2162                 if (bulk_sec_desc_unpack(msg, offset, swabbed))
2163                         RETURN(-EINVAL);
2164
2165                 req->rq_pack_bulk = 1;
2166                 grctx->src_reqbsd = lustre_msg_buf(msg, offset, 0);
2167                 grctx->src_reqbsd_size = lustre_msg_buflen(msg, offset);
2168         }
2169
2170         req->rq_reqmsg = lustre_msg_buf(msg, 1, 0);
2171         req->rq_reqlen = msg->lm_buflens[1];
2172         RETURN(0);
2173 }
2174
2175 static
2176 int gss_svc_unseal_request(struct ptlrpc_request *req,
2177                            struct gss_svc_reqctx *grctx,
2178                            struct gss_wire_ctx *gw,
2179                            __u32 *major)
2180 {
2181         struct gss_svc_ctx *gctx = grctx->src_ctx;
2182         struct lustre_msg  *msg = req->rq_reqbuf;
2183         int                 swabbed, msglen, offset = 1;
2184         ENTRY;
2185
2186         if (gss_check_seq_num(&gctx->gsc_seqdata, gw->gw_seq, 0)) {
2187                 CERROR("phase 0: discard replayed req: seq %u\n", gw->gw_seq);
2188                 *major = GSS_S_DUPLICATE_TOKEN;
2189                 RETURN(-EACCES);
2190         }
2191
2192         *major = gss_unseal_msg(gctx->gsc_mechctx, msg,
2193                                &msglen, req->rq_reqdata_len);
2194         if (*major != GSS_S_COMPLETE) {
2195                 CERROR("failed to unwrap request: %x\n", *major);
2196                 RETURN(-EACCES);
2197         }
2198
2199         if (gss_check_seq_num(&gctx->gsc_seqdata, gw->gw_seq, 1)) {
2200                 CERROR("phase 1+: discard replayed req: seq %u\n", gw->gw_seq);
2201                 *major = GSS_S_DUPLICATE_TOKEN;
2202                 RETURN(-EACCES);
2203         }
2204
2205         swabbed = __lustre_unpack_msg(msg, msglen);
2206         if (swabbed < 0) {
2207                 CERROR("Failed to unpack after decryption\n");
2208                 RETURN(-EINVAL);
2209         }
2210         req->rq_reqdata_len = msglen;
2211
2212         if (msg->lm_bufcount < 1) {
2213                 CERROR("Invalid buffer: is empty\n");
2214                 RETURN(-EINVAL);
2215         }
2216
2217         if (gw->gw_flags & LUSTRE_GSS_PACK_USER) {
2218                 if (msg->lm_bufcount < offset + 1) {
2219                         CERROR("no user descriptor included\n");
2220                         RETURN(-EINVAL);
2221                 }
2222
2223                 if (sptlrpc_unpack_user_desc(msg, offset, swabbed)) {
2224                         CERROR("Mal-formed user descriptor\n");
2225                         RETURN(-EINVAL);
2226                 }
2227
2228                 req->rq_pack_udesc = 1;
2229                 req->rq_user_desc = lustre_msg_buf(msg, offset, 0);
2230                 offset++;
2231         }
2232
2233         if (gw->gw_flags & LUSTRE_GSS_PACK_BULK) {
2234                 if (msg->lm_bufcount < offset + 1) {
2235                         CERROR("no bulk checksum included\n");
2236                         RETURN(-EINVAL);
2237                 }
2238
2239                 if (bulk_sec_desc_unpack(msg, offset, swabbed))
2240                         RETURN(-EINVAL);
2241
2242                 req->rq_pack_bulk = 1;
2243                 grctx->src_reqbsd = lustre_msg_buf(msg, offset, 0);
2244                 grctx->src_reqbsd_size = lustre_msg_buflen(msg, offset);
2245         }
2246
2247         req->rq_reqmsg = lustre_msg_buf(req->rq_reqbuf, 0, 0);
2248         req->rq_reqlen = req->rq_reqbuf->lm_buflens[0];
2249         RETURN(0);
2250 }
2251
2252 static
2253 int gss_svc_handle_data(struct ptlrpc_request *req,
2254                         struct gss_wire_ctx *gw)
2255 {
2256         struct gss_svc_reqctx *grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
2257         __u32                  major = 0;
2258         int                    rc = 0;
2259         ENTRY;
2260
2261         grctx->src_ctx = gss_svc_upcall_get_ctx(req, gw);
2262         if (!grctx->src_ctx) {
2263                 major = GSS_S_NO_CONTEXT;
2264                 goto error;
2265         }
2266
2267         switch (gw->gw_svc) {
2268         case SPTLRPC_SVC_NULL:
2269         case SPTLRPC_SVC_AUTH:
2270         case SPTLRPC_SVC_INTG:
2271                 rc = gss_svc_verify_request(req, grctx, gw, &major);
2272                 break;
2273         case SPTLRPC_SVC_PRIV:
2274                 rc = gss_svc_unseal_request(req, grctx, gw, &major);
2275                 break;
2276         default:
2277                 CERROR("unsupported gss service %d\n", gw->gw_svc);
2278                 rc = -EINVAL;
2279         }
2280
2281         if (rc == 0)
2282                 RETURN(SECSVC_OK);
2283
2284         CERROR("svc %u failed: major 0x%08x: req xid "LPU64" ctx %p idx "
2285                LPX64"(%u->%s)\n", gw->gw_svc, major, req->rq_xid,
2286                grctx->src_ctx, gss_handle_to_u64(&gw->gw_handle),
2287                grctx->src_ctx->gsc_uid, libcfs_nid2str(req->rq_peer.nid));
2288 error:
2289         /* we only notify client in case of NO_CONTEXT/BAD_SIG, which
2290          * might happen after server reboot, to allow recovery. */
2291         if ((major == GSS_S_NO_CONTEXT || major == GSS_S_BAD_SIG) &&
2292             gss_pack_err_notify(req, major, 0) == 0)
2293                 RETURN(SECSVC_COMPLETE);
2294
2295         RETURN(SECSVC_DROP);
2296 }
2297
2298 static
2299 int gss_svc_handle_destroy(struct ptlrpc_request *req,
2300                            struct gss_wire_ctx *gw)
2301 {
2302         struct gss_svc_reqctx  *grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
2303         __u32                   major;
2304         ENTRY;
2305
2306         req->rq_ctx_fini = 1;
2307         req->rq_no_reply = 1;
2308
2309         grctx->src_ctx = gss_svc_upcall_get_ctx(req, gw);
2310         if (!grctx->src_ctx) {
2311                 CDEBUG(D_SEC, "invalid gss context handle for destroy.\n");
2312                 RETURN(SECSVC_DROP);
2313         }
2314
2315         if (gw->gw_svc != SPTLRPC_SVC_INTG) {
2316                 CERROR("svc %u is not supported in destroy.\n", gw->gw_svc);
2317                 RETURN(SECSVC_DROP);
2318         }
2319
2320         if (gss_svc_verify_request(req, grctx, gw, &major))
2321                 RETURN(SECSVC_DROP);
2322
2323         CWARN("destroy svc ctx %p idx "LPX64" (%u->%s)\n",
2324               grctx->src_ctx, gss_handle_to_u64(&gw->gw_handle),
2325               grctx->src_ctx->gsc_uid, libcfs_nid2str(req->rq_peer.nid));
2326
2327         gss_svc_upcall_destroy_ctx(grctx->src_ctx);
2328
2329         if (gw->gw_flags & LUSTRE_GSS_PACK_USER) {
2330                 if (req->rq_reqbuf->lm_bufcount < 4) {
2331                         CERROR("missing user descriptor, ignore it\n");
2332                         RETURN(SECSVC_OK);
2333                 }
2334                 if (sptlrpc_unpack_user_desc(req->rq_reqbuf, 2,
2335                                              ptlrpc_req_need_swab(req))) {
2336                         CERROR("Mal-formed user descriptor, ignore it\n");
2337                         RETURN(SECSVC_OK);
2338                 }
2339
2340                 req->rq_pack_udesc = 1;
2341                 req->rq_user_desc = lustre_msg_buf(req->rq_reqbuf, 2, 0);
2342         }
2343
2344         RETURN(SECSVC_OK);
2345 }
2346
2347 int gss_svc_accept(struct ptlrpc_sec_policy *policy, struct ptlrpc_request *req)
2348 {
2349         struct gss_header      *ghdr;
2350         struct gss_svc_reqctx  *grctx;
2351         struct gss_wire_ctx    *gw;
2352         int                     swabbed, rc;
2353         ENTRY;
2354
2355         LASSERT(req->rq_reqbuf);
2356         LASSERT(req->rq_svc_ctx == NULL);
2357
2358         if (req->rq_reqbuf->lm_bufcount < 2) {
2359                 CERROR("buf count only %d\n", req->rq_reqbuf->lm_bufcount);
2360                 RETURN(SECSVC_DROP);
2361         }
2362
2363         swabbed = ptlrpc_req_need_swab(req);
2364
2365         ghdr = gss_swab_header(req->rq_reqbuf, 0, swabbed);
2366         if (ghdr == NULL) {
2367                 CERROR("can't decode gss header\n");
2368                 RETURN(SECSVC_DROP);
2369         }
2370
2371         /* sanity checks */
2372         if (ghdr->gh_version != PTLRPC_GSS_VERSION) {
2373                 CERROR("gss version %u, expect %u\n", ghdr->gh_version,
2374                        PTLRPC_GSS_VERSION);
2375                 RETURN(SECSVC_DROP);
2376         }
2377
2378         req->rq_sp_from = ghdr->gh_sp;
2379
2380         /* alloc grctx data */
2381         OBD_ALLOC_PTR(grctx);
2382         if (!grctx)
2383                 RETURN(SECSVC_DROP);
2384
2385         grctx->src_base.sc_policy = sptlrpc_policy_get(policy);
2386         cfs_atomic_set(&grctx->src_base.sc_refcount, 1);
2387         req->rq_svc_ctx = &grctx->src_base;
2388         gw = &grctx->src_wirectx;
2389
2390         /* save wire context */
2391         gw->gw_flags = ghdr->gh_flags;
2392         gw->gw_proc = ghdr->gh_proc;
2393         gw->gw_seq = ghdr->gh_seq;
2394         gw->gw_svc = ghdr->gh_svc;
2395         rawobj_from_netobj(&gw->gw_handle, &ghdr->gh_handle);
2396
2397         /* keep original wire header which subject to checksum verification */
2398         if (swabbed)
2399                 gss_header_swabber(ghdr);
2400
2401         switch(ghdr->gh_proc) {
2402         case PTLRPC_GSS_PROC_INIT:
2403         case PTLRPC_GSS_PROC_CONTINUE_INIT:
2404                 rc = gss_svc_handle_init(req, gw);
2405                 break;
2406         case PTLRPC_GSS_PROC_DATA:
2407                 rc = gss_svc_handle_data(req, gw);
2408                 break;
2409         case PTLRPC_GSS_PROC_DESTROY:
2410                 rc = gss_svc_handle_destroy(req, gw);
2411                 break;
2412         default:
2413                 CERROR("unknown proc %u\n", gw->gw_proc);
2414                 rc = SECSVC_DROP;
2415                 break;
2416         }
2417
2418         switch (rc) {
2419         case SECSVC_OK:
2420                 LASSERT (grctx->src_ctx);
2421
2422                 req->rq_auth_gss = 1;
2423                 req->rq_auth_remote = grctx->src_ctx->gsc_remote;
2424                 req->rq_auth_usr_mdt = grctx->src_ctx->gsc_usr_mds;
2425                 req->rq_auth_usr_root = grctx->src_ctx->gsc_usr_root;
2426                 req->rq_auth_uid = grctx->src_ctx->gsc_uid;
2427                 req->rq_auth_mapped_uid = grctx->src_ctx->gsc_mapped_uid;
2428                 break;
2429         case SECSVC_COMPLETE:
2430                 break;
2431         case SECSVC_DROP:
2432                 gss_svc_reqctx_free(grctx);
2433                 req->rq_svc_ctx = NULL;
2434                 break;
2435         }
2436
2437         RETURN(rc);
2438 }
2439
2440 void gss_svc_invalidate_ctx(struct ptlrpc_svc_ctx *svc_ctx)
2441 {
2442         struct gss_svc_reqctx  *grctx;
2443         ENTRY;
2444
2445         if (svc_ctx == NULL) {
2446                 EXIT;
2447                 return;
2448         }
2449
2450         grctx = gss_svc_ctx2reqctx(svc_ctx);
2451
2452         CWARN("gss svc invalidate ctx %p(%u)\n",
2453               grctx->src_ctx, grctx->src_ctx->gsc_uid);
2454         gss_svc_upcall_destroy_ctx(grctx->src_ctx);
2455
2456         EXIT;
2457 }
2458
2459 static inline
2460 int gss_svc_payload(struct gss_svc_reqctx *grctx, int early,
2461                     int msgsize, int privacy)
2462 {
2463         /* we should treat early reply normally, but which is actually sharing
2464          * the same ctx with original request, so in this case we should
2465          * ignore the special ctx's special flags */
2466         if (early == 0 && gss_svc_reqctx_is_special(grctx))
2467                 return grctx->src_reserve_len;
2468
2469         return gss_mech_payload(NULL, msgsize, privacy);
2470 }
2471
2472 static int gss_svc_bulk_payload(struct gss_svc_ctx *gctx,
2473                                 struct sptlrpc_flavor *flvr,
2474                                 int read)
2475 {
2476         int     payload = sizeof(struct ptlrpc_bulk_sec_desc);
2477
2478         if (read) {
2479                 switch (SPTLRPC_FLVR_BULK_SVC(flvr->sf_rpc)) {
2480                 case SPTLRPC_BULK_SVC_NULL:
2481                         break;
2482                 case SPTLRPC_BULK_SVC_INTG:
2483                         payload += gss_mech_payload(NULL, 0, 0);
2484                         break;
2485                 case SPTLRPC_BULK_SVC_PRIV:
2486                         payload += gss_mech_payload(NULL, 0, 1);
2487                         break;
2488                 case SPTLRPC_BULK_SVC_AUTH:
2489                 default:
2490                         LBUG();
2491                 }
2492         }
2493
2494         return payload;
2495 }
2496
2497 int gss_svc_alloc_rs(struct ptlrpc_request *req, int msglen)
2498 {
2499         struct gss_svc_reqctx       *grctx;
2500         struct ptlrpc_reply_state   *rs;
2501         int                          early, privacy, svc, bsd_off = 0;
2502         __u32                        ibuflens[2], buflens[4];
2503         int                          ibufcnt = 0, bufcnt;
2504         int                          txtsize, wmsg_size, rs_size;
2505         ENTRY;
2506
2507         LASSERT(msglen % 8 == 0);
2508
2509         if (req->rq_pack_bulk && !req->rq_bulk_read && !req->rq_bulk_write) {
2510                 CERROR("client request bulk sec on non-bulk rpc\n");
2511                 RETURN(-EPROTO);
2512         }
2513
2514         svc = SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc);
2515         early = (req->rq_packed_final == 0);
2516
2517         grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
2518         if (!early && gss_svc_reqctx_is_special(grctx))
2519                 privacy = 0;
2520         else
2521                 privacy = (svc == SPTLRPC_SVC_PRIV);
2522
2523         if (privacy) {
2524                 /* inner clear buffers */
2525                 ibufcnt = 1;
2526                 ibuflens[0] = msglen;
2527
2528                 if (req->rq_pack_bulk) {
2529                         LASSERT(grctx->src_reqbsd);
2530
2531                         bsd_off = ibufcnt;
2532                         ibuflens[ibufcnt++] = gss_svc_bulk_payload(
2533                                                         grctx->src_ctx,
2534                                                         &req->rq_flvr,
2535                                                         req->rq_bulk_read);
2536                 }
2537
2538                 txtsize = lustre_msg_size_v2(ibufcnt, ibuflens);
2539                 txtsize += GSS_MAX_CIPHER_BLOCK;
2540
2541                 /* wrapper buffer */
2542                 bufcnt = 2;
2543                 buflens[0] = PTLRPC_GSS_HEADER_SIZE;
2544                 buflens[1] = gss_svc_payload(grctx, early, txtsize, 1);
2545         } else {
2546                 bufcnt = 2;
2547                 buflens[0] = PTLRPC_GSS_HEADER_SIZE;
2548                 buflens[1] = msglen;
2549
2550                 txtsize = buflens[0];
2551                 if (svc == SPTLRPC_SVC_INTG)
2552                         txtsize += buflens[1];
2553
2554                 if (req->rq_pack_bulk) {
2555                         LASSERT(grctx->src_reqbsd);
2556
2557                         bsd_off = bufcnt;
2558                         buflens[bufcnt] = gss_svc_bulk_payload(
2559                                                         grctx->src_ctx,
2560                                                         &req->rq_flvr,
2561                                                         req->rq_bulk_read);
2562                         if (svc == SPTLRPC_SVC_INTG)
2563                                 txtsize += buflens[bufcnt];
2564                         bufcnt++;
2565                 }
2566
2567                 if ((!early && gss_svc_reqctx_is_special(grctx)) ||
2568                     svc != SPTLRPC_SVC_NULL)
2569                         buflens[bufcnt++] = gss_svc_payload(grctx, early,
2570                                                             txtsize, 0);
2571         }
2572
2573         wmsg_size = lustre_msg_size_v2(bufcnt, buflens);
2574
2575         rs_size = sizeof(*rs) + wmsg_size;
2576         rs = req->rq_reply_state;
2577
2578         if (rs) {
2579                 /* pre-allocated */
2580                 LASSERT(rs->rs_size >= rs_size);
2581         } else {
2582                 OBD_ALLOC(rs, rs_size);
2583                 if (rs == NULL)
2584                         RETURN(-ENOMEM);
2585
2586                 rs->rs_size = rs_size;
2587         }
2588
2589         rs->rs_repbuf = (struct lustre_msg *) (rs + 1);
2590         rs->rs_repbuf_len = wmsg_size;
2591
2592         /* initialize the buffer */
2593         if (privacy) {
2594                 lustre_init_msg_v2(rs->rs_repbuf, ibufcnt, ibuflens, NULL);
2595                 rs->rs_msg = lustre_msg_buf(rs->rs_repbuf, 0, msglen);
2596         } else {
2597                 lustre_init_msg_v2(rs->rs_repbuf, bufcnt, buflens, NULL);
2598                 rs->rs_repbuf->lm_secflvr = req->rq_flvr.sf_rpc;
2599
2600                 rs->rs_msg = lustre_msg_buf(rs->rs_repbuf, 1, 0);
2601         }
2602
2603         if (bsd_off) {
2604                 grctx->src_repbsd = lustre_msg_buf(rs->rs_repbuf, bsd_off, 0);
2605                 grctx->src_repbsd_size = lustre_msg_buflen(rs->rs_repbuf,
2606                                                            bsd_off);
2607         }
2608
2609         gss_svc_reqctx_addref(grctx);
2610         rs->rs_svc_ctx = req->rq_svc_ctx;
2611
2612         LASSERT(rs->rs_msg);
2613         req->rq_reply_state = rs;
2614         RETURN(0);
2615 }
2616
2617 static int gss_svc_seal(struct ptlrpc_request *req,
2618                         struct ptlrpc_reply_state *rs,
2619                         struct gss_svc_reqctx *grctx)
2620 {
2621         struct gss_svc_ctx      *gctx = grctx->src_ctx;
2622         rawobj_t                 hdrobj, msgobj, token;
2623         struct gss_header       *ghdr;
2624         __u8                    *token_buf;
2625         int                      token_buflen; 
2626         __u32                    buflens[2], major;
2627         int                      msglen, rc;
2628         ENTRY;
2629
2630         /* get clear data length. note embedded lustre_msg might
2631          * have been shrinked */
2632         if (req->rq_replen != lustre_msg_buflen(rs->rs_repbuf, 0))
2633                 msglen = lustre_shrink_msg(rs->rs_repbuf, 0, req->rq_replen, 1);
2634         else 
2635                 msglen = lustre_msg_size_v2(rs->rs_repbuf->lm_bufcount,
2636                                             rs->rs_repbuf->lm_buflens);
2637
2638         /* temporarily use tail of buffer to hold gss header data */
2639         LASSERT(msglen + PTLRPC_GSS_HEADER_SIZE <= rs->rs_repbuf_len);
2640         ghdr = (struct gss_header *) ((char *) rs->rs_repbuf +
2641                                 rs->rs_repbuf_len - PTLRPC_GSS_HEADER_SIZE);
2642         ghdr->gh_version = PTLRPC_GSS_VERSION;
2643         ghdr->gh_sp = LUSTRE_SP_ANY;
2644         ghdr->gh_flags = 0;
2645         ghdr->gh_proc = PTLRPC_GSS_PROC_DATA;
2646         ghdr->gh_seq = grctx->src_wirectx.gw_seq;
2647         ghdr->gh_svc = SPTLRPC_SVC_PRIV;
2648         ghdr->gh_handle.len = 0;
2649         if (req->rq_pack_bulk)
2650                 ghdr->gh_flags |= LUSTRE_GSS_PACK_BULK;
2651
2652         /* allocate temporary cipher buffer */
2653         token_buflen = gss_mech_payload(gctx->gsc_mechctx, msglen, 1);
2654         OBD_ALLOC(token_buf, token_buflen);
2655         if (token_buf == NULL)
2656                 RETURN(-ENOMEM);
2657
2658         hdrobj.len = PTLRPC_GSS_HEADER_SIZE;
2659         hdrobj.data = (__u8 *) ghdr;
2660         msgobj.len = msglen;
2661         msgobj.data = (__u8 *) rs->rs_repbuf;
2662         token.len = token_buflen;
2663         token.data = token_buf;
2664
2665         major = lgss_wrap(gctx->gsc_mechctx, &hdrobj, &msgobj,
2666                           rs->rs_repbuf_len - PTLRPC_GSS_HEADER_SIZE, &token);
2667         if (major != GSS_S_COMPLETE) {
2668                 CERROR("wrap message error: %08x\n", major);
2669                 GOTO(out_free, rc = -EPERM);
2670         }
2671         LASSERT(token.len <= token_buflen);
2672
2673         /* we are about to override data at rs->rs_repbuf, nullify pointers
2674          * to which to catch further illegal usage. */
2675         if (req->rq_pack_bulk) {
2676                 grctx->src_repbsd = NULL;
2677                 grctx->src_repbsd_size = 0;
2678         }
2679
2680         /* now fill the actual wire data
2681          * - gss header
2682          * - gss token
2683          */
2684         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
2685         buflens[1] = token.len;
2686
2687         rs->rs_repdata_len = lustre_msg_size_v2(2, buflens);
2688         LASSERT(rs->rs_repdata_len <= rs->rs_repbuf_len);
2689
2690         lustre_init_msg_v2(rs->rs_repbuf, 2, buflens, NULL);
2691         rs->rs_repbuf->lm_secflvr = req->rq_flvr.sf_rpc;
2692
2693         memcpy(lustre_msg_buf(rs->rs_repbuf, 0, 0), ghdr,
2694                PTLRPC_GSS_HEADER_SIZE);
2695         memcpy(lustre_msg_buf(rs->rs_repbuf, 1, 0), token.data, token.len);
2696
2697         /* reply offset */
2698         if (req->rq_packed_final &&
2699             (lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT))
2700                 req->rq_reply_off = gss_at_reply_off_priv;
2701         else
2702                 req->rq_reply_off = 0;
2703
2704         /* to catch upper layer's further access */
2705         rs->rs_msg = NULL;
2706         req->rq_repmsg = NULL;
2707         req->rq_replen = 0;
2708
2709         rc = 0;
2710 out_free:
2711         OBD_FREE(token_buf, token_buflen);
2712         RETURN(rc);
2713 }
2714
2715 int gss_svc_authorize(struct ptlrpc_request *req)
2716 {
2717         struct ptlrpc_reply_state *rs = req->rq_reply_state;
2718         struct gss_svc_reqctx     *grctx = gss_svc_ctx2reqctx(req->rq_svc_ctx);
2719         struct gss_wire_ctx       *gw = &grctx->src_wirectx;
2720         int                        early, rc;
2721         ENTRY;
2722
2723         early = (req->rq_packed_final == 0);
2724
2725         if (!early && gss_svc_reqctx_is_special(grctx)) {
2726                 LASSERT(rs->rs_repdata_len != 0);
2727
2728                 req->rq_reply_off = gss_at_reply_off_integ;
2729                 RETURN(0);
2730         }
2731
2732         /* early reply could happen in many cases */
2733         if (!early &&
2734             gw->gw_proc != PTLRPC_GSS_PROC_DATA &&
2735             gw->gw_proc != PTLRPC_GSS_PROC_DESTROY) {
2736                 CERROR("proc %d not support\n", gw->gw_proc);
2737                 RETURN(-EINVAL);
2738         }
2739
2740         LASSERT(grctx->src_ctx);
2741
2742         switch (gw->gw_svc) {
2743         case SPTLRPC_SVC_NULL:
2744         case SPTLRPC_SVC_AUTH:
2745         case SPTLRPC_SVC_INTG:
2746                 rc = gss_svc_sign(req, rs, grctx, gw->gw_svc);
2747                 break;
2748         case SPTLRPC_SVC_PRIV:
2749                 rc = gss_svc_seal(req, rs, grctx);
2750                 break;
2751         default:
2752                 CERROR("Unknown service %d\n", gw->gw_svc);
2753                 GOTO(out, rc = -EINVAL);
2754         }
2755         rc = 0;
2756
2757 out:
2758         RETURN(rc);
2759 }
2760
2761 void gss_svc_free_rs(struct ptlrpc_reply_state *rs)
2762 {
2763         struct gss_svc_reqctx *grctx;
2764
2765         LASSERT(rs->rs_svc_ctx);
2766         grctx = container_of(rs->rs_svc_ctx, struct gss_svc_reqctx, src_base);
2767
2768         gss_svc_reqctx_decref(grctx);
2769         rs->rs_svc_ctx = NULL;
2770
2771         if (!rs->rs_prealloc)
2772                 OBD_FREE(rs, rs->rs_size);
2773 }
2774
2775 void gss_svc_free_ctx(struct ptlrpc_svc_ctx *ctx)
2776 {
2777         LASSERT(cfs_atomic_read(&ctx->sc_refcount) == 0);
2778         gss_svc_reqctx_free(gss_svc_ctx2reqctx(ctx));
2779 }
2780
2781 int gss_copy_rvc_cli_ctx(struct ptlrpc_cli_ctx *cli_ctx,
2782                          struct ptlrpc_svc_ctx *svc_ctx)
2783 {
2784         struct gss_cli_ctx     *cli_gctx = ctx2gctx(cli_ctx);
2785         struct gss_svc_ctx     *svc_gctx = gss_svc_ctx2gssctx(svc_ctx);
2786         struct gss_ctx         *mechctx = NULL;
2787
2788         LASSERT(cli_gctx);
2789         LASSERT(svc_gctx && svc_gctx->gsc_mechctx);
2790
2791         cli_gctx->gc_proc = PTLRPC_GSS_PROC_DATA;
2792         cli_gctx->gc_win = GSS_SEQ_WIN;
2793
2794         /* The problem is the reverse ctx might get lost in some recovery
2795          * situations, and the same svc_ctx will be used to re-create it.
2796          * if there's callback be sentout before that, new reverse ctx start
2797          * with sequence 0 will lead to future callback rpc be treated as
2798          * replay.
2799          *
2800          * each reverse root ctx will record its latest sequence number on its
2801          * buddy svcctx before be destroied, so here we continue use it.
2802          */
2803         cfs_atomic_set(&cli_gctx->gc_seq, svc_gctx->gsc_rvs_seq);
2804
2805         if (gss_svc_upcall_dup_handle(&cli_gctx->gc_svc_handle, svc_gctx)) {
2806                 CERROR("failed to dup svc handle\n");
2807                 goto err_out;
2808         }
2809
2810         if (lgss_copy_reverse_context(svc_gctx->gsc_mechctx, &mechctx) !=
2811             GSS_S_COMPLETE) {
2812                 CERROR("failed to copy mech context\n");
2813                 goto err_svc_handle;
2814         }
2815
2816         if (rawobj_dup(&cli_gctx->gc_handle, &svc_gctx->gsc_rvs_hdl)) {
2817                 CERROR("failed to dup reverse handle\n");
2818                 goto err_ctx;
2819         }
2820
2821         cli_gctx->gc_mechctx = mechctx;
2822         gss_cli_ctx_uptodate(cli_gctx);
2823
2824         return 0;
2825
2826 err_ctx:
2827         lgss_delete_sec_context(&mechctx);
2828 err_svc_handle:
2829         rawobj_free(&cli_gctx->gc_svc_handle);
2830 err_out:
2831         return -ENOMEM;
2832 }
2833
2834 static void gss_init_at_reply_offset(void)
2835 {
2836         __u32 buflens[3];
2837         int clearsize;
2838
2839         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
2840         buflens[1] = lustre_msg_early_size();
2841         buflens[2] = gss_cli_payload(NULL, buflens[1], 0);
2842         gss_at_reply_off_integ = lustre_msg_size_v2(3, buflens);
2843
2844         buflens[0] = lustre_msg_early_size();
2845         clearsize = lustre_msg_size_v2(1, buflens);
2846         buflens[0] = PTLRPC_GSS_HEADER_SIZE;
2847         buflens[1] = gss_cli_payload(NULL, clearsize, 0);
2848         buflens[2] = gss_cli_payload(NULL, clearsize, 1);
2849         gss_at_reply_off_priv = lustre_msg_size_v2(3, buflens);
2850 }
2851
2852 int __init sptlrpc_gss_init(void)
2853 {
2854         int rc;
2855
2856         rc = gss_init_lproc();
2857         if (rc)
2858                 return rc;
2859
2860         rc = gss_init_cli_upcall();
2861         if (rc)
2862                 goto out_lproc;
2863
2864         rc = gss_init_svc_upcall();
2865         if (rc)
2866                 goto out_cli_upcall;
2867
2868         rc = init_kerberos_module();
2869         if (rc)
2870                 goto out_svc_upcall;
2871
2872         /* register policy after all other stuff be intialized, because it
2873          * might be in used immediately after the registration. */
2874
2875         rc = gss_init_keyring();
2876         if (rc)
2877                 goto out_kerberos;
2878
2879 #ifdef HAVE_GSS_PIPEFS
2880         rc = gss_init_pipefs();
2881         if (rc)
2882                 goto out_keyring;
2883 #endif
2884
2885         gss_init_at_reply_offset();
2886
2887         return 0;
2888
2889 #ifdef HAVE_GSS_PIPEFS
2890 out_keyring:
2891         gss_exit_keyring();
2892 #endif
2893
2894 out_kerberos:
2895         cleanup_kerberos_module();
2896 out_svc_upcall:
2897         gss_exit_svc_upcall();
2898 out_cli_upcall:
2899         gss_exit_cli_upcall();
2900 out_lproc:
2901         gss_exit_lproc();
2902         return rc;
2903 }
2904
2905 static void __exit sptlrpc_gss_exit(void)
2906 {
2907         gss_exit_keyring();
2908 #ifdef HAVE_GSS_PIPEFS
2909         gss_exit_pipefs();
2910 #endif
2911         cleanup_kerberos_module();
2912         gss_exit_svc_upcall();
2913         gss_exit_cli_upcall();
2914         gss_exit_lproc();
2915 }
2916
2917 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
2918 MODULE_DESCRIPTION("GSS security policy for Lustre");
2919 MODULE_LICENSE("GPL");
2920
2921 module_init(sptlrpc_gss_init);
2922 module_exit(sptlrpc_gss_exit);