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