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