1 /*
2  * Neil Brown <neilb@cse.unsw.edu.au>
3  * J. Bruce Fields <bfields@umich.edu>
4  * Andy Adamson <andros@umich.edu>
5  * Dug Song <dugsong@monkey.org>
6  *
7  * RPCSEC_GSS server authentication.
8  * This implements RPCSEC_GSS as defined in rfc2203 (rpcsec_gss) and rfc2078
9  * (gssapi)
10  *
11  * The RPCSEC_GSS involves three stages:
12  *  1/ context creation
13  *  2/ data exchange
14  *  3/ context destruction
15  *
16  * Context creation is handled largely by upcalls to user-space.
17  *  In particular, GSS_Accept_sec_context is handled by an upcall
18  * Data exchange is handled entirely within the kernel
19  *  In particular, GSS_GetMIC, GSS_VerifyMIC, GSS_Seal, GSS_Unseal are in-kernel.
20  * Context destruction is handled in-kernel
21  *  GSS_Delete_sec_context is in-kernel
22  *
23  * Context creation is initiated by a RPCSEC_GSS_INIT request arriving.
24  * The context handle and gss_token are used as a key into the rpcsec_init cache.
25  * The content of this cache includes some of the outputs of GSS_Accept_sec_context,
26  * being major_status, minor_status, context_handle, reply_token.
27  * These are sent back to the client.
28  * Sequence window management is handled by the kernel.  The window size if currently
29  * a compile time constant.
30  *
31  * When user-space is happy that a context is established, it places an entry
32  * in the rpcsec_context cache. The key for this cache is the context_handle.
33  * The content includes:
34  *   uid/gidlist - for determining access rights
35  *   mechanism type
36  *   mechanism specific information, such as a key
37  *
38  */
39 
40 #include <linux/slab.h>
41 #include <linux/types.h>
42 #include <linux/module.h>
43 #include <linux/pagemap.h>
44 #include <linux/user_namespace.h>
45 
46 #include <linux/sunrpc/auth_gss.h>
47 #include <linux/sunrpc/gss_err.h>
48 #include <linux/sunrpc/svcauth.h>
49 #include <linux/sunrpc/svcauth_gss.h>
50 #include <linux/sunrpc/cache.h>
51 
52 #include "../netns.h"
53 
54 #ifdef RPC_DEBUG
55 # define RPCDBG_FACILITY	RPCDBG_AUTH
56 #endif
57 
58 /* The rpcsec_init cache is used for mapping RPCSEC_GSS_{,CONT_}INIT requests
59  * into replies.
60  *
61  * Key is context handle (\x if empty) and gss_token.
62  * Content is major_status minor_status (integers) context_handle, reply_token.
63  *
64  */
65 
66 static int netobj_equal(struct xdr_netobj *a, struct xdr_netobj *b)
67 {
68 	return a->len == b->len && 0 == memcmp(a->data, b->data, a->len);
69 }
70 
71 #define	RSI_HASHBITS	6
72 #define	RSI_HASHMAX	(1<<RSI_HASHBITS)
73 
74 struct rsi {
75 	struct cache_head	h;
76 	struct xdr_netobj	in_handle, in_token;
77 	struct xdr_netobj	out_handle, out_token;
78 	int			major_status, minor_status;
79 };
80 
81 static struct rsi *rsi_update(struct cache_detail *cd, struct rsi *new, struct rsi *old);
82 static struct rsi *rsi_lookup(struct cache_detail *cd, struct rsi *item);
83 
84 static void rsi_free(struct rsi *rsii)
85 {
86 	kfree(rsii->in_handle.data);
87 	kfree(rsii->in_token.data);
88 	kfree(rsii->out_handle.data);
89 	kfree(rsii->out_token.data);
90 }
91 
92 static void rsi_put(struct kref *ref)
93 {
94 	struct rsi *rsii = container_of(ref, struct rsi, h.ref);
95 	rsi_free(rsii);
96 	kfree(rsii);
97 }
98 
99 static inline int rsi_hash(struct rsi *item)
100 {
101 	return hash_mem(item->in_handle.data, item->in_handle.len, RSI_HASHBITS)
102 	     ^ hash_mem(item->in_token.data, item->in_token.len, RSI_HASHBITS);
103 }
104 
105 static int rsi_match(struct cache_head *a, struct cache_head *b)
106 {
107 	struct rsi *item = container_of(a, struct rsi, h);
108 	struct rsi *tmp = container_of(b, struct rsi, h);
109 	return netobj_equal(&item->in_handle, &tmp->in_handle) &&
110 	       netobj_equal(&item->in_token, &tmp->in_token);
111 }
112 
113 static int dup_to_netobj(struct xdr_netobj *dst, char *src, int len)
114 {
115 	dst->len = len;
116 	dst->data = (len ? kmemdup(src, len, GFP_KERNEL) : NULL);
117 	if (len && !dst->data)
118 		return -ENOMEM;
119 	return 0;
120 }
121 
122 static inline int dup_netobj(struct xdr_netobj *dst, struct xdr_netobj *src)
123 {
124 	return dup_to_netobj(dst, src->data, src->len);
125 }
126 
127 static void rsi_init(struct cache_head *cnew, struct cache_head *citem)
128 {
129 	struct rsi *new = container_of(cnew, struct rsi, h);
130 	struct rsi *item = container_of(citem, struct rsi, h);
131 
132 	new->out_handle.data = NULL;
133 	new->out_handle.len = 0;
134 	new->out_token.data = NULL;
135 	new->out_token.len = 0;
136 	new->in_handle.len = item->in_handle.len;
137 	item->in_handle.len = 0;
138 	new->in_token.len = item->in_token.len;
139 	item->in_token.len = 0;
140 	new->in_handle.data = item->in_handle.data;
141 	item->in_handle.data = NULL;
142 	new->in_token.data = item->in_token.data;
143 	item->in_token.data = NULL;
144 }
145 
146 static void update_rsi(struct cache_head *cnew, struct cache_head *citem)
147 {
148 	struct rsi *new = container_of(cnew, struct rsi, h);
149 	struct rsi *item = container_of(citem, struct rsi, h);
150 
151 	BUG_ON(new->out_handle.data || new->out_token.data);
152 	new->out_handle.len = item->out_handle.len;
153 	item->out_handle.len = 0;
154 	new->out_token.len = item->out_token.len;
155 	item->out_token.len = 0;
156 	new->out_handle.data = item->out_handle.data;
157 	item->out_handle.data = NULL;
158 	new->out_token.data = item->out_token.data;
159 	item->out_token.data = NULL;
160 
161 	new->major_status = item->major_status;
162 	new->minor_status = item->minor_status;
163 }
164 
165 static struct cache_head *rsi_alloc(void)
166 {
167 	struct rsi *rsii = kmalloc(sizeof(*rsii), GFP_KERNEL);
168 	if (rsii)
169 		return &rsii->h;
170 	else
171 		return NULL;
172 }
173 
174 static void rsi_request(struct cache_detail *cd,
175 		       struct cache_head *h,
176 		       char **bpp, int *blen)
177 {
178 	struct rsi *rsii = container_of(h, struct rsi, h);
179 
180 	qword_addhex(bpp, blen, rsii->in_handle.data, rsii->in_handle.len);
181 	qword_addhex(bpp, blen, rsii->in_token.data, rsii->in_token.len);
182 	(*bpp)[-1] = '\n';
183 }
184 
185 static int rsi_upcall(struct cache_detail *cd, struct cache_head *h)
186 {
187 	return sunrpc_cache_pipe_upcall(cd, h, cd->cache_request);
188 }
189 
190 
191 static int rsi_parse(struct cache_detail *cd,
192 		    char *mesg, int mlen)
193 {
194 	/* context token expiry major minor context token */
195 	char *buf = mesg;
196 	char *ep;
197 	int len;
198 	struct rsi rsii, *rsip = NULL;
199 	time_t expiry;
200 	int status = -EINVAL;
201 
202 	memset(&rsii, 0, sizeof(rsii));
203 	/* handle */
204 	len = qword_get(&mesg, buf, mlen);
205 	if (len < 0)
206 		goto out;
207 	status = -ENOMEM;
208 	if (dup_to_netobj(&rsii.in_handle, buf, len))
209 		goto out;
210 
211 	/* token */
212 	len = qword_get(&mesg, buf, mlen);
213 	status = -EINVAL;
214 	if (len < 0)
215 		goto out;
216 	status = -ENOMEM;
217 	if (dup_to_netobj(&rsii.in_token, buf, len))
218 		goto out;
219 
220 	rsip = rsi_lookup(cd, &rsii);
221 	if (!rsip)
222 		goto out;
223 
224 	rsii.h.flags = 0;
225 	/* expiry */
226 	expiry = get_expiry(&mesg);
227 	status = -EINVAL;
228 	if (expiry == 0)
229 		goto out;
230 
231 	/* major/minor */
232 	len = qword_get(&mesg, buf, mlen);
233 	if (len <= 0)
234 		goto out;
235 	rsii.major_status = simple_strtoul(buf, &ep, 10);
236 	if (*ep)
237 		goto out;
238 	len = qword_get(&mesg, buf, mlen);
239 	if (len <= 0)
240 		goto out;
241 	rsii.minor_status = simple_strtoul(buf, &ep, 10);
242 	if (*ep)
243 		goto out;
244 
245 	/* out_handle */
246 	len = qword_get(&mesg, buf, mlen);
247 	if (len < 0)
248 		goto out;
249 	status = -ENOMEM;
250 	if (dup_to_netobj(&rsii.out_handle, buf, len))
251 		goto out;
252 
253 	/* out_token */
254 	len = qword_get(&mesg, buf, mlen);
255 	status = -EINVAL;
256 	if (len < 0)
257 		goto out;
258 	status = -ENOMEM;
259 	if (dup_to_netobj(&rsii.out_token, buf, len))
260 		goto out;
261 	rsii.h.expiry_time = expiry;
262 	rsip = rsi_update(cd, &rsii, rsip);
263 	status = 0;
264 out:
265 	rsi_free(&rsii);
266 	if (rsip)
267 		cache_put(&rsip->h, cd);
268 	else
269 		status = -ENOMEM;
270 	return status;
271 }
272 
273 static struct cache_detail rsi_cache_template = {
274 	.owner		= THIS_MODULE,
275 	.hash_size	= RSI_HASHMAX,
276 	.name           = "auth.rpcsec.init",
277 	.cache_put      = rsi_put,
278 	.cache_upcall   = rsi_upcall,
279 	.cache_request  = rsi_request,
280 	.cache_parse    = rsi_parse,
281 	.match		= rsi_match,
282 	.init		= rsi_init,
283 	.update		= update_rsi,
284 	.alloc		= rsi_alloc,
285 };
286 
287 static struct rsi *rsi_lookup(struct cache_detail *cd, struct rsi *item)
288 {
289 	struct cache_head *ch;
290 	int hash = rsi_hash(item);
291 
292 	ch = sunrpc_cache_lookup(cd, &item->h, hash);
293 	if (ch)
294 		return container_of(ch, struct rsi, h);
295 	else
296 		return NULL;
297 }
298 
299 static struct rsi *rsi_update(struct cache_detail *cd, struct rsi *new, struct rsi *old)
300 {
301 	struct cache_head *ch;
302 	int hash = rsi_hash(new);
303 
304 	ch = sunrpc_cache_update(cd, &new->h,
305 				 &old->h, hash);
306 	if (ch)
307 		return container_of(ch, struct rsi, h);
308 	else
309 		return NULL;
310 }
311 
312 
313 /*
314  * The rpcsec_context cache is used to store a context that is
315  * used in data exchange.
316  * The key is a context handle. The content is:
317  *  uid, gidlist, mechanism, service-set, mech-specific-data
318  */
319 
320 #define	RSC_HASHBITS	10
321 #define	RSC_HASHMAX	(1<<RSC_HASHBITS)
322 
323 #define GSS_SEQ_WIN	128
324 
325 struct gss_svc_seq_data {
326 	/* highest seq number seen so far: */
327 	int			sd_max;
328 	/* for i such that sd_max-GSS_SEQ_WIN < i <= sd_max, the i-th bit of
329 	 * sd_win is nonzero iff sequence number i has been seen already: */
330 	unsigned long		sd_win[GSS_SEQ_WIN/BITS_PER_LONG];
331 	spinlock_t		sd_lock;
332 };
333 
334 struct rsc {
335 	struct cache_head	h;
336 	struct xdr_netobj	handle;
337 	struct svc_cred		cred;
338 	struct gss_svc_seq_data	seqdata;
339 	struct gss_ctx		*mechctx;
340 };
341 
342 static struct rsc *rsc_update(struct cache_detail *cd, struct rsc *new, struct rsc *old);
343 static struct rsc *rsc_lookup(struct cache_detail *cd, struct rsc *item);
344 
345 static void rsc_free(struct rsc *rsci)
346 {
347 	kfree(rsci->handle.data);
348 	if (rsci->mechctx)
349 		gss_delete_sec_context(&rsci->mechctx);
350 	free_svc_cred(&rsci->cred);
351 }
352 
353 static void rsc_put(struct kref *ref)
354 {
355 	struct rsc *rsci = container_of(ref, struct rsc, h.ref);
356 
357 	rsc_free(rsci);
358 	kfree(rsci);
359 }
360 
361 static inline int
362 rsc_hash(struct rsc *rsci)
363 {
364 	return hash_mem(rsci->handle.data, rsci->handle.len, RSC_HASHBITS);
365 }
366 
367 static int
368 rsc_match(struct cache_head *a, struct cache_head *b)
369 {
370 	struct rsc *new = container_of(a, struct rsc, h);
371 	struct rsc *tmp = container_of(b, struct rsc, h);
372 
373 	return netobj_equal(&new->handle, &tmp->handle);
374 }
375 
376 static void
377 rsc_init(struct cache_head *cnew, struct cache_head *ctmp)
378 {
379 	struct rsc *new = container_of(cnew, struct rsc, h);
380 	struct rsc *tmp = container_of(ctmp, struct rsc, h);
381 
382 	new->handle.len = tmp->handle.len;
383 	tmp->handle.len = 0;
384 	new->handle.data = tmp->handle.data;
385 	tmp->handle.data = NULL;
386 	new->mechctx = NULL;
387 	new->cred.cr_group_info = NULL;
388 	new->cred.cr_principal = NULL;
389 }
390 
391 static void
392 update_rsc(struct cache_head *cnew, struct cache_head *ctmp)
393 {
394 	struct rsc *new = container_of(cnew, struct rsc, h);
395 	struct rsc *tmp = container_of(ctmp, struct rsc, h);
396 
397 	new->mechctx = tmp->mechctx;
398 	tmp->mechctx = NULL;
399 	memset(&new->seqdata, 0, sizeof(new->seqdata));
400 	spin_lock_init(&new->seqdata.sd_lock);
401 	new->cred = tmp->cred;
402 	tmp->cred.cr_group_info = NULL;
403 	new->cred.cr_principal = tmp->cred.cr_principal;
404 	tmp->cred.cr_principal = NULL;
405 }
406 
407 static struct cache_head *
408 rsc_alloc(void)
409 {
410 	struct rsc *rsci = kmalloc(sizeof(*rsci), GFP_KERNEL);
411 	if (rsci)
412 		return &rsci->h;
413 	else
414 		return NULL;
415 }
416 
417 static int rsc_parse(struct cache_detail *cd,
418 		     char *mesg, int mlen)
419 {
420 	/* contexthandle expiry [ uid gid N <n gids> mechname ...mechdata... ] */
421 	char *buf = mesg;
422 	int len, rv;
423 	struct rsc rsci, *rscp = NULL;
424 	time_t expiry;
425 	int status = -EINVAL;
426 	struct gss_api_mech *gm = NULL;
427 
428 	memset(&rsci, 0, sizeof(rsci));
429 	/* context handle */
430 	len = qword_get(&mesg, buf, mlen);
431 	if (len < 0) goto out;
432 	status = -ENOMEM;
433 	if (dup_to_netobj(&rsci.handle, buf, len))
434 		goto out;
435 
436 	rsci.h.flags = 0;
437 	/* expiry */
438 	expiry = get_expiry(&mesg);
439 	status = -EINVAL;
440 	if (expiry == 0)
441 		goto out;
442 
443 	rscp = rsc_lookup(cd, &rsci);
444 	if (!rscp)
445 		goto out;
446 
447 	/* uid, or NEGATIVE */
448 	rv = get_int(&mesg, &rsci.cred.cr_uid);
449 	if (rv == -EINVAL)
450 		goto out;
451 	if (rv == -ENOENT)
452 		set_bit(CACHE_NEGATIVE, &rsci.h.flags);
453 	else {
454 		int N, i;
455 
456 		/* gid */
457 		if (get_int(&mesg, &rsci.cred.cr_gid))
458 			goto out;
459 
460 		/* number of additional gid's */
461 		if (get_int(&mesg, &N))
462 			goto out;
463 		status = -ENOMEM;
464 		rsci.cred.cr_group_info = groups_alloc(N);
465 		if (rsci.cred.cr_group_info == NULL)
466 			goto out;
467 
468 		/* gid's */
469 		status = -EINVAL;
470 		for (i=0; i<N; i++) {
471 			gid_t gid;
472 			kgid_t kgid;
473 			if (get_int(&mesg, &gid))
474 				goto out;
475 			kgid = make_kgid(&init_user_ns, gid);
476 			if (!gid_valid(kgid))
477 				goto out;
478 			GROUP_AT(rsci.cred.cr_group_info, i) = kgid;
479 		}
480 
481 		/* mech name */
482 		len = qword_get(&mesg, buf, mlen);
483 		if (len < 0)
484 			goto out;
485 		gm = gss_mech_get_by_name(buf);
486 		status = -EOPNOTSUPP;
487 		if (!gm)
488 			goto out;
489 
490 		status = -EINVAL;
491 		/* mech-specific data: */
492 		len = qword_get(&mesg, buf, mlen);
493 		if (len < 0)
494 			goto out;
495 		status = gss_import_sec_context(buf, len, gm, &rsci.mechctx, GFP_KERNEL);
496 		if (status)
497 			goto out;
498 
499 		/* get client name */
500 		len = qword_get(&mesg, buf, mlen);
501 		if (len > 0) {
502 			rsci.cred.cr_principal = kstrdup(buf, GFP_KERNEL);
503 			if (!rsci.cred.cr_principal)
504 				goto out;
505 		}
506 
507 	}
508 	rsci.h.expiry_time = expiry;
509 	rscp = rsc_update(cd, &rsci, rscp);
510 	status = 0;
511 out:
512 	gss_mech_put(gm);
513 	rsc_free(&rsci);
514 	if (rscp)
515 		cache_put(&rscp->h, cd);
516 	else
517 		status = -ENOMEM;
518 	return status;
519 }
520 
521 static struct cache_detail rsc_cache_template = {
522 	.owner		= THIS_MODULE,
523 	.hash_size	= RSC_HASHMAX,
524 	.name		= "auth.rpcsec.context",
525 	.cache_put	= rsc_put,
526 	.cache_parse	= rsc_parse,
527 	.match		= rsc_match,
528 	.init		= rsc_init,
529 	.update		= update_rsc,
530 	.alloc		= rsc_alloc,
531 };
532 
533 static struct rsc *rsc_lookup(struct cache_detail *cd, struct rsc *item)
534 {
535 	struct cache_head *ch;
536 	int hash = rsc_hash(item);
537 
538 	ch = sunrpc_cache_lookup(cd, &item->h, hash);
539 	if (ch)
540 		return container_of(ch, struct rsc, h);
541 	else
542 		return NULL;
543 }
544 
545 static struct rsc *rsc_update(struct cache_detail *cd, struct rsc *new, struct rsc *old)
546 {
547 	struct cache_head *ch;
548 	int hash = rsc_hash(new);
549 
550 	ch = sunrpc_cache_update(cd, &new->h,
551 				 &old->h, hash);
552 	if (ch)
553 		return container_of(ch, struct rsc, h);
554 	else
555 		return NULL;
556 }
557 
558 
559 static struct rsc *
560 gss_svc_searchbyctx(struct cache_detail *cd, struct xdr_netobj *handle)
561 {
562 	struct rsc rsci;
563 	struct rsc *found;
564 
565 	memset(&rsci, 0, sizeof(rsci));
566 	if (dup_to_netobj(&rsci.handle, handle->data, handle->len))
567 		return NULL;
568 	found = rsc_lookup(cd, &rsci);
569 	rsc_free(&rsci);
570 	if (!found)
571 		return NULL;
572 	if (cache_check(cd, &found->h, NULL))
573 		return NULL;
574 	return found;
575 }
576 
577 /* Implements sequence number algorithm as specified in RFC 2203. */
578 static int
579 gss_check_seq_num(struct rsc *rsci, int seq_num)
580 {
581 	struct gss_svc_seq_data *sd = &rsci->seqdata;
582 
583 	spin_lock(&sd->sd_lock);
584 	if (seq_num > sd->sd_max) {
585 		if (seq_num >= sd->sd_max + GSS_SEQ_WIN) {
586 			memset(sd->sd_win,0,sizeof(sd->sd_win));
587 			sd->sd_max = seq_num;
588 		} else while (sd->sd_max < seq_num) {
589 			sd->sd_max++;
590 			__clear_bit(sd->sd_max % GSS_SEQ_WIN, sd->sd_win);
591 		}
592 		__set_bit(seq_num % GSS_SEQ_WIN, sd->sd_win);
593 		goto ok;
594 	} else if (seq_num <= sd->sd_max - GSS_SEQ_WIN) {
595 		goto drop;
596 	}
597 	/* sd_max - GSS_SEQ_WIN < seq_num <= sd_max */
598 	if (__test_and_set_bit(seq_num % GSS_SEQ_WIN, sd->sd_win))
599 		goto drop;
600 ok:
601 	spin_unlock(&sd->sd_lock);
602 	return 1;
603 drop:
604 	spin_unlock(&sd->sd_lock);
605 	return 0;
606 }
607 
608 static inline u32 round_up_to_quad(u32 i)
609 {
610 	return (i + 3 ) & ~3;
611 }
612 
613 static inline int
614 svc_safe_getnetobj(struct kvec *argv, struct xdr_netobj *o)
615 {
616 	int l;
617 
618 	if (argv->iov_len < 4)
619 		return -1;
620 	o->len = svc_getnl(argv);
621 	l = round_up_to_quad(o->len);
622 	if (argv->iov_len < l)
623 		return -1;
624 	o->data = argv->iov_base;
625 	argv->iov_base += l;
626 	argv->iov_len -= l;
627 	return 0;
628 }
629 
630 static inline int
631 svc_safe_putnetobj(struct kvec *resv, struct xdr_netobj *o)
632 {
633 	u8 *p;
634 
635 	if (resv->iov_len + 4 > PAGE_SIZE)
636 		return -1;
637 	svc_putnl(resv, o->len);
638 	p = resv->iov_base + resv->iov_len;
639 	resv->iov_len += round_up_to_quad(o->len);
640 	if (resv->iov_len > PAGE_SIZE)
641 		return -1;
642 	memcpy(p, o->data, o->len);
643 	memset(p + o->len, 0, round_up_to_quad(o->len) - o->len);
644 	return 0;
645 }
646 
647 /*
648  * Verify the checksum on the header and return SVC_OK on success.
649  * Otherwise, return SVC_DROP (in the case of a bad sequence number)
650  * or return SVC_DENIED and indicate error in authp.
651  */
652 static int
653 gss_verify_header(struct svc_rqst *rqstp, struct rsc *rsci,
654 		  __be32 *rpcstart, struct rpc_gss_wire_cred *gc, __be32 *authp)
655 {
656 	struct gss_ctx		*ctx_id = rsci->mechctx;
657 	struct xdr_buf		rpchdr;
658 	struct xdr_netobj	checksum;
659 	u32			flavor = 0;
660 	struct kvec		*argv = &rqstp->rq_arg.head[0];
661 	struct kvec		iov;
662 
663 	/* data to compute the checksum over: */
664 	iov.iov_base = rpcstart;
665 	iov.iov_len = (u8 *)argv->iov_base - (u8 *)rpcstart;
666 	xdr_buf_from_iov(&iov, &rpchdr);
667 
668 	*authp = rpc_autherr_badverf;
669 	if (argv->iov_len < 4)
670 		return SVC_DENIED;
671 	flavor = svc_getnl(argv);
672 	if (flavor != RPC_AUTH_GSS)
673 		return SVC_DENIED;
674 	if (svc_safe_getnetobj(argv, &checksum))
675 		return SVC_DENIED;
676 
677 	if (rqstp->rq_deferred) /* skip verification of revisited request */
678 		return SVC_OK;
679 	if (gss_verify_mic(ctx_id, &rpchdr, &checksum) != GSS_S_COMPLETE) {
680 		*authp = rpcsec_gsserr_credproblem;
681 		return SVC_DENIED;
682 	}
683 
684 	if (gc->gc_seq > MAXSEQ) {
685 		dprintk("RPC:       svcauth_gss: discarding request with "
686 				"large sequence number %d\n", gc->gc_seq);
687 		*authp = rpcsec_gsserr_ctxproblem;
688 		return SVC_DENIED;
689 	}
690 	if (!gss_check_seq_num(rsci, gc->gc_seq)) {
691 		dprintk("RPC:       svcauth_gss: discarding request with "
692 				"old sequence number %d\n", gc->gc_seq);
693 		return SVC_DROP;
694 	}
695 	return SVC_OK;
696 }
697 
698 static int
699 gss_write_null_verf(struct svc_rqst *rqstp)
700 {
701 	__be32     *p;
702 
703 	svc_putnl(rqstp->rq_res.head, RPC_AUTH_NULL);
704 	p = rqstp->rq_res.head->iov_base + rqstp->rq_res.head->iov_len;
705 	/* don't really need to check if head->iov_len > PAGE_SIZE ... */
706 	*p++ = 0;
707 	if (!xdr_ressize_check(rqstp, p))
708 		return -1;
709 	return 0;
710 }
711 
712 static int
713 gss_write_verf(struct svc_rqst *rqstp, struct gss_ctx *ctx_id, u32 seq)
714 {
715 	__be32			xdr_seq;
716 	u32			maj_stat;
717 	struct xdr_buf		verf_data;
718 	struct xdr_netobj	mic;
719 	__be32			*p;
720 	struct kvec		iov;
721 
722 	svc_putnl(rqstp->rq_res.head, RPC_AUTH_GSS);
723 	xdr_seq = htonl(seq);
724 
725 	iov.iov_base = &xdr_seq;
726 	iov.iov_len = sizeof(xdr_seq);
727 	xdr_buf_from_iov(&iov, &verf_data);
728 	p = rqstp->rq_res.head->iov_base + rqstp->rq_res.head->iov_len;
729 	mic.data = (u8 *)(p + 1);
730 	maj_stat = gss_get_mic(ctx_id, &verf_data, &mic);
731 	if (maj_stat != GSS_S_COMPLETE)
732 		return -1;
733 	*p++ = htonl(mic.len);
734 	memset((u8 *)p + mic.len, 0, round_up_to_quad(mic.len) - mic.len);
735 	p += XDR_QUADLEN(mic.len);
736 	if (!xdr_ressize_check(rqstp, p))
737 		return -1;
738 	return 0;
739 }
740 
741 struct gss_domain {
742 	struct auth_domain	h;
743 	u32			pseudoflavor;
744 };
745 
746 static struct auth_domain *
747 find_gss_auth_domain(struct gss_ctx *ctx, u32 svc)
748 {
749 	char *name;
750 
751 	name = gss_service_to_auth_domain_name(ctx->mech_type, svc);
752 	if (!name)
753 		return NULL;
754 	return auth_domain_find(name);
755 }
756 
757 static struct auth_ops svcauthops_gss;
758 
759 u32 svcauth_gss_flavor(struct auth_domain *dom)
760 {
761 	struct gss_domain *gd = container_of(dom, struct gss_domain, h);
762 
763 	return gd->pseudoflavor;
764 }
765 
766 EXPORT_SYMBOL_GPL(svcauth_gss_flavor);
767 
768 int
769 svcauth_gss_register_pseudoflavor(u32 pseudoflavor, char * name)
770 {
771 	struct gss_domain	*new;
772 	struct auth_domain	*test;
773 	int			stat = -ENOMEM;
774 
775 	new = kmalloc(sizeof(*new), GFP_KERNEL);
776 	if (!new)
777 		goto out;
778 	kref_init(&new->h.ref);
779 	new->h.name = kstrdup(name, GFP_KERNEL);
780 	if (!new->h.name)
781 		goto out_free_dom;
782 	new->h.flavour = &svcauthops_gss;
783 	new->pseudoflavor = pseudoflavor;
784 
785 	stat = 0;
786 	test = auth_domain_lookup(name, &new->h);
787 	if (test != &new->h) { /* Duplicate registration */
788 		auth_domain_put(test);
789 		kfree(new->h.name);
790 		goto out_free_dom;
791 	}
792 	return 0;
793 
794 out_free_dom:
795 	kfree(new);
796 out:
797 	return stat;
798 }
799 
800 EXPORT_SYMBOL_GPL(svcauth_gss_register_pseudoflavor);
801 
802 static inline int
803 read_u32_from_xdr_buf(struct xdr_buf *buf, int base, u32 *obj)
804 {
805 	__be32  raw;
806 	int     status;
807 
808 	status = read_bytes_from_xdr_buf(buf, base, &raw, sizeof(*obj));
809 	if (status)
810 		return status;
811 	*obj = ntohl(raw);
812 	return 0;
813 }
814 
815 /* It would be nice if this bit of code could be shared with the client.
816  * Obstacles:
817  *	The client shouldn't malloc(), would have to pass in own memory.
818  *	The server uses base of head iovec as read pointer, while the
819  *	client uses separate pointer. */
820 static int
821 unwrap_integ_data(struct svc_rqst *rqstp, struct xdr_buf *buf, u32 seq, struct gss_ctx *ctx)
822 {
823 	int stat = -EINVAL;
824 	u32 integ_len, maj_stat;
825 	struct xdr_netobj mic;
826 	struct xdr_buf integ_buf;
827 
828 	/* Did we already verify the signature on the original pass through? */
829 	if (rqstp->rq_deferred)
830 		return 0;
831 
832 	integ_len = svc_getnl(&buf->head[0]);
833 	if (integ_len & 3)
834 		return stat;
835 	if (integ_len > buf->len)
836 		return stat;
837 	if (xdr_buf_subsegment(buf, &integ_buf, 0, integ_len))
838 		BUG();
839 	/* copy out mic... */
840 	if (read_u32_from_xdr_buf(buf, integ_len, &mic.len))
841 		BUG();
842 	if (mic.len > RPC_MAX_AUTH_SIZE)
843 		return stat;
844 	mic.data = kmalloc(mic.len, GFP_KERNEL);
845 	if (!mic.data)
846 		return stat;
847 	if (read_bytes_from_xdr_buf(buf, integ_len + 4, mic.data, mic.len))
848 		goto out;
849 	maj_stat = gss_verify_mic(ctx, &integ_buf, &mic);
850 	if (maj_stat != GSS_S_COMPLETE)
851 		goto out;
852 	if (svc_getnl(&buf->head[0]) != seq)
853 		goto out;
854 	/* trim off the mic at the end before returning */
855 	xdr_buf_trim(buf, mic.len + 4);
856 	stat = 0;
857 out:
858 	kfree(mic.data);
859 	return stat;
860 }
861 
862 static inline int
863 total_buf_len(struct xdr_buf *buf)
864 {
865 	return buf->head[0].iov_len + buf->page_len + buf->tail[0].iov_len;
866 }
867 
868 static void
869 fix_priv_head(struct xdr_buf *buf, int pad)
870 {
871 	if (buf->page_len == 0) {
872 		/* We need to adjust head and buf->len in tandem in this
873 		 * case to make svc_defer() work--it finds the original
874 		 * buffer start using buf->len - buf->head[0].iov_len. */
875 		buf->head[0].iov_len -= pad;
876 	}
877 }
878 
879 static int
880 unwrap_priv_data(struct svc_rqst *rqstp, struct xdr_buf *buf, u32 seq, struct gss_ctx *ctx)
881 {
882 	u32 priv_len, maj_stat;
883 	int pad, saved_len, remaining_len, offset;
884 
885 	rqstp->rq_splice_ok = 0;
886 
887 	priv_len = svc_getnl(&buf->head[0]);
888 	if (rqstp->rq_deferred) {
889 		/* Already decrypted last time through! The sequence number
890 		 * check at out_seq is unnecessary but harmless: */
891 		goto out_seq;
892 	}
893 	/* buf->len is the number of bytes from the original start of the
894 	 * request to the end, where head[0].iov_len is just the bytes
895 	 * not yet read from the head, so these two values are different: */
896 	remaining_len = total_buf_len(buf);
897 	if (priv_len > remaining_len)
898 		return -EINVAL;
899 	pad = remaining_len - priv_len;
900 	buf->len -= pad;
901 	fix_priv_head(buf, pad);
902 
903 	/* Maybe it would be better to give gss_unwrap a length parameter: */
904 	saved_len = buf->len;
905 	buf->len = priv_len;
906 	maj_stat = gss_unwrap(ctx, 0, buf);
907 	pad = priv_len - buf->len;
908 	buf->len = saved_len;
909 	buf->len -= pad;
910 	/* The upper layers assume the buffer is aligned on 4-byte boundaries.
911 	 * In the krb5p case, at least, the data ends up offset, so we need to
912 	 * move it around. */
913 	/* XXX: This is very inefficient.  It would be better to either do
914 	 * this while we encrypt, or maybe in the receive code, if we can peak
915 	 * ahead and work out the service and mechanism there. */
916 	offset = buf->head[0].iov_len % 4;
917 	if (offset) {
918 		buf->buflen = RPCSVC_MAXPAYLOAD;
919 		xdr_shift_buf(buf, offset);
920 		fix_priv_head(buf, pad);
921 	}
922 	if (maj_stat != GSS_S_COMPLETE)
923 		return -EINVAL;
924 out_seq:
925 	if (svc_getnl(&buf->head[0]) != seq)
926 		return -EINVAL;
927 	return 0;
928 }
929 
930 struct gss_svc_data {
931 	/* decoded gss client cred: */
932 	struct rpc_gss_wire_cred	clcred;
933 	/* save a pointer to the beginning of the encoded verifier,
934 	 * for use in encryption/checksumming in svcauth_gss_release: */
935 	__be32				*verf_start;
936 	struct rsc			*rsci;
937 };
938 
939 static int
940 svcauth_gss_set_client(struct svc_rqst *rqstp)
941 {
942 	struct gss_svc_data *svcdata = rqstp->rq_auth_data;
943 	struct rsc *rsci = svcdata->rsci;
944 	struct rpc_gss_wire_cred *gc = &svcdata->clcred;
945 	int stat;
946 
947 	/*
948 	 * A gss export can be specified either by:
949 	 * 	export	*(sec=krb5,rw)
950 	 * or by
951 	 * 	export gss/krb5(rw)
952 	 * The latter is deprecated; but for backwards compatibility reasons
953 	 * the nfsd code will still fall back on trying it if the former
954 	 * doesn't work; so we try to make both available to nfsd, below.
955 	 */
956 	rqstp->rq_gssclient = find_gss_auth_domain(rsci->mechctx, gc->gc_svc);
957 	if (rqstp->rq_gssclient == NULL)
958 		return SVC_DENIED;
959 	stat = svcauth_unix_set_client(rqstp);
960 	if (stat == SVC_DROP || stat == SVC_CLOSE)
961 		return stat;
962 	return SVC_OK;
963 }
964 
965 static inline int
966 gss_write_init_verf(struct cache_detail *cd, struct svc_rqst *rqstp,
967 		struct xdr_netobj *out_handle, int *major_status)
968 {
969 	struct rsc *rsci;
970 	int        rc;
971 
972 	if (*major_status != GSS_S_COMPLETE)
973 		return gss_write_null_verf(rqstp);
974 	rsci = gss_svc_searchbyctx(cd, out_handle);
975 	if (rsci == NULL) {
976 		*major_status = GSS_S_NO_CONTEXT;
977 		return gss_write_null_verf(rqstp);
978 	}
979 	rc = gss_write_verf(rqstp, rsci->mechctx, GSS_SEQ_WIN);
980 	cache_put(&rsci->h, cd);
981 	return rc;
982 }
983 
984 static inline int
985 gss_read_verf(struct rpc_gss_wire_cred *gc,
986 	      struct kvec *argv, __be32 *authp,
987 	      struct xdr_netobj *in_handle,
988 	      struct xdr_netobj *in_token)
989 {
990 	struct xdr_netobj tmpobj;
991 
992 	/* Read the verifier; should be NULL: */
993 	*authp = rpc_autherr_badverf;
994 	if (argv->iov_len < 2 * 4)
995 		return SVC_DENIED;
996 	if (svc_getnl(argv) != RPC_AUTH_NULL)
997 		return SVC_DENIED;
998 	if (svc_getnl(argv) != 0)
999 		return SVC_DENIED;
1000 	/* Martial context handle and token for upcall: */
1001 	*authp = rpc_autherr_badcred;
1002 	if (gc->gc_proc == RPC_GSS_PROC_INIT && gc->gc_ctx.len != 0)
1003 		return SVC_DENIED;
1004 	if (dup_netobj(in_handle, &gc->gc_ctx))
1005 		return SVC_CLOSE;
1006 	*authp = rpc_autherr_badverf;
1007 	if (svc_safe_getnetobj(argv, &tmpobj)) {
1008 		kfree(in_handle->data);
1009 		return SVC_DENIED;
1010 	}
1011 	if (dup_netobj(in_token, &tmpobj)) {
1012 		kfree(in_handle->data);
1013 		return SVC_CLOSE;
1014 	}
1015 
1016 	return 0;
1017 }
1018 
1019 static inline int
1020 gss_write_resv(struct kvec *resv, size_t size_limit,
1021 	       struct xdr_netobj *out_handle, struct xdr_netobj *out_token,
1022 	       int major_status, int minor_status)
1023 {
1024 	if (resv->iov_len + 4 > size_limit)
1025 		return -1;
1026 	svc_putnl(resv, RPC_SUCCESS);
1027 	if (svc_safe_putnetobj(resv, out_handle))
1028 		return -1;
1029 	if (resv->iov_len + 3 * 4 > size_limit)
1030 		return -1;
1031 	svc_putnl(resv, major_status);
1032 	svc_putnl(resv, minor_status);
1033 	svc_putnl(resv, GSS_SEQ_WIN);
1034 	if (svc_safe_putnetobj(resv, out_token))
1035 		return -1;
1036 	return 0;
1037 }
1038 
1039 /*
1040  * Having read the cred already and found we're in the context
1041  * initiation case, read the verifier and initiate (or check the results
1042  * of) upcalls to userspace for help with context initiation.  If
1043  * the upcall results are available, write the verifier and result.
1044  * Otherwise, drop the request pending an answer to the upcall.
1045  */
1046 static int svcauth_gss_handle_init(struct svc_rqst *rqstp,
1047 			struct rpc_gss_wire_cred *gc, __be32 *authp)
1048 {
1049 	struct kvec *argv = &rqstp->rq_arg.head[0];
1050 	struct kvec *resv = &rqstp->rq_res.head[0];
1051 	struct rsi *rsip, rsikey;
1052 	int ret;
1053 	struct sunrpc_net *sn = net_generic(rqstp->rq_xprt->xpt_net, sunrpc_net_id);
1054 
1055 	memset(&rsikey, 0, sizeof(rsikey));
1056 	ret = gss_read_verf(gc, argv, authp,
1057 			    &rsikey.in_handle, &rsikey.in_token);
1058 	if (ret)
1059 		return ret;
1060 
1061 	/* Perform upcall, or find upcall result: */
1062 	rsip = rsi_lookup(sn->rsi_cache, &rsikey);
1063 	rsi_free(&rsikey);
1064 	if (!rsip)
1065 		return SVC_CLOSE;
1066 	if (cache_check(sn->rsi_cache, &rsip->h, &rqstp->rq_chandle) < 0)
1067 		/* No upcall result: */
1068 		return SVC_CLOSE;
1069 
1070 	ret = SVC_CLOSE;
1071 	/* Got an answer to the upcall; use it: */
1072 	if (gss_write_init_verf(sn->rsc_cache, rqstp,
1073 				&rsip->out_handle, &rsip->major_status))
1074 		goto out;
1075 	if (gss_write_resv(resv, PAGE_SIZE,
1076 			   &rsip->out_handle, &rsip->out_token,
1077 			   rsip->major_status, rsip->minor_status))
1078 		goto out;
1079 
1080 	ret = SVC_COMPLETE;
1081 out:
1082 	cache_put(&rsip->h, sn->rsi_cache);
1083 	return ret;
1084 }
1085 
1086 /*
1087  * Accept an rpcsec packet.
1088  * If context establishment, punt to user space
1089  * If data exchange, verify/decrypt
1090  * If context destruction, handle here
1091  * In the context establishment and destruction case we encode
1092  * response here and return SVC_COMPLETE.
1093  */
1094 static int
1095 svcauth_gss_accept(struct svc_rqst *rqstp, __be32 *authp)
1096 {
1097 	struct kvec	*argv = &rqstp->rq_arg.head[0];
1098 	struct kvec	*resv = &rqstp->rq_res.head[0];
1099 	u32		crlen;
1100 	struct gss_svc_data *svcdata = rqstp->rq_auth_data;
1101 	struct rpc_gss_wire_cred *gc;
1102 	struct rsc	*rsci = NULL;
1103 	__be32		*rpcstart;
1104 	__be32		*reject_stat = resv->iov_base + resv->iov_len;
1105 	int		ret;
1106 	struct sunrpc_net *sn = net_generic(rqstp->rq_xprt->xpt_net, sunrpc_net_id);
1107 
1108 	dprintk("RPC:       svcauth_gss: argv->iov_len = %zd\n",
1109 			argv->iov_len);
1110 
1111 	*authp = rpc_autherr_badcred;
1112 	if (!svcdata)
1113 		svcdata = kmalloc(sizeof(*svcdata), GFP_KERNEL);
1114 	if (!svcdata)
1115 		goto auth_err;
1116 	rqstp->rq_auth_data = svcdata;
1117 	svcdata->verf_start = NULL;
1118 	svcdata->rsci = NULL;
1119 	gc = &svcdata->clcred;
1120 
1121 	/* start of rpc packet is 7 u32's back from here:
1122 	 * xid direction rpcversion prog vers proc flavour
1123 	 */
1124 	rpcstart = argv->iov_base;
1125 	rpcstart -= 7;
1126 
1127 	/* credential is:
1128 	 *   version(==1), proc(0,1,2,3), seq, service (1,2,3), handle
1129 	 * at least 5 u32s, and is preceded by length, so that makes 6.
1130 	 */
1131 
1132 	if (argv->iov_len < 5 * 4)
1133 		goto auth_err;
1134 	crlen = svc_getnl(argv);
1135 	if (svc_getnl(argv) != RPC_GSS_VERSION)
1136 		goto auth_err;
1137 	gc->gc_proc = svc_getnl(argv);
1138 	gc->gc_seq = svc_getnl(argv);
1139 	gc->gc_svc = svc_getnl(argv);
1140 	if (svc_safe_getnetobj(argv, &gc->gc_ctx))
1141 		goto auth_err;
1142 	if (crlen != round_up_to_quad(gc->gc_ctx.len) + 5 * 4)
1143 		goto auth_err;
1144 
1145 	if ((gc->gc_proc != RPC_GSS_PROC_DATA) && (rqstp->rq_proc != 0))
1146 		goto auth_err;
1147 
1148 	*authp = rpc_autherr_badverf;
1149 	switch (gc->gc_proc) {
1150 	case RPC_GSS_PROC_INIT:
1151 	case RPC_GSS_PROC_CONTINUE_INIT:
1152 		return svcauth_gss_handle_init(rqstp, gc, authp);
1153 	case RPC_GSS_PROC_DATA:
1154 	case RPC_GSS_PROC_DESTROY:
1155 		/* Look up the context, and check the verifier: */
1156 		*authp = rpcsec_gsserr_credproblem;
1157 		rsci = gss_svc_searchbyctx(sn->rsc_cache, &gc->gc_ctx);
1158 		if (!rsci)
1159 			goto auth_err;
1160 		switch (gss_verify_header(rqstp, rsci, rpcstart, gc, authp)) {
1161 		case SVC_OK:
1162 			break;
1163 		case SVC_DENIED:
1164 			goto auth_err;
1165 		case SVC_DROP:
1166 			goto drop;
1167 		}
1168 		break;
1169 	default:
1170 		*authp = rpc_autherr_rejectedcred;
1171 		goto auth_err;
1172 	}
1173 
1174 	/* now act upon the command: */
1175 	switch (gc->gc_proc) {
1176 	case RPC_GSS_PROC_DESTROY:
1177 		if (gss_write_verf(rqstp, rsci->mechctx, gc->gc_seq))
1178 			goto auth_err;
1179 		rsci->h.expiry_time = get_seconds();
1180 		set_bit(CACHE_NEGATIVE, &rsci->h.flags);
1181 		if (resv->iov_len + 4 > PAGE_SIZE)
1182 			goto drop;
1183 		svc_putnl(resv, RPC_SUCCESS);
1184 		goto complete;
1185 	case RPC_GSS_PROC_DATA:
1186 		*authp = rpcsec_gsserr_ctxproblem;
1187 		svcdata->verf_start = resv->iov_base + resv->iov_len;
1188 		if (gss_write_verf(rqstp, rsci->mechctx, gc->gc_seq))
1189 			goto auth_err;
1190 		rqstp->rq_cred = rsci->cred;
1191 		get_group_info(rsci->cred.cr_group_info);
1192 		*authp = rpc_autherr_badcred;
1193 		switch (gc->gc_svc) {
1194 		case RPC_GSS_SVC_NONE:
1195 			break;
1196 		case RPC_GSS_SVC_INTEGRITY:
1197 			/* placeholders for length and seq. number: */
1198 			svc_putnl(resv, 0);
1199 			svc_putnl(resv, 0);
1200 			if (unwrap_integ_data(rqstp, &rqstp->rq_arg,
1201 					gc->gc_seq, rsci->mechctx))
1202 				goto garbage_args;
1203 			break;
1204 		case RPC_GSS_SVC_PRIVACY:
1205 			/* placeholders for length and seq. number: */
1206 			svc_putnl(resv, 0);
1207 			svc_putnl(resv, 0);
1208 			if (unwrap_priv_data(rqstp, &rqstp->rq_arg,
1209 					gc->gc_seq, rsci->mechctx))
1210 				goto garbage_args;
1211 			break;
1212 		default:
1213 			goto auth_err;
1214 		}
1215 		svcdata->rsci = rsci;
1216 		cache_get(&rsci->h);
1217 		rqstp->rq_cred.cr_flavor = gss_svc_to_pseudoflavor(
1218 					rsci->mechctx->mech_type, gc->gc_svc);
1219 		ret = SVC_OK;
1220 		goto out;
1221 	}
1222 garbage_args:
1223 	ret = SVC_GARBAGE;
1224 	goto out;
1225 auth_err:
1226 	/* Restore write pointer to its original value: */
1227 	xdr_ressize_check(rqstp, reject_stat);
1228 	ret = SVC_DENIED;
1229 	goto out;
1230 complete:
1231 	ret = SVC_COMPLETE;
1232 	goto out;
1233 drop:
1234 	ret = SVC_DROP;
1235 out:
1236 	if (rsci)
1237 		cache_put(&rsci->h, sn->rsc_cache);
1238 	return ret;
1239 }
1240 
1241 static __be32 *
1242 svcauth_gss_prepare_to_wrap(struct xdr_buf *resbuf, struct gss_svc_data *gsd)
1243 {
1244 	__be32 *p;
1245 	u32 verf_len;
1246 
1247 	p = gsd->verf_start;
1248 	gsd->verf_start = NULL;
1249 
1250 	/* If the reply stat is nonzero, don't wrap: */
1251 	if (*(p-1) != rpc_success)
1252 		return NULL;
1253 	/* Skip the verifier: */
1254 	p += 1;
1255 	verf_len = ntohl(*p++);
1256 	p += XDR_QUADLEN(verf_len);
1257 	/* move accept_stat to right place: */
1258 	memcpy(p, p + 2, 4);
1259 	/* Also don't wrap if the accept stat is nonzero: */
1260 	if (*p != rpc_success) {
1261 		resbuf->head[0].iov_len -= 2 * 4;
1262 		return NULL;
1263 	}
1264 	p++;
1265 	return p;
1266 }
1267 
1268 static inline int
1269 svcauth_gss_wrap_resp_integ(struct svc_rqst *rqstp)
1270 {
1271 	struct gss_svc_data *gsd = (struct gss_svc_data *)rqstp->rq_auth_data;
1272 	struct rpc_gss_wire_cred *gc = &gsd->clcred;
1273 	struct xdr_buf *resbuf = &rqstp->rq_res;
1274 	struct xdr_buf integ_buf;
1275 	struct xdr_netobj mic;
1276 	struct kvec *resv;
1277 	__be32 *p;
1278 	int integ_offset, integ_len;
1279 	int stat = -EINVAL;
1280 
1281 	p = svcauth_gss_prepare_to_wrap(resbuf, gsd);
1282 	if (p == NULL)
1283 		goto out;
1284 	integ_offset = (u8 *)(p + 1) - (u8 *)resbuf->head[0].iov_base;
1285 	integ_len = resbuf->len - integ_offset;
1286 	BUG_ON(integ_len % 4);
1287 	*p++ = htonl(integ_len);
1288 	*p++ = htonl(gc->gc_seq);
1289 	if (xdr_buf_subsegment(resbuf, &integ_buf, integ_offset,
1290 				integ_len))
1291 		BUG();
1292 	if (resbuf->tail[0].iov_base == NULL) {
1293 		if (resbuf->head[0].iov_len + RPC_MAX_AUTH_SIZE > PAGE_SIZE)
1294 			goto out_err;
1295 		resbuf->tail[0].iov_base = resbuf->head[0].iov_base
1296 						+ resbuf->head[0].iov_len;
1297 		resbuf->tail[0].iov_len = 0;
1298 		resv = &resbuf->tail[0];
1299 	} else {
1300 		resv = &resbuf->tail[0];
1301 	}
1302 	mic.data = (u8 *)resv->iov_base + resv->iov_len + 4;
1303 	if (gss_get_mic(gsd->rsci->mechctx, &integ_buf, &mic))
1304 		goto out_err;
1305 	svc_putnl(resv, mic.len);
1306 	memset(mic.data + mic.len, 0,
1307 			round_up_to_quad(mic.len) - mic.len);
1308 	resv->iov_len += XDR_QUADLEN(mic.len) << 2;
1309 	/* not strictly required: */
1310 	resbuf->len += XDR_QUADLEN(mic.len) << 2;
1311 	BUG_ON(resv->iov_len > PAGE_SIZE);
1312 out:
1313 	stat = 0;
1314 out_err:
1315 	return stat;
1316 }
1317 
1318 static inline int
1319 svcauth_gss_wrap_resp_priv(struct svc_rqst *rqstp)
1320 {
1321 	struct gss_svc_data *gsd = (struct gss_svc_data *)rqstp->rq_auth_data;
1322 	struct rpc_gss_wire_cred *gc = &gsd->clcred;
1323 	struct xdr_buf *resbuf = &rqstp->rq_res;
1324 	struct page **inpages = NULL;
1325 	__be32 *p, *len;
1326 	int offset;
1327 	int pad;
1328 
1329 	p = svcauth_gss_prepare_to_wrap(resbuf, gsd);
1330 	if (p == NULL)
1331 		return 0;
1332 	len = p++;
1333 	offset = (u8 *)p - (u8 *)resbuf->head[0].iov_base;
1334 	*p++ = htonl(gc->gc_seq);
1335 	inpages = resbuf->pages;
1336 	/* XXX: Would be better to write some xdr helper functions for
1337 	 * nfs{2,3,4}xdr.c that place the data right, instead of copying: */
1338 
1339 	/*
1340 	 * If there is currently tail data, make sure there is
1341 	 * room for the head, tail, and 2 * RPC_MAX_AUTH_SIZE in
1342 	 * the page, and move the current tail data such that
1343 	 * there is RPC_MAX_AUTH_SIZE slack space available in
1344 	 * both the head and tail.
1345 	 */
1346 	if (resbuf->tail[0].iov_base) {
1347 		BUG_ON(resbuf->tail[0].iov_base >= resbuf->head[0].iov_base
1348 							+ PAGE_SIZE);
1349 		BUG_ON(resbuf->tail[0].iov_base < resbuf->head[0].iov_base);
1350 		if (resbuf->tail[0].iov_len + resbuf->head[0].iov_len
1351 				+ 2 * RPC_MAX_AUTH_SIZE > PAGE_SIZE)
1352 			return -ENOMEM;
1353 		memmove(resbuf->tail[0].iov_base + RPC_MAX_AUTH_SIZE,
1354 			resbuf->tail[0].iov_base,
1355 			resbuf->tail[0].iov_len);
1356 		resbuf->tail[0].iov_base += RPC_MAX_AUTH_SIZE;
1357 	}
1358 	/*
1359 	 * If there is no current tail data, make sure there is
1360 	 * room for the head data, and 2 * RPC_MAX_AUTH_SIZE in the
1361 	 * allotted page, and set up tail information such that there
1362 	 * is RPC_MAX_AUTH_SIZE slack space available in both the
1363 	 * head and tail.
1364 	 */
1365 	if (resbuf->tail[0].iov_base == NULL) {
1366 		if (resbuf->head[0].iov_len + 2*RPC_MAX_AUTH_SIZE > PAGE_SIZE)
1367 			return -ENOMEM;
1368 		resbuf->tail[0].iov_base = resbuf->head[0].iov_base
1369 			+ resbuf->head[0].iov_len + RPC_MAX_AUTH_SIZE;
1370 		resbuf->tail[0].iov_len = 0;
1371 	}
1372 	if (gss_wrap(gsd->rsci->mechctx, offset, resbuf, inpages))
1373 		return -ENOMEM;
1374 	*len = htonl(resbuf->len - offset);
1375 	pad = 3 - ((resbuf->len - offset - 1)&3);
1376 	p = (__be32 *)(resbuf->tail[0].iov_base + resbuf->tail[0].iov_len);
1377 	memset(p, 0, pad);
1378 	resbuf->tail[0].iov_len += pad;
1379 	resbuf->len += pad;
1380 	return 0;
1381 }
1382 
1383 static int
1384 svcauth_gss_release(struct svc_rqst *rqstp)
1385 {
1386 	struct gss_svc_data *gsd = (struct gss_svc_data *)rqstp->rq_auth_data;
1387 	struct rpc_gss_wire_cred *gc = &gsd->clcred;
1388 	struct xdr_buf *resbuf = &rqstp->rq_res;
1389 	int stat = -EINVAL;
1390 	struct sunrpc_net *sn = net_generic(rqstp->rq_xprt->xpt_net, sunrpc_net_id);
1391 
1392 	if (gc->gc_proc != RPC_GSS_PROC_DATA)
1393 		goto out;
1394 	/* Release can be called twice, but we only wrap once. */
1395 	if (gsd->verf_start == NULL)
1396 		goto out;
1397 	/* normally not set till svc_send, but we need it here: */
1398 	/* XXX: what for?  Do we mess it up the moment we call svc_putu32
1399 	 * or whatever? */
1400 	resbuf->len = total_buf_len(resbuf);
1401 	switch (gc->gc_svc) {
1402 	case RPC_GSS_SVC_NONE:
1403 		break;
1404 	case RPC_GSS_SVC_INTEGRITY:
1405 		stat = svcauth_gss_wrap_resp_integ(rqstp);
1406 		if (stat)
1407 			goto out_err;
1408 		break;
1409 	case RPC_GSS_SVC_PRIVACY:
1410 		stat = svcauth_gss_wrap_resp_priv(rqstp);
1411 		if (stat)
1412 			goto out_err;
1413 		break;
1414 	/*
1415 	 * For any other gc_svc value, svcauth_gss_accept() already set
1416 	 * the auth_error appropriately; just fall through:
1417 	 */
1418 	}
1419 
1420 out:
1421 	stat = 0;
1422 out_err:
1423 	if (rqstp->rq_client)
1424 		auth_domain_put(rqstp->rq_client);
1425 	rqstp->rq_client = NULL;
1426 	if (rqstp->rq_gssclient)
1427 		auth_domain_put(rqstp->rq_gssclient);
1428 	rqstp->rq_gssclient = NULL;
1429 	if (rqstp->rq_cred.cr_group_info)
1430 		put_group_info(rqstp->rq_cred.cr_group_info);
1431 	rqstp->rq_cred.cr_group_info = NULL;
1432 	if (gsd->rsci)
1433 		cache_put(&gsd->rsci->h, sn->rsc_cache);
1434 	gsd->rsci = NULL;
1435 
1436 	return stat;
1437 }
1438 
1439 static void
1440 svcauth_gss_domain_release(struct auth_domain *dom)
1441 {
1442 	struct gss_domain *gd = container_of(dom, struct gss_domain, h);
1443 
1444 	kfree(dom->name);
1445 	kfree(gd);
1446 }
1447 
1448 static struct auth_ops svcauthops_gss = {
1449 	.name		= "rpcsec_gss",
1450 	.owner		= THIS_MODULE,
1451 	.flavour	= RPC_AUTH_GSS,
1452 	.accept		= svcauth_gss_accept,
1453 	.release	= svcauth_gss_release,
1454 	.domain_release = svcauth_gss_domain_release,
1455 	.set_client	= svcauth_gss_set_client,
1456 };
1457 
1458 static int rsi_cache_create_net(struct net *net)
1459 {
1460 	struct sunrpc_net *sn = net_generic(net, sunrpc_net_id);
1461 	struct cache_detail *cd;
1462 	int err;
1463 
1464 	cd = cache_create_net(&rsi_cache_template, net);
1465 	if (IS_ERR(cd))
1466 		return PTR_ERR(cd);
1467 	err = cache_register_net(cd, net);
1468 	if (err) {
1469 		cache_destroy_net(cd, net);
1470 		return err;
1471 	}
1472 	sn->rsi_cache = cd;
1473 	return 0;
1474 }
1475 
1476 static void rsi_cache_destroy_net(struct net *net)
1477 {
1478 	struct sunrpc_net *sn = net_generic(net, sunrpc_net_id);
1479 	struct cache_detail *cd = sn->rsi_cache;
1480 
1481 	sn->rsi_cache = NULL;
1482 	cache_purge(cd);
1483 	cache_unregister_net(cd, net);
1484 	cache_destroy_net(cd, net);
1485 }
1486 
1487 static int rsc_cache_create_net(struct net *net)
1488 {
1489 	struct sunrpc_net *sn = net_generic(net, sunrpc_net_id);
1490 	struct cache_detail *cd;
1491 	int err;
1492 
1493 	cd = cache_create_net(&rsc_cache_template, net);
1494 	if (IS_ERR(cd))
1495 		return PTR_ERR(cd);
1496 	err = cache_register_net(cd, net);
1497 	if (err) {
1498 		cache_destroy_net(cd, net);
1499 		return err;
1500 	}
1501 	sn->rsc_cache = cd;
1502 	return 0;
1503 }
1504 
1505 static void rsc_cache_destroy_net(struct net *net)
1506 {
1507 	struct sunrpc_net *sn = net_generic(net, sunrpc_net_id);
1508 	struct cache_detail *cd = sn->rsc_cache;
1509 
1510 	sn->rsc_cache = NULL;
1511 	cache_purge(cd);
1512 	cache_unregister_net(cd, net);
1513 	cache_destroy_net(cd, net);
1514 }
1515 
1516 int
1517 gss_svc_init_net(struct net *net)
1518 {
1519 	int rv;
1520 
1521 	rv = rsc_cache_create_net(net);
1522 	if (rv)
1523 		return rv;
1524 	rv = rsi_cache_create_net(net);
1525 	if (rv)
1526 		goto out1;
1527 	return 0;
1528 out1:
1529 	rsc_cache_destroy_net(net);
1530 	return rv;
1531 }
1532 
1533 void
1534 gss_svc_shutdown_net(struct net *net)
1535 {
1536 	rsi_cache_destroy_net(net);
1537 	rsc_cache_destroy_net(net);
1538 }
1539 
1540 int
1541 gss_svc_init(void)
1542 {
1543 	return svc_auth_register(RPC_AUTH_GSS, &svcauthops_gss);
1544 }
1545 
1546 void
1547 gss_svc_shutdown(void)
1548 {
1549 	svc_auth_unregister(RPC_AUTH_GSS);
1550 }
1551