xref: /linux/net/netfilter/nf_conntrack_sip.c (revision 87320be9f0d24fce67631b7eef919f0b79c3e45c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* SIP extension for IP connection tracking.
3  *
4  * (C) 2005 by Christian Hentschel <chentschel@arnet.com.ar>
5  * based on RR's ip_conntrack_ftp.c and other modules.
6  * (C) 2007 United Security Providers
7  * (C) 2007, 2008 Patrick McHardy <kaber@trash.net>
8  */
9 
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11 
12 #include <linux/module.h>
13 #include <linux/ctype.h>
14 #include <linux/skbuff.h>
15 #include <linux/inet.h>
16 #include <linux/in.h>
17 #include <linux/udp.h>
18 #include <linux/tcp.h>
19 #include <linux/netfilter.h>
20 #include <linux/netfilter_ipv4.h>
21 #include <linux/netfilter_ipv6.h>
22 
23 #include <net/netfilter/nf_conntrack.h>
24 #include <net/netfilter/nf_conntrack_core.h>
25 #include <net/netfilter/nf_conntrack_expect.h>
26 #include <net/netfilter/nf_conntrack_helper.h>
27 #include <net/netfilter/nf_conntrack_zones.h>
28 #include <linux/netfilter/nf_conntrack_sip.h>
29 
30 #define HELPER_NAME "sip"
31 
32 MODULE_LICENSE("GPL");
33 MODULE_AUTHOR("Christian Hentschel <chentschel@arnet.com.ar>");
34 MODULE_DESCRIPTION("SIP connection tracking helper");
35 MODULE_ALIAS("ip_conntrack_sip");
36 MODULE_ALIAS_NFCT_HELPER(HELPER_NAME);
37 
38 #define MAX_PORTS	8
39 static unsigned short ports[MAX_PORTS];
40 static unsigned int ports_c;
41 module_param_array(ports, ushort, &ports_c, 0400);
42 MODULE_PARM_DESC(ports, "port numbers of SIP servers");
43 
44 static unsigned int sip_timeout __read_mostly = SIP_TIMEOUT;
45 module_param(sip_timeout, uint, 0600);
46 MODULE_PARM_DESC(sip_timeout, "timeout for the master SIP session");
47 
48 static int sip_direct_signalling __read_mostly = 1;
49 module_param(sip_direct_signalling, int, 0600);
50 MODULE_PARM_DESC(sip_direct_signalling, "expect incoming calls from registrar "
51 					"only (default 1)");
52 
53 static int sip_direct_media __read_mostly = 1;
54 module_param(sip_direct_media, int, 0600);
55 MODULE_PARM_DESC(sip_direct_media, "Expect Media streams between signalling "
56 				   "endpoints only (default 1)");
57 
58 static int sip_external_media __read_mostly = 0;
59 module_param(sip_external_media, int, 0600);
60 MODULE_PARM_DESC(sip_external_media, "Expect Media streams between external "
61 				     "endpoints (default 0)");
62 
63 const struct nf_nat_sip_hooks __rcu *nf_nat_sip_hooks;
64 EXPORT_SYMBOL_GPL(nf_nat_sip_hooks);
65 
string_len(const struct nf_conn * ct,const char * dptr,const char * limit,int * shift)66 static int string_len(const struct nf_conn *ct, const char *dptr,
67 		      const char *limit, int *shift)
68 {
69 	int len = 0;
70 
71 	while (dptr < limit && isalpha(*dptr)) {
72 		dptr++;
73 		len++;
74 	}
75 	return len;
76 }
77 
digits_len(const struct nf_conn * ct,const char * dptr,const char * limit,int * shift)78 static int digits_len(const struct nf_conn *ct, const char *dptr,
79 		      const char *limit, int *shift)
80 {
81 	int len = 0;
82 	while (dptr < limit && isdigit(*dptr)) {
83 		dptr++;
84 		len++;
85 	}
86 	return len;
87 }
88 
iswordc(const char c)89 static int iswordc(const char c)
90 {
91 	if (isalnum(c) || c == '!' || c == '"' || c == '%' ||
92 	    (c >= '(' && c <= '+') || c == ':' || c == '<' || c == '>' ||
93 	    c == '?' || (c >= '[' && c <= ']') || c == '_' || c == '`' ||
94 	    c == '{' || c == '}' || c == '~' || (c >= '-' && c <= '/') ||
95 	    c == '\'')
96 		return 1;
97 	return 0;
98 }
99 
word_len(const char * dptr,const char * limit)100 static int word_len(const char *dptr, const char *limit)
101 {
102 	int len = 0;
103 	while (dptr < limit && iswordc(*dptr)) {
104 		dptr++;
105 		len++;
106 	}
107 	return len;
108 }
109 
callid_len(const struct nf_conn * ct,const char * dptr,const char * limit,int * shift)110 static int callid_len(const struct nf_conn *ct, const char *dptr,
111 		      const char *limit, int *shift)
112 {
113 	int len, domain_len;
114 
115 	len = word_len(dptr, limit);
116 	dptr += len;
117 	if (!len || dptr == limit || *dptr != '@')
118 		return len;
119 	dptr++;
120 	len++;
121 
122 	domain_len = word_len(dptr, limit);
123 	if (!domain_len)
124 		return 0;
125 	return len + domain_len;
126 }
127 
128 /* get media type + port length */
media_len(const struct nf_conn * ct,const char * dptr,const char * limit,int * shift)129 static int media_len(const struct nf_conn *ct, const char *dptr,
130 		     const char *limit, int *shift)
131 {
132 	int len = string_len(ct, dptr, limit, shift);
133 
134 	dptr += len;
135 	if (dptr >= limit || *dptr != ' ')
136 		return 0;
137 	len++;
138 	dptr++;
139 
140 	return len + digits_len(ct, dptr, limit, shift);
141 }
142 
sip_parse_addr(const struct nf_conn * ct,const char * cp,const char ** endp,union nf_inet_addr * addr,const char * limit,bool delim)143 static int sip_parse_addr(const struct nf_conn *ct, const char *cp,
144 			  const char **endp, union nf_inet_addr *addr,
145 			  const char *limit, bool delim)
146 {
147 	const char *end;
148 	int ret;
149 
150 	if (!ct)
151 		return 0;
152 
153 	memset(addr, 0, sizeof(*addr));
154 	switch (nf_ct_l3num(ct)) {
155 	case AF_INET:
156 		ret = in4_pton(cp, limit - cp, (u8 *)&addr->ip, -1, &end);
157 		if (ret == 0)
158 			return 0;
159 		break;
160 	case AF_INET6:
161 		if (cp < limit && *cp == '[')
162 			cp++;
163 		else if (delim)
164 			return 0;
165 
166 		ret = in6_pton(cp, limit - cp, (u8 *)&addr->ip6, -1, &end);
167 		if (ret == 0)
168 			return 0;
169 
170 		if (end < limit && *end == ']')
171 			end++;
172 		else if (delim)
173 			return 0;
174 		break;
175 	default:
176 		BUG();
177 	}
178 
179 	if (endp)
180 		*endp = end;
181 	return 1;
182 }
183 
184 /* Parse optional port number after IP address.
185  * Returns false on malformed input, true otherwise.
186  * If port is non-NULL, stores parsed port in network byte order.
187  * If no port is present, sets *port to default SIP port.
188  */
sip_parse_port(const char * dptr,const char ** endp,const char * limit,__be16 * port)189 static bool sip_parse_port(const char *dptr, const char **endp,
190 			   const char *limit, __be16 *port)
191 {
192 	unsigned int p = 0;
193 	int len = 0;
194 
195 	if (dptr >= limit)
196 		return false;
197 
198 	if (*dptr != ':') {
199 		if (port)
200 			*port = htons(SIP_PORT);
201 		if (endp)
202 			*endp = dptr;
203 		return true;
204 	}
205 
206 	dptr++; /* skip ':' */
207 
208 	while (dptr < limit && isdigit(*dptr)) {
209 		p = p * 10 + (*dptr - '0');
210 		dptr++;
211 		len++;
212 		if (len > 5) /* max "65535" */
213 			return false;
214 	}
215 
216 	if (len == 0)
217 		return false;
218 
219 	/* reached limit while parsing port */
220 	if (dptr >= limit)
221 		return false;
222 
223 	if (p < 1024 || p > 65535)
224 		return false;
225 
226 	if (port)
227 		*port = htons(p);
228 
229 	if (endp)
230 		*endp = dptr;
231 
232 	return true;
233 }
234 
235 /* skip ip address. returns its length. */
epaddr_len(const struct nf_conn * ct,const char * dptr,const char * limit,int * shift)236 static int epaddr_len(const struct nf_conn *ct, const char *dptr,
237 		      const char *limit, int *shift)
238 {
239 	union nf_inet_addr addr;
240 	const char *aux = dptr;
241 
242 	if (!sip_parse_addr(ct, dptr, &dptr, &addr, limit, true)) {
243 		pr_debug("ip: %s parse failed.!\n", dptr);
244 		return 0;
245 	}
246 
247 	if (!sip_parse_port(dptr, &dptr, limit, NULL))
248 		return 0;
249 	return dptr - aux;
250 }
251 
252 /* get address length, skiping user info. */
skp_epaddr_len(const struct nf_conn * ct,const char * dptr,const char * limit,int * shift)253 static int skp_epaddr_len(const struct nf_conn *ct, const char *dptr,
254 			  const char *limit, int *shift)
255 {
256 	const char *start = dptr;
257 	int s = *shift;
258 
259 	/* Search for @, but stop at the end of the line.
260 	 * We are inside a sip: URI, so we don't need to worry about
261 	 * continuation lines. */
262 	while (dptr < limit &&
263 	       *dptr != '@' && *dptr != '\r' && *dptr != '\n') {
264 		(*shift)++;
265 		dptr++;
266 	}
267 
268 	if (dptr < limit && *dptr == '@') {
269 		dptr++;
270 		(*shift)++;
271 	} else {
272 		dptr = start;
273 		*shift = s;
274 	}
275 
276 	return epaddr_len(ct, dptr, limit, shift);
277 }
278 
279 /* simple_strtoul stops after first non-number character.
280  * But as we're not dealing with c-strings, we can't rely on
281  * hitting \r,\n,\0 etc. before moving past end of buffer.
282  *
283  * This is a variant of simple_strtoul, but doesn't require
284  * a c-string.
285  *
286  * If value exceeds UINT_MAX, 0 is returned.
287  */
sip_strtouint(const char * cp,unsigned int len,char ** endp)288 static unsigned int sip_strtouint(const char *cp, unsigned int len, char **endp)
289 {
290 	const unsigned int max = sizeof("4294967295");
291 	unsigned int olen = len;
292 	const char *s = cp;
293 	u64 result = 0;
294 
295 	if (len > max)
296 		len = max;
297 
298 	while (olen > 0 && isdigit(*s)) {
299 		unsigned int value;
300 
301 		if (len == 0)
302 			goto err;
303 
304 		value = *s - '0';
305 		result = result * 10 + value;
306 
307 		if (result > UINT_MAX)
308 			goto err;
309 		s++;
310 		len--;
311 		olen--;
312 	}
313 
314 	if (endp)
315 		*endp = (char *)s;
316 
317 	return result;
318 err:
319 	if (endp)
320 		*endp = (char *)cp;
321 	return 0;
322 }
323 
324 /* Parse a SIP request line of the form:
325  *
326  * Request-Line = Method SP Request-URI SP SIP-Version CRLF
327  *
328  * and return the offset and length of the address contained in the Request-URI.
329  */
ct_sip_parse_request(const struct nf_conn * ct,const char * dptr,unsigned int datalen,unsigned int * matchoff,unsigned int * matchlen,union nf_inet_addr * addr,__be16 * port)330 int ct_sip_parse_request(const struct nf_conn *ct,
331 			 const char *dptr, unsigned int datalen,
332 			 unsigned int *matchoff, unsigned int *matchlen,
333 			 union nf_inet_addr *addr, __be16 *port)
334 {
335 	const char *start = dptr, *limit = dptr + datalen, *end;
336 	unsigned int mlen;
337 	int shift = 0;
338 
339 	/* Skip method and following whitespace */
340 	mlen = string_len(ct, dptr, limit, NULL);
341 	if (!mlen)
342 		return 0;
343 	dptr += mlen;
344 	if (++dptr >= limit)
345 		return 0;
346 
347 	/* Find SIP URI */
348 	for (; dptr < limit - strlen("sip:"); dptr++) {
349 		if (*dptr == '\r' || *dptr == '\n')
350 			return -1;
351 		if (strncasecmp(dptr, "sip:", strlen("sip:")) == 0) {
352 			dptr += strlen("sip:");
353 			break;
354 		}
355 	}
356 	if (!skp_epaddr_len(ct, dptr, limit, &shift))
357 		return 0;
358 	dptr += shift;
359 
360 	if (!sip_parse_addr(ct, dptr, &end, addr, limit, true))
361 		return -1;
362 	if (!sip_parse_port(end, &end, limit, port))
363 		return -1;
364 
365 	if (end == dptr)
366 		return 0;
367 	*matchoff = dptr - start;
368 	*matchlen = end - dptr;
369 	return 1;
370 }
371 EXPORT_SYMBOL_GPL(ct_sip_parse_request);
372 
373 /* SIP header parsing: SIP headers are located at the beginning of a line, but
374  * may span several lines, in which case the continuation lines begin with a
375  * whitespace character. RFC 2543 allows lines to be terminated with CR, LF or
376  * CRLF, RFC 3261 allows only CRLF, we support both.
377  *
378  * Headers are followed by (optionally) whitespace, a colon, again (optionally)
379  * whitespace and the values. Whitespace in this context means any amount of
380  * tabs, spaces and continuation lines, which are treated as a single whitespace
381  * character.
382  *
383  * Some headers may appear multiple times. A comma separated list of values is
384  * equivalent to multiple headers.
385  */
386 static const struct sip_header ct_sip_hdrs[] = {
387 	[SIP_HDR_CSEQ]			= SIP_HDR("CSeq", NULL, NULL, digits_len),
388 	[SIP_HDR_FROM]			= SIP_HDR("From", "f", "sip:", skp_epaddr_len),
389 	[SIP_HDR_TO]			= SIP_HDR("To", "t", "sip:", skp_epaddr_len),
390 	[SIP_HDR_CONTACT]		= SIP_HDR("Contact", "m", "sip:", skp_epaddr_len),
391 	[SIP_HDR_VIA_UDP]		= SIP_HDR("Via", "v", "UDP ", epaddr_len),
392 	[SIP_HDR_VIA_TCP]		= SIP_HDR("Via", "v", "TCP ", epaddr_len),
393 	[SIP_HDR_EXPIRES]		= SIP_HDR("Expires", NULL, NULL, digits_len),
394 	[SIP_HDR_CONTENT_LENGTH]	= SIP_HDR("Content-Length", "l", NULL, digits_len),
395 	[SIP_HDR_CALL_ID]		= SIP_HDR("Call-Id", "i", NULL, callid_len),
396 };
397 
sip_follow_continuation(const char * dptr,const char * limit)398 static const char *sip_follow_continuation(const char *dptr, const char *limit)
399 {
400 	/* Walk past newline */
401 	if (++dptr >= limit)
402 		return NULL;
403 
404 	/* Skip '\n' in CR LF */
405 	if (*(dptr - 1) == '\r' && *dptr == '\n') {
406 		if (++dptr >= limit)
407 			return NULL;
408 	}
409 
410 	/* Continuation line? */
411 	if (*dptr != ' ' && *dptr != '\t')
412 		return NULL;
413 
414 	/* skip leading whitespace */
415 	for (; dptr < limit; dptr++) {
416 		if (*dptr != ' ' && *dptr != '\t')
417 			break;
418 	}
419 	return dptr;
420 }
421 
sip_skip_whitespace(const char * dptr,const char * limit)422 static const char *sip_skip_whitespace(const char *dptr, const char *limit)
423 {
424 	for (; dptr < limit; dptr++) {
425 		if (*dptr == ' ' || *dptr == '\t')
426 			continue;
427 		if (*dptr != '\r' && *dptr != '\n')
428 			break;
429 		dptr = sip_follow_continuation(dptr, limit);
430 		break;
431 	}
432 	return dptr;
433 }
434 
435 /* Search within a SIP header value, dealing with continuation lines */
ct_sip_header_search(const char * dptr,const char * limit,const char * needle,unsigned int len)436 static const char *ct_sip_header_search(const char *dptr, const char *limit,
437 					const char *needle, unsigned int len)
438 {
439 	for (limit -= len; dptr < limit; dptr++) {
440 		if (*dptr == '\r' || *dptr == '\n') {
441 			dptr = sip_follow_continuation(dptr, limit);
442 			if (dptr == NULL)
443 				break;
444 			continue;
445 		}
446 
447 		if (strncasecmp(dptr, needle, len) == 0)
448 			return dptr;
449 	}
450 	return NULL;
451 }
452 
ct_sip_get_header(const struct nf_conn * ct,const char * dptr,unsigned int dataoff,unsigned int datalen,enum sip_header_types type,unsigned int * matchoff,unsigned int * matchlen)453 int ct_sip_get_header(const struct nf_conn *ct, const char *dptr,
454 		      unsigned int dataoff, unsigned int datalen,
455 		      enum sip_header_types type,
456 		      unsigned int *matchoff, unsigned int *matchlen)
457 {
458 	const struct sip_header *hdr = &ct_sip_hdrs[type];
459 	const char *start = dptr, *limit = dptr + datalen;
460 	int shift = 0;
461 
462 	for (dptr += dataoff; dptr < limit; dptr++) {
463 		/* Find beginning of line */
464 		if (*dptr != '\r' && *dptr != '\n')
465 			continue;
466 		if (++dptr >= limit)
467 			break;
468 		if (*(dptr - 1) == '\r' && *dptr == '\n') {
469 			if (++dptr >= limit)
470 				break;
471 		}
472 
473 		/* Skip continuation lines */
474 		if (*dptr == ' ' || *dptr == '\t')
475 			continue;
476 
477 		/* Find header. Compact headers must be followed by a
478 		 * non-alphabetic character to avoid mismatches. */
479 		if (limit - dptr >= hdr->len &&
480 		    strncasecmp(dptr, hdr->name, hdr->len) == 0)
481 			dptr += hdr->len;
482 		else if (hdr->cname && limit - dptr >= hdr->clen + 1 &&
483 			 strncasecmp(dptr, hdr->cname, hdr->clen) == 0 &&
484 			 !isalpha(*(dptr + hdr->clen)))
485 			dptr += hdr->clen;
486 		else
487 			continue;
488 
489 		/* Find and skip colon */
490 		dptr = sip_skip_whitespace(dptr, limit);
491 		if (dptr == NULL)
492 			break;
493 		if (*dptr != ':' || ++dptr >= limit)
494 			break;
495 
496 		/* Skip whitespace after colon */
497 		dptr = sip_skip_whitespace(dptr, limit);
498 		if (dptr == NULL)
499 			break;
500 
501 		*matchoff = dptr - start;
502 		if (hdr->search) {
503 			dptr = ct_sip_header_search(dptr, limit, hdr->search,
504 						    hdr->slen);
505 			if (!dptr)
506 				return -1;
507 			dptr += hdr->slen;
508 		}
509 
510 		*matchlen = hdr->match_len(ct, dptr, limit, &shift);
511 		if (!*matchlen)
512 			return -1;
513 		*matchoff = dptr - start + shift;
514 		return 1;
515 	}
516 	return 0;
517 }
518 EXPORT_SYMBOL_GPL(ct_sip_get_header);
519 
520 /* Get next header field in a list of comma separated values */
ct_sip_next_header(const struct nf_conn * ct,const char * dptr,unsigned int dataoff,unsigned int datalen,enum sip_header_types type,unsigned int * matchoff,unsigned int * matchlen)521 static int ct_sip_next_header(const struct nf_conn *ct, const char *dptr,
522 			      unsigned int dataoff, unsigned int datalen,
523 			      enum sip_header_types type,
524 			      unsigned int *matchoff, unsigned int *matchlen)
525 {
526 	const struct sip_header *hdr = &ct_sip_hdrs[type];
527 	const char *start = dptr, *limit = dptr + datalen;
528 	int shift = 0;
529 
530 	dptr += dataoff;
531 
532 	dptr = ct_sip_header_search(dptr, limit, ",", strlen(","));
533 	if (!dptr)
534 		return 0;
535 
536 	dptr = ct_sip_header_search(dptr, limit, hdr->search, hdr->slen);
537 	if (!dptr)
538 		return 0;
539 	dptr += hdr->slen;
540 
541 	*matchoff = dptr - start;
542 	*matchlen = hdr->match_len(ct, dptr, limit, &shift);
543 	if (!*matchlen)
544 		return -1;
545 	*matchoff += shift;
546 	return 1;
547 }
548 
549 /* Walk through headers until a parsable one is found or no header of the
550  * given type is left. */
ct_sip_walk_headers(const struct nf_conn * ct,const char * dptr,unsigned int dataoff,unsigned int datalen,enum sip_header_types type,int * in_header,unsigned int * matchoff,unsigned int * matchlen)551 static int ct_sip_walk_headers(const struct nf_conn *ct, const char *dptr,
552 			       unsigned int dataoff, unsigned int datalen,
553 			       enum sip_header_types type, int *in_header,
554 			       unsigned int *matchoff, unsigned int *matchlen)
555 {
556 	int ret;
557 
558 	if (in_header && *in_header) {
559 		while (1) {
560 			ret = ct_sip_next_header(ct, dptr, dataoff, datalen,
561 						 type, matchoff, matchlen);
562 			if (ret > 0)
563 				return ret;
564 			if (ret == 0)
565 				break;
566 			dataoff = *matchoff;
567 		}
568 		*in_header = 0;
569 	}
570 
571 	while (1) {
572 		ret = ct_sip_get_header(ct, dptr, dataoff, datalen,
573 					type, matchoff, matchlen);
574 		if (ret > 0)
575 			break;
576 		if (ret == 0)
577 			return ret;
578 		dataoff = *matchoff;
579 	}
580 
581 	if (in_header)
582 		*in_header = 1;
583 	return 1;
584 }
585 
586 /* Locate a SIP header, parse the URI and return the offset and length of
587  * the address as well as the address and port themselves. A stream of
588  * headers can be parsed by handing in a non-NULL datalen and in_header
589  * pointer.
590  */
ct_sip_parse_header_uri(const struct nf_conn * ct,const char * dptr,unsigned int * dataoff,unsigned int datalen,enum sip_header_types type,int * in_header,unsigned int * matchoff,unsigned int * matchlen,union nf_inet_addr * addr,__be16 * port)591 int ct_sip_parse_header_uri(const struct nf_conn *ct, const char *dptr,
592 			    unsigned int *dataoff, unsigned int datalen,
593 			    enum sip_header_types type, int *in_header,
594 			    unsigned int *matchoff, unsigned int *matchlen,
595 			    union nf_inet_addr *addr, __be16 *port)
596 {
597 	const char *c, *limit = dptr + datalen;
598 	int ret;
599 
600 	ret = ct_sip_walk_headers(ct, dptr, dataoff ? *dataoff : 0, datalen,
601 				  type, in_header, matchoff, matchlen);
602 	WARN_ON(ret < 0);
603 	if (ret == 0)
604 		return ret;
605 
606 	if (!sip_parse_addr(ct, dptr + *matchoff, &c, addr, limit, true))
607 		return -1;
608 	if (!sip_parse_port(c, &c, limit, port))
609 		return -1;
610 
611 	if (dataoff)
612 		*dataoff = c - dptr;
613 	return 1;
614 }
615 EXPORT_SYMBOL_GPL(ct_sip_parse_header_uri);
616 
ct_sip_parse_param(const struct nf_conn * ct,const char * dptr,unsigned int dataoff,unsigned int datalen,const char * name,unsigned int * matchoff,unsigned int * matchlen)617 static int ct_sip_parse_param(const struct nf_conn *ct, const char *dptr,
618 			      unsigned int dataoff, unsigned int datalen,
619 			      const char *name,
620 			      unsigned int *matchoff, unsigned int *matchlen)
621 {
622 	const char *limit = dptr + datalen;
623 	const char *start;
624 	const char *end;
625 
626 	limit = ct_sip_header_search(dptr + dataoff, limit, ",", strlen(","));
627 	if (!limit)
628 		limit = dptr + datalen;
629 
630 	start = ct_sip_header_search(dptr + dataoff, limit, name, strlen(name));
631 	if (!start)
632 		return 0;
633 	start += strlen(name);
634 
635 	end = ct_sip_header_search(start, limit, ";", strlen(";"));
636 	if (!end)
637 		end = limit;
638 
639 	*matchoff = start - dptr;
640 	*matchlen = end - start;
641 	return 1;
642 }
643 
644 /* Parse address from header parameter and return address, offset and length */
ct_sip_parse_address_param(const struct nf_conn * ct,const char * dptr,unsigned int dataoff,unsigned int datalen,const char * name,unsigned int * matchoff,unsigned int * matchlen,union nf_inet_addr * addr,bool delim)645 int ct_sip_parse_address_param(const struct nf_conn *ct, const char *dptr,
646 			       unsigned int dataoff, unsigned int datalen,
647 			       const char *name,
648 			       unsigned int *matchoff, unsigned int *matchlen,
649 			       union nf_inet_addr *addr, bool delim)
650 {
651 	const char *limit = dptr + datalen;
652 	const char *start, *end;
653 
654 	limit = ct_sip_header_search(dptr + dataoff, limit, ",", strlen(","));
655 	if (!limit)
656 		limit = dptr + datalen;
657 
658 	start = ct_sip_header_search(dptr + dataoff, limit, name, strlen(name));
659 	if (!start)
660 		return 0;
661 
662 	start += strlen(name);
663 	if (!sip_parse_addr(ct, start, &end, addr, limit, delim))
664 		return 0;
665 	*matchoff = start - dptr;
666 	*matchlen = end - start;
667 	return 1;
668 }
669 EXPORT_SYMBOL_GPL(ct_sip_parse_address_param);
670 
671 /* Parse numerical header parameter and return value, offset and length */
ct_sip_parse_numerical_param(const struct nf_conn * ct,const char * dptr,unsigned int dataoff,unsigned int datalen,const char * name,unsigned int * matchoff,unsigned int * matchlen,unsigned int * val)672 int ct_sip_parse_numerical_param(const struct nf_conn *ct, const char *dptr,
673 				 unsigned int dataoff, unsigned int datalen,
674 				 const char *name,
675 				 unsigned int *matchoff, unsigned int *matchlen,
676 				 unsigned int *val)
677 {
678 	const char *limit = dptr + datalen;
679 	const char *start;
680 	char *end;
681 
682 	limit = ct_sip_header_search(dptr + dataoff, limit, ",", strlen(","));
683 	if (!limit)
684 		limit = dptr + datalen;
685 
686 	start = ct_sip_header_search(dptr + dataoff, limit, name, strlen(name));
687 	if (!start)
688 		return 0;
689 
690 	start += strlen(name);
691 	*val = sip_strtouint(start, limit - start, (char **)&end);
692 	if (start == end)
693 		return -1;
694 	if (matchoff && matchlen) {
695 		*matchoff = start - dptr;
696 		*matchlen = end - start;
697 	}
698 	return 1;
699 }
700 EXPORT_SYMBOL_GPL(ct_sip_parse_numerical_param);
701 
ct_sip_parse_transport(struct nf_conn * ct,const char * dptr,unsigned int dataoff,unsigned int datalen,u8 * proto)702 static int ct_sip_parse_transport(struct nf_conn *ct, const char *dptr,
703 				  unsigned int dataoff, unsigned int datalen,
704 				  u8 *proto)
705 {
706 	unsigned int matchoff, matchlen;
707 
708 	if (ct_sip_parse_param(ct, dptr, dataoff, datalen, "transport=",
709 			       &matchoff, &matchlen)) {
710 		if (!strncasecmp(dptr + matchoff, "TCP", strlen("TCP")))
711 			*proto = IPPROTO_TCP;
712 		else if (!strncasecmp(dptr + matchoff, "UDP", strlen("UDP")))
713 			*proto = IPPROTO_UDP;
714 		else
715 			return 0;
716 
717 		if (*proto != nf_ct_protonum(ct))
718 			return 0;
719 	} else
720 		*proto = nf_ct_protonum(ct);
721 
722 	return 1;
723 }
724 
sdp_parse_addr(const struct nf_conn * ct,const char * cp,const char ** endp,union nf_inet_addr * addr,const char * limit)725 static int sdp_parse_addr(const struct nf_conn *ct, const char *cp,
726 			  const char **endp, union nf_inet_addr *addr,
727 			  const char *limit)
728 {
729 	const char *end;
730 	int ret;
731 
732 	memset(addr, 0, sizeof(*addr));
733 	switch (nf_ct_l3num(ct)) {
734 	case AF_INET:
735 		ret = in4_pton(cp, limit - cp, (u8 *)&addr->ip, -1, &end);
736 		break;
737 	case AF_INET6:
738 		ret = in6_pton(cp, limit - cp, (u8 *)&addr->ip6, -1, &end);
739 		break;
740 	default:
741 		BUG();
742 	}
743 
744 	if (ret == 0)
745 		return 0;
746 	if (endp)
747 		*endp = end;
748 	return 1;
749 }
750 
751 /* skip ip address. returns its length. */
sdp_addr_len(const struct nf_conn * ct,const char * dptr,const char * limit,int * shift)752 static int sdp_addr_len(const struct nf_conn *ct, const char *dptr,
753 			const char *limit, int *shift)
754 {
755 	union nf_inet_addr addr;
756 	const char *aux = dptr;
757 
758 	if (!sdp_parse_addr(ct, dptr, &dptr, &addr, limit)) {
759 		pr_debug("ip: %s parse failed.!\n", dptr);
760 		return 0;
761 	}
762 
763 	return dptr - aux;
764 }
765 
766 /* SDP header parsing: a SDP session description contains an ordered set of
767  * headers, starting with a section containing general session parameters,
768  * optionally followed by multiple media descriptions.
769  *
770  * SDP headers always start at the beginning of a line. According to RFC 2327:
771  * "The sequence CRLF (0x0d0a) is used to end a record, although parsers should
772  * be tolerant and also accept records terminated with a single newline
773  * character". We handle both cases.
774  */
775 static const struct sip_header ct_sdp_hdrs_v4[] = {
776 	[SDP_HDR_VERSION]	= SDP_HDR("v=", NULL, digits_len),
777 	[SDP_HDR_OWNER]		= SDP_HDR("o=", "IN IP4 ", sdp_addr_len),
778 	[SDP_HDR_CONNECTION]	= SDP_HDR("c=", "IN IP4 ", sdp_addr_len),
779 	[SDP_HDR_MEDIA]		= SDP_HDR("m=", NULL, media_len),
780 };
781 
782 static const struct sip_header ct_sdp_hdrs_v6[] = {
783 	[SDP_HDR_VERSION]	= SDP_HDR("v=", NULL, digits_len),
784 	[SDP_HDR_OWNER]		= SDP_HDR("o=", "IN IP6 ", sdp_addr_len),
785 	[SDP_HDR_CONNECTION]	= SDP_HDR("c=", "IN IP6 ", sdp_addr_len),
786 	[SDP_HDR_MEDIA]		= SDP_HDR("m=", NULL, media_len),
787 };
788 
789 /* Linear string search within SDP header values */
ct_sdp_header_search(const char * dptr,const char * limit,const char * needle,unsigned int len)790 static const char *ct_sdp_header_search(const char *dptr, const char *limit,
791 					const char *needle, unsigned int len)
792 {
793 	for (limit -= len; dptr < limit; dptr++) {
794 		if (*dptr == '\r' || *dptr == '\n')
795 			break;
796 		if (strncmp(dptr, needle, len) == 0)
797 			return dptr;
798 	}
799 	return NULL;
800 }
801 
802 /* Locate a SDP header (optionally a substring within the header value),
803  * optionally stopping at the first occurrence of the term header, parse
804  * it and return the offset and length of the data we're interested in.
805  */
ct_sip_get_sdp_header(const struct nf_conn * ct,const char * dptr,unsigned int dataoff,unsigned int datalen,enum sdp_header_types type,enum sdp_header_types term,unsigned int * matchoff,unsigned int * matchlen)806 int ct_sip_get_sdp_header(const struct nf_conn *ct, const char *dptr,
807 			  unsigned int dataoff, unsigned int datalen,
808 			  enum sdp_header_types type,
809 			  enum sdp_header_types term,
810 			  unsigned int *matchoff, unsigned int *matchlen)
811 {
812 	const struct sip_header *hdrs, *hdr, *thdr;
813 	const char *start = dptr, *limit = dptr + datalen;
814 	int shift = 0;
815 
816 	hdrs = nf_ct_l3num(ct) == NFPROTO_IPV4 ? ct_sdp_hdrs_v4 : ct_sdp_hdrs_v6;
817 	hdr = &hdrs[type];
818 	thdr = &hdrs[term];
819 
820 	for (dptr += dataoff; dptr < limit; dptr++) {
821 		/* Find beginning of line */
822 		if (*dptr != '\r' && *dptr != '\n')
823 			continue;
824 		if (++dptr >= limit)
825 			break;
826 		if (*(dptr - 1) == '\r' && *dptr == '\n') {
827 			if (++dptr >= limit)
828 				break;
829 		}
830 
831 		if (term != SDP_HDR_UNSPEC &&
832 		    limit - dptr >= thdr->len &&
833 		    strncasecmp(dptr, thdr->name, thdr->len) == 0)
834 			break;
835 		else if (limit - dptr >= hdr->len &&
836 			 strncasecmp(dptr, hdr->name, hdr->len) == 0)
837 			dptr += hdr->len;
838 		else
839 			continue;
840 
841 		*matchoff = dptr - start;
842 		if (hdr->search) {
843 			dptr = ct_sdp_header_search(dptr, limit, hdr->search,
844 						    hdr->slen);
845 			if (!dptr)
846 				return -1;
847 			dptr += hdr->slen;
848 		}
849 
850 		*matchlen = hdr->match_len(ct, dptr, limit, &shift);
851 		if (!*matchlen)
852 			return -1;
853 		*matchoff = dptr - start + shift;
854 		return 1;
855 	}
856 	return 0;
857 }
858 EXPORT_SYMBOL_GPL(ct_sip_get_sdp_header);
859 
ct_sip_parse_sdp_addr(const struct nf_conn * ct,const char * dptr,unsigned int dataoff,unsigned int datalen,enum sdp_header_types type,enum sdp_header_types term,unsigned int * matchoff,unsigned int * matchlen,union nf_inet_addr * addr)860 static int ct_sip_parse_sdp_addr(const struct nf_conn *ct, const char *dptr,
861 				 unsigned int dataoff, unsigned int datalen,
862 				 enum sdp_header_types type,
863 				 enum sdp_header_types term,
864 				 unsigned int *matchoff, unsigned int *matchlen,
865 				 union nf_inet_addr *addr)
866 {
867 	int ret;
868 
869 	ret = ct_sip_get_sdp_header(ct, dptr, dataoff, datalen, type, term,
870 				    matchoff, matchlen);
871 	if (ret <= 0)
872 		return ret;
873 
874 	if (!sdp_parse_addr(ct, dptr + *matchoff, NULL, addr,
875 			    dptr + *matchoff + *matchlen))
876 		return -1;
877 	return 1;
878 }
879 
refresh_signalling_expectation(struct nf_conn * ct,union nf_inet_addr * addr,u8 proto,__be16 port,unsigned int expires)880 static int refresh_signalling_expectation(struct nf_conn *ct,
881 					  union nf_inet_addr *addr,
882 					  u8 proto, __be16 port,
883 					  unsigned int expires)
884 {
885 	struct nf_conn_help *help = nfct_help(ct);
886 	struct nf_conntrack_expect *exp;
887 	struct hlist_node *next;
888 	int found = 0;
889 
890 	if (!help)
891 		return 0;
892 
893 	spin_lock_bh(&nf_conntrack_expect_lock);
894 	hlist_for_each_entry_safe(exp, next, &help->expectations, lnode) {
895 		if (exp->class != SIP_EXPECT_SIGNALLING ||
896 		    !nf_inet_addr_cmp(&exp->tuple.dst.u3, addr) ||
897 		    exp->tuple.dst.protonum != proto ||
898 		    exp->tuple.dst.u.udp.port != port)
899 			continue;
900 		WRITE_ONCE(exp->timeout, nfct_time_stamp + (expires * HZ));
901 		WRITE_ONCE(exp->flags, exp->flags & ~NF_CT_EXPECT_INACTIVE);
902 		found = 1;
903 		break;
904 	}
905 	spin_unlock_bh(&nf_conntrack_expect_lock);
906 	return found;
907 }
908 
flush_expectations(struct nf_conn * ct,bool media)909 static void flush_expectations(struct nf_conn *ct, bool media)
910 {
911 	struct nf_conn_help *help = nfct_help(ct);
912 	struct nf_conntrack_expect *exp;
913 	struct hlist_node *next;
914 
915 	if (!help)
916 		return;
917 
918 	spin_lock_bh(&nf_conntrack_expect_lock);
919 	hlist_for_each_entry_safe(exp, next, &help->expectations, lnode) {
920 		if ((exp->class != SIP_EXPECT_SIGNALLING) ^ media)
921 			continue;
922 		nf_ct_unlink_expect(exp);
923 		if (!media)
924 			break;
925 	}
926 	spin_unlock_bh(&nf_conntrack_expect_lock);
927 }
928 
set_expected_rtp_rtcp(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen,union nf_inet_addr * daddr,__be16 port,enum sip_expectation_classes class,unsigned int mediaoff,unsigned int medialen)929 static int set_expected_rtp_rtcp(struct sk_buff *skb, unsigned int protoff,
930 				 unsigned int dataoff,
931 				 const char **dptr, unsigned int *datalen,
932 				 union nf_inet_addr *daddr, __be16 port,
933 				 enum sip_expectation_classes class,
934 				 unsigned int mediaoff, unsigned int medialen)
935 {
936 	struct nf_conntrack_expect *exp, *rtp_exp, *rtcp_exp;
937 	enum ip_conntrack_info ctinfo;
938 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
939 	struct net *net = nf_ct_net(ct);
940 	enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
941 	union nf_inet_addr *saddr;
942 	struct nf_conntrack_tuple tuple;
943 	int direct_rtp = 0, skip_expect = 0, ret = NF_DROP;
944 	u_int16_t base_port;
945 	__be16 rtp_port, rtcp_port;
946 	const struct nf_nat_sip_hooks *hooks;
947 	struct nf_conn_help *help;
948 
949 	help = nfct_help(ct);
950 	if (!help)
951 		return NF_DROP;
952 
953 	saddr = NULL;
954 	if (sip_direct_media) {
955 		if (!nf_inet_addr_cmp(daddr, &ct->tuplehash[dir].tuple.src.u3))
956 			return NF_ACCEPT;
957 		saddr = &ct->tuplehash[!dir].tuple.src.u3;
958 	} else if (sip_external_media) {
959 		struct dst_entry *dst = NULL;
960 		struct flowi fl;
961 
962 		memset(&fl, 0, sizeof(fl));
963 
964 		switch (nf_ct_l3num(ct)) {
965 			case NFPROTO_IPV4:
966 				fl.u.ip4.daddr = daddr->ip;
967 				nf_ip_route(net, &dst, &fl, false);
968 				break;
969 
970 			case NFPROTO_IPV6:
971 				fl.u.ip6.daddr = daddr->in6;
972 				nf_ip6_route(net, &dst, &fl, false);
973 				break;
974 		}
975 
976 		/* Don't predict any conntracks when media endpoint is reachable
977 		 * through the same interface as the signalling peer.
978 		 */
979 		if (dst) {
980 			const struct dst_entry *this_dst = skb_dst(skb);
981 			bool external_media = false;
982 
983 			if (this_dst && dst->dev == this_dst->dev)
984 				external_media = true;
985 
986 			dst_release(dst);
987 			if (external_media)
988 				return NF_ACCEPT;
989 		}
990 	}
991 
992 	/* We need to check whether the registration exists before attempting
993 	 * to register it since we can see the same media description multiple
994 	 * times on different connections in case multiple endpoints receive
995 	 * the same call.
996 	 *
997 	 * RTP optimization: if we find a matching media channel expectation
998 	 * and both the expectation and this connection are SNATed, we assume
999 	 * both sides can reach each other directly and use the final
1000 	 * destination address from the expectation. We still need to keep
1001 	 * the NATed expectations for media that might arrive from the
1002 	 * outside, and additionally need to expect the direct RTP stream
1003 	 * in case it passes through us even without NAT.
1004 	 */
1005 	memset(&tuple, 0, sizeof(tuple));
1006 	if (saddr)
1007 		tuple.src.u3 = *saddr;
1008 	tuple.src.l3num		= nf_ct_l3num(ct);
1009 	tuple.dst.protonum	= IPPROTO_UDP;
1010 	tuple.dst.u3		= *daddr;
1011 	tuple.dst.u.udp.port	= port;
1012 
1013 	do {
1014 		exp = __nf_ct_expect_find(net, nf_ct_zone(ct), &tuple);
1015 
1016 		if (!exp || exp->master == ct ||
1017 		    exp->helper != help->helper ||
1018 		    exp->class != class)
1019 			break;
1020 #if IS_ENABLED(CONFIG_NF_NAT)
1021 		if (!direct_rtp &&
1022 		    (!nf_inet_addr_cmp(&exp->saved_addr, &exp->tuple.dst.u3) ||
1023 		     exp->saved_proto.udp.port != exp->tuple.dst.u.udp.port) &&
1024 		    ct->status & IPS_NAT_MASK) {
1025 			*daddr			= exp->saved_addr;
1026 			tuple.dst.u3		= exp->saved_addr;
1027 			tuple.dst.u.udp.port	= exp->saved_proto.udp.port;
1028 			direct_rtp = 1;
1029 		} else
1030 #endif
1031 			skip_expect = 1;
1032 	} while (!skip_expect);
1033 
1034 	base_port = ntohs(tuple.dst.u.udp.port) & ~1;
1035 	rtp_port = htons(base_port);
1036 	rtcp_port = htons(base_port + 1);
1037 
1038 	if (direct_rtp) {
1039 		hooks = rcu_dereference(nf_nat_sip_hooks);
1040 		if (hooks &&
1041 		    !hooks->sdp_port(skb, protoff, dataoff, dptr, datalen,
1042 				     mediaoff, medialen, ntohs(rtp_port)))
1043 			goto err1;
1044 	}
1045 
1046 	if (skip_expect)
1047 		return NF_ACCEPT;
1048 
1049 	rtp_exp = nf_ct_expect_alloc(ct);
1050 	if (rtp_exp == NULL)
1051 		goto err1;
1052 	nf_ct_expect_init(rtp_exp, class, nf_ct_l3num(ct), saddr, daddr,
1053 			  IPPROTO_UDP, NULL, &rtp_port);
1054 
1055 	rtcp_exp = nf_ct_expect_alloc(ct);
1056 	if (rtcp_exp == NULL)
1057 		goto err2;
1058 	nf_ct_expect_init(rtcp_exp, class, nf_ct_l3num(ct), saddr, daddr,
1059 			  IPPROTO_UDP, NULL, &rtcp_port);
1060 
1061 	hooks = rcu_dereference(nf_nat_sip_hooks);
1062 	if (hooks && ct->status & IPS_NAT_MASK && !direct_rtp)
1063 		ret = hooks->sdp_media(skb, protoff, dataoff, dptr,
1064 				       datalen, rtp_exp, rtcp_exp,
1065 				       mediaoff, medialen, daddr);
1066 	else {
1067 		/* -EALREADY handling works around end-points that send
1068 		 * SDP messages with identical port but different media type,
1069 		 * we pretend expectation was set up.
1070 		 * It also works in the case that SDP messages are sent with
1071 		 * identical expect tuples but for different master conntracks.
1072 		 */
1073 		int errp = nf_ct_expect_related(rtp_exp,
1074 						NF_CT_EXP_F_SKIP_MASTER);
1075 
1076 		if (errp == 0 || errp == -EALREADY) {
1077 			int errcp = nf_ct_expect_related(rtcp_exp,
1078 						NF_CT_EXP_F_SKIP_MASTER);
1079 
1080 			if (errcp == 0 || errcp == -EALREADY)
1081 				ret = NF_ACCEPT;
1082 			else if (errp == 0)
1083 				nf_ct_unexpect_related(rtp_exp);
1084 		}
1085 	}
1086 	nf_ct_expect_put(rtcp_exp);
1087 err2:
1088 	nf_ct_expect_put(rtp_exp);
1089 err1:
1090 	return ret;
1091 }
1092 
1093 static const struct sdp_media_type sdp_media_types[] = {
1094 	SDP_MEDIA_TYPE("audio ", SIP_EXPECT_AUDIO),
1095 	SDP_MEDIA_TYPE("video ", SIP_EXPECT_VIDEO),
1096 	SDP_MEDIA_TYPE("image ", SIP_EXPECT_IMAGE),
1097 };
1098 
sdp_media_type(const char * dptr,unsigned int matchoff,unsigned int matchlen)1099 static const struct sdp_media_type *sdp_media_type(const char *dptr,
1100 						   unsigned int matchoff,
1101 						   unsigned int matchlen)
1102 {
1103 	const struct sdp_media_type *t;
1104 	unsigned int i;
1105 
1106 	for (i = 0; i < ARRAY_SIZE(sdp_media_types); i++) {
1107 		t = &sdp_media_types[i];
1108 		if (matchlen < t->len ||
1109 		    strncmp(dptr + matchoff, t->name, t->len))
1110 			continue;
1111 		return t;
1112 	}
1113 	return NULL;
1114 }
1115 
process_sdp(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen,unsigned int cseq)1116 static int process_sdp(struct sk_buff *skb, unsigned int protoff,
1117 		       unsigned int dataoff,
1118 		       const char **dptr, unsigned int *datalen,
1119 		       unsigned int cseq)
1120 {
1121 	enum ip_conntrack_info ctinfo;
1122 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1123 	unsigned int matchoff, matchlen;
1124 	unsigned int mediaoff, medialen;
1125 	unsigned int sdpoff;
1126 	unsigned int caddr_len, maddr_len;
1127 	unsigned int i;
1128 	union nf_inet_addr caddr, maddr, rtp_addr;
1129 	const struct nf_nat_sip_hooks *hooks;
1130 	unsigned int port;
1131 	const struct sdp_media_type *t;
1132 	int ret = NF_ACCEPT;
1133 	bool have_rtp_addr = false;
1134 
1135 	hooks = rcu_dereference(nf_nat_sip_hooks);
1136 
1137 	/* Find beginning of session description */
1138 	if (ct_sip_get_sdp_header(ct, *dptr, 0, *datalen,
1139 				  SDP_HDR_VERSION, SDP_HDR_UNSPEC,
1140 				  &matchoff, &matchlen) <= 0)
1141 		return NF_ACCEPT;
1142 	sdpoff = matchoff;
1143 
1144 	/* The connection information is contained in the session description
1145 	 * and/or once per media description. The first media description marks
1146 	 * the end of the session description. */
1147 	caddr_len = 0;
1148 	if (ct_sip_parse_sdp_addr(ct, *dptr, sdpoff, *datalen,
1149 				  SDP_HDR_CONNECTION, SDP_HDR_MEDIA,
1150 				  &matchoff, &matchlen, &caddr) > 0) {
1151 		caddr_len = matchlen;
1152 		memcpy(&rtp_addr, &caddr, sizeof(rtp_addr));
1153 		have_rtp_addr = true;
1154 	}
1155 
1156 	mediaoff = sdpoff;
1157 	for (i = 0; i < ARRAY_SIZE(sdp_media_types); ) {
1158 		char *end;
1159 
1160 		if (ct_sip_get_sdp_header(ct, *dptr, mediaoff, *datalen,
1161 					  SDP_HDR_MEDIA, SDP_HDR_UNSPEC,
1162 					  &mediaoff, &medialen) <= 0)
1163 			break;
1164 
1165 		/* Get media type and port number. A media port value of zero
1166 		 * indicates an inactive stream. */
1167 		t = sdp_media_type(*dptr, mediaoff, medialen);
1168 		if (!t) {
1169 			mediaoff += medialen;
1170 			continue;
1171 		}
1172 		mediaoff += t->len;
1173 		medialen -= t->len;
1174 
1175 		port = sip_strtouint(*dptr + mediaoff, *datalen - mediaoff, (char **)&end);
1176 		if (port == 0 || *dptr + mediaoff == end)
1177 			continue;
1178 		if (port < 1024 || port > 65535) {
1179 			nf_ct_helper_log(skb, ct, "wrong port %u", port);
1180 			return NF_DROP;
1181 		}
1182 
1183 		/* The media description overrides the session description. */
1184 		maddr_len = 0;
1185 		if (ct_sip_parse_sdp_addr(ct, *dptr, mediaoff, *datalen,
1186 					  SDP_HDR_CONNECTION, SDP_HDR_MEDIA,
1187 					  &matchoff, &matchlen, &maddr) > 0) {
1188 			maddr_len = matchlen;
1189 			memcpy(&rtp_addr, &maddr, sizeof(rtp_addr));
1190 			have_rtp_addr = true;
1191 		} else if (caddr_len) {
1192 			memcpy(&rtp_addr, &caddr, sizeof(rtp_addr));
1193 			have_rtp_addr = true;
1194 		} else {
1195 			nf_ct_helper_log(skb, ct, "cannot parse SDP message");
1196 			return NF_DROP;
1197 		}
1198 
1199 		ret = set_expected_rtp_rtcp(skb, protoff, dataoff,
1200 					    dptr, datalen,
1201 					    &rtp_addr, htons(port), t->class,
1202 					    mediaoff, medialen);
1203 		if (ret != NF_ACCEPT) {
1204 			nf_ct_helper_log(skb, ct,
1205 					 "cannot add expectation for voice");
1206 			return ret;
1207 		}
1208 
1209 		/* Update media connection address if present */
1210 		if (maddr_len && hooks && ct->status & IPS_NAT_MASK) {
1211 			ret = hooks->sdp_addr(skb, protoff, dataoff,
1212 					      dptr, datalen, mediaoff,
1213 					      SDP_HDR_CONNECTION,
1214 					      SDP_HDR_MEDIA,
1215 					      &rtp_addr);
1216 			if (ret != NF_ACCEPT) {
1217 				nf_ct_helper_log(skb, ct, "cannot mangle SDP");
1218 				return ret;
1219 			}
1220 		}
1221 		i++;
1222 	}
1223 
1224 	/* Update session connection and owner addresses */
1225 	hooks = rcu_dereference(nf_nat_sip_hooks);
1226 	if (hooks && ct->status & IPS_NAT_MASK && have_rtp_addr)
1227 		ret = hooks->sdp_session(skb, protoff, dataoff,
1228 					 dptr, datalen, sdpoff,
1229 					 &rtp_addr);
1230 
1231 	return ret;
1232 }
process_invite_response(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen,unsigned int cseq,unsigned int code)1233 static int process_invite_response(struct sk_buff *skb, unsigned int protoff,
1234 				   unsigned int dataoff,
1235 				   const char **dptr, unsigned int *datalen,
1236 				   unsigned int cseq, unsigned int code)
1237 {
1238 	enum ip_conntrack_info ctinfo;
1239 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1240 	struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1241 
1242 	if (!ct_sip_info)
1243 		return NF_DROP;
1244 
1245 	if ((code >= 100 && code <= 199) ||
1246 	    (code >= 200 && code <= 299))
1247 		return process_sdp(skb, protoff, dataoff, dptr, datalen, cseq);
1248 	else if (ct_sip_info->invite_cseq == cseq)
1249 		flush_expectations(ct, true);
1250 	return NF_ACCEPT;
1251 }
1252 
process_update_response(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen,unsigned int cseq,unsigned int code)1253 static int process_update_response(struct sk_buff *skb, unsigned int protoff,
1254 				   unsigned int dataoff,
1255 				   const char **dptr, unsigned int *datalen,
1256 				   unsigned int cseq, unsigned int code)
1257 {
1258 	enum ip_conntrack_info ctinfo;
1259 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1260 	struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1261 
1262 	if (!ct_sip_info)
1263 		return NF_DROP;
1264 
1265 	if ((code >= 100 && code <= 199) ||
1266 	    (code >= 200 && code <= 299))
1267 		return process_sdp(skb, protoff, dataoff, dptr, datalen, cseq);
1268 	else if (ct_sip_info->invite_cseq == cseq)
1269 		flush_expectations(ct, true);
1270 	return NF_ACCEPT;
1271 }
1272 
process_prack_response(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen,unsigned int cseq,unsigned int code)1273 static int process_prack_response(struct sk_buff *skb, unsigned int protoff,
1274 				  unsigned int dataoff,
1275 				  const char **dptr, unsigned int *datalen,
1276 				  unsigned int cseq, unsigned int code)
1277 {
1278 	enum ip_conntrack_info ctinfo;
1279 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1280 	struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1281 
1282 	if (!ct_sip_info)
1283 		return NF_DROP;
1284 
1285 	if ((code >= 100 && code <= 199) ||
1286 	    (code >= 200 && code <= 299))
1287 		return process_sdp(skb, protoff, dataoff, dptr, datalen, cseq);
1288 	else if (ct_sip_info->invite_cseq == cseq)
1289 		flush_expectations(ct, true);
1290 	return NF_ACCEPT;
1291 }
1292 
process_invite_request(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen,unsigned int cseq)1293 static int process_invite_request(struct sk_buff *skb, unsigned int protoff,
1294 				  unsigned int dataoff,
1295 				  const char **dptr, unsigned int *datalen,
1296 				  unsigned int cseq)
1297 {
1298 	enum ip_conntrack_info ctinfo;
1299 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1300 	struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1301 	unsigned int ret;
1302 
1303 	if (!ct_sip_info)
1304 		return NF_DROP;
1305 
1306 	flush_expectations(ct, true);
1307 	ret = process_sdp(skb, protoff, dataoff, dptr, datalen, cseq);
1308 	if (ret == NF_ACCEPT)
1309 		ct_sip_info->invite_cseq = cseq;
1310 	return ret;
1311 }
1312 
process_bye_request(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen,unsigned int cseq)1313 static int process_bye_request(struct sk_buff *skb, unsigned int protoff,
1314 			       unsigned int dataoff,
1315 			       const char **dptr, unsigned int *datalen,
1316 			       unsigned int cseq)
1317 {
1318 	enum ip_conntrack_info ctinfo;
1319 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1320 
1321 	flush_expectations(ct, true);
1322 	return NF_ACCEPT;
1323 }
1324 
1325 /* Parse a REGISTER request and create a permanent expectation for incoming
1326  * signalling connections. The expectation is marked inactive and is activated
1327  * when receiving a response indicating success from the registrar.
1328  */
process_register_request(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen,unsigned int cseq)1329 static int process_register_request(struct sk_buff *skb, unsigned int protoff,
1330 				    unsigned int dataoff,
1331 				    const char **dptr, unsigned int *datalen,
1332 				    unsigned int cseq)
1333 {
1334 	enum ip_conntrack_info ctinfo;
1335 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1336 	struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1337 	enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
1338 	unsigned int matchoff, matchlen;
1339 	struct nf_conntrack_expect *exp;
1340 	union nf_inet_addr *saddr, daddr;
1341 	const struct nf_nat_sip_hooks *hooks;
1342 	struct nf_conntrack_helper *helper;
1343 	struct nf_conn_help *help;
1344 	__be16 port;
1345 	u8 proto;
1346 	unsigned int expires = 0;
1347 	int ret;
1348 
1349 	if (!ct_sip_info)
1350 		return NF_DROP;
1351 
1352 	/* Expected connections can not register again. */
1353 	if (ct->status & IPS_EXPECTED)
1354 		return NF_ACCEPT;
1355 
1356 	/* We must check the expiration time: a value of zero signals the
1357 	 * registrar to release the binding. We'll remove our expectation
1358 	 * when receiving the new bindings in the response, but we don't
1359 	 * want to create new ones.
1360 	 *
1361 	 * The expiration time may be contained in Expires: header, the
1362 	 * Contact: header parameters or the URI parameters.
1363 	 */
1364 	if (ct_sip_get_header(ct, *dptr, 0, *datalen, SIP_HDR_EXPIRES,
1365 			      &matchoff, &matchlen) > 0)
1366 		expires = sip_strtouint(*dptr + matchoff, *datalen - matchoff, NULL);
1367 
1368 	ret = ct_sip_parse_header_uri(ct, *dptr, NULL, *datalen,
1369 				      SIP_HDR_CONTACT, NULL,
1370 				      &matchoff, &matchlen, &daddr, &port);
1371 	if (ret < 0) {
1372 		nf_ct_helper_log(skb, ct, "cannot parse contact");
1373 		return NF_DROP;
1374 	} else if (ret == 0)
1375 		return NF_ACCEPT;
1376 
1377 	/* We don't support third-party registrations */
1378 	if (!nf_inet_addr_cmp(&ct->tuplehash[dir].tuple.src.u3, &daddr))
1379 		return NF_ACCEPT;
1380 
1381 	if (ct_sip_parse_transport(ct, *dptr, matchoff + matchlen, *datalen,
1382 				   &proto) == 0)
1383 		return NF_ACCEPT;
1384 
1385 	if (ct_sip_parse_numerical_param(ct, *dptr,
1386 					 matchoff + matchlen, *datalen,
1387 					 "expires=", NULL, NULL, &expires) < 0) {
1388 		nf_ct_helper_log(skb, ct, "cannot parse expires");
1389 		return NF_DROP;
1390 	}
1391 
1392 	if (expires == 0) {
1393 		ret = NF_ACCEPT;
1394 		goto store_cseq;
1395 	}
1396 
1397 	help = nfct_help(ct);
1398 	if (!help)
1399 		return NF_DROP;
1400 
1401 	helper = rcu_dereference(help->helper);
1402 	if (!helper)
1403 		return NF_DROP;
1404 
1405 	exp = nf_ct_expect_alloc(ct);
1406 	if (!exp) {
1407 		nf_ct_helper_log(skb, ct, "cannot alloc expectation");
1408 		return NF_DROP;
1409 	}
1410 
1411 	saddr = NULL;
1412 	if (sip_direct_signalling)
1413 		saddr = &ct->tuplehash[!dir].tuple.src.u3;
1414 
1415 	nf_ct_expect_init(exp, SIP_EXPECT_SIGNALLING, nf_ct_l3num(ct),
1416 			  saddr, &daddr, proto, NULL, &port);
1417 	rcu_assign_pointer(exp->assign_helper, helper);
1418 	exp->flags = NF_CT_EXPECT_PERMANENT | NF_CT_EXPECT_INACTIVE;
1419 
1420 	hooks = rcu_dereference(nf_nat_sip_hooks);
1421 	if (hooks && ct->status & IPS_NAT_MASK)
1422 		ret = hooks->expect(skb, protoff, dataoff, dptr, datalen,
1423 				    exp, matchoff, matchlen);
1424 	else {
1425 		if (nf_ct_expect_related(exp, 0) != 0) {
1426 			nf_ct_helper_log(skb, ct, "cannot add expectation");
1427 			ret = NF_DROP;
1428 		} else
1429 			ret = NF_ACCEPT;
1430 	}
1431 	nf_ct_expect_put(exp);
1432 
1433 store_cseq:
1434 	if (ret == NF_ACCEPT)
1435 		ct_sip_info->register_cseq = cseq;
1436 	return ret;
1437 }
1438 
process_register_response(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen,unsigned int cseq,unsigned int code)1439 static int process_register_response(struct sk_buff *skb, unsigned int protoff,
1440 				     unsigned int dataoff,
1441 				     const char **dptr, unsigned int *datalen,
1442 				     unsigned int cseq, unsigned int code)
1443 {
1444 	enum ip_conntrack_info ctinfo;
1445 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1446 	struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1447 	enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
1448 	union nf_inet_addr addr;
1449 	__be16 port;
1450 	u8 proto;
1451 	unsigned int matchoff, matchlen, coff = 0;
1452 	unsigned int expires = 0;
1453 	int in_contact = 0, ret;
1454 
1455 	if (!ct_sip_info)
1456 		return NF_DROP;
1457 
1458 	/* According to RFC 3261, "UAs MUST NOT send a new registration until
1459 	 * they have received a final response from the registrar for the
1460 	 * previous one or the previous REGISTER request has timed out".
1461 	 *
1462 	 * However, some servers fail to detect retransmissions and send late
1463 	 * responses, so we store the sequence number of the last valid
1464 	 * request and compare it here.
1465 	 */
1466 	if (ct_sip_info->register_cseq != cseq)
1467 		return NF_ACCEPT;
1468 
1469 	if (code >= 100 && code <= 199)
1470 		return NF_ACCEPT;
1471 	if (code < 200 || code > 299)
1472 		goto flush;
1473 
1474 	if (ct_sip_get_header(ct, *dptr, 0, *datalen, SIP_HDR_EXPIRES,
1475 			      &matchoff, &matchlen) > 0)
1476 		expires = sip_strtouint(*dptr + matchoff, *datalen - matchoff, NULL);
1477 
1478 	while (1) {
1479 		unsigned int c_expires = expires;
1480 
1481 		ret = ct_sip_parse_header_uri(ct, *dptr, &coff, *datalen,
1482 					      SIP_HDR_CONTACT, &in_contact,
1483 					      &matchoff, &matchlen,
1484 					      &addr, &port);
1485 		if (ret < 0) {
1486 			nf_ct_helper_log(skb, ct, "cannot parse contact");
1487 			return NF_DROP;
1488 		} else if (ret == 0)
1489 			break;
1490 
1491 		/* We don't support third-party registrations */
1492 		if (!nf_inet_addr_cmp(&ct->tuplehash[dir].tuple.dst.u3, &addr))
1493 			continue;
1494 
1495 		if (ct_sip_parse_transport(ct, *dptr, matchoff + matchlen,
1496 					   *datalen, &proto) == 0)
1497 			continue;
1498 
1499 		ret = ct_sip_parse_numerical_param(ct, *dptr,
1500 						   matchoff + matchlen,
1501 						   *datalen, "expires=",
1502 						   NULL, NULL, &c_expires);
1503 		if (ret < 0) {
1504 			nf_ct_helper_log(skb, ct, "cannot parse expires");
1505 			return NF_DROP;
1506 		}
1507 		if (c_expires == 0)
1508 			break;
1509 		if (refresh_signalling_expectation(ct, &addr, proto, port,
1510 						   c_expires))
1511 			return NF_ACCEPT;
1512 	}
1513 
1514 flush:
1515 	flush_expectations(ct, false);
1516 	return NF_ACCEPT;
1517 }
1518 
1519 static const struct sip_handler sip_handlers[] = {
1520 	SIP_HANDLER("INVITE", process_invite_request, process_invite_response),
1521 	SIP_HANDLER("UPDATE", process_sdp, process_update_response),
1522 	SIP_HANDLER("ACK", process_sdp, NULL),
1523 	SIP_HANDLER("PRACK", process_sdp, process_prack_response),
1524 	SIP_HANDLER("BYE", process_bye_request, NULL),
1525 	SIP_HANDLER("REGISTER", process_register_request, process_register_response),
1526 };
1527 
process_sip_response(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen)1528 static int process_sip_response(struct sk_buff *skb, unsigned int protoff,
1529 				unsigned int dataoff,
1530 				const char **dptr, unsigned int *datalen)
1531 {
1532 	enum ip_conntrack_info ctinfo;
1533 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1534 	unsigned int matchoff, matchlen, matchend;
1535 	unsigned int code, cseq, i;
1536 	char *end;
1537 
1538 	if (*datalen < strlen("SIP/2.0 200"))
1539 		return NF_ACCEPT;
1540 	code = sip_strtouint(*dptr + strlen("SIP/2.0 "),
1541 			     *datalen - strlen("SIP/2.0 "), NULL);
1542 	if (!code) {
1543 		nf_ct_helper_log(skb, ct, "cannot get code");
1544 		return NF_DROP;
1545 	}
1546 
1547 	if (ct_sip_get_header(ct, *dptr, 0, *datalen, SIP_HDR_CSEQ,
1548 			      &matchoff, &matchlen) <= 0) {
1549 		nf_ct_helper_log(skb, ct, "cannot parse cseq");
1550 		return NF_DROP;
1551 	}
1552 	cseq = sip_strtouint(*dptr + matchoff, *datalen - matchoff, (char **)&end);
1553 	if (*dptr + matchoff == end) {
1554 		nf_ct_helper_log(skb, ct, "cannot get cseq");
1555 		return NF_DROP;
1556 	}
1557 	matchend = matchoff + matchlen + 1;
1558 
1559 	for (i = 0; i < ARRAY_SIZE(sip_handlers); i++) {
1560 		const struct sip_handler *handler;
1561 
1562 		handler = &sip_handlers[i];
1563 		if (handler->response == NULL)
1564 			continue;
1565 		if (*datalen < matchend + handler->len ||
1566 		    strncasecmp(*dptr + matchend, handler->method, handler->len))
1567 			continue;
1568 		return handler->response(skb, protoff, dataoff, dptr, datalen,
1569 					 cseq, code);
1570 	}
1571 	return NF_ACCEPT;
1572 }
1573 
process_sip_request(struct sk_buff * skb,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen)1574 static int process_sip_request(struct sk_buff *skb, unsigned int protoff,
1575 			       unsigned int dataoff,
1576 			       const char **dptr, unsigned int *datalen)
1577 {
1578 	enum ip_conntrack_info ctinfo;
1579 	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1580 	struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1581 	enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
1582 	unsigned int matchoff, matchlen;
1583 	unsigned int cseq, i;
1584 	union nf_inet_addr addr;
1585 	__be16 port;
1586 
1587 	if (!ct_sip_info)
1588 		return NF_DROP;
1589 
1590 	/* Many Cisco IP phones use a high source port for SIP requests, but
1591 	 * listen for the response on port 5060.  If we are the local
1592 	 * router for one of these phones, save the port number from the
1593 	 * Via: header so that nf_nat_sip can redirect the responses to
1594 	 * the correct port.
1595 	 */
1596 	if (ct_sip_parse_header_uri(ct, *dptr, NULL, *datalen,
1597 				    SIP_HDR_VIA_UDP, NULL, &matchoff,
1598 				    &matchlen, &addr, &port) > 0 &&
1599 	    port != ct->tuplehash[dir].tuple.src.u.udp.port &&
1600 	    nf_inet_addr_cmp(&addr, &ct->tuplehash[dir].tuple.src.u3))
1601 		ct_sip_info->forced_dport = port;
1602 
1603 	for (i = 0; i < ARRAY_SIZE(sip_handlers); i++) {
1604 		const struct sip_handler *handler;
1605 		char *end;
1606 
1607 		handler = &sip_handlers[i];
1608 		if (handler->request == NULL)
1609 			continue;
1610 		if (*datalen < handler->len + 2 ||
1611 		    strncasecmp(*dptr, handler->method, handler->len))
1612 			continue;
1613 		if ((*dptr)[handler->len] != ' ' ||
1614 		    !isalpha((*dptr)[handler->len+1]))
1615 			continue;
1616 
1617 		if (ct_sip_get_header(ct, *dptr, 0, *datalen, SIP_HDR_CSEQ,
1618 				      &matchoff, &matchlen) <= 0) {
1619 			nf_ct_helper_log(skb, ct, "cannot parse cseq");
1620 			return NF_DROP;
1621 		}
1622 		cseq = sip_strtouint(*dptr + matchoff, *datalen - matchoff, (char **)&end);
1623 		if (*dptr + matchoff == end) {
1624 			nf_ct_helper_log(skb, ct, "cannot get cseq");
1625 			return NF_DROP;
1626 		}
1627 
1628 		return handler->request(skb, protoff, dataoff, dptr, datalen,
1629 					cseq);
1630 	}
1631 	return NF_ACCEPT;
1632 }
1633 
process_sip_msg(struct sk_buff * skb,struct nf_conn * ct,unsigned int protoff,unsigned int dataoff,const char ** dptr,unsigned int * datalen)1634 static int process_sip_msg(struct sk_buff *skb, struct nf_conn *ct,
1635 			   unsigned int protoff, unsigned int dataoff,
1636 			   const char **dptr, unsigned int *datalen)
1637 {
1638 	const struct nf_nat_sip_hooks *hooks;
1639 	int ret;
1640 
1641 	if (strncasecmp(*dptr, "SIP/2.0 ", strlen("SIP/2.0 ")) != 0)
1642 		ret = process_sip_request(skb, protoff, dataoff, dptr, datalen);
1643 	else
1644 		ret = process_sip_response(skb, protoff, dataoff, dptr, datalen);
1645 
1646 	if (ret == NF_ACCEPT && ct->status & IPS_NAT_MASK) {
1647 		hooks = rcu_dereference(nf_nat_sip_hooks);
1648 		if (hooks && !hooks->msg(skb, protoff, dataoff,
1649 					 dptr, datalen)) {
1650 			nf_ct_helper_log(skb, ct, "cannot NAT SIP message");
1651 			ret = NF_DROP;
1652 		}
1653 	}
1654 
1655 	return ret;
1656 }
1657 
sip_help_tcp(struct sk_buff * skb,unsigned int protoff,struct nf_conn * ct,enum ip_conntrack_info ctinfo)1658 static int sip_help_tcp(struct sk_buff *skb, unsigned int protoff,
1659 			struct nf_conn *ct, enum ip_conntrack_info ctinfo)
1660 {
1661 	struct tcphdr *th, _tcph;
1662 	unsigned int dataoff, datalen;
1663 	unsigned int matchoff, matchlen;
1664 	unsigned int msglen, origlen;
1665 	const char *dptr, *end;
1666 	s16 diff, tdiff = 0;
1667 	int ret = NF_ACCEPT;
1668 	unsigned long clen;
1669 	bool term;
1670 
1671 	if (ctinfo != IP_CT_ESTABLISHED &&
1672 	    ctinfo != IP_CT_ESTABLISHED_REPLY)
1673 		return NF_ACCEPT;
1674 
1675 	/* No Data ? */
1676 	th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
1677 	if (th == NULL)
1678 		return NF_ACCEPT;
1679 	dataoff = protoff + th->doff * 4;
1680 	if (dataoff >= skb->len)
1681 		return NF_ACCEPT;
1682 
1683 	nf_ct_refresh(ct, sip_timeout * HZ);
1684 
1685 	if (unlikely(skb_linearize(skb)))
1686 		return NF_DROP;
1687 
1688 	dptr = skb->data + dataoff;
1689 	datalen = skb->len - dataoff;
1690 	if (datalen < strlen("SIP/2.0 200"))
1691 		return NF_ACCEPT;
1692 
1693 	while (1) {
1694 		if (ct_sip_get_header(ct, dptr, 0, datalen,
1695 				      SIP_HDR_CONTENT_LENGTH,
1696 				      &matchoff, &matchlen) <= 0)
1697 			break;
1698 
1699 		clen = sip_strtouint(dptr + matchoff, datalen - matchoff, (char **)&end);
1700 		if (dptr + matchoff == end)
1701 			break;
1702 
1703 		if (clen > datalen)
1704 			break;
1705 
1706 		term = false;
1707 		for (; end + strlen("\r\n\r\n") <= dptr + datalen; end++) {
1708 			if (end[0] == '\r' && end[1] == '\n' &&
1709 			    end[2] == '\r' && end[3] == '\n') {
1710 				term = true;
1711 				break;
1712 			}
1713 		}
1714 		if (!term)
1715 			break;
1716 		end += strlen("\r\n\r\n") + clen;
1717 
1718 		msglen = origlen = end - dptr;
1719 		if (msglen > datalen)
1720 			return NF_ACCEPT;
1721 
1722 		ret = process_sip_msg(skb, ct, protoff, dataoff,
1723 				      &dptr, &msglen);
1724 		/* process_sip_* functions report why this packet is dropped */
1725 		if (ret != NF_ACCEPT)
1726 			break;
1727 		diff     = msglen - origlen;
1728 		tdiff   += diff;
1729 
1730 		dataoff += msglen;
1731 		dptr    += msglen;
1732 		datalen  = datalen + diff - msglen;
1733 	}
1734 
1735 	if (ret == NF_ACCEPT && ct->status & IPS_NAT_MASK) {
1736 		const struct nf_nat_sip_hooks *hooks;
1737 
1738 		hooks = rcu_dereference(nf_nat_sip_hooks);
1739 		if (hooks)
1740 			hooks->seq_adjust(skb, protoff, tdiff);
1741 	}
1742 
1743 	return ret;
1744 }
1745 
sip_help_udp(struct sk_buff * skb,unsigned int protoff,struct nf_conn * ct,enum ip_conntrack_info ctinfo)1746 static int sip_help_udp(struct sk_buff *skb, unsigned int protoff,
1747 			struct nf_conn *ct, enum ip_conntrack_info ctinfo)
1748 {
1749 	unsigned int dataoff, datalen;
1750 	const char *dptr;
1751 
1752 	/* No Data ? */
1753 	dataoff = protoff + sizeof(struct udphdr);
1754 	if (dataoff >= skb->len)
1755 		return NF_ACCEPT;
1756 
1757 	nf_ct_refresh(ct, sip_timeout * HZ);
1758 
1759 	if (unlikely(skb_linearize(skb)))
1760 		return NF_DROP;
1761 
1762 	dptr = skb->data + dataoff;
1763 	datalen = skb->len - dataoff;
1764 	if (datalen < strlen("SIP/2.0 200"))
1765 		return NF_ACCEPT;
1766 
1767 	return process_sip_msg(skb, ct, protoff, dataoff, &dptr, &datalen);
1768 }
1769 
1770 static struct nf_conntrack_helper sip[MAX_PORTS * 4] __read_mostly;
1771 static struct nf_conntrack_helper *sip_ptr[MAX_PORTS * 4] __read_mostly;
1772 
1773 static const struct nf_conntrack_expect_policy sip_exp_policy[SIP_EXPECT_MAX + 1] = {
1774 	[SIP_EXPECT_SIGNALLING] = {
1775 		.name		= "signalling",
1776 		.max_expected	= 1,
1777 		.timeout	= 3 * 60,
1778 	},
1779 	[SIP_EXPECT_AUDIO] = {
1780 		.name		= "audio",
1781 		.max_expected	= 2 * IP_CT_DIR_MAX,
1782 		.timeout	= 3 * 60,
1783 	},
1784 	[SIP_EXPECT_VIDEO] = {
1785 		.name		= "video",
1786 		.max_expected	= 2 * IP_CT_DIR_MAX,
1787 		.timeout	= 3 * 60,
1788 	},
1789 	[SIP_EXPECT_IMAGE] = {
1790 		.name		= "image",
1791 		.max_expected	= IP_CT_DIR_MAX,
1792 		.timeout	= 3 * 60,
1793 	},
1794 };
1795 
nf_conntrack_sip_fini(void)1796 static void __exit nf_conntrack_sip_fini(void)
1797 {
1798 	nf_conntrack_helpers_unregister(sip_ptr, ports_c * 4);
1799 }
1800 
nf_conntrack_sip_init(void)1801 static int __init nf_conntrack_sip_init(void)
1802 {
1803 	int i, ret;
1804 
1805 	NF_CT_HELPER_BUILD_BUG_ON(sizeof(struct nf_ct_sip_master));
1806 
1807 	if (ports_c == 0)
1808 		ports[ports_c++] = SIP_PORT;
1809 
1810 	for (i = 0; i < ports_c; i++) {
1811 		nf_ct_helper_init(&sip[4 * i], AF_INET, IPPROTO_UDP,
1812 				  HELPER_NAME, SIP_PORT, ports[i], i,
1813 				  sip_exp_policy, SIP_EXPECT_MAX, sip_help_udp,
1814 				  NULL, THIS_MODULE);
1815 		nf_ct_helper_init(&sip[4 * i + 1], AF_INET, IPPROTO_TCP,
1816 				  HELPER_NAME, SIP_PORT, ports[i], i,
1817 				  sip_exp_policy, SIP_EXPECT_MAX, sip_help_tcp,
1818 				  NULL, THIS_MODULE);
1819 		nf_ct_helper_init(&sip[4 * i + 2], AF_INET6, IPPROTO_UDP,
1820 				  HELPER_NAME, SIP_PORT, ports[i], i,
1821 				  sip_exp_policy, SIP_EXPECT_MAX, sip_help_udp,
1822 				  NULL, THIS_MODULE);
1823 		nf_ct_helper_init(&sip[4 * i + 3], AF_INET6, IPPROTO_TCP,
1824 				  HELPER_NAME, SIP_PORT, ports[i], i,
1825 				  sip_exp_policy, SIP_EXPECT_MAX, sip_help_tcp,
1826 				  NULL, THIS_MODULE);
1827 	}
1828 
1829 	ret = nf_conntrack_helpers_register(sip, ports_c * 4, sip_ptr);
1830 	if (ret < 0) {
1831 		pr_err("failed to register helpers\n");
1832 		return ret;
1833 	}
1834 	return 0;
1835 }
1836 
1837 module_init(nf_conntrack_sip_init);
1838 module_exit(nf_conntrack_sip_fini);
1839