openssl-certgen.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. // Copyright (C) 2014 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <openssl/err.h>
  15. #include <openssl/evp.h>
  16. #include <openssl/pem.h>
  17. #include <openssl/x509.h>
  18. #include <openssl/x509v3.h>
  19. #include <cstring>
  20. #include <iostream>
  21. #include <fstream>
  22. #include <memory>
  23. #include <getopt.h>
  24. // For cleaner 'does not exist or is not readable' output than
  25. // openssl provides
  26. #include <unistd.h>
  27. #include <errno.h>
  28. // This is a simple tool that creates a self-signed PEM certificate
  29. // for use with BIND 10. It creates a simple certificate for initial
  30. // setup. Currently, all values are hardcoded defaults. For future
  31. // versions, we may want to add more options for administrators.
  32. // It will create a PEM file containing a certificate with the following
  33. // values:
  34. // common name: localhost
  35. // organization: BIND10
  36. // country code: US
  37. // Additional error return codes; these are specifically
  38. // chosen to be distinct from validation error codes as
  39. // provided by OpenSSL. Their main use is to distinguish
  40. // error cases in the unit tests.
  41. const int DECODING_ERROR = 100;
  42. const int BAD_OPTIONS = 101;
  43. const int READ_ERROR = 102;
  44. const int WRITE_ERROR = 103;
  45. const int UNKNOWN_ERROR = 104;
  46. const int NO_SUCH_FILE = 105;
  47. const int FILE_PERMISSION_ERROR = 106;
  48. void
  49. usage() {
  50. std::cout << "Usage: b10-certgen [OPTION]..." << std::endl;
  51. std::cout << "Validate, create, or update a self-signed certificate for "
  52. "use with b10-cmdctl" << std::endl;
  53. std::cout << "" << std::endl;
  54. std::cout << "Options:" << std::endl;
  55. std::cout << "-c, --certfile=FILE\t\tfile to read or store the certificate"
  56. << std::endl;
  57. std::cout << "-f, --force\t\t\toverwrite existing certificate even if it"
  58. << std::endl <<"\t\t\t\tis valid" << std::endl;
  59. std::cout << "-h, --help\t\t\tshow this help" << std::endl;
  60. std::cout << "-k, --keyfile=FILE\t\tfile to store the generated private key"
  61. << std::endl;
  62. std::cout << "-w, --write\t\t\tcreate a new certificate if the given file"
  63. << std::endl << "\t\t\t\tdoes not exist, or if is is not valid"
  64. << std::endl;
  65. std::cout << "-q, --quiet\t\t\tprint no output when creating or validating"
  66. << std::endl;
  67. }
  68. /// \brief Returns true if the given file exists
  69. ///
  70. /// \param filename The file to check
  71. /// \return true if file exists
  72. bool
  73. fileExists(const std::string& filename) {
  74. return (access(filename.c_str(), F_OK) == 0);
  75. }
  76. /// \brief Returns true if the given file exists and is readable
  77. ///
  78. /// \param filename The file to check
  79. /// \return true if file exists and is readable
  80. bool
  81. fileIsReadable(const std::string& filename) {
  82. return (access(filename.c_str(), R_OK) == 0);
  83. }
  84. /// \brief Returns true if the given file exists and is writable
  85. ///
  86. /// \param filename The file to check
  87. /// \return true if file exists and is writable
  88. bool
  89. fileIsWritable(const std::string& filename) {
  90. return (access(filename.c_str(), W_OK) == 0);
  91. }
  92. class CertificateTool {
  93. public:
  94. CertificateTool(bool quiet) : quiet_(quiet) {}
  95. int
  96. createKeyAndCertificate(const std::string& key_file_name,
  97. const std::string& cert_file_name) {
  98. // Create and store a private key
  99. print("Creating key file " + key_file_name);
  100. RSA* rsa = RSA_generate_key(2048, 65537UL, NULL, NULL);
  101. std::ofstream key_file(key_file_name.c_str());
  102. if (!key_file.good()) {
  103. print(std::string("Error writing to ") + key_file_name +
  104. ": " + std::strerror(errno));
  105. return (WRITE_ERROR);
  106. }
  107. BIO* key_mem = BIO_new(BIO_s_mem());
  108. PEM_write_bio_RSAPrivateKey(key_mem, rsa, NULL, NULL, 0, NULL, NULL);
  109. char* p;
  110. long len = BIO_get_mem_data(key_mem, &p);
  111. key_file.write(p, (unsigned) len);
  112. BIO_free(key_mem);
  113. if (!key_file.good()) {
  114. print(std::string("Error writing to ") + key_file_name +
  115. ": " + std::strerror(errno));
  116. return (WRITE_ERROR);
  117. }
  118. key_file.close();
  119. // Certificate options, currently hardcoded.
  120. // For a future version we may want to make these
  121. // settable.
  122. X509* cert = X509_new();
  123. X509_set_version(cert, 2);
  124. BIGNUM* serial = BN_new();
  125. BN_pseudo_rand(serial, 64, 0, 0);
  126. BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(cert));
  127. BN_free(serial);
  128. X509_NAME* name = X509_get_subject_name(cert);
  129. std::string cn("localhost");
  130. X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_ASC,
  131. (unsigned char*) cn.c_str(), cn.size(),
  132. -1, 0);
  133. std::string org("UNKNOWN");
  134. X509_NAME_add_entry_by_NID(name, NID_organizationName, MBSTRING_ASC,
  135. (unsigned char*) org.c_str(), org.size(),
  136. -1, 0);
  137. std::string cc("XX");
  138. X509_NAME_add_entry_by_NID(name, NID_countryName, MBSTRING_ASC,
  139. (unsigned char*) cc.c_str(), cc.size(),
  140. -1, 0);
  141. X509_set_issuer_name(cert, name);
  142. X509_gmtime_adj(X509_get_notBefore(cert), 0);
  143. X509_gmtime_adj(X509_get_notAfter(cert), 60*60*24*365L);
  144. EVP_PKEY* pkey = EVP_PKEY_new();
  145. EVP_PKEY_assign_RSA(pkey, rsa);
  146. X509_set_pubkey(cert, pkey);
  147. X509V3_CTX ec;
  148. X509V3_set_ctx_nodb(&ec);
  149. X509V3_set_ctx(&ec, cert, cert, NULL, NULL, 0);
  150. const std::string bc_val("critical,CA:TRUE,pathlen:1");
  151. X509_EXTENSION* bc = X509V3_EXT_conf_nid(NULL, &ec,
  152. NID_basic_constraints,
  153. (char*) bc_val.c_str());
  154. X509_add_ext(cert, bc, -1);
  155. X509_EXTENSION_free(bc);
  156. const std::string ku_val=("critical,keyCertSign,cRLSign");
  157. X509_EXTENSION* ku = X509V3_EXT_conf_nid(NULL, &ec,
  158. NID_key_usage,
  159. (char*) ku_val.c_str());
  160. X509_add_ext(cert, ku, -1);
  161. X509_EXTENSION_free(ku);
  162. const std::string ski_val("hash");
  163. X509_EXTENSION* ski = X509V3_EXT_conf_nid(NULL, &ec,
  164. NID_subject_key_identifier,
  165. (char*) ski_val.c_str());
  166. X509_add_ext(cert, ski, -1);
  167. X509_EXTENSION_free(ski);
  168. X509_sign(cert, pkey, EVP_sha256());
  169. print("Creating certificate file " + cert_file_name);
  170. std::ofstream cert_file(cert_file_name.c_str());
  171. if (!cert_file.good()) {
  172. print(std::string("Error writing to ") + cert_file_name +
  173. ": " + std::strerror(errno));
  174. return (WRITE_ERROR);
  175. }
  176. BIO* cert_mem = BIO_new(BIO_s_mem());
  177. PEM_write_bio_X509(cert_mem, cert);
  178. p = NULL;
  179. len = BIO_get_mem_data(cert_mem, &p);
  180. cert_file.write(p, (unsigned) len);
  181. BIO_free(cert_mem);
  182. if (!cert_file.good()) {
  183. print(std::string("Error writing to ") + cert_file_name +
  184. ": " + std::strerror(errno));
  185. return (WRITE_ERROR);
  186. }
  187. cert_file.close();
  188. X509_free(cert);
  189. RSA_free(rsa);
  190. return (0);
  191. }
  192. int
  193. validateCertificate(const std::string& certfile) {
  194. // Since we are dealing with a self-signed certificate here, we
  195. // also use the certificate to check itself; i.e. we add it
  196. // as a trusted certificate, then validate the certificate itself.
  197. BIO* in = BIO_new_file(certfile.c_str(), "r");
  198. if (in == NULL) {
  199. print("failed to read " + certfile);
  200. return (READ_ERROR);
  201. }
  202. X509* cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
  203. BIO_free(in);
  204. if (cert == NULL) {
  205. print("failed to decode " + certfile);
  206. return (DECODING_ERROR);
  207. }
  208. X509_STORE* store = X509_STORE_new();
  209. X509_STORE_CTX* csc = X509_STORE_CTX_new();
  210. X509_STORE_CTX_init(csc, store, cert, NULL);
  211. STACK_OF(X509)* trusted = sk_X509_new_null();
  212. sk_X509_push(trusted, X509_dup(cert));
  213. X509_STORE_CTX_trusted_stack(csc, trusted);
  214. const int result = X509_verify_cert(csc);
  215. const int cerror = X509_STORE_CTX_get_error(csc);
  216. X509_STORE_CTX_free(csc);
  217. X509_free(cert);
  218. if (result > 0) {
  219. print(certfile + " is valid");
  220. return (X509_V_OK);
  221. } else {
  222. print(certfile + " failed to verify: " +
  223. X509_verify_cert_error_string(cerror));
  224. return (cerror);
  225. }
  226. }
  227. /// \brief Runs the tool
  228. ///
  229. /// \param create_cert Create certificate if true, validate if false.
  230. /// Does nothing if certificate exists and is valid.
  231. /// \param force_create Create new certificate even if it is valid.
  232. /// \param certfile Certificate file to read to or write from.
  233. /// \param keyfile Key file to write if certificate is created.
  234. /// Ignored if create_cert is false
  235. /// \return zero on success, non-zero on failure
  236. int
  237. run(bool create_cert, bool force_create, const std::string& certfile,
  238. const std::string& keyfile)
  239. {
  240. if (create_cert) {
  241. // Unless force is given, only create it if the current
  242. // one is not OK
  243. // First do some basic permission checks; both files
  244. // should either not exist, or be both readable
  245. // and writable
  246. // The checks are done one by one so all errors can
  247. // be enumerated in one go
  248. if (fileExists(certfile)) {
  249. if (!fileIsReadable(certfile)) {
  250. print(certfile + " not readable: " + std::strerror(errno));
  251. create_cert = false;
  252. }
  253. if (!fileIsWritable(certfile)) {
  254. print(certfile + " not writable: " + std::strerror(errno));
  255. create_cert = false;
  256. }
  257. }
  258. // The key file really only needs write permissions (for
  259. // b10-certgen that is)
  260. if (fileExists(keyfile)) {
  261. if (!fileIsWritable(keyfile)) {
  262. print(keyfile + " not writable: " + std::strerror(errno));
  263. create_cert = false;
  264. }
  265. }
  266. if (!create_cert) {
  267. print("Not creating new certificate, "
  268. "check file permissions");
  269. return (FILE_PERMISSION_ERROR);
  270. }
  271. // If we reach this, we know that if they exist, we can both
  272. // read and write them, so now it's up to content checking
  273. // and/or force_create
  274. if (force_create || !fileExists(certfile) ||
  275. validateCertificate(certfile) != X509_V_OK) {
  276. return (createKeyAndCertificate(keyfile, certfile));
  277. } else {
  278. print("Not creating a new certificate (use -f to force)");
  279. }
  280. } else {
  281. if (!fileExists(certfile)) {
  282. print(certfile + ": " + std::strerror(errno));
  283. return (NO_SUCH_FILE);
  284. }
  285. if (!fileIsReadable(certfile)) {
  286. print(certfile + " not readable: " + std::strerror(errno));
  287. return (FILE_PERMISSION_ERROR);
  288. }
  289. int result = validateCertificate(certfile);
  290. if (result != 0) {
  291. print("Running with -w would overwrite the certificate");
  292. }
  293. return (result);
  294. }
  295. return (0);
  296. }
  297. private:
  298. /// Prints the message to stdout unless quiet_ is true
  299. void print(const std::string& msg) {
  300. if (!quiet_) {
  301. std::cout << msg << std::endl;
  302. }
  303. }
  304. bool quiet_;
  305. };
  306. int
  307. main(int argc, char* argv[])
  308. {
  309. // ERR_load_crypto_strings();
  310. // create or check certificate
  311. bool create_cert = false;
  312. // force creation even if not necessary
  313. bool force_create = false;
  314. // don't print any output
  315. bool quiet = false;
  316. // default certificate file
  317. std::string certfile("cmdctl-certfile.pem");
  318. // default key file
  319. std::string keyfile("cmdctl-keyfile.pem");
  320. // whether or not the above values have been
  321. // overridden (used in command line checking)
  322. bool certfile_default = true;
  323. bool keyfile_default = true;
  324. // It would appear some environments insist on
  325. // char* here (Sunstudio on Solaris), so we const_cast
  326. // them to get rid of compiler warnings.
  327. const struct option long_options[] = {
  328. { const_cast<char*>("certfile"), required_argument, NULL, 'c' },
  329. { const_cast<char*>("force"), no_argument, NULL, 'f' },
  330. { const_cast<char*>("help"), no_argument, NULL, 'h' },
  331. { const_cast<char*>("keyfile"), required_argument, NULL, 'k' },
  332. { const_cast<char*>("write"), no_argument, NULL, 'w' },
  333. { const_cast<char*>("quiet"), no_argument, NULL, 'q' },
  334. { NULL, 0, NULL, 0 }
  335. };
  336. int opt, option_index;
  337. while ((opt = getopt_long(argc, argv, "c:fhk:wq", long_options,
  338. &option_index)) != -1) {
  339. switch (opt) {
  340. case 'c':
  341. certfile = optarg;
  342. certfile_default = false;
  343. break;
  344. case 'f':
  345. force_create = true;
  346. break;
  347. case 'h':
  348. usage();
  349. return (0);
  350. break;
  351. case 'k':
  352. keyfile = optarg;
  353. keyfile_default = false;
  354. break;
  355. case 'w':
  356. create_cert = true;
  357. break;
  358. case 'q':
  359. quiet = true;
  360. break;
  361. default:
  362. // A message will have already been output about the error.
  363. return (BAD_OPTIONS);
  364. }
  365. }
  366. if (optind < argc) {
  367. std::cout << "Error: extraneous arguments" << std::endl << std::endl;
  368. usage();
  369. return (BAD_OPTIONS);
  370. }
  371. // Some sanity checks on option combinations
  372. if (create_cert && (certfile_default ^ keyfile_default)) {
  373. std::cout << "Error: keyfile and certfile must both be specified "
  374. "if one of them is when calling b10-certgen in write "
  375. "mode." << std::endl;
  376. return (BAD_OPTIONS);
  377. }
  378. if (!create_cert && !keyfile_default) {
  379. std::cout << "Error: keyfile is not used when not in write mode"
  380. << std::endl;
  381. return (BAD_OPTIONS);
  382. }
  383. // Initialize the tool and perform the appropriate action(s)
  384. CertificateTool tool(quiet);
  385. return (tool.run(create_cert, force_create, certfile, keyfile));
  386. }