lime.c 43.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
linphone
Copyright (C) 2015  Belledonne Communications SARL

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
17
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 19
*/

20
#include "lime.h"
johan's avatar
johan committed
21 22 23 24 25
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef HAVE_LIME
26
#include "private.h"
johan's avatar
johan committed
27
#include "bctoolbox/crypto.h"
johan's avatar
johan committed
28

29 30
#define FILE_TRANSFER_KEY_SIZE 32

johan's avatar
johan committed
31 32 33 34 35
/**
 * @brief check at runtime if LIME is available
 *
 * @return TRUE when Lime was fully compiled, FALSE when it wasn't
 */
36
bool_t lime_is_available(void) { return TRUE; }
johan's avatar
johan committed
37

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
/**
 * @brief	convert an hexa char [0-9a-fA-F] into the corresponding unsigned integer value
 * Any invalid char will be converted to zero without any warning
 *
 * @param[in]	inputChar	a char which shall be in range [0-9a-fA-F]
 *
 * @return		the unsigned integer value in range [0-15]
 */
uint8_t lime_charToByte(uint8_t inputChar) {
	/* 0-9 */
	if (inputChar>0x29 && inputChar<0x3A) {
		return inputChar - 0x30;
	}

	/* a-f */
	if (inputChar>0x60 && inputChar<0x67) {
		return inputChar - 0x57; /* 0x57 = 0x61(a) + 0x0A*/
	}

	/* A-F */
	if (inputChar>0x40 && inputChar<0x47) {
		return inputChar - 0x37; /* 0x37 = 0x41(a) + 0x0A*/
	}

	/* shall never arrive here, string is not Hex*/
	return 0;

}

/**
 * @brief	convert a byte which value is in range [0-15] into an hexa char [0-9a-fA-F]
 *
 * @param[in]	inputByte	an integer which shall be in range [0-15]
 *
 * @return		the hexa char [0-9a-f] corresponding to the input
 */
uint8_t lime_byteToChar(uint8_t inputByte) {
	inputByte &=0x0F; /* restrict the input value to range [0-15] */
	/* 0-9 */
	if(inputByte<0x0A) {
		return inputByte+0x30;
	}
	/* a-f */
	return inputByte + 0x57;
}


/**
 * @brief Convert an hexadecimal string into the corresponding byte buffer
 *
 * @param[out]	outputBytes			The output bytes buffer, must have a length of half the input string buffer
 * @param[in]	inputString			The input string buffer, must be hexadecimal(it is not checked by function, any non hexa char is converted to 0)
 * @param[in]	inputStringLength	The lenght in chars of the string buffer, output is half this length
 */
void lime_strToUint8(uint8_t *outputBytes, uint8_t *inputString, uint16_t inputStringLength) {
	int i;
	for (i=0; i<inputStringLength/2; i++) {
		outputBytes[i] = (lime_charToByte(inputString[2*i]))<<4 | lime_charToByte(inputString[2*i+1]);
	}
}

/**
 * @brief Convert a byte buffer into the corresponding hexadecimal string
 *
 * @param[out]	outputString		The output string buffer, must have a length of twice the input bytes buffer
 * @param[in]	inputBytes			The input bytes buffer
 * @param[in]	inputBytesLength	The lenght in bytes buffer, output is twice this length
 */
void lime_int8ToStr(uint8_t *outputString, uint8_t *inputBytes, uint16_t inputBytesLength) {
	int i;
	for (i=0; i<inputBytesLength; i++) {
		outputString[2*i] = lime_byteToChar((inputBytes[i]>>4)&0x0F);
		outputString[2*i+1] = lime_byteToChar(inputBytes[i]&0x0F);
	}
}



johan's avatar
johan committed
116 117 118 119 120 121 122 123 124
/**
 * @brief Retrieve selfZID from cache
 *
 * @param[in]	cacheBuffer		The xmlDoc containing current cache
 * @param[out]	selfZid			The ZID found as a 24 hexa char string null terminated
 *
 * @return 0 on success, error code otherwise
 */
static int lime_getSelfZid(xmlDocPtr cacheBuffer, uint8_t selfZid[25]) {
johan's avatar
johan committed
125 126 127
	xmlNodePtr cur;
	xmlChar *selfZidHex;

128 129
	if (cacheBuffer == NULL ) {
		return LIME_INVALID_CACHE;
130 131
	}

johan's avatar
johan committed
132
	cur = xmlDocGetRootElement(cacheBuffer);
133
	/* if we found a root element, parse its children node */
134
	if (cur!=NULL)
135 136 137
	{
		cur = cur->xmlChildrenNode;
	}
johan's avatar
johan committed
138
	selfZidHex = NULL;
139 140
	while (cur!=NULL) {
		if ((!xmlStrcmp(cur->name, (const xmlChar *)"selfZID"))){ /* self ZID found, extract it */
141
			selfZidHex = xmlNodeListGetString(cacheBuffer, cur->xmlChildrenNode, 1);
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
			/* copy it to the output buffer and add the null termination */
			memcpy(selfZid, selfZidHex, 24);
			selfZid[24]='\0';
			break;
		}
		cur = cur->next;
	}

	/* did we found a ZID? */
	if (selfZidHex == NULL) {
		return LIME_INVALID_CACHE;
	}

	xmlFree(selfZidHex);
	return 0;
}

int lime_getCachedSndKeysByURI(xmlDocPtr cacheBuffer, limeURIKeys_t *associatedKeys) {
johan's avatar
johan committed
160
	xmlNodePtr cur;
161

162 163 164 165 166 167 168 169 170
	/* parse the file to get all peer matching the sipURI given in associatedKeys*/
	if (cacheBuffer == NULL ) { /* there is no cache return error */
		return LIME_INVALID_CACHE;
	}

	/* reset number of associated keys and their buffer */
	associatedKeys->associatedZIDNumber = 0;
	associatedKeys->peerKeys = NULL;

johan's avatar
johan committed
171
	cur = xmlDocGetRootElement(cacheBuffer);
172
	/* if we found a root element, parse its children node */
173
	if (cur!=NULL)
174 175 176 177 178 179 180
	{
		cur = cur->xmlChildrenNode;
	}
	while (cur!=NULL) { /* loop on all peer nodes */
		uint8_t matchingURIFlag = 0; /* this flag is set to one if we found the requested sipURI in the current peer node */
		if ((!xmlStrcmp(cur->name, (const xmlChar *)"peer"))) { /* found a peer node, check if there is a matching sipURI node in it */
			xmlNodePtr peerNodeChildren = cur->xmlChildrenNode;
johan's avatar
johan committed
181
			matchingURIFlag = 0;
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

			/* loop on children nodes until the end or we found the matching sipURI */
			while (peerNodeChildren!=NULL && matchingURIFlag==0) {
				if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"uri")) { /* found a peer an URI node, check the content */
					xmlChar *uriNodeContent = xmlNodeListGetString(cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
					if (!xmlStrcmp(uriNodeContent, (const xmlChar *)associatedKeys->peerURI)) { /* found a match with requested URI */
						matchingURIFlag=1;
					}
					xmlFree(uriNodeContent);
				}
				peerNodeChildren = peerNodeChildren->next;
			}

			if (matchingURIFlag == 1) { /* we found a match for the URI in this peer node, extract the keys, session Id and index values */
				/* allocate a new limeKey_t structure to hold the retreived keys */
				limeKey_t *currentPeerKeys = (limeKey_t *)malloc(sizeof(limeKey_t));
198 199
				uint8_t itemFound = 0; /* count the item found, we must get all of the requested infos: 5 nodes*/
				uint8_t pvs = 0;
200

201
				peerNodeChildren = cur->xmlChildrenNode; /* reset peerNodeChildren to the first child of node */
202
				while (peerNodeChildren!=NULL && itemFound<5) {
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
					xmlChar *nodeContent = NULL;
					if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"ZID")) {
						nodeContent = xmlNodeListGetString(cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
						lime_strToUint8(currentPeerKeys->peerZID, nodeContent, 24);
						itemFound++;
					}

					if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"sndKey")) {
						nodeContent = xmlNodeListGetString(cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
						lime_strToUint8(currentPeerKeys->key, nodeContent, 64);
						itemFound++;
					}
					if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"sndSId")) {
						nodeContent = xmlNodeListGetString(cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
						lime_strToUint8(currentPeerKeys->sessionId, nodeContent, 64);
						itemFound++;
					}
					if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"sndIndex")) {
						uint8_t sessionIndexBuffer[4]; /* session index is a uint32_t but we first retrieved it as an hexa string, convert it to a 4 uint8_t buffer */
johan's avatar
johan committed
222
						nodeContent = xmlNodeListGetString(cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
223 224 225 226 227
						lime_strToUint8(sessionIndexBuffer, nodeContent, 8);
						/* convert it back to a uint32_t (MSByte first)*/
						currentPeerKeys->sessionIndex = sessionIndexBuffer[3] + (sessionIndexBuffer[2]<<8) + (sessionIndexBuffer[1]<<16) + (sessionIndexBuffer[0]<<24);
						itemFound++;
					}
228 229 230 231 232
					if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"pvs")) {
						nodeContent = xmlNodeListGetString(cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
						lime_strToUint8(&pvs, nodeContent, 2); /* pvs is retrieved as a 2 characters hexa string, convert it to an int8 */
						itemFound++;
					}
233 234 235 236 237

					xmlFree(nodeContent);
					peerNodeChildren = peerNodeChildren->next;
				}

