tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

secutil.h (18354B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 #ifndef _SEC_UTIL_H_
      5 #define _SEC_UTIL_H_
      6 
      7 #include "seccomon.h"
      8 #include "secitem.h"
      9 #include "secport.h"
     10 #include "prerror.h"
     11 #include "base64.h"
     12 #include "keyhi.h"
     13 #include "secpkcs7.h"
     14 #include "secasn1.h"
     15 #include "secder.h"
     16 #include <stdio.h>
     17 
     18 #include "basicutil.h"
     19 #include "sslerr.h"
     20 #include "sslt.h"
     21 #include "blapi.h"
     22 
     23 #define SEC_CT_PRIVATE_KEY "private-key"
     24 #define SEC_CT_PUBLIC_KEY "public-key"
     25 #define SEC_CT_CERTIFICATE "certificate"
     26 #define SEC_CT_CERTIFICATE_REQUEST "certificate-request"
     27 #define SEC_CT_CERTIFICATE_ID "certificate-identity"
     28 #define SEC_CT_PKCS7 "pkcs7"
     29 #define SEC_CT_PKCS12 "pkcs12"
     30 #define SEC_CT_CRL "crl"
     31 #define SEC_CT_NAME "name"
     32 
     33 #define NS_CERTREQ_HEADER "-----BEGIN NEW CERTIFICATE REQUEST-----"
     34 #define NS_CERTREQ_TRAILER "-----END NEW CERTIFICATE REQUEST-----"
     35 
     36 #define NS_CERT_HEADER "-----BEGIN CERTIFICATE-----"
     37 #define NS_CERT_TRAILER "-----END CERTIFICATE-----"
     38 
     39 #define NS_CRL_HEADER "-----BEGIN CRL-----"
     40 #define NS_CRL_TRAILER "-----END CRL-----"
     41 
     42 #define SECU_Strerror PORT_ErrorToString
     43 /* where to wrap the columns when outputting Usage messages */
     44 #define SECU_MAX_COL_LEN 79
     45 
     46 typedef struct {
     47    enum {
     48        PW_NONE = 0,
     49        PW_FROMFILE = 1,
     50        PW_PLAINTEXT = 2,
     51        PW_EXTERNAL = 3
     52    } source;
     53    char *data;
     54 } secuPWData;
     55 
     56 /*
     57 ** Change a password on a token, or initialize a token with a password
     58 ** if it does not already have one.
     59 ** Use passwd to send the password in plaintext, pwFile to specify a
     60 ** file containing the password, or NULL for both to prompt the user.
     61 */
     62 SECStatus SECU_ChangePW(PK11SlotInfo *slot, char *passwd, char *pwFile);
     63 
     64 /*
     65 ** Change a password on a token, or initialize a token with a password
     66 ** if it does not already have one.
     67 ** In this function, you can specify both the old and new passwords
     68 ** as either a string or file. NOTE: any you don't specify will
     69 ** be prompted for
     70 */
     71 SECStatus SECU_ChangePW2(PK11SlotInfo *slot, char *oldPass, char *newPass,
     72                         char *oldPwFile, char *newPwFile);
     73 
     74 /*  These were stolen from the old sec.h... */
     75 /*
     76 ** Check a password for legitimacy. Passwords must be at least 8
     77 ** characters long and contain one non-alphabetic. Return DSTrue if the
     78 ** password is ok, DSFalse otherwise.
     79 */
     80 extern PRBool SEC_CheckPassword(char *password);
     81 
     82 /*
     83 ** Blind check of a password. Complement to SEC_CheckPassword which
     84 ** ignores length and content type, just retuning DSTrue is the password
     85 ** exists, DSFalse if NULL
     86 */
     87 extern PRBool SEC_BlindCheckPassword(char *password);
     88 
     89 /*
     90 ** Get a password.
     91 ** First prompt with "msg" on "out", then read the password from "in".
     92 ** The password is then checked using "chkpw".
     93 */
     94 extern char *SEC_GetPassword(FILE *in, FILE *out, char *msg,
     95                             PRBool (*chkpw)(char *));
     96 
     97 char *SECU_FilePasswd(PK11SlotInfo *slot, PRBool retry, void *arg);
     98 
     99 char *SECU_GetPasswordString(void *arg, char *prompt);
    100 
    101 /*
    102 ** Write a dongle password.
    103 ** Uses MD5 to hash constant system data (hostname, etc.), and then
    104 ** creates RC4 key to encrypt a password "pw" into a file "fd".
    105 */
    106 extern SECStatus SEC_WriteDongleFile(int fd, char *pw);
    107 
    108 /*
    109 ** Get a dongle password.
    110 ** Uses MD5 to hash constant system data (hostname, etc.), and then
    111 ** creates RC4 key to decrypt and return a password from file "fd".
    112 */
    113 extern char *SEC_ReadDongleFile(int fd);
    114 
    115 /* End stolen headers */
    116 
    117 /* Just sticks the two strings together with a / if needed */
    118 char *SECU_AppendFilenameToDir(char *dir, char *filename);
    119 
    120 /* Returns result of PR_GetEnvSecure("SSL_DIR") or NULL */
    121 extern char *SECU_DefaultSSLDir(void);
    122 
    123 /*
    124 ** Should be called once during initialization to set the default
    125 **    directory for looking for cert.db, key.db, and cert-nameidx.db files
    126 ** Removes trailing '/' in 'base'
    127 ** If 'base' is NULL, defaults to set to .netscape in home directory.
    128 */
    129 extern char *SECU_ConfigDirectory(const char *base);
    130 
    131 /*
    132 ** Basic callback function for SSL_GetClientAuthDataHook
    133 */
    134 extern int
    135 SECU_GetClientAuthData(void *arg, PRFileDesc *fd,
    136                       struct CERTDistNamesStr *caNames,
    137                       struct CERTCertificateStr **pRetCert,
    138                       struct SECKEYPrivateKeyStr **pRetKey);
    139 
    140 extern PRBool SECU_GetWrapEnabled(void);
    141 extern void SECU_EnableWrap(PRBool enable);
    142 
    143 extern PRBool SECU_GetUtf8DisplayEnabled(void);
    144 extern void SECU_EnableUtf8Display(PRBool enable);
    145 
    146 /* revalidate the cert and print information about cert verification
    147 * failure at time == now */
    148 extern void
    149 SECU_printCertProblems(FILE *outfile, CERTCertDBHandle *handle,
    150                       CERTCertificate *cert, PRBool checksig,
    151                       SECCertificateUsage certUsage, void *pinArg, PRBool verbose);
    152 
    153 /* revalidate the cert and print information about cert verification
    154 * failure at specified time */
    155 extern void
    156 SECU_printCertProblemsOnDate(FILE *outfile, CERTCertDBHandle *handle,
    157                             CERTCertificate *cert, PRBool checksig, SECCertificateUsage certUsage,
    158                             void *pinArg, PRBool verbose, PRTime datetime);
    159 
    160 /* print out CERTVerifyLog info. */
    161 extern void
    162 SECU_displayVerifyLog(FILE *outfile, CERTVerifyLog *log,
    163                      PRBool verbose);
    164 
    165 /* Read in a DER from a file, may be ascii  */
    166 extern SECStatus
    167 SECU_ReadDERFromFile(SECItem *der, PRFileDesc *inFile, PRBool ascii,
    168                     PRBool warnOnPrivateKeyInAsciiFile);
    169 
    170 /* Print integer value and hex */
    171 extern void SECU_PrintInteger(FILE *out, const SECItem *i, const char *m,
    172                              int level);
    173 
    174 /* Print ObjectIdentifier symbolically */
    175 extern SECOidTag SECU_PrintObjectID(FILE *out, const SECItem *oid,
    176                                    const char *m, int level);
    177 
    178 /* Print AlgorithmIdentifier symbolically */
    179 extern void SECU_PrintAlgorithmID(FILE *out, SECAlgorithmID *a, char *m,
    180                                  int level);
    181 
    182 /*
    183 * Format and print the UTC Time "t".  If the tag message "m" is not NULL,
    184 * do indent formatting based on "level" and add a newline afterward;
    185 * otherwise just print the formatted time string only.
    186 */
    187 extern void SECU_PrintUTCTime(FILE *out, const SECItem *t, const char *m,
    188                              int level);
    189 
    190 /*
    191 * Format and print the Generalized Time "t".  If the tag message "m"
    192 * is not NULL, * do indent formatting based on "level" and add a newline
    193 * afterward; otherwise just print the formatted time string only.
    194 */
    195 extern void SECU_PrintGeneralizedTime(FILE *out, const SECItem *t,
    196                                      const char *m, int level);
    197 
    198 /*
    199 * Format and print the UTC or Generalized Time "t".  If the tag message
    200 * "m" is not NULL, do indent formatting based on "level" and add a newline
    201 * afterward; otherwise just print the formatted time string only.
    202 */
    203 extern void SECU_PrintTimeChoice(FILE *out, const SECItem *t, const char *m,
    204                                 int level);
    205 
    206 /* callback for listing certs through pkcs11 */
    207 extern SECStatus SECU_PrintCertNickname(CERTCertListNode *cert, void *data);
    208 
    209 /* Dump all certificate nicknames in a database */
    210 extern SECStatus
    211 SECU_PrintCertificateNames(CERTCertDBHandle *handle, PRFileDesc *out,
    212                           PRBool sortByName, PRBool sortByTrust);
    213 
    214 /* See if nickname already in database. Return 1 true, 0 false, -1 error */
    215 int SECU_CheckCertNameExists(CERTCertDBHandle *handle, char *nickname);
    216 
    217 /* Dump contents of cert req */
    218 extern int SECU_PrintCertificateRequest(FILE *out, const SECItem *der, const char *m,
    219                                        int level);
    220 
    221 /* Dump contents of certificate */
    222 extern int SECU_PrintCertificate(FILE *out, const SECItem *der, const char *m,
    223                                 int level);
    224 
    225 extern int SECU_PrintCertificateBasicInfo(FILE *out, const SECItem *der, const char *m,
    226                                          int level);
    227 
    228 extern int SECU_PrintDumpDerIssuerAndSerial(FILE *out, const SECItem *der, const char *m,
    229                                            int level);
    230 
    231 /* Dump contents of a DER certificate name (issuer or subject) */
    232 extern int SECU_PrintDERName(FILE *out, SECItem *der, const char *m, int level);
    233 
    234 /* print trust flags on a cert */
    235 extern void SECU_PrintTrustFlags(FILE *out, CERTCertTrust *trust, char *m,
    236                                 int level);
    237 
    238 extern int SECU_PrintSubjectPublicKeyInfo(FILE *out, SECItem *der, char *m,
    239                                          int level);
    240 
    241 /* Dump contents of private key */
    242 extern int SECU_PrintPrivateKey(FILE *out, SECItem *der, char *m, int level);
    243 
    244 /* Dump contents of an RSA public key */
    245 extern void SECU_PrintRSAPublicKey(FILE *out, SECKEYPublicKey *pk, char *m, int level);
    246 
    247 /* Dump contents of a DSA public key */
    248 extern void SECU_PrintDSAPublicKey(FILE *out, SECKEYPublicKey *pk, char *m, int level);
    249 
    250 /* Dump contents of a ML-DSA public key */
    251 extern void SECU_PrintMLDSAPublicKey(FILE *out, SECKEYPublicKey *pk, char *m, int level);
    252 
    253 /* Print the MD5 and SHA1 fingerprints of a cert */
    254 extern int SECU_PrintFingerprints(FILE *out, SECItem *derCert, char *m,
    255                                  int level);
    256 
    257 /* Pretty-print any PKCS7 thing */
    258 extern int SECU_PrintPKCS7ContentInfo(FILE *out, SECItem *der, char *m,
    259                                      int level);
    260 /* Pretty-print a pkcs12 file */
    261 extern SECStatus SECU_PrintPKCS12(FILE *out, const SECItem *der, char *m, int level);
    262 /* Init PKCS11 stuff */
    263 extern SECStatus SECU_PKCS11Init(PRBool readOnly);
    264 
    265 /* Dump contents of signed data */
    266 extern int SECU_PrintSignedData(FILE *out, SECItem *der, const char *m,
    267                                int level, SECU_PPFunc inner);
    268 
    269 /* Dump contents of signed data, excluding the signature */
    270 extern int SECU_PrintSignedContent(FILE *out, SECItem *der, char *m, int level,
    271                                   SECU_PPFunc inner);
    272 
    273 /* Print cert data and its trust flags */
    274 extern SECStatus SEC_PrintCertificateAndTrust(CERTCertificate *cert,
    275                                              const char *label,
    276                                              CERTCertTrust *trust);
    277 
    278 extern int SECU_PrintCrl(FILE *out, const SECItem *der, const char *m, int level);
    279 
    280 extern void
    281 SECU_PrintCRLInfo(FILE *out, CERTCrl *crl, const char *m, int level);
    282 
    283 extern void SECU_PrintString(FILE *out, const SECItem *si, const char *m,
    284                             int level);
    285 extern void SECU_PrintAny(FILE *out, const SECItem *i, const char *m, int level);
    286 
    287 extern void SECU_PrintPolicy(FILE *out, SECItem *value, char *msg, int level);
    288 extern void SECU_PrintPrivKeyUsagePeriodExtension(FILE *out, SECItem *value,
    289                                                  char *msg, int level);
    290 
    291 extern void SECU_PrintExtensions(FILE *out, CERTCertExtension **extensions,
    292                                 char *msg, int level);
    293 
    294 extern void SECU_PrintNameQuotesOptional(FILE *out, CERTName *name,
    295                                         const char *msg, int level,
    296                                         PRBool quotes);
    297 extern void SECU_PrintName(FILE *out, CERTName *name, const char *msg,
    298                           int level);
    299 extern void SECU_PrintRDN(FILE *out, CERTRDN *rdn, const char *msg, int level);
    300 
    301 #ifdef SECU_GetPassword
    302 /* Convert a High public Key to a Low public Key */
    303 extern SECKEYLowPublicKey *SECU_ConvHighToLow(SECKEYPublicKey *pubHighKey);
    304 #endif
    305 
    306 extern char *SECU_GetModulePassword(PK11SlotInfo *slot, PRBool retry, void *arg);
    307 
    308 extern SECStatus DER_PrettyPrint(FILE *out, const SECItem *it, PRBool raw);
    309 
    310 extern char *SECU_SECModDBName(void);
    311 
    312 /* Fetch and register an oid if it hasn't been done already */
    313 extern void SECU_cert_fetchOID(SECOidTag *data, const SECOidData *src);
    314 
    315 extern SECStatus SECU_RegisterDynamicOids(void);
    316 
    317 /* Identifies hash algorithm tag by its string representation. */
    318 extern SECOidTag SECU_StringToSignatureAlgTag(const char *alg);
    319 
    320 /* Store CRL in output file or pk11 db. Also
    321 * encodes with base64 and exports to file if ascii flag is set
    322 * and file is not NULL. */
    323 extern SECStatus SECU_StoreCRL(PK11SlotInfo *slot, SECItem *derCrl,
    324                               PRFileDesc *outFile, PRBool ascii, char *url);
    325 
    326 /*
    327 ** DER sign a single block of data using private key encryption and the
    328 ** MD5 hashing algorithm. This routine first computes a digital signature
    329 ** using SEC_SignData, then wraps it with an CERTSignedData and then der
    330 ** encodes the result.
    331 **     "arena" is the memory arena to use to allocate data from
    332 **     "sd" returned CERTSignedData
    333 **     "result" the final der encoded data (memory is allocated)
    334 **     "buf" the input data to sign
    335 **     "len" the amount of data to sign
    336 **     "pk" the private key to encrypt with
    337 */
    338 extern SECStatus SECU_DerSignDataCRL(PLArenaPool *arena, CERTSignedData *sd,
    339                                     unsigned char *buf, int len,
    340                                     SECKEYPrivateKey *pk, SECOidTag algID);
    341 
    342 typedef enum {
    343    noKeyFound = 1,
    344    noSignatureMatch = 2,
    345    failToEncode = 3,
    346    failToSign = 4,
    347    noMem = 5
    348 } SignAndEncodeFuncExitStat;
    349 
    350 extern SECStatus
    351 SECU_SignAndEncodeCRL(CERTCertificate *issuer, CERTSignedCrl *signCrl,
    352                      SECOidTag hashAlgTag, SignAndEncodeFuncExitStat *resCode);
    353 
    354 extern SECStatus
    355 SECU_CopyCRL(PLArenaPool *destArena, CERTCrl *destCrl, CERTCrl *srcCrl);
    356 
    357 /*
    358 ** Finds the crl Authority Key Id extension. Returns NULL if no such extension
    359 ** was found.
    360 */
    361 CERTAuthKeyID *
    362 SECU_FindCRLAuthKeyIDExten(PLArenaPool *arena, CERTSignedCrl *crl);
    363 
    364 /*
    365 * Find the issuer of a crl. Cert usage should be checked before signing a crl.
    366 */
    367 CERTCertificate *
    368 SECU_FindCrlIssuer(CERTCertDBHandle *dbHandle, SECItem *subject,
    369                   CERTAuthKeyID *id, PRTime validTime);
    370 
    371 /* call back function used in encoding of an extension. Called from
    372 * SECU_EncodeAndAddExtensionValue */
    373 typedef SECStatus (*EXTEN_EXT_VALUE_ENCODER)(PLArenaPool *extHandleArena,
    374                                             void *value, SECItem *encodedValue);
    375 
    376 #define DECL_EXTEN_EXT_VALUE_ENCODER(mmm)                                \
    377    SECStatus EXTEN_EXT_VALUE_ENCODER_##mmm(PLArenaPool *extHandleArena, \
    378                                            void *value, SECItem *encodedValue);
    379 
    380 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodeAltNameExtension);
    381 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodeAuthKeyID);
    382 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodeBasicConstraintValue);
    383 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodeCRLDistributionPoints);
    384 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodeCertPoliciesExtension);
    385 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodeInfoAccessExtension);
    386 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodeInhibitAnyExtension);
    387 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodeNameConstraintsExtension);
    388 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodePolicyConstraintsExtension);
    389 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodePolicyMappingExtension);
    390 DECL_EXTEN_EXT_VALUE_ENCODER(CERT_EncodeSubjectKeyID);
    391 
    392 /* Encodes and adds extensions to the CRL or CRL entries. */
    393 SECStatus
    394 SECU_EncodeAndAddExtensionValue(PLArenaPool *arena, void *extHandle,
    395                                void *value, PRBool criticality, int extenType,
    396                                EXTEN_EXT_VALUE_ENCODER EncodeValueFn);
    397 
    398 /* Caller ensures that dst is at least item->len*2+1 bytes long */
    399 void
    400 SECU_SECItemToHex(const SECItem *item, char *dst);
    401 
    402 /* Requires 0x prefix. Case-insensitive. Will do in-place replacement if
    403 * successful */
    404 SECStatus
    405 SECU_SECItemHexStringToBinary(SECItem *srcdest);
    406 
    407 /* Parse a version range string, with "min" and "max" version numbers,
    408 * separated by colon (":"), and return the result in vr and v2.
    409 *
    410 * Both min and max values are optional.
    411 * The following syntax is used to specify the enabled protocol versions:
    412 * A string with only a max value is expected as ":{max}",
    413 * and all implemented versions less than or equal to max will be enabled.
    414 * A string with only a min value is expected as "{min}:",
    415 * and all implemented versions greater than or equal to min will be enabled.
    416 * A string consisting of a colon only means "all versions enabled".
    417 *
    418 * In order to avoid a link dependency from libsectool to libssl,
    419 * the caller must provide the desired default values for the min/max values,
    420 * by providing defaultVersionRange (which can be obtained from libssl by
    421 * calling SSL_VersionRangeGetSupported).
    422 */
    423 SECStatus
    424 SECU_ParseSSLVersionRangeString(const char *input,
    425                                const SSLVersionRange defaultVersionRange,
    426                                SSLVersionRange *vrange);
    427 
    428 SECStatus parseGroupList(const char *arg, SSLNamedGroup **enabledGroups,
    429                         unsigned int *enabledGroupsCount);
    430 SECStatus parseSigSchemeList(const char *arg,
    431                             const SSLSignatureScheme **enabledSigSchemes,
    432                             unsigned int *enabledSigSchemeCount);
    433 const char *SECU_NamedGroupToGroupName(SSLNamedGroup grp);
    434 const char *SECU_SignatureSchemeName(SSLSignatureScheme schmeme);
    435 const char *SECU_NamedGroupGetNextName(size_t i);
    436 const char *SECU_SignatureSchemeGetNextScheme(size_t i);
    437 
    438 typedef struct {
    439    SECItem label;
    440    PRBool hasContext;
    441    SECItem context;
    442    unsigned int outputLength;
    443 } secuExporter;
    444 
    445 SECStatus parseExporters(const char *arg,
    446                         const secuExporter **enabledExporters,
    447                         unsigned int *enabledExporterCount);
    448 
    449 SECStatus exportKeyingMaterials(PRFileDesc *fd,
    450                                const secuExporter *exporters,
    451                                unsigned int exporterCount);
    452 
    453 SECStatus readPSK(const char *arg, SECItem *psk, SECItem *label);
    454 
    455 /*
    456 *
    457 *  Error messaging
    458 *
    459 */
    460 
    461 void printflags(char *trusts, unsigned int flags);
    462 
    463 #if !defined(XP_UNIX)
    464 extern int ffs(unsigned int i);
    465 #endif
    466 
    467 /* Finds certificate by searching it in the DB or by examinig file
    468 * in the local directory. */
    469 CERTCertificate *
    470 SECU_FindCertByNicknameOrFilename(CERTCertDBHandle *handle,
    471                                  char *name, PRBool ascii,
    472                                  void *pwarg);
    473 #include "secerr.h"
    474 #include "sslerr.h"
    475 
    476 #endif /* _SEC_UTIL_H_ */