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