sig.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /*
  2. *******************************************************************************
  3. \file sig.c
  4. \brief Sign files and verify signatures
  5. \project bee2/cmd
  6. \created 2022.08.01
  7. \version 2023.12.17
  8. \copyright The Bee2 authors
  9. \license Licensed under the Apache License, Version 2.0 (see LICENSE.txt).
  10. *******************************************************************************
  11. */
  12. #include "../cmd.h"
  13. #include <bee2/core/blob.h>
  14. #include <bee2/core/dec.h>
  15. #include <bee2/core/err.h>
  16. #include <bee2/core/mem.h>
  17. #include <bee2/core/hex.h>
  18. #include <bee2/core/prng.h>
  19. #include <bee2/core/str.h>
  20. #include <bee2/core/tm.h>
  21. #include <bee2/core/util.h>
  22. #include <bee2/crypto/belt.h>
  23. #include <bee2/crypto/bign.h>
  24. #include <stdio.h>
  25. /*
  26. *******************************************************************************
  27. Утилита sig
  28. Функционал:
  29. - выработка ЭЦП;
  30. - проверка ЭЦП;
  31. - печать ЭЦП.
  32. Пример (после примера в cvc.c):
  33. # внешняя подпись
  34. bee2cmd sig sign -certs "cert0 cert1 cert2" -pass pass:alice privkey2 \
  35. cert0 sig_file
  36. bee2cmd sig val -anchor cert0 cert0 sig_file
  37. bee2cmd sig val -pubkey pubkey2 cert0 sig_file
  38. bee2cmd sig print sig_file
  39. # встроенная подпись
  40. bee2cmd sig sign -certs "cert0 cert1 cert2" -date 230526 -pass pass:alice \
  41. privkey2 sig_file sig_file
  42. bee2cmd sig val -anchor cert0 sig_file sig_file
  43. bee2cmd sig val -pubkey pubkey2 sig_file sig_file
  44. bee2cmd sig print sig_file
  45. bee2cmd sig print -certc sig_file
  46. bee2cmd sig print -date sig_file
  47. # извлечение частей
  48. bee2cmd sig extr -body sig_file body
  49. bee2cmd sig extr -sig sig_file sig
  50. bee2cmd sig extr -body sig_file body
  51. bee2cmd sig extr -cert0 sig_file cert01
  52. *******************************************************************************
  53. */
  54. static const char _name[] = "sig";
  55. static const char _descr[] = "sign files and verify signatures";
  56. /*
  57. *******************************************************************************
  58. Справка по использованию
  59. *******************************************************************************
  60. */
  61. static int sigUsage()
  62. {
  63. printf(
  64. "bee2cmd/%s: %s\n"
  65. "Usage:\n"
  66. " sig sign [options] <privkey> <file> <sig>\n"
  67. " sign <file> using <privkey> and store the signature in <sig>\n"
  68. " sig val {-pubkey <pubkey>|-anchor <anchor>} <file> <sig>\n"
  69. " verify <sig> of <file> using either <pubkey> or <anchor>\n"
  70. " sig extr {-cert<n>|-body|-sig} <sig> <file>\n"
  71. " extract from <sig> an object and store it in <file>\n"
  72. " -cert<n> -- the <n>th attached certificate\n"
  73. " \\remark certificates are numbered from zero\n"
  74. " \\remark the signing certificate comes last\n"
  75. " -body -- the signed body\n"
  76. " -sig -- the signature itself\n"
  77. " sig print [field] <sig>\n"
  78. " print <sig> info: all fields or a specific field\n"
  79. " .\n"
  80. " <privkey>\n"
  81. " container with a private key\n"
  82. " <pubkey>\n"
  83. " file with a public key\n"
  84. " <anchor>\n"
  85. " file with a trusted sertificate\n"
  86. " options:\n"
  87. " -certs <certs> -- certificate chain (optional)\n"
  88. " -date <YYMMDD> -- date of signing (optional)\n"
  89. " -pass <schema> -- password description\n"
  90. " field:\n"
  91. " {-certc|-date|-sig}\n"
  92. " -certc -- the number of attached certificates\n"
  93. " -date -- date of signing\n"
  94. " -sig -- base signature\n"
  95. ,
  96. _name, _descr
  97. );
  98. return -1;
  99. }
  100. /*
  101. *******************************************************************************
  102. Самотестирование
  103. *******************************************************************************
  104. */
  105. static err_t sigSelfTest()
  106. {
  107. octet state[1024];
  108. bign_params params[1];
  109. octet privkey[32];
  110. octet pubkey[64];
  111. octet hash[32];
  112. const octet oid[] = {
  113. 0x06, 0x09, 0x2A, 0x70, 0x00, 0x02, 0x00, 0x22, 0x65, 0x1F, 0x51,
  114. };
  115. octet sig[48];
  116. // bign-genkeypair
  117. hexTo(privkey,
  118. "1F66B5B84B7339674533F0329C74F218"
  119. "34281FED0732429E0C79235FC273E269");
  120. ASSERT(sizeof(state) >= prngEcho_keep());
  121. prngEchoStart(state, privkey, 32);
  122. if (bignParamsStd(params, "1.2.112.0.2.0.34.101.45.3.1") != ERR_OK ||
  123. bignKeypairGen(privkey, pubkey, params, prngEchoStepR,
  124. state) != ERR_OK ||
  125. !hexEq(pubkey,
  126. "BD1A5650179D79E03FCEE49D4C2BD5DD"
  127. "F54CE46D0CF11E4FF87BF7A890857FD0"
  128. "7AC6A60361E8C8173491686D461B2826"
  129. "190C2EDA5909054A9AB84D2AB9D99A90"))
  130. return ERR_SELFTEST;
  131. // bign-valpubkey
  132. if (bignPubkeyVal(params, pubkey) != ERR_OK)
  133. return ERR_SELFTEST;
  134. // bign-sign
  135. if (beltHash(hash, beltH(), 13) != ERR_OK)
  136. return ERR_SELFTEST;
  137. if (bignSign2(sig, params, oid, sizeof(oid), hash, privkey,
  138. 0, 0) != ERR_OK)
  139. return ERR_SELFTEST;
  140. if (!hexEq(sig,
  141. "19D32B7E01E25BAE4A70EB6BCA42602C"
  142. "CA6A13944451BCC5D4C54CFD8737619C"
  143. "328B8A58FB9C68FD17D569F7D06495FB"))
  144. return ERR_SELFTEST;
  145. if (bignVerify(params, oid, sizeof(oid), hash, sig, pubkey) != ERR_OK)
  146. return ERR_SELFTEST;
  147. sig[0] ^= 1;
  148. if (bignVerify(params, oid, sizeof(oid), hash, sig, pubkey) == ERR_OK)
  149. return ERR_SELFTEST;
  150. // все нормально
  151. return ERR_OK;
  152. }
  153. /*
  154. *******************************************************************************
  155. Выработка подписи
  156. sig sign [-certs <certs>] [-date <YYMMDD>] -pass <schema> <file> <sig>
  157. *******************************************************************************
  158. */
  159. static err_t sigSign(int argc, char* argv[])
  160. {
  161. err_t code;
  162. const char* certs = 0;
  163. octet date[6];
  164. cmd_pwd_t pwd = 0;
  165. size_t privkey_len;
  166. octet* privkey;
  167. // самотестирование
  168. code = sigSelfTest();
  169. ERR_CALL_CHECK(code);
  170. // без даты по умолчанию
  171. memSetZero(date, 6);
  172. // разобрать опции
  173. while (argc && strStartsWith(*argv, "-"))
  174. {
  175. if (argc < 2)
  176. {
  177. code = ERR_CMD_PARAMS;
  178. break;
  179. }
  180. if (strStartsWith(*argv, "-certs"))
  181. {
  182. if (certs)
  183. {
  184. code = ERR_CMD_DUPLICATE;
  185. break;
  186. }
  187. ++argv, --argc;
  188. ASSERT(argc > 0);
  189. certs = *argv;
  190. ++argv, --argc;
  191. }
  192. else if (strStartsWith(*argv, "-date"))
  193. {
  194. if (!memIsZero(date, 6))
  195. {
  196. code = ERR_CMD_DUPLICATE;
  197. break;
  198. }
  199. --argc, ++argv;
  200. ASSERT(argc > 0);
  201. code = cmdDateParse(date, *argv);
  202. if (code != ERR_OK)
  203. break;
  204. --argc, ++argv;
  205. }
  206. else if (strStartsWith(*argv, "-pass"))
  207. {
  208. if (pwd)
  209. {
  210. code = ERR_CMD_DUPLICATE;
  211. break;
  212. }
  213. ++argv, --argc;
  214. ASSERT(argc > 0);
  215. code = cmdPwdRead(&pwd, *argv);
  216. if (code != ERR_OK)
  217. break;
  218. ASSERT(cmdPwdIsValid(pwd));
  219. ++argv, --argc;
  220. }
  221. else
  222. {
  223. code = ERR_CMD_PARAMS;
  224. break;
  225. }
  226. }
  227. if (code == ERR_OK && (!pwd || argc != 3))
  228. code = ERR_CMD_PARAMS;
  229. ERR_CALL_HANDLE(code, cmdPwdClose(pwd));
  230. // проверить наличие <privkey> и <file>
  231. code = cmdFileValExist(2, argv);
  232. ERR_CALL_HANDLE(code, cmdPwdClose(pwd));
  233. // получить разрешение на перезапись <sig>
  234. if (!cmdFileAreSame(argv[1], argv[2]))
  235. {
  236. code = cmdFileValNotExist(1, argv + 2);
  237. ERR_CALL_HANDLE(code, cmdPwdClose(pwd));
  238. }
  239. // прочитать личный ключ
  240. privkey_len = 0;
  241. code = cmdPrivkeyRead(0, &privkey_len, argv[0], pwd);
  242. ERR_CALL_HANDLE(code, cmdPwdClose(pwd));
  243. code = cmdBlobCreate(privkey, privkey_len);
  244. ERR_CALL_HANDLE(code, cmdPwdClose(pwd));
  245. code = cmdPrivkeyRead(privkey, 0, argv[0], pwd);
  246. cmdPwdClose(pwd);
  247. ERR_CALL_HANDLE(code, cmdBlobClose(privkey));
  248. // подписать
  249. code = cmdSigSign(argv[2], argv[1], certs, date, privkey, privkey_len);
  250. // завершить
  251. cmdBlobClose(privkey);
  252. return code;
  253. }
  254. /*
  255. *******************************************************************************
  256. Проверка подписи
  257. sig val {-pubkey <pubkey> | -anchor <anchor>} <file> <sig>
  258. *******************************************************************************
  259. */
  260. static err_t sigVal(int argc, char* argv[])
  261. {
  262. err_t code;
  263. size_t count;
  264. octet* stack;
  265. // самотестирование
  266. code = sigSelfTest();
  267. ERR_CALL_CHECK(code);
  268. // проверить опции
  269. if (argc != 4 ||
  270. !strEq(argv[0], "-pubkey") && !strEq(argv[0], "-anchor"))
  271. return ERR_CMD_PARAMS;
  272. // проверить наличие {<pubkey> | <anchor>} <file> <sig>
  273. code = cmdFileValExist(3, argv + 1);
  274. ERR_CALL_CHECK(code);
  275. // прочитать pubkey / anchor
  276. code = cmdFileReadAll(0, &count, argv[1]);
  277. ERR_CALL_CHECK(code);
  278. code = cmdBlobCreate(stack, count);
  279. ERR_CALL_CHECK(code);
  280. code = cmdFileReadAll(stack, &count, argv[1]);
  281. ERR_CALL_HANDLE(code, cmdBlobClose(stack));
  282. // проверить подпись
  283. if (strEq(argv[0], "-pubkey"))
  284. code = cmdSigVerify(argv[2], argv[3], stack, count);
  285. else
  286. code = cmdSigVerify2(argv[2], argv[3], stack, count);
  287. // завершить
  288. cmdBlobClose(stack);
  289. return code;
  290. }
  291. /*
  292. *******************************************************************************
  293. Извлечение из подписи объекта
  294. sig extr {-cert<n>|-body|-sig} <sig> <file>
  295. *******************************************************************************
  296. */
  297. static err_t sigExtr(int argc, char* argv[])
  298. {
  299. err_t code;
  300. const char* scope;
  301. // обработать опции
  302. if (argc != 3)
  303. return ERR_CMD_PARAMS;
  304. scope = argv[0];
  305. if (strLen(scope) < 1 || scope[0] != '-')
  306. return ERR_CMD_PARAMS;
  307. ++scope, --argc, ++argv;
  308. // проверить наличие/отсутствие файлов
  309. code = cmdFileValExist(1, argv);
  310. ERR_CALL_CHECK(code);
  311. code = cmdFileValNotExist(1, argv + 1);
  312. ERR_CALL_CHECK(code);
  313. // извлечь объект
  314. code = cmdSigExtr(argv[1], argv[0], scope);
  315. // завершить
  316. return code;
  317. }
  318. /*
  319. *******************************************************************************
  320. Печать подписи
  321. sig print [{-date|-certc|-cert<n>}] <sig>
  322. *******************************************************************************
  323. */
  324. static err_t sigPrint(int argc, char * argv[])
  325. {
  326. err_t code;
  327. const char* scope = 0;
  328. // обработать опции
  329. if (argc < 1 || argc > 2)
  330. return ERR_CMD_PARAMS;
  331. if (argc == 2)
  332. {
  333. scope = argv[0];
  334. if (strLen(scope) < 1 || scope[0] != '-')
  335. return ERR_CMD_PARAMS;
  336. ++scope, --argc, ++argv;
  337. }
  338. // проверить наличие файла подписи
  339. code = cmdFileValExist(1, argv);
  340. ERR_CALL_CHECK(code);
  341. // печатать подпись
  342. return cmdSigPrint(argv[0], scope);
  343. }
  344. /*
  345. *******************************************************************************
  346. Главная функция
  347. *******************************************************************************
  348. */
  349. static int sigMain(int argc, char* argv[])
  350. {
  351. err_t code;
  352. // справка
  353. if (argc < 2)
  354. return sigUsage();
  355. // разбор команды
  356. --argc, ++argv;
  357. if (strEq(argv[0], "sign"))
  358. code = sigSign(argc - 1, argv + 1);
  359. else if (strEq(argv[0], "val"))
  360. code = sigVal(argc - 1, argv + 1);
  361. else if (strEq(argv[0], "extr"))
  362. code = sigExtr(argc - 1, argv + 1);
  363. else if (strEq(argv[0], "print"))
  364. code = sigPrint(argc - 1, argv + 1);
  365. else
  366. code = ERR_CMD_NOT_FOUND;
  367. // завершить
  368. if (code != ERR_OK || strEq(argv[0], "val"))
  369. printf("bee2cmd/%s: %s\n", _name, errMsg(code));
  370. return code != ERR_OK ? -1 : 0;
  371. }
  372. err_t sigInit()
  373. {
  374. return cmdReg(_name, _descr, sigMain);
  375. }