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