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