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