verifyDSASignature() buffer & other fixes
[platform/upstream/rpm.git] / lib / signature.c
1 /** \ingroup signature
2  * \file lib/signature.c
3  */
4
5 #include "system.h"
6
7 #include <popt.h>
8
9 #include <rpm/rpmtag.h>
10 #include <rpm/rpmlib.h>         /* XXX RPMSIGTAG* & related */
11 #include <rpm/rpmmacro.h>       /* XXX for rpmGetPath() */
12 #include <rpm/rpmdb.h>
13 #include <rpm/rpmstring.h>
14 #include <rpm/rpmfileutil.h>
15 #include <rpm/rpmlog.h>
16 #include <rpm/rpmts.h>
17
18 #include "rpmio/digest.h"
19 #include "lib/misc.h"   /* XXX for dosetenv() */
20 #include "lib/rpmlead.h"
21 #include "lib/signature.h"
22 #include "rpmdb/header_internal.h"
23
24 #include "debug.h"
25
26 #if !defined(__GLIBC__) && !defined(__APPLE__)
27 char ** environ = NULL;
28 #endif
29
30 int rpmLookupSignatureType(int action)
31 {
32     static int disabled = 0;
33     int rc = 0;
34
35     switch (action) {
36     case RPMLOOKUPSIG_DISABLE:
37         disabled = -2;
38         break;
39     case RPMLOOKUPSIG_ENABLE:
40         disabled = 0;
41     case RPMLOOKUPSIG_QUERY:
42         if (disabled)
43             break;      /* Disabled */
44       { char *name = rpmExpand("%{?_signature}", NULL);
45         if (!(name && *name != '\0'))
46             rc = 0;
47         else if (!rstrcasecmp(name, "none"))
48             rc = 0;
49         else if (!rstrcasecmp(name, "pgp"))
50             rc = RPMSIGTAG_PGP;
51         else if (!rstrcasecmp(name, "pgp5"))    /* XXX legacy */
52             rc = RPMSIGTAG_PGP;
53         else if (!rstrcasecmp(name, "gpg"))
54             rc = RPMSIGTAG_GPG;
55         else
56             rc = -1;    /* Invalid %_signature spec in macro file */
57         name = _free(name);
58       } break;
59     }
60     return rc;
61 }
62
63 /* rpmDetectPGPVersion() returns the absolute path to the "pgp"  */
64 /* executable of the requested version, or NULL when none found. */
65
66 const char * rpmDetectPGPVersion(pgpVersion * pgpVer)
67 {
68     /* Actually this should support having more then one pgp version. */
69     /* At the moment only one version is possible since we only       */
70     /* have one %_pgpbin and one %_pgp_path.                          */
71
72     static pgpVersion saved_pgp_version = PGP_UNKNOWN;
73     char *pgpbin = rpmGetPath("%{?_pgpbin}", NULL);
74
75     if (saved_pgp_version == PGP_UNKNOWN) {
76         char *pgpvbin;
77         struct stat st;
78
79         if (!(pgpbin && pgpbin[0] != '\0')) {
80             pgpbin = _free(pgpbin);
81             saved_pgp_version = -1;
82             return NULL;
83         }
84         pgpvbin = (char *)alloca(strlen(pgpbin) + sizeof("v"));
85         (void)stpcpy(stpcpy(pgpvbin, pgpbin), "v");
86
87         if (stat(pgpvbin, &st) == 0)
88             saved_pgp_version = PGP_5;
89         else if (stat(pgpbin, &st) == 0)
90             saved_pgp_version = PGP_2;
91         else
92             saved_pgp_version = PGP_NOTDETECTED;
93     }
94
95     if (pgpVer && pgpbin)
96         *pgpVer = saved_pgp_version;
97     return pgpbin;
98 }
99
100 /**
101  * Print package size.
102  * @todo rpmio: use fdSize rather than fstat(2) to get file size.
103  * @param fd                    package file handle
104  * @param siglen                signature header size
105  * @param pad                   signature padding
106  * @param datalen               length of header+payload
107  * @return                      rpmRC return code
108  */
109 static inline rpmRC printSize(FD_t fd, size_t siglen, size_t pad, rpm_off_t datalen)
110 {
111     struct stat st;
112     int fdno = Fileno(fd);
113
114     if (fstat(fdno, &st) < 0)
115         return RPMRC_FAIL;
116
117     rpmlog(RPMLOG_DEBUG,
118         "Expected size: %12zd = lead(%d)+sigs(%zd)+pad(%zd)+data(%d)\n",
119                 RPMLEAD_SIZE+siglen+pad+datalen,
120                 RPMLEAD_SIZE, siglen, pad, datalen);
121     rpmlog(RPMLOG_DEBUG,
122         "  Actual size: %12d\n", (int)st.st_size);
123
124     return RPMRC_OK;
125 }
126
127 /* XXX sigh yet another duplicate.. */
128 static unsigned char const header_magic[8] = {
129     0x8e, 0xad, 0xe8, 0x01, 0x00, 0x00, 0x00, 0x00
130 };
131
132 rpmRC rpmReadSignature(FD_t fd, Header * sighp, sigType sig_type, char ** msg)
133 {
134     char *buf = NULL;
135     int32_t block[4];
136     int32_t il;
137     int32_t dl;
138     int32_t * ei = NULL;
139     entryInfo pe;
140     size_t nb;
141     int32_t ril = 0;
142     indexEntry entry = memset(alloca(sizeof(*entry)), 0, sizeof(*entry));
143     entryInfo info = memset(alloca(sizeof(*info)), 0, sizeof(*info));
144     unsigned char * dataStart;
145     unsigned char * dataEnd = NULL;
146     Header sigh = NULL;
147     rpmRC rc = RPMRC_FAIL;              /* assume failure */
148     int xx;
149     int i;
150
151     if (sighp)
152         *sighp = NULL;
153
154     if (sig_type != RPMSIGTYPE_HEADERSIG)
155         goto exit;
156
157     memset(block, 0, sizeof(block));
158     if ((xx = timedRead(fd, (void *)block, sizeof(block))) != sizeof(block)) {
159         rasprintf(&buf, _("sigh size(%d): BAD, read returned %d\n"), 
160                   (int)sizeof(block), xx);
161         goto exit;
162     }
163     if (memcmp(block, header_magic, sizeof(header_magic))) {
164         rasprintf(&buf, _("sigh magic: BAD\n"));
165         goto exit;
166     }
167     il = ntohl(block[2]);
168     if (il < 0 || il > 32) {
169         rasprintf(&buf, 
170                   _("sigh tags: BAD, no. of tags(%d) out of range\n"), il);
171         goto exit;
172     }
173     dl = ntohl(block[3]);
174     if (dl < 0 || dl > 8192) {
175         rasprintf(&buf, 
176                   _("sigh data: BAD, no. of  bytes(%d) out of range\n"), dl);
177         goto exit;
178     }
179
180     nb = (il * sizeof(struct entryInfo_s)) + dl;
181     ei = xmalloc(sizeof(il) + sizeof(dl) + nb);
182     ei[0] = block[2];
183     ei[1] = block[3];
184     pe = (entryInfo) &ei[2];
185     dataStart = (unsigned char *) (pe + il);
186     if ((xx = timedRead(fd, (void *)pe, nb)) != nb) {
187         rasprintf(&buf,
188                   _("sigh blob(%d): BAD, read returned %d\n"), (int)nb, xx);
189         goto exit;
190     }
191     
192     /* Check (and convert) the 1st tag element. */
193     xx = headerVerifyInfo(1, dl, pe, &entry->info, 0);
194     if (xx != -1) {
195         rasprintf(&buf, _("tag[%d]: BAD, tag %d type %d offset %d count %d\n"),
196                   0, entry->info.tag, entry->info.type,
197                   entry->info.offset, entry->info.count);
198         goto exit;
199     }
200
201     /* Is there an immutable header region tag? */
202     if (entry->info.tag == RPMTAG_HEADERSIGNATURES
203        && entry->info.type == RPM_BIN_TYPE
204        && entry->info.count == REGION_TAG_COUNT)
205     {
206
207         if (entry->info.offset >= dl) {
208             rasprintf(&buf, 
209                 _("region offset: BAD, tag %d type %d offset %d count %d\n"),
210                 entry->info.tag, entry->info.type,
211                 entry->info.offset, entry->info.count);
212             goto exit;
213         }
214
215         /* Is there an immutable header region tag trailer? */
216         dataEnd = dataStart + entry->info.offset;
217         (void) memcpy(info, dataEnd, REGION_TAG_COUNT);
218         /* XXX Really old packages have HEADER_IMAGE, not HEADER_SIGNATURES. */
219         if (info->tag == htonl(RPMTAG_HEADERIMAGE)) {
220             rpmSigTag stag = htonl(RPMTAG_HEADERSIGNATURES);
221             info->tag = stag;
222             memcpy(dataEnd, &stag, sizeof(stag));
223         }
224         dataEnd += REGION_TAG_COUNT;
225
226         xx = headerVerifyInfo(1, dl, info, &entry->info, 1);
227         if (xx != -1 ||
228             !((entry->info.tag == RPMTAG_HEADERSIGNATURES || entry->info.tag == RPMTAG_HEADERIMAGE)
229            && entry->info.type == RPM_BIN_TYPE
230            && entry->info.count == REGION_TAG_COUNT))
231         {
232             rasprintf(&buf,
233                 _("region trailer: BAD, tag %d type %d offset %d count %d\n"),
234                 entry->info.tag, entry->info.type,
235                 entry->info.offset, entry->info.count);
236             goto exit;
237         }
238         memset(info, 0, sizeof(*info));
239
240         /* Is the no. of tags in the region less than the total no. of tags? */
241         ril = entry->info.offset/sizeof(*pe);
242         if ((entry->info.offset % sizeof(*pe)) || ril > il) {
243             rasprintf(&buf, _("region size: BAD, ril(%d) > il(%d)\n"), ril, il);
244             goto exit;
245         }
246     }
247
248     /* Sanity check signature tags */
249     memset(info, 0, sizeof(*info));
250     for (i = 1; i < il; i++) {
251         xx = headerVerifyInfo(1, dl, pe+i, &entry->info, 0);
252         if (xx != -1) {
253             rasprintf(&buf, 
254                 _("sigh tag[%d]: BAD, tag %d type %d offset %d count %d\n"),
255                 i, entry->info.tag, entry->info.type,
256                 entry->info.offset, entry->info.count);
257             goto exit;
258         }
259     }
260
261     /* OK, blob looks sane, load the header. */
262     sigh = headerLoad(ei);
263     if (sigh == NULL) {
264         rasprintf(&buf, _("sigh load: BAD\n"));
265         goto exit;
266     }
267     sigh->flags |= HEADERFLAG_ALLOCATED;
268
269     {   size_t sigSize = headerSizeof(sigh, HEADER_MAGIC_YES);
270         size_t pad = (8 - (sigSize % 8)) % 8; /* 8-byte pad */
271         ssize_t trc;
272         rpm_off_t * archSize = NULL;
273
274         /* Position at beginning of header. */
275         if (pad && (trc = timedRead(fd, (void *)block, pad)) != pad) {
276             rasprintf(&buf,
277                       _("sigh pad(%zd): BAD, read %zd bytes\n"), pad, trc);
278             goto exit;
279         }
280
281         /* Print package component sizes. */
282         if (headerGetEntry(sigh, RPMSIGTAG_SIZE, NULL,(rpm_data_t *)&archSize, NULL)) {
283             rc = printSize(fd, sigSize, pad, *archSize);
284             if (rc != RPMRC_OK) {
285                 rasprintf(&buf,
286                        _("sigh sigSize(%zd): BAD, fstat(2) failed\n"), sigSize);
287                 goto exit;
288             }
289         }
290     }
291
292 exit:
293     if (sighp && sigh && rc == RPMRC_OK)
294         *sighp = headerLink(sigh);
295     sigh = headerFree(sigh);
296
297     if (msg != NULL) {
298         *msg = buf;
299     } else {
300         free(buf);
301     }
302
303     return rc;
304 }
305
306 int rpmWriteSignature(FD_t fd, Header sigh)
307 {
308     static uint8_t buf[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
309     int sigSize, pad;
310     int rc;
311
312     rc = headerWrite(fd, sigh, HEADER_MAGIC_YES);
313     if (rc)
314         return rc;
315
316     sigSize = headerSizeof(sigh, HEADER_MAGIC_YES);
317     pad = (8 - (sigSize % 8)) % 8;
318     if (pad) {
319         if (Fwrite(buf, sizeof(buf[0]), pad, fd) != pad)
320             rc = 1;
321     }
322     rpmlog(RPMLOG_DEBUG, "Signature: size(%d)+pad(%d)\n", sigSize, pad);
323     return rc;
324 }
325
326 Header rpmNewSignature(void)
327 {
328     Header sigh = headerNew();
329     return sigh;
330 }
331
332 Header rpmFreeSignature(Header sigh)
333 {
334     return headerFree(sigh);
335 }
336
337 /**
338  * Generate PGP signature(s) for a header+payload file.
339  * @param file          header+payload file name
340  * @retval *sigTagp     signature tag
341  * @retval *pktp        signature packet(s)
342  * @retval *pktlenp     signature packet(s) length
343  * @param passPhrase    private key pass phrase
344  * @return              0 on success, 1 on failure
345  */
346 static int makePGPSignature(const char * file, rpmSigTag * sigTagp,
347                 uint8_t ** pktp, size_t * pktlenp,
348                 const char * passPhrase)
349 {
350     char * sigfile = alloca(1024);
351     int pid, status;
352     int inpipe[2];
353     struct stat st;
354     const char * cmd;
355     char *const *av;
356 #ifdef NOTYET
357     pgpDig dig = NULL;
358     pgpDigParams sigp = NULL;
359 #endif
360     int rc;
361
362     (void) stpcpy( stpcpy(sigfile, file), ".sig");
363
364     addMacro(NULL, "__plaintext_filename", NULL, file, -1);
365     addMacro(NULL, "__signature_filename", NULL, sigfile, -1);
366
367     inpipe[0] = inpipe[1] = 0;
368     (void) pipe(inpipe);
369
370     if (!(pid = fork())) {
371         const char *pgp_path = rpmExpand("%{?_pgp_path}", NULL);
372         const char *path;
373         pgpVersion pgpVer;
374
375         (void) dup2(inpipe[0], 3);
376         (void) close(inpipe[1]);
377
378         (void) dosetenv("PGPPASSFD", "3", 1);
379         if (pgp_path && *pgp_path != '\0')
380             (void) dosetenv("PGPPATH", pgp_path, 1);
381
382         /* dosetenv("PGPPASS", passPhrase, 1); */
383
384         unsetenv("MALLOC_CHECK_");
385         if ((path = rpmDetectPGPVersion(&pgpVer)) != NULL) {
386             switch(pgpVer) {
387             case PGP_2:
388                 cmd = rpmExpand("%{?__pgp_sign_cmd}", NULL);
389                 rc = poptParseArgvString(cmd, NULL, (const char ***)&av);
390                 if (!rc)
391                     rc = execve(av[0], av+1, environ);
392                 break;
393             case PGP_5:
394                 cmd = rpmExpand("%{?__pgp5_sign_cmd}", NULL);
395                 rc = poptParseArgvString(cmd, NULL, (const char ***)&av);
396                 if (!rc)
397                     rc = execve(av[0], av+1, environ);
398                 break;
399             case PGP_UNKNOWN:
400             case PGP_NOTDETECTED:
401                 errno = ENOENT;
402                 break;
403             }
404         }
405         rpmlog(RPMLOG_ERR, _("Could not exec %s: %s\n"), "pgp",
406                         strerror(errno));
407         _exit(EXIT_FAILURE);
408     }
409
410     delMacro(NULL, "__plaintext_filename");
411     delMacro(NULL, "__signature_filename");
412
413     (void) close(inpipe[0]);
414     if (passPhrase)
415         (void) write(inpipe[1], passPhrase, strlen(passPhrase));
416     (void) write(inpipe[1], "\n", 1);
417     (void) close(inpipe[1]);
418
419     (void)waitpid(pid, &status, 0);
420     if (!WIFEXITED(status) || WEXITSTATUS(status)) {
421         rpmlog(RPMLOG_ERR, _("pgp failed\n"));
422         return 1;
423     }
424
425     if (stat(sigfile, &st)) {
426         /* PGP failed to write signature */
427         if (sigfile) (void) unlink(sigfile);  /* Just in case */
428         rpmlog(RPMLOG_ERR, _("pgp failed to write signature\n"));
429         return 1;
430     }
431
432     *pktlenp = st.st_size;
433     rpmlog(RPMLOG_DEBUG, "PGP sig size: %zd\n", *pktlenp);
434     *pktp = xmalloc(*pktlenp);
435
436     {   FD_t fd;
437
438         rc = 0;
439         fd = Fopen(sigfile, "r.fdio");
440         if (fd != NULL && !Ferror(fd)) {
441             rc = timedRead(fd, (void *)*pktp, *pktlenp);
442             if (sigfile) (void) unlink(sigfile);
443             (void) Fclose(fd);
444         }
445         if (rc != *pktlenp) {
446             *pktp = _free(*pktp);
447             rpmlog(RPMLOG_ERR, _("unable to read the signature\n"));
448             return 1;
449         }
450     }
451
452     rpmlog(RPMLOG_DEBUG, "Got %zd bytes of PGP sig\n", *pktlenp);
453
454 #ifdef  NOTYET
455     /* Parse the signature, change signature tag as appropriate. */
456     dig = pgpNewDig();
457
458     (void) pgpPrtPkts(*pktp, *pktlenp, dig, 0);
459     sigp = &dig->signature;
460
461     dig = pgpFreeDig(dig);
462 #endif
463
464     return 0;
465 }
466
467 /**
468  * Generate GPG signature(s) for a header+payload file.
469  * @param file          header+payload file name
470  * @retval *sigTagp     signature tag
471  * @retval *pktp        signature packet(s)
472  * @retval *pktlenp     signature packet(s) length
473  * @param passPhrase    private key pass phrase
474  * @return              0 on success, 1 on failure
475  */
476 static int makeGPGSignature(const char * file, rpmSigTag * sigTagp,
477                 uint8_t ** pktp, size_t * pktlenp,
478                 const char * passPhrase)
479 {
480     char * sigfile = alloca(strlen(file)+sizeof(".sig"));
481     int pid, status;
482     int inpipe[2];
483     FILE * fpipe;
484     struct stat st;
485     const char * cmd;
486     char *const *av;
487     pgpDig dig = NULL;
488     pgpDigParams sigp = NULL;
489     int rc;
490
491     (void) stpcpy( stpcpy(sigfile, file), ".sig");
492
493     addMacro(NULL, "__plaintext_filename", NULL, file, -1);
494     addMacro(NULL, "__signature_filename", NULL, sigfile, -1);
495
496     inpipe[0] = inpipe[1] = 0;
497     (void) pipe(inpipe);
498
499     if (!(pid = fork())) {
500         const char *gpg_path = rpmExpand("%{?_gpg_path}", NULL);
501
502         (void) dup2(inpipe[0], 3);
503         (void) close(inpipe[1]);
504
505         if (gpg_path && *gpg_path != '\0')
506             (void) dosetenv("GNUPGHOME", gpg_path, 1);
507         (void) dosetenv("LC_ALL", "C", 1);
508
509         unsetenv("MALLOC_CHECK_");
510         cmd = rpmExpand("%{?__gpg_sign_cmd}", NULL);
511         rc = poptParseArgvString(cmd, NULL, (const char ***)&av);
512         if (!rc)
513             rc = execve(av[0], av+1, environ);
514
515         rpmlog(RPMLOG_ERR, _("Could not exec %s: %s\n"), "gpg",
516                         strerror(errno));
517         _exit(EXIT_FAILURE);
518     }
519
520     delMacro(NULL, "__plaintext_filename");
521     delMacro(NULL, "__signature_filename");
522
523     fpipe = fdopen(inpipe[1], "w");
524     (void) close(inpipe[0]);
525     if (fpipe) {
526         fprintf(fpipe, "%s\n", (passPhrase ? passPhrase : ""));
527         (void) fclose(fpipe);
528     }
529
530     (void) waitpid(pid, &status, 0);
531     if (!WIFEXITED(status) || WEXITSTATUS(status)) {
532         rpmlog(RPMLOG_ERR, _("gpg exec failed (%d)\n"), WEXITSTATUS(status));
533         return 1;
534     }
535
536     if (stat(sigfile, &st)) {
537         /* GPG failed to write signature */
538         if (sigfile) (void) unlink(sigfile);  /* Just in case */
539         rpmlog(RPMLOG_ERR, _("gpg failed to write signature\n"));
540         return 1;
541     }
542
543     *pktlenp = st.st_size;
544     rpmlog(RPMLOG_DEBUG, "GPG sig size: %zd\n", *pktlenp);
545     *pktp = xmalloc(*pktlenp);
546
547     {   FD_t fd;
548
549         rc = 0;
550         fd = Fopen(sigfile, "r.fdio");
551         if (fd != NULL && !Ferror(fd)) {
552             rc = timedRead(fd, (void *)*pktp, *pktlenp);
553             if (sigfile) (void) unlink(sigfile);
554             (void) Fclose(fd);
555         }
556         if (rc != *pktlenp) {
557             *pktp = _free(*pktp);
558             rpmlog(RPMLOG_ERR, _("unable to read the signature\n"));
559             return 1;
560         }
561     }
562
563     rpmlog(RPMLOG_DEBUG, "Got %zd bytes of GPG sig\n", *pktlenp);
564
565     /* Parse the signature, change signature tag as appropriate. */
566     dig = pgpNewDig();
567
568     (void) pgpPrtPkts(*pktp, *pktlenp, dig, 0);
569     sigp = &dig->signature;
570
571     switch (*sigTagp) {
572     case RPMSIGTAG_SIZE:
573     case RPMSIGTAG_MD5:
574     case RPMSIGTAG_SHA1:
575         break;
576     case RPMSIGTAG_GPG:
577         /* XXX check MD5 hash too? */
578         if (sigp->pubkey_algo == PGPPUBKEYALGO_RSA)
579             *sigTagp = RPMSIGTAG_PGP;
580         break;
581     case RPMSIGTAG_PGP5:        /* XXX legacy */
582     case RPMSIGTAG_PGP:
583         if (sigp->pubkey_algo == PGPPUBKEYALGO_DSA)
584             *sigTagp = RPMSIGTAG_GPG;
585         break;
586     case RPMSIGTAG_DSA:
587         /* XXX check MD5 hash too? */
588         if (sigp->pubkey_algo == PGPPUBKEYALGO_RSA)
589             *sigTagp = RPMSIGTAG_RSA;
590         break;
591     case RPMSIGTAG_RSA:
592         if (sigp->pubkey_algo == PGPPUBKEYALGO_DSA)
593             *sigTagp = RPMSIGTAG_DSA;
594         break;
595     /* shut up gcc */
596     case RPMSIGTAG_LEMD5_1:
597     case RPMSIGTAG_LEMD5_2:
598     case RPMSIGTAG_BADSHA1_1:
599     case RPMSIGTAG_BADSHA1_2:
600     case RPMSIGTAG_PAYLOADSIZE:
601         break;
602     }
603
604     dig = pgpFreeDig(dig);
605
606     return 0;
607 }
608
609 /**
610  * Generate header only signature(s) from a header+payload file.
611  * @param sigh          signature header
612  * @param file          header+payload file name
613  * @param sigTag        type of signature(s) to add
614  * @param passPhrase    private key pass phrase
615  * @return              0 on success, -1 on failure
616  */
617 static int makeHDRSignature(Header sigh, const char * file, rpmSigTag sigTag,
618                 const char * passPhrase)
619 {
620     Header h = NULL;
621     FD_t fd = NULL;
622     uint8_t * pkt;
623     size_t pktlen;
624     char * fn = NULL;
625     char * SHA1 = NULL;
626     int ret = -1;       /* assume failure. */
627
628     switch (sigTag) {
629     case RPMSIGTAG_SIZE:
630     case RPMSIGTAG_MD5:
631     case RPMSIGTAG_PGP5:        /* XXX legacy */
632     case RPMSIGTAG_PGP:
633     case RPMSIGTAG_GPG:
634         goto exit;
635         break;
636     case RPMSIGTAG_SHA1:
637         fd = Fopen(file, "r.fdio");
638         if (fd == NULL || Ferror(fd))
639             goto exit;
640         h = headerRead(fd, HEADER_MAGIC_YES);
641         if (h == NULL)
642             goto exit;
643         (void) Fclose(fd);      fd = NULL;
644
645         if (headerIsEntry(h, RPMTAG_HEADERIMMUTABLE)) {
646             DIGEST_CTX ctx;
647             void * uh;
648             rpmTagType uht;
649             rpm_count_t uhc;
650         
651             if (!headerGetEntry(h, RPMTAG_HEADERIMMUTABLE, &uht, &uh, &uhc)
652              ||  uh == NULL)
653             {
654                 h = headerFree(h);
655                 goto exit;
656             }
657             ctx = rpmDigestInit(PGPHASHALGO_SHA1, RPMDIGEST_NONE);
658             (void) rpmDigestUpdate(ctx, header_magic, sizeof(header_magic));
659             (void) rpmDigestUpdate(ctx, uh, uhc);
660             (void) rpmDigestFinal(ctx, (void **)&SHA1, NULL, 1);
661             uh = headerFreeData(uh, uht);
662         }
663         h = headerFree(h);
664
665         if (SHA1 == NULL)
666             goto exit;
667         if (!headerAddEntry(sigh, RPMSIGTAG_SHA1, RPM_STRING_TYPE, SHA1, 1))
668             goto exit;
669         ret = 0;
670         break;
671     case RPMSIGTAG_DSA:
672         fd = Fopen(file, "r.fdio");
673         if (fd == NULL || Ferror(fd))
674             goto exit;
675         h = headerRead(fd, HEADER_MAGIC_YES);
676         if (h == NULL)
677             goto exit;
678         (void) Fclose(fd);      fd = NULL;
679         if (rpmMkTempFile(NULL, &fn, &fd))
680             goto exit;
681         if (headerWrite(fd, h, HEADER_MAGIC_YES))
682             goto exit;
683         (void) Fclose(fd);      fd = NULL;
684         if (makeGPGSignature(fn, &sigTag, &pkt, &pktlen, passPhrase)
685          || !headerAddEntry(sigh, sigTag, RPM_BIN_TYPE, pkt, pktlen))
686             goto exit;
687         ret = 0;
688         break;
689     case RPMSIGTAG_RSA:
690         fd = Fopen(file, "r.fdio");
691         if (fd == NULL || Ferror(fd))
692             goto exit;
693         h = headerRead(fd, HEADER_MAGIC_YES);
694         if (h == NULL)
695             goto exit;
696         (void) Fclose(fd);      fd = NULL;
697         if (rpmMkTempFile(NULL, &fn, &fd))
698             goto exit;
699         if (headerWrite(fd, h, HEADER_MAGIC_YES))
700             goto exit;
701         (void) Fclose(fd);      fd = NULL;
702         if (makePGPSignature(fn, &sigTag, &pkt, &pktlen, passPhrase)
703          || !headerAddEntry(sigh, sigTag, RPM_BIN_TYPE, pkt, pktlen))
704             goto exit;
705         ret = 0;
706         break;
707     /* shut up gcc */
708     case RPMSIGTAG_LEMD5_1:
709     case RPMSIGTAG_LEMD5_2:
710     case RPMSIGTAG_BADSHA1_1:
711     case RPMSIGTAG_BADSHA1_2:
712     case RPMSIGTAG_PAYLOADSIZE:
713         break;
714     }
715
716 exit:
717     if (fn) {
718         (void) unlink(fn);
719         fn = _free(fn);
720     }
721     SHA1 = _free(SHA1);
722     h = headerFree(h);
723     if (fd != NULL) (void) Fclose(fd);
724     return ret;
725 }
726
727 int rpmAddSignature(Header sigh, const char * file, rpmSigTag sigTag,
728                 const char * passPhrase)
729 {
730     struct stat st;
731     uint8_t * pkt;
732     size_t pktlen;
733     int ret = -1;       /* assume failure. */
734
735     switch (sigTag) {
736     case RPMSIGTAG_SIZE:
737         if (stat(file, &st) != 0)
738             break;
739         pktlen = st.st_size;
740         if (!headerAddEntry(sigh, sigTag, RPM_INT32_TYPE, &pktlen, 1))
741             break;
742         ret = 0;
743         break;
744     case RPMSIGTAG_MD5:
745         pktlen = 16;
746         pkt = memset(alloca(pktlen), 0, pktlen);
747         if (rpmDoDigest(PGPHASHALGO_MD5, file, 0, pkt, NULL)
748          || !headerAddEntry(sigh, sigTag, RPM_BIN_TYPE, pkt, pktlen))
749             break;
750         ret = 0;
751         break;
752     case RPMSIGTAG_PGP5:        /* XXX legacy */
753     case RPMSIGTAG_PGP:
754         if (makePGPSignature(file, &sigTag, &pkt, &pktlen, passPhrase)
755          || !headerAddEntry(sigh, sigTag, RPM_BIN_TYPE, pkt, pktlen))
756             break;
757 #ifdef  NOTYET  /* XXX needs hdrmd5ctx, like hdrsha1ctx. */
758         /* XXX Piggyback a header-only RSA signature as well. */
759         ret = makeHDRSignature(sigh, file, RPMSIGTAG_RSA, passPhrase);
760 #endif
761         ret = 0;
762         break;
763     case RPMSIGTAG_GPG:
764         if (makeGPGSignature(file, &sigTag, &pkt, &pktlen, passPhrase)
765          || !headerAddEntry(sigh, sigTag, RPM_BIN_TYPE, pkt, pktlen))
766             break;
767         /* XXX Piggyback a header-only DSA signature as well. */
768         ret = makeHDRSignature(sigh, file, RPMSIGTAG_DSA, passPhrase);
769         break;
770     case RPMSIGTAG_RSA:
771     case RPMSIGTAG_DSA:
772     case RPMSIGTAG_SHA1:
773         ret = makeHDRSignature(sigh, file, sigTag, passPhrase);
774         break;
775     /* shut up gcc */
776     case RPMSIGTAG_LEMD5_1:
777     case RPMSIGTAG_LEMD5_2:
778     case RPMSIGTAG_BADSHA1_1:
779     case RPMSIGTAG_BADSHA1_2:
780     case RPMSIGTAG_PAYLOADSIZE:
781         break;
782     }
783
784     return ret;
785 }
786
787 static int checkPassPhrase(const char * passPhrase, const rpmSigTag sigTag)
788 {
789     int passPhrasePipe[2];
790     int pid, status;
791     int rc;
792     int xx;
793
794     passPhrasePipe[0] = passPhrasePipe[1] = 0;
795     xx = pipe(passPhrasePipe);
796     if (!(pid = fork())) {
797         const char * cmd;
798         char *const *av;
799         int fdno;
800
801         xx = close(STDIN_FILENO);
802         xx = close(STDOUT_FILENO);
803         xx = close(passPhrasePipe[1]);
804         if (! rpmIsVerbose())
805             xx = close(STDERR_FILENO);
806         if ((fdno = open("/dev/null", O_RDONLY)) != STDIN_FILENO) {
807             xx = dup2(fdno, STDIN_FILENO);
808             xx = close(fdno);
809         }
810         if ((fdno = open("/dev/null", O_WRONLY)) != STDOUT_FILENO) {
811             xx = dup2(fdno, STDOUT_FILENO);
812             xx = close(fdno);
813         }
814         xx = dup2(passPhrasePipe[0], 3);
815
816         unsetenv("MALLOC_CHECK_");
817         switch (sigTag) {
818         case RPMSIGTAG_DSA:
819         case RPMSIGTAG_GPG:
820         {   const char *gpg_path = rpmExpand("%{?_gpg_path}", NULL);
821
822             if (gpg_path && *gpg_path != '\0')
823                 (void) dosetenv("GNUPGHOME", gpg_path, 1);
824
825             cmd = rpmExpand("%{?__gpg_check_password_cmd}", NULL);
826             rc = poptParseArgvString(cmd, NULL, (const char ***)&av);
827             if (!rc)
828                 rc = execve(av[0], av+1, environ);
829
830             rpmlog(RPMLOG_ERR, _("Could not exec %s: %s\n"), "gpg",
831                         strerror(errno));
832         }   break;
833         case RPMSIGTAG_RSA:
834         case RPMSIGTAG_PGP5:    /* XXX legacy */
835         case RPMSIGTAG_PGP:
836         {   const char *pgp_path = rpmExpand("%{?_pgp_path}", NULL);
837             const char *path;
838             pgpVersion pgpVer;
839
840             (void) dosetenv("PGPPASSFD", "3", 1);
841             if (pgp_path && *pgp_path != '\0')
842                 xx = dosetenv("PGPPATH", pgp_path, 1);
843
844             if ((path = rpmDetectPGPVersion(&pgpVer)) != NULL) {
845                 switch(pgpVer) {
846                 case PGP_2:
847                     cmd = rpmExpand("%{?__pgp_check_password_cmd}", NULL);
848                     rc = poptParseArgvString(cmd, NULL, (const char ***)&av);
849                     if (!rc)
850                         rc = execve(av[0], av+1, environ);
851                     break;
852                 case PGP_5:     /* XXX legacy */
853                     cmd = rpmExpand("%{?__pgp5_check_password_cmd}", NULL);
854                     rc = poptParseArgvString(cmd, NULL, (const char ***)&av);
855                     if (!rc)
856                         rc = execve(av[0], av+1, environ);
857                     break;
858                 case PGP_UNKNOWN:
859                 case PGP_NOTDETECTED:
860                     break;
861                 }
862             }
863             rpmlog(RPMLOG_ERR, _("Could not exec %s: %s\n"), "pgp",
864                         strerror(errno));
865             _exit(EXIT_FAILURE);
866         }   break;
867         default: /* This case should have been screened out long ago. */
868             rpmlog(RPMLOG_ERR, _("Invalid %%_signature spec in macro file\n"));
869             _exit(EXIT_FAILURE);
870             break;
871         }
872     }
873
874     xx = close(passPhrasePipe[0]);
875     xx = write(passPhrasePipe[1], passPhrase, strlen(passPhrase));
876     xx = write(passPhrasePipe[1], "\n", 1);
877     xx = close(passPhrasePipe[1]);
878
879     (void) waitpid(pid, &status, 0);
880
881     return ((!WIFEXITED(status) || WEXITSTATUS(status)) ? 1 : 0);
882 }
883
884 char * rpmGetPassPhrase(const char * prompt, const rpmSigTag sigTag)
885 {
886     char *pass = NULL;
887     int aok = 0;
888
889     switch (sigTag) {
890     case RPMSIGTAG_DSA:
891     case RPMSIGTAG_GPG:
892       { char *name = rpmExpand("%{?_gpg_name}", NULL);
893         aok = (name && *name != '\0');
894         name = _free(name);
895       }
896         if (aok)
897             break;
898         rpmlog(RPMLOG_ERR,
899                 _("You must set \"%%_gpg_name\" in your macro file\n"));
900         break;
901     case RPMSIGTAG_RSA:
902     case RPMSIGTAG_PGP5:        /* XXX legacy */
903     case RPMSIGTAG_PGP:
904       { char *name = rpmExpand("%{?_pgp_name}", NULL);
905         aok = (name && *name != '\0');
906         name = _free(name);
907       }
908         if (aok)
909             break;
910         rpmlog(RPMLOG_ERR,
911                 _("You must set \"%%_pgp_name\" in your macro file\n"));
912         break;
913     default:
914         /* Currently the calling function (rpm.c:main) is checking this and
915          * doing a better job.  This section should never be accessed.
916          */
917         rpmlog(RPMLOG_ERR, _("Invalid %%_signature spec in macro file\n"));
918         break;
919     }
920
921     if (aok) {
922         pass = getpass( (prompt ? prompt : "") );
923
924         if (checkPassPhrase(pass, sigTag))
925             pass = NULL;
926     }
927
928     return pass;
929 }
930
931 static const char * rpmSigString(rpmRC res)
932 {
933     const char * str;
934     switch (res) {
935     case RPMRC_OK:              str = "OK";             break;
936     case RPMRC_FAIL:            str = "BAD";            break;
937     case RPMRC_NOKEY:           str = "NOKEY";          break;
938     case RPMRC_NOTTRUSTED:      str = "NOTRUSTED";      break;
939     default:
940     case RPMRC_NOTFOUND:        str = "UNKNOWN";        break;
941     }
942     return str;
943 }
944
945 static rpmRC
946 verifySizeSignature(const rpmts ts, char ** msg)
947 {
948     rpm_constdata_t sig = rpmtsSig(ts);
949     pgpDig dig = rpmtsDig(ts);
950     rpmRC res;
951     size_t size = 0x7fffffff;
952     const char * title = _("Header+Payload size:");
953
954     assert(msg != NULL);
955     *msg = NULL;
956
957     if (sig == NULL || dig == NULL || dig->nbytes == 0) {
958         res = RPMRC_NOKEY;
959         rasprintf(msg, "%s %s\n", title, rpmSigString(res));
960         goto exit;
961     }
962
963     memcpy(&size, sig, sizeof(size));
964
965     if (size != dig->nbytes) {
966         res = RPMRC_FAIL;
967         rasprintf(msg, "%s %s Expected(%zd) != (%zd)\n", title,
968                   rpmSigString(res), size, dig->nbytes);
969     } else {
970         res = RPMRC_OK;
971         rasprintf(msg, "%s %s (%zd)\n", title, rpmSigString(res), dig->nbytes);
972     }
973
974 exit:
975     return res;
976 }
977
978 static rpmRC
979 verifyMD5Signature(const rpmts ts, char ** msg,
980                 DIGEST_CTX md5ctx)
981 {
982     rpm_constdata_t sig = rpmtsSig(ts);
983     size_t siglen = rpmtsSiglen(ts);
984     pgpDig dig = rpmtsDig(ts);
985     rpmRC res;
986     uint8_t * md5sum = NULL;
987     size_t md5len = 0;
988     char *md5;
989     const char *title = _("MD5 digest:");
990
991     assert(msg != NULL);
992     *msg = NULL;
993
994     if (md5ctx == NULL || sig == NULL || dig == NULL) {
995         res = RPMRC_NOKEY;
996         rasprintf(msg, "%s %s\n", title, rpmSigString(res));
997         goto exit;
998     }
999
1000     (void) rpmswEnter(rpmtsOp(ts, RPMTS_OP_DIGEST), 0);
1001     (void) rpmDigestFinal(rpmDigestDup(md5ctx),
1002                 (void **)&md5sum, &md5len, 0);
1003     (void) rpmswExit(rpmtsOp(ts, RPMTS_OP_DIGEST), 0);
1004     rpmtsOp(ts, RPMTS_OP_DIGEST)->count--;      /* XXX one too many */
1005
1006     md5 = pgpHexStr(md5sum, md5len);
1007     if (md5len != siglen || memcmp(md5sum, sig, md5len)) {
1008         res = RPMRC_FAIL;
1009         char *hex = pgpHexStr(sig, siglen);
1010         rasprintf(msg, "%s %s Expected(%s) != (%s)\n", title,
1011                   rpmSigString(res), hex, md5);
1012         free(hex);
1013     } else {
1014         res = RPMRC_OK;
1015         rasprintf(msg, "%s %s (%s)\n", title, rpmSigString(res), md5);
1016     }
1017     free(md5);
1018
1019 exit:
1020     md5sum = _free(md5sum);
1021     return res;
1022 }
1023
1024 /**
1025  * Verify header immutable region SHA1 digest.
1026  * @param ts            transaction set
1027  * @retval msg          verbose success/failure text
1028  * @param sha1ctx
1029  * @return              RPMRC_OK on success
1030  */
1031 static rpmRC
1032 verifySHA1Signature(const rpmts ts, char ** msg,
1033                 DIGEST_CTX sha1ctx)
1034 {
1035     const char *sig = rpmtsSig(ts);
1036 #ifdef  NOTYET
1037     size_t siglen = rpmtsSiglen(ts);
1038 #endif
1039     pgpDig dig = rpmtsDig(ts);
1040     rpmRC res;
1041     char * SHA1 = NULL;
1042     const char *title = _("Header SHA1 digest:");
1043
1044     assert(msg != NULL);
1045     *msg = NULL;
1046
1047     if (sha1ctx == NULL || sig == NULL || dig == NULL) {
1048         res = RPMRC_NOKEY;
1049         rasprintf(msg, "%s %s\n", title, rpmSigString(res));
1050         goto exit;
1051     }
1052
1053     (void) rpmswEnter(rpmtsOp(ts, RPMTS_OP_DIGEST), 0);
1054     (void) rpmDigestFinal(rpmDigestDup(sha1ctx),
1055                 (void **)&SHA1, NULL, 1);
1056     (void) rpmswExit(rpmtsOp(ts, RPMTS_OP_DIGEST), 0);
1057
1058     if (SHA1 == NULL || strlen(SHA1) != strlen(sig) || strcmp(SHA1, sig)) {
1059         res = RPMRC_FAIL;
1060         rasprintf(msg, "%s %s Expected(%s) != (%s)\n", title,
1061                   rpmSigString(res), sig, SHA1 ? SHA1 : "(nil)");
1062     } else {
1063         res = RPMRC_OK;
1064         rasprintf(msg, "%s %s (%s)\n", title, rpmSigString(res), SHA1);
1065     }
1066
1067 exit:
1068     SHA1 = _free(SHA1);
1069     return res;
1070 }
1071
1072 /**
1073  * Verify RSA signature.
1074  * @param ts            transaction set
1075  * @retval msg          rbose success/failure text
1076  * @param md5ctx
1077  * @return              RPMRC_OK on success
1078  */
1079 static rpmRC
1080 verifyRSASignature(rpmts ts, char ** msg,
1081                 DIGEST_CTX md5ctx)
1082 {
1083     rpm_constdata_t sig = rpmtsSig(ts);
1084 #ifdef  NOTYET
1085     size_t siglen = rpmtsSiglen(ts);
1086 #endif
1087     rpmSigTag sigtag = rpmtsSigtag(ts);
1088     pgpDig dig = rpmtsDig(ts);
1089     pgpDigParams sigp = rpmtsSignature(ts);
1090     SECOidTag sigalg;
1091     rpmRC res = RPMRC_OK;
1092     int xx;
1093     SECItem digest;
1094     char *t;
1095
1096     *msg = xmalloc(BUFSIZ); /* XXX FIXME, calculate string size instead */
1097     t = *msg;
1098
1099     if (dig != NULL && dig->hdrmd5ctx == md5ctx)
1100         t = stpcpy(t, _("Header "));
1101     *t++ = 'V';
1102     switch (sigp->version) {
1103     case 3:     *t++ = '3';     break;
1104     case 4:     *t++ = '4';     break;
1105     }
1106
1107     if (md5ctx == NULL || sig == NULL || dig == NULL || sigp == NULL) {
1108         res = RPMRC_NOKEY;
1109     }
1110
1111     /* Verify the desired signature match. */
1112     switch (sigp->pubkey_algo) {
1113     case PGPPUBKEYALGO_RSA:
1114         if (sigtag == RPMSIGTAG_PGP || sigtag == RPMSIGTAG_PGP5 || sigtag == RPMSIGTAG_RSA)
1115             break;
1116     default:
1117         res = RPMRC_NOKEY;
1118         break;
1119     }
1120
1121     /* Verify the desired hash match. */
1122     /* XXX Values from PKCS#1 v2.1 (aka RFC-3447) */
1123     switch (sigp->hash_algo) {
1124     case PGPHASHALGO_MD5:
1125         t = stpcpy(t, " RSA/MD5");
1126         sigalg = SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION;
1127         break;
1128     case PGPHASHALGO_SHA1:
1129         t = stpcpy(t, " RSA/SHA1");
1130         sigalg = SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION;
1131         break;
1132     case PGPHASHALGO_RIPEMD160:
1133         res = RPMRC_NOKEY;
1134         break;
1135     case PGPHASHALGO_MD2:
1136         t = stpcpy(t, " RSA/MD2");
1137         sigalg = SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION;
1138         break;
1139     case PGPHASHALGO_TIGER192:
1140         res = RPMRC_NOKEY;
1141         break;
1142     case PGPHASHALGO_HAVAL_5_160:
1143         res = RPMRC_NOKEY;
1144         break;
1145     case PGPHASHALGO_SHA256:
1146         t = stpcpy(t, " RSA/SHA256");
1147         sigalg = SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION;
1148         break;
1149     case PGPHASHALGO_SHA384:
1150         t = stpcpy(t, " RSA/SHA384");
1151         sigalg = SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION;
1152         break;
1153     case PGPHASHALGO_SHA512:
1154         t = stpcpy(t, " RSA/SHA512");
1155         sigalg = SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION;
1156         break;
1157     default:
1158         res = RPMRC_NOKEY;
1159         sigalg = SEC_OID_UNKNOWN;
1160         break;
1161     }
1162
1163     t = stpcpy(t, _(" signature: "));
1164     if (res != RPMRC_OK) {
1165         goto exit;
1166     }
1167
1168     (void) rpmswEnter(rpmtsOp(ts, RPMTS_OP_DIGEST), 0);
1169     {   DIGEST_CTX ctx = rpmDigestDup(md5ctx);
1170
1171         if (sigp->hash != NULL)
1172             xx = rpmDigestUpdate(ctx, sigp->hash, sigp->hashlen);
1173
1174 #ifdef  NOTYET  /* XXX not for binary/text signatures as in packages. */
1175         if (!(sigp->sigtype == PGPSIGTYPE_BINARY || sigp->sigtype == PGP_SIGTYPE_TEXT)) {
1176             size_t nb = dig->nbytes + sigp->hashlen;
1177             uint8_t trailer[6];
1178             nb = htonl(nb);
1179             trailer[0] = 0x4;
1180             trailer[1] = 0xff;
1181             memcpy(trailer+2, &nb, sizeof(nb));
1182             xx = rpmDigestUpdate(ctx, trailer, sizeof(trailer));
1183         }
1184 #endif
1185
1186         xx = rpmDigestFinal(ctx, (void **)&dig->md5, &dig->md5len, 0);
1187         (void) rpmswExit(rpmtsOp(ts, RPMTS_OP_DIGEST), sigp->hashlen);
1188         rpmtsOp(ts, RPMTS_OP_DIGEST)->count--;  /* XXX one too many */
1189
1190         /* Compare leading 16 bits of digest for quick check. */
1191         if (memcmp(dig->md5, sigp->signhash16, 2)) {
1192             res = RPMRC_FAIL;
1193             goto exit;
1194         }
1195         digest.type = siBuffer;
1196         digest.data = dig->md5;
1197         digest.len = dig->md5len;
1198     }
1199
1200     /* Retrieve the matching public key. */
1201     res = rpmtsFindPubkey(ts);
1202     if (res != RPMRC_OK)
1203         goto exit;
1204
1205     (void) rpmswEnter(rpmtsOp(ts, RPMTS_OP_SIGNATURE), 0);
1206     if (VFY_VerifyDigest(&digest, dig->rsa, dig->rsasig, sigalg, NULL) == SECSuccess)
1207         res = RPMRC_OK;
1208     else
1209         res = RPMRC_FAIL;
1210     (void) rpmswExit(rpmtsOp(ts, RPMTS_OP_SIGNATURE), 0);
1211
1212 exit:
1213     t = stpcpy(t, rpmSigString(res));
1214     if (sigp != NULL) {
1215         char * signid = pgpHexStr(sigp->signid+4, sizeof(sigp->signid)-4);
1216         t = stpcpy(t, ", key ID ");
1217         t = stpcpy(t, signid);
1218         free(signid);
1219     }
1220     t = stpcpy(t, "\n");
1221     return res;
1222 }
1223
1224 /**
1225  * Verify DSA signature.
1226  * @param ts            transaction set
1227  * @retval t            verbose success/failure text
1228  * @param sha1ctx
1229  * @return              RPMRC_OK on success
1230  */
1231 static rpmRC
1232 verifyDSASignature(rpmts ts, char ** msg,
1233                 DIGEST_CTX sha1ctx)
1234 {
1235     rpm_constdata_t sig = rpmtsSig(ts);
1236 #ifdef  NOTYET
1237     size_t siglen = rpmtsSiglen(ts);
1238 #endif
1239     rpmSigTag sigtag = rpmtsSigtag(ts);
1240     pgpDig dig = rpmtsDig(ts);
1241     pgpDigParams sigp = rpmtsSignature(ts);
1242     rpmRC res;
1243     int xx;
1244     SECItem digest;
1245     const char *hdr;
1246     int sigver;
1247
1248     hdr = (dig != NULL && dig->hdrsha1ctx == sha1ctx) ? _("Header ") : "";
1249     sigver = sigp !=NULL ? sigp->version : 0;
1250
1251     if (sha1ctx == NULL || sig == NULL || dig == NULL || sigp == NULL) {
1252         res = RPMRC_NOKEY;
1253         goto exit;
1254     }
1255
1256     /* XXX sanity check on sigtag and signature agreement. */
1257     if (!((sigtag == RPMSIGTAG_GPG || sigtag == RPMSIGTAG_DSA)
1258         && sigp->pubkey_algo == PGPPUBKEYALGO_DSA
1259         && sigp->hash_algo == PGPHASHALGO_SHA1))
1260     {
1261         res = RPMRC_NOKEY;
1262         goto exit;
1263     }
1264
1265     (void) rpmswEnter(rpmtsOp(ts, RPMTS_OP_DIGEST), 0);
1266     {   DIGEST_CTX ctx = rpmDigestDup(sha1ctx);
1267
1268         if (sigp->hash != NULL)
1269             xx = rpmDigestUpdate(ctx, sigp->hash, sigp->hashlen);
1270
1271         if (sigp->version == 4) {
1272             size_t nb = sigp->hashlen;
1273             uint8_t trailer[6];
1274             nb = htonl(nb);
1275             trailer[0] = sigp->version;
1276             trailer[1] = 0xff;
1277             memcpy(trailer+2, &nb, sizeof(nb));
1278             xx = rpmDigestUpdate(ctx, trailer, sizeof(trailer));
1279         }
1280         xx = rpmDigestFinal(ctx, (void **)&dig->sha1, &dig->sha1len, 0);
1281         (void) rpmswExit(rpmtsOp(ts, RPMTS_OP_DIGEST), sigp->hashlen);
1282         rpmtsOp(ts, RPMTS_OP_DIGEST)->count--;  /* XXX one too many */
1283
1284         /* Compare leading 16 bits of digest for quick check. */
1285         if (memcmp(dig->sha1, sigp->signhash16, 2)) {
1286             res = RPMRC_FAIL;
1287             goto exit;
1288         }
1289         digest.type = siBuffer;
1290         digest.data = dig->sha1;
1291         digest.len = dig->sha1len;
1292     }
1293
1294     /* Retrieve the matching public key. */
1295     res = rpmtsFindPubkey(ts);
1296     if (res != RPMRC_OK)
1297         goto exit;
1298
1299     (void) rpmswEnter(rpmtsOp(ts, RPMTS_OP_SIGNATURE), 0);
1300     if (VFY_VerifyDigest(&digest, dig->dsa, dig->dsasig,
1301                 SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST, NULL) == SECSuccess)
1302         res = RPMRC_OK;
1303     else
1304         res = RPMRC_FAIL;
1305     (void) rpmswExit(rpmtsOp(ts, RPMTS_OP_SIGNATURE), 0);
1306
1307 exit:
1308     if (sigp != NULL) {
1309         char *signid = pgpHexStr(sigp->signid+4, sizeof(sigp->signid)-4);
1310         rasprintf(msg, _("%sV%d DSA signature: %s, key ID %s\n"),
1311                   hdr, sigver, rpmSigString(res), signid);
1312         free(signid);
1313     } else {
1314         rasprintf(msg, _("%sV%d DSA signature: %s\n"),
1315                   hdr, sigver, rpmSigString(res));
1316     }
1317
1318     return res;
1319 }
1320
1321 rpmRC
1322 rpmVerifySignature(const rpmts ts, char ** result)
1323 {
1324     rpm_constdata_t sig = rpmtsSig(ts);
1325     size_t siglen = rpmtsSiglen(ts);
1326     rpmSigTag sigtag = rpmtsSigtag(ts);
1327     pgpDig dig = rpmtsDig(ts);
1328     rpmRC res;
1329
1330     assert(result != NULL);
1331
1332     if (sig == NULL || siglen <= 0 || dig == NULL) {
1333         rasprintf(result, _("Verify signature: BAD PARAMETERS\n"));
1334         return RPMRC_NOTFOUND;
1335     }
1336
1337     switch (sigtag) {
1338     case RPMSIGTAG_SIZE:
1339         res = verifySizeSignature(ts, result);
1340         break;
1341     case RPMSIGTAG_MD5:
1342         res = verifyMD5Signature(ts, result, dig->md5ctx);
1343         break;
1344     case RPMSIGTAG_SHA1:
1345         res = verifySHA1Signature(ts, result, dig->hdrsha1ctx);
1346         break;
1347     case RPMSIGTAG_RSA:
1348         res = verifyRSASignature(ts, result, dig->hdrmd5ctx);
1349         break;
1350     case RPMSIGTAG_PGP5:        /* XXX legacy */
1351     case RPMSIGTAG_PGP:
1352         res = verifyRSASignature(ts, result,
1353                 ((dig->signature.hash_algo == PGPHASHALGO_MD5)
1354                         ? dig->md5ctx : dig->sha1ctx));
1355         break;
1356     case RPMSIGTAG_DSA:
1357         res = verifyDSASignature(ts, result, dig->hdrsha1ctx);
1358         break;
1359     case RPMSIGTAG_GPG:
1360         res = verifyDSASignature(ts, result, dig->sha1ctx);
1361         break;
1362     case RPMSIGTAG_LEMD5_1:
1363     case RPMSIGTAG_LEMD5_2:
1364         rasprintf(result, _("Broken MD5 digest: UNSUPPORTED\n"));
1365         res = RPMRC_NOTFOUND;
1366         break;
1367     default:
1368         rasprintf(result, _("Signature: UNKNOWN (%d)\n"), sigtag);
1369         res = RPMRC_NOTFOUND;
1370         break;
1371     }
1372     return res;
1373 }