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