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