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