rgwx_sip.c 29.9 KB
Newer Older
1
2
/*********************************************************************************************************
* Software License Agreement (BSD License)                                                               *
3
4
5
* Author: Alexandre Westfahl <awestfahl@freediameter.net>						 *
*													 *
* Copyright (c) 2010, Alexandre Westfahl, Teraoka Laboratory (Keio University), and the WIDE Project. 	 *		
6
7
*													 *
* All rights reserved.											 *
8
* Based on rgwx_auth plugin (Sebastien Decugis <sdecugis@nict.go.jp>)					 *
9
10
11
12
13
14
15
16
17
18
19
20
21
* 													 *
* Redistribution and use of this software in source and binary forms, with or without modification, are  *
* permitted provided that the following conditions are met:						 *
* 													 *
* * Redistributions of source code must retain the above 						 *
*   copyright notice, this list of conditions and the 							 *
*   following disclaimer.										 *
*    													 *
* * Redistributions in binary form must reproduce the above 						 *
*   copyright notice, this list of conditions and the 							 *
*   following disclaimer in the documentation and/or other						 *
*   materials provided with the distribution.								 *
* 													 *
22
* * Neither the name of the Teraoka Laboratory nor the 							 *
23
24
*   names of its contributors may be used to endorse or 						 *
*   promote products derived from this software without 						 *
25
26
*   specific prior written permission of Teraoka Laboratory 						 *
*   													 *
27
28
29
30
31
32
33
34
35
36
37
* 													 *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED *
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR *
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 	 *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 	 *
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR *
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF   *
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.								 *
*********************************************************************************************************/

38

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* RADIUS Access-Request messages translation plugin */

#include "rgw_common.h"
#include <string.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h> 

/* Other constants we use */
#define AI_SIP				6	/* Diameter SIP application */
#define CC_MULTIMEDIA_AUTH_REQUEST	286	/* MAR */
#define CC_MULTIMEDIA_AUTH_ANSWER	286	/* MAA */
#define ACV_ASS_STATE_MAINTAINED	0	/* STATE_MAINTAINED */
#define ACV_ASS_NO_STATE_MAINTAINED	1	/* NO_STATE_MAINTAINED */
#define ER_DIAMETER_SUCCESS_AUTH_SENT_SERVER_NOT_STORED	2008
#define ER_DIAMETER_SUCCESS_SERVER_NAME_NOT_STORED	2006



/* This macro converts a RADIUS attribute to a Diameter AVP of type OctetString */
#define CONV2DIAM_STR( _dictobj_ )	\
60
	CHECK_PARAMS( attr->length >= sizeof(struct radius_attr_hdr) );			\
61
62
	/* Create the AVP with the specified dictionary model */			\
	CHECK_FCT( fd_msg_avp_new ( cs->dict._dictobj_, 0, &avp ) );			\
63
64
	value.os.len = attr->length - sizeof(struct radius_attr_hdr);			\
	value.os.data = (os0_t)(attr + 1);						\
65
66
67
68
69
	CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );				\
	/* Add the AVP in the Diameter message. */					\
	CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_LAST_CHILD, avp) );		\

#define CONV2DIAM_STR_AUTH( _dictobj_ )	\
70
	CHECK_PARAMS( attr->length >= sizeof(struct radius_attr_hdr) );			\
71
72
	/* Create the AVP with the specified dictionary model */			\
	CHECK_FCT( fd_msg_avp_new ( cs->dict._dictobj_, 0, &avp ) );			\
73
74
	value.os.len = attr->length - sizeof(struct radius_attr_hdr);			\
	value.os.data = (os0_t)(attr + 1);						\
75
76
	CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );				\
	/* Add the AVP in the Diameter message. */					\
77
	CHECK_FCT( fd_msg_avp_add ( auth, MSG_BRW_LAST_CHILD, avp) );			\
78
79
80
		
/* Same thing, for scalar AVPs of 32 bits */
#define CONV2DIAM_32B( _dictobj_ )	\
81
	CHECK_PARAMS( attr->length == sizeof(struct radius_attr_hdr)+sizeof(uint32_t) );\
82
83
84
85
	CHECK_FCT( fd_msg_avp_new ( cs->dict._dictobj_, 0, &avp ) );			\
	{										\
		uint8_t * v = (uint8_t *)(attr + 1);					\
		value.u32  = (v[0] << 24)						\
86
87
88
			   | (v[1] << 16)						\
			   | (v[2] <<  8)						\
			   |  v[3] ;							\
89
90
	}										\
	CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );				\
91
	CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_LAST_CHILD, avp) );		\
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
				
				
				
				
				
