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