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