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