Browse Source

- added STUN keep-alive functionality in accordance with draft-ietf-behave-rfc3489bis-04.txt

Vladimir Marek 19 years ago
parent
commit
96227c65df
10 changed files with 1487 additions and 9 deletions
  1. 11 0
      Makefile.defs
  2. 12 1
      cfg.lex
  3. 25 0
      cfg.y
  4. 6 0
      globals.h
  5. 11 0
      main.c
  6. 1080 0
      ser_stun.c
  7. 184 0
      ser_stun.h
  8. 3 1
      tcp_conn.h
  9. 128 1
      tcp_read.c
  10. 27 6
      udp_server.c

+ 11 - 0
Makefile.defs

@@ -351,6 +351,8 @@ endif
 # -DPROFILING
 #		if enabled profiling will be enabled for child processes
 #		Don't forget to set PROFILE (see below)
+# -DUSE_STUN
+#		compiles in stun support
 
 # Sometimes is needes correct non-quoted $OS. HACK: gcc translates known OS to number ('linux'), so there is added underscore
 
@@ -394,6 +396,10 @@ ifneq ($(TLS),)
 	DEFS+= -DUSE_TLS
 endif
 
+ifneq ($(STUN),)
+	DEFS+= -DUSE_STUN
+endif
+
 ifeq ($(mode),)
 	mode = release
 endif
@@ -1388,6 +1394,11 @@ DEFS+= -I$(LOCALBASE)/ssl/include
 LIBS+= -L$(LOCALBASE)/lib -L$(LOCALBASE)/ssl/lib -lssl  -lcrypto
 endif
 
+ifneq ($(STUN),)
+DEFS+= -I$(LOCALBASE)/ssl/include
+LIBS+= -L$(LOCALBASE)/lib -L$(LOCALBASE)/ssl/lib -lcrypto
+endif
+
 ifneq ($(found_lock_method), yes)
 $(warning	No locking method found so far, trying SYS V sems)
 		DEFS+= -DUSE_SYSV_SEM  # try sys v sems

+ 12 - 1
cfg.lex

@@ -60,8 +60,10 @@
  *              to_{ip,port} (andrei)
  *  2005-12-12  separated drop, exit, break, return, added RETCODE (andrei)
  *  2005-12-19  select framework (mma)
- * 2006-09-11  added dns cache (use, flags, ttls, mem ,gc) & dst blacklist
+ *  2006-09-11  added dns cache (use, flags, ttls, mem ,gc) & dst blacklist
  *              options (andrei)
+ *  2006-10-13  added STUN_ALLOW_STUN, STUN_ALLOW_FP, STUN_REFRESH_INTERVAL
+ *              (vlada)
  */
 
 
@@ -289,6 +291,11 @@ MCAST_LOOPBACK		"mcast_loopback"
 MCAST_TTL		"mcast_ttl"
 TOS			"tos"
 
+/* stun config variables */
+STUN_REFRESH_INTERVAL "stun_refresh_interval"
+STUN_ALLOW_STUN "stun_allow_stun"
+STUN_ALLOW_FP "stun_allow_fp"
+
 LOADMODULE	loadmodule
 MODPARAM        modparam
 
@@ -528,6 +535,10 @@ EAT_ABLE	[\ \t\b\r]
 <INITIAL>{LOADMODULE}	{ count(); yylval.strval=yytext; return LOADMODULE; }
 <INITIAL>{MODPARAM}     { count(); yylval.strval=yytext; return MODPARAM; }
 
+<INITIAL>{STUN_REFRESH_INTERVAL} { count(); yylval.strval=yytext; return STUN_REFRESH_INTERVAL;}
+<INITIAL>{STUN_ALLOW_STUN} { count(); yylval.strval=yytext; return STUN_ALLOW_STUN;}
+<INITIAL>{STUN_ALLOW_FP} { count(); yylval.strval=yytext; return STUN_ALLOW_FP;}
+
 <INITIAL>{EQUAL}	{ count(); return EQUAL; }
 <INITIAL>{ADDEQ}          { count(); return ADDEQ; }
 <INITIAL>{EQUAL_T}	{ count(); return EQUAL_T; }

+ 25 - 0
cfg.y

@@ -74,6 +74,8 @@
  * 2006-05-30  avp flags (tma)
  * 2006-09-11  added dns cache (use, flags, ttls, mem ,gc) & dst blacklist
  *              options (andrei)
