1 /*
2   Copyright (C) 2006-2013 Werner Dittmann
3 
4   This program is free software: you can redistribute it and/or modify
5   it under the terms of the GNU Lesser General Public License as published by
6   the Free Software Foundation, either version 3 of the License, or
7   (at your option) any later version.
8 
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13 
14   You should have received a copy of the GNU General Public License
15   along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17 
18 #ifndef _ZRTP_H_
19 #define _ZRTP_H_
20 /**
21  * @file ZRtp.h
22  * @brief The ZRTP main engine
23  * @defgroup GNU_ZRTP The GNU ZRTP C++ implementation
24  * @{
25  */
26 
27 #include <cstdlib>
28 
29 #include <libzrtpcpp/ZrtpPacketHello.h>
30 #include <libzrtpcpp/ZrtpPacketHelloAck.h>
31 #include <libzrtpcpp/ZrtpPacketCommit.h>
32 #include <libzrtpcpp/ZrtpPacketDHPart.h>
33 #include <libzrtpcpp/ZrtpPacketConfirm.h>
34 #include <libzrtpcpp/ZrtpPacketConf2Ack.h>
35 #include <libzrtpcpp/ZrtpPacketGoClear.h>
36 #include <libzrtpcpp/ZrtpPacketClearAck.h>
37 #include <libzrtpcpp/ZrtpPacketError.h>
38 #include <libzrtpcpp/ZrtpPacketErrorAck.h>
39 #include <libzrtpcpp/ZrtpPacketPing.h>
40 #include <libzrtpcpp/ZrtpPacketPingAck.h>
41 #include <libzrtpcpp/ZrtpPacketSASrelay.h>
42 #include <libzrtpcpp/ZrtpPacketRelayAck.h>
43 #include <libzrtpcpp/ZrtpCallback.h>
44 #include <libzrtpcpp/ZIDCache.h>
45 
46 #include <cryptcommon/skeinApi.h>
47 #ifdef ZRTP_OPENSSL
48 #include <openssl/crypto.h>
49 #include <openssl/sha.h>
50 #else
51 #include <zrtp/crypto/sha2.h>
52 #endif
53 
54 #ifndef SHA256_DIGEST_LENGTH
55 #define SHA256_DIGEST_LENGTH 32
56 #endif
57 
58 // Prepare to support digest algorithms up to 512 bit (64 bytes)
59 #define MAX_DIGEST_LENGTH       64
60 #define IMPL_MAX_DIGEST_LENGTH  64
61 
62 // max. number of parallel supported ZRTP protocol versions.
63 #define MAX_ZRTP_VERSIONS       2
64 
65 // currently only 1.10 supported
66 #define SUPPORTED_ZRTP_VERSIONS       1
67 
68 // Integer representation of highest supported ZRTP protocol version
69 #define HIGHEST_ZRTP_VERION    12
70 
71 class __EXPORT ZrtpStateClass;
72 class ZrtpDH;
73 class ZRtp;
74 
75 /**
76  * The main ZRTP class.
77  *
78  * This is the main class of the RTP/SRTP independent part of the GNU
79  * ZRTP. It handles the ZRTP HMAC, DH, and other data management. The
80  * user of this class needs to know only a few methods and needs to
81  * provide only a few external functions to connect to a Timer
82  * mechanism and to send data via RTP and SRTP. Refer to the
83  * ZrtpCallback class to get detailed information regading the
84  * callback methods required by GNU RTP.
85  *
86  * The class ZrtpQueue is the GNU ccRTP specific implementation that
87  * extends standard ccRTP RTP provide ZRTP support. Refer to the
88  * documentation of ZrtpQueue to get more information about the usage
89  * of ZRtp and associated classes.
90  *
91  * The main entry into the ZRTP class is the processExtensionHeader()
92  * method.
93  *
94  * This class does not directly handle the protocol states, timers,
95  * and packet resend. The protocol state engine is responsible for
96  * these actions.
97  *
98  * Example how to use ZRtp:
99  *<pre>
100  *    zrtpEngine = new ZRtp((uint8_t*)ownZid, (ZrtpCallback*)this, idString);
101  *    zrtpEngine->startZrtpEngine();
102  *</pre>
103  * @see ZrtpCallback
104  *
105  * @author Werner Dittmann <Werner.Dittmann@t-online.de>
106  */
107 class __EXPORT ZRtp {
108 
109     public:
110 
111     typedef enum _secrets {
112         Rs1 = 1,
113         Rs2 = 2,
114         Pbx = 4,
115         Aux = 8
116     } secrets;
117 
118     typedef struct _zrtpInfo {
119         int32_t secretsCached;
120         int32_t secretsMatched;
121         int32_t secretsMatchedDH;
122         const char *hash;
123         const char *cipher;
124         const char *pubKey;
125         const char *sasType;
126         const char *authLength;
127     } zrtpInfo;
128 
129     /**
130      * Faster access to Hello packets with different versions.
131      */
132     typedef struct _HelloPacketVersion {
133         int32_t version;
134         ZrtpPacketHello* packet;
135         uint8_t helloHash[IMPL_MAX_DIGEST_LENGTH];
136     } HelloPacketVersion;
137 
138     /**
139      * Constructor intializes all relevant data but does not start the
140      * engine.
141      */
142     ZRtp(uint8_t* myZid, ZrtpCallback* cb, std::string id,
143          ZrtpConfigure* config, bool mitmm= false, bool sasSignSupport= false);
144 
145     /**
146      * Destructor cleans up.
147      */
148     ~ZRtp();
149 
150     /**
151      * Kick off the ZRTP protocol engine.
152      *
153      * This method calls the ZrtpStateClass#evInitial() state of the state
154      * engine. After this call we are able to process ZRTP packets
155      * from our peer and to process them.
156      */
157     void startZrtpEngine();
158 
159     /**
160      * Stop ZRTP security.
161      *
162      */
163     void stopZrtp();
164 
165     /**
166      * Process ZRTP message.
167      *
168      * The method takes the data and forwards it to the ZRTP state engine for further
169      * processing. It's the caller's duty to check the ZRTP CRC and the ZRTP magic
170      * cookie before calling this function.
171      *
172      * @param extHeader
173      *    A pointer to the first byte of the ZRTP message. Refer to RFC6189.
174      * @param peerSSRC
175      *    The peer's SSRC.
176      * @param length
177      *     of the received data packet, this includes the RTP like header
178      *     and the ZRTP CRC field - used to do santity checks.
179      *
180      * @return
181      *    Code indicating further packet handling, see description above.
182      */
183     void processZrtpMessage(uint8_t *extHeader, uint32_t peerSSRC, size_t length);
184 
185     /**
186      * Process a timeout event.
187      *
188      * We got a timeout from the timeout provider. Forward it to the
189      * protocol state engine.
190      *
191      */
192     void processTimeout();
193 
194     /**
195      * Check for and handle GoClear ZRTP packet header.
196      *
197      * This method checks if this is a GoClear packet. If not, just return
198      * false. Otherwise handle it according to the specification.
199      *
200      * @param extHeader
201      *    A pointer to the first byte of the extension header. Refer to
202      *    RFC3550.
203      * @return
204      *    False if not a GoClear, true otherwise.
205      */
206     bool handleGoClear(uint8_t *extHeader);
207 
208     /**
209      * Set the auxilliary secret.
210      *
211      * Use this method to set the auxilliary secret data. Refer to ZRTP
212      * specification, chapter 4.3 ff
213      *
214      * @param data
215      *     Points to the secret data.
216      * @param length
217      *     Length of the auxilliary secrect in bytes
218      */
219     void setAuxSecret(uint8_t* data, int32_t length);
220 
221     /**
222      * Check current state of the ZRTP state engine
223      *
224      * @param state
225      *    The state to check.
226      * @return
227      *    Returns true id ZRTP engine is in the given state, false otherwise.
228      */
229     bool inState(int32_t state);
230 
231     /**
232      * Set SAS as verified.
233      *
234      * Call this method if the user confirmed (verfied) the SAS. ZRTP
235      * remembers this together with the retained secrets data.
236      */
237     void SASVerified();
238 
239     /**
240      * Reset the SAS verfied flag for the current active user's retained secrets.
241      *
242      */
243     void resetSASVerified();
244 
245      /**
246       * Check if SAS verfied by both parties, valid after received Confirm1 or Confirm2.
247       *
248       */
249      bool isSASVerified();
250 
251      /**
252      * Get the ZRTP Hello Hash data.
253      *
254      * Use this method to get the ZRTP Hello hash data. The method
255      * returns the data as a string containing the ZRTP protocol version and
256      * hex-digits.
257      *
258      * The index defines which Hello packet to use. Each supported ZRTP procol version
259      * uses a different Hello packet and thus computes different hashes.
260      *
261      * Refer to ZRTP specification, chapter 8.
262      *
263      * @param index
264      *     Hello hash of the Hello packet identfied by index. Index must be 0 <= index < MAX_ZRTP_VERSIONS.
265      *
266      * @return
267      *    a std::string formatted according to RFC6189 section 8 without the leading 'a=zrtp-hash:'
268      *    SDP attribute identifier. The hello hash is available immediately after class instantiation.
269      *
270      * @see getNumberSupportedVersions()
271      */
272     std::string getHelloHash(int index);
273 
274     /**
275      * Get the peer's ZRTP Hello Hash data.
276      *
277      * Use this method to get the peer's ZRTP Hello Hash data. The method
278      * returns the data as a string containing the ZRTP protocol version and
279      * hex-digits.
280      *
281      * The peer's hello hash is available only after ZRTP received a hello. If
282      * no data is available the function returns an empty string.
283      *
284      * Refer to ZRTP specification, chapter 8.
285      *
286      * @return
287      *    a std:string containing the Hello version and the hello hash as hex digits.
288      */
289     std::string getPeerHelloHash();
290 
291     /**
292      * Get Multi-stream parameters.
293      *
294      * Deprecated - use  getMultiStrParams(ZRtp **zrtpMaster);
295      *
296      * Use this method to get the Multi-stream that were computed during
297      * the ZRTP handshake. An application may use these parameters to
298      * enable multi-stream processing for an associated SRTP session.
299      *
300      * Refer to chapter 4.4.2 in the ZRTP specification for further details
301      * and restriction how and when to use multi-stream mode.
302      *
303      * @return
304      *    a string that contains the multi-stream parameters. The application
305      *    must not modify the contents of this string, it is opaque data. The
306      *    application may hand over this string to a new ZrtpQueue instance
307      *    to enable multi-stream processing for this ZrtpQueue.
308      *    If ZRTP was not started or ZRTP is not yet in secure state the method
309      *    returns an empty string.
310      */
getMultiStrParams()311     DEPRECATED_ZRTP std::string getMultiStrParams() {return getMultiStrParams(NULL); }
312 
313     /**
314      * Set Multi-stream parameters.
315      *
316      * Deprecated - use setMultiStrParams(std::string parameters, ZRtp* zrtpMaster);
317      *
318      * Use this method to set the parameters required to enable Multi-stream
319      * processing of ZRTP. The multi-stream parameters must be set before the
320      * application starts the ZRTP protocol engine.
321      *
322      * Refer to chapter 4.4.2 in the ZRTP specification for further details
323      * of multi-stream mode.
324      *
325      * @param parameters
326      *     A string that contains the multi-stream parameters that this
327      *     new ZrtpQueue instanace shall use. See also
328      *     <code>getMultiStrParams()</code>
329      */
setMultiStrParams(std::string parameters)330     DEPRECATED_ZRTP void setMultiStrParams(std::string parameters) { setMultiStrParams(parameters, NULL);}
331 
332     /**
333      * Get Multi-stream parameters.
334      *
335      * Use this method to get the Multi-stream that were computed during
336      * the ZRTP handshake. An application may use these parameters to
337      * enable multi-stream processing for an associated SRTP session.
338      *
339      * Refer to chapter 4.4.2 in the ZRTP specification for further details
340      * and restriction how and when to use multi-stream mode.
341      *
342      * @param zrtpMaster
343      *     Where the function returns the pointer of the ZRTP master stream.
344      * @return
345      *    a string that contains the multi-stream parameters. The application
346      *    must not modify the contents of this string, it is opaque data. The
347      *    application may hand over this string to a new ZrtpQueue instance
348      *    to enable multi-stream processing for this ZrtpQueue.
349      *    If ZRTP was not started or ZRTP is not yet in secure state the method
350      *    returns an empty string.
351      */
352     std::string getMultiStrParams(ZRtp **zrtpMaster);
353 
354     /**
355      * Set Multi-stream parameters.
356      *
357      * Use this method to set the parameters required to enable Multi-stream
358      * processing of ZRTP. The multi-stream parameters must be set before the
359      * application starts the ZRTP protocol engine.
360      *
361      * Refer to chapter 4.4.2 in the ZRTP specification for further details
362      * of multi-stream mode.
363      *
364      * @param parameters
365      *     A string that contains the multi-stream parameters that this
366      *     new ZrtpQueue instanace shall use. See also
367      *     <code>getMultiStrParams(ZRtp **zrtpMaster)</code>
368      * @param zrtpMaster
369      *     The pointer of the ZRTP master stream.
370      */
371     void setMultiStrParams(std::string parameters, ZRtp* zrtpMaster);
372 
373     /**
374      * Check if this ZRTP session is a Multi-stream session.
375      *
376      * Use this method to check if this ZRTP instance uses multi-stream.
377      * Refer to chapters 4.2 and 4.4.2 in the ZRTP.
378      *
379      * @return
380      *     True if multi-stream is used, false otherwise.
381      */
382     bool isMultiStream();
383 
384     /**
385      * Check if the other ZRTP client supports Multi-stream.
386      *
387      * Use this method to check if the other ZRTP client supports
388      * Multi-stream mode.
389      *
390      * @return
391      *     True if multi-stream is available, false otherwise.
392      */
393     bool isMultiStreamAvailable();
394 
395     /**
396      * Accept a PBX enrollment request.
397      *
398      * If a PBX service asks to enroll the PBX trusted MitM key and the user
399      * accepts this request, for example by pressing an OK button, the client
400      * application shall call this method and set the parameter
401      * <code>accepted</code> to true. If the user does not accept the request
402      * set the parameter to false.
403      *
404      * @param accepted
405      *     True if the enrollment request is accepted, false otherwise.
406      */
407     void acceptEnrollment(bool accepted);
408 
409     /**
410      * Check the state of the enrollment mode.
411      *
412      * If true then we will set the enrollment flag (E) in the confirm
413      * packets and perform the enrollment actions. A MitM (PBX) enrollment service
414      * started this ZRTP session. Can be set to true only if mitmMode is also true.
415      *
416      * @return status of the enrollmentMode flag.
417      */
418     bool isEnrollmentMode();
419 
420     /**
421      * Set the state of the enrollment mode.
422      *
423      * If true then we will set the enrollment flag (E) in the confirm
424      * packets and perform the enrollment actions. A MitM (PBX) enrollment
425      * service must sets this mode to true.
426      *
427      * Can be set to true only if mitmMode is also true.
428      *
429      * @param enrollmentMode defines the new state of the enrollmentMode flag
430      */
431     void setEnrollmentMode(bool enrollmentMode);
432 
433     /**
434      * Check if a peer's cache entry has a vaild MitM key.
435      *
436      * If true then the other peer ha a valid MtiM key, i.e. the peer has performed
437      * the enrollment procedure. A PBX ZRTP Back-2-Back application can use this function
438      * to check which of the peers is enrolled.
439      *
440      * @return True if the other peer has a valid Mitm key (is enrolled).
441      */
442     bool isPeerEnrolled();
443 
444     /**
445      * Send the SAS relay packet.
446      *
447      * The method creates and sends a SAS relay packet according to the ZRTP
448      * specifications. Usually only a MitM capable user agent (PBX) uses this
449      * function.
450      *
451      * @param sh the full SAS hash value, 32 bytes
452      * @param render the SAS rendering algorithm
453      */
454     bool sendSASRelayPacket(uint8_t* sh, std::string render);
455 
456     /**
457      * Get the commited SAS rendering algorithm for this ZRTP session.
458      *
459      * @return the commited SAS rendering algorithm
460      */
461     std::string getSasType();
462 
463     /**
464      * Get the computed SAS hash for this ZRTP session.
465      *
466      * A PBX ZRTP back-to-Back function uses this function to get the SAS
467      * hash of an enrolled client to construct the SAS relay packet for
468      * the other client.
469      *
470      * @return a pointer to the byte array that contains the full
471      *         SAS hash.
472      */
473     uint8_t* getSasHash();
474 
475     /**
476      * Set signature data.
477      *
478      * This functions stores signature data and transmitts it during ZRTP
479      * processing to the other party as part of the Confirm packets. Refer to
480      * chapters 5.7 and 7.2.
481      *
482      * The signature data must be set before ZRTP the application calls
483      * <code>start()</code>.
484      *
485      * @param data
486      *    The signature data including the signature type block. The method
487      *    copies this data into the Confirm packet at signature type block.
488      * @param length
489      *    The length of the signature data in bytes. This length must be
490      *    multiple of 4.
491      * @return
492      *    True if the method stored the data, false otherwise.
493      */
494     bool setSignatureData(uint8_t* data, int32_t length);
495 
496     /**
497      * Get signature data.
498      *
499      * This functions returns a pointer to the signature data that was receivied
500      * during ZRTP processing. Refer to chapters 5.7 and 7.2.
501      *
502      * The returned pointer points to volatile data that is valid only during the
503      * <code>checkSASSignature()</code> callback funtion. The application must copy
504      * the signature data if it will be used after the callback function returns.
505      *
506      * The signature data can be retrieved after ZRTP enters secure state.
507      * <code>start()</code>.
508      *
509      * @return
510      *    Pointer to signature data.
511      */
512     const uint8_t* getSignatureData();
513 
514     /**
515      * Get length of signature data in number of bytes.
516      *
517      * This functions returns the length of signature data that was receivied
518      * during ZRTP processing. Refer to chapters 5.7 and 7.2.
519      *
520      * @return
521      *    Length in bytes of the received signature data. The method returns
522      *    zero if no signature data is avilable.
523      */
524     int32_t getSignatureLength();
525 
526     /**
527      * Emulate a Conf2Ack packet.
528      *
529      * This method emulates a Conf2Ack packet. According to ZRTP specification
530      * the first valid SRTP packet that the Initiator receives must switch
531      * on secure mode. Refer to chapter 4 in the specificaton
532      *
533      */
534     void conf2AckSecure();
535 
536      /**
537       * Get other party's ZID (ZRTP Identifier) data
538       *
539       * This functions returns the other party's ZID that was receivied
540       * during ZRTP processing.
541       *
542       * The ZID data can be retrieved after ZRTP receive the first Hello
543       * packet from the other party. The application may call this method
544       * for example during SAS processing in showSAS(...) user callback
545       * method.
546       *
547       * @param data
548       *    Pointer to a data buffer. This buffer must have a size of
549       *    at least 12 bytes (96 bit) (ZRTP Identifier, see chap. 4.9)
550       * @return
551       *    Number of bytes copied into the data buffer - must be equivalent
552       *    to 96 bit, usually 12 bytes.
553       */
554      int32_t getPeerZid(uint8_t* data);
555 
556      /**
557       * Returns a pointer to the gather detailed information structure.
558       *
559       * This structure contains some detailed information about the negotiated
560       * algorithms, the chached and matched shared secrets.
561       */
562      const zrtpInfo *getDetailInfo();
563 
564      /**
565       * Get peer's client id.
566       *
567       * @return the peer's client id or an empty @c string if not set.
568       */
569      std::string getPeerClientId();
570 
571      /**
572       * Get peer's protocl version string.
573       *
574       * @return the peer's protocol version or an empty @c string if not set.
575       */
576      std::string getPeerProtcolVersion();
577 
578      /**
579       * Get number of supported ZRTP protocol versions.
580       *
581       * @return the number of supported ZRTP protocol versions.
582       */
getNumberSupportedVersions()583      int32_t getNumberSupportedVersions() {return SUPPORTED_ZRTP_VERSIONS;}
584 
585      /**
586       * Get negotiated ZRTP protocol version.
587       *
588       * @return the integer representation of the negotiated ZRTP protocol version.
589       */
getCurrentProtocolVersion()590      int32_t getCurrentProtocolVersion() {return currentHelloPacket->getVersionInt();}
591 
592      /**
593       * Validate the RS2 data if necessary.
594       *
595       * The cache functions stores the RS2 data but does not set its valid flag. The
596       * application may decide to set this flag.
597       */
598      void setRs2Valid();
599 
600      /**
601       * Get the secure since field
602       *
603       * Returns the secure since field or 0 if no such field is available. Secure since
604       * uses the unixepoch.
605       */
606      int64_t getSecureSince();
607 
608      /**
609       * Set the resend counter of timer T1 - T1 controls the Hello packets.
610       *
611       * This overwrites the standard value of 20 retries. Setting to <0 means
612       * 'indefinite', counter values less then 10 are ignored.
613       *
614       * Applications may set the resend counter based on network  or some other
615       * conditions. Applications may set this value any time and it's in effect
616       * for the current call. Setting the counter after the hello phase has no
617       * effect.
618       */
619      void setT1Resend(int32_t counter);
620 
621      /**
622       * Set the extended resend counter of timer T1 - T1 controls the Hello packets.
623       *
624       * More retries to extend time, see RFC6189 chap. 6. This overwrites the standard
625       * value of 60 extended retiries.
626       *
627       * Applications may set the resend counter based on network  or some other
628       * conditions.
629       */
630      void setT1ResendExtend(int32_t counter);
631 
632      /**
633       * Set the time capping of timer T1 - T1 controls the Hello packets.
634       *
635       * Values <50ms are not set.
636       */
637      void setT1Capping(int32_t capping);
638 
639      /**
640       * Set the resend counter of timer T2 - T2 controls other (post-Hello) packets.
641       *
642       * This overwrites the standard value of 10 retiries. Setting to <0 means
643       * 'indefinite', counter values less then 10 are ignored.
644       *
645       * Applications may set the resend counter based on network  or some other
646       * conditions. Applications may set this value any time and it's in effect
647       * for the current call. Setting the counter after tZRTP enetered secure state
648       * has no effect.
649       */
650      void setT2Resend(int32_t counter);
651 
652      /**
653       * Set the time capping of timer T2 - T2 controls other (post-Hello) packets.
654       *
655       * Values <150ms are not set.
656       */
657      void setT2Capping(int32_t capping);
658 
659      /**
660       * @brief Get required buffer size to get all 32-bit statistic counters of ZRTP
661       *
662       * @param streamNm stream, if not specified the default is @c AudioStream
663       *
664       * @return number of 32 bit integer elements required or < 0 on error
665       */
666      int getNumberOfCountersZrtp();
667 
668      /**
669       * @brief Read statistic counters of ZRTP
670       *
671       * @param buffer Pointer to buffer of 32-bit integers. The buffer must be able to
672       *         hold at least getNumberOfCountersZrtp() 32-bit integers
673       * @param streamNm stream, if not specified the default is @c AudioStream
674       *
675       * @return number of 32-bit counters returned in buffer or < 0 on error
676       */
677      int getCountersZrtp(int32_t* counters);
678 
679      /**
680       * @brief Get the computed ZRTP exported key.
681       *
682       * Returns a pointer to the computed exported key. The application should copy
683       * the data it needs.
684       *
685       * @param length pointer to an int, gets the length of the exported key.
686       * @return pointer to the exported key data.
687       */
688      uint8_t* getExportedKey(int32_t *length);
689 
690      /**
691       * @brief Return either Initiator or Responder.
692       */
getZrtpRole()693      int32_t getZrtpRole() { return myRole; }
694 
695      /**
696       * @brief Get status of our peer's disclosure flag
697       */
isPeerDisclosureFlag()698      bool isPeerDisclosureFlag(){ return peerDisclosureFlagSeen; }
699 
700 private:
701      typedef union _hashCtx {
702          SkeinCtx_t  skeinCtx;
703 #ifdef ZRTP_OPENSSL
704          SHA256_CTX  sha256Ctx;
705          SHA512_CTX  sha384Ctx;
706 #else
707          sha256_ctx  sha256Ctx;
708          sha384_ctx  sha384Ctx;
709 #endif
710      } HashCtx;
711 
712      friend class ZrtpStateClass;
713 
714     /**
715      * The state engine takes care of protocol processing.
716      */
717     ZrtpStateClass* stateEngine;
718 
719     /**
720      * This is my ZID that I send to the peer.
721      */
722     uint8_t ownZid[IDENTIFIER_LEN];
723 
724     /**
725      * The peer's ZID
726      */
727     uint8_t peerZid[IDENTIFIER_LEN];
728 
729     /**
730      * The callback class provides me with the interface to send
731      * data and to deal with timer management of the hosting system.
732      */
733     ZrtpCallback* callback;
734 
735     /**
736      * My active Diffie-Helman context
737      */
738     ZrtpDH* dhContext;
739 
740     /**
741      * The computed DH shared secret
742      */
743     uint8_t* DHss;
744 
745     /**
746      * My computed public key
747      */
748     uint8_t pubKeyBytes[400];
749     /**
750      * Length off public key
751      */
752 //    int32_t pubKeyLen;
753     /**
754      * My Role in the game
755      */
756     Role myRole;
757 
758     /**
759      * The human readable SAS value
760      */
761     std::string SAS;
762 
763     /**
764      * The SAS hash for signaling and alike. Refer to chapters
765      * 4.5 and 7 how sasHash, sasValue and the SAS string are derived.
766      */
767     uint8_t sasHash[MAX_DIGEST_LENGTH];
768     /**
769      * The ids for the retained and other shared secrets
770      */
771     uint8_t rs1IDr[MAX_DIGEST_LENGTH];
772     uint8_t rs2IDr[MAX_DIGEST_LENGTH];
773     uint8_t auxSecretIDr[MAX_DIGEST_LENGTH];
774     uint8_t pbxSecretIDr[MAX_DIGEST_LENGTH];
775 
776     uint8_t rs1IDi[MAX_DIGEST_LENGTH];
777     uint8_t rs2IDi[MAX_DIGEST_LENGTH];
778     uint8_t auxSecretIDi[MAX_DIGEST_LENGTH];
779     uint8_t pbxSecretIDi[MAX_DIGEST_LENGTH];
780 
781     /**
782      * pointers to aux secret storage and length of aux secret
783      */
784     uint8_t* auxSecret;
785     int32_t auxSecretLength;
786 
787     /**
788      * Record if valid rs1 and/or rs1 were found in the
789      * retaind secret cache.
790      */
791     bool rs1Valid;
792     bool rs2Valid;
793     /**
794      * My hvi
795      */
796     uint8_t hvi[MAX_DIGEST_LENGTH];
797 
798     /**
799      * The peer's hvi
800      */
801     uint8_t peerHvi[8*ZRTP_WORD_SIZE];
802 
803     /**
804      * Context to compute the SHA256 hash of selected messages.
805      * Used to compute the s0, refer to chapter 4.4.1.4
806      */
807     void* msgShaContext;
808     /**
809      * Commited Hash, Cipher, and public key algorithms
810      */
811     AlgorithmEnum* hash;
812     AlgorithmEnum* cipher;
813     AlgorithmEnum* pubKey;
814     /**
815      * The selected SAS type.
816      */
817     AlgorithmEnum* sasType;
818 
819     /**
820      * The selected SAS type.
821      */
822     AlgorithmEnum* authLength;
823 
824     /**
825      * The Hash images as defined in chapter 5.1.1 (H0 is a random value,
826      * not stored here). Need full SHA 256 lenght to store hash value but
827      * only the leftmost 128 bits are used in computations and comparisons.
828      */
829     uint8_t H0[IMPL_MAX_DIGEST_LENGTH];
830     uint8_t H1[IMPL_MAX_DIGEST_LENGTH];
831     uint8_t H2[IMPL_MAX_DIGEST_LENGTH];
832     uint8_t H3[IMPL_MAX_DIGEST_LENGTH];
833 
834     uint8_t peerHelloHash[IMPL_MAX_DIGEST_LENGTH];
835     uint8_t peerHelloVersion[ZRTP_WORD_SIZE + 1];   // +1 for nul byte
836 
837     // We get the peer's H? from the message where length is defined as 8 words
838     uint8_t peerH0[8*ZRTP_WORD_SIZE];
839     uint8_t peerH1[8*ZRTP_WORD_SIZE];
840     uint8_t peerH2[8*ZRTP_WORD_SIZE];
841     uint8_t peerH3[8*ZRTP_WORD_SIZE];
842 
843     /**
844      * The SHA256 hash over selected messages
845      */
846     uint8_t messageHash[MAX_DIGEST_LENGTH];
847 
848     /**
849      * The s0
850      */
851     uint8_t s0[MAX_DIGEST_LENGTH];
852 
853     /**
854      * The new Retained Secret
855      */
856     uint8_t newRs1[MAX_DIGEST_LENGTH];
857 
858     /**
859      * The GoClear HMAC keys and confirm HMAC key
860      */
861     uint8_t hmacKeyI[MAX_DIGEST_LENGTH];
862     uint8_t hmacKeyR[MAX_DIGEST_LENGTH];
863 
864     /**
865      * The Initiator's srtp key and salt
866      */
867     uint8_t srtpKeyI[MAX_DIGEST_LENGTH];
868     uint8_t srtpSaltI[MAX_DIGEST_LENGTH];
869 
870     /**
871      * The Responder's srtp key and salt
872      */
873     uint8_t srtpKeyR[MAX_DIGEST_LENGTH];
874     uint8_t srtpSaltR[MAX_DIGEST_LENGTH];
875 
876     /**
877      * The keys used to encrypt/decrypt the confirm message
878      */
879     uint8_t zrtpKeyI[MAX_DIGEST_LENGTH];
880     uint8_t zrtpKeyR[MAX_DIGEST_LENGTH];
881 
882     HashCtx hashCtx;
883 
884     /**
885      * Pointers to negotiated hash and HMAC functions
886      */
887     void (*hashFunction)(unsigned char *data,
888             unsigned int data_length,
889             unsigned char *digest);
890 
891     void (*hashListFunction)(unsigned char *data[],
892             unsigned int data_length[],
893             unsigned char *digest);
894 
895     void (*hmacFunction)(uint8_t* key, uint32_t key_length,
896                 uint8_t* data, int32_t data_length,
897                 uint8_t* mac, uint32_t* mac_length);
898 
899     void (*hmacListFunction)( uint8_t* key, uint32_t key_length,
900                            uint8_t* data[], uint32_t data_length[],
901                            uint8_t* mac, uint32_t* mac_length );
902 
903     void* (*createHashCtx)(void* ctx);
904 
905     void (*closeHashCtx)(void* ctx, unsigned char* digest);
906 
907     void (*hashCtxFunction)(void* ctx, unsigned char* data,
908            unsigned int dataLength);
909 
910     void (*hashCtxListFunction)(void* ctx, unsigned char* dataChunks[],
911            unsigned int dataChunkLength[]);
912 
913     int32_t hashLength;
914 
915     // Funtion pointers to implicit hash and hmac functions
916     void (*hashFunctionImpl)(unsigned char *data,
917             unsigned int data_length,
918             unsigned char *digest);
919 
920     void (*hashListFunctionImpl)(unsigned char *data[],
921             unsigned int data_length[],
922             unsigned char *digest);
923 
924     void (*hmacFunctionImpl)(uint8_t* key, uint32_t key_length,
925                 uint8_t* data, int32_t data_length,
926                 uint8_t* mac, uint32_t* mac_length);
927 
928     void (*hmacListFunctionImpl)( uint8_t* key, uint32_t key_length,
929                            uint8_t* data[], uint32_t data_length[],
930                            uint8_t* mac, uint32_t* mac_length );
931 
932     int32_t hashLengthImpl;
933 
934     /**
935      * The ZRTP Session Key
936      * Refer to chapter 4.5.2
937      */
938     uint8_t zrtpSession[MAX_DIGEST_LENGTH];
939 
940     /**
941      * The ZRTP export Key
942      * Refer to chapter 4.5.2
943      */
944     uint8_t zrtpExport[MAX_DIGEST_LENGTH];
945 
946     /**
947      * True if this ZRTP instance uses multi-stream mode.
948      */
949     bool multiStream;
950 
951         /**
952      * True if the other ZRTP client supports multi-stream mode.
953      */
954     bool multiStreamAvailable;
955 
956     /**
957      * Enable MitM (PBX) enrollment
958      *
959      * If set to true then ZRTP honors the PBX enrollment flag in
960      * Commit packets and calls the appropriate user callback
961      * methods. If the parameter is set to false ZRTP ignores the PBX
962      * enrollment flags.
963      */
964     bool enableMitmEnrollment;
965 
966     /**
967      * True if a valid trusted MitM key of the other peer is available, i.e. enrolled.
968      */
969     bool peerIsEnrolled;
970 
971     /**
972      * Set to true if the Hello packet contained the M-flag (MitM flag).
973      * We use this later to check some stuff for SAS Relay processing
974      */
975     bool mitmSeen;
976 
977     /**
978      * Temporarily store computed pbxSecret, if user accepts enrollment then
979      * it will copied to our ZID record of the PBX (MitM)
980      */
981     uint8_t* pbxSecretTmp;
982     uint8_t  pbxSecretTmpBuffer[MAX_DIGEST_LENGTH];
983 
984     /**
985      * If true then we will set the enrollment flag (E) in the confirm
986      * packets. Set to true if the PBX enrollment service started this ZRTP
987      * session. Can be set to true only if mitmMode is also true.
988      */
989     bool enrollmentMode;
990 
991     /**
992      * Configuration data which algorithms to use.
993      */
994     ZrtpConfigure configureAlgos;
995     /**
996      * Pre-initialized packets.
997      */
998     ZrtpPacketHello    zrtpHello_11;
999     ZrtpPacketHello    zrtpHello_12;   // Prepare for ZRTP protocol version 1.2
1000 
1001     ZrtpPacketHelloAck zrtpHelloAck;
1002     ZrtpPacketConf2Ack zrtpConf2Ack;
1003     ZrtpPacketClearAck zrtpClearAck;
1004     ZrtpPacketGoClear  zrtpGoClear;
1005     ZrtpPacketError    zrtpError;
1006     ZrtpPacketErrorAck zrtpErrorAck;
1007     ZrtpPacketDHPart   zrtpDH1;
1008     ZrtpPacketDHPart   zrtpDH2;
1009     ZrtpPacketCommit   zrtpCommit;
1010     ZrtpPacketConfirm  zrtpConfirm1;
1011     ZrtpPacketConfirm  zrtpConfirm2;
1012     ZrtpPacketPingAck  zrtpPingAck;
1013     ZrtpPacketSASrelay zrtpSasRelay;
1014     ZrtpPacketRelayAck zrtpRelayAck;
1015 
1016     HelloPacketVersion helloPackets[MAX_ZRTP_VERSIONS + 1];
1017     int32_t highestZrtpVersion;
1018 
1019     /// Pointer to Hello packet sent to partner, initialized in ZRtp, modified by ZrtpStateClass
1020     ZrtpPacketHello* currentHelloPacket;
1021 
1022     /**
1023      * ZID cache record
1024      */
1025     ZIDRecord *zidRec;
1026 
1027     /**
1028      * Save record
1029      *
1030      * If false don't save record until user verified and confirmed the SAS.
1031      */
1032     bool saveZidRecord;
1033     /**
1034      * Random IV data to encrypt the confirm data, 128 bit for AES
1035      */
1036     uint8_t randomIV[16];
1037 
1038     uint8_t tempMsgBuffer[1024];
1039     int32_t lengthOfMsgData;
1040 
1041     /**
1042      * Variables to store signature data. Includes the signature type block
1043      */
1044     const uint8_t* signatureData;       // will be set when needed
1045     int32_t  signatureLength;     // overall length in bytes
1046 
1047     /**
1048      * Is true if the other peer signaled SAS signature support in its Hello packet.
1049      */
1050     bool signSasSeen;
1051 
1052     uint32_t peerSSRC;           // peer's SSRC, required to setup PingAck packet
1053 
1054     zrtpInfo detailInfo;         // filled with some more detailded information if application would like to know
1055 
1056     std::string peerClientId;    // store the peer's client Id
1057 
1058     ZRtp* masterStream;                    // This is the master stream in case this is a multi-stream
1059     std::vector<std::string> peerNonces;   // Store nonces we got from our partner. Using std::string
1060                                            // just simplifies memnory management, nonces are binary data, not strings :-)
1061     /**
1062      * Enable or disable paranoid mode.
1063      *
1064      * The Paranoid mode controls the behaviour and handling of the SAS verify flag. If
1065      * Panaoid mode is set to flase then ZRtp applies the normal handling. If Paranoid
1066      * mode is set to true then the handling is:
1067      *
1068      * <ul>
1069      * <li> Force the SAS verify flag to be false at srtpSecretsOn() callback. This gives
1070      *      the user interface (UI) the indication to handle the SAS as <b>not verified</b>.
1071      *      See implementation note below.</li>
1072      * <li> Don't set the SAS verify flag in the <code>Confirm</code> packets, thus the other
1073      *      also must report the SAS as <b>not verified</b>.</li>
1074      * <li> ignore the <code>SASVerified()</code> function, thus do not set the SAS to verified
1075      *      in the ZRTP cache. </li>
1076      * <li> Disable the <b>Trusted PBX MitM</b> feature. Just send the <code>SASRelay</code> packet
1077      *      but do not process the relayed data. This protects the user from a malicious
1078      *      "trusted PBX".</li>
1079      * </ul>
1080      * ZRtp performs alls other steps during the ZRTP negotiations as usual, in particular it
1081      * computes, compares, uses, and stores the retained secrets. This avoids unnecessary warning
1082      * messages. The user may enable or disable the Paranoid mode on a call-by-call basis without
1083      * breaking the key continuity data.
1084      *
1085      * <b>Implementation note:</b></br>
1086      * An application shall always display the SAS code if the SAS verify flag is <code>false</code>.
1087      * The application shall also use mechanisms to remind the user to compare the SAS code, for
1088      * example useing larger fonts, different colours and other display features.
1089      */
1090     bool paranoidMode;
1091 
1092     /**
1093      * Is true if the other peer sent a Disclosure flag in its Confirm packet.
1094      */
1095     bool peerDisclosureFlagSeen;
1096 
1097     /**
1098      * Find the best Hash algorithm that is offered in Hello.
1099      *
1100      * Find the best, that is the strongest, Hash algorithm that our peer
1101      * offers in its Hello packet.
1102      *
1103      * @param hello
1104      *    The Hello packet.
1105      * @return
1106      *    The Enum that identifies the best offered Hash algortihm. Return
1107      *    mandatory algorithm if no match was found.
1108      */
1109     AlgorithmEnum* findBestHash(ZrtpPacketHello *hello);
1110 
1111     /**
1112      * Find the best symmetric cipher algorithm that is offered in Hello.
1113      *
1114      * Find the best, that is the strongest, cipher algorithm that our peer
1115      * offers in its Hello packet.
1116      *
1117      * @param hello
1118      *    The Hello packet.
1119      * @param pk
1120      *    The id of the selected public key algorithm
1121      * @return
1122      *    The Enum that identifies the best offered Cipher algorithm. Return
1123      *    mandatory algorithm if no match was found.
1124      */
1125     AlgorithmEnum* findBestCipher(ZrtpPacketHello *hello,  AlgorithmEnum* pk);
1126 
1127     /**
1128      * Find the best Public Key algorithm that is offered in Hello.
1129      *
1130      * Find the best, that is the strongest, public key algorithm that our peer
1131      * offers in its Hello packet.
1132      *
1133      * @param hello
1134      *    The Hello packet.
1135      * @return
1136      *    The Enum that identifies the best offered Public Key algorithm. Return
1137      *    mandatory algorithm if no match was found.
1138      */
1139     AlgorithmEnum* findBestPubkey(ZrtpPacketHello *hello);
1140 
1141     /**
1142      * Find the best SAS algorithm that is offered in Hello.
1143      *
1144      * Find the best, that is the strongest, SAS algorithm that our peer
1145      * offers in its Hello packet. The method works as definied in RFC 6189,
1146      * chapter 4.1.2.
1147      *
1148      * The list of own supported public key algorithms must follow the rules
1149      * defined in RFC 6189, chapter 4.1.2, thus the order in the list must go
1150      * from fastest to slowest.
1151      *
1152      * @param hello
1153      *    The Hello packet.
1154      * @return
1155      *    The Enum that identifies the best offered SAS algorithm. Return
1156      *    mandatory algorithm if no match was found.
1157      */
1158     AlgorithmEnum* findBestSASType(ZrtpPacketHello* hello);
1159 
1160     /**
1161      * Find the best authentication length that is offered in Hello.
1162      *
1163      * Find the best, that is the strongest, authentication length that our peer
1164      * offers in its Hello packet.
1165      *
1166      * @param hello
1167      *    The Hello packet.
1168      * @return
1169      *    The Enum that identifies the best offered authentication length. Return
1170      *    mandatory algorithm if no match was found.
1171      */
1172     AlgorithmEnum* findBestAuthLen(ZrtpPacketHello* hello);
1173 
1174     /**
1175      * Check if MultiStream mode is offered in Hello.
1176      *
1177      * Find the best, that is the strongest, authentication length that our peer
1178      * offers in its Hello packet.
1179      *
1180      * @param hello
1181      *    The Hello packet.
1182      * @return
1183      *    True if multi stream mode is available, false otherwise.
1184      */
1185     bool checkMultiStream(ZrtpPacketHello* hello);
1186 
1187     /**
1188      * Checks if Hello packet contains a strong (384bit) hash based on selection policy.
1189      *
1190      * The function currently implements the nonNist policy only:
1191      * If the public key algorithm is a non-NIST ECC algorithm this function prefers
1192      * non-NIST HASH algorithms (Skein etc).
1193      *
1194      * If Hello packet does not contain a strong hash then this functions returns @c NULL.
1195      *
1196      * @param hello The Hello packet.
1197      * @param algoName name of selected PK algorithm
1198      * @return @c hash algorithm if found in Hello packet, @c NULL otherwise.
1199      */
1200     AlgorithmEnum* getStrongHashOffered(ZrtpPacketHello *hello, int32_t algoName);
1201 
1202     /**
1203      * Checks if Hello packet offers a strong (256bit) symmetric cipher based on selection policy.
1204      *
1205      * The function currently implements the nonNist policy only:
1206      * If the public key algorithm is a non-NIST ECC algorithm this function prefers
1207      * non-NIST symmetric cipher algorithms (Twofish etc).
1208      *
1209      * If Hello packet does not contain a symmetric cipher then this functions returns @c NULL.
1210 
1211      * @param hello The Hello packet.
1212      * @param algoName name of selected PK algorithm
1213      * @return @c hash algorithm if found in Hello packet, @c NULL otherwise.
1214      *
1215      * @return @c cipher algorithm if found in Hello packet, @c NULL otherwise.
1216      */
1217     AlgorithmEnum* getStrongCipherOffered(ZrtpPacketHello *hello, int32_t algoName);
1218 
1219     /**
1220      * Checks if Hello packet contains a hash based on selection policy.
1221      *
1222      * The function currently implements the nonNist policy only:
1223      * If the public key algorithm is a non-NIST ECC algorithm this function prefers
1224      * non-NIST HASH algorithms (Skein etc).
1225      *
1226      * @param hello The Hello packet.
1227      * @param algoName name of selected PK algorithm
1228      * @return @c hash algorithm found in Hello packet.
1229      */
1230     AlgorithmEnum* getHashOffered(ZrtpPacketHello *hello, int32_t algoName);
1231 
1232     /**
1233      * Checks if Hello packet offers a symmetric cipher based on selection policy.
1234      *
1235      * The function currently implements the nonNist policy only:
1236      * If the public key algorithm is a non-NIST ECC algorithm this function prefers
1237      * non-NIST symmetric cipher algorithms (Twofish etc).
1238      *
1239      * @param hello The Hello packet.
1240      * @param algoName name of selected PK algorithm
1241      * @return non-NIST @c cipher algorithm if found in Hello packet, @c NULL otherwise
1242      */
1243     AlgorithmEnum* getCipherOffered(ZrtpPacketHello *hello, int32_t algoName);
1244 
1245     /**
1246      * Checks if Hello packet offers a SRTP authentication length based on selection policy.
1247      *
1248      * The function currently implements the nonNist policy only:
1249      * If the public key algorithm is a non-NIST ECC algorithm this function prefers
1250      * non-NIST algorithms (Skein etc).
1251      *
1252      * @param hello The Hello packet.
1253      * @param algoName algoName name of selected PK algorithm
1254      * @return @c authLen algorithm found in Hello packet
1255      */
1256     AlgorithmEnum* getAuthLenOffered(ZrtpPacketHello *hello, int32_t algoName);
1257 
1258     /**
1259      * Save the computed MitM secret to the ZID record of the peer
1260      */
1261     void writeEnrollmentPBX();
1262 
1263     /**
1264      * Compute my hvi value according to ZRTP specification.
1265      */
1266     void computeHvi(ZrtpPacketDHPart* dh, ZrtpPacketHello *hello);
1267 
1268     void computeSharedSecretSet(ZIDRecord *zidRec);
1269 
1270     void computeAuxSecretIds();
1271 
1272     void computeSRTPKeys();
1273 
1274     void KDF(uint8_t* key, uint32_t keyLength, uint8_t* label, int32_t labelLength,
1275                uint8_t* context, int32_t contextLength, int32_t L, uint8_t* output);
1276 
1277     void generateKeysInitiator(ZrtpPacketDHPart *dhPart, ZIDRecord *zidRec);
1278 
1279     void generateKeysResponder(ZrtpPacketDHPart *dhPart, ZIDRecord *zidRec);
1280 
1281     void generateKeysMultiStream();
1282 
1283     void computePBXSecret();
1284 
1285     void setNegotiatedHash(AlgorithmEnum* hash);
1286 
1287     /*
1288      * The following methods are helper functions for ZrtpStateClass.
1289      * ZrtpStateClass calls them to prepare packets, send data, report
1290      * problems, etc.
1291      */
1292     /**
1293      * Send a ZRTP packet.
1294      *
1295      * The state engines calls this method to send a packet via the RTP
1296      * stack.
1297      *
1298      * @param packet
1299      *    Points to the ZRTP packet.
1300      * @return
1301      *    zero if sending failed, one if packet was send
1302      */
1303     int32_t sendPacketZRTP(ZrtpPacketBase *packet);
1304 
1305     /**
1306      * Activate a Timer using the host callback.
1307      *
1308      * @param tm
1309      *    The time in milliseconds.
1310      * @return
1311      *    zero if activation failed, one if timer was activated
1312      */
1313     int32_t activateTimer(int32_t tm);
1314 
1315     /**
1316      * Cancel the active Timer using the host callback.
1317      *
1318      * @return
1319      *    zero if activation failed, one if timer was activated
1320      */
1321     int32_t cancelTimer();
1322 
1323     /**
1324      * Prepare a Hello packet.
1325      *
1326      * Just take the preinitialized Hello packet and return it. No
1327      * further processing required.
1328      *
1329      * @return
1330      *    A pointer to the initialized Hello packet.
1331      */
1332     ZrtpPacketHello* prepareHello();
1333 
1334     /**
1335      * Prepare a HelloAck packet.
1336      *
1337      * Just take the preinitialized HelloAck packet and return it. No
1338      * further processing required.
1339      *
1340      * @return
1341      *    A pointer to the initialized HelloAck packet.
1342      */
1343     ZrtpPacketHelloAck* prepareHelloAck();
1344 
1345     /**
1346      * Prepare a Commit packet.
1347      *
1348      * We have received a Hello packet from our peer. Check the offers
1349      * it makes to us and select the most appropriate. Using the
1350      * selected values prepare a Commit packet and return it to protocol
1351      * state engine.
1352      *
1353      * @param hello
1354      *    Points to the received Hello packet
1355      * @param errMsg
1356      *    Points to an integer that can hold a ZRTP error code.
1357      * @return
1358      *    A pointer to the prepared Commit packet
1359      */
1360     ZrtpPacketCommit* prepareCommit(ZrtpPacketHello *hello, uint32_t* errMsg);
1361 
1362     /**
1363      * Prepare a Commit packet for Multi Stream mode.
1364      *
1365      * Using the selected values prepare a Commit packet and return it to protocol
1366      * state engine.
1367      *
1368      * @param hello
1369      *    Points to the received Hello packet
1370      * @return
1371      *    A pointer to the prepared Commit packet for multi stream mode
1372      */
1373     ZrtpPacketCommit* prepareCommitMultiStream(ZrtpPacketHello *hello);
1374 
1375     /**
1376      * Prepare the DHPart1 packet.
1377      *
1378      * This method prepares a DHPart1 packet. The input to the method is always
1379      * a Commit packet received from the peer. Also we a in the role of the
1380      * Responder.
1381      *
1382      * When we receive a Commit packet we get the selected ciphers, hashes, etc
1383      * and cross-check if this is ok. Then we need to initialize a set of DH
1384      * keys according to the selected cipher. Using this data we prepare our DHPart1
1385      * packet.
1386      */
1387     ZrtpPacketDHPart* prepareDHPart1(ZrtpPacketCommit *commit, uint32_t* errMsg);
1388 
1389     /**
1390      * Prepare the DHPart2 packet.
1391      *
1392      * This method prepares a DHPart2 packet. The input to the method is always
1393      * a DHPart1 packet received from the peer. Our peer sends the DH1Part as
1394      * response to our Commit packet. Thus we are in the role of the
1395      * Initiator.
1396      *
1397      */
1398     ZrtpPacketDHPart* prepareDHPart2(ZrtpPacketDHPart* dhPart1, uint32_t* errMsg);
1399 
1400     /**
1401      * Prepare the Confirm1 packet.
1402      *
1403      * This method prepare the Confirm1 packet. The input to this method is the
1404      * DHPart2 packect received from our peer. The peer sends the DHPart2 packet
1405      * as response of our DHPart1. Here we are in the role of the Responder
1406      *
1407      */
1408     ZrtpPacketConfirm* prepareConfirm1(ZrtpPacketDHPart* dhPart2, uint32_t* errMsg);
1409 
1410     /**
1411      * Prepare the Confirm1 packet in multi stream mode.
1412      *
1413      * This method prepares the Confirm1 packet. The state engine call this method
1414      * if multi stream mode is selected and a Commit packet was received. The input to
1415      * this method is the Commit.
1416      * Here we are in the role of the Responder
1417      *
1418      */
1419     ZrtpPacketConfirm* prepareConfirm1MultiStream(ZrtpPacketCommit* commit, uint32_t* errMsg);
1420 
1421     /**
1422      * Prepare the Confirm2 packet.
1423      *
1424      * This method prepare the Confirm2 packet. The input to this method is the
1425      * Confirm1 packet received from our peer. The peer sends the Confirm1 packet
1426      * as response of our DHPart2. Here we are in the role of the Initiator
1427      */
1428     ZrtpPacketConfirm* prepareConfirm2(ZrtpPacketConfirm* confirm1, uint32_t* errMsg);
1429 
1430     /**
1431      * Prepare the Confirm2 packet in multi stream mode.
1432      *
1433      * This method prepares the Confirm2 packet. The state engine call this method if
1434      * multi stream mode is active and in state CommitSent. The input to this method is
1435      * the Confirm1 packet received from our peer. The peer sends the Confirm1 packet
1436      * as response of our Commit packet in multi stream mode.
1437      * Here we are in the role of the Initiator
1438      */
1439     ZrtpPacketConfirm* prepareConfirm2MultiStream(ZrtpPacketConfirm* confirm1, uint32_t* errMsg);
1440 
1441     /**
1442      * Prepare the Conf2Ack packet.
1443      *
1444      * This method prepare the Conf2Ack packet. The input to this method is the
1445      * Confirm2 packet received from our peer. The peer sends the Confirm2 packet
1446      * as response of our Confirm1. Here we are in the role of the Initiator
1447      */
1448     ZrtpPacketConf2Ack* prepareConf2Ack(ZrtpPacketConfirm* confirm2, uint32_t* errMsg);
1449 
1450     /**
1451      * Prepare the ErrorAck packet.
1452      *
1453      * This method prepares the ErrorAck packet. The input to this method is the
1454      * Error packet received from the peer.
1455      */
1456     ZrtpPacketErrorAck* prepareErrorAck(ZrtpPacketError* epkt);
1457 
1458     /**
1459      * Prepare the Error packet.
1460      *
1461      * This method prepares the Error packet. The input to this method is the
1462      * error code to be included into the message.
1463      */
1464     ZrtpPacketError* prepareError(uint32_t errMsg);
1465 
1466     /**
1467      * Prepare a ClearAck packet.
1468      *
1469      * This method checks if the GoClear message is valid. If yes then switch
1470      * off SRTP processing, stop sending of RTP packets (pause transmit) and
1471      * inform the user about the fact. Only if user confirms the GoClear message
1472      * normal RTP processing is resumed.
1473      *
1474      * @return
1475      *     NULL if GoClear could not be authenticated, a ClearAck packet
1476      *     otherwise.
1477      */
1478     ZrtpPacketClearAck* prepareClearAck(ZrtpPacketGoClear* gpkt);
1479 
1480     /**
1481      * Prepare the ErrorAck packet.
1482      *
1483      * This method prepares the ErrorAck packet. The input to this method is the
1484      * Error packet received from the peer.
1485      */
1486     ZrtpPacketPingAck* preparePingAck(ZrtpPacketPing* ppkt);
1487 
1488     /**
1489      * Prepare the RelayAck packet.
1490      *
1491      * This method prepares the RelayAck packet. The input to this method is the
1492      * SASrelay packet received from the peer.
1493      */
1494     ZrtpPacketRelayAck* prepareRelayAck(ZrtpPacketSASrelay* srly, uint32_t* errMsg);
1495 
1496     /**
1497      * Prepare a GoClearAck packet w/o HMAC
1498      *
1499      * Prepare a GoCLear packet without a HMAC but with a short error message.
1500      * This type of GoClear is used if something went wrong during the ZRTP
1501      * negotiation phase.
1502      *
1503      * @return
1504      *     A goClear packet without HMAC
1505      */
1506     ZrtpPacketGoClear* prepareGoClear(uint32_t errMsg = 0);
1507 
1508     /**
1509      * Compare the hvi values.
1510      *
1511      * Compare a received Commit packet with our Commit packet and returns
1512      * which Commit packt is "more important". See chapter 5.2 to get further
1513      * information how to compare Commit packets.
1514      *
1515      * @param commit
1516      *    Pointer to the peer's commit packet we just received.
1517      * @return
1518      *    <0 if our Commit packet is "less important"
1519      *    >0 if our Commit is "more important"
1520      *     0 shouldn't happen because we compare crypto hashes
1521      */
1522     int32_t compareCommit(ZrtpPacketCommit *commit);
1523 
1524     /**
1525      * Verify the H2 hash image.
1526      *
1527      * Verifies the H2 hash contained in a received commit message.
1528      * This functions just verifies H2 but does not store it.
1529      *
1530      * @param commit
1531      *    Pointer to the peer's commit packet we just received.
1532      * @return
1533      *    true if H2 is ok and verified
1534      *    false if H2 could not be verified
1535      */
1536     bool verifyH2(ZrtpPacketCommit *commit);
1537 
1538     /**
1539      * Send information messages to the hosting environment.
1540      *
1541      * The ZRTP implementation uses this method to send information messages
1542      * to the host. Along with the message ZRTP provides a severity indicator
1543      * that defines: Info, Warning, Error, Alert. Refer to the MessageSeverity
1544      * enum in the ZrtpCallback class.
1545      *
1546      * @param severity
1547      *     This defines the message's severity
1548      * @param subCode
1549      *     The subcode identifying the reason.
1550      * @see ZrtpCodes#MessageSeverity
1551      */
1552     void sendInfo(GnuZrtpCodes::MessageSeverity severity, int32_t subCode);
1553 
1554     /**
1555      * ZRTP state engine calls this if the negotiation failed.
1556      *
1557      * ZRTP calls this method in case ZRTP negotiation failed. The parameters
1558      * show the severity as well as some explanatory text.
1559      *
1560      * @param severity
1561      *     This defines the message's severity
1562      * @param subCode
1563      *     The subcode identifying the reason.
1564      * @see ZrtpCodes#MessageSeverity
1565      */
1566     void zrtpNegotiationFailed(GnuZrtpCodes::MessageSeverity severity, int32_t subCode);
1567 
1568     /**
1569      * ZRTP state engine calls this method if the other side does not support ZRTP.
1570      *
1571      * If the other side does not answer the ZRTP <em>Hello</em> packets then
1572      * ZRTP calls this method,
1573      *
1574      */
1575     void zrtpNotSuppOther();
1576 
1577     /**
1578      * Signal SRTP secrets are ready.
1579      *
1580      * This method calls a callback method to inform the host that the SRTP
1581      * secrets are ready.
1582      *
1583      * @param part
1584      *    Defines for which part (sender or receiver) to switch on security
1585      * @return
1586      *    Returns false if something went wrong during initialization of SRTP
1587      *    context. Propagate error back to state engine.
1588      */
1589     bool srtpSecretsReady(EnableSecurity part);
1590 
1591     /**
1592      * Switch off SRTP secrets.
1593      *
1594      * This method calls a callback method to inform the host that the SRTP
1595      * secrets shall be cleared.
1596      *
1597      * @param part
1598      *    Defines for which part (sender or receiver) to clear
1599      */
1600     void srtpSecretsOff(EnableSecurity part);
1601 
1602     /**
1603      * ZRTP state engine calls these methods to enter or leave its
1604      * synchronization mutex.
1605      */
1606     void synchEnter();
1607 
1608     void synchLeave();
1609 
1610     /**
1611      * Helper function to store ZRTP message data in a temporary buffer
1612      *
1613      * This functions first clears the temporary buffer, then stores
1614      * the packet's data to it. We use this to check the packet's HMAC
1615      * after we received the HMAC key in to following packet.
1616      *
1617      * @param data
1618      *    Pointer to the packet's ZRTP message
1619     */
1620      void storeMsgTemp(ZrtpPacketBase* pkt);
1621 
1622      /**
1623       * Helper function to check a ZRTP message HMAC
1624       *
1625       * This function gets a HMAC key and uses it to compute a HMAC
1626       * with this key and the stored data of a previous received ZRTP
1627       * message. It compares the computed HMAC and the HMAC stored in
1628       * the received message and returns the result.
1629       *
1630       * @param key
1631       *    Pointer to the HMAC key.
1632       * @return
1633       *    Returns true if the computed HMAC and the stored HMAC match,
1634       *    false otherwise.
1635       */
1636      bool checkMsgHmac(uint8_t* key);
1637 
1638      /**
1639       * Set the client ID for ZRTP Hello message.
1640       *
1641       * The user of ZRTP must set its id to identify itself in the
1642       * ZRTP HELLO message. The maximum length is 16 characters. Shorter
1643       * id string are allowed, they will be filled with blanks. A longer id
1644       * is truncated to 16 characters.
1645       *
1646       * The identifier is set in the Hello packet of ZRTP. Thus only after
1647       * setting the identifier ZRTP can compute the HMAC and the final
1648       * helloHash.
1649       *
1650       * @param id
1651       *     The client's id
1652       * @param hpv
1653       *     Pointer to hello packet version structure.
1654       */
1655      void setClientId(std::string id, HelloPacketVersion* hpv);
1656 
1657      /**
1658       * Check and set a nonce.
1659       *
1660       * The function first checks if the nonce is already in use (was seen) in this ZRTP
1661       * session. Refer to 4.4.3.1.
1662       *
1663       * @param nonce
1664       *     The nonce to check and to store if not already seen.
1665       *
1666       * @return
1667       *     True if the the nonce was stroed, thus not yet seen.
1668       */
1669      bool checkAndSetNonce(uint8_t* nonce);
1670 };
1671 
1672 /**
1673  * @}
1674  */
1675 #endif // ZRTP
1676 
1677