238 239
				/* check if we have all the requested information and the PVS flag is set to 1 */
				if (itemFound == 5 && pvs == 1) {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
					associatedKeys->associatedZIDNumber +=1;
					/* extend array of pointer to limeKey_t structures to add the one we found */
					associatedKeys->peerKeys = (limeKey_t **)realloc(associatedKeys->peerKeys, (associatedKeys->associatedZIDNumber)*sizeof(limeKey_t *));

					/* add the new entry at the end */
					associatedKeys->peerKeys[associatedKeys->associatedZIDNumber-1] = currentPeerKeys;

				} else {
					free(currentPeerKeys);
				}
			}
		}
		cur = cur->next;
	}
	return 0;
}

int lime_getCachedRcvKeyByZid(xmlDocPtr cacheBuffer, limeKey_t *associatedKey) {
johan's avatar
johan committed
258 259 260 261 262 263
	uint8_t peerZidHex[25];
	/* to check we collect all the information needed from the cache and that pvs(boolean for previously verified Sas) is set in cache */
	uint8_t itemFound = 0;
	uint8_t pvs = 0;
	xmlNodePtr cur;

264 265 266 267 268 269 270 271
	if (cacheBuffer == NULL ) { /* there is no cache return error */
		return LIME_INVALID_CACHE;
	}

	/* get the given ZID into hex format */
	lime_int8ToStr(peerZidHex, associatedKey->peerZID, 12);
	peerZidHex[24]='\0'; /* must be a null terminated string */

johan's avatar
johan committed
272
	cur = xmlDocGetRootElement(cacheBuffer);
273
	/* if we found a root element, parse its children node */
274
	if (cur!=NULL)
275 276 277 278
	{
		cur = cur->xmlChildrenNode;

	}
279 280

	while (cur!=NULL) { /* loop on all peer nodes */
281 282 283 284
		if ((!xmlStrcmp(cur->name, (const xmlChar *)"peer"))){ /* found a peer, check his ZID element */
			xmlChar *currentZidHex = xmlNodeListGetString(cacheBuffer, cur->xmlChildrenNode->xmlChildrenNode, 1); /* ZID is the first element of peer */
			if (!xmlStrcmp(currentZidHex, (const xmlChar *)peerZidHex)) { /* we found the peer element we are looking for */
				xmlNodePtr peerNodeChildren = cur->xmlChildrenNode->next;
285
				while (peerNodeChildren != NULL && itemFound<4) { /* look for the tag we want to read : rcvKey, rcvSId, rcvIndex and pvs*/
286 287 288 289 290 291 292 293 294 295 296 297 298
					xmlChar *nodeContent = NULL;
					if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"rcvKey")) {
						nodeContent = xmlNodeListGetString(cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
						lime_strToUint8(associatedKey->key, nodeContent, 64);
						itemFound++;
					}
					if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"rcvSId")) {
						nodeContent = xmlNodeListGetString(cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
						lime_strToUint8(associatedKey->sessionId, nodeContent, 64);
						itemFound++;
					}
					if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"rcvIndex")) {
						uint8_t sessionIndexBuffer[4]; /* session index is a uint32_t but we first retrieved it as an hexa string, convert it to a 4 uint8_t buffer */
johan's avatar
johan committed
299
						nodeContent = xmlNodeListGetString(cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
300 301 302 303 304
						lime_strToUint8(sessionIndexBuffer, nodeContent, 8);
						/* convert it back to a uint32_t (MSByte first)*/
						associatedKey->sessionIndex = sessionIndexBuffer[3] + (sessionIndexBuffer[2]<<8) + (sessionIndexBuffer[1]<<16) + (sessionIndexBuffer[0]<<24);
						itemFound++;
					}
305 306 307 308 309
					if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"pvs")) {
						nodeContent = xmlNodeListGetString(cacheBuffer, peerNodeChildren->xmlChildrenNode, 1);
						lime_strToUint8(&pvs, nodeContent, 2); /* pvs is retrieved as a 2 characters hexa string, convert it to an int8 */
						itemFound++;
					}
310 311 312
					xmlFree(nodeContent);
					peerNodeChildren = peerNodeChildren->next;
				}
313 314
				xmlFree(currentZidHex);
				break; /* we parsed the peer node we were looking for, get out of the main while */
315 316 317 318 319 320
			}
			xmlFree(currentZidHex);
		}
		cur = cur->next;
	}

321 322 323 324 325 326 327
	/* if we manage to find the correct key information and that pvs is set to 1, return 0 (success) */
	if ((pvs == 1) && (itemFound == 4)) {
		return 0;
	}

	/* otherwise, key wasn't found or is invalid */
	return LIME_NO_VALID_KEY_FOUND_FOR_PEER;
328 329 330
}