/* The state we keep for this plugin */
struct rgwp_config {
	struct {
		struct dict_object * Session_Id;		
		struct dict_object * Auth_Application_Id;	
		struct dict_object * Auth_Session_State;	
		struct dict_object * Origin_Host;		
		struct dict_object * Origin_Realm;		
		struct dict_object * Destination_Realm;		
		struct dict_object * SIP_AOR;			
		struct dict_object * SIP_Method;			
		struct dict_object * Destination_Host;		
		struct dict_object * User_Name;			
		struct dict_object * SIP_Server_URI;		
		struct dict_object * SIP_Number_Auth_Items;	
		struct dict_object * SIP_Authorization;	
		struct dict_object * SIP_Authentication_Scheme;	
		struct dict_object * SIP_Authentication_Info;	
		struct dict_object * SIP_Auth_Data_Item;	
		struct dict_object * Proxy_Info;		
		struct dict_object * Route_Record;		
		struct dict_object * Service_Type;		
		struct dict_object * Result_Code;		
		struct dict_object * Digest_URI;		
		struct dict_object * Digest_Nonce;
		struct dict_object * Digest_CNonce;
		struct dict_object * Digest_Nonce_Count;				
		struct dict_object * Digest_Realm;		
		struct dict_object * Digest_Response;
		struct dict_object * Digest_Method;
		struct dict_object * Digest_Response_Auth;		
		struct dict_object * Digest_Username;
		struct dict_object * Digest_Algorithm;	
		struct dict_object * Digest_QOP;

		
		
	} dict; /* cache of the dictionary objects we use */
	struct session_handler * sess_hdl; /* We store RADIUS request authenticator information in the session */
	char * confstr;
137
	//Chained list of nonce
138
139
140
141
142
143
144
145
146
	struct fd_list listnonce;
	//This will be used to lock access to chained list
	pthread_mutex_t nonce_mutex; 
};

typedef struct noncechain noncechain;
struct noncechain
{
	struct fd_list chain;
147
    os0_t sid;
148
    size_t sidlen;
149
    os0_t nonce;
150
    size_t noncelen;
151
152
153
    
};

154
static int nonce_add_element(os0_t nonce, size_t noncelen, os0_t sid, size_t sidlen, struct rgwp_config * state)
155
{
156
157
	CHECK_PARAMS(nonce && state && sid && sidlen && noncelen);
	
158
159
160
	noncechain *newelt;
	CHECK_MALLOC(newelt=malloc(sizeof(noncechain)));
	
161
	CHECK_MALLOC(newelt->nonce= os0dup(nonce, noncelen));
162
163
	newelt->noncelen=noncelen;
	
164
	CHECK_MALLOC(newelt->sid=os0dup(sid, sidlen));
165
	newelt->sidlen=sidlen;
166
	
167
	fd_list_init(&newelt->chain,NULL);
168
169
170
171
	
	CHECK_POSIX(pthread_mutex_lock(&state->nonce_mutex));
	fd_list_insert_before(&state->listnonce,&newelt->chain);
	CHECK_POSIX(pthread_mutex_unlock(&state->nonce_mutex));
172
173
	
	return 0;
174
}
175
/*
176
static void nonce_del_element(char * nonce, struct rgwp_config *state)
177
{
178
179
180
181
182
	struct fd_list * li;
	
	CHECK_PARAMS_DO(nonce && state, return);
	
	for(li=state->listnonce.next;li!=&state->listnonce;li=li->next)
183
	{
184
		noncechain *temp=(noncechain *)li;
185
		
186
		if(strcmp(temp->nonce,nonce)==0)
187
		{
188
189
190
191
192
			fd_list_unlink (li);
			free(temp->sid);
			free(temp->nonce);
			free(temp);
			break;
193
194
195
		}
	}
}
196
*/
197
//Retrieve sid from nonce
198
static os0_t nonce_get_sid(os0_t nonce, size_t noncelen, size_t * sidlen, struct rgwp_config *state)
199
{
200
	struct fd_list * li;
201
	os0_t sid=NULL;
202
	
203
	CHECK_PARAMS_DO(nonce && state && noncelen && sidlen, return NULL);
204
205
	*sidlen=0;
	
206
	// **Start mutex
207
208
	CHECK_POSIX_DO(pthread_mutex_lock(&state->nonce_mutex),); 
	for(li=state->listnonce.next;li!=&state->listnonce;li=li->next)
209
	{
210
		noncechain *temp=(noncechain *)li;
211
		
212
		if (!fd_os_cmp(temp->nonce, temp->noncelen, nonce, noncelen))
213
		{
214
215
216
217
218
219
			fd_list_unlink (li);
			sid=temp->sid;
			*sidlen=temp->sidlen;
			free(temp->nonce);
			free(temp);
			break;
220
221
222
		}
		
	}
223
	CHECK_POSIX_DO(pthread_mutex_unlock(&state->nonce_mutex),); 
224
	// ***Stop mutex
225
	return sid;
226
227
}

