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