[NETFILTER]: nf_conntrack_sip: parse SIP headers properly
[safe/jmp/linux-2.6] / net / netfilter / nf_conntrack_sip.c
1 /* SIP extension for IP connection tracking.
2  *
3  * (C) 2005 by Christian Hentschel <chentschel@arnet.com.ar>
4  * based on RR's ip_conntrack_ftp.c and other modules.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  */
10
11 #include <linux/module.h>
12 #include <linux/ctype.h>
13 #include <linux/skbuff.h>
14 #include <linux/inet.h>
15 #include <linux/in.h>
16 #include <linux/udp.h>
17 #include <linux/netfilter.h>
18
19 #include <net/netfilter/nf_conntrack.h>
20 #include <net/netfilter/nf_conntrack_expect.h>
21 #include <net/netfilter/nf_conntrack_helper.h>
22 #include <linux/netfilter/nf_conntrack_sip.h>
23
24 MODULE_LICENSE("GPL");
25 MODULE_AUTHOR("Christian Hentschel <chentschel@arnet.com.ar>");
26 MODULE_DESCRIPTION("SIP connection tracking helper");
27 MODULE_ALIAS("ip_conntrack_sip");
28
29 #define MAX_PORTS       8
30 static unsigned short ports[MAX_PORTS];
31 static unsigned int ports_c;
32 module_param_array(ports, ushort, &ports_c, 0400);
33 MODULE_PARM_DESC(ports, "port numbers of SIP servers");
34
35 static unsigned int sip_timeout __read_mostly = SIP_TIMEOUT;
36 module_param(sip_timeout, uint, 0600);
37 MODULE_PARM_DESC(sip_timeout, "timeout for the master SIP session");
38
39 unsigned int (*nf_nat_sip_hook)(struct sk_buff *skb,
40                                 const char **dptr,
41                                 unsigned int *datalen) __read_mostly;
42 EXPORT_SYMBOL_GPL(nf_nat_sip_hook);
43
44 unsigned int (*nf_nat_sdp_hook)(struct sk_buff *skb,
45                                 const char **dptr,
46                                 unsigned int *datalen,
47                                 struct nf_conntrack_expect *exp) __read_mostly;
48 EXPORT_SYMBOL_GPL(nf_nat_sdp_hook);
49
50 static int string_len(const struct nf_conn *ct, const char *dptr,
51                       const char *limit, int *shift)
52 {
53         int len = 0;
54
55         while (dptr < limit && isalpha(*dptr)) {
56                 dptr++;
57                 len++;
58         }
59         return len;
60 }
61
62 static int digits_len(const struct nf_conn *ct, const char *dptr,
63                       const char *limit, int *shift)
64 {
65         int len = 0;
66         while (dptr < limit && isdigit(*dptr)) {
67                 dptr++;
68                 len++;
69         }
70         return len;
71 }
72
73 static int parse_addr(const struct nf_conn *ct, const char *cp,
74                       const char **endp, union nf_inet_addr *addr,
75                       const char *limit)
76 {
77         const char *end;
78         int family = ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.l3num;
79         int ret = 0;
80
81         switch (family) {
82         case AF_INET:
83                 ret = in4_pton(cp, limit - cp, (u8 *)&addr->ip, -1, &end);
84                 break;
85         case AF_INET6:
86                 ret = in6_pton(cp, limit - cp, (u8 *)&addr->ip6, -1, &end);
87                 break;
88         default:
89                 BUG();
90         }
91
92         if (ret == 0 || end == cp)
93                 return 0;
94         if (endp)
95                 *endp = end;
96         return 1;
97 }
98
99 /* skip ip address. returns its length. */
100 static int epaddr_len(const struct nf_conn *ct, const char *dptr,
101                       const char *limit, int *shift)
102 {
103         union nf_inet_addr addr;
104         const char *aux = dptr;
105
106         if (!parse_addr(ct, dptr, &dptr, &addr, limit)) {
107                 pr_debug("ip: %s parse failed.!\n", dptr);
108                 return 0;
109         }
110
111         /* Port number */
112         if (*dptr == ':') {
113                 dptr++;
114                 dptr += digits_len(ct, dptr, limit, shift);
115         }
116         return dptr - aux;
117 }
118
119 /* get address length, skiping user info. */
120 static int skp_epaddr_len(const struct nf_conn *ct, const char *dptr,
121                           const char *limit, int *shift)
122 {
123         const char *start = dptr;
124         int s = *shift;
125
126         /* Search for @, but stop at the end of the line.
127          * We are inside a sip: URI, so we don't need to worry about
128          * continuation lines. */
129         while (dptr < limit &&
130                *dptr != '@' && *dptr != '\r' && *dptr != '\n') {
131                 (*shift)++;
132                 dptr++;
133         }
134
135         if (dptr < limit && *dptr == '@') {
136                 dptr++;
137                 (*shift)++;
138         } else {
139                 dptr = start;
140                 *shift = s;
141         }
142
143         return epaddr_len(ct, dptr, limit, shift);
144 }
145
146 /* Parse a SIP request line of the form:
147  *
148  * Request-Line = Method SP Request-URI SP SIP-Version CRLF
149  *
150  * and return the offset and length of the address contained in the Request-URI.
151  */
152 int ct_sip_parse_request(const struct nf_conn *ct,
153                          const char *dptr, unsigned int datalen,
154                          unsigned int *matchoff, unsigned int *matchlen)
155 {
156         const char *start = dptr, *limit = dptr + datalen;
157         unsigned int mlen;
158         int shift = 0;
159
160         /* Skip method and following whitespace */
161         mlen = string_len(ct, dptr, limit, NULL);
162         if (!mlen)
163                 return 0;
164         dptr += mlen;
165         if (++dptr >= limit)
166                 return 0;
167
168         /* Find SIP URI */
169         limit -= strlen("sip:");
170         for (; dptr < limit; dptr++) {
171                 if (*dptr == '\r' || *dptr == '\n')
172                         return -1;
173                 if (strnicmp(dptr, "sip:", strlen("sip:")) == 0)
174                         break;
175         }
176         *matchlen = skp_epaddr_len(ct, dptr, limit, &shift);
177         if (!*matchlen)
178                 return 0;
179         *matchoff = dptr - start + shift;
180         return 1;
181 }
182 EXPORT_SYMBOL_GPL(ct_sip_parse_request);
183
184 /* SIP header parsing: SIP headers are located at the beginning of a line, but
185  * may span several lines, in which case the continuation lines begin with a
186  * whitespace character. RFC 2543 allows lines to be terminated with CR, LF or
187  * CRLF, RFC 3261 allows only CRLF, we support both.
188  *
189  * Headers are followed by (optionally) whitespace, a colon, again (optionally)
190  * whitespace and the values. Whitespace in this context means any amount of
191  * tabs, spaces and continuation lines, which are treated as a single whitespace
192  * character.
193  */
194 static const struct sip_header ct_sip_hdrs[] = {
195         [SIP_HDR_FROM]                  = SIP_HDR("From", "f", "sip:", skp_epaddr_len),
196         [SIP_HDR_TO]                    = SIP_HDR("To", "t", "sip:", skp_epaddr_len),
197         [SIP_HDR_CONTACT]               = SIP_HDR("Contact", "m", "sip:", skp_epaddr_len),
198         [SIP_HDR_VIA]                   = SIP_HDR("Via", "v", "UDP ", epaddr_len),
199         [SIP_HDR_CONTENT_LENGTH]        = SIP_HDR("Content-Length", "l", NULL, digits_len),
200 };
201
202 static const char *sip_follow_continuation(const char *dptr, const char *limit)
203 {
204         /* Walk past newline */
205         if (++dptr >= limit)
206                 return NULL;
207
208         /* Skip '\n' in CR LF */
209         if (*(dptr - 1) == '\r' && *dptr == '\n') {
210                 if (++dptr >= limit)
211                         return NULL;
212         }
213
214         /* Continuation line? */
215         if (*dptr != ' ' && *dptr != '\t')
216                 return NULL;
217
218         /* skip leading whitespace */
219         for (; dptr < limit; dptr++) {
220                 if (*dptr != ' ' && *dptr != '\t')
221                         break;
222         }
223         return dptr;
224 }
225
226 static const char *sip_skip_whitespace(const char *dptr, const char *limit)
227 {
228         for (; dptr < limit; dptr++) {
229                 if (*dptr == ' ')
230                         continue;
231                 if (*dptr != '\r' && *dptr != '\n')
232                         break;
233                 dptr = sip_follow_continuation(dptr, limit);
234                 if (dptr == NULL)
235                         return NULL;
236         }
237         return dptr;
238 }
239
240 /* Search within a SIP header value, dealing with continuation lines */
241 static const char *ct_sip_header_search(const char *dptr, const char *limit,
242                                         const char *needle, unsigned int len)
243 {
244         for (limit -= len; dptr < limit; dptr++) {
245                 if (*dptr == '\r' || *dptr == '\n') {
246                         dptr = sip_follow_continuation(dptr, limit);
247                         if (dptr == NULL)
248                                 break;
249                         continue;
250                 }
251
252                 if (strnicmp(dptr, needle, len) == 0)
253                         return dptr;
254         }
255         return NULL;
256 }
257
258 int ct_sip_get_header(const struct nf_conn *ct, const char *dptr,
259                       unsigned int dataoff, unsigned int datalen,
260                       enum sip_header_types type,
261                       unsigned int *matchoff, unsigned int *matchlen)
262 {
263         const struct sip_header *hdr = &ct_sip_hdrs[type];
264         const char *start = dptr, *limit = dptr + datalen;
265         int shift = 0;
266
267         for (dptr += dataoff; dptr < limit; dptr++) {
268                 /* Find beginning of line */
269                 if (*dptr != '\r' && *dptr != '\n')
270                         continue;
271                 if (++dptr >= limit)
272                         break;
273                 if (*(dptr - 1) == '\r' && *dptr == '\n') {
274                         if (++dptr >= limit)
275                                 break;
276                 }
277
278                 /* Skip continuation lines */
279                 if (*dptr == ' ' || *dptr == '\t')
280                         continue;
281
282                 /* Find header. Compact headers must be followed by a
283                  * non-alphabetic character to avoid mismatches. */
284                 if (limit - dptr >= hdr->len &&
285                     strnicmp(dptr, hdr->name, hdr->len) == 0)
286                         dptr += hdr->len;
287                 else if (hdr->cname && limit - dptr >= hdr->clen + 1 &&
288                          strnicmp(dptr, hdr->cname, hdr->clen) == 0 &&
289                          !isalpha(*(dptr + hdr->clen + 1)))
290                         dptr += hdr->clen;
291                 else
292                         continue;
293
294                 /* Find and skip colon */
295                 dptr = sip_skip_whitespace(dptr, limit);
296                 if (dptr == NULL)
297                         break;
298                 if (*dptr != ':' || ++dptr >= limit)
299                         break;
300
301                 /* Skip whitespace after colon */
302                 dptr = sip_skip_whitespace(dptr, limit);
303                 if (dptr == NULL)
304                         break;
305
306                 *matchoff = dptr - start;
307                 if (hdr->search) {
308                         dptr = ct_sip_header_search(dptr, limit, hdr->search,
309                                                     hdr->slen);
310                         if (!dptr)
311                                 return -1;
312                         dptr += hdr->slen;
313                 }
314
315                 *matchlen = hdr->match_len(ct, dptr, limit, &shift);
316                 if (!*matchlen)
317                         return -1;
318                 *matchoff = dptr - start + shift;
319                 return 1;
320         }
321         return 0;
322 }
323 EXPORT_SYMBOL_GPL(ct_sip_get_header);
324
325 /* SDP header parsing: a SDP session description contains an ordered set of
326  * headers, starting with a section containing general session parameters,
327  * optionally followed by multiple media descriptions.
328  *
329  * SDP headers always start at the beginning of a line. According to RFC 2327:
330  * "The sequence CRLF (0x0d0a) is used to end a record, although parsers should
331  * be tolerant and also accept records terminated with a single newline
332  * character". We handle both cases.
333  */
334 static const struct sip_header ct_sdp_hdrs[] = {
335         [SDP_HDR_VERSION]               = SDP_HDR("v=", NULL, digits_len),
336         [SDP_HDR_OWNER_IP4]             = SDP_HDR("o=", "IN IP4 ", epaddr_len),
337         [SDP_HDR_CONNECTION_IP4]        = SDP_HDR("c=", "IN IP4 ", epaddr_len),
338         [SDP_HDR_OWNER_IP6]             = SDP_HDR("o=", "IN IP6 ", epaddr_len),
339         [SDP_HDR_CONNECTION_IP6]        = SDP_HDR("c=", "IN IP6 ", epaddr_len),
340         [SDP_HDR_MEDIA]                 = SDP_HDR("m=", "audio ", digits_len),
341 };
342
343 /* Linear string search within SDP header values */
344 static const char *ct_sdp_header_search(const char *dptr, const char *limit,
345                                         const char *needle, unsigned int len)
346 {
347         for (limit -= len; dptr < limit; dptr++) {
348                 if (*dptr == '\r' || *dptr == '\n')
349                         break;
350                 if (strncmp(dptr, needle, len) == 0)
351                         return dptr;
352         }
353         return NULL;
354 }
355
356 /* Locate a SDP header (optionally a substring within the header value),
357  * optionally stopping at the first occurence of the term header, parse
358  * it and return the offset and length of the data we're interested in.
359  */
360 int ct_sip_get_sdp_header(const struct nf_conn *ct, const char *dptr,
361                           unsigned int dataoff, unsigned int datalen,
362                           enum sdp_header_types type,
363                           enum sdp_header_types term,
364                           unsigned int *matchoff, unsigned int *matchlen)
365 {
366         const struct sip_header *hdr = &ct_sdp_hdrs[type];
367         const struct sip_header *thdr = &ct_sdp_hdrs[term];
368         const char *start = dptr, *limit = dptr + datalen;
369         int shift = 0;
370
371         for (dptr += dataoff; dptr < limit; dptr++) {
372                 /* Find beginning of line */
373                 if (*dptr != '\r' && *dptr != '\n')
374                         continue;
375                 if (++dptr >= limit)
376                         break;
377                 if (*(dptr - 1) == '\r' && *dptr == '\n') {
378                         if (++dptr >= limit)
379                                 break;
380                 }
381
382                 if (term != SDP_HDR_UNSPEC &&
383                     limit - dptr >= thdr->len &&
384                     strnicmp(dptr, thdr->name, thdr->len) == 0)
385                         break;
386                 else if (limit - dptr >= hdr->len &&
387                          strnicmp(dptr, hdr->name, hdr->len) == 0)
388                         dptr += hdr->len;
389                 else
390                         continue;
391
392                 *matchoff = dptr - start;
393                 if (hdr->search) {
394                         dptr = ct_sdp_header_search(dptr, limit, hdr->search,
395                                                     hdr->slen);
396                         if (!dptr)
397                                 return -1;
398                         dptr += hdr->slen;
399                 }
400
401                 *matchlen = hdr->match_len(ct, dptr, limit, &shift);
402                 if (!*matchlen)
403                         return -1;
404                 *matchoff = dptr - start + shift;
405                 return 1;
406         }
407         return 0;
408 }
409 EXPORT_SYMBOL_GPL(ct_sip_get_sdp_header);
410
411 static int set_expected_rtp(struct sk_buff *skb,
412                             const char **dptr, unsigned int *datalen,
413                             union nf_inet_addr *addr, __be16 port)
414 {
415         struct nf_conntrack_expect *exp;
416         enum ip_conntrack_info ctinfo;
417         struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
418         enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
419         int family = ct->tuplehash[!dir].tuple.src.l3num;
420         int ret;
421         typeof(nf_nat_sdp_hook) nf_nat_sdp;
422
423         exp = nf_ct_expect_alloc(ct);
424         if (exp == NULL)
425                 return NF_DROP;
426         nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, family,
427                           &ct->tuplehash[!dir].tuple.src.u3, addr,
428                           IPPROTO_UDP, NULL, &port);
429
430         nf_nat_sdp = rcu_dereference(nf_nat_sdp_hook);
431         if (nf_nat_sdp && ct->status & IPS_NAT_MASK)
432                 ret = nf_nat_sdp(skb, dptr, datalen, exp);
433         else {
434                 if (nf_ct_expect_related(exp) != 0)
435                         ret = NF_DROP;
436                 else
437                         ret = NF_ACCEPT;
438         }
439         nf_ct_expect_put(exp);
440
441         return ret;
442 }
443
444 static int sip_help(struct sk_buff *skb,
445                     unsigned int protoff,
446                     struct nf_conn *ct,
447                     enum ip_conntrack_info ctinfo)
448 {
449         int family = ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.l3num;
450         union nf_inet_addr addr;
451         unsigned int dataoff, datalen;
452         const char *dptr;
453         int ret = NF_ACCEPT;
454         unsigned int matchoff, matchlen;
455         u_int16_t port;
456         enum sdp_header_types type;
457         typeof(nf_nat_sip_hook) nf_nat_sip;
458
459         /* No Data ? */
460         dataoff = protoff + sizeof(struct udphdr);
461         if (dataoff >= skb->len)
462                 return NF_ACCEPT;
463
464         nf_ct_refresh(ct, skb, sip_timeout * HZ);
465
466         if (!skb_is_nonlinear(skb))
467                 dptr = skb->data + dataoff;
468         else {
469                 pr_debug("Copy of skbuff not supported yet.\n");
470                 goto out;
471         }
472
473         nf_nat_sip = rcu_dereference(nf_nat_sip_hook);
474         if (nf_nat_sip && ct->status & IPS_NAT_MASK) {
475                 if (!nf_nat_sip(skb, &dptr, &datalen)) {
476                         ret = NF_DROP;
477                         goto out;
478                 }
479         }
480
481         datalen = skb->len - dataoff;
482         if (datalen < strlen("SIP/2.0 200"))
483                 goto out;
484
485         /* RTP info only in some SDP pkts */
486         if (strnicmp(dptr, "INVITE", strlen("INVITE")) != 0 &&
487             strnicmp(dptr, "UPDATE", strlen("UPDATE")) != 0 &&
488             strnicmp(dptr, "SIP/2.0 180", strlen("SIP/2.0 180")) != 0 &&
489             strnicmp(dptr, "SIP/2.0 183", strlen("SIP/2.0 183")) != 0 &&
490             strnicmp(dptr, "SIP/2.0 200", strlen("SIP/2.0 200")) != 0) {
491                 goto out;
492         }
493         /* Get address and port from SDP packet. */
494         type = family == AF_INET ? SDP_HDR_CONNECTION_IP4 :
495                                    SDP_HDR_CONNECTION_IP6;
496         if (ct_sip_get_sdp_header(ct, dptr, 0, datalen, type, SDP_HDR_UNSPEC,
497                                   &matchoff, &matchlen) > 0) {
498
499                 /* We'll drop only if there are parse problems. */
500                 if (!parse_addr(ct, dptr + matchoff, NULL, &addr,
501                                 dptr + datalen)) {
502                         ret = NF_DROP;
503                         goto out;
504                 }
505                 if (ct_sip_get_sdp_header(ct, dptr, 0, datalen,
506                                           SDP_HDR_MEDIA, SDP_HDR_UNSPEC,
507                                           &matchoff, &matchlen) > 0) {
508
509                         port = simple_strtoul(dptr + matchoff, NULL, 10);
510                         if (port < 1024) {
511                                 ret = NF_DROP;
512                                 goto out;
513                         }
514                         ret = set_expected_rtp(skb, &dptr, &datalen,
515                                                &addr, htons(port));
516                 }
517         }
518 out:
519         return ret;
520 }
521
522 static struct nf_conntrack_helper sip[MAX_PORTS][2] __read_mostly;
523 static char sip_names[MAX_PORTS][2][sizeof("sip-65535")] __read_mostly;
524
525 static const struct nf_conntrack_expect_policy sip_exp_policy = {
526         .max_expected   = 2,
527         .timeout        = 3 * 60,
528 };
529
530 static void nf_conntrack_sip_fini(void)
531 {
532         int i, j;
533
534         for (i = 0; i < ports_c; i++) {
535                 for (j = 0; j < 2; j++) {
536                         if (sip[i][j].me == NULL)
537                                 continue;
538                         nf_conntrack_helper_unregister(&sip[i][j]);
539                 }
540         }
541 }
542
543 static int __init nf_conntrack_sip_init(void)
544 {
545         int i, j, ret;
546         char *tmpname;
547
548         if (ports_c == 0)
549                 ports[ports_c++] = SIP_PORT;
550
551         for (i = 0; i < ports_c; i++) {
552                 memset(&sip[i], 0, sizeof(sip[i]));
553
554                 sip[i][0].tuple.src.l3num = AF_INET;
555                 sip[i][1].tuple.src.l3num = AF_INET6;
556                 for (j = 0; j < 2; j++) {
557                         sip[i][j].tuple.dst.protonum = IPPROTO_UDP;
558                         sip[i][j].tuple.src.u.udp.port = htons(ports[i]);
559                         sip[i][j].expect_policy = &sip_exp_policy;
560                         sip[i][j].me = THIS_MODULE;
561                         sip[i][j].help = sip_help;
562
563                         tmpname = &sip_names[i][j][0];
564                         if (ports[i] == SIP_PORT)
565                                 sprintf(tmpname, "sip");
566                         else
567                                 sprintf(tmpname, "sip-%u", i);
568                         sip[i][j].name = tmpname;
569
570                         pr_debug("port #%u: %u\n", i, ports[i]);
571
572                         ret = nf_conntrack_helper_register(&sip[i][j]);
573                         if (ret) {
574                                 printk("nf_ct_sip: failed to register helper "
575                                        "for pf: %u port: %u\n",
576                                        sip[i][j].tuple.src.l3num, ports[i]);
577                                 nf_conntrack_sip_fini();
578                                 return ret;
579                         }
580                 }
581         }
582         return 0;
583 }
584
585 module_init(nf_conntrack_sip_init);
586 module_exit(nf_conntrack_sip_fini);