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 /*
19  * Authors: Werner Dittmann <Werner.Dittmann@t-online.de>
20  */
21 #include <sstream>
22 
23 #include <crypto/zrtpDH.h>
24 #include <crypto/hmac256.h>
25 #include <crypto/sha256.h>
26 #include <crypto/hmac384.h>
27 #include <crypto/sha384.h>
28 
29 #include <crypto/skeinMac256.h>
30 #include <crypto/skein256.h>
31 #include <crypto/skeinMac384.h>
32 #include <crypto/skein384.h>
33 
34 #include <crypto/aesCFB.h>
35 #include <crypto/twoCFB.h>
36 
37 #include <libzrtpcpp/ZRtp.h>
38 #include <libzrtpcpp/ZrtpStateClass.h>
39 #include <libzrtpcpp/ZIDCache.h>
40 #include <libzrtpcpp/Base32.h>
41 #include <libzrtpcpp/EmojiBase32.h>
42 
43 using namespace GnuZrtpCodes;
44 
45 /* disabled...but used in testing and debugging, probably should have a
46    controlling #define...
47    *
48 static void hexdump(const char* title, const unsigned char *s, int l) {
49     int n=0;
50 
51     if (s == NULL) return;
52 
53     fprintf(stderr, "%s",title);
54     for( ; n < l ; ++n)
55     {
56         if((n%16) == 0)
57             fprintf(stderr, "\n%04x",n);
58         fprintf(stderr, " %02x",s[n]);
59     }
60     fprintf(stderr, "\n");
61 }
62  * */
63 
64 /*
65  * This method simplifies detection of libzrtpcpp inside Automake, configure
66  * and friends
67  */
68 #ifdef __cplusplus
69 extern "C" {
70 #endif
ZrtpAvailable()71     int ZrtpAvailable()
72     {
73         return 1;
74     }
75 #ifdef __cplusplus
76 }
77 #endif
78 
ZRtp(uint8_t * myZid,ZrtpCallback * cb,std::string id,ZrtpConfigure * config,bool mitmm,bool sasSignSupport)79 ZRtp::ZRtp(uint8_t *myZid, ZrtpCallback *cb, std::string id, ZrtpConfigure* config, bool mitmm, bool sasSignSupport):
80         callback(cb), dhContext(NULL), DHss(NULL), auxSecret(NULL), auxSecretLength(0), rs1Valid(false),
81         rs2Valid(false), msgShaContext(NULL), hash(NULL), cipher(NULL), pubKey(NULL), sasType(NULL), authLength(NULL),
82         multiStream(false), multiStreamAvailable(false), peerIsEnrolled(false), mitmSeen(false), pbxSecretTmp(NULL),
83         enrollmentMode(false), configureAlgos(*config), zidRec(NULL), saveZidRecord(true), signSasSeen(false),
84         masterStream(NULL), peerDisclosureFlagSeen(false) {
85 
86 #ifdef ZRTP_SAS_RELAY_SUPPORT
87     enableMitmEnrollment = config->isTrustedMitM();
88 #pragma message "ZRTP SAS relay support is enabled."
89 #else
90     enableMitmEnrollment = false;
91 #endif
92 
93     signatureData = NULL;
94     paranoidMode = config->isParanoidMode();
95     sasSignSupport = config->isSasSignature();
96 
97     // setup the implicit hash function pointers and length
98     hashLengthImpl = SHA256_DIGEST_LENGTH;
99     hashFunctionImpl = sha256;
100     hashListFunctionImpl = sha256;
101 
102     hmacFunctionImpl = hmac_sha256;
103     hmacListFunctionImpl = hmac_sha256;
104 
105     memcpy(ownZid, myZid, ZID_SIZE);        // save the ZID
106 
107     /*
108      * Generate H0 as a random number (256 bits, 32 bytes) and then
109      * the hash chain, refer to chapter 9. Use the implicit hash function.
110      */
111     randomZRTP(H0, HASH_IMAGE_SIZE);
112     sha256(H0, HASH_IMAGE_SIZE, H1);        // hash H0 and generate H1
113     sha256(H1, HASH_IMAGE_SIZE, H2);        // H2
114     sha256(H2, HASH_IMAGE_SIZE, H3);        // H3
115 
116     // configure all supported Hello packet versions
117     zrtpHello_11.configureHello(&configureAlgos);
118     zrtpHello_11.setH3(H3);                    // set H3 in Hello, included in helloHash
119     zrtpHello_11.setZid(ownZid);
120     zrtpHello_11.setVersion((uint8_t*)zrtpVersion_11);
121 
122 
123     zrtpHello_12.configureHello(&configureAlgos);
124     zrtpHello_12.setH3(H3);                 // set H3 in Hello, included in helloHash
125     zrtpHello_12.setZid(ownZid);
126     zrtpHello_12.setVersion((uint8_t*)zrtpVersion_12);
127 
128     if (mitmm) {                            // this session acts for a trusted MitM (PBX)
129         zrtpHello_11.setMitmMode();
130         zrtpHello_12.setMitmMode();
131     }
132     if (sasSignSupport) {                   // the application supports SAS signing
133         zrtpHello_11.setSasSign();
134         zrtpHello_12.setSasSign();
135     }
136 
137     // Keep array in ascending order (greater index -> greater version)
138     helloPackets[0].packet = &zrtpHello_11;
139     helloPackets[0].version = zrtpHello_11.getVersionInt();
140     setClientId(id, &helloPackets[0]);      // set id, compute HMAC and final helloHash
141 
142     helloPackets[1].packet = &zrtpHello_12;
143     helloPackets[1].version = zrtpHello_12.getVersionInt();
144     setClientId(id, &helloPackets[1]);      // set id, compute HMAC and final helloHash
145 
146     currentHelloPacket = helloPackets[SUPPORTED_ZRTP_VERSIONS-1].packet;  // start with highest supported version
147     helloPackets[SUPPORTED_ZRTP_VERSIONS].packet = NULL;
148     peerHelloVersion[0] = 0;
149 
150     stateEngine = new ZrtpStateClass(this);
151 }
152 
~ZRtp()153 ZRtp::~ZRtp() {
154     stopZrtp();
155     if (DHss != NULL) {
156         delete DHss;
157         DHss = NULL;
158     }
159     if (stateEngine != NULL) {
160         delete stateEngine;
161         stateEngine = NULL;
162     }
163     if (dhContext != NULL) {
164         delete dhContext;
165         dhContext = NULL;
166     }
167     if (msgShaContext != NULL) {
168         closeHashCtx(msgShaContext, NULL);
169         msgShaContext = NULL;
170     }
171     if (auxSecret != NULL) {
172         delete auxSecret;
173         auxSecret = NULL;
174         auxSecretLength = 0;
175     }
176     if (zidRec != NULL) {
177         delete zidRec;
178         zidRec = NULL;
179     }
180     memset(hmacKeyI, 0, MAX_DIGEST_LENGTH);
181     memset(hmacKeyR, 0, MAX_DIGEST_LENGTH);
182 
183     memset(zrtpKeyI, 0, MAX_DIGEST_LENGTH);
184     memset(zrtpKeyR, 0, MAX_DIGEST_LENGTH);
185     /*
186      * Clear the Initiator's srtp key and salt
187      */
188     memset(srtpKeyI, 0, MAX_DIGEST_LENGTH);
189     memset(srtpSaltI, 0,  MAX_DIGEST_LENGTH);
190     /*
191      * Clear he Responder's srtp key and salt
192      */
193     memset(srtpKeyR, 0, MAX_DIGEST_LENGTH);
194     memset(srtpSaltR, 0, MAX_DIGEST_LENGTH);
195 
196     memset(zrtpSession, 0, MAX_DIGEST_LENGTH);
197 
198     peerNonces.clear();
199 }
200 
processZrtpMessage(uint8_t * message,uint32_t pSSRC,size_t length)201 void ZRtp::processZrtpMessage(uint8_t *message, uint32_t pSSRC, size_t length) {
202     Event_t ev;
203 
204     peerSSRC = pSSRC;
205     ev.type = ZrtpPacket;
206     ev.length = length;
207     ev.packet = message;
208 
209     if (stateEngine != NULL) {
210         stateEngine->processEvent(&ev);
211     }
212 }
213 
processTimeout()214 void ZRtp::processTimeout() {
215     Event_t ev;
216 
217     ev.type = Timer;
218     if (stateEngine != NULL) {
219         stateEngine->processEvent(&ev);
220     }
221 }
222 
223 #ifdef oldgoclear
handleGoClear(uint8_t * message)224 bool ZRtp::handleGoClear(uint8_t *message)
225 {
226     char *msg, first, last;
227 
228     msg = (char *)message + 4;
229     first = tolower(*msg);
230     last = tolower(*(msg+6));
231 
232     if (first == 'g' && last == 'r') {
233         Event_t ev;
234 
235         ev.type = ZrtpGoClear;
236         ev.packet = message;
237         if (stateEngine != NULL) {
238             stateEngine->processEvent(&ev);
239         }
240         return true;
241     }
242     else {
243         return false;
244     }
245 }
246 #endif
247 
startZrtpEngine()248 void ZRtp::startZrtpEngine() {
249     Event_t ev;
250 
251     if (stateEngine != NULL && stateEngine->inState(Initial)) {
252         ev.type = ZrtpInitial;
253         stateEngine->processEvent(&ev);
254     }
255 }
256 
stopZrtp()257 void ZRtp::stopZrtp() {
258     Event_t ev;
259 
260     if (stateEngine != NULL) {
261         ev.type = ZrtpClose;
262         stateEngine->processEvent(&ev);
263     }
264 }
265 
inState(int32_t state)266 bool ZRtp::inState(int32_t state)
267 {
268     if (stateEngine != NULL) {
269         return stateEngine->inState(state);
270     }
271     else {
272         return false;
273     }
274 }
275 
prepareHello()276 ZrtpPacketHello* ZRtp::prepareHello() {
277     return currentHelloPacket;
278 }
279 
prepareHelloAck()280 ZrtpPacketHelloAck* ZRtp::prepareHelloAck() {
281     return &zrtpHelloAck;
282 }
283 
284 /*
285  * At this point we will assume the role of Initiator. This role may change
286  * in case we have a commit-clash. Refer to chapter 5.2 in the spec how
287  * to break this tie.
288  */
prepareCommit(ZrtpPacketHello * hello,uint32_t * errMsg)289 ZrtpPacketCommit* ZRtp::prepareCommit(ZrtpPacketHello *hello, uint32_t* errMsg) {
290 
291     myRole = Initiator;
292 
293     if (!hello->isLengthOk()) {
294         *errMsg = CriticalSWError;
295         return NULL;
296     }
297     // Save data before detailed checks - may aid in analysing problems
298     peerClientId.assign((char*)hello->getClientId(), ZRTP_WORD_SIZE * 4);
299     memcpy(peerHelloVersion, hello->getVersion(), ZRTP_WORD_SIZE);
300     peerHelloVersion[ZRTP_WORD_SIZE] = 0;
301 
302     // Save our peer's (presumably the Responder) ZRTP id
303     memcpy(peerZid, hello->getZid(), ZID_SIZE);
304     if (memcmp(peerZid, ownZid, ZID_SIZE) == 0) {       // peers have same ZID????
305         *errMsg = EqualZIDHello;
306         return NULL;
307     }
308     memcpy(peerH3, hello->getH3(), HASH_IMAGE_SIZE);
309 
310     int32_t helloLen = hello->getLength() * ZRTP_WORD_SIZE;
311 
312     // calculate hash over the received Hello packet - is peer's hello hash.
313     // Use implicit hash algorithm
314     hashFunctionImpl((unsigned char*)hello->getHeaderBase(), helloLen, peerHelloHash);
315 
316     sendInfo(Info, InfoHelloReceived);
317 
318     /*
319      * The Following section extracts the algorithm from the peer's Hello
320      * packet. Always the preferend offered algorithms are
321      * used. If the received Hello does not contain algo specifiers
322      * or offers only unsupported optional algos then replace
323      * these with mandatory algos and put them into the Commit packet.
324      * Refer to the findBest*() functions.
325      * If this is a MultiStream ZRTP object then do not get the cipher,
326      * authentication from hello packet but use the pre-initialized values
327      * as proposed by the standard. If we switch to responder mode the
328      * commit packet may contain other algos - see function
329      * prepareConfirm2MultiStream(...).
330      */
331     sasType = findBestSASType(hello);
332 
333     if (!multiStream) {
334         pubKey = findBestPubkey(hello);                 // Check for public key algorithm first, must set 'hash' as well
335         if (hash == NULL) {
336             *errMsg = UnsuppHashType;
337             return NULL;
338         }
339         if (cipher == NULL)                             // public key selection may have set the cipher already
340             cipher = findBestCipher(hello, pubKey);
341         if (authLength == NULL)                         // public key selection may have set the SRTP authLen already
342             authLength = findBestAuthLen(hello);
343         multiStreamAvailable = checkMultiStream(hello);
344     }
345     else {
346         if (checkMultiStream(hello)) {
347             return prepareCommitMultiStream(hello);
348         }
349         else {
350             // we are in multi-stream but peer does not offer multi-stream
351             // return error code to other party - unsupported PK, must be Mult
352             *errMsg = UnsuppPKExchange;
353             return NULL;
354         }
355     }
356     setNegotiatedHash(hash);
357 
358     // Modify here when introducing new DH key agreement, for example
359     // elliptic curves.
360     dhContext = new ZrtpDH(pubKey->getName());
361     dhContext->generatePublicKey();
362 
363     dhContext->getPubKeyBytes(pubKeyBytes);
364     sendInfo(Info, InfoCommitDHGenerated);
365 
366     // Prepare IV data that we will use during confirm packet encryption.
367     randomZRTP(randomIV, sizeof(randomIV));
368 
369     /*
370      * Prepare our DHPart2 packet here. Required to compute HVI. If we stay
371      * in Initiator role then we reuse this packet later in prepareDHPart2().
372      * To create this DH packet we have to compute the retained secret ids,
373      * thus get our peer's retained secret data first.
374      */
375     zidRec = getZidCacheInstance()->getRecord(peerZid);
376 
377     //Compute the Initator's and Responder's retained secret ids.
378     computeSharedSecretSet(zidRec);
379 
380 #ifdef ZRTP_SAS_RELAY_SUPPORT
381     // Check if a PBX application set the MitM flag.
382     mitmSeen = hello->isMitmMode();
383 #endif
384 
385     signSasSeen = hello->isSasSign();
386 
387     // Construct a DHPart2 message (Initiator's DH message). This packet
388     // is required to compute the HVI (Hash Value Initiator), refer to
389     // chapter 5.4.1.1.
390 
391     // Fill the values in the DHPart2 packet
392     zrtpDH2.setPubKeyType(pubKey->getName());
393     zrtpDH2.setMessageType((uint8_t*)DHPart2Msg);
394     zrtpDH2.setRs1Id(rs1IDi);
395     zrtpDH2.setRs2Id(rs2IDi);
396     zrtpDH2.setAuxSecretId(auxSecretIDi);
397     zrtpDH2.setPbxSecretId(pbxSecretIDi);
398     zrtpDH2.setPv(pubKeyBytes);
399     zrtpDH2.setH1(H1);
400 
401     int32_t len = zrtpDH2.getLength() * ZRTP_WORD_SIZE;
402 
403     // Compute HMAC over DH2, excluding the HMAC field (HMAC_SIZE)
404     // and store in DH2. Key to HMAC is H0, use HASH_IMAGE_SIZE bytes only.
405     // Must use implicit HMAC functions.
406     uint8_t hmac[IMPL_MAX_DIGEST_LENGTH];
407     uint32_t macLen;
408     hmacFunctionImpl(H0, HASH_IMAGE_SIZE, (uint8_t*)zrtpDH2.getHeaderBase(), len-(HMAC_SIZE), hmac, &macLen);
409     zrtpDH2.setHMAC(hmac);
410 
411     // Compute the HVI, refer to chapter 5.4.1.1 of the specification
412     computeHvi(&zrtpDH2, hello);
413 
414     zrtpCommit.setZid(ownZid);
415     zrtpCommit.setHashType((uint8_t*)hash->getName());
416     zrtpCommit.setCipherType((uint8_t*)cipher->getName());
417     zrtpCommit.setAuthLen((uint8_t*)authLength->getName());
418     zrtpCommit.setPubKeyType((uint8_t*)pubKey->getName());
419     zrtpCommit.setSasType((uint8_t*)sasType->getName());
420     zrtpCommit.setHvi(hvi);
421     zrtpCommit.setH2(H2);
422 
423     len = zrtpCommit.getLength() * ZRTP_WORD_SIZE;
424 
425     // Compute HMAC over Commit, excluding the HMAC field (HMAC_SIZE)
426     // and store in Hello. Key to HMAC is H1, use HASH_IMAGE_SIZE bytes only.
427     // Must use implicit HMAC functions.
428     hmacFunctionImpl(H1, HASH_IMAGE_SIZE, (uint8_t*)zrtpCommit.getHeaderBase(), len-(HMAC_SIZE), hmac, &macLen);
429     zrtpCommit.setHMAC(hmac);
430 
431     // hash first messages to produce overall message hash
432     // First the Responder's Hello message, second the Commit (always Initator's).
433     // Must use negotiated hash.
434     msgShaContext = createHashCtx(msgShaContext);
435     hashCtxFunction(msgShaContext, (unsigned char*)hello->getHeaderBase(), helloLen);
436     hashCtxFunction(msgShaContext, (unsigned char*)zrtpCommit.getHeaderBase(), len);
437 
438     // store Hello data temporarily until we can check HMAC after receiving Commit as
439     // Responder or DHPart1 as Initiator
440     storeMsgTemp(hello);
441 
442     return &zrtpCommit;
443 }
444 
prepareCommitMultiStream(ZrtpPacketHello * hello)445 ZrtpPacketCommit* ZRtp::prepareCommitMultiStream(ZrtpPacketHello *hello) {
446 
447     randomZRTP(hvi, ZRTP_WORD_SIZE*4);  // This is the Multi-Stream NONCE size
448 
449     zrtpCommit.setZid(ownZid);
450     zrtpCommit.setHashType((uint8_t*)hash->getName());
451     zrtpCommit.setCipherType((uint8_t*)cipher->getName());
452     zrtpCommit.setAuthLen((uint8_t*)authLength->getName());
453     zrtpCommit.setPubKeyType((uint8_t*)mult);  // this is fixed because of Multi Stream mode
454     zrtpCommit.setSasType((uint8_t*)sasType->getName());
455     zrtpCommit.setNonce(hvi);
456     zrtpCommit.setH2(H2);
457 
458     int32_t len = zrtpCommit.getLength() * ZRTP_WORD_SIZE;
459 
460     // Compute HMAC over Commit, excluding the HMAC field (HMAC_SIZE)
461     // and store in Hello. Key to HMAC is H1, use HASH_IMAGE_SIZE bytes only.
462     // Must use the implicit HMAC function.
463     uint8_t hmac[IMPL_MAX_DIGEST_LENGTH];
464     uint32_t macLen;
465     hmacFunctionImpl(H1, HASH_IMAGE_SIZE, (uint8_t*)zrtpCommit.getHeaderBase(), len-(HMAC_SIZE), hmac, &macLen);
466     zrtpCommit.setHMACMulti(hmac);
467 
468 
469     // hash first messages to produce overall message hash
470     // First the Responder's Hello message, second the Commit
471     // (always Initator's).
472     // Must use the negotiated hash.
473     msgShaContext = createHashCtx(msgShaContext);
474 
475     int32_t helloLen = hello->getLength() * ZRTP_WORD_SIZE;
476     hashCtxFunction(msgShaContext, (unsigned char*)hello->getHeaderBase(), helloLen);
477     hashCtxFunction(msgShaContext, (unsigned char*)zrtpCommit.getHeaderBase(), len);
478 
479     // store Hello data temporarily until we can check HMAC after receiving Commit as
480     // Responder or DHPart1 as Initiator
481     storeMsgTemp(hello);
482 
483     return &zrtpCommit;
484 }
485 
486 /*
487  * At this point we will take the role of the Responder. We have been in
488  * the role of the Initiator before and already sent a commit packet that
489  * clashed with a commit packet from our peer. If our HVI was lower than our
490  * peer's HVI then we switched to Responder and handle our peer's commit packet
491  * here. This method takes care to delete and refresh data left over from a
492  * possible Initiator preparation. This belongs to prepared DH data, message
493  * hash SHA context
494  */
prepareDHPart1(ZrtpPacketCommit * commit,uint32_t * errMsg)495 ZrtpPacketDHPart* ZRtp::prepareDHPart1(ZrtpPacketCommit *commit, uint32_t* errMsg) {
496 
497     sendInfo(Info, InfoRespCommitReceived);
498 
499     if (!commit->isLengthOk(ZrtpPacketCommit::DhExchange)) {
500         *errMsg = CriticalSWError;
501         return NULL;
502     }
503 
504     // Check if ZID in Commit is the same as we got in Hello
505     uint8_t tmpZid[ZID_SIZE];
506     memcpy(tmpZid, commit->getZid(), ZID_SIZE);
507     if (memcmp(peerZid, tmpZid, ZID_SIZE) != 0) {       // ZIDs do not match????
508         sendInfo(Severe, SevereProtocolError);
509         *errMsg = CriticalSWError;
510         return NULL;
511     }
512 
513     // The following code checks the hash chain according chapter 10 to detect false ZRTP packets.
514     // Must use the implicit hash function.
515     uint8_t tmpH3[IMPL_MAX_DIGEST_LENGTH];
516     memcpy(peerH2, commit->getH2(), HASH_IMAGE_SIZE);
517     hashFunctionImpl(peerH2, HASH_IMAGE_SIZE, tmpH3);
518 
519     if (memcmp(tmpH3, peerH3, HASH_IMAGE_SIZE) != 0) {
520         *errMsg = IgnorePacket;
521         return NULL;
522     }
523 
524     // Check HMAC of previous Hello packet stored in temporary buffer. The
525     // HMAC key of peer's Hello packet is peer's H2 that is contained in the
526     // Commit packet. Refer to chapter 9.1.
527     if (!checkMsgHmac(peerH2)) {
528         sendInfo(Severe, SevereHelloHMACFailed);
529         *errMsg = CriticalSWError;
530         return NULL;
531     }
532 
533     // check if we support the commited Cipher type
534     AlgorithmEnum* cp = &zrtpSymCiphers.getByName((const char*)commit->getCipherType());
535     if (!cp->isValid()) { // no match - something went wrong
536         *errMsg = UnsuppCiphertype;
537         return NULL;
538     }
539     cipher = cp;
540 
541     // check if we support the commited Authentication length
542     cp = &zrtpAuthLengths.getByName((const char*)commit->getAuthLen());
543     if (!cp->isValid()) { // no match - something went wrong
544         *errMsg = UnsuppSRTPAuthTag;
545         return NULL;
546     }
547     authLength = cp;
548 
549     // check if we support the commited hash type
550     cp = &zrtpHashes.getByName((const char*)commit->getHashType());
551     if (!cp->isValid()) { // no match - something went wrong
552         *errMsg = UnsuppHashType;
553         return NULL;
554     }
555     // check if the peer's commited hash is the same that we used when
556     // preparing our commit packet. If not do the necessary resets and
557     // recompute some data.
558     if (*(int32_t*)(hash->getName()) != *(int32_t*)(cp->getName())) {
559         hash = cp;
560         setNegotiatedHash(hash);
561         // Compute the Initator's and Responder's retained secret ids
562         // with the committed hash.
563         computeSharedSecretSet(zidRec);
564     }
565     // check if we support the commited pub key type
566     cp = &zrtpPubKeys.getByName((const char*)commit->getPubKeysType());
567     if (!cp->isValid()) { // no match - something went wrong
568         *errMsg = UnsuppPKExchange;
569         return NULL;
570     }
571     if (*(int32_t*)(cp->getName()) == *(int32_t*)ec38 || *(int32_t*)(cp->getName()) == *(int32_t*)e414) {
572         if (!(*(int32_t*)(hash->getName()) == *(int32_t*)s384 || *(int32_t*)(hash->getName()) == *(int32_t*)skn3)) {
573             *errMsg = UnsuppHashType;
574             return NULL;
575         }
576     }
577     pubKey = cp;
578 
579     // check if we support the commited SAS type
580     cp = &zrtpSasTypes.getByName((const char*)commit->getSasType());
581     if (!cp->isValid()) { // no match - something went wrong
582         *errMsg = UnsuppSASScheme;
583         return NULL;
584     }
585     sasType = cp;
586 
587     // dhContext cannot be NULL - always setup during prepareCommit()
588     // check if we can use the dhContext prepared by prepareCommit(),
589     // if not delete old DH context and generate new one
590     // The algorithm names are 4 chars only, thus we can cast to int32_t
591     if (*(int32_t*)(dhContext->getDHtype()) != *(int32_t*)(pubKey->getName())) {
592         delete dhContext;
593         dhContext = new ZrtpDH(pubKey->getName());
594         dhContext->generatePublicKey();
595     }
596     sendInfo(Info, InfoDH1DHGenerated);
597 
598     dhContext->getPubKeyBytes(pubKeyBytes);
599 
600     // Re-compute auxSecretIDr because we changed roles *IDr with my H3, *IDi with peer's H3
601     // Setup a DHPart1 packet.
602     myRole = Responder;
603     computeAuxSecretIds();                 // recompute AUX secret ids because we are now Responder, use different H3
604 
605     zrtpDH1.setPubKeyType(pubKey->getName());
606     zrtpDH1.setMessageType((uint8_t*)DHPart1Msg);
607     zrtpDH1.setRs1Id(rs1IDr);
608     zrtpDH1.setRs2Id(rs2IDr);
609     zrtpDH1.setAuxSecretId(auxSecretIDr);
610     zrtpDH1.setPbxSecretId(pbxSecretIDr);
611     zrtpDH1.setPv(pubKeyBytes);
612     zrtpDH1.setH1(H1);
613 
614     int32_t len = zrtpDH1.getLength() * ZRTP_WORD_SIZE;
615 
616     // Compute HMAC over DHPart1, excluding the HMAC field (HMAC_SIZE)
617     // and store in DHPart1.
618     // Use implicit Hash function
619     uint8_t hmac[IMPL_MAX_DIGEST_LENGTH];
620     uint32_t macLen;
621     hmacFunctionImpl(H0, HASH_IMAGE_SIZE, (uint8_t*)zrtpDH1.getHeaderBase(), len-(HMAC_SIZE), hmac, &macLen);
622     zrtpDH1.setHMAC(hmac);
623 
624     // We are definitly responder. Save the peer's hvi for later compare.
625     memcpy(peerHvi, commit->getHvi(), HVI_SIZE);
626 
627     // We are responder. Release the pre-computed SHA context because it was prepared for Initiator.
628     // Setup and compute for Responder.
629     if (msgShaContext != NULL) {
630         closeHashCtx(msgShaContext, NULL);
631     }
632     msgShaContext = createHashCtx(msgShaContext);
633 
634     // Hash messages to produce overall message hash:
635     // First the Responder's (my) Hello message, second the Commit (always Initator's),
636     // then the DH1 message (which is always a Responder's message).
637     // Must use negotiated hash.
638     hashCtxFunction(msgShaContext, (unsigned char*)currentHelloPacket->getHeaderBase(), currentHelloPacket->getLength() * ZRTP_WORD_SIZE);
639     hashCtxFunction(msgShaContext, (unsigned char*)commit->getHeaderBase(), commit->getLength() * ZRTP_WORD_SIZE);
640     hashCtxFunction(msgShaContext, (unsigned char*)zrtpDH1.getHeaderBase(), zrtpDH1.getLength() * ZRTP_WORD_SIZE);
641 
642     // store Commit data temporarily until we can check HMAC after we got DHPart2
643     storeMsgTemp(commit);
644 
645     return &zrtpDH1;
646 }
647 
648 /*
649  * At this point we will take the role of the Initiator.
650  */
prepareDHPart2(ZrtpPacketDHPart * dhPart1,uint32_t * errMsg)651 ZrtpPacketDHPart* ZRtp::prepareDHPart2(ZrtpPacketDHPart *dhPart1, uint32_t* errMsg) {
652 
653     uint8_t* pvr;
654 
655     sendInfo(Info, InfoInitDH1Received);
656 
657     if (!dhPart1->isLengthOk()) {
658         *errMsg = CriticalSWError;
659         return NULL;
660     }
661     // Because we are initiator the protocol engine didn't receive Commit
662     // thus could not store a peer's H2. A two step SHA256 is required to
663     // re-compute H3. Then compare with peer's H3 from peer's Hello packet.
664     // Must use implicit hash function.
665     uint8_t tmpHash[IMPL_MAX_DIGEST_LENGTH];
666     hashFunctionImpl(dhPart1->getH1(), HASH_IMAGE_SIZE, tmpHash); // Compute peer's H2
667     memcpy(peerH2, tmpHash, HASH_IMAGE_SIZE);
668     hashFunctionImpl(peerH2, HASH_IMAGE_SIZE, tmpHash);          // Compute peer's H3 (tmpHash)
669 
670     if (memcmp(tmpHash, peerH3, HASH_IMAGE_SIZE) != 0) {
671         *errMsg = IgnorePacket;
672         return NULL;
673     }
674 
675     // Check HMAC of previous Hello packet stored in temporary buffer. The
676     // HMAC key of the Hello packet is peer's H2 that was computed above.
677     // Refer to chapter 9.1 and chapter 10.
678     if (!checkMsgHmac(peerH2)) {
679         sendInfo(Severe, SevereHelloHMACFailed);
680         *errMsg = CriticalSWError;
681         return NULL;
682     }
683 
684     // get memory to store DH result TODO: make it fixed memory
685     DHss = new uint8_t[dhContext->getDhSize()];
686     if (DHss == NULL) {
687         *errMsg = CriticalSWError;
688         return NULL;
689     }
690 
691     // get and check Responder's public value, see chap. 5.4.3 in the spec
692     pvr = dhPart1->getPv();
693     if (pvr == NULL) {
694         *errMsg = IgnorePacket;
695         return NULL;
696     }
697     if (!dhContext->checkPubKey(pvr)) {
698         *errMsg = DHErrorWrongPV;
699         return NULL;
700     }
701     dhContext->computeSecretKey(pvr, DHss);
702 
703     // We are Initiator: the Responder's Hello and the Initiator's (our) Commit
704     // are already hashed in the context. Now hash the Responder's DH1 and then
705     // the Initiator's (our) DH2 in that order.
706     // Use the negotiated hash function.
707     hashCtxFunction(msgShaContext, (unsigned char*)dhPart1->getHeaderBase(), dhPart1->getLength() * ZRTP_WORD_SIZE);
708     hashCtxFunction(msgShaContext, (unsigned char*)zrtpDH2.getHeaderBase(), zrtpDH2.getLength() * ZRTP_WORD_SIZE);
709 
710     // Compute the message Hash
711     closeHashCtx(msgShaContext, messageHash);
712     msgShaContext = NULL;
713     // Now compute the S0, all dependend keys and the new RS1. The function
714     // also performs sign SAS callback if it's active.
715     generateKeysInitiator(dhPart1, zidRec);
716 
717     delete dhContext;
718     dhContext = NULL;
719 
720     // TODO: at initiator we can call signSAS at this point, don't dealy until confirm1 reveived
721     // store DHPart1 data temporarily until we can check HMAC after receiving Confirm1
722     storeMsgTemp(dhPart1);
723     return &zrtpDH2;
724 }
725 
726 /*
727  * At this point we are Responder.
728  */
prepareConfirm1(ZrtpPacketDHPart * dhPart2,uint32_t * errMsg)729 ZrtpPacketConfirm* ZRtp::prepareConfirm1(ZrtpPacketDHPart* dhPart2, uint32_t* errMsg) {
730 
731     uint8_t* pvi;
732 
733     sendInfo(Info, InfoRespDH2Received);
734 
735     if (!dhPart2->isLengthOk()) {
736         *errMsg = CriticalSWError;
737         return NULL;
738     }
739     // Because we are responder we received a Commit and stored its H2.
740     // Now re-compute H2 from received H1 and compare with stored peer's H2.
741     // Use implicit hash function
742     uint8_t tmpHash[IMPL_MAX_DIGEST_LENGTH];
743     hashFunctionImpl(dhPart2->getH1(), HASH_IMAGE_SIZE, tmpHash);
744     if (memcmp(tmpHash, peerH2, HASH_IMAGE_SIZE) != 0) {
745         *errMsg = IgnorePacket;
746         return NULL;
747     }
748 
749     // Check HMAC of Commit packet stored in temporary buffer. The
750     // HMAC key of the Commit packet is peer's H1 that is contained in
751     // DHPart2. Refer to chapter 9.1 and chapter 10.
752     if (!checkMsgHmac(dhPart2->getH1())) {
753         sendInfo(Severe, SevereCommitHMACFailed);
754         *errMsg = CriticalSWError;
755         return NULL;
756     }
757     // Now we have the peer's pvi. Because we are responder re-compute my hvi
758     // using my Hello packet and the Initiator's DHPart2 and compare with
759     // hvi sent in commit packet. If it doesn't macht then a MitM attack
760     // may have occured.
761     computeHvi(dhPart2, currentHelloPacket);
762     if (memcmp(hvi, peerHvi, HVI_SIZE) != 0) {
763         *errMsg = DHErrorWrongHVI;
764         return NULL;
765     }
766     DHss = new uint8_t[dhContext->getDhSize()];
767     if (DHss == NULL) {
768         *errMsg = CriticalSWError;
769         return NULL;
770     }
771     // Get and check the Initiator's public value, see chap. 5.4.2 of the spec
772     pvi = dhPart2->getPv();
773     if (!dhContext->checkPubKey(pvi)) {
774         *errMsg = DHErrorWrongPV;
775         return NULL;
776     }
777     dhContext->computeSecretKey(pvi, DHss);
778 
779     // Hash the Initiator's DH2 into the message Hash (other messages already prepared, see method prepareDHPart1().
780     // Use neotiated hash function
781     hashCtxFunction(msgShaContext, (unsigned char*)dhPart2->getHeaderBase(), dhPart2->getLength() * ZRTP_WORD_SIZE);
782 
783     closeHashCtx(msgShaContext, messageHash);
784     msgShaContext = NULL;
785     /*
786      * The expected shared secret Ids were already computed when we built the
787      * DHPart1 packet. Generate s0, all depended keys, and the new RS1 value
788      * for the ZID record. The functions also performs sign SAS callback if it's
789      * active. May reset the verify flag in ZID record.
790      */
791     generateKeysResponder(dhPart2, zidRec);
792 
793     delete dhContext;
794     dhContext = NULL;
795 
796     // Fill in Confirm1 packet.
797     zrtpConfirm1.setMessageType((uint8_t*)Confirm1Msg);
798 
799     // Check if user verfied the SAS in a previous call and thus verfied
800     // the retained secret. Don't set the verified flag if paranoidMode is true.
801     if (zidRec->isSasVerified() && !paranoidMode) {
802         zrtpConfirm1.setSASFlag();
803     }
804     if (configureAlgos.isDisclosureFlag()) {
805         zrtpConfirm1.setDisclosureFlag();
806     }
807     zrtpConfirm1.setExpTime(0xFFFFFFFF);
808     zrtpConfirm1.setIv(randomIV);
809     zrtpConfirm1.setHashH0(H0);
810 
811 #ifdef ZRTP_SAS_RELAY_SUPPORT
812     // if this runs at PBX user agent enrollment service then set flag in confirm
813     // packet and store the MitM key
814     if (enrollmentMode) {
815         // As clarification to RFC6189: store new PBX secret only if we don't have
816         // a matching PBX secret for the peer's ZID.
817         if (!peerIsEnrolled) {
818             computePBXSecret();
819             zidRec->setMiTMData(pbxSecretTmp);
820         }
821         // Set flag to enable user's client to ask for confirmation or re-confirmation.
822         zrtpConfirm1.setPBXEnrollment();
823     }
824 #endif
825     uint8_t confMac[MAX_DIGEST_LENGTH];
826     uint32_t macLen;
827 
828     // Encrypt and HMAC with Responder's key - we are Respondere here
829     int hmlen = (zrtpConfirm1.getLength() - 9) * ZRTP_WORD_SIZE;
830     cipher->getEncrypt()(zrtpKeyR, cipher->getKeylen(), randomIV, zrtpConfirm1.getHashH0(), hmlen);
831     hmacFunction(hmacKeyR, hashLength, (unsigned char*)zrtpConfirm1.getHashH0(), hmlen, confMac, &macLen);
832 
833     zrtpConfirm1.setHmac(confMac);
834 
835     // store DHPart2 data temporarily until we can check HMAC after receiving Confirm2
836     storeMsgTemp(dhPart2);
837     return &zrtpConfirm1;
838 }
839 
840 /*
841  * At this point we are Responder.
842  */
prepareConfirm1MultiStream(ZrtpPacketCommit * commit,uint32_t * errMsg)843 ZrtpPacketConfirm* ZRtp::prepareConfirm1MultiStream(ZrtpPacketCommit* commit, uint32_t* errMsg) {
844 
845     sendInfo(Info, InfoRespCommitReceived);
846 
847     if (!commit->isLengthOk(ZrtpPacketCommit::MultiStream)) {
848         *errMsg = CriticalSWError;
849         return NULL;
850     }
851     // The following code checks the hash chain according chapter 10 to detect
852     // false ZRTP packets.
853     // Use implicit hash function
854     uint8_t tmpH3[IMPL_MAX_DIGEST_LENGTH];
855     memcpy(peerH2, commit->getH2(), HASH_IMAGE_SIZE);
856     hashFunctionImpl(peerH2, HASH_IMAGE_SIZE, tmpH3);
857 
858     if (memcmp(tmpH3, peerH3, HASH_IMAGE_SIZE) != 0) {
859         *errMsg = IgnorePacket;
860         return NULL;
861     }
862 
863     // Check HMAC of previous Hello packet stored in temporary buffer. The
864     // HMAC key of peer's Hello packet is peer's H2 that is contained in the
865     // Commit packet. Refer to chapter 9.1.
866     if (!checkMsgHmac(peerH2)) {
867         sendInfo(Severe, SevereHelloHMACFailed);
868         *errMsg = CriticalSWError;
869         return NULL;
870     }
871 
872     if (!checkAndSetNonce(commit->getNonce())) {
873         *errMsg = NonceReused;
874         return NULL;
875     }
876     // check if Commit contains "Mult" as pub key type
877     AlgorithmEnum* cp = &zrtpPubKeys.getByName((const char*)commit->getPubKeysType());
878     if (!cp->isValid() || *(int32_t*)(cp->getName()) != *(int32_t*)mult) {
879         *errMsg = UnsuppPKExchange;
880         return NULL;
881     }
882 
883     // check if we support the commited cipher
884     cp = &zrtpSymCiphers.getByName((const char*)commit->getCipherType());
885     if (!cp->isValid()) { // no match - something went wrong
886         *errMsg = UnsuppCiphertype;
887         return NULL;
888     }
889     cipher = cp;
890 
891     // check if we support the commited Authentication length
892     cp = &zrtpAuthLengths.getByName((const char*)commit->getAuthLen());
893     if (!cp->isValid()) { // no match - something went wrong
894         *errMsg = UnsuppSRTPAuthTag;
895         return NULL;
896     }
897     authLength = cp;
898 
899     // check if we support the commited hash type
900     cp = &zrtpHashes.getByName((const char*)commit->getHashType());
901     if (!cp->isValid()) { // no match - something went wrong
902         *errMsg = UnsuppHashType;
903         return NULL;
904     }
905     // check if the peer's commited hash is the same that we used when
906     // preparing our commit packet. If not do the necessary resets and
907     // recompute some data.
908     if (*(int32_t*)(hash->getName()) != *(int32_t*)(cp->getName())) {
909         hash = cp;
910         setNegotiatedHash(hash);
911     }
912     myRole = Responder;
913 
914     // We are responder. Release a possibly pre-computed SHA256 context
915     // because this was prepared for Initiator. Then create a new one.
916     if (msgShaContext != NULL) {
917         closeHashCtx(msgShaContext, NULL);
918     }
919     msgShaContext = createHashCtx(msgShaContext);
920 
921     // Hash messages to produce overall message hash:
922     // First the Responder's (my) Hello message, second the Commit
923     // (always Initator's)
924     // use negotiated hash
925     hashCtxFunction(msgShaContext, (unsigned char*)currentHelloPacket->getHeaderBase(), currentHelloPacket->getLength() * ZRTP_WORD_SIZE);
926     hashCtxFunction(msgShaContext, (unsigned char*)commit->getHeaderBase(), commit->getLength() * ZRTP_WORD_SIZE);
927 
928     closeHashCtx(msgShaContext, messageHash);
929     msgShaContext = NULL;
930 
931     generateKeysMultiStream();
932 
933     // Fill in Confirm1 packet.
934     zrtpConfirm1.setMessageType((uint8_t*)Confirm1Msg);
935     if (configureAlgos.isDisclosureFlag()) {
936         zrtpConfirm1.setDisclosureFlag();
937     }
938     zrtpConfirm1.setExpTime(0xFFFFFFFF);
939     zrtpConfirm1.setIv(randomIV);
940     zrtpConfirm1.setHashH0(H0);
941 
942     uint8_t confMac[MAX_DIGEST_LENGTH];
943     uint32_t macLen;
944 
945     // Encrypt and HMAC with Responder's key - we are Respondere here
946     int32_t hmlen = (zrtpConfirm1.getLength() - 9) * ZRTP_WORD_SIZE;
947     cipher->getEncrypt()(zrtpKeyR, cipher->getKeylen(), randomIV, zrtpConfirm1.getHashH0(), hmlen);
948 
949     // Use negotiated HMAC (hash)
950     hmacFunction(hmacKeyR, hashLength, (unsigned char*)zrtpConfirm1.getHashH0(), hmlen, confMac, &macLen);
951 
952     zrtpConfirm1.setHmac(confMac);
953 
954     // Store Commit data temporarily until we can check HMAC after receiving Confirm2
955     storeMsgTemp(commit);
956     return &zrtpConfirm1;
957 }
958 
959 /*
960  * At this point we are Initiator.
961  */
prepareConfirm2(ZrtpPacketConfirm * confirm1,uint32_t * errMsg)962 ZrtpPacketConfirm* ZRtp::prepareConfirm2(ZrtpPacketConfirm* confirm1, uint32_t* errMsg) {
963 
964     sendInfo(Info, InfoInitConf1Received);
965 
966     if (!confirm1->isLengthOk()) {
967         *errMsg = CriticalSWError;
968         return NULL;
969     }
970     uint8_t confMac[MAX_DIGEST_LENGTH];
971     uint32_t macLen;
972 
973     // Use the Responder's keys here because we are Initiator here and
974     // receive packets from Responder
975     int16_t hmlen = (confirm1->getLength() - 9) * ZRTP_WORD_SIZE;
976 
977     // Use negotiated HMAC (hash)
978     hmacFunction(hmacKeyR, hashLength, (unsigned char*)confirm1->getHashH0(), hmlen, confMac, &macLen);
979 
980     if (memcmp(confMac, confirm1->getHmac(), HMAC_SIZE) != 0) {
981         *errMsg = ConfirmHMACWrong;
982         return NULL;
983     }
984     cipher->getDecrypt()(zrtpKeyR, cipher->getKeylen(), (uint8_t*)confirm1->getIv(), confirm1->getHashH0(), hmlen);
985 
986     // Check HMAC of DHPart1 packet stored in temporary buffer. The
987     // HMAC key of the DHPart1 packet is peer's H0 that is contained in
988     // Confirm1. Refer to chapter 9.
989     if (!checkMsgHmac(confirm1->getHashH0())) {
990         sendInfo(Severe, SevereDH1HMACFailed);
991         *errMsg = CriticalSWError;
992         return NULL;
993     }
994     /*
995      * The Confirm1 is ok, handle the Retained secret stuff and inform
996      * GUI about state.
997      */
998     bool sasFlag = confirm1->isSASFlag();
999 
1000     // Our peer did not confirm the SAS in last session, thus reset
1001     // our SAS flag too. Reset the flag also if paranoidMode is true.
1002     if (!sasFlag || paranoidMode) {
1003         zidRec->resetSasVerified();
1004     }
1005 
1006     // Store the status of the Disclosure flag
1007     peerDisclosureFlagSeen = confirm1->isDisclosureFlag();
1008 
1009     // get verified flag from current RS1 before set a new RS1. This
1010     // may not be set even if peer's flag is set in confirm1 message.
1011     sasFlag = zidRec->isSasVerified();
1012 
1013     signatureLength = confirm1->getSignatureLength();
1014     if (signSasSeen && signatureLength > 0 && confirm1->isSignatureLengthOk()) {
1015         signatureData = confirm1->getSignatureData();
1016         callback->checkSASSignature(sasHash);
1017         // TODO: error handling if checkSASSignature returns false.
1018     }
1019     // now we are ready to save the new RS1 which inherits the verified
1020     // flag from old RS1
1021     zidRec->setNewRs1((const uint8_t*)newRs1);
1022 
1023     // now generate my Confirm2 message
1024     zrtpConfirm2.setMessageType((uint8_t*)Confirm2Msg);
1025     zrtpConfirm2.setHashH0(H0);
1026 
1027     if (sasFlag) {
1028         zrtpConfirm2.setSASFlag();
1029     }
1030     if (configureAlgos.isDisclosureFlag()) {
1031         zrtpConfirm2.setDisclosureFlag();
1032     }
1033     zrtpConfirm2.setExpTime(0xFFFFFFFF);
1034     zrtpConfirm2.setIv(randomIV);
1035 
1036 #ifdef ZRTP_SAS_RELAY_SUPPORT
1037     // Compute PBX secret if we are in enrollemnt mode (PBX user agent)
1038     // or enrollment was enabled at normal user agent and flag in confirm packet
1039     if (enrollmentMode || (enableMitmEnrollment && confirm1->isPBXEnrollment())) {
1040         computePBXSecret();
1041 
1042         // if this runs at PBX user agent enrollment service then set flag in confirm
1043         // packet and store the MitM key. The PBX user agent service always stores
1044         // its MitM key.
1045         if (enrollmentMode) {
1046             // As clarification to RFC6189: store new PBX secret only if we don't have
1047             // a matching PBX secret for the peer's ZID.
1048             if (!peerIsEnrolled) {
1049                 computePBXSecret();
1050                 zidRec->setMiTMData(pbxSecretTmp);
1051             }
1052             // Set flag to enable user's client to ask for confirmation or re-confirmation.
1053             zrtpConfirm2.setPBXEnrollment();
1054         }
1055     }
1056 #endif
1057     if (saveZidRecord)
1058         getZidCacheInstance()->saveRecord(zidRec);
1059 
1060     // Encrypt and HMAC with Initiator's key - we are Initiator here
1061     hmlen = (zrtpConfirm2.getLength() - 9) * ZRTP_WORD_SIZE;
1062     cipher->getEncrypt()(zrtpKeyI, cipher->getKeylen(), randomIV, zrtpConfirm2.getHashH0(), hmlen);
1063 
1064     // Use negotiated HMAC (hash)
1065     hmacFunction(hmacKeyI, hashLength, (unsigned char*)zrtpConfirm2.getHashH0(), hmlen, confMac, &macLen);
1066 
1067     zrtpConfirm2.setHmac(confMac);
1068 
1069 #ifdef ZRTP_SAS_RELAY_SUPPORT
1070     // Ask for enrollment only if enabled via configuration and the
1071     // confirm1 packet contains the enrollment flag. The enrolling user
1072     // agent stores the MitM key only if the user accepts the enrollment
1073     // request.
1074     if (enableMitmEnrollment && confirm1->isPBXEnrollment()) {
1075         // As clarification to RFC6189: if already enrolled (having a matching PBX secret)
1076         // ask for reconfirmation.
1077         if (!peerIsEnrolled) {
1078             callback->zrtpAskEnrollment(EnrollmentRequest);
1079         }
1080         else {
1081             callback->zrtpAskEnrollment(EnrollmentReconfirm);
1082         }
1083     }
1084 #endif
1085     return &zrtpConfirm2;
1086 }
1087 
1088 /*
1089  * At this point we are Initiator.
1090  */
prepareConfirm2MultiStream(ZrtpPacketConfirm * confirm1,uint32_t * errMsg)1091 ZrtpPacketConfirm* ZRtp::prepareConfirm2MultiStream(ZrtpPacketConfirm* confirm1, uint32_t* errMsg) {
1092 
1093     // check Confirm1 packet using the keys
1094     // prepare Confirm2 packet
1095     // don't update SAS, RS
1096     sendInfo(Info, InfoInitConf1Received);
1097 
1098     if (!confirm1->isLengthOk()) {
1099         *errMsg = CriticalSWError;
1100         return NULL;
1101     }
1102     uint8_t confMac[MAX_DIGEST_LENGTH];
1103     uint32_t macLen;
1104 
1105     closeHashCtx(msgShaContext, messageHash);
1106     msgShaContext = NULL;
1107     myRole = Initiator;
1108 
1109     generateKeysMultiStream();
1110 
1111     // Use the Responder's keys here because we are Initiator here and
1112     // receive packets from Responder
1113     int32_t hmlen = (confirm1->getLength() - 9) * ZRTP_WORD_SIZE;
1114 
1115     // Use negotiated HMAC (hash)
1116     hmacFunction(hmacKeyR, hashLength, (unsigned char*)confirm1->getHashH0(), hmlen, confMac, &macLen);
1117 
1118     if (memcmp(confMac, confirm1->getHmac(), HMAC_SIZE) != 0) {
1119         *errMsg = ConfirmHMACWrong;
1120         return NULL;
1121     }
1122     // Cast away the const for the IV - the standalone AES CFB modifies IV on return
1123     cipher->getDecrypt()(zrtpKeyR, cipher->getKeylen(), (uint8_t*)confirm1->getIv(), confirm1->getHashH0(), hmlen);
1124 
1125     // Because we are initiator the protocol engine didn't receive Commit and
1126     // because we are using multi-stream mode here we also did not receive a DHPart1 and
1127     // thus could not store a responder's H2 or H1. A two step hash is required to
1128     // re-compute H1, H2.
1129     // USe implicit hash function.
1130     uint8_t tmpHash[IMPL_MAX_DIGEST_LENGTH];
1131     hashFunctionImpl(confirm1->getHashH0(), HASH_IMAGE_SIZE, tmpHash); // Compute peer's H1 in tmpHash
1132     hashFunctionImpl(tmpHash, HASH_IMAGE_SIZE, tmpHash);               // Compute peer's H2 in tmpHash
1133     memcpy(peerH2, tmpHash, HASH_IMAGE_SIZE);                          // copy and truncate to peerH2
1134 
1135     // Check HMAC of previous Hello packet stored in temporary buffer. The
1136     // HMAC key of the Hello packet is peer's H2 that was computed above.
1137     // Refer to chapter 9.1 and chapter 10.
1138     if (!checkMsgHmac(peerH2)) {
1139         sendInfo(Severe, SevereHelloHMACFailed);
1140         *errMsg = CriticalSWError;
1141         return NULL;
1142     }
1143     // Store the status of the Disclosure flag
1144     peerDisclosureFlagSeen = confirm1->isDisclosureFlag();
1145 
1146     // now generate my Confirm2 message
1147     zrtpConfirm2.setMessageType((uint8_t*)Confirm2Msg);
1148     if (configureAlgos.isDisclosureFlag()) {
1149         zrtpConfirm2.setDisclosureFlag();
1150     }
1151     zrtpConfirm2.setHashH0(H0);
1152     zrtpConfirm2.setExpTime(0xFFFFFFFF);
1153     zrtpConfirm2.setIv(randomIV);
1154 
1155     // Encrypt and HMAC with Initiator's key - we are Initiator here
1156     hmlen = (zrtpConfirm2.getLength() - 9) * ZRTP_WORD_SIZE;
1157     cipher->getEncrypt()(zrtpKeyI, cipher->getKeylen(), randomIV, zrtpConfirm2.getHashH0(), hmlen);
1158 
1159     // Use negotiated HMAC (hash)
1160     hmacFunction(hmacKeyI, hashLength, (unsigned char*)zrtpConfirm2.getHashH0(), hmlen, confMac, &macLen);
1161 
1162     zrtpConfirm2.setHmac(confMac);
1163     return &zrtpConfirm2;
1164 }
1165 
1166 /*
1167  * At this point we are Responder.
1168  */
prepareConf2Ack(ZrtpPacketConfirm * confirm2,uint32_t * errMsg)1169 ZrtpPacketConf2Ack* ZRtp::prepareConf2Ack(ZrtpPacketConfirm *confirm2, uint32_t* errMsg) {
1170 
1171     sendInfo(Info, InfoRespConf2Received);
1172 
1173     if (!confirm2->isLengthOk()) {
1174         *errMsg = CriticalSWError;
1175         return NULL;
1176     }
1177     uint8_t confMac[MAX_DIGEST_LENGTH];
1178     uint32_t macLen;
1179 
1180     // Use the Initiator's keys here because we are Responder here and
1181     // reveice packets from Initiator
1182     int16_t hmlen = (confirm2->getLength() - 9) * ZRTP_WORD_SIZE;
1183 
1184     // Use negotiated HMAC (hash)
1185     hmacFunction(hmacKeyI, hashLength,
1186                  (unsigned char*)confirm2->getHashH0(),
1187                  hmlen, confMac, &macLen);
1188 
1189     if (memcmp(confMac, confirm2->getHmac(), HMAC_SIZE) != 0) {
1190         *errMsg = ConfirmHMACWrong;
1191         return NULL;
1192     }
1193     // Cast away the const for the IV - the standalone AES CFB modifies IV on return
1194     cipher->getDecrypt()(zrtpKeyI, cipher->getKeylen(), (uint8_t*)confirm2->getIv(), confirm2->getHashH0(), hmlen);
1195 
1196     if (!multiStream) {
1197         // Check HMAC of DHPart2 packet stored in temporary buffer. The
1198         // HMAC key of the DHPart2 packet is peer's H0 that is contained in
1199         // Confirm2. Refer to chapter 9.1 and chapter 10.
1200         if (!checkMsgHmac(confirm2->getHashH0())) {
1201             sendInfo(Severe, SevereDH2HMACFailed);
1202             *errMsg = CriticalSWError;
1203             return NULL;
1204         }
1205         /*
1206          * The Confirm2 is ok, handle the Retained secret stuff and inform
1207          * GUI about state.
1208          */
1209         bool sasFlag = confirm2->isSASFlag();
1210         // Our peer did not confirm the SAS in last session, thus reset
1211         // our SAS flag too. Reset the flag also if paranoidMode is true.
1212         if (!sasFlag || paranoidMode) {
1213             zidRec->resetSasVerified();
1214         }
1215         signatureLength = confirm2->getSignatureLength();
1216         if (signSasSeen && signatureLength > 0 && confirm2->isSignatureLengthOk() ) {
1217             signatureData = confirm2->getSignatureData();
1218             callback->checkSASSignature(sasHash);
1219             // TODO: error handling if checkSASSignature returns false.
1220         }
1221         // save new RS1, this inherits the verified flag from old RS1
1222         zidRec->setNewRs1((const uint8_t*)newRs1);
1223         if (saveZidRecord)
1224             getZidCacheInstance()->saveRecord(zidRec);
1225 
1226 #ifdef ZRTP_SAS_RELAY_SUPPORT
1227         // Ask for enrollment only if enabled via configuration and the
1228         // confirm packet contains the enrollment flag. The enrolling user
1229         // agent stores the MitM key only if the user accepts the enrollment
1230         // request.
1231         if (enableMitmEnrollment && confirm2->isPBXEnrollment()) {
1232             computePBXSecret();
1233             // As clarification to RFC6189: if already enrolled (having a matching PBX secret)
1234             // ask for reconfirmation.
1235             if (!peerIsEnrolled) {
1236                 callback->zrtpAskEnrollment(EnrollmentRequest);
1237             }
1238             else {
1239                 callback->zrtpAskEnrollment(EnrollmentReconfirm);
1240             }
1241         }
1242 #endif
1243     }
1244     else {
1245         // Check HMAC of Commit packet stored in temporary buffer. The
1246         // HMAC key of the Commit packet is initiator's H1
1247         // use implicit hash function.
1248         uint8_t tmpHash[IMPL_MAX_DIGEST_LENGTH];
1249         hashFunctionImpl(confirm2->getHashH0(), HASH_IMAGE_SIZE, tmpHash); // Compute initiator's H1 in tmpHash
1250 
1251         if (!checkMsgHmac(tmpHash)) {
1252             sendInfo(Severe, SevereCommitHMACFailed);
1253             *errMsg = CriticalSWError;
1254             return NULL;
1255         }
1256     }
1257     // Store the status of the Disclosure flag
1258     peerDisclosureFlagSeen = confirm2->isDisclosureFlag();
1259 
1260     return &zrtpConf2Ack;
1261 }
1262 
prepareErrorAck(ZrtpPacketError * epkt)1263 ZrtpPacketErrorAck* ZRtp::prepareErrorAck(ZrtpPacketError* epkt) {
1264     if (epkt->getLength() < 4)
1265         sendInfo(ZrtpError, CriticalSWError * -1);
1266     else
1267         sendInfo(ZrtpError, epkt->getErrorCode() * -1);
1268     return &zrtpErrorAck;
1269 }
1270 
prepareError(uint32_t errMsg)1271 ZrtpPacketError* ZRtp::prepareError(uint32_t errMsg) {
1272     zrtpError.setErrorCode(errMsg);
1273     return &zrtpError;
1274 }
1275 
preparePingAck(ZrtpPacketPing * ppkt)1276 ZrtpPacketPingAck* ZRtp::preparePingAck(ZrtpPacketPing* ppkt) {
1277     if (ppkt->getLength() != 6)                    // A PING packet must have a length of 6 words
1278         return NULL;
1279     // Because we do not support ZRTP proxy mode use the truncated ZID.
1280     // If this code shall be used in ZRTP proxy implementation the computation
1281     // of the endpoint hash must be enhanced (see chaps 5.15ff and 5.16)
1282     zrtpPingAck.setLocalEpHash(ownZid);
1283     zrtpPingAck.setRemoteEpHash(ppkt->getEpHash());
1284     zrtpPingAck.setSSRC(peerSSRC);
1285     return &zrtpPingAck;
1286 }
1287 
prepareRelayAck(ZrtpPacketSASrelay * srly,uint32_t * errMsg)1288 ZrtpPacketRelayAck* ZRtp::prepareRelayAck(ZrtpPacketSASrelay* srly, uint32_t* errMsg) {
1289 
1290 #ifdef ZRTP_SAS_RELAY_SUPPORT
1291     // handle and render SAS relay data only if the peer announced that it is a trusted
1292     // PBX. Don't handle SAS relay in paranoidMode.
1293     if (!mitmSeen || paranoidMode)
1294         return &zrtpRelayAck;
1295 
1296     if (!srly->isLengthOk()) {
1297         *errMsg = CriticalSWError;
1298         return NULL;
1299     }
1300     uint8_t* hkey, *ekey;
1301     // If we are responder then the PBX used it's Initiator keys
1302     if (myRole == Responder) {
1303         hkey = hmacKeyI;
1304         ekey = zrtpKeyI;
1305     }
1306     else {
1307         hkey = hmacKeyR;
1308         ekey = zrtpKeyR;
1309     }
1310 
1311     uint8_t confMac[MAX_DIGEST_LENGTH];
1312     uint32_t macLen;
1313 
1314     int16_t hmlen = (srly->getLength() - 9) * ZRTP_WORD_SIZE;
1315 
1316     // Use negotiated HMAC (hash)
1317     hmacFunction(hkey, hashLength, (unsigned char*)srly->getFiller(), hmlen, confMac, &macLen);
1318 
1319     if (memcmp(confMac, srly->getHmac(), HMAC_SIZE) != 0) {
1320         *errMsg = ConfirmHMACWrong;
1321         return NULL;                // TODO - check error handling
1322     }
1323     // Cast away the const for the IV - the standalone AES CFB modifies IV on return
1324     cipher->getDecrypt()(ekey, cipher->getKeylen(), (uint8_t*)srly->getIv(), (uint8_t*)srly->getFiller(), hmlen);
1325 
1326     const uint8_t* newSasHash = srly->getTrustedSas();
1327     bool sasHashNull = true;
1328     for (int i = 0; i < HASH_IMAGE_SIZE; i++) {
1329         if (newSasHash[i] != 0) {
1330             sasHashNull = false;
1331             break;
1332         }
1333     }
1334     std::string cs(cipher->getReadable());
1335     cs.append("/").append(pubKey->getName());
1336 
1337     // Check if new SAS is null or a trusted MitM relationship doesn't exist.
1338     // If this is the case then don't render and don't show the new SAS - use
1339     // our computed SAS hash but we may use a different SAS rendering algorithm to
1340     // render the computed SAS.
1341     if (sasHashNull || !peerIsEnrolled) {
1342         cs.append("/MitM");
1343         newSasHash = sasHash;
1344     }
1345     else {
1346         cs.append("/SASviaMitM");
1347     }
1348     // If other SAS schemes required - check here and use others
1349     const uint8_t* render = srly->getSasAlgo();
1350     AlgorithmEnum* renderAlgo = &zrtpSasTypes.getByName((const char*)render);
1351     uint8_t sasBytes[4];
1352     if (renderAlgo->isValid()) {
1353         sasBytes[0] = newSasHash[0];
1354         sasBytes[1] = newSasHash[1];
1355         sasBytes[2] = newSasHash[2] & 0xf0;
1356         sasBytes[3] = 0;
1357         if (*(int32_t*)b32 == *(int32_t*)(renderAlgo->getName())) {
1358             SAS = Base32(sasBytes, 20).getEncoded();
1359         }
1360         else if (*(int32_t*)b32e == *(int32_t*)(renderAlgo->getName())) {
1361             SAS = *EmojiBase32::u32StringToUtf8(EmojiBase32(sasBytes, 20).getEncoded());
1362         }
1363         else {
1364             SAS.assign(sas256WordsEven[sasBytes[0]]).append(":").append(sas256WordsOdd[sasBytes[1]]);
1365         }
1366     }
1367     bool verify = zidRec->isSasVerified() && srly->isSASFlag();
1368     callback->srtpSecretsOn(cs, SAS, verify);
1369 
1370 #endif
1371     return &zrtpRelayAck;
1372 }
1373 
1374 // TODO Implement GoClear handling
prepareClearAck(ZrtpPacketGoClear * gpkt)1375 ZrtpPacketClearAck* ZRtp::prepareClearAck(ZrtpPacketGoClear* gpkt) {
1376     sendInfo(Warning, WarningGoClearReceived);
1377     return &zrtpClearAck;
1378 }
1379 
prepareGoClear(uint32_t errMsg)1380 ZrtpPacketGoClear* ZRtp::prepareGoClear(uint32_t errMsg) {
1381     ZrtpPacketGoClear* gclr = &zrtpGoClear;
1382     gclr->clrClearHmac();
1383     return gclr;
1384 }
1385 
1386 /*
1387  * The next functions look up and return a prefered algorithm. These
1388  * functions work as follows:
1389  * - If the Hello packet does not contain an algorithm (number of algorithms
1390 *    is zero) then return the mandatory algorithm.
1391  * - Build a list of algorithm names and ids from configuration data. If
1392  *   the configuration data does not contain a mandatory algorithm append
1393  *   the mandatory algorithm to the list and ids.
1394  * - Build a list of algorithm names from the Hello message. If
1395  *   the Hello message does not contain a mandatory algorithm append
1396  *   the mandatory algorithm to the list.
1397  * - Lookup a matching algorithm. The list built from Hello takes
1398  *   precedence in the lookup (indexed by the outermost loop).
1399  *
1400  * This guarantees that we always return a supported alogrithm respecting
1401  * the order of algorithms in the Hello message
1402  *
1403  * The mandatory algorithms are: (internal enums are our prefered algoritms)
1404  * Hash:                S256 (SHA 256)             (internal enum Sha256)
1405  * Symmetric Cipher:    AES1 (AES 128)             (internal enum Aes128)
1406  * SRTP Authentication: HS32 and HS80 (32/80 bits) (internal enum AuthLen32)
1407  * Key Agreement:       DH3k (3072 Diffie-Helman)  (internal enum Dh3072)
1408  *
1409  */
findBestHash(ZrtpPacketHello * hello)1410 AlgorithmEnum* ZRtp::findBestHash(ZrtpPacketHello *hello) {
1411 
1412     int i;
1413     int ii;
1414     int numAlgosOffered;
1415     AlgorithmEnum* algosOffered[ZrtpConfigure::maxNoOfAlgos+1];
1416 
1417     int numAlgosConf;
1418     AlgorithmEnum* algosConf[ZrtpConfigure::maxNoOfAlgos+1];
1419 
1420     // If Hello does not contain any hash names return Sha256, its mandatory
1421     int num = hello->getNumHashes();
1422     if (num == 0) {
1423         return &zrtpHashes.getByName(mandatoryHash);
1424     }
1425     // Build list of configured hash algorithm names.
1426     numAlgosConf = configureAlgos.getNumConfiguredAlgos(HashAlgorithm);
1427     for (i = 0; i < numAlgosConf; i++) {
1428         algosConf[i] = &configureAlgos.getAlgoAt(HashAlgorithm, i);
1429     }
1430 
1431     // Build list of offered known algos in Hello, append mandatory algos if necessary
1432     for (numAlgosOffered = 0, i = 0; i < num; i++) {
1433         algosOffered[numAlgosOffered] = &zrtpHashes.getByName((const char*)hello->getHashType(i));
1434         if (!algosOffered[numAlgosOffered]->isValid())
1435             continue;
1436         numAlgosOffered++;
1437     }
1438 
1439     // Lookup offered algos in configured algos.
1440     for (i = 0; i < numAlgosOffered; i++) {
1441         for (ii = 0; ii < numAlgosConf; ii++) {
1442             if (*(int32_t*)(algosOffered[i]->getName()) == *(int32_t*)(algosConf[ii]->getName())) {
1443                 return algosConf[ii];
1444             }
1445         }
1446     }
1447     return &zrtpHashes.getByName(mandatoryHash);
1448 }
1449 
1450 
findBestCipher(ZrtpPacketHello * hello,AlgorithmEnum * pk)1451 AlgorithmEnum* ZRtp::findBestCipher(ZrtpPacketHello *hello, AlgorithmEnum* pk) {
1452 
1453     int i;
1454     int ii;
1455     int numAlgosOffered;
1456     AlgorithmEnum* algosOffered[ZrtpConfigure::maxNoOfAlgos+1];
1457 
1458     int numAlgosConf;
1459     AlgorithmEnum* algosConf[ZrtpConfigure::maxNoOfAlgos+1];
1460 
1461     int num = hello->getNumCiphers();
1462     if (num == 0 || (*(int32_t*)(pk->getName()) == *(int32_t*)dh2k)) {
1463         return &zrtpSymCiphers.getByName(aes1);
1464     }
1465 
1466     // Build list of configured cipher algorithm names.
1467     numAlgosConf = configureAlgos.getNumConfiguredAlgos(CipherAlgorithm);
1468     for (i = 0; i < numAlgosConf; i++) {
1469         algosConf[i] = &configureAlgos.getAlgoAt(CipherAlgorithm, i);
1470     }
1471     // Build list of offered known algos names in Hello.
1472     for (numAlgosOffered = 0, i = 0; i < num; i++) {
1473         algosOffered[numAlgosOffered] = &zrtpSymCiphers.getByName((const char*)hello->getCipherType(i));
1474         if (!algosOffered[numAlgosOffered]->isValid())
1475             continue;
1476         numAlgosOffered++;
1477     }
1478     // Lookup offered algos in configured algos.  Prefer algorithms that appear first in Hello packet (offered).
1479     for (i = 0; i < numAlgosOffered; i++) {
1480         for (ii = 0; ii < numAlgosConf; ii++) {
1481             if (*(int32_t*)(algosOffered[i]->getName()) == *(int32_t*)(algosConf[ii]->getName())) {
1482                 return algosConf[ii];
1483             }
1484         }
1485     }
1486     // If we don't have a match - use the mandatory algorithm
1487     return &zrtpSymCiphers.getByName(mandatoryCipher);
1488 }
1489 
1490 // We can have the non-NIST in the list of orderedAlgos even if they are not available
1491 // in the code (refer to ZrtpConfigure.cpp). If they are not build in they cannot appear
1492 // in'configureAlgos' and thus not in the intersection lists. Thus a ZRTP build that
1493 // does not include the non-NIST curves also works without problems.
1494 //
findBestPubkey(ZrtpPacketHello * hello)1495 AlgorithmEnum* ZRtp::findBestPubkey(ZrtpPacketHello *hello) {
1496 
1497     AlgorithmEnum* peerIntersect[ZrtpConfigure::maxNoOfAlgos+1];
1498     AlgorithmEnum* ownIntersect[ZrtpConfigure::maxNoOfAlgos+1];
1499 
1500     // Build list of own pubkey algorithm names, must follow the order
1501     // defined in RFC 6189, chapter 4.1.2.
1502     const char *orderedAlgos[] = {dh2k, e255, ec25, dh3k, e414, ec38};
1503     int numOrderedAlgos = sizeof(orderedAlgos) / sizeof(const char*);
1504 
1505     int numAlgosPeer = hello->getNumPubKeys();
1506     if (numAlgosPeer == 0) {
1507         hash = findBestHash(hello);                    // find a hash algorithm
1508         return &zrtpPubKeys.getByName(mandatoryPubKey);
1509     }
1510     // Build own list of intersecting algos, keep own order or algorithms
1511     // The list must include real public key algorithms only, so skip mult-stream mode,
1512     // preshared and alike.
1513     int numAlgosOwn = configureAlgos.getNumConfiguredAlgos(PubKeyAlgorithm);
1514     int numOwnIntersect = 0;
1515     for (int i = 0; i < numAlgosOwn; i++) {
1516         ownIntersect[numOwnIntersect] = &configureAlgos.getAlgoAt(PubKeyAlgorithm, i);
1517         if (*(int32_t*)(ownIntersect[numOwnIntersect]->getName()) == *(int32_t*)mult) {
1518             continue;                               // skip multi-stream mode
1519         }
1520         for (int ii = 0; ii < numAlgosPeer; ii++) {
1521             if (*(int32_t*)(ownIntersect[numOwnIntersect]->getName()) == *(int32_t*)(zrtpPubKeys.getByName((const char*)hello->getPubKeyType(ii)).getName())) {
1522                 numOwnIntersect++;
1523                 break;
1524             }
1525         }
1526     }
1527     // Build list of peer's intersecting algos: take own list as input and build a
1528     // list of algorithms that we have in common. The order of the list is according
1529     // to peer's Hello packet (peer's preferences).
1530     int numPeerIntersect = 0;
1531     for (int i = 0; i < numAlgosPeer; i++) {
1532         peerIntersect[numPeerIntersect] = &zrtpPubKeys.getByName((const char*)hello->getPubKeyType(i));
1533         for (int ii = 0; ii < numOwnIntersect; ii++) {
1534             if (*(int32_t*)(ownIntersect[ii]->getName()) == *(int32_t*)(peerIntersect[numPeerIntersect]->getName())) {
1535                 numPeerIntersect++;
1536                 break;
1537             }
1538         }
1539     }
1540     if (numPeerIntersect == 0) {       // If we don't have a common algorithm - use mandatory algorithms
1541         hash = findBestHash(hello);
1542         return &zrtpPubKeys.getByName(mandatoryPubKey);
1543     }
1544 
1545     // If we have only one algorithm in common or if the first entry matches - take it.
1546     // Otherwise determine which algorithm from the intersection lists is first in the
1547     // list of ordered algorithms and select it (RFC6189, section 4.1.2).
1548     AlgorithmEnum* useAlgo;
1549     if (numPeerIntersect > 1 && *(int32_t*)(ownIntersect[0]->getName()) != *(int32_t*)(peerIntersect[0]->getName())) {
1550         int own, peer;
1551 
1552         const int32_t *name = (int32_t*)ownIntersect[0]->getName();
1553         for (own = 0; own < numOrderedAlgos; own++) {
1554             if (*name == *(int32_t*)orderedAlgos[own])
1555                 break;
1556         }
1557         name = (int32_t*)peerIntersect[0]->getName();
1558         for (peer = 0; peer < numOrderedAlgos; peer++) {
1559             if (*name == *(int32_t*)orderedAlgos[peer])
1560                 break;
1561         }
1562         if (own < peer) {
1563             useAlgo = ownIntersect[0];
1564         }
1565         else {
1566             useAlgo = peerIntersect[0];
1567         }
1568         // find fastest of conf vs intersecting
1569     }
1570     else {
1571         useAlgo = peerIntersect[0];
1572     }
1573     int32_t algoName = *(int32_t*)(useAlgo->getName());
1574 
1575     // select a corresponding strong hash if necessary.
1576     if (algoName == *(int32_t*)ec38 || algoName == *(int32_t*)e414) {
1577         hash = getStrongHashOffered(hello, algoName);
1578         cipher = getStrongCipherOffered(hello, algoName);
1579     }
1580     else {
1581         hash = getHashOffered(hello, algoName);;
1582         cipher = getCipherOffered(hello, algoName);
1583     }
1584     authLength = getAuthLenOffered(hello, algoName);
1585     return useAlgo;
1586 }
1587 
findBestSASType(ZrtpPacketHello * hello)1588 AlgorithmEnum* ZRtp::findBestSASType(ZrtpPacketHello *hello) {
1589 
1590     int  i;
1591     int ii;
1592     int numAlgosOffered;
1593     AlgorithmEnum* algosOffered[ZrtpConfigure::maxNoOfAlgos+1];
1594 
1595     int numAlgosConf;
1596     AlgorithmEnum* algosConf[ZrtpConfigure::maxNoOfAlgos+1];
1597 
1598     int num = hello->getNumSas();
1599     if (num == 0) {
1600         return &zrtpSasTypes.getByName(mandatorySasType);
1601     }
1602     // Build list of configured SAS algorithm names
1603     numAlgosConf = configureAlgos.getNumConfiguredAlgos(SasType);
1604     for (i = 0; i < numAlgosConf; i++) {
1605         algosConf[i] = &configureAlgos.getAlgoAt(SasType, i);
1606     }
1607     // Build list of offered known algos in Hello,
1608     for (numAlgosOffered = 0, i = 0; i < num; i++) {
1609         algosOffered[numAlgosOffered] = &zrtpSasTypes.getByName((const char*)hello->getSasType(i));
1610         if (!algosOffered[numAlgosOffered]->isValid())
1611             continue;
1612         numAlgosOffered++;
1613     }
1614     // Lookup offered algos in configured algos. Prefer algorithms that appear first in Hello packet (offered).
1615     for (i = 0; i < numAlgosOffered; i++) {
1616         for (ii = 0; ii < numAlgosConf; ii++) {
1617             if (*(int32_t*)(algosOffered[i]->getName()) == *(int32_t*)(algosConf[ii]->getName())) {
1618                 return algosConf[ii];
1619             }
1620         }
1621     }
1622     // If we don't have a match - use the mandatory algorithm
1623     return &zrtpSasTypes.getByName(mandatorySasType);
1624 }
1625 
findBestAuthLen(ZrtpPacketHello * hello)1626 AlgorithmEnum* ZRtp::findBestAuthLen(ZrtpPacketHello *hello) {
1627 
1628     int  i;
1629     int ii;
1630     int numAlgosOffered;
1631     AlgorithmEnum* algosOffered[ZrtpConfigure::maxNoOfAlgos+2];
1632 
1633     int numAlgosConf;
1634     AlgorithmEnum* algosConf[ZrtpConfigure::maxNoOfAlgos+2];
1635 
1636     int num = hello->getNumAuth();
1637     if (num == 0) {
1638         return &zrtpAuthLengths.getByName(mandatoryAuthLen_1);
1639     }
1640 
1641     // Build list of configured Authentication tag length algorithm names.
1642     numAlgosConf = configureAlgos.getNumConfiguredAlgos(AuthLength);
1643     for (i = 0; i < numAlgosConf; i++) {
1644         algosConf[i] = &configureAlgos.getAlgoAt(AuthLength, i);
1645     }
1646 
1647     // Build list of offered known algos in Hello.
1648     for (numAlgosOffered = 0, i = 0; i < num; i++) {
1649         algosOffered[numAlgosOffered] = &zrtpAuthLengths.getByName((const char*)hello->getAuthLen(i));
1650         if (!algosOffered[numAlgosOffered]->isValid())
1651             continue;
1652         numAlgosOffered++;
1653     }
1654 
1655     // Lookup offered algos in configured algos. Prefer algorithms that appear first in Hello packet (offered).
1656     for (i = 0; i < numAlgosOffered; i++) {
1657         for (ii = 0; ii < numAlgosConf; ii++) {
1658             if (*(int32_t*)(algosOffered[i]->getName()) == *(int32_t*)(algosConf[ii]->getName())) {
1659                 return algosConf[ii];
1660             }
1661         }
1662     }
1663     // If we don't have a match - use the mandatory algorithm
1664     return &zrtpAuthLengths.getByName(mandatoryAuthLen_1);
1665 }
1666 
1667 // The following set of functions implement a 'non-NIST first policy' if nonNist computes
1668 // to true. They prefer nonNist algorithms if these are available. Otherwise they use the NIST
1669 // counterpart or simply call the according findBest*(...) function.
1670 //
1671 // Only the findBestPubkey(...) function calls them after it selected the public key algorithm.
1672 // If the public key algorithm is non-NIST and if the policy is set to PreferNonNist then
1673 // nonNist becomes true.
1674 //
1675 // The functions work according to the RFC6189 spec: the initiator can select every algorithm
1676 // that both parties support. Thus the Initiator can even select an algorithm the wasn't offered
1677 // in its own Hello packet but that the Initiator found in the peer's Hello and that is available
1678 // for it.
1679 //
getStrongHashOffered(ZrtpPacketHello * hello,int32_t algoName)1680 AlgorithmEnum* ZRtp::getStrongHashOffered(ZrtpPacketHello *hello, int32_t algoName) {
1681 
1682     int numHash = hello->getNumHashes();
1683     bool nonNist = (algoName == *(int32_t*)e414 || algoName == *(int32_t*)e255) && configureAlgos.getSelectionPolicy() == ZrtpConfigure::PreferNonNist;
1684 
1685     if (nonNist) {
1686         for (int i = 0; i < numHash; i++) {
1687             int32_t nm = *(int32_t*)(hello->getHashType(i));
1688             if (nm == *(int32_t*)skn3) {
1689                 return &zrtpHashes.getByName((const char*)hello->getHashType(i));
1690             }
1691         }
1692     }
1693     for (int i = 0; i < numHash; i++) {
1694         int32_t nm = *(int32_t*)(hello->getHashType(i));
1695         if (nm == *(int32_t*)s384 || nm == *(int32_t*)skn3) {
1696             return &zrtpHashes.getByName((const char*)hello->getHashType(i));
1697         }
1698     }
1699     return NULL;         // returning NULL -> prepareCommit(...) terminates ZRTP, missing strong hash is an error
1700 }
1701 
getStrongCipherOffered(ZrtpPacketHello * hello,int32_t algoName)1702 AlgorithmEnum* ZRtp::getStrongCipherOffered(ZrtpPacketHello *hello, int32_t algoName) {
1703 
1704     int num = hello->getNumCiphers();
1705     bool nonNist = (algoName == *(int32_t*)e414 || algoName == *(int32_t*)e255) && configureAlgos.getSelectionPolicy() == ZrtpConfigure::PreferNonNist;
1706 
1707     if (nonNist) {
1708         for (int i = 0; i < num; i++) {
1709             int32_t nm = *(int32_t*)(hello->getCipherType(i));
1710             if (nm == *(int32_t*)two3) {
1711                 return &zrtpSymCiphers.getByName((const char*)hello->getCipherType(i));
1712             }
1713         }
1714     }
1715     for (int i = 0; i < num; i++) {
1716         int32_t nm = *(int32_t*)(hello->getCipherType(i));
1717         if (nm == *(int32_t*)aes3 || nm == *(int32_t*)two3) {
1718             return &zrtpSymCiphers.getByName((const char*)hello->getCipherType(i));
1719         }
1720     }
1721     return NULL;       // returning NULL -> prepareCommit(...) finds the best cipher
1722 }
1723 
getHashOffered(ZrtpPacketHello * hello,int32_t algoName)1724 AlgorithmEnum* ZRtp::getHashOffered(ZrtpPacketHello *hello, int32_t algoName) {
1725 
1726     int num = hello->getNumHashes();
1727     bool nonNist = (algoName == *(int32_t*)e414 || algoName == *(int32_t*)e255) && configureAlgos.getSelectionPolicy() == ZrtpConfigure::PreferNonNist;
1728 
1729     if (nonNist) {
1730         for (int i = 0; i < num; i++) {
1731             int32_t nm = *(int32_t*)(hello->getHashType(i));
1732             if (nm == *(int32_t*)skn2 || nm == *(int32_t*)skn3) {
1733                 return &zrtpHashes.getByName((const char*)hello->getHashType(i));
1734             }
1735         }
1736     }
1737     return findBestHash(hello);
1738 }
1739 
getCipherOffered(ZrtpPacketHello * hello,int32_t algoName)1740 AlgorithmEnum* ZRtp::getCipherOffered(ZrtpPacketHello *hello, int32_t algoName) {
1741 
1742     int num = hello->getNumCiphers();
1743     bool nonNist = (algoName == *(int32_t*)e414 || algoName == *(int32_t*)e255) && configureAlgos.getSelectionPolicy() == ZrtpConfigure::PreferNonNist;
1744 
1745     if (nonNist) {
1746         for (int i = 0; i < num; i++) {
1747             int32_t nm = *(int32_t*)(hello->getCipherType(i));
1748             if (nm == *(int32_t*)two2 || nm == *(int32_t*)two3) {
1749                 return &zrtpSymCiphers.getByName((const char*)hello->getCipherType(i));
1750             }
1751         }
1752     }
1753     return NULL;       // returning NULL -> prepareCommit(...) finds the best cipher
1754 }
1755 
getAuthLenOffered(ZrtpPacketHello * hello,int32_t algoName)1756 AlgorithmEnum* ZRtp::getAuthLenOffered(ZrtpPacketHello *hello, int32_t algoName) {
1757 
1758     int num = hello->getNumAuth();
1759     bool nonNist = (algoName == *(int32_t*)e414 || algoName == *(int32_t*)e255) && configureAlgos.getSelectionPolicy() == ZrtpConfigure::PreferNonNist;
1760 
1761     if (nonNist) {
1762         for (int i = 0; i < num; i++) {
1763             int32_t nm = *(int32_t*)(hello->getAuthLen(i));
1764             if (nm == *(int32_t*)sk32 || nm == *(int32_t*)sk64) {
1765                 return &zrtpAuthLengths.getByName((const char*)hello->getAuthLen(i));
1766             }
1767         }
1768     }
1769     return findBestAuthLen(hello);
1770 }
1771 
checkMultiStream(ZrtpPacketHello * hello)1772 bool ZRtp::checkMultiStream(ZrtpPacketHello *hello) {
1773 
1774     int  i;
1775     int num = hello->getNumPubKeys();
1776 
1777     // Multi Stream mode is mandatory, thus if nothing is offered then it is supported :-)
1778     if (num == 0) {
1779         return true;
1780     }
1781     for (i = 0; i < num; i++) {
1782         if (*(int32_t*)(hello->getPubKeyType(i)) == *(int32_t*)mult) {
1783             return true;
1784         }
1785     }
1786     return false;
1787 }
1788 
verifyH2(ZrtpPacketCommit * commit)1789 bool ZRtp::verifyH2(ZrtpPacketCommit *commit) {
1790     uint8_t tmpH3[IMPL_MAX_DIGEST_LENGTH];
1791 
1792     // packet does not have the correct size, treat H2 verfication as failed.
1793     if (!commit->isLengthOk(multiStream ? ZrtpPacketCommit::MultiStream : ZrtpPacketCommit::DhExchange))
1794         return false;
1795 
1796     sha256(commit->getH2(), HASH_IMAGE_SIZE, tmpH3);
1797     if (memcmp(tmpH3, peerH3, HASH_IMAGE_SIZE) != 0) {
1798         return false;
1799     }
1800     return true;
1801 }
1802 
computeHvi(ZrtpPacketDHPart * dh,ZrtpPacketHello * hello)1803 void ZRtp::computeHvi(ZrtpPacketDHPart* dh, ZrtpPacketHello *hello) {
1804 
1805     unsigned char* data[3];
1806     unsigned int length[3];
1807     /*
1808      * populate the vector to compute the HVI hash according to the
1809      * ZRTP specification.
1810      */
1811     data[0] = (uint8_t*)dh->getHeaderBase();
1812     length[0] = dh->getLength() * ZRTP_WORD_SIZE;
1813 
1814     data[1] = (uint8_t*)hello->getHeaderBase();
1815     length[1] = hello->getLength() * ZRTP_WORD_SIZE;
1816 
1817     data[2] = NULL;            // terminate data chunks
1818     hashListFunction(data, length, hvi);
1819     return;
1820 }
1821 
computeSharedSecretSet(ZIDRecord * zidRec)1822 void ZRtp:: computeSharedSecretSet(ZIDRecord *zidRec) {
1823 
1824     /*
1825      * Compute the Initiator's and Reponder's retained shared secret Ids.
1826      * Use negotiated HMAC.
1827      */
1828     uint8_t randBuf[RS_LENGTH];
1829     uint32_t macLen;
1830 
1831     detailInfo.secretsCached = 0;
1832     if (!zidRec->isRs1Valid()) {
1833         randomZRTP(randBuf, RS_LENGTH);
1834         hmacFunction(randBuf, RS_LENGTH, (unsigned char*)initiator, strlen(initiator), rs1IDi, &macLen);
1835         hmacFunction(randBuf, RS_LENGTH, (unsigned char*)responder, strlen(responder), rs1IDr, &macLen);
1836     }
1837     else {
1838         rs1Valid = true;
1839         hmacFunction((unsigned char*)zidRec->getRs1(), RS_LENGTH, (unsigned char*)initiator, strlen(initiator), rs1IDi, &macLen);
1840         hmacFunction((unsigned char*)zidRec->getRs1(), RS_LENGTH, (unsigned char*)responder, strlen(responder), rs1IDr, &macLen);
1841         detailInfo.secretsCached = Rs1;
1842     }
1843 
1844     if (!zidRec->isRs2Valid()) {
1845         randomZRTP(randBuf, RS_LENGTH);
1846         hmacFunction(randBuf, RS_LENGTH, (unsigned char*)initiator, strlen(initiator), rs2IDi, &macLen);
1847         hmacFunction(randBuf, RS_LENGTH, (unsigned char*)responder, strlen(responder), rs2IDr, &macLen);
1848     }
1849     else {
1850         rs2Valid = true;
1851         hmacFunction((unsigned char*)zidRec->getRs2(), RS_LENGTH, (unsigned char*)initiator, strlen(initiator), rs2IDi, &macLen);
1852         hmacFunction((unsigned char*)zidRec->getRs2(), RS_LENGTH, (unsigned char*)responder, strlen(responder), rs2IDr, &macLen);
1853         detailInfo.secretsCached |= Rs2;
1854     }
1855 
1856     if (!zidRec->isMITMKeyAvailable()) {
1857         randomZRTP(randBuf, RS_LENGTH);
1858         hmacFunction(randBuf, RS_LENGTH, (unsigned char*)initiator, strlen(initiator), pbxSecretIDi, &macLen);
1859         hmacFunction(randBuf, RS_LENGTH, (unsigned char*)responder, strlen(responder), pbxSecretIDr, &macLen);
1860 
1861     }
1862     else {
1863         hmacFunction((unsigned char*)zidRec->getMiTMData(), RS_LENGTH, (unsigned char*)initiator, strlen(initiator), pbxSecretIDi, &macLen);
1864         hmacFunction((unsigned char*)zidRec->getMiTMData(), RS_LENGTH, (unsigned char*)responder, strlen(responder), pbxSecretIDr, &macLen);
1865         detailInfo.secretsCached |= Pbx;
1866     }
1867     computeAuxSecretIds();
1868 }
1869 
computeAuxSecretIds()1870 void ZRtp::computeAuxSecretIds() {
1871     uint8_t randBuf[RS_LENGTH];
1872     uint32_t macLen;
1873 
1874     if (auxSecret == NULL) {
1875         randomZRTP(randBuf, RS_LENGTH);
1876         hmacFunction(randBuf, RS_LENGTH, H3, HASH_IMAGE_SIZE, auxSecretIDi, &macLen);
1877         hmacFunction(randBuf, RS_LENGTH, H3, HASH_IMAGE_SIZE, auxSecretIDr, &macLen);
1878     }
1879     else {
1880         if (myRole == Initiator) {  // I'm initiator thus use my H3 for initiator's IDi, peerH3 for respnder's IDr
1881             hmacFunction(auxSecret, auxSecretLength, H3, HASH_IMAGE_SIZE, auxSecretIDi, &macLen);
1882             hmacFunction(auxSecret, auxSecretLength, peerH3, HASH_IMAGE_SIZE, auxSecretIDr, &macLen);
1883         }
1884         else {
1885             hmacFunction(auxSecret, auxSecretLength, peerH3, HASH_IMAGE_SIZE, auxSecretIDi, &macLen);
1886             hmacFunction(auxSecret, auxSecretLength, H3, HASH_IMAGE_SIZE, auxSecretIDr, &macLen);
1887         }
1888     }
1889 }
1890 
1891 /*
1892  * memset_volatile is a volatile pointer to the memset function.
1893  * You can call (*memset_volatile)(buf, val, len) or even
1894  * memset_volatile(buf, val, len) just as you would call
1895  * memset(buf, val, len), but the use of a volatile pointer
1896  * guarantees that the compiler will not optimise the call away.
1897  */
1898 static void * (*volatile memset_volatile)(void *, int, size_t) = memset;
1899 
1900 /*
1901  * The DH packet for this function is DHPart1 and contains the Responder's
1902  * retained secret ids. Compare them with the expected secret ids (refer
1903  * to chapter 5.3 in the specification).
1904  * When using this method then we are in Initiator role.
1905  */
generateKeysInitiator(ZrtpPacketDHPart * dhPart,ZIDRecord * zidRec)1906 void ZRtp::generateKeysInitiator(ZrtpPacketDHPart *dhPart, ZIDRecord *zidRec) {
1907     const uint8_t* setD[3];
1908     int32_t rsFound = 0;
1909 
1910     setD[0] = setD[1] = setD[2] = NULL;
1911 
1912     detailInfo.secretsMatchedDH = 0;
1913     if (memcmp(rs1IDr, dhPart->getRs1Id(), HMAC_SIZE) == 0 || memcmp(rs1IDr, dhPart->getRs2Id(), HMAC_SIZE) == 0)
1914         detailInfo.secretsMatchedDH |= Rs1;
1915     if (memcmp(rs2IDr, dhPart->getRs1Id(), HMAC_SIZE) == 0 || memcmp(rs2IDr, dhPart->getRs2Id(), HMAC_SIZE) == 0)
1916         detailInfo.secretsMatchedDH |= Rs2;
1917     /*
1918      * Select the real secrets into setD. The dhPart is DHpart1 message
1919      * received from responder. rs1IDr and rs2IDr are the expected ids using
1920      * the initator's cached retained secrets.
1921      */
1922     // Check which RS we shall use for first place (s1)
1923     detailInfo.secretsMatched = 0;
1924     if (memcmp(rs1IDr, dhPart->getRs1Id(), HMAC_SIZE) == 0) {
1925         setD[0] = zidRec->getRs1();
1926         rsFound = 0x1;
1927         detailInfo.secretsMatched = Rs1;
1928     }
1929     else if (memcmp(rs1IDr, dhPart->getRs2Id(), HMAC_SIZE) == 0) {
1930         setD[0] = zidRec->getRs1();
1931         rsFound = 0x2;
1932         detailInfo.secretsMatched = Rs1;
1933     }
1934     else if (memcmp(rs2IDr, dhPart->getRs1Id(), HMAC_SIZE) == 0) {
1935         setD[0] = zidRec->getRs2();
1936         rsFound = 0x4;
1937         detailInfo.secretsMatched = Rs2;
1938     }
1939     else if (memcmp(rs2IDr, dhPart->getRs2Id(), HMAC_SIZE) == 0) {
1940         setD[0] = zidRec->getRs2();
1941         rsFound = 0x8;
1942         detailInfo.secretsMatched = Rs2;
1943     }
1944 
1945     if (memcmp(auxSecretIDr, dhPart->getAuxSecretId(), 8) == 0) {
1946         DEBUGOUT((fprintf(stdout, "Initiator: Match for aux secret found\n")));
1947         setD[1] = auxSecret;
1948         detailInfo.secretsMatched |= Aux;
1949         detailInfo.secretsMatchedDH |= Aux;
1950     }
1951     if (auxSecret != NULL && (detailInfo.secretsMatched & Aux) == 0) {
1952         sendInfo(Warning, WarningNoExpectedAuxMatch);
1953     }
1954 
1955 #ifdef ZRTP_SAS_RELAY_SUPPORT
1956     // check if we have a matching PBX secret and place it third (s3)
1957     if (memcmp(pbxSecretIDr, dhPart->getPbxSecretId(), HMAC_SIZE) == 0) {
1958         DEBUGOUT((fprintf(stdout, "%c: Match for Other_secret found\n", zid[0])));
1959         setD[2] = zidRec->getMiTMData();
1960         detailInfo.secretsMatched |= Pbx;
1961         detailInfo.secretsMatchedDH |= Pbx;
1962         // Flag to record that fact that we have a MitM key of the other peer.
1963         peerIsEnrolled = true;
1964     }
1965 #endif
1966     // Check if some retained secrets found
1967     if (rsFound == 0) {                        // no RS matches found
1968         if (rs1Valid || rs2Valid) {            // but valid RS records in cache
1969             sendInfo(Warning, WarningNoExpectedRSMatch);
1970             zidRec->resetSasVerified();
1971             saveZidRecord = false;             // Don't save RS until user verfied/confirmed SAS
1972         }
1973         else {                                 // No valid RS record in cache
1974             sendInfo(Warning, WarningNoRSMatch);
1975         }
1976     }
1977     else {                                     // at least one RS matches
1978         sendInfo(Info, InfoRSMatchFound);
1979     }
1980     /*
1981      * Ready to generate s0 here.
1982      * The formular to compute S0 (Refer to ZRTP specification 5.4.4):
1983      *
1984       s0 = hash( counter | DHResult | "ZRTP-HMAC-KDF" | ZIDi | ZIDr | \
1985       total_hash | len(s1) | s1 | len(s2) | s2 | len(s3) | s3)
1986      *
1987      * Note: in this function we are Initiator, thus ZIDi is our zid
1988      * (zid), ZIDr is the peer's zid (peerZid).
1989      */
1990 
1991     /*
1992      * These arrays hold the pointers and lengths of the data that must be
1993      * hashed to create S0.  According to the formula the max number of
1994      * elements to hash is 12, add one for the terminating "NULL"
1995      */
1996     unsigned char* data[13];
1997     unsigned int   length[13];
1998     uint32_t pos = 0;                  // index into the array
1999 
2000     // we need a number of length data items, so define them here
2001     uint32_t counter, sLen[3];
2002 
2003     //Very first element is a fixed counter, big endian
2004     counter = 1;
2005     counter = zrtpHtonl(counter);
2006     data[pos] = (unsigned char*)&counter;
2007     length[pos++] = sizeof(uint32_t);
2008 
2009     // Next is the DH result itself
2010     data[pos] = DHss;
2011     length[pos++] = dhContext->getDhSize();
2012 
2013     // Next the fixed string "ZRTP-HMAC-KDF"
2014     data[pos] = (unsigned char*)KDFString;
2015     length[pos++] = strlen(KDFString);
2016 
2017     // Next is Initiator's id (ZIDi), in this case as Initiator
2018     // it is zid
2019     data[pos] = ownZid;
2020     length[pos++] = ZID_SIZE;
2021 
2022     // Next is Responder's id (ZIDr), in this case our peer's id
2023     data[pos] = peerZid;
2024     length[pos++] = ZID_SIZE;
2025 
2026     // Next ist total hash (messageHash) itself
2027     data[pos] = messageHash;
2028     length[pos++] = hashLength;
2029 
2030     /*
2031      * For each matching shared secret hash the length of
2032      * the shared secret as 32 bit big-endian number followd by the
2033      * shared secret itself. The length of a shared seceret is
2034      * currently fixed to RS_LENGTH. If a shared
2035      * secret is not used _only_ its length is hased as zero
2036      * length. NOTE: if implementing auxSecret and/or pbxSecret -> check
2037      * this length stuff again.
2038      */
2039     int secretHashLen = RS_LENGTH;
2040     secretHashLen = zrtpHtonl(secretHashLen);        // prepare 32 bit big-endian number
2041 
2042     for (int32_t i = 0; i < 3; i++) {
2043         if (setD[i] != NULL) {           // a matching secret, set length, then secret
2044             sLen[i] = secretHashLen;
2045             data[pos] = (unsigned char*)&sLen[i];
2046             length[pos++] = sizeof(uint32_t);
2047             data[pos] = (unsigned char*)setD[i];
2048             length[pos++] = (i != 1) ? RS_LENGTH : auxSecretLength;
2049         }
2050         else {                           // no machting secret, set length 0, skip secret
2051             sLen[i] = 0;
2052             data[pos] = (unsigned char*)&sLen[i];
2053             length[pos++] = sizeof(uint32_t);
2054         }
2055     }
2056 
2057     data[pos] = NULL;
2058     hashListFunction(data, length, s0);
2059 //  hexdump("S0 I", s0, hashLength);
2060 
2061     memset_volatile(DHss, 0, dhContext->getDhSize());
2062     delete[] DHss;
2063     DHss = NULL;
2064 
2065     computeSRTPKeys();
2066     memset(s0, 0, MAX_DIGEST_LENGTH);
2067 }
2068 /*
2069  * The DH packet for this function is DHPart2 and contains the Initiator's
2070  * retained secret ids. Compare them with the expected secret ids (refer
2071  * to chapter 5.3.1 in the specification).
2072  */
generateKeysResponder(ZrtpPacketDHPart * dhPart,ZIDRecord * zidRec)2073 void ZRtp::generateKeysResponder(ZrtpPacketDHPart *dhPart, ZIDRecord *zidRec) {
2074     const uint8_t* setD[3];
2075     int32_t rsFound = 0;
2076 
2077     setD[0] = setD[1] = setD[2] = NULL;
2078 
2079     detailInfo.secretsMatchedDH = 0;
2080     if (memcmp(rs1IDi, dhPart->getRs1Id(), HMAC_SIZE) == 0 || memcmp(rs1IDi, dhPart->getRs2Id(), HMAC_SIZE) == 0)
2081         detailInfo.secretsMatchedDH |= Rs1;
2082     if (memcmp(rs2IDi, dhPart->getRs1Id(), HMAC_SIZE) == 0 || memcmp(rs2IDi, dhPart->getRs2Id(), HMAC_SIZE) == 0)
2083         detailInfo.secretsMatchedDH |= Rs2;
2084 
2085     /*
2086      * Select the real secrets into setD
2087      */
2088     // Check which RS we shall use for first place (s1)
2089     detailInfo.secretsMatched = 0;
2090     if (memcmp(rs1IDi, dhPart->getRs1Id(), HMAC_SIZE) == 0) {
2091         setD[0] = zidRec->getRs1();
2092         rsFound = 0x1;
2093         detailInfo.secretsMatched = Rs1;
2094     }
2095     else if (memcmp(rs1IDi, dhPart->getRs2Id(), HMAC_SIZE) == 0) {
2096         setD[0] = zidRec->getRs1();
2097         rsFound = 0x2;
2098         detailInfo.secretsMatched = Rs1;
2099     }
2100     else if (memcmp(rs2IDi, dhPart->getRs1Id(), HMAC_SIZE) == 0) {
2101         setD[0] = zidRec->getRs2();
2102         rsFound |= 0x4;
2103         detailInfo.secretsMatched = Rs2;
2104     }
2105     else if (memcmp(rs2IDi, dhPart->getRs2Id(), HMAC_SIZE) == 0) {
2106         setD[0] = zidRec->getRs2();
2107         rsFound |= 0x8;
2108         detailInfo.secretsMatched = Rs2;
2109     }
2110 
2111     if (memcmp(auxSecretIDi, dhPart->getAuxSecretId(), 8) == 0) {
2112         DEBUGOUT((fprintf(stdout, "Responder: Match for aux secret found\n")));
2113         setD[1] = auxSecret;
2114         detailInfo.secretsMatched |= Aux;
2115         detailInfo.secretsMatchedDH |= Aux;
2116     }
2117     // If we have an auxSecret but no match from peer - report this.
2118     if (auxSecret != NULL && (detailInfo.secretsMatched & Aux) == 0) {
2119         sendInfo(Warning, WarningNoExpectedAuxMatch);
2120     }
2121 
2122 #ifdef ZRTP_SAS_RELAY_SUPPORT
2123     if (memcmp(pbxSecretIDi, dhPart->getPbxSecretId(), 8) == 0) {
2124         DEBUGOUT((fprintf(stdout, "%c: Match for PBX secret found\n", ownZid[0])));
2125         setD[2] = zidRec->getMiTMData();
2126         detailInfo.secretsMatched |= Pbx;
2127         detailInfo.secretsMatchedDH |= Pbx;
2128         peerIsEnrolled = true;
2129     }
2130 #endif
2131     // Check if some retained secrets found
2132     if (rsFound == 0) {                        // no RS matches found
2133         if (rs1Valid || rs2Valid) {            // but valid RS records in cache
2134             sendInfo(Warning, WarningNoExpectedRSMatch);
2135             zidRec->resetSasVerified();
2136             saveZidRecord = false;             // Don't save RS until user verfied/confirmed SAS
2137         }
2138         else {                                 // No valid RS record in cache
2139             sendInfo(Warning, WarningNoRSMatch);
2140         }
2141     }
2142     else {                                     // at least one RS matches
2143         sendInfo(Info, InfoRSMatchFound);
2144     }
2145 
2146     /*
2147      * ready to generate s0 here.
2148      * The formular to compute S0 (Refer to ZRTP specification 5.4.4):
2149      *
2150       s0 = hash( counter | DHResult | "ZRTP-HMAC-KDF" | ZIDi | ZIDr | \
2151       total_hash | len(s1) | s1 | len(s2) | s2 | len(s3) | s3)
2152      *
2153      * Note: in this function we are Responder, thus ZIDi is the peer's zid
2154      * (peerZid), ZIDr is our zid.
2155      */
2156 
2157     /*
2158      * These arrays hold the pointers and lengths of the data that must be
2159      * hashed to create S0.  According to the formula the max number of
2160      * elements to hash is 12, add one for the terminating "NULL"
2161      */
2162     unsigned char* data[13];
2163     unsigned int   length[13];
2164     uint32_t pos = 0;                  // index into the array
2165 
2166 
2167     // we need a number of length data items, so define them here
2168     uint32_t counter, sLen[3];
2169 
2170     //Very first element is a fixed counter, big endian
2171     counter = 1;
2172     counter = zrtpHtonl(counter);
2173     data[pos] = (unsigned char*)&counter;
2174     length[pos++] = sizeof(uint32_t);
2175 
2176     // Next is the DH result itself
2177     data[pos] = DHss;
2178     length[pos++] = dhContext->getDhSize();
2179 
2180     // Next the fixed string "ZRTP-HMAC-KDF"
2181     data[pos] = (unsigned char*)KDFString;
2182     length[pos++] = strlen(KDFString);
2183 
2184     // Next is Initiator's id (ZIDi), in this case as Responder
2185     // it is peerZid
2186     data[pos] = peerZid;
2187     length[pos++] = ZID_SIZE;
2188 
2189     // Next is Responder's id (ZIDr), in this case our own zid
2190     data[pos] = ownZid;
2191     length[pos++] = ZID_SIZE;
2192 
2193     // Next ist total hash (messageHash) itself
2194     data[pos] = messageHash;
2195     length[pos++] = hashLength;
2196 
2197     /*
2198      * For each matching shared secret hash the length of
2199      * the shared secret as 32 bit big-endian number followd by the
2200      * shared secret itself. The length of a shared seceret is
2201      * currently fixed to SHA256_DIGEST_LENGTH. If a shared
2202      * secret is not used _only_ its length is hased as zero
2203      * length. NOTE: if implementing auxSecret and/or pbxSecret -> check
2204      * this length stuff again.
2205      */
2206     int secretHashLen = RS_LENGTH;
2207     secretHashLen = zrtpHtonl(secretHashLen);        // prepare 32 bit big-endian number
2208 
2209     for (int32_t i = 0; i < 3; i++) {
2210         if (setD[i] != NULL) {           // a matching secret, set length, then secret
2211             sLen[i] = secretHashLen;
2212             data[pos] = (unsigned char*)&sLen[i];
2213             length[pos++] = sizeof(uint32_t);
2214             data[pos] = (unsigned char*)setD[i];
2215             length[pos++] = (i != 1) ? RS_LENGTH : auxSecretLength;
2216         }
2217         else {                           // no machting secret, set length 0, skip secret
2218             sLen[i] = 0;
2219             data[pos] = (unsigned char*)&sLen[i];
2220             length[pos++] = sizeof(uint32_t);
2221         }
2222     }
2223 
2224     data[pos] = NULL;
2225     hashListFunction(data, length, s0);
2226 //  hexdump("S0 R", s0, hashLength);
2227 
2228     memset_volatile(DHss, 0, dhContext->getDhSize());
2229     delete[] DHss;
2230     DHss = NULL;
2231 
2232     computeSRTPKeys();
2233     memset(s0, 0, MAX_DIGEST_LENGTH);
2234 }
2235 
2236 
KDF(uint8_t * key,uint32_t keyLength,uint8_t * label,int32_t labelLength,uint8_t * context,int32_t contextLength,int32_t L,uint8_t * output)2237 void ZRtp::KDF(uint8_t* key, uint32_t keyLength, uint8_t* label, int32_t labelLength,
2238                uint8_t* context, int32_t contextLength, int32_t L, uint8_t* output) {
2239 
2240     unsigned char* data[6];
2241     uint32_t length[6];
2242     uint32_t pos = 0;                  // index into the array
2243     uint32_t maclen = 0;
2244 
2245     // Very first element is a fixed counter, big endian
2246     uint32_t counter = 1;
2247     counter = zrtpHtonl(counter);
2248     data[pos] = (unsigned char*)&counter;
2249     length[pos++] = sizeof(uint32_t);
2250 
2251     // Next element is the label, null terminated, labelLength includes null byte.
2252     data[pos] = label;
2253     length[pos++] = labelLength;
2254 
2255     // Next is the KDF context
2256     data[pos] = context;
2257     length[pos++] = contextLength;
2258 
2259     // last element is HMAC length in bits, big endian
2260     uint32_t len = zrtpHtonl(L);
2261     data[pos] = (unsigned char*)&len;
2262     length[pos++] = sizeof(uint32_t);
2263 
2264     data[pos] = NULL;
2265 
2266     // Use negotiated hash.
2267     hmacListFunction(key, keyLength, data, length, output, &maclen);
2268 }
2269 
2270 // Compute the Multi Stream mode s0
generateKeysMultiStream()2271 void ZRtp::generateKeysMultiStream() {
2272 
2273     // allocate the maximum size, compute real size to use
2274     uint8_t KDFcontext[sizeof(peerZid)+sizeof(ownZid)+sizeof(messageHash)];
2275     int32_t kdfSize = sizeof(peerZid)+sizeof(ownZid)+hashLength;
2276 
2277     if (myRole == Responder) {
2278         memcpy(KDFcontext, peerZid, sizeof(peerZid));
2279         memcpy(KDFcontext+sizeof(peerZid), ownZid, sizeof(ownZid));
2280     }
2281     else {
2282         memcpy(KDFcontext, ownZid, sizeof(ownZid));
2283         memcpy(KDFcontext+sizeof(ownZid), peerZid, sizeof(peerZid));
2284     }
2285     memcpy(KDFcontext+sizeof(ownZid)+sizeof(peerZid), messageHash, hashLength);
2286 
2287     KDF(zrtpSession, hashLength, (unsigned char*)zrtpMsk, strlen(zrtpMsk)+1, KDFcontext, kdfSize, hashLength*8, s0);
2288 
2289     memset(KDFcontext, 0, sizeof(KDFcontext));
2290 
2291     computeSRTPKeys();
2292 }
2293 
computePBXSecret()2294 void ZRtp::computePBXSecret() {
2295 #ifdef ZRTP_SAS_RELAY_SUPPORT
2296     // Construct the KDF context as per ZRTP specification chap 7.3.1:
2297     // ZIDi || ZIDr
2298     uint8_t KDFcontext[sizeof(peerZid)+sizeof(ownZid)];
2299     int32_t kdfSize = sizeof(peerZid)+sizeof(ownZid);
2300 
2301     if (myRole == Responder) {
2302         memcpy(KDFcontext, peerZid, sizeof(peerZid));
2303         memcpy(KDFcontext+sizeof(peerZid), ownZid, sizeof(ownZid));
2304     }
2305     else {
2306         memcpy(KDFcontext, ownZid, sizeof(ownZid));
2307         memcpy(KDFcontext+sizeof(ownZid), peerZid, sizeof(peerZid));
2308     }
2309 
2310     KDF(zrtpSession, hashLength, (unsigned char*)zrtpTrustedMitm, strlen(zrtpTrustedMitm)+1, KDFcontext,
2311         kdfSize, SHA256_DIGEST_LENGTH * 8, pbxSecretTmpBuffer);
2312 
2313     pbxSecretTmp = pbxSecretTmpBuffer;  // set pointer to buffer, signal PBX secret was computed
2314 #endif
2315 }
2316 
computeSRTPKeys()2317 void ZRtp::computeSRTPKeys() {
2318 
2319     // allocate the maximum size, compute real size to use
2320     uint8_t KDFcontext[sizeof(peerZid)+sizeof(ownZid)+sizeof(messageHash)];
2321     int32_t kdfSize = sizeof(peerZid)+sizeof(ownZid)+hashLength;
2322 
2323     int32_t keyLen = cipher->getKeylen() * 8;
2324 
2325     if (myRole == Responder) {
2326         memcpy(KDFcontext, peerZid, sizeof(peerZid));
2327         memcpy(KDFcontext+sizeof(peerZid), ownZid, sizeof(ownZid));
2328     }
2329     else {
2330         memcpy(KDFcontext, ownZid, sizeof(ownZid));
2331         memcpy(KDFcontext+sizeof(ownZid), peerZid, sizeof(peerZid));
2332     }
2333     memcpy(KDFcontext+sizeof(ownZid)+sizeof(peerZid), messageHash, hashLength);
2334 
2335     // Inititiator key and salt
2336     KDF(s0, hashLength, (unsigned char*)iniMasterKey, strlen(iniMasterKey)+1, KDFcontext, kdfSize, keyLen, srtpKeyI);
2337     KDF(s0, hashLength, (unsigned char*)iniMasterSalt, strlen(iniMasterSalt)+1, KDFcontext, kdfSize, 112, srtpSaltI);
2338 
2339     // Responder key and salt
2340     KDF(s0, hashLength, (unsigned char*)respMasterKey, strlen(respMasterKey)+1, KDFcontext, kdfSize, keyLen, srtpKeyR);
2341     KDF(s0, hashLength, (unsigned char*)respMasterSalt, strlen(respMasterSalt)+1, KDFcontext, kdfSize, 112, srtpSaltR);
2342 
2343     // The HMAC keys for GoClear
2344     KDF(s0, hashLength, (unsigned char*)iniHmacKey, strlen(iniHmacKey)+1, KDFcontext, kdfSize, hashLength*8, hmacKeyI);
2345     KDF(s0, hashLength, (unsigned char*)respHmacKey, strlen(respHmacKey)+1, KDFcontext, kdfSize, hashLength*8, hmacKeyR);
2346 
2347     // The keys for Confirm messages
2348     KDF(s0, hashLength, (unsigned char*)iniZrtpKey, strlen(iniZrtpKey)+1, KDFcontext, kdfSize, keyLen, zrtpKeyI);
2349     KDF(s0, hashLength, (unsigned char*)respZrtpKey, strlen(respZrtpKey)+1, KDFcontext, kdfSize, keyLen, zrtpKeyR);
2350 
2351     detailInfo.pubKey = detailInfo.sasType = NULL;
2352     if (!multiStream) {
2353         // Compute the new Retained Secret
2354         KDF(s0, hashLength, (unsigned char*)retainedSec, strlen(retainedSec)+1, KDFcontext, kdfSize, SHA256_DIGEST_LENGTH*8, newRs1);
2355 
2356         // Compute the ZRTP Session Key
2357         KDF(s0, hashLength, (unsigned char*)zrtpSessionKey, strlen(zrtpSessionKey)+1, KDFcontext, kdfSize, hashLength*8, zrtpSession);
2358 
2359         // Compute the exported Key
2360         KDF(s0, hashLength, (unsigned char*)zrtpExportedKey, strlen(zrtpExportedKey)+1, KDFcontext, kdfSize, hashLength*8, zrtpExport);
2361         // perform  generation according to chapter 5.5 and 8.
2362         // we don't need a speciai sasValue filed. sasValue are the first
2363         // (leftmost) 32 bits (4 bytes) of sasHash
2364         uint8_t sasBytes[4];
2365         KDF(s0, hashLength, (unsigned char*)sasString, strlen(sasString)+1, KDFcontext, kdfSize, SHA256_DIGEST_LENGTH*8, sasHash);
2366 
2367         // according to chapter 8 only the leftmost 20 bits of sasValue (aka
2368         //  sasHash) are used to create the character SAS string of type SAS
2369         // base 32 (5 bits per character)
2370         sasBytes[0] = sasHash[0];
2371         sasBytes[1] = sasHash[1];
2372         sasBytes[2] = sasHash[2] & 0xf0;
2373         sasBytes[3] = 0;
2374         if (*(int32_t*)b32 == *(int32_t*)(sasType->getName())) {
2375             SAS = Base32(sasBytes, 20).getEncoded();
2376         }
2377         else if (*(int32_t*)b32e == *(int32_t*)(sasType->getName())) {
2378             SAS = *EmojiBase32::u32StringToUtf8(EmojiBase32(sasBytes, 20).getEncoded());
2379         }
2380         else {
2381             SAS.assign(sas256WordsEven[sasBytes[0]]).append(":").append(sas256WordsOdd[sasBytes[1]]);
2382         }
2383 
2384         if (signSasSeen)
2385              callback->signSAS(sasHash);
2386 
2387         detailInfo.pubKey = pubKey->getReadable();
2388         detailInfo.sasType = sasType->getReadable();
2389     }
2390     // set algorithm names into detailInfo structure
2391     detailInfo.authLength = authLength->getReadable();
2392     detailInfo.cipher = cipher->getReadable();
2393     detailInfo.hash = hash->getReadable();
2394 
2395     memset(KDFcontext, 0, sizeof(KDFcontext));
2396 }
2397 
srtpSecretsReady(EnableSecurity part)2398 bool ZRtp::srtpSecretsReady(EnableSecurity part) {
2399 
2400     SrtpSecret_t sec;
2401 
2402     sec.symEncAlgorithm = cipher->getAlgoId();
2403 
2404     sec.keyInitiator = srtpKeyI;
2405     sec.initKeyLen = cipher->getKeylen() * 8;
2406     sec.saltInitiator = srtpSaltI;
2407     sec.initSaltLen = 112;
2408 
2409     sec.keyResponder = srtpKeyR;
2410     sec.respKeyLen = cipher->getKeylen() * 8;
2411     sec.saltResponder = srtpSaltR;
2412     sec.respSaltLen = 112;
2413 
2414     sec.authAlgorithm = authLength->getAlgoId();
2415     sec.srtpAuthTagLen = authLength->getKeylen();
2416 
2417     sec.sas = SAS;
2418     sec.role = myRole;
2419 
2420     bool rc = callback->srtpSecretsReady(&sec, part);
2421 
2422     // The call state engine calls ForSender always after ForReceiver.
2423     if (part == ForSender) {
2424         std::string cs(cipher->getReadable());
2425         if (!multiStream) {
2426             cs.append("/").append(pubKey->getName());
2427             if (mitmSeen)
2428                 cs.append("/EndAtMitM");
2429             callback->srtpSecretsOn(cs, SAS, zidRec->isSasVerified());
2430         }
2431         else {
2432             std::string cs1("");
2433             if (mitmSeen)
2434                 cs.append("/EndAtMitM");
2435             callback->srtpSecretsOn(cs, cs1, true);
2436         }
2437     }
2438     return rc;
2439 }
2440 
2441 
setNegotiatedHash(AlgorithmEnum * hash)2442 void ZRtp::setNegotiatedHash(AlgorithmEnum* hash) {
2443     switch (zrtpHashes.getOrdinal(*hash)) {
2444     case 0:
2445         hashLength = SHA256_DIGEST_LENGTH;
2446         hashFunction = sha256;
2447         hashListFunction = sha256;
2448 
2449         hmacFunction = hmac_sha256;
2450         hmacListFunction = hmac_sha256;
2451 
2452         createHashCtx = initializeSha256Context;
2453         msgShaContext = &hashCtx.sha256Ctx;
2454         closeHashCtx = finalizeSha256Context;
2455         hashCtxFunction = sha256Ctx;
2456         hashCtxListFunction = sha256Ctx;
2457         break;
2458 
2459     case 1:
2460         hashLength = SHA384_DIGEST_LENGTH;
2461         hashFunction = sha384;
2462         hashListFunction = sha384;
2463 
2464         hmacFunction = hmac_sha384;
2465         hmacListFunction = hmac_sha384;
2466 
2467         createHashCtx = initializeSha384Context;
2468         msgShaContext = &hashCtx.sha384Ctx;
2469         closeHashCtx = finalizeSha384Context;
2470         hashCtxFunction = sha384Ctx;
2471         hashCtxListFunction = sha384Ctx;
2472         break;
2473 
2474     case 2:
2475         hashLength = SKEIN256_DIGEST_LENGTH;
2476         hashFunction = skein256;
2477         hashListFunction = skein256;
2478 
2479         hmacFunction = macSkein256;
2480         hmacListFunction = macSkein256;
2481 
2482         createHashCtx = initializeSkein256Context;
2483         msgShaContext = &hashCtx.skeinCtx;
2484         closeHashCtx = finalizeSkein256Context;
2485         hashCtxFunction = skein256Ctx;
2486         hashCtxListFunction = skein256Ctx;
2487         break;
2488 
2489     case 3:
2490         hashLength = SKEIN384_DIGEST_LENGTH;
2491         hashFunction = skein384;
2492         hashListFunction = skein384;
2493 
2494         hmacFunction = macSkein384;
2495         hmacListFunction = macSkein384;
2496 
2497         createHashCtx = initializeSkein384Context;
2498         msgShaContext = &hashCtx.skeinCtx;
2499         closeHashCtx = finalizeSkein384Context;
2500         hashCtxFunction = skein384Ctx;
2501         hashCtxListFunction = skein384Ctx;
2502         break;
2503     }
2504 }
2505 
2506 
srtpSecretsOff(EnableSecurity part)2507 void ZRtp::srtpSecretsOff(EnableSecurity part) {
2508     callback->srtpSecretsOff(part);
2509 }
2510 
SASVerified()2511 void ZRtp::SASVerified() {
2512     if (paranoidMode)
2513         return;
2514 
2515     zidRec->setSasVerified();
2516     saveZidRecord = true;
2517     getZidCacheInstance()->saveRecord(zidRec);
2518 }
2519 
resetSASVerified()2520 void ZRtp::resetSASVerified() {
2521 
2522     zidRec->resetSasVerified();
2523     getZidCacheInstance()->saveRecord(zidRec);
2524 }
2525 
isSASVerified()2526 bool ZRtp::isSASVerified() {
2527     return zidRec->isSasVerified();
2528 }
2529 
setRs2Valid()2530 void ZRtp::setRs2Valid() {
2531 
2532     if (zidRec != NULL) {
2533         zidRec->setRs2Valid();
2534         if (saveZidRecord)
2535             getZidCacheInstance()->saveRecord(zidRec);
2536     }
2537 }
2538 
getSecureSince()2539 int64_t ZRtp::getSecureSince() {
2540     if (zidRec != NULL)
2541         return zidRec->getSecureSince();
2542     return 0;
2543 }
2544 
2545 
sendInfo(GnuZrtpCodes::MessageSeverity severity,int32_t subCode)2546 void ZRtp::sendInfo(GnuZrtpCodes::MessageSeverity severity, int32_t subCode) {
2547 
2548     // We've reached secure state: overwrite the SRTP master key and master salt.
2549     if (severity == Info && subCode == InfoSecureStateOn) {
2550         memset(srtpKeyI, 0, cipher->getKeylen());
2551         memset(srtpSaltI, 0, 112/8);
2552         memset(srtpKeyR, 0, cipher->getKeylen());
2553         memset(srtpSaltR, 0, 112/8);
2554     }
2555     callback->sendInfo(severity, subCode);
2556 }
2557 
2558 
zrtpNegotiationFailed(GnuZrtpCodes::MessageSeverity severity,int32_t subCode)2559 void ZRtp::zrtpNegotiationFailed(GnuZrtpCodes::MessageSeverity severity, int32_t subCode) {
2560     callback->zrtpNegotiationFailed(severity, subCode);
2561 }
2562 
zrtpNotSuppOther()2563 void ZRtp::zrtpNotSuppOther() {
2564     callback->zrtpNotSuppOther();
2565 }
2566 
synchEnter()2567 void ZRtp::synchEnter() {
2568     callback->synchEnter();
2569 }
2570 
synchLeave()2571 void ZRtp::synchLeave() {
2572     callback->synchLeave();
2573 }
2574 
sendPacketZRTP(ZrtpPacketBase * packet)2575 int32_t ZRtp::sendPacketZRTP(ZrtpPacketBase *packet) {
2576     return ((packet == NULL) ? 0 :
2577             callback->sendDataZRTP(packet->getHeaderBase(), (packet->getLength() * 4) + 4));
2578 }
2579 
activateTimer(int32_t tm)2580 int32_t ZRtp::activateTimer(int32_t tm) {
2581     return (callback->activateTimer(tm));
2582 }
2583 
cancelTimer()2584 int32_t ZRtp::cancelTimer() {
2585     return (callback->cancelTimer());
2586 }
2587 
setAuxSecret(uint8_t * data,int32_t length)2588 void ZRtp::setAuxSecret(uint8_t* data, int32_t length) {
2589     if (length > 0) {
2590         auxSecret = new uint8_t[length];
2591         auxSecretLength = length;
2592         memcpy(auxSecret, data, length);
2593     }
2594 }
2595 
setClientId(std::string id,HelloPacketVersion * hpv)2596 void ZRtp::setClientId(std::string id, HelloPacketVersion* hpv) {
2597 
2598     unsigned char tmp[CLIENT_ID_SIZE +1] = {' '};
2599     memcpy(tmp, id.c_str(), id.size() > CLIENT_ID_SIZE ? CLIENT_ID_SIZE : id.size());
2600     tmp[CLIENT_ID_SIZE] = 0;
2601 
2602     hpv->packet->setClientId(tmp);
2603 
2604     int32_t len = hpv->packet->getLength() * ZRTP_WORD_SIZE;
2605 
2606     // Hello packets are ready now, compute its HMAC
2607     // (excluding the HMAC field (2*ZTP_WORD_SIZE)) and store in Hello
2608     // use the implicit hash function
2609     uint8_t hmac[IMPL_MAX_DIGEST_LENGTH];
2610     uint32_t macLen;
2611     hmacFunctionImpl(H2, HASH_IMAGE_SIZE, (uint8_t*)hpv->packet->getHeaderBase(), len-(2*ZRTP_WORD_SIZE), hmac, &macLen);
2612     hpv->packet->setHMAC(hmac);
2613 
2614     // calculate hash over the final Hello packet, refer to chap 9.1 how to
2615     // use this hash in SIP/SDP.
2616     hashFunctionImpl((uint8_t*)hpv->packet->getHeaderBase(), len, hpv->helloHash);
2617 }
2618 
storeMsgTemp(ZrtpPacketBase * pkt)2619 void ZRtp::storeMsgTemp(ZrtpPacketBase* pkt) {
2620     uint32_t length = pkt->getLength() * ZRTP_WORD_SIZE;
2621     length = (length > sizeof(tempMsgBuffer)) ? sizeof(tempMsgBuffer) : length;
2622     memset(tempMsgBuffer, 0, sizeof(tempMsgBuffer));
2623     memcpy(tempMsgBuffer, (uint8_t*)pkt->getHeaderBase(), length);
2624     lengthOfMsgData = length;
2625 }
2626 
checkMsgHmac(uint8_t * key)2627 bool ZRtp::checkMsgHmac(uint8_t* key) {
2628     uint8_t hmac[IMPL_MAX_DIGEST_LENGTH];
2629     uint32_t macLen;
2630     int32_t len = lengthOfMsgData-(HMAC_SIZE);  // compute HMAC, but exlude the stored HMAC :-)
2631 
2632     // Use the implicit hash function
2633     hmacFunctionImpl(key, HASH_IMAGE_SIZE, tempMsgBuffer, len, hmac, &macLen);
2634     return (memcmp(hmac, tempMsgBuffer+len, (HMAC_SIZE)) == 0 ? true : false);
2635 }
2636 
getHelloHash(int32_t index)2637 std::string ZRtp::getHelloHash(int32_t index) {
2638     std::ostringstream stm;
2639 
2640     if (index < 0 || index >= MAX_ZRTP_VERSIONS)
2641         return std::string();
2642 
2643     uint8_t* hp = helloPackets[index].helloHash;
2644 
2645     char version[5] = {'\0'};
2646     strncpy(version, (const char*)helloPackets[index].packet->getVersion(), ZRTP_WORD_SIZE);
2647 
2648     stm << version;
2649     stm << " ";
2650     stm.fill('0');
2651     stm << hex;
2652     for (int i = 0; i < hashLengthImpl; i++) {
2653         stm.width(2);
2654         stm << static_cast<uint32_t>(*hp++);
2655     }
2656     return stm.str();
2657 }
2658 
getPeerHelloHash()2659 std::string ZRtp::getPeerHelloHash() {
2660     std::ostringstream stm;
2661 
2662     if (peerHelloVersion[0] == 0)
2663         return std::string();
2664 
2665     uint8_t* hp = peerHelloHash;
2666 
2667     stm << peerHelloVersion;
2668     stm << " ";
2669     stm.fill('0');
2670     stm << hex;
2671     for (int i = 0; i < hashLengthImpl; i++) {
2672         stm.width(2);
2673         stm << static_cast<uint32_t>(*hp++);
2674     }
2675     return stm.str();
2676 }
2677 
getMultiStrParams(ZRtp ** zrtpMaster)2678 std::string ZRtp::getMultiStrParams(ZRtp **zrtpMaster) {
2679 
2680     // the string will hold binary data - it's opaque to the application
2681     std::string str("");
2682     char tmp[MAX_DIGEST_LENGTH + 1 + 1 + 1]; // hash length + cipher + authLength + hash
2683 
2684     if (inState(SecureState) && !multiStream) {
2685         // construct array that holds zrtpSession, cipher type, auth-length, and hash type
2686         tmp[0] = zrtpHashes.getOrdinal(*hash);
2687         tmp[1] = zrtpAuthLengths.getOrdinal(*authLength);
2688         tmp[2] = zrtpSymCiphers.getOrdinal(*cipher);
2689         memcpy(tmp+3, zrtpSession, hashLength);
2690         str.assign(tmp, hashLength + 1 + 1 + 1); // set chars (bytes) to the string
2691         if (zrtpMaster != NULL)
2692             *zrtpMaster = this;
2693     }
2694     return str;
2695 }
2696 
setMultiStrParams(std::string parameters,ZRtp * zrtpMaster)2697 void ZRtp::setMultiStrParams(std::string parameters, ZRtp *zrtpMaster) {
2698 
2699     char tmp[MAX_DIGEST_LENGTH + 1 + 1 + 1]; // max. hash length + cipher + authLength + hash
2700 
2701     // First get negotiated hash from parameters, set algorithms and length
2702     int i = parameters.at(0) & 0xff;
2703     hash = &zrtpHashes.getByOrdinal(i);
2704     setNegotiatedHash(hash);           // sets hashlength
2705 
2706     // use string.copy(buffer, num, start=0) to retrieve chars (bytes) from the string
2707     parameters.copy(tmp, hashLength + 1 + 1 + 1, 0);
2708 
2709     i = tmp[1] & 0xff;
2710     authLength = &zrtpAuthLengths.getByOrdinal(i);
2711     i = tmp[2] & 0xff;
2712     cipher = &zrtpSymCiphers.getByOrdinal(i);
2713     memcpy(zrtpSession, tmp+3, hashLength);
2714 
2715     // after setting zrtpSession, cipher, and auth-length set multi-stream to true
2716     multiStream = true;
2717     stateEngine->setMultiStream(true);
2718     if (zrtpMaster != NULL)
2719         masterStream = zrtpMaster;
2720 }
2721 
isMultiStream()2722 bool ZRtp::isMultiStream() {
2723     return multiStream;
2724 }
2725 
isMultiStreamAvailable()2726 bool ZRtp::isMultiStreamAvailable() {
2727     return multiStreamAvailable;
2728 }
2729 
acceptEnrollment(bool accepted)2730 void ZRtp::acceptEnrollment(bool accepted) {
2731 #ifdef ZRTP_SAS_RELAY_SUPPORT
2732     if (!accepted) {
2733         zidRec->resetMITMKeyAvailable();
2734         callback->zrtpInformEnrollment(EnrollmentCanceled);
2735         getZidCacheInstance()->saveRecord(zidRec);
2736         return;
2737     }
2738     if (pbxSecretTmp != NULL) {
2739         zidRec->setMiTMData(pbxSecretTmp);
2740         getZidCacheInstance()->saveRecord(zidRec);
2741         callback->zrtpInformEnrollment(EnrollmentOk);
2742     }
2743     else {
2744         callback->zrtpInformEnrollment(EnrollmentFailed);
2745     }
2746 #endif
2747 }
2748 
setSignatureData(uint8_t * data,int32_t length)2749 bool ZRtp::setSignatureData(uint8_t* data, int32_t length) {
2750     if ((length % 4) != 0)
2751         return false;
2752 
2753     ZrtpPacketConfirm* cfrm = (myRole == Responder) ? &zrtpConfirm1 : &zrtpConfirm2;
2754     cfrm->setSignatureLength(length / 4);
2755     return cfrm->setSignatureData(data, length);
2756 }
2757 
getSignatureData()2758 const uint8_t* ZRtp::getSignatureData() {
2759     return signatureData;
2760 }
2761 
getSignatureLength()2762 int32_t ZRtp::getSignatureLength() {
2763     return signatureLength * ZRTP_WORD_SIZE;
2764 }
2765 
conf2AckSecure()2766 void ZRtp::conf2AckSecure() {
2767     Event_t ev;
2768 
2769     ev.type = ZrtpPacket;
2770     ev.packet = (uint8_t*)zrtpConf2Ack.getHeaderBase();
2771     ev.length = sizeof (Conf2AckPacket_t) + 12;  // 12 is fixed ZRTP (RTP) header size
2772 
2773     if (stateEngine != NULL) {
2774         stateEngine->processEvent(&ev);
2775     }
2776 }
2777 
compareCommit(ZrtpPacketCommit * commit)2778 int32_t ZRtp::compareCommit(ZrtpPacketCommit *commit) {
2779     // TODO: enhance to compare according to rules defined in chapter 4.2,
2780     // but we don't support Preshared.
2781     int32_t len = 0;
2782     len = !multiStream ? HVI_SIZE : (4 * ZRTP_WORD_SIZE);
2783     return (memcmp(hvi, commit->getHvi(), len));
2784 }
2785 
isEnrollmentMode()2786 bool ZRtp::isEnrollmentMode() {
2787     return enrollmentMode;
2788 }
2789 
setEnrollmentMode(bool enrollmentMode)2790 void ZRtp::setEnrollmentMode(bool enrollmentMode) {
2791 #ifdef ZRTP_SAS_RELAY_SUPPORT
2792     this->enrollmentMode = enrollmentMode;
2793 #else
2794     this->enrollmentMode = false;
2795 #endif
2796 }
2797 
isPeerEnrolled()2798 bool ZRtp::isPeerEnrolled() {
2799     return peerIsEnrolled;
2800 }
2801 
sendSASRelayPacket(uint8_t * sh,std::string render)2802 bool ZRtp::sendSASRelayPacket(uint8_t* sh, std::string render) {
2803 
2804     uint8_t confMac[MAX_DIGEST_LENGTH];
2805     uint32_t macLen;
2806     uint8_t* hkey, *ekey;
2807 
2808     // If we are responder then the PBX used it's Initiator keys
2809     if (myRole == Responder) {
2810         hkey = hmacKeyR;
2811         ekey = zrtpKeyR;
2812         // TODO: check signature length in zrtpConfirm1 and if not zero copy Signature data
2813     }
2814     else {
2815         hkey = hmacKeyI;
2816         ekey = zrtpKeyI;
2817         // TODO: check signature length in zrtpConfirm2 and if not zero copy Signature data
2818     }
2819     // Prepare IV data that we will use during confirm packet encryption.
2820     randomZRTP(randomIV, sizeof(randomIV));
2821     zrtpSasRelay.setIv(randomIV);
2822     zrtpSasRelay.setTrustedSas(sh);
2823     zrtpSasRelay.setSasAlgo((uint8_t*)render.c_str());
2824 
2825     int16_t hmlen = (zrtpSasRelay.getLength() - 9) * ZRTP_WORD_SIZE;
2826     cipher->getEncrypt()(ekey, cipher->getKeylen(), randomIV, (uint8_t*)zrtpSasRelay.getFiller(), hmlen);
2827 
2828     // Use negotiated HMAC (hash)
2829     hmacFunction(hkey, hashLength, (unsigned char*)zrtpSasRelay.getFiller(), hmlen, confMac, &macLen);
2830 
2831     zrtpSasRelay.setHmac(confMac);
2832 
2833     stateEngine->sendSASRelay(&zrtpSasRelay);
2834     return true;
2835 }
2836 
getSasType()2837 std::string ZRtp::getSasType() {
2838     std::string sasT(sasType->getName());
2839     return sasT;
2840 }
2841 
getSasHash()2842 uint8_t* ZRtp::getSasHash() {
2843     return sasHash;
2844 }
2845 
getPeerZid(uint8_t * data)2846 int32_t ZRtp::getPeerZid(uint8_t* data) {
2847     memcpy(data, peerZid, IDENTIFIER_LEN);
2848     return IDENTIFIER_LEN;
2849 }
2850 
getDetailInfo()2851 const ZRtp::zrtpInfo* ZRtp::getDetailInfo() {
2852     return &detailInfo;
2853 }
2854 
getPeerClientId()2855 std::string ZRtp::getPeerClientId() {
2856     if (peerClientId.empty())
2857         return std::string();
2858     return peerClientId;
2859 }
2860 
getPeerProtcolVersion()2861 std::string ZRtp::getPeerProtcolVersion() {
2862     if (peerHelloVersion[0] == 0)
2863         return std::string();
2864     return std::string((char*)peerHelloVersion);
2865 }
2866 
setT1Resend(int32_t counter)2867 void ZRtp::setT1Resend(int32_t counter) {
2868     if (counter < 0 || counter > 10)
2869         stateEngine->setT1Resend(counter);
2870 }
2871 
setT1ResendExtend(int32_t counter)2872 void ZRtp::setT1ResendExtend(int32_t counter) {
2873     stateEngine->setT1ResendExtend(counter);
2874 }
2875 
setT1Capping(int32_t capping)2876 void ZRtp::setT1Capping(int32_t capping) {
2877     if (capping >= 50)
2878         stateEngine->setT1Capping(capping);
2879 }
2880 
setT2Resend(int32_t counter)2881 void ZRtp::setT2Resend(int32_t counter) {
2882     if (counter < 0 || counter > 10)
2883         stateEngine->setT2Resend(counter);
2884 }
2885 
setT2Capping(int32_t capping)2886 void ZRtp::setT2Capping(int32_t capping) {
2887     if (capping >= 150)
2888         stateEngine->setT2Capping(capping);
2889 }
2890 
getNumberOfCountersZrtp()2891 int ZRtp::getNumberOfCountersZrtp() {
2892     // If we add some other counters add them here before returning
2893     return stateEngine->getNumberOfRetryCounters();
2894 }
2895 
getCountersZrtp(int32_t * counters)2896 int ZRtp::getCountersZrtp(int32_t* counters) {
2897     return stateEngine->getRetryCounters(counters);
2898 }
2899 
getExportedKey(int32_t * length)2900 uint8_t* ZRtp::getExportedKey(int32_t *length) {
2901     if (length != NULL)
2902         *length = hashLength;
2903     return zrtpExport;
2904 }
2905 
checkAndSetNonce(uint8_t * nonce)2906 bool ZRtp::checkAndSetNonce(uint8_t* nonce) {
2907     // This is for backward compatibility if an applications uses the old
2908     // get- and setMultiStrParams functions
2909     if (masterStream == NULL)
2910         return true;
2911 
2912     for (std::vector<std::string>::iterator it = masterStream->peerNonces.begin() ; it != masterStream->peerNonces.end(); ++it) {
2913         if (memcmp((*it).data(), nonce, ZRTP_WORD_SIZE * 4) == 0) {
2914             return false;
2915         }
2916     }
2917     // the string holds the binary nonce
2918     std::string str("");
2919     str.assign((char *)nonce, ZRTP_WORD_SIZE * 4);
2920     masterStream->peerNonces.push_back(str);
2921     return true;
2922 }
2923 
2924 /** EMACS **
2925  * Local variables:
2926  * mode: c++
2927  * c-default-style: ellemtel
2928  * c-basic-offset: 4
2929  * End:
2930  */
2931 
2932