228
static void nonce_deletelistnonce(struct rgwp_config *state)
229
{
230
	// **Start mutex
231
232
	CHECK_POSIX_DO(pthread_mutex_lock(&state->nonce_mutex),); 
	while(!(FD_IS_LIST_EMPTY(&state->listnonce)) )
233
	{
234
235
236
237
238
239
		noncechain *temp=(noncechain *)state->listnonce.next;
		
		fd_list_unlink (&temp->chain);
		free(temp->sid);
		free(temp->nonce);
		free(temp);
240
241
		
	}
242
	CHECK_POSIX_DO(pthread_mutex_unlock(&state->nonce_mutex),); 
243
	// ***Stop mutex
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
}

/* Initialize the plugin */
static int sip_conf_parse(char * conffile, struct rgwp_config ** state)
{
	struct rgwp_config * new;
	struct dict_object * app;
	
	
	TRACE_ENTRY("%p %p", conffile, state);
	CHECK_PARAMS( state );
	
	CHECK_MALLOC( new = malloc(sizeof(struct rgwp_config)) );
	memset(new, 0, sizeof(struct rgwp_config));
	
259
	CHECK_FCT( fd_sess_handler_create( &new->sess_hdl, free, NULL ) );
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
	new->confstr = conffile;
	
	/* Resolve all dictionary objects we use */
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Session-Id", &new->dict.Session_Id, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Auth-Application-Id", &new->dict.Auth_Application_Id, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Auth-Session-State", &new->dict.Auth_Session_State, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Origin-Host", &new->dict.Origin_Host, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Origin-Realm", &new->dict.Origin_Realm, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Destination-Realm", &new->dict.Destination_Realm, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "SIP-AOR", &new->dict.SIP_AOR, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "SIP-Method", &new->dict.SIP_Method, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Destination-Host", &new->dict.Destination_Host, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "User-Name", &new->dict.User_Name, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "SIP-Server-URI", &new->dict.SIP_Server_URI, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "SIP-Number-Auth-Items", &new->dict.SIP_Number_Auth_Items, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "SIP-Authorization", &new->dict.SIP_Authorization, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "SIP-Auth-Data-Item", &new->dict.SIP_Auth_Data_Item, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "SIP-Authentication-Scheme", &new->dict.SIP_Authentication_Scheme, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "SIP-Authentication-Info", &new->dict.SIP_Authentication_Info, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Proxy-Info", &new->dict.Proxy_Info, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Route-Record", &new->dict.Route_Record, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Result-Code", &new->dict.Result_Code, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-URI", &new->dict.Digest_URI, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-Nonce", &new->dict.Digest_Nonce, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-Method", &new->dict.Digest_Method, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-CNonce", &new->dict.Digest_CNonce, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-Nonce-Count", &new->dict.Digest_Nonce_Count, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-Realm", &new->dict.Digest_Realm, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-Response", &new->dict.Digest_Response, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-Response-Auth", &new->dict.Digest_Response_Auth, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-Username", &new->dict.Digest_Username, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-Algorithm", &new->dict.Digest_Algorithm, ENOENT) );
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Digest-QoP", &new->dict.Digest_QOP, ENOENT) );


	
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_APPLICATION, APPLICATION_BY_NAME, "Diameter Session Initiation Protocol (SIP) Application", &app, ENOENT) );
	CHECK_FCT( fd_disp_app_support ( app, NULL, 1, 0 ) );
	
	//chained list
300
	fd_list_init(&new->listnonce,NULL);
301
302
303
304
305
306
307
308
309
310
311
312
	CHECK_POSIX(pthread_mutex_init(&new->nonce_mutex,NULL));
	
	*state = new;
	return 0;
}

/* deinitialize */
static void sip_conf_free(struct rgwp_config * state)
{
	TRACE_ENTRY("%p", state);
	CHECK_PARAMS_DO( state, return );
	
313
	CHECK_FCT_DO( fd_sess_handler_destroy( &state->sess_hdl, NULL ),  );
314
	
315
	nonce_deletelistnonce(state);
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
	CHECK_POSIX_DO(pthread_mutex_destroy(&state->nonce_mutex), /*continue*/);
	
	free(state);
	return;
}


