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