ca.c 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643
  1. /*
  2. * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <ctype.h>
  13. #include <sys/types.h>
  14. #include <openssl/conf.h>
  15. #include <openssl/bio.h>
  16. #include <openssl/err.h>
  17. #include <openssl/bn.h>
  18. #include <openssl/txt_db.h>
  19. #include <openssl/evp.h>
  20. #include <openssl/x509.h>
  21. #include <openssl/x509v3.h>
  22. #include <openssl/objects.h>
  23. #include <openssl/ocsp.h>
  24. #include <openssl/pem.h>
  25. #ifndef W_OK
  26. # ifdef OPENSSL_SYS_VMS
  27. # include <unistd.h>
  28. # elif !defined(OPENSSL_SYS_VXWORKS) && !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_TANDEM)
  29. # include <sys/file.h>
  30. # endif
  31. #endif
  32. #include "apps.h"
  33. #include "progs.h"
  34. #ifndef W_OK
  35. # define F_OK 0
  36. # define W_OK 2
  37. # define R_OK 4
  38. #endif
  39. #ifndef PATH_MAX
  40. # define PATH_MAX 4096
  41. #endif
  42. #define BASE_SECTION "ca"
  43. #define ENV_DEFAULT_CA "default_ca"
  44. #define STRING_MASK "string_mask"
  45. #define UTF8_IN "utf8"
  46. #define ENV_NEW_CERTS_DIR "new_certs_dir"
  47. #define ENV_CERTIFICATE "certificate"
  48. #define ENV_SERIAL "serial"
  49. #define ENV_RAND_SERIAL "rand_serial"
  50. #define ENV_CRLNUMBER "crlnumber"
  51. #define ENV_PRIVATE_KEY "private_key"
  52. #define ENV_DEFAULT_DAYS "default_days"
  53. #define ENV_DEFAULT_STARTDATE "default_startdate"
  54. #define ENV_DEFAULT_ENDDATE "default_enddate"
  55. #define ENV_DEFAULT_CRL_DAYS "default_crl_days"
  56. #define ENV_DEFAULT_CRL_HOURS "default_crl_hours"
  57. #define ENV_DEFAULT_MD "default_md"
  58. #define ENV_DEFAULT_EMAIL_DN "email_in_dn"
  59. #define ENV_PRESERVE "preserve"
  60. #define ENV_POLICY "policy"
  61. #define ENV_EXTENSIONS "x509_extensions"
  62. #define ENV_CRLEXT "crl_extensions"
  63. #define ENV_MSIE_HACK "msie_hack"
  64. #define ENV_NAMEOPT "name_opt"
  65. #define ENV_CERTOPT "cert_opt"
  66. #define ENV_EXTCOPY "copy_extensions"
  67. #define ENV_UNIQUE_SUBJECT "unique_subject"
  68. #define ENV_DATABASE "database"
  69. /* Additional revocation information types */
  70. typedef enum {
  71. REV_VALID = -1, /* Valid (not-revoked) status */
  72. REV_NONE = 0, /* No additional information */
  73. REV_CRL_REASON = 1, /* Value is CRL reason code */
  74. REV_HOLD = 2, /* Value is hold instruction */
  75. REV_KEY_COMPROMISE = 3, /* Value is cert key compromise time */
  76. REV_CA_COMPROMISE = 4 /* Value is CA key compromise time */
  77. } REVINFO_TYPE;
  78. static char *lookup_conf(const CONF *conf, const char *group, const char *tag);
  79. static int certify(X509 **xret, const char *infile, int informat,
  80. EVP_PKEY *pkey, X509 *x509,
  81. const char *dgst,
  82. STACK_OF(OPENSSL_STRING) *sigopts,
  83. STACK_OF(OPENSSL_STRING) *vfyopts,
  84. STACK_OF(CONF_VALUE) *policy, CA_DB *db,
  85. BIGNUM *serial, const char *subj, unsigned long chtype,
  86. int multirdn, int email_dn, const char *startdate,
  87. const char *enddate,
  88. long days, int batch, const char *ext_sect, CONF *conf,
  89. int verbose, unsigned long certopt, unsigned long nameopt,
  90. int default_op, int ext_copy, int selfsign, unsigned long dateopt);
  91. static int certify_cert(X509 **xret, const char *infile, int certformat,
  92. const char *passin, EVP_PKEY *pkey, X509 *x509,
  93. const char *dgst,
  94. STACK_OF(OPENSSL_STRING) *sigopts,
  95. STACK_OF(OPENSSL_STRING) *vfyopts,
  96. STACK_OF(CONF_VALUE) *policy, CA_DB *db,
  97. BIGNUM *serial, const char *subj, unsigned long chtype,
  98. int multirdn, int email_dn, const char *startdate,
  99. const char *enddate, long days, int batch, const char *ext_sect,
  100. CONF *conf, int verbose, unsigned long certopt,
  101. unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt);
  102. static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey,
  103. X509 *x509, const char *dgst,
  104. STACK_OF(OPENSSL_STRING) *sigopts,
  105. STACK_OF(CONF_VALUE) *policy, CA_DB *db,
  106. BIGNUM *serial, const char *subj, unsigned long chtype,
  107. int multirdn, int email_dn, const char *startdate,
  108. const char *enddate, long days, const char *ext_sect, CONF *conf,
  109. int verbose, unsigned long certopt,
  110. unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt);
  111. static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
  112. const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
  113. STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial,
  114. const char *subj, unsigned long chtype, int multirdn,
  115. int email_dn, const char *startdate, const char *enddate, long days,
  116. int batch, int verbose, X509_REQ *req, const char *ext_sect,
  117. CONF *conf, unsigned long certopt, unsigned long nameopt,
  118. int default_op, int ext_copy, int selfsign, unsigned long dateopt);
  119. static int get_certificate_status(const char *ser_status, CA_DB *db);
  120. static int check_time_format(const char *str);
  121. static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type,
  122. const char *extval);
  123. static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg);
  124. static int make_revoked(X509_REVOKED *rev, const char *str);
  125. static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str);
  126. static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext);
  127. static CONF *extfile_conf = NULL;
  128. static int preserve = 0;
  129. static int msie_hack = 0;
  130. typedef enum OPTION_choice {
  131. OPT_COMMON,
  132. OPT_ENGINE, OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SUBJ, OPT_UTF8,
  133. OPT_CREATE_SERIAL, OPT_MULTIVALUE_RDN, OPT_STARTDATE, OPT_ENDDATE,
  134. OPT_DAYS, OPT_MD, OPT_POLICY, OPT_KEYFILE, OPT_KEYFORM, OPT_PASSIN,
  135. OPT_KEY, OPT_CERT, OPT_CERTFORM, OPT_SELFSIGN,
  136. OPT_IN, OPT_INFORM, OPT_OUT, OPT_DATEOPT, OPT_OUTDIR, OPT_VFYOPT,
  137. OPT_SIGOPT, OPT_NOTEXT, OPT_BATCH, OPT_PRESERVEDN, OPT_NOEMAILDN,
  138. OPT_GENCRL, OPT_MSIE_HACK, OPT_CRL_LASTUPDATE, OPT_CRL_NEXTUPDATE,
  139. OPT_CRLDAYS, OPT_CRLHOURS, OPT_CRLSEC,
  140. OPT_INFILES, OPT_SS_CERT, OPT_SPKAC, OPT_REVOKE, OPT_VALID,
  141. OPT_EXTENSIONS, OPT_EXTFILE, OPT_STATUS, OPT_UPDATEDB, OPT_CRLEXTS,
  142. OPT_RAND_SERIAL, OPT_QUIET,
  143. OPT_R_ENUM, OPT_PROV_ENUM,
  144. /* Do not change the order here; see related case statements below */
  145. OPT_CRL_REASON, OPT_CRL_HOLD, OPT_CRL_COMPROMISE, OPT_CRL_CA_COMPROMISE
  146. } OPTION_CHOICE;
  147. const OPTIONS ca_options[] = {
  148. {OPT_HELP_STR, 1, '-', "Usage: %s [options] [certreq...]\n"},
  149. OPT_SECTION("General"),
  150. {"help", OPT_HELP, '-', "Display this summary"},
  151. {"verbose", OPT_VERBOSE, '-', "Verbose output during processing"},
  152. {"quiet", OPT_QUIET, '-', "Terse output during processing"},
  153. {"outdir", OPT_OUTDIR, '/', "Where to put output cert"},
  154. {"in", OPT_IN, '<', "The input cert request(s)"},
  155. {"inform", OPT_INFORM, 'F',
  156. "CSR input format to use (PEM or DER; by default try PEM first)"},
  157. {"infiles", OPT_INFILES, '-', "The last argument, requests to process"},
  158. {"out", OPT_OUT, '>', "Where to put the output file(s)"},
  159. {"dateopt", OPT_DATEOPT, 's', "Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822."},
  160. {"notext", OPT_NOTEXT, '-', "Do not print the generated certificate"},
  161. {"batch", OPT_BATCH, '-', "Don't ask questions"},
  162. {"msie_hack", OPT_MSIE_HACK, '-',
  163. "msie modifications to handle all Universal Strings"},
  164. {"ss_cert", OPT_SS_CERT, '<', "File contains a self signed cert to sign"},
  165. {"spkac", OPT_SPKAC, '<',
  166. "File contains DN and signed public key and challenge"},
  167. #ifndef OPENSSL_NO_ENGINE
  168. {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
  169. #endif
  170. OPT_SECTION("Configuration"),
  171. {"config", OPT_CONFIG, 's', "A config file"},
  172. {"name", OPT_NAME, 's', "The particular CA definition to use"},
  173. {"section", OPT_NAME, 's', "An alias for -name"},
  174. {"policy", OPT_POLICY, 's', "The CA 'policy' to support"},
  175. OPT_SECTION("Certificate"),
  176. {"subj", OPT_SUBJ, 's', "Use arg instead of request's subject"},
  177. {"utf8", OPT_UTF8, '-', "Input characters are UTF8; default ASCII"},
  178. {"create_serial", OPT_CREATE_SERIAL, '-',
  179. "If reading serial fails, create a new random serial"},
  180. {"rand_serial", OPT_RAND_SERIAL, '-',
  181. "Always create a random serial; do not store it"},
  182. {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
  183. "Deprecated; multi-valued RDNs support is always on."},
  184. {"startdate", OPT_STARTDATE, 's', "Cert notBefore, YYMMDDHHMMSSZ"},
  185. {"enddate", OPT_ENDDATE, 's',
  186. "YYMMDDHHMMSSZ cert notAfter (overrides -days)"},
  187. {"days", OPT_DAYS, 'p', "Number of days to certify the cert for"},
  188. {"extensions", OPT_EXTENSIONS, 's',
  189. "Extension section (override value in config file)"},
  190. {"extfile", OPT_EXTFILE, '<',
  191. "Configuration file with X509v3 extensions to add"},
  192. {"preserveDN", OPT_PRESERVEDN, '-', "Don't re-order the DN"},
  193. {"noemailDN", OPT_NOEMAILDN, '-', "Don't add the EMAIL field to the DN"},
  194. OPT_SECTION("Signing"),
  195. {"md", OPT_MD, 's', "Digest to use, such as sha256"},
  196. {"keyfile", OPT_KEYFILE, 's', "The CA private key"},
  197. {"keyform", OPT_KEYFORM, 'f',
  198. "Private key file format (ENGINE, other values ignored)"},
  199. {"passin", OPT_PASSIN, 's', "Key and cert input file pass phrase source"},
  200. {"key", OPT_KEY, 's',
  201. "Key to decrypt the private key or cert files if encrypted. Better use -passin"},
  202. {"cert", OPT_CERT, '<', "The CA cert"},
  203. {"certform", OPT_CERTFORM, 'F',
  204. "Certificate input format (DER/PEM/P12); has no effect"},
  205. {"selfsign", OPT_SELFSIGN, '-',
  206. "Sign a cert with the key associated with it"},
  207. {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
  208. {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
  209. OPT_SECTION("Revocation"),
  210. {"gencrl", OPT_GENCRL, '-', "Generate a new CRL"},
  211. {"valid", OPT_VALID, 's',
  212. "Add a Valid(not-revoked) DB entry about a cert (given in file)"},
  213. {"status", OPT_STATUS, 's', "Shows cert status given the serial number"},
  214. {"updatedb", OPT_UPDATEDB, '-', "Updates db for expired cert"},
  215. {"crlexts", OPT_CRLEXTS, 's',
  216. "CRL extension section (override value in config file)"},
  217. {"crl_reason", OPT_CRL_REASON, 's', "revocation reason"},
  218. {"crl_hold", OPT_CRL_HOLD, 's',
  219. "the hold instruction, an OID. Sets revocation reason to certificateHold"},
  220. {"crl_compromise", OPT_CRL_COMPROMISE, 's',
  221. "sets compromise time to val and the revocation reason to keyCompromise"},
  222. {"crl_CA_compromise", OPT_CRL_CA_COMPROMISE, 's',
  223. "sets compromise time to val and the revocation reason to CACompromise"},
  224. {"crl_lastupdate", OPT_CRL_LASTUPDATE, 's',
  225. "Sets the CRL lastUpdate time to val (YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ)"},
  226. {"crl_nextupdate", OPT_CRL_NEXTUPDATE, 's',
  227. "Sets the CRL nextUpdate time to val (YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ)"},
  228. {"crldays", OPT_CRLDAYS, 'p', "Days until the next CRL is due"},
  229. {"crlhours", OPT_CRLHOURS, 'p', "Hours until the next CRL is due"},
  230. {"crlsec", OPT_CRLSEC, 'p', "Seconds until the next CRL is due"},
  231. {"revoke", OPT_REVOKE, '<', "Revoke a cert (given in file)"},
  232. OPT_R_OPTIONS,
  233. OPT_PROV_OPTIONS,
  234. OPT_PARAMETERS(),
  235. {"certreq", 0, 0, "Certificate requests to be signed (optional)"},
  236. {NULL}
  237. };
  238. int ca_main(int argc, char **argv)
  239. {
  240. CONF *conf = NULL;
  241. ENGINE *e = NULL;
  242. BIGNUM *crlnumber = NULL, *serial = NULL;
  243. EVP_PKEY *pkey = NULL;
  244. BIO *in = NULL, *out = NULL, *Sout = NULL;
  245. ASN1_INTEGER *tmpser;
  246. CA_DB *db = NULL;
  247. DB_ATTR db_attr;
  248. STACK_OF(CONF_VALUE) *attribs = NULL;
  249. STACK_OF(OPENSSL_STRING) *sigopts = NULL, *vfyopts = NULL;
  250. STACK_OF(X509) *cert_sk = NULL;
  251. X509_CRL *crl = NULL;
  252. char *configfile = default_config_file, *section = NULL;
  253. char def_dgst[80] = "";
  254. char *dgst = NULL, *policy = NULL, *keyfile = NULL;
  255. char *certfile = NULL, *crl_ext = NULL, *crlnumberfile = NULL;
  256. int certformat = FORMAT_UNDEF, informat = FORMAT_UNDEF;
  257. unsigned long dateopt = ASN1_DTFLGS_RFC822;
  258. const char *infile = NULL, *spkac_file = NULL, *ss_cert_file = NULL;
  259. const char *extensions = NULL, *extfile = NULL, *passinarg = NULL;
  260. char *passin = NULL;
  261. char *outdir = NULL, *outfile = NULL, *rev_arg = NULL, *ser_status = NULL;
  262. const char *serialfile = NULL, *subj = NULL;
  263. char *prog, *startdate = NULL, *enddate = NULL;
  264. char *dbfile = NULL, *f;
  265. char new_cert[PATH_MAX];
  266. char tmp[10 + 1] = "\0";
  267. char *const *pp;
  268. const char *p;
  269. size_t outdirlen = 0;
  270. int create_ser = 0, free_passin = 0, total = 0, total_done = 0;
  271. int batch = 0, default_op = 1, doupdatedb = 0, ext_copy = EXT_COPY_NONE;
  272. int keyformat = FORMAT_UNDEF, multirdn = 1, notext = 0, output_der = 0;
  273. int ret = 1, email_dn = 1, req = 0, verbose = 0, gencrl = 0, dorevoke = 0;
  274. int rand_ser = 0, i, j, selfsign = 0, def_ret;
  275. char *crl_lastupdate = NULL, *crl_nextupdate = NULL;
  276. long crldays = 0, crlhours = 0, crlsec = 0, days = 0;
  277. unsigned long chtype = MBSTRING_ASC, certopt = 0;
  278. X509 *x509 = NULL, *x509p = NULL, *x = NULL;
  279. REVINFO_TYPE rev_type = REV_NONE;
  280. X509_REVOKED *r = NULL;
  281. OPTION_CHOICE o;
  282. prog = opt_init(argc, argv, ca_options);
  283. while ((o = opt_next()) != OPT_EOF) {
  284. switch (o) {
  285. case OPT_EOF:
  286. case OPT_ERR:
  287. opthelp:
  288. BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
  289. goto end;
  290. case OPT_HELP:
  291. opt_help(ca_options);
  292. ret = 0;
  293. goto end;
  294. case OPT_IN:
  295. req = 1;
  296. infile = opt_arg();
  297. break;
  298. case OPT_INFORM:
  299. if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
  300. goto opthelp;
  301. break;
  302. case OPT_OUT:
  303. outfile = opt_arg();
  304. break;
  305. case OPT_DATEOPT:
  306. if (!set_dateopt(&dateopt, opt_arg()))
  307. goto opthelp;
  308. break;
  309. case OPT_VERBOSE:
  310. verbose = 1;
  311. break;
  312. case OPT_QUIET:
  313. verbose = 0;
  314. break;
  315. case OPT_CONFIG:
  316. configfile = opt_arg();
  317. break;
  318. case OPT_NAME:
  319. section = opt_arg();
  320. break;
  321. case OPT_SUBJ:
  322. subj = opt_arg();
  323. /* preserve=1; */
  324. break;
  325. case OPT_UTF8:
  326. chtype = MBSTRING_UTF8;
  327. break;
  328. case OPT_RAND_SERIAL:
  329. rand_ser = 1;
  330. break;
  331. case OPT_CREATE_SERIAL:
  332. create_ser = 1;
  333. break;
  334. case OPT_MULTIVALUE_RDN:
  335. /* obsolete */
  336. break;
  337. case OPT_STARTDATE:
  338. startdate = opt_arg();
  339. break;
  340. case OPT_ENDDATE:
  341. enddate = opt_arg();
  342. break;
  343. case OPT_DAYS:
  344. days = atoi(opt_arg());
  345. break;
  346. case OPT_MD:
  347. dgst = opt_arg();
  348. break;
  349. case OPT_POLICY:
  350. policy = opt_arg();
  351. break;
  352. case OPT_KEYFILE:
  353. keyfile = opt_arg();
  354. break;
  355. case OPT_KEYFORM:
  356. if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
  357. goto opthelp;
  358. break;
  359. case OPT_PASSIN:
  360. passinarg = opt_arg();
  361. break;
  362. case OPT_R_CASES:
  363. if (!opt_rand(o))
  364. goto end;
  365. break;
  366. case OPT_PROV_CASES:
  367. if (!opt_provider(o))
  368. goto end;
  369. break;
  370. case OPT_KEY:
  371. passin = opt_arg();
  372. break;
  373. case OPT_CERT:
  374. certfile = opt_arg();
  375. break;
  376. case OPT_CERTFORM:
  377. if (!opt_format(opt_arg(), OPT_FMT_ANY, &certformat))
  378. goto opthelp;
  379. break;
  380. case OPT_SELFSIGN:
  381. selfsign = 1;
  382. break;
  383. case OPT_OUTDIR:
  384. outdir = opt_arg();
  385. break;
  386. case OPT_SIGOPT:
  387. if (sigopts == NULL)
  388. sigopts = sk_OPENSSL_STRING_new_null();
  389. if (sigopts == NULL || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
  390. goto end;
  391. break;
  392. case OPT_VFYOPT:
  393. if (vfyopts == NULL)
  394. vfyopts = sk_OPENSSL_STRING_new_null();
  395. if (vfyopts == NULL || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
  396. goto end;
  397. break;
  398. case OPT_NOTEXT:
  399. notext = 1;
  400. break;
  401. case OPT_BATCH:
  402. batch = 1;
  403. break;
  404. case OPT_PRESERVEDN:
  405. preserve = 1;
  406. break;
  407. case OPT_NOEMAILDN:
  408. email_dn = 0;
  409. break;
  410. case OPT_GENCRL:
  411. gencrl = 1;
  412. break;
  413. case OPT_MSIE_HACK:
  414. msie_hack = 1;
  415. break;
  416. case OPT_CRL_LASTUPDATE:
  417. crl_lastupdate = opt_arg();
  418. break;
  419. case OPT_CRL_NEXTUPDATE:
  420. crl_nextupdate = opt_arg();
  421. break;
  422. case OPT_CRLDAYS:
  423. crldays = atol(opt_arg());
  424. break;
  425. case OPT_CRLHOURS:
  426. crlhours = atol(opt_arg());
  427. break;
  428. case OPT_CRLSEC:
  429. crlsec = atol(opt_arg());
  430. break;
  431. case OPT_INFILES:
  432. req = 1;
  433. goto end_of_options;
  434. case OPT_SS_CERT:
  435. ss_cert_file = opt_arg();
  436. req = 1;
  437. break;
  438. case OPT_SPKAC:
  439. spkac_file = opt_arg();
  440. req = 1;
  441. break;
  442. case OPT_REVOKE:
  443. infile = opt_arg();
  444. dorevoke = 1;
  445. break;
  446. case OPT_VALID:
  447. infile = opt_arg();
  448. dorevoke = 2;
  449. break;
  450. case OPT_EXTENSIONS:
  451. extensions = opt_arg();
  452. break;
  453. case OPT_EXTFILE:
  454. extfile = opt_arg();
  455. break;
  456. case OPT_STATUS:
  457. ser_status = opt_arg();
  458. break;
  459. case OPT_UPDATEDB:
  460. doupdatedb = 1;
  461. break;
  462. case OPT_CRLEXTS:
  463. crl_ext = opt_arg();
  464. break;
  465. case OPT_CRL_REASON: /* := REV_CRL_REASON */
  466. case OPT_CRL_HOLD:
  467. case OPT_CRL_COMPROMISE:
  468. case OPT_CRL_CA_COMPROMISE:
  469. rev_arg = opt_arg();
  470. rev_type = (o - OPT_CRL_REASON) + REV_CRL_REASON;
  471. break;
  472. case OPT_ENGINE:
  473. e = setup_engine(opt_arg(), 0);
  474. break;
  475. }
  476. }
  477. end_of_options:
  478. /* Remaining args are files to certify. */
  479. argc = opt_num_rest();
  480. argv = opt_rest();
  481. if ((conf = app_load_config_verbose(configfile, 1)) == NULL)
  482. goto end;
  483. if (configfile != default_config_file && !app_load_modules(conf))
  484. goto end;
  485. /* Lets get the config section we are using */
  486. if (section == NULL
  487. && (section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_CA)) == NULL)
  488. goto end;
  489. p = app_conf_try_string(conf, NULL, "oid_file");
  490. if (p != NULL) {
  491. BIO *oid_bio = BIO_new_file(p, "r");
  492. if (oid_bio == NULL) {
  493. ERR_clear_error();
  494. } else {
  495. OBJ_create_objects(oid_bio);
  496. BIO_free(oid_bio);
  497. }
  498. }
  499. if (!add_oid_section(conf))
  500. goto end;
  501. app_RAND_load_conf(conf, BASE_SECTION);
  502. if (!app_RAND_load())
  503. goto end;
  504. f = app_conf_try_string(conf, section, STRING_MASK);
  505. if (f != NULL && !ASN1_STRING_set_default_mask_asc(f)) {
  506. BIO_printf(bio_err, "Invalid global string mask setting %s\n", f);
  507. goto end;
  508. }
  509. if (chtype != MBSTRING_UTF8) {
  510. f = app_conf_try_string(conf, section, UTF8_IN);
  511. if (f != NULL && strcmp(f, "yes") == 0)
  512. chtype = MBSTRING_UTF8;
  513. }
  514. db_attr.unique_subject = 1;
  515. p = app_conf_try_string(conf, section, ENV_UNIQUE_SUBJECT);
  516. if (p != NULL)
  517. db_attr.unique_subject = parse_yesno(p, 1);
  518. /*****************************************************************/
  519. /* report status of cert with serial number given on command line */
  520. if (ser_status) {
  521. dbfile = lookup_conf(conf, section, ENV_DATABASE);
  522. if (dbfile == NULL)
  523. goto end;
  524. db = load_index(dbfile, &db_attr);
  525. if (db == NULL) {
  526. BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", dbfile);
  527. goto end;
  528. }
  529. if (index_index(db) <= 0)
  530. goto end;
  531. if (get_certificate_status(ser_status, db) != 1)
  532. BIO_printf(bio_err, "Error verifying serial %s!\n", ser_status);
  533. goto end;
  534. }
  535. /*****************************************************************/
  536. /* we definitely need a private key, so let's get it */
  537. if (keyfile == NULL
  538. && (keyfile = lookup_conf(conf, section, ENV_PRIVATE_KEY)) == NULL)
  539. goto end;
  540. if (passin == NULL) {
  541. free_passin = 1;
  542. if (!app_passwd(passinarg, NULL, &passin, NULL)) {
  543. BIO_printf(bio_err, "Error getting password\n");
  544. goto end;
  545. }
  546. }
  547. pkey = load_key(keyfile, keyformat, 0, passin, e, "CA private key");
  548. cleanse(passin);
  549. if (pkey == NULL)
  550. /* load_key() has already printed an appropriate message */
  551. goto end;
  552. /*****************************************************************/
  553. /* we need a certificate */
  554. if (!selfsign || spkac_file || ss_cert_file || gencrl) {
  555. if (certfile == NULL
  556. && (certfile = lookup_conf(conf, section, ENV_CERTIFICATE)) == NULL)
  557. goto end;
  558. x509 = load_cert_pass(certfile, certformat, 1, passin, "CA certificate");
  559. if (x509 == NULL)
  560. goto end;
  561. if (!X509_check_private_key(x509, pkey)) {
  562. BIO_printf(bio_err,
  563. "CA certificate and CA private key do not match\n");
  564. goto end;
  565. }
  566. }
  567. if (!selfsign)
  568. x509p = x509;
  569. f = app_conf_try_string(conf, BASE_SECTION, ENV_PRESERVE);
  570. if (f != NULL && (*f == 'y' || *f == 'Y'))
  571. preserve = 1;
  572. f = app_conf_try_string(conf, BASE_SECTION, ENV_MSIE_HACK);
  573. if (f != NULL && (*f == 'y' || *f == 'Y'))
  574. msie_hack = 1;
  575. f = app_conf_try_string(conf, section, ENV_NAMEOPT);
  576. if (f != NULL) {
  577. if (!set_nameopt(f)) {
  578. BIO_printf(bio_err, "Invalid name options: \"%s\"\n", f);
  579. goto end;
  580. }
  581. default_op = 0;
  582. }
  583. f = app_conf_try_string(conf, section, ENV_CERTOPT);
  584. if (f != NULL) {
  585. if (!set_cert_ex(&certopt, f)) {
  586. BIO_printf(bio_err, "Invalid certificate options: \"%s\"\n", f);
  587. goto end;
  588. }
  589. default_op = 0;
  590. }
  591. f = app_conf_try_string(conf, section, ENV_EXTCOPY);
  592. if (f != NULL) {
  593. if (!set_ext_copy(&ext_copy, f)) {
  594. BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", f);
  595. goto end;
  596. }
  597. }
  598. /*****************************************************************/
  599. /* lookup where to write new certificates */
  600. if ((outdir == NULL) && (req)) {
  601. outdir = NCONF_get_string(conf, section, ENV_NEW_CERTS_DIR);
  602. if (outdir == NULL) {
  603. BIO_printf(bio_err,
  604. "there needs to be defined a directory for new certificate to be placed in\n");
  605. goto end;
  606. }
  607. #ifndef OPENSSL_SYS_VMS
  608. /*
  609. * outdir is a directory spec, but access() for VMS demands a
  610. * filename. We could use the DEC C routine to convert the
  611. * directory syntax to Unix, and give that to app_isdir,
  612. * but for now the fopen will catch the error if it's not a
  613. * directory
  614. */
  615. if (app_isdir(outdir) <= 0) {
  616. BIO_printf(bio_err, "%s: %s is not a directory\n", prog, outdir);
  617. perror(outdir);
  618. goto end;
  619. }
  620. #endif
  621. }
  622. /*****************************************************************/
  623. /* we need to load the database file */
  624. dbfile = lookup_conf(conf, section, ENV_DATABASE);
  625. if (dbfile == NULL)
  626. goto end;
  627. db = load_index(dbfile, &db_attr);
  628. if (db == NULL) {
  629. BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", dbfile);
  630. goto end;
  631. }
  632. /* Lets check some fields */
  633. for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
  634. pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
  635. if ((pp[DB_type][0] != DB_TYPE_REV) && (pp[DB_rev_date][0] != '\0')) {
  636. BIO_printf(bio_err,
  637. "entry %d: not revoked yet, but has a revocation date\n",
  638. i + 1);
  639. goto end;
  640. }
  641. if ((pp[DB_type][0] == DB_TYPE_REV) &&
  642. !make_revoked(NULL, pp[DB_rev_date])) {
  643. BIO_printf(bio_err, " in entry %d\n", i + 1);
  644. goto end;
  645. }
  646. if (!check_time_format((char *)pp[DB_exp_date])) {
  647. BIO_printf(bio_err, "entry %d: invalid expiry date\n", i + 1);
  648. goto end;
  649. }
  650. p = pp[DB_serial];
  651. j = strlen(p);
  652. if (*p == '-') {
  653. p++;
  654. j--;
  655. }
  656. if ((j & 1) || (j < 2)) {
  657. BIO_printf(bio_err, "entry %d: bad serial number length (%d)\n",
  658. i + 1, j);
  659. goto end;
  660. }
  661. for ( ; *p; p++) {
  662. if (!isxdigit(_UC(*p))) {
  663. BIO_printf(bio_err,
  664. "entry %d: bad char 0%o '%c' in serial number\n",
  665. i + 1, *p, *p);
  666. goto end;
  667. }
  668. }
  669. }
  670. if (verbose) {
  671. TXT_DB_write(bio_out, db->db);
  672. BIO_printf(bio_err, "%d entries loaded from the database\n",
  673. sk_OPENSSL_PSTRING_num(db->db->data));
  674. BIO_printf(bio_err, "generating index\n");
  675. }
  676. if (index_index(db) <= 0)
  677. goto end;
  678. /*****************************************************************/
  679. /* Update the db file for expired certificates */
  680. if (doupdatedb) {
  681. if (verbose)
  682. BIO_printf(bio_err, "Updating %s ...\n", dbfile);
  683. i = do_updatedb(db, NULL);
  684. if (i == -1) {
  685. BIO_printf(bio_err, "Malloc failure\n");
  686. goto end;
  687. } else if (i == 0) {
  688. if (verbose)
  689. BIO_printf(bio_err, "No entries found to mark expired\n");
  690. } else {
  691. if (!save_index(dbfile, "new", db))
  692. goto end;
  693. if (!rotate_index(dbfile, "new", "old"))
  694. goto end;
  695. if (verbose)
  696. BIO_printf(bio_err, "Done. %d entries marked as expired\n", i);
  697. }
  698. }
  699. /*****************************************************************/
  700. /* Read extensions config file */
  701. if (extfile) {
  702. if ((extfile_conf = app_load_config(extfile)) == NULL) {
  703. ret = 1;
  704. goto end;
  705. }
  706. if (verbose)
  707. BIO_printf(bio_err, "Successfully loaded extensions file %s\n",
  708. extfile);
  709. /* We can have sections in the ext file */
  710. if (extensions == NULL) {
  711. extensions =
  712. app_conf_try_string(extfile_conf, "default", "extensions");
  713. if (extensions == NULL)
  714. extensions = "default";
  715. }
  716. }
  717. /*****************************************************************/
  718. if (req || gencrl) {
  719. if (spkac_file != NULL && outfile != NULL) {
  720. output_der = 1;
  721. batch = 1;
  722. }
  723. }
  724. def_ret = EVP_PKEY_get_default_digest_name(pkey, def_dgst, sizeof(def_dgst));
  725. /*
  726. * EVP_PKEY_get_default_digest_name() returns 2 if the digest is
  727. * mandatory for this algorithm.
  728. *
  729. * That call may give back the name "UNDEF", which has these meanings:
  730. *
  731. * when def_ret == 2: the user MUST leave the digest unspecified
  732. * when def_ret == 1: the user MAY leave the digest unspecified
  733. */
  734. if (def_ret == 2 && strcmp(def_dgst, "UNDEF") == 0) {
  735. dgst = NULL;
  736. } else if (dgst == NULL
  737. && (dgst = lookup_conf(conf, section, ENV_DEFAULT_MD)) == NULL
  738. && strcmp(def_dgst, "UNDEF") != 0) {
  739. goto end;
  740. } else {
  741. if (strcmp(dgst, "default") == 0 || strcmp(def_dgst, "UNDEF") == 0) {
  742. if (def_ret <= 0) {
  743. BIO_puts(bio_err, "no default digest\n");
  744. goto end;
  745. }
  746. dgst = def_dgst;
  747. }
  748. }
  749. if (req) {
  750. if (email_dn == 1) {
  751. char *tmp_email_dn = NULL;
  752. tmp_email_dn =
  753. app_conf_try_string(conf, section, ENV_DEFAULT_EMAIL_DN);
  754. if (tmp_email_dn != NULL && strcmp(tmp_email_dn, "no") == 0)
  755. email_dn = 0;
  756. }
  757. if (verbose)
  758. BIO_printf(bio_err, "message digest is %s\n", dgst);
  759. if (policy == NULL
  760. && (policy = lookup_conf(conf, section, ENV_POLICY)) == NULL)
  761. goto end;
  762. if (verbose)
  763. BIO_printf(bio_err, "policy is %s\n", policy);
  764. if (app_conf_try_string(conf, section, ENV_RAND_SERIAL) != NULL) {
  765. rand_ser = 1;
  766. } else {
  767. serialfile = lookup_conf(conf, section, ENV_SERIAL);
  768. if (serialfile == NULL)
  769. goto end;
  770. }
  771. if (extfile_conf != NULL) {
  772. /* Check syntax of extfile */
  773. X509V3_CTX ctx;
  774. X509V3_set_ctx_test(&ctx);
  775. X509V3_set_nconf(&ctx, extfile_conf);
  776. if (!X509V3_EXT_add_nconf(extfile_conf, &ctx, extensions, NULL)) {
  777. BIO_printf(bio_err,
  778. "Error checking certificate extensions from extfile section %s\n",
  779. extensions);
  780. ret = 1;
  781. goto end;
  782. }
  783. } else {
  784. /*
  785. * no '-extfile' option, so we look for extensions in the main
  786. * configuration file
  787. */
  788. if (extensions == NULL)
  789. extensions = app_conf_try_string(conf, section, ENV_EXTENSIONS);
  790. if (extensions != NULL) {
  791. /* Check syntax of config file section */
  792. X509V3_CTX ctx;
  793. X509V3_set_ctx_test(&ctx);
  794. X509V3_set_nconf(&ctx, conf);
  795. if (!X509V3_EXT_add_nconf(conf, &ctx, extensions, NULL)) {
  796. BIO_printf(bio_err,
  797. "Error checking certificate extension config section %s\n",
  798. extensions);
  799. ret = 1;
  800. goto end;
  801. }
  802. }
  803. }
  804. if (startdate == NULL)
  805. startdate =
  806. app_conf_try_string(conf, section, ENV_DEFAULT_STARTDATE);
  807. if (startdate != NULL && !ASN1_TIME_set_string_X509(NULL, startdate)) {
  808. BIO_printf(bio_err,
  809. "start date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
  810. goto end;
  811. }
  812. if (startdate == NULL)
  813. startdate = "today";
  814. if (enddate == NULL)
  815. enddate = app_conf_try_string(conf, section, ENV_DEFAULT_ENDDATE);
  816. if (enddate != NULL && !ASN1_TIME_set_string_X509(NULL, enddate)) {
  817. BIO_printf(bio_err,
  818. "end date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
  819. goto end;
  820. }
  821. if (days == 0) {
  822. if (!app_conf_try_number(conf, section, ENV_DEFAULT_DAYS, &days))
  823. days = 0;
  824. }
  825. if (enddate == NULL && days == 0) {
  826. BIO_printf(bio_err, "cannot lookup how many days to certify for\n");
  827. goto end;
  828. }
  829. if (rand_ser) {
  830. if ((serial = BN_new()) == NULL || !rand_serial(serial, NULL)) {
  831. BIO_printf(bio_err, "error generating serial number\n");
  832. goto end;
  833. }
  834. } else {
  835. serial = load_serial(serialfile, NULL, create_ser, NULL);
  836. if (serial == NULL) {
  837. BIO_printf(bio_err, "error while loading serial number\n");
  838. goto end;
  839. }
  840. if (verbose) {
  841. if (BN_is_zero(serial)) {
  842. BIO_printf(bio_err, "next serial number is 00\n");
  843. } else {
  844. if ((f = BN_bn2hex(serial)) == NULL)
  845. goto end;
  846. BIO_printf(bio_err, "next serial number is %s\n", f);
  847. OPENSSL_free(f);
  848. }
  849. }
  850. }
  851. if ((attribs = NCONF_get_section(conf, policy)) == NULL) {
  852. BIO_printf(bio_err, "unable to find 'section' for %s\n", policy);
  853. goto end;
  854. }
  855. if ((cert_sk = sk_X509_new_null()) == NULL) {
  856. BIO_printf(bio_err, "Memory allocation failure\n");
  857. goto end;
  858. }
  859. if (spkac_file != NULL) {
  860. total++;
  861. j = certify_spkac(&x, spkac_file, pkey, x509, dgst, sigopts,
  862. attribs, db, serial, subj, chtype, multirdn,
  863. email_dn, startdate, enddate, days, extensions,
  864. conf, verbose, certopt, get_nameopt(), default_op,
  865. ext_copy, dateopt);
  866. if (j < 0)
  867. goto end;
  868. if (j > 0) {
  869. total_done++;
  870. BIO_printf(bio_err, "\n");
  871. if (!BN_add_word(serial, 1))
  872. goto end;
  873. if (!sk_X509_push(cert_sk, x)) {
  874. BIO_printf(bio_err, "Memory allocation failure\n");
  875. goto end;
  876. }
  877. }
  878. }
  879. if (ss_cert_file != NULL) {
  880. total++;
  881. j = certify_cert(&x, ss_cert_file, certformat, passin, pkey,
  882. x509, dgst, sigopts, vfyopts, attribs,
  883. db, serial, subj, chtype, multirdn, email_dn,
  884. startdate, enddate, days, batch, extensions,
  885. conf, verbose, certopt, get_nameopt(), default_op,
  886. ext_copy, dateopt);
  887. if (j < 0)
  888. goto end;
  889. if (j > 0) {
  890. total_done++;
  891. BIO_printf(bio_err, "\n");
  892. if (!BN_add_word(serial, 1))
  893. goto end;
  894. if (!sk_X509_push(cert_sk, x)) {
  895. BIO_printf(bio_err, "Memory allocation failure\n");
  896. goto end;
  897. }
  898. }
  899. }
  900. if (infile != NULL) {
  901. total++;
  902. j = certify(&x, infile, informat, pkey, x509p, dgst,
  903. sigopts, vfyopts, attribs, db,
  904. serial, subj, chtype, multirdn, email_dn, startdate,
  905. enddate, days, batch, extensions, conf, verbose,
  906. certopt, get_nameopt(), default_op, ext_copy, selfsign, dateopt);
  907. if (j < 0)
  908. goto end;
  909. if (j > 0) {
  910. total_done++;
  911. BIO_printf(bio_err, "\n");
  912. if (!BN_add_word(serial, 1))
  913. goto end;
  914. if (!sk_X509_push(cert_sk, x)) {
  915. BIO_printf(bio_err, "Memory allocation failure\n");
  916. goto end;
  917. }
  918. }
  919. }
  920. for (i = 0; i < argc; i++) {
  921. total++;
  922. j = certify(&x, argv[i], informat, pkey, x509p, dgst,
  923. sigopts, vfyopts,
  924. attribs, db,
  925. serial, subj, chtype, multirdn, email_dn, startdate,
  926. enddate, days, batch, extensions, conf, verbose,
  927. certopt, get_nameopt(), default_op, ext_copy, selfsign, dateopt);
  928. if (j < 0)
  929. goto end;
  930. if (j > 0) {
  931. total_done++;
  932. BIO_printf(bio_err, "\n");
  933. if (!BN_add_word(serial, 1)) {
  934. X509_free(x);
  935. goto end;
  936. }
  937. if (!sk_X509_push(cert_sk, x)) {
  938. BIO_printf(bio_err, "Memory allocation failure\n");
  939. X509_free(x);
  940. goto end;
  941. }
  942. }
  943. }
  944. /*
  945. * we have a stack of newly certified certificates and a database
  946. * and serial number that need updating
  947. */
  948. if (sk_X509_num(cert_sk) > 0) {
  949. if (!batch) {
  950. BIO_printf(bio_err,
  951. "\n%d out of %d certificate requests certified, commit? [y/n]",
  952. total_done, total);
  953. (void)BIO_flush(bio_err);
  954. tmp[0] = '\0';
  955. if (fgets(tmp, sizeof(tmp), stdin) == NULL) {
  956. BIO_printf(bio_err, "CERTIFICATION CANCELED: I/O error\n");
  957. ret = 0;
  958. goto end;
  959. }
  960. if (tmp[0] != 'y' && tmp[0] != 'Y') {
  961. BIO_printf(bio_err, "CERTIFICATION CANCELED\n");
  962. ret = 0;
  963. goto end;
  964. }
  965. }
  966. BIO_printf(bio_err, "Write out database with %d new entries\n",
  967. sk_X509_num(cert_sk));
  968. if (serialfile != NULL
  969. && !save_serial(serialfile, "new", serial, NULL))
  970. goto end;
  971. if (!save_index(dbfile, "new", db))
  972. goto end;
  973. }
  974. outdirlen = OPENSSL_strlcpy(new_cert, outdir, sizeof(new_cert));
  975. #ifndef OPENSSL_SYS_VMS
  976. outdirlen = OPENSSL_strlcat(new_cert, "/", sizeof(new_cert));
  977. #endif
  978. if (verbose)
  979. BIO_printf(bio_err, "writing new certificates\n");
  980. for (i = 0; i < sk_X509_num(cert_sk); i++) {
  981. BIO *Cout = NULL;
  982. X509 *xi = sk_X509_value(cert_sk, i);
  983. const ASN1_INTEGER *serialNumber = X509_get0_serialNumber(xi);
  984. const unsigned char *psn = ASN1_STRING_get0_data(serialNumber);
  985. const int snl = ASN1_STRING_length(serialNumber);
  986. const int filen_len = 2 * (snl > 0 ? snl : 1) + sizeof(".pem");
  987. char *n = new_cert + outdirlen;
  988. if (outdirlen + filen_len > PATH_MAX) {
  989. BIO_printf(bio_err, "certificate file name too long\n");
  990. goto end;
  991. }
  992. if (snl > 0) {
  993. static const char HEX_DIGITS[] = "0123456789ABCDEF";
  994. for (j = 0; j < snl; j++, psn++) {
  995. *n++ = HEX_DIGITS[*psn >> 4];
  996. *n++ = HEX_DIGITS[*psn & 0x0F];
  997. }
  998. } else {
  999. *(n++) = '0';
  1000. *(n++) = '0';
  1001. }
  1002. *(n++) = '.';
  1003. *(n++) = 'p';
  1004. *(n++) = 'e';
  1005. *(n++) = 'm';
  1006. *n = '\0'; /* closing new_cert */
  1007. if (verbose)
  1008. BIO_printf(bio_err, "writing %s\n", new_cert);
  1009. Sout = bio_open_default(outfile, 'w',
  1010. output_der ? FORMAT_ASN1 : FORMAT_TEXT);
  1011. if (Sout == NULL)
  1012. goto end;
  1013. Cout = BIO_new_file(new_cert, "w");
  1014. if (Cout == NULL) {
  1015. perror(new_cert);
  1016. goto end;
  1017. }
  1018. write_new_certificate(Cout, xi, 0, notext);
  1019. write_new_certificate(Sout, xi, output_der, notext);
  1020. BIO_free_all(Cout);
  1021. BIO_free_all(Sout);
  1022. Sout = NULL;
  1023. }
  1024. if (sk_X509_num(cert_sk)) {
  1025. /* Rename the database and the serial file */
  1026. if (serialfile != NULL
  1027. && !rotate_serial(serialfile, "new", "old"))
  1028. goto end;
  1029. if (!rotate_index(dbfile, "new", "old"))
  1030. goto end;
  1031. BIO_printf(bio_err, "Database updated\n");
  1032. }
  1033. }
  1034. /*****************************************************************/
  1035. if (gencrl) {
  1036. int crl_v2 = 0;
  1037. if (crl_ext == NULL)
  1038. crl_ext = app_conf_try_string(conf, section, ENV_CRLEXT);
  1039. if (crl_ext != NULL) {
  1040. /* Check syntax of file */
  1041. X509V3_CTX ctx;
  1042. X509V3_set_ctx_test(&ctx);
  1043. X509V3_set_nconf(&ctx, conf);
  1044. if (!X509V3_EXT_add_nconf(conf, &ctx, crl_ext, NULL)) {
  1045. BIO_printf(bio_err,
  1046. "Error checking CRL extension section %s\n", crl_ext);
  1047. ret = 1;
  1048. goto end;
  1049. }
  1050. }
  1051. crlnumberfile = app_conf_try_string(conf, section, ENV_CRLNUMBER);
  1052. if (crlnumberfile != NULL) {
  1053. if ((crlnumber = load_serial(crlnumberfile, NULL, 0, NULL))
  1054. == NULL) {
  1055. BIO_printf(bio_err, "error while loading CRL number\n");
  1056. goto end;
  1057. }
  1058. }
  1059. if (!crldays && !crlhours && !crlsec) {
  1060. if (!app_conf_try_number(conf, section,
  1061. ENV_DEFAULT_CRL_DAYS, &crldays))
  1062. crldays = 0;
  1063. if (!app_conf_try_number(conf, section,
  1064. ENV_DEFAULT_CRL_HOURS, &crlhours))
  1065. crlhours = 0;
  1066. }
  1067. if ((crl_nextupdate == NULL) &&
  1068. (crldays == 0) && (crlhours == 0) && (crlsec == 0)) {
  1069. BIO_printf(bio_err,
  1070. "cannot lookup how long until the next CRL is issued\n");
  1071. goto end;
  1072. }
  1073. if (verbose)
  1074. BIO_printf(bio_err, "making CRL\n");
  1075. if ((crl = X509_CRL_new_ex(app_get0_libctx(), app_get0_propq())) == NULL)
  1076. goto end;
  1077. if (!X509_CRL_set_issuer_name(crl, X509_get_subject_name(x509)))
  1078. goto end;
  1079. if (!set_crl_lastupdate(crl, crl_lastupdate)) {
  1080. BIO_puts(bio_err, "error setting CRL lastUpdate\n");
  1081. ret = 1;
  1082. goto end;
  1083. }
  1084. if (!set_crl_nextupdate(crl, crl_nextupdate,
  1085. crldays, crlhours, crlsec)) {
  1086. BIO_puts(bio_err, "error setting CRL nextUpdate\n");
  1087. ret = 1;
  1088. goto end;
  1089. }
  1090. for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
  1091. pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
  1092. if (pp[DB_type][0] == DB_TYPE_REV) {
  1093. if ((r = X509_REVOKED_new()) == NULL)
  1094. goto end;
  1095. j = make_revoked(r, pp[DB_rev_date]);
  1096. if (!j)
  1097. goto end;
  1098. if (j == 2)
  1099. crl_v2 = 1;
  1100. if (!BN_hex2bn(&serial, pp[DB_serial]))
  1101. goto end;
  1102. tmpser = BN_to_ASN1_INTEGER(serial, NULL);
  1103. BN_free(serial);
  1104. serial = NULL;
  1105. if (!tmpser)
  1106. goto end;
  1107. X509_REVOKED_set_serialNumber(r, tmpser);
  1108. ASN1_INTEGER_free(tmpser);
  1109. X509_CRL_add0_revoked(crl, r);
  1110. }
  1111. }
  1112. /*
  1113. * sort the data so it will be written in serial number order
  1114. */
  1115. X509_CRL_sort(crl);
  1116. /* we now have a CRL */
  1117. if (verbose)
  1118. BIO_printf(bio_err, "signing CRL\n");
  1119. /* Add any extensions asked for */
  1120. if (crl_ext != NULL || crlnumberfile != NULL) {
  1121. X509V3_CTX crlctx;
  1122. X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0);
  1123. X509V3_set_nconf(&crlctx, conf);
  1124. if (crl_ext != NULL)
  1125. if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx, crl_ext, crl)) {
  1126. BIO_printf(bio_err,
  1127. "Error adding CRL extensions from section %s\n", crl_ext);
  1128. goto end;
  1129. }
  1130. if (crlnumberfile != NULL) {
  1131. tmpser = BN_to_ASN1_INTEGER(crlnumber, NULL);
  1132. if (!tmpser)
  1133. goto end;
  1134. X509_CRL_add1_ext_i2d(crl, NID_crl_number, tmpser, 0, 0);
  1135. ASN1_INTEGER_free(tmpser);
  1136. crl_v2 = 1;
  1137. if (!BN_add_word(crlnumber, 1))
  1138. goto end;
  1139. }
  1140. }
  1141. if (crl_ext != NULL || crl_v2) {
  1142. if (!X509_CRL_set_version(crl, X509_CRL_VERSION_2))
  1143. goto end;
  1144. }
  1145. /* we have a CRL number that need updating */
  1146. if (crlnumberfile != NULL
  1147. && !save_serial(crlnumberfile, "new", crlnumber, NULL))
  1148. goto end;
  1149. BN_free(crlnumber);
  1150. crlnumber = NULL;
  1151. if (!do_X509_CRL_sign(crl, pkey, dgst, sigopts))
  1152. goto end;
  1153. Sout = bio_open_default(outfile, 'w',
  1154. output_der ? FORMAT_ASN1 : FORMAT_TEXT);
  1155. if (Sout == NULL)
  1156. goto end;
  1157. PEM_write_bio_X509_CRL(Sout, crl);
  1158. /* Rename the crlnumber file */
  1159. if (crlnumberfile != NULL
  1160. && !rotate_serial(crlnumberfile, "new", "old"))
  1161. goto end;
  1162. }
  1163. /*****************************************************************/
  1164. if (dorevoke) {
  1165. if (infile == NULL) {
  1166. BIO_printf(bio_err, "no input files\n");
  1167. goto end;
  1168. } else {
  1169. X509 *revcert;
  1170. revcert = load_cert_pass(infile, informat, 1, passin,
  1171. "certificate to be revoked");
  1172. if (revcert == NULL)
  1173. goto end;
  1174. if (dorevoke == 2)
  1175. rev_type = REV_VALID;
  1176. j = do_revoke(revcert, db, rev_type, rev_arg);
  1177. if (j <= 0)
  1178. goto end;
  1179. X509_free(revcert);
  1180. if (!save_index(dbfile, "new", db))
  1181. goto end;
  1182. if (!rotate_index(dbfile, "new", "old"))
  1183. goto end;
  1184. BIO_printf(bio_err, "Database updated\n");
  1185. }
  1186. }
  1187. ret = 0;
  1188. end:
  1189. if (ret)
  1190. ERR_print_errors(bio_err);
  1191. BIO_free_all(Sout);
  1192. BIO_free_all(out);
  1193. BIO_free_all(in);
  1194. OSSL_STACK_OF_X509_free(cert_sk);
  1195. cleanse(passin);
  1196. if (free_passin)
  1197. OPENSSL_free(passin);
  1198. BN_free(serial);
  1199. BN_free(crlnumber);
  1200. free_index(db);
  1201. sk_OPENSSL_STRING_free(sigopts);
  1202. sk_OPENSSL_STRING_free(vfyopts);
  1203. EVP_PKEY_free(pkey);
  1204. X509_free(x509);
  1205. X509_CRL_free(crl);
  1206. NCONF_free(conf);
  1207. NCONF_free(extfile_conf);
  1208. release_engine(e);
  1209. return ret;
  1210. }
  1211. static char *lookup_conf(const CONF *conf, const char *section, const char *tag)
  1212. {
  1213. char *entry = NCONF_get_string(conf, section, tag);
  1214. if (entry == NULL)
  1215. BIO_printf(bio_err, "variable lookup failed for %s::%s\n", section, tag);
  1216. return entry;
  1217. }
  1218. static int certify(X509 **xret, const char *infile, int informat,
  1219. EVP_PKEY *pkey, X509 *x509,
  1220. const char *dgst,
  1221. STACK_OF(OPENSSL_STRING) *sigopts,
  1222. STACK_OF(OPENSSL_STRING) *vfyopts,
  1223. STACK_OF(CONF_VALUE) *policy, CA_DB *db,
  1224. BIGNUM *serial, const char *subj, unsigned long chtype,
  1225. int multirdn, int email_dn, const char *startdate,
  1226. const char *enddate,
  1227. long days, int batch, const char *ext_sect, CONF *lconf,
  1228. int verbose, unsigned long certopt, unsigned long nameopt,
  1229. int default_op, int ext_copy, int selfsign, unsigned long dateopt)
  1230. {
  1231. X509_REQ *req = NULL;
  1232. EVP_PKEY *pktmp = NULL;
  1233. int ok = -1, i;
  1234. req = load_csr_autofmt(infile, informat, vfyopts, "certificate request");
  1235. if (req == NULL)
  1236. goto end;
  1237. if ((pktmp = X509_REQ_get0_pubkey(req)) == NULL) {
  1238. BIO_printf(bio_err, "Error unpacking public key\n");
  1239. goto end;
  1240. }
  1241. if (verbose)
  1242. X509_REQ_print_ex(bio_err, req, nameopt, X509_FLAG_COMPAT);
  1243. BIO_printf(bio_err, "Check that the request matches the signature\n");
  1244. ok = 0;
  1245. if (selfsign && !X509_REQ_check_private_key(req, pkey)) {
  1246. BIO_printf(bio_err,
  1247. "Certificate request and CA private key do not match\n");
  1248. goto end;
  1249. }
  1250. i = do_X509_REQ_verify(req, pktmp, vfyopts);
  1251. if (i < 0) {
  1252. BIO_printf(bio_err, "Signature verification problems...\n");
  1253. goto end;
  1254. }
  1255. if (i == 0) {
  1256. BIO_printf(bio_err,
  1257. "Signature did not match the certificate request\n");
  1258. goto end;
  1259. }
  1260. BIO_printf(bio_err, "Signature ok\n");
  1261. ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
  1262. chtype, multirdn, email_dn, startdate, enddate, days, batch,
  1263. verbose, req, ext_sect, lconf, certopt, nameopt, default_op,
  1264. ext_copy, selfsign, dateopt);
  1265. end:
  1266. ERR_print_errors(bio_err);
  1267. X509_REQ_free(req);
  1268. return ok;
  1269. }
  1270. static int certify_cert(X509 **xret, const char *infile, int certformat,
  1271. const char *passin, EVP_PKEY *pkey, X509 *x509,
  1272. const char *dgst,
  1273. STACK_OF(OPENSSL_STRING) *sigopts,
  1274. STACK_OF(OPENSSL_STRING) *vfyopts,
  1275. STACK_OF(CONF_VALUE) *policy, CA_DB *db,
  1276. BIGNUM *serial, const char *subj, unsigned long chtype,
  1277. int multirdn, int email_dn, const char *startdate,
  1278. const char *enddate, long days, int batch, const char *ext_sect,
  1279. CONF *lconf, int verbose, unsigned long certopt,
  1280. unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt)
  1281. {
  1282. X509 *template_cert = NULL;
  1283. X509_REQ *rreq = NULL;
  1284. EVP_PKEY *pktmp = NULL;
  1285. int ok = -1, i;
  1286. if ((template_cert = load_cert_pass(infile, certformat, 1, passin,
  1287. "template certificate")) == NULL)
  1288. goto end;
  1289. if (verbose)
  1290. X509_print(bio_err, template_cert);
  1291. BIO_printf(bio_err, "Check that the request matches the signature\n");
  1292. if ((pktmp = X509_get0_pubkey(template_cert)) == NULL) {
  1293. BIO_printf(bio_err, "error unpacking public key\n");
  1294. goto end;
  1295. }
  1296. i = do_X509_verify(template_cert, pktmp, vfyopts);
  1297. if (i < 0) {
  1298. ok = 0;
  1299. BIO_printf(bio_err, "Signature verification problems....\n");
  1300. goto end;
  1301. }
  1302. if (i == 0) {
  1303. ok = 0;
  1304. BIO_printf(bio_err, "Signature did not match the certificate\n");
  1305. goto end;
  1306. } else {
  1307. BIO_printf(bio_err, "Signature ok\n");
  1308. }
  1309. if ((rreq = X509_to_X509_REQ(template_cert, NULL, NULL)) == NULL)
  1310. goto end;
  1311. ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
  1312. chtype, multirdn, email_dn, startdate, enddate, days, batch,
  1313. verbose, rreq, ext_sect, lconf, certopt, nameopt, default_op,
  1314. ext_copy, 0, dateopt);
  1315. end:
  1316. X509_REQ_free(rreq);
  1317. X509_free(template_cert);
  1318. return ok;
  1319. }
  1320. static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
  1321. const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
  1322. STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial,
  1323. const char *subj, unsigned long chtype, int multirdn,
  1324. int email_dn, const char *startdate, const char *enddate, long days,
  1325. int batch, int verbose, X509_REQ *req, const char *ext_sect,
  1326. CONF *lconf, unsigned long certopt, unsigned long nameopt,
  1327. int default_op, int ext_copy, int selfsign, unsigned long dateopt)
  1328. {
  1329. const X509_NAME *name = NULL;
  1330. X509_NAME *CAname = NULL, *subject = NULL;
  1331. const ASN1_TIME *tm;
  1332. ASN1_STRING *str, *str2;
  1333. ASN1_OBJECT *obj;
  1334. X509 *ret = NULL;
  1335. X509_NAME_ENTRY *ne, *tne;
  1336. EVP_PKEY *pktmp;
  1337. int ok = -1, i, j, last, nid;
  1338. const char *p;
  1339. CONF_VALUE *cv;
  1340. OPENSSL_STRING row[DB_NUMBER];
  1341. OPENSSL_STRING *irow = NULL;
  1342. OPENSSL_STRING *rrow = NULL;
  1343. char buf[25];
  1344. X509V3_CTX ext_ctx;
  1345. for (i = 0; i < DB_NUMBER; i++)
  1346. row[i] = NULL;
  1347. if (subj) {
  1348. X509_NAME *n = parse_name(subj, chtype, multirdn, "subject");
  1349. if (!n)
  1350. goto end;
  1351. X509_REQ_set_subject_name(req, n);
  1352. X509_NAME_free(n);
  1353. }
  1354. if (default_op)
  1355. BIO_printf(bio_err, "The Subject's Distinguished Name is as follows\n");
  1356. name = X509_REQ_get_subject_name(req);
  1357. for (i = 0; i < X509_NAME_entry_count(name); i++) {
  1358. ne = X509_NAME_get_entry(name, i);
  1359. str = X509_NAME_ENTRY_get_data(ne);
  1360. obj = X509_NAME_ENTRY_get_object(ne);
  1361. nid = OBJ_obj2nid(obj);
  1362. if (msie_hack) {
  1363. /* assume all type should be strings */
  1364. if (str->type == V_ASN1_UNIVERSALSTRING)
  1365. ASN1_UNIVERSALSTRING_to_string(str);
  1366. if (str->type == V_ASN1_IA5STRING && nid != NID_pkcs9_emailAddress)
  1367. str->type = V_ASN1_T61STRING;
  1368. if (nid == NID_pkcs9_emailAddress
  1369. && str->type == V_ASN1_PRINTABLESTRING)
  1370. str->type = V_ASN1_IA5STRING;
  1371. }
  1372. /* If no EMAIL is wanted in the subject */
  1373. if (nid == NID_pkcs9_emailAddress && !email_dn)
  1374. continue;
  1375. /* check some things */
  1376. if (nid == NID_pkcs9_emailAddress && str->type != V_ASN1_IA5STRING) {
  1377. BIO_printf(bio_err,
  1378. "\nemailAddress type needs to be of type IA5STRING\n");
  1379. goto end;
  1380. }
  1381. if (str->type != V_ASN1_BMPSTRING && str->type != V_ASN1_UTF8STRING) {
  1382. j = ASN1_PRINTABLE_type(str->data, str->length);
  1383. if ((j == V_ASN1_T61STRING && str->type != V_ASN1_T61STRING) ||
  1384. (j == V_ASN1_IA5STRING && str->type == V_ASN1_PRINTABLESTRING))
  1385. {
  1386. BIO_printf(bio_err,
  1387. "\nThe string contains characters that are illegal for the ASN.1 type\n");
  1388. goto end;
  1389. }
  1390. }
  1391. if (default_op)
  1392. old_entry_print(obj, str);
  1393. }
  1394. /* Ok, now we check the 'policy' stuff. */
  1395. if ((subject = X509_NAME_new()) == NULL) {
  1396. BIO_printf(bio_err, "Memory allocation failure\n");
  1397. goto end;
  1398. }
  1399. /* take a copy of the issuer name before we mess with it. */
  1400. if (selfsign)
  1401. CAname = X509_NAME_dup(name);
  1402. else
  1403. CAname = X509_NAME_dup(X509_get_subject_name(x509));
  1404. if (CAname == NULL)
  1405. goto end;
  1406. str = str2 = NULL;
  1407. for (i = 0; i < sk_CONF_VALUE_num(policy); i++) {
  1408. cv = sk_CONF_VALUE_value(policy, i); /* get the object id */
  1409. if ((j = OBJ_txt2nid(cv->name)) == NID_undef) {
  1410. BIO_printf(bio_err,
  1411. "%s:unknown object type in 'policy' configuration\n",
  1412. cv->name);
  1413. goto end;
  1414. }
  1415. obj = OBJ_nid2obj(j);
  1416. last = -1;
  1417. for (;;) {
  1418. X509_NAME_ENTRY *push = NULL;
  1419. /* lookup the object in the supplied name list */
  1420. j = X509_NAME_get_index_by_OBJ(name, obj, last);
  1421. if (j < 0) {
  1422. if (last != -1)
  1423. break;
  1424. tne = NULL;
  1425. } else {
  1426. tne = X509_NAME_get_entry(name, j);
  1427. }
  1428. last = j;
  1429. /* depending on the 'policy', decide what to do. */
  1430. if (strcmp(cv->value, "optional") == 0) {
  1431. if (tne != NULL)
  1432. push = tne;
  1433. } else if (strcmp(cv->value, "supplied") == 0) {
  1434. if (tne == NULL) {
  1435. BIO_printf(bio_err,
  1436. "The %s field needed to be supplied and was missing\n",
  1437. cv->name);
  1438. goto end;
  1439. } else {
  1440. push = tne;
  1441. }
  1442. } else if (strcmp(cv->value, "match") == 0) {
  1443. int last2;
  1444. if (tne == NULL) {
  1445. BIO_printf(bio_err,
  1446. "The mandatory %s field was missing\n",
  1447. cv->name);
  1448. goto end;
  1449. }
  1450. last2 = -1;
  1451. again2:
  1452. j = X509_NAME_get_index_by_OBJ(CAname, obj, last2);
  1453. if ((j < 0) && (last2 == -1)) {
  1454. BIO_printf(bio_err,
  1455. "The %s field does not exist in the CA certificate,\n"
  1456. "the 'policy' is misconfigured\n", cv->name);
  1457. goto end;
  1458. }
  1459. if (j >= 0) {
  1460. push = X509_NAME_get_entry(CAname, j);
  1461. str = X509_NAME_ENTRY_get_data(tne);
  1462. str2 = X509_NAME_ENTRY_get_data(push);
  1463. last2 = j;
  1464. if (ASN1_STRING_cmp(str, str2) != 0)
  1465. goto again2;
  1466. }
  1467. if (j < 0) {
  1468. BIO_printf(bio_err,
  1469. "The %s field is different between\n"
  1470. "CA certificate (%s) and the request (%s)\n",
  1471. cv->name,
  1472. ((str2 == NULL) ? "NULL" : (char *)str2->data),
  1473. ((str == NULL) ? "NULL" : (char *)str->data));
  1474. goto end;
  1475. }
  1476. } else {
  1477. BIO_printf(bio_err,
  1478. "%s:invalid type in 'policy' configuration\n",
  1479. cv->value);
  1480. goto end;
  1481. }
  1482. if (push != NULL) {
  1483. if (!X509_NAME_add_entry(subject, push, -1, 0)) {
  1484. BIO_printf(bio_err, "Memory allocation failure\n");
  1485. goto end;
  1486. }
  1487. }
  1488. if (j < 0)
  1489. break;
  1490. }
  1491. }
  1492. if (preserve) {
  1493. X509_NAME_free(subject);
  1494. /* subject=X509_NAME_dup(X509_REQ_get_subject_name(req)); */
  1495. subject = X509_NAME_dup(name);
  1496. if (subject == NULL)
  1497. goto end;
  1498. }
  1499. /* We are now totally happy, lets make and sign the certificate */
  1500. if (verbose)
  1501. BIO_printf(bio_err,
  1502. "Everything appears to be ok, creating and signing the certificate\n");
  1503. if ((ret = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL)
  1504. goto end;
  1505. if (BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(ret)) == NULL)
  1506. goto end;
  1507. if (selfsign) {
  1508. if (!X509_set_issuer_name(ret, subject))
  1509. goto end;
  1510. } else {
  1511. if (!X509_set_issuer_name(ret, X509_get_subject_name(x509)))
  1512. goto end;
  1513. }
  1514. if (!set_cert_times(ret, startdate, enddate, days))
  1515. goto end;
  1516. if (enddate != NULL) {
  1517. int tdays;
  1518. if (!ASN1_TIME_diff(&tdays, NULL, NULL, X509_get0_notAfter(ret)))
  1519. goto end;
  1520. days = tdays;
  1521. }
  1522. if (!X509_set_subject_name(ret, subject))
  1523. goto end;
  1524. pktmp = X509_REQ_get0_pubkey(req);
  1525. i = X509_set_pubkey(ret, pktmp);
  1526. if (!i)
  1527. goto end;
  1528. /* Initialize the context structure */
  1529. X509V3_set_ctx(&ext_ctx, selfsign ? ret : x509,
  1530. ret, NULL /* no need to give req, needed info is in ret */,
  1531. NULL, X509V3_CTX_REPLACE);
  1532. /* prepare fallback for AKID, but only if issuer cert equals subject cert */
  1533. if (selfsign) {
  1534. if (!X509V3_set_issuer_pkey(&ext_ctx, pkey))
  1535. goto end;
  1536. if (!cert_matches_key(ret, pkey))
  1537. BIO_printf(bio_err,
  1538. "Warning: Signature key and public key of cert do not match\n");
  1539. }
  1540. /* Lets add the extensions, if there are any */
  1541. if (ext_sect) {
  1542. if (extfile_conf != NULL) {
  1543. if (verbose)
  1544. BIO_printf(bio_err, "Extra configuration file found\n");
  1545. /* Use the extfile_conf configuration db LHASH */
  1546. X509V3_set_nconf(&ext_ctx, extfile_conf);
  1547. /* Adds exts contained in the configuration file */
  1548. if (!X509V3_EXT_add_nconf(extfile_conf, &ext_ctx, ext_sect, ret)) {
  1549. BIO_printf(bio_err,
  1550. "Error adding certificate extensions from extfile section %s\n",
  1551. ext_sect);
  1552. goto end;
  1553. }
  1554. if (verbose)
  1555. BIO_printf(bio_err,
  1556. "Successfully added extensions from file.\n");
  1557. } else if (ext_sect) {
  1558. /* We found extensions to be set from config file */
  1559. X509V3_set_nconf(&ext_ctx, lconf);
  1560. if (!X509V3_EXT_add_nconf(lconf, &ext_ctx, ext_sect, ret)) {
  1561. BIO_printf(bio_err,
  1562. "Error adding certificate extensions from config section %s\n",
  1563. ext_sect);
  1564. goto end;
  1565. }
  1566. if (verbose)
  1567. BIO_printf(bio_err,
  1568. "Successfully added extensions from config\n");
  1569. }
  1570. }
  1571. /* Copy extensions from request (if any) */
  1572. if (!copy_extensions(ret, req, ext_copy)) {
  1573. BIO_printf(bio_err, "ERROR: adding extensions from request\n");
  1574. goto end;
  1575. }
  1576. if (verbose)
  1577. BIO_printf(bio_err,
  1578. "The subject name appears to be ok, checking database for clashes\n");
  1579. /* Build the correct Subject if no e-mail is wanted in the subject. */
  1580. if (!email_dn) {
  1581. X509_NAME_ENTRY *tmpne;
  1582. X509_NAME *dn_subject;
  1583. /*
  1584. * Its best to dup the subject DN and then delete any email addresses
  1585. * because this retains its structure.
  1586. */
  1587. if ((dn_subject = X509_NAME_dup(subject)) == NULL) {
  1588. BIO_printf(bio_err, "Memory allocation failure\n");
  1589. goto end;
  1590. }
  1591. i = -1;
  1592. while ((i = X509_NAME_get_index_by_NID(dn_subject,
  1593. NID_pkcs9_emailAddress,
  1594. i)) >= 0) {
  1595. tmpne = X509_NAME_delete_entry(dn_subject, i--);
  1596. X509_NAME_ENTRY_free(tmpne);
  1597. }
  1598. if (!X509_set_subject_name(ret, dn_subject)) {
  1599. X509_NAME_free(dn_subject);
  1600. goto end;
  1601. }
  1602. X509_NAME_free(dn_subject);
  1603. }
  1604. row[DB_name] = X509_NAME_oneline(X509_get_subject_name(ret), NULL, 0);
  1605. if (row[DB_name] == NULL) {
  1606. BIO_printf(bio_err, "Memory allocation failure\n");
  1607. goto end;
  1608. }
  1609. if (BN_is_zero(serial))
  1610. row[DB_serial] = OPENSSL_strdup("00");
  1611. else
  1612. row[DB_serial] = BN_bn2hex(serial);
  1613. if (row[DB_serial] == NULL) {
  1614. BIO_printf(bio_err, "Memory allocation failure\n");
  1615. goto end;
  1616. }
  1617. if (row[DB_name][0] == '\0') {
  1618. /*
  1619. * An empty subject! We'll use the serial number instead. If
  1620. * unique_subject is in use then we don't want different entries with
  1621. * empty subjects matching each other.
  1622. */
  1623. OPENSSL_free(row[DB_name]);
  1624. row[DB_name] = OPENSSL_strdup(row[DB_serial]);
  1625. if (row[DB_name] == NULL) {
  1626. BIO_printf(bio_err, "Memory allocation failure\n");
  1627. goto end;
  1628. }
  1629. }
  1630. if (db->attributes.unique_subject) {
  1631. OPENSSL_STRING *crow = row;
  1632. rrow = TXT_DB_get_by_index(db->db, DB_name, crow);
  1633. if (rrow != NULL) {
  1634. BIO_printf(bio_err,
  1635. "ERROR:There is already a certificate for %s\n",
  1636. row[DB_name]);
  1637. }
  1638. }
  1639. if (rrow == NULL) {
  1640. rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
  1641. if (rrow != NULL) {
  1642. BIO_printf(bio_err,
  1643. "ERROR:Serial number %s has already been issued,\n",
  1644. row[DB_serial]);
  1645. BIO_printf(bio_err,
  1646. " check the database/serial_file for corruption\n");
  1647. }
  1648. }
  1649. if (rrow != NULL) {
  1650. BIO_printf(bio_err, "The matching entry has the following details\n");
  1651. if (rrow[DB_type][0] == DB_TYPE_EXP)
  1652. p = "Expired";
  1653. else if (rrow[DB_type][0] == DB_TYPE_REV)
  1654. p = "Revoked";
  1655. else if (rrow[DB_type][0] == DB_TYPE_VAL)
  1656. p = "Valid";
  1657. else
  1658. p = "\ninvalid type, Database error\n";
  1659. BIO_printf(bio_err, "Type :%s\n", p);
  1660. if (rrow[DB_type][0] == DB_TYPE_REV) {
  1661. p = rrow[DB_exp_date];
  1662. if (p == NULL)
  1663. p = "undef";
  1664. BIO_printf(bio_err, "Was revoked on:%s\n", p);
  1665. }
  1666. p = rrow[DB_exp_date];
  1667. if (p == NULL)
  1668. p = "undef";
  1669. BIO_printf(bio_err, "Expires on :%s\n", p);
  1670. p = rrow[DB_serial];
  1671. if (p == NULL)
  1672. p = "undef";
  1673. BIO_printf(bio_err, "Serial Number :%s\n", p);
  1674. p = rrow[DB_file];
  1675. if (p == NULL)
  1676. p = "undef";
  1677. BIO_printf(bio_err, "File name :%s\n", p);
  1678. p = rrow[DB_name];
  1679. if (p == NULL)
  1680. p = "undef";
  1681. BIO_printf(bio_err, "Subject Name :%s\n", p);
  1682. ok = -1; /* This is now a 'bad' error. */
  1683. goto end;
  1684. }
  1685. if (!default_op) {
  1686. BIO_printf(bio_err, "Certificate Details:\n");
  1687. /*
  1688. * Never print signature details because signature not present
  1689. */
  1690. certopt |= X509_FLAG_NO_SIGDUMP | X509_FLAG_NO_SIGNAME;
  1691. X509_print_ex(bio_err, ret, nameopt, certopt);
  1692. }
  1693. BIO_printf(bio_err, "Certificate is to be certified until ");
  1694. ASN1_TIME_print_ex(bio_err, X509_get0_notAfter(ret), dateopt);
  1695. if (days)
  1696. BIO_printf(bio_err, " (%ld days)", days);
  1697. BIO_printf(bio_err, "\n");
  1698. if (!batch) {
  1699. BIO_printf(bio_err, "Sign the certificate? [y/n]:");
  1700. (void)BIO_flush(bio_err);
  1701. buf[0] = '\0';
  1702. if (fgets(buf, sizeof(buf), stdin) == NULL) {
  1703. BIO_printf(bio_err,
  1704. "CERTIFICATE WILL NOT BE CERTIFIED: I/O error\n");
  1705. ok = 0;
  1706. goto end;
  1707. }
  1708. if (!(buf[0] == 'y' || buf[0] == 'Y')) {
  1709. BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED\n");
  1710. ok = 0;
  1711. goto end;
  1712. }
  1713. }
  1714. pktmp = X509_get0_pubkey(ret);
  1715. if (EVP_PKEY_missing_parameters(pktmp) &&
  1716. !EVP_PKEY_missing_parameters(pkey))
  1717. EVP_PKEY_copy_parameters(pktmp, pkey);
  1718. if (!do_X509_sign(ret, 0, pkey, dgst, sigopts, &ext_ctx))
  1719. goto end;
  1720. /* We now just add it to the database as DB_TYPE_VAL('V') */
  1721. row[DB_type] = OPENSSL_strdup("V");
  1722. tm = X509_get0_notAfter(ret);
  1723. row[DB_exp_date] = app_malloc(tm->length + 1, "row expdate");
  1724. memcpy(row[DB_exp_date], tm->data, tm->length);
  1725. row[DB_exp_date][tm->length] = '\0';
  1726. row[DB_rev_date] = NULL;
  1727. row[DB_file] = OPENSSL_strdup("unknown");
  1728. if ((row[DB_type] == NULL) || (row[DB_file] == NULL)
  1729. || (row[DB_name] == NULL)) {
  1730. BIO_printf(bio_err, "Memory allocation failure\n");
  1731. goto end;
  1732. }
  1733. irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row space");
  1734. for (i = 0; i < DB_NUMBER; i++)
  1735. irow[i] = row[i];
  1736. irow[DB_NUMBER] = NULL;
  1737. if (!TXT_DB_insert(db->db, irow)) {
  1738. BIO_printf(bio_err, "failed to update database\n");
  1739. BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
  1740. goto end;
  1741. }
  1742. irow = NULL;
  1743. ok = 1;
  1744. end:
  1745. if (ok != 1) {
  1746. for (i = 0; i < DB_NUMBER; i++)
  1747. OPENSSL_free(row[i]);
  1748. }
  1749. OPENSSL_free(irow);
  1750. X509_NAME_free(CAname);
  1751. X509_NAME_free(subject);
  1752. if (ok <= 0)
  1753. X509_free(ret);
  1754. else
  1755. *xret = ret;
  1756. return ok;
  1757. }
  1758. static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext)
  1759. {
  1760. if (output_der) {
  1761. (void)i2d_X509_bio(bp, x);
  1762. return;
  1763. }
  1764. if (!notext)
  1765. X509_print(bp, x);
  1766. PEM_write_bio_X509(bp, x);
  1767. }
  1768. static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey,
  1769. X509 *x509, const char *dgst,
  1770. STACK_OF(OPENSSL_STRING) *sigopts,
  1771. STACK_OF(CONF_VALUE) *policy, CA_DB *db,
  1772. BIGNUM *serial, const char *subj, unsigned long chtype,
  1773. int multirdn, int email_dn, const char *startdate,
  1774. const char *enddate, long days, const char *ext_sect,
  1775. CONF *lconf, int verbose, unsigned long certopt,
  1776. unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt)
  1777. {
  1778. STACK_OF(CONF_VALUE) *sk = NULL;
  1779. LHASH_OF(CONF_VALUE) *parms = NULL;
  1780. X509_REQ *req = NULL;
  1781. CONF_VALUE *cv = NULL;
  1782. NETSCAPE_SPKI *spki = NULL;
  1783. char *type, *buf;
  1784. EVP_PKEY *pktmp = NULL;
  1785. X509_NAME *n = NULL;
  1786. X509_NAME_ENTRY *ne = NULL;
  1787. int ok = -1, i, j;
  1788. long errline;
  1789. int nid;
  1790. /*
  1791. * Load input file into a hash table. (This is just an easy
  1792. * way to read and parse the file, then put it into a convenient
  1793. * STACK format).
  1794. */
  1795. parms = CONF_load(NULL, infile, &errline);
  1796. if (parms == NULL) {
  1797. BIO_printf(bio_err, "error on line %ld of %s\n", errline, infile);
  1798. goto end;
  1799. }
  1800. sk = CONF_get_section(parms, "default");
  1801. if (sk_CONF_VALUE_num(sk) == 0) {
  1802. BIO_printf(bio_err, "no name/value pairs found in %s\n", infile);
  1803. goto end;
  1804. }
  1805. /*
  1806. * Now create a dummy X509 request structure. We don't actually
  1807. * have an X509 request, but we have many of the components
  1808. * (a public key, various DN components). The idea is that we
  1809. * put these components into the right X509 request structure
  1810. * and we can use the same code as if you had a real X509 request.
  1811. */
  1812. req = X509_REQ_new();
  1813. if (req == NULL)
  1814. goto end;
  1815. /*
  1816. * Build up the subject name set.
  1817. */
  1818. n = X509_REQ_get_subject_name(req);
  1819. for (i = 0;; i++) {
  1820. if (sk_CONF_VALUE_num(sk) <= i)
  1821. break;
  1822. cv = sk_CONF_VALUE_value(sk, i);
  1823. type = cv->name;
  1824. /*
  1825. * Skip past any leading X. X: X, etc to allow for multiple instances
  1826. */
  1827. for (buf = cv->name; *buf; buf++)
  1828. if ((*buf == ':') || (*buf == ',') || (*buf == '.')) {
  1829. buf++;
  1830. if (*buf)
  1831. type = buf;
  1832. break;
  1833. }
  1834. buf = cv->value;
  1835. if ((nid = OBJ_txt2nid(type)) == NID_undef) {
  1836. if (strcmp(type, "SPKAC") == 0) {
  1837. spki = NETSCAPE_SPKI_b64_decode(cv->value, -1);
  1838. if (spki == NULL) {
  1839. BIO_printf(bio_err,
  1840. "unable to load Netscape SPKAC structure\n");
  1841. goto end;
  1842. }
  1843. }
  1844. continue;
  1845. }
  1846. if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
  1847. (unsigned char *)buf, -1, -1, 0))
  1848. goto end;
  1849. }
  1850. if (spki == NULL) {
  1851. BIO_printf(bio_err, "Netscape SPKAC structure not found in %s\n",
  1852. infile);
  1853. goto end;
  1854. }
  1855. /*
  1856. * Now extract the key from the SPKI structure.
  1857. */
  1858. BIO_printf(bio_err, "Check that the SPKAC request matches the signature\n");
  1859. if ((pktmp = NETSCAPE_SPKI_get_pubkey(spki)) == NULL) {
  1860. BIO_printf(bio_err, "error unpacking SPKAC public key\n");
  1861. goto end;
  1862. }
  1863. j = NETSCAPE_SPKI_verify(spki, pktmp);
  1864. if (j <= 0) {
  1865. EVP_PKEY_free(pktmp);
  1866. BIO_printf(bio_err,
  1867. "signature verification failed on SPKAC public key\n");
  1868. goto end;
  1869. }
  1870. BIO_printf(bio_err, "Signature ok\n");
  1871. X509_REQ_set_pubkey(req, pktmp);
  1872. EVP_PKEY_free(pktmp);
  1873. ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
  1874. chtype, multirdn, email_dn, startdate, enddate, days, 1,
  1875. verbose, req, ext_sect, lconf, certopt, nameopt, default_op,
  1876. ext_copy, 0, dateopt);
  1877. end:
  1878. X509_REQ_free(req);
  1879. CONF_free(parms);
  1880. NETSCAPE_SPKI_free(spki);
  1881. X509_NAME_ENTRY_free(ne);
  1882. return ok;
  1883. }
  1884. static int check_time_format(const char *str)
  1885. {
  1886. return ASN1_TIME_set_string(NULL, str);
  1887. }
  1888. static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type,
  1889. const char *value)
  1890. {
  1891. const ASN1_TIME *tm = NULL;
  1892. char *row[DB_NUMBER], **rrow, **irow;
  1893. char *rev_str = NULL;
  1894. BIGNUM *bn = NULL;
  1895. int ok = -1, i;
  1896. for (i = 0; i < DB_NUMBER; i++)
  1897. row[i] = NULL;
  1898. row[DB_name] = X509_NAME_oneline(X509_get_subject_name(x509), NULL, 0);
  1899. bn = ASN1_INTEGER_to_BN(X509_get0_serialNumber(x509), NULL);
  1900. if (!bn)
  1901. goto end;
  1902. if (BN_is_zero(bn))
  1903. row[DB_serial] = OPENSSL_strdup("00");
  1904. else
  1905. row[DB_serial] = BN_bn2hex(bn);
  1906. BN_free(bn);
  1907. if (row[DB_name] != NULL && row[DB_name][0] == '\0') {
  1908. /* Entries with empty Subjects actually use the serial number instead */
  1909. OPENSSL_free(row[DB_name]);
  1910. row[DB_name] = OPENSSL_strdup(row[DB_serial]);
  1911. }
  1912. if ((row[DB_name] == NULL) || (row[DB_serial] == NULL)) {
  1913. BIO_printf(bio_err, "Memory allocation failure\n");
  1914. goto end;
  1915. }
  1916. /*
  1917. * We have to lookup by serial number because name lookup skips revoked
  1918. * certs
  1919. */
  1920. rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
  1921. if (rrow == NULL) {
  1922. BIO_printf(bio_err,
  1923. "Adding Entry with serial number %s to DB for %s\n",
  1924. row[DB_serial], row[DB_name]);
  1925. /* We now just add it to the database as DB_TYPE_REV('V') */
  1926. row[DB_type] = OPENSSL_strdup("V");
  1927. tm = X509_get0_notAfter(x509);
  1928. row[DB_exp_date] = app_malloc(tm->length + 1, "row exp_data");
  1929. memcpy(row[DB_exp_date], tm->data, tm->length);
  1930. row[DB_exp_date][tm->length] = '\0';
  1931. row[DB_rev_date] = NULL;
  1932. row[DB_file] = OPENSSL_strdup("unknown");
  1933. if (row[DB_type] == NULL || row[DB_file] == NULL) {
  1934. BIO_printf(bio_err, "Memory allocation failure\n");
  1935. goto end;
  1936. }
  1937. irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row ptr");
  1938. for (i = 0; i < DB_NUMBER; i++)
  1939. irow[i] = row[i];
  1940. irow[DB_NUMBER] = NULL;
  1941. if (!TXT_DB_insert(db->db, irow)) {
  1942. BIO_printf(bio_err, "failed to update database\n");
  1943. BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
  1944. OPENSSL_free(irow);
  1945. goto end;
  1946. }
  1947. for (i = 0; i < DB_NUMBER; i++)
  1948. row[i] = NULL;
  1949. /* Revoke Certificate */
  1950. if (rev_type == REV_VALID)
  1951. ok = 1;
  1952. else
  1953. /* Retry revocation after DB insertion */
  1954. ok = do_revoke(x509, db, rev_type, value);
  1955. goto end;
  1956. } else if (index_name_cmp_noconst(row, rrow)) {
  1957. BIO_printf(bio_err, "ERROR:name does not match %s\n", row[DB_name]);
  1958. goto end;
  1959. } else if (rev_type == REV_VALID) {
  1960. BIO_printf(bio_err, "ERROR:Already present, serial number %s\n",
  1961. row[DB_serial]);
  1962. goto end;
  1963. } else if (rrow[DB_type][0] == DB_TYPE_REV) {
  1964. BIO_printf(bio_err, "ERROR:Already revoked, serial number %s\n",
  1965. row[DB_serial]);
  1966. goto end;
  1967. } else {
  1968. BIO_printf(bio_err, "Revoking Certificate %s.\n", rrow[DB_serial]);
  1969. rev_str = make_revocation_str(rev_type, value);
  1970. if (!rev_str) {
  1971. BIO_printf(bio_err, "Error in revocation arguments\n");
  1972. goto end;
  1973. }
  1974. rrow[DB_type][0] = DB_TYPE_REV;
  1975. rrow[DB_type][1] = '\0';
  1976. rrow[DB_rev_date] = rev_str;
  1977. }
  1978. ok = 1;
  1979. end:
  1980. for (i = 0; i < DB_NUMBER; i++)
  1981. OPENSSL_free(row[i]);
  1982. return ok;
  1983. }
  1984. static int get_certificate_status(const char *serial, CA_DB *db)
  1985. {
  1986. char *row[DB_NUMBER], **rrow;
  1987. int ok = -1, i;
  1988. size_t serial_len = strlen(serial);
  1989. /* Free Resources */
  1990. for (i = 0; i < DB_NUMBER; i++)
  1991. row[i] = NULL;
  1992. /* Malloc needed char spaces */
  1993. row[DB_serial] = app_malloc(serial_len + 2, "row serial#");
  1994. if (serial_len % 2) {
  1995. /*
  1996. * Set the first char to 0
  1997. */
  1998. row[DB_serial][0] = '0';
  1999. /* Copy String from serial to row[DB_serial] */
  2000. memcpy(row[DB_serial] + 1, serial, serial_len);
  2001. row[DB_serial][serial_len + 1] = '\0';
  2002. } else {
  2003. /* Copy String from serial to row[DB_serial] */
  2004. memcpy(row[DB_serial], serial, serial_len);
  2005. row[DB_serial][serial_len] = '\0';
  2006. }
  2007. /* Make it Upper Case */
  2008. make_uppercase(row[DB_serial]);
  2009. ok = 1;
  2010. /* Search for the certificate */
  2011. rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
  2012. if (rrow == NULL) {
  2013. BIO_printf(bio_err, "Serial %s not present in db.\n", row[DB_serial]);
  2014. ok = -1;
  2015. goto end;
  2016. } else if (rrow[DB_type][0] == DB_TYPE_VAL) {
  2017. BIO_printf(bio_err, "%s=Valid (%c)\n",
  2018. row[DB_serial], rrow[DB_type][0]);
  2019. goto end;
  2020. } else if (rrow[DB_type][0] == DB_TYPE_REV) {
  2021. BIO_printf(bio_err, "%s=Revoked (%c)\n",
  2022. row[DB_serial], rrow[DB_type][0]);
  2023. goto end;
  2024. } else if (rrow[DB_type][0] == DB_TYPE_EXP) {
  2025. BIO_printf(bio_err, "%s=Expired (%c)\n",
  2026. row[DB_serial], rrow[DB_type][0]);
  2027. goto end;
  2028. } else if (rrow[DB_type][0] == DB_TYPE_SUSP) {
  2029. BIO_printf(bio_err, "%s=Suspended (%c)\n",
  2030. row[DB_serial], rrow[DB_type][0]);
  2031. goto end;
  2032. } else {
  2033. BIO_printf(bio_err, "%s=Unknown (%c).\n",
  2034. row[DB_serial], rrow[DB_type][0]);
  2035. ok = -1;
  2036. }
  2037. end:
  2038. for (i = 0; i < DB_NUMBER; i++) {
  2039. OPENSSL_free(row[i]);
  2040. }
  2041. return ok;
  2042. }
  2043. int do_updatedb(CA_DB *db, time_t *now)
  2044. {
  2045. ASN1_TIME *a_tm = NULL;
  2046. int i, cnt = 0;
  2047. char **rrow;
  2048. a_tm = ASN1_TIME_new();
  2049. if (a_tm == NULL)
  2050. return -1;
  2051. /* get actual time */
  2052. if (X509_time_adj(a_tm, 0, now) == NULL) {
  2053. ASN1_TIME_free(a_tm);
  2054. return -1;
  2055. }
  2056. for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
  2057. rrow = sk_OPENSSL_PSTRING_value(db->db->data, i);
  2058. if (rrow[DB_type][0] == DB_TYPE_VAL) {
  2059. /* ignore entries that are not valid */
  2060. ASN1_TIME *exp_date = NULL;
  2061. exp_date = ASN1_TIME_new();
  2062. if (exp_date == NULL) {
  2063. ASN1_TIME_free(a_tm);
  2064. return -1;
  2065. }
  2066. if (!ASN1_TIME_set_string(exp_date, rrow[DB_exp_date])) {
  2067. ASN1_TIME_free(a_tm);
  2068. ASN1_TIME_free(exp_date);
  2069. return -1;
  2070. }
  2071. if (ASN1_TIME_compare(exp_date, a_tm) <= 0) {
  2072. rrow[DB_type][0] = DB_TYPE_EXP;
  2073. rrow[DB_type][1] = '\0';
  2074. cnt++;
  2075. BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]);
  2076. }
  2077. ASN1_TIME_free(exp_date);
  2078. }
  2079. }
  2080. ASN1_TIME_free(a_tm);
  2081. return cnt;
  2082. }
  2083. static const char *crl_reasons[] = {
  2084. /* CRL reason strings */
  2085. "unspecified",
  2086. "keyCompromise",
  2087. "CACompromise",
  2088. "affiliationChanged",
  2089. "superseded",
  2090. "cessationOfOperation",
  2091. "certificateHold",
  2092. "removeFromCRL",
  2093. /* Additional pseudo reasons */
  2094. "holdInstruction",
  2095. "keyTime",
  2096. "CAkeyTime"
  2097. };
  2098. #define NUM_REASONS OSSL_NELEM(crl_reasons)
  2099. /*
  2100. * Given revocation information convert to a DB string. The format of the
  2101. * string is: revtime[,reason,extra]. Where 'revtime' is the revocation time
  2102. * (the current time). 'reason' is the optional CRL reason and 'extra' is any
  2103. * additional argument
  2104. */
  2105. static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg)
  2106. {
  2107. char *str;
  2108. const char *reason = NULL, *other = NULL;
  2109. ASN1_OBJECT *otmp;
  2110. ASN1_UTCTIME *revtm = NULL;
  2111. int i;
  2112. switch (rev_type) {
  2113. case REV_NONE:
  2114. case REV_VALID:
  2115. break;
  2116. case REV_CRL_REASON:
  2117. for (i = 0; i < 8; i++) {
  2118. if (OPENSSL_strcasecmp(rev_arg, crl_reasons[i]) == 0) {
  2119. reason = crl_reasons[i];
  2120. break;
  2121. }
  2122. }
  2123. if (reason == NULL) {
  2124. BIO_printf(bio_err, "Unknown CRL reason %s\n", rev_arg);
  2125. return NULL;
  2126. }
  2127. break;
  2128. case REV_HOLD:
  2129. /* Argument is an OID */
  2130. otmp = OBJ_txt2obj(rev_arg, 0);
  2131. ASN1_OBJECT_free(otmp);
  2132. if (otmp == NULL) {
  2133. BIO_printf(bio_err, "Invalid object identifier %s\n", rev_arg);
  2134. return NULL;
  2135. }
  2136. reason = "holdInstruction";
  2137. other = rev_arg;
  2138. break;
  2139. case REV_KEY_COMPROMISE:
  2140. case REV_CA_COMPROMISE:
  2141. /* Argument is the key compromise time */
  2142. if (!ASN1_GENERALIZEDTIME_set_string(NULL, rev_arg)) {
  2143. BIO_printf(bio_err,
  2144. "Invalid time format %s. Need YYYYMMDDHHMMSSZ\n",
  2145. rev_arg);
  2146. return NULL;
  2147. }
  2148. other = rev_arg;
  2149. if (rev_type == REV_KEY_COMPROMISE)
  2150. reason = "keyTime";
  2151. else
  2152. reason = "CAkeyTime";
  2153. break;
  2154. }
  2155. revtm = X509_gmtime_adj(NULL, 0);
  2156. if (!revtm)
  2157. return NULL;
  2158. i = revtm->length + 1;
  2159. if (reason)
  2160. i += strlen(reason) + 1;
  2161. if (other)
  2162. i += strlen(other) + 1;
  2163. str = app_malloc(i, "revocation reason");
  2164. OPENSSL_strlcpy(str, (char *)revtm->data, i);
  2165. if (reason) {
  2166. OPENSSL_strlcat(str, ",", i);
  2167. OPENSSL_strlcat(str, reason, i);
  2168. }
  2169. if (other) {
  2170. OPENSSL_strlcat(str, ",", i);
  2171. OPENSSL_strlcat(str, other, i);
  2172. }
  2173. ASN1_UTCTIME_free(revtm);
  2174. return str;
  2175. }
  2176. /*-
  2177. * Convert revocation field to X509_REVOKED entry
  2178. * return code:
  2179. * 0 error
  2180. * 1 OK
  2181. * 2 OK and some extensions added (i.e. V2 CRL)
  2182. */
  2183. static int make_revoked(X509_REVOKED *rev, const char *str)
  2184. {
  2185. char *tmp = NULL;
  2186. int reason_code = -1;
  2187. int i, ret = 0;
  2188. ASN1_OBJECT *hold = NULL;
  2189. ASN1_GENERALIZEDTIME *comp_time = NULL;
  2190. ASN1_ENUMERATED *rtmp = NULL;
  2191. ASN1_TIME *revDate = NULL;
  2192. i = unpack_revinfo(&revDate, &reason_code, &hold, &comp_time, str);
  2193. if (i == 0)
  2194. goto end;
  2195. if (rev && !X509_REVOKED_set_revocationDate(rev, revDate))
  2196. goto end;
  2197. if (rev && (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)) {
  2198. rtmp = ASN1_ENUMERATED_new();
  2199. if (rtmp == NULL || !ASN1_ENUMERATED_set(rtmp, reason_code))
  2200. goto end;
  2201. if (X509_REVOKED_add1_ext_i2d(rev, NID_crl_reason, rtmp, 0, 0) <= 0)
  2202. goto end;
  2203. }
  2204. if (rev && comp_time) {
  2205. if (X509_REVOKED_add1_ext_i2d
  2206. (rev, NID_invalidity_date, comp_time, 0, 0) <= 0)
  2207. goto end;
  2208. }
  2209. if (rev && hold) {
  2210. if (X509_REVOKED_add1_ext_i2d
  2211. (rev, NID_hold_instruction_code, hold, 0, 0) <= 0)
  2212. goto end;
  2213. }
  2214. if (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)
  2215. ret = 2;
  2216. else
  2217. ret = 1;
  2218. end:
  2219. OPENSSL_free(tmp);
  2220. ASN1_OBJECT_free(hold);
  2221. ASN1_GENERALIZEDTIME_free(comp_time);
  2222. ASN1_ENUMERATED_free(rtmp);
  2223. ASN1_TIME_free(revDate);
  2224. return ret;
  2225. }
  2226. static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str)
  2227. {
  2228. char buf[25], *pbuf;
  2229. const char *p;
  2230. int j;
  2231. j = i2a_ASN1_OBJECT(bio_err, obj);
  2232. pbuf = buf;
  2233. for (j = 22 - j; j > 0; j--)
  2234. *(pbuf++) = ' ';
  2235. *(pbuf++) = ':';
  2236. *(pbuf++) = '\0';
  2237. BIO_puts(bio_err, buf);
  2238. if (str->type == V_ASN1_PRINTABLESTRING)
  2239. BIO_printf(bio_err, "PRINTABLE:'");
  2240. else if (str->type == V_ASN1_T61STRING)
  2241. BIO_printf(bio_err, "T61STRING:'");
  2242. else if (str->type == V_ASN1_IA5STRING)
  2243. BIO_printf(bio_err, "IA5STRING:'");
  2244. else if (str->type == V_ASN1_UNIVERSALSTRING)
  2245. BIO_printf(bio_err, "UNIVERSALSTRING:'");
  2246. else
  2247. BIO_printf(bio_err, "ASN.1 %2d:'", str->type);
  2248. p = (const char *)str->data;
  2249. for (j = str->length; j > 0; j--) {
  2250. if ((*p >= ' ') && (*p <= '~'))
  2251. BIO_printf(bio_err, "%c", *p);
  2252. else if (*p & 0x80)
  2253. BIO_printf(bio_err, "\\0x%02X", *p);
  2254. else if ((unsigned char)*p == 0xf7)
  2255. BIO_printf(bio_err, "^?");
  2256. else
  2257. BIO_printf(bio_err, "^%c", *p + '@');
  2258. p++;
  2259. }
  2260. BIO_printf(bio_err, "'\n");
  2261. return 1;
  2262. }
  2263. int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold,
  2264. ASN1_GENERALIZEDTIME **pinvtm, const char *str)
  2265. {
  2266. char *tmp;
  2267. char *rtime_str, *reason_str = NULL, *arg_str = NULL, *p;
  2268. int reason_code = -1;
  2269. int ret = 0;
  2270. unsigned int i;
  2271. ASN1_OBJECT *hold = NULL;
  2272. ASN1_GENERALIZEDTIME *comp_time = NULL;
  2273. tmp = OPENSSL_strdup(str);
  2274. if (!tmp) {
  2275. BIO_printf(bio_err, "memory allocation failure\n");
  2276. goto end;
  2277. }
  2278. p = strchr(tmp, ',');
  2279. rtime_str = tmp;
  2280. if (p) {
  2281. *p = '\0';
  2282. p++;
  2283. reason_str = p;
  2284. p = strchr(p, ',');
  2285. if (p) {
  2286. *p = '\0';
  2287. arg_str = p + 1;
  2288. }
  2289. }
  2290. if (prevtm) {
  2291. *prevtm = ASN1_UTCTIME_new();
  2292. if (*prevtm == NULL) {
  2293. BIO_printf(bio_err, "memory allocation failure\n");
  2294. goto end;
  2295. }
  2296. if (!ASN1_UTCTIME_set_string(*prevtm, rtime_str)) {
  2297. BIO_printf(bio_err, "invalid revocation date %s\n", rtime_str);
  2298. goto end;
  2299. }
  2300. }
  2301. if (reason_str) {
  2302. for (i = 0; i < NUM_REASONS; i++) {
  2303. if (OPENSSL_strcasecmp(reason_str, crl_reasons[i]) == 0) {
  2304. reason_code = i;
  2305. break;
  2306. }
  2307. }
  2308. if (reason_code == OCSP_REVOKED_STATUS_NOSTATUS) {
  2309. BIO_printf(bio_err, "invalid reason code %s\n", reason_str);
  2310. goto end;
  2311. }
  2312. if (reason_code == 7) {
  2313. reason_code = OCSP_REVOKED_STATUS_REMOVEFROMCRL;
  2314. } else if (reason_code == 8) { /* Hold instruction */
  2315. if (!arg_str) {
  2316. BIO_printf(bio_err, "missing hold instruction\n");
  2317. goto end;
  2318. }
  2319. reason_code = OCSP_REVOKED_STATUS_CERTIFICATEHOLD;
  2320. hold = OBJ_txt2obj(arg_str, 0);
  2321. if (!hold) {
  2322. BIO_printf(bio_err, "invalid object identifier %s\n", arg_str);
  2323. goto end;
  2324. }
  2325. if (phold)
  2326. *phold = hold;
  2327. else
  2328. ASN1_OBJECT_free(hold);
  2329. } else if ((reason_code == 9) || (reason_code == 10)) {
  2330. if (!arg_str) {
  2331. BIO_printf(bio_err, "missing compromised time\n");
  2332. goto end;
  2333. }
  2334. comp_time = ASN1_GENERALIZEDTIME_new();
  2335. if (comp_time == NULL) {
  2336. BIO_printf(bio_err, "memory allocation failure\n");
  2337. goto end;
  2338. }
  2339. if (!ASN1_GENERALIZEDTIME_set_string(comp_time, arg_str)) {
  2340. BIO_printf(bio_err, "invalid compromised time %s\n", arg_str);
  2341. goto end;
  2342. }
  2343. if (reason_code == 9)
  2344. reason_code = OCSP_REVOKED_STATUS_KEYCOMPROMISE;
  2345. else
  2346. reason_code = OCSP_REVOKED_STATUS_CACOMPROMISE;
  2347. }
  2348. }
  2349. if (preason)
  2350. *preason = reason_code;
  2351. if (pinvtm) {
  2352. *pinvtm = comp_time;
  2353. comp_time = NULL;
  2354. }
  2355. ret = 1;
  2356. end:
  2357. OPENSSL_free(tmp);
  2358. ASN1_GENERALIZEDTIME_free(comp_time);
  2359. return ret;
  2360. }