int lime_setCachedKey(xmlDocPtr cacheBuffer, limeKey_t *associatedKey, uint8_t role) {
johan's avatar
johan committed
331 332 333 334 335 336 337
	xmlNodePtr cur;
	uint8_t peerZidHex[25];
	uint8_t keyHex[65]; /* key is 32 bytes long -> 64 bytes string + null termination */
	uint8_t sessionIdHex[65]; /* sessionId is 32 bytes long -> 64 bytes string + null termination */
	uint8_t sessionIndexHex[9]; /*  sessionInedx is an uint32_t : 4 bytes long -> 8 bytes string + null termination */
	uint8_t itemFound = 0;

338 339 340 341 342 343 344 345
	if (cacheBuffer == NULL ) { /* there is no cache return error */
		return LIME_INVALID_CACHE;
	}

	/* get the given ZID into hex format */
	lime_int8ToStr(peerZidHex, associatedKey->peerZID, 12);
	peerZidHex[24]='\0'; /* must be a null terminated string */

johan's avatar
johan committed
346
	cur = xmlDocGetRootElement(cacheBuffer);
347
	/* if we found a root element, parse its children node */
348
	if (cur!=NULL)
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
	{
		cur = cur->xmlChildrenNode;

	}

	/* convert the given tag content to null terminated Hexadecimal strings */
	lime_int8ToStr(keyHex, associatedKey->key, 32);
	keyHex[64] = '\0';
	lime_int8ToStr(sessionIdHex, associatedKey->sessionId, 32);
	sessionIdHex[64] = '\0';
	sessionIndexHex[0] = lime_byteToChar((uint8_t)((associatedKey->sessionIndex>>28)&0x0F));
	sessionIndexHex[1] = lime_byteToChar((uint8_t)((associatedKey->sessionIndex>>24)&0x0F));
	sessionIndexHex[2] = lime_byteToChar((uint8_t)((associatedKey->sessionIndex>>20)&0x0F));
	sessionIndexHex[3] = lime_byteToChar((uint8_t)((associatedKey->sessionIndex>>16)&0x0F));
	sessionIndexHex[4] = lime_byteToChar((uint8_t)((associatedKey->sessionIndex>>12)&0x0F));
	sessionIndexHex[5] = lime_byteToChar((uint8_t)((associatedKey->sessionIndex>>8)&0x0F));
	sessionIndexHex[6] = lime_byteToChar((uint8_t)((associatedKey->sessionIndex>>4)&0x0F));
	sessionIndexHex[7] = lime_byteToChar((uint8_t)((associatedKey->sessionIndex)&0x0F));
	sessionIndexHex[8] = '\0';

	while (cur!=NULL && itemFound<3) { /* loop on all peer nodes */
		if ((!xmlStrcmp(cur->name, (const xmlChar *)"peer"))){ /* found a peer, check his ZID element */
			xmlChar *currentZidHex = xmlNodeListGetString(cacheBuffer, cur->xmlChildrenNode->xmlChildrenNode, 1); /* ZID is the first element of peer */
			if (!xmlStrcmp(currentZidHex, (const xmlChar *)peerZidHex)) { /* we found the peer element we are looking for */
				xmlNodePtr peerNodeChildren = cur->xmlChildrenNode->next;
				while (peerNodeChildren != NULL && itemFound<3) { /* look for the tag we want to write */
					if (role == LIME_RECEIVER) { /* writing receiver key */
						if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"rcvKey")) {
							xmlNodeSetContent(peerNodeChildren, (const xmlChar *)keyHex);
							itemFound++;
						}
						if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"rcvSId")) {
							xmlNodeSetContent(peerNodeChildren, (const xmlChar *)sessionIdHex);
							itemFound++;
						}
						if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"rcvIndex")) {
							xmlNodeSetContent(peerNodeChildren, (const xmlChar *)sessionIndexHex);
							itemFound++;
						}
					} else { /* writing sender key */
						if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"sndKey")) {
							xmlNodeSetContent(peerNodeChildren, (const xmlChar *)keyHex);
							itemFound++;
						}
						if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"sndSId")) {
							xmlNodeSetContent(peerNodeChildren, (const xmlChar *)sessionIdHex);
							itemFound++;
						}
						if (!xmlStrcmp(peerNodeChildren->name, (const xmlChar *)"sndIndex")) {
							xmlNodeSetContent(peerNodeChildren, (const xmlChar *)sessionIndexHex);
							itemFound++;
						}
					}
					peerNodeChildren = peerNodeChildren->next;
				}
			}
			xmlFree(currentZidHex);
		}
		cur = cur->next;
	}

410

411 412 413
	return 0;
}

johan's avatar
johan committed
414 415 416 417 418 419 420 421 422
/**
 * @brief Derive in place the key given in parameter and increment session index
 * Derivation is made derived Key = HMAC_SHA256(Key, 0x0000001||"MessageKey"||0x00||SessionId||SessionIndex||256)
 *
 * @param[in/out]	key		The structure containing the original key which will be overwritten, the sessionId and SessionIndex
 *
 * @return 0 on success, error code otherwise
 */
static int lime_deriveKey(limeKey_t *key) {
johan's avatar
johan committed
423 424 425
	uint8_t inputData[55];
	uint8_t derivedKey[32];

426 427 428 429 430 431 432 433 434 435
	if (key == NULL) {
		return LIME_UNABLE_TO_DERIVE_KEY;
	}

 	/* Derivation is made derived Key = HMAC_SHA256(Key, 0x0000001||"MessageKey"||0x00||SessionId||SessionIndex||0x00000100)*/
	/* total data to be hashed is       55 bytes  :           4   +      10     +   1 +     32   +   4         +   4 */
	inputData[0] = 0x00;
	inputData[1] = 0x00;
	inputData[2] = 0x00;
	inputData[3] = 0x01;
436

437 438 439
	memcpy(inputData+4, "MessageKey", 10);

	inputData[14] = 0x00;
440

441
	memcpy(inputData+15, key->sessionId, 32);
442

443 444 445 446
	inputData[47] = (uint8_t)((key->sessionIndex>>24)&0x000000FF);
	inputData[48] = (uint8_t)((key->sessionIndex>>16)&0x000000FF);
	inputData[49] = (uint8_t)((key->sessionIndex>>8)&0x000000FF);
	inputData[50] = (uint8_t)(key->sessionIndex&0x000000FF);
447

448 449 450 451 452 453
	inputData[51] = 0x00;
	inputData[52] = 0x00;
	inputData[53] = 0x01;
	inputData[54] = 0x00;

	/* derive the key in a temp buffer */
jehan's avatar
jehan committed
454
	bctbx_hmacSha256(key->key, 32, inputData, 55, 32, derivedKey);
455 456 457 458 459 460 461 462 463

	/* overwrite the old key with the derived one */
	memcpy(key->key, derivedKey, 32);

	/* increment the session Index */
	key->sessionIndex += 1;
	return 0;
}

464
void lime_freeKeys(limeURIKeys_t *associatedKeys) {
465 466 467
	int i;

	/* free all associated keys */
468 469
	for (i=0; i< associatedKeys->associatedZIDNumber; i++) {
		if (associatedKeys->peerKeys[i] != NULL) {
Simon Morlat's avatar
Simon Morlat committed
470
			/*shouldn't we memset to zero the content of peerKeys[i] in order clear keys?*/
471 472
			free(associatedKeys->peerKeys[i]);
			associatedKeys->peerKeys[i] = NULL;
473 474 475
		}
	}

476
	free(associatedKeys->peerKeys);
Simon Morlat's avatar
Simon Morlat committed
477
	associatedKeys->peerKeys = NULL;
478 479

	/* free sipURI string */
480
	free(associatedKeys->peerURI);
Simon Morlat's avatar
Simon Morlat committed
481
	associatedKeys->peerURI = NULL;
482 483 484 485
}

