inet: refactor inet[6]_lookup functions to take skb
[cascardo/linux.git] / net / ipv4 / inet_diag.c
1 /*
2  * inet_diag.c  Module for monitoring INET transport protocols sockets.
3  *
4  * Authors:     Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
5  *
6  *      This program is free software; you can redistribute it and/or
7  *      modify it under the terms of the GNU General Public License
8  *      as published by the Free Software Foundation; either version
9  *      2 of the License, or (at your option) any later version.
10  */
11
12 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/types.h>
15 #include <linux/fcntl.h>
16 #include <linux/random.h>
17 #include <linux/slab.h>
18 #include <linux/cache.h>
19 #include <linux/init.h>
20 #include <linux/time.h>
21
22 #include <net/icmp.h>
23 #include <net/tcp.h>
24 #include <net/ipv6.h>
25 #include <net/inet_common.h>
26 #include <net/inet_connection_sock.h>
27 #include <net/inet_hashtables.h>
28 #include <net/inet_timewait_sock.h>
29 #include <net/inet6_hashtables.h>
30 #include <net/netlink.h>
31
32 #include <linux/inet.h>
33 #include <linux/stddef.h>
34
35 #include <linux/inet_diag.h>
36 #include <linux/sock_diag.h>
37
38 static const struct inet_diag_handler **inet_diag_table;
39
40 struct inet_diag_entry {
41         const __be32 *saddr;
42         const __be32 *daddr;
43         u16 sport;
44         u16 dport;
45         u16 family;
46         u16 userlocks;
47 };
48
49 static DEFINE_MUTEX(inet_diag_table_mutex);
50
51 static const struct inet_diag_handler *inet_diag_lock_handler(int proto)
52 {
53         if (!inet_diag_table[proto])
54                 request_module("net-pf-%d-proto-%d-type-%d-%d", PF_NETLINK,
55                                NETLINK_SOCK_DIAG, AF_INET, proto);
56
57         mutex_lock(&inet_diag_table_mutex);
58         if (!inet_diag_table[proto])
59                 return ERR_PTR(-ENOENT);
60
61         return inet_diag_table[proto];
62 }
63
64 static void inet_diag_unlock_handler(const struct inet_diag_handler *handler)
65 {
66         mutex_unlock(&inet_diag_table_mutex);
67 }
68
69 static void inet_diag_msg_common_fill(struct inet_diag_msg *r, struct sock *sk)
70 {
71         r->idiag_family = sk->sk_family;
72
73         r->id.idiag_sport = htons(sk->sk_num);
74         r->id.idiag_dport = sk->sk_dport;
75         r->id.idiag_if = sk->sk_bound_dev_if;
76         sock_diag_save_cookie(sk, r->id.idiag_cookie);
77
78 #if IS_ENABLED(CONFIG_IPV6)
79         if (sk->sk_family == AF_INET6) {
80                 *(struct in6_addr *)r->id.idiag_src = sk->sk_v6_rcv_saddr;
81                 *(struct in6_addr *)r->id.idiag_dst = sk->sk_v6_daddr;
82         } else
83 #endif
84         {
85         memset(&r->id.idiag_src, 0, sizeof(r->id.idiag_src));
86         memset(&r->id.idiag_dst, 0, sizeof(r->id.idiag_dst));
87
88         r->id.idiag_src[0] = sk->sk_rcv_saddr;
89         r->id.idiag_dst[0] = sk->sk_daddr;
90         }
91 }
92
93 static size_t inet_sk_attr_size(void)
94 {
95         return    nla_total_size(sizeof(struct tcp_info))
96                 + nla_total_size(1) /* INET_DIAG_SHUTDOWN */
97                 + nla_total_size(1) /* INET_DIAG_TOS */
98                 + nla_total_size(1) /* INET_DIAG_TCLASS */
99                 + nla_total_size(sizeof(struct inet_diag_meminfo))
100                 + nla_total_size(sizeof(struct inet_diag_msg))
101                 + nla_total_size(SK_MEMINFO_VARS * sizeof(u32))
102                 + nla_total_size(TCP_CA_NAME_MAX)
103                 + nla_total_size(sizeof(struct tcpvegas_info))
104                 + 64;
105 }
106
107 int inet_sk_diag_fill(struct sock *sk, struct inet_connection_sock *icsk,
108                       struct sk_buff *skb, const struct inet_diag_req_v2 *req,
109                       struct user_namespace *user_ns,
110                       u32 portid, u32 seq, u16 nlmsg_flags,
111                       const struct nlmsghdr *unlh)
112 {
113         const struct inet_sock *inet = inet_sk(sk);
114         const struct tcp_congestion_ops *ca_ops;
115         const struct inet_diag_handler *handler;
116         int ext = req->idiag_ext;
117         struct inet_diag_msg *r;
118         struct nlmsghdr  *nlh;
119         struct nlattr *attr;
120         void *info = NULL;
121
122         handler = inet_diag_table[req->sdiag_protocol];
123         BUG_ON(!handler);
124
125         nlh = nlmsg_put(skb, portid, seq, unlh->nlmsg_type, sizeof(*r),
126                         nlmsg_flags);
127         if (!nlh)
128                 return -EMSGSIZE;
129
130         r = nlmsg_data(nlh);
131         BUG_ON(!sk_fullsock(sk));
132
133         inet_diag_msg_common_fill(r, sk);
134         r->idiag_state = sk->sk_state;
135         r->idiag_timer = 0;
136         r->idiag_retrans = 0;
137
138         if (nla_put_u8(skb, INET_DIAG_SHUTDOWN, sk->sk_shutdown))
139                 goto errout;
140
141         /* IPv6 dual-stack sockets use inet->tos for IPv4 connections,
142          * hence this needs to be included regardless of socket family.
143          */
144         if (ext & (1 << (INET_DIAG_TOS - 1)))
145                 if (nla_put_u8(skb, INET_DIAG_TOS, inet->tos) < 0)
146                         goto errout;
147
148 #if IS_ENABLED(CONFIG_IPV6)
149         if (r->idiag_family == AF_INET6) {
150                 if (ext & (1 << (INET_DIAG_TCLASS - 1)))
151                         if (nla_put_u8(skb, INET_DIAG_TCLASS,
152                                        inet6_sk(sk)->tclass) < 0)
153                                 goto errout;
154
155                 if (((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) &&
156                     nla_put_u8(skb, INET_DIAG_SKV6ONLY, ipv6_only_sock(sk)))
157                         goto errout;
158         }
159 #endif
160
161         r->idiag_uid = from_kuid_munged(user_ns, sock_i_uid(sk));
162         r->idiag_inode = sock_i_ino(sk);
163
164         if (ext & (1 << (INET_DIAG_MEMINFO - 1))) {
165                 struct inet_diag_meminfo minfo = {
166                         .idiag_rmem = sk_rmem_alloc_get(sk),
167                         .idiag_wmem = sk->sk_wmem_queued,
168                         .idiag_fmem = sk->sk_forward_alloc,
169                         .idiag_tmem = sk_wmem_alloc_get(sk),
170                 };
171
172                 if (nla_put(skb, INET_DIAG_MEMINFO, sizeof(minfo), &minfo) < 0)
173                         goto errout;
174         }
175
176         if (ext & (1 << (INET_DIAG_SKMEMINFO - 1)))
177                 if (sock_diag_put_meminfo(sk, skb, INET_DIAG_SKMEMINFO))
178                         goto errout;
179
180         if (!icsk) {
181                 handler->idiag_get_info(sk, r, NULL);
182                 goto out;
183         }
184
185 #define EXPIRES_IN_MS(tmo)  DIV_ROUND_UP((tmo - jiffies) * 1000, HZ)
186
187         if (icsk->icsk_pending == ICSK_TIME_RETRANS ||
188             icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS ||
189             icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
190                 r->idiag_timer = 1;
191                 r->idiag_retrans = icsk->icsk_retransmits;
192                 r->idiag_expires = EXPIRES_IN_MS(icsk->icsk_timeout);
193         } else if (icsk->icsk_pending == ICSK_TIME_PROBE0) {
194                 r->idiag_timer = 4;
195                 r->idiag_retrans = icsk->icsk_probes_out;
196                 r->idiag_expires = EXPIRES_IN_MS(icsk->icsk_timeout);
197         } else if (timer_pending(&sk->sk_timer)) {
198                 r->idiag_timer = 2;
199                 r->idiag_retrans = icsk->icsk_probes_out;
200                 r->idiag_expires = EXPIRES_IN_MS(sk->sk_timer.expires);
201         } else {
202                 r->idiag_timer = 0;
203                 r->idiag_expires = 0;
204         }
205 #undef EXPIRES_IN_MS
206
207         if ((ext & (1 << (INET_DIAG_INFO - 1))) && handler->idiag_info_size) {
208                 attr = nla_reserve(skb, INET_DIAG_INFO,
209                                    handler->idiag_info_size);
210                 if (!attr)
211                         goto errout;
212
213                 info = nla_data(attr);
214         }
215
216         if (ext & (1 << (INET_DIAG_CONG - 1))) {
217                 int err = 0;
218
219                 rcu_read_lock();
220                 ca_ops = READ_ONCE(icsk->icsk_ca_ops);
221                 if (ca_ops)
222                         err = nla_put_string(skb, INET_DIAG_CONG, ca_ops->name);
223                 rcu_read_unlock();
224                 if (err < 0)
225                         goto errout;
226         }
227
228         handler->idiag_get_info(sk, r, info);
229
230         if (sk->sk_state < TCP_TIME_WAIT) {
231                 union tcp_cc_info info;
232                 size_t sz = 0;
233                 int attr;
234
235                 rcu_read_lock();
236                 ca_ops = READ_ONCE(icsk->icsk_ca_ops);
237                 if (ca_ops && ca_ops->get_info)
238                         sz = ca_ops->get_info(sk, ext, &attr, &info);
239                 rcu_read_unlock();
240                 if (sz && nla_put(skb, attr, sz, &info) < 0)
241                         goto errout;
242         }
243
244 out:
245         nlmsg_end(skb, nlh);
246         return 0;
247
248 errout:
249         nlmsg_cancel(skb, nlh);
250         return -EMSGSIZE;
251 }
252 EXPORT_SYMBOL_GPL(inet_sk_diag_fill);
253
254 static int inet_csk_diag_fill(struct sock *sk,
255                               struct sk_buff *skb,
256                               const struct inet_diag_req_v2 *req,
257                               struct user_namespace *user_ns,
258                               u32 portid, u32 seq, u16 nlmsg_flags,
259                               const struct nlmsghdr *unlh)
260 {
261         return inet_sk_diag_fill(sk, inet_csk(sk), skb, req,
262                                  user_ns, portid, seq, nlmsg_flags, unlh);
263 }
264
265 static int inet_twsk_diag_fill(struct sock *sk,
266                                struct sk_buff *skb,
267                                u32 portid, u32 seq, u16 nlmsg_flags,
268                                const struct nlmsghdr *unlh)
269 {
270         struct inet_timewait_sock *tw = inet_twsk(sk);
271         struct inet_diag_msg *r;
272         struct nlmsghdr *nlh;
273         long tmo;
274
275         nlh = nlmsg_put(skb, portid, seq, unlh->nlmsg_type, sizeof(*r),
276                         nlmsg_flags);
277         if (!nlh)
278                 return -EMSGSIZE;
279
280         r = nlmsg_data(nlh);
281         BUG_ON(tw->tw_state != TCP_TIME_WAIT);
282
283         tmo = tw->tw_timer.expires - jiffies;
284         if (tmo < 0)
285                 tmo = 0;
286
287         inet_diag_msg_common_fill(r, sk);
288         r->idiag_retrans      = 0;
289
290         r->idiag_state        = tw->tw_substate;
291         r->idiag_timer        = 3;
292         r->idiag_expires      = jiffies_to_msecs(tmo);
293         r->idiag_rqueue       = 0;
294         r->idiag_wqueue       = 0;
295         r->idiag_uid          = 0;
296         r->idiag_inode        = 0;
297
298         nlmsg_end(skb, nlh);
299         return 0;
300 }
301
302 static int inet_req_diag_fill(struct sock *sk, struct sk_buff *skb,
303                               u32 portid, u32 seq, u16 nlmsg_flags,
304                               const struct nlmsghdr *unlh)
305 {
306         struct inet_diag_msg *r;
307         struct nlmsghdr *nlh;
308         long tmo;
309
310         nlh = nlmsg_put(skb, portid, seq, unlh->nlmsg_type, sizeof(*r),
311                         nlmsg_flags);
312         if (!nlh)
313                 return -EMSGSIZE;
314
315         r = nlmsg_data(nlh);
316         inet_diag_msg_common_fill(r, sk);
317         r->idiag_state = TCP_SYN_RECV;
318         r->idiag_timer = 1;
319         r->idiag_retrans = inet_reqsk(sk)->num_retrans;
320
321         BUILD_BUG_ON(offsetof(struct inet_request_sock, ir_cookie) !=
322                      offsetof(struct sock, sk_cookie));
323
324         tmo = inet_reqsk(sk)->rsk_timer.expires - jiffies;
325         r->idiag_expires = (tmo >= 0) ? jiffies_to_msecs(tmo) : 0;
326         r->idiag_rqueue = 0;
327         r->idiag_wqueue = 0;
328         r->idiag_uid    = 0;
329         r->idiag_inode  = 0;
330
331         nlmsg_end(skb, nlh);
332         return 0;
333 }
334
335 static int sk_diag_fill(struct sock *sk, struct sk_buff *skb,
336                         const struct inet_diag_req_v2 *r,
337                         struct user_namespace *user_ns,
338                         u32 portid, u32 seq, u16 nlmsg_flags,
339                         const struct nlmsghdr *unlh)
340 {
341         if (sk->sk_state == TCP_TIME_WAIT)
342                 return inet_twsk_diag_fill(sk, skb, portid, seq,
343                                            nlmsg_flags, unlh);
344
345         if (sk->sk_state == TCP_NEW_SYN_RECV)
346                 return inet_req_diag_fill(sk, skb, portid, seq,
347                                           nlmsg_flags, unlh);
348
349         return inet_csk_diag_fill(sk, skb, r, user_ns, portid, seq,
350                                   nlmsg_flags, unlh);
351 }
352
353 struct sock *inet_diag_find_one_icsk(struct net *net,
354                                      struct inet_hashinfo *hashinfo,
355                                      const struct inet_diag_req_v2 *req)
356 {
357         struct sock *sk;
358
359         if (req->sdiag_family == AF_INET)
360                 sk = inet_lookup(net, hashinfo, NULL, 0, req->id.idiag_dst[0],
361                                  req->id.idiag_dport, req->id.idiag_src[0],
362                                  req->id.idiag_sport, req->id.idiag_if);
363 #if IS_ENABLED(CONFIG_IPV6)
364         else if (req->sdiag_family == AF_INET6) {
365                 if (ipv6_addr_v4mapped((struct in6_addr *)req->id.idiag_dst) &&
366                     ipv6_addr_v4mapped((struct in6_addr *)req->id.idiag_src))
367                         sk = inet_lookup(net, hashinfo, NULL, 0, req->id.idiag_dst[3],
368                                          req->id.idiag_dport, req->id.idiag_src[3],
369                                          req->id.idiag_sport, req->id.idiag_if);
370                 else
371                         sk = inet6_lookup(net, hashinfo, NULL, 0,
372                                           (struct in6_addr *)req->id.idiag_dst,
373                                           req->id.idiag_dport,
374                                           (struct in6_addr *)req->id.idiag_src,
375                                           req->id.idiag_sport,
376                                           req->id.idiag_if);
377         }
378 #endif
379         else
380                 return ERR_PTR(-EINVAL);
381
382         if (!sk)
383                 return ERR_PTR(-ENOENT);
384
385         if (sock_diag_check_cookie(sk, req->id.idiag_cookie)) {
386                 sock_gen_put(sk);
387                 return ERR_PTR(-ENOENT);
388         }
389
390         return sk;
391 }
392 EXPORT_SYMBOL_GPL(inet_diag_find_one_icsk);
393
394 int inet_diag_dump_one_icsk(struct inet_hashinfo *hashinfo,
395                             struct sk_buff *in_skb,
396                             const struct nlmsghdr *nlh,
397                             const struct inet_diag_req_v2 *req)
398 {
399         struct net *net = sock_net(in_skb->sk);
400         struct sk_buff *rep;
401         struct sock *sk;
402         int err;
403
404         sk = inet_diag_find_one_icsk(net, hashinfo, req);
405         if (IS_ERR(sk))
406                 return PTR_ERR(sk);
407
408         rep = nlmsg_new(inet_sk_attr_size(), GFP_KERNEL);
409         if (!rep) {
410                 err = -ENOMEM;
411                 goto out;
412         }
413
414         err = sk_diag_fill(sk, rep, req,
415                            sk_user_ns(NETLINK_CB(in_skb).sk),
416                            NETLINK_CB(in_skb).portid,
417                            nlh->nlmsg_seq, 0, nlh);
418         if (err < 0) {
419                 WARN_ON(err == -EMSGSIZE);
420                 nlmsg_free(rep);
421                 goto out;
422         }
423         err = netlink_unicast(net->diag_nlsk, rep, NETLINK_CB(in_skb).portid,
424                               MSG_DONTWAIT);
425         if (err > 0)
426                 err = 0;
427
428 out:
429         if (sk)
430                 sock_gen_put(sk);
431
432         return err;
433 }
434 EXPORT_SYMBOL_GPL(inet_diag_dump_one_icsk);
435
436 static int inet_diag_cmd_exact(int cmd, struct sk_buff *in_skb,
437                                const struct nlmsghdr *nlh,
438                                const struct inet_diag_req_v2 *req)
439 {
440         const struct inet_diag_handler *handler;
441         int err;
442
443         handler = inet_diag_lock_handler(req->sdiag_protocol);
444         if (IS_ERR(handler))
445                 err = PTR_ERR(handler);
446         else if (cmd == SOCK_DIAG_BY_FAMILY)
447                 err = handler->dump_one(in_skb, nlh, req);
448         else if (cmd == SOCK_DESTROY && handler->destroy)
449                 err = handler->destroy(in_skb, req);
450         else
451                 err = -EOPNOTSUPP;
452         inet_diag_unlock_handler(handler);
453
454         return err;
455 }
456
457 static int bitstring_match(const __be32 *a1, const __be32 *a2, int bits)
458 {
459         int words = bits >> 5;
460
461         bits &= 0x1f;
462
463         if (words) {
464                 if (memcmp(a1, a2, words << 2))
465                         return 0;
466         }
467         if (bits) {
468                 __be32 w1, w2;
469                 __be32 mask;
470
471                 w1 = a1[words];
472                 w2 = a2[words];
473
474                 mask = htonl((0xffffffff) << (32 - bits));
475
476                 if ((w1 ^ w2) & mask)
477                         return 0;
478         }
479
480         return 1;
481 }
482
483 static int inet_diag_bc_run(const struct nlattr *_bc,
484                             const struct inet_diag_entry *entry)
485 {
486         const void *bc = nla_data(_bc);
487         int len = nla_len(_bc);
488
489         while (len > 0) {
490                 int yes = 1;
491                 const struct inet_diag_bc_op *op = bc;
492
493                 switch (op->code) {
494                 case INET_DIAG_BC_NOP:
495                         break;
496                 case INET_DIAG_BC_JMP:
497                         yes = 0;
498                         break;
499                 case INET_DIAG_BC_S_GE:
500                         yes = entry->sport >= op[1].no;
501                         break;
502                 case INET_DIAG_BC_S_LE:
503                         yes = entry->sport <= op[1].no;
504                         break;
505                 case INET_DIAG_BC_D_GE:
506                         yes = entry->dport >= op[1].no;
507                         break;
508                 case INET_DIAG_BC_D_LE:
509                         yes = entry->dport <= op[1].no;
510                         break;
511                 case INET_DIAG_BC_AUTO:
512                         yes = !(entry->userlocks & SOCK_BINDPORT_LOCK);
513                         break;
514                 case INET_DIAG_BC_S_COND:
515                 case INET_DIAG_BC_D_COND: {
516                         const struct inet_diag_hostcond *cond;
517                         const __be32 *addr;
518
519                         cond = (const struct inet_diag_hostcond *)(op + 1);
520                         if (cond->port != -1 &&
521                             cond->port != (op->code == INET_DIAG_BC_S_COND ?
522                                              entry->sport : entry->dport)) {
523                                 yes = 0;
524                                 break;
525                         }
526
527                         if (op->code == INET_DIAG_BC_S_COND)
528                                 addr = entry->saddr;
529                         else
530                                 addr = entry->daddr;
531
532                         if (cond->family != AF_UNSPEC &&
533                             cond->family != entry->family) {
534                                 if (entry->family == AF_INET6 &&
535                                     cond->family == AF_INET) {
536                                         if (addr[0] == 0 && addr[1] == 0 &&
537                                             addr[2] == htonl(0xffff) &&
538                                             bitstring_match(addr + 3,
539                                                             cond->addr,
540                                                             cond->prefix_len))
541                                                 break;
542                                 }
543                                 yes = 0;
544                                 break;
545                         }
546
547                         if (cond->prefix_len == 0)
548                                 break;
549                         if (bitstring_match(addr, cond->addr,
550                                             cond->prefix_len))
551                                 break;
552                         yes = 0;
553                         break;
554                 }
555                 }
556
557                 if (yes) {
558                         len -= op->yes;
559                         bc += op->yes;
560                 } else {
561                         len -= op->no;
562                         bc += op->no;
563                 }
564         }
565         return len == 0;
566 }
567
568 /* This helper is available for all sockets (ESTABLISH, TIMEWAIT, SYN_RECV)
569  */
570 static void entry_fill_addrs(struct inet_diag_entry *entry,
571                              const struct sock *sk)
572 {
573 #if IS_ENABLED(CONFIG_IPV6)
574         if (sk->sk_family == AF_INET6) {
575                 entry->saddr = sk->sk_v6_rcv_saddr.s6_addr32;
576                 entry->daddr = sk->sk_v6_daddr.s6_addr32;
577         } else
578 #endif
579         {
580                 entry->saddr = &sk->sk_rcv_saddr;
581                 entry->daddr = &sk->sk_daddr;
582         }
583 }
584
585 int inet_diag_bc_sk(const struct nlattr *bc, struct sock *sk)
586 {
587         struct inet_sock *inet = inet_sk(sk);
588         struct inet_diag_entry entry;
589
590         if (!bc)
591                 return 1;
592
593         entry.family = sk->sk_family;
594         entry_fill_addrs(&entry, sk);
595         entry.sport = inet->inet_num;
596         entry.dport = ntohs(inet->inet_dport);
597         entry.userlocks = sk_fullsock(sk) ? sk->sk_userlocks : 0;
598
599         return inet_diag_bc_run(bc, &entry);
600 }
601 EXPORT_SYMBOL_GPL(inet_diag_bc_sk);
602
603 static int valid_cc(const void *bc, int len, int cc)
604 {
605         while (len >= 0) {
606                 const struct inet_diag_bc_op *op = bc;
607
608                 if (cc > len)
609                         return 0;
610                 if (cc == len)
611                         return 1;
612                 if (op->yes < 4 || op->yes & 3)
613                         return 0;
614                 len -= op->yes;
615                 bc  += op->yes;
616         }
617         return 0;
618 }
619
620 /* Validate an inet_diag_hostcond. */
621 static bool valid_hostcond(const struct inet_diag_bc_op *op, int len,
622                            int *min_len)
623 {
624         struct inet_diag_hostcond *cond;
625         int addr_len;
626
627         /* Check hostcond space. */
628         *min_len += sizeof(struct inet_diag_hostcond);
629         if (len < *min_len)
630                 return false;
631         cond = (struct inet_diag_hostcond *)(op + 1);
632
633         /* Check address family and address length. */
634         switch (cond->family) {
635         case AF_UNSPEC:
636                 addr_len = 0;
637                 break;
638         case AF_INET:
639                 addr_len = sizeof(struct in_addr);
640                 break;
641         case AF_INET6:
642                 addr_len = sizeof(struct in6_addr);
643                 break;
644         default:
645                 return false;
646         }
647         *min_len += addr_len;
648         if (len < *min_len)
649                 return false;
650
651         /* Check prefix length (in bits) vs address length (in bytes). */
652         if (cond->prefix_len > 8 * addr_len)
653                 return false;
654
655         return true;
656 }
657
658 /* Validate a port comparison operator. */
659 static bool valid_port_comparison(const struct inet_diag_bc_op *op,
660                                   int len, int *min_len)
661 {
662         /* Port comparisons put the port in a follow-on inet_diag_bc_op. */
663         *min_len += sizeof(struct inet_diag_bc_op);
664         if (len < *min_len)
665                 return false;
666         return true;
667 }
668
669 static int inet_diag_bc_audit(const void *bytecode, int bytecode_len)
670 {
671         const void *bc = bytecode;
672         int  len = bytecode_len;
673
674         while (len > 0) {
675                 int min_len = sizeof(struct inet_diag_bc_op);
676                 const struct inet_diag_bc_op *op = bc;
677
678                 switch (op->code) {
679                 case INET_DIAG_BC_S_COND:
680                 case INET_DIAG_BC_D_COND:
681                         if (!valid_hostcond(bc, len, &min_len))
682                                 return -EINVAL;
683                         break;
684                 case INET_DIAG_BC_S_GE:
685                 case INET_DIAG_BC_S_LE:
686                 case INET_DIAG_BC_D_GE:
687                 case INET_DIAG_BC_D_LE:
688                         if (!valid_port_comparison(bc, len, &min_len))
689                                 return -EINVAL;
690                         break;
691                 case INET_DIAG_BC_AUTO:
692                 case INET_DIAG_BC_JMP:
693                 case INET_DIAG_BC_NOP:
694                         break;
695                 default:
696                         return -EINVAL;
697                 }
698
699                 if (op->code != INET_DIAG_BC_NOP) {
700                         if (op->no < min_len || op->no > len + 4 || op->no & 3)
701                                 return -EINVAL;
702                         if (op->no < len &&
703                             !valid_cc(bytecode, bytecode_len, len - op->no))
704                                 return -EINVAL;
705                 }
706
707                 if (op->yes < min_len || op->yes > len + 4 || op->yes & 3)
708                         return -EINVAL;
709                 bc  += op->yes;
710                 len -= op->yes;
711         }
712         return len == 0 ? 0 : -EINVAL;
713 }
714
715 static int inet_csk_diag_dump(struct sock *sk,
716                               struct sk_buff *skb,
717                               struct netlink_callback *cb,
718                               const struct inet_diag_req_v2 *r,
719                               const struct nlattr *bc)
720 {
721         if (!inet_diag_bc_sk(bc, sk))
722                 return 0;
723
724         return inet_csk_diag_fill(sk, skb, r,
725                                   sk_user_ns(NETLINK_CB(cb->skb).sk),
726                                   NETLINK_CB(cb->skb).portid,
727                                   cb->nlh->nlmsg_seq, NLM_F_MULTI, cb->nlh);
728 }
729
730 static void twsk_build_assert(void)
731 {
732         BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_family) !=
733                      offsetof(struct sock, sk_family));
734
735         BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_num) !=
736                      offsetof(struct inet_sock, inet_num));
737
738         BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_dport) !=
739                      offsetof(struct inet_sock, inet_dport));
740
741         BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_rcv_saddr) !=
742                      offsetof(struct inet_sock, inet_rcv_saddr));
743
744         BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_daddr) !=
745                      offsetof(struct inet_sock, inet_daddr));
746
747 #if IS_ENABLED(CONFIG_IPV6)
748         BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_v6_rcv_saddr) !=
749                      offsetof(struct sock, sk_v6_rcv_saddr));
750
751         BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_v6_daddr) !=
752                      offsetof(struct sock, sk_v6_daddr));
753 #endif
754 }
755
756 void inet_diag_dump_icsk(struct inet_hashinfo *hashinfo, struct sk_buff *skb,
757                          struct netlink_callback *cb,
758                          const struct inet_diag_req_v2 *r, struct nlattr *bc)
759 {
760         struct net *net = sock_net(skb->sk);
761         int i, num, s_i, s_num;
762         u32 idiag_states = r->idiag_states;
763
764         if (idiag_states & TCPF_SYN_RECV)
765                 idiag_states |= TCPF_NEW_SYN_RECV;
766         s_i = cb->args[1];
767         s_num = num = cb->args[2];
768
769         if (cb->args[0] == 0) {
770                 if (!(idiag_states & TCPF_LISTEN))
771                         goto skip_listen_ht;
772
773                 for (i = s_i; i < INET_LHTABLE_SIZE; i++) {
774                         struct inet_listen_hashbucket *ilb;
775                         struct hlist_nulls_node *node;
776                         struct sock *sk;
777
778                         num = 0;
779                         ilb = &hashinfo->listening_hash[i];
780                         spin_lock_bh(&ilb->lock);
781                         sk_nulls_for_each(sk, node, &ilb->head) {
782                                 struct inet_sock *inet = inet_sk(sk);
783
784                                 if (!net_eq(sock_net(sk), net))
785                                         continue;
786
787                                 if (num < s_num) {
788                                         num++;
789                                         continue;
790                                 }
791
792                                 if (r->sdiag_family != AF_UNSPEC &&
793                                     sk->sk_family != r->sdiag_family)
794                                         goto next_listen;
795
796                                 if (r->id.idiag_sport != inet->inet_sport &&
797                                     r->id.idiag_sport)
798                                         goto next_listen;
799
800                                 if (r->id.idiag_dport ||
801                                     cb->args[3] > 0)
802                                         goto next_listen;
803
804                                 if (inet_csk_diag_dump(sk, skb, cb, r, bc) < 0) {
805                                         spin_unlock_bh(&ilb->lock);
806                                         goto done;
807                                 }
808
809 next_listen:
810                                 cb->args[3] = 0;
811                                 cb->args[4] = 0;
812                                 ++num;
813                         }
814                         spin_unlock_bh(&ilb->lock);
815
816                         s_num = 0;
817                         cb->args[3] = 0;
818                         cb->args[4] = 0;
819                 }
820 skip_listen_ht:
821                 cb->args[0] = 1;
822                 s_i = num = s_num = 0;
823         }
824
825         if (!(idiag_states & ~TCPF_LISTEN))
826                 goto out;
827
828         for (i = s_i; i <= hashinfo->ehash_mask; i++) {
829                 struct inet_ehash_bucket *head = &hashinfo->ehash[i];
830                 spinlock_t *lock = inet_ehash_lockp(hashinfo, i);
831                 struct hlist_nulls_node *node;
832                 struct sock *sk;
833
834                 num = 0;
835
836                 if (hlist_nulls_empty(&head->chain))
837                         continue;
838
839                 if (i > s_i)
840                         s_num = 0;
841
842                 spin_lock_bh(lock);
843                 sk_nulls_for_each(sk, node, &head->chain) {
844                         int state, res;
845
846                         if (!net_eq(sock_net(sk), net))
847                                 continue;
848                         if (num < s_num)
849                                 goto next_normal;
850                         state = (sk->sk_state == TCP_TIME_WAIT) ?
851                                 inet_twsk(sk)->tw_substate : sk->sk_state;
852                         if (!(idiag_states & (1 << state)))
853                                 goto next_normal;
854                         if (r->sdiag_family != AF_UNSPEC &&
855                             sk->sk_family != r->sdiag_family)
856                                 goto next_normal;
857                         if (r->id.idiag_sport != htons(sk->sk_num) &&
858                             r->id.idiag_sport)
859                                 goto next_normal;
860                         if (r->id.idiag_dport != sk->sk_dport &&
861                             r->id.idiag_dport)
862                                 goto next_normal;
863                         twsk_build_assert();
864
865                         if (!inet_diag_bc_sk(bc, sk))
866                                 goto next_normal;
867
868                         res = sk_diag_fill(sk, skb, r,
869                                            sk_user_ns(NETLINK_CB(cb->skb).sk),
870                                            NETLINK_CB(cb->skb).portid,
871                                            cb->nlh->nlmsg_seq, NLM_F_MULTI,
872                                            cb->nlh);
873                         if (res < 0) {
874                                 spin_unlock_bh(lock);
875                                 goto done;
876                         }
877 next_normal:
878                         ++num;
879                 }
880
881                 spin_unlock_bh(lock);
882         }
883
884 done:
885         cb->args[1] = i;
886         cb->args[2] = num;
887 out:
888         ;
889 }
890 EXPORT_SYMBOL_GPL(inet_diag_dump_icsk);
891
892 static int __inet_diag_dump(struct sk_buff *skb, struct netlink_callback *cb,
893                             const struct inet_diag_req_v2 *r,
894                             struct nlattr *bc)
895 {
896         const struct inet_diag_handler *handler;
897         int err = 0;
898
899         handler = inet_diag_lock_handler(r->sdiag_protocol);
900         if (!IS_ERR(handler))
901                 handler->dump(skb, cb, r, bc);
902         else
903                 err = PTR_ERR(handler);
904         inet_diag_unlock_handler(handler);
905
906         return err ? : skb->len;
907 }
908
909 static int inet_diag_dump(struct sk_buff *skb, struct netlink_callback *cb)
910 {
911         int hdrlen = sizeof(struct inet_diag_req_v2);
912         struct nlattr *bc = NULL;
913
914         if (nlmsg_attrlen(cb->nlh, hdrlen))
915                 bc = nlmsg_find_attr(cb->nlh, hdrlen, INET_DIAG_REQ_BYTECODE);
916
917         return __inet_diag_dump(skb, cb, nlmsg_data(cb->nlh), bc);
918 }
919
920 static int inet_diag_type2proto(int type)
921 {
922         switch (type) {
923         case TCPDIAG_GETSOCK:
924                 return IPPROTO_TCP;
925         case DCCPDIAG_GETSOCK:
926                 return IPPROTO_DCCP;
927         default:
928                 return 0;
929         }
930 }
931
932 static int inet_diag_dump_compat(struct sk_buff *skb,
933                                  struct netlink_callback *cb)
934 {
935         struct inet_diag_req *rc = nlmsg_data(cb->nlh);
936         int hdrlen = sizeof(struct inet_diag_req);
937         struct inet_diag_req_v2 req;
938         struct nlattr *bc = NULL;
939
940         req.sdiag_family = AF_UNSPEC; /* compatibility */
941         req.sdiag_protocol = inet_diag_type2proto(cb->nlh->nlmsg_type);
942         req.idiag_ext = rc->idiag_ext;
943         req.idiag_states = rc->idiag_states;
944         req.id = rc->id;
945
946         if (nlmsg_attrlen(cb->nlh, hdrlen))
947                 bc = nlmsg_find_attr(cb->nlh, hdrlen, INET_DIAG_REQ_BYTECODE);
948
949         return __inet_diag_dump(skb, cb, &req, bc);
950 }
951
952 static int inet_diag_get_exact_compat(struct sk_buff *in_skb,
953                                       const struct nlmsghdr *nlh)
954 {
955         struct inet_diag_req *rc = nlmsg_data(nlh);
956         struct inet_diag_req_v2 req;
957
958         req.sdiag_family = rc->idiag_family;
959         req.sdiag_protocol = inet_diag_type2proto(nlh->nlmsg_type);
960         req.idiag_ext = rc->idiag_ext;
961         req.idiag_states = rc->idiag_states;
962         req.id = rc->id;
963
964         return inet_diag_cmd_exact(SOCK_DIAG_BY_FAMILY, in_skb, nlh, &req);
965 }
966
967 static int inet_diag_rcv_msg_compat(struct sk_buff *skb, struct nlmsghdr *nlh)
968 {
969         int hdrlen = sizeof(struct inet_diag_req);
970         struct net *net = sock_net(skb->sk);
971
972         if (nlh->nlmsg_type >= INET_DIAG_GETSOCK_MAX ||
973             nlmsg_len(nlh) < hdrlen)
974                 return -EINVAL;
975
976         if (nlh->nlmsg_flags & NLM_F_DUMP) {
977                 if (nlmsg_attrlen(nlh, hdrlen)) {
978                         struct nlattr *attr;
979
980                         attr = nlmsg_find_attr(nlh, hdrlen,
981                                                INET_DIAG_REQ_BYTECODE);
982                         if (!attr ||
983                             nla_len(attr) < sizeof(struct inet_diag_bc_op) ||
984                             inet_diag_bc_audit(nla_data(attr), nla_len(attr)))
985                                 return -EINVAL;
986                 }
987                 {
988                         struct netlink_dump_control c = {
989                                 .dump = inet_diag_dump_compat,
990                         };
991                         return netlink_dump_start(net->diag_nlsk, skb, nlh, &c);
992                 }
993         }
994
995         return inet_diag_get_exact_compat(skb, nlh);
996 }
997
998 static int inet_diag_handler_cmd(struct sk_buff *skb, struct nlmsghdr *h)
999 {
1000         int hdrlen = sizeof(struct inet_diag_req_v2);
1001         struct net *net = sock_net(skb->sk);
1002
1003         if (nlmsg_len(h) < hdrlen)
1004                 return -EINVAL;
1005
1006         if (h->nlmsg_type == SOCK_DIAG_BY_FAMILY &&
1007             h->nlmsg_flags & NLM_F_DUMP) {
1008                 if (nlmsg_attrlen(h, hdrlen)) {
1009                         struct nlattr *attr;
1010
1011                         attr = nlmsg_find_attr(h, hdrlen,
1012                                                INET_DIAG_REQ_BYTECODE);
1013                         if (!attr ||
1014                             nla_len(attr) < sizeof(struct inet_diag_bc_op) ||
1015                             inet_diag_bc_audit(nla_data(attr), nla_len(attr)))
1016                                 return -EINVAL;
1017                 }
1018                 {
1019                         struct netlink_dump_control c = {
1020                                 .dump = inet_diag_dump,
1021                         };
1022                         return netlink_dump_start(net->diag_nlsk, skb, h, &c);
1023                 }
1024         }
1025
1026         return inet_diag_cmd_exact(h->nlmsg_type, skb, h, nlmsg_data(h));
1027 }
1028
1029 static
1030 int inet_diag_handler_get_info(struct sk_buff *skb, struct sock *sk)
1031 {
1032         const struct inet_diag_handler *handler;
1033         struct nlmsghdr *nlh;
1034         struct nlattr *attr;
1035         struct inet_diag_msg *r;
1036         void *info = NULL;
1037         int err = 0;
1038
1039         nlh = nlmsg_put(skb, 0, 0, SOCK_DIAG_BY_FAMILY, sizeof(*r), 0);
1040         if (!nlh)
1041                 return -ENOMEM;
1042
1043         r = nlmsg_data(nlh);
1044         memset(r, 0, sizeof(*r));
1045         inet_diag_msg_common_fill(r, sk);
1046         if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_STREAM)
1047                 r->id.idiag_sport = inet_sk(sk)->inet_sport;
1048         r->idiag_state = sk->sk_state;
1049
1050         if ((err = nla_put_u8(skb, INET_DIAG_PROTOCOL, sk->sk_protocol))) {
1051                 nlmsg_cancel(skb, nlh);
1052                 return err;
1053         }
1054
1055         handler = inet_diag_lock_handler(sk->sk_protocol);
1056         if (IS_ERR(handler)) {
1057                 inet_diag_unlock_handler(handler);
1058                 nlmsg_cancel(skb, nlh);
1059                 return PTR_ERR(handler);
1060         }
1061
1062         attr = handler->idiag_info_size
1063                 ? nla_reserve(skb, INET_DIAG_INFO, handler->idiag_info_size)
1064                 : NULL;
1065         if (attr)
1066                 info = nla_data(attr);
1067
1068         handler->idiag_get_info(sk, r, info);
1069         inet_diag_unlock_handler(handler);
1070
1071         nlmsg_end(skb, nlh);
1072         return 0;
1073 }
1074
1075 static const struct sock_diag_handler inet_diag_handler = {
1076         .family = AF_INET,
1077         .dump = inet_diag_handler_cmd,
1078         .get_info = inet_diag_handler_get_info,
1079         .destroy = inet_diag_handler_cmd,
1080 };
1081
1082 static const struct sock_diag_handler inet6_diag_handler = {
1083         .family = AF_INET6,
1084         .dump = inet_diag_handler_cmd,
1085         .get_info = inet_diag_handler_get_info,
1086         .destroy = inet_diag_handler_cmd,
1087 };
1088
1089 int inet_diag_register(const struct inet_diag_handler *h)
1090 {
1091         const __u16 type = h->idiag_type;
1092         int err = -EINVAL;
1093
1094         if (type >= IPPROTO_MAX)
1095                 goto out;
1096
1097         mutex_lock(&inet_diag_table_mutex);
1098         err = -EEXIST;
1099         if (!inet_diag_table[type]) {
1100                 inet_diag_table[type] = h;
1101                 err = 0;
1102         }
1103         mutex_unlock(&inet_diag_table_mutex);
1104 out:
1105         return err;
1106 }
1107 EXPORT_SYMBOL_GPL(inet_diag_register);
1108
1109 void inet_diag_unregister(const struct inet_diag_handler *h)
1110 {
1111         const __u16 type = h->idiag_type;
1112
1113         if (type >= IPPROTO_MAX)
1114                 return;
1115
1116         mutex_lock(&inet_diag_table_mutex);
1117         inet_diag_table[type] = NULL;
1118         mutex_unlock(&inet_diag_table_mutex);
1119 }
1120 EXPORT_SYMBOL_GPL(inet_diag_unregister);
1121
1122 static int __init inet_diag_init(void)
1123 {
1124         const int inet_diag_table_size = (IPPROTO_MAX *
1125                                           sizeof(struct inet_diag_handler *));
1126         int err = -ENOMEM;
1127
1128         inet_diag_table = kzalloc(inet_diag_table_size, GFP_KERNEL);
1129         if (!inet_diag_table)
1130                 goto out;
1131
1132         err = sock_diag_register(&inet_diag_handler);
1133         if (err)
1134                 goto out_free_nl;
1135
1136         err = sock_diag_register(&inet6_diag_handler);
1137         if (err)
1138                 goto out_free_inet;
1139
1140         sock_diag_register_inet_compat(inet_diag_rcv_msg_compat);
1141 out:
1142         return err;
1143
1144 out_free_inet:
1145         sock_diag_unregister(&inet_diag_handler);
1146 out_free_nl:
1147         kfree(inet_diag_table);
1148         goto out;
1149 }
1150
1151 static void __exit inet_diag_exit(void)
1152 {
1153         sock_diag_unregister(&inet6_diag_handler);
1154         sock_diag_unregister(&inet_diag_handler);
1155         sock_diag_unregister_inet_compat(inet_diag_rcv_msg_compat);
1156         kfree(inet_diag_table);
1157 }
1158
1159 module_init(inet_diag_init);
1160 module_exit(inet_diag_exit);
1161 MODULE_LICENSE("GPL");
1162 MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_NETLINK, NETLINK_SOCK_DIAG, 2 /* AF_INET */);
1163 MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_NETLINK, NETLINK_SOCK_DIAG, 10 /* AF_INET6 */);