+ * 2006-10-13  added STUN_ALLOW_STUN, STUN_ALLOW_FP, STUN_REFRESH_INTERVAL
+ *              (vlada)
  */
 
 %{
@@ -335,6 +337,10 @@ static struct socket_id* mk_listen_id(char*, int, int);
 %token ATTR_GLOBAL
 %token ADDEQ
 
+%token STUN_REFRESH_INTERVAL
+%token STUN_ALLOW_STUN
+%token STUN_ALLOW_FP
+
 /* operators */
 %nonassoc EQUAL
 %nonassoc EQUAL_T
@@ -864,6 +870,25 @@ assign_stm:
 	| TOS EQUAL NUMBER { tos=$3; }
 	| TOS EQUAL error { yyerror("number expected"); }
 	| error EQUAL { yyerror("unknown config variable"); }
+	| STUN_REFRESH_INTERVAL EQUAL NUMBER { 
+		#ifdef USE_STUN
+			stun_refresh_interval=$3;
+		#endif
+		}
+	| STUN_REFRESH_INTERVAL EQUAL error{ yyerror("number expected"); }
+	| STUN_ALLOW_STUN EQUAL NUMBER { 
+		#ifdef USE_STUN
+			stun_allow_stun=$3;
+		#endif
+		}
+	| STUN_ALLOW_STUN EQUAL error{ yyerror("number expected"); }
+	| STUN_ALLOW_FP EQUAL NUMBER { 
+		#ifdef USE_STUN
+			stun_allow_fp=$3;
+		#endif
+		}
+	| STUN_ALLOW_FP EQUAL error{ yyerror("number expected"); }
+	| error EQUAL { yyerror("unknown config variable"); }
 	;
 module_stm:
 	LOADMODULE STRING {

+ 6 - 0
globals.h

@@ -114,6 +114,12 @@ extern int mcast_loopback;
 extern int mcast_ttl;
 #endif /* USE_MCAST */
 
+#ifdef USE_STUN
+extern unsigned int stun_refresh_interval;
+extern int stun_allow_stun;
+extern int stun_allow_fp;
+#endif
+
 extern int tos;
 
 /*

+ 11 - 0
main.c

@@ -62,6 +62,8 @@
  *               of them might use it "unset" (andrei)
  *  2005-07-25  use sigaction for setting the signal handlers (andrei)
  *  2006-07-13  added dns cache/failover init. (andrei)
+ *  2006-10-13  added global variables stun_refresh_interval, stun_allow_stun
+ *              and stun_allow_fp (vlada)
  */
 
 
@@ -353,6 +355,15 @@ unsigned short port_no=0; /* default port*/
 unsigned short tls_port_no=0; /* default port */
 #endif
 
+#ifdef USE_STUN
+/* refresh interval in miliseconds */
+unsigned int stun_refresh_interval=0;
+/* stun can be switch off even if it is compiled */
+int stun_allow_stun=1;
+/* use or don't use fingerprint */
+int stun_allow_fp=1;
+#endif
+
 struct host_alias* aliases=0; /* name aliases list */
 
 /* Parameter to child_init */

+ 1080 - 0
ser_stun.c

@@ -0,0 +1,1080 @@
+/*
+ * $Id$
+ *
+ * Copyright (C) 2001-2003 FhG Fokus
+ *
+ * This file is part of ser, a free SIP server.
+ *
+ * ser is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ * For a license to use the ser software under conditions
+ * other than those described here, or to purchase support for this
+ * software, please contact iptel.org by e-mail at the following addresses:
+ *    [email protected]
+ *
+ * ser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License 
+ * along with this program; if not, write to the Free Software 
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * History
+ * --------
+ *  2006-10-13  created (vlada)
+ */
+
+#ifdef USE_STUN 
+ 
+#include <arpa/inet.h>
+#include "ser_stun.h"
+#include "forward.h"
+
+extern unsigned char* SHA1(const unsigned char* d, size_t m,unsigned char* md);
+
+/*
+ * ****************************************************************************
+ *                     Declaration of functions                               *
+ * ****************************************************************************
+ */
+int stun_parse_header(struct stun_msg* req, USHORT_T* error_code);
+int stun_parse_body(
+				struct stun_msg* req,
+				struct stun_unknown_att** unknown,
+				USHORT_T* error_code);
+void stun_delete_unknown_attrs(struct stun_unknown_att* unknown);
+struct stun_unknown_att* stun_alloc_unknown_attr(USHORT_T type);
+int stun_add_address_attr(struct stun_msg* res, 
+						UINT_T		af,
+						USHORT_T	port,
+						UINT_T*		ip_addr,
+						USHORT_T	type,
+						int do_xor);
+int add_unknown_attr(struct stun_msg* res, struct stun_unknown_att* unknown);
+int add_error_code(struct stun_msg* res, USHORT_T error_code);
+int add_fingerprint(struct stun_buffer* msg);
+int copy_str_to_buffer(struct stun_msg* res, const char* data, UINT_T pad);
+int validate_fingerprint(struct stun_msg* req, USHORT_T* error_code);
+int reallock_buffer(struct stun_buffer* buffer, UINT_T len);
+int buf_copy(struct stun_buffer* msg, void* source, UINT_T len);
+void clean_memory(struct stun_msg* req,
+				struct stun_msg* res,	struct stun_unknown_att* unknown);
+int stun_create_response(
+						struct stun_msg* req,
+						struct stun_msg* res,
+						struct receive_info* ri,
+						struct stun_unknown_att* unknown, 
+						UINT_T error_code);
+int stun_add_common_integer_attr(struct stun_msg* res, USHORT_T type, UINT_T value);
+int stun_add_common_text_attr(struct stun_msg* res, USHORT_T type, char* value, 
+							USHORT_T pad);
+
+
+/*
+ * ****************************************************************************
+ *                      Definition of functions                               *
+ * ****************************************************************************
+ */
+ 
+/* 
+ * stun_process_msg(): 
+ * 			buf - incoming message
+ * 			len - length of incoming message
+ * 			ri  - information about socket that received a message and 
+ *                also information about sender (its IP, port, protocol)
+ * 
+ * This function ensures processing of incoming message. It's common for both
+ * TCP and UDP protocol. There is no other function as an interface.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ * 
+ */
+int stun_process_msg(char* buf, unsigned len, struct receive_info* ri)
+{
+	struct stun_msg 			msg_req;
+	struct stun_msg 			msg_res;
+	struct dest_info			dst;
+	struct stun_unknown_att*	unknown;
+	USHORT_T					error_code;
+	int ii;
+	 
+	memset(&msg_req, 0, sizeof(msg_req));
+	memset(&msg_res, 0, sizeof(msg_res));
+	
+	msg_req.msg.buf.s = buf;
+	msg_req.msg.buf.len = len;	
+	unknown = NULL;
+	error_code = RESPONSE_OK;
+	
+	if (stun_parse_header(&msg_req, &error_code) != 0) {
+		goto error;
+	}
+	
+	if (error_code == RESPONSE_OK) {
+		if (stun_parse_body(&msg_req, &unknown, &error_code) != 0) {
+			goto error;
+		}
+	}
+	
+	if (stun_create_response(&msg_req, &msg_res, ri,  
+							unknown, error_code) != 0) {
+		goto error;
+	}
+	
+	init_dst_from_rcv(&dst, ri);
+
+#ifdef EXTRA_DEBUG	
+	struct ip_addr ip;
+	su2ip_addr(&ip, &dst.to);
+	char *ipp = ip_addr2a(&ip);
+	int porttt = su_getport(&dst.to);
+	LOG(L_DBG, "DEBUG: ser_stun: %s:%d):\n", ip_addr2a(&ip), 
+		su_getport(&dst.to));
+#endif
+	
+	/* send STUN response */
+	if (msg_send(&dst, msg_res.msg.buf.s, msg_res.msg.buf.len) != 0) {
+		goto error;
+	}
+	
+	clean_memory(&msg_req, &msg_res, unknown);
+	return 0;
+	
+error:
+	clean_memory(&msg_req, &msg_res, unknown);
+	return FATAL_ERROR;
+}
+
+/*
+ * stun_parse_header():
+ * 			- req: request from host that should be processed
+ * 			- error_code: indication of any protocol error
+ * 
+ * This function ensures parsing of incoming header.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+
+int stun_parse_header(struct stun_msg* req, USHORT_T* error_code)
+{
+	
+	if (sizeof(req->hdr) > req->msg.buf.len) {
+		/* the received message does not contain whole header */
+		LOG(L_INFO, "INFO: incomplete header of STUN message\n");
+		/* Any better solution? IMHO it's not possible to send error response
+		 * because the transaction ID is not available.
+		 */
+		return FATAL_ERROR;
+	}
+	
+	memcpy(&req->hdr, req->msg.buf.s, sizeof(struct stun_hdr));
+	req->hdr.type = ntohs(req->hdr.type);
+	
+	/* the SER supports only Binding Request right now */ 
+	if (req->hdr.type != BINDING_REQUEST) {
+		LOG(L_INFO, "INFO: unsupported type of STUN message: %x\n", 
+					req->hdr.type);
+		/* resending of same message is not welcome */
+		*error_code = GLOBAL_FAILURE_ERR;
+	}
+	
+	req->hdr.len = ntohs(req->hdr.len);
+	
+	/* check if there is correct magic cookie */
+	req->old = (req->hdr.id.magic_cookie == htonl(MAGIC_COOKIE)) ? 0 : 1;
+
+	return 0;
+}
+
+/*
+ * stun_parse_body():
+ * 			- req: request from host that should be processed
+ * 			- unknown: this is a link list header of attributes 
+ * 					   that are unknown to SER; defaul value is NULL
+ * 			- error_code: indication of any protocol error
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+int stun_parse_body(
+				struct stun_msg* req,
+				struct stun_unknown_att** unknown,
+				USHORT_T* error_code)
+{
+	UINT_T not_parsed;
+	struct stun_attr attr;
+	USHORT_T attr_size;
+	UINT_T padded_len;
+	struct stun_unknown_att*	tmp_unknown;
+	struct stun_unknown_att*	body;
+	char*	buf;
+	int		fp_present;
+	
+	attr_size = sizeof(struct stun_attr);
+	buf = &req->msg.buf.s[sizeof(struct stun_hdr)];
+	fp_present = 0;
+	
+	/* 
+	 * the message length is different for rfc and rfc bis 
+	 * the bis version contains fingerprint that is not included in 
+	 * length of body which is listed in header of message
+	 */
+	not_parsed = req->msg.buf.len - sizeof(struct stun_hdr);
+	
+	if (req->old) {
+		if (not_parsed != req->hdr.len) {
+			*error_code = BAD_REQUEST_ERR;
+			return 0;
+		} 
+	}
+	else {
+		if (not_parsed != 
+		    req->hdr.len + SHA_DIGEST_LENGTH + sizeof(struct stun_attr)) {
+			*error_code = BAD_REQUEST_ERR;
+			return 0;
+		}
+	}
+	
+	tmp_unknown = *unknown;
+	body = NULL;
+	
+	while (not_parsed > 0 && *error_code == RESPONSE_OK) {
+		memset(&attr, 0, attr_size);
+		
+		/* check if there are 4 bytes for attribute type and its value */
+		if (not_parsed < 4) {
+			*error_code = BAD_REQUEST_ERR;
+			continue;
+		}
+		
+		memcpy(&attr, buf, attr_size);
+		
+		buf += attr_size;
+		not_parsed -= attr_size;
+		
+		/* check if there is enought unparsed space for attribute's value */
+		if (not_parsed < ntohs(attr.len)) {
+			*error_code = BAD_REQUEST_ERR;
+			continue;
+		}
+		
+		/* check if the attribute is known to the server */
+		switch (htons(attr.type)) {			
+			case REALM_ATTR:
+			case NONCE_ATTR:
+			case MAPPED_ADDRESS_ATTR:
+			case XOR_MAPPED_ADDRESS_ATTR:
+			case ALTERNATE_SERVER_ATTR:
+			case REFRESH_INTERVAL_ATTR:
+			case RESPONSE_ADDRESS_ATTR:
+			case SOURCE_ADDRESS_ATTR:
+			case REFLECTED_FROM_ATTR:		
+			case CHANGE_REQUEST_ATTR:
+			case CHANGED_ADDRESS_ATTR:
+				padded_len = ntohs(attr.len);
+				break;
+			
+			/* following attributes must be padded to 4 bytes */
+			case USERNAME_ATTR:
+			case PASSWORD_ATTR:
+			case ERROR_CODE_ATTR:
+			case UNKNOWN_ATTRIBUTES_ATTR:
+			case SERVER_ATTR:
+				padded_len = PADDED_TO_FOUR(ntohs(attr.len));
+				break;
+
+			/* MESSAGE_INTEGRITY must be padded to sixty four bytes*/
+			case MESSAGE_INTEGRITY_ATTR:
+				padded_len = PADDED_TO_SIXTYFOUR(ntohs(attr.len));
+				break;
+			
+			case FINGERPRINT_ATTR:
+				fp_present = 1;			
+				if (ntohs(attr.len) != SHA_DIGEST_LENGTH) {
+					LOG(L_WARN, 
+						"WARNING: STUN: Incorrect fingerprint of request.\n");
+					*error_code = BAD_REQUEST_ERR;
+					continue;
+				}
+
+				memcpy(req->fp, buf, SHA_DIGEST_LENGTH);
+				if(stun_allow_fp) {
+					if (validate_fingerprint(req, error_code) != 0) {
+						LOG(L_WARN, 
+							"WARNING: STUN: Incorrect fingerprint of request.\n");
+						*error_code = BAD_REQUEST_ERR;
+						continue;
+					}
+				} 
+
+				padded_len = SHA_DIGEST_LENGTH;
+				if (not_parsed > SHA_DIGEST_LENGTH) {
+					/* fingerprint must be last parameter in request */
+					*error_code = BAD_REQUEST_ERR;
+					continue;
+				}
+				break;
+			
+			default:
+				/* 
+				 * the attribute is uknnown to the server
+				 * let see if it's necessary to generate error response 
+				 */
+				if (attr.type <= htons(MANDATORY_ATTR)) {
+					tmp_unknown = stun_alloc_unknown_attr(attr.type);
+					if (tmp_unknown == NULL) {
+						return FATAL_ERROR;
+					}
+					if (*unknown == NULL) {
+						*unknown = body = tmp_unknown;
+					}
+					else { 
+						body->next = tmp_unknown;
+						body = body->next;
+					}
+				}
+				padded_len = ntohs(attr.len);
+				break;
+		}
+		buf += padded_len;
+		not_parsed -= padded_len;
+	}  /* while */
+	
+	/*
+	 * The unknown attribute error code must set after parsing of whole body
+	 * because it's necessary to obtain all of unknown attributes! 
+	 */
+	if (*error_code == RESPONSE_OK && *unknown != NULL) {
+		*error_code = UNKNOWN_ATTRIBUTE_ERR;
+	} 
+	
+	if (fp_present == 0 && req->old == 0) {
+		/* missing mandatory attribute fingerprint */
+		*error_code = BAD_REQUEST_ERR;
+	}
+	
+	return 0;
+}
+
+/*
+ * stun_create_response():
+ * 			- req: original request from host
+ * 			- res: this will represent response to host
+ * 			- ri: information about request, necessary because of IP 
+ * 				  address and port 
+ *			- unknown: link list of unknown attributes
+ * 			- error_code: indication of any protocol error
+ * 
+ * The function stun_create_response ensures creating response to a host.
+ * The type of response depends on value of error_code parameter.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory  
+ */
+
+int stun_create_response(
+						struct stun_msg* req,
+						struct stun_msg* res,
+						struct receive_info* ri,
+						struct stun_unknown_att* unknown, 
+						UINT_T error_code)
+{
+	/*
+	 * Alloc some space for response.
+	 * Optimalization? - maybe it would be better to use biggish static array.
+	 */
+	res->msg.buf.s = (char *) pkg_malloc(sizeof(char)*STUN_MSG_LEN);
+	if (res->msg.buf.s == NULL) {
+		LOG(L_ERR, "ERROR: STUN: out of memory\n");
+		return FATAL_ERROR;
+	}
+	
+	memset(res->msg.buf.s, 0, sizeof(char)*STUN_MSG_LEN); 
+	res->msg.buf.len = 0;
+	res->msg.empty = STUN_MSG_LEN;
+	
+	/* use magic cookie and transaction ID from request */
+	memcpy(&res->hdr.id, &req->hdr.id, sizeof(struct transaction_id));
+	/* the correct body length will be added ASAP it will be known */ 
+	res->hdr.len = htons(0);
+	
+	if (error_code == RESPONSE_OK) {
+		res->hdr.type = htons(BINDING_RESPONSE);
+		
+		/* copy header into msg buffer */
+		if (buf_copy(&res->msg, (void *) &res->hdr, 
+					sizeof(struct stun_hdr)) != 0) {
+			return FATAL_ERROR;
+		}
+
+		/* 
+		 * If the SER received message in old format, then the body will 
+		 * contain MAPPED-ADDRESS attribute instead of XOR-MAPPED-ADDRESS
+		 * attribute.
+		 */		
+		if (req->old == 0) {
+			if (stun_add_address_attr(res, ri->src_ip.af, ri->src_port, 
+						  ri->src_ip.u.addr32, XOR_MAPPED_ADDRESS_ATTR, 
+						  XOR) != 0) {
+				return FATAL_ERROR;
+			}
+			
+			if (stun_add_common_integer_attr(res, REFRESH_INTERVAL_ATTR, 
+						stun_refresh_interval) != 0) {
+				return FATAL_ERROR;
+			}
+		}
+		else {
+			if (stun_add_address_attr(res, ri->src_ip.af, ri->src_port, 
+						ri->src_ip.u.addr32, MAPPED_ADDRESS_ATTR, !XOR) != 0) {
+				return FATAL_ERROR;
+			}
+		}
+	}
+	else {
+		res->hdr.type = htons(BINDING_ERROR_RESPONSE);
+		
+		if (buf_copy(&res->msg, (void *) &res->hdr, 
+								sizeof(struct stun_hdr)) != 0) {
+			return FATAL_ERROR;
+		}
+		
+		if (add_error_code(res, error_code) != 0) {
+			return FATAL_ERROR;
+		}
+		
+		if (unknown != NULL) {
+			if (add_unknown_attr(res, unknown) != 0) {
+				return FATAL_ERROR;
+			}
+		} 
+	}
+	
+	/* count length of body except header and fingerprint
+	 * and copy message length at the beginning of buffer
+	 */
+	res->hdr.len = htons(res->msg.buf.len - sizeof(struct stun_hdr));
+	memcpy(&res->msg.buf.s[sizeof(USHORT_T)], (void *) &res->hdr.len,
+		sizeof(USHORT_T));
+	
+	if (req->old == 0) {
+		/* add optional information about server */
+		if (stun_add_common_text_attr(res, SERVER_ATTR, SERVER_HDR, PAD4)!=0) {
+			return FATAL_ERROR;
+		}
+		
+		if (stun_allow_fp) {	
+			if (add_fingerprint(&res->msg) != 0) {
+				return FATAL_ERROR;
+			}
+		}
+	}
+	
+	return 0;
+}
+
+/*
+ * add_unknown_attr()
+ * 			- res: response representation
+ * 			- unknown: link list of unknown attributes
+ * 
+ * The function add_unknown_attr ensures copy of link list of unknown 
+ * attributes into response buffer.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ * 
+ */
+int add_unknown_attr(struct stun_msg* res, struct stun_unknown_att* unknown)
+{
+	struct stun_attr attr;
+	struct stun_unknown_att* tmp_unknown;
+	UINT_T		counter;
+	USHORT_T	orig_len;
+
+	counter = 0;
+	orig_len = res->msg.buf.len;
+	tmp_unknown = unknown;
+	
+	attr.type = htons(UNKNOWN_ATTRIBUTES_ATTR);
+	attr.len = htons(0);
+	
+	if (buf_copy(&res->msg, (void *) &attr, sizeof(struct stun_attr)) != 0) {
+		return FATAL_ERROR;
+	}
+	
+	while (tmp_unknown != NULL) {
+		if (buf_copy(&res->msg, (void *)&tmp_unknown->type, 
+								sizeof(USHORT_T)) != 0) {
+			return FATAL_ERROR;
+		}
+		tmp_unknown = tmp_unknown->next;
+		++counter;
+	}
+	
+	attr.len = htons(res->msg.buf.len - orig_len);
+	memcpy(&res->msg.buf.s[orig_len], (void *)&attr, sizeof(struct stun_attr));
+	
+	/* check if there is an odd number of unknown attributes and if yes, 
+	 * repeat one of them because of padding to 32
+	 */
+	if (counter/2 != 0 && unknown != NULL) {
+		if (buf_copy(&res->msg, (void *)&unknown->type, sizeof(USHORT_T))!=0) {
+			return FATAL_ERROR;
+		}
+	}	
+	
+	return 0;
+}
+
+/*
+ * add_error_code()
+ * 			- res: response representation
+ * 			- error_code: value of error type
+ * 
+ * The function add_error_code ensures copy of link list of unknown 
+ * attributes into response buffer.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+int add_error_code(struct stun_msg* res, USHORT_T error_code)
+{
+	struct stun_attr attr;
+	USHORT_T	orig_len;
+	USHORT_T	two_bytes;
+	int			text_pad;
+	char		err[2];
+	
+	orig_len = res->msg.buf.len;
+	text_pad = 0;
+	
+	/* the type and length will be copy as last one because of unknown length*/
+	if (res->msg.buf.len < sizeof(struct stun_attr)) {
+		if (reallock_buffer(&res->msg, sizeof(struct stun_attr)) != 0) {
+			return FATAL_ERROR;
+		}
+	}
+	res->msg.buf.len += sizeof(struct stun_attr);
+	res->msg.empty -= sizeof(struct stun_attr);
+	
+	/* first two bytes are empty */
+	two_bytes = 0x0000;
+	
+	if (buf_copy(&res->msg, (void *) &two_bytes, sizeof(USHORT_T)) != 0) {
+		return FATAL_ERROR;
+	}
+	
+	err[0] = error_code / 100;
+	err[1] = error_code % 100;
+	if (buf_copy(&res->msg, (void *) err, sizeof(UCHAR_T)*2) != 0) {
+		return FATAL_ERROR;
+	}
+	
+	switch (error_code) {
+		case TRY_ALTERNATE_ERR:
+			text_pad = copy_str_to_buffer(res, TRY_ALTERNATE_TXT, PAD4); 
+			break;
+		case BAD_REQUEST_ERR:
+			text_pad = copy_str_to_buffer(res, BAD_REQUEST_TXT, PAD4); 
+			break;
+		case UNAUTHORIZED_ERR:
+			text_pad = copy_str_to_buffer(res, UNAUTHORIZED_TXT, PAD4); 
+			break;
+		case UNKNOWN_ATTRIBUTE_ERR:
+			text_pad = copy_str_to_buffer(res, UNKNOWN_ATTRIBUTE_TXT, PAD4);
+			break;
+		case STALE_CREDENTIALS_ERR:
+			text_pad = copy_str_to_buffer(res, STALE_CREDENTIALS_TXT, PAD4); 
+			break;
+		case INTEGRITY_CHECK_ERR:
+			text_pad = copy_str_to_buffer(res, INTEGRITY_CHECK_TXT, PAD4); 
+			break;
+		case MISSING_USERNAME_ERR:
+			text_pad = copy_str_to_buffer(res, MISSING_USERNAME_TXT, PAD4); 
+			break;
+		case USE_TLS_ERR:
+			text_pad = copy_str_to_buffer(res, USE_TLS_TXT, PAD4); 
+			break;
+		case MISSING_REALM_ERR:
+			text_pad = copy_str_to_buffer(res, MISSING_REALM_TXT, PAD4); 
+			break;
+		case MISSING_NONCE_ERR:
+			text_pad = copy_str_to_buffer(res, MISSING_NONCE_TXT, PAD4); 
+			break;
+		case UNKNOWN_USERNAME_ERR:
+			text_pad = copy_str_to_buffer(res, UNKNOWN_USERNAME_TXT, PAD4); 
+			break;
+		case STALE_NONCE_ERR:
+			text_pad = copy_str_to_buffer(res, STALE_NONCE_TXT, PAD4);
+			break;
+		case SERVER_ERROR_ERR:
+			text_pad = copy_str_to_buffer(res, SERVER_ERROR_TXT, PAD4); 
+			break;
+		case GLOBAL_FAILURE_ERR:
+			text_pad = copy_str_to_buffer(res, GLOBAL_FAILURE_TXT, PAD4); 
+			break;
+		default:
+			LOG(L_ERR, "ERROR: STUN: Unknown error code.\n");
+			break;
+	}
+	if (text_pad < 0) {
+		goto error;
+	}
+	attr.type = htons(ERROR_CODE_ATTR);
+	/* count length of "value" field -> without type and lehgth field */
+	attr.len = htons(res->msg.buf.len - orig_len - 
+					 text_pad - sizeof(struct stun_attr));
+	memcpy(&res->msg.buf.s[orig_len], (void *)&attr, sizeof(struct stun_attr));
+	
+	return 0;
+
+error:
+	return FATAL_ERROR;
+}
+
+/*
+ * copy_str_to_buffer()
+ * 			- res: response representation
+ * 			- data: text data, in our case almost text representation of error
+ * 			- pad: the size of pad (for how much bytes the string should be 
+ * 				   padded
+ * 
+ * The function copy_str_to_buffer ensures copy of text buffer into response
+ * buffer.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+int copy_str_to_buffer(struct stun_msg* res, const char* data, UINT_T pad)
+{
+	USHORT_T	pad_len;
+	UINT_T		data_len;
+	UCHAR_T		empty[pad];
+	
+	data_len = strlen(data);
+	memset(&empty, 0, pad);
+	
+	pad_len = pad - data_len%pad;
+	
+	if (buf_copy(&res->msg, (void *) data, sizeof(UCHAR_T)*data_len) != 0) {
+		return FATAL_ERROR;
+	}
+	
+	if (pad_len != 0) {
+		if (buf_copy(&res->msg, &empty, pad_len) != 0) {
+			return FATAL_ERROR;
+		}	
+	}
+
+	return pad_len;	
+}
+
+/*
+ * stun_add_address_attr()
+ * 			- res: response representation
+ * 			- af: address family
+ * 			- port: port
+ * 			- ip_addr: represent both IPv4 and IPv6, the differences is in 
+ * 			length  
+ * 			- type: type of attribute
+ * 			- do_xor: if the port should be XOR-ed or not.
+ * 
+ * The function stun_add_address_attr ensures copy of any IP attribute into
+ * response buffer.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+int stun_add_address_attr(struct stun_msg* res, 
+						UINT_T		af,
+						USHORT_T	port,
+						UINT_T*		ip_addr,
+						USHORT_T	type,
+						int do_xor)
+{
+	struct stun_attr attr;
+	UINT_T	 id[IP_ADDR];
+	int		 ip_struct_len;
+	int i;
+	
+	ip_struct_len = 0;
+	attr.type = htons(type);
+	res->ip_addr.port = (do_xor) ? htons(port) ^ MAGIC_COOKIE_2B : htons(port);
+	switch(af) {
+		case AF_INET:
+			ip_struct_len = sizeof(struct stun_ip_addr) - 3*sizeof(UINT_T);
+			res->ip_addr.family = htons(IPV4_FAMILY);
+			memcpy(res->ip_addr.ip, ip_addr, IPV4_LEN);
+			res->ip_addr.ip[0] = (do_xor) ? 
+					res->ip_addr.ip[0] ^ MAGIC_COOKIE : res->ip_addr.ip[0];		
+			break;
+#ifdef USE_IPV6
+		case AF_INET6:
+			ip_struct_len = sizeof(struct stun_ip_addr);
+			res->ip_addr.family = htons(IPV6_FAMILY);
+			memcpy(&res->ip_addr.ip, ip_addr, IPV6_LEN);
+			memcpy(id, &res->hdr.id, sizeof(struct transaction_id));
+			for (i=0; i<IP_ADDR; i++) {
+				res->ip_addr.ip[i] = (do_xor) ? 
+							res->ip_addr.ip[i] ^ id[i] : res->ip_addr.ip[i];
+			}
+			break;
+#endif /* USE_IPV6 */ 
+		default:
+			break;
+	}
+	
+	attr.len = htons(ip_struct_len);
+	
+	/* copy type and attribute's length */ 
+	if (buf_copy(&res->msg, (void *) &attr, sizeof(struct stun_attr)) != 0) {
+		return FATAL_ERROR;
+	}
+	
+	/* copy family, port and IP */
+	if (buf_copy(&res->msg, (void *) &res->ip_addr, ip_struct_len) != 0) {
+		return FATAL_ERROR;
+	}
+
+	return 0;
+}
+
+/*
+ * add_fingerprint()
+ * 			- msg: response buffer
+ * 
+ * The function add_fingerprint ensures adding fingerprint attribute into
+ * response buffer.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+int add_fingerprint(struct stun_buffer* msg)
+{
+	struct stun_attr attr;
+	USHORT_T attr_type_size;
+	
+	attr_type_size = sizeof(struct stun_attr);
+	attr.type = htons(FINGERPRINT_ATTR);
+	attr.len = htons(SHA_DIGEST_LENGTH);
+	
+	if (msg->empty < (SHA_DIGEST_LENGTH + attr_type_size)) {
+		if (reallock_buffer(msg, SHA_DIGEST_LENGTH + attr_type_size) != 0) {
+			return FATAL_ERROR;
+		}
+	}
+	
+	memcpy(&msg->buf.s[msg->buf.len], (void *) &attr, attr_type_size);	
+	msg->buf.len += attr_type_size;
+	msg->empty -= attr_type_size;
+	
+	if (SHA1((UCHAR_T *)msg->buf.s, msg->buf.len-attr_type_size, 
+			 (UCHAR_T *) &msg->buf.s[msg->buf.len]) == 0) {
+		LOG(L_ERR, "ERROR: STUN: SHA-1 algorithm failed.\n");
+		return FATAL_ERROR;
+	}
+	
+	msg->buf.len += SHA_DIGEST_LENGTH;
+	msg->empty -= SHA_DIGEST_LENGTH;
+	
+	return 0;
+}
+
+/*
+ * stun_alloc_unknown_attr()
+ * 			- type: type of unknown attribute
+ * 
+ * The function stun_alloc_unknown_attr ensures allocationg new element for
+ * the link list of unknown attributes.
+ * 
+ * Return value: pointer to new element of link list in positive case
+ * 				 NULL if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+struct stun_unknown_att* stun_alloc_unknown_attr(USHORT_T type)
+{
+	struct stun_unknown_att* attr;
+
+	attr = (struct stun_unknown_att *) pkg_malloc(sizeof(struct stun_unknown_att));
+	if (attr == NULL) {
+		LOG(L_ERR, "ERROR: STUN: out of memory\n");
+		return NULL;
+	}
+	
+	attr->type = type;
+	attr->next = NULL;
+	
+	return attr;
+}
+
+/*
+ * stun_delete_unknown_attrs()
+ * 			- unknown: link list of unknown attributes
+ * 
+ * The function stun_delete_unknown_attrs ensures deleting of link list
+ * 
+ * Return value: none
+ */
+void stun_delete_unknown_attrs(struct stun_unknown_att* unknown)
+{
+	struct stun_unknown_att* tmp_unknown;
+	
+	if (unknown == NULL) {
+		return;
+	}
+	
+	while(unknown->next) {
+		tmp_unknown = unknown->next;
+		unknown->next = tmp_unknown->next;
+		pkg_free(tmp_unknown);		
+	}
+	pkg_free(unknown);
+}
+
+/*
+ * validate_fingerprint()
+ * 			- req: structure representing request message
+ * 			- error_code: indication of any protocol error
+ * 
+ * The function validate_fingerprint ensures validation of FINGERPRINT
+ * attribute.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+int validate_fingerprint(struct stun_msg* req, USHORT_T* error_code)
+{
+	UCHAR_T	msg_digest[SHA_DIGEST_LENGTH];
+	UINT_T	buf_len; 
+	
+	buf_len = req->hdr.len+sizeof(struct stun_hdr);
+	
+	if (SHA1((UCHAR_T *) req->msg.buf.s, buf_len, msg_digest) == 0) {
+		LOG(L_ERR, "ERROR: STUN: SHA-1 algorithm failed.\n");
+		return FATAL_ERROR;
+	} 
+	
+	if (memcmp((void *)req->fp, (void *)&msg_digest, SHA_DIGEST_LENGTH) != 0) {
+		*error_code = BAD_REQUEST_ERR;
+	}
+	
+	return 0;	
+}
+
+/*
+ * buf_copy()
+ * 			- msg: buffer where the data will be copy to
+ * 			- source: source data buffer
+ * 			- len: number of bytes that should be copied
+ * 
+ * The function buf_copy copies "len" bytes from source into msg buffer
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+int buf_copy(struct stun_buffer* msg, void* source, UINT_T len)
+{
+	if (msg->empty < len) {
+		if (reallock_buffer(msg, len) != 0) {
+			return FATAL_ERROR;
+		}
+	}
+	
+	memcpy(&msg->buf.s[msg->buf.len], source, len);
+	msg->buf.len += len;
+	msg->empty -= len;
+	
+	return 0;
+}
+
+/*
+ * reallock_buffer()
+ * 			- buffer: original buffer
+ * 			- len: represents minimum of bytes that must be available after 
+ * 					reallocation
+ * 
+ * The function reallock_buffer reallocks buffer. New buffer's length will be 
+ * original length plus bigger from len and STUN_MSG_LEN constant.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+int reallock_buffer(struct stun_buffer* buffer, UINT_T len)
+{
+	char*	tmp_buf;
+	UINT_T	new_len;
+	
+	new_len = (STUN_MSG_LEN < len) ? STUN_MSG_LEN+len : STUN_MSG_LEN;
+	
+	tmp_buf = (char *) pkg_realloc(buffer->buf.s, 
+								   buffer->buf.len + buffer->empty + new_len);
+	if (tmp_buf == 0) {
+		LOG(L_ERR, "ERROR: STUN: out of memory\n");
+		return FATAL_ERROR;
+	}
+	
+	buffer->buf.s = tmp_buf;
+	buffer->empty += new_len;
+
+	return 0;
+}
+
+/*
+ * clean_memory()
+ * 			- res: structure representing response message
+ * 			- unknown: link list of unknown attributes
+ * 
+ * The function clean_memory should free dynamic allocated memory.
+ * 
+ * Return value: none
+ */
+void clean_memory(struct stun_msg* req,
+				struct stun_msg* res,	struct stun_unknown_att* unknown)
+{
+#ifdef DYN_BUF
+	pkg_free(req->msg.buf.s);
+#endif
+
+	if (res->msg.buf.s != NULL) {
+		pkg_free(res->msg.buf.s);
+	}
+	stun_delete_unknown_attrs(unknown);
+}
+
+/*
+ * stun_add_common_integer_attr()
+ * 			- res: structure representing response
+ * 			- type: type of attribute
+ * 			- value: attribute's value
+ * 
+ * The function stun_add_common_integer_attr copy attribute with integer value 
+ * into response buffer.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+int stun_add_common_integer_attr(struct stun_msg* res, 
+								 USHORT_T type, 
+								 UINT_T value)
+{
+	struct stun_attr attr;
+	
+	attr.type = htons(type);
+	attr.len = htons(sizeof(UINT_T));
+	
+	if (buf_copy(&res->msg, (void *) &attr, sizeof(struct stun_attr)) != 0) {
+		return FATAL_ERROR;
+	}
+	
+	value = htonl(value);
+	if (buf_copy(&res->msg, (void *) &value, sizeof(UINT_T)) != 0) {
+		return FATAL_ERROR;
+	}
+	
+	return 0;
+}
+
+/*
+ * stun_add_common_text_attr()
+ * 			- res: structure representing response
+ * 			- type: type of attribute
+ * 			- value: attribute's value
+ * 			- pad: size of pad
+ * 
+ * The function stun_add_common_text_attr copy attribute with string value 
+ * into response buffer.
+ * 
+ * Return value:	0	if there is no environment error
+ * 					-1	if there is some enviroment error such as insufficiency
+ * 						of memory
+ */
+int stun_add_common_text_attr(struct stun_msg* res, 
+							  USHORT_T type, 
+							  char* value, 
+							  USHORT_T pad)
+{
+	struct stun_attr attr;
+	
+	if (value == NULL) {
+		LOG(L_INFO, "INFO: stun_add_common_text_attr: value is NULL\n");
+		return 0;
+	}
+	
+	attr.type = htons(type);
+	attr.len = htons(strlen(value));
+	
+	if (buf_copy(&res->msg, (void *) &attr, sizeof(struct stun_attr)) != 0) {
+		return FATAL_ERROR;
+	}
+	
+	if (copy_str_to_buffer(res, value, pad) < 0) {
+		return FATAL_ERROR;
+	}
+	
+	return 0;
+	
+}
+
+#endif  /* USE_STUN */
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+ 184 - 0
ser_stun.h