int lime_encryptMessage(limeKey_t *key, uint8_t *plainMessage, uint32_t messageLength, uint8_t selfZID[12], uint8_t *encryptedMessage) {
	uint8_t authenticatedData[28];
johan's avatar
johan committed
486
	/* Authenticated data is senderZID(12 bytes)||receiverZID(12 bytes)||sessionIndex(4 bytes) */
487 488 489 490 491 492 493 494 495
	memcpy(authenticatedData, selfZID, 12);
	memcpy(authenticatedData+12, key->peerZID, 12);
	authenticatedData[24] = (uint8_t)((key->sessionIndex>>24)&0x000000FF);
	authenticatedData[25] = (uint8_t)((key->sessionIndex>>16)&0x000000FF);
	authenticatedData[26] = (uint8_t)((key->sessionIndex>>8)&0x000000FF);
	authenticatedData[27] = (uint8_t)(key->sessionIndex&0x000000FF);

	/* AES-GCM : key is 192 bits long, Init Vector 64 bits. 256 bits key given is AES key||IV */
	/* tag is 16 bytes long and is set in the 16 first bytes of the encrypted message */
jehan's avatar
jehan committed
496
	return bctbx_aes_gcm_encrypt_and_tag(key->key, 24,
johan's avatar
johan committed
497 498 499 500 501
			plainMessage, messageLength,
			authenticatedData, 28,
			key->key+24, 8, /* IV is at the end(last 64 bits) of the given key buffer */
			encryptedMessage, 16, /* the first 16 bytes of output are the authentication tag */
			encryptedMessage+16); /* actual encrypted message starts after 16 bytes of authentication tag */
502 503 504 505

	return 0;
}

johan's avatar
johan committed
506
int lime_encryptFile(void **cryptoContext, unsigned char *key, size_t length, char *plain, char *cipher) {
jehan's avatar
jehan committed
507
	bctbx_aes_gcm_context_t *gcmContext;
johan's avatar
johan committed
508 509

	if (*cryptoContext == NULL) { /* first call to the function, allocate a crypto context and initialise it */
johan's avatar
johan committed
510
		/* key contains 192bits of key || 64 bits of Initialisation Vector, no additional data */
jehan's avatar
jehan committed
511
		gcmContext = bctbx_aes_gcm_context_new(key, 24, NULL, 0, key+24, 8, BCTBX_GCM_ENCRYPT);
johan's avatar
johan committed
512
		*cryptoContext = gcmContext;
johan's avatar
johan committed
513
	} else { /* this is not the first call, get the context */
jehan's avatar
jehan committed
514
		gcmContext = (bctbx_aes_gcm_context_t *)*cryptoContext;
johan's avatar
johan committed
515 516 517
	}

	if (length != 0) {
jehan's avatar
jehan committed
518
		bctbx_aes_gcm_process_chunk(gcmContext, (const uint8_t *)plain, length, (uint8_t *)cipher);
johan's avatar
johan committed
519
	} else { /* lenght is 0, finish the stream, no tag to be generated */
jehan's avatar
jehan committed
520
		bctbx_aes_gcm_finish(gcmContext, NULL, 0);
johan's avatar
johan committed
521 522 523 524 525 526 527
		*cryptoContext = NULL;
	}

	return 0;
}

int lime_decryptFile(void **cryptoContext, unsigned char *key, size_t length, char *plain, char *cipher) {
jehan's avatar
jehan committed
528
	bctbx_aes_gcm_context_t *gcmContext;
johan's avatar
johan committed
529 530

	if (*cryptoContext == NULL) { /* first call to the function, allocate a crypto context and initialise it */
johan's avatar
johan committed
531
		/* key contains 192bits of key || 64 bits of Initialisation Vector, no additional data */
jehan's avatar
jehan committed
532
		gcmContext = bctbx_aes_gcm_context_new(key, 24, NULL, 0, key+24, 8, BCTBX_GCM_DECRYPT);
johan's avatar
johan committed
533
		*cryptoContext = gcmContext;
johan's avatar
johan committed
534
	} else { /* this is not the first call, get the context */
jehan's avatar
jehan committed
535
		gcmContext = (bctbx_aes_gcm_context_t *)*cryptoContext;
johan's avatar
johan committed
536
	}
537

johan's avatar
johan committed
538
	if (length != 0) {
jehan's avatar
jehan committed
539
		bctbx_aes_gcm_process_chunk(gcmContext, (const unsigned char *)cipher, length, (unsigned char *)plain);
johan's avatar
johan committed
540
	} else { /* lenght is 0, finish the stream */
jehan's avatar
jehan committed
541
		bctbx_aes_gcm_finish(gcmContext, NULL, 0);
johan's avatar
johan committed
542 543 544 545 546 547 548
		*cryptoContext = NULL;
	}

	return 0;
}


549 550
int lime_decryptMessage(limeKey_t *key, uint8_t *encryptedMessage, uint32_t messageLength, uint8_t selfZID[12], uint8_t *plainMessage) {
	uint8_t authenticatedData[28];
johan's avatar
johan committed
551 552 553
	int retval;

	/* Authenticated data is senderZID(12 bytes)||receiverZID(12 bytes)||sessionIndex(4 bytes) */
554 555 556 557 558 559 560 561 562
	memcpy(authenticatedData, key->peerZID, 12);
	memcpy(authenticatedData+12, selfZID, 12);
	authenticatedData[24] = (uint8_t)((key->sessionIndex>>24)&0x000000FF);
	authenticatedData[25] = (uint8_t)((key->sessionIndex>>16)&0x000000FF);
	authenticatedData[26] = (uint8_t)((key->sessionIndex>>8)&0x000000FF);
	authenticatedData[27] = (uint8_t)(key->sessionIndex&0x000000FF);

	/* AES-GCM : key is 192 bits long, Init Vector 64 bits. 256 bits key given is AES key||IV */
	/* tag is 16 bytes long and is the 16 first bytes of the encrypted message */
jehan's avatar
jehan committed
563
	retval = bctbx_aes_gcm_decrypt_and_auth(key->key, 24, /* key is 192 bits long */
johan's avatar
johan committed
564 565 566 567 568 569
			encryptedMessage+16,  messageLength-16, /* encrypted message first 16 bytes store the authentication tag, then is the actual message */
			authenticatedData, 28, /* additionnal data needed for authentication */
			key->key+24, 8, /* last 8 bytes of key is the initialisation vector */
			encryptedMessage, 16, /* first 16 bytes of message is the authentication tag */
			plainMessage);

570 571 572 573 574 575 576 577
	/* add the null termination char */
	plainMessage[messageLength-16] = '\0';

	return retval;
}

