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