PageRenderTime 65ms CodeModel.GetById 11ms app.highlight 49ms RepoModel.GetById 1ms app.codeStats 0ms

/security/nss/cmd/lib/secutil.h

http://github.com/zpao/v8monkey
C Header | 464 lines | 199 code | 90 blank | 175 comment | 1 complexity | 2009420cfa3a3437863be69f752ccfe6 MD5 | raw file
  1/* ***** BEGIN LICENSE BLOCK *****
  2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3 *
  4 * The contents of this file are subject to the Mozilla Public License Version
  5 * 1.1 (the "License"); you may not use this file except in compliance with
  6 * the License. You may obtain a copy of the License at
  7 * http://www.mozilla.org/MPL/
  8 *
  9 * Software distributed under the License is distributed on an "AS IS" basis,
 10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 11 * for the specific language governing rights and limitations under the
 12 * License.
 13 *
 14 * The Original Code is the Netscape security libraries.
 15 *
 16 * The Initial Developer of the Original Code is
 17 * Netscape Communications Corporation.
 18 * Portions created by the Initial Developer are Copyright (C) 1994-2000
 19 * the Initial Developer. All Rights Reserved.
 20 *
 21 * Contributor(s):
 22 *
 23 * Alternatively, the contents of this file may be used under the terms of
 24 * either the GNU General Public License Version 2 or later (the "GPL"), or
 25 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 26 * in which case the provisions of the GPL or the LGPL are applicable instead
 27 * of those above. If you wish to allow use of your version of this file only
 28 * under the terms of either the GPL or the LGPL, and not to allow others to
 29 * use your version of this file under the terms of the MPL, indicate your
 30 * decision by deleting the provisions above and replace them with the notice
 31 * and other provisions required by the GPL or the LGPL. If you do not delete
 32 * the provisions above, a recipient may use your version of this file under
 33 * the terms of any one of the MPL, the GPL or the LGPL.
 34 *
 35 * ***** END LICENSE BLOCK ***** */
 36#ifndef _SEC_UTIL_H_
 37#define _SEC_UTIL_H_
 38
 39#include "seccomon.h"
 40#include "secitem.h"
 41#include "secport.h"
 42#include "prerror.h"
 43#include "base64.h"
 44#include "key.h"
 45#include "secpkcs7.h"
 46#include "secasn1.h"
 47#include "secder.h"
 48#include <stdio.h>
 49
 50#define SEC_CT_PRIVATE_KEY		"private-key"
 51#define SEC_CT_PUBLIC_KEY		"public-key"
 52#define SEC_CT_CERTIFICATE		"certificate"
 53#define SEC_CT_CERTIFICATE_REQUEST	"certificate-request"
 54#define SEC_CT_PKCS7			"pkcs7"
 55#define SEC_CT_CRL			"crl"
 56#define SEC_CT_NAME			"name"
 57
 58#define NS_CERTREQ_HEADER "-----BEGIN NEW CERTIFICATE REQUEST-----"
 59#define NS_CERTREQ_TRAILER "-----END NEW CERTIFICATE REQUEST-----"
 60
 61#define NS_CERT_HEADER "-----BEGIN CERTIFICATE-----"
 62#define NS_CERT_TRAILER "-----END CERTIFICATE-----"
 63
 64#define NS_CRL_HEADER  "-----BEGIN CRL-----"
 65#define NS_CRL_TRAILER "-----END CRL-----"
 66
 67#define SECU_Strerror PORT_ErrorToString
 68
 69#ifdef SECUTIL_NEW
 70typedef int (*SECU_PPFunc)(PRFileDesc *out, SECItem *item, 
 71                           char *msg, int level);
 72#else
 73typedef int (*SECU_PPFunc)(FILE *out, SECItem *item, char *msg, int level);
 74#endif
 75
 76typedef struct {
 77    enum {
 78	PW_NONE = 0,
 79	PW_FROMFILE = 1,
 80	PW_PLAINTEXT = 2,
 81	PW_EXTERNAL = 3
 82    } source;
 83    char *data;
 84} secuPWData;
 85
 86/*
 87** Change a password on a token, or initialize a token with a password
 88** if it does not already have one.
 89** Use passwd to send the password in plaintext, pwFile to specify a
 90** file containing the password, or NULL for both to prompt the user.
 91*/
 92SECStatus SECU_ChangePW(PK11SlotInfo *slot, char *passwd, char *pwFile);
 93
 94/*
 95** Change a password on a token, or initialize a token with a password
 96** if it does not already have one.
 97** In this function, you can specify both the old and new passwords
 98** as either a string or file. NOTE: any you don't specify will
 99** be prompted for
100*/
101SECStatus SECU_ChangePW2(PK11SlotInfo *slot, char *oldPass, char *newPass,
102                        char *oldPwFile, char *newPwFile);
103
104/*  These were stolen from the old sec.h... */
105/*
106** Check a password for legitimacy. Passwords must be at least 8
107** characters long and contain one non-alphabetic. Return DSTrue if the
108** password is ok, DSFalse otherwise.
109*/
110extern PRBool SEC_CheckPassword(char *password);
111
112/*
113** Blind check of a password. Complement to SEC_CheckPassword which 
114** ignores length and content type, just retuning DSTrue is the password
115** exists, DSFalse if NULL
116*/
117extern PRBool SEC_BlindCheckPassword(char *password);
118
119/*
120** Get a password.
121** First prompt with "msg" on "out", then read the password from "in".
122** The password is then checked using "chkpw".
123*/
124extern char *SEC_GetPassword(FILE *in, FILE *out, char *msg,
125				      PRBool (*chkpw)(char *));
126
127char *SECU_FilePasswd(PK11SlotInfo *slot, PRBool retry, void *arg);
128
129char *SECU_GetPasswordString(void *arg, char *prompt);
130
131/*
132** Write a dongle password.
133** Uses MD5 to hash constant system data (hostname, etc.), and then
134** creates RC4 key to encrypt a password "pw" into a file "fd".
135*/
136extern SECStatus SEC_WriteDongleFile(int fd, char *pw);
137
138/*
139** Get a dongle password.
140** Uses MD5 to hash constant system data (hostname, etc.), and then
141** creates RC4 key to decrypt and return a password from file "fd".
142*/
143extern char *SEC_ReadDongleFile(int fd);
144
145
146/* End stolen headers */
147
148/* Just sticks the two strings together with a / if needed */
149char *SECU_AppendFilenameToDir(char *dir, char *filename);
150
151/* Returns result of getenv("SSL_DIR") or NULL */
152extern char *SECU_DefaultSSLDir(void);
153
154/*
155** Should be called once during initialization to set the default 
156**    directory for looking for cert.db, key.db, and cert-nameidx.db files
157** Removes trailing '/' in 'base' 
158** If 'base' is NULL, defaults to set to .netscape in home directory.
159*/
160extern char *SECU_ConfigDirectory(const char* base);
161
162/* 
163** Basic callback function for SSL_GetClientAuthDataHook
164*/
165extern int
166SECU_GetClientAuthData(void *arg, PRFileDesc *fd,
167		       struct CERTDistNamesStr *caNames,
168		       struct CERTCertificateStr **pRetCert,
169		       struct SECKEYPrivateKeyStr **pRetKey);
170
171/* print out an error message */
172extern void SECU_PrintError(char *progName, char *msg, ...);
173
174/* print out a system error message */
175extern void SECU_PrintSystemError(char *progName, char *msg, ...);
176
177/* revalidate the cert and print information about cert verification
178 * failure at time == now */
179extern void
180SECU_printCertProblems(FILE *outfile, CERTCertDBHandle *handle, 
181	CERTCertificate *cert, PRBool checksig, 
182	SECCertificateUsage certUsage, void *pinArg, PRBool verbose);
183
184/* revalidate the cert and print information about cert verification
185 * failure at specified time */
186extern void
187SECU_printCertProblemsOnDate(FILE *outfile, CERTCertDBHandle *handle, 
188	CERTCertificate *cert, PRBool checksig, SECCertificateUsage certUsage, 
189	void *pinArg, PRBool verbose, PRTime datetime);
190
191/* print out CERTVerifyLog info. */
192extern void
193SECU_displayVerifyLog(FILE *outfile, CERTVerifyLog *log,
194                      PRBool verbose);
195
196/* Read the contents of a file into a SECItem */
197extern SECStatus SECU_FileToItem(SECItem *dst, PRFileDesc *src);
198extern SECStatus SECU_TextFileToItem(SECItem *dst, PRFileDesc *src);
199
200/* Read in a DER from a file, may be ascii  */
201extern SECStatus 
202SECU_ReadDERFromFile(SECItem *der, PRFileDesc *inFile, PRBool ascii);
203
204/* Indent based on "level" */
205extern void SECU_Indent(FILE *out, int level);
206
207/* Print integer value and hex */
208extern void SECU_PrintInteger(FILE *out, SECItem *i, char *m, int level);
209
210/* Print ObjectIdentifier symbolically */
211extern SECOidTag SECU_PrintObjectID(FILE *out, SECItem *oid, char *m, int level);
212
213/* Print AlgorithmIdentifier symbolically */
214extern void SECU_PrintAlgorithmID(FILE *out, SECAlgorithmID *a, char *m,
215				  int level);
216
217/* Print SECItem as hex */
218extern void SECU_PrintAsHex(FILE *out, SECItem *i, const char *m, int level);
219
220/* dump a buffer in hex and ASCII */
221extern void SECU_PrintBuf(FILE *out, const char *msg, const void *vp, int len);
222
223/*
224 * Format and print the UTC Time "t".  If the tag message "m" is not NULL,
225 * do indent formatting based on "level" and add a newline afterward;
226 * otherwise just print the formatted time string only.
227 */
228extern void SECU_PrintUTCTime(FILE *out, SECItem *t, char *m, int level);
229
230/*
231 * Format and print the Generalized Time "t".  If the tag message "m"
232 * is not NULL, * do indent formatting based on "level" and add a newline
233 * afterward; otherwise just print the formatted time string only.
234 */
235extern void SECU_PrintGeneralizedTime(FILE *out, SECItem *t, char *m,
236				      int level);
237
238/*
239 * Format and print the UTC or Generalized Time "t".  If the tag message
240 * "m" is not NULL, do indent formatting based on "level" and add a newline
241 * afterward; otherwise just print the formatted time string only.
242 */
243extern void SECU_PrintTimeChoice(FILE *out, SECItem *t, char *m, int level);
244
245/* callback for listing certs through pkcs11 */
246extern SECStatus SECU_PrintCertNickname(CERTCertListNode* cert, void *data);
247
248/* Dump all certificate nicknames in a database */
249extern SECStatus
250SECU_PrintCertificateNames(CERTCertDBHandle *handle, PRFileDesc* out, 
251                           PRBool sortByName, PRBool sortByTrust);
252
253/* See if nickname already in database. Return 1 true, 0 false, -1 error */
254int SECU_CheckCertNameExists(CERTCertDBHandle *handle, char *nickname);
255
256/* Dump contents of cert req */
257extern int SECU_PrintCertificateRequest(FILE *out, SECItem *der, char *m,
258	int level);
259
260/* Dump contents of certificate */
261extern int SECU_PrintCertificate(FILE *out, SECItem *der, char *m, int level);
262
263/* Dump contents of a DER certificate name (issuer or subject) */
264extern int SECU_PrintDERName(FILE *out, SECItem *der, const char *m, int level);
265
266/* print trust flags on a cert */
267extern void SECU_PrintTrustFlags(FILE *out, CERTCertTrust *trust, char *m, 
268                                 int level);
269
270/* Dump contents of an RSA public key */
271extern int SECU_PrintRSAPublicKey(FILE *out, SECItem *der, char *m, int level);
272
273extern int SECU_PrintSubjectPublicKeyInfo(FILE *out, SECItem *der, char *m, 
274                                          int level);
275
276#ifdef HAVE_EPV_TEMPLATE
277/* Dump contents of private key */
278extern int SECU_PrintPrivateKey(FILE *out, SECItem *der, char *m, int level);
279#endif
280
281/* Print the MD5 and SHA1 fingerprints of a cert */
282extern int SECU_PrintFingerprints(FILE *out, SECItem *derCert, char *m,
283                                  int level);
284
285/* Pretty-print any PKCS7 thing */
286extern int SECU_PrintPKCS7ContentInfo(FILE *out, SECItem *der, char *m, 
287				      int level);
288
289/* Init PKCS11 stuff */
290extern SECStatus SECU_PKCS11Init(PRBool readOnly);
291
292/* Dump contents of signed data */
293extern int SECU_PrintSignedData(FILE *out, SECItem *der, const char *m, 
294                                int level, SECU_PPFunc inner);
295
296/* Print cert data and its trust flags */
297extern SECStatus SEC_PrintCertificateAndTrust(CERTCertificate *cert,
298                                              const char *label,
299                                              CERTCertTrust *trust);
300
301extern int SECU_PrintCrl(FILE *out, SECItem *der, char *m, int level);
302
303extern void
304SECU_PrintCRLInfo(FILE *out, CERTCrl *crl, char *m, int level);
305
306extern void SECU_PrintString(FILE *out, SECItem *si, char *m, int level);
307extern void SECU_PrintAny(FILE *out, SECItem *i, char *m, int level);
308
309extern void SECU_PrintPolicy(FILE *out, SECItem *value, char *msg, int level);
310extern void SECU_PrintPrivKeyUsagePeriodExtension(FILE *out, SECItem *value,
311                                 char *msg, int level);
312
313extern void SECU_PrintExtensions(FILE *out, CERTCertExtension **extensions,
314				 char *msg, int level);
315
316extern void SECU_PrintName(FILE *out, CERTName *name, const char *msg,
317                           int level);
318extern void SECU_PrintRDN(FILE *out, CERTRDN *rdn, const char *msg, int level);
319
320#ifdef SECU_GetPassword
321/* Convert a High public Key to a Low public Key */
322extern SECKEYLowPublicKey *SECU_ConvHighToLow(SECKEYPublicKey *pubHighKey);
323#endif
324
325extern char *SECU_GetModulePassword(PK11SlotInfo *slot, PRBool retry, void *arg);
326
327extern SECStatus DER_PrettyPrint(FILE *out, SECItem *it, PRBool raw);
328
329extern char *SECU_SECModDBName(void);
330
331extern void SECU_PrintPRandOSError(char *progName);
332
333extern SECStatus SECU_RegisterDynamicOids(void);
334
335/* Identifies hash algorithm tag by its string representation. */
336extern SECOidTag SECU_StringToSignatureAlgTag(const char *alg);
337
338/* Store CRL in output file or pk11 db. Also
339 * encodes with base64 and exports to file if ascii flag is set
340 * and file is not NULL. */
341extern SECStatus SECU_StoreCRL(PK11SlotInfo *slot, SECItem *derCrl,
342                               PRFileDesc *outFile, PRBool ascii, char *url);
343
344
345/*
346** DER sign a single block of data using private key encryption and the
347** MD5 hashing algorithm. This routine first computes a digital signature
348** using SEC_SignData, then wraps it with an CERTSignedData and then der
349** encodes the result.
350**	"arena" is the memory arena to use to allocate data from
351**      "sd" returned CERTSignedData 
352** 	"result" the final der encoded data (memory is allocated)
353** 	"buf" the input data to sign
354** 	"len" the amount of data to sign
355** 	"pk" the private key to encrypt with
356*/
357extern SECStatus SECU_DerSignDataCRL(PRArenaPool *arena, CERTSignedData *sd,
358                                     unsigned char *buf, int len,
359                                     SECKEYPrivateKey *pk, SECOidTag algID);
360
361typedef enum  {
362    noKeyFound = 1,
363    noSignatureMatch = 2,
364    failToEncode = 3,
365    failToSign = 4,
366    noMem = 5
367} SignAndEncodeFuncExitStat;
368
369extern SECStatus
370SECU_SignAndEncodeCRL(CERTCertificate *issuer, CERTSignedCrl *signCrl,
371                      SECOidTag hashAlgTag, SignAndEncodeFuncExitStat *resCode);
372
373extern SECStatus
374SECU_CopyCRL(PRArenaPool *destArena, CERTCrl *destCrl, CERTCrl *srcCrl);
375
376/*
377** Finds the crl Authority Key Id extension. Returns NULL if no such extension
378** was found.
379*/
380CERTAuthKeyID *
381SECU_FindCRLAuthKeyIDExten (PRArenaPool *arena, CERTSignedCrl *crl);
382
383/*
384 * Find the issuer of a crl. Cert usage should be checked before signing a crl.
385 */
386CERTCertificate *
387SECU_FindCrlIssuer(CERTCertDBHandle *dbHandle, SECItem* subject,
388                   CERTAuthKeyID* id, PRTime validTime);
389
390
391/* call back function used in encoding of an extension. Called from
392 * SECU_EncodeAndAddExtensionValue */
393typedef SECStatus (* EXTEN_EXT_VALUE_ENCODER) (PRArenaPool *extHandleArena,
394                                               void *value, SECItem *encodedValue);
395
396/* Encodes and adds extensions to the CRL or CRL entries. */
397SECStatus 
398SECU_EncodeAndAddExtensionValue(PRArenaPool *arena, void *extHandle, 
399                                void *value, PRBool criticality, int extenType, 
400                                EXTEN_EXT_VALUE_ENCODER EncodeValueFn);
401
402/* Caller ensures that dst is at least item->len*2+1 bytes long */
403void
404SECU_SECItemToHex(const SECItem * item, char * dst);
405
406/* Requires 0x prefix. Case-insensitive. Will do in-place replacement if
407 * successful */
408SECStatus
409SECU_SECItemHexStringToBinary(SECItem* srcdest);
410
411/*
412 *
413 *  Utilities for parsing security tools command lines 
414 *
415 */
416
417/*  A single command flag  */
418typedef struct {
419    char flag;
420    PRBool needsArg;
421    char *arg;
422    PRBool activated;
423    char *longform;
424} secuCommandFlag;
425
426/*  A full array of command/option flags  */
427typedef struct
428{
429    int numCommands;
430    int numOptions;
431
432    secuCommandFlag *commands;
433    secuCommandFlag *options;
434} secuCommand;
435
436/*  fill the "arg" and "activated" fields for each flag  */
437SECStatus 
438SECU_ParseCommandLine(int argc, char **argv, char *progName,
439		      const secuCommand *cmd);
440char *
441SECU_GetOptionArg(const secuCommand *cmd, int optionNum);
442
443/*
444 *
445 *  Error messaging
446 *
447 */
448
449void printflags(char *trusts, unsigned int flags);
450
451#if !defined(XP_UNIX) && !defined(XP_OS2)
452extern int ffs(unsigned int i);
453#endif
454
455/* Finds certificate by searching it in the DB or by examinig file
456 * in the local directory. */
457CERTCertificate*
458SECU_FindCertByNicknameOrFilename(CERTCertDBHandle *handle,
459                                  char *name, PRBool ascii,
460                                  void *pwarg);
461#include "secerr.h"
462#include "sslerr.h"
463
464#endif /* _SEC_UTIL_H_ */