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