@@ -0,0 +1,184 @@
+/*
+ * $Id$
+ *
+ * Copyright (C) 2001-2003 FhG Fokus
+ *
+ * This file is part of ser, a free SIP server.
+ *
+ * ser is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version
+ *
+ * For a license to use the ser software under conditions
+ * other than those described here, or to purchase support for this
+ * software, please contact iptel.org by e-mail at the following addresses:
+ *    [email protected]
+ *
+ * ser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ *
+ * History:
+ * --------
+ *  2006-10-13  created (vlada)
+ */
+
+
+#ifndef _ser_stun_h
+#define _ser_stun_h
+
+#ifdef USE_STUN
+
+#include <openssl/sha.h>
+
+#include "str.h"
+#include "tcp_conn.h"
+#include "ip_addr.h"
+
+/* type redefinition */
+typedef unsigned char	UCHAR_T;
+typedef unsigned short USHORT_T;
+typedef unsigned int	UINT_T;
+typedef unsigned long	ULONG_T;
+
+/* STUN message types supported by SER */
+#define BINDING_REQUEST			0x0001
+#define BINDING_RESPONSE		0x0101
+#define BINDING_ERROR_RESPONSE	0x0111
+
+/* common STUN attributes */
+#define MAPPED_ADDRESS_ATTR		0x0001
+#define USERNAME_ATTR			0x0006
+#define PASSWORD_ATTR			0x0007
+#define MESSAGE_INTEGRITY_ATTR	0x0008
+#define ERROR_CODE_ATTR			0x0009
+#define UNKNOWN_ATTRIBUTES_ATTR	0x000A
+
+/* STUN attributes defined by rfc3489bis */
+#define REALM_ATTR				0x0014
+#define NONCE_ATTR				0x0015
+#define XOR_MAPPED_ADDRESS_ATTR	0x0020 
+#define FINGERPRINT_ATTR		0x0023
+#define SERVER_ATTR				0x8022
+#define ALTERNATE_SERVER_ATTR	0x8023
+#define REFRESH_INTERVAL_ATTR	0x8024
+
+/* STUN attributes defined by rfc3489 */
+#define RESPONSE_ADDRESS_ATTR	0x0002
+#define CHANGE_REQUEST_ATTR		0x0003
+#define SOURCE_ADDRESS_ATTR		0x0004
+#define CHANGED_ADDRESS_ATTR	0x0005
+#define REFLECTED_FROM_ATTR		0x000b
+
+/* STUN error codes supported by SER */
+#define RESPONSE_OK				200
+#define TRY_ALTERNATE_ERR		300
+#define BAD_REQUEST_ERR			400
+#define UNAUTHORIZED_ERR		401
+#define UNKNOWN_ATTRIBUTE_ERR	420
+#define STALE_CREDENTIALS_ERR	430
+#define INTEGRITY_CHECK_ERR		431
+#define MISSING_USERNAME_ERR	432
+#define USE_TLS_ERR				433
+#define MISSING_REALM_ERR		434
+#define MISSING_NONCE_ERR		435
+#define UNKNOWN_USERNAME_ERR	436
+#define STALE_NONCE_ERR			438
+#define SERVER_ERROR_ERR		500
+#define GLOBAL_FAILURE_ERR		600
+
+#define TRY_ALTERNATE_TXT 		"The client should contact an alternate server for this request."
+#define BAD_REQUEST_TXT			"The request was malformed. The client should not retry the request without modification from the previous attempt."
+#define UNAUTHORIZED_TXT		"The request did not contain a MESSAGE-INTEGRITY attribute."
+#define UNKNOWN_ATTRIBUTE_TXT	"The server did not understand a mandatory attribute in the request."
+#define STALE_CREDENTIALS_TXT	"The request did contain a MESSAGE-INTEGRITY attribute, but it used a shared secret that has expired. The client should obtain a new shared secret and try again."
+#define INTEGRITY_CHECK_TXT		"The request contained a MESSAGE-INTEGRITY attribute, but the HMAC failed verification. This could be a sign of a potential attack, or client implementation error."
+#define MISSING_USERNAME_TXT	"The request contained a MESSAGE-INTEGRITY attribute, but not a USERNAME attribute.  Both USERNAME and MESSAGE-INTEGRITY must be present for integrity checks."
+#define USE_TLS_TXT				"The Shared Secret request has to be sent over TLS, but was not received over TLS."
+#define MISSING_REALM_TXT		"The REALM attribute was not present in the request."
+#define MISSING_NONCE_TXT		"The NONCE attribute was not present in the request."
+#define UNKNOWN_USERNAME_TXT	"The USERNAME supplied in the request is not known or is not known to the server."
+#define STALE_NONCE_TXT			"The NONCE attribute was present in the request but wasn't valid."
+#define SERVER_ERROR_TXT		"The server has suffered a temporary error. The client should try again."
+#define GLOBAL_FAILURE_TXT		"The server is refusing to fulfill the request. The client should not retry."
+
+
+/* other stuff */
+#define MAGIC_COOKIE	0x2112A442
+#define MAGIC_COOKIE_2B 0x2112	/* because of XOR for port */
+#define MANDATORY_ATTR	0x7fff
+#define PAD4			4
+#define PAD64			64
+#define STUN_MSG_LEN	516
+#define IPV4_LEN		4
+#define IPV6_LEN		16
+#define IPV4_FAMILY		0x0001
+#define IPV6_FAMILY		0x0002
+#define	FATAL_ERROR		-1
+#define IP_ADDR			4
+#define XOR				1
+#define TRANSACTION_ID	12
+
+#define PADDED_TO_FOUR(len) (len == 0) ? 0 : len + (PAD4 - len%PAD4)
+#define PADDED_TO_SIXTYFOUR(len) (len == 0) ? 0 : len + (PAD64 - len%PAD64)
+
+struct transaction_id {
+	UINT_T	magic_cookie;
+	UCHAR_T	id[TRANSACTION_ID];
+};
+
+struct stun_hdr {
+	USHORT_T				type;
+	USHORT_T				len;
+	struct transaction_id	id;
+};
+
+struct stun_ip_addr {
+	USHORT_T	family; /* 0x01: IPv4; 0x02: IPv6 */
+	USHORT_T	port;
+	UINT_T		ip[IP_ADDR];
+};
+
+struct stun_buffer {
+	str			buf;
+	USHORT_T	empty;	/* number of free bytes in buf before 
+						 * it'll be necessary to realloc the buf 
+						 */
+};
+
+struct stun_unknown_att {
+	USHORT_T					type;
+	struct stun_unknown_att*	next;
+};
+
+struct stun_attr {
+	USHORT_T	type;
+	USHORT_T	len;
+};
+
+struct stun_msg {
+	struct stun_hdr			hdr;
+	struct stun_ip_addr		ip_addr;		/* XOR values for rfc3489bis, 
+											normal values for rfc3489 */
+	char					fp[SHA_DIGEST_LENGTH];		/* fingerprint value */
+	struct stun_buffer		msg;
+	UCHAR_T					old;		/* true: the format of message is in 
+										accordance with rfc3489 */ 
+};
+
+
+/*
+ * stun functions called from ser
+ */
+int stun_process_msg(char* buf, unsigned len, struct receive_info* ri);
+
+#endif /* USE_STUN */
+
+#endif  /* _ser_stun_h */

