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 
11 #ifndef __ZRTP_TYPES_H__
12 #define __ZRTP_TYPES_H__
13 
14 #include "zrtp_config.h"
15 #include "bn.h"
16 #include "zrtp_base.h"
17 #include "zrtp_iface.h"
18 #include "zrtp_list.h"
19 #include "zrtp_legal.h"
20 #include "zrtp_string.h"
21 #include "zrtp_protocol.h"
22 
23 
24 /**
25  * \brief Defines ZRTP state-machine states
26  * \ingroup zrtp_types
27  *
28  * The conditions for switching from one state to another, and libzrtp behavior in every state is
29  * described in detail in \ref XXX and depicted in diagram XXX and XXX.
30  *
31  * The current stream state is stored in the zrtp_stream_info_t#state variable and available for
32  * reading at any time.
33  */
34 typedef enum zrtp_state_t
35 {
36 	ZRTP_STATE_NONE				= 0,
37 	ZRTP_STATE_ACTIVE,					/** Just right stream attaching, before protocol start */
38 	ZRTP_STATE_START,					/** Protocol initiated, Discovery haven't started yet */
39 	ZRTP_STATE_WAIT_HELLOACK,			/** Hello sending, waiting for HelloAck */
40 	ZRTP_STATE_WAIT_HELLO,				/** HelloAck received, Waiting for peer Hello */
41 	ZRTP_STATE_CLEAR,					/** CLEAR state */
42 	ZRTP_STATE_START_INITIATINGSECURE,	/** Starting Initiator state-machine */
43 	ZRTP_STATE_INITIATINGSECURE,		/** Commit retries, waiting for DH1 */
44 	ZRTP_STATE_WAIT_CONFIRM1,			/** DH2 retries, waiting for Confirm1 */
45 	ZRTP_STATE_WAIT_CONFIRMACK,			/** Confirm2 retries, waiting for ConfirmAck */
46 	ZRTP_STATE_PENDINGSECURE,			/** Responder state-machine, waiting for DH2 */
47 	ZRTP_STATE_WAIT_CONFIRM2,			/** Waiting for Confirm2 to finalize ZRTP exchange */
48 	ZRTP_STATE_SECURE,					/** SECURE state, call is encrypted */
49 	ZRTP_STATE_SASRELAYING,				/** SAS transferring to the remote peer (for MiTM only) */
50 	ZRTP_STATE_INITIATINGCLEAR,			/** Switching to CLEAR initated by the local endpoint */
51 	ZRTP_STATE_PENDINGCLEAR,			/** CLEAR request have been received */
52 	ZRTP_STATE_INITIATINGERROR,			/** Protocol ERROR detected on local side */
53 	ZRTP_STATE_PENDINGERROR,			/** Protocol ERROR received from the remote peer */
54 	ZRTP_STATE_ERROR,					/** Protocol ERROR state. Check zrtp_stream_info#last_error*/
55 #if (defined(ZRTP_BUILD_FOR_CSD) && (ZRTP_BUILD_FOR_CSD == 1))
56 	ZRTP_STATE_DRIVEN_INITIATOR,
57 	ZRTP_STATE_DRIVEN_RESPONDER,
58 	ZRTP_STATE_DRIVEN_PENDING,
59 #endif
60 	ZRTP_STATE_NO_ZRTP,					/** Discovery phase failed. Remote peer doesn't support ZRTP */
61 	ZRTP_STATE_COUNT
62 } zrtp_state_t;
63 
64 /**
65  * \brief Enumeration for ZRTP stream mode definition
66  * \ingroup zrtp_types
67  */
68 typedef enum zrtp_stream_mode_t
69 {
70 	ZRTP_STREAM_MODE_UNKN      = 0, /** Unused stream - unknown mode */
71 	ZRTP_STREAM_MODE_CLEAR     = 1, /** Just after stream attaching - mode is undefined */
72 	ZRTP_STREAM_MODE_DH        = 2, /** FULL DH ZRTP stream mode */
73 	ZRTP_STREAM_MODE_PRESHARED = 3, /** Preshared ZRTP stream mode */
74 	ZRTP_STREAM_MODE_MULT	   = 4, /** Multistream ZRTP stream mode */
75 	ZRTP_STREAM_MODE_COUNT 	   = 5
76 } zrtp_stream_mode_t;
77 
78 /**
79  * \brief ZRTP session profile
80  * \ingroup zrtp_types
81  * \ingroup zrtp_main_init
82  *
83  * ZRTP Sessions are configured with a profile scheme. Each profile is defined by a structure of the
84  * given type.  zrtp_profile_t contains a set of preferences for crypto components and other
85  * protocol parameters.
86  *
87  * The Crypto component choosing mechanism is as follows: both sides communicated their supported
88  * components during the "discovery phase". After that the initiator chooses the optimal
89  * intersection of components.
90  *
91  * For components identification the numerical values of the following types are used:
92  * zrtp_hash_id_t, zrtp_cipher_id_t, zrtp_atl_id_t, and zrtp_sas_id_t. The profile field responsible
93  * for components of a particular type setting is an integer-valued array where component
94  * identifiers should be placed in order of priority. 0-element is of the first priority. The list
95  * should end with ZRTP_COMP_UNKN=0.
96  *
97  * The values in the profile may be filled either by libzrtp zrtp_profile_defaults() or by the user
98  * manually.
99  *
100  * The profile is applied to the stream context on allocation by zrtp_session_init().
101  *
102  * \sa XXX
103  */
104 struct zrtp_profile_t
105 {
106 	/**
107 	 * \brief Allowclear mode flag
108 	 *
109 	 * This option means that the ZRTP peer allows SRTP termination. If allowclear is disabled, the
110 	 * ZRTP peer must stay in protected mode until the moment the ZRTP stream is shut down. When not
111 	 * in "allowclear" mode, libzrtp will reject all incoming GoClear packages and will not generate
112 	 * its own.
113 	 *
114 	 * Setting the value equal to 1 turns "allowclear" on, and 0 turns "allowclear" off. If
115 	 * "allowclear" is disabled zrtp_stream_clear() returns zrtp_status_fail.
116 	 */
117 	uint8_t				allowclear;
118 
119 	/**
120 	 * \brief ZRTP "autosecure" mode flag
121 	 *
122 	 * In "autosecure" mode, a protected connection will be initiated automatically just after
123 	 * stream start-up. If the option "autosecure" is switched off, then a secure connection can be
124 	 *initialized only by calling zrtp_stream_secure().
125 	 */
126 	uint8_t				autosecure;
127 
128 	/**
129 	 * \brief Disclose bit.
130 	 *
131 	 * This field MUST be set by user application if it's going to disclose stream keys.
132 	 */
133 	uint8_t				disclose_bit;
134 
135 	/**
136 	 * \brief Enabled Discovery Optimization
137 	 *
138 	 * ZRTP protocol specification allows to speed-up the discovery process by sending Commit
139 	 * instead of HelloAck. This is the default behavior for most of ZRTP endpoints. It allows to
140 	 * eliminate one unnecessary exchange.
141 	 *
142 	 * At other hand, this optimization may cose some problems on slow devices: using this option,
143 	 * the endpoint starts to compute DH value right after receiving remote Hello. It may take
144 	 * seginificent amount of time on slow device (of is the device is busy on other calculations).
145 	 * As all libzrtp messages are processed in single thread, while local endpoint computing DH
146 	 * it be unable to response on remote Hello-s and remote side may switch to NO_ZRTP state.
147 	 *
148 	 * Not use this option is you running libzrtp on slow device or your software supports HQ video
149 	 * conferences. Enabled by default.
150 	 */
151 	uint8_t				discovery_optimization;
152 
153 	/**
154 	 * \brief Cache time-to-live
155 	 *
156 	 * The time interval libzrtp should retain secrets. This parameter sets the secret's time to
157 	 * live in seconds. This option is global for all connections processed by the library. It is
158 	 * used together with zrtp_session_info_t#cache_ttl.
159 	 *
160 	 * ZRTP_CACHE_DEFAULT_TTL value is used by default.
161 	 */
162 	uint32_t			cache_ttl;
163 
164 	/** \brief SAS calculation scheme preferences */
165 	uint8_t				sas_schemes[ZRTP_MAX_COMP_COUNT+1];
166 
167 	/** \brief Cipher type preferences */
168 	uint8_t				cipher_types[ZRTP_MAX_COMP_COUNT+1];
169 
170 	/** \brief Public key exchange scheme preferences */
171 	uint8_t				pk_schemes[ZRTP_MAX_COMP_COUNT+1];
172 
173 	/** \brief Auth tag length preferences */
174 	uint8_t				auth_tag_lens[ZRTP_MAX_COMP_COUNT+1];
175 
176 	/**
177 	 * \brief Hash calculation scheme preferences
178 	 * \note ZRTP_HASH_SHA256 is only one hash algorithm supported by current version of libzrtp.
179 	 */
180 	uint8_t				hash_schemes[ZRTP_MAX_COMP_COUNT+1];
181 };
182 
183 /**
184  * \brief Shared secret structure
185  * \ingroup zrtp_iface_cache
186  *
187  * This structure stores ZRTP shared secret values used in the protocol.
188  */
189 struct zrtp_shared_secret_t
190 {
191     /** \brief ZRTP secret value */
192     zrtp_string64_t			value;
193 
194 	/**
195 	 * \brief last usage time-stamp in seconds.
196 	 *
197 	 * Library updates this value on generation of the new value based on previous one.
198 	 */
199 	uint32_t				lastused_at;
200 
201 	/**
202 	 * \brief TTL value in seconds.
203 	 *
204 	 * Available for reading after the Hello exchange. Updated on switching to Secure state.
205 	 */
206 	uint32_t				ttl;
207 
208 	/**
209      * \brief Loaded secret flag.
210      *
211      * When the flag is set (= 1), the secret has been loaded from the cache. Otherwise the secret
212      * has been generated.
213      * \warning For internal use only. Don't modify this flag in the application.
214      */
215     uint8_t					_cachedflag;
216 };
217 
218 /**
219  * \brief Lists MitM roles on PBX call transferring
220  *
221  * Enumeration type for the ZRTP modes based on the role of the MitM.
222  */
223 typedef enum zrtp_mitm_mode_t
224 {
225 	/** MitM is not supported or not activated. */
226 	ZRTP_MITM_MODE_UNKN = 0,
227 
228 	/**
229 	 * \brief Client-side mode called to the PBX in ZRTP trusted MiTM mode.
230 	 *
231 	 * Libzrtp activates this state on receiving an Hello, indicating that remote side is trusted
232 	 * MiTM.
233 	 */
234 	ZRTP_MITM_MODE_CLIENT,
235 
236 	/**
237 	 * \brief Server-side mode to transfer SAS to the registrant.
238 	 *
239 	 * Libzrtp switches to this state on starting zrtp_update_remote_options().
240 	 */
241 	ZRTP_MITM_MODE_RECONFIRM_SERVER,
242 	/**
243 	 * \brief Client-side mode accepted SAS transfer from the trusted MiTM.
244 	 *
245 	 * Libzrtp activates this state on receiving an SASRELAY from a trusted MiTM endpoint.
246 	 */
247 	ZRTP_MITM_MODE_RECONFIRM_CLIENT,
248 	/**
249 	 * \brief Server-side mode to accept the user's registration requests.
250 	 *
251 	 * Libzrtp switches to this state on starting a registration stream by
252 	 * zrtp_stream_registration_start() or zrtp_stream_registration_secure().
253 	 */
254 	ZRTP_MITM_MODE_REG_SERVER,
255 	/**
256 	 * \brief User-side mode to confirm the registration ritual.
257 	 *
258 	 * The library enables this state when a remote party invites it to the registration ritual
259 	 * by a special flag in the Confirm packet.
260 	 */
261 	ZRTP_MITM_MODE_REG_CLIENT
262 } zrtp_mitm_mode_t;
263 
264 
265 /** \manonly */
266 
267 
268 /*======================================================================*/
269 /*    Internal ZRTP libzrtp datatypes                                   */
270 /*======================================================================*/
271 
272 /**
273  * @defgroup types_dev libzrtp types for developers
274  * The data types used in inside libzrte. This section is for libzrtp developers
275  * @ingroup zrtp_dev
276  * \{
277  */
278 
279 
280 /**
281  * @brief Enumeration for ZRTP protocol packets type definition
282  * @warning! Don't change order of these definition without synchronizing with
283  * print* functions (see zrtp_log.h)
284  */
285 typedef enum
286 {
287 	ZRTP_UNPARSED		= -1,   /** Unparsed packet */
288 	ZRTP_NONE			= 0,	/** Not ZRTP packet */
289 	ZRTP_HELLO			= 1,    /** ZRTP protocol HELLO packet */
290 	ZRTP_HELLOACK		= 2,    /** ZRTP protocol HELLOACK packet */
291 	ZRTP_COMMIT			= 3,    /** ZRTP protocol COMMIT packet */
292 	ZRTP_DHPART1		= 4,    /** ZRTP protocol DHPART1 packet */
293 	ZRTP_DHPART2		= 5,    /** ZRTP protocol DHPART2 packet */
294 	ZRTP_CONFIRM1		= 6,    /** ZRTP protocol CONFIRM1 packet */
295 	ZRTP_CONFIRM2		= 7,    /** ZRTP protocol CONFIRM2 packet */
296 	ZRTP_CONFIRM2ACK	= 8,    /** ZRTP protocol CONFIRM2ACK packet */
297 	ZRTP_GOCLEAR		= 9,    /** ZRTP protocol GOCLEAR packet */
298 	ZRTP_GOCLEARACK		= 10,   /** ZRTP protocol GOCLEARACK packet */
299 	ZRTP_ERROR			= 11,   /** ZRTP protocol ERROR packet */
300 	ZRTP_ERRORACK		= 12,   /** ZRTP protocol ERRORACK packet */
301 	ZRTP_PROCESS		= 13,   /** This is not a packet type but type of task for scheduler */
302 	ZRTP_SASRELAY		= 14,	/** ZRTP protocol SASRELAY packet */
303 	ZRTP_RELAYACK		= 15,	/** ZRTP protocol RELAYACK packet */
304 	ZRTP_ZFONEPING		= 16,	/** Zfone3 Ping packet */
305 	ZRTP_ZFONEPINGACK	= 17,	/** Zfone3 PingAck packet */
306 	ZRTP_MSG_TYPE_COUNT	= 18
307 } zrtp_msg_type_t;
308 
309 
310 /**
311  * @brief enumeration for protocol state-machine roles
312  * Protocol role fully defines it's behavior. ZRTP peer chooses a role according
313  * to specification. For details see internal developers documentation
314  */
315 typedef enum zrtp_statemachine_type_t
316 {
317 	ZRTP_STATEMACHINE_NONE		= 0,	/** Unknown type. Used as error value */
318 	ZRTP_STATEMACHINE_INITIATOR	= 1,	/** Defines initiator's protocol logic */
319 	ZRTP_STATEMACHINE_RESPONDER	= 2		/** Defines responder's protocol logic */
320 } zrtp_statemachine_type_t;
321 
322 #define    ZRTP_BIT_RS1		0x02
323 #define    ZRTP_BIT_RS2		0x04
324 #define    ZRTP_BIT_AUX		0x10
325 #define    ZRTP_BIT_PBX		0x20
326 
327 /**
328  * @brief Library global context
329  * Compilers and linkers on some operating systems don't support the declaration
330  * of global variables in c files. Storing a context allows us to solve this
331  * problem in a way that unifies component use. The context is created by calling
332  * zrtp_init(), and is destroyed with zrtp_down(). It contains data necessary
333  * for crypto-component algorithms, including hash schemes, cipher types, SAS
334  * schemes etc. Context data can be divided into three groups:
335  *  - ID of client ZRTP peer;
336  *  - RNG related fields (hash context for entropy computing);
337  *  - DH scheme related fields(internal data used for DH exchange);
338  *  - headers of the lists of every crypto-component type used for component
339  *    management.
340  * All of this data, except for "RNG related fields", is for internal use only
341  * and set automatically. All that is needed is to link every created session
342  * to global context.
343  * @sa zrtp_init() zrtp_down() zrtp_session_init()
344  */
345 struct zrtp_global_t
346 {
347 	uint32_t				lic_mode;			/** ZRTP license mode. */
348     zrtp_string16_t			client_id;			/** Local ZRTP client ID. */
349 	uint8_t					is_mitm;			/** Flags defines that the local endpoint acts as ZRTP MiTM. */
350     MD_CTX					rand_ctx;			/** Hash context for entropy accumulation for the RNG unit. */
351     uint8_t					rand_initialized;	/** RNG unit initialization flag. */
352 	zrtp_string256_t		def_cache_path;		/** Full path to ZRTP cache file. */
353 	unsigned				cache_auto_store;	/** Set when user wants libzrtp to flush the cache once it changed */
354     zrtp_mutex_t*			rng_protector;		/** This object is used to protect the shared RNG hash zrtp#rand_ctx */
355     struct BigNum			one;				/** This section provides static data for DH3K and DH4K components */
356     struct BigNum			G;
357 	struct BigNum			P_2048;
358     struct BigNum			P_2048_1;
359     struct BigNum			P_3072;
360     struct BigNum			P_3072_1;
361 	uint8_t					P_2048_data[256];
362     uint8_t					P_3072_data[384];
363     mlist_t					hash_head;			/** Head of hash components list */
364     mlist_t					cipher_head;		/** Head of ciphers list */
365     mlist_t					atl_head;			/** Head of ATL components list */
366     mlist_t					pktype_head;		/** Head of public key exchange schemes list */
367     mlist_t					sas_head;			/** SAS schemes list */
368     void*					srtp_global;		/** Storage for some SRTP global data */
369     mlist_t					sessions_head;		/** Head of ZRTP sessions list */
370 	uint32_t				sessions_count;		/** Global sessions count used to create ZRTP session IDs. For debug purposes mostly. */
371 	uint32_t				streams_count;		/** Global streams count used to create ZRTP session IDs. For debug purposes mostly. */
372     zrtp_mutex_t*			sessions_protector;	/** This object is used to synchronize sessions list operations */
373 	zrtp_callback_t			cb;					/** Set of feedback callbacks used by libzrtp to interact with the user-space.*/
374 };
375 
376 
377 /**
378  * @brief RTP packet structure used in libzrtp
379  * Used for conveniently working with RTP/ZRTP packets. A binary RTP/ZRTP
380  * packet is converted into a zrtp_rtp_info_t structure before processing by
381  * _zrtp_packet_preparse()
382  */
383 typedef struct zrtp_rtp_info_t
384 {
385 	/** Packet length in bytes */
386 	uint32_t				*length;
387 
388 	/** Pointer to the RTP/ZRTP packet body */
389 	char					*packet;
390 
391 	/** Pointer to ZRTP Message part (skip ZRTP transport header part) */
392 	void					*message;
393 
394 	/** ZRTP packet type (ZRTP_NONE in case of non command packet) */
395 	zrtp_msg_type_t			type;
396 
397 	/** Straightened RTP/ZRTP sequence number in host mode */
398 	uint32_t				seq;
399 
400 	/** RTP SSRC/ZRTP in network mode */
401 	uint32_t				ssrc;
402 } zrtp_rtp_info_t;
403 
404 
405 /**
406  * @brief Retained secrets container
407  * Contains the session's shared secret values and related flags restored from
408  * the cache. Every subsequent stream within a session uses these values
409  * through @ref zrtp_proto_secret_t pointers. By definition, different ZRTP
410  * streams can't change secret values. Secret flags are protected against race
411  * conditions by the mutex \c _protector. For internal use only.
412  */
413 typedef struct zrtp_secrets_t
414 {
415 	/** First retained secret RS1. */
416     zrtp_shared_secret_t    *rs1;
417 
418 	/** Second retained secret RS1. */
419     zrtp_shared_secret_t    *rs2;
420 
421 	/** User-defined secret. */
422     zrtp_shared_secret_t    *auxs;
423 
424 	/** PBX Secret for trusted MiTMs. */
425     zrtp_shared_secret_t    *pbxs;
426 
427 	/** Bit-map to summarize shared secrets "Cached" flags. */
428     uint32_t				cached;
429 	uint32_t				cached_curr;
430 
431 	/** Bit-map to summarize shared secrets "Matches" flags. */
432     uint32_t				matches;
433 	uint32_t				matches_curr;
434 
435 	/** Bit-map to summarize shared secrets "Wrongs" flags. */
436 	uint32_t				wrongs;
437 	uint32_t				wrongs_curr;
438 
439 	/** This flag equals one if the secrets have been uploaded from the cache. */
440     uint8_t					is_ready;
441 } zrtp_secrets_t;
442 
443 
444 /**
445  * @brief Protocol shared secret
446  * Wrapper around the session shared secrets \ref zrtp_shared_secret. Used
447  * for ID storing and secret sorting according to ZRTP ID sec. 5.4.4.
448  */
449 typedef struct zrtp_proto_secret_t
450 {
451 	/** Local-side secret ID */
452 	zrtp_string8_t			id;
453 
454 	/** Remote-side secret ID */
455 	zrtp_string8_t			peer_id;
456 
457 	/** Pointer to the binary value and set of related flags */
458 	zrtp_shared_secret_t	*secret;
459 } zrtp_proto_secret_t;
460 
461 
462 /**
463  * @brief ZRTP messages cache
464  * This structure contains ZRTP messages prepared for sending or received from
465  * the other side. This scheme allows speed-ups the resending of packets and
466  * computing message hashes, and makes resending thread-safe. Besides packets,
467  * tasks retries are stored as well.
468  */
469 typedef struct zrtp_stream_mescache_t
470 {
471 	zrtp_packet_Hello_t		peer_hello;
472 	zrtp_packet_Hello_t		hello;
473 	zrtp_packet_GoClear_t   goclear;
474 	zrtp_packet_Commit_t    peer_commit;
475 	zrtp_packet_Commit_t    commit;
476 	zrtp_packet_DHPart_t    peer_dhpart;
477 	zrtp_packet_DHPart_t    dhpart;
478 	zrtp_packet_Confirm_t   confirm;
479 	zrtp_string32_t			h0;
480 	zrtp_packet_Confirm_t   peer_confirm;
481 	zrtp_packet_Error_t     error;
482 	zrtp_packet_SASRelay_t  sasrelay;
483 
484 	zrtp_retry_task_t       hello_task;
485 	zrtp_retry_task_t       goclear_task;
486 	zrtp_retry_task_t       dh_task;
487 	zrtp_retry_task_t       commit_task;
488 	zrtp_retry_task_t       dhpart_task;
489 	zrtp_retry_task_t       confirm_task;
490 	zrtp_retry_task_t       error_task;
491 	zrtp_retry_task_t       errorack_task;
492 	zrtp_retry_task_t       sasrelay_task;
493 
494 	/*!
495 	 * Hash pre-image of the remote party Hello retrieved from Signaling. When
496 	 * user calls zrtp_signaling_hash_set() libzrtp stores hash value in this
497 	 * variable and checks all incoming Hello-s to prevent DOS attacks.
498 	 */
499 	zrtp_string64_t			signaling_hash;
500 } zrtp_stream_mescache_t;
501 
502 
503 /**
504  * @brief Crypto context for Diffie-Hellman calculations
505  * Used only by DH streams to store Diffie-Hellman calculations. Allocated on
506  * protocol initialization and released on switching to SECURE mode.
507  */
508 typedef struct zrtp_dh_crypto_context_t
509 {
510 	/** DH secret value */
511 	struct BigNum			sv;
512 
513 	/** DH public value */
514 	struct BigNum			pv;
515 
516 	/** DH public value recalculated for remote side */
517 	struct BigNum			peer_pv;
518 
519 	/** DH shared secret. DHSS = hash(DHResult) */
520 	zrtp_string64_t			dhss;
521 
522 	unsigned int			initialized_with;
523 } zrtp_dh_crypto_context_t;
524 
525 
526 /*!
527  * \brief Crypto context for ECDSA calculations
528  * Used to store ECDSA keys and calculations. Allocated on
529  * protocol initialization and released on switching to SECURE mode.
530  */
531 typedef struct zrtp_dsa_crypto_context_t
532 {
533 	struct BigNum			sv;		/*!< DSA secret value */
534 	struct BigNum			pv;		/*!< DSA public value */
535 	struct BigNum			peer_pv;/*!< DSA public value for some remote side */
536 } zrtp_dsa_crypto_context_t;
537 
538 
539 /**
540  * @brief Protocol crypto context
541  * Used as temporary storage for ZRTP crypto data during protocol running.
542  * Unlike \ref zrtp_stream_crypto_t this context is needed only during key
543  * negotiation and destroyed on switching to SECURE state.
544  */
545 typedef struct zrtp_proto_crypto_t
546 {
547 	/** ZRTP */
548 	zrtp_string128_t		kdf_context;
549 
550 	/** ZRTP stream key */
551 	zrtp_string64_t			s0;
552 
553 	/** Local hvi value for the hash commitment: hvi or nonce for Multistream. */
554 	zrtp_string64_t			hv;
555 
556 	/** Remove hvi value for the hash commitment: hvi or nonce for Multistream. */
557 	zrtp_string64_t			peer_hv;
558 
559 	/** Total messages hash. See ZRTP ID 5.4.4/5.5.4 */
560 	zrtp_string64_t			mes_hash;
561 
562 	/** RS1 */
563 	zrtp_proto_secret_t		rs1;
564 
565 	/** RS2 */
566 	zrtp_proto_secret_t		rs2;
567 
568 	/** User-Defined secret */
569 	zrtp_proto_secret_t		auxs;
570 
571 	/** PBX secret */
572 	zrtp_proto_secret_t		pbxs;
573 } zrtp_proto_crypto_t;
574 
575 /*!
576  * \brief ZRTP protocol structure
577  * Protocol structure is responsible for ZRTP protocol logic (CLEAR-SECURE
578  * switching) and RTP media encrypting/decrypting. The protocol is created
579  * right after the discovery phase and destroyed on stream closing.
580  */
581 struct zrtp_protocol_t
582 {
583 	/** Protocol mode: responder or initiator. */
584 	zrtp_statemachine_type_t type;
585 
586 	/** Context for storing protocol crypto data. */
587 	zrtp_proto_crypto_t*	cc;
588 
589 	/** SRTP crypto engine */
590 	zrtp_srtp_ctx_t*		_srtp;
591 
592 	/** Back-pointer to ZRTP stream context. */
593 	zrtp_stream_t		*context;
594 };
595 
596 /**
597  * @brief Stream-persistent crypto options.
598  * Unlike \ref zrtp_proto_crypto_t these data are kept after switching to Secure
599  * state or stopping the protocol; used to sign/verify Confirm and GoClear packets.
600  */
601 typedef struct zrtp_stream_crypto_t
602 {
603 	/** Local side hmackey value. */
604 	zrtp_string64_t			hmackey;
605 
606 	/** Remote side hmackey value. */
607 	zrtp_string64_t			peer_hmackey;
608 
609 	/** Local side ZRTP key for Confirms protection. */
610 	zrtp_string64_t			zrtp_key;
611 
612 	/** Remote side ZRTP key for Confirms verification. */
613 	zrtp_string64_t			peer_zrtp_key;
614 } zrtp_stream_crypto_t;
615 
616 
617 /**
618  * @brief stream media context. Contains all RTP media-related information.
619  */
620 typedef struct zrtp_media_context_t
621 {
622 	/** The highest ZRTP message sequence number received. */
623 	uint32_t				high_in_zrtp_seq;
624 
625 	/** The last ZRTP message sequence number sent. */
626 	uint32_t				high_out_zrtp_seq;
627 
628 	/** The highest	RTP media sequence number received; used by SRTP. */
629 	uint32_t				high_in_media_seq;
630 
631 	/** The highest RTP media sequence number sent; used by SRTP. */
632 	uint32_t				high_out_media_seq;
633 
634 	/** SSRC of the RTP media stream associated with the current ZRTP stream. */
635 	uint32_t				ssrc;
636 } zrtp_media_context_t;
637 
638 /*!
639  * \brief ZRTP stream context
640  * \warning Fields with prefix "_" are for internal use only.
641  */
642 struct zrtp_stream_t
643 {
644 	/*! Stream unique identifier for debug purposes */
645 	zrtp_id_t				id;
646 
647 	/*!
648 	 * \brief Stream mode
649 	 * This field defines libzrtp behavior related to specified contexts. See
650 	 * <A HREF="http://zfoneproject.com/zrtp_ietf.html">"ZRTP Internet Draft"</A>
651 	 * and \ref usage for additional information about stream types and their
652 	 * processing logic.
653 	 */
654 	zrtp_stream_mode_t		mode;
655 
656 	/*!
657 	 * \brief Defines ZRTP role in trusted MitM scheme.
658 	 * The value of this mode determines the behavior of the ZRTP machine
659 	 * according to it's role in the MitM scheme.  Initially the mode is
660 	 * ZRTP_MITM_MODE_UNKN and then changes on protocol running.
661 	 */
662 	zrtp_mitm_mode_t		mitm_mode;
663 
664 	/*!
665 	 * \brief Previous ZRTP protocol states
666 	 * Used in analysis to determine the reason for a switch from one state to
667 	 * another. Enabled by _zrtp_change_state(.
668 	 */
669 	zrtp_state_t			prev_state;
670 
671 	/** 1 means that peer Hello have been raceived within current ZRTP session */
672 	uint8_t					is_hello_received;
673 
674 	/*!< Reflects current state of ZRTP protocol */
675 	zrtp_state_t			state;
676 
677 	/**
678 	 * @brief Persistent stream crypto options.
679 	 * Stores persistent crypto data needed after Confirmation. This data can be
680 	 * cleared only when the stream is destroyed.
681 	 */
682 	zrtp_stream_crypto_t	cc;
683 
684 	/** DH crypto context used in PK calculations */
685 	zrtp_dh_crypto_context_t dh_cc;
686 
687 	/*!
688 	 * \brief Pointer to the ZRTP protocol implementation
689 	 * The protocol structure stores all crypto data during the securing
690 	 * procedure.  After switching to SECURE state the protocol clears all
691 	 * crypto sources and performs traffic encryption/decryption.
692 	 */
693 	zrtp_protocol_t			*protocol;
694 
695 	/*!< Holder for RTP/ZRTP media stream options. */
696 	zrtp_media_context_t	media_ctx;
697 
698 	/*!< ZRTP messages and task retries cache */
699 	zrtp_stream_mescache_t	messages;
700 
701 	/*!
702 	 * Current value of "allowclear" option exchanged during ZRTP negotiation.
703 	 * Available for reading in SECURE state.
704 	 */
705 	uint8_t					allowclear;
706 
707 	/*!
708 	 * This flag shows when remote side is "passive" (has license mode PASSIVE)
709 	 * Available for reading in CLEAR state.
710 	 */
711 	uint8_t					peer_passive;
712 
713 	/*!
714 	 * \brief actual lifetime of stream secrets
715 	 * This variable contains the interval for retaining secrets within an
716 	 * established stream. In accordance with <A
717 	 * HREF="http://zfoneproject.com/zrtp_ietf.html">"ZRTP Internet Draft"</A>
718 	 * this value is calculated as the minimal of local and remote TTLs after
719 	 * confirmation. Value is given in seconds and can be read in the SECURE
720 	 * state. It may be used in displaying session parameters.
721 	 */
722 	uint32_t				cache_ttl;
723 
724 	/*!
725 	 * \brief Peer disclose bit Indicates the ability of the remote side to
726 	 * disclose its session key.  Specifies that the remote side allows call
727 	 * monitoring. If this flag is set, the end user must be informed. It can
728 	 * be read in the SECURE state.
729 	 */
730 	uint8_t					peer_disclose_bit;
731 
732 	/*!
733 	 * \brief Last protocol error code
734 	 * If there is a mistake in running the protocol, zrtp_event_callback()
735 	 * will  be called and the required error code will be set to this field.
736 	 * An error code is the numeric representation of ZRTP errors defined in
737 	 * the draft. All error codes are defined by \ref zrtp_protocol_error_t.
738 	 */
739 	zrtp_protocol_error_t	last_error;
740 
741 	/**
742 	 * Duplicates MiTM flag from peer Hello message
743 	 */
744 	uint8_t					peer_mitm_flag;
745 
746 	/**
747 	 * Duplicates U flag from peer Hello message
748 	 */
749 	uint8_t					peer_super_flag;
750 
751 	/*!
752 	 * \brief Pointer to the concurrent DH stream
753 	 * If Commit messages are sent by both ZRTP endpoints at the same time, but
754 	 * are received in different media streams, "tie-breaking" rules apply - the
755 	 * Commit message with the lowest hvi value is discarded and the other side
756 	 * becomes the initiator. The media stream in which the Commit was sent will
757 	 * proceed through the ZRTP exchange while the media stream with the discarded
758 	 * Commit must wait for the completion of the other ZRTP exchange. A pointer
759 	 * to that "waiting" stream is stored in \c _concurrent. When the running
760 	 * stream is switched to "Initiating Secure" the concurrent stream is resumed.
761 	 */
762 	zrtp_stream_t			*concurrent;
763 
764 	/** Back-pointer to the ZRTP global data */
765 	zrtp_global_t			*zrtp;
766 
767 	/** Pointer to parent session context. Used for back capability */
768 	zrtp_session_t			*session;
769 
770 	/*!< Public key exchange component used within current stream */
771 	zrtp_pk_scheme_t		*pubkeyscheme;
772 
773 	/*!
774 	 * Pointer to the user data. This pointer can be used for fast access to
775 	 * some additional data attached to this ZRTP stream by the user application
776 	 */
777 	void					*usr_data;
778 
779 	/*!
780 	 * Pointer to the peer stream during a trusted MiTM call.
781 	 * @sa zrtp_link_mitm_calls()
782 	 */
783 	zrtp_stream_t			*linked_mitm;
784 
785 	/*!
786 	 * \brief Stream data protector
787 	 * A mutex is used to avoid race conditions during asynchronous calls
788 	 * (zrtp_stream_secure(), zrtp_stream_clear() etc.) in parallel to the main
789 	 * processing loop zrtp_process_rtp/srtp().
790 	 */
791 	zrtp_mutex_t*			stream_protector;
792 };
793 
794 
795 /*!
796  * \brief ZRTP session context
797  * Describes the state of the ZRTP session. Stores data necessary and sufficient
798  * for processing ZRTP sessions. Encapsulates ZRTP streams and all crypto-data.
799  */
800 struct zrtp_session_t
801 {
802 	/*! Session unique identifier for debug purposes */
803 	zrtp_id_t				id;
804 
805 	/*!
806 	 * \brief Local-side ZID
807 	 * The unique 12-characters string that identifies the local ZRTP endpoint.
808 	 * It must be generated by the user application on installation and used
809 	 * permanently for every ZRTP session. This ID allows remote peers to
810 	 * recognize this ZRTP endpoint.
811 	 */
812 	zrtp_string16_t			zid;
813 
814 	/*!
815 	 * \brief Remote-side ZID
816 	 * Extracted from the Hello packet of the very first ZRTP stream. Uniquely
817 	 * identifies the remote ZRTP peer. Used in combination with the local zid
818 	 * to restore secrets and other data from the previous call. Available for
819 	 * reading after the discovering phase.
820 	 */
821 	zrtp_string16_t			peer_zid;
822 
823 	/*!< ZRTP profile, defined crypto options and behavior for every stream within current session */
824 	zrtp_profile_t			profile;
825 
826 	/*
827 	 * Signaling Role which protocol was started with, one of zrtp_signaling_role_t values.
828 	 */
829 	unsigned				signaling_role;
830 
831 	/*!
832 	 * \brief Set of retained secrets and flags for the current ZRTP session.
833 	 * libzrtp uploads secrets and flags from the cache on the very first
834 	 * stream within every ZRTP session.
835 	 */
836 	zrtp_secrets_t			secrets;
837 
838 	/*!< ZRTP session key used to extend ZRTP session without additional DH exchange */
839 	zrtp_string64_t			zrtpsess;
840 
841 	/** First SAS base32/256 string */
842 	zrtp_string16_t			sas1;
843 
844 	/** Second SAS 256 string */
845 	zrtp_string16_t			sas2;
846 
847 	/** Binary SAS digest (ZRTP_SAS_DIGEST_LENGTH bytes) */
848 	zrtp_string32_t			sasbin;
849 
850 	/*!< Back-pointer to the ZRTP global data */
851 	zrtp_global_t			*zrtp;
852 
853 	/*!< Back-pointer to user data associated with this session context. */
854 	void					*usr_data;
855 
856 	/** Hash component used within current session */
857 	zrtp_hash_t				*hash;
858 
859 	/** Cipher component used within current session */
860 	zrtp_cipher_t			*blockcipher;
861 
862 	/** SRTP authentication component used within current session */
863 	zrtp_auth_tag_length_t	*authtaglength;
864 
865 	/** SAS scheme component used within current session */
866 	zrtp_sas_scheme_t		*sasscheme;
867 
868 	/** List of ZRTP streams attached to the session. */
869 	zrtp_stream_t			streams[ZRTP_MAX_STREAMS_PER_SESSION];
870 
871 	/** This object is used to synchronize all stream list operations */
872 	zrtp_mutex_t*			streams_protector;
873 
874 	/** Prevents race conditions if streams start simultaneously. */
875 	zrtp_mutex_t*			init_protector;
876 
877 	/**
878 	 * This flag indicates that possible MiTM attach was detected during the protocol exchange.
879 	 */
880 	uint8_t					mitm_alert_detected;
881 
882 	mlist_t					_mlist;
883 };
884 
885 /*! \} */
886 
887 
888 /*===========================================================================*/
889 /* Data types and definitions for SRTP                                       */
890 /*===========================================================================*/
891 
892 #if ZRTP_BYTE_ORDER == ZBO_LITTLE_ENDIAN
893 
894 /**
895  * RTP header structure
896  * @ingroup dev_srtp
897  */
898 typedef struct
899 {
900   uint16_t		cc:4;       /** CSRC count             */
901   uint16_t		x:1;        /** header extension flag  */
902   uint16_t		p:1;        /** padding flag           */
903   uint16_t		version:2;  /** protocol version		*/
904   uint16_t		pt:7;       /** payload type           */
905   uint16_t		m:1;        /** marker bit             */
906   uint16_t		seq;        /** sequence number        */
907   uint32_t		ts;         /** timestamp              */
908   uint32_t		ssrc;       /** synchronization source */
909 } zrtp_rtp_hdr_t;
910 
911 /**
912  * RTCP header structure
913  * @ingroup dev_srtp
914  */
915 typedef struct
916 {
917   unsigned char	rc:5;       /** reception report count */
918   unsigned char p:1;        /** padding flag           */
919   unsigned char version:2;  /** protocol version       */
920   unsigned char pt:8;       /** payload type           */
921   uint16_t		len;		/** length                 */
922   uint32_t		ssrc;		/** synchronization source */
923 } zrtp_rtcp_hdr_t;
924 
925 typedef struct
926 {
927   unsigned int	index:31;	/** srtcp packet index in network order! */
928   unsigned int	e:1;        /** encrypted? 1=yes */
929                             /** optional mikey/etc go here */
930                             /** and then the variable-length auth tag */
931 } zrtp_rtcp_trailer_t;
932 
933 #else
934 
935 /**
936  * RTP header structure
937  * @ingroup dev_srtp
938  */
939 typedef struct
940 {
941   uint16_t		version:2;	/** protocol version       */
942   uint16_t		p:1;		/** padding flag           */
943   uint16_t		x:1;		/** header extension flag  */
944   uint16_t		cc:4;		/** CSRC count             */
945   uint16_t		m:1;		/** marker bit             */
946   uint16_t		pt:7;		/** payload type           */
947   uint16_t		seq;		/** sequence number        */
948   uint32_t		ts;			/** timestamp              */
949   uint32_t		ssrc;		/** synchronization source */
950 } zrtp_rtp_hdr_t;
951 
952 /**
953  * RTCP header structure
954  * @ingroup dev_srtp
955  */
956 typedef struct
957 {
958   unsigned char	version:2;	/** protocol version       */
959   unsigned char p:1;        /** padding flag           */
960   unsigned char rc:5;       /** reception report count */
961   unsigned char pt:8;       /** payload type           */
962   uint16_t		len;        /** length                 */
963   uint32_t		ssrc;       /** synchronization source */
964 } zrtp_rtcp_hdr_t;
965 
966 typedef struct
967 {
968   unsigned int e:1;         /** encrypted? 1=yes */
969   unsigned int index:31;    /** srtcp packet index */
970 } zrtp_rtcp_trailer_t;
971 
972 #endif
973 
974 /**
975  * RTP header extension structure
976  * @ingroup dev_srtp
977  */
978 typedef struct
979 {
980   uint16_t		profile_specific; /** profile-specific info               */
981   uint16_t		length;           /** number of 32-bit words in extension */
982 } zrtp_rtp_hdr_xtnd_t;
983 
984 
985 /** \endmanonly */
986 
987 #endif  /* __ZRTP_TYPES_H__ */
988