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