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