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