+ 3 - 1
tcp_conn.h

@@ -30,6 +30,7 @@
  *  2003-01-29  tcp buffer size ++-ed to allow for 0-terminator
  *  2003-06-30  added tcp_connection flags & state (andrei) 
  *  2003-10-27  tcp port aliases support added (andrei)
+ *  2006-10-13  added tcp_req_states for STUN (vlada)
  */
 
 
@@ -67,7 +68,8 @@ enum tcp_req_states {	H_SKIP_EMPTY, H_SKIP, H_LF, H_LFCR,  H_BODY, H_STARTWS,
 		H_CONT_LEN1, H_CONT_LEN2, H_CONT_LEN3, H_CONT_LEN4, H_CONT_LEN5,
 		H_CONT_LEN6, H_CONT_LEN7, H_CONT_LEN8, H_CONT_LEN9, H_CONT_LEN10,
 		H_CONT_LEN11, H_CONT_LEN12, H_CONT_LEN13, H_L_COLON, 
-		H_CONT_LEN_BODY, H_CONT_LEN_BODY_PARSE 
+		H_CONT_LEN_BODY, H_CONT_LEN_BODY_PARSE,
+		H_STUN_MSG, H_STUN_READ_BODY, H_STUN_FP, H_STUN_END 
 	};
 
 enum tcp_conn_states { S_CONN_ERROR=-2, S_CONN_BAD=-1, S_CONN_OK=0, 

+ 128 - 1
tcp_read.c

@@ -35,6 +35,7 @@
  * 2003-07-04  fixed tcp EOF handling (possible infinite loop) (andrei)
  * 2005-07-05  migrated to the new io_wait code (andrei)
  * 2006-02-03  use tsend_stream instead of send_all (andrei)
+ * 2006-10-13  added STUN support - state machine for TCP (vlada)
  */
 
 #ifdef USE_TCP
@@ -69,6 +70,13 @@
 #include <fcntl.h> /* must be included after io_wait.h if SIGIO_RT is used */
 #include "tsend.h"
 
+#ifdef USE_STUN
+#include "ser_stun.h"
+
+int is_msg_complete(struct tcp_req* r);
+
+#endif /* USE_STUN */
+
 /* types used in io_wait* */
 enum fd_types { F_NONE, F_TCPMAIN, F_TCPCONN };
 
@@ -138,6 +146,11 @@ int tcp_read_headers(struct tcp_connection *c)
 	char *p;
 	struct tcp_req* r;
 	
+#ifdef USE_STUN
+	unsigned int mc;   /* magic cookie */
+	unsigned short body_len;
+#endif
+	
 	#define crlf_default_skip_case \
 					case '\n': \
 						r->state=H_LF; \
@@ -296,11 +309,98 @@ int tcp_read_headers(struct tcp_connection *c)
 						r->start=p;
 						break;
 					default:
+#ifdef USE_STUN
+						/* STUN support can be switched off even if it's compiled */
+						/* stun test */						
+						if (stun_allow_stun && (unsigned char)*p == 0x00) {
+							r->state=H_STUN_MSG;
+						/* body will used as pointer to the last used byte */
+							r->body=p;
+							body_len = 0;
+							DBG("stun msg detected\n");
+						}else
+#endif
 						r->state=H_SKIP;
 						r->start=p;
 				};
 				p++;
 				break;
