1 /*
2  * libZRTP SDK library, implements the ZRTP secure VoIP protocol.
3  * Copyright (c) 2006-2009 Philip R. Zimmermann.  All rights reserved.
4  * Contact: http://philzimmermann.com
5  * For licensing and other legal details, see the file zrtp_legal.c.
6  *
7  * Viktor Krykun <v.krikun at zfoneproject.com>
8  */
9 
10 #include "zrtp.h"
11 
12 #if (ZRTP_PLATFORM == ZP_WIN32_KERNEL)
13 #include <ndis.h>
14 #include <ntstrsafe.h>
15 #endif
16 
17 #if ZRTP_LOG_MAX_LEVEL >= 1
18 
19 /*----------------------------------------------------------------------------*/
20 #if defined ZRTP_HAVE_STDIO_H
21 #	include <stdio.h>
22 #endif
23 #if defined ZRTP_HAVE_STRING_H
24 #	include <string.h>
25 #endif
26 #if defined ZRTP_HAVE_STDARG_H
27 #	include <stdarg.h>
28 #endif
29 
30 static const char* k_unknown = "UNKNOWN";
31 
32 #if ZRTP_PLATFORM != ZP_WIN32_KERNEL
zrtp_def_log_write(int level,char * buffer,int len,int offset)33 void zrtp_def_log_write(int level, char *buffer, int len, int offset) {
34     printf("%s", buffer);
35 }
36 
37 static zrtp_log_engine *log_writer = &zrtp_def_log_write;
38 #else
39 static zrtp_log_engine *log_writer = NULL;
40 #endif
41 
42 static uint32_t log_max_level = ZRTP_LOG_MAX_LEVEL;
43 
44 
45 /*----------------------------------------------------------------------------*/
zrtp_log_set_level(uint32_t level)46 void zrtp_log_set_level(uint32_t level) {
47 	log_max_level = level;
48 }
49 
zrtp_log_set_log_engine(zrtp_log_engine * engine)50 void zrtp_log_set_log_engine(zrtp_log_engine *engine) {
51     log_writer = engine;
52 }
53 
54 /*----------------------------------------------------------------------------*/
zrtp_log(uint8_t is_clean,const char * sender,uint32_t level,const char * format,va_list marker)55 static void zrtp_log(uint8_t is_clean, const char *sender, uint32_t level,  const char *format, va_list marker)
56 {
57 #if (defined(ZRTP_USE_STACK_MINIM) && (ZRTP_USE_STACK_MINIM == 1))
58 	char *log_buffer = zrtp_sys_alloc(ZRTP_LOG_BUFFER_SIZE);
59 #else
60 	char log_buffer[ZRTP_LOG_BUFFER_SIZE];
61 #endif
62 	char* sline = log_buffer;
63 	uint32_t offset = 0;
64 	int len = 0;
65 
66 	if (!sline) {
67 		return;
68 	}
69 
70 	if (!is_clean) {
71 		/* Print sender with left aligment */
72 		uint32_t sender_len = strlen(sender);
73 		*sline++ = ' ';
74 		*sline++ = '[';
75 		if (sender_len <= ZRTP_LOG_SENDER_MAX_LEN) {
76 			while (sender_len < ZRTP_LOG_SENDER_MAX_LEN) {
77 				*sline++ = ' ', ++sender_len;
78 			}
79 			while (*sender) {
80 				*sline++ = *sender++;
81 			}
82 		} else {
83 			int i = 0;
84 			for (i=0; i<ZRTP_LOG_SENDER_MAX_LEN; ++i) {
85 				*sline++ = *sender++;
86 			}
87 		}
88 
89 		*sline++ = ']';
90 		*sline++ = ':';
91 		offset += 3 + ZRTP_LOG_SENDER_MAX_LEN;
92 
93 		*sline++ = ' ';
94 		offset += 1;
95 	}
96 
97 	/* Print Message itself */
98 #if (ZRTP_PLATFORM == ZP_WIN32) || (ZRTP_PLATFORM == ZP_WIN64) || (ZRTP_PLATFORM == ZP_WINCE)
99 #	if (_MSC_VER >= 1400) && (ZRTP_PLATFORM != ZP_WINCE)
100 	len = _vsnprintf_s(sline, ZRTP_LOG_BUFFER_SIZE-offset-1, ZRTP_LOG_BUFFER_SIZE-offset-1, format, marker);
101 #	else
102 	len = _vsnprintf(sline, ZRTP_LOG_BUFFER_SIZE-offset, format, marker);
103 #	endif
104 #elif (ZRTP_PLATFORM == ZP_WIN32_KERNEL)
105 	RtlStringCchVPrintfA(sline, ZRTP_LOG_BUFFER_SIZE-offset, format, marker);
106 #elif (ZRTP_PLATFORM == ZP_LINUX) || (ZRTP_PLATFORM == ZP_DARWIN) || (ZRTP_PLATFORM == ZP_BSD) || (ZRTP_PLATFORM == ZP_ANDROID)
107 	len = vsnprintf(sline, ZRTP_LOG_BUFFER_SIZE-offset, format, marker);
108 #elif (ZRTP_PLATFORM == ZP_SYMBIAN)
109 	len = vsprintf(sline, format, marker);
110 #endif
111 
112 	if ((len > 0) && log_writer) {
113 		(*log_writer)(level, log_buffer, len+offset, offset);
114 	}
115 
116 #if (defined(ZRTP_USE_STACK_MINIM) && (ZRTP_USE_STACK_MINIM == 1))
117 	zrtp_sys_free(log_buffer);
118 #endif
119 }
120 
121 
122 #if ZRTP_LOG_MAX_LEVEL >= 1
zrtp_log_1(const char * obj,const char * format,...)123 void zrtp_log_1(const char *obj, const char *format, ...)
124 {
125     va_list arg;
126     va_start(arg, format);
127     zrtp_log(0, obj, 1, format, arg);
128     va_end(arg);
129 }
zrtp_logc_1(const char * format,...)130 void zrtp_logc_1(const char *format, ...)
131 {
132     va_list arg;
133     va_start(arg, format);
134     zrtp_log(1, NULL, 1, format, arg);
135     va_end(arg);
136 }
137 
138 #endif
139 
140 #if ZRTP_LOG_MAX_LEVEL >= 2
zrtp_log_2(const char * obj,const char * format,...)141 void zrtp_log_2(const char *obj, const char *format, ...)
142 {
143     va_list arg;
144     va_start(arg, format);
145     zrtp_log(0, obj, 2, format, arg);
146     va_end(arg);
147 }
zrtp_logc_2(const char * format,...)148 void zrtp_logc_2(const char *format, ...)
149 {
150     va_list arg;
151     va_start(arg, format);
152     zrtp_log(1, NULL, 2, format, arg);
153     va_end(arg);
154 }
155 
156 #endif
157 
158 #if ZRTP_LOG_MAX_LEVEL >= 3
zrtp_log_3(const char * obj,const char * format,...)159 void zrtp_log_3(const char *obj, const char *format, ...)
160 {
161     va_list arg;
162     va_start(arg, format);
163     zrtp_log(0, obj, 3, format, arg);
164     va_end(arg);
165 }
zrtp_logc_3(const char * format,...)166 void zrtp_logc_3(const char *format, ...)
167 {
168     va_list arg;
169     va_start(arg, format);
170     zrtp_log(1, NULL, 3, format, arg);
171     va_end(arg);
172 }
173 
174 #endif
175 
176 #endif
177 
178 /*---------------------------------------------------------------------------*/
179 struct _error_strings_t
180 {
181 	zrtp_protocol_error_t code;
182 	char*				  descr;
183 };
184 
185 static const struct _error_strings_t _error_strings[] = {
186 	{zrtp_error_unknown,		"Unknown"},
187 	{zrtp_error_timeout,		"Protocol Packets Retries Timeout"},
188 	{zrtp_error_invalid_packet,	"Malformed packet (CRC OK, but wrong structure)"},
189 	{zrtp_error_software,		"Critical software error: no memory, can't call some system function, etc"},
190 	{zrtp_error_version,		"Unsupported ZRTP version"},
191 	{zrtp_error_hello_mistmatch,"Hello components mismatch "},
192 
193 	{zrtp_error_hash_unsp,		"Hash type not supported"},
194 	{zrtp_error_cipher_unsp,	"Cipher type not supported"},
195 	{zrtp_error_pktype_unsp,	"Public key exchange not supported"},
196 	{zrtp_error_auth_unsp,		"SRTP auth. tag not supported"},
197 	{zrtp_error_sas_unsp,		"SAS scheme not supported"},
198 	{zrtp_error_no_secret,		"No shared secret available, DH mode required"},
199 
200 	{zrtp_error_possible_mitm1,	"Attack DH Error: bad pvi or pvr ( == 1, 0, or p-1)"},
201 	{zrtp_error_possible_mitm2,	"Attack DH Error: hvi != hashed data"},
202 	{zrtp_error_possible_mitm3,	"Attack Received relayed SAS from untrusted MiTM"},
203 
204 	{zrtp_error_auth_decrypt,	"Auth. Error: Bad Confirm pkt HMAC"},
205 	{zrtp_error_nonse_reuse,	"Nonce reuse"},
206 	{zrtp_error_equal_zid,		"Equal ZIDs in Hello"},
207 	{zrtp_error_service_unavail,"Service unavailable"},
208 	{zrtp_error_goclear_unsp,	"GoClear packet received, but not allowed"},
209 
210 	{zrtp_error_wrong_zid,		"ZID received in new Hello doesn't equal to ZID from the previous stream"},
211 	{zrtp_error_wrong_meshmac,	"Message HMAC doesn't match with pre-received one"}
212 };
213 
zrtp_log_error2str(zrtp_protocol_error_t error)214 const char* zrtp_log_error2str(zrtp_protocol_error_t error)
215 {
216 	int i=0;
217 	for(i=0; i<22; i++) {
218 		if (error == _error_strings[i].code) {
219 			return _error_strings[i].descr;
220 		}
221 	}
222 
223 	return k_unknown;
224 }
225 
226 /*---------------------------------------------------------------------------*/
227 static char* _status_strings[zrtp_status_count] =
228 {
229 	"OK status",
230 	"General, unspecified failure",
231 	"Wrong, unsupported parameter",
232 	"Fail allocate memory",
233 	"SRTP authentication failure",
234 	"Cipher failure on RTP encrypt/decrypt",
235 	"General Crypto Algorithm failure",
236 	"SRTP can't use key any longer",
237 	"Input buffer too small",
238 	"Packet process DROP status",
239 	"Failed to open file/device",
240 	"Unable to read data from the file/stream",
241 	"Unable to write to the file/stream",
242 	"SRTP packet is out of sliding window",
243 	"RTP replay protection failed",
244 	"ZRTP replay protection failed",
245 	"ZRTP packet CRC is wrong",
246 	"Can't generate random value",
247 	"Illegal operation in current state",
248 	"Attack detected",
249 	"Function is not available in current configuration"
250 };
251 
zrtp_log_status2str(zrtp_status_t error)252 const char* zrtp_log_status2str(zrtp_status_t error)
253 {
254 	if (zrtp_status_count > error) {
255 		return _status_strings[error];
256 	} else {
257 		return k_unknown;
258 	}
259 }
260 
261 /*---------------------------------------------------------------------------*/
262 static char* _state_names[ZRTP_STATE_COUNT] =
263 {
264 	"NONE",
265 	"ACTIVE",
266 	"START",
267 	"W4HACK",
268 	"W4HELLO",
269 	"CLEAR",
270 	"SINITSEC",
271 	"INITSEC",
272 	"WCONFIRM",
273 	"W4CONFACK",
274 	"PENDSEC",
275 	"W4CONF2",
276 	"SECURE",
277 	"SASRELAY",
278 	"INITCLEAR",
279 	"PENDCLEAR",
280 	"INITERROR",
281 	"PENDERROR",
282 	"ERROR",
283 	#if (defined(ZRTP_BUILD_FOR_CSD) && (ZRTP_BUILD_FOR_CSD == 1))
284 	"DRIVINIT",
285 	"DRIVRESP",
286 	"DRIVPEND",
287 	#endif
288 	"NOZRTP"
289 };
290 
zrtp_log_state2str(zrtp_state_t state)291 const char* zrtp_log_state2str(zrtp_state_t state)
292 {
293 	if (state < ZRTP_STATE_COUNT) {
294 		return _state_names[state];
295 	} else {
296 		return k_unknown;
297 	}
298 };
299 
300 /*---------------------------------------------------------------------------*/
301 static char* _stream_mode_name[ZRTP_STREAM_MODE_COUNT] =
302 {
303 	"UNKNOWN",
304 	"CLEAR",
305 	"DH",
306 	"PRESHARED",
307 	"MULTI"
308 };
309 
zrtp_log_mode2str(zrtp_stream_mode_t mode)310 const char* zrtp_log_mode2str(zrtp_stream_mode_t mode)
311 {
312 	if (mode <  ZRTP_STREAM_MODE_COUNT) {
313 		return _stream_mode_name[mode];
314 	} else {
315 		return k_unknown;
316 	}
317 };
318 
319 /*---------------------------------------------------------------------------*/
320 static char* _msg_type_names[ZRTP_MSG_TYPE_COUNT] =
321 {
322 	"NONE",
323 	"HELLO",
324 	"HELLOACK",
325 	"COMMIT",
326 	"DH1",
327 	"DH2",
328 	"CONFIRM1",
329 	"CONFIRM2",
330 	"CONFIRMACK",
331 	"GOCLEAR",
332 	"CLEARACKE",
333 	"ERROR",
334 	"ERRORACK",
335 	"PROCESS",
336 	"SASRELAY",
337 	"RELAYACK",
338 	"PING",
339 	"PINGACK",
340 };
341 
zrtp_log_pkt2str(zrtp_msg_type_t type)342 const char* zrtp_log_pkt2str(zrtp_msg_type_t type)
343 {
344 	if (type < ZRTP_MSG_TYPE_COUNT) {
345 		return _msg_type_names[type];
346 	} else {
347 		return k_unknown;
348 	}
349 }
350 
351 /*---------------------------------------------------------------------------*/
352 static char* _event_code_name[] =
353 {
354 	"ZRTP_EVENT_UNSUPPORTED",
355 	"ZRTP_EVENT_IS_CLEAR",
356 	"ZRTP_EVENT_IS_INITIATINGSECURE",
357 	"ZRTP_EVENT_IS_PENDINGSECURE",
358 	"ZRTP_EVENT_IS_PENDINGCLEAR",
359 	"ZRTP_EVENT_NO_ZRTP",
360 	"ZRTP_EVENT_NO_ZRTP_QUICK",
361 	"ZRTP_EVENT_IS_CLIENT_ENROLLMENT",
362 	"ZRTP_EVENT_NEW_USER_ENROLLED",
363 	"ZRTP_EVENT_USER_ALREADY_ENROLLED",
364 	"ZRTP_EVENT_USER_UNENROLLED",
365 	"ZRTP_EVENT_LOCAL_SAS_UPDATED",
366 	"ZRTP_EVENT_REMOTE_SAS_UPDATED",
367 	"ZRTP_EVENT_IS_SECURE",
368 	"ZRTP_EVENT_IS_SECURE_DONE",
369 	"ZRTP_EVENT_IS_PASSIVE_RESTRICTION",
370 	"ZRTP_EVENT_PROTOCOL_ERROR",
371 	"ZRTP_EVENT_WRONG_SIGNALING_HASH",
372 	"ZRTP_EVENT_WRONG_MESSAGE_HMAC",
373 	"ZRTP_EVENT_MITM_WARNING"
374 };
375 
zrtp_log_event2str(uint8_t event)376 const char* zrtp_log_event2str(uint8_t event)
377 {
378 	if (event <= ZRTP_EVENT_WRONG_MESSAGE_HMAC) {
379 		return _event_code_name[event];
380 	} else {
381 		return k_unknown;
382 	}
383 }
384 
385 static char* _sign_role_name[] =
386 {
387 	"Unknown",
388 	"Initiator",
389 	"Responder"
390 };
391 
zrtp_log_sign_role2str(unsigned role)392 const char* zrtp_log_sign_role2str(unsigned role) {
393 	if (role < ZRTP_SIGNALING_ROLE_COUNT) {
394 		return _sign_role_name[role];
395 	} else {
396 		return k_unknown;
397 	}
398 }
399 
400 /*---------------------------------------------------------------------------*/
401 typedef struct _zrtp_aling_test
402 {
403 	uint_8t	c1;
404 	uint_8t	c2;
405 	uint_8t	c3;
406 } _zrtp_aling_test;
407 
zrtp_print_env_settings(zrtp_config_t * config)408 void zrtp_print_env_settings(zrtp_config_t* config)
409 {
410 #if (ZRTP_PLATFORM == ZP_WIN32)
411 	char* platform = "Windows 32bit";
412 #elif (ZRTP_PLATFORM == ZP_WIN32_KERNEL)
413 	char* platform = "Windows Kernel 32bit";
414 #elif (ZRTP_PLATFORM == ZP_WINCE)
415 	char* platform = "Windows CE";
416 #elif (ZRTP_PLATFORM == ZP_DARWIN)
417 	char* platform = "Darwin OS X";
418 #elif (ZRTP_PLATFORM == ZP_BSD)
419 	char* platform = "BSD";
420 #elif (ZRTP_PLATFORM == ZP_LINUX)
421 	char* platform = "Linux OS";
422 #elif (ZRTP_PLATFORM == ZP_SYMBIAN)
423 	char* platform = "Symbian OS";
424 #elif (ZRTP_PLATFORM == ZP_ANDROID)
425 	char* platform = "Android OS";
426 #endif
427 
428 	ZRTP_LOG(3,("zrtp","============================================================\n"));
429 	ZRTP_LOG(3,("zrtp","ZRTP Configuration Settings\n"));
430 	ZRTP_LOG(3,("zrtp","============================================================\n"));
431 	ZRTP_LOG(3,("zrtp","                      PLATFORM: %s\n", platform));
432 #if (ZRTP_BYTE_ORDER == ZBO_BIG_ENDIAN)
433 	ZRTP_LOG(3,("zrtp","                    BYTE ORDER: BIG ENDIAN\n"));
434 #else
435 	ZRTP_LOG(3,("zrtp","                    BYTE ORDER: LITTLE ENDIAN\n"));
436 #endif
437 	ZRTP_LOG(3,("zrtp","        ZRTP_SAS_DIGEST_LENGTH: %d\n", ZRTP_SAS_DIGEST_LENGTH));
438 	ZRTP_LOG(3,("zrtp","  ZRTP_MAX_STREAMS_PER_SESSION: %d\n", ZRTP_MAX_STREAMS_PER_SESSION));
439 	ZRTP_LOG(3,("zrtp","          ZRTP_USE_EXTERN_SRTP: %d\n", ZRTP_USE_EXTERN_SRTP));
440 	ZRTP_LOG(3,("zrtp","          ZRTP_USE_STACK_MINIM: %d\n", ZRTP_USE_STACK_MINIM));
441     ZRTP_LOG(3,("zrtp","            ZRTP_BUILD_FOR_CSD: %d\n", ZRTP_BUILD_FOR_CSD));
442     ZRTP_LOG(3,("zrtp","              ZRTP_USE_BUILTIN: %d\n", ZRTP_USE_BUILTIN));
443 	ZRTP_LOG(3,("zrtp","    ZRTP_USE_BUILTIN_SCEHDULER: %d\n", ZRTP_USE_BUILTIN_SCEHDULER));
444 	ZRTP_LOG(3,("zrtp","        ZRTP_USE_BUILTIN_CACHE: %d\n", ZRTP_USE_BUILTIN_CACHE));
445     ZRTP_LOG(3,("zrtp","            ZRTP_LOG_MAX_LEVEL: %d\n", ZRTP_LOG_MAX_LEVEL));
446 
447 	ZRTP_LOG(3,("zrtp","         sizeo of unsigned int: %d\n", sizeof(unsigned int)));
448     ZRTP_LOG(3,("zrtp","    size of unsigned long long: %d\n", sizeof(unsigned long long)));
449 	ZRTP_LOG(3,("zrtp","          sizeo of three chars: %d\n", sizeof(_zrtp_aling_test)));
450 	ZRTP_LOG(3,("zrtp","\n"));
451 	ZRTP_LOG(3,("zrtp","ZRTP Initialization Settings\n"));
452 	ZRTP_LOG(3,("zrtp","                    client ID: %s\n", config->client_id));
453 	ZRTP_LOG(3,("zrtp","                      license: %d\n", config->lic_mode));
454 	ZRTP_LOG(3,("zrtp","                         MiTM: %s\n", config->is_mitm?"ENABLED":"DIABLED"));
455 	ZRTP_LOG(3,("zrtp","                   cache path: %s\n", config->def_cache_path.length?config->def_cache_path.buffer:""));
456 }
457 
458 /*---------------------------------------------------------------------------*/
zrtp_log_print_streaminfo(zrtp_stream_info_t * info)459 void zrtp_log_print_streaminfo(zrtp_stream_info_t* info)
460 {
461 	ZRTP_LOG(3,("zrtp"," ZRTP Stream ID=%u\n", info->id));
462 	ZRTP_LOG(3,("zrtp","           mode: %s\n", zrtp_log_mode2str(info->mode)));
463 	ZRTP_LOG(3,("zrtp","          state: %s\n", zrtp_log_state2str(info->state)));
464 	ZRTP_LOG(3,("zrtp","          error: %s\n", zrtp_log_error2str(info->last_error)));
465 
466 	ZRTP_LOG(3,("zrtp","   peer passive: %s\n", info->peer_passive?"ON":"OFF"));
467 	ZRTP_LOG(3,("zrtp","  peer disclose: %s\n", info->peer_disclose?"ON":"OFF"));
468 	ZRTP_LOG(3,("zrtp","      peer mitm: %s\n", info->peer_mitm?"ON":"OFF"));
469 	ZRTP_LOG(3,("zrtp"," res allowclear: %s\n", info->res_allowclear?"ON":"OFF"));
470 }
471 
zrtp_log_print_sessioninfo(zrtp_session_info_t * info)472 void zrtp_log_print_sessioninfo(zrtp_session_info_t* info)
473 {
474 	char buffer[256];
475 
476 	ZRTP_LOG(3,("zrtp"," ZRTP Session sID=%u is ready=%s\n", info->id, info->sas_is_ready?"YES":"NO"));
477 	ZRTP_LOG(3,("zrtp","    peer client: <%s> V=<%s>\n", info->peer_clientid.buffer, info->peer_version.buffer));
478 	hex2str(info->zid.buffer, info->zid.length, buffer, sizeof(buffer));
479 	ZRTP_LOG(3,("zrtp","            zid: %s\n", buffer));
480 	hex2str(info->peer_zid.buffer, info->peer_zid.length, buffer, sizeof(buffer));
481 	ZRTP_LOG(3,("zrtp","       peer zid: %s\n", buffer));
482 	hex2str(info->zid.buffer, info->zid.length, buffer, sizeof(buffer));
483 
484 	ZRTP_LOG(3,("zrtp","     is base256: %s\n", info->sas_is_base256?"YES":"NO"));
485 	ZRTP_LOG(3,("zrtp","           SAS1: %s\n", info->sas1.buffer));
486 	ZRTP_LOG(3,("zrtp","           SAS2: %s\n", info->sas2.buffer));
487 	hex2str(info->sasbin.buffer, info->sasbin.length, buffer, sizeof(buffer));
488 	ZRTP_LOG(3,("zrtp","        bin SAS: %s\n", buffer));
489 	ZRTP_LOG(3,("zrtp","            TTL: %u\n", info->secrets_ttl));
490 
491 	ZRTP_LOG(3,("zrtp","           hash: %s\n", info->hash_name.buffer));
492 	ZRTP_LOG(3,("zrtp","         cipher: %s\n", info->cipher_name.buffer));
493 	ZRTP_LOG(3,("zrtp","           auth: %s\n", info->auth_name.buffer));
494 	ZRTP_LOG(3,("zrtp","            sas: %s\n", info->sas_name.buffer));
495 	ZRTP_LOG(3,("zrtp","            pks: %s\n", info->pk_name.buffer));
496 }
497