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