int lime_createMultipartMessage(xmlDocPtr cacheBuffer, uint8_t *message, uint8_t *peerURI, uint8_t **output) {
	uint8_t selfZidHex[25];
johan's avatar
johan committed
578 579 580 581 582 583 584
	uint8_t selfZid[12]; /* same data but in byte buffer */
	uint32_t encryptedMessageLength;
	limeURIKeys_t associatedKeys;
	xmlDocPtr xmlOutputMessage;
	xmlNodePtr rootNode;
	int i;
	int xmlStringLength;
Sylvain Berfini's avatar
Sylvain Berfini committed
585
	xmlChar *local_output = NULL;
johan's avatar
johan committed
586 587

	/* retrieve selfZIDHex from cache(return a 24 char hexa string + null termination) */
588 589 590 591 592 593
	if (lime_getSelfZid(cacheBuffer, selfZidHex) != 0) {
		return LIME_UNABLE_TO_ENCRYPT_MESSAGE;
	}
	lime_strToUint8(selfZid, selfZidHex, 24);

	/* encrypted message length is plaintext + 16 for tag */
Ghislain MARY's avatar
Ghislain MARY committed
594
	encryptedMessageLength = (uint32_t)strlen((char *)message) + 16;
595 596 597 598 599 600 601 602

	/* retrieve keys associated to the peer URI */
	associatedKeys.peerURI = (uint8_t *)malloc(strlen((char *)peerURI)+1);
	strcpy((char *)(associatedKeys.peerURI), (char *)peerURI);
	associatedKeys.associatedZIDNumber  = 0;
	associatedKeys.peerKeys = NULL;

	if (lime_getCachedSndKeysByURI(cacheBuffer, &associatedKeys) != 0) {
603
		lime_freeKeys(&associatedKeys);
604 605 606 607
		return LIME_UNABLE_TO_ENCRYPT_MESSAGE;
	}

	if (associatedKeys.associatedZIDNumber == 0) {
608
		lime_freeKeys(&associatedKeys);
609
		return LIME_NO_VALID_KEY_FOUND_FOR_PEER;
610 611 612
	}

	/* create an xml doc to hold the multipart message */
johan's avatar
johan committed
613
	xmlOutputMessage = xmlNewDoc((const xmlChar *)"1.0");
614
	/* root tag is "doc" */
johan's avatar
johan committed
615
	rootNode = xmlNewDocNode(xmlOutputMessage, NULL, (const xmlChar *)"doc", NULL);
616 617 618 619 620 621
	xmlDocSetRootElement(xmlOutputMessage, rootNode);
	/* add the self ZID child */
	xmlNewTextChild(rootNode, NULL, (const xmlChar *)"ZID", selfZidHex);

	/* loop on all keys found */
	for (i=0; i<associatedKeys.associatedZIDNumber; i++) {
johan's avatar
johan committed
622 623 624
		uint8_t peerZidHex[25];
		uint8_t sessionIndexHex[9];
		xmlNodePtr msgNode;
johan's avatar
johan committed
625 626
		size_t b64Size = 0;
		unsigned char *encryptedMessageb64;
johan's avatar
johan committed
627

628 629 630
		/* encrypt message with current key */
		limeKey_t *currentKey = associatedKeys.peerKeys[i];
		/* encrypted message include a 16 bytes tag */
Sylvain Berfini's avatar
Sylvain Berfini committed
631
		uint8_t *encryptedMessage = (uint8_t *)ms_malloc(encryptedMessageLength);
Ghislain MARY's avatar
Ghislain MARY committed
632
		lime_encryptMessage(currentKey, message, (uint32_t)strlen((char *)message), selfZid, encryptedMessage);
633 634 635 636 637 638
		/* add a "msg" node the the output message, doc node is :
		 * <msg>
		 * 		<pzid>peerZID</pzid>
		 * 		<index>session index</index>
		 * 		<text>ciphertext</text>
		 * </msg> */
johan's avatar
johan committed
639
		msgNode = xmlNewDocNode(xmlOutputMessage, NULL, (const xmlChar *)"msg", NULL);
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
		lime_int8ToStr(peerZidHex, currentKey->peerZID, 12);
		peerZidHex[24] = '\0';
		sessionIndexHex[0] = lime_byteToChar((uint8_t)((currentKey->sessionIndex>>28)&0x0F));
		sessionIndexHex[1] = lime_byteToChar((uint8_t)((currentKey->sessionIndex>>24)&0x0F));
		sessionIndexHex[2] = lime_byteToChar((uint8_t)((currentKey->sessionIndex>>20)&0x0F));
		sessionIndexHex[3] = lime_byteToChar((uint8_t)((currentKey->sessionIndex>>16)&0x0F));
		sessionIndexHex[4] = lime_byteToChar((uint8_t)((currentKey->sessionIndex>>12)&0x0F));
		sessionIndexHex[5] = lime_byteToChar((uint8_t)((currentKey->sessionIndex>>8)&0x0F));
		sessionIndexHex[6] = lime_byteToChar((uint8_t)((currentKey->sessionIndex>>4)&0x0F));
		sessionIndexHex[7] = lime_byteToChar((uint8_t)((currentKey->sessionIndex)&0x0F));
		sessionIndexHex[8] = '\0';

		xmlNewTextChild(msgNode, NULL, (const xmlChar *)"pzid", peerZidHex);
		xmlNewTextChild(msgNode, NULL, (const xmlChar *)"index", sessionIndexHex);

		/* convert the cipherText to base 64 */
jehan's avatar
jehan committed
656
		bctbx_base64_encode(NULL, &b64Size, encryptedMessage, encryptedMessageLength); /* b64Size is 0, so it is set to the requested output buffer size */
Sylvain Berfini's avatar
Sylvain Berfini committed
657
		encryptedMessageb64 = ms_malloc(b64Size+1); /* allocate a buffer of requested size +1 for NULL termination */
jehan's avatar
jehan committed
658
		bctbx_base64_encode(encryptedMessageb64, &b64Size, encryptedMessage, encryptedMessageLength); /* b64Size is 0, so it is set to the requested output buffer size */
659 660
		encryptedMessageb64[b64Size] = '\0'; /* libxml need a null terminated string */
		xmlNewTextChild(msgNode, NULL, (const xmlChar *)"text", (const xmlChar *)encryptedMessageb64);
Sylvain Berfini's avatar
Sylvain Berfini committed
661 662
		ms_free(encryptedMessage);
		ms_free(encryptedMessageb64);
663

664 665
		/* add the message Node into the doc */
		xmlAddChild(rootNode, msgNode);
666

667 668 669 670 671 672
		/* update the key used */
		lime_deriveKey(currentKey);
		lime_setCachedKey(cacheBuffer, currentKey, LIME_SENDER);
	}

	/* dump the whole message doc into the output */
Sylvain Berfini's avatar
Sylvain Berfini committed
673 674 675 676 677
	xmlDocDumpFormatMemoryEnc(xmlOutputMessage, &local_output, &xmlStringLength, "UTF-8", 0);

	*output = (uint8_t *)ms_malloc(xmlStringLength + 1);
	memcpy(*output, local_output, xmlStringLength);
	(*output)[xmlStringLength] = '\0';
678

Sylvain Berfini's avatar
Sylvain Berfini committed
679 680
	xmlFree(local_output);
	xmlFreeDoc(xmlOutputMessage);
681
	lime_freeKeys(&associatedKeys);
682 683 684 685 686

	return 0;
}

