1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 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 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 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 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
|
/*
* Copyright (c) 2024 Gergo Ferenc Kovacs
* Copyright (c) 2019 Airbus Commercial Aircraft
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* As an additional exemption you are allowed to compile & link against the
* OpenSSL libraries as published by the OpenSSL project. See the file
* COPYING for details.
*
*/
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <openssl/cmac.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
#include <openssl/params.h>
#endif
#include "messages.h"
#include "slog.h"
// Argument indicators for command line utilities
#define LONG_OPT_INDICATOR "--"
#define SHORT_OPT_INDICATOR "-"
// This initialization only works with GCC.
static unsigned char KEYPATTERN[AES_BLOCKSIZE] = { [0 ... (AES_BLOCKSIZE-1) ] = IPAD };
static unsigned char MACPATTERN[AES_BLOCKSIZE] = { [0 ... (AES_BLOCKSIZE-1) ] = OPAD };
static unsigned char GAMMA[AES_BLOCKSIZE] = { [0 ... (AES_BLOCKSIZE-1) ] = EPAD};
/*
* Conditional msg_error output.
*
* 1. Parameter: error variable (input)
* 2. Parameter: main error string to output (input)
*/
void cond_msg_error(GError *myError, char *errorMsg)
{
if (myError==NULL)
{
msg_error(errorMsg);
}
else
{
msg_error(errorMsg, evt_tag_str("error", myError->message));
}
}
/*
* Create specific sub-keys for encryption and CMAC generation from key.
*
* 1. Parameter: (main) key (input)
* 2. Parameter: encryption key (output)
* 3. Parameter: (C)MAC key (output)
*
* Note: encKey and MACKey must have space to hold KEY_LENGTH many bytes.
*/
void deriveSubKeys(unsigned char *mainKey, unsigned char *encKey, unsigned char *MACKey)
{
deriveEncSubKey(mainKey, encKey);
deriveMACSubKey(mainKey, MACKey);
}
void deriveEncSubKey(unsigned char *mainKey, unsigned char *encKey)
{
PRF(mainKey, KEYPATTERN, sizeof(KEYPATTERN), encKey, KEY_LENGTH);
}
void deriveMACSubKey(unsigned char *mainKey, unsigned char *MACKey)
{
PRF(mainKey, MACPATTERN, sizeof(MACPATTERN), MACKey, KEY_LENGTH);
}
/*
* AES256-GCM encryption
*
* Encrypts plaintext
*
* 1. Parameter: pointer to plaintext (input)
* 2. Parameter: length of plaintext (input)
* 3. Parameter: pointer to key (input)
* 4. Parameter: pointer to IV (input, nonce of length IV_LENGTH)
* 5. Parameter: pointer to ciphertext (output)
* 6. Parameter: pointer to tag (output)
*
* Note: caller must take care of memory management.
*
* Return:
* Length of ciphertext (>0)
* 0 on error
*/
int sLogEncrypt(unsigned char *plaintext, int plaintext_len,
unsigned char *key, unsigned char *iv,
unsigned char *ciphertext, unsigned char *tag)
{
/*
* This function is largely borrowed from
*
* https://wiki.openssl.org/index.php/EVP_Authenticated_Encryption_and_Decryption#Authenticated_Encryption_using_GCM_mode
*
*/
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new()))
{
msg_error("[SLOG] ERROR: Unable to initialize OpenSSL context");
return 0;
}
/* Initialise the encryption operation. */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
{
msg_error("[SLOG] ERROR: Unable to initialize OpenSSL context");
return 0;
}
if (IV_LENGTH!=12)
{
/* Set IV length if default 12 bytes (96 bits) is not appropriate */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, IV_LENGTH, NULL))
{
msg_error("[SLOG] ERROR: Unable to set IV length");
return 0;
}
}
/* Initialise key and IV */
if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
{
msg_error("[SLOG] ERROR: Unable to initialize encryption key and IV");
return 0;
}
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
{
msg_error("[SLOG] ERROR: Unable to encrypt data");
return 0;
}
ciphertext_len = len;
/* Finalise the encryption. Normally ciphertext bytes may be written at
* this stage, but this does not occur in GCM mode
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
{
msg_error("[SLOG] ERROR: Unable to complete encryption of data");
return 0;
}
ciphertext_len += len;
/* Get the tag */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, AES_BLOCKSIZE, tag))
{
msg_error("[SLOG] ERROR: Unable to acquire encryption tag");
return 0;
}
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
/*
* Decrypt ciphertext and verify integrity
*
* 1. Parameter: Pointer to ciphertext (input)
* 2. Parameter: Ciphertext length (input)
* 3. Parameter: Pointer to integrity tag (input)
* 4. Parameter: Pointer to IV (input)
* 5. Parameter: Pointer to plaintext (output)
*
* Note: Caller must take care of memory management.
*
* Return:
* >0 success
* -1 in case verification fails
* 0 on error
*/
int sLogDecrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *tag, unsigned char *key,
unsigned char *iv,
unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
int ret;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new()))
{
msg_error("[SLOG] ERROR: Unable to initialize OpenSSL context");
return 0;
}
/* Initialise the decryption operation. */
if(!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
{
msg_error("[SLOG] ERROR: Unable initiate decryption operation");
return 0;
}
if(IV_LENGTH!=12)
{
/* Set IV length. Not necessary if this is 12 bytes (96 bits) */
if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, IV_LENGTH, NULL))
{
msg_error("[SLOG] ERROR: Unable set IV length");
return 0;
}
}
/* Initialise key and IV */
if(!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv))
{
msg_error("[SLOG] ERROR: Unable to initialize key and IV");
return 0;
}
/* Provide the message to be decrypted, and obtain the plaintext output.
* EVP_DecryptUpdate can be called multiple times if necessary
*/
if(!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
{
msg_error("Unable to decrypt");
return 0;
}
plaintext_len = len;
/* Set expected tag value. Works in OpenSSL 1.0.1d and later */
if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, AES_BLOCKSIZE, tag))
{
msg_error("[SLOG] ERROR: Unable set tag value");
return 0;
}
/* Finalise the decryption. A positive return value indicates success,
* anything else is a failure - the plaintext is not trustworthy.
*/
ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
if(ret > 0)
{
/* Success */
plaintext_len += len;
return plaintext_len;
}
else
{
/* Verify failed */
return -1;
}
}
/*
* Create new forward-secure log entry
*
* This function creates a new encrypted log entry updates the corresponding MAC accordingly
*
* 1. Parameter: Number of log entries (for enumerating the entries in the log file)
* 2. Parameter: The original log message
* 3. Parameter: The current key
* 4. Parameter: The current MAC
* 5. Parameter: The resulting encrypted log entry
* 6. Parameter: The newly updated MAC
* 7. Parameter: The capacity of the newly updated MAC buffer
*/
void sLogEntry(guint64 numberOfLogEntries, GString *text, unsigned char *mainKey, unsigned char *inputBigMac,
GString *output, unsigned char *outputBigMac, gsize outputBigMac_capacity)
{
unsigned char encKey[KEY_LENGTH];
unsigned char MACKey[KEY_LENGTH];
deriveSubKeys(mainKey, encKey, MACKey);
// Compute current log entry number
gchar *counterString = convertToBase64((unsigned char *)&numberOfLogEntries, sizeof(numberOfLogEntries));
int slen = (int) text->len;
// This buffer holds everything: AggregatedMAC, IV, Tag, and CText
// Binary data cannot be larger than its base64 encoding
unsigned char bigBuf[AES_BLOCKSIZE+IV_LENGTH+AES_BLOCKSIZE+slen];
// This is where are ciphertext related data starts
unsigned char *ctBuf = &bigBuf[AES_BLOCKSIZE];
unsigned char *iv = ctBuf;
unsigned char *tag = &bigBuf[AES_BLOCKSIZE+IV_LENGTH];
unsigned char *ciphertext = &bigBuf[AES_BLOCKSIZE+IV_LENGTH+AES_BLOCKSIZE];
// Generate random nonce
if (RAND_bytes(iv, IV_LENGTH)==1)
{
// Encrypt log data
int ct_length = sLogEncrypt((guchar *)text->str, slen, encKey, iv, ciphertext, tag);
if(ct_length <= 0)
{
msg_error("[SLOG] ERROR: Unable to correctly encrypt log message");
g_string_printf(output, "%*.*s:%s: %s", COUNTER_LENGTH, COUNTER_LENGTH, counterString,
"[SLOG] ERROR: Unable to correctly encrypt the following log message:", text->str);
g_free(counterString);
return;
}
// Write current log entry number
g_string_printf (output, "%*.*s:", COUNTER_LENGTH, COUNTER_LENGTH, counterString);
g_free(counterString);
// Write IV, tag, and ciphertext at once
gchar *encodedCtBuf = convertToBase64(ctBuf, IV_LENGTH+AES_BLOCKSIZE+ct_length);
g_string_append(output, encodedCtBuf);
g_free(encodedCtBuf);
// Compute aggregated MAC
// Not the first aggregated MAC
if (numberOfLogEntries>0)
{
memcpy(bigBuf, inputBigMac, AES_BLOCKSIZE);
gsize outlen;
cmac(MACKey, bigBuf, AES_BLOCKSIZE+IV_LENGTH+AES_BLOCKSIZE+ct_length, outputBigMac, &outlen, outputBigMac_capacity);
}
else // First aggregated MAC
{
gsize outlen = 0;
cmac(MACKey, &bigBuf[AES_BLOCKSIZE], IV_LENGTH+AES_BLOCKSIZE+ct_length, outputBigMac, &outlen, outputBigMac_capacity);
}
}
else
{
// We did not get enough random bytes
msg_error("[SLOG] ERROR: Could not obtain enough random bytes");
g_string_printf(output, "%*.*s:%s: %s", COUNTER_LENGTH, COUNTER_LENGTH, counterString,
"[SLOG] ERROR: Could not obtain enough random bytes for the following log message:", text->str);
g_free(counterString);
return;
}
}
/*
* Evolve key multiple times
*
* 1. Parameter: Pointer to destination key (output)
* 2. Parameter: Number of times current key should be evolved (input)
* 3. Parameter: Pointer to current key (input)
*
* Note: Caller must take care of memory management.
*
*/
void deriveKey(unsigned char *dst, guint64 index, guint64 currentKey)
{
for (guint64 i = currentKey; i<index; i++)
{
evolveKey(dst);
}
}
guchar *convertToBin(char *input, gsize *outLen)
{
return g_base64_decode ((const gchar *) input, outLen);
}
gchar *convertToBase64(unsigned char *input, gsize len)
{
return g_base64_encode ((const guchar *) input, len);
}
/*
* Compute AES256 CMAC of input
*
* 1. Parameter: Pointer to key (input)
* 2. Parameter: Pointer to input (input)
* 3. Parameter: Input length (input)
* 4. Parameter: Pointer to output (output)
* 5. Parameter: Length of output (output)
* 6. Parameter: Capacity of output buffer (input)
*
* Note: caller must take care of memory management.
*
* If Parameter 5 == 0, there was an error.
*
*/
void cmac(unsigned char *key, const void *input, gsize length, unsigned char *out, gsize *outlen, gsize out_capacity)
{
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
EVP_MAC *mac = EVP_MAC_fetch(NULL, "CMAC", NULL);
OSSL_PARAM params[] =
{
OSSL_PARAM_utf8_string("cipher", "aes-256-cbc", 0),
OSSL_PARAM_END,
};
EVP_MAC_CTX *ctx = EVP_MAC_CTX_new(mac);
EVP_MAC_init(ctx, key, KEY_LENGTH, params);
EVP_MAC_update(ctx, input, length);
size_t out_len;
EVP_MAC_final(ctx, out, &out_len, out_capacity);
EVP_MAC_CTX_free(ctx);
EVP_MAC_free(mac);
#else
CMAC_CTX *ctx = CMAC_CTX_new();
CMAC_Init(ctx, key, KEY_LENGTH, EVP_aes_256_cbc(), NULL);
CMAC_Update(ctx, input, length);
size_t out_len;
CMAC_Final(ctx, out, &out_len);
*outlen = out_len;
CMAC_CTX_free(ctx);
#endif
}
/*
* Evolve key
*
* 1. Parameter: Pointer to key (input/output)
*
*/
void evolveKey(unsigned char *key)
{
unsigned char buf[KEY_LENGTH];
PRF(key, GAMMA, sizeof(GAMMA), buf, KEY_LENGTH);
memcpy(key, buf, KEY_LENGTH);
}
/*
* AES-CMAC based pseudo-random function (with variable input length and output length)
*
* 1. Parameter: Pointer to key (input)
* 2. Parameter: Pointer to input (input)
* 3. Parameter: Length of input (input)
* 4. Parameter: Pointer to output (output)
* 5. Parameter: Required output length (input)
*
* Note: For security, outputLength must be less than 255 * AES_BLOCKSIZE.
*
*/
void PRF(unsigned char *key, unsigned char *originalInput, guint64 inputLength, unsigned char *output,
guint64 outputLength)
{
unsigned char input[inputLength];
memcpy(input, originalInput, inputLength);
// Make sure that temporary buffer can hold at least outputLength bytes, rounded up to a multiple of AES_BLOCKSIZE
unsigned char buf[outputLength+AES_BLOCKSIZE];
gsize buf_capacity = G_N_ELEMENTS(buf);
// Prepare plaintext
for (int i=0; i<outputLength/AES_BLOCKSIZE; i++)
{
gsize outlen;
cmac(key, input, AES_BLOCKSIZE, buf + (i*AES_BLOCKSIZE), &outlen, buf_capacity - (i*AES_BLOCKSIZE));
input[inputLength-1]++;
}
if (outputLength % AES_BLOCKSIZE!=0)
{
int index = outputLength/AES_BLOCKSIZE;
gsize outlen;
cmac(key, input, AES_BLOCKSIZE, buf + (index*AES_BLOCKSIZE), &outlen, buf_capacity - (index*AES_BLOCKSIZE));
}
memcpy(output, buf, outputLength);
}
/*
* Generate a master key
*
* This unique master key requires 32 bytes of storage.
* The caller has to allocate this memory.
*
* Return:
* 1 on success
* 0 on error
*/
int generateMasterKey(guchar *masterkey)
{
return RAND_bytes(masterkey, KEY_LENGTH);
}
/*
* Generate a host key based on a previously created master key
*
* 1. Parameter: master key
* 2. Parameter: Host MAC address
* 3. Parameter: Host S/N
*
* The specific unique host key k_0 is k_0 = H(master key|| MAC address || S/N)
* and requires 48 bytes of storage. Additional 8 bytes need to be allocated to store
* the serial number of the host key. The caller has to allocate this memory.
*
* Return:
* 1 on success
* 0 on error
*/
int deriveHostKey(guchar *masterkey, gchar *macAddr, gchar *serial, guchar *hostkey)
{
EVP_MD_CTX *ctx;
if((ctx = EVP_MD_CTX_create()) == NULL)
return 0;
if(1 != EVP_DigestInit_ex(ctx, EVP_sha256(), NULL))
return 0;
if(1 != EVP_DigestUpdate(ctx, masterkey, KEY_LENGTH))
return 0;
if(1 != EVP_DigestUpdate(ctx, macAddr, strlen(macAddr)))
return 0;
if(1 != EVP_DigestUpdate(ctx, serial, strlen(serial)))
return 0;
if(KEY_LENGTH != SHA256_DIGEST_LENGTH)
{
msg_error("[SLOG] ERROR: Error in updating digest");
g_assert_not_reached();
return 0;
}
guint digest_len = KEY_LENGTH;
if(1 != EVP_DigestFinal_ex(ctx, hostkey, &digest_len))
return 0;
EVP_MD_CTX_destroy(ctx);
return 1;
}
/*
* Write whole log MAC to file
*
* Return:
* 1 on success
* 0 on error
*/
int writeBigMAC(gchar *filename, char *outputBuffer)
{
GError *error = NULL;
GIOChannel *macfile = g_io_channel_new_file(filename, "w+", &error);
if(!macfile)
{
msg_error("[SLOG] ERROR: Unable open MAC file",
evt_tag_str("base_dir", filename));
cond_msg_error(error, "Additional Information");
g_clear_error(&error);
return 0;
}
GIOStatus status = g_io_channel_set_encoding(macfile, NULL, &error);
if(status != G_IO_STATUS_NORMAL)
{
msg_error("[SLOG] ERROR: Unable to set encoding for MAC data",
evt_tag_str("File", filename));
cond_msg_error(error, "Additional information");
g_clear_error(&error);
g_io_channel_shutdown(macfile, TRUE, &error);
g_io_channel_unref(macfile);
g_clear_error(&error);
return 0;
}
gsize outlen = 0;
status = g_io_channel_write_chars(macfile, outputBuffer, CMAC_LENGTH, &outlen, &error);
if(status != G_IO_STATUS_NORMAL)
{
msg_error("[SLOG] ERROR: Unable to write big MAC data",
evt_tag_str("File", filename));
cond_msg_error(error, "Additional information");
g_clear_error(&error);
g_io_channel_shutdown(macfile, TRUE, &error);
g_io_channel_unref(macfile);
g_clear_error(&error);
return 0;
}
// Compute aggregated MAC
gchar outputmacdata[CMAC_LENGTH];
gsize outputmacdata_capacity = G_N_ELEMENTS(outputmacdata);
unsigned char keyBuffer[KEY_LENGTH];
bzero(keyBuffer, KEY_LENGTH);
unsigned char zeroBuffer[CMAC_LENGTH];
bzero(zeroBuffer, CMAC_LENGTH);
memcpy(keyBuffer, outputBuffer, MIN(CMAC_LENGTH, KEY_LENGTH));
cmac(keyBuffer, zeroBuffer, CMAC_LENGTH, (guchar *)outputmacdata, &outlen, outputmacdata_capacity);
status = g_io_channel_write_chars(macfile, outputmacdata, CMAC_LENGTH, &outlen, &error);
if(status != G_IO_STATUS_NORMAL)
{
msg_error("[SLOG] ERROR: Unable to write aggregated MAC",
evt_tag_str("File", filename));
cond_msg_error(error, "Additional information");
g_clear_error(&error);
g_io_channel_shutdown(macfile, TRUE, &error);
g_io_channel_unref(macfile);
g_clear_error(&error);
return 0;
}
status = g_io_channel_shutdown(macfile, TRUE, &error);
g_io_channel_unref(macfile);
if(status != G_IO_STATUS_NORMAL)
{
cond_msg_error(error, "[SLOG] ERROR: Cannot close aggregated MAC");
g_clear_error(&error);
}
return 1;
}
/*
* Read whole log MAC from file
*
* Return:
* 1 on success
* 0 on error
*/
int readBigMAC(gchar *filename, char *outputBuffer)
{
GError *myError = NULL;
GIOChannel *macfile = g_io_channel_new_file(filename, "r", &myError);
if(!macfile)
{
// MAC file does not exist -> New MAC file will be created
g_clear_error(&myError);
return 0;
}
GIOStatus status = g_io_channel_set_encoding(macfile, NULL, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error(myError, "[SLOG] ERROR: Cannot set encoding of MAC file");
g_clear_error(&myError);
g_io_channel_shutdown(macfile, TRUE, &myError);
g_io_channel_unref(macfile);
g_clear_error(&myError);
return 0;
}
gchar macdata[2*CMAC_LENGTH];
gsize mac_bytes_read = 0;
status = g_io_channel_read_chars(macfile, macdata, 2*CMAC_LENGTH, &mac_bytes_read, &myError);
if(status != G_IO_STATUS_NORMAL)
{
cond_msg_error(myError, "[SLOG] ERROR: Cannot read MAC file");
g_clear_error(&myError);
g_io_channel_shutdown(macfile, TRUE, &myError);
g_io_channel_unref(macfile);
g_clear_error(&myError);
return 0;
}
status = g_io_channel_shutdown(macfile, TRUE, &myError);
g_io_channel_unref(macfile);
if(status != G_IO_STATUS_NORMAL)
{
msg_error("[SLOG] ERROR: Cannot close MAC file");
g_clear_error(&myError);
return 0;
}
if (mac_bytes_read!=2*CMAC_LENGTH)
{
msg_error("[SLOG] ERROR: $(slog) parsing failed, invalid size of MAC file");
return 0;
}
gsize outlen = 0;
unsigned char keyBuffer[KEY_LENGTH];
bzero(keyBuffer, KEY_LENGTH);
unsigned char zeroBuffer[CMAC_LENGTH];
bzero(zeroBuffer, CMAC_LENGTH);
memcpy(keyBuffer, macdata, MIN(CMAC_LENGTH, KEY_LENGTH));
unsigned char testOutput[CMAC_LENGTH];
gsize testOutput_capacity = G_N_ELEMENTS(testOutput);
cmac(keyBuffer, zeroBuffer, CMAC_LENGTH, testOutput, &outlen, testOutput_capacity);
if (0 != memcmp(testOutput, &macdata[CMAC_LENGTH], CMAC_LENGTH))
{
msg_warning("[SLOG] ERROR: MAC computation invalid");
return 0;
}
else
{
msg_info("[SLOG] INFO: MAC successfully loaded");
}
memcpy(outputBuffer, macdata, CMAC_LENGTH);
return 1;
}
/*
* Read key from file
*
* Return:
* 1 on success
* 0 on error
*/
int readKey(char *destKey, guint64 *destCounter, gchar *keypath)
{
GError *myError = NULL;
GIOChannel *keyfile = g_io_channel_new_file(keypath, "r", &myError);
if (!keyfile)
{
cond_msg_error(myError, "[SLOG] ERROR: Key file not found");
g_clear_error(&myError);
return 0;
}
GIOStatus status = g_io_channel_set_encoding(keyfile, NULL, &myError);
if(status != G_IO_STATUS_NORMAL)
{
cond_msg_error(myError, "[SLOG] ERROR: Unable to set encoding for key file");
g_clear_error(&myError);
g_io_channel_shutdown(keyfile, TRUE, &myError);
g_io_channel_unref(keyfile);
g_clear_error(&myError);
return 0;
}
// Key file contains
// 1. the number of log entries already logged (and therewith the index of the key); this is at the end of the key file
// 2. the actual 32 byte key, this is at the beginning of the key file
// 3. a 16 byte CMAC of the two previous data, this is stored after the key
gchar keydata[KEY_LENGTH + CMAC_LENGTH];
gsize key_bytes_read = 0;
status = g_io_channel_read_chars(keyfile, keydata, KEY_LENGTH + CMAC_LENGTH, &key_bytes_read, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error(myError, "[SLOG] ERROR: Cannot read from key file");
g_clear_error(&myError);
g_io_channel_shutdown(keyfile, TRUE, &myError);
g_io_channel_unref(keyfile);
g_clear_error(&myError);
return 0;
}
if (key_bytes_read!=KEY_LENGTH+CMAC_LENGTH)
{
msg_error("[SLOG] ERROR: Invalid key file. Missing CMAC");
status = g_io_channel_shutdown(keyfile, TRUE, &myError);
g_io_channel_unref(keyfile);
g_clear_error(&myError);
return 0;
}
guint64 littleEndianCounter;
status = g_io_channel_read_chars(keyfile, (gchar *) &littleEndianCounter, sizeof(littleEndianCounter), &key_bytes_read,
&myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error(myError, "[SLOG] ERROR: Cannot read counter from key file");
g_clear_error(&myError);
g_io_channel_shutdown(keyfile, TRUE, &myError);
g_io_channel_unref(keyfile);
g_clear_error(&myError);
return 0;
}
status = g_io_channel_shutdown(keyfile, TRUE, &myError);
g_io_channel_unref(keyfile);
g_clear_error(&myError);
if (key_bytes_read!=sizeof(littleEndianCounter))
{
msg_error("[SLOG] ERROR: $(slog) parsing failed, key file invalid while reading counter");
return 0;
}
gsize outlen=0;
unsigned char testOutput[CMAC_LENGTH];
gsize testOutputCapacity = G_N_ELEMENTS(testOutput);
cmac((guchar *)keydata, &(littleEndianCounter), sizeof(littleEndianCounter), testOutput, &outlen, testOutputCapacity);
if (0!=memcmp(testOutput, &keydata[KEY_LENGTH], CMAC_LENGTH))
{
msg_warning("[SLOG] ERROR: Host key corrupted. CMAC in key file not matching");
return 0;
}
memcpy(destKey, keydata, KEY_LENGTH);
*destCounter = GUINT64_FROM_LE(littleEndianCounter);
return 1;
}
/*
* Write key to file
*
* Return:
* 1 on success
* 0 on error
*/
int writeKey(char *key, guint64 counter, gchar *keypath)
{
GError *error = NULL;
GIOChannel *keyfile = g_io_channel_new_file(keypath, "w+", &error);
if(!keyfile)
{
cond_msg_error(error, "[SLOG] ERROR: Cannot open key file");
g_clear_error(&error);
return 0;
}
GIOStatus status = g_io_channel_set_encoding(keyfile, NULL, &error);
if(status != G_IO_STATUS_NORMAL)
{
cond_msg_error(error, "[SLOG] ERROR: Unable to set encoding for key file");
g_clear_error(&error);
g_io_channel_shutdown(keyfile, TRUE, &error);
g_io_channel_unref(keyfile);
g_clear_error(&error);
return 0;
}
gsize outlen = 0;
// Write key
status = g_io_channel_write_chars(keyfile, key, KEY_LENGTH, &outlen, &error);
if(status != G_IO_STATUS_NORMAL)
{
cond_msg_error(error, "[SLOG] ERROR: Unable to write updated key");
g_clear_error(&error);
g_io_channel_shutdown(keyfile, TRUE, &error);
g_io_channel_unref(keyfile);
g_clear_error(&error);
return 0;
}
guint64 littleEndianCounter = GINT64_TO_LE(counter);
gchar outputmacdata[CMAC_LENGTH];
gsize outputmacdata_capacity = G_N_ELEMENTS(outputmacdata);
cmac((guchar *)key, &littleEndianCounter, sizeof(littleEndianCounter), (guchar *)outputmacdata, &outlen,
outputmacdata_capacity);
// Write CMAC
status = g_io_channel_write_chars(keyfile, outputmacdata, CMAC_LENGTH, &outlen, &error);
if(status != G_IO_STATUS_NORMAL)
{
cond_msg_error(error, "[SLOG] ERROR: Unable to write key CMAC");
g_clear_error(&error);
g_io_channel_shutdown(keyfile, TRUE, &error);
g_io_channel_unref(keyfile);
g_clear_error(&error);
return 0;
}
// Write counter
status = g_io_channel_write_chars(keyfile, (gchar *) &littleEndianCounter, sizeof(littleEndianCounter), &outlen,
&error);
if(status != G_IO_STATUS_NORMAL)
{
cond_msg_error(error, "[SLOG] ERROR: Unable to write key counter");
g_clear_error(&error);
g_io_channel_shutdown(keyfile, TRUE, &error);
g_io_channel_unref(keyfile);
g_clear_error(&error);
return 0;
}
status = g_io_channel_shutdown(keyfile, TRUE, &error);
g_io_channel_unref(keyfile);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error(error, "[SLOG] ERROR: Cannot close key file");
g_clear_error(&error);
return 0;
}
return 1;
}
int iterateBuffer(guint64 entriesInBuffer, GString **input, guint64 *nextLogEntry, unsigned char *mainKey,
unsigned char *keyZero, guint keyNumber, GString **output, guint64 *numberOfLogEntries, unsigned char *cmac_tag,
gsize cmac_tag_capacity, GHashTable *tab)
{
int ret = 1;
for (guint64 i=0; i<entriesInBuffer; i++)
{
output[i] = g_string_new(NULL);
guint64 len = input[i]->len;
if (len > (COUNTER_LENGTH + 1))
{
// Interpret the first COUNTER_LENGTH+1 characters
char ctrbuf[COUNTER_LENGTH+1];
memcpy(ctrbuf, input[i]->str, COUNTER_LENGTH);
ctrbuf[COUNTER_LENGTH] = 0;
gsize outLen;
guchar *tmp = convertToBin(ctrbuf, &outLen);
guint64 logEntryOnDisk;
if (outLen!=sizeof(guint64))
{
msg_error("[SLOG] ERROR: Cannot derive integer value from counter field", evt_tag_long("Log entry number",
*nextLogEntry));
logEntryOnDisk = *nextLogEntry;
g_free(tmp);
}
else
{
memcpy(&logEntryOnDisk, tmp, sizeof(logEntryOnDisk));
g_free(tmp);
}
len = len - (COUNTER_LENGTH+1);
if (logEntryOnDisk != *nextLogEntry)
{
if (tab != NULL)
{
char key[CTR_LEN_SIMPLE+1];
snprintf(key, CTR_LEN_SIMPLE+1, "%"G_GUINT64_FORMAT, logEntryOnDisk);
if(g_hash_table_contains(tab, key) == TRUE)
{
msg_error("[SLOG] ERROR: Duplicate entry detected", evt_tag_long("entry", logEntryOnDisk));
ret = 0;
}
}
if (logEntryOnDisk<(*nextLogEntry))
{
if (logEntryOnDisk<keyNumber)
{
msg_error("[SLOG] ERROR: Log claims to be past entry from past archive. We cannot rewind back to this key without key0. This is going to fail.",
evt_tag_long("entry", logEntryOnDisk));
ret = 0;
}
else
{
msg_error("[SLOG] ERROR: Log claims to be past entry. We rewind from first known key, this might take some time",
evt_tag_long("entry", logEntryOnDisk));
// Rewind key to k0
memcpy(mainKey, keyZero, KEY_LENGTH);
deriveKey(mainKey, logEntryOnDisk, keyNumber);
*nextLogEntry = logEntryOnDisk;
ret = 0;
}
}
if (logEntryOnDisk-(*nextLogEntry)>1000000)
{
msg_info("[SLOG] INFO: Deriving key for distant future. This might take some time.",
evt_tag_long("next log entry should be", *nextLogEntry), evt_tag_long("key to derive to", logEntryOnDisk),
evt_tag_long("number of log entries", *numberOfLogEntries));
}
deriveKey(mainKey, logEntryOnDisk, *nextLogEntry);
*nextLogEntry = logEntryOnDisk;
}
GString *line = input[i];
char *ct = &(line->str)[COUNTER_LENGTH+1];
gsize outputLength;
// binBuf = IV + TAG + CT
guchar *binBuf = convertToBin(ct, &outputLength);
int pt_length = 0;
// Check whether something weird has happened during conversion
if (outputLength>IV_LENGTH+AES_BLOCKSIZE)
{
unsigned char pt[outputLength - IV_LENGTH - AES_BLOCKSIZE];
unsigned char encKey[KEY_LENGTH];
deriveEncSubKey(mainKey, encKey);
pt_length = sLogDecrypt(&binBuf[IV_LENGTH+AES_BLOCKSIZE], outputLength - IV_LENGTH - AES_BLOCKSIZE, &binBuf[IV_LENGTH],
encKey, binBuf, pt);
if (pt_length>0)
{
// Include colon, whitespace, and \0
g_string_append_printf(output[i], "%0*"G_GINT64_MODIFIER"x: %.*s", CTR_LEN_SIMPLE, logEntryOnDisk, pt_length, pt);
if (tab != NULL)
{
char *key = g_new0(char, CTR_LEN_SIMPLE+1);
snprintf(key, CTR_LEN_SIMPLE+1, "%"G_GUINT64_FORMAT, logEntryOnDisk);
if (g_hash_table_insert(tab, key, (gpointer)logEntryOnDisk) == FALSE)
{
msg_warning("[SLOG] WARNING: Unable to process hash table while entering decrypted log entry", evt_tag_long("entry",
logEntryOnDisk));
ret = 0;
}
}
// Update BigHMAC
if ((*numberOfLogEntries) == 0UL) // First aggregated MAC
{
gsize outlen = 0;
unsigned char MACKey[KEY_LENGTH];
deriveMACSubKey(mainKey, MACKey);
cmac(MACKey, binBuf, IV_LENGTH+AES_BLOCKSIZE+pt_length, cmac_tag, &outlen, cmac_tag_capacity);
}
else
{
// numberOfEntries > 0
gsize outlen;
unsigned char bigBuf[AES_BLOCKSIZE+IV_LENGTH+AES_BLOCKSIZE+pt_length];
memcpy(bigBuf, cmac_tag, AES_BLOCKSIZE);
memcpy(&bigBuf[AES_BLOCKSIZE], binBuf, IV_LENGTH+AES_BLOCKSIZE+pt_length);
unsigned char MACKey[KEY_LENGTH];
deriveMACSubKey(mainKey, MACKey);
cmac(MACKey, bigBuf, AES_BLOCKSIZE+IV_LENGTH+AES_BLOCKSIZE+pt_length, cmac_tag, &outlen, cmac_tag_capacity);
}
}
}
if (pt_length<=0)
{
msg_warning("[SLOG] WARNING: Decryption not successful",
evt_tag_long("entry", logEntryOnDisk));
ret = 0;
}
g_free(binBuf);
evolveKey(mainKey);
(*numberOfLogEntries)++;
(*nextLogEntry)++;
}
else
{
msg_error("[SLOG] ERROR: Cannot read log entry", evt_tag_long("", *nextLogEntry));
ret = 0;
}
} // for
return ret;
}
// Perform the final verification step
int finalizeVerify(guint64 startingEntry, guint64 entriesInFile, unsigned char *bigMac, unsigned char *cmac_tag,
GHashTable *tab)
{
int ret = 1;
// Check which entries are missing
guint64 notRecovered = 0;
for (guint64 i = startingEntry; i < startingEntry + entriesInFile; i++)
{
if (tab != NULL)
{
// Hashtable key
char key[CTR_LEN_SIMPLE+1];
snprintf(key, CTR_LEN_SIMPLE+1, "%"G_GUINT64_FORMAT, i);
if(g_hash_table_contains(tab, key) == FALSE)
{
notRecovered++;
msg_warning("[SLOG] WARNING: Unable to recover", evt_tag_long("entry", i));
ret = 0;
}
}
}
if ((notRecovered == 0) && (tab != NULL))
{
msg_info("[SLOG] INFO: All entries recovered successfully");
}
int equal = memcmp(bigMac, cmac_tag, CMAC_LENGTH);
if (equal != 0)
{
msg_warning("[SLOG] WARNING: Aggregated MAC mismatch. Log might be incomplete");
ret = 0;
}
else
{
msg_info("[SLOG] Aggregated MAC matches. Log contains all expected log messages.");
}
g_hash_table_unref(tab);
return ret;
}
// Initialize log verification
int initVerify(guint64 entriesInFile, unsigned char *mainKey, guint64 *nextLogEntry, guint64 *startingEntry,
GString **input, GHashTable **tab)
{
// Create hash table
*tab = g_hash_table_new(g_str_hash, g_str_equal);
if (*tab == NULL)
{
msg_error("[SLOG] ERROR: Cannot create hash table");
return 0;
}
if (input[0]->len>(COUNTER_LENGTH+1))
{
gsize outLen;
char buf[COUNTER_LENGTH+1];
memcpy(buf, input[0]->str, COUNTER_LENGTH);
buf[COUNTER_LENGTH] = 0;
guchar *tempInt = convertToBin(buf, &outLen);
if (outLen!=sizeof(guint64))
{
msg_warning("[SLOG] WARNING: Cannot derive integer value from first input line counter");
(*startingEntry) = 0UL;
g_free(tempInt);
return 0;
}
else
{
memcpy(startingEntry, tempInt, sizeof(guint64));
g_free(tempInt);
}
if((*startingEntry) > 0)
{
msg_warning("[SLOG] WARNING: Log does not start with index 0",
evt_tag_long("index", (*startingEntry)));
(*nextLogEntry) = (*startingEntry);
deriveKey(mainKey, (*nextLogEntry), 0);
return 0;
}
}
else
{
msg_warning("[SLOG] WARNING: Problems reading log entry at first line.");
return 0;
}
return 1;
}
/*
* Iteratively verify the integrity of an existing log file
*
* Return:
* 1 on success
* 0 on error
*/
int iterativeFileVerify(unsigned char *previousMAC, unsigned char *mainKey, char *inputFileName, unsigned char *bigMAC,
char *outputFileName, guint64 entriesInFile, int chunkLength, guint64 keyNumber)
{
if(entriesInFile==0)
{
msg_error("[SLOG] ERROR: Nothing to verify");
return 0;
}
unsigned char keyZero[KEY_LENGTH];
memcpy(keyZero, mainKey, KEY_LENGTH);
int startedWithZero = 0;
if (keyNumber!=0)
{
msg_info("[SLOG] INFO: Verification using a key different from k0", evt_tag_long("key number", keyNumber));
}
else
{
msg_info("[SLOG] INFO: Verification starting with k0. Is this really what you want?");
startedWithZero = 1;
}
int ret = 1;
GError *myError = NULL;
GIOChannel *input = g_io_channel_new_file(inputFileName, "r", &myError);
if (!input)
{
cond_msg_error (myError, "[SLOG] ERROR: Cannot open input file");
g_clear_error(&myError);
return 0;
}
GIOStatus status = g_io_channel_set_encoding(input, NULL, &myError);
if(status != G_IO_STATUS_NORMAL)
{
cond_msg_error (myError, "[SLOG] ERROR: set encoding for input file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
return 0;
}
GIOChannel *output = g_io_channel_new_file(outputFileName, "w+", &myError);
if (!output)
{
cond_msg_error(myError, "[SLOG] ERROR: Cannot open output file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
return 0;
}
status = g_io_channel_set_encoding(output, NULL, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error(myError, "[SLOG] ERROR: Cannot set output file encoding");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
return 0;
}
GString **inputBuffer = g_new0(GString *, chunkLength);
GString **outputBuffer = g_new0(GString *, chunkLength);
if ((outputBuffer==NULL)||(inputBuffer == NULL))
{
msg_error("[SLOG] ERROR: [iterativeFileVerify] cannot allocate memory");
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
unsigned char cmac_tag[CMAC_LENGTH];
gsize cmac_tag_capacity = G_N_ELEMENTS(cmac_tag);
memcpy(cmac_tag, previousMAC, CMAC_LENGTH);
guint64 nextLogEntry = keyNumber;
guint64 startingEntry = keyNumber;
guint64 numberOfLogEntries = keyNumber;
// This is only to avoid updating BigMAC during the first iteration
if (keyNumber == 0)
{
numberOfLogEntries = 1;
}
if (chunkLength>entriesInFile)
{
chunkLength = entriesInFile;
}
// Create the hash table
GHashTable *tab = g_hash_table_new(g_str_hash, g_str_equal);
if (tab == NULL)
{
msg_error("[SLOG] ERROR: Cannot create hash table");
return 0;
}
// Process file in chunks
for (int j = 0; j < (entriesInFile / chunkLength); j++)
{
for (guint64 i = 0; i < chunkLength; i++)
{
inputBuffer[i] = g_string_new(NULL);
status = g_io_channel_read_line_string(input, inputBuffer[i], NULL, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error(myError, "[SLOG] ERROR: reading from input file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
// Cut last character to remove the trailing new line...
g_string_truncate(inputBuffer[i], (inputBuffer[i]->len) - 1);
}
ret = ret * iterateBuffer(chunkLength, inputBuffer, &nextLogEntry, mainKey, keyZero, keyNumber, outputBuffer,
&numberOfLogEntries, cmac_tag, cmac_tag_capacity, tab);
// ...and write to file
for (guint64 i = 0; i < chunkLength; i++)
{
if (outputBuffer[i]->len!=0)
{
gsize size;
//Add newline
g_string_append(outputBuffer[i], "\n");
status = g_io_channel_write_chars(output, (outputBuffer[i])->str, (outputBuffer[i])->len, &size, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error(myError, "[SLOG] ERROR: writing to output file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
}
g_string_free(outputBuffer[i], TRUE);
g_string_free(inputBuffer[i], TRUE);
}
}
if ((entriesInFile % chunkLength) > 0)
{
for (guint64 i = 0; i < (entriesInFile % chunkLength); i++)
{
inputBuffer[i] = g_string_new(NULL);
status = g_io_channel_read_line_string(input, inputBuffer[i], NULL, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error(myError, "[SLOG] ERROR: reading from input file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
// Cut last character to remove the trailing new line
g_string_truncate(inputBuffer[i], (inputBuffer[i]->len) - 1);
}
ret = ret * iterateBuffer((entriesInFile % chunkLength), inputBuffer, &nextLogEntry, mainKey, keyZero, keyNumber,
outputBuffer, &numberOfLogEntries, cmac_tag, cmac_tag_capacity, tab);
for (guint64 i = 0; i < (entriesInFile % chunkLength); i++)
{
if (outputBuffer[i]->len!=0)
{
gsize size;
//Add newline
g_string_append(outputBuffer[i], "\n");
status = g_io_channel_write_chars(output, (outputBuffer[i])->str, (outputBuffer[i])->len, &size, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error(myError, "[SLOG] ERROR: writing to output file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
}
g_string_free(outputBuffer[i], TRUE);
g_string_free(inputBuffer[i], TRUE);
}
}
if (startedWithZero==1)
{
msg_info("[SLOG] INFO: We started with key key0. There might be a lot of warnings about missing log entries.");
}
ret = ret * finalizeVerify(startingEntry, entriesInFile, bigMAC, cmac_tag, tab);
g_free(inputBuffer);
g_free(outputBuffer);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
return ret;
}
/*
* Verify the integrity of an existing log file
*
* Return:
* 1 on success
* 0 on error
*/
int fileVerify(unsigned char *mainKey, char *inputFileName, char *outputFileName, unsigned char *bigMac,
guint64 entriesInFile, int chunkLength)
{
unsigned char keyZero[KEY_LENGTH];
memcpy(keyZero, mainKey, KEY_LENGTH);
GHashTable *tab = NULL;
int ret = 1;
if(entriesInFile==0)
{
msg_error("[SLOG] ERROR: Nothing to verify");
return 0;
}
GError *myError = NULL;
GIOChannel *input = g_io_channel_new_file(inputFileName, "r", &myError);
if (!input)
{
cond_msg_error (myError, "[SLOG] ERROR: Cannot open input file");
g_clear_error(&myError);
return 0;
}
GIOStatus status = g_io_channel_set_encoding(input, NULL, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error (myError, "[SLOG] ERROR: Cannot set input file encoding");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
return 0;
}
GIOChannel *output = g_io_channel_new_file(outputFileName, "w+", &myError);
if (!output)
{
cond_msg_error (myError, "[SLOG] ERROR: Cannot open output file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
return 0;
}
status = g_io_channel_set_encoding(output, NULL, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error (myError, "[SLOG] ERROR: Cannot set output file encoding");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
return 0;
}
GString **inputBuffer = g_new0(GString *, chunkLength);
GString **outputBuffer = g_new0(GString *, chunkLength);
if ((outputBuffer==NULL)||(inputBuffer == NULL))
{
msg_error("[SLOG] ERROR: [fileVerify] cannot allocate memory");
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
return 0;
}
guint64 nextLogEntry = 0UL;
guint64 startingEntry = 0UL;
unsigned char cmac_tag[CMAC_LENGTH];
gsize cmac_tag_capacity = G_N_ELEMENTS(cmac_tag);
guint64 numberOfLogEntries = 0UL;
if (chunkLength>entriesInFile)
{
chunkLength = entriesInFile;
}
for (guint64 i = 0; i < chunkLength; i++)
{
inputBuffer[i] = g_string_new(NULL);
status = g_io_channel_read_line_string(input, inputBuffer[i], NULL, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error (myError, "[SLOG] ERROR: Cannot read from input file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
// Cut last character to remove the trailing new line
g_string_truncate(inputBuffer[i], (inputBuffer[i]->len) - 1);
}
ret = ret * initVerify(entriesInFile, mainKey, &nextLogEntry, &startingEntry, inputBuffer, &tab);
ret = ret * iterateBuffer(chunkLength, inputBuffer, &nextLogEntry, mainKey, keyZero, 0, outputBuffer,
&numberOfLogEntries, cmac_tag, cmac_tag_capacity, tab);
// Write to file
for (guint64 i = 0; i < chunkLength; i++)
{
if (outputBuffer[i]->len!=0)
{
gsize size;
//Add newline
g_string_append(outputBuffer[i], "\n");
status = g_io_channel_write_chars(output, (outputBuffer[i])->str, (outputBuffer[i])->len, &size, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error (myError, "[SLOG] ERROR: writing to output file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
}
g_string_free(outputBuffer[i], TRUE);
g_string_free(inputBuffer[i], TRUE);
}
// Process file in chunks
for (int j = 0; j<(entriesInFile/chunkLength)-1; j++)
{
for (guint64 i = 0; i < chunkLength; i++)
{
inputBuffer[i] = g_string_new(NULL);
status = g_io_channel_read_line_string(input, inputBuffer[i], NULL, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error (myError, "[SLOG] ERROR: Cannot read from input file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
// Cut last character to remove the trailing new line...
g_string_truncate(inputBuffer[i], (inputBuffer[i]->len) - 1);
}
ret = ret * iterateBuffer(chunkLength, inputBuffer, &nextLogEntry, mainKey, keyZero, 0, outputBuffer,
&numberOfLogEntries, cmac_tag, cmac_tag_capacity, tab);
// ...and write to file
for (guint64 i = 0; i < chunkLength; i++)
{
if (outputBuffer[i]->len!=0)
{
gsize size;
//Add newline
g_string_append(outputBuffer[i], "\n");
status = g_io_channel_write_chars(output, (outputBuffer[i])->str, (outputBuffer[i])->len, &size, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error (myError, "[SLOG] ERROR: writing to output file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
}
g_string_free(outputBuffer[i], TRUE);
g_string_free(inputBuffer[i], TRUE);
}
}
if ((entriesInFile % chunkLength) > 0)
{
for (guint64 i = 0; i < (entriesInFile % chunkLength); i++)
{
inputBuffer[i] = g_string_new(NULL);
status = g_io_channel_read_line_string(input, inputBuffer[i], NULL, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error (myError, "[SLOG] ERROR: Cannot read from input file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
// Cut last character to remove the trailing new line
g_string_truncate(inputBuffer[i], (inputBuffer[i]->len) - 1);
}
ret = ret * iterateBuffer((entriesInFile % chunkLength), inputBuffer, &nextLogEntry, mainKey, keyZero, 0, outputBuffer,
&numberOfLogEntries, cmac_tag, cmac_tag_capacity, tab);
for (guint64 i = 0; i < (entriesInFile % chunkLength); i++)
{
if (outputBuffer[i]->len!=0)
{
gsize size;
//Add newline
g_string_append(outputBuffer[i], "\n");
status = g_io_channel_write_chars(output, (outputBuffer[i])->str, (outputBuffer[i])->len, &size, &myError);
if (status != G_IO_STATUS_NORMAL)
{
cond_msg_error (myError, "[SLOG] ERROR: Cannot write to output file");
g_clear_error(&myError);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
g_free(inputBuffer);
g_free(outputBuffer);
return 0;
}
}
g_string_free(outputBuffer[i], TRUE);
g_string_free(inputBuffer[i], TRUE);
}
}
ret = ret * finalizeVerify(startingEntry, entriesInFile, bigMac, cmac_tag, tab);
g_free(inputBuffer);
g_free(outputBuffer);
g_io_channel_shutdown(input, TRUE, &myError);
g_io_channel_unref(input);
g_clear_error(&myError);
g_io_channel_shutdown(output, TRUE, &myError);
g_io_channel_unref(output);
g_clear_error(&myError);
return ret;
}
// Print usage message and clean up
int slog_usage(GOptionContext *ctx, GOptionGroup *grp, GString *errormsg)
{
if(errormsg != NULL)
{
g_print ("\nERROR: %s\n\n", errormsg->str);
g_string_free(errormsg, TRUE);
}
g_print("%s", g_option_context_get_help(ctx, TRUE, NULL));
g_option_context_free(ctx);
return 1;
}
/*
* Callback function to check whether a command line argument represents a valid file name
*
* Return:
* TRUE on success
* FALSE on error
*/
gboolean validFileNameArg(const gchar *option_name, const gchar *value, gpointer data, GError **error)
{
gboolean isValid = FALSE;
GString *currentOption = g_string_new(option_name);
GString *currentValue = g_string_new(value);
GString *longOption = g_string_new(LONG_OPT_INDICATOR);
GString *shortOption = g_string_new(SHORT_OPT_INDICATOR);
SLogOptions *opts = (SLogOptions *)data;
for(SLogOptions *option = opts; option != NULL && option->longname != NULL; option++)
{
g_string_append(longOption, option->longname);
g_string_append_c(shortOption, option->shortname);
if(g_string_equal(currentOption, longOption) || g_string_equal(currentOption, shortOption))
{
if(g_file_test(value, G_FILE_TEST_IS_REGULAR))
{
option->arg = currentValue->str;
isValid = TRUE;
break;
}
}
// Reset for next option argument to check
g_string_assign(longOption, LONG_OPT_INDICATOR);
g_string_assign(shortOption, SHORT_OPT_INDICATOR);
}
if (!isValid)
{
*error = g_error_new(G_FILE_ERROR, G_OPTION_ERROR_FAILED, "Invalid path or non existing regular file: %s", value);
}
g_string_free(currentOption, TRUE);
g_string_free(currentValue, FALSE);
g_string_free(longOption, TRUE);
g_string_free(shortOption, TRUE);
return isValid;
}
|