/* Handle an incoming RADIUS request */
static int sip_rad_req( struct rgwp_config * cs, struct session ** session, struct radius_msg * rad_req, struct radius_msg ** rad_ans, struct msg ** diam_fw, struct rgw_client * cli )
{
	int idx;
	int got_AOR = 0;
	int got_Dusername = 0;
	int got_Drealm = 0;
	int got_Duri = 0;
	int got_Dmethod = 0;
	int got_Dqop = 0;
	int got_Dnonce_count = 0;
	int got_Dnonce = 0;
	int got_Dcnonce = 0;
	int got_Dresponse = 0;
	int got_Dalgorithm = 0;
338
339
340
	os0_t sid = NULL;
	size_t sidlen;
	os0_t un=NULL;
341
	size_t  un_len;
342
343
344
345
346
347
	size_t nattr_used = 0;
	struct avp *auth_data=NULL, *auth=NULL, *avp = NULL;
	union avp_value value;
	
	TRACE_ENTRY("%p %p %p %p %p %p", cs, session, rad_req, rad_ans, diam_fw, cli);
	
348
	CHECK_PARAMS(rad_req && (rad_req->hdr->code == RADIUS_CODE_ACCESS_REQUEST) && rad_ans && diam_fw && *diam_fw && session);
349
350
351
352
	
	//We check that session is not already filled
	if(*session)
	{
353
		TRACE_DEBUG(INFO,"INTERNAL ERROR: We are not supposed to receive a session in radSIP plugin.");
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
		return EINVAL;
	}
	
	/*
	   RFC5090 RADIUS Extension Digest Application
	*/
	
	/* Check basic information is there */
	for (idx = 0; idx < rad_req->attr_used; idx++) {
		struct radius_attr_hdr * attr = (struct radius_attr_hdr *)(rad_req->buf + rad_req->attr_pos[idx]);
		
		
		switch (attr->type) {
			
			case RADIUS_ATTR_USER_NAME:
369
370
371
				if (attr->length>sizeof(struct radius_attr_hdr)) 
				{
					TRACE_DEBUG(ANNOYING, "Found a User-Name attribute: '%.*s'", attr->length- sizeof(struct radius_attr_hdr), (char *)(attr+1));
372
					un = (os0_t)(attr + 1);
373
374
					un_len =attr->length - sizeof(struct radius_attr_hdr);
				}
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
			break;
			case RADIUS_ATTR_DIGEST_USERNAME:
				got_Dusername = 1;
			break;
			case RADIUS_ATTR_DIGEST_REALM:
				got_Drealm = 1;
			break;
			case RADIUS_ATTR_DIGEST_URI:
				got_Duri = 1;
			break;
			case RADIUS_ATTR_DIGEST_METHOD:
				got_Dmethod = 1;
			break;
			case RADIUS_ATTR_DIGEST_QOP:
				got_Dqop = 1;
			break;
			case RADIUS_ATTR_DIGEST_NONCE_COUNT:
				got_Dnonce_count = 1;
			break;
			case RADIUS_ATTR_DIGEST_NONCE:
				got_Dnonce = 1;
396
				
397
				sid=nonce_get_sid((os0_t)(attr+1), attr->length - sizeof(struct radius_attr_hdr), &sidlen, cs);
398
399
400
401
402
403
404
				if(!sid)
				{
					TRACE_DEBUG(INFO,"We haven't found the session.'");
					return EINVAL;
				}
				CHECK_FCT(fd_sess_fromsid (sid, sidlen, session, NULL));
				free(sid);
405
							
406
				
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
			break;
			case RADIUS_ATTR_DIGEST_CNONCE:
				got_Dcnonce = 1;
			break;
			case RADIUS_ATTR_DIGEST_RESPONSE:
				got_Dresponse = 1;
			break;			
			case RADIUS_ATTR_DIGEST_ALGORITHM:
				got_Dalgorithm = 1;
			break;
			case RADIUS_ATTR_SIP_AOR:
				got_AOR = 1;
			break;
		}
	}
422
	if(!un)
423
424
	{
		TRACE_DEBUG(INFO,"No Username in request");
425
		return EINVAL;
426
	}
427
428
429

	/* Create the session if it is not already done */
	if (!*session) {
430
		
431
432
433
434
		DiamId_t fqdn;
		size_t fqdn_len;
		DiamId_t realm;
		size_t realm_len;
435
436
437
438
439
		
		
		
		
		/* Get information on the RADIUS client */
440
		CHECK_FCT( rgw_clients_get_origin(cli, &fqdn, &fqdn_len, &realm, &realm_len) );
441
442
443
		
		/* Create a new Session-Id. The format is: {fqdn;hi32;lo32;username;diamid} */
		CHECK_MALLOC( sid = malloc(un_len + 1 /* ';' */ + fd_g_config->cnf_diamid_len + 1 /* '\0' */) );
444
445
		sidlen = sprintf((char *)sid, "%.*s;%s", (int)un_len, un, fd_g_config->cnf_diamid);
		CHECK_FCT( fd_sess_new(session, fqdn, fqdn_len, sid, sidlen) );
446
447
448
449
450
451
452
		free(sid);
	}
		
	/* Add the Destination-Realm AVP */
	CHECK_FCT( fd_msg_avp_new ( cs->dict.Destination_Realm, 0, &avp ) );
	
	int i = 0;
453
454
455
456
457
458
	
	/* Is there an '@' in the user name? We don't care for decorated NAI here */
	for (i = un_len - 2; i > 0; i--) {
		if (un[i] == '@') {
			i++;
			break;
459
		}
460
	}
461

462
463
	if (i == 0) {
		/* Not found in the User-Name => we use the local domain of this gateway */
464
		value.os.data = (os0_t)fd_g_config->cnf_diamrlm;
465
466
		value.os.len  = fd_g_config->cnf_diamrlm_len;
	} else {
467
		value.os.data = un + i;
468
469
470
471
472
473
474
		value.os.len  = un_len - i;
	}
	
	CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
	CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_FIRST_CHILD, avp) );
	
	/* Now, add the Session-Id AVP at beginning of Diameter message */
