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