1 // SPDX-License-Identifier: GPL-2.0 2 #include <linux/crypto.h> 3 #include <linux/err.h> 4 #include <linux/init.h> 5 #include <linux/kernel.h> 6 #include <linux/list.h> 7 #include <linux/tcp.h> 8 #include <linux/rcupdate.h> 9 #include <linux/rculist.h> 10 #include <net/inetpeer.h> 11 #include <net/tcp.h> 12 13 void tcp_fastopen_init_key_once(struct net *net) 14 { 15 u8 key[TCP_FASTOPEN_KEY_LENGTH]; 16 struct tcp_fastopen_context *ctxt; 17 18 rcu_read_lock(); 19 ctxt = rcu_dereference(net->ipv4.tcp_fastopen_ctx); 20 if (ctxt) { 21 rcu_read_unlock(); 22 return; 23 } 24 rcu_read_unlock(); 25 26 /* tcp_fastopen_reset_cipher publishes the new context 27 * atomically, so we allow this race happening here. 28 * 29 * All call sites of tcp_fastopen_cookie_gen also check 30 * for a valid cookie, so this is an acceptable risk. 31 */ 32 get_random_bytes(key, sizeof(key)); 33 tcp_fastopen_reset_cipher(net, NULL, key, NULL, sizeof(key)); 34 } 35 36 static void tcp_fastopen_ctx_free(struct rcu_head *head) 37 { 38 struct tcp_fastopen_context *ctx = 39 container_of(head, struct tcp_fastopen_context, rcu); 40 int i; 41 42 /* We own ctx, thus no need to hold the Fastopen-lock */ 43 for (i = 0; i < TCP_FASTOPEN_KEY_MAX; i++) { 44 if (ctx->tfm[i]) 45 crypto_free_cipher(ctx->tfm[i]); 46 } 47 kfree(ctx); 48 } 49 50 void tcp_fastopen_destroy_cipher(struct sock *sk) 51 { 52 struct tcp_fastopen_context *ctx; 53 54 ctx = rcu_dereference_protected( 55 inet_csk(sk)->icsk_accept_queue.fastopenq.ctx, 1); 56 if (ctx) 57 call_rcu(&ctx->rcu, tcp_fastopen_ctx_free); 58 } 59 60 void tcp_fastopen_ctx_destroy(struct net *net) 61 { 62 struct tcp_fastopen_context *ctxt; 63 64 spin_lock(&net->ipv4.tcp_fastopen_ctx_lock); 65 66 ctxt = rcu_dereference_protected(net->ipv4.tcp_fastopen_ctx, 67 lockdep_is_held(&net->ipv4.tcp_fastopen_ctx_lock)); 68 rcu_assign_pointer(net->ipv4.tcp_fastopen_ctx, NULL); 69 spin_unlock(&net->ipv4.tcp_fastopen_ctx_lock); 70 71 if (ctxt) 72 call_rcu(&ctxt->rcu, tcp_fastopen_ctx_free); 73 } 74 75 struct tcp_fastopen_context *tcp_fastopen_alloc_ctx(void *primary_key, 76 void *backup_key, 77 unsigned int len) 78 { 79 struct tcp_fastopen_context *new_ctx; 80 void *key = primary_key; 81 int err, i; 82 83 new_ctx = kmalloc(sizeof(*new_ctx), GFP_KERNEL); 84 if (!new_ctx) 85 return ERR_PTR(-ENOMEM); 86 for (i = 0; i < TCP_FASTOPEN_KEY_MAX; i++) 87 new_ctx->tfm[i] = NULL; 88 for (i = 0; i < (backup_key ? 2 : 1); i++) { 89 new_ctx->tfm[i] = crypto_alloc_cipher("aes", 0, 0); 90 if (IS_ERR(new_ctx->tfm[i])) { 91 err = PTR_ERR(new_ctx->tfm[i]); 92 new_ctx->tfm[i] = NULL; 93 pr_err("TCP: TFO aes cipher alloc error: %d\n", err); 94 goto out; 95 } 96 err = crypto_cipher_setkey(new_ctx->tfm[i], key, len); 97 if (err) { 98 pr_err("TCP: TFO cipher key error: %d\n", err); 99 goto out; 100 } 101 memcpy(&new_ctx->key[i * TCP_FASTOPEN_KEY_LENGTH], key, len); 102 key = backup_key; 103 } 104 return new_ctx; 105 out: 106 tcp_fastopen_ctx_free(&new_ctx->rcu); 107 return ERR_PTR(err); 108 } 109 110 int tcp_fastopen_reset_cipher(struct net *net, struct sock *sk, 111 void *primary_key, void *backup_key, 112 unsigned int len) 113 { 114 struct tcp_fastopen_context *ctx, *octx; 115 struct fastopen_queue *q; 116 int err = 0; 117 118 ctx = tcp_fastopen_alloc_ctx(primary_key, backup_key, len); 119 if (IS_ERR(ctx)) { 120 err = PTR_ERR(ctx); 121 goto out; 122 } 123 spin_lock(&net->ipv4.tcp_fastopen_ctx_lock); 124 if (sk) { 125 q = &inet_csk(sk)->icsk_accept_queue.fastopenq; 126 octx = rcu_dereference_protected(q->ctx, 127 lockdep_is_held(&net->ipv4.tcp_fastopen_ctx_lock)); 128 rcu_assign_pointer(q->ctx, ctx); 129 } else { 130 octx = rcu_dereference_protected(net->ipv4.tcp_fastopen_ctx, 131 lockdep_is_held(&net->ipv4.tcp_fastopen_ctx_lock)); 132 rcu_assign_pointer(net->ipv4.tcp_fastopen_ctx, ctx); 133 } 134 spin_unlock(&net->ipv4.tcp_fastopen_ctx_lock); 135 136 if (octx) 137 call_rcu(&octx->rcu, tcp_fastopen_ctx_free); 138 out: 139 return err; 140 } 141 142 static bool __tcp_fastopen_cookie_gen_cipher(struct request_sock *req, 143 struct sk_buff *syn, 144 struct crypto_cipher *tfm, 145 struct tcp_fastopen_cookie *foc) 146 { 147 if (req->rsk_ops->family == AF_INET) { 148 const struct iphdr *iph = ip_hdr(syn); 149 __be32 path[4] = { iph->saddr, iph->daddr, 0, 0 }; 150 151 crypto_cipher_encrypt_one(tfm, foc->val, (void *)path); 152 foc->len = TCP_FASTOPEN_COOKIE_SIZE; 153 return true; 154 } 155 156 #if IS_ENABLED(CONFIG_IPV6) 157 if (req->rsk_ops->family == AF_INET6) { 158 const struct ipv6hdr *ip6h = ipv6_hdr(syn); 159 struct tcp_fastopen_cookie tmp; 160 struct in6_addr *buf; 161 int i; 162 163 crypto_cipher_encrypt_one(tfm, tmp.val, 164 (void *)&ip6h->saddr); 165 buf = &tmp.addr; 166 for (i = 0; i < 4; i++) 167 buf->s6_addr32[i] ^= ip6h->daddr.s6_addr32[i]; 168 crypto_cipher_encrypt_one(tfm, foc->val, (void *)buf); 169 foc->len = TCP_FASTOPEN_COOKIE_SIZE; 170 return true; 171 } 172 #endif 173 return false; 174 } 175 176 /* Generate the fastopen cookie by doing aes128 encryption on both 177 * the source and destination addresses. Pad 0s for IPv4 or IPv4-mapped-IPv6 178 * addresses. For the longer IPv6 addresses use CBC-MAC. 179 * 180 * XXX (TFO) - refactor when TCP_FASTOPEN_COOKIE_SIZE != AES_BLOCK_SIZE. 181 */ 182 static void tcp_fastopen_cookie_gen(struct sock *sk, 183 struct request_sock *req, 184 struct sk_buff *syn, 185 struct tcp_fastopen_cookie *foc) 186 { 187 struct tcp_fastopen_context *ctx; 188 189 rcu_read_lock(); 190 ctx = tcp_fastopen_get_ctx(sk); 191 if (ctx) 192 __tcp_fastopen_cookie_gen_cipher(req, syn, ctx->tfm[0], foc); 193 rcu_read_unlock(); 194 } 195 196 /* If an incoming SYN or SYNACK frame contains a payload and/or FIN, 197 * queue this additional data / FIN. 198 */ 199 void tcp_fastopen_add_skb(struct sock *sk, struct sk_buff *skb) 200 { 201 struct tcp_sock *tp = tcp_sk(sk); 202 203 if (TCP_SKB_CB(skb)->end_seq == tp->rcv_nxt) 204 return; 205 206 skb = skb_clone(skb, GFP_ATOMIC); 207 if (!skb) 208 return; 209 210 skb_dst_drop(skb); 211 /* segs_in has been initialized to 1 in tcp_create_openreq_child(). 212 * Hence, reset segs_in to 0 before calling tcp_segs_in() 213 * to avoid double counting. Also, tcp_segs_in() expects 214 * skb->len to include the tcp_hdrlen. Hence, it should 215 * be called before __skb_pull(). 216 */ 217 tp->segs_in = 0; 218 tcp_segs_in(tp, skb); 219 __skb_pull(skb, tcp_hdrlen(skb)); 220 sk_forced_mem_schedule(sk, skb->truesize); 221 skb_set_owner_r(skb, sk); 222 223 TCP_SKB_CB(skb)->seq++; 224 TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_SYN; 225 226 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq; 227 __skb_queue_tail(&sk->sk_receive_queue, skb); 228 tp->syn_data_acked = 1; 229 230 /* u64_stats_update_begin(&tp->syncp) not needed here, 231 * as we certainly are not changing upper 32bit value (0) 232 */ 233 tp->bytes_received = skb->len; 234 235 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) 236 tcp_fin(sk); 237 } 238 239 /* returns 0 - no key match, 1 for primary, 2 for backup */ 240 static int tcp_fastopen_cookie_gen_check(struct sock *sk, 241 struct request_sock *req, 242 struct sk_buff *syn, 243 struct tcp_fastopen_cookie *orig, 244 struct tcp_fastopen_cookie *valid_foc) 245 { 246 struct tcp_fastopen_cookie search_foc = { .len = -1 }; 247 struct tcp_fastopen_cookie *foc = valid_foc; 248 struct tcp_fastopen_context *ctx; 249 int i, ret = 0; 250 251 rcu_read_lock(); 252 ctx = tcp_fastopen_get_ctx(sk); 253 if (!ctx) 254 goto out; 255 for (i = 0; i < tcp_fastopen_context_len(ctx); i++) { 256 __tcp_fastopen_cookie_gen_cipher(req, syn, ctx->tfm[i], foc); 257 if (tcp_fastopen_cookie_match(foc, orig)) { 258 ret = i + 1; 259 goto out; 260 } 261 foc = &search_foc; 262 } 263 out: 264 rcu_read_unlock(); 265 return ret; 266 } 267 268 static struct sock *tcp_fastopen_create_child(struct sock *sk, 269 struct sk_buff *skb, 270 struct request_sock *req) 271 { 272 struct tcp_sock *tp; 273 struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue; 274 struct sock *child; 275 bool own_req; 276 277 req->num_retrans = 0; 278 req->num_timeout = 0; 279 req->sk = NULL; 280 281 child = inet_csk(sk)->icsk_af_ops->syn_recv_sock(sk, skb, req, NULL, 282 NULL, &own_req); 283 if (!child) 284 return NULL; 285 286 spin_lock(&queue->fastopenq.lock); 287 queue->fastopenq.qlen++; 288 spin_unlock(&queue->fastopenq.lock); 289 290 /* Initialize the child socket. Have to fix some values to take 291 * into account the child is a Fast Open socket and is created 292 * only out of the bits carried in the SYN packet. 293 */ 294 tp = tcp_sk(child); 295 296 tp->fastopen_rsk = req; 297 tcp_rsk(req)->tfo_listener = true; 298 299 /* RFC1323: The window in SYN & SYN/ACK segments is never 300 * scaled. So correct it appropriately. 301 */ 302 tp->snd_wnd = ntohs(tcp_hdr(skb)->window); 303 tp->max_window = tp->snd_wnd; 304 305 /* Activate the retrans timer so that SYNACK can be retransmitted. 306 * The request socket is not added to the ehash 307 * because it's been added to the accept queue directly. 308 */ 309 inet_csk_reset_xmit_timer(child, ICSK_TIME_RETRANS, 310 TCP_TIMEOUT_INIT, TCP_RTO_MAX); 311 312 refcount_set(&req->rsk_refcnt, 2); 313 314 /* Now finish processing the fastopen child socket. */ 315 tcp_init_transfer(child, BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB); 316 317 tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1; 318 319 tcp_fastopen_add_skb(child, skb); 320 321 tcp_rsk(req)->rcv_nxt = tp->rcv_nxt; 322 tp->rcv_wup = tp->rcv_nxt; 323 /* tcp_conn_request() is sending the SYNACK, 324 * and queues the child into listener accept queue. 325 */ 326 return child; 327 } 328 329 static bool tcp_fastopen_queue_check(struct sock *sk) 330 { 331 struct fastopen_queue *fastopenq; 332 333 /* Make sure the listener has enabled fastopen, and we don't 334 * exceed the max # of pending TFO requests allowed before trying 335 * to validating the cookie in order to avoid burning CPU cycles 336 * unnecessarily. 337 * 338 * XXX (TFO) - The implication of checking the max_qlen before 339 * processing a cookie request is that clients can't differentiate 340 * between qlen overflow causing Fast Open to be disabled 341 * temporarily vs a server not supporting Fast Open at all. 342 */ 343 fastopenq = &inet_csk(sk)->icsk_accept_queue.fastopenq; 344 if (fastopenq->max_qlen == 0) 345 return false; 346 347 if (fastopenq->qlen >= fastopenq->max_qlen) { 348 struct request_sock *req1; 349 spin_lock(&fastopenq->lock); 350 req1 = fastopenq->rskq_rst_head; 351 if (!req1 || time_after(req1->rsk_timer.expires, jiffies)) { 352 __NET_INC_STATS(sock_net(sk), 353 LINUX_MIB_TCPFASTOPENLISTENOVERFLOW); 354 spin_unlock(&fastopenq->lock); 355 return false; 356 } 357 fastopenq->rskq_rst_head = req1->dl_next; 358 fastopenq->qlen--; 359 spin_unlock(&fastopenq->lock); 360 reqsk_put(req1); 361 } 362 return true; 363 } 364 365 static bool tcp_fastopen_no_cookie(const struct sock *sk, 366 const struct dst_entry *dst, 367 int flag) 368 { 369 return (sock_net(sk)->ipv4.sysctl_tcp_fastopen & flag) || 370 tcp_sk(sk)->fastopen_no_cookie || 371 (dst && dst_metric(dst, RTAX_FASTOPEN_NO_COOKIE)); 372 } 373 374 /* Returns true if we should perform Fast Open on the SYN. The cookie (foc) 375 * may be updated and return the client in the SYN-ACK later. E.g., Fast Open 376 * cookie request (foc->len == 0). 377 */ 378 struct sock *tcp_try_fastopen(struct sock *sk, struct sk_buff *skb, 379 struct request_sock *req, 380 struct tcp_fastopen_cookie *foc, 381 const struct dst_entry *dst) 382 { 383 bool syn_data = TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq + 1; 384 int tcp_fastopen = sock_net(sk)->ipv4.sysctl_tcp_fastopen; 385 struct tcp_fastopen_cookie valid_foc = { .len = -1 }; 386 struct sock *child; 387 int ret = 0; 388 389 if (foc->len == 0) /* Client requests a cookie */ 390 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPFASTOPENCOOKIEREQD); 391 392 if (!((tcp_fastopen & TFO_SERVER_ENABLE) && 393 (syn_data || foc->len >= 0) && 394 tcp_fastopen_queue_check(sk))) { 395 foc->len = -1; 396 return NULL; 397 } 398 399 if (syn_data && 400 tcp_fastopen_no_cookie(sk, dst, TFO_SERVER_COOKIE_NOT_REQD)) 401 goto fastopen; 402 403 if (foc->len == 0) { 404 /* Client requests a cookie. */ 405 tcp_fastopen_cookie_gen(sk, req, skb, &valid_foc); 406 } else if (foc->len > 0) { 407 ret = tcp_fastopen_cookie_gen_check(sk, req, skb, foc, 408 &valid_foc); 409 if (!ret) { 410 NET_INC_STATS(sock_net(sk), 411 LINUX_MIB_TCPFASTOPENPASSIVEFAIL); 412 } else { 413 /* Cookie is valid. Create a (full) child socket to 414 * accept the data in SYN before returning a SYN-ACK to 415 * ack the data. If we fail to create the socket, fall 416 * back and ack the ISN only but includes the same 417 * cookie. 418 * 419 * Note: Data-less SYN with valid cookie is allowed to 420 * send data in SYN_RECV state. 421 */ 422 fastopen: 423 child = tcp_fastopen_create_child(sk, skb, req); 424 if (child) { 425 if (ret == 2) { 426 valid_foc.exp = foc->exp; 427 *foc = valid_foc; 428 NET_INC_STATS(sock_net(sk), 429 LINUX_MIB_TCPFASTOPENPASSIVEALTKEY); 430 } else { 431 foc->len = -1; 432 } 433 NET_INC_STATS(sock_net(sk), 434 LINUX_MIB_TCPFASTOPENPASSIVE); 435 return child; 436 } 437 NET_INC_STATS(sock_net(sk), 438 LINUX_MIB_TCPFASTOPENPASSIVEFAIL); 439 } 440 } 441 valid_foc.exp = foc->exp; 442 *foc = valid_foc; 443 return NULL; 444 } 445 446 bool tcp_fastopen_cookie_check(struct sock *sk, u16 *mss, 447 struct tcp_fastopen_cookie *cookie) 448 { 449 const struct dst_entry *dst; 450 451 tcp_fastopen_cache_get(sk, mss, cookie); 452 453 /* Firewall blackhole issue check */ 454 if (tcp_fastopen_active_should_disable(sk)) { 455 cookie->len = -1; 456 return false; 457 } 458 459 dst = __sk_dst_get(sk); 460 461 if (tcp_fastopen_no_cookie(sk, dst, TFO_CLIENT_NO_COOKIE)) { 462 cookie->len = -1; 463 return true; 464 } 465 return cookie->len > 0; 466 } 467 468 /* This function checks if we want to defer sending SYN until the first 469 * write(). We defer under the following conditions: 470 * 1. fastopen_connect sockopt is set 471 * 2. we have a valid cookie 472 * Return value: return true if we want to defer until application writes data 473 * return false if we want to send out SYN immediately 474 */ 475 bool tcp_fastopen_defer_connect(struct sock *sk, int *err) 476 { 477 struct tcp_fastopen_cookie cookie = { .len = 0 }; 478 struct tcp_sock *tp = tcp_sk(sk); 479 u16 mss; 480 481 if (tp->fastopen_connect && !tp->fastopen_req) { 482 if (tcp_fastopen_cookie_check(sk, &mss, &cookie)) { 483 inet_sk(sk)->defer_connect = 1; 484 return true; 485 } 486 487 /* Alloc fastopen_req in order for FO option to be included 488 * in SYN 489 */ 490 tp->fastopen_req = kzalloc(sizeof(*tp->fastopen_req), 491 sk->sk_allocation); 492 if (tp->fastopen_req) 493 tp->fastopen_req->cookie = cookie; 494 else 495 *err = -ENOBUFS; 496 } 497 return false; 498 } 499 EXPORT_SYMBOL(tcp_fastopen_defer_connect); 500 501 /* 502 * The following code block is to deal with middle box issues with TFO: 503 * Middlebox firewall issues can potentially cause server's data being 504 * blackholed after a successful 3WHS using TFO. 505 * The proposed solution is to disable active TFO globally under the 506 * following circumstances: 507 * 1. client side TFO socket receives out of order FIN 508 * 2. client side TFO socket receives out of order RST 509 * 3. client side TFO socket has timed out three times consecutively during 510 * or after handshake 511 * We disable active side TFO globally for 1hr at first. Then if it 512 * happens again, we disable it for 2h, then 4h, 8h, ... 513 * And we reset the timeout back to 1hr when we see a successful active 514 * TFO connection with data exchanges. 515 */ 516 517 /* Disable active TFO and record current jiffies and 518 * tfo_active_disable_times 519 */ 520 void tcp_fastopen_active_disable(struct sock *sk) 521 { 522 struct net *net = sock_net(sk); 523 524 atomic_inc(&net->ipv4.tfo_active_disable_times); 525 net->ipv4.tfo_active_disable_stamp = jiffies; 526 NET_INC_STATS(net, LINUX_MIB_TCPFASTOPENBLACKHOLE); 527 } 528 529 /* Calculate timeout for tfo active disable 530 * Return true if we are still in the active TFO disable period 531 * Return false if timeout already expired and we should use active TFO 532 */ 533 bool tcp_fastopen_active_should_disable(struct sock *sk) 534 { 535 unsigned int tfo_bh_timeout = sock_net(sk)->ipv4.sysctl_tcp_fastopen_blackhole_timeout; 536 int tfo_da_times = atomic_read(&sock_net(sk)->ipv4.tfo_active_disable_times); 537 unsigned long timeout; 538 int multiplier; 539 540 if (!tfo_da_times) 541 return false; 542 543 /* Limit timout to max: 2^6 * initial timeout */ 544 multiplier = 1 << min(tfo_da_times - 1, 6); 545 timeout = multiplier * tfo_bh_timeout * HZ; 546 if (time_before(jiffies, sock_net(sk)->ipv4.tfo_active_disable_stamp + timeout)) 547 return true; 548 549 /* Mark check bit so we can check for successful active TFO 550 * condition and reset tfo_active_disable_times 551 */ 552 tcp_sk(sk)->syn_fastopen_ch = 1; 553 return false; 554 } 555 556 /* Disable active TFO if FIN is the only packet in the ofo queue 557 * and no data is received. 558 * Also check if we can reset tfo_active_disable_times if data is 559 * received successfully on a marked active TFO sockets opened on 560 * a non-loopback interface 561 */ 562 void tcp_fastopen_active_disable_ofo_check(struct sock *sk) 563 { 564 struct tcp_sock *tp = tcp_sk(sk); 565 struct dst_entry *dst; 566 struct sk_buff *skb; 567 568 if (!tp->syn_fastopen) 569 return; 570 571 if (!tp->data_segs_in) { 572 skb = skb_rb_first(&tp->out_of_order_queue); 573 if (skb && !skb_rb_next(skb)) { 574 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) { 575 tcp_fastopen_active_disable(sk); 576 return; 577 } 578 } 579 } else if (tp->syn_fastopen_ch && 580 atomic_read(&sock_net(sk)->ipv4.tfo_active_disable_times)) { 581 dst = sk_dst_get(sk); 582 if (!(dst && dst->dev && (dst->dev->flags & IFF_LOOPBACK))) 583 atomic_set(&sock_net(sk)->ipv4.tfo_active_disable_times, 0); 584 dst_release(dst); 585 } 586 } 587 588 void tcp_fastopen_active_detect_blackhole(struct sock *sk, bool expired) 589 { 590 u32 timeouts = inet_csk(sk)->icsk_retransmits; 591 struct tcp_sock *tp = tcp_sk(sk); 592 593 /* Broken middle-boxes may black-hole Fast Open connection during or 594 * even after the handshake. Be extremely conservative and pause 595 * Fast Open globally after hitting the third consecutive timeout or 596 * exceeding the configured timeout limit. 597 */ 598 if ((tp->syn_fastopen || tp->syn_data || tp->syn_data_acked) && 599 (timeouts == 2 || (timeouts < 2 && expired))) { 600 tcp_fastopen_active_disable(sk); 601 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVEFAIL); 602 } 603 } 604