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