xref: /linux/net/ipv6/esp6.c (revision 26ba30221c03364d6ed9910be8da4c1fd871b07b)
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 			allocsize = ALIGN(tailen, L1_CACHE_BYTES);
475 
476 			spin_lock_bh(&x->lock);
477 
478 			if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
479 				spin_unlock_bh(&x->lock);
480 				goto cow;
481 			}
482 
483 			page = pfrag->page;
484 			get_page(page);
485 
486 			tail = page_address(page) + pfrag->offset;
487 
488 			esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);
489 
490 			nfrags = skb_shinfo(skb)->nr_frags;
491 
492 			__skb_fill_page_desc(skb, nfrags, page, pfrag->offset,
493 					     tailen);
494 			skb_shinfo(skb)->nr_frags = ++nfrags;
495 
496 			pfrag->offset = pfrag->offset + allocsize;
497 
498 			spin_unlock_bh(&x->lock);
499 
500 			nfrags++;
501 
502 			skb->len += tailen;
503 			skb->data_len += tailen;
504 			skb->truesize += tailen;
505 			if (sk && sk_fullsock(sk))
506 				refcount_add(tailen, &sk->sk_wmem_alloc);
507 
508 			goto out;
509 		}
510 	}
511 
512 cow:
513 	esph_offset = (unsigned char *)esp->esph - skb_transport_header(skb);
514 
515 	nfrags = skb_cow_data(skb, tailen, &trailer);
516 	if (nfrags < 0)
517 		goto out;
518 	tail = skb_tail_pointer(trailer);
519 	esp->esph = (struct ip_esp_hdr *)(skb_transport_header(skb) + esph_offset);
520 
521 skip_cow:
522 	esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);
523 	pskb_put(skb, trailer, tailen);
524 
525 out:
526 	return nfrags;
527 }
528 EXPORT_SYMBOL_GPL(esp6_output_head);
529 
530 int esp6_output_tail(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp)
531 {
532 	u8 *iv;
533 	int alen;
534 	void *tmp;
535 	int ivlen;
536 	int assoclen;
537 	int extralen;
538 	struct page *page;
539 	struct ip_esp_hdr *esph;
540 	struct aead_request *req;
541 	struct crypto_aead *aead;
542 	struct scatterlist *sg, *dsg;
543 	struct esp_output_extra *extra;
544 	int err = -ENOMEM;
545 
546 	assoclen = sizeof(struct ip_esp_hdr);
547 	extralen = 0;
548 
549 	if (x->props.flags & XFRM_STATE_ESN) {
550 		extralen += sizeof(*extra);
551 		assoclen += sizeof(__be32);
552 	}
553 
554 	aead = x->data;
555 	alen = crypto_aead_authsize(aead);
556 	ivlen = crypto_aead_ivsize(aead);
557 
558 	tmp = esp_alloc_tmp(aead, esp->nfrags + 2, extralen);
559 	if (!tmp)
560 		goto error;
561 
562 	extra = esp_tmp_extra(tmp);
563 	iv = esp_tmp_iv(aead, tmp, extralen);
564 	req = esp_tmp_req(aead, iv);
565 	sg = esp_req_sg(aead, req);
566 
567 	if (esp->inplace)
568 		dsg = sg;
569 	else
570 		dsg = &sg[esp->nfrags];
571 
572 	esph = esp_output_set_esn(skb, x, esp->esph, extra);
573 	esp->esph = esph;
574 
575 	sg_init_table(sg, esp->nfrags);
576 	err = skb_to_sgvec(skb, sg,
577 		           (unsigned char *)esph - skb->data,
578 		           assoclen + ivlen + esp->clen + alen);
579 	if (unlikely(err < 0))
580 		goto error_free;
581 
582 	if (!esp->inplace) {
583 		int allocsize;
584 		struct page_frag *pfrag = &x->xfrag;
585 
586 		allocsize = ALIGN(skb->data_len, L1_CACHE_BYTES);
587 
588 		spin_lock_bh(&x->lock);
589 		if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
590 			spin_unlock_bh(&x->lock);
591 			goto error_free;
592 		}
593 
594 		skb_shinfo(skb)->nr_frags = 1;
595 
596 		page = pfrag->page;
597 		get_page(page);
598 		/* replace page frags in skb with new page */
599 		__skb_fill_page_desc(skb, 0, page, pfrag->offset, skb->data_len);
600 		pfrag->offset = pfrag->offset + allocsize;
601 		spin_unlock_bh(&x->lock);
602 
603 		sg_init_table(dsg, skb_shinfo(skb)->nr_frags + 1);
604 		err = skb_to_sgvec(skb, dsg,
605 			           (unsigned char *)esph - skb->data,
606 			           assoclen + ivlen + esp->clen + alen);
607 		if (unlikely(err < 0)) {
608 			esp_ssg_unref(x, tmp, skb, true);
609 			goto error_free;
610 		}
611 	}
612 
613 	if ((x->props.flags & XFRM_STATE_ESN))
614 		aead_request_set_callback(req, 0, esp_output_done_esn, skb);
615 	else
616 		aead_request_set_callback(req, 0, esp_output_done, skb);
617 
618 	aead_request_set_crypt(req, sg, dsg, ivlen + esp->clen, iv);
619 	aead_request_set_ad(req, assoclen);
620 
621 	memset(iv, 0, ivlen);
622 	memcpy(iv + ivlen - min(ivlen, 8), (u8 *)&esp->seqno + 8 - min(ivlen, 8),
623 	       min(ivlen, 8));
624 
625 	ESP_SKB_CB(skb)->tmp = tmp;
626 	err = crypto_aead_encrypt(req);
627 
628 	switch (err) {
629 	case -EINPROGRESS:
630 		goto error;
631 
632 	case -ENOSPC:
633 		err = NET_XMIT_DROP;
634 		break;
635 
636 	case 0:
637 		if ((x->props.flags & XFRM_STATE_ESN))
638 			esp_output_restore_header(skb);
639 		esp_output_encap_csum(skb);
640 	}
641 
642 	if (sg != dsg)
643 		esp_ssg_unref(x, tmp, skb, false);
644 
645 	if (!err && x->encap && x->encap->encap_type == TCP_ENCAP_ESPINTCP)
646 		err = esp_output_tail_tcp(x, skb);
647 
648 error_free:
649 	kfree(tmp);
650 error:
651 	return err;
652 }
653 EXPORT_SYMBOL_GPL(esp6_output_tail);
654 
655 static int esp6_output(struct xfrm_state *x, struct sk_buff *skb)
656 {
657 	int alen;
658 	int blksize;
659 	struct ip_esp_hdr *esph;
660 	struct crypto_aead *aead;
661 	struct esp_info esp;
662 
663 	esp.inplace = true;
664 
665 	esp.proto = *skb_mac_header(skb);
666 	*skb_mac_header(skb) = IPPROTO_ESP;
667 
668 	/* skb is pure payload to encrypt */
669 
670 	aead = x->data;
671 	alen = crypto_aead_authsize(aead);
672 
673 	esp.tfclen = 0;
674 	if (x->tfcpad) {
675 		struct xfrm_dst *dst = (struct xfrm_dst *)skb_dst(skb);
676 		u32 padto;
677 
678 		padto = min(x->tfcpad, xfrm_state_mtu(x, dst->child_mtu_cached));
679 		if (skb->len < padto)
680 			esp.tfclen = padto - skb->len;
681 	}
682 	blksize = ALIGN(crypto_aead_blocksize(aead), 4);
683 	esp.clen = ALIGN(skb->len + 2 + esp.tfclen, blksize);
684 	esp.plen = esp.clen - skb->len - esp.tfclen;
685 	esp.tailen = esp.tfclen + esp.plen + alen;
686 
687 	esp.esph = ip_esp_hdr(skb);
688 
689 	esp.nfrags = esp6_output_head(x, skb, &esp);
690 	if (esp.nfrags < 0)
691 		return esp.nfrags;
692 
693 	esph = esp.esph;
694 	esph->spi = x->id.spi;
695 
696 	esph->seq_no = htonl(XFRM_SKB_CB(skb)->seq.output.low);
697 	esp.seqno = cpu_to_be64(XFRM_SKB_CB(skb)->seq.output.low +
698 			    ((u64)XFRM_SKB_CB(skb)->seq.output.hi << 32));
699 
700 	skb_push(skb, -skb_network_offset(skb));
701 
702 	return esp6_output_tail(x, skb, &esp);
703 }
704 
705 static inline int esp_remove_trailer(struct sk_buff *skb)
706 {
707 	struct xfrm_state *x = xfrm_input_state(skb);
708 	struct crypto_aead *aead = x->data;
709 	int alen, hlen, elen;
710 	int padlen, trimlen;
711 	__wsum csumdiff;
712 	u8 nexthdr[2];
713 	int ret;
714 
715 	alen = crypto_aead_authsize(aead);
716 	hlen = sizeof(struct ip_esp_hdr) + crypto_aead_ivsize(aead);
717 	elen = skb->len - hlen;
718 
719 	ret = skb_copy_bits(skb, skb->len - alen - 2, nexthdr, 2);
720 	BUG_ON(ret);
721 
722 	ret = -EINVAL;
723 	padlen = nexthdr[0];
724 	if (padlen + 2 + alen >= elen) {
725 		net_dbg_ratelimited("ipsec esp packet is garbage padlen=%d, elen=%d\n",
726 				    padlen + 2, elen - alen);
727 		goto out;
728 	}
729 
730 	trimlen = alen + padlen + 2;
731 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
732 		csumdiff = skb_checksum(skb, skb->len - trimlen, trimlen, 0);
733 		skb->csum = csum_block_sub(skb->csum, csumdiff,
734 					   skb->len - trimlen);
735 	}
736 	ret = pskb_trim(skb, skb->len - trimlen);
737 	if (unlikely(ret))
738 		return ret;
739 
740 	ret = nexthdr[1];
741 
742 out:
743 	return ret;
744 }
745 
746 int esp6_input_done2(struct sk_buff *skb, int err)
747 {
748 	struct xfrm_state *x = xfrm_input_state(skb);
749 	struct xfrm_offload *xo = xfrm_offload(skb);
750 	struct crypto_aead *aead = x->data;
751 	int hlen = sizeof(struct ip_esp_hdr) + crypto_aead_ivsize(aead);
752 	int hdr_len = skb_network_header_len(skb);
753 
754 	if (!xo || !(xo->flags & CRYPTO_DONE))
755 		kfree(ESP_SKB_CB(skb)->tmp);
756 
757 	if (unlikely(err))
758 		goto out;
759 
760 	err = esp_remove_trailer(skb);
761 	if (unlikely(err < 0))
762 		goto out;
763 
764 	if (x->encap) {
765 		const struct ipv6hdr *ip6h = ipv6_hdr(skb);
766 		int offset = skb_network_offset(skb) + sizeof(*ip6h);
767 		struct xfrm_encap_tmpl *encap = x->encap;
768 		u8 nexthdr = ip6h->nexthdr;
769 		__be16 frag_off, source;
770 		struct udphdr *uh;
771 		struct tcphdr *th;
772 
773 		offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
774 		if (offset == -1) {
775 			err = -EINVAL;
776 			goto out;
777 		}
778 
779 		uh = (void *)(skb->data + offset);
780 		th = (void *)(skb->data + offset);
781 		hdr_len += offset;
782 
783 		switch (x->encap->encap_type) {
784 		case TCP_ENCAP_ESPINTCP:
785 			source = th->source;
786 			break;
787 		case UDP_ENCAP_ESPINUDP:
788 			source = uh->source;
789 			break;
790 		default:
791 			WARN_ON_ONCE(1);
792 			err = -EINVAL;
793 			goto out;
794 		}
795 
796 		/*
797 		 * 1) if the NAT-T peer's IP or port changed then
798 		 *    advertise the change to the keying daemon.
799 		 *    This is an inbound SA, so just compare
800 		 *    SRC ports.
801 		 */
802 		if (!ipv6_addr_equal(&ip6h->saddr, &x->props.saddr.in6) ||
803 		    source != encap->encap_sport) {
804 			xfrm_address_t ipaddr;
805 
806 			memcpy(&ipaddr.a6, &ip6h->saddr.s6_addr, sizeof(ipaddr.a6));
807 			km_new_mapping(x, &ipaddr, source);
808 
809 			/* XXX: perhaps add an extra
810 			 * policy check here, to see
811 			 * if we should allow or
812 			 * reject a packet from a
813 			 * different source
814 			 * address/port.
815 			 */
816 		}
817 
818 		/*
819 		 * 2) ignore UDP/TCP checksums in case
820 		 *    of NAT-T in Transport Mode, or
821 		 *    perform other post-processing fixes
822 		 *    as per draft-ietf-ipsec-udp-encaps-06,
823 		 *    section 3.1.2
824 		 */
825 		if (x->props.mode == XFRM_MODE_TRANSPORT)
826 			skb->ip_summed = CHECKSUM_UNNECESSARY;
827 	}
828 
829 	skb_postpull_rcsum(skb, skb_network_header(skb),
830 			   skb_network_header_len(skb));
831 	skb_pull_rcsum(skb, hlen);
832 	if (x->props.mode == XFRM_MODE_TUNNEL ||
833 	    x->props.mode == XFRM_MODE_IPTFS)
834 		skb_reset_transport_header(skb);
835 	else
836 		skb_set_transport_header(skb, -hdr_len);
837 
838 	/* RFC4303: Drop dummy packets without any error */
839 	if (err == IPPROTO_NONE)
840 		err = -EINVAL;
841 
842 out:
843 	return err;
844 }
845 EXPORT_SYMBOL_GPL(esp6_input_done2);
846 
847 static void esp_input_done(void *data, int err)
848 {
849 	struct sk_buff *skb = data;
850 
851 	xfrm_input_resume(skb, esp6_input_done2(skb, err));
852 }
853 
854 static void esp_input_restore_header(struct sk_buff *skb)
855 {
856 	esp_restore_header(skb, 0);
857 	__skb_pull(skb, 4);
858 }
859 
860 static void esp_input_set_header(struct sk_buff *skb, __be32 *seqhi)
861 {
862 	struct xfrm_state *x = xfrm_input_state(skb);
863 
864 	/* For ESN we move the header forward by 4 bytes to
865 	 * accommodate the high bits.  We will move it back after
866 	 * decryption.
867 	 */
868 	if ((x->props.flags & XFRM_STATE_ESN)) {
869 		struct ip_esp_hdr *esph = skb_push(skb, 4);
870 
871 		*seqhi = esph->spi;
872 		esph->spi = esph->seq_no;
873 		esph->seq_no = XFRM_SKB_CB(skb)->seq.input.hi;
874 	}
875 }
876 
877 static void esp_input_done_esn(void *data, int err)
878 {
879 	struct sk_buff *skb = data;
880 
881 	esp_input_restore_header(skb);
882 	esp_input_done(data, err);
883 }
884 
885 static int esp6_input(struct xfrm_state *x, struct sk_buff *skb)
886 {
887 	struct crypto_aead *aead = x->data;
888 	struct aead_request *req;
889 	struct sk_buff *trailer;
890 	int ivlen = crypto_aead_ivsize(aead);
891 	int elen = skb->len - sizeof(struct ip_esp_hdr) - ivlen;
892 	int nfrags;
893 	int assoclen;
894 	int seqhilen;
895 	int ret = 0;
896 	void *tmp;
897 	__be32 *seqhi;
898 	u8 *iv;
899 	struct scatterlist *sg;
900 
901 	if (!pskb_may_pull(skb, sizeof(struct ip_esp_hdr) + ivlen)) {
902 		ret = -EINVAL;
903 		goto out;
904 	}
905 
906 	if (elen <= 0) {
907 		ret = -EINVAL;
908 		goto out;
909 	}
910 
911 	assoclen = sizeof(struct ip_esp_hdr);
912 	seqhilen = 0;
913 
914 	if (x->props.flags & XFRM_STATE_ESN) {
915 		seqhilen += sizeof(__be32);
916 		assoclen += seqhilen;
917 	}
918 
919 	if (!skb_cloned(skb)) {
920 		if (!skb_is_nonlinear(skb)) {
921 			nfrags = 1;
922 
923 			goto skip_cow;
924 		} else if (!skb_has_frag_list(skb) &&
925 			   !skb_has_shared_frag(skb)) {
926 			nfrags = skb_shinfo(skb)->nr_frags;
927 			nfrags++;
928 
929 			goto skip_cow;
930 		}
931 	}
932 
933 	nfrags = skb_cow_data(skb, 0, &trailer);
934 	if (nfrags < 0) {
935 		ret = -EINVAL;
936 		goto out;
937 	}
938 
939 skip_cow:
940 	ret = -ENOMEM;
941 	tmp = esp_alloc_tmp(aead, nfrags, seqhilen);
942 	if (!tmp)
943 		goto out;
944 
945 	ESP_SKB_CB(skb)->tmp = tmp;
946 	seqhi = esp_tmp_extra(tmp);
947 	iv = esp_tmp_iv(aead, tmp, seqhilen);
948 	req = esp_tmp_req(aead, iv);
949 	sg = esp_req_sg(aead, req);
950 
951 	esp_input_set_header(skb, seqhi);
952 
953 	sg_init_table(sg, nfrags);
954 	ret = skb_to_sgvec(skb, sg, 0, skb->len);
955 	if (unlikely(ret < 0)) {
956 		kfree(tmp);
957 		goto out;
958 	}
959 
960 	skb->ip_summed = CHECKSUM_NONE;
961 
962 	if ((x->props.flags & XFRM_STATE_ESN))
963 		aead_request_set_callback(req, 0, esp_input_done_esn, skb);
964 	else
965 		aead_request_set_callback(req, 0, esp_input_done, skb);
966 
967 	aead_request_set_crypt(req, sg, sg, elen + ivlen, iv);
968 	aead_request_set_ad(req, assoclen);
969 
970 	ret = crypto_aead_decrypt(req);
971 	if (ret == -EINPROGRESS)
972 		goto out;
973 
974 	if ((x->props.flags & XFRM_STATE_ESN))
975 		esp_input_restore_header(skb);
976 
977 	ret = esp6_input_done2(skb, ret);
978 
979 out:
980 	return ret;
981 }
982 
983 static int esp6_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
984 		    u8 type, u8 code, int offset, __be32 info)
985 {
986 	struct net *net = dev_net(skb->dev);
987 	const struct ipv6hdr *iph = (const struct ipv6hdr *)skb->data;
988 	struct ip_esp_hdr *esph = (struct ip_esp_hdr *)(skb->data + offset);
989 	struct xfrm_state *x;
990 
991 	if (type != ICMPV6_PKT_TOOBIG &&
992 	    type != NDISC_REDIRECT)
993 		return 0;
994 
995 	x = xfrm_state_lookup(net, skb->mark, (const xfrm_address_t *)&iph->daddr,
996 			      esph->spi, IPPROTO_ESP, AF_INET6);
997 	if (!x)
998 		return 0;
999 
1000 	if (type == NDISC_REDIRECT)
1001 		ip6_redirect(skb, net, skb->dev->ifindex, 0,
1002 			     sock_net_uid(net, NULL));
1003 	else
1004 		ip6_update_pmtu(skb, net, info, 0, 0, sock_net_uid(net, NULL));
1005 	xfrm_state_put(x);
1006 
1007 	return 0;
1008 }
1009 
1010 static void esp6_destroy(struct xfrm_state *x)
1011 {
1012 	struct crypto_aead *aead = x->data;
1013 
1014 	if (!aead)
1015 		return;
1016 
1017 	crypto_free_aead(aead);
1018 }
1019 
1020 static int esp_init_aead(struct xfrm_state *x, struct netlink_ext_ack *extack)
1021 {
1022 	char aead_name[CRYPTO_MAX_ALG_NAME];
1023 	struct crypto_aead *aead;
1024 	int err;
1025 
1026 	if (snprintf(aead_name, CRYPTO_MAX_ALG_NAME, "%s(%s)",
1027 		     x->geniv, x->aead->alg_name) >= CRYPTO_MAX_ALG_NAME) {
1028 		NL_SET_ERR_MSG(extack, "Algorithm name is too long");
1029 		return -ENAMETOOLONG;
1030 	}
1031 
1032 	aead = crypto_alloc_aead(aead_name, 0, 0);
1033 	err = PTR_ERR(aead);
1034 	if (IS_ERR(aead))
1035 		goto error;
1036 
1037 	x->data = aead;
1038 
1039 	err = crypto_aead_setkey(aead, x->aead->alg_key,
1040 				 (x->aead->alg_key_len + 7) / 8);
1041 	if (err)
1042 		goto error;
1043 
1044 	err = crypto_aead_setauthsize(aead, x->aead->alg_icv_len / 8);
1045 	if (err)
1046 		goto error;
1047 
1048 	return 0;
1049 
1050 error:
1051 	NL_SET_ERR_MSG(extack, "Kernel was unable to initialize cryptographic operations");
1052 	return err;
1053 }
1054 
1055 static int esp_init_authenc(struct xfrm_state *x,
1056 			    struct netlink_ext_ack *extack)
1057 {
1058 	struct crypto_aead *aead;
1059 	struct crypto_authenc_key_param *param;
1060 	struct rtattr *rta;
1061 	char *key;
1062 	char *p;
1063 	char authenc_name[CRYPTO_MAX_ALG_NAME];
1064 	unsigned int keylen;
1065 	int err;
1066 
1067 	err = -ENAMETOOLONG;
1068 
1069 	if ((x->props.flags & XFRM_STATE_ESN)) {
1070 		if (snprintf(authenc_name, CRYPTO_MAX_ALG_NAME,
1071 			     "%s%sauthencesn(%s,%s)%s",
1072 			     x->geniv ?: "", x->geniv ? "(" : "",
1073 			     x->aalg ? x->aalg->alg_name : "digest_null",
1074 			     x->ealg->alg_name,
1075 			     x->geniv ? ")" : "") >= CRYPTO_MAX_ALG_NAME) {
1076 			NL_SET_ERR_MSG(extack, "Algorithm name is too long");
1077 			goto error;
1078 		}
1079 	} else {
1080 		if (snprintf(authenc_name, CRYPTO_MAX_ALG_NAME,
1081 			     "%s%sauthenc(%s,%s)%s",
1082 			     x->geniv ?: "", x->geniv ? "(" : "",
1083 			     x->aalg ? x->aalg->alg_name : "digest_null",
1084 			     x->ealg->alg_name,
1085 			     x->geniv ? ")" : "") >= CRYPTO_MAX_ALG_NAME) {
1086 			NL_SET_ERR_MSG(extack, "Algorithm name is too long");
1087 			goto error;
1088 		}
1089 	}
1090 
1091 	aead = crypto_alloc_aead(authenc_name, 0, 0);
1092 	err = PTR_ERR(aead);
1093 	if (IS_ERR(aead)) {
1094 		NL_SET_ERR_MSG(extack, "Kernel was unable to initialize cryptographic operations");
1095 		goto error;
1096 	}
1097 
1098 	x->data = aead;
1099 
1100 	keylen = (x->aalg ? (x->aalg->alg_key_len + 7) / 8 : 0) +
1101 		 (x->ealg->alg_key_len + 7) / 8 + RTA_SPACE(sizeof(*param));
1102 	err = -ENOMEM;
1103 	key = kmalloc(keylen, GFP_KERNEL);
1104 	if (!key)
1105 		goto error;
1106 
1107 	p = key;
1108 	rta = (void *)p;
1109 	rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
1110 	rta->rta_len = RTA_LENGTH(sizeof(*param));
1111 	param = RTA_DATA(rta);
1112 	p += RTA_SPACE(sizeof(*param));
1113 
1114 	if (x->aalg) {
1115 		struct xfrm_algo_desc *aalg_desc;
1116 
1117 		memcpy(p, x->aalg->alg_key, (x->aalg->alg_key_len + 7) / 8);
1118 		p += (x->aalg->alg_key_len + 7) / 8;
1119 
1120 		aalg_desc = xfrm_aalg_get_byname(x->aalg->alg_name, 0);
1121 		BUG_ON(!aalg_desc);
1122 
1123 		err = -EINVAL;
1124 		if (aalg_desc->uinfo.auth.icv_fullbits / 8 !=
1125 		    crypto_aead_authsize(aead)) {
1126 			NL_SET_ERR_MSG(extack, "Kernel was unable to initialize cryptographic operations");
1127 			goto free_key;
1128 		}
1129 
1130 		err = crypto_aead_setauthsize(
1131 			aead, x->aalg->alg_trunc_len / 8);
1132 		if (err) {
1133 			NL_SET_ERR_MSG(extack, "Kernel was unable to initialize cryptographic operations");
1134 			goto free_key;
1135 		}
1136 	}
1137 
1138 	param->enckeylen = cpu_to_be32((x->ealg->alg_key_len + 7) / 8);
1139 	memcpy(p, x->ealg->alg_key, (x->ealg->alg_key_len + 7) / 8);
1140 
1141 	err = crypto_aead_setkey(aead, key, keylen);
1142 
1143 free_key:
1144 	kfree(key);
1145 
1146 error:
1147 	return err;
1148 }
1149 
1150 static int esp6_init_state(struct xfrm_state *x, struct netlink_ext_ack *extack)
1151 {
1152 	struct crypto_aead *aead;
1153 	u32 align;
1154 	int err;
1155 
1156 	x->data = NULL;
1157 
1158 	if (x->aead) {
1159 		err = esp_init_aead(x, extack);
1160 	} else if (x->ealg) {
1161 		err = esp_init_authenc(x, extack);
1162 	} else {
1163 		NL_SET_ERR_MSG(extack, "ESP: AEAD or CRYPT must be provided");
1164 		err = -EINVAL;
1165 	}
1166 
1167 	if (err)
1168 		goto error;
1169 
1170 	aead = x->data;
1171 
1172 	x->props.header_len = sizeof(struct ip_esp_hdr) +
1173 			      crypto_aead_ivsize(aead);
1174 	switch (x->props.mode) {
1175 	case XFRM_MODE_BEET:
1176 		if (x->sel.family != AF_INET6)
1177 			x->props.header_len += IPV4_BEET_PHMAXLEN +
1178 					       (sizeof(struct ipv6hdr) - sizeof(struct iphdr));
1179 		break;
1180 	default:
1181 	case XFRM_MODE_TRANSPORT:
1182 		break;
1183 	case XFRM_MODE_TUNNEL:
1184 		x->props.header_len += sizeof(struct ipv6hdr);
1185 		break;
1186 	}
1187 
1188 	if (x->encap) {
1189 		struct xfrm_encap_tmpl *encap = x->encap;
1190 
1191 		switch (encap->encap_type) {
1192 		default:
1193 			NL_SET_ERR_MSG(extack, "Unsupported encapsulation type for ESP");
1194 			err = -EINVAL;
1195 			goto error;
1196 		case UDP_ENCAP_ESPINUDP:
1197 			x->props.header_len += sizeof(struct udphdr);
1198 			break;
1199 #ifdef CONFIG_INET6_ESPINTCP
1200 		case TCP_ENCAP_ESPINTCP:
1201 			/* only the length field, TCP encap is done by
1202 			 * the socket
1203 			 */
1204 			x->props.header_len += 2;
1205 			break;
1206 #endif
1207 		}
1208 	}
1209 
1210 	align = ALIGN(crypto_aead_blocksize(aead), 4);
1211 	x->props.trailer_len = align + 1 + crypto_aead_authsize(aead);
1212 
1213 error:
1214 	return err;
1215 }
1216 
1217 static int esp6_rcv_cb(struct sk_buff *skb, int err)
1218 {
1219 	return 0;
1220 }
1221 
1222 static const struct xfrm_type esp6_type = {
1223 	.owner		= THIS_MODULE,
1224 	.proto		= IPPROTO_ESP,
1225 	.flags		= XFRM_TYPE_REPLAY_PROT,
1226 	.init_state	= esp6_init_state,
1227 	.destructor	= esp6_destroy,
1228 	.input		= esp6_input,
1229 	.output		= esp6_output,
1230 };
1231 
1232 static struct xfrm6_protocol esp6_protocol = {
1233 	.handler	=	xfrm6_rcv,
1234 	.input_handler	=	xfrm_input,
1235 	.cb_handler	=	esp6_rcv_cb,
1236 	.err_handler	=	esp6_err,
1237 	.priority	=	0,
1238 };
1239 
1240 static int __init esp6_init(void)
1241 {
1242 	if (xfrm_register_type(&esp6_type, AF_INET6) < 0) {
1243 		pr_info("%s: can't add xfrm type\n", __func__);
1244 		return -EAGAIN;
1245 	}
1246 	if (xfrm6_protocol_register(&esp6_protocol, IPPROTO_ESP) < 0) {
1247 		pr_info("%s: can't add protocol\n", __func__);
1248 		xfrm_unregister_type(&esp6_type, AF_INET6);
1249 		return -EAGAIN;
1250 	}
1251 
1252 	return 0;
1253 }
1254 
1255 static void __exit esp6_fini(void)
1256 {
1257 	if (xfrm6_protocol_deregister(&esp6_protocol, IPPROTO_ESP) < 0)
1258 		pr_info("%s: can't remove protocol\n", __func__);
1259 	xfrm_unregister_type(&esp6_type, AF_INET6);
1260 }
1261 
1262 module_init(esp6_init);
1263 module_exit(esp6_fini);
1264 
1265 MODULE_DESCRIPTION("IPv6 ESP transformation helpers");
1266 MODULE_LICENSE("GPL");
1267 MODULE_ALIAS_XFRM_TYPE(AF_INET6, XFRM_PROTO_ESP);
1268