475
	CHECK_FCT( fd_sess_getsid(*session, &sid, &sidlen) );
476
477
478
479
480
	
	TRACE_DEBUG(FULL, "[sip.rgwx] Translating new message for session '%s'...", sid);
	
	/* Add the Session-Id AVP as first AVP */
	CHECK_FCT( fd_msg_avp_new ( cs->dict.Session_Id, 0, &avp ) );
481
482
	value.os.data = sid;
	value.os.len = sidlen;
483
484
485
	CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
	CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_FIRST_CHILD, avp) );
	
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
	/*
	If the RADIUS Access-Request message does not
	contain any Digest-* attribute, then the RADIUS client does not want
	to apply HTTP Digest authentication, in which case, actions at the
	gateway are outside the scope of this document.
	*/
	
	if(!(got_Dmethod && got_Duri))
	{
		TRACE_DEBUG(INFO,"No Digest attributes in request, we drop it...");
		return 1;
	}

	/* Add the appropriate command code & Auth-Application-Id */
	{
		struct msg_hdr * header = NULL;
		CHECK_FCT( fd_msg_hdr ( *diam_fw, &header ) );
		header->msg_flags = CMD_FLAG_REQUEST | CMD_FLAG_PROXIABLE;
		header->msg_code = CC_MULTIMEDIA_AUTH_REQUEST;
		header->msg_appl = AI_SIP;
	
	
		/* Add the Auth-Application-Id */
		{
			CHECK_FCT( fd_msg_avp_new ( cs->dict.Auth_Application_Id, 0, &avp ) );
			value.i32 = header->msg_appl;
			CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
			CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_LAST_CHILD, avp) );
		}
	}
	/*Add Auth_Session_State  AVP */
	{
		CHECK_FCT( fd_msg_avp_new ( cs->dict.Auth_Session_State, 0, &avp ) );
		value.i32 = ACV_ASS_NO_STATE_MAINTAINED;
		CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
		CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_LAST_CHILD, avp) );
	}

	
	/*Add SIP_Number_Auth_Items  AVP */
	{
		CHECK_FCT( fd_msg_avp_new ( cs->dict.SIP_Number_Auth_Items, 0, &avp ) );
		value.i32 = 1; //We just treat one auth per request in gateway
		CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
		CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_LAST_CHILD, avp) );
	}

	/* Add SIP_Auth_Data_Item AVP */
	{
		CHECK_FCT( fd_msg_avp_new ( cs->dict.SIP_Auth_Data_Item, 0, &auth_data ) );
	}
	/* Add SIP_Authentication_Scheme AVP */
	{
		CHECK_FCT( fd_msg_avp_new ( cs->dict.SIP_Authentication_Scheme, 0, &avp ) );
		value.i32=0; //There is only Digest Auth in RFC for now
		CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
		CHECK_FCT( fd_msg_avp_add ( auth_data, MSG_BRW_LAST_CHILD, avp) );
	
	}

	
	/* Add SIP_Authorization AVP */
	{
		CHECK_FCT( fd_msg_avp_new ( cs->dict.SIP_Authorization, 0, &auth ) );
		CHECK_FCT( fd_msg_avp_add ( auth_data, MSG_BRW_LAST_CHILD, auth) );
	}

	for (idx = 0; idx < rad_req->attr_used; idx++) 
	{
		struct radius_attr_hdr * attr = (struct radius_attr_hdr *)(rad_req->buf + rad_req->attr_pos[idx]);
		
		switch (attr->type) {

			case RADIUS_ATTR_USER_NAME:
			CONV2DIAM_STR( User_Name );
			
			if(!got_Dusername)
			{
				CONV2DIAM_STR_AUTH(Digest_Username);
				got_Dusername=1;
			}
			
			break;

			case RADIUS_ATTR_DIGEST_URI:
			
			CONV2DIAM_STR_AUTH(Digest_URI);
			
			//All of these attributes are required by Diameter but not defined in RFC5090 so we provide FAKE values (only in first exchange)
			if(!got_AOR)
			{
				CONV2DIAM_STR( SIP_AOR );
				got_AOR=1;
			}
			/*
			We must provide a fake nonce because of RFC4740 problem
			TODO: remove when RFC is updated
			==START of FAKE
			*/
			if(!got_Dresponse)
			{
				CONV2DIAM_STR_AUTH(Digest_Response);
				got_Dresponse=1;
			}
			/*
			==END of FAKE
			*/
			if(!got_Drealm)
			{
				//We extract Realm from Digest_URI
596
597
598
599
600
601
602
603
604
605
606
607
608
609
				DiamId_t realm=NULL;
				size_t realm_len;
				os0_t temp;
				
				temp = (os0_t)(attr + 1);
				
				for (i=attr->length - sizeof(struct radius_attr_hdr) - 1; i>=0; i--) {
					if (temp[i] == '@') {
						realm = (DiamId_t)temp + i + 1;
						CHECK_FCT_DO( fd_os_validate_DiameterIdentity(&realm, &realm_len, 1),
							realm = NULL );
						break;
					}
				}
610
611
612
613
			
				if(realm!=NULL)
				{
					CHECK_FCT( fd_msg_avp_new ( cs->dict.Digest_Realm, 0, &avp ) );
614
615
					value.os.data=(os0_t)realm;
					value.os.len=realm_len;
616
617
618
619
620
					CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
					CHECK_FCT( fd_msg_avp_add ( auth, MSG_BRW_LAST_CHILD, avp) );
					
					//We add SIP-Server-URI AVP because SIP server is registrar (through gateway)
					CHECK_FCT( fd_msg_avp_new ( cs->dict.SIP_Server_URI, 0, &avp ) );
621
622
					value.os.data=(os0_t)realm;
					value.os.len=realm_len;
623
624
625
					CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
					CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_LAST_CHILD, avp) );
					
626
					free(realm);
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
				}
				else
				{
					TRACE_DEBUG(INFO, "Can't extract domain from URI, droping request...");
					return 1;
				}	
				got_Drealm=1;
			}
			break;

			case RADIUS_ATTR_DIGEST_METHOD:
			CONV2DIAM_STR(SIP_Method);
			CONV2DIAM_STR_AUTH(Digest_Method);
			break;
			case RADIUS_ATTR_DIGEST_REALM:
			CONV2DIAM_STR_AUTH(Digest_Realm);
			
			//We add SIP-Server-URI AVP because SIP server is registrar (through gateway)
			CHECK_FCT( fd_msg_avp_new ( cs->dict.SIP_Server_URI, 0, &avp ) );
