Whamcloud - gitweb
land b_hd_sec: perm/acl authorization for remote users.
[fs/lustre-release.git] / lustre / sec / gss / sec_gss.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * Modifications for Lustre
5  * Copyright 2004, Cluster File Systems, Inc.
6  * All rights reserved
7  * Author: Eric Mei <ericm@clusterfs.com>
8  */
9
10 /*
11  * linux/net/sunrpc/auth_gss.c
12  *
13  * RPCSEC_GSS client authentication.
14  *
15  *  Copyright (c) 2000 The Regents of the University of Michigan.
16  *  All rights reserved.
17  *
18  *  Dug Song       <dugsong@monkey.org>
19  *  Andy Adamson   <andros@umich.edu>
20  *
21  *  Redistribution and use in source and binary forms, with or without
22  *  modification, are permitted provided that the following conditions
23  *  are met:
24  *
25  *  1. Redistributions of source code must retain the above copyright
26  *     notice, this list of conditions and the following disclaimer.
27  *  2. Redistributions in binary form must reproduce the above copyright
28  *     notice, this list of conditions and the following disclaimer in the
29  *     documentation and/or other materials provided with the distribution.
30  *  3. Neither the name of the University nor the names of its
31  *     contributors may be used to endorse or promote products derived
32  *     from this software without specific prior written permission.
33  *
34  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
35  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
36  *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
37  *  DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
38  *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
39  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
40  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
41  *  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
42  *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
43  *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
44  *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45  *
46  */
47
48 #ifndef EXPORT_SYMTAB
49 # define EXPORT_SYMTAB
50 #endif
51 #define DEBUG_SUBSYSTEM S_SEC
52 #ifdef __KERNEL__
53 #include <linux/init.h>
54 #include <linux/module.h>
55 #include <linux/slab.h>
56 #include <linux/dcache.h>
57 #include <linux/fs.h>
58 #include <linux/random.h>
59 /* for rpc_pipefs */
60 struct rpc_clnt;
61 #include <linux/sunrpc/rpc_pipe_fs.h>
62 #else
63 #include <liblustre.h>
64 #endif
65
66 #include <libcfs/kp30.h>
67 #include <linux/obd.h>
68 #include <linux/obd_class.h>
69 #include <linux/obd_support.h>
70 #include <linux/lustre_idl.h>
71 #include <linux/lustre_net.h>
72 #include <linux/lustre_import.h>
73 #include <linux/lustre_sec.h>
74
75 #include "gss_err.h"
76 #include "gss_internal.h"
77 #include "gss_api.h"
78
79 #define LUSTRE_PIPEDIR          "/lustre"
80
81 #define GSS_CREDCACHE_EXPIRE    (30 * 60)          /* 30 minute */
82
83 #define GSS_TIMEOUT_DELTA       (5)
84 #define CRED_REFRESH_UPCALL_TIMEOUT                             \
85         ({                                                      \
86                 int timeout = obd_timeout - GSS_TIMEOUT_DELTA;  \
87                                                                 \
88                 if (timeout < GSS_TIMEOUT_DELTA * 2)            \
89                         timeout = GSS_TIMEOUT_DELTA * 2;        \
90                 timeout;                                        \
91         })
92 #define SECINIT_RPC_TIMEOUT                                     \
93         ({                                                      \
94                 int timeout = CRED_REFRESH_UPCALL_TIMEOUT -     \
95                               GSS_TIMEOUT_DELTA;                \
96                 if (timeout < GSS_TIMEOUT_DELTA)                \
97                         timeout = GSS_TIMEOUT_DELTA;            \
98                 timeout;                                        \
99         })
100 #define SECFINI_RPC_TIMEOUT     (GSS_TIMEOUT_DELTA)
101
102
103 /**********************************************
104  * gss security init/fini helper              *
105  **********************************************/
106
107 static int secinit_compose_request(struct obd_import *imp,
108                                    char *buf, int bufsize,
109                                    int lustre_srv,
110                                    uid_t uid, gid_t gid,
111                                    long token_size,
112                                    char __user *token)
113 {
114         struct ptlrpcs_wire_hdr *hdr;
115         struct lustre_msg       *lmsg;
116         struct mds_req_sec_desc *secdesc;
117         int                      size = sizeof(*secdesc);
118         __u32                    lmsg_size, *p;
119         int                      rc;
120
121         lmsg_size = lustre_msg_size(1, &size);
122
123         if (sizeof(*hdr) + lmsg_size + size_round(token_size) > bufsize) {
124                 CERROR("token size %ld too large\n", token_size);
125                 return -EINVAL;
126         }
127
128         /* security wire hdr */
129         hdr = buf_to_sec_hdr(buf);
130         hdr->flavor  = cpu_to_le32(PTLRPCS_FLVR_GSS_NONE);
131         hdr->msg_len = cpu_to_le32(lmsg_size);
132         hdr->sec_len = cpu_to_le32(8 * 4 + token_size);
133
134         /* lustre message & secdesc */
135         lmsg = buf_to_lustre_msg(buf);
136
137         lustre_init_msg(lmsg, 1, &size, NULL);
138         secdesc = lustre_msg_buf(lmsg, 0, size);
139         secdesc->rsd_uid = secdesc->rsd_fsuid = uid;
140         secdesc->rsd_gid = secdesc->rsd_fsgid = gid;
141         secdesc->rsd_cap = secdesc->rsd_ngroups = 0;
142
143         lmsg->handle   = imp->imp_remote_handle;
144         lmsg->type     = PTL_RPC_MSG_REQUEST;
145         lmsg->opc      = SEC_INIT;
146         lmsg->flags    = 0;
147         lmsg->conn_cnt = imp->imp_conn_cnt;
148
149         p = (__u32 *) (buf + sizeof(*hdr) + lmsg_size);
150
151         /* gss hdr */
152         *p++ = cpu_to_le32(PTLRPC_SEC_GSS_VERSION);     /* gss version */
153         *p++ = cpu_to_le32(PTLRPCS_FLVR_KRB5I);         /* subflavor */
154         *p++ = cpu_to_le32(PTLRPCS_GSS_PROC_INIT);      /* proc */
155         *p++ = cpu_to_le32(0);                          /* seq */
156         *p++ = cpu_to_le32(PTLRPCS_GSS_SVC_NONE);       /* service */
157         *p++ = cpu_to_le32(0);                          /* context handle */
158
159         /* plus lustre svc type */
160         *p++ = cpu_to_le32(lustre_srv);
161
162         /* now the token part */
163         *p++ = cpu_to_le32((__u32) token_size);
164         LASSERT(((char *)p - buf) + token_size <= bufsize);
165
166         rc = copy_from_user(p, token, token_size);
167         if (rc) {
168                 CERROR("can't copy token\n");
169                 return -EFAULT;
170         }
171
172         rc = size_round(((char *)p - buf) + token_size);
173         return rc;
174 }
175
176 static int secinit_parse_reply(char *repbuf, int replen,
177                                char __user *outbuf, long outlen)
178 {
179         __u32                   *p = (__u32 *)repbuf;
180         struct ptlrpcs_wire_hdr *hdr = (struct ptlrpcs_wire_hdr *) repbuf;
181         __u32                    lmsg_len, sec_len, status;
182         __u32                    major, minor, seq, obj_len, round_len;
183         __u32                    effective = 0;
184
185         if (replen <= (4 + 6) * 4) {
186                 CERROR("reply size %d too small\n", replen);
187                 return -EINVAL;
188         }
189
190         hdr->flavor = le32_to_cpu(hdr->flavor);
191         hdr->msg_len = le32_to_cpu(hdr->msg_len);
192         hdr->sec_len = le32_to_cpu(hdr->sec_len);
193
194         lmsg_len = le32_to_cpu(p[2]);
195         sec_len = le32_to_cpu(p[3]);
196
197         /* sanity checks */
198         if (hdr->flavor != PTLRPCS_FLVR_GSS_NONE) {
199                 CERROR("unexpected reply\n");
200                 return -EINVAL;
201         }
202         if (hdr->msg_len % 8 ||
203             sizeof(*hdr) + hdr->msg_len + hdr->sec_len > replen) {
204                 CERROR("unexpected reply\n");
205                 return -EINVAL;
206         }
207         if (hdr->sec_len > outlen) {
208                 CERROR("outbuf too small\n");
209                 return -EINVAL;
210         }
211
212         p = (__u32 *) buf_to_sec_data(repbuf);
213         effective = 0;
214
215         status = le32_to_cpu(*p++);
216         major = le32_to_cpu(*p++);
217         minor = le32_to_cpu(*p++);
218         seq = le32_to_cpu(*p++);
219         effective += 4 * 4;
220
221         if (copy_to_user(outbuf, &status, 4))
222                 return -EFAULT;
223         outbuf += 4;
224         if (copy_to_user(outbuf, &major, 4))
225                 return -EFAULT;
226         outbuf += 4;
227         if (copy_to_user(outbuf, &minor, 4))
228                 return -EFAULT;
229         outbuf += 4;
230         if (copy_to_user(outbuf, &seq, 4))
231                 return -EFAULT;
232         outbuf += 4;
233
234         obj_len = le32_to_cpu(*p++);
235         round_len = (obj_len + 3) & ~ 3;
236         if (copy_to_user(outbuf, &obj_len, 4))
237                 return -EFAULT;
238         outbuf += 4;
239         if (copy_to_user(outbuf, (char *)p, round_len))
240                 return -EFAULT;
241         p += round_len / 4;
242         outbuf += round_len;
243         effective += 4 + round_len;
244
245         obj_len = le32_to_cpu(*p++);
246         round_len = (obj_len + 3) & ~ 3;
247         if (copy_to_user(outbuf, &obj_len, 4))
248                 return -EFAULT;
249         outbuf += 4;
250         if (copy_to_user(outbuf, (char *)p, round_len))
251                 return -EFAULT;
252         p += round_len / 4;
253         outbuf += round_len;
254         effective += 4 + round_len;
255
256         return effective;
257 }
258
259 /* XXX move to where lgssd could see */
260 struct lgssd_ioctl_param {
261         int             version;        /* in   */
262         char           *uuid;           /* in   */
263         int             lustre_svc;     /* in   */
264         uid_t           uid;            /* in   */
265         gid_t           gid;            /* in   */
266         long            send_token_size;/* in   */
267         char           *send_token;     /* in   */
268         long            reply_buf_size; /* in   */
269         char           *reply_buf;      /* in   */
270         long            status;         /* out  */
271         long            reply_length;   /* out  */
272 };
273
274 static int gss_send_secinit_rpc(__user char *buffer, unsigned long count)
275 {
276         struct obd_import        *imp;
277         struct ptlrpc_request    *request = NULL;
278         struct lgssd_ioctl_param  param;
279         const int                 reqbuf_size = 1024;
280         const int                 repbuf_size = 1024;
281         char                     *reqbuf, *repbuf;
282         struct obd_device        *obd;
283         char                      obdname[64];
284         long                      lsize;
285         int                       rc, reqlen, replen;
286
287         if (count != sizeof(param)) {
288                 CERROR("ioctl size %lu, expect %d, please check lgssd version\n",
289                         count, sizeof(param));
290                 RETURN(-EINVAL);
291         }
292         if (copy_from_user(&param, buffer, sizeof(param))) {
293                 CERROR("failed copy data from lgssd\n");
294                 RETURN(-EFAULT);
295         }
296
297         if (param.version != GSSD_INTERFACE_VERSION) {
298                 CERROR("gssd interface version %d (expect %d)\n",
299                         param.version, GSSD_INTERFACE_VERSION);
300                 RETURN(-EINVAL);
301         }
302
303         /* take name */
304         if (strncpy_from_user(obdname, param.uuid,
305                               sizeof(obdname)) <= 0) {
306                 CERROR("Invalid obdname pointer\n");
307                 RETURN(-EFAULT);
308         }
309
310         obd = class_name2obd(obdname);
311         if (!obd) {
312                 CERROR("no such obd %s\n", obdname);
313                 RETURN(-EINVAL);
314         }
315
316         imp = class_import_get(obd->u.cli.cl_import);
317
318         OBD_ALLOC(reqbuf, reqbuf_size);
319         OBD_ALLOC(repbuf, reqbuf_size);
320
321         if (!reqbuf || !repbuf) {
322                 CERROR("Can't alloc buffer: %p/%p\n", reqbuf, repbuf);
323                 param.status = -ENOMEM;
324                 goto out_copy;
325         }
326
327         /* get token */
328         reqlen = secinit_compose_request(imp, reqbuf, reqbuf_size,
329                                          param.lustre_svc,
330                                          param.uid, param.gid,
331                                          param.send_token_size,
332                                          param.send_token);
333         if (reqlen < 0) {
334                 param.status = reqlen;
335                 goto out_copy;
336         }
337
338         request = ptl_do_rawrpc(imp, reqbuf, reqbuf_size, reqlen,
339                                 repbuf, repbuf_size, &replen,
340                                 SECINIT_RPC_TIMEOUT, &rc);
341         if (request == NULL || rc) {
342                 param.status = rc;
343                 goto out_copy;
344         }
345
346         if (replen > param.reply_buf_size) {
347                 CERROR("output buffer size %ld too small, need %d\n",
348                         param.reply_buf_size, replen);
349                 param.status = -EINVAL;
350                 goto out_copy;
351         }
352
353         lsize = secinit_parse_reply(repbuf, replen,
354                                     param.reply_buf, param.reply_buf_size);
355         if (lsize < 0) {
356                 param.status = (int) lsize;
357                 goto out_copy;
358         }
359
360         param.status = 0;
361         param.reply_length = lsize;
362
363 out_copy:
364         if (copy_to_user(buffer, &param, sizeof(param)))
365                 rc = -EFAULT;
366         else
367                 rc = 0;
368
369         class_import_put(imp);
370         if (request == NULL) {
371                 if (repbuf)
372                         OBD_FREE(repbuf, repbuf_size);
373                 if (reqbuf)
374                         OBD_FREE(reqbuf, reqbuf_size);
375         } else {
376                 rawrpc_req_finished(request);
377         }
378         RETURN(rc);
379 }
380
381 /**********************************************
382  * structure definitions                      *
383  **********************************************/
384 struct gss_sec {
385         struct ptlrpc_sec       gs_base;
386         struct gss_api_mech    *gs_mech;
387 #ifdef __KERNEL__
388         spinlock_t              gs_lock;
389         struct list_head        gs_upcalls;
390         char                   *gs_pipepath;
391         struct dentry          *gs_depipe;
392 #endif
393 };
394
395 #ifdef __KERNEL__
396
397 static rwlock_t gss_ctx_lock = RW_LOCK_UNLOCKED;
398
399 struct gss_upcall_msg_data {
400         __u32                           gum_uid;
401         __u32                           gum_svc;
402         __u32                           gum_nal;
403         __u32                           gum_netid;
404         __u64                           gum_nid;
405 };
406
407 struct gss_upcall_msg {
408         struct rpc_pipe_msg             gum_base;
409         atomic_t                        gum_refcount;
410         struct list_head                gum_list;
411         struct gss_sec                 *gum_gsec;
412         wait_queue_head_t               gum_waitq;
413         char                            gum_obdname[64];
414         struct gss_upcall_msg_data      gum_data;
415 };
416
417 /**********************************************
418  * rpc_pipe upcall helpers                    *
419  **********************************************/
420 static
421 void gss_release_msg(struct gss_upcall_msg *gmsg)
422 {
423         ENTRY;
424         LASSERT(atomic_read(&gmsg->gum_refcount) > 0);
425
426         if (!atomic_dec_and_test(&gmsg->gum_refcount)) {
427                 CDEBUG(D_SEC, "gmsg %p ref %d\n", gmsg,
428                        atomic_read(&gmsg->gum_refcount));
429                 EXIT;
430                 return;
431         }
432         LASSERT(list_empty(&gmsg->gum_list));
433 #if 0
434         LASSERT(list_empty(&gmsg->gum_base.list));
435 #else
436         /* XXX */
437         if (!list_empty(&gmsg->gum_base.list)) {
438                 CWARN("msg %p: list: %p/%p/%p, copied %d, err %d, wq %d\n",
439                       gmsg, &gmsg->gum_base.list,
440                       gmsg->gum_base.list.prev, gmsg->gum_base.list.next,
441                       gmsg->gum_base.copied, gmsg->gum_base.errno,
442                       list_empty(&gmsg->gum_waitq.task_list));
443                 LBUG();
444         }
445 #endif
446         OBD_FREE(gmsg, sizeof(*gmsg));
447         EXIT;
448 }
449
450 static void
451 gss_unhash_msg_nolock(struct gss_upcall_msg *gmsg)
452 {
453         LASSERT(spin_is_locked(&gmsg->gum_gsec->gs_lock));
454
455         if (list_empty(&gmsg->gum_list))
456                 return;
457
458         list_del_init(&gmsg->gum_list);
459         wake_up(&gmsg->gum_waitq);
460         LASSERT(atomic_read(&gmsg->gum_refcount) > 1);
461         atomic_dec(&gmsg->gum_refcount);
462 }
463
464 static void
465 gss_unhash_msg(struct gss_upcall_msg *gmsg)
466 {
467         struct gss_sec *gsec = gmsg->gum_gsec;
468
469         spin_lock(&gsec->gs_lock);
470         gss_unhash_msg_nolock(gmsg);
471         spin_unlock(&gsec->gs_lock);
472 }
473
474 static
475 struct gss_upcall_msg * gss_find_upcall(struct gss_sec *gsec,
476                                         char *obdname,
477                                         struct gss_upcall_msg_data *gmd)
478 {
479         struct gss_upcall_msg *gmsg;
480         ENTRY;
481
482         LASSERT(spin_is_locked(&gsec->gs_lock));
483
484         list_for_each_entry(gmsg, &gsec->gs_upcalls, gum_list) {
485                 if (memcmp(&gmsg->gum_data, gmd, sizeof(*gmd)))
486                         continue;
487                 if (strcmp(gmsg->gum_obdname, obdname))
488                         continue;
489                 LASSERT(atomic_read(&gmsg->gum_refcount) > 0);
490                 atomic_inc(&gmsg->gum_refcount);
491                 CDEBUG(D_SEC, "found gmsg at %p: obdname %s, uid %d, ref %d\n",
492                        gmsg, obdname, gmd->gum_uid,
493                        atomic_read(&gmsg->gum_refcount));
494                 RETURN(gmsg);
495         }
496         RETURN(NULL);
497 }
498
499 static void gss_init_upcall_msg(struct gss_upcall_msg *gmsg,
500                                 struct gss_sec *gsec, char *obdname,
501                                 struct gss_upcall_msg_data *gmd)
502 {
503         struct rpc_pipe_msg *rpcmsg;
504         ENTRY;
505
506         /* 2 refs: 1 for hash, 1 for current user */
507         init_waitqueue_head(&gmsg->gum_waitq);
508         list_add(&gmsg->gum_list, &gsec->gs_upcalls);
509         atomic_set(&gmsg->gum_refcount, 2);
510         gmsg->gum_gsec = gsec;
511         strncpy(gmsg->gum_obdname, obdname, sizeof(gmsg->gum_obdname));
512         memcpy(&gmsg->gum_data, gmd, sizeof(*gmd));
513
514         rpcmsg = &gmsg->gum_base;
515         INIT_LIST_HEAD(&rpcmsg->list);
516         rpcmsg->data = &gmsg->gum_data;
517         rpcmsg->len = sizeof(gmsg->gum_data);
518         rpcmsg->copied = 0;
519         rpcmsg->errno = 0;
520         EXIT;
521 }
522 #endif /* __KERNEL__ */
523
524 /********************************************
525  * gss cred manipulation helpers            *
526  ********************************************/
527 #if 0
528 static
529 int gss_cred_is_uptodate_ctx(struct ptlrpc_cred *cred)
530 {
531         struct gss_cred *gcred = container_of(cred, struct gss_cred, gc_base);
532         int res = 0;
533
534         read_lock(&gss_ctx_lock);
535         if (((cred->pc_flags & PTLRPC_CRED_FLAGS_MASK) ==
536              PTLRPC_CRED_UPTODATE) &&
537             gcred->gc_ctx)
538                 res = 1;
539         read_unlock(&gss_ctx_lock);
540         return res;
541 }
542 #endif
543
544 static inline
545 struct gss_cl_ctx * gss_get_ctx(struct gss_cl_ctx *ctx)
546 {
547         atomic_inc(&ctx->gc_refcount);
548         return ctx;
549 }
550
551 static
552 void gss_destroy_ctx(struct gss_cl_ctx *ctx)
553 {
554         ENTRY;
555
556         CDEBUG(D_SEC, "destroy cl_ctx %p\n", ctx);
557         if (ctx->gc_gss_ctx)
558                 kgss_delete_sec_context(&ctx->gc_gss_ctx);
559
560         if (ctx->gc_wire_ctx.len > 0) {
561                 OBD_FREE(ctx->gc_wire_ctx.data, ctx->gc_wire_ctx.len);
562                 ctx->gc_wire_ctx.len = 0;
563         }
564
565         OBD_FREE(ctx, sizeof(*ctx));
566 }
567
568 static
569 void gss_put_ctx(struct gss_cl_ctx *ctx)
570 {
571         if (atomic_dec_and_test(&ctx->gc_refcount))
572                 gss_destroy_ctx(ctx);
573 }
574
575 static
576 struct gss_cl_ctx *gss_cred_get_ctx(struct ptlrpc_cred *cred)
577 {
578         struct gss_cred *gcred = container_of(cred, struct gss_cred, gc_base);
579         struct gss_cl_ctx *ctx = NULL;
580
581         read_lock(&gss_ctx_lock);
582         if (gcred->gc_ctx)
583                 ctx = gss_get_ctx(gcred->gc_ctx);
584         read_unlock(&gss_ctx_lock);
585         return ctx;
586 }
587
588 static
589 void gss_cred_set_ctx(struct ptlrpc_cred *cred, struct gss_cl_ctx *ctx)
590 {
591         struct gss_cred *gcred = container_of(cred, struct gss_cred, gc_base);
592         struct gss_cl_ctx *old;
593         __u64 ctx_expiry;
594         ENTRY;
595
596         if (kgss_inquire_context(ctx->gc_gss_ctx, &ctx_expiry)) {
597                 CERROR("unable to get expire time\n");
598                 ctx_expiry = 1; /* make it expired now */
599         }
600         cred->pc_expire = (unsigned long) ctx_expiry;
601
602         write_lock(&gss_ctx_lock);
603         old = gcred->gc_ctx;
604         gcred->gc_ctx = ctx;
605         set_bit(PTLRPC_CRED_UPTODATE_BIT, &cred->pc_flags);
606         write_unlock(&gss_ctx_lock);
607         if (old)
608                 gss_put_ctx(old);
609
610         CDEBUG(D_SEC, "client refreshed gss cred %p(uid %u)\n",
611                cred, cred->pc_uid);
612         EXIT;
613 }
614
615 static int
616 simple_get_bytes(char **buf, __u32 *buflen, void *res, __u32 reslen)
617 {
618         if (*buflen < reslen) {
619                 CERROR("buflen %u < %u\n", *buflen, reslen);
620                 return -EINVAL;
621         }
622
623         memcpy(res, *buf, reslen);
624         *buf += reslen;
625         *buflen -= reslen;
626         return 0;
627 }
628
629 /* data passed down:
630  *  - uid
631  *  - timeout
632  *  - gc_win / error
633  *  - wire_ctx (rawobj)
634  *  - mech_ctx? (rawobj)
635  */
636 static
637 int gss_parse_init_downcall(struct gss_api_mech *gm, rawobj_t *buf,
638                             struct gss_cl_ctx **gc,
639                             struct gss_upcall_msg_data *gmd, int *gss_err)
640 {
641         char *p = (char *)buf->data;
642         struct gss_cl_ctx *ctx;
643         __u32 len = buf->len;
644         unsigned int timeout;
645         rawobj_t tmp_buf;
646         int err = -EPERM;
647         ENTRY;
648
649         *gc = NULL;
650         *gss_err = 0;
651
652         OBD_ALLOC(ctx, sizeof(*ctx));
653         if (!ctx)
654                 RETURN(-ENOMEM);
655
656         ctx->gc_proc = RPC_GSS_PROC_DATA;
657         ctx->gc_seq = 0;
658         spin_lock_init(&ctx->gc_seq_lock);
659         atomic_set(&ctx->gc_refcount,1);
660
661         if (simple_get_bytes(&p, &len, &gmd->gum_uid, sizeof(gmd->gum_uid)))
662                 goto err_free_ctx;
663         if (simple_get_bytes(&p, &len, &gmd->gum_svc, sizeof(gmd->gum_svc)))
664                 goto err_free_ctx;
665         if (simple_get_bytes(&p, &len, &gmd->gum_nal, sizeof(gmd->gum_nal)))
666                 goto err_free_ctx;
667         if (simple_get_bytes(&p, &len, &gmd->gum_netid, sizeof(gmd->gum_netid)))
668                 goto err_free_ctx;
669         if (simple_get_bytes(&p, &len, &gmd->gum_nid, sizeof(gmd->gum_nid)))
670                 goto err_free_ctx;
671         /* FIXME: discarded timeout for now */
672         if (simple_get_bytes(&p, &len, &timeout, sizeof(timeout)))
673                 goto err_free_ctx;
674         if (simple_get_bytes(&p, &len, &ctx->gc_win, sizeof(ctx->gc_win)))
675                 goto err_free_ctx;
676
677         /* lgssd signals an error by passing ctx->gc_win = 0: */
678         if (!ctx->gc_win) {
679                 /* in which case the next 2 int are:
680                  * - rpc error
681                  * - gss error
682                  */
683                 if (simple_get_bytes(&p, &len, &err, sizeof(err))) {
684                         err = -EPERM;
685                         goto err_free_ctx;
686                 }
687                 if (simple_get_bytes(&p, &len, gss_err, sizeof(*gss_err))) {
688                         err = -EPERM;
689                         goto err_free_ctx;
690                 }
691                 if (err == 0 && *gss_err == 0) {
692                         CERROR("no error passed from downcall\n");
693                         err = -EPERM;
694                 }
695                 goto err_free_ctx;
696         }
697
698         if (rawobj_extract_local(&tmp_buf, (__u32 **) ((void *)&p), &len))
699                 goto err_free_ctx;
700         if (rawobj_dup(&ctx->gc_wire_ctx, &tmp_buf)) {
701                 err = -ENOMEM;
702                 goto err_free_ctx;
703         }
704         if (rawobj_extract_local(&tmp_buf, (__u32 **) ((void *)&p), &len))
705                 goto err_free_wire_ctx;
706         if (len) {
707                 CERROR("unexpected trailing %u bytes\n", len);
708                 goto err_free_wire_ctx;
709         }
710         if (kgss_import_sec_context(&tmp_buf, gm, &ctx->gc_gss_ctx))
711                 goto err_free_wire_ctx;
712
713         *gc = ctx;
714         RETURN(0);
715
716 err_free_wire_ctx:
717         if (ctx->gc_wire_ctx.data)
718                 OBD_FREE(ctx->gc_wire_ctx.data, ctx->gc_wire_ctx.len);
719 err_free_ctx:
720         OBD_FREE(ctx, sizeof(*ctx));
721         CDEBUG(D_SEC, "err_code %d, gss code %d\n", err, *gss_err);
722         return err;
723 }
724
725 /***************************************
726  * cred APIs                           *
727  ***************************************/
728 #ifdef __KERNEL__
729 static int gss_cred_refresh(struct ptlrpc_cred *cred)
730 {
731         struct obd_import          *import;
732         struct gss_sec             *gsec;
733         struct gss_upcall_msg      *gss_msg, *gss_new;
734         struct gss_upcall_msg_data  gmd;
735         struct dentry              *dentry;
736         char                       *obdname, *obdtype;
737         wait_queue_t                wait;
738         uid_t                       uid = cred->pc_uid;
739         int                         res;
740         ENTRY;
741
742         might_sleep();
743
744         /* any flags means it has been handled, do nothing */
745         if (cred->pc_flags & PTLRPC_CRED_FLAGS_MASK)
746                 RETURN(0);
747
748         LASSERT(cred->pc_sec);
749         LASSERT(cred->pc_sec->ps_import);
750         LASSERT(cred->pc_sec->ps_import->imp_obd);
751
752         import = cred->pc_sec->ps_import;
753         if (!import->imp_connection) {
754                 CERROR("import has no connection set\n");
755                 RETURN(-EINVAL);
756         }
757
758         gmd.gum_uid = uid;
759         gmd.gum_nal = import->imp_connection->c_peer.peer_ni->pni_number;
760         gmd.gum_netid = 0;
761         gmd.gum_nid = import->imp_connection->c_peer.peer_id.nid;
762
763         obdtype = import->imp_obd->obd_type->typ_name;
764         if (!strcmp(obdtype, "mdc"))
765                 gmd.gum_svc = LUSTRE_GSS_SVC_MDS;
766         else if (!strcmp(obdtype, "osc"))
767                 gmd.gum_svc = LUSTRE_GSS_SVC_OSS;
768         else {
769                 CERROR("gss on %s?\n", obdtype);
770                 RETURN(-EINVAL);
771         }
772
773         gsec = container_of(cred->pc_sec, struct gss_sec, gs_base);
774         obdname = import->imp_obd->obd_name;
775         dentry = gsec->gs_depipe;
776         gss_new = NULL;
777         res = 0;
778
779         CDEBUG(D_SEC, "Initiate gss context %p(%u@%s)\n",
780                container_of(cred, struct gss_cred, gc_base),
781                uid, import->imp_target_uuid.uuid);
782
783 again:
784         spin_lock(&gsec->gs_lock);
785         gss_msg = gss_find_upcall(gsec, obdname, &gmd);
786         if (gss_msg) {
787                 if (gss_new) {
788                         OBD_FREE(gss_new, sizeof(*gss_new));
789                         gss_new = NULL;
790                 }
791                 GOTO(waiting, res);
792         }
793
794         if (!gss_new) {
795                 spin_unlock(&gsec->gs_lock);
796                 OBD_ALLOC(gss_new, sizeof(*gss_new));
797                 if (!gss_new)
798                         RETURN(-ENOMEM);
799                 goto again;
800         }
801         /* so far we'v created gss_new */
802         gss_init_upcall_msg(gss_new, gsec, obdname, &gmd);
803
804         /* we'v created upcall msg, nobody else should touch the
805          * flag of this cred, unless be set as dead/expire by
806          * administrator via lctl etc.
807          */
808         if (cred->pc_flags & PTLRPC_CRED_FLAGS_MASK) {
809                 CWARN("cred %p("LPU64"/%u) was set flags %lx unexpectedly\n",
810                       cred, cred->pc_pag, cred->pc_uid, cred->pc_flags);
811                 cred->pc_flags |= PTLRPC_CRED_DEAD | PTLRPC_CRED_ERROR;
812                 gss_unhash_msg_nolock(gss_new);
813                 spin_unlock(&gsec->gs_lock);
814                 gss_release_msg(gss_new);
815                 RETURN(0);
816         }
817
818         /* need to make upcall now */
819         spin_unlock(&gsec->gs_lock);
820         res = rpc_queue_upcall(dentry->d_inode, &gss_new->gum_base);
821         if (res) {
822                 CERROR("rpc_queue_upcall failed: %d\n", res);
823                 gss_unhash_msg(gss_new);
824                 gss_release_msg(gss_new);
825                 cred->pc_flags |= PTLRPC_CRED_DEAD | PTLRPC_CRED_ERROR;
826                 RETURN(res);
827         }
828         gss_msg = gss_new;
829         spin_lock(&gsec->gs_lock);
830
831 waiting:
832         /* upcall might finish quickly */
833         if (list_empty(&gss_msg->gum_list)) {
834                 spin_unlock(&gsec->gs_lock);
835                 res = 0;
836                 goto out;
837         }
838
839         init_waitqueue_entry(&wait, current);
840         set_current_state(TASK_INTERRUPTIBLE);
841         add_wait_queue(&gss_msg->gum_waitq, &wait);
842         spin_unlock(&gsec->gs_lock);
843
844         if (gss_new)
845                 res = schedule_timeout(CRED_REFRESH_UPCALL_TIMEOUT * HZ);
846         else {
847                 schedule();
848                 res = 0;
849         }
850
851         remove_wait_queue(&gss_msg->gum_waitq, &wait);
852
853         /* - the one who refresh the cred for us should also be responsible
854          *   to set the status of cred, we can simply return.
855          * - if cred flags has been set, we also don't need to do that again,
856          *   no matter signal pending or timeout etc.
857          */
858         if (!gss_new || cred->pc_flags & PTLRPC_CRED_FLAGS_MASK)
859                 goto out;
860
861         if (signal_pending(current)) {
862                 CERROR("%s: cred %p: interrupted upcall\n",
863                        current->comm, cred);
864                 cred->pc_flags |= PTLRPC_CRED_DEAD | PTLRPC_CRED_ERROR;
865                 res = -EINTR;
866         } else if (res == 0) {
867                 CERROR("cred %p: upcall timedout\n", cred);
868                 set_bit(PTLRPC_CRED_DEAD_BIT, &cred->pc_flags);
869                 res = -ETIMEDOUT;
870         } else
871                 res = 0;
872
873 out:
874         gss_release_msg(gss_msg);
875
876         RETURN(res);
877 }
878 #else /* !__KERNEL__ */
879 extern int lgss_handle_krb5_upcall(uid_t uid, __u32 dest_ip,
880                                    char *obd_name,
881                                    char *buf, int bufsize,
882                                    int (*callback)(char*, unsigned long));
883
884 static int gss_cred_refresh(struct ptlrpc_cred *cred)
885 {
886         char                    buf[4096];
887         rawobj_t                obj;
888         struct obd_import      *imp;
889         struct gss_sec         *gsec;
890         struct gss_api_mech    *mech;
891         struct gss_cl_ctx      *ctx = NULL;
892         struct vfs_cred         vcred = { 0 };
893         ptl_nid_t               peer_nid;
894         __u32                   dest_ip;
895         __u32                   subflavor;
896         int                     rc, gss_err;
897
898         LASSERT(cred);
899         LASSERT(cred->pc_sec);
900         LASSERT(cred->pc_sec->ps_import);
901         LASSERT(cred->pc_sec->ps_import->imp_obd);
902
903         if (ptlrpcs_cred_is_uptodate(cred))
904                 RETURN(0);
905
906         imp = cred->pc_sec->ps_import;
907         peer_nid = imp->imp_connection->c_peer.peer_id.nid;
908         dest_ip = (__u32) (peer_nid & 0xFFFFFFFF);
909         subflavor = cred->pc_sec->ps_flavor.subflavor;
910
911         if (subflavor != PTLRPC_SEC_GSS_KRB5I) {
912                 CERROR("unknown subflavor %u\n", subflavor);
913                 GOTO(err_out, rc = -EINVAL);
914         }
915
916         rc = lgss_handle_krb5_upcall(cred->pc_uid, dest_ip,
917                                      imp->imp_obd->obd_name,
918                                      buf, sizeof(buf),
919                                      gss_send_secinit_rpc);
920         LASSERT(rc != 0);
921         if (rc < 0)
922                 goto err_out;
923
924         obj.data = buf;
925         obj.len = rc;
926
927         gsec = container_of(cred->pc_sec, struct gss_sec, gs_base);
928         mech = gsec->gs_mech;
929         LASSERT(mech);
930         rc = gss_parse_init_downcall(mech, &obj, &ctx, &vcred, &dest_ip,
931                                      &gss_err);
932         if (rc || gss_err) {
933                 CERROR("parse init downcall: rpc %d, gss 0x%x\n", rc, gss_err);
934                 if (rc != -ERESTART || gss_err != 0)
935                         set_bit(PTLRPC_CRED_ERROR_BIT, &cred->pc_flags);
936                 if (rc == 0)
937                         rc = -EPERM;
938                 goto err_out;
939         }
940
941         LASSERT(ctx);
942         gss_cred_set_ctx(cred, ctx);
943         LASSERT(gss_cred_is_uptodate_ctx(cred));
944
945         return 0;
946 err_out:
947         set_bit(PTLRPC_CRED_DEAD_BIT, &cred->pc_flags);
948         return rc;
949 }
950 #endif
951
952 static int gss_cred_match(struct ptlrpc_cred *cred,
953                           struct vfs_cred *vcred)
954 {
955         RETURN(cred->pc_pag == vcred->vc_pag);
956 }
957
958 static int gss_cred_sign(struct ptlrpc_cred *cred,
959                          struct ptlrpc_request *req)
960 {
961         struct gss_cred         *gcred;
962         struct gss_cl_ctx       *ctx;
963         rawobj_t                 lmsg, mic;
964         __u32                   *vp, *vpsave, vlen, seclen;
965         __u32                    seqnum, major, rc = 0;
966         ENTRY;
967
968         LASSERT(req->rq_reqbuf);
969         LASSERT(req->rq_cred == cred);
970
971         gcred = container_of(cred, struct gss_cred, gc_base);
972         ctx = gss_cred_get_ctx(cred);
973         if (!ctx) {
974                 CERROR("cred %p("LPU64"/%u) invalidated?\n",
975                         cred, cred->pc_pag, cred->pc_uid);
976                 RETURN(-EPERM);
977         }
978
979         lmsg.len = req->rq_reqlen;
980         lmsg.data = (__u8 *) req->rq_reqmsg;
981
982         vp = (__u32 *) (lmsg.data + lmsg.len);
983         vlen = req->rq_reqbuf_len - sizeof(struct ptlrpcs_wire_hdr) -
984                lmsg.len;
985         seclen = vlen;
986
987         if (vlen < 6 * 4 + size_round4(ctx->gc_wire_ctx.len)) {
988                 CERROR("vlen %d, need %d\n",
989                         vlen, 6 * 4 + size_round4(ctx->gc_wire_ctx.len));
990                 rc = -EIO;
991                 goto out;
992         }
993
994         spin_lock(&ctx->gc_seq_lock);
995         seqnum = ctx->gc_seq++;
996         spin_unlock(&ctx->gc_seq_lock);
997
998         *vp++ = cpu_to_le32(PTLRPC_SEC_GSS_VERSION);    /* version */
999         *vp++ = cpu_to_le32(PTLRPCS_FLVR_KRB5I);        /* subflavor */
1000         *vp++ = cpu_to_le32(ctx->gc_proc);              /* proc */
1001         *vp++ = cpu_to_le32(seqnum);                    /* seq */
1002         *vp++ = cpu_to_le32(PTLRPCS_GSS_SVC_INTEGRITY); /* service */
1003         vlen -= 5 * 4;
1004
1005         if (rawobj_serialize(&ctx->gc_wire_ctx, &vp, &vlen)) {
1006                 rc = -EIO;
1007                 goto out;
1008         }
1009         CDEBUG(D_SEC, "encoded wire_ctx length %d\n", ctx->gc_wire_ctx.len);
1010
1011         vpsave = vp++;  /* reserve for size */
1012         vlen -= 4;
1013
1014         mic.len = vlen;
1015         mic.data = (unsigned char *)vp;
1016
1017         CDEBUG(D_SEC, "reqbuf at %p, lmsg at %p, len %d, mic at %p, len %d\n",
1018                req->rq_reqbuf, lmsg.data, lmsg.len, mic.data, mic.len);
1019         major = kgss_get_mic(ctx->gc_gss_ctx, GSS_C_QOP_DEFAULT, &lmsg, &mic);
1020         if (major) {
1021                 CERROR("cred %p: req %p compute mic error, major %x\n",
1022                        cred, req, major);
1023                 rc = -EACCES;
1024                 goto out;
1025         }
1026
1027         *vpsave = cpu_to_le32(mic.len);
1028         
1029         seclen = seclen - vlen + mic.len;
1030         buf_to_sec_hdr(req->rq_reqbuf)->sec_len = cpu_to_le32(seclen);
1031         req->rq_reqdata_len += size_round(seclen);
1032         CDEBUG(D_SEC, "msg size %d, checksum size %d, total sec size %d\n",
1033                lmsg.len, mic.len, seclen);
1034 out:
1035         gss_put_ctx(ctx);
1036         RETURN(rc);
1037 }
1038
1039 static int gss_cred_verify(struct ptlrpc_cred *cred,
1040                            struct ptlrpc_request *req)
1041 {
1042         struct gss_cred        *gcred;
1043         struct gss_cl_ctx      *ctx;
1044         struct ptlrpcs_wire_hdr *sec_hdr;
1045         rawobj_t                lmsg, mic;
1046         __u32                   *vp, vlen, subflavor, proc, seq, svc;
1047         __u32                   major, minor, rc;
1048         ENTRY;
1049
1050         LASSERT(req->rq_repbuf);
1051         LASSERT(req->rq_cred == cred);
1052
1053         sec_hdr = buf_to_sec_hdr(req->rq_repbuf);
1054         vp = (__u32 *) (req->rq_repbuf + sizeof(*sec_hdr) + sec_hdr->msg_len);
1055         vlen = sec_hdr->sec_len;
1056
1057         if (vlen < 7 * 4) {
1058                 CERROR("reply sec size %u too small\n", vlen);
1059                 RETURN(-EPROTO);
1060         }
1061
1062         if (*vp++ != cpu_to_le32(PTLRPC_SEC_GSS_VERSION)) {
1063                 CERROR("reply have different gss version\n");
1064                 RETURN(-EPROTO);
1065         }
1066         subflavor = le32_to_cpu(*vp++);
1067         proc = le32_to_cpu(*vp++);
1068         vlen -= 3 * 4;
1069
1070         switch (proc) {
1071         case PTLRPCS_GSS_PROC_DATA:
1072                 seq = le32_to_cpu(*vp++);
1073                 svc = le32_to_cpu(*vp++);
1074                 if (svc != PTLRPCS_GSS_SVC_INTEGRITY) {
1075                         CERROR("Unknown svc %d\n", svc);
1076                         RETURN(-EPROTO);
1077                 }
1078                 if (*vp++ != 0) {
1079                         CERROR("Unexpected ctx handle\n");
1080                         RETURN(-EPROTO);
1081                 }
1082                 mic.len = le32_to_cpu(*vp++);
1083                 vlen -= 4 * 4;
1084                 if (vlen < mic.len) {
1085                         CERROR("vlen %d, mic.len %d\n", vlen, mic.len);
1086                         RETURN(-EINVAL);
1087                 }
1088                 mic.data = (unsigned char *)vp;
1089
1090                 gcred = container_of(cred, struct gss_cred, gc_base);
1091                 ctx = gss_cred_get_ctx(cred);
1092                 LASSERT(ctx);
1093
1094                 lmsg.len = sec_hdr->msg_len;
1095                 lmsg.data = (__u8 *) buf_to_lustre_msg(req->rq_repbuf);
1096
1097                 major = kgss_verify_mic(ctx->gc_gss_ctx, &lmsg, &mic, NULL);
1098                 if (major != GSS_S_COMPLETE) {
1099                         CERROR("cred %p: req %p verify mic error: major %x\n",
1100                                cred, req, major);
1101
1102                         if (major == GSS_S_CREDENTIALS_EXPIRED ||
1103                             major == GSS_S_CONTEXT_EXPIRED) {
1104                                 ptlrpcs_cred_expire(cred);
1105                                 req->rq_ptlrpcs_restart = 1;
1106                                 rc = 0;
1107                         } else
1108                                 rc = -EINVAL;
1109
1110                         GOTO(proc_data_out, rc);
1111                 }
1112
1113                 req->rq_repmsg = (struct lustre_msg *) lmsg.data;
1114                 req->rq_replen = lmsg.len;
1115
1116                 /* here we could check the seq number is the same one
1117                  * we sent to server. but portals has prevent us from
1118                  * replay attack, so maybe we don't need check it again.
1119                  */
1120                 rc = 0;
1121 proc_data_out:
1122                 gss_put_ctx(ctx);
1123                 break;
1124         case PTLRPCS_GSS_PROC_ERR:
1125                 major = le32_to_cpu(*vp++);
1126                 minor = le32_to_cpu(*vp++);
1127                 /* server return NO_CONTEXT might be caused by context expire
1128                  * or server reboot/failover. we refresh the cred transparently
1129                  * to upper layer.
1130                  * In some cases, our gss handle is possible to be incidentally
1131                  * identical to another handle since the handle itself is not
1132                  * fully random. In krb5 case, the GSS_S_BAD_SIG will be
1133                  * returned, maybe other gss error for other mechanism. Here we
1134                  * only consider krb5 mech (FIXME) and try to establish new
1135                  * context.
1136                  */
1137                 if (major == GSS_S_NO_CONTEXT ||
1138                     major == GSS_S_BAD_SIG) {
1139                         CWARN("req %p: server report cred %p %s, expired?\n",
1140                                req, cred, (major == GSS_S_NO_CONTEXT) ?
1141                                            "NO_CONTEXT" : "BAD_SIG");
1142
1143                         ptlrpcs_cred_expire(cred);
1144                         req->rq_ptlrpcs_restart = 1;
1145                         rc = 0;
1146                 } else {
1147                         CERROR("req %p: unrecognized gss error (%x/%x)\n",
1148                                 req, major, minor);
1149                         rc = -EACCES;
1150                 }
1151                 break;
1152         default:
1153                 CERROR("unknown gss proc %d\n", proc);
1154                 rc = -EPROTO;
1155         }
1156
1157         RETURN(rc);
1158 }
1159
1160 static int gss_cred_seal(struct ptlrpc_cred *cred,
1161                          struct ptlrpc_request *req)
1162 {
1163         struct gss_cred         *gcred;
1164         struct gss_cl_ctx       *ctx;
1165         struct ptlrpcs_wire_hdr *sec_hdr;
1166         rawobj_buf_t             msg_buf;
1167         rawobj_t                 cipher_buf;
1168         __u32                   *vp, *vpsave, vlen, seclen;
1169         __u32                    major, seqnum, rc = 0;
1170         ENTRY;
1171
1172         LASSERT(req->rq_reqbuf);
1173         LASSERT(req->rq_cred == cred);
1174
1175         gcred = container_of(cred, struct gss_cred, gc_base);
1176         ctx = gss_cred_get_ctx(cred);
1177         if (!ctx) {
1178                 CERROR("cred %p("LPU64"/%u) invalidated?\n",
1179                         cred, cred->pc_pag, cred->pc_uid);
1180                 RETURN(-EPERM);
1181         }
1182
1183         vp = (__u32 *) (req->rq_reqbuf + sizeof(*sec_hdr));
1184         vlen = req->rq_reqbuf_len - sizeof(*sec_hdr);
1185         seclen = vlen;
1186
1187         if (vlen < 6 * 4 + size_round4(ctx->gc_wire_ctx.len)) {
1188                 CERROR("vlen %d, need %d\n",
1189                         vlen, 6 * 4 + size_round4(ctx->gc_wire_ctx.len));
1190                 rc = -EIO;
1191                 goto out;
1192         }
1193
1194         spin_lock(&ctx->gc_seq_lock);
1195         seqnum = ctx->gc_seq++;
1196         spin_unlock(&ctx->gc_seq_lock);
1197
1198         *vp++ = cpu_to_le32(PTLRPC_SEC_GSS_VERSION);    /* version */
1199         *vp++ = cpu_to_le32(PTLRPCS_FLVR_KRB5P);        /* subflavor */
1200         *vp++ = cpu_to_le32(ctx->gc_proc);              /* proc */
1201         *vp++ = cpu_to_le32(seqnum);                    /* seq */
1202         *vp++ = cpu_to_le32(PTLRPCS_GSS_SVC_PRIVACY);   /* service */
1203         vlen -= 5 * 4;
1204
1205         if (rawobj_serialize(&ctx->gc_wire_ctx, &vp, &vlen)) {
1206                 rc = -EIO;
1207                 goto out;
1208         }
1209         CDEBUG(D_SEC, "encoded wire_ctx length %d\n", ctx->gc_wire_ctx.len);
1210
1211         vpsave = vp++;  /* reserve for size */
1212         vlen -= 4;
1213
1214         msg_buf.buf = (__u8 *) req->rq_reqmsg - GSS_PRIVBUF_PREFIX_LEN;
1215         msg_buf.buflen = req->rq_reqlen + GSS_PRIVBUF_PREFIX_LEN +
1216                                           GSS_PRIVBUF_SUFFIX_LEN;
1217         msg_buf.dataoff = GSS_PRIVBUF_PREFIX_LEN;
1218         msg_buf.datalen = req->rq_reqlen;
1219
1220         cipher_buf.data = (__u8 *) vp;
1221         cipher_buf.len = vlen;
1222
1223         major = kgss_wrap(ctx->gc_gss_ctx, GSS_C_QOP_DEFAULT,
1224                           &msg_buf, &cipher_buf);
1225         if (major) {
1226                 CERROR("cred %p: error wrap: major 0x%x\n", cred, major);
1227                 GOTO(out, rc = -EINVAL);
1228         }
1229
1230         *vpsave = cpu_to_le32(cipher_buf.len);
1231
1232         seclen = seclen - vlen + cipher_buf.len;
1233         sec_hdr = buf_to_sec_hdr(req->rq_reqbuf);
1234         sec_hdr->sec_len = cpu_to_le32(seclen);
1235         req->rq_reqdata_len += size_round(seclen);
1236
1237         CDEBUG(D_SEC, "msg size %d, total sec size %d\n",
1238                req->rq_reqlen, seclen);
1239 out:
1240         gss_put_ctx(ctx);
1241         RETURN(rc);
1242 }
1243
1244 static int gss_cred_unseal(struct ptlrpc_cred *cred,
1245                            struct ptlrpc_request *req)
1246 {
1247         struct gss_cred        *gcred;
1248         struct gss_cl_ctx      *ctx;
1249         struct ptlrpcs_wire_hdr *sec_hdr;
1250         rawobj_t                cipher_text, plain_text;
1251         __u32                   *vp, vlen, subflavor, proc, seq, svc;
1252         __u32                   major, rc;
1253         ENTRY;
1254
1255         LASSERT(req->rq_repbuf);
1256         LASSERT(req->rq_cred == cred);
1257
1258         sec_hdr = buf_to_sec_hdr(req->rq_repbuf);
1259         if (sec_hdr->msg_len != 0) {
1260                 CERROR("unexpected msg_len %u\n", sec_hdr->msg_len);
1261                 RETURN(-EPROTO);
1262         }
1263
1264         vp = (__u32 *) (req->rq_repbuf + sizeof(*sec_hdr));
1265         vlen = sec_hdr->sec_len;
1266
1267         if (vlen < 7 * 4) {
1268                 CERROR("reply sec size %u too small\n", vlen);
1269                 RETURN(-EPROTO);
1270         }
1271
1272         if (*vp++ != cpu_to_le32(PTLRPC_SEC_GSS_VERSION)) {
1273                 CERROR("reply have different gss version\n");
1274                 RETURN(-EPROTO);
1275         }
1276         subflavor = le32_to_cpu(*vp++);
1277         proc = le32_to_cpu(*vp++);
1278         seq = le32_to_cpu(*vp++);
1279         svc = le32_to_cpu(*vp++);
1280         vlen -= 5 * 4;
1281
1282         switch (proc) {
1283         case PTLRPCS_GSS_PROC_DATA:
1284                 if (svc != PTLRPCS_GSS_SVC_PRIVACY) {
1285                         CERROR("Unknown svc %d\n", svc);
1286                         RETURN(-EPROTO);
1287                 }
1288                 if (*vp++ != 0) {
1289                         CERROR("Unexpected ctx handle\n");
1290                         RETURN(-EPROTO);
1291                 }
1292                 vlen -= 4;
1293
1294                 cipher_text.len = le32_to_cpu(*vp++);
1295                 cipher_text.data = (__u8 *) vp;
1296                 vlen -= 4;
1297
1298                 if (vlen < cipher_text.len) {
1299                         CERROR("cipher text to be %u while buf only %u\n",
1300                                 cipher_text.len, vlen);
1301                         RETURN(-EPROTO);
1302                 }
1303
1304                 plain_text = cipher_text;
1305
1306                 gcred = container_of(cred, struct gss_cred, gc_base);
1307                 ctx = gss_cred_get_ctx(cred);
1308                 LASSERT(ctx);
1309
1310                 major = kgss_unwrap(ctx->gc_gss_ctx, GSS_C_QOP_DEFAULT,
1311                                     &cipher_text, &plain_text);
1312                 if (major) {
1313                         CERROR("cred %p: error unwrap: major 0x%x\n",
1314                                cred, major);
1315
1316                         if (major == GSS_S_CREDENTIALS_EXPIRED ||
1317                             major == GSS_S_CONTEXT_EXPIRED) {
1318                                 ptlrpcs_cred_expire(cred);
1319                                 req->rq_ptlrpcs_restart = 1;
1320                                 rc = 0;
1321                         } else
1322                                 rc = -EINVAL;
1323
1324                         GOTO(proc_out, rc);
1325                 }
1326
1327                 req->rq_repmsg = (struct lustre_msg *) vp;
1328                 req->rq_replen = plain_text.len;
1329
1330                 rc = 0;
1331 proc_out:
1332                 gss_put_ctx(ctx);
1333                 break;
1334         default:
1335                 CERROR("unknown gss proc %d\n", proc);
1336                 rc = -EPROTO;
1337         }
1338
1339         RETURN(rc);
1340 }
1341
1342 static void destroy_gss_context(struct ptlrpc_cred *cred)
1343 {
1344         struct ptlrpcs_wire_hdr *hdr;
1345         struct lustre_msg       *lmsg;
1346         struct gss_cred         *gcred;
1347         struct ptlrpc_request    req;
1348         struct obd_import       *imp;
1349         __u32                   *vp, lmsg_size;
1350         struct ptlrpc_request   *raw_req = NULL;
1351         const int                repbuf_len = 256;
1352         char                    *repbuf;
1353         int                      replen, rc;
1354         ENTRY;
1355
1356         imp = cred->pc_sec->ps_import;
1357         LASSERT(imp);
1358
1359         if (test_bit(PTLRPC_CRED_ERROR_BIT, &cred->pc_flags) ||
1360             !test_bit(PTLRPC_CRED_UPTODATE_BIT, &cred->pc_flags)) {
1361                 CDEBUG(D_SEC, "Destroy dead cred %p(%u@%s)\n",
1362                        cred, cred->pc_uid, imp->imp_target_uuid.uuid);
1363                 EXIT;
1364                 return;
1365         }
1366
1367         might_sleep();
1368
1369         /* cred's refcount is 0, steal one */
1370         atomic_inc(&cred->pc_refcount);
1371
1372         gcred = container_of(cred, struct gss_cred, gc_base);
1373         gcred->gc_ctx->gc_proc = PTLRPCS_GSS_PROC_DESTROY;
1374
1375         CDEBUG(D_SEC, "client destroy gss cred %p(%u@%s)\n",
1376                gcred, cred->pc_uid, imp->imp_target_uuid.uuid);
1377
1378         lmsg_size = lustre_msg_size(0, NULL);
1379         req.rq_req_secflvr = cred->pc_sec->ps_flavor;
1380         req.rq_cred = cred;
1381         req.rq_reqbuf_len = sizeof(*hdr) + lmsg_size +
1382                             ptlrpcs_est_req_payload(&req, lmsg_size);
1383
1384         OBD_ALLOC(req.rq_reqbuf, req.rq_reqbuf_len);
1385         if (!req.rq_reqbuf) {
1386                 CERROR("Fail to alloc reqbuf, cancel anyway\n");
1387                 atomic_dec(&cred->pc_refcount);
1388                 EXIT;
1389                 return;
1390         }
1391
1392         /* wire hdr */
1393         hdr = buf_to_sec_hdr(req.rq_reqbuf);
1394         hdr->flavor  = cpu_to_le32(PTLRPCS_FLVR_GSS_AUTH);
1395         hdr->msg_len = cpu_to_le32(lmsg_size);
1396         hdr->sec_len = cpu_to_le32(0);
1397
1398         /* lustre message */
1399         lmsg = buf_to_lustre_msg(req.rq_reqbuf);
1400         lustre_init_msg(lmsg, 0, NULL, NULL);
1401         lmsg->handle   = imp->imp_remote_handle;
1402         lmsg->type     = PTL_RPC_MSG_REQUEST;
1403         lmsg->opc      = SEC_FINI;
1404         lmsg->flags    = 0;
1405         lmsg->conn_cnt = imp->imp_conn_cnt;
1406         /* add this for randomize */
1407         get_random_bytes(&lmsg->last_xid, sizeof(lmsg->last_xid));
1408         get_random_bytes(&lmsg->transno, sizeof(lmsg->transno));
1409
1410         vp = (__u32 *) req.rq_reqbuf;
1411
1412         req.rq_cred = cred;
1413         req.rq_reqmsg = buf_to_lustre_msg(req.rq_reqbuf);
1414         req.rq_reqlen = lmsg_size;
1415         req.rq_reqdata_len = sizeof(*hdr) + lmsg_size;
1416
1417         if (gss_cred_sign(cred, &req)) {
1418                 CERROR("failed to sign, cancel anyway\n");
1419                 atomic_dec(&cred->pc_refcount);
1420                 goto exit;
1421         }
1422         atomic_dec(&cred->pc_refcount);
1423
1424         OBD_ALLOC(repbuf, repbuf_len);
1425         if (!repbuf)
1426                 goto exit;
1427
1428         raw_req = ptl_do_rawrpc(imp, req.rq_reqbuf, req.rq_reqbuf_len,
1429                                 req.rq_reqdata_len, repbuf, repbuf_len, &replen,
1430                                 SECFINI_RPC_TIMEOUT, &rc);
1431         if (!raw_req)
1432                 OBD_FREE(repbuf, repbuf_len);
1433
1434 exit:
1435         if (raw_req == NULL)
1436                 OBD_FREE(req.rq_reqbuf, req.rq_reqbuf_len);
1437         else
1438                 rawrpc_req_finished(raw_req);
1439         EXIT;
1440 }
1441
1442 static void gss_cred_destroy(struct ptlrpc_cred *cred)
1443 {
1444         struct gss_cred *gcred;
1445         ENTRY;
1446
1447         LASSERT(cred);
1448         LASSERT(!atomic_read(&cred->pc_refcount));
1449
1450         gcred = container_of(cred, struct gss_cred, gc_base);
1451         if (gcred->gc_ctx) {
1452                 destroy_gss_context(cred);
1453                 gss_put_ctx(gcred->gc_ctx);
1454         }
1455
1456         CDEBUG(D_SEC, "sec.gss %p: destroy cred %p\n", cred->pc_sec, gcred);
1457
1458         OBD_FREE(gcred, sizeof(*gcred));
1459         EXIT;
1460 }
1461
1462 static struct ptlrpc_credops gss_credops = {
1463         .refresh        = gss_cred_refresh,
1464         .match          = gss_cred_match,
1465         .sign           = gss_cred_sign,
1466         .verify         = gss_cred_verify,
1467         .seal           = gss_cred_seal,
1468         .unseal         = gss_cred_unseal,
1469         .destroy        = gss_cred_destroy,
1470 };
1471
1472 #ifdef __KERNEL__
1473 /*******************************************
1474  * rpc_pipe APIs                           *
1475  *******************************************/
1476 static ssize_t
1477 gss_pipe_upcall(struct file *filp, struct rpc_pipe_msg *msg,
1478                 char *dst, size_t buflen)
1479 {
1480         char *data = (char *)msg->data + msg->copied;
1481         ssize_t mlen = msg->len;
1482         ssize_t left;
1483         ENTRY;
1484
1485         if (mlen > buflen)
1486                 mlen = buflen;
1487         left = copy_to_user(dst, data, mlen);
1488         if (left < 0) {
1489                 msg->errno = left;
1490                 RETURN(left);
1491         }
1492         mlen -= left;
1493         msg->copied += mlen;
1494         msg->errno = 0;
1495         RETURN(mlen);
1496 }
1497
1498 static ssize_t
1499 gss_pipe_downcall(struct file *filp, const char *src, size_t mlen)
1500 {
1501         char *buf;
1502         const int bufsize = 1024;
1503         rawobj_t obj;
1504         struct inode *inode = filp->f_dentry->d_inode;
1505         struct rpc_inode *rpci = RPC_I(inode);
1506         struct obd_import *import;
1507         struct ptlrpc_sec *sec;
1508         struct gss_sec *gsec;
1509         char *obdname;
1510         struct gss_api_mech *mech;
1511         struct vfs_cred vcred = { 0 };
1512         struct ptlrpc_cred *cred;
1513         struct gss_upcall_msg *gss_msg;
1514         struct gss_upcall_msg_data gmd = { 0 };
1515         struct gss_cl_ctx *ctx = NULL;
1516         ssize_t left;
1517         int err, gss_err;
1518         ENTRY;
1519
1520         if (mlen > bufsize) {
1521                 CERROR("mlen %ld > bufsize %d\n", (long)mlen, bufsize);
1522                 RETURN(-ENOSPC);
1523         }
1524
1525         OBD_ALLOC(buf, bufsize);
1526         if (!buf) {
1527                 CERROR("alloc mem failed\n");
1528                 RETURN(-ENOMEM);
1529         }
1530
1531         left = copy_from_user(buf, src, mlen);
1532         if (left)
1533                 GOTO(err_free, err = -EFAULT);
1534
1535         obj.data = (unsigned char *)buf;
1536         obj.len = mlen;
1537
1538         LASSERT(rpci->private);
1539         gsec = (struct gss_sec *)rpci->private;
1540         sec = &gsec->gs_base;
1541         LASSERT(sec->ps_import);
1542         import = class_import_get(sec->ps_import);
1543         LASSERT(import->imp_obd);
1544         obdname = import->imp_obd->obd_name;
1545         mech = gsec->gs_mech;
1546
1547         err = gss_parse_init_downcall(mech, &obj, &ctx, &gmd, &gss_err);
1548         if (err)
1549                 CERROR("parse init downcall err %d\n", err);
1550
1551         vcred.vc_uid = gmd.gum_uid;
1552         vcred.vc_pag = vcred.vc_uid; /* FIXME */
1553
1554         cred = ptlrpcs_cred_lookup(sec, &vcred);
1555         if (!cred) {
1556                 CWARN("didn't find cred for uid %u\n", vcred.vc_uid);
1557                 GOTO(err, err = -EINVAL);
1558         }
1559
1560         if (err || gss_err) {
1561                 set_bit(PTLRPC_CRED_DEAD_BIT, &cred->pc_flags);
1562                 if (err != -ERESTART || gss_err != 0)
1563                         set_bit(PTLRPC_CRED_ERROR_BIT, &cred->pc_flags);
1564                 CERROR("cred %p: rpc err %d, gss err 0x%x, fatal %d\n",
1565                        cred, err, gss_err,
1566                        (test_bit(PTLRPC_CRED_ERROR_BIT, &cred->pc_flags) != 0));
1567         } else {
1568                 CDEBUG(D_SEC, "get initial ctx:\n");
1569                 gss_cred_set_ctx(cred, ctx);
1570         }
1571
1572         spin_lock(&gsec->gs_lock);
1573         gss_msg = gss_find_upcall(gsec, obdname, &gmd);
1574         if (gss_msg) {
1575                 gss_unhash_msg_nolock(gss_msg);
1576                 spin_unlock(&gsec->gs_lock);
1577                 gss_release_msg(gss_msg);
1578         } else
1579                 spin_unlock(&gsec->gs_lock);
1580
1581         ptlrpcs_cred_put(cred, 1);
1582         class_import_put(import);
1583         OBD_FREE(buf, bufsize);
1584         RETURN(mlen);
1585 err:
1586         if (ctx)
1587                 gss_destroy_ctx(ctx);
1588         class_import_put(import);
1589 err_free:
1590         OBD_FREE(buf, bufsize);
1591         CDEBUG(D_SEC, "gss_pipe_downcall returning %d\n", err);
1592         RETURN(err);
1593 }
1594
1595 static
1596 void gss_pipe_destroy_msg(struct rpc_pipe_msg *msg)
1597 {
1598         struct gss_upcall_msg *gmsg;
1599         static unsigned long ratelimit;
1600         ENTRY;
1601
1602         LASSERT(list_empty(&msg->list));
1603
1604         if (msg->errno >= 0) {
1605                 EXIT;
1606                 return;
1607         }
1608
1609         gmsg = container_of(msg, struct gss_upcall_msg, gum_base);
1610         CDEBUG(D_SEC, "destroy gmsg %p\n", gmsg);
1611         LASSERT(atomic_read(&gmsg->gum_refcount) > 0);
1612         atomic_inc(&gmsg->gum_refcount);
1613         gss_unhash_msg(gmsg);
1614         if (msg->errno == -ETIMEDOUT || msg->errno == -EPIPE) {
1615                 unsigned long now = get_seconds();
1616                 if (time_after(now, ratelimit)) {
1617                         CWARN("sec.gss upcall timed out.\n"
1618                               "Please check user daemon is running!\n");
1619                         ratelimit = now + 15;
1620                 }
1621         }
1622         gss_release_msg(gmsg);
1623         EXIT;
1624 }
1625
1626 static
1627 void gss_pipe_release(struct inode *inode)
1628 {
1629         struct rpc_inode *rpci = RPC_I(inode);
1630         struct ptlrpc_sec *sec;
1631         struct gss_sec *gsec;
1632         ENTRY;
1633
1634         gsec = (struct gss_sec *)rpci->private;
1635         sec = &gsec->gs_base;
1636         spin_lock(&gsec->gs_lock);
1637         while (!list_empty(&gsec->gs_upcalls)) {
1638                 struct gss_upcall_msg *gmsg;
1639
1640                 gmsg = list_entry(gsec->gs_upcalls.next,
1641                                   struct gss_upcall_msg, gum_list);
1642                 LASSERT(list_empty(&gmsg->gum_base.list));
1643                 gmsg->gum_base.errno = -EPIPE;
1644                 atomic_inc(&gmsg->gum_refcount);
1645                 gss_unhash_msg_nolock(gmsg);
1646                 gss_release_msg(gmsg);
1647         }
1648         spin_unlock(&gsec->gs_lock);
1649         EXIT;
1650 }
1651
1652 static struct rpc_pipe_ops gss_upcall_ops = {
1653         .upcall         = gss_pipe_upcall,
1654         .downcall       = gss_pipe_downcall,
1655         .destroy_msg    = gss_pipe_destroy_msg,
1656         .release_pipe   = gss_pipe_release,
1657 };
1658 #endif /* __KERNEL__ */
1659
1660 /*********************************************
1661  * GSS security APIs                         *
1662  *********************************************/
1663
1664 static
1665 struct ptlrpc_sec* gss_create_sec(__u32 flavor,
1666                                   const char *pipe_dir,
1667                                   void *pipe_data)
1668 {
1669         struct gss_sec *gsec;
1670         struct ptlrpc_sec *sec;
1671 #ifdef __KERNEL__
1672         char *pos;
1673         int   pipepath_len;
1674         uid_t save_uid;
1675 #endif
1676         ENTRY;
1677
1678         LASSERT(SEC_FLAVOR_MAJOR(flavor) == PTLRPCS_FLVR_MAJOR_GSS);
1679
1680         OBD_ALLOC(gsec, sizeof(*gsec));
1681         if (!gsec) {
1682                 CERROR("can't alloc gsec\n");
1683                 RETURN(NULL);
1684         }
1685
1686         gsec->gs_mech = kgss_subflavor_to_mech(SEC_FLAVOR_SUB(flavor));
1687         if (!gsec->gs_mech) {
1688                 CERROR("subflavor 0x%x not found\n", flavor);
1689                 goto err_free;
1690         }
1691
1692         /* initialize gss sec */
1693 #ifdef __KERNEL__
1694         INIT_LIST_HEAD(&gsec->gs_upcalls);
1695         spin_lock_init(&gsec->gs_lock);
1696
1697         pipepath_len = strlen(LUSTRE_PIPEDIR) + strlen(pipe_dir) +
1698                        strlen(gsec->gs_mech->gm_name) + 3;
1699         OBD_ALLOC(gsec->gs_pipepath, pipepath_len);
1700         if (!gsec->gs_pipepath)
1701                 goto err_mech_put;
1702
1703         /* pipe rpc require root permission */
1704         save_uid = current->fsuid;
1705         current->fsuid = 0;
1706
1707         sprintf(gsec->gs_pipepath, LUSTRE_PIPEDIR"/%s", pipe_dir);
1708         if (IS_ERR(rpc_mkdir(gsec->gs_pipepath, NULL))) {
1709                 CERROR("can't make pipedir %s\n", gsec->gs_pipepath);
1710                 goto err_free_path;
1711         }
1712
1713         sprintf(gsec->gs_pipepath, LUSTRE_PIPEDIR"/%s/%s", pipe_dir,
1714                 gsec->gs_mech->gm_name); 
1715         gsec->gs_depipe = rpc_mkpipe(gsec->gs_pipepath, gsec,
1716                                      &gss_upcall_ops, RPC_PIPE_WAIT_FOR_OPEN);
1717         if (IS_ERR(gsec->gs_depipe)) {
1718                 CERROR("failed to make rpc_pipe %s: %ld\n",
1719                         gsec->gs_pipepath, PTR_ERR(gsec->gs_depipe));
1720                 goto err_rmdir;
1721         }
1722         CDEBUG(D_SEC, "gss sec %p, pipe path %s\n", gsec, gsec->gs_pipepath);
1723 #endif
1724
1725         sec = &gsec->gs_base;
1726         sec->ps_expire = GSS_CREDCACHE_EXPIRE;
1727         sec->ps_nextgc = get_seconds() + sec->ps_expire;
1728         sec->ps_flags = 0;
1729
1730         current->fsuid = save_uid;
1731
1732         CDEBUG(D_SEC, "Create sec.gss %p\n", gsec);
1733         RETURN(sec);
1734
1735 #ifdef __KERNEL__
1736 err_rmdir:
1737         pos = strrchr(gsec->gs_pipepath, '/');
1738         LASSERT(pos);
1739         *pos = 0;
1740         rpc_rmdir(gsec->gs_pipepath);
1741 err_free_path:
1742         current->fsuid = save_uid;
1743         OBD_FREE(gsec->gs_pipepath, pipepath_len);
1744 err_mech_put:
1745 #endif
1746         kgss_mech_put(gsec->gs_mech);
1747 err_free:
1748         OBD_FREE(gsec, sizeof(*gsec));
1749         RETURN(NULL);
1750 }
1751
1752 static
1753 void gss_destroy_sec(struct ptlrpc_sec *sec)
1754 {
1755         struct gss_sec *gsec;
1756 #ifdef __KERNEL__
1757         char *pos;
1758         int   pipepath_len;
1759 #endif
1760         ENTRY;
1761
1762         gsec = container_of(sec, struct gss_sec, gs_base);
1763         CDEBUG(D_SEC, "Destroy sec.gss %p\n", gsec);
1764
1765         LASSERT(gsec->gs_mech);
1766         LASSERT(!atomic_read(&sec->ps_refcount));
1767         LASSERT(!atomic_read(&sec->ps_credcount));
1768 #ifdef __KERNEL__
1769         pipepath_len = strlen(gsec->gs_pipepath) + 1;
1770         rpc_unlink(gsec->gs_pipepath);
1771         pos = strrchr(gsec->gs_pipepath, '/');
1772         LASSERT(pos);
1773         *pos = 0;
1774         rpc_rmdir(gsec->gs_pipepath);
1775         OBD_FREE(gsec->gs_pipepath, pipepath_len);
1776 #endif
1777
1778         kgss_mech_put(gsec->gs_mech);
1779         OBD_FREE(gsec, sizeof(*gsec));
1780         EXIT;
1781 }
1782
1783 static
1784 struct ptlrpc_cred * gss_create_cred(struct ptlrpc_sec *sec,
1785                                      struct vfs_cred *vcred)
1786 {
1787         struct gss_cred *gcred;
1788         struct ptlrpc_cred *cred;
1789         ENTRY;
1790
1791         OBD_ALLOC(gcred, sizeof(*gcred));
1792         if (!gcred)
1793                 RETURN(NULL);
1794
1795         cred = &gcred->gc_base;
1796         INIT_LIST_HEAD(&cred->pc_hash);
1797         atomic_set(&cred->pc_refcount, 0);
1798         cred->pc_sec = sec;
1799         cred->pc_ops = &gss_credops;
1800         cred->pc_expire = 0;
1801         cred->pc_flags = 0;
1802         cred->pc_pag = vcred->vc_pag;
1803         cred->pc_uid = vcred->vc_uid;
1804         CDEBUG(D_SEC, "create a gss cred at %p("LPU64"/%u)\n",
1805                cred, vcred->vc_pag, vcred->vc_uid);
1806
1807         RETURN(cred);
1808 }
1809
1810 static int gss_estimate_payload(struct ptlrpc_sec *sec,
1811                                 struct ptlrpc_request *req,
1812                                 int msgsize)
1813 {
1814         switch (SEC_FLAVOR_SVC(req->rq_req_secflvr)) {
1815         case PTLRPCS_SVC_AUTH:
1816                 return GSS_MAX_AUTH_PAYLOAD;
1817         case PTLRPCS_SVC_PRIV:
1818                 return size_round16(GSS_MAX_AUTH_PAYLOAD + msgsize +
1819                                     GSS_PRIVBUF_PREFIX_LEN +
1820                                     GSS_PRIVBUF_SUFFIX_LEN);
1821         default:
1822                 LBUG();
1823                 return 0;
1824         }
1825 }
1826
1827 static int gss_alloc_reqbuf(struct ptlrpc_sec *sec,
1828                             struct ptlrpc_request *req,
1829                             int lmsg_size)
1830 {
1831         int msg_payload, sec_payload;
1832         int privacy, rc;
1833         ENTRY;
1834
1835         /* In PRIVACY mode, lustre message is always 0 (already encoded into
1836          * security payload).
1837          */
1838         privacy = (SEC_FLAVOR_SVC(req->rq_req_secflvr) == PTLRPCS_SVC_PRIV);
1839         msg_payload = privacy ? 0 : lmsg_size;
1840         sec_payload = gss_estimate_payload(sec, req, lmsg_size);
1841
1842         rc = sec_alloc_reqbuf(sec, req, msg_payload, sec_payload);
1843         if (rc)
1844                 return rc;
1845
1846         if (privacy) {
1847                 int buflen = lmsg_size + GSS_PRIVBUF_PREFIX_LEN +
1848                              GSS_PRIVBUF_SUFFIX_LEN;
1849                 char *buf;
1850
1851                 OBD_ALLOC(buf, buflen);
1852                 if (!buf) {
1853                         CERROR("Fail to alloc %d\n", buflen);
1854                         sec_free_reqbuf(sec, req);
1855                         RETURN(-ENOMEM);
1856                 }
1857                 req->rq_reqmsg = (struct lustre_msg *)
1858                                         (buf + GSS_PRIVBUF_PREFIX_LEN);
1859         }
1860
1861         RETURN(0);
1862 }
1863
1864 static void gss_free_reqbuf(struct ptlrpc_sec *sec,
1865                             struct ptlrpc_request *req)
1866 {
1867         char *buf;
1868         int privacy;
1869         ENTRY;
1870
1871         LASSERT(req->rq_reqmsg);
1872         LASSERT(req->rq_reqlen);
1873
1874         privacy = SEC_FLAVOR_SVC(req->rq_req_secflvr) == PTLRPCS_SVC_PRIV;
1875         if (privacy) {
1876                 buf = (char *) req->rq_reqmsg - GSS_PRIVBUF_PREFIX_LEN;
1877                 LASSERT(buf < req->rq_reqbuf ||
1878                         buf >= req->rq_reqbuf + req->rq_reqbuf_len);
1879                 OBD_FREE(buf, req->rq_reqlen + GSS_PRIVBUF_PREFIX_LEN +
1880                               GSS_PRIVBUF_SUFFIX_LEN);
1881                 req->rq_reqmsg = NULL;
1882         }
1883
1884         sec_free_reqbuf(sec, req);
1885 }
1886
1887 static struct ptlrpc_secops gss_secops = {
1888         .create_sec             = gss_create_sec,
1889         .destroy_sec            = gss_destroy_sec,
1890         .create_cred            = gss_create_cred,
1891         .est_req_payload        = gss_estimate_payload,
1892         .est_rep_payload        = gss_estimate_payload,
1893         .alloc_reqbuf           = gss_alloc_reqbuf,
1894         .free_reqbuf            = gss_free_reqbuf,
1895 };
1896
1897 static struct ptlrpc_sec_type gss_type = {
1898         .pst_owner      = THIS_MODULE,
1899         .pst_name       = "sec.gss",
1900         .pst_inst       = ATOMIC_INIT(0),
1901         .pst_flavor     = PTLRPCS_FLVR_MAJOR_GSS,
1902         .pst_ops        = &gss_secops,
1903 };
1904
1905 extern int
1906 (*lustre_secinit_downcall_handler)(char *buffer, unsigned long count);
1907
1908 int __init ptlrpcs_gss_init(void)
1909 {
1910         int rc;
1911
1912         rc = ptlrpcs_register(&gss_type);
1913         if (rc)
1914                 return rc;
1915
1916 #ifdef __KERNEL__
1917         gss_svc_init();
1918
1919         rc = PTR_ERR(rpc_mkdir(LUSTRE_PIPEDIR, NULL));
1920         if (IS_ERR((void *)rc) && rc != -EEXIST) {
1921                 CERROR("fail to make rpcpipedir for lustre\n");
1922                 gss_svc_exit();
1923                 ptlrpcs_unregister(&gss_type);
1924                 return -1;
1925         }
1926         rc = 0;
1927 #else
1928 #endif
1929         rc = init_kerberos_module();
1930         if (rc) {
1931                 ptlrpcs_unregister(&gss_type);
1932         }
1933
1934         lustre_secinit_downcall_handler = gss_send_secinit_rpc;
1935
1936         return rc;
1937 }
1938
1939 #ifdef __KERNEL__
1940 static void __exit ptlrpcs_gss_exit(void)
1941 {
1942         lustre_secinit_downcall_handler = NULL;
1943
1944         cleanup_kerberos_module();
1945         rpc_rmdir(LUSTRE_PIPEDIR);
1946         gss_svc_exit();
1947         ptlrpcs_unregister(&gss_type);
1948 }
1949 #endif
1950
1951 MODULE_AUTHOR("Cluster File Systems, Inc. <info@clusterfs.com>");
1952 MODULE_DESCRIPTION("GSS Security module for Lustre");
1953 MODULE_LICENSE("GPL");
1954
1955 module_init(ptlrpcs_gss_init);
1956 module_exit(ptlrpcs_gss_exit);