px5g-mbedtls.c 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /*
  2. * px5g - Embedded x509 key and certificate generator based on PolarSSL
  3. *
  4. * Copyright (C) 2009 Steven Barth <[email protected]>
  5. * Copyright (C) 2014 Felix Fietkau <[email protected]>
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License, version 2.1 as published by the Free Software Foundation.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. * MA 02110-1301 USA
  20. */
  21. #include <sys/types.h>
  22. #include <sys/random.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <time.h>
  27. #include <limits.h>
  28. #include <unistd.h>
  29. #include <fcntl.h>
  30. #include <stdbool.h>
  31. #include <errno.h>
  32. #include <mbedtls/bignum.h>
  33. #include <mbedtls/entropy.h>
  34. #include <mbedtls/x509_crt.h>
  35. #include <mbedtls/ecp.h>
  36. #include <mbedtls/rsa.h>
  37. #include <mbedtls/pk.h>
  38. #define PX5G_VERSION "0.2"
  39. #define PX5G_COPY "Copyright (c) 2009 Steven Barth <[email protected]>"
  40. #define PX5G_LICENSE "Licensed under the GNU Lesser General Public License v2.1"
  41. static char buf[16384];
  42. static int _urandom(void *ctx, unsigned char *out, size_t len)
  43. {
  44. ssize_t ret;
  45. ret = getrandom(out, len, 0);
  46. if (ret < 0 || (size_t)ret != len)
  47. return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
  48. return 0;
  49. }
  50. static void write_file(const char *path, size_t len, bool pem, bool cert)
  51. {
  52. mode_t mode = S_IRUSR | S_IWUSR;
  53. const char *buf_start = buf;
  54. int fd = STDERR_FILENO;
  55. ssize_t written;
  56. int err;
  57. if (!pem)
  58. buf_start += sizeof(buf) - len;
  59. if (!len) {
  60. fprintf(stderr, "No data to write\n");
  61. exit(1);
  62. }
  63. if (cert)
  64. mode |= S_IRGRP | S_IROTH;
  65. if (path)
  66. fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
  67. if (fd < 0) {
  68. fprintf(stderr, "error: I/O error\n");
  69. exit(1);
  70. }
  71. written = write(fd, buf_start, len);
  72. if (written != len) {
  73. fprintf(stderr, "writing key failed with: %s\n", strerror(errno));
  74. exit(1);
  75. }
  76. err = fsync(fd);
  77. if (err < 0) {
  78. fprintf(stderr, "syncing key failed with: %s\n", strerror(errno));
  79. exit(1);
  80. }
  81. if (path)
  82. close(fd);
  83. }
  84. static mbedtls_ecp_group_id ecp_curve(const char *name)
  85. {
  86. const mbedtls_ecp_curve_info *curve_info;
  87. if (!strcmp(name, "P-256"))
  88. return MBEDTLS_ECP_DP_SECP256R1;
  89. else if (!strcmp(name, "P-384"))
  90. return MBEDTLS_ECP_DP_SECP384R1;
  91. else if (!strcmp(name, "P-521"))
  92. return MBEDTLS_ECP_DP_SECP521R1;
  93. curve_info = mbedtls_ecp_curve_info_from_name(name);
  94. if (curve_info == NULL)
  95. return MBEDTLS_ECP_DP_NONE;
  96. else
  97. return curve_info->grp_id;
  98. }
  99. static void write_key(mbedtls_pk_context *key, const char *path, bool pem)
  100. {
  101. int len = 0;
  102. if (pem) {
  103. if (mbedtls_pk_write_key_pem(key, (void *) buf, sizeof(buf)) == 0)
  104. len = strlen(buf);
  105. } else {
  106. len = mbedtls_pk_write_key_der(key, (void *) buf, sizeof(buf));
  107. if (len < 0)
  108. len = 0;
  109. }
  110. write_file(path, len, pem, false);
  111. }
  112. static void gen_key(mbedtls_pk_context *key, bool rsa, int ksize, int exp,
  113. mbedtls_ecp_group_id curve, bool pem)
  114. {
  115. mbedtls_pk_init(key);
  116. if (rsa) {
  117. fprintf(stderr, "Generating RSA private key, %i bit long modulus\n", ksize);
  118. mbedtls_pk_setup(key, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
  119. if (!mbedtls_rsa_gen_key(mbedtls_pk_rsa(*key), _urandom, NULL, ksize, exp))
  120. return;
  121. } else {
  122. fprintf(stderr, "Generating EC private key\n");
  123. mbedtls_pk_setup(key, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY));
  124. if (!mbedtls_ecp_gen_key(curve, mbedtls_pk_ec(*key), _urandom, NULL))
  125. return;
  126. }
  127. fprintf(stderr, "error: key generation failed\n");
  128. exit(1);
  129. }
  130. int dokey(bool rsa, char **arg)
  131. {
  132. mbedtls_pk_context key;
  133. unsigned int ksize = 512;
  134. int exp = 65537;
  135. char *path = NULL;
  136. bool pem = true;
  137. mbedtls_ecp_group_id curve = MBEDTLS_ECP_DP_SECP256R1;
  138. while (*arg && **arg == '-') {
  139. if (!strcmp(*arg, "-out") && arg[1]) {
  140. path = arg[1];
  141. arg++;
  142. } else if (!strcmp(*arg, "-3")) {
  143. exp = 3;
  144. } else if (!strcmp(*arg, "-der")) {
  145. pem = false;
  146. }
  147. arg++;
  148. }
  149. if (*arg && rsa) {
  150. ksize = (unsigned int)atoi(*arg);
  151. } else if (*arg) {
  152. curve = ecp_curve((const char *)*arg);
  153. if (curve == MBEDTLS_ECP_DP_NONE) {
  154. fprintf(stderr, "error: invalid curve name: %s\n", *arg);
  155. return 1;
  156. }
  157. }
  158. gen_key(&key, rsa, ksize, exp, curve, pem);
  159. write_key(&key, path, pem);
  160. mbedtls_pk_free(&key);
  161. return 0;
  162. }
  163. int selfsigned(char **arg)
  164. {
  165. mbedtls_pk_context key;
  166. mbedtls_x509write_cert cert;
  167. mbedtls_mpi serial;
  168. char *subject = "";
  169. unsigned int ksize = 512;
  170. int exp = 65537;
  171. unsigned int days = 30;
  172. char *keypath = NULL, *certpath = NULL;
  173. bool pem = true;
  174. time_t from = time(NULL), to;
  175. char fstr[20], tstr[20], sstr[17];
  176. int len;
  177. bool rsa = true;
  178. mbedtls_ecp_group_id curve = MBEDTLS_ECP_DP_SECP256R1;
  179. while (*arg && **arg == '-') {
  180. if (!strcmp(*arg, "-der")) {
  181. pem = false;
  182. } else if (!strcmp(*arg, "-newkey") && arg[1]) {
  183. if (!strncmp(arg[1], "rsa:", 4)) {
  184. rsa = true;
  185. ksize = (unsigned int)atoi(arg[1] + 4);
  186. } else if (!strcmp(arg[1], "ec")) {
  187. rsa = false;
  188. } else {
  189. fprintf(stderr, "error: invalid algorithm\n");
  190. return 1;
  191. }
  192. arg++;
  193. } else if (!strcmp(*arg, "-days") && arg[1]) {
  194. days = (unsigned int)atoi(arg[1]);
  195. arg++;
  196. } else if (!strcmp(*arg, "-pkeyopt") && arg[1]) {
  197. if (strncmp(arg[1], "ec_paramgen_curve:", 18)) {
  198. fprintf(stderr, "error: invalid pkey option: %s\n", arg[1]);
  199. return 1;
  200. }
  201. curve = ecp_curve((const char *)(arg[1] + 18));
  202. if (curve == MBEDTLS_ECP_DP_NONE) {
  203. fprintf(stderr, "error: invalid curve name: %s\n", arg[1] + 18);
  204. return 1;
  205. }
  206. arg++;
  207. } else if (!strcmp(*arg, "-keyout") && arg[1]) {
  208. keypath = arg[1];
  209. arg++;
  210. } else if (!strcmp(*arg, "-out") && arg[1]) {
  211. certpath = arg[1];
  212. arg++;
  213. } else if (!strcmp(*arg, "-subj") && arg[1]) {
  214. if (arg[1][0] != '/' || strchr(arg[1], ';')) {
  215. fprintf(stderr, "error: invalid subject");
  216. return 1;
  217. }
  218. subject = calloc(strlen(arg[1]) + 1, 1);
  219. char *oldc = arg[1] + 1, *newc = subject, *delim;
  220. do {
  221. delim = strchr(oldc, '=');
  222. if (!delim) {
  223. fprintf(stderr, "error: invalid subject");
  224. return 1;
  225. }
  226. memcpy(newc, oldc, delim - oldc + 1);
  227. newc += delim - oldc + 1;
  228. oldc = delim + 1;
  229. delim = strchr(oldc, '/');
  230. if (!delim) {
  231. delim = arg[1] + strlen(arg[1]);
  232. }
  233. memcpy(newc, oldc, delim - oldc);
  234. newc += delim - oldc;
  235. *newc++ = ',';
  236. oldc = delim + 1;
  237. } while(*delim);
  238. arg++;
  239. }
  240. arg++;
  241. }
  242. gen_key(&key, rsa, ksize, exp, curve, pem);
  243. if (keypath)
  244. write_key(&key, keypath, pem);
  245. from = (from < 1000000000) ? 1000000000 : from;
  246. strftime(fstr, sizeof(fstr), "%Y%m%d%H%M%S", gmtime(&from));
  247. to = from + 60 * 60 * 24 * days;
  248. if (to < from)
  249. to = INT_MAX;
  250. strftime(tstr, sizeof(tstr), "%Y%m%d%H%M%S", gmtime(&to));
  251. fprintf(stderr, "Generating selfsigned certificate with subject '%s'"
  252. " and validity %s-%s\n", subject, fstr, tstr);
  253. mbedtls_x509write_crt_init(&cert);
  254. mbedtls_x509write_crt_set_md_alg(&cert, MBEDTLS_MD_SHA256);
  255. mbedtls_x509write_crt_set_issuer_key(&cert, &key);
  256. mbedtls_x509write_crt_set_subject_key(&cert, &key);
  257. mbedtls_x509write_crt_set_subject_name(&cert, subject);
  258. mbedtls_x509write_crt_set_issuer_name(&cert, subject);
  259. mbedtls_x509write_crt_set_validity(&cert, fstr, tstr);
  260. mbedtls_x509write_crt_set_basic_constraints(&cert, 0, -1);
  261. mbedtls_x509write_crt_set_subject_key_identifier(&cert);
  262. mbedtls_x509write_crt_set_authority_key_identifier(&cert);
  263. _urandom(NULL, (void *) buf, 8);
  264. for (len = 0; len < 8; len++)
  265. sprintf(sstr + len*2, "%02x", (unsigned char) buf[len]);
  266. mbedtls_mpi_init(&serial);
  267. mbedtls_mpi_read_string(&serial, 16, sstr);
  268. mbedtls_x509write_crt_set_serial(&cert, &serial);
  269. if (pem) {
  270. if (mbedtls_x509write_crt_pem(&cert, (void *) buf, sizeof(buf), _urandom, NULL) < 0) {
  271. fprintf(stderr, "Failed to generate certificate\n");
  272. return 1;
  273. }
  274. len = strlen(buf);
  275. } else {
  276. len = mbedtls_x509write_crt_der(&cert, (void *) buf, sizeof(buf), _urandom, NULL);
  277. if (len < 0) {
  278. fprintf(stderr, "Failed to generate certificate: %d\n", len);
  279. return 1;
  280. }
  281. }
  282. write_file(certpath, len, pem, true);
  283. mbedtls_x509write_crt_free(&cert);
  284. mbedtls_mpi_free(&serial);
  285. mbedtls_pk_free(&key);
  286. return 0;
  287. }
  288. int main(int argc, char *argv[])
  289. {
  290. if (!argv[1]) {
  291. //Usage
  292. } else if (!strcmp(argv[1], "eckey")) {
  293. return dokey(false, argv+2);
  294. } else if (!strcmp(argv[1], "rsakey")) {
  295. return dokey(true, argv+2);
  296. } else if (!strcmp(argv[1], "selfsigned")) {
  297. return selfsigned(argv+2);
  298. }
  299. fprintf(stderr,
  300. "PX5G X.509 Certificate Generator Utility v" PX5G_VERSION "\n" PX5G_COPY
  301. "\nbased on PolarSSL by Christophe Devine and Paul Bakker\n\n");
  302. fprintf(stderr, "Usage: %s [eckey|rsakey|selfsigned]\n", *argv);
  303. return 1;
  304. }