646
647
648
649
			os0_t temp;
			#define SIP_PREFIX	"sip:"
			size_t temp_len = attr->length - sizeof(struct radius_attr_hdr) + CONSTSTRLEN(SIP_PREFIX) + 1;
			CHECK_MALLOC( temp = malloc(temp_len) );
650
			temp_len = snprintf((char *)temp, temp_len, SIP_PREFIX "%.*s", (int)(attr->length - sizeof(struct radius_attr_hdr)), (char *)(attr + 1));
651
			
652
653
			value.os.data=temp;
			value.os.len=temp_len;
654
655
			
			free(temp);
656
			
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
			CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
			CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_LAST_CHILD, avp) );
			break;
			
			case RADIUS_ATTR_DIGEST_USERNAME:
			CONV2DIAM_STR_AUTH(Digest_Username);
			break;
				
			case RADIUS_ATTR_DIGEST_QOP:
			CONV2DIAM_STR_AUTH( Digest_QOP );
			break;
			case RADIUS_ATTR_DIGEST_ALGORITHM:		
			CONV2DIAM_STR_AUTH( Digest_Algorithm );
			break;
			case RADIUS_ATTR_DIGEST_CNONCE:
			CONV2DIAM_STR_AUTH( Digest_CNonce );
			break;
			case RADIUS_ATTR_DIGEST_NONCE:
				CONV2DIAM_STR_AUTH( Digest_Nonce );
			break;
			case RADIUS_ATTR_DIGEST_NONCE_COUNT:
			CONV2DIAM_STR_AUTH( Digest_Nonce_Count );
			break;
			case RADIUS_ATTR_DIGEST_RESPONSE:
			CONV2DIAM_STR_AUTH( Digest_Response );
			break;
			case RADIUS_ATTR_SIP_AOR:
			CONV2DIAM_STR( SIP_AOR );
			break;
				
			default:
			if(!got_Dalgorithm)
			{
				//[Note 3] If Digest-Algorithm is missing, 'MD5' is assumed.
691
				#define DIGEST_ALGO_MD5	"MD5"
692
693
										
				CHECK_FCT( fd_msg_avp_new ( cs->dict.Digest_Algorithm, 0, &avp ) );			
694
										
695
696
				value.os.data = (os0_t)DIGEST_ALGO_MD5;
				value.os.len = CONSTSTRLEN(DIGEST_ALGO_MD5) - 1;
697
698
699
700
701
702
703
704
705
				CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );					
				CHECK_FCT( fd_msg_avp_add ( auth, MSG_BRW_LAST_CHILD, avp) );	
				got_Dalgorithm=1;	
			}
			
			if(!got_Dnonce)
			{
				//We give a fake nonce because it will be calculated at the server.
				CHECK_FCT( fd_msg_avp_new ( cs->dict.Digest_Nonce, 0, &avp ) );
706
707
				value.os.data=(unsigned char *)"nonce";
				value.os.len=strlen((const char *)value.os.data);
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
				CHECK_FCT( fd_msg_avp_setvalue ( avp, &value ) );
				CHECK_FCT( fd_msg_avp_add ( auth, MSG_BRW_LAST_CHILD, avp) );	
				got_Dnonce=1;
			}
			break;
	
		}
	}

	
	CHECK_FCT( fd_msg_avp_add ( *diam_fw, MSG_BRW_LAST_CHILD, auth_data) );
	
	/* Update the radius message to remove all handled attributes */
	rad_req->attr_used = nattr_used;

	//fd_msg_dump_walk(1,*diam_fw);
	
	/* Store the request identifier in the session (if provided) */
