xref: /linux/net/ipv6/esp6.c (revision 7c7d5e9d7e3942ba5aec9847f61a6e76d7773191)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C)2002 USAGI/WIDE Project
4  *
5  * Authors
6  *
7  *	Mitsuru KANDA @USAGI       : IPv6 Support
8  *	Kazunori MIYAZAWA @USAGI   :
9  *	Kunihiro Ishiguro <kunihiro@ipinfusion.com>
10  *
11  *	This file is derived from net/ipv4/esp.c
12  */
13 
14 #define pr_fmt(fmt) "IPv6: " fmt
15 
16 #include <crypto/aead.h>
17 #include <crypto/authenc.h>
18 #include <linux/err.h>
19 #include <linux/module.h>
20 #include <net/ip.h>
21 #include <net/xfrm.h>
22 #include <net/esp.h>
23 #include <linux/scatterlist.h>
24 #include <linux/kernel.h>
25 #include <linux/pfkeyv2.h>
26 #include <linux/random.h>
27 #include <linux/slab.h>
28 #include <linux/spinlock.h>
29 #include <net/ip6_checksum.h>
30 #include <net/ip6_route.h>
31 #include <net/icmp.h>
32 #include <net/ipv6.h>
33 #include <net/protocol.h>
34 #include <net/udp.h>
35 #include <linux/icmpv6.h>
36 #include <net/tcp.h>
37 #include <net/espintcp.h>
38 #include <net/inet6_hashtables.h>
39 #include <linux/skbuff_ref.h>
40 
41 #include <linux/highmem.h>
42 
43 struct esp_skb_cb {
44 	struct xfrm_skb_cb xfrm;
45 	void *tmp;
46 };
47 
48 struct esp_output_extra {
49 	__be32 seqhi;
50 	u32 esphoff;
51 };
52 
53 #define ESP_SKB_CB(__skb) ((struct esp_skb_cb *)&((__skb)->cb[0]))
54 
55 /*
56  * Allocate an AEAD request structure with extra space for SG and IV.
57  *
58  * For alignment considerations the upper 32 bits of the sequence number are
59  * placed at the front, if present. Followed by the IV, the request and finally
60  * the SG list.
61  *
62  * TODO: Use spare space in skb for this where possible.
63  */
64 static void *esp_alloc_tmp(struct crypto_aead *aead, int nfrags, int seqihlen)
65 {
66 	unsigned int len;
67 
68 	len = seqihlen;
69 
70 	len += crypto_aead_ivsize(aead);
71 
72 	if (len) {
73 		len += crypto_aead_alignmask(aead) &
74 		       ~(crypto_tfm_ctx_alignment() - 1);
75 		len = ALIGN(len, crypto_tfm_ctx_alignment());
76 	}
77 
78 	len += sizeof(struct aead_request) + crypto_aead_reqsize(aead);
79 	len = ALIGN(len, __alignof__(struct scatterlist));
80 
81 	len += sizeof(struct scatterlist) * nfrags;
82 
83 	return kmalloc(len, GFP_ATOMIC);
84 }
85 
86 static inline void *esp_tmp_extra(void *tmp)
87 {
88 	return PTR_ALIGN(tmp, __alignof__(struct esp_output_extra));
89 }
90 
91 static inline u8 *esp_tmp_iv(struct crypto_aead *aead, void *tmp, int seqhilen)
92 {
93 	return crypto_aead_ivsize(aead) ?
94 	       PTR_ALIGN((u8 *)tmp + seqhilen,
95 			 crypto_aead_alignmask(aead) + 1) : tmp + seqhilen;
96 }
97 
98 static inline struct aead_request *esp_tmp_req(struct crypto_aead *aead, u8 *iv)
99 {
100 	struct aead_request *req;
101 
102 	req = (void *)PTR_ALIGN(iv + crypto_aead_ivsize(aead),
103 				crypto_tfm_ctx_alignment());
104 	aead_request_set_tfm(req, aead);
105 	return req;
106 }
107 
108 static inline struct scatterlist *esp_req_sg(struct crypto_aead *aead,
109 					     struct aead_request *req)
110 {
111 	return (void *)ALIGN((unsigned long)(req + 1) +
112 			     crypto_aead_reqsize(aead),
113 			     __alignof__(struct scatterlist));
114 }
115 
116 static void esp_ssg_unref(struct xfrm_state *x, void *tmp, struct sk_buff *skb, bool already_unref)
117 {
118 	struct crypto_aead *aead = x->data;
119 	int extralen = 0;
120 	u8 *iv;
121 	struct aead_request *req;
122 	struct scatterlist *sg;
123 
124 	if (x->props.flags & XFRM_STATE_ESN)
125 		extralen += sizeof(struct esp_output_extra);
126 
127 	iv = esp_tmp_iv(aead, tmp, extralen);
128 	req = esp_tmp_req(aead, iv);
129 
130 	/* Unref skb_frag_pages in the src scatterlist if necessary.
131 	 * Skip the first sg which comes from skb->data.
132 	 */
133 	if (already_unref || req->src != req->dst) {
134 		struct scatterlist *src = already_unref ? esp_req_sg(aead, req) : req->src;
135 
136 		for (sg = sg_next(src); sg; sg = sg_next(sg))
137 			skb_page_unref(page_to_netmem(sg_page(sg)),
138 				       skb->pp_recycle);
139 	}
140 }
141 
142 #ifdef CONFIG_INET6_ESPINTCP
143 static struct sock *esp6_find_tcp_sk(struct xfrm_state *x)
144 {
145 	struct xfrm_encap_tmpl *encap = x->encap;
146 	struct net *net = xs_net(x);
147 	__be16 sport, dport;
148 	struct sock *sk;
149 
150 	spin_lock_bh(&x->lock);
151 	sport = encap->encap_sport;
152 	dport = encap->encap_dport;
153 	spin_unlock_bh(&x->lock);
154 
155 	sk = __inet6_lookup_established(net, &x->id.daddr.in6, dport,
156 					&x->props.saddr.in6, ntohs(sport), 0, 0);
157 	if (!sk)
158 		return ERR_PTR(-ENOENT);
159 
160 	if (!tcp_is_ulp_esp(sk)) {
161 		sock_put(sk);
162 		return ERR_PTR(-EINVAL);
163 	}
164 
165 	return sk;
166 }
167 
168 static int esp_output_tcp_finish(struct xfrm_state *x, struct sk_buff *skb)
169 {
170 	struct sock *sk;
171 	int err;
172 
173 	rcu_read_lock();
174 
175 	sk = esp6_find_tcp_sk(x);
176 	err = PTR_ERR_OR_ZERO(sk);
177 	if (err) {
178 		kfree_skb(skb);
179 		goto out;
180 	}
181 
182 	bh_lock_sock(sk);
183 	if (sock_owned_by_user(sk))
184 		err = espintcp_queue_out(sk, skb);
185 	else
186 		err = espintcp_push_skb(sk, skb);
187 	bh_unlock_sock(sk);
188 
189 	sock_put(sk);
190 
191 out:
192 	rcu_read_unlock();
193 	return err;
194 }
195 
196 static int esp_output_tcp_encap_cb(struct net *net, struct sock *sk,
197 				   struct sk_buff *skb)
198 {
199 	struct dst_entry *dst = skb_dst(skb);
200 	struct xfrm_state *x = dst->xfrm;
201 
202 	return esp_output_tcp_finish(x, skb);
203 }
204 
205 static int esp_output_tail_tcp(struct xfrm_state *x, struct sk_buff *skb)
206 {
207 	int err;
208 
209 	local_bh_disable();
210 	err = xfrm_trans_queue_net(xs_net(x), skb, esp_output_tcp_encap_cb);
211 	local_bh_enable();
212 
213 	/* EINPROGRESS just happens to do the right thing.  It
214 	 * actually means that the skb has been consumed and
215 	 * isn't coming back.
216 	 */
217 	return err ?: -EINPROGRESS;
218 }
219 #else
220 static int esp_output_tail_tcp(struct xfrm_state *x, struct sk_buff *skb)
221 {
222 	WARN_ON(1);
223 	return -EOPNOTSUPP;
224 }
225 #endif
226 
227 static void esp_output_encap_csum(struct sk_buff *skb)
228 {
229 	/* UDP encap with IPv6 requires a valid checksum */
230 	if (*skb_mac_header(skb) == IPPROTO_UDP) {
231 		struct udphdr *uh = udp_hdr(skb);
232 		struct ipv6hdr *ip6h = ipv6_hdr(skb);
233 		/* esp6_output_udp_encap limits len to U16_MAX. */
234 		int len = udp_get_len_short(uh);
235 		unsigned int offset = skb_transport_offset(skb);
236 		__wsum csum = skb_checksum(skb, offset, skb->len - offset, 0);
237 
238 		uh->check = csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr,
239 					    len, IPPROTO_UDP, csum);
240 		if (uh->check == 0)
241 			uh->check = CSUM_MANGLED_0;
242 	}
243 }
244 
245 static void esp_output_done(void *data, int err)
246 {
247 	struct sk_buff *skb = data;
248 	struct xfrm_offload *xo = xfrm_offload(skb);
249 	void *tmp;
250 	struct xfrm_state *x;
251 
252 	if (xo && (xo->flags & XFRM_DEV_RESUME)) {
253 		struct sec_path *sp = skb_sec_path(skb);
254 
255 		x = sp->xvec[sp->len - 1];
256 	} else {
257 		x = skb_dst(skb)->xfrm;
258 	}
259 
260 	tmp = ESP_SKB_CB(skb)->tmp;
261 	esp_ssg_unref(x, tmp, skb, false);
262 	kfree(tmp);
263 
264 	esp_output_encap_csum(skb);
265 
266 	if (xo && (xo->flags & XFRM_DEV_RESUME)) {
267 		if (err) {
268 			XFRM_INC_STATS(xs_net(x), LINUX_MIB_XFRMOUTSTATEPROTOERROR);
269 			kfree_skb(skb);
270 			return;
271 		}
272 
273 		skb_push(skb, skb->data - skb_mac_header(skb));
274 		secpath_reset(skb);
275 		xfrm_dev_resume(skb);
276 	} else {
277 		if (!err &&
278 		    x->encap && x->encap->encap_type == TCP_ENCAP_ESPINTCP) {
279 			err = esp_output_tail_tcp(x, skb);
280 			if (err != -EINPROGRESS)
281 				kfree_skb(skb);
282 		} else {
283 			xfrm_output_resume(skb_to_full_sk(skb), skb, err);
284 		}
285 	}
286 }
287 
288 /* Move ESP header back into place. */
289 static void esp_restore_header(struct sk_buff *skb, unsigned int offset)
290 {
291 	struct ip_esp_hdr *esph = (void *)(skb->data + offset);
292 	void *tmp = ESP_SKB_CB(skb)->tmp;
293 	__be32 *seqhi = esp_tmp_extra(tmp);
294 
295 	esph->seq_no = esph->spi;
296 	esph->spi = *seqhi;
297 }
298 
299 static void esp_output_restore_header(struct sk_buff *skb)
300 {
301 	void *tmp = ESP_SKB_CB(skb)->tmp;
302 	struct esp_output_extra *extra = esp_tmp_extra(tmp);
303 
304 	esp_restore_header(skb, skb_transport_offset(skb) + extra->esphoff -
305 				sizeof(__be32));
306 }
307 
308 static struct ip_esp_hdr *esp_output_set_esn(struct sk_buff *skb,
309 					     struct xfrm_state *x,
310 					     struct ip_esp_hdr *esph,
311 					     struct esp_output_extra *extra)
312 {
313 	/* For ESN we move the header forward by 4 bytes to
314 	 * accommodate the high bits.  We will move it back after
315 	 * encryption.
316 	 */
317 	if ((x->props.flags & XFRM_STATE_ESN)) {
318 		__u32 seqhi;
319 		struct xfrm_offload *xo = xfrm_offload(skb);
320 
321 		if (xo)
322 			seqhi = xo->seq.hi;
323 		else
324 			seqhi = XFRM_SKB_CB(skb)->seq.output.hi;
325 
326 		extra->esphoff = (unsigned char *)esph -
327 				 skb_transport_header(skb);
328 		esph = (struct ip_esp_hdr *)((unsigned char *)esph - 4);
329 		extra->seqhi = esph->spi;
330 		esph->seq_no = htonl(seqhi);
331 	}
332 
333 	esph->spi = x->id.spi;
334 
335 	return esph;
336 }
337 
338 static void esp_output_done_esn(void *data, int err)
339 {
340 	struct sk_buff *skb = data;
341 
342 	esp_output_restore_header(skb);
343 	esp_output_done(data, err);
344 }
345 
346 static struct ip_esp_hdr *esp6_output_udp_encap(struct sk_buff *skb,
347 					       int encap_type,
348 					       struct esp_info *esp,
349 					       __be16 sport,
350 					       __be16 dport)
351 {
352 	struct udphdr *uh;
353 	unsigned int len;
354 
355 	len = skb->len + esp->tailen - skb_transport_offset(skb);
356 	if (len > U16_MAX)
357 		return ERR_PTR(-EMSGSIZE);
358 
359 	uh = (struct udphdr *)esp->esph;
360 	uh->source = sport;
361 	uh->dest = dport;
362 	udp_set_len_short(uh, len);
363 	uh->check = 0;
364 
365 	*skb_mac_header(skb) = IPPROTO_UDP;
366 
367 	return (struct ip_esp_hdr *)(uh + 1);
368 }
369 
370 #ifdef CONFIG_INET6_ESPINTCP
371 static struct ip_esp_hdr *esp6_output_tcp_encap(struct xfrm_state *x,
372 						struct sk_buff *skb,
373 						struct esp_info *esp)
374 {
375 	__be16 *lenp = (void *)esp->esph;
376 	struct ip_esp_hdr *esph;
377 	unsigned int len;
378 	struct sock *sk;
379 
380 	len = skb->len + esp->tailen - skb_transport_offset(skb);
381 	if (len > IP_MAX_MTU)
382 		return ERR_PTR(-EMSGSIZE);
383 
384 	rcu_read_lock();
385 	sk = esp6_find_tcp_sk(x);
386 	rcu_read_unlock();
387 
388 	if (IS_ERR(sk))
389 		return ERR_CAST(sk);
390 
391 	sock_put(sk);
392 
393 	*lenp = htons(len);
394 	esph = (struct ip_esp_hdr *)(lenp + 1);
395 
396 	return esph;
397 }
398 #else
399 static struct ip_esp_hdr *esp6_output_tcp_encap(struct xfrm_state *x,
400 						struct sk_buff *skb,
401 						struct esp_info *esp)
402 {
403 	return ERR_PTR(-EOPNOTSUPP);
404 }
405 #endif
406 
407 static int esp6_output_encap(struct xfrm_state *x, struct sk_buff *skb,
408 			    struct esp_info *esp)
409 {
410 	struct xfrm_encap_tmpl *encap = x->encap;
411 	struct ip_esp_hdr *esph;
412 	__be16 sport, dport;
413 	int encap_type;
414 
415 	spin_lock_bh(&x->lock);
416 	sport = encap->encap_sport;
417 	dport = encap->encap_dport;
418 	encap_type = encap->encap_type;
419 	spin_unlock_bh(&x->lock);
420 
421 	switch (encap_type) {
422 	default:
423 	case UDP_ENCAP_ESPINUDP:
424 		esph = esp6_output_udp_encap(skb, encap_type, esp, sport, dport);
425 		break;
426 	case TCP_ENCAP_ESPINTCP:
427 		esph = esp6_output_tcp_encap(x, skb, esp);
428 		break;
429 	}
430 
431 	if (IS_ERR(esph))
432 		return PTR_ERR(esph);
433 
434 	esp->esph = esph;
435 
436 	return 0;
437 }
438 
439 int esp6_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp)
440 {
441 	u8 *tail;
442 	int nfrags;
443 	int esph_offset;
444 	struct page *page;
445 	struct sk_buff *trailer;
446 	int tailen = esp->tailen;
447 
448 	if (x->encap) {
449 		int err = esp6_output_encap(x, skb, esp);
450 
451 		if (err < 0)
452 			return err;
453 	}
454 
455 	if (ALIGN(skb->data_len + tailen, L1_CACHE_BYTES) >
456 	    PAGE_SIZE)
457 		goto cow;
458 
459 	if (!skb_cloned(skb)) {
460 		if (tailen <= skb_tailroom(skb)) {
461 			nfrags = 1;
462 			trailer = skb;
463 			tail = skb_tail_pointer(trailer);
464 
465 			goto skip_cow;
466 		} else if ((skb_shinfo(skb)->nr_frags < MAX_SKB_FRAGS)
467 			   && !skb_has_frag_list(skb)) {
468 			int allocsize;
469 			struct sock *sk = skb->sk;
470 			struct page_frag *pfrag = &x->xfrag;
471 
472 			esp->inplace = false;
473 
474 			/* Take real page refs and clear SKBFL_MANAGED_FRAG_REFS before
475 			 * we mutate the frag array, so the per-frag unref stays balanced
476 			 * for zerocopy managed frags (see __ip_append_data()).
477 			 */
478 			skb_zcopy_downgrade_managed(skb);
479 
480 			allocsize = ALIGN(tailen, L1_CACHE_BYTES);
481 
482 			spin_lock_bh(&x->lock);
483 
484 			if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
485 				spin_unlock_bh(&x->lock);
486 				goto cow;
487 			}
488 
489 			page = pfrag->page;
490 			get_page(page);
491 
492 			tail = page_address(page) + pfrag->offset;
493 
494 			esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);
495 
496 			nfrags = skb_shinfo(skb)->nr_frags;
497 
498 			__skb_fill_page_desc(skb, nfrags, page, pfrag->offset,
499 					     tailen);
500 			skb_shinfo(skb)->nr_frags = ++nfrags;
501 
502 			pfrag->offset = pfrag->offset + allocsize;
503 
504 			spin_unlock_bh(&x->lock);
505 
506 			nfrags++;
507 
508 			skb->len += tailen;
509 			skb->data_len += tailen;
510 			skb->truesize += tailen;
511 			if (sk && sk_fullsock(sk))
512 				refcount_add(tailen, &sk->sk_wmem_alloc);
513 
514 			goto out;
515 		}
516 	}
517 
518 cow:
519 	esph_offset = (unsigned char *)esp->esph - skb_transport_header(skb);
520 
521 	nfrags = skb_cow_data(skb, tailen, &trailer);
522 	if (nfrags < 0)
523 		goto out;
524 	tail = skb_tail_pointer(trailer);
525 	esp->esph = (struct ip_esp_hdr *)(skb_transport_header(skb) + esph_offset);
526 
527 skip_cow:
528 	esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);
529 	pskb_put(skb, trailer, tailen);
530 
531 out:
532 	return nfrags;
533 }
534 EXPORT_SYMBOL_GPL(esp6_output_head);
535 
536 int esp6_output_tail(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp)
537 {
538 	u8 *iv;
539 	int alen;
540 	void *tmp;
541 	int ivlen;
542 	int assoclen;
543 	int extralen;
544 	struct page *page;
545 	struct ip_esp_hdr *esph;
546 	struct aead_request *req;
547 	struct crypto_aead *aead;
548 	struct scatterlist *sg, *dsg;
549 	struct esp_output_extra *extra;
550 	int err = -ENOMEM;
551 
552 	assoclen = sizeof(struct ip_esp_hdr);
553 	extralen = 0;
554 
555 	if (x->props.flags & XFRM_STATE_ESN) {
556 		extralen += sizeof(*extra);
557 		assoclen += sizeof(__be32);
558 	}
559 
560 	aead = x->data;
561 	alen = crypto_aead_authsize(aead);
562 	ivlen = crypto_aead_ivsize(aead);
563 
564 	tmp = esp_alloc_tmp(aead, esp->nfrags + 2, extralen);
565 	if (!tmp)
566 		goto error;
567 
568 	extra = esp_tmp_extra(tmp);
569 	iv = esp_tmp_iv(aead, tmp, extralen);
570 	req = esp_tmp_req(aead, iv);
571 	sg = esp_req_sg(aead, req);
572 
573 	if (esp->inplace)
574 		dsg = sg;
575 	else
576 		dsg = &sg[esp->nfrags];
577 
578 	esph = esp_output_set_esn(skb, x, esp->esph, extra);
579 	esp->esph = esph;
580 
581 	sg_init_table(sg, esp->nfrags);
582 	err = skb_to_sgvec(skb, sg,
583 		           (unsigned char *)esph - skb->data,
584 		           assoclen + ivlen + esp->clen + alen);
585 	if (unlikely(err < 0))
586 		goto error_free;
587 
588 	if (!esp->inplace) {
589 		int allocsize;
590 		struct page_frag *pfrag = &x->xfrag;
591 
592 		allocsize = ALIGN(skb->data_len, L1_CACHE_BYTES);
593 
594 		spin_lock_bh(&x->lock);
595 		if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
596 			spin_unlock_bh(&x->lock);
597 			goto error_free;
598 		}
599 
600 		skb_shinfo(skb)->nr_frags = 1;
601 
602 		page = pfrag->page;
603 		get_page(page);
604 		/* replace page frags in skb with new page */
605 		__skb_fill_page_desc(skb, 0, page, pfrag->offset, skb->data_len);
606 		pfrag->offset = pfrag->offset + allocsize;
607 		spin_unlock_bh(&x->lock);
608 
609 		sg_init_table(dsg, skb_shinfo(skb)->nr_frags + 1);
610 		err = skb_to_sgvec(skb, dsg,
611 			           (unsigned char *)esph - skb->data,
612 			           assoclen + ivlen + esp->clen + alen);
613 		if (unlikely(err < 0)) {
614 			esp_ssg_unref(x, tmp, skb, true);
615 			goto error_free;
616 		}
617 	}
618 
619 	if ((x->props.flags & XFRM_STATE_ESN))
620 		aead_request_set_callback(req, 0, esp_output_done_esn, skb);
621 	else
622 		aead_request_set_callback(req, 0, esp_output_done, skb);
623 
624 	aead_request_set_crypt(req, sg, dsg, ivlen + esp->clen, iv);
625 	aead_request_set_ad(req, assoclen);
626 
627 	memset(iv, 0, ivlen);
628 	memcpy(iv + ivlen - min(ivlen, 8), (u8 *)&esp->seqno + 8 - min(ivlen, 8),
629 	       min(ivlen, 8));
630 
631 	ESP_SKB_CB(skb)->tmp = tmp;
632 	err = crypto_aead_encrypt(req);
633 
634 	switch (err) {
635 	case -EINPROGRESS:
636 		goto error;
637 
638 	case -ENOSPC:
639 		err = NET_XMIT_DROP;
640 		break;
641 
642 	case 0:
643 		if ((x->props.flags & XFRM_STATE_ESN))
644 			esp_output_restore_header(skb);
645 		esp_output_encap_csum(skb);
646 	}
647 
648 	if (sg != dsg)
649 		esp_ssg_unref(x, tmp, skb, false);
650 
651 	if (!err && x->encap && x->encap->encap_type == TCP_ENCAP_ESPINTCP)
652 		err = esp_output_tail_tcp(x, skb);
653 
654 error_free:
655 	kfree(tmp);
656 error:
657 	return err;
658 }
659 EXPORT_SYMBOL_GPL(esp6_output_tail);
660 
661 static int esp6_output(struct xfrm_state *x, struct sk_buff *skb)
662 {
663 	int alen;
664 	int blksize;
665 	struct ip_esp_hdr *esph;
666 	struct crypto_aead *aead;
667 	struct esp_info esp;
668 
669 	esp.inplace = true;
670 
671 	esp.proto = *skb_mac_header(skb);
672 	*skb_mac_header(skb) = IPPROTO_ESP;
673 
674 	/* skb is pure payload to encrypt */
675 
676 	aead = x->data;
677 	alen = crypto_aead_authsize(aead);
678 
679 	esp.tfclen = 0;
680 	if (x->tfcpad) {
681 		struct xfrm_dst *dst = (struct xfrm_dst *)skb_dst(skb);
682 		u32 padto;
683 
684 		padto = min(x->tfcpad, xfrm_state_mtu(x, dst->child_mtu_cached));
685 		if (skb->len < padto)
686 			esp.tfclen = padto - skb->len;
687 	}
688 	blksize = ALIGN(crypto_aead_blocksize(aead), 4);
689 	esp.clen = ALIGN(skb->len + 2 + esp.tfclen, blksize);
690 	esp.plen = esp.clen - skb->len - esp.tfclen;
691 	esp.tailen = esp.tfclen + esp.plen + alen;
692 
693 	esp.esph = ip_esp_hdr(skb);
694 
695 	esp.nfrags = esp6_output_head(x, skb, &esp);
696 	if (esp.nfrags < 0)
697 		return esp.nfrags;
698 
699 	esph = esp.esph;
700 	esph->spi = x->id.spi;
701 
702 	esph->seq_no = htonl(XFRM_SKB_CB(skb)->seq.output.low);
703 	esp.seqno = cpu_to_be64(XFRM_SKB_CB(skb)->seq.output.low +
704 			    ((u64)XFRM_SKB_CB(skb)->seq.output.hi << 32));
705 
706 	skb_push(skb, -skb_network_offset(skb));
707 
708 	return esp6_output_tail(x, skb, &esp);
709 }
710 
711 static inline int esp_remove_trailer(struct sk_buff *skb)
712 {
713 	struct xfrm_state *x = xfrm_input_state(skb);
714 	struct crypto_aead *aead = x->data;
715 	int alen, hlen, elen;
716 	int padlen, trimlen;
717 	__wsum csumdiff;
718 	u8 nexthdr[2];
719 	int ret;
720 
721 	alen = crypto_aead_authsize(aead);
722 	hlen = sizeof(struct ip_esp_hdr) + crypto_aead_ivsize(aead);
723 	elen = skb->len - hlen;
724 
725 	ret = skb_copy_bits(skb, skb->len - alen - 2, nexthdr, 2);
726 	BUG_ON(ret);
727 
728 	ret = -EINVAL;
729 	padlen = nexthdr[0];
730 	if (padlen + 2 + alen >= elen) {
731 		net_dbg_ratelimited("ipsec esp packet is garbage padlen=%d, elen=%d\n",
732 				    padlen + 2, elen - alen);
733 		goto out;
734 	}
735 
736 	trimlen = alen + padlen + 2;
737 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
738 		csumdiff = skb_checksum(skb, skb->len - trimlen, trimlen, 0);
739 		skb->csum = csum_block_sub(skb->csum, csumdiff,
740 					   skb->len - trimlen);
741 	}
742 	ret = pskb_trim(skb, skb->len - trimlen);
743 	if (unlikely(ret))
744 		return ret;
745 
746 	ret = nexthdr[1];
747 
748 out:
749 	return ret;
750 }
751 
752 int esp6_input_done2(struct sk_buff *skb, int err)
753 {
754 	struct xfrm_state *x = xfrm_input_state(skb);
755 	struct xfrm_offload *xo = xfrm_offload(skb);
756 	struct crypto_aead *aead = x->data;
757 	int hlen = sizeof(struct ip_esp_hdr) + crypto_aead_ivsize(aead);
758 	int hdr_len = skb_network_header_len(skb);
759 
760 	if (!xo || !(xo->flags & CRYPTO_DONE))
761 		kfree(ESP_SKB_CB(skb)->tmp);
762 
763 	if (unlikely(err))
764 		goto out;
765 
766 	err = esp_remove_trailer(skb);
767 	if (unlikely(err < 0))
768 		goto out;
769 
770 	if (x->encap) {
771 		const struct ipv6hdr *ip6h = ipv6_hdr(skb);
772 		int offset = skb_network_offset(skb) + sizeof(*ip6h);
773 		struct xfrm_encap_tmpl *encap = x->encap;
774 		u8 nexthdr = ip6h->nexthdr;
775 		__be16 frag_off, source;
776 		struct udphdr *uh;
777 		struct tcphdr *th;
778 
779 		offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
780 		if (offset == -1) {
781 			err = -EINVAL;
782 			goto out;
783 		}
784 
785 		uh = (void *)(skb->data + offset);
786 		th = (void *)(skb->data + offset);
787 		hdr_len += offset;
788 
789 		switch (x->encap->encap_type) {
790 		case TCP_ENCAP_ESPINTCP:
791 			source = th->source;
792 			break;
793 		case UDP_ENCAP_ESPINUDP:
794 			source = uh->source;
795 			break;
796 		default:
797 			WARN_ON_ONCE(1);
798 			err = -EINVAL;
799 			goto out;
800 		}
801 
802 		/*
803 		 * 1) if the NAT-T peer's IP or port changed then
804 		 *    advertise the change to the keying daemon.
805 		 *    This is an inbound SA, so just compare
806 		 *    SRC ports.
807 		 */
808 		if (!ipv6_addr_equal(&ip6h->saddr, &x->props.saddr.in6) ||
809 		    source != encap->encap_sport) {
810 			xfrm_address_t ipaddr;
811 
812 			memcpy(&ipaddr.a6, &ip6h->saddr.s6_addr, sizeof(ipaddr.a6));
813 			km_new_mapping(x, &ipaddr, source);
814 
815 			/* XXX: perhaps add an extra
816 			 * policy check here, to see
817 			 * if we should allow or
818 			 * reject a packet from a
819 			 * different source
820 			 * address/port.
821 			 */
822 		}
823 
824 		/*
825 		 * 2) ignore UDP/TCP checksums in case
826 		 *    of NAT-T in Transport Mode, or
827 		 *    perform other post-processing fixes
828 		 *    as per draft-ietf-ipsec-udp-encaps-06,
829 		 *    section 3.1.2
830 		 */
831 		if (x->props.mode == XFRM_MODE_TRANSPORT)
832 			skb->ip_summed = CHECKSUM_UNNECESSARY;
833 	}
834 
835 	skb_postpull_rcsum(skb, skb_network_header(skb),
836 			   skb_network_header_len(skb));
837 	skb_pull_rcsum(skb, hlen);
838 	if (x->props.mode == XFRM_MODE_TUNNEL ||
839 	    x->props.mode == XFRM_MODE_IPTFS)
840 		skb_reset_transport_header(skb);
841 	else
842 		skb_set_transport_header(skb, -hdr_len);
843 
844 	/* RFC4303: Drop dummy packets without any error */
845 	if (err == IPPROTO_NONE)
846 		err = -EINVAL;
847 
848 out:
849 	return err;
850 }
851 EXPORT_SYMBOL_GPL(esp6_input_done2);
852 
853 static void esp_input_done(void *data, int err)
854 {
855 	struct sk_buff *skb = data;
856 
857 	xfrm_input_resume(skb, esp6_input_done2(skb, err));
858 }
859 
860 static void esp_input_restore_header(struct sk_buff *skb)
861 {
862 	esp_restore_header(skb, 0);
863 	__skb_pull(skb, 4);
864 }
865 
866 static void esp_input_set_header(struct sk_buff *skb, __be32 *seqhi)
867 {
868 	struct xfrm_state *x = xfrm_input_state(skb);
869 
870 	/* For ESN we move the header forward by 4 bytes to
871 	 * accommodate the high bits.  We will move it back after
872 	 * decryption.
873 	 */
874 	if ((x->props.flags & XFRM_STATE_ESN)) {
875 		struct ip_esp_hdr *esph = skb_push(skb, 4);
876 
877 		*seqhi = esph->spi;
878 		esph->spi = esph->seq_no;
879 		esph->seq_no = XFRM_SKB_CB(skb)->seq.input.hi;
880 	}
881 }
882 
883 static void esp_input_done_esn(void *data, int err)
884 {
885 	struct sk_buff *skb = data;
886 
887 	esp_input_restore_header(skb);
888 	esp_input_done(data, err);
889 }
890 
891 static int esp6_input(struct xfrm_state *x, struct sk_buff *skb)
892 {
893 	struct crypto_aead *aead = x->data;
894 	struct aead_request *req;
895 	struct sk_buff *trailer;
896 	int ivlen = crypto_aead_ivsize(aead);
897 	int elen = skb->len - sizeof(struct ip_esp_hdr) - ivlen;
898 	int nfrags;
899 	int assoclen;
900 	int seqhilen;
901 	int ret = 0;
902 	void *tmp;
903 	__be32 *seqhi;
904 	u8 *iv;
905 	struct scatterlist *sg;
906 
907 	if (!pskb_may_pull(skb, sizeof(struct ip_esp_hdr) + ivlen)) {
908 		ret = -EINVAL;
909 		goto out;
910 	}
911 
912 	if (elen <= 0) {
913 		ret = -EINVAL;
914 		goto out;
915 	}
916 
917 	assoclen = sizeof(struct ip_esp_hdr);
918 	seqhilen = 0;
919 
920 	if (x->props.flags & XFRM_STATE_ESN) {
921 		seqhilen += sizeof(__be32);
922 		assoclen += seqhilen;
923 	}
924 
925 	if (!skb_cloned(skb)) {
926 		if (!skb_is_nonlinear(skb)) {
927 			nfrags = 1;
928 
929 			goto skip_cow;
930 		} else if (!skb_has_frag_list(skb) &&
931 			   !skb_has_shared_frag(skb)) {
932 			nfrags = skb_shinfo(skb)->nr_frags;
933 			nfrags++;
934 
935 			goto skip_cow;
936 		}
937 	}
938 
939 	nfrags = skb_cow_data(skb, 0, &trailer);
940 	if (nfrags < 0) {
941 		ret = -EINVAL;
942 		goto out;
943 	}
944 
945 skip_cow:
946 	ret = -ENOMEM;
947 	tmp = esp_alloc_tmp(aead, nfrags, seqhilen);
948 	if (!tmp)
949 		goto out;
950 
951 	ESP_SKB_CB(skb)->tmp = tmp;
952 	seqhi = esp_tmp_extra(tmp);
953 	iv = esp_tmp_iv(aead, tmp, seqhilen);
954 	req = esp_tmp_req(aead, iv);
955 	sg = esp_req_sg(aead, req);
956 
957 	esp_input_set_header(skb, seqhi);
958 
959 	sg_init_table(sg, nfrags);
960 	ret = skb_to_sgvec(skb, sg, 0, skb->len);
961 	if (unlikely(ret < 0)) {
962 		kfree(tmp);
963 		goto out;
964 	}
965 
966 	skb->ip_summed = CHECKSUM_NONE;
967 
968 	if ((x->props.flags & XFRM_STATE_ESN))
969 		aead_request_set_callback(req, 0, esp_input_done_esn, skb);
970 	else
971 		aead_request_set_callback(req, 0, esp_input_done, skb);
972 
973 	aead_request_set_crypt(req, sg, sg, elen + ivlen, iv);
974 	aead_request_set_ad(req, assoclen);
975 
976 	ret = crypto_aead_decrypt(req);
977 	if (ret == -EINPROGRESS)
978 		goto out;
979 
980 	if ((x->props.flags & XFRM_STATE_ESN))
981 		esp_input_restore_header(skb);
982 
983 	ret = esp6_input_done2(skb, ret);
984 
985 out:
986 	return ret;
987 }
988 
989 static int esp6_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
990 		    u8 type, u8 code, int offset, __be32 info)
991 {
992 	struct net *net = dev_net(skb->dev);
993 	const struct ipv6hdr *iph = (const struct ipv6hdr *)skb->data;
994 	struct ip_esp_hdr *esph = (struct ip_esp_hdr *)(skb->data + offset);
995 	struct xfrm_state *x;
996 
997 	if (type != ICMPV6_PKT_TOOBIG &&
998 	    type != NDISC_REDIRECT)
999 		return 0;
1000 
1001 	x = xfrm_state_lookup(net, skb->mark, (const xfrm_address_t *)&iph->daddr,
1002 			      esph->spi, IPPROTO_ESP, AF_INET6);
1003 	if (!x)
1004 		return 0;
1005 
1006 	if (type == NDISC_REDIRECT)
1007 		ip6_redirect(skb, net, skb->dev->ifindex, 0,
1008 			     sock_net_uid(net, NULL));
1009 	else
1010 		ip6_update_pmtu(skb, net, info, 0, 0, sock_net_uid(net, NULL));
1011 	xfrm_state_put(x);
1012 
1013 	return 0;
1014 }
1015 
1016 static void esp6_destroy(struct xfrm_state *x)
1017 {
1018 	struct crypto_aead *aead = x->data;
1019 
1020 	if (!aead)
1021 		return;
1022 
1023 	crypto_free_aead(aead);
1024 }
1025 
1026 static int esp_init_aead(struct xfrm_state *x, struct netlink_ext_ack *extack)
1027 {
1028 	char aead_name[CRYPTO_MAX_ALG_NAME];
1029 	struct crypto_aead *aead;
1030 	int err;
1031 
1032 	if (snprintf(aead_name, CRYPTO_MAX_ALG_NAME, "%s(%s)",
1033 		     x->geniv, x->aead->alg_name) >= CRYPTO_MAX_ALG_NAME) {
1034 		NL_SET_ERR_MSG(extack, "Algorithm name is too long");
1035 		return -ENAMETOOLONG;
1036 	}
1037 
1038 	aead = crypto_alloc_aead(aead_name, 0, 0);
1039 	err = PTR_ERR(aead);
1040 	if (IS_ERR(aead))
1041 		goto error;
1042 
1043 	x->data = aead;
1044 
1045 	err = crypto_aead_setkey(aead, x->aead->alg_key,
1046 				 (x->aead->alg_key_len + 7) / 8);
1047 	if (err)
1048 		goto error;
1049 
1050 	err = crypto_aead_setauthsize(aead, x->aead->alg_icv_len / 8);
1051 	if (err)
1052 		goto error;
1053 
1054 	return 0;
1055 
1056 error:
1057 	NL_SET_ERR_MSG(extack, "Kernel was unable to initialize cryptographic operations");
1058 	return err;
1059 }
1060 
1061 static int esp_init_authenc(struct xfrm_state *x,
1062 			    struct netlink_ext_ack *extack)
1063 {
1064 	struct crypto_aead *aead;
1065 	struct crypto_authenc_key_param *param;
1066 	struct rtattr *rta;
1067 	char *key;
1068 	char *p;
1069 	char authenc_name[CRYPTO_MAX_ALG_NAME];
1070 	unsigned int keylen;
1071 	int err;
1072 
1073 	err = -ENAMETOOLONG;
1074 
1075 	if ((x->props.flags & XFRM_STATE_ESN)) {
1076 		if (snprintf(authenc_name, CRYPTO_MAX_ALG_NAME,
1077 			     "%s%sauthencesn(%s,%s)%s",
1078 			     x->geniv ?: "", x->geniv ? "(" : "",
1079 			     x->aalg ? x->aalg->alg_name : "digest_null",
1080 			     x->ealg->alg_name,
1081 			     x->geniv ? ")" : "") >= CRYPTO_MAX_ALG_NAME) {
1082 			NL_SET_ERR_MSG(extack, "Algorithm name is too long");
1083 			goto error;
1084 		}
1085 	} else {
1086 		if (snprintf(authenc_name, CRYPTO_MAX_ALG_NAME,
1087 			     "%s%sauthenc(%s,%s)%s",
1088 			     x->geniv ?: "", x->geniv ? "(" : "",
1089 			     x->aalg ? x->aalg->alg_name : "digest_null",
1090 			     x->ealg->alg_name,
1091 			     x->geniv ? ")" : "") >= CRYPTO_MAX_ALG_NAME) {
1092 			NL_SET_ERR_MSG(extack, "Algorithm name is too long");
1093 			goto error;
1094 		}
1095 	}
1096 
1097 	aead = crypto_alloc_aead(authenc_name, 0, 0);
1098 	err = PTR_ERR(aead);
1099 	if (IS_ERR(aead)) {
1100 		NL_SET_ERR_MSG(extack, "Kernel was unable to initialize cryptographic operations");
1101 		goto error;
1102 	}
1103 
1104 	x->data = aead;
1105 
1106 	keylen = (x->aalg ? (x->aalg->alg_key_len + 7) / 8 : 0) +
1107 		 (x->ealg->alg_key_len + 7) / 8 + RTA_SPACE(sizeof(*param));
1108 	err = -ENOMEM;
1109 	key = kmalloc(keylen, GFP_KERNEL);
1110 	if (!key)
1111 		goto error;
1112 
1113 	p = key;
1114 	rta = (void *)p;
1115 	rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
1116 	rta->rta_len = RTA_LENGTH(sizeof(*param));
1117 	param = RTA_DATA(rta);
1118 	p += RTA_SPACE(sizeof(*param));
1119 
1120 	if (x->aalg) {
1121 		struct xfrm_algo_desc *aalg_desc;
1122 
1123 		memcpy(p, x->aalg->alg_key, (x->aalg->alg_key_len + 7) / 8);
1124 		p += (x->aalg->alg_key_len + 7) / 8;
1125 
1126 		aalg_desc = xfrm_aalg_get_byname(x->aalg->alg_name, 0);
1127 		BUG_ON(!aalg_desc);
1128 
1129 		err = -EINVAL;
1130 		if (aalg_desc->uinfo.auth.icv_fullbits / 8 !=
1131 		    crypto_aead_authsize(aead)) {
1132 			NL_SET_ERR_MSG(extack, "Kernel was unable to initialize cryptographic operations");
1133 			goto free_key;
1134 		}
1135 
1136 		err = crypto_aead_setauthsize(
1137 			aead, x->aalg->alg_trunc_len / 8);
1138 		if (err) {
1139 			NL_SET_ERR_MSG(extack, "Kernel was unable to initialize cryptographic operations");
1140 			goto free_key;
1141 		}
1142 	}
1143 
1144 	param->enckeylen = cpu_to_be32((x->ealg->alg_key_len + 7) / 8);
1145 	memcpy(p, x->ealg->alg_key, (x->ealg->alg_key_len + 7) / 8);
1146 
1147 	err = crypto_aead_setkey(aead, key, keylen);
1148 
1149 free_key:
1150 	kfree(key);
1151 
1152 error:
1153 	return err;
1154 }
1155 
1156 static int esp6_init_state(struct xfrm_state *x, struct netlink_ext_ack *extack)
1157 {
1158 	struct crypto_aead *aead;
1159 	u32 align;
1160 	int err;
1161 
1162 	x->data = NULL;
1163 
1164 	if (x->aead) {
1165 		err = esp_init_aead(x, extack);
1166 	} else if (x->ealg) {
1167 		err = esp_init_authenc(x, extack);
1168 	} else {
1169 		NL_SET_ERR_MSG(extack, "ESP: AEAD or CRYPT must be provided");
1170 		err = -EINVAL;
1171 	}
1172 
1173 	if (err)
1174 		goto error;
1175 
1176 	aead = x->data;
1177 
1178 	x->props.header_len = sizeof(struct ip_esp_hdr) +
1179 			      crypto_aead_ivsize(aead);
1180 	switch (x->props.mode) {
1181 	case XFRM_MODE_BEET:
1182 		if (x->sel.family != AF_INET6)
1183 			x->props.header_len += IPV4_BEET_PHMAXLEN +
1184 					       (sizeof(struct ipv6hdr) - sizeof(struct iphdr));
1185 		break;
1186 	default:
1187 	case XFRM_MODE_TRANSPORT:
1188 		break;
1189 	case XFRM_MODE_TUNNEL:
1190 		x->props.header_len += sizeof(struct ipv6hdr);
1191 		break;
1192 	}
1193 
1194 	if (x->encap) {
1195 		struct xfrm_encap_tmpl *encap = x->encap;
1196 
1197 		switch (encap->encap_type) {
1198 		default:
1199 			NL_SET_ERR_MSG(extack, "Unsupported encapsulation type for ESP");
1200 			err = -EINVAL;
1201 			goto error;
1202 		case UDP_ENCAP_ESPINUDP:
1203 			x->props.header_len += sizeof(struct udphdr);
1204 			break;
1205 #ifdef CONFIG_INET6_ESPINTCP
1206 		case TCP_ENCAP_ESPINTCP:
1207 			/* only the length field, TCP encap is done by
1208 			 * the socket
1209 			 */
1210 			x->props.header_len += 2;
1211 			break;
1212 #endif
1213 		}
1214 	}
1215 
1216 	align = ALIGN(crypto_aead_blocksize(aead), 4);
1217 	x->props.trailer_len = align + 1 + crypto_aead_authsize(aead);
1218 
1219 error:
1220 	return err;
1221 }
1222 
1223 static int esp6_rcv_cb(struct sk_buff *skb, int err)
1224 {
1225 	return 0;
1226 }
1227 
1228 static const struct xfrm_type esp6_type = {
1229 	.owner		= THIS_MODULE,
1230 	.proto		= IPPROTO_ESP,
1231 	.flags		= XFRM_TYPE_REPLAY_PROT,
1232 	.init_state	= esp6_init_state,
1233 	.destructor	= esp6_destroy,
1234 	.input		= esp6_input,
1235 	.output		= esp6_output,
1236 };
1237 
1238 static struct xfrm6_protocol esp6_protocol = {
1239 	.handler	=	xfrm6_rcv,
1240 	.input_handler	=	xfrm_input,
1241 	.cb_handler	=	esp6_rcv_cb,
1242 	.err_handler	=	esp6_err,
1243 	.priority	=	0,
1244 };
1245 
1246 static int __init esp6_init(void)
1247 {
1248 	if (xfrm_register_type(&esp6_type, AF_INET6) < 0) {
1249 		pr_info("%s: can't add xfrm type\n", __func__);
1250 		return -EAGAIN;
1251 	}
1252 	if (xfrm6_protocol_register(&esp6_protocol, IPPROTO_ESP) < 0) {
1253 		pr_info("%s: can't add protocol\n", __func__);
1254 		xfrm_unregister_type(&esp6_type, AF_INET6);
1255 		return -EAGAIN;
1256 	}
1257 
1258 	return 0;
1259 }
1260 
1261 static void __exit esp6_fini(void)
1262 {
1263 	if (xfrm6_protocol_deregister(&esp6_protocol, IPPROTO_ESP) < 0)
1264 		pr_info("%s: can't remove protocol\n", __func__);
1265 	xfrm_unregister_type(&esp6_type, AF_INET6);
1266 }
1267 
1268 module_init(esp6_init);
1269 module_exit(esp6_fini);
1270 
1271 MODULE_DESCRIPTION("IPv6 ESP transformation helpers");
1272 MODULE_LICENSE("GPL");
1273 MODULE_ALIAS_XFRM_TYPE(AF_INET6, XFRM_PROTO_ESP);
1274