int lime_decryptMultipartMessage(xmlDocPtr cacheBuffer, uint8_t *message, uint8_t **output) {
687
	int retval;
johan's avatar
johan committed
688 689 690 691 692 693
	uint8_t selfZidHex[25];
	uint8_t selfZid[12]; /* same data but in byte buffer */
	limeKey_t associatedKey;
	xmlChar *peerZidHex = NULL;
	xmlNodePtr cur;
	uint8_t *encryptedMessage = NULL;
johan's avatar
johan committed
694
	size_t encryptedMessageLength = 0;
johan's avatar
johan committed
695 696
	uint32_t usedSessionIndex = 0;
	xmlDocPtr xmlEncryptedMessage;
697 698 699 700

	if (cacheBuffer == NULL) {
		return LIME_INVALID_CACHE;
	}
701 702 703 704 705 706 707
	/* retrieve selfZIDHex from cache(return a 24 char hexa string + null termination) */
	if (lime_getSelfZid(cacheBuffer, selfZidHex) != 0) {
		return LIME_UNABLE_TO_DECRYPT_MESSAGE;
	}
	lime_strToUint8(selfZid, selfZidHex, 24);

	/* parse the message into an xml doc */
708
	/* make sure we have a valid xml message before trying to parse it */
Sylvain Berfini's avatar
Sylvain Berfini committed
709
	if (memcmp(message, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", 38) != 0) {
710 711
		return LIME_INVALID_ENCRYPTED_MESSAGE;
	}
johan's avatar
johan committed
712
	xmlEncryptedMessage = xmlParseDoc((const xmlChar *)message);
713 714 715
	if (xmlEncryptedMessage == NULL) {
		return LIME_INVALID_ENCRYPTED_MESSAGE;
	}
716 717

	/* retrieve the sender ZID which is the first child of root */
johan's avatar
johan committed
718
	cur = xmlDocGetRootElement(xmlEncryptedMessage);
719 720 721
	if (cur != NULL) {
		cur = cur->xmlChildrenNode;
		if ((!xmlStrcmp(cur->name, (const xmlChar *)"ZID"))){ /* sender ZID found, extract it */
722
			peerZidHex = xmlNodeListGetString(xmlEncryptedMessage, cur->xmlChildrenNode, 1);
723
			/* convert it from hexa string to bytes string and set the result in the associatedKey structure */
724
			lime_strToUint8(associatedKey.peerZID, peerZidHex, (uint16_t)strlen((char *)peerZidHex));
725 726 727 728 729 730
			cur = cur->next;
		}
	}

	if (peerZidHex != NULL) {
		/* get from cache the matching key */
731
		retval = lime_getCachedRcvKeyByZid(cacheBuffer, &associatedKey);
732

733 734 735 736 737
		if (retval != 0) {
			xmlFree(peerZidHex);
			xmlFreeDoc(xmlEncryptedMessage);
			return retval;
		}
738

739 740 741 742 743 744
		/* retrieve the portion of message which is encrypted with our key */
		while (cur != NULL) { /* loop on all "msg" node in the message */
			xmlNodePtr msgChildrenNode = cur->xmlChildrenNode;
			xmlChar *currentZidHex = xmlNodeListGetString(cacheBuffer, msgChildrenNode->xmlChildrenNode, 1); /* pZID is the first element of msg */
			if (!xmlStrcmp(currentZidHex, (const xmlChar *)selfZidHex)) { /* we found the msg node we are looking for */
				/* get the index (second node in the msg one) */
johan's avatar
johan committed
745 746 747
				xmlChar *sessionIndexHex;
				xmlChar *encryptedMessageb64;

748
				msgChildrenNode = msgChildrenNode->next;
johan's avatar
johan committed
749
				sessionIndexHex = xmlNodeListGetString(cacheBuffer, msgChildrenNode->xmlChildrenNode, 1);
750 751 752 753 754 755 756 757 758
				usedSessionIndex = (((uint32_t)lime_charToByte(sessionIndexHex[0]))<<28)
					| (((uint32_t)lime_charToByte(sessionIndexHex[1]))<<24)
					| (((uint32_t)lime_charToByte(sessionIndexHex[2]))<<20)
					| (((uint32_t)lime_charToByte(sessionIndexHex[3]))<<16)
					| (((uint32_t)lime_charToByte(sessionIndexHex[4]))<<12)
					| (((uint32_t)lime_charToByte(sessionIndexHex[5]))<<8)
					| (((uint32_t)lime_charToByte(sessionIndexHex[6]))<<4)
					| (((uint32_t)lime_charToByte(sessionIndexHex[7])));
				xmlFree(sessionIndexHex);
johan's avatar
johan committed
759

760 761
				/* get the encrypted message */
				msgChildrenNode = msgChildrenNode->next;
johan's avatar
johan committed
762

763
				/* convert the cipherText from base 64 */
johan's avatar
johan committed
764
				encryptedMessageb64 = xmlNodeListGetString(cacheBuffer, msgChildrenNode->xmlChildrenNode, 1);
jehan's avatar
jehan committed
765
				bctbx_base64_decode(NULL, &encryptedMessageLength, encryptedMessageb64, strlen((char *)encryptedMessageb64)); /* encryptedMessageLength is 0, so it will be set to the requested buffer length */
Sylvain Berfini's avatar
Sylvain Berfini committed
766
				encryptedMessage = (uint8_t *)ms_malloc(encryptedMessageLength);
jehan's avatar
jehan committed
767
				bctbx_base64_decode(encryptedMessage, &encryptedMessageLength, encryptedMessageb64, strlen((char *)encryptedMessageb64));
johan's avatar
johan committed
768

769
				xmlFree(encryptedMessageb64);
johan's avatar
johan committed
770 771
				xmlFree(currentZidHex);
				break;
772 773 774 775
			}

			cur = cur->next;
			xmlFree(currentZidHex);
776 777 778 779 780 781 782 783 784 785 786 787
			}
	}

	xmlFree(peerZidHex);
	xmlFreeDoc(xmlEncryptedMessage);

	/* do we have retrieved correctly all the needed data */
	if (encryptedMessage == NULL) {
		return LIME_UNABLE_TO_DECRYPT_MESSAGE;
	}

	/* shall we derive our key before going for decryption */
788 789
	if (usedSessionIndex < associatedKey.sessionIndex) {
		/* something wen't wrong with the cache, this shall never happend */
Sylvain Berfini's avatar
Sylvain Berfini committed
790
		ms_free(encryptedMessage);
791 792 793 794 795
		return LIME_UNABLE_TO_DECRYPT_MESSAGE;
	}

	if ((usedSessionIndex - associatedKey.sessionIndex > MAX_DERIVATION_NUMBER) ) {
		/* we missed to many messages, ask for a cache reset via a ZRTP call */
Sylvain Berfini's avatar
Sylvain Berfini committed
796
		ms_free(encryptedMessage);
797 798 799 800 801
		return LIME_UNABLE_TO_DECRYPT_MESSAGE;
	}

	while (usedSessionIndex>associatedKey.sessionIndex) {
		lime_deriveKey(&associatedKey);
802 803 804
	}

	/* decrypt the message */
Sylvain Berfini's avatar
Sylvain Berfini committed
805
	*output = (uint8_t *)ms_malloc(encryptedMessageLength - 16 +1); /* plain message is same length than encrypted one with 16 bytes less for the tag + 1 to add the null termination char */
Ghislain MARY's avatar
Ghislain MARY committed
806
	retval = lime_decryptMessage(&associatedKey, encryptedMessage, (uint32_t)encryptedMessageLength, selfZid, *output);
807

Sylvain Berfini's avatar
Sylvain Berfini committed
808
	ms_free(encryptedMessage);
809

Sylvain Berfini's avatar
Sylvain Berfini committed
810 811
	if (retval != 0) {
		ms_free(*output);
812 813 814 815
		*output = NULL;
		return LIME_UNABLE_TO_DECRYPT_MESSAGE;
	}

816 817 818 819 820 821
	/* update used key */
	lime_deriveKey(&associatedKey);
	lime_setCachedKey(cacheBuffer, &associatedKey, LIME_RECEIVER);

	return 0;
}
822

823 824 825 826
bool_t linphone_chat_room_lime_available(LinphoneChatRoom *cr) {
	if (cr) {
		switch (linphone_core_lime_enabled(cr->lc)) {
			case LinphoneLimeDisabled: return FALSE;
827
			case LinphoneLimeMandatory:
828 829 830 831 832 833 834
			case LinphoneLimePreferred: {
				FILE *CACHEFD = NULL;
				if (cr->lc->zrtp_secrets_cache != NULL) {
					CACHEFD = fopen(cr->lc->zrtp_secrets_cache, "rb+");
					if (CACHEFD) {
						size_t cacheSize;
						xmlDocPtr cacheXml;
Sylvain Berfini's avatar
Sylvain Berfini committed
835 836 837
						char *cacheString = ms_load_file_content(CACHEFD, &cacheSize);
						if (!cacheString) {
							ms_warning("Unable to load content of ZRTP ZID cache");
838 839 840 841 842 843 844 845 846 847
							return FALSE;
						}
						cacheString[cacheSize] = '\0';
						cacheSize += 1;
						fclose(CACHEFD);
						cacheXml = xmlParseDoc((xmlChar*)cacheString);
						ms_free(cacheString);
						if (cacheXml) {
							bool_t res;
							limeURIKeys_t associatedKeys;
Sylvain Berfini's avatar
Sylvain Berfini committed
848 849
							char *peer = linphone_address_as_string_uri_only(linphone_chat_room_get_peer_address(room));
							
850
							/* retrieve keys associated to the peer URI */
Sylvain Berfini's avatar
Sylvain Berfini committed
851 852
							associatedKeys.peerURI = (uint8_t *)malloc(strlen(peer)+1);
							strcpy((char *)(associatedKeys.peerURI), peer);
853 854 855 856 857 858
							associatedKeys.associatedZIDNumber  = 0;
							associatedKeys.peerKeys = NULL;

							res = (lime_getCachedSndKeysByURI(cacheXml, &associatedKeys) == 0 && associatedKeys.associatedZIDNumber != 0);
							lime_freeKeys(&associatedKeys);
							xmlFreeDoc(cacheXml);
Sylvain Berfini's avatar
Sylvain Berfini committed
859
							ms_free(peer);
860 861 862 863 864 865 866 867
							return res;
						}
					}
				}
			}
		}
	}
	return FALSE;
868 869
}

870 871
int lime_im_encryption_engine_process_incoming_message_cb(LinphoneImEncryptionEngine *engine, LinphoneChatRoom *room, LinphoneChatMessage *msg) {
	LinphoneCore *lc = linphone_im_encryption_engine_get_core(engine);
872 873
	int errcode = -1;
	/* check if we have a xml/cipher message to be decrypted */
874
	if (msg->content_type && (strcmp("xml/cipher", msg->content_type) == 0 || strcmp("application/cipher.vnd.gsma.rcs-ft-http+xml", msg->content_type) == 0)) {
875 876 877 878 879 880 881 882 883 884 885 886 887 888
		/* access the zrtp cache to get keys needed to decipher the message */
		FILE *CACHEFD = NULL;
		const char *zrtp_secrets_cache = linphone_core_get_zrtp_secrets_file(lc);
		errcode = 0;
		if (zrtp_secrets_cache != NULL) CACHEFD = fopen(zrtp_secrets_cache, "rb+");
		if (CACHEFD == NULL) {
			ms_warning("Unable to access ZRTP ZID cache to decrypt message");
			errcode = 500;
			return errcode;
		} else {
			size_t cacheSize;
			char *cacheString;
			int retval;
			xmlDocPtr cacheXml;
889
			uint8_t *decrypted_body = NULL;
890 891 892 893 894 895 896 897 898 899 900 901
			
			cacheString=ms_load_file_content(CACHEFD, &cacheSize);
			if (!cacheString){
				ms_warning("Unable to load content of ZRTP ZID cache to decrypt message");
				errcode = 500;
				return errcode;
			}
			cacheString[cacheSize] = '\0';
			cacheSize += 1;
			fclose(CACHEFD);
			cacheXml = xmlParseDoc((xmlChar*)cacheString);
			ms_free(cacheString);
902
			retval = lime_decryptMultipartMessage(cacheXml, (uint8_t *)msg->message, &decrypted_body);
903 904
			if (retval != 0) {
				ms_warning("Unable to decrypt message, reason : %s", lime_error_code_to_string(retval));
Sylvain Berfini's avatar
Sylvain Berfini committed
905
				if (decrypted_body) ms_free(decrypted_body);
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
				xmlFreeDoc(cacheXml);
				errcode = 488;
				return errcode;
			} else {
				/* dump updated cache to a string */
				xmlChar *xmlStringOutput;
				int xmlStringLength;
				xmlDocDumpFormatMemoryEnc(cacheXml, &xmlStringOutput, &xmlStringLength, "UTF-8", 0);
				/* write it to the cache file */
				CACHEFD = fopen(zrtp_secrets_cache, "wb+");
				if (fwrite(xmlStringOutput, 1, xmlStringLength, CACHEFD)<=0){
					ms_warning("Fail to write cache");
				}
				xmlFree(xmlStringOutput);
				fclose(CACHEFD);
921 922 923 924 925 926 927 928 929 930 931 932
				if (msg->message) {
					ms_free(msg->message);
				}
				msg->message = (char *)decrypted_body;
				
				if (strcmp("application/cipher.vnd.gsma.rcs-ft-http+xml", msg->content_type) == 0) {
					ms_free(msg->content_type);
					msg->content_type = ms_strdup("application/vnd.gsma.rcs-ft-http+xml");
				} else {
					ms_free(msg->content_type);
					msg->content_type = ms_strdup("text/plain");
				}
933 934 935 936 937 938 939 940
			}

			xmlFreeDoc(cacheXml);
		}
	}
	return errcode;
}

941 942
int lime_im_encryption_engine_process_outgoing_message_cb(LinphoneImEncryptionEngine *engine, LinphoneChatRoom *room, LinphoneChatMessage *msg) {
	LinphoneCore *lc = linphone_im_encryption_engine_get_core(engine);
943
	int errcode = -1;
944
	char *content_type = "xml/cipher";
945 946 947 948 949 950 951 952 953 954 955
	if(linphone_core_lime_enabled(room->lc)) {
		if (linphone_chat_room_lime_available(room)) {
			if (msg->content_type) {
				if (strcmp(msg->content_type, "application/vnd.gsma.rcs-ft-http+xml") == 0) {
					/* it's a file transfer, content type shall be set to
					application/cipher.vnd.gsma.rcs-ft-http+xml*/
					content_type = "application/cipher.vnd.gsma.rcs-ft-http+xml";
				} else if (strcmp(msg->content_type, "application/im-iscomposing+xml") == 0) {
					/* We don't encrypt composing messages */
					return errcode;
				}
956
			}
957
			msg->content_type = ms_strdup(content_type);
958 959
	
	
960 961 962 963 964 965
			/* access the zrtp cache to get keys needed to cipher the message */
			const char *zrtp_secrets_cache = linphone_core_get_zrtp_secrets_file(lc);
			FILE *CACHEFD = fopen(zrtp_secrets_cache, "rb+");
			errcode = 0;
			if (CACHEFD == NULL) {
				ms_warning("Unable to access ZRTP ZID cache to encrypt message");
966 967
				errcode = 488;
			} else {
968 969 970 971 972 973 974 975 976 977 978 979
				size_t cacheSize;
				char *cacheString;
				xmlDocPtr cacheXml;
				int retval;
				uint8_t *crypted_body = NULL;
				char *peer = linphone_address_as_string_uri_only(linphone_chat_room_get_peer_address(room));

				cacheString=ms_load_file_content(CACHEFD, &cacheSize);
				if (!cacheString){
					ms_warning("Unable to load content of ZRTP ZID cache to encrypt message");
					errcode = 500;
					return errcode;
980
				}
981 982
				cacheString[cacheSize] = '\0';
				cacheSize += 1;
983
				fclose(CACHEFD);
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
				cacheXml = xmlParseDoc((xmlChar*)cacheString);
				ms_free(cacheString);
				retval = lime_createMultipartMessage(cacheXml, (uint8_t *)msg->message, (uint8_t *)peer, &crypted_body);
				if (retval != 0) {
					ms_warning("Unable to encrypt message for %s : %s", peer, lime_error_code_to_string(retval));
					if (crypted_body) ms_free(crypted_body);
					errcode = 488;
				} else {
					/* dump updated cache to a string */
					xmlChar *xmlStringOutput;
					int xmlStringLength;
					xmlDocDumpFormatMemoryEnc(cacheXml, &xmlStringOutput, &xmlStringLength, "UTF-8", 0);
					/* write it to the cache file */
					CACHEFD = fopen(zrtp_secrets_cache, "wb+");
					if (fwrite(xmlStringOutput, 1, xmlStringLength, CACHEFD)<=0){
						ms_warning("Unable to write zid cache");
					}
					xmlFree(xmlStringOutput);
					fclose(CACHEFD);
					if (msg->message) {
						ms_free(msg->message);
					}
					msg->message = (char *)crypted_body;
1007
				}
1008 1009
				ms_free(peer);
				xmlFreeDoc(cacheXml);
1010
			}
1011 1012 1013
		} else {
			ms_warning("Unable to access ZRTP ZID cache to encrypt message");
			errcode = 488;
1014 1015 1016 1017
		}
	}
	return errcode;
}
johan's avatar
johan committed
1018

1019
int lime_im_encryption_engine_process_downloading_file_cb(LinphoneImEncryptionEngine *engine, LinphoneChatMessage *msg, const char *buffer, size_t size, char *decrypted_buffer) {
1020 1021 1022 1023 1024 1025 1026
	if (linphone_content_get_key(msg->file_transfer_information) == NULL) return -1;
	
	if (buffer == NULL || size == 0) {
		return lime_decryptFile(linphone_content_get_cryptoContext_address(msg->file_transfer_information), NULL, 0, NULL, NULL);
	}
	
	return lime_decryptFile(linphone_content_get_cryptoContext_address(msg->file_transfer_information),
1027
						 (unsigned char *)linphone_content_get_key(msg->file_transfer_information), size, decrypted_buffer,
1028 1029 1030
						 (char *)buffer);
}

1031
int lime_im_encryption_engine_process_uploading_file_cb(LinphoneImEncryptionEngine *engine, LinphoneChatMessage *msg, size_t offset, const char *buffer, size_t *size, char *encrypted_buffer) {
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
	if (linphone_content_get_key(msg->file_transfer_information) == NULL) return -1;
	
	if (buffer == NULL || *size == 0) {
		return lime_encryptFile(linphone_content_get_cryptoContext_address(msg->file_transfer_information), NULL, 0, NULL, NULL);
	}
	
	if (offset + *size < linphone_content_get_size(msg->file_transfer_information)) {
		*size -= (*size % 16);
	}
	
	return lime_encryptFile(linphone_content_get_cryptoContext_address(msg->file_transfer_information),
					(unsigned char *)linphone_content_get_key(msg->file_transfer_information), *size,
					(char *)buffer, encrypted_buffer);
}

1047 1048
bool_t lime_im_encryption_engine_is_file_encryption_enabled_cb(LinphoneImEncryptionEngine *engine, LinphoneChatRoom *room) {
	LinphoneCore *lc = linphone_im_encryption_engine_get_core(engine);
1049 1050 1051
	return linphone_chat_room_lime_available(room) && linphone_core_lime_for_file_sharing_enabled(lc);
}

1052
void lime_im_encryption_engine_generate_file_transfer_key_cb(LinphoneImEncryptionEngine *engine, LinphoneChatRoom *room, LinphoneChatMessage *msg) {
1053 1054 1055 1056 1057 1058 1059
	char keyBuffer [FILE_TRANSFER_KEY_SIZE]; /* temporary storage of generated key: 192 bits of key + 64 bits of initial vector */
	/* generate a random 192 bits key + 64 bits of initial vector and store it into the
		* file_transfer_information->key field of the msg */
	sal_get_random_bytes((unsigned char *)keyBuffer, FILE_TRANSFER_KEY_SIZE);
	linphone_content_set_key(msg->file_transfer_information, keyBuffer, FILE_TRANSFER_KEY_SIZE); /* key is duplicated in the content private structure */
}

johan's avatar
johan committed
1060 1061 1062 1063 1064 1065 1066
#else /* HAVE_LIME */

bool_t lime_is_available() { return FALSE; }
int lime_decryptFile(void **cryptoContext, unsigned char *key, size_t length, char *plain, char *cipher) { return LIME_NOT_ENABLED;}
int lime_decryptMultipartMessage(xmlDocPtr cacheBuffer, uint8_t *message, uint8_t **output) { return LIME_NOT_ENABLED;}
int lime_createMultipartMessage(xmlDocPtr cacheBuffer, uint8_t *message, uint8_t *peerURI, uint8_t **output) { return LIME_NOT_ENABLED;}
int lime_encryptFile(void **cryptoContext, unsigned char *key, size_t length, char *plain, char *cipher) {return LIME_NOT_ENABLED;}
1067
void lime_freeKeys(limeURIKeys_t *associatedKeys){
1068 1069 1070 1071
}
int lime_getCachedSndKeysByURI(xmlDocPtr cacheBuffer, limeURIKeys_t *associatedKeys){
	return LIME_NOT_ENABLED;
}
jehan's avatar
jehan committed
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
int lime_encryptMessage(limeKey_t *key, uint8_t *plainMessage, uint32_t messageLength, uint8_t selfZID[12], uint8_t *encryptedMessage) {
	return LIME_NOT_ENABLED;
}
int lime_setCachedKey(xmlDocPtr cacheBuffer, limeKey_t *associatedKey, uint8_t role) {
	return LIME_NOT_ENABLED;
}
int lime_getCachedRcvKeyByZid(xmlDocPtr cacheBuffer, limeKey_t *associatedKey) {
	return LIME_NOT_ENABLED;
}
int lime_decryptMessage(limeKey_t *key, uint8_t *encryptedMessage, uint32_t messageLength, uint8_t selfZID[12], uint8_t *plainMessage) {
	return LIME_NOT_ENABLED;
}
1084 1085 1086
bool_t linphone_chat_room_lime_available(LinphoneChatRoom *cr) {
	return FALSE;
}
1087
int lime_im_encryption_engine_process_incoming_message_cb(LinphoneImEncryptionEngine *engine, LinphoneChatRoom *room, LinphoneChatMessage *msg) {
1088 1089
	return 500;
}
1090
int lime_im_encryption_engine_process_outgoing_message_cb(LinphoneImEncryptionEngine *engine, LinphoneChatRoom *room, LinphoneChatMessage *msg) {
1091 1092
	return 500;
}
1093
int lime_im_encryption_engine_process_downloading_file_cb(LinphoneImEncryptionEngine *engine, LinphoneChatMessage *msg, const char *buffer, size_t size, char *decrypted_buffer) {
1094 1095
	return 500;
}
1096
int lime_im_encryption_engine_process_uploading_file_cb(LinphoneImEncryptionEngine *engine, LinphoneChatMessage *msg, size_t offset, const char *buffer, size_t *size, char *encrypted_buffer) {
Sylvain Berfini's avatar