+#ifdef USE_STUN
+			case H_STUN_MSG:
+				if ((r->pos - r->body) >= sizeof(struct stun_hdr)) {
+					r->content_len = 0;
+					/* copy second short from buffer where should be body 
+					 * length 
+					 */
+					memcpy(&body_len, &r->start[sizeof(unsigned short)], 
+						sizeof(unsigned short));
+					
+					body_len = ntohs(r->content_len);
+					
+					/* check if there is valid magic cookie */
+					memcpy(&mc, &r->start[sizeof(unsigned int)], 
+						sizeof(unsigned int));
+					mc = ntohl(mc);
+					/* using has_content_len as a flag if there should be
+					 * fingerprint or no
+					 */
+					r->has_content_len = (mc == MAGIC_COOKIE) ? 1 : 0;
+					
+					r->body += sizeof(struct stun_hdr);
+					p = r->body; 
+					
+					if (body_len > 0) {
+						r->state = H_STUN_READ_BODY;
+					}
+					else {
+						if (is_msg_complete(r) != 0) {
+							goto skip;
+						}
+						else {
+							/* set content_len to length of fingerprint */
+							body_len = sizeof(struct stun_attr) + 
+									   SHA_DIGEST_LENGTH;
+						}
+					}
+				}
+				else {
+					p = r->pos; 
+				}
+				break;
+				
+			case H_STUN_READ_BODY:
+				/* check if the whole body was read */
+				if ((r->pos - r->body) >= body_len) {
+					r->body += body_len;
+					p = r->body;
+					if (is_msg_complete(r) != 0) {
+						goto skip;
+					}
+					else {
+						/* set content_len to length of fingerprint */
+						body_len = sizeof(struct stun_attr)+SHA_DIGEST_LENGTH;
+					}
+				}
+				else {
+					p = r->pos;
+				}
+				break;
+				
+			case H_STUN_FP:
+				/* content_len contains length of fingerprint in this place! */
+				if ((r->pos - r->body) >= body_len) {
+					r->body += body_len;
+					p = r->body;
+					r->state = H_STUN_END;
+					r->complete = 1;
+					r->has_content_len = 1; /* hack to avoid error check */
+					goto skip;
+				}
+				else {
+					p = r->pos;
+				}
+				break;
+#endif /* USE_STUN */
 			change_state_case(H_CONT_LEN1,  'O', 'o', H_CONT_LEN2);
 			change_state_case(H_CONT_LEN2,  'N', 'n', H_CONT_LEN3);
 			change_state_case(H_CONT_LEN3,  'T', 't', H_CONT_LEN4);
