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