Whamcloud - gitweb
adjust gss timeout valud, don't use fixed value.
[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         LASSERT(list_empty(&gmsg->gum_base.list));
434         OBD_FREE(gmsg, sizeof(*gmsg));
435         EXIT;
436 }
437
438 static void
439 gss_unhash_msg_nolock(struct gss_upcall_msg *gmsg)
440 {
441         ENTRY;
442         if (list_empty(&gmsg->gum_list)) {
443                 EXIT;
444                 return;
445         }
446
447         list_del_init(&gmsg->gum_list);
448         wake_up(&gmsg->gum_waitq);
449         atomic_dec(&gmsg->gum_refcount);
450         CDEBUG(D_SEC, "gmsg %p refcount now %d\n",
451                gmsg, atomic_read(&gmsg->gum_refcount));
452         LASSERT(atomic_read(&gmsg->gum_refcount) > 0);
453         EXIT;
454 }
455
456 static void
457 gss_unhash_msg(struct gss_upcall_msg *gmsg)
458 {
459         struct gss_sec *gsec = gmsg->gum_gsec;
460
461         spin_lock(&gsec->gs_lock);
462         gss_unhash_msg_nolock(gmsg);
463         spin_unlock(&gsec->gs_lock);
464 }
465
466 static
467 struct gss_upcall_msg * gss_find_upcall(struct gss_sec *gsec,
468                                         char *obdname,
469                                         struct gss_upcall_msg_data *gmd)
470 {
471         struct gss_upcall_msg *gmsg;
472         ENTRY;
473
474         list_for_each_entry(gmsg, &gsec->gs_upcalls, gum_list) {
475                 if (memcmp(&gmsg->gum_data, gmd, sizeof(*gmd)))
476                         continue;
477                 if (strcmp(gmsg->gum_obdname, obdname))
478                         continue;
479                 atomic_inc(&gmsg->gum_refcount);
480                 CDEBUG(D_SEC, "found gmsg at %p: obdname %s, uid %d, ref %d\n",
481                        gmsg, obdname, gmd->gum_uid,
482                        atomic_read(&gmsg->gum_refcount));
483                 RETURN(gmsg);
484         }
485         RETURN(NULL);
486 }
487
488 static void gss_init_upcall_msg(struct gss_upcall_msg *gmsg,
489                                 struct gss_sec *gsec, char *obdname,
490                                 struct gss_upcall_msg_data *gmd)
491 {
492         struct rpc_pipe_msg *rpcmsg;
493         ENTRY;
494
495         /* 2 refs: 1 for hash, 1 for current user */
496         init_waitqueue_head(&gmsg->gum_waitq);
497         list_add(&gmsg->gum_list, &gsec->gs_upcalls);
498         atomic_set(&gmsg->gum_refcount, 2);
499         gmsg->gum_gsec = gsec;
500         strncpy(gmsg->gum_obdname, obdname, sizeof(gmsg->gum_obdname));
501         memcpy(&gmsg->gum_data, gmd, sizeof(*gmd));
502
503         rpcmsg = &gmsg->gum_base;
504         rpcmsg->data = &gmsg->gum_data;
505         rpcmsg->len = sizeof(gmsg->gum_data);
506         EXIT;
507 }
508 #endif /* __KERNEL__ */
509
510 /********************************************
511  * gss cred manipulation helpers            *
512  ********************************************/
513 #if 0
514 static
515 int gss_cred_is_uptodate_ctx(struct ptlrpc_cred *cred)
516 {
517         struct gss_cred *gcred = container_of(cred, struct gss_cred, gc_base);
518         int res = 0;
519
520         read_lock(&gss_ctx_lock);
521         if (((cred->pc_flags & PTLRPC_CRED_FLAGS_MASK) ==
522              PTLRPC_CRED_UPTODATE) &&
523             gcred->gc_ctx)
524                 res = 1;
525         read_unlock(&gss_ctx_lock);
526         return res;
527 }
528 #endif
529
530 static inline
531 struct gss_cl_ctx * gss_get_ctx(struct gss_cl_ctx *ctx)
532 {
533         atomic_inc(&ctx->gc_refcount);
534         return ctx;
535 }
536
537 static
538 void gss_destroy_ctx(struct gss_cl_ctx *ctx)
539 {
540         ENTRY;
541
542         CDEBUG(D_SEC, "destroy cl_ctx %p\n", ctx);
543         if (ctx->gc_gss_ctx)
544                 kgss_delete_sec_context(&ctx->gc_gss_ctx);
545
546         if (ctx->gc_wire_ctx.len > 0) {
547                 OBD_FREE(ctx->gc_wire_ctx.data, ctx->gc_wire_ctx.len);
548                 ctx->gc_wire_ctx.len = 0;
549         }
550
551         OBD_FREE(ctx, sizeof(*ctx));
552 }
553
554 static
555 void gss_put_ctx(struct gss_cl_ctx *ctx)
556 {
557         if (atomic_dec_and_test(&ctx->gc_refcount))
558                 gss_destroy_ctx(ctx);
559 }
560
561 static
562 struct gss_cl_ctx *gss_cred_get_ctx(struct ptlrpc_cred *cred)
563 {
564         struct gss_cred *gcred = container_of(cred, struct gss_cred, gc_base);
565         struct gss_cl_ctx *ctx = NULL;
566
567         read_lock(&gss_ctx_lock);
568         if (gcred->gc_ctx)
569                 ctx = gss_get_ctx(gcred->gc_ctx);
570         read_unlock(&gss_ctx_lock);
571         return ctx;
572 }
573
574 static
575 void gss_cred_set_ctx(struct ptlrpc_cred *cred, struct gss_cl_ctx *ctx)
576 {
577         struct gss_cred *gcred = container_of(cred, struct gss_cred, gc_base);
578         struct gss_cl_ctx *old;
579         __u64 ctx_expiry;
580         ENTRY;
581
582         if (kgss_inquire_context(ctx->gc_gss_ctx, &ctx_expiry)) {
583                 CERROR("unable to get expire time\n");
584                 ctx_expiry = 1; /* make it expired now */
585         }
586         cred->pc_expire = (unsigned long) ctx_expiry;
587
588         write_lock(&gss_ctx_lock);
589         old = gcred->gc_ctx;
590         gcred->gc_ctx = ctx;
591         set_bit(PTLRPC_CRED_UPTODATE_BIT, &cred->pc_flags);
592         write_unlock(&gss_ctx_lock);
593         if (old)
594                 gss_put_ctx(old);
595
596         CDEBUG(D_SEC, "client refreshed gss cred %p(uid %u)\n",
597                cred, cred->pc_uid);
598         EXIT;
599 }
600
601 static int
602 simple_get_bytes(char **buf, __u32 *buflen, void *res, __u32 reslen)
603 {
604         if (*buflen < reslen) {
605                 CERROR("buflen %u < %u\n", *buflen, reslen);
606                 return -EINVAL;
607         }
608
609         memcpy(res, *buf, reslen);
610         *buf += reslen;
611         *buflen -= reslen;
612         return 0;
613 }
614
615 /* data passed down:
616  *  - uid
617  *  - timeout
618  *  - gc_win / error
619  *  - wire_ctx (rawobj)
620  *  - mech_ctx? (rawobj)
621  */
622 static
623 int gss_parse_init_downcall(struct gss_api_mech *gm, rawobj_t *buf,
624                             struct gss_cl_ctx **gc,
625                             struct gss_upcall_msg_data *gmd, int *gss_err)
626 {
627         char *p = (char *)buf->data;
628         struct gss_cl_ctx *ctx;
629         __u32 len = buf->len;
630         unsigned int timeout;
631         rawobj_t tmp_buf;
632         int err = -EPERM;
633         ENTRY;
634
635         *gc = NULL;
636         *gss_err = 0;
637
638         OBD_ALLOC(ctx, sizeof(*ctx));
639         if (!ctx)
640                 RETURN(-ENOMEM);
641
642         ctx->gc_proc = RPC_GSS_PROC_DATA;
643         ctx->gc_seq = 0;
644         spin_lock_init(&ctx->gc_seq_lock);
645         atomic_set(&ctx->gc_refcount,1);
646
647         if (simple_get_bytes(&p, &len, &gmd->gum_uid, sizeof(gmd->gum_uid)))
648                 goto err_free_ctx;
649         if (simple_get_bytes(&p, &len, &gmd->gum_svc, sizeof(gmd->gum_svc)))
650                 goto err_free_ctx;
651         if (simple_get_bytes(&p, &len, &gmd->gum_nal, sizeof(gmd->gum_nal)))
652                 goto err_free_ctx;
653         if (simple_get_bytes(&p, &len, &gmd->gum_netid, sizeof(gmd->gum_netid)))
654                 goto err_free_ctx;
655         if (simple_get_bytes(&p, &len, &gmd->gum_nid, sizeof(gmd->gum_nid)))
656                 goto err_free_ctx;
657         /* FIXME: discarded timeout for now */
658         if (simple_get_bytes(&p, &len, &timeout, sizeof(timeout)))
659                 goto err_free_ctx;
660         if (simple_get_bytes(&p, &len, &ctx->gc_win, sizeof(ctx->gc_win)))
661                 goto err_free_ctx;
662
663         /* lgssd signals an error by passing ctx->gc_win = 0: */
664         if (!ctx->gc_win) {
665                 /* in which case the next 2 int are:
666                  * - rpc error
667                  * - gss error
668                  */
669                 if (simple_get_bytes(&p, &len, &err, sizeof(err))) {
670                         err = -EPERM;
671                         goto err_free_ctx;
672                 }
673                 if (simple_get_bytes(&p, &len, gss_err, sizeof(*gss_err))) {
674                         err = -EPERM;
675                         goto err_free_ctx;
676                 }
677                 if (err == 0 && *gss_err == 0) {
678                         CERROR("no error passed from downcall\n");
679                         err = -EPERM;
680                 }
681                 goto err_free_ctx;
682         }
683
684         if (rawobj_extract_local(&tmp_buf, (__u32 **) ((void *)&p), &len))
685                 goto err_free_ctx;
686         if (rawobj_dup(&ctx->gc_wire_ctx, &tmp_buf)) {
687                 err = -ENOMEM;
688                 goto err_free_ctx;
689         }
690         if (rawobj_extract_local(&tmp_buf, (__u32 **) ((void *)&p), &len))
691                 goto err_free_wire_ctx;
692         if (len) {
693                 CERROR("unexpected trailing %u bytes\n", len);
694                 goto err_free_wire_ctx;
695         }
696         if (kgss_import_sec_context(&tmp_buf, gm, &ctx->gc_gss_ctx))
697                 goto err_free_wire_ctx;
698
699         *gc = ctx;
700         RETURN(0);
701
702 err_free_wire_ctx:
703         if (ctx->gc_wire_ctx.data)
704                 OBD_FREE(ctx->gc_wire_ctx.data, ctx->gc_wire_ctx.len);
705 err_free_ctx:
706         OBD_FREE(ctx, sizeof(*ctx));
707         CDEBUG(D_SEC, "err_code %d, gss code %d\n", err, *gss_err);
708         return err;
709 }
710
711 /***************************************
712  * cred APIs                           *
713  ***************************************/
714 #ifdef __KERNEL__
715 static int gss_cred_refresh(struct ptlrpc_cred *cred)
716 {
717         struct obd_import          *import;
718         struct gss_sec             *gsec;
719         struct gss_upcall_msg      *gss_msg, *gss_new;
720         struct gss_upcall_msg_data  gmd;
721         struct dentry              *dentry;
722         char                       *obdname, *obdtype;
723         wait_queue_t                wait;
724         uid_t                       uid = cred->pc_uid;
725         int                         res;
726         ENTRY;
727
728         might_sleep();
729
730         /* any flags means it has been handled, do nothing */
731         if (cred->pc_flags & PTLRPC_CRED_FLAGS_MASK)
732                 RETURN(0);
733
734         LASSERT(cred->pc_sec);
735         LASSERT(cred->pc_sec->ps_import);
736         LASSERT(cred->pc_sec->ps_import->imp_obd);
737
738         import = cred->pc_sec->ps_import;
739         if (!import->imp_connection) {
740                 CERROR("import has no connection set\n");
741                 RETURN(-EINVAL);
742         }
743
744         gmd.gum_uid = uid;
745         gmd.gum_nal = import->imp_connection->c_peer.peer_ni->pni_number;
746         gmd.gum_netid = 0;
747         gmd.gum_nid = import->imp_connection->c_peer.peer_id.nid;
748
749         obdtype = import->imp_obd->obd_type->typ_name;
750         if (!strcmp(obdtype, "mdc"))
751                 gmd.gum_svc = LUSTRE_GSS_SVC_MDS;
752         else if (!strcmp(obdtype, "osc"))
753                 gmd.gum_svc = LUSTRE_GSS_SVC_OSS;
754         else {
755                 CERROR("gss on %s?\n", obdtype);
756                 RETURN(-EINVAL);
757         }
758
759         gsec = container_of(cred->pc_sec, struct gss_sec, gs_base);
760         obdname = import->imp_obd->obd_name;
761         dentry = gsec->gs_depipe;
762         gss_new = NULL;
763         res = 0;
764
765         CDEBUG(D_SEC, "Initiate gss context %p(%u@%s)\n",
766                container_of(cred, struct gss_cred, gc_base),
767                uid, import->imp_target_uuid.uuid);
768
769 again:
770         spin_lock(&gsec->gs_lock);
771         gss_msg = gss_find_upcall(gsec, obdname, &gmd);
772         if (gss_msg) {
773                 if (gss_new) {
774                         OBD_FREE(gss_new, sizeof(*gss_new));
775                         gss_new = NULL;
776                 }
777                 GOTO(waiting, res);
778         }
779
780         if (!gss_new) {
781                 spin_unlock(&gsec->gs_lock);
782                 OBD_ALLOC(gss_new, sizeof(*gss_new));
783                 if (!gss_new)
784                         RETURN(-ENOMEM);
785                 goto again;
786         }
787         /* so far we'v created gss_new */
788         gss_init_upcall_msg(gss_new, gsec, obdname, &gmd);
789
790         /* we'v created upcall msg, nobody else should touch the
791          * flag of this cred, unless be set as dead/expire by
792          * administrator via lctl etc.
793          */
794         if (cred->pc_flags & PTLRPC_CRED_FLAGS_MASK) {
795                 CWARN("cred %p("LPU64"/%u) was set flags %lx unexpectedly\n",
796                       cred, cred->pc_pag, cred->pc_uid, cred->pc_flags);
797                 cred->pc_flags |= PTLRPC_CRED_DEAD | PTLRPC_CRED_ERROR;
798                 gss_unhash_msg_nolock(gss_new);
799                 spin_unlock(&gsec->gs_lock);
800                 gss_release_msg(gss_new);
801                 RETURN(0);
802         }
803
804         /* need to make upcall now */
805         spin_unlock(&gsec->gs_lock);
806         res = rpc_queue_upcall(dentry->d_inode, &gss_new->gum_base);
807         if (res) {
808                 CERROR("rpc_queue_upcall failed: %d\n", res);
809                 gss_unhash_msg(gss_new);
810                 gss_release_msg(gss_new);
811                 cred->pc_flags |= PTLRPC_CRED_DEAD | PTLRPC_CRED_ERROR;
812                 RETURN(res);
813         }
814         gss_msg = gss_new;
815         spin_lock(&gsec->gs_lock);
816
817 waiting:
818         /* upcall might finish quickly */
819         if (list_empty(&gss_msg->gum_list)) {
820                 spin_unlock(&gsec->gs_lock);
821                 res = 0;
822                 goto out;
823         }
824
825         init_waitqueue_entry(&wait, current);
826         set_current_state(TASK_INTERRUPTIBLE);
827         add_wait_queue(&gss_msg->gum_waitq, &wait);
828         spin_unlock(&gsec->gs_lock);
829
830         if (gss_new)
831                 res = schedule_timeout(CRED_REFRESH_UPCALL_TIMEOUT * HZ);
832         else {
833                 schedule();
834                 res = 0;
835         }
836
837         remove_wait_queue(&gss_msg->gum_waitq, &wait);
838
839         /* - the one who refresh the cred for us should also be responsible
840          *   to set the status of cred, we can simply return.
841          * - if cred flags has been set, we also don't need to do that again,
842          *   no matter signal pending or timeout etc.
843          */
844         if (!gss_new || cred->pc_flags & PTLRPC_CRED_FLAGS_MASK)
845                 goto out;
846
847         if (signal_pending(current)) {
848                 CERROR("%s: cred %p: interrupted upcall\n",
849                        current->comm, cred);
850                 cred->pc_flags |= PTLRPC_CRED_DEAD | PTLRPC_CRED_ERROR;
851                 res = -EINTR;
852         } else if (res == 0) {
853                 CERROR("cred %p: upcall timedout\n", cred);
854                 set_bit(PTLRPC_CRED_DEAD_BIT, &cred->pc_flags);
855                 res = -ETIMEDOUT;
856         } else
857                 res = 0;
858
859 out:
860         gss_release_msg(gss_msg);
861
862         RETURN(res);
863 }
864 #else /* !__KERNEL__ */
865 extern int lgss_handle_krb5_upcall(uid_t uid, __u32 dest_ip,
866                                    char *obd_name,
867                                    char *buf, int bufsize,
868                                    int (*callback)(char*, unsigned long));
869
870 static int gss_cred_refresh(struct ptlrpc_cred *cred)
871 {
872         char                    buf[4096];
873         rawobj_t                obj;
874         struct obd_import      *imp;
875         struct gss_sec         *gsec;
876         struct gss_api_mech    *mech;
877         struct gss_cl_ctx      *ctx = NULL;
878         struct vfs_cred         vcred = { 0 };
879         ptl_nid_t               peer_nid;
880         __u32                   dest_ip;
881         __u32                   subflavor;
882         int                     rc, gss_err;
883
884         LASSERT(cred);
885         LASSERT(cred->pc_sec);
886         LASSERT(cred->pc_sec->ps_import);
887         LASSERT(cred->pc_sec->ps_import->imp_obd);
888
889         if (ptlrpcs_cred_is_uptodate(cred))
890                 RETURN(0);
891
892         imp = cred->pc_sec->ps_import;
893         peer_nid = imp->imp_connection->c_peer.peer_id.nid;
894         dest_ip = (__u32) (peer_nid & 0xFFFFFFFF);
895         subflavor = cred->pc_sec->ps_flavor.subflavor;
896
897         if (subflavor != PTLRPC_SEC_GSS_KRB5I) {
898                 CERROR("unknown subflavor %u\n", subflavor);
899                 GOTO(err_out, rc = -EINVAL);
900         }
901
902         rc = lgss_handle_krb5_upcall(cred->pc_uid, dest_ip,
903                                      imp->imp_obd->obd_name,
904                                      buf, sizeof(buf),
905                                      gss_send_secinit_rpc);
906         LASSERT(rc != 0);
907         if (rc < 0)
908                 goto err_out;
909
910         obj.data = buf;
911         obj.len = rc;
912
913         gsec = container_of(cred->pc_sec, struct gss_sec, gs_base);
914         mech = gsec->gs_mech;
915         LASSERT(mech);
916         rc = gss_parse_init_downcall(mech, &obj, &ctx, &vcred, &dest_ip,
917                                      &gss_err);
918         if (rc || gss_err) {
919                 CERROR("parse init downcall: rpc %d, gss 0x%x\n", rc, gss_err);
920                 if (rc != -ERESTART || gss_err != 0)
921                         set_bit(PTLRPC_CRED_ERROR_BIT, &cred->pc_flags);
922                 if (rc == 0)
923                         rc = -EPERM;
924                 goto err_out;
925         }
926
927         LASSERT(ctx);
928         gss_cred_set_ctx(cred, ctx);
929         LASSERT(gss_cred_is_uptodate_ctx(cred));
930
931         return 0;
932 err_out:
933         set_bit(PTLRPC_CRED_DEAD_BIT, &cred->pc_flags);
934         return rc;
935 }
936 #endif
937
938 static int gss_cred_match(struct ptlrpc_cred *cred,
939                           struct vfs_cred *vcred)
940 {
941         RETURN(cred->pc_pag == vcred->vc_pag);
942 }
943
944 static int gss_cred_sign(struct ptlrpc_cred *cred,
945                          struct ptlrpc_request *req)
946 {
947         struct gss_cred         *gcred;
948         struct gss_cl_ctx       *ctx;
949         rawobj_t                 lmsg, mic;
950         __u32                   *vp, *vpsave, vlen, seclen;
951         __u32                    seqnum, major, rc = 0;
952         ENTRY;
953
954         LASSERT(req->rq_reqbuf);
955         LASSERT(req->rq_cred == cred);
956
957         gcred = container_of(cred, struct gss_cred, gc_base);
958         ctx = gss_cred_get_ctx(cred);
959         if (!ctx) {
960                 CERROR("cred %p("LPU64"/%u) invalidated?\n",
961                         cred, cred->pc_pag, cred->pc_uid);
962                 RETURN(-EPERM);
963         }
964
965         lmsg.len = req->rq_reqlen;
966         lmsg.data = (__u8 *) req->rq_reqmsg;
967
968         vp = (__u32 *) (lmsg.data + lmsg.len);
969         vlen = req->rq_reqbuf_len - sizeof(struct ptlrpcs_wire_hdr) -
970                lmsg.len;
971         seclen = vlen;
972
973         if (vlen < 6 * 4 + size_round4(ctx->gc_wire_ctx.len)) {
974                 CERROR("vlen %d, need %d\n",
975                         vlen, 6 * 4 + size_round4(ctx->gc_wire_ctx.len));
976                 rc = -EIO;
977                 goto out;
978         }
979
980         spin_lock(&ctx->gc_seq_lock);
981         seqnum = ctx->gc_seq++;
982         spin_unlock(&ctx->gc_seq_lock);
983
984         *vp++ = cpu_to_le32(PTLRPC_SEC_GSS_VERSION);    /* version */
985         *vp++ = cpu_to_le32(PTLRPCS_FLVR_KRB5I);        /* subflavor */
986         *vp++ = cpu_to_le32(ctx->gc_proc);              /* proc */
987         *vp++ = cpu_to_le32(seqnum);                    /* seq */
988         *vp++ = cpu_to_le32(PTLRPCS_GSS_SVC_INTEGRITY); /* service */
989         vlen -= 5 * 4;
990
991         if (rawobj_serialize(&ctx->gc_wire_ctx, &vp, &vlen)) {
992                 rc = -EIO;
993                 goto out;
994         }
995         CDEBUG(D_SEC, "encoded wire_ctx length %d\n", ctx->gc_wire_ctx.len);
996
997         vpsave = vp++;  /* reserve for size */
998         vlen -= 4;
999
1000         mic.len = vlen;
1001         mic.data = (unsigned char *)vp;
1002
1003         CDEBUG(D_SEC, "reqbuf at %p, lmsg at %p, len %d, mic at %p, len %d\n",
1004                req->rq_reqbuf, lmsg.data, lmsg.len, mic.data, mic.len);
1005         major = kgss_get_mic(ctx->gc_gss_ctx, GSS_C_QOP_DEFAULT, &lmsg, &mic);
1006         if (major) {
1007                 CERROR("cred %p: req %p compute mic error, major %x\n",
1008                        cred, req, major);
1009                 rc = -EACCES;
1010                 goto out;
1011         }
1012
1013         *vpsave = cpu_to_le32(mic.len);
1014         
1015         seclen = seclen - vlen + mic.len;
1016         buf_to_sec_hdr(req->rq_reqbuf)->sec_len = cpu_to_le32(seclen);
1017         req->rq_reqdata_len += size_round(seclen);
1018         CDEBUG(D_SEC, "msg size %d, checksum size %d, total sec size %d\n",
1019                lmsg.len, mic.len, seclen);
1020 out:
1021         gss_put_ctx(ctx);
1022         RETURN(rc);
1023 }
1024
1025 static int gss_cred_verify(struct ptlrpc_cred *cred,
1026                            struct ptlrpc_request *req)
1027 {
1028         struct gss_cred        *gcred;
1029         struct gss_cl_ctx      *ctx;
1030         struct ptlrpcs_wire_hdr *sec_hdr;
1031         rawobj_t                lmsg, mic;
1032         __u32                   *vp, vlen, subflavor, proc, seq, svc;
1033         __u32                   major, minor, rc;
1034         ENTRY;
1035
1036         LASSERT(req->rq_repbuf);
1037         LASSERT(req->rq_cred == cred);
1038
1039         sec_hdr = buf_to_sec_hdr(req->rq_repbuf);
1040         vp = (__u32 *) (req->rq_repbuf + sizeof(*sec_hdr) + sec_hdr->msg_len);
1041         vlen = sec_hdr->sec_len;
1042
1043         if (vlen < 7 * 4) {
1044                 CERROR("reply sec size %u too small\n", vlen);
1045                 RETURN(-EPROTO);
1046         }
1047
1048         if (*vp++ != cpu_to_le32(PTLRPC_SEC_GSS_VERSION)) {
1049                 CERROR("reply have different gss version\n");
1050                 RETURN(-EPROTO);
1051         }
1052         subflavor = le32_to_cpu(*vp++);
1053         proc = le32_to_cpu(*vp++);
1054         vlen -= 3 * 4;
1055
1056         switch (proc) {
1057         case PTLRPCS_GSS_PROC_DATA:
1058                 seq = le32_to_cpu(*vp++);
1059                 svc = le32_to_cpu(*vp++);
1060                 if (svc != PTLRPCS_GSS_SVC_INTEGRITY) {
1061                         CERROR("Unknown svc %d\n", svc);
1062                         RETURN(-EPROTO);
1063                 }
1064                 if (*vp++ != 0) {
1065                         CERROR("Unexpected ctx handle\n");
1066                         RETURN(-EPROTO);
1067                 }
1068                 mic.len = le32_to_cpu(*vp++);
1069                 vlen -= 4 * 4;
1070                 if (vlen < mic.len) {
1071                         CERROR("vlen %d, mic.len %d\n", vlen, mic.len);
1072                         RETURN(-EINVAL);
1073                 }
1074                 mic.data = (unsigned char *)vp;
1075
1076                 gcred = container_of(cred, struct gss_cred, gc_base);
1077                 ctx = gss_cred_get_ctx(cred);
1078                 LASSERT(ctx);
1079
1080                 lmsg.len = sec_hdr->msg_len;
1081                 lmsg.data = (__u8 *) buf_to_lustre_msg(req->rq_repbuf);
1082
1083                 major = kgss_verify_mic(ctx->gc_gss_ctx, &lmsg, &mic, NULL);
1084                 if (major != GSS_S_COMPLETE) {
1085                         CERROR("cred %p: req %p verify mic error: major %x\n",
1086                                cred, req, major);
1087
1088                         if (major == GSS_S_CREDENTIALS_EXPIRED ||
1089                             major == GSS_S_CONTEXT_EXPIRED) {
1090                                 ptlrpcs_cred_expire(cred);
1091                                 req->rq_ptlrpcs_restart = 1;
1092                                 rc = 0;
1093                         } else
1094                                 rc = -EINVAL;
1095
1096                         GOTO(proc_data_out, rc);
1097                 }
1098
1099                 req->rq_repmsg = (struct lustre_msg *) lmsg.data;
1100                 req->rq_replen = lmsg.len;
1101
1102                 /* here we could check the seq number is the same one
1103                  * we sent to server. but portals has prevent us from
1104                  * replay attack, so maybe we don't need check it again.
1105                  */
1106                 rc = 0;
1107 proc_data_out:
1108                 gss_put_ctx(ctx);
1109                 break;
1110         case PTLRPCS_GSS_PROC_ERR:
1111                 major = le32_to_cpu(*vp++);
1112                 minor = le32_to_cpu(*vp++);
1113                 /* server return NO_CONTEXT might be caused by context expire
1114                  * or server reboot/failover. we refresh the cred transparently
1115                  * to upper layer.
1116                  * In some cases, our gss handle is possible to be incidentally
1117                  * identical to another handle since the handle itself is not
1118                  * fully random. In krb5 case, the GSS_S_BAD_SIG will be
1119                  * returned, maybe other gss error for other mechanism. Here we
1120                  * only consider krb5 mech (FIXME) and try to establish new
1121                  * context.
1122                  */
1123                 if (major == GSS_S_NO_CONTEXT ||
1124                     major == GSS_S_BAD_SIG) {
1125                         CWARN("req %p: server report cred %p %s, expired?\n",
1126                                req, cred, (major == GSS_S_NO_CONTEXT) ?
1127                                            "NO_CONTEXT" : "BAD_SIG");
1128
1129                         ptlrpcs_cred_expire(cred);
1130                         req->rq_ptlrpcs_restart = 1;
1131                         rc = 0;
1132                 } else {
1133                         CERROR("req %p: unrecognized gss error (%x/%x)\n",
1134                                 req, major, minor);
1135                         rc = -EACCES;
1136                 }
1137                 break;
1138         default:
1139                 CERROR("unknown gss proc %d\n", proc);
1140                 rc = -EPROTO;
1141         }
1142
1143         RETURN(rc);
1144 }
1145
1146 static int gss_cred_seal(struct ptlrpc_cred *cred,
1147                          struct ptlrpc_request *req)
1148 {
1149         struct gss_cred         *gcred;
1150         struct gss_cl_ctx       *ctx;
1151         struct ptlrpcs_wire_hdr *sec_hdr;
1152         rawobj_buf_t             msg_buf;
1153         rawobj_t                 cipher_buf;
1154         __u32                   *vp, *vpsave, vlen, seclen;
1155         __u32                    major, seqnum, rc = 0;
1156         ENTRY;
1157
1158         LASSERT(req->rq_reqbuf);
1159         LASSERT(req->rq_cred == cred);
1160
1161         gcred = container_of(cred, struct gss_cred, gc_base);
1162         ctx = gss_cred_get_ctx(cred);
1163         if (!ctx) {
1164                 CERROR("cred %p("LPU64"/%u) invalidated?\n",
1165                         cred, cred->pc_pag, cred->pc_uid);
1166                 RETURN(-EPERM);
1167         }
1168
1169         vp = (__u32 *) (req->rq_reqbuf + sizeof(*sec_hdr));
1170         vlen = req->rq_reqbuf_len - sizeof(*sec_hdr);
1171         seclen = vlen;
1172
1173         if (vlen < 6 * 4 + size_round4(ctx->gc_wire_ctx.len)) {
1174                 CERROR("vlen %d, need %d\n",
1175                         vlen, 6 * 4 + size_round4(ctx->gc_wire_ctx.len));
1176                 rc = -EIO;
1177                 goto out;
1178         }
1179
1180         spin_lock(&ctx->gc_seq_lock);
1181         seqnum = ctx->gc_seq++;
1182         spin_unlock(&ctx->gc_seq_lock);
1183
1184         *vp++ = cpu_to_le32(PTLRPC_SEC_GSS_VERSION);    /* version */
1185         *vp++ = cpu_to_le32(PTLRPCS_FLVR_KRB5P);        /* subflavor */
1186         *vp++ = cpu_to_le32(ctx->gc_proc);              /* proc */
1187         *vp++ = cpu_to_le32(seqnum);                    /* seq */
1188         *vp++ = cpu_to_le32(PTLRPCS_GSS_SVC_PRIVACY);   /* service */
1189         vlen -= 5 * 4;
1190
1191         if (rawobj_serialize(&ctx->gc_wire_ctx, &vp, &vlen)) {
1192                 rc = -EIO;
1193                 goto out;
1194         }
1195         CDEBUG(D_SEC, "encoded wire_ctx length %d\n", ctx->gc_wire_ctx.len);
1196
1197         vpsave = vp++;  /* reserve for size */
1198         vlen -= 4;
1199
1200         msg_buf.buf = (__u8 *) req->rq_reqmsg - GSS_PRIVBUF_PREFIX_LEN;
1201         msg_buf.buflen = req->rq_reqlen + GSS_PRIVBUF_PREFIX_LEN +
1202                                           GSS_PRIVBUF_SUFFIX_LEN;
1203         msg_buf.dataoff = GSS_PRIVBUF_PREFIX_LEN;
1204         msg_buf.datalen = req->rq_reqlen;
1205
1206         cipher_buf.data = (__u8 *) vp;
1207         cipher_buf.len = vlen;
1208
1209         major = kgss_wrap(ctx->gc_gss_ctx, GSS_C_QOP_DEFAULT,
1210                           &msg_buf, &cipher_buf);
1211         if (major) {
1212                 CERROR("cred %p: error wrap: major 0x%x\n", cred, major);
1213                 GOTO(out, rc = -EINVAL);
1214         }
1215
1216         *vpsave = cpu_to_le32(cipher_buf.len);
1217
1218         seclen = seclen - vlen + cipher_buf.len;
1219         sec_hdr = buf_to_sec_hdr(req->rq_reqbuf);
1220         sec_hdr->sec_len = cpu_to_le32(seclen);
1221         req->rq_reqdata_len += size_round(seclen);
1222
1223         CDEBUG(D_SEC, "msg size %d, total sec size %d\n",
1224                req->rq_reqlen, seclen);
1225 out:
1226         gss_put_ctx(ctx);
1227         RETURN(rc);
1228 }
1229
1230 static int gss_cred_unseal(struct ptlrpc_cred *cred,
1231                            struct ptlrpc_request *req)
1232 {
1233         struct gss_cred        *gcred;
1234         struct gss_cl_ctx      *ctx;
1235         struct ptlrpcs_wire_hdr *sec_hdr;
1236         rawobj_t                cipher_text, plain_text;
1237         __u32                   *vp, vlen, subflavor, proc, seq, svc;
1238         __u32                   major, rc;
1239         ENTRY;
1240
1241         LASSERT(req->rq_repbuf);
1242         LASSERT(req->rq_cred == cred);
1243
1244         sec_hdr = buf_to_sec_hdr(req->rq_repbuf);
1245         if (sec_hdr->msg_len != 0) {
1246                 CERROR("unexpected msg_len %u\n", sec_hdr->msg_len);
1247                 RETURN(-EPROTO);
1248         }
1249
1250         vp = (__u32 *) (req->rq_repbuf + sizeof(*sec_hdr));
1251         vlen = sec_hdr->sec_len;
1252
1253         if (vlen < 7 * 4) {
1254                 CERROR("reply sec size %u too small\n", vlen);
1255                 RETURN(-EPROTO);
1256         }
1257
1258         if (*vp++ != cpu_to_le32(PTLRPC_SEC_GSS_VERSION)) {
1259                 CERROR("reply have different gss version\n");
1260                 RETURN(-EPROTO);
1261         }
1262         subflavor = le32_to_cpu(*vp++);
1263         proc = le32_to_cpu(*vp++);
1264         seq = le32_to_cpu(*vp++);
1265         svc = le32_to_cpu(*vp++);
1266         vlen -= 5 * 4;
1267
1268         switch (proc) {
1269         case PTLRPCS_GSS_PROC_DATA:
1270                 if (svc != PTLRPCS_GSS_SVC_PRIVACY) {
1271                         CERROR("Unknown svc %d\n", svc);
1272                         RETURN(-EPROTO);
1273                 }
1274                 if (*vp++ != 0) {
1275                         CERROR("Unexpected ctx handle\n");
1276                         RETURN(-EPROTO);
1277                 }
1278                 vlen -= 4;
1279
1280                 cipher_text.len = le32_to_cpu(*vp++);
1281                 cipher_text.data = (__u8 *) vp;
1282                 vlen -= 4;
1283
1284                 if (vlen < cipher_text.len) {
1285                         CERROR("cipher text to be %u while buf only %u\n",
1286                                 cipher_text.len, vlen);
1287                         RETURN(-EPROTO);
1288                 }
1289
1290                 plain_text = cipher_text;
1291
1292                 gcred = container_of(cred, struct gss_cred, gc_base);
1293                 ctx = gss_cred_get_ctx(cred);
1294                 LASSERT(ctx);
1295
1296                 major = kgss_unwrap(ctx->gc_gss_ctx, GSS_C_QOP_DEFAULT,
1297                                     &cipher_text, &plain_text);
1298                 if (major) {
1299                         CERROR("cred %p: error unwrap: major 0x%x\n",
1300                                cred, major);
1301
1302                         if (major == GSS_S_CREDENTIALS_EXPIRED ||
1303                             major == GSS_S_CONTEXT_EXPIRED) {
1304                                 ptlrpcs_cred_expire(cred);
1305                                 req->rq_ptlrpcs_restart = 1;
1306                                 rc = 0;
1307                         } else
1308                                 rc = -EINVAL;
1309
1310                         GOTO(proc_out, rc);
1311                 }
1312
1313                 req->rq_repmsg = (struct lustre_msg *) vp;
1314                 req->rq_replen = plain_text.len;
1315
1316                 rc = 0;
1317 proc_out:
1318                 gss_put_ctx(ctx);
1319                 break;
1320         default:
1321                 CERROR("unknown gss proc %d\n", proc);
1322                 rc = -EPROTO;
1323         }
1324
1325         RETURN(rc);
1326 }
1327
1328 static void destroy_gss_context(struct ptlrpc_cred *cred)
1329 {
1330         struct ptlrpcs_wire_hdr *hdr;
1331         struct lustre_msg       *lmsg;
1332         struct gss_cred         *gcred;
1333         struct ptlrpc_request    req;
1334         struct obd_import       *imp;
1335         __u32                   *vp, lmsg_size;
1336         struct ptlrpc_request   *raw_req = NULL;
1337         const int                repbuf_len = 256;
1338         char                    *repbuf;
1339         int                      replen, rc;
1340         ENTRY;
1341
1342         imp = cred->pc_sec->ps_import;
1343         LASSERT(imp);
1344
1345         if (test_bit(PTLRPC_CRED_ERROR_BIT, &cred->pc_flags) ||
1346             !test_bit(PTLRPC_CRED_UPTODATE_BIT, &cred->pc_flags)) {
1347                 CDEBUG(D_SEC, "Destroy dead cred %p(%u@%s)\n",
1348                        cred, cred->pc_uid, imp->imp_target_uuid.uuid);
1349                 EXIT;
1350                 return;
1351         }
1352
1353         might_sleep();
1354
1355         /* cred's refcount is 0, steal one */
1356         atomic_inc(&cred->pc_refcount);
1357
1358         gcred = container_of(cred, struct gss_cred, gc_base);
1359         gcred->gc_ctx->gc_proc = PTLRPCS_GSS_PROC_DESTROY;
1360
1361         CDEBUG(D_SEC, "client destroy gss cred %p(%u@%s)\n",
1362                gcred, cred->pc_uid, imp->imp_target_uuid.uuid);
1363
1364         lmsg_size = lustre_msg_size(0, NULL);
1365         req.rq_req_secflvr = cred->pc_sec->ps_flavor;
1366         req.rq_cred = cred;
1367         req.rq_reqbuf_len = sizeof(*hdr) + lmsg_size +
1368                             ptlrpcs_est_req_payload(&req, lmsg_size);
1369
1370         OBD_ALLOC(req.rq_reqbuf, req.rq_reqbuf_len);
1371         if (!req.rq_reqbuf) {
1372                 CERROR("Fail to alloc reqbuf, cancel anyway\n");
1373                 atomic_dec(&cred->pc_refcount);
1374                 EXIT;
1375                 return;
1376         }
1377
1378         /* wire hdr */
1379         hdr = buf_to_sec_hdr(req.rq_reqbuf);
1380         hdr->flavor  = cpu_to_le32(PTLRPCS_FLVR_GSS_AUTH);
1381         hdr->msg_len = cpu_to_le32(lmsg_size);
1382         hdr->sec_len = cpu_to_le32(0);
1383
1384         /* lustre message */
1385         lmsg = buf_to_lustre_msg(req.rq_reqbuf);
1386         lustre_init_msg(lmsg, 0, NULL, NULL);
1387         lmsg->handle   = imp->imp_remote_handle;
1388         lmsg->type     = PTL_RPC_MSG_REQUEST;
1389         lmsg->opc      = SEC_FINI;
1390         lmsg->flags    = 0;
1391         lmsg->conn_cnt = imp->imp_conn_cnt;
1392         /* add this for randomize */
1393         get_random_bytes(&lmsg->last_xid, sizeof(lmsg->last_xid));
1394         get_random_bytes(&lmsg->transno, sizeof(lmsg->transno));
1395
1396         vp = (__u32 *) req.rq_reqbuf;
1397
1398         req.rq_cred = cred;
1399         req.rq_reqmsg = buf_to_lustre_msg(req.rq_reqbuf);
1400         req.rq_reqlen = lmsg_size;
1401         req.rq_reqdata_len = sizeof(*hdr) + lmsg_size;
1402
1403         if (gss_cred_sign(cred, &req)) {
1404                 CERROR("failed to sign, cancel anyway\n");
1405                 atomic_dec(&cred->pc_refcount);
1406                 goto exit;
1407         }
1408         atomic_dec(&cred->pc_refcount);
1409
1410         OBD_ALLOC(repbuf, repbuf_len);
1411         if (!repbuf)
1412                 goto exit;
1413
1414         raw_req = ptl_do_rawrpc(imp, req.rq_reqbuf, req.rq_reqbuf_len,
1415                                 req.rq_reqdata_len, repbuf, repbuf_len, &replen,
1416                                 SECFINI_RPC_TIMEOUT, &rc);
1417         if (!raw_req)
1418                 OBD_FREE(repbuf, repbuf_len);
1419
1420 exit:
1421         if (raw_req == NULL)
1422                 OBD_FREE(req.rq_reqbuf, req.rq_reqbuf_len);
1423         else
1424                 rawrpc_req_finished(raw_req);
1425         EXIT;
1426 }
1427
1428 static void gss_cred_destroy(struct ptlrpc_cred *cred)
1429 {
1430         struct gss_cred *gcred;
1431         ENTRY;
1432
1433         LASSERT(cred);
1434         LASSERT(!atomic_read(&cred->pc_refcount));
1435
1436         gcred = container_of(cred, struct gss_cred, gc_base);
1437         if (gcred->gc_ctx) {
1438                 destroy_gss_context(cred);
1439                 gss_put_ctx(gcred->gc_ctx);
1440         }
1441
1442         CDEBUG(D_SEC, "GSS_SEC: destroy cred %p\n", gcred);
1443
1444         OBD_FREE(gcred, sizeof(*gcred));
1445         EXIT;
1446 }
1447
1448 static struct ptlrpc_credops gss_credops = {
1449         .refresh        = gss_cred_refresh,
1450         .match          = gss_cred_match,
1451         .sign           = gss_cred_sign,
1452         .verify         = gss_cred_verify,
1453         .seal           = gss_cred_seal,
1454         .unseal         = gss_cred_unseal,
1455         .destroy        = gss_cred_destroy,
1456 };
1457
1458 #ifdef __KERNEL__
1459 /*******************************************
1460  * rpc_pipe APIs                           *
1461  *******************************************/
1462 static ssize_t
1463 gss_pipe_upcall(struct file *filp, struct rpc_pipe_msg *msg,
1464                 char *dst, size_t buflen)
1465 {
1466         char *data = (char *)msg->data + msg->copied;
1467         ssize_t mlen = msg->len;
1468         ssize_t left;
1469         ENTRY;
1470
1471         if (mlen > buflen)
1472                 mlen = buflen;
1473         left = copy_to_user(dst, data, mlen);
1474         if (left < 0) {
1475                 msg->errno = left;
1476                 RETURN(left);
1477         }
1478         mlen -= left;
1479         msg->copied += mlen;
1480         msg->errno = 0;
1481         RETURN(mlen);
1482 }
1483
1484 static ssize_t
1485 gss_pipe_downcall(struct file *filp, const char *src, size_t mlen)
1486 {
1487         char *buf;
1488         const int bufsize = 1024;
1489         rawobj_t obj;
1490         struct inode *inode = filp->f_dentry->d_inode;
1491         struct rpc_inode *rpci = RPC_I(inode);
1492         struct obd_import *import;
1493         struct ptlrpc_sec *sec;
1494         struct gss_sec *gsec;
1495         char *obdname;
1496         struct gss_api_mech *mech;
1497         struct vfs_cred vcred = { 0 };
1498         struct ptlrpc_cred *cred;
1499         struct gss_upcall_msg *gss_msg;
1500         struct gss_upcall_msg_data gmd = { 0 };
1501         struct gss_cl_ctx *ctx = NULL;
1502         ssize_t left;
1503         int err, gss_err;
1504         ENTRY;
1505
1506         if (mlen > bufsize) {
1507                 CERROR("mlen %ld > bufsize %d\n", (long)mlen, bufsize);
1508                 RETURN(-ENOSPC);
1509         }
1510
1511         OBD_ALLOC(buf, bufsize);
1512         if (!buf) {
1513                 CERROR("alloc mem failed\n");
1514                 RETURN(-ENOMEM);
1515         }
1516
1517         left = copy_from_user(buf, src, mlen);
1518         if (left)
1519                 GOTO(err_free, err = -EFAULT);
1520
1521         obj.data = (unsigned char *)buf;
1522         obj.len = mlen;
1523
1524         LASSERT(rpci->private);
1525         gsec = (struct gss_sec *)rpci->private;
1526         sec = &gsec->gs_base;
1527         LASSERT(sec->ps_import);
1528         import = class_import_get(sec->ps_import);
1529         LASSERT(import->imp_obd);
1530         obdname = import->imp_obd->obd_name;
1531         mech = gsec->gs_mech;
1532
1533         err = gss_parse_init_downcall(mech, &obj, &ctx, &gmd, &gss_err);
1534         if (err)
1535                 CERROR("parse init downcall err %d\n", err);
1536
1537         vcred.vc_uid = gmd.gum_uid;
1538         vcred.vc_pag = vcred.vc_uid; /* FIXME */
1539
1540         cred = ptlrpcs_cred_lookup(sec, &vcred);
1541         if (!cred) {
1542                 CWARN("didn't find cred for uid %u\n", vcred.vc_uid);
1543                 GOTO(err, err = -EINVAL);
1544         }
1545
1546         if (err || gss_err) {
1547                 set_bit(PTLRPC_CRED_DEAD_BIT, &cred->pc_flags);
1548                 if (err != -ERESTART || gss_err != 0)
1549                         set_bit(PTLRPC_CRED_ERROR_BIT, &cred->pc_flags);
1550                 CERROR("cred %p: rpc err %d, gss err 0x%x, fatal %d\n",
1551                        cred, err, gss_err,
1552                        (test_bit(PTLRPC_CRED_ERROR_BIT, &cred->pc_flags) != 0));
1553         } else {
1554                 CDEBUG(D_SEC, "get initial ctx:\n");
1555                 gss_cred_set_ctx(cred, ctx);
1556         }
1557
1558         spin_lock(&gsec->gs_lock);
1559         gss_msg = gss_find_upcall(gsec, obdname, &gmd);
1560         if (gss_msg) {
1561                 gss_unhash_msg_nolock(gss_msg);
1562                 spin_unlock(&gsec->gs_lock);
1563                 gss_release_msg(gss_msg);
1564         } else
1565                 spin_unlock(&gsec->gs_lock);
1566
1567         ptlrpcs_cred_put(cred, 1);
1568         class_import_put(import);
1569         OBD_FREE(buf, bufsize);
1570         RETURN(mlen);
1571 err:
1572         if (ctx)
1573                 gss_destroy_ctx(ctx);
1574         class_import_put(import);
1575 err_free:
1576         OBD_FREE(buf, bufsize);
1577         CDEBUG(D_SEC, "gss_pipe_downcall returning %d\n", err);
1578         RETURN(err);
1579 }
1580
1581 static
1582 void gss_pipe_destroy_msg(struct rpc_pipe_msg *msg)
1583 {
1584         struct gss_upcall_msg *gmsg;
1585         static unsigned long ratelimit;
1586         ENTRY;
1587
1588         if (msg->errno >= 0) {
1589                 EXIT;
1590                 return;
1591         }
1592
1593         gmsg = container_of(msg, struct gss_upcall_msg, gum_base);
1594         CDEBUG(D_SEC, "destroy gmsg %p\n", gmsg);
1595         atomic_inc(&gmsg->gum_refcount);
1596         gss_unhash_msg(gmsg);
1597         if (msg->errno == -ETIMEDOUT || msg->errno == -EPIPE) {
1598                 unsigned long now = get_seconds();
1599                 if (time_after(now, ratelimit)) {
1600                         CWARN("GSS_SEC upcall timed out.\n"
1601                               "Please check user daemon is running!\n");
1602                         ratelimit = now + 15;
1603                 }
1604         }
1605         gss_release_msg(gmsg);
1606         EXIT;
1607 }
1608
1609 static
1610 void gss_pipe_release(struct inode *inode)
1611 {
1612         struct rpc_inode *rpci = RPC_I(inode);
1613         struct ptlrpc_sec *sec;
1614         struct gss_sec *gsec;
1615         ENTRY;
1616
1617         gsec = (struct gss_sec *)rpci->private;
1618         sec = &gsec->gs_base;
1619         spin_lock(&gsec->gs_lock);
1620         while (!list_empty(&gsec->gs_upcalls)) {
1621                 struct gss_upcall_msg *gmsg;
1622
1623                 gmsg = list_entry(gsec->gs_upcalls.next,
1624                                   struct gss_upcall_msg, gum_list);
1625                 gmsg->gum_base.errno = -EPIPE;
1626                 atomic_inc(&gmsg->gum_refcount);
1627                 gss_unhash_msg_nolock(gmsg);
1628                 gss_release_msg(gmsg);
1629         }
1630         spin_unlock(&gsec->gs_lock);
1631         EXIT;
1632 }
1633
1634 static struct rpc_pipe_ops gss_upcall_ops = {
1635         .upcall         = gss_pipe_upcall,
1636         .downcall       = gss_pipe_downcall,
1637         .destroy_msg    = gss_pipe_destroy_msg,
1638         .release_pipe   = gss_pipe_release,
1639 };
1640 #endif /* __KERNEL__ */
1641
1642 /*********************************************
1643  * GSS security APIs                         *
1644  *********************************************/
1645
1646 static
1647 struct ptlrpc_sec* gss_create_sec(__u32 flavor,
1648                                   const char *pipe_dir,
1649                                   void *pipe_data)
1650 {
1651         struct gss_sec *gsec;
1652         struct ptlrpc_sec *sec;
1653 #ifdef __KERNEL__
1654         char *pos;
1655         int   pipepath_len;
1656         uid_t save_uid;
1657 #endif
1658         ENTRY;
1659
1660         LASSERT(SEC_FLAVOR_MAJOR(flavor) == PTLRPCS_FLVR_MAJOR_GSS);
1661
1662         OBD_ALLOC(gsec, sizeof(*gsec));
1663         if (!gsec) {
1664                 CERROR("can't alloc gsec\n");
1665                 RETURN(NULL);
1666         }
1667
1668         gsec->gs_mech = kgss_subflavor_to_mech(SEC_FLAVOR_SUB(flavor));
1669         if (!gsec->gs_mech) {
1670                 CERROR("subflavor 0x%x not found\n", flavor);
1671                 goto err_free;
1672         }
1673
1674         /* initialize gss sec */
1675 #ifdef __KERNEL__
1676         INIT_LIST_HEAD(&gsec->gs_upcalls);
1677         spin_lock_init(&gsec->gs_lock);
1678
1679         pipepath_len = strlen(LUSTRE_PIPEDIR) + strlen(pipe_dir) +
1680                        strlen(gsec->gs_mech->gm_name) + 3;
1681         OBD_ALLOC(gsec->gs_pipepath, pipepath_len);
1682         if (!gsec->gs_pipepath)
1683                 goto err_mech_put;
1684
1685         /* pipe rpc require root permission */
1686         save_uid = current->fsuid;
1687         current->fsuid = 0;
1688
1689         sprintf(gsec->gs_pipepath, LUSTRE_PIPEDIR"/%s", pipe_dir);
1690         if (IS_ERR(rpc_mkdir(gsec->gs_pipepath, NULL))) {
1691                 CERROR("can't make pipedir %s\n", gsec->gs_pipepath);
1692                 goto err_free_path;
1693         }
1694
1695         sprintf(gsec->gs_pipepath, LUSTRE_PIPEDIR"/%s/%s", pipe_dir,
1696                 gsec->gs_mech->gm_name); 
1697         gsec->gs_depipe = rpc_mkpipe(gsec->gs_pipepath, gsec,
1698                                      &gss_upcall_ops, RPC_PIPE_WAIT_FOR_OPEN);
1699         if (IS_ERR(gsec->gs_depipe)) {
1700                 CERROR("failed to make rpc_pipe %s: %ld\n",
1701                         gsec->gs_pipepath, PTR_ERR(gsec->gs_depipe));
1702                 goto err_rmdir;
1703         }
1704         CDEBUG(D_SEC, "gss sec %p, pipe path %s\n", gsec, gsec->gs_pipepath);
1705 #endif
1706
1707         sec = &gsec->gs_base;
1708         sec->ps_expire = GSS_CREDCACHE_EXPIRE;
1709         sec->ps_nextgc = get_seconds() + sec->ps_expire;
1710         sec->ps_flags = 0;
1711
1712         current->fsuid = save_uid;
1713
1714         CDEBUG(D_SEC, "Create GSS security instance at %p(external %p)\n",
1715                gsec, sec);
1716         RETURN(sec);
1717
1718 #ifdef __KERNEL__
1719 err_rmdir:
1720         pos = strrchr(gsec->gs_pipepath, '/');
1721         LASSERT(pos);
1722         *pos = 0;
1723         rpc_rmdir(gsec->gs_pipepath);
1724 err_free_path:
1725         current->fsuid = save_uid;
1726         OBD_FREE(gsec->gs_pipepath, pipepath_len);
1727 err_mech_put:
1728 #endif
1729         kgss_mech_put(gsec->gs_mech);
1730 err_free:
1731         OBD_FREE(gsec, sizeof(*gsec));
1732         RETURN(NULL);
1733 }
1734
1735 static
1736 void gss_destroy_sec(struct ptlrpc_sec *sec)
1737 {
1738         struct gss_sec *gsec;
1739 #ifdef __KERNEL__
1740         char *pos;
1741         int   pipepath_len;
1742 #endif
1743         ENTRY;
1744
1745         gsec = container_of(sec, struct gss_sec, gs_base);
1746         CDEBUG(D_SEC, "Destroy GSS security instance at %p\n", gsec);
1747
1748         LASSERT(gsec->gs_mech);
1749         LASSERT(!atomic_read(&sec->ps_refcount));
1750         LASSERT(!atomic_read(&sec->ps_credcount));
1751 #ifdef __KERNEL__
1752         pipepath_len = strlen(gsec->gs_pipepath) + 1;
1753         rpc_unlink(gsec->gs_pipepath);
1754         pos = strrchr(gsec->gs_pipepath, '/');
1755         LASSERT(pos);
1756         *pos = 0;
1757         rpc_rmdir(gsec->gs_pipepath);
1758         OBD_FREE(gsec->gs_pipepath, pipepath_len);
1759 #endif
1760
1761         kgss_mech_put(gsec->gs_mech);
1762         OBD_FREE(gsec, sizeof(*gsec));
1763         EXIT;
1764 }
1765
1766 static
1767 struct ptlrpc_cred * gss_create_cred(struct ptlrpc_sec *sec,
1768                                      struct vfs_cred *vcred)
1769 {
1770         struct gss_cred *gcred;
1771         struct ptlrpc_cred *cred;
1772         ENTRY;
1773
1774         OBD_ALLOC(gcred, sizeof(*gcred));
1775         if (!gcred)
1776                 RETURN(NULL);
1777
1778         cred = &gcred->gc_base;
1779         INIT_LIST_HEAD(&cred->pc_hash);
1780         atomic_set(&cred->pc_refcount, 0);
1781         cred->pc_sec = sec;
1782         cred->pc_ops = &gss_credops;
1783         cred->pc_expire = 0;
1784         cred->pc_flags = 0;
1785         cred->pc_pag = vcred->vc_pag;
1786         cred->pc_uid = vcred->vc_uid;
1787         CDEBUG(D_SEC, "create a gss cred at %p("LPU64"/%u)\n",
1788                cred, vcred->vc_pag, vcred->vc_uid);
1789
1790         RETURN(cred);
1791 }
1792
1793 static int gss_estimate_payload(struct ptlrpc_sec *sec,
1794                                 struct ptlrpc_request *req,
1795                                 int msgsize)
1796 {
1797         switch (SEC_FLAVOR_SVC(req->rq_req_secflvr)) {
1798         case PTLRPCS_SVC_AUTH:
1799                 return GSS_MAX_AUTH_PAYLOAD;
1800         case PTLRPCS_SVC_PRIV:
1801                 return size_round16(GSS_MAX_AUTH_PAYLOAD + msgsize +
1802                                     GSS_PRIVBUF_PREFIX_LEN +
1803                                     GSS_PRIVBUF_SUFFIX_LEN);
1804         default:
1805                 LBUG();
1806                 return 0;
1807         }
1808 }
1809
1810 static int gss_alloc_reqbuf(struct ptlrpc_sec *sec,
1811                             struct ptlrpc_request *req,
1812                             int lmsg_size)
1813 {
1814         int msg_payload, sec_payload;
1815         int privacy, rc;
1816         ENTRY;
1817
1818         /* In PRIVACY mode, lustre message is always 0 (already encoded into
1819          * security payload).
1820          */
1821         privacy = (SEC_FLAVOR_SVC(req->rq_req_secflvr) == PTLRPCS_SVC_PRIV);
1822         msg_payload = privacy ? 0 : lmsg_size;
1823         sec_payload = gss_estimate_payload(sec, req, lmsg_size);
1824
1825         rc = sec_alloc_reqbuf(sec, req, msg_payload, sec_payload);
1826         if (rc)
1827                 return rc;
1828
1829         if (privacy) {
1830                 int buflen = lmsg_size + GSS_PRIVBUF_PREFIX_LEN +
1831                              GSS_PRIVBUF_SUFFIX_LEN;
1832                 char *buf;
1833
1834                 OBD_ALLOC(buf, buflen);
1835                 if (!buf) {
1836                         CERROR("Fail to alloc %d\n", buflen);
1837                         sec_free_reqbuf(sec, req);
1838                         RETURN(-ENOMEM);
1839                 }
1840                 req->rq_reqmsg = (struct lustre_msg *)
1841                                         (buf + GSS_PRIVBUF_PREFIX_LEN);
1842         }
1843
1844         RETURN(0);
1845 }
1846
1847 static void gss_free_reqbuf(struct ptlrpc_sec *sec,
1848                             struct ptlrpc_request *req)
1849 {
1850         char *buf;
1851         int privacy;
1852         ENTRY;
1853
1854         LASSERT(req->rq_reqmsg);
1855         LASSERT(req->rq_reqlen);
1856
1857         privacy = SEC_FLAVOR_SVC(req->rq_req_secflvr) == PTLRPCS_SVC_PRIV;
1858         if (privacy) {
1859                 buf = (char *) req->rq_reqmsg - GSS_PRIVBUF_PREFIX_LEN;
1860                 LASSERT(buf < req->rq_reqbuf ||
1861                         buf >= req->rq_reqbuf + req->rq_reqbuf_len);
1862                 OBD_FREE(buf, req->rq_reqlen + GSS_PRIVBUF_PREFIX_LEN +
1863                               GSS_PRIVBUF_SUFFIX_LEN);
1864                 req->rq_reqmsg = NULL;
1865         }
1866
1867         sec_free_reqbuf(sec, req);
1868 }
1869
1870 static struct ptlrpc_secops gss_secops = {
1871         .create_sec             = gss_create_sec,
1872         .destroy_sec            = gss_destroy_sec,
1873         .create_cred            = gss_create_cred,
1874         .est_req_payload        = gss_estimate_payload,
1875         .est_rep_payload        = gss_estimate_payload,
1876         .alloc_reqbuf           = gss_alloc_reqbuf,
1877         .free_reqbuf            = gss_free_reqbuf,
1878 };
1879
1880 static struct ptlrpc_sec_type gss_type = {
1881         .pst_owner      = THIS_MODULE,
1882         .pst_name       = "sec.gss",
1883         .pst_inst       = ATOMIC_INIT(0),
1884         .pst_flavor     = PTLRPCS_FLVR_MAJOR_GSS,
1885         .pst_ops        = &gss_secops,
1886 };
1887
1888 extern int
1889 (*lustre_secinit_downcall_handler)(char *buffer, unsigned long count);
1890
1891 int __init ptlrpcs_gss_init(void)
1892 {
1893         int rc;
1894
1895         rc = ptlrpcs_register(&gss_type);
1896         if (rc)
1897                 return rc;
1898
1899 #ifdef __KERNEL__
1900         gss_svc_init();
1901
1902         rc = PTR_ERR(rpc_mkdir(LUSTRE_PIPEDIR, NULL));
1903         if (IS_ERR((void *)rc) && rc != -EEXIST) {
1904                 CERROR("fail to make rpcpipedir for lustre\n");
1905                 gss_svc_exit();
1906                 ptlrpcs_unregister(&gss_type);
1907                 return -1;
1908         }
1909         rc = 0;
1910 #else
1911 #endif
1912         rc = init_kerberos_module();
1913         if (rc) {
1914                 ptlrpcs_unregister(&gss_type);
1915         }
1916
1917         lustre_secinit_downcall_handler = gss_send_secinit_rpc;
1918
1919         return rc;
1920 }
1921
1922 #ifdef __KERNEL__
1923 static void __exit ptlrpcs_gss_exit(void)
1924 {
1925         lustre_secinit_downcall_handler = NULL;
1926
1927         cleanup_kerberos_module();
1928         rpc_rmdir(LUSTRE_PIPEDIR);
1929         gss_svc_exit();
1930         ptlrpcs_unregister(&gss_type);
1931 }
1932 #endif
1933
1934 MODULE_AUTHOR("Cluster File Systems, Inc. <info@clusterfs.com>");
1935 MODULE_DESCRIPTION("GSS Security module for Lustre");
1936 MODULE_LICENSE("GPL");
1937
1938 module_init(ptlrpcs_gss_init);
1939 module_exit(ptlrpcs_gss_exit);