@@ -408,6 +508,7 @@ int tcp_read_req(struct tcp_connection* con, int* bytes_read)
 	struct tcp_req* req;
 	int s;
 	char c;
+	int ret;
 		
 		bytes=-1;
 		total_bytes=0;
@@ -505,7 +606,16 @@ again:
 							   previous char, req->parsed should be ok
 							   because we always alloc BUF_SIZE+1 */
 			*req->parsed=0;
-			if (receive_msg(req->start, req->parsed-req->start, &con->rcv)<0){
+#ifdef USE_STUN
+			if (req->state==H_STUN_END){
+				/* stun request */
+				ret = stun_process_msg(req->start, req->parsed-req->start,
+									 &con->rcv);
+			}else
+#endif
+				ret = receive_msg(req->start, req->parsed-req->start, &con->rcv);
+				
+			if (ret < 0) {
 				*req->parsed=c;
 				resp=CONN_ERROR;
 				goto end_req;
@@ -925,4 +1035,21 @@ error:
 
 #endif /* DEBUG_TCP_RECEIVE */
 
+#ifdef USE_STUN
+int is_msg_complete(struct tcp_req* r)
+{
+	if (r->has_content_len == 1) {
+		r->state = H_STUN_FP;
+		return 0;
+	}
+	else {
+		/* STUN message is complete */
+		r->state = H_STUN_END;
+		r->complete = 1;
+		r->has_content_len = 1; /* hack to avoid error check */
+		return 1;
+	}
+}
+#endif
+
 #endif /* USE_TCP */

+ 27 - 6
udp_server.c

@@ -37,6 +37,7 @@
  *  2005-03-10  multicast options are now set for all the udp sockets (andrei)
  *  2005-06-26  failure to set mcast options is not an error anymore (andrei)
  *  2006-04-12  udp_send() switched to struct dest_info (andrei)
+ *  2006-10-13  added STUN support (vlada)
  */
 
 
@@ -63,6 +64,9 @@
 #include "mem/mem.h"
 #include "ip_addr.h"
 
+#ifdef USE_STUN
+  #include "ser_stun.h"
+#endif
 
 #ifdef DBG_MSG_QA
 /* message quality assurance -- frequently, bugs in ser have
@@ -442,12 +446,20 @@ int udp_rcv_loop()
 		ri.src_port=su_getport(from);
 
 #ifndef NO_ZERO_CHECKS
-		if (len<MIN_UDP_PACKET) {
-			tmp=ip_addr2a(&ri.src_ip);
-			DBG("udp_rcv_loop: probing packet received from %s %d\n",
-					tmp, htons(ri.src_port));
-			continue;
+#ifdef USE_STUN
+		/* STUN support can be switched off even if it's compiled */
+		if (stun_allow_stun == 0 || (unsigned char)*buf != 0x00) {
+#endif
+		  if (len<MIN_UDP_PACKET) {
+			  tmp=ip_addr2a(&ri.src_ip);
+			  DBG("udp_rcv_loop: probing packet received from %s %d\n",
+				  	tmp, htons(ri.src_port));
+			  continue;
+		  }
+#ifdef USE_STUN
 		}
+#endif
+#ifndef USE_STUN
 		if (buf[len-1]==0) {
 			tmp=ip_addr2a(&ri.src_ip);
 			LOG(L_WARN, "WARNING: udp_rcv_loop: "
@@ -456,6 +468,7 @@ int udp_rcv_loop()
 			len--;
 		}
 #endif
+#endif
 #ifdef DBG_MSG_QA
 		if (!dbg_msg_qa(buf, len)) {
 			LOG(L_WARN, "WARNING: an incoming message didn't pass test,"
@@ -469,7 +482,15 @@ int udp_rcv_loop()
 			continue;
 		}
 		
-		
+#ifdef USE_STUN
+			/* STUN support can be switched off even if it's compiled */
+			if (stun_allow_stun && (unsigned char)*buf == 0x00) {
+			    /* stun_process_msg releases buf memory if necessary */
+				if ((stun_process_msg(buf, len, &ri)) != 0) {
+					continue; /* some error occurred */
+				}
+			} else
+#endif
 		/* receive_msg must free buf too!*/
 		receive_msg(buf, len, &ri);