726
	if (*session) {
727
728
729
730
		unsigned char * req_sip;
		CHECK_MALLOC(req_sip = malloc(16));
		memcpy(req_sip, &rad_req->hdr->authenticator[0], 16);
		
731
		CHECK_FCT( fd_sess_state_store( cs->sess_hdl, *session, &req_sip ) );
732
733
734
735
736
737
738
739
740
	}
	
	
	return 0;
}

static int sip_diam_ans( struct rgwp_config * cs, struct session * session, struct msg ** diam_ans, struct radius_msg ** rad_fw, struct rgw_client * cli, int * statefull )
{
	
741
	
742
	struct avp *avp, *next, *asid;
743
744
	struct avp_hdr *ahdr, *sid;
	//char buf[254]; /* to store some attributes values (with final '\0') */
745
	unsigned char * req_sip = NULL;
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
	int in_success=0;
	
	TRACE_ENTRY("%p %p %p %p %p", cs, session, diam_ans, rad_fw, cli);
	CHECK_PARAMS(cs && session && diam_ans && *diam_ans && rad_fw && *rad_fw);
	
	
	
	
	
	/* MACROS to help in the process: convert AVP data to RADIUS attributes. */
	/* Control large attributes:  _trunc_ = 0 => error; _trunc_ = 1 => truncate; _trunc = 2 => create several attributes */
	#define CONV2RAD_STR( _attr_, _data_, _len_, _trunc_)	{					\
		size_t __l = (size_t)(_len_);								\
		size_t __off = 0;									\
		TRACE_DEBUG(FULL, "Converting AVP to "#_attr_);						\
		if ((_trunc_) == 0) {									\
			CHECK_PARAMS( __l <= 253 );							\
		}											\
		if ((__l > 253) && (_trunc_ == 1)) {							\
			TRACE_DEBUG(INFO, "[authSIP.rgwx] AVP truncated in "#_attr_);			\
			__l = 253;									\
		}											\
		do {											\
			size_t __w = (__l > 253) ? 253 : __l;						\
			CHECK_MALLOC(radius_msg_add_attr(*rad_fw, (_attr_), (_data_) + __off, __w));	\
			__off += __w;									\
			__l   -= __w;									\
		} while (__l);										\
	}

	#define CONV2RAD_32B( _attr_, _data_)	{							\
		uint32_t __v = htonl((uint32_t)(_data_));						\
		TRACE_DEBUG(FULL, "Converting AVP to "#_attr_);						\
		CHECK_MALLOC(radius_msg_add_attr(*rad_fw, (_attr_), (uint8_t *)&__v, sizeof(__v)));	\
	}


	/* Search the different AVPs we handle here */
	CHECK_FCT( fd_msg_search_avp (*diam_ans, cs->dict.Session_Id, &asid) );
	CHECK_FCT( fd_msg_avp_hdr ( asid, &sid ) );

	/* Check the Diameter error code */
	CHECK_FCT( fd_msg_search_avp (*diam_ans, cs->dict.Result_Code, &avp) );
	ASSERT( avp ); /* otherwise the message should have been discarded a lot earlier because of ABNF */
	CHECK_FCT( fd_msg_avp_hdr ( avp, &ahdr ) );
	switch (ahdr->avp_value->u32) {
		case ER_DIAMETER_MULTI_ROUND_AUTH:
		case ER_DIAMETER_SUCCESS_AUTH_SENT_SERVER_NOT_STORED:		
			(*rad_fw)->hdr->code = RADIUS_CODE_ACCESS_CHALLENGE;
795
796
797
798
			//struct timespec nowts;
			//CHECK_SYS(clock_gettime(CLOCK_REALTIME, &nowts));
			//nowts.tv_sec+=600;
			//CHECK_FCT(fd_sess_settimeout(session, &nowts ));
799
800
801
802
803
804
805
806
807
			break;
		case ER_DIAMETER_SUCCESS_SERVER_NAME_NOT_STORED:
		case ER_DIAMETER_SUCCESS:
			(*rad_fw)->hdr->code = RADIUS_CODE_ACCESS_ACCEPT;
			in_success=1;
			break;
		
		default:
			(*rad_fw)->hdr->code = RADIUS_CODE_ACCESS_REJECT;
808
			fd_log_debug("[sip.rgwx] Received Diameter answer with error code '%d', session %.*s, translating into Access-Reject\n",
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
					ahdr->avp_value->u32, 
					sid->avp_value->os.len, sid->avp_value->os.data);
			return 0;
	}
	/* Remove this Result-Code avp */
	CHECK_FCT( fd_msg_free( avp ) );
	
	/* Now loop in the list of AVPs and convert those that we know how */
	CHECK_FCT( fd_msg_browse(*diam_ans, MSG_BRW_FIRST_CHILD, &next, NULL) );
	
	while (next) {
		int handled = 1;
		avp = next;
		CHECK_FCT( fd_msg_browse(avp, MSG_BRW_WALK, &next, NULL) );
		
		CHECK_FCT( fd_msg_avp_hdr ( avp, &ahdr ) );
		
		if (!(ahdr->avp_flags & AVP_FLAG_VENDOR)) {
			switch (ahdr->avp_code) {
				
829
				
830
831
832
833
				case DIAM_ATTR_DIGEST_NONCE:
					CONV2RAD_STR(DIAM_ATTR_DIGEST_NONCE, ahdr->avp_value->os.data, ahdr->avp_value->os.len, 0);
					/* Retrieve the request identified which was stored in the session */
					if (session) {
834
						os0_t sid=NULL;
835
						size_t sidlen;
836
						fd_sess_getsid (session, &sid, &sidlen );
837
						
838
						nonce_add_element(ahdr->avp_value->os.data, ahdr->avp_value->os.len, sid, sidlen, cs);
839
840
841
842
843
844
845
846
847
848
849
850
851
852
					}
					break;
				case DIAM_ATTR_DIGEST_REALM:
					CONV2RAD_STR(DIAM_ATTR_DIGEST_REALM, ahdr->avp_value->os.data, ahdr->avp_value->os.len, 1);
					break;
				case DIAM_ATTR_DIGEST_QOP:
					CONV2RAD_STR(DIAM_ATTR_DIGEST_QOP, ahdr->avp_value->os.data, ahdr->avp_value->os.len, 1);
					break;
				case DIAM_ATTR_DIGEST_ALGORITHM:
					CONV2RAD_STR(DIAM_ATTR_DIGEST_ALGORITHM, ahdr->avp_value->os.data, ahdr->avp_value->os.len, 1);
					break;		
				case DIAM_ATTR_DIGEST_RESPONSE_AUTH:
					CONV2RAD_STR(DIAM_ATTR_DIGEST_RESPONSE_AUTH, ahdr->avp_value->os.data, ahdr->avp_value->os.len, 0);
					break;
853
854
855
				default:
					handled=0;
					break;
856
857
858
859
860
861
862
863
864
865
866
			}
		} 
		else 
		{
			/* Vendor-specific AVPs */
			switch (ahdr->avp_vendor) {
				
				default: /* unknown vendor */
					handled = 0;
			}
		}
867
868
869
		if (handled) {
			CHECK_FCT( fd_msg_free( avp ) );
		}
870
	}
871
872
873
874
875
876
877
	
	if (session) 
	{
		CHECK_FCT( fd_sess_state_retrieve( cs->sess_hdl, session, &req_sip ) );
	}
	free(req_sip);
	
878
879
880
881
882
883
884
885
886
887
888
889
890
	
	return 0;
}

/* The exported symbol */
struct rgw_api rgwp_descriptor = {
	.rgwp_name       = "sip",
	.rgwp_conf_parse = sip_conf_parse,
	.rgwp_conf_free  = sip_conf_free,
	.rgwp_rad_req    = sip_rad_req,
	.rgwp_diam_